@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.
- package/README.md +18 -8
- package/dist/client/.vite/manifest.json +214 -182
- package/dist/client/assets/{ActiveWorkPage-Dd1mxPrq.js → ActiveWorkPage-g2-Jyavo.js} +2 -2
- package/dist/client/assets/{ActiveWorkPage-Dd1mxPrq.js.map → ActiveWorkPage-g2-Jyavo.js.map} +1 -1
- package/dist/client/assets/AgentPage-B6GQdZAs.css +1 -0
- package/dist/client/assets/AgentPage-DmVsEe13.js +6 -0
- package/dist/client/assets/AgentPage-DmVsEe13.js.map +1 -0
- package/dist/client/assets/AtlassianOAuthCallbackPage-C8u9ItMj.js +2 -0
- package/dist/client/assets/{AtlassianOAuthCallbackPage-BPoF6oKf.js.map → AtlassianOAuthCallbackPage-C8u9ItMj.js.map} +1 -1
- package/dist/client/assets/{AuthorizedSharePage-jjqu6W_f.js → AuthorizedSharePage-CVBJ1NTm.js} +2 -2
- package/dist/client/assets/{AuthorizedSharePage-jjqu6W_f.js.map → AuthorizedSharePage-CVBJ1NTm.js.map} +1 -1
- package/dist/client/assets/BrowserCrypto-3BoTVFdl.js +2 -0
- package/dist/client/assets/{BrowserCrypto-BMbjhcvP.js.map → BrowserCrypto-3BoTVFdl.js.map} +1 -1
- package/dist/client/assets/BrowserSessionHydrator-CpZnNm4X.js +2 -0
- package/dist/client/assets/{BrowserSessionHydrator-BC1ymLkL.js.map → BrowserSessionHydrator-CpZnNm4X.js.map} +1 -1
- package/dist/client/assets/{CommandSearch-WwAVDrD9.js → CommandSearch-DUeRRbV2.js} +2 -2
- package/dist/client/assets/{CommandSearch-WwAVDrD9.js.map → CommandSearch-DUeRRbV2.js.map} +1 -1
- package/dist/client/assets/{ItemsPage-CKK_KkJ2.js → ItemsPage-BF2ZkSzh.js} +2 -2
- package/dist/client/assets/{ItemsPage-CKK_KkJ2.js.map → ItemsPage-BF2ZkSzh.js.map} +1 -1
- package/dist/client/assets/{PairPage-DA6cmyqF.js → PairPage-CkaZltHd.js} +2 -2
- package/dist/client/assets/{PairPage-DA6cmyqF.js.map → PairPage-CkaZltHd.js.map} +1 -1
- package/dist/client/assets/PortfolioOverview-CEUHJmGC.js +2 -0
- package/dist/client/assets/{PortfolioOverview-CEI4gpXi.js.map → PortfolioOverview-CEUHJmGC.js.map} +1 -1
- package/dist/client/assets/{PullRequestReviewPanel-D7AKnwL-.js → PullRequestReviewPanel-D1IpvHe2.js} +3 -3
- package/dist/client/assets/{PullRequestReviewPanel-D7AKnwL-.js.map → PullRequestReviewPanel-D1IpvHe2.js.map} +1 -1
- package/dist/client/assets/{ReleaseRoute-CbPW3qUT.js → ReleaseRoute-BuQybrsg.js} +2 -2
- package/dist/client/assets/{ReleaseRoute-CbPW3qUT.js.map → ReleaseRoute-BuQybrsg.js.map} +1 -1
- package/dist/client/assets/ReleaseWorkset-BclY0Nvj.js +2 -0
- package/dist/client/assets/ReleaseWorkset-BclY0Nvj.js.map +1 -0
- package/dist/client/assets/ServicesPage-hw5Ee69-.js +2 -0
- package/dist/client/assets/{ServicesPage-_B89DAvG.js.map → ServicesPage-hw5Ee69-.js.map} +1 -1
- package/dist/client/assets/{TimelinePage-DvpgD8AY.js → TimelinePage-Cj3V98uI.js} +2 -2
- package/dist/client/assets/{TimelinePage-DvpgD8AY.js.map → TimelinePage-Cj3V98uI.js.map} +1 -1
- package/dist/client/assets/{WorkspaceEntityLink-DPj6MKI2.js → WorkspaceEntityLink-C_rc8lxi.js} +2 -2
- package/dist/client/assets/{WorkspaceEntityLink-DPj6MKI2.js.map → WorkspaceEntityLink-C_rc8lxi.js.map} +1 -1
- package/dist/client/assets/WorkspaceEntityRoute-DLLT6fY0.css +1 -0
- package/dist/client/assets/WorkspaceEntityRoute-kbnrQ_lY.js +14 -0
- package/dist/client/assets/WorkspaceEntityRoute-kbnrQ_lY.js.map +1 -0
- package/dist/client/assets/WorkspaceHomeLink-DeYYLEsH.js +2 -0
- package/dist/client/assets/{WorkspaceHomeLink-CkJfzO25.js.map → WorkspaceHomeLink-DeYYLEsH.js.map} +1 -1
- package/dist/client/assets/WorkspacePullRequestDetails-CizqydjN.js +3 -0
- package/dist/client/assets/{WorkspacePullRequestDetails-HwDgp12e.js.map → WorkspacePullRequestDetails-CizqydjN.js.map} +1 -1
- package/dist/client/assets/{WorkspaceReleaseLayout-CGHi8eoo.js → WorkspaceReleaseLayout-CXAQUhkh.js} +2 -2
- package/dist/client/assets/{WorkspaceReleaseLayout-CGHi8eoo.js.map → WorkspaceReleaseLayout-CXAQUhkh.js.map} +1 -1
- package/dist/client/assets/{WorkspaceRichText-D1M637Ff.js → WorkspaceRichText-CCOciILO.js} +2 -2
- package/dist/client/assets/WorkspaceRichText-CCOciILO.js.map +1 -0
- package/dist/client/assets/WorkspaceSettingsPage-GoBfQzBx.css +1 -0
- package/dist/client/assets/WorkspaceSettingsPage-JG-pN_CA.js +2 -0
- package/dist/client/assets/WorkspaceSettingsPage-JG-pN_CA.js.map +1 -0
- package/dist/client/assets/agent-api-Dl9TuGOJ.js +19 -0
- package/dist/client/assets/agent-api-Dl9TuGOJ.js.map +1 -0
- package/dist/client/assets/atlassianOAuthSetupIntentStorage-DE4ySCTb.js +2 -0
- package/dist/client/assets/atlassianOAuthSetupIntentStorage-DE4ySCTb.js.map +1 -0
- package/dist/client/assets/authenticatedMutationClient-DdowMjyo.js +2 -0
- package/dist/client/assets/{authenticatedMutationClient-DYaieXUe.js.map → authenticatedMutationClient-DdowMjyo.js.map} +1 -1
- package/dist/client/assets/{authorizedShareTransport-cxBoQzQ2.js → authorizedShareTransport-CnclcYai.js} +2 -2
- package/dist/client/assets/{authorizedShareTransport-cxBoQzQ2.js.map → authorizedShareTransport-CnclcYai.js.map} +1 -1
- package/dist/client/assets/client-Dq_XQE_l.js +5 -0
- package/dist/client/assets/client-Dq_XQE_l.js.map +1 -0
- package/dist/client/assets/confluenceTasks-DtKq8_eU.js +5 -0
- package/dist/client/assets/confluenceTasks-DtKq8_eU.js.map +1 -0
- package/dist/client/assets/connectionTestTransport-CPK98z7H.js +2 -0
- package/dist/client/assets/connectionTestTransport-CPK98z7H.js.map +1 -0
- package/dist/client/assets/{index-C7_FDTU7.js → index-zVjlBm9l.js} +3 -3
- package/dist/client/assets/{index-C7_FDTU7.js.map → index-zVjlBm9l.js.map} +1 -1
- package/dist/client/assets/{patterns-5N-j-AD2-B9qgekXA.js → patterns-5N-j-AD2-DLfaGePK.js} +2 -2
- package/dist/client/assets/{patterns-5N-j-AD2-B9qgekXA.js.map → patterns-5N-j-AD2-DLfaGePK.js.map} +1 -1
- package/dist/client/assets/{presentPortfolio-C_JsoSWg.js → presentPortfolio-DLEq-vEz.js} +2 -2
- package/dist/client/assets/{presentPortfolio-C_JsoSWg.js.map → presentPortfolio-DLEq-vEz.js.map} +1 -1
- package/dist/client/assets/{presentWorkspaceItems-DboAfwGc.js → presentWorkspaceItems-BOY3FbhO.js} +2 -2
- package/dist/client/assets/{presentWorkspaceItems-DboAfwGc.js.map → presentWorkspaceItems-BOY3FbhO.js.map} +1 -1
- package/dist/client/assets/{pullRequestReviewFailures-DHmYwffV.js → pullRequestReviewFailures-CyjTVnSX.js} +2 -2
- package/dist/client/assets/{pullRequestReviewFailures-DHmYwffV.js.map → pullRequestReviewFailures-CyjTVnSX.js.map} +1 -1
- package/dist/client/assets/{pullRequestReviewThreadReplay-Vy1k53qE.js → pullRequestReviewThreadReplay-CXHspFTr.js} +2 -2
- package/dist/client/assets/{pullRequestReviewThreadReplay-Vy1k53qE.js.map → pullRequestReviewThreadReplay-CXHspFTr.js.map} +1 -1
- package/dist/client/assets/releaseAgentTransport-DaO4svPu.js +2 -0
- package/dist/client/assets/releaseAgentTransport-DaO4svPu.js.map +1 -0
- package/dist/client/assets/releaseRoutes-B4ciNOJj.js +2 -0
- package/dist/client/assets/{releaseRoutes-t9uCfs5T.js.map → releaseRoutes-B4ciNOJj.js.map} +1 -1
- package/dist/client/assets/{serviceOnboarding-DLINCon7.js → serviceOnboarding-D0FmodRi.js} +2 -2
- package/dist/client/assets/{serviceOnboarding-DLINCon7.js.map → serviceOnboarding-D0FmodRi.js.map} +1 -1
- package/dist/client/assets/{useWorkspaceDefaultLanding-CC5ImHkL.js → useWorkspaceDefaultLanding-BaQdg0sY.js} +3 -3
- package/dist/client/assets/{useWorkspaceDefaultLanding-CC5ImHkL.js.map → useWorkspaceDefaultLanding-BaQdg0sY.js.map} +1 -1
- package/dist/client/assets/{useWorkspaceItems-B1X-JNwq.js → useWorkspaceItems-B-7JHtm0.js} +2 -2
- package/dist/client/assets/{useWorkspaceItems-B1X-JNwq.js.map → useWorkspaceItems-B-7JHtm0.js.map} +1 -1
- package/dist/client/assets/workspaceEntityRoutes-DqqDa0AB.js +2 -0
- package/dist/client/assets/workspaceEntityRoutes-DqqDa0AB.js.map +1 -0
- package/dist/client/assets/{workspaceScrollCapture-BsjcWVsk.js → workspaceScrollCapture-BYNfR2wo.js} +2 -2
- package/dist/client/assets/{workspaceScrollCapture-BsjcWVsk.js.map → workspaceScrollCapture-BYNfR2wo.js.map} +1 -1
- package/dist/client/assets/{workspaceSettingsTransport-Dw2hueXv.js → workspaceSettingsTransport-Br4lBmvS.js} +2 -2
- package/dist/client/assets/{workspaceSettingsTransport-Dw2hueXv.js.map → workspaceSettingsTransport-Br4lBmvS.js.map} +1 -1
- package/dist/client/build-graph.json +98 -0
- package/dist/client/index.html +1 -1
- package/dist/server/api/agent.d.ts +12 -0
- package/dist/server/api/agent.d.ts.map +1 -1
- package/dist/server/api/deliveryGraph.d.ts +20 -0
- package/dist/server/api/deliveryGraph.d.ts.map +1 -1
- package/dist/server/api/index.d.ts +1 -1
- package/dist/server/api/index.d.ts.map +1 -1
- package/dist/server/api/index.js +3 -3
- package/dist/server/api/session.d.ts +23 -1
- package/dist/server/api/session.d.ts.map +1 -1
- package/dist/server/api/shares.d.ts +2 -0
- package/dist/server/api/shares.d.ts.map +1 -1
- package/dist/server/assets/{BindConfig-Bj282xDC.js → BindConfig-DAASchDn.js} +315 -36
- package/dist/server/assets/BindConfig-DAASchDn.js.map +1 -0
- package/dist/server/assets/{agent-ZvwskOQu.js → agent-xQhAQXly.js} +26 -6
- package/dist/server/assets/agent-xQhAQXly.js.map +1 -0
- package/dist/server/assets/{controlCenterApi-5j3gOXgE.js → controlCenterApi-DNXK7MT1.js} +4 -3
- package/dist/server/assets/controlCenterApi-DNXK7MT1.js.map +1 -0
- package/dist/server/assets/{manualPluginSynchronization-CzIhZ_Dw.js → manualPluginSynchronization-DFIeUHP9.js} +4 -3
- package/dist/server/assets/manualPluginSynchronization-DFIeUHP9.js.map +1 -0
- package/dist/server/assets/{readiness-BtntBhDj.js → readiness-31Mqc-9H.js} +2 -2
- package/dist/server/assets/{readiness-BtntBhDj.js.map → readiness-31Mqc-9H.js.map} +1 -1
- package/dist/server/assets/{relationshipInferenceMaterialization-CR6xyMNL.js → relationshipInferenceMaterialization-Dyix96px.js} +41 -14
- package/dist/server/assets/relationshipInferenceMaterialization-Dyix96px.js.map +1 -0
- package/dist/server/assets/{workspaceSettings-C2Zsk6RI.js → workspaceSettings-sv8h_h2P.js} +4 -1
- package/dist/server/assets/workspaceSettings-sv8h_h2P.js.map +1 -0
- package/dist/server/build-graph.json +28 -1
- package/dist/server/domain/confluenceTasks.d.ts +27 -0
- package/dist/server/domain/confluenceTasks.d.ts.map +1 -0
- package/dist/server/domain/deliveryGraph.d.ts +2 -0
- package/dist/server/domain/deliveryGraph.d.ts.map +1 -1
- package/dist/server/domain/governedAction/bindings.d.ts +2 -0
- package/dist/server/domain/governedAction/bindings.d.ts.map +1 -1
- package/dist/server/domain/governedAction/model.d.ts +6 -0
- package/dist/server/domain/governedAction/model.d.ts.map +1 -1
- package/dist/server/domain/index.js +2 -2
- package/dist/server/domain/normalizedPage.d.ts +1 -0
- package/dist/server/domain/normalizedPage.d.ts.map +1 -1
- package/dist/server/domain/releasePipelineApproval.d.ts +31 -0
- package/dist/server/domain/releasePipelineApproval.d.ts.map +1 -0
- package/dist/server/index.js +5 -5
- package/dist/server/server/api/Handlers.d.ts +1 -1
- package/dist/server/server/api/Handlers.d.ts.map +1 -1
- package/dist/server/server/application/deliveryGraphInspection.d.ts.map +1 -1
- package/dist/server/server/application/normalizedPluginPageMaterialization.d.ts.map +1 -1
- package/dist/server/server/application/pipelineExecutionProjection.d.ts +1 -0
- package/dist/server/server/application/pipelineExecutionProjection.d.ts.map +1 -1
- package/dist/server/server/application/portfolioSnapshots.d.ts +4 -0
- package/dist/server/server/application/portfolioSnapshots.d.ts.map +1 -1
- package/dist/server/server/application/releasePublicationSubmissions.d.ts +32 -1
- package/dist/server/server/application/releasePublicationSubmissions.d.ts.map +1 -1
- package/dist/server/server/application/releaseRunbookHydration.d.ts +2310 -0
- package/dist/server/server/application/releaseRunbookHydration.d.ts.map +1 -0
- package/dist/server/server/cli.js +3 -3
- package/dist/server/server/governance/governedActionDigests.d.ts +3 -0
- package/dist/server/server/governance/governedActionDigests.d.ts.map +1 -1
- package/dist/server/server/governance/internal/execution-store/recovery-claim.d.ts +1 -0
- package/dist/server/server/governance/internal/execution-store/recovery-claim.d.ts.map +1 -1
- package/dist/server/server/index.js +2 -2
- package/dist/server/server/persistence/Persistence.d.ts +10 -0
- package/dist/server/server/persistence/Persistence.d.ts.map +1 -1
- package/dist/server/server/persistence/object-store/BlobPublisher.d.ts.map +1 -1
- package/dist/server/server/persistence/object-store/PinnedDirectory.d.ts +2 -2
- package/dist/server/server/persistence/object-store/PinnedDirectory.d.ts.map +1 -1
- package/dist/server/server/persistence/repositories/delivery-graph/contract.d.ts +10 -0
- package/dist/server/server/persistence/repositories/delivery-graph/contract.d.ts.map +1 -1
- package/dist/server/server/persistence/repositories/delivery-graph/decode.d.ts +2 -0
- package/dist/server/server/persistence/repositories/delivery-graph/decode.d.ts.map +1 -1
- package/dist/server/server/persistence/repositories/delivery-graph/read.d.ts +6 -0
- package/dist/server/server/persistence/repositories/delivery-graph/read.d.ts.map +1 -1
- package/dist/server/server/persistence/repositories/delivery-graph/rows.d.ts +1 -0
- package/dist/server/server/persistence/repositories/delivery-graph/rows.d.ts.map +1 -1
- package/dist/server/server/persistence/repositories/delivery-graph/write.d.ts +2 -0
- package/dist/server/server/persistence/repositories/delivery-graph/write.d.ts.map +1 -1
- package/dist/server/server/persistence/repositories/deliveryGraphRepository.d.ts +6 -0
- package/dist/server/server/persistence/repositories/deliveryGraphRepository.d.ts.map +1 -1
- package/dist/server/server/persistence/repositories/governed-action/codec.d.ts +4 -0
- package/dist/server/server/persistence/repositories/governed-action/codec.d.ts.map +1 -1
- package/dist/server/server/persistence/repositories/governed-action/contract.d.ts +2 -0
- package/dist/server/server/persistence/repositories/governed-action/contract.d.ts.map +1 -1
- package/dist/server/server/persistence/repositories/governed-action/read.d.ts +4 -0
- package/dist/server/server/persistence/repositories/governed-action/read.d.ts.map +1 -1
- package/dist/server/server/persistence/repositories/governed-action/transaction.d.ts +4 -0
- package/dist/server/server/persistence/repositories/governed-action/transaction.d.ts.map +1 -1
- package/dist/server/server/persistence/repositories/governed-action/write-preparation.d.ts +1 -0
- package/dist/server/server/persistence/repositories/governed-action/write-preparation.d.ts.map +1 -1
- package/dist/server/server/persistence/repositories/governed-action/write-replay.d.ts +2 -0
- package/dist/server/server/persistence/repositories/governed-action/write-replay.d.ts.map +1 -1
- package/dist/server/server/persistence/repositories/governed-action/write.d.ts +2 -0
- package/dist/server/server/persistence/repositories/governed-action/write.d.ts.map +1 -1
- package/dist/server/server/persistence/repositories/governedActionRepository.d.ts +4 -0
- package/dist/server/server/persistence/repositories/governedActionRepository.d.ts.map +1 -1
- package/package.json +3 -3
- package/dist/client/assets/AgentPage-C3LThgPZ.js +0 -3
- package/dist/client/assets/AgentPage-C3LThgPZ.js.map +0 -1
- package/dist/client/assets/AgentPage-DVSgQgJa.css +0 -1
- package/dist/client/assets/AtlassianOAuthCallbackPage-BPoF6oKf.js +0 -2
- package/dist/client/assets/BrowserCrypto-BMbjhcvP.js +0 -2
- package/dist/client/assets/BrowserSessionHydrator-BC1ymLkL.js +0 -2
- package/dist/client/assets/PortfolioOverview-CEI4gpXi.js +0 -2
- package/dist/client/assets/ReleaseWorkset-BluAe7Sq.js +0 -2
- package/dist/client/assets/ReleaseWorkset-BluAe7Sq.js.map +0 -1
- package/dist/client/assets/ServicesPage-_B89DAvG.js +0 -2
- package/dist/client/assets/WorkspaceEntityRoute-9iMOV64J.css +0 -1
- package/dist/client/assets/WorkspaceEntityRoute-B01fxxB3.js +0 -3
- package/dist/client/assets/WorkspaceEntityRoute-B01fxxB3.js.map +0 -1
- package/dist/client/assets/WorkspaceHomeLink-CkJfzO25.js +0 -2
- package/dist/client/assets/WorkspacePullRequestDetails-HwDgp12e.js +0 -3
- package/dist/client/assets/WorkspaceRichText-D1M637Ff.js.map +0 -1
- package/dist/client/assets/WorkspaceSettingsPage-DyoGiGJG.js +0 -2
- package/dist/client/assets/WorkspaceSettingsPage-DyoGiGJG.js.map +0 -1
- package/dist/client/assets/WorkspaceSettingsPage-P6yfac0b.css +0 -1
- package/dist/client/assets/agent-api-CeONl_8w.js +0 -19
- package/dist/client/assets/agent-api-CeONl_8w.js.map +0 -1
- package/dist/client/assets/authenticatedMutationClient-DYaieXUe.js +0 -2
- package/dist/client/assets/client-DKS82kT_.js +0 -5
- package/dist/client/assets/client-DKS82kT_.js.map +0 -1
- package/dist/client/assets/connectionTestTransport-I_Ga9UNs.js +0 -2
- package/dist/client/assets/connectionTestTransport-I_Ga9UNs.js.map +0 -1
- package/dist/client/assets/releaseRoutes-t9uCfs5T.js +0 -2
- package/dist/client/assets/workspaceEntityRoutes-2TejMrzb.js +0 -2
- package/dist/client/assets/workspaceEntityRoutes-2TejMrzb.js.map +0 -1
- package/dist/server/assets/BindConfig-Bj282xDC.js.map +0 -1
- package/dist/server/assets/agent-ZvwskOQu.js.map +0 -1
- package/dist/server/assets/controlCenterApi-5j3gOXgE.js.map +0 -1
- package/dist/server/assets/manualPluginSynchronization-CzIhZ_Dw.js.map +0 -1
- package/dist/server/assets/relationshipInferenceMaterialization-CR6xyMNL.js.map +0 -1
- package/dist/server/assets/workspaceSettings-C2Zsk6RI.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"relationshipInferenceMaterialization-CR6xyMNL.js","names":["#envelope","#transition","#evaluation","#digest","#authorization","#attempt"],"sources":["../../../src/server/persistence/object-store/BlobDigest.ts","../../../src/server/persistence/backup/errors.ts","../../../src/server/persistence/errors.ts","../../../src/server/persistence/PersistenceConfig.ts","../../../src/server/persistence/schema.json","../../../src/server/persistence/schema.ts","../../../src/server/persistence/schemas.ts","../../../src/server/persistence/Database.ts","../../../src/server/persistence/repositories/internal.ts","../../../src/server/persistence/object-store/BlobRef.ts","../../../src/server/persistence/repositories/models.ts","../../../src/server/persistence/repositories/quarantineRepository.ts","../../../src/server/persistence/repositories/persistedRowQuarantine.ts","../../../src/server/secrets/SecretRef.ts","../../../src/server/persistence/object-store/BlobPath.ts","../../../src/server/persistence/repositories/agentJobModels.ts","../../../src/server/persistence/object-store/BlobStoreError.ts","../../../src/server/persistence/object-store/BlobPublisher.ts","../../../src/server/persistence/object-store/PinnedDirectory.ts","../../../src/server/persistence/object-store/OpenedBlob.ts","../../../src/server/persistence/object-store/BlobStore.ts","../../../src/server/persistence/repositories/contentBlobMetadataRepository.ts","../../../src/server/persistence/ContentStore.ts","../../../src/domain/prReviewReconciliation.ts","../../../src/server/persistence/repositories/internal/reviewSuggestionRevisions.ts","../../../src/server/persistence/repositories/agentJobRepository.ts","../../../src/server/persistence/repositories/authorizedShareRepository.ts","../../../src/server/persistence/repositories/delivery-graph/contract.ts","../../../src/server/persistence/repositories/delivery-graph/quarantine.ts","../../../src/server/persistence/repositories/delivery-graph/rows.ts","../../../src/server/persistence/repositories/delivery-graph/integrity.ts","../../../src/server/persistence/repositories/delivery-graph/decode.ts","../../../src/server/persistence/repositories/delivery-graph/release-slice.ts","../../../src/server/persistence/repositories/delivery-graph/read.ts","../../../src/server/persistence/repositories/delivery-graph/write.ts","../../../src/server/persistence/repositories/deliveryGraphRepository.ts","../../../src/server/persistence/repositories/diffContentCacheRepository.ts","../../../src/server/persistence/repositories/domainEventModels.ts","../../../src/server/persistence/repositories/domainEventRepository.ts","../../../src/server/persistence/repositories/entityRepository.ts","../../../src/server/persistence/repositories/governed-action/contract.ts","../../../src/server/persistence/repositories/governed-action/quarantine.ts","../../../src/server/governance/governedActionDigests.ts","../../../src/server/persistence/governedActionReconciliationLocator.ts","../../../src/server/persistence/repositories/governed-action/codec.ts","../../../src/server/persistence/repositories/governed-action/rows.ts","../../../src/server/persistence/repositories/governed-action/read.ts","../../../src/server/persistence/repositories/governed-action/transaction.ts","../../../src/server/persistence/repositories/governed-action/write-preparation.ts","../../../src/server/persistence/repositories/governed-action/write-replay.ts","../../../src/server/persistence/repositories/governed-action/write.ts","../../../src/server/persistence/repositories/governedActionRepository.ts","../../../src/server/persistence/repositories/peopleRepository.ts","../../../src/server/persistence/repositories/pluginConfigurationModels.ts","../../../src/server/persistence/repositories/pluginConfigurationRepository.ts","../../../src/server/persistence/repositories/pluginConnectionRepository.ts","../../../src/server/persistence/repositories/pluginRuntimeModels.ts","../../../src/server/plugins/negotiation.ts","../../../src/server/persistence/repositories/pluginRuntimeRepository.ts","../../../src/server/persistence/repositories/providerAccountRepository.ts","../../../src/server/readinessDigests.ts","../../../src/server/persistence/repositories/readiness/codec.ts","../../../src/server/persistence/repositories/readiness/contract.ts","../../../src/server/persistence/repositories/readiness/quarantine.ts","../../../src/server/persistence/repositories/readiness/rows.ts","../../../src/server/persistence/repositories/readiness/materialization.ts","../../../src/server/persistence/repositories/readiness/rules.ts","../../../src/server/persistence/repositories/readiness/assessments.ts","../../../src/server/persistence/repositories/readiness/queue.ts","../../../src/server/persistence/repositories/readinessRepository.ts","../../../src/server/persistence/repositories/relationshipRepairProposalRepository.ts","../../../src/server/persistence/repositories/releaseRepository.ts","../../../src/server/governance/GovernedHumanMutationPolicyEvaluator.ts","../../../src/server/persistence/repositories/workspaceSettingsRepository.ts","../../../src/server/persistence/repositories/retentionRepository.ts","../../../src/server/persistence/repositories/reviewCommandArtifactRepository.ts","../../../src/server/persistence/repositories/timelineExportAuditRepository.ts","../../../src/server/persistence/repositories/timelineRepository.ts","../../../src/server/persistence/repositories/workspaceRepository.ts","../../../src/server/persistence/Persistence.ts","../../../src/server/plugins/PluginConnection.ts","../../../src/server/api/ApplicationServices.ts","../../../src/server/plugins/confluence/ConfluencePageSchemas.ts","../../../src/server/plugins/firstPartySynchronization.ts","../../../src/server/runtime/DomainEventWakeups.ts","../../../src/server/application/portfolioInvalidation.ts","../../../src/server/application/relationshipInference.ts","../../../src/server/application/relationshipInferenceMaterialization.ts"],"sourcesContent":["import { Schema } from \"effect\"\n\nconst LOWERCASE_SHA_256_PATTERN = /^[0-9a-f]{64}$/\n\n/** Exact lowercase hexadecimal encoding of a SHA-256 digest. */\nexport const BlobDigest = Schema.String.check(\n Schema.isPattern(LOWERCASE_SHA_256_PATTERN, {\n expected: \"a 64-character lowercase SHA-256 digest\"\n })\n).pipe(Schema.brand(\"BlobDigest\"))\n\n/** Decoded content digest. */\nexport type BlobDigest = typeof BlobDigest.Type\n","import { Schema } from \"effect\"\n\nimport { WorkspaceId } from \"../../../domain/identifiers.js\"\nimport { BlobDigest } from \"../object-store/BlobDigest.js\"\n\nconst BackupOperation = Schema.String.check(\n Schema.isTrimmed(),\n Schema.isNonEmpty(),\n Schema.isMaxLength(100)\n)\n\n/** Untrusted archive or destination input did not satisfy the local operation contract. */\nexport class BackupInputError extends Schema.TaggedErrorClass<BackupInputError>()(\"BackupInputError\", {\n operation: BackupOperation,\n reason: Schema.Literals([\"already-exists\", \"invalid-path\", \"overlap\", \"target-raced\"])\n}) {}\n\n/** An archive artifact exceeded a documented bounded-read limit. */\nexport class BackupLimitError extends Schema.TaggedErrorClass<BackupLimitError>()(\"BackupLimitError\", {\n artifact: Schema.Literals([\"blob\", \"database\", \"manifest\"]),\n maximumBytes: Schema.Number.check(Schema.isInt(), Schema.isGreaterThan(0))\n}) {}\n\n/** A platform storage operation failed; callers retain its cause for redacted diagnostics. */\nexport class BackupStorageError extends Schema.TaggedErrorClass<BackupStorageError>()(\"BackupStorageError\", {\n cause: Schema.Defect(),\n operation: BackupOperation\n}) {}\n\n/** A database snapshot or integrity operation failed with its diagnostic cause retained. */\nexport class BackupSqlError extends Schema.TaggedErrorClass<BackupSqlError>()(\"BackupSqlError\", {\n cause: Schema.Defect(),\n operation: BackupOperation\n}) {}\n\n/** The manifest is malformed, unsupported, or inconsistent with its snapshot. */\nexport class BackupManifestError extends Schema.TaggedErrorClass<BackupManifestError>()(\n \"BackupManifestError\",\n {\n reason: Schema.Literals([\n \"blob-count-mismatch\",\n \"blob-inventory-mismatch\",\n \"boundary-mismatch\",\n \"duplicate-blob\",\n \"malformed\",\n \"schema-mismatch\",\n \"unsorted-blob-inventory\",\n \"unsupported\"\n ])\n }\n) {}\n\n/** Authoritative database or blob evidence did not pass integrity verification. */\nexport class BackupIntegrityError extends Schema.TaggedErrorClass<BackupIntegrityError>()(\n \"BackupIntegrityError\",\n {\n digest: Schema.NullOr(BlobDigest),\n reason: Schema.Literals([\n \"blob-corrupt\",\n \"blob-missing\",\n \"database-corrupt\",\n \"database-digest-mismatch\",\n \"foreign-key-violation\",\n \"owner-mode-invalid\",\n \"unexpected-artifact\"\n ]),\n workspaceId: Schema.NullOr(WorkspaceId)\n }\n) {}\n\n/** The scoped SQLite write barrier could not be acquired for schema initialization. */\nexport class SchemaWriteBarrierError extends Schema.TaggedErrorClass<SchemaWriteBarrierError>()(\n \"SchemaWriteBarrierError\",\n { phase: Schema.Literals([\"acquire\", \"verify\"]) }\n) {}\n\n/** Typed failures exposed by backup, verification, and restore operations. */\nexport type BackupFailure =\n | BackupInputError\n | BackupIntegrityError\n | BackupLimitError\n | BackupManifestError\n | BackupSqlError\n | BackupStorageError\n","import * as Schema from \"effect/Schema\"\nimport { WorkspaceId } from \"../../domain/identifiers.js\"\nimport { BlobDigest } from \"./object-store/BlobDigest.js\"\n\nconst RecordKind = Schema.String.check(\n Schema.isTrimmed(),\n Schema.isNonEmpty(),\n Schema.isMaxLength(100)\n)\n\n/** Maximum diagnostic identity retained by persistence-domain errors. */\nexport const MAXIMUM_PERSISTENCE_RECORD_KEY_LENGTH = 500\n\nconst RecordKey = Schema.String.check(\n Schema.isTrimmed(),\n Schema.isNonEmpty(),\n Schema.isMaxLength(MAXIMUM_PERSISTENCE_RECORD_KEY_LENGTH)\n)\n\nconst Revision = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))\n\n/** Raised when persistence configuration cannot be decoded safely. */\nexport class PersistenceConfigError extends Schema.TaggedErrorClass<PersistenceConfigError>()(\n \"PersistenceConfigError\",\n {\n message: Schema.String\n }\n) {}\n\n/** Raised when a database startup operation fails. */\nexport class DatabaseInitializationError extends Schema.TaggedErrorClass<DatabaseInitializationError>()(\n \"DatabaseInitializationError\",\n {\n operation: Schema.Literals([\n \"connect\",\n \"configure\",\n \"initialize-schema\",\n \"verify-integrity\",\n \"verify-pragmas\",\n \"verify-schema\"\n ])\n }\n) {}\n\n/** Raised when a workspace-scoped persisted record does not exist. */\nexport class RecordNotFoundError extends Schema.TaggedErrorClass<RecordNotFoundError>()(\n \"RecordNotFoundError\",\n {\n recordKey: RecordKey,\n recordKind: RecordKind,\n workspaceId: WorkspaceId\n }\n) {}\n\n/** Raised when creating a record would replace an existing workspace-scoped identity. */\nexport class RecordAlreadyExistsError extends Schema.TaggedErrorClass<RecordAlreadyExistsError>()(\n \"RecordAlreadyExistsError\",\n {\n recordKey: RecordKey,\n recordKind: RecordKind,\n workspaceId: WorkspaceId\n }\n) {}\n\n/** Raised when a workspace has reached its bounded plugin-connection capacity. */\nexport class PluginConnectionLimitError extends Schema.TaggedErrorClass<PluginConnectionLimitError>()(\n \"PluginConnectionLimitError\",\n {\n maximum: Schema.Number.check(Schema.isInt(), Schema.isGreaterThan(0)),\n workspaceId: WorkspaceId\n }\n) {}\n\n/** Raised when an entity update attempts to replace its immutable vendor identity. */\nexport class SourceIdentityMismatchError extends Schema.TaggedErrorClass<SourceIdentityMismatchError>()(\n \"SourceIdentityMismatchError\",\n {\n recordKey: RecordKey,\n recordKind: RecordKind,\n workspaceId: WorkspaceId\n }\n) {}\n\n/** Stable boundary error for a failed persistence operation. */\nexport class PersistenceOperationError extends Schema.TaggedErrorClass<PersistenceOperationError>()(\n \"PersistenceOperationError\",\n {\n operation: Schema.String.check(\n Schema.isTrimmed(),\n Schema.isNonEmpty(),\n Schema.isMaxLength(100)\n )\n }\n) {}\n\n/** Raised when identical content bytes are registered with conflicting durable metadata. */\nexport class ContentMetadataMismatchError extends Schema.TaggedErrorClass<ContentMetadataMismatchError>()(\n \"ContentMetadataMismatchError\",\n {\n digest: BlobDigest,\n workspaceId: WorkspaceId\n }\n) {}\n\n/** Reproducible bytes are unavailable and the owning adapter may safely refetch them. */\nexport class ReproducibleContentUnavailableError extends Schema.TaggedErrorClass<\n ReproducibleContentUnavailableError\n>()(\n \"ReproducibleContentUnavailableError\",\n {\n digest: BlobDigest,\n workspaceId: WorkspaceId,\n reason: Schema.Literals([\"corrupt\", \"missing\"]),\n recovery: Schema.Literal(\"refetch\")\n }\n) {}\n\n/** Raised when a compare-and-swap update observes a different persisted revision. */\nexport class RevisionConflictError extends Schema.TaggedErrorClass<RevisionConflictError>()(\n \"RevisionConflictError\",\n {\n actualRevision: Schema.Union([Revision, Schema.Null]),\n expectedRevision: Revision,\n recordKey: RecordKey,\n recordKind: RecordKind,\n workspaceId: WorkspaceId\n }\n) {}\n\n/** Raised when an opaque secret reference is reused outside its durable first-use scope. */\nexport class SecretReferenceScopeConflictError extends Schema.TaggedErrorClass<SecretReferenceScopeConflictError>()(\n \"SecretReferenceScopeConflictError\",\n {}\n) {}\n\n/** Raised when a persisted record cannot be decoded into its trusted domain model. */\nexport class PersistedRecordError extends Schema.TaggedErrorClass<PersistedRecordError>()(\n \"PersistedRecordError\",\n {\n diagnosticCode: Schema.String.check(\n Schema.isTrimmed(),\n Schema.isNonEmpty(),\n Schema.isMaxLength(100)\n ),\n recordKey: RecordKey,\n recordKind: RecordKind,\n workspaceId: WorkspaceId\n }\n) {}\n\n/** A settings mutation did not acknowledge the exact governed sections it changes. */\nexport class WorkspaceSettingsGovernanceError extends Schema.TaggedErrorClass<\n WorkspaceSettingsGovernanceError\n>()(\"WorkspaceSettingsGovernanceError\", {}) {}\n\n/** A settings mutation identity was already committed with different semantics. */\nexport class WorkspaceSettingsMutationConflictError extends Schema.TaggedErrorClass<\n WorkspaceSettingsMutationConflictError\n>()(\"WorkspaceSettingsMutationConflictError\", {}) {}\n\n/** A complete settings replacement did not change the current aggregate. */\nexport class WorkspaceSettingsNoChangesError extends Schema.TaggedErrorClass<\n WorkspaceSettingsNoChangesError\n>()(\"WorkspaceSettingsNoChangesError\", {}) {}\n\n/** Raised when a bounded quarantine diagnostic cannot be persisted. */\nexport class QuarantineWriteError extends Schema.TaggedErrorClass<QuarantineWriteError>()(\n \"QuarantineWriteError\",\n {\n recordKey: RecordKey,\n recordKind: RecordKind,\n workspaceId: WorkspaceId\n }\n) {}\n","import { Effect, Schema } from \"effect\"\nimport { PersistenceConfigError } from \"./errors.js\"\n\nconst LOCAL_DATABASE_URL_PATTERN = /^file:(?:\\/(?!\\/)|\\/\\/\\/(?!\\/)|[A-Za-z]:[\\\\/])[^?#]+$/u\nconst ABSOLUTE_PATH_PATTERN = /^(?:\\/|[A-Za-z]:[\\\\/])/u\nconst ENCODED_CONTROL_CHARACTER_PATTERN = /%(?:[01][0-9a-f]|7f|8[0-9a-f]|9[0-9a-f])/iu\n\nconst hasNoControlCharacters = (value: string): boolean =>\n Array.from(value).every((character) => {\n const codePoint = character.codePointAt(0)\n return (\n codePoint !== undefined &&\n !((codePoint >= 0 && codePoint <= 0x1f) || (codePoint >= 0x7f && codePoint <= 0x9f))\n )\n })\n\nconst SafeLocalString = Schema.String.check(\n Schema.makeFilter(hasNoControlCharacters, {\n expected: \"a local value without control characters\"\n }),\n Schema.makeFilter((value) => !ENCODED_CONTROL_CHARACTER_PATTERN.test(value), {\n expected: \"a local value without encoded control characters\"\n })\n)\n\n/** Local libSQL database URL accepted by the Control Center persistence layer. */\nexport const LocalDatabaseUrl = SafeLocalString.check(\n Schema.isTrimmed(),\n Schema.isNonEmpty(),\n Schema.isMaxLength(4_096),\n Schema.isPattern(LOCAL_DATABASE_URL_PATTERN, {\n expected: \"a local file: database URL without an authority\"\n })\n).pipe(Schema.brand(\"LocalDatabaseUrl\"))\n\n/** Decoded local libSQL database URL. */\nexport type LocalDatabaseUrl = typeof LocalDatabaseUrl.Type\n\n/** Absolute owner-controlled root for content-addressed blob bytes. */\nexport const BlobRoot = SafeLocalString.check(\n Schema.isTrimmed(),\n Schema.isNonEmpty(),\n Schema.isMaxLength(4_096),\n Schema.isPattern(ABSOLUTE_PATH_PATTERN, { expected: \"an absolute filesystem path\" })\n).pipe(Schema.brand(\"BlobRoot\"))\n\n/** Decoded owner-controlled blob root. */\nexport type BlobRoot = typeof BlobRoot.Type\n\n/** Secret-free configuration shared by the database and blob persistence layers. */\nexport const PersistenceConfig = Schema.Struct({\n blobRoot: BlobRoot,\n busyTimeoutMilliseconds: Schema.Literal(5_000),\n databaseUrl: LocalDatabaseUrl,\n maxConnections: Schema.Literal(1)\n}).annotate({ identifier: \"PersistenceConfig\" })\n\n/** Decoded Control Center persistence configuration. */\nexport type PersistenceConfig = typeof PersistenceConfig.Type\n\n/** Decode untrusted persistence configuration without exposing rejected values. */\nexport const decodePersistenceConfig = Effect.fn(\"decodePersistenceConfig\")(function*(\n input: unknown\n): Effect.fn.Return<PersistenceConfig, PersistenceConfigError> {\n return yield* Schema.decodeUnknownEffect(PersistenceConfig)(input).pipe(\n Effect.mapError(\n () =>\n new PersistenceConfigError({\n message:\n \"Persistence configuration requires a local database URL, absolute blob root, and bounded concurrency\"\n })\n )\n )\n})\n","{\n \"version\": \"unstable\",\n \"objects\": [\n {\n \"type\": \"table\",\n \"name\": \"agent_job_attempts\",\n \"sql\": \"CREATE TABLE agent_job_attempts (\\n workspace_id TEXT NOT NULL,\\n job_id TEXT NOT NULL,\\n attempt_sequence INTEGER NOT NULL CHECK(attempt_sequence BETWEEN 1 AND 9007199254740991),\\n context_snapshot_json TEXT NOT NULL CHECK(length(context_snapshot_json) BETWEEN 2 AND 65536),\\n context_snapshot_digest TEXT NOT NULL CHECK(\\n length(context_snapshot_digest) = 71 AND context_snapshot_digest GLOB 'sha256:*'\\n AND substr(context_snapshot_digest, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n output_bytes INTEGER NOT NULL DEFAULT 0 CHECK(output_bytes BETWEEN 0 AND 1048576),\\n provider_run_ref TEXT CHECK(provider_run_ref IS NULL OR length(provider_run_ref) BETWEEN 1 AND 1000),\\n session_ref TEXT CHECK(session_ref IS NULL OR length(session_ref) BETWEEN 1 AND 200),\\n started_at TEXT NOT NULL,\\n completed_at TEXT,\\n outcome TEXT CHECK(outcome IS NULL OR outcome IN ('success', 'failed', 'cancelled', 'max-steps')),\\n error_json TEXT CHECK(error_json IS NULL OR length(error_json) BETWEEN 2 AND 8192),\\n PRIMARY KEY (workspace_id, job_id, attempt_sequence),\\n FOREIGN KEY (workspace_id, job_id)\\n REFERENCES agent_jobs(workspace_id, job_id)\\n ON DELETE RESTRICT,\\n CHECK(\\n (completed_at IS NULL AND outcome IS NULL AND error_json IS NULL) OR\\n (completed_at IS NOT NULL AND outcome IS NOT NULL AND started_at <= completed_at)\\n ),\\n CHECK(error_json IS NULL OR outcome = 'failed')\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"agent_job_leases\",\n \"sql\": \"CREATE TABLE agent_job_leases (\\n workspace_id TEXT NOT NULL,\\n job_id TEXT NOT NULL,\\n attempt_sequence INTEGER NOT NULL CHECK(attempt_sequence BETWEEN 1 AND 9007199254740991),\\n lease_owner TEXT NOT NULL CHECK(length(lease_owner) BETWEEN 1 AND 200),\\n lease_token TEXT NOT NULL CHECK(\\n length(lease_token) = 64 AND lease_token NOT GLOB '*[^0-9a-f]*'\\n ),\\n acquired_at TEXT NOT NULL,\\n last_renewed_at TEXT NOT NULL,\\n lease_expires_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, job_id, attempt_sequence),\\n UNIQUE (lease_token),\\n FOREIGN KEY (workspace_id, job_id, attempt_sequence)\\n REFERENCES agent_job_attempts(workspace_id, job_id, attempt_sequence)\\n ON DELETE RESTRICT,\\n CHECK(acquired_at <= last_renewed_at),\\n CHECK(last_renewed_at < lease_expires_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"agent_jobs\",\n \"sql\": \"CREATE TABLE agent_jobs (\\n workspace_id TEXT NOT NULL,\\n job_id TEXT NOT NULL,\\n thread_id TEXT NOT NULL,\\n release_id TEXT NOT NULL,\\n provider_id TEXT NOT NULL CHECK(length(provider_id) BETWEEN 1 AND 200),\\n model TEXT CHECK(model IS NULL OR length(model) BETWEEN 1 AND 500),\\n access TEXT NOT NULL CHECK(access IN ('read-only', 'workspace-write')),\\n prompt TEXT NOT NULL CHECK(length(prompt) BETWEEN 1 AND 5000),\\n context_fingerprint TEXT NOT NULL CHECK(\\n length(context_fingerprint) = 71 AND context_fingerprint GLOB 'sha256:*'\\n AND substr(context_fingerprint, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n subject_revision TEXT NOT NULL CHECK(length(subject_revision) BETWEEN 1 AND 500),\\n task_context_json TEXT NOT NULL CHECK(length(task_context_json) BETWEEN 2 AND 32768),\\n task_context_digest TEXT NOT NULL CHECK(\\n length(task_context_digest) = 71 AND task_context_digest GLOB 'sha256:*'\\n AND substr(task_context_digest, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n state TEXT NOT NULL CHECK(state IN (\\n 'queued', 'running', 'cancel-requested', 'succeeded', 'failed', 'cancelled'\\n )),\\n created_at TEXT NOT NULL,\\n cancel_requested_at TEXT,\\n terminal_at TEXT,\\n PRIMARY KEY (workspace_id, job_id),\\n UNIQUE (workspace_id, job_id, thread_id),\\n FOREIGN KEY (workspace_id, thread_id)\\n REFERENCES agent_threads(workspace_id, thread_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, release_id)\\n REFERENCES releases(workspace_id, release_id)\\n ON DELETE RESTRICT,\\n CHECK(cancel_requested_at IS NULL OR created_at <= cancel_requested_at),\\n CHECK(terminal_at IS NULL OR created_at <= terminal_at),\\n CHECK(\\n (state IN ('queued', 'running') AND cancel_requested_at IS NULL AND terminal_at IS NULL) OR\\n (state = 'cancel-requested' AND cancel_requested_at IS NOT NULL AND terminal_at IS NULL) OR\\n (state IN ('succeeded', 'failed') AND terminal_at IS NOT NULL) OR\\n (state = 'cancelled' AND terminal_at IS NOT NULL)\\n )\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"agent_review_command_artifacts\",\n \"sql\": \"CREATE TABLE agent_review_command_artifacts (\\n workspace_id TEXT NOT NULL,\\n thread_id TEXT NOT NULL,\\n job_id TEXT NOT NULL,\\n attempt_sequence INTEGER NOT NULL CHECK(attempt_sequence BETWEEN 1 AND 9007199254740991),\\n command_sequence INTEGER NOT NULL CHECK(command_sequence BETWEEN 1 AND 9007199254740991),\\n artifact_id TEXT NOT NULL CHECK(length(artifact_id) = 36),\\n stream TEXT NOT NULL CHECK(stream IN ('stderr', 'stdout')),\\n byte_length INTEGER NOT NULL CHECK(byte_length BETWEEN 1 AND 16777216),\\n content_blob BLOB NOT NULL CHECK(typeof(content_blob) = 'blob'),\\n created_at TEXT NOT NULL,\\n expires_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, artifact_id),\\n UNIQUE (workspace_id, job_id, attempt_sequence, command_sequence, stream),\\n FOREIGN KEY (workspace_id, job_id, thread_id)\\n REFERENCES agent_jobs(workspace_id, job_id, thread_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, job_id, attempt_sequence)\\n REFERENCES agent_job_attempts(workspace_id, job_id, attempt_sequence)\\n ON DELETE RESTRICT,\\n CHECK(byte_length = length(content_blob)),\\n CHECK(created_at < expires_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"agent_review_suggestion_publications\",\n \"sql\": \"CREATE TABLE agent_review_suggestion_publications (\\n workspace_id TEXT NOT NULL,\\n job_id TEXT NOT NULL,\\n suggestion_id TEXT NOT NULL CHECK(\\n length(suggestion_id) = 71 AND suggestion_id GLOB 'sha256:*'\\n AND substr(suggestion_id, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n revision_id TEXT NOT NULL CHECK(\\n length(revision_id) = 71 AND revision_id GLOB 'sha256:*'\\n AND substr(revision_id, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n content_digest TEXT NOT NULL CHECK(\\n length(content_digest) = 71 AND content_digest GLOB 'sha256:*'\\n AND substr(content_digest, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n state TEXT NOT NULL CHECK(state IN ('reserved', 'published')),\\n publication_id TEXT,\\n comment_id TEXT CHECK(comment_id IS NULL OR length(comment_id) BETWEEN 1 AND 512),\\n previous_content_digest TEXT CHECK(previous_content_digest IS NULL OR (length(previous_content_digest) = 71 AND previous_content_digest GLOB 'sha256:*' AND substr(previous_content_digest, 8) NOT GLOB '*[^0-9a-f]*')),\\n previous_publication_id TEXT CHECK(previous_publication_id IS NULL OR length(previous_publication_id) BETWEEN 1 AND 512),\\n previous_published_at TEXT,\\n reservation_id TEXT NOT NULL,\\n reservation_acquired_at TEXT NOT NULL,\\n reserved_at TEXT NOT NULL,\\n published_at TEXT,\\n CHECK((previous_content_digest IS NULL AND previous_publication_id IS NULL AND previous_published_at IS NULL) OR (previous_content_digest IS NOT NULL AND previous_publication_id IS NOT NULL AND previous_published_at IS NOT NULL AND state = 'reserved')),\\n PRIMARY KEY (workspace_id, job_id, suggestion_id, revision_id),\\n FOREIGN KEY (workspace_id, job_id)\\n REFERENCES agent_jobs(workspace_id, job_id)\\n ON DELETE RESTRICT,\\n CHECK(reserved_at <= reservation_acquired_at),\\n CHECK(\\n (state = 'reserved' AND (\\n (publication_id IS NULL AND published_at IS NULL) OR\\n (publication_id IS NOT NULL AND published_at IS NOT NULL AND reserved_at <= published_at)\\n )) OR\\n (state = 'published' AND publication_id IS NOT NULL AND published_at IS NOT NULL\\n AND reserved_at <= published_at)\\n )\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"agent_review_suggestion_revisions\",\n \"sql\": \"CREATE TABLE agent_review_suggestion_revisions (\\n workspace_id TEXT NOT NULL,\\n source_job_id TEXT NOT NULL,\\n suggestion_id TEXT NOT NULL CHECK(\\n length(suggestion_id) = 71 AND suggestion_id GLOB 'sha256:*'\\n AND substr(suggestion_id, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n revision_sequence INTEGER NOT NULL CHECK(\\n revision_sequence BETWEEN 2 AND 9007199254740991\\n ),\\n revision_id TEXT NOT NULL CHECK(\\n length(revision_id) = 71 AND revision_id GLOB 'sha256:*'\\n AND substr(revision_id, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n predecessor_revision_id TEXT NOT NULL CHECK(\\n length(predecessor_revision_id) = 71 AND predecessor_revision_id GLOB 'sha256:*'\\n AND substr(predecessor_revision_id, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n revision_json TEXT NOT NULL CHECK(length(revision_json) BETWEEN 2 AND 65536),\\n revision_digest TEXT NOT NULL CHECK(\\n length(revision_digest) = 71 AND revision_digest GLOB 'sha256:*'\\n AND substr(revision_digest, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n created_at TEXT NOT NULL,\\n PRIMARY KEY (\\n workspace_id, source_job_id, suggestion_id, revision_sequence\\n ),\\n UNIQUE (workspace_id, revision_id),\\n FOREIGN KEY (workspace_id, source_job_id)\\n REFERENCES agent_jobs(workspace_id, job_id)\\n ON DELETE RESTRICT\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"agent_thread_events\",\n \"sql\": \"CREATE TABLE agent_thread_events (\\n workspace_id TEXT NOT NULL,\\n thread_id TEXT NOT NULL,\\n event_sequence INTEGER NOT NULL CHECK(event_sequence BETWEEN 1 AND 9007199254740991),\\n job_id TEXT NOT NULL,\\n attempt_sequence INTEGER,\\n event_kind TEXT NOT NULL CHECK(event_kind IN (\\n 'user-message', 'job-queued', 'job-started', 'assistant-output', 'progress',\\n 'usage', 'review-report', 'review-suggestion-revised',\\n 'review-suggestion-published', 'job-completed', 'job-failed', 'cancel-requested'\\n )),\\n payload_json TEXT NOT NULL CHECK(length(payload_json) BETWEEN 2 AND 32768),\\n payload_digest TEXT NOT NULL CHECK(\\n length(payload_digest) = 71 AND payload_digest GLOB 'sha256:*'\\n AND substr(payload_digest, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n payload_byte_length INTEGER NOT NULL CHECK(payload_byte_length BETWEEN 2 AND 32768),\\n occurred_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, thread_id, event_sequence),\\n FOREIGN KEY (workspace_id, thread_id)\\n REFERENCES agent_threads(workspace_id, thread_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, job_id)\\n REFERENCES agent_jobs(workspace_id, job_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, job_id, attempt_sequence)\\n REFERENCES agent_job_attempts(workspace_id, job_id, attempt_sequence)\\n ON DELETE RESTRICT,\\n CHECK(payload_byte_length = length(CAST(payload_json AS BLOB))),\\n CHECK(\\n (event_kind IN (\\n 'user-message', 'job-queued', 'cancel-requested', 'review-suggestion-revised'\\n ) AND attempt_sequence IS NULL) OR\\n (event_kind IN (\\n 'job-started', 'assistant-output', 'progress', 'usage', 'review-report',\\n 'review-suggestion-published', 'job-completed', 'job-failed'\\n ) AND attempt_sequence IS NOT NULL)\\n )\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"agent_threads\",\n \"sql\": \"CREATE TABLE agent_threads (\\n workspace_id TEXT NOT NULL,\\n thread_id TEXT NOT NULL,\\n thread_kind TEXT NOT NULL CHECK(thread_kind IN ('release-chat', 'pr-review')),\\n subject_key TEXT NOT NULL CHECK(length(subject_key) BETWEEN 1 AND 2048),\\n release_id TEXT NOT NULL,\\n next_event_sequence INTEGER NOT NULL DEFAULT 1 CHECK(\\n next_event_sequence BETWEEN 1 AND 9007199254740991\\n ),\\n created_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, thread_id),\\n UNIQUE (workspace_id, thread_kind, subject_key),\\n FOREIGN KEY (workspace_id) REFERENCES workspaces(workspace_id),\\n FOREIGN KEY (workspace_id, release_id)\\n REFERENCES releases(workspace_id, release_id)\\n ON DELETE RESTRICT\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"audit_events\",\n \"sql\": \"CREATE TABLE audit_events (\\n workspace_id TEXT NOT NULL,\\n action_id TEXT NOT NULL,\\n transition_id TEXT NOT NULL,\\n audit_event_id TEXT NOT NULL,\\n event_kind TEXT NOT NULL CHECK(event_kind IN (\\n 'proposed', 'authorized', 'denied', 'expired', 'cancelled', 'started',\\n 'cancel-requested', 'cancel-requested-unknown', 'succeeded', 'failed', 'unknown'\\n )),\\n cause_kind TEXT NOT NULL CHECK(cause_kind IN ('human', 'agent', 'system')),\\n actor_id TEXT CHECK(actor_id IS NULL OR length(actor_id) BETWEEN 1 AND 512),\\n session_id TEXT,\\n job_id TEXT CHECK(job_id IS NULL OR length(job_id) BETWEEN 1 AND 512),\\n system_component TEXT CHECK(\\n system_component IS NULL OR length(system_component) BETWEEN 1 AND 200\\n ),\\n causation_id TEXT,\\n correlation_id TEXT CHECK(\\n correlation_id IS NULL OR length(correlation_id) BETWEEN 1 AND 128\\n ),\\n payload_digest TEXT NOT NULL CHECK(\\n length(payload_digest) = 71 AND payload_digest GLOB 'sha256:*'\\n AND substr(payload_digest, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n payload_json TEXT NOT NULL CHECK(length(payload_json) BETWEEN 2 AND 262144),\\n occurred_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, audit_event_id),\\n UNIQUE (workspace_id, action_id, transition_id),\\n FOREIGN KEY (workspace_id, action_id, transition_id)\\n REFERENCES governed_action_transitions(workspace_id, action_id, transition_id),\\n FOREIGN KEY (workspace_id, session_id)\\n REFERENCES sessions(workspace_id, session_id),\\n CHECK(\\n (cause_kind = 'human' AND actor_id IS NOT NULL AND session_id IS NOT NULL\\n AND job_id IS NULL AND system_component IS NULL) OR\\n (cause_kind = 'agent' AND actor_id IS NOT NULL AND session_id IS NULL\\n AND job_id IS NOT NULL AND system_component IS NULL) OR\\n (cause_kind = 'system' AND actor_id IS NULL AND session_id IS NULL\\n AND job_id IS NULL AND system_component IS NOT NULL)\\n )\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"authorized_share_grants\",\n \"sql\": \"CREATE TABLE authorized_share_grants (\\n workspace_id TEXT NOT NULL,\\n share_id TEXT NOT NULL,\\n schema_version INTEGER NOT NULL CHECK(schema_version = 1),\\n entity_id TEXT NOT NULL,\\n grantee_person_id TEXT NOT NULL,\\n created_by_person_id TEXT NOT NULL,\\n created_by_session_id TEXT NOT NULL,\\n expires_at TEXT NOT NULL,\\n created_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, share_id),\\n FOREIGN KEY (workspace_id, entity_id)\\n REFERENCES entities(workspace_id, entity_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, grantee_person_id)\\n REFERENCES persons(workspace_id, person_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, created_by_person_id)\\n REFERENCES persons(workspace_id, person_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, created_by_session_id)\\n REFERENCES sessions(workspace_id, session_id)\\n ON DELETE RESTRICT,\\n CHECK(created_at < expires_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"authorized_share_revocations\",\n \"sql\": \"CREATE TABLE authorized_share_revocations (\\n workspace_id TEXT NOT NULL,\\n share_id TEXT NOT NULL,\\n revoked_by_person_id TEXT NOT NULL,\\n revoked_by_session_id TEXT NOT NULL,\\n revoked_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, share_id),\\n FOREIGN KEY (workspace_id, share_id)\\n REFERENCES authorized_share_grants(workspace_id, share_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, revoked_by_person_id)\\n REFERENCES persons(workspace_id, person_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, revoked_by_session_id)\\n REFERENCES sessions(workspace_id, session_id)\\n ON DELETE RESTRICT\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"content_blobs\",\n \"sql\": \"CREATE TABLE content_blobs (\\n workspace_id TEXT NOT NULL,\\n digest TEXT NOT NULL CHECK(\\n length(digest) = 64 AND\\n digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n storage_class TEXT NOT NULL CHECK(storage_class IN ('durable', 'reproducible-cache')),\\n byte_length INTEGER NOT NULL CHECK(byte_length >= 0),\\n mime_type TEXT CHECK(mime_type IS NULL OR length(mime_type) BETWEEN 1 AND 255),\\n created_at TEXT NOT NULL,\\n last_verified_at TEXT,\\n PRIMARY KEY (workspace_id, digest),\\n FOREIGN KEY (workspace_id) REFERENCES workspaces(workspace_id),\\n CHECK(last_verified_at IS NULL OR created_at <= last_verified_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"delivery_nodes\",\n \"sql\": \"CREATE TABLE delivery_nodes (\\n workspace_id TEXT NOT NULL,\\n node_id TEXT NOT NULL,\\n node_key_digest TEXT NOT NULL CHECK(\\n length(node_key_digest) = 64 AND\\n node_key_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n node_kind TEXT NOT NULL CHECK(node_kind IN ('entity', 'release', 'environment')),\\n endpoint_kind TEXT NOT NULL CHECK(endpoint_kind IN (\\n 'issue', 'pull-request', 'page', 'pipeline-execution',\\n 'deployment', 'time-entry', 'release', 'environment'\\n )),\\n resolution_state TEXT NOT NULL CHECK(resolution_state IN ('resolved', 'missing')),\\n entity_id TEXT,\\n release_id TEXT,\\n environment_id TEXT,\\n expected_entity_kind TEXT CHECK(\\n expected_entity_kind IS NULL OR expected_entity_kind IN (\\n 'issue', 'pull-request', 'page', 'pipeline-execution',\\n 'deployment', 'time-entry'\\n )\\n ),\\n missing_key TEXT CHECK(missing_key IS NULL OR length(missing_key) BETWEEN 1 AND 512),\\n created_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, node_id),\\n UNIQUE (workspace_id, node_id, endpoint_kind),\\n UNIQUE (workspace_id, node_key_digest),\\n FOREIGN KEY (workspace_id, entity_id)\\n REFERENCES entities(workspace_id, entity_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, release_id)\\n REFERENCES releases(workspace_id, release_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, release_id, environment_id)\\n REFERENCES release_targets(workspace_id, release_id, environment_id)\\n ON DELETE RESTRICT,\\n CHECK(\\n (\\n resolution_state = 'resolved' AND\\n expected_entity_kind IS NULL AND missing_key IS NULL AND\\n (\\n (node_kind = 'entity' AND endpoint_kind IN (\\n 'issue', 'pull-request', 'page', 'pipeline-execution', 'deployment', 'time-entry'\\n ) AND entity_id IS NOT NULL AND release_id IS NULL AND environment_id IS NULL) OR\\n (node_kind = 'release' AND endpoint_kind = 'release' AND\\n entity_id IS NULL AND release_id IS NOT NULL AND environment_id IS NULL) OR\\n (node_kind = 'environment' AND endpoint_kind = 'environment' AND\\n entity_id IS NULL AND release_id IS NOT NULL AND environment_id IS NOT NULL)\\n )\\n ) OR (\\n resolution_state = 'missing' AND\\n entity_id IS NULL AND release_id IS NULL AND environment_id IS NULL AND\\n missing_key IS NOT NULL AND\\n (\\n (node_kind = 'entity' AND expected_entity_kind IS NOT NULL AND\\n endpoint_kind = expected_entity_kind) OR\\n (node_kind IN ('release', 'environment') AND expected_entity_kind IS NULL AND\\n endpoint_kind = node_kind)\\n )\\n )\\n )\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"diff_content_cache_cleanup\",\n \"sql\": \"CREATE TABLE diff_content_cache_cleanup (\\n workspace_id TEXT NOT NULL,\\n content_digest TEXT NOT NULL CHECK(\\n length(content_digest) = 64 AND content_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n requested_at TEXT NOT NULL,\\n attempt_count INTEGER NOT NULL DEFAULT 0 CHECK(attempt_count >= 0),\\n PRIMARY KEY (workspace_id, content_digest),\\n FOREIGN KEY (workspace_id, content_digest)\\n REFERENCES content_blobs(workspace_id, digest)\\n ON DELETE CASCADE\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"diff_content_cache_entries\",\n \"sql\": \"CREATE TABLE diff_content_cache_entries (\\n workspace_id TEXT NOT NULL,\\n plugin_connection_id TEXT NOT NULL,\\n vendor_immutable_id TEXT NOT NULL CHECK(length(vendor_immutable_id) BETWEEN 1 AND 512),\\n source_revision TEXT NOT NULL CHECK(length(source_revision) BETWEEN 1 AND 512),\\n file_anchor TEXT NOT NULL CHECK(\\n length(file_anchor) = 71 AND file_anchor GLOB 'sha256:*'\\n AND substr(file_anchor, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n file_status TEXT NOT NULL CHECK(file_status IN ('added', 'modified', 'deleted', 'renamed', 'copied')),\\n side TEXT NOT NULL CHECK(side IN ('before', 'after')),\\n content_digest TEXT NOT NULL CHECK(\\n length(content_digest) = 64 AND content_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n cached_at TEXT NOT NULL,\\n PRIMARY KEY (\\n workspace_id, plugin_connection_id, vendor_immutable_id, source_revision,\\n file_anchor, file_status, side\\n ),\\n FOREIGN KEY (workspace_id, plugin_connection_id)\\n REFERENCES plugin_connections(workspace_id, plugin_connection_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, content_digest)\\n REFERENCES content_blobs(workspace_id, digest)\\n ON DELETE RESTRICT\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"domain_event_streams\",\n \"sql\": \"CREATE TABLE domain_event_streams (\\n workspace_id TEXT NOT NULL,\\n next_cursor INTEGER NOT NULL DEFAULT 1 CHECK(\\n next_cursor BETWEEN 1 AND 9007199254740991\\n ),\\n pruned_through_cursor INTEGER NOT NULL DEFAULT 0 CHECK(\\n pruned_through_cursor >= 0 AND pruned_through_cursor < next_cursor\\n ),\\n updated_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id),\\n FOREIGN KEY (workspace_id) REFERENCES workspaces(workspace_id)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"domain_events\",\n \"sql\": \"CREATE TABLE domain_events (\\n workspace_id TEXT NOT NULL,\\n event_cursor INTEGER NOT NULL CHECK(\\n event_cursor BETWEEN 1 AND 9007199254740990\\n ),\\n event_id TEXT NOT NULL,\\n schema_version INTEGER NOT NULL CHECK(schema_version >= 1),\\n event_type TEXT NOT NULL CHECK(length(event_type) BETWEEN 1 AND 100),\\n dedupe_key TEXT NOT NULL CHECK(length(dedupe_key) BETWEEN 1 AND 512),\\n release_id TEXT,\\n plugin_connection_id TEXT,\\n entity_id TEXT,\\n job_id TEXT,\\n occurred_at TEXT NOT NULL,\\n ingested_at TEXT NOT NULL,\\n causation_id TEXT,\\n correlation_id TEXT CHECK(\\n correlation_id IS NULL OR length(correlation_id) BETWEEN 1 AND 128\\n ),\\n payload_json TEXT NOT NULL CHECK(length(payload_json) BETWEEN 1 AND 65536),\\n payload_digest TEXT NOT NULL CHECK(\\n length(payload_digest) = 64 AND\\n payload_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n PRIMARY KEY (workspace_id, event_cursor),\\n UNIQUE (workspace_id, event_id),\\n UNIQUE (workspace_id, event_type, dedupe_key),\\n FOREIGN KEY (workspace_id) REFERENCES workspaces(workspace_id),\\n FOREIGN KEY (workspace_id, release_id)\\n REFERENCES releases(workspace_id, release_id),\\n FOREIGN KEY (workspace_id, plugin_connection_id)\\n REFERENCES plugin_connections(workspace_id, plugin_connection_id),\\n FOREIGN KEY (workspace_id, entity_id)\\n REFERENCES entities(workspace_id, entity_id)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"entities\",\n \"sql\": \"CREATE TABLE entities (\\n workspace_id TEXT NOT NULL,\\n entity_id TEXT NOT NULL,\\n plugin_connection_id TEXT NOT NULL,\\n provider_id TEXT NOT NULL CHECK(provider_id IN (\\n 'codecommit', 'codepipeline', 'jira', 'confluence', 'clockify'\\n )),\\n vendor_immutable_id TEXT NOT NULL CHECK(length(vendor_immutable_id) BETWEEN 1 AND 512),\\n entity_type TEXT NOT NULL CHECK(length(entity_type) BETWEEN 1 AND 100),\\n current_revision INTEGER NOT NULL CHECK(current_revision >= 1),\\n created_at TEXT NOT NULL,\\n updated_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, entity_id),\\n UNIQUE (\\n workspace_id,\\n plugin_connection_id,\\n provider_id,\\n vendor_immutable_id\\n ),\\n FOREIGN KEY (workspace_id, plugin_connection_id, provider_id)\\n REFERENCES plugin_connections(workspace_id, plugin_connection_id, provider_id),\\n CHECK(created_at <= updated_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"entity_projection_revisions\",\n \"sql\": \"CREATE TABLE entity_projection_revisions (\\n workspace_id TEXT NOT NULL,\\n entity_id TEXT NOT NULL,\\n projection_revision INTEGER NOT NULL CHECK(projection_revision >= 1),\\n source_entity_revision INTEGER NOT NULL CHECK(source_entity_revision >= 1),\\n supersedes_projection_revision INTEGER,\\n projection_schema_version INTEGER NOT NULL CHECK(projection_schema_version >= 1),\\n entity_state TEXT NOT NULL CHECK(entity_state IN ('present', 'deleted')),\\n display_key TEXT NOT NULL CHECK(length(display_key) BETWEEN 1 AND 200),\\n title TEXT NOT NULL CHECK(length(title) BETWEEN 1 AND 500),\\n extension_json TEXT NOT NULL CHECK(length(extension_json) BETWEEN 2 AND 263168),\\n extension_digest TEXT NOT NULL CHECK(\\n length(extension_digest) = 64 AND\\n extension_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n recorded_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, entity_id, projection_revision),\\n FOREIGN KEY (workspace_id, entity_id, source_entity_revision)\\n REFERENCES entity_revisions(workspace_id, entity_id, revision)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, entity_id, supersedes_projection_revision)\\n REFERENCES entity_projection_revisions(workspace_id, entity_id, projection_revision)\\n ON DELETE RESTRICT,\\n CHECK(\\n (projection_revision = 1 AND supersedes_projection_revision IS NULL) OR\\n (projection_revision > 1 AND supersedes_projection_revision = projection_revision - 1)\\n )\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"entity_revisions\",\n \"sql\": \"CREATE TABLE entity_revisions (\\n workspace_id TEXT NOT NULL,\\n entity_id TEXT NOT NULL,\\n revision INTEGER NOT NULL CHECK(revision >= 1),\\n source_revision TEXT NOT NULL CHECK(length(source_revision) BETWEEN 1 AND 512),\\n normalization_schema_version INTEGER NOT NULL CHECK(normalization_schema_version >= 1),\\n source_url TEXT,\\n first_observed_at TEXT NOT NULL,\\n last_observed_at TEXT NOT NULL,\\n synchronized_at TEXT NOT NULL,\\n created_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, entity_id, revision),\\n FOREIGN KEY (workspace_id, entity_id)\\n REFERENCES entities(workspace_id, entity_id),\\n CHECK(first_observed_at <= last_observed_at),\\n CHECK(last_observed_at <= synchronized_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"evidence_claims\",\n \"sql\": \"CREATE TABLE evidence_claims (\\n workspace_id TEXT NOT NULL,\\n evidence_claim_id TEXT NOT NULL,\\n evidence_id TEXT NOT NULL,\\n subject_node_id TEXT NOT NULL,\\n predicate TEXT NOT NULL CHECK(predicate IN (\\n 'relationship-observed', 'status-observed', 'approval-recorded',\\n 'check-observed', 'execution-observed', 'deployment-observed',\\n 'documentation-observed', 'time-observed'\\n )),\\n value_schema_version INTEGER NOT NULL CHECK(value_schema_version >= 1),\\n value_json TEXT NOT NULL CHECK(length(value_json) BETWEEN 2 AND 8192),\\n value_digest TEXT NOT NULL CHECK(\\n length(value_digest) = 64 AND\\n value_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n supersedes_claim_id TEXT,\\n recorded_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, evidence_claim_id),\\n FOREIGN KEY (workspace_id, evidence_id)\\n REFERENCES evidence_items(workspace_id, evidence_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, subject_node_id)\\n REFERENCES delivery_nodes(workspace_id, node_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, supersedes_claim_id)\\n REFERENCES evidence_claims(workspace_id, evidence_claim_id)\\n ON DELETE RESTRICT,\\n CHECK(evidence_claim_id <> supersedes_claim_id)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"evidence_items\",\n \"sql\": \"CREATE TABLE evidence_items (\\n workspace_id TEXT NOT NULL,\\n evidence_id TEXT NOT NULL,\\n schema_version INTEGER NOT NULL CHECK(schema_version >= 1),\\n evidence_digest TEXT NOT NULL CHECK(\\n length(evidence_digest) = 64 AND\\n evidence_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n origin_kind TEXT NOT NULL CHECK(origin_kind IN ('plugin', 'human', 'agent', 'system')),\\n plugin_connection_id TEXT,\\n source_entity_id TEXT,\\n source_entity_revision INTEGER,\\n person_id TEXT,\\n agent_id TEXT,\\n system_component TEXT CHECK(\\n system_component IS NULL OR length(system_component) BETWEEN 1 AND 200\\n ),\\n verifier_kind TEXT NOT NULL CHECK(verifier_kind IN ('human', 'agent', 'system')),\\n verifier_person_id TEXT,\\n verifier_agent_id TEXT,\\n verifier_component TEXT CHECK(\\n verifier_component IS NULL OR length(verifier_component) BETWEEN 1 AND 200\\n ),\\n observed_at TEXT NOT NULL,\\n recorded_at TEXT NOT NULL,\\n valid_until TEXT,\\n freshness_json TEXT NOT NULL CHECK(length(freshness_json) BETWEEN 2 AND 65536),\\n freshness_digest TEXT NOT NULL CHECK(\\n length(freshness_digest) = 64 AND\\n freshness_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n retention_class TEXT NOT NULL CHECK(\\n retention_class IN ('audit', 'evidence', 'normalized-cache')\\n ),\\n retain_until TEXT,\\n legal_hold INTEGER NOT NULL CHECK(legal_hold IN (0, 1)),\\n PRIMARY KEY (workspace_id, evidence_id),\\n UNIQUE (workspace_id, evidence_digest),\\n FOREIGN KEY (workspace_id) REFERENCES workspaces(workspace_id),\\n FOREIGN KEY (workspace_id, plugin_connection_id)\\n REFERENCES plugin_connections(workspace_id, plugin_connection_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, source_entity_id, source_entity_revision)\\n REFERENCES entity_revisions(workspace_id, entity_id, revision)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, person_id)\\n REFERENCES persons(workspace_id, person_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, verifier_person_id)\\n REFERENCES persons(workspace_id, person_id)\\n ON DELETE RESTRICT,\\n CHECK(observed_at <= recorded_at),\\n CHECK(valid_until IS NULL OR observed_at < valid_until),\\n CHECK(retain_until IS NULL OR recorded_at <= retain_until),\\n CHECK(\\n (origin_kind = 'plugin' AND plugin_connection_id IS NOT NULL AND\\n source_entity_id IS NOT NULL AND source_entity_revision IS NOT NULL AND\\n person_id IS NULL AND agent_id IS NULL AND system_component IS NULL) OR\\n (origin_kind = 'human' AND plugin_connection_id IS NULL AND\\n source_entity_id IS NULL AND source_entity_revision IS NULL AND\\n person_id IS NOT NULL AND agent_id IS NULL AND system_component IS NULL) OR\\n (origin_kind = 'agent' AND plugin_connection_id IS NULL AND\\n source_entity_id IS NULL AND source_entity_revision IS NULL AND\\n person_id IS NULL AND agent_id IS NOT NULL AND system_component IS NULL) OR\\n (origin_kind = 'system' AND plugin_connection_id IS NULL AND\\n source_entity_id IS NULL AND source_entity_revision IS NULL AND\\n person_id IS NULL AND agent_id IS NULL AND system_component IS NOT NULL)\\n ),\\n CHECK(\\n (verifier_kind = 'human' AND verifier_person_id IS NOT NULL AND\\n verifier_agent_id IS NULL AND verifier_component IS NULL) OR\\n (verifier_kind = 'agent' AND verifier_person_id IS NULL AND\\n verifier_agent_id IS NOT NULL AND verifier_component IS NULL) OR\\n (verifier_kind = 'system' AND verifier_person_id IS NULL AND\\n verifier_agent_id IS NULL AND verifier_component IS NOT NULL)\\n )\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"followed_resources\",\n \"sql\": \"CREATE TABLE followed_resources (\\n workspace_id TEXT NOT NULL,\\n followed_resource_id TEXT NOT NULL,\\n provider_account_id TEXT NOT NULL,\\n provider_family TEXT NOT NULL CHECK(provider_family IN (\\n 'aws', 'atlassian', 'clockify'\\n )),\\n provider_id TEXT NOT NULL CHECK(provider_id IN (\\n 'codecommit', 'codepipeline', 'jira', 'confluence', 'clockify'\\n )),\\n vendor_resource_id TEXT NOT NULL CHECK(length(vendor_resource_id) BETWEEN 1 AND 512),\\n display_name TEXT NOT NULL CHECK(length(display_name) BETWEEN 1 AND 200),\\n revision INTEGER NOT NULL DEFAULT 1 CHECK(revision >= 1),\\n is_enabled INTEGER NOT NULL DEFAULT 1 CHECK(is_enabled IN (0, 1)),\\n created_at TEXT NOT NULL,\\n updated_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, followed_resource_id),\\n UNIQUE (workspace_id, followed_resource_id, provider_account_id, provider_id),\\n UNIQUE (workspace_id, provider_account_id, provider_id, vendor_resource_id),\\n FOREIGN KEY (workspace_id, provider_account_id, provider_family)\\n REFERENCES provider_accounts(workspace_id, provider_account_id, provider_family),\\n CHECK(created_at <= updated_at),\\n CHECK(\\n (provider_family = 'aws' AND provider_id IN ('codecommit', 'codepipeline')) OR\\n (provider_family = 'atlassian' AND provider_id IN ('jira', 'confluence')) OR\\n (provider_family = 'clockify' AND provider_id = 'clockify')\\n )\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"governed_action_attempts\",\n \"sql\": \"CREATE TABLE governed_action_attempts (\\n workspace_id TEXT NOT NULL,\\n action_id TEXT NOT NULL,\\n attempt_id TEXT NOT NULL,\\n authorization_id TEXT NOT NULL,\\n policy_evaluation_digest TEXT NOT NULL,\\n attempt_digest TEXT NOT NULL CHECK(\\n length(attempt_digest) = 71 AND attempt_digest GLOB 'sha256:*'\\n AND substr(attempt_digest, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n attempt_number INTEGER NOT NULL CHECK(attempt_number = 1),\\n attempt_json TEXT NOT NULL CHECK(length(attempt_json) BETWEEN 2 AND 262144),\\n started_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, attempt_id),\\n UNIQUE (workspace_id, action_id),\\n UNIQUE (workspace_id, action_id, attempt_id),\\n UNIQUE (workspace_id, authorization_id),\\n FOREIGN KEY (workspace_id, action_id)\\n REFERENCES governed_actions(workspace_id, action_id),\\n FOREIGN KEY (workspace_id, action_id, authorization_id)\\n REFERENCES governed_action_authorizations(workspace_id, action_id, authorization_id),\\n FOREIGN KEY (workspace_id, action_id, policy_evaluation_digest)\\n REFERENCES governed_action_policy_evaluations(workspace_id, action_id, evaluation_digest)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"governed_action_authorizations\",\n \"sql\": \"CREATE TABLE governed_action_authorizations (\\n workspace_id TEXT NOT NULL,\\n action_id TEXT NOT NULL,\\n authorization_id TEXT NOT NULL,\\n session_id TEXT NOT NULL,\\n envelope_digest TEXT NOT NULL,\\n authorization_digest TEXT NOT NULL CHECK(\\n length(authorization_digest) = 71 AND authorization_digest GLOB 'sha256:*'\\n AND substr(authorization_digest, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n authorization_json TEXT NOT NULL CHECK(length(authorization_json) BETWEEN 2 AND 262144),\\n authorized_at TEXT NOT NULL,\\n expires_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, authorization_id),\\n UNIQUE (workspace_id, action_id),\\n UNIQUE (workspace_id, action_id, authorization_id),\\n FOREIGN KEY (workspace_id, action_id, envelope_digest)\\n REFERENCES governed_actions(workspace_id, action_id, envelope_digest),\\n FOREIGN KEY (workspace_id, session_id)\\n REFERENCES sessions(workspace_id, session_id),\\n CHECK(authorized_at < expires_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"governed_action_denial_policy_evaluations\",\n \"sql\": \"CREATE TABLE governed_action_denial_policy_evaluations (\\n workspace_id TEXT NOT NULL,\\n action_id TEXT NOT NULL,\\n transition_id TEXT NOT NULL,\\n policy_evaluation_digest TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, action_id, transition_id),\\n UNIQUE (workspace_id, action_id, policy_evaluation_digest),\\n FOREIGN KEY (workspace_id, action_id, transition_id)\\n REFERENCES governed_action_transitions(workspace_id, action_id, transition_id),\\n FOREIGN KEY (workspace_id, action_id, policy_evaluation_digest)\\n REFERENCES governed_action_policy_evaluations(workspace_id, action_id, evaluation_digest)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"governed_action_entity_targets\",\n \"sql\": \"CREATE TABLE governed_action_entity_targets (\\n workspace_id TEXT NOT NULL,\\n action_id TEXT NOT NULL,\\n plugin_connection_id TEXT NOT NULL,\\n provider_id TEXT NOT NULL CHECK(provider_id IN (\\n 'codecommit', 'codepipeline', 'jira', 'confluence', 'clockify'\\n )),\\n entity_id TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, action_id),\\n FOREIGN KEY (workspace_id, action_id)\\n REFERENCES governed_actions(workspace_id, action_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, entity_id, plugin_connection_id, provider_id)\\n REFERENCES entities(workspace_id, entity_id, plugin_connection_id, provider_id)\\n ON DELETE RESTRICT\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"governed_action_execution_leases\",\n \"sql\": \"CREATE TABLE governed_action_execution_leases (\\n workspace_id TEXT NOT NULL,\\n action_id TEXT NOT NULL,\\n attempt_id TEXT NOT NULL,\\n start_transition_id TEXT NOT NULL,\\n permit_token_digest TEXT NOT NULL CHECK(\\n length(permit_token_digest) = 64 AND permit_token_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n runtime_authority_token TEXT NOT NULL CHECK(length(runtime_authority_token) BETWEEN 1 AND 512),\\n recovery_capability_version INTEGER NOT NULL CHECK(recovery_capability_version = 1),\\n created_at TEXT NOT NULL,\\n dispatch_deadline TEXT NOT NULL,\\n lease_expires_at TEXT NOT NULL,\\n recovery_eligible_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, action_id),\\n UNIQUE (workspace_id, action_id, attempt_id),\\n UNIQUE (permit_token_digest),\\n UNIQUE (workspace_id, action_id, permit_token_digest),\\n FOREIGN KEY (workspace_id, action_id, attempt_id)\\n REFERENCES governed_action_attempts(workspace_id, action_id, attempt_id),\\n FOREIGN KEY (workspace_id, action_id, start_transition_id)\\n REFERENCES governed_action_transitions(workspace_id, action_id, transition_id),\\n CHECK(created_at <= dispatch_deadline),\\n CHECK(dispatch_deadline < lease_expires_at),\\n CHECK(lease_expires_at < recovery_eligible_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"governed_action_execution_preparations\",\n \"sql\": \"CREATE TABLE governed_action_execution_preparations (\\n preparation_token_digest TEXT PRIMARY KEY CHECK(\\n length(preparation_token_digest) = 64\\n AND preparation_token_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n workspace_id TEXT NOT NULL,\\n action_id TEXT NOT NULL,\\n expected_head_transition_id TEXT NOT NULL,\\n expected_envelope_digest TEXT NOT NULL,\\n created_at TEXT NOT NULL,\\n expires_at TEXT NOT NULL,\\n UNIQUE (workspace_id, action_id, preparation_token_digest),\\n FOREIGN KEY (workspace_id, action_id, expected_head_transition_id)\\n REFERENCES governed_action_transitions(workspace_id, action_id, transition_id),\\n FOREIGN KEY (workspace_id, action_id, expected_envelope_digest)\\n REFERENCES governed_actions(workspace_id, action_id, envelope_digest),\\n CHECK(created_at < expires_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"governed_action_legacy_recovery_unavailable_outcomes\",\n \"sql\": \"CREATE TABLE governed_action_legacy_recovery_unavailable_outcomes (\\n workspace_id TEXT NOT NULL,\\n action_id TEXT NOT NULL,\\n outcome_id TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, action_id, outcome_id),\\n FOREIGN KEY (workspace_id, action_id, outcome_id)\\n REFERENCES governed_action_provider_outcomes(workspace_id, action_id, outcome_id)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"governed_action_policy_evaluations\",\n \"sql\": \"CREATE TABLE governed_action_policy_evaluations (\\n workspace_id TEXT NOT NULL,\\n action_id TEXT NOT NULL,\\n evaluation_digest TEXT NOT NULL CHECK(\\n length(evaluation_digest) = 71 AND evaluation_digest GLOB 'sha256:*'\\n AND substr(evaluation_digest, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n evaluation_json TEXT NOT NULL CHECK(length(evaluation_json) BETWEEN 2 AND 262144),\\n decision TEXT NOT NULL CHECK(decision IN ('allowed', 'denied')),\\n evaluated_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, action_id, evaluation_digest),\\n FOREIGN KEY (workspace_id, action_id)\\n REFERENCES governed_actions(workspace_id, action_id)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"governed_action_provider_outcome_folds\",\n \"sql\": \"CREATE TABLE governed_action_provider_outcome_folds (\\n workspace_id TEXT NOT NULL,\\n action_id TEXT NOT NULL,\\n outcome_id TEXT NOT NULL,\\n transition_id TEXT NOT NULL,\\n folded_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, action_id, outcome_id),\\n UNIQUE (workspace_id, action_id, transition_id),\\n FOREIGN KEY (workspace_id, action_id, outcome_id)\\n REFERENCES governed_action_provider_outcomes(workspace_id, action_id, outcome_id),\\n FOREIGN KEY (workspace_id, action_id, transition_id)\\n REFERENCES governed_action_transitions(workspace_id, action_id, transition_id)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"governed_action_provider_outcomes\",\n \"sql\": \"CREATE TABLE governed_action_provider_outcomes (\\n workspace_id TEXT NOT NULL,\\n action_id TEXT NOT NULL,\\n outcome_id TEXT NOT NULL,\\n source_kind TEXT NOT NULL CHECK(source_kind IN ('dispatch', 'reconciliation')),\\n permit_token_digest TEXT,\\n recovery_claim_token_digest TEXT,\\n result_kind TEXT NOT NULL CHECK(result_kind IN (\\n 'accepted', 'succeeded', 'failed', 'cancelled', 'unknown', 'manual-unknown',\\n 'pending', 'recovery-unavailable'\\n )),\\n schema_version INTEGER NOT NULL CHECK(schema_version = 1),\\n outcome_json TEXT NOT NULL CHECK(length(outcome_json) BETWEEN 2 AND 262144),\\n outcome_digest TEXT NOT NULL CHECK(\\n length(outcome_digest) = 64 AND outcome_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n expected_command_digest TEXT NOT NULL CHECK(\\n length(expected_command_digest) = 71\\n AND expected_command_digest GLOB 'sha256:*'\\n AND substr(expected_command_digest, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n observed_at TEXT NOT NULL,\\n received_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, action_id, outcome_id),\\n UNIQUE (permit_token_digest),\\n UNIQUE (recovery_claim_token_digest),\\n FOREIGN KEY (workspace_id, action_id)\\n REFERENCES governed_actions(workspace_id, action_id),\\n FOREIGN KEY (workspace_id, action_id, permit_token_digest)\\n REFERENCES governed_action_execution_leases(workspace_id, action_id, permit_token_digest),\\n FOREIGN KEY (workspace_id, action_id, recovery_claim_token_digest)\\n REFERENCES governed_action_recovery_claims(workspace_id, action_id, claim_token_digest),\\n CHECK(observed_at <= received_at),\\n CHECK(\\n (source_kind = 'dispatch' AND permit_token_digest IS NOT NULL\\n AND recovery_claim_token_digest IS NULL\\n AND result_kind IN (\\n 'accepted', 'succeeded', 'failed', 'cancelled', 'unknown', 'manual-unknown'\\n )) OR\\n (source_kind = 'reconciliation' AND permit_token_digest IS NULL\\n AND recovery_claim_token_digest IS NOT NULL\\n AND result_kind IN (\\n 'pending', 'succeeded', 'failed', 'cancelled', 'recovery-unavailable'\\n ))\\n )\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"governed_action_recovery_claim_expirations\",\n \"sql\": \"CREATE TABLE governed_action_recovery_claim_expirations (\\n workspace_id TEXT NOT NULL,\\n action_id TEXT NOT NULL,\\n claim_sequence INTEGER NOT NULL CHECK(claim_sequence >= 1),\\n expired_at TEXT NOT NULL,\\n reason TEXT NOT NULL CHECK(reason = 'shutdown'),\\n PRIMARY KEY (workspace_id, action_id, claim_sequence),\\n FOREIGN KEY (workspace_id, action_id, claim_sequence)\\n REFERENCES governed_action_recovery_claims(workspace_id, action_id, claim_sequence)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"governed_action_recovery_claims\",\n \"sql\": \"CREATE TABLE governed_action_recovery_claims (\\n workspace_id TEXT NOT NULL,\\n action_id TEXT NOT NULL,\\n claim_sequence INTEGER NOT NULL CHECK(claim_sequence >= 1),\\n claim_token_digest TEXT NOT NULL CHECK(\\n length(claim_token_digest) = 64 AND claim_token_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n claimed_at TEXT NOT NULL,\\n lease_expires_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, action_id, claim_sequence),\\n UNIQUE (claim_token_digest),\\n UNIQUE (workspace_id, action_id, claim_token_digest),\\n FOREIGN KEY (workspace_id, action_id)\\n REFERENCES governed_action_execution_leases(workspace_id, action_id),\\n CHECK(claimed_at < lease_expires_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"governed_action_release_publication_slots\",\n \"sql\": \"CREATE TABLE governed_action_release_publication_slots (\\n workspace_id TEXT NOT NULL,\\n action_id TEXT NOT NULL,\\n provider_id TEXT NOT NULL CHECK(provider_id = 'confluence'),\\n release_id TEXT NOT NULL CHECK(length(release_id) = 36),\\n predecessor_action_id TEXT CHECK(\\n predecessor_action_id IS NULL OR length(predecessor_action_id) = 36\\n ),\\n PRIMARY KEY (workspace_id, action_id),\\n FOREIGN KEY (workspace_id, action_id)\\n REFERENCES governed_action_release_publications(workspace_id, action_id)\\n ON DELETE RESTRICT\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"governed_action_release_publications\",\n \"sql\": \"CREATE TABLE governed_action_release_publications (\\n workspace_id TEXT NOT NULL,\\n action_id TEXT NOT NULL,\\n provider_id TEXT NOT NULL CHECK(provider_id IN (\\n 'codecommit', 'codepipeline', 'jira', 'confluence', 'clockify'\\n )),\\n release_id TEXT NOT NULL CHECK(length(release_id) = 36),\\n predecessor_action_id TEXT CHECK(\\n predecessor_action_id IS NULL OR length(predecessor_action_id) = 36\\n ),\\n PRIMARY KEY (workspace_id, action_id),\\n FOREIGN KEY (workspace_id, action_id)\\n REFERENCES governed_actions(workspace_id, action_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, release_id)\\n REFERENCES releases(workspace_id, release_id)\\n ON DELETE RESTRICT\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"governed_action_target_dimensions\",\n \"sql\": \"CREATE TABLE governed_action_target_dimensions (\\n workspace_id TEXT NOT NULL,\\n action_id TEXT NOT NULL,\\n action_kind TEXT NOT NULL CHECK(length(action_kind) BETWEEN 1 AND 100),\\n expected_revision TEXT NOT NULL CHECK(length(expected_revision) BETWEEN 1 AND 512),\\n PRIMARY KEY (workspace_id, action_id),\\n FOREIGN KEY (workspace_id, action_id)\\n REFERENCES governed_actions(workspace_id, action_id)\\n ON DELETE RESTRICT\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"governed_action_transitions\",\n \"sql\": \"CREATE TABLE governed_action_transitions (\\n workspace_id TEXT NOT NULL,\\n action_id TEXT NOT NULL,\\n transition_id TEXT NOT NULL,\\n previous_transition_id TEXT,\\n sequence INTEGER NOT NULL CHECK(sequence >= 1),\\n command_id TEXT NOT NULL CHECK(length(command_id) BETWEEN 1 AND 512),\\n command_tag TEXT NOT NULL CHECK(command_tag IN (\\n 'propose', 'authorize', 'deny', 'expire', 'cancel', 'start',\\n 'requestCancellation', 'recordAccepted', 'recordSucceeded', 'recordFailed',\\n 'recordUnknown', 'recordCancelled', 'reconciliationPending'\\n )),\\n authorization_id TEXT,\\n attempt_id TEXT,\\n outcome_source_kind TEXT CHECK(\\n outcome_source_kind IS NULL OR outcome_source_kind IN (\\n 'direct', 'providerOperation', 'reconciliation'\\n )\\n ),\\n command_provider_operation_id TEXT CHECK(\\n command_provider_operation_id IS NULL OR length(command_provider_operation_id) BETWEEN 1 AND 512\\n ),\\n command_reconciliation_key TEXT CHECK(\\n command_reconciliation_key IS NULL OR length(command_reconciliation_key) BETWEEN 1 AND 512\\n ),\\n command_terminal_status TEXT CHECK(\\n command_terminal_status IS NULL OR command_terminal_status IN ('succeeded', 'failed', 'cancelled')\\n ),\\n command_unknown_kind TEXT CHECK(\\n command_unknown_kind IS NULL OR command_unknown_kind IN ('reconcilable', 'manual')\\n ),\\n command_digest TEXT NOT NULL CHECK(\\n length(command_digest) = 71 AND command_digest GLOB 'sha256:*'\\n AND substr(command_digest, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n transition_digest TEXT NOT NULL CHECK(\\n length(transition_digest) = 71 AND transition_digest GLOB 'sha256:*'\\n AND substr(transition_digest, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n envelope_digest TEXT NOT NULL,\\n from_state TEXT CHECK(from_state IS NULL OR from_state IN (\\n 'proposed', 'authorized', 'denied', 'expired', 'cancelled', 'started',\\n 'cancel-requested', 'cancel-requested-unknown', 'succeeded', 'failed', 'unknown'\\n )),\\n to_state TEXT NOT NULL CHECK(to_state IN (\\n 'proposed', 'authorized', 'denied', 'expired', 'cancelled', 'started',\\n 'cancel-requested', 'cancel-requested-unknown', 'succeeded', 'failed', 'unknown'\\n )),\\n result_lineage_json TEXT NOT NULL CHECK(length(result_lineage_json) BETWEEN 2 AND 65536),\\n result_lineage_kind TEXT NOT NULL CHECK(result_lineage_kind IN (\\n 'none', 'accepted', 'reconcilable', 'manual', 'terminal'\\n )),\\n result_provider_operation_id TEXT CHECK(\\n result_provider_operation_id IS NULL OR length(result_provider_operation_id) BETWEEN 1 AND 512\\n ),\\n result_reconciliation_key TEXT CHECK(\\n result_reconciliation_key IS NULL OR length(result_reconciliation_key) BETWEEN 1 AND 512\\n ),\\n result_terminal_status TEXT CHECK(\\n result_terminal_status IS NULL OR result_terminal_status IN ('succeeded', 'failed', 'cancelled')\\n ),\\n cause_kind TEXT NOT NULL CHECK(cause_kind IN ('human', 'agent', 'system')),\\n cause_actor_id TEXT CHECK(cause_actor_id IS NULL OR length(cause_actor_id) BETWEEN 1 AND 512),\\n cause_session_id TEXT,\\n cause_job_id TEXT CHECK(cause_job_id IS NULL OR length(cause_job_id) BETWEEN 1 AND 512),\\n cause_system_component TEXT CHECK(\\n cause_system_component IS NULL OR length(cause_system_component) BETWEEN 1 AND 200\\n ),\\n causation_id TEXT,\\n correlation_id TEXT CHECK(\\n correlation_id IS NULL OR length(correlation_id) BETWEEN 1 AND 128\\n ),\\n transition_json TEXT NOT NULL CHECK(length(transition_json) BETWEEN 2 AND 262144),\\n occurred_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, transition_id),\\n UNIQUE (workspace_id, action_id, transition_id),\\n UNIQUE (workspace_id, action_id, sequence),\\n UNIQUE (workspace_id, action_id, command_id),\\n FOREIGN KEY (workspace_id, action_id, envelope_digest)\\n REFERENCES governed_actions(workspace_id, action_id, envelope_digest),\\n FOREIGN KEY (workspace_id, action_id, previous_transition_id)\\n REFERENCES governed_action_transitions(workspace_id, action_id, transition_id),\\n FOREIGN KEY (workspace_id, action_id, authorization_id)\\n REFERENCES governed_action_authorizations(workspace_id, action_id, authorization_id),\\n FOREIGN KEY (workspace_id, action_id, attempt_id)\\n REFERENCES governed_action_attempts(workspace_id, action_id, attempt_id),\\n FOREIGN KEY (workspace_id, cause_session_id)\\n REFERENCES sessions(workspace_id, session_id),\\n CHECK(\\n (sequence = 1 AND previous_transition_id IS NULL AND from_state IS NULL) OR\\n (sequence > 1 AND previous_transition_id IS NOT NULL AND from_state IS NOT NULL)\\n ),\\n CHECK(\\n (command_tag = 'authorize' AND authorization_id IS NOT NULL AND attempt_id IS NULL) OR\\n (command_tag = 'start' AND authorization_id IS NULL AND attempt_id IS NOT NULL) OR\\n (command_tag NOT IN ('authorize', 'start') AND authorization_id IS NULL AND attempt_id IS NULL)\\n ),\\n CHECK(COALESCE((\\n (command_tag IN (\\n 'propose', 'authorize', 'deny', 'expire', 'cancel', 'start', 'requestCancellation'\\n ) AND outcome_source_kind IS NULL AND command_provider_operation_id IS NULL\\n AND command_reconciliation_key IS NULL AND command_terminal_status IS NULL\\n AND command_unknown_kind IS NULL) OR\\n (command_tag = 'recordAccepted' AND outcome_source_kind IS NULL\\n AND command_provider_operation_id IS NOT NULL AND command_reconciliation_key IS NOT NULL\\n AND command_terminal_status IS NULL AND command_unknown_kind IS NULL) OR\\n (command_tag = 'recordUnknown' AND outcome_source_kind IS NULL\\n AND command_provider_operation_id IS NULL AND command_terminal_status IS NULL\\n AND command_unknown_kind IS NOT NULL AND (\\n (command_unknown_kind = 'reconcilable' AND command_reconciliation_key IS NOT NULL) OR\\n (command_unknown_kind = 'manual' AND command_reconciliation_key IS NULL)\\n )) OR\\n (command_tag = 'reconciliationPending' AND outcome_source_kind IS NULL\\n AND command_provider_operation_id IS NULL AND command_reconciliation_key IS NOT NULL\\n AND command_terminal_status IS NULL AND command_unknown_kind IS NULL) OR\\n (command_tag IN ('recordSucceeded', 'recordFailed', 'recordCancelled')\\n AND outcome_source_kind IS NOT NULL AND command_provider_operation_id IS NOT NULL\\n AND command_terminal_status = CASE command_tag\\n WHEN 'recordSucceeded' THEN 'succeeded'\\n WHEN 'recordFailed' THEN 'failed'\\n ELSE 'cancelled'\\n END\\n AND command_unknown_kind IS NULL\\n AND (\\n (outcome_source_kind IN ('direct', 'providerOperation')\\n AND command_reconciliation_key IS NULL) OR\\n (outcome_source_kind = 'reconciliation' AND command_reconciliation_key IS NOT NULL)\\n ))\\n ), 0)),\\n CHECK(\\n (cause_kind = 'human' AND cause_actor_id IS NOT NULL AND cause_session_id IS NOT NULL\\n AND cause_job_id IS NULL AND cause_system_component IS NULL) OR\\n (cause_kind = 'agent' AND cause_actor_id IS NOT NULL AND cause_session_id IS NULL\\n AND cause_job_id IS NOT NULL AND cause_system_component IS NULL) OR\\n (cause_kind = 'system' AND cause_actor_id IS NULL AND cause_session_id IS NULL\\n AND cause_job_id IS NULL AND cause_system_component IS NOT NULL)\\n ),\\n CHECK(COALESCE((\\n (cause_kind = 'agent' AND command_tag = 'propose') OR\\n (cause_kind = 'human' AND command_tag IN (\\n 'propose', 'authorize', 'deny', 'cancel', 'requestCancellation'\\n )) OR\\n (cause_kind = 'system' AND command_tag IN (\\n 'deny', 'expire', 'cancel', 'start', 'requestCancellation', 'recordAccepted',\\n 'recordSucceeded', 'recordFailed', 'recordUnknown', 'recordCancelled',\\n 'reconciliationPending'\\n ))\\n ), 0)),\\n CHECK(\\n causation_id IS NULL OR length(causation_id) BETWEEN 1 AND 512\\n ),\\n CHECK(COALESCE((\\n (command_tag = 'propose' AND from_state IS NULL AND to_state = 'proposed') OR\\n (command_tag = 'authorize' AND from_state = 'proposed' AND to_state = 'authorized') OR\\n (command_tag = 'deny' AND from_state IN ('proposed', 'authorized') AND to_state = 'denied') OR\\n (command_tag = 'expire' AND from_state IN ('proposed', 'authorized') AND to_state = 'expired') OR\\n (command_tag = 'cancel' AND from_state IN ('proposed', 'authorized') AND to_state = 'cancelled') OR\\n (command_tag = 'start' AND from_state = 'authorized' AND to_state = 'started') OR\\n (command_tag = 'requestCancellation' AND (\\n (from_state = 'started' AND to_state = 'cancel-requested') OR\\n (from_state = 'unknown' AND to_state = 'cancel-requested-unknown')\\n )) OR\\n (command_tag = 'recordAccepted' AND from_state = to_state\\n AND from_state IN ('started', 'cancel-requested')) OR\\n (command_tag = 'recordUnknown' AND (\\n (from_state = 'started' AND to_state = 'unknown') OR\\n (from_state = 'cancel-requested' AND to_state = 'cancel-requested-unknown')\\n )) OR\\n (command_tag IN ('recordSucceeded', 'recordFailed', 'recordCancelled')\\n AND to_state = CASE command_tag\\n WHEN 'recordSucceeded' THEN 'succeeded'\\n WHEN 'recordFailed' THEN 'failed'\\n ELSE 'cancelled'\\n END\\n AND (\\n from_state IN ('started', 'cancel-requested') OR\\n (from_state IN ('unknown', 'cancel-requested-unknown')\\n AND outcome_source_kind = 'reconciliation')\\n )) OR\\n (command_tag = 'reconciliationPending' AND from_state = to_state\\n AND from_state IN ('started', 'cancel-requested', 'unknown', 'cancel-requested-unknown'))\\n ), 0)),\\n CHECK(\\n (result_lineage_kind = 'none' AND result_provider_operation_id IS NULL\\n AND result_reconciliation_key IS NULL AND result_terminal_status IS NULL) OR\\n (result_lineage_kind = 'accepted' AND result_provider_operation_id IS NOT NULL\\n AND result_reconciliation_key IS NOT NULL AND result_terminal_status IS NULL) OR\\n (result_lineage_kind = 'reconcilable' AND result_reconciliation_key IS NOT NULL\\n AND result_terminal_status IS NULL) OR\\n (result_lineage_kind = 'manual' AND result_reconciliation_key IS NULL\\n AND result_terminal_status IS NULL) OR\\n (result_lineage_kind = 'terminal' AND result_provider_operation_id IS NOT NULL\\n AND result_reconciliation_key IS NULL AND result_terminal_status IS NOT NULL)\\n ),\\n CHECK(\\n (to_state IN ('proposed', 'authorized', 'denied', 'expired') AND result_lineage_kind = 'none') OR\\n (to_state = 'cancelled' AND (\\n result_lineage_kind = 'none' OR\\n (result_lineage_kind = 'terminal' AND result_terminal_status = 'cancelled')\\n )) OR\\n (to_state IN ('started', 'cancel-requested') AND result_lineage_kind IN ('none', 'accepted')) OR\\n (to_state IN ('unknown', 'cancel-requested-unknown')\\n AND result_lineage_kind IN ('reconcilable', 'manual')) OR\\n (to_state = 'succeeded' AND result_lineage_kind = 'terminal'\\n AND result_terminal_status = 'succeeded') OR\\n (to_state = 'failed' AND result_lineage_kind = 'terminal'\\n AND result_terminal_status = 'failed')\\n )\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"governed_actions\",\n \"sql\": \"CREATE TABLE governed_actions (\\n workspace_id TEXT NOT NULL,\\n action_id TEXT NOT NULL,\\n plugin_connection_id TEXT NOT NULL,\\n provider_id TEXT NOT NULL CHECK(provider_id IN (\\n 'codecommit', 'codepipeline', 'jira', 'confluence', 'clockify'\\n )),\\n target_entity_id TEXT NOT NULL,\\n idempotency_key TEXT NOT NULL CHECK(length(idempotency_key) BETWEEN 1 AND 512),\\n envelope_digest TEXT NOT NULL CHECK(\\n length(envelope_digest) = 71 AND envelope_digest GLOB 'sha256:*'\\n AND substr(envelope_digest, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n envelope_json TEXT NOT NULL CHECK(length(envelope_json) BETWEEN 2 AND 1048576),\\n state TEXT CHECK(state IN (\\n 'proposed', 'authorized', 'denied', 'expired', 'cancelled', 'started',\\n 'cancel-requested', 'cancel-requested-unknown', 'succeeded', 'failed', 'unknown'\\n )),\\n lineage_json TEXT CHECK(lineage_json IS NULL OR length(lineage_json) BETWEEN 2 AND 65536),\\n lineage_kind TEXT CHECK(lineage_kind IS NULL OR lineage_kind IN (\\n 'none', 'accepted', 'reconcilable', 'manual', 'terminal'\\n )),\\n provider_operation_id TEXT CHECK(\\n provider_operation_id IS NULL OR length(provider_operation_id) BETWEEN 1 AND 512\\n ),\\n reconciliation_key TEXT CHECK(\\n reconciliation_key IS NULL OR length(reconciliation_key) BETWEEN 1 AND 512\\n ),\\n terminal_status TEXT CHECK(\\n terminal_status IS NULL OR terminal_status IN ('succeeded', 'failed', 'cancelled')\\n ),\\n head_transition_id TEXT,\\n head_sequence INTEGER CHECK(head_sequence IS NULL OR head_sequence >= 1),\\n created_at TEXT NOT NULL,\\n updated_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, action_id),\\n UNIQUE (workspace_id, plugin_connection_id, idempotency_key),\\n UNIQUE (workspace_id, action_id, envelope_digest),\\n FOREIGN KEY (workspace_id) REFERENCES workspaces(workspace_id),\\n FOREIGN KEY (workspace_id, plugin_connection_id, provider_id)\\n REFERENCES plugin_connections(workspace_id, plugin_connection_id, provider_id),\\n CHECK(created_at <= updated_at),\\n CHECK(\\n (state IS NULL AND lineage_json IS NULL AND lineage_kind IS NULL\\n AND provider_operation_id IS NULL AND reconciliation_key IS NULL AND terminal_status IS NULL\\n AND head_transition_id IS NULL AND head_sequence IS NULL) OR\\n (state IS NOT NULL AND lineage_json IS NOT NULL AND lineage_kind IS NOT NULL\\n AND head_transition_id IS NOT NULL AND head_sequence IS NOT NULL)\\n ),\\n CHECK(\\n lineage_kind IS NULL OR\\n (lineage_kind = 'none' AND provider_operation_id IS NULL\\n AND reconciliation_key IS NULL AND terminal_status IS NULL) OR\\n (lineage_kind = 'accepted' AND provider_operation_id IS NOT NULL\\n AND reconciliation_key IS NOT NULL AND terminal_status IS NULL) OR\\n (lineage_kind = 'reconcilable' AND reconciliation_key IS NOT NULL\\n AND terminal_status IS NULL) OR\\n (lineage_kind = 'manual' AND reconciliation_key IS NULL AND terminal_status IS NULL) OR\\n (lineage_kind = 'terminal' AND provider_operation_id IS NOT NULL\\n AND reconciliation_key IS NULL AND terminal_status IS NOT NULL)\\n ),\\n CHECK(\\n state IS NULL OR\\n (state IN ('proposed', 'authorized', 'denied', 'expired') AND lineage_kind = 'none') OR\\n (state = 'cancelled' AND (\\n lineage_kind = 'none' OR (lineage_kind = 'terminal' AND terminal_status = 'cancelled')\\n )) OR\\n (state IN ('started', 'cancel-requested') AND lineage_kind IN ('none', 'accepted')) OR\\n (state IN ('unknown', 'cancel-requested-unknown')\\n AND lineage_kind IN ('reconcilable', 'manual')) OR\\n (state = 'succeeded' AND lineage_kind = 'terminal' AND terminal_status = 'succeeded') OR\\n (state = 'failed' AND lineage_kind = 'terminal' AND terminal_status = 'failed')\\n )\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"pairing_codes\",\n \"sql\": \"CREATE TABLE pairing_codes (\\n workspace_id TEXT NOT NULL,\\n pairing_code_id TEXT NOT NULL,\\n code_hash TEXT NOT NULL UNIQUE CHECK(\\n length(code_hash) = 64 AND code_hash NOT GLOB '*[^0-9a-f]*'\\n ),\\n purpose TEXT NOT NULL CHECK(purpose IN ('first-run', 'device', 'recovery')),\\n actor_kind TEXT NOT NULL CHECK(actor_kind IN ('human', 'agent')),\\n person_id TEXT,\\n agent_id TEXT,\\n permission TEXT NOT NULL CHECK(permission IN (\\n 'workspace-owner', 'workspace-approver', 'release-owner', 'release-approver',\\n 'change-owner', 'issue-owner', 'issue-assignee', 'page-owner', 'author',\\n 'contributor', 'reviewer', 'operator', 'deployment-approver', 'merge-approver',\\n 'watcher'\\n )),\\n issued_by_session_id TEXT,\\n created_at TEXT NOT NULL,\\n expires_at TEXT NOT NULL,\\n consumed_at TEXT,\\n consumed_by_session_id TEXT,\\n revoked_at TEXT,\\n PRIMARY KEY (workspace_id, pairing_code_id),\\n FOREIGN KEY (workspace_id) REFERENCES workspaces(workspace_id),\\n FOREIGN KEY (workspace_id, issued_by_session_id)\\n REFERENCES sessions(workspace_id, session_id),\\n FOREIGN KEY (workspace_id, consumed_by_session_id)\\n REFERENCES sessions(workspace_id, session_id),\\n CHECK(\\n (actor_kind = 'human' AND person_id IS NOT NULL AND agent_id IS NULL) OR\\n (actor_kind = 'agent' AND agent_id IS NOT NULL AND person_id IS NULL)\\n ),\\n CHECK(created_at < expires_at),\\n CHECK(consumed_at IS NULL OR created_at <= consumed_at),\\n CHECK(revoked_at IS NULL OR created_at <= revoked_at),\\n CHECK((consumed_at IS NULL) = (consumed_by_session_id IS NULL)),\\n CHECK(consumed_at IS NULL OR revoked_at IS NULL)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"person_identities\",\n \"sql\": \"CREATE TABLE person_identities (\\n workspace_id TEXT NOT NULL,\\n person_id TEXT NOT NULL,\\n plugin_connection_id TEXT NOT NULL,\\n provider_id TEXT NOT NULL CHECK(provider_id IN (\\n 'codecommit', 'codepipeline', 'jira', 'confluence', 'clockify'\\n )),\\n vendor_person_id TEXT NOT NULL CHECK(length(vendor_person_id) BETWEEN 1 AND 512),\\n created_at TEXT NOT NULL,\\n PRIMARY KEY (\\n workspace_id,\\n person_id,\\n plugin_connection_id,\\n provider_id,\\n vendor_person_id\\n ),\\n UNIQUE (workspace_id, plugin_connection_id, provider_id, vendor_person_id),\\n FOREIGN KEY (workspace_id, person_id)\\n REFERENCES persons(workspace_id, person_id),\\n FOREIGN KEY (workspace_id, plugin_connection_id, provider_id)\\n REFERENCES plugin_connections(workspace_id, plugin_connection_id, provider_id)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"persons\",\n \"sql\": \"CREATE TABLE persons (\\n workspace_id TEXT NOT NULL,\\n person_id TEXT NOT NULL,\\n display_name TEXT NOT NULL CHECK(length(display_name) BETWEEN 1 AND 200),\\n avatar_json TEXT NOT NULL CHECK(length(avatar_json) > 0),\\n is_active INTEGER NOT NULL CHECK(is_active IN (0, 1)),\\n revision INTEGER NOT NULL DEFAULT 1 CHECK(revision >= 1),\\n created_at TEXT NOT NULL,\\n updated_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, person_id),\\n FOREIGN KEY (workspace_id) REFERENCES workspaces(workspace_id),\\n CHECK(created_at <= updated_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"plugin_cache_entries\",\n \"sql\": \"CREATE TABLE plugin_cache_entries (\\n workspace_id TEXT NOT NULL,\\n plugin_connection_id TEXT NOT NULL,\\n stream_key TEXT NOT NULL,\\n record_key TEXT NOT NULL CHECK(length(record_key) BETWEEN 1 AND 700),\\n state TEXT NOT NULL CHECK(state IN ('present', 'tombstoned')),\\n payload_json TEXT CHECK(payload_json IS NULL OR length(payload_json) BETWEEN 2 AND 524288),\\n payload_digest TEXT CHECK(payload_digest IS NULL OR (length(payload_digest) = 64 AND payload_digest NOT GLOB '*[^0-9a-f]*')),\\n source_revision TEXT NOT NULL CHECK(length(source_revision) BETWEEN 1 AND 512),\\n last_page_id TEXT NOT NULL,\\n cached_at TEXT NOT NULL,\\n tombstoned_at TEXT,\\n PRIMARY KEY (workspace_id, plugin_connection_id, stream_key, record_key),\\n FOREIGN KEY (workspace_id, plugin_connection_id, stream_key)\\n REFERENCES plugin_sync_streams(workspace_id, plugin_connection_id, stream_key),\\n FOREIGN KEY (workspace_id, plugin_connection_id, stream_key, last_page_id)\\n REFERENCES plugin_sync_pages(workspace_id, plugin_connection_id, stream_key, page_id),\\n CHECK((payload_json IS NULL) = (payload_digest IS NULL)),\\n CHECK(state = 'tombstoned' OR payload_json IS NOT NULL),\\n CHECK((state = 'tombstoned') = (tombstoned_at IS NOT NULL))\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"plugin_configurations\",\n \"sql\": \"CREATE TABLE plugin_configurations (\\n workspace_id TEXT NOT NULL,\\n plugin_connection_id TEXT NOT NULL,\\n revision INTEGER NOT NULL CHECK(revision >= 1),\\n configuration_json TEXT NOT NULL CHECK(length(configuration_json) BETWEEN 2 AND 65536),\\n configuration_digest TEXT NOT NULL CHECK(\\n length(configuration_digest) = 64 AND configuration_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n created_at TEXT NOT NULL,\\n updated_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, plugin_connection_id),\\n FOREIGN KEY (workspace_id, plugin_connection_id)\\n REFERENCES plugin_connections(workspace_id, plugin_connection_id),\\n CHECK(created_at <= updated_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"plugin_connections\",\n \"sql\": \"CREATE TABLE plugin_connections (\\n workspace_id TEXT NOT NULL,\\n plugin_connection_id TEXT NOT NULL,\\n provider_account_id TEXT,\\n followed_resource_id TEXT,\\n provider_id TEXT NOT NULL CHECK(provider_id IN (\\n 'codecommit', 'codepipeline', 'jira', 'confluence', 'clockify'\\n )),\\n display_name TEXT NOT NULL CHECK(length(display_name) BETWEEN 1 AND 200),\\n revision INTEGER NOT NULL DEFAULT 1 CHECK(revision >= 1),\\n is_enabled INTEGER NOT NULL DEFAULT 1 CHECK(is_enabled IN (0, 1)),\\n created_at TEXT NOT NULL,\\n updated_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, plugin_connection_id),\\n UNIQUE (workspace_id, plugin_connection_id, provider_id),\\n UNIQUE (workspace_id, followed_resource_id),\\n FOREIGN KEY (workspace_id) REFERENCES workspaces(workspace_id),\\n FOREIGN KEY (workspace_id, provider_account_id)\\n REFERENCES provider_accounts(workspace_id, provider_account_id),\\n FOREIGN KEY (workspace_id, followed_resource_id, provider_account_id, provider_id)\\n REFERENCES followed_resources(\\n workspace_id, followed_resource_id, provider_account_id, provider_id\\n ),\\n CHECK((provider_account_id IS NULL) = (followed_resource_id IS NULL)),\\n CHECK(created_at <= updated_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"plugin_runtime_authority_generations\",\n \"sql\": \"CREATE TABLE plugin_runtime_authority_generations (\\n workspace_id TEXT NOT NULL,\\n plugin_connection_id TEXT NOT NULL,\\n generation INTEGER NOT NULL CHECK(generation >= 1),\\n authority_digest TEXT NOT NULL CHECK(\\n length(authority_digest) = 71 AND substr(authority_digest, 1, 7) = 'sha256:' AND\\n substr(authority_digest, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n activated_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, plugin_connection_id, generation),\\n UNIQUE (workspace_id, plugin_connection_id, authority_digest),\\n FOREIGN KEY (workspace_id, plugin_connection_id)\\n REFERENCES plugin_connections(workspace_id, plugin_connection_id)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"plugin_runtime_authority_heads\",\n \"sql\": \"CREATE TABLE plugin_runtime_authority_heads (\\n workspace_id TEXT NOT NULL,\\n plugin_connection_id TEXT NOT NULL,\\n provider_id TEXT NOT NULL,\\n authority_schema_version INTEGER NOT NULL CHECK(authority_schema_version = 1),\\n generation INTEGER NOT NULL CHECK(generation >= 1),\\n connection_revision INTEGER NOT NULL CHECK(connection_revision >= 1),\\n descriptor_generation INTEGER NOT NULL CHECK(descriptor_generation >= 1),\\n configuration_revision INTEGER,\\n configuration_digest TEXT,\\n descriptor_digest TEXT NOT NULL CHECK(\\n length(descriptor_digest) = 64 AND descriptor_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n account_digest TEXT NOT NULL CHECK(\\n length(account_digest) = 71 AND substr(account_digest, 1, 7) = 'sha256:' AND\\n substr(account_digest, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n authority_digest TEXT NOT NULL CHECK(\\n length(authority_digest) = 71 AND substr(authority_digest, 1, 7) = 'sha256:' AND\\n substr(authority_digest, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n activated_at TEXT NOT NULL CHECK(\\n length(activated_at) = 24 AND\\n activated_at GLOB\\n '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'\\n ),\\n PRIMARY KEY (workspace_id, plugin_connection_id),\\n FOREIGN KEY (workspace_id, plugin_connection_id, provider_id)\\n REFERENCES plugin_connections(workspace_id, plugin_connection_id, provider_id),\\n CHECK(\\n (configuration_revision IS NULL AND configuration_digest IS NULL) OR\\n (\\n configuration_revision IS NOT NULL AND configuration_revision >= 1 AND\\n configuration_digest IS NOT NULL AND length(configuration_digest) = 64 AND\\n configuration_digest NOT GLOB '*[^0-9a-f]*'\\n )\\n )\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"plugin_runtime_state\",\n \"sql\": \"CREATE TABLE plugin_runtime_state (\\n workspace_id TEXT NOT NULL,\\n plugin_connection_id TEXT NOT NULL,\\n provider_id TEXT NOT NULL,\\n revision INTEGER NOT NULL DEFAULT 1 CHECK(revision >= 1),\\n descriptor_schema_version INTEGER NOT NULL CHECK(descriptor_schema_version >= 1),\\n descriptor_json TEXT NOT NULL CHECK(length(descriptor_json) BETWEEN 2 AND 65536),\\n descriptor_digest TEXT NOT NULL CHECK(length(descriptor_digest) = 64 AND descriptor_digest NOT GLOB '*[^0-9a-f]*'),\\n accepted_at TEXT NOT NULL,\\n health_state TEXT NOT NULL CHECK(health_state IN ('healthy', 'degraded', 'unavailable', 'disabled')),\\n failure_class TEXT CHECK(failure_class IS NULL OR failure_class IN (\\n 'authentication', 'authorization', 'rate-limit', 'timeout', 'malformed-response', 'outage', 'unknown'\\n )),\\n safe_message TEXT CHECK(safe_message IS NULL OR length(safe_message) BETWEEN 1 AND 500),\\n checked_at TEXT NOT NULL,\\n retry_at TEXT,\\n consecutive_failures INTEGER NOT NULL DEFAULT 0 CHECK(consecutive_failures >= 0), descriptor_generation\\n INTEGER NOT NULL DEFAULT 1 CHECK(descriptor_generation >= 1),\\n PRIMARY KEY (workspace_id, plugin_connection_id),\\n FOREIGN KEY (workspace_id, plugin_connection_id, provider_id)\\n REFERENCES plugin_connections(workspace_id, plugin_connection_id, provider_id),\\n CHECK(retry_at IS NULL OR checked_at <= retry_at),\\n CHECK(\\n (health_state IN ('healthy', 'disabled') AND failure_class IS NULL AND safe_message IS NULL AND retry_at IS NULL) OR\\n (health_state IN ('degraded', 'unavailable') AND failure_class IS NOT NULL AND safe_message IS NOT NULL)\\n )\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"plugin_secret_bindings\",\n \"sql\": \"CREATE TABLE plugin_secret_bindings (\\n secret_ref TEXT PRIMARY KEY CHECK(\\n length(secret_ref) = 71 AND substr(secret_ref, 1, 7) = 'secret_' AND\\n substr(secret_ref, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n workspace_id TEXT NOT NULL,\\n plugin_connection_id TEXT NOT NULL,\\n field_key TEXT NOT NULL CHECK(length(field_key) BETWEEN 1 AND 100),\\n FOREIGN KEY (workspace_id, plugin_connection_id)\\n REFERENCES plugin_connections(workspace_id, plugin_connection_id)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"plugin_secret_cleanup\",\n \"sql\": \"CREATE TABLE plugin_secret_cleanup (\\n secret_ref TEXT PRIMARY KEY CHECK(\\n length(secret_ref) = 71 AND substr(secret_ref, 1, 7) = 'secret_' AND\\n substr(secret_ref, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n requested_at TEXT NOT NULL,\\n FOREIGN KEY (secret_ref) REFERENCES plugin_secret_bindings(secret_ref)\\n ON DELETE RESTRICT\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"plugin_sync_attempt_completions\",\n \"sql\": \"CREATE TABLE plugin_sync_attempt_completions (\\n workspace_id TEXT NOT NULL,\\n plugin_connection_id TEXT NOT NULL,\\n stream_key TEXT NOT NULL CHECK(length(stream_key) BETWEEN 1 AND 100),\\n attempt_sequence INTEGER NOT NULL CHECK(attempt_sequence >= 1),\\n outcome TEXT NOT NULL CHECK(outcome IN ('synchronized', 'source-unavailable', 'interrupted')),\\n ending_revision INTEGER NOT NULL CHECK(ending_revision >= 0),\\n pages_committed INTEGER NOT NULL CHECK(pages_committed >= 0),\\n completed_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, plugin_connection_id, stream_key, attempt_sequence),\\n FOREIGN KEY (workspace_id, plugin_connection_id, stream_key, attempt_sequence)\\n REFERENCES plugin_sync_attempts(workspace_id, plugin_connection_id, stream_key, attempt_sequence)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"plugin_sync_attempts\",\n \"sql\": \"CREATE TABLE plugin_sync_attempts (\\n workspace_id TEXT NOT NULL,\\n plugin_connection_id TEXT NOT NULL,\\n provider_id TEXT NOT NULL,\\n stream_key TEXT NOT NULL CHECK(length(stream_key) BETWEEN 1 AND 100),\\n attempt_sequence INTEGER NOT NULL CHECK(attempt_sequence >= 1),\\n started_revision INTEGER NOT NULL CHECK(started_revision >= 0),\\n started_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, plugin_connection_id, stream_key, attempt_sequence),\\n FOREIGN KEY (workspace_id, plugin_connection_id, provider_id)\\n REFERENCES plugin_connections(workspace_id, plugin_connection_id, provider_id)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"plugin_sync_claims\",\n \"sql\": \"CREATE TABLE plugin_sync_claims (\\n workspace_id TEXT NOT NULL,\\n plugin_connection_id TEXT NOT NULL,\\n provider_id TEXT NOT NULL,\\n stream_key TEXT NOT NULL CHECK(length(stream_key) BETWEEN 1 AND 100),\\n claim_id TEXT NOT NULL CHECK(length(claim_id) = 36),\\n claimed_at TEXT NOT NULL,\\n expires_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, plugin_connection_id, stream_key),\\n UNIQUE (workspace_id, plugin_connection_id, stream_key, claim_id),\\n FOREIGN KEY (workspace_id, plugin_connection_id, provider_id)\\n REFERENCES plugin_connections(workspace_id, plugin_connection_id, provider_id),\\n CHECK(claimed_at < expires_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"plugin_sync_evidence\",\n \"sql\": \"CREATE TABLE plugin_sync_evidence (\\n workspace_id TEXT NOT NULL,\\n plugin_connection_id TEXT NOT NULL,\\n stream_key TEXT NOT NULL,\\n page_id TEXT NOT NULL,\\n ordinal INTEGER NOT NULL CHECK(ordinal >= 0),\\n event_id TEXT NOT NULL CHECK(length(event_id) BETWEEN 1 AND 512),\\n event_digest TEXT NOT NULL CHECK(length(event_digest) = 64 AND event_digest NOT GLOB '*[^0-9a-f]*'),\\n event_kind TEXT NOT NULL CHECK(event_kind IN ('upsert', 'tombstone')),\\n record_key TEXT NOT NULL CHECK(length(record_key) BETWEEN 1 AND 700),\\n source_revision TEXT NOT NULL CHECK(length(source_revision) BETWEEN 1 AND 512),\\n payload_json TEXT NOT NULL CHECK(length(payload_json) BETWEEN 2 AND 524288),\\n observed_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, plugin_connection_id, stream_key, page_id, ordinal),\\n UNIQUE (workspace_id, plugin_connection_id, stream_key, event_id),\\n FOREIGN KEY (workspace_id, plugin_connection_id, stream_key, page_id)\\n REFERENCES plugin_sync_pages(workspace_id, plugin_connection_id, stream_key, page_id),\\n CHECK(length(payload_json) >= 2)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"plugin_sync_pages\",\n \"sql\": \"CREATE TABLE plugin_sync_pages (\\n workspace_id TEXT NOT NULL,\\n plugin_connection_id TEXT NOT NULL,\\n stream_key TEXT NOT NULL,\\n page_id TEXT NOT NULL CHECK(length(page_id) BETWEEN 1 AND 200),\\n expected_revision INTEGER NOT NULL CHECK(expected_revision >= 0),\\n page_digest TEXT NOT NULL CHECK(length(page_digest) = 64 AND page_digest NOT GLOB '*[^0-9a-f]*'),\\n checkpoint_digest TEXT NOT NULL CHECK(length(checkpoint_digest) = 64 AND checkpoint_digest NOT GLOB '*[^0-9a-f]*'),\\n timeline_event_digest TEXT NOT NULL CHECK(length(timeline_event_digest) = 64 AND timeline_event_digest NOT GLOB '*[^0-9a-f]*'),\\n event_count INTEGER NOT NULL CHECK(event_count >= 0),\\n committed_at TEXT NOT NULL, has_more INTEGER NOT NULL DEFAULT 0 CHECK(has_more IN (0, 1)), successful_health_json TEXT\\n CHECK(successful_health_json IS NULL OR length(successful_health_json) BETWEEN 2 AND 2048), successful_health_digest TEXT\\n CHECK(\\n (successful_health_digest IS NULL) = (successful_health_json IS NULL) AND\\n (successful_health_digest IS NULL OR (\\n length(successful_health_digest) = 64 AND successful_health_digest NOT GLOB '*[^0-9a-f]*'\\n ))\\n ),\\n PRIMARY KEY (workspace_id, plugin_connection_id, stream_key, page_id),\\n UNIQUE (workspace_id, plugin_connection_id, stream_key, expected_revision),\\n UNIQUE (workspace_id, timeline_event_digest),\\n FOREIGN KEY (workspace_id, plugin_connection_id, stream_key)\\n REFERENCES plugin_sync_streams(workspace_id, plugin_connection_id, stream_key)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"plugin_sync_streams\",\n \"sql\": \"CREATE TABLE plugin_sync_streams (\\n workspace_id TEXT NOT NULL,\\n plugin_connection_id TEXT NOT NULL,\\n provider_id TEXT NOT NULL,\\n stream_key TEXT NOT NULL CHECK(length(stream_key) BETWEEN 1 AND 100),\\n revision INTEGER NOT NULL DEFAULT 0 CHECK(revision >= 0),\\n checkpoint_json TEXT CHECK(checkpoint_json IS NULL OR length(checkpoint_json) BETWEEN 2 AND 65536),\\n checkpoint_digest TEXT CHECK(checkpoint_digest IS NULL OR (length(checkpoint_digest) = 64 AND checkpoint_digest NOT GLOB '*[^0-9a-f]*')),\\n last_page_id TEXT,\\n synchronized_at TEXT,\\n PRIMARY KEY (workspace_id, plugin_connection_id, stream_key),\\n FOREIGN KEY (workspace_id, plugin_connection_id, provider_id)\\n REFERENCES plugin_connections(workspace_id, plugin_connection_id, provider_id),\\n CHECK((checkpoint_json IS NULL) = (checkpoint_digest IS NULL))\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"provider_accounts\",\n \"sql\": \"CREATE TABLE provider_accounts (\\n workspace_id TEXT NOT NULL,\\n provider_account_id TEXT NOT NULL,\\n provider_family TEXT NOT NULL CHECK(provider_family IN (\\n 'aws', 'atlassian', 'clockify'\\n )),\\n vendor_account_id TEXT NOT NULL CHECK(length(vendor_account_id) BETWEEN 1 AND 512),\\n display_name TEXT NOT NULL CHECK(length(display_name) BETWEEN 1 AND 200),\\n revision INTEGER NOT NULL DEFAULT 1 CHECK(revision >= 1),\\n created_at TEXT NOT NULL,\\n updated_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, provider_account_id),\\n UNIQUE (workspace_id, provider_account_id, provider_family),\\n UNIQUE (workspace_id, provider_family, vendor_account_id),\\n FOREIGN KEY (workspace_id) REFERENCES workspaces(workspace_id),\\n CHECK(created_at <= updated_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"quarantined_records\",\n \"sql\": \"CREATE TABLE quarantined_records (\\n workspace_id TEXT NOT NULL,\\n record_kind TEXT NOT NULL CHECK(length(record_kind) BETWEEN 1 AND 100),\\n record_key TEXT NOT NULL CHECK(length(record_key) BETWEEN 1 AND 500),\\n schema_version INTEGER NOT NULL CHECK(schema_version >= 1),\\n payload_digest TEXT NOT NULL CHECK(\\n length(payload_digest) = 64 AND\\n payload_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n diagnostic_code TEXT NOT NULL CHECK(length(diagnostic_code) BETWEEN 1 AND 100),\\n diagnostic_summary TEXT NOT NULL CHECK(length(diagnostic_summary) BETWEEN 1 AND 1000),\\n first_observed_at TEXT NOT NULL,\\n last_observed_at TEXT NOT NULL,\\n occurrence_count INTEGER NOT NULL DEFAULT 1 CHECK(occurrence_count >= 1),\\n PRIMARY KEY (\\n workspace_id,\\n record_kind,\\n record_key,\\n schema_version,\\n payload_digest,\\n diagnostic_code\\n ),\\n FOREIGN KEY (workspace_id) REFERENCES workspaces(workspace_id),\\n CHECK(first_observed_at <= last_observed_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"readiness_assessment_evidence\",\n \"sql\": \"CREATE TABLE readiness_assessment_evidence (\\n workspace_id TEXT NOT NULL,\\n assessment_id TEXT NOT NULL,\\n evidence_id TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, assessment_id, evidence_id),\\n FOREIGN KEY (workspace_id, assessment_id)\\n REFERENCES readiness_assessments(workspace_id, assessment_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, evidence_id)\\n REFERENCES evidence_items(workspace_id, evidence_id)\\n ON DELETE RESTRICT\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"readiness_assessment_sources\",\n \"sql\": \"CREATE TABLE readiness_assessment_sources (\\n workspace_id TEXT NOT NULL,\\n assessment_id TEXT NOT NULL,\\n plugin_connection_id TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, assessment_id, plugin_connection_id),\\n FOREIGN KEY (workspace_id, assessment_id)\\n REFERENCES readiness_assessments(workspace_id, assessment_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, plugin_connection_id)\\n REFERENCES plugin_connections(workspace_id, plugin_connection_id)\\n ON DELETE RESTRICT\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"readiness_assessments\",\n \"sql\": \"CREATE TABLE readiness_assessments (\\n workspace_id TEXT NOT NULL,\\n assessment_id TEXT NOT NULL,\\n scope_kind TEXT NOT NULL CHECK(scope_kind IN ('environment', 'release')),\\n release_id TEXT NOT NULL,\\n environment_id TEXT,\\n release_revision INTEGER NOT NULL CHECK(release_revision >= 1),\\n artifact_revision TEXT NOT NULL CHECK(length(artifact_revision) BETWEEN 1 AND 512),\\n candidate_digest TEXT NOT NULL CHECK(\\n length(candidate_digest) = 71 AND\\n candidate_digest GLOB 'sha256:*' AND\\n substr(candidate_digest, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n rule_id TEXT NOT NULL CHECK(length(rule_id) BETWEEN 1 AND 200),\\n rule_version INTEGER NOT NULL CHECK(rule_version >= 1),\\n rule_digest TEXT NOT NULL CHECK(\\n length(rule_digest) = 71 AND\\n rule_digest GLOB 'sha256:*' AND\\n substr(rule_digest, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n derivation_version INTEGER NOT NULL CHECK(derivation_version >= 1),\\n previous_assessment_id TEXT,\\n verdict TEXT NOT NULL CHECK(verdict IN (\\n 'blocked', 'ready', 'deploying', 'building', 'shipped', 'held'\\n )),\\n evaluated_at TEXT NOT NULL,\\n next_evaluation_at TEXT,\\n assessment_json TEXT NOT NULL CHECK(length(assessment_json) BETWEEN 2 AND 1048576),\\n assessment_digest TEXT NOT NULL CHECK(\\n length(assessment_digest) = 64 AND\\n assessment_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n PRIMARY KEY (workspace_id, assessment_id),\\n UNIQUE (workspace_id, assessment_id, scope_kind),\\n UNIQUE (workspace_id, assessment_id, candidate_digest),\\n FOREIGN KEY (workspace_id, release_id, release_revision)\\n REFERENCES release_revisions(workspace_id, release_id, revision)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, release_id, environment_id)\\n REFERENCES release_targets(workspace_id, release_id, environment_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, rule_id, rule_version, rule_digest)\\n REFERENCES readiness_rule_snapshots(workspace_id, rule_id, rule_version, rule_digest)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, previous_assessment_id)\\n REFERENCES readiness_assessments(workspace_id, assessment_id)\\n ON DELETE RESTRICT,\\n CHECK(\\n (scope_kind = 'environment' AND environment_id IS NOT NULL) OR\\n (scope_kind = 'release' AND environment_id IS NULL)\\n ),\\n CHECK(previous_assessment_id IS NULL OR previous_assessment_id <> assessment_id),\\n CHECK(next_evaluation_at IS NULL OR evaluated_at <= next_evaluation_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"readiness_environment_heads\",\n \"sql\": \"CREATE TABLE readiness_environment_heads (\\n workspace_id TEXT NOT NULL,\\n release_id TEXT NOT NULL,\\n environment_id TEXT NOT NULL,\\n head_revision INTEGER NOT NULL CHECK(head_revision >= 1),\\n assessment_id TEXT NOT NULL,\\n candidate_digest TEXT NOT NULL,\\n rule_id TEXT NOT NULL,\\n rule_version INTEGER NOT NULL CHECK(rule_version >= 1),\\n rule_digest TEXT NOT NULL,\\n derivation_version INTEGER NOT NULL CHECK(derivation_version >= 1),\\n created_at TEXT NOT NULL,\\n updated_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, release_id, environment_id),\\n UNIQUE (workspace_id, release_id, environment_id, assessment_id),\\n FOREIGN KEY (workspace_id, assessment_id)\\n REFERENCES readiness_assessments(workspace_id, assessment_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, release_id, environment_id)\\n REFERENCES release_targets(workspace_id, release_id, environment_id)\\n ON DELETE RESTRICT,\\n CHECK(created_at <= updated_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"readiness_environment_queue\",\n \"sql\": \"CREATE TABLE readiness_environment_queue (\\n workspace_id TEXT NOT NULL,\\n release_id TEXT NOT NULL,\\n environment_id TEXT NOT NULL,\\n invalidation_revision INTEGER NOT NULL CHECK(invalidation_revision >= 1),\\n reason TEXT NOT NULL CHECK(reason IN (\\n 'evidence-changed', 'plugin-health-changed', 'rule-changed',\\n 'candidate-changed', 'scheduled'\\n )),\\n source_evidence_id TEXT,\\n source_plugin_connection_id TEXT,\\n queued_at TEXT NOT NULL,\\n available_at TEXT NOT NULL,\\n attempts INTEGER NOT NULL DEFAULT 0 CHECK(attempts >= 0),\\n claim_owner TEXT,\\n claim_expires_at TEXT, claim_token TEXT,\\n PRIMARY KEY (workspace_id, release_id, environment_id),\\n FOREIGN KEY (workspace_id, release_id, environment_id)\\n REFERENCES release_targets(workspace_id, release_id, environment_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, source_evidence_id)\\n REFERENCES evidence_items(workspace_id, evidence_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, source_plugin_connection_id)\\n REFERENCES plugin_connections(workspace_id, plugin_connection_id)\\n ON DELETE RESTRICT,\\n CHECK(queued_at <= available_at),\\n CHECK(\\n (claim_owner IS NULL AND claim_expires_at IS NULL) OR\\n (claim_owner IS NOT NULL AND length(claim_owner) BETWEEN 1 AND 200 AND claim_expires_at IS NOT NULL)\\n )\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"readiness_evaluation_schedules\",\n \"sql\": \"CREATE TABLE readiness_evaluation_schedules (\\n workspace_id TEXT NOT NULL,\\n release_id TEXT NOT NULL,\\n environment_id TEXT NOT NULL,\\n assessment_id TEXT NOT NULL,\\n due_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, release_id, environment_id),\\n FOREIGN KEY (workspace_id, release_id, environment_id, assessment_id)\\n REFERENCES readiness_environment_heads(workspace_id, release_id, environment_id, assessment_id)\\n ON DELETE RESTRICT\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"readiness_head_history\",\n \"sql\": \"CREATE TABLE readiness_head_history (\\n workspace_id TEXT NOT NULL,\\n scope_kind TEXT NOT NULL CHECK(scope_kind IN ('environment', 'release')),\\n release_id TEXT NOT NULL,\\n environment_key TEXT NOT NULL,\\n head_revision INTEGER NOT NULL CHECK(head_revision >= 1),\\n assessment_id TEXT NOT NULL,\\n committed_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, scope_kind, release_id, environment_key, head_revision),\\n UNIQUE (workspace_id, assessment_id),\\n FOREIGN KEY (workspace_id, assessment_id)\\n REFERENCES readiness_assessments(workspace_id, assessment_id)\\n ON DELETE RESTRICT,\\n CHECK(\\n (scope_kind = 'environment' AND length(environment_key) > 0) OR\\n (scope_kind = 'release' AND environment_key = '')\\n )\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"readiness_release_children\",\n \"sql\": \"CREATE TABLE readiness_release_children (\\n workspace_id TEXT NOT NULL,\\n release_assessment_id TEXT NOT NULL,\\n environment_id TEXT NOT NULL,\\n environment_assessment_id TEXT NOT NULL,\\n environment_candidate_digest TEXT NOT NULL CHECK(\\n length(environment_candidate_digest) = 71 AND\\n environment_candidate_digest GLOB 'sha256:*' AND\\n substr(environment_candidate_digest, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n PRIMARY KEY (workspace_id, release_assessment_id, environment_id),\\n UNIQUE (workspace_id, release_assessment_id, environment_assessment_id),\\n FOREIGN KEY (workspace_id, release_assessment_id)\\n REFERENCES readiness_assessments(workspace_id, assessment_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, environment_assessment_id)\\n REFERENCES readiness_assessments(workspace_id, assessment_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, environment_assessment_id, environment_candidate_digest)\\n REFERENCES readiness_assessments(workspace_id, assessment_id, candidate_digest)\\n ON DELETE RESTRICT\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"readiness_release_heads\",\n \"sql\": \"CREATE TABLE readiness_release_heads (\\n workspace_id TEXT NOT NULL,\\n release_id TEXT NOT NULL,\\n head_revision INTEGER NOT NULL CHECK(head_revision >= 1),\\n assessment_id TEXT NOT NULL,\\n candidate_digest TEXT NOT NULL,\\n rule_id TEXT NOT NULL,\\n rule_version INTEGER NOT NULL CHECK(rule_version >= 1),\\n rule_digest TEXT NOT NULL,\\n derivation_version INTEGER NOT NULL CHECK(derivation_version >= 1),\\n created_at TEXT NOT NULL,\\n updated_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, release_id),\\n UNIQUE (workspace_id, release_id, assessment_id),\\n FOREIGN KEY (workspace_id, assessment_id)\\n REFERENCES readiness_assessments(workspace_id, assessment_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, release_id)\\n REFERENCES releases(workspace_id, release_id)\\n ON DELETE RESTRICT,\\n CHECK(created_at <= updated_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"readiness_release_queue\",\n \"sql\": \"CREATE TABLE readiness_release_queue (\\n workspace_id TEXT NOT NULL,\\n release_id TEXT NOT NULL,\\n invalidation_revision INTEGER NOT NULL CHECK(invalidation_revision >= 1),\\n reason TEXT NOT NULL CHECK(reason IN (\\n 'environment-assessment-changed', 'rule-changed', 'candidate-changed'\\n )),\\n source_environment_id TEXT,\\n queued_at TEXT NOT NULL,\\n available_at TEXT NOT NULL,\\n attempts INTEGER NOT NULL DEFAULT 0 CHECK(attempts >= 0),\\n claim_owner TEXT,\\n claim_expires_at TEXT, claim_token TEXT,\\n PRIMARY KEY (workspace_id, release_id),\\n FOREIGN KEY (workspace_id, release_id)\\n REFERENCES releases(workspace_id, release_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, release_id, source_environment_id)\\n REFERENCES release_targets(workspace_id, release_id, environment_id)\\n ON DELETE RESTRICT,\\n CHECK(queued_at <= available_at),\\n CHECK(\\n (claim_owner IS NULL AND claim_expires_at IS NULL) OR\\n (claim_owner IS NOT NULL AND length(claim_owner) BETWEEN 1 AND 200 AND claim_expires_at IS NOT NULL)\\n )\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"readiness_rule_snapshots\",\n \"sql\": \"CREATE TABLE readiness_rule_snapshots (\\n workspace_id TEXT NOT NULL,\\n rule_id TEXT NOT NULL CHECK(length(rule_id) BETWEEN 1 AND 200),\\n rule_version INTEGER NOT NULL CHECK(rule_version >= 1),\\n rule_digest TEXT NOT NULL CHECK(\\n length(rule_digest) = 71 AND\\n rule_digest GLOB 'sha256:*' AND\\n substr(rule_digest, 8) NOT GLOB '*[^0-9a-f]*'\\n ),\\n material_json TEXT NOT NULL CHECK(length(material_json) BETWEEN 2 AND 262144),\\n created_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, rule_id, rule_version),\\n UNIQUE (workspace_id, rule_id, rule_version, rule_digest),\\n FOREIGN KEY (workspace_id) REFERENCES workspaces(workspace_id) ON DELETE RESTRICT\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"recovery_audit_events\",\n \"sql\": \"CREATE TABLE recovery_audit_events (\\n workspace_id TEXT NOT NULL,\\n pairing_code_id TEXT NOT NULL,\\n event_kind TEXT NOT NULL CHECK(event_kind = 'owner-recovery-issued'),\\n revoked_owner_sessions INTEGER NOT NULL CHECK(revoked_owner_sessions IN (0, 1)),\\n created_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, pairing_code_id),\\n FOREIGN KEY (workspace_id, pairing_code_id)\\n REFERENCES pairing_codes(workspace_id, pairing_code_id)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"relationship_heads\",\n \"sql\": \"CREATE TABLE relationship_heads (\\n workspace_id TEXT NOT NULL,\\n relationship_id TEXT NOT NULL,\\n current_revision INTEGER NOT NULL CHECK(current_revision >= 1),\\n edge_digest TEXT NOT NULL CHECK(\\n length(edge_digest) = 64 AND\\n edge_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n created_at TEXT NOT NULL,\\n updated_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, relationship_id),\\n UNIQUE (workspace_id, edge_digest),\\n FOREIGN KEY (workspace_id) REFERENCES workspaces(workspace_id),\\n CHECK(created_at <= updated_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"relationship_repair_applications\",\n \"sql\": \"CREATE TABLE relationship_repair_applications (\\n workspace_id TEXT NOT NULL,\\n proposal_id TEXT NOT NULL,\\n relationship_id TEXT NOT NULL,\\n applied_revision INTEGER NOT NULL CHECK(applied_revision >= 2),\\n actor_kind TEXT NOT NULL CHECK(actor_kind IN ('human', 'agent')),\\n person_id TEXT,\\n agent_id TEXT,\\n session_id TEXT NOT NULL,\\n applied_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, proposal_id),\\n UNIQUE (workspace_id, relationship_id, applied_revision),\\n FOREIGN KEY (workspace_id, proposal_id)\\n REFERENCES relationship_repair_proposals(workspace_id, proposal_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, relationship_id, applied_revision)\\n REFERENCES relationship_revisions(workspace_id, relationship_id, revision)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, session_id)\\n REFERENCES sessions(workspace_id, session_id)\\n ON DELETE RESTRICT,\\n CHECK(\\n (actor_kind = 'human' AND person_id IS NOT NULL AND agent_id IS NULL) OR\\n (actor_kind = 'agent' AND agent_id IS NOT NULL AND person_id IS NULL)\\n )\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"relationship_repair_proposals\",\n \"sql\": \"CREATE TABLE relationship_repair_proposals (\\n workspace_id TEXT NOT NULL,\\n proposal_id TEXT NOT NULL,\\n schema_version INTEGER NOT NULL CHECK(schema_version = 2),\\n release_id TEXT NOT NULL,\\n environment_id TEXT,\\n relationship_id TEXT NOT NULL,\\n expected_revision INTEGER NOT NULL CHECK(expected_revision >= 1),\\n disposition TEXT NOT NULL CHECK(disposition IN ('link', 'verify', 'reject')),\\n rationale TEXT NOT NULL CHECK(length(rationale) BETWEEN 1 AND 1000),\\n actor_kind TEXT NOT NULL CHECK(actor_kind IN ('human', 'agent')),\\n person_id TEXT,\\n agent_id TEXT,\\n session_id TEXT NOT NULL,\\n status TEXT NOT NULL CHECK(status IN ('pending', 'approved', 'rejected')),\\n proposed_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, proposal_id),\\n FOREIGN KEY (workspace_id, release_id)\\n REFERENCES releases(workspace_id, release_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, release_id, environment_id)\\n REFERENCES release_targets(workspace_id, release_id, environment_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, relationship_id, expected_revision)\\n REFERENCES relationship_revisions(workspace_id, relationship_id, revision)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, session_id)\\n REFERENCES sessions(workspace_id, session_id)\\n ON DELETE RESTRICT,\\n CHECK(\\n (actor_kind = 'human' AND person_id IS NOT NULL AND agent_id IS NULL) OR\\n (actor_kind = 'agent' AND agent_id IS NOT NULL AND person_id IS NULL)\\n )\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"relationship_repair_reviews\",\n \"sql\": \"CREATE TABLE relationship_repair_reviews (\\n workspace_id TEXT NOT NULL,\\n proposal_id TEXT NOT NULL,\\n review_id TEXT NOT NULL,\\n decision TEXT NOT NULL CHECK(decision IN ('approved', 'rejected')),\\n rationale TEXT NOT NULL CHECK(length(rationale) BETWEEN 1 AND 1000),\\n actor_kind TEXT NOT NULL CHECK(actor_kind IN ('human', 'agent')),\\n person_id TEXT,\\n agent_id TEXT,\\n session_id TEXT NOT NULL,\\n reviewed_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, proposal_id),\\n UNIQUE (workspace_id, review_id),\\n FOREIGN KEY (workspace_id, proposal_id)\\n REFERENCES relationship_repair_proposals(workspace_id, proposal_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, session_id)\\n REFERENCES sessions(workspace_id, session_id)\\n ON DELETE RESTRICT,\\n CHECK(\\n (actor_kind = 'human' AND person_id IS NOT NULL AND agent_id IS NULL) OR\\n (actor_kind = 'agent' AND agent_id IS NOT NULL AND person_id IS NULL)\\n )\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"relationship_revision_evidence\",\n \"sql\": \"CREATE TABLE relationship_revision_evidence (\\n workspace_id TEXT NOT NULL,\\n relationship_id TEXT NOT NULL,\\n relationship_revision INTEGER NOT NULL,\\n evidence_claim_id TEXT NOT NULL,\\n PRIMARY KEY (\\n workspace_id,\\n relationship_id,\\n relationship_revision,\\n evidence_claim_id\\n ),\\n FOREIGN KEY (workspace_id, relationship_id, relationship_revision)\\n REFERENCES relationship_revisions(workspace_id, relationship_id, revision)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, evidence_claim_id)\\n REFERENCES evidence_claims(workspace_id, evidence_claim_id)\\n ON DELETE RESTRICT\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"relationship_revisions\",\n \"sql\": \"CREATE TABLE relationship_revisions (\\n workspace_id TEXT NOT NULL,\\n relationship_id TEXT NOT NULL,\\n revision INTEGER NOT NULL CHECK(revision >= 1),\\n supersedes_revision INTEGER,\\n schema_version INTEGER NOT NULL CHECK(schema_version >= 1),\\n kind TEXT NOT NULL CHECK(kind IN (\\n 'contains', 'implements', 'depends-on', 'verified-by',\\n 'delivered-by', 'documented-by', 'tracks-time-for'\\n )),\\n source_node_id TEXT NOT NULL,\\n source_node_kind TEXT NOT NULL CHECK(source_node_kind IN (\\n 'issue', 'pull-request', 'page', 'pipeline-execution',\\n 'deployment', 'time-entry', 'release', 'environment'\\n )),\\n target_node_id TEXT NOT NULL,\\n target_node_kind TEXT NOT NULL CHECK(target_node_kind IN (\\n 'issue', 'pull-request', 'page', 'pipeline-execution',\\n 'deployment', 'time-entry', 'release', 'environment'\\n )),\\n lifecycle TEXT NOT NULL CHECK(lifecycle IN (\\n 'missing', 'inferred', 'proposed', 'verified',\\n 'governed', 'rejected', 'superseded'\\n )),\\n lifecycle_reason TEXT CHECK(\\n lifecycle_reason IS NULL OR length(lifecycle_reason) BETWEEN 1 AND 1000\\n ),\\n release_id TEXT,\\n environment_id TEXT,\\n confidence_kind TEXT NOT NULL CHECK(\\n confidence_kind IN ('unknown', 'inferred', 'confirmed')\\n ),\\n confidence_score REAL CHECK(\\n confidence_score IS NULL OR confidence_score BETWEEN 0 AND 1\\n ),\\n confidence_rationale TEXT CHECK(\\n confidence_rationale IS NULL OR length(confidence_rationale) BETWEEN 1 AND 1000\\n ),\\n provenance_kind TEXT NOT NULL CHECK(\\n provenance_kind IN ('plugin', 'human', 'agent', 'rule')\\n ),\\n provenance_plugin_connection_id TEXT,\\n provenance_source_entity_id TEXT,\\n provenance_source_entity_revision INTEGER,\\n provenance_person_id TEXT,\\n provenance_agent_id TEXT,\\n provenance_rule_id TEXT CHECK(\\n provenance_rule_id IS NULL OR length(provenance_rule_id) BETWEEN 1 AND 200\\n ),\\n provenance_rule_version INTEGER CHECK(\\n provenance_rule_version IS NULL OR provenance_rule_version >= 1\\n ),\\n provenance_rationale TEXT CHECK(\\n provenance_rationale IS NULL OR length(provenance_rationale) BETWEEN 1 AND 1000\\n ),\\n recorded_by_kind TEXT NOT NULL CHECK(\\n recorded_by_kind IN ('human', 'agent', 'system')\\n ),\\n recorded_by_person_id TEXT,\\n recorded_by_agent_id TEXT,\\n recorded_by_component TEXT CHECK(\\n recorded_by_component IS NULL OR length(recorded_by_component) BETWEEN 1 AND 200\\n ),\\n effective_at TEXT NOT NULL,\\n recorded_at TEXT NOT NULL,\\n revision_digest TEXT NOT NULL CHECK(\\n length(revision_digest) = 64 AND\\n revision_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n PRIMARY KEY (workspace_id, relationship_id, revision),\\n UNIQUE (workspace_id, relationship_id, revision_digest),\\n FOREIGN KEY (workspace_id, relationship_id)\\n REFERENCES relationship_heads(workspace_id, relationship_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, relationship_id, supersedes_revision)\\n REFERENCES relationship_revisions(workspace_id, relationship_id, revision)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, source_node_id, source_node_kind)\\n REFERENCES delivery_nodes(workspace_id, node_id, endpoint_kind)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, target_node_id, target_node_kind)\\n REFERENCES delivery_nodes(workspace_id, node_id, endpoint_kind)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, release_id)\\n REFERENCES releases(workspace_id, release_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, release_id, environment_id)\\n REFERENCES release_targets(workspace_id, release_id, environment_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, provenance_plugin_connection_id)\\n REFERENCES plugin_connections(workspace_id, plugin_connection_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (\\n workspace_id,\\n provenance_source_entity_id,\\n provenance_source_entity_revision\\n ) REFERENCES entity_revisions(workspace_id, entity_id, revision)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, provenance_person_id)\\n REFERENCES persons(workspace_id, person_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, recorded_by_person_id)\\n REFERENCES persons(workspace_id, person_id)\\n ON DELETE RESTRICT,\\n CHECK(source_node_id <> target_node_id),\\n CHECK(\\n (kind = 'contains' AND source_node_kind = 'release' AND target_node_kind IN (\\n 'issue', 'pull-request', 'page', 'pipeline-execution', 'deployment', 'time-entry'\\n )) OR\\n (kind = 'implements' AND source_node_kind = 'pull-request' AND target_node_kind = 'issue') OR\\n kind = 'depends-on' OR\\n (kind IN ('verified-by', 'delivered-by') AND\\n source_node_kind = 'pull-request' AND target_node_kind = 'pipeline-execution') OR\\n (kind = 'documented-by' AND source_node_kind IN ('issue', 'release') AND\\n target_node_kind = 'page') OR\\n (kind = 'tracks-time-for' AND source_node_kind = 'time-entry' AND target_node_kind = 'issue')\\n ),\\n CHECK(effective_at <= recorded_at),\\n CHECK(\\n (revision = 1 AND supersedes_revision IS NULL) OR\\n (revision > 1 AND supersedes_revision = revision - 1)\\n ),\\n CHECK(\\n (environment_id IS NULL) OR\\n (release_id IS NOT NULL)\\n ),\\n CHECK(kind <> 'contains' OR release_id IS NOT NULL),\\n CHECK(\\n (confidence_kind = 'inferred' AND confidence_score IS NOT NULL) OR\\n (confidence_kind IN ('unknown', 'confirmed') AND confidence_score IS NULL)\\n ),\\n CHECK(lifecycle <> 'inferred' OR confidence_kind <> 'confirmed'),\\n CHECK(\\n confidence_kind = 'confirmed' OR confidence_rationale IS NOT NULL\\n ),\\n CHECK(\\n lifecycle NOT IN ('missing', 'rejected', 'superseded') OR\\n lifecycle_reason IS NOT NULL\\n ),\\n CHECK(\\n (provenance_kind = 'plugin' AND provenance_plugin_connection_id IS NOT NULL AND\\n provenance_source_entity_id IS NOT NULL AND provenance_source_entity_revision IS NOT NULL AND\\n provenance_person_id IS NULL AND provenance_agent_id IS NULL AND\\n provenance_rule_id IS NULL AND provenance_rule_version IS NULL) OR\\n (provenance_kind = 'human' AND provenance_plugin_connection_id IS NULL AND\\n provenance_source_entity_id IS NULL AND provenance_source_entity_revision IS NULL AND\\n provenance_person_id IS NOT NULL AND provenance_agent_id IS NULL AND\\n provenance_rule_id IS NULL AND provenance_rule_version IS NULL) OR\\n (provenance_kind = 'agent' AND provenance_plugin_connection_id IS NULL AND\\n provenance_source_entity_id IS NULL AND provenance_source_entity_revision IS NULL AND\\n provenance_person_id IS NULL AND provenance_agent_id IS NOT NULL AND\\n provenance_rule_id IS NULL AND provenance_rule_version IS NULL) OR\\n (provenance_kind = 'rule' AND provenance_plugin_connection_id IS NULL AND\\n provenance_source_entity_id IS NULL AND provenance_source_entity_revision IS NULL AND\\n provenance_person_id IS NULL AND provenance_agent_id IS NULL AND\\n provenance_rule_id IS NOT NULL AND provenance_rule_version IS NOT NULL)\\n ),\\n CHECK(\\n (recorded_by_kind = 'human' AND recorded_by_person_id IS NOT NULL AND\\n recorded_by_agent_id IS NULL AND recorded_by_component IS NULL) OR\\n (recorded_by_kind = 'agent' AND recorded_by_person_id IS NULL AND\\n recorded_by_agent_id IS NOT NULL AND recorded_by_component IS NULL) OR\\n (recorded_by_kind = 'system' AND recorded_by_person_id IS NULL AND\\n recorded_by_agent_id IS NULL AND recorded_by_component IS NOT NULL)\\n )\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"release_revisions\",\n \"sql\": \"CREATE TABLE release_revisions (\\n workspace_id TEXT NOT NULL,\\n release_id TEXT NOT NULL,\\n revision INTEGER NOT NULL CHECK(revision >= 1),\\n snapshot_json TEXT NOT NULL CHECK(length(snapshot_json) > 0),\\n snapshot_digest TEXT NOT NULL CHECK(\\n length(snapshot_digest) = 64 AND\\n snapshot_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n created_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, release_id, revision),\\n FOREIGN KEY (workspace_id, release_id)\\n REFERENCES releases(workspace_id, release_id)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"release_targets\",\n \"sql\": \"CREATE TABLE release_targets (\\n workspace_id TEXT NOT NULL,\\n release_id TEXT NOT NULL,\\n environment_id TEXT NOT NULL,\\n created_at TEXT NOT NULL, lifecycle_kind TEXT NOT NULL DEFAULT 'active'\\n CHECK(lifecycle_kind IN ('active', 'ended')), ended_at TEXT,\\n PRIMARY KEY (workspace_id, release_id, environment_id),\\n FOREIGN KEY (workspace_id, release_id)\\n REFERENCES releases(workspace_id, release_id)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"releases\",\n \"sql\": \"CREATE TABLE releases (\\n workspace_id TEXT NOT NULL,\\n release_id TEXT NOT NULL,\\n current_revision INTEGER NOT NULL CHECK(current_revision >= 1),\\n created_at TEXT NOT NULL,\\n updated_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, release_id),\\n FOREIGN KEY (workspace_id) REFERENCES workspaces(workspace_id),\\n CHECK(created_at <= updated_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"retention_cleanup_claims\",\n \"sql\": \"CREATE TABLE retention_cleanup_claims (\\n workspace_id TEXT NOT NULL,\\n run_id TEXT NOT NULL,\\n retention_class TEXT NOT NULL CHECK(retention_class IN (\\n 'evidence', 'agent-content', 'sandbox-artifact'\\n )),\\n record_key TEXT NOT NULL CHECK(length(record_key) BETWEEN 1 AND 200),\\n PRIMARY KEY (workspace_id, run_id, retention_class, record_key),\\n FOREIGN KEY (workspace_id, run_id, retention_class)\\n REFERENCES retention_cleanup_runs(workspace_id, run_id, retention_class)\\n ON DELETE RESTRICT\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"retention_cleanup_runs\",\n \"sql\": \"CREATE TABLE retention_cleanup_runs (\\n workspace_id TEXT NOT NULL,\\n run_id TEXT NOT NULL CHECK(length(run_id) = 36),\\n retention_class TEXT NOT NULL CHECK(retention_class IN (\\n 'audit-replay', 'reproducible-content', 'evidence',\\n 'agent-content', 'sandbox-artifact'\\n )),\\n policy_revision INTEGER NOT NULL CHECK(policy_revision >= 1),\\n cutoff_at TEXT NOT NULL,\\n batch_limit INTEGER NOT NULL CHECK(batch_limit BETWEEN 1 AND 512),\\n selected_count INTEGER NOT NULL CHECK(selected_count BETWEEN 0 AND batch_limit),\\n deleted_count INTEGER NOT NULL CHECK(deleted_count BETWEEN 0 AND selected_count),\\n completed_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, run_id),\\n UNIQUE (workspace_id, run_id, retention_class),\\n FOREIGN KEY (workspace_id, policy_revision)\\n REFERENCES workspace_settings_versions(workspace_id, revision)\\n ON DELETE RESTRICT,\\n CHECK(cutoff_at <= completed_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"role_assignments\",\n \"sql\": \"CREATE TABLE role_assignments (\\n workspace_id TEXT NOT NULL,\\n assignment_id TEXT NOT NULL,\\n actor_kind TEXT NOT NULL CHECK(actor_kind IN ('human', 'agent')),\\n person_id TEXT,\\n agent_id TEXT,\\n role TEXT NOT NULL CHECK(role IN (\\n 'workspace-owner', 'workspace-approver', 'release-owner',\\n 'release-approver', 'change-owner', 'issue-owner', 'issue-assignee',\\n 'page-owner', 'author', 'contributor', 'reviewer', 'operator',\\n 'deployment-approver', 'merge-approver', 'watcher'\\n )),\\n scope_kind TEXT NOT NULL CHECK(scope_kind IN (\\n 'workspace', 'release', 'environment', 'entity'\\n )),\\n release_id TEXT,\\n environment_id TEXT,\\n entity_id TEXT,\\n lifecycle_kind TEXT NOT NULL CHECK(lifecycle_kind IN ('active', 'ended', 'revoked')),\\n assigned_at TEXT NOT NULL,\\n ended_at TEXT,\\n revoked_at TEXT,\\n revision INTEGER NOT NULL DEFAULT 1 CHECK(revision >= 1),\\n created_at TEXT NOT NULL,\\n updated_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, assignment_id),\\n FOREIGN KEY (workspace_id) REFERENCES workspaces(workspace_id),\\n FOREIGN KEY (workspace_id, person_id)\\n REFERENCES persons(workspace_id, person_id),\\n FOREIGN KEY (workspace_id, release_id)\\n REFERENCES releases(workspace_id, release_id),\\n FOREIGN KEY (workspace_id, release_id, environment_id)\\n REFERENCES release_targets(workspace_id, release_id, environment_id),\\n FOREIGN KEY (workspace_id, entity_id)\\n REFERENCES entities(workspace_id, entity_id),\\n CHECK(\\n (actor_kind = 'human' AND person_id IS NOT NULL AND agent_id IS NULL) OR\\n (actor_kind = 'agent' AND agent_id IS NOT NULL AND person_id IS NULL)\\n ),\\n CHECK(\\n (scope_kind = 'workspace' AND release_id IS NULL AND environment_id IS NULL AND entity_id IS NULL) OR\\n (scope_kind = 'release' AND release_id IS NOT NULL AND environment_id IS NULL AND entity_id IS NULL) OR\\n (scope_kind = 'environment' AND release_id IS NOT NULL AND environment_id IS NOT NULL AND entity_id IS NULL) OR\\n (scope_kind = 'entity' AND release_id IS NULL AND environment_id IS NULL AND entity_id IS NOT NULL)\\n ),\\n CHECK(\\n (lifecycle_kind = 'active' AND ended_at IS NULL AND revoked_at IS NULL) OR\\n (lifecycle_kind = 'ended' AND ended_at IS NOT NULL AND revoked_at IS NULL AND assigned_at <= ended_at) OR\\n (lifecycle_kind = 'revoked' AND ended_at IS NULL AND revoked_at IS NOT NULL AND assigned_at <= revoked_at)\\n ),\\n CHECK(created_at <= updated_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"sessions\",\n \"sql\": \"CREATE TABLE sessions (\\n workspace_id TEXT NOT NULL,\\n session_id TEXT NOT NULL,\\n token_hash TEXT NOT NULL UNIQUE CHECK(\\n length(token_hash) = 64 AND token_hash NOT GLOB '*[^0-9a-f]*'\\n ),\\n csrf_hash TEXT NOT NULL CHECK(\\n length(csrf_hash) = 64 AND csrf_hash NOT GLOB '*[^0-9a-f]*'\\n ),\\n actor_kind TEXT NOT NULL CHECK(actor_kind IN ('human', 'agent')),\\n person_id TEXT,\\n agent_id TEXT,\\n permission TEXT NOT NULL CHECK(permission IN (\\n 'workspace-owner', 'workspace-approver', 'release-owner', 'release-approver',\\n 'change-owner', 'issue-owner', 'issue-assignee', 'page-owner', 'author',\\n 'contributor', 'reviewer', 'operator', 'deployment-approver', 'merge-approver',\\n 'watcher'\\n )),\\n created_at TEXT NOT NULL,\\n last_seen_at TEXT NOT NULL,\\n idle_expires_at TEXT NOT NULL,\\n absolute_expires_at TEXT NOT NULL,\\n revoked_at TEXT,\\n PRIMARY KEY (workspace_id, session_id),\\n FOREIGN KEY (workspace_id) REFERENCES workspaces(workspace_id),\\n CHECK(\\n (actor_kind = 'human' AND person_id IS NOT NULL AND agent_id IS NULL) OR\\n (actor_kind = 'agent' AND agent_id IS NOT NULL AND person_id IS NULL)\\n ),\\n CHECK(created_at <= last_seen_at),\\n CHECK(last_seen_at <= idle_expires_at),\\n CHECK(idle_expires_at <= absolute_expires_at),\\n CHECK(revoked_at IS NULL OR created_at <= revoked_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"timeline_export_audits\",\n \"sql\": \"CREATE TABLE timeline_export_audits (\\n workspace_id TEXT NOT NULL,\\n export_audit_id TEXT NOT NULL,\\n schema_version INTEGER NOT NULL CHECK(schema_version = 1),\\n person_id TEXT NOT NULL,\\n session_id TEXT NOT NULL,\\n format TEXT NOT NULL CHECK(format IN ('csv', 'json')),\\n actor_filter TEXT CHECK(actor_filter IS NULL OR actor_filter IN ('agent', 'human', 'plugin', 'system')),\\n from_filter TEXT,\\n to_filter TEXT,\\n requested_limit INTEGER NOT NULL CHECK(requested_limit BETWEEN 1 AND 1000),\\n returned_count INTEGER NOT NULL CHECK(returned_count BETWEEN 0 AND requested_limit),\\n is_truncated INTEGER NOT NULL CHECK(is_truncated IN (0, 1)),\\n recorded_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, export_audit_id),\\n FOREIGN KEY (workspace_id) REFERENCES workspaces(workspace_id),\\n FOREIGN KEY (workspace_id, person_id) REFERENCES persons(workspace_id, person_id),\\n FOREIGN KEY (workspace_id, session_id) REFERENCES sessions(workspace_id, session_id),\\n CHECK(from_filter IS NULL OR to_filter IS NULL OR from_filter <= to_filter)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"workspace_settings\",\n \"sql\": \"CREATE TABLE workspace_settings (\\n workspace_id TEXT NOT NULL,\\n schema_version INTEGER NOT NULL CHECK(schema_version = 1),\\n revision INTEGER NOT NULL DEFAULT 1 CHECK(revision >= 1),\\n policy_revision INTEGER NOT NULL DEFAULT 1 CHECK(policy_revision >= 1),\\n settings_json TEXT NOT NULL CHECK(\\n length(settings_json) BETWEEN 2 AND 32768 AND json_valid(settings_json)\\n ),\\n settings_digest TEXT NOT NULL CHECK(\\n length(settings_digest) = 64 AND settings_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n created_at TEXT NOT NULL,\\n updated_at TEXT NOT NULL,\\n updated_by_person_id TEXT,\\n PRIMARY KEY (workspace_id),\\n UNIQUE (workspace_id, revision),\\n FOREIGN KEY (workspace_id) REFERENCES workspaces(workspace_id),\\n FOREIGN KEY (workspace_id, updated_by_person_id)\\n REFERENCES persons(workspace_id, person_id)\\n ON DELETE RESTRICT,\\n CHECK(created_at <= updated_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"workspace_settings_audits\",\n \"sql\": \"CREATE TABLE workspace_settings_audits (\\n workspace_id TEXT NOT NULL,\\n mutation_id TEXT NOT NULL,\\n request_digest TEXT NOT NULL CHECK(\\n length(request_digest) = 64 AND request_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n from_revision INTEGER NOT NULL CHECK(from_revision >= 1),\\n to_revision INTEGER NOT NULL CHECK(to_revision = from_revision + 1),\\n actor_person_id TEXT NOT NULL,\\n session_id TEXT NOT NULL,\\n changed_sections_json TEXT NOT NULL CHECK(\\n length(changed_sections_json) BETWEEN 2 AND 256 AND json_valid(changed_sections_json)\\n ),\\n governed INTEGER NOT NULL CHECK(governed IN (0, 1)),\\n governance_authority_digest TEXT CHECK(\\n governance_authority_digest IS NULL OR (\\n length(governance_authority_digest) = 64 AND\\n governance_authority_digest NOT GLOB '*[^0-9a-f]*'\\n )\\n ),\\n before_digest TEXT NOT NULL CHECK(\\n length(before_digest) = 64 AND before_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n after_digest TEXT NOT NULL CHECK(\\n length(after_digest) = 64 AND after_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n occurred_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id, mutation_id),\\n UNIQUE (workspace_id, to_revision),\\n FOREIGN KEY (workspace_id) REFERENCES workspaces(workspace_id),\\n FOREIGN KEY (workspace_id, actor_person_id)\\n REFERENCES persons(workspace_id, person_id)\\n ON DELETE RESTRICT,\\n FOREIGN KEY (workspace_id, session_id)\\n REFERENCES sessions(workspace_id, session_id)\\n ON DELETE RESTRICT,\\n CHECK(\\n (governed = 0 AND governance_authority_digest IS NULL) OR\\n (governed = 1 AND governance_authority_digest IS NOT NULL)\\n )\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"workspace_settings_versions\",\n \"sql\": \"CREATE TABLE workspace_settings_versions (\\n workspace_id TEXT NOT NULL,\\n schema_version INTEGER NOT NULL CHECK(schema_version = 1),\\n revision INTEGER NOT NULL CHECK(revision >= 1),\\n policy_revision INTEGER NOT NULL CHECK(policy_revision >= 1),\\n settings_json TEXT NOT NULL CHECK(\\n length(settings_json) BETWEEN 2 AND 32768 AND json_valid(settings_json)\\n ),\\n settings_digest TEXT NOT NULL CHECK(\\n length(settings_digest) = 64 AND settings_digest NOT GLOB '*[^0-9a-f]*'\\n ),\\n created_at TEXT NOT NULL,\\n updated_at TEXT NOT NULL,\\n updated_by_person_id TEXT,\\n PRIMARY KEY (workspace_id, revision),\\n FOREIGN KEY (workspace_id) REFERENCES workspaces(workspace_id),\\n FOREIGN KEY (workspace_id, updated_by_person_id)\\n REFERENCES persons(workspace_id, person_id)\\n ON DELETE RESTRICT,\\n CHECK(created_at <= updated_at)\\n )\"\n },\n {\n \"type\": \"table\",\n \"name\": \"workspaces\",\n \"sql\": \"CREATE TABLE workspaces (\\n workspace_id TEXT NOT NULL,\\n display_name TEXT NOT NULL CHECK(length(display_name) BETWEEN 1 AND 200),\\n revision INTEGER NOT NULL DEFAULT 1 CHECK(revision >= 1),\\n created_at TEXT NOT NULL,\\n updated_at TEXT NOT NULL,\\n PRIMARY KEY (workspace_id),\\n CHECK(created_at <= updated_at)\\n )\"\n },\n {\n \"type\": \"index\",\n \"name\": \"agent_job_leases_recovery_idx\",\n \"sql\": \"CREATE INDEX agent_job_leases_recovery_idx\\n ON agent_job_leases(workspace_id, lease_expires_at, job_id, attempt_sequence)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"agent_jobs_state_idx\",\n \"sql\": \"CREATE INDEX agent_jobs_state_idx\\n ON agent_jobs(workspace_id, state, created_at, job_id)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"agent_review_command_artifacts_expiry_idx\",\n \"sql\": \"CREATE INDEX agent_review_command_artifacts_expiry_idx\\n ON agent_review_command_artifacts(workspace_id, expires_at, artifact_id)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"agent_review_suggestion_revisions_history_idx\",\n \"sql\": \"CREATE INDEX agent_review_suggestion_revisions_history_idx\\n ON agent_review_suggestion_revisions(\\n workspace_id, source_job_id, suggestion_id, revision_sequence DESC\\n )\"\n },\n {\n \"type\": \"index\",\n \"name\": \"agent_thread_events_job_idx\",\n \"sql\": \"CREATE INDEX agent_thread_events_job_idx\\n ON agent_thread_events(workspace_id, job_id, attempt_sequence, event_sequence)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"agent_thread_events_review_result_idx\",\n \"sql\": \"CREATE INDEX agent_thread_events_review_result_idx\\n ON agent_thread_events(workspace_id, job_id, event_sequence DESC)\\n WHERE event_kind = 'review-report'\"\n },\n {\n \"type\": \"index\",\n \"name\": \"agent_thread_events_review_suggestion_published_idx\",\n \"sql\": \"CREATE UNIQUE INDEX agent_thread_events_review_suggestion_published_idx\\n ON agent_thread_events(\\n workspace_id, job_id, json_extract(payload_json, '$.suggestionId'),\\n json_extract(payload_json, '$.revisionId')\\n )\\n WHERE event_kind = 'review-suggestion-published'\"\n },\n {\n \"type\": \"index\",\n \"name\": \"authorized_share_grantee_expiry_idx\",\n \"sql\": \"CREATE INDEX authorized_share_grantee_expiry_idx\\n ON authorized_share_grants(workspace_id, grantee_person_id, expires_at)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"content_blobs_storage_created_idx\",\n \"sql\": \"CREATE INDEX content_blobs_storage_created_idx\\n ON content_blobs(workspace_id, storage_class, created_at)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"delivery_nodes_entity_idx\",\n \"sql\": \"CREATE INDEX delivery_nodes_entity_idx\\n ON delivery_nodes(workspace_id, entity_id)\\n WHERE entity_id IS NOT NULL\"\n },\n {\n \"type\": \"index\",\n \"name\": \"delivery_nodes_missing_idx\",\n \"sql\": \"CREATE INDEX delivery_nodes_missing_idx\\n ON delivery_nodes(workspace_id, expected_entity_kind, created_at DESC)\\n WHERE resolution_state = 'missing'\"\n },\n {\n \"type\": \"index\",\n \"name\": \"delivery_nodes_release_idx\",\n \"sql\": \"CREATE INDEX delivery_nodes_release_idx\\n ON delivery_nodes(workspace_id, release_id, environment_id)\\n WHERE release_id IS NOT NULL\"\n },\n {\n \"type\": \"index\",\n \"name\": \"diff_content_cache_cleanup_requested_idx\",\n \"sql\": \"CREATE INDEX diff_content_cache_cleanup_requested_idx\\n ON diff_content_cache_cleanup(attempt_count, requested_at, workspace_id, content_digest)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"diff_content_cache_content_digest_idx\",\n \"sql\": \"CREATE INDEX diff_content_cache_content_digest_idx\\n ON diff_content_cache_entries(workspace_id, content_digest)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"domain_events_retention_idx\",\n \"sql\": \"CREATE INDEX domain_events_retention_idx\\n ON domain_events(workspace_id, ingested_at, event_cursor)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"domain_events_timeline_idx\",\n \"sql\": \"CREATE INDEX domain_events_timeline_idx\\n ON domain_events(workspace_id, occurred_at DESC, event_id DESC)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"entities_governed_action_scope_idx\",\n \"sql\": \"CREATE UNIQUE INDEX entities_governed_action_scope_idx\\n ON entities(workspace_id, entity_id, plugin_connection_id, provider_id)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"entities_type_updated_at_idx\",\n \"sql\": \"CREATE INDEX entities_type_updated_at_idx\\n ON entities(workspace_id, entity_type, updated_at DESC)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"entity_projection_state_idx\",\n \"sql\": \"CREATE INDEX entity_projection_state_idx\\n ON entity_projection_revisions(workspace_id, entity_state, recorded_at DESC)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"entity_revisions_synchronized_at_idx\",\n \"sql\": \"CREATE INDEX entity_revisions_synchronized_at_idx\\n ON entity_revisions(workspace_id, synchronized_at DESC)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"evidence_claim_single_successor_idx\",\n \"sql\": \"CREATE UNIQUE INDEX evidence_claim_single_successor_idx\\n ON evidence_claims(workspace_id, supersedes_claim_id)\\n WHERE supersedes_claim_id IS NOT NULL\"\n },\n {\n \"type\": \"index\",\n \"name\": \"evidence_claim_subject_idx\",\n \"sql\": \"CREATE INDEX evidence_claim_subject_idx\\n ON evidence_claims(workspace_id, subject_node_id, predicate, recorded_at DESC)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"evidence_retention_idx\",\n \"sql\": \"CREATE INDEX evidence_retention_idx\\n ON evidence_items(workspace_id, legal_hold, retain_until)\\n WHERE retain_until IS NOT NULL\"\n },\n {\n \"type\": \"index\",\n \"name\": \"evidence_source_revision_idx\",\n \"sql\": \"CREATE INDEX evidence_source_revision_idx\\n ON evidence_items(workspace_id, source_entity_id, source_entity_revision)\\n WHERE source_entity_id IS NOT NULL\"\n },\n {\n \"type\": \"index\",\n \"name\": \"governed_action_audit_history_idx\",\n \"sql\": \"CREATE INDEX governed_action_audit_history_idx\\n ON audit_events(workspace_id, action_id, occurred_at DESC)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"governed_action_audit_timeline_idx\",\n \"sql\": \"CREATE INDEX governed_action_audit_timeline_idx\\n ON audit_events(workspace_id, occurred_at DESC, audit_event_id DESC)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"governed_action_execution_preparations_expiry_idx\",\n \"sql\": \"CREATE INDEX governed_action_execution_preparations_expiry_idx\\n ON governed_action_execution_preparations(expires_at, workspace_id, action_id)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"governed_action_execution_recovery_idx\",\n \"sql\": \"CREATE INDEX governed_action_execution_recovery_idx\\n ON governed_action_execution_leases(recovery_eligible_at, workspace_id, action_id)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"governed_action_provider_outcomes_received_idx\",\n \"sql\": \"CREATE INDEX governed_action_provider_outcomes_received_idx\\n ON governed_action_provider_outcomes(received_at, workspace_id, action_id)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"governed_action_recovery_claim_expiry_idx\",\n \"sql\": \"CREATE INDEX governed_action_recovery_claim_expiry_idx\\n ON governed_action_recovery_claims(lease_expires_at, workspace_id, action_id, claim_sequence)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"governed_action_release_publication_slots_unique_idx\",\n \"sql\": \"CREATE UNIQUE INDEX governed_action_release_publication_slots_unique_idx\\n ON governed_action_release_publication_slots(\\n workspace_id, provider_id, release_id, COALESCE(predecessor_action_id, '')\\n )\"\n },\n {\n \"type\": \"index\",\n \"name\": \"governed_action_release_publications_lookup_idx\",\n \"sql\": \"CREATE INDEX governed_action_release_publications_lookup_idx\\n ON governed_action_release_publications(\\n workspace_id, provider_id, release_id, action_id DESC\\n )\"\n },\n {\n \"type\": \"index\",\n \"name\": \"governed_action_target_dimensions_lookup_idx\",\n \"sql\": \"CREATE INDEX governed_action_target_dimensions_lookup_idx\\n ON governed_action_target_dimensions(\\n workspace_id, action_kind, expected_revision, action_id DESC\\n )\"\n },\n {\n \"type\": \"index\",\n \"name\": \"governed_action_transitions_history_idx\",\n \"sql\": \"CREATE INDEX governed_action_transitions_history_idx\\n ON governed_action_transitions(workspace_id, action_id, sequence DESC)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"governed_actions_state_idx\",\n \"sql\": \"CREATE INDEX governed_actions_state_idx\\n ON governed_actions(workspace_id, state, updated_at DESC)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"pairing_codes_active_idx\",\n \"sql\": \"CREATE INDEX pairing_codes_active_idx\\n ON pairing_codes(workspace_id, expires_at)\\n WHERE consumed_at IS NULL AND revoked_at IS NULL\"\n },\n {\n \"type\": \"index\",\n \"name\": \"pairing_codes_first_run_idx\",\n \"sql\": \"CREATE UNIQUE INDEX pairing_codes_first_run_idx\\n ON pairing_codes(workspace_id)\\n WHERE purpose = 'first-run'\"\n },\n {\n \"type\": \"index\",\n \"name\": \"persons_display_name_idx\",\n \"sql\": \"CREATE INDEX persons_display_name_idx\\n ON persons(workspace_id, display_name)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"plugin_cache_pipeline_execution_idx\",\n \"sql\": \"CREATE INDEX plugin_cache_pipeline_execution_idx\\n ON plugin_cache_entries(\\n workspace_id, plugin_connection_id, stream_key, state,\\n CASE WHEN json_valid(payload_json)\\n THEN json_extract(payload_json, '$.attributes.pipelineName') END,\\n CASE WHEN json_valid(payload_json)\\n THEN json_extract(payload_json, '$.attributes.executionId') END,\\n CASE WHEN json_valid(payload_json)\\n THEN json_extract(payload_json, '$.entityType') END\\n )\"\n },\n {\n \"type\": \"index\",\n \"name\": \"plugin_cache_pipeline_version_idx\",\n \"sql\": \"CREATE INDEX plugin_cache_pipeline_version_idx\\n ON plugin_cache_entries(\\n workspace_id, plugin_connection_id, stream_key, state,\\n CASE WHEN json_valid(payload_json)\\n THEN json_extract(payload_json, '$.attributes.pipelineName') END,\\n CASE WHEN json_valid(payload_json)\\n THEN json_extract(payload_json, '$.entityType') END,\\n CASE WHEN json_valid(payload_json)\\n THEN json_extract(payload_json, '$.attributes.pipelineVersion') END,\\n cached_at DESC\\n )\"\n },\n {\n \"type\": \"index\",\n \"name\": \"plugin_cache_state_idx\",\n \"sql\": \"CREATE INDEX plugin_cache_state_idx\\n ON plugin_cache_entries(workspace_id, plugin_connection_id, stream_key, state)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"plugin_configuration_updated_idx\",\n \"sql\": \"CREATE INDEX plugin_configuration_updated_idx\\n ON plugin_configurations(workspace_id, updated_at DESC, plugin_connection_id)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"plugin_evidence_record_idx\",\n \"sql\": \"CREATE INDEX plugin_evidence_record_idx\\n ON plugin_sync_evidence(workspace_id, plugin_connection_id, record_key, observed_at DESC)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"plugin_runtime_health_retry_idx\",\n \"sql\": \"CREATE INDEX plugin_runtime_health_retry_idx\\n ON plugin_runtime_state(workspace_id, health_state, retry_at)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"plugin_secret_binding_scope_idx\",\n \"sql\": \"CREATE INDEX plugin_secret_binding_scope_idx\\n ON plugin_secret_bindings(workspace_id, plugin_connection_id, field_key)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"plugin_sync_pages_timeline_idx\",\n \"sql\": \"CREATE INDEX plugin_sync_pages_timeline_idx\\n ON plugin_sync_pages(workspace_id, committed_at DESC, timeline_event_digest DESC)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"quarantined_records_last_observed_idx\",\n \"sql\": \"CREATE INDEX quarantined_records_last_observed_idx\\n ON quarantined_records(workspace_id, last_observed_at DESC)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"readiness_assessment_rule_idx\",\n \"sql\": \"CREATE INDEX readiness_assessment_rule_idx\\n ON readiness_assessments(workspace_id, rule_id, rule_version, derivation_version)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"readiness_assessment_scope_idx\",\n \"sql\": \"CREATE INDEX readiness_assessment_scope_idx\\n ON readiness_assessments(workspace_id, release_id, environment_id, evaluated_at DESC)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"readiness_environment_queue_available_idx\",\n \"sql\": \"CREATE INDEX readiness_environment_queue_available_idx\\n ON readiness_environment_queue(available_at, claim_expires_at)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"readiness_evidence_dependency_idx\",\n \"sql\": \"CREATE INDEX readiness_evidence_dependency_idx\\n ON readiness_assessment_evidence(workspace_id, evidence_id, assessment_id)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"readiness_head_history_assessment_idx\",\n \"sql\": \"CREATE INDEX readiness_head_history_assessment_idx\\n ON readiness_head_history(workspace_id, assessment_id)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"readiness_release_queue_available_idx\",\n \"sql\": \"CREATE INDEX readiness_release_queue_available_idx\\n ON readiness_release_queue(available_at, claim_expires_at)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"readiness_schedule_due_idx\",\n \"sql\": \"CREATE INDEX readiness_schedule_due_idx\\n ON readiness_evaluation_schedules(due_at)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"readiness_source_dependency_idx\",\n \"sql\": \"CREATE INDEX readiness_source_dependency_idx\\n ON readiness_assessment_sources(workspace_id, plugin_connection_id, assessment_id)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"recovery_audit_events_created_idx\",\n \"sql\": \"CREATE INDEX recovery_audit_events_created_idx\\n ON recovery_audit_events(workspace_id, created_at DESC)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"relationship_repair_one_pending_revision_idx\",\n \"sql\": \"CREATE UNIQUE INDEX relationship_repair_one_pending_revision_idx\\n ON relationship_repair_proposals(workspace_id, relationship_id, expected_revision)\\n WHERE status = 'pending'\"\n },\n {\n \"type\": \"index\",\n \"name\": \"relationship_repair_release_status_idx\",\n \"sql\": \"CREATE INDEX relationship_repair_release_status_idx\\n ON relationship_repair_proposals(workspace_id, release_id, status, proposed_at DESC, proposal_id DESC)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"relationship_revision_scope_idx\",\n \"sql\": \"CREATE INDEX relationship_revision_scope_idx\\n ON relationship_revisions(workspace_id, release_id, environment_id, recorded_at DESC)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"relationship_revision_source_idx\",\n \"sql\": \"CREATE INDEX relationship_revision_source_idx\\n ON relationship_revisions(workspace_id, source_node_id, kind, recorded_at DESC)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"relationship_revision_target_idx\",\n \"sql\": \"CREATE INDEX relationship_revision_target_idx\\n ON relationship_revisions(workspace_id, target_node_id, kind, recorded_at DESC)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"relationship_revision_timeline_idx\",\n \"sql\": \"CREATE INDEX relationship_revision_timeline_idx\\n ON relationship_revisions(workspace_id, recorded_at DESC, revision_digest DESC)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"release_revisions_created_at_idx\",\n \"sql\": \"CREATE INDEX release_revisions_created_at_idx\\n ON release_revisions(workspace_id, release_id, created_at DESC)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"release_targets_environment_idx\",\n \"sql\": \"CREATE INDEX release_targets_environment_idx\\n ON release_targets(workspace_id, environment_id, release_id)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"releases_updated_at_idx\",\n \"sql\": \"CREATE INDEX releases_updated_at_idx\\n ON releases(workspace_id, updated_at DESC)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"retention_cleanup_claims_record_idx\",\n \"sql\": \"CREATE INDEX retention_cleanup_claims_record_idx\\n ON retention_cleanup_claims(workspace_id, retention_class, record_key)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"role_assignments_entity_idx\",\n \"sql\": \"CREATE INDEX role_assignments_entity_idx\\n ON role_assignments(workspace_id, entity_id, role)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"role_assignments_release_idx\",\n \"sql\": \"CREATE INDEX role_assignments_release_idx\\n ON role_assignments(workspace_id, release_id, role)\"\n },\n {\n \"type\": \"index\",\n \"name\": \"sessions_active_idx\",\n \"sql\": \"CREATE INDEX sessions_active_idx\\n ON sessions(workspace_id, absolute_expires_at)\\n WHERE revoked_at IS NULL\"\n },\n {\n \"type\": \"index\",\n \"name\": \"timeline_export_audits_recorded_idx\",\n \"sql\": \"CREATE INDEX timeline_export_audits_recorded_idx\\n ON timeline_export_audits(workspace_id, recorded_at DESC, export_audit_id DESC)\"\n },\n {\n \"type\": \"view\",\n \"name\": \"current_plugin_runtime_authority_heads\",\n \"sql\": \"CREATE VIEW current_plugin_runtime_authority_heads AS\\n SELECT authority.*\\n FROM plugin_runtime_authority_heads authority\\n WHERE \\n EXISTS (\\n SELECT 1\\n FROM plugin_connections connection\\n JOIN plugin_runtime_state runtime\\n ON runtime.workspace_id = connection.workspace_id\\n AND runtime.plugin_connection_id = connection.plugin_connection_id\\n AND runtime.provider_id = connection.provider_id\\n WHERE connection.workspace_id = authority.workspace_id\\n AND connection.plugin_connection_id = authority.plugin_connection_id\\n AND connection.provider_id = authority.provider_id\\n AND connection.is_enabled = 1\\n AND connection.revision = authority.connection_revision\\n AND connection.updated_at <= authority.activated_at\\n AND runtime.descriptor_generation = authority.descriptor_generation\\n AND runtime.descriptor_digest = authority.descriptor_digest\\n AND runtime.accepted_at <= authority.activated_at\\n AND (\\n (\\n authority.configuration_revision IS NULL\\n AND authority.configuration_digest IS NULL\\n AND NOT EXISTS (\\n SELECT 1\\n FROM plugin_configurations configuration\\n WHERE configuration.workspace_id = authority.workspace_id\\n AND configuration.plugin_connection_id = authority.plugin_connection_id\\n )\\n ) OR (\\n authority.configuration_revision IS NOT NULL\\n AND authority.configuration_digest IS NOT NULL\\n AND EXISTS (\\n SELECT 1\\n FROM plugin_configurations configuration\\n WHERE configuration.workspace_id = authority.workspace_id\\n AND configuration.plugin_connection_id = authority.plugin_connection_id\\n AND configuration.revision = authority.configuration_revision\\n AND configuration.configuration_digest = authority.configuration_digest\\n AND configuration.updated_at <= authority.activated_at\\n )\\n )\\n )\\n )\"\n },\n {\n \"type\": \"view\",\n \"name\": \"readiness_assessment_dependency_integrity\",\n \"sql\": \"CREATE VIEW readiness_assessment_dependency_integrity AS\\n SELECT assessment.workspace_id, assessment.assessment_id\\n FROM readiness_assessments assessment\\n WHERE json_type(assessment.assessment_json, '$.evidenceIds') = 'array'\\n AND json_type(assessment.assessment_json, '$.sourceFreshness') = 'array'\\n AND NOT EXISTS (\\n SELECT 1 FROM json_each(assessment.assessment_json, '$.evidenceIds') expected\\n WHERE NOT EXISTS (\\n SELECT 1 FROM readiness_assessment_evidence dependency\\n WHERE dependency.workspace_id = assessment.workspace_id\\n AND dependency.assessment_id = assessment.assessment_id\\n AND dependency.evidence_id = expected.value\\n )\\n )\\n AND NOT EXISTS (\\n SELECT 1 FROM readiness_assessment_evidence dependency\\n WHERE dependency.workspace_id = assessment.workspace_id\\n AND dependency.assessment_id = assessment.assessment_id\\n AND NOT EXISTS (\\n SELECT 1 FROM json_each(assessment.assessment_json, '$.evidenceIds') expected\\n WHERE expected.value = dependency.evidence_id\\n )\\n )\\n AND NOT EXISTS (\\n SELECT 1 FROM json_each(assessment.assessment_json, '$.sourceFreshness') expected\\n WHERE NOT EXISTS (\\n SELECT 1 FROM readiness_assessment_sources dependency\\n WHERE dependency.workspace_id = assessment.workspace_id\\n AND dependency.assessment_id = assessment.assessment_id\\n AND dependency.plugin_connection_id = json_extract(expected.value, '$.pluginConnectionId')\\n )\\n )\\n AND NOT EXISTS (\\n SELECT 1 FROM readiness_assessment_sources dependency\\n WHERE dependency.workspace_id = assessment.workspace_id\\n AND dependency.assessment_id = assessment.assessment_id\\n AND NOT EXISTS (\\n SELECT 1 FROM json_each(assessment.assessment_json, '$.sourceFreshness') expected\\n WHERE json_extract(expected.value, '$.pluginConnectionId') = dependency.plugin_connection_id\\n )\\n )\"\n },\n {\n \"type\": \"view\",\n \"name\": \"readiness_release_child_integrity\",\n \"sql\": \"CREATE VIEW readiness_release_child_integrity AS\\n SELECT assessment.workspace_id, assessment.assessment_id\\n FROM readiness_assessments assessment\\n WHERE assessment.scope_kind = 'release'\\n AND json_type(assessment.assessment_json, '$.environments') = 'array'\\n AND json_array_length(assessment.assessment_json, '$.environments') > 0\\n AND NOT EXISTS (\\n SELECT 1 FROM json_each(assessment.assessment_json, '$.environments') expected\\n WHERE NOT EXISTS (\\n SELECT 1 FROM readiness_release_children child\\n WHERE child.workspace_id = assessment.workspace_id\\n AND child.release_assessment_id = assessment.assessment_id\\n AND child.environment_id = json_extract(expected.value, '$.environmentId')\\n AND child.environment_assessment_id = json_extract(expected.value, '$.assessmentId')\\n AND child.environment_candidate_digest = json_extract(expected.value, '$.candidateDigest')\\n )\\n )\\n AND NOT EXISTS (\\n SELECT 1 FROM readiness_release_children child\\n WHERE child.workspace_id = assessment.workspace_id\\n AND child.release_assessment_id = assessment.assessment_id\\n AND NOT EXISTS (\\n SELECT 1 FROM json_each(assessment.assessment_json, '$.environments') expected\\n WHERE json_extract(expected.value, '$.environmentId') = child.environment_id\\n AND json_extract(expected.value, '$.assessmentId') = child.environment_assessment_id\\n AND json_extract(expected.value, '$.candidateDigest') = child.environment_candidate_digest\\n )\\n )\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"agent_review_command_artifacts_bounded_insert\",\n \"sql\": \"CREATE TRIGGER agent_review_command_artifacts_bounded_insert\\n BEFORE INSERT ON agent_review_command_artifacts\\n WHEN (\\n SELECT COUNT(*) >= 64 OR COALESCE(SUM(byte_length), 0) + NEW.byte_length > 67108864\\n FROM agent_review_command_artifacts\\n WHERE workspace_id = NEW.workspace_id\\n AND job_id = NEW.job_id\\n AND attempt_sequence = NEW.attempt_sequence\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'review command artifact attempt capacity exceeded');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"agent_review_command_artifacts_no_delete\",\n \"sql\": \"CREATE TRIGGER agent_review_command_artifacts_no_delete\\n BEFORE DELETE ON agent_review_command_artifacts\\n WHEN NOT EXISTS (\\n SELECT 1 FROM retention_cleanup_claims claim\\n JOIN retention_cleanup_runs run\\n ON run.workspace_id = claim.workspace_id\\n AND run.run_id = claim.run_id\\n AND run.retention_class = claim.retention_class\\n WHERE claim.workspace_id = OLD.workspace_id\\n AND claim.retention_class = 'sandbox-artifact'\\n AND claim.record_key = OLD.artifact_id\\n AND OLD.expires_at <= run.cutoff_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'agent review command artifacts are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"agent_review_command_artifacts_no_replace\",\n \"sql\": \"CREATE TRIGGER agent_review_command_artifacts_no_replace\\n BEFORE INSERT ON agent_review_command_artifacts\\n WHEN EXISTS (\\n SELECT 1 FROM agent_review_command_artifacts artifact\\n WHERE artifact.workspace_id = NEW.workspace_id\\n AND (\\n artifact.artifact_id = NEW.artifact_id OR\\n (\\n artifact.job_id = NEW.job_id\\n AND artifact.attempt_sequence = NEW.attempt_sequence\\n AND artifact.command_sequence = NEW.command_sequence\\n AND artifact.stream = NEW.stream\\n )\\n )\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'agent review command artifacts are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"agent_review_command_artifacts_no_update\",\n \"sql\": \"CREATE TRIGGER agent_review_command_artifacts_no_update\\n BEFORE UPDATE ON agent_review_command_artifacts\\n BEGIN\\n SELECT RAISE(ABORT, 'agent review command artifacts are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"agent_review_suggestion_revisions_no_delete\",\n \"sql\": \"CREATE TRIGGER agent_review_suggestion_revisions_no_delete\\n BEFORE DELETE ON agent_review_suggestion_revisions\\n WHEN NOT EXISTS (\\n SELECT 1 FROM retention_cleanup_claims claim\\n JOIN retention_cleanup_runs run\\n ON run.workspace_id = claim.workspace_id\\n AND run.run_id = claim.run_id\\n AND run.retention_class = claim.retention_class\\n JOIN agent_jobs job\\n ON job.workspace_id = OLD.workspace_id\\n AND job.job_id = OLD.source_job_id\\n WHERE claim.workspace_id = OLD.workspace_id\\n AND claim.retention_class = 'agent-content'\\n AND claim.record_key = OLD.source_job_id\\n AND job.terminal_at IS NOT NULL\\n AND job.terminal_at <= run.cutoff_at\\n AND OLD.created_at <= run.cutoff_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'agent review suggestion revisions are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"agent_review_suggestion_revisions_no_update\",\n \"sql\": \"CREATE TRIGGER agent_review_suggestion_revisions_no_update\\n BEFORE UPDATE ON agent_review_suggestion_revisions\\n BEGIN\\n SELECT RAISE(ABORT, 'agent review suggestion revisions are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"agent_thread_events_no_delete\",\n \"sql\": \"CREATE TRIGGER agent_thread_events_no_delete\\n BEFORE DELETE ON agent_thread_events\\n WHEN NOT EXISTS (\\n SELECT 1 FROM retention_cleanup_claims claim\\n JOIN retention_cleanup_runs run\\n ON run.workspace_id = claim.workspace_id\\n AND run.run_id = claim.run_id\\n AND run.retention_class = claim.retention_class\\n JOIN agent_jobs job\\n ON job.workspace_id = OLD.workspace_id\\n AND job.job_id = OLD.job_id\\n WHERE claim.workspace_id = OLD.workspace_id\\n AND claim.retention_class = 'agent-content'\\n AND claim.record_key = OLD.job_id\\n AND job.terminal_at IS NOT NULL\\n AND job.terminal_at <= run.cutoff_at\\n AND OLD.occurred_at <= run.cutoff_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'agent thread events are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"agent_thread_events_no_update\",\n \"sql\": \"CREATE TRIGGER agent_thread_events_no_update\\n BEFORE UPDATE ON agent_thread_events\\n BEGIN\\n SELECT RAISE(ABORT, 'agent thread events are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"audit_events_no_delete\",\n \"sql\": \"CREATE TRIGGER audit_events_no_delete\\n BEFORE DELETE ON audit_events\\n BEGIN\\n SELECT RAISE(ABORT, 'audit_events is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"audit_events_no_update\",\n \"sql\": \"CREATE TRIGGER audit_events_no_update\\n BEFORE UPDATE ON audit_events\\n BEGIN\\n SELECT RAISE(ABORT, 'audit_events is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"authorized_share_current_present_target\",\n \"sql\": \"CREATE TRIGGER authorized_share_current_present_target\\n BEFORE INSERT ON authorized_share_grants\\n WHEN NOT EXISTS (\\n SELECT 1\\n FROM entity_projection_revisions projection\\n JOIN entities entity\\n ON entity.workspace_id = projection.workspace_id\\n AND entity.entity_id = projection.entity_id\\n WHERE projection.workspace_id = NEW.workspace_id\\n AND projection.entity_id = NEW.entity_id\\n AND projection.projection_revision = (\\n SELECT MAX(current_projection.projection_revision)\\n FROM entity_projection_revisions current_projection\\n WHERE current_projection.workspace_id = NEW.workspace_id\\n AND current_projection.entity_id = NEW.entity_id\\n )\\n AND projection.source_entity_revision = entity.current_revision\\n AND projection.entity_state = 'present'\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'authorized share requires a current present entity');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"authorized_share_grants_no_delete\",\n \"sql\": \"CREATE TRIGGER authorized_share_grants_no_delete\\n BEFORE DELETE ON authorized_share_grants\\n BEGIN\\n SELECT RAISE(ABORT, 'authorized share grants are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"authorized_share_grants_no_update\",\n \"sql\": \"CREATE TRIGGER authorized_share_grants_no_update\\n BEFORE UPDATE ON authorized_share_grants\\n BEGIN\\n SELECT RAISE(ABORT, 'authorized share grants are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"authorized_share_owner_origin\",\n \"sql\": \"CREATE TRIGGER authorized_share_owner_origin\\n BEFORE INSERT ON authorized_share_grants\\n WHEN NOT EXISTS (\\n SELECT 1\\n FROM sessions session\\n WHERE session.workspace_id = NEW.workspace_id\\n AND session.session_id = NEW.created_by_session_id\\n AND session.actor_kind = 'human'\\n AND session.person_id = NEW.created_by_person_id\\n AND session.agent_id IS NULL\\n AND session.permission = 'workspace-owner'\\n AND session.revoked_at IS NULL\\n AND session.created_at <= NEW.created_at\\n AND session.idle_expires_at > NEW.created_at\\n AND session.absolute_expires_at > NEW.created_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'authorized share requires current human owner authority');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"authorized_share_revocation_owner_authority\",\n \"sql\": \"CREATE TRIGGER authorized_share_revocation_owner_authority\\n BEFORE INSERT ON authorized_share_revocations\\n WHEN NOT EXISTS (\\n SELECT 1\\n FROM authorized_share_grants grant_record\\n JOIN sessions session\\n ON session.workspace_id = NEW.workspace_id\\n AND session.session_id = NEW.revoked_by_session_id\\n WHERE grant_record.workspace_id = NEW.workspace_id\\n AND grant_record.share_id = NEW.share_id\\n AND grant_record.created_at <= NEW.revoked_at\\n AND session.actor_kind = 'human'\\n AND session.person_id = NEW.revoked_by_person_id\\n AND session.agent_id IS NULL\\n AND session.permission = 'workspace-owner'\\n AND session.revoked_at IS NULL\\n AND session.created_at <= NEW.revoked_at\\n AND session.idle_expires_at > NEW.revoked_at\\n AND session.absolute_expires_at > NEW.revoked_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'authorized share revocation requires current human owner authority');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"authorized_share_revocations_no_delete\",\n \"sql\": \"CREATE TRIGGER authorized_share_revocations_no_delete\\n BEFORE DELETE ON authorized_share_revocations\\n BEGIN\\n SELECT RAISE(ABORT, 'authorized share revocations are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"authorized_share_revocations_no_update\",\n \"sql\": \"CREATE TRIGGER authorized_share_revocations_no_update\\n BEFORE UPDATE ON authorized_share_revocations\\n BEGIN\\n SELECT RAISE(ABORT, 'authorized share revocations are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"delivery_nodes_entity_kind\",\n \"sql\": \"CREATE TRIGGER delivery_nodes_entity_kind\\n BEFORE INSERT ON delivery_nodes\\n WHEN NEW.resolution_state = 'resolved' AND NEW.node_kind = 'entity' AND NOT EXISTS (\\n SELECT 1\\n FROM entities\\n WHERE workspace_id = NEW.workspace_id\\n AND entity_id = NEW.entity_id\\n AND CASE entity_type\\n WHEN 'pipeline' THEN 'pipeline-execution'\\n ELSE entity_type\\n END = NEW.endpoint_kind\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'delivery node kind must match its canonical entity');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"delivery_nodes_no_delete\",\n \"sql\": \"CREATE TRIGGER delivery_nodes_no_delete\\n BEFORE DELETE ON delivery_nodes\\n BEGIN\\n SELECT RAISE(ABORT, 'delivery nodes are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"delivery_nodes_no_update\",\n \"sql\": \"CREATE TRIGGER delivery_nodes_no_update\\n BEFORE UPDATE ON delivery_nodes\\n BEGIN\\n SELECT RAISE(ABORT, 'delivery nodes are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"entity_projection_revisions_chronological\",\n \"sql\": \"CREATE TRIGGER entity_projection_revisions_chronological\\n BEFORE INSERT ON entity_projection_revisions\\n WHEN NEW.supersedes_projection_revision IS NOT NULL AND NEW.recorded_at < (\\n SELECT recorded_at\\n FROM entity_projection_revisions\\n WHERE workspace_id = NEW.workspace_id\\n AND entity_id = NEW.entity_id\\n AND projection_revision = NEW.supersedes_projection_revision\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'entity projection revisions must be chronological');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"entity_projection_revisions_entity_kind\",\n \"sql\": \"CREATE TRIGGER entity_projection_revisions_entity_kind\\n BEFORE INSERT ON entity_projection_revisions\\n WHEN NOT EXISTS (\\n SELECT 1\\n FROM entities\\n WHERE workspace_id = NEW.workspace_id\\n AND entity_id = NEW.entity_id\\n AND CASE entity_type\\n WHEN 'pipeline' THEN 'pipeline-execution'\\n ELSE entity_type\\n END = json_extract(NEW.extension_json, '$._tag')\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'entity projection kind must match its canonical entity');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"entity_projection_revisions_no_delete\",\n \"sql\": \"CREATE TRIGGER entity_projection_revisions_no_delete\\n BEFORE DELETE ON entity_projection_revisions\\n BEGIN\\n SELECT RAISE(ABORT, 'entity projection revisions are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"entity_projection_revisions_no_update\",\n \"sql\": \"CREATE TRIGGER entity_projection_revisions_no_update\\n BEFORE UPDATE ON entity_projection_revisions\\n BEGIN\\n SELECT RAISE(ABORT, 'entity projection revisions are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"entity_projection_revisions_source_monotonic\",\n \"sql\": \"CREATE TRIGGER entity_projection_revisions_source_monotonic\\n BEFORE INSERT ON entity_projection_revisions\\n WHEN NEW.supersedes_projection_revision IS NOT NULL AND\\n NEW.source_entity_revision < (\\n SELECT source_entity_revision\\n FROM entity_projection_revisions\\n WHERE workspace_id = NEW.workspace_id\\n AND entity_id = NEW.entity_id\\n AND projection_revision = NEW.supersedes_projection_revision\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'entity projection source revisions must not regress');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"evidence_claims_after_evidence\",\n \"sql\": \"CREATE TRIGGER evidence_claims_after_evidence\\n BEFORE INSERT ON evidence_claims\\n WHEN NOT EXISTS (\\n SELECT 1\\n FROM evidence_items\\n WHERE workspace_id = NEW.workspace_id\\n AND evidence_id = NEW.evidence_id\\n AND recorded_at <= NEW.recorded_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'evidence claims must not predate their evidence');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"evidence_claims_chronological\",\n \"sql\": \"CREATE TRIGGER evidence_claims_chronological\\n BEFORE INSERT ON evidence_claims\\n WHEN NEW.supersedes_claim_id IS NOT NULL AND NEW.recorded_at < (\\n SELECT recorded_at\\n FROM evidence_claims\\n WHERE workspace_id = NEW.workspace_id\\n AND evidence_claim_id = NEW.supersedes_claim_id\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'evidence claim supersession must be chronological');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"evidence_claims_no_delete\",\n \"sql\": \"CREATE TRIGGER evidence_claims_no_delete\\n BEFORE DELETE ON evidence_claims\\n BEGIN\\n SELECT RAISE(ABORT, 'evidence claims are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"evidence_claims_no_update\",\n \"sql\": \"CREATE TRIGGER evidence_claims_no_update\\n BEFORE UPDATE ON evidence_claims\\n BEGIN\\n SELECT RAISE(ABORT, 'evidence claims are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"evidence_claims_same_fact\",\n \"sql\": \"CREATE TRIGGER evidence_claims_same_fact\\n BEFORE INSERT ON evidence_claims\\n WHEN NEW.supersedes_claim_id IS NOT NULL AND NOT EXISTS (\\n SELECT 1\\n FROM evidence_claims\\n WHERE workspace_id = NEW.workspace_id\\n AND evidence_claim_id = NEW.supersedes_claim_id\\n AND subject_node_id = NEW.subject_node_id\\n AND predicate = NEW.predicate\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'evidence claim supersession must preserve fact identity');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"evidence_items_freshness_connection\",\n \"sql\": \"CREATE TRIGGER evidence_items_freshness_connection\\n BEFORE INSERT ON evidence_items\\n WHEN NEW.origin_kind = 'plugin' AND NOT EXISTS (\\n SELECT 1\\n FROM entities entity\\n INNER JOIN entity_revisions revision\\n ON revision.workspace_id = entity.workspace_id\\n AND revision.entity_id = entity.entity_id\\n WHERE entity.workspace_id = NEW.workspace_id\\n AND entity.entity_id = NEW.source_entity_id\\n AND revision.revision = NEW.source_entity_revision\\n AND json_extract(NEW.freshness_json, '$.provenance._tag') IN ('provider', 'cache')\\n AND entity.plugin_connection_id =\\n json_extract(NEW.freshness_json, '$.provenance.sourceRevision.pluginConnectionId')\\n AND entity.provider_id =\\n json_extract(NEW.freshness_json, '$.provenance.sourceRevision.providerId')\\n AND entity.vendor_immutable_id =\\n json_extract(NEW.freshness_json, '$.provenance.sourceRevision.vendorImmutableId')\\n AND revision.source_revision =\\n json_extract(NEW.freshness_json, '$.provenance.sourceRevision.revision')\\n AND revision.source_url IS\\n json_extract(NEW.freshness_json, '$.provenance.sourceRevision.sourceUrl')\\n AND revision.first_observed_at =\\n json_extract(NEW.freshness_json, '$.provenance.sourceRevision.firstObservedAt')\\n AND revision.last_observed_at =\\n json_extract(NEW.freshness_json, '$.provenance.sourceRevision.lastObservedAt')\\n AND revision.synchronized_at =\\n json_extract(NEW.freshness_json, '$.provenance.sourceRevision.synchronizedAt')\\n AND revision.normalization_schema_version =\\n json_extract(NEW.freshness_json, '$.provenance.sourceRevision.normalizationSchemaVersion')\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'plugin evidence attribution must match its exact freshness source revision');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"evidence_items_no_delete\",\n \"sql\": \"CREATE TRIGGER evidence_items_no_delete\\n BEFORE DELETE ON evidence_items\\n WHEN NOT EXISTS (\\n SELECT 1 FROM retention_cleanup_claims claim\\n JOIN retention_cleanup_runs run\\n ON run.workspace_id = claim.workspace_id\\n AND run.run_id = claim.run_id\\n AND run.retention_class = claim.retention_class\\n WHERE claim.workspace_id = OLD.workspace_id\\n AND claim.retention_class = 'evidence'\\n AND claim.record_key = OLD.evidence_id\\n AND OLD.legal_hold = 0\\n AND OLD.retain_until IS NOT NULL\\n AND OLD.retain_until <= run.cutoff_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'evidence items are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"evidence_items_no_update\",\n \"sql\": \"CREATE TRIGGER evidence_items_no_update\\n BEFORE UPDATE ON evidence_items\\n BEGIN\\n SELECT RAISE(ABORT, 'evidence items are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"evidence_items_plugin_source_owner\",\n \"sql\": \"CREATE TRIGGER evidence_items_plugin_source_owner\\n BEFORE INSERT ON evidence_items\\n WHEN NEW.origin_kind = 'plugin' AND NOT EXISTS (\\n SELECT 1\\n FROM entities\\n WHERE workspace_id = NEW.workspace_id\\n AND entity_id = NEW.source_entity_id\\n AND plugin_connection_id = NEW.plugin_connection_id\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'plugin evidence must reference an entity owned by the same connection');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_attempt_allowed_policy\",\n \"sql\": \"CREATE TRIGGER governed_action_attempt_allowed_policy\\n BEFORE INSERT ON governed_action_attempts\\n WHEN NOT EXISTS (\\n SELECT 1\\n FROM governed_action_policy_evaluations evaluation\\n JOIN governed_action_authorizations authorization\\n ON authorization.workspace_id = NEW.workspace_id\\n AND authorization.action_id = NEW.action_id\\n AND authorization.authorization_id = NEW.authorization_id\\n JOIN sessions session\\n ON session.workspace_id = authorization.workspace_id\\n AND session.session_id = authorization.session_id\\n WHERE evaluation.workspace_id = NEW.workspace_id\\n AND evaluation.action_id = NEW.action_id\\n AND evaluation.evaluation_digest = NEW.policy_evaluation_digest\\n AND evaluation.decision = 'allowed'\\n AND evaluation.evaluated_at <= NEW.started_at\\n AND authorization.authorized_at <= NEW.started_at\\n AND NEW.started_at < authorization.expires_at\\n AND session.actor_kind = 'human'\\n AND session.revoked_at IS NULL\\n AND session.created_at <= NEW.started_at\\n AND session.last_seen_at <= NEW.started_at\\n AND NEW.started_at < session.idle_expires_at\\n AND NEW.started_at < session.absolute_expires_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action attempt requires an exact allowed policy evaluation');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_attempts_no_delete\",\n \"sql\": \"CREATE TRIGGER governed_action_attempts_no_delete\\n BEFORE DELETE ON governed_action_attempts\\n BEGIN\\n SELECT RAISE(ABORT, 'governed_action_attempts is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_attempts_no_update\",\n \"sql\": \"CREATE TRIGGER governed_action_attempts_no_update\\n BEFORE UPDATE ON governed_action_attempts\\n BEGIN\\n SELECT RAISE(ABORT, 'governed_action_attempts is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_audit_exact_transition\",\n \"sql\": \"CREATE TRIGGER governed_action_audit_exact_transition\\n BEFORE INSERT ON audit_events\\n WHEN NOT EXISTS (\\n SELECT 1\\n FROM governed_action_transitions transition_record\\n LEFT JOIN sessions session\\n ON session.workspace_id = NEW.workspace_id AND session.session_id = NEW.session_id\\n WHERE transition_record.workspace_id = NEW.workspace_id\\n AND transition_record.action_id = NEW.action_id\\n AND transition_record.transition_id = NEW.transition_id\\n AND transition_record.to_state = NEW.event_kind\\n AND transition_record.occurred_at = NEW.occurred_at\\n AND transition_record.cause_kind = NEW.cause_kind\\n AND transition_record.cause_actor_id IS NEW.actor_id\\n AND transition_record.cause_session_id IS NEW.session_id\\n AND transition_record.cause_job_id IS NEW.job_id\\n AND transition_record.cause_system_component IS NEW.system_component\\n AND transition_record.causation_id IS NEW.causation_id\\n AND transition_record.correlation_id IS NEW.correlation_id\\n AND transition_record.transition_digest = NEW.payload_digest\\n AND (NEW.cause_kind <> 'human' OR\\n (session.actor_kind = 'human' AND session.person_id = NEW.actor_id))\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'audit event must attribute its exact governed action transition');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_authorization_current_human_session\",\n \"sql\": \"CREATE TRIGGER governed_action_authorization_current_human_session\\n BEFORE INSERT ON governed_action_authorizations\\n WHEN NOT EXISTS (\\n SELECT 1 FROM sessions session\\n WHERE session.workspace_id = NEW.workspace_id\\n AND session.session_id = NEW.session_id\\n AND session.actor_kind = 'human'\\n AND session.revoked_at IS NULL\\n AND session.created_at <= NEW.authorized_at\\n AND session.last_seen_at <= NEW.authorized_at\\n AND NEW.authorized_at < session.idle_expires_at\\n AND NEW.authorized_at < session.absolute_expires_at\\n AND NEW.expires_at <= session.idle_expires_at\\n AND NEW.expires_at <= session.absolute_expires_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action authorization requires a current human session');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_authorizations_no_delete\",\n \"sql\": \"CREATE TRIGGER governed_action_authorizations_no_delete\\n BEFORE DELETE ON governed_action_authorizations\\n BEGIN\\n SELECT RAISE(ABORT, 'governed_action_authorizations is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_authorizations_no_update\",\n \"sql\": \"CREATE TRIGGER governed_action_authorizations_no_update\\n BEFORE UPDATE ON governed_action_authorizations\\n BEGIN\\n SELECT RAISE(ABORT, 'governed_action_authorizations is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_denial_policy_evaluations_no_delete\",\n \"sql\": \"CREATE TRIGGER governed_action_denial_policy_evaluations_no_delete\\n BEFORE DELETE ON governed_action_denial_policy_evaluations\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action denial policy ownership is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_denial_policy_evaluations_no_update\",\n \"sql\": \"CREATE TRIGGER governed_action_denial_policy_evaluations_no_update\\n BEFORE UPDATE ON governed_action_denial_policy_evaluations\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action denial policy ownership is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_denial_policy_exact_owner\",\n \"sql\": \"CREATE TRIGGER governed_action_denial_policy_exact_owner\\n BEFORE INSERT ON governed_action_denial_policy_evaluations\\n WHEN NOT EXISTS (\\n SELECT 1\\n FROM governed_action_transitions transition_record\\n JOIN governed_action_policy_evaluations evaluation\\n ON evaluation.workspace_id = NEW.workspace_id\\n AND evaluation.action_id = NEW.action_id\\n AND evaluation.evaluation_digest = NEW.policy_evaluation_digest\\n WHERE transition_record.workspace_id = NEW.workspace_id\\n AND transition_record.action_id = NEW.action_id\\n AND transition_record.transition_id = NEW.transition_id\\n AND transition_record.command_tag = 'deny'\\n AND evaluation.decision = 'denied'\\n AND evaluation.evaluated_at <= transition_record.occurred_at\\n AND NOT EXISTS (\\n SELECT 1\\n FROM audit_events audit\\n WHERE audit.workspace_id = transition_record.workspace_id\\n AND audit.action_id = transition_record.action_id\\n AND audit.transition_id = transition_record.transition_id\\n )\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'denial policy evaluation must belong to its exact deny transition');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_entity_targets_exact\",\n \"sql\": \"CREATE TRIGGER governed_action_entity_targets_exact\\n BEFORE INSERT ON governed_action_entity_targets\\n WHEN NOT EXISTS (\\n SELECT 1 FROM governed_actions action\\n WHERE action.workspace_id = NEW.workspace_id\\n AND action.action_id = NEW.action_id\\n AND action.plugin_connection_id = NEW.plugin_connection_id\\n AND action.provider_id = NEW.provider_id\\n AND action.target_entity_id = NEW.entity_id\\n AND json_type(action.envelope_json, '$.releasePublication') IS NULL\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action entity target must match the immutable envelope');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_entity_targets_no_delete\",\n \"sql\": \"CREATE TRIGGER governed_action_entity_targets_no_delete\\n BEFORE DELETE ON governed_action_entity_targets\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action entity targets are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_entity_targets_no_update\",\n \"sql\": \"CREATE TRIGGER governed_action_entity_targets_no_update\\n BEFORE UPDATE ON governed_action_entity_targets\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action entity targets are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_execution_lease_exact_start\",\n \"sql\": \"CREATE TRIGGER governed_action_execution_lease_exact_start\\n BEFORE INSERT ON governed_action_execution_leases\\n WHEN NOT EXISTS (\\n SELECT 1\\n FROM governed_actions action\\n JOIN governed_action_transitions transition_record\\n ON transition_record.workspace_id = action.workspace_id\\n AND transition_record.action_id = action.action_id\\n AND transition_record.transition_id = NEW.start_transition_id\\n WHERE action.workspace_id = NEW.workspace_id\\n AND action.action_id = NEW.action_id\\n AND action.state = 'started'\\n AND action.head_transition_id = NEW.start_transition_id\\n AND transition_record.command_tag = 'start'\\n AND transition_record.attempt_id = NEW.attempt_id\\n AND transition_record.occurred_at = NEW.created_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action execution lease requires its exact start transition');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_execution_leases_no_delete\",\n \"sql\": \"CREATE TRIGGER governed_action_execution_leases_no_delete\\n BEFORE DELETE ON governed_action_execution_leases\\n BEGIN\\n SELECT RAISE(ABORT, 'governed_action_execution_leases is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_execution_leases_no_update\",\n \"sql\": \"CREATE TRIGGER governed_action_execution_leases_no_update\\n BEFORE UPDATE ON governed_action_execution_leases\\n BEGIN\\n SELECT RAISE(ABORT, 'governed_action_execution_leases is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_execution_preparation_exact_head\",\n \"sql\": \"CREATE TRIGGER governed_action_execution_preparation_exact_head\\n BEFORE INSERT ON governed_action_execution_preparations\\n WHEN NOT EXISTS (\\n SELECT 1\\n FROM governed_actions action\\n JOIN governed_action_transitions transition_record\\n ON transition_record.workspace_id = action.workspace_id\\n AND transition_record.action_id = action.action_id\\n AND transition_record.transition_id = action.head_transition_id\\n WHERE action.workspace_id = NEW.workspace_id\\n AND action.action_id = NEW.action_id\\n AND action.state = 'authorized'\\n AND action.head_transition_id = NEW.expected_head_transition_id\\n AND action.envelope_digest = NEW.expected_envelope_digest\\n AND transition_record.to_state = 'authorized'\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action execution preparation requires the current authorized head');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_execution_preparations_no_update\",\n \"sql\": \"CREATE TRIGGER governed_action_execution_preparations_no_update\\n BEFORE UPDATE ON governed_action_execution_preparations\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action execution preparation is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_head_exact_update\",\n \"sql\": \"CREATE TRIGGER governed_action_head_exact_update\\n BEFORE UPDATE ON governed_actions\\n WHEN NOT EXISTS (\\n SELECT 1 FROM governed_action_transitions transition_record\\n WHERE transition_record.workspace_id = NEW.workspace_id\\n AND transition_record.action_id = NEW.action_id\\n AND transition_record.transition_id = NEW.head_transition_id\\n AND transition_record.sequence = NEW.head_sequence\\n AND transition_record.to_state = NEW.state\\n AND transition_record.result_lineage_json = NEW.lineage_json\\n AND transition_record.result_lineage_kind = NEW.lineage_kind\\n AND transition_record.result_provider_operation_id IS NEW.provider_operation_id\\n AND transition_record.result_reconciliation_key IS NEW.reconciliation_key\\n AND transition_record.result_terminal_status IS NEW.terminal_status\\n AND NEW.updated_at = transition_record.occurred_at\\n AND NEW.updated_at >= OLD.updated_at\\n AND EXISTS (\\n SELECT 1 FROM audit_events audit\\n WHERE audit.workspace_id = NEW.workspace_id\\n AND audit.action_id = NEW.action_id\\n AND audit.transition_id = NEW.head_transition_id\\n )\\n AND (\\n (OLD.head_sequence IS NULL AND NEW.head_sequence = 1\\n AND transition_record.previous_transition_id IS NULL AND transition_record.from_state IS NULL) OR\\n (OLD.head_sequence IS NOT NULL AND NEW.head_sequence = OLD.head_sequence + 1\\n AND transition_record.previous_transition_id = OLD.head_transition_id\\n AND transition_record.from_state = OLD.state)\\n )\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action head must advance to its exact transition');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_identity_immutable\",\n \"sql\": \"CREATE TRIGGER governed_action_identity_immutable\\n BEFORE UPDATE ON governed_actions\\n WHEN OLD.workspace_id <> NEW.workspace_id OR OLD.action_id <> NEW.action_id\\n OR OLD.plugin_connection_id <> NEW.plugin_connection_id OR OLD.provider_id <> NEW.provider_id\\n OR OLD.target_entity_id <> NEW.target_entity_id OR OLD.idempotency_key <> NEW.idempotency_key\\n OR OLD.envelope_digest <> NEW.envelope_digest OR OLD.envelope_json <> NEW.envelope_json\\n OR OLD.created_at <> NEW.created_at\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action identity is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_initial_head_empty\",\n \"sql\": \"CREATE TRIGGER governed_action_initial_head_empty\\n BEFORE INSERT ON governed_actions\\n WHEN NEW.state IS NOT NULL OR NEW.lineage_json IS NOT NULL OR NEW.lineage_kind IS NOT NULL\\n OR NEW.provider_operation_id IS NOT NULL OR NEW.reconciliation_key IS NOT NULL\\n OR NEW.terminal_status IS NOT NULL OR NEW.head_transition_id IS NOT NULL\\n OR NEW.head_sequence IS NOT NULL\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action must begin without a fabricated head');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_legacy_recovery_unavailable_outcomes_no_delete\",\n \"sql\": \"CREATE TRIGGER governed_action_legacy_recovery_unavailable_outcomes_no_delete\\n BEFORE DELETE ON governed_action_legacy_recovery_unavailable_outcomes\\n BEGIN\\n SELECT RAISE(ABORT, 'legacy recovery outcome markers are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_legacy_recovery_unavailable_outcomes_no_insert\",\n \"sql\": \"CREATE TRIGGER governed_action_legacy_recovery_unavailable_outcomes_no_insert\\n BEFORE INSERT ON governed_action_legacy_recovery_unavailable_outcomes\\n BEGIN\\n SELECT RAISE(ABORT, 'legacy recovery outcome markers are migration-owned');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_legacy_recovery_unavailable_outcomes_no_update\",\n \"sql\": \"CREATE TRIGGER governed_action_legacy_recovery_unavailable_outcomes_no_update\\n BEFORE UPDATE ON governed_action_legacy_recovery_unavailable_outcomes\\n BEGIN\\n SELECT RAISE(ABORT, 'legacy recovery outcome markers are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_policy_evaluations_no_delete\",\n \"sql\": \"CREATE TRIGGER governed_action_policy_evaluations_no_delete\\n BEFORE DELETE ON governed_action_policy_evaluations\\n BEGIN\\n SELECT RAISE(ABORT, 'governed_action_policy_evaluations is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_policy_evaluations_no_update\",\n \"sql\": \"CREATE TRIGGER governed_action_policy_evaluations_no_update\\n BEFORE UPDATE ON governed_action_policy_evaluations\\n BEGIN\\n SELECT RAISE(ABORT, 'governed_action_policy_evaluations is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_provider_outcome_active_lease\",\n \"sql\": \"CREATE TRIGGER governed_action_provider_outcome_active_lease\\n BEFORE INSERT ON governed_action_provider_outcomes\\n WHEN NOT (\\n (NEW.source_kind = 'dispatch' AND EXISTS (\\n SELECT 1\\n FROM governed_action_execution_leases execution\\n WHERE execution.workspace_id = NEW.workspace_id\\n AND execution.action_id = NEW.action_id\\n AND execution.permit_token_digest = NEW.permit_token_digest\\n AND (\\n (\\n NEW.result_kind IN ('succeeded', 'failed', 'cancelled')\\n AND json_valid(NEW.outcome_json)\\n AND json_extract(NEW.outcome_json, '$.receipt.observationBasis') = 'authorization'\\n AND json_extract(NEW.outcome_json, '$.receipt.status') = NEW.result_kind\\n AND json_extract(NEW.outcome_json, '$.receipt.observedAt') = NEW.observed_at\\n AND EXISTS (\\n SELECT 1\\n FROM governed_action_authorizations authorization\\n WHERE authorization.workspace_id = execution.workspace_id\\n AND authorization.action_id = execution.action_id\\n AND authorization.authorized_at = NEW.observed_at\\n )\\n ) OR (\\n CASE WHEN json_valid(NEW.outcome_json)\\n THEN json_extract(NEW.outcome_json, '$.receipt.observationBasis') END\\n IS NOT 'authorization'\\n AND execution.created_at <= NEW.observed_at\\n )\\n )\\n AND NEW.received_at < execution.lease_expires_at\\n AND (NEW.result_kind = 'manual-unknown'\\n OR NEW.observed_at < execution.dispatch_deadline)\\n AND NOT EXISTS (\\n SELECT 1\\n FROM governed_action_recovery_claims recovery\\n WHERE recovery.workspace_id = execution.workspace_id\\n AND recovery.action_id = execution.action_id\\n )\\n )) OR\\n (NEW.source_kind = 'reconciliation' AND EXISTS (\\n SELECT 1\\n FROM governed_action_recovery_claims recovery\\n WHERE recovery.workspace_id = NEW.workspace_id\\n AND recovery.action_id = NEW.action_id\\n AND recovery.claim_token_digest = NEW.recovery_claim_token_digest\\n AND (\\n (\\n NEW.result_kind IN ('succeeded', 'failed', 'cancelled')\\n AND json_valid(NEW.outcome_json)\\n AND json_extract(NEW.outcome_json, '$.receipt.observationBasis') = 'authorization'\\n AND json_extract(NEW.outcome_json, '$.receipt.status') = NEW.result_kind\\n AND json_extract(NEW.outcome_json, '$.receipt.observedAt') = NEW.observed_at\\n AND EXISTS (\\n SELECT 1\\n FROM governed_action_authorizations authorization\\n WHERE authorization.workspace_id = recovery.workspace_id\\n AND authorization.action_id = recovery.action_id\\n AND authorization.authorized_at = NEW.observed_at\\n )\\n ) OR (\\n CASE WHEN json_valid(NEW.outcome_json)\\n THEN json_extract(NEW.outcome_json, '$.receipt.observationBasis') END\\n IS NOT 'authorization'\\n AND recovery.claimed_at <= NEW.observed_at\\n )\\n )\\n AND NEW.received_at < recovery.lease_expires_at\\n AND NOT EXISTS (\\n SELECT 1\\n FROM governed_action_recovery_claim_expirations expiration\\n WHERE expiration.workspace_id = recovery.workspace_id\\n AND expiration.action_id = recovery.action_id\\n AND expiration.claim_sequence = recovery.claim_sequence\\n )\\n AND NOT EXISTS (\\n SELECT 1\\n FROM governed_action_recovery_claims later\\n WHERE later.workspace_id = recovery.workspace_id\\n AND later.action_id = recovery.action_id\\n AND later.claim_sequence > recovery.claim_sequence\\n )\\n ))\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action provider outcome requires the active execution lease');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_provider_outcome_fold_order\",\n \"sql\": \"CREATE TRIGGER governed_action_provider_outcome_fold_order\\n BEFORE INSERT ON governed_action_provider_outcome_folds\\n WHEN NOT EXISTS (\\n SELECT 1\\n FROM governed_action_provider_outcomes outcome\\n JOIN governed_actions action\\n ON action.workspace_id = outcome.workspace_id\\n AND action.action_id = outcome.action_id\\n JOIN governed_action_transitions transition_record\\n ON transition_record.workspace_id = outcome.workspace_id\\n AND transition_record.action_id = outcome.action_id\\n AND transition_record.transition_id = NEW.transition_id\\n WHERE outcome.workspace_id = NEW.workspace_id\\n AND outcome.action_id = NEW.action_id\\n AND outcome.outcome_id = NEW.outcome_id\\n AND action.head_transition_id = NEW.transition_id\\n AND outcome.received_at <= NEW.folded_at\\n AND outcome.observed_at <= transition_record.occurred_at\\n AND transition_record.occurred_at <= NEW.folded_at\\n AND outcome.expected_command_digest = transition_record.command_digest\\n AND (\\n (outcome.result_kind = 'accepted' AND transition_record.command_tag = 'recordAccepted') OR\\n (outcome.result_kind = 'succeeded' AND transition_record.command_tag = 'recordSucceeded') OR\\n (outcome.result_kind = 'failed' AND transition_record.command_tag = 'recordFailed') OR\\n (outcome.result_kind = 'cancelled' AND transition_record.command_tag = 'recordCancelled') OR\\n (outcome.result_kind IN ('unknown', 'manual-unknown')\\n AND transition_record.command_tag = 'recordUnknown') OR\\n (outcome.result_kind = 'pending'\\n AND transition_record.command_tag = 'reconciliationPending') OR\\n (outcome.result_kind = 'recovery-unavailable' AND (\\n (EXISTS (\\n SELECT 1 FROM governed_action_legacy_recovery_unavailable_outcomes legacy\\n WHERE legacy.workspace_id = outcome.workspace_id\\n AND legacy.action_id = outcome.action_id\\n AND legacy.outcome_id = outcome.outcome_id\\n ) AND transition_record.command_tag = 'recordUnknown') OR\\n (NOT EXISTS (\\n SELECT 1 FROM governed_action_legacy_recovery_unavailable_outcomes legacy\\n WHERE legacy.workspace_id = outcome.workspace_id\\n AND legacy.action_id = outcome.action_id\\n AND legacy.outcome_id = outcome.outcome_id\\n ) AND transition_record.command_tag = 'reconciliationPending')\\n ))\\n )\\n AND (\\n outcome.result_kind NOT IN ('succeeded', 'failed', 'cancelled') OR\\n (outcome.source_kind = 'reconciliation'\\n AND transition_record.outcome_source_kind = 'reconciliation') OR\\n (outcome.source_kind = 'dispatch'\\n AND transition_record.outcome_source_kind IN ('direct', 'providerOperation'))\\n )\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action provider outcome cannot fold before receipt and transition');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_provider_outcome_folds_no_delete\",\n \"sql\": \"CREATE TRIGGER governed_action_provider_outcome_folds_no_delete\\n BEFORE DELETE ON governed_action_provider_outcome_folds\\n BEGIN\\n SELECT RAISE(ABORT, 'governed_action_provider_outcome_folds is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_provider_outcome_folds_no_update\",\n \"sql\": \"CREATE TRIGGER governed_action_provider_outcome_folds_no_update\\n BEFORE UPDATE ON governed_action_provider_outcome_folds\\n BEGIN\\n SELECT RAISE(ABORT, 'governed_action_provider_outcome_folds is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_provider_outcomes_no_delete\",\n \"sql\": \"CREATE TRIGGER governed_action_provider_outcomes_no_delete\\n BEFORE DELETE ON governed_action_provider_outcomes\\n BEGIN\\n SELECT RAISE(ABORT, 'governed_action_provider_outcomes is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_provider_outcomes_no_update\",\n \"sql\": \"CREATE TRIGGER governed_action_provider_outcomes_no_update\\n BEFORE UPDATE ON governed_action_provider_outcomes\\n BEGIN\\n SELECT RAISE(ABORT, 'governed_action_provider_outcomes is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_recovery_claim_after_pending_outcome\",\n \"sql\": \"CREATE TRIGGER governed_action_recovery_claim_after_pending_outcome\\n BEFORE INSERT ON governed_action_recovery_claims\\n WHEN EXISTS (\\n SELECT 1\\n FROM governed_action_provider_outcomes outcome\\n LEFT JOIN governed_action_provider_outcome_folds fold\\n ON fold.workspace_id = outcome.workspace_id\\n AND fold.action_id = outcome.action_id\\n AND fold.outcome_id = outcome.outcome_id\\n WHERE outcome.workspace_id = NEW.workspace_id\\n AND outcome.action_id = NEW.action_id\\n AND fold.outcome_id IS NULL\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action pending provider outcome must fold before recovery');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_recovery_claim_after_safety_interval\",\n \"sql\": \"CREATE TRIGGER governed_action_recovery_claim_after_safety_interval\\n BEFORE INSERT ON governed_action_recovery_claims\\n WHEN NOT EXISTS (\\n SELECT 1\\n FROM governed_action_execution_leases execution\\n JOIN governed_actions action\\n ON action.workspace_id = execution.workspace_id\\n AND action.action_id = execution.action_id\\n WHERE execution.workspace_id = NEW.workspace_id\\n AND execution.action_id = NEW.action_id\\n AND execution.recovery_eligible_at <= NEW.claimed_at\\n AND action.state IN ('started', 'cancel-requested', 'unknown', 'cancel-requested-unknown')\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action recovery cannot begin before its safety interval');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_recovery_claim_exact_sequence\",\n \"sql\": \"CREATE TRIGGER governed_action_recovery_claim_exact_sequence\\n BEFORE INSERT ON governed_action_recovery_claims\\n WHEN NOT (\\n (NEW.claim_sequence = 1 AND NOT EXISTS (\\n SELECT 1 FROM governed_action_recovery_claims existing\\n WHERE existing.workspace_id = NEW.workspace_id AND existing.action_id = NEW.action_id\\n )) OR\\n EXISTS (\\n SELECT 1 FROM governed_action_recovery_claims previous\\n WHERE previous.workspace_id = NEW.workspace_id\\n AND previous.action_id = NEW.action_id\\n AND previous.claim_sequence = NEW.claim_sequence - 1\\n AND (previous.lease_expires_at <= NEW.claimed_at OR EXISTS (\\n SELECT 1 FROM governed_action_recovery_claim_expirations expiration\\n WHERE expiration.workspace_id = previous.workspace_id\\n AND expiration.action_id = previous.action_id\\n AND expiration.claim_sequence = previous.claim_sequence\\n AND expiration.expired_at <= NEW.claimed_at\\n ))\\n AND NOT EXISTS (\\n SELECT 1 FROM governed_action_recovery_claims later\\n WHERE later.workspace_id = NEW.workspace_id\\n AND later.action_id = NEW.action_id\\n AND later.claim_sequence >= NEW.claim_sequence\\n )\\n )\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action recovery claim must follow the expired latest claim');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_recovery_claim_expiration_exact\",\n \"sql\": \"CREATE TRIGGER governed_action_recovery_claim_expiration_exact\\n BEFORE INSERT ON governed_action_recovery_claim_expirations\\n WHEN NOT EXISTS (\\n SELECT 1\\n FROM governed_action_recovery_claims claim\\n WHERE claim.workspace_id = NEW.workspace_id\\n AND claim.action_id = NEW.action_id\\n AND claim.claim_sequence = NEW.claim_sequence\\n AND claim.claimed_at <= NEW.expired_at\\n AND NEW.expired_at < claim.lease_expires_at\\n AND NOT EXISTS (\\n SELECT 1 FROM governed_action_recovery_claims later\\n WHERE later.workspace_id = claim.workspace_id\\n AND later.action_id = claim.action_id\\n AND later.claim_sequence > claim.claim_sequence\\n )\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action recovery expiration requires the live latest claim');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_recovery_claim_expiration_no_delete\",\n \"sql\": \"CREATE TRIGGER governed_action_recovery_claim_expiration_no_delete\\n BEFORE DELETE ON governed_action_recovery_claim_expirations\\n BEGIN\\n SELECT RAISE(ABORT, 'governed_action_recovery_claim_expirations is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_recovery_claim_expiration_no_update\",\n \"sql\": \"CREATE TRIGGER governed_action_recovery_claim_expiration_no_update\\n BEFORE UPDATE ON governed_action_recovery_claim_expirations\\n BEGIN\\n SELECT RAISE(ABORT, 'governed_action_recovery_claim_expirations is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_recovery_claims_no_delete\",\n \"sql\": \"CREATE TRIGGER governed_action_recovery_claims_no_delete\\n BEFORE DELETE ON governed_action_recovery_claims\\n BEGIN\\n SELECT RAISE(ABORT, 'governed_action_recovery_claims is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_recovery_claims_no_update\",\n \"sql\": \"CREATE TRIGGER governed_action_recovery_claims_no_update\\n BEFORE UPDATE ON governed_action_recovery_claims\\n BEGIN\\n SELECT RAISE(ABORT, 'governed_action_recovery_claims is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_release_publication_slots_exact\",\n \"sql\": \"CREATE TRIGGER governed_action_release_publication_slots_exact\\n BEFORE INSERT ON governed_action_release_publication_slots\\n WHEN NOT EXISTS (\\n SELECT 1 FROM governed_action_release_publications publication\\n WHERE publication.workspace_id = NEW.workspace_id\\n AND publication.action_id = NEW.action_id\\n AND publication.provider_id = NEW.provider_id\\n AND publication.release_id = NEW.release_id\\n AND publication.predecessor_action_id IS NEW.predecessor_action_id\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action release publication slot must match immutable publication history');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_release_publication_slots_release\",\n \"sql\": \"CREATE TRIGGER governed_action_release_publication_slots_release\\n AFTER UPDATE OF state ON governed_actions\\n WHEN NEW.state IN ('denied', 'expired', 'cancelled', 'failed')\\n BEGIN\\n DELETE FROM governed_action_release_publication_slots\\n WHERE workspace_id = NEW.workspace_id AND action_id = NEW.action_id;\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_release_publications_exact\",\n \"sql\": \"CREATE TRIGGER governed_action_release_publications_exact\\n BEFORE INSERT ON governed_action_release_publications\\n WHEN NOT EXISTS (\\n SELECT 1 FROM governed_actions action\\n WHERE action.workspace_id = NEW.workspace_id\\n AND action.action_id = NEW.action_id\\n AND action.provider_id = NEW.provider_id\\n AND json_extract(action.envelope_json, '$.releasePublication.releaseId') = NEW.release_id\\n AND json_extract(action.envelope_json, '$.releasePublication.predecessorPublicationActionId') IS NEW.predecessor_action_id\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action release publication must match the immutable envelope');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_release_publications_no_delete\",\n \"sql\": \"CREATE TRIGGER governed_action_release_publications_no_delete\\n BEFORE DELETE ON governed_action_release_publications\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action release publications are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_release_publications_no_update\",\n \"sql\": \"CREATE TRIGGER governed_action_release_publications_no_update\\n BEFORE UPDATE ON governed_action_release_publications\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action release publications are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_target_authority_exact\",\n \"sql\": \"CREATE TRIGGER governed_action_target_authority_exact\\n BEFORE INSERT ON governed_actions\\n WHEN NOT EXISTS (\\n SELECT 1 FROM entities entity\\n WHERE entity.workspace_id = NEW.workspace_id\\n AND entity.entity_id = NEW.target_entity_id\\n AND entity.plugin_connection_id = NEW.plugin_connection_id\\n AND entity.provider_id = NEW.provider_id\\n ) AND NOT (\\n json_valid(NEW.envelope_json)\\n AND json_extract(NEW.envelope_json, '$.releasePublication.releaseId') = NEW.target_entity_id\\n AND (\\n (\\n NEW.provider_id = 'jira'\\n AND json_extract(NEW.envelope_json, '$.proposal.request.actionKind') = 'create-release-version'\\n AND json_extract(NEW.envelope_json, '$.proposal.request.target.entityType') = 'jira.project-version'\\n ) OR (\\n NEW.provider_id = 'confluence'\\n AND (\\n (\\n json_extract(NEW.envelope_json, '$.proposal.request.actionKind') = 'create-page'\\n AND json_extract(NEW.envelope_json, '$.proposal.request.target.entityType') = 'release-page'\\n ) OR (\\n json_extract(NEW.envelope_json, '$.proposal.request.actionKind') = 'update-page'\\n AND json_extract(NEW.envelope_json, '$.proposal.request.target.entityType') = 'page'\\n )\\n )\\n )\\n )\\n AND EXISTS (\\n SELECT 1 FROM releases release\\n WHERE release.workspace_id = NEW.workspace_id\\n AND release.release_id = NEW.target_entity_id\\n )\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action target must be an exact entity or supported release publication');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_target_dimensions_exact\",\n \"sql\": \"CREATE TRIGGER governed_action_target_dimensions_exact\\n BEFORE INSERT ON governed_action_target_dimensions\\n WHEN NOT EXISTS (\\n SELECT 1 FROM governed_actions action\\n WHERE action.workspace_id = NEW.workspace_id\\n AND action.action_id = NEW.action_id\\n AND json_extract(action.envelope_json, '$.proposal.request.actionKind') = NEW.action_kind\\n AND json_extract(action.envelope_json, '$.proposal.request.expectedRevision') = NEW.expected_revision\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action target dimensions must match the immutable envelope');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_target_dimensions_no_delete\",\n \"sql\": \"CREATE TRIGGER governed_action_target_dimensions_no_delete\\n BEFORE DELETE ON governed_action_target_dimensions\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action target dimensions are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_target_dimensions_no_update\",\n \"sql\": \"CREATE TRIGGER governed_action_target_dimensions_no_update\\n BEFORE UPDATE ON governed_action_target_dimensions\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action target dimensions are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_transition_exact_append\",\n \"sql\": \"CREATE TRIGGER governed_action_transition_exact_append\\n BEFORE INSERT ON governed_action_transitions\\n WHEN NOT EXISTS (\\n SELECT 1 FROM governed_actions action\\n WHERE action.workspace_id = NEW.workspace_id\\n AND action.action_id = NEW.action_id\\n AND action.envelope_digest = NEW.envelope_digest\\n AND NEW.occurred_at >= action.created_at\\n AND (\\n (NEW.cause_kind = 'human' AND EXISTS (\\n SELECT 1 FROM sessions session\\n WHERE session.workspace_id = NEW.workspace_id\\n AND session.session_id = NEW.cause_session_id\\n AND session.actor_kind = 'human'\\n AND session.person_id = NEW.cause_actor_id\\n AND session.revoked_at IS NULL\\n AND session.created_at <= NEW.occurred_at\\n AND session.last_seen_at <= NEW.occurred_at\\n AND NEW.occurred_at < session.idle_expires_at\\n AND NEW.occurred_at < session.absolute_expires_at\\n )) OR NEW.cause_kind IN ('agent', 'system')\\n )\\n AND (\\n NEW.command_tag <> 'authorize' OR EXISTS (\\n SELECT 1 FROM governed_action_authorizations authorization\\n WHERE authorization.workspace_id = NEW.workspace_id\\n AND authorization.action_id = NEW.action_id\\n AND authorization.authorization_id = NEW.authorization_id\\n AND authorization.session_id = NEW.cause_session_id\\n AND authorization.authorized_at = NEW.occurred_at\\n )\\n )\\n AND (\\n NEW.command_tag <> 'start' OR EXISTS (\\n SELECT 1 FROM governed_action_attempts attempt\\n WHERE attempt.workspace_id = NEW.workspace_id\\n AND attempt.action_id = NEW.action_id\\n AND attempt.attempt_id = NEW.attempt_id\\n AND attempt.started_at = NEW.occurred_at\\n )\\n )\\n AND (\\n (NEW.command_tag = 'propose' AND NEW.result_lineage_kind = 'none') OR\\n (NEW.command_tag IN (\\n 'authorize', 'deny', 'expire', 'cancel', 'start', 'requestCancellation'\\n )\\n AND NEW.result_lineage_json IS action.lineage_json\\n AND NEW.result_lineage_kind IS action.lineage_kind\\n AND NEW.result_provider_operation_id IS action.provider_operation_id\\n AND NEW.result_reconciliation_key IS action.reconciliation_key\\n AND NEW.result_terminal_status IS action.terminal_status) OR\\n (NEW.command_tag = 'recordAccepted'\\n AND NEW.result_lineage_kind = 'accepted'\\n AND NEW.result_provider_operation_id = NEW.command_provider_operation_id\\n AND NEW.result_reconciliation_key = NEW.command_reconciliation_key\\n AND NEW.result_terminal_status IS NULL\\n AND (\\n action.lineage_kind = 'none' OR\\n (action.lineage_kind = 'accepted'\\n AND action.provider_operation_id = NEW.command_provider_operation_id\\n AND action.reconciliation_key = NEW.command_reconciliation_key)\\n )) OR\\n (NEW.command_tag = 'recordUnknown'\\n AND NEW.result_provider_operation_id IS action.provider_operation_id\\n AND NEW.result_terminal_status IS NULL\\n AND (\\n (NEW.command_unknown_kind = 'reconcilable'\\n AND NEW.result_lineage_kind = 'reconcilable'\\n AND NEW.result_reconciliation_key = NEW.command_reconciliation_key) OR\\n (NEW.command_unknown_kind = 'manual'\\n AND (\\n (action.reconciliation_key IS NULL\\n AND NEW.result_lineage_kind = 'manual'\\n AND NEW.result_reconciliation_key IS NULL) OR\\n (action.reconciliation_key IS NOT NULL\\n AND NEW.result_lineage_kind = 'reconcilable'\\n AND NEW.result_reconciliation_key = action.reconciliation_key)\\n ))\\n )) OR\\n (NEW.command_tag = 'reconciliationPending'\\n AND (\\n (NEW.command_reconciliation_key = ' @knpkv/idempotency-reconciliation/v1'\\n AND action.lineage_kind IN ('none', 'manual')\\n AND action.reconciliation_key IS NULL) OR\\n (NEW.command_reconciliation_key <> ' @knpkv/idempotency-reconciliation/v1'\\n AND action.lineage_kind IN ('accepted', 'reconcilable')\\n AND NEW.command_reconciliation_key = action.reconciliation_key)\\n )\\n AND NEW.result_lineage_json = action.lineage_json\\n AND NEW.result_lineage_kind = action.lineage_kind\\n AND NEW.result_provider_operation_id IS action.provider_operation_id\\n AND NEW.result_reconciliation_key IS action.reconciliation_key\\n AND NEW.result_terminal_status IS action.terminal_status) OR\\n (NEW.command_tag IN ('recordSucceeded', 'recordFailed', 'recordCancelled')\\n AND NEW.result_lineage_kind = 'terminal'\\n AND NEW.result_provider_operation_id = NEW.command_provider_operation_id\\n AND NEW.result_terminal_status = NEW.command_terminal_status\\n AND NEW.result_reconciliation_key IS NULL\\n AND (\\n (NEW.outcome_source_kind = 'direct' AND action.lineage_kind = 'none') OR\\n (NEW.outcome_source_kind = 'providerOperation'\\n AND action.lineage_kind = 'accepted'\\n AND action.provider_operation_id = NEW.command_provider_operation_id) OR\\n (NEW.outcome_source_kind = 'reconciliation' AND (\\n (NEW.command_reconciliation_key = ' @knpkv/idempotency-reconciliation/v1'\\n AND action.lineage_kind IN ('none', 'manual')\\n AND action.reconciliation_key IS NULL\\n AND (action.provider_operation_id IS NULL\\n OR action.provider_operation_id = NEW.command_provider_operation_id)) OR\\n (NEW.command_reconciliation_key <> ' @knpkv/idempotency-reconciliation/v1'\\n AND action.lineage_kind IN ('accepted', 'reconcilable')\\n AND action.reconciliation_key = NEW.command_reconciliation_key\\n AND (action.provider_operation_id IS NULL\\n OR action.provider_operation_id = NEW.command_provider_operation_id))\\n ))\\n ))\\n )\\n AND (\\n (NEW.sequence = 1 AND action.head_transition_id IS NULL\\n AND action.head_sequence IS NULL AND action.state IS NULL) OR\\n (NEW.sequence = action.head_sequence + 1\\n AND NEW.previous_transition_id = action.head_transition_id\\n AND NEW.from_state = action.state\\n AND NEW.occurred_at >= action.updated_at)\\n )\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'governed action transition must append to the exact head');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_transition_reserved_reconciliation_locator\",\n \"sql\": \"CREATE TRIGGER governed_action_transition_reserved_reconciliation_locator\\n BEFORE INSERT ON governed_action_transitions\\n WHEN NEW.command_reconciliation_key = ' @knpkv/idempotency-reconciliation/v1'\\n AND NOT (\\n NEW.command_tag = 'reconciliationPending' OR\\n (NEW.command_tag IN ('recordSucceeded', 'recordFailed', 'recordCancelled')\\n AND NEW.outcome_source_kind = 'reconciliation')\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'reserved reconciliation locator is execution-owned');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_transitions_no_delete\",\n \"sql\": \"CREATE TRIGGER governed_action_transitions_no_delete\\n BEFORE DELETE ON governed_action_transitions\\n BEGIN\\n SELECT RAISE(ABORT, 'governed_action_transitions is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_action_transitions_no_update\",\n \"sql\": \"CREATE TRIGGER governed_action_transitions_no_update\\n BEFORE UPDATE ON governed_action_transitions\\n BEGIN\\n SELECT RAISE(ABORT, 'governed_action_transitions is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"governed_actions_no_delete\",\n \"sql\": \"CREATE TRIGGER governed_actions_no_delete\\n BEFORE DELETE ON governed_actions\\n BEGIN\\n SELECT RAISE(ABORT, 'governed actions are immutable audit roots');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"plugin_runtime_authority_generation_immutable_update\",\n \"sql\": \"CREATE TRIGGER plugin_runtime_authority_generation_immutable_update\\n BEFORE UPDATE ON plugin_runtime_authority_generations\\n BEGIN\\n SELECT RAISE(ABORT, 'plugin runtime authority generation is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"plugin_runtime_authority_generation_no_delete\",\n \"sql\": \"CREATE TRIGGER plugin_runtime_authority_generation_no_delete\\n BEFORE DELETE ON plugin_runtime_authority_generations\\n BEGIN\\n SELECT RAISE(ABORT, 'plugin runtime authority generation cannot be deleted');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"plugin_runtime_authority_head_current_insert\",\n \"sql\": \"CREATE TRIGGER plugin_runtime_authority_head_current_insert\\n BEFORE INSERT ON plugin_runtime_authority_heads\\n WHEN NEW.generation <> 1 OR NOT (\\n EXISTS (\\n SELECT 1\\n FROM plugin_connections connection\\n JOIN plugin_runtime_state runtime\\n ON runtime.workspace_id = connection.workspace_id\\n AND runtime.plugin_connection_id = connection.plugin_connection_id\\n AND runtime.provider_id = connection.provider_id\\n WHERE connection.workspace_id = NEW.workspace_id\\n AND connection.plugin_connection_id = NEW.plugin_connection_id\\n AND connection.provider_id = NEW.provider_id\\n AND connection.is_enabled = 1\\n AND connection.revision = NEW.connection_revision\\n AND connection.updated_at <= NEW.activated_at\\n AND runtime.descriptor_generation = NEW.descriptor_generation\\n AND runtime.descriptor_digest = NEW.descriptor_digest\\n AND runtime.accepted_at <= NEW.activated_at\\n AND (\\n (\\n NEW.configuration_revision IS NULL\\n AND NEW.configuration_digest IS NULL\\n AND NOT EXISTS (\\n SELECT 1\\n FROM plugin_configurations configuration\\n WHERE configuration.workspace_id = NEW.workspace_id\\n AND configuration.plugin_connection_id = NEW.plugin_connection_id\\n )\\n ) OR (\\n NEW.configuration_revision IS NOT NULL\\n AND NEW.configuration_digest IS NOT NULL\\n AND EXISTS (\\n SELECT 1\\n FROM plugin_configurations configuration\\n WHERE configuration.workspace_id = NEW.workspace_id\\n AND configuration.plugin_connection_id = NEW.plugin_connection_id\\n AND configuration.revision = NEW.configuration_revision\\n AND configuration.configuration_digest = NEW.configuration_digest\\n AND configuration.updated_at <= NEW.activated_at\\n )\\n )\\n )\\n ))\\n BEGIN\\n SELECT RAISE(ABORT, 'plugin runtime authority must match the current enabled source');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"plugin_runtime_authority_head_current_update\",\n \"sql\": \"CREATE TRIGGER plugin_runtime_authority_head_current_update\\n BEFORE UPDATE ON plugin_runtime_authority_heads\\n WHEN NOT (\\n EXISTS (\\n SELECT 1\\n FROM plugin_connections connection\\n JOIN plugin_runtime_state runtime\\n ON runtime.workspace_id = connection.workspace_id\\n AND runtime.plugin_connection_id = connection.plugin_connection_id\\n AND runtime.provider_id = connection.provider_id\\n WHERE connection.workspace_id = NEW.workspace_id\\n AND connection.plugin_connection_id = NEW.plugin_connection_id\\n AND connection.provider_id = NEW.provider_id\\n AND connection.is_enabled = 1\\n AND connection.revision = NEW.connection_revision\\n AND connection.updated_at <= NEW.activated_at\\n AND runtime.descriptor_generation = NEW.descriptor_generation\\n AND runtime.descriptor_digest = NEW.descriptor_digest\\n AND runtime.accepted_at <= NEW.activated_at\\n AND (\\n (\\n NEW.configuration_revision IS NULL\\n AND NEW.configuration_digest IS NULL\\n AND NOT EXISTS (\\n SELECT 1\\n FROM plugin_configurations configuration\\n WHERE configuration.workspace_id = NEW.workspace_id\\n AND configuration.plugin_connection_id = NEW.plugin_connection_id\\n )\\n ) OR (\\n NEW.configuration_revision IS NOT NULL\\n AND NEW.configuration_digest IS NOT NULL\\n AND EXISTS (\\n SELECT 1\\n FROM plugin_configurations configuration\\n WHERE configuration.workspace_id = NEW.workspace_id\\n AND configuration.plugin_connection_id = NEW.plugin_connection_id\\n AND configuration.revision = NEW.configuration_revision\\n AND configuration.configuration_digest = NEW.configuration_digest\\n AND configuration.updated_at <= NEW.activated_at\\n )\\n )\\n )\\n ))\\n BEGIN\\n SELECT RAISE(ABORT, 'plugin runtime authority must match the current enabled source');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"plugin_runtime_authority_head_exact_update\",\n \"sql\": \"CREATE TRIGGER plugin_runtime_authority_head_exact_update\\n BEFORE UPDATE ON plugin_runtime_authority_heads\\n WHEN NEW.workspace_id <> OLD.workspace_id\\n OR NEW.plugin_connection_id <> OLD.plugin_connection_id\\n OR NEW.provider_id <> OLD.provider_id\\n OR NEW.generation <> OLD.generation + 1\\n OR NEW.activated_at < OLD.activated_at\\n BEGIN\\n SELECT RAISE(ABORT, 'plugin runtime authority generation must advance exactly');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"plugin_runtime_authority_head_no_delete\",\n \"sql\": \"CREATE TRIGGER plugin_runtime_authority_head_no_delete\\n BEFORE DELETE ON plugin_runtime_authority_heads\\n BEGIN\\n SELECT RAISE(ABORT, 'plugin runtime authority generation cannot be deleted');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"plugin_runtime_authority_head_record_initial_generation\",\n \"sql\": \"CREATE TRIGGER plugin_runtime_authority_head_record_initial_generation\\n AFTER INSERT ON plugin_runtime_authority_heads\\n BEGIN\\n INSERT INTO plugin_runtime_authority_generations (\\n workspace_id, plugin_connection_id, generation, authority_digest, activated_at\\n ) VALUES (\\n NEW.workspace_id, NEW.plugin_connection_id, NEW.generation,\\n NEW.authority_digest, NEW.activated_at\\n );\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"plugin_runtime_authority_head_record_next_generation\",\n \"sql\": \"CREATE TRIGGER plugin_runtime_authority_head_record_next_generation\\n AFTER UPDATE ON plugin_runtime_authority_heads\\n BEGIN\\n INSERT INTO plugin_runtime_authority_generations (\\n workspace_id, plugin_connection_id, generation, authority_digest, activated_at\\n ) VALUES (\\n NEW.workspace_id, NEW.plugin_connection_id, NEW.generation,\\n NEW.authority_digest, NEW.activated_at\\n );\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"plugin_runtime_descriptor_generation_exact_update\",\n \"sql\": \"CREATE TRIGGER plugin_runtime_descriptor_generation_exact_update\\n BEFORE UPDATE ON plugin_runtime_state\\n WHEN NEW.descriptor_generation < OLD.descriptor_generation\\n OR NEW.descriptor_generation > OLD.descriptor_generation + 1\\n OR (\\n (\\n NEW.provider_id <> OLD.provider_id\\n OR NEW.descriptor_schema_version <> OLD.descriptor_schema_version\\n OR NEW.descriptor_json <> OLD.descriptor_json\\n OR NEW.descriptor_digest <> OLD.descriptor_digest\\n OR NEW.accepted_at <> OLD.accepted_at\\n )\\n AND NEW.descriptor_generation <> OLD.descriptor_generation + 1\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'plugin runtime descriptor generation must advance exactly');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"plugin_runtime_state_no_delete_after_authority\",\n \"sql\": \"CREATE TRIGGER plugin_runtime_state_no_delete_after_authority\\n BEFORE DELETE ON plugin_runtime_state\\n WHEN EXISTS (\\n SELECT 1\\n FROM plugin_runtime_authority_generations authority\\n WHERE authority.workspace_id = OLD.workspace_id\\n AND authority.plugin_connection_id = OLD.plugin_connection_id\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'authorized plugin runtime state cannot be recreated');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"plugin_sync_attempt_completion_exact_insert\",\n \"sql\": \"CREATE TRIGGER plugin_sync_attempt_completion_exact_insert\\n BEFORE INSERT ON plugin_sync_attempt_completions\\n WHEN NOT EXISTS (\\n SELECT 1 FROM plugin_sync_attempts attempt\\n WHERE attempt.workspace_id = NEW.workspace_id\\n AND attempt.plugin_connection_id = NEW.plugin_connection_id\\n AND attempt.stream_key = NEW.stream_key\\n AND attempt.attempt_sequence = NEW.attempt_sequence\\n AND attempt.started_at <= NEW.completed_at\\n AND attempt.started_revision <= NEW.ending_revision\\n AND NEW.pages_committed = NEW.ending_revision - attempt.started_revision\\n ) OR NEW.ending_revision <> COALESCE((\\n SELECT stream.revision FROM plugin_sync_streams stream\\n WHERE stream.workspace_id = NEW.workspace_id\\n AND stream.plugin_connection_id = NEW.plugin_connection_id\\n AND stream.stream_key = NEW.stream_key\\n ), 0)\\n BEGIN\\n SELECT RAISE(ABORT, 'plugin sync completion must match its attempt and current stream revision');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"plugin_sync_attempt_completions_no_delete\",\n \"sql\": \"CREATE TRIGGER plugin_sync_attempt_completions_no_delete\\n BEFORE DELETE ON plugin_sync_attempt_completions\\n BEGIN\\n SELECT RAISE(ABORT, 'plugin sync attempt completions are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"plugin_sync_attempt_completions_no_update\",\n \"sql\": \"CREATE TRIGGER plugin_sync_attempt_completions_no_update\\n BEFORE UPDATE ON plugin_sync_attempt_completions\\n BEGIN\\n SELECT RAISE(ABORT, 'plugin sync attempt completions are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"plugin_sync_attempt_exact_insert\",\n \"sql\": \"CREATE TRIGGER plugin_sync_attempt_exact_insert\\n BEFORE INSERT ON plugin_sync_attempts\\n WHEN NEW.started_revision <> COALESCE((\\n SELECT stream.revision FROM plugin_sync_streams stream\\n WHERE stream.workspace_id = NEW.workspace_id\\n AND stream.plugin_connection_id = NEW.plugin_connection_id\\n AND stream.stream_key = NEW.stream_key\\n ), 0) OR NEW.attempt_sequence <> COALESCE((\\n SELECT MAX(attempt.attempt_sequence) FROM plugin_sync_attempts attempt\\n WHERE attempt.workspace_id = NEW.workspace_id\\n AND attempt.plugin_connection_id = NEW.plugin_connection_id\\n AND attempt.stream_key = NEW.stream_key\\n ), 0) + 1 OR EXISTS (\\n SELECT 1 FROM plugin_sync_attempts attempt\\n WHERE attempt.workspace_id = NEW.workspace_id\\n AND attempt.plugin_connection_id = NEW.plugin_connection_id\\n AND attempt.stream_key = NEW.stream_key\\n AND NOT EXISTS (\\n SELECT 1 FROM plugin_sync_attempt_completions completion\\n WHERE completion.workspace_id = attempt.workspace_id\\n AND completion.plugin_connection_id = attempt.plugin_connection_id\\n AND completion.stream_key = attempt.stream_key\\n AND completion.attempt_sequence = attempt.attempt_sequence\\n )\\n ) OR EXISTS (\\n SELECT 1 FROM plugin_sync_attempt_completions completion\\n WHERE completion.workspace_id = NEW.workspace_id\\n AND completion.plugin_connection_id = NEW.plugin_connection_id\\n AND completion.stream_key = NEW.stream_key\\n AND completion.completed_at > NEW.started_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'plugin sync attempts must be chronological, contiguous, and begin at the current revision');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"plugin_sync_attempts_no_delete\",\n \"sql\": \"CREATE TRIGGER plugin_sync_attempts_no_delete\\n BEFORE DELETE ON plugin_sync_attempts\\n BEGIN\\n SELECT RAISE(ABORT, 'plugin sync attempts are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"plugin_sync_attempts_no_update\",\n \"sql\": \"CREATE TRIGGER plugin_sync_attempts_no_update\\n BEFORE UPDATE ON plugin_sync_attempts\\n BEGIN\\n SELECT RAISE(ABORT, 'plugin sync attempts are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_assessment_evidence_no_delete\",\n \"sql\": \"CREATE TRIGGER \\\"readiness_assessment_evidence_no_delete\\\"\\n BEFORE DELETE ON \\\"readiness_assessment_evidence\\\"\\n BEGIN\\n SELECT RAISE(ABORT, 'readiness audit records are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_assessment_evidence_no_update\",\n \"sql\": \"CREATE TRIGGER \\\"readiness_assessment_evidence_no_update\\\"\\n BEFORE UPDATE ON \\\"readiness_assessment_evidence\\\"\\n BEGIN\\n SELECT RAISE(ABORT, 'readiness audit records are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_assessment_evidence_seal_published\",\n \"sql\": \"CREATE TRIGGER \\\"readiness_assessment_evidence_seal_published\\\"\\n BEFORE INSERT ON \\\"readiness_assessment_evidence\\\"\\n WHEN EXISTS (\\n SELECT 1 FROM readiness_environment_heads head\\n WHERE head.workspace_id = NEW.workspace_id\\n AND head.assessment_id = NEW.assessment_id\\n UNION ALL\\n SELECT 1 FROM readiness_release_heads head\\n WHERE head.workspace_id = NEW.workspace_id\\n AND head.assessment_id = NEW.assessment_id\\n UNION ALL\\n SELECT 1 FROM readiness_assessments successor\\n WHERE successor.workspace_id = NEW.workspace_id\\n AND successor.previous_assessment_id = NEW.assessment_id\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'published readiness dependencies are sealed');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_assessment_sources_no_delete\",\n \"sql\": \"CREATE TRIGGER \\\"readiness_assessment_sources_no_delete\\\"\\n BEFORE DELETE ON \\\"readiness_assessment_sources\\\"\\n BEGIN\\n SELECT RAISE(ABORT, 'readiness audit records are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_assessment_sources_no_update\",\n \"sql\": \"CREATE TRIGGER \\\"readiness_assessment_sources_no_update\\\"\\n BEFORE UPDATE ON \\\"readiness_assessment_sources\\\"\\n BEGIN\\n SELECT RAISE(ABORT, 'readiness audit records are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_assessment_sources_seal_published\",\n \"sql\": \"CREATE TRIGGER \\\"readiness_assessment_sources_seal_published\\\"\\n BEFORE INSERT ON \\\"readiness_assessment_sources\\\"\\n WHEN EXISTS (\\n SELECT 1 FROM readiness_environment_heads head\\n WHERE head.workspace_id = NEW.workspace_id\\n AND head.assessment_id = NEW.assessment_id\\n UNION ALL\\n SELECT 1 FROM readiness_release_heads head\\n WHERE head.workspace_id = NEW.workspace_id\\n AND head.assessment_id = NEW.assessment_id\\n UNION ALL\\n SELECT 1 FROM readiness_assessments successor\\n WHERE successor.workspace_id = NEW.workspace_id\\n AND successor.previous_assessment_id = NEW.assessment_id\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'published readiness dependencies are sealed');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_assessments_no_delete\",\n \"sql\": \"CREATE TRIGGER \\\"readiness_assessments_no_delete\\\"\\n BEFORE DELETE ON \\\"readiness_assessments\\\"\\n BEGIN\\n SELECT RAISE(ABORT, 'readiness audit records are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_assessments_no_update\",\n \"sql\": \"CREATE TRIGGER \\\"readiness_assessments_no_update\\\"\\n BEFORE UPDATE ON \\\"readiness_assessments\\\"\\n BEGIN\\n SELECT RAISE(ABORT, 'readiness audit records are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_assessments_previous_scope\",\n \"sql\": \"CREATE TRIGGER readiness_assessments_previous_scope\\n BEFORE INSERT ON readiness_assessments\\n WHEN NEW.previous_assessment_id IS NOT NULL AND NOT EXISTS (\\n SELECT 1 FROM readiness_assessments previous\\n WHERE previous.workspace_id = NEW.workspace_id\\n AND previous.assessment_id = NEW.previous_assessment_id\\n AND previous.scope_kind = NEW.scope_kind\\n AND previous.release_id = NEW.release_id\\n AND previous.environment_id IS NEW.environment_id\\n AND previous.evaluated_at <= NEW.evaluated_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'readiness assessment supersession must preserve scope and chronology');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_environment_heads_history_insert\",\n \"sql\": \"CREATE TRIGGER readiness_environment_heads_history_insert\\n BEFORE INSERT ON readiness_environment_heads\\n WHEN NOT EXISTS (\\n SELECT 1 FROM readiness_head_history history\\n WHERE history.workspace_id = NEW.workspace_id\\n AND history.scope_kind = 'environment'\\n AND history.release_id = NEW.release_id\\n AND history.environment_key = NEW.environment_id\\n AND history.head_revision = NEW.head_revision\\n AND history.assessment_id = NEW.assessment_id\\n AND history.committed_at = NEW.updated_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'environment readiness head must have exact immutable history');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_environment_heads_history_update\",\n \"sql\": \"CREATE TRIGGER readiness_environment_heads_history_update\\n BEFORE UPDATE ON readiness_environment_heads\\n WHEN NOT EXISTS (\\n SELECT 1 FROM readiness_head_history history\\n WHERE history.workspace_id = NEW.workspace_id\\n AND history.scope_kind = 'environment'\\n AND history.release_id = NEW.release_id\\n AND history.environment_key = NEW.environment_id\\n AND history.head_revision = NEW.head_revision\\n AND history.assessment_id = NEW.assessment_id\\n AND history.committed_at = NEW.updated_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'environment readiness head must have exact immutable history');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_environment_heads_match_insert\",\n \"sql\": \"CREATE TRIGGER readiness_environment_heads_match_insert\\n BEFORE INSERT ON readiness_environment_heads\\n WHEN NEW.head_revision <> 1 OR NOT EXISTS (\\n SELECT 1 FROM readiness_assessments assessment\\n INNER JOIN releases release\\n ON release.workspace_id = assessment.workspace_id\\n AND release.release_id = assessment.release_id\\n INNER JOIN release_targets target\\n ON target.workspace_id = assessment.workspace_id\\n AND target.release_id = assessment.release_id\\n AND target.environment_id = assessment.environment_id\\n AND target.lifecycle_kind = 'active'\\n WHERE assessment.workspace_id = NEW.workspace_id\\n AND assessment.assessment_id = NEW.assessment_id\\n AND assessment.scope_kind = 'environment'\\n AND assessment.release_id = NEW.release_id\\n AND assessment.environment_id = NEW.environment_id\\n AND assessment.candidate_digest = NEW.candidate_digest\\n AND assessment.rule_id = NEW.rule_id\\n AND assessment.rule_version = NEW.rule_version\\n AND assessment.rule_digest = NEW.rule_digest\\n AND assessment.derivation_version = NEW.derivation_version\\n AND assessment.previous_assessment_id IS NULL\\n AND assessment.release_revision = release.current_revision\\n AND EXISTS (\\n SELECT 1 FROM readiness_assessment_dependency_integrity integrity\\n WHERE integrity.workspace_id = assessment.workspace_id\\n AND integrity.assessment_id = assessment.assessment_id\\n )\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'environment readiness head must match its exact assessment');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_environment_heads_match_update\",\n \"sql\": \"CREATE TRIGGER readiness_environment_heads_match_update\\n BEFORE UPDATE ON readiness_environment_heads\\n WHEN NEW.workspace_id <> OLD.workspace_id\\n OR NEW.release_id <> OLD.release_id\\n OR NEW.environment_id <> OLD.environment_id\\n OR NEW.created_at <> OLD.created_at\\n OR NEW.head_revision <> OLD.head_revision + 1 OR NOT EXISTS (\\n SELECT 1 FROM readiness_assessments assessment\\n INNER JOIN releases release\\n ON release.workspace_id = assessment.workspace_id\\n AND release.release_id = assessment.release_id\\n INNER JOIN release_targets target\\n ON target.workspace_id = assessment.workspace_id\\n AND target.release_id = assessment.release_id\\n AND target.environment_id = assessment.environment_id\\n AND target.lifecycle_kind = 'active'\\n WHERE assessment.workspace_id = NEW.workspace_id\\n AND assessment.assessment_id = NEW.assessment_id\\n AND assessment.scope_kind = 'environment'\\n AND assessment.release_id = NEW.release_id\\n AND assessment.environment_id = NEW.environment_id\\n AND assessment.candidate_digest = NEW.candidate_digest\\n AND assessment.rule_id = NEW.rule_id\\n AND assessment.rule_version = NEW.rule_version\\n AND assessment.rule_digest = NEW.rule_digest\\n AND assessment.derivation_version = NEW.derivation_version\\n AND assessment.previous_assessment_id = OLD.assessment_id\\n AND assessment.release_revision = release.current_revision\\n AND EXISTS (\\n SELECT 1 FROM readiness_assessment_dependency_integrity integrity\\n WHERE integrity.workspace_id = assessment.workspace_id\\n AND integrity.assessment_id = assessment.assessment_id\\n )\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'environment readiness head must advance once to an exact assessment');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_environment_heads_no_delete\",\n \"sql\": \"CREATE TRIGGER readiness_environment_heads_no_delete\\n BEFORE DELETE ON readiness_environment_heads\\n BEGIN\\n SELECT RAISE(ABORT, 'environment readiness heads are durable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_environment_queue_lease_shape_insert\",\n \"sql\": \"CREATE TRIGGER readiness_environment_queue_lease_shape_insert\\n BEFORE INSERT ON readiness_environment_queue\\n WHEN NOT (\\n (NEW.claim_owner IS NULL AND NEW.claim_token IS NULL AND NEW.claim_expires_at IS NULL) OR\\n (NEW.claim_owner IS NOT NULL AND length(NEW.claim_owner) BETWEEN 1 AND 200\\n AND NEW.claim_token IS NOT NULL AND length(NEW.claim_token) BETWEEN 1 AND 200\\n AND NEW.claim_expires_at IS NOT NULL)\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'readiness lease fields must be all null or all populated');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_environment_queue_lease_shape_update\",\n \"sql\": \"CREATE TRIGGER readiness_environment_queue_lease_shape_update\\n BEFORE UPDATE ON readiness_environment_queue\\n WHEN NOT (\\n (NEW.claim_owner IS NULL AND NEW.claim_token IS NULL AND NEW.claim_expires_at IS NULL) OR\\n (NEW.claim_owner IS NOT NULL AND length(NEW.claim_owner) BETWEEN 1 AND 200\\n AND NEW.claim_token IS NOT NULL AND length(NEW.claim_token) BETWEEN 1 AND 200\\n AND NEW.claim_expires_at IS NOT NULL)\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'readiness lease fields must be all null or all populated');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_head_history_exact_insert\",\n \"sql\": \"CREATE TRIGGER readiness_head_history_exact_insert\\n BEFORE INSERT ON readiness_head_history\\n WHEN NOT EXISTS (\\n SELECT 1\\n FROM readiness_assessments assessment\\n WHERE assessment.workspace_id = NEW.workspace_id\\n AND assessment.assessment_id = NEW.assessment_id\\n AND assessment.scope_kind = NEW.scope_kind\\n AND assessment.release_id = NEW.release_id\\n AND COALESCE(assessment.environment_id, '') = NEW.environment_key\\n AND assessment.evaluated_at <= NEW.committed_at\\n AND (\\n (NEW.head_revision = 1 AND assessment.previous_assessment_id IS NULL AND NOT EXISTS (\\n SELECT 1 FROM readiness_head_history previous\\n WHERE previous.workspace_id = NEW.workspace_id\\n AND previous.scope_kind = NEW.scope_kind\\n AND previous.release_id = NEW.release_id\\n AND previous.environment_key = NEW.environment_key\\n )) OR\\n (NEW.head_revision > 1 AND EXISTS (\\n SELECT 1 FROM readiness_head_history previous\\n WHERE previous.workspace_id = NEW.workspace_id\\n AND previous.scope_kind = NEW.scope_kind\\n AND previous.release_id = NEW.release_id\\n AND previous.environment_key = NEW.environment_key\\n AND previous.head_revision = NEW.head_revision - 1\\n AND previous.assessment_id = assessment.previous_assessment_id\\n AND previous.committed_at <= NEW.committed_at\\n ))\\n )\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'readiness head history must be exact and contiguous');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_head_history_no_delete\",\n \"sql\": \"CREATE TRIGGER readiness_head_history_no_delete\\n BEFORE DELETE ON readiness_head_history\\n BEGIN\\n SELECT RAISE(ABORT, 'readiness head history is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_head_history_no_update\",\n \"sql\": \"CREATE TRIGGER readiness_head_history_no_update\\n BEFORE UPDATE ON readiness_head_history\\n BEGIN\\n SELECT RAISE(ABORT, 'readiness head history is immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_release_children_match\",\n \"sql\": \"CREATE TRIGGER readiness_release_children_match\\n BEFORE INSERT ON readiness_release_children\\n WHEN NOT EXISTS (\\n SELECT 1\\n FROM readiness_assessments release_assessment\\n INNER JOIN readiness_assessments environment_assessment\\n ON environment_assessment.workspace_id = release_assessment.workspace_id\\n AND environment_assessment.assessment_id = NEW.environment_assessment_id\\n WHERE release_assessment.workspace_id = NEW.workspace_id\\n AND release_assessment.assessment_id = NEW.release_assessment_id\\n AND release_assessment.scope_kind = 'release'\\n AND environment_assessment.scope_kind = 'environment'\\n AND environment_assessment.release_id = release_assessment.release_id\\n AND environment_assessment.environment_id = NEW.environment_id\\n AND environment_assessment.release_revision = release_assessment.release_revision\\n AND environment_assessment.artifact_revision = release_assessment.artifact_revision\\n AND environment_assessment.rule_id = release_assessment.rule_id\\n AND environment_assessment.rule_version = release_assessment.rule_version\\n AND environment_assessment.rule_digest = release_assessment.rule_digest\\n AND environment_assessment.derivation_version = release_assessment.derivation_version\\n AND environment_assessment.candidate_digest = NEW.environment_candidate_digest\\n AND environment_assessment.evaluated_at <= release_assessment.evaluated_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'release readiness child must match its exact release candidate and policy');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_release_children_no_delete\",\n \"sql\": \"CREATE TRIGGER \\\"readiness_release_children_no_delete\\\"\\n BEFORE DELETE ON \\\"readiness_release_children\\\"\\n BEGIN\\n SELECT RAISE(ABORT, 'readiness audit records are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_release_children_no_update\",\n \"sql\": \"CREATE TRIGGER \\\"readiness_release_children_no_update\\\"\\n BEFORE UPDATE ON \\\"readiness_release_children\\\"\\n BEGIN\\n SELECT RAISE(ABORT, 'readiness audit records are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_release_children_seal_published\",\n \"sql\": \"CREATE TRIGGER readiness_release_children_seal_published\\n BEFORE INSERT ON readiness_release_children\\n WHEN EXISTS (\\n SELECT 1 FROM readiness_release_heads head\\n WHERE head.workspace_id = NEW.workspace_id\\n AND head.assessment_id = NEW.release_assessment_id\\n UNION ALL\\n SELECT 1 FROM readiness_assessments successor\\n WHERE successor.workspace_id = NEW.workspace_id\\n AND successor.previous_assessment_id = NEW.release_assessment_id\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'published release readiness children are sealed');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_release_heads_history_insert\",\n \"sql\": \"CREATE TRIGGER readiness_release_heads_history_insert\\n BEFORE INSERT ON readiness_release_heads\\n WHEN NOT EXISTS (\\n SELECT 1 FROM readiness_head_history history\\n WHERE history.workspace_id = NEW.workspace_id\\n AND history.scope_kind = 'release'\\n AND history.release_id = NEW.release_id\\n AND history.environment_key = ''\\n AND history.head_revision = NEW.head_revision\\n AND history.assessment_id = NEW.assessment_id\\n AND history.committed_at = NEW.updated_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'release readiness head must have exact immutable history');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_release_heads_history_update\",\n \"sql\": \"CREATE TRIGGER readiness_release_heads_history_update\\n BEFORE UPDATE ON readiness_release_heads\\n WHEN NOT EXISTS (\\n SELECT 1 FROM readiness_head_history history\\n WHERE history.workspace_id = NEW.workspace_id\\n AND history.scope_kind = 'release'\\n AND history.release_id = NEW.release_id\\n AND history.environment_key = ''\\n AND history.head_revision = NEW.head_revision\\n AND history.assessment_id = NEW.assessment_id\\n AND history.committed_at = NEW.updated_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'release readiness head must have exact immutable history');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_release_heads_match_insert\",\n \"sql\": \"CREATE TRIGGER readiness_release_heads_match_insert\\n BEFORE INSERT ON readiness_release_heads\\n WHEN NEW.head_revision <> 1 OR NOT EXISTS (\\n SELECT 1 FROM readiness_assessments assessment\\n INNER JOIN releases release\\n ON release.workspace_id = assessment.workspace_id\\n AND release.release_id = assessment.release_id\\n WHERE assessment.workspace_id = NEW.workspace_id\\n AND assessment.assessment_id = NEW.assessment_id\\n AND assessment.scope_kind = 'release'\\n AND assessment.release_id = NEW.release_id\\n AND assessment.candidate_digest = NEW.candidate_digest\\n AND assessment.rule_id = NEW.rule_id\\n AND assessment.rule_version = NEW.rule_version\\n AND assessment.rule_digest = NEW.rule_digest\\n AND assessment.derivation_version = NEW.derivation_version\\n AND assessment.previous_assessment_id IS NULL\\n AND assessment.release_revision = release.current_revision\\n AND EXISTS (\\n SELECT 1 FROM readiness_assessment_dependency_integrity integrity\\n WHERE integrity.workspace_id = assessment.workspace_id\\n AND integrity.assessment_id = assessment.assessment_id\\n )\\n AND EXISTS (\\n SELECT 1 FROM readiness_release_child_integrity integrity\\n WHERE integrity.workspace_id = assessment.workspace_id\\n AND integrity.assessment_id = assessment.assessment_id\\n )\\n ) OR NOT EXISTS (\\n SELECT 1 FROM readiness_release_children child\\n WHERE child.workspace_id = NEW.workspace_id\\n AND child.release_assessment_id = NEW.assessment_id\\n ) OR EXISTS (\\n SELECT 1\\n FROM readiness_release_children child\\n LEFT JOIN release_targets target\\n ON target.workspace_id = child.workspace_id\\n AND target.release_id = NEW.release_id\\n AND target.environment_id = child.environment_id\\n AND target.lifecycle_kind = 'active'\\n LEFT JOIN readiness_environment_heads head\\n ON head.workspace_id = target.workspace_id\\n AND head.release_id = target.release_id\\n AND head.environment_id = target.environment_id\\n WHERE child.workspace_id = NEW.workspace_id\\n AND child.release_assessment_id = NEW.assessment_id\\n AND (target.environment_id IS NULL OR head.assessment_id IS NULL OR\\n head.assessment_id <> child.environment_assessment_id)\\n ) OR EXISTS (\\n SELECT 1\\n FROM release_targets target\\n LEFT JOIN readiness_environment_heads head\\n ON head.workspace_id = target.workspace_id\\n AND head.release_id = target.release_id\\n AND head.environment_id = target.environment_id\\n LEFT JOIN readiness_release_children child\\n ON child.workspace_id = target.workspace_id\\n AND child.release_assessment_id = NEW.assessment_id\\n AND child.environment_id = target.environment_id\\n WHERE target.workspace_id = NEW.workspace_id\\n AND target.release_id = NEW.release_id\\n AND target.lifecycle_kind = 'active'\\n AND (head.assessment_id IS NULL OR child.environment_assessment_id IS NULL)\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'release readiness head must match exact current environment children');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_release_heads_match_update\",\n \"sql\": \"CREATE TRIGGER readiness_release_heads_match_update\\n BEFORE UPDATE ON readiness_release_heads\\n WHEN NEW.workspace_id <> OLD.workspace_id\\n OR NEW.release_id <> OLD.release_id\\n OR NEW.created_at <> OLD.created_at\\n OR NEW.head_revision <> OLD.head_revision + 1 OR NOT EXISTS (\\n SELECT 1 FROM readiness_assessments assessment\\n INNER JOIN releases release\\n ON release.workspace_id = assessment.workspace_id\\n AND release.release_id = assessment.release_id\\n WHERE assessment.workspace_id = NEW.workspace_id\\n AND assessment.assessment_id = NEW.assessment_id\\n AND assessment.scope_kind = 'release'\\n AND assessment.release_id = NEW.release_id\\n AND assessment.candidate_digest = NEW.candidate_digest\\n AND assessment.rule_id = NEW.rule_id\\n AND assessment.rule_version = NEW.rule_version\\n AND assessment.rule_digest = NEW.rule_digest\\n AND assessment.derivation_version = NEW.derivation_version\\n AND assessment.previous_assessment_id = OLD.assessment_id\\n AND assessment.release_revision = release.current_revision\\n AND EXISTS (\\n SELECT 1 FROM readiness_assessment_dependency_integrity integrity\\n WHERE integrity.workspace_id = assessment.workspace_id\\n AND integrity.assessment_id = assessment.assessment_id\\n )\\n AND EXISTS (\\n SELECT 1 FROM readiness_release_child_integrity integrity\\n WHERE integrity.workspace_id = assessment.workspace_id\\n AND integrity.assessment_id = assessment.assessment_id\\n )\\n ) OR NOT EXISTS (\\n SELECT 1 FROM readiness_release_children child\\n WHERE child.workspace_id = NEW.workspace_id\\n AND child.release_assessment_id = NEW.assessment_id\\n ) OR EXISTS (\\n SELECT 1\\n FROM readiness_release_children child\\n LEFT JOIN release_targets target\\n ON target.workspace_id = child.workspace_id\\n AND target.release_id = NEW.release_id\\n AND target.environment_id = child.environment_id\\n AND target.lifecycle_kind = 'active'\\n LEFT JOIN readiness_environment_heads head\\n ON head.workspace_id = target.workspace_id\\n AND head.release_id = target.release_id\\n AND head.environment_id = target.environment_id\\n WHERE child.workspace_id = NEW.workspace_id\\n AND child.release_assessment_id = NEW.assessment_id\\n AND (target.environment_id IS NULL OR head.assessment_id IS NULL OR\\n head.assessment_id <> child.environment_assessment_id)\\n ) OR EXISTS (\\n SELECT 1\\n FROM release_targets target\\n LEFT JOIN readiness_environment_heads head\\n ON head.workspace_id = target.workspace_id\\n AND head.release_id = target.release_id\\n AND head.environment_id = target.environment_id\\n LEFT JOIN readiness_release_children child\\n ON child.workspace_id = target.workspace_id\\n AND child.release_assessment_id = NEW.assessment_id\\n AND child.environment_id = target.environment_id\\n WHERE target.workspace_id = NEW.workspace_id\\n AND target.release_id = NEW.release_id\\n AND target.lifecycle_kind = 'active'\\n AND (head.assessment_id IS NULL OR child.environment_assessment_id IS NULL)\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'release readiness head must advance once with current environment children');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_release_heads_no_delete\",\n \"sql\": \"CREATE TRIGGER readiness_release_heads_no_delete\\n BEFORE DELETE ON readiness_release_heads\\n BEGIN\\n SELECT RAISE(ABORT, 'release readiness heads are durable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_release_queue_lease_shape_insert\",\n \"sql\": \"CREATE TRIGGER readiness_release_queue_lease_shape_insert\\n BEFORE INSERT ON readiness_release_queue\\n WHEN NOT (\\n (NEW.claim_owner IS NULL AND NEW.claim_token IS NULL AND NEW.claim_expires_at IS NULL) OR\\n (NEW.claim_owner IS NOT NULL AND length(NEW.claim_owner) BETWEEN 1 AND 200\\n AND NEW.claim_token IS NOT NULL AND length(NEW.claim_token) BETWEEN 1 AND 200\\n AND NEW.claim_expires_at IS NOT NULL)\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'readiness lease fields must be all null or all populated');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_release_queue_lease_shape_update\",\n \"sql\": \"CREATE TRIGGER readiness_release_queue_lease_shape_update\\n BEFORE UPDATE ON readiness_release_queue\\n WHEN NOT (\\n (NEW.claim_owner IS NULL AND NEW.claim_token IS NULL AND NEW.claim_expires_at IS NULL) OR\\n (NEW.claim_owner IS NOT NULL AND length(NEW.claim_owner) BETWEEN 1 AND 200\\n AND NEW.claim_token IS NOT NULL AND length(NEW.claim_token) BETWEEN 1 AND 200\\n AND NEW.claim_expires_at IS NOT NULL)\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'readiness lease fields must be all null or all populated');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_rule_snapshots_no_delete\",\n \"sql\": \"CREATE TRIGGER \\\"readiness_rule_snapshots_no_delete\\\"\\n BEFORE DELETE ON \\\"readiness_rule_snapshots\\\"\\n BEGIN\\n SELECT RAISE(ABORT, 'readiness audit records are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_rule_snapshots_no_update\",\n \"sql\": \"CREATE TRIGGER \\\"readiness_rule_snapshots_no_update\\\"\\n BEFORE UPDATE ON \\\"readiness_rule_snapshots\\\"\\n BEGIN\\n SELECT RAISE(ABORT, 'readiness audit records are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_schedules_exact_insert\",\n \"sql\": \"CREATE TRIGGER readiness_schedules_exact_insert\\n BEFORE INSERT ON readiness_evaluation_schedules\\n WHEN NOT EXISTS (\\n SELECT 1\\n FROM readiness_environment_heads head\\n INNER JOIN readiness_assessments assessment\\n ON assessment.workspace_id = head.workspace_id\\n AND assessment.assessment_id = head.assessment_id\\n WHERE head.workspace_id = NEW.workspace_id\\n AND head.release_id = NEW.release_id\\n AND head.environment_id = NEW.environment_id\\n AND head.assessment_id = NEW.assessment_id\\n AND assessment.next_evaluation_at = NEW.due_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'readiness schedule must match the current assessment boundary');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"readiness_schedules_exact_update\",\n \"sql\": \"CREATE TRIGGER readiness_schedules_exact_update\\n BEFORE UPDATE ON readiness_evaluation_schedules\\n WHEN NOT EXISTS (\\n SELECT 1\\n FROM readiness_environment_heads head\\n INNER JOIN readiness_assessments assessment\\n ON assessment.workspace_id = head.workspace_id\\n AND assessment.assessment_id = head.assessment_id\\n WHERE head.workspace_id = NEW.workspace_id\\n AND head.release_id = NEW.release_id\\n AND head.environment_id = NEW.environment_id\\n AND head.assessment_id = NEW.assessment_id\\n AND assessment.next_evaluation_at = NEW.due_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'readiness schedule must match the current assessment boundary');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"relationship_repair_application_authority\",\n \"sql\": \"CREATE TRIGGER relationship_repair_application_authority\\n BEFORE INSERT ON relationship_repair_applications\\n WHEN NOT EXISTS (\\n SELECT 1\\n FROM relationship_repair_proposals proposal\\n JOIN relationship_repair_reviews review\\n ON review.workspace_id = proposal.workspace_id\\n AND review.proposal_id = proposal.proposal_id\\n JOIN relationship_heads head\\n ON head.workspace_id = proposal.workspace_id\\n AND head.relationship_id = proposal.relationship_id\\n JOIN relationship_revisions revision\\n ON revision.workspace_id = proposal.workspace_id\\n AND revision.relationship_id = proposal.relationship_id\\n AND revision.revision = NEW.applied_revision\\n JOIN sessions session\\n ON session.workspace_id = NEW.workspace_id\\n AND session.session_id = NEW.session_id\\n WHERE proposal.workspace_id = NEW.workspace_id\\n AND proposal.proposal_id = NEW.proposal_id\\n AND proposal.status = 'approved'\\n AND review.decision = 'approved'\\n AND review.reviewed_at <= NEW.applied_at\\n AND proposal.relationship_id = NEW.relationship_id\\n AND NEW.applied_revision = proposal.expected_revision + 1\\n AND revision.supersedes_revision = proposal.expected_revision\\n AND head.current_revision = NEW.applied_revision\\n AND (\\n (proposal.disposition = 'link' AND revision.lifecycle = 'governed') OR\\n (proposal.disposition = 'verify' AND revision.lifecycle = 'verified') OR\\n (proposal.disposition = 'reject' AND revision.lifecycle = 'rejected'\\n AND revision.lifecycle_reason = proposal.rationale)\\n )\\n AND revision.provenance_kind = NEW.actor_kind\\n AND revision.provenance_person_id IS NEW.person_id\\n AND revision.provenance_agent_id IS NEW.agent_id\\n AND revision.provenance_rationale = proposal.rationale\\n AND revision.recorded_by_kind = NEW.actor_kind\\n AND revision.recorded_by_person_id IS NEW.person_id\\n AND revision.recorded_by_agent_id IS NEW.agent_id\\n AND revision.recorded_at = NEW.applied_at\\n AND session.actor_kind = NEW.actor_kind\\n AND session.person_id IS NEW.person_id\\n AND session.agent_id IS NEW.agent_id\\n AND session.permission = 'workspace-owner'\\n AND session.revoked_at IS NULL\\n AND session.created_at <= NEW.applied_at\\n AND session.idle_expires_at > NEW.applied_at\\n AND session.absolute_expires_at > NEW.applied_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'relationship repair application requires approved current owner authority');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"relationship_repair_applications_no_delete\",\n \"sql\": \"CREATE TRIGGER relationship_repair_applications_no_delete\\n BEFORE DELETE ON relationship_repair_applications\\n BEGIN\\n SELECT RAISE(ABORT, 'relationship repair applications are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"relationship_repair_applications_no_update\",\n \"sql\": \"CREATE TRIGGER relationship_repair_applications_no_update\\n BEFORE UPDATE ON relationship_repair_applications\\n BEGIN\\n SELECT RAISE(ABORT, 'relationship repair applications are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"relationship_repair_proposal_authenticated_origin\",\n \"sql\": \"CREATE TRIGGER relationship_repair_proposal_authenticated_origin\\n BEFORE INSERT ON relationship_repair_proposals\\n WHEN NOT EXISTS (\\n SELECT 1\\n FROM sessions session\\n WHERE session.workspace_id = NEW.workspace_id\\n AND session.session_id = NEW.session_id\\n AND session.actor_kind = NEW.actor_kind\\n AND session.person_id IS NEW.person_id\\n AND session.agent_id IS NEW.agent_id\\n AND session.permission = 'workspace-owner'\\n AND session.revoked_at IS NULL\\n AND session.created_at <= NEW.proposed_at\\n AND session.idle_expires_at > NEW.proposed_at\\n AND session.absolute_expires_at > NEW.proposed_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'relationship repair proposal requires current owner authority');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"relationship_repair_proposal_current_candidate\",\n \"sql\": \"CREATE TRIGGER relationship_repair_proposal_current_candidate\\n BEFORE INSERT ON relationship_repair_proposals\\n WHEN NOT EXISTS (\\n SELECT 1\\n FROM relationship_heads head\\n JOIN relationship_revisions revision\\n ON revision.workspace_id = head.workspace_id\\n AND revision.relationship_id = head.relationship_id\\n AND revision.revision = head.current_revision\\n WHERE head.workspace_id = NEW.workspace_id\\n AND head.relationship_id = NEW.relationship_id\\n AND head.current_revision = NEW.expected_revision\\n AND revision.release_id = NEW.release_id\\n AND (\\n (NEW.environment_id IS NULL AND revision.environment_id IS NULL) OR\\n revision.environment_id = NEW.environment_id\\n )\\n AND revision.lifecycle IN ('missing', 'inferred', 'proposed')\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'relationship repair proposal requires the current scoped candidate');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"relationship_repair_proposal_pending_insert\",\n \"sql\": \"CREATE TRIGGER relationship_repair_proposal_pending_insert\\n BEFORE INSERT ON relationship_repair_proposals\\n WHEN NEW.status <> 'pending'\\n BEGIN\\n SELECT RAISE(ABORT, 'relationship repair proposals must begin pending');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"relationship_repair_proposal_review_transition\",\n \"sql\": \"CREATE TRIGGER relationship_repair_proposal_review_transition\\n BEFORE UPDATE ON relationship_repair_proposals\\n WHEN NOT (\\n OLD.status = 'pending'\\n AND NEW.status IN ('approved', 'rejected')\\n AND OLD.workspace_id = NEW.workspace_id\\n AND OLD.proposal_id = NEW.proposal_id\\n AND OLD.schema_version = NEW.schema_version\\n AND OLD.release_id = NEW.release_id\\n AND OLD.environment_id IS NEW.environment_id\\n AND OLD.relationship_id = NEW.relationship_id\\n AND OLD.expected_revision = NEW.expected_revision\\n AND OLD.disposition = NEW.disposition\\n AND OLD.rationale = NEW.rationale\\n AND OLD.actor_kind = NEW.actor_kind\\n AND OLD.person_id IS NEW.person_id\\n AND OLD.agent_id IS NEW.agent_id\\n AND OLD.session_id = NEW.session_id\\n AND OLD.proposed_at = NEW.proposed_at\\n AND EXISTS (\\n SELECT 1\\n FROM relationship_repair_reviews review\\n WHERE review.workspace_id = NEW.workspace_id\\n AND review.proposal_id = NEW.proposal_id\\n AND review.decision = NEW.status\\n )\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'relationship repair proposal status requires its immutable review');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"relationship_repair_proposals_no_delete\",\n \"sql\": \"CREATE TRIGGER relationship_repair_proposals_no_delete\\n BEFORE DELETE ON relationship_repair_proposals\\n BEGIN\\n SELECT RAISE(ABORT, 'relationship repair proposals are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"relationship_repair_review_authority\",\n \"sql\": \"CREATE TRIGGER relationship_repair_review_authority\\n BEFORE INSERT ON relationship_repair_reviews\\n WHEN NOT EXISTS (\\n SELECT 1\\n FROM relationship_repair_proposals proposal\\n JOIN sessions session\\n ON session.workspace_id = NEW.workspace_id\\n AND session.session_id = NEW.session_id\\n WHERE proposal.workspace_id = NEW.workspace_id\\n AND proposal.proposal_id = NEW.proposal_id\\n AND proposal.status = 'pending'\\n AND proposal.proposed_at <= NEW.reviewed_at\\n AND session.actor_kind = NEW.actor_kind\\n AND session.person_id IS NEW.person_id\\n AND session.agent_id IS NEW.agent_id\\n AND session.permission IN ('workspace-owner', 'workspace-approver')\\n AND session.revoked_at IS NULL\\n AND session.created_at <= NEW.reviewed_at\\n AND session.idle_expires_at > NEW.reviewed_at\\n AND session.absolute_expires_at > NEW.reviewed_at\\n AND NOT (\\n proposal.actor_kind = NEW.actor_kind\\n AND proposal.person_id IS NEW.person_id\\n AND proposal.agent_id IS NEW.agent_id\\n )\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'relationship repair review requires current independent authority');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"relationship_repair_review_finalize_proposal\",\n \"sql\": \"CREATE TRIGGER relationship_repair_review_finalize_proposal\\n AFTER INSERT ON relationship_repair_reviews\\n BEGIN\\n UPDATE relationship_repair_proposals\\n SET status = NEW.decision\\n WHERE workspace_id = NEW.workspace_id\\n AND proposal_id = NEW.proposal_id\\n AND status = 'pending';\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"relationship_repair_reviews_no_delete\",\n \"sql\": \"CREATE TRIGGER relationship_repair_reviews_no_delete\\n BEFORE DELETE ON relationship_repair_reviews\\n BEGIN\\n SELECT RAISE(ABORT, 'relationship repair reviews are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"relationship_repair_reviews_no_update\",\n \"sql\": \"CREATE TRIGGER relationship_repair_reviews_no_update\\n BEFORE UPDATE ON relationship_repair_reviews\\n BEGIN\\n SELECT RAISE(ABORT, 'relationship repair reviews are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"relationship_revision_evidence_causal\",\n \"sql\": \"CREATE TRIGGER relationship_revision_evidence_causal\\n BEFORE INSERT ON relationship_revision_evidence\\n WHEN NOT EXISTS (\\n SELECT 1\\n FROM relationship_revisions relationship\\n INNER JOIN evidence_claims claim\\n ON claim.workspace_id = relationship.workspace_id\\n AND claim.evidence_claim_id = NEW.evidence_claim_id\\n WHERE relationship.workspace_id = NEW.workspace_id\\n AND relationship.relationship_id = NEW.relationship_id\\n AND relationship.revision = NEW.relationship_revision\\n AND claim.recorded_at <= relationship.recorded_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'relationships must not predate their evidence claims');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"relationship_revision_evidence_no_delete\",\n \"sql\": \"CREATE TRIGGER relationship_revision_evidence_no_delete\\n BEFORE DELETE ON relationship_revision_evidence\\n BEGIN\\n SELECT RAISE(ABORT, 'relationship evidence bindings are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"relationship_revision_evidence_no_update\",\n \"sql\": \"CREATE TRIGGER relationship_revision_evidence_no_update\\n BEFORE UPDATE ON relationship_revision_evidence\\n BEGIN\\n SELECT RAISE(ABORT, 'relationship evidence bindings are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"relationship_revisions_chronological\",\n \"sql\": \"CREATE TRIGGER relationship_revisions_chronological\\n BEFORE INSERT ON relationship_revisions\\n WHEN NEW.supersedes_revision IS NOT NULL AND NEW.recorded_at < (\\n SELECT recorded_at\\n FROM relationship_revisions\\n WHERE workspace_id = NEW.workspace_id\\n AND relationship_id = NEW.relationship_id\\n AND revision = NEW.supersedes_revision\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'relationship revisions must be chronological');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"relationship_revisions_contains_release_scope\",\n \"sql\": \"CREATE TRIGGER relationship_revisions_contains_release_scope\\n BEFORE INSERT ON relationship_revisions\\n WHEN NEW.kind = 'contains' AND NOT EXISTS (\\n SELECT 1\\n FROM delivery_nodes\\n WHERE workspace_id = NEW.workspace_id\\n AND node_id = NEW.source_node_id\\n AND node_kind = 'release'\\n AND resolution_state = 'resolved'\\n AND release_id = NEW.release_id\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'release containment scope must match its resolved release source');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"relationship_revisions_no_delete\",\n \"sql\": \"CREATE TRIGGER relationship_revisions_no_delete\\n BEFORE DELETE ON relationship_revisions\\n BEGIN\\n SELECT RAISE(ABORT, 'relationship revisions are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"relationship_revisions_no_update\",\n \"sql\": \"CREATE TRIGGER relationship_revisions_no_update\\n BEFORE UPDATE ON relationship_revisions\\n BEGIN\\n SELECT RAISE(ABORT, 'relationship revisions are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"relationship_revisions_plugin_source_owner\",\n \"sql\": \"CREATE TRIGGER relationship_revisions_plugin_source_owner\\n BEFORE INSERT ON relationship_revisions\\n WHEN NEW.provenance_kind = 'plugin' AND NOT EXISTS (\\n SELECT 1\\n FROM entities\\n WHERE workspace_id = NEW.workspace_id\\n AND entity_id = NEW.provenance_source_entity_id\\n AND plugin_connection_id = NEW.provenance_plugin_connection_id\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'plugin relationship provenance must reference an entity owned by the same connection');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"release_targets_lifecycle_insert\",\n \"sql\": \"CREATE TRIGGER release_targets_lifecycle_insert\\n BEFORE INSERT ON release_targets\\n WHEN NOT (\\n (NEW.lifecycle_kind = 'active' AND NEW.ended_at IS NULL) OR\\n (NEW.lifecycle_kind = 'ended' AND NEW.ended_at IS NOT NULL AND\\n NEW.created_at <= NEW.ended_at)\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'release target lifecycle is invalid');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"release_targets_lifecycle_update\",\n \"sql\": \"CREATE TRIGGER release_targets_lifecycle_update\\n BEFORE UPDATE ON release_targets\\n WHEN NOT (\\n (NEW.lifecycle_kind = 'active' AND NEW.ended_at IS NULL) OR\\n (NEW.lifecycle_kind = 'ended' AND NEW.ended_at IS NOT NULL AND\\n NEW.created_at <= NEW.ended_at)\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'release target lifecycle is invalid');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"release_targets_no_delete\",\n \"sql\": \"CREATE TRIGGER release_targets_no_delete\\n BEFORE DELETE ON release_targets\\n BEGIN\\n SELECT RAISE(ABORT, 'release target identity is durable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"retention_cleanup_runs_no_delete\",\n \"sql\": \"CREATE TRIGGER retention_cleanup_runs_no_delete\\n BEFORE DELETE ON retention_cleanup_runs\\n BEGIN\\n SELECT RAISE(ABORT, 'retention cleanup runs are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"retention_cleanup_runs_no_update\",\n \"sql\": \"CREATE TRIGGER retention_cleanup_runs_no_update\\n BEFORE UPDATE ON retention_cleanup_runs\\n BEGIN\\n SELECT RAISE(ABORT, 'retention cleanup runs are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"timeline_export_audits_authority\",\n \"sql\": \"CREATE TRIGGER timeline_export_audits_authority\\n BEFORE INSERT ON timeline_export_audits\\n WHEN NOT EXISTS (\\n SELECT 1 FROM sessions session\\n WHERE session.workspace_id = NEW.workspace_id\\n AND session.session_id = NEW.session_id\\n AND session.actor_kind = 'human'\\n AND session.person_id = NEW.person_id\\n AND session.agent_id IS NULL\\n AND session.permission IN ('workspace-owner', 'workspace-approver')\\n AND session.revoked_at IS NULL\\n AND session.created_at <= NEW.recorded_at\\n AND session.idle_expires_at > NEW.recorded_at\\n AND session.absolute_expires_at > NEW.recorded_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'timeline export audit requires current human read authority');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"timeline_export_audits_no_delete\",\n \"sql\": \"CREATE TRIGGER timeline_export_audits_no_delete\\n BEFORE DELETE ON timeline_export_audits\\n BEGIN\\n SELECT RAISE(ABORT, 'timeline export audits are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"timeline_export_audits_no_update\",\n \"sql\": \"CREATE TRIGGER timeline_export_audits_no_update\\n BEFORE UPDATE ON timeline_export_audits\\n BEGIN\\n SELECT RAISE(ABORT, 'timeline export audits are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"workspace_settings_audits_authority\",\n \"sql\": \"CREATE TRIGGER workspace_settings_audits_authority\\n BEFORE INSERT ON workspace_settings_audits\\n WHEN NOT EXISTS (\\n SELECT 1 FROM sessions session\\n WHERE session.workspace_id = NEW.workspace_id\\n AND session.session_id = NEW.session_id\\n AND session.actor_kind = 'human'\\n AND session.person_id = NEW.actor_person_id\\n AND session.agent_id IS NULL\\n AND session.permission = 'workspace-owner'\\n AND session.revoked_at IS NULL\\n AND session.created_at <= NEW.occurred_at\\n AND session.idle_expires_at > NEW.occurred_at\\n AND session.absolute_expires_at > NEW.occurred_at\\n )\\n BEGIN\\n SELECT RAISE(ABORT, 'workspace settings audit requires current human owner authority');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"workspace_settings_audits_no_delete\",\n \"sql\": \"CREATE TRIGGER workspace_settings_audits_no_delete\\n BEFORE DELETE ON workspace_settings_audits\\n BEGIN\\n SELECT RAISE(ABORT, 'workspace settings audits are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"workspace_settings_audits_no_update\",\n \"sql\": \"CREATE TRIGGER workspace_settings_audits_no_update\\n BEFORE UPDATE ON workspace_settings_audits\\n BEGIN\\n SELECT RAISE(ABORT, 'workspace settings audits are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"workspace_settings_versions_no_delete\",\n \"sql\": \"CREATE TRIGGER workspace_settings_versions_no_delete\\n BEFORE DELETE ON workspace_settings_versions\\n BEGIN\\n SELECT RAISE(ABORT, 'workspace settings versions are immutable');\\n END\"\n },\n {\n \"type\": \"trigger\",\n \"name\": \"workspace_settings_versions_no_update\",\n \"sql\": \"CREATE TRIGGER workspace_settings_versions_no_update\\n BEFORE UPDATE ON workspace_settings_versions\\n BEGIN\\n SELECT RAISE(ABORT, 'workspace settings versions are immutable');\\n END\"\n }\n ]\n}\n","import { Effect, Schema } from \"effect\"\nimport type * as SqlClient from \"effect/unstable/sql/SqlClient\"\n\nimport { DatabaseInitializationError } from \"./errors.js\"\nimport currentSchemaJson from \"./schema.json\" with { type: \"json\" }\n\nconst CurrentSchemaObject = Schema.Struct({\n type: Schema.Literals([\"index\", \"table\", \"trigger\", \"view\"]),\n name: Schema.String.check(Schema.isNonEmpty()),\n sql: Schema.String.check(Schema.isNonEmpty())\n})\n\nconst CurrentSchema = Schema.Struct({\n version: Schema.Literal(\"unstable\"),\n objects: Schema.Array(CurrentSchemaObject)\n})\n\nconst currentSchema = Schema.decodeUnknownSync(CurrentSchema)(currentSchemaJson)\n\n/** Unstable schema identity stored in prototype backup manifests. */\nexport const CURRENT_SCHEMA_VERSION = currentSchema.version\n\nconst readSchemaObjects = Effect.fn(\"DatabaseSchema.readObjects\")(function*(sql: SqlClient.SqlClient) {\n const rows = yield* sql`SELECT type, name, sql\n FROM sqlite_schema\n WHERE sql IS NOT NULL AND name NOT LIKE 'sqlite_%'\n ORDER BY CASE type\n WHEN 'table' THEN 0\n WHEN 'index' THEN 1\n WHEN 'view' THEN 2\n WHEN 'trigger' THEN 3\n ELSE 4\n END, name`\n return yield* Schema.decodeUnknownEffect(Schema.Array(CurrentSchemaObject))(rows)\n})\n\nconst matchesCurrentSchema = (actual: ReadonlyArray<typeof CurrentSchemaObject.Type>): boolean =>\n actual.length === currentSchema.objects.length &&\n actual.every((object, index) => {\n const expected = currentSchema.objects[index]\n return (\n expected !== undefined &&\n object.type === expected.type &&\n object.name === expected.name &&\n object.sql === expected.sql\n )\n })\n\n/** Require the exact current prototype schema without compatibility handling. */\nexport const validateCurrentSchema = Effect.fn(\"DatabaseSchema.validate\")(function*(sql: SqlClient.SqlClient) {\n const objects = yield* readSchemaObjects(sql).pipe(\n Effect.mapError(() => new DatabaseInitializationError({ operation: \"verify-schema\" }))\n )\n if (!matchesCurrentSchema(objects)) {\n return yield* new DatabaseInitializationError({ operation: \"verify-schema\" })\n }\n})\n\n/**\n * Initialize a brand-new prototype database or require the exact current shape.\n *\n * Start versioned migrations only after the persistence model is declared stable\n * and a released database file must remain readable by a newer application build.\n * Until then, schema changes are intentionally breaking and require recreating the\n * local database.\n */\nexport const initializeCurrentSchema = Effect.fn(\"DatabaseSchema.initialize\")(function*(sql: SqlClient.SqlClient) {\n const existing = yield* readSchemaObjects(sql).pipe(\n Effect.mapError(() => new DatabaseInitializationError({ operation: \"initialize-schema\" }))\n )\n if (existing.length > 0) return yield* validateCurrentSchema(sql)\n\n yield* Effect.forEach(currentSchema.objects, ({ sql: statement }) => sql.unsafe(statement), { discard: true }).pipe(\n Effect.mapError(() => new DatabaseInitializationError({ operation: \"initialize-schema\" }))\n )\n yield* validateCurrentSchema(sql)\n})\n","import * as Schema from \"effect/Schema\"\n\n/** Decoded SQLite foreign-key pragma result. */\nexport const ForeignKeysPragmaRow = Schema.Struct({\n foreignKeys: Schema.Number.check(Schema.isInt())\n})\n\n/** Decoded SQLite journal-mode pragma result. */\nexport const JournalModePragmaRow = Schema.Struct({\n journalMode: Schema.String\n})\n\n/** Decoded SQLite busy-timeout pragma result. */\nexport const BusyTimeoutPragmaRow = Schema.Struct({\n timeout: Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))\n})\n\n/** Decoded SQLite database-integrity diagnostic. */\nexport const IntegrityCheckPragmaRow = Schema.Struct({\n integrityCheck: Schema.String\n})\n","import * as LibsqlClient from \"@effect/sql-libsql/LibsqlClient\"\nimport { Cause, Context, Effect, FileSystem, Layer, Option, Path, Schema, Semaphore } from \"effect\"\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\"\n\nimport { SchemaWriteBarrierError } from \"./backup/errors.js\"\nimport { DatabaseInitializationError, type PersistenceConfigError } from \"./errors.js\"\nimport { decodePersistenceConfig, type PersistenceConfig } from \"./PersistenceConfig.js\"\nimport { initializeCurrentSchema, validateCurrentSchema } from \"./schema.js\"\nimport { BusyTimeoutPragmaRow, ForeignKeysPragmaRow, IntegrityCheckPragmaRow, JournalModePragmaRow } from \"./schemas.js\"\n\n/** Busy timeout used for bounded local write contention. */\nexport const BUSY_TIMEOUT_MILLISECONDS = 5_000\n\n// The pinned libSQL client applies this option to every local connection, while\n// the current Effect beta has not yet surfaced it in LibsqlClientConfig.Full.\ninterface LocalLibsqlConfig extends LibsqlClient.LibsqlClientConfig.Full {\n readonly timeout: number\n}\n\n/** Database operations shared by all workspace-scoped persistence services. */\nexport interface DatabaseShape {\n readonly sql: SqlClient.SqlClient\n readonly transaction: SqlClient.SqlClient[\"withTransaction\"]\n readonly validateSchema: Effect.Effect<void, DatabaseInitializationError>\n}\n\n/** Scoped Control Center database service backed by one shared libSQL client. */\nexport class Database extends Context.Service<Database, DatabaseShape>()(\n \"@knpkv/control-center/server/persistence/Database\"\n) {}\n\n// SQLite remains the cross-process authority; this permit only removes races\n// between independently acquired database layers inside one process.\nconst schemaLock = Semaphore.makeUnsafe(1)\n\nconst snakeToCamel = (value: string): string =>\n value.replace(/_([a-z])/gu, (_, character: string) => character.toUpperCase())\n\nconst decodeRows = <SchemaType extends Schema.Top>(schema: SchemaType, rows: unknown) =>\n Schema.decodeUnknownEffect(Schema.Array(schema))(rows)\n\nconst configureAndVerifyPragmas = Effect.fn(\"Database.configureAndVerifyPragmas\")(function*(\n sql: SqlClient.SqlClient\n): Effect.fn.Return<void, DatabaseInitializationError> {\n yield* Effect.gen(function*() {\n yield* sql`PRAGMA foreign_keys = ON`\n yield* sql`PRAGMA journal_mode = WAL`\n yield* sql`PRAGMA busy_timeout = 5000`\n }).pipe(\n Effect.mapError(() => new DatabaseInitializationError({ operation: \"configure\" }))\n )\n\n yield* Effect.gen(function*() {\n const foreignKeys = yield* sql`PRAGMA foreign_keys`.pipe(\n Effect.flatMap((rows) => decodeRows(ForeignKeysPragmaRow, rows))\n )\n const journalMode = yield* sql`PRAGMA journal_mode`.pipe(\n Effect.flatMap((rows) => decodeRows(JournalModePragmaRow, rows))\n )\n const busyTimeout = yield* sql`PRAGMA busy_timeout`.pipe(\n Effect.flatMap((rows) => decodeRows(BusyTimeoutPragmaRow, rows))\n )\n if (\n foreignKeys.length !== 1 ||\n foreignKeys[0]?.foreignKeys !== 1 ||\n journalMode.length !== 1 ||\n journalMode[0]?.journalMode.toLowerCase() !== \"wal\" ||\n busyTimeout.length !== 1 ||\n busyTimeout[0]?.timeout !== BUSY_TIMEOUT_MILLISECONDS\n ) return yield* Effect.fail(\"SQLite pragmas did not retain their required values\")\n }).pipe(\n Effect.mapError(() => new DatabaseInitializationError({ operation: \"verify-pragmas\" }))\n )\n})\n\n/** Run the startup SQLite integrity boundary. @internal */\nexport const verifyDatabaseIntegrity = Effect.fn(\"Database.verifyIntegrity\")(function*(\n sql: SqlClient.SqlClient\n): Effect.fn.Return<void, DatabaseInitializationError> {\n yield* Effect.gen(function*() {\n const rows = yield* sql`PRAGMA integrity_check`.pipe(\n Effect.flatMap((result) => decodeRows(IntegrityCheckPragmaRow, result))\n )\n if (rows.length !== 1 || rows[0]?.integrityCheck.toLowerCase() !== \"ok\") {\n return yield* Effect.fail(\"SQLite integrity check did not return one ok result\")\n }\n const foreignKeyRows = yield* sql`PRAGMA foreign_key_check`\n if (foreignKeyRows.length !== 0) {\n return yield* Effect.fail(\"SQLite foreign key check returned violations\")\n }\n }).pipe(\n Effect.mapError(() => new DatabaseInitializationError({ operation: \"verify-integrity\" }))\n )\n})\n\nconst checkpointBeforeSchemaChange = Effect.fn(\"Database.checkpointBeforeSchemaChange\")(function*(\n sql: SqlClient.SqlClient\n): Effect.fn.Return<void, SchemaWriteBarrierError> {\n yield* sql`PRAGMA wal_checkpoint(TRUNCATE)`.pipe(\n Effect.mapError(() => new SchemaWriteBarrierError({ phase: \"acquire\" }))\n )\n})\n\nconst verifyCheckpointStayedQuiescent = Effect.fn(\"Database.verifyCheckpointStayedQuiescent\")(function*(\n databaseFile: string\n): Effect.fn.Return<void, SchemaWriteBarrierError, FileSystem.FileSystem> {\n const fileSystem = yield* FileSystem.FileSystem\n const walFile = `${databaseFile}-wal`\n const exists = yield* fileSystem.exists(walFile).pipe(\n Effect.mapError(() => new SchemaWriteBarrierError({ phase: \"verify\" }))\n )\n if (!exists) return\n const info = yield* fileSystem.stat(walFile).pipe(\n Effect.mapError(() => new SchemaWriteBarrierError({ phase: \"verify\" }))\n )\n if (info.type !== \"File\" || info.size !== 0n) {\n return yield* new SchemaWriteBarrierError({ phase: \"verify\" })\n }\n})\n\n/** Convert transaction defects into a redacted failure while preserving cancellation. */\nexport const sandboxSchemaTransaction = <Value, Failure, Requirements>(\n transaction: Effect.Effect<Value, Failure, Requirements>\n): Effect.Effect<Value, Failure | SchemaWriteBarrierError, Requirements> =>\n transaction.pipe(\n // eslint-disable-next-line local-rules/require-exact-cause-rethrow -- The schema barrier intentionally redacts defects; database.test.ts covers redaction and interruption.\n Effect.catchCause((cause): Effect.Effect<never, Failure | SchemaWriteBarrierError> => {\n if (Cause.hasInterrupts(cause)) return Effect.failCause(cause)\n const typedFailure = Cause.findErrorOption(cause)\n if (Cause.hasDies(cause) || Option.isNone(typedFailure)) {\n return Effect.fail<Failure | SchemaWriteBarrierError>(new SchemaWriteBarrierError({ phase: \"verify\" }))\n }\n return Effect.fail<Failure | SchemaWriteBarrierError>(typedFailure.value)\n })\n )\n\n/** Hold SQLite's reserved writer transaction across one fresh-schema operation. */\nexport const withSchemaWriteBarrier = <Value, Failure, Requirements>(\n sql: SqlClient.SqlClient,\n databaseSourceFile: string,\n operation: Effect.Effect<Value, Failure, Requirements>\n): Effect.Effect<Value, Failure | SchemaWriteBarrierError, FileSystem.FileSystem | Requirements> =>\n checkpointBeforeSchemaChange(sql).pipe(\n Effect.andThen(\n sandboxSchemaTransaction(sql.withTransaction(\n verifyCheckpointStayedQuiescent(databaseSourceFile).pipe(Effect.andThen(operation))\n )).pipe(\n Effect.catchTag(\"SqlError\", () => new SchemaWriteBarrierError({ phase: \"acquire\" }))\n )\n )\n )\n\nconst makeClientLayer = (\n busyTimeoutMilliseconds: number,\n databaseUrl: string,\n maxConnections: number\n) => {\n const clientConfig: LocalLibsqlConfig = {\n concurrency: maxConnections,\n timeout: busyTimeoutMilliseconds,\n transformResultNames: snakeToCamel,\n url: databaseUrl\n }\n return LibsqlClient.layer(clientConfig).pipe(\n // eslint-disable-next-line local-rules/require-exact-cause-rethrow -- The database adapter redacts connection defects while retaining cancellation; database.test.ts covers both paths.\n Layer.catchCause(handleDatabaseConnectionCause)\n )\n}\n\n/** Redact client construction defects while retaining every original interruption reason. @internal */\nexport const handleDatabaseConnectionCause = <Failure>(\n cause: Cause.Cause<Failure>\n): Layer.Layer<unknown, DatabaseInitializationError> =>\n Cause.hasInterrupts(cause)\n ? Layer.effectContext(\n Effect.failCause(Cause.fromReasons(cause.reasons.filter(Cause.isInterruptReason)))\n )\n : Layer.effectContext(Effect.fail(new DatabaseInitializationError({ operation: \"connect\" })))\n\nconst initializeDatabase = Effect.fn(\"Database.initializeDatabase\")(function*(config: PersistenceConfig) {\n yield* schemaLock.withPermit(\n Effect.scoped(\n Effect.gen(function*() {\n const context = yield* Layer.build(\n makeClientLayer(config.busyTimeoutMilliseconds, config.databaseUrl, 1)\n )\n const sql = Context.get(context, SqlClient.SqlClient)\n const path = yield* Path.Path\n const databaseSourceFile = yield* path.fromFileUrl(new URL(config.databaseUrl)).pipe(\n Effect.mapError(() => new DatabaseInitializationError({ operation: \"connect\" }))\n )\n yield* configureAndVerifyPragmas(sql)\n yield* verifyDatabaseIntegrity(sql)\n yield* withSchemaWriteBarrier(sql, databaseSourceFile, initializeCurrentSchema(sql))\n })\n )\n )\n})\n\nconst databaseFromSql = () =>\n Layer.effect(\n Database,\n Effect.gen(function*() {\n const sql = yield* SqlClient.SqlClient\n yield* configureAndVerifyPragmas(sql)\n yield* verifyDatabaseIntegrity(sql)\n yield* validateCurrentSchema(sql)\n return Database.of({\n sql,\n transaction: sql.withTransaction,\n validateSchema: validateCurrentSchema(sql)\n })\n })\n )\n\n/** Verify that an existing local database has the exact current prototype schema. */\nexport const validateExistingControlCenterDatabase = Effect.fn(\n \"Database.validateExistingControlCenterDatabase\"\n)(function*(\n input: unknown\n): Effect.fn.Return<void, PersistenceConfigError | DatabaseInitializationError> {\n const config = yield* decodePersistenceConfig(input)\n yield* Effect.scoped(\n Effect.gen(function*() {\n const context = yield* Layer.build(\n makeClientLayer(config.busyTimeoutMilliseconds, config.databaseUrl, config.maxConnections)\n )\n const sql = Context.get(context, SqlClient.SqlClient)\n yield* verifyDatabaseIntegrity(sql)\n yield* validateCurrentSchema(sql)\n })\n )\n})\n\n/** Build a scoped database layer after decoding secret-free local configuration. */\nexport const databaseLayer = (\n input: unknown\n): Layer.Layer<\n Database,\n DatabaseInitializationError | SchemaWriteBarrierError | PersistenceConfigError,\n FileSystem.FileSystem | Path.Path\n> =>\n Layer.unwrap(\n decodePersistenceConfig(input).pipe(\n Effect.flatMap((config) => initializeDatabase(config).pipe(Effect.as(config))),\n Effect.map((config) => {\n const clientLayer = makeClientLayer(\n config.busyTimeoutMilliseconds,\n config.databaseUrl,\n config.maxConnections\n )\n return databaseFromSql().pipe(Layer.provide(clientLayer))\n })\n )\n )\n","import * as Effect from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\nimport * as Schema from \"effect/Schema\"\nimport type * as SqlClient from \"effect/unstable/sql/SqlClient\"\nimport * as SqlError from \"effect/unstable/sql/SqlError\"\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\"\n\nimport type { WorkspaceId } from \"../../../domain/identifiers.js\"\nimport {\n PersistenceOperationError,\n RecordAlreadyExistsError,\n RecordNotFoundError,\n RevisionConflictError\n} from \"../errors.js\"\n\nconst ChangesRow = Schema.Struct({ changes: Schema.Number })\nconst RevisionRow = Schema.Struct({ revision: Schema.Number })\n\n/** Parameters shared by optimistic-concurrency failure resolution. */\nexport interface ResolveCasFailureOptions {\n readonly workspaceId: WorkspaceId\n readonly recordKind: string\n readonly recordKey: string\n readonly expectedRevision: number\n readonly findActualRevision: Effect.Effect<Option.Option<{ readonly revision: number }>, unknown>\n}\n\n/** Identity used to translate a unique-constraint violation into a domain error. */\nexport interface AlreadyExistsOptions {\n readonly workspaceId: WorkspaceId\n readonly recordKind: string\n readonly recordKey: string\n}\n\nconst isUniqueViolation = (error: unknown): error is SqlError.SqlError =>\n SqlError.isSqlError(error) && error.reason._tag === \"UniqueViolation\"\n\ntype PersistenceInfrastructureError = SqlError.SqlError | Schema.SchemaError\n\nconst isPersistenceInfrastructureError = (error: unknown): error is PersistenceInfrastructureError =>\n SqlError.isSqlError(error) || Schema.isSchemaError(error)\n\n/** Preserve operational SQL failures while classifying duplicate identities. */\nexport const mapAlreadyExists =\n (options: AlreadyExistsOptions) =>\n <Success, Failure, Requirements>(effect: Effect.Effect<Success, Failure, Requirements>) =>\n effect.pipe(\n Effect.catchIf(isUniqueViolation, () =>\n new RecordAlreadyExistsError({\n workspaceId: options.workspaceId,\n recordKind: options.recordKind,\n recordKey: options.recordKey\n }))\n )\n\n/** Hide driver details at repository boundaries while retaining an internal diagnostic. */\nexport function mapPersistenceOperation(\n operation: string\n): <Success, Failure, Requirements>(\n effect: Effect.Effect<Success, Failure, Requirements>\n) => Effect.Effect<\n Success,\n Exclude<Failure, PersistenceInfrastructureError> | PersistenceOperationError,\n Requirements\n>\nexport function mapPersistenceOperation(operation: string) {\n return <Success, Failure, Requirements>(\n effect: Effect.Effect<Success, Failure, Requirements>\n ) =>\n Effect.catchIf(\n effect,\n isPersistenceInfrastructureError,\n (error) =>\n Effect.logError(\"Control Center persistence operation failed\", {\n failureClass: SqlError.isSqlError(error) ? error.reason._tag : \"SchemaError\",\n operation\n }).pipe(\n Effect.andThen(new PersistenceOperationError({ operation }))\n )\n )\n}\n\n/** Read the affected-row count of the immediately preceding SQLite statement. */\nexport const readChanges = (sql: SqlClient.SqlClient): Effect.Effect<number, unknown> => {\n const query = SqlSchema.findOne({\n Request: Schema.Void,\n Result: ChangesRow,\n execute: () => sql`SELECT changes() AS changes`\n })\n return query(undefined).pipe(Effect.map(({ changes }) => changes))\n}\n\n/** Build a workspace-scoped current-revision lookup for a mutable record. */\nexport const revisionLookup = (\n execute: () => Effect.Effect<ReadonlyArray<unknown>, unknown>\n): Effect.Effect<Option.Option<{ readonly revision: number }>, unknown> =>\n SqlSchema.findOneOption({ Request: Schema.Void, Result: RevisionRow, execute })(undefined)\n\n/** Distinguish a missing record from an optimistic-concurrency conflict. */\nexport const resolveCasFailure = Effect.fn(\"resolveCasFailure\")(function*(\n options: ResolveCasFailureOptions\n) {\n const actual = yield* options.findActualRevision\n if (Option.isNone(actual)) {\n return yield* new RecordNotFoundError({\n workspaceId: options.workspaceId,\n recordKind: options.recordKind,\n recordKey: options.recordKey\n })\n }\n return yield* new RevisionConflictError({\n workspaceId: options.workspaceId,\n recordKind: options.recordKind,\n recordKey: options.recordKey,\n expectedRevision: options.expectedRevision,\n actualRevision: actual.value.revision\n })\n})\n","import { Schema } from \"effect\"\n\nimport { WorkspaceId } from \"../../../domain/identifiers.js\"\nimport { BlobDigest } from \"./BlobDigest.js\"\n\n/** Whether bytes are authoritative evidence or a safely regenerable cache. */\nexport const BlobClassification = Schema.Literals([\"durable\", \"reproducible-cache\"])\n\n/** Decoded blob durability classification. */\nexport type BlobClassification = typeof BlobClassification.Type\n\n/** Workspace-scoped reference persisted by repository metadata. */\nexport class BlobRef extends Schema.Class<BlobRef>(\"BlobRef\")({\n workspaceId: WorkspaceId,\n digest: BlobDigest,\n sizeBytes: Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0)),\n classification: BlobClassification\n}) {}\n","import * as Schema from \"effect/Schema\"\n\nimport { Person, RoleAssignment } from \"../../../domain/actors.js\"\nimport {\n EntityId,\n FollowedResourceId,\n PluginConnectionId,\n ProviderAccountId,\n WorkspaceId\n} from \"../../../domain/identifiers.js\"\nimport { Release } from \"../../../domain/release.js\"\nimport { ProviderId, SourceRevision } from \"../../../domain/sourceRevision.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport { BlobDigest } from \"../object-store/BlobDigest.js\"\nimport { BlobClassification } from \"../object-store/BlobRef.js\"\n\nconst boundedName = (identifier: string) =>\n Schema.String.check(Schema.isTrimmed(), Schema.isNonEmpty(), Schema.isMaxLength(200)).annotate({ identifier })\n\n/** Positive optimistic-concurrency revision stored with mutable records. */\nexport const RecordRevision = Schema.Number.check(Schema.isInt(), Schema.isGreaterThan(0)).pipe(\n Schema.brand(\"RecordRevision\")\n)\n\n/** Decoded optimistic-concurrency revision. */\nexport type RecordRevision = typeof RecordRevision.Type\n\n/** Workspace name shown in navigation and administrative surfaces. */\nexport const WorkspaceName = boundedName(\"WorkspaceName\").pipe(Schema.brand(\"WorkspaceName\"))\n\n/** Decoded workspace display name. */\nexport type WorkspaceName = typeof WorkspaceName.Type\n\n/** Persisted workspace row exposed by the workspace repository. */\nexport const WorkspaceRecord = Schema.Struct({\n workspaceId: WorkspaceId,\n displayName: WorkspaceName,\n revision: RecordRevision,\n createdAt: UtcTimestamp,\n updatedAt: UtcTimestamp\n})\n\n/** Decoded persisted workspace row. */\nexport type WorkspaceRecord = typeof WorkspaceRecord.Type\n\n/** Provider family sharing one external account and local authentication context. */\nexport const ProviderFamily = Schema.Literals([\"aws\", \"atlassian\", \"clockify\"])\n\n/** Decoded provider family. */\nexport type ProviderFamily = typeof ProviderFamily.Type\n\n/** Provider family that owns one concrete first-party service. */\nexport const providerFamilyForProvider = (providerId: ProviderId): ProviderFamily => {\n switch (providerId) {\n case \"codecommit\":\n case \"codepipeline\":\n return \"aws\"\n case \"jira\":\n case \"confluence\":\n return \"atlassian\"\n case \"clockify\":\n return \"clockify\"\n }\n}\n\n/** Cross-field persistence invariant shared by followed-resource codecs. */\nexport const ProviderFamilyMatchesProvider = Schema.makeFilter(\n ({ providerFamily, providerId }: { readonly providerFamily: ProviderFamily; readonly providerId: ProviderId }) =>\n providerFamilyForProvider(providerId) === providerFamily,\n { expected: \"a provider service owned by the persisted provider family\" }\n)\n\n/** Human-readable provider-account label. */\nexport const ProviderAccountDisplayName = boundedName(\"ProviderAccountDisplayName\").pipe(\n Schema.brand(\"ProviderAccountDisplayName\")\n)\n\n/** Decoded provider-account display name. */\nexport type ProviderAccountDisplayName = typeof ProviderAccountDisplayName.Type\n\n/** Immutable account identifier assigned by the external provider. */\nexport const VendorAccountId = Schema.String.check(\n Schema.isTrimmed(),\n Schema.isNonEmpty(),\n Schema.isMaxLength(512)\n).pipe(Schema.brand(\"VendorAccountId\"))\n\n/** Decoded external provider-account identifier. */\nexport type VendorAccountId = typeof VendorAccountId.Type\n\n/** Public, non-secret metadata for one external provider account. */\nexport const ProviderAccountRecord = Schema.Struct({\n workspaceId: WorkspaceId,\n providerAccountId: ProviderAccountId,\n providerFamily: ProviderFamily,\n vendorAccountId: VendorAccountId,\n displayName: ProviderAccountDisplayName,\n revision: RecordRevision,\n createdAt: UtcTimestamp,\n updatedAt: UtcTimestamp\n})\n\n/** Decoded external provider-account metadata. */\nexport type ProviderAccountRecord = typeof ProviderAccountRecord.Type\n\n/** Human-readable followed-resource label. */\nexport const FollowedResourceDisplayName = boundedName(\"FollowedResourceDisplayName\").pipe(\n Schema.brand(\"FollowedResourceDisplayName\")\n)\n\n/** Decoded followed-resource display name. */\nexport type FollowedResourceDisplayName = typeof FollowedResourceDisplayName.Type\n\n/** Immutable repository, pipeline, site, or workspace identifier assigned by its provider. */\nexport const VendorResourceId = Schema.String.check(\n Schema.isTrimmed(),\n Schema.isNonEmpty(),\n Schema.isMaxLength(512)\n).pipe(Schema.brand(\"VendorResourceId\"))\n\n/** Decoded external followed-resource identifier. */\nexport type VendorResourceId = typeof VendorResourceId.Type\n\n/** Public metadata for one provider resource selected by the workspace. */\nexport const FollowedResourceRecord = Schema.Struct({\n workspaceId: WorkspaceId,\n followedResourceId: FollowedResourceId,\n providerAccountId: ProviderAccountId,\n providerFamily: ProviderFamily,\n providerId: ProviderId,\n vendorResourceId: VendorResourceId,\n displayName: FollowedResourceDisplayName,\n isEnabled: Schema.Boolean,\n revision: RecordRevision,\n createdAt: UtcTimestamp,\n updatedAt: UtcTimestamp\n}).check(ProviderFamilyMatchesProvider)\n\n/** Decoded followed-resource metadata. */\nexport type FollowedResourceRecord = typeof FollowedResourceRecord.Type\n\n/** Plugin-connection label shown without exposing credentials or configuration. */\nexport const PluginConnectionDisplayName = boundedName(\"PluginConnectionDisplayName\").pipe(\n Schema.brand(\"PluginConnectionDisplayName\")\n)\n\n/** Decoded plugin-connection display name. */\nexport type PluginConnectionDisplayName = typeof PluginConnectionDisplayName.Type\n\n/** Public, non-secret metadata for a configured plugin connection. */\nexport const PluginConnectionRecord = Schema.Struct({\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n providerAccountId: Schema.NullOr(ProviderAccountId),\n followedResourceId: Schema.NullOr(FollowedResourceId),\n providerId: ProviderId,\n displayName: PluginConnectionDisplayName,\n isEnabled: Schema.Boolean,\n revision: RecordRevision,\n createdAt: UtcTimestamp,\n updatedAt: UtcTimestamp\n})\n\n/** Decoded plugin-connection metadata. */\nexport type PluginConnectionRecord = typeof PluginConnectionRecord.Type\n\n/** Provider-neutral category of a normalized delivery entity. */\nexport const EntityKind = Schema.Literals([\n \"issue\",\n \"pull-request\",\n \"page\",\n // Kept for v1–v7 databases; new CodePipeline writes use the execution kind.\n \"pipeline\",\n \"pipeline-execution\",\n \"deployment\",\n \"time-entry\"\n])\n\n/** Decoded normalized entity category. */\nexport type EntityKind = typeof EntityKind.Type\n\n/** Current normalized entity and exact provider revision that produced it. */\nexport const EntityRecord = Schema.Struct({\n workspaceId: WorkspaceId,\n entityId: EntityId,\n entityType: EntityKind,\n sourceRevision: SourceRevision,\n revision: RecordRevision,\n createdAt: UtcTimestamp,\n updatedAt: UtcTimestamp\n})\n\n/** Decoded persisted normalized entity. */\nexport type EntityRecord = typeof EntityRecord.Type\n\n/** Canonical person stored within one workspace. */\nexport const PersonRecord = Schema.Struct({\n workspaceId: WorkspaceId,\n person: Person,\n revision: RecordRevision,\n createdAt: UtcTimestamp,\n updatedAt: UtcTimestamp\n})\n\n/** Decoded canonical person record. */\nexport type PersonRecord = typeof PersonRecord.Type\n\n/** Workspace-bound collaborator role assignment. */\nexport const RoleAssignmentRecord = Schema.Struct({\n workspaceId: WorkspaceId,\n assignment: RoleAssignment,\n revision: RecordRevision,\n createdAt: UtcTimestamp,\n updatedAt: UtcTimestamp\n})\n\n/** Decoded collaborator role-assignment record. */\nexport type RoleAssignmentRecord = typeof RoleAssignmentRecord.Type\n\n/** Immutable decoded release snapshot and its repository revision. */\nexport const ReleaseSnapshotRecord = Schema.Struct({\n release: Release,\n revision: RecordRevision\n})\n\n/** Decoded immutable release snapshot. */\nexport type ReleaseSnapshotRecord = typeof ReleaseSnapshotRecord.Type\n\n/** Lowercase SHA-256 digest used as the content-addressed blob identity. */\nexport const ContentBlobDigest = BlobDigest\n\n/** Decoded content-addressed blob digest. */\nexport type ContentBlobDigest = typeof ContentBlobDigest.Type\n\n/** Retention behavior of bytes in the content-addressed object store. */\nexport const ContentBlobStorageClass = BlobClassification\n\n/** Decoded content-blob retention classification. */\nexport type ContentBlobStorageClass = typeof ContentBlobStorageClass.Type\n\n/** Metadata for content bytes held by the separate object-store service. */\nexport const ContentBlobMetadata = Schema.Struct({\n workspaceId: WorkspaceId,\n digest: ContentBlobDigest,\n storageClass: ContentBlobStorageClass,\n mimeType: Schema.Union([\n Schema.String.check(Schema.isTrimmed(), Schema.isNonEmpty(), Schema.isMaxLength(200)),\n Schema.Null\n ]),\n byteLength: Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0)),\n createdAt: UtcTimestamp,\n lastVerifiedAt: Schema.Union([UtcTimestamp, Schema.Null])\n})\n\n/** Decoded object-store blob metadata. */\nexport type ContentBlobMetadata = typeof ContentBlobMetadata.Type\n\n/** Persisted record categories whose malformed snapshots may be quarantined. */\nexport const QuarantineRecordKind = Schema.Literals([\n \"content-metadata\",\n \"delivery-node\",\n \"delivery-relationship\",\n \"domain-event\",\n \"entity-projection\",\n \"entity-revision\",\n \"evidence-claim\",\n \"evidence-freshness\",\n \"evidence-item\",\n \"followed-resource\",\n \"governed-action\",\n \"governed-action-policy-evaluation\",\n \"governed-action-authorization\",\n \"governed-action-attempt\",\n \"governed-action-transition\",\n \"governed-action-audit\",\n \"person-avatar\",\n \"person-identity\",\n \"person\",\n \"plugin-connection\",\n \"plugin-configuration\",\n \"plugin-descriptor\",\n \"plugin-sync-page\",\n \"provider-account\",\n \"release-head\",\n \"release-revision\",\n \"readiness-assessment\",\n \"readiness-environment-head\",\n \"readiness-release-head\",\n \"readiness-rule\",\n \"role-assignment\",\n \"session\",\n \"pairing-code\",\n \"workspace-settings\",\n \"workspace\"\n])\n\n/** Decoded quarantined-record category. */\nexport type QuarantineRecordKind = typeof QuarantineRecordKind.Type\n\n/** Bounded diagnostic code that never contains persisted payload data. */\nexport const QuarantineReasonCode = Schema.Literals([\n \"content-metadata-schema-invalid\",\n \"delivery-graph-digest-mismatch\",\n \"delivery-node-schema-invalid\",\n \"delivery-relationship-schema-invalid\",\n \"domain-event-payload-digest-mismatch\",\n \"domain-event-schema-invalid\",\n \"entity-projection-schema-invalid\",\n \"entity-revision-schema-invalid\",\n \"evidence-claim-schema-invalid\",\n \"evidence-freshness-schema-invalid\",\n \"evidence-item-schema-invalid\",\n \"followed-resource-schema-invalid\",\n \"governed-action-schema-invalid\",\n \"governed-action-digest-mismatch\",\n \"governed-action-identity-mismatch\",\n \"governed-action-chain-invalid\",\n \"governed-action-head-mismatch\",\n \"governed-action-companion-invalid\",\n \"governed-action-transition-schema-invalid\",\n \"governed-action-transition-digest-mismatch\",\n \"governed-action-audit-mismatch\",\n \"person-identity-schema-invalid\",\n \"person-schema-invalid\",\n \"plugin-connection-schema-invalid\",\n \"plugin-configuration-schema-invalid\",\n \"plugin-descriptor-schema-invalid\",\n \"plugin-descriptor-envelope-invalid\",\n \"plugin-capability-duplicate\",\n \"plugin-contract-major-unsupported\",\n \"plugin-required-capability-unsupported\",\n \"plugin-negotiated-descriptor-invalid\",\n \"plugin-descriptor-provider-mismatch\",\n \"plugin-sync-page-schema-invalid\",\n \"provider-account-schema-invalid\",\n \"release-head-schema-invalid\",\n \"release-revision-envelope-invalid\",\n \"readiness-assessment-digest-mismatch\",\n \"readiness-assessment-identity-mismatch\",\n \"readiness-assessment-materialization-mismatch\",\n \"readiness-assessment-schema-invalid\",\n \"readiness-candidate-digest-mismatch\",\n \"readiness-environment-head-schema-invalid\",\n \"readiness-head-assessment-mismatch\",\n \"readiness-release-head-schema-invalid\",\n \"readiness-rule-digest-mismatch\",\n \"readiness-rule-identity-mismatch\",\n \"readiness-rule-schema-invalid\",\n \"role-assignment-schema-invalid\",\n \"session-schema-invalid\",\n \"pairing-code-schema-invalid\",\n \"schema-decode-failed\",\n \"snapshot-beyond-head\",\n \"snapshot-digest-mismatch\",\n \"snapshot-identity-mismatch\",\n \"workspace-settings-digest-mismatch\",\n \"workspace-settings-schema-invalid\",\n \"workspace-schema-invalid\"\n])\n\n/** Decoded quarantine diagnostic code. */\nexport type QuarantineReasonCode = typeof QuarantineReasonCode.Type\n\n/** Fixed diagnostics prevent malformed payload content entering quarantine text. */\nexport const QuarantineDiagnosticSummary = Schema.Literals([\n \"Stored content metadata failed schema validation.\",\n \"Stored delivery graph record digest does not match its content.\",\n \"Stored delivery node failed schema validation.\",\n \"Stored delivery relationship failed schema validation.\",\n \"Stored domain event payload digest does not match its content.\",\n \"Stored domain event failed schema validation.\",\n \"Stored entity projection failed schema validation.\",\n \"Stored entity revision failed schema validation.\",\n \"Stored evidence claim failed schema validation.\",\n \"Stored evidence freshness failed schema validation.\",\n \"Stored evidence item failed schema validation.\",\n \"Stored followed-resource failed schema validation.\",\n \"Stored governed action failed schema validation.\",\n \"Stored governed action digest does not match its content.\",\n \"Stored governed action identity does not match its repository key.\",\n \"Stored governed action transition chain is invalid.\",\n \"Stored governed action head does not match its transition history.\",\n \"Stored governed action authority companion is invalid.\",\n \"Stored governed action transition failed schema validation.\",\n \"Stored governed action transition digest does not match its content.\",\n \"Stored governed action audit record does not match its transition.\",\n \"Stored person avatar failed schema validation.\",\n \"Stored person identity failed schema validation.\",\n \"Stored person record failed schema validation.\",\n \"Stored plugin connection failed schema validation.\",\n \"Stored plugin configuration failed schema validation.\",\n \"Plugin descriptor candidate failed schema validation.\",\n \"Plugin descriptor envelope failed schema validation.\",\n \"Plugin descriptor contains duplicate capability offers.\",\n \"Plugin descriptor contract major is unsupported.\",\n \"Plugin descriptor requires an unsupported capability version.\",\n \"Negotiated plugin descriptor failed schema validation.\",\n \"Plugin descriptor provider does not match its connection.\",\n \"Plugin sync page failed schema validation.\",\n \"Stored provider-account failed schema validation.\",\n \"Stored release head failed schema validation.\",\n \"Stored release revision envelope failed schema validation.\",\n \"Stored readiness assessment digest does not match its content.\",\n \"Stored readiness assessment identity does not match its repository key.\",\n \"Stored readiness assessment materialization does not match its canonical content.\",\n \"Stored readiness assessment failed schema validation.\",\n \"Stored readiness candidate digest does not match its canonical material.\",\n \"Stored environment readiness head failed schema validation.\",\n \"Stored readiness head does not match its referenced assessment.\",\n \"Stored release readiness head failed schema validation.\",\n \"Stored readiness rule digest does not match its canonical material.\",\n \"Stored readiness rule identity does not match its repository key.\",\n \"Stored readiness rule failed schema validation.\",\n \"Stored release snapshot exceeds its authoritative head.\",\n \"Stored release snapshot digest does not match its content.\",\n \"Stored release snapshot does not satisfy the current release schema.\",\n \"Stored release snapshot failed schema validation.\",\n \"Stored release snapshot identity does not match its repository key.\",\n \"Stored role assignment failed schema validation.\",\n \"Stored session failed schema validation.\",\n \"Stored pairing code failed schema validation.\",\n \"Stored workspace settings digest does not match its content.\",\n \"Stored workspace settings failed schema validation.\",\n \"Stored workspace failed schema validation.\"\n])\n\n/** Decoded fixed quarantine diagnostic summary. */\nexport type QuarantineDiagnosticSummary = typeof QuarantineDiagnosticSummary.Type\n\nconst QuarantineRecordKey = Schema.String.check(\n Schema.isPattern(\n /^(?:[0-9a-f]{64}|[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}(?::[1-9]\\d*)?)$/u,\n { expected: \"a canonical digest, entity ID, or revision-qualified entity ID\" }\n )\n)\n\n/** Redacted metadata describing a malformed persisted record. */\nexport const QuarantinedRecordMetadata = Schema.Struct({\n workspaceId: WorkspaceId,\n recordKind: QuarantineRecordKind,\n recordKey: QuarantineRecordKey,\n schemaVersion: Schema.Number.check(Schema.isInt(), Schema.isGreaterThan(0)),\n payloadDigest: ContentBlobDigest,\n diagnosticCode: QuarantineReasonCode,\n diagnosticSummary: QuarantineDiagnosticSummary,\n firstObservedAt: UtcTimestamp,\n lastObservedAt: UtcTimestamp,\n occurrenceCount: Schema.Number.check(Schema.isInt(), Schema.isGreaterThan(0))\n})\n\n/** Decoded redacted quarantine metadata. */\nexport type QuarantinedRecordMetadata = typeof QuarantinedRecordMetadata.Type\n","import * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport type { Success } from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Schema from \"effect/Schema\"\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\"\n\nimport { WorkspaceId } from \"../../../domain/identifiers.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport { Database } from \"../Database.js\"\nimport { QuarantineWriteError } from \"../errors.js\"\nimport { mapPersistenceOperation } from \"./internal.js\"\nimport { ContentBlobDigest, QuarantinedRecordMetadata, QuarantineReasonCode, QuarantineRecordKind } from \"./models.js\"\n\nconst QuarantineIdentity = Schema.Struct({\n workspaceId: WorkspaceId,\n recordKind: QuarantineRecordKind,\n recordKey: QuarantinedRecordMetadata.fields.recordKey,\n schemaVersion: Schema.Number.check(Schema.isInt(), Schema.isGreaterThan(0)),\n payloadDigest: ContentBlobDigest,\n diagnosticCode: QuarantineReasonCode\n})\n\nconst RecordMalformedRequest = Schema.Struct({\n ...QuarantineIdentity.fields,\n diagnosticSummary: QuarantinedRecordMetadata.fields.diagnosticSummary,\n observedAt: UtcTimestamp\n})\n\nconst makeQuarantineRepository = Effect.gen(function*() {\n const database = yield* Database\n const sql = database.sql\n\n const upsert = SqlSchema.void({\n Request: RecordMalformedRequest,\n execute: ({\n diagnosticCode,\n diagnosticSummary,\n observedAt,\n payloadDigest,\n recordKey,\n recordKind,\n schemaVersion,\n workspaceId\n }) =>\n sql`INSERT INTO quarantined_records (\n workspace_id, record_kind, record_key, schema_version, payload_digest,\n diagnostic_code, diagnostic_summary, first_observed_at,\n last_observed_at, occurrence_count\n ) VALUES (\n ${workspaceId}, ${recordKind}, ${recordKey}, ${schemaVersion}, ${payloadDigest},\n ${diagnosticCode}, ${diagnosticSummary}, ${observedAt}, ${observedAt}, 1\n )\n ON CONFLICT (\n workspace_id, record_kind, record_key, schema_version,\n payload_digest, diagnostic_code\n ) DO UPDATE SET\n diagnostic_summary = excluded.diagnostic_summary,\n first_observed_at = MIN(\n quarantined_records.first_observed_at,\n excluded.first_observed_at\n ),\n last_observed_at = MAX(\n quarantined_records.last_observed_at,\n excluded.last_observed_at\n ),\n occurrence_count = quarantined_records.occurrence_count + 1`\n })\n\n const listRows = SqlSchema.findAll({\n Request: Schema.Struct({ workspaceId: WorkspaceId }),\n Result: QuarantinedRecordMetadata,\n execute: ({ workspaceId }) =>\n sql`SELECT\n workspace_id AS workspaceId,\n record_kind AS recordKind,\n record_key AS recordKey,\n schema_version AS schemaVersion,\n payload_digest AS payloadDigest,\n diagnostic_code AS diagnosticCode,\n diagnostic_summary AS diagnosticSummary,\n first_observed_at AS firstObservedAt,\n last_observed_at AS lastObservedAt,\n occurrence_count AS occurrenceCount\n FROM quarantined_records\n WHERE workspace_id = ${workspaceId}\n ORDER BY last_observed_at DESC, record_key`\n })\n\n return {\n list: Effect.fn(\"QuarantineRepository.list\")(function*(workspaceId: WorkspaceId) {\n return yield* listRows({ workspaceId }).pipe(mapPersistenceOperation(\"quarantine.list\"))\n }),\n recordMalformed: Effect.fn(\"QuarantineRepository.recordMalformed\")(function*(\n workspaceId: WorkspaceId,\n input: Omit<typeof RecordMalformedRequest.Type, \"workspaceId\">\n ) {\n return yield* upsert({ workspaceId, ...input }).pipe(\n Effect.mapError(() =>\n new QuarantineWriteError({\n workspaceId,\n recordKind: input.recordKind,\n recordKey: input.recordKey\n })\n )\n )\n })\n }\n})\n\n/** Redacted, bounded malformed-record diagnostics with workspace isolation. */\nexport interface QuarantineRepositoryService extends Success<typeof makeQuarantineRepository> {}\n\n/** Effect service for persisted-record quarantine metadata. */\nexport class QuarantineRepository extends Context.Service<\n QuarantineRepository,\n QuarantineRepositoryService\n>()(\"@knpkv/control-center/QuarantineRepository\") {\n /** Layer that binds SQL queries to the shared database at construction. */\n static readonly layer = Layer.effect(QuarantineRepository, makeQuarantineRepository)\n}\n","import type * as Crypto from \"effect/Crypto\"\nimport * as Effect from \"effect/Effect\"\nimport * as Encoding from \"effect/Encoding\"\n\nimport type { WorkspaceId } from \"../../../domain/identifiers.js\"\nimport type { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport { PersistenceOperationError } from \"../errors.js\"\nimport { ContentBlobDigest } from \"./models.js\"\nimport type {\n QuarantineDiagnosticSummary,\n QuarantinedRecordMetadata,\n QuarantineReasonCode,\n QuarantineRecordKind\n} from \"./models.js\"\nimport type { QuarantineRepositoryService } from \"./quarantineRepository.js\"\n\n/** Fixed, redacted identity for quarantining one malformed persisted row. */\nexport interface PersistedRowDiagnostic {\n readonly workspaceId: WorkspaceId\n readonly recordKind: QuarantineRecordKind\n readonly recordKey: QuarantinedRecordMetadata[\"recordKey\"]\n readonly diagnosticCode: QuarantineReasonCode\n readonly diagnosticSummary: QuarantineDiagnosticSummary\n readonly observedAt: UtcTimestamp\n readonly row: unknown\n}\n\n/** Build row-level quarantine writes without retaining any malformed values. */\nexport const makePersistedRowQuarantine = (\n cryptoService: Crypto.Crypto,\n quarantine: QuarantineRepositoryService\n) => {\n const digestRow = Effect.fn(\"PersistedRowQuarantine.digest\")(function*(row: unknown) {\n const serialized = yield* Effect.try({\n try: () => JSON.stringify(row),\n catch: () => new PersistenceOperationError({ operation: \"quarantine.encode-row\" })\n })\n const bytes = yield* Effect.fromResult(\n Encoding.decodeBase64(Encoding.encodeBase64(serialized))\n ).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"quarantine.encode-row\" }))\n )\n const digest = yield* cryptoService.digest(\"SHA-256\", bytes).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"quarantine.digest-row\" }))\n )\n return ContentBlobDigest.make(Encoding.encodeHex(digest))\n })\n\n return Effect.fn(\"PersistedRowQuarantine.record\")(function*(diagnostic: PersistedRowDiagnostic) {\n const payloadDigest = yield* digestRow(diagnostic.row)\n yield* quarantine.recordMalformed(diagnostic.workspaceId, {\n recordKind: diagnostic.recordKind,\n recordKey: diagnostic.recordKey,\n schemaVersion: 1,\n payloadDigest,\n diagnosticCode: diagnostic.diagnosticCode,\n diagnosticSummary: diagnostic.diagnosticSummary,\n observedAt: diagnostic.observedAt\n })\n })\n}\n","import { Schema } from \"effect\"\n\nconst SECRET_REF_PATTERN = /^secret_[0-9a-f]{64}$/u\n\n/** Opaque identifier for an owner-only secret. It never contains secret bytes. */\nexport const SecretRef = Schema.String.check(\n Schema.isPattern(SECRET_REF_PATTERN, { expected: \"an opaque secret reference\" })\n).pipe(Schema.brand(\"SecretRef\"))\n\n/** Decoded opaque secret identifier. */\nexport type SecretRef = typeof SecretRef.Type\n","import type { Path } from \"effect\"\n\nimport type { WorkspaceId } from \"../../../domain/identifiers.js\"\nimport type { BlobDigest } from \"./BlobDigest.js\"\n\n/** Derived path shape. It is kept inside the server persistence boundary. */\nexport interface BlobPath {\n readonly workspaceDirectory: string\n readonly objectDirectory: string\n readonly file: string\n}\n\n/** Derives the partitioned object path from already-decoded identity values. */\nexport const blobPath = (\n path: Path.Path,\n canonicalRoot: string,\n workspaceId: WorkspaceId,\n digest: BlobDigest\n): BlobPath => {\n const workspaceDirectory = path.join(canonicalRoot, \"objects\", workspaceId)\n const objectDirectory = path.join(\n workspaceDirectory,\n \"sha256\",\n digest.slice(0, 2),\n digest.slice(2, 4)\n )\n\n return {\n workspaceDirectory,\n objectDirectory,\n file: path.join(objectDirectory, digest)\n }\n}\n","/** Durable release-thread and local-agent job contracts. @module */\nimport { AgentContextFingerprint, AgentProviderId, AgentRuntimeEvent, AgentSessionRef } from \"@knpkv/ai-runtime\"\nimport * as Schema from \"effect/Schema\"\nimport * as SchemaGetter from \"effect/SchemaGetter\"\n\nimport { ReviewAgentProfile, ReviewSuggestionPublicationOperation } from \"../../../api/agent.js\"\nimport {\n AgentThreadId,\n GovernedActionId,\n JobId,\n PluginConnectionId,\n PrReviewSuggestionRevisionId,\n ReleaseId,\n ReviewSuggestionPublicationReservationId,\n WorkspaceId\n} from \"../../../domain/identifiers.js\"\nimport { PrReviewReport, PrReviewSubject, PrReviewSuggestion, PrReviewSuggestionId } from \"../../../domain/prReview.js\"\nimport {\n PrReviewSuggestionEdit,\n PrReviewSuggestionRevisionAuthor,\n PrReviewSuggestionRevisionPage,\n PrReviewSuggestionRevisionPageSize,\n PrReviewSuggestionRevisionSequence\n} from \"../../../domain/prReviewRevision.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\n\n/** Maximum persisted provider output across one attempt. */\nexport const MAXIMUM_AGENT_ATTEMPT_OUTPUT_BYTES = 1_048_576\n\n/**\n * Maximum prompt characters accepted by durable enqueue.\n *\n * JSON may escape one UTF-16 code unit to six bytes. This conservative bound\n * therefore keeps the complete `{ \"prompt\": ... }` event below 32 KiB.\n */\nexport const MAXIMUM_AGENT_JOB_PROMPT_LENGTH = 5_000\n\n/** Maximum thread events returned by one replay page. */\nexport const MAXIMUM_AGENT_THREAD_EVENT_PAGE_SIZE = 128\n\n/** One explicit extension is bounded to the selected profile's original budget. */\nexport const MAXIMUM_REVIEW_BUDGET_EXTENSION_COUNT = 1\n\n/** Hard upper bound for one immutable review, including its single extension. */\nexport const MAXIMUM_REVIEW_BUDGET_MILLIS = 3_600_000\n\n/** Positive sequence assigned to attempts within one durable job. */\nexport const AgentAttemptSequence = Schema.Int.check(\n Schema.isBetween({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER })\n).pipe(Schema.brand(\"AgentAttemptSequence\"))\nexport type AgentAttemptSequence = typeof AgentAttemptSequence.Type\n\n/** Cursor used to request thread events after an already observed event. */\nexport const AgentEventCursor = Schema.Int.check(\n Schema.isBetween({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER })\n).pipe(Schema.brand(\"AgentEventCursor\"))\nexport type AgentEventCursor = typeof AgentEventCursor.Type\n\n/** Bounded replay-page size accepted by the repository. */\nexport const AgentThreadEventPageSize = Schema.Int.check(\n Schema.isBetween({ minimum: 1, maximum: MAXIMUM_AGENT_THREAD_EVENT_PAGE_SIZE })\n).pipe(Schema.brand(\"AgentThreadEventPageSize\"))\nexport type AgentThreadEventPageSize = typeof AgentThreadEventPageSize.Type\n\n/** Opaque worker identity retained with a durable claim. */\nexport const AgentLeaseOwner = Schema.String.check(\n Schema.isTrimmed(),\n Schema.isNonEmpty(),\n Schema.isMaxLength(200)\n).pipe(Schema.brand(\"AgentLeaseOwner\"))\nexport type AgentLeaseOwner = typeof AgentLeaseOwner.Type\n\n/** Secret bearer value proving ownership of one attempt lease. */\nexport const AgentLeaseToken = Schema.String.check(\n Schema.isPattern(/^[0-9a-f]{64}$/u, { expected: \"a lowercase 256-bit token\" })\n).pipe(Schema.brand(\"AgentLeaseToken\"))\nexport type AgentLeaseToken = typeof AgentLeaseToken.Type\n\nconst SubjectRevision = Schema.String.check(\n Schema.isTrimmed(),\n Schema.isNonEmpty(),\n Schema.isMaxLength(500)\n)\n\nconst AgentModel = Schema.NullOr(\n Schema.String.check(Schema.isTrimmed(), Schema.isNonEmpty(), Schema.isMaxLength(500))\n)\n\n/** Prompt guaranteed to fit the durable user-message event envelope. */\nexport const AgentJobPrompt = Schema.String.check(\n Schema.isNonEmpty(),\n Schema.isMaxLength(MAXIMUM_AGENT_JOB_PROMPT_LENGTH)\n)\nexport type AgentJobPrompt = typeof AgentJobPrompt.Type\n\n/** Durable task discriminator used to scope worker claims before execution. */\nexport const AgentJobTaskTag = Schema.Literals([\"release-chat\", \"pr-review\"])\nexport type AgentJobTaskTag = typeof AgentJobTaskTag.Type\n\n/** Existing release-scoped conversational work. */\nconst ReleaseChatAgentJobTask = Schema.TaggedStruct(\"release-chat\", {})\n\nconst PrReviewAgentJobTaskFields = {\n pluginConnectionId: PluginConnectionId,\n subject: PrReviewSubject,\n reviewProfile: ReviewAgentProfile,\n intent: Schema.optionalKey(Schema.Literals([\"full-review\", \"suggestion-edit\", \"suggestion-revalidation\"])),\n target: Schema.optionalKey(Schema.Struct({\n sourceJobId: JobId,\n suggestionId: PrReviewSuggestionId,\n selectedRevisionId: PrReviewSuggestionRevisionId,\n history: PrReviewSuggestionRevisionPage\n }))\n}\n\n/** Read-only review request bound to one immutable pull request head. */\nconst EnqueuePrReviewAgentJobTask = Schema.TaggedStruct(\"pr-review\", PrReviewAgentJobTaskFields)\n\nconst PrReviewThreadRequestSummary = Schema.Struct({\n jobId: JobId,\n prompt: AgentJobPrompt,\n subjectRevision: SubjectRevision,\n requestedAt: UtcTimestamp\n})\n\nconst PrReviewThreadRunSummary = Schema.Struct({\n jobId: JobId,\n subject: PrReviewSubject,\n state: Schema.Literals([\"cancelled\", \"failed\", \"interrupted\", \"succeeded\", \"unknown\"]),\n requestedAt: UtcTimestamp,\n suggestionTitles: Schema.Array(\n Schema.String.check(Schema.isTrimmed(), Schema.isNonEmpty(), Schema.isMaxLength(500))\n ).check(Schema.isMaxLength(8)),\n suggestionsTruncated: Schema.Boolean,\n noteTitles: Schema.Array(\n Schema.String.check(Schema.isTrimmed(), Schema.isNonEmpty(), Schema.isMaxLength(500))\n ).check(Schema.isMaxLength(8)),\n notesTruncated: Schema.Boolean,\n limitation: Schema.NullOr(\n Schema.String.check(Schema.isTrimmed(), Schema.isNonEmpty(), Schema.isMaxLength(1_000))\n )\n})\n\n/**\n * Small review-thread context frozen into one immutable run.\n *\n * Full messages and artifacts remain behind explicit paged lookup boundaries.\n */\nexport const PrReviewThreadContextSnapshot = Schema.Struct({\n recentRequests: Schema.Array(PrReviewThreadRequestSummary).check(Schema.isMaxLength(4)),\n priorRuns: Schema.Array(PrReviewThreadRunSummary).check(Schema.isMaxLength(4)),\n historyTruncated: Schema.Boolean\n})\nexport type PrReviewThreadContextSnapshot = typeof PrReviewThreadContextSnapshot.Type\n\n/** Empty first-run context used before a review thread has prior activity. */\nexport const EMPTY_PR_REVIEW_THREAD_CONTEXT = PrReviewThreadContextSnapshot.make({\n recentRequests: [],\n priorRuns: [],\n historyTruncated: false\n})\n\n/** Persisted review work with the bounded thread context selected at enqueue. */\nconst PrReviewAgentJobTask = Schema.TaggedStruct(\"pr-review\", {\n ...PrReviewAgentJobTaskFields,\n context: PrReviewThreadContextSnapshot\n})\n\n/** Caller-owned task request before repository context enrichment. */\nexport const EnqueueAgentJobTask = Schema.Union([\n ReleaseChatAgentJobTask,\n EnqueuePrReviewAgentJobTask\n]).pipe(Schema.toTaggedUnion(\"_tag\"))\nexport type EnqueueAgentJobTask = typeof EnqueueAgentJobTask.Type\n\n/** Durable task context used to select an internal task executor. */\nexport const AgentJobTask = Schema.Union([\n ReleaseChatAgentJobTask,\n PrReviewAgentJobTask\n]).pipe(Schema.toTaggedUnion(\"_tag\"))\nexport type AgentJobTask = typeof AgentJobTask.Type\n\n/** Lifecycle state of one durable agent job. */\nexport const AgentJobState = Schema.Literals([\n \"queued\",\n \"running\",\n \"cancel-requested\",\n \"succeeded\",\n \"failed\",\n \"cancelled\"\n])\nexport type AgentJobState = typeof AgentJobState.Type\n\n/** Immutable request persisted before a worker may claim it. */\nexport const EnqueueAgentJobInput = Schema.Struct({\n workspaceId: WorkspaceId,\n releaseId: ReleaseId,\n jobId: JobId,\n providerId: AgentProviderId,\n model: AgentModel,\n access: Schema.Literals([\"read-only\", \"workspace-write\"]),\n userPrompt: AgentJobPrompt,\n prompt: AgentJobPrompt,\n contextFingerprint: AgentContextFingerprint,\n subjectRevision: SubjectRevision,\n task: EnqueueAgentJobTask,\n createdAt: UtcTimestamp\n})\nexport type EnqueueAgentJobInput = typeof EnqueueAgentJobInput.Type\n\n/** Context frozen for one provider attempt. */\nexport const AgentContextSnapshotRecord = Schema.Struct({\n workspaceId: WorkspaceId,\n releaseId: ReleaseId,\n subjectRevision: SubjectRevision,\n fingerprint: AgentContextFingerprint,\n task: AgentJobTask\n})\nexport type AgentContextSnapshotRecord = typeof AgentContextSnapshotRecord.Type\n\n/** Claimed work returned only after the lease and attempt are durable. */\nexport const ClaimedAgentJob = Schema.Struct({\n workspaceId: WorkspaceId,\n releaseId: ReleaseId,\n threadId: AgentThreadId,\n jobId: JobId,\n attemptSequence: AgentAttemptSequence,\n leaseOwner: AgentLeaseOwner,\n leaseToken: AgentLeaseToken,\n leaseExpiresAt: UtcTimestamp,\n providerId: AgentProviderId,\n model: AgentModel,\n access: Schema.Literals([\"read-only\", \"workspace-write\"]),\n prompt: AgentJobPrompt,\n context: AgentContextSnapshotRecord,\n reviewBudgetMillis: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 3_600_000 }))),\n reviewBudgetExtensionCount: Schema.optionalKey(\n Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: MAXIMUM_REVIEW_BUDGET_EXTENSION_COUNT }))\n ),\n sessionRef: Schema.NullOr(AgentSessionRef),\n cancellationRequested: Schema.Boolean\n})\nexport type ClaimedAgentJob = typeof ClaimedAgentJob.Type\n\n/**\n * Identity and expiration used to claim or reclaim one queued job.\n *\n * `claimedAt` is caller-reported context only; repository clock time owns\n * lease eligibility and the durable acquisition timestamp.\n */\nexport const ClaimAgentJobInput = Schema.Struct({\n workspaceId: WorkspaceId,\n taskTags: Schema.Array(AgentJobTaskTag).check(\n Schema.isMinLength(1),\n Schema.isMaxLength(AgentJobTaskTag.literals.length),\n Schema.isUnique()\n ),\n leaseOwner: AgentLeaseOwner,\n leaseToken: AgentLeaseToken,\n claimedAt: UtcTimestamp,\n leaseExpiresAt: UtcTimestamp\n})\nexport type ClaimAgentJobInput = typeof ClaimAgentJobInput.Type\n\n/** Provider event persisted under an active attempt lease. */\nexport const AppendAgentEventInput = Schema.Struct({\n workspaceId: WorkspaceId,\n jobId: JobId,\n attemptSequence: AgentAttemptSequence,\n leaseToken: AgentLeaseToken,\n event: AgentRuntimeEvent,\n occurredAt: UtcTimestamp\n})\nexport type AppendAgentEventInput = typeof AppendAgentEventInput.Type\n\n/** Untrusted complete review output presented under one active attempt lease. */\nexport const CompleteAgentReviewInput = Schema.Struct({\n workspaceId: WorkspaceId,\n jobId: JobId,\n attemptSequence: AgentAttemptSequence,\n leaseToken: AgentLeaseToken,\n report: Schema.Unknown,\n completedAt: UtcTimestamp\n})\nexport type CompleteAgentReviewInput = typeof CompleteAgentReviewInput.Type\n\n/** Startup transition for review attempts whose owning process disappeared. */\nexport const InterruptRunningReviewsInput = Schema.Struct({\n workspaceId: WorkspaceId,\n interruptedAt: UtcTimestamp,\n preservedAttempts: Schema.optionalKey(Schema.Array(Schema.Struct({\n jobId: JobId,\n attemptSequence: AgentAttemptSequence\n })))\n})\nexport type InterruptRunningReviewsInput = typeof InterruptRunningReviewsInput.Type\n\n/** Durable identity used to match a live Review Sandbox to one immutable attempt. */\nexport const RunningPrReviewAttempt = Schema.Struct({\n jobId: JobId,\n attemptSequence: AgentAttemptSequence,\n attemptId: Schema.String.check(Schema.isPattern(/^[a-f0-9]{12}$/u)),\n sessionRef: Schema.NullOr(AgentSessionRef)\n})\nexport type RunningPrReviewAttempt = typeof RunningPrReviewAttempt.Type\n\n/** Startup handoff for a live server-private Review Sandbox. */\nexport const AttachRunningPrReviewSessionInput = Schema.Struct({\n workspaceId: WorkspaceId,\n jobId: JobId,\n attemptSequence: AgentAttemptSequence,\n sessionRef: AgentSessionRef\n})\nexport type AttachRunningPrReviewSessionInput = typeof AttachRunningPrReviewSessionInput.Type\n\n/** Persist the latest validated report while an immutable review is still running. */\nexport const RecordAgentReviewProgressInput = Schema.Struct({\n workspaceId: WorkspaceId,\n jobId: JobId,\n attemptSequence: AgentAttemptSequence,\n leaseToken: AgentLeaseToken,\n report: Schema.Unknown,\n occurredAt: UtcTimestamp\n})\nexport type RecordAgentReviewProgressInput = typeof RecordAgentReviewProgressInput.Type\n\n/** Read the effective budget of one claimed immutable review. */\nexport const ReadReviewBudgetInput = Schema.Struct({\n workspaceId: WorkspaceId,\n jobId: JobId,\n task: AgentJobTask\n})\nexport type ReadReviewBudgetInput = typeof ReadReviewBudgetInput.Type\n\n/** Digest binding one durable publication reservation to the exact confirmed body. */\nexport const ReviewSuggestionPublicationDigest = Schema.String.check(\n Schema.isPattern(/^sha256:[0-9a-f]{64}$/u, { expected: \"a lowercase SHA-256 digest\" })\n).pipe(Schema.brand(\"ReviewSuggestionPublicationDigest\"))\nexport type ReviewSuggestionPublicationDigest = typeof ReviewSuggestionPublicationDigest.Type\n\n/** Provider comment identity retained for governed lifecycle operations. */\nexport const ReviewSuggestionPublicationCommentId = Schema.String.check(\n Schema.isTrimmed(),\n Schema.isNonEmpty(),\n Schema.isMaxLength(512)\n).pipe(Schema.brand(\"ReviewSuggestionPublicationCommentId\"))\nexport type ReviewSuggestionPublicationCommentId = typeof ReviewSuggestionPublicationCommentId.Type\n\nconst ReviewSuggestionPublicationCommentLocatorEncoded = Schema.TemplateLiteral([\n Schema.Literal(\"comment:\"),\n ReviewSuggestionPublicationCommentId\n])\n\n/** Provider receipt coordinate decoded to the persisted comment identity. */\nexport const ReviewSuggestionPublicationCommentLocator = ReviewSuggestionPublicationCommentLocatorEncoded.pipe(\n Schema.decodeTo(ReviewSuggestionPublicationCommentId, {\n decode: SchemaGetter.transform((locator) => locator.slice(\"comment:\".length)),\n encode: SchemaGetter.transform((commentId): `comment:${string}` => `comment:${commentId}`)\n })\n)\n\n/** Atomic pre-provider reservation for one suggestion and exact confirmed body. */\nexport const ReserveReviewSuggestionPublicationInput = Schema.Struct({\n workspaceId: WorkspaceId,\n jobId: JobId,\n suggestionId: PrReviewSuggestionId,\n revisionId: PrReviewSuggestionRevisionId,\n contentDigest: ReviewSuggestionPublicationDigest,\n operation: Schema.optionalKey(ReviewSuggestionPublicationOperation),\n commentId: Schema.optionalKey(ReviewSuggestionPublicationCommentId),\n reservationId: ReviewSuggestionPublicationReservationId,\n reservedAt: UtcTimestamp\n})\nexport type ReserveReviewSuggestionPublicationInput = typeof ReserveReviewSuggestionPublicationInput.Type\n\n/** Durable result of reserving an exact publication body. */\nexport const ReviewSuggestionPublicationReservation = Schema.Union([\n Schema.TaggedStruct(\"acquired\", {\n commentId: Schema.optionalKey(ReviewSuggestionPublicationCommentId)\n }),\n Schema.TaggedStruct(\"in-progress\", {\n commentId: Schema.optionalKey(ReviewSuggestionPublicationCommentId)\n }),\n Schema.TaggedStruct(\"recoverable\", {\n publicationId: GovernedActionId,\n publishedAt: UtcTimestamp,\n reservationId: ReviewSuggestionPublicationReservationId,\n commentId: Schema.optionalKey(ReviewSuggestionPublicationCommentId)\n }),\n Schema.TaggedStruct(\"published\", {\n publicationId: GovernedActionId,\n publishedAt: UtcTimestamp,\n commentId: Schema.optionalKey(ReviewSuggestionPublicationCommentId)\n })\n])\nexport type ReviewSuggestionPublicationReservation = typeof ReviewSuggestionPublicationReservation.Type\n\n/** Release one exact reservation after a confirmed provider no-write outcome. */\nexport const ReleaseReviewSuggestionPublicationInput = Schema.Struct({\n workspaceId: WorkspaceId,\n jobId: JobId,\n suggestionId: PrReviewSuggestionId,\n revisionId: PrReviewSuggestionRevisionId,\n contentDigest: ReviewSuggestionPublicationDigest,\n reservationId: ReviewSuggestionPublicationReservationId\n})\nexport type ReleaseReviewSuggestionPublicationInput = typeof ReleaseReviewSuggestionPublicationInput.Type\n\n/** Successful governed publication to overlay onto one immutable review report. */\nexport const RecordReviewSuggestionPublicationInput = Schema.Struct({\n workspaceId: WorkspaceId,\n jobId: JobId,\n suggestionId: PrReviewSuggestionId,\n revisionId: PrReviewSuggestionRevisionId,\n contentDigest: ReviewSuggestionPublicationDigest,\n operation: Schema.optionalKey(ReviewSuggestionPublicationOperation),\n reservationId: ReviewSuggestionPublicationReservationId,\n publicationId: GovernedActionId,\n commentId: Schema.optionalKey(ReviewSuggestionPublicationCommentId),\n publishedAt: UtcTimestamp,\n finalize: Schema.optionalKey(Schema.Boolean)\n})\nexport type RecordReviewSuggestionPublicationInput = typeof RecordReviewSuggestionPublicationInput.Type\n\n/** Lookup for the latest durable publication target of one exact suggestion. */\nexport const ReadReviewSuggestionPublicationInput = Schema.Struct({\n workspaceId: WorkspaceId,\n jobId: JobId,\n suggestionId: PrReviewSuggestionId,\n revisionId: PrReviewSuggestionRevisionId\n})\nexport type ReadReviewSuggestionPublicationInput = typeof ReadReviewSuggestionPublicationInput.Type\n\nexport const ReadReviewSuggestionPublication = Schema.Struct({\n state: Schema.Literal(\"published\"),\n publicationId: GovernedActionId,\n commentId: ReviewSuggestionPublicationCommentId\n})\nexport type ReadReviewSuggestionPublication = typeof ReadReviewSuggestionPublication.Type\n\n/** Workspace-scoped lookup for one durable review result. */\nexport const AgentReviewResultInput = Schema.Struct({\n workspaceId: WorkspaceId,\n jobId: JobId\n})\nexport type AgentReviewResultInput = typeof AgentReviewResultInput.Type\n\n/** Request one operator-authorized extension of a running review's budget. */\nexport const ExtendReviewBudgetInput = Schema.Struct({\n workspaceId: WorkspaceId,\n jobId: JobId,\n extendedAt: UtcTimestamp\n})\nexport type ExtendReviewBudgetInput = typeof ExtendReviewBudgetInput.Type\n\n/** Sanitized durable review result attributable to one terminal attempt. */\nexport const AgentReviewResultRecord = Schema.Struct({\n workspaceId: WorkspaceId,\n jobId: JobId,\n attemptSequence: AgentAttemptSequence,\n report: PrReviewReport,\n completedAt: UtcTimestamp\n})\nexport type AgentReviewResultRecord = typeof AgentReviewResultRecord.Type\n\n/** Workspace-scoped bounded read of one stable suggestion's prior revisions. */\nexport const ReadReviewSuggestionRevisionsInput = Schema.Struct({\n workspaceId: WorkspaceId,\n jobId: JobId,\n suggestionId: PrReviewSuggestionId,\n beforeSequence: Schema.NullOr(PrReviewSuggestionRevisionSequence),\n limit: PrReviewSuggestionRevisionPageSize\n})\nexport type ReadReviewSuggestionRevisionsInput = typeof ReadReviewSuggestionRevisionsInput.Type\n\n/** Complete compare-and-append command for one immutable suggestion edit. */\nexport const ReviewSuggestionRevisionLeaseFence = Schema.Struct({\n jobId: JobId,\n attemptSequence: AgentAttemptSequence,\n leaseToken: AgentLeaseToken\n})\nexport type ReviewSuggestionRevisionLeaseFence = typeof ReviewSuggestionRevisionLeaseFence.Type\n\nexport const AppendReviewSuggestionRevisionInput = Schema.Struct({\n workspaceId: WorkspaceId,\n jobId: JobId,\n suggestionId: PrReviewSuggestionId,\n expectedRevisionId: PrReviewSuggestionRevisionId,\n expectedSequence: PrReviewSuggestionRevisionSequence,\n edit: PrReviewSuggestionEdit,\n state: Schema.optionalKey(Schema.Literals([\"dismissed\", \"stale\"])),\n dismissalReason: Schema.optionalKey(PrReviewSuggestion.fields.dismissalReason),\n validation: Schema.optionalKey(Schema.Literal(\"validated\")),\n author: PrReviewSuggestionRevisionAuthor,\n createdAt: UtcTimestamp,\n leaseFence: Schema.optionalKey(ReviewSuggestionRevisionLeaseFence)\n})\nexport type AppendReviewSuggestionRevisionInput = typeof AppendReviewSuggestionRevisionInput.Type\n\n/** Atomic targeted completion: append the source revision and terminalize the worker job together. */\nexport const CompleteTargetedReviewInput = Schema.Struct({\n source: AppendReviewSuggestionRevisionInput,\n target: CompleteAgentReviewInput\n})\nexport type CompleteTargetedReviewInput = typeof CompleteTargetedReviewInput.Type\n\n/** Exact immutable subject used to recover its newest durable review job. */\nexport const LatestAgentReviewInput = Schema.Struct({\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n subject: PrReviewSubject,\n excludeJobId: Schema.optionalKey(JobId),\n excludeSubjectRevision: Schema.optionalKey(Schema.String),\n jobId: Schema.optionalKey(JobId),\n allowDifferentHead: Schema.optionalKey(Schema.Boolean)\n})\nexport type LatestAgentReviewInput = typeof LatestAgentReviewInput.Type\n\n/** Cursor-bounded lookup for the durable thread behind a stable pull request. */\nexport const PrReviewThreadSubject = Schema.Struct({\n providerId: PrReviewSubject.fields.providerId,\n repository: PrReviewSubject.fields.repository,\n pullRequestId: PrReviewSubject.fields.pullRequestId\n})\nexport type PrReviewThreadSubject = typeof PrReviewThreadSubject.Type\n\nexport const AgentReviewThreadAfterInput = Schema.Struct({\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n subject: PrReviewThreadSubject,\n after: AgentEventCursor,\n limit: AgentThreadEventPageSize\n})\nexport type AgentReviewThreadAfterInput = typeof AgentReviewThreadAfterInput.Type\n\nexport const AgentReviewThreadBeforeInput = Schema.Struct({\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n subject: PrReviewThreadSubject,\n before: AgentEventCursor,\n limit: AgentThreadEventPageSize\n})\nexport type AgentReviewThreadBeforeInput = typeof AgentReviewThreadBeforeInput.Type\n\n/** Cursor-bounded prior history fenced before one immutable review job. */\nexport const AgentReviewThreadHistoryInput = Schema.Struct({\n workspaceId: WorkspaceId,\n threadId: AgentThreadId,\n beforeJobId: JobId,\n after: AgentEventCursor,\n limit: AgentThreadEventPageSize\n})\nexport type AgentReviewThreadHistoryInput = typeof AgentReviewThreadHistoryInput.Type\n\nexport const AgentReviewThreadTailInput = Schema.Struct({\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n subject: PrReviewThreadSubject,\n limit: AgentThreadEventPageSize\n})\nexport type AgentReviewThreadTailInput = typeof AgentReviewThreadTailInput.Type\n\n/** Newest durable lifecycle state for one exact immutable review subject. */\nexport const LatestAgentReviewRecord = Schema.Struct({\n jobId: JobId,\n threadId: AgentThreadId,\n providerId: AgentProviderId,\n model: AgentModel,\n state: Schema.Union([AgentJobState, Schema.Literal(\"interrupted\")]),\n createdAt: UtcTimestamp,\n terminalAt: Schema.NullOr(UtcTimestamp),\n startedAt: Schema.optionalKey(Schema.NullOr(UtcTimestamp)),\n reviewBudgetMillis: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 3_600_000 }))),\n reviewBudgetExtensionCount: Schema.optionalKey(\n Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: MAXIMUM_REVIEW_BUDGET_EXTENSION_COUNT }))\n ),\n taskIntent: Schema.optionalKey(Schema.NullOr(Schema.Literals([\"suggestion-edit\", \"suggestion-revalidation\"]))),\n report: Schema.NullOr(PrReviewReport),\n reviewProfile: ReviewAgentProfile,\n activity: Schema.Struct({\n events: Schema.Array(\n Schema.String.check(Schema.isNonEmpty(), Schema.isMaxLength(MAXIMUM_AGENT_ATTEMPT_OUTPUT_BYTES))\n ).check(Schema.isMaxLength(MAXIMUM_AGENT_THREAD_EVENT_PAGE_SIZE)),\n truncated: Schema.Boolean\n })\n}).check(\n Schema.makeFilter(\n ({ report, state }) =>\n report === null || state === \"succeeded\" || state === \"failed\" ||\n state === \"cancelled\" || state === \"interrupted\",\n { expected: \"only terminal review jobs to carry a report\" }\n )\n)\nexport type LatestAgentReviewRecord = typeof LatestAgentReviewRecord.Type\n\n/** One immutable event in a release thread. */\nexport const AgentThreadEvent = Schema.Struct({\n workspaceId: WorkspaceId,\n threadId: AgentThreadId,\n eventSequence: AgentEventCursor.check(Schema.isGreaterThan(0)),\n jobId: JobId,\n attemptSequence: Schema.NullOr(AgentAttemptSequence),\n task: Schema.optionalKey(EnqueueAgentJobTask),\n eventKind: Schema.Literals([\n \"user-message\",\n \"job-queued\",\n \"job-started\",\n \"assistant-output\",\n \"progress\",\n \"usage\",\n \"review-report\",\n \"review-suggestion-revised\",\n \"review-suggestion-published\",\n \"job-completed\",\n \"job-failed\",\n \"cancel-requested\"\n ]),\n payload: Schema.Unknown,\n occurredAt: UtcTimestamp\n})\nexport type AgentThreadEvent = typeof AgentThreadEvent.Type\n\n/** Ordered bounded replay page for one release thread. */\nexport interface AgentThreadEventPage {\n readonly events: ReadonlyArray<AgentThreadEvent>\n readonly nextCursor: AgentEventCursor\n}\n\n/** Stable typed failure for invalid job state, lease, or bounded output. */\nexport class AgentJobInputError extends Schema.TaggedErrorClass<AgentJobInputError>()(\n \"AgentJobInputError\",\n {\n workspaceId: WorkspaceId,\n jobId: JobId,\n reason: Schema.Literals([\n \"invalid-transition\",\n \"lease-lost\",\n \"lease-expired\",\n \"cancellation-requested\",\n \"output-limit-exceeded\",\n \"event-limit-exceeded\",\n \"invalid-result\",\n \"revision-identity-mismatch\",\n \"task-mismatch\"\n ])\n }\n) {}\n","import { Schema } from \"effect\"\n\nimport { BlobDigest } from \"./BlobDigest.js\"\n\n/** A blob reference or read option did not satisfy the storage contract. */\nexport class BlobStoreInputError extends Schema.TaggedErrorClass<BlobStoreInputError>()(\"BlobStoreInputError\", {\n operation: Schema.String,\n message: Schema.String\n}) {}\n\n/** The requested blob does not exist in the selected workspace. */\nexport class BlobNotFoundError extends Schema.TaggedErrorClass<BlobNotFoundError>()(\"BlobNotFoundError\", {\n digest: BlobDigest\n}) {}\n\n/** A blob exceeded the operation's configured byte bound. */\nexport class BlobTooLargeError extends Schema.TaggedErrorClass<BlobTooLargeError>()(\"BlobTooLargeError\", {\n digest: Schema.Union([BlobDigest, Schema.Null]),\n actualBytes: Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0)),\n maximumBytes: Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))\n}) {}\n\n/** An opened blob ended before the exact requested byte count was read. */\nexport class BlobUnexpectedEofError extends Schema.TaggedErrorClass<BlobUnexpectedEofError>()(\n \"BlobUnexpectedEofError\",\n {\n operation: Schema.String,\n expectedBytes: Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0)),\n actualBytes: Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))\n }\n) {}\n\n/** Stored bytes no longer match their content address. */\nexport class BlobIntegrityError extends Schema.TaggedErrorClass<BlobIntegrityError>()(\"BlobIntegrityError\", {\n expectedDigest: BlobDigest,\n actualDigest: BlobDigest\n}) {}\n\n/** A path escaped the owner-only object root or crossed a symbolic link. */\nexport class BlobContainmentError extends Schema.TaggedErrorClass<BlobContainmentError>()(\n \"BlobContainmentError\",\n {\n operation: Schema.String,\n message: Schema.String\n }\n) {}\n\n/** The platform object-store operation failed. */\nexport class BlobStoreIoError extends Schema.TaggedErrorClass<BlobStoreIoError>()(\"BlobStoreIoError\", {\n operation: Schema.String,\n message: Schema.String\n}) {}\n\n/** Redacts platform details before they cross the object-store boundary. */\nexport const blobStoreIoError = (operation: string, _cause: unknown): BlobStoreIoError =>\n new BlobStoreIoError({ operation, message: \"platform storage operation failed\" })\n\n/** Typed failures exposed by the blob-store boundary. */\nexport type BlobStoreError =\n | BlobContainmentError\n | BlobIntegrityError\n | BlobNotFoundError\n | BlobStoreInputError\n | BlobStoreIoError\n | BlobTooLargeError\n | BlobUnexpectedEofError\n","import type { Crypto, FileSystem, Path } from \"effect\"\nimport { Effect, Result } from \"effect\"\n\nimport { type BlobStoreError, blobStoreIoError } from \"./BlobStoreError.js\"\nimport type { PinnedDirectory } from \"./PinnedDirectory.js\"\n\nexport const BLOB_FILE_MODE = 0o600\nconst TEMPORARY_NAME_ATTEMPTS = 4\n\nconst openFailure = <E>(error: E): { readonly _tag: \"OpenFailure\"; readonly error: E } => ({\n _tag: \"OpenFailure\",\n error\n})\n\nconst linkResult = <A>(linked: A): { readonly _tag: \"LinkResult\"; readonly linked: A } => ({\n _tag: \"LinkResult\",\n linked\n})\n\n/** Builds crash-safe exclusive publication around captured platform services. */\nexport const makeBlobPublisher = (\n fs: FileSystem.FileSystem,\n path: Path.Path,\n cryptoService: Crypto.Crypto\n) => {\n const temporaryName = Effect.fn(\"BlobStore.temporaryName\")(function*(directory: string) {\n const random = yield* cryptoService.randomBytes(16).pipe(\n Effect.mapError((cause) => blobStoreIoError(\"create temporary name\", cause))\n )\n const suffix = Array.from(random, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")\n return path.join(directory, `.incoming-${suffix}`)\n })\n\n return Effect.fn(\"BlobStore.publish\")(function*(\n directory: PinnedDirectory,\n destinationName: string,\n bytes: Uint8Array,\n mode: \"exclusive\" | \"replace\" = \"exclusive\",\n commit?: ((destination: string) => Effect.Effect<void, BlobStoreError>) | undefined\n ) {\n const destination = path.join(directory.path, destinationName)\n for (let attempt = 0; attempt < TEMPORARY_NAME_ATTEMPTS; attempt += 1) {\n const temporary = yield* temporaryName(directory.path)\n const outcome = yield* Effect.scoped(\n Effect.uninterruptibleMask((restore) =>\n Effect.gen(function*() {\n const opened = yield* fs.open(temporary, { flag: \"wx\", mode: BLOB_FILE_MODE }).pipe(Effect.result)\n\n if (Result.isFailure(opened)) {\n return openFailure(opened.failure)\n }\n\n yield* Effect.addFinalizer(() => fs.remove(temporary, { force: true }).pipe(Effect.ignore))\n yield* restore(opened.success.writeAll(bytes)).pipe(\n Effect.mapError((cause) => blobStoreIoError(\"write temporary blob\", cause))\n )\n yield* restore(opened.success.sync).pipe(\n Effect.mapError((cause) => blobStoreIoError(\"sync temporary blob\", cause))\n )\n\n const linked = yield* (mode === \"replace\"\n ? fs.rename(temporary, destination)\n : fs.link(temporary, destination)).pipe(Effect.result)\n if (Result.isSuccess(linked) && commit !== undefined) yield* commit(destination)\n return linkResult(linked)\n })\n )\n )\n\n if (outcome._tag === \"LinkResult\") {\n return outcome.linked\n }\n\n if (outcome.error.reason._tag !== \"AlreadyExists\") {\n return yield* blobStoreIoError(\"open temporary blob\", outcome.error)\n }\n }\n\n return yield* blobStoreIoError(\"open temporary blob\", \"temporary filename collision limit reached\")\n })\n}\n","import type { FileSystem, Path } from \"effect\"\nimport { Effect, Result } from \"effect\"\n\nimport { BlobContainmentError, blobStoreIoError } from \"./BlobStoreError.js\"\n\n/** Descriptor-backed directory alias used for containment-safe publication. */\nexport interface PinnedDirectory {\n readonly path: string\n readonly sync: Effect.Effect<void, ReturnType<typeof blobStoreIoError>>\n readonly assertIdentity: Effect.Effect<void, BlobContainmentError>\n}\n\nconst descriptorAliases = (path: Path.Path, descriptor: FileSystem.File.Descriptor) => [\n path.join(\"/proc/self/fd\", String(descriptor)),\n path.join(\"/dev/fd\", String(descriptor))\n]\n\n/** Resolve a verified alias for the exact object already held by a descriptor. */\nexport const resolveDescriptorAlias = Effect.fn(\"BlobStore.resolveDescriptorAlias\")(function*(\n fs: FileSystem.FileSystem,\n path: Path.Path,\n descriptor: FileSystem.File.Descriptor,\n expectedPath: string,\n operation: string\n) {\n for (const alias of descriptorAliases(path, descriptor)) {\n const resolved = yield* fs.realPath(alias).pipe(Effect.result)\n if (Result.isSuccess(resolved) && resolved.success === expectedPath) return alias\n }\n\n return yield* new BlobContainmentError({\n operation,\n message: \"opened descriptor does not match its expected contained path\"\n })\n})\n\n/**\n * Pin an already validated directory and fail closed when the platform cannot\n * address children through that exact descriptor.\n */\nexport const pinDirectory = Effect.fn(\"BlobStore.pinDirectory\")(function*(\n fs: FileSystem.FileSystem,\n path: Path.Path,\n directory: string\n) {\n const handle = yield* fs.open(directory, { flag: \"r\" }).pipe(\n Effect.mapError((cause) => blobStoreIoError(\"pin object directory\", cause))\n )\n\n const alias = yield* resolveDescriptorAlias(fs, path, handle.fd, directory, \"publish blob\")\n const assertIdentity = fs.realPath(alias).pipe(\n Effect.result,\n Effect.flatMap((current) =>\n Result.isSuccess(current) && current.success === directory\n ? Effect.void\n : new BlobContainmentError({\n operation: \"publish blob\",\n message: \"pinned object directory identity changed\"\n })\n )\n )\n return {\n path: alias,\n sync: handle.sync.pipe(\n Effect.mapError((cause) => blobStoreIoError(\"sync pinned object directory\", cause))\n ),\n assertIdentity\n } satisfies PinnedDirectory\n})\n","import type { Path } from \"effect\"\nimport { Effect, FileSystem, Option, Result, Stream } from \"effect\"\n\nimport type { BlobDigest } from \"./BlobDigest.js\"\nimport { BlobContainmentError, BlobNotFoundError, blobStoreIoError, BlobUnexpectedEofError } from \"./BlobStoreError.js\"\nimport type { BlobStoreError } from \"./BlobStoreError.js\"\nimport { resolveDescriptorAlias } from \"./PinnedDirectory.js\"\n\nconst READ_CHUNK_BYTES = 64 * 1024\n\n/** Expected contained path and digest for an opened blob. */\nexport interface BlobFileReference {\n readonly digest: BlobDigest\n readonly filePath: string\n}\n\n/** File identity captured from a verified descriptor. */\nexport interface PinnedBlobLocation extends BlobFileReference {\n readonly info: FileSystem.File.Info\n}\n\nconst streamStep = (\n bytes: Uint8Array,\n nextOffset: number\n): readonly [Uint8Array, number] => [bytes, nextOffset]\n\nconst concatenate = (chunks: ReadonlyArray<Uint8Array>): Uint8Array => {\n const size = chunks.reduce((total, chunk) => total + chunk.byteLength, 0)\n const bytes = new Uint8Array(size)\n let offset = 0\n\n for (const chunk of chunks) {\n bytes.set(chunk, offset)\n offset += chunk.byteLength\n }\n\n return bytes\n}\n\n/** Builds descriptor-first readers around captured filesystem and path services. */\nexport const makeOpenedBlobReader = (\n fs: FileSystem.FileSystem,\n path: Path.Path\n) => {\n const openExpected = Effect.fn(\"BlobStore.openExpected\")(function*(\n operation: string,\n reference: BlobFileReference,\n expectedInfo?: FileSystem.File.Info\n ) {\n const opened = yield* fs.open(reference.filePath, { flag: \"r\" }).pipe(Effect.result)\n\n if (Result.isFailure(opened)) {\n if (opened.failure.reason._tag === \"NotFound\") {\n return yield* new BlobNotFoundError({ digest: reference.digest })\n }\n return yield* blobStoreIoError(operation, opened.failure)\n }\n\n const file = opened.success\n yield* resolveDescriptorAlias(fs, path, file.fd, reference.filePath, operation)\n const openedInfo = yield* file.stat.pipe(\n Effect.mapError((cause) => blobStoreIoError(operation, cause))\n )\n\n if (openedInfo.type !== \"File\" || (openedInfo.mode & 0o077) !== 0) {\n return yield* new BlobContainmentError({\n operation,\n message: \"opened blob is not a supported regular file\"\n })\n }\n\n if (expectedInfo !== undefined) {\n const sameInode = Option.isSome(expectedInfo.ino) &&\n Option.isSome(openedInfo.ino) &&\n expectedInfo.ino.value === openedInfo.ino.value\n\n if (\n openedInfo.dev !== expectedInfo.dev ||\n !sameInode ||\n openedInfo.size !== expectedInfo.size\n ) {\n return yield* new BlobContainmentError({\n operation,\n message: \"opened blob no longer matches its contained path\"\n })\n }\n }\n\n return { file, info: openedInfo }\n })\n\n const inspect = Effect.fn(\"BlobStore.inspectOpened\")(function*(\n operation: string,\n reference: BlobFileReference\n ) {\n return yield* Effect.scoped(\n openExpected(operation, reference).pipe(Effect.map((opened) => opened.info))\n )\n })\n\n const streamFromFile = (\n operation: string,\n file: FileSystem.File,\n bytesToRead: number\n ): Stream.Stream<Uint8Array, BlobStoreError> =>\n Stream.unfold(0, (totalBytesRead) => {\n if (totalBytesRead >= bytesToRead) return Effect.succeed(undefined)\n\n const remaining = bytesToRead - totalBytesRead\n return file.readAlloc(Math.min(READ_CHUNK_BYTES, remaining)).pipe(\n Effect.mapError((cause) => blobStoreIoError(operation, cause)),\n Effect.flatMap(\n Option.match({\n onNone: () =>\n new BlobUnexpectedEofError({\n operation,\n expectedBytes: bytesToRead,\n actualBytes: totalBytesRead\n }),\n onSome: (bytes) =>\n bytes.byteLength === 0\n ? new BlobUnexpectedEofError({\n operation,\n expectedBytes: bytesToRead,\n actualBytes: totalBytesRead\n })\n : Effect.succeed(streamStep(bytes, totalBytesRead + bytes.byteLength))\n })\n )\n )\n })\n\n const stream = (\n operation: string,\n location: PinnedBlobLocation,\n offset: number,\n length: number\n ): Stream.Stream<Uint8Array, BlobStoreError> =>\n Stream.unwrap(\n Effect.gen(function*() {\n const opened = yield* openExpected(operation, location, location.info)\n\n if (offset > 0) yield* opened.file.seek(FileSystem.Size(offset), \"start\")\n\n return streamFromFile(operation, opened.file, length)\n })\n )\n\n const read = Effect.fn(\"BlobStore.readPinned\")(function*(\n operation: string,\n location: PinnedBlobLocation,\n offset: number,\n length: number\n ) {\n const chunks = yield* stream(operation, location, offset, length).pipe(Stream.runCollect)\n const bytes = concatenate(chunks)\n\n if (bytes.byteLength !== length) {\n return yield* new BlobUnexpectedEofError({\n operation,\n expectedBytes: length,\n actualBytes: bytes.byteLength\n })\n }\n return bytes\n })\n\n return { inspect, read, stream }\n}\n","import { Context, Crypto, Effect, FileSystem, Layer, Path, Result, Schema } from \"effect\"\n\nimport { WorkspaceId } from \"../../../domain/identifiers.js\"\nimport { BlobRoot } from \"../PersistenceConfig.js\"\nimport { BlobDigest } from \"./BlobDigest.js\"\nimport { blobPath } from \"./BlobPath.js\"\nimport { BLOB_FILE_MODE, makeBlobPublisher } from \"./BlobPublisher.js\"\nimport { BlobClassification, BlobRef } from \"./BlobRef.js\"\nimport {\n BlobContainmentError,\n BlobIntegrityError,\n type BlobStoreError,\n BlobStoreInputError,\n blobStoreIoError,\n BlobTooLargeError,\n BlobUnexpectedEofError\n} from \"./BlobStoreError.js\"\nimport type { BlobRange, BlobRangeRead, BlobReadStream, BlobVerification } from \"./BlobStoreTypes.js\"\nimport { makeOpenedBlobReader } from \"./OpenedBlob.js\"\nimport { pinDirectory } from \"./PinnedDirectory.js\"\n\nconst DIRECTORY_MODE = 0o700\nconst DEFAULT_MAXIMUM_READ_ALL_BYTES = 8 * 1024 * 1024\nconst DEFAULT_MAXIMUM_RANGE_BYTES = 2 * 1024 * 1024\nconst DEFAULT_MAXIMUM_BLOB_BYTES = 256 * 1024 * 1024\nconst INTEGRITY_NOT_VERIFIED: \"not-verified\" = \"not-verified\"\n\nconst NonNegativeSafeInteger = Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0))\nconst PositiveSafeInteger = Schema.Number.check(Schema.isInt(), Schema.isGreaterThan(0))\n\n/** Options used when constructing the owner-only object directory. */\nexport interface BlobStoreOptions {\n readonly blobRoot: BlobRoot\n readonly maximumBlobBytes?: number | undefined\n readonly maximumReadAllBytes?: number | undefined\n readonly maximumRangeBytes?: number | undefined\n}\n\n/** Result of a content-addressed write. */\nexport interface BlobPutResult {\n readonly ref: BlobRef\n readonly stored: boolean\n}\n\ninterface BlobStoreService {\n /** Reconfirm a just-published canonical object while its SQL owner holds the cleanup lock. */\n readonly assertPublished: (\n workspaceId: WorkspaceId,\n digest: BlobDigest,\n expectedBytes: number\n ) => Effect.Effect<void, BlobStoreError>\n readonly put: (\n workspaceId: WorkspaceId,\n bytes: Uint8Array,\n classification: BlobClassification\n ) => Effect.Effect<BlobPutResult, BlobStoreError>\n readonly readAll: (\n workspaceId: WorkspaceId,\n digest: BlobDigest,\n maximumBytes?: number | undefined\n ) => Effect.Effect<Uint8Array, BlobStoreError>\n readonly readRange: (\n workspaceId: WorkspaceId,\n digest: BlobDigest,\n range: BlobRange\n ) => Effect.Effect<BlobRangeRead, BlobStoreError>\n readonly readStream: (\n workspaceId: WorkspaceId,\n digest: BlobDigest,\n range?: BlobRange | undefined\n ) => Effect.Effect<BlobReadStream, BlobStoreError>\n /** Replace corrupt bytes only after ContentStore authorizes persisted reproducible-cache metadata. */\n readonly repairReproducible: (\n workspaceId: WorkspaceId,\n bytes: Uint8Array\n ) => Effect.Effect<BlobPutResult, BlobStoreError>\n /** Remove bytes only after ContentStore has authorized the persisted storage class. */\n readonly removeAuthorizedBytes: (\n workspaceId: WorkspaceId,\n digest: BlobDigest\n ) => Effect.Effect<void, BlobStoreError>\n readonly verify: (\n workspaceId: WorkspaceId,\n digest: BlobDigest\n ) => Effect.Effect<BlobVerification, BlobStoreError>\n}\n\n/** Workspace-isolated, content-addressed byte storage. */\nexport class BlobStore extends Context.Service<BlobStore, BlobStoreService>()(\n \"@knpkv/control-center/server/persistence/BlobStore\"\n) {\n static readonly layer = (\n options: BlobStoreOptions\n ): Layer.Layer<BlobStore, BlobStoreError, Crypto.Crypto | FileSystem.FileSystem | Path.Path> =>\n Layer.effect(BlobStore, makeBlobStore(options))\n}\n\nconst decodeInput = <S extends Schema.ConstraintDecoder<unknown>>(\n operation: string,\n schema: S,\n input: unknown\n): Effect.Effect<S[\"Type\"], BlobStoreInputError> => {\n const result = Schema.decodeUnknownResult(schema)(input)\n\n return Result.isSuccess(result)\n ? Effect.succeed(result.success)\n : Effect.fail(new BlobStoreInputError({ operation, message: \"input failed schema validation\" }))\n}\n\n/** Constructs a blob store while capturing the platform services in its layer. */\nexport const makeBlobStore: (\n options: BlobStoreOptions\n) => Effect.Effect<\n BlobStore[\"Service\"],\n BlobStoreError,\n Crypto.Crypto | FileSystem.FileSystem | Path.Path\n> = Effect.fn(\"BlobStore.make\")(function*(options: BlobStoreOptions) {\n const fs = yield* FileSystem.FileSystem\n const path = yield* Path.Path\n const cryptoService = yield* Crypto.Crypto\n const maximumBlobBytes = yield* decodeInput(\n \"configure maximumBlobBytes\",\n PositiveSafeInteger,\n options.maximumBlobBytes ?? DEFAULT_MAXIMUM_BLOB_BYTES\n )\n const maximumReadAllBytes = yield* decodeInput(\n \"configure maximumReadAllBytes\",\n PositiveSafeInteger,\n options.maximumReadAllBytes ?? DEFAULT_MAXIMUM_READ_ALL_BYTES\n )\n const maximumRangeBytes = yield* decodeInput(\n \"configure maximumRangeBytes\",\n PositiveSafeInteger,\n options.maximumRangeBytes ?? DEFAULT_MAXIMUM_RANGE_BYTES\n )\n const decodedBlobRoot = yield* decodeInput(\"configure blobRoot\", BlobRoot, options.blobRoot)\n const configuredRoot = path.resolve(decodedBlobRoot)\n\n if (maximumReadAllBytes > maximumBlobBytes || maximumRangeBytes > maximumBlobBytes) {\n return yield* new BlobStoreInputError({\n operation: \"configure blob limits\",\n message: \"read bounds cannot exceed the maximum blob size\"\n })\n }\n\n const syncDirectory = Effect.fn(\"BlobStore.syncDirectory\")(function*(directory: string) {\n yield* Effect.scoped(\n Effect.gen(function*() {\n const handle = yield* fs.open(directory, { flag: \"r\" }).pipe(\n Effect.mapError((cause) => blobStoreIoError(\"open directory for sync\", cause))\n )\n yield* handle.sync.pipe(\n Effect.mapError((cause) => blobStoreIoError(\"sync directory\", cause))\n )\n })\n )\n })\n\n const missingDirectories: Array<string> = []\n let existingAncestor = configuredRoot\n\n while (\n !(yield* fs.exists(existingAncestor).pipe(\n Effect.mapError((cause) => blobStoreIoError(\"check blob root ancestor\", cause))\n ))\n ) {\n missingDirectories.unshift(existingAncestor)\n const parent = path.dirname(existingAncestor)\n\n if (parent === existingAncestor) {\n break\n }\n existingAncestor = parent\n }\n\n for (const directory of missingDirectories) {\n yield* fs.makeDirectory(directory, { mode: DIRECTORY_MODE }).pipe(\n Effect.mapError((cause) => blobStoreIoError(\"create blob root directory\", cause))\n )\n yield* fs.chmod(directory, DIRECTORY_MODE).pipe(\n Effect.mapError((cause) => blobStoreIoError(\"secure blob root directory\", cause))\n )\n yield* syncDirectory(directory)\n yield* syncDirectory(path.dirname(directory))\n }\n\n const canonicalRoot = yield* fs.realPath(configuredRoot).pipe(\n Effect.mapError((cause) => blobStoreIoError(\"resolve blob root\", cause))\n )\n\n if (canonicalRoot !== configuredRoot) {\n return yield* new BlobContainmentError({\n operation: \"initialize\",\n message: \"blobRoot must be a canonical path\"\n })\n }\n\n yield* fs.chmod(configuredRoot, DIRECTORY_MODE).pipe(\n Effect.mapError((cause) => blobStoreIoError(\"secure blob root\", cause))\n )\n yield* syncDirectory(configuredRoot)\n\n const rootInfo = yield* fs.stat(canonicalRoot).pipe(\n Effect.mapError((cause) => blobStoreIoError(\"inspect blob root\", cause))\n )\n\n if (rootInfo.type !== \"Directory\") {\n return yield* new BlobContainmentError({\n operation: \"initialize\",\n message: \"blobRoot must resolve to a directory\"\n })\n }\n\n const isContained = (candidate: string): boolean =>\n candidate === canonicalRoot || candidate.startsWith(`${canonicalRoot}${path.sep}`)\n\n const digestBytes = Effect.fn(\"BlobStore.digestBytes\")(function*(bytes: Uint8Array) {\n const digest = yield* cryptoService.digest(\"SHA-256\", bytes).pipe(\n Effect.mapError((cause) => blobStoreIoError(\"digest\", cause))\n )\n const encoded = Array.from(digest, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")\n\n return yield* decodeInput(\"digest\", BlobDigest, encoded)\n })\n\n const secureDirectory = Effect.fn(\"BlobStore.secureDirectory\")(function*(directory: string) {\n if (!isContained(directory)) {\n return yield* new BlobContainmentError({\n operation: \"secure directory\",\n message: \"derived directory escaped blobRoot\"\n })\n }\n\n const exists = yield* fs.exists(directory).pipe(\n Effect.mapError((cause) => blobStoreIoError(\"check object directory\", cause))\n )\n\n if (!exists) {\n const created = yield* fs.makeDirectory(directory, { mode: DIRECTORY_MODE }).pipe(Effect.result)\n if (Result.isFailure(created) && created.failure.reason._tag !== \"AlreadyExists\") {\n return yield* blobStoreIoError(\"create object directory\", created.failure)\n }\n }\n\n const canonicalDirectory = yield* fs.realPath(directory).pipe(\n Effect.mapError((cause) => blobStoreIoError(\"resolve object directory\", cause))\n )\n\n if (canonicalDirectory !== directory || !isContained(canonicalDirectory)) {\n return yield* new BlobContainmentError({\n operation: \"secure directory\",\n message: \"object directory crossed a symbolic link\"\n })\n }\n\n const info = yield* fs.stat(canonicalDirectory).pipe(\n Effect.mapError((cause) => blobStoreIoError(\"inspect object directory\", cause))\n )\n\n if (info.type !== \"Directory\") {\n return yield* new BlobContainmentError({\n operation: \"secure directory\",\n message: \"object path is not a directory\"\n })\n }\n\n yield* fs.chmod(canonicalDirectory, DIRECTORY_MODE).pipe(\n Effect.mapError((cause) => blobStoreIoError(\"secure object directory\", cause))\n )\n\n if (!exists) {\n yield* syncDirectory(canonicalDirectory)\n yield* syncDirectory(path.dirname(canonicalDirectory))\n }\n })\n\n const decodeReference = Effect.fn(\"BlobStore.decodeReference\")(function*(\n operation: string,\n workspaceId: WorkspaceId,\n digest: BlobDigest\n ) {\n const decodedWorkspaceId = yield* decodeInput(operation, WorkspaceId, workspaceId)\n const decodedDigest = yield* decodeInput(operation, BlobDigest, digest)\n const derived = blobPath(path, canonicalRoot, decodedWorkspaceId, decodedDigest)\n\n if (!isContained(derived.file)) {\n return yield* new BlobContainmentError({\n operation,\n message: \"derived object path escaped blobRoot\"\n })\n }\n\n return { workspaceId: decodedWorkspaceId, digest: decodedDigest, derived }\n })\n\n const openedBlobReader = makeOpenedBlobReader(fs, path)\n\n const locate = Effect.fn(\"BlobStore.locate\")(function*(\n operation: string,\n workspaceId: WorkspaceId,\n digest: BlobDigest\n ) {\n const reference = yield* decodeReference(operation, workspaceId, digest)\n const info = yield* openedBlobReader.inspect(operation, {\n digest: reference.digest,\n filePath: reference.derived.file\n })\n\n if (\n info.size > BigInt(maximumBlobBytes) ||\n info.size > BigInt(Number.MAX_SAFE_INTEGER) ||\n (info.mode & 0o077) !== 0\n ) {\n if (info.size > BigInt(maximumBlobBytes)) {\n return yield* new BlobTooLargeError({\n digest: reference.digest,\n actualBytes: info.size > BigInt(Number.MAX_SAFE_INTEGER) ? Number.MAX_SAFE_INTEGER : Number(info.size),\n maximumBytes: maximumBlobBytes\n })\n }\n\n return yield* new BlobContainmentError({\n operation,\n message: \"blob path is not a supported regular file\"\n })\n }\n\n return { ...reference, info, sizeBytes: Number(info.size) }\n })\n\n const pinnedLocation = (located: Effect.Success<ReturnType<typeof locate>>) => ({\n digest: located.digest,\n filePath: located.derived.file,\n info: located.info\n })\n\n const verifyLocated = Effect.fn(\"BlobStore.verifyLocated\")(function*(\n located: Effect.Success<ReturnType<typeof locate>>\n ) {\n const bytes = yield* openedBlobReader.read(\"verify blob\", pinnedLocation(located), 0, located.sizeBytes)\n const actualDigest = yield* digestBytes(bytes)\n\n if (actualDigest !== located.digest) {\n return yield* new BlobIntegrityError({ expectedDigest: located.digest, actualDigest })\n }\n\n return bytes\n })\n\n const readLocatedBounded = Effect.fn(\"BlobStore.readLocatedBounded\")(function*(\n located: Effect.Success<ReturnType<typeof locate>>,\n maximumBytes: number\n ) {\n const bytes = yield* openedBlobReader.read(\n \"read bounded blob\",\n pinnedLocation(located),\n 0,\n located.sizeBytes\n )\n\n if (located.sizeBytes > maximumBytes || located.sizeBytes !== bytes.byteLength) {\n return yield* new BlobTooLargeError({\n digest: located.digest,\n actualBytes: located.sizeBytes,\n maximumBytes\n })\n }\n\n const actualDigest = yield* digestBytes(bytes)\n\n if (actualDigest !== located.digest) {\n return yield* new BlobIntegrityError({ expectedDigest: located.digest, actualDigest })\n }\n\n return bytes\n })\n\n const verify = Effect.fn(\"BlobStore.verify\")(function*(workspaceId: WorkspaceId, digest: BlobDigest) {\n const located = yield* locate(\"verify blob\", workspaceId, digest)\n const bytes = yield* verifyLocated(located)\n\n return {\n digest: located.digest,\n sizeBytes: bytes.byteLength\n }\n })\n\n const assertPublished = Effect.fn(\"BlobStore.assertPublished\")(function*(\n workspaceId: WorkspaceId,\n digest: BlobDigest,\n expectedBytes: number\n ) {\n const decodedExpectedBytes = yield* decodeInput(\n \"assert published blob\",\n NonNegativeSafeInteger,\n expectedBytes\n )\n const located = yield* locate(\"assert published blob\", workspaceId, digest)\n if (located.sizeBytes !== decodedExpectedBytes) {\n return yield* new BlobUnexpectedEofError({\n operation: \"assert published blob\",\n expectedBytes: decodedExpectedBytes,\n actualBytes: located.sizeBytes\n })\n }\n })\n\n const publish = makeBlobPublisher(fs, path, cryptoService)\n\n const put = Effect.fn(\"BlobStore.put\")(function*(\n workspaceId: WorkspaceId,\n bytes: Uint8Array,\n classification: BlobClassification\n ) {\n const decodedWorkspaceId = yield* decodeInput(\"put blob\", WorkspaceId, workspaceId)\n const decodedClassification = yield* decodeInput(\n \"put blob\",\n BlobClassification,\n classification\n )\n if (bytes.byteLength > maximumBlobBytes) {\n return yield* new BlobTooLargeError({\n digest: null,\n actualBytes: bytes.byteLength,\n maximumBytes: maximumBlobBytes\n })\n }\n\n const digest = yield* digestBytes(bytes)\n\n const derived = blobPath(path, canonicalRoot, decodedWorkspaceId, digest)\n\n yield* secureDirectory(path.join(canonicalRoot, \"objects\"))\n yield* secureDirectory(derived.workspaceDirectory)\n yield* secureDirectory(path.join(derived.workspaceDirectory, \"sha256\"))\n yield* secureDirectory(path.dirname(derived.objectDirectory))\n yield* secureDirectory(derived.objectDirectory)\n\n const existing = yield* fs.exists(derived.file).pipe(\n Effect.mapError((cause) => blobStoreIoError(\"check blob cache\", cause))\n )\n\n if (existing) {\n yield* Effect.scoped(\n Effect.gen(function*() {\n const pinned = yield* pinDirectory(fs, path, derived.objectDirectory)\n yield* pinned.sync\n yield* pinned.assertIdentity\n })\n )\n const verification = yield* verify(decodedWorkspaceId, digest).pipe(Effect.result)\n if (Result.isSuccess(verification)) {\n return {\n ref: new BlobRef({\n workspaceId: decodedWorkspaceId,\n digest,\n sizeBytes: bytes.byteLength,\n classification: decodedClassification\n }),\n stored: false\n }\n }\n return yield* verification.failure\n }\n\n const linked = yield* Effect.scoped(\n Effect.gen(function*() {\n const pinned = yield* pinDirectory(fs, path, derived.objectDirectory)\n const pinnedDestination = path.join(pinned.path, digest)\n const result = yield* publish(pinned, digest, bytes)\n\n if (Result.isFailure(result)) {\n const wonByAnotherWriter = yield* fs.exists(pinnedDestination).pipe(\n Effect.mapError((cause) => blobStoreIoError(\"check concurrent blob write\", cause))\n )\n\n if (!wonByAnotherWriter) {\n return yield* blobStoreIoError(\"publish blob\", result.failure)\n }\n } else {\n yield* fs.chmod(pinnedDestination, BLOB_FILE_MODE).pipe(\n Effect.mapError((cause) => blobStoreIoError(\"secure blob\", cause))\n )\n }\n\n // Every writer, including a hard-link loser, establishes publication\n // durability before SQL metadata is allowed to become visible.\n yield* pinned.sync\n const identity = yield* pinned.assertIdentity.pipe(Effect.result)\n\n if (Result.isFailure(identity)) {\n if (Result.isSuccess(result)) {\n yield* fs.remove(pinnedDestination, { force: true }).pipe(\n Effect.mapError((cause) => blobStoreIoError(\"remove displaced publication\", cause))\n )\n yield* pinned.sync\n }\n return yield* identity.failure\n }\n return result\n })\n )\n\n yield* verify(decodedWorkspaceId, digest)\n\n return {\n ref: new BlobRef({\n workspaceId: decodedWorkspaceId,\n digest,\n sizeBytes: bytes.byteLength,\n classification: decodedClassification\n }),\n stored: Result.isSuccess(linked)\n }\n })\n\n const repairReproducible = Effect.fn(\"BlobStore.repairReproducible\")(function*(\n workspaceId: WorkspaceId,\n bytes: Uint8Array\n ) {\n const decodedWorkspaceId = yield* decodeInput(\"repair blob\", WorkspaceId, workspaceId)\n if (bytes.byteLength > maximumBlobBytes) {\n return yield* new BlobTooLargeError({\n digest: null,\n actualBytes: bytes.byteLength,\n maximumBytes: maximumBlobBytes\n })\n }\n const digest = yield* digestBytes(bytes)\n const derived = blobPath(path, canonicalRoot, decodedWorkspaceId, digest)\n yield* secureDirectory(derived.objectDirectory)\n yield* Effect.scoped(\n Effect.gen(function*() {\n const pinned = yield* pinDirectory(fs, path, derived.objectDirectory)\n const replaced = yield* publish(\n pinned,\n digest,\n bytes,\n \"replace\",\n (pinnedDestination) =>\n fs.chmod(pinnedDestination, BLOB_FILE_MODE).pipe(\n Effect.mapError((cause) => blobStoreIoError(\"secure repaired blob\", cause)),\n Effect.andThen(pinned.sync),\n Effect.andThen(pinned.assertIdentity)\n )\n )\n if (Result.isFailure(replaced)) return yield* blobStoreIoError(\"repair blob\", replaced.failure)\n })\n )\n yield* verify(decodedWorkspaceId, digest)\n return {\n ref: new BlobRef({\n workspaceId: decodedWorkspaceId,\n digest,\n sizeBytes: bytes.byteLength,\n classification: \"reproducible-cache\"\n }),\n stored: true\n }\n })\n\n const removeAuthorizedBytes = Effect.fn(\"BlobStore.removeAuthorizedBytes\")(function*(\n workspaceId: WorkspaceId,\n digest: BlobDigest\n ) {\n const reference = yield* decodeReference(\"remove reproducible blob\", workspaceId, digest)\n yield* Effect.scoped(\n Effect.gen(function*() {\n const pinned = yield* pinDirectory(fs, path, reference.derived.objectDirectory)\n yield* pinned.assertIdentity\n yield* fs.remove(path.join(pinned.path, reference.digest), { force: true }).pipe(\n Effect.mapError((cause) => blobStoreIoError(\"remove reproducible blob\", cause))\n )\n yield* pinned.sync\n yield* pinned.assertIdentity\n })\n )\n })\n\n const readAll = Effect.fn(\"BlobStore.readAll\")(function*(\n workspaceId: WorkspaceId,\n digest: BlobDigest,\n requestedMaximumBytes?: number | undefined\n ) {\n const limit = yield* decodeInput(\n \"read all blob\",\n PositiveSafeInteger,\n requestedMaximumBytes ?? maximumReadAllBytes\n )\n\n if (limit > maximumReadAllBytes) {\n return yield* new BlobStoreInputError({\n operation: \"read all blob\",\n message: \"requested bound exceeds the configured readAll maximum\"\n })\n }\n\n const located = yield* locate(\"read all blob\", workspaceId, digest)\n\n if (located.sizeBytes > limit) {\n return yield* new BlobTooLargeError({\n digest: located.digest,\n actualBytes: located.sizeBytes,\n maximumBytes: limit\n })\n }\n\n return yield* readLocatedBounded(located, limit)\n })\n\n const decodeRange = Effect.fn(\"BlobStore.decodeRange\")(function*(range: BlobRange) {\n const offset = yield* decodeInput(\"read blob range\", NonNegativeSafeInteger, range.offset)\n const length = yield* decodeInput(\"read blob range\", PositiveSafeInteger, range.length)\n\n if (length > maximumRangeBytes) {\n return yield* new BlobStoreInputError({\n operation: \"read blob range\",\n message: `range length exceeds ${maximumRangeBytes} bytes`\n })\n }\n\n return { offset, length }\n })\n\n const readRange = Effect.fn(\"BlobStore.readRange\")(function*(\n workspaceId: WorkspaceId,\n digest: BlobDigest,\n requestedRange: BlobRange\n ) {\n const range = yield* decodeRange(requestedRange)\n const located = yield* locate(\"read blob range\", workspaceId, digest)\n\n if (range.offset > located.sizeBytes || range.length > located.sizeBytes - range.offset) {\n return yield* new BlobStoreInputError({\n operation: \"read blob range\",\n message: \"range exceeds blob length\"\n })\n }\n\n const bytes = yield* openedBlobReader.read(\n \"read blob range\",\n pinnedLocation(located),\n range.offset,\n range.length\n )\n\n return {\n digest: located.digest,\n sizeBytes: located.sizeBytes,\n integrity: INTEGRITY_NOT_VERIFIED,\n bytes\n }\n })\n\n const readStream = Effect.fn(\"BlobStore.readStream\")(function*(\n workspaceId: WorkspaceId,\n digest: BlobDigest,\n requestedRange?: BlobRange | undefined\n ) {\n const located = yield* locate(\"stream blob\", workspaceId, digest)\n const range = requestedRange === undefined ? undefined : yield* decodeRange(requestedRange)\n\n if (\n range !== undefined &&\n (range.offset > located.sizeBytes || range.length > located.sizeBytes - range.offset)\n ) {\n return yield* new BlobStoreInputError({\n operation: \"stream blob\",\n message: \"range exceeds blob length\"\n })\n }\n\n const offset = range?.offset ?? 0\n const length = range?.length ?? located.sizeBytes\n\n return {\n digest: located.digest,\n sizeBytes: located.sizeBytes,\n integrity: INTEGRITY_NOT_VERIFIED,\n bytes: openedBlobReader.stream(\"stream blob\", pinnedLocation(located), offset, length)\n }\n })\n\n return BlobStore.of({\n assertPublished,\n put,\n readAll,\n readRange,\n readStream,\n removeAuthorizedBytes,\n repairReproducible,\n verify\n })\n})\n","import * as Context from \"effect/Context\"\nimport * as Crypto from \"effect/Crypto\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport type { Success } from \"effect/Effect\"\nimport * as Encoding from \"effect/Encoding\"\nimport * as Layer from \"effect/Layer\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\"\n\nimport { WorkspaceId } from \"../../../domain/identifiers.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport { Database } from \"../Database.js\"\nimport { PersistedRecordError, PersistenceOperationError, RecordNotFoundError } from \"../errors.js\"\nimport { mapAlreadyExists, mapPersistenceOperation } from \"./internal.js\"\nimport { ContentBlobDigest, ContentBlobMetadata, ContentBlobStorageClass } from \"./models.js\"\nimport { QuarantineRepository } from \"./quarantineRepository.js\"\n\nconst ContentBlobKey = Schema.Struct({\n workspaceId: WorkspaceId,\n digest: ContentBlobDigest\n})\n\nconst ContentBlobIdentity = Schema.Struct({ digest: ContentBlobDigest })\n\nconst CreateContentBlobMetadataRequest = Schema.Struct({\n ...ContentBlobKey.fields,\n storageClass: ContentBlobStorageClass,\n byteLength: ContentBlobMetadata.fields.byteLength,\n mimeType: ContentBlobMetadata.fields.mimeType,\n createdAt: UtcTimestamp,\n lastVerifiedAt: ContentBlobMetadata.fields.lastVerifiedAt\n})\n\nconst makeContentBlobMetadataRepository = Effect.gen(function*() {\n const cryptoService = yield* Crypto.Crypto\n const database = yield* Database\n const quarantine = yield* QuarantineRepository\n const sql = database.sql\n\n const digestPersistedRow = Effect.fn(\"ContentBlobMetadataRepository.digestPersistedRow\")(function*(\n row: unknown\n ) {\n const serialized = yield* Effect.try({\n try: () => JSON.stringify(row),\n catch: () => new PersistenceOperationError({ operation: \"content-blob.quarantine-encode\" })\n })\n const bytes = yield* Effect.fromResult(\n Encoding.decodeBase64(Encoding.encodeBase64(serialized))\n ).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"content-blob.quarantine-encode\" }))\n )\n const digest = yield* cryptoService.digest(\"SHA-256\", bytes).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"content-blob.quarantine-digest\" }))\n )\n return ContentBlobDigest.make(Encoding.encodeHex(digest))\n })\n\n const quarantineMalformed = Effect.fn(\"ContentBlobMetadataRepository.quarantineMalformed\")(function*(\n workspaceId: WorkspaceId,\n row: unknown,\n fallbackKey: ContentBlobDigest | WorkspaceId\n ) {\n const identity = Schema.decodeUnknownResult(ContentBlobIdentity)(row)\n const payloadDigest = yield* digestPersistedRow(row)\n const observedAt = yield* DateTime.now\n yield* quarantine.recordMalformed(workspaceId, {\n recordKind: \"content-metadata\",\n recordKey: Result.isSuccess(identity) ? identity.success.digest : fallbackKey,\n schemaVersion: 1,\n payloadDigest,\n diagnosticCode: \"content-metadata-schema-invalid\",\n diagnosticSummary: \"Stored content metadata failed schema validation.\",\n observedAt\n })\n })\n\n const selectColumns = sql`SELECT\n workspace_id AS workspaceId,\n digest,\n storage_class AS storageClass,\n byte_length AS byteLength,\n mime_type AS mimeType,\n created_at AS createdAt,\n last_verified_at AS lastVerifiedAt\n FROM content_blobs`\n\n const findRows = ({ digest, workspaceId }: typeof ContentBlobKey.Type) =>\n sql<Record<string, unknown>>`${selectColumns}\n WHERE workspace_id = ${workspaceId}\n AND digest = ${digest}`\n\n const listRows = (workspaceId: WorkspaceId) =>\n sql<Record<string, unknown>>`${selectColumns}\n WHERE workspace_id = ${workspaceId}\n ORDER BY created_at DESC, digest`\n\n const insert = SqlSchema.void({\n Request: CreateContentBlobMetadataRequest,\n execute: ({ byteLength, createdAt, digest, lastVerifiedAt, mimeType, storageClass, workspaceId }) =>\n sql`INSERT INTO content_blobs (\n workspace_id, digest, storage_class, byte_length, mime_type,\n created_at, last_verified_at\n ) VALUES (\n ${workspaceId}, ${digest}, ${storageClass}, ${byteLength}, ${mimeType},\n ${createdAt}, ${lastVerifiedAt}\n )`\n })\n\n const markVerified = SqlSchema.void({\n Request: Schema.Struct({ ...ContentBlobKey.fields, verifiedAt: UtcTimestamp }),\n execute: ({ digest, verifiedAt, workspaceId }) =>\n sql`UPDATE content_blobs\n SET last_verified_at = CASE\n WHEN last_verified_at IS NULL OR last_verified_at < ${verifiedAt}\n THEN ${verifiedAt}\n ELSE last_verified_at\n END\n WHERE workspace_id = ${workspaceId}\n AND digest = ${digest}`\n })\n\n const get = Effect.fn(\"ContentBlobMetadataRepository.get\")(function*(\n workspaceId: WorkspaceId,\n digest: ContentBlobDigest\n ) {\n const rows = yield* findRows({ workspaceId, digest }).pipe(\n mapPersistenceOperation(\"content-blob.get\")\n )\n if (rows.length === 0) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"content-blob\",\n recordKey: digest\n })\n }\n const decoded = Schema.decodeUnknownResult(ContentBlobMetadata)(rows[0])\n if (Result.isSuccess(decoded)) return decoded.success\n yield* quarantineMalformed(workspaceId, rows[0], digest)\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"content-metadata\",\n recordKey: digest,\n diagnosticCode: \"content-metadata-schema-invalid\"\n })\n })\n\n return {\n create: Effect.fn(\"ContentBlobMetadataRepository.create\")(function*(\n workspaceId: WorkspaceId,\n input: Omit<typeof CreateContentBlobMetadataRequest.Type, \"workspaceId\">\n ) {\n yield* insert({ workspaceId, ...input }).pipe(\n mapAlreadyExists({ workspaceId, recordKind: \"content-blob\", recordKey: input.digest }),\n mapPersistenceOperation(\"content-blob.create\")\n )\n return yield* get(workspaceId, input.digest)\n }),\n get,\n list: Effect.fn(\"ContentBlobMetadataRepository.list\")(function*(workspaceId: WorkspaceId) {\n const rows = yield* listRows(workspaceId).pipe(mapPersistenceOperation(\"content-blob.list\"))\n const metadata: Array<ContentBlobMetadata> = []\n for (const row of rows) {\n const decoded = Schema.decodeUnknownResult(ContentBlobMetadata)(row)\n if (Result.isSuccess(decoded)) {\n metadata.push(decoded.success)\n } else {\n yield* quarantineMalformed(workspaceId, row, workspaceId)\n }\n }\n return metadata\n }),\n markVerified: Effect.fn(\"ContentBlobMetadataRepository.markVerified\")(function*(\n workspaceId: WorkspaceId,\n digest: ContentBlobDigest,\n verifiedAt: UtcTimestamp\n ) {\n yield* markVerified({ workspaceId, digest, verifiedAt }).pipe(\n mapPersistenceOperation(\"content-blob.verify\")\n )\n return yield* get(workspaceId, digest)\n })\n }\n})\n\n/** Workspace-isolated metadata for content addressed bytes stored elsewhere. */\nexport interface ContentBlobMetadataRepositoryService extends\n Success<\n typeof makeContentBlobMetadataRepository\n >\n{}\n\n/** Effect service for content-blob metadata. */\nexport class ContentBlobMetadataRepository extends Context.Service<\n ContentBlobMetadataRepository,\n ContentBlobMetadataRepositoryService\n>()(\"@knpkv/control-center/ContentBlobMetadataRepository\") {\n /** Layer that binds SQL queries to the shared database at construction. */\n static readonly layer = Layer.effect(ContentBlobMetadataRepository, makeContentBlobMetadataRepository)\n}\n","import { Context, Effect, Layer, Option, Result, Stream } from \"effect\"\nimport type { Success } from \"effect/Effect\"\n\nimport type { WorkspaceId } from \"../../domain/identifiers.js\"\nimport type { UtcTimestamp } from \"../../domain/utcTimestamp.js\"\nimport { Database } from \"./Database.js\"\nimport { ContentMetadataMismatchError, ReproducibleContentUnavailableError } from \"./errors.js\"\nimport type { BlobDigest } from \"./object-store/BlobDigest.js\"\nimport type { BlobClassification } from \"./object-store/BlobRef.js\"\nimport { BlobStore } from \"./object-store/BlobStore.js\"\nimport type { BlobStoreError } from \"./object-store/BlobStoreError.js\"\nimport type { BlobRange } from \"./object-store/BlobStoreTypes.js\"\nimport { ContentBlobMetadataRepository } from \"./repositories/contentBlobMetadataRepository.js\"\nimport { mapPersistenceOperation } from \"./repositories/internal.js\"\nimport type { ContentBlobMetadata } from \"./repositories/models.js\"\n\n/** Metadata supplied when content bytes cross into durable persistence. */\nexport interface PutContentInput {\n readonly bytes: Uint8Array\n readonly classification: BlobClassification\n readonly mimeType: string | null\n readonly createdAt: UtcTimestamp\n}\n\n/** Reproducible content published while the cache coordinator owns the writer transaction. */\nexport interface ReproduciblePutContentInput extends Omit<PutContentInput, \"classification\"> {\n readonly classification: \"reproducible-cache\"\n}\n\n/** Result of publishing bytes before their SQL metadata becomes visible. */\nexport interface PutContentResult {\n readonly metadata: ContentBlobMetadata\n readonly stored: boolean\n}\n\nconst makeContentStore = Effect.gen(function*() {\n const blobs = yield* BlobStore\n const database = yield* Database\n const metadataRepository = yield* ContentBlobMetadataRepository\n\n const requireMetadata = (workspaceId: WorkspaceId, digest: BlobDigest) => metadataRepository.get(workspaceId, digest)\n\n const mapReadFailure = (\n metadata: ContentBlobMetadata,\n failure: BlobStoreError\n ): BlobStoreError | ReproducibleContentUnavailableError => {\n if (metadata.storageClass !== \"reproducible-cache\") return failure\n if (failure._tag === \"BlobNotFoundError\") {\n return new ReproducibleContentUnavailableError({\n digest: metadata.digest,\n workspaceId: metadata.workspaceId,\n reason: \"missing\",\n recovery: \"refetch\"\n })\n }\n if (failure._tag === \"BlobIntegrityError\" || failure._tag === \"BlobUnexpectedEofError\") {\n return new ReproducibleContentUnavailableError({\n digest: metadata.digest,\n workspaceId: metadata.workspaceId,\n reason: \"corrupt\",\n recovery: \"refetch\"\n })\n }\n return failure\n }\n\n const ensureMetadata = Effect.fn(\"ContentStore.ensureMetadata\")(function*(\n workspaceId: WorkspaceId,\n digest: BlobDigest,\n input: PutContentInput\n ) {\n const existing = yield* metadataRepository.get(workspaceId, digest).pipe(\n Effect.map(Option.some),\n Effect.catchTag(\"RecordNotFoundError\", () => Effect.succeed(Option.none()))\n )\n const metadata = Option.isSome(existing)\n ? existing.value\n : yield* metadataRepository.create(workspaceId, {\n digest,\n storageClass: input.classification,\n byteLength: input.bytes.byteLength,\n mimeType: input.mimeType,\n createdAt: input.createdAt,\n lastVerifiedAt: null\n }).pipe(\n Effect.catchTag(\"RecordAlreadyExistsError\", () => metadataRepository.get(workspaceId, digest))\n )\n\n if (\n metadata.byteLength !== input.bytes.byteLength ||\n metadata.storageClass !== input.classification ||\n metadata.mimeType !== input.mimeType\n ) {\n return yield* new ContentMetadataMismatchError({ workspaceId, digest })\n }\n return metadata\n })\n\n const publish = Effect.fn(\"ContentStore.publish\")(function*(\n workspaceId: WorkspaceId,\n input: PutContentInput\n ) {\n const attempted = yield* blobs.put(workspaceId, input.bytes, input.classification).pipe(Effect.result)\n if (Result.isSuccess(attempted)) return attempted.success\n if (attempted.failure._tag !== \"BlobIntegrityError\" || input.classification !== \"reproducible-cache\") {\n return yield* attempted.failure\n }\n const metadata = yield* metadataRepository.get(workspaceId, attempted.failure.expectedDigest)\n if (\n metadata.storageClass !== \"reproducible-cache\" ||\n metadata.byteLength !== input.bytes.byteLength ||\n metadata.mimeType !== input.mimeType\n ) {\n return yield* new ContentMetadataMismatchError({ workspaceId, digest: attempted.failure.expectedDigest })\n }\n return yield* blobs.repairReproducible(workspaceId, input.bytes)\n })\n\n const publishDurable = Effect.fn(\"ContentStore.publishDurable\")(function*(\n workspaceId: WorkspaceId,\n input: PutContentInput\n ) {\n const published = yield* publish(workspaceId, input)\n return yield* database.transaction(\n Effect.gen(function*() {\n yield* database.sql`UPDATE workspaces\n SET workspace_id = workspace_id\n WHERE workspace_id = ${workspaceId}`\n yield* blobs.assertPublished(\n workspaceId,\n published.ref.digest,\n input.bytes.byteLength\n )\n const metadata = yield* ensureMetadata(workspaceId, published.ref.digest, input)\n return { metadata, stored: published.stored }\n })\n ).pipe(mapPersistenceOperation(\"content.put\"))\n })\n\n const putReproducibleLocked = Effect.fn(\"ContentStore.putReproducibleLocked\")(function*(\n workspaceId: WorkspaceId,\n input: ReproduciblePutContentInput\n ) {\n const published = yield* publish(workspaceId, input)\n const metadata = yield* ensureMetadata(workspaceId, published.ref.digest, input)\n return { metadata, stored: published.stored }\n })\n\n return {\n put: Effect.fn(\"ContentStore.put\")(function*(\n workspaceId: WorkspaceId,\n input: PutContentInput\n ) {\n if (input.classification === \"durable\") {\n // Durable bytes are never reclaimed by diff-cache cleanup. Publish them\n // without holding SQLite's global writer lock across filesystem I/O,\n // then briefly serialize the canonical-presence check and metadata.\n const firstAttempt = yield* publishDurable(workspaceId, input).pipe(Effect.result)\n if (Result.isSuccess(firstAttempt)) return firstAttempt.success\n if (firstAttempt.failure._tag !== \"BlobNotFoundError\") return yield* firstAttempt.failure\n // A concurrent reproducible-cache sweep may win before the short SQL\n // finalization window. Republish once after that durable intent is gone.\n return yield* publishDurable(workspaceId, input)\n }\n return yield* database.transaction(\n Effect.gen(function*() {\n // Cache cleanup takes the same SQLite writer lock before unlinking bytes.\n // Holding it from before publication through metadata insertion makes\n // identical-digest publication and reclamation cross-process serial.\n yield* database.sql`UPDATE workspaces\n SET workspace_id = workspace_id\n WHERE workspace_id = ${workspaceId}`\n return yield* putReproducibleLocked(workspaceId, {\n bytes: input.bytes,\n classification: \"reproducible-cache\",\n mimeType: input.mimeType,\n createdAt: input.createdAt\n })\n })\n ).pipe(mapPersistenceOperation(\"content.put\"))\n }),\n getMetadata: requireMetadata,\n listMetadata: (workspaceId: WorkspaceId) => metadataRepository.list(workspaceId),\n readAll: Effect.fn(\"ContentStore.readAll\")(function*(\n workspaceId: WorkspaceId,\n digest: BlobDigest,\n maximumBytes?: number | undefined\n ) {\n const metadata = yield* requireMetadata(workspaceId, digest)\n return yield* blobs.readAll(workspaceId, digest, maximumBytes).pipe(\n Effect.mapError((failure) => mapReadFailure(metadata, failure))\n )\n }),\n readRange: Effect.fn(\"ContentStore.readRange\")(function*(\n workspaceId: WorkspaceId,\n digest: BlobDigest,\n range: BlobRange\n ) {\n const metadata = yield* requireMetadata(workspaceId, digest)\n return yield* blobs.readRange(workspaceId, digest, range).pipe(\n Effect.mapError((failure) => mapReadFailure(metadata, failure))\n )\n }),\n readStream: Effect.fn(\"ContentStore.readStream\")(function*(\n workspaceId: WorkspaceId,\n digest: BlobDigest,\n range?: BlobRange | undefined\n ) {\n const metadata = yield* requireMetadata(workspaceId, digest)\n const result = yield* blobs.readStream(workspaceId, digest, range).pipe(\n Effect.mapError((failure) => mapReadFailure(metadata, failure))\n )\n return {\n ...result,\n bytes: result.bytes.pipe(Stream.mapError((failure) => mapReadFailure(metadata, failure)))\n }\n }),\n removeReproducible: Effect.fn(\"ContentStore.removeReproducible\")(function*(\n workspaceId: WorkspaceId,\n digest: BlobDigest\n ) {\n const metadata = yield* requireMetadata(workspaceId, digest).pipe(\n Effect.map(Option.some),\n Effect.catchTag(\"RecordNotFoundError\", () => Effect.succeed(Option.none()))\n )\n // Another process may have completed the same stale cleanup candidate.\n if (Option.isNone(metadata)) return\n if (metadata.value.storageClass !== \"reproducible-cache\") {\n return yield* new ContentMetadataMismatchError({ workspaceId, digest })\n }\n yield* blobs.removeAuthorizedBytes(workspaceId, digest)\n }),\n verify: Effect.fn(\"ContentStore.verify\")(function*(\n workspaceId: WorkspaceId,\n digest: BlobDigest,\n verifiedAt: UtcTimestamp\n ) {\n const expected = yield* requireMetadata(workspaceId, digest)\n const verification = yield* blobs.verify(workspaceId, digest).pipe(\n Effect.mapError((failure) => mapReadFailure(expected, failure))\n )\n if (verification.sizeBytes !== expected.byteLength) {\n return yield* new ContentMetadataMismatchError({ workspaceId, digest })\n }\n const metadata = yield* metadataRepository.markVerified(workspaceId, digest, verifiedAt)\n return { metadata, verification }\n })\n }\n})\n\n/** Durable, workspace-scoped content whose SQL metadata never precedes its bytes. */\nexport interface ContentStoreService extends Success<typeof makeContentStore> {}\n\n/** Public content service combining the owner-only object store and SQL metadata. */\nexport class ContentStore extends Context.Service<ContentStore, ContentStoreService>()(\n \"@knpkv/control-center/ContentStore\"\n) {\n static readonly layer = Layer.effect(ContentStore, makeContentStore)\n}\n","/** Pure cross-head reconciliation for immutable PR-review suggestions. @module */\n\nimport {\n type PrReviewReport,\n type PrReviewSuggestionId,\n type PrReviewSuggestionState,\n type PrReviewSuggestionTransition,\n reconcilePrReviewReports\n} from \"./prReview.js\"\n\n/** One suggestion's state at the last completed review head. */\nexport type PreviousPrReviewSuggestion = {\n readonly suggestionId: PrReviewSuggestionId\n readonly state: PrReviewSuggestionState\n}\n\n/** Host-observed transition declared by the completed re-review. */\nexport type DeclaredPrReviewSuggestionTransition = {\n readonly suggestionId: PrReviewSuggestionId\n readonly kind: PrReviewSuggestionReconciliationKind\n}\n\n/** Explicit lifecycle result for one stable suggestion identity. */\nexport type PrReviewSuggestionReconciliationKind =\n | \"still-present\"\n | \"resolved\"\n | \"reopened\"\n | \"new\"\n\n/** Inputs to the pure reconciliation seam. */\nexport type ReconcilePrReviewSuggestionsInput = {\n readonly previous: ReadonlyArray<PreviousPrReviewSuggestion>\n readonly currentSuggestionIds: ReadonlyArray<PrReviewSuggestionId>\n readonly declared: ReadonlyArray<DeclaredPrReviewSuggestionTransition>\n}\n\n/** Why a re-review cannot be committed as a single lifecycle transition. */\nexport type ReconcilePrReviewSuggestionsFailure =\n | { readonly _tag: \"duplicate-id\"; readonly suggestionId: PrReviewSuggestionId }\n | { readonly _tag: \"unknown-id\"; readonly suggestionId: PrReviewSuggestionId }\n | {\n readonly _tag: \"contradictory-transition\"\n readonly suggestionId: PrReviewSuggestionId\n readonly expected: PrReviewSuggestionReconciliationKind\n readonly actual: PrReviewSuggestionReconciliationKind\n }\n | { readonly _tag: \"missing-transition\"; readonly suggestionId: PrReviewSuggestionId }\n\n/** One committed transition, returned in deterministic identity order. */\nexport type PrReviewSuggestionReconciliation = {\n readonly suggestionId: PrReviewSuggestionId\n readonly kind: PrReviewSuggestionReconciliationKind\n}\n\nexport type ReconcilePrReviewSuggestionsResult =\n | { readonly _tag: \"success\"; readonly transitions: ReadonlyArray<PrReviewSuggestionReconciliation> }\n | { readonly _tag: \"failure\"; readonly failure: ReconcilePrReviewSuggestionsFailure }\n\n/** Validate a report's explicit host transition set against the two immutable heads. */\nexport const validatePrReviewReportTransitions = (\n previous: PrReviewReport,\n current: PrReviewReport,\n declared: ReadonlyArray<PrReviewSuggestionTransition>\n): ReconcilePrReviewSuggestionsResult => {\n const expected = reconcilePrReviewReports(previous, current)\n const expectedById = new Map(expected.map((transition) => [transition.suggestionId, transition]))\n const declaredById = new Map<PrReviewSuggestionId, PrReviewSuggestionTransition>()\n\n for (const transition of declared) {\n if (!expectedById.has(transition.suggestionId)) {\n return { _tag: \"failure\", failure: { _tag: \"unknown-id\", suggestionId: transition.suggestionId } }\n }\n if (declaredById.has(transition.suggestionId)) {\n return { _tag: \"failure\", failure: { _tag: \"duplicate-id\", suggestionId: transition.suggestionId } }\n }\n declaredById.set(transition.suggestionId, transition)\n }\n\n for (const [suggestionId, expectedTransition] of expectedById) {\n const actual = declaredById.get(suggestionId)\n if (actual === undefined) {\n return { _tag: \"failure\", failure: { _tag: \"missing-transition\", suggestionId } }\n }\n if (\n actual.transition !== expectedTransition.transition ||\n actual.previousState !== expectedTransition.previousState ||\n actual.currentState !== expectedTransition.currentState ||\n actual.previousDismissalReason !== expectedTransition.previousDismissalReason ||\n actual.previousHead !== expectedTransition.previousHead ||\n actual.currentHead !== expectedTransition.currentHead\n ) {\n return {\n _tag: \"failure\",\n failure: {\n _tag: \"contradictory-transition\",\n suggestionId,\n expected: expectedTransition.transition,\n actual: actual.transition\n }\n }\n }\n }\n\n return {\n _tag: \"success\",\n transitions: expected.map(({ suggestionId, transition: kind }) => ({ suggestionId, kind }))\n }\n}\n\nconst isPresentState = (state: PrReviewSuggestionState): boolean =>\n state === \"draft\" || state === \"published\" || state === \"stale\" || state === \"reopened\"\n\n/**\n * Validate and classify a complete re-review observation without touching\n * persistence. Callers can reject the whole transaction on the failure branch.\n */\nexport const reconcilePrReviewSuggestions = (\n input: ReconcilePrReviewSuggestionsInput\n): ReconcilePrReviewSuggestionsResult => {\n const previous = new Map<PrReviewSuggestionId, PrReviewSuggestionState>()\n for (const suggestion of input.previous) {\n if (previous.has(suggestion.suggestionId)) {\n return { _tag: \"failure\", failure: { _tag: \"duplicate-id\", suggestionId: suggestion.suggestionId } }\n }\n previous.set(suggestion.suggestionId, suggestion.state)\n }\n\n const current = new Set<PrReviewSuggestionId>()\n for (const suggestionId of input.currentSuggestionIds) {\n if (current.has(suggestionId)) {\n return { _tag: \"failure\", failure: { _tag: \"duplicate-id\", suggestionId } }\n }\n current.add(suggestionId)\n }\n\n const expected = new Map<PrReviewSuggestionId, PrReviewSuggestionReconciliationKind>()\n for (const [suggestionId, state] of previous) {\n if (!current.has(suggestionId) && (state === \"dismissed\" || state === \"resolved\")) continue\n expected.set(\n suggestionId,\n current.has(suggestionId)\n ? state === \"dismissed\" || state === \"resolved\"\n ? \"reopened\"\n : \"still-present\"\n : isPresentState(state)\n ? \"resolved\"\n : \"resolved\"\n )\n }\n for (const suggestionId of current) {\n if (!expected.has(suggestionId)) expected.set(suggestionId, \"new\")\n }\n\n const declared = new Map<PrReviewSuggestionId, PrReviewSuggestionReconciliationKind>()\n for (const transition of input.declared) {\n if (!expected.has(transition.suggestionId)) {\n return { _tag: \"failure\", failure: { _tag: \"unknown-id\", suggestionId: transition.suggestionId } }\n }\n if (declared.has(transition.suggestionId)) {\n return { _tag: \"failure\", failure: { _tag: \"duplicate-id\", suggestionId: transition.suggestionId } }\n }\n declared.set(transition.suggestionId, transition.kind)\n }\n\n for (const [suggestionId, kind] of expected) {\n const actual = declared.get(suggestionId)\n if (actual === undefined) {\n return { _tag: \"failure\", failure: { _tag: \"missing-transition\", suggestionId } }\n }\n if (actual !== kind) {\n return {\n _tag: \"failure\",\n failure: { _tag: \"contradictory-transition\", suggestionId, expected: kind, actual }\n }\n }\n }\n\n return {\n _tag: \"success\",\n transitions: [...expected].map(([suggestionId, kind]) => ({ suggestionId, kind }))\n }\n}\n","/** Append-only PR-review suggestion revision projection and persistence. @module */\nimport type { AgentProviderId } from \"@knpkv/ai-runtime\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\n\nimport {\n type AgentThreadId,\n type JobId,\n PrReviewSuggestionRevisionId,\n type WorkspaceId\n} from \"../../../../domain/identifiers.js\"\nimport { PrReviewSuggestion, type PrReviewSuggestionId } from \"../../../../domain/prReview.js\"\nimport {\n hasSamePrReviewTechnicalClaim,\n MAXIMUM_PR_REVIEW_SUGGESTION_REVISION_BYTES,\n PrReviewSuggestionAgentAuthor,\n PrReviewSuggestionEdit,\n PrReviewSuggestionRequiresRevalidation,\n PrReviewSuggestionRevision,\n PrReviewSuggestionRevisionPage,\n PrReviewSuggestionRevisionSequence,\n PrReviewSuggestionValidated\n} from \"../../../../domain/prReviewRevision.js\"\nimport { type UtcTimestamp } from \"../../../../domain/utcTimestamp.js\"\nimport type { Database } from \"../../Database.js\"\nimport {\n PersistedRecordError,\n PersistenceOperationError,\n RecordNotFoundError,\n RevisionConflictError\n} from \"../../errors.js\"\nimport {\n AgentJobInputError,\n type AgentJobTask,\n type AgentReviewResultRecord,\n AppendReviewSuggestionRevisionInput,\n ReadReviewSuggestionRevisionsInput\n} from \"../agentJobModels.js\"\n\nconst REVISION_ID_NAMESPACE = \"review-suggestion-revision/v1\"\n\nconst PersistedDigest = Schema.String.check(\n Schema.isPattern(/^sha256:[0-9a-f]{64}$/u, {\n expected: \"a lowercase SHA-256 digest\"\n })\n)\n\nconst RevisionRow = Schema.Struct({\n revisionSequence: PrReviewSuggestionRevisionSequence,\n revisionId: PrReviewSuggestionRevisionId,\n predecessorRevisionId: PrReviewSuggestionRevisionId,\n revisionJson: Schema.String,\n revisionDigest: PersistedDigest,\n createdAt: PrReviewSuggestionRevision.fields.createdAt\n})\n\nconst RevisionStatsRow = Schema.Struct({\n revisionCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n minimumSequence: Schema.NullOr(PrReviewSuggestionRevisionSequence),\n maximumSequence: Schema.NullOr(PrReviewSuggestionRevisionSequence)\n})\n\n/** Metadata-only durable event emitted with an accepted suggestion revision. */\nexport const ReviewSuggestionRevisedPayload = Schema.Struct({\n suggestionId: PrReviewSuggestion.fields.suggestionId,\n revisionId: PrReviewSuggestionRevision.fields.revisionId,\n sequence: PrReviewSuggestionRevision.fields.sequence,\n authorKind: Schema.Literals([\"operator\", \"agent\"]),\n validationState: Schema.Literals([\"validated\", \"requires-revalidation\"]),\n suggestionState: Schema.optionalKey(PrReviewSuggestion.fields.state)\n})\n\ninterface SourceJob {\n readonly threadId: AgentThreadId\n readonly providerId: AgentProviderId\n readonly model: null | string\n readonly task: AgentJobTask\n}\n\ninterface RevisionOperationsDependencies<\n ReadFailure,\n JobFailure,\n EventFailure\n> {\n readonly database: Database[\"Service\"]\n readonly bytesFromText: (\n value: string\n ) => Effect.Effect<Uint8Array, PersistenceOperationError>\n readonly digestBytes: (\n bytes: Uint8Array\n ) => Effect.Effect<string, PersistenceOperationError>\n readonly readReviewResult: (\n input: {\n readonly workspaceId: WorkspaceId\n readonly jobId: JobId\n }\n ) => Effect.Effect<AgentReviewResultRecord, ReadFailure>\n readonly getJob: (\n workspaceId: WorkspaceId,\n jobId: JobId\n ) => Effect.Effect<SourceJob, JobFailure>\n readonly appendThreadEvent: (options: {\n readonly workspaceId: WorkspaceId\n readonly threadId: AgentThreadId\n readonly jobId: JobId\n readonly attemptSequence: null\n readonly eventKind: \"review-suggestion-revised\"\n readonly payload: typeof ReviewSuggestionRevisedPayload.Type\n readonly payloadSchema: typeof ReviewSuggestionRevisedPayload\n readonly occurredAt: UtcTimestamp\n }) => Effect.Effect<unknown, EventFailure>\n}\n\nconst revisionRecordKey = (\n jobId: JobId,\n suggestionId: PrReviewSuggestionId\n): string => `${jobId}/${suggestionId}`\n\n/** Build the cohesive revision boundary inside the owning agent repository. */\nexport const makeReviewSuggestionRevisionOperations = <\n ReadFailure,\n JobFailure,\n EventFailure\n>(\n dependencies: RevisionOperationsDependencies<\n ReadFailure,\n JobFailure,\n EventFailure\n >\n) => {\n const {\n appendThreadEvent,\n bytesFromText,\n database,\n digestBytes,\n getJob,\n readReviewResult\n } = dependencies\n const sql = database.sql\n\n const operationFailure = (operation: string) => new PersistenceOperationError({ operation })\n\n const recordFailure = (\n workspaceId: WorkspaceId,\n jobId: JobId,\n suggestionId: PrReviewSuggestionId,\n diagnosticCode: string\n ) =>\n new PersistedRecordError({\n workspaceId,\n recordKind: \"agent-review-suggestion-revision\",\n recordKey: revisionRecordKey(jobId, suggestionId),\n diagnosticCode\n })\n\n const deriveRevisionId = Effect.fn(\n \"ReviewSuggestionRevisions.deriveRevisionId\"\n )(function*(\n jobId: JobId,\n suggestionId: PrReviewSuggestionId,\n sequence: typeof PrReviewSuggestionRevisionSequence.Type\n ) {\n const bytes = yield* bytesFromText(\n `${REVISION_ID_NAMESPACE}\\u0000${jobId}\\u0000${suggestionId}\\u0000${String(sequence)}`\n )\n return yield* Schema.decodeUnknownEffect(PrReviewSuggestionRevisionId)(\n yield* digestBytes(bytes)\n ).pipe(\n Effect.mapError(() => operationFailure(\"agent-job.review-revision-id\"))\n )\n })\n\n const encodeRevision = Effect.fn(\n \"ReviewSuggestionRevisions.encodeRevision\"\n )(function*(\n workspaceId: WorkspaceId,\n revision: PrReviewSuggestionRevision\n ) {\n const json = yield* Schema.encodeUnknownEffect(\n Schema.fromJsonString(PrReviewSuggestionRevision)\n )(revision).pipe(\n Effect.mapError(() => operationFailure(\"agent-job.encode-review-revision\"))\n )\n const bytes = yield* bytesFromText(json)\n if (bytes.length > MAXIMUM_PR_REVIEW_SUGGESTION_REVISION_BYTES) {\n return yield* new AgentJobInputError({\n workspaceId,\n jobId: revision.sourceJobId,\n reason: \"output-limit-exceeded\"\n })\n }\n return {\n json,\n digest: yield* digestBytes(bytes)\n }\n })\n\n const originalRevision = Effect.fn(\n \"ReviewSuggestionRevisions.originalRevision\"\n )(function*(\n workspaceId: WorkspaceId,\n jobId: JobId,\n suggestionId: PrReviewSuggestionId\n ) {\n const job = yield* getJob(workspaceId, jobId)\n const result = yield* readReviewResult({ workspaceId, jobId })\n if (job.task._tag !== \"pr-review\") {\n return yield* recordFailure(\n workspaceId,\n jobId,\n suggestionId,\n \"agent-review-revision-task-mismatch\"\n )\n }\n const suggestion = result.report.suggestions.find(\n (candidate) => candidate.suggestionId === suggestionId\n )\n if (suggestion === undefined) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"agent-review-suggestion\",\n recordKey: suggestionId\n })\n }\n const sequence = PrReviewSuggestionRevisionSequence.make(1)\n const revisionId = yield* deriveRevisionId(jobId, suggestionId, sequence)\n return yield* Effect.try({\n try: () =>\n PrReviewSuggestionRevision.make({\n revisionId,\n sequence,\n predecessorRevisionId: null,\n sourceJobId: jobId,\n subject: result.report.subject,\n suggestion,\n validation: PrReviewSuggestionValidated.make({\n reviewedHead: result.report.subject.headRevision,\n validatingJobId: jobId,\n sourceRevisionId: revisionId\n }),\n author: PrReviewSuggestionAgentAuthor.make({\n jobId,\n providerId: job.providerId,\n model: job.model,\n runtimeMetadata: null\n }),\n createdAt: result.completedAt\n }),\n catch: () =>\n recordFailure(\n workspaceId,\n jobId,\n suggestionId,\n \"agent-review-original-revision-invalid\"\n )\n })\n })\n\n const revisionStats = Effect.fn(\n \"ReviewSuggestionRevisions.revisionStats\"\n )(function*(\n workspaceId: WorkspaceId,\n jobId: JobId,\n suggestionId: PrReviewSuggestionId\n ) {\n const rows = yield* sql<Record<string, unknown>>`SELECT\n COUNT(*) AS revisionCount,\n MIN(revision_sequence) AS minimumSequence,\n MAX(revision_sequence) AS maximumSequence\n FROM agent_review_suggestion_revisions\n WHERE workspace_id = ${workspaceId}\n AND source_job_id = ${jobId}\n AND suggestion_id = ${suggestionId}`\n const decoded = Schema.decodeUnknownResult(\n Schema.Array(RevisionStatsRow)\n )(rows)\n const stats = Result.isSuccess(decoded) ? decoded.success[0] : undefined\n if (stats === undefined) {\n return yield* recordFailure(\n workspaceId,\n jobId,\n suggestionId,\n \"agent-review-revision-stats-invalid\"\n )\n }\n if (\n stats.revisionCount > 0 &&\n (\n stats.minimumSequence !== 2 ||\n stats.maximumSequence === null ||\n stats.maximumSequence !== stats.revisionCount + 1\n )\n ) {\n return yield* recordFailure(\n workspaceId,\n jobId,\n suggestionId,\n \"agent-review-revision-sequence-invalid\"\n )\n }\n return stats\n })\n\n const decodeRevisionRow = Effect.fn(\n \"ReviewSuggestionRevisions.decodeRevisionRow\"\n )(function*(\n workspaceId: WorkspaceId,\n jobId: JobId,\n suggestionId: PrReviewSuggestionId,\n unknownRow: Record<string, unknown>\n ) {\n const row = Schema.decodeUnknownResult(RevisionRow)(unknownRow)\n if (Result.isFailure(row)) {\n return yield* recordFailure(\n workspaceId,\n jobId,\n suggestionId,\n \"agent-review-revision-row-invalid\"\n )\n }\n const bytes = yield* bytesFromText(row.success.revisionJson)\n if ((yield* digestBytes(bytes)) !== row.success.revisionDigest) {\n return yield* recordFailure(\n workspaceId,\n jobId,\n suggestionId,\n \"agent-review-revision-integrity-invalid\"\n )\n }\n const revision = yield* Schema.decodeUnknownEffect(\n Schema.fromJsonString(PrReviewSuggestionRevision)\n )(row.success.revisionJson).pipe(\n Effect.mapError(() =>\n recordFailure(\n workspaceId,\n jobId,\n suggestionId,\n \"agent-review-revision-payload-invalid\"\n )\n )\n )\n const expectedRevisionId = yield* deriveRevisionId(\n jobId,\n suggestionId,\n row.success.revisionSequence\n )\n if (row.success.revisionSequence < 2) {\n return yield* recordFailure(\n workspaceId,\n jobId,\n suggestionId,\n \"agent-review-revision-row-invalid\"\n )\n }\n const expectedPredecessorId = yield* deriveRevisionId(\n jobId,\n suggestionId,\n PrReviewSuggestionRevisionSequence.make(\n row.success.revisionSequence - 1\n )\n )\n if (\n row.success.revisionId !== expectedRevisionId ||\n row.success.predecessorRevisionId !== expectedPredecessorId ||\n revision.revisionId !== row.success.revisionId ||\n revision.predecessorRevisionId !== row.success.predecessorRevisionId ||\n revision.sequence !== row.success.revisionSequence ||\n revision.sourceJobId !== jobId ||\n revision.suggestion.suggestionId !== suggestionId ||\n !DateTime.Equivalence(revision.createdAt, row.success.createdAt)\n ) {\n return yield* recordFailure(\n workspaceId,\n jobId,\n suggestionId,\n \"agent-review-revision-projection-invalid\"\n )\n }\n return revision\n })\n\n const currentRevision = Effect.fn(\n \"ReviewSuggestionRevisions.currentRevision\"\n )(function*(\n workspaceId: WorkspaceId,\n jobId: JobId,\n suggestionId: PrReviewSuggestionId\n ) {\n const original = yield* originalRevision(workspaceId, jobId, suggestionId)\n const stats = yield* revisionStats(workspaceId, jobId, suggestionId)\n if (stats.maximumSequence === null) return original\n const rows = yield* sql<Record<string, unknown>>`SELECT\n revision_sequence AS revisionSequence,\n revision_id AS revisionId,\n predecessor_revision_id AS predecessorRevisionId,\n revision_json AS revisionJson,\n revision_digest AS revisionDigest,\n created_at AS createdAt\n FROM agent_review_suggestion_revisions\n WHERE workspace_id = ${workspaceId}\n AND source_job_id = ${jobId}\n AND suggestion_id = ${suggestionId}\n AND revision_sequence = ${stats.maximumSequence}`\n if (rows.length !== 1) {\n return yield* recordFailure(\n workspaceId,\n jobId,\n suggestionId,\n \"agent-review-current-revision-missing\"\n )\n }\n return yield* decodeRevisionRow(\n workspaceId,\n jobId,\n suggestionId,\n rows[0]!\n )\n })\n\n const read = Effect.fn(\"ReviewSuggestionRevisions.read\")(function*(\n input: typeof ReadReviewSuggestionRevisionsInput.Type\n ) {\n const request = yield* Schema.decodeUnknownEffect(\n Schema.toType(ReadReviewSuggestionRevisionsInput)\n )(input)\n const current = yield* currentRevision(\n request.workspaceId,\n request.jobId,\n request.suggestionId\n )\n const before = request.beforeSequence ?? current.sequence\n if (before > current.sequence) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-transition\"\n })\n }\n const unknownRows = before <= 2\n ? []\n : yield* sql<Record<string, unknown>>`SELECT\n revision_sequence AS revisionSequence,\n revision_id AS revisionId,\n predecessor_revision_id AS predecessorRevisionId,\n revision_json AS revisionJson,\n revision_digest AS revisionDigest,\n created_at AS createdAt\n FROM agent_review_suggestion_revisions\n WHERE workspace_id = ${request.workspaceId}\n AND source_job_id = ${request.jobId}\n AND suggestion_id = ${request.suggestionId}\n AND revision_sequence < ${before}\n ORDER BY revision_sequence DESC\n LIMIT ${request.limit + 1}`\n const candidates = yield* Effect.forEach(\n unknownRows,\n (row) =>\n decodeRevisionRow(\n request.workspaceId,\n request.jobId,\n request.suggestionId,\n row\n )\n )\n if (\n candidates.length <= request.limit &&\n before > 1 &&\n (candidates.at(-1)?.sequence ?? before) > 1\n ) {\n candidates.push(\n yield* originalRevision(\n request.workspaceId,\n request.jobId,\n request.suggestionId\n )\n )\n }\n const revisions = candidates.slice(0, request.limit)\n const hasMore = candidates.length > request.limit\n return yield* Schema.decodeUnknownEffect(\n Schema.toType(PrReviewSuggestionRevisionPage)\n )({\n current,\n revisions,\n hasMore,\n nextBeforeSequence: hasMore\n ? revisions.at(-1)?.sequence ?? null\n : null\n }).pipe(\n Effect.mapError(() => operationFailure(\"agent-job.review-revision-page-invalid\"))\n )\n })\n\n const appendInTransaction = Effect.fn(\"ReviewSuggestionRevisions.appendInTransaction\")(function*(\n input: typeof AppendReviewSuggestionRevisionInput.Type\n ) {\n const request = yield* Schema.decodeUnknownEffect(\n Schema.toType(AppendReviewSuggestionRevisionInput)\n )(input)\n return yield* Effect.gen(function*() {\n if (request.leaseFence !== undefined) {\n const activeFence = yield* sql`SELECT 1\n FROM agent_jobs job\n JOIN agent_job_leases lease\n ON lease.workspace_id = job.workspace_id\n AND lease.job_id = job.job_id\n AND lease.attempt_sequence = ${request.leaseFence.attemptSequence}\n AND lease.lease_token = ${request.leaseFence.leaseToken}\n WHERE job.workspace_id = ${request.workspaceId}\n AND job.job_id = ${request.leaseFence.jobId}\n AND job.state = 'running'\n AND job.cancel_requested_at IS NULL\n AND lease.lease_expires_at > ${\n Schema.encodeSync(\n PrReviewSuggestionRevision.fields.createdAt\n )(request.createdAt)\n }\n LIMIT 1`\n if (activeFence.length !== 1) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.leaseFence.jobId,\n reason: \"cancellation-requested\"\n })\n }\n }\n const current = yield* currentRevision(\n request.workspaceId,\n request.jobId,\n request.suggestionId\n )\n const expectedRevisionId = yield* deriveRevisionId(\n request.jobId,\n request.suggestionId,\n request.expectedSequence\n )\n if (expectedRevisionId !== request.expectedRevisionId) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"revision-identity-mismatch\"\n })\n }\n if (\n current.revisionId !== request.expectedRevisionId ||\n current.sequence !== request.expectedSequence\n ) {\n return yield* new RevisionConflictError({\n workspaceId: request.workspaceId,\n recordKind: \"agent-review-suggestion-revision\",\n recordKey: revisionRecordKey(\n request.jobId,\n request.suggestionId\n ),\n expectedRevision: request.expectedSequence,\n actualRevision: current.sequence\n })\n }\n const currentEdit = yield* Schema.decodeUnknownEffect(\n Schema.toType(PrReviewSuggestionEdit)\n )(current.suggestion).pipe(\n Effect.mapError(() =>\n recordFailure(\n request.workspaceId,\n request.jobId,\n request.suggestionId,\n \"agent-review-current-edit-invalid\"\n )\n )\n )\n const currentEditJson = yield* Schema.encodeUnknownEffect(\n Schema.fromJsonString(PrReviewSuggestionEdit)\n )(currentEdit).pipe(\n Effect.mapError(() => operationFailure(\"agent-job.encode-current-review-edit\"))\n )\n const requestedEditJson = yield* Schema.encodeUnknownEffect(\n Schema.fromJsonString(PrReviewSuggestionEdit)\n )(request.edit).pipe(\n Effect.mapError(() => operationFailure(\"agent-job.encode-requested-review-edit\"))\n )\n if (\n currentEditJson === requestedEditJson &&\n request.state === undefined &&\n request.validation === undefined\n ) return current\n const activePublication = yield* sql`SELECT 1\n FROM agent_review_suggestion_publications\n WHERE workspace_id = ${request.workspaceId}\n AND job_id = ${request.jobId}\n AND suggestion_id = ${request.suggestionId}\n LIMIT 1`\n if (activePublication.length > 0) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-transition\"\n })\n }\n if (\n (\n current.suggestion.state !== \"draft\" &&\n !(request.state === \"stale\" && current.suggestion.state === \"published\")\n ) ||\n (request.state === \"dismissed\" && request.dismissalReason === undefined) ||\n (request.state !== \"dismissed\" && request.dismissalReason !== undefined) ||\n (\n request.edit.replacement !== undefined &&\n request.edit.replacement.reviewedHead !==\n current.subject.headRevision\n ) ||\n DateTime.Order(request.createdAt, current.createdAt) < 0\n ) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-transition\"\n })\n }\n const sequence = PrReviewSuggestionRevisionSequence.make(\n current.sequence + 1\n )\n const revisionId = yield* deriveRevisionId(\n request.jobId,\n request.suggestionId,\n sequence\n )\n const isAgentValidation = request.validation === \"validated\" &&\n request.author._tag === \"agent\"\n const validation = isAgentValidation\n ? PrReviewSuggestionValidated.make({\n reviewedHead: current.subject.headRevision,\n validatingJobId: request.author.jobId,\n sourceRevisionId: current.revisionId\n })\n : hasSamePrReviewTechnicalClaim(currentEdit, request.edit)\n ? current.validation\n : PrReviewSuggestionRequiresRevalidation.make({\n reviewedHead: current.subject.headRevision,\n sourceRevisionId: current.revisionId,\n reason: request.author._tag === \"agent\"\n ? \"agent-edit-not-validated\"\n : \"technical-claim-edited\"\n })\n const suggestion = yield* Schema.decodeUnknownEffect(\n Schema.toType(PrReviewSuggestion)\n )({\n suggestionId: request.suggestionId,\n state: request.state ?? current.suggestion.state,\n ...(request.dismissalReason === undefined ? {} : { dismissalReason: request.dismissalReason }),\n ...request.edit\n }).pipe(\n Effect.mapError(() => operationFailure(\"agent-job.review-revision-suggestion-invalid\"))\n )\n const revision = yield* Effect.try({\n try: () =>\n PrReviewSuggestionRevision.make({\n revisionId,\n sequence,\n predecessorRevisionId: current.revisionId,\n sourceJobId: request.jobId,\n subject: current.subject,\n suggestion,\n validation,\n author: request.author,\n createdAt: request.createdAt\n }),\n catch: () => operationFailure(\"agent-job.review-revision-invalid\")\n })\n const encoded = yield* encodeRevision(request.workspaceId, revision)\n yield* sql`INSERT INTO agent_review_suggestion_revisions (\n workspace_id, source_job_id, suggestion_id, revision_sequence,\n revision_id, predecessor_revision_id, revision_json,\n revision_digest, created_at\n ) VALUES (\n ${request.workspaceId}, ${request.jobId}, ${request.suggestionId},\n ${sequence}, ${revisionId}, ${current.revisionId},\n ${encoded.json}, ${encoded.digest},\n ${\n Schema.encodeSync(PrReviewSuggestionRevision.fields.createdAt)(\n request.createdAt\n )\n }\n )`\n const job = yield* getJob(request.workspaceId, request.jobId)\n yield* appendThreadEvent({\n workspaceId: request.workspaceId,\n threadId: job.threadId,\n jobId: request.jobId,\n attemptSequence: null,\n eventKind: \"review-suggestion-revised\",\n payload: {\n suggestionId: request.suggestionId,\n revisionId,\n sequence,\n authorKind: request.author._tag,\n validationState: validation._tag,\n suggestionState: suggestion.state\n },\n payloadSchema: ReviewSuggestionRevisedPayload,\n occurredAt: request.createdAt\n })\n return revision\n })\n })\n\n const append = Effect.fn(\"ReviewSuggestionRevisions.append\")(function*(\n input: typeof AppendReviewSuggestionRevisionInput.Type\n ) {\n return yield* database.transaction(appendInTransaction(input))\n })\n\n return { append, appendInTransaction, read }\n}\n","/** Durable release-thread job claiming, event persistence, and replay. @module */\nimport { AgentProviderError, AgentRuntimeEvent, MAXIMUM_AGENT_RUNTIME_EVENT_BYTES } from \"@knpkv/ai-runtime\"\nimport {\n type ClaimableAgentJobState,\n renderAgentJobClaimQuery,\n renderAgentJobDispatchCandidatesQuery,\n renderAgentReviewContextEventsQuery,\n renderAgentReviewThreadHistoryQuery,\n renderAgentThreadBeforeQuery,\n renderAgentThreadReplayQuery,\n renderAgentThreadTailQuery,\n renderLatestAgentReviewQuery\n} from \"@knpkv/control-center-sql\"\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 type { Success } from \"effect/Effect\"\nimport * as Encoding from \"effect/Encoding\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\n\nimport {\n AgentThreadId,\n GovernedActionId,\n JobId,\n PluginConnectionId,\n ReleaseId,\n ReviewSuggestionPublicationReservationId,\n WorkspaceId\n} from \"../../../domain/identifiers.js\"\nimport {\n MAXIMUM_PR_REVIEW_REPORT_BYTES,\n PrReviewReport,\n PrReviewSubject,\n PrReviewSuggestionId,\n reconcilePrReviewReports\n} from \"../../../domain/prReview.js\"\nimport { validatePrReviewReportTransitions } from \"../../../domain/prReviewReconciliation.js\"\nimport {\n PrReviewSuggestionAgentAuthor,\n PrReviewSuggestionEdit,\n PrReviewSuggestionRevision,\n PrReviewSuggestionRevisionPageSize\n} from \"../../../domain/prReviewRevision.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport { Database } from \"../Database.js\"\nimport {\n MAXIMUM_PERSISTENCE_RECORD_KEY_LENGTH,\n PersistedRecordError,\n PersistenceOperationError,\n RecordNotFoundError\n} from \"../errors.js\"\nimport {\n AgentAttemptSequence,\n AgentContextSnapshotRecord,\n AgentEventCursor,\n AgentJobInputError,\n type AgentJobPrompt,\n AgentJobState,\n AgentJobTask,\n AgentJobTaskTag,\n AgentLeaseToken,\n AgentReviewResultInput,\n AgentReviewResultRecord,\n AgentReviewThreadAfterInput,\n AgentReviewThreadBeforeInput,\n AgentReviewThreadHistoryInput,\n AgentReviewThreadTailInput,\n AgentThreadEvent,\n type AgentThreadEventPage,\n AgentThreadEventPageSize,\n AppendAgentEventInput,\n type AppendReviewSuggestionRevisionInput,\n AttachRunningPrReviewSessionInput,\n ClaimAgentJobInput,\n ClaimedAgentJob,\n CompleteAgentReviewInput,\n CompleteTargetedReviewInput,\n EnqueueAgentJobInput,\n ExtendReviewBudgetInput,\n InterruptRunningReviewsInput,\n LatestAgentReviewInput,\n LatestAgentReviewRecord,\n MAXIMUM_AGENT_ATTEMPT_OUTPUT_BYTES,\n MAXIMUM_AGENT_THREAD_EVENT_PAGE_SIZE,\n PrReviewThreadContextSnapshot,\n type PrReviewThreadSubject,\n ReadReviewBudgetInput,\n ReadReviewSuggestionPublication,\n ReadReviewSuggestionPublicationInput,\n type ReadReviewSuggestionRevisionsInput,\n RecordAgentReviewProgressInput,\n RecordReviewSuggestionPublicationInput,\n ReleaseReviewSuggestionPublicationInput,\n ReserveReviewSuggestionPublicationInput,\n ReviewSuggestionPublicationCommentId,\n ReviewSuggestionPublicationDigest,\n ReviewSuggestionPublicationReservation,\n RunningPrReviewAttempt\n} from \"./agentJobModels.js\"\nimport { mapAlreadyExists, mapPersistenceOperation, readChanges } from \"./internal.js\"\nimport {\n makeReviewSuggestionRevisionOperations,\n ReviewSuggestionRevisedPayload\n} from \"./internal/reviewSuggestionRevisions.js\"\n\nconst DISPATCH_CANDIDATE_LIMIT = 32\nconst MAXIMUM_AGENT_EVENT_BYTES = MAXIMUM_AGENT_RUNTIME_EVENT_BYTES\nconst SHA_256_PREFIX = \"sha256:\"\nconst REVIEW_SUGGESTION_PUBLICATION_RESERVATION_LIFETIME_MINUTES = 10\nconst REVIEW_CONTEXT_EVENT_LIMIT = 32\nconst REVIEW_CONTEXT_ITEM_LIMIT = 4\nconst REVIEW_CONTEXT_REPORT_ITEM_LIMIT = 8\nconst PrReviewSubjectEquivalence = Schema.toEquivalence(PrReviewSubject)\nconst PrReviewThreadIdentity = Schema.Struct({\n pluginConnectionId: PluginConnectionId,\n providerId: PrReviewSubject.fields.providerId,\n repository: PrReviewSubject.fields.repository,\n pullRequestId: PrReviewSubject.fields.pullRequestId\n})\n\nconst PersistedDigest = Schema.String.check(\n Schema.isPattern(/^sha256:[0-9a-f]{64}$/u, { expected: \"a lowercase SHA-256 digest\" })\n)\n\nconst ReviewSuggestionLifecycleRevisionRow = Schema.Struct({\n suggestionId: PrReviewSuggestionId,\n revisionJson: Schema.String,\n revisionDigest: PersistedDigest\n})\n\nconst UserMessagePayload = Schema.Struct({\n prompt: EnqueueAgentJobInput.fields.userPrompt\n})\n\nconst JobQueuedPayload = Schema.Struct({\n model: EnqueueAgentJobInput.fields.model,\n providerId: EnqueueAgentJobInput.fields.providerId\n})\n\nconst PersistedJobQueuedPayload = Schema.Struct({\n access: EnqueueAgentJobInput.fields.access,\n contextFingerprint: EnqueueAgentJobInput.fields.contextFingerprint,\n model: EnqueueAgentJobInput.fields.model,\n providerId: EnqueueAgentJobInput.fields.providerId,\n subjectRevision: EnqueueAgentJobInput.fields.subjectRevision,\n task: AgentJobTask,\n reviewBudgetMillis: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 3_600_000 }))),\n reviewBudgetExtensionCount: Schema.optionalKey(Schema.Literal(1))\n})\n\nconst CancellationRequestedPayload = Schema.Struct({\n requestedAt: UtcTimestamp\n})\n\nconst ProviderFailurePayload = Schema.Struct({\n error: AgentProviderError\n})\n\nexport const PROCESS_RESTART_INTERRUPTION_MESSAGE = \"Review interrupted because the Control Center process restarted.\"\n\nconst ReviewSuggestionPublishedPayload = Schema.Struct({\n suggestionId: RecordReviewSuggestionPublicationInput.fields.suggestionId,\n revisionId: RecordReviewSuggestionPublicationInput.fields.revisionId,\n publicationId: RecordReviewSuggestionPublicationInput.fields.publicationId\n})\n\nconst ReviewSuggestionPublicationRow = Schema.Struct({\n revisionId: RecordReviewSuggestionPublicationInput.fields.revisionId,\n contentDigest: ReviewSuggestionPublicationDigest,\n state: Schema.Literals([\"reserved\", \"published\"]),\n publicationId: Schema.NullOr(GovernedActionId),\n commentId: Schema.NullOr(ReviewSuggestionPublicationCommentId),\n previousContentDigest: Schema.NullOr(ReviewSuggestionPublicationDigest),\n previousPublicationId: Schema.NullOr(GovernedActionId),\n previousPublishedAt: Schema.NullOr(UtcTimestamp),\n reservationAcquiredAt: UtcTimestamp,\n reservationId: ReviewSuggestionPublicationReservationId,\n reservedAt: UtcTimestamp,\n publishedAt: Schema.NullOr(UtcTimestamp)\n})\n\nconst ThreadRow = Schema.Struct({\n threadId: AgentThreadId,\n threadKind: AgentJobTaskTag,\n subjectKey: Schema.String,\n releaseId: ReleaseId\n})\n\nconst JobRow = Schema.Struct({\n workspaceId: WorkspaceId,\n jobId: JobId,\n threadId: AgentThreadId,\n releaseId: ReleaseId,\n providerId: EnqueueAgentJobInput.fields.providerId,\n model: EnqueueAgentJobInput.fields.model,\n access: EnqueueAgentJobInput.fields.access,\n prompt: EnqueueAgentJobInput.fields.prompt,\n contextFingerprint: EnqueueAgentJobInput.fields.contextFingerprint,\n subjectRevision: EnqueueAgentJobInput.fields.subjectRevision,\n taskContextJson: Schema.String,\n taskContextDigest: PersistedDigest,\n state: AgentJobState,\n createdAt: UtcTimestamp,\n cancelRequestedAt: Schema.NullOr(UtcTimestamp),\n terminalAt: Schema.NullOr(UtcTimestamp)\n})\n\nconst LatestReviewRow = Schema.Struct({\n jobId: JobId,\n threadId: AgentThreadId,\n providerId: EnqueueAgentJobInput.fields.providerId,\n model: EnqueueAgentJobInput.fields.model,\n state: AgentJobState,\n createdAt: UtcTimestamp,\n terminalAt: Schema.NullOr(UtcTimestamp),\n taskContextJson: Schema.String,\n taskContextDigest: PersistedDigest\n})\n\nconst DispatchCandidateRow = Schema.Struct({\n ...JobRow.fields,\n state: Schema.Literals([\"queued\", \"running\", \"cancel-requested\"]),\n attemptSequence: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER }))\n})\n\nconst PreviousAttemptRow = Schema.Struct({\n contextSnapshotJson: Schema.String,\n contextSnapshotDigest: PersistedDigest,\n sessionRef: ClaimedAgentJob.fields.sessionRef\n})\n\nconst ActiveAttemptRow = Schema.Struct({\n startedAt: UtcTimestamp,\n completedAt: Schema.NullOr(UtcTimestamp)\n})\n\nconst LeaseRow = Schema.Struct({\n leaseToken: AgentLeaseToken,\n leaseExpiresAt: UtcTimestamp\n})\n\nconst ActiveLeaseRow = Schema.Struct({\n active: Schema.Int\n})\n\nconst ThreadEventRow = Schema.Struct({\n workspaceId: WorkspaceId,\n threadId: AgentThreadId,\n eventSequence: AgentEventCursor.check(Schema.isGreaterThan(0)),\n jobId: JobId,\n attemptSequence: Schema.NullOr(AgentAttemptSequence),\n eventKind: AgentThreadEvent.fields.eventKind,\n payloadJson: Schema.String,\n payloadDigest: PersistedDigest,\n payloadByteLength: Schema.Int,\n occurredAt: UtcTimestamp\n})\n\nconst ReplayThreadEventRow = Schema.Struct({\n ...ThreadEventRow.fields,\n taskContextJson: Schema.String,\n taskContextDigest: PersistedDigest\n})\n\nconst ReviewContextThreadEventRow = Schema.Struct({\n ...ReplayThreadEventRow.fields,\n jobState: AgentJobState\n})\n\nconst FailAgentAttemptInput = Schema.Struct({\n workspaceId: WorkspaceId,\n jobId: JobId,\n attemptSequence: AgentAttemptSequence,\n leaseToken: AgentLeaseToken,\n error: AgentProviderError,\n failedAt: UtcTimestamp\n})\n\nconst RequestAgentCancellationInput = Schema.Struct({\n workspaceId: WorkspaceId,\n jobId: JobId,\n requestedAt: UtcTimestamp\n})\n\nconst HeartbeatAgentJobInput = Schema.Struct({\n workspaceId: WorkspaceId,\n jobId: JobId,\n attemptSequence: AgentAttemptSequence,\n leaseToken: AgentLeaseToken,\n leaseExpiresAt: UtcTimestamp\n})\n\nconst AgentThreadAfterInput = Schema.Struct({\n workspaceId: WorkspaceId,\n releaseId: ReleaseId,\n after: AgentEventCursor,\n limit: AgentThreadEventPageSize\n})\n\ntype EncodedPayload = {\n readonly bytes: Uint8Array\n readonly digest: string\n readonly json: string\n}\n\ntype EventKind = typeof AgentThreadEvent.fields.eventKind.Type\n\nconst encodeTimestamp = Schema.encodeSync(UtcTimestamp)\n\nconst persistedRecordError = (\n workspaceId: typeof WorkspaceId.Type,\n recordKind: string,\n recordKey: string,\n diagnosticCode: string\n) => new PersistedRecordError({ workspaceId, recordKind, recordKey, diagnosticCode })\n\nconst makeAgentJobRepository = Effect.gen(function*() {\n const cryptoService = yield* Crypto.Crypto\n const database = yield* Database\n const sql = database.sql\n\n const bytesFromText = Effect.fn(\"AgentJobRepository.bytesFromText\")(function*(value: string) {\n return yield* Effect.fromResult(Encoding.decodeBase64(Encoding.encodeBase64(value))).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"agent-job.encode-utf8\" }))\n )\n })\n\n const digestBytes = Effect.fn(\"AgentJobRepository.digestBytes\")(function*(bytes: Uint8Array) {\n const digest = yield* cryptoService\n .digest(\"SHA-256\", bytes)\n .pipe(Effect.mapError(() => new PersistenceOperationError({ operation: \"agent-job.digest\" })))\n return `${SHA_256_PREFIX}${Encoding.encodeHex(digest)}`\n })\n\n const encodePayload = Effect.fn(\"AgentJobRepository.encodePayload\")(function*(\n schema: Schema.Codec<unknown, unknown, never, never>,\n payload: unknown\n ): Effect.fn.Return<EncodedPayload, PersistenceOperationError> {\n const json = yield* Schema.encodeUnknownEffect(Schema.fromJsonString(schema))(payload).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"agent-job.encode-payload\" }))\n )\n const bytes = yield* bytesFromText(json)\n if (bytes.length > MAXIMUM_AGENT_EVENT_BYTES) {\n return yield* new PersistenceOperationError({ operation: \"agent-job.event-too-large\" })\n }\n return { bytes, digest: yield* digestBytes(bytes), json }\n })\n\n const encodeReviewReport = Effect.fn(\"AgentJobRepository.encodeReviewReport\")(function*(\n report: typeof PrReviewReport.Type\n ): Effect.fn.Return<EncodedPayload, PersistenceOperationError> {\n const json = yield* Schema.encodeUnknownEffect(Schema.fromJsonString(PrReviewReport))(report).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"agent-job.encode-review-report\" }))\n )\n const bytes = yield* bytesFromText(json)\n if (bytes.length > MAXIMUM_PR_REVIEW_REPORT_BYTES) {\n return yield* new PersistenceOperationError({ operation: \"agent-job.review-report-too-large\" })\n }\n return { bytes, digest: yield* digestBytes(bytes), json }\n })\n\n const sanitizeAgentReviewReport = (report: typeof PrReviewReport.Type): typeof PrReviewReport.Type =>\n (() => {\n const { transitions: _agentOwnedTransitions, ...agentOwnedReport } = report\n return PrReviewReport.make(agentOwnedReport)\n })()\n const isAgentOwnedSuggestionState = (state: typeof PrReviewReport.Type[\"suggestions\"][number][\"state\"]): boolean =>\n state === \"draft\" || state === \"resolved\"\n\n const decodeTaskContext = Effect.fn(\"AgentJobRepository.decodeTaskContext\")(function*(\n workspaceId: typeof WorkspaceId.Type,\n jobId: typeof JobId.Type,\n taskContextJson: string,\n taskContextDigest: typeof PersistedDigest.Type\n ) {\n const bytes = yield* bytesFromText(taskContextJson)\n const actualDigest = yield* digestBytes(bytes)\n if (actualDigest !== taskContextDigest) {\n return yield* persistedRecordError(\n workspaceId,\n \"agent-job\",\n jobId,\n \"agent-job-task-context-integrity-invalid\"\n )\n }\n return yield* Schema.decodeUnknownEffect(Schema.fromJsonString(AgentJobTask))(taskContextJson).pipe(\n Effect.mapError(() => persistedRecordError(workspaceId, \"agent-job\", jobId, \"agent-job-task-context-invalid\"))\n )\n })\n\n const reserveEventSequence = Effect.fn(\"AgentJobRepository.reserveEventSequence\")(function*(\n workspaceId: typeof WorkspaceId.Type,\n threadId: typeof AgentThreadId.Type\n ) {\n const rows = yield* sql<{ readonly eventSequence: number }>`UPDATE agent_threads\n SET next_event_sequence = next_event_sequence + 1\n WHERE workspace_id = ${workspaceId}\n AND thread_id = ${threadId}\n AND next_event_sequence < ${Number.MAX_SAFE_INTEGER}\n RETURNING next_event_sequence - 1 AS eventSequence`\n const eventSequence = rows[0]?.eventSequence\n if (eventSequence === undefined) {\n return yield* new PersistenceOperationError({ operation: \"agent-job.reserve-event-sequence\" })\n }\n return yield* Schema.decodeUnknownEffect(AgentEventCursor.check(Schema.isGreaterThan(0)))(eventSequence)\n })\n\n const appendThreadEvent = Effect.fn(\"AgentJobRepository.appendThreadEvent\")(function*(options: {\n readonly workspaceId: typeof WorkspaceId.Type\n readonly threadId: typeof AgentThreadId.Type\n readonly jobId: typeof JobId.Type\n readonly attemptSequence: null | typeof AgentAttemptSequence.Type\n readonly eventKind: EventKind\n readonly payload: unknown\n readonly payloadSchema: Schema.Codec<unknown, unknown, never, never>\n readonly occurredAt: typeof UtcTimestamp.Type\n }) {\n const encoded = yield* encodePayload(options.payloadSchema, options.payload).pipe(\n Effect.mapError((error): AgentJobInputError | PersistenceOperationError =>\n error.operation === \"agent-job.event-too-large\"\n ? new AgentJobInputError({\n workspaceId: options.workspaceId,\n jobId: options.jobId,\n reason: \"event-limit-exceeded\"\n })\n : error\n )\n )\n const eventSequence = yield* reserveEventSequence(options.workspaceId, options.threadId)\n yield* sql`INSERT INTO agent_thread_events (\n workspace_id, thread_id, event_sequence, job_id, attempt_sequence,\n event_kind, payload_json, payload_digest, payload_byte_length, occurred_at\n ) VALUES (\n ${options.workspaceId}, ${options.threadId}, ${eventSequence}, ${options.jobId},\n ${options.attemptSequence}, ${options.eventKind}, ${encoded.json}, ${encoded.digest},\n ${encoded.bytes.length}, ${encodeTimestamp(options.occurredAt)}\n )`\n return yield* Schema.decodeUnknownEffect(Schema.toType(AgentThreadEvent))({\n workspaceId: options.workspaceId,\n threadId: options.threadId,\n eventSequence,\n jobId: options.jobId,\n attemptSequence: options.attemptSequence,\n eventKind: options.eventKind,\n payload: options.payload,\n occurredAt: options.occurredAt\n })\n })\n\n const findThread = Effect.fn(\"AgentJobRepository.findThread\")(function*(\n workspaceId: typeof WorkspaceId.Type,\n threadKind: typeof AgentJobTaskTag.Type,\n subjectKey: string\n ) {\n const rows = yield* sql<Record<string, unknown>>`SELECT\n thread_id AS threadId, thread_kind AS threadKind,\n subject_key AS subjectKey, release_id AS releaseId\n FROM agent_threads\n WHERE workspace_id = ${workspaceId}\n AND thread_kind = ${threadKind}\n AND subject_key = ${subjectKey}`\n if (rows.length === 0) return Option.none<typeof ThreadRow.Type>()\n const decoded = Schema.decodeUnknownResult(ThreadRow)(rows[0])\n if (Result.isFailure(decoded)) {\n return yield* persistedRecordError(workspaceId, \"agent-thread\", subjectKey, \"agent-thread-schema-invalid\")\n }\n return Option.some(decoded.success)\n })\n\n const reviewThreadSubjectKey = Effect.fn(\"AgentJobRepository.reviewThreadSubjectKey\")(function*(\n pluginConnectionId: typeof PluginConnectionId.Type,\n subject: typeof PrReviewThreadSubject.Type\n ) {\n return yield* Schema.encodeUnknownEffect(\n Schema.fromJsonString(PrReviewThreadIdentity)\n )({\n pluginConnectionId,\n providerId: subject.providerId,\n repository: subject.repository,\n pullRequestId: subject.pullRequestId\n }).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"agent-job.review-thread-subject-key\" }))\n )\n })\n\n const getJob = Effect.fn(\"AgentJobRepository.getJob\")(function*(\n workspaceId: typeof WorkspaceId.Type,\n jobId: typeof JobId.Type\n ) {\n const rows = yield* sql<Record<string, unknown>>`SELECT\n workspace_id AS workspaceId, job_id AS jobId, thread_id AS threadId,\n release_id AS releaseId, provider_id AS providerId, model, access, prompt,\n context_fingerprint AS contextFingerprint, subject_revision AS subjectRevision,\n task_context_json AS taskContextJson, task_context_digest AS taskContextDigest,\n state, created_at AS createdAt, cancel_requested_at AS cancelRequestedAt,\n terminal_at AS terminalAt\n FROM agent_jobs\n WHERE workspace_id = ${workspaceId} AND job_id = ${jobId}`\n if (rows.length === 0) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"agent-job\",\n recordKey: jobId\n })\n }\n const decoded = Schema.decodeUnknownResult(JobRow)(rows[0])\n if (Result.isFailure(decoded)) {\n return yield* persistedRecordError(workspaceId, \"agent-job\", jobId, \"agent-job-schema-invalid\")\n }\n return {\n ...decoded.success,\n task: yield* decodeTaskContext(\n workspaceId,\n jobId,\n decoded.success.taskContextJson,\n decoded.success.taskContextDigest\n )\n }\n })\n\n const validateLease = Effect.fn(\"AgentJobRepository.validateLease\")(function*(options: {\n readonly workspaceId: typeof WorkspaceId.Type\n readonly jobId: typeof JobId.Type\n readonly attemptSequence: typeof AgentAttemptSequence.Type\n readonly leaseToken: typeof AgentLeaseToken.Type\n readonly observedAt: typeof UtcTimestamp.Type\n }) {\n const currentTime = yield* DateTime.now\n const leaseRows = yield* sql<Record<string, unknown>>`SELECT\n lease.lease_token AS leaseToken, lease.lease_expires_at AS leaseExpiresAt\n FROM agent_job_leases lease\n WHERE lease.workspace_id = ${options.workspaceId}\n AND lease.job_id = ${options.jobId}\n AND lease.attempt_sequence = ${options.attemptSequence}\n AND NOT EXISTS (\n SELECT 1 FROM agent_job_attempts newer\n WHERE newer.workspace_id = lease.workspace_id\n AND newer.job_id = lease.job_id\n AND newer.attempt_sequence > lease.attempt_sequence\n )`\n const lease = Schema.decodeUnknownResult(LeaseRow)(leaseRows[0])\n if (Result.isFailure(lease) || lease.success.leaseToken !== options.leaseToken) {\n return yield* new AgentJobInputError({\n workspaceId: options.workspaceId,\n jobId: options.jobId,\n reason: \"lease-lost\"\n })\n }\n const attemptRows = yield* sql<Record<string, unknown>>`SELECT\n started_at AS startedAt, completed_at AS completedAt\n FROM agent_job_attempts\n WHERE workspace_id = ${options.workspaceId}\n AND job_id = ${options.jobId}\n AND attempt_sequence = ${options.attemptSequence}`\n const attempt = Schema.decodeUnknownResult(ActiveAttemptRow)(attemptRows[0])\n if (Result.isFailure(attempt) || attempt.success.completedAt !== null) {\n return yield* new AgentJobInputError({\n workspaceId: options.workspaceId,\n jobId: options.jobId,\n reason: \"invalid-transition\"\n })\n }\n if (\n DateTime.Order(currentTime, lease.success.leaseExpiresAt) >= 0 ||\n DateTime.Order(options.observedAt, lease.success.leaseExpiresAt) >= 0\n ) {\n return yield* new AgentJobInputError({\n workspaceId: options.workspaceId,\n jobId: options.jobId,\n reason: \"lease-expired\"\n })\n }\n if (DateTime.Order(attempt.success.startedAt, options.observedAt) > 0) {\n return yield* new AgentJobInputError({\n workspaceId: options.workspaceId,\n jobId: options.jobId,\n reason: \"invalid-transition\"\n })\n }\n })\n\n const completeAttempt = Effect.fn(\"AgentJobRepository.completeAttempt\")(function*(options: {\n readonly workspaceId: typeof WorkspaceId.Type\n readonly jobId: typeof JobId.Type\n readonly attemptSequence: typeof AgentAttemptSequence.Type\n readonly completedAt: typeof UtcTimestamp.Type\n readonly outcome: \"success\" | \"failed\" | \"cancelled\" | \"max-steps\"\n readonly state: \"succeeded\" | \"failed\" | \"cancelled\"\n readonly sessionRef: null | typeof ClaimedAgentJob.fields.sessionRef.Type\n readonly errorJson: null | string\n }) {\n yield* sql`UPDATE agent_job_attempts\n SET completed_at = ${encodeTimestamp(options.completedAt)},\n outcome = ${options.outcome},\n session_ref = COALESCE(${options.sessionRef}, session_ref),\n error_json = ${options.errorJson}\n WHERE workspace_id = ${options.workspaceId}\n AND job_id = ${options.jobId}\n AND attempt_sequence = ${options.attemptSequence}\n AND completed_at IS NULL`\n if ((yield* readChanges(sql)) !== 1) {\n return yield* new AgentJobInputError({\n workspaceId: options.workspaceId,\n jobId: options.jobId,\n reason: \"invalid-transition\"\n })\n }\n yield* sql`UPDATE agent_jobs\n SET state = ${options.state}, terminal_at = ${encodeTimestamp(options.completedAt)}\n WHERE workspace_id = ${options.workspaceId}\n AND job_id = ${options.jobId}\n AND state IN ('running', 'cancel-requested')\n AND terminal_at IS NULL`\n if ((yield* readChanges(sql)) !== 1) {\n return yield* new AgentJobInputError({\n workspaceId: options.workspaceId,\n jobId: options.jobId,\n reason: \"invalid-transition\"\n })\n }\n yield* sql`DELETE FROM agent_job_leases\n WHERE workspace_id = ${options.workspaceId}\n AND job_id = ${options.jobId}`\n })\n\n const decodeRuntimePayload = Effect.fn(\"AgentJobRepository.decodeRuntimePayload\")(function*(\n workspaceId: typeof WorkspaceId.Type,\n row: typeof ThreadEventRow.Type,\n parsed: unknown\n ) {\n const decoded = Schema.decodeUnknownResult(AgentRuntimeEvent)(parsed)\n if (Result.isFailure(decoded)) {\n return yield* persistedRecordError(\n workspaceId,\n \"agent-thread-event\",\n `${row.threadId}/${row.eventSequence}`,\n \"agent-thread-event-payload-invalid\"\n )\n }\n const event = decoded.success\n const matches = row.eventKind === \"job-started\"\n ? event._tag === \"started\"\n : row.eventKind === \"assistant-output\"\n ? event._tag === \"output\" && event.channel === \"assistant\"\n : row.eventKind === \"progress\"\n ? event._tag === \"output\" && event.channel === \"progress\"\n : row.eventKind === \"usage\"\n ? event._tag === \"usage\"\n : row.eventKind === \"job-completed\" && event._tag === \"completed\"\n if (!matches) {\n return yield* persistedRecordError(\n workspaceId,\n \"agent-thread-event\",\n `${row.threadId}/${row.eventSequence}`,\n \"agent-thread-event-kind-mismatch\"\n )\n }\n return event\n })\n\n const decodeEventPayload = Effect.fn(\"AgentJobRepository.decodeEventPayload\")(function*(\n workspaceId: typeof WorkspaceId.Type,\n row: typeof ThreadEventRow.Type\n ) {\n const bytes = yield* bytesFromText(row.payloadJson)\n const actualDigest = yield* digestBytes(bytes)\n if (bytes.length !== row.payloadByteLength || actualDigest !== row.payloadDigest) {\n return yield* persistedRecordError(\n workspaceId,\n \"agent-thread-event\",\n `${row.threadId}/${row.eventSequence}`,\n \"agent-thread-event-integrity-invalid\"\n )\n }\n const parsed = Schema.decodeUnknownResult(Schema.UnknownFromJsonString)(row.payloadJson)\n if (Result.isFailure(parsed)) {\n return yield* persistedRecordError(\n workspaceId,\n \"agent-thread-event\",\n `${row.threadId}/${row.eventSequence}`,\n \"agent-thread-event-json-invalid\"\n )\n }\n const payload = parsed.success\n switch (row.eventKind) {\n case \"user-message\":\n return yield* Schema.decodeUnknownEffect(UserMessagePayload)(payload).pipe(\n Effect.mapError(() =>\n persistedRecordError(\n workspaceId,\n \"agent-thread-event\",\n `${row.threadId}/${row.eventSequence}`,\n \"agent-thread-event-payload-invalid\"\n )\n )\n )\n case \"job-queued\":\n return yield* Schema.decodeUnknownEffect(JobQueuedPayload)(payload).pipe(\n Effect.mapError(() =>\n persistedRecordError(\n workspaceId,\n \"agent-thread-event\",\n `${row.threadId}/${row.eventSequence}`,\n \"agent-thread-event-payload-invalid\"\n )\n )\n )\n case \"cancel-requested\":\n return yield* Schema.decodeUnknownEffect(CancellationRequestedPayload)(payload).pipe(\n Effect.mapError(() =>\n persistedRecordError(\n workspaceId,\n \"agent-thread-event\",\n `${row.threadId}/${row.eventSequence}`,\n \"agent-thread-event-payload-invalid\"\n )\n )\n )\n case \"job-failed\":\n return yield* Schema.decodeUnknownEffect(ProviderFailurePayload)(payload).pipe(\n Effect.mapError(() =>\n persistedRecordError(\n workspaceId,\n \"agent-thread-event\",\n `${row.threadId}/${row.eventSequence}`,\n \"agent-thread-event-payload-invalid\"\n )\n )\n )\n case \"review-report\":\n return yield* Schema.decodeUnknownEffect(PrReviewReport)(payload).pipe(\n Effect.mapError(() =>\n persistedRecordError(\n workspaceId,\n \"agent-thread-event\",\n `${row.threadId}/${row.eventSequence}`,\n \"agent-thread-event-payload-invalid\"\n )\n )\n )\n case \"review-suggestion-revised\":\n return yield* Schema.decodeUnknownEffect(\n ReviewSuggestionRevisedPayload\n )(payload).pipe(\n Effect.mapError(() =>\n persistedRecordError(\n workspaceId,\n \"agent-thread-event\",\n `${row.threadId}/${row.eventSequence}`,\n \"agent-thread-event-payload-invalid\"\n )\n )\n )\n case \"review-suggestion-published\":\n return yield* Schema.decodeUnknownEffect(ReviewSuggestionPublishedPayload)(payload).pipe(\n Effect.mapError(() =>\n persistedRecordError(\n workspaceId,\n \"agent-thread-event\",\n `${row.threadId}/${row.eventSequence}`,\n \"agent-thread-event-payload-invalid\"\n )\n )\n )\n case \"job-started\":\n case \"assistant-output\":\n case \"progress\":\n case \"usage\":\n case \"job-completed\":\n return yield* decodeRuntimePayload(workspaceId, row, payload)\n }\n })\n\n const reviewBudgetState = Effect.fn(\"AgentJobRepository.reviewBudgetState\")(function*(\n workspaceId: typeof WorkspaceId.Type,\n jobId: typeof JobId.Type,\n task: typeof AgentJobTask.Type\n ) {\n if (task._tag !== \"pr-review\") {\n return { reviewBudgetMillis: undefined, reviewBudgetExtensionCount: 0 }\n }\n const rows = yield* sql<Record<string, unknown>>`SELECT\n workspace_id AS workspaceId, thread_id AS threadId,\n event_sequence AS eventSequence, job_id AS jobId,\n attempt_sequence AS attemptSequence, event_kind AS eventKind,\n payload_json AS payloadJson, payload_digest AS payloadDigest,\n payload_byte_length AS payloadByteLength, occurred_at AS occurredAt\n FROM agent_thread_events\n WHERE workspace_id = ${workspaceId}\n AND job_id = ${jobId}\n AND event_kind = 'job-queued'\n ORDER BY event_sequence`.pipe(mapPersistenceOperation(\"agent-job.review-budget\"))\n let reviewBudgetMillis = task.reviewProfile.budgetMillis\n let reviewBudgetExtensionCount = 0\n for (const unknownRow of rows) {\n const row = Schema.decodeUnknownResult(ThreadEventRow)(unknownRow)\n if (Result.isFailure(row)) {\n return yield* persistedRecordError(\n workspaceId,\n \"agent-review-budget\",\n jobId,\n \"agent-review-budget-event-schema-invalid\"\n )\n }\n const bytes = yield* bytesFromText(row.success.payloadJson)\n const actualDigest = yield* digestBytes(bytes)\n if (bytes.length !== row.success.payloadByteLength || actualDigest !== row.success.payloadDigest) {\n return yield* persistedRecordError(\n workspaceId,\n \"agent-review-budget\",\n jobId,\n \"agent-review-budget-event-integrity-invalid\"\n )\n }\n const parsed = Schema.decodeUnknownResult(Schema.UnknownFromJsonString)(row.success.payloadJson)\n if (Result.isFailure(parsed)) {\n return yield* persistedRecordError(\n workspaceId,\n \"agent-review-budget\",\n jobId,\n \"agent-review-budget-event-json-invalid\"\n )\n }\n const decoded = Schema.decodeUnknownResult(PersistedJobQueuedPayload)(parsed.success)\n if (Result.isFailure(decoded)) {\n const legacy = Schema.decodeUnknownResult(JobQueuedPayload)(parsed.success)\n if (Result.isFailure(legacy)) {\n return yield* persistedRecordError(\n workspaceId,\n \"agent-review-budget\",\n jobId,\n \"agent-review-budget-event-invalid\"\n )\n }\n continue\n }\n if (decoded.success.task._tag !== \"pr-review\") continue\n if (decoded.success.reviewBudgetMillis !== undefined) {\n reviewBudgetMillis = decoded.success.reviewBudgetMillis\n reviewBudgetExtensionCount = decoded.success.reviewBudgetExtensionCount ?? 1\n }\n }\n return { reviewBudgetMillis, reviewBudgetExtensionCount }\n })\n\n const reviewContextSnapshot = Effect.fn(\"AgentJobRepository.reviewContextSnapshot\")(function*(\n workspaceId: typeof WorkspaceId.Type,\n threadId: typeof AgentThreadId.Type\n ) {\n const rendered = renderAgentReviewContextEventsQuery({\n workspaceId,\n threadId,\n eventKinds: [\"user-message\", \"review-report\", \"job-completed\", \"job-failed\", \"cancel-requested\"],\n limit: REVIEW_CONTEXT_EVENT_LIMIT + 1\n })\n const unknownRows = yield* sql\n .unsafe<Record<string, unknown>>(rendered.sql, [...rendered.params])\n .pipe(mapPersistenceOperation(\"agent-job.review-context\"))\n const decodedRows = Schema.decodeUnknownResult(\n Schema.Array(ReviewContextThreadEventRow)\n )(unknownRows.slice(0, REVIEW_CONTEXT_EVENT_LIMIT))\n if (Result.isFailure(decodedRows)) {\n return yield* persistedRecordError(\n workspaceId,\n \"agent-thread\",\n threadId,\n \"agent-review-context-schema-invalid\"\n )\n }\n\n type RunDraft = {\n readonly jobId: typeof JobId.Type\n readonly subject: typeof PrReviewSubject.Type\n readonly requestedAt: typeof UtcTimestamp.Type\n readonly state: \"cancelled\" | \"failed\" | \"interrupted\" | \"succeeded\" | \"unknown\"\n readonly report: null | typeof PrReviewReport.Type\n }\n\n const requests = new Array<{\n readonly jobId: typeof JobId.Type\n readonly prompt: typeof AgentJobPrompt.Type\n readonly subjectRevision: string\n readonly requestedAt: typeof UtcTimestamp.Type\n }>()\n const runs = new Map<typeof JobId.Type, RunDraft>()\n const tasks = new Map<typeof JobId.Type, typeof AgentJobTask.Type>()\n for (const row of [...decodedRows.success].reverse()) {\n const cachedTask = tasks.get(row.jobId)\n const task = cachedTask ?? (yield* decodeTaskContext(\n workspaceId,\n row.jobId,\n row.taskContextJson,\n row.taskContextDigest\n ))\n if (cachedTask === undefined) tasks.set(row.jobId, task)\n if (task._tag !== \"pr-review\") continue\n const current: RunDraft = runs.get(row.jobId) ?? {\n jobId: row.jobId,\n subject: task.subject,\n requestedAt: row.occurredAt,\n state: \"unknown\",\n report: null\n }\n const payload = yield* decodeEventPayload(workspaceId, row)\n switch (row.eventKind) {\n case \"user-message\": {\n const message = yield* Schema.decodeUnknownEffect(UserMessagePayload)(payload).pipe(\n Effect.mapError(() =>\n persistedRecordError(\n workspaceId,\n \"agent-thread-event\",\n `${row.threadId}/${row.eventSequence}`,\n \"agent-review-context-message-invalid\"\n )\n )\n )\n requests.push({\n jobId: row.jobId,\n prompt: message.prompt,\n subjectRevision: task.subject.headRevision,\n requestedAt: row.occurredAt\n })\n runs.set(row.jobId, { ...current, requestedAt: row.occurredAt })\n break\n }\n case \"review-report\": {\n const report = yield* Schema.decodeUnknownEffect(PrReviewReport)(payload).pipe(\n Effect.mapError(() =>\n persistedRecordError(\n workspaceId,\n \"agent-thread-event\",\n `${row.threadId}/${row.eventSequence}`,\n \"agent-review-context-report-invalid\"\n )\n )\n )\n runs.set(row.jobId, { ...current, report, state: \"succeeded\" })\n break\n }\n case \"job-completed\": {\n const runtimeEvent = yield* Schema.decodeUnknownEffect(AgentRuntimeEvent)(payload).pipe(\n Effect.mapError(() =>\n persistedRecordError(\n workspaceId,\n \"agent-thread-event\",\n `${row.threadId}/${row.eventSequence}`,\n \"agent-review-context-outcome-invalid\"\n )\n )\n )\n if (runtimeEvent._tag !== \"completed\") {\n return yield* persistedRecordError(\n workspaceId,\n \"agent-thread-event\",\n `${row.threadId}/${row.eventSequence}`,\n \"agent-review-context-outcome-invalid\"\n )\n }\n runs.set(row.jobId, {\n ...current,\n state: runtimeEvent.outcome === \"cancelled\" ? \"cancelled\" : \"succeeded\"\n })\n break\n }\n case \"job-failed\": {\n const failure = yield* Schema.decodeUnknownEffect(ProviderFailurePayload)(payload)\n runs.set(row.jobId, {\n ...current,\n state: failure.error.message === PROCESS_RESTART_INTERRUPTION_MESSAGE ? \"interrupted\" : \"failed\"\n })\n break\n }\n case \"cancel-requested\":\n if (row.jobState === \"cancelled\") {\n runs.set(row.jobId, { ...current, state: \"cancelled\" })\n }\n break\n default:\n break\n }\n }\n\n const allRuns = Array.from(runs.values())\n const selectedRuns = allRuns.slice(-REVIEW_CONTEXT_ITEM_LIMIT)\n const recentRequests = requests.slice(-REVIEW_CONTEXT_ITEM_LIMIT)\n const boundedText = (value: string, maximum: number): string => value.slice(0, maximum).trim()\n return yield* Schema.decodeUnknownEffect(Schema.toType(PrReviewThreadContextSnapshot))({\n recentRequests,\n priorRuns: selectedRuns.map(({ jobId, report, requestedAt, state, subject }) => ({\n jobId,\n subject,\n requestedAt,\n state,\n suggestionTitles: report?.suggestions\n .slice(0, REVIEW_CONTEXT_REPORT_ITEM_LIMIT)\n .map(({ title }) => boundedText(title, 500)) ?? [],\n suggestionsTruncated: (report?.suggestions.length ?? 0) > REVIEW_CONTEXT_REPORT_ITEM_LIMIT,\n noteTitles: report?.notes\n .slice(0, REVIEW_CONTEXT_REPORT_ITEM_LIMIT)\n .map(({ title }) => boundedText(title, 500)) ?? [],\n notesTruncated: (report?.notes.length ?? 0) > REVIEW_CONTEXT_REPORT_ITEM_LIMIT,\n limitation: report?.completion.status === \"unable-to-conclude\"\n ? boundedText(report.completion.reason, 1_000)\n : null\n })),\n historyTruncated: unknownRows.length > REVIEW_CONTEXT_EVENT_LIMIT ||\n requests.length > REVIEW_CONTEXT_ITEM_LIMIT ||\n allRuns.length > REVIEW_CONTEXT_ITEM_LIMIT\n })\n })\n\n const fitPrReviewTask = Effect.fn(\"AgentJobRepository.fitPrReviewTask\")(function*(\n request: typeof EnqueueAgentJobInput.Type,\n snapshot: typeof PrReviewThreadContextSnapshot.Type\n ) {\n if (request.task._tag !== \"pr-review\") {\n return yield* new PersistenceOperationError({\n operation: \"agent-job.fit-review-task-mismatch\"\n })\n }\n let context = snapshot\n while (true) {\n const task = yield* Schema.decodeUnknownEffect(Schema.toType(AgentJobTask))({\n ...request.task,\n context\n }).pipe(\n Effect.mapError(() =>\n new PersistenceOperationError({\n operation: \"agent-job.encode-payload\"\n })\n )\n )\n const taskContext = yield* Effect.result(encodePayload(AgentJobTask, task))\n const queuedPayload = yield* Effect.result(encodePayload(PersistedJobQueuedPayload, {\n access: request.access,\n contextFingerprint: request.contextFingerprint,\n model: request.model,\n providerId: request.providerId,\n subjectRevision: request.subjectRevision,\n task\n }))\n const attemptContext = yield* Schema.decodeUnknownEffect(\n Schema.toType(AgentContextSnapshotRecord)\n )({\n workspaceId: request.workspaceId,\n releaseId: request.releaseId,\n subjectRevision: request.subjectRevision,\n fingerprint: request.contextFingerprint,\n task\n }).pipe(\n Effect.mapError(() =>\n new PersistenceOperationError({\n operation: \"agent-job.encode-payload\"\n })\n )\n )\n const attemptContextPayload = yield* Effect.result(\n encodePayload(AgentContextSnapshotRecord, attemptContext)\n )\n if (\n Result.isSuccess(taskContext) &&\n Result.isSuccess(queuedPayload) &&\n Result.isSuccess(attemptContextPayload)\n ) {\n return { task, taskContext: taskContext.success }\n }\n const failure = Result.isFailure(taskContext)\n ? taskContext.failure\n : Result.isFailure(queuedPayload)\n ? queuedPayload.failure\n : Result.isFailure(attemptContextPayload)\n ? attemptContextPayload.failure\n : null\n if (failure === null || failure.operation !== \"agent-job.event-too-large\") {\n return yield* (failure ?? new PersistenceOperationError({\n operation: \"agent-job.fit-review-task\"\n }))\n }\n if (context.priorRuns.length > 0) {\n context = PrReviewThreadContextSnapshot.make({\n ...context,\n priorRuns: context.priorRuns.slice(1),\n historyTruncated: true\n })\n continue\n }\n if (context.recentRequests.length > 0) {\n context = PrReviewThreadContextSnapshot.make({\n ...context,\n recentRequests: context.recentRequests.slice(1),\n historyTruncated: true\n })\n continue\n }\n return yield* failure\n }\n })\n\n const readReviewResult = Effect.fnUntraced(function*(\n input: typeof AgentReviewResultInput.Type\n ) {\n const request = yield* Schema.decodeUnknownEffect(Schema.toType(AgentReviewResultInput))(input)\n const rows = yield* sql<Record<string, unknown>>`SELECT\n workspace_id AS workspaceId, thread_id AS threadId,\n event_sequence AS eventSequence, job_id AS jobId,\n attempt_sequence AS attemptSequence, event_kind AS eventKind,\n payload_json AS payloadJson, payload_digest AS payloadDigest,\n payload_byte_length AS payloadByteLength, occurred_at AS occurredAt\n FROM agent_thread_events\n WHERE workspace_id = ${request.workspaceId}\n AND job_id = ${request.jobId}\n AND event_kind = 'review-report'\n ORDER BY event_sequence DESC\n LIMIT 1`.pipe(mapPersistenceOperation(\"agent-job.review-result\"))\n if (rows.length === 0) {\n return yield* new RecordNotFoundError({\n workspaceId: request.workspaceId,\n recordKind: \"agent-review-result\",\n recordKey: request.jobId\n })\n }\n const row = Schema.decodeUnknownResult(ThreadEventRow)(rows[0])\n if (Result.isFailure(row) || row.success.attemptSequence === null) {\n return yield* persistedRecordError(\n request.workspaceId,\n \"agent-review-result\",\n request.jobId,\n \"agent-review-result-schema-invalid\"\n )\n }\n const report = yield* decodeEventPayload(request.workspaceId, row.success)\n const decodedReport = Schema.decodeUnknownResult(PrReviewReport)(report)\n if (Result.isFailure(decodedReport)) {\n return yield* persistedRecordError(\n request.workspaceId,\n \"agent-review-result\",\n request.jobId,\n \"agent-review-result-payload-invalid\"\n )\n }\n const publicationRows = yield* sql<Record<string, unknown>>`SELECT\n workspace_id AS workspaceId, thread_id AS threadId,\n event_sequence AS eventSequence, job_id AS jobId,\n attempt_sequence AS attemptSequence, event_kind AS eventKind,\n payload_json AS payloadJson, payload_digest AS payloadDigest,\n payload_byte_length AS payloadByteLength, occurred_at AS occurredAt\n FROM agent_thread_events\n WHERE workspace_id = ${request.workspaceId}\n AND job_id = ${request.jobId}\n AND event_kind = 'review-suggestion-published'\n ORDER BY event_sequence`.pipe(\n mapPersistenceOperation(\"agent-job.review-suggestion-publications\")\n )\n const publishedSuggestionIds = new Set<string>()\n for (const unknownPublicationRow of publicationRows) {\n const publicationRow = Schema.decodeUnknownResult(ThreadEventRow)(unknownPublicationRow)\n if (Result.isFailure(publicationRow)) {\n return yield* persistedRecordError(\n request.workspaceId,\n \"agent-review-result\",\n request.jobId,\n \"agent-review-publication-schema-invalid\"\n )\n }\n const publication = yield* decodeEventPayload(request.workspaceId, publicationRow.success)\n const decodedPublication = Schema.decodeUnknownResult(\n ReviewSuggestionPublishedPayload\n )(publication)\n if (Result.isFailure(decodedPublication)) {\n return yield* persistedRecordError(\n request.workspaceId,\n \"agent-review-result\",\n request.jobId,\n \"agent-review-publication-payload-invalid\"\n )\n }\n publishedSuggestionIds.add(decodedPublication.success.suggestionId)\n }\n const lifecycleRows = yield* sql<Record<string, unknown>>`SELECT\n revision.suggestion_id AS suggestionId,\n revision.revision_json AS revisionJson,\n revision.revision_digest AS revisionDigest\n FROM agent_review_suggestion_revisions revision\n WHERE revision.workspace_id = ${request.workspaceId}\n AND revision.source_job_id = ${request.jobId}\n AND NOT EXISTS (\n SELECT 1\n FROM agent_review_suggestion_revisions newer\n WHERE newer.workspace_id = revision.workspace_id\n AND newer.source_job_id = revision.source_job_id\n AND newer.suggestion_id = revision.suggestion_id\n AND newer.revision_sequence > revision.revision_sequence\n )`.pipe(\n mapPersistenceOperation(\"agent-job.review-suggestion-lifecycle-revisions\")\n )\n const dismissedSuggestionIds = new Set<string>()\n for (const unknownLifecycleRow of lifecycleRows) {\n const lifecycleRow = Schema.decodeUnknownResult(\n ReviewSuggestionLifecycleRevisionRow\n )(unknownLifecycleRow)\n if (Result.isFailure(lifecycleRow)) {\n return yield* persistedRecordError(\n request.workspaceId,\n \"agent-review-result\",\n request.jobId,\n \"agent-review-lifecycle-revision-schema-invalid\"\n )\n }\n const bytes = yield* bytesFromText(lifecycleRow.success.revisionJson)\n if ((yield* digestBytes(bytes)) !== lifecycleRow.success.revisionDigest) {\n return yield* persistedRecordError(\n request.workspaceId,\n \"agent-review-result\",\n request.jobId,\n \"agent-review-lifecycle-revision-integrity-invalid\"\n )\n }\n const revision = Schema.decodeUnknownResult(\n Schema.fromJsonString(PrReviewSuggestionRevision)\n )(lifecycleRow.success.revisionJson)\n if (\n Result.isFailure(revision) ||\n revision.success.sourceJobId !== request.jobId ||\n revision.success.suggestion.suggestionId !== lifecycleRow.success.suggestionId\n ) {\n return yield* persistedRecordError(\n request.workspaceId,\n \"agent-review-result\",\n request.jobId,\n \"agent-review-lifecycle-revision-payload-invalid\"\n )\n }\n if (revision.success.suggestion.state === \"dismissed\") {\n dismissedSuggestionIds.add(lifecycleRow.success.suggestionId)\n }\n }\n if (publishedSuggestionIds.size === 0 && dismissedSuggestionIds.size === 0) {\n return yield* Schema.decodeUnknownEffect(Schema.toType(AgentReviewResultRecord))({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n attemptSequence: row.success.attemptSequence,\n report: decodedReport.success,\n completedAt: row.success.occurredAt\n })\n }\n const projectedReport = yield* Schema.decodeUnknownEffect(Schema.toType(PrReviewReport))({\n ...decodedReport.success,\n suggestions: decodedReport.success.suggestions.map((suggestion) => {\n const state = publishedSuggestionIds.has(suggestion.suggestionId)\n ? \"published\"\n : dismissedSuggestionIds.has(suggestion.suggestionId)\n ? \"dismissed\"\n : suggestion.state\n return state === suggestion.state ? suggestion : { ...suggestion, state }\n })\n }).pipe(\n Effect.mapError(() =>\n persistedRecordError(\n request.workspaceId,\n \"agent-review-result\",\n request.jobId,\n \"agent-review-lifecycle-projection-invalid\"\n )\n )\n )\n return yield* Schema.decodeUnknownEffect(Schema.toType(AgentReviewResultRecord))({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n attemptSequence: row.success.attemptSequence,\n report: projectedReport,\n completedAt: row.success.occurredAt\n })\n }, Effect.withTracerEnabled(false))\n\n const readOriginalReviewResult = Effect.fn(\n \"AgentJobRepository.readOriginalReviewResult\"\n )(function*(input: typeof AgentReviewResultInput.Type) {\n const request = yield* Schema.decodeUnknownEffect(\n Schema.toType(AgentReviewResultInput)\n )(input)\n const rows = yield* sql<Record<string, unknown>>`SELECT\n workspace_id AS workspaceId, thread_id AS threadId,\n event_sequence AS eventSequence, job_id AS jobId,\n attempt_sequence AS attemptSequence, event_kind AS eventKind,\n payload_json AS payloadJson, payload_digest AS payloadDigest,\n payload_byte_length AS payloadByteLength, occurred_at AS occurredAt\n FROM agent_thread_events\n WHERE workspace_id = ${request.workspaceId}\n AND job_id = ${request.jobId}\n AND event_kind = 'review-report'\n ORDER BY event_sequence ASC\n LIMIT 1`.pipe(\n mapPersistenceOperation(\"agent-job.original-review-result\")\n )\n if (rows.length === 0) {\n return yield* new RecordNotFoundError({\n workspaceId: request.workspaceId,\n recordKind: \"agent-review-result\",\n recordKey: request.jobId\n })\n }\n const row = Schema.decodeUnknownResult(ThreadEventRow)(rows[0])\n if (\n Result.isFailure(row) ||\n row.success.attemptSequence === null\n ) {\n return yield* persistedRecordError(\n request.workspaceId,\n \"agent-review-result\",\n request.jobId,\n \"agent-review-original-result-schema-invalid\"\n )\n }\n const report = Schema.decodeUnknownResult(\n PrReviewReport\n )(yield* decodeEventPayload(request.workspaceId, row.success))\n if (Result.isFailure(report)) {\n return yield* persistedRecordError(\n request.workspaceId,\n \"agent-review-result\",\n request.jobId,\n \"agent-review-original-result-payload-invalid\"\n )\n }\n return yield* Schema.decodeUnknownEffect(\n Schema.toType(AgentReviewResultRecord)\n )({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n attemptSequence: row.success.attemptSequence,\n report: report.success,\n completedAt: row.success.occurredAt\n })\n })\n\n const findPreviousReviewReport = Effect.fn(\"AgentJobRepository.findPreviousReviewReport\")(function*(input: {\n readonly workspaceId: typeof WorkspaceId.Type\n readonly pluginConnectionId: typeof PluginConnectionId.Type\n readonly subject: typeof PrReviewSubject.Type\n readonly excludeJobId: typeof JobId.Type\n }) {\n const subjectJson = yield* Schema.encodeUnknownEffect(Schema.fromJsonString(PrReviewSubject))(input.subject).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"agent-job.previous-review-subject\" }))\n )\n const taskContextPrefix =\n `{\"_tag\":\"pr-review\",\"pluginConnectionId\":\"${input.pluginConnectionId}\",\"subject\":${subjectJson},\"reviewProfile\":`\n const identityPrefix = taskContextPrefix.slice(0, taskContextPrefix.indexOf(\"\\\"baseRevision\\\"\"))\n const rendered = renderLatestAgentReviewQuery({\n workspaceId: input.workspaceId,\n taskContextPrefix: identityPrefix,\n excludeTargeted: true,\n excludeJobId: input.excludeJobId,\n excludeSubjectRevision: input.subject.headRevision,\n limit: 32\n })\n const rows = yield* sql\n .unsafe<Record<string, unknown>>(rendered.sql, [...rendered.params])\n .pipe(mapPersistenceOperation(\"agent-job.previous-review\"))\n for (const rawRow of rows) {\n const row = Schema.decodeUnknownResult(LatestReviewRow)(rawRow)\n if (Result.isFailure(row)) {\n return yield* persistedRecordError(\n input.workspaceId,\n \"agent-review\",\n input.subject.pullRequestId,\n \"agent-review-previous-schema-invalid\"\n )\n }\n if (row.success.state !== \"succeeded\" && row.success.state !== \"failed\" && row.success.state !== \"cancelled\") {\n continue\n }\n const result = yield* readReviewResult({ workspaceId: input.workspaceId, jobId: row.success.jobId }).pipe(\n Effect.catchTag(\"RecordNotFoundError\", () => Effect.succeed(null))\n )\n if (result !== null && result.report !== null) {\n return Option.some({ jobId: row.success.jobId, report: result.report })\n }\n }\n return Option.none<{ readonly jobId: typeof JobId.Type; readonly report: typeof PrReviewReport.Type }>()\n })\n\n const decodeThreadEventRows = Effect.fn(\"AgentJobRepository.decodeThreadEventRows\")(function*(\n workspaceId: typeof WorkspaceId.Type,\n threadId: typeof AgentThreadId.Type,\n rows: ReadonlyArray<Record<string, unknown>>\n ) {\n const decodedRows = yield* Schema.decodeUnknownEffect(\n Schema.Array(ReplayThreadEventRow)\n )(rows).pipe(\n Effect.mapError(() =>\n persistedRecordError(\n workspaceId,\n \"agent-thread\",\n threadId,\n \"agent-thread-event-schema-invalid\"\n )\n )\n )\n const tasksByJob = new Map<typeof JobId.Type, typeof AgentJobTask.Type>()\n return yield* Effect.forEach(\n decodedRows,\n (row) =>\n Effect.gen(function*() {\n const payload = yield* decodeEventPayload(workspaceId, row)\n let task = tasksByJob.get(row.jobId)\n if (task === undefined) {\n task = yield* decodeTaskContext(\n workspaceId,\n row.jobId,\n row.taskContextJson,\n row.taskContextDigest\n )\n tasksByJob.set(row.jobId, task)\n }\n const presentedTask = task._tag === \"release-chat\"\n ? task\n : {\n _tag: task._tag,\n pluginConnectionId: task.pluginConnectionId,\n subject: task.subject,\n reviewProfile: task.reviewProfile\n }\n return yield* Schema.decodeUnknownEffect(Schema.toType(AgentThreadEvent))({\n workspaceId: row.workspaceId,\n threadId: row.threadId,\n eventSequence: row.eventSequence,\n jobId: row.jobId,\n attemptSequence: row.attemptSequence,\n task: presentedTask,\n eventKind: row.eventKind,\n payload,\n occurredAt: row.occurredAt\n })\n })\n )\n })\n\n const threadEventsAfter = Effect.fn(\"AgentJobRepository.threadEventsAfter\")(function*(\n workspaceId: typeof WorkspaceId.Type,\n threadId: typeof AgentThreadId.Type,\n after: typeof AgentEventCursor.Type,\n limit: typeof AgentThreadEventPageSize.Type\n ) {\n const replay = renderAgentThreadReplayQuery({\n workspaceId,\n threadId,\n afterSequence: after,\n limit\n })\n const rows = yield* sql\n .unsafe<Record<string, unknown>>(replay.sql, [...replay.params])\n .pipe(mapPersistenceOperation(\"agent-job.thread-after\"))\n const events = yield* decodeThreadEventRows(workspaceId, threadId, rows)\n return {\n events,\n nextCursor: events.at(-1)?.eventSequence ?? after\n }\n })\n\n const threadEventsBefore = Effect.fn(\"AgentJobRepository.threadEventsBefore\")(function*(\n workspaceId: typeof WorkspaceId.Type,\n threadId: typeof AgentThreadId.Type,\n before: typeof AgentEventCursor.Type,\n limit: typeof AgentThreadEventPageSize.Type\n ) {\n const history = renderAgentThreadBeforeQuery({\n workspaceId,\n threadId,\n beforeSequence: before,\n limit\n })\n const rows = yield* sql\n .unsafe<Record<string, unknown>>(history.sql, [...history.params])\n .pipe(mapPersistenceOperation(\"agent-job.thread-before\"))\n const events = yield* decodeThreadEventRows(\n workspaceId,\n threadId,\n [...rows].reverse()\n )\n return {\n events,\n nextCursor: events[0]?.eventSequence ?? before\n }\n })\n\n const threadEventsTail = Effect.fn(\"AgentJobRepository.threadEventsTail\")(function*(\n workspaceId: typeof WorkspaceId.Type,\n threadId: typeof AgentThreadId.Type,\n limit: typeof AgentThreadEventPageSize.Type\n ) {\n const tail = renderAgentThreadTailQuery({\n workspaceId,\n threadId,\n limit\n })\n const rows = yield* sql\n .unsafe<Record<string, unknown>>(tail.sql, [...tail.params])\n .pipe(mapPersistenceOperation(\"agent-job.thread-tail\"))\n const events = yield* decodeThreadEventRows(\n workspaceId,\n threadId,\n [...rows].reverse()\n )\n return {\n events,\n nextCursor: events.at(-1)?.eventSequence ?? AgentEventCursor.make(0)\n }\n })\n\n const reviewSuggestionRevisions = makeReviewSuggestionRevisionOperations({\n database,\n bytesFromText,\n digestBytes,\n readReviewResult: readOriginalReviewResult,\n getJob,\n appendThreadEvent: (options) => appendThreadEvent(options)\n })\n\n const currentPublishableReviewSuggestion = Effect.fn(\n \"AgentJobRepository.currentPublishableReviewSuggestion\"\n )(function*(input: {\n readonly workspaceId: typeof WorkspaceId.Type\n readonly jobId: typeof JobId.Type\n readonly suggestionId: typeof RecordReviewSuggestionPublicationInput.fields.suggestionId.Type\n readonly revisionId: typeof RecordReviewSuggestionPublicationInput.fields.revisionId.Type\n }) {\n const current = (yield* reviewSuggestionRevisions.read({\n workspaceId: input.workspaceId,\n jobId: input.jobId,\n suggestionId: input.suggestionId,\n beforeSequence: null,\n limit: PrReviewSuggestionRevisionPageSize.make(1)\n })).current\n if (\n current.revisionId !== input.revisionId ||\n current.suggestion.state !== \"draft\" ||\n current.validation._tag !== \"validated\"\n ) {\n return yield* new AgentJobInputError({\n workspaceId: input.workspaceId,\n jobId: input.jobId,\n reason: \"invalid-transition\"\n })\n }\n return current\n })\n\n const currentPublishedReviewSuggestion = Effect.fn(\n \"AgentJobRepository.currentPublishedReviewSuggestion\"\n )(function*(input: {\n readonly workspaceId: typeof WorkspaceId.Type\n readonly jobId: typeof JobId.Type\n readonly suggestionId: typeof RecordReviewSuggestionPublicationInput.fields.suggestionId.Type\n readonly revisionId: typeof RecordReviewSuggestionPublicationInput.fields.revisionId.Type\n }) {\n const current = (yield* reviewSuggestionRevisions.read({\n workspaceId: input.workspaceId,\n jobId: input.jobId,\n suggestionId: input.suggestionId,\n beforeSequence: null,\n limit: PrReviewSuggestionRevisionPageSize.make(1)\n })).current\n if (\n current.revisionId !== input.revisionId ||\n current.suggestion.state !== \"published\" ||\n current.validation._tag !== \"validated\"\n ) {\n return yield* new AgentJobInputError({\n workspaceId: input.workspaceId,\n jobId: input.jobId,\n reason: \"invalid-transition\"\n })\n }\n return current\n })\n\n return {\n appendReviewSuggestionRevision: Effect.fn(\n \"AgentJobRepository.appendReviewSuggestionRevision\"\n )(function*(input: typeof AppendReviewSuggestionRevisionInput.Type) {\n return yield* reviewSuggestionRevisions.append(input).pipe(\n mapPersistenceOperation(\"agent-job.append-review-suggestion-revision\")\n )\n }),\n\n completeTargetedReview: Effect.fn(\n \"AgentJobRepository.completeTargetedReview\"\n )(function*(input: typeof CompleteTargetedReviewInput.Type) {\n const request = yield* Schema.decodeUnknownEffect(\n Schema.toType(CompleteTargetedReviewInput)\n )(input)\n const report = yield* Schema.decodeUnknownEffect(Schema.toType(PrReviewReport))(request.target.report).pipe(\n Effect.mapError(() =>\n new AgentJobInputError({\n workspaceId: request.target.workspaceId,\n jobId: request.target.jobId,\n reason: \"invalid-result\"\n })\n )\n )\n const encodedReport = yield* encodeReviewReport(report).pipe(\n Effect.mapError(() =>\n new AgentJobInputError({\n workspaceId: request.target.workspaceId,\n jobId: request.target.jobId,\n reason: \"invalid-result\"\n })\n )\n )\n return yield* database.transaction(\n Effect.gen(function*() {\n const job = yield* getJob(request.target.workspaceId, request.target.jobId)\n if (job.state === \"cancel-requested\") {\n return yield* new AgentJobInputError({\n workspaceId: request.target.workspaceId,\n jobId: request.target.jobId,\n reason: \"cancellation-requested\"\n })\n }\n if (\n job.state !== \"running\" ||\n job.task._tag !== \"pr-review\" ||\n job.subjectRevision !== job.task.subject.headRevision ||\n !PrReviewSubjectEquivalence(job.task.subject, report.subject)\n ) {\n return yield* new AgentJobInputError({\n workspaceId: request.target.workspaceId,\n jobId: request.target.jobId,\n reason: \"task-mismatch\"\n })\n }\n yield* validateLease({\n workspaceId: request.target.workspaceId,\n jobId: request.target.jobId,\n attemptSequence: request.target.attemptSequence,\n leaseToken: request.target.leaseToken,\n observedAt: request.target.completedAt\n })\n const revision = yield* reviewSuggestionRevisions.appendInTransaction(request.source)\n const eventSequence = yield* reserveEventSequence(\n request.target.workspaceId,\n job.threadId\n )\n yield* sql`INSERT INTO agent_thread_events (\n workspace_id, thread_id, event_sequence, job_id, attempt_sequence,\n event_kind, payload_json, payload_digest, payload_byte_length, occurred_at\n ) VALUES (\n ${request.target.workspaceId}, ${job.threadId}, ${eventSequence},\n ${request.target.jobId}, ${request.target.attemptSequence}, 'review-report',\n ${encodedReport.json}, ${encodedReport.digest}, ${encodedReport.bytes.length},\n ${encodeTimestamp(request.target.completedAt)}\n )`\n yield* appendThreadEvent({\n workspaceId: request.target.workspaceId,\n threadId: job.threadId,\n jobId: request.target.jobId,\n attemptSequence: request.target.attemptSequence,\n eventKind: \"job-completed\",\n payload: { _tag: \"completed\", outcome: \"success\", sessionRef: null },\n payloadSchema: AgentRuntimeEvent,\n occurredAt: request.target.completedAt\n })\n yield* completeAttempt({\n workspaceId: request.target.workspaceId,\n jobId: request.target.jobId,\n attemptSequence: request.target.attemptSequence,\n completedAt: request.target.completedAt,\n outcome: \"success\",\n state: \"succeeded\",\n sessionRef: null,\n errorJson: null\n })\n return revision\n })\n ).pipe(mapPersistenceOperation(\"agent-job.complete-targeted-review\"))\n }),\n\n enqueue: Effect.fn(\"AgentJobRepository.enqueue\")(function*(input: typeof EnqueueAgentJobInput.Type) {\n const request = yield* Schema.decodeUnknownEffect(Schema.toType(EnqueueAgentJobInput))(input)\n if (\n request.task._tag === \"pr-review\" &&\n (request.access !== \"read-only\" || request.subjectRevision !== request.task.subject.headRevision)\n ) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"task-mismatch\"\n })\n }\n const candidateThreadId = yield* cryptoService.randomUUIDv7.pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(AgentThreadId)),\n Effect.mapError(() => new PersistenceOperationError({ operation: \"agent-job.thread-id\" }))\n )\n const threadKind = request.task._tag\n const subjectKey = request.task._tag === \"release-chat\"\n ? request.releaseId\n : yield* reviewThreadSubjectKey(\n request.task.pluginConnectionId,\n request.task.subject\n )\n return yield* database\n .transaction(\n Effect.gen(function*() {\n const releaseRows = yield* sql`SELECT release_id FROM releases\n WHERE workspace_id = ${request.workspaceId} AND release_id = ${request.releaseId}`\n if (releaseRows.length === 0) {\n return yield* new RecordNotFoundError({\n workspaceId: request.workspaceId,\n recordKind: \"release\",\n recordKey: request.releaseId\n })\n }\n yield* sql`INSERT INTO agent_threads (\n workspace_id, thread_id, thread_kind, subject_key, release_id,\n next_event_sequence, created_at\n ) VALUES (\n ${request.workspaceId}, ${candidateThreadId}, ${threadKind}, ${subjectKey},\n ${request.releaseId}, 1,\n ${encodeTimestamp(request.createdAt)}\n ) ON CONFLICT (workspace_id, thread_kind, subject_key) DO NOTHING`\n const thread = yield* findThread(request.workspaceId, threadKind, subjectKey)\n if (Option.isNone(thread)) {\n return yield* new PersistenceOperationError({ operation: \"agent-job.find-thread\" })\n }\n const fitted = request.task._tag === \"release-chat\"\n ? {\n task: request.task,\n taskContext: yield* encodePayload(AgentJobTask, request.task)\n }\n : yield* fitPrReviewTask(\n request,\n yield* reviewContextSnapshot(\n request.workspaceId,\n thread.value.threadId\n )\n )\n const { task, taskContext } = fitted\n yield* sql`INSERT INTO agent_jobs (\n workspace_id, job_id, thread_id, release_id, provider_id, model, access, prompt,\n context_fingerprint, subject_revision, task_context_json, task_context_digest, state, created_at,\n cancel_requested_at, terminal_at\n ) VALUES (\n ${request.workspaceId}, ${request.jobId}, ${thread.value.threadId},\n ${request.releaseId}, ${request.providerId}, ${request.model},\n ${request.access}, ${request.prompt},\n ${request.contextFingerprint}, ${request.subjectRevision}, ${taskContext.json}, ${taskContext.digest}, 'queued',\n ${encodeTimestamp(request.createdAt)}, NULL, NULL\n )`\n yield* appendThreadEvent({\n workspaceId: request.workspaceId,\n threadId: thread.value.threadId,\n jobId: request.jobId,\n attemptSequence: null,\n eventKind: \"user-message\",\n payload: { prompt: request.userPrompt },\n payloadSchema: UserMessagePayload,\n occurredAt: request.createdAt\n })\n yield* appendThreadEvent({\n workspaceId: request.workspaceId,\n threadId: thread.value.threadId,\n jobId: request.jobId,\n attemptSequence: null,\n eventKind: \"job-queued\",\n payload: {\n access: request.access,\n contextFingerprint: request.contextFingerprint,\n model: request.model,\n providerId: request.providerId,\n subjectRevision: request.subjectRevision,\n task\n },\n payloadSchema: PersistedJobQueuedPayload,\n occurredAt: request.createdAt\n })\n return thread.value.threadId\n })\n )\n .pipe(\n mapAlreadyExists({\n workspaceId: request.workspaceId,\n recordKind: \"agent-job\",\n recordKey: request.jobId\n }),\n mapPersistenceOperation(\"agent-job.enqueue\")\n )\n }),\n\n claimNext: Effect.fn(\"AgentJobRepository.claimNext\")(function*(input: typeof ClaimAgentJobInput.Type) {\n const request = yield* Schema.decodeUnknownEffect(Schema.toType(ClaimAgentJobInput))(input)\n return yield* database\n .transaction(\n Effect.gen(function*() {\n const claimedAt = yield* DateTime.now\n const observedAt = encodeTimestamp(claimedAt)\n const dispatch = renderAgentJobDispatchCandidatesQuery({\n workspaceId: request.workspaceId,\n observedAt,\n taskTags: request.taskTags,\n limit: DISPATCH_CANDIDATE_LIMIT\n })\n const candidateRows = yield* sql.unsafe<Record<string, unknown>>(dispatch.sql, [...dispatch.params])\n const candidates = Schema.decodeUnknownResult(Schema.Array(DispatchCandidateRow))(candidateRows)\n if (Result.isFailure(candidates)) {\n return yield* persistedRecordError(\n request.workspaceId,\n \"agent-job\",\n request.workspaceId,\n \"agent-job-dispatch-schema-invalid\"\n )\n }\n for (const candidate of candidates.success) {\n const task = yield* decodeTaskContext(\n request.workspaceId,\n candidate.jobId,\n candidate.taskContextJson,\n candidate.taskContextDigest\n )\n if (!request.taskTags.includes(task._tag)) continue\n if (DateTime.Order(claimedAt, request.leaseExpiresAt) >= 0) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: candidate.jobId,\n reason: \"invalid-transition\"\n })\n }\n const claim = renderAgentJobClaimQuery({\n workspaceId: request.workspaceId,\n jobId: candidate.jobId,\n expectedAttemptSequence: candidate.attemptSequence,\n expectedState: candidate.state satisfies ClaimableAgentJobState,\n observedAt\n })\n const claimedRows = yield* sql.unsafe<Record<string, unknown>>(claim.sql, [...claim.params])\n if (claimedRows.length === 0) continue\n const claimed = Schema.decodeUnknownResult(JobRow)(claimedRows[0])\n if (Result.isFailure(claimed)) {\n return yield* persistedRecordError(\n request.workspaceId,\n \"agent-job\",\n candidate.jobId,\n \"agent-job-schema-invalid\"\n )\n }\n const context = yield* Schema.decodeUnknownEffect(Schema.toType(AgentContextSnapshotRecord))({\n workspaceId: request.workspaceId,\n releaseId: claimed.success.releaseId,\n subjectRevision: claimed.success.subjectRevision,\n fingerprint: claimed.success.contextFingerprint,\n task\n })\n const reviewBudget = yield* reviewBudgetState(\n request.workspaceId,\n candidate.jobId,\n task\n )\n const contextPayload = yield* encodePayload(AgentContextSnapshotRecord, context)\n let sessionRef: null | typeof ClaimedAgentJob.fields.sessionRef.Type = null\n if (candidate.attemptSequence > 0) {\n const previousRows = yield* sql<Record<string, unknown>>`SELECT\n context_snapshot_json AS contextSnapshotJson,\n context_snapshot_digest AS contextSnapshotDigest,\n session_ref AS sessionRef\n FROM agent_job_attempts\n WHERE workspace_id = ${request.workspaceId}\n AND job_id = ${candidate.jobId}\n AND attempt_sequence = ${candidate.attemptSequence}`\n const previous = Schema.decodeUnknownResult(PreviousAttemptRow)(previousRows[0])\n const previousContext = Result.isSuccess(previous)\n ? Schema.decodeUnknownResult(Schema.fromJsonString(AgentContextSnapshotRecord))(\n previous.success.contextSnapshotJson\n )\n : null\n if (\n Result.isFailure(previous) ||\n previousContext === null ||\n Result.isFailure(previousContext) ||\n previous.success.contextSnapshotDigest !== contextPayload.digest ||\n previous.success.contextSnapshotJson !== contextPayload.json\n ) {\n return yield* persistedRecordError(\n request.workspaceId,\n \"agent-job-attempt\",\n `${candidate.jobId}/${candidate.attemptSequence}`,\n \"agent-job-context-invalid\"\n )\n }\n sessionRef = previous.success.sessionRef\n }\n const attemptSequence = yield* Schema.decodeUnknownEffect(AgentAttemptSequence)(\n candidate.attemptSequence + 1\n )\n yield* sql`INSERT INTO agent_job_attempts (\n workspace_id, job_id, attempt_sequence, context_snapshot_json,\n context_snapshot_digest, output_bytes, provider_run_ref, session_ref,\n started_at, completed_at, outcome, error_json\n ) VALUES (\n ${request.workspaceId}, ${candidate.jobId}, ${attemptSequence},\n ${contextPayload.json}, ${contextPayload.digest}, 0, NULL, ${sessionRef},\n ${observedAt}, NULL, NULL, NULL\n )`\n yield* sql`INSERT INTO agent_job_leases (\n workspace_id, job_id, attempt_sequence, lease_owner, lease_token,\n acquired_at, last_renewed_at, lease_expires_at\n ) VALUES (\n ${request.workspaceId}, ${candidate.jobId}, ${attemptSequence},\n ${request.leaseOwner}, ${request.leaseToken}, ${observedAt}, ${observedAt},\n ${encodeTimestamp(request.leaseExpiresAt)}\n )`\n const claimedJob = yield* Schema.decodeUnknownEffect(Schema.toType(ClaimedAgentJob))({\n workspaceId: request.workspaceId,\n releaseId: claimed.success.releaseId,\n threadId: claimed.success.threadId,\n jobId: candidate.jobId,\n attemptSequence,\n leaseOwner: request.leaseOwner,\n leaseToken: request.leaseToken,\n leaseExpiresAt: request.leaseExpiresAt,\n providerId: claimed.success.providerId,\n model: claimed.success.model,\n access: claimed.success.access,\n prompt: claimed.success.prompt,\n context,\n ...(reviewBudget.reviewBudgetMillis === undefined\n ? {}\n : { reviewBudgetMillis: reviewBudget.reviewBudgetMillis }),\n reviewBudgetExtensionCount: reviewBudget.reviewBudgetExtensionCount,\n sessionRef,\n cancellationRequested: claimed.success.state === \"cancel-requested\"\n })\n return Option.some(claimedJob)\n }\n return Option.none<typeof ClaimedAgentJob.Type>()\n })\n )\n .pipe(mapPersistenceOperation(\"agent-job.claim-next\"))\n }),\n\n isLeaseActive: Effect.fn(\"AgentJobRepository.isLeaseActive\")((\n workspaceId: typeof WorkspaceId.Type,\n jobId: typeof JobId.Type\n ) =>\n Effect.gen(function*() {\n const observedAt = encodeTimestamp(yield* DateTime.now)\n const rows = yield* sql<Record<string, unknown>>`SELECT COUNT(*) AS active\n FROM agent_jobs job\n JOIN agent_job_leases lease\n ON lease.workspace_id = job.workspace_id\n AND lease.job_id = job.job_id\n WHERE job.workspace_id = ${workspaceId}\n AND job.job_id = ${jobId}\n AND job.state IN ('running', 'cancel-requested')\n AND lease.lease_expires_at > ${observedAt}\n AND lease.attempt_sequence = (\n SELECT MAX(latest.attempt_sequence)\n FROM agent_job_leases latest\n WHERE latest.workspace_id = job.workspace_id\n AND latest.job_id = job.job_id\n )`\n const decoded = Schema.decodeUnknownResult(Schema.Array(ActiveLeaseRow))(rows)\n if (Result.isFailure(decoded) || decoded.success.length !== 1) {\n return yield* persistedRecordError(\n workspaceId,\n \"agent-job\",\n jobId,\n \"agent-job-active-lease-schema-invalid\"\n )\n }\n return decoded.success[0]?.active === 1\n }).pipe(mapPersistenceOperation(\"agent-job.is-lease-active\"))\n ),\n\n heartbeat: Effect.fn(\"AgentJobRepository.heartbeat\")(function*(\n input: typeof HeartbeatAgentJobInput.Type\n ) {\n const request = yield* Schema.decodeUnknownEffect(Schema.toType(HeartbeatAgentJobInput))(input)\n return yield* database.transaction(\n Effect.gen(function*() {\n const renewedAt = yield* DateTime.now\n if (DateTime.Order(renewedAt, request.leaseExpiresAt) >= 0) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-transition\"\n })\n }\n const job = yield* getJob(request.workspaceId, request.jobId)\n if (job.state !== \"running\" && job.state !== \"cancel-requested\") {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-transition\"\n })\n }\n yield* validateLease({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n attemptSequence: request.attemptSequence,\n leaseToken: request.leaseToken,\n observedAt: renewedAt\n })\n yield* sql`UPDATE agent_job_leases\n SET last_renewed_at = ${encodeTimestamp(renewedAt)},\n lease_expires_at = ${encodeTimestamp(request.leaseExpiresAt)}\n WHERE workspace_id = ${request.workspaceId}\n AND job_id = ${request.jobId}\n AND attempt_sequence = ${request.attemptSequence}\n AND lease_token = ${request.leaseToken}`\n if ((yield* readChanges(sql)) !== 1) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"lease-lost\"\n })\n }\n return job.state === \"cancel-requested\"\n })\n ).pipe(mapPersistenceOperation(\"agent-job.heartbeat\"))\n }),\n\n appendEvent: Effect.fn(\"AgentJobRepository.appendEvent\")(function*(input: typeof AppendAgentEventInput.Type) {\n const request = yield* Schema.decodeUnknownEffect(Schema.toType(AppendAgentEventInput))(input)\n return yield* database\n .transaction(\n Effect.gen(function*() {\n const job = yield* getJob(request.workspaceId, request.jobId)\n if (job.state !== \"running\" && job.state !== \"cancel-requested\") {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-transition\"\n })\n }\n if (\n job.state === \"cancel-requested\" &&\n request.event._tag === \"completed\" &&\n request.event.outcome !== \"cancelled\"\n ) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"cancellation-requested\"\n })\n }\n yield* validateLease({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n attemptSequence: request.attemptSequence,\n leaseToken: request.leaseToken,\n observedAt: request.occurredAt\n })\n const allowedReviewActivity = request.event._tag === \"started\" ||\n request.event._tag === \"usage\" ||\n (request.event._tag === \"output\" && request.event.channel === \"progress\") ||\n (\n job.state === \"cancel-requested\" &&\n request.event._tag === \"completed\" &&\n request.event.outcome === \"cancelled\"\n )\n if (job.task._tag === \"pr-review\" && !allowedReviewActivity) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-transition\"\n })\n }\n let eventKind: EventKind\n switch (request.event._tag) {\n case \"started\":\n eventKind = \"job-started\"\n yield* sql`UPDATE agent_job_attempts\n SET provider_run_ref = ${request.event.providerRunRef},\n session_ref = COALESCE(${request.event.sessionRef}, session_ref)\n WHERE workspace_id = ${request.workspaceId}\n AND job_id = ${request.jobId}\n AND attempt_sequence = ${request.attemptSequence}\n AND completed_at IS NULL`\n break\n case \"output\": {\n eventKind = request.event.channel === \"assistant\" ? \"assistant-output\" : \"progress\"\n const outputBytes = yield* bytesFromText(request.event.text)\n yield* sql`UPDATE agent_job_attempts\n SET output_bytes = output_bytes + ${outputBytes.length}\n WHERE workspace_id = ${request.workspaceId}\n AND job_id = ${request.jobId}\n AND attempt_sequence = ${request.attemptSequence}\n AND completed_at IS NULL\n AND output_bytes + ${outputBytes.length} <= ${MAXIMUM_AGENT_ATTEMPT_OUTPUT_BYTES}`\n if ((yield* readChanges(sql)) !== 1) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"output-limit-exceeded\"\n })\n }\n break\n }\n case \"usage\":\n eventKind = \"usage\"\n break\n case \"completed\":\n eventKind = \"job-completed\"\n break\n }\n const persistedEvent = yield* appendThreadEvent({\n workspaceId: request.workspaceId,\n threadId: job.threadId,\n jobId: request.jobId,\n attemptSequence: request.attemptSequence,\n eventKind,\n payload: request.event,\n payloadSchema: AgentRuntimeEvent,\n occurredAt: request.occurredAt\n })\n if (request.event._tag === \"completed\") {\n const state = request.event.outcome === \"success\"\n ? \"succeeded\"\n : request.event.outcome === \"cancelled\"\n ? \"cancelled\"\n : \"failed\"\n yield* completeAttempt({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n attemptSequence: request.attemptSequence,\n completedAt: request.occurredAt,\n outcome: request.event.outcome,\n state,\n sessionRef: request.event.sessionRef,\n errorJson: null\n })\n }\n return persistedEvent\n })\n )\n .pipe(mapPersistenceOperation(\"agent-job.append-event\"))\n }),\n\n recordReviewProgress: Effect.fnUntraced(function*(\n input: typeof RecordAgentReviewProgressInput.Type\n ) {\n const request = yield* Schema.decodeUnknownEffect(Schema.toType(RecordAgentReviewProgressInput))(input)\n const agentReport = yield* Schema.decodeUnknownEffect(Schema.toType(PrReviewReport))(request.report).pipe(\n Effect.mapError(\n () =>\n new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-result\"\n })\n )\n )\n if (!agentReport.suggestions.every(({ state }) => isAgentOwnedSuggestionState(state))) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-result\"\n })\n }\n const report = sanitizeAgentReviewReport(agentReport)\n return yield* database.transaction(\n Effect.gen(function*() {\n const job = yield* getJob(request.workspaceId, request.jobId)\n if (\n job.state !== \"running\" &&\n job.state !== \"cancel-requested\" ||\n job.task._tag !== \"pr-review\" ||\n !PrReviewSubjectEquivalence(job.task.subject, report.subject)\n ) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"task-mismatch\"\n })\n }\n yield* validateLease({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n attemptSequence: request.attemptSequence,\n leaseToken: request.leaseToken,\n observedAt: request.occurredAt\n })\n yield* appendThreadEvent({\n workspaceId: request.workspaceId,\n threadId: job.threadId,\n jobId: request.jobId,\n attemptSequence: request.attemptSequence,\n eventKind: \"review-report\",\n payload: report,\n payloadSchema: PrReviewReport,\n occurredAt: request.occurredAt\n })\n return yield* Schema.decodeUnknownEffect(Schema.toType(AgentReviewResultRecord))({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n attemptSequence: request.attemptSequence,\n report,\n completedAt: request.occurredAt\n })\n })\n ).pipe(mapPersistenceOperation(\"agent-job.record-review-progress\"))\n }, Effect.withTracerEnabled(false)),\n\n completeReview: Effect.fnUntraced(function*(\n input: typeof CompleteAgentReviewInput.Type\n ) {\n const request = yield* Schema.decodeUnknownEffect(Schema.toType(CompleteAgentReviewInput))(input)\n const agentReport = yield* Schema.decodeUnknownEffect(Schema.toType(PrReviewReport))(request.report).pipe(\n Effect.mapError(\n () =>\n new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-result\"\n })\n )\n )\n if (!agentReport.suggestions.every(({ state }) => isAgentOwnedSuggestionState(state))) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-result\"\n })\n }\n return yield* database\n .transaction(\n Effect.gen(function*() {\n const job = yield* getJob(request.workspaceId, request.jobId)\n if (job.state === \"cancel-requested\") {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"cancellation-requested\"\n })\n }\n if (\n job.state !== \"running\" ||\n job.task._tag !== \"pr-review\" ||\n job.subjectRevision !== job.task.subject.headRevision ||\n !PrReviewSubjectEquivalence(job.task.subject, agentReport.subject)\n ) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"task-mismatch\"\n })\n }\n const previous = yield* findPreviousReviewReport({\n workspaceId: request.workspaceId,\n pluginConnectionId: job.task.pluginConnectionId,\n subject: job.task.subject,\n excludeJobId: request.jobId\n })\n const previousReport = Option.isSome(previous)\n ? previous.value.report\n : PrReviewReport.make({ ...agentReport, suggestions: [], transitions: [] })\n if (Option.isSome(previous)) {\n for (const suggestion of previous.value.report.suggestions) {\n if (\n suggestion.state !== \"draft\" && suggestion.state !== \"published\" && suggestion.state !== \"reopened\"\n ) {\n continue\n }\n const currentRevision = yield* reviewSuggestionRevisions.read({\n workspaceId: request.workspaceId,\n jobId: previous.value.jobId,\n suggestionId: suggestion.suggestionId,\n beforeSequence: null,\n limit: PrReviewSuggestionRevisionPageSize.make(1)\n })\n if (\n currentRevision.current.suggestion.state !== \"draft\" &&\n currentRevision.current.suggestion.state !== \"published\"\n ) {\n continue\n }\n yield* reviewSuggestionRevisions.appendInTransaction({\n workspaceId: request.workspaceId,\n jobId: previous.value.jobId,\n suggestionId: suggestion.suggestionId,\n expectedRevisionId: currentRevision.current.revisionId,\n expectedSequence: currentRevision.current.sequence,\n edit: Schema.decodeUnknownSync(PrReviewSuggestionEdit)(currentRevision.current.suggestion),\n state: \"stale\",\n author: PrReviewSuggestionAgentAuthor.make({\n jobId: request.jobId,\n providerId: job.providerId,\n model: job.model,\n runtimeMetadata: null\n }),\n createdAt: request.completedAt\n })\n }\n }\n const expectedTransitions = reconcilePrReviewReports(previousReport, agentReport)\n if (agentReport.transitions !== undefined) {\n const validation = validatePrReviewReportTransitions(\n previousReport,\n agentReport,\n agentReport.transitions\n )\n if (validation._tag === \"failure\") {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-result\"\n })\n }\n }\n const report = PrReviewReport.make({ ...agentReport, transitions: expectedTransitions })\n const encodedReport = yield* encodeReviewReport(report).pipe(\n Effect.mapError(\n () =>\n new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-result\"\n })\n )\n )\n yield* validateLease({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n attemptSequence: request.attemptSequence,\n leaseToken: request.leaseToken,\n observedAt: request.completedAt\n })\n const eventSequence = yield* reserveEventSequence(request.workspaceId, job.threadId)\n yield* sql`INSERT INTO agent_thread_events (\n workspace_id, thread_id, event_sequence, job_id, attempt_sequence,\n event_kind, payload_json, payload_digest, payload_byte_length, occurred_at\n ) VALUES (\n ${request.workspaceId}, ${job.threadId}, ${eventSequence}, ${request.jobId},\n ${request.attemptSequence}, 'review-report', ${encodedReport.json},\n ${encodedReport.digest}, ${encodedReport.bytes.length},\n ${encodeTimestamp(request.completedAt)}\n )`\n yield* appendThreadEvent({\n workspaceId: request.workspaceId,\n threadId: job.threadId,\n jobId: request.jobId,\n attemptSequence: request.attemptSequence,\n eventKind: \"job-completed\",\n payload: { _tag: \"completed\", outcome: \"success\", sessionRef: null },\n payloadSchema: AgentRuntimeEvent,\n occurredAt: request.completedAt\n })\n yield* completeAttempt({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n attemptSequence: request.attemptSequence,\n completedAt: request.completedAt,\n outcome: \"success\",\n state: \"succeeded\",\n sessionRef: null,\n errorJson: null\n })\n return yield* Schema.decodeUnknownEffect(Schema.toType(AgentReviewResultRecord))({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n attemptSequence: request.attemptSequence,\n report,\n completedAt: request.completedAt\n })\n })\n )\n .pipe(mapPersistenceOperation(\"agent-job.complete-review\"))\n }, Effect.withTracerEnabled(false)),\n\n readReviewSuggestionPublication: Effect.fn(\n \"AgentJobRepository.readReviewSuggestionPublication\"\n )(function*(input: typeof ReadReviewSuggestionPublicationInput.Type) {\n const request = yield* Schema.decodeUnknownEffect(\n Schema.toType(ReadReviewSuggestionPublicationInput)\n )(input)\n const rows = yield* sql<Record<string, unknown>>`SELECT\n revision_id AS revisionId, content_digest AS contentDigest, state,\n publication_id AS publicationId, comment_id AS commentId,\n previous_content_digest AS previousContentDigest,\n previous_publication_id AS previousPublicationId,\n previous_published_at AS previousPublishedAt,\n reservation_id AS reservationId,\n reservation_acquired_at AS reservationAcquiredAt, reserved_at AS reservedAt,\n published_at AS publishedAt\n FROM agent_review_suggestion_publications\n WHERE workspace_id = ${request.workspaceId}\n AND job_id = ${request.jobId}\n AND suggestion_id = ${request.suggestionId}\n AND revision_id = ${request.revisionId}`\n if (rows.length === 0) return null\n const decoded = Schema.decodeUnknownResult(ReviewSuggestionPublicationRow)(rows[0])\n if (Result.isFailure(decoded)) {\n return yield* persistedRecordError(\n request.workspaceId,\n \"agent-review-suggestion-publication\",\n `${request.jobId}:${request.suggestionId}:${request.revisionId}`,\n \"agent-review-suggestion-publication-schema-invalid\"\n )\n }\n const row = decoded.success\n if (row.state !== \"published\" || row.publicationId === null || row.commentId === null) return null\n return yield* Schema.decodeUnknownEffect(ReadReviewSuggestionPublication)({\n state: row.state,\n publicationId: row.publicationId,\n commentId: row.commentId\n })\n }),\n\n reserveReviewSuggestionPublication: Effect.fn(\n \"AgentJobRepository.reserveReviewSuggestionPublication\"\n )(function*(input: typeof ReserveReviewSuggestionPublicationInput.Type) {\n const request = yield* Schema.decodeUnknownEffect(\n Schema.toType(ReserveReviewSuggestionPublicationInput)\n )(input)\n return yield* database.transaction(\n Effect.gen(function*() {\n const operation = request.operation ?? \"create\"\n const existingRows = yield* sql<Record<string, unknown>>`SELECT\n revision_id AS revisionId, content_digest AS contentDigest, state,\n publication_id AS publicationId, comment_id AS commentId,\n previous_content_digest AS previousContentDigest,\n previous_publication_id AS previousPublicationId,\n previous_published_at AS previousPublishedAt, reservation_id AS reservationId,\n reservation_acquired_at AS reservationAcquiredAt, reserved_at AS reservedAt,\n published_at AS publishedAt\n FROM agent_review_suggestion_publications\n WHERE workspace_id = ${request.workspaceId}\n AND job_id = ${request.jobId}\n AND suggestion_id = ${request.suggestionId}\n AND revision_id = ${request.revisionId}`\n if (existingRows.length > 0) {\n const existing = yield* Schema.decodeUnknownEffect(\n ReviewSuggestionPublicationRow\n )(existingRows[0])\n if (existing.contentDigest !== request.contentDigest) {\n if (\n operation !== \"create\" &&\n existing.state === \"published\" &&\n existing.publicationId !== null &&\n existing.publishedAt !== null &&\n existing.commentId !== null &&\n existing.commentId === request.commentId\n ) {\n yield* currentPublishedReviewSuggestion(request)\n yield* sql`UPDATE agent_review_suggestion_publications\n SET content_digest = ${request.contentDigest},\n state = 'reserved',\n publication_id = NULL,\n previous_content_digest = ${existing.contentDigest},\n previous_publication_id = ${existing.publicationId},\n previous_published_at = ${encodeTimestamp(existing.publishedAt)},\n reservation_id = ${request.reservationId},\n reservation_acquired_at = ${encodeTimestamp(request.reservedAt)},\n published_at = NULL\n WHERE workspace_id = ${request.workspaceId}\n AND job_id = ${request.jobId}\n AND suggestion_id = ${request.suggestionId}\n AND revision_id = ${request.revisionId}\n AND state = 'published'\n AND content_digest = ${existing.contentDigest}\n AND comment_id = ${request.commentId}`\n return ReviewSuggestionPublicationReservation.make({\n _tag: (yield* readChanges(sql)) === 1 ? \"acquired\" : \"in-progress\",\n commentId: existing.commentId\n })\n }\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-transition\"\n })\n }\n return existing.state === \"published\" &&\n existing.publicationId !== null &&\n existing.publishedAt !== null\n ? ReviewSuggestionPublicationReservation.make({\n _tag: \"published\",\n publicationId: existing.publicationId,\n publishedAt: existing.publishedAt,\n ...(existing.commentId === null ? {} : { commentId: existing.commentId })\n })\n : existing.publicationId !== null && existing.publishedAt !== null\n ? ReviewSuggestionPublicationReservation.make({\n _tag: \"recoverable\",\n publicationId: existing.publicationId,\n publishedAt: existing.publishedAt,\n reservationId: existing.reservationId,\n ...(existing.commentId === null ? {} : { commentId: existing.commentId })\n })\n : yield* Effect.gen(function*() {\n const recoveryEligibleAt = DateTime.add(existing.reservationAcquiredAt, {\n minutes: REVIEW_SUGGESTION_PUBLICATION_RESERVATION_LIFETIME_MINUTES\n })\n if (DateTime.Order(request.reservedAt, recoveryEligibleAt) < 0) {\n return ReviewSuggestionPublicationReservation.make({\n _tag: \"in-progress\",\n ...(existing.commentId === null ? {} : { commentId: existing.commentId })\n })\n }\n yield* sql`UPDATE agent_review_suggestion_publications\n SET reservation_id = ${request.reservationId},\n reservation_acquired_at = ${encodeTimestamp(request.reservedAt)}\n WHERE workspace_id = ${request.workspaceId}\n AND job_id = ${request.jobId}\n AND suggestion_id = ${request.suggestionId}\n AND revision_id = ${request.revisionId}\n AND content_digest = ${request.contentDigest}\n AND state = 'reserved'\n AND publication_id IS NULL\n AND reservation_id = ${existing.reservationId}\n AND reservation_acquired_at = ${encodeTimestamp(existing.reservationAcquiredAt)}`\n return ReviewSuggestionPublicationReservation.make({\n _tag: (yield* readChanges(sql)) === 1 ? \"acquired\" : \"in-progress\",\n ...(existing.commentId === null ? {} : { commentId: existing.commentId })\n })\n })\n }\n if (operation !== \"create\") {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-transition\"\n })\n }\n yield* currentPublishableReviewSuggestion(request)\n const inserted = yield* sql<Record<string, unknown>>`INSERT INTO agent_review_suggestion_publications (\n workspace_id, job_id, suggestion_id, revision_id, content_digest, state,\n publication_id, comment_id, reservation_id, reservation_acquired_at,\n reserved_at, published_at, previous_content_digest,\n previous_publication_id, previous_published_at\n ) VALUES (\n ${request.workspaceId}, ${request.jobId}, ${request.suggestionId},\n ${request.revisionId}, ${request.contentDigest}, 'reserved', NULL,\n NULL,\n ${request.reservationId}, ${encodeTimestamp(request.reservedAt)},\n ${encodeTimestamp(request.reservedAt)}, NULL, NULL, NULL, NULL\n ) ON CONFLICT DO NOTHING\n RETURNING suggestion_id AS suggestionId`\n const rows = yield* sql<Record<string, unknown>>`SELECT\n revision_id AS revisionId, content_digest AS contentDigest, state,\n publication_id AS publicationId, comment_id AS commentId,\n previous_content_digest AS previousContentDigest,\n previous_publication_id AS previousPublicationId,\n previous_published_at AS previousPublishedAt, reservation_id AS reservationId,\n reservation_acquired_at AS reservationAcquiredAt, reserved_at AS reservedAt,\n published_at AS publishedAt\n FROM agent_review_suggestion_publications\n WHERE workspace_id = ${request.workspaceId}\n AND job_id = ${request.jobId}\n AND suggestion_id = ${request.suggestionId}\n AND revision_id = ${request.revisionId}`\n const row = Schema.decodeUnknownResult(ReviewSuggestionPublicationRow)(rows[0])\n if (\n rows.length !== 1 ||\n Result.isFailure(row) ||\n row.success.revisionId !== request.revisionId ||\n row.success.contentDigest !== request.contentDigest\n ) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-transition\"\n })\n }\n return row.success.state === \"published\" &&\n row.success.publicationId !== null &&\n row.success.publishedAt !== null\n ? ReviewSuggestionPublicationReservation.make({\n _tag: \"published\",\n publicationId: row.success.publicationId,\n publishedAt: row.success.publishedAt,\n ...(row.success.commentId === null ? {} : { commentId: row.success.commentId })\n })\n : row.success.publicationId !== null && row.success.publishedAt !== null\n ? ReviewSuggestionPublicationReservation.make({\n _tag: \"recoverable\",\n publicationId: row.success.publicationId,\n publishedAt: row.success.publishedAt,\n reservationId: row.success.reservationId,\n ...(row.success.commentId === null ? {} : { commentId: row.success.commentId })\n })\n : ReviewSuggestionPublicationReservation.make({\n _tag: inserted.length === 1 ? \"acquired\" : \"in-progress\"\n })\n })\n ).pipe(mapPersistenceOperation(\"agent-job.reserve-review-suggestion-publication\"))\n }),\n\n releaseReviewSuggestionPublication: Effect.fn(\n \"AgentJobRepository.releaseReviewSuggestionPublication\"\n )(function*(input: typeof ReleaseReviewSuggestionPublicationInput.Type) {\n const request = yield* Schema.decodeUnknownEffect(\n Schema.toType(ReleaseReviewSuggestionPublicationInput)\n )(input)\n yield* database.transaction(\n Effect.gen(function*() {\n yield* sql`UPDATE agent_review_suggestion_publications\n SET content_digest = previous_content_digest,\n state = 'published',\n publication_id = previous_publication_id,\n previous_content_digest = NULL,\n previous_publication_id = NULL,\n previous_published_at = NULL,\n published_at = previous_published_at\n WHERE workspace_id = ${request.workspaceId}\n AND job_id = ${request.jobId}\n AND suggestion_id = ${request.suggestionId}\n AND revision_id = ${request.revisionId}\n AND content_digest = ${request.contentDigest}\n AND state = 'reserved'\n AND publication_id IS NULL\n AND previous_content_digest IS NOT NULL\n AND reservation_id = ${request.reservationId}`\n if ((yield* readChanges(sql)) === 0) {\n yield* sql`DELETE FROM agent_review_suggestion_publications\n WHERE workspace_id = ${request.workspaceId}\n AND job_id = ${request.jobId}\n AND suggestion_id = ${request.suggestionId}\n AND revision_id = ${request.revisionId}\n AND content_digest = ${request.contentDigest}\n AND state = 'reserved'\n AND publication_id IS NULL\n AND reservation_id = ${request.reservationId}`\n }\n })\n ).pipe(mapPersistenceOperation(\"agent-job.release-review-suggestion-publication\"))\n }),\n\n recordReviewSuggestionPublication: Effect.fn(\n \"AgentJobRepository.recordReviewSuggestionPublication\"\n )(function*(input: typeof RecordReviewSuggestionPublicationInput.Type) {\n const request = yield* Schema.decodeUnknownEffect(\n Schema.toType(RecordReviewSuggestionPublicationInput)\n )(input)\n return yield* database.transaction(\n Effect.gen(function*() {\n const job = yield* getJob(request.workspaceId, request.jobId)\n const publicationRows = yield* sql<Record<string, unknown>>`SELECT\n revision_id AS revisionId, content_digest AS contentDigest, state,\n publication_id AS publicationId, comment_id AS commentId,\n previous_content_digest AS previousContentDigest,\n previous_publication_id AS previousPublicationId,\n previous_published_at AS previousPublishedAt, reservation_id AS reservationId,\n reservation_acquired_at AS reservationAcquiredAt, reserved_at AS reservedAt,\n published_at AS publishedAt\n FROM agent_review_suggestion_publications\n WHERE workspace_id = ${request.workspaceId}\n AND job_id = ${request.jobId}\n AND suggestion_id = ${request.suggestionId}\n AND revision_id = ${request.revisionId}`\n const publication = Schema.decodeUnknownResult(\n ReviewSuggestionPublicationRow\n )(publicationRows[0])\n if (publicationRows.length !== 1 || Result.isFailure(publication)) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-transition\"\n })\n }\n if (publication.success.state === \"published\") {\n if (\n publication.success.contentDigest === request.contentDigest &&\n publication.success.publicationId === request.publicationId &&\n (request.commentId === undefined || publication.success.commentId === request.commentId)\n ) return\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-transition\"\n })\n }\n if (publication.success.contentDigest !== request.contentDigest) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-transition\"\n })\n }\n if (\n (request.commentId !== undefined && publication.success.commentId !== null &&\n publication.success.commentId !== request.commentId)\n ) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-transition\"\n })\n }\n if (request.finalize === false) {\n yield* sql`UPDATE agent_review_suggestion_publications\n SET publication_id = ${request.publicationId},\n comment_id = COALESCE(${request.commentId ?? null}, comment_id),\n previous_content_digest = NULL,\n previous_publication_id = NULL,\n previous_published_at = NULL,\n published_at = ${encodeTimestamp(request.publishedAt)}\n WHERE workspace_id = ${request.workspaceId}\n AND job_id = ${request.jobId}\n AND suggestion_id = ${request.suggestionId}\n AND revision_id = ${request.revisionId}\n AND content_digest = ${request.contentDigest}\n AND state = 'reserved'\n AND reservation_id = ${request.reservationId}\n AND (\n publication_id IS NULL OR publication_id = ${request.publicationId}\n )`\n if ((yield* readChanges(sql)) !== 1) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-transition\"\n })\n }\n return\n }\n if (\n publication.success.publicationId !== null &&\n publication.success.publicationId !== request.publicationId\n ) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-transition\"\n })\n }\n const review = yield* readReviewResult({\n workspaceId: request.workspaceId,\n jobId: request.jobId\n })\n if ((request.operation ?? \"create\") === \"create\") {\n yield* currentPublishableReviewSuggestion(request)\n } else {\n yield* currentPublishedReviewSuggestion(request)\n }\n yield* sql`UPDATE agent_review_suggestion_publications\n SET state = 'published',\n publication_id = ${request.publicationId},\n comment_id = COALESCE(${request.commentId ?? null}, comment_id),\n previous_content_digest = NULL,\n previous_publication_id = NULL,\n previous_published_at = NULL,\n published_at = ${encodeTimestamp(request.publishedAt)}\n WHERE workspace_id = ${request.workspaceId}\n AND job_id = ${request.jobId}\n AND suggestion_id = ${request.suggestionId}\n AND revision_id = ${request.revisionId}\n AND content_digest = ${request.contentDigest}\n AND state = 'reserved'\n AND reservation_id = ${request.reservationId}\n AND (\n publication_id IS NULL OR publication_id = ${request.publicationId}\n )`\n if ((yield* readChanges(sql)) !== 1) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-transition\"\n })\n }\n yield* appendThreadEvent({\n workspaceId: request.workspaceId,\n threadId: job.threadId,\n jobId: request.jobId,\n attemptSequence: review.attemptSequence,\n eventKind: \"review-suggestion-published\",\n payload: {\n suggestionId: request.suggestionId,\n revisionId: request.revisionId,\n publicationId: request.publicationId\n },\n payloadSchema: ReviewSuggestionPublishedPayload,\n occurredAt: request.publishedAt\n })\n })\n ).pipe(mapPersistenceOperation(\"agent-job.record-review-suggestion-publication\"))\n }),\n\n failAttempt: Effect.fn(\"AgentJobRepository.failAttempt\")(function*(input: typeof FailAgentAttemptInput.Type) {\n const request = yield* Schema.decodeUnknownEffect(Schema.toType(FailAgentAttemptInput))(input)\n return yield* database\n .transaction(\n Effect.gen(function*() {\n const job = yield* getJob(request.workspaceId, request.jobId)\n if (job.state === \"cancel-requested\") {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"cancellation-requested\"\n })\n }\n if (\n job.state !== \"running\" ||\n job.providerId !== request.error.providerId\n ) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-transition\"\n })\n }\n yield* validateLease({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n attemptSequence: request.attemptSequence,\n leaseToken: request.leaseToken,\n observedAt: request.failedAt\n })\n const payload = { error: request.error }\n const persistedEvent = yield* appendThreadEvent({\n workspaceId: request.workspaceId,\n threadId: job.threadId,\n jobId: request.jobId,\n attemptSequence: request.attemptSequence,\n eventKind: \"job-failed\",\n payload,\n payloadSchema: ProviderFailurePayload,\n occurredAt: request.failedAt\n })\n const encodedFailure = yield* encodePayload(ProviderFailurePayload, payload)\n yield* completeAttempt({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n attemptSequence: request.attemptSequence,\n completedAt: request.failedAt,\n outcome: \"failed\",\n state: \"failed\",\n sessionRef: null,\n errorJson: encodedFailure.json\n })\n return persistedEvent\n })\n )\n .pipe(mapPersistenceOperation(\"agent-job.fail-attempt\"))\n }),\n\n listRunningPrReviewAttempts: Effect.fn(\"AgentJobRepository.listRunningPrReviewAttempts\")(function*(\n workspaceId: typeof WorkspaceId.Type\n ) {\n const rows = yield* sql<Record<string, unknown>>`SELECT\n job.job_id AS jobId, attempt.attempt_sequence AS attemptSequence,\n job.provider_id AS providerId, attempt.session_ref AS sessionRef\n FROM agent_jobs job\n JOIN agent_job_attempts attempt\n ON attempt.workspace_id = job.workspace_id\n AND attempt.job_id = job.job_id\n WHERE job.workspace_id = ${workspaceId}\n AND job.state IN ('running', 'cancel-requested')\n AND attempt.completed_at IS NULL\n ORDER BY job.job_id, attempt.attempt_sequence`\n const attempts: Array<typeof RunningPrReviewAttempt.Type> = []\n for (const row of rows) {\n const jobId = yield* Schema.decodeUnknownEffect(JobId)(row.jobId).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"agent-job.running-review-job-id\" }))\n )\n const attemptSequence = yield* Schema.decodeUnknownEffect(AgentAttemptSequence)(row.attemptSequence).pipe(\n Effect.mapError(() =>\n new PersistenceOperationError({ operation: \"agent-job.running-review-attempt-sequence\" })\n )\n )\n const providerId = yield* Schema.decodeUnknownEffect(Schema.String)(row.providerId).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"agent-job.running-review-provider-id\" }))\n )\n const job = yield* getJob(workspaceId, jobId)\n if (job.task._tag !== \"pr-review\") continue\n const digest = yield* cryptoService.digest(\n \"SHA-256\",\n yield* bytesFromText(`${providerId}:${jobId}:${String(attemptSequence)}`)\n ).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"agent-job.running-review-attempt-id\" }))\n )\n const attempt = Schema.decodeUnknownResult(RunningPrReviewAttempt)({\n jobId,\n attemptSequence,\n attemptId: Encoding.encodeHex(digest).slice(0, 12),\n sessionRef: row.sessionRef\n })\n if (Result.isFailure(attempt)) {\n return yield* new PersistenceOperationError({ operation: \"agent-job.running-review-attempt-invalid\" })\n }\n attempts.push(attempt.success)\n }\n return attempts\n }),\n\n attachRunningPrReviewSession: Effect.fn(\"AgentJobRepository.attachRunningPrReviewSession\")(function*(\n input: typeof AttachRunningPrReviewSessionInput.Type\n ) {\n const request = yield* Schema.decodeUnknownEffect(\n Schema.toType(AttachRunningPrReviewSessionInput)\n )(input)\n yield* sql`UPDATE agent_job_attempts\n SET session_ref = ${request.sessionRef}\n WHERE workspace_id = ${request.workspaceId}\n AND job_id = ${request.jobId}\n AND attempt_sequence = ${request.attemptSequence}\n AND completed_at IS NULL\n AND EXISTS (\n SELECT 1 FROM agent_jobs job\n WHERE job.workspace_id = agent_job_attempts.workspace_id\n AND job.job_id = agent_job_attempts.job_id\n AND job.state IN ('running', 'cancel-requested')\n )`\n return undefined\n }),\n\n interruptRunningReviews: Effect.fn(\"AgentJobRepository.interruptRunningReviews\")(function*(\n input: typeof InterruptRunningReviewsInput.Type\n ) {\n const request = yield* Schema.decodeUnknownEffect(\n Schema.toType(InterruptRunningReviewsInput)\n )(input)\n return yield* database.transaction(\n Effect.gen(function*() {\n const rows = yield* sql<Record<string, unknown>>`SELECT job_id AS jobId\n FROM agent_jobs\n WHERE workspace_id = ${request.workspaceId}\n AND state IN ('running', 'cancel-requested')`\n let interrupted = 0\n for (const row of rows) {\n const jobId = yield* Schema.decodeUnknownEffect(JobId)(row.jobId).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"agent-job.interrupt-job-id\" }))\n )\n const job = yield* getJob(request.workspaceId, jobId)\n if (job.task._tag !== \"pr-review\") continue\n const attemptRows = yield* sql<Record<string, unknown>>`SELECT attempt_sequence AS attemptSequence\n FROM agent_job_attempts\n WHERE workspace_id = ${request.workspaceId}\n AND job_id = ${jobId}\n AND completed_at IS NULL\n ORDER BY attempt_sequence DESC\n LIMIT 1`\n const attempt = Schema.decodeUnknownResult(\n Schema.Struct({ attemptSequence: AgentAttemptSequence })\n )(attemptRows[0])\n if (Result.isFailure(attempt)) continue\n if (\n request.preservedAttempts?.some((preserved) =>\n preserved.jobId === jobId && preserved.attemptSequence === attempt.success.attemptSequence\n )\n ) continue\n const existing = yield* readReviewResult({\n workspaceId: request.workspaceId,\n jobId\n }).pipe(Effect.result)\n if (Result.isFailure(existing) && existing.failure._tag !== \"RecordNotFoundError\") {\n return yield* existing.failure\n }\n const report = Result.isSuccess(existing)\n ? {\n ...existing.success.report,\n completion: {\n status: \"unable-to-conclude\",\n reason: PROCESS_RESTART_INTERRUPTION_MESSAGE\n }\n }\n : {\n schemaVersion: 3,\n subject: job.task.subject,\n completion: {\n status: \"unable-to-conclude\",\n reason: PROCESS_RESTART_INTERRUPTION_MESSAGE\n },\n suggestions: [],\n notes: []\n } satisfies typeof PrReviewReport.Type\n yield* appendThreadEvent({\n workspaceId: request.workspaceId,\n threadId: job.threadId,\n jobId,\n attemptSequence: attempt.success.attemptSequence,\n eventKind: \"review-report\",\n payload: report,\n payloadSchema: PrReviewReport,\n occurredAt: request.interruptedAt\n })\n const error = new AgentProviderError({\n providerId: job.providerId,\n phase: \"execution\",\n message: PROCESS_RESTART_INTERRUPTION_MESSAGE,\n retryable: false\n })\n const encodedFailure = yield* encodePayload(ProviderFailurePayload, { error })\n yield* appendThreadEvent({\n workspaceId: request.workspaceId,\n threadId: job.threadId,\n jobId,\n attemptSequence: attempt.success.attemptSequence,\n eventKind: \"job-failed\",\n payload: { error },\n payloadSchema: ProviderFailurePayload,\n occurredAt: request.interruptedAt\n })\n yield* completeAttempt({\n workspaceId: request.workspaceId,\n jobId,\n attemptSequence: attempt.success.attemptSequence,\n completedAt: request.interruptedAt,\n outcome: \"failed\",\n state: \"failed\",\n sessionRef: null,\n errorJson: encodedFailure.json\n })\n interrupted += 1\n }\n return { interrupted }\n })\n ).pipe(mapPersistenceOperation(\"agent-job.interrupt-running-reviews\"))\n }),\n\n reviewBudget: Effect.fn(\"AgentJobRepository.reviewBudget\")(function*(\n input: typeof ReadReviewBudgetInput.Type\n ) {\n const request = yield* Schema.decodeUnknownEffect(Schema.toType(ReadReviewBudgetInput))(input)\n return yield* reviewBudgetState(request.workspaceId, request.jobId, request.task)\n }),\n\n extendReviewBudget: Effect.fn(\"AgentJobRepository.extendReviewBudget\")(function*(\n input: typeof ExtendReviewBudgetInput.Type\n ) {\n const request = yield* Schema.decodeUnknownEffect(Schema.toType(ExtendReviewBudgetInput))(input)\n return yield* database.transaction(\n Effect.gen(function*() {\n const job = yield* getJob(request.workspaceId, request.jobId)\n if (job.task._tag !== \"pr-review\" || job.state !== \"running\") {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-transition\"\n })\n }\n const current = yield* reviewBudgetState(request.workspaceId, request.jobId, job.task)\n if (\n current.reviewBudgetExtensionCount >= 1 ||\n current.reviewBudgetMillis === undefined ||\n current.reviewBudgetMillis + job.task.reviewProfile.budgetMillis > 3_600_000\n ) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-transition\"\n })\n }\n const reviewBudgetMillis = current.reviewBudgetMillis + job.task.reviewProfile.budgetMillis\n yield* appendThreadEvent({\n workspaceId: request.workspaceId,\n threadId: job.threadId,\n jobId: request.jobId,\n attemptSequence: null,\n eventKind: \"job-queued\",\n payload: {\n access: job.access,\n contextFingerprint: job.contextFingerprint,\n model: job.model,\n providerId: job.providerId,\n subjectRevision: job.subjectRevision,\n task: job.task,\n reviewBudgetMillis,\n reviewBudgetExtensionCount: 1\n },\n payloadSchema: PersistedJobQueuedPayload,\n occurredAt: request.extendedAt\n })\n return { reviewBudgetMillis, reviewBudgetExtensionCount: 1 }\n })\n ).pipe(mapPersistenceOperation(\"agent-job.extend-review-budget\"))\n }),\n\n requestCancellation: Effect.fn(\"AgentJobRepository.requestCancellation\")(function*(\n input: typeof RequestAgentCancellationInput.Type\n ) {\n const request = yield* Schema.decodeUnknownEffect(Schema.toType(RequestAgentCancellationInput))(input)\n yield* database\n .transaction(\n Effect.gen(function*() {\n const job = yield* getJob(request.workspaceId, request.jobId)\n if (job.state === \"cancel-requested\") return\n if (job.state !== \"queued\" && job.state !== \"running\") {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-transition\"\n })\n }\n const requestedAt = encodeTimestamp(request.requestedAt)\n const nextState = job.state === \"queued\" ? \"cancelled\" : \"cancel-requested\"\n const terminalAt = job.state === \"queued\" ? requestedAt : null\n yield* sql`UPDATE agent_jobs\n SET state = ${nextState}, cancel_requested_at = ${requestedAt}, terminal_at = ${terminalAt}\n WHERE workspace_id = ${request.workspaceId}\n AND job_id = ${request.jobId}\n AND state = ${job.state}`\n if ((yield* readChanges(sql)) !== 1) {\n return yield* new AgentJobInputError({\n workspaceId: request.workspaceId,\n jobId: request.jobId,\n reason: \"invalid-transition\"\n })\n }\n yield* appendThreadEvent({\n workspaceId: request.workspaceId,\n threadId: job.threadId,\n jobId: request.jobId,\n attemptSequence: null,\n eventKind: \"cancel-requested\",\n payload: { requestedAt: request.requestedAt },\n payloadSchema: CancellationRequestedPayload,\n occurredAt: request.requestedAt\n })\n })\n )\n .pipe(mapPersistenceOperation(\"agent-job.request-cancellation\"))\n }),\n\n latestReview: Effect.fnUntraced(function*(input) {\n const request = yield* Schema.decodeUnknownEffect(Schema.toType(LatestAgentReviewInput))(input)\n const subjectJson = yield* Schema.encodeUnknownEffect(\n Schema.fromJsonString(PrReviewSubject)\n )(request.subject).pipe(\n Effect.mapError(() =>\n new PersistenceOperationError({\n operation: \"agent-job.latest-review-subject\"\n })\n )\n )\n const taskContextPrefix =\n `{\"_tag\":\"pr-review\",\"pluginConnectionId\":\"${request.pluginConnectionId}\",\"subject\":${subjectJson},\"reviewProfile\":`\n const identityPrefix = taskContextPrefix.slice(0, taskContextPrefix.indexOf(\"\\\"baseRevision\\\"\"))\n const rendered = renderLatestAgentReviewQuery({\n workspaceId: request.workspaceId,\n ...(request.excludeJobId === undefined ? {} : { excludeJobId: request.excludeJobId }),\n ...(request.allowDifferentHead === true ? {} : { subjectRevision: request.subject.headRevision }),\n taskContextPrefix: request.allowDifferentHead === true ? identityPrefix : taskContextPrefix,\n excludeTargeted: true,\n ...(request.jobId === undefined ? {} : { jobId: request.jobId })\n })\n const rows = yield* sql\n .unsafe<Record<string, unknown>>(rendered.sql, [...rendered.params])\n .pipe(mapPersistenceOperation(\"agent-job.latest-review\"))\n if (rows.length === 0) return Option.none<typeof LatestAgentReviewRecord.Type>()\n const row = Schema.decodeUnknownResult(LatestReviewRow)(rows[0])\n if (rows.length !== 1 || Result.isFailure(row)) {\n return yield* persistedRecordError(\n request.workspaceId,\n \"agent-review\",\n request.subject.pullRequestId,\n \"agent-review-latest-schema-invalid\"\n )\n }\n const task = yield* decodeTaskContext(\n request.workspaceId,\n row.success.jobId,\n row.success.taskContextJson,\n row.success.taskContextDigest\n )\n let interrupted = false\n if (row.success.state === \"failed\") {\n const interruptionRows = yield* sql<Record<string, unknown>>`SELECT COUNT(*) AS interrupted\n FROM agent_thread_events\n WHERE workspace_id = ${request.workspaceId}\n AND job_id = ${row.success.jobId}\n AND event_kind = 'job-failed'\n AND payload_json LIKE ${`%${PROCESS_RESTART_INTERRUPTION_MESSAGE}%`}`.pipe(\n mapPersistenceOperation(\"agent-job.latest-review-interruption\")\n )\n interrupted = Number(interruptionRows[0]?.interrupted ?? 0) > 0\n }\n if (\n task._tag !== \"pr-review\" ||\n task.pluginConnectionId !== request.pluginConnectionId ||\n (\n request.allowDifferentHead === true\n ? task.subject.providerId !== request.subject.providerId ||\n task.subject.repository !== request.subject.repository ||\n task.subject.pullRequestId !== request.subject.pullRequestId\n : !PrReviewSubjectEquivalence(task.subject, request.subject)\n )\n ) {\n return yield* persistedRecordError(\n request.workspaceId,\n \"agent-review\",\n request.subject.pullRequestId,\n \"agent-review-subject-mismatch\"\n )\n }\n const reviewBudget = yield* reviewBudgetState(\n request.workspaceId,\n row.success.jobId,\n task\n )\n const startedRows = yield* sql<Record<string, unknown>>`SELECT MAX(started_at) AS startedAt\n FROM agent_job_attempts\n WHERE workspace_id = ${request.workspaceId} AND job_id = ${row.success.jobId}`.pipe(\n mapPersistenceOperation(\"agent-job.latest-review-started-at\")\n )\n const startedAt = Schema.decodeUnknownResult(\n Schema.Struct({ startedAt: Schema.NullOr(UtcTimestamp) })\n )(startedRows[0])\n if (startedRows.length !== 1 || Result.isFailure(startedAt)) {\n return yield* persistedRecordError(\n request.workspaceId,\n \"agent-review\",\n request.subject.pullRequestId,\n \"agent-review-started-at-schema-invalid\"\n )\n }\n const reviewResult = row.success.state === \"succeeded\" ||\n row.success.state === \"failed\" ||\n row.success.state === \"cancelled\"\n ? yield* readReviewResult({\n workspaceId: request.workspaceId,\n jobId: row.success.jobId\n }).pipe(Effect.catchTag(\"RecordNotFoundError\", () => Effect.succeed(null)))\n : null\n const report = reviewResult === null ? null : reviewResult.report\n const activityRows = yield* sql<Record<string, unknown>>`SELECT\n workspace_id AS workspaceId, thread_id AS threadId,\n event_sequence AS eventSequence, job_id AS jobId,\n attempt_sequence AS attemptSequence, event_kind AS eventKind,\n payload_json AS payloadJson, payload_digest AS payloadDigest,\n payload_byte_length AS payloadByteLength, occurred_at AS occurredAt\n FROM agent_thread_events\n WHERE workspace_id = ${request.workspaceId}\n AND job_id = ${row.success.jobId}\n AND event_kind = 'progress'\n ORDER BY event_sequence DESC\n LIMIT ${MAXIMUM_AGENT_THREAD_EVENT_PAGE_SIZE + 1}`.pipe(\n mapPersistenceOperation(\"agent-job.latest-review-activity\")\n )\n const activity = new Array<string>()\n for (\n const unknownRow of activityRows\n .slice(0, MAXIMUM_AGENT_THREAD_EVENT_PAGE_SIZE)\n .reverse()\n ) {\n const decodedRow = Schema.decodeUnknownResult(ThreadEventRow)(unknownRow)\n if (Result.isFailure(decodedRow)) {\n return yield* persistedRecordError(\n request.workspaceId,\n \"agent-review\",\n request.subject.pullRequestId,\n \"agent-review-activity-schema-invalid\"\n )\n }\n const payload = yield* decodeEventPayload(request.workspaceId, decodedRow.success)\n const decodedEvent = Schema.decodeUnknownResult(AgentRuntimeEvent)(payload)\n if (\n Result.isFailure(decodedEvent) ||\n decodedEvent.success._tag !== \"output\" ||\n decodedEvent.success.channel !== \"progress\"\n ) {\n return yield* persistedRecordError(\n request.workspaceId,\n \"agent-review\",\n request.subject.pullRequestId,\n \"agent-review-activity-payload-invalid\"\n )\n }\n activity.push(decodedEvent.success.text)\n }\n const record = yield* Schema.decodeUnknownEffect(Schema.toType(LatestAgentReviewRecord))({\n ...row.success,\n state: interrupted ? \"interrupted\" : row.success.state,\n startedAt: startedAt.success.startedAt,\n ...(reviewBudget.reviewBudgetMillis === undefined\n ? {}\n : { reviewBudgetMillis: reviewBudget.reviewBudgetMillis }),\n reviewBudgetExtensionCount: reviewBudget.reviewBudgetExtensionCount,\n taskIntent: task.intent ?? null,\n report,\n reviewProfile: task.reviewProfile,\n activity: {\n events: activity,\n truncated: activityRows.length > MAXIMUM_AGENT_THREAD_EVENT_PAGE_SIZE\n }\n })\n return Option.some(record)\n }, Effect.withTracerEnabled(false)),\n\n reviewResult: readReviewResult,\n\n reviewSuggestionRevisions: Effect.fn(\n \"AgentJobRepository.reviewSuggestionRevisions\"\n )(function*(input: typeof ReadReviewSuggestionRevisionsInput.Type) {\n return yield* reviewSuggestionRevisions.read(input).pipe(\n mapPersistenceOperation(\"agent-job.review-suggestion-revisions\")\n )\n }),\n\n threadAfter: Effect.fn(\"AgentJobRepository.threadAfter\")(function*(input: typeof AgentThreadAfterInput.Type) {\n const request = yield* Schema.decodeUnknownEffect(Schema.toType(AgentThreadAfterInput))(input)\n const thread = yield* findThread(\n request.workspaceId,\n \"release-chat\",\n request.releaseId\n ).pipe(\n mapPersistenceOperation(\"agent-job.find-thread\")\n )\n if (Option.isNone(thread)) {\n return yield* new RecordNotFoundError({\n workspaceId: request.workspaceId,\n recordKind: \"agent-thread\",\n recordKey: request.releaseId\n })\n }\n return yield* threadEventsAfter(\n request.workspaceId,\n thread.value.threadId,\n request.after,\n request.limit\n )\n }),\n\n reviewThreadAfter: Effect.fnUntraced(function*(\n input: typeof AgentReviewThreadAfterInput.Type\n ) {\n const request = yield* Schema.decodeUnknownEffect(\n Schema.toType(AgentReviewThreadAfterInput)\n )(input)\n const subjectKey = yield* reviewThreadSubjectKey(\n request.pluginConnectionId,\n request.subject\n )\n const thread = yield* findThread(\n request.workspaceId,\n \"pr-review\",\n subjectKey\n ).pipe(mapPersistenceOperation(\"agent-job.find-review-thread\"))\n if (Option.isNone(thread)) {\n return yield* new RecordNotFoundError({\n workspaceId: request.workspaceId,\n recordKind: \"agent-review-thread\",\n recordKey: request.subject.pullRequestId\n .slice(0, MAXIMUM_PERSISTENCE_RECORD_KEY_LENGTH)\n .trimEnd()\n })\n }\n return yield* threadEventsAfter(\n request.workspaceId,\n thread.value.threadId,\n request.after,\n request.limit\n )\n }, Effect.withTracerEnabled(false)),\n\n reviewThreadBefore: Effect.fnUntraced(function*(\n input: typeof AgentReviewThreadBeforeInput.Type\n ) {\n const request = yield* Schema.decodeUnknownEffect(\n Schema.toType(AgentReviewThreadBeforeInput)\n )(input)\n const subjectKey = yield* reviewThreadSubjectKey(\n request.pluginConnectionId,\n request.subject\n )\n const thread = yield* findThread(\n request.workspaceId,\n \"pr-review\",\n subjectKey\n ).pipe(mapPersistenceOperation(\"agent-job.find-review-thread\"))\n if (Option.isNone(thread)) {\n return yield* new RecordNotFoundError({\n workspaceId: request.workspaceId,\n recordKind: \"agent-review-thread\",\n recordKey: request.subject.pullRequestId\n .slice(0, MAXIMUM_PERSISTENCE_RECORD_KEY_LENGTH)\n .trimEnd()\n })\n }\n return yield* threadEventsBefore(\n request.workspaceId,\n thread.value.threadId,\n request.before,\n request.limit\n )\n }, Effect.withTracerEnabled(false)),\n\n reviewThreadHistory: Effect.fnUntraced(function*(\n input: typeof AgentReviewThreadHistoryInput.Type\n ) {\n const request = yield* Schema.decodeUnknownEffect(\n Schema.toType(AgentReviewThreadHistoryInput)\n )(input)\n const history = renderAgentReviewThreadHistoryQuery({\n workspaceId: request.workspaceId,\n threadId: request.threadId,\n beforeJobId: request.beforeJobId,\n afterSequence: request.after,\n limit: request.limit\n })\n const rows = yield* sql\n .unsafe<Record<string, unknown>>(history.sql, [...history.params])\n .pipe(mapPersistenceOperation(\"agent-job.review-thread-history\"))\n const events = yield* decodeThreadEventRows(\n request.workspaceId,\n request.threadId,\n rows\n )\n return {\n events,\n nextCursor: events.at(-1)?.eventSequence ?? request.after\n } satisfies AgentThreadEventPage\n }, Effect.withTracerEnabled(false)),\n\n reviewThreadTail: Effect.fnUntraced(function*(\n input: typeof AgentReviewThreadTailInput.Type\n ) {\n const request = yield* Schema.decodeUnknownEffect(\n Schema.toType(AgentReviewThreadTailInput)\n )(input)\n const subjectKey = yield* reviewThreadSubjectKey(\n request.pluginConnectionId,\n request.subject\n )\n const thread = yield* findThread(\n request.workspaceId,\n \"pr-review\",\n subjectKey\n ).pipe(mapPersistenceOperation(\"agent-job.find-review-thread\"))\n if (Option.isNone(thread)) {\n return yield* new RecordNotFoundError({\n workspaceId: request.workspaceId,\n recordKind: \"agent-review-thread\",\n recordKey: request.subject.pullRequestId\n .slice(0, MAXIMUM_PERSISTENCE_RECORD_KEY_LENGTH)\n .trimEnd()\n })\n }\n return yield* threadEventsTail(\n request.workspaceId,\n thread.value.threadId,\n request.limit\n )\n }, Effect.withTracerEnabled(false))\n }\n})\n\n/** Durable release-thread repository with transactional worker ownership. */\nexport interface AgentJobRepositoryService extends Success<typeof makeAgentJobRepository> {}\n\n/** Effect service owning durable agent job lifecycle and ordered replay. */\nexport class AgentJobRepository extends Context.Service<AgentJobRepository, AgentJobRepositoryService>()(\n \"@knpkv/control-center/AgentJobRepository\"\n) {\n /** Layer that captures the shared SQLite database and cryptography services. */\n static readonly layer = Layer.effect(AgentJobRepository, makeAgentJobRepository)\n}\n","import * as Context from \"effect/Context\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport type { Success } from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Schema from \"effect/Schema\"\n\nimport { AuthorizedShareGrant } from \"../../../domain/authorizedShare.js\"\nimport { EntityId, PersonId, SessionId, ShareId, WorkspaceId } from \"../../../domain/identifiers.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport { Database } from \"../Database.js\"\nimport { RecordAlreadyExistsError, RecordNotFoundError } from \"../errors.js\"\nimport { mapPersistenceOperation } from \"./internal.js\"\n\nconst RECORD_KIND = \"authorized-share\"\n\n/** Raised when authorized-share persistence input fails boundary decoding. */\nexport class AuthorizedShareInputError extends Schema.TaggedErrorClass<AuthorizedShareInputError>()(\n \"AuthorizedShareInputError\",\n { operation: Schema.Literals([\"create\", \"get\", \"revoke\"]) }\n) {}\n\n/** Immutable owner-authored exact-entity share grant. */\nexport const CreateAuthorizedShareInput = Schema.Struct({\n workspaceId: WorkspaceId,\n shareId: ShareId,\n entityId: EntityId,\n granteePersonId: PersonId,\n createdByPersonId: PersonId,\n createdBySessionId: SessionId,\n createdAt: UtcTimestamp,\n expiresAt: UtcTimestamp\n})\n\n/** Decoded authorized-share creation command. */\nexport type CreateAuthorizedShareInput = typeof CreateAuthorizedShareInput.Type\n\n/** Workspace-scoped authorized-share lookup. */\nexport const ReadAuthorizedShareInput = Schema.Struct({\n workspaceId: WorkspaceId,\n shareId: ShareId\n})\n\n/** Immutable owner-authored share revocation. */\nexport const RevokeAuthorizedShareInput = Schema.Struct({\n workspaceId: WorkspaceId,\n shareId: ShareId,\n revokedByPersonId: PersonId,\n revokedBySessionId: SessionId,\n revokedAt: UtcTimestamp\n})\n\n/** Decoded authorized-share revocation command. */\nexport type RevokeAuthorizedShareInput = typeof RevokeAuthorizedShareInput.Type\n\nconst AuthorizedShareRow = Schema.Struct({\n workspaceId: WorkspaceId,\n shareId: ShareId,\n entityId: EntityId,\n granteePersonId: PersonId,\n createdByPersonId: PersonId,\n createdBySessionId: SessionId,\n createdAt: UtcTimestamp,\n expiresAt: UtcTimestamp,\n revokedAt: Schema.NullOr(UtcTimestamp)\n})\n\ntype AuthorizedShareRow = typeof AuthorizedShareRow.Type\n\nconst decodeInput = <SchemaType extends Schema.Top>(\n schema: SchemaType,\n operation: AuthorizedShareInputError[\"operation\"],\n input: unknown\n): Effect.Effect<SchemaType[\"Type\"], AuthorizedShareInputError, SchemaType[\"DecodingServices\"]> =>\n Schema.decodeUnknownEffect(Schema.toType(schema))(input).pipe(\n Effect.mapError(() => new AuthorizedShareInputError({ operation }))\n )\n\nconst grantFromRow = (row: AuthorizedShareRow): Effect.Effect<AuthorizedShareGrant, Schema.SchemaError> =>\n Schema.decodeUnknownEffect(Schema.toType(AuthorizedShareGrant))({\n workspaceId: row.workspaceId,\n shareId: row.shareId,\n target: { _tag: \"entity\", entityId: row.entityId },\n granteePersonId: row.granteePersonId,\n createdByPersonId: row.createdByPersonId,\n createdBySessionId: row.createdBySessionId,\n createdAt: row.createdAt,\n expiresAt: row.expiresAt,\n revokedAt: row.revokedAt\n })\n\nconst sameCreateIntent = (\n existing: AuthorizedShareGrant,\n requested: CreateAuthorizedShareInput\n): boolean =>\n existing.workspaceId === requested.workspaceId &&\n existing.shareId === requested.shareId &&\n existing.target.entityId === requested.entityId &&\n existing.granteePersonId === requested.granteePersonId &&\n existing.createdByPersonId === requested.createdByPersonId &&\n existing.createdBySessionId === requested.createdBySessionId &&\n DateTime.Order(existing.expiresAt, requested.expiresAt) === 0\n\nconst makeAuthorizedShareRepository = Effect.gen(function*() {\n const database = yield* Database\n const sql = database.sql\n\n const findRows = Effect.fn(\"AuthorizedShareRepository.findRows\")(function*(\n workspaceId: WorkspaceId,\n shareId: ShareId\n ) {\n const rows = yield* sql`SELECT\n grant_record.workspace_id AS workspaceId,\n grant_record.share_id AS shareId,\n grant_record.entity_id AS entityId,\n grant_record.grantee_person_id AS granteePersonId,\n grant_record.created_by_person_id AS createdByPersonId,\n grant_record.created_by_session_id AS createdBySessionId,\n grant_record.created_at AS createdAt,\n grant_record.expires_at AS expiresAt,\n revocation.revoked_at AS revokedAt\n FROM authorized_share_grants grant_record\n LEFT JOIN authorized_share_revocations revocation\n ON revocation.workspace_id = grant_record.workspace_id\n AND revocation.share_id = grant_record.share_id\n WHERE grant_record.workspace_id = ${workspaceId}\n AND grant_record.share_id = ${shareId}`\n return yield* Schema.decodeUnknownEffect(Schema.Array(AuthorizedShareRow))(rows)\n })\n\n const readGrant = Effect.fn(\"AuthorizedShareRepository.readGrant\")(function*(request: {\n readonly workspaceId: WorkspaceId\n readonly shareId: ShareId\n }) {\n const rows = yield* findRows(request.workspaceId, request.shareId)\n const row = rows[0]\n if (row === undefined) {\n return yield* new RecordNotFoundError({\n workspaceId: request.workspaceId,\n recordKind: RECORD_KIND,\n recordKey: request.shareId\n })\n }\n return yield* grantFromRow(row)\n })\n\n const read = Effect.fn(\"AuthorizedShareRepository.read\")(function*(input: unknown) {\n const request = yield* decodeInput(ReadAuthorizedShareInput, \"get\", input)\n return yield* readGrant(request)\n }, mapPersistenceOperation(\"authorized-share.get\"))\n\n return {\n create: Effect.fn(\"AuthorizedShareRepository.create\")(function*(input: unknown) {\n const request = yield* decodeInput(CreateAuthorizedShareInput, \"create\", input)\n // Keep conflict arbitration in one autocommit statement so concurrent processes cannot\n // both hold deferred read transactions before competing for the immutable grant identity.\n yield* sql`INSERT INTO authorized_share_grants (\n workspace_id, share_id, schema_version, entity_id, grantee_person_id,\n created_by_person_id, created_by_session_id, expires_at, created_at\n ) VALUES (\n ${request.workspaceId}, ${request.shareId}, 1, ${request.entityId}, ${request.granteePersonId},\n ${request.createdByPersonId}, ${request.createdBySessionId},\n ${Schema.encodeSync(UtcTimestamp)(request.expiresAt)},\n ${Schema.encodeSync(UtcTimestamp)(request.createdAt)}\n ) ON CONFLICT(workspace_id, share_id) DO NOTHING`\n const existing = yield* readGrant(request)\n if (sameCreateIntent(existing, request)) return existing\n return yield* new RecordAlreadyExistsError({\n workspaceId: request.workspaceId,\n recordKind: RECORD_KIND,\n recordKey: request.shareId\n })\n }, mapPersistenceOperation(\"authorized-share.create\")),\n get: read,\n revoke: Effect.fn(\"AuthorizedShareRepository.revoke\")(function*(input: unknown) {\n const request = yield* decodeInput(RevokeAuthorizedShareInput, \"revoke\", input)\n return yield* database.transaction(\n Effect.gen(function*() {\n const existing = yield* readGrant(request)\n if (existing.revokedAt !== null) return existing\n yield* sql`INSERT INTO authorized_share_revocations (\n workspace_id, share_id, revoked_by_person_id, revoked_by_session_id, revoked_at\n ) VALUES (\n ${request.workspaceId}, ${request.shareId}, ${request.revokedByPersonId},\n ${request.revokedBySessionId}, ${Schema.encodeSync(UtcTimestamp)(request.revokedAt)}\n )`\n return yield* read(request)\n })\n )\n }, mapPersistenceOperation(\"authorized-share.revoke\"))\n }\n})\n\n/** Durable exact-scope authorized-share repository service. */\nexport interface AuthorizedShareRepositoryService extends Success<typeof makeAuthorizedShareRepository> {}\n\n/** Private authorized-share SQL repository. */\nexport class AuthorizedShareRepository extends Context.Service<\n AuthorizedShareRepository,\n AuthorizedShareRepositoryService\n>()(\"@knpkv/control-center/server/persistence/AuthorizedShareRepository\") {\n static readonly layer = Layer.effect(AuthorizedShareRepository, makeAuthorizedShareRepository)\n}\n","import * as Schema from \"effect/Schema\"\n\nimport { PersonSourceIdentity, Role } from \"../../../../domain/actors.js\"\nimport {\n DeliveryEntityKind,\n DeliveryEntityProjection,\n DeliveryEntityService,\n DeliveryEntityStatusGroup,\n DeliveryNode,\n DeliveryRelationship,\n EvidenceClaim,\n EvidenceItem,\n LedgerRevision\n} from \"../../../../domain/deliveryGraph.js\"\nimport {\n EntityId,\n EnvironmentId,\n EvidenceId,\n GraphNodeId,\n PersonId,\n PluginConnectionId,\n RelationshipId,\n ReleaseId\n} from \"../../../../domain/identifiers.js\"\nimport { ProviderId, Revision, VendorImmutableId } from \"../../../../domain/sourceRevision.js\"\nimport { UtcTimestamp } from \"../../../../domain/utcTimestamp.js\"\n\nconst MAXIMUM_BATCH_RECORDS = 500\nconst MAXIMUM_WORKSPACE_ENTITY_OWNERS = 20\nconst MAXIMUM_WORKSPACE_OWNER_OPTIONS = 200\n\nconst WorkspaceEntityOwner = Schema.Struct({\n avatarFallback: Schema.String.check(Schema.isTrimmed(), Schema.isNonEmpty(), Schema.isMaxLength(4)),\n displayName: Schema.String.check(Schema.isTrimmed(), Schema.isNonEmpty(), Schema.isMaxLength(200)),\n personId: PersonId,\n roles: Schema.Array(Role).check(Schema.isMinLength(1), Schema.isMaxLength(16)),\n sourceIdentities: Schema.optionalKey(Schema.Array(PersonSourceIdentity).check(Schema.isMaxLength(16)))\n})\n\nexport const EntityProjectionWrite = Schema.Struct({\n projection: DeliveryEntityProjection,\n recordedAt: UtcTimestamp\n})\n\n/** Bounded atomic set of immutable delivery-graph records. */\nexport const DeliveryGraphWriteBatch = Schema.Struct({\n entityProjections: Schema.Array(EntityProjectionWrite).check(\n Schema.isMaxLength(MAXIMUM_BATCH_RECORDS)\n ),\n nodes: Schema.Array(DeliveryNode).check(Schema.isMaxLength(MAXIMUM_BATCH_RECORDS)),\n evidenceItems: Schema.Array(EvidenceItem).check(Schema.isMaxLength(MAXIMUM_BATCH_RECORDS)),\n evidenceClaims: Schema.Array(EvidenceClaim).check(Schema.isMaxLength(MAXIMUM_BATCH_RECORDS)),\n relationships: Schema.Array(DeliveryRelationship).check(\n Schema.isMaxLength(MAXIMUM_BATCH_RECORDS)\n )\n}).check(\n Schema.makeFilter(\n (batch) => {\n const size = batch.entityProjections.length + batch.nodes.length +\n batch.evidenceItems.length + batch.evidenceClaims.length + batch.relationships.length\n return size > 0 && size <= MAXIMUM_BATCH_RECORDS\n },\n { expected: `a nonempty delivery graph batch of at most ${MAXIMUM_BATCH_RECORDS} records` }\n )\n)\n\n/** Decoded atomic delivery-graph write batch. */\nexport type DeliveryGraphWriteBatch = typeof DeliveryGraphWriteBatch.Type\n\n/** Tagged, bounded read supported by the delivery-graph persistence seam. */\nexport const DeliveryGraphQuery = Schema.TaggedUnion({\n entityProjection: {\n entityId: EntityId,\n revision: Schema.NullOr(LedgerRevision)\n },\n sourceEntityProjection: {\n pluginConnectionId: PluginConnectionId,\n providerId: ProviderId,\n vendorImmutableId: VendorImmutableId,\n revision: Revision\n },\n node: { nodeId: GraphNodeId },\n evidence: {\n evidenceId: EvidenceId,\n limit: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 200 }))\n },\n relationship: {\n relationshipId: RelationshipId,\n revision: Schema.NullOr(LedgerRevision)\n },\n relationshipHistory: {\n relationshipId: RelationshipId,\n limit: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 200 }))\n },\n entitySlice: {\n entityId: EntityId,\n limit: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 }))\n },\n nodeRelationships: {\n nodeId: GraphNodeId,\n limit: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 500 }))\n },\n releaseSlice: {\n releaseId: ReleaseId,\n environmentId: Schema.NullOr(EnvironmentId),\n limit: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 500 }))\n },\n componentRelationships: {\n releaseId: Schema.NullOr(ReleaseId),\n component: Schema.String.check(Schema.isTrimmed(), Schema.isNonEmpty(), Schema.isMaxLength(200)),\n limit: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 2_000 }))\n },\n workspaceEntityProjections: {\n owner: Schema.NullOr(PersonId),\n query: Schema.NullOr(\n Schema.String.check(Schema.isTrimmed(), Schema.isNonEmpty(), Schema.isMaxLength(200))\n ),\n service: Schema.NullOr(DeliveryEntityService),\n status: Schema.NullOr(DeliveryEntityStatusGroup),\n type: Schema.NullOr(DeliveryEntityKind),\n limit: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 500 }))\n },\n releaseSummary: {\n releaseId: ReleaseId\n }\n})\n\n/** Decoded delivery-graph read query. */\nexport type DeliveryGraphQuery = typeof DeliveryGraphQuery.Type\n\nexport const PersistedEntityProjection = Schema.Struct({\n projection: DeliveryEntityProjection,\n recordedAt: UtcTimestamp\n})\n\nexport const PersistedSourceEntityProjection = Schema.Struct({\n sourceRevision: Revision,\n projection: DeliveryEntityProjection,\n recordedAt: UtcTimestamp\n})\n\nconst EvidenceBundle = Schema.Struct({\n evidence: EvidenceItem,\n claims: Schema.Array(EvidenceClaim)\n})\n\nconst NodeRelationships = Schema.Struct({\n nodeId: GraphNodeId,\n truncated: Schema.Boolean,\n relationships: Schema.Array(DeliveryRelationship)\n})\n\nconst ReleaseSlice = Schema.Struct({\n releaseId: ReleaseId,\n environmentId: Schema.NullOr(EnvironmentId),\n truncated: Schema.Boolean,\n nodes: Schema.Array(DeliveryNode),\n entityProjections: Schema.Array(PersistedEntityProjection),\n relationships: Schema.Array(DeliveryRelationship),\n evidenceClaims: Schema.Array(EvidenceClaim),\n evidenceItems: Schema.Array(EvidenceItem)\n})\n\nconst ComponentRelationships = Schema.Struct({\n releaseId: Schema.NullOr(ReleaseId),\n truncated: Schema.Boolean,\n relationships: Schema.Array(DeliveryRelationship)\n})\n\nconst MAXIMUM_WORKSPACE_ENTITY_RELEASES = 500\n\nconst WorkspaceEntityReleaseIds = Schema.Array(ReleaseId).check(\n Schema.isUnique(),\n Schema.isMaxLength(MAXIMUM_WORKSPACE_ENTITY_RELEASES),\n Schema.makeFilter(\n (releaseIds) =>\n releaseIds.every((releaseId, index) => {\n const previous = releaseIds[index - 1]\n return index === 0 || (previous !== undefined && previous < releaseId)\n }),\n { expected: \"sorted workspace entity release identifiers\" }\n )\n)\n\nconst WorkspaceEntityProjection = Schema.Struct({\n canonicalReleaseId: Schema.NullOr(ReleaseId),\n owners: Schema.Array(WorkspaceEntityOwner).check(Schema.isMaxLength(MAXIMUM_WORKSPACE_ENTITY_OWNERS)),\n ownersTruncated: Schema.Boolean,\n releaseIds: WorkspaceEntityReleaseIds,\n releaseMembershipsTruncated: Schema.Boolean,\n projection: DeliveryEntityProjection,\n recordedAt: UtcTimestamp\n}).check(\n Schema.makeFilter(\n ({ canonicalReleaseId, releaseIds }) => canonicalReleaseId === (releaseIds[0] ?? null),\n { expected: \"canonical release identifier to be the first current release membership\" }\n ),\n Schema.makeFilter(\n ({ releaseIds, releaseMembershipsTruncated }) =>\n !releaseMembershipsTruncated || releaseIds.length === MAXIMUM_WORKSPACE_ENTITY_RELEASES,\n { expected: \"truncated workspace release memberships to contain the complete bounded prefix\" }\n ),\n Schema.makeFilter(\n ({ owners, ownersTruncated }) => !ownersTruncated || owners.length === MAXIMUM_WORKSPACE_ENTITY_OWNERS,\n { expected: \"truncated workspace owners to contain the complete bounded prefix\" }\n )\n)\n\nconst EntitySlice = Schema.Struct({\n entity: WorkspaceEntityProjection,\n truncated: Schema.Boolean,\n nodes: Schema.Array(DeliveryNode),\n relatedEntityProjections: Schema.Array(PersistedEntityProjection),\n relationships: Schema.Array(DeliveryRelationship),\n evidenceClaims: Schema.Array(EvidenceClaim),\n evidenceItems: Schema.Array(EvidenceItem)\n})\n\nconst WorkspaceEntityProjections = Schema.Struct({\n matchedCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n ownerOptions: Schema.Array(WorkspaceEntityOwner).check(Schema.isMaxLength(MAXIMUM_WORKSPACE_OWNER_OPTIONS)),\n ownerOptionsTruncated: Schema.Boolean,\n totalCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n truncated: Schema.Boolean,\n items: Schema.Array(WorkspaceEntityProjection)\n}).check(\n Schema.makeFilter(\n ({ ownerOptions, ownerOptionsTruncated }) =>\n !ownerOptionsTruncated || ownerOptions.length === MAXIMUM_WORKSPACE_OWNER_OPTIONS,\n { expected: \"truncated workspace owner options to contain the complete bounded prefix\" }\n )\n)\n\nconst ReleaseRelationshipSummary = Schema.Struct({\n issues: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n pullRequests: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n pipelineExecutions: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))\n})\n\n/** Tagged read result; callers never need to understand the SQL representation. */\nexport const DeliveryGraphReadResult = Schema.TaggedUnion({\n entityProjection: { value: PersistedEntityProjection },\n sourceEntityProjection: { value: PersistedSourceEntityProjection },\n node: { value: DeliveryNode },\n evidence: { value: EvidenceBundle },\n relationship: { value: DeliveryRelationship },\n relationshipHistory: { value: Schema.Array(DeliveryRelationship) },\n entitySlice: { value: EntitySlice },\n nodeRelationships: { value: NodeRelationships },\n releaseSlice: { value: ReleaseSlice },\n componentRelationships: { value: ComponentRelationships },\n workspaceEntityProjections: { value: WorkspaceEntityProjections },\n releaseSummary: { value: ReleaseRelationshipSummary }\n})\n\n/** Decoded delivery-graph read result. */\nexport type DeliveryGraphReadResult = typeof DeliveryGraphReadResult.Type\n\n/** Counts committed by one atomic delivery-graph write. */\nexport const DeliveryGraphWriteReceipt = Schema.Struct({\n entityProjectionCount: Schema.Int,\n nodeCount: Schema.Int,\n evidenceItemCount: Schema.Int,\n evidenceClaimCount: Schema.Int,\n relationshipCount: Schema.Int\n})\n\n/** Decoded delivery-graph write receipt. */\nexport type DeliveryGraphWriteReceipt = typeof DeliveryGraphWriteReceipt.Type\n\n/** Invalid unknown input rejected before any graph SQL is run. */\nexport class DeliveryGraphInputError extends Schema.TaggedErrorClass<DeliveryGraphInputError>()(\n \"DeliveryGraphInputError\",\n { operation: Schema.Literals([\"read\", \"write\"]) }\n) {}\n","import * as Effect from \"effect/Effect\"\nimport * as Predicate from \"effect/Predicate\"\n\nimport type { PersistedRecordError } from \"../../errors.js\"\nimport type { QuarantineDiagnosticSummary, QuarantineReasonCode, QuarantineRecordKind } from \"../models.js\"\n\ntype DeliveryGraphQuarantineRecordKind = Extract<\n QuarantineRecordKind,\n | \"delivery-node\"\n | \"delivery-relationship\"\n | \"entity-projection\"\n | \"evidence-claim\"\n | \"evidence-freshness\"\n | \"evidence-item\"\n | \"person\"\n | \"person-avatar\"\n>\n\ninterface DeliveryGraphQuarantineDiagnostic {\n readonly diagnosticCode: QuarantineReasonCode\n readonly diagnosticSummary: QuarantineDiagnosticSummary\n readonly recordKind: DeliveryGraphQuarantineRecordKind\n}\n\n/** Internal carrier that keeps malformed values out of the public error channel. */\nexport class MalformedDeliveryGraphRecord {\n readonly _tag = \"MalformedDeliveryGraphRecord\"\n readonly error: PersistedRecordError\n readonly row: unknown\n\n constructor(error: PersistedRecordError, row: unknown) {\n this.error = error\n this.row = row\n }\n}\n\n/** Attach an ephemeral raw row to a bounded graph decode failure for later redacted quarantine. */\nexport const captureMalformedDeliveryGraphRow = (row: unknown) =>\n<Success, Failure, Requirements>(\n effect: Effect.Effect<Success, Failure, Requirements>\n) =>\n Effect.catchIf(\n effect,\n (failure): failure is Failure & PersistedRecordError => Predicate.isTagged(\"PersistedRecordError\")(failure),\n (error) => Effect.fail(new MalformedDeliveryGraphRecord(error, row))\n )\n\nconst isDeliveryGraphRecordKind = (recordKind: string): recordKind is DeliveryGraphQuarantineRecordKind => {\n switch (recordKind) {\n case \"delivery-node\":\n case \"delivery-relationship\":\n case \"entity-projection\":\n case \"evidence-claim\":\n case \"evidence-freshness\":\n case \"evidence-item\":\n return true\n default:\n return false\n }\n}\n\n/** Translate graph decoder failures into the fixed metadata accepted by quarantine storage. */\nexport const deliveryGraphQuarantineDiagnostic = (\n error: PersistedRecordError\n): DeliveryGraphQuarantineDiagnostic | null => {\n switch (error.diagnosticCode) {\n case \"delivery-graph-digest-mismatch\":\n return isDeliveryGraphRecordKind(error.recordKind)\n ? {\n recordKind: error.recordKind,\n diagnosticCode: \"delivery-graph-digest-mismatch\",\n diagnosticSummary: \"Stored delivery graph record digest does not match its content.\"\n }\n : null\n case \"delivery-node-schema-invalid\":\n return {\n recordKind: \"delivery-node\",\n diagnosticCode: \"delivery-node-schema-invalid\",\n diagnosticSummary: \"Stored delivery node failed schema validation.\"\n }\n case \"delivery-relationship-schema-invalid\":\n return {\n recordKind: \"delivery-relationship\",\n diagnosticCode: \"delivery-relationship-schema-invalid\",\n diagnosticSummary: \"Stored delivery relationship failed schema validation.\"\n }\n case \"entity-projection-schema-invalid\":\n return {\n recordKind: \"entity-projection\",\n diagnosticCode: \"entity-projection-schema-invalid\",\n diagnosticSummary: \"Stored entity projection failed schema validation.\"\n }\n case \"evidence-claim-schema-invalid\":\n return {\n recordKind: \"evidence-claim\",\n diagnosticCode: \"evidence-claim-schema-invalid\",\n diagnosticSummary: \"Stored evidence claim failed schema validation.\"\n }\n case \"evidence-freshness-schema-invalid\":\n return {\n recordKind: \"evidence-freshness\",\n diagnosticCode: \"evidence-freshness-schema-invalid\",\n diagnosticSummary: \"Stored evidence freshness failed schema validation.\"\n }\n case \"evidence-item-schema-invalid\":\n return {\n recordKind: \"evidence-item\",\n diagnosticCode: \"evidence-item-schema-invalid\",\n diagnosticSummary: \"Stored evidence item failed schema validation.\"\n }\n case \"person-schema-invalid\":\n return error.recordKind === \"person\"\n ? {\n recordKind: \"person\",\n diagnosticCode: \"person-schema-invalid\",\n diagnosticSummary: \"Stored person record failed schema validation.\"\n }\n : null\n case \"schema-decode-failed\":\n return error.recordKind === \"person-avatar\"\n ? {\n recordKind: \"person-avatar\",\n diagnosticCode: \"schema-decode-failed\",\n diagnosticSummary: \"Stored person avatar failed schema validation.\"\n }\n : null\n default:\n return null\n }\n}\n","import * as Schema from \"effect/Schema\"\n\nimport {\n DeliveryEntityProjection,\n DeliveryNode,\n DeliveryRelationship,\n EvidenceClaim,\n EvidenceItem,\n EvidenceValue,\n LedgerRevision,\n RelationshipEndpointKind\n} from \"../../../../domain/deliveryGraph.js\"\nimport { Freshness } from \"../../../../domain/freshness.js\"\nimport {\n AgentId,\n EntityId,\n EnvironmentId,\n EvidenceClaimId,\n EvidenceId,\n GraphNodeId,\n PersonId,\n PluginConnectionId,\n RelationshipId,\n ReleaseId,\n WorkspaceId\n} from \"../../../../domain/identifiers.js\"\nimport { UtcTimestamp } from \"../../../../domain/utcTimestamp.js\"\nimport { PersistedRecordError } from \"../../errors.js\"\nimport { ContentBlobDigest } from \"../models.js\"\n\nexport const DELIVERY_GRAPH_SCHEMA_VERSION = 1\n\nexport const ProjectionRow = Schema.Struct({\n workspaceId: WorkspaceId,\n entityId: EntityId,\n projectionRevision: LedgerRevision,\n sourceEntityRevision: LedgerRevision,\n supersedesProjectionRevision: Schema.NullOr(LedgerRevision),\n projectionSchemaVersion: Schema.Int,\n entityState: Schema.Literals([\"present\", \"deleted\"]),\n entityType: DeliveryEntityProjection.fields.entityType,\n displayKey: Schema.String,\n title: Schema.String,\n extensionJson: Schema.String,\n extensionDigest: ContentBlobDigest,\n recordedAt: Schema.String\n})\n\nexport const ProjectionSummaryRow = Schema.Struct({\n ...ProjectionRow.fields,\n originalExtensionJson: Schema.String\n})\n\nexport const WorkspaceProjectionRow = Schema.Struct({\n ...ProjectionSummaryRow.fields,\n ownerIdentitiesJson: Schema.String,\n releaseIdsJson: Schema.String\n})\n\nexport const NodeRow = Schema.Struct({\n workspaceId: WorkspaceId,\n nodeId: GraphNodeId,\n nodeKeyDigest: ContentBlobDigest,\n nodeKind: Schema.Literals([\"entity\", \"release\", \"environment\"]),\n endpointKind: RelationshipEndpointKind,\n resolutionState: Schema.Literals([\"resolved\", \"missing\"]),\n entityId: Schema.NullOr(EntityId),\n releaseId: Schema.NullOr(ReleaseId),\n environmentId: Schema.NullOr(EnvironmentId),\n expectedEntityKind: Schema.NullOr(DeliveryEntityProjection.fields.entityType),\n missingKey: Schema.NullOr(Schema.String),\n createdAt: Schema.String\n})\n\nexport const EvidenceRow = Schema.Struct({\n workspaceId: WorkspaceId,\n evidenceId: EvidenceId,\n schemaVersion: Schema.Int,\n evidenceDigest: ContentBlobDigest,\n originKind: Schema.Literals([\"plugin\", \"human\", \"agent\", \"system\"]),\n pluginConnectionId: Schema.NullOr(PluginConnectionId),\n sourceEntityId: Schema.NullOr(EntityId),\n sourceEntityRevision: Schema.NullOr(LedgerRevision),\n personId: Schema.NullOr(PersonId),\n agentId: Schema.NullOr(AgentId),\n systemComponent: Schema.NullOr(Schema.String),\n verifierKind: Schema.Literals([\"human\", \"agent\", \"system\"]),\n verifierPersonId: Schema.NullOr(PersonId),\n verifierAgentId: Schema.NullOr(AgentId),\n verifierComponent: Schema.NullOr(Schema.String),\n observedAt: Schema.String,\n recordedAt: Schema.String,\n validUntil: Schema.NullOr(Schema.String),\n freshnessJson: Schema.String,\n freshnessDigest: ContentBlobDigest,\n retentionClass: EvidenceItem.fields.retention.fields.classification,\n retainUntil: Schema.NullOr(Schema.String),\n legalHold: Schema.Number\n})\n\nexport const ClaimRow = Schema.Struct({\n workspaceId: WorkspaceId,\n evidenceClaimId: EvidenceClaimId,\n evidenceId: EvidenceId,\n subjectNodeId: GraphNodeId,\n predicate: EvidenceClaim.fields.predicate,\n valueJson: Schema.String,\n valueDigest: ContentBlobDigest,\n supersedesEvidenceClaimId: Schema.NullOr(EvidenceClaimId),\n recordedAt: Schema.String\n})\n\nexport const RelationshipRow = Schema.Struct({\n workspaceId: WorkspaceId,\n relationshipId: RelationshipId,\n revision: LedgerRevision,\n supersedesRevision: Schema.NullOr(LedgerRevision),\n relationshipSchemaVersion: Schema.Literal(1),\n kind: DeliveryRelationship.fields.kind,\n sourceNodeId: GraphNodeId,\n sourceNodeKind: RelationshipEndpointKind,\n targetNodeId: GraphNodeId,\n targetNodeKind: RelationshipEndpointKind,\n lifecycle: Schema.String,\n lifecycleReason: Schema.NullOr(Schema.String),\n releaseId: Schema.NullOr(ReleaseId),\n environmentId: Schema.NullOr(EnvironmentId),\n confidenceKind: Schema.String,\n confidenceScore: Schema.NullOr(Schema.Number),\n confidenceRationale: Schema.NullOr(Schema.String),\n provenanceKind: Schema.String,\n provenancePluginConnectionId: Schema.NullOr(PluginConnectionId),\n provenanceSourceEntityId: Schema.NullOr(EntityId),\n provenanceSourceEntityRevision: Schema.NullOr(LedgerRevision),\n provenancePersonId: Schema.NullOr(PersonId),\n provenanceAgentId: Schema.NullOr(AgentId),\n provenanceRuleId: Schema.NullOr(Schema.String),\n provenanceRuleVersion: Schema.NullOr(Schema.Int),\n provenanceRationale: Schema.NullOr(Schema.String),\n recordedByKind: Schema.String,\n recordedByPersonId: Schema.NullOr(PersonId),\n recordedByAgentId: Schema.NullOr(AgentId),\n recordedByComponent: Schema.NullOr(Schema.String),\n effectiveAt: Schema.String,\n recordedAt: Schema.String,\n revisionDigest: ContentBlobDigest,\n evidenceClaimIds: Schema.Array(EvidenceClaimId)\n})\n\nexport const projectionJson = Schema.fromJsonString(DeliveryEntityProjection.fields.details)\nexport const evidenceJson = Schema.fromJsonString(EvidenceItem)\nexport const freshnessJson = Schema.fromJsonString(Freshness)\nexport const evidenceValueJson = Schema.fromJsonString(EvidenceValue)\nexport const nodeResolutionJson = Schema.fromJsonString(DeliveryNode.fields.resolution)\nexport const relationshipJson = Schema.fromJsonString(DeliveryRelationship)\nexport const edgeJson = Schema.fromJsonString(Schema.Struct({\n kind: DeliveryRelationship.fields.kind,\n sourceNodeId: GraphNodeId,\n sourceNodeKind: RelationshipEndpointKind,\n targetNodeId: GraphNodeId,\n targetNodeKind: RelationshipEndpointKind,\n scope: DeliveryRelationship.fields.scope\n}))\n\nexport const encodeTimestamp = Schema.encodeSync(UtcTimestamp)\n\nexport const decodeRows = <SchemaType extends Schema.Top>(schema: SchemaType, rows: unknown) =>\n Schema.decodeUnknownEffect(Schema.Array(schema))(rows)\n\nexport const graphRecordError = (\n workspaceId: WorkspaceId,\n recordKind: string,\n recordKey: string,\n diagnosticCode: string\n) => new PersistedRecordError({ workspaceId, recordKind, recordKey, diagnosticCode })\n","import * as Crypto from \"effect/Crypto\"\nimport * as Effect from \"effect/Effect\"\nimport * as Encoding from \"effect/Encoding\"\n\nimport type { WorkspaceId } from \"../../../../domain/identifiers.js\"\nimport { PersistenceOperationError } from \"../../errors.js\"\nimport { ContentBlobDigest } from \"../models.js\"\nimport { graphRecordError } from \"./rows.js\"\n\nexport const makeDeliveryGraphIntegrity = Effect.gen(function*() {\n const cryptoService = yield* Crypto.Crypto\n\n const digestText = Effect.fn(\"DeliveryGraphRepository.digestText\")(function*(value: string) {\n const bytes = yield* Effect.fromResult(\n Encoding.decodeBase64(Encoding.encodeBase64(value))\n ).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"delivery-graph.encode\" }))\n )\n const digest = yield* cryptoService.digest(\"SHA-256\", bytes).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"delivery-graph.digest\" }))\n )\n return ContentBlobDigest.make(Encoding.encodeHex(digest))\n })\n\n const verifyDigest = Effect.fn(\"DeliveryGraphRepository.verifyDigest\")(function*(options: {\n readonly workspaceId: WorkspaceId\n readonly recordKind: string\n readonly recordKey: string\n readonly json: string\n readonly expected: ContentBlobDigest\n }) {\n const actual = yield* digestText(options.json)\n if (actual !== options.expected) {\n return yield* graphRecordError(\n options.workspaceId,\n options.recordKind,\n options.recordKey,\n \"delivery-graph-digest-mismatch\"\n )\n }\n })\n\n return { digestText, verifyDigest }\n})\n","import * as Effect from \"effect/Effect\"\nimport * as Schema from \"effect/Schema\"\n\nimport {\n DeliveryEntityProjection,\n DeliveryNode,\n DeliveryRelationship,\n EvidenceClaim,\n EvidenceItem\n} from \"../../../../domain/deliveryGraph.js\"\nimport { UtcTimestamp } from \"../../../../domain/utcTimestamp.js\"\nimport { PersistenceOperationError } from \"../../errors.js\"\nimport { makeDeliveryGraphIntegrity } from \"./integrity.js\"\nimport {\n type ClaimRow,\n evidenceJson,\n type EvidenceRow,\n evidenceValueJson,\n graphRecordError,\n nodeResolutionJson,\n type NodeRow,\n projectionJson,\n type ProjectionRow,\n type ProjectionSummaryRow,\n relationshipJson,\n type RelationshipRow\n} from \"./rows.js\"\n\nexport const makeDeliveryGraphDecoders = Effect.gen(function*() {\n const { verifyDigest } = yield* makeDeliveryGraphIntegrity\n\n const decodeProjection = Effect.fn(\"DeliveryGraphRepository.decodeProjection\")(function*(\n row: typeof ProjectionRow.Type,\n digestJson: string\n ) {\n yield* verifyDigest({\n workspaceId: row.workspaceId,\n recordKind: \"entity-projection\",\n recordKey: `${row.entityId}:${row.projectionRevision}`,\n json: digestJson,\n expected: row.extensionDigest\n })\n const details = yield* Schema.decodeUnknownEffect(projectionJson)(row.extensionJson).pipe(\n Effect.mapError(() =>\n graphRecordError(\n row.workspaceId,\n \"entity-projection\",\n `${row.entityId}:${row.projectionRevision}`,\n \"entity-projection-schema-invalid\"\n )\n )\n )\n const projection = yield* Schema.decodeUnknownEffect(Schema.toType(DeliveryEntityProjection))({\n workspaceId: row.workspaceId,\n entityId: row.entityId,\n projectionRevision: row.projectionRevision,\n sourceEntityRevision: row.sourceEntityRevision,\n supersedesProjectionRevision: row.supersedesProjectionRevision,\n projectionSchemaVersion: row.projectionSchemaVersion,\n entityState: row.entityState,\n entityType: row.entityType,\n displayKey: row.displayKey,\n title: row.title,\n details\n }).pipe(\n Effect.mapError(() =>\n graphRecordError(\n row.workspaceId,\n \"entity-projection\",\n `${row.entityId}:${row.projectionRevision}`,\n \"entity-projection-schema-invalid\"\n )\n )\n )\n const recordedAt = yield* Schema.decodeUnknownEffect(UtcTimestamp)(row.recordedAt).pipe(\n Effect.mapError(() =>\n graphRecordError(\n row.workspaceId,\n \"entity-projection\",\n `${row.entityId}:${row.projectionRevision}`,\n \"entity-projection-schema-invalid\"\n )\n )\n )\n return { projection, recordedAt }\n })\n\n const decodeProjectionRow = Effect.fn(\"DeliveryGraphRepository.decodeProjectionRow\")(function*(\n row: typeof ProjectionRow.Type\n ) {\n return yield* decodeProjection(row, row.extensionJson)\n })\n\n const decodeProjectionSummaryRow = Effect.fn(\n \"DeliveryGraphRepository.decodeProjectionSummaryRow\"\n )(function*(row: typeof ProjectionSummaryRow.Type) {\n return yield* decodeProjection(row, row.originalExtensionJson)\n })\n\n const decodeNodeRow = Effect.fn(\"DeliveryGraphRepository.decodeNodeRow\")(function*(\n row: typeof NodeRow.Type\n ) {\n const resolution: unknown = row.resolutionState === \"missing\"\n ? {\n _tag: \"missing\",\n expectedKind: row.nodeKind,\n expectedEntityKind: row.expectedEntityKind,\n missingKey: row.missingKey\n }\n : row.nodeKind === \"entity\"\n ? {\n _tag: \"resolved\",\n target: { _tag: \"entity\", entityId: row.entityId, entityKind: row.endpointKind }\n }\n : row.nodeKind === \"release\"\n ? { _tag: \"resolved\", target: { _tag: \"release\", releaseId: row.releaseId } }\n : {\n _tag: \"resolved\",\n target: {\n _tag: \"environment\",\n releaseId: row.releaseId,\n environmentId: row.environmentId\n }\n }\n const node = yield* Schema.decodeUnknownEffect(DeliveryNode)({\n workspaceId: row.workspaceId,\n nodeId: row.nodeId,\n endpointKind: row.endpointKind,\n resolution,\n createdAt: row.createdAt\n }).pipe(\n Effect.mapError(() =>\n graphRecordError(\n row.workspaceId,\n \"delivery-node\",\n row.nodeId,\n \"delivery-node-schema-invalid\"\n )\n )\n )\n const resolutionPayload = yield* Schema.encodeEffect(nodeResolutionJson)(node.resolution).pipe(\n Effect.mapError(() =>\n graphRecordError(\n row.workspaceId,\n \"delivery-node\",\n row.nodeId,\n \"delivery-node-schema-invalid\"\n )\n )\n )\n yield* verifyDigest({\n workspaceId: row.workspaceId,\n recordKind: \"delivery-node\",\n recordKey: row.nodeId,\n json: resolutionPayload,\n expected: row.nodeKeyDigest\n })\n return node\n })\n\n const decodeEvidenceRow = Effect.fn(\"DeliveryGraphRepository.decodeEvidenceRow\")(function*(\n row: typeof EvidenceRow.Type\n ) {\n const attribution: unknown = row.originKind === \"plugin\"\n ? {\n _tag: \"plugin\",\n pluginConnectionId: row.pluginConnectionId,\n sourceEntityId: row.sourceEntityId,\n sourceEntityRevision: row.sourceEntityRevision\n }\n : row.originKind === \"human\"\n ? { _tag: \"human\", personId: row.personId }\n : row.originKind === \"agent\"\n ? { _tag: \"agent\", agentId: row.agentId }\n : { _tag: \"system\", component: row.systemComponent }\n const verifier: unknown = row.verifierKind === \"human\"\n ? { _tag: \"human\", personId: row.verifierPersonId }\n : row.verifierKind === \"agent\"\n ? { _tag: \"agent\", agentId: row.verifierAgentId }\n : { _tag: \"system\", component: row.verifierComponent }\n yield* verifyDigest({\n workspaceId: row.workspaceId,\n recordKind: \"evidence-freshness\",\n recordKey: row.evidenceId,\n json: row.freshnessJson,\n expected: row.freshnessDigest\n })\n const freshness = yield* Schema.decodeUnknownEffect(\n Schema.fromJsonString(Schema.Unknown)\n )(row.freshnessJson).pipe(\n Effect.mapError(() =>\n graphRecordError(\n row.workspaceId,\n \"evidence-item\",\n row.evidenceId,\n \"evidence-freshness-schema-invalid\"\n )\n )\n )\n const evidence = yield* Schema.decodeUnknownEffect(EvidenceItem)({\n workspaceId: row.workspaceId,\n evidenceId: row.evidenceId,\n schemaVersion: row.schemaVersion,\n attribution,\n verifier,\n observedAt: row.observedAt,\n recordedAt: row.recordedAt,\n validUntil: row.validUntil,\n freshness,\n retention: {\n classification: row.retentionClass,\n retainUntil: row.retainUntil,\n legalHold: row.legalHold === 1\n }\n }).pipe(\n Effect.mapError(() =>\n graphRecordError(\n row.workspaceId,\n \"evidence-item\",\n row.evidenceId,\n \"evidence-item-schema-invalid\"\n )\n )\n )\n const payload = yield* Schema.encodeEffect(evidenceJson)(evidence).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"delivery-graph.encode-evidence\" }))\n )\n yield* verifyDigest({\n workspaceId: row.workspaceId,\n recordKind: \"evidence-item\",\n recordKey: row.evidenceId,\n json: payload,\n expected: row.evidenceDigest\n })\n return evidence\n })\n\n const decodeClaimRow = Effect.fn(\"DeliveryGraphRepository.decodeClaimRow\")(function*(\n row: typeof ClaimRow.Type\n ) {\n yield* verifyDigest({\n workspaceId: row.workspaceId,\n recordKind: \"evidence-claim\",\n recordKey: row.evidenceClaimId,\n json: row.valueJson,\n expected: row.valueDigest\n })\n const value = yield* Schema.decodeUnknownEffect(evidenceValueJson)(row.valueJson).pipe(\n Effect.mapError(() =>\n graphRecordError(\n row.workspaceId,\n \"evidence-claim\",\n row.evidenceClaimId,\n \"evidence-claim-schema-invalid\"\n )\n )\n )\n return yield* Schema.decodeUnknownEffect(EvidenceClaim)({\n workspaceId: row.workspaceId,\n evidenceClaimId: row.evidenceClaimId,\n evidenceId: row.evidenceId,\n subjectNodeId: row.subjectNodeId,\n predicate: row.predicate,\n value,\n recordedAt: row.recordedAt,\n supersedesEvidenceClaimId: row.supersedesEvidenceClaimId\n }).pipe(\n Effect.mapError(() =>\n graphRecordError(\n row.workspaceId,\n \"evidence-claim\",\n row.evidenceClaimId,\n \"evidence-claim-schema-invalid\"\n )\n )\n )\n })\n\n const decodeRelationshipRow = Effect.fn(\"DeliveryGraphRepository.decodeRelationshipRow\")(function*(\n row: typeof RelationshipRow.Type\n ) {\n const lifecycle: unknown = row.lifecycle === \"missing\" || row.lifecycle === \"rejected\" ||\n row.lifecycle === \"superseded\"\n ? { _tag: row.lifecycle, effectiveAt: row.effectiveAt, reason: row.lifecycleReason }\n : { _tag: row.lifecycle, effectiveAt: row.effectiveAt }\n const scope: unknown = row.environmentId !== null\n ? { _tag: \"environment\", releaseId: row.releaseId, environmentId: row.environmentId }\n : row.releaseId !== null\n ? { _tag: \"release\", releaseId: row.releaseId }\n : null\n const confidence: unknown = row.confidenceKind === \"inferred\"\n ? {\n _tag: \"inferred\",\n score: row.confidenceScore,\n rationale: row.confidenceRationale\n }\n : row.confidenceKind === \"unknown\"\n ? { _tag: \"unknown\", rationale: row.confidenceRationale }\n : { _tag: row.confidenceKind }\n const provenance: unknown = row.provenanceKind === \"plugin\"\n ? {\n _tag: \"plugin\",\n pluginConnectionId: row.provenancePluginConnectionId,\n sourceEntityId: row.provenanceSourceEntityId,\n sourceEntityRevision: row.provenanceSourceEntityRevision\n }\n : row.provenanceKind === \"human\"\n ? { _tag: \"human\", personId: row.provenancePersonId, rationale: row.provenanceRationale }\n : row.provenanceKind === \"agent\"\n ? { _tag: \"agent\", agentId: row.provenanceAgentId, rationale: row.provenanceRationale }\n : {\n _tag: row.provenanceKind,\n ruleId: row.provenanceRuleId,\n ruleVersion: row.provenanceRuleVersion,\n rationale: row.provenanceRationale\n }\n const recordedBy: unknown = row.recordedByKind === \"human\"\n ? { _tag: \"human\", personId: row.recordedByPersonId }\n : row.recordedByKind === \"agent\"\n ? { _tag: \"agent\", agentId: row.recordedByAgentId }\n : { _tag: row.recordedByKind, component: row.recordedByComponent }\n const relationship = yield* Schema.decodeUnknownEffect(DeliveryRelationship)({\n workspaceId: row.workspaceId,\n relationshipId: row.relationshipId,\n relationshipSchemaVersion: row.relationshipSchemaVersion,\n revision: row.revision,\n supersedesRevision: row.supersedesRevision,\n kind: row.kind,\n sourceNodeId: row.sourceNodeId,\n sourceNodeKind: row.sourceNodeKind,\n targetNodeId: row.targetNodeId,\n targetNodeKind: row.targetNodeKind,\n scope,\n lifecycle,\n confidence,\n provenance,\n recordedBy,\n evidenceClaimIds: row.evidenceClaimIds,\n recordedAt: row.recordedAt\n }).pipe(\n Effect.mapError(() =>\n graphRecordError(\n row.workspaceId,\n \"delivery-relationship\",\n `${row.relationshipId}:${row.revision}`,\n \"delivery-relationship-schema-invalid\"\n )\n )\n )\n const payload = yield* Schema.encodeEffect(relationshipJson)(relationship).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"delivery-graph.encode-relationship\" }))\n )\n yield* verifyDigest({\n workspaceId: row.workspaceId,\n recordKind: \"delivery-relationship\",\n recordKey: `${row.relationshipId}:${row.revision}`,\n json: payload,\n expected: row.revisionDigest\n })\n return relationship\n })\n\n return {\n decodeClaimRow,\n decodeEvidenceRow,\n decodeNodeRow,\n decodeProjectionRow,\n decodeProjectionSummaryRow,\n decodeRelationshipRow\n }\n})\n","interface RelationshipClosureIdentity {\n readonly sourceNodeId: string\n readonly targetNodeId: string\n readonly evidenceClaimIds: ReadonlyArray<string>\n}\n\n/** Deterministic complete prefix whose expanded node and evidence closure stays bounded. */\nexport const selectBoundedRelationshipClosure = <Relationship extends RelationshipClosureIdentity>(\n relationships: ReadonlyArray<Relationship>,\n limits: { readonly relationships: number; readonly nodes: number; readonly evidenceClaims: number }\n): { readonly relationships: ReadonlyArray<Relationship>; readonly truncated: boolean } => {\n const nodes = new Set<string>()\n const evidenceClaims = new Set<string>()\n const selected: Array<Relationship> = []\n\n for (const relationship of relationships) {\n if (selected.length >= limits.relationships) {\n return { relationships: selected, truncated: true }\n }\n const nextNodes = new Set(nodes)\n nextNodes.add(relationship.sourceNodeId)\n nextNodes.add(relationship.targetNodeId)\n const nextEvidenceClaims = new Set(evidenceClaims)\n for (const claimId of relationship.evidenceClaimIds) nextEvidenceClaims.add(claimId)\n if (nextNodes.size > limits.nodes || nextEvidenceClaims.size > limits.evidenceClaims) {\n return { relationships: selected, truncated: true }\n }\n selected.push(relationship)\n nextNodes.forEach((nodeId) => nodes.add(nodeId))\n nextEvidenceClaims.forEach((claimId) => evidenceClaims.add(claimId))\n }\n\n return { relationships: selected, truncated: false }\n}\n","import {\n type RenderedSql,\n renderWorkspaceEntityOwnersQuery,\n renderWorkspaceEntityRelationshipsQuery,\n renderWorkspaceEntityReleasesQuery\n} from \"@knpkv/control-center-sql\"\nimport * as Effect from \"effect/Effect\"\nimport * as Schema from \"effect/Schema\"\n\nimport { derivePersonInitials, PersonAvatar, PersonSourceIdentity, Role } from \"../../../../domain/actors.js\"\nimport { type DeliveryNode, type DeliveryRelationship, LedgerRevision } from \"../../../../domain/deliveryGraph.js\"\nimport type { EntityId, EvidenceId, GraphNodeId, WorkspaceId } from \"../../../../domain/identifiers.js\"\nimport { EvidenceClaimId, PersonId, RelationshipId, ReleaseId } from \"../../../../domain/identifiers.js\"\nimport { Revision } from \"../../../../domain/sourceRevision.js\"\nimport { Database } from \"../../Database.js\"\nimport { RecordNotFoundError } from \"../../errors.js\"\nimport { type DeliveryGraphQuery, DeliveryGraphReadResult } from \"./contract.js\"\nimport { makeDeliveryGraphDecoders } from \"./decode.js\"\nimport { captureMalformedDeliveryGraphRow } from \"./quarantine.js\"\nimport { selectBoundedRelationshipClosure } from \"./release-slice.js\"\nimport {\n ClaimRow,\n decodeRows,\n EvidenceRow,\n graphRecordError,\n NodeRow,\n ProjectionSummaryRow,\n RelationshipRow,\n WorkspaceProjectionRow\n} from \"./rows.js\"\n\nconst WorkspaceProjectionCountRow = Schema.Struct({\n matchedCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n totalCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))\n})\nconst SourceProjectionRow = Schema.Struct({\n ...ProjectionSummaryRow.fields,\n sourceRevision: Revision\n})\n\nconst WorkspaceProjectionReleaseIds = Schema.fromJsonString(Schema.Array(ReleaseId))\nconst WorkspaceOwnerIdentity = Schema.Struct({\n avatarJson: Schema.String,\n displayName: Schema.String,\n personId: PersonId,\n rolesCsv: Schema.String\n})\nconst WorkspaceOwnerIdentities = Schema.fromJsonString(Schema.Array(WorkspaceOwnerIdentity))\nconst WorkspaceOwnerOptionRow = WorkspaceOwnerIdentity\nconst WorkspaceOwnerRoleRow = Schema.Struct({\n avatarJson: Schema.String,\n displayName: Schema.String,\n personId: PersonId,\n role: Role\n})\nconst WorkspaceEntityRelationshipIdentity = Schema.Struct({ relationshipId: RelationshipId })\nconst WorkspaceEntityReleaseIdentity = Schema.Struct({ releaseId: Schema.NullOr(ReleaseId) })\nconst PersonAvatarJson = Schema.fromJsonString(PersonAvatar)\nconst WorkspaceOwnerDisplayName = Schema.String.check(\n Schema.isTrimmed(),\n Schema.isNonEmpty(),\n Schema.isMaxLength(200)\n)\nconst WorkspaceOwnerRoles = Schema.Array(Role).check(\n Schema.isMinLength(1),\n Schema.isMaxLength(16),\n Schema.isUnique()\n)\n\nconst decodeWorkspaceOwner = Effect.fn(\"DeliveryGraphRepository.decodeWorkspaceOwner\")(function*(\n workspaceId: WorkspaceId,\n owner: typeof WorkspaceOwnerIdentity.Type\n) {\n const displayName = yield* Schema.decodeUnknownEffect(WorkspaceOwnerDisplayName)(owner.displayName).pipe(\n Effect.mapError(() => graphRecordError(workspaceId, \"person\", owner.personId, \"person-schema-invalid\"))\n )\n const avatar = yield* Schema.decodeUnknownEffect(PersonAvatarJson)(owner.avatarJson).pipe(\n Effect.mapError(() => graphRecordError(workspaceId, \"person-avatar\", owner.personId, \"schema-decode-failed\"))\n )\n const roles = yield* Schema.decodeUnknownEffect(WorkspaceOwnerRoles)(\n owner.rolesCsv.split(\",\").sort()\n ).pipe(\n Effect.mapError(() => graphRecordError(workspaceId, \"person\", owner.personId, \"person-schema-invalid\"))\n )\n return {\n avatarFallback: avatar._tag === \"initials\" ? avatar.text : derivePersonInitials(displayName),\n displayName,\n personId: owner.personId,\n roles\n }\n})\n\nexport const makeDeliveryGraphReader = Effect.gen(function*() {\n const database = yield* Database\n const sql = database.sql\n const {\n decodeClaimRow,\n decodeEvidenceRow,\n decodeNodeRow,\n decodeProjectionRow,\n decodeProjectionSummaryRow,\n decodeRelationshipRow\n } = yield* makeDeliveryGraphDecoders\n\n const summaryExtensionJson = sql`CASE WHEN entity.entity_type = 'page'\n AND json_valid(projection.extension_json)\n THEN json_set(\n projection.extension_json,\n '$.content', json('null'),\n '$.contentState', 'lazy'\n )\n ELSE projection.extension_json\n END`\n\n const executePlan = Effect.fn(\"DeliveryGraphRepository.executePlan\")(function*<RowSchema extends Schema.Top>(\n plan: RenderedSql,\n schema: RowSchema\n ) {\n const rows = yield* sql.unsafe(plan.sql, [...plan.params])\n return yield* decodeRows(schema, rows)\n })\n\n const loadProjection = Effect.fn(\"DeliveryGraphRepository.loadProjection\")(function*(\n workspaceId: WorkspaceId,\n entityId: EntityId,\n revision: LedgerRevision | null,\n content: \"exact\" | \"summary\"\n ) {\n const extensionJson = content === \"exact\" ? sql`projection.extension_json` : summaryExtensionJson\n const rows = yield* sql`SELECT\n projection.workspace_id AS workspaceId,\n projection.entity_id AS entityId,\n projection.projection_revision AS projectionRevision,\n projection.source_entity_revision AS sourceEntityRevision,\n projection.supersedes_projection_revision AS supersedesProjectionRevision,\n projection.projection_schema_version AS projectionSchemaVersion,\n projection.entity_state AS entityState,\n CASE entity.entity_type\n WHEN 'pipeline' THEN 'pipeline-execution'\n ELSE entity.entity_type\n END AS entityType,\n projection.display_key AS displayKey,\n projection.title,\n ${extensionJson} AS extensionJson,\n projection.extension_json AS originalExtensionJson,\n projection.extension_digest AS extensionDigest,\n projection.recorded_at AS recordedAt\n FROM entity_projection_revisions projection\n INNER JOIN entities entity\n ON entity.workspace_id = projection.workspace_id\n AND entity.entity_id = projection.entity_id\n WHERE projection.workspace_id = ${workspaceId}\n AND projection.entity_id = ${entityId}\n AND (${revision} IS NULL OR projection.projection_revision = ${revision})\n ORDER BY projection.projection_revision DESC\n LIMIT 1`\n const decoded = yield* decodeRows(ProjectionSummaryRow, rows).pipe(\n Effect.mapError(() =>\n graphRecordError(\n workspaceId,\n \"entity-projection\",\n entityId,\n \"entity-projection-schema-invalid\"\n )\n ),\n captureMalformedDeliveryGraphRow(rows)\n )\n const row = decoded[0]\n if (row === undefined) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"entity-projection\",\n recordKey: revision === null ? entityId : `${entityId}:${revision}`\n })\n }\n const decode = content === \"exact\" ? decodeProjectionRow : decodeProjectionSummaryRow\n return yield* decode(row).pipe(captureMalformedDeliveryGraphRow(row))\n })\n\n const loadSourceProjection = Effect.fn(\"DeliveryGraphRepository.loadSourceProjection\")(function*(\n workspaceId: WorkspaceId,\n query: Extract<DeliveryGraphQuery, { readonly _tag: \"sourceEntityProjection\" }>\n ) {\n const rows = yield* sql`SELECT\n projection.workspace_id AS workspaceId,\n projection.entity_id AS entityId,\n projection.projection_revision AS projectionRevision,\n projection.source_entity_revision AS sourceEntityRevision,\n projection.supersedes_projection_revision AS supersedesProjectionRevision,\n projection.projection_schema_version AS projectionSchemaVersion,\n projection.entity_state AS entityState,\n CASE entity.entity_type\n WHEN 'pipeline' THEN 'pipeline-execution'\n ELSE entity.entity_type\n END AS entityType,\n projection.display_key AS displayKey,\n projection.title,\n projection.extension_json AS extensionJson,\n projection.extension_json AS originalExtensionJson,\n projection.extension_digest AS extensionDigest,\n projection.recorded_at AS recordedAt,\n source.source_revision AS sourceRevision\n FROM entity_projection_revisions projection\n INNER JOIN entities entity\n ON entity.workspace_id = projection.workspace_id\n AND entity.entity_id = projection.entity_id\n INNER JOIN entity_revisions source\n ON source.workspace_id = projection.workspace_id\n AND source.entity_id = projection.entity_id\n AND source.revision = projection.source_entity_revision\n WHERE projection.workspace_id = ${workspaceId}\n AND entity.plugin_connection_id = ${query.pluginConnectionId}\n AND entity.provider_id = ${query.providerId}\n AND entity.vendor_immutable_id = ${query.vendorImmutableId}\n AND source.source_revision = ${query.revision}\n ORDER BY projection.projection_revision DESC\n LIMIT 1`\n const decoded = yield* decodeRows(SourceProjectionRow, rows).pipe(\n Effect.mapError(() =>\n graphRecordError(workspaceId, \"entity-projection\", query.vendorImmutableId, \"entity-projection-schema-invalid\")\n ),\n captureMalformedDeliveryGraphRow(rows)\n )\n const row = decoded[0]\n if (row === undefined) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"entity-source-projection\",\n recordKey: query.vendorImmutableId\n })\n }\n const value = yield* decodeProjectionRow(row).pipe(captureMalformedDeliveryGraphRow(row))\n return { ...value, sourceRevision: row.sourceRevision }\n })\n\n const loadNode = Effect.fn(\"DeliveryGraphRepository.loadNode\")(function*(\n workspaceId: WorkspaceId,\n nodeId: GraphNodeId\n ) {\n const rows = yield* sql`SELECT\n workspace_id AS workspaceId, node_id AS nodeId, node_key_digest AS nodeKeyDigest,\n node_kind AS nodeKind, endpoint_kind AS endpointKind,\n resolution_state AS resolutionState, entity_id AS entityId,\n release_id AS releaseId, environment_id AS environmentId,\n expected_entity_kind AS expectedEntityKind, missing_key AS missingKey, created_at AS createdAt\n FROM delivery_nodes\n WHERE workspace_id = ${workspaceId} AND node_id = ${nodeId}`\n const decoded = yield* decodeRows(NodeRow, rows).pipe(\n Effect.mapError(() =>\n graphRecordError(\n workspaceId,\n \"delivery-node\",\n nodeId,\n \"delivery-node-schema-invalid\"\n )\n ),\n captureMalformedDeliveryGraphRow(rows)\n )\n const row = decoded[0]\n if (row === undefined) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"delivery-node\",\n recordKey: nodeId\n })\n }\n return yield* decodeNodeRow(row).pipe(captureMalformedDeliveryGraphRow(row))\n })\n\n const loadEvidence = Effect.fn(\"DeliveryGraphRepository.loadEvidence\")(function*(\n workspaceId: WorkspaceId,\n evidenceId: EvidenceId\n ) {\n const rows = yield* sql`SELECT\n workspace_id AS workspaceId, evidence_id AS evidenceId, schema_version AS schemaVersion,\n evidence_digest AS evidenceDigest, origin_kind AS originKind,\n plugin_connection_id AS pluginConnectionId, source_entity_id AS sourceEntityId,\n source_entity_revision AS sourceEntityRevision, person_id AS personId, agent_id AS agentId,\n system_component AS systemComponent, verifier_kind AS verifierKind,\n verifier_person_id AS verifierPersonId, verifier_agent_id AS verifierAgentId,\n verifier_component AS verifierComponent, observed_at AS observedAt, recorded_at AS recordedAt,\n valid_until AS validUntil, freshness_json AS freshnessJson,\n freshness_digest AS freshnessDigest, retention_class AS retentionClass, retain_until AS retainUntil,\n legal_hold AS legalHold\n FROM evidence_items\n WHERE workspace_id = ${workspaceId} AND evidence_id = ${evidenceId}`\n const decoded = yield* decodeRows(EvidenceRow, rows).pipe(\n Effect.mapError(() =>\n graphRecordError(\n workspaceId,\n \"evidence-item\",\n evidenceId,\n \"evidence-item-schema-invalid\"\n )\n ),\n captureMalformedDeliveryGraphRow(rows)\n )\n const row = decoded[0]\n if (row === undefined) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"evidence-item\",\n recordKey: evidenceId\n })\n }\n return yield* decodeEvidenceRow(row).pipe(captureMalformedDeliveryGraphRow(row))\n })\n\n const loadClaim = Effect.fn(\"DeliveryGraphRepository.loadClaim\")(function*(\n workspaceId: WorkspaceId,\n evidenceClaimId: EvidenceClaimId\n ) {\n const rows = yield* sql`SELECT\n workspace_id AS workspaceId, evidence_claim_id AS evidenceClaimId,\n evidence_id AS evidenceId, subject_node_id AS subjectNodeId, predicate,\n value_json AS valueJson, value_digest AS valueDigest,\n supersedes_claim_id AS supersedesEvidenceClaimId, recorded_at AS recordedAt\n FROM evidence_claims\n WHERE workspace_id = ${workspaceId} AND evidence_claim_id = ${evidenceClaimId}`\n const decoded = yield* decodeRows(ClaimRow, rows).pipe(\n Effect.mapError(() =>\n graphRecordError(\n workspaceId,\n \"evidence-claim\",\n evidenceClaimId,\n \"evidence-claim-schema-invalid\"\n )\n ),\n captureMalformedDeliveryGraphRow(rows)\n )\n const row = decoded[0]\n if (row === undefined) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"evidence-claim\",\n recordKey: evidenceClaimId\n })\n }\n return yield* decodeClaimRow(row).pipe(captureMalformedDeliveryGraphRow(row))\n })\n\n const listClaimsForEvidence = Effect.fn(\"DeliveryGraphRepository.listClaimsForEvidence\")(function*(\n workspaceId: WorkspaceId,\n evidenceId: EvidenceId,\n limit: number\n ) {\n const identities = yield* sql`SELECT evidence_claim_id AS evidenceClaimId\n FROM evidence_claims\n WHERE workspace_id = ${workspaceId} AND evidence_id = ${evidenceId}\n ORDER BY recorded_at, evidence_claim_id\n LIMIT ${limit}`\n const decoded = yield* decodeRows(Schema.Struct({ evidenceClaimId: EvidenceClaimId }), identities)\n return yield* Effect.forEach(decoded, ({ evidenceClaimId }) => loadClaim(workspaceId, evidenceClaimId))\n })\n\n const loadRelationship = Effect.fn(\"DeliveryGraphRepository.loadRelationship\")(function*(\n workspaceId: WorkspaceId,\n relationshipId: RelationshipId,\n revision: LedgerRevision | null\n ) {\n const rows = yield* sql`SELECT\n revision.workspace_id AS workspaceId, revision.relationship_id AS relationshipId,\n revision.revision, revision.supersedes_revision AS supersedesRevision,\n revision.schema_version AS relationshipSchemaVersion, revision.kind,\n revision.source_node_id AS sourceNodeId, revision.source_node_kind AS sourceNodeKind,\n revision.target_node_id AS targetNodeId, revision.target_node_kind AS targetNodeKind,\n revision.lifecycle, revision.lifecycle_reason AS lifecycleReason,\n revision.release_id AS releaseId, revision.environment_id AS environmentId,\n revision.confidence_kind AS confidenceKind, revision.confidence_score AS confidenceScore,\n revision.confidence_rationale AS confidenceRationale,\n revision.provenance_kind AS provenanceKind,\n revision.provenance_plugin_connection_id AS provenancePluginConnectionId,\n revision.provenance_source_entity_id AS provenanceSourceEntityId,\n revision.provenance_source_entity_revision AS provenanceSourceEntityRevision,\n revision.provenance_person_id AS provenancePersonId,\n revision.provenance_agent_id AS provenanceAgentId,\n revision.provenance_rule_id AS provenanceRuleId,\n revision.provenance_rule_version AS provenanceRuleVersion,\n revision.provenance_rationale AS provenanceRationale,\n revision.recorded_by_kind AS recordedByKind,\n revision.recorded_by_person_id AS recordedByPersonId,\n revision.recorded_by_agent_id AS recordedByAgentId,\n revision.recorded_by_component AS recordedByComponent,\n revision.effective_at AS effectiveAt, revision.recorded_at AS recordedAt,\n revision.revision_digest AS revisionDigest, NULL AS evidenceClaimIds\n FROM relationship_revisions revision\n INNER JOIN relationship_heads head\n ON head.workspace_id = revision.workspace_id\n AND head.relationship_id = revision.relationship_id\n WHERE revision.workspace_id = ${workspaceId}\n AND revision.relationship_id = ${relationshipId}\n AND revision.revision = COALESCE(${revision}, head.current_revision)\n LIMIT 1`\n const baseSchema = Schema.Struct({ ...RelationshipRow.fields, evidenceClaimIds: Schema.Null })\n const decoded = yield* decodeRows(baseSchema, rows).pipe(\n Effect.mapError(() =>\n graphRecordError(\n workspaceId,\n \"delivery-relationship\",\n relationshipId,\n \"delivery-relationship-schema-invalid\"\n )\n ),\n captureMalformedDeliveryGraphRow(rows)\n )\n const row = decoded[0]\n if (row === undefined) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"delivery-relationship\",\n recordKey: revision === null ? relationshipId : `${relationshipId}:${revision}`\n })\n }\n const evidenceRows = yield* sql`SELECT evidence_claim_id AS evidenceClaimId\n FROM relationship_revision_evidence\n WHERE workspace_id = ${workspaceId}\n AND relationship_id = ${relationshipId}\n AND relationship_revision = ${row.revision}\n ORDER BY evidence_claim_id`\n const evidenceClaimIds = (yield* decodeRows(\n Schema.Struct({ evidenceClaimId: EvidenceClaimId }),\n evidenceRows\n )).map(({ evidenceClaimId }) => evidenceClaimId)\n const persistedRow = { ...row, evidenceClaimIds }\n return yield* decodeRelationshipRow(persistedRow).pipe(\n captureMalformedDeliveryGraphRow(persistedRow)\n )\n })\n\n const loadWorkspaceEntityOwners = Effect.fn(\"DeliveryGraphRepository.loadWorkspaceEntityOwners\")(function*(\n workspaceId: WorkspaceId,\n entityId: EntityId\n ) {\n const rows = yield* executePlan(\n renderWorkspaceEntityOwnersQuery({ workspaceId, entityId }),\n WorkspaceOwnerRoleRow\n )\n const identities = new Map<PersonId, {\n readonly avatarJson: string\n readonly displayName: string\n readonly personId: PersonId\n readonly roles: Set<Role>\n }>()\n for (const row of rows) {\n const existing = identities.get(row.personId)\n if (existing === undefined) {\n identities.set(row.personId, { ...row, roles: new Set([row.role]) })\n } else {\n existing.roles.add(row.role)\n }\n }\n const candidates = [...identities.values()]\n const owners = yield* Effect.forEach(candidates.slice(0, 20), (owner) =>\n Effect.gen(function*() {\n const decoded = yield* decodeWorkspaceOwner(workspaceId, {\n avatarJson: owner.avatarJson,\n displayName: owner.displayName,\n personId: owner.personId,\n rolesCsv: [...owner.roles].sort().join(\",\")\n })\n const identityRows = yield* sql<Record<string, unknown>>`SELECT\n identity.plugin_connection_id AS pluginConnectionId,\n identity.provider_id AS providerId,\n identity.vendor_person_id AS vendorPersonId\n FROM person_identities AS identity\n WHERE identity.workspace_id = ${workspaceId}\n AND identity.person_id = ${owner.personId}\n AND EXISTS (\n SELECT 1\n FROM entities AS entity\n WHERE entity.workspace_id = ${workspaceId}\n AND entity.entity_id = ${entityId}\n AND entity.provider_id = identity.provider_id\n AND entity.plugin_connection_id = identity.plugin_connection_id\n )\n ORDER BY identity.vendor_person_id\n LIMIT 16`\n const sourceIdentities = yield* decodeRows(PersonSourceIdentity, identityRows).pipe(\n Effect.mapError(() => graphRecordError(workspaceId, \"person\", owner.personId, \"person-schema-invalid\")),\n captureMalformedDeliveryGraphRow(identityRows)\n )\n return sourceIdentities.length === 0 ? decoded : { ...decoded, sourceIdentities }\n }))\n return { owners, ownersTruncated: candidates.length > 20 }\n })\n\n const loadWorkspaceEntityReleaseIds = Effect.fn(\n \"DeliveryGraphRepository.loadWorkspaceEntityReleaseIds\"\n )(function*(workspaceId: WorkspaceId, entityId: EntityId) {\n const rows = yield* executePlan(\n renderWorkspaceEntityReleasesQuery({ workspaceId, entityId }),\n WorkspaceEntityReleaseIdentity\n )\n const releaseIds = rows.flatMap(({ releaseId }): ReadonlyArray<ReleaseId> => releaseId === null ? [] : [releaseId])\n return {\n releaseIds: releaseIds.slice(0, 500),\n releaseMembershipsTruncated: releaseIds.length > 500\n }\n })\n\n const hydrateRelationshipClosure = Effect.fn(\n \"DeliveryGraphRepository.hydrateRelationshipClosure\"\n )(function*(\n workspaceId: WorkspaceId,\n candidateRelationships: ReadonlyArray<DeliveryRelationship>,\n bounds: { readonly relationships: number; readonly nodes: number; readonly evidenceClaims: number },\n projectionPolicy: (nodes: ReadonlyArray<DeliveryNode>) => ReadonlyArray<EntityId>\n ) {\n const bounded = selectBoundedRelationshipClosure(candidateRelationships, bounds)\n const relationships = bounded.relationships\n const nodeIds = Array.from(\n new Set(relationships.flatMap(({ sourceNodeId, targetNodeId }) => [sourceNodeId, targetNodeId]))\n )\n const nodes = yield* Effect.forEach(nodeIds, (nodeId) => loadNode(workspaceId, nodeId))\n const entityProjections = yield* Effect.forEach(\n projectionPolicy(nodes),\n (entityId) => loadProjection(workspaceId, entityId, null, \"summary\")\n )\n const claimIds = Array.from(\n new Set(relationships.flatMap(({ evidenceClaimIds }) => evidenceClaimIds))\n )\n const evidenceClaims = yield* Effect.forEach(\n claimIds,\n (evidenceClaimId) => loadClaim(workspaceId, evidenceClaimId)\n )\n const evidenceIds = Array.from(new Set(evidenceClaims.map(({ evidenceId }) => evidenceId)))\n const evidenceItems = yield* Effect.forEach(\n evidenceIds,\n (evidenceId) => loadEvidence(workspaceId, evidenceId)\n )\n return {\n entityProjections,\n evidenceClaims,\n evidenceItems,\n nodes,\n relationships,\n truncated: bounded.truncated\n }\n })\n\n const readDecoded = Effect.fn(\"DeliveryGraphRepository.readDecoded\")(function*(\n workspaceId: WorkspaceId,\n query: DeliveryGraphQuery\n ) {\n switch (query._tag) {\n case \"entityProjection\":\n return DeliveryGraphReadResult.make({\n _tag: \"entityProjection\",\n value: yield* loadProjection(workspaceId, query.entityId, query.revision, \"exact\")\n })\n case \"sourceEntityProjection\":\n return DeliveryGraphReadResult.make({\n _tag: \"sourceEntityProjection\",\n value: yield* loadSourceProjection(workspaceId, query)\n })\n case \"node\":\n return DeliveryGraphReadResult.make({\n _tag: \"node\",\n value: yield* loadNode(workspaceId, query.nodeId)\n })\n case \"evidence\": {\n const evidence = yield* loadEvidence(workspaceId, query.evidenceId)\n const claims = yield* listClaimsForEvidence(workspaceId, query.evidenceId, query.limit)\n return DeliveryGraphReadResult.make({ _tag: \"evidence\", value: { evidence, claims } })\n }\n case \"relationship\":\n return DeliveryGraphReadResult.make({\n _tag: \"relationship\",\n value: yield* loadRelationship(workspaceId, query.relationshipId, query.revision)\n })\n case \"relationshipHistory\": {\n const rows = yield* sql`SELECT revision\n FROM relationship_revisions\n WHERE workspace_id = ${workspaceId} AND relationship_id = ${query.relationshipId}\n ORDER BY revision DESC LIMIT ${query.limit}`\n const revisions = yield* decodeRows(Schema.Struct({ revision: LedgerRevision }), rows)\n if (revisions.length === 0) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"delivery-relationship\",\n recordKey: query.relationshipId\n })\n }\n const value = yield* Effect.forEach(\n revisions,\n ({ revision }) => loadRelationship(workspaceId, query.relationshipId, revision)\n )\n return DeliveryGraphReadResult.make({ _tag: \"relationshipHistory\", value })\n }\n case \"entitySlice\": {\n const projection = yield* loadProjection(workspaceId, query.entityId, null, \"exact\")\n if (projection.projection.entityState === \"deleted\") {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"entity-projection\",\n recordKey: query.entityId\n })\n }\n const { owners, ownersTruncated } = yield* loadWorkspaceEntityOwners(workspaceId, query.entityId)\n const { releaseIds, releaseMembershipsTruncated } = yield* loadWorkspaceEntityReleaseIds(\n workspaceId,\n query.entityId\n )\n const identityRows = yield* executePlan(\n renderWorkspaceEntityRelationshipsQuery({\n workspaceId,\n entityId: query.entityId,\n limit: query.limit + 1\n }),\n WorkspaceEntityRelationshipIdentity\n )\n const candidateRelationships = yield* Effect.forEach(\n identityRows.slice(0, query.limit),\n ({ relationshipId }) => loadRelationship(workspaceId, relationshipId, null)\n )\n const closure = yield* hydrateRelationshipClosure(workspaceId, candidateRelationships, {\n relationships: query.limit,\n nodes: 200,\n evidenceClaims: 200\n }, (nodes) => {\n const relatedEntityIds = new Set<EntityId>()\n for (const node of nodes) {\n if (node.resolution._tag !== \"resolved\" || node.resolution.target._tag !== \"entity\") continue\n if (node.resolution.target.entityId !== query.entityId) {\n relatedEntityIds.add(node.resolution.target.entityId)\n }\n }\n return [...relatedEntityIds]\n })\n return DeliveryGraphReadResult.make({\n _tag: \"entitySlice\",\n value: {\n entity: {\n canonicalReleaseId: releaseIds[0] ?? null,\n owners,\n ownersTruncated,\n releaseIds,\n releaseMembershipsTruncated,\n ...projection\n },\n truncated: identityRows.length > query.limit || closure.truncated,\n nodes: closure.nodes,\n relatedEntityProjections: closure.entityProjections,\n relationships: closure.relationships,\n evidenceClaims: closure.evidenceClaims,\n evidenceItems: closure.evidenceItems\n }\n })\n }\n case \"nodeRelationships\": {\n const identityRows = yield* sql`SELECT relationship_id AS relationshipId FROM (\n SELECT revision.relationship_id\n FROM relationship_revisions revision\n INNER JOIN relationship_heads head\n ON head.workspace_id = revision.workspace_id\n AND head.relationship_id = revision.relationship_id\n AND head.current_revision = revision.revision\n WHERE revision.workspace_id = ${workspaceId}\n AND revision.source_node_id = ${query.nodeId}\n AND revision.lifecycle NOT IN ('rejected', 'superseded')\n UNION\n SELECT revision.relationship_id\n FROM relationship_revisions revision\n INNER JOIN relationship_heads head\n ON head.workspace_id = revision.workspace_id\n AND head.relationship_id = revision.relationship_id\n AND head.current_revision = revision.revision\n WHERE revision.workspace_id = ${workspaceId}\n AND revision.target_node_id = ${query.nodeId}\n AND revision.lifecycle NOT IN ('rejected', 'superseded')\n )\n ORDER BY relationship_id\n LIMIT ${query.limit + 1}`\n const identities = yield* decodeRows(Schema.Struct({ relationshipId: RelationshipId }), identityRows)\n const relationships = yield* Effect.forEach(\n identities.slice(0, query.limit),\n ({ relationshipId }) => loadRelationship(workspaceId, relationshipId, null)\n )\n return DeliveryGraphReadResult.make({\n _tag: \"nodeRelationships\",\n value: {\n nodeId: query.nodeId,\n truncated: identities.length > query.limit,\n relationships\n }\n })\n }\n case \"releaseSlice\": {\n const identityLimit = query.limit + 1\n const identityRows = query.environmentId === null\n ? yield* sql`SELECT revision.relationship_id AS relationshipId\n FROM relationship_revisions revision\n INNER JOIN relationship_heads head\n ON head.workspace_id = revision.workspace_id\n AND head.relationship_id = revision.relationship_id\n AND head.current_revision = revision.revision\n WHERE revision.workspace_id = ${workspaceId}\n AND revision.release_id = ${query.releaseId}\n AND revision.environment_id IS NULL\n AND revision.lifecycle NOT IN ('rejected', 'superseded')\n ORDER BY revision.recorded_at DESC\n LIMIT ${identityLimit}`\n : yield* sql`SELECT revision.relationship_id AS relationshipId\n FROM relationship_revisions revision\n INNER JOIN relationship_heads head\n ON head.workspace_id = revision.workspace_id\n AND head.relationship_id = revision.relationship_id\n AND head.current_revision = revision.revision\n WHERE revision.workspace_id = ${workspaceId}\n AND revision.release_id = ${query.releaseId}\n AND revision.environment_id = ${query.environmentId}\n AND revision.lifecycle NOT IN ('rejected', 'superseded')\n ORDER BY revision.recorded_at DESC\n LIMIT ${identityLimit}`\n const identities = yield* decodeRows(Schema.Struct({ relationshipId: RelationshipId }), identityRows)\n const candidateRelationships = yield* Effect.forEach(\n identities.slice(0, query.limit),\n ({ relationshipId }) => loadRelationship(workspaceId, relationshipId, null)\n )\n const closure = yield* hydrateRelationshipClosure(workspaceId, candidateRelationships, {\n relationships: query.limit,\n nodes: 500,\n evidenceClaims: 500\n }, (nodes) =>\n nodes.flatMap((node): ReadonlyArray<EntityId> => {\n if (node.resolution._tag !== \"resolved\" || node.resolution.target._tag !== \"entity\") return []\n return [node.resolution.target.entityId]\n }))\n return DeliveryGraphReadResult.make({\n _tag: \"releaseSlice\",\n value: {\n releaseId: query.releaseId,\n environmentId: query.environmentId,\n truncated: identities.length > query.limit || closure.truncated,\n nodes: closure.nodes,\n entityProjections: closure.entityProjections,\n relationships: closure.relationships,\n evidenceClaims: closure.evidenceClaims,\n evidenceItems: closure.evidenceItems\n }\n })\n }\n case \"componentRelationships\": {\n const identityRows = yield* sql`SELECT revision.relationship_id AS relationshipId\n FROM relationship_revisions revision\n INNER JOIN relationship_heads head\n ON head.workspace_id = revision.workspace_id\n AND head.relationship_id = revision.relationship_id\n AND head.current_revision = revision.revision\n WHERE revision.workspace_id = ${workspaceId}\n AND (${query.releaseId} IS NULL OR revision.release_id = ${query.releaseId})\n AND revision.environment_id IS NULL\n AND revision.lifecycle NOT IN ('rejected', 'superseded')\n AND revision.recorded_by_kind = 'system'\n AND revision.recorded_by_component = ${query.component}\n ORDER BY revision.relationship_id\n LIMIT ${query.limit + 1}`\n const identities = yield* decodeRows(Schema.Struct({ relationshipId: RelationshipId }), identityRows)\n const relationships = yield* Effect.forEach(\n identities.slice(0, query.limit),\n ({ relationshipId }) => loadRelationship(workspaceId, relationshipId, null)\n )\n return DeliveryGraphReadResult.make({\n _tag: \"componentRelationships\",\n value: {\n releaseId: query.releaseId,\n truncated: identities.length > query.limit,\n relationships\n }\n })\n }\n case \"workspaceEntityProjections\": {\n const rowLimit = query.limit + 1\n const ownerRole = sql`assignment.role IN (\n 'change-owner', 'issue-owner', 'issue-assignee', 'page-owner', 'author', 'operator',\n 'contributor', 'reviewer', 'watcher', 'deployment-approver', 'merge-approver'\n )`\n const activeOwner = sql`assignment.workspace_id = projection.workspace_id\n AND assignment.entity_id = projection.entity_id\n AND assignment.scope_kind = 'entity'\n AND assignment.actor_kind = 'human'\n AND assignment.lifecycle_kind = 'active'\n AND ${ownerRole}`\n const entityType = sql`CASE entity.entity_type\n WHEN 'pipeline' THEN 'pipeline-execution'\n ELSE entity.entity_type\n END`\n const service = sql`CASE ${entityType}\n WHEN 'issue' THEN 'jira'\n WHEN 'pull-request' THEN 'codecommit'\n WHEN 'page' THEN 'confluence'\n WHEN 'pipeline-execution' THEN 'codepipeline'\n WHEN 'deployment' THEN 'codepipeline'\n WHEN 'time-entry' THEN 'clockify'\n END`\n const rawStatusText = sql`lower(COALESCE(\n json_extract(projection.extension_json, '$.status'),\n json_extract(projection.extension_json, '$.reviewState'),\n json_extract(projection.extension_json, '$.approvalState'),\n ''\n ))`\n const statusText = sql`CASE ${entityType}\n WHEN 'issue' THEN ${rawStatusText}\n ELSE replace(${rawStatusText}, '-', ' ')\n END`\n const pullRequestReviewText = sql`replace(lower(COALESCE(\n json_extract(projection.extension_json, '$.reviewState'),\n ''\n )), '-', ' ')`\n const pullRequestLifecycleText = sql`lower(COALESCE(\n json_extract(projection.extension_json, '$.lifecycle'),\n ''\n ))`\n const pullRequestSearchStatusText = sql`trim(\n CASE ${pullRequestReviewText}\n WHEN 'not requested' THEN 'review not requested'\n WHEN 'requested' THEN 'review requested'\n ELSE ${pullRequestReviewText}\n END || ' ' || ${pullRequestLifecycleText}\n )`\n const searchStatusText = sql`CASE ${entityType}\n WHEN 'pull-request' THEN ${pullRequestSearchStatusText}\n ELSE ${statusText}\n END`\n const statusGroup = sql`CASE ${entityType}\n WHEN 'issue' THEN CASE\n WHEN ${statusText} IN ('blocked', 'rejected') THEN 'failed'\n WHEN ${statusText} IN ('closed', 'done', 'resolved') THEN 'done'\n ELSE 'active'\n END\n WHEN 'pull-request' THEN CASE\n WHEN ${pullRequestReviewText} = 'changes requested' THEN 'failed'\n WHEN ${pullRequestReviewText} IN ('approved', 'merged') THEN 'done'\n WHEN ${pullRequestLifecycleText} IN ('closed', 'merged') THEN 'done'\n ELSE 'active'\n END\n WHEN 'page' THEN CASE\n WHEN ${statusText} = 'superseded' THEN 'failed'\n WHEN ${statusText} = 'current' THEN 'done'\n ELSE 'active'\n END\n WHEN 'pipeline-execution' THEN CASE\n WHEN ${statusText} IN ('failed', 'stopped') THEN 'failed'\n WHEN ${statusText} = 'succeeded' THEN 'done'\n ELSE 'active'\n END\n WHEN 'deployment' THEN CASE\n WHEN ${statusText} IN ('failed', 'rolled back') THEN 'failed'\n WHEN ${statusText} = 'succeeded' THEN 'done'\n ELSE 'active'\n END\n WHEN 'time-entry' THEN CASE\n WHEN ${statusText} = 'rejected' THEN 'failed'\n WHEN ${statusText} IN ('approved', 'not required') THEN 'done'\n ELSE 'active'\n END\n END`\n const isCurrent = sql`projection.workspace_id = ${workspaceId}\n AND projection.entity_state = 'present'\n AND projection.source_entity_revision = entity.current_revision\n AND NOT EXISTS (\n SELECT 1\n FROM entity_projection_revisions newer\n WHERE newer.workspace_id = projection.workspace_id\n AND newer.entity_id = projection.entity_id\n AND newer.projection_revision > projection.projection_revision\n )`\n const matchesFilters = sql`(${query.query} IS NULL OR instr(\n lower(projection.display_key || ' ' || projection.title || ' ' || ${searchStatusText}),\n lower(${query.query})\n ) > 0)\n AND (${query.service} IS NULL OR ${service} = ${query.service})\n AND (${query.status} IS NULL OR ${statusGroup} = ${query.status})\n AND (${query.type} IS NULL OR ${entityType} = ${query.type})\n AND (${query.owner} IS NULL OR EXISTS (\n SELECT 1\n FROM role_assignments assignment\n INNER JOIN persons person\n ON person.workspace_id = assignment.workspace_id\n AND person.person_id = assignment.person_id\n AND person.is_active = 1\n WHERE ${activeOwner}\n AND assignment.person_id = ${query.owner}\n ))`\n // The repository executes this reader in one transaction, so counts and rows share a snapshot.\n const countRows = yield* sql`SELECT\n COUNT(CASE WHEN ${matchesFilters} THEN 1 END) AS matchedCount,\n COUNT(*) AS totalCount\n FROM entity_projection_revisions projection\n INNER JOIN entities entity\n ON entity.workspace_id = projection.workspace_id\n AND entity.entity_id = projection.entity_id\n WHERE ${isCurrent}`\n const counts = (yield* decodeRows(WorkspaceProjectionCountRow, countRows))[0]\n if (counts === undefined) return yield* Effect.die(\"Expected workspace projection counts\")\n const rows = yield* sql`SELECT\n projection.workspace_id AS workspaceId,\n projection.entity_id AS entityId,\n projection.projection_revision AS projectionRevision,\n projection.source_entity_revision AS sourceEntityRevision,\n projection.supersedes_projection_revision AS supersedesProjectionRevision,\n projection.projection_schema_version AS projectionSchemaVersion,\n projection.entity_state AS entityState,\n ${entityType} AS entityType,\n projection.display_key AS displayKey,\n projection.title,\n ${summaryExtensionJson} AS extensionJson,\n projection.extension_json AS originalExtensionJson,\n projection.extension_digest AS extensionDigest,\n projection.recorded_at AS recordedAt,\n COALESCE((\n SELECT json_group_array(json_object(\n 'avatarJson', owner.avatar_json,\n 'displayName', owner.display_name,\n 'personId', owner.person_id,\n 'rolesCsv', owner.roles_csv\n ))\n FROM (\n SELECT person.person_id, person.display_name, person.avatar_json,\n group_concat(DISTINCT assignment.role) AS roles_csv\n FROM role_assignments assignment\n INNER JOIN persons person\n ON person.workspace_id = assignment.workspace_id\n AND person.person_id = assignment.person_id\n AND person.is_active = 1\n WHERE ${activeOwner}\n GROUP BY person.person_id, person.display_name, person.avatar_json\n ORDER BY CASE WHEN person.person_id = ${query.owner} THEN 0 ELSE 1 END,\n person.display_name, person.person_id\n LIMIT 21\n ) owner\n ), '[]') AS ownerIdentitiesJson,\n COALESCE((\n SELECT json_group_array(current_release.release_id)\n FROM (\n SELECT DISTINCT relationship.release_id\n FROM delivery_nodes node\n INNER JOIN relationship_revisions relationship\n ON relationship.workspace_id = node.workspace_id\n AND (relationship.source_node_id = node.node_id OR relationship.target_node_id = node.node_id)\n INNER JOIN relationship_heads head\n ON head.workspace_id = relationship.workspace_id\n AND head.relationship_id = relationship.relationship_id\n AND head.current_revision = relationship.revision\n WHERE node.workspace_id = projection.workspace_id\n AND node.entity_id = projection.entity_id\n AND relationship.release_id IS NOT NULL\n AND relationship.lifecycle NOT IN ('rejected', 'superseded')\n ORDER BY relationship.release_id\n LIMIT 501\n ) current_release\n ), '[]') AS releaseIdsJson\n FROM entity_projection_revisions projection\n INNER JOIN entities entity\n ON entity.workspace_id = projection.workspace_id\n AND entity.entity_id = projection.entity_id\n WHERE ${isCurrent}\n AND ${matchesFilters}\n ORDER BY projection.display_key, projection.entity_id\n LIMIT ${rowLimit}`\n const decoded = yield* decodeRows(WorkspaceProjectionRow, rows).pipe(\n Effect.mapError(() =>\n graphRecordError(\n workspaceId,\n \"workspace-entity-projections\",\n workspaceId,\n \"entity-projection-schema-invalid\"\n )\n ),\n captureMalformedDeliveryGraphRow(rows)\n )\n const items = yield* Effect.forEach(decoded.slice(0, query.limit), (row) =>\n Effect.gen(function*() {\n const releaseIds = yield* Schema.decodeUnknownEffect(WorkspaceProjectionReleaseIds)(row.releaseIdsJson)\n .pipe(\n Effect.mapError(() =>\n graphRecordError(\n workspaceId,\n \"workspace-entity-projections\",\n row.entityId,\n \"workspace-release-memberships-schema-invalid\"\n )\n ),\n captureMalformedDeliveryGraphRow(row)\n )\n const boundedReleaseIds = releaseIds.slice(0, 500)\n const ownerIdentities = yield* Schema.decodeUnknownEffect(WorkspaceOwnerIdentities)(\n row.ownerIdentitiesJson\n ).pipe(\n Effect.mapError(() =>\n graphRecordError(\n workspaceId,\n \"person\",\n row.entityId,\n \"person-schema-invalid\"\n )\n ),\n captureMalformedDeliveryGraphRow(row)\n )\n const owners = yield* Effect.forEach(\n ownerIdentities.slice(0, 20),\n (owner) => decodeWorkspaceOwner(workspaceId, owner).pipe(captureMalformedDeliveryGraphRow(owner))\n )\n const { projection, recordedAt } = yield* decodeProjectionSummaryRow(row).pipe(\n captureMalformedDeliveryGraphRow(row)\n )\n return {\n canonicalReleaseId: boundedReleaseIds[0] ?? null,\n owners,\n ownersTruncated: ownerIdentities.length > 20,\n releaseIds: boundedReleaseIds,\n releaseMembershipsTruncated: releaseIds.length > 500,\n projection,\n recordedAt\n }\n }))\n const ownerOptionRows = yield* sql`SELECT\n person.person_id AS personId,\n person.display_name AS displayName,\n person.avatar_json AS avatarJson,\n group_concat(DISTINCT assignment.role) AS rolesCsv\n FROM role_assignments assignment\n INNER JOIN persons person\n ON person.workspace_id = assignment.workspace_id\n AND person.person_id = assignment.person_id\n AND person.is_active = 1\n INNER JOIN entity_projection_revisions projection\n ON projection.workspace_id = assignment.workspace_id\n AND projection.entity_id = assignment.entity_id\n INNER JOIN entities entity\n ON entity.workspace_id = projection.workspace_id\n AND entity.entity_id = projection.entity_id\n WHERE ${activeOwner}\n AND ${isCurrent}\n GROUP BY person.person_id, person.display_name, person.avatar_json\n ORDER BY person.display_name, person.person_id\n LIMIT 201`\n const decodedOwnerOptions = yield* decodeRows(WorkspaceOwnerOptionRow, ownerOptionRows).pipe(\n Effect.mapError(() =>\n graphRecordError(\n workspaceId,\n \"person\",\n workspaceId,\n \"person-schema-invalid\"\n )\n ),\n captureMalformedDeliveryGraphRow(ownerOptionRows)\n )\n const ownerOptions = yield* Effect.forEach(\n decodedOwnerOptions.slice(0, 200),\n (owner) => decodeWorkspaceOwner(workspaceId, owner).pipe(captureMalformedDeliveryGraphRow(owner))\n )\n return DeliveryGraphReadResult.make({\n _tag: \"workspaceEntityProjections\",\n value: {\n items,\n matchedCount: counts.matchedCount,\n ownerOptions,\n ownerOptionsTruncated: decodedOwnerOptions.length > 200,\n totalCount: counts.totalCount,\n truncated: decoded.length > query.limit\n }\n })\n }\n case \"releaseSummary\": {\n const rows = yield* sql`WITH current_relationships AS (\n SELECT revision.source_node_id, revision.source_node_kind,\n revision.target_node_id, revision.target_node_kind\n FROM relationship_revisions revision\n INNER JOIN relationship_heads head\n ON head.workspace_id = revision.workspace_id\n AND head.relationship_id = revision.relationship_id\n AND head.current_revision = revision.revision\n WHERE revision.workspace_id = ${workspaceId}\n AND revision.release_id = ${query.releaseId}\n AND revision.environment_id IS NULL\n AND revision.lifecycle NOT IN ('rejected', 'superseded')\n ), endpoints AS (\n SELECT source_node_id AS node_id, source_node_kind AS endpoint_kind\n FROM current_relationships\n UNION\n SELECT target_node_id AS node_id, target_node_kind AS endpoint_kind\n FROM current_relationships\n ), resolved_endpoints AS (\n SELECT endpoints.node_id, endpoints.endpoint_kind\n FROM endpoints\n INNER JOIN delivery_nodes node\n ON node.workspace_id = ${workspaceId}\n AND node.node_id = endpoints.node_id\n AND node.resolution_state = 'resolved'\n )\n SELECT\n COUNT(DISTINCT CASE WHEN endpoint_kind = 'issue' THEN node_id END) AS issues,\n COUNT(DISTINCT CASE WHEN endpoint_kind = 'pull-request' THEN node_id END) AS pullRequests,\n COUNT(DISTINCT CASE WHEN endpoint_kind = 'pipeline-execution' THEN node_id END) AS pipelineExecutions\n FROM resolved_endpoints`\n const summaries = yield* decodeRows(\n Schema.Struct({\n issues: Schema.Int,\n pullRequests: Schema.Int,\n pipelineExecutions: Schema.Int\n }),\n rows\n )\n const value = summaries[0]\n if (value === undefined) return yield* Effect.die(\"release relationship summary query returned no row\")\n return DeliveryGraphReadResult.make({ _tag: \"releaseSummary\", value })\n }\n }\n })\n\n return { readDecoded }\n})\n","import * as Effect from \"effect/Effect\"\nimport * as Schema from \"effect/Schema\"\n\nimport type { DeliveryNode, DeliveryRelationship, EvidenceItem } from \"../../../../domain/deliveryGraph.js\"\nimport { DeliveryEntityKind, EvidenceClaim, LedgerRevision } from \"../../../../domain/deliveryGraph.js\"\nimport type { EntityId, WorkspaceId } from \"../../../../domain/identifiers.js\"\nimport { GraphNodeId, PluginConnectionId, ReleaseId } from \"../../../../domain/identifiers.js\"\nimport { Database } from \"../../Database.js\"\nimport { PersistenceOperationError, RevisionConflictError } from \"../../errors.js\"\nimport { ContentBlobDigest } from \"../models.js\"\nimport { DeliveryGraphInputError, DeliveryGraphWriteReceipt } from \"./contract.js\"\nimport type { DeliveryGraphWriteBatch, EntityProjectionWrite } from \"./contract.js\"\nimport { makeDeliveryGraphIntegrity } from \"./integrity.js\"\nimport {\n decodeRows,\n DELIVERY_GRAPH_SCHEMA_VERSION,\n edgeJson,\n encodeTimestamp,\n evidenceJson,\n evidenceValueJson,\n freshnessJson,\n graphRecordError,\n nodeResolutionJson,\n projectionJson,\n relationshipJson\n} from \"./rows.js\"\n\nexport const makeDeliveryGraphWriter = Effect.gen(function*() {\n const database = yield* Database\n const { digestText } = yield* makeDeliveryGraphIntegrity\n const sql = database.sql\n\n const loadCanonicalEntity = Effect.fn(\"DeliveryGraphRepository.loadCanonicalEntity\")(function*(\n workspaceId: WorkspaceId,\n entityId: EntityId\n ) {\n const rows = yield* sql`SELECT\n CASE entity_type\n WHEN 'pipeline' THEN 'pipeline-execution'\n ELSE entity_type\n END AS entityKind,\n plugin_connection_id AS pluginConnectionId\n FROM entities\n WHERE workspace_id = ${workspaceId}\n AND entity_id = ${entityId}`\n const entities = yield* decodeRows(\n Schema.Struct({\n entityKind: DeliveryEntityKind,\n pluginConnectionId: PluginConnectionId\n }),\n rows\n )\n const entity = entities[0]\n if (entity === undefined) {\n return yield* graphRecordError(\n workspaceId,\n \"entity\",\n entityId,\n \"delivery-graph-entity-not-found\"\n )\n }\n return entity\n })\n\n const ensurePluginEvidenceSourceRevision = Effect.fn(\n \"DeliveryGraphRepository.ensurePluginEvidenceSourceRevision\"\n )(function*(evidence: EvidenceItem) {\n if (evidence.attribution._tag !== \"plugin\") return\n const provenance = evidence.freshness.provenance\n if (provenance._tag === \"none\") {\n return yield* graphRecordError(\n evidence.workspaceId,\n \"evidence-item\",\n evidence.evidenceId,\n \"evidence-plugin-source-revision-mismatch\"\n )\n }\n const sourceRevision = provenance.sourceRevision\n const sourceUrl = sourceRevision.sourceUrl === null ? null : sourceRevision.sourceUrl.toString()\n const firstObservedAt = encodeTimestamp(sourceRevision.firstObservedAt)\n const lastObservedAt = encodeTimestamp(sourceRevision.lastObservedAt)\n const synchronizedAt = encodeTimestamp(sourceRevision.synchronizedAt)\n const rows = yield* sql`SELECT 1 AS matches\n FROM entities entity\n INNER JOIN entity_revisions revision\n ON revision.workspace_id = entity.workspace_id\n AND revision.entity_id = entity.entity_id\n WHERE entity.workspace_id = ${evidence.workspaceId}\n AND entity.entity_id = ${evidence.attribution.sourceEntityId}\n AND revision.revision = ${evidence.attribution.sourceEntityRevision}\n AND entity.plugin_connection_id = ${sourceRevision.pluginConnectionId}\n AND entity.provider_id = ${sourceRevision.providerId}\n AND entity.vendor_immutable_id = ${sourceRevision.vendorImmutableId}\n AND revision.source_revision = ${sourceRevision.revision}\n AND revision.source_url IS ${sourceUrl}\n AND revision.first_observed_at = ${firstObservedAt}\n AND revision.last_observed_at = ${lastObservedAt}\n AND revision.synchronized_at = ${synchronizedAt}\n AND revision.normalization_schema_version = ${sourceRevision.normalizationSchemaVersion}`\n const matches = yield* decodeRows(Schema.Struct({ matches: Schema.Literal(1) }), rows)\n if (matches.length !== 1) {\n return yield* graphRecordError(\n evidence.workspaceId,\n \"evidence-item\",\n evidence.evidenceId,\n \"evidence-plugin-source-revision-mismatch\"\n )\n }\n })\n\n const ensureWorkspace = Effect.fn(\"DeliveryGraphRepository.ensureWorkspace\")(function*(\n workspaceId: WorkspaceId,\n batch: DeliveryGraphWriteBatch\n ) {\n const records = [\n ...batch.entityProjections.map(({ projection }) => projection),\n ...batch.nodes,\n ...batch.evidenceItems,\n ...batch.evidenceClaims,\n ...batch.relationships\n ]\n if (records.some((record) => record.workspaceId !== workspaceId)) {\n return yield* new DeliveryGraphInputError({ operation: \"write\" })\n }\n })\n\n const appendEntityProjection = Effect.fn(\"DeliveryGraphRepository.appendEntityProjection\")(function*(\n projectionWrite: typeof EntityProjectionWrite.Type\n ) {\n const { projection, recordedAt } = projectionWrite\n const entity = yield* loadCanonicalEntity(projection.workspaceId, projection.entityId)\n if (entity.entityKind !== projection.entityType) {\n return yield* graphRecordError(\n projection.workspaceId,\n \"entity-projection\",\n projection.entityId,\n \"entity-projection-entity-kind-mismatch\"\n )\n }\n const recordedAtText = encodeTimestamp(recordedAt)\n const previousRows = yield* sql`SELECT\n projection_revision AS revision,\n source_entity_revision AS sourceEntityRevision\n FROM entity_projection_revisions\n WHERE workspace_id = ${projection.workspaceId}\n AND entity_id = ${projection.entityId}\n ORDER BY projection_revision DESC\n LIMIT 1`\n const decodedPrevious = yield* Schema.decodeUnknownEffect(\n Schema.Array(Schema.Struct({\n revision: Schema.Number,\n sourceEntityRevision: Schema.Number\n }))\n )(previousRows)\n const previous = decodedPrevious[0]\n const actualRevision = previous?.revision ?? null\n const expectedRevision = projection.projectionRevision - 1\n if (actualRevision !== (expectedRevision === 0 ? null : expectedRevision)) {\n return yield* new RevisionConflictError({\n workspaceId: projection.workspaceId,\n recordKind: \"entity-projection\",\n recordKey: projection.entityId,\n expectedRevision,\n actualRevision\n })\n }\n if (\n previous !== undefined &&\n projection.sourceEntityRevision < previous.sourceEntityRevision\n ) {\n return yield* graphRecordError(\n projection.workspaceId,\n \"entity-projection\",\n projection.entityId,\n \"entity-projection-source-revision-regression\"\n )\n }\n const extensionJson = yield* Schema.encodeEffect(projectionJson)(projection.details).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"delivery-graph.encode-projection\" }))\n )\n const extensionDigest = yield* digestText(extensionJson)\n yield* sql`INSERT INTO entity_projection_revisions (\n workspace_id, entity_id, projection_revision, source_entity_revision,\n supersedes_projection_revision,\n projection_schema_version, entity_state, display_key, title,\n extension_json, extension_digest, recorded_at\n ) VALUES (\n ${projection.workspaceId}, ${projection.entityId}, ${projection.projectionRevision},\n ${projection.sourceEntityRevision}, ${projection.supersedesProjectionRevision},\n ${projection.projectionSchemaVersion},\n ${projection.entityState}, ${projection.displayKey}, ${projection.title},\n ${extensionJson}, ${extensionDigest}, ${recordedAtText}\n )`\n })\n\n const insertNode = Effect.fn(\"DeliveryGraphRepository.insertNode\")(function*(node: DeliveryNode) {\n const createdAt = encodeTimestamp(node.createdAt)\n const resolutionJson = yield* Schema.encodeEffect(nodeResolutionJson)(node.resolution).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"delivery-graph.encode-node\" }))\n )\n const nodeKeyDigest = yield* digestText(resolutionJson)\n const isResolved = node.resolution._tag === \"resolved\"\n const target = isResolved ? node.resolution.target : null\n const nodeKind = isResolved ? target?._tag : node.resolution.expectedKind\n const entityId = target?._tag === \"entity\" ? target.entityId : null\n const releaseId = target?._tag === \"release\" || target?._tag === \"environment\"\n ? target.releaseId\n : null\n const environmentId = target?._tag === \"environment\" ? target.environmentId : null\n const expectedEntityKind = !isResolved && node.resolution.expectedKind === \"entity\"\n ? node.resolution.expectedEntityKind\n : null\n const missingKey = isResolved ? null : node.resolution.missingKey\n if (target?._tag === \"entity\") {\n const entity = yield* loadCanonicalEntity(node.workspaceId, target.entityId)\n if (entity.entityKind !== target.entityKind) {\n return yield* graphRecordError(\n node.workspaceId,\n \"delivery-node\",\n node.nodeId,\n \"delivery-node-entity-kind-mismatch\"\n )\n }\n }\n yield* sql`INSERT INTO delivery_nodes (\n workspace_id, node_id, node_key_digest, node_kind, endpoint_kind, resolution_state,\n entity_id, release_id, environment_id, expected_entity_kind, missing_key, created_at\n ) VALUES (\n ${node.workspaceId}, ${node.nodeId}, ${nodeKeyDigest}, ${nodeKind}, ${node.endpointKind},\n ${node.resolution._tag},\n ${entityId}, ${releaseId}, ${environmentId}, ${expectedEntityKind}, ${missingKey}, ${createdAt}\n )`\n })\n\n const insertEvidence = Effect.fn(\"DeliveryGraphRepository.insertEvidence\")(function*(\n evidence: EvidenceItem\n ) {\n if (evidence.attribution._tag === \"plugin\") {\n const entity = yield* loadCanonicalEntity(\n evidence.workspaceId,\n evidence.attribution.sourceEntityId\n )\n if (entity.pluginConnectionId !== evidence.attribution.pluginConnectionId) {\n return yield* graphRecordError(\n evidence.workspaceId,\n \"evidence-item\",\n evidence.evidenceId,\n \"evidence-plugin-source-owner-mismatch\"\n )\n }\n }\n yield* ensurePluginEvidenceSourceRevision(evidence)\n const evidencePayload = yield* Schema.encodeEffect(evidenceJson)(evidence).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"delivery-graph.encode-evidence\" }))\n )\n const evidenceDigest = yield* digestText(evidencePayload)\n const encodedFreshness = yield* Schema.encodeEffect(freshnessJson)(evidence.freshness).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"delivery-graph.encode-freshness\" }))\n )\n const freshnessDigest = yield* digestText(encodedFreshness)\n const attribution = evidence.attribution\n const verifier = evidence.verifier\n const observedAt = encodeTimestamp(evidence.observedAt)\n const recordedAt = encodeTimestamp(evidence.recordedAt)\n const validUntil = evidence.validUntil === null ? null : encodeTimestamp(evidence.validUntil)\n const retainUntil = evidence.retention.retainUntil === null\n ? null\n : encodeTimestamp(evidence.retention.retainUntil)\n yield* sql`INSERT INTO evidence_items (\n workspace_id, evidence_id, schema_version, evidence_digest,\n origin_kind, plugin_connection_id, source_entity_id, source_entity_revision,\n person_id, agent_id, system_component,\n verifier_kind, verifier_person_id, verifier_agent_id, verifier_component,\n observed_at, recorded_at, valid_until, freshness_json, freshness_digest,\n retention_class, retain_until, legal_hold\n ) VALUES (\n ${evidence.workspaceId}, ${evidence.evidenceId}, ${evidence.schemaVersion}, ${evidenceDigest},\n ${attribution._tag},\n ${attribution._tag === \"plugin\" ? attribution.pluginConnectionId : null},\n ${attribution._tag === \"plugin\" ? attribution.sourceEntityId : null},\n ${attribution._tag === \"plugin\" ? attribution.sourceEntityRevision : null},\n ${attribution._tag === \"human\" ? attribution.personId : null},\n ${attribution._tag === \"agent\" ? attribution.agentId : null},\n ${attribution._tag === \"system\" ? attribution.component : null},\n ${verifier._tag},\n ${verifier._tag === \"human\" ? verifier.personId : null},\n ${verifier._tag === \"agent\" ? verifier.agentId : null},\n ${verifier._tag === \"system\" ? verifier.component : null},\n ${observedAt}, ${recordedAt}, ${validUntil}, ${encodedFreshness}, ${freshnessDigest},\n ${evidence.retention.classification}, ${retainUntil},\n ${evidence.retention.legalHold ? 1 : 0}\n )`\n })\n\n const insertClaim = Effect.fn(\"DeliveryGraphRepository.insertClaim\")(function*(claim: EvidenceClaim) {\n const recordedAt = encodeTimestamp(claim.recordedAt)\n const causalEvidenceRows = yield* sql`SELECT 1 AS matches\n FROM evidence_items\n WHERE workspace_id = ${claim.workspaceId}\n AND evidence_id = ${claim.evidenceId}\n AND recorded_at <= ${recordedAt}`\n const causalEvidence = yield* decodeRows(\n Schema.Struct({ matches: Schema.Literal(1) }),\n causalEvidenceRows\n )\n if (causalEvidence.length !== 1) {\n return yield* graphRecordError(\n claim.workspaceId,\n \"evidence-claim\",\n claim.evidenceClaimId,\n \"evidence-claim-precedes-evidence\"\n )\n }\n if (claim.supersedesEvidenceClaimId !== null) {\n const predecessorRows = yield* sql`SELECT\n subject_node_id AS subjectNodeId,\n predicate,\n (SELECT evidence_claim_id FROM evidence_claims successor\n WHERE successor.workspace_id = predecessor.workspace_id\n AND successor.supersedes_claim_id = predecessor.evidence_claim_id\n LIMIT 1) AS successorId\n FROM evidence_claims predecessor\n WHERE workspace_id = ${claim.workspaceId}\n AND evidence_claim_id = ${claim.supersedesEvidenceClaimId}`\n const predecessor = yield* Schema.decodeUnknownEffect(Schema.Array(Schema.Struct({\n subjectNodeId: GraphNodeId,\n predicate: EvidenceClaim.fields.predicate,\n successorId: Schema.NullOr(EvidenceClaim.fields.evidenceClaimId)\n })))(predecessorRows)\n const row = predecessor[0]\n if (\n row === undefined || row.subjectNodeId !== claim.subjectNodeId ||\n row.predicate !== claim.predicate || row.successorId !== null\n ) {\n return yield* graphRecordError(\n claim.workspaceId,\n \"evidence-claim\",\n claim.evidenceClaimId,\n \"evidence-claim-supersession-invalid\"\n )\n }\n }\n const valueJson = yield* Schema.encodeEffect(evidenceValueJson)(claim.value).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"delivery-graph.encode-claim\" }))\n )\n const valueDigest = yield* digestText(valueJson)\n yield* sql`INSERT INTO evidence_claims (\n workspace_id, evidence_claim_id, evidence_id, subject_node_id, predicate,\n value_schema_version, value_json, value_digest, supersedes_claim_id, recorded_at\n ) VALUES (\n ${claim.workspaceId}, ${claim.evidenceClaimId}, ${claim.evidenceId}, ${claim.subjectNodeId},\n ${claim.predicate}, ${DELIVERY_GRAPH_SCHEMA_VERSION}, ${valueJson}, ${valueDigest},\n ${claim.supersedesEvidenceClaimId}, ${recordedAt}\n )`\n })\n\n const ensureContainsScope = Effect.fn(\"DeliveryGraphRepository.ensureContainsScope\")(function*(\n relationship: DeliveryRelationship\n ) {\n if (relationship.kind !== \"contains\") return\n if (relationship.scope === null) {\n return yield* graphRecordError(\n relationship.workspaceId,\n \"delivery-relationship\",\n relationship.relationshipId,\n \"relationship-containment-scope-missing\"\n )\n }\n const rows = yield* sql`SELECT release_id AS releaseId\n FROM delivery_nodes\n WHERE workspace_id = ${relationship.workspaceId}\n AND node_id = ${relationship.sourceNodeId}\n AND node_kind = 'release'\n AND resolution_state = 'resolved'`\n const sources = yield* decodeRows(Schema.Struct({ releaseId: ReleaseId }), rows)\n if (sources[0]?.releaseId !== relationship.scope.releaseId) {\n return yield* graphRecordError(\n relationship.workspaceId,\n \"delivery-relationship\",\n relationship.relationshipId,\n \"relationship-containment-release-mismatch\"\n )\n }\n })\n\n const appendRelationship = Effect.fn(\"DeliveryGraphRepository.appendRelationship\")(function*(\n relationship: DeliveryRelationship\n ) {\n yield* ensureContainsScope(relationship)\n if (relationship.provenance._tag === \"plugin\") {\n const entity = yield* loadCanonicalEntity(\n relationship.workspaceId,\n relationship.provenance.sourceEntityId\n )\n if (entity.pluginConnectionId !== relationship.provenance.pluginConnectionId) {\n return yield* graphRecordError(\n relationship.workspaceId,\n \"delivery-relationship\",\n relationship.relationshipId,\n \"relationship-plugin-source-owner-mismatch\"\n )\n }\n }\n const relationshipPayload = yield* Schema.encodeEffect(relationshipJson)(relationship).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"delivery-graph.encode-relationship\" }))\n )\n const revisionDigest = yield* digestText(relationshipPayload)\n const edgePayload = yield* Schema.encodeEffect(edgeJson)({\n kind: relationship.kind,\n sourceNodeId: relationship.sourceNodeId,\n sourceNodeKind: relationship.sourceNodeKind,\n targetNodeId: relationship.targetNodeId,\n targetNodeKind: relationship.targetNodeKind,\n scope: relationship.scope\n }).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"delivery-graph.encode-edge\" }))\n )\n const edgeDigest = yield* digestText(edgePayload)\n const lifecycle = relationship.lifecycle\n const confidence = relationship.confidence\n const provenance = relationship.provenance\n const recordedBy = relationship.recordedBy\n const recordedAt = encodeTimestamp(relationship.recordedAt)\n const effectiveAt = encodeTimestamp(lifecycle.effectiveAt)\n const releaseId = relationship.scope?._tag === \"release\" || relationship.scope?._tag === \"environment\"\n ? relationship.scope.releaseId\n : null\n const environmentId = relationship.scope?._tag === \"environment\"\n ? relationship.scope.environmentId\n : null\n\n yield* Effect.forEach(\n relationship.evidenceClaimIds,\n (evidenceClaimId) =>\n Effect.gen(function*() {\n const causalClaimRows = yield* sql`SELECT 1 AS matches\n FROM evidence_claims\n WHERE workspace_id = ${relationship.workspaceId}\n AND evidence_claim_id = ${evidenceClaimId}\n AND recorded_at <= ${recordedAt}`\n const causalClaims = yield* decodeRows(\n Schema.Struct({ matches: Schema.Literal(1) }),\n causalClaimRows\n )\n if (causalClaims.length !== 1) {\n return yield* graphRecordError(\n relationship.workspaceId,\n \"delivery-relationship\",\n relationship.relationshipId,\n \"relationship-precedes-evidence-claim\"\n )\n }\n }),\n { discard: true }\n )\n\n if (relationship.revision === 1) {\n yield* sql`INSERT INTO relationship_heads (\n workspace_id, relationship_id, current_revision, edge_digest, created_at, updated_at\n ) VALUES (\n ${relationship.workspaceId}, ${relationship.relationshipId}, 1, ${edgeDigest},\n ${recordedAt}, ${recordedAt}\n )`\n } else {\n const headRows = yield* sql`SELECT current_revision AS revision, edge_digest AS edgeDigest\n FROM relationship_heads\n WHERE workspace_id = ${relationship.workspaceId}\n AND relationship_id = ${relationship.relationshipId}`\n const heads = yield* Schema.decodeUnknownEffect(Schema.Array(Schema.Struct({\n revision: LedgerRevision,\n edgeDigest: ContentBlobDigest\n })))(headRows)\n const head = heads[0]\n if (head?.revision !== relationship.supersedesRevision) {\n return yield* new RevisionConflictError({\n workspaceId: relationship.workspaceId,\n recordKind: \"delivery-relationship\",\n recordKey: relationship.relationshipId,\n expectedRevision: relationship.supersedesRevision ?? 0,\n actualRevision: head?.revision ?? null\n })\n }\n if (head.edgeDigest !== edgeDigest) {\n return yield* graphRecordError(\n relationship.workspaceId,\n \"delivery-relationship\",\n relationship.relationshipId,\n \"relationship-edge-identity-mismatch\"\n )\n }\n }\n\n const lifecycleReason = lifecycle._tag === \"missing\" || lifecycle._tag === \"rejected\" ||\n lifecycle._tag === \"superseded\"\n ? lifecycle.reason\n : null\n const confidenceRationale = confidence._tag === \"confirmed\"\n ? \"Confirmed by recorded evidence.\"\n : confidence.rationale\n yield* sql`INSERT INTO relationship_revisions (\n workspace_id, relationship_id, revision, supersedes_revision, schema_version,\n kind, source_node_id, source_node_kind, target_node_id, target_node_kind,\n lifecycle, lifecycle_reason,\n release_id, environment_id, confidence_kind, confidence_score, confidence_rationale,\n provenance_kind, provenance_plugin_connection_id, provenance_source_entity_id,\n provenance_source_entity_revision, provenance_person_id, provenance_agent_id,\n provenance_rule_id, provenance_rule_version, provenance_rationale,\n recorded_by_kind, recorded_by_person_id, recorded_by_agent_id, recorded_by_component,\n effective_at, recorded_at, revision_digest\n ) VALUES (\n ${relationship.workspaceId}, ${relationship.relationshipId}, ${relationship.revision},\n ${relationship.supersedesRevision}, ${relationship.relationshipSchemaVersion}, ${relationship.kind},\n ${relationship.sourceNodeId}, ${relationship.sourceNodeKind},\n ${relationship.targetNodeId}, ${relationship.targetNodeKind}, ${lifecycle._tag}, ${lifecycleReason},\n ${releaseId}, ${environmentId}, ${confidence._tag},\n ${confidence._tag === \"inferred\" ? confidence.score : null}, ${confidenceRationale},\n ${provenance._tag},\n ${provenance._tag === \"plugin\" ? provenance.pluginConnectionId : null},\n ${provenance._tag === \"plugin\" ? provenance.sourceEntityId : null},\n ${provenance._tag === \"plugin\" ? provenance.sourceEntityRevision : null},\n ${provenance._tag === \"human\" ? provenance.personId : null},\n ${provenance._tag === \"agent\" ? provenance.agentId : null},\n ${provenance._tag === \"rule\" ? provenance.ruleId : null},\n ${provenance._tag === \"rule\" ? provenance.ruleVersion : null},\n ${\n provenance._tag === \"human\" || provenance._tag === \"agent\" || provenance._tag === \"rule\"\n ? provenance.rationale\n : null\n },\n ${recordedBy._tag},\n ${recordedBy._tag === \"human\" ? recordedBy.personId : null},\n ${recordedBy._tag === \"agent\" ? recordedBy.agentId : null},\n ${recordedBy._tag === \"system\" ? recordedBy.component : null},\n ${effectiveAt}, ${recordedAt}, ${revisionDigest}\n )`\n yield* Effect.forEach(\n relationship.evidenceClaimIds,\n (evidenceClaimId) =>\n sql`INSERT INTO relationship_revision_evidence (\n workspace_id, relationship_id, relationship_revision, evidence_claim_id\n ) VALUES (\n ${relationship.workspaceId}, ${relationship.relationshipId},\n ${relationship.revision}, ${evidenceClaimId}\n )`,\n { discard: true }\n )\n if (relationship.revision > 1) {\n yield* sql`UPDATE relationship_heads\n SET current_revision = ${relationship.revision}, updated_at = ${recordedAt}\n WHERE workspace_id = ${relationship.workspaceId}\n AND relationship_id = ${relationship.relationshipId}\n AND current_revision = ${relationship.supersedesRevision}`\n const changesRows = yield* sql`SELECT changes() AS changes`\n const changes = yield* decodeRows(Schema.Struct({ changes: Schema.Number }), changesRows)\n if (changes[0]?.changes !== 1) {\n return yield* new RevisionConflictError({\n workspaceId: relationship.workspaceId,\n recordKind: \"delivery-relationship\",\n recordKey: relationship.relationshipId,\n expectedRevision: relationship.supersedesRevision ?? 0,\n actualRevision: null\n })\n }\n }\n })\n\n const writeDecoded = Effect.fn(\"DeliveryGraphRepository.writeDecoded\")(function*(\n batch: DeliveryGraphWriteBatch\n ) {\n yield* Effect.forEach(batch.entityProjections, appendEntityProjection, { discard: true })\n yield* Effect.forEach(batch.nodes, insertNode, { discard: true })\n yield* Effect.forEach(batch.evidenceItems, insertEvidence, { discard: true })\n yield* Effect.forEach(batch.evidenceClaims, insertClaim, { discard: true })\n yield* Effect.forEach(batch.relationships, appendRelationship, { discard: true })\n return DeliveryGraphWriteReceipt.make({\n entityProjectionCount: batch.entityProjections.length,\n nodeCount: batch.nodes.length,\n evidenceItemCount: batch.evidenceItems.length,\n evidenceClaimCount: batch.evidenceClaims.length,\n relationshipCount: batch.relationships.length\n })\n })\n\n return { ensureWorkspace, writeDecoded }\n})\n","import * as Context from \"effect/Context\"\nimport * as Crypto from \"effect/Crypto\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport type { Success } from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\n\nimport type { WorkspaceId } from \"../../../domain/identifiers.js\"\nimport { Database } from \"../Database.js\"\nimport { DeliveryGraphInputError, DeliveryGraphQuery, DeliveryGraphWriteBatch } from \"./delivery-graph/contract.js\"\nimport { deliveryGraphQuarantineDiagnostic } from \"./delivery-graph/quarantine.js\"\nimport { makeDeliveryGraphReader } from \"./delivery-graph/read.js\"\nimport { makeDeliveryGraphWriter } from \"./delivery-graph/write.js\"\nimport { mapPersistenceOperation } from \"./internal.js\"\nimport { makePersistedRowQuarantine } from \"./persistedRowQuarantine.js\"\nimport { QuarantineRepository } from \"./quarantineRepository.js\"\n\nexport {\n DeliveryGraphInputError,\n DeliveryGraphQuery,\n DeliveryGraphReadResult,\n DeliveryGraphWriteBatch,\n DeliveryGraphWriteReceipt\n} from \"./delivery-graph/contract.js\"\n\nconst makeDeliveryGraphRepository = Effect.gen(function*() {\n const database = yield* Database\n const cryptoService = yield* Crypto.Crypto\n const quarantine = yield* QuarantineRepository\n const quarantineRow = makePersistedRowQuarantine(cryptoService, quarantine)\n const writer = yield* makeDeliveryGraphWriter\n const reader = yield* makeDeliveryGraphReader\n\n const decodeBatch = Effect.fn(\"DeliveryGraphRepository.decodeBatch\")(function*(input: unknown) {\n return yield* Schema.decodeUnknownEffect(DeliveryGraphWriteBatch)(input).pipe(\n Effect.mapError(() => new DeliveryGraphInputError({ operation: \"write\" }))\n )\n })\n\n const decodeQuery = Effect.fn(\"DeliveryGraphRepository.decodeQuery\")(function*(input: unknown) {\n return yield* Schema.decodeUnknownEffect(DeliveryGraphQuery)(input).pipe(\n Effect.mapError(() => new DeliveryGraphInputError({ operation: \"read\" }))\n )\n })\n\n return {\n write: Effect.fn(\"DeliveryGraphRepository.write\")(function*(\n workspaceId: WorkspaceId,\n input: unknown\n ) {\n const batch = yield* decodeBatch(input)\n yield* writer.ensureWorkspace(workspaceId, batch)\n return yield* database.transaction(writer.writeDecoded(batch)).pipe(\n mapPersistenceOperation(\"delivery-graph.write\")\n )\n }),\n read: Effect.fn(\"DeliveryGraphRepository.read\")(function*(\n workspaceId: WorkspaceId,\n input: unknown\n ) {\n const query = yield* decodeQuery(input)\n const result = yield* database.transaction(\n reader.readDecoded(workspaceId, query).pipe(Effect.result)\n ).pipe(mapPersistenceOperation(\"delivery-graph.read\"))\n if (Result.isSuccess(result)) return result.success\n if (!Predicate.isTagged(\"MalformedDeliveryGraphRecord\")(result.failure)) return yield* result.failure\n\n const diagnostic = deliveryGraphQuarantineDiagnostic(result.failure.error)\n if (diagnostic !== null) {\n yield* quarantineRow({\n workspaceId,\n ...diagnostic,\n recordKey: result.failure.error.recordKey,\n observedAt: yield* DateTime.now,\n row: result.failure.row\n })\n }\n return yield* result.failure.error\n })\n }\n})\n\n/** Deep workspace-safe persistence interface for the complete delivery graph ledger. */\nexport interface DeliveryGraphRepositoryService extends Success<typeof makeDeliveryGraphRepository> {}\n\n/** Effect service exposing one atomic write and one tagged read operation. */\nexport class DeliveryGraphRepository extends Context.Service<\n DeliveryGraphRepository,\n DeliveryGraphRepositoryService\n>()(\"@knpkv/control-center/DeliveryGraphRepository\") {\n /** Layer binding graph persistence to the shared database and cryptography services. */\n static readonly layer = Layer.effect(DeliveryGraphRepository, makeDeliveryGraphRepository)\n}\n","import * as Context from \"effect/Context\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport type { Success } from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\n\nimport type { CompleteDiffInventoryEntry, DiffFileAnchor } from \"../../../api/diff.js\"\nimport { type PluginConnectionId, WorkspaceId } from \"../../../domain/identifiers.js\"\nimport type { Revision, VendorImmutableId } from \"../../../domain/sourceRevision.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport { Database } from \"../Database.js\"\nimport { PersistedRecordError } from \"../errors.js\"\nimport { mapPersistenceOperation } from \"./internal.js\"\nimport type { ContentBlobDigest } from \"./models.js\"\nimport { ContentBlobDigest as ContentBlobDigestSchema } from \"./models.js\"\n\n/** Per-workspace hard cap; each entry represents at most one MiB of reproducible bytes. */\nexport const MaximumDiffContentCacheEntriesPerWorkspace = 2_000\n/** Maximum number of persistent cleanup intents processed by one sweep. */\nexport const MaximumDiffContentCacheCleanupBatch = 64\n\n/** Immutable identity of one cached side of one changed file. */\nexport interface DiffContentCacheKey {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n readonly vendorImmutableId: VendorImmutableId\n readonly revision: Revision\n readonly anchor: DiffFileAnchor\n readonly status: CompleteDiffInventoryEntry[\"status\"]\n readonly side: \"before\" | \"after\"\n}\n\nconst CachedDigestRow = Schema.Struct({ digest: ContentBlobDigestSchema })\nconst CleanupCandidateRow = Schema.Struct({\n workspaceId: WorkspaceId,\n digest: ContentBlobDigestSchema\n})\nconst UnknownPersistedWorkspaceId = WorkspaceId.make(\"00000000-0000-7000-8000-000000000000\")\n\nconst makeDiffContentCacheRepository = Effect.gen(function*() {\n const database = yield* Database\n const sql = database.sql\n\n const get = Effect.fn(\"DiffContentCacheRepository.get\")(function*(key: DiffContentCacheKey) {\n const rows = yield* sql<Record<string, unknown>>`SELECT content_digest AS digest\n FROM diff_content_cache_entries\n WHERE workspace_id = ${key.workspaceId}\n AND plugin_connection_id = ${key.pluginConnectionId}\n AND vendor_immutable_id = ${key.vendorImmutableId}\n AND source_revision = ${key.revision}\n AND file_anchor = ${key.anchor}\n AND file_status = ${key.status}\n AND side = ${key.side}`.pipe(mapPersistenceOperation(\"diff-content-cache.get\"))\n if (rows.length === 0) return Option.none<ContentBlobDigest>()\n const decoded = Schema.decodeUnknownResult(CachedDigestRow)(rows[0])\n if (Result.isSuccess(decoded)) return Option.some(decoded.success.digest)\n return yield* new PersistedRecordError({\n workspaceId: key.workspaceId,\n recordKind: \"diff-content-cache\",\n recordKey: key.anchor,\n diagnosticCode: \"diff-content-cache-schema-invalid\"\n })\n })\n\n const requestCleanup = Effect.fn(\"DiffContentCacheRepository.requestCleanup\")(function*(\n workspaceId: WorkspaceId,\n digest: ContentBlobDigest\n ) {\n const requestedAt = Schema.encodeSync(UtcTimestamp)(yield* DateTime.now)\n yield* sql`INSERT INTO diff_content_cache_cleanup (\n workspace_id, content_digest, requested_at\n )\n SELECT blobs.workspace_id, blobs.digest, ${requestedAt}\n FROM content_blobs AS blobs\n WHERE blobs.workspace_id = ${workspaceId}\n AND blobs.digest = ${digest}\n AND blobs.storage_class = 'reproducible-cache'\n ON CONFLICT (workspace_id, content_digest) DO NOTHING`.pipe(\n mapPersistenceOperation(\"diff-content-cache.request-cleanup\")\n )\n })\n\n return {\n cancelCleanup: Effect.fn(\"DiffContentCacheRepository.cancelCleanup\")(function*(\n workspaceId: WorkspaceId,\n digest: ContentBlobDigest\n ) {\n yield* sql`DELETE FROM diff_content_cache_cleanup\n WHERE workspace_id = ${workspaceId}\n AND content_digest = ${digest}`.pipe(\n mapPersistenceOperation(\"diff-content-cache.cancel-cleanup\")\n )\n }),\n completeCleanup: Effect.fn(\"DiffContentCacheRepository.completeCleanup\")(function*(\n workspaceId: WorkspaceId,\n digest: ContentBlobDigest\n ) {\n yield* sql`DELETE FROM content_blobs\n WHERE workspace_id = ${workspaceId}\n AND digest = ${digest}\n AND storage_class = 'reproducible-cache'\n AND EXISTS (\n SELECT 1\n FROM diff_content_cache_cleanup\n WHERE workspace_id = ${workspaceId}\n AND content_digest = ${digest}\n )\n AND NOT EXISTS (\n SELECT 1\n FROM diff_content_cache_entries\n WHERE workspace_id = ${workspaceId}\n AND content_digest = ${digest}\n )`.pipe(mapPersistenceOperation(\"diff-content-cache.complete-cleanup\"))\n }),\n deferCleanup: Effect.fn(\"DiffContentCacheRepository.deferCleanup\")(function*(\n workspaceId: WorkspaceId,\n digest: ContentBlobDigest\n ) {\n const requestedAt = Schema.encodeSync(UtcTimestamp)(yield* DateTime.now)\n yield* sql`UPDATE diff_content_cache_cleanup\n SET requested_at = ${requestedAt},\n attempt_count = attempt_count + 1\n WHERE workspace_id = ${workspaceId}\n AND content_digest = ${digest}`.pipe(\n mapPersistenceOperation(\"diff-content-cache.defer-cleanup\")\n )\n }),\n get,\n isReferenced: Effect.fn(\"DiffContentCacheRepository.isReferenced\")(function*(\n workspaceId: WorkspaceId,\n digest: ContentBlobDigest\n ) {\n const rows = yield* sql`SELECT 1\n FROM diff_content_cache_entries\n WHERE workspace_id = ${workspaceId}\n AND content_digest = ${digest}\n LIMIT 1`.pipe(mapPersistenceOperation(\"diff-content-cache.is-referenced\"))\n return rows.length > 0\n }),\n pendingCleanup: Effect.fn(\"DiffContentCacheRepository.pendingCleanup\")(function*(\n maximumCandidates: number = MaximumDiffContentCacheCleanupBatch\n ) {\n const rows = yield* sql<Record<string, unknown>>`SELECT\n workspace_id AS workspaceId,\n content_digest AS digest\n FROM diff_content_cache_cleanup\n ORDER BY attempt_count, requested_at, workspace_id, content_digest\n LIMIT ${maximumCandidates}`.pipe(\n mapPersistenceOperation(\"diff-content-cache.pending-cleanup\")\n )\n const decoded = Schema.decodeUnknownResult(Schema.Array(CleanupCandidateRow))(rows)\n if (Result.isSuccess(decoded)) return decoded.success\n return yield* new PersistedRecordError({\n workspaceId: UnknownPersistedWorkspaceId,\n recordKind: \"diff-content-cache-cleanup\",\n recordKey: \"pending\",\n diagnosticCode: \"diff-content-cache-cleanup-schema-invalid\"\n })\n }),\n put: Effect.fn(\"DiffContentCacheRepository.put\")(function*(\n key: DiffContentCacheKey,\n digest: ContentBlobDigest,\n maximumEntries: number = MaximumDiffContentCacheEntriesPerWorkspace\n ) {\n const cachedAt = yield* DateTime.now\n const encodedCachedAt = Schema.encodeSync(UtcTimestamp)(cachedAt)\n return yield* database.transaction(\n Effect.gen(function*() {\n yield* sql`INSERT INTO diff_content_cache_cleanup (\n workspace_id, content_digest, requested_at\n )\n SELECT entries.workspace_id, entries.content_digest, ${encodedCachedAt}\n FROM diff_content_cache_entries AS entries\n JOIN content_blobs AS blobs\n ON blobs.workspace_id = entries.workspace_id\n AND blobs.digest = entries.content_digest\n WHERE entries.workspace_id = ${key.workspaceId}\n AND entries.plugin_connection_id = ${key.pluginConnectionId}\n AND entries.vendor_immutable_id = ${key.vendorImmutableId}\n AND entries.source_revision = ${key.revision}\n AND entries.file_anchor = ${key.anchor}\n AND entries.file_status = ${key.status}\n AND entries.side = ${key.side}\n AND entries.content_digest <> ${digest}\n AND blobs.storage_class = 'reproducible-cache'\n ON CONFLICT (workspace_id, content_digest) DO NOTHING`\n\n yield* sql`INSERT INTO diff_content_cache_entries (\n workspace_id, plugin_connection_id, vendor_immutable_id, source_revision,\n file_anchor, file_status, side, content_digest, cached_at\n ) VALUES (\n ${key.workspaceId}, ${key.pluginConnectionId}, ${key.vendorImmutableId}, ${key.revision},\n ${key.anchor}, ${key.status}, ${key.side}, ${digest}, ${encodedCachedAt}\n )\n ON CONFLICT (\n workspace_id, plugin_connection_id, vendor_immutable_id, source_revision,\n file_anchor, file_status, side\n ) DO UPDATE SET\n content_digest = excluded.content_digest,\n cached_at = excluded.cached_at`\n\n yield* sql`INSERT INTO diff_content_cache_cleanup (\n workspace_id, content_digest, requested_at\n )\n SELECT DISTINCT entries.workspace_id, entries.content_digest, ${encodedCachedAt}\n FROM diff_content_cache_entries AS entries\n JOIN content_blobs AS blobs\n ON blobs.workspace_id = entries.workspace_id\n AND blobs.digest = entries.content_digest\n WHERE entries.workspace_id = ${key.workspaceId}\n AND entries.rowid IN (\n SELECT rowid\n FROM diff_content_cache_entries\n WHERE workspace_id = ${key.workspaceId}\n ORDER BY cached_at DESC, rowid DESC\n LIMIT -1 OFFSET ${maximumEntries}\n )\n AND blobs.storage_class = 'reproducible-cache'\n ON CONFLICT (workspace_id, content_digest) DO NOTHING`\n\n yield* sql`DELETE FROM diff_content_cache_entries\n WHERE workspace_id = ${key.workspaceId}\n AND rowid IN (\n SELECT rowid\n FROM diff_content_cache_entries\n WHERE workspace_id = ${key.workspaceId}\n ORDER BY cached_at DESC, rowid DESC\n LIMIT -1 OFFSET ${maximumEntries}\n )`\n })\n ).pipe(mapPersistenceOperation(\"diff-content-cache.put\"))\n }),\n requestCleanup\n }\n})\n\n/** Durable lookup from immutable diff identity to content-addressed bytes. */\nexport interface DiffContentCacheRepositoryService extends Success<typeof makeDiffContentCacheRepository> {}\n\n/** Private repository for reproducible complete-diff cache entries. */\nexport class DiffContentCacheRepository extends Context.Service<\n DiffContentCacheRepository,\n DiffContentCacheRepositoryService\n>()(\"@knpkv/control-center/server/persistence/DiffContentCacheRepository\") {\n static readonly layer = Layer.effect(DiffContentCacheRepository, makeDiffContentCacheRepository)\n}\n","import * as Schema from \"effect/Schema\"\n\nimport {\n DomainEventCorrelationId,\n DomainEventMetadataV1,\n PortfolioInvalidatedPayloadV1\n} from \"../../../domain/domainEvent.js\"\nimport {\n DomainEventId,\n EntityId,\n EventCursor,\n JobId,\n PluginConnectionId,\n ReleaseId,\n WorkspaceId\n} from \"../../../domain/identifiers.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport { ContentBlobDigest } from \"./models.js\"\n\n/** Maximum number of durable events read in one replay page. */\nexport const MAXIMUM_DOMAIN_EVENT_PAGE_SIZE = 128\n\n/** Maximum number of durable events removed in one retention transaction. */\nexport const MAXIMUM_DOMAIN_EVENT_PRUNE_SIZE = 500\n\n/** Bounded caller identity used to make event appends idempotent. */\nexport const DomainEventDedupeKey = Schema.String.check(\n Schema.isTrimmed(),\n Schema.isNonEmpty(),\n Schema.isMaxLength(512)\n).pipe(Schema.brand(\"DomainEventDedupeKey\"))\n\n/** Decoded durable-event deduplication key. */\nexport type DomainEventDedupeKey = typeof DomainEventDedupeKey.Type\n\n/** Positive workspace-local cursor assigned only to persisted events. */\nexport const PersistedEventCursor = EventCursor.check(Schema.isGreaterThan(0))\n\n/** Bounded replay-page size accepted by the repository. */\nexport const DomainEventPageSize = Schema.Int.check(\n Schema.isBetween({ minimum: 1, maximum: MAXIMUM_DOMAIN_EVENT_PAGE_SIZE })\n).pipe(Schema.brand(\"DomainEventPageSize\"))\n\n/** Decoded replay-page size. */\nexport type DomainEventPageSize = typeof DomainEventPageSize.Type\n\n/** Bounded retention batch size accepted by the repository. */\nexport const DomainEventPruneSize = Schema.Int.check(\n Schema.isBetween({ minimum: 1, maximum: MAXIMUM_DOMAIN_EVENT_PRUNE_SIZE })\n).pipe(Schema.brand(\"DomainEventPruneSize\"))\n\n/** Decoded retention batch size. */\nexport type DomainEventPruneSize = typeof DomainEventPruneSize.Type\n\n/** Durable stream head and the highest cursor removed by retention. */\nexport const DomainEventStreamState = Schema.Struct({\n headCursor: EventCursor,\n prunedThroughCursor: EventCursor\n})\n\n/** Decoded durable stream state. */\nexport type DomainEventStreamState = typeof DomainEventStreamState.Type\n\n/** Raw persisted event row decoded before payload integrity verification. */\nexport const DomainEventRow = Schema.Struct({\n workspaceId: WorkspaceId,\n eventCursor: PersistedEventCursor,\n eventId: DomainEventId,\n schemaVersion: Schema.Literal(1),\n eventType: Schema.Literal(\"portfolio-invalidated\"),\n dedupeKey: DomainEventDedupeKey,\n releaseId: Schema.NullOr(ReleaseId),\n pluginConnectionId: Schema.NullOr(PluginConnectionId),\n entityId: Schema.NullOr(EntityId),\n jobId: Schema.NullOr(JobId),\n occurredAt: UtcTimestamp,\n ingestedAt: UtcTimestamp,\n causationId: Schema.NullOr(DomainEventId),\n correlationId: Schema.NullOr(\n DomainEventCorrelationId\n ),\n payloadJson: Schema.String.check(Schema.isNonEmpty()),\n payloadDigest: ContentBlobDigest\n})\n\n/** Decoded raw durable event row. */\nexport type DomainEventRow = typeof DomainEventRow.Type\n\n/** Caller-provided facts required before the repository assigns a cursor and ingest time. */\nexport const AppendDomainEventInput = Schema.Struct({\n dedupeKey: DomainEventDedupeKey,\n schemaVersion: Schema.Literal(1),\n eventId: DomainEventId,\n eventType: Schema.Literal(\"portfolio-invalidated\"),\n occurredAt: UtcTimestamp,\n causationId: Schema.NullOr(DomainEventId),\n correlationId: Schema.NullOr(DomainEventCorrelationId),\n metadata: DomainEventMetadataV1,\n payload: PortfolioInvalidatedPayloadV1\n})\n\n/** Decoded input for one idempotent durable-event append. */\nexport type AppendDomainEventInput = typeof AppendDomainEventInput.Type\n\n/** Result of one bounded replay read. */\nexport type DomainEventPage<Event> =\n | {\n readonly _tag: \"page\"\n readonly events: ReadonlyArray<Event>\n readonly headCursor: typeof EventCursor.Type\n readonly nextCursor: typeof EventCursor.Type\n readonly prunedThroughCursor: typeof EventCursor.Type\n }\n | {\n readonly _tag: \"reset\"\n readonly headCursor: typeof EventCursor.Type\n readonly prunedThroughCursor: typeof EventCursor.Type\n readonly reason: \"cursor-ahead\" | \"gap\" | \"retention\"\n readonly requestedCursor: typeof EventCursor.Type\n }\n\n/** Result of one bounded retention transaction. */\nexport interface DomainEventPruneResult {\n readonly deletedCount: number\n readonly prunedThroughCursor: typeof EventCursor.Type\n}\n","import * as Context from \"effect/Context\"\nimport * as Crypto from \"effect/Crypto\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport type { Success } from \"effect/Effect\"\nimport * as Encoding from \"effect/Encoding\"\nimport * as Layer from \"effect/Layer\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\n\nimport { PortfolioInvalidatedEventV1, PortfolioInvalidatedPayloadV1 } from \"../../../domain/domainEvent.js\"\nimport type { WorkspaceId } from \"../../../domain/identifiers.js\"\nimport { DomainEventId, EventCursor } from \"../../../domain/identifiers.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport { Database } from \"../Database.js\"\nimport {\n PersistedRecordError,\n PersistenceOperationError,\n type QuarantineWriteError,\n SourceIdentityMismatchError\n} from \"../errors.js\"\nimport {\n AppendDomainEventInput,\n type AppendDomainEventInput as AppendDomainEventInputType,\n type DomainEventPage,\n DomainEventPageSize,\n type DomainEventPruneResult,\n DomainEventPruneSize,\n DomainEventRow,\n type DomainEventRow as DomainEventRowType,\n DomainEventStreamState,\n PersistedEventCursor\n} from \"./domainEventModels.js\"\nimport { mapPersistenceOperation } from \"./internal.js\"\nimport { ContentBlobDigest } from \"./models.js\"\nimport { makePersistedRowQuarantine } from \"./persistedRowQuarantine.js\"\nimport { QuarantineRepository } from \"./quarantineRepository.js\"\n\nconst AllocatedCursorRow = Schema.Struct({ eventCursor: PersistedEventCursor })\nconst EventIdentity = Schema.Struct({ eventId: DomainEventId })\nconst payloadJson = Schema.fromJsonString(PortfolioInvalidatedPayloadV1)\n\nconst DedupeSemantic = Schema.Struct({\n schemaVersion: AppendDomainEventInput.fields.schemaVersion,\n eventType: AppendDomainEventInput.fields.eventType,\n occurredAt: AppendDomainEventInput.fields.occurredAt,\n causationId: AppendDomainEventInput.fields.causationId,\n correlationId: AppendDomainEventInput.fields.correlationId,\n metadata: AppendDomainEventInput.fields.metadata,\n payload: AppendDomainEventInput.fields.payload\n})\nconst semanticJson = Schema.fromJsonString(DedupeSemantic)\nconst NO_EVENT_ROWS: ReadonlyArray<unknown> = []\n\nconst encodeDigest = (bytes: Uint8Array): string => Encoding.encodeHex(bytes)\n\nconst metadataColumns = (metadata: AppendDomainEventInputType[\"metadata\"]) => ({\n releaseId: metadata.releaseId ?? null,\n pluginConnectionId: metadata.pluginConnectionId ?? null,\n entityId: metadata.entityId ?? null,\n jobId: metadata.jobId ?? null\n})\n\nconst makeMetadata = (row: DomainEventRowType): Record<string, string> => ({\n ...(row.releaseId === null ? {} : { releaseId: row.releaseId }),\n ...(row.pluginConnectionId === null ? {} : { pluginConnectionId: row.pluginConnectionId }),\n ...(row.entityId === null ? {} : { entityId: row.entityId }),\n ...(row.jobId === null ? {} : { jobId: row.jobId })\n})\n\nconst makeDomainEventRepository = Effect.gen(function*() {\n const cryptoService = yield* Crypto.Crypto\n const database = yield* Database\n const quarantine = yield* QuarantineRepository\n const quarantineRow = makePersistedRowQuarantine(cryptoService, quarantine)\n const sql = database.sql\n\n const digestText = Effect.fn(\"DomainEventRepository.digestText\")(function*(value: string) {\n const bytes = yield* Effect.fromResult(\n Encoding.decodeBase64(Encoding.encodeBase64(value))\n ).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"domain-event.encode\" }))\n )\n const digest = yield* cryptoService.digest(\"SHA-256\", bytes).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"domain-event.digest\" }))\n )\n return ContentBlobDigest.make(encodeDigest(digest))\n })\n\n const findEventRowsByIdentity = (\n workspaceId: typeof WorkspaceId.Type,\n eventId: typeof DomainEventId.Type,\n eventType: AppendDomainEventInputType[\"eventType\"],\n dedupeKey: AppendDomainEventInputType[\"dedupeKey\"]\n ) =>\n sql<Record<string, unknown>>`SELECT\n workspace_id AS workspaceId,\n event_cursor AS eventCursor,\n event_id AS eventId,\n schema_version AS schemaVersion,\n event_type AS eventType,\n dedupe_key AS dedupeKey,\n release_id AS releaseId,\n plugin_connection_id AS pluginConnectionId,\n entity_id AS entityId,\n job_id AS jobId,\n occurred_at AS occurredAt,\n ingested_at AS ingestedAt,\n causation_id AS causationId,\n correlation_id AS correlationId,\n payload_json AS payloadJson,\n payload_digest AS payloadDigest\n FROM domain_events\n WHERE workspace_id = ${workspaceId}\n AND (\n event_id = ${eventId}\n OR (event_type = ${eventType} AND dedupe_key = ${dedupeKey})\n )\n ORDER BY event_cursor`\n\n const findEventRowsAfter = (\n workspaceId: typeof WorkspaceId.Type,\n after: typeof EventCursor.Type,\n limit: typeof DomainEventPageSize.Type\n ) =>\n sql<Record<string, unknown>>`SELECT\n workspace_id AS workspaceId,\n event_cursor AS eventCursor,\n event_id AS eventId,\n schema_version AS schemaVersion,\n event_type AS eventType,\n dedupe_key AS dedupeKey,\n release_id AS releaseId,\n plugin_connection_id AS pluginConnectionId,\n entity_id AS entityId,\n job_id AS jobId,\n occurred_at AS occurredAt,\n ingested_at AS ingestedAt,\n causation_id AS causationId,\n correlation_id AS correlationId,\n payload_json AS payloadJson,\n payload_digest AS payloadDigest\n FROM domain_events\n WHERE workspace_id = ${workspaceId}\n AND event_cursor > ${after}\n ORDER BY event_cursor\n LIMIT ${limit}`\n\n const quarantineMalformed = Effect.fn(\"DomainEventRepository.quarantineMalformed\")(function*(\n workspaceId: typeof WorkspaceId.Type,\n rawRow: unknown,\n diagnosticCode: \"domain-event-payload-digest-mismatch\" | \"domain-event-schema-invalid\",\n diagnosticSummary:\n | \"Stored domain event payload digest does not match its content.\"\n | \"Stored domain event failed schema validation.\"\n ) {\n const identity = Schema.decodeUnknownResult(EventIdentity)(rawRow)\n yield* quarantineRow({\n workspaceId,\n recordKind: \"domain-event\",\n recordKey: Result.isSuccess(identity) ? identity.success.eventId : workspaceId,\n diagnosticCode,\n diagnosticSummary,\n observedAt: yield* DateTime.now,\n row: rawRow\n })\n })\n\n const decodeRow = Effect.fn(\"DomainEventRepository.decodeRow\")(function*(\n workspaceId: typeof WorkspaceId.Type,\n rawRow: unknown\n ) {\n const decodedRow = Schema.decodeUnknownResult(DomainEventRow)(rawRow)\n if (Result.isFailure(decodedRow)) {\n yield* quarantineMalformed(\n workspaceId,\n rawRow,\n \"domain-event-schema-invalid\",\n \"Stored domain event failed schema validation.\"\n )\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"domain-event\",\n recordKey: workspaceId,\n diagnosticCode: \"domain-event-schema-invalid\"\n })\n }\n const row = decodedRow.success\n const actualDigest = yield* digestText(row.payloadJson)\n if (actualDigest !== row.payloadDigest) {\n yield* quarantineMalformed(\n workspaceId,\n rawRow,\n \"domain-event-payload-digest-mismatch\",\n \"Stored domain event payload digest does not match its content.\"\n )\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"domain-event\",\n recordKey: row.eventId,\n diagnosticCode: \"domain-event-payload-digest-mismatch\"\n })\n }\n const payload = yield* Schema.decodeUnknownEffect(payloadJson)(row.payloadJson).pipe(\n Effect.catchTag(\"SchemaError\", () =>\n Effect.gen(function*() {\n yield* quarantineMalformed(\n workspaceId,\n rawRow,\n \"domain-event-schema-invalid\",\n \"Stored domain event failed schema validation.\"\n )\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"domain-event\",\n recordKey: row.eventId,\n diagnosticCode: \"domain-event-schema-invalid\"\n })\n }))\n )\n const decodedEvent = Schema.decodeUnknownResult(Schema.toType(PortfolioInvalidatedEventV1))({\n schemaVersion: row.schemaVersion,\n eventId: row.eventId,\n eventCursor: row.eventCursor,\n workspaceId: row.workspaceId,\n eventType: row.eventType,\n occurredAt: row.occurredAt,\n ingestedAt: row.ingestedAt,\n causationId: row.causationId,\n correlationId: row.correlationId,\n metadata: makeMetadata(row),\n payload\n })\n if (Result.isFailure(decodedEvent)) {\n yield* quarantineMalformed(\n workspaceId,\n rawRow,\n \"domain-event-schema-invalid\",\n \"Stored domain event failed schema validation.\"\n )\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"domain-event\",\n recordKey: row.eventId,\n diagnosticCode: \"domain-event-schema-invalid\"\n })\n }\n return { event: decodedEvent.success, row }\n })\n\n const readStreamState = Effect.fn(\"DomainEventRepository.readStreamState\")(function*(\n workspaceId: typeof WorkspaceId.Type\n ) {\n const rows = yield* sql<Record<string, unknown>>`SELECT\n next_cursor - 1 AS headCursor,\n pruned_through_cursor AS prunedThroughCursor\n FROM domain_event_streams\n WHERE workspace_id = ${workspaceId}`.pipe(\n mapPersistenceOperation(\"domain-event.stream-state\")\n )\n if (rows.length === 0) {\n return DomainEventStreamState.make({\n headCursor: EventCursor.make(0),\n prunedThroughCursor: EventCursor.make(0)\n })\n }\n return yield* Schema.decodeUnknownEffect(DomainEventStreamState)(rows[0]).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"domain-event.stream-state\" }))\n )\n })\n\n const encodeSemantic = Effect.fn(\"DomainEventRepository.encodeSemantic\")(function*(input: {\n readonly schemaVersion: AppendDomainEventInputType[\"schemaVersion\"]\n readonly eventType: AppendDomainEventInputType[\"eventType\"]\n readonly occurredAt: AppendDomainEventInputType[\"occurredAt\"]\n readonly causationId: AppendDomainEventInputType[\"causationId\"]\n readonly correlationId: AppendDomainEventInputType[\"correlationId\"]\n readonly metadata: AppendDomainEventInputType[\"metadata\"]\n readonly payload: AppendDomainEventInputType[\"payload\"]\n }) {\n return yield* Schema.encodeEffect(semanticJson)(input).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"domain-event.encode-semantic\" }))\n )\n })\n\n const append = Effect.fn(\"DomainEventRepository.append\")(function*(\n workspaceId: typeof WorkspaceId.Type,\n input: AppendDomainEventInputType\n ) {\n const decodedInput = yield* Schema.decodeUnknownEffect(\n Schema.toType(AppendDomainEventInput)\n )(input).pipe(\n Effect.mapError(\n () => new PersistenceOperationError({ operation: \"domain-event.append-input\" })\n )\n )\n const encodedPayload = yield* Schema.encodeEffect(payloadJson)(decodedInput.payload).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"domain-event.encode-payload\" }))\n )\n const payloadDigest = yield* digestText(encodedPayload)\n const ingestedAt = yield* DateTime.now\n const encodedOccurredAt = yield* Schema.encodeEffect(UtcTimestamp)(\n decodedInput.occurredAt\n ).pipe(\n Effect.mapError(\n () => new PersistenceOperationError({ operation: \"domain-event.encode-occurred-at\" })\n )\n )\n const encodedIngestedAt = yield* Schema.encodeEffect(UtcTimestamp)(ingestedAt).pipe(\n Effect.mapError(\n () => new PersistenceOperationError({ operation: \"domain-event.encode-ingested-at\" })\n )\n )\n const metadata = metadataColumns(decodedInput.metadata)\n\n const rows = yield* database.transaction(\n Effect.gen(function*() {\n const existing = yield* findEventRowsByIdentity(\n workspaceId,\n decodedInput.eventId,\n decodedInput.eventType,\n decodedInput.dedupeKey\n )\n if (existing.length > 1) {\n return yield* new SourceIdentityMismatchError({\n workspaceId,\n recordKind: \"domain-event\",\n recordKey: decodedInput.eventId\n })\n }\n if (existing.length > 0) return existing\n\n yield* sql`INSERT INTO domain_event_streams (\n workspace_id, next_cursor, pruned_through_cursor, updated_at\n ) VALUES (${workspaceId}, 1, 0, ${encodedIngestedAt})\n ON CONFLICT (workspace_id) DO NOTHING`\n\n const allocatedRows = yield* sql`UPDATE domain_event_streams\n SET next_cursor = next_cursor + 1,\n updated_at = ${encodedIngestedAt}\n WHERE workspace_id = ${workspaceId}\n AND next_cursor < 9007199254740991\n RETURNING next_cursor - 1 AS eventCursor`\n const allocated = yield* Schema.decodeUnknownEffect(Schema.Array(AllocatedCursorRow))(allocatedRows).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"domain-event.allocate-cursor\" }))\n )\n const eventCursor = allocated[0]?.eventCursor\n if (eventCursor === undefined) {\n return yield* new PersistenceOperationError({ operation: \"domain-event.cursor-exhausted\" })\n }\n\n yield* sql`INSERT INTO domain_events (\n workspace_id, event_cursor, event_id, schema_version, event_type,\n dedupe_key, release_id, plugin_connection_id, entity_id, job_id,\n occurred_at, ingested_at, causation_id, correlation_id,\n payload_json, payload_digest\n ) VALUES (\n ${workspaceId}, ${eventCursor}, ${decodedInput.eventId}, ${decodedInput.schemaVersion},\n ${decodedInput.eventType}, ${decodedInput.dedupeKey}, ${metadata.releaseId},\n ${metadata.pluginConnectionId}, ${metadata.entityId}, ${metadata.jobId},\n ${encodedOccurredAt}, ${encodedIngestedAt}, ${decodedInput.causationId},\n ${decodedInput.correlationId}, ${encodedPayload}, ${payloadDigest}\n )`\n return yield* findEventRowsByIdentity(\n workspaceId,\n decodedInput.eventId,\n decodedInput.eventType,\n decodedInput.dedupeKey\n )\n })\n ).pipe(mapPersistenceOperation(\"domain-event.append\"))\n\n const rawRow = rows[0]\n if (rawRow === undefined) {\n return yield* new PersistenceOperationError({ operation: \"domain-event.append-read\" })\n }\n const persisted = yield* decodeRow(workspaceId, rawRow)\n const expectedSemantic = yield* encodeSemantic(decodedInput)\n const actualSemantic = yield* encodeSemantic(persisted.event)\n if (expectedSemantic !== actualSemantic || persisted.row.dedupeKey !== decodedInput.dedupeKey) {\n return yield* new SourceIdentityMismatchError({\n workspaceId,\n recordKind: \"domain-event\",\n recordKey: persisted.event.eventId\n })\n }\n return persisted.event\n })\n\n const pageAfter = Effect.fn(\"DomainEventRepository.pageAfter\")(function*(\n workspaceId: typeof WorkspaceId.Type,\n after: typeof EventCursor.Type,\n requestedLimit: number\n ): Effect.fn.Return<\n DomainEventPage<typeof PortfolioInvalidatedEventV1.Type>,\n PersistenceOperationError | QuarantineWriteError,\n never\n > {\n const cursor = yield* Schema.decodeUnknownEffect(EventCursor)(after).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"domain-event.after-cursor\" }))\n )\n const limit = yield* Schema.decodeUnknownEffect(DomainEventPageSize)(requestedLimit).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"domain-event.page-size\" }))\n )\n const snapshot = yield* database.transaction(\n Effect.gen(function*() {\n const state = yield* readStreamState(workspaceId)\n if (cursor < state.prunedThroughCursor || cursor > state.headCursor) {\n return { state, rows: NO_EVENT_ROWS }\n }\n const rows = yield* findEventRowsAfter(workspaceId, cursor, limit)\n return { state, rows }\n })\n ).pipe(mapPersistenceOperation(\"domain-event.page\"))\n\n if (cursor < snapshot.state.prunedThroughCursor) {\n return {\n _tag: \"reset\",\n reason: \"retention\",\n requestedCursor: cursor,\n ...snapshot.state\n }\n }\n if (cursor > snapshot.state.headCursor) {\n return {\n _tag: \"reset\",\n reason: \"cursor-ahead\",\n requestedCursor: cursor,\n ...snapshot.state\n }\n }\n\n const decodedResult = yield* Effect.forEach(\n snapshot.rows,\n (row) => decodeRow(workspaceId, row)\n ).pipe(Effect.result)\n if (Result.isFailure(decodedResult)) {\n if (decodedResult.failure._tag === \"PersistedRecordError\") {\n return {\n _tag: \"reset\",\n reason: \"gap\",\n requestedCursor: cursor,\n ...snapshot.state\n }\n }\n return yield* decodedResult.failure\n }\n const decoded = decodedResult.success\n let expectedCursor = cursor + 1\n for (const persisted of decoded) {\n if (persisted.event.eventCursor !== expectedCursor) {\n return {\n _tag: \"reset\",\n reason: \"gap\",\n requestedCursor: cursor,\n ...snapshot.state\n }\n }\n expectedCursor += 1\n }\n if (decoded.length === 0 && cursor < snapshot.state.headCursor) {\n return {\n _tag: \"reset\",\n reason: \"gap\",\n requestedCursor: cursor,\n ...snapshot.state\n }\n }\n const nextCursor = decoded.at(-1)?.event.eventCursor ?? cursor\n return {\n _tag: \"page\",\n events: decoded.map(({ event }) => event),\n headCursor: snapshot.state.headCursor,\n nextCursor,\n prunedThroughCursor: snapshot.state.prunedThroughCursor\n }\n })\n\n const prune = Effect.fn(\"DomainEventRepository.prune\")(function*(\n workspaceId: typeof WorkspaceId.Type,\n throughCursor: typeof EventCursor.Type,\n requestedLimit: number\n ): Effect.fn.Return<DomainEventPruneResult, PersistenceOperationError, never> {\n const cursor = yield* Schema.decodeUnknownEffect(EventCursor)(throughCursor).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"domain-event.prune-cursor\" }))\n )\n const limit = yield* Schema.decodeUnknownEffect(DomainEventPruneSize)(requestedLimit).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"domain-event.prune-size\" }))\n )\n return yield* database.transaction(\n Effect.gen(function*() {\n const state = yield* readStreamState(workspaceId)\n const deleted = yield* sql<{ readonly eventCursor: number }>`DELETE FROM domain_events\n WHERE workspace_id = ${workspaceId}\n AND event_cursor IN (\n SELECT event_cursor\n FROM domain_events\n WHERE workspace_id = ${workspaceId}\n AND event_cursor <= ${cursor}\n ORDER BY event_cursor\n LIMIT ${limit}\n )\n RETURNING event_cursor AS eventCursor`\n const prunedThrough = deleted.reduce<number>(\n (maximum, row) => Math.max(maximum, row.eventCursor),\n state.prunedThroughCursor\n )\n if (deleted.length > 0) {\n yield* sql`UPDATE domain_event_streams\n SET pruned_through_cursor = MAX(pruned_through_cursor, ${prunedThrough})\n WHERE workspace_id = ${workspaceId}`\n }\n return {\n deletedCount: deleted.length,\n prunedThroughCursor: EventCursor.make(prunedThrough)\n }\n })\n ).pipe(mapPersistenceOperation(\"domain-event.prune\"))\n })\n\n return { append, pageAfter, prune, streamState: readStreamState }\n})\n\n/** Workspace-local durable event outbox with bounded replay and retention. */\nexport interface DomainEventRepositoryService extends Success<typeof makeDomainEventRepository> {}\n\n/** Effect service for durable workspace event streams. */\nexport class DomainEventRepository extends Context.Service<\n DomainEventRepository,\n DomainEventRepositoryService\n>()(\"@knpkv/control-center/DomainEventRepository\") {\n /** Layer that binds event queries, integrity checks, and quarantine writes. */\n static readonly layer = Layer.effect(DomainEventRepository, makeDomainEventRepository)\n}\n","import { type RenderedSql, renderEntitySourceIdentityQuery } from \"@knpkv/control-center-sql\"\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 type { Success } from \"effect/Effect\"\nimport * as Encoding from \"effect/Encoding\"\nimport * as Layer from \"effect/Layer\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\"\n\nimport { EntityId, type PluginConnectionId, WorkspaceId } from \"../../../domain/identifiers.js\"\nimport {\n NormalizationSchemaVersion,\n ProviderId,\n Revision,\n SourceRevision,\n SourceUrl,\n VendorImmutableId\n} from \"../../../domain/sourceRevision.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport { Database } from \"../Database.js\"\nimport {\n PersistedRecordError,\n PersistenceOperationError,\n RecordNotFoundError,\n SourceIdentityMismatchError\n} from \"../errors.js\"\nimport {\n mapAlreadyExists,\n mapPersistenceOperation,\n readChanges,\n resolveCasFailure,\n revisionLookup\n} from \"./internal.js\"\nimport { ContentBlobDigest, EntityKind, EntityRecord, RecordRevision } from \"./models.js\"\nimport { QuarantineRepository } from \"./quarantineRepository.js\"\n\nconst EntityKey = Schema.Struct({ workspaceId: WorkspaceId, entityId: EntityId })\n\nconst EntityRow = Schema.Struct({\n workspaceId: WorkspaceId,\n entityId: EntityId,\n entityType: EntityKind,\n recordRevision: RecordRevision,\n pluginConnectionId: SourceRevision.fields.pluginConnectionId,\n providerId: ProviderId,\n vendorImmutableId: VendorImmutableId,\n sourceRevision: Revision,\n normalizationSchemaVersion: NormalizationSchemaVersion,\n sourceUrl: Schema.Union([SourceUrl, Schema.Null]),\n firstObservedAt: UtcTimestamp,\n lastObservedAt: UtcTimestamp,\n synchronizedAt: UtcTimestamp,\n createdAt: UtcTimestamp,\n updatedAt: UtcTimestamp\n})\n\nconst CreateEntityRequest = Schema.Struct({\n ...EntityKey.fields,\n entityType: EntityKind,\n sourceRevision: SourceRevision,\n createdAt: UtcTimestamp\n})\n\nconst UpdateEntityRequest = Schema.Struct({\n ...EntityKey.fields,\n sourceRevision: SourceRevision,\n expectedRevision: RecordRevision,\n updatedAt: UtcTimestamp\n})\n\nconst EntityIdentityHead = Schema.Struct({\n entityId: EntityId,\n recordRevision: RecordRevision,\n pluginConnectionId: SourceRevision.fields.pluginConnectionId,\n providerId: ProviderId,\n vendorImmutableId: VendorImmutableId\n})\n\nconst EntityRevisionIdentity = Schema.Struct({\n entityId: EntityId,\n recordRevision: RecordRevision\n})\n\nconst decodeEntityRecord = Effect.fn(\"EntityRepository.decodeRecord\")(function*(row: typeof EntityRow.Type) {\n return yield* Schema.decodeUnknownEffect(Schema.toType(EntityRecord))({\n workspaceId: row.workspaceId,\n entityId: row.entityId,\n entityType: row.entityType,\n revision: row.recordRevision,\n sourceRevision: {\n pluginConnectionId: row.pluginConnectionId,\n providerId: row.providerId,\n vendorImmutableId: row.vendorImmutableId,\n revision: row.sourceRevision,\n normalizationSchemaVersion: row.normalizationSchemaVersion,\n sourceUrl: row.sourceUrl,\n firstObservedAt: row.firstObservedAt,\n lastObservedAt: row.lastObservedAt,\n synchronizedAt: row.synchronizedAt\n },\n createdAt: row.createdAt,\n updatedAt: row.updatedAt\n })\n})\n\nconst makeEntityRepository = Effect.gen(function*() {\n const cryptoService = yield* Crypto.Crypto\n const database = yield* Database\n const quarantine = yield* QuarantineRepository\n const sql = database.sql\n const run = (plan: RenderedSql) => sql.unsafe<Record<string, unknown>>(plan.sql, [...plan.params])\n\n const digestPersistedRow = Effect.fn(\"EntityRepository.digestPersistedRow\")(function*(row: unknown) {\n const serialized = yield* Effect.try({\n try: () => JSON.stringify(row),\n catch: () => new PersistenceOperationError({ operation: \"entity.quarantine-encode\" })\n })\n const bytes = yield* Effect.fromResult(\n Encoding.decodeBase64(Encoding.encodeBase64(serialized))\n ).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"entity.quarantine-encode\" }))\n )\n const digest = yield* cryptoService.digest(\"SHA-256\", bytes).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"entity.quarantine-digest\" }))\n )\n return ContentBlobDigest.make(Encoding.encodeHex(digest))\n })\n\n const quarantineMalformedRevision = Effect.fn(\"EntityRepository.quarantineMalformed\")(function*(\n workspaceId: WorkspaceId,\n row: unknown,\n identity: Result.Result<typeof EntityRevisionIdentity.Type, Schema.SchemaError>\n ) {\n const payloadDigest = yield* digestPersistedRow(row)\n const observedAt = yield* DateTime.now\n yield* quarantine.recordMalformed(workspaceId, {\n recordKind: \"entity-revision\",\n recordKey: Result.isSuccess(identity)\n ? `${identity.success.entityId}:${identity.success.recordRevision}`\n : workspaceId,\n schemaVersion: 1,\n payloadDigest,\n diagnosticCode: \"entity-revision-schema-invalid\",\n diagnosticSummary: \"Stored entity revision failed schema validation.\",\n observedAt\n })\n })\n\n const selectColumns = sql`SELECT\n entity.workspace_id AS workspaceId,\n entity.entity_id AS entityId,\n entity.entity_type AS entityType,\n revision.revision AS recordRevision,\n entity.plugin_connection_id AS pluginConnectionId,\n entity.provider_id AS providerId,\n entity.vendor_immutable_id AS vendorImmutableId,\n revision.source_revision AS sourceRevision,\n revision.normalization_schema_version AS normalizationSchemaVersion,\n revision.source_url AS sourceUrl,\n revision.first_observed_at AS firstObservedAt,\n revision.last_observed_at AS lastObservedAt,\n revision.synchronized_at AS synchronizedAt,\n entity.created_at AS createdAt,\n entity.updated_at AS updatedAt\n FROM entities AS entity\n INNER JOIN entity_revisions AS revision\n ON revision.workspace_id = entity.workspace_id\n AND revision.entity_id = entity.entity_id\n AND revision.revision <= entity.current_revision`\n\n const findRows = ({ entityId, workspaceId }: typeof EntityKey.Type) =>\n sql<Record<string, unknown>>`${selectColumns}\n WHERE entity.workspace_id = ${workspaceId}\n AND entity.entity_id = ${entityId}\n ORDER BY revision.revision DESC`\n\n const listRows = (workspaceId: WorkspaceId) =>\n sql<Record<string, unknown>>`${selectColumns}\n WHERE entity.workspace_id = ${workspaceId}\n ORDER BY entity.updated_at DESC, entity.entity_id, revision.revision DESC`\n\n const get = Effect.fn(\"EntityRepository.get\")(function*(\n workspaceId: WorkspaceId,\n entityId: EntityId\n ) {\n const headRows = yield* findIdentityHeadRows({ workspaceId, entityId }).pipe(\n mapPersistenceOperation(\"entity.get-head\")\n )\n if (headRows.length === 0) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"entity\",\n recordKey: entityId\n })\n }\n const head = Schema.decodeUnknownResult(EntityIdentityHead)(headRows[0])\n if (Result.isFailure(head)) {\n yield* quarantineMalformedRevision(\n workspaceId,\n headRows[0],\n Schema.decodeUnknownResult(EntityRevisionIdentity)(headRows[0])\n )\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"entity\",\n recordKey: entityId,\n diagnosticCode: \"entity-revision-schema-invalid\"\n })\n }\n const rows = yield* findRows({ workspaceId, entityId }).pipe(\n mapPersistenceOperation(\"entity.get-revisions\")\n )\n for (const row of rows) {\n const identity = Schema.decodeUnknownResult(EntityRevisionIdentity)(row)\n const decoded = Schema.decodeUnknownResult(EntityRow)(row)\n if (Result.isFailure(decoded)) {\n yield* quarantineMalformedRevision(workspaceId, row, identity)\n continue\n }\n const record = yield* decodeEntityRecord(decoded.success).pipe(Effect.result)\n if (Result.isFailure(record)) {\n yield* quarantineMalformedRevision(workspaceId, row, identity)\n continue\n }\n return record.success\n }\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"entity\",\n recordKey: entityId,\n diagnosticCode: \"no-valid-entity-revision\"\n })\n })\n\n const insertHead = SqlSchema.void({\n Request: CreateEntityRequest,\n execute: ({ createdAt, entityId, entityType, sourceRevision, workspaceId }) =>\n sql`INSERT INTO entities (\n workspace_id, entity_id, plugin_connection_id, provider_id,\n vendor_immutable_id, entity_type, current_revision, created_at, updated_at\n ) VALUES (\n ${workspaceId}, ${entityId}, ${sourceRevision.pluginConnectionId}, ${sourceRevision.providerId},\n ${sourceRevision.vendorImmutableId}, ${entityType}, 1, ${createdAt}, ${createdAt}\n )`\n })\n\n const insertRevision = SqlSchema.void({\n Request: Schema.Struct({\n ...EntityKey.fields,\n revision: RecordRevision,\n sourceRevision: SourceRevision,\n createdAt: UtcTimestamp\n }),\n execute: ({ createdAt, entityId, revision, sourceRevision, workspaceId }) =>\n sql`INSERT INTO entity_revisions (\n workspace_id, entity_id, revision, source_revision,\n normalization_schema_version, source_url, first_observed_at,\n last_observed_at, synchronized_at, created_at\n ) VALUES (\n ${workspaceId}, ${entityId}, ${revision}, ${sourceRevision.revision},\n ${sourceRevision.normalizationSchemaVersion}, ${sourceRevision.sourceUrl},\n ${sourceRevision.firstObservedAt}, ${sourceRevision.lastObservedAt},\n ${sourceRevision.synchronizedAt}, ${createdAt}\n )`\n })\n\n const updateHead = SqlSchema.void({\n Request: UpdateEntityRequest,\n execute: ({ entityId, expectedRevision, updatedAt, workspaceId }) =>\n sql`UPDATE entities\n SET current_revision = current_revision + 1,\n updated_at = ${updatedAt}\n WHERE workspace_id = ${workspaceId}\n AND entity_id = ${entityId}\n AND current_revision = ${expectedRevision}`\n })\n\n const findIdentityHeadRows = ({ entityId, workspaceId }: typeof EntityKey.Type) =>\n sql<Record<string, unknown>>`SELECT\n entity_id AS entityId,\n current_revision AS recordRevision,\n plugin_connection_id AS pluginConnectionId,\n provider_id AS providerId,\n vendor_immutable_id AS vendorImmutableId\n FROM entities\n WHERE workspace_id = ${workspaceId}\n AND entity_id = ${entityId}`\n\n const listIdentityHeadRows = (workspaceId: WorkspaceId) =>\n sql<Record<string, unknown>>`SELECT\n entity_id AS entityId,\n current_revision AS recordRevision,\n plugin_connection_id AS pluginConnectionId,\n provider_id AS providerId,\n vendor_immutable_id AS vendorImmutableId\n FROM entities\n WHERE workspace_id = ${workspaceId}\n ORDER BY entity_id`\n\n const findBySourceIdentity = Effect.fn(\"EntityRepository.findBySourceIdentity\")(function*(\n workspaceId: WorkspaceId,\n identity: {\n readonly pluginConnectionId: PluginConnectionId\n readonly providerId: ProviderId\n readonly vendorImmutableId: VendorImmutableId\n }\n ) {\n const rows = yield* run(renderEntitySourceIdentityQuery({ workspaceId, ...identity })).pipe(\n mapPersistenceOperation(\"entity.find-by-source-identity\")\n )\n if (rows.length === 0) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"entity-source-identity\",\n recordKey: identity.pluginConnectionId\n })\n }\n const decoded = Schema.decodeUnknownResult(Schema.Struct({ entityId: EntityId }))(rows[0])\n if (Result.isFailure(decoded)) {\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"entity-source-identity\",\n recordKey: identity.pluginConnectionId,\n diagnosticCode: \"entity-revision-schema-invalid\"\n })\n }\n return yield* get(workspaceId, decoded.success.entityId)\n })\n\n return {\n create: Effect.fn(\"EntityRepository.create\")(function*(\n workspaceId: WorkspaceId,\n input: {\n readonly entityId: EntityId\n readonly entityType: EntityKind\n readonly sourceRevision: SourceRevision\n readonly createdAt: UtcTimestamp\n }\n ) {\n yield* database.transaction(\n Effect.gen(function*() {\n yield* insertHead({ workspaceId, ...input })\n yield* insertRevision({\n workspaceId,\n entityId: input.entityId,\n revision: RecordRevision.make(1),\n sourceRevision: input.sourceRevision,\n createdAt: input.createdAt\n })\n }).pipe(\n mapAlreadyExists({ workspaceId, recordKind: \"entity\", recordKey: input.entityId }),\n mapPersistenceOperation(\"entity.create\")\n )\n )\n return yield* get(workspaceId, input.entityId)\n }),\n findBySourceIdentity,\n get,\n list: Effect.fn(\"EntityRepository.list\")(function*(workspaceId: WorkspaceId) {\n const headRows = yield* listIdentityHeadRows(workspaceId).pipe(\n mapPersistenceOperation(\"entity.list-heads\")\n )\n const validHeads = new Set<EntityId>()\n for (const row of headRows) {\n const head = Schema.decodeUnknownResult(EntityIdentityHead)(row)\n if (Result.isSuccess(head)) {\n validHeads.add(head.success.entityId)\n } else {\n yield* quarantineMalformedRevision(\n workspaceId,\n row,\n Schema.decodeUnknownResult(EntityRevisionIdentity)(row)\n )\n }\n }\n const rows = yield* listRows(workspaceId).pipe(mapPersistenceOperation(\"entity.list\"))\n const records: Array<EntityRecord> = []\n const resolved = new Set<EntityId>()\n for (const row of rows) {\n const identity = Schema.decodeUnknownResult(EntityRevisionIdentity)(row)\n if (Result.isSuccess(identity) && !validHeads.has(identity.success.entityId)) continue\n if (Result.isSuccess(identity) && resolved.has(identity.success.entityId)) continue\n const decoded = Schema.decodeUnknownResult(EntityRow)(row)\n if (Result.isFailure(decoded)) {\n yield* quarantineMalformedRevision(workspaceId, row, identity)\n continue\n }\n const record = yield* decodeEntityRecord(decoded.success).pipe(Effect.result)\n if (Result.isFailure(record)) {\n yield* quarantineMalformedRevision(workspaceId, row, identity)\n continue\n }\n records.push(record.success)\n resolved.add(decoded.success.entityId)\n }\n return records\n }),\n updateSourceRevision: Effect.fn(\"EntityRepository.updateSourceRevision\")(function*(\n workspaceId: WorkspaceId,\n entityId: EntityId,\n input: {\n readonly sourceRevision: SourceRevision\n readonly expectedRevision: RecordRevision\n readonly updatedAt: UtcTimestamp\n }\n ) {\n yield* database.transaction(\n Effect.gen(function*() {\n const identityHeadRows = yield* findIdentityHeadRows({ workspaceId, entityId })\n if (identityHeadRows.length === 0) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"entity\",\n recordKey: entityId\n })\n }\n const identityHead = Schema.decodeUnknownResult(EntityIdentityHead)(identityHeadRows[0])\n if (Result.isFailure(identityHead)) {\n yield* quarantineMalformedRevision(\n workspaceId,\n identityHeadRows[0],\n Schema.decodeUnknownResult(EntityRevisionIdentity)(identityHeadRows[0])\n )\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"entity\",\n recordKey: entityId,\n diagnosticCode: \"entity-revision-schema-invalid\"\n })\n }\n if (\n identityHead.success.pluginConnectionId !== input.sourceRevision.pluginConnectionId ||\n identityHead.success.providerId !== input.sourceRevision.providerId ||\n identityHead.success.vendorImmutableId !== input.sourceRevision.vendorImmutableId\n ) {\n return yield* new SourceIdentityMismatchError({\n workspaceId,\n recordKind: \"entity\",\n recordKey: entityId\n })\n }\n yield* updateHead({ workspaceId, entityId, ...input })\n const changes = yield* readChanges(sql)\n if (changes === 0) {\n return yield* resolveCasFailure({\n workspaceId,\n recordKind: \"entity\",\n recordKey: entityId,\n expectedRevision: input.expectedRevision,\n findActualRevision: revisionLookup(() =>\n sql`SELECT current_revision AS revision\n FROM entities\n WHERE workspace_id = ${workspaceId}\n AND entity_id = ${entityId}`\n )\n })\n }\n yield* insertRevision({\n workspaceId,\n entityId,\n revision: RecordRevision.make(input.expectedRevision + 1),\n sourceRevision: input.sourceRevision,\n createdAt: input.updatedAt\n })\n })\n ).pipe(mapPersistenceOperation(\"entity.update\"))\n return yield* get(workspaceId, entityId)\n })\n }\n})\n\n/** Workspace-scoped normalized entity persistence with immutable revisions. */\nexport interface EntityRepositoryService extends Success<typeof makeEntityRepository> {}\n\n/** Effect service for normalized delivery entities. */\nexport class EntityRepository extends Context.Service<EntityRepository, EntityRepositoryService>()(\n \"@knpkv/control-center/EntityRepository\"\n) {\n /** Layer that binds SQL queries to the shared database at construction. */\n static readonly layer = Layer.effect(EntityRepository, makeEntityRepository)\n}\n","import * as DateTime from \"effect/DateTime\"\nimport * as Schema from \"effect/Schema\"\n\nimport {\n GovernedActionAttemptV1,\n GovernedActionAuthorizationV1,\n GovernedActionCommandId,\n GovernedActionEnvelopeV1,\n GovernedActionLifecycleHeadV1,\n governedActionPermissionGrants,\n GovernedActionPolicyEvaluationV1,\n GovernedActionTransitionCause,\n GovernedActionTransitionCommand,\n GovernedActionTransitionV1\n} from \"../../../../domain/governedAction/index.js\"\nimport {\n DomainEventId,\n EntityId,\n GovernedActionId,\n GovernedActionTransitionId,\n PluginConnectionId,\n ReleaseId,\n WorkspaceId\n} from \"../../../../domain/identifiers.js\"\nimport { ProviderId, Revision } from \"../../../../domain/sourceRevision.js\"\nimport { UtcTimestamp } from \"../../../../domain/utcTimestamp.js\"\n\n/** Immutable identity of the audit record paired with one action transition. */\nexport const GovernedActionAuditEventId = DomainEventId\n\n/** Decoded governed-action audit identity. */\nexport type GovernedActionAuditEventId = typeof GovernedActionAuditEventId.Type\n\n/** Authority records that must commit in the same transaction as their transition. */\nexport const GovernedActionCommitCompanion = Schema.TaggedUnion({\n none: {},\n authorization: { authorization: GovernedActionAuthorizationV1 },\n dispatch: {\n policyEvaluation: GovernedActionPolicyEvaluationV1,\n attempt: GovernedActionAttemptV1\n },\n policyDenial: { policyEvaluation: GovernedActionPolicyEvaluationV1 }\n})\n\n/** Decoded authority companion. */\nexport type GovernedActionCommitCompanion = typeof GovernedActionCommitCompanion.Type\n\nconst companionMatchesCommand = ({\n command,\n companion\n}: {\n readonly command: GovernedActionTransitionCommand\n readonly companion: GovernedActionCommitCompanion\n}): boolean => {\n switch (command._tag) {\n case \"authorize\":\n return companion._tag === \"authorization\" &&\n companion.authorization.authorizationId === command.authorizationId\n case \"start\":\n return companion._tag === \"dispatch\" && companion.attempt.attemptId === command.attemptId\n case \"deny\":\n return companion._tag === \"none\" || companion._tag === \"policyDenial\"\n case \"propose\":\n case \"expire\":\n case \"cancel\":\n case \"requestCancellation\":\n case \"recordAccepted\":\n case \"recordSucceeded\":\n case \"recordFailed\":\n case \"recordUnknown\":\n case \"recordCancelled\":\n case \"reconciliationPending\":\n return companion._tag === \"none\"\n }\n}\n\n/** Caller intent; lifecycle state, sequence, lineage, and audit payload are derived by the repository. */\nexport const GovernedActionCommitInput = Schema.Struct({\n envelope: GovernedActionEnvelopeV1,\n expectedHeadTransitionId: Schema.NullOr(GovernedActionTransitionId),\n transitionId: GovernedActionTransitionId,\n commandId: GovernedActionCommandId,\n command: GovernedActionTransitionCommand,\n cause: GovernedActionTransitionCause,\n occurredAt: UtcTimestamp,\n causationId: GovernedActionTransitionV1.fields.causationId,\n correlationId: GovernedActionTransitionV1.fields.correlationId,\n companion: GovernedActionCommitCompanion,\n auditEventId: GovernedActionAuditEventId\n}).check(\n Schema.makeFilter(companionMatchesCommand, {\n expected: \"authority companion to match the lifecycle command\"\n }),\n Schema.makeFilter(\n ({ command, expectedHeadTransitionId }) => (command._tag === \"propose\") === (expectedHeadTransitionId === null),\n { expected: \"only a proposal to begin without an expected lifecycle head\" }\n ),\n Schema.makeFilter(\n ({ cause, command, envelope }) => {\n if (command._tag !== \"propose\") return true\n if (envelope.origin._tag === \"human\" && cause._tag === \"human\") {\n return envelope.origin.actor.personId === cause.actor.personId &&\n envelope.origin.sessionId === cause.sessionId\n }\n if (envelope.origin._tag === \"agent\" && cause._tag === \"agent\") {\n return envelope.origin.actor.agentId === cause.actor.agentId && envelope.origin.jobId === cause.jobId\n }\n return false\n },\n { expected: \"proposal cause to match its immutable origin\" }\n ),\n Schema.makeFilter(\n ({ cause, command, companion, envelope, occurredAt }) =>\n companion._tag !== \"authorization\" ||\n (command._tag === \"authorize\" &&\n companion.authorization.workspaceId === envelope.workspaceId &&\n companion.authorization.actionId === envelope.actionId &&\n companion.authorization.pluginConnectionId === envelope.pluginConnectionId &&\n companion.authorization.pluginConnectionRevision === envelope.pluginConnectionRevision &&\n companion.authorization.pluginConnectionAuthorityDigest === envelope.pluginConnectionAuthorityDigest &&\n companion.authorization.actionEnvelopeDigest === envelope.envelopeDigest &&\n companion.authorization.idempotencyKey === envelope.idempotencyKey &&\n companion.authorization.payloadDigest === envelope.proposal.payloadDigest &&\n companion.authorization.evidenceSetDigest === envelope.evidenceSetDigest &&\n companion.authorization.policyDigest === envelope.policy.policyDigest &&\n companion.authorization.expectedRevision === envelope.proposal.request.expectedRevision &&\n companion.authorization.capabilityVersion === envelope.capability.version &&\n companion.authorization.requiredPermission === envelope.policy.requiredPermission &&\n governedActionPermissionGrants(\n companion.authorization.sessionPermission,\n companion.authorization.requiredPermission\n ) &&\n cause._tag === \"human\" &&\n companion.authorization.actor.personId === cause.actor.personId &&\n companion.authorization.sessionId === cause.sessionId &&\n companion.authorization.authorizationId === command.authorizationId &&\n DateTime.Order(companion.authorization.authorizedAt, occurredAt) === 0 &&\n DateTime.Order(companion.authorization.authorizedAt, envelope.proposal.proposedAt) >= 0 &&\n DateTime.Order(companion.authorization.authorizedAt, envelope.proposalExpiresAt) < 0 &&\n DateTime.Order(companion.authorization.expiresAt, envelope.proposalExpiresAt) <= 0),\n { expected: \"authorization to bind the exact action and transition\" }\n ),\n Schema.makeFilter(\n ({ companion, envelope, occurredAt }) => {\n if (companion._tag !== \"dispatch\") return true\n return companion.attempt.workspaceId === envelope.workspaceId &&\n companion.attempt.actionId === envelope.actionId &&\n companion.attempt.actionEnvelopeDigest === envelope.envelopeDigest &&\n companion.attempt.idempotencyKey === envelope.idempotencyKey &&\n companion.attempt.pluginConnectionId === envelope.pluginConnectionId &&\n companion.attempt.expectedRevision === envelope.proposal.request.expectedRevision &&\n companion.policyEvaluation.workspaceId === envelope.workspaceId &&\n companion.policyEvaluation.actionId === envelope.actionId &&\n companion.policyEvaluation.policy.policyId === envelope.policy.policyId &&\n companion.policyEvaluation.policy.policyVersion === envelope.policy.policyVersion &&\n companion.policyEvaluation.policy.policyDigest === envelope.policy.policyDigest &&\n companion.policyEvaluation.policy.requiredPermission === envelope.policy.requiredPermission &&\n companion.policyEvaluation.payloadDigest === envelope.proposal.payloadDigest &&\n companion.policyEvaluation.evidenceSetDigest === envelope.evidenceSetDigest &&\n companion.policyEvaluation.expectedRevision === envelope.proposal.request.expectedRevision &&\n companion.policyEvaluation.decision === \"allowed\" &&\n DateTime.Order(companion.policyEvaluation.evaluatedAt, envelope.proposal.proposedAt) >= 0 &&\n DateTime.Order(companion.policyEvaluation.evaluatedAt, companion.attempt.startedAt) === 0 &&\n DateTime.Order(companion.attempt.startedAt, occurredAt) === 0 &&\n DateTime.Order(companion.attempt.startedAt, envelope.proposalExpiresAt) < 0 &&\n envelope.evidence.every((reference) =>\n reference.source === \"current\" &&\n DateTime.Order(reference.evaluatedAt, companion.attempt.startedAt) <= 0 &&\n (reference.currentUntil === null ||\n DateTime.Order(companion.attempt.startedAt, reference.currentUntil) < 0) &&\n (reference.validUntil === null ||\n DateTime.Order(companion.attempt.startedAt, reference.validUntil) < 0)\n )\n },\n { expected: \"dispatch authority to bind the exact action envelope\" }\n ),\n Schema.makeFilter(\n ({ companion, envelope, occurredAt }) =>\n companion._tag !== \"policyDenial\" ||\n (companion.policyEvaluation.workspaceId === envelope.workspaceId &&\n companion.policyEvaluation.actionId === envelope.actionId &&\n companion.policyEvaluation.policy.policyId === envelope.policy.policyId &&\n companion.policyEvaluation.policy.policyVersion === envelope.policy.policyVersion &&\n companion.policyEvaluation.policy.policyDigest === envelope.policy.policyDigest &&\n companion.policyEvaluation.policy.requiredPermission === envelope.policy.requiredPermission &&\n companion.policyEvaluation.payloadDigest === envelope.proposal.payloadDigest &&\n companion.policyEvaluation.evidenceSetDigest === envelope.evidenceSetDigest &&\n companion.policyEvaluation.expectedRevision === envelope.proposal.request.expectedRevision &&\n companion.policyEvaluation.decision === \"denied\" &&\n DateTime.Order(companion.policyEvaluation.evaluatedAt, occurredAt) <= 0),\n { expected: \"denied policy evaluation to bind the exact action inputs\" }\n )\n)\n\n/** Decoded atomic governed-action commit intent. */\nexport type GovernedActionCommitInput = typeof GovernedActionCommitInput.Type\n\n/** Workspace-scoped aggregate lookup. */\nexport const GovernedActionReadInput = Schema.Struct({\n workspaceId: WorkspaceId,\n actionId: GovernedActionId\n})\n\n/** Decoded governed-action lookup. */\nexport type GovernedActionReadInput = typeof GovernedActionReadInput.Type\n\n/** Workspace/connection-scoped lookup for a previously submitted idempotent action. */\nexport const GovernedActionIdempotencyReadInput = Schema.Struct({\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n idempotencyKey: GovernedActionEnvelopeV1.fields.idempotencyKey\n})\n\n/** Decoded governed-action idempotency lookup. */\nexport type GovernedActionIdempotencyReadInput = typeof GovernedActionIdempotencyReadInput.Type\n\n/** Bounded newest-first terminal action lookup for one exact workspace entity. */\nexport const GovernedActionTargetReadInput = Schema.Struct({\n workspaceId: WorkspaceId,\n providerId: ProviderId,\n targetEntityId: EntityId,\n actionKind: GovernedActionEnvelopeV1.fields.proposal.fields.request.fields.actionKind,\n expectedRevision: Schema.optionalKey(Revision),\n limit: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 }))\n})\n\n/** Decoded newest terminal target lookup. */\nexport type GovernedActionTargetReadInput = typeof GovernedActionTargetReadInput.Type\n\n/** Bounded batched lookup for the latest successful publications of exact releases. */\nexport const GovernedActionReleasePublicationReadInput = Schema.Struct({\n workspaceId: WorkspaceId,\n providerId: Schema.Literal(\"confluence\"),\n releaseIds: Schema.Array(ReleaseId).check(\n Schema.isMinLength(1),\n Schema.isMaxLength(200),\n Schema.isUnique()\n )\n})\n\n/** Decoded release-publication batch lookup. */\nexport type GovernedActionReleasePublicationReadInput = typeof GovernedActionReleasePublicationReadInput.Type\n\n/** Trusted governed action reconstructed from its immutable ordered history. */\nexport const GovernedActionRecord = Schema.Struct({\n envelope: GovernedActionEnvelopeV1,\n head: GovernedActionLifecycleHeadV1,\n headTransition: GovernedActionTransitionV1,\n history: Schema.Array(GovernedActionTransitionV1).check(Schema.isNonEmpty()),\n authorization: Schema.NullOr(GovernedActionAuthorizationV1),\n policyEvaluation: Schema.NullOr(GovernedActionPolicyEvaluationV1),\n attempt: Schema.NullOr(GovernedActionAttemptV1)\n})\n\n/** Decoded governed-action aggregate. */\nexport type GovernedActionRecord = typeof GovernedActionRecord.Type\n\n/** Exact command commit or replay result. Replays never carry an execution permit. */\nexport type GovernedActionCommitResult =\n | { readonly _tag: \"committed\"; readonly transition: GovernedActionTransitionV1 }\n | { readonly _tag: \"replayed\"; readonly transition: GovernedActionTransitionV1 }\n\n/** Caller material is invalid or conflicts with immutable governed-action identity. */\nexport class GovernedActionInputError extends Schema.TaggedErrorClass<GovernedActionInputError>()(\n \"GovernedActionInputError\",\n {\n operation: Schema.Literals([\"commit\", \"read\"]),\n reason: Schema.Literals([\n \"changed-command-retry\",\n \"conflicting-action-identity\",\n \"illegal-transition\",\n \"invalid-request\",\n \"stale-head\"\n ])\n }\n) {}\n","import * as Effect from \"effect/Effect\"\nimport * as Predicate from \"effect/Predicate\"\n\nimport type { PersistedRecordError } from \"../../errors.js\"\nimport type { QuarantineDiagnosticSummary, QuarantineReasonCode, QuarantineRecordKind } from \"../models.js\"\n\ntype GovernedActionRecordKind = Extract<\n QuarantineRecordKind,\n | \"governed-action\"\n | \"governed-action-policy-evaluation\"\n | \"governed-action-authorization\"\n | \"governed-action-attempt\"\n | \"governed-action-transition\"\n | \"governed-action-audit\"\n>\n\ninterface GovernedActionQuarantineDiagnostic {\n readonly diagnosticCode: QuarantineReasonCode\n readonly diagnosticSummary: QuarantineDiagnosticSummary\n readonly recordKind: GovernedActionRecordKind\n}\n\n/** Internal carrier retaining an untrusted row only until quarantine runs after rollback. */\nexport class MalformedGovernedActionRecord {\n readonly _tag = \"MalformedGovernedActionRecord\"\n readonly error: PersistedRecordError\n readonly row: unknown\n\n constructor(error: PersistedRecordError, row: unknown) {\n this.error = error\n this.row = row\n }\n}\n\n/** Attach an ephemeral raw row to a bounded persisted-record failure. */\nexport const captureMalformedGovernedActionRow =\n (row: unknown) => <Success, Failure, Requirements>(effect: Effect.Effect<Success, Failure, Requirements>) =>\n Effect.catchIf(\n effect,\n (failure): failure is Failure & PersistedRecordError => Predicate.isTagged(\"PersistedRecordError\")(failure),\n (error) => Effect.fail(new MalformedGovernedActionRecord(error, row))\n )\n\n/** Fixed, non-secret quarantine metadata for governed-action corruption. */\nexport const governedActionQuarantineDiagnostic = (\n error: PersistedRecordError\n): GovernedActionQuarantineDiagnostic | null => {\n const diagnostic = (\n recordKind: GovernedActionRecordKind,\n diagnosticCode: QuarantineReasonCode,\n diagnosticSummary: QuarantineDiagnosticSummary\n ): GovernedActionQuarantineDiagnostic => ({ recordKind, diagnosticCode, diagnosticSummary })\n\n switch (error.diagnosticCode) {\n case \"governed-action-schema-invalid\":\n return diagnostic(\n \"governed-action\",\n error.diagnosticCode,\n \"Stored governed action failed schema validation.\"\n )\n case \"governed-action-digest-mismatch\":\n return diagnostic(\n \"governed-action\",\n error.diagnosticCode,\n \"Stored governed action digest does not match its content.\"\n )\n case \"governed-action-identity-mismatch\":\n return diagnostic(\n \"governed-action\",\n error.diagnosticCode,\n \"Stored governed action identity does not match its repository key.\"\n )\n case \"governed-action-chain-invalid\":\n return diagnostic(\n \"governed-action-transition\",\n error.diagnosticCode,\n \"Stored governed action transition chain is invalid.\"\n )\n case \"governed-action-head-mismatch\":\n return diagnostic(\n \"governed-action\",\n error.diagnosticCode,\n \"Stored governed action head does not match its transition history.\"\n )\n case \"governed-action-companion-invalid\":\n return diagnostic(\n error.recordKind === \"governed-action-policy-evaluation\" ||\n error.recordKind === \"governed-action-authorization\" ||\n error.recordKind === \"governed-action-attempt\"\n ? error.recordKind\n : \"governed-action\",\n error.diagnosticCode,\n \"Stored governed action authority companion is invalid.\"\n )\n case \"governed-action-transition-schema-invalid\":\n return diagnostic(\n \"governed-action-transition\",\n error.diagnosticCode,\n \"Stored governed action transition failed schema validation.\"\n )\n case \"governed-action-transition-digest-mismatch\":\n return diagnostic(\n \"governed-action-transition\",\n error.diagnosticCode,\n \"Stored governed action transition digest does not match its content.\"\n )\n case \"governed-action-audit-mismatch\":\n return diagnostic(\n \"governed-action-audit\",\n error.diagnosticCode,\n \"Stored governed action audit record does not match its transition.\"\n )\n default:\n return null\n }\n}\n","import * as Crypto from \"effect/Crypto\"\nimport * as Effect from \"effect/Effect\"\nimport * as Encoding from \"effect/Encoding\"\nimport * as Schema from \"effect/Schema\"\n\nimport {\n GovernedActionAttemptDigest,\n GovernedActionAttemptV1,\n type GovernedActionAttemptV1 as GovernedActionAttempt,\n GovernedActionAuthorizationDigest,\n GovernedActionAuthorizationV1,\n type GovernedActionAuthorizationV1 as GovernedActionAuthorization,\n GovernedActionEnvelopeDigest,\n GovernedActionEnvelopeMaterialV1,\n type GovernedActionEnvelopeMaterialV1 as GovernedActionEnvelopeMaterial,\n type GovernedActionEnvelopeV1 as GovernedActionEnvelope,\n type GovernedActionEvidenceReference as GovernedActionEvidence,\n GovernedActionEvidenceSet,\n GovernedActionEvidenceSetDigest,\n GovernedActionPolicyDigest,\n GovernedActionPolicyEvaluationDigest,\n GovernedActionPolicyEvaluationV1,\n type GovernedActionPolicyEvaluationV1 as GovernedActionPolicyEvaluation\n} from \"../../domain/governedAction/model.js\"\nimport {\n GovernedActionCommandDigest,\n GovernedActionTransitionCommand,\n type GovernedActionTransitionCommand as GovernedActionCommand,\n GovernedActionTransitionDigest,\n type GovernedActionTransitionMaterialV1 as GovernedActionTransitionMaterial,\n GovernedActionTransitionV1,\n type GovernedActionTransitionV1 as GovernedActionTransition,\n GovernedActionUnknownOutcome,\n type GovernedActionUnknownOutcome as GovernedActionUnknown\n} from \"../../domain/governedAction/stateMachine.js\"\nimport {\n PluginActionDispatchResultV1,\n type PluginActionDispatchResultV1 as PluginActionDispatchResult,\n PluginActionPayloadDigest\n} from \"../../domain/plugins/actions.js\"\nimport type { PluginPayloadJson } from \"../../domain/plugins/bounds.js\"\n\n/** Bounded failure while encoding or hashing governed-action authority. */\nexport class GovernedActionDigestError extends Schema.TaggedErrorClass<GovernedActionDigestError>()(\n \"GovernedActionDigestError\",\n {\n operation: Schema.Literals([\"encode\", \"encode-utf8\", \"digest\"])\n }\n) {}\n\n/** Exact immutable action binding that failed canonical verification. */\nexport class GovernedActionBindingMismatch extends Schema.TaggedErrorClass<GovernedActionBindingMismatch>()(\n \"GovernedActionBindingMismatch\",\n {\n reason: Schema.Literals([\n \"payload-digest-mismatch\",\n \"evidence-set-digest-mismatch\",\n \"envelope-digest-mismatch\",\n \"command-digest-mismatch\",\n \"policy-evaluation-digest-mismatch\",\n \"authorization-digest-mismatch\",\n \"attempt-digest-mismatch\",\n \"transition-digest-mismatch\"\n ]),\n expectedDigest: Schema.String.check(Schema.isNonEmpty(), Schema.isMaxLength(80)),\n actualDigest: Schema.String.check(Schema.isNonEmpty(), Schema.isMaxLength(80))\n }\n) {}\n\nclass VerifiedEnvelope {\n readonly #envelope: GovernedActionEnvelope\n\n constructor(envelope: GovernedActionEnvelope) {\n this.#envelope = envelope\n }\n\n /** Structurally decoded envelope whose canonical bindings were recomputed successfully. */\n get envelope(): GovernedActionEnvelope {\n return this.#envelope\n }\n}\n\n/** Nominal server-only proof that an action envelope passed canonical verification. */\nexport type VerifiedGovernedActionEnvelope = VerifiedEnvelope\n\nclass VerifiedTransition {\n readonly #transition: GovernedActionTransition\n\n constructor(transition: GovernedActionTransition) {\n this.#transition = transition\n }\n\n /** Structurally valid transition whose canonical command binding was recomputed successfully. */\n get transition(): GovernedActionTransition {\n return this.#transition\n }\n}\n\n/** Nominal server-only proof that a transition command digest was verified. */\nexport type VerifiedGovernedActionTransition = VerifiedTransition\n\nclass VerifiedPolicyEvaluation {\n readonly #evaluation: GovernedActionPolicyEvaluation\n readonly #digest: GovernedActionPolicyEvaluationDigest\n\n constructor(\n evaluation: GovernedActionPolicyEvaluation,\n digest: GovernedActionPolicyEvaluationDigest\n ) {\n this.#evaluation = evaluation\n this.#digest = digest\n }\n\n /** Structurally valid policy evaluation whose complete canonical digest was verified. */\n get evaluation(): GovernedActionPolicyEvaluation {\n return this.#evaluation\n }\n\n /** Recomputed canonical digest that matched the persisted policy-evaluation digest. */\n get digest(): GovernedActionPolicyEvaluationDigest {\n return this.#digest\n }\n}\n\n/** Nominal server-only proof that a complete policy-evaluation digest was verified. */\nexport type VerifiedGovernedActionPolicyEvaluation = VerifiedPolicyEvaluation\n\nclass VerifiedAuthorization {\n readonly #authorization: GovernedActionAuthorization\n readonly #digest: GovernedActionAuthorizationDigest\n\n constructor(authorization: GovernedActionAuthorization, digest: GovernedActionAuthorizationDigest) {\n this.#authorization = authorization\n this.#digest = digest\n }\n\n /** Structurally valid authorization whose complete canonical digest was verified. */\n get authorization(): GovernedActionAuthorization {\n return this.#authorization\n }\n\n /** Recomputed canonical digest that matched the persisted authorization digest. */\n get digest(): GovernedActionAuthorizationDigest {\n return this.#digest\n }\n}\n\n/** Nominal server-only proof that a complete authorization digest was verified. */\nexport type VerifiedGovernedActionAuthorization = VerifiedAuthorization\n\nclass VerifiedAttempt {\n readonly #attempt: GovernedActionAttempt\n readonly #digest: GovernedActionAttemptDigest\n\n constructor(attempt: GovernedActionAttempt, digest: GovernedActionAttemptDigest) {\n this.#attempt = attempt\n this.#digest = digest\n }\n\n /** Structurally valid dispatch attempt whose complete canonical digest was verified. */\n get attempt(): GovernedActionAttempt {\n return this.#attempt\n }\n\n /** Recomputed canonical digest that matched the persisted attempt digest. */\n get digest(): GovernedActionAttemptDigest {\n return this.#digest\n }\n}\n\n/** Nominal server-only proof that a complete dispatch-attempt digest was verified. */\nexport type VerifiedGovernedActionAttempt = VerifiedAttempt\n\nclass VerifiedTransitionRecord {\n readonly #transition: GovernedActionTransition\n readonly #digest: GovernedActionTransitionDigest\n\n constructor(transition: GovernedActionTransition, digest: GovernedActionTransitionDigest) {\n this.#transition = transition\n this.#digest = digest\n }\n\n /** Structurally valid transition whose command and complete canonical digest were verified. */\n get transition(): GovernedActionTransition {\n return this.#transition\n }\n\n /** Recomputed canonical digest that matched the persisted transition digest. */\n get digest(): GovernedActionTransitionDigest {\n return this.#digest\n }\n}\n\n/** Nominal server-only proof that a complete transition record and its command were verified. */\nexport type VerifiedGovernedActionTransitionRecord = VerifiedTransitionRecord\n\nconst compareText = (left: string, right: string): number => (left < right ? -1 : left > right ? 1 : 0)\n\n/** Canonical JSON text with recursively sorted object keys and order-preserving arrays. */\nexport const canonicalizeGovernedActionJson = (value: Schema.Json): string => {\n if (value === null) return \"null\"\n if (Array.isArray(value)) return `[${value.map(canonicalizeGovernedActionJson).join(\",\")}]`\n\n switch (typeof value) {\n case \"boolean\":\n return value ? \"true\" : \"false\"\n case \"number\":\n return JSON.stringify(value) ?? \"null\"\n case \"string\":\n return JSON.stringify(value)\n case \"object\":\n return `{${\n Object.entries(value)\n .sort(([leftKey], [rightKey]) => compareText(leftKey, rightKey))\n .map(([key, nestedValue]) => `${JSON.stringify(key)}:${canonicalizeGovernedActionJson(nestedValue)}`)\n .join(\",\")\n }}`\n }\n}\n\n/** Hash canonical JSON with the governed-action SHA-256 representation. */\nexport const digestCanonicalGovernedActionJson = Effect.fn(\n \"GovernedActionDigests.digestCanonicalJson\"\n)(function*(value: Schema.Json) {\n const cryptoService = yield* Crypto.Crypto\n const canonicalJson = canonicalizeGovernedActionJson(value)\n const bytes = yield* Effect.fromResult(Encoding.decodeBase64(Encoding.encodeBase64(canonicalJson))).pipe(\n Effect.mapError(() => new GovernedActionDigestError({ operation: \"encode-utf8\" }))\n )\n const digest = yield* cryptoService\n .digest(\"SHA-256\", bytes)\n .pipe(Effect.mapError(() => new GovernedActionDigestError({ operation: \"digest\" })))\n return Encoding.encodeHex(digest)\n})\n\nconst encodeCommand = Schema.encodeEffect(GovernedActionTransitionCommand)\nconst encodeDispatchResult = Schema.encodeEffect(PluginActionDispatchResultV1)\nconst encodeUnknownOutcome = Schema.encodeEffect(GovernedActionUnknownOutcome)\nconst encodeEvidence = Schema.encodeEffect(GovernedActionEvidenceSet)\nconst encodeEnvelope = Schema.encodeEffect(GovernedActionEnvelopeMaterialV1)\nconst encodePolicyEvaluation = Schema.encodeEffect(GovernedActionPolicyEvaluationV1)\nconst encodeAuthorization = Schema.encodeEffect(GovernedActionAuthorizationV1)\nconst encodeAttempt = Schema.encodeEffect(GovernedActionAttemptV1)\nconst encodeTransition = Schema.encodeEffect(GovernedActionTransitionV1)\n\nconst decodeJson = Effect.fn(\"GovernedActionDigests.decodeJson\")(function*(value: unknown) {\n return yield* Schema.decodeUnknownEffect(Schema.Json)(value).pipe(\n Effect.mapError(() => new GovernedActionDigestError({ operation: \"encode\" }))\n )\n})\n\n/** Canonical immutable representation of one immediate provider outcome. */\nexport interface EncodedGovernedActionDispatchOutcome {\n readonly outcomeDigest: string\n readonly outcomeJson: string\n}\n\n/** Encode and hash the exact versioned provider result retained by the durable execution inbox. */\nexport const encodeGovernedActionDispatchOutcome = Effect.fn(\n \"GovernedActionDigests.dispatchOutcome\"\n)(function*(result: PluginActionDispatchResult): Effect.fn.Return<\n EncodedGovernedActionDispatchOutcome,\n GovernedActionDigestError,\n Crypto.Crypto\n> {\n const encoded = yield* encodeDispatchResult(result).pipe(\n Effect.mapError(() => new GovernedActionDigestError({ operation: \"encode\" }))\n )\n const json = yield* decodeJson(encoded)\n return {\n outcomeDigest: yield* digestCanonicalGovernedActionJson(json),\n outcomeJson: canonicalizeGovernedActionJson(json)\n }\n})\n\n/** Encode and hash one locally observed unknown result retained by the dispatch inbox. */\nexport const encodeGovernedActionUnknownOutcome = Effect.fn(\n \"GovernedActionDigests.unknownOutcome\"\n)(function*(outcome: GovernedActionUnknown): Effect.fn.Return<\n EncodedGovernedActionDispatchOutcome,\n GovernedActionDigestError,\n Crypto.Crypto\n> {\n const encoded = yield* encodeUnknownOutcome(outcome).pipe(\n Effect.mapError(() => new GovernedActionDigestError({ operation: \"encode\" }))\n )\n const json = yield* decodeJson(encoded)\n return {\n outcomeDigest: yield* digestCanonicalGovernedActionJson(json),\n outcomeJson: canonicalizeGovernedActionJson(json)\n }\n})\n\n/** Hash one bounded provider payload independently of object insertion order. */\nexport const digestGovernedActionPayload = Effect.fn(\"GovernedActionDigests.payload\")(function*(\n payload: typeof PluginPayloadJson.Type\n) {\n const digest = yield* digestCanonicalGovernedActionJson(payload)\n return PluginActionPayloadDigest.make(digest)\n})\n\n/** Hash one closed transition command for exact caller-command replay checks. */\nexport const digestGovernedActionTransitionCommand = Effect.fn(\"GovernedActionDigests.command\")(function*(\n command: GovernedActionCommand\n) {\n const encoded = yield* encodeCommand(command).pipe(\n Effect.mapError(() => new GovernedActionDigestError({ operation: \"encode\" }))\n )\n const digest = yield* digestCanonicalGovernedActionJson(yield* decodeJson(encoded))\n return GovernedActionCommandDigest.make(`sha256:${digest}`)\n})\n\n/** Reject a retried command whose canonical content changed under the same identity. */\nexport const verifyGovernedActionTransitionCommandDigest = Effect.fn(\n \"GovernedActionDigests.verifyCommand\"\n)(function*(command: GovernedActionCommand, expectedDigest: GovernedActionCommandDigest) {\n const actualDigest = yield* digestGovernedActionTransitionCommand(command)\n if (actualDigest !== expectedDigest) {\n return yield* new GovernedActionBindingMismatch({\n reason: \"command-digest-mismatch\",\n expectedDigest,\n actualDigest\n })\n }\n return command\n})\n\n/** Construct an append-only transition with a digest of its exact canonical command. */\nexport const makeGovernedActionTransition = Effect.fn(\n \"GovernedActionDigests.makeTransition\"\n)(function*(material: GovernedActionTransitionMaterial) {\n return new VerifiedTransition({\n ...material,\n commandDigest: yield* digestGovernedActionTransitionCommand(material.command)\n })\n})\n\n/** Reject a decoded transition when its persisted command digest is stale or forged. */\nexport const verifyGovernedActionTransition = Effect.fn(\n \"GovernedActionDigests.verifyTransition\"\n)(function*(transition: GovernedActionTransition) {\n yield* verifyGovernedActionTransitionCommandDigest(transition.command, transition.commandDigest)\n return new VerifiedTransition(transition)\n})\n\n/** Hash the exact canonical evidence set bound to policy and authorization. */\nexport const digestGovernedActionEvidenceSet = Effect.fn(\"GovernedActionDigests.evidenceSet\")(function*(\n evidence: ReadonlyArray<GovernedActionEvidence>\n) {\n const encoded = yield* encodeEvidence(evidence).pipe(\n Effect.mapError(() => new GovernedActionDigestError({ operation: \"encode\" }))\n )\n const digest = yield* digestCanonicalGovernedActionJson(yield* decodeJson(encoded))\n return GovernedActionEvidenceSetDigest.make(`sha256:${digest}`)\n})\n\n/** Hash one canonical declarative policy definition independently of object insertion order. */\nexport const digestGovernedActionPolicyDefinition = Effect.fn(\n \"GovernedActionDigests.policyDefinition\"\n)(function*(definition: Schema.Json) {\n const digest = yield* digestCanonicalGovernedActionJson(definition)\n return GovernedActionPolicyDigest.make(`sha256:${digest}`)\n})\n\n/** Hash a fresh policy decision so the exact evaluation can be retained with dispatch intent. */\nexport const digestGovernedActionPolicyEvaluation = Effect.fn(\n \"GovernedActionDigests.policyEvaluation\"\n)(function*(evaluation: GovernedActionPolicyEvaluation) {\n const encoded = yield* encodePolicyEvaluation(evaluation).pipe(\n Effect.mapError(() => new GovernedActionDigestError({ operation: \"encode\" }))\n )\n const digest = yield* digestCanonicalGovernedActionJson(yield* decodeJson(encoded))\n return GovernedActionPolicyEvaluationDigest.make(`sha256:${digest}`)\n})\n\n/** Hash the complete immutable human authorization retained by the ledger. */\nexport const digestGovernedActionAuthorization = Effect.fn(\n \"GovernedActionDigests.authorization\"\n)(function*(authorization: GovernedActionAuthorization) {\n const encoded = yield* encodeAuthorization(authorization).pipe(\n Effect.mapError(() => new GovernedActionDigestError({ operation: \"encode\" }))\n )\n const digest = yield* digestCanonicalGovernedActionJson(yield* decodeJson(encoded))\n return GovernedActionAuthorizationDigest.make(`sha256:${digest}`)\n})\n\n/** Hash the complete immutable durable dispatch intent retained by the ledger. */\nexport const digestGovernedActionAttempt = Effect.fn(\n \"GovernedActionDigests.attempt\"\n)(function*(attempt: GovernedActionAttempt) {\n const encoded = yield* encodeAttempt(attempt).pipe(\n Effect.mapError(() => new GovernedActionDigestError({ operation: \"encode\" }))\n )\n const digest = yield* digestCanonicalGovernedActionJson(yield* decodeJson(encoded))\n return GovernedActionAttemptDigest.make(`sha256:${digest}`)\n})\n\n/** Hash a complete immutable transition for audit-event binding. */\nexport const digestGovernedActionTransition = Effect.fn(\n \"GovernedActionDigests.transition\"\n)(function*(transition: GovernedActionTransition) {\n const encoded = yield* encodeTransition(transition).pipe(\n Effect.mapError(() => new GovernedActionDigestError({ operation: \"encode\" }))\n )\n const digest = yield* digestCanonicalGovernedActionJson(yield* decodeJson(encoded))\n return GovernedActionTransitionDigest.make(`sha256:${digest}`)\n})\n\n/** Verify the persisted digest of a complete immutable policy evaluation. */\nexport const verifyGovernedActionPolicyEvaluation = Effect.fn(\n \"GovernedActionDigests.verifyPolicyEvaluation\"\n)(function*(\n evaluation: GovernedActionPolicyEvaluation,\n expectedDigest: GovernedActionPolicyEvaluationDigest\n) {\n const actualDigest = yield* digestGovernedActionPolicyEvaluation(evaluation)\n if (actualDigest !== expectedDigest) {\n return yield* new GovernedActionBindingMismatch({\n reason: \"policy-evaluation-digest-mismatch\",\n expectedDigest,\n actualDigest\n })\n }\n return new VerifiedPolicyEvaluation(evaluation, actualDigest)\n})\n\n/** Verify the persisted digest of a complete immutable human authorization. */\nexport const verifyGovernedActionAuthorization = Effect.fn(\n \"GovernedActionDigests.verifyAuthorization\"\n)(function*(authorization: GovernedActionAuthorization, expectedDigest: GovernedActionAuthorizationDigest) {\n const actualDigest = yield* digestGovernedActionAuthorization(authorization)\n if (actualDigest !== expectedDigest) {\n return yield* new GovernedActionBindingMismatch({\n reason: \"authorization-digest-mismatch\",\n expectedDigest,\n actualDigest\n })\n }\n return new VerifiedAuthorization(authorization, actualDigest)\n})\n\n/** Verify the persisted digest of a complete immutable dispatch attempt. */\nexport const verifyGovernedActionAttempt = Effect.fn(\n \"GovernedActionDigests.verifyAttempt\"\n)(function*(attempt: GovernedActionAttempt, expectedDigest: GovernedActionAttemptDigest) {\n const actualDigest = yield* digestGovernedActionAttempt(attempt)\n if (actualDigest !== expectedDigest) {\n return yield* new GovernedActionBindingMismatch({\n reason: \"attempt-digest-mismatch\",\n expectedDigest,\n actualDigest\n })\n }\n return new VerifiedAttempt(attempt, actualDigest)\n})\n\n/** Verify both the embedded command digest and persisted digest of a complete transition. */\nexport const verifyGovernedActionTransitionDigest = Effect.fn(\n \"GovernedActionDigests.verifyTransitionDigest\"\n)(function*(transition: GovernedActionTransition, expectedDigest: GovernedActionTransitionDigest) {\n yield* verifyGovernedActionTransitionCommandDigest(transition.command, transition.commandDigest)\n const actualDigest = yield* digestGovernedActionTransition(transition)\n if (actualDigest !== expectedDigest) {\n return yield* new GovernedActionBindingMismatch({\n reason: \"transition-digest-mismatch\",\n expectedDigest,\n actualDigest\n })\n }\n return new VerifiedTransitionRecord(transition, actualDigest)\n})\n\n/** Hash every digest-free field in a complete immutable V1 action envelope. */\nexport const digestGovernedActionEnvelope = Effect.fn(\"GovernedActionDigests.envelope\")(function*(\n material: GovernedActionEnvelopeMaterial\n) {\n const encoded = yield* encodeEnvelope(material).pipe(\n Effect.mapError(() => new GovernedActionDigestError({ operation: \"encode\" }))\n )\n const digest = yield* digestCanonicalGovernedActionJson(yield* decodeJson(encoded))\n return GovernedActionEnvelopeDigest.make(`sha256:${digest}`)\n})\n\nconst verifyMaterialBindings = Effect.fn(\"GovernedActionDigests.verifyMaterialBindings\")(function*(\n material: GovernedActionEnvelopeMaterial\n) {\n const actualPayloadDigest = yield* digestGovernedActionPayload(material.proposal.request.payload)\n if (actualPayloadDigest !== material.proposal.payloadDigest) {\n return yield* new GovernedActionBindingMismatch({\n reason: \"payload-digest-mismatch\",\n expectedDigest: material.proposal.payloadDigest,\n actualDigest: actualPayloadDigest\n })\n }\n\n const actualEvidenceSetDigest = yield* digestGovernedActionEvidenceSet(material.evidence)\n if (actualEvidenceSetDigest !== material.evidenceSetDigest) {\n return yield* new GovernedActionBindingMismatch({\n reason: \"evidence-set-digest-mismatch\",\n expectedDigest: material.evidenceSetDigest,\n actualDigest: actualEvidenceSetDigest\n })\n }\n})\n\n/** Construct an envelope only after its payload and evidence bindings verify exactly. */\nexport const makeGovernedActionEnvelope = Effect.fn(\"GovernedActionDigests.makeEnvelope\")(function*(\n material: GovernedActionEnvelopeMaterial\n) {\n yield* verifyMaterialBindings(material)\n return new VerifiedEnvelope({\n ...material,\n envelopeDigest: yield* digestGovernedActionEnvelope(material)\n })\n})\n\n/** Recompute every canonical binding before trusting a decoded persisted envelope. */\nexport const verifyGovernedActionEnvelope = Effect.fn(\"GovernedActionDigests.verifyEnvelope\")(function*(\n envelope: GovernedActionEnvelope\n) {\n const { envelopeDigest, ...material } = envelope\n yield* verifyMaterialBindings(material)\n const actualEnvelopeDigest = yield* digestGovernedActionEnvelope(material)\n if (actualEnvelopeDigest !== envelopeDigest) {\n return yield* new GovernedActionBindingMismatch({\n reason: \"envelope-digest-mismatch\",\n expectedDigest: envelopeDigest,\n actualDigest: actualEnvelopeDigest\n })\n }\n return new VerifiedEnvelope(envelope)\n})\n","import * as Schema from \"effect/Schema\"\n\nimport { PluginActionReconciliationKey } from \"../../domain/plugins/actions.js\"\n\n/**\n * SQL-only encoding for reconciliation by the action's immutable idempotency identity.\n * Leading whitespace makes this value impossible to decode as a provider reconciliation key.\n */\nexport const PERSISTED_IDEMPOTENCY_RECONCILIATION_LOCATOR = \" @knpkv/idempotency-reconciliation/v1\"\n\n/** Provider locator or the private idempotency encoding stored in command projection columns. */\nexport const PersistedGovernedActionReconciliationLocator = Schema.Union([\n PluginActionReconciliationKey,\n Schema.Literal(PERSISTED_IDEMPOTENCY_RECONCILIATION_LOCATOR)\n])\n\n/** Decoded SQL-only reconciliation locator. */\nexport type PersistedGovernedActionReconciliationLocator = typeof PersistedGovernedActionReconciliationLocator.Type\n\n/** Encode the domain's explicit null convention without weakening legacy SQL checks. */\nexport const encodePersistedGovernedActionReconciliationLocator = (\n reconciliationKey: typeof PluginActionReconciliationKey.Type | null\n): PersistedGovernedActionReconciliationLocator => reconciliationKey ?? PERSISTED_IDEMPOTENCY_RECONCILIATION_LOCATOR\n","import * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport * as Schema from \"effect/Schema\"\n\nimport {\n GovernedActionLifecycleHeadV1,\n GovernedActionProviderLineage,\n type GovernedActionProviderLineage as GovernedActionLineage\n} from \"../../../../domain/governedAction/lifecycle.js\"\nimport {\n GovernedActionAttemptV1,\n type GovernedActionAttemptV1 as GovernedActionAttempt,\n GovernedActionAuthorizationV1,\n type GovernedActionAuthorizationV1 as GovernedActionAuthorization,\n GovernedActionEnvelopeV1,\n type GovernedActionEnvelopeV1 as GovernedActionEnvelope,\n GovernedActionPolicyEvaluationV1,\n type GovernedActionPolicyEvaluationV1 as GovernedActionPolicyEvaluation\n} from \"../../../../domain/governedAction/model.js\"\nimport {\n GovernedActionTransitionCause,\n GovernedActionTransitionCommand,\n GovernedActionTransitionV1,\n type GovernedActionTransitionV1 as GovernedActionTransition\n} from \"../../../../domain/governedAction/stateMachine.js\"\nimport type {\n AgentId,\n GovernedActionAttemptId,\n GovernedActionAuthorizationId,\n GovernedActionTransitionId,\n JobId,\n PersonId,\n SessionId\n} from \"../../../../domain/identifiers.js\"\nimport type { PluginActionReconciliationKey, PluginProviderOperationId } from \"../../../../domain/plugins/actions.js\"\nimport { UtcTimestamp } from \"../../../../domain/utcTimestamp.js\"\nimport {\n digestGovernedActionAttempt,\n digestGovernedActionAuthorization,\n digestGovernedActionPolicyEvaluation,\n digestGovernedActionTransition,\n verifyGovernedActionEnvelope,\n verifyGovernedActionTransition\n} from \"../../../governance/governedActionDigests.js\"\nimport { PersistedRecordError, PersistenceOperationError } from \"../../errors.js\"\nimport {\n encodePersistedGovernedActionReconciliationLocator,\n type PersistedGovernedActionReconciliationLocator\n} from \"../../governedActionReconciliationLocator.js\"\nimport type { QuarantineReasonCode, QuarantineRecordKind } from \"../models.js\"\nimport type {\n GovernedActionAttemptRow,\n GovernedActionAuditEventRow,\n GovernedActionAuthorizationRow,\n GovernedActionPolicyEvaluationRow,\n GovernedActionRow,\n GovernedActionTransitionRow\n} from \"./rows.js\"\n\nconst envelopeJson = Schema.fromJsonString(GovernedActionEnvelopeV1)\nconst policyEvaluationJson = Schema.fromJsonString(GovernedActionPolicyEvaluationV1)\nconst authorizationJson = Schema.fromJsonString(GovernedActionAuthorizationV1)\nconst attemptJson = Schema.fromJsonString(GovernedActionAttemptV1)\nconst transitionJson = Schema.fromJsonString(GovernedActionTransitionV1)\nconst lineageJson = Schema.fromJsonString(GovernedActionProviderLineage)\nconst commandJson = Schema.fromJsonString(GovernedActionTransitionCommand)\nconst causeJson = Schema.fromJsonString(GovernedActionTransitionCause)\n\n/** Canonical JSON codecs shared by governed-action reads and writes. */\nexport {\n attemptJson as GovernedActionAttemptJson,\n authorizationJson as GovernedActionAuthorizationJson,\n causeJson as GovernedActionCauseJson,\n commandJson as GovernedActionCommandJson,\n envelopeJson as GovernedActionEnvelopeJson,\n lineageJson as GovernedActionLineageJson,\n policyEvaluationJson as GovernedActionPolicyEvaluationJson,\n transitionJson as GovernedActionTransitionJson\n}\n\nconst encodeEnvelopeJson = Schema.encodeEffect(envelopeJson)\nconst encodePolicyEvaluationJson = Schema.encodeEffect(policyEvaluationJson)\nconst encodeAuthorizationJson = Schema.encodeEffect(authorizationJson)\nconst encodeAttemptJson = Schema.encodeEffect(attemptJson)\nconst encodeTransitionJson = Schema.encodeEffect(transitionJson)\nconst encodeLineageJson = Schema.encodeEffect(lineageJson)\nconst decodeEnvelopeJson = Schema.decodeUnknownEffect(envelopeJson)\nconst decodePolicyEvaluationJson = Schema.decodeUnknownEffect(policyEvaluationJson)\nconst decodeAuthorizationJson = Schema.decodeUnknownEffect(authorizationJson)\nconst decodeAttemptJson = Schema.decodeUnknownEffect(attemptJson)\nconst decodeTransitionJson = Schema.decodeUnknownEffect(transitionJson)\nconst decodeLineageJson = Schema.decodeUnknownEffect(lineageJson)\nconst decodeTimestamp = Schema.decodeUnknownEffect(UtcTimestamp)\nconst encodeTimestamp = Schema.encodeSync(UtcTimestamp)\n\n/** Closed quarantine kinds emitted by the governed-action integrity codec. */\nexport type GovernedActionQuarantineRecordKind = Extract<\n QuarantineRecordKind,\n | \"governed-action\"\n | \"governed-action-policy-evaluation\"\n | \"governed-action-authorization\"\n | \"governed-action-attempt\"\n | \"governed-action-transition\"\n | \"governed-action-audit\"\n>\n\n/** Closed diagnostics emitted by the governed-action integrity codec. */\nexport type GovernedActionQuarantineReasonCode = Extract<\n QuarantineReasonCode,\n | \"governed-action-schema-invalid\"\n | \"governed-action-digest-mismatch\"\n | \"governed-action-identity-mismatch\"\n | \"governed-action-chain-invalid\"\n | \"governed-action-head-mismatch\"\n | \"governed-action-companion-invalid\"\n | \"governed-action-transition-schema-invalid\"\n | \"governed-action-transition-digest-mismatch\"\n | \"governed-action-audit-mismatch\"\n>\n\ninterface GovernedActionRecordErrorOptions {\n readonly workspaceId: typeof GovernedActionRow.Type[\"workspaceId\"]\n readonly recordKind: GovernedActionQuarantineRecordKind\n readonly recordKey: string\n readonly diagnosticCode: GovernedActionQuarantineReasonCode\n}\n\n/** Construct a bounded corruption diagnostic without retaining raw governed-action material. */\nexport const governedActionRecordError = (\n options: GovernedActionRecordErrorOptions\n): PersistedRecordError => new PersistedRecordError(options)\n\nconst encodeFailure = (operation: string): PersistenceOperationError => new PersistenceOperationError({ operation })\n\n/** Denormalized provider-lineage columns shared by action heads and transitions. */\nexport interface GovernedActionLineageProjection {\n readonly lineageKind: GovernedActionLineage[\"_tag\"]\n readonly providerOperationId: PluginProviderOperationId | null\n readonly reconciliationKey: PluginActionReconciliationKey | null\n readonly terminalStatus: \"succeeded\" | \"failed\" | \"cancelled\" | null\n}\n\n/** Denormalized replay and provider-identity columns for one transition command. */\nexport interface GovernedActionCommandProjection {\n readonly commandTag: GovernedActionTransitionCommand[\"_tag\"]\n readonly authorizationId: GovernedActionAuthorizationId | null\n readonly attemptId: GovernedActionAttemptId | null\n readonly outcomeSourceKind: \"direct\" | \"providerOperation\" | \"reconciliation\" | null\n readonly commandProviderOperationId: PluginProviderOperationId | null\n readonly commandReconciliationKey: PersistedGovernedActionReconciliationLocator | null\n readonly commandTerminalStatus: \"succeeded\" | \"failed\" | \"cancelled\" | null\n readonly commandUnknownKind: \"reconcilable\" | \"manual\" | null\n}\n\n/** Denormalized human, agent, or system attribution columns for one transition. */\nexport interface GovernedActionCauseProjection {\n readonly causeKind: GovernedActionTransitionCause[\"_tag\"]\n readonly causeActorId: PersonId | AgentId | null\n readonly causeSessionId: SessionId | null\n readonly causeJobId: JobId | null\n readonly causeSystemComponent: string | null\n}\n\n/** Verified materialized action-head metadata reconstructed from the persisted lineage. */\nexport interface GovernedActionHeadRecord {\n readonly transitionId: GovernedActionTransitionId\n readonly sequence: number\n readonly lifecycle: typeof GovernedActionLifecycleHeadV1.Type\n readonly updatedAt: typeof UtcTimestamp.Type\n}\n\n/** Verified action envelope and its nullable transaction-local materialized head. */\nexport interface DecodedGovernedActionRow {\n readonly envelope: GovernedActionEnvelope\n readonly head: GovernedActionHeadRecord | null\n readonly createdAt: typeof UtcTimestamp.Type\n}\n\n/** Verified transition and the independently persisted lifecycle projection it produced. */\nexport interface DecodedGovernedActionTransitionRow {\n readonly transition: GovernedActionTransition\n readonly transitionDigest: typeof GovernedActionTransitionRow.Type[\"transitionDigest\"]\n readonly resultHead: typeof GovernedActionLifecycleHeadV1.Type\n}\n\n/** Project provider lineage into the independently constrained SQL columns. */\nexport const projectGovernedActionLineage = (\n lineage: GovernedActionLineage\n): GovernedActionLineageProjection => {\n switch (lineage._tag) {\n case \"none\":\n return {\n lineageKind: \"none\",\n providerOperationId: null,\n reconciliationKey: null,\n terminalStatus: null\n }\n case \"accepted\":\n return {\n lineageKind: \"accepted\",\n providerOperationId: lineage.receipt.providerOperationId,\n reconciliationKey: lineage.receipt.reconciliationKey,\n terminalStatus: null\n }\n case \"reconcilable\":\n return {\n lineageKind: \"reconcilable\",\n providerOperationId: lineage.providerOperationId,\n reconciliationKey: lineage.reconciliationKey,\n terminalStatus: null\n }\n case \"manual\":\n return {\n lineageKind: \"manual\",\n providerOperationId: lineage.providerOperationId,\n reconciliationKey: null,\n terminalStatus: null\n }\n case \"terminal\":\n return {\n lineageKind: \"terminal\",\n providerOperationId: lineage.receipt.providerOperationId,\n reconciliationKey: null,\n terminalStatus: lineage.receipt.status\n }\n }\n}\n\nconst emptyCommandProjection = (\n commandTag: GovernedActionTransitionCommand[\"_tag\"]\n): GovernedActionCommandProjection => ({\n commandTag,\n authorizationId: null,\n attemptId: null,\n outcomeSourceKind: null,\n commandProviderOperationId: null,\n commandReconciliationKey: null,\n commandTerminalStatus: null,\n commandUnknownKind: null\n})\n\n/** Project command-specific identities without retaining descriptions or provider payloads. */\nexport const projectGovernedActionCommand = (\n command: GovernedActionTransitionCommand\n): GovernedActionCommandProjection => {\n switch (command._tag) {\n case \"authorize\":\n return { ...emptyCommandProjection(command._tag), authorizationId: command.authorizationId }\n case \"start\":\n return { ...emptyCommandProjection(command._tag), attemptId: command.attemptId }\n case \"recordAccepted\":\n return {\n ...emptyCommandProjection(command._tag),\n commandProviderOperationId: command.receipt.providerOperationId,\n commandReconciliationKey: command.receipt.reconciliationKey\n }\n case \"recordSucceeded\":\n case \"recordFailed\":\n case \"recordCancelled\":\n return {\n ...emptyCommandProjection(command._tag),\n outcomeSourceKind: command.source._tag,\n commandProviderOperationId: command.receipt.providerOperationId,\n commandReconciliationKey: command.source._tag === \"reconciliation\"\n ? encodePersistedGovernedActionReconciliationLocator(command.source.reconciliationKey)\n : null,\n commandTerminalStatus: command.receipt.status\n }\n case \"recordUnknown\":\n return {\n ...emptyCommandProjection(command._tag),\n commandReconciliationKey: command.outcome._tag === \"reconcilable\"\n ? command.outcome.reconciliationKey\n : null,\n commandUnknownKind: command.outcome._tag\n }\n case \"reconciliationPending\":\n return {\n ...emptyCommandProjection(command._tag),\n commandReconciliationKey: encodePersistedGovernedActionReconciliationLocator(\n command.reconciliationKey\n )\n }\n case \"propose\":\n case \"deny\":\n case \"expire\":\n case \"cancel\":\n case \"requestCancellation\":\n return emptyCommandProjection(command._tag)\n }\n}\n\n/** Project closed transition attribution into mutually exclusive SQL columns. */\nexport const projectGovernedActionCause = (\n cause: GovernedActionTransitionCause\n): GovernedActionCauseProjection => {\n switch (cause._tag) {\n case \"human\":\n return {\n causeKind: \"human\",\n causeActorId: cause.actor.personId,\n causeSessionId: cause.sessionId,\n causeJobId: null,\n causeSystemComponent: null\n }\n case \"agent\":\n return {\n causeKind: \"agent\",\n causeActorId: cause.actor.agentId,\n causeSessionId: null,\n causeJobId: cause.jobId,\n causeSystemComponent: null\n }\n case \"system\":\n return {\n causeKind: \"system\",\n causeActorId: null,\n causeSessionId: null,\n causeJobId: null,\n causeSystemComponent: cause.component\n }\n }\n}\n\n/** Encode a validated immutable governed-action envelope as bounded JSON text. */\nexport const encodeGovernedActionEnvelopeJson = Effect.fn(\"GovernedActionCodec.encodeEnvelope\")(function*(\n envelope: GovernedActionEnvelope\n) {\n return yield* encodeEnvelopeJson(envelope).pipe(\n Effect.mapError(() => encodeFailure(\"governed-action.encode-envelope\"))\n )\n})\n\n/** Encode a validated fresh policy evaluation as bounded JSON text. */\nexport const encodeGovernedActionPolicyEvaluationJson = Effect.fn(\n \"GovernedActionCodec.encodePolicyEvaluation\"\n)(function*(evaluation: GovernedActionPolicyEvaluation) {\n return yield* encodePolicyEvaluationJson(evaluation).pipe(\n Effect.mapError(() => encodeFailure(\"governed-action.encode-policy-evaluation\"))\n )\n})\n\n/** Encode a validated immutable human authorization as bounded JSON text. */\nexport const encodeGovernedActionAuthorizationJson = Effect.fn(\n \"GovernedActionCodec.encodeAuthorization\"\n)(function*(authorization: GovernedActionAuthorization) {\n return yield* encodeAuthorizationJson(authorization).pipe(\n Effect.mapError(() => encodeFailure(\"governed-action.encode-authorization\"))\n )\n})\n\n/** Encode a validated durable dispatch attempt as bounded JSON text. */\nexport const encodeGovernedActionAttemptJson = Effect.fn(\"GovernedActionCodec.encodeAttempt\")(function*(\n attempt: GovernedActionAttempt\n) {\n return yield* encodeAttemptJson(attempt).pipe(\n Effect.mapError(() => encodeFailure(\"governed-action.encode-attempt\"))\n )\n})\n\n/** Encode a validated immutable lifecycle transition as bounded JSON text. */\nexport const encodeGovernedActionTransitionJson = Effect.fn(\"GovernedActionCodec.encodeTransition\")(function*(\n transition: GovernedActionTransition\n) {\n return yield* encodeTransitionJson(transition).pipe(\n Effect.mapError(() => encodeFailure(\"governed-action.encode-transition\"))\n )\n})\n\n/** Encode a validated provider lineage projection as bounded JSON text. */\nexport const encodeGovernedActionLineageJson = Effect.fn(\"GovernedActionCodec.encodeLineage\")(function*(\n lineage: GovernedActionLineage\n) {\n return yield* encodeLineageJson(lineage).pipe(\n Effect.mapError(() => encodeFailure(\"governed-action.encode-lineage\"))\n )\n})\n\nconst lineageProjectionMatches = (\n projection: GovernedActionLineageProjection,\n row: {\n readonly lineageKind: GovernedActionLineageProjection[\"lineageKind\"]\n readonly providerOperationId: PluginProviderOperationId | null\n readonly reconciliationKey: PluginActionReconciliationKey | null\n readonly terminalStatus: GovernedActionLineageProjection[\"terminalStatus\"]\n }\n): boolean =>\n projection.lineageKind === row.lineageKind &&\n projection.providerOperationId === row.providerOperationId &&\n projection.reconciliationKey === row.reconciliationKey &&\n projection.terminalStatus === row.terminalStatus\n\nconst commandProjectionMatches = (\n projection: GovernedActionCommandProjection,\n row: typeof GovernedActionTransitionRow.Type\n): boolean =>\n projection.commandTag === row.commandTag &&\n projection.authorizationId === row.authorizationId &&\n projection.attemptId === row.attemptId &&\n projection.outcomeSourceKind === row.outcomeSourceKind &&\n projection.commandProviderOperationId === row.commandProviderOperationId &&\n projection.commandReconciliationKey === row.commandReconciliationKey &&\n projection.commandTerminalStatus === row.commandTerminalStatus &&\n projection.commandUnknownKind === row.commandUnknownKind\n\nconst causeProjectionMatches = (\n projection: GovernedActionCauseProjection,\n row: {\n readonly causeKind: GovernedActionCauseProjection[\"causeKind\"]\n readonly causeActorId: PersonId | AgentId | null\n readonly causeSessionId: SessionId | null\n readonly causeJobId: JobId | null\n readonly causeSystemComponent: string | null\n }\n): boolean =>\n projection.causeKind === row.causeKind &&\n projection.causeActorId === row.causeActorId &&\n projection.causeSessionId === row.causeSessionId &&\n projection.causeJobId === row.causeJobId &&\n projection.causeSystemComponent === row.causeSystemComponent\n\n/** Decode and verify the immutable envelope and nullable action-head projection. */\nexport const decodeGovernedActionRow = Effect.fn(\"GovernedActionCodec.decodeActionRow\")(function*(\n row: typeof GovernedActionRow.Type\n) {\n const malformed = (diagnosticCode: GovernedActionQuarantineReasonCode) =>\n governedActionRecordError({\n workspaceId: row.workspaceId,\n recordKind: \"governed-action\",\n recordKey: row.actionId,\n diagnosticCode\n })\n const envelope = yield* decodeEnvelopeJson(row.envelopeJson).pipe(\n Effect.mapError(() => malformed(\"governed-action-schema-invalid\"))\n )\n const verifiedEnvelope = yield* verifyGovernedActionEnvelope(envelope).pipe(\n Effect.mapError(() => malformed(\"governed-action-digest-mismatch\"))\n )\n const envelopeProjectionMatches = envelope.workspaceId === row.workspaceId &&\n envelope.actionId === row.actionId &&\n envelope.pluginConnectionId === row.pluginConnectionId &&\n envelope.providerId === row.providerId &&\n envelope.targetEntityId === row.targetEntityId &&\n envelope.idempotencyKey === row.idempotencyKey &&\n envelope.envelopeDigest === row.envelopeDigest\n if (!envelopeProjectionMatches) {\n return yield* malformed(\"governed-action-identity-mismatch\")\n }\n const createdAt = yield* decodeTimestamp(row.createdAt).pipe(\n Effect.mapError(() => malformed(\"governed-action-head-mismatch\"))\n )\n const updatedAt = yield* decodeTimestamp(row.updatedAt).pipe(\n Effect.mapError(() => malformed(\"governed-action-head-mismatch\"))\n )\n if (DateTime.Order(createdAt, updatedAt) > 0) {\n return yield* malformed(\"governed-action-head-mismatch\")\n }\n\n const nullableHead = [\n row.state,\n row.lineageJson,\n row.lineageKind,\n row.headTransitionId,\n row.headSequence\n ]\n const hasEmptyHead = nullableHead.every((value) => value === null) &&\n row.providerOperationId === null &&\n row.reconciliationKey === null &&\n row.terminalStatus === null\n if (hasEmptyHead) {\n return { envelope: verifiedEnvelope.envelope, head: null, createdAt }\n }\n if (\n row.state === null ||\n row.lineageJson === null ||\n row.lineageKind === null ||\n row.headTransitionId === null ||\n row.headSequence === null\n ) {\n return yield* malformed(\"governed-action-head-mismatch\")\n }\n const lineage = yield* decodeLineageJson(row.lineageJson).pipe(\n Effect.mapError(() => malformed(\"governed-action-head-mismatch\"))\n )\n const lifecycle = yield* Schema.decodeUnknownEffect(Schema.toType(GovernedActionLifecycleHeadV1))({\n state: row.state,\n lineage\n }).pipe(\n Effect.mapError(() => malformed(\"governed-action-head-mismatch\"))\n )\n if (\n !lineageProjectionMatches(projectGovernedActionLineage(lineage), {\n lineageKind: row.lineageKind,\n providerOperationId: row.providerOperationId,\n reconciliationKey: row.reconciliationKey,\n terminalStatus: row.terminalStatus\n })\n ) {\n return yield* malformed(\"governed-action-head-mismatch\")\n }\n return {\n envelope: verifiedEnvelope.envelope,\n head: {\n transitionId: row.headTransitionId,\n sequence: row.headSequence,\n lifecycle,\n updatedAt\n },\n createdAt\n }\n})\n\n/** Decode a policy evaluation, then verify its digest and denormalized identity. */\nexport const decodeGovernedActionPolicyEvaluationRow = Effect.fn(\n \"GovernedActionCodec.decodePolicyEvaluationRow\"\n)(function*(row: typeof GovernedActionPolicyEvaluationRow.Type) {\n const malformed = (diagnosticCode: GovernedActionQuarantineReasonCode) =>\n governedActionRecordError({\n workspaceId: row.workspaceId,\n recordKind: \"governed-action-policy-evaluation\",\n recordKey: row.actionId,\n diagnosticCode\n })\n const evaluation = yield* decodePolicyEvaluationJson(row.evaluationJson).pipe(\n Effect.mapError(() => malformed(\"governed-action-companion-invalid\"))\n )\n const actualDigest = yield* digestGovernedActionPolicyEvaluation(evaluation).pipe(\n Effect.mapError(() => malformed(\"governed-action-companion-invalid\"))\n )\n if (actualDigest !== row.evaluationDigest) {\n return yield* malformed(\"governed-action-companion-invalid\")\n }\n if (\n evaluation.workspaceId !== row.workspaceId ||\n evaluation.actionId !== row.actionId ||\n evaluation.decision !== row.decision ||\n encodeTimestamp(evaluation.evaluatedAt) !== row.evaluatedAt\n ) {\n return yield* malformed(\"governed-action-companion-invalid\")\n }\n return evaluation\n})\n\n/** Decode an authorization, then verify its full digest and denormalized authority columns. */\nexport const decodeGovernedActionAuthorizationRow = Effect.fn(\n \"GovernedActionCodec.decodeAuthorizationRow\"\n)(function*(row: typeof GovernedActionAuthorizationRow.Type) {\n const malformed = (diagnosticCode: GovernedActionQuarantineReasonCode) =>\n governedActionRecordError({\n workspaceId: row.workspaceId,\n recordKind: \"governed-action-authorization\",\n recordKey: row.authorizationId,\n diagnosticCode\n })\n const authorization = yield* decodeAuthorizationJson(row.authorizationJson).pipe(\n Effect.mapError(() => malformed(\"governed-action-companion-invalid\"))\n )\n const actualDigest = yield* digestGovernedActionAuthorization(authorization).pipe(\n Effect.mapError(() => malformed(\"governed-action-companion-invalid\"))\n )\n if (actualDigest !== row.authorizationDigest) {\n return yield* malformed(\"governed-action-companion-invalid\")\n }\n if (\n authorization.workspaceId !== row.workspaceId ||\n authorization.actionId !== row.actionId ||\n authorization.authorizationId !== row.authorizationId ||\n authorization.sessionId !== row.sessionId ||\n authorization.actionEnvelopeDigest !== row.envelopeDigest ||\n encodeTimestamp(authorization.authorizedAt) !== row.authorizedAt ||\n encodeTimestamp(authorization.expiresAt) !== row.expiresAt\n ) {\n return yield* malformed(\"governed-action-companion-invalid\")\n }\n return authorization\n})\n\n/** Decode a durable attempt, then verify its full digest and authority linkage columns. */\nexport const decodeGovernedActionAttemptRow = Effect.fn(\n \"GovernedActionCodec.decodeAttemptRow\"\n)(function*(row: typeof GovernedActionAttemptRow.Type) {\n const malformed = (diagnosticCode: GovernedActionQuarantineReasonCode) =>\n governedActionRecordError({\n workspaceId: row.workspaceId,\n recordKind: \"governed-action-attempt\",\n recordKey: row.attemptId,\n diagnosticCode\n })\n const attempt = yield* decodeAttemptJson(row.attemptJson).pipe(\n Effect.mapError(() => malformed(\"governed-action-companion-invalid\"))\n )\n const actualDigest = yield* digestGovernedActionAttempt(attempt).pipe(\n Effect.mapError(() => malformed(\"governed-action-companion-invalid\"))\n )\n if (actualDigest !== row.attemptDigest) {\n return yield* malformed(\"governed-action-companion-invalid\")\n }\n if (\n attempt.workspaceId !== row.workspaceId ||\n attempt.actionId !== row.actionId ||\n attempt.attemptId !== row.attemptId ||\n attempt.authorizationId !== row.authorizationId ||\n attempt.policyEvaluationDigest !== row.policyEvaluationDigest ||\n attempt.attemptNumber !== row.attemptNumber ||\n encodeTimestamp(attempt.startedAt) !== row.startedAt\n ) {\n return yield* malformed(\"governed-action-companion-invalid\")\n }\n return attempt\n})\n\n/** Decode a transition and verify both canonical digests plus every replay projection. */\nexport const decodeGovernedActionTransitionRow = Effect.fn(\n \"GovernedActionCodec.decodeTransitionRow\"\n)(function*(row: typeof GovernedActionTransitionRow.Type) {\n const malformed = (diagnosticCode: GovernedActionQuarantineReasonCode) =>\n governedActionRecordError({\n workspaceId: row.workspaceId,\n recordKind: \"governed-action-transition\",\n recordKey: row.transitionId,\n diagnosticCode\n })\n const transition = yield* decodeTransitionJson(row.transitionJson).pipe(\n Effect.mapError(() => malformed(\"governed-action-transition-schema-invalid\"))\n )\n yield* verifyGovernedActionTransition(transition).pipe(\n Effect.mapError(() => malformed(\"governed-action-transition-digest-mismatch\"))\n )\n const actualDigest = yield* digestGovernedActionTransition(transition).pipe(\n Effect.mapError(() => malformed(\"governed-action-transition-digest-mismatch\"))\n )\n if (actualDigest !== row.transitionDigest) {\n return yield* malformed(\"governed-action-transition-digest-mismatch\")\n }\n const identityMatches = transition.workspaceId === row.workspaceId &&\n transition.actionId === row.actionId &&\n transition.transitionId === row.transitionId &&\n transition.previousTransitionId === row.previousTransitionId &&\n transition.sequence === row.sequence &&\n transition.commandId === row.commandId &&\n transition.commandDigest === row.commandDigest &&\n transition.actionEnvelopeDigest === row.envelopeDigest &&\n (row.policyEvaluationDigest === null || transition.command._tag === \"deny\") &&\n transition.fromState === row.fromState &&\n transition.toState === row.toState &&\n transition.causationId === row.causationId &&\n transition.correlationId === row.correlationId &&\n encodeTimestamp(transition.occurredAt) === row.occurredAt\n if (!identityMatches) {\n return yield* malformed(\"governed-action-chain-invalid\")\n }\n if (!commandProjectionMatches(projectGovernedActionCommand(transition.command), row)) {\n return yield* malformed(\"governed-action-chain-invalid\")\n }\n if (!causeProjectionMatches(projectGovernedActionCause(transition.cause), row)) {\n return yield* malformed(\"governed-action-chain-invalid\")\n }\n const lineage = yield* decodeLineageJson(row.resultLineageJson).pipe(\n Effect.mapError(() => malformed(\"governed-action-chain-invalid\"))\n )\n const resultHead = yield* Schema.decodeUnknownEffect(Schema.toType(GovernedActionLifecycleHeadV1))({\n state: transition.toState,\n lineage\n }).pipe(\n Effect.mapError(() => malformed(\"governed-action-chain-invalid\"))\n )\n if (\n !lineageProjectionMatches(projectGovernedActionLineage(lineage), {\n lineageKind: row.resultLineageKind,\n providerOperationId: row.resultProviderOperationId,\n reconciliationKey: row.resultReconciliationKey,\n terminalStatus: row.resultTerminalStatus\n })\n ) {\n return yield* malformed(\"governed-action-chain-invalid\")\n }\n return { transition, transitionDigest: row.transitionDigest, resultHead }\n})\n\n/** Decode an audit payload and prove that all audit columns attribute its exact transition. */\nexport const decodeGovernedActionAuditEventRow = Effect.fn(\n \"GovernedActionCodec.decodeAuditEventRow\"\n)(function*(row: typeof GovernedActionAuditEventRow.Type) {\n const malformed = (diagnosticCode: GovernedActionQuarantineReasonCode) =>\n governedActionRecordError({\n workspaceId: row.workspaceId,\n recordKind: \"governed-action-audit\",\n recordKey: row.auditEventId,\n diagnosticCode\n })\n const transition = yield* decodeTransitionJson(row.payloadJson).pipe(\n Effect.mapError(() => malformed(\"governed-action-audit-mismatch\"))\n )\n yield* verifyGovernedActionTransition(transition).pipe(\n Effect.mapError(() => malformed(\"governed-action-audit-mismatch\"))\n )\n const actualDigest = yield* digestGovernedActionTransition(transition).pipe(\n Effect.mapError(() => malformed(\"governed-action-audit-mismatch\"))\n )\n if (actualDigest !== row.payloadDigest) {\n return yield* malformed(\"governed-action-audit-mismatch\")\n }\n const cause = projectGovernedActionCause(transition.cause)\n const projectionMatches = transition.workspaceId === row.workspaceId &&\n transition.actionId === row.actionId &&\n transition.transitionId === row.transitionId &&\n transition.toState === row.eventKind &&\n transition.causationId === row.causationId &&\n transition.correlationId === row.correlationId &&\n encodeTimestamp(transition.occurredAt) === row.occurredAt &&\n causeProjectionMatches(cause, {\n causeKind: row.causeKind,\n causeActorId: row.actorId,\n causeSessionId: row.sessionId,\n causeJobId: row.jobId,\n causeSystemComponent: row.systemComponent\n })\n if (!projectionMatches) {\n return yield* malformed(\"governed-action-audit-mismatch\")\n }\n return transition\n})\n","import * as Schema from \"effect/Schema\"\n\nimport { DomainEventCorrelationId } from \"../../../../domain/domainEvent.js\"\nimport {\n GovernedActionAttemptDigest,\n GovernedActionAuthorizationDigest,\n GovernedActionEnvelopeDigest,\n GovernedActionIdempotencyKey,\n GovernedActionPolicyEvaluationDigest\n} from \"../../../../domain/governedAction/model.js\"\nimport {\n GovernedActionCommandDigest,\n GovernedActionCommandId,\n GovernedActionState,\n GovernedActionTransitionDigest\n} from \"../../../../domain/governedAction/stateMachine.js\"\nimport {\n AgentId,\n DomainEventId,\n EntityId,\n GovernedActionAttemptId,\n GovernedActionAuthorizationId,\n GovernedActionId,\n GovernedActionTransitionId,\n JobId,\n PersonId,\n PluginConnectionId,\n SessionId,\n WorkspaceId\n} from \"../../../../domain/identifiers.js\"\nimport { PluginActionReconciliationKey, PluginProviderOperationId } from \"../../../../domain/plugins/actions.js\"\nimport { ProviderId } from \"../../../../domain/sourceRevision.js\"\nimport { PersistedGovernedActionReconciliationLocator } from \"../../governedActionReconciliationLocator.js\"\nimport { GovernedActionAuditEventId } from \"./contract.js\"\n\nconst PositiveInteger = Schema.Int.check(Schema.isGreaterThan(0))\nconst GovernedActionLineageKind = Schema.Literals([\n \"none\",\n \"accepted\",\n \"reconcilable\",\n \"manual\",\n \"terminal\"\n])\nconst GovernedActionTerminalStatus = Schema.Literals([\"succeeded\", \"failed\", \"cancelled\"])\nconst GovernedActionCauseKind = Schema.Literals([\"human\", \"agent\", \"system\"])\nconst GovernedActionCommandTag = Schema.Literals([\n \"propose\",\n \"authorize\",\n \"deny\",\n \"expire\",\n \"cancel\",\n \"start\",\n \"requestCancellation\",\n \"recordAccepted\",\n \"recordSucceeded\",\n \"recordFailed\",\n \"recordUnknown\",\n \"recordCancelled\",\n \"reconciliationPending\"\n])\nconst GovernedActionSystemComponent = Schema.String.check(\n Schema.isTrimmed(),\n Schema.isNonEmpty(),\n Schema.isMaxLength(200),\n Schema.isPattern(/^[A-Za-z0-9._:/-]+$/u, { expected: \"a bounded system component\" })\n)\n\n/** Driver row retained without trust until repository-controlled decoding and verification. */\nexport const RawGovernedActionRow = Schema.Record(Schema.String, Schema.Unknown)\n\n/** Persisted immutable action envelope plus its materialized lifecycle head. */\nexport const GovernedActionRow = Schema.Struct({\n workspaceId: WorkspaceId,\n actionId: GovernedActionId,\n pluginConnectionId: PluginConnectionId,\n providerId: ProviderId,\n targetEntityId: EntityId,\n idempotencyKey: GovernedActionIdempotencyKey,\n envelopeDigest: GovernedActionEnvelopeDigest,\n envelopeJson: Schema.String,\n state: Schema.NullOr(GovernedActionState),\n lineageJson: Schema.NullOr(Schema.String),\n lineageKind: Schema.NullOr(GovernedActionLineageKind),\n providerOperationId: Schema.NullOr(PluginProviderOperationId),\n reconciliationKey: Schema.NullOr(PluginActionReconciliationKey),\n terminalStatus: Schema.NullOr(GovernedActionTerminalStatus),\n headTransitionId: Schema.NullOr(GovernedActionTransitionId),\n headSequence: Schema.NullOr(PositiveInteger),\n createdAt: Schema.String,\n updatedAt: Schema.String\n})\n\n/** Persisted canonical policy decision bound to one governed action. */\nexport const GovernedActionPolicyEvaluationRow = Schema.Struct({\n workspaceId: WorkspaceId,\n actionId: GovernedActionId,\n evaluationDigest: GovernedActionPolicyEvaluationDigest,\n evaluationJson: Schema.String,\n decision: Schema.Literals([\"allowed\", \"denied\"]),\n evaluatedAt: Schema.String\n})\n\n/** Persisted immutable human authorization bound to an exact envelope. */\nexport const GovernedActionAuthorizationRow = Schema.Struct({\n workspaceId: WorkspaceId,\n actionId: GovernedActionId,\n authorizationId: GovernedActionAuthorizationId,\n sessionId: SessionId,\n envelopeDigest: GovernedActionEnvelopeDigest,\n authorizationDigest: GovernedActionAuthorizationDigest,\n authorizationJson: Schema.String,\n authorizedAt: Schema.String,\n expiresAt: Schema.String\n})\n\n/** Persisted durable dispatch intent bound to authorization and fresh policy. */\nexport const GovernedActionAttemptRow = Schema.Struct({\n workspaceId: WorkspaceId,\n actionId: GovernedActionId,\n attemptId: GovernedActionAttemptId,\n authorizationId: GovernedActionAuthorizationId,\n policyEvaluationDigest: GovernedActionPolicyEvaluationDigest,\n attemptDigest: GovernedActionAttemptDigest,\n attemptNumber: Schema.Literal(1),\n attemptJson: Schema.String,\n startedAt: Schema.String\n})\n\n/** Persisted transition with exact command, cause, result-lineage, and replay projections. */\nexport const GovernedActionTransitionRow = Schema.Struct({\n workspaceId: WorkspaceId,\n actionId: GovernedActionId,\n transitionId: GovernedActionTransitionId,\n previousTransitionId: Schema.NullOr(GovernedActionTransitionId),\n sequence: PositiveInteger,\n commandId: GovernedActionCommandId,\n commandTag: GovernedActionCommandTag,\n authorizationId: Schema.NullOr(GovernedActionAuthorizationId),\n attemptId: Schema.NullOr(GovernedActionAttemptId),\n policyEvaluationDigest: Schema.NullOr(GovernedActionPolicyEvaluationDigest),\n outcomeSourceKind: Schema.NullOr(Schema.Literals([\"direct\", \"providerOperation\", \"reconciliation\"])),\n commandProviderOperationId: Schema.NullOr(PluginProviderOperationId),\n commandReconciliationKey: Schema.NullOr(PersistedGovernedActionReconciliationLocator),\n commandTerminalStatus: Schema.NullOr(GovernedActionTerminalStatus),\n commandUnknownKind: Schema.NullOr(Schema.Literals([\"reconcilable\", \"manual\"])),\n commandDigest: GovernedActionCommandDigest,\n transitionDigest: GovernedActionTransitionDigest,\n envelopeDigest: GovernedActionEnvelopeDigest,\n fromState: Schema.NullOr(GovernedActionState),\n toState: GovernedActionState,\n resultLineageJson: Schema.String,\n resultLineageKind: GovernedActionLineageKind,\n resultProviderOperationId: Schema.NullOr(PluginProviderOperationId),\n resultReconciliationKey: Schema.NullOr(PluginActionReconciliationKey),\n resultTerminalStatus: Schema.NullOr(GovernedActionTerminalStatus),\n causeKind: GovernedActionCauseKind,\n causeActorId: Schema.NullOr(Schema.Union([PersonId, AgentId])),\n causeSessionId: Schema.NullOr(SessionId),\n causeJobId: Schema.NullOr(JobId),\n causeSystemComponent: Schema.NullOr(GovernedActionSystemComponent),\n causationId: Schema.NullOr(DomainEventId),\n correlationId: Schema.NullOr(DomainEventCorrelationId),\n transitionJson: Schema.String,\n occurredAt: Schema.String\n})\n\n/** Persisted audit event whose payload is the exact canonical transition JSON. */\nexport const GovernedActionAuditEventRow = Schema.Struct({\n workspaceId: WorkspaceId,\n actionId: GovernedActionId,\n transitionId: GovernedActionTransitionId,\n auditEventId: GovernedActionAuditEventId,\n eventKind: GovernedActionState,\n causeKind: GovernedActionCauseKind,\n actorId: Schema.NullOr(Schema.Union([PersonId, AgentId])),\n sessionId: Schema.NullOr(SessionId),\n jobId: Schema.NullOr(JobId),\n systemComponent: Schema.NullOr(GovernedActionSystemComponent),\n causationId: Schema.NullOr(DomainEventId),\n correlationId: Schema.NullOr(DomainEventCorrelationId),\n payloadDigest: GovernedActionTransitionDigest,\n payloadJson: Schema.String,\n occurredAt: Schema.String\n})\n\n/** Decode an untrusted driver result without allowing malformed rows into repository logic. */\nexport const decodeGovernedActionRows = <SchemaType extends Schema.Top>(schema: SchemaType, rows: unknown) =>\n Schema.decodeUnknownEffect(Schema.Array(schema))(rows)\n","import { type RenderedSql, renderGovernedActionIdempotencyQuery } from \"@knpkv/control-center-sql\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport * as Equal from \"effect/Equal\"\nimport * as Schema from \"effect/Schema\"\n\nimport {\n advanceGovernedActionLifecycle,\n governedActionAuthorityMismatches,\n governedActionAuthorizationMatchesTransition,\n governedActionAuthorizationMismatches\n} from \"../../../../domain/governedAction/index.js\"\nimport { GovernedActionId, ReleaseId } from \"../../../../domain/identifiers.js\"\nimport { UtcTimestamp } from \"../../../../domain/utcTimestamp.js\"\nimport { digestGovernedActionPolicyEvaluation } from \"../../../governance/governedActionDigests.js\"\nimport { Database } from \"../../Database.js\"\nimport { PersistedRecordError, RecordNotFoundError } from \"../../errors.js\"\nimport {\n decodeGovernedActionAttemptRow,\n decodeGovernedActionAuditEventRow,\n decodeGovernedActionAuthorizationRow,\n decodeGovernedActionPolicyEvaluationRow,\n decodeGovernedActionRow,\n decodeGovernedActionTransitionRow,\n encodeGovernedActionTransitionJson,\n type GovernedActionQuarantineReasonCode,\n type GovernedActionQuarantineRecordKind,\n governedActionRecordError\n} from \"./codec.js\"\nimport type {\n GovernedActionIdempotencyReadInput,\n GovernedActionReadInput,\n GovernedActionRecord,\n GovernedActionReleasePublicationReadInput,\n GovernedActionTargetReadInput\n} from \"./contract.js\"\nimport { captureMalformedGovernedActionRow } from \"./quarantine.js\"\nimport {\n GovernedActionAttemptRow,\n GovernedActionAuditEventRow,\n GovernedActionAuthorizationRow,\n GovernedActionPolicyEvaluationRow,\n GovernedActionRow,\n GovernedActionTransitionRow\n} from \"./rows.js\"\n\nconst MAXIMUM_GOVERNED_ACTION_TRANSITIONS = 1_000\nconst TERMINAL_TARGET_PAGE_SIZE = 100\n\nconst GovernedActionTargetCandidateIdentity = Schema.Struct({\n actionId: GovernedActionId,\n sortAt: UtcTimestamp\n})\n\nconst GovernedActionReleasePublicationCandidate = Schema.Struct({\n actionId: GovernedActionId,\n releaseId: ReleaseId\n})\n\nconst malformed = (\n request: GovernedActionReadInput,\n recordKind: GovernedActionQuarantineRecordKind,\n diagnosticCode: GovernedActionQuarantineReasonCode,\n recordKey: string = request.actionId\n) =>\n governedActionRecordError({\n workspaceId: request.workspaceId,\n recordKind,\n recordKey,\n diagnosticCode\n })\n\nconst decodeRawRow = <SchemaType extends Schema.Top>(\n request: GovernedActionReadInput,\n schema: SchemaType,\n raw: unknown,\n recordKind: GovernedActionQuarantineRecordKind,\n diagnosticCode: GovernedActionQuarantineReasonCode\n) =>\n Schema.decodeUnknownEffect(schema)(raw).pipe(\n Effect.mapError(() => malformed(request, recordKind, diagnosticCode)),\n captureMalformedGovernedActionRow(raw)\n )\n\nconst decodeRows = <SchemaType extends Schema.Top>(\n request: GovernedActionReadInput,\n schema: SchemaType,\n rows: ReadonlyArray<unknown>,\n recordKind: GovernedActionQuarantineRecordKind,\n diagnosticCode: GovernedActionQuarantineReasonCode\n) => Effect.forEach(rows, (row) => decodeRawRow(request, schema, row, recordKind, diagnosticCode))\n\nconst failMalformed = (\n request: GovernedActionReadInput,\n recordKind: GovernedActionQuarantineRecordKind,\n diagnosticCode: GovernedActionQuarantineReasonCode,\n row: unknown,\n recordKey?: string\n) => Effect.fail(malformed(request, recordKind, diagnosticCode, recordKey)).pipe(captureMalformedGovernedActionRow(row))\n\n/** Order verified target candidates by terminal observation and enforce local approval provenance. @internal */\nexport const selectLatestTerminalByTarget = (\n request: GovernedActionTargetReadInput,\n candidates: ReadonlyArray<GovernedActionRecord>\n): ReadonlyArray<GovernedActionRecord> =>\n candidates.filter(({ authorization, envelope, head }) =>\n envelope.proposal.request.actionKind === request.actionKind &&\n (\n request.expectedRevision === undefined ||\n envelope.proposal.request.expectedRevision === request.expectedRevision\n ) &&\n (\n request.actionKind !== \"record-approval\" ||\n (\n authorization !== null &&\n head.lineage._tag === \"terminal\" &&\n head.lineage.receipt.observationBasis === \"authorization\" &&\n DateTime.Order(head.lineage.receipt.observedAt, authorization.authorizedAt) === 0\n )\n )\n ).sort((left, right) => {\n if (left.head.lineage._tag !== \"terminal\" || right.head.lineage._tag !== \"terminal\") return 0\n const newestFirst = DateTime.Order(\n right.head.lineage.receipt.observedAt,\n left.head.lineage.receipt.observedAt\n )\n return newestFirst !== 0\n ? newestFirst\n : right.envelope.actionId.localeCompare(left.envelope.actionId)\n }).slice(0, request.limit)\n\n/** Decide whether verified candidates satisfy a bounded target read without another SQL page. @internal */\nexport const hasEnoughTerminalByTargetCandidates = (\n request: GovernedActionTargetReadInput,\n candidates: ReadonlyArray<GovernedActionRecord>\n): boolean => selectLatestTerminalByTarget(request, candidates).length >= request.limit\n\n/** @internal Decode the unique action identity returned by an idempotency lookup. */\nexport const decodeGovernedActionIdempotencyRows = Effect.fn(\n \"GovernedActionReader.decodeIdempotencyRows\"\n)(function*(\n request: GovernedActionIdempotencyReadInput,\n rows: ReadonlyArray<unknown>\n) {\n if (rows.length === 0) {\n return yield* new RecordNotFoundError({\n workspaceId: request.workspaceId,\n recordKind: \"governed-action\",\n recordKey: request.idempotencyKey\n })\n }\n if (rows.length !== 1) {\n return yield* new PersistedRecordError({\n workspaceId: request.workspaceId,\n recordKind: \"governed-action\",\n recordKey: request.idempotencyKey,\n diagnosticCode: \"governed-action-identity-mismatch\"\n })\n }\n const decoded = yield* Schema.decodeUnknownEffect(\n Schema.Struct({ actionId: GovernedActionId })\n )(rows[0]).pipe(\n Effect.mapError(() =>\n new PersistedRecordError({\n workspaceId: request.workspaceId,\n recordKind: \"governed-action\",\n recordKey: request.pluginConnectionId,\n diagnosticCode: \"governed-action-schema-invalid\"\n })\n )\n )\n return decoded.actionId\n})\n\n/** Build verified governed-action aggregate reads over one transaction-local SQL client. */\nexport const makeGovernedActionRead = Effect.gen(function*() {\n const { sql } = yield* Database\n const run = (plan: RenderedSql) => sql.unsafe<Record<string, unknown>>(plan.sql, [...plan.params])\n\n const read = Effect.fn(\"GovernedActionReader.read\")(function*(request: GovernedActionReadInput) {\n const rootRows = yield* sql<Record<string, unknown>>`SELECT\n workspace_id AS workspaceId, action_id AS actionId,\n plugin_connection_id AS pluginConnectionId, provider_id AS providerId,\n target_entity_id AS targetEntityId, idempotency_key AS idempotencyKey,\n envelope_digest AS envelopeDigest, envelope_json AS envelopeJson,\n state, lineage_json AS lineageJson, lineage_kind AS lineageKind,\n provider_operation_id AS providerOperationId,\n reconciliation_key AS reconciliationKey, terminal_status AS terminalStatus,\n head_transition_id AS headTransitionId, head_sequence AS headSequence,\n created_at AS createdAt, updated_at AS updatedAt\n FROM governed_actions\n WHERE workspace_id = ${request.workspaceId} AND action_id = ${request.actionId}`\n if (rootRows.length === 0) {\n return yield* new RecordNotFoundError({\n workspaceId: request.workspaceId,\n recordKind: \"governed-action\",\n recordKey: request.actionId\n })\n }\n if (rootRows.length !== 1) {\n return yield* new PersistedRecordError({\n workspaceId: request.workspaceId,\n recordKind: \"governed-action\",\n recordKey: request.actionId,\n diagnosticCode: \"governed-action-identity-mismatch\"\n })\n }\n const rootRow = rootRows[0]\n const decodedRootRow = yield* decodeRawRow(\n request,\n GovernedActionRow,\n rootRow,\n \"governed-action\",\n \"governed-action-schema-invalid\"\n )\n const root = yield* decodeGovernedActionRow(decodedRootRow).pipe(\n captureMalformedGovernedActionRow(rootRow)\n )\n if (root.head === null) {\n return yield* failMalformed(\n request,\n \"governed-action\",\n \"governed-action-head-mismatch\",\n rootRow\n )\n }\n\n const transitionRawRows = yield* sql<Record<string, unknown>>`SELECT\n workspace_id AS workspaceId, action_id AS actionId, transition_id AS transitionId,\n previous_transition_id AS previousTransitionId, sequence, command_id AS commandId,\n command_tag AS commandTag, authorization_id AS authorizationId, attempt_id AS attemptId,\n (SELECT ownership.policy_evaluation_digest\n FROM governed_action_denial_policy_evaluations ownership\n WHERE ownership.workspace_id = governed_action_transitions.workspace_id\n AND ownership.action_id = governed_action_transitions.action_id\n AND ownership.transition_id = governed_action_transitions.transition_id\n ) AS policyEvaluationDigest,\n outcome_source_kind AS outcomeSourceKind,\n command_provider_operation_id AS commandProviderOperationId,\n command_reconciliation_key AS commandReconciliationKey,\n command_terminal_status AS commandTerminalStatus, command_unknown_kind AS commandUnknownKind,\n command_digest AS commandDigest, transition_digest AS transitionDigest,\n envelope_digest AS envelopeDigest, from_state AS fromState, to_state AS toState,\n result_lineage_json AS resultLineageJson, result_lineage_kind AS resultLineageKind,\n result_provider_operation_id AS resultProviderOperationId,\n result_reconciliation_key AS resultReconciliationKey,\n result_terminal_status AS resultTerminalStatus, cause_kind AS causeKind,\n cause_actor_id AS causeActorId, cause_session_id AS causeSessionId,\n cause_job_id AS causeJobId, cause_system_component AS causeSystemComponent,\n causation_id AS causationId, correlation_id AS correlationId,\n transition_json AS transitionJson, occurred_at AS occurredAt\n FROM governed_action_transitions\n WHERE workspace_id = ${request.workspaceId} AND action_id = ${request.actionId}\n ORDER BY sequence\n LIMIT ${MAXIMUM_GOVERNED_ACTION_TRANSITIONS + 1}`\n if (\n transitionRawRows.length === 0 ||\n transitionRawRows.length > MAXIMUM_GOVERNED_ACTION_TRANSITIONS\n ) {\n return yield* failMalformed(\n request,\n \"governed-action-transition\",\n \"governed-action-chain-invalid\",\n rootRow\n )\n }\n const transitionRows = yield* decodeRows(\n request,\n GovernedActionTransitionRow,\n transitionRawRows,\n \"governed-action-transition\",\n \"governed-action-transition-schema-invalid\"\n )\n const decodedTransitions = yield* Effect.forEach(\n transitionRows,\n (row, index) =>\n decodeGovernedActionTransitionRow(row).pipe(\n captureMalformedGovernedActionRow(transitionRawRows[index])\n )\n )\n\n const auditRawRows = yield* sql<Record<string, unknown>>`SELECT\n workspace_id AS workspaceId, action_id AS actionId, transition_id AS transitionId,\n audit_event_id AS auditEventId, event_kind AS eventKind, cause_kind AS causeKind,\n actor_id AS actorId, session_id AS sessionId, job_id AS jobId,\n system_component AS systemComponent, causation_id AS causationId,\n correlation_id AS correlationId, payload_digest AS payloadDigest,\n payload_json AS payloadJson, occurred_at AS occurredAt\n FROM audit_events\n WHERE workspace_id = ${request.workspaceId} AND action_id = ${request.actionId}\n ORDER BY occurred_at, transition_id`\n const auditRows = yield* decodeRows(\n request,\n GovernedActionAuditEventRow,\n auditRawRows,\n \"governed-action-audit\",\n \"governed-action-audit-mismatch\"\n )\n const decodedAudits = yield* Effect.forEach(\n auditRows,\n (row, index) =>\n decodeGovernedActionAuditEventRow(row).pipe(\n captureMalformedGovernedActionRow(auditRawRows[index])\n )\n )\n if (decodedAudits.length !== decodedTransitions.length) {\n return yield* failMalformed(\n request,\n \"governed-action-audit\",\n \"governed-action-audit-mismatch\",\n transitionRawRows.at(-1) ?? rootRow\n )\n }\n\n let lifecycle: GovernedActionRecord[\"head\"] | null = null\n let previousTransitionId: GovernedActionRecord[\"headTransition\"][\"transitionId\"] | null = null\n for (const [index, decoded] of decodedTransitions.entries()) {\n const transition = decoded.transition\n const expectedSequence = index + 1\n if (\n transition.sequence !== expectedSequence ||\n transition.previousTransitionId !== previousTransitionId ||\n transition.workspaceId !== request.workspaceId ||\n transition.actionId !== request.actionId ||\n transition.actionEnvelopeDigest !== root.envelope.envelopeDigest\n ) {\n return yield* failMalformed(\n request,\n \"governed-action-transition\",\n \"governed-action-chain-invalid\",\n transitionRawRows[index]\n )\n }\n const nextLifecycle = advanceGovernedActionLifecycle(lifecycle, transition.command)\n if (nextLifecycle === null || !Equal.equals(nextLifecycle, decoded.resultHead)) {\n return yield* failMalformed(\n request,\n \"governed-action-transition\",\n \"governed-action-chain-invalid\",\n transitionRawRows[index]\n )\n }\n const auditTransition = decodedAudits.find(\n (candidate) => candidate.transitionId === transition.transitionId\n )\n if (\n auditTransition === undefined ||\n (yield* encodeGovernedActionTransitionJson(auditTransition)) !==\n (yield* encodeGovernedActionTransitionJson(transition))\n ) {\n return yield* failMalformed(\n request,\n \"governed-action-audit\",\n \"governed-action-audit-mismatch\",\n auditRawRows[index] ?? transitionRawRows[index]\n )\n }\n lifecycle = nextLifecycle\n previousTransitionId = transition.transitionId\n }\n\n const finalTransition = decodedTransitions.at(-1)?.transition\n if (\n finalTransition === undefined ||\n lifecycle === null ||\n root.head.transitionId !== finalTransition.transitionId ||\n root.head.sequence !== finalTransition.sequence ||\n !Equal.equals(root.head.lifecycle, lifecycle) ||\n DateTime.Order(root.head.updatedAt, finalTransition.occurredAt) !== 0\n ) {\n return yield* failMalformed(\n request,\n \"governed-action\",\n \"governed-action-head-mismatch\",\n rootRow\n )\n }\n\n const authorizationRawRows = yield* sql<Record<string, unknown>>`SELECT\n workspace_id AS workspaceId, action_id AS actionId, authorization_id AS authorizationId,\n session_id AS sessionId, envelope_digest AS envelopeDigest,\n authorization_digest AS authorizationDigest, authorization_json AS authorizationJson,\n authorized_at AS authorizedAt, expires_at AS expiresAt\n FROM governed_action_authorizations\n WHERE workspace_id = ${request.workspaceId} AND action_id = ${request.actionId}\n LIMIT 2`\n const policyRawRows = yield* sql<Record<string, unknown>>`SELECT\n workspace_id AS workspaceId, action_id AS actionId, evaluation_digest AS evaluationDigest,\n evaluation_json AS evaluationJson, decision, evaluated_at AS evaluatedAt\n FROM governed_action_policy_evaluations\n WHERE workspace_id = ${request.workspaceId} AND action_id = ${request.actionId}\n LIMIT 2`\n const attemptRawRows = yield* sql<Record<string, unknown>>`SELECT\n workspace_id AS workspaceId, action_id AS actionId, attempt_id AS attemptId,\n authorization_id AS authorizationId, policy_evaluation_digest AS policyEvaluationDigest,\n attempt_digest AS attemptDigest, attempt_number AS attemptNumber,\n attempt_json AS attemptJson, started_at AS startedAt\n FROM governed_action_attempts\n WHERE workspace_id = ${request.workspaceId} AND action_id = ${request.actionId}\n LIMIT 2`\n if (authorizationRawRows.length > 1 || policyRawRows.length > 1 || attemptRawRows.length > 1) {\n return yield* failMalformed(\n request,\n \"governed-action\",\n \"governed-action-companion-invalid\",\n authorizationRawRows[1] ?? policyRawRows[1] ?? attemptRawRows[1] ?? rootRow\n )\n }\n\n const authorizationRow = authorizationRawRows[0]\n const policyRow = policyRawRows[0]\n const attemptRow = attemptRawRows[0]\n const authorization = authorizationRow === undefined\n ? null\n : yield* decodeRawRow(\n request,\n GovernedActionAuthorizationRow,\n authorizationRow,\n \"governed-action-authorization\",\n \"governed-action-companion-invalid\"\n ).pipe(\n Effect.flatMap(decodeGovernedActionAuthorizationRow),\n captureMalformedGovernedActionRow(authorizationRow)\n )\n const policyEvaluation = policyRow === undefined\n ? null\n : yield* decodeRawRow(\n request,\n GovernedActionPolicyEvaluationRow,\n policyRow,\n \"governed-action-policy-evaluation\",\n \"governed-action-companion-invalid\"\n ).pipe(\n Effect.flatMap(decodeGovernedActionPolicyEvaluationRow),\n captureMalformedGovernedActionRow(policyRow)\n )\n const attempt = attemptRow === undefined\n ? null\n : yield* decodeRawRow(\n request,\n GovernedActionAttemptRow,\n attemptRow,\n \"governed-action-attempt\",\n \"governed-action-companion-invalid\"\n ).pipe(\n Effect.flatMap(decodeGovernedActionAttemptRow),\n captureMalformedGovernedActionRow(attemptRow)\n )\n\n const authorizeTransition = decodedTransitions.find(({ transition }) => transition.command._tag === \"authorize\")\n ?.transition\n const startTransition = decodedTransitions.find(({ transition }) => transition.command._tag === \"start\")\n ?.transition\n const denialTransitionIndex = decodedTransitions.findIndex(\n ({ transition }) => transition.command._tag === \"deny\"\n )\n const denialPolicyEvaluationDigest = denialTransitionIndex < 0\n ? null\n : (transitionRows[denialTransitionIndex]?.policyEvaluationDigest ?? null)\n const policyEvaluationDigest = policyEvaluation === null\n ? null\n : yield* digestGovernedActionPolicyEvaluation(policyEvaluation).pipe(\n Effect.mapError(() =>\n malformed(\n request,\n \"governed-action-policy-evaluation\",\n \"governed-action-companion-invalid\"\n )\n )\n )\n const authorizationMatchesEnvelope = authorization === null ||\n governedActionAuthorizationMismatches({\n envelope: root.envelope,\n authorization\n }).length === 0\n const authorizationMatchesTransition = authorization === null ||\n (authorizeTransition !== undefined &&\n governedActionAuthorizationMatchesTransition(authorization, authorizeTransition))\n const policyMatchesEnvelope = policyEvaluation === null ||\n (Equal.equals(policyEvaluation.policy, root.envelope.policy) &&\n policyEvaluation.payloadDigest === root.envelope.proposal.payloadDigest &&\n policyEvaluation.evidenceSetDigest === root.envelope.evidenceSetDigest &&\n policyEvaluation.expectedRevision === root.envelope.proposal.request.expectedRevision)\n const attemptMatchesEnvelope = attempt === null ||\n (attempt.pluginConnectionId === root.envelope.pluginConnectionId &&\n attempt.idempotencyKey === root.envelope.idempotencyKey &&\n attempt.actionEnvelopeDigest === root.envelope.envelopeDigest &&\n attempt.expectedRevision === root.envelope.proposal.request.expectedRevision)\n const expectedPolicyEvaluationDigest = attempt?.policyEvaluationDigest ?? denialPolicyEvaluationDigest\n const policyHasOwningTransition = policyEvaluation === null\n ? expectedPolicyEvaluationDigest === null\n : expectedPolicyEvaluationDigest === policyEvaluationDigest &&\n (attempt !== null || policyEvaluation.decision === \"denied\")\n const dispatchAuthorityMatches = attempt === null ||\n (authorization !== null && policyEvaluation !== null &&\n DateTime.Order(policyEvaluation.evaluatedAt, attempt.startedAt) === 0 &&\n governedActionAuthorityMismatches({\n envelope: root.envelope,\n authorization,\n attempt,\n evaluatedAt: attempt.startedAt\n }).length === 0)\n if (\n !authorizationMatchesEnvelope ||\n !authorizationMatchesTransition ||\n (authorization === null) !== (authorizeTransition === undefined)\n ) {\n return yield* failMalformed(\n request,\n \"governed-action-authorization\",\n \"governed-action-companion-invalid\",\n authorizationRow ?? rootRow,\n authorization?.authorizationId\n )\n }\n if (\n !policyMatchesEnvelope ||\n !attemptMatchesEnvelope ||\n !policyHasOwningTransition ||\n !dispatchAuthorityMatches ||\n (attempt === null) !== (startTransition === undefined) ||\n (attempt !== null &&\n (startTransition?.command._tag !== \"start\" ||\n startTransition.command.attemptId !== attempt.attemptId ||\n authorization === null ||\n policyEvaluation === null ||\n attempt.authorizationId !== authorization.authorizationId ||\n attempt.policyEvaluationDigest !== policyEvaluationDigest))\n ) {\n return yield* failMalformed(\n request,\n \"governed-action\",\n \"governed-action-companion-invalid\",\n attemptRow ?? authorizationRow ?? policyRow ?? rootRow\n )\n }\n\n return {\n envelope: root.envelope,\n head: lifecycle,\n headTransition: finalTransition,\n history: decodedTransitions.map(({ transition }) => transition),\n authorization,\n policyEvaluation,\n attempt\n } satisfies GovernedActionRecord\n })\n\n const readByIdempotencyKey = Effect.fn(\n \"GovernedActionReader.readByIdempotencyKey\"\n )(function*(request: GovernedActionIdempotencyReadInput) {\n const rows = yield* run(renderGovernedActionIdempotencyQuery(request))\n const actionId = yield* decodeGovernedActionIdempotencyRows(request, rows).pipe(\n Effect.catchIf(\n (failure): failure is PersistedRecordError =>\n Schema.is(PersistedRecordError)(failure) &&\n failure.diagnosticCode === \"governed-action-schema-invalid\",\n (failure) => Effect.fail(failure).pipe(captureMalformedGovernedActionRow(rows[0]))\n )\n )\n return yield* read({ workspaceId: request.workspaceId, actionId })\n })\n\n const readLatestTerminalByTarget = Effect.fn(\n \"GovernedActionReader.readLatestTerminalByTarget\"\n )(function*(request: GovernedActionTargetReadInput) {\n const candidates: Array<GovernedActionRecord> = []\n const expectedRevision = request.expectedRevision ?? null\n let cursor: typeof GovernedActionTargetCandidateIdentity.Type | null = null\n while (!hasEnoughTerminalByTargetCandidates(request, candidates)) {\n const rows: ReadonlyArray<Record<string, unknown>> = request.actionKind === \"record-approval\"\n ? cursor === null\n ? yield* sql<Record<string, unknown>>`SELECT\n action.action_id AS actionId,\n COALESCE(authorization.authorized_at, action.updated_at) AS sortAt\n FROM governed_actions AS action\n JOIN governed_action_target_dimensions AS dimensions\n ON dimensions.workspace_id = action.workspace_id\n AND dimensions.action_id = action.action_id\n LEFT JOIN governed_action_authorizations AS authorization\n ON authorization.workspace_id = action.workspace_id\n AND authorization.action_id = action.action_id\n WHERE action.workspace_id = ${request.workspaceId}\n AND action.provider_id = ${request.providerId}\n AND action.target_entity_id = ${request.targetEntityId}\n AND action.terminal_status = 'succeeded'\n AND dimensions.action_kind = ${request.actionKind}\n AND (\n ${expectedRevision} IS NULL OR\n dimensions.expected_revision = ${expectedRevision}\n )\n ORDER BY\n COALESCE(authorization.authorized_at, action.updated_at) DESC,\n action.action_id DESC\n LIMIT ${TERMINAL_TARGET_PAGE_SIZE}`\n : yield* sql<Record<string, unknown>>`SELECT\n action.action_id AS actionId,\n COALESCE(authorization.authorized_at, action.updated_at) AS sortAt\n FROM governed_actions AS action\n JOIN governed_action_target_dimensions AS dimensions\n ON dimensions.workspace_id = action.workspace_id\n AND dimensions.action_id = action.action_id\n LEFT JOIN governed_action_authorizations AS authorization\n ON authorization.workspace_id = action.workspace_id\n AND authorization.action_id = action.action_id\n WHERE action.workspace_id = ${request.workspaceId}\n AND action.provider_id = ${request.providerId}\n AND action.target_entity_id = ${request.targetEntityId}\n AND action.terminal_status = 'succeeded'\n AND dimensions.action_kind = ${request.actionKind}\n AND (\n ${expectedRevision} IS NULL OR\n dimensions.expected_revision = ${expectedRevision}\n )\n AND (\n COALESCE(authorization.authorized_at, action.updated_at) < ${DateTime.formatIso(cursor.sortAt)}\n OR (\n COALESCE(authorization.authorized_at, action.updated_at) = ${DateTime.formatIso(cursor.sortAt)}\n AND action.action_id < ${cursor.actionId}\n )\n )\n ORDER BY\n COALESCE(authorization.authorized_at, action.updated_at) DESC,\n action.action_id DESC\n LIMIT ${TERMINAL_TARGET_PAGE_SIZE}`\n : cursor === null\n ? yield* sql<Record<string, unknown>>`SELECT\n action.action_id AS actionId, action.updated_at AS sortAt\n FROM governed_actions AS action\n JOIN governed_action_target_dimensions AS dimensions\n ON dimensions.workspace_id = action.workspace_id\n AND dimensions.action_id = action.action_id\n WHERE action.workspace_id = ${request.workspaceId}\n AND action.provider_id = ${request.providerId}\n AND action.target_entity_id = ${request.targetEntityId}\n AND action.terminal_status = 'succeeded'\n AND dimensions.action_kind = ${request.actionKind}\n AND (\n ${expectedRevision} IS NULL OR\n dimensions.expected_revision = ${expectedRevision}\n )\n ORDER BY action.updated_at DESC, action.action_id DESC\n LIMIT ${TERMINAL_TARGET_PAGE_SIZE}`\n : yield* sql<Record<string, unknown>>`SELECT\n action.action_id AS actionId, action.updated_at AS sortAt\n FROM governed_actions AS action\n JOIN governed_action_target_dimensions AS dimensions\n ON dimensions.workspace_id = action.workspace_id\n AND dimensions.action_id = action.action_id\n WHERE action.workspace_id = ${request.workspaceId}\n AND action.provider_id = ${request.providerId}\n AND action.target_entity_id = ${request.targetEntityId}\n AND action.terminal_status = 'succeeded'\n AND dimensions.action_kind = ${request.actionKind}\n AND (\n ${expectedRevision} IS NULL OR\n dimensions.expected_revision = ${expectedRevision}\n )\n AND (\n action.updated_at < ${DateTime.formatIso(cursor.sortAt)}\n OR (\n action.updated_at = ${DateTime.formatIso(cursor.sortAt)}\n AND action.action_id < ${cursor.actionId}\n )\n )\n ORDER BY action.updated_at DESC, action.action_id DESC\n LIMIT ${TERMINAL_TARGET_PAGE_SIZE}`\n const identities: ReadonlyArray<typeof GovernedActionTargetCandidateIdentity.Type> = yield* Schema\n .decodeUnknownEffect(\n Schema.Array(GovernedActionTargetCandidateIdentity).check(\n Schema.isMaxLength(TERMINAL_TARGET_PAGE_SIZE)\n )\n )(rows).pipe(\n Effect.mapError(() =>\n new PersistedRecordError({\n workspaceId: request.workspaceId,\n recordKind: \"governed-action\",\n recordKey: request.targetEntityId,\n diagnosticCode: \"governed-action-schema-invalid\"\n })\n )\n )\n const verifiedPage = yield* Effect.forEach(\n identities,\n ({ actionId }) => read({ workspaceId: request.workspaceId, actionId })\n )\n for (const candidate of verifiedPage) candidates.push(candidate)\n if (identities.length < TERMINAL_TARGET_PAGE_SIZE) break\n cursor = identities[identities.length - 1] ?? null\n }\n return selectLatestTerminalByTarget(request, candidates)\n })\n\n const readLatestTerminalReleasePublications = Effect.fn(\n \"GovernedActionReader.readLatestTerminalReleasePublications\"\n )(function*(request: GovernedActionReleasePublicationReadInput) {\n const releaseIdsJson = JSON.stringify(request.releaseIds)\n const rows = yield* sql<Record<string, unknown>>`WITH requested_release_ids AS (\n SELECT value AS releaseId\n FROM json_each(${releaseIdsJson})\n ),\n ranked_publications AS (\n SELECT\n publication.action_id AS actionId,\n publication.release_id AS releaseId,\n ROW_NUMBER() OVER (\n PARTITION BY publication.release_id\n ORDER BY action.updated_at DESC, action.action_id DESC\n ) AS candidateRank\n FROM governed_action_release_publications AS publication\n JOIN governed_actions AS action\n ON action.workspace_id = publication.workspace_id\n AND action.action_id = publication.action_id\n JOIN governed_action_target_dimensions AS dimensions\n ON dimensions.workspace_id = action.workspace_id\n AND dimensions.action_id = action.action_id\n JOIN requested_release_ids AS requested\n ON requested.releaseId = publication.release_id\n WHERE publication.workspace_id = ${request.workspaceId}\n AND publication.provider_id = ${request.providerId}\n AND action.state IN (\n 'proposed', 'authorized', 'started', 'cancel-requested',\n 'unknown', 'cancel-requested-unknown', 'succeeded'\n )\n AND dimensions.action_kind IN ('create-page', 'update-page')\n )\n SELECT actionId, releaseId\n FROM ranked_publications\n WHERE candidateRank = 1\n ORDER BY releaseId`\n const candidates = yield* Schema.decodeUnknownEffect(\n Schema.Array(GovernedActionReleasePublicationCandidate).check(\n Schema.isMaxLength(request.releaseIds.length)\n )\n )(rows).pipe(\n Effect.mapError(() =>\n new PersistedRecordError({\n workspaceId: request.workspaceId,\n recordKind: \"governed-action\",\n recordKey: request.workspaceId,\n diagnosticCode: \"governed-action-schema-invalid\"\n })\n )\n )\n return yield* Effect.forEach(\n candidates,\n ({ actionId, releaseId }) =>\n read({ workspaceId: request.workspaceId, actionId }).pipe(\n Effect.flatMap((record) => {\n const publication = record.envelope.releasePublication\n const actionKind = record.envelope.proposal.request.actionKind\n return publication !== undefined &&\n publication.releaseId === releaseId &&\n record.envelope.providerId === request.providerId &&\n (actionKind === \"create-page\" || actionKind === \"update-page\") &&\n (\n record.head.state === \"proposed\" ||\n record.head.state === \"authorized\" ||\n record.head.state === \"started\" ||\n record.head.state === \"cancel-requested\" ||\n record.head.state === \"unknown\" ||\n record.head.state === \"cancel-requested-unknown\" ||\n (\n record.head.state === \"succeeded\" &&\n record.head.lineage._tag === \"terminal\" &&\n record.head.lineage.receipt.status === \"succeeded\"\n )\n )\n ? Effect.succeed(record)\n : Effect.fail(\n new PersistedRecordError({\n workspaceId: request.workspaceId,\n recordKind: \"governed-action\",\n recordKey: actionId,\n diagnosticCode: \"governed-action-identity-mismatch\"\n })\n )\n })\n )\n )\n })\n\n return {\n read,\n readByIdempotencyKey,\n readLatestTerminalByTarget,\n readLatestTerminalReleasePublications\n }\n})\n","import * as Clock from \"effect/Clock\"\nimport * as Crypto from \"effect/Crypto\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Result from \"effect/Result\"\n\nimport { Database } from \"../../Database.js\"\nimport type { PersistedRecordError, PersistenceOperationError, QuarantineWriteError } from \"../../errors.js\"\nimport { mapPersistenceOperation } from \"../internal.js\"\nimport { makePersistedRowQuarantine } from \"../persistedRowQuarantine.js\"\nimport { QuarantineRepository } from \"../quarantineRepository.js\"\nimport type {\n GovernedActionIdempotencyReadInput,\n GovernedActionReadInput,\n GovernedActionReleasePublicationReadInput,\n GovernedActionTargetReadInput\n} from \"./contract.js\"\nimport type { MalformedGovernedActionRecord } from \"./quarantine.js\"\nimport { governedActionQuarantineDiagnostic } from \"./quarantine.js\"\nimport { makeGovernedActionRead } from \"./read.js\"\n\nconst isMalformedGovernedActionRecord = (failure: unknown): failure is MalformedGovernedActionRecord =>\n Predicate.isTagged(\"MalformedGovernedActionRecord\")(failure) &&\n Predicate.hasProperty(failure, \"error\") &&\n Predicate.isTagged(\"PersistedRecordError\")(failure.error) &&\n Predicate.hasProperty(failure, \"row\")\n\n/**\n * Build the rollback-then-quarantine boundary shared by verified governed-action transactions.\n * Raw malformed rows never escape this module or enter the quarantine table before rollback.\n */\nexport const makeGovernedActionTransaction = Effect.gen(function*() {\n const database = yield* Database\n const clock = yield* Clock.Clock\n const cryptoService = yield* Crypto.Crypto\n const quarantine = yield* QuarantineRepository\n const quarantineRow = makePersistedRowQuarantine(cryptoService, quarantine)\n const reader = yield* makeGovernedActionRead\n\n const quarantineMalformed = Effect.fn(\"GovernedActionTransaction.quarantineMalformed\")(function*(\n malformed: MalformedGovernedActionRecord\n ) {\n const diagnostic = governedActionQuarantineDiagnostic(malformed.error)\n if (diagnostic !== null) {\n yield* quarantineRow({\n workspaceId: malformed.error.workspaceId,\n ...diagnostic,\n recordKey: malformed.error.recordKey,\n observedAt: DateTime.makeUnsafe(yield* clock.currentTimeMillis),\n row: malformed.row\n })\n }\n return yield* malformed.error\n })\n\n const capture = <Value, Failure, Requirements>(\n effect: Effect.Effect<Value, Failure, Requirements>\n ): Effect.Effect<\n Value,\n Failure | PersistedRecordError | PersistenceOperationError | QuarantineWriteError,\n Requirements\n > =>\n effect.pipe(\n Effect.result,\n Effect.flatMap(\n (\n result\n ): Effect.Effect<\n Value,\n Failure | PersistedRecordError | PersistenceOperationError | QuarantineWriteError,\n Requirements\n > => {\n if (Result.isSuccess(result)) return Effect.succeed(result.success)\n return isMalformedGovernedActionRecord(result.failure)\n ? quarantineMalformed(result.failure)\n : Effect.fail(result.failure)\n }\n )\n )\n\n const transact = <Value, Failure, Requirements>(\n operation: string,\n effect: Effect.Effect<Value, Failure, Requirements>\n ): Effect.Effect<\n Value,\n Failure | PersistedRecordError | PersistenceOperationError | QuarantineWriteError,\n Requirements\n > => capture(database.transaction(effect).pipe(mapPersistenceOperation(operation)))\n\n const read = (request: GovernedActionReadInput) =>\n reader.read(request).pipe(Effect.provideService(Crypto.Crypto, cryptoService))\n const readByIdempotencyKey = (request: GovernedActionIdempotencyReadInput) =>\n reader.readByIdempotencyKey(request).pipe(\n Effect.provideService(Crypto.Crypto, cryptoService)\n )\n const readLatestTerminalByTarget = (request: GovernedActionTargetReadInput) =>\n reader.readLatestTerminalByTarget(request).pipe(\n Effect.provideService(Crypto.Crypto, cryptoService)\n )\n const readLatestTerminalReleasePublications = (request: GovernedActionReleasePublicationReadInput) =>\n reader.readLatestTerminalReleasePublications(request).pipe(\n Effect.provideService(Crypto.Crypto, cryptoService)\n )\n\n return {\n capture,\n read,\n readByIdempotencyKey,\n readLatestTerminalByTarget,\n readLatestTerminalReleasePublications,\n transact\n }\n})\n","import * as Crypto from \"effect/Crypto\"\nimport * as Effect from \"effect/Effect\"\nimport * as Schema from \"effect/Schema\"\n\nimport { UtcTimestamp } from \"../../../../domain/utcTimestamp.js\"\nimport {\n digestGovernedActionAttempt,\n digestGovernedActionAuthorization,\n digestGovernedActionPolicyEvaluation\n} from \"../../../governance/governedActionDigests.js\"\nimport { PersistedRecordError, PersistenceOperationError } from \"../../errors.js\"\nimport {\n GovernedActionAttemptJson,\n GovernedActionAuthorizationJson,\n GovernedActionCauseJson,\n GovernedActionCommandJson,\n GovernedActionEnvelopeJson,\n GovernedActionLineageJson,\n GovernedActionPolicyEvaluationJson,\n type GovernedActionQuarantineReasonCode,\n type GovernedActionQuarantineRecordKind,\n GovernedActionTransitionJson,\n projectGovernedActionCause,\n projectGovernedActionCommand,\n projectGovernedActionLineage\n} from \"./codec.js\"\nimport type { GovernedActionCommitCompanion, GovernedActionCommitInput } from \"./contract.js\"\nimport { GovernedActionInputError } from \"./contract.js\"\n\nexport const EnvelopeJson = GovernedActionEnvelopeJson\nexport const TransitionJson = GovernedActionTransitionJson\nconst AuthorizationJson = GovernedActionAuthorizationJson\nconst PolicyEvaluationJson = GovernedActionPolicyEvaluationJson\nconst AttemptJson = GovernedActionAttemptJson\nexport const CommandJson = GovernedActionCommandJson\nexport const CauseJson = GovernedActionCauseJson\nexport const LineageJson = GovernedActionLineageJson\n\ninterface PreparedCompanionNone {\n readonly _tag: \"none\"\n}\n\ninterface PreparedCompanionAuthorization {\n readonly _tag: \"authorization\"\n readonly value: GovernedActionCommitCompanion & { readonly _tag: \"authorization\" }\n readonly digest: string\n readonly json: string\n readonly authorizedAt: string\n readonly expiresAt: string\n}\n\ninterface PreparedCompanionDispatch {\n readonly _tag: \"dispatch\"\n readonly value: Extract<GovernedActionCommitCompanion, { readonly _tag: \"dispatch\" }>\n readonly evaluationDigest: string\n readonly evaluationJson: string\n readonly evaluatedAt: string\n readonly attemptDigest: string\n readonly attemptJson: string\n readonly startedAt: string\n}\n\ninterface PreparedCompanionPolicyDenial {\n readonly _tag: \"policyDenial\"\n readonly value: Extract<GovernedActionCommitCompanion, { readonly _tag: \"policyDenial\" }>\n readonly evaluationDigest: string\n readonly evaluationJson: string\n readonly evaluatedAt: string\n}\n\nexport type PreparedCompanion =\n | PreparedCompanionNone\n | PreparedCompanionAuthorization\n | PreparedCompanionDispatch\n | PreparedCompanionPolicyDenial\n\ninterface CauseColumns {\n readonly kind: \"human\" | \"agent\" | \"system\"\n readonly actorId: string | null\n readonly sessionId: string | null\n readonly jobId: string | null\n readonly systemComponent: string | null\n}\n\ninterface LineageColumns {\n readonly kind: \"none\" | \"accepted\" | \"reconcilable\" | \"manual\" | \"terminal\"\n readonly providerOperationId: string | null\n readonly reconciliationKey: string | null\n readonly terminalStatus: \"succeeded\" | \"failed\" | \"cancelled\" | null\n}\n\nexport const persistedError = (\n input: GovernedActionCommitInput,\n recordKind: GovernedActionQuarantineRecordKind,\n recordKey: string,\n diagnosticCode: GovernedActionQuarantineReasonCode\n) =>\n new PersistedRecordError({\n workspaceId: input.envelope.workspaceId,\n recordKind,\n recordKey,\n diagnosticCode\n })\n\nexport const inputError = (reason: GovernedActionInputError[\"reason\"]) =>\n new GovernedActionInputError({ operation: \"commit\", reason })\n\nexport const encodeJson = <Value, Encoded, Requirements>(\n operation: string,\n codec: Schema.Codec<Value, Encoded, Requirements>,\n value: Value\n) =>\n Schema.encodeEffect(codec)(value).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation }))\n )\n\nexport const encodeTimestamp = (operation: string, value: typeof UtcTimestamp.Type) =>\n encodeJson(operation, UtcTimestamp, value)\n\nexport const prepareCompanion = (cryptoService: Crypto.Crypto) =>\n Effect.fn(\"GovernedActionWriter.prepareCompanion\")(function*(\n companion: GovernedActionCommitCompanion\n ): Effect.fn.Return<PreparedCompanion, GovernedActionInputError | PersistenceOperationError> {\n switch (companion._tag) {\n case \"none\":\n return { _tag: \"none\" }\n case \"authorization\":\n return {\n _tag: \"authorization\",\n value: companion,\n digest: yield* digestGovernedActionAuthorization(companion.authorization).pipe(\n Effect.provideService(Crypto.Crypto, cryptoService),\n Effect.mapError(() => new PersistenceOperationError({ operation: \"governed-action.digest-authorization\" }))\n ),\n json: yield* encodeJson(\n \"governed-action.encode-authorization\",\n AuthorizationJson,\n companion.authorization\n ),\n authorizedAt: yield* encodeTimestamp(\n \"governed-action.encode-authorization-time\",\n companion.authorization.authorizedAt\n ),\n expiresAt: yield* encodeTimestamp(\n \"governed-action.encode-authorization-expiry\",\n companion.authorization.expiresAt\n )\n }\n case \"dispatch\": {\n const attempt = companion.attempt\n const evaluationDigest = yield* digestGovernedActionPolicyEvaluation(companion.policyEvaluation).pipe(\n Effect.provideService(Crypto.Crypto, cryptoService),\n Effect.mapError(() => new PersistenceOperationError({ operation: \"governed-action.digest-policy\" }))\n )\n if (\n companion.policyEvaluation.decision !== \"allowed\" ||\n evaluationDigest !== attempt.policyEvaluationDigest\n ) {\n return yield* inputError(\"illegal-transition\")\n }\n return {\n _tag: \"dispatch\",\n value: companion,\n evaluationDigest,\n evaluationJson: yield* encodeJson(\n \"governed-action.encode-policy\",\n PolicyEvaluationJson,\n companion.policyEvaluation\n ),\n evaluatedAt: yield* encodeTimestamp(\n \"governed-action.encode-policy-time\",\n companion.policyEvaluation.evaluatedAt\n ),\n attemptDigest: yield* digestGovernedActionAttempt(attempt).pipe(\n Effect.provideService(Crypto.Crypto, cryptoService),\n Effect.mapError(() => new PersistenceOperationError({ operation: \"governed-action.digest-attempt\" }))\n ),\n attemptJson: yield* encodeJson(\"governed-action.encode-attempt\", AttemptJson, attempt),\n startedAt: yield* encodeTimestamp(\"governed-action.encode-attempt-time\", attempt.startedAt)\n }\n }\n case \"policyDenial\":\n return {\n _tag: \"policyDenial\",\n value: companion,\n evaluationDigest: yield* digestGovernedActionPolicyEvaluation(companion.policyEvaluation).pipe(\n Effect.provideService(Crypto.Crypto, cryptoService),\n Effect.mapError(() => new PersistenceOperationError({ operation: \"governed-action.digest-policy\" }))\n ),\n evaluationJson: yield* encodeJson(\n \"governed-action.encode-policy\",\n PolicyEvaluationJson,\n companion.policyEvaluation\n ),\n evaluatedAt: yield* encodeTimestamp(\n \"governed-action.encode-policy-time\",\n companion.policyEvaluation.evaluatedAt\n )\n }\n }\n })\n\nexport const commandColumns = (command: GovernedActionCommitInput[\"command\"]) => {\n const projection = projectGovernedActionCommand(command)\n return {\n authorizationId: projection.authorizationId,\n attemptId: projection.attemptId,\n outcomeSourceKind: projection.outcomeSourceKind,\n providerOperationId: projection.commandProviderOperationId,\n reconciliationKey: projection.commandReconciliationKey,\n terminalStatus: projection.commandTerminalStatus,\n unknownKind: projection.commandUnknownKind\n }\n}\n\nexport const causeColumns = (cause: GovernedActionCommitInput[\"cause\"]): CauseColumns => {\n const projection = projectGovernedActionCause(cause)\n return {\n kind: projection.causeKind,\n actorId: projection.causeActorId,\n sessionId: projection.causeSessionId,\n jobId: projection.causeJobId,\n systemComponent: projection.causeSystemComponent\n }\n}\n\nexport const lineageColumns = (\n lineage: Parameters<typeof projectGovernedActionLineage>[0]\n): LineageColumns => {\n const projection = projectGovernedActionLineage(lineage)\n return {\n kind: projection.lineageKind,\n providerOperationId: projection.providerOperationId,\n reconciliationKey: projection.reconciliationKey,\n terminalStatus: projection.terminalStatus\n }\n}\n","import * as Crypto from \"effect/Crypto\"\nimport * as Effect from \"effect/Effect\"\nimport * as Schema from \"effect/Schema\"\n\nimport {\n governedActionAuthorizationMatchesTransition,\n governedActionAuthorizationMismatches\n} from \"../../../../domain/governedAction/index.js\"\nimport {\n digestGovernedActionTransition,\n verifyGovernedActionTransition\n} from \"../../../governance/governedActionDigests.js\"\nimport { decodeGovernedActionAuthorizationRow, type GovernedActionQuarantineRecordKind } from \"./codec.js\"\nimport type { GovernedActionCommitInput, GovernedActionCommitResult } from \"./contract.js\"\nimport { GovernedActionAuthorizationRow } from \"./rows.js\"\nimport {\n causeColumns,\n CauseJson,\n CommandJson,\n encodeJson,\n encodeTimestamp,\n inputError,\n persistedError,\n type PreparedCompanion,\n TransitionJson\n} from \"./write-preparation.js\"\n\nexport const GovernedActionReplayRow = Schema.Struct({\n transitionId: Schema.String,\n previousTransitionId: Schema.NullOr(Schema.String),\n commandId: Schema.String,\n commandDigest: Schema.String,\n transitionDigest: Schema.String,\n transitionJson: Schema.String,\n linkedPolicyEvaluationDigest: Schema.NullOr(Schema.String),\n auditEventId: Schema.NullOr(Schema.String),\n auditEventKind: Schema.NullOr(Schema.String),\n auditCauseKind: Schema.NullOr(Schema.String),\n auditActorId: Schema.NullOr(Schema.String),\n auditSessionId: Schema.NullOr(Schema.String),\n auditJobId: Schema.NullOr(Schema.String),\n auditSystemComponent: Schema.NullOr(Schema.String),\n auditCausationId: Schema.NullOr(Schema.String),\n auditCorrelationId: Schema.NullOr(Schema.String),\n auditPayloadDigest: Schema.NullOr(Schema.String),\n auditPayloadJson: Schema.NullOr(Schema.String),\n auditOccurredAt: Schema.NullOr(Schema.String),\n authorizationWorkspaceId: Schema.NullOr(Schema.String),\n authorizationActionId: Schema.NullOr(Schema.String),\n authorizationId: Schema.NullOr(Schema.String),\n authorizationSessionId: Schema.NullOr(Schema.String),\n authorizationEnvelopeDigest: Schema.NullOr(Schema.String),\n authorizationDigest: Schema.NullOr(Schema.String),\n authorizationJson: Schema.NullOr(Schema.String),\n authorizationAuthorizedAt: Schema.NullOr(Schema.String),\n authorizationExpiresAt: Schema.NullOr(Schema.String),\n evaluationDigest: Schema.NullOr(Schema.String),\n evaluationJson: Schema.NullOr(Schema.String),\n attemptDigest: Schema.NullOr(Schema.String),\n attemptJson: Schema.NullOr(Schema.String),\n unownedEvaluationCount: Schema.Int\n})\n\nexport type GovernedActionReplayRow = typeof GovernedActionReplayRow.Type\n\nexport const makeGovernedActionReplay = (cryptoService: Crypto.Crypto) => {\n const decodeRows = Effect.fn(\"GovernedActionWriter.decodeReplayRows\")(function*(\n input: GovernedActionCommitInput,\n rows: ReadonlyArray<unknown>\n ) {\n return yield* Schema.decodeUnknownEffect(Schema.Array(GovernedActionReplayRow))(rows).pipe(\n Effect.mapError(() =>\n persistedError(\n input,\n \"governed-action-transition\",\n input.transitionId,\n \"governed-action-transition-schema-invalid\"\n )\n )\n )\n })\n\n const decodeTransition = Effect.fn(\"GovernedActionWriter.decodeTransition\")(function*(\n input: GovernedActionCommitInput,\n json: string,\n recordKey: string\n ) {\n const transition = yield* Schema.decodeUnknownEffect(TransitionJson)(json).pipe(\n Effect.mapError(() =>\n persistedError(input, \"governed-action-transition\", recordKey, \"governed-action-transition-schema-invalid\")\n )\n )\n yield* verifyGovernedActionTransition(transition).pipe(\n Effect.provideService(Crypto.Crypto, cryptoService),\n Effect.mapError(() =>\n persistedError(input, \"governed-action-transition\", recordKey, \"governed-action-transition-digest-mismatch\")\n )\n )\n return transition\n })\n\n const resolve = Effect.fn(\"GovernedActionWriter.resolveReplay\")(function*(\n input: GovernedActionCommitInput,\n commandDigest: string,\n commandJson: string,\n causeJson: string,\n companion: PreparedCompanion,\n rows: ReadonlyArray<GovernedActionReplayRow>\n ) {\n if (rows.length === 0) return null\n if (rows.length !== 1) return yield* inputError(\"changed-command-retry\")\n\n const row = rows[0]\n if (row === undefined) return yield* inputError(\"changed-command-retry\")\n const transition = yield* decodeTransition(input, row.transitionJson, row.transitionId)\n const storedCommandJson = yield* encodeJson(\n \"governed-action.encode-replayed-command\",\n CommandJson,\n transition.command\n ).pipe(\n Effect.mapError(() =>\n persistedError(\n input,\n \"governed-action-transition\",\n row.transitionId,\n \"governed-action-transition-schema-invalid\"\n )\n )\n )\n const storedCauseJson = yield* encodeJson(\n \"governed-action.encode-replayed-cause\",\n CauseJson,\n transition.cause\n ).pipe(\n Effect.mapError(() =>\n persistedError(\n input,\n \"governed-action-transition\",\n row.transitionId,\n \"governed-action-transition-schema-invalid\"\n )\n )\n )\n const occurredAt = yield* encodeTimestamp(\"governed-action.encode-replayed-time\", transition.occurredAt).pipe(\n Effect.mapError(() =>\n persistedError(\n input,\n \"governed-action-transition\",\n row.transitionId,\n \"governed-action-transition-schema-invalid\"\n )\n )\n )\n\n if (\n row.transitionId !== input.transitionId ||\n row.previousTransitionId !== input.expectedHeadTransitionId ||\n row.commandId !== input.commandId ||\n row.commandDigest !== commandDigest ||\n transition.workspaceId !== input.envelope.workspaceId ||\n transition.actionId !== input.envelope.actionId ||\n transition.actionEnvelopeDigest !== input.envelope.envelopeDigest ||\n storedCommandJson !== commandJson ||\n storedCauseJson !== causeJson ||\n occurredAt !== (yield* encodeTimestamp(\"governed-action.encode-command-time\", input.occurredAt)) ||\n transition.causationId !== input.causationId ||\n transition.correlationId !== input.correlationId\n ) {\n return yield* inputError(\"changed-command-retry\")\n }\n\n const companionMissing = (recordKind: GovernedActionQuarantineRecordKind) =>\n persistedError(input, recordKind, row.transitionId, \"governed-action-companion-invalid\")\n if (row.unownedEvaluationCount !== 0) {\n return yield* companionMissing(\"governed-action-policy-evaluation\")\n }\n switch (companion._tag) {\n case \"none\":\n if (\n row.linkedPolicyEvaluationDigest !== null ||\n row.authorizationDigest !== null ||\n row.authorizationJson !== null ||\n row.evaluationDigest !== null ||\n row.evaluationJson !== null ||\n row.attemptDigest !== null ||\n row.attemptJson !== null\n ) {\n return yield* inputError(\"changed-command-retry\")\n }\n break\n case \"authorization\": {\n if (\n row.authorizationWorkspaceId === null ||\n row.authorizationActionId === null ||\n row.authorizationId === null ||\n row.authorizationSessionId === null ||\n row.authorizationEnvelopeDigest === null ||\n row.authorizationDigest === null ||\n row.authorizationJson === null ||\n row.authorizationAuthorizedAt === null ||\n row.authorizationExpiresAt === null\n ) {\n return yield* companionMissing(\"governed-action-authorization\")\n }\n const authorizationRaw = {\n workspaceId: row.authorizationWorkspaceId,\n actionId: row.authorizationActionId,\n authorizationId: row.authorizationId,\n sessionId: row.authorizationSessionId,\n envelopeDigest: row.authorizationEnvelopeDigest,\n authorizationDigest: row.authorizationDigest,\n authorizationJson: row.authorizationJson,\n authorizedAt: row.authorizationAuthorizedAt,\n expiresAt: row.authorizationExpiresAt\n }\n const authorizationRow = yield* Schema.decodeUnknownEffect(\n GovernedActionAuthorizationRow\n )(authorizationRaw).pipe(\n Effect.mapError(() => companionMissing(\"governed-action-authorization\"))\n )\n const authorization = yield* decodeGovernedActionAuthorizationRow(authorizationRow).pipe(\n Effect.provideService(Crypto.Crypto, cryptoService)\n )\n if (\n governedActionAuthorizationMismatches({\n envelope: input.envelope,\n authorization\n }).length > 0 ||\n !governedActionAuthorizationMatchesTransition(authorization, transition)\n ) {\n return yield* persistedError(\n input,\n \"governed-action-authorization\",\n authorization.authorizationId,\n \"governed-action-companion-invalid\"\n )\n }\n if (row.authorizationDigest !== companion.digest || row.authorizationJson !== companion.json) {\n return yield* inputError(\"changed-command-retry\")\n }\n break\n }\n case \"policyDenial\":\n if (row.linkedPolicyEvaluationDigest === null) {\n return yield* inputError(\"changed-command-retry\")\n }\n if (row.evaluationDigest === null || row.evaluationJson === null) {\n return yield* companionMissing(\"governed-action-policy-evaluation\")\n }\n if (\n row.linkedPolicyEvaluationDigest !== companion.evaluationDigest ||\n row.evaluationDigest !== companion.evaluationDigest ||\n row.evaluationJson !== companion.evaluationJson\n ) {\n return yield* inputError(\"changed-command-retry\")\n }\n break\n case \"dispatch\":\n if (\n row.linkedPolicyEvaluationDigest !== null ||\n row.evaluationDigest === null ||\n row.evaluationJson === null ||\n row.attemptDigest === null ||\n row.attemptJson === null\n ) {\n return yield* companionMissing(\"governed-action-attempt\")\n }\n if (\n row.evaluationDigest !== companion.evaluationDigest ||\n row.evaluationJson !== companion.evaluationJson ||\n row.attemptDigest !== companion.attemptDigest ||\n row.attemptJson !== companion.attemptJson\n ) {\n return yield* inputError(\"changed-command-retry\")\n }\n break\n }\n\n if (\n row.auditEventId === null ||\n row.auditEventKind === null ||\n row.auditCauseKind === null ||\n row.auditPayloadDigest === null ||\n row.auditPayloadJson === null ||\n row.auditOccurredAt === null\n ) {\n return yield* persistedError(\n input,\n \"governed-action-transition\",\n row.transitionId,\n \"governed-action-audit-mismatch\"\n )\n }\n if (row.auditEventId !== input.auditEventId) return yield* inputError(\"changed-command-retry\")\n\n const transitionDigest = yield* digestGovernedActionTransition(transition).pipe(\n Effect.provideService(Crypto.Crypto, cryptoService),\n Effect.mapError(() =>\n persistedError(\n input,\n \"governed-action-transition\",\n row.transitionId,\n \"governed-action-transition-digest-mismatch\"\n )\n )\n )\n const auditTransition = yield* decodeTransition(input, row.auditPayloadJson, row.transitionId)\n const canonicalTransition = yield* encodeJson(\n \"governed-action.encode-replayed-transition\",\n TransitionJson,\n transition\n ).pipe(\n Effect.mapError(() =>\n persistedError(\n input,\n \"governed-action-transition\",\n row.transitionId,\n \"governed-action-transition-schema-invalid\"\n )\n )\n )\n const canonicalAuditTransition = yield* encodeJson(\n \"governed-action.encode-replayed-audit\",\n TransitionJson,\n auditTransition\n ).pipe(\n Effect.mapError(() =>\n persistedError(input, \"governed-action-audit\", row.transitionId, \"governed-action-audit-mismatch\")\n )\n )\n const cause = causeColumns(transition.cause)\n\n if (\n row.transitionDigest !== transitionDigest ||\n row.auditPayloadDigest !== transitionDigest ||\n canonicalAuditTransition !== canonicalTransition ||\n row.auditEventKind !== transition.toState ||\n row.auditCauseKind !== cause.kind ||\n row.auditActorId !== cause.actorId ||\n row.auditSessionId !== cause.sessionId ||\n row.auditJobId !== cause.jobId ||\n row.auditSystemComponent !== cause.systemComponent ||\n row.auditCausationId !== transition.causationId ||\n row.auditCorrelationId !== transition.correlationId ||\n row.auditOccurredAt !== occurredAt\n ) {\n return yield* persistedError(\n input,\n \"governed-action-audit\",\n row.transitionId,\n \"governed-action-audit-mismatch\"\n )\n }\n const result: GovernedActionCommitResult = { _tag: \"replayed\", transition }\n return result\n })\n\n return { decodeRows, resolve }\n}\n","import * as Crypto from \"effect/Crypto\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport * as Schema from \"effect/Schema\"\n\nimport type { GovernedActionProviderLineage } from \"../../../../domain/governedAction/index.js\"\nimport {\n advanceGovernedActionLifecycle,\n governedActionAuthorityMismatches,\n GovernedActionLifecycleHeadV1,\n GovernedActionTransitionV1\n} from \"../../../../domain/governedAction/index.js\"\nimport { UtcTimestamp } from \"../../../../domain/utcTimestamp.js\"\nimport {\n digestGovernedActionTransition,\n digestGovernedActionTransitionCommand,\n makeGovernedActionTransition,\n verifyGovernedActionEnvelope\n} from \"../../../governance/governedActionDigests.js\"\nimport { Database } from \"../../Database.js\"\nimport { PersistenceOperationError } from \"../../errors.js\"\nimport { mapPersistenceOperation, readChanges } from \"../internal.js\"\nimport { decodeGovernedActionAuthorizationRow } from \"./codec.js\"\nimport { GovernedActionCommitInput, type GovernedActionCommitResult } from \"./contract.js\"\nimport { captureMalformedGovernedActionRow } from \"./quarantine.js\"\nimport { GovernedActionAuthorizationRow } from \"./rows.js\"\nimport {\n causeColumns,\n CauseJson,\n commandColumns,\n CommandJson,\n encodeJson,\n encodeTimestamp,\n EnvelopeJson,\n inputError,\n lineageColumns,\n LineageJson,\n persistedError,\n prepareCompanion,\n type PreparedCompanion,\n TransitionJson\n} from \"./write-preparation.js\"\nimport { makeGovernedActionReplay } from \"./write-replay.js\"\n\nconst RootRow = Schema.Struct({\n actionId: Schema.String,\n pluginConnectionId: Schema.String,\n providerId: Schema.String,\n targetEntityId: Schema.String,\n idempotencyKey: Schema.String,\n envelopeDigest: Schema.String,\n envelopeJson: Schema.String,\n state: Schema.NullOr(Schema.String),\n lineageJson: Schema.NullOr(Schema.String),\n lineageKind: Schema.NullOr(Schema.String),\n providerOperationId: Schema.NullOr(Schema.String),\n reconciliationKey: Schema.NullOr(Schema.String),\n terminalStatus: Schema.NullOr(Schema.String),\n headTransitionId: Schema.NullOr(Schema.String),\n headSequence: Schema.NullOr(Schema.Int),\n persistedHeadTransitionId: Schema.NullOr(Schema.String),\n updatedAt: Schema.String\n})\n\nconst SessionAuthorityRow = Schema.Struct({\n personId: Schema.String,\n permission: Schema.String\n})\n\ntype RootRow = typeof RootRow.Type\n\ninterface RootHead {\n readonly state: typeof GovernedActionTransitionV1.Type[\"toState\"]\n readonly lineage: typeof GovernedActionProviderLineage.Type\n readonly transitionId: GovernedActionCommitInput[\"transitionId\"]\n readonly sequence: number\n readonly updatedAt: typeof UtcTimestamp.Type\n}\n\nconst makeGovernedActionTransactionWriter = Effect.gen(function*() {\n const database = yield* Database\n const cryptoService = yield* Crypto.Crypto\n const sql = database.sql\n const replay = makeGovernedActionReplay(cryptoService)\n\n const decodeRootRows = Effect.fn(\"GovernedActionWriter.decodeRootRows\")(function*(\n input: GovernedActionCommitInput,\n rows: ReadonlyArray<unknown>\n ) {\n return yield* Schema.decodeUnknownEffect(Schema.Array(RootRow))(rows).pipe(\n Effect.mapError(() =>\n persistedError(input, \"governed-action\", input.envelope.actionId, \"governed-action-schema-invalid\")\n )\n )\n })\n\n const verifyRootIdentity = Effect.fn(\"GovernedActionWriter.verifyRootIdentity\")(function*(\n input: GovernedActionCommitInput,\n expectedEnvelopeJson: string,\n row: RootRow\n ) {\n const envelope = yield* Schema.decodeUnknownEffect(EnvelopeJson)(row.envelopeJson).pipe(\n Effect.mapError(() => persistedError(input, \"governed-action\", row.actionId, \"governed-action-schema-invalid\"))\n )\n yield* verifyGovernedActionEnvelope(envelope).pipe(\n Effect.provideService(Crypto.Crypto, cryptoService),\n Effect.mapError(() => persistedError(input, \"governed-action\", row.actionId, \"governed-action-digest-mismatch\"))\n )\n const canonicalEnvelope = yield* encodeJson(\n \"governed-action.encode-stored-envelope\",\n EnvelopeJson,\n envelope\n ).pipe(\n Effect.mapError(() => persistedError(input, \"governed-action\", row.actionId, \"governed-action-schema-invalid\"))\n )\n if (\n row.actionId !== input.envelope.actionId ||\n row.pluginConnectionId !== input.envelope.pluginConnectionId ||\n row.providerId !== input.envelope.providerId ||\n row.targetEntityId !== input.envelope.targetEntityId ||\n row.idempotencyKey !== input.envelope.idempotencyKey ||\n row.envelopeDigest !== input.envelope.envelopeDigest ||\n canonicalEnvelope !== expectedEnvelopeJson\n ) {\n return yield* inputError(\"conflicting-action-identity\")\n }\n })\n\n const decodeRootHead = Effect.fn(\"GovernedActionWriter.decodeRootHead\")(function*(\n input: GovernedActionCommitInput,\n row: RootRow\n ) {\n if (\n row.state === null ||\n row.lineageJson === null ||\n row.headTransitionId === null ||\n row.headSequence === null\n ) {\n return yield* persistedError(input, \"governed-action\", row.actionId, \"governed-action-head-mismatch\")\n }\n const malformedHead = () => persistedError(input, \"governed-action\", row.actionId, \"governed-action-head-mismatch\")\n const state = yield* Schema.decodeUnknownEffect(GovernedActionTransitionV1.fields.toState)(row.state).pipe(\n Effect.mapError(malformedHead)\n )\n const lineage = yield* Schema.decodeUnknownEffect(LineageJson)(row.lineageJson).pipe(\n Effect.mapError(malformedHead)\n )\n const canonicalLineage = yield* encodeJson(\n \"governed-action.encode-stored-lineage\",\n LineageJson,\n lineage\n ).pipe(Effect.mapError(malformedHead))\n if (canonicalLineage !== row.lineageJson) return yield* malformedHead()\n const updatedAt = yield* Schema.decodeUnknownEffect(UtcTimestamp)(row.updatedAt).pipe(\n Effect.mapError(malformedHead)\n )\n const transitionId = yield* Schema.decodeUnknownEffect(\n GovernedActionTransitionV1.fields.transitionId\n )(row.headTransitionId).pipe(Effect.mapError(malformedHead))\n const lifecycle = yield* Schema.decodeUnknownEffect(Schema.toType(GovernedActionLifecycleHeadV1))({\n state,\n lineage\n }).pipe(\n Effect.mapError(malformedHead)\n )\n const normalizedLineage = lineageColumns(lifecycle.lineage)\n if (\n row.persistedHeadTransitionId !== row.headTransitionId ||\n row.lineageKind !== normalizedLineage.kind ||\n row.providerOperationId !== normalizedLineage.providerOperationId ||\n row.reconciliationKey !== normalizedLineage.reconciliationKey ||\n row.terminalStatus !== normalizedLineage.terminalStatus\n ) {\n return yield* malformedHead()\n }\n return {\n state: lifecycle.state,\n lineage: lifecycle.lineage,\n transitionId,\n sequence: row.headSequence,\n updatedAt\n }\n })\n\n const insertCompanion = Effect.fn(\"GovernedActionWriter.insertCompanion\")(function*(\n prepared: PreparedCompanion\n ) {\n switch (prepared._tag) {\n case \"none\":\n return\n case \"authorization\": {\n const authorization = prepared.value.authorization\n const sessionRows = yield* sql`SELECT person_id AS personId, permission\n FROM sessions\n WHERE workspace_id = ${authorization.workspaceId}\n AND session_id = ${authorization.sessionId}`\n const sessions = yield* Schema.decodeUnknownEffect(Schema.Array(SessionAuthorityRow))(sessionRows).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"governed-action.read-session-authority\" }))\n )\n if (\n sessions.length !== 1 ||\n sessions[0]?.personId !== authorization.actor.personId ||\n sessions[0]?.permission !== authorization.sessionPermission\n ) {\n return yield* inputError(\"illegal-transition\")\n }\n yield* sql`INSERT INTO governed_action_authorizations (\n workspace_id, action_id, authorization_id, session_id, envelope_digest,\n authorization_digest, authorization_json, authorized_at, expires_at\n ) VALUES (\n ${authorization.workspaceId}, ${authorization.actionId}, ${authorization.authorizationId},\n ${authorization.sessionId}, ${authorization.actionEnvelopeDigest}, ${prepared.digest},\n ${prepared.json}, ${prepared.authorizedAt}, ${prepared.expiresAt}\n )`\n return\n }\n case \"policyDenial\":\n case \"dispatch\": {\n const evaluation = prepared.value.policyEvaluation\n yield* sql`INSERT INTO governed_action_policy_evaluations (\n workspace_id, action_id, evaluation_digest, evaluation_json, decision, evaluated_at\n ) VALUES (\n ${evaluation.workspaceId}, ${evaluation.actionId}, ${prepared.evaluationDigest},\n ${prepared.evaluationJson}, ${evaluation.decision}, ${prepared.evaluatedAt}\n )`\n if (prepared._tag === \"policyDenial\") return\n const attempt = prepared.value.attempt\n yield* sql`INSERT INTO governed_action_attempts (\n workspace_id, action_id, attempt_id, authorization_id, policy_evaluation_digest,\n attempt_digest, attempt_number, attempt_json, started_at\n ) VALUES (\n ${attempt.workspaceId}, ${attempt.actionId}, ${attempt.attemptId}, ${attempt.authorizationId},\n ${prepared.evaluationDigest}, ${prepared.attemptDigest}, ${attempt.attemptNumber},\n ${prepared.attemptJson}, ${prepared.startedAt}\n )`\n }\n }\n })\n\n const verifyDispatchAuthorization = Effect.fn(\n \"GovernedActionWriter.verifyDispatchAuthorization\"\n )(function*(\n input: GovernedActionCommitInput,\n prepared: PreparedCompanion,\n mode: \"commit\" | \"replay\"\n ) {\n if (prepared._tag !== \"dispatch\") return\n const attempt = prepared.value.attempt\n const authorizationRawRows = yield* sql`SELECT\n workspace_id AS workspaceId, action_id AS actionId, authorization_id AS authorizationId,\n session_id AS sessionId, envelope_digest AS envelopeDigest,\n authorization_digest AS authorizationDigest, authorization_json AS authorizationJson,\n authorized_at AS authorizedAt, expires_at AS expiresAt\n FROM governed_action_authorizations\n WHERE workspace_id = ${attempt.workspaceId}\n AND action_id = ${attempt.actionId}\n AND authorization_id = ${attempt.authorizationId}\n LIMIT 2`\n const authorizationRows = yield* Schema.decodeUnknownEffect(\n Schema.Array(GovernedActionAuthorizationRow)\n )(authorizationRawRows).pipe(\n Effect.mapError(() =>\n persistedError(\n input,\n \"governed-action-authorization\",\n attempt.authorizationId,\n \"governed-action-companion-invalid\"\n )\n ),\n captureMalformedGovernedActionRow(authorizationRawRows)\n )\n const authorizationRow = authorizationRows[0]\n if (authorizationRows.length !== 1 || authorizationRow === undefined) {\n if (mode === \"commit\") return yield* inputError(\"illegal-transition\")\n return yield* Effect.fail(\n persistedError(\n input,\n \"governed-action-authorization\",\n attempt.authorizationId,\n \"governed-action-companion-invalid\"\n )\n ).pipe(captureMalformedGovernedActionRow(authorizationRawRows))\n }\n const authorization = yield* decodeGovernedActionAuthorizationRow(authorizationRow).pipe(\n Effect.provideService(Crypto.Crypto, cryptoService),\n captureMalformedGovernedActionRow(authorizationRow)\n )\n const mismatches = governedActionAuthorityMismatches({\n envelope: input.envelope,\n authorization,\n attempt,\n evaluatedAt: attempt.startedAt\n })\n if (mismatches.length === 0) return\n if (mode === \"commit\") return yield* inputError(\"illegal-transition\")\n return yield* Effect.fail(\n persistedError(\n input,\n \"governed-action-authorization\",\n attempt.authorizationId,\n \"governed-action-companion-invalid\"\n )\n ).pipe(captureMalformedGovernedActionRow(authorizationRow))\n })\n\n const commit = Effect.fn(\"GovernedActionWriter.commit\")(function*(input: GovernedActionCommitInput) {\n yield* Schema.decodeUnknownEffect(Schema.toType(GovernedActionCommitInput))(input).pipe(\n Effect.mapError(() => inputError(\"invalid-request\"))\n )\n yield* verifyGovernedActionEnvelope(input.envelope).pipe(\n Effect.provideService(Crypto.Crypto, cryptoService),\n Effect.mapError(() => inputError(\"conflicting-action-identity\"))\n )\n const envelopeJson = yield* encodeJson(\"governed-action.encode-envelope\", EnvelopeJson, input.envelope)\n const commandDigest = yield* digestGovernedActionTransitionCommand(input.command).pipe(\n Effect.provideService(Crypto.Crypto, cryptoService),\n Effect.mapError(() => new PersistenceOperationError({ operation: \"governed-action.digest-command\" }))\n )\n const commandJson = yield* encodeJson(\"governed-action.encode-command\", CommandJson, input.command)\n const causeJson = yield* encodeJson(\"governed-action.encode-cause\", CauseJson, input.cause)\n const occurredAt = yield* encodeTimestamp(\"governed-action.encode-occurred-at\", input.occurredAt)\n const preparedCompanion = yield* prepareCompanion(cryptoService)(input.companion)\n return yield* Effect.gen(function*() {\n // Exact replay must remain the first SQL statement and precede head validation.\n const replayRaw = yield* sql`SELECT\n transition_record.transition_id AS transitionId,\n transition_record.previous_transition_id AS previousTransitionId,\n transition_record.command_id AS commandId,\n transition_record.command_digest AS commandDigest,\n transition_record.transition_digest AS transitionDigest,\n transition_record.transition_json AS transitionJson,\n denial_policy.policy_evaluation_digest AS linkedPolicyEvaluationDigest,\n audit.audit_event_id AS auditEventId, audit.event_kind AS auditEventKind,\n audit.cause_kind AS auditCauseKind, audit.actor_id AS auditActorId,\n audit.session_id AS auditSessionId, audit.job_id AS auditJobId,\n audit.system_component AS auditSystemComponent, audit.causation_id AS auditCausationId,\n audit.correlation_id AS auditCorrelationId, audit.payload_digest AS auditPayloadDigest,\n audit.payload_json AS auditPayloadJson, audit.occurred_at AS auditOccurredAt,\n authorization.workspace_id AS authorizationWorkspaceId,\n authorization.action_id AS authorizationActionId,\n authorization.authorization_id AS authorizationId,\n authorization.session_id AS authorizationSessionId,\n authorization.envelope_digest AS authorizationEnvelopeDigest,\n authorization.authorization_digest AS authorizationDigest,\n authorization.authorization_json AS authorizationJson,\n authorization.authorized_at AS authorizationAuthorizedAt,\n authorization.expires_at AS authorizationExpiresAt,\n evaluation.evaluation_digest AS evaluationDigest,\n evaluation.evaluation_json AS evaluationJson,\n attempt.attempt_digest AS attemptDigest, attempt.attempt_json AS attemptJson,\n (SELECT COUNT(*) FROM (\n SELECT 1 FROM governed_action_policy_evaluations unowned_evaluation\n WHERE unowned_evaluation.workspace_id = transition_record.workspace_id\n AND unowned_evaluation.action_id = transition_record.action_id\n AND NOT EXISTS (\n SELECT 1 FROM governed_action_attempts owning_attempt\n WHERE owning_attempt.workspace_id = unowned_evaluation.workspace_id\n AND owning_attempt.action_id = unowned_evaluation.action_id\n AND owning_attempt.policy_evaluation_digest = unowned_evaluation.evaluation_digest\n )\n AND NOT EXISTS (\n SELECT 1 FROM governed_action_denial_policy_evaluations owning_denial\n WHERE owning_denial.workspace_id = unowned_evaluation.workspace_id\n AND owning_denial.action_id = unowned_evaluation.action_id\n AND owning_denial.policy_evaluation_digest = unowned_evaluation.evaluation_digest\n )\n LIMIT 2\n )) AS unownedEvaluationCount\n FROM governed_action_transitions transition_record\n LEFT JOIN audit_events audit ON audit.workspace_id = transition_record.workspace_id\n AND audit.action_id = transition_record.action_id AND audit.transition_id = transition_record.transition_id\n LEFT JOIN governed_action_authorizations authorization\n ON authorization.workspace_id = transition_record.workspace_id\n AND authorization.action_id = transition_record.action_id\n AND authorization.authorization_id = transition_record.authorization_id\n LEFT JOIN governed_action_attempts attempt ON attempt.workspace_id = transition_record.workspace_id\n AND attempt.action_id = transition_record.action_id AND attempt.attempt_id = transition_record.attempt_id\n LEFT JOIN governed_action_denial_policy_evaluations denial_policy\n ON denial_policy.workspace_id = transition_record.workspace_id\n AND denial_policy.action_id = transition_record.action_id\n AND denial_policy.transition_id = transition_record.transition_id\n LEFT JOIN governed_action_policy_evaluations evaluation\n ON evaluation.workspace_id = transition_record.workspace_id\n AND evaluation.action_id = transition_record.action_id\n AND evaluation.evaluation_digest = COALESCE(\n attempt.policy_evaluation_digest,\n denial_policy.policy_evaluation_digest\n )\n WHERE transition_record.workspace_id = ${input.envelope.workspaceId}\n AND transition_record.action_id = ${input.envelope.actionId}\n AND (transition_record.command_id = ${input.commandId}\n OR transition_record.transition_id = ${input.transitionId})\n LIMIT 2`\n const replayRows = yield* replay.decodeRows(input, replayRaw).pipe(\n captureMalformedGovernedActionRow(replayRaw)\n )\n const replayResult = yield* replay.resolve(\n input,\n commandDigest,\n commandJson,\n causeJson,\n preparedCompanion,\n replayRows\n ).pipe(captureMalformedGovernedActionRow(replayRows[0] ?? replayRaw))\n if (replayResult !== null) {\n yield* verifyDispatchAuthorization(input, preparedCompanion, \"replay\")\n return replayResult\n }\n\n const rootRaw = yield* sql`SELECT\n action.action_id AS actionId, action.plugin_connection_id AS pluginConnectionId,\n action.provider_id AS providerId, action.target_entity_id AS targetEntityId,\n action.idempotency_key AS idempotencyKey, action.envelope_digest AS envelopeDigest,\n action.envelope_json AS envelopeJson, action.state, action.lineage_json AS lineageJson,\n action.lineage_kind AS lineageKind, action.provider_operation_id AS providerOperationId,\n action.reconciliation_key AS reconciliationKey, action.terminal_status AS terminalStatus,\n action.head_transition_id AS headTransitionId, action.head_sequence AS headSequence,\n head.transition_id AS persistedHeadTransitionId, action.updated_at AS updatedAt\n FROM governed_actions action\n LEFT JOIN governed_action_transitions head ON head.workspace_id = action.workspace_id\n AND head.action_id = action.action_id AND head.transition_id = action.head_transition_id\n AND head.sequence = action.head_sequence\n WHERE action.workspace_id = ${input.envelope.workspaceId}\n AND (action.action_id = ${input.envelope.actionId}\n OR (action.plugin_connection_id = ${input.envelope.pluginConnectionId}\n AND action.idempotency_key = ${input.envelope.idempotencyKey}))`\n const rootRows = yield* decodeRootRows(input, rootRaw).pipe(captureMalformedGovernedActionRow(rootRaw))\n if (rootRows.length > 1) return yield* inputError(\"conflicting-action-identity\")\n const root = rootRows[0]\n\n let currentHead: RootHead | null = null\n if (root === undefined) {\n if (input.command._tag !== \"propose\" || input.expectedHeadTransitionId !== null) {\n return yield* inputError(\"conflicting-action-identity\")\n }\n yield* sql`INSERT INTO governed_actions (\n workspace_id, action_id, plugin_connection_id, provider_id, target_entity_id,\n idempotency_key, envelope_digest, envelope_json, state, lineage_json,\n lineage_kind, provider_operation_id, reconciliation_key, terminal_status,\n head_transition_id, head_sequence, created_at, updated_at\n ) VALUES (\n ${input.envelope.workspaceId}, ${input.envelope.actionId}, ${input.envelope.pluginConnectionId},\n ${input.envelope.providerId}, ${input.envelope.targetEntityId}, ${input.envelope.idempotencyKey},\n ${input.envelope.envelopeDigest}, ${envelopeJson}, NULL, NULL, NULL, NULL, NULL, NULL,\n NULL, NULL, ${occurredAt}, ${occurredAt})`\n yield* sql`INSERT INTO governed_action_target_dimensions (\n workspace_id, action_id, action_kind, expected_revision\n ) VALUES (\n ${input.envelope.workspaceId}, ${input.envelope.actionId},\n ${input.envelope.proposal.request.actionKind},\n ${input.envelope.proposal.request.expectedRevision}\n )`\n if (input.envelope.releasePublication !== undefined) {\n yield* sql`INSERT INTO governed_action_release_publications (\n workspace_id, action_id, provider_id, release_id, predecessor_action_id\n ) VALUES (\n ${input.envelope.workspaceId}, ${input.envelope.actionId},\n ${input.envelope.providerId}, ${input.envelope.releasePublication.releaseId},\n ${input.envelope.releasePublication.predecessorPublicationActionId ?? null}\n )`\n if (input.envelope.providerId === \"confluence\") {\n yield* sql`INSERT INTO governed_action_release_publication_slots (\n workspace_id, action_id, provider_id, release_id, predecessor_action_id\n ) VALUES (\n ${input.envelope.workspaceId}, ${input.envelope.actionId},\n ${input.envelope.providerId}, ${input.envelope.releasePublication.releaseId},\n ${input.envelope.releasePublication.predecessorPublicationActionId ?? null}\n )`\n }\n } else {\n yield* sql`INSERT INTO governed_action_entity_targets (\n workspace_id, action_id, plugin_connection_id, provider_id, entity_id\n ) VALUES (\n ${input.envelope.workspaceId}, ${input.envelope.actionId},\n ${input.envelope.pluginConnectionId}, ${input.envelope.providerId},\n ${input.envelope.targetEntityId}\n )`\n }\n } else {\n yield* verifyRootIdentity(input, envelopeJson, root).pipe(captureMalformedGovernedActionRow(root))\n if (input.command._tag === \"propose\") return yield* inputError(\"conflicting-action-identity\")\n currentHead = yield* decodeRootHead(input, root).pipe(captureMalformedGovernedActionRow(root))\n if (currentHead.transitionId !== input.expectedHeadTransitionId) return yield* inputError(\"stale-head\")\n if (DateTime.Order(input.occurredAt, currentHead.updatedAt) < 0) {\n return yield* inputError(\"illegal-transition\")\n }\n }\n\n const nextHead = advanceGovernedActionLifecycle(\n currentHead === null ? null : { state: currentHead.state, lineage: currentHead.lineage },\n input.command\n )\n if (nextHead === null) return yield* inputError(\"illegal-transition\")\n const transition = (yield* makeGovernedActionTransition({\n schemaVersion: 1,\n transitionId: input.transitionId,\n previousTransitionId: currentHead?.transitionId ?? null,\n commandId: input.commandId,\n actionId: input.envelope.actionId,\n workspaceId: input.envelope.workspaceId,\n sequence: (currentHead?.sequence ?? 0) + 1,\n fromState: currentHead?.state ?? null,\n toState: nextHead.state,\n actionEnvelopeDigest: input.envelope.envelopeDigest,\n command: input.command,\n cause: input.cause,\n occurredAt: input.occurredAt,\n causationId: input.causationId,\n correlationId: input.correlationId\n }).pipe(\n Effect.provideService(Crypto.Crypto, cryptoService),\n Effect.mapError(() => inputError(\"illegal-transition\"))\n )).transition\n const transitionJson = yield* encodeJson(\"governed-action.encode-transition\", TransitionJson, transition)\n const transitionDigest = yield* digestGovernedActionTransition(transition).pipe(\n Effect.provideService(Crypto.Crypto, cryptoService),\n Effect.mapError(() => new PersistenceOperationError({ operation: \"governed-action.digest-transition\" }))\n )\n const lineageJson = yield* encodeJson(\"governed-action.encode-lineage\", LineageJson, nextHead.lineage)\n const command = commandColumns(input.command)\n const cause = causeColumns(input.cause)\n const lineage = lineageColumns(nextHead.lineage)\n const denialPolicyEvaluationDigest = preparedCompanion._tag === \"policyDenial\"\n ? preparedCompanion.evaluationDigest\n : null\n\n yield* verifyDispatchAuthorization(input, preparedCompanion, \"commit\")\n yield* insertCompanion(preparedCompanion)\n yield* sql`INSERT INTO governed_action_transitions (\n workspace_id, action_id, transition_id, previous_transition_id, sequence,\n command_id, command_tag, authorization_id, attempt_id, outcome_source_kind,\n command_provider_operation_id, command_reconciliation_key, command_terminal_status,\n command_unknown_kind, command_digest, transition_digest, envelope_digest,\n from_state, to_state, result_lineage_json, result_lineage_kind,\n result_provider_operation_id, result_reconciliation_key, result_terminal_status,\n cause_kind, cause_actor_id, cause_session_id, cause_job_id, cause_system_component,\n causation_id, correlation_id, transition_json, occurred_at\n ) VALUES (\n ${input.envelope.workspaceId}, ${input.envelope.actionId}, ${input.transitionId},\n ${currentHead?.transitionId ?? null}, ${transition.sequence}, ${input.commandId},\n ${input.command._tag}, ${command.authorizationId}, ${command.attemptId},\n ${command.outcomeSourceKind}, ${command.providerOperationId}, ${command.reconciliationKey},\n ${command.terminalStatus}, ${command.unknownKind}, ${transition.commandDigest},\n ${transitionDigest}, ${input.envelope.envelopeDigest}, ${currentHead?.state ?? null},\n ${nextHead.state}, ${lineageJson}, ${lineage.kind}, ${lineage.providerOperationId},\n ${lineage.reconciliationKey}, ${lineage.terminalStatus}, ${cause.kind}, ${cause.actorId},\n ${cause.sessionId}, ${cause.jobId}, ${cause.systemComponent}, ${input.causationId},\n ${input.correlationId}, ${transitionJson}, ${occurredAt})`\n if (denialPolicyEvaluationDigest !== null) {\n yield* sql`INSERT INTO governed_action_denial_policy_evaluations (\n workspace_id, action_id, transition_id, policy_evaluation_digest\n ) VALUES (\n ${input.envelope.workspaceId}, ${input.envelope.actionId}, ${input.transitionId},\n ${denialPolicyEvaluationDigest}\n )`\n }\n yield* sql`INSERT INTO audit_events (\n workspace_id, action_id, transition_id, audit_event_id, event_kind,\n cause_kind, actor_id, session_id, job_id, system_component, causation_id,\n correlation_id, payload_digest, payload_json, occurred_at\n ) VALUES (\n ${input.envelope.workspaceId}, ${input.envelope.actionId}, ${input.transitionId},\n ${input.auditEventId}, ${nextHead.state}, ${cause.kind}, ${cause.actorId},\n ${cause.sessionId}, ${cause.jobId}, ${cause.systemComponent}, ${input.causationId},\n ${input.correlationId}, ${transitionDigest}, ${transitionJson}, ${occurredAt})`\n yield* sql`UPDATE governed_actions SET\n state = ${nextHead.state}, lineage_json = ${lineageJson}, lineage_kind = ${lineage.kind},\n provider_operation_id = ${lineage.providerOperationId},\n reconciliation_key = ${lineage.reconciliationKey}, terminal_status = ${lineage.terminalStatus},\n head_transition_id = ${input.transitionId}, head_sequence = ${transition.sequence},\n updated_at = ${occurredAt}\n WHERE workspace_id = ${input.envelope.workspaceId} AND action_id = ${input.envelope.actionId}\n AND head_sequence IS ${currentHead?.sequence ?? null}\n AND head_transition_id IS ${currentHead?.transitionId ?? null}\n AND state IS ${currentHead?.state ?? null}`\n const changed = yield* readChanges(sql).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"governed-action.read-changes\" }))\n )\n if (changed !== 1) return yield* inputError(\"stale-head\")\n const result: GovernedActionCommitResult = { _tag: \"committed\", transition }\n return result\n })\n })\n\n return { commit }\n})\n\n/**\n * Private governed-action writer that participates in the caller's current transaction.\n *\n * It never opens a transaction. Execution coordination uses this seam to commit a lifecycle\n * transition and its lease atomically; ordinary repository callers use `makeGovernedActionWrite`.\n */\nexport const makeGovernedActionTransactionWrite = makeGovernedActionTransactionWriter\n\nconst makeGovernedActionWriter = Effect.gen(function*() {\n const database = yield* Database\n const writer = yield* makeGovernedActionTransactionWrite\n\n const commit = Effect.fn(\"GovernedActionWriter.commit\")(function*(input: GovernedActionCommitInput) {\n return yield* database.transaction(writer.commit(input)).pipe(\n mapPersistenceOperation(\"governed-action.commit\")\n )\n })\n\n return { commit }\n})\n\n/** Private transactional governed-action writer used by the repository facade. */\nexport const makeGovernedActionWrite = makeGovernedActionWriter\n","import * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport type { Success } from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Schema from \"effect/Schema\"\n\nimport {\n GovernedActionCommitInput,\n GovernedActionIdempotencyReadInput,\n GovernedActionInputError,\n GovernedActionReadInput,\n GovernedActionReleasePublicationReadInput,\n GovernedActionTargetReadInput\n} from \"./governed-action/contract.js\"\nimport { makeGovernedActionTransaction } from \"./governed-action/transaction.js\"\nimport { makeGovernedActionWrite } from \"./governed-action/write.js\"\n\nexport * from \"./governed-action/contract.js\"\n\nconst makeGovernedActionRepository = Effect.gen(function*() {\n const transaction = yield* makeGovernedActionTransaction\n const writer = yield* makeGovernedActionWrite\n\n const commit = Effect.fn(\"GovernedActionRepository.commit\")(function*(input: unknown) {\n const request = yield* Schema.decodeUnknownEffect(Schema.toType(GovernedActionCommitInput))(input).pipe(\n Effect.mapError(() => new GovernedActionInputError({ operation: \"commit\", reason: \"invalid-request\" }))\n )\n return yield* transaction.capture(writer.commit(request))\n })\n\n const read = Effect.fn(\"GovernedActionRepository.read\")(function*(input: unknown) {\n const request = yield* Schema.decodeUnknownEffect(Schema.toType(GovernedActionReadInput))(input).pipe(\n Effect.mapError(() => new GovernedActionInputError({ operation: \"read\", reason: \"invalid-request\" }))\n )\n return yield* transaction.transact(\"governed-action.read\", transaction.read(request))\n })\n\n const readByIdempotencyKey = Effect.fn(\n \"GovernedActionRepository.readByIdempotencyKey\"\n )(function*(input: unknown) {\n const request = yield* Schema.decodeUnknownEffect(\n Schema.toType(GovernedActionIdempotencyReadInput)\n )(input).pipe(\n Effect.mapError(() => new GovernedActionInputError({ operation: \"read\", reason: \"invalid-request\" }))\n )\n return yield* transaction.transact(\n \"governed-action.read-by-idempotency-key\",\n transaction.readByIdempotencyKey(request)\n )\n })\n\n const readLatestTerminalByTarget = Effect.fn(\n \"GovernedActionRepository.readLatestTerminalByTarget\"\n )(function*(input: unknown) {\n const request = yield* Schema.decodeUnknownEffect(\n Schema.toType(GovernedActionTargetReadInput)\n )(input).pipe(\n Effect.mapError(() => new GovernedActionInputError({ operation: \"read\", reason: \"invalid-request\" }))\n )\n return yield* transaction.transact(\n \"governed-action.read-latest-terminal-by-target\",\n transaction.readLatestTerminalByTarget(request)\n )\n })\n\n const readLatestTerminalReleasePublications = Effect.fn(\n \"GovernedActionRepository.readLatestTerminalReleasePublications\"\n )(function*(input: unknown) {\n const request = yield* Schema.decodeUnknownEffect(\n Schema.toType(GovernedActionReleasePublicationReadInput)\n )(input).pipe(\n Effect.mapError(() => new GovernedActionInputError({ operation: \"read\", reason: \"invalid-request\" }))\n )\n return yield* transaction.transact(\n \"governed-action.read-latest-terminal-release-publications\",\n transaction.readLatestTerminalReleasePublications(request)\n )\n })\n\n return {\n commit,\n read,\n readByIdempotencyKey,\n readLatestTerminalByTarget,\n readLatestTerminalReleasePublications\n }\n})\n\n/** Deep server-only repository for governed action authority, lifecycle, and audit. */\nexport interface GovernedActionRepositoryService extends Success<typeof makeGovernedActionRepository> {}\n\n/** Atomic governed-action persistence service. It never exposes provider execution capability. */\nexport class GovernedActionRepository extends Context.Service<\n GovernedActionRepository,\n GovernedActionRepositoryService\n>()(\"@knpkv/control-center/GovernedActionRepository\") {\n /** Layer binding governed-action persistence to database, cryptography, and quarantine. */\n static readonly layer = Layer.effect(GovernedActionRepository, makeGovernedActionRepository)\n}\n","import * as Context from \"effect/Context\"\nimport * as Crypto from \"effect/Crypto\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport type { Success } from \"effect/Effect\"\nimport * as Encoding from \"effect/Encoding\"\nimport * as Layer from \"effect/Layer\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\"\n\nimport { Person, PersonAvatar, PersonSourceIdentity, Role, RoleAssignment } from \"../../../domain/actors.js\"\nimport {\n AgentId,\n EntityId,\n EnvironmentId,\n PersonId,\n ReleaseId,\n RoleAssignmentId,\n WorkspaceId\n} from \"../../../domain/identifiers.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport { Database } from \"../Database.js\"\nimport { PersistedRecordError, PersistenceOperationError, RecordNotFoundError } from \"../errors.js\"\nimport {\n mapAlreadyExists,\n mapPersistenceOperation,\n readChanges,\n resolveCasFailure,\n revisionLookup\n} from \"./internal.js\"\nimport { ContentBlobDigest, PersonRecord, RecordRevision, RoleAssignmentRecord } from \"./models.js\"\nimport { makePersistedRowQuarantine } from \"./persistedRowQuarantine.js\"\nimport { QuarantineRepository } from \"./quarantineRepository.js\"\n\nconst PersonRow = Schema.Struct({\n workspaceId: WorkspaceId,\n personId: PersonId,\n displayName: Person.fields.displayName,\n avatarJson: Schema.String.check(Schema.isNonEmpty()),\n isActive: Schema.Number.check(Schema.isInt(), Schema.isBetween({ minimum: 0, maximum: 1 })),\n revision: RecordRevision,\n createdAt: UtcTimestamp,\n updatedAt: UtcTimestamp\n})\n\nconst PersonIdentityRow = Schema.Struct({\n pluginConnectionId: PersonSourceIdentity.fields.pluginConnectionId,\n providerId: PersonSourceIdentity.fields.providerId,\n vendorPersonId: PersonSourceIdentity.fields.vendorPersonId\n})\n\nconst RoleAssignmentRow = Schema.Struct({\n workspaceId: WorkspaceId,\n assignmentId: RoleAssignmentId,\n actorKind: Schema.Literals([\"human\", \"agent\"]),\n personId: Schema.Union([PersonId, Schema.Null]),\n agentId: Schema.Union([AgentId, Schema.Null]),\n role: Role,\n scopeKind: Schema.Literals([\"workspace\", \"release\", \"environment\", \"entity\"]),\n releaseId: Schema.Union([ReleaseId, Schema.Null]),\n environmentId: Schema.Union([EnvironmentId, Schema.Null]),\n entityId: Schema.Union([EntityId, Schema.Null]),\n lifecycleKind: Schema.Literals([\"active\", \"ended\", \"revoked\"]),\n assignedAt: UtcTimestamp,\n endedAt: Schema.Union([UtcTimestamp, Schema.Null]),\n revokedAt: Schema.Union([UtcTimestamp, Schema.Null]),\n revision: RecordRevision,\n createdAt: UtcTimestamp,\n updatedAt: UtcTimestamp\n})\n\nconst RoleAssignmentIdentity = Schema.Struct({ assignmentId: RoleAssignmentId })\nconst RoleAssignmentOwnership = Schema.Struct({ scopeKind: RoleAssignmentRow.fields.scopeKind })\n\nconst avatarJson = Schema.fromJsonString(PersonAvatar)\nconst encodeAvatar = Schema.encodeEffect(avatarJson)\nconst decodeAvatar = Schema.decodeUnknownResult(avatarJson)\n\nconst decodeActor = (row: typeof RoleAssignmentRow.Type): unknown =>\n row.actorKind === \"human\"\n ? { _tag: \"human\", personId: row.personId }\n : { _tag: \"agent\", agentId: row.agentId }\n\nconst decodeScope = (row: typeof RoleAssignmentRow.Type): unknown => {\n switch (row.scopeKind) {\n case \"workspace\":\n return { _tag: \"workspace\", workspaceId: row.workspaceId }\n case \"release\":\n return { _tag: \"release\", workspaceId: row.workspaceId, releaseId: row.releaseId }\n case \"environment\":\n return {\n _tag: \"environment\",\n workspaceId: row.workspaceId,\n releaseId: row.releaseId,\n environmentId: row.environmentId\n }\n case \"entity\":\n return { _tag: \"entity\", workspaceId: row.workspaceId, entityId: row.entityId }\n }\n}\n\nconst decodeLifecycle = (row: typeof RoleAssignmentRow.Type): unknown => {\n switch (row.lifecycleKind) {\n case \"active\":\n return { _tag: \"active\", assignedAt: row.assignedAt }\n case \"ended\":\n return { _tag: \"ended\", assignedAt: row.assignedAt, endedAt: row.endedAt }\n case \"revoked\":\n return { _tag: \"revoked\", assignedAt: row.assignedAt, revokedAt: row.revokedAt }\n }\n}\n\nconst isReleaseOwnedScope = (scopeKind: typeof RoleAssignmentRow.Type[\"scopeKind\"]): boolean =>\n scopeKind === \"release\" || scopeKind === \"environment\"\n\nconst releaseOwnedRoleError = (operation: \"create\" | \"update\") =>\n new PersistenceOperationError({ operation: `people.release-owned-role.${operation}` })\n\nconst decodeRoleAssignmentRecord = Effect.fn(\"PeopleRepository.decodeRoleAssignment\")(function*(\n row: typeof RoleAssignmentRow.Type\n) {\n const assignment = yield* Schema.decodeUnknownEffect(Schema.toType(RoleAssignment))({\n assignmentId: row.assignmentId,\n actor: decodeActor(row),\n role: row.role,\n scope: decodeScope(row),\n lifecycle: decodeLifecycle(row)\n })\n return yield* Schema.decodeUnknownEffect(Schema.toType(RoleAssignmentRecord))({\n workspaceId: row.workspaceId,\n assignment,\n revision: row.revision,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt\n })\n})\n\nconst makePeopleRepository = Effect.gen(function*() {\n const cryptoService = yield* Crypto.Crypto\n const database = yield* Database\n const quarantine = yield* QuarantineRepository\n const quarantineRow = makePersistedRowQuarantine(cryptoService, quarantine)\n const sql = database.sql\n\n const digestPersistedText = Effect.fn(\"PeopleRepository.digestPersistedText\")(function*(value: string) {\n const bytes = yield* Effect.fromResult(\n Encoding.decodeBase64(Encoding.encodeBase64(value))\n ).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"people.avatar-encode\" }))\n )\n const digest = yield* cryptoService.digest(\"SHA-256\", bytes).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"people.avatar-digest\" }))\n )\n return ContentBlobDigest.make(Encoding.encodeHex(digest))\n })\n\n const decodePersistedAvatar = Effect.fn(\"PeopleRepository.decodePersistedAvatar\")(function*(\n workspaceId: WorkspaceId,\n personId: PersonId,\n value: string,\n observedAt: UtcTimestamp\n ) {\n const decoded = decodeAvatar(value)\n if (decoded._tag === \"Success\") return decoded.success\n\n const payloadDigest = yield* digestPersistedText(value)\n yield* quarantine.recordMalformed(workspaceId, {\n recordKind: \"person-avatar\",\n recordKey: personId,\n schemaVersion: 1,\n payloadDigest,\n diagnosticCode: \"schema-decode-failed\",\n diagnosticSummary: \"Stored person avatar failed schema validation.\",\n observedAt\n })\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"person-avatar\",\n recordKey: personId,\n diagnosticCode: \"schema-decode-failed\"\n })\n })\n\n const findPersonRows = (\n { personId, workspaceId }: { readonly personId: PersonId; readonly workspaceId: WorkspaceId }\n ) =>\n sql<Record<string, unknown>>`SELECT\n workspace_id AS workspaceId,\n person_id AS personId,\n display_name AS displayName,\n avatar_json AS avatarJson,\n is_active AS isActive,\n revision,\n created_at AS createdAt,\n updated_at AS updatedAt\n FROM persons\n WHERE workspace_id = ${workspaceId}\n AND person_id = ${personId}`\n\n const findIdentityRows = (\n { personId, workspaceId }: { readonly personId: PersonId; readonly workspaceId: WorkspaceId }\n ) =>\n sql<Record<string, unknown>>`SELECT\n plugin_connection_id AS pluginConnectionId,\n provider_id AS providerId,\n vendor_person_id AS vendorPersonId\n FROM person_identities\n WHERE workspace_id = ${workspaceId}\n AND person_id = ${personId}\n ORDER BY provider_id, plugin_connection_id, vendor_person_id`\n\n const quarantineMalformedPerson = Effect.fn(\"PeopleRepository.quarantineMalformedPerson\")(function*(\n workspaceId: WorkspaceId,\n personId: PersonId,\n row: unknown\n ) {\n const observedAt = yield* DateTime.now\n yield* quarantineRow({\n workspaceId,\n recordKind: \"person\",\n recordKey: personId,\n diagnosticCode: \"person-schema-invalid\",\n diagnosticSummary: \"Stored person record failed schema validation.\",\n observedAt,\n row\n })\n })\n\n const getPerson = Effect.fn(\"PeopleRepository.getPerson\")(function*(\n workspaceId: WorkspaceId,\n personId: PersonId\n ) {\n const rows = yield* findPersonRows({ workspaceId, personId }).pipe(\n mapPersistenceOperation(\"people.get-person\")\n )\n if (rows.length === 0) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"person\",\n recordKey: personId\n })\n }\n const decodedRow = Schema.decodeUnknownResult(PersonRow)(rows[0])\n if (Result.isFailure(decodedRow)) {\n yield* quarantineMalformedPerson(workspaceId, personId, rows[0])\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"person\",\n recordKey: personId,\n diagnosticCode: \"person-schema-invalid\"\n })\n }\n const identityRows = yield* findIdentityRows({ workspaceId, personId }).pipe(\n mapPersistenceOperation(\"people.get-person-identities\")\n )\n const identities: Array<typeof PersonIdentityRow.Type> = []\n for (const identityRow of identityRows) {\n const decodedIdentity = Schema.decodeUnknownResult(PersonIdentityRow)(identityRow)\n if (Result.isSuccess(decodedIdentity)) {\n identities.push(decodedIdentity.success)\n } else {\n const observedAt = yield* DateTime.now\n yield* quarantineRow({\n workspaceId,\n recordKind: \"person-identity\",\n recordKey: personId,\n diagnosticCode: \"person-identity-schema-invalid\",\n diagnosticSummary: \"Stored person identity failed schema validation.\",\n observedAt,\n row: identityRow\n })\n }\n }\n const avatar = yield* decodePersistedAvatar(\n workspaceId,\n personId,\n decodedRow.success.avatarJson,\n decodedRow.success.updatedAt\n )\n const decodedPerson = Schema.decodeUnknownResult(Schema.toType(Person))({\n personId,\n displayName: decodedRow.success.displayName,\n avatar,\n isActive: decodedRow.success.isActive === 1,\n sourceIdentities: identities\n })\n if (Result.isFailure(decodedPerson)) {\n yield* quarantineMalformedPerson(workspaceId, personId, {\n person: rows[0],\n identities: identityRows\n })\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"person\",\n recordKey: personId,\n diagnosticCode: \"person-schema-invalid\"\n })\n }\n return yield* Schema.decodeUnknownEffect(Schema.toType(PersonRecord))({\n workspaceId,\n person: decodedPerson.success,\n revision: decodedRow.success.revision,\n createdAt: decodedRow.success.createdAt,\n updatedAt: decodedRow.success.updatedAt\n })\n })\n\n const findPersonBySourceIdentity = Effect.fn(\"PeopleRepository.findPersonBySourceIdentity\")(function*(\n workspaceId: WorkspaceId,\n identity: PersonSourceIdentity\n ) {\n const rows = yield* sql<Record<string, unknown>>`SELECT person_id AS personId\n FROM person_identities\n WHERE workspace_id = ${workspaceId}\n AND plugin_connection_id = ${identity.pluginConnectionId}\n AND provider_id = ${identity.providerId}\n AND vendor_person_id = ${identity.vendorPersonId}`.pipe(\n mapPersistenceOperation(\"people.find-person-by-source-identity\")\n )\n if (rows.length === 0) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"person-identity\",\n recordKey: identity.pluginConnectionId\n })\n }\n const decoded = Schema.decodeUnknownResult(Schema.Struct({ personId: PersonId }))(rows[0])\n if (Result.isFailure(decoded)) {\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"person-identity\",\n recordKey: identity.pluginConnectionId,\n diagnosticCode: \"person-identity-schema-invalid\"\n })\n }\n return yield* getPerson(workspaceId, decoded.success.personId)\n })\n\n const insertPerson = SqlSchema.void({\n Request: Schema.Struct({\n workspaceId: WorkspaceId,\n person: Person,\n avatarJson: Schema.String,\n createdAt: UtcTimestamp\n }),\n execute: ({ avatarJson, createdAt, person, workspaceId }) =>\n sql`INSERT INTO persons (\n workspace_id, person_id, display_name, avatar_json, is_active,\n revision, created_at, updated_at\n ) VALUES (\n ${workspaceId}, ${person.personId}, ${person.displayName}, ${avatarJson},\n ${person.isActive ? 1 : 0}, 1, ${createdAt}, ${createdAt}\n )`\n })\n\n const insertIdentity = SqlSchema.void({\n Request: Schema.Struct({\n workspaceId: WorkspaceId,\n personId: PersonId,\n identity: PersonSourceIdentity,\n createdAt: UtcTimestamp\n }),\n execute: ({ createdAt, identity, personId, workspaceId }) =>\n sql`INSERT INTO person_identities (\n workspace_id, person_id, plugin_connection_id, provider_id,\n vendor_person_id, created_at\n ) VALUES (\n ${workspaceId}, ${personId}, ${identity.pluginConnectionId}, ${identity.providerId},\n ${identity.vendorPersonId}, ${createdAt}\n )`\n })\n\n const replaceIdentities = Effect.fn(\"PeopleRepository.replaceIdentities\")(function*(\n workspaceId: WorkspaceId,\n person: Person,\n createdAt: UtcTimestamp\n ) {\n yield* sql`DELETE FROM person_identities\n WHERE workspace_id = ${workspaceId}\n AND person_id = ${person.personId}`\n yield* Effect.forEach(\n person.sourceIdentities,\n (identity) => insertIdentity({ workspaceId, personId: person.personId, identity, createdAt }),\n { discard: true }\n )\n })\n\n const updatePerson = SqlSchema.void({\n Request: Schema.Struct({\n workspaceId: WorkspaceId,\n person: Person,\n avatarJson: Schema.String,\n expectedRevision: RecordRevision,\n updatedAt: UtcTimestamp\n }),\n execute: ({ avatarJson, expectedRevision, person, updatedAt, workspaceId }) =>\n sql`UPDATE persons\n SET display_name = ${person.displayName},\n avatar_json = ${avatarJson},\n is_active = ${person.isActive ? 1 : 0},\n revision = revision + 1,\n updated_at = ${updatedAt}\n WHERE workspace_id = ${workspaceId}\n AND person_id = ${person.personId}\n AND revision = ${expectedRevision}`\n })\n\n const assignmentColumns = sql`SELECT\n workspace_id AS workspaceId,\n assignment_id AS assignmentId,\n actor_kind AS actorKind,\n person_id AS personId,\n agent_id AS agentId,\n role,\n scope_kind AS scopeKind,\n release_id AS releaseId,\n environment_id AS environmentId,\n entity_id AS entityId,\n lifecycle_kind AS lifecycleKind,\n assigned_at AS assignedAt,\n ended_at AS endedAt,\n revoked_at AS revokedAt,\n revision,\n created_at AS createdAt,\n updated_at AS updatedAt\n FROM role_assignments`\n\n const findAssignmentRows = (\n { assignmentId, workspaceId }: {\n readonly assignmentId: RoleAssignmentId\n readonly workspaceId: WorkspaceId\n }\n ) =>\n sql<Record<string, unknown>>`${assignmentColumns}\n WHERE workspace_id = ${workspaceId}\n AND assignment_id = ${assignmentId}`\n\n const listAssignmentRows = (workspaceId: WorkspaceId) =>\n sql<Record<string, unknown>>`${assignmentColumns}\n WHERE workspace_id = ${workspaceId}\n ORDER BY updated_at DESC, assignment_id`\n\n const quarantineMalformedAssignment = Effect.fn(\n \"PeopleRepository.quarantineMalformedAssignment\"\n )(function*(workspaceId: WorkspaceId, row: unknown, fallbackKey: RoleAssignmentId | WorkspaceId) {\n const identity = Schema.decodeUnknownResult(RoleAssignmentIdentity)(row)\n const observedAt = yield* DateTime.now\n yield* quarantineRow({\n workspaceId,\n recordKind: \"role-assignment\",\n recordKey: Result.isSuccess(identity) ? identity.success.assignmentId : fallbackKey,\n diagnosticCode: \"role-assignment-schema-invalid\",\n diagnosticSummary: \"Stored role assignment failed schema validation.\",\n observedAt,\n row\n })\n })\n\n const assignmentValues = (assignment: RoleAssignment | typeof RoleAssignment.Encoded) => ({\n actorKind: assignment.actor._tag,\n personId: assignment.actor._tag === \"human\" ? assignment.actor.personId : null,\n agentId: assignment.actor._tag === \"agent\" ? assignment.actor.agentId : null,\n scopeKind: assignment.scope._tag,\n releaseId: assignment.scope._tag === \"release\" || assignment.scope._tag === \"environment\"\n ? assignment.scope.releaseId\n : null,\n environmentId: assignment.scope._tag === \"environment\" ? assignment.scope.environmentId : null,\n entityId: assignment.scope._tag === \"entity\" ? assignment.scope.entityId : null,\n lifecycleKind: assignment.lifecycle._tag,\n assignedAt: assignment.lifecycle.assignedAt,\n endedAt: assignment.lifecycle._tag === \"ended\" ? assignment.lifecycle.endedAt : null,\n revokedAt: assignment.lifecycle._tag === \"revoked\" ? assignment.lifecycle.revokedAt : null\n })\n\n const AssignmentWriteRequest = Schema.Struct({\n workspaceId: WorkspaceId,\n assignment: RoleAssignment,\n revision: RecordRevision,\n timestamp: UtcTimestamp\n })\n\n const insertAssignment = SqlSchema.void({\n Request: AssignmentWriteRequest,\n execute: ({ assignment, timestamp, workspaceId }) => {\n const values = assignmentValues(assignment)\n return sql`INSERT INTO role_assignments (\n workspace_id, assignment_id, actor_kind, person_id, agent_id, role,\n scope_kind, release_id, environment_id, entity_id, lifecycle_kind,\n assigned_at, ended_at, revoked_at, revision, created_at, updated_at\n ) VALUES (\n ${workspaceId}, ${assignment.assignmentId}, ${values.actorKind}, ${values.personId},\n ${values.agentId}, ${assignment.role}, ${values.scopeKind}, ${values.releaseId},\n ${values.environmentId}, ${values.entityId}, ${values.lifecycleKind},\n ${values.assignedAt}, ${values.endedAt}, ${values.revokedAt}, 1, ${timestamp}, ${timestamp}\n )`\n }\n })\n\n const updateAssignment = SqlSchema.void({\n Request: AssignmentWriteRequest,\n execute: ({ assignment, revision, timestamp, workspaceId }) => {\n const values = assignmentValues(assignment)\n return sql`UPDATE role_assignments SET\n actor_kind = ${values.actorKind}, person_id = ${values.personId}, agent_id = ${values.agentId},\n role = ${assignment.role}, scope_kind = ${values.scopeKind}, release_id = ${values.releaseId},\n environment_id = ${values.environmentId}, entity_id = ${values.entityId},\n lifecycle_kind = ${values.lifecycleKind}, assigned_at = ${values.assignedAt},\n ended_at = ${values.endedAt}, revoked_at = ${values.revokedAt},\n revision = revision + 1, updated_at = ${timestamp}\n WHERE workspace_id = ${workspaceId}\n AND assignment_id = ${assignment.assignmentId}\n AND revision = ${revision}\n AND scope_kind IN ('workspace', 'entity')`\n }\n })\n\n const getRoleAssignment = Effect.fn(\"PeopleRepository.getRoleAssignment\")(function*(\n workspaceId: WorkspaceId,\n assignmentId: RoleAssignmentId\n ) {\n const rows = yield* findAssignmentRows({ workspaceId, assignmentId }).pipe(\n mapPersistenceOperation(\"people.get-role\")\n )\n if (rows.length === 0) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"role-assignment\",\n recordKey: assignmentId\n })\n }\n const decoded = Schema.decodeUnknownResult(RoleAssignmentRow)(rows[0])\n if (Result.isSuccess(decoded)) {\n const record = yield* decodeRoleAssignmentRecord(decoded.success).pipe(Effect.result)\n if (Result.isSuccess(record)) return record.success\n }\n yield* quarantineMalformedAssignment(workspaceId, rows[0], assignmentId)\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"role-assignment\",\n recordKey: assignmentId,\n diagnosticCode: \"role-assignment-schema-invalid\"\n })\n })\n\n return {\n createPerson: Effect.fn(\"PeopleRepository.createPerson\")(function*(\n workspaceId: WorkspaceId,\n person: Person,\n createdAt: UtcTimestamp\n ) {\n const encodedAvatar = yield* encodeAvatar(person.avatar)\n yield* database.transaction(\n Effect.gen(function*() {\n yield* insertPerson({ workspaceId, person, avatarJson: encodedAvatar, createdAt })\n yield* replaceIdentities(workspaceId, person, createdAt)\n }).pipe(\n mapAlreadyExists({ workspaceId, recordKind: \"person\", recordKey: person.personId }),\n mapPersistenceOperation(\"people.create-person\")\n )\n )\n return yield* getPerson(workspaceId, person.personId)\n }),\n getPerson,\n findPersonBySourceIdentity,\n updatePerson: Effect.fn(\"PeopleRepository.updatePerson\")(function*(\n workspaceId: WorkspaceId,\n person: Person,\n expectedRevision: RecordRevision,\n updatedAt: UtcTimestamp\n ) {\n const encodedAvatar = yield* encodeAvatar(person.avatar)\n yield* database.transaction(\n Effect.gen(function*() {\n yield* updatePerson({ workspaceId, person, avatarJson: encodedAvatar, expectedRevision, updatedAt })\n const changes = yield* readChanges(sql)\n if (changes === 0) {\n return yield* resolveCasFailure({\n workspaceId,\n recordKind: \"person\",\n recordKey: person.personId,\n expectedRevision,\n findActualRevision: revisionLookup(() =>\n sql`SELECT revision FROM persons\n WHERE workspace_id = ${workspaceId} AND person_id = ${person.personId}`\n )\n })\n }\n yield* replaceIdentities(workspaceId, person, updatedAt)\n }).pipe(mapPersistenceOperation(\"people.update-person\"))\n )\n return yield* getPerson(workspaceId, person.personId)\n }),\n createRoleAssignment: Effect.fn(\"PeopleRepository.createRoleAssignment\")(function*(\n workspaceId: WorkspaceId,\n assignment: RoleAssignment,\n createdAt: UtcTimestamp\n ) {\n if (isReleaseOwnedScope(assignment.scope._tag)) {\n return yield* releaseOwnedRoleError(\"create\")\n }\n if (assignment.scope.workspaceId !== workspaceId) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"role-assignment\",\n recordKey: assignment.assignmentId\n })\n }\n yield* insertAssignment({\n workspaceId,\n assignment,\n revision: RecordRevision.make(1),\n timestamp: createdAt\n }).pipe(\n mapAlreadyExists({\n workspaceId,\n recordKind: \"role-assignment\",\n recordKey: assignment.assignmentId\n }),\n mapPersistenceOperation(\"people.create-role\")\n )\n return yield* getRoleAssignment(workspaceId, assignment.assignmentId)\n }),\n getRoleAssignment,\n listRoleAssignments: Effect.fn(\"PeopleRepository.listRoleAssignments\")(function*(\n workspaceId: WorkspaceId\n ) {\n const rows = yield* listAssignmentRows(workspaceId).pipe(\n mapPersistenceOperation(\"people.list-roles\")\n )\n const assignments: Array<RoleAssignmentRecord> = []\n for (const row of rows) {\n const decoded = Schema.decodeUnknownResult(RoleAssignmentRow)(row)\n if (Result.isSuccess(decoded)) {\n const record = yield* decodeRoleAssignmentRecord(decoded.success).pipe(Effect.result)\n if (Result.isSuccess(record)) {\n assignments.push(record.success)\n continue\n }\n }\n yield* quarantineMalformedAssignment(workspaceId, row, workspaceId)\n }\n return assignments\n }),\n updateRoleAssignment: Effect.fn(\"PeopleRepository.updateRoleAssignment\")(function*(\n workspaceId: WorkspaceId,\n assignment: RoleAssignment,\n expectedRevision: RecordRevision,\n updatedAt: UtcTimestamp\n ) {\n if (isReleaseOwnedScope(assignment.scope._tag)) {\n return yield* releaseOwnedRoleError(\"update\")\n }\n if (assignment.scope.workspaceId !== workspaceId) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"role-assignment\",\n recordKey: assignment.assignmentId\n })\n }\n yield* database.transaction(\n Effect.gen(function*() {\n yield* updateAssignment({ workspaceId, assignment, revision: expectedRevision, timestamp: updatedAt })\n const changes = yield* readChanges(sql)\n if (changes === 0) {\n const existing = yield* sql<Record<string, unknown>>`SELECT scope_kind AS scopeKind\n FROM role_assignments\n WHERE workspace_id = ${workspaceId}\n AND assignment_id = ${assignment.assignmentId}`\n const ownership = Schema.decodeUnknownResult(RoleAssignmentOwnership)(existing[0])\n if (Result.isSuccess(ownership) && isReleaseOwnedScope(ownership.success.scopeKind)) {\n return yield* releaseOwnedRoleError(\"update\")\n }\n return yield* resolveCasFailure({\n workspaceId,\n recordKind: \"role-assignment\",\n recordKey: assignment.assignmentId,\n expectedRevision,\n findActualRevision: revisionLookup(() =>\n sql`SELECT revision FROM role_assignments\n WHERE workspace_id = ${workspaceId}\n AND assignment_id = ${assignment.assignmentId}`\n )\n })\n }\n }).pipe(mapPersistenceOperation(\"people.update-role\"))\n )\n return yield* getRoleAssignment(workspaceId, assignment.assignmentId)\n })\n }\n})\n\n/** Workspace-scoped canonical people, identities, and collaborator roles. */\nexport interface PeopleRepositoryService extends Success<typeof makePeopleRepository> {}\n\n/** Effect service for human-centric collaborator persistence. */\nexport class PeopleRepository extends Context.Service<PeopleRepository, PeopleRepositoryService>()(\n \"@knpkv/control-center/PeopleRepository\"\n) {\n /** Layer that binds SQL queries to the shared database at construction. */\n static readonly layer = Layer.effect(PeopleRepository, makePeopleRepository)\n}\n","import * as Schema from \"effect/Schema\"\n\nimport { PluginConnectionId, WorkspaceId } from \"../../../domain/identifiers.js\"\nimport { hasMaximumPluginJsonBytes } from \"../../../domain/plugins/bounds.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport { SecretRef } from \"../../secrets/SecretRef.js\"\nimport { ContentBlobDigest } from \"./models.js\"\n\n/** Stable field key from a negotiated plugin descriptor. */\nexport const StoredPluginConfigurationKey = Schema.String.check(\n Schema.isTrimmed(),\n Schema.isNonEmpty(),\n Schema.isMaxLength(100)\n).pipe(Schema.brand(\"StoredPluginConfigurationKey\"))\n\nexport type StoredPluginConfigurationKey = typeof StoredPluginConfigurationKey.Type\n\nconst common = { key: StoredPluginConfigurationKey }\nconst boundedValue = Schema.String.check(Schema.isTrimmed(), Schema.isMaxLength(4_096))\n\n/** Durable non-secret value or opaque secret reference for one plugin field. */\nexport const StoredPluginConfigurationValue = Schema.Union([\n Schema.TaggedStruct(\"text\", { ...common, value: boundedValue }),\n Schema.TaggedStruct(\"url\", { ...common, value: boundedValue }),\n Schema.TaggedStruct(\"boolean\", { ...common, value: Schema.Boolean }),\n Schema.TaggedStruct(\"integer\", { ...common, value: Schema.Int }),\n Schema.TaggedStruct(\"select\", { ...common, value: boundedValue }),\n Schema.TaggedStruct(\"secret-reference\", { ...common, ref: SecretRef })\n]).pipe(Schema.toTaggedUnion(\"_tag\"))\n\nexport type StoredPluginConfigurationValue = typeof StoredPluginConfigurationValue.Type\n\n/** Canonical ordered plugin configuration persisted as bounded JSON. */\nexport const StoredPluginConfiguration = Schema.Array(StoredPluginConfigurationValue).check(\n Schema.makeFilter((values) => values.length <= 100, {\n expected: \"at most 100 plugin configuration values\"\n }),\n Schema.makeFilter(\n (values) => new Set(values.map(({ key }) => key)).size === values.length,\n { expected: \"unique plugin configuration keys\" }\n ),\n Schema.makeFilter(\n (values) =>\n values.slice(1).every((value, index) => {\n const previous = values[index]\n return previous !== undefined && previous.key < value.key\n }),\n { expected: \"plugin configuration values ordered by key\" }\n ),\n hasMaximumPluginJsonBytes(64 * 1024)\n)\n\nexport type StoredPluginConfiguration = typeof StoredPluginConfiguration.Type\n\n/** Revisioned secret-safe configuration record. */\nexport const PluginConfigurationRecord = Schema.Struct({\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n revision: Schema.Int.check(Schema.isGreaterThan(0)),\n values: StoredPluginConfiguration,\n configurationDigest: ContentBlobDigest,\n createdAt: UtcTimestamp,\n updatedAt: UtcTimestamp\n})\n\nexport type PluginConfigurationRecord = typeof PluginConfigurationRecord.Type\n","import * as Context from \"effect/Context\"\nimport * as Crypto from \"effect/Crypto\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport type { Success } from \"effect/Effect\"\nimport * as Encoding from \"effect/Encoding\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\n\nimport type { PluginConnectionId, WorkspaceId } from \"../../../domain/identifiers.js\"\nimport { UtcTimestamp, type UtcTimestamp as UtcTimestampType } from \"../../../domain/utcTimestamp.js\"\nimport { SecretRef } from \"../../secrets/SecretRef.js\"\nimport { Database } from \"../Database.js\"\nimport {\n PersistedRecordError,\n PersistenceOperationError,\n RevisionConflictError,\n SecretReferenceScopeConflictError\n} from \"../errors.js\"\nimport { mapPersistenceOperation, readChanges, revisionLookup } from \"./internal.js\"\nimport { ContentBlobDigest } from \"./models.js\"\nimport {\n PluginConfigurationRecord,\n StoredPluginConfiguration,\n type StoredPluginConfiguration as StoredPluginConfigurationType\n} from \"./pluginConfigurationModels.js\"\nimport { QuarantineRepository } from \"./quarantineRepository.js\"\n\nconst PluginConfigurationRow = Schema.Struct({\n workspaceId: Schema.String,\n pluginConnectionId: Schema.String,\n revision: Schema.Int.check(Schema.isGreaterThan(0)),\n configurationJson: Schema.String.check(Schema.isNonEmpty(), Schema.isMaxLength(65_536)),\n configurationDigest: ContentBlobDigest,\n createdAt: Schema.String,\n updatedAt: Schema.String\n})\n\nconst ConfigurationJson = Schema.fromJsonString(StoredPluginConfiguration)\nconst encodeConfiguration = Schema.encodeEffect(ConfigurationJson)\nconst decodeConfiguration = Schema.decodeUnknownResult(ConfigurationJson)\nconst encodeTimestamp = Schema.encodeSync(UtcTimestamp)\nconst PendingSecretCleanupRow = Schema.Struct({\n secretRef: SecretRef\n})\n\nconst makePluginConfigurationRepository = Effect.gen(function*() {\n const cryptoService = yield* Crypto.Crypto\n const database = yield* Database\n const quarantine = yield* QuarantineRepository\n const sql = database.sql\n\n const digestText = Effect.fn(\"PluginConfigurationRepository.digestText\")(function*(value: string) {\n const bytes = yield* Effect.fromResult(Encoding.decodeBase64(Encoding.encodeBase64(value))).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"plugin-configuration.digest\" }))\n )\n const digest = yield* cryptoService.digest(\"SHA-256\", bytes).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"plugin-configuration.digest\" }))\n )\n return ContentBlobDigest.make(Encoding.encodeHex(digest))\n })\n\n const readRows = (workspaceId: WorkspaceId, pluginConnectionId: PluginConnectionId) =>\n sql<Record<string, unknown>>`SELECT\n workspace_id AS workspaceId,\n plugin_connection_id AS pluginConnectionId,\n revision,\n configuration_json AS configurationJson,\n configuration_digest AS configurationDigest,\n created_at AS createdAt,\n updated_at AS updatedAt\n FROM plugin_configurations\n WHERE workspace_id = ${workspaceId}\n AND plugin_connection_id = ${pluginConnectionId}`\n\n const quarantineMalformed = Effect.fn(\"PluginConfigurationRepository.quarantineMalformed\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n row: unknown\n ) {\n const serialized = yield* Effect.try({\n try: () => JSON.stringify(row),\n catch: () => \"<unserializable>\"\n })\n yield* quarantine.recordMalformed(workspaceId, {\n recordKind: \"plugin-configuration\",\n recordKey: pluginConnectionId,\n schemaVersion: 1,\n payloadDigest: yield* digestText(serialized),\n diagnosticCode: \"plugin-configuration-schema-invalid\",\n diagnosticSummary: \"Stored plugin configuration failed schema validation.\",\n observedAt: yield* DateTime.now\n })\n })\n\n const get = Effect.fn(\"PluginConfigurationRepository.get\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId\n ) {\n const rows = yield* readRows(workspaceId, pluginConnectionId).pipe(\n mapPersistenceOperation(\"plugin-configuration.get\")\n )\n if (rows.length === 0) return Option.none<typeof PluginConfigurationRecord.Type>()\n\n const decodedRow = Schema.decodeUnknownResult(PluginConfigurationRow)(rows[0])\n if (Result.isFailure(decodedRow)) {\n yield* quarantineMalformed(workspaceId, pluginConnectionId, rows[0])\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"plugin-configuration\",\n recordKey: pluginConnectionId,\n diagnosticCode: \"plugin-configuration-schema-invalid\"\n })\n }\n const values = decodeConfiguration(decodedRow.success.configurationJson)\n const actualDigest = yield* digestText(decodedRow.success.configurationJson)\n if (Result.isFailure(values)) {\n yield* quarantineMalformed(workspaceId, pluginConnectionId, rows[0])\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"plugin-configuration\",\n recordKey: pluginConnectionId,\n diagnosticCode: \"plugin-configuration-schema-invalid\"\n })\n }\n const record = Schema.decodeUnknownResult(PluginConfigurationRecord)({\n ...decodedRow.success,\n workspaceId,\n pluginConnectionId,\n values: values.success\n })\n if (Result.isFailure(record) || actualDigest !== decodedRow.success.configurationDigest) {\n yield* quarantineMalformed(workspaceId, pluginConnectionId, rows[0])\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"plugin-configuration\",\n recordKey: pluginConnectionId,\n diagnosticCode: \"plugin-configuration-schema-invalid\"\n })\n }\n return Option.some(record.success)\n })\n\n const update = Effect.fn(\"PluginConfigurationRepository.update\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n values: StoredPluginConfigurationType,\n expectedRevision: number,\n updatedAt: UtcTimestampType\n ) {\n const decodedValues = yield* Schema.decodeUnknownEffect(StoredPluginConfiguration)(values)\n const configurationJson = yield* encodeConfiguration(decodedValues).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"plugin-configuration.encode\" }))\n )\n const configurationDigest = yield* digestText(configurationJson)\n const encodedUpdatedAt = encodeTimestamp(updatedAt)\n\n yield* database.transaction(\n Effect.gen(function*() {\n for (const value of decodedValues) {\n if (value._tag !== \"secret-reference\") continue\n yield* sql`INSERT INTO plugin_secret_bindings (\n secret_ref, workspace_id, plugin_connection_id, field_key\n ) VALUES (\n ${value.ref}, ${workspaceId}, ${pluginConnectionId}, ${value.key}\n ) ON CONFLICT(secret_ref) DO NOTHING`.pipe(\n mapPersistenceOperation(\"plugin-configuration.bind-secret\")\n )\n const exactBinding = yield* sql<{ readonly bound: number }>`SELECT 1 AS bound\n FROM plugin_secret_bindings\n WHERE secret_ref = ${value.ref}\n AND workspace_id = ${workspaceId}\n AND plugin_connection_id = ${pluginConnectionId}\n AND field_key = ${value.key}`.pipe(\n mapPersistenceOperation(\"plugin-configuration.verify-secret-binding\")\n )\n if (exactBinding.length !== 1) return yield* new SecretReferenceScopeConflictError()\n }\n if (expectedRevision === 0) {\n yield* sql`INSERT INTO plugin_configurations (\n workspace_id, plugin_connection_id, revision, configuration_json,\n configuration_digest, created_at, updated_at\n ) VALUES (\n ${workspaceId}, ${pluginConnectionId}, 1, ${configurationJson},\n ${configurationDigest}, ${encodedUpdatedAt}, ${encodedUpdatedAt}\n ) ON CONFLICT(workspace_id, plugin_connection_id) DO NOTHING`.pipe(\n mapPersistenceOperation(\"plugin-configuration.insert\")\n )\n } else {\n yield* sql`UPDATE plugin_configurations\n SET revision = revision + 1,\n configuration_json = ${configurationJson},\n configuration_digest = ${configurationDigest},\n updated_at = ${encodedUpdatedAt}\n WHERE workspace_id = ${workspaceId}\n AND plugin_connection_id = ${pluginConnectionId}\n AND revision = ${expectedRevision}`.pipe(\n mapPersistenceOperation(\"plugin-configuration.cas-update\")\n )\n }\n const changes = yield* readChanges(sql)\n if (changes !== 0) return\n const actual = yield* revisionLookup(() =>\n sql`SELECT revision\n FROM plugin_configurations\n WHERE workspace_id = ${workspaceId}\n AND plugin_connection_id = ${pluginConnectionId}`\n )\n return yield* new RevisionConflictError({\n workspaceId,\n recordKind: \"plugin-configuration\",\n recordKey: pluginConnectionId,\n expectedRevision,\n actualRevision: Option.isSome(actual) ? actual.value.revision : null\n })\n }).pipe(mapPersistenceOperation(\"plugin-configuration.update\"))\n )\n\n const persisted = yield* get(workspaceId, pluginConnectionId)\n if (Option.isNone(persisted)) {\n return yield* new PersistenceOperationError({ operation: \"plugin-configuration.update\" })\n }\n return persisted.value\n })\n\n const requestSecretCleanup = Effect.fn(\"PluginConfigurationRepository.requestSecretCleanup\")(function*(\n ref: SecretRef,\n requestedAt: UtcTimestampType\n ) {\n yield* sql`INSERT INTO plugin_secret_cleanup (secret_ref, requested_at)\n VALUES (${ref}, ${encodeTimestamp(requestedAt)})\n ON CONFLICT(secret_ref) DO NOTHING`.pipe(\n mapPersistenceOperation(\"plugin-configuration.request-secret-cleanup\")\n )\n })\n\n const pendingSecretCleanup = Effect.fn(\"PluginConfigurationRepository.pendingSecretCleanup\")(function*() {\n const rows = yield* sql<Record<string, unknown>>`SELECT secret_ref AS secretRef\n FROM plugin_secret_cleanup\n ORDER BY requested_at, secret_ref\n LIMIT 100`.pipe(\n mapPersistenceOperation(\"plugin-configuration.pending-secret-cleanup\")\n )\n return yield* Schema.decodeUnknownEffect(Schema.Array(PendingSecretCleanupRow))(rows).pipe(\n Effect.mapError(() =>\n new PersistenceOperationError({\n operation: \"plugin-configuration.pending-secret-cleanup\"\n })\n )\n )\n })\n\n const completeSecretCleanup = Effect.fn(\"PluginConfigurationRepository.completeSecretCleanup\")(function*(\n ref: SecretRef\n ) {\n yield* sql`DELETE FROM plugin_secret_cleanup\n WHERE secret_ref = ${ref}`.pipe(\n mapPersistenceOperation(\"plugin-configuration.complete-secret-cleanup\")\n )\n })\n\n return { completeSecretCleanup, get, pendingSecretCleanup, requestSecretCleanup, update }\n})\n\n/** Durable plugin-configuration service with CAS updates and opaque secret references. */\nexport type PluginConfigurationRepositoryService = Success<typeof makePluginConfigurationRepository>\n\n/** Effect service for revisioned plugin configuration. */\nexport class PluginConfigurationRepository extends Context.Service<\n PluginConfigurationRepository,\n PluginConfigurationRepositoryService\n>()(\"@knpkv/control-center/PluginConfigurationRepository\") {\n static readonly layer = Layer.effect(PluginConfigurationRepository, makePluginConfigurationRepository)\n}\n","import {\n renderBindPluginConnectionQuery,\n renderCreatePluginConnectionQuery,\n type RenderedSql,\n renderPluginConnectionCountQuery,\n renderPluginConnectionQuery,\n renderPluginConnectionsQuery,\n renderUpdatePluginConnectionQuery\n} from \"@knpkv/control-center-sql\"\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 type { Success } from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\"\n\nimport { FollowedResourceId, PluginConnectionId, ProviderAccountId, WorkspaceId } from \"../../../domain/identifiers.js\"\nimport { ProviderId } from \"../../../domain/sourceRevision.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport { Database } from \"../Database.js\"\nimport { PersistedRecordError, PluginConnectionLimitError, RecordNotFoundError } from \"../errors.js\"\nimport {\n mapAlreadyExists,\n mapPersistenceOperation,\n readChanges,\n resolveCasFailure,\n revisionLookup\n} from \"./internal.js\"\nimport { PluginConnectionDisplayName, PluginConnectionRecord, RecordRevision } from \"./models.js\"\nimport { makePersistedRowQuarantine } from \"./persistedRowQuarantine.js\"\nimport { QuarantineRepository } from \"./quarantineRepository.js\"\n\nconst PluginConnectionRow = Schema.Struct({\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n providerAccountId: Schema.NullOr(ProviderAccountId),\n followedResourceId: Schema.NullOr(FollowedResourceId),\n providerId: ProviderId,\n displayName: PluginConnectionDisplayName,\n isEnabled: Schema.Number.check(Schema.isInt(), Schema.isBetween({ minimum: 0, maximum: 1 })),\n revision: RecordRevision,\n createdAt: UtcTimestamp,\n updatedAt: UtcTimestamp\n})\n\nconst PluginConnectionKey = Schema.Struct({\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId\n})\n\nconst PluginConnectionIdentity = Schema.Struct({ pluginConnectionId: PluginConnectionId })\n\nconst CreatePluginConnectionRequest = Schema.Struct({\n ...PluginConnectionKey.fields,\n providerId: ProviderId,\n displayName: PluginConnectionDisplayName,\n isEnabled: Schema.Boolean,\n createdAt: UtcTimestamp\n})\n\nconst UpdatePluginConnectionRequest = Schema.Struct({\n ...PluginConnectionKey.fields,\n displayName: PluginConnectionDisplayName,\n isEnabled: Schema.Boolean,\n expectedRevision: RecordRevision,\n updatedAt: UtcTimestamp\n})\n\nconst BindPluginConnectionRequest = Schema.Struct({\n ...PluginConnectionKey.fields,\n providerAccountId: ProviderAccountId,\n followedResourceId: FollowedResourceId,\n expectedRevision: RecordRevision,\n updatedAt: UtcTimestamp\n})\n\nconst PluginConnectionCountRow = Schema.Struct({ connectionCount: Schema.Number })\n\nconst decodeRecord = Effect.fn(\"PluginConnectionRepository.decodeRecord\")(function*(\n row: typeof PluginConnectionRow.Type\n) {\n return yield* Schema.decodeUnknownEffect(Schema.toType(PluginConnectionRecord))({\n ...row,\n isEnabled: row.isEnabled === 1\n })\n})\n\nconst makePluginConnectionRepository = Effect.gen(function*() {\n const cryptoService = yield* Crypto.Crypto\n const database = yield* Database\n const quarantine = yield* QuarantineRepository\n const quarantineRow = makePersistedRowQuarantine(cryptoService, quarantine)\n const sql = database.sql\n const run = (plan: RenderedSql) => sql.unsafe<Record<string, unknown>>(plan.sql, [...plan.params])\n\n const quarantineMalformed = Effect.fn(\"PluginConnectionRepository.quarantineMalformed\")(function*(\n workspaceId: WorkspaceId,\n row: unknown,\n fallbackKey: PluginConnectionId | WorkspaceId\n ) {\n const identity = Schema.decodeUnknownResult(PluginConnectionIdentity)(row)\n const observedAt = yield* DateTime.now\n yield* quarantineRow({\n workspaceId,\n recordKind: \"plugin-connection\",\n recordKey: Result.isSuccess(identity) ? identity.success.pluginConnectionId : fallbackKey,\n diagnosticCode: \"plugin-connection-schema-invalid\",\n diagnosticSummary: \"Stored plugin connection failed schema validation.\",\n observedAt,\n row\n })\n })\n\n const get = Effect.fn(\"PluginConnectionRepository.get\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId\n ) {\n const rows = yield* run(renderPluginConnectionQuery({ workspaceId, pluginConnectionId })).pipe(\n mapPersistenceOperation(\"plugin-connection.get\")\n )\n if (rows.length === 0) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"plugin-connection\",\n recordKey: pluginConnectionId\n })\n }\n const decoded = Schema.decodeUnknownResult(PluginConnectionRow)(rows[0])\n if (Result.isSuccess(decoded)) return yield* decodeRecord(decoded.success)\n yield* quarantineMalformed(workspaceId, rows[0], pluginConnectionId)\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"plugin-connection\",\n recordKey: pluginConnectionId,\n diagnosticCode: \"plugin-connection-schema-invalid\"\n })\n })\n\n const insert = SqlSchema.void({\n Request: CreatePluginConnectionRequest,\n execute: (request) => run(renderCreatePluginConnectionQuery(request))\n })\n\n const update = SqlSchema.void({\n Request: UpdatePluginConnectionRequest,\n execute: (request) => run(renderUpdatePluginConnectionQuery(request))\n })\n\n const bind = SqlSchema.void({\n Request: BindPluginConnectionRequest,\n execute: (request) => run(renderBindPluginConnectionQuery(request))\n })\n\n const resolveMutationFailure = (\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n expectedRevision: RecordRevision\n ) =>\n resolveCasFailure({\n workspaceId,\n recordKind: \"plugin-connection\",\n recordKey: pluginConnectionId,\n expectedRevision,\n findActualRevision: revisionLookup(() =>\n sql`SELECT revision\n FROM plugin_connections\n WHERE workspace_id = ${workspaceId}\n AND plugin_connection_id = ${pluginConnectionId}`\n )\n })\n\n return {\n create: Effect.fn(\"PluginConnectionRepository.create\")(function*(\n workspaceId: WorkspaceId,\n input: {\n readonly pluginConnectionId: PluginConnectionId\n readonly providerId: ProviderId\n readonly displayName: PluginConnectionDisplayName\n readonly isEnabled: boolean\n readonly createdAt: UtcTimestamp\n }\n ) {\n yield* insert({ workspaceId, ...input }).pipe(\n mapAlreadyExists({\n workspaceId,\n recordKind: \"plugin-connection\",\n recordKey: input.pluginConnectionId\n }),\n mapPersistenceOperation(\"plugin-connection.create\")\n )\n return yield* get(workspaceId, input.pluginConnectionId)\n }),\n createBounded: Effect.fn(\"PluginConnectionRepository.createBounded\")(function*(\n workspaceId: WorkspaceId,\n input: {\n readonly pluginConnectionId: PluginConnectionId\n readonly providerId: ProviderId\n readonly displayName: PluginConnectionDisplayName\n readonly isEnabled: boolean\n readonly createdAt: UtcTimestamp\n readonly maximum: number\n }\n ) {\n yield* database.transaction(\n Effect.gen(function*() {\n const countRows = yield* run(renderPluginConnectionCountQuery(workspaceId))\n const [{ connectionCount }] = yield* Schema.decodeUnknownEffect(\n Schema.Tuple([PluginConnectionCountRow])\n )(countRows)\n if (connectionCount >= input.maximum) {\n return yield* new PluginConnectionLimitError({ workspaceId, maximum: input.maximum })\n }\n yield* insert({ workspaceId, ...input })\n })\n ).pipe(\n mapAlreadyExists({\n workspaceId,\n recordKind: \"plugin-connection\",\n recordKey: input.pluginConnectionId\n }),\n mapPersistenceOperation(\"plugin-connection.create-bounded\")\n )\n return yield* get(workspaceId, input.pluginConnectionId)\n }),\n get,\n list: Effect.fn(\"PluginConnectionRepository.list\")(function*(workspaceId: WorkspaceId) {\n const rows = yield* run(renderPluginConnectionsQuery(workspaceId)).pipe(\n mapPersistenceOperation(\"plugin-connection.list\")\n )\n const records: Array<PluginConnectionRecord> = []\n for (const row of rows) {\n const decoded = Schema.decodeUnknownResult(PluginConnectionRow)(row)\n if (Result.isSuccess(decoded)) {\n records.push(yield* decodeRecord(decoded.success))\n } else {\n yield* quarantineMalformed(workspaceId, row, workspaceId)\n }\n }\n return records\n }),\n updateMetadata: Effect.fn(\"PluginConnectionRepository.updateMetadata\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n input: {\n readonly displayName: PluginConnectionDisplayName\n readonly isEnabled: boolean\n readonly expectedRevision: RecordRevision\n readonly updatedAt: UtcTimestamp\n }\n ) {\n yield* database.transaction(\n Effect.gen(function*() {\n yield* update({ workspaceId, pluginConnectionId, ...input })\n const changes = yield* readChanges(sql)\n if (changes === 0) {\n return yield* resolveMutationFailure(workspaceId, pluginConnectionId, input.expectedRevision)\n }\n })\n ).pipe(mapPersistenceOperation(\"plugin-connection.update\"))\n return yield* get(workspaceId, pluginConnectionId)\n }),\n bindResource: Effect.fn(\"PluginConnectionRepository.bindResource\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n input: Omit<typeof BindPluginConnectionRequest.Type, \"workspaceId\" | \"pluginConnectionId\">\n ) {\n yield* database.transaction(\n Effect.gen(function*() {\n yield* bind({ workspaceId, pluginConnectionId, ...input }).pipe(\n mapAlreadyExists({\n workspaceId,\n recordKind: \"plugin-connection-resource\",\n recordKey: input.followedResourceId\n })\n )\n if ((yield* readChanges(sql)) === 0) {\n return yield* resolveMutationFailure(workspaceId, pluginConnectionId, input.expectedRevision)\n }\n })\n ).pipe(mapPersistenceOperation(\"plugin-connection.bind-resource\"))\n return yield* get(workspaceId, pluginConnectionId)\n })\n }\n})\n\n/** Workspace-isolated plugin-connection persistence without secret material. */\nexport interface PluginConnectionRepositoryService extends Success<typeof makePluginConnectionRepository> {}\n\n/** Effect service for plugin-connection metadata. */\nexport class PluginConnectionRepository extends Context.Service<\n PluginConnectionRepository,\n PluginConnectionRepositoryService\n>()(\"@knpkv/control-center/PluginConnectionRepository\") {\n /** Layer that binds SQL queries to the shared database at construction. */\n static readonly layer = Layer.effect(PluginConnectionRepository, makePluginConnectionRepository)\n}\n","import * as DateTime from \"effect/DateTime\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\n\nimport { PluginHealth } from \"../../../domain/freshness.js\"\nimport { PluginConnectionId, WorkspaceId } from \"../../../domain/identifiers.js\"\nimport { ProviderId, Revision } from \"../../../domain/sourceRevision.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport { ContentBlobDigest } from \"./models.js\"\n\nconst bounded = (maximum: number) =>\n Schema.String.check(Schema.isTrimmed(), Schema.isNonEmpty(), Schema.isMaxLength(maximum))\n\nconst jsonText = (maximum: number) =>\n bounded(maximum).check(\n Schema.isMinLength(2),\n Schema.makeFilter(\n (value) => Result.isSuccess(Schema.decodeUnknownResult(Schema.UnknownFromJsonString)(value)),\n { expected: \"bounded valid JSON text\" }\n )\n )\n\n/** Stable logical collection synchronized through one checkpoint. */\nexport const PluginStreamKey = bounded(100).pipe(Schema.brand(\"PluginStreamKey\"))\nexport type PluginStreamKey = typeof PluginStreamKey.Type\n\n/** Provider page identity used for idempotent commits. */\nexport const PluginPageId = bounded(200).pipe(Schema.brand(\"PluginPageId\"))\nexport type PluginPageId = typeof PluginPageId.Type\n\n/** Stable provider record identity within one stream. */\nexport const PluginRecordKey = bounded(700).pipe(Schema.brand(\"PluginRecordKey\"))\nexport type PluginRecordKey = typeof PluginRecordKey.Type\n\nexport const DescriptorCandidate = Schema.Struct({\n providerId: ProviderId,\n schemaVersion: Schema.Int.check(Schema.isGreaterThan(0)),\n descriptorJson: jsonText(65_536)\n})\nexport type DescriptorCandidate = typeof DescriptorCandidate.Type\n\nexport const PluginRuntimeRecord = Schema.Struct({\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n providerId: ProviderId,\n revision: Schema.Int.check(Schema.isGreaterThan(0)),\n descriptorGeneration: Schema.Int.check(Schema.isGreaterThan(0)),\n descriptorSchemaVersion: Schema.Int.check(Schema.isGreaterThan(0)),\n descriptorJson: jsonText(65_536),\n descriptorDigest: ContentBlobDigest,\n acceptedAt: UtcTimestamp,\n health: PluginHealth,\n consecutiveFailures: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))\n})\nexport type PluginRuntimeRecord = typeof PluginRuntimeRecord.Type\n\nconst EventBase = {\n eventId: bounded(512),\n eventJson: jsonText(524_288),\n recordKey: PluginRecordKey,\n sourceRevision: Revision,\n observedAt: UtcTimestamp\n}\n\nexport const PluginSyncEvent = Schema.Union([\n Schema.TaggedStruct(\"upsert\", {\n ...EventBase,\n payloadJson: jsonText(524_288)\n }),\n Schema.TaggedStruct(\"tombstone\", EventBase)\n]).pipe(Schema.toTaggedUnion(\"_tag\"))\nexport type PluginSyncEvent = typeof PluginSyncEvent.Type\n\nexport const PluginSyncPage = Schema.Struct({\n providerId: ProviderId,\n streamKey: PluginStreamKey,\n pageId: PluginPageId,\n expectedRevision: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n checkpointJson: jsonText(65_536),\n hasMore: Schema.Boolean,\n successfulHealth: PluginHealth.check(\n Schema.makeFilter(({ _tag }) => _tag === \"healthy\" || _tag === \"degraded\", {\n expected: \"usable plugin health for a successfully committed page\"\n })\n ),\n committedAt: UtcTimestamp,\n events: Schema.Array(PluginSyncEvent).check(\n Schema.makeFilter((events) => events.length <= 500, {\n expected: \"at most 500 persisted plugin events\"\n }),\n Schema.makeFilter(\n (events) => new Set(events.map(({ eventId }) => eventId)).size === events.length,\n { expected: \"unique event identities within a persisted page\" }\n )\n )\n})\nexport type PluginSyncPage = typeof PluginSyncPage.Type\n\nexport const PluginStreamRecord = Schema.Struct({\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n providerId: ProviderId,\n streamKey: PluginStreamKey,\n revision: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n checkpointJson: Schema.NullOr(jsonText(65_536)),\n checkpointDigest: Schema.NullOr(ContentBlobDigest),\n lastPageId: Schema.NullOr(PluginPageId),\n synchronizedAt: Schema.NullOr(UtcTimestamp)\n}).check(\n Schema.makeFilter(\n ({ checkpointDigest, checkpointJson, lastPageId, synchronizedAt }) =>\n (checkpointJson === null) === (checkpointDigest === null) &&\n (checkpointJson === null) === (lastPageId === null) &&\n (lastPageId === null) === (synchronizedAt === null),\n { expected: \"coherent checkpoint, page, and synchronization metadata\" }\n )\n)\nexport type PluginStreamRecord = typeof PluginStreamRecord.Type\n\n/** Durable terminal classification for one fake-plugin synchronization attempt. */\nexport const PluginSyncAttemptOutcome = Schema.Literals([\"synchronized\", \"source-unavailable\", \"interrupted\"])\nexport type PluginSyncAttemptOutcome = typeof PluginSyncAttemptOutcome.Type\n\n/** Terminal outcome that a normal synchronization invocation may record directly. */\nexport const PluginSyncCompletionOutcome = Schema.Literals([\"synchronized\", \"source-unavailable\"])\nexport type PluginSyncCompletionOutcome = typeof PluginSyncCompletionOutcome.Type\n\n/** Append-only synchronization attempt with its optional immutable completion. */\nexport const PluginSyncAttemptRecord = Schema.Struct({\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n providerId: ProviderId,\n streamKey: PluginStreamKey,\n attemptSequence: Schema.Int.check(Schema.isGreaterThan(0)),\n startedRevision: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n startedAt: UtcTimestamp,\n outcome: Schema.NullOr(PluginSyncAttemptOutcome),\n endingRevision: Schema.NullOr(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n pagesCommitted: Schema.NullOr(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n completedAt: Schema.NullOr(UtcTimestamp)\n}).check(\n Schema.makeFilter(\n ({ completedAt, endingRevision, outcome, pagesCommitted, startedAt, startedRevision }) =>\n outcome === null\n ? endingRevision === null && pagesCommitted === null && completedAt === null\n : endingRevision !== null && pagesCommitted !== null && completedAt !== null &&\n endingRevision >= startedRevision && pagesCommitted === endingRevision - startedRevision &&\n DateTime.Order(completedAt, startedAt) >= 0,\n { expected: \"coherent open or completed synchronization attempt\" }\n )\n)\nexport type PluginSyncAttemptRecord = typeof PluginSyncAttemptRecord.Type\n\n/** Bounded materialization of the attempt records needed for current synchronization state. */\nexport const PluginSyncAttemptState = Schema.Struct({\n latestAttempt: Schema.NullOr(PluginSyncAttemptRecord),\n latestSynchronized: Schema.NullOr(PluginSyncAttemptRecord)\n})\nexport type PluginSyncAttemptState = typeof PluginSyncAttemptState.Type\n\nexport const PluginCacheRecord = Schema.Struct({\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n streamKey: PluginStreamKey,\n recordKey: PluginRecordKey,\n state: Schema.Literals([\"present\", \"tombstoned\"]),\n payloadJson: Schema.NullOr(jsonText(524_288)),\n payloadDigest: Schema.NullOr(ContentBlobDigest),\n sourceRevision: Revision,\n lastPageId: PluginPageId,\n cachedAt: UtcTimestamp,\n tombstonedAt: Schema.NullOr(UtcTimestamp)\n}).check(\n Schema.makeFilter(\n ({ payloadDigest, payloadJson, state, tombstonedAt }) =>\n (payloadJson === null) === (payloadDigest === null) &&\n (state === \"present\"\n ? payloadJson !== null && tombstonedAt === null\n : tombstonedAt !== null),\n { expected: \"a coherent present or tombstoned plugin cache record\" }\n )\n)\nexport type PluginCacheRecord = typeof PluginCacheRecord.Type\n\n/** Indexed CodePipeline cache coordinates used by canonical execution correlation. */\nexport interface CodePipelineCacheSelector {\n readonly executionId: string | null\n readonly pipelineName: string\n readonly pipelineVersion: number | null\n}\n\n/** Maximum distinct execution/declaration correlation scopes accepted in one plugin page. */\nexport const MaximumCodePipelineCorrelationExecutions = 32\n\nexport const PluginEvidenceRecord = Schema.Struct({\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n streamKey: PluginStreamKey,\n pageId: PluginPageId,\n ordinal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n eventId: bounded(512),\n eventDigest: ContentBlobDigest,\n eventKind: Schema.Literals([\"upsert\", \"tombstone\"]),\n recordKey: PluginRecordKey,\n sourceRevision: Revision,\n payloadJson: jsonText(524_288),\n observedAt: UtcTimestamp\n})\nexport type PluginEvidenceRecord = typeof PluginEvidenceRecord.Type\n","import * as Effect from \"effect/Effect\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\n\nimport {\n type NegotiatedPluginCapabilityV1,\n NegotiatedPluginDescriptorV1,\n type PluginCapabilityId as PluginCapabilityIdType,\n PluginDescriptorV1,\n type PluginDescriptorV1 as PluginDescriptorV1Type,\n SemanticVersion\n} from \"../../domain/plugins/descriptor.js\"\nimport { PluginMalformedResponseFailure, PluginUnsupportedCapabilityFailure } from \"./failures.js\"\n\nconst DescriptorEnvelope = Schema.Struct({\n contractId: Schema.Literal(\"dev.knpkv.control-center.plugin\"),\n contractVersion: SemanticVersion\n})\n\n/** Capability versions implemented by this host contract major. */\nexport const HOST_PLUGIN_CAPABILITY_VERSIONS: Readonly<\n Record<PluginCapabilityIdType, ReadonlyArray<number>>\n> = {\n \"entity.read\": [1],\n \"sync.incremental\": [1],\n \"action.propose\": [1],\n \"action.execute\": [1],\n \"action.cancel\": [1],\n \"action.reconcile\": [1],\n \"diff.inventory\": [1, 2],\n \"diff.content\": [1, 2],\n \"pipeline.logs\": [1],\n \"pipeline.artifact\": [1]\n}\n\nconst selectHighestCommonVersion = (\n capabilityId: PluginCapabilityIdType,\n offered: ReadonlyArray<number>\n): number | null => {\n const supported = new Set(HOST_PLUGIN_CAPABILITY_VERSIONS[capabilityId])\n const common = offered.filter((version) => supported.has(version)).sort((left, right) => right - left)\n return common[0] ?? null\n}\n\nconst decodeDescriptor = (raw: unknown) => {\n const envelope = Schema.decodeUnknownResult(DescriptorEnvelope)(raw)\n if (Result.isFailure(envelope)) {\n return Effect.fail(\n new PluginMalformedResponseFailure({\n operation: \"plugin-descriptor\",\n diagnosticCode: \"plugin-descriptor-envelope-invalid\"\n })\n )\n }\n if (envelope.success.contractVersion.major !== 1) {\n return Effect.fail(\n new PluginUnsupportedCapabilityFailure({\n capabilityId: null,\n requestedVersion: envelope.success.contractVersion.major,\n diagnosticCode: \"plugin-contract-major-unsupported\"\n })\n )\n }\n return Schema.decodeUnknownEffect(PluginDescriptorV1)(raw).pipe(\n Effect.mapError(\n () =>\n new PluginMalformedResponseFailure({\n operation: \"plugin-descriptor\",\n diagnosticCode: \"plugin-descriptor-schema-invalid\"\n })\n )\n )\n}\n\nconst negotiateCapabilities = Effect.fn(\"PluginContract.negotiateCapabilities\")(function*(\n descriptor: PluginDescriptorV1Type\n) {\n const seen = new Set<PluginCapabilityIdType>()\n const capabilities: Array<NegotiatedPluginCapabilityV1> = []\n\n for (const offer of descriptor.capabilities) {\n if (seen.has(offer.capabilityId)) {\n return yield* new PluginMalformedResponseFailure({\n operation: \"plugin-descriptor\",\n diagnosticCode: \"plugin-capability-duplicate\"\n })\n }\n seen.add(offer.capabilityId)\n const version = selectHighestCommonVersion(offer.capabilityId, offer.supportedVersions)\n if (version === null) {\n if (offer.requirement === \"required\") {\n return yield* new PluginUnsupportedCapabilityFailure({\n capabilityId: offer.capabilityId,\n requestedVersion: Math.max(...offer.supportedVersions),\n diagnosticCode: \"plugin-required-capability-unsupported\"\n })\n }\n continue\n }\n capabilities.push({ capabilityId: offer.capabilityId, version })\n }\n\n const decoded = yield* Schema.decodeUnknownEffect(NegotiatedPluginDescriptorV1)({\n descriptor,\n capabilities\n }).pipe(\n Effect.mapError(\n () =>\n new PluginMalformedResponseFailure({\n operation: \"plugin-descriptor\",\n diagnosticCode: \"plugin-negotiated-descriptor-invalid\"\n })\n )\n )\n return decoded\n})\n\n/** Decode and negotiate a descriptor before any plugin factory can be invoked. */\nexport const negotiatePluginDescriptorV1 = Effect.fn(\"PluginContract.negotiateDescriptor\")(function*(\n raw: unknown\n) {\n const descriptor = yield* decodeDescriptor(raw)\n return yield* negotiateCapabilities(descriptor)\n})\n\n/** Whether a negotiated descriptor exposes one exact capability version. */\nexport const hasPluginCapability = (\n descriptor: typeof NegotiatedPluginDescriptorV1.Type,\n capabilityId: PluginCapabilityIdType,\n version: number\n): boolean =>\n descriptor.capabilities.some(\n (capability) => capability.capabilityId === capabilityId && capability.version === version\n )\n","import {\n renderOpenPluginSyncAttemptsQuery,\n renderPluginSyncAttemptsQuery,\n renderPluginSyncAttemptStateQuery\n} from \"@knpkv/control-center-sql\"\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 type { Success } from \"effect/Effect\"\nimport * as Encoding from \"effect/Encoding\"\nimport * as Layer from \"effect/Layer\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\n\nimport { PluginHealth } from \"../../../domain/freshness.js\"\nimport type { PluginConnectionId, WorkspaceId } from \"../../../domain/identifiers.js\"\nimport { NegotiatedPluginDescriptorV1 } from \"../../../domain/plugins/descriptor.js\"\nimport { NormalizedPluginEventV1, type PluginSyncPageV1 } from \"../../../domain/plugins/events.js\"\nimport { ProviderId } from \"../../../domain/sourceRevision.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport { negotiatePluginDescriptorV1 } from \"../../plugins/negotiation.js\"\nimport { Database } from \"../Database.js\"\nimport {\n PersistedRecordError,\n PersistenceOperationError,\n RecordNotFoundError,\n RevisionConflictError,\n SourceIdentityMismatchError\n} from \"../errors.js\"\nimport { mapPersistenceOperation, readChanges } from \"./internal.js\"\nimport { ContentBlobDigest } from \"./models.js\"\nimport type { CodePipelineCacheSelector, PluginStreamKey } from \"./pluginRuntimeModels.js\"\nimport {\n DescriptorCandidate,\n MaximumCodePipelineCorrelationExecutions,\n PluginCacheRecord,\n PluginEvidenceRecord,\n PluginRuntimeRecord,\n PluginStreamRecord,\n PluginSyncAttemptRecord,\n PluginSyncAttemptState,\n PluginSyncCompletionOutcome,\n PluginSyncPage\n} from \"./pluginRuntimeModels.js\"\nimport { QuarantineRepository } from \"./quarantineRepository.js\"\n\ntype DescriptorRejection = {\n readonly code:\n | \"plugin-capability-duplicate\"\n | \"plugin-contract-major-unsupported\"\n | \"plugin-descriptor-envelope-invalid\"\n | \"plugin-descriptor-schema-invalid\"\n | \"plugin-negotiated-descriptor-invalid\"\n | \"plugin-required-capability-unsupported\"\n readonly summary:\n | \"Plugin descriptor contains duplicate capability offers.\"\n | \"Plugin descriptor contract major is unsupported.\"\n | \"Plugin descriptor envelope failed schema validation.\"\n | \"Plugin descriptor candidate failed schema validation.\"\n | \"Negotiated plugin descriptor failed schema validation.\"\n | \"Plugin descriptor requires an unsupported capability version.\"\n}\n\nconst descriptorRejection = (diagnosticCode: string): DescriptorRejection => {\n switch (diagnosticCode) {\n case \"plugin-capability-duplicate\":\n return {\n code: diagnosticCode,\n summary: \"Plugin descriptor contains duplicate capability offers.\"\n }\n case \"plugin-contract-major-unsupported\":\n return {\n code: diagnosticCode,\n summary: \"Plugin descriptor contract major is unsupported.\"\n }\n case \"plugin-descriptor-envelope-invalid\":\n return {\n code: diagnosticCode,\n summary: \"Plugin descriptor envelope failed schema validation.\"\n }\n case \"plugin-negotiated-descriptor-invalid\":\n return {\n code: diagnosticCode,\n summary: \"Negotiated plugin descriptor failed schema validation.\"\n }\n case \"plugin-required-capability-unsupported\":\n return {\n code: diagnosticCode,\n summary: \"Plugin descriptor requires an unsupported capability version.\"\n }\n case \"plugin-descriptor-schema-invalid\":\n default:\n return {\n code: \"plugin-descriptor-schema-invalid\",\n summary: \"Plugin descriptor candidate failed schema validation.\"\n }\n }\n}\n\nconst serialize = Effect.fn(\"PluginRuntimeRepository.serialize\")(function*(value: unknown) {\n return yield* Effect.try({\n try: () => JSON.stringify(value),\n catch: () => new PersistenceOperationError({ operation: \"plugin-runtime.serialize\" })\n })\n})\n\nconst encodeTimestamp = Schema.encodeSync(UtcTimestamp)\n\nconst makePluginRuntimeRepository = Effect.gen(function*() {\n const cryptoService = yield* Crypto.Crypto\n const database = yield* Database\n const quarantine = yield* QuarantineRepository\n const sql = database.sql\n\n const digestText = Effect.fn(\"PluginRuntimeRepository.digestText\")(function*(value: string) {\n const bytes = yield* Effect.fromResult(Encoding.decodeBase64(Encoding.encodeBase64(value))).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"plugin-runtime.digest\" }))\n )\n const digest = yield* cryptoService.digest(\"SHA-256\", bytes).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"plugin-runtime.digest\" }))\n )\n return ContentBlobDigest.make(Encoding.encodeHex(digest))\n })\n\n const digestUnknown = Effect.fn(\"PluginRuntimeRepository.digestUnknown\")(function*(value: unknown) {\n const encoded = yield* serialize(value).pipe(Effect.orElseSucceed(() => \"<unserializable>\"))\n return yield* digestText(encoded)\n })\n\n const normalizedRecordKey = Effect.fn(\"PluginRuntimeRepository.normalizedRecordKey\")(function*(\n event: typeof NormalizedPluginEventV1.Type\n ) {\n switch (event._tag) {\n case \"UpsertEntity\":\n case \"TombstoneEntity\":\n return `entity/${yield* digestText(yield* serialize([event.entityType, event.vendorImmutableId]))}`\n case \"AppendEvidence\":\n return `evidence/${yield* digestText(yield* serialize(event.evidenceId))}`\n case \"UpsertPerson\":\n return `person/${yield* digestText(yield* serialize(event.vendorPersonId))}`\n case \"ProposeRelationship\":\n return `relationship/${yield* digestText(yield* serialize(event.relationshipId))}`\n }\n })\n\n const readConnectionProvider = Effect.fn(\"PluginRuntimeRepository.readProvider\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId\n ) {\n const rows = yield* sql<{ readonly providerId: string }>`SELECT provider_id AS providerId\n FROM plugin_connections\n WHERE workspace_id = ${workspaceId}\n AND plugin_connection_id = ${pluginConnectionId}`\n if (rows.length === 0) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"plugin-connection\",\n recordKey: pluginConnectionId\n })\n }\n return yield* Schema.decodeUnknownEffect(ProviderId)(rows[0]?.providerId)\n })\n\n const verifyProvider = Effect.fn(\"PluginRuntimeRepository.verifyProvider\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n providerId: typeof ProviderId.Type\n ) {\n const actual = yield* readConnectionProvider(workspaceId, pluginConnectionId)\n if (actual !== providerId) {\n return yield* new SourceIdentityMismatchError({\n workspaceId,\n recordKind: \"plugin-runtime\",\n recordKey: pluginConnectionId\n })\n }\n })\n\n const getRuntime = Effect.fn(\"PluginRuntimeRepository.getRuntime\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId\n ) {\n const rows = yield* sql<Record<string, unknown>>`SELECT\n workspace_id AS workspaceId, plugin_connection_id AS pluginConnectionId,\n provider_id AS providerId, revision, descriptor_generation AS descriptorGeneration,\n descriptor_schema_version AS descriptorSchemaVersion,\n descriptor_json AS descriptorJson, descriptor_digest AS descriptorDigest,\n accepted_at AS acceptedAt, health_state AS healthState, failure_class AS failureClass,\n safe_message AS safeMessage, checked_at AS checkedAt, retry_at AS retryAt,\n consecutive_failures AS consecutiveFailures\n FROM plugin_runtime_state\n WHERE workspace_id = ${workspaceId} AND plugin_connection_id = ${pluginConnectionId}`.pipe(\n mapPersistenceOperation(\"plugin-runtime.get\")\n )\n if (rows.length === 0) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"plugin-runtime\",\n recordKey: pluginConnectionId\n })\n }\n const row = rows[0]\n const state = row?.healthState\n const health = state === \"healthy\" || state === \"disabled\"\n ? { _tag: state, checkedAt: row?.checkedAt }\n : {\n _tag: state,\n checkedAt: row?.checkedAt,\n failureClass: row?.failureClass,\n retryAt: row?.retryAt,\n safeMessage: row?.safeMessage\n }\n const decoded = Schema.decodeUnknownResult(PluginRuntimeRecord)({ ...row, health })\n const descriptorText = row?.descriptorJson\n const descriptorDigest = row?.descriptorDigest\n const descriptor = typeof descriptorText === \"string\"\n ? Schema.decodeUnknownResult(Schema.UnknownFromJsonString)(descriptorText)\n : null\n const canonical = descriptor !== null && Result.isSuccess(descriptor)\n ? Schema.decodeUnknownResult(NegotiatedPluginDescriptorV1)(descriptor.success)\n : null\n const actualDigest = typeof descriptorText === \"string\" ? yield* digestText(descriptorText) : null\n if (\n Result.isFailure(decoded) ||\n canonical === null ||\n Result.isFailure(canonical) ||\n typeof descriptorDigest !== \"string\" ||\n actualDigest !== descriptorDigest ||\n canonical.success.descriptor.contractVersion.major !== row?.descriptorSchemaVersion\n ) {\n const observedAt = yield* DateTime.now\n yield* quarantine.recordMalformed(workspaceId, {\n recordKind: \"plugin-descriptor\",\n recordKey: pluginConnectionId,\n schemaVersion: 1,\n payloadDigest: yield* digestUnknown(row),\n diagnosticCode: \"plugin-descriptor-schema-invalid\",\n diagnosticSummary: \"Plugin descriptor candidate failed schema validation.\",\n observedAt\n })\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"plugin-runtime\",\n recordKey: pluginConnectionId,\n diagnosticCode: \"plugin-runtime-schema-invalid\"\n })\n }\n return decoded.success\n })\n\n const acceptDescriptor = Effect.fn(\"PluginRuntimeRepository.acceptDescriptor\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n candidate: unknown,\n expectedRevision: number,\n acceptedAt: UtcTimestamp\n ) {\n const decoded = Schema.decodeUnknownResult(DescriptorCandidate)(candidate)\n if (Result.isFailure(decoded)) {\n yield* quarantine.recordMalformed(workspaceId, {\n recordKind: \"plugin-descriptor\",\n recordKey: pluginConnectionId,\n schemaVersion: 1,\n payloadDigest: yield* digestUnknown(candidate),\n diagnosticCode: \"plugin-descriptor-schema-invalid\",\n diagnosticSummary: \"Plugin descriptor candidate failed schema validation.\",\n observedAt: acceptedAt\n })\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"plugin-descriptor\",\n recordKey: pluginConnectionId,\n diagnosticCode: \"plugin-descriptor-schema-invalid\"\n })\n }\n const descriptorDigest = yield* digestText(decoded.success.descriptorJson)\n const acceptedAtText = encodeTimestamp(acceptedAt)\n yield* database.transaction(\n Effect.gen(function*() {\n yield* verifyProvider(workspaceId, pluginConnectionId, decoded.success.providerId)\n if (expectedRevision === 0) {\n yield* sql`INSERT INTO plugin_runtime_state (\n workspace_id, plugin_connection_id, provider_id, revision,\n descriptor_schema_version, descriptor_json, descriptor_digest, accepted_at,\n health_state, checked_at, consecutive_failures\n ) VALUES (\n ${workspaceId}, ${pluginConnectionId}, ${decoded.success.providerId}, 1,\n ${decoded.success.schemaVersion}, ${decoded.success.descriptorJson}, ${descriptorDigest}, ${acceptedAtText},\n 'healthy', ${acceptedAtText}, 0\n ) ON CONFLICT (workspace_id, plugin_connection_id) DO NOTHING`\n } else {\n yield* sql`UPDATE plugin_runtime_state SET\n revision = revision + 1,\n descriptor_generation = descriptor_generation + 1,\n provider_id = ${decoded.success.providerId},\n descriptor_schema_version = ${decoded.success.schemaVersion},\n descriptor_json = ${decoded.success.descriptorJson},\n descriptor_digest = ${descriptorDigest},\n accepted_at = ${acceptedAtText}\n WHERE workspace_id = ${workspaceId} AND plugin_connection_id = ${pluginConnectionId}\n AND revision = ${expectedRevision}`\n }\n if ((yield* readChanges(sql)) === 0) {\n const revisions = yield* sql<{ readonly revision: number }>`SELECT revision FROM plugin_runtime_state\n WHERE workspace_id = ${workspaceId} AND plugin_connection_id = ${pluginConnectionId}`\n return yield* new RevisionConflictError({\n workspaceId,\n recordKind: \"plugin-runtime\",\n recordKey: pluginConnectionId,\n expectedRevision,\n actualRevision: revisions[0]?.revision ?? null\n })\n }\n })\n ).pipe(mapPersistenceOperation(\"plugin-runtime.accept-descriptor\"))\n return yield* getRuntime(workspaceId, pluginConnectionId)\n })\n\n const acceptPluginDescriptor = Effect.fn(\"PluginRuntimeRepository.acceptPluginDescriptor\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n providerId: typeof ProviderId.Type,\n rawDescriptor: unknown,\n expectedRevision: number,\n observedAt: UtcTimestamp\n ) {\n const payloadDigest = yield* digestUnknown(rawDescriptor)\n const negotiated = yield* negotiatePluginDescriptorV1(rawDescriptor).pipe(Effect.result)\n if (Result.isFailure(negotiated)) {\n const rejection = descriptorRejection(negotiated.failure.diagnosticCode)\n yield* quarantine.recordMalformed(workspaceId, {\n recordKind: \"plugin-descriptor\",\n recordKey: pluginConnectionId,\n schemaVersion: 1,\n payloadDigest,\n diagnosticCode: rejection.code,\n diagnosticSummary: rejection.summary,\n observedAt\n })\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"plugin-descriptor\",\n recordKey: pluginConnectionId,\n diagnosticCode: rejection.code\n })\n }\n\n const connectionProvider = yield* readConnectionProvider(workspaceId, pluginConnectionId).pipe(\n mapPersistenceOperation(\"plugin-runtime.read-descriptor-provider\")\n )\n if (connectionProvider !== providerId) {\n yield* quarantine.recordMalformed(workspaceId, {\n recordKind: \"plugin-descriptor\",\n recordKey: pluginConnectionId,\n schemaVersion: 1,\n payloadDigest,\n diagnosticCode: \"plugin-descriptor-provider-mismatch\",\n diagnosticSummary: \"Plugin descriptor provider does not match its connection.\",\n observedAt\n })\n return yield* new SourceIdentityMismatchError({\n workspaceId,\n recordKind: \"plugin-descriptor\",\n recordKey: pluginConnectionId\n })\n }\n\n return yield* acceptDescriptor(\n workspaceId,\n pluginConnectionId,\n {\n providerId,\n schemaVersion: negotiated.success.descriptor.contractVersion.major,\n descriptorJson: yield* serialize(negotiated.success)\n },\n expectedRevision,\n observedAt\n )\n })\n\n const recordHealth = Effect.fn(\"PluginRuntimeRepository.recordHealth\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n expectedRevision: number,\n health: PluginHealth,\n consecutiveFailures: number\n ) {\n const failure = health._tag === \"degraded\" || health._tag === \"unavailable\" ? health : undefined\n const checkedAt = encodeTimestamp(health.checkedAt)\n const retryAt = failure?.retryAt === null || failure?.retryAt === undefined\n ? null\n : encodeTimestamp(failure.retryAt)\n yield* database.transaction(\n Effect.gen(function*() {\n yield* sql`UPDATE plugin_runtime_state SET\n revision = revision + 1,\n health_state = ${health._tag},\n failure_class = ${failure?.failureClass ?? null},\n safe_message = ${failure?.safeMessage ?? null},\n checked_at = ${checkedAt},\n retry_at = ${retryAt},\n consecutive_failures = ${consecutiveFailures}\n WHERE workspace_id = ${workspaceId} AND plugin_connection_id = ${pluginConnectionId}\n AND revision = ${expectedRevision}`\n if ((yield* readChanges(sql)) === 0) {\n const revisions = yield* sql<{ readonly revision: number }>`SELECT revision FROM plugin_runtime_state\n WHERE workspace_id = ${workspaceId} AND plugin_connection_id = ${pluginConnectionId}`\n if (revisions.length === 0) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"plugin-runtime\",\n recordKey: pluginConnectionId\n })\n }\n return yield* new RevisionConflictError({\n workspaceId,\n recordKind: \"plugin-runtime\",\n recordKey: pluginConnectionId,\n expectedRevision,\n actualRevision: revisions[0]?.revision ?? null\n })\n }\n })\n ).pipe(mapPersistenceOperation(\"plugin-runtime.record-health\"))\n return yield* getRuntime(workspaceId, pluginConnectionId)\n })\n\n const getStream = Effect.fn(\"PluginRuntimeRepository.getStream\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n streamKey: PluginStreamKey\n ) {\n const rows = yield* sql<Record<string, unknown>>`SELECT workspace_id AS workspaceId,\n plugin_connection_id AS pluginConnectionId, provider_id AS providerId,\n stream_key AS streamKey, revision, checkpoint_json AS checkpointJson,\n checkpoint_digest AS checkpointDigest, last_page_id AS lastPageId,\n synchronized_at AS synchronizedAt\n FROM plugin_sync_streams\n WHERE workspace_id = ${workspaceId} AND plugin_connection_id = ${pluginConnectionId}\n AND stream_key = ${streamKey}`\n if (rows.length === 0) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"plugin-sync-stream\",\n recordKey: pluginConnectionId\n })\n }\n const row = rows[0]\n const decoded = Schema.decodeUnknownResult(PluginStreamRecord)(row)\n const checkpointText = row?.checkpointJson\n const checkpointDigest = row?.checkpointDigest\n const actualDigest = typeof checkpointText === \"string\" ? yield* digestText(checkpointText) : null\n if (\n Result.isFailure(decoded) ||\n ((checkpointText === null || checkpointText === undefined)\n ? checkpointDigest !== null\n : typeof checkpointDigest !== \"string\" || actualDigest !== checkpointDigest)\n ) {\n const observedAt = yield* DateTime.now\n yield* quarantine.recordMalformed(workspaceId, {\n recordKind: \"plugin-sync-page\",\n recordKey: pluginConnectionId,\n schemaVersion: 1,\n payloadDigest: yield* digestUnknown(row),\n diagnosticCode: \"plugin-sync-page-schema-invalid\",\n diagnosticSummary: \"Plugin sync page failed schema validation.\",\n observedAt\n })\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"plugin-sync-stream\",\n recordKey: pluginConnectionId,\n diagnosticCode: \"plugin-sync-page-schema-invalid\"\n })\n }\n return decoded.success\n })\n\n const currentStreamRevision = Effect.fn(\"PluginRuntimeRepository.currentStreamRevision\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n streamKey: PluginStreamKey\n ) {\n const rows = yield* sql<{ readonly revision: number }>`SELECT revision\n FROM plugin_sync_streams\n WHERE workspace_id = ${workspaceId} AND plugin_connection_id = ${pluginConnectionId}\n AND stream_key = ${streamKey}`\n return rows[0]?.revision ?? 0\n })\n\n const openSyncAttempts = Effect.fn(\"PluginRuntimeRepository.openSyncAttempts\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n streamKey: PluginStreamKey\n ) {\n const rendered = renderOpenPluginSyncAttemptsQuery({ workspaceId, pluginConnectionId, streamKey })\n return yield* sql.unsafe<{\n readonly attemptSequence: number\n readonly startedRevision: number\n }>(rendered.sql, [...rendered.params])\n })\n\n const reconcileOpenSyncAttempts = Effect.fn(\"PluginRuntimeRepository.reconcileOpenSyncAttempts\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n streamKey: PluginStreamKey,\n completedAt: UtcTimestamp,\n attemptSequence?: number\n ) {\n const openAttempts = yield* openSyncAttempts(workspaceId, pluginConnectionId, streamKey)\n const attempts = attemptSequence === undefined\n ? openAttempts\n : openAttempts.filter((attempt) => attempt.attemptSequence === attemptSequence)\n const endingRevision = yield* currentStreamRevision(workspaceId, pluginConnectionId, streamKey)\n for (const attempt of attempts) {\n yield* sql`INSERT INTO plugin_sync_attempt_completions (\n workspace_id, plugin_connection_id, stream_key, attempt_sequence, outcome,\n ending_revision, pages_committed, completed_at\n ) VALUES (\n ${workspaceId}, ${pluginConnectionId}, ${streamKey}, ${attempt.attemptSequence}, 'interrupted',\n ${endingRevision}, ${endingRevision - attempt.startedRevision}, ${encodeTimestamp(completedAt)}\n )`\n }\n return attempts.length\n })\n\n const reconcileSyncAttempts = Effect.fn(\"PluginRuntimeRepository.reconcileSyncAttempts\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n providerId: typeof ProviderId.Type,\n streamKey: PluginStreamKey,\n completedAt: UtcTimestamp,\n attemptSequence?: number\n ) {\n return yield* database.transaction(Effect.gen(function*() {\n yield* verifyProvider(workspaceId, pluginConnectionId, providerId)\n return yield* reconcileOpenSyncAttempts(\n workspaceId,\n pluginConnectionId,\n streamKey,\n completedAt,\n attemptSequence\n )\n })).pipe(mapPersistenceOperation(\"plugin-runtime.reconcile-sync-attempts\"))\n })\n\n const beginSyncAttempt = Effect.fn(\"PluginRuntimeRepository.beginSyncAttempt\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n providerId: typeof ProviderId.Type,\n streamKey: PluginStreamKey,\n startedAt: UtcTimestamp\n ) {\n return yield* database.transaction(Effect.gen(function*() {\n yield* verifyProvider(workspaceId, pluginConnectionId, providerId)\n yield* reconcileOpenSyncAttempts(workspaceId, pluginConnectionId, streamKey, startedAt)\n const startedRevision = yield* currentStreamRevision(workspaceId, pluginConnectionId, streamKey)\n const sequences = yield* sql<{ readonly nextSequence: number }>`SELECT\n COALESCE(MAX(attempt_sequence), 0) + 1 AS nextSequence\n FROM plugin_sync_attempts\n WHERE workspace_id = ${workspaceId} AND plugin_connection_id = ${pluginConnectionId}\n AND stream_key = ${streamKey}`\n const attemptSequence = sequences[0]?.nextSequence ?? 1\n yield* sql`INSERT INTO plugin_sync_attempts (\n workspace_id, plugin_connection_id, provider_id, stream_key,\n attempt_sequence, started_revision, started_at\n ) VALUES (\n ${workspaceId}, ${pluginConnectionId}, ${providerId}, ${streamKey},\n ${attemptSequence}, ${startedRevision}, ${encodeTimestamp(startedAt)}\n )`\n return yield* Schema.decodeUnknownEffect(Schema.toType(PluginSyncAttemptRecord))({\n workspaceId,\n pluginConnectionId,\n providerId,\n streamKey,\n attemptSequence,\n startedRevision,\n startedAt,\n outcome: null,\n endingRevision: null,\n pagesCommitted: null,\n completedAt: null\n })\n })).pipe(mapPersistenceOperation(\"plugin-runtime.begin-sync-attempt\"))\n })\n\n const claimSync = Effect.fn(\"PluginRuntimeRepository.claimSync\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n providerId: typeof ProviderId.Type,\n streamKey: PluginStreamKey,\n claimId: string,\n claimedAt: UtcTimestamp,\n expiresAt: UtcTimestamp\n ) {\n return yield* database.transaction(Effect.gen(function*() {\n yield* verifyProvider(workspaceId, pluginConnectionId, providerId)\n yield* sql`DELETE FROM plugin_sync_claims\n WHERE workspace_id = ${workspaceId} AND plugin_connection_id = ${pluginConnectionId}\n AND stream_key = ${streamKey} AND expires_at <= ${encodeTimestamp(claimedAt)}`\n yield* sql`INSERT INTO plugin_sync_claims (\n workspace_id, plugin_connection_id, provider_id, stream_key, claim_id, claimed_at, expires_at\n ) VALUES (\n ${workspaceId}, ${pluginConnectionId}, ${providerId}, ${streamKey}, ${claimId},\n ${encodeTimestamp(claimedAt)}, ${encodeTimestamp(expiresAt)}\n ) ON CONFLICT (workspace_id, plugin_connection_id, stream_key) DO NOTHING`\n return (yield* readChanges(sql)) === 1\n })).pipe(mapPersistenceOperation(\"plugin-runtime.claim-sync\"))\n })\n\n const releaseSyncClaim = Effect.fn(\"PluginRuntimeRepository.releaseSyncClaim\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n streamKey: PluginStreamKey,\n claimId: string\n ) {\n yield* sql`DELETE FROM plugin_sync_claims\n WHERE workspace_id = ${workspaceId} AND plugin_connection_id = ${pluginConnectionId}\n AND stream_key = ${streamKey} AND claim_id = ${claimId}`\n }, mapPersistenceOperation(\"plugin-runtime.release-sync-claim\"))\n\n const listSyncAttempts = Effect.fn(\"PluginRuntimeRepository.listSyncAttempts\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n streamKey: PluginStreamKey\n ) {\n const rendered = renderPluginSyncAttemptsQuery({ workspaceId, pluginConnectionId, streamKey })\n const rows = yield* sql.unsafe<Record<string, unknown>>(rendered.sql, [...rendered.params])\n return yield* Schema.decodeUnknownEffect(Schema.Array(PluginSyncAttemptRecord))(rows)\n })\n\n const getSyncAttemptState = Effect.fn(\"PluginRuntimeRepository.getSyncAttemptState\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n streamKey: PluginStreamKey\n ) {\n const rendered = renderPluginSyncAttemptStateQuery({ workspaceId, pluginConnectionId, streamKey })\n const rows = yield* sql.unsafe<Record<string, unknown>>(rendered.sql, [...rendered.params])\n const decodedRows = yield* Schema.decodeUnknownEffect(\n Schema.Array(PluginSyncAttemptRecord).check(Schema.isMaxLength(2))\n )(rows)\n const latestAttempt = decodedRows.at(0) ?? null\n const latestSynchronized = decodedRows.find(({ outcome }) => outcome === \"synchronized\") ?? null\n return yield* Schema.decodeUnknownEffect(Schema.toType(PluginSyncAttemptState))({\n latestAttempt,\n latestSynchronized\n })\n })\n\n const completeSyncAttempt = Effect.fn(\"PluginRuntimeRepository.completeSyncAttempt\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n streamKey: PluginStreamKey,\n attemptSequence: number,\n outcome: typeof PluginSyncCompletionOutcome.Type,\n completedAt: UtcTimestamp\n ) {\n return yield* database.transaction(Effect.gen(function*() {\n const decodedOutcome = yield* Schema.decodeUnknownEffect(PluginSyncCompletionOutcome)(outcome)\n const attempts = yield* sql<{ readonly startedRevision: number }>`SELECT\n started_revision AS startedRevision FROM plugin_sync_attempts\n WHERE workspace_id = ${workspaceId} AND plugin_connection_id = ${pluginConnectionId}\n AND stream_key = ${streamKey} AND attempt_sequence = ${attemptSequence}`\n const attempt = attempts[0]\n if (attempt === undefined) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"plugin-sync-attempt\",\n recordKey: `${pluginConnectionId}/${streamKey}/${attemptSequence}`\n })\n }\n const existingRecords = yield* listSyncAttempts(workspaceId, pluginConnectionId, streamKey)\n const existing = existingRecords.find((record) => record.attemptSequence === attemptSequence)\n if (existing !== undefined && existing.outcome !== null) {\n if (existing.outcome !== decodedOutcome) {\n return yield* new SourceIdentityMismatchError({\n workspaceId,\n recordKind: \"plugin-sync-attempt\",\n recordKey: `${pluginConnectionId}/${streamKey}/${attemptSequence}`\n })\n }\n return existing\n }\n const endingRevision = yield* currentStreamRevision(workspaceId, pluginConnectionId, streamKey)\n yield* sql`INSERT INTO plugin_sync_attempt_completions (\n workspace_id, plugin_connection_id, stream_key, attempt_sequence, outcome,\n ending_revision, pages_committed, completed_at\n ) VALUES (\n ${workspaceId}, ${pluginConnectionId}, ${streamKey}, ${attemptSequence}, ${decodedOutcome},\n ${endingRevision}, ${endingRevision - attempt.startedRevision}, ${encodeTimestamp(completedAt)}\n )`\n const records = yield* listSyncAttempts(workspaceId, pluginConnectionId, streamKey)\n const completed = records.find((record) => record.attemptSequence === attemptSequence)\n if (\n completed === undefined ||\n completed.outcome !== decodedOutcome ||\n completed.endingRevision !== endingRevision ||\n completed.pagesCommitted !== endingRevision - attempt.startedRevision\n ) {\n return yield* new SourceIdentityMismatchError({\n workspaceId,\n recordKind: \"plugin-sync-attempt\",\n recordKey: `${pluginConnectionId}/${streamKey}/${attemptSequence}`\n })\n }\n return completed\n })).pipe(mapPersistenceOperation(\"plugin-runtime.complete-sync-attempt\"))\n })\n\n const commitPageReceipt = Effect.fn(\"PluginRuntimeRepository.commitPageReceipt\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n input: unknown\n ) {\n const decoded = Schema.decodeUnknownResult(PluginSyncPage)(input)\n const observedAt = Result.isSuccess(decoded) ? decoded.success.committedAt : yield* DateTime.now\n if (Result.isFailure(decoded)) {\n yield* quarantine.recordMalformed(workspaceId, {\n recordKind: \"plugin-sync-page\",\n recordKey: pluginConnectionId,\n schemaVersion: 1,\n payloadDigest: yield* digestUnknown(input),\n diagnosticCode: \"plugin-sync-page-schema-invalid\",\n diagnosticSummary: \"Plugin sync page failed schema validation.\",\n observedAt\n })\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"plugin-sync-page\",\n recordKey: pluginConnectionId,\n diagnosticCode: \"plugin-sync-page-schema-invalid\"\n })\n }\n const page = decoded.success\n const pageDigest = yield* digestText(\n yield* serialize({\n providerId: page.providerId,\n streamKey: page.streamKey,\n pageId: page.pageId,\n checkpointJson: page.checkpointJson,\n hasMore: page.hasMore,\n events: page.events\n })\n )\n const checkpointDigest = yield* digestText(page.checkpointJson)\n const timelineEventDigest = yield* digestText(\n yield* serialize([workspaceId, pluginConnectionId, page.streamKey, page.pageId])\n )\n const successfulHealthJson = yield* serialize(yield* Schema.encodeEffect(PluginHealth)(page.successfulHealth))\n const successfulHealthDigest = yield* digestText(successfulHealthJson)\n const committedAt = encodeTimestamp(page.committedAt)\n const payloadDigests = yield* Effect.forEach(\n page.events,\n (event) => event._tag === \"upsert\" ? digestText(event.payloadJson) : Effect.succeed(null)\n )\n const eventDigests = yield* Effect.forEach(page.events, (event) => digestText(event.eventJson))\n const acceptedEventIds: Array<string> = []\n let pageCommitted = false\n\n const committed = yield* database.transaction(\n Effect.gen(function*() {\n yield* verifyProvider(workspaceId, pluginConnectionId, page.providerId)\n yield* sql`INSERT INTO plugin_sync_streams (\n workspace_id, plugin_connection_id, provider_id, stream_key, revision\n ) VALUES (${workspaceId}, ${pluginConnectionId}, ${page.providerId}, ${page.streamKey}, 0)\n ON CONFLICT (workspace_id, plugin_connection_id, stream_key) DO NOTHING`\n\n const duplicate = yield* sql<{ readonly checkpointDigest: string; readonly pageDigest: string }>`SELECT\n page_digest AS pageDigest, checkpoint_digest AS checkpointDigest\n FROM plugin_sync_pages\n WHERE workspace_id = ${workspaceId} AND plugin_connection_id = ${pluginConnectionId}\n AND stream_key = ${page.streamKey} AND page_id = ${page.pageId}`\n if (duplicate.length > 0) {\n if (duplicate[0]?.pageDigest === pageDigest && duplicate[0]?.checkpointDigest === checkpointDigest) return\n return yield* new SourceIdentityMismatchError({\n workspaceId,\n recordKind: \"plugin-sync-page\",\n recordKey: pluginConnectionId\n })\n }\n\n const heads = yield* sql<{ readonly revision: number }>`SELECT revision FROM plugin_sync_streams\n WHERE workspace_id = ${workspaceId} AND plugin_connection_id = ${pluginConnectionId}\n AND stream_key = ${page.streamKey}`\n const actualRevision = heads[0]?.revision ?? null\n if (actualRevision !== page.expectedRevision) {\n return yield* new RevisionConflictError({\n workspaceId,\n recordKind: \"plugin-sync-stream\",\n recordKey: pluginConnectionId,\n expectedRevision: page.expectedRevision,\n actualRevision\n })\n }\n\n yield* sql`INSERT INTO plugin_sync_pages (\n workspace_id, plugin_connection_id, stream_key, page_id, expected_revision,\n page_digest, checkpoint_digest, timeline_event_digest, event_count, committed_at, has_more,\n successful_health_json, successful_health_digest\n ) VALUES (\n ${workspaceId}, ${pluginConnectionId}, ${page.streamKey}, ${page.pageId}, ${page.expectedRevision},\n ${pageDigest}, ${checkpointDigest}, ${timelineEventDigest}, ${page.events.length}, ${committedAt}, ${page.hasMore},\n ${successfulHealthJson}, ${successfulHealthDigest}\n )`\n\n for (let ordinal = 0; ordinal < page.events.length; ordinal++) {\n const event = page.events[ordinal]\n if (event === undefined) continue\n const payloadDigest = payloadDigests[ordinal] ?? null\n const eventDigest = eventDigests[ordinal]\n if (eventDigest === undefined) continue\n const observedAtText = encodeTimestamp(event.observedAt)\n const existingEvent = yield* sql<{ readonly eventDigest: string }>`SELECT event_digest AS eventDigest\n FROM plugin_sync_evidence\n WHERE workspace_id = ${workspaceId} AND plugin_connection_id = ${pluginConnectionId}\n AND stream_key = ${page.streamKey} AND event_id = ${event.eventId}`\n if (existingEvent.length > 0) {\n if (existingEvent[0]?.eventDigest === eventDigest) continue\n return yield* new SourceIdentityMismatchError({\n workspaceId,\n recordKind: \"plugin-sync-event\",\n recordKey: pluginConnectionId\n })\n }\n yield* sql`INSERT INTO plugin_sync_evidence (\n workspace_id, plugin_connection_id, stream_key, page_id, ordinal,\n event_id, event_digest, event_kind, record_key, source_revision, payload_json, observed_at\n ) VALUES (\n ${workspaceId}, ${pluginConnectionId}, ${page.streamKey}, ${page.pageId}, ${ordinal},\n ${event.eventId}, ${eventDigest}, ${event._tag}, ${event.recordKey}, ${event.sourceRevision},\n ${event.eventJson}, ${observedAtText}\n )`\n acceptedEventIds.push(event.eventId)\n if (event._tag === \"upsert\") {\n yield* sql`INSERT INTO plugin_cache_entries (\n workspace_id, plugin_connection_id, stream_key, record_key, state,\n payload_json, payload_digest, source_revision, last_page_id, cached_at, tombstoned_at\n ) VALUES (\n ${workspaceId}, ${pluginConnectionId}, ${page.streamKey}, ${event.recordKey}, 'present',\n ${event.payloadJson}, ${payloadDigest}, ${event.sourceRevision}, ${page.pageId}, ${committedAt}, NULL\n ) ON CONFLICT (workspace_id, plugin_connection_id, stream_key, record_key) DO UPDATE SET\n state = 'present', payload_json = excluded.payload_json, payload_digest = excluded.payload_digest,\n source_revision = excluded.source_revision, last_page_id = excluded.last_page_id,\n cached_at = excluded.cached_at, tombstoned_at = NULL`\n } else {\n yield* sql`INSERT INTO plugin_cache_entries (\n workspace_id, plugin_connection_id, stream_key, record_key, state,\n source_revision, last_page_id, cached_at, tombstoned_at\n ) VALUES (\n ${workspaceId}, ${pluginConnectionId}, ${page.streamKey}, ${event.recordKey}, 'tombstoned',\n ${event.sourceRevision}, ${page.pageId}, ${committedAt}, ${observedAtText}\n ) ON CONFLICT (workspace_id, plugin_connection_id, stream_key, record_key) DO UPDATE SET\n state = 'tombstoned', source_revision = excluded.source_revision,\n last_page_id = excluded.last_page_id, cached_at = excluded.cached_at,\n tombstoned_at = excluded.tombstoned_at`\n }\n }\n\n yield* sql`UPDATE plugin_sync_streams SET revision = revision + 1,\n checkpoint_json = ${page.checkpointJson}, checkpoint_digest = ${checkpointDigest},\n last_page_id = ${page.pageId}, synchronized_at = ${committedAt}\n WHERE workspace_id = ${workspaceId} AND plugin_connection_id = ${pluginConnectionId}\n AND stream_key = ${page.streamKey} AND revision = ${page.expectedRevision}`\n if ((yield* readChanges(sql)) === 0) {\n return yield* new RevisionConflictError({\n workspaceId,\n recordKind: \"plugin-sync-stream\",\n recordKey: pluginConnectionId,\n expectedRevision: page.expectedRevision,\n actualRevision: null\n })\n }\n pageCommitted = true\n })\n ).pipe(mapPersistenceOperation(\"plugin-runtime.commit-page\"), Effect.result)\n if (Result.isFailure(committed)) {\n const failure = committed.failure\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 yield* quarantine.recordMalformed(workspaceId, {\n recordKind: \"plugin-sync-page\",\n recordKey: pluginConnectionId,\n schemaVersion: 1,\n payloadDigest: pageDigest,\n diagnosticCode: \"plugin-sync-page-schema-invalid\",\n diagnosticSummary: \"Plugin sync page failed schema validation.\",\n observedAt\n })\n }\n return yield* Effect.fail(failure)\n }\n return {\n acceptedEventIds,\n pageCommitted,\n stream: yield* getStream(workspaceId, pluginConnectionId, page.streamKey)\n }\n })\n\n const commitPage = Effect.fn(\"PluginRuntimeRepository.commitPage\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n input: unknown\n ) {\n return (yield* commitPageReceipt(workspaceId, pluginConnectionId, input)).stream\n })\n\n const commitNormalizedPageReceipt = Effect.fn(\n \"PluginRuntimeRepository.commitNormalizedPageReceipt\"\n )(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n providerId: typeof ProviderId.Type,\n streamKey: PluginStreamKey,\n expectedRevision: number,\n page: PluginSyncPageV1,\n committedAt: UtcTimestamp,\n successfulHealth: PluginHealth\n ) {\n const pageId = yield* digestText(\n yield* serialize({\n checkpointAfterPage: page.checkpointAfterPage,\n eventIds: page.events.map(({ eventId }) => eventId)\n })\n )\n const checkpointJson = yield* serialize(page.checkpointAfterPage)\n const events = yield* Effect.forEach(page.events, (event) =>\n Effect.gen(function*() {\n const payloadJson = yield* serialize(yield* Schema.encodeEffect(NormalizedPluginEventV1)(event))\n const observedAt = encodeTimestamp(event.observedAt)\n switch (event._tag) {\n case \"UpsertEntity\": {\n const identityDigest = yield* digestText(\n yield* serialize([event.entityType, event.vendorImmutableId])\n )\n return {\n _tag: \"upsert\",\n eventId: event.eventId,\n eventJson: payloadJson,\n recordKey: `entity/${identityDigest}`,\n sourceRevision: event.revision,\n observedAt,\n payloadJson\n }\n }\n case \"TombstoneEntity\": {\n const identityDigest = yield* digestText(\n yield* serialize([event.entityType, event.vendorImmutableId])\n )\n return {\n _tag: \"tombstone\",\n eventId: event.eventId,\n eventJson: payloadJson,\n recordKey: `entity/${identityDigest}`,\n sourceRevision: event.revision,\n observedAt\n }\n }\n case \"AppendEvidence\": {\n const identityDigest = yield* digestText(yield* serialize(event.evidenceId))\n return {\n _tag: \"upsert\",\n eventId: event.eventId,\n eventJson: payloadJson,\n recordKey: `evidence/${identityDigest}`,\n sourceRevision: event.revision,\n observedAt,\n payloadJson\n }\n }\n case \"UpsertPerson\": {\n const identityDigest = yield* digestText(yield* serialize(event.vendorPersonId))\n return {\n _tag: \"upsert\",\n eventId: event.eventId,\n eventJson: payloadJson,\n recordKey: `person/${identityDigest}`,\n sourceRevision: event.revision,\n observedAt,\n payloadJson\n }\n }\n case \"ProposeRelationship\": {\n const identityDigest = yield* digestText(yield* serialize(event.relationshipId))\n return {\n _tag: \"upsert\",\n eventId: event.eventId,\n eventJson: payloadJson,\n recordKey: `relationship/${identityDigest}`,\n sourceRevision: event.revision,\n observedAt,\n payloadJson\n }\n }\n }\n }))\n return yield* commitPageReceipt(workspaceId, pluginConnectionId, {\n providerId,\n streamKey,\n pageId,\n expectedRevision,\n checkpointJson,\n hasMore: page.hasMore,\n successfulHealth: yield* Schema.encodeEffect(PluginHealth)(successfulHealth),\n committedAt: encodeTimestamp(committedAt),\n events\n })\n })\n\n const commitNormalizedPage = Effect.fn(\"PluginRuntimeRepository.commitNormalizedPage\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n providerId: typeof ProviderId.Type,\n streamKey: PluginStreamKey,\n expectedRevision: number,\n page: PluginSyncPageV1,\n committedAt: UtcTimestamp,\n successfulHealth: PluginHealth\n ) {\n return (yield* commitNormalizedPageReceipt(\n workspaceId,\n pluginConnectionId,\n providerId,\n streamKey,\n expectedRevision,\n page,\n committedAt,\n successfulHealth\n )).stream\n })\n\n const getLastSuccessfulHealth = Effect.fn(\"PluginRuntimeRepository.getLastSuccessfulHealth\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n streamKey: PluginStreamKey\n ) {\n const rows = yield* sql<Record<string, unknown>>`SELECT\n page.successful_health_json AS successfulHealthJson,\n page.successful_health_digest AS successfulHealthDigest,\n page.expected_revision AS pageExpectedRevision,\n page.checkpoint_digest AS pageCheckpointDigest,\n page.committed_at AS pageCommittedAt,\n stream.revision AS streamRevision,\n stream.last_page_id AS streamLastPageId,\n stream.checkpoint_digest AS streamCheckpointDigest,\n stream.synchronized_at AS streamSynchronizedAt\n FROM plugin_sync_streams AS stream\n LEFT JOIN plugin_sync_pages AS page\n ON page.workspace_id = stream.workspace_id\n AND page.plugin_connection_id = stream.plugin_connection_id\n AND page.stream_key = stream.stream_key\n AND page.page_id = stream.last_page_id\n WHERE stream.workspace_id = ${workspaceId}\n AND stream.plugin_connection_id = ${pluginConnectionId}\n AND stream.stream_key = ${streamKey}`\n if (rows.length === 0) return null\n const row = rows[0]\n if (\n row?.streamRevision === 0 &&\n row.streamLastPageId === null &&\n row.streamCheckpointDigest === null &&\n row.streamSynchronizedAt === null\n ) return null\n const healthJson = row?.successfulHealthJson\n const healthDigest = row?.successfulHealthDigest\n const exactHead = typeof row?.pageExpectedRevision === \"number\" &&\n typeof row.streamRevision === \"number\" &&\n row.pageExpectedRevision + 1 === row.streamRevision &&\n typeof row.pageCheckpointDigest === \"string\" &&\n row.pageCheckpointDigest === row.streamCheckpointDigest &&\n typeof row.pageCommittedAt === \"string\" &&\n row.pageCommittedAt === row.streamSynchronizedAt\n if (!exactHead) {\n const observedAt = yield* DateTime.now\n yield* quarantine.recordMalformed(workspaceId, {\n recordKind: \"plugin-sync-page\",\n recordKey: pluginConnectionId,\n schemaVersion: 1,\n payloadDigest: yield* digestUnknown(row),\n diagnosticCode: \"plugin-sync-page-schema-invalid\",\n diagnosticSummary: \"Plugin sync page failed schema validation.\",\n observedAt\n })\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"plugin-sync-page\",\n recordKey: pluginConnectionId,\n diagnosticCode: \"plugin-sync-page-schema-invalid\"\n })\n }\n if (healthJson === null && healthDigest === null) return null\n const parsed = typeof healthJson === \"string\"\n ? Schema.decodeUnknownResult(Schema.fromJsonString(PluginHealth))(healthJson)\n : null\n const actualDigest = typeof healthJson === \"string\" ? yield* digestText(healthJson) : null\n if (\n parsed === null ||\n Result.isFailure(parsed) ||\n (parsed.success._tag !== \"healthy\" && parsed.success._tag !== \"degraded\") ||\n typeof healthDigest !== \"string\" ||\n actualDigest !== healthDigest\n ) {\n const observedAt = yield* DateTime.now\n yield* quarantine.recordMalformed(workspaceId, {\n recordKind: \"plugin-sync-page\",\n recordKey: pluginConnectionId,\n schemaVersion: 1,\n payloadDigest: yield* digestUnknown(row),\n diagnosticCode: \"plugin-sync-page-schema-invalid\",\n diagnosticSummary: \"Plugin sync page failed schema validation.\",\n observedAt\n })\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"plugin-sync-page\",\n recordKey: pluginConnectionId,\n diagnosticCode: \"plugin-sync-page-schema-invalid\"\n })\n }\n return parsed.success\n })\n\n const decodeCacheRows = Effect.fn(\"PluginRuntimeRepository.decodeCacheRows\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n rows: ReadonlyArray<Record<string, unknown>>\n ) {\n const records: Array<typeof PluginCacheRecord.Type> = []\n for (const row of rows) {\n const decoded = Schema.decodeUnknownResult(PluginCacheRecord)(row)\n const payloadText = row.payloadJson\n const payloadDigest = row.payloadDigest\n const payload = typeof payloadText === \"string\"\n ? Schema.decodeUnknownResult(Schema.UnknownFromJsonString)(payloadText)\n : null\n const normalized = payload !== null && Result.isSuccess(payload)\n ? Schema.decodeUnknownResult(NormalizedPluginEventV1)(payload.success)\n : null\n const latestEventText = row.latestEventJson\n const latestEventPayload = typeof latestEventText === \"string\"\n ? Schema.decodeUnknownResult(Schema.UnknownFromJsonString)(latestEventText)\n : null\n const latestEvent = latestEventPayload !== null && Result.isSuccess(latestEventPayload)\n ? Schema.decodeUnknownResult(NormalizedPluginEventV1)(latestEventPayload.success)\n : null\n const actualDigest = typeof payloadText === \"string\" ? yield* digestText(payloadText) : null\n const expectedRecordKey = latestEvent !== null && Result.isSuccess(latestEvent)\n ? yield* normalizedRecordKey(latestEvent.success)\n : null\n const expectedState = latestEvent !== null && Result.isSuccess(latestEvent) &&\n latestEvent.success._tag === \"TombstoneEntity\"\n ? \"tombstoned\"\n : \"present\"\n const payloadValid = payloadText === null\n ? payloadDigest === null\n : normalized !== null &&\n Result.isSuccess(normalized) &&\n actualDigest === payloadDigest &&\n (row.state === \"tombstoned\" || normalized.success.revision === row.sourceRevision)\n if (\n Result.isFailure(decoded) ||\n !payloadValid ||\n latestEvent === null ||\n Result.isFailure(latestEvent) ||\n expectedRecordKey !== row.recordKey ||\n latestEvent.success.revision !== row.sourceRevision ||\n expectedState !== row.state\n ) {\n const observedAt = yield* DateTime.now\n yield* quarantine.recordMalformed(workspaceId, {\n recordKind: \"plugin-sync-page\",\n recordKey: pluginConnectionId,\n schemaVersion: 1,\n payloadDigest: yield* digestUnknown(row),\n diagnosticCode: \"plugin-sync-page-schema-invalid\",\n diagnosticSummary: \"Plugin sync page failed schema validation.\",\n observedAt\n })\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"plugin-sync-page\",\n recordKey: pluginConnectionId,\n diagnosticCode: \"plugin-sync-page-schema-invalid\"\n })\n }\n records.push(decoded.success)\n }\n return records\n })\n\n const getCache = Effect.fn(\"PluginRuntimeRepository.getCache\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n streamKey: PluginStreamKey\n ) {\n const rows = yield* sql<Record<string, unknown>>`SELECT cache.workspace_id AS workspaceId,\n cache.plugin_connection_id AS pluginConnectionId, cache.stream_key AS streamKey,\n cache.record_key AS recordKey, cache.state, cache.payload_json AS payloadJson,\n cache.payload_digest AS payloadDigest, cache.source_revision AS sourceRevision,\n cache.last_page_id AS lastPageId, cache.cached_at AS cachedAt, cache.tombstoned_at AS tombstonedAt,\n (SELECT evidence.payload_json FROM plugin_sync_evidence AS evidence\n WHERE evidence.workspace_id = cache.workspace_id\n AND evidence.plugin_connection_id = cache.plugin_connection_id\n AND evidence.stream_key = cache.stream_key\n AND evidence.page_id = cache.last_page_id\n AND evidence.record_key = cache.record_key\n ORDER BY evidence.ordinal DESC LIMIT 1) AS latestEventJson\n FROM plugin_cache_entries AS cache WHERE cache.workspace_id = ${workspaceId}\n AND cache.plugin_connection_id = ${pluginConnectionId} AND cache.stream_key = ${streamKey}\n ORDER BY cache.record_key`\n return yield* decodeCacheRows(workspaceId, pluginConnectionId, rows)\n })\n\n const getCodePipelineCacheBeforeTombstones = Effect.fn(\n \"PluginRuntimeRepository.getCodePipelineCacheBeforeTombstones\"\n )(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n streamKey: PluginStreamKey,\n tombstones: ReadonlyArray<Extract<typeof NormalizedPluginEventV1.Type, { readonly _tag: \"TombstoneEntity\" }>>\n ) {\n const records = new Map<string, typeof PluginCacheRecord.Type>()\n for (const tombstone of tombstones) {\n const recordKey = yield* normalizedRecordKey(tombstone)\n const rows = yield* sql<Record<string, unknown>>`SELECT cache.workspace_id AS workspaceId,\n cache.plugin_connection_id AS pluginConnectionId, cache.stream_key AS streamKey,\n cache.record_key AS recordKey, cache.state, cache.payload_json AS payloadJson,\n cache.payload_digest AS payloadDigest, cache.source_revision AS sourceRevision,\n cache.last_page_id AS lastPageId, cache.cached_at AS cachedAt, cache.tombstoned_at AS tombstonedAt,\n (SELECT evidence.payload_json FROM plugin_sync_evidence AS evidence\n WHERE evidence.workspace_id = cache.workspace_id\n AND evidence.plugin_connection_id = cache.plugin_connection_id\n AND evidence.stream_key = cache.stream_key\n AND evidence.page_id = cache.last_page_id\n AND evidence.record_key = cache.record_key\n ORDER BY evidence.ordinal DESC LIMIT 1) AS latestEventJson\n FROM plugin_cache_entries AS cache\n WHERE cache.workspace_id = ${workspaceId}\n AND cache.plugin_connection_id = ${pluginConnectionId}\n AND cache.stream_key = ${streamKey}\n AND cache.record_key = ${recordKey}\n AND cache.state = 'present'\n LIMIT 1`\n for (const record of yield* decodeCacheRows(workspaceId, pluginConnectionId, rows)) {\n records.set(record.recordKey, record)\n }\n }\n return [...records.values()]\n })\n\n const getCodePipelineCache = Effect.fn(\"PluginRuntimeRepository.getCodePipelineCache\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n streamKey: PluginStreamKey,\n selectors: ReadonlyArray<CodePipelineCacheSelector>\n ) {\n const maximumExecutions = MaximumCodePipelineCorrelationExecutions\n const executionSelectors = new Map<string, CodePipelineCacheSelector>()\n const declarations = new Map<string, CodePipelineCacheSelector>()\n for (const selector of selectors) {\n if (selector.executionId === null) {\n const key = `${selector.pipelineName}\\u0000${String(selector.pipelineVersion ?? \"\")}`\n if (declarations.size < maximumExecutions) declarations.set(key, selector)\n } else if (executionSelectors.size < maximumExecutions) {\n const key = `${selector.pipelineName}\\u0000${selector.executionId}`\n executionSelectors.set(key, selector)\n }\n }\n\n for (const selector of declarations.values()) {\n if (executionSelectors.size >= maximumExecutions) break\n const executionRows = selector.pipelineVersion === null\n ? yield* sql<{ readonly executionId: unknown }>`SELECT\n CASE WHEN json_valid(payload_json)\n THEN json_extract(payload_json, '$.attributes.executionId') END AS executionId\n FROM plugin_cache_entries\n WHERE workspace_id = ${workspaceId}\n AND plugin_connection_id = ${pluginConnectionId}\n AND stream_key = ${streamKey}\n AND state = 'present'\n AND CASE WHEN json_valid(payload_json)\n THEN json_extract(payload_json, '$.attributes.pipelineName') END = ${selector.pipelineName}\n AND CASE WHEN json_valid(payload_json)\n THEN json_extract(payload_json, '$.entityType') END = 'aws.codepipeline.execution'\n ORDER BY cached_at DESC, record_key\n LIMIT ${maximumExecutions}`\n : yield* sql<{ readonly executionId: unknown }>`SELECT\n CASE WHEN json_valid(payload_json)\n THEN json_extract(payload_json, '$.attributes.executionId') END AS executionId\n FROM plugin_cache_entries\n WHERE workspace_id = ${workspaceId}\n AND plugin_connection_id = ${pluginConnectionId}\n AND stream_key = ${streamKey}\n AND state = 'present'\n AND CASE WHEN json_valid(payload_json)\n THEN json_extract(payload_json, '$.attributes.pipelineName') END = ${selector.pipelineName}\n AND CASE WHEN json_valid(payload_json)\n THEN json_extract(payload_json, '$.entityType') END = 'aws.codepipeline.execution'\n AND (\n CASE WHEN json_valid(payload_json)\n THEN json_extract(payload_json, '$.attributes.pipelineVersion') END = ${selector.pipelineVersion}\n OR CASE WHEN json_valid(payload_json)\n THEN json_extract(payload_json, '$.attributes.pipelineVersion') END IS NULL\n )\n ORDER BY cached_at DESC, record_key\n LIMIT ${maximumExecutions}`\n for (const row of executionRows) {\n if (executionSelectors.size >= maximumExecutions || typeof row.executionId !== \"string\") break\n const executionId = row.executionId.trim()\n if (executionId.length === 0 || executionId.length > 512) continue\n const executionSelector = { ...selector, executionId }\n executionSelectors.set(`${selector.pipelineName}\\u0000${executionId}`, executionSelector)\n }\n }\n\n const records = new Map<string, typeof PluginCacheRecord.Type>()\n for (const selector of executionSelectors.values()) {\n const rows = yield* sql<Record<string, unknown>>`SELECT cache.workspace_id AS workspaceId,\n cache.plugin_connection_id AS pluginConnectionId, cache.stream_key AS streamKey,\n cache.record_key AS recordKey, cache.state, cache.payload_json AS payloadJson,\n cache.payload_digest AS payloadDigest, cache.source_revision AS sourceRevision,\n cache.last_page_id AS lastPageId, cache.cached_at AS cachedAt, cache.tombstoned_at AS tombstonedAt,\n (SELECT evidence.payload_json FROM plugin_sync_evidence AS evidence\n WHERE evidence.workspace_id = cache.workspace_id\n AND evidence.plugin_connection_id = cache.plugin_connection_id\n AND evidence.stream_key = cache.stream_key\n AND evidence.page_id = cache.last_page_id\n AND evidence.record_key = cache.record_key\n ORDER BY evidence.ordinal DESC LIMIT 1) AS latestEventJson\n FROM plugin_cache_entries AS cache\n WHERE cache.workspace_id = ${workspaceId}\n AND cache.plugin_connection_id = ${pluginConnectionId}\n AND cache.stream_key = ${streamKey}\n AND cache.state = 'present'\n AND CASE WHEN json_valid(cache.payload_json)\n THEN json_extract(cache.payload_json, '$.attributes.pipelineName') END = ${selector.pipelineName}\n AND CASE WHEN json_valid(cache.payload_json)\n THEN json_extract(cache.payload_json, '$.entityType') END IN (\n 'aws.codepipeline.pipeline',\n 'aws.codepipeline.execution',\n 'aws.codepipeline.stage',\n 'aws.codepipeline.action'\n )\n AND (\n CASE WHEN json_valid(cache.payload_json)\n THEN json_extract(cache.payload_json, '$.entityType') END = 'aws.codepipeline.pipeline'\n OR CASE WHEN json_valid(cache.payload_json)\n THEN json_extract(cache.payload_json, '$.attributes.executionId') END = ${selector.executionId}\n )\n ORDER BY CASE WHEN json_valid(cache.payload_json) THEN\n CASE json_extract(cache.payload_json, '$.entityType')\n WHEN 'aws.codepipeline.execution' THEN 0\n WHEN 'aws.codepipeline.pipeline' THEN 1\n WHEN 'aws.codepipeline.stage' THEN 2\n ELSE 3\n END ELSE 4 END, cache.cached_at DESC, cache.record_key\n LIMIT 503`\n for (const record of yield* decodeCacheRows(workspaceId, pluginConnectionId, rows)) {\n records.set(record.recordKey, record)\n }\n }\n return [...records.values()]\n })\n\n const listEvidence = Effect.fn(\"PluginRuntimeRepository.listEvidence\")(function*(\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n streamKey: PluginStreamKey\n ) {\n const rows = yield* sql<Record<string, unknown>>`SELECT evidence.workspace_id AS workspaceId,\n evidence.plugin_connection_id AS pluginConnectionId, evidence.stream_key AS streamKey,\n evidence.page_id AS pageId, evidence.ordinal, evidence.event_kind AS eventKind,\n evidence.event_id AS eventId, evidence.event_digest AS eventDigest,\n evidence.record_key AS recordKey, evidence.source_revision AS sourceRevision,\n evidence.payload_json AS payloadJson,\n evidence.observed_at AS observedAt\n FROM plugin_sync_evidence AS evidence\n INNER JOIN plugin_sync_pages AS page\n ON page.workspace_id = evidence.workspace_id\n AND page.plugin_connection_id = evidence.plugin_connection_id\n AND page.stream_key = evidence.stream_key\n AND page.page_id = evidence.page_id\n WHERE evidence.workspace_id = ${workspaceId}\n AND evidence.plugin_connection_id = ${pluginConnectionId} AND evidence.stream_key = ${streamKey}\n ORDER BY page.expected_revision, evidence.ordinal`\n const records: Array<typeof PluginEvidenceRecord.Type> = []\n for (const row of rows) {\n const decoded = Schema.decodeUnknownResult(PluginEvidenceRecord)(row)\n const payloadText = row.payloadJson\n const payload = typeof payloadText === \"string\"\n ? Schema.decodeUnknownResult(Schema.UnknownFromJsonString)(payloadText)\n : null\n const normalized = payload !== null && Result.isSuccess(payload)\n ? Schema.decodeUnknownResult(NormalizedPluginEventV1)(payload.success)\n : null\n const actualDigest = typeof payloadText === \"string\" ? yield* digestText(payloadText) : null\n const expectedRecordKey = normalized !== null && Result.isSuccess(normalized)\n ? yield* normalizedRecordKey(normalized.success)\n : null\n const eventKind =\n normalized !== null && Result.isSuccess(normalized) && normalized.success._tag === \"TombstoneEntity\"\n ? \"tombstone\"\n : \"upsert\"\n if (\n Result.isFailure(decoded) ||\n normalized === null ||\n Result.isFailure(normalized) ||\n actualDigest !== row.eventDigest ||\n normalized.success.eventId !== row.eventId ||\n normalized.success.revision !== row.sourceRevision ||\n encodeTimestamp(normalized.success.observedAt) !== row.observedAt ||\n expectedRecordKey !== row.recordKey ||\n eventKind !== row.eventKind\n ) {\n const observedAt = yield* DateTime.now\n yield* quarantine.recordMalformed(workspaceId, {\n recordKind: \"plugin-sync-page\",\n recordKey: pluginConnectionId,\n schemaVersion: 1,\n payloadDigest: yield* digestUnknown(row),\n diagnosticCode: \"plugin-sync-page-schema-invalid\",\n diagnosticSummary: \"Plugin sync page failed schema validation.\",\n observedAt\n })\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"plugin-sync-page\",\n recordKey: pluginConnectionId,\n diagnosticCode: \"plugin-sync-page-schema-invalid\"\n })\n }\n records.push(decoded.success)\n }\n return records\n })\n\n return {\n acceptPluginDescriptor,\n beginSyncAttempt,\n claimSync,\n commitNormalizedPage,\n commitNormalizedPageReceipt,\n commitPage,\n completeSyncAttempt,\n getCache,\n getCodePipelineCacheBeforeTombstones,\n getCodePipelineCache,\n getLastSuccessfulHealth,\n getRuntime,\n getSyncAttemptState,\n getStream,\n listEvidence,\n listSyncAttempts,\n reconcileSyncAttempts,\n releaseSyncClaim,\n recordHealth\n }\n})\n\n/** Durable descriptor, health, checkpoint, last-valid cache, and evidence repository. */\nexport interface PluginRuntimeRepositoryService extends Success<typeof makePluginRuntimeRepository> {}\n\nexport class PluginRuntimeRepository extends Context.Service<\n PluginRuntimeRepository,\n PluginRuntimeRepositoryService\n>()(\"@knpkv/control-center/PluginRuntimeRepository\") {\n static readonly layer = Layer.effect(PluginRuntimeRepository, makePluginRuntimeRepository)\n}\n","import {\n renderCreateFollowedResourceQuery,\n renderCreateProviderAccountQuery,\n type RenderedSql,\n renderFollowedResourceQuery,\n renderFollowedResourcesQuery,\n renderProviderAccountIdentityQuery,\n renderProviderAccountQuery,\n renderProviderAccountsQuery,\n renderUpdateFollowedResourceQuery,\n renderUpdateProviderAccountQuery\n} from \"@knpkv/control-center-sql\"\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 type { Success } from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\"\n\nimport { FollowedResourceId, ProviderAccountId, WorkspaceId } from \"../../../domain/identifiers.js\"\nimport { ProviderId } from \"../../../domain/sourceRevision.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport { Database } from \"../Database.js\"\nimport { PersistedRecordError, RecordAlreadyExistsError, RecordNotFoundError } from \"../errors.js\"\nimport {\n mapAlreadyExists,\n mapPersistenceOperation,\n readChanges,\n resolveCasFailure,\n revisionLookup\n} from \"./internal.js\"\nimport {\n FollowedResourceDisplayName,\n FollowedResourceRecord,\n ProviderAccountDisplayName,\n ProviderAccountRecord,\n ProviderFamily,\n providerFamilyForProvider,\n ProviderFamilyMatchesProvider,\n RecordRevision,\n VendorAccountId,\n VendorResourceId\n} from \"./models.js\"\nimport { makePersistedRowQuarantine } from \"./persistedRowQuarantine.js\"\nimport { QuarantineRepository } from \"./quarantineRepository.js\"\n\n/** Invalid provider/resource combination rejected before persistence. */\nexport class ProviderAccountInputError extends Schema.TaggedErrorClass<ProviderAccountInputError>()(\n \"ProviderAccountInputError\",\n {\n operation: Schema.Literals([\"follow-resource\"]),\n reason: Schema.Literals([\"provider-family-mismatch\"])\n }\n) {}\n\nconst ProviderAccountKey = Schema.Struct({\n workspaceId: WorkspaceId,\n providerAccountId: ProviderAccountId\n})\n\nconst FollowedResourceKey = Schema.Struct({\n workspaceId: WorkspaceId,\n followedResourceId: FollowedResourceId\n})\n\nconst CreateProviderAccountRequest = Schema.Struct({\n ...ProviderAccountKey.fields,\n providerFamily: ProviderFamily,\n vendorAccountId: VendorAccountId,\n displayName: ProviderAccountDisplayName,\n createdAt: UtcTimestamp\n})\n\nconst UpdateProviderAccountRequest = Schema.Struct({\n ...ProviderAccountKey.fields,\n displayName: ProviderAccountDisplayName,\n expectedRevision: RecordRevision,\n updatedAt: UtcTimestamp\n})\n\nconst CreateFollowedResourceRequest = Schema.Struct({\n ...FollowedResourceKey.fields,\n providerAccountId: ProviderAccountId,\n providerId: ProviderId,\n vendorResourceId: VendorResourceId,\n displayName: FollowedResourceDisplayName,\n isEnabled: Schema.Boolean,\n createdAt: UtcTimestamp\n})\n\nconst UpdateFollowedResourceRequest = Schema.Struct({\n ...FollowedResourceKey.fields,\n displayName: FollowedResourceDisplayName,\n isEnabled: Schema.Boolean,\n expectedRevision: RecordRevision,\n updatedAt: UtcTimestamp\n})\n\nconst FollowedResourceRow = Schema.Struct({\n workspaceId: WorkspaceId,\n followedResourceId: FollowedResourceId,\n providerAccountId: ProviderAccountId,\n providerFamily: ProviderFamily,\n providerId: ProviderId,\n vendorResourceId: VendorResourceId,\n displayName: FollowedResourceDisplayName,\n isEnabled: Schema.Number.check(Schema.isInt(), Schema.isBetween({ minimum: 0, maximum: 1 })),\n revision: RecordRevision,\n createdAt: UtcTimestamp,\n updatedAt: UtcTimestamp\n}).check(ProviderFamilyMatchesProvider)\n\nconst makeProviderAccountRepository = Effect.gen(function*() {\n const cryptoService = yield* Crypto.Crypto\n const database = yield* Database\n const quarantine = yield* QuarantineRepository\n const quarantineRow = makePersistedRowQuarantine(cryptoService, quarantine)\n const sql = database.sql\n\n const run = (plan: RenderedSql) => sql.unsafe<Record<string, unknown>>(plan.sql, [...plan.params])\n\n const quarantineMalformed = Effect.fn(\"ProviderAccountRepository.quarantineMalformed\")(function*(\n workspaceId: WorkspaceId,\n recordKind: \"provider-account\" | \"followed-resource\",\n recordKey: string,\n row: unknown\n ) {\n yield* quarantineRow({\n workspaceId,\n recordKind,\n recordKey,\n diagnosticCode: `${recordKind}-schema-invalid`,\n diagnosticSummary: `Stored ${recordKind} failed schema validation.`,\n observedAt: yield* DateTime.now,\n row\n })\n })\n\n const decodeProviderAccount = Effect.fn(\"ProviderAccountRepository.decodeProviderAccount\")(function*(\n workspaceId: WorkspaceId,\n fallbackKey: string,\n row: unknown\n ) {\n const decoded = Schema.decodeUnknownResult(ProviderAccountRecord)(row)\n if (Result.isSuccess(decoded)) return decoded.success\n yield* quarantineMalformed(workspaceId, \"provider-account\", fallbackKey, row)\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"provider-account\",\n recordKey: fallbackKey,\n diagnosticCode: \"provider-account-schema-invalid\"\n })\n })\n\n const decodeFollowedResource = Effect.fn(\"ProviderAccountRepository.decodeFollowedResource\")(function*(\n workspaceId: WorkspaceId,\n fallbackKey: string,\n row: unknown\n ) {\n const decoded = Schema.decodeUnknownResult(FollowedResourceRow)(row)\n if (Result.isSuccess(decoded)) {\n return yield* Schema.decodeUnknownEffect(Schema.toType(FollowedResourceRecord))({\n ...decoded.success,\n isEnabled: decoded.success.isEnabled === 1\n })\n }\n yield* quarantineMalformed(workspaceId, \"followed-resource\", fallbackKey, row)\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"followed-resource\",\n recordKey: fallbackKey,\n diagnosticCode: \"followed-resource-schema-invalid\"\n })\n })\n\n const get = Effect.fn(\"ProviderAccountRepository.get\")(function*(\n workspaceId: WorkspaceId,\n providerAccountId: ProviderAccountId\n ) {\n const rows = yield* run(renderProviderAccountQuery({ workspaceId, providerAccountId })).pipe(\n mapPersistenceOperation(\"provider-account.get\")\n )\n if (rows.length === 0) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"provider-account\",\n recordKey: providerAccountId\n })\n }\n return yield* decodeProviderAccount(workspaceId, providerAccountId, rows[0])\n })\n\n const getResource = Effect.fn(\"ProviderAccountRepository.getResource\")(function*(\n workspaceId: WorkspaceId,\n followedResourceId: FollowedResourceId\n ) {\n const rows = yield* run(renderFollowedResourceQuery({ workspaceId, followedResourceId })).pipe(\n mapPersistenceOperation(\"followed-resource.get\")\n )\n if (rows.length === 0) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"followed-resource\",\n recordKey: followedResourceId\n })\n }\n return yield* decodeFollowedResource(workspaceId, followedResourceId, rows[0])\n })\n\n const insertAccount = SqlSchema.void({\n Request: CreateProviderAccountRequest,\n execute: (request) => run(renderCreateProviderAccountQuery(request))\n })\n\n const updateAccount = SqlSchema.void({\n Request: UpdateProviderAccountRequest,\n execute: (request) => run(renderUpdateProviderAccountQuery(request))\n })\n\n const insertResource = SqlSchema.void({\n Request: Schema.Struct({ ...CreateFollowedResourceRequest.fields, providerFamily: ProviderFamily }),\n execute: (request) => run(renderCreateFollowedResourceQuery(request))\n })\n\n const updateResource = SqlSchema.void({\n Request: UpdateFollowedResourceRequest,\n execute: (request) => run(renderUpdateFollowedResourceQuery(request))\n })\n\n return {\n create: Effect.fn(\"ProviderAccountRepository.create\")(function*(\n workspaceId: WorkspaceId,\n input: Omit<typeof CreateProviderAccountRequest.Type, \"workspaceId\">\n ) {\n yield* database.transaction(\n Effect.gen(function*() {\n const existing = yield* run(renderProviderAccountIdentityQuery({\n workspaceId,\n providerFamily: input.providerFamily,\n vendorAccountId: input.vendorAccountId\n }))\n if (existing.length > 0) {\n return yield* new RecordAlreadyExistsError({\n workspaceId,\n recordKind: \"provider-account\",\n recordKey: input.providerAccountId\n })\n }\n yield* insertAccount({ workspaceId, ...input }).pipe(\n mapAlreadyExists({\n workspaceId,\n recordKind: \"provider-account\",\n recordKey: input.providerAccountId\n })\n )\n })\n ).pipe(mapPersistenceOperation(\"provider-account.create\"))\n return yield* get(workspaceId, input.providerAccountId)\n }),\n get,\n list: Effect.fn(\"ProviderAccountRepository.list\")(function*(workspaceId: WorkspaceId) {\n const rows = yield* run(renderProviderAccountsQuery(workspaceId)).pipe(\n mapPersistenceOperation(\"provider-account.list\")\n )\n const records: Array<ProviderAccountRecord> = []\n for (const row of rows) {\n const record = yield* decodeProviderAccount(\n workspaceId,\n Schema.is(ProviderAccountId)(row.providerAccountId) ? row.providerAccountId : workspaceId,\n row\n ).pipe(Effect.catchTag(\"PersistedRecordError\", () => Effect.succeed(null)))\n if (record !== null) records.push(record)\n }\n return records\n }),\n updateMetadata: Effect.fn(\"ProviderAccountRepository.updateMetadata\")(function*(\n workspaceId: WorkspaceId,\n providerAccountId: ProviderAccountId,\n input: Omit<typeof UpdateProviderAccountRequest.Type, \"workspaceId\" | \"providerAccountId\">\n ) {\n yield* database.transaction(\n Effect.gen(function*() {\n yield* updateAccount({ workspaceId, providerAccountId, ...input })\n if ((yield* readChanges(sql)) === 0) {\n return yield* resolveCasFailure({\n workspaceId,\n recordKind: \"provider-account\",\n recordKey: providerAccountId,\n expectedRevision: input.expectedRevision,\n findActualRevision: revisionLookup(() =>\n sql`SELECT revision FROM provider_accounts\n WHERE workspace_id = ${workspaceId}\n AND provider_account_id = ${providerAccountId}`\n )\n })\n }\n })\n ).pipe(mapPersistenceOperation(\"provider-account.update\"))\n return yield* get(workspaceId, providerAccountId)\n }),\n followResource: Effect.fn(\"ProviderAccountRepository.followResource\")(function*(\n workspaceId: WorkspaceId,\n input: Omit<typeof CreateFollowedResourceRequest.Type, \"workspaceId\">\n ) {\n const account = yield* get(workspaceId, input.providerAccountId)\n if (providerFamilyForProvider(input.providerId) !== account.providerFamily) {\n return yield* new ProviderAccountInputError({\n operation: \"follow-resource\",\n reason: \"provider-family-mismatch\"\n })\n }\n yield* insertResource({ workspaceId, providerFamily: account.providerFamily, ...input }).pipe(\n mapAlreadyExists({\n workspaceId,\n recordKind: \"followed-resource\",\n recordKey: input.followedResourceId\n }),\n mapPersistenceOperation(\"followed-resource.create\")\n )\n return yield* getResource(workspaceId, input.followedResourceId)\n }),\n getResource,\n listResources: Effect.fn(\"ProviderAccountRepository.listResources\")(function*(\n workspaceId: WorkspaceId,\n providerAccountId: ProviderAccountId\n ) {\n yield* get(workspaceId, providerAccountId)\n const rows = yield* run(renderFollowedResourcesQuery(workspaceId, providerAccountId)).pipe(\n mapPersistenceOperation(\"followed-resource.list\")\n )\n const records: Array<FollowedResourceRecord> = []\n for (const row of rows) {\n const record = yield* decodeFollowedResource(\n workspaceId,\n Schema.is(FollowedResourceId)(row.followedResourceId) ? row.followedResourceId : workspaceId,\n row\n ).pipe(Effect.catchTag(\"PersistedRecordError\", () => Effect.succeed(null)))\n if (record !== null) records.push(record)\n }\n return records\n }),\n updateResourceMetadata: Effect.fn(\"ProviderAccountRepository.updateResourceMetadata\")(function*(\n workspaceId: WorkspaceId,\n followedResourceId: FollowedResourceId,\n input: Omit<typeof UpdateFollowedResourceRequest.Type, \"workspaceId\" | \"followedResourceId\">\n ) {\n yield* database.transaction(\n Effect.gen(function*() {\n yield* updateResource({ workspaceId, followedResourceId, ...input })\n if ((yield* readChanges(sql)) === 0) {\n return yield* resolveCasFailure({\n workspaceId,\n recordKind: \"followed-resource\",\n recordKey: followedResourceId,\n expectedRevision: input.expectedRevision,\n findActualRevision: revisionLookup(() =>\n sql`SELECT revision FROM followed_resources\n WHERE workspace_id = ${workspaceId}\n AND followed_resource_id = ${followedResourceId}`\n )\n })\n }\n })\n ).pipe(mapPersistenceOperation(\"followed-resource.update\"))\n return yield* getResource(workspaceId, followedResourceId)\n })\n }\n})\n\n/** Provider accounts with their independently followed resources. */\nexport interface ProviderAccountRepositoryService extends Success<typeof makeProviderAccountRepository> {}\n\n/** Effect service for provider-account and followed-resource persistence. */\nexport class ProviderAccountRepository extends Context.Service<\n ProviderAccountRepository,\n ProviderAccountRepositoryService\n>()(\"@knpkv/control-center/ProviderAccountRepository\") {\n /** Layer binding account and resource plans to the shared database. */\n static readonly layer = Layer.effect(ProviderAccountRepository, makeProviderAccountRepository)\n}\n","import * as Crypto from \"effect/Crypto\"\nimport * as Effect from \"effect/Effect\"\nimport * as Encoding from \"effect/Encoding\"\nimport * as Schema from \"effect/Schema\"\n\nimport {\n EnvironmentReadinessCandidateMaterial,\n normalizeEnvironmentReadinessCandidateMaterial,\n normalizeReadinessRuleMaterial,\n normalizeReleaseReadinessCandidateMaterial,\n ReadinessCandidateDigest,\n type ReadinessRuleMaterial,\n ReadinessRuleMaterial as ReadinessRuleMaterialSchema,\n ReleaseReadinessCandidateMaterial\n} from \"../domain/readiness/index.js\"\n\n/** Bounded server failure while producing a canonical readiness digest. */\nexport class ReadinessDigestError extends Schema.TaggedErrorClass<ReadinessDigestError>()(\"ReadinessDigestError\", {\n operation: Schema.Literals([\"encode\", \"encode-utf8\", \"digest\"])\n}) {}\n\nconst environmentMaterialJson = Schema.fromJsonString(EnvironmentReadinessCandidateMaterial)\nconst releaseMaterialJson = Schema.fromJsonString(ReleaseReadinessCandidateMaterial)\nconst ruleMaterialJson = Schema.fromJsonString(ReadinessRuleMaterialSchema)\n\nconst encodeEnvironmentMaterial = Schema.encodeEffect(environmentMaterialJson)\nconst encodeReleaseMaterial = Schema.encodeEffect(releaseMaterialJson)\nconst encodeRuleMaterial = Schema.encodeEffect(ruleMaterialJson)\n\nconst digestCanonicalJson = Effect.fn(\"ReadinessDigests.digestCanonicalJson\")(function*(value: string) {\n const cryptoService = yield* Crypto.Crypto\n const bytes = yield* Effect.fromResult(Encoding.decodeBase64(Encoding.encodeBase64(value))).pipe(\n Effect.mapError(() => new ReadinessDigestError({ operation: \"encode-utf8\" }))\n )\n const digest = yield* cryptoService\n .digest(\"SHA-256\", bytes)\n .pipe(Effect.mapError(() => new ReadinessDigestError({ operation: \"digest\" })))\n return ReadinessCandidateDigest.make(`sha256:${Encoding.encodeHex(digest)}`)\n})\n\n/** Hash the complete environment candidate after deterministic nested normalization. */\nexport const digestEnvironmentReadinessCandidate = Effect.fn(\"ReadinessDigests.environmentCandidate\")(function*(\n material: EnvironmentReadinessCandidateMaterial\n) {\n const value = yield* encodeEnvironmentMaterial(normalizeEnvironmentReadinessCandidateMaterial(material)).pipe(\n Effect.mapError(() => new ReadinessDigestError({ operation: \"encode\" }))\n )\n return yield* digestCanonicalJson(value)\n})\n\n/** Hash the exact set of child assessments forming a release candidate. */\nexport const digestReleaseReadinessCandidate = Effect.fn(\"ReadinessDigests.releaseCandidate\")(function*(\n material: ReleaseReadinessCandidateMaterial\n) {\n const value = yield* encodeReleaseMaterial(normalizeReleaseReadinessCandidateMaterial(material)).pipe(\n Effect.mapError(() => new ReadinessDigestError({ operation: \"encode\" }))\n )\n return yield* digestCanonicalJson(value)\n})\n\n/** Hash a complete immutable readiness-rule snapshot. */\nexport const digestReadinessRule = Effect.fn(\"ReadinessDigests.rule\")(function*(material: ReadinessRuleMaterial) {\n const value = yield* encodeRuleMaterial(normalizeReadinessRuleMaterial(material)).pipe(\n Effect.mapError(() => new ReadinessDigestError({ operation: \"encode\" }))\n )\n return yield* digestCanonicalJson(value)\n})\n","import * as Crypto from \"effect/Crypto\"\nimport * as Effect from \"effect/Effect\"\nimport * as Encoding from \"effect/Encoding\"\nimport * as Schema from \"effect/Schema\"\n\nimport type { PluginConnectionId } from \"../../../../domain/identifiers.js\"\nimport {\n normalizeReadinessRuleMaterial,\n ReadinessAssessment,\n ReadinessRuleMaterial as ReadinessRuleMaterialSchema\n} from \"../../../../domain/readiness/index.js\"\nimport type {\n EnvironmentReadinessAssessment,\n EnvironmentReadinessCandidateMaterial,\n ReadinessAssessment as ReadinessAssessmentType,\n ReadinessRuleMaterial,\n ReleaseReadinessAssessment,\n ReleaseReadinessCandidateMaterial\n} from \"../../../../domain/readiness/index.js\"\nimport { UtcTimestamp } from \"../../../../domain/utcTimestamp.js\"\nimport {\n digestEnvironmentReadinessCandidate,\n digestReadinessRule,\n digestReleaseReadinessCandidate\n} from \"../../../readinessDigests.js\"\nimport { PersistedRecordError, PersistenceOperationError } from \"../../errors.js\"\nimport { ContentBlobDigest } from \"../models.js\"\nimport type { ReadinessAssessmentRow, ReadinessRuleRow } from \"./rows.js\"\n\nconst assessmentJson = Schema.fromJsonString(ReadinessAssessment)\nconst ruleJson = Schema.fromJsonString(ReadinessRuleMaterialSchema)\nconst encodeAssessment = Schema.encodeEffect(assessmentJson)\nconst encodeRule = Schema.encodeEffect(ruleJson)\nconst decodeAssessment = Schema.decodeUnknownEffect(assessmentJson)\nconst decodeRule = Schema.decodeUnknownEffect(ruleJson)\nconst encodeTimestamp = Schema.encodeSync(UtcTimestamp)\n\nconst environmentMaterial = (assessment: EnvironmentReadinessAssessment): EnvironmentReadinessCandidateMaterial => ({\n workspaceId: assessment.candidate.workspaceId,\n releaseRevision: assessment.candidate.releaseRevision,\n artifactRevision: assessment.candidate.artifactRevision,\n scope: assessment.candidate.scope,\n complete: assessment.inputComplete,\n definitions: assessment.facts.map(({ definition }) => definition),\n observations: assessment.facts.flatMap(({ observation }) => (observation === null ? [] : [observation]))\n})\n\nconst releaseMaterial = (assessment: ReleaseReadinessAssessment): ReleaseReadinessCandidateMaterial => {\n const [first, ...remaining] = assessment.environments\n return {\n workspaceId: assessment.candidate.workspaceId,\n releaseRevision: assessment.candidate.releaseRevision,\n artifactRevision: assessment.candidate.artifactRevision,\n scope: assessment.candidate.scope,\n environments: [\n {\n assessmentId: first.assessmentId,\n environmentId: first.environmentId,\n candidateDigest: first.candidateDigest\n },\n ...remaining.map(({ assessmentId, candidateDigest, environmentId }) => ({\n assessmentId,\n environmentId,\n candidateDigest\n }))\n ]\n }\n}\n\nconst sourceIds = (assessment: ReadinessAssessmentType): Array<PluginConnectionId> =>\n assessment.sourceFreshness.map(({ pluginConnectionId }) => pluginConnectionId)\n\nconst encodeBytes = (value: string) =>\n Effect.fromResult(Encoding.decodeBase64(Encoding.encodeBase64(value))).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"readiness.encode-utf8\" }))\n )\n\nexport const makeReadinessCodec = Effect.gen(function*() {\n const cryptoService = yield* Crypto.Crypto\n\n const digestJson = Effect.fn(\"ReadinessCodec.digestJson\")(function*(value: string) {\n const bytes = yield* encodeBytes(value)\n const digest = yield* cryptoService\n .digest(\"SHA-256\", bytes)\n .pipe(Effect.mapError(() => new PersistenceOperationError({ operation: \"readiness.digest-json\" })))\n return ContentBlobDigest.make(Encoding.encodeHex(digest))\n })\n\n const candidateDigest = Effect.fn(\"ReadinessCodec.candidateDigest\")(function*(assessment: ReadinessAssessmentType) {\n return assessment._tag === \"environment\"\n ? yield* digestEnvironmentReadinessCandidate(environmentMaterial(assessment))\n : yield* digestReleaseReadinessCandidate(releaseMaterial(assessment))\n })\n\n const prepareRule = Effect.fn(\"ReadinessCodec.prepareRule\")(function*(material: ReadinessRuleMaterial) {\n const canonicalMaterial = normalizeReadinessRuleMaterial(material)\n const materialJson = yield* encodeRule(canonicalMaterial).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"readiness.encode-rule\" }))\n )\n const ruleDigest = yield* digestReadinessRule(material)\n return { material: canonicalMaterial, materialJson, ruleDigest }\n })\n\n const prepareAssessment = Effect.fn(\"ReadinessCodec.prepareAssessment\")(function*(\n assessment: ReadinessAssessmentType\n ) {\n const encoded = yield* encodeAssessment(assessment).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"readiness.encode-assessment\" }))\n )\n const computedCandidateDigest = yield* candidateDigest(assessment)\n const assessmentDigest = yield* digestJson(encoded)\n return {\n assessmentJson: encoded,\n assessmentDigest,\n computedCandidateDigest,\n evidenceIds: assessment.evidenceIds,\n sourcePluginConnectionIds: sourceIds(assessment),\n releaseChildren: assessment._tag === \"release\"\n ? assessment.environments.map(({ assessmentId, candidateDigest, environmentId }) => ({\n environmentId,\n environmentAssessmentId: assessmentId,\n environmentCandidateDigest: candidateDigest\n }))\n : []\n }\n })\n\n const malformedAssessment = (row: typeof ReadinessAssessmentRow.Type, diagnosticCode: string) =>\n new PersistedRecordError({\n workspaceId: row.workspaceId,\n recordKind: \"readiness-assessment\",\n recordKey: row.assessmentId,\n diagnosticCode\n })\n\n const decodeAssessmentRow = Effect.fn(\"ReadinessCodec.decodeAssessmentRow\")(function*(\n row: typeof ReadinessAssessmentRow.Type\n ) {\n const storedDigest = yield* digestJson(row.assessmentJson)\n if (storedDigest !== row.assessmentDigest) {\n return yield* malformedAssessment(row, \"readiness-assessment-digest-mismatch\")\n }\n const assessment = yield* decodeAssessment(row.assessmentJson).pipe(\n Effect.mapError(() => malformedAssessment(row, \"readiness-assessment-schema-invalid\"))\n )\n const scopeMatches = assessment._tag === row.scopeKind &&\n assessment.assessmentId === row.assessmentId &&\n assessment.candidate.workspaceId === row.workspaceId &&\n assessment.candidate.scope.releaseId === row.releaseId &&\n assessment.candidate.releaseRevision === row.releaseRevision &&\n assessment.candidate.artifactRevision === row.artifactRevision &&\n assessment.candidate.digest === row.candidateDigest &&\n assessment.rule.ruleId === row.ruleId &&\n assessment.rule.version === row.ruleVersion &&\n assessment.rule.digest === row.ruleDigest &&\n assessment.derivationVersion === row.derivationVersion &&\n assessment.previousAssessmentId === row.previousAssessmentId &&\n assessment.verdict === row.verdict &&\n encodeTimestamp(assessment.evaluatedAt) === row.evaluatedAt &&\n (assessment.nextEvaluationAt === null\n ? row.nextEvaluationAt === null\n : encodeTimestamp(assessment.nextEvaluationAt) === row.nextEvaluationAt) &&\n (assessment._tag === \"release\"\n ? row.environmentId === null\n : assessment.candidate.scope.environmentId === row.environmentId)\n if (!scopeMatches) {\n return yield* malformedAssessment(row, \"readiness-assessment-identity-mismatch\")\n }\n const computedCandidateDigest = yield* candidateDigest(assessment).pipe(\n Effect.mapError(() => malformedAssessment(row, \"readiness-candidate-digest-mismatch\"))\n )\n if (computedCandidateDigest !== assessment.candidate.digest) {\n return yield* malformedAssessment(row, \"readiness-candidate-digest-mismatch\")\n }\n return assessment\n })\n\n const decodeRuleRow = Effect.fn(\"ReadinessCodec.decodeRuleRow\")(function*(row: typeof ReadinessRuleRow.Type) {\n const malformed = (diagnosticCode: string) =>\n new PersistedRecordError({\n workspaceId: row.workspaceId,\n recordKind: \"readiness-rule\",\n recordKey: row.ruleDigest.slice(7),\n diagnosticCode\n })\n const material = yield* decodeRule(row.materialJson).pipe(\n Effect.mapError(() => malformed(\"readiness-rule-schema-invalid\"))\n )\n if (material.ruleId !== row.ruleId || material.version !== row.ruleVersion) {\n return yield* malformed(\"readiness-rule-identity-mismatch\")\n }\n const digest = yield* digestReadinessRule(material).pipe(\n Effect.mapError(() => malformed(\"readiness-rule-digest-mismatch\"))\n )\n if (digest !== row.ruleDigest) return yield* malformed(\"readiness-rule-digest-mismatch\")\n return material\n })\n\n return {\n candidateDigest,\n decodeAssessmentRow,\n decodeRuleRow,\n digestJson,\n prepareAssessment,\n prepareRule\n }\n})\n","import * as DateTime from \"effect/DateTime\"\nimport * as Schema from \"effect/Schema\"\n\nimport {\n EnvironmentId,\n EvidenceId,\n PluginConnectionId,\n ReleaseId,\n WorkspaceId\n} from \"../../../../domain/identifiers.js\"\nimport {\n EnvironmentReadinessAssessment,\n ReadinessCandidateDigest,\n ReadinessRuleMaterial,\n ReleaseReadinessAssessment\n} from \"../../../../domain/readiness/index.js\"\nimport { UtcTimestamp } from \"../../../../domain/utcTimestamp.js\"\n\nconst boundedText = (maximumLength: number, identifier: string) =>\n Schema.String.check(Schema.isTrimmed(), Schema.isNonEmpty(), Schema.isMaxLength(maximumLength)).annotate({\n identifier\n })\n\n/** Positive optimistic-concurrency revision of one readiness-assessment head. */\nexport const ReadinessHeadRevision = Schema.Int.check(Schema.isGreaterThan(0)).pipe(\n Schema.brand(\"ReadinessHeadRevision\")\n)\n\n/** Decoded readiness-assessment head revision. */\nexport type ReadinessHeadRevision = typeof ReadinessHeadRevision.Type\n\n/** Positive monotonic revision of one coalesced readiness invalidation. */\nexport const ReadinessInvalidationRevision = Schema.Int.check(Schema.isGreaterThan(0)).pipe(\n Schema.brand(\"ReadinessInvalidationRevision\")\n)\n\n/** Decoded readiness-invalidation revision. */\nexport type ReadinessInvalidationRevision = typeof ReadinessInvalidationRevision.Type\n\n/** Stable identity of one readiness-invalidation worker lease. */\nexport const ReadinessLeaseOwner = boundedText(200, \"ReadinessLeaseOwner\").pipe(Schema.brand(\"ReadinessLeaseOwner\"))\n\n/** Decoded readiness lease-owner identity. */\nexport type ReadinessLeaseOwner = typeof ReadinessLeaseOwner.Type\n\n/** Storage-generated fencing token for one exact readiness lease generation. */\nexport const ReadinessLeaseToken = boundedText(200, \"ReadinessLeaseToken\").pipe(\n Schema.brand(\"ReadinessLeaseToken\")\n)\n\n/** Decoded readiness lease fencing token. */\nexport type ReadinessLeaseToken = typeof ReadinessLeaseToken.Type\n\n/** Closed machine-readable reason for reevaluating readiness. */\nexport const ReadinessInvalidationReason = Schema.Literals([\n \"evidence-changed\",\n \"plugin-health-changed\",\n \"rule-changed\",\n \"candidate-changed\",\n \"scheduled\",\n \"environment-assessment-changed\"\n])\n\n/** Decoded readiness-invalidation reason. */\nexport type ReadinessInvalidationReason = typeof ReadinessInvalidationReason.Type\n\n/** Bounded number of immutable assessments returned by one history read. */\nexport const ReadinessHistoryLimit = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 200 })).pipe(\n Schema.brand(\"ReadinessHistoryLimit\")\n)\n\n/** Decoded readiness-history page size. */\nexport type ReadinessHistoryLimit = typeof ReadinessHistoryLimit.Type\n\n/** Bounded caller or integrity failure at the readiness repository boundary. */\nexport class ReadinessInputError extends Schema.TaggedErrorClass<ReadinessInputError>()(\"ReadinessInputError\", {\n operation: Schema.Literals([\n \"register-rule\",\n \"commit-environment\",\n \"commit-release\",\n \"read-current\",\n \"read-current-releases\",\n \"read-history\",\n \"enqueue-invalidation\",\n \"claim-invalidation\",\n \"enqueue-affected\",\n \"enqueue-due\"\n ]),\n reason: Schema.Literals([\n \"invalid-request\",\n \"candidate-digest-mismatch\",\n \"rule-digest-mismatch\",\n \"rule-definition-mismatch\",\n \"stale-invalidation\"\n ])\n}) {}\n\n/** Immutable, digest-bound readiness rule stored within one workspace. */\nexport const ReadinessRuleRecord = Schema.Struct({\n workspaceId: WorkspaceId,\n material: ReadinessRuleMaterial,\n digest: ReadinessCandidateDigest,\n registeredAt: UtcTimestamp\n})\n\n/** Decoded persisted readiness-rule record. */\nexport type ReadinessRuleRecord = typeof ReadinessRuleRecord.Type\n\n/** Request to idempotently register one immutable readiness-rule snapshot. */\nexport const RegisterReadinessRuleRequest = ReadinessRuleRecord\n\n/** Decoded immutable readiness-rule registration request. */\nexport type RegisterReadinessRuleRequest = typeof RegisterReadinessRuleRequest.Type\n\n/** Outcome of registering an immutable rule or finding its exact existing record. */\nexport const RegisterReadinessRuleResult = Schema.TaggedUnion({\n created: { record: ReadinessRuleRecord },\n existing: { record: ReadinessRuleRecord }\n})\n\n/** Decoded immutable readiness-rule registration outcome. */\nexport type RegisterReadinessRuleResult = typeof RegisterReadinessRuleResult.Type\n\n/** Persisted immutable environment assessment at one subject-head revision. */\nexport const EnvironmentReadinessAssessmentRecord = Schema.Struct({\n headRevision: ReadinessHeadRevision,\n assessment: EnvironmentReadinessAssessment,\n committedAt: UtcTimestamp\n})\n\n/** Decoded persisted environment-readiness assessment. */\nexport type EnvironmentReadinessAssessmentRecord = typeof EnvironmentReadinessAssessmentRecord.Type\n\n/** Persisted immutable release assessment at one subject-head revision. */\nexport const ReleaseReadinessAssessmentRecord = Schema.Struct({\n headRevision: ReadinessHeadRevision,\n assessment: ReleaseReadinessAssessment,\n committedAt: UtcTimestamp\n})\n\n/** Decoded persisted release-readiness assessment. */\nexport type ReleaseReadinessAssessmentRecord = typeof ReleaseReadinessAssessmentRecord.Type\n\n/** Exact leased invalidation a worker must consume with its assessment commit. */\nexport const ReadinessCommitLease = Schema.Struct({\n invalidationRevision: ReadinessInvalidationRevision,\n leaseOwner: ReadinessLeaseOwner,\n leaseToken: ReadinessLeaseToken\n})\n\n/** Decoded exact leased invalidation used by a readiness commit. */\nexport type ReadinessCommitLease = typeof ReadinessCommitLease.Type\n\n/** Compare-and-swap request for an immutable environment assessment. */\nexport const CommitEnvironmentReadinessAssessmentRequest = Schema.Struct({\n expectedHeadRevision: Schema.NullOr(ReadinessHeadRevision),\n invalidation: Schema.NullOr(ReadinessCommitLease),\n assessment: EnvironmentReadinessAssessment\n}).check(\n Schema.makeFilter(\n ({ assessment, expectedHeadRevision }) =>\n (expectedHeadRevision === null) === (assessment.previousAssessmentId === null),\n { expected: \"a create commit without a predecessor and an update commit with one\" }\n )\n)\n\n/** Decoded environment-readiness commit request. */\nexport type CommitEnvironmentReadinessAssessmentRequest = typeof CommitEnvironmentReadinessAssessmentRequest.Type\n\n/** Environment-readiness record committed at the new head revision. */\nexport const CommitEnvironmentReadinessAssessmentResult = EnvironmentReadinessAssessmentRecord\n\n/** Decoded environment-readiness commit result. */\nexport type CommitEnvironmentReadinessAssessmentResult = typeof CommitEnvironmentReadinessAssessmentResult.Type\n\n/** Compare-and-swap request for an immutable release assessment. */\nexport const CommitReleaseReadinessAssessmentRequest = Schema.Struct({\n expectedHeadRevision: Schema.NullOr(ReadinessHeadRevision),\n invalidation: Schema.NullOr(ReadinessCommitLease),\n assessment: ReleaseReadinessAssessment\n}).check(\n Schema.makeFilter(\n ({ assessment, expectedHeadRevision }) =>\n (expectedHeadRevision === null) === (assessment.previousAssessmentId === null),\n { expected: \"a create commit without a predecessor and an update commit with one\" }\n )\n)\n\n/** Decoded release-readiness commit request. */\nexport type CommitReleaseReadinessAssessmentRequest = typeof CommitReleaseReadinessAssessmentRequest.Type\n\n/** Release-readiness record committed at the new head revision. */\nexport const CommitReleaseReadinessAssessmentResult = ReleaseReadinessAssessmentRecord\n\n/** Decoded release-readiness commit result. */\nexport type CommitReleaseReadinessAssessmentResult = typeof CommitReleaseReadinessAssessmentResult.Type\n\n/** Exhaustive environment or release subject addressed by readiness persistence. */\nexport const ReadinessAssessmentTarget = Schema.TaggedUnion({\n environment: {\n workspaceId: WorkspaceId,\n releaseId: ReleaseId,\n environmentId: EnvironmentId\n },\n release: {\n workspaceId: WorkspaceId,\n releaseId: ReleaseId\n }\n})\n\n/** Decoded readiness-assessment target. */\nexport type ReadinessAssessmentTarget = typeof ReadinessAssessmentTarget.Type\n\n/** Whether a current readiness verdict may be used for governed decisions. */\nexport const ReadinessAssessmentAuthority = Schema.Literals([\"authoritative\", \"pending\"])\n\n/** Decoded authority state for a current readiness verdict. */\nexport type ReadinessAssessmentAuthority = typeof ReadinessAssessmentAuthority.Type\n\n/** Current environment assessment plus its atomic invalidation authority state. */\nexport const CurrentEnvironmentReadinessAssessmentRecord = Schema.Struct({\n ...EnvironmentReadinessAssessmentRecord.fields,\n authority: ReadinessAssessmentAuthority\n})\n\n/** Decoded current environment readiness record. */\nexport type CurrentEnvironmentReadinessAssessmentRecord = typeof CurrentEnvironmentReadinessAssessmentRecord.Type\n\n/** Current release assessment plus its atomic invalidation authority state. */\nexport const CurrentReleaseReadinessAssessmentRecord = Schema.Struct({\n ...ReleaseReadinessAssessmentRecord.fields,\n authority: ReadinessAssessmentAuthority\n})\n\n/** Decoded current release readiness record. */\nexport type CurrentReleaseReadinessAssessmentRecord = typeof CurrentReleaseReadinessAssessmentRecord.Type\n\n/** Request for the current environment or release readiness head. */\nexport const ReadCurrentReadinessAssessmentRequest = ReadinessAssessmentTarget\n\n/** Decoded current-readiness request. */\nexport type ReadCurrentReadinessAssessmentRequest = typeof ReadCurrentReadinessAssessmentRequest.Type\n\n/** Scope-preserving result of reading a current readiness head. */\nexport const ReadCurrentReadinessAssessmentResult = Schema.TaggedUnion({\n environment: { record: Schema.NullOr(CurrentEnvironmentReadinessAssessmentRecord) },\n release: { record: Schema.NullOr(CurrentReleaseReadinessAssessmentRecord) }\n})\n\n/** Decoded current-readiness result. */\nexport type ReadCurrentReadinessAssessmentResult = typeof ReadCurrentReadinessAssessmentResult.Type\n\n/** Maximum release heads accepted by one bounded current-readiness batch read. */\nexport const MAXIMUM_CURRENT_RELEASE_READINESS_BATCH = 200\n\n/** Request for current release readiness heads within one workspace. */\nexport const ReadCurrentReleaseReadinessAssessmentsRequest = Schema.Struct({\n workspaceId: WorkspaceId,\n releaseIds: Schema.Array(ReleaseId).check(\n Schema.isMaxLength(MAXIMUM_CURRENT_RELEASE_READINESS_BATCH),\n Schema.makeFilter((releaseIds) => new Set(releaseIds).size === releaseIds.length, {\n expected: \"unique release identifiers\"\n })\n )\n})\n\n/** Decoded bounded current release-readiness batch request. */\nexport type ReadCurrentReleaseReadinessAssessmentsRequest = typeof ReadCurrentReleaseReadinessAssessmentsRequest.Type\n\n/** Existing current release heads returned in release-identifier order. */\nexport const ReadCurrentReleaseReadinessAssessmentsResult = Schema.Array(\n CurrentReleaseReadinessAssessmentRecord\n).check(Schema.isMaxLength(MAXIMUM_CURRENT_RELEASE_READINESS_BATCH))\n\n/** Decoded current release-readiness batch result. */\nexport type ReadCurrentReleaseReadinessAssessmentsResult = typeof ReadCurrentReleaseReadinessAssessmentsResult.Type\n\n/** Exclusive-cursor request for newest-first immutable readiness history. */\nexport const ReadReadinessHistoryRequest = Schema.TaggedUnion({\n environment: {\n workspaceId: WorkspaceId,\n releaseId: ReleaseId,\n environmentId: EnvironmentId,\n beforeHeadRevision: Schema.NullOr(ReadinessHeadRevision),\n limit: ReadinessHistoryLimit\n },\n release: {\n workspaceId: WorkspaceId,\n releaseId: ReleaseId,\n beforeHeadRevision: Schema.NullOr(ReadinessHeadRevision),\n limit: ReadinessHistoryLimit\n }\n})\n\n/** Decoded readiness-history request. */\nexport type ReadReadinessHistoryRequest = typeof ReadReadinessHistoryRequest.Type\n\n/** Scope-preserving page of newest-first immutable readiness history. */\nexport const ReadReadinessHistoryResult = Schema.TaggedUnion({\n environment: {\n records: Schema.Array(EnvironmentReadinessAssessmentRecord).check(Schema.isMaxLength(200)),\n nextBeforeHeadRevision: Schema.NullOr(ReadinessHeadRevision)\n },\n release: {\n records: Schema.Array(ReleaseReadinessAssessmentRecord).check(Schema.isMaxLength(200)),\n nextBeforeHeadRevision: Schema.NullOr(ReadinessHeadRevision)\n }\n})\n\n/** Decoded readiness-history page. */\nexport type ReadReadinessHistoryResult = typeof ReadReadinessHistoryResult.Type\n\n/** Active worker ownership of one exact readiness-invalidation revision. */\nexport const ReadinessInvalidationLease = Schema.Struct({\n owner: ReadinessLeaseOwner,\n token: ReadinessLeaseToken,\n claimedAt: UtcTimestamp,\n expiresAt: UtcTimestamp\n}).check(\n Schema.makeFilter(({ claimedAt, expiresAt }) => DateTime.Order(claimedAt, expiresAt) < 0, {\n expected: \"a readiness invalidation lease to expire after it is claimed\"\n })\n)\n\n/** Decoded readiness-invalidation lease. */\nexport type ReadinessInvalidationLease = typeof ReadinessInvalidationLease.Type\n\nconst ReadinessInvalidationRecordFields = {\n invalidationRevision: ReadinessInvalidationRevision,\n reason: ReadinessInvalidationReason,\n enqueuedAt: UtcTimestamp,\n lease: Schema.NullOr(ReadinessInvalidationLease)\n}\n\n/** Coalesced environment or release invalidation with its exact monotonic revision. */\nexport const ReadinessInvalidationRecord = Schema.TaggedUnion({\n environment: {\n workspaceId: WorkspaceId,\n releaseId: ReleaseId,\n environmentId: EnvironmentId,\n ...ReadinessInvalidationRecordFields\n },\n release: {\n workspaceId: WorkspaceId,\n releaseId: ReleaseId,\n ...ReadinessInvalidationRecordFields\n }\n})\n\n/** Decoded readiness-invalidation record. */\nexport type ReadinessInvalidationRecord = typeof ReadinessInvalidationRecord.Type\n\n/** Request to enqueue or advance a coalesced environment or release invalidation. */\nexport const EnqueueReadinessInvalidationRequest = Schema.TaggedUnion({\n environment: {\n workspaceId: WorkspaceId,\n releaseId: ReleaseId,\n environmentId: EnvironmentId,\n reason: Schema.Literals([\n \"evidence-changed\",\n \"plugin-health-changed\",\n \"rule-changed\",\n \"candidate-changed\",\n \"scheduled\"\n ]),\n enqueuedAt: UtcTimestamp\n },\n release: {\n workspaceId: WorkspaceId,\n releaseId: ReleaseId,\n reason: Schema.Literals([\"environment-assessment-changed\", \"rule-changed\", \"candidate-changed\"]),\n enqueuedAt: UtcTimestamp\n }\n})\n\n/** Decoded readiness-invalidation enqueue request. */\nexport type EnqueueReadinessInvalidationRequest = typeof EnqueueReadinessInvalidationRequest.Type\n\n/** Invalidation record created or revision-advanced by an enqueue. */\nexport const EnqueueReadinessInvalidationResult = ReadinessInvalidationRecord\n\n/** Decoded readiness-invalidation enqueue result. */\nexport type EnqueueReadinessInvalidationResult = typeof EnqueueReadinessInvalidationResult.Type\n\n/** Exact evidence or plugin-health change used to invalidate only dependent current heads. */\nexport const EnqueueAffectedReadinessRequest = Schema.TaggedUnion({\n evidence: {\n workspaceId: WorkspaceId,\n evidenceId: EvidenceId,\n enqueuedAt: UtcTimestamp\n },\n plugin: {\n workspaceId: WorkspaceId,\n pluginConnectionId: PluginConnectionId,\n enqueuedAt: UtcTimestamp\n }\n})\n\n/** Decoded dependency-scoped readiness invalidation request. */\nexport type EnqueueAffectedReadinessRequest = typeof EnqueueAffectedReadinessRequest.Type\n\n/** Counts of current environment and release subjects invalidated by one dependency change. */\nexport const EnqueueAffectedReadinessResult = Schema.Struct({\n environments: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n releases: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))\n})\n\n/** Decoded dependency-scoped readiness invalidation result. */\nexport type EnqueueAffectedReadinessResult = typeof EnqueueAffectedReadinessResult.Type\n\nconst ClaimReadinessInvalidationFields = {\n expectedInvalidationRevision: ReadinessInvalidationRevision,\n leaseOwner: ReadinessLeaseOwner,\n leaseExpiresAt: UtcTimestamp\n}\n\n/** Compare-and-swap request to lease one exact readiness-invalidation revision. */\nexport const ClaimReadinessInvalidationRequest = Schema.TaggedUnion({\n environment: {\n workspaceId: WorkspaceId,\n releaseId: ReleaseId,\n environmentId: EnvironmentId,\n ...ClaimReadinessInvalidationFields\n },\n release: {\n workspaceId: WorkspaceId,\n releaseId: ReleaseId,\n ...ClaimReadinessInvalidationFields\n }\n})\n\n/** Decoded readiness-invalidation claim request. */\nexport type ClaimReadinessInvalidationRequest = typeof ClaimReadinessInvalidationRequest.Type\n\n/** Exact leased invalidation, or null when the compare-and-swap claim lost. */\nexport const ClaimReadinessInvalidationResult = Schema.NullOr(ReadinessInvalidationRecord)\n\n/** Decoded readiness-invalidation claim result. */\nexport type ClaimReadinessInvalidationResult = typeof ClaimReadinessInvalidationResult.Type\n\n/** Bounded due-schedule sweep for one workspace. */\nexport const EnqueueDueReadinessEvaluationsRequest = Schema.Struct({\n workspaceId: WorkspaceId,\n dueAt: UtcTimestamp,\n limit: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 500 }))\n})\n\n/** Decoded due-schedule sweep request. */\nexport type EnqueueDueReadinessEvaluationsRequest = typeof EnqueueDueReadinessEvaluationsRequest.Type\n\n/** Number of exact due schedules promoted to coalesced environment invalidations. */\nexport const EnqueueDueReadinessEvaluationsResult = Schema.Struct({\n enqueued: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 500 }))\n})\n\n/** Decoded due-schedule sweep result. */\nexport type EnqueueDueReadinessEvaluationsResult = typeof EnqueueDueReadinessEvaluationsResult.Type\n","import * as Effect from \"effect/Effect\"\nimport * as Predicate from \"effect/Predicate\"\n\nimport type { PersistedRecordError } from \"../../errors.js\"\nimport type { QuarantineDiagnosticSummary, QuarantineReasonCode, QuarantineRecordKind } from \"../models.js\"\n\ntype ReadinessQuarantineRecordKind = Extract<\n QuarantineRecordKind,\n \"readiness-assessment\" | \"readiness-environment-head\" | \"readiness-release-head\" | \"readiness-rule\"\n>\n\ninterface ReadinessQuarantineDiagnostic {\n readonly diagnosticCode: QuarantineReasonCode\n readonly diagnosticSummary: QuarantineDiagnosticSummary\n readonly recordKind: ReadinessQuarantineRecordKind\n}\n\n/** Internal carrier that keeps malformed readiness values out of the public error channel. */\nexport class MalformedReadinessRecord {\n readonly _tag = \"MalformedReadinessRecord\"\n readonly error: PersistedRecordError\n readonly row: unknown\n\n constructor(error: PersistedRecordError, row: unknown) {\n this.error = error\n this.row = row\n }\n}\n\n/** Attach an ephemeral raw row to a bounded readiness decode failure for quarantine after commit. */\nexport const captureMalformedReadinessRow =\n (row: unknown) => <Success, Failure, Requirements>(effect: Effect.Effect<Success, Failure, Requirements>) =>\n Effect.catchIf(\n effect,\n (failure): failure is Failure & PersistedRecordError => Predicate.isTagged(\"PersistedRecordError\")(failure),\n (error) => Effect.fail(new MalformedReadinessRecord(error, row))\n )\n\nconst isReadinessHeadRecordKind = (\n recordKind: string\n): recordKind is Extract<ReadinessQuarantineRecordKind, \"readiness-environment-head\" | \"readiness-release-head\"> => {\n switch (recordKind) {\n case \"readiness-environment-head\":\n case \"readiness-release-head\":\n return true\n default:\n return false\n }\n}\n\n/** Translate readiness decode failures into the fixed metadata accepted by quarantine storage. */\nexport const readinessQuarantineDiagnostic = (error: PersistedRecordError): ReadinessQuarantineDiagnostic | null => {\n switch (error.diagnosticCode) {\n case \"readiness-rule-schema-invalid\":\n return {\n recordKind: \"readiness-rule\",\n diagnosticCode: \"readiness-rule-schema-invalid\",\n diagnosticSummary: \"Stored readiness rule failed schema validation.\"\n }\n case \"readiness-rule-digest-mismatch\":\n return {\n recordKind: \"readiness-rule\",\n diagnosticCode: \"readiness-rule-digest-mismatch\",\n diagnosticSummary: \"Stored readiness rule digest does not match its canonical material.\"\n }\n case \"readiness-rule-identity-mismatch\":\n return {\n recordKind: \"readiness-rule\",\n diagnosticCode: \"readiness-rule-identity-mismatch\",\n diagnosticSummary: \"Stored readiness rule identity does not match its repository key.\"\n }\n case \"readiness-assessment-schema-invalid\":\n return {\n recordKind: \"readiness-assessment\",\n diagnosticCode: \"readiness-assessment-schema-invalid\",\n diagnosticSummary: \"Stored readiness assessment failed schema validation.\"\n }\n case \"readiness-assessment-digest-mismatch\":\n return {\n recordKind: \"readiness-assessment\",\n diagnosticCode: \"readiness-assessment-digest-mismatch\",\n diagnosticSummary: \"Stored readiness assessment digest does not match its content.\"\n }\n case \"readiness-candidate-digest-mismatch\":\n return {\n recordKind: \"readiness-assessment\",\n diagnosticCode: \"readiness-candidate-digest-mismatch\",\n diagnosticSummary: \"Stored readiness candidate digest does not match its canonical material.\"\n }\n case \"readiness-assessment-identity-mismatch\":\n return {\n recordKind: \"readiness-assessment\",\n diagnosticCode: \"readiness-assessment-identity-mismatch\",\n diagnosticSummary: \"Stored readiness assessment identity does not match its repository key.\"\n }\n case \"readiness-assessment-materialization-mismatch\":\n return {\n recordKind: \"readiness-assessment\",\n diagnosticCode: \"readiness-assessment-materialization-mismatch\",\n diagnosticSummary: \"Stored readiness assessment materialization does not match its canonical content.\"\n }\n case \"readiness-environment-head-schema-invalid\":\n return {\n recordKind: \"readiness-environment-head\",\n diagnosticCode: \"readiness-environment-head-schema-invalid\",\n diagnosticSummary: \"Stored environment readiness head failed schema validation.\"\n }\n case \"readiness-release-head-schema-invalid\":\n return {\n recordKind: \"readiness-release-head\",\n diagnosticCode: \"readiness-release-head-schema-invalid\",\n diagnosticSummary: \"Stored release readiness head failed schema validation.\"\n }\n case \"readiness-head-assessment-mismatch\":\n return isReadinessHeadRecordKind(error.recordKind)\n ? {\n recordKind: error.recordKind,\n diagnosticCode: \"readiness-head-assessment-mismatch\",\n diagnosticSummary: \"Stored readiness head does not match its referenced assessment.\"\n }\n : null\n default:\n return null\n }\n}\n","import * as Schema from \"effect/Schema\"\n\nimport {\n EnvironmentId,\n EvidenceId,\n PluginConnectionId,\n ReadinessAssessmentId,\n ReleaseId,\n WorkspaceId\n} from \"../../../../domain/identifiers.js\"\nimport {\n ReadinessArtifactRevision,\n ReadinessCandidateDigest,\n ReadinessDerivationVersion,\n ReadinessRuleId,\n ReadinessRuleVersion,\n ReadinessVerdict\n} from \"../../../../domain/readiness/index.js\"\nimport { ContentBlobDigest } from \"../models.js\"\n\n/** Driver row retained without trust until repository-controlled quarantine decoding. */\nexport const RawReadinessRow = Schema.Record(Schema.String, Schema.Unknown)\n\nexport const ReadinessRuleRow = Schema.Struct({\n workspaceId: WorkspaceId,\n ruleId: ReadinessRuleId,\n ruleVersion: ReadinessRuleVersion,\n ruleDigest: ReadinessCandidateDigest,\n materialJson: Schema.String,\n createdAt: Schema.String\n})\n\nexport const ReadinessAssessmentRow = Schema.Struct({\n workspaceId: WorkspaceId,\n assessmentId: ReadinessAssessmentId,\n scopeKind: Schema.Literals([\"environment\", \"release\"]),\n releaseId: ReleaseId,\n environmentId: Schema.NullOr(EnvironmentId),\n releaseRevision: Schema.Int,\n artifactRevision: ReadinessArtifactRevision,\n candidateDigest: ReadinessCandidateDigest,\n ruleId: ReadinessRuleId,\n ruleVersion: ReadinessRuleVersion,\n ruleDigest: ReadinessCandidateDigest,\n derivationVersion: ReadinessDerivationVersion,\n previousAssessmentId: Schema.NullOr(ReadinessAssessmentId),\n verdict: ReadinessVerdict,\n evaluatedAt: Schema.String,\n nextEvaluationAt: Schema.NullOr(Schema.String),\n assessmentJson: Schema.String,\n assessmentDigest: ContentBlobDigest\n})\n\nconst ReadinessHeadRowBase = {\n workspaceId: WorkspaceId,\n releaseId: ReleaseId,\n headRevision: Schema.Int,\n assessmentId: ReadinessAssessmentId,\n candidateDigest: ReadinessCandidateDigest,\n ruleId: ReadinessRuleId,\n ruleVersion: ReadinessRuleVersion,\n ruleDigest: ReadinessCandidateDigest,\n derivationVersion: ReadinessDerivationVersion,\n createdAt: Schema.String,\n updatedAt: Schema.String\n}\n\nexport const ReadinessEnvironmentHeadRow = Schema.Struct({\n ...ReadinessHeadRowBase,\n environmentId: EnvironmentId\n})\n\nexport const ReadinessReleaseHeadRow = Schema.Struct(ReadinessHeadRowBase)\n\nexport const ReadinessHistoryRow = Schema.Struct({\n headRevision: Schema.Int,\n committedAt: Schema.String,\n ...ReadinessAssessmentRow.fields\n})\n\nexport const ReadinessCurrentRow = Schema.Struct({\n ...ReadinessHistoryRow.fields,\n joinComplete: Schema.Literals([0, 1]),\n headWorkspaceId: WorkspaceId,\n headReleaseId: ReleaseId,\n headEnvironmentId: Schema.NullOr(EnvironmentId),\n headAssessmentId: ReadinessAssessmentId,\n headUpdatedAt: Schema.String,\n currentHeadRevision: Schema.Int,\n pendingCount: Schema.Int,\n headCandidateDigest: ReadinessCandidateDigest,\n headRuleId: ReadinessRuleId,\n headRuleVersion: ReadinessRuleVersion,\n headRuleDigest: ReadinessCandidateDigest,\n headDerivationVersion: ReadinessDerivationVersion\n})\n\nexport const ReadinessEvidenceDependencyRow = Schema.Struct({ evidenceId: EvidenceId })\n\nexport const ReadinessSourceDependencyRow = Schema.Struct({\n pluginConnectionId: PluginConnectionId\n})\n\nexport const ReadinessReleaseChildRow = Schema.Struct({\n environmentId: EnvironmentId,\n environmentAssessmentId: ReadinessAssessmentId,\n environmentCandidateDigest: ReadinessCandidateDigest\n})\n\nexport const ReadinessMaterializedEvidenceRow = Schema.Struct({\n assessmentId: ReadinessAssessmentId,\n evidenceId: EvidenceId\n})\n\nexport const ReadinessMaterializedSourceRow = Schema.Struct({\n assessmentId: ReadinessAssessmentId,\n pluginConnectionId: PluginConnectionId\n})\n\nexport const ReadinessMaterializedReleaseChildRow = Schema.Struct({\n assessmentId: ReadinessAssessmentId,\n ...ReadinessReleaseChildRow.fields\n})\n\nconst QueueRowBase = {\n workspaceId: WorkspaceId,\n releaseId: ReleaseId,\n invalidationRevision: Schema.Int,\n queuedAt: Schema.String,\n availableAt: Schema.String,\n attempts: Schema.Int,\n claimOwner: Schema.NullOr(Schema.String),\n claimToken: Schema.NullOr(Schema.String),\n claimExpiresAt: Schema.NullOr(Schema.String)\n}\n\nexport const ReadinessEnvironmentQueueRow = Schema.Struct({\n ...QueueRowBase,\n environmentId: EnvironmentId,\n reason: Schema.Literals([\n \"evidence-changed\",\n \"plugin-health-changed\",\n \"rule-changed\",\n \"candidate-changed\",\n \"scheduled\"\n ]),\n sourceEvidenceId: Schema.NullOr(EvidenceId),\n sourcePluginConnectionId: Schema.NullOr(PluginConnectionId)\n})\n\nexport const ReadinessReleaseQueueRow = Schema.Struct({\n ...QueueRowBase,\n reason: Schema.Literals([\"environment-assessment-changed\", \"rule-changed\", \"candidate-changed\"]),\n sourceEnvironmentId: Schema.NullOr(EnvironmentId)\n})\n","import * as Effect from \"effect/Effect\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\"\n\nimport type { ReadinessAssessmentId, WorkspaceId } from \"../../../../domain/identifiers.js\"\nimport type { ReadinessAssessment } from \"../../../../domain/readiness/index.js\"\nimport { Database } from \"../../Database.js\"\nimport { PersistedRecordError } from \"../../errors.js\"\nimport { captureMalformedReadinessRow } from \"./quarantine.js\"\nimport {\n RawReadinessRow,\n ReadinessMaterializedEvidenceRow,\n ReadinessMaterializedReleaseChildRow,\n ReadinessMaterializedSourceRow\n} from \"./rows.js\"\n\ntype EvidenceRow = typeof ReadinessMaterializedEvidenceRow.Type\ntype SourceRow = typeof ReadinessMaterializedSourceRow.Type\ntype ChildRow = typeof ReadinessMaterializedReleaseChildRow.Type\n\ninterface MaterializationRows {\n readonly evidence: ReadonlyArray<EvidenceRow>\n readonly sources: ReadonlyArray<SourceRow>\n readonly children: ReadonlyArray<ChildRow>\n}\n\nexport interface GroupedMaterialization {\n readonly evidence: ReadonlyMap<ReadinessAssessmentId, ReadonlyArray<EvidenceRow>>\n readonly sources: ReadonlyMap<ReadinessAssessmentId, ReadonlyArray<SourceRow>>\n readonly children: ReadonlyMap<ReadinessAssessmentId, ReadonlyArray<ChildRow>>\n}\n\nconst groupByAssessment = <Row extends { readonly assessmentId: ReadinessAssessmentId }>(\n rows: ReadonlyArray<Row>\n): ReadonlyMap<ReadinessAssessmentId, ReadonlyArray<Row>> => {\n const grouped = new Map<ReadinessAssessmentId, Array<Row>>()\n for (const row of rows) {\n const group = grouped.get(row.assessmentId)\n if (group === undefined) grouped.set(row.assessmentId, [row])\n else group.push(row)\n }\n return grouped\n}\n\n/** Index each persisted dependency exactly once before aggregate verification. */\nexport const groupReadinessMaterialization = (rows: MaterializationRows): GroupedMaterialization => ({\n evidence: groupByAssessment(rows.evidence),\n sources: groupByAssessment(rows.sources),\n children: groupByAssessment(rows.children)\n})\n\nexport const makeReadinessMaterialization = Effect.gen(function*() {\n const { sql } = yield* Database\n\n const malformed = (workspaceId: WorkspaceId, row: typeof RawReadinessRow.Type) =>\n new PersistedRecordError({\n workspaceId,\n recordKind: \"readiness-assessment\",\n recordKey: Predicate.hasProperty(row, \"assessmentId\") && typeof row.assessmentId === \"string\"\n ? row.assessmentId\n : \"unknown-materialization\",\n diagnosticCode: \"readiness-assessment-materialization-mismatch\"\n })\n\n const load = Effect.fn(\"ReadinessMaterialization.load\")(function*(input: {\n readonly workspaceId: WorkspaceId\n readonly assessmentIds: ReadonlyArray<ReadinessAssessmentId>\n }) {\n if (input.assessmentIds.length === 0) {\n return groupReadinessMaterialization({ evidence: [], sources: [], children: [] })\n }\n const evidenceRows = yield* SqlSchema.findAll({\n Request: Schema.Void,\n Result: RawReadinessRow,\n execute: () =>\n sql`SELECT assessment_id AS assessmentId, evidence_id AS evidenceId\n FROM readiness_assessment_evidence\n WHERE workspace_id = ${input.workspaceId}\n AND assessment_id IN ${sql.in(input.assessmentIds)}\n ORDER BY assessment_id, evidence_id`\n })(undefined)\n const sourceRows = yield* SqlSchema.findAll({\n Request: Schema.Void,\n Result: RawReadinessRow,\n execute: () =>\n sql`SELECT assessment_id AS assessmentId, plugin_connection_id AS pluginConnectionId\n FROM readiness_assessment_sources\n WHERE workspace_id = ${input.workspaceId}\n AND assessment_id IN ${sql.in(input.assessmentIds)}\n ORDER BY assessment_id, plugin_connection_id`\n })(undefined)\n const childRows = yield* SqlSchema.findAll({\n Request: Schema.Void,\n Result: RawReadinessRow,\n execute: () =>\n sql`SELECT release_assessment_id AS assessmentId, environment_id AS environmentId,\n environment_assessment_id AS environmentAssessmentId,\n environment_candidate_digest AS environmentCandidateDigest\n FROM readiness_release_children\n WHERE workspace_id = ${input.workspaceId}\n AND release_assessment_id IN ${sql.in(input.assessmentIds)}\n ORDER BY release_assessment_id, environment_id`\n })(undefined)\n const evidence = yield* Effect.forEach(\n evidenceRows,\n (row) =>\n Schema.decodeUnknownEffect(ReadinessMaterializedEvidenceRow)(row).pipe(\n Effect.mapError(() => malformed(input.workspaceId, row)),\n captureMalformedReadinessRow(row)\n )\n )\n const sources = yield* Effect.forEach(\n sourceRows,\n (row) =>\n Schema.decodeUnknownEffect(ReadinessMaterializedSourceRow)(row).pipe(\n Effect.mapError(() => malformed(input.workspaceId, row)),\n captureMalformedReadinessRow(row)\n )\n )\n const children = yield* Effect.forEach(\n childRows,\n (row) =>\n Schema.decodeUnknownEffect(ReadinessMaterializedReleaseChildRow)(row).pipe(\n Effect.mapError(() => malformed(input.workspaceId, row)),\n captureMalformedReadinessRow(row)\n )\n )\n return groupReadinessMaterialization({ evidence, sources, children })\n })\n\n const verify = Effect.fn(\"ReadinessMaterialization.verify\")(function*(\n assessment: ReadinessAssessment,\n row: unknown,\n grouped: Effect.Success<ReturnType<typeof load>>\n ) {\n const evidence = grouped.evidence.get(assessment.assessmentId) ?? []\n const sources = grouped.sources.get(assessment.assessmentId) ?? []\n const children = grouped.children.get(assessment.assessmentId) ?? []\n const expectedChildren = assessment._tag === \"release\"\n ? assessment.environments.map(({ assessmentId, candidateDigest, environmentId }) => ({\n assessmentId: assessment.assessmentId,\n environmentId,\n environmentAssessmentId: assessmentId,\n environmentCandidateDigest: candidateDigest\n }))\n : []\n const matches = JSON.stringify(evidence.map(({ assessmentId, evidenceId }) => ({ assessmentId, evidenceId }))) ===\n JSON.stringify(\n assessment.evidenceIds.map((evidenceId) => ({ assessmentId: assessment.assessmentId, evidenceId }))\n ) &&\n JSON.stringify(sources.map(({ assessmentId, pluginConnectionId }) => ({ assessmentId, pluginConnectionId }))) ===\n JSON.stringify(\n assessment.sourceFreshness.map(({ pluginConnectionId }) => ({\n assessmentId: assessment.assessmentId,\n pluginConnectionId\n }))\n ) &&\n JSON.stringify(children) === JSON.stringify(expectedChildren)\n if (!matches) {\n return yield* captureMalformedReadinessRow(row)(\n Effect.fail(\n new PersistedRecordError({\n workspaceId: assessment.candidate.workspaceId,\n recordKind: \"readiness-assessment\",\n recordKey: assessment.assessmentId,\n diagnosticCode: \"readiness-assessment-materialization-mismatch\"\n })\n )\n )\n }\n })\n\n return { load, verify }\n})\n","import * as Effect from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\nimport * as Schema from \"effect/Schema\"\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\"\n\nimport type {\n ReadinessRuleId,\n ReadinessRuleMaterial,\n ReadinessRuleVersion\n} from \"../../../../domain/readiness/index.js\"\nimport { UtcTimestamp } from \"../../../../domain/utcTimestamp.js\"\nimport { Database } from \"../../Database.js\"\nimport { PersistedRecordError, RecordNotFoundError } from \"../../errors.js\"\nimport { readChanges } from \"../internal.js\"\nimport { makeReadinessCodec } from \"./codec.js\"\nimport { ReadinessInputError, RegisterReadinessRuleRequest, type RegisterReadinessRuleResult } from \"./contract.js\"\nimport { captureMalformedReadinessRow } from \"./quarantine.js\"\nimport { RawReadinessRow, ReadinessRuleRow } from \"./rows.js\"\n\nconst RuleKey = Schema.Struct({\n workspaceId: RegisterReadinessRuleRequest.fields.workspaceId,\n ruleId: RegisterReadinessRuleRequest.fields.material.fields.ruleId,\n ruleVersion: RegisterReadinessRuleRequest.fields.material.fields.version\n})\n\nconst InsertRule = Schema.Struct({\n ...RuleKey.fields,\n ruleDigest: RegisterReadinessRuleRequest.fields.digest,\n materialJson: Schema.String,\n createdAt: UtcTimestamp\n})\n\nexport const makeReadinessRules = Effect.gen(function*() {\n const database = yield* Database\n const codec = yield* makeReadinessCodec\n const sql = database.sql\n\n const findRule = SqlSchema.findOneOption({\n Request: RuleKey,\n Result: RawReadinessRow,\n execute: ({ ruleId, ruleVersion, workspaceId }) =>\n sql`SELECT workspace_id AS workspaceId,\n rule_id AS ruleId,\n rule_version AS ruleVersion,\n rule_digest AS ruleDigest,\n material_json AS materialJson,\n created_at AS createdAt\n FROM readiness_rule_snapshots\n WHERE workspace_id = ${workspaceId}\n AND rule_id = ${ruleId}\n AND rule_version = ${ruleVersion}`\n })\n\n const insertRule = SqlSchema.void({\n Request: InsertRule,\n execute: ({ createdAt, materialJson, ruleDigest, ruleId, ruleVersion, workspaceId }) =>\n sql`INSERT INTO readiness_rule_snapshots (\n workspace_id, rule_id, rule_version, rule_digest, material_json, created_at\n ) VALUES (\n ${workspaceId}, ${ruleId}, ${ruleVersion}, ${ruleDigest}, ${materialJson}, ${createdAt}\n ) ON CONFLICT (workspace_id, rule_id, rule_version) DO NOTHING`\n })\n\n const decodeStoredRule = Effect.fn(\"ReadinessRules.decodeStoredRule\")(function*(\n row: typeof RawReadinessRow.Type,\n key: typeof RuleKey.Type\n ) {\n const malformed = () =>\n new PersistedRecordError({\n workspaceId: key.workspaceId,\n recordKind: \"readiness-rule\",\n recordKey: `${key.ruleId}:${key.ruleVersion}`,\n diagnosticCode: \"readiness-rule-schema-invalid\"\n })\n const decodedRow = yield* Schema.decodeUnknownEffect(ReadinessRuleRow)(row).pipe(\n Effect.mapError(malformed),\n captureMalformedReadinessRow(row)\n )\n const material = yield* codec.decodeRuleRow(decodedRow).pipe(captureMalformedReadinessRow(row))\n const registeredAt = yield* Schema.decodeUnknownEffect(UtcTimestamp)(decodedRow.createdAt).pipe(\n Effect.mapError(malformed),\n captureMalformedReadinessRow(row)\n )\n return { material, registeredAt, row: decodedRow }\n })\n\n const loadRule = Effect.fn(\"ReadinessRules.load\")(function*(input: {\n readonly workspaceId: (typeof RuleKey.Type)[\"workspaceId\"]\n readonly ruleId: ReadinessRuleId\n readonly ruleVersion: ReadinessRuleVersion\n }) {\n const found = yield* findRule(input)\n if (Option.isNone(found)) {\n return yield* new RecordNotFoundError({\n workspaceId: input.workspaceId,\n recordKind: \"readiness-rule\",\n recordKey: `${input.ruleId}:${input.ruleVersion}`\n })\n }\n return yield* decodeStoredRule(found.value, input)\n })\n\n const register = Effect.fn(\"ReadinessRules.register\")(function*(request: RegisterReadinessRuleRequest) {\n const prepared = yield* codec.prepareRule(request.material)\n if (prepared.ruleDigest !== request.digest) {\n return yield* new ReadinessInputError({\n operation: \"register-rule\",\n reason: \"rule-digest-mismatch\"\n })\n }\n const key = {\n workspaceId: request.workspaceId,\n ruleId: request.material.ruleId,\n ruleVersion: request.material.version\n }\n yield* insertRule({\n ...key,\n ruleDigest: request.digest,\n materialJson: prepared.materialJson,\n createdAt: request.registeredAt\n })\n if ((yield* readChanges(sql)) === 1) {\n return {\n _tag: \"created\",\n record: { ...request, material: prepared.material }\n } satisfies RegisterReadinessRuleResult\n }\n const existing = yield* findRule(key)\n if (Option.isNone(existing)) {\n return yield* new RecordNotFoundError({\n workspaceId: request.workspaceId,\n recordKind: \"readiness-rule\",\n recordKey: `${request.material.ruleId}:${request.material.version}`\n })\n }\n const stored = yield* decodeStoredRule(existing.value, key)\n if (\n stored.row.ruleDigest !== request.digest ||\n JSON.stringify(stored.material) !== JSON.stringify(prepared.material)\n ) {\n return yield* new ReadinessInputError({\n operation: \"register-rule\",\n reason: \"rule-digest-mismatch\"\n })\n }\n return {\n _tag: \"existing\",\n record: {\n workspaceId: request.workspaceId,\n material: stored.material,\n digest: stored.row.ruleDigest,\n registeredAt: stored.registeredAt\n }\n } satisfies RegisterReadinessRuleResult\n })\n\n const definitionsMatch = (\n material: ReadinessRuleMaterial,\n definitions: ReadonlyArray<ReadinessRuleMaterial[\"definitions\"][number]>\n ): boolean => JSON.stringify(material.definitions) === JSON.stringify(definitions)\n\n return { definitionsMatch, loadRule, register }\n})\n","import { renderCurrentReleaseReadinessQuery } from \"@knpkv/control-center-sql\"\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 Schema from \"effect/Schema\"\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\"\n\nimport { EnvironmentId, ReleaseId, type WorkspaceId } from \"../../../../domain/identifiers.js\"\nimport type {\n EnvironmentReadinessAssessment,\n ReadinessAssessment,\n ReadinessFactDefinition,\n ReadinessRuleMaterial,\n ReleaseReadinessAssessment\n} from \"../../../../domain/readiness/index.js\"\nimport { summarizeEnvironmentReadiness } from \"../../../../domain/readiness/index.js\"\nimport { UtcTimestamp } from \"../../../../domain/utcTimestamp.js\"\nimport { Database } from \"../../Database.js\"\nimport { PersistedRecordError, RevisionConflictError } from \"../../errors.js\"\nimport { mapPersistenceOperation, readChanges } from \"../internal.js\"\nimport { makeReadinessCodec } from \"./codec.js\"\nimport type {\n CommitEnvironmentReadinessAssessmentRequest,\n CommitReleaseReadinessAssessmentRequest,\n ReadCurrentReadinessAssessmentRequest,\n ReadCurrentReleaseReadinessAssessmentsRequest,\n ReadReadinessHistoryRequest\n} from \"./contract.js\"\nimport { ReadinessHeadRevision, ReadinessInputError } from \"./contract.js\"\nimport { makeReadinessMaterialization } from \"./materialization.js\"\nimport { captureMalformedReadinessRow } from \"./quarantine.js\"\nimport { RawReadinessRow, ReadinessCurrentRow, ReadinessHistoryRow } from \"./rows.js\"\nimport { makeReadinessRules } from \"./rules.js\"\n\nconst encodeTimestamp = Schema.encodeSync(UtcTimestamp)\nconst CurrentRevisionRow = Schema.Struct({\n revision: ReadinessHeadRevision,\n assessmentId: ReadinessCurrentRow.fields.assessmentId\n})\nconst CountRow = Schema.Struct({ count: Schema.Int })\nconst authorityOf = (pendingCount: number): \"authoritative\" | \"pending\" =>\n pendingCount === 0 ? \"authoritative\" : \"pending\"\n\nconst assessmentColumns = `\n assessment.workspace_id AS workspaceId,\n assessment.assessment_id AS assessmentId,\n assessment.scope_kind AS scopeKind,\n assessment.release_id AS releaseId,\n assessment.environment_id AS environmentId,\n assessment.release_revision AS releaseRevision,\n assessment.artifact_revision AS artifactRevision,\n assessment.candidate_digest AS candidateDigest,\n assessment.rule_id AS ruleId,\n assessment.rule_version AS ruleVersion,\n assessment.rule_digest AS ruleDigest,\n assessment.derivation_version AS derivationVersion,\n assessment.previous_assessment_id AS previousAssessmentId,\n assessment.verdict AS verdict,\n assessment.evaluated_at AS evaluatedAt,\n assessment.next_evaluation_at AS nextEvaluationAt,\n assessment.assessment_json AS assessmentJson,\n assessment.assessment_digest AS assessmentDigest`\n\nconst definitionsOf = (assessment: EnvironmentReadinessAssessment) =>\n assessment.facts.map(({ definition }) => definition)\n\nconst ruleMatchesAssessment = (\n assessment: ReadinessAssessment,\n definitionsMatch: (material: ReadinessRuleMaterial, definitions: ReadonlyArray<ReadinessFactDefinition>) => boolean,\n material: ReadinessRuleMaterial\n): boolean =>\n assessment._tag === \"environment\"\n ? definitionsMatch(material, definitionsOf(assessment))\n : assessment.environments.every(({ facts }) =>\n definitionsMatch(\n material,\n facts.map(({ definition }) => definition)\n )\n )\n\nexport const makeReadinessAssessments = Effect.gen(function*() {\n const database = yield* Database\n const codec = yield* makeReadinessCodec\n const materialization = yield* makeReadinessMaterialization\n const rules = yield* makeReadinessRules\n const sql = database.sql\n\n const countEnvironmentInvalidations = SqlSchema.findOne({\n Request: Schema.Struct({\n workspaceId: ReadinessCurrentRow.fields.workspaceId,\n releaseId: ReadinessCurrentRow.fields.releaseId,\n environmentId: EnvironmentId\n }),\n Result: CountRow,\n execute: ({ environmentId, releaseId, workspaceId }) =>\n sql`SELECT COUNT(*) AS count FROM readiness_environment_queue\n WHERE workspace_id = ${workspaceId} AND release_id = ${releaseId}\n AND environment_id = ${environmentId}`\n })\n\n const countReleaseInvalidations = SqlSchema.findOne({\n Request: Schema.Struct({\n workspaceId: ReadinessCurrentRow.fields.workspaceId,\n releaseId: ReadinessCurrentRow.fields.releaseId\n }),\n Result: CountRow,\n execute: ({ releaseId, workspaceId }) =>\n sql`SELECT COUNT(*) AS count FROM readiness_release_queue\n WHERE workspace_id = ${workspaceId} AND release_id = ${releaseId}`\n })\n\n const countReleaseEnvironmentInvalidations = SqlSchema.findOne({\n Request: Schema.Struct({\n workspaceId: ReadinessCurrentRow.fields.workspaceId,\n releaseId: ReadinessCurrentRow.fields.releaseId\n }),\n Result: CountRow,\n execute: ({ releaseId, workspaceId }) =>\n sql`SELECT COUNT(*) AS count FROM readiness_environment_queue\n WHERE workspace_id = ${workspaceId} AND release_id = ${releaseId}`\n })\n\n const findEnvironmentRevision = SqlSchema.findOneOption({\n Request: Schema.Struct({\n workspaceId: ReadinessCurrentRow.fields.workspaceId,\n releaseId: ReadinessCurrentRow.fields.releaseId,\n environmentId: EnvironmentId\n }),\n Result: CurrentRevisionRow,\n execute: ({ environmentId, releaseId, workspaceId }) =>\n sql`SELECT head_revision AS revision, assessment_id AS assessmentId\n FROM readiness_environment_heads\n WHERE workspace_id = ${workspaceId}\n AND release_id = ${releaseId}\n AND environment_id = ${environmentId}`\n })\n\n const findReleaseRevision = SqlSchema.findOneOption({\n Request: Schema.Struct({\n workspaceId: ReadinessCurrentRow.fields.workspaceId,\n releaseId: ReadinessCurrentRow.fields.releaseId\n }),\n Result: CurrentRevisionRow,\n execute: ({ releaseId, workspaceId }) =>\n sql`SELECT head_revision AS revision, assessment_id AS assessmentId\n FROM readiness_release_heads\n WHERE workspace_id = ${workspaceId} AND release_id = ${releaseId}`\n })\n\n const verifyExpectedHead = Effect.fn(\"ReadinessAssessments.verifyExpectedHead\")(function*(input: {\n readonly workspaceId: WorkspaceId\n readonly recordKey: string\n readonly expected: ReadinessHeadRevision | null\n readonly actual: Option.Option<typeof CurrentRevisionRow.Type>\n readonly previousAssessmentId: ReadinessAssessment[\"previousAssessmentId\"]\n }) {\n const actualRevision = Option.match(input.actual, {\n onNone: () => null,\n onSome: ({ revision }) => revision\n })\n if (actualRevision !== input.expected) {\n return yield* new RevisionConflictError({\n workspaceId: input.workspaceId,\n recordKind: \"readiness-head\",\n recordKey: input.recordKey,\n expectedRevision: input.expected ?? 0,\n actualRevision\n })\n }\n const actualAssessmentId = Option.match(input.actual, {\n onNone: () => null,\n onSome: ({ assessmentId }) => assessmentId\n })\n if (actualAssessmentId !== input.previousAssessmentId) {\n return yield* new ReadinessInputError({\n operation: input.recordKey.includes(\":\") ? \"commit-environment\" : \"commit-release\",\n reason: \"invalid-request\"\n })\n }\n })\n\n const insertAssessment = Effect.fn(\"ReadinessAssessments.insertAssessment\")(function*(input: {\n readonly assessment: ReadinessAssessment\n readonly assessmentJson: string\n readonly assessmentDigest: string\n }) {\n const { assessment } = input\n const environmentId = assessment._tag === \"environment\" ? assessment.candidate.scope.environmentId : null\n yield* sql`INSERT INTO readiness_assessments (\n workspace_id, assessment_id, scope_kind, release_id, environment_id,\n release_revision, artifact_revision, candidate_digest,\n rule_id, rule_version, rule_digest, derivation_version,\n previous_assessment_id, verdict, evaluated_at, next_evaluation_at,\n assessment_json, assessment_digest\n ) VALUES (\n ${assessment.candidate.workspaceId}, ${assessment.assessmentId}, ${assessment._tag},\n ${assessment.candidate.scope.releaseId}, ${environmentId},\n ${assessment.candidate.releaseRevision}, ${assessment.candidate.artifactRevision},\n ${assessment.candidate.digest}, ${assessment.rule.ruleId}, ${assessment.rule.version},\n ${assessment.rule.digest}, ${assessment.derivationVersion}, ${assessment.previousAssessmentId},\n ${assessment.verdict}, ${encodeTimestamp(assessment.evaluatedAt)},\n ${assessment.nextEvaluationAt === null ? null : encodeTimestamp(assessment.nextEvaluationAt)},\n ${input.assessmentJson}, ${input.assessmentDigest}\n )`\n })\n\n const materializeAssessment = Effect.fn(\"ReadinessAssessments.materialize\")(function*(input: {\n readonly assessment: ReadinessAssessment\n readonly evidenceIds: ReadonlyArray<string>\n readonly sourcePluginConnectionIds: ReadonlyArray<string>\n readonly releaseChildren: ReadonlyArray<{\n readonly environmentId: string\n readonly environmentAssessmentId: string\n readonly environmentCandidateDigest: string\n }>\n }) {\n const workspaceId = input.assessment.candidate.workspaceId\n yield* Effect.forEach(\n input.evidenceIds,\n (evidenceId) =>\n sql`INSERT INTO readiness_assessment_evidence (\n workspace_id, assessment_id, evidence_id\n ) VALUES (${workspaceId}, ${input.assessment.assessmentId}, ${evidenceId})`,\n { discard: true }\n )\n yield* Effect.forEach(\n input.sourcePluginConnectionIds,\n (pluginConnectionId) =>\n sql`INSERT INTO readiness_assessment_sources (\n workspace_id, assessment_id, plugin_connection_id\n ) VALUES (${workspaceId}, ${input.assessment.assessmentId}, ${pluginConnectionId})`,\n { discard: true }\n )\n yield* Effect.forEach(\n input.releaseChildren,\n (child) =>\n sql`INSERT INTO readiness_release_children (\n workspace_id, release_assessment_id, environment_id,\n environment_assessment_id, environment_candidate_digest\n ) VALUES (\n ${workspaceId}, ${input.assessment.assessmentId}, ${child.environmentId},\n ${child.environmentAssessmentId}, ${child.environmentCandidateDigest}\n )`,\n { discard: true }\n )\n })\n\n const insertHistory = Effect.fn(\"ReadinessAssessments.insertHistory\")(function*(input: {\n readonly assessment: ReadinessAssessment\n readonly headRevision: ReadinessHeadRevision\n readonly committedAt: UtcTimestamp\n }) {\n const environmentKey = input.assessment._tag === \"environment\" ? input.assessment.candidate.scope.environmentId : \"\"\n yield* sql`INSERT INTO readiness_head_history (\n workspace_id, scope_kind, release_id, environment_key,\n head_revision, assessment_id, committed_at\n ) VALUES (\n ${input.assessment.candidate.workspaceId}, ${input.assessment._tag},\n ${input.assessment.candidate.scope.releaseId}, ${environmentKey},\n ${input.headRevision}, ${input.assessment.assessmentId}, ${encodeTimestamp(input.committedAt)}\n )`\n })\n\n const publishEnvironmentHead = Effect.fn(\"ReadinessAssessments.publishEnvironmentHead\")(function*(input: {\n readonly assessment: EnvironmentReadinessAssessment\n readonly expected: ReadinessHeadRevision | null\n readonly headRevision: ReadinessHeadRevision\n readonly committedAt: UtcTimestamp\n }) {\n const assessment = input.assessment\n const timestamp = encodeTimestamp(input.committedAt)\n if (input.expected === null) {\n yield* sql`INSERT INTO readiness_environment_heads (\n workspace_id, release_id, environment_id, head_revision, assessment_id,\n candidate_digest, rule_id, rule_version, rule_digest, derivation_version,\n created_at, updated_at\n ) VALUES (\n ${assessment.candidate.workspaceId}, ${assessment.candidate.scope.releaseId},\n ${assessment.candidate.scope.environmentId}, ${input.headRevision}, ${assessment.assessmentId},\n ${assessment.candidate.digest}, ${assessment.rule.ruleId}, ${assessment.rule.version},\n ${assessment.rule.digest}, ${assessment.derivationVersion}, ${timestamp}, ${timestamp}\n )`.pipe(mapPersistenceOperation(\"readiness.insert-environment-head\"))\n } else {\n // The schedule FK names the exact current assessment, so remove it inside\n // the same transaction before advancing the mutable head.\n yield* sql`DELETE FROM readiness_evaluation_schedules\n WHERE workspace_id = ${assessment.candidate.workspaceId}\n AND release_id = ${assessment.candidate.scope.releaseId}\n AND environment_id = ${assessment.candidate.scope.environmentId}`\n yield* sql`UPDATE readiness_environment_heads\n SET head_revision = ${input.headRevision}, assessment_id = ${assessment.assessmentId},\n candidate_digest = ${assessment.candidate.digest}, rule_id = ${assessment.rule.ruleId},\n rule_version = ${assessment.rule.version}, rule_digest = ${assessment.rule.digest},\n derivation_version = ${assessment.derivationVersion}, updated_at = ${timestamp}\n WHERE workspace_id = ${assessment.candidate.workspaceId}\n AND release_id = ${assessment.candidate.scope.releaseId}\n AND environment_id = ${assessment.candidate.scope.environmentId}\n AND head_revision = ${input.expected}`\n if ((yield* readChanges(sql)) === 0) {\n const actual = yield* findEnvironmentRevision({\n workspaceId: assessment.candidate.workspaceId,\n releaseId: assessment.candidate.scope.releaseId,\n environmentId: assessment.candidate.scope.environmentId\n })\n return yield* new RevisionConflictError({\n workspaceId: assessment.candidate.workspaceId,\n recordKind: \"readiness-head\",\n recordKey: `${assessment.candidate.scope.releaseId}:${assessment.candidate.scope.environmentId}`,\n expectedRevision: input.expected,\n actualRevision: Option.match(actual, { onNone: () => null, onSome: ({ revision }) => revision })\n })\n }\n }\n if (assessment.nextEvaluationAt === null) {\n yield* sql`DELETE FROM readiness_evaluation_schedules\n WHERE workspace_id = ${assessment.candidate.workspaceId}\n AND release_id = ${assessment.candidate.scope.releaseId}\n AND environment_id = ${assessment.candidate.scope.environmentId}`\n } else {\n yield* sql`INSERT INTO readiness_evaluation_schedules (\n workspace_id, release_id, environment_id, assessment_id, due_at\n ) VALUES (\n ${assessment.candidate.workspaceId}, ${assessment.candidate.scope.releaseId},\n ${assessment.candidate.scope.environmentId}, ${assessment.assessmentId},\n ${encodeTimestamp(assessment.nextEvaluationAt)}\n ) ON CONFLICT (workspace_id, release_id, environment_id) DO UPDATE SET\n assessment_id = excluded.assessment_id, due_at = excluded.due_at`.pipe(\n mapPersistenceOperation(\"readiness.upsert-schedule\")\n )\n }\n yield* sql`INSERT INTO readiness_release_queue (\n workspace_id, release_id, invalidation_revision, reason, source_environment_id,\n queued_at, available_at, attempts, claim_owner, claim_token, claim_expires_at\n ) VALUES (\n ${assessment.candidate.workspaceId}, ${assessment.candidate.scope.releaseId}, 1,\n 'environment-assessment-changed', ${assessment.candidate.scope.environmentId},\n ${timestamp}, ${timestamp}, 0, NULL, NULL, NULL\n ) ON CONFLICT (workspace_id, release_id) DO UPDATE SET\n invalidation_revision = readiness_release_queue.invalidation_revision + 1,\n reason = excluded.reason, source_environment_id = excluded.source_environment_id,\n queued_at = excluded.queued_at, available_at = excluded.available_at,\n claim_owner = NULL, claim_token = NULL, claim_expires_at = NULL`.pipe(\n mapPersistenceOperation(\"readiness.enqueue-release-after-environment\")\n )\n })\n\n const publishReleaseHead = Effect.fn(\"ReadinessAssessments.publishReleaseHead\")(function*(input: {\n readonly assessment: ReleaseReadinessAssessment\n readonly expected: ReadinessHeadRevision | null\n readonly headRevision: ReadinessHeadRevision\n readonly committedAt: UtcTimestamp\n }) {\n const assessment = input.assessment\n const timestamp = encodeTimestamp(input.committedAt)\n if (input.expected === null) {\n yield* sql`INSERT INTO readiness_release_heads (\n workspace_id, release_id, head_revision, assessment_id, candidate_digest,\n rule_id, rule_version, rule_digest, derivation_version, created_at, updated_at\n ) VALUES (\n ${assessment.candidate.workspaceId}, ${assessment.candidate.scope.releaseId},\n ${input.headRevision}, ${assessment.assessmentId}, ${assessment.candidate.digest},\n ${assessment.rule.ruleId}, ${assessment.rule.version}, ${assessment.rule.digest},\n ${assessment.derivationVersion}, ${timestamp}, ${timestamp}\n )`\n } else {\n yield* sql`UPDATE readiness_release_heads\n SET head_revision = ${input.headRevision}, assessment_id = ${assessment.assessmentId},\n candidate_digest = ${assessment.candidate.digest}, rule_id = ${assessment.rule.ruleId},\n rule_version = ${assessment.rule.version}, rule_digest = ${assessment.rule.digest},\n derivation_version = ${assessment.derivationVersion}, updated_at = ${timestamp}\n WHERE workspace_id = ${assessment.candidate.workspaceId}\n AND release_id = ${assessment.candidate.scope.releaseId}\n AND head_revision = ${input.expected}`\n if ((yield* readChanges(sql)) === 0) {\n const actual = yield* findReleaseRevision({\n workspaceId: assessment.candidate.workspaceId,\n releaseId: assessment.candidate.scope.releaseId\n })\n return yield* new RevisionConflictError({\n workspaceId: assessment.candidate.workspaceId,\n recordKind: \"readiness-head\",\n recordKey: assessment.candidate.scope.releaseId,\n expectedRevision: input.expected,\n actualRevision: Option.match(actual, { onNone: () => null, onSome: ({ revision }) => revision })\n })\n }\n }\n })\n\n const prepareCommit = Effect.fn(\"ReadinessAssessments.prepareCommit\")(function*(\n assessment: ReadinessAssessment,\n operation: \"commit-environment\" | \"commit-release\"\n ) {\n const prepared = yield* codec.prepareAssessment(assessment)\n if (prepared.computedCandidateDigest !== assessment.candidate.digest) {\n return yield* new ReadinessInputError({ operation, reason: \"candidate-digest-mismatch\" })\n }\n const rule = yield* rules.loadRule({\n workspaceId: assessment.candidate.workspaceId,\n ruleId: assessment.rule.ruleId,\n ruleVersion: assessment.rule.version\n })\n if (rule.row.ruleDigest !== assessment.rule.digest) {\n return yield* new ReadinessInputError({ operation, reason: \"rule-digest-mismatch\" })\n }\n if (!ruleMatchesAssessment(assessment, rules.definitionsMatch, rule.material)) {\n return yield* new ReadinessInputError({ operation, reason: \"rule-definition-mismatch\" })\n }\n return prepared\n })\n\n const consumeEnvironmentInvalidation = Effect.fn(\"ReadinessAssessments.consumeEnvironmentInvalidation\")(\n function*(request: CommitEnvironmentReadinessAssessmentRequest) {\n const assessment = request.assessment\n if (request.invalidation === null) {\n const { count } = yield* countEnvironmentInvalidations({\n workspaceId: assessment.candidate.workspaceId,\n releaseId: assessment.candidate.scope.releaseId,\n environmentId: assessment.candidate.scope.environmentId\n })\n if (count === 0) return\n } else {\n const now = encodeTimestamp(yield* DateTime.now)\n yield* sql`DELETE FROM readiness_environment_queue\n WHERE workspace_id = ${assessment.candidate.workspaceId}\n AND release_id = ${assessment.candidate.scope.releaseId}\n AND environment_id = ${assessment.candidate.scope.environmentId}\n AND invalidation_revision = ${request.invalidation.invalidationRevision}\n AND claim_owner = ${request.invalidation.leaseOwner}\n AND claim_token = ${request.invalidation.leaseToken}\n AND claim_expires_at > ${now}`\n if ((yield* readChanges(sql)) === 1) return\n }\n return yield* new ReadinessInputError({\n operation: \"commit-environment\",\n reason: \"stale-invalidation\"\n })\n }\n )\n\n const consumeReleaseInvalidation = Effect.fn(\"ReadinessAssessments.consumeReleaseInvalidation\")(\n function*(request: CommitReleaseReadinessAssessmentRequest) {\n const assessment = request.assessment\n const { count: pendingEnvironmentCount } = yield* countReleaseEnvironmentInvalidations({\n workspaceId: assessment.candidate.workspaceId,\n releaseId: assessment.candidate.scope.releaseId\n })\n if (pendingEnvironmentCount > 0) {\n return yield* new ReadinessInputError({ operation: \"commit-release\", reason: \"stale-invalidation\" })\n }\n if (request.invalidation === null) {\n const { count } = yield* countReleaseInvalidations({\n workspaceId: assessment.candidate.workspaceId,\n releaseId: assessment.candidate.scope.releaseId\n })\n if (count === 0) return\n } else {\n const now = encodeTimestamp(yield* DateTime.now)\n yield* sql`DELETE FROM readiness_release_queue\n WHERE workspace_id = ${assessment.candidate.workspaceId}\n AND release_id = ${assessment.candidate.scope.releaseId}\n AND invalidation_revision = ${request.invalidation.invalidationRevision}\n AND claim_owner = ${request.invalidation.leaseOwner}\n AND claim_token = ${request.invalidation.leaseToken}\n AND claim_expires_at > ${now}`\n if ((yield* readChanges(sql)) === 1) return\n }\n return yield* new ReadinessInputError({ operation: \"commit-release\", reason: \"stale-invalidation\" })\n }\n )\n\n const verifyReleaseChildren = Effect.fn(\"ReadinessAssessments.verifyReleaseChildren\")(function*(\n assessment: ReleaseReadinessAssessment\n ) {\n const rows = yield* SqlSchema.findAll({\n Request: Schema.Void,\n Result: RawReadinessRow,\n execute: () =>\n sql.unsafe(\n `SELECT 1 AS headRevision, assessment.evaluated_at AS committedAt,\n ${assessmentColumns}\n FROM readiness_environment_heads head\n INNER JOIN readiness_assessments assessment\n ON assessment.workspace_id = head.workspace_id\n AND assessment.assessment_id = head.assessment_id\n INNER JOIN release_targets target\n ON target.workspace_id = head.workspace_id\n AND target.release_id = head.release_id\n AND target.environment_id = head.environment_id\n AND target.lifecycle_kind = 'active'\n WHERE head.workspace_id = ? AND head.release_id = ?\n ORDER BY head.environment_id`,\n [assessment.candidate.workspaceId, assessment.candidate.scope.releaseId]\n )\n })(undefined)\n const decodedChildren = yield* Effect.forEach(rows, (row) =>\n Effect.gen(function*() {\n const decodedRow = yield* Schema.decodeUnknownEffect(ReadinessHistoryRow)(row).pipe(\n Effect.mapError(() =>\n new PersistedRecordError({\n workspaceId: assessment.candidate.workspaceId,\n recordKind: \"readiness-assessment\",\n recordKey: assessment.candidate.scope.releaseId,\n diagnosticCode: \"readiness-assessment-schema-invalid\"\n })\n ),\n captureMalformedReadinessRow(row)\n )\n const current = yield* codec.decodeAssessmentRow(decodedRow).pipe(captureMalformedReadinessRow(row))\n return { current, row }\n }))\n const groupedMaterialization = yield* materialization.load({\n workspaceId: assessment.candidate.workspaceId,\n assessmentIds: decodedChildren.map(({ current }) => current.assessmentId)\n })\n const currentSummaries = yield* Effect.forEach(decodedChildren, ({ current, row }) =>\n Effect.gen(function*() {\n yield* materialization.verify(current, row, groupedMaterialization)\n return current._tag === \"environment\"\n ? summarizeEnvironmentReadiness(current)\n : yield* new ReadinessInputError({ operation: \"commit-release\", reason: \"invalid-request\" })\n }))\n const matches = currentSummaries.length === assessment.environments.length &&\n currentSummaries.every((summary, index) => {\n const supplied: ReleaseReadinessAssessment[\"environments\"][number] | undefined = assessment.environments[index]\n return supplied !== undefined && JSON.stringify(summary) === JSON.stringify(supplied)\n })\n if (!matches) {\n return yield* new ReadinessInputError({ operation: \"commit-release\", reason: \"invalid-request\" })\n }\n })\n\n const commitEnvironment = Effect.fn(\"ReadinessAssessments.commitEnvironment\")(function*(\n request: CommitEnvironmentReadinessAssessmentRequest\n ) {\n const assessment = request.assessment\n const committedAt = yield* DateTime.now\n if (DateTime.Order(assessment.evaluatedAt, committedAt) > 0) {\n return yield* new ReadinessInputError({ operation: \"commit-environment\", reason: \"invalid-request\" })\n }\n const current = yield* findEnvironmentRevision({\n workspaceId: assessment.candidate.workspaceId,\n releaseId: assessment.candidate.scope.releaseId,\n environmentId: assessment.candidate.scope.environmentId\n })\n yield* verifyExpectedHead({\n workspaceId: assessment.candidate.workspaceId,\n recordKey: `${assessment.candidate.scope.releaseId}:${assessment.candidate.scope.environmentId}`,\n expected: request.expectedHeadRevision,\n actual: current,\n previousAssessmentId: assessment.previousAssessmentId\n })\n const prepared = yield* prepareCommit(assessment, \"commit-environment\")\n const headRevision = ReadinessHeadRevision.make((request.expectedHeadRevision ?? 0) + 1)\n yield* insertAssessment({ assessment, ...prepared }).pipe(mapPersistenceOperation(\"readiness.insert-assessment\"))\n yield* materializeAssessment({ assessment, ...prepared }).pipe(\n mapPersistenceOperation(\"readiness.materialize-assessment\")\n )\n yield* insertHistory({ assessment, headRevision, committedAt }).pipe(\n mapPersistenceOperation(\"readiness.insert-head-history\")\n )\n yield* publishEnvironmentHead({\n assessment,\n expected: request.expectedHeadRevision,\n headRevision,\n committedAt\n }).pipe(mapPersistenceOperation(\"readiness.publish-environment-head\"))\n yield* consumeEnvironmentInvalidation(request)\n return { assessment, headRevision, committedAt }\n })\n\n const commitRelease = Effect.fn(\"ReadinessAssessments.commitRelease\")(function*(\n request: CommitReleaseReadinessAssessmentRequest\n ) {\n const assessment = request.assessment\n const committedAt = yield* DateTime.now\n if (DateTime.Order(assessment.evaluatedAt, committedAt) > 0) {\n return yield* new ReadinessInputError({ operation: \"commit-release\", reason: \"invalid-request\" })\n }\n const current = yield* findReleaseRevision({\n workspaceId: assessment.candidate.workspaceId,\n releaseId: assessment.candidate.scope.releaseId\n })\n yield* verifyExpectedHead({\n workspaceId: assessment.candidate.workspaceId,\n recordKey: assessment.candidate.scope.releaseId,\n expected: request.expectedHeadRevision,\n actual: current,\n previousAssessmentId: assessment.previousAssessmentId\n })\n yield* verifyReleaseChildren(assessment)\n const prepared = yield* prepareCommit(assessment, \"commit-release\")\n const headRevision = ReadinessHeadRevision.make((request.expectedHeadRevision ?? 0) + 1)\n yield* insertAssessment({ assessment, ...prepared })\n yield* materializeAssessment({ assessment, ...prepared })\n yield* insertHistory({ assessment, headRevision, committedAt })\n yield* publishReleaseHead({\n assessment,\n expected: request.expectedHeadRevision,\n headRevision,\n committedAt\n })\n yield* consumeReleaseInvalidation(request)\n return { assessment, headRevision, committedAt }\n })\n\n const currentRows = (request: ReadCurrentReadinessAssessmentRequest) => {\n const environmentKey = request._tag === \"environment\" ? request.environmentId : \"\"\n const headTable = request._tag === \"environment\" ? \"readiness_environment_heads\" : \"readiness_release_heads\"\n const environmentPredicate = request._tag === \"environment\" ? \"AND head.environment_id = ?\" : \"\"\n const pendingExpression = request._tag === \"environment\"\n ? `EXISTS (\n SELECT 1 FROM readiness_environment_queue pending\n WHERE pending.workspace_id = head.workspace_id\n AND pending.release_id = head.release_id\n AND pending.environment_id = head.environment_id\n )`\n : `EXISTS (\n SELECT 1 FROM readiness_release_queue pending\n WHERE pending.workspace_id = head.workspace_id\n AND pending.release_id = head.release_id\n ) OR EXISTS (\n SELECT 1 FROM readiness_environment_queue pending_environment\n WHERE pending_environment.workspace_id = head.workspace_id\n AND pending_environment.release_id = head.release_id\n )`\n const parameters = request._tag === \"environment\"\n ? [request._tag, environmentKey, request.workspaceId, request.releaseId, request.environmentId]\n : [request._tag, environmentKey, request.workspaceId, request.releaseId]\n return SqlSchema.findAll({\n Request: Schema.Void,\n Result: RawReadinessRow,\n execute: () =>\n sql.unsafe(\n `SELECT\n CASE WHEN history.assessment_id IS NOT NULL AND assessment.assessment_id IS NOT NULL\n THEN 1 ELSE 0 END AS joinComplete,\n head.workspace_id AS headWorkspaceId,\n head.release_id AS headReleaseId,\n ${request._tag === \"environment\" ? \"head.environment_id\" : \"NULL\"} AS headEnvironmentId,\n head.assessment_id AS headAssessmentId,\n head.updated_at AS headUpdatedAt,\n history.head_revision AS headRevision,\n head.head_revision AS currentHeadRevision,\n history.committed_at AS committedAt,\n CASE WHEN ${pendingExpression} THEN 1 ELSE 0 END AS pendingCount,\n ${assessmentColumns},\n head.candidate_digest AS headCandidateDigest,\n head.rule_id AS headRuleId,\n head.rule_version AS headRuleVersion,\n head.rule_digest AS headRuleDigest,\n head.derivation_version AS headDerivationVersion\n FROM ${headTable} head\n LEFT JOIN readiness_head_history history\n ON history.workspace_id = head.workspace_id\n AND history.assessment_id = head.assessment_id\n AND history.scope_kind = ?\n AND history.release_id = head.release_id\n AND history.environment_key = ?\n AND history.head_revision = head.head_revision\n LEFT JOIN readiness_assessments assessment\n ON assessment.workspace_id = head.workspace_id\n AND assessment.assessment_id = head.assessment_id\n WHERE head.workspace_id = ? AND head.release_id = ? ${environmentPredicate}`,\n parameters\n )\n })(undefined)\n }\n\n const currentReleaseRows = Effect.fn(\"ReadinessAssessments.currentReleaseRows\")((\n request: ReadCurrentReleaseReadinessAssessmentsRequest\n ) => {\n const [firstReleaseId, ...remainingReleaseIds] = request.releaseIds\n if (firstReleaseId === undefined) return Effect.succeed([])\n const rendered = renderCurrentReleaseReadinessQuery({\n workspaceId: request.workspaceId,\n releaseIds: [firstReleaseId, ...remainingReleaseIds]\n })\n return sql.unsafe<typeof RawReadinessRow.Type>(rendered.sql, [...rendered.params]).pipe(\n Effect.map((rows) =>\n rows.map((row) => ({\n ...row,\n headEnvironmentId: null,\n joinComplete: row.historyAssessmentId !== null && row.assessmentId !== null ? 1 : 0,\n pendingCount: row.pending === 1 ? 1 : 0\n }))\n )\n )\n })\n\n const historyRows = (request: ReadReadinessHistoryRequest) => {\n const environmentKey = request._tag === \"environment\" ? request.environmentId : \"\"\n return SqlSchema.findAll({\n Request: Schema.Void,\n Result: RawReadinessRow,\n execute: () =>\n sql.unsafe(\n `SELECT\n CASE WHEN assessment.assessment_id IS NOT NULL THEN 1 ELSE 0 END AS joinComplete,\n history.head_revision AS headRevision,\n history.committed_at AS committedAt,\n ${assessmentColumns}\n FROM readiness_head_history history\n LEFT JOIN readiness_assessments assessment\n ON assessment.workspace_id = history.workspace_id\n AND assessment.assessment_id = history.assessment_id\n WHERE history.workspace_id = ?\n AND history.scope_kind = ?\n AND history.release_id = ?\n AND history.environment_key = ?\n AND (? IS NULL OR history.head_revision < ?)\n ORDER BY history.head_revision DESC\n LIMIT ?`,\n [\n request.workspaceId,\n request._tag,\n request.releaseId,\n environmentKey,\n request.beforeHeadRevision,\n request.beforeHeadRevision,\n request.limit + 1\n ]\n )\n })(undefined)\n }\n\n const decodeCurrentRow = Effect.fn(\"ReadinessAssessments.decodeCurrentRow\")(function*(\n row: typeof RawReadinessRow.Type,\n request: ReadCurrentReadinessAssessmentRequest\n ) {\n const recordKind = request._tag === \"environment\" ? \"readiness-environment-head\" : \"readiness-release-head\"\n const recordKey = request._tag === \"environment\" ? request.environmentId : request.releaseId\n const malformedHead = (diagnosticCode: string) =>\n new PersistedRecordError({ workspaceId: request.workspaceId, recordKind, recordKey, diagnosticCode })\n if (!Predicate.hasProperty(row, \"joinComplete\") || row.joinComplete !== 1) {\n return yield* captureMalformedReadinessRow(row)(\n Effect.fail(malformedHead(\"readiness-head-assessment-mismatch\"))\n )\n }\n const decodedRow = yield* Schema.decodeUnknownEffect(ReadinessCurrentRow)(row).pipe(\n Effect.mapError(() =>\n malformedHead(\n request._tag === \"environment\"\n ? \"readiness-environment-head-schema-invalid\"\n : \"readiness-release-head-schema-invalid\"\n )\n ),\n captureMalformedReadinessRow(row)\n )\n const assessment = yield* codec.decodeAssessmentRow(decodedRow).pipe(captureMalformedReadinessRow(row))\n if (\n decodedRow.headWorkspaceId !== request.workspaceId ||\n decodedRow.headReleaseId !== request.releaseId ||\n (request._tag === \"environment\"\n ? decodedRow.headEnvironmentId !== request.environmentId\n : decodedRow.headEnvironmentId !== null) ||\n decodedRow.headAssessmentId !== decodedRow.assessmentId ||\n decodedRow.workspaceId !== decodedRow.headWorkspaceId ||\n decodedRow.releaseId !== decodedRow.headReleaseId ||\n decodedRow.scopeKind !== request._tag ||\n (request._tag === \"environment\"\n ? decodedRow.environmentId !== request.environmentId\n : decodedRow.environmentId !== null) ||\n decodedRow.headCandidateDigest !== decodedRow.candidateDigest ||\n decodedRow.currentHeadRevision !== decodedRow.headRevision ||\n decodedRow.headRuleId !== decodedRow.ruleId ||\n decodedRow.headRuleVersion !== decodedRow.ruleVersion ||\n decodedRow.headRuleDigest !== decodedRow.ruleDigest ||\n decodedRow.headDerivationVersion !== decodedRow.derivationVersion ||\n decodedRow.headUpdatedAt !== decodedRow.committedAt\n ) {\n return yield* captureMalformedReadinessRow(row)(\n Effect.fail(malformedHead(\"readiness-head-assessment-mismatch\"))\n )\n }\n const committedAt = yield* Schema.decodeUnknownEffect(UtcTimestamp)(decodedRow.committedAt).pipe(\n Effect.mapError(() =>\n malformedHead(\n request._tag === \"environment\"\n ? \"readiness-environment-head-schema-invalid\"\n : \"readiness-release-head-schema-invalid\"\n )\n ),\n captureMalformedReadinessRow(row)\n )\n return {\n assessment,\n headRevision: ReadinessHeadRevision.make(decodedRow.headRevision),\n committedAt,\n authority: authorityOf(decodedRow.pendingCount)\n }\n })\n\n const decodeCurrentReleaseRow = Effect.fn(\"ReadinessAssessments.decodeCurrentReleaseRow\")(function*(\n row: typeof RawReadinessRow.Type,\n workspaceId: WorkspaceId\n ) {\n const releaseId = yield* Schema.decodeUnknownEffect(ReleaseId)(\n Predicate.hasProperty(row, \"headReleaseId\") ? row.headReleaseId : undefined\n ).pipe(\n Effect.mapError(() =>\n new PersistedRecordError({\n workspaceId,\n recordKind: \"readiness-release-head\",\n recordKey: \"unknown-release\",\n diagnosticCode: \"readiness-release-head-schema-invalid\"\n })\n ),\n captureMalformedReadinessRow(row)\n )\n return yield* decodeCurrentRow(row, { _tag: \"release\", workspaceId, releaseId })\n })\n\n const decodeHistoryRow = Effect.fn(\"ReadinessAssessments.decodeHistoryRow\")(function*(\n row: typeof RawReadinessRow.Type,\n request: ReadReadinessHistoryRequest\n ) {\n const recordKey = request._tag === \"environment\" ? request.environmentId : request.releaseId\n const malformed = (diagnosticCode: string) =>\n new PersistedRecordError({\n workspaceId: request.workspaceId,\n recordKind: \"readiness-assessment\",\n recordKey,\n diagnosticCode\n })\n if (!Predicate.hasProperty(row, \"joinComplete\") || row.joinComplete !== 1) {\n return yield* captureMalformedReadinessRow(row)(\n Effect.fail(malformed(\"readiness-assessment-identity-mismatch\"))\n )\n }\n const decodedRow = yield* Schema.decodeUnknownEffect(ReadinessHistoryRow)(row).pipe(\n Effect.mapError(() => malformed(\"readiness-assessment-schema-invalid\")),\n captureMalformedReadinessRow(row)\n )\n const assessment = yield* codec.decodeAssessmentRow(decodedRow).pipe(captureMalformedReadinessRow(row))\n const identityMatches = decodedRow.workspaceId === request.workspaceId &&\n decodedRow.releaseId === request.releaseId &&\n decodedRow.scopeKind === request._tag &&\n (request._tag === \"environment\"\n ? decodedRow.environmentId === request.environmentId\n : decodedRow.environmentId === null)\n if (!identityMatches) {\n return yield* captureMalformedReadinessRow(row)(\n Effect.fail(malformed(\"readiness-assessment-identity-mismatch\"))\n )\n }\n const committedAt = yield* Schema.decodeUnknownEffect(UtcTimestamp)(decodedRow.committedAt).pipe(\n Effect.mapError(() => malformed(\"readiness-assessment-schema-invalid\")),\n captureMalformedReadinessRow(row)\n )\n return {\n assessment,\n headRevision: ReadinessHeadRevision.make(decodedRow.headRevision),\n committedAt\n }\n })\n\n return {\n commitEnvironment,\n commitRelease,\n currentReleaseRows,\n currentRows,\n decodeCurrentReleaseRow,\n decodeCurrentRow,\n decodeHistoryRow,\n historyRows,\n loadAssessmentMaterialization: materialization.load,\n verifyAssessmentMaterialization: materialization.verify\n }\n})\n","import * as Crypto from \"effect/Crypto\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport * as Schema from \"effect/Schema\"\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\"\n\nimport { EnvironmentId, ReleaseId, WorkspaceId } from \"../../../../domain/identifiers.js\"\nimport { UtcTimestamp } from \"../../../../domain/utcTimestamp.js\"\nimport { Database } from \"../../Database.js\"\nimport { PersistenceOperationError } from \"../../errors.js\"\nimport { readChanges } from \"../internal.js\"\nimport {\n type ClaimReadinessInvalidationRequest,\n type EnqueueAffectedReadinessRequest,\n type EnqueueDueReadinessEvaluationsRequest,\n type EnqueueReadinessInvalidationRequest,\n ReadinessInputError,\n type ReadinessInvalidationRecord,\n ReadinessInvalidationRevision,\n ReadinessLeaseToken\n} from \"./contract.js\"\nimport { ReadinessEnvironmentQueueRow, ReadinessReleaseQueueRow } from \"./rows.js\"\n\nconst encodeTimestamp = Schema.encodeSync(UtcTimestamp)\nconst MAX_READINESS_LEASE_MILLISECONDS = 15 * 60 * 1_000\n\nconst DueScheduleRow = Schema.Struct({\n workspaceId: WorkspaceId,\n releaseId: ReleaseId,\n environmentId: EnvironmentId,\n assessmentId: Schema.String,\n dueAt: Schema.String\n})\n\nconst AffectedEnvironmentRow = Schema.Struct({\n workspaceId: WorkspaceId,\n releaseId: ReleaseId,\n environmentId: EnvironmentId\n})\n\nexport const makeReadinessQueue = Effect.gen(function*() {\n const database = yield* Database\n const cryptoService = yield* Crypto.Crypto\n const sql = database.sql\n\n const readEnvironmentQueue = SqlSchema.findOne({\n Request: Schema.Struct({ workspaceId: WorkspaceId, releaseId: ReleaseId, environmentId: EnvironmentId }),\n Result: ReadinessEnvironmentQueueRow,\n execute: ({ environmentId, releaseId, workspaceId }) =>\n sql`SELECT workspace_id AS workspaceId, release_id AS releaseId,\n environment_id AS environmentId, invalidation_revision AS invalidationRevision,\n reason, source_evidence_id AS sourceEvidenceId,\n source_plugin_connection_id AS sourcePluginConnectionId,\n queued_at AS queuedAt, available_at AS availableAt, attempts,\n claim_owner AS claimOwner, claim_token AS claimToken,\n claim_expires_at AS claimExpiresAt\n FROM readiness_environment_queue\n WHERE workspace_id = ${workspaceId} AND release_id = ${releaseId}\n AND environment_id = ${environmentId}`\n })\n\n const readReleaseQueue = SqlSchema.findOne({\n Request: Schema.Struct({ workspaceId: WorkspaceId, releaseId: ReleaseId }),\n Result: ReadinessReleaseQueueRow,\n execute: ({ releaseId, workspaceId }) =>\n sql`SELECT workspace_id AS workspaceId, release_id AS releaseId,\n invalidation_revision AS invalidationRevision, reason,\n source_environment_id AS sourceEnvironmentId,\n queued_at AS queuedAt, available_at AS availableAt, attempts,\n claim_owner AS claimOwner, claim_token AS claimToken,\n claim_expires_at AS claimExpiresAt\n FROM readiness_release_queue\n WHERE workspace_id = ${workspaceId} AND release_id = ${releaseId}`\n })\n\n const environmentRecord = Effect.fn(\"ReadinessQueue.environmentRecord\")(function*(\n row: typeof ReadinessEnvironmentQueueRow.Type,\n lease: null | {\n readonly owner: ClaimReadinessInvalidationRequest[\"leaseOwner\"]\n readonly token: typeof ReadinessLeaseToken.Type\n readonly claimedAt: UtcTimestamp\n readonly expiresAt: UtcTimestamp\n }\n ): Effect.fn.Return<ReadinessInvalidationRecord, Schema.SchemaError> {\n return {\n _tag: \"environment\",\n workspaceId: row.workspaceId,\n releaseId: row.releaseId,\n environmentId: row.environmentId,\n invalidationRevision: yield* Schema.decodeUnknownEffect(ReadinessInvalidationRevision)(\n row.invalidationRevision\n ),\n reason: row.reason,\n enqueuedAt: yield* Schema.decodeUnknownEffect(UtcTimestamp)(row.queuedAt),\n lease\n }\n })\n\n const releaseRecord = Effect.fn(\"ReadinessQueue.releaseRecord\")(function*(\n row: typeof ReadinessReleaseQueueRow.Type,\n lease: null | {\n readonly owner: ClaimReadinessInvalidationRequest[\"leaseOwner\"]\n readonly token: typeof ReadinessLeaseToken.Type\n readonly claimedAt: UtcTimestamp\n readonly expiresAt: UtcTimestamp\n }\n ): Effect.fn.Return<ReadinessInvalidationRecord, Schema.SchemaError> {\n return {\n _tag: \"release\",\n workspaceId: row.workspaceId,\n releaseId: row.releaseId,\n invalidationRevision: yield* Schema.decodeUnknownEffect(ReadinessInvalidationRevision)(\n row.invalidationRevision\n ),\n reason: row.reason,\n enqueuedAt: yield* Schema.decodeUnknownEffect(UtcTimestamp)(row.queuedAt),\n lease\n }\n })\n\n const enqueue = Effect.fn(\"ReadinessQueue.enqueue\")(function*(request: EnqueueReadinessInvalidationRequest) {\n const timestamp = encodeTimestamp(request.enqueuedAt)\n if (request._tag === \"environment\") {\n yield* sql`INSERT INTO readiness_environment_queue (\n workspace_id, release_id, environment_id, invalidation_revision, reason,\n source_evidence_id, source_plugin_connection_id, queued_at, available_at,\n attempts, claim_owner, claim_token, claim_expires_at\n ) VALUES (\n ${request.workspaceId}, ${request.releaseId}, ${request.environmentId}, 1,\n ${request.reason}, NULL, NULL, ${timestamp}, ${timestamp}, 0, NULL, NULL, NULL\n ) ON CONFLICT (workspace_id, release_id, environment_id) DO UPDATE SET\n invalidation_revision = readiness_environment_queue.invalidation_revision + 1,\n reason = excluded.reason, source_evidence_id = NULL, source_plugin_connection_id = NULL,\n queued_at = excluded.queued_at, available_at = excluded.available_at,\n claim_owner = NULL, claim_token = NULL, claim_expires_at = NULL`\n return yield* environmentRecord(yield* readEnvironmentQueue(request), null)\n }\n yield* sql`INSERT INTO readiness_release_queue (\n workspace_id, release_id, invalidation_revision, reason, source_environment_id,\n queued_at, available_at, attempts, claim_owner, claim_token, claim_expires_at\n ) VALUES (\n ${request.workspaceId}, ${request.releaseId}, 1, ${request.reason}, NULL,\n ${timestamp}, ${timestamp}, 0, NULL, NULL, NULL\n ) ON CONFLICT (workspace_id, release_id) DO UPDATE SET\n invalidation_revision = readiness_release_queue.invalidation_revision + 1,\n reason = excluded.reason, source_environment_id = NULL,\n queued_at = excluded.queued_at, available_at = excluded.available_at,\n claim_owner = NULL, claim_token = NULL, claim_expires_at = NULL`\n return yield* releaseRecord(yield* readReleaseQueue(request), null)\n })\n\n const claim = Effect.fn(\"ReadinessQueue.claim\")(function*(request: ClaimReadinessInvalidationRequest) {\n const claimedAtValue = yield* DateTime.now\n if (DateTime.Order(claimedAtValue, request.leaseExpiresAt) >= 0) return null\n if (\n DateTime.toEpochMillis(request.leaseExpiresAt) - DateTime.toEpochMillis(claimedAtValue) >\n MAX_READINESS_LEASE_MILLISECONDS\n ) {\n return yield* new ReadinessInputError({ operation: \"claim-invalidation\", reason: \"invalid-request\" })\n }\n const claimedAt = encodeTimestamp(claimedAtValue)\n const expiresAt = encodeTimestamp(request.leaseExpiresAt)\n const token = ReadinessLeaseToken.make(\n yield* cryptoService.randomUUIDv7.pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"readiness.claim-token\" }))\n )\n )\n if (request._tag === \"environment\") {\n yield* sql`UPDATE readiness_environment_queue\n SET claim_owner = ${request.leaseOwner}, claim_token = ${token},\n claim_expires_at = ${expiresAt}, attempts = attempts + 1\n WHERE workspace_id = ${request.workspaceId} AND release_id = ${request.releaseId}\n AND environment_id = ${request.environmentId}\n AND invalidation_revision = ${request.expectedInvalidationRevision}\n AND available_at <= ${claimedAt}\n AND (claim_owner IS NULL OR claim_expires_at <= ${claimedAt})`\n if ((yield* readChanges(sql)) === 0) return null\n const row = yield* readEnvironmentQueue(request)\n return yield* environmentRecord(row, {\n owner: request.leaseOwner,\n token,\n claimedAt: claimedAtValue,\n expiresAt: request.leaseExpiresAt\n })\n }\n yield* sql`UPDATE readiness_release_queue\n SET claim_owner = ${request.leaseOwner}, claim_token = ${token},\n claim_expires_at = ${expiresAt}, attempts = attempts + 1\n WHERE workspace_id = ${request.workspaceId} AND release_id = ${request.releaseId}\n AND invalidation_revision = ${request.expectedInvalidationRevision}\n AND available_at <= ${claimedAt}\n AND (claim_owner IS NULL OR claim_expires_at <= ${claimedAt})`\n if ((yield* readChanges(sql)) === 0) return null\n const row = yield* readReleaseQueue(request)\n return yield* releaseRecord(row, {\n owner: request.leaseOwner,\n token,\n claimedAt: claimedAtValue,\n expiresAt: request.leaseExpiresAt\n })\n })\n\n const enqueueDue = Effect.fn(\"ReadinessQueue.enqueueDue\")(function*(request: EnqueueDueReadinessEvaluationsRequest) {\n const dueAt = encodeTimestamp(request.dueAt)\n const schedules = yield* SqlSchema.findAll({\n Request: Schema.Void,\n Result: DueScheduleRow,\n execute: () =>\n sql`SELECT workspace_id AS workspaceId, release_id AS releaseId,\n environment_id AS environmentId, assessment_id AS assessmentId,\n due_at AS dueAt\n FROM readiness_evaluation_schedules\n WHERE workspace_id = ${request.workspaceId} AND due_at <= ${dueAt}\n ORDER BY due_at, release_id, environment_id\n LIMIT ${request.limit}`\n })(undefined)\n yield* Effect.forEach(\n schedules,\n (schedule) =>\n Effect.gen(function*() {\n yield* enqueue({\n _tag: \"environment\",\n workspaceId: schedule.workspaceId,\n releaseId: schedule.releaseId,\n environmentId: schedule.environmentId,\n reason: \"scheduled\",\n enqueuedAt: request.dueAt\n })\n yield* sql`DELETE FROM readiness_evaluation_schedules\n WHERE workspace_id = ${schedule.workspaceId} AND release_id = ${schedule.releaseId}\n AND environment_id = ${schedule.environmentId}\n AND assessment_id = ${schedule.assessmentId} AND due_at = ${schedule.dueAt}`\n }),\n { discard: true }\n )\n return { enqueued: schedules.length }\n })\n\n const enqueueAffected = Effect.fn(\"ReadinessQueue.enqueueAffected\")(function*(\n request: EnqueueAffectedReadinessRequest\n ) {\n const affected = yield* request._tag === \"evidence\"\n ? SqlSchema.findAll({\n Request: Schema.Void,\n Result: AffectedEnvironmentRow,\n execute: () =>\n sql`SELECT head.workspace_id AS workspaceId,\n head.release_id AS releaseId,\n head.environment_id AS environmentId\n FROM readiness_environment_heads head\n INNER JOIN readiness_assessment_evidence dependency\n ON dependency.workspace_id = head.workspace_id\n AND dependency.assessment_id = head.assessment_id\n WHERE head.workspace_id = ${request.workspaceId}\n AND dependency.evidence_id = ${request.evidenceId}\n ORDER BY head.release_id, head.environment_id`\n })(undefined)\n : SqlSchema.findAll({\n Request: Schema.Void,\n Result: AffectedEnvironmentRow,\n execute: () =>\n sql`SELECT head.workspace_id AS workspaceId,\n head.release_id AS releaseId,\n head.environment_id AS environmentId\n FROM readiness_environment_heads head\n INNER JOIN readiness_assessment_sources dependency\n ON dependency.workspace_id = head.workspace_id\n AND dependency.assessment_id = head.assessment_id\n WHERE head.workspace_id = ${request.workspaceId}\n AND dependency.plugin_connection_id = ${request.pluginConnectionId}\n ORDER BY head.release_id, head.environment_id`\n })(undefined)\n const timestamp = encodeTimestamp(request.enqueuedAt)\n yield* Effect.forEach(\n affected,\n (target) =>\n sql`INSERT INTO readiness_environment_queue (\n workspace_id, release_id, environment_id, invalidation_revision, reason,\n source_evidence_id, source_plugin_connection_id, queued_at, available_at,\n attempts, claim_owner, claim_token, claim_expires_at\n ) VALUES (\n ${target.workspaceId}, ${target.releaseId}, ${target.environmentId}, 1,\n ${request._tag === \"evidence\" ? \"evidence-changed\" : \"plugin-health-changed\"},\n ${request._tag === \"evidence\" ? request.evidenceId : null},\n ${request._tag === \"plugin\" ? request.pluginConnectionId : null},\n ${timestamp}, ${timestamp}, 0, NULL, NULL, NULL\n ) ON CONFLICT (workspace_id, release_id, environment_id) DO UPDATE SET\n invalidation_revision = readiness_environment_queue.invalidation_revision + 1,\n reason = excluded.reason, source_evidence_id = excluded.source_evidence_id,\n source_plugin_connection_id = excluded.source_plugin_connection_id,\n queued_at = excluded.queued_at, available_at = excluded.available_at,\n claim_owner = NULL, claim_token = NULL, claim_expires_at = NULL`,\n { discard: true }\n )\n const releaseIds = Array.from(new Set(affected.map(({ releaseId }) => releaseId)))\n return { environments: affected.length, releases: releaseIds.length }\n })\n\n return { claim, enqueue, enqueueAffected, enqueueDue }\n})\n","import * as Context from \"effect/Context\"\nimport * as Crypto from \"effect/Crypto\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport type { Success } from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\n\nimport type { WorkspaceId } from \"../../../domain/identifiers.js\"\nimport { Database } from \"../Database.js\"\nimport { PersistedRecordError, type PersistenceOperationError, type QuarantineWriteError } from \"../errors.js\"\nimport { mapPersistenceOperation } from \"./internal.js\"\nimport { makePersistedRowQuarantine } from \"./persistedRowQuarantine.js\"\nimport { QuarantineRepository } from \"./quarantineRepository.js\"\nimport { makeReadinessAssessments } from \"./readiness/assessments.js\"\nimport {\n ClaimReadinessInvalidationRequest,\n CommitEnvironmentReadinessAssessmentRequest,\n CommitReleaseReadinessAssessmentRequest,\n type CurrentEnvironmentReadinessAssessmentRecord,\n type CurrentReleaseReadinessAssessmentRecord,\n EnqueueAffectedReadinessRequest,\n EnqueueDueReadinessEvaluationsRequest,\n EnqueueReadinessInvalidationRequest,\n type EnvironmentReadinessAssessmentRecord,\n ReadCurrentReadinessAssessmentRequest,\n type ReadCurrentReadinessAssessmentResult,\n ReadCurrentReleaseReadinessAssessmentsRequest,\n type ReadCurrentReleaseReadinessAssessmentsResult,\n ReadinessInputError,\n ReadReadinessHistoryRequest,\n type ReadReadinessHistoryResult,\n RegisterReadinessRuleRequest,\n type ReleaseReadinessAssessmentRecord\n} from \"./readiness/contract.js\"\nimport type { MalformedReadinessRecord } from \"./readiness/quarantine.js\"\nimport { readinessQuarantineDiagnostic } from \"./readiness/quarantine.js\"\nimport { makeReadinessQueue } from \"./readiness/queue.js\"\nimport { makeReadinessRules } from \"./readiness/rules.js\"\n\nexport * from \"./readiness/contract.js\"\n\nconst makeReadinessRepository = Effect.gen(function*() {\n const database = yield* Database\n const cryptoService = yield* Crypto.Crypto\n const quarantine = yield* QuarantineRepository\n const quarantineRow = makePersistedRowQuarantine(cryptoService, quarantine)\n const assessments = yield* makeReadinessAssessments\n const queue = yield* makeReadinessQueue\n const rules = yield* makeReadinessRules\n\n const decodeInput = <Value, Encoded, Requirements>(\n operation: ReadinessInputError[\"operation\"],\n schema: Schema.Codec<Value, Encoded, Requirements>,\n input: unknown\n ) =>\n Schema.decodeUnknownEffect(Schema.toType(schema))(input).pipe(\n Effect.mapError(() => new ReadinessInputError({ operation, reason: \"invalid-request\" }))\n )\n\n const quarantineMalformed = Effect.fn(\"ReadinessRepository.quarantineMalformed\")(function*(\n malformed: MalformedReadinessRecord\n ) {\n const diagnostic = readinessQuarantineDiagnostic(malformed.error)\n if (diagnostic !== null) {\n yield* quarantineRow({\n workspaceId: malformed.error.workspaceId,\n ...diagnostic,\n recordKey: malformed.error.recordKey,\n observedAt: yield* DateTime.now,\n row: malformed.row\n })\n }\n return yield* malformed.error\n })\n\n const isMalformedReadinessRecord = (failure: unknown): failure is MalformedReadinessRecord =>\n Predicate.isTagged(\"MalformedReadinessRecord\")(failure) &&\n Predicate.hasProperty(failure, \"error\") &&\n Predicate.isTagged(\"PersistedRecordError\")(failure.error) &&\n Predicate.hasProperty(failure, \"row\")\n\n const transactCaptured = <Value, Failure, Requirements>(effect: Effect.Effect<Value, Failure, Requirements>) =>\n database.transaction(effect).pipe(\n mapPersistenceOperation(\"readiness.transaction\"),\n Effect.result,\n Effect.flatMap(\n (\n result\n ): Effect.Effect<\n Value,\n Failure | PersistedRecordError | PersistenceOperationError | QuarantineWriteError,\n Requirements\n > => {\n if (Result.isSuccess(result)) return Effect.succeed(result.success)\n return isMalformedReadinessRecord(result.failure)\n ? quarantineMalformed(result.failure)\n : Effect.fail(result.failure)\n }\n )\n )\n\n const registerRule = Effect.fn(\"ReadinessRepository.registerRule\")(function*(input: unknown) {\n const request = yield* decodeInput(\"register-rule\", RegisterReadinessRuleRequest, input)\n return yield* transactCaptured(rules.register(request))\n })\n\n const commitEnvironment = Effect.fn(\"ReadinessRepository.commitEnvironment\")(function*(input: unknown) {\n const request = yield* decodeInput(\"commit-environment\", CommitEnvironmentReadinessAssessmentRequest, input)\n return yield* transactCaptured(assessments.commitEnvironment(request))\n })\n\n const commitRelease = Effect.fn(\"ReadinessRepository.commitRelease\")(function*(input: unknown) {\n const request = yield* decodeInput(\"commit-release\", CommitReleaseReadinessAssessmentRequest, input)\n return yield* transactCaptured(assessments.commitRelease(request))\n })\n\n type CurrentRow = Success<ReturnType<typeof assessments.currentRows>>[number]\n type DecodedCurrentRecord = Success<ReturnType<typeof assessments.decodeCurrentRow>>\n const verifyCurrentMaterialization = Effect.fn(\"ReadinessRepository.verifyCurrentMaterialization\")(\n function*(input: {\n readonly workspaceId: WorkspaceId\n readonly rows: ReadonlyArray<CurrentRow>\n readonly records: ReadonlyArray<DecodedCurrentRecord>\n }) {\n const materialization = yield* assessments.loadAssessmentMaterialization({\n workspaceId: input.workspaceId,\n assessmentIds: input.records.map(({ assessment }) => assessment.assessmentId)\n })\n yield* Effect.forEach(\n input.records,\n (record, index) =>\n assessments.verifyAssessmentMaterialization(record.assessment, input.rows[index], materialization),\n { discard: true }\n )\n }\n )\n\n const readCurrent = Effect.fn(\"ReadinessRepository.readCurrent\")(function*(input: unknown) {\n const request = yield* decodeInput(\"read-current\", ReadCurrentReadinessAssessmentRequest, input)\n const records = yield* transactCaptured(\n Effect.gen(function*() {\n const rows = yield* assessments.currentRows(request)\n const decoded = yield* Effect.forEach(rows, (row) => assessments.decodeCurrentRow(row, request))\n yield* verifyCurrentMaterialization({\n workspaceId: request.workspaceId,\n rows,\n records: decoded\n })\n return decoded\n })\n )\n const decoded = records[0]\n if (decoded === undefined) return { _tag: request._tag, record: null }\n if (records.length !== 1) {\n return yield* new PersistedRecordError({\n workspaceId: request.workspaceId,\n recordKind: request._tag === \"environment\" ? \"readiness-environment-head\" : \"readiness-release-head\",\n recordKey: request._tag === \"environment\" ? request.environmentId : request.releaseId,\n diagnosticCode: request._tag === \"environment\"\n ? \"readiness-environment-head-schema-invalid\"\n : \"readiness-release-head-schema-invalid\"\n })\n }\n if (request._tag === \"environment\" && decoded.assessment._tag === \"environment\") {\n const record: CurrentEnvironmentReadinessAssessmentRecord = {\n ...decoded,\n assessment: decoded.assessment\n }\n return { _tag: \"environment\", record } satisfies ReadCurrentReadinessAssessmentResult\n }\n if (request._tag === \"release\" && decoded.assessment._tag === \"release\") {\n const record: CurrentReleaseReadinessAssessmentRecord = {\n ...decoded,\n assessment: decoded.assessment\n }\n return { _tag: \"release\", record } satisfies ReadCurrentReadinessAssessmentResult\n }\n return yield* new PersistedRecordError({\n workspaceId: request.workspaceId,\n recordKind: request._tag === \"environment\" ? \"readiness-environment-head\" : \"readiness-release-head\",\n recordKey: request._tag === \"environment\" ? request.environmentId : request.releaseId,\n diagnosticCode: \"readiness-head-assessment-mismatch\"\n })\n })\n\n const readCurrentReleases = Effect.fn(\"ReadinessRepository.readCurrentReleases\")(function*(input: unknown) {\n const request = yield* decodeInput(\n \"read-current-releases\",\n ReadCurrentReleaseReadinessAssessmentsRequest,\n input\n )\n const decoded = yield* transactCaptured(\n Effect.gen(function*() {\n const rows = yield* assessments.currentReleaseRows(request)\n const records = yield* Effect.forEach(\n rows,\n (row) => assessments.decodeCurrentReleaseRow(row, request.workspaceId)\n )\n yield* verifyCurrentMaterialization({\n workspaceId: request.workspaceId,\n rows,\n records\n })\n return records\n })\n )\n const records: Array<CurrentReleaseReadinessAssessmentRecord> = decoded.flatMap((record) =>\n record.assessment._tag === \"release\"\n ? [{ ...record, assessment: record.assessment }]\n : []\n )\n const releaseIds = records.map(({ assessment }) => assessment.candidate.scope.releaseId)\n const requestedReleaseIds = new Set(request.releaseIds)\n if (\n records.length !== decoded.length ||\n new Set(releaseIds).size !== releaseIds.length ||\n releaseIds.some((releaseId) => !requestedReleaseIds.has(releaseId))\n ) {\n return yield* new PersistedRecordError({\n workspaceId: request.workspaceId,\n recordKind: \"readiness-release-head\",\n recordKey: \"release-batch\",\n diagnosticCode: \"readiness-head-assessment-mismatch\"\n })\n }\n return records satisfies ReadCurrentReleaseReadinessAssessmentsResult\n })\n\n const readHistory = Effect.fn(\"ReadinessRepository.readHistory\")(function*(input: unknown) {\n const request = yield* decodeInput(\"read-history\", ReadReadinessHistoryRequest, input)\n const snapshot = yield* transactCaptured(\n Effect.gen(function*() {\n const rows = yield* assessments.historyRows(request)\n const pageRows = rows.slice(0, request.limit)\n const decoded = yield* Effect.forEach(pageRows, (row) => assessments.decodeHistoryRow(row, request))\n const materialization = yield* assessments.loadAssessmentMaterialization({\n workspaceId: request.workspaceId,\n assessmentIds: decoded.map(({ assessment }) => assessment.assessmentId)\n })\n yield* Effect.forEach(\n decoded,\n (record, index) =>\n assessments.verifyAssessmentMaterialization(record.assessment, pageRows[index], materialization),\n { discard: true }\n )\n return { decoded, hasMore: rows.length > request.limit }\n })\n )\n const { decoded } = snapshot\n const last = decoded.at(-1)\n const nextBeforeHeadRevision = snapshot.hasMore && last !== undefined ? last.headRevision : null\n if (request._tag === \"environment\") {\n const records: Array<EnvironmentReadinessAssessmentRecord> = decoded.flatMap((record) =>\n record.assessment._tag === \"environment\"\n ? [{ ...record, assessment: record.assessment }]\n : []\n )\n if (records.length !== decoded.length) {\n return yield* new PersistedRecordError({\n workspaceId: request.workspaceId,\n recordKind: \"readiness-assessment\",\n recordKey: request.releaseId,\n diagnosticCode: \"readiness-assessment-identity-mismatch\"\n })\n }\n return {\n _tag: \"environment\",\n records,\n nextBeforeHeadRevision\n } satisfies ReadReadinessHistoryResult\n }\n const records: Array<ReleaseReadinessAssessmentRecord> = decoded.flatMap((record) =>\n record.assessment._tag === \"release\"\n ? [{ ...record, assessment: record.assessment }]\n : []\n )\n if (records.length !== decoded.length) {\n return yield* new PersistedRecordError({\n workspaceId: request.workspaceId,\n recordKind: \"readiness-assessment\",\n recordKey: request.releaseId,\n diagnosticCode: \"readiness-assessment-identity-mismatch\"\n })\n }\n return { _tag: \"release\", records, nextBeforeHeadRevision } satisfies ReadReadinessHistoryResult\n })\n\n const enqueueInvalidation = Effect.fn(\"ReadinessRepository.enqueueInvalidation\")(function*(input: unknown) {\n const request = yield* decodeInput(\"enqueue-invalidation\", EnqueueReadinessInvalidationRequest, input)\n return yield* database\n .transaction(queue.enqueue(request))\n .pipe(mapPersistenceOperation(\"readiness.enqueue-invalidation\"))\n })\n\n const enqueueAffected = Effect.fn(\"ReadinessRepository.enqueueAffected\")(function*(input: unknown) {\n const request = yield* decodeInput(\"enqueue-affected\", EnqueueAffectedReadinessRequest, input)\n return yield* database\n .transaction(queue.enqueueAffected(request))\n .pipe(mapPersistenceOperation(\"readiness.enqueue-affected\"))\n })\n\n const claimInvalidation = Effect.fn(\"ReadinessRepository.claimInvalidation\")(function*(input: unknown) {\n const request = yield* decodeInput(\"claim-invalidation\", ClaimReadinessInvalidationRequest, input)\n return yield* database\n .transaction(queue.claim(request))\n .pipe(mapPersistenceOperation(\"readiness.claim-invalidation\"))\n })\n\n const enqueueDue = Effect.fn(\"ReadinessRepository.enqueueDue\")(function*(input: unknown) {\n const request = yield* decodeInput(\"enqueue-due\", EnqueueDueReadinessEvaluationsRequest, input)\n return yield* database.transaction(queue.enqueueDue(request)).pipe(mapPersistenceOperation(\"readiness.enqueue-due\"))\n })\n\n return {\n claimInvalidation,\n commitEnvironment,\n commitRelease,\n enqueueAffected,\n enqueueDue,\n enqueueInvalidation,\n readCurrent,\n readCurrentReleases,\n readHistory,\n registerRule\n }\n})\n\n/** Deep persistence interface for digest-bound readiness assessments and reevaluation work. */\nexport interface ReadinessRepositoryService extends Success<typeof makeReadinessRepository> {}\n\n/** Effect service binding readiness audit records, current heads, schedules, and queues. */\nexport class ReadinessRepository extends Context.Service<ReadinessRepository, ReadinessRepositoryService>()(\n \"@knpkv/control-center/ReadinessRepository\"\n) {\n static readonly layer = Layer.effect(ReadinessRepository, makeReadinessRepository)\n}\n","import * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport type { Success } from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\n\nimport { Actor } from \"../../../domain/actors.js\"\nimport { LedgerRevision } from \"../../../domain/deliveryGraph.js\"\nimport {\n AgentId,\n EnvironmentId,\n PersonId,\n RelationshipId,\n RelationshipRepairProposalId,\n RelationshipRepairReviewId,\n ReleaseId,\n SessionId,\n WorkspaceId\n} from \"../../../domain/identifiers.js\"\nimport {\n RelationshipRepairApplication,\n RelationshipRepairDisposition,\n RelationshipRepairProposal,\n RelationshipRepairProposalOrigin,\n RelationshipRepairRationale,\n RelationshipRepairReview,\n RelationshipRepairReviewDecision\n} from \"../../../domain/relationshipRepair.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport { Database } from \"../Database.js\"\nimport {\n PersistedRecordError,\n PersistenceOperationError,\n RecordAlreadyExistsError,\n RecordNotFoundError,\n RevisionConflictError\n} from \"../errors.js\"\nimport { mapPersistenceOperation, readChanges } from \"./internal.js\"\n\nconst RECORD_KIND = \"relationship-repair-proposal\"\nconst MAXIMUM_PROPOSAL_PAGE_SIZE = 128\nconst encodeTimestamp = Schema.encodeSync(UtcTimestamp)\n\n/** Raised when a relationship-repair persistence command fails boundary decoding. */\nexport class RelationshipRepairProposalInputError extends Schema.TaggedErrorClass<\n RelationshipRepairProposalInputError\n>()(\"RelationshipRepairProposalInputError\", {\n operation: Schema.Literals([\n \"application\",\n \"create\",\n \"get\",\n \"list\",\n \"list-applications\",\n \"record-application\",\n \"review\"\n ])\n}) {}\n\n/** Caller intent for one durable pending relationship-repair proposal. */\nexport const CreateRelationshipRepairProposalInput = Schema.Struct({\n proposalId: RelationshipRepairProposalId,\n workspaceId: WorkspaceId,\n releaseId: ReleaseId,\n environmentId: Schema.NullOr(EnvironmentId),\n relationshipId: RelationshipId,\n expectedRevision: LedgerRevision,\n disposition: RelationshipRepairDisposition,\n rationale: RelationshipRepairRationale,\n origin: RelationshipRepairProposalOrigin,\n proposedAt: UtcTimestamp\n})\n\n/** Decoded durable relationship-repair proposal intent. */\nexport type CreateRelationshipRepairProposalInput = typeof CreateRelationshipRepairProposalInput.Type\n\n/** Workspace-scoped proposal lookup. */\nexport const ReadRelationshipRepairProposalInput = Schema.Struct({\n workspaceId: WorkspaceId,\n proposalId: RelationshipRepairProposalId\n})\n\n/** Bounded release/environment proposal query. */\nexport const ListRelationshipRepairProposalsInput = Schema.Struct({\n workspaceId: WorkspaceId,\n releaseId: ReleaseId,\n environmentId: Schema.NullOr(EnvironmentId),\n status: Schema.NullOr(RelationshipRepairProposal.fields.status)\n})\n\n/** Bounded release/environment application query matching the proposal page. */\nexport const ListRelationshipRepairApplicationsInput = ListRelationshipRepairProposalsInput\n\n/** Idempotent reviewer decision over one pending proposal. */\nexport const ReviewRelationshipRepairProposalInput = Schema.Struct({\n workspaceId: WorkspaceId,\n proposalId: RelationshipRepairProposalId,\n reviewId: RelationshipRepairReviewId,\n decision: RelationshipRepairReviewDecision,\n rationale: RelationshipRepairRationale,\n origin: RelationshipRepairProposalOrigin,\n reviewedAt: UtcTimestamp\n})\n\n/** Decoded immutable relationship-repair review command. */\nexport type ReviewRelationshipRepairProposalInput = typeof ReviewRelationshipRepairProposalInput.Type\n\n/** Workspace-scoped lookup for an existing proposal application. */\nexport const ReadRelationshipRepairApplicationInput = ReadRelationshipRepairProposalInput\n\n/** Owner-authorized record of an exact relationship revision appended by a proposal. */\nexport const RecordRelationshipRepairApplicationInput = Schema.Struct({\n workspaceId: WorkspaceId,\n proposalId: RelationshipRepairProposalId,\n relationshipId: RelationshipId,\n appliedRevision: LedgerRevision,\n origin: RelationshipRepairProposalOrigin,\n appliedAt: UtcTimestamp\n})\n\n/** Decoded relationship-repair application command. */\nexport type RecordRelationshipRepairApplicationInput = typeof RecordRelationshipRepairApplicationInput.Type\n\nconst ProposalRow = Schema.Struct({\n workspaceId: WorkspaceId,\n proposalId: RelationshipRepairProposalId,\n schemaVersion: Schema.Literal(2),\n releaseId: ReleaseId,\n environmentId: Schema.NullOr(EnvironmentId),\n relationshipId: RelationshipId,\n expectedRevision: LedgerRevision,\n disposition: RelationshipRepairDisposition,\n rationale: RelationshipRepairRationale,\n actorKind: Schema.Literals([\"human\", \"agent\"]),\n personId: Schema.NullOr(PersonId),\n agentId: Schema.NullOr(AgentId),\n sessionId: SessionId,\n status: RelationshipRepairProposal.fields.status,\n proposedAt: UtcTimestamp,\n reviewId: Schema.NullOr(RelationshipRepairReviewId),\n reviewDecision: Schema.NullOr(RelationshipRepairReviewDecision),\n reviewRationale: Schema.NullOr(RelationshipRepairRationale),\n reviewerActorKind: Schema.NullOr(Schema.Literals([\"human\", \"agent\"])),\n reviewerPersonId: Schema.NullOr(PersonId),\n reviewerAgentId: Schema.NullOr(AgentId),\n reviewerSessionId: Schema.NullOr(SessionId),\n reviewedAt: Schema.NullOr(UtcTimestamp)\n})\n\ntype ProposalRow = typeof ProposalRow.Type\nconst ProposalRowIdentity = Schema.Struct({ proposalId: RelationshipRepairProposalId })\n\nconst ApplicationRow = Schema.Struct({\n proposalId: RelationshipRepairProposalId,\n relationshipId: RelationshipId,\n appliedRevision: LedgerRevision,\n actorKind: Schema.Literals([\"human\", \"agent\"]),\n personId: Schema.NullOr(PersonId),\n agentId: Schema.NullOr(AgentId),\n sessionId: SessionId,\n appliedAt: UtcTimestamp\n})\n\nconst actorFromColumns = (input: {\n readonly actorKind: \"human\" | \"agent\"\n readonly personId: PersonId | null\n readonly agentId: AgentId | null\n}): Actor | undefined => {\n if (input.actorKind === \"human\" && input.personId !== null && input.agentId === null) {\n return Actor.make({ _tag: \"human\", personId: input.personId })\n }\n if (input.actorKind === \"agent\" && input.agentId !== null && input.personId === null) {\n return Actor.make({ _tag: \"agent\", agentId: input.agentId })\n }\n return undefined\n}\n\nconst sameActor = (left: Actor, right: Actor): boolean =>\n left._tag === right._tag &&\n (left._tag === \"human\"\n ? left.personId === (right._tag === \"human\" ? right.personId : null)\n : left.agentId === (right._tag === \"agent\" ? right.agentId : null))\n\nconst sameCreateIntent = (\n existing: RelationshipRepairProposal,\n requested: CreateRelationshipRepairProposalInput\n): boolean =>\n existing.proposalId === requested.proposalId &&\n existing.workspaceId === requested.workspaceId &&\n existing.releaseId === requested.releaseId &&\n existing.environmentId === requested.environmentId &&\n existing.relationshipId === requested.relationshipId &&\n existing.expectedRevision === requested.expectedRevision &&\n existing.disposition === requested.disposition &&\n existing.rationale === requested.rationale &&\n existing.origin.sessionId === requested.origin.sessionId &&\n sameActor(existing.origin.actor, requested.origin.actor)\n\nconst sameReviewIntent = (\n existing: RelationshipRepairReview,\n requested: ReviewRelationshipRepairProposalInput\n): boolean =>\n existing.reviewId === requested.reviewId &&\n existing.decision === requested.decision &&\n existing.rationale === requested.rationale &&\n existing.origin.sessionId === requested.origin.sessionId &&\n sameActor(existing.origin.actor, requested.origin.actor)\n\nconst makeRelationshipRepairProposalRepository = Effect.gen(function*() {\n const database = yield* Database\n const sql = database.sql\n\n const findApplicationRows = (\n workspaceId: WorkspaceId,\n proposalId: RelationshipRepairProposalId\n ) =>\n sql<Record<string, unknown>>`SELECT\n proposal_id AS proposalId,\n relationship_id AS relationshipId,\n applied_revision AS appliedRevision,\n actor_kind AS actorKind,\n person_id AS personId,\n agent_id AS agentId,\n session_id AS sessionId,\n applied_at AS appliedAt\n FROM relationship_repair_applications\n WHERE workspace_id = ${workspaceId}\n AND proposal_id = ${proposalId}`\n\n const decodeApplicationRow = Effect.fn(\"RelationshipRepairProposalRepository.decodeApplicationRow\")(function*(\n workspaceId: WorkspaceId,\n proposalId: RelationshipRepairProposalId,\n rawRow: unknown\n ) {\n const decoded = Schema.decodeUnknownResult(ApplicationRow)(rawRow)\n if (Result.isFailure(decoded)) {\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"relationship-repair-application\",\n recordKey: proposalId,\n diagnosticCode: \"relationship-repair-application-schema-invalid\"\n })\n }\n const row = decoded.success\n const actor = actorFromColumns(row)\n if (actor === undefined) {\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"relationship-repair-application\",\n recordKey: proposalId,\n diagnosticCode: \"relationship-repair-application-actor-invalid\"\n })\n }\n return RelationshipRepairApplication.make({\n proposalId: row.proposalId,\n relationshipId: row.relationshipId,\n appliedRevision: row.appliedRevision,\n origin: { actor, sessionId: row.sessionId },\n appliedAt: row.appliedAt\n })\n })\n\n const selectColumns = sql`SELECT\n proposal.workspace_id AS workspaceId,\n proposal.proposal_id AS proposalId,\n proposal.schema_version AS schemaVersion,\n proposal.release_id AS releaseId,\n proposal.environment_id AS environmentId,\n proposal.relationship_id AS relationshipId,\n proposal.expected_revision AS expectedRevision,\n proposal.disposition,\n proposal.rationale,\n proposal.actor_kind AS actorKind,\n proposal.person_id AS personId,\n proposal.agent_id AS agentId,\n proposal.session_id AS sessionId,\n proposal.status,\n proposal.proposed_at AS proposedAt,\n review.review_id AS reviewId,\n review.decision AS reviewDecision,\n review.rationale AS reviewRationale,\n review.actor_kind AS reviewerActorKind,\n review.person_id AS reviewerPersonId,\n review.agent_id AS reviewerAgentId,\n review.session_id AS reviewerSessionId,\n review.reviewed_at AS reviewedAt\n FROM relationship_repair_proposals proposal\n LEFT JOIN relationship_repair_reviews review\n ON review.workspace_id = proposal.workspace_id\n AND review.proposal_id = proposal.proposal_id`\n\n const findRows = (workspaceId: WorkspaceId, proposalId: RelationshipRepairProposalId) =>\n sql<Record<string, unknown>>`${selectColumns}\n WHERE proposal.workspace_id = ${workspaceId}\n AND proposal.proposal_id = ${proposalId}`\n\n const decodeRow = Effect.fn(\"RelationshipRepairProposalRepository.decodeRow\")(function*(\n workspaceId: WorkspaceId,\n proposalId: RelationshipRepairProposalId,\n rawRow: unknown\n ) {\n const decoded = Schema.decodeUnknownResult(ProposalRow)(rawRow)\n if (Result.isFailure(decoded)) {\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: RECORD_KIND,\n recordKey: proposalId,\n diagnosticCode: \"relationship-repair-proposal-schema-invalid\"\n })\n }\n const row = decoded.success\n const actor = actorFromColumns(row)\n if (actor === undefined) {\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: RECORD_KIND,\n recordKey: proposalId,\n diagnosticCode: \"relationship-repair-proposal-actor-invalid\"\n })\n }\n\n let review: RelationshipRepairReview | null = null\n if (row.status === \"pending\") {\n if (\n row.reviewId !== null || row.reviewDecision !== null || row.reviewRationale !== null ||\n row.reviewerActorKind !== null || row.reviewerPersonId !== null || row.reviewerAgentId !== null ||\n row.reviewerSessionId !== null || row.reviewedAt !== null\n ) {\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: RECORD_KIND,\n recordKey: proposalId,\n diagnosticCode: \"relationship-repair-pending-review-invalid\"\n })\n }\n } else {\n if (\n row.reviewId === null || row.reviewDecision !== row.status || row.reviewRationale === null ||\n row.reviewerActorKind === null || row.reviewerSessionId === null || row.reviewedAt === null\n ) {\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: RECORD_KIND,\n recordKey: proposalId,\n diagnosticCode: \"relationship-repair-final-review-invalid\"\n })\n }\n const reviewer = actorFromColumns({\n actorKind: row.reviewerActorKind,\n personId: row.reviewerPersonId,\n agentId: row.reviewerAgentId\n })\n if (reviewer === undefined) {\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: RECORD_KIND,\n recordKey: proposalId,\n diagnosticCode: \"relationship-repair-reviewer-invalid\"\n })\n }\n review = RelationshipRepairReview.make({\n reviewId: row.reviewId,\n decision: row.reviewDecision,\n rationale: row.reviewRationale,\n origin: { actor: reviewer, sessionId: row.reviewerSessionId },\n reviewedAt: row.reviewedAt\n })\n }\n\n return RelationshipRepairProposal.make({\n schemaVersion: row.schemaVersion,\n proposalId: row.proposalId,\n workspaceId: row.workspaceId,\n releaseId: row.releaseId,\n environmentId: row.environmentId,\n relationshipId: row.relationshipId,\n expectedRevision: row.expectedRevision,\n disposition: row.disposition,\n rationale: row.rationale,\n origin: { actor, sessionId: row.sessionId },\n status: row.status,\n proposedAt: row.proposedAt,\n review\n })\n })\n\n const getDecoded = Effect.fn(\"RelationshipRepairProposalRepository.getDecoded\")(function*(input: {\n readonly workspaceId: WorkspaceId\n readonly proposalId: RelationshipRepairProposalId\n }) {\n const rows = yield* findRows(input.workspaceId, input.proposalId)\n const rawRow = rows[0]\n if (rawRow === undefined) {\n return yield* new RecordNotFoundError({\n workspaceId: input.workspaceId,\n recordKind: RECORD_KIND,\n recordKey: input.proposalId\n })\n }\n if (rows.length !== 1) {\n return yield* new PersistenceOperationError({ operation: \"relationship-repair-proposal.read-identity\" })\n }\n return yield* decodeRow(input.workspaceId, input.proposalId, rawRow)\n })\n\n const decodeInput = <Decoded, Encoded>(\n operation:\n | \"application\"\n | \"create\"\n | \"get\"\n | \"list\"\n | \"list-applications\"\n | \"record-application\"\n | \"review\",\n schema: Schema.Codec<Decoded, Encoded>,\n input: unknown\n ) =>\n Schema.decodeUnknownEffect(Schema.toType(schema))(input).pipe(\n Effect.mapError(() => new RelationshipRepairProposalInputError({ operation }))\n )\n\n return {\n application: Effect.fn(\"RelationshipRepairProposalRepository.application\")(function*(input: unknown) {\n const request = yield* decodeInput(\"application\", ReadRelationshipRepairApplicationInput, input)\n const rows = yield* findApplicationRows(request.workspaceId, request.proposalId).pipe(\n mapPersistenceOperation(\"relationship-repair-proposal.application\")\n )\n const row = rows[0]\n if (row === undefined) return null\n if (rows.length !== 1) {\n return yield* new PersistenceOperationError({\n operation: \"relationship-repair-proposal.application-identity\"\n })\n }\n return yield* decodeApplicationRow(request.workspaceId, request.proposalId, row)\n }),\n create: Effect.fn(\"RelationshipRepairProposalRepository.create\")(function*(input: unknown) {\n const request = yield* decodeInput(\"create\", CreateRelationshipRepairProposalInput, input)\n const proposedAt = encodeTimestamp(request.proposedAt)\n return yield* database.transaction(Effect.gen(function*() {\n const existingRows = yield* findRows(request.workspaceId, request.proposalId)\n const existingRaw = existingRows[0]\n if (existingRaw !== undefined) {\n const existing = yield* decodeRow(request.workspaceId, request.proposalId, existingRaw)\n if (sameCreateIntent(existing, request)) return existing\n return yield* new RecordAlreadyExistsError({\n workspaceId: request.workspaceId,\n recordKind: RECORD_KIND,\n recordKey: request.proposalId\n })\n }\n\n const personId = request.origin.actor._tag === \"human\" ? request.origin.actor.personId : null\n const agentId = request.origin.actor._tag === \"agent\" ? request.origin.actor.agentId : null\n yield* sql`INSERT OR IGNORE INTO relationship_repair_proposals (\n workspace_id, proposal_id, schema_version, release_id, environment_id,\n relationship_id, expected_revision, disposition, rationale, actor_kind,\n person_id, agent_id, session_id, status, proposed_at\n ) SELECT\n ${request.workspaceId}, ${request.proposalId}, 2, ${request.releaseId}, ${request.environmentId},\n ${request.relationshipId}, ${request.expectedRevision}, ${request.disposition}, ${request.rationale},\n ${request.origin.actor._tag}, ${personId}, ${agentId}, ${request.origin.sessionId}, 'pending',\n ${proposedAt}\n FROM relationship_heads head\n JOIN relationship_revisions revision\n ON revision.workspace_id = head.workspace_id\n AND revision.relationship_id = head.relationship_id\n AND revision.revision = head.current_revision\n WHERE head.workspace_id = ${request.workspaceId}\n AND head.relationship_id = ${request.relationshipId}\n AND head.current_revision = ${request.expectedRevision}\n AND revision.release_id = ${request.releaseId}\n AND (\n (${request.environmentId} IS NULL AND revision.environment_id IS NULL) OR\n revision.environment_id = ${request.environmentId}\n )\n AND revision.lifecycle IN ('missing', 'inferred', 'proposed')`\n\n if ((yield* readChanges(sql)) === 0) {\n const headRows = yield* sql<Record<string, unknown>>`SELECT current_revision AS revision\n FROM relationship_heads\n WHERE workspace_id = ${request.workspaceId}\n AND relationship_id = ${request.relationshipId}`\n const head = Schema.decodeUnknownResult(Schema.Struct({ revision: LedgerRevision }))(headRows[0])\n if (Result.isSuccess(head) && head.success.revision !== request.expectedRevision) {\n return yield* new RevisionConflictError({\n workspaceId: request.workspaceId,\n recordKind: \"delivery-relationship\",\n recordKey: request.relationshipId,\n expectedRevision: request.expectedRevision,\n actualRevision: head.success.revision\n })\n }\n if (Result.isSuccess(head)) {\n const pendingRows = yield* sql`SELECT proposal_id\n FROM relationship_repair_proposals\n WHERE workspace_id = ${request.workspaceId}\n AND relationship_id = ${request.relationshipId}\n AND expected_revision = ${request.expectedRevision}\n AND status = 'pending'`\n if (pendingRows.length > 0) {\n return yield* new RecordAlreadyExistsError({\n workspaceId: request.workspaceId,\n recordKind: RECORD_KIND,\n recordKey: request.proposalId\n })\n }\n }\n return yield* new RecordNotFoundError({\n workspaceId: request.workspaceId,\n recordKind: \"delivery-relationship\",\n recordKey: request.relationshipId\n })\n }\n return yield* getDecoded(request)\n })).pipe(mapPersistenceOperation(\"relationship-repair-proposal.create\"))\n }),\n get: Effect.fn(\"RelationshipRepairProposalRepository.get\")(function*(input: unknown) {\n const request = yield* decodeInput(\"get\", ReadRelationshipRepairProposalInput, input)\n return yield* getDecoded(request).pipe(mapPersistenceOperation(\"relationship-repair-proposal.get\"))\n }),\n list: Effect.fn(\"RelationshipRepairProposalRepository.list\")(function*(input: unknown) {\n const request = yield* decodeInput(\"list\", ListRelationshipRepairProposalsInput, input)\n const rows = yield* sql<Record<string, unknown>>`${selectColumns}\n WHERE proposal.workspace_id = ${request.workspaceId}\n AND proposal.release_id = ${request.releaseId}\n AND (\n (${request.environmentId} IS NULL AND proposal.environment_id IS NULL) OR\n proposal.environment_id = ${request.environmentId}\n )\n AND (${request.status} IS NULL OR proposal.status = ${request.status})\n ORDER BY proposal.proposed_at DESC, proposal.proposal_id DESC\n LIMIT ${MAXIMUM_PROPOSAL_PAGE_SIZE + 1}`.pipe(\n mapPersistenceOperation(\"relationship-repair-proposal.list\")\n )\n const proposals = yield* Effect.forEach(\n rows.slice(0, MAXIMUM_PROPOSAL_PAGE_SIZE),\n (row) =>\n Effect.gen(function*() {\n const identity = Schema.decodeUnknownResult(ProposalRowIdentity)(row)\n if (Result.isFailure(identity)) {\n return yield* new PersistedRecordError({\n workspaceId: request.workspaceId,\n recordKind: RECORD_KIND,\n recordKey: request.releaseId,\n diagnosticCode: \"relationship-repair-proposal-identity-invalid\"\n })\n }\n return yield* decodeRow(request.workspaceId, identity.success.proposalId, row)\n }),\n { concurrency: 1 }\n )\n return { proposals, truncated: rows.length > MAXIMUM_PROPOSAL_PAGE_SIZE }\n }),\n listApplications: Effect.fn(\"RelationshipRepairProposalRepository.listApplications\")(function*(input: unknown) {\n const request = yield* decodeInput(\"list-applications\", ListRelationshipRepairApplicationsInput, input)\n const rows = yield* sql<Record<string, unknown>>`WITH proposal_page AS (\n SELECT proposal_id\n FROM relationship_repair_proposals\n WHERE workspace_id = ${request.workspaceId}\n AND release_id = ${request.releaseId}\n AND (\n (${request.environmentId} IS NULL AND environment_id IS NULL) OR\n environment_id = ${request.environmentId}\n )\n AND (${request.status} IS NULL OR status = ${request.status})\n ORDER BY proposed_at DESC, proposal_id DESC\n LIMIT ${MAXIMUM_PROPOSAL_PAGE_SIZE}\n )\n SELECT\n application.proposal_id AS proposalId,\n application.relationship_id AS relationshipId,\n application.applied_revision AS appliedRevision,\n application.actor_kind AS actorKind,\n application.person_id AS personId,\n application.agent_id AS agentId,\n application.session_id AS sessionId,\n application.applied_at AS appliedAt\n FROM relationship_repair_applications application\n JOIN proposal_page page ON page.proposal_id = application.proposal_id\n WHERE application.workspace_id = ${request.workspaceId}\n ORDER BY application.applied_at DESC, application.proposal_id DESC`.pipe(\n mapPersistenceOperation(\"relationship-repair-proposal.list-applications\")\n )\n return yield* Effect.forEach(\n rows,\n (row) => {\n const identity = Schema.decodeUnknownResult(ProposalRowIdentity)(row)\n if (Result.isFailure(identity)) {\n return Effect.fail(\n new PersistedRecordError({\n workspaceId: request.workspaceId,\n recordKind: \"relationship-repair-application\",\n recordKey: request.releaseId,\n diagnosticCode: \"relationship-repair-application-identity-invalid\"\n })\n )\n }\n return decodeApplicationRow(request.workspaceId, identity.success.proposalId, row)\n },\n { concurrency: 1 }\n )\n }),\n review: Effect.fn(\"RelationshipRepairProposalRepository.review\")(function*(input: unknown) {\n const request = yield* decodeInput(\"review\", ReviewRelationshipRepairProposalInput, input)\n const reviewedAt = encodeTimestamp(request.reviewedAt)\n return yield* database.transaction(Effect.gen(function*() {\n const proposal = yield* getDecoded(request)\n if (proposal.review !== null) {\n if (sameReviewIntent(proposal.review, request)) return proposal\n return yield* new RecordAlreadyExistsError({\n workspaceId: request.workspaceId,\n recordKind: \"relationship-repair-review\",\n recordKey: request.reviewId\n })\n }\n if (sameActor(proposal.origin.actor, request.origin.actor)) {\n return yield* new RecordAlreadyExistsError({\n workspaceId: request.workspaceId,\n recordKind: \"relationship-repair-review\",\n recordKey: request.reviewId\n })\n }\n\n const reviewCollision = yield* sql`SELECT proposal_id\n FROM relationship_repair_reviews\n WHERE workspace_id = ${request.workspaceId}\n AND review_id = ${request.reviewId}`\n if (reviewCollision.length > 0) {\n return yield* new RecordAlreadyExistsError({\n workspaceId: request.workspaceId,\n recordKind: \"relationship-repair-review\",\n recordKey: request.reviewId\n })\n }\n\n const personId = request.origin.actor._tag === \"human\" ? request.origin.actor.personId : null\n const agentId = request.origin.actor._tag === \"agent\" ? request.origin.actor.agentId : null\n yield* sql`INSERT INTO relationship_repair_reviews (\n workspace_id, proposal_id, review_id, decision, rationale, actor_kind,\n person_id, agent_id, session_id, reviewed_at\n ) VALUES (\n ${request.workspaceId}, ${request.proposalId}, ${request.reviewId}, ${request.decision},\n ${request.rationale}, ${request.origin.actor._tag}, ${personId}, ${agentId},\n ${request.origin.sessionId}, ${reviewedAt}\n )`\n return yield* getDecoded(request)\n })).pipe(mapPersistenceOperation(\"relationship-repair-proposal.review\"))\n }),\n recordApplication: Effect.fn(\"RelationshipRepairProposalRepository.recordApplication\")(function*(input: unknown) {\n const request = yield* decodeInput(\n \"record-application\",\n RecordRelationshipRepairApplicationInput,\n input\n )\n const appliedAt = encodeTimestamp(request.appliedAt)\n return yield* database.transaction(Effect.gen(function*() {\n const existingRows = yield* findApplicationRows(request.workspaceId, request.proposalId)\n const existing = existingRows[0]\n if (existing !== undefined) {\n return yield* decodeApplicationRow(request.workspaceId, request.proposalId, existing)\n }\n const personId = request.origin.actor._tag === \"human\" ? request.origin.actor.personId : null\n const agentId = request.origin.actor._tag === \"agent\" ? request.origin.actor.agentId : null\n yield* sql`INSERT INTO relationship_repair_applications (\n workspace_id, proposal_id, relationship_id, applied_revision,\n actor_kind, person_id, agent_id, session_id, applied_at\n ) VALUES (\n ${request.workspaceId}, ${request.proposalId}, ${request.relationshipId},\n ${request.appliedRevision}, ${request.origin.actor._tag}, ${personId}, ${agentId},\n ${request.origin.sessionId}, ${appliedAt}\n )`\n const rows = yield* findApplicationRows(request.workspaceId, request.proposalId)\n const row = rows[0]\n if (row === undefined) {\n return yield* new PersistenceOperationError({\n operation: \"relationship-repair-proposal.record-application-readback\"\n })\n }\n return yield* decodeApplicationRow(request.workspaceId, request.proposalId, row)\n })).pipe(mapPersistenceOperation(\"relationship-repair-proposal.record-application\"))\n })\n }\n})\n\n/** Workspace-scoped durable relationship-repair proposal persistence. */\nexport interface RelationshipRepairProposalRepositoryService\n extends Success<typeof makeRelationshipRepairProposalRepository>\n{}\n\n/** Server-only repository for relationship-repair proposals and immutable reviews. */\nexport class RelationshipRepairProposalRepository extends Context.Service<\n RelationshipRepairProposalRepository,\n RelationshipRepairProposalRepositoryService\n>()(\"@knpkv/control-center/RelationshipRepairProposalRepository\") {\n /** Layer binding proposal persistence to the shared database. */\n static readonly layer = Layer.effect(\n RelationshipRepairProposalRepository,\n makeRelationshipRepairProposalRepository\n )\n}\n","import * as Context from \"effect/Context\"\nimport * as Crypto from \"effect/Crypto\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport type { Success } from \"effect/Effect\"\nimport * as Encoding from \"effect/Encoding\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\"\n\nimport { RoleAssignment } from \"../../../domain/actors.js\"\nimport { EnvironmentId, ReleaseId, WorkspaceId } from \"../../../domain/identifiers.js\"\nimport { Release } from \"../../../domain/release.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport { Database } from \"../Database.js\"\nimport {\n PersistedRecordError,\n PersistenceOperationError,\n RecordNotFoundError,\n SourceIdentityMismatchError\n} from \"../errors.js\"\nimport {\n mapAlreadyExists,\n mapPersistenceOperation,\n readChanges,\n resolveCasFailure,\n revisionLookup\n} from \"./internal.js\"\nimport {\n ContentBlobDigest,\n type QuarantineDiagnosticSummary,\n type QuarantineReasonCode,\n RecordRevision,\n ReleaseSnapshotRecord\n} from \"./models.js\"\nimport { makePersistedRowQuarantine } from \"./persistedRowQuarantine.js\"\nimport { QuarantineRepository } from \"./quarantineRepository.js\"\n\nconst RELEASE_SCHEMA_VERSION = 1\n\nconst ReleaseKey = Schema.Struct({ workspaceId: WorkspaceId, releaseId: ReleaseId })\n\nconst ReleaseRevisionRow = Schema.Struct({\n revision: RecordRevision,\n snapshotJson: Schema.String.check(Schema.isNonEmpty()),\n snapshotDigest: ContentBlobDigest,\n createdAt: UtcTimestamp\n})\n\nconst ReleaseRevisionIdentity = Schema.Struct({ revision: RecordRevision })\n\n/** Maximum number of release heads returned by one portfolio read. */\nexport const ReleaseListLimit = Schema.Int.check(\n Schema.isBetween({ minimum: 1, maximum: 200 })\n).pipe(Schema.brand(\"ReleaseListLimit\"))\n\nexport type ReleaseListLimit = typeof ReleaseListLimit.Type\n\nconst ReleaseListHead = Schema.Struct({\n releaseId: ReleaseId,\n revision: RecordRevision,\n updatedAt: UtcTimestamp\n})\n\nconst CreateReleaseRequest = Schema.Struct({\n ...ReleaseKey.fields,\n snapshotJson: Schema.String.check(Schema.isNonEmpty()),\n snapshotDigest: ContentBlobDigest,\n createdAt: UtcTimestamp,\n updatedAt: UtcTimestamp\n})\n\nconst AppendReleaseRequest = Schema.Struct({\n ...CreateReleaseRequest.fields,\n expectedRevision: RecordRevision\n})\n\nconst releaseJson = Schema.fromJsonString(Release)\nconst encodeTimestamp = Schema.encodeSync(UtcTimestamp)\nconst encodeRelease = Schema.encodeEffect(releaseJson)\nconst decodeRelease = Schema.decodeUnknownResult(releaseJson)\n\nconst encodeDigest = (bytes: Uint8Array): string =>\n Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")\n\nconst makeReleaseRepository = Effect.gen(function*() {\n const database = yield* Database\n const cryptoService = yield* Crypto.Crypto\n const quarantine = yield* QuarantineRepository\n const quarantineRow = makePersistedRowQuarantine(cryptoService, quarantine)\n const sql = database.sql\n\n const digestSnapshot = Effect.fn(\"ReleaseRepository.digestSnapshot\")(function*(snapshotJson: string) {\n const bytes = yield* Effect.fromResult(\n Encoding.decodeBase64(Encoding.encodeBase64(snapshotJson))\n ).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"release.encode-utf8\" }))\n )\n const digest = yield* cryptoService.digest(\"SHA-256\", bytes).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"release.digest\" }))\n )\n return ContentBlobDigest.make(encodeDigest(digest))\n })\n\n const prepareSnapshot = Effect.fn(\"ReleaseRepository.prepareSnapshot\")(function*(release: Release) {\n const snapshotJson = yield* encodeRelease(release).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"release.encode\" }))\n )\n const snapshotDigest = yield* digestSnapshot(snapshotJson)\n return { snapshotJson, snapshotDigest }\n })\n\n const insertHead = SqlSchema.void({\n Request: CreateReleaseRequest,\n execute: ({ createdAt, releaseId, updatedAt, workspaceId }) =>\n sql`INSERT INTO releases (\n workspace_id, release_id, current_revision, created_at, updated_at\n ) VALUES (${workspaceId}, ${releaseId}, 1, ${createdAt}, ${updatedAt})`\n })\n\n const insertRevision = SqlSchema.void({\n Request: Schema.Struct({\n ...CreateReleaseRequest.fields,\n revision: RecordRevision\n }),\n execute: ({ releaseId, revision, snapshotDigest, snapshotJson, updatedAt, workspaceId }) =>\n sql`INSERT INTO release_revisions (\n workspace_id, release_id, revision, snapshot_json, snapshot_digest, created_at\n ) VALUES (\n ${workspaceId}, ${releaseId}, ${revision}, ${snapshotJson}, ${snapshotDigest}, ${updatedAt}\n )`\n })\n\n const insertTarget = SqlSchema.void({\n Request: Schema.Struct({\n ...ReleaseKey.fields,\n environmentId: EnvironmentId,\n createdAt: UtcTimestamp\n }),\n execute: ({ createdAt, environmentId, releaseId, workspaceId }) =>\n sql`INSERT INTO release_targets (\n workspace_id, release_id, environment_id, created_at,\n lifecycle_kind, ended_at\n ) VALUES (\n ${workspaceId}, ${releaseId}, ${environmentId}, ${createdAt},\n 'active', NULL\n )\n ON CONFLICT (workspace_id, release_id, environment_id) DO UPDATE SET\n lifecycle_kind = 'active',\n ended_at = NULL`\n })\n\n const replaceTargets = Effect.fn(\"ReleaseRepository.replaceTargets\")(function*(\n workspaceId: WorkspaceId,\n release: Release\n ) {\n yield* Effect.forEach(\n release.targetEnvironmentIds,\n (environmentId) =>\n insertTarget({\n workspaceId,\n releaseId: release.id,\n environmentId,\n createdAt: release.updatedAt\n }),\n { discard: true }\n )\n })\n\n const TargetHead = Schema.Struct({ environmentId: EnvironmentId })\n\n const listTargetHeads = SqlSchema.findAll({\n Request: ReleaseKey,\n Result: TargetHead,\n execute: ({ releaseId, workspaceId }) =>\n sql`SELECT environment_id AS environmentId\n FROM release_targets\n WHERE workspace_id = ${workspaceId}\n AND release_id = ${releaseId}\n AND lifecycle_kind = 'active'`\n })\n\n const endObsoleteTargets = Effect.fn(\"ReleaseRepository.endObsoleteTargets\")(function*(\n workspaceId: WorkspaceId,\n release: Release\n ) {\n const endedAt = encodeTimestamp(release.updatedAt)\n const desired = new Set(release.targetEnvironmentIds)\n const existing = yield* listTargetHeads({ workspaceId, releaseId: release.id })\n yield* Effect.forEach(\n existing.filter(({ environmentId }) => !desired.has(environmentId)),\n ({ environmentId }) =>\n sql`UPDATE release_targets\n SET lifecycle_kind = 'ended',\n ended_at = ${endedAt}\n WHERE workspace_id = ${workspaceId}\n AND release_id = ${release.id}\n AND environment_id = ${environmentId}\n AND lifecycle_kind = 'active'`,\n { discard: true }\n )\n })\n\n const insertProjectedAssignment = SqlSchema.void({\n Request: Schema.Struct({\n workspaceId: WorkspaceId,\n assignment: RoleAssignment,\n timestamp: UtcTimestamp\n }),\n execute: ({ assignment, timestamp, workspaceId }) => {\n const personId = assignment.actor._tag === \"human\" ? assignment.actor.personId : null\n const agentId = assignment.actor._tag === \"agent\" ? assignment.actor.agentId : null\n const releaseId = assignment.scope._tag === \"release\" || assignment.scope._tag === \"environment\"\n ? assignment.scope.releaseId\n : null\n const environmentId = assignment.scope._tag === \"environment\" ? assignment.scope.environmentId : null\n const entityId = assignment.scope._tag === \"entity\" ? assignment.scope.entityId : null\n const endedAt = assignment.lifecycle._tag === \"ended\" ? assignment.lifecycle.endedAt : null\n const revokedAt = assignment.lifecycle._tag === \"revoked\" ? assignment.lifecycle.revokedAt : null\n return sql`INSERT INTO role_assignments (\n workspace_id, assignment_id, actor_kind, person_id, agent_id, role,\n scope_kind, release_id, environment_id, entity_id, lifecycle_kind,\n assigned_at, ended_at, revoked_at, revision, created_at, updated_at\n ) VALUES (\n ${workspaceId}, ${assignment.assignmentId}, ${assignment.actor._tag}, ${personId},\n ${agentId}, ${assignment.role}, ${assignment.scope._tag}, ${releaseId},\n ${environmentId}, ${entityId}, ${assignment.lifecycle._tag},\n ${assignment.lifecycle.assignedAt}, ${endedAt}, ${revokedAt}, 1, ${timestamp}, ${timestamp}\n )\n ON CONFLICT (workspace_id, assignment_id) DO UPDATE SET\n actor_kind = excluded.actor_kind,\n person_id = excluded.person_id,\n agent_id = excluded.agent_id,\n role = excluded.role,\n scope_kind = excluded.scope_kind,\n release_id = excluded.release_id,\n environment_id = excluded.environment_id,\n entity_id = excluded.entity_id,\n lifecycle_kind = excluded.lifecycle_kind,\n assigned_at = excluded.assigned_at,\n ended_at = excluded.ended_at,\n revoked_at = excluded.revoked_at,\n revision = role_assignments.revision + 1,\n updated_at = excluded.updated_at`\n }\n })\n\n const ProjectionHead = Schema.Struct({\n assignmentId: RoleAssignment.fields.assignmentId,\n releaseId: Schema.Union([ReleaseId, Schema.Null]),\n revision: RecordRevision\n })\n\n const listProjectionHeads = SqlSchema.findAll({\n Request: ReleaseKey,\n Result: ProjectionHead,\n execute: ({ releaseId, workspaceId }) =>\n sql`SELECT\n assignment_id AS assignmentId,\n release_id AS releaseId,\n revision\n FROM role_assignments\n WHERE workspace_id = ${workspaceId}\n AND release_id = ${releaseId}`\n })\n\n const findProjectionHead = SqlSchema.findOneOption({\n Request: Schema.Struct({\n workspaceId: WorkspaceId,\n assignmentId: RoleAssignment.fields.assignmentId\n }),\n Result: ProjectionHead,\n execute: ({ assignmentId, workspaceId }) =>\n sql`SELECT\n assignment_id AS assignmentId,\n release_id AS releaseId,\n revision\n FROM role_assignments\n WHERE workspace_id = ${workspaceId}\n AND assignment_id = ${assignmentId}`\n })\n\n const replaceRoleAssignments = Effect.fn(\"ReleaseRepository.replaceRoleAssignments\")(function*(\n workspaceId: WorkspaceId,\n release: Release\n ) {\n const updatedAt = encodeTimestamp(release.updatedAt)\n const projected = release.roleAssignments.filter(\n ({ scope }) => scope._tag === \"release\" || scope._tag === \"environment\"\n )\n const desiredIds = new Set(projected.map(({ assignmentId }) => assignmentId))\n const existing = yield* listProjectionHeads({ workspaceId, releaseId: release.id })\n yield* Effect.forEach(\n existing.filter(({ assignmentId }) => !desiredIds.has(assignmentId)),\n ({ assignmentId }) =>\n sql`UPDATE role_assignments\n SET lifecycle_kind = 'ended',\n ended_at = ${updatedAt},\n revoked_at = NULL,\n revision = revision + 1,\n updated_at = ${updatedAt}\n WHERE workspace_id = ${workspaceId}\n AND assignment_id = ${assignmentId}\n AND lifecycle_kind = 'active'`,\n { discard: true }\n )\n yield* Effect.forEach(\n projected,\n (assignment) =>\n Effect.gen(function*() {\n const head = yield* findProjectionHead({ workspaceId, assignmentId: assignment.assignmentId })\n if (Option.isSome(head) && head.value.releaseId !== release.id) {\n return yield* new SourceIdentityMismatchError({\n workspaceId,\n recordKind: \"role-assignment\",\n recordKey: assignment.assignmentId\n })\n }\n yield* insertProjectedAssignment({ workspaceId, assignment, timestamp: release.updatedAt })\n }),\n { discard: true }\n )\n })\n\n const updateHead = SqlSchema.void({\n Request: AppendReleaseRequest,\n execute: ({ expectedRevision, releaseId, updatedAt, workspaceId }) =>\n sql`UPDATE releases\n SET current_revision = current_revision + 1,\n updated_at = ${updatedAt}\n WHERE workspace_id = ${workspaceId}\n AND release_id = ${releaseId}\n AND current_revision = ${expectedRevision}`\n })\n\n const ReleaseHead = Schema.Struct({\n revision: RecordRevision,\n createdAt: UtcTimestamp\n })\n\n const findReleaseHead = SqlSchema.findOneOption({\n Request: ReleaseKey,\n Result: ReleaseHead,\n execute: ({ releaseId, workspaceId }) =>\n sql`SELECT current_revision AS revision, created_at AS createdAt\n FROM releases\n WHERE workspace_id = ${workspaceId}\n AND release_id = ${releaseId}`\n })\n\n const findReleaseHeadRows = ({ releaseId, workspaceId }: typeof ReleaseKey.Type) =>\n sql<Record<string, unknown>>`SELECT current_revision AS revision, created_at AS createdAt\n FROM releases\n WHERE workspace_id = ${workspaceId}\n AND release_id = ${releaseId}`\n\n const findRevisionRows = ({ releaseId, workspaceId }: typeof ReleaseKey.Type) =>\n sql<Record<string, unknown>>`SELECT\n revision,\n snapshot_json AS snapshotJson,\n snapshot_digest AS snapshotDigest,\n created_at AS createdAt\n FROM release_revisions\n WHERE workspace_id = ${workspaceId}\n AND release_id = ${releaseId}\n ORDER BY revision DESC`\n\n const listHeadRows = (workspaceId: WorkspaceId, limit: ReleaseListLimit) =>\n sql<Record<string, unknown>>`SELECT\n release_id AS releaseId,\n current_revision AS revision,\n updated_at AS updatedAt\n FROM releases\n WHERE workspace_id = ${workspaceId}\n ORDER BY updated_at DESC, release_id\n LIMIT ${limit}`\n\n const quarantineMalformed = Effect.fn(\"ReleaseRepository.quarantineMalformed\")(function*(\n workspaceId: WorkspaceId,\n releaseId: ReleaseId,\n row: typeof ReleaseRevisionRow.Type,\n diagnosticCode: QuarantineReasonCode,\n diagnosticSummary: QuarantineDiagnosticSummary,\n observedAt: UtcTimestamp,\n payloadDigest: ContentBlobDigest = row.snapshotDigest\n ) {\n yield* quarantine.recordMalformed(workspaceId, {\n recordKind: \"release-revision\",\n recordKey: `${releaseId}:${row.revision}`,\n schemaVersion: RELEASE_SCHEMA_VERSION,\n payloadDigest,\n diagnosticCode,\n diagnosticSummary,\n observedAt\n })\n })\n\n const decodeLatestValid = Effect.fn(\"ReleaseRepository.decodeLatestValid\")(function*(\n workspaceId: WorkspaceId,\n releaseId: ReleaseId,\n rows: ReadonlyArray<typeof ReleaseRevisionRow.Type>\n ) {\n const observedAt = yield* DateTime.now\n for (const row of rows) {\n const actualDigest = yield* digestSnapshot(row.snapshotJson)\n if (actualDigest !== row.snapshotDigest) {\n yield* quarantineMalformed(\n workspaceId,\n releaseId,\n row,\n \"snapshot-digest-mismatch\",\n \"Stored release snapshot digest does not match its content.\",\n observedAt,\n actualDigest\n )\n continue\n }\n\n const decoded = decodeRelease(row.snapshotJson)\n if (Result.isFailure(decoded)) {\n yield* quarantineMalformed(\n workspaceId,\n releaseId,\n row,\n \"schema-decode-failed\",\n \"Stored release snapshot does not satisfy the current release schema.\",\n observedAt\n )\n continue\n }\n if (decoded.success.workspaceId !== workspaceId || decoded.success.id !== releaseId) {\n yield* quarantineMalformed(\n workspaceId,\n releaseId,\n row,\n \"snapshot-identity-mismatch\",\n \"Stored release snapshot identity does not match its repository key.\",\n observedAt\n )\n continue\n }\n return yield* Schema.decodeUnknownEffect(Schema.toType(ReleaseSnapshotRecord))({\n release: decoded.success,\n revision: row.revision\n })\n }\n\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"release\",\n recordKey: releaseId,\n diagnosticCode: \"no-valid-snapshot\"\n })\n })\n\n const get = Effect.fn(\"ReleaseRepository.get\")(function*(\n workspaceId: WorkspaceId,\n releaseId: ReleaseId\n ) {\n const headRows = yield* findReleaseHeadRows({ workspaceId, releaseId })\n if (headRows.length === 0) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"release\",\n recordKey: releaseId\n })\n }\n const head = Schema.decodeUnknownResult(ReleaseHead)(headRows[0])\n if (Result.isFailure(head)) {\n const observedAt = yield* DateTime.now\n yield* quarantineRow({\n workspaceId,\n recordKind: \"release-head\",\n recordKey: releaseId,\n diagnosticCode: \"release-head-schema-invalid\",\n diagnosticSummary: \"Stored release head failed schema validation.\",\n observedAt,\n row: headRows[0]\n })\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"release\",\n recordKey: releaseId,\n diagnosticCode: \"release-head-schema-invalid\"\n })\n }\n const rawRows = yield* findRevisionRows({ workspaceId, releaseId })\n const rows: Array<typeof ReleaseRevisionRow.Type> = []\n for (const rawRow of rawRows) {\n const identity = Schema.decodeUnknownResult(ReleaseRevisionIdentity)(rawRow)\n const recordKey = Result.isSuccess(identity)\n ? `${releaseId}:${identity.success.revision}`\n : releaseId\n if (Result.isSuccess(identity) && identity.success.revision > head.success.revision) {\n const observedAt = yield* DateTime.now\n yield* quarantineRow({\n workspaceId,\n recordKind: \"release-revision\",\n recordKey,\n diagnosticCode: \"snapshot-beyond-head\",\n diagnosticSummary: \"Stored release snapshot exceeds its authoritative head.\",\n observedAt,\n row: rawRow\n })\n continue\n }\n const decoded = Schema.decodeUnknownResult(ReleaseRevisionRow)(rawRow)\n if (Result.isFailure(decoded)) {\n const observedAt = yield* DateTime.now\n yield* quarantineRow({\n workspaceId,\n recordKind: \"release-revision\",\n recordKey,\n diagnosticCode: \"release-revision-envelope-invalid\",\n diagnosticSummary: \"Stored release revision envelope failed schema validation.\",\n observedAt,\n row: rawRow\n })\n continue\n }\n rows.push(decoded.success)\n }\n return yield* decodeLatestValid(workspaceId, releaseId, rows)\n })\n\n const ensureWorkspace = Effect.fn(\"ReleaseRepository.ensureWorkspace\")(function*(\n workspaceId: WorkspaceId,\n release: Release\n ) {\n if (release.workspaceId !== workspaceId) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"release\",\n recordKey: release.id\n })\n }\n })\n\n return {\n create: Effect.fn(\"ReleaseRepository.create\")(function*(workspaceId: WorkspaceId, release: Release) {\n yield* ensureWorkspace(workspaceId, release)\n const snapshot = yield* prepareSnapshot(release)\n yield* database.transaction(\n Effect.gen(function*() {\n yield* insertHead({\n workspaceId,\n releaseId: release.id,\n ...snapshot,\n createdAt: release.createdAt,\n updatedAt: release.updatedAt\n })\n yield* insertRevision({\n workspaceId,\n releaseId: release.id,\n ...snapshot,\n createdAt: release.createdAt,\n updatedAt: release.updatedAt,\n revision: RecordRevision.make(1)\n })\n yield* replaceTargets(workspaceId, release)\n yield* replaceRoleAssignments(workspaceId, release)\n yield* endObsoleteTargets(workspaceId, release)\n }).pipe(\n mapAlreadyExists({ workspaceId, recordKind: \"release\", recordKey: release.id }),\n mapPersistenceOperation(\"release.create\")\n )\n )\n return yield* get(workspaceId, release.id)\n }),\n get: (workspaceId: WorkspaceId, releaseId: ReleaseId) =>\n get(workspaceId, releaseId).pipe(mapPersistenceOperation(\"release.get\")),\n list: Effect.fn(\"ReleaseRepository.list\")(function*(\n workspaceId: WorkspaceId,\n requestedLimit: number\n ) {\n const limit = yield* Schema.decodeUnknownEffect(ReleaseListLimit)(requestedLimit).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"release.list-limit\" }))\n )\n const rows = yield* listHeadRows(workspaceId, limit).pipe(\n mapPersistenceOperation(\"release.list-heads\")\n )\n const snapshots: Array<typeof ReleaseSnapshotRecord.Type> = []\n for (const row of rows) {\n const head = Schema.decodeUnknownResult(ReleaseListHead)(row)\n if (Result.isFailure(head)) {\n const identity = Schema.decodeUnknownResult(Schema.Struct({ releaseId: ReleaseId }))(row)\n const recordKey = Result.isSuccess(identity) ? identity.success.releaseId : workspaceId\n yield* quarantineRow({\n workspaceId,\n recordKind: \"release-head\",\n recordKey,\n diagnosticCode: \"release-head-schema-invalid\",\n diagnosticSummary: \"Stored release head failed schema validation.\",\n observedAt: yield* DateTime.now,\n row\n })\n continue\n }\n const snapshot = yield* get(workspaceId, head.success.releaseId).pipe(Effect.result)\n if (Result.isSuccess(snapshot)) {\n snapshots.push(snapshot.success)\n continue\n }\n if (snapshot.failure._tag === \"PersistedRecordError\" || snapshot.failure._tag === \"RecordNotFoundError\") {\n continue\n }\n return yield* snapshot.failure\n }\n return snapshots\n }),\n append: Effect.fn(\"ReleaseRepository.append\")(function*(\n workspaceId: WorkspaceId,\n release: Release,\n expectedRevision: RecordRevision\n ) {\n yield* ensureWorkspace(workspaceId, release)\n const snapshot = yield* prepareSnapshot(release)\n yield* database.transaction(\n Effect.gen(function*() {\n const head = yield* findReleaseHead({ workspaceId, releaseId: release.id })\n if (Option.isNone(head)) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"release\",\n recordKey: release.id\n })\n }\n if (!DateTime.Equivalence(head.value.createdAt, release.createdAt)) {\n return yield* new SourceIdentityMismatchError({\n workspaceId,\n recordKind: \"release\",\n recordKey: release.id\n })\n }\n yield* updateHead({\n workspaceId,\n releaseId: release.id,\n ...snapshot,\n createdAt: release.createdAt,\n updatedAt: release.updatedAt,\n expectedRevision\n })\n const changes = yield* readChanges(sql)\n if (changes === 0) {\n return yield* resolveCasFailure({\n workspaceId,\n recordKind: \"release\",\n recordKey: release.id,\n expectedRevision,\n findActualRevision: revisionLookup(() =>\n sql`SELECT current_revision AS revision\n FROM releases\n WHERE workspace_id = ${workspaceId}\n AND release_id = ${release.id}`\n )\n })\n }\n yield* insertRevision({\n workspaceId,\n releaseId: release.id,\n ...snapshot,\n createdAt: release.createdAt,\n updatedAt: release.updatedAt,\n revision: RecordRevision.make(expectedRevision + 1)\n })\n yield* replaceTargets(workspaceId, release)\n yield* replaceRoleAssignments(workspaceId, release)\n yield* endObsoleteTargets(workspaceId, release)\n }).pipe(mapPersistenceOperation(\"release.append\"))\n )\n return yield* get(workspaceId, release.id)\n })\n }\n})\n\n/** Immutable release snapshots with CAS heads and quarantined fallback reads. */\nexport interface ReleaseRepositoryService extends Success<typeof makeReleaseRepository> {}\n\n/** Effect service for release aggregate persistence. */\nexport class ReleaseRepository extends Context.Service<ReleaseRepository, ReleaseRepositoryService>()(\n \"@knpkv/control-center/ReleaseRepository\"\n) {\n /** Layer that captures database, cryptography, and quarantine dependencies. */\n static readonly layer = Layer.effect(ReleaseRepository, makeReleaseRepository)\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 Schema from \"effect/Schema\"\n\nimport type { SessionSummary } from \"../../api/session.js\"\nimport type { Role } from \"../../domain/actors.js\"\nimport { governedActionPermissionGrants } from \"../../domain/governedAction/index.js\"\nimport { PersonId, SessionId, WorkspaceId, WorkspaceSettingsMutationId } from \"../../domain/identifiers.js\"\nimport type { UtcTimestamp } from \"../../domain/utcTimestamp.js\"\nimport { GovernedWorkspaceSettingsSections, WorkspaceSettingsV1 } from \"../../domain/workspaceSettings.js\"\nimport { ContentBlobDigest, RecordRevision } from \"../persistence/repositories/models.js\"\n\n/** Provider-neutral D03 policy input shared by local and plugin mutations. */\nexport interface GovernedHumanMutationPolicyInput {\n readonly requiredPermission: Role\n readonly session: SessionSummary\n readonly workspaceId: WorkspaceId\n}\n\n/** Evaluate the common human-session permission and workspace rules. */\nexport const governedHumanMutationPolicyAllows = (\n input: GovernedHumanMutationPolicyInput\n): boolean =>\n input.session.actor._tag === \"human\" &&\n input.session.workspaceId === input.workspaceId &&\n governedActionPermissionGrants(\n input.session.permission,\n input.requiredPermission\n )\n\nexport const WorkspaceSettingsGovernanceRequest = Schema.Struct({\n workspaceId: WorkspaceId,\n mutationId: WorkspaceSettingsMutationId,\n expectedRevision: RecordRevision,\n settings: WorkspaceSettingsV1,\n acknowledgedGovernedSections: GovernedWorkspaceSettingsSections,\n actorPersonId: PersonId,\n sessionId: SessionId\n})\n\nexport type WorkspaceSettingsGovernanceRequest = typeof WorkspaceSettingsGovernanceRequest.Type\n\nconst WorkspaceSettingsGovernanceRequestJson = Schema.fromJsonString(\n WorkspaceSettingsGovernanceRequest\n)\nconst encodeRequest = Schema.encodeEffect(WorkspaceSettingsGovernanceRequestJson)\nconst utf8Encoder = new TextEncoder()\n\n/** Digest one exact attributable settings request using the D03 digest convention. */\nexport const digestWorkspaceSettingsGovernanceRequest = Effect.fn(\n \"GovernedHumanMutationPolicyEvaluator.digestWorkspaceSettingsRequest\"\n)(function*(request: WorkspaceSettingsGovernanceRequest) {\n const encoded = yield* encodeRequest(request)\n const cryptoService = yield* Crypto.Crypto\n const digest = yield* cryptoService.digest(\"SHA-256\", utf8Encoder.encode(encoded))\n return ContentBlobDigest.make(Encoding.encodeHex(digest))\n})\n\nconst issuedAuthorities = new WeakSet<object>()\n\n/**\n * Nominal, process-local proof that the common D03 human policy authorized one\n * exact governed settings request. It cannot be constructed from HTTP or JSON.\n */\nexport class WorkspaceSettingsGovernanceAuthority {\n readonly authorizedAt: UtcTimestamp\n readonly requestDigest: ContentBlobDigest\n\n constructor(\n requestDigest: ContentBlobDigest,\n authorizedAt: UtcTimestamp\n ) {\n this.authorizedAt = authorizedAt\n this.requestDigest = requestDigest\n }\n}\n\n/** Issue a nominal authority only for an exact current human-owner request. */\nexport const authorizeWorkspaceSettingsGovernanceRequest = Effect.fn(\n \"GovernedHumanMutationPolicyEvaluator.authorizeWorkspaceSettingsRequest\"\n)(function*(\n session: SessionSummary,\n request: WorkspaceSettingsGovernanceRequest,\n authorizedAt: UtcTimestamp\n) {\n if (\n !governedHumanMutationPolicyAllows({\n requiredPermission: \"workspace-owner\",\n session,\n workspaceId: request.workspaceId\n }) ||\n session.actor._tag !== \"human\" ||\n session.actor.personId !== request.actorPersonId ||\n session.sessionId !== request.sessionId\n ) {\n return null\n }\n const authority = new WorkspaceSettingsGovernanceAuthority(\n yield* digestWorkspaceSettingsGovernanceRequest(request),\n authorizedAt\n )\n issuedAuthorities.add(authority)\n return authority\n})\n\n/** Verify that an authority was issued here for the exact persisted request. */\nexport const workspaceSettingsGovernanceAuthorityMatches = (\n authority: WorkspaceSettingsGovernanceAuthority | null,\n requestDigest: ContentBlobDigest,\n authorizedAt: UtcTimestamp\n): boolean =>\n authority !== null &&\n issuedAuthorities.has(authority) &&\n authority.requestDigest === requestDigest &&\n DateTime.Equivalence(authority.authorizedAt, authorizedAt)\n","import * as Context from \"effect/Context\"\nimport * as Crypto from \"effect/Crypto\"\nimport * as Data from \"effect/Data\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport type { Success } from \"effect/Effect\"\nimport * as Encoding from \"effect/Encoding\"\nimport * as Layer from \"effect/Layer\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\n\nimport { PersonId, SessionId, WorkspaceId, WorkspaceSettingsMutationId } from \"../../../domain/identifiers.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport {\n changedWorkspaceSettingsSections,\n DEFAULT_WORKSPACE_SETTINGS,\n GovernedWorkspaceSettingsSections,\n isGovernedWorkspaceSettingsSection,\n WorkspaceSettingsSections,\n WorkspaceSettingsV1\n} from \"../../../domain/workspaceSettings.js\"\nimport {\n digestWorkspaceSettingsGovernanceRequest,\n type WorkspaceSettingsGovernanceAuthority,\n workspaceSettingsGovernanceAuthorityMatches\n} from \"../../governance/GovernedHumanMutationPolicyEvaluator.js\"\nimport { Database } from \"../Database.js\"\nimport type { QuarantineWriteError } from \"../errors.js\"\nimport {\n PersistedRecordError,\n PersistenceOperationError,\n RecordNotFoundError,\n RevisionConflictError,\n WorkspaceSettingsGovernanceError,\n WorkspaceSettingsMutationConflictError,\n WorkspaceSettingsNoChangesError\n} from \"../errors.js\"\nimport { mapPersistenceOperation, readChanges } from \"./internal.js\"\nimport { ContentBlobDigest, RecordRevision } from \"./models.js\"\nimport { makePersistedRowQuarantine } from \"./persistedRowQuarantine.js\"\nimport { QuarantineRepository } from \"./quarantineRepository.js\"\n\nconst WorkspaceSettingsRow = Schema.Struct({\n workspaceId: WorkspaceId,\n schemaVersion: Schema.Literal(1),\n revision: RecordRevision,\n policyRevision: RecordRevision,\n settingsJson: Schema.String.check(Schema.isNonEmpty(), Schema.isMaxLength(32_768)),\n settingsDigest: ContentBlobDigest,\n createdAt: UtcTimestamp,\n updatedAt: UtcTimestamp,\n updatedByPersonId: Schema.NullOr(PersonId)\n})\n\n/** Decoded current workspace-settings persistence record. */\nexport const WorkspaceSettingsRecord = Schema.Struct({\n workspaceId: WorkspaceId,\n revision: RecordRevision,\n policyRevision: RecordRevision,\n settings: WorkspaceSettingsV1,\n settingsDigest: ContentBlobDigest,\n createdAt: UtcTimestamp,\n updatedAt: UtcTimestamp,\n updatedByPersonId: Schema.NullOr(PersonId)\n})\n\n/** Decoded current workspace-settings persistence record. */\nexport type WorkspaceSettingsRecord = typeof WorkspaceSettingsRecord.Type\n\nconst WorkspaceSettingsAuditRow = Schema.Struct({\n workspaceId: WorkspaceId,\n mutationId: WorkspaceSettingsMutationId,\n requestDigest: ContentBlobDigest,\n fromRevision: RecordRevision,\n toRevision: RecordRevision,\n actorPersonId: PersonId,\n sessionId: SessionId,\n changedSectionsJson: Schema.String.check(Schema.isNonEmpty(), Schema.isMaxLength(256)),\n governed: Schema.Literals([0, 1]),\n governanceAuthorityDigest: Schema.NullOr(ContentBlobDigest),\n beforeDigest: ContentBlobDigest,\n afterDigest: ContentBlobDigest,\n occurredAt: UtcTimestamp\n})\n\n/** Immutable attributable record of one successful settings mutation. */\nexport const WorkspaceSettingsAuditRecord = Schema.Struct({\n workspaceId: WorkspaceId,\n mutationId: WorkspaceSettingsMutationId,\n requestDigest: ContentBlobDigest,\n fromRevision: RecordRevision,\n toRevision: RecordRevision,\n actorPersonId: PersonId,\n sessionId: SessionId,\n changedSections: WorkspaceSettingsSections,\n governed: Schema.Boolean,\n governanceAuthorityDigest: Schema.NullOr(ContentBlobDigest),\n beforeDigest: ContentBlobDigest,\n afterDigest: ContentBlobDigest,\n occurredAt: UtcTimestamp\n})\n\n/** Decoded immutable workspace-settings audit. */\nexport type WorkspaceSettingsAuditRecord = typeof WorkspaceSettingsAuditRecord.Type\n\n/** Internal decoded input accepted by the workspace settings persistence boundary. */\nexport const UpdateWorkspaceSettingsInput = Schema.Struct({\n mutationId: WorkspaceSettingsMutationId,\n expectedRevision: RecordRevision,\n settings: WorkspaceSettingsV1,\n acknowledgedGovernedSections: GovernedWorkspaceSettingsSections,\n actorPersonId: PersonId,\n sessionId: SessionId,\n updatedAt: UtcTimestamp\n})\n\ntype UpdateWorkspaceSettingsInput =\n & typeof UpdateWorkspaceSettingsInput.Type\n & {\n readonly governanceAuthority: WorkspaceSettingsGovernanceAuthority | null\n }\n\nconst SettingsJson = Schema.fromJsonString(WorkspaceSettingsV1)\nconst ChangedSectionsJson = Schema.fromJsonString(WorkspaceSettingsSections)\nconst encodeSettings = Schema.encodeEffect(SettingsJson)\nconst decodeSettings = Schema.decodeUnknownResult(SettingsJson, {\n onExcessProperty: \"error\"\n})\nconst encodeChangedSections = Schema.encodeEffect(ChangedSectionsJson)\nconst decodeChangedSections = Schema.decodeUnknownResult(ChangedSectionsJson)\nconst governedSectionsEqual = Schema.toEquivalence(GovernedWorkspaceSettingsSections)\nconst encodeTimestamp = Schema.encodeSync(UtcTimestamp)\nconst utf8Encoder = new TextEncoder()\n\nclass MalformedWorkspaceSettingsRecord extends Data.TaggedError(\n \"MalformedWorkspaceSettingsRecord\"\n)<{\n readonly error: PersistedRecordError\n readonly row: unknown\n}> {}\n\nconst isMalformedWorkspaceSettingsRecord = (\n failure: unknown\n): failure is MalformedWorkspaceSettingsRecord =>\n Predicate.isTagged(\"MalformedWorkspaceSettingsRecord\")(failure) &&\n Predicate.hasProperty(failure, \"error\") &&\n Schema.is(PersistedRecordError)(failure.error) &&\n Predicate.hasProperty(failure, \"row\")\n\nconst makeWorkspaceSettingsRepository = Effect.gen(function*() {\n const cryptoService = yield* Crypto.Crypto\n const database = yield* Database\n const quarantine = yield* QuarantineRepository\n const quarantineRow = makePersistedRowQuarantine(cryptoService, quarantine)\n const sql = database.sql\n\n const digestText = Effect.fn(\"WorkspaceSettingsRepository.digestText\")(function*(value: string) {\n const digest = yield* cryptoService.digest(\"SHA-256\", utf8Encoder.encode(value)).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"workspace-settings.digest\" }))\n )\n return ContentBlobDigest.make(Encoding.encodeHex(digest))\n })\n\n const readRows = (workspaceId: WorkspaceId) =>\n sql<Record<string, unknown>>`SELECT\n workspace_id AS workspaceId,\n schema_version AS schemaVersion,\n revision,\n policy_revision AS policyRevision,\n settings_json AS settingsJson,\n settings_digest AS settingsDigest,\n created_at AS createdAt,\n updated_at AS updatedAt,\n updated_by_person_id AS updatedByPersonId\n FROM workspace_settings\n WHERE workspace_id = ${workspaceId}`\n\n const readVersionRows = (\n workspaceId: WorkspaceId,\n revision: RecordRevision\n ) =>\n sql<Record<string, unknown>>`SELECT\n workspace_id AS workspaceId,\n schema_version AS schemaVersion,\n revision,\n policy_revision AS policyRevision,\n settings_json AS settingsJson,\n settings_digest AS settingsDigest,\n created_at AS createdAt,\n updated_at AS updatedAt,\n updated_by_person_id AS updatedByPersonId\n FROM workspace_settings_versions\n WHERE workspace_id = ${workspaceId}\n AND revision = ${revision}`\n\n const readAuditRows = (\n workspaceId: WorkspaceId,\n mutationId?: WorkspaceSettingsMutationId\n ) =>\n sql<Record<string, unknown>>`SELECT\n workspace_id AS workspaceId,\n mutation_id AS mutationId,\n request_digest AS requestDigest,\n from_revision AS fromRevision,\n to_revision AS toRevision,\n actor_person_id AS actorPersonId,\n session_id AS sessionId,\n changed_sections_json AS changedSectionsJson,\n governed,\n governance_authority_digest AS governanceAuthorityDigest,\n before_digest AS beforeDigest,\n after_digest AS afterDigest,\n occurred_at AS occurredAt\n FROM workspace_settings_audits\n WHERE workspace_id = ${workspaceId}\n AND (${mutationId ?? null} IS NULL OR mutation_id = ${mutationId ?? null})\n ORDER BY to_revision`\n\n const quarantineMalformed = Effect.fn(\"WorkspaceSettingsRepository.quarantineMalformed\")(function*(\n workspaceId: WorkspaceId,\n row: unknown,\n diagnosticCode: \"workspace-settings-digest-mismatch\" | \"workspace-settings-schema-invalid\",\n diagnosticSummary:\n | \"Stored workspace settings digest does not match its content.\"\n | \"Stored workspace settings failed schema validation.\"\n ) {\n yield* quarantineRow({\n workspaceId,\n recordKind: \"workspace-settings\",\n recordKey: workspaceId,\n diagnosticCode,\n diagnosticSummary,\n observedAt: yield* DateTime.now,\n row\n })\n })\n\n const decodeCurrent = Effect.fn(\"WorkspaceSettingsRepository.decodeCurrent\")(function*(\n workspaceId: WorkspaceId,\n row: unknown,\n quarantineMode: \"deferred\" | \"immediate\"\n ) {\n const failMalformed = (\n error: PersistedRecordError,\n diagnosticCode:\n | \"workspace-settings-digest-mismatch\"\n | \"workspace-settings-schema-invalid\",\n diagnosticSummary:\n | \"Stored workspace settings digest does not match its content.\"\n | \"Stored workspace settings failed schema validation.\"\n ) =>\n quarantineMode === \"deferred\"\n ? Effect.fail(new MalformedWorkspaceSettingsRecord({ error, row }))\n : quarantineMalformed(\n workspaceId,\n row,\n diagnosticCode,\n diagnosticSummary\n ).pipe(Effect.andThen(Effect.fail(error)))\n const decodedRow = Schema.decodeUnknownResult(WorkspaceSettingsRow)(row)\n if (Result.isFailure(decodedRow)) {\n const error = new PersistedRecordError({\n workspaceId,\n recordKind: \"workspace-settings\",\n recordKey: workspaceId,\n diagnosticCode: \"workspace-settings-schema-invalid\"\n })\n return yield* failMalformed(\n error,\n \"workspace-settings-schema-invalid\",\n \"Stored workspace settings failed schema validation.\"\n )\n }\n const settings = decodeSettings(decodedRow.success.settingsJson)\n if (Result.isFailure(settings)) {\n const error = new PersistedRecordError({\n workspaceId,\n recordKind: \"workspace-settings\",\n recordKey: workspaceId,\n diagnosticCode: \"workspace-settings-schema-invalid\"\n })\n return yield* failMalformed(\n error,\n \"workspace-settings-schema-invalid\",\n \"Stored workspace settings failed schema validation.\"\n )\n }\n const actualDigest = yield* digestText(decodedRow.success.settingsJson)\n if (actualDigest !== decodedRow.success.settingsDigest) {\n const error = new PersistedRecordError({\n workspaceId,\n recordKind: \"workspace-settings\",\n recordKey: workspaceId,\n diagnosticCode: \"workspace-settings-digest-mismatch\"\n })\n return yield* failMalformed(\n error,\n \"workspace-settings-digest-mismatch\",\n \"Stored workspace settings digest does not match its content.\"\n )\n }\n return WorkspaceSettingsRecord.make({\n workspaceId,\n revision: decodedRow.success.revision,\n policyRevision: decodedRow.success.policyRevision,\n settings: settings.success,\n settingsDigest: decodedRow.success.settingsDigest,\n createdAt: decodedRow.success.createdAt,\n updatedAt: decodedRow.success.updatedAt,\n updatedByPersonId: decodedRow.success.updatedByPersonId\n })\n })\n\n const readCurrent = Effect.fn(\"WorkspaceSettingsRepository.readCurrent\")(function*(\n workspaceId: WorkspaceId,\n quarantineMode: \"deferred\" | \"immediate\" = \"immediate\"\n ) {\n const rows = yield* readRows(workspaceId)\n const row = rows[0]\n if (row === undefined) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"workspace-settings\",\n recordKey: workspaceId\n })\n }\n return yield* decodeCurrent(workspaceId, row, quarantineMode)\n })\n\n const readVersion = Effect.fn(\"WorkspaceSettingsRepository.readVersion\")(function*(\n workspaceId: WorkspaceId,\n revision: RecordRevision\n ) {\n const rows = yield* readVersionRows(workspaceId, revision)\n const row = rows[0]\n if (row === undefined) {\n return yield* new WorkspaceSettingsMutationConflictError()\n }\n return yield* decodeCurrent(workspaceId, row, \"deferred\")\n })\n\n const quarantineAfterRollback = Effect.fn(\n \"WorkspaceSettingsRepository.quarantineAfterRollback\"\n )(function*(malformed: MalformedWorkspaceSettingsRecord) {\n yield* quarantineMalformed(\n malformed.error.workspaceId,\n malformed.row,\n malformed.error.diagnosticCode ===\n \"workspace-settings-digest-mismatch\"\n ? \"workspace-settings-digest-mismatch\"\n : \"workspace-settings-schema-invalid\",\n malformed.error.diagnosticCode ===\n \"workspace-settings-digest-mismatch\"\n ? \"Stored workspace settings digest does not match its content.\"\n : \"Stored workspace settings failed schema validation.\"\n )\n return yield* malformed.error\n })\n\n const decodeAudit = Effect.fn(\"WorkspaceSettingsRepository.decodeAudit\")(function*(row: unknown) {\n const decodedRow = yield* Schema.decodeUnknownEffect(WorkspaceSettingsAuditRow)(row).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"workspace-settings.decode-audit\" }))\n )\n const changedSections = decodeChangedSections(decodedRow.changedSectionsJson)\n if (Result.isFailure(changedSections)) {\n return yield* new PersistenceOperationError({ operation: \"workspace-settings.decode-audit\" })\n }\n return WorkspaceSettingsAuditRecord.make({\n ...decodedRow,\n changedSections: changedSections.success,\n governed: decodedRow.governed === 1\n })\n })\n\n const ensureDefault = Effect.fn(\"WorkspaceSettingsRepository.ensureDefault\")(function*(\n workspaceId: WorkspaceId\n ) {\n const settingsJson = yield* encodeSettings(DEFAULT_WORKSPACE_SETTINGS).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"workspace-settings.encode-default\" }))\n )\n const settingsDigest = yield* digestText(settingsJson)\n yield* database.transaction(\n Effect.gen(function*() {\n yield* sql`INSERT INTO workspace_settings (\n workspace_id, schema_version, revision, settings_json, settings_digest,\n policy_revision, created_at, updated_at, updated_by_person_id\n )\n SELECT workspace_id, 1, 1, ${settingsJson}, ${settingsDigest},\n 1, created_at, created_at, NULL\n FROM workspaces\n WHERE workspace_id = ${workspaceId}\n ON CONFLICT(workspace_id) DO NOTHING`\n yield* sql`INSERT INTO workspace_settings_versions (\n workspace_id, schema_version, revision, settings_json, settings_digest,\n policy_revision, created_at, updated_at, updated_by_person_id\n )\n SELECT workspace_id, schema_version, revision, settings_json, settings_digest,\n policy_revision, created_at, updated_at, updated_by_person_id\n FROM workspace_settings\n WHERE workspace_id = ${workspaceId}\n AND revision = 1\n ON CONFLICT(workspace_id, revision) DO NOTHING`\n })\n )\n })\n\n const replayCommittedMutation = Effect.fn(\"WorkspaceSettingsRepository.replayCommittedMutation\")(function*(\n workspaceId: WorkspaceId,\n audit: WorkspaceSettingsAuditRecord,\n requestDigest: ContentBlobDigest\n ) {\n if (audit.requestDigest !== requestDigest) {\n return yield* new WorkspaceSettingsMutationConflictError()\n }\n const committed = yield* readVersion(workspaceId, audit.toRevision)\n if (committed.settingsDigest !== audit.afterDigest) {\n return yield* new WorkspaceSettingsMutationConflictError()\n }\n return yield* readCurrent(workspaceId, \"deferred\")\n })\n\n const get = Effect.fn(\"WorkspaceSettingsRepository.get\")(function*(workspaceId: WorkspaceId) {\n return yield* readCurrent(workspaceId).pipe(\n Effect.catchTag(\"RecordNotFoundError\", () =>\n ensureDefault(workspaceId).pipe(\n mapPersistenceOperation(\"workspace-settings.ensure-default\"),\n Effect.andThen(readCurrent(workspaceId))\n )),\n mapPersistenceOperation(\"workspace-settings.get\")\n )\n })\n\n const updateWithinTransaction = Effect.fn(\"WorkspaceSettingsRepository.updateWithinTransaction\")(function*(\n workspaceId: WorkspaceId,\n input: UpdateWorkspaceSettingsInput,\n afterUpdate: (\n before: WorkspaceSettingsRecord,\n current: WorkspaceSettingsRecord\n ) => Effect.Effect<unknown, unknown>\n ) {\n const { governanceAuthority, ...untrustedInput } = input\n const decodedInput = yield* Schema.decodeUnknownEffect(\n Schema.toType(UpdateWorkspaceSettingsInput),\n { onExcessProperty: \"error\" }\n )(untrustedInput).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"workspace-settings.update-input\" }))\n )\n const settingsJson = yield* encodeSettings(decodedInput.settings).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"workspace-settings.encode-update\" }))\n )\n const settingsDigest = yield* digestText(settingsJson)\n const requestDigest = yield* digestWorkspaceSettingsGovernanceRequest({\n workspaceId,\n mutationId: decodedInput.mutationId,\n expectedRevision: decodedInput.expectedRevision,\n settings: decodedInput.settings,\n acknowledgedGovernedSections: decodedInput.acknowledgedGovernedSections,\n actorPersonId: decodedInput.actorPersonId,\n sessionId: decodedInput.sessionId\n }).pipe(\n Effect.provideService(Crypto.Crypto, cryptoService),\n Effect.mapError(() => new PersistenceOperationError({ operation: \"workspace-settings.digest-mutation\" }))\n )\n const encodedUpdatedAt = encodeTimestamp(decodedInput.updatedAt)\n yield* ensureDefault(workspaceId).pipe(mapPersistenceOperation(\"workspace-settings.ensure-default\"))\n\n return yield* database.transaction(\n Effect.gen(function*() {\n const before = yield* readCurrent(workspaceId, \"deferred\")\n const existingAuditRows = yield* readAuditRows(workspaceId, decodedInput.mutationId)\n if (existingAuditRows.length > 1) {\n return yield* new WorkspaceSettingsMutationConflictError()\n }\n const existingAuditRow = existingAuditRows[0]\n if (existingAuditRow !== undefined) {\n const existingAudit = yield* decodeAudit(existingAuditRow)\n const replayed = yield* replayCommittedMutation(workspaceId, existingAudit, requestDigest)\n yield* afterUpdate(before, replayed)\n return replayed\n }\n\n const current = before\n if (current.revision !== decodedInput.expectedRevision) {\n return yield* new RevisionConflictError({\n workspaceId,\n recordKind: \"workspace-settings\",\n recordKey: workspaceId,\n expectedRevision: decodedInput.expectedRevision,\n actualRevision: current.revision\n })\n }\n\n const changedSections = changedWorkspaceSettingsSections(\n current.settings,\n decodedInput.settings\n )\n if (changedSections.length === 0) {\n return yield* new WorkspaceSettingsNoChangesError()\n }\n const governedSections = changedSections.filter(isGovernedWorkspaceSettingsSection)\n if (\n !governedSectionsEqual(\n governedSections,\n decodedInput.acknowledgedGovernedSections\n ) ||\n (\n governedSections.length > 0 &&\n !workspaceSettingsGovernanceAuthorityMatches(\n governanceAuthority,\n requestDigest,\n decodedInput.updatedAt\n )\n )\n ) {\n return yield* new WorkspaceSettingsGovernanceError()\n }\n const changedSectionsJson = yield* encodeChangedSections(changedSections).pipe(\n Effect.mapError(() =>\n new PersistenceOperationError({\n operation: \"workspace-settings.encode-changed-sections\"\n })\n )\n )\n\n yield* sql`UPDATE workspace_settings\n SET revision = revision + 1,\n policy_revision = policy_revision + ${governedSections.length === 0 ? 0 : 1},\n settings_json = ${settingsJson},\n settings_digest = ${settingsDigest},\n updated_by_person_id = ${decodedInput.actorPersonId},\n updated_at = ${encodedUpdatedAt}\n WHERE workspace_id = ${workspaceId}\n AND revision = ${decodedInput.expectedRevision}`\n const changes = yield* readChanges(sql)\n if (changes === 0) {\n const replayRows = yield* readAuditRows(workspaceId, decodedInput.mutationId)\n const replayRow = replayRows[0]\n if (replayRow !== undefined && replayRows.length === 1) {\n const replayAudit = yield* decodeAudit(replayRow)\n return yield* replayCommittedMutation(workspaceId, replayAudit, requestDigest)\n }\n const latest = yield* readCurrent(workspaceId, \"deferred\")\n return yield* new RevisionConflictError({\n workspaceId,\n recordKind: \"workspace-settings\",\n recordKey: workspaceId,\n expectedRevision: decodedInput.expectedRevision,\n actualRevision: latest.revision\n })\n }\n\n const toRevision = RecordRevision.make(decodedInput.expectedRevision + 1)\n yield* sql`INSERT INTO workspace_settings_versions (\n workspace_id, schema_version, revision, settings_json, settings_digest,\n policy_revision, created_at, updated_at, updated_by_person_id\n )\n SELECT workspace_id, schema_version, revision, settings_json, settings_digest,\n policy_revision, created_at, updated_at, updated_by_person_id\n FROM workspace_settings\n WHERE workspace_id = ${workspaceId}\n AND revision = ${toRevision}`\n yield* sql`INSERT INTO workspace_settings_audits (\n workspace_id, mutation_id, request_digest, from_revision, to_revision,\n actor_person_id, session_id, changed_sections_json, governed, governance_authority_digest,\n before_digest, after_digest, occurred_at\n ) VALUES (\n ${workspaceId}, ${decodedInput.mutationId}, ${requestDigest},\n ${decodedInput.expectedRevision}, ${toRevision},\n ${decodedInput.actorPersonId}, ${decodedInput.sessionId}, ${changedSectionsJson},\n ${governedSections.length === 0 ? 0 : 1},\n ${governedSections.length === 0 ? null : requestDigest},\n ${current.settingsDigest}, ${settingsDigest}, ${encodedUpdatedAt}\n )`\n const updated = yield* readCurrent(workspaceId, \"deferred\")\n yield* afterUpdate(before, updated)\n return updated\n })\n ).pipe(\n Effect.result,\n Effect.flatMap((result) =>\n Result.isFailure(result) &&\n isMalformedWorkspaceSettingsRecord(result.failure)\n ? quarantineAfterRollback(result.failure)\n : Effect.fromResult(result)\n ),\n mapPersistenceOperation(\"workspace-settings.update\")\n )\n })\n\n const update = Effect.fn(\"WorkspaceSettingsRepository.update\")(function*(\n workspaceId: WorkspaceId,\n input: UpdateWorkspaceSettingsInput\n ) {\n return yield* updateWithinTransaction(workspaceId, input, () => Effect.void)\n })\n\n /**\n * Run a settings-dependent workflow in the repository-owned transaction so\n * malformed-row quarantine is written only after the complete workflow rolls back.\n */\n const readAtomically = <Value, Failure, Requirements>(\n workspaceId: WorkspaceId,\n use: (\n current: WorkspaceSettingsRecord\n ) => Effect.Effect<Value, Failure, Requirements>\n ): Effect.Effect<\n Value,\n | Failure\n | PersistedRecordError\n | PersistenceOperationError\n | QuarantineWriteError\n | RecordNotFoundError,\n Requirements\n > =>\n database.transaction(\n Effect.gen(function*() {\n const current = yield* readCurrent(workspaceId, \"deferred\").pipe(\n Effect.catchTag(\"RecordNotFoundError\", () =>\n ensureDefault(workspaceId).pipe(\n Effect.andThen(readCurrent(workspaceId, \"deferred\"))\n ))\n )\n return yield* use(current)\n })\n ).pipe(\n Effect.result,\n Effect.flatMap((result) => {\n if (Result.isSuccess(result)) return Effect.succeed(result.success)\n return isMalformedWorkspaceSettingsRecord(result.failure)\n ? quarantineAfterRollback(result.failure)\n : Effect.fail(result.failure)\n }),\n mapPersistenceOperation(\"workspace-settings.read-atomically\")\n )\n\n /**\n * Extend the repository-owned settings transaction with a dependent durable\n * update. Keeping transaction ownership here lets malformed-row quarantine\n * run only after the complete transaction has rolled back.\n */\n const updateAtomically = Effect.fn(\"WorkspaceSettingsRepository.updateAtomically\")(function*(\n workspaceId: WorkspaceId,\n input: UpdateWorkspaceSettingsInput,\n afterUpdate: (\n before: WorkspaceSettingsRecord,\n current: WorkspaceSettingsRecord\n ) => Effect.Effect<unknown, unknown>\n ) {\n return yield* updateWithinTransaction(workspaceId, input, afterUpdate)\n })\n\n const audits = Effect.fn(\"WorkspaceSettingsRepository.audits\")(function*(\n workspaceId: WorkspaceId\n ) {\n const rows = yield* readAuditRows(workspaceId).pipe(\n mapPersistenceOperation(\"workspace-settings.audits\")\n )\n return yield* Effect.forEach(rows, decodeAudit)\n })\n\n return { audits, get, readAtomically, update, updateAtomically }\n})\n\n/** Durable workspace-settings persistence with CAS and transactional audit. */\nexport interface WorkspaceSettingsRepositoryService extends\n Success<\n typeof makeWorkspaceSettingsRepository\n >\n{}\n\n/** Effect service for the current workspace settings aggregate and immutable audits. */\nexport class WorkspaceSettingsRepository extends Context.Service<\n WorkspaceSettingsRepository,\n WorkspaceSettingsRepositoryService\n>()(\"@knpkv/control-center/WorkspaceSettingsRepository\") {\n /** Layer backed by the shared Control Center database and quarantine services. */\n static readonly layer = Layer.effect(\n WorkspaceSettingsRepository,\n makeWorkspaceSettingsRepository\n )\n}\n","/** Bounded, policy-driven retention with immutable cleanup attribution. @module */\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 Layer from \"effect/Layer\"\nimport * as Schema from \"effect/Schema\"\n\nimport { WorkspaceId } from \"../../../domain/identifiers.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport { Database } from \"../Database.js\"\nimport { PersistenceOperationError } from \"../errors.js\"\nimport { mapPersistenceOperation } from \"./internal.js\"\nimport { type RecordRevision, RecordRevision as RecordRevisionSchema } from \"./models.js\"\nimport { WorkspaceSettingsRepository } from \"./workspaceSettingsRepository.js\"\n\nconst AUDIT_REPLAY_BATCH_LIMIT = 512\nconst REPRODUCIBLE_CONTENT_BATCH_LIMIT = 64\nconst EVIDENCE_BATCH_LIMIT = 64\nconst AGENT_CONTENT_BATCH_LIMIT = 8\nconst SANDBOX_ARTIFACT_BATCH_LIMIT = 512\n\n/** Durable retention classes whose policy application is independently audited. */\nexport const RetentionClass = Schema.Literals([\n \"audit-replay\",\n \"reproducible-content\",\n \"evidence\",\n \"agent-content\",\n \"sandbox-artifact\"\n])\nexport type RetentionClass = typeof RetentionClass.Type\n\n/** Immutable summary of one committed bounded cleanup transaction. */\nexport const RetentionCleanupRun = Schema.Struct({\n workspaceId: WorkspaceId,\n runId: Schema.String.check(Schema.isUUID(7)),\n retentionClass: RetentionClass,\n policyRevision: RecordRevisionSchema,\n cutoffAt: UtcTimestamp,\n batchLimit: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 512 })),\n selectedCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n deletedCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n completedAt: UtcTimestamp\n})\nexport type RetentionCleanupRun = typeof RetentionCleanupRun.Type\ntype EncodedUtcTimestamp = typeof UtcTimestamp.Encoded\n\n/** Internal bounded retention operations for one exact-schema database. */\nexport interface RetentionRepositoryService {\n readonly listRuns: (\n workspaceId: WorkspaceId\n ) => Effect.Effect<ReadonlyArray<RetentionCleanupRun>, PersistenceOperationError>\n readonly recordSandboxReconciliation: (\n workspaceId: WorkspaceId,\n removedCount: number\n ) => Effect.Effect<ReadonlyArray<RetentionCleanupRun>, PersistenceOperationError>\n readonly sweepWorkspace: (\n workspaceId: WorkspaceId\n ) => Effect.Effect<ReadonlyArray<RetentionCleanupRun>, PersistenceOperationError>\n}\n\nconst EventCursorRow = Schema.Struct({\n eventCursor: Schema.Int.check(Schema.isGreaterThan(0))\n})\nconst CacheCandidateRow = Schema.Struct({\n rowId: Schema.Int.check(Schema.isGreaterThan(0))\n})\nconst EvidenceCandidateRow = Schema.Struct({\n evidenceId: Schema.String\n})\nconst AgentCandidateRow = Schema.Struct({\n jobId: Schema.String\n})\nconst SandboxArtifactCandidateRow = Schema.Struct({\n artifactId: Schema.String\n})\n\nconst decodeRows = <Row extends Schema.Top>(schema: Row, rows: unknown) =>\n Schema.decodeUnknownEffect(Schema.Array(schema))(rows).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"retention.decode\" }))\n )\n\nconst makeRetentionRepository: Effect.Effect<\n RetentionRepositoryService,\n never,\n Crypto.Crypto | Database | WorkspaceSettingsRepository\n> = Effect.gen(function*() {\n const cryptoService = yield* Crypto.Crypto\n const database = yield* Database\n const workspaceSettings = yield* WorkspaceSettingsRepository\n const sql = database.sql\n\n const recordRun = Effect.fn(\"RetentionRepository.recordRun\")(function*(\n workspaceId: WorkspaceId,\n retentionClass: RetentionClass,\n policyRevision: RecordRevision,\n cutoffAt: EncodedUtcTimestamp,\n batchLimit: number,\n selectedCount: number,\n deletedCount: number,\n completedAt: EncodedUtcTimestamp\n ) {\n const runId = yield* cryptoService.randomUUIDv7.pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"retention.identity\" }))\n )\n yield* sql`INSERT INTO retention_cleanup_runs (\n workspace_id, run_id, retention_class, policy_revision, cutoff_at,\n batch_limit, selected_count, deleted_count, completed_at\n ) VALUES (\n ${workspaceId}, ${runId}, ${retentionClass}, ${policyRevision}, ${cutoffAt},\n ${batchLimit}, ${selectedCount}, ${deletedCount}, ${completedAt}\n )`\n return RetentionCleanupRun.make({\n workspaceId,\n runId,\n retentionClass,\n policyRevision,\n cutoffAt: DateTime.makeUnsafe(cutoffAt),\n batchLimit,\n selectedCount,\n deletedCount,\n completedAt: DateTime.makeUnsafe(completedAt)\n })\n })\n\n const sweepAuditReplay = Effect.fn(\"RetentionRepository.sweepAuditReplay\")(function*(\n workspaceId: WorkspaceId,\n policyRevision: RecordRevision,\n cutoffAt: EncodedUtcTimestamp,\n completedAt: EncodedUtcTimestamp\n ) {\n return yield* database\n .transaction(\n Effect.gen(function*() {\n const selected = yield* sql`WITH RECURSIVE contiguous(event_cursor, selected_count) AS (\n SELECT stream.pruned_through_cursor + 1, 1\n FROM domain_event_streams stream\n JOIN domain_events event\n ON event.workspace_id = stream.workspace_id\n AND event.event_cursor = stream.pruned_through_cursor + 1\n WHERE stream.workspace_id = ${workspaceId}\n AND event.ingested_at <= ${cutoffAt}\n UNION ALL\n SELECT contiguous.event_cursor + 1, contiguous.selected_count + 1\n FROM contiguous\n JOIN domain_events event\n ON event.workspace_id = ${workspaceId}\n AND event.event_cursor = contiguous.event_cursor + 1\n WHERE contiguous.selected_count < ${AUDIT_REPLAY_BATCH_LIMIT}\n AND event.ingested_at <= ${cutoffAt}\n )\n SELECT event_cursor AS eventCursor\n FROM contiguous\n ORDER BY event_cursor`.pipe(Effect.flatMap((rows) => decodeRows(EventCursorRow, rows)))\n const run = yield* recordRun(\n workspaceId,\n \"audit-replay\",\n policyRevision,\n cutoffAt,\n AUDIT_REPLAY_BATCH_LIMIT,\n selected.length,\n selected.length,\n completedAt\n )\n if (selected.length === 0) return run\n const eventCursors = selected.map(({ eventCursor }) => eventCursor)\n const deleted = yield* sql`DELETE FROM domain_events\n WHERE workspace_id = ${workspaceId}\n AND event_cursor IN ${sql.in(eventCursors)}\n RETURNING event_cursor AS eventCursor`.pipe(Effect.flatMap((rows) => decodeRows(EventCursorRow, rows)))\n if (deleted.length !== selected.length) {\n return yield* new PersistenceOperationError({ operation: \"retention.audit-replay-count\" })\n }\n const prunedThrough = deleted.reduce((maximum, row) => Math.max(maximum, row.eventCursor), 0)\n yield* sql`UPDATE domain_event_streams\n SET pruned_through_cursor = MAX(pruned_through_cursor, ${prunedThrough})\n WHERE workspace_id = ${workspaceId}`\n return run\n })\n )\n .pipe(mapPersistenceOperation(\"retention.audit-replay\"))\n })\n\n const sweepReproducibleContent = Effect.fn(\"RetentionRepository.sweepReproducibleContent\")(function*(\n workspaceId: WorkspaceId,\n policyRevision: RecordRevision,\n cutoffAt: EncodedUtcTimestamp,\n completedAt: EncodedUtcTimestamp\n ) {\n return yield* database\n .transaction(\n Effect.gen(function*() {\n const selected = yield* sql`SELECT rowid AS rowId\n FROM diff_content_cache_entries\n WHERE workspace_id = ${workspaceId}\n AND cached_at <= ${cutoffAt}\n ORDER BY cached_at, rowid\n LIMIT ${REPRODUCIBLE_CONTENT_BATCH_LIMIT}`.pipe(Effect.flatMap((rows) => decodeRows(CacheCandidateRow, rows)))\n const run = yield* recordRun(\n workspaceId,\n \"reproducible-content\",\n policyRevision,\n cutoffAt,\n REPRODUCIBLE_CONTENT_BATCH_LIMIT,\n selected.length,\n selected.length,\n completedAt\n )\n if (selected.length === 0) return run\n const rowIds = selected.map(({ rowId }) => rowId)\n yield* sql`INSERT INTO diff_content_cache_cleanup (\n workspace_id, content_digest, requested_at\n )\n SELECT DISTINCT entries.workspace_id, entries.content_digest, ${completedAt}\n FROM diff_content_cache_entries entries\n JOIN content_blobs blobs\n ON blobs.workspace_id = entries.workspace_id\n AND blobs.digest = entries.content_digest\n WHERE entries.workspace_id = ${workspaceId}\n AND entries.rowid IN ${sql.in(rowIds)}\n AND blobs.storage_class = 'reproducible-cache'\n ON CONFLICT (workspace_id, content_digest) DO NOTHING`\n const deleted = yield* sql`DELETE FROM diff_content_cache_entries\n WHERE workspace_id = ${workspaceId}\n AND rowid IN ${sql.in(rowIds)}\n RETURNING rowid AS rowId`.pipe(Effect.flatMap((rows) => decodeRows(CacheCandidateRow, rows)))\n if (deleted.length !== selected.length) {\n return yield* new PersistenceOperationError({ operation: \"retention.reproducible-content-count\" })\n }\n return run\n })\n )\n .pipe(mapPersistenceOperation(\"retention.reproducible-content\"))\n })\n\n const sweepEvidence = Effect.fn(\"RetentionRepository.sweepEvidence\")(function*(\n workspaceId: WorkspaceId,\n policyRevision: RecordRevision,\n completedAt: EncodedUtcTimestamp\n ) {\n const cutoffAt = completedAt\n return yield* database\n .transaction(\n Effect.gen(function*() {\n const candidates = () =>\n sql`SELECT evidence.evidence_id AS evidenceId\n FROM evidence_items evidence\n WHERE evidence.workspace_id = ${workspaceId}\n AND evidence.legal_hold = 0\n AND evidence.retain_until IS NOT NULL\n AND evidence.retain_until <= ${cutoffAt}\n AND NOT EXISTS (\n SELECT 1 FROM evidence_claims claim\n WHERE claim.workspace_id = evidence.workspace_id\n AND claim.evidence_id = evidence.evidence_id\n )\n AND NOT EXISTS (\n SELECT 1 FROM readiness_assessment_evidence assessment\n WHERE assessment.workspace_id = evidence.workspace_id\n AND assessment.evidence_id = evidence.evidence_id\n )\n AND NOT EXISTS (\n SELECT 1 FROM readiness_environment_queue queue\n WHERE queue.workspace_id = evidence.workspace_id\n AND queue.source_evidence_id = evidence.evidence_id\n )\n ORDER BY evidence.retain_until, evidence.evidence_id\n LIMIT ${EVIDENCE_BATCH_LIMIT}`\n const selected = yield* candidates().pipe(Effect.flatMap((rows) => decodeRows(EvidenceCandidateRow, rows)))\n const run = yield* recordRun(\n workspaceId,\n \"evidence\",\n policyRevision,\n cutoffAt,\n EVIDENCE_BATCH_LIMIT,\n selected.length,\n selected.length,\n completedAt\n )\n if (selected.length === 0) return run\n const evidenceIds = selected.map(({ evidenceId }) => evidenceId)\n yield* Effect.forEach(\n selected,\n ({ evidenceId }) =>\n sql`INSERT INTO retention_cleanup_claims (\n workspace_id, run_id, retention_class, record_key\n ) VALUES (${workspaceId}, ${run.runId}, 'evidence', ${evidenceId})`,\n { discard: true }\n )\n const deleted = yield* sql`DELETE FROM evidence_items\n WHERE workspace_id = ${workspaceId}\n AND evidence_id IN ${sql.in(evidenceIds)}\n RETURNING evidence_id AS evidenceId`.pipe(Effect.flatMap((rows) => decodeRows(EvidenceCandidateRow, rows)))\n if (deleted.length !== selected.length) {\n return yield* new PersistenceOperationError({ operation: \"retention.evidence-count\" })\n }\n yield* sql`DELETE FROM retention_cleanup_claims\n WHERE workspace_id = ${workspaceId}\n AND run_id = ${run.runId}`\n return run\n })\n )\n .pipe(mapPersistenceOperation(\"retention.evidence\"))\n })\n\n const sweepAgentContent = Effect.fn(\"RetentionRepository.sweepAgentContent\")(function*(\n workspaceId: WorkspaceId,\n policyRevision: RecordRevision,\n cutoffAt: EncodedUtcTimestamp,\n completedAt: EncodedUtcTimestamp\n ) {\n const candidateQuery = () =>\n sql`SELECT job.job_id AS jobId\n FROM agent_jobs job\n WHERE job.workspace_id = ${workspaceId}\n AND job.state IN ('succeeded', 'failed', 'cancelled')\n AND job.terminal_at IS NOT NULL\n AND job.terminal_at <= ${cutoffAt}\n AND NOT EXISTS (\n SELECT 1 FROM agent_review_command_artifacts artifact\n WHERE artifact.workspace_id = job.workspace_id\n AND artifact.job_id = job.job_id\n )\n AND NOT EXISTS (\n SELECT 1 FROM agent_review_suggestion_publications publication\n WHERE publication.workspace_id = job.workspace_id\n AND publication.job_id = job.job_id\n )\n AND NOT EXISTS (\n SELECT 1 FROM audit_events audit\n WHERE audit.workspace_id = job.workspace_id\n AND audit.job_id = job.job_id\n )\n AND NOT EXISTS (\n SELECT 1 FROM governed_action_transitions transition_record\n WHERE transition_record.workspace_id = job.workspace_id\n AND transition_record.cause_job_id = job.job_id\n )\n AND NOT EXISTS (\n SELECT 1 FROM agent_review_suggestion_revisions revision\n WHERE revision.workspace_id = job.workspace_id\n AND revision.source_job_id = job.job_id\n )\n AND NOT EXISTS (\n SELECT 1 FROM agent_thread_events event\n WHERE event.workspace_id = job.workspace_id\n AND event.job_id = job.job_id\n )\n AND NOT EXISTS (\n SELECT 1 FROM domain_events event\n WHERE event.workspace_id = job.workspace_id\n AND event.job_id = job.job_id\n )\n ORDER BY job.terminal_at, job.job_id\n LIMIT ${AGENT_CONTENT_BATCH_LIMIT}`\n return yield* database\n .transaction(\n Effect.gen(function*() {\n const selected = yield* candidateQuery().pipe(Effect.flatMap((rows) => decodeRows(AgentCandidateRow, rows)))\n const run = yield* recordRun(\n workspaceId,\n \"agent-content\",\n policyRevision,\n cutoffAt,\n AGENT_CONTENT_BATCH_LIMIT,\n selected.length,\n selected.length,\n completedAt\n )\n if (selected.length === 0) return run\n const jobIds = selected.map(({ jobId }) => jobId)\n yield* Effect.forEach(\n jobIds,\n (jobId) =>\n sql`INSERT INTO retention_cleanup_claims (\n workspace_id, run_id, retention_class, record_key\n ) VALUES (${workspaceId}, ${run.runId}, 'agent-content', ${jobId})`,\n { discard: true }\n )\n yield* sql`DELETE FROM agent_job_leases\n WHERE workspace_id = ${workspaceId}\n AND job_id IN ${sql.in(jobIds)}`\n yield* sql`DELETE FROM agent_job_attempts\n WHERE workspace_id = ${workspaceId}\n AND job_id IN ${sql.in(jobIds)}`\n const deleted = yield* sql`DELETE FROM agent_jobs\n WHERE workspace_id = ${workspaceId}\n AND job_id IN ${sql.in(jobIds)}\n RETURNING job_id AS jobId`.pipe(Effect.flatMap((rows) => decodeRows(AgentCandidateRow, rows)))\n if (deleted.length !== selected.length) {\n return yield* new PersistenceOperationError({ operation: \"retention.agent-content-count\" })\n }\n yield* sql`DELETE FROM retention_cleanup_claims\n WHERE workspace_id = ${workspaceId}\n AND run_id = ${run.runId}`\n return run\n })\n )\n .pipe(mapPersistenceOperation(\"retention.agent-content\"))\n })\n\n const sweepSandboxArtifacts = Effect.fn(\"RetentionRepository.sweepSandboxArtifacts\")(function*(\n workspaceId: WorkspaceId,\n policyRevision: RecordRevision,\n completedAt: EncodedUtcTimestamp\n ) {\n const cutoffAt = completedAt\n return yield* database\n .transaction(\n Effect.gen(function*() {\n const selected = yield* sql`SELECT artifact_id AS artifactId\n FROM agent_review_command_artifacts\n WHERE workspace_id = ${workspaceId}\n AND expires_at <= ${cutoffAt}\n ORDER BY expires_at, artifact_id\n LIMIT ${SANDBOX_ARTIFACT_BATCH_LIMIT}`.pipe(\n Effect.flatMap((rows) => decodeRows(SandboxArtifactCandidateRow, rows))\n )\n const run = yield* recordRun(\n workspaceId,\n \"sandbox-artifact\",\n policyRevision,\n cutoffAt,\n SANDBOX_ARTIFACT_BATCH_LIMIT,\n selected.length,\n selected.length,\n completedAt\n )\n if (selected.length === 0) return run\n yield* Effect.forEach(\n selected,\n ({ artifactId }) =>\n sql`INSERT INTO retention_cleanup_claims (\n workspace_id, run_id, retention_class, record_key\n ) VALUES (\n ${workspaceId}, ${run.runId}, 'sandbox-artifact', ${artifactId}\n )`,\n { discard: true }\n )\n const artifactIds = selected.map(({ artifactId }) => artifactId)\n const deleted = yield* sql`DELETE FROM agent_review_command_artifacts\n WHERE workspace_id = ${workspaceId}\n AND artifact_id IN ${sql.in(artifactIds)}\n RETURNING artifact_id AS artifactId`.pipe(\n Effect.flatMap((rows) => decodeRows(SandboxArtifactCandidateRow, rows))\n )\n if (deleted.length !== selected.length) {\n return yield* new PersistenceOperationError({\n operation: \"retention.sandbox-artifact-count\"\n })\n }\n yield* sql`DELETE FROM retention_cleanup_claims\n WHERE workspace_id = ${workspaceId}\n AND run_id = ${run.runId}`\n return run\n })\n )\n .pipe(mapPersistenceOperation(\"retention.sandbox-artifact\"))\n })\n\n return {\n listRuns: Effect.fn(\"RetentionRepository.listRuns\")(function*(workspaceId: WorkspaceId) {\n const rows = yield* sql`SELECT\n workspace_id AS workspaceId,\n run_id AS runId,\n retention_class AS retentionClass,\n policy_revision AS policyRevision,\n cutoff_at AS cutoffAt,\n batch_limit AS batchLimit,\n selected_count AS selectedCount,\n deleted_count AS deletedCount,\n completed_at AS completedAt\n FROM retention_cleanup_runs\n WHERE workspace_id = ${workspaceId}\n ORDER BY completed_at, run_id`.pipe(mapPersistenceOperation(\"retention.list-runs\"))\n return yield* decodeRows(RetentionCleanupRun, rows)\n }),\n recordSandboxReconciliation: Effect.fn(\"RetentionRepository.recordSandboxReconciliation\")(function*(\n workspaceId: WorkspaceId,\n removedCount: number\n ) {\n if (!Number.isSafeInteger(removedCount) || removedCount < 0) {\n return yield* new PersistenceOperationError({\n operation: \"retention.sandbox-artifact-count\"\n })\n }\n const settings = yield* workspaceSettings.get(workspaceId).pipe(\n Effect.mapError(\n () =>\n new PersistenceOperationError({\n operation: \"retention.workspace-settings\"\n })\n )\n )\n const completedAt = Schema.encodeSync(UtcTimestamp)(yield* DateTime.now)\n const cutoffAt = Schema.encodeSync(UtcTimestamp)(\n DateTime.subtract(DateTime.makeUnsafe(completedAt), {\n days: settings.settings.retention.sandboxArtifactDays\n })\n )\n return yield* database\n .transaction(\n Effect.gen(function*() {\n const runs = new Array<RetentionCleanupRun>()\n let remaining = removedCount\n do {\n const chunk = Math.min(remaining, SANDBOX_ARTIFACT_BATCH_LIMIT)\n runs.push(\n yield* recordRun(\n workspaceId,\n \"sandbox-artifact\",\n settings.policyRevision,\n cutoffAt,\n SANDBOX_ARTIFACT_BATCH_LIMIT,\n chunk,\n chunk,\n completedAt\n )\n )\n remaining -= chunk\n } while (remaining > 0)\n return runs\n })\n )\n .pipe(mapPersistenceOperation(\"retention.sandbox-artifact\"))\n }),\n sweepWorkspace: Effect.fn(\"RetentionRepository.sweepWorkspace\")(function*(workspaceId: WorkspaceId) {\n const settings = yield* workspaceSettings\n .get(workspaceId)\n .pipe(Effect.mapError(() => new PersistenceOperationError({ operation: \"retention.workspace-settings\" })))\n const completedAt = Schema.encodeSync(UtcTimestamp)(yield* DateTime.now)\n const now = DateTime.makeUnsafe(completedAt)\n const auditCutoff = Schema.encodeSync(UtcTimestamp)(\n DateTime.subtract(now, { days: settings.settings.retention.auditDays })\n )\n const contentCutoff = Schema.encodeSync(UtcTimestamp)(\n DateTime.subtract(now, { days: settings.settings.retention.contentDays })\n )\n const agentCutoff = Schema.encodeSync(UtcTimestamp)(\n DateTime.subtract(now, { days: settings.settings.retention.agentActivityDays })\n )\n const runs = new Array<RetentionCleanupRun>()\n runs.push(yield* sweepAuditReplay(workspaceId, settings.policyRevision, auditCutoff, completedAt))\n runs.push(yield* sweepReproducibleContent(workspaceId, settings.policyRevision, contentCutoff, completedAt))\n runs.push(yield* sweepEvidence(workspaceId, settings.policyRevision, completedAt))\n runs.push(yield* sweepSandboxArtifacts(workspaceId, settings.policyRevision, completedAt))\n runs.push(yield* sweepAgentContent(workspaceId, settings.policyRevision, agentCutoff, completedAt))\n return runs\n })\n }\n})\n\n/** Effect service for policy-driven cleanup and immutable cleanup attribution. */\nexport class RetentionRepository extends Context.Service<RetentionRepository, RetentionRepositoryService>()(\n \"@knpkv/control-center/server/persistence/RetentionRepository\"\n) {\n static readonly layer = Layer.effect(RetentionRepository, makeRetentionRepository)\n}\n","/** Durable, bounded Review Sandbox command artifacts with redacted metadata. @module */\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 Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport * as Schema from \"effect/Schema\"\n\nimport { AgentThreadId, JobId, ReviewCommandArtifactId, WorkspaceId } from \"../../../domain/identifiers.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport { Database } from \"../Database.js\"\nimport { PersistenceOperationError, RecordNotFoundError } from \"../errors.js\"\nimport { AgentAttemptSequence } from \"./agentJobModels.js\"\nimport { mapPersistenceOperation } from \"./internal.js\"\nimport { WorkspaceSettingsRepository } from \"./workspaceSettingsRepository.js\"\n\nexport const MAXIMUM_REVIEW_COMMAND_ARTIFACT_BYTES = 16 * 1_024 * 1_024\nexport const MAXIMUM_REVIEW_COMMAND_ARTIFACT_ATTEMPT_BYTES = 64 * 1_024 * 1_024\nexport const MAXIMUM_REVIEW_COMMAND_ARTIFACTS_PER_ATTEMPT = 64\nexport const MAXIMUM_REVIEW_COMMAND_ARTIFACT_PAGE_LENGTH = 64 * 1_024\nexport const MAXIMUM_REVIEW_COMMAND_ARTIFACT_SEARCH_MATCHES = 100\nconst textDecoder = new TextDecoder(\"utf-8\", { fatal: true })\nconst textEncoder = new TextEncoder()\n\nexport const ReviewCommandSequence = Schema.Int.check(\n Schema.isBetween({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER })\n)\nexport type ReviewCommandSequence = typeof ReviewCommandSequence.Type\n\nexport const ReviewCommandArtifactStream = Schema.Literals([\"stderr\", \"stdout\"])\nexport type ReviewCommandArtifactStream = typeof ReviewCommandArtifactStream.Type\n\n/** Durable opaque handle carrying the immutable command identity needed for scoped reads. */\nexport const ReviewCommandArtifactHandle = Schema.Struct({\n artifactId: ReviewCommandArtifactId,\n attemptSequence: AgentAttemptSequence,\n commandSequence: ReviewCommandSequence,\n stream: ReviewCommandArtifactStream\n})\nexport type ReviewCommandArtifactHandle = typeof ReviewCommandArtifactHandle.Type\n\n/** Browser-safe identity and lifecycle metadata. Command text and output are intentionally absent. */\nexport const ReviewCommandArtifactMetadata = Schema.Struct({\n workspaceId: WorkspaceId,\n threadId: AgentThreadId,\n jobId: JobId,\n attemptSequence: AgentAttemptSequence,\n commandSequence: ReviewCommandSequence,\n artifactId: ReviewCommandArtifactId,\n stream: ReviewCommandArtifactStream,\n byteLength: Schema.Int.check(\n Schema.isBetween({ minimum: 1, maximum: MAXIMUM_REVIEW_COMMAND_ARTIFACT_BYTES })\n ),\n createdAt: UtcTimestamp,\n expiresAt: UtcTimestamp\n})\nexport type ReviewCommandArtifactMetadata = typeof ReviewCommandArtifactMetadata.Type\n\nconst ReviewCommandArtifactDraft = Schema.Struct({\n stream: ReviewCommandArtifactStream,\n content: Schema.String.check(\n Schema.isNonEmpty(),\n Schema.makeFilter(\n (value) => textEncoder.encode(value).byteLength <= MAXIMUM_REVIEW_COMMAND_ARTIFACT_BYTES,\n { expected: `UTF-8 content no larger than ${MAXIMUM_REVIEW_COMMAND_ARTIFACT_BYTES} bytes` }\n )\n )\n})\n\nconst ReviewCommandArtifactDrafts = Schema.Array(ReviewCommandArtifactDraft).check(\n Schema.isMinLength(1),\n Schema.isMaxLength(2),\n Schema.makeFilter(\n (artifacts) => new Set(artifacts.map(({ stream }) => stream)).size === artifacts.length,\n { expected: \"at most one artifact for each command output stream\" }\n )\n)\n\nexport const CreateReviewCommandArtifactsInput = Schema.Struct({\n workspaceId: WorkspaceId,\n threadId: AgentThreadId,\n jobId: JobId,\n attemptSequence: AgentAttemptSequence,\n commandSequence: ReviewCommandSequence,\n artifacts: ReviewCommandArtifactDrafts\n})\nexport type CreateReviewCommandArtifactsInput = typeof CreateReviewCommandArtifactsInput.Type\n\nconst ScopedArtifactInput = Schema.Struct({\n workspaceId: WorkspaceId,\n threadId: AgentThreadId,\n jobId: JobId,\n ...ReviewCommandArtifactHandle.fields\n})\n\nexport const PageReviewCommandArtifactInput = Schema.Struct({\n ...ScopedArtifactInput.fields,\n offset: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n limit: Schema.Int.check(\n Schema.isBetween({ minimum: 1, maximum: MAXIMUM_REVIEW_COMMAND_ARTIFACT_PAGE_LENGTH })\n )\n})\nexport type PageReviewCommandArtifactInput = typeof PageReviewCommandArtifactInput.Type\n\nexport const SearchReviewCommandArtifactInput = Schema.Struct({\n ...ScopedArtifactInput.fields,\n query: Schema.String.check(Schema.isNonEmpty(), Schema.isMaxLength(1_024))\n})\nexport type SearchReviewCommandArtifactInput = typeof SearchReviewCommandArtifactInput.Type\n\nexport const ListReviewCommandArtifactsInput = Schema.Struct({\n workspaceId: WorkspaceId,\n threadId: AgentThreadId,\n jobId: JobId,\n limit: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 256 }))\n})\nexport type ListReviewCommandArtifactsInput = typeof ListReviewCommandArtifactsInput.Type\n\nexport const ReviewCommandArtifactPage = Schema.Struct({\n text: Schema.String,\n nextOffset: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n complete: Schema.Boolean\n})\nexport type ReviewCommandArtifactPage = typeof ReviewCommandArtifactPage.Type\n\nconst MetadataRow = Schema.Struct({\n workspaceId: WorkspaceId,\n threadId: AgentThreadId,\n jobId: JobId,\n attemptSequence: AgentAttemptSequence,\n commandSequence: ReviewCommandSequence,\n artifactId: ReviewCommandArtifactId,\n stream: ReviewCommandArtifactStream,\n byteLength: Schema.Int,\n createdAt: UtcTimestamp,\n expiresAt: UtcTimestamp\n})\n\nconst ContentRow = Schema.Struct({\n content: Schema.instanceOf(ArrayBuffer)\n})\n\nconst isContinuationByte = (byte: number): boolean => byte >> 6 === 0b10\n\n/** @internal Shared by the repository's contract test adapter. */\nexport const pageReviewCommandArtifactBytes = (\n bytes: Uint8Array,\n offset: number,\n limit: number\n): ReviewCommandArtifactPage | null => {\n const start = Math.min(offset, bytes.byteLength)\n if (start < bytes.byteLength && isContinuationByte(bytes[start] ?? 0)) return null\n let end = Math.min(start + limit, bytes.byteLength)\n while (end > start && end < bytes.byteLength && isContinuationByte(bytes[end] ?? 0)) {\n end -= 1\n }\n if (end === start && start < bytes.byteLength) return null\n return {\n text: textDecoder.decode(bytes.slice(start, end)),\n nextOffset: end,\n complete: end === bytes.byteLength\n }\n}\n\n/** @internal Shared by the repository's contract test adapter. */\nexport const searchReviewCommandArtifactBytes = (\n haystack: Uint8Array,\n query: string\n): ReadonlyArray<number> => {\n const needle = textEncoder.encode(query)\n const prefix = new Uint32Array(needle.byteLength)\n for (let index = 1, matched = 0; index < needle.byteLength; index += 1) {\n while (matched > 0 && needle[index] !== needle[matched]) {\n matched = prefix[matched - 1] ?? 0\n }\n if (needle[index] === needle[matched]) matched += 1\n prefix[index] = matched\n }\n const matches = new Array<number>()\n for (let index = 0, matched = 0; index < haystack.byteLength; index += 1) {\n while (matched > 0 && haystack[index] !== needle[matched]) {\n matched = prefix[matched - 1] ?? 0\n }\n if (haystack[index] === needle[matched]) matched += 1\n if (matched !== needle.byteLength) continue\n matches.push(index - needle.byteLength + 1)\n if (matches.length >= MAXIMUM_REVIEW_COMMAND_ARTIFACT_SEARCH_MATCHES) break\n matched = prefix[matched - 1] ?? 0\n }\n return matches\n}\n\nconst decodeRows = <Row extends Schema.Top>(schema: Row, rows: unknown) =>\n Schema.decodeUnknownEffect(Schema.Array(schema))(rows).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"review-artifact.decode\" }))\n )\n\nexport interface ReviewCommandArtifactRepositoryService {\n readonly createCommand: (\n input: CreateReviewCommandArtifactsInput\n ) => Effect.Effect<ReadonlyArray<ReviewCommandArtifactMetadata>, PersistenceOperationError>\n readonly metadata: (\n input: typeof ScopedArtifactInput.Type\n ) => Effect.Effect<Option.Option<ReviewCommandArtifactMetadata>, PersistenceOperationError>\n readonly list: (\n input: ListReviewCommandArtifactsInput\n ) => Effect.Effect<ReadonlyArray<ReviewCommandArtifactMetadata>, PersistenceOperationError>\n readonly page: (\n input: PageReviewCommandArtifactInput\n ) => Effect.Effect<ReviewCommandArtifactPage, PersistenceOperationError | RecordNotFoundError>\n readonly search: (\n input: SearchReviewCommandArtifactInput\n ) => Effect.Effect<ReadonlyArray<number>, PersistenceOperationError | RecordNotFoundError>\n}\n\nconst makeReviewCommandArtifactRepository: Effect.Effect<\n ReviewCommandArtifactRepositoryService,\n never,\n Crypto.Crypto | Database | WorkspaceSettingsRepository\n> = Effect.gen(function*() {\n const cryptoService = yield* Crypto.Crypto\n const database = yield* Database\n const settings = yield* WorkspaceSettingsRepository\n const sql = database.sql\n\n const readContent = Effect.fnUntraced(\n function*(input: typeof ScopedArtifactInput.Type) {\n const readAt = Schema.encodeSync(UtcTimestamp)(yield* DateTime.now)\n const rows = yield* sql`SELECT content_blob AS content\n FROM agent_review_command_artifacts\n WHERE workspace_id = ${input.workspaceId}\n AND thread_id = ${input.threadId}\n AND job_id = ${input.jobId}\n AND attempt_sequence = ${input.attemptSequence}\n AND command_sequence = ${input.commandSequence}\n AND stream = ${input.stream}\n AND artifact_id = ${input.artifactId}\n AND expires_at > ${readAt}`.pipe(\n mapPersistenceOperation(\"review-artifact.read\"),\n Effect.flatMap((result) => decodeRows(ContentRow, result))\n )\n const row = rows[0]\n if (row === undefined) {\n return yield* new RecordNotFoundError({\n recordKind: \"review-command-artifact\",\n recordKey: input.artifactId,\n workspaceId: input.workspaceId\n })\n }\n return new Uint8Array(row.content)\n },\n Effect.withTracerEnabled(false)\n )\n\n return {\n createCommand: Effect.fn(\"ReviewCommandArtifactRepository.createCommand\")(function*(unknownInput) {\n const input = yield* Schema.decodeUnknownEffect(CreateReviewCommandArtifactsInput)(unknownInput).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"review-artifact.input\" }))\n )\n const workspaceSettings = yield* settings.get(input.workspaceId).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"review-artifact.settings\" }))\n )\n const artifacts = yield* Effect.forEach(\n input.artifacts,\n Effect.fnUntraced(function*(artifact) {\n const artifactId = yield* cryptoService.randomUUIDv7.pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"review-artifact.identity\" }))\n )\n const content = textEncoder.encode(artifact.content)\n return { ...artifact, artifactId, content, byteLength: content.byteLength }\n })\n )\n const createdAt = yield* DateTime.now\n const expiresAt = DateTime.add(createdAt, {\n days: workspaceSettings.settings.retention.sandboxArtifactDays\n })\n const encodedCreatedAt = Schema.encodeSync(UtcTimestamp)(createdAt)\n const encodedExpiresAt = Schema.encodeSync(UtcTimestamp)(expiresAt)\n yield* database.transaction(\n Effect.forEach(\n artifacts,\n (artifact) =>\n sql`INSERT INTO agent_review_command_artifacts (\n workspace_id, thread_id, job_id, attempt_sequence, command_sequence,\n artifact_id, stream, byte_length, content_blob, created_at, expires_at\n ) VALUES (\n ${input.workspaceId}, ${input.threadId}, ${input.jobId}, ${input.attemptSequence},\n ${input.commandSequence}, ${artifact.artifactId}, ${artifact.stream}, ${artifact.byteLength},\n ${artifact.content}, ${encodedCreatedAt}, ${encodedExpiresAt}\n )`,\n { discard: true }\n )\n ).pipe(mapPersistenceOperation(\"review-artifact.create\"))\n return artifacts.map((artifact) =>\n ReviewCommandArtifactMetadata.make({\n workspaceId: input.workspaceId,\n threadId: input.threadId,\n jobId: input.jobId,\n attemptSequence: input.attemptSequence,\n commandSequence: input.commandSequence,\n artifactId: ReviewCommandArtifactId.make(artifact.artifactId),\n stream: artifact.stream,\n byteLength: artifact.byteLength,\n createdAt,\n expiresAt\n })\n )\n }),\n metadata: Effect.fn(\"ReviewCommandArtifactRepository.metadata\")(function*(unknownInput) {\n const input = yield* Schema.decodeUnknownEffect(ScopedArtifactInput)(unknownInput).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"review-artifact.input\" }))\n )\n const rows = yield* sql`SELECT\n workspace_id AS workspaceId,\n thread_id AS threadId,\n job_id AS jobId,\n attempt_sequence AS attemptSequence,\n command_sequence AS commandSequence,\n artifact_id AS artifactId,\n stream,\n byte_length AS byteLength,\n created_at AS createdAt,\n expires_at AS expiresAt\n FROM agent_review_command_artifacts\n WHERE workspace_id = ${input.workspaceId}\n AND thread_id = ${input.threadId}\n AND job_id = ${input.jobId}\n AND attempt_sequence = ${input.attemptSequence}\n AND command_sequence = ${input.commandSequence}\n AND stream = ${input.stream}\n AND artifact_id = ${input.artifactId}`.pipe(\n mapPersistenceOperation(\"review-artifact.metadata\"),\n Effect.flatMap((result) => decodeRows(MetadataRow, result))\n )\n return Option.fromUndefinedOr(rows[0])\n }),\n list: Effect.fn(\"ReviewCommandArtifactRepository.list\")(function*(unknownInput) {\n const input = yield* Schema.decodeUnknownEffect(ListReviewCommandArtifactsInput)(unknownInput).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"review-artifact.input\" }))\n )\n const readAt = Schema.encodeSync(UtcTimestamp)(yield* DateTime.now)\n const rows = yield* sql`SELECT\n workspace_id AS workspaceId,\n thread_id AS threadId,\n job_id AS jobId,\n attempt_sequence AS attemptSequence,\n command_sequence AS commandSequence,\n artifact_id AS artifactId,\n stream,\n byte_length AS byteLength,\n created_at AS createdAt,\n expires_at AS expiresAt\n FROM agent_review_command_artifacts\n WHERE workspace_id = ${input.workspaceId}\n AND thread_id = ${input.threadId}\n AND job_id = ${input.jobId}\n AND expires_at > ${readAt}\n ORDER BY attempt_sequence DESC, command_sequence DESC, stream\n LIMIT ${input.limit}`.pipe(\n mapPersistenceOperation(\"review-artifact.list\"),\n Effect.flatMap((result) => decodeRows(MetadataRow, result))\n )\n return rows\n }),\n page: Effect.fnUntraced(\n function*(unknownInput) {\n const input = yield* Schema.decodeUnknownEffect(PageReviewCommandArtifactInput)(unknownInput).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"review-artifact.input\" }))\n )\n const content = yield* readContent(input)\n const page = pageReviewCommandArtifactBytes(content, input.offset, input.limit)\n if (page === null) {\n return yield* new PersistenceOperationError({ operation: \"review-artifact.page-boundary\" })\n }\n return page\n },\n Effect.withTracerEnabled(false)\n ),\n search: Effect.fnUntraced(\n function*(unknownInput) {\n const input = yield* Schema.decodeUnknownEffect(SearchReviewCommandArtifactInput)(unknownInput).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"review-artifact.input\" }))\n )\n const content = yield* readContent(input)\n return searchReviewCommandArtifactBytes(content, input.query)\n },\n Effect.withTracerEnabled(false)\n )\n }\n})\n\n/** SQLite-backed command-artifact operations used by the Review Sandbox. */\nexport class ReviewCommandArtifactRepository extends Context.Service<\n ReviewCommandArtifactRepository,\n ReviewCommandArtifactRepositoryService\n>()(\"@knpkv/control-center/server/persistence/ReviewCommandArtifactRepository\") {\n static readonly layer = Layer.effect(\n ReviewCommandArtifactRepository,\n makeReviewCommandArtifactRepository\n )\n}\n","import * as Context from \"effect/Context\"\nimport * as Crypto from \"effect/Crypto\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport type { Success } from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Schema from \"effect/Schema\"\n\nimport { PersonId, SessionId, WorkspaceId } from \"../../../domain/identifiers.js\"\nimport { TimelineActorKind } from \"../../../domain/timeline.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport { Database } from \"../Database.js\"\nimport { mapPersistenceOperation } from \"./internal.js\"\n\n/** Raised when Timeline export audit persistence input is invalid. */\nexport class TimelineExportAuditInputError extends Schema.TaggedErrorClass<TimelineExportAuditInputError>()(\n \"TimelineExportAuditInputError\",\n {}\n) {}\n\n/** One immutable attribution record for a successfully collected Timeline export. */\nexport const RecordTimelineExportAuditInput = Schema.Struct({\n workspaceId: WorkspaceId,\n personId: PersonId,\n sessionId: SessionId,\n format: Schema.Literals([\"csv\", \"json\"]),\n actorKind: Schema.NullOr(TimelineActorKind),\n from: Schema.NullOr(UtcTimestamp),\n to: Schema.NullOr(UtcTimestamp),\n requestedLimit: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 1_000 })),\n returnedCount: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 1_000 })),\n truncated: Schema.Boolean\n}).check(\n Schema.makeFilter(\n ({ requestedLimit, returnedCount }) => returnedCount <= requestedLimit,\n { expected: \"returned Timeline export count not to exceed its requested limit\" }\n )\n)\n\n/** Decoded Timeline export audit append command. */\nexport type RecordTimelineExportAuditInput = typeof RecordTimelineExportAuditInput.Type\n\nconst makeTimelineExportAuditRepository = Effect.gen(function*() {\n const cryptoService = yield* Crypto.Crypto\n const { sql } = yield* Database\n\n return {\n record: Effect.fn(\"TimelineExportAuditRepository.record\")(function*(input: unknown) {\n const audit = yield* Schema.decodeUnknownEffect(Schema.toType(RecordTimelineExportAuditInput))(input).pipe(\n Effect.mapError(() => new TimelineExportAuditInputError())\n )\n const exportAuditId = yield* cryptoService.randomUUIDv7\n const recordedAt = yield* DateTime.now\n yield* sql`INSERT INTO timeline_export_audits (\n workspace_id, export_audit_id, schema_version, person_id, session_id,\n format, actor_filter, from_filter, to_filter, requested_limit,\n returned_count, is_truncated, recorded_at\n ) VALUES (\n ${audit.workspaceId}, ${exportAuditId}, 1, ${audit.personId}, ${audit.sessionId},\n ${audit.format}, ${audit.actorKind},\n ${audit.from === null ? null : Schema.encodeSync(UtcTimestamp)(audit.from)},\n ${audit.to === null ? null : Schema.encodeSync(UtcTimestamp)(audit.to)},\n ${audit.requestedLimit}, ${audit.returnedCount}, ${audit.truncated ? 1 : 0},\n ${Schema.encodeSync(UtcTimestamp)(recordedAt)}\n )`\n }, mapPersistenceOperation(\"timeline-export-audit.record\"))\n }\n})\n\n/** Durable append-only Timeline export audit repository service. */\nexport interface TimelineExportAuditRepositoryService extends Success<typeof makeTimelineExportAuditRepository> {}\n\n/** Private Timeline export attribution repository. */\nexport class TimelineExportAuditRepository extends Context.Service<\n TimelineExportAuditRepository,\n TimelineExportAuditRepositoryService\n>()(\"@knpkv/control-center/server/persistence/TimelineExportAuditRepository\") {\n static readonly layer = Layer.effect(TimelineExportAuditRepository, makeTimelineExportAuditRepository)\n}\n","import { renderTimelineDetailQueries, renderTimelineQueries } from \"@knpkv/control-center-sql\"\nimport * as Context from \"effect/Context\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport type { Success } from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Schema from \"effect/Schema\"\n\nimport type { EntityId, WorkspaceId } from \"../../../domain/identifiers.js\"\nimport type {\n TimelineActorKind,\n TimelineCursor,\n TimelineService,\n TimelineSourceKind\n} from \"../../../domain/timeline.js\"\nimport type { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport { Database } from \"../Database.js\"\nimport { mapPersistenceOperation } from \"./internal.js\"\n\nconst TimelineRow = Schema.Struct({\n eventKey: Schema.String,\n occurredAt: Schema.String,\n actorKind: Schema.String,\n actorId: Schema.NullOr(Schema.String),\n actorLabel: Schema.NullOr(Schema.String),\n eventType: Schema.String,\n sourceKind: Schema.String,\n service: Schema.NullOr(Schema.String),\n releaseId: Schema.NullOr(Schema.String),\n entityId: Schema.NullOr(Schema.String),\n actionId: Schema.NullOr(Schema.String),\n relationshipId: Schema.NullOr(Schema.String),\n pluginConnectionId: Schema.NullOr(Schema.String),\n agentJobId: Schema.NullOr(Schema.String)\n})\n\n/** Trusted durable Timeline row after SQL result decoding. */\nexport interface TimelineRecord {\n readonly eventKey: string\n readonly occurredAt: UtcTimestamp\n readonly actorKind: TimelineActorKind\n readonly actorId: string | null\n readonly actorLabel: string | null\n readonly eventType: string\n readonly sourceKind: TimelineSourceKind\n readonly service: TimelineService | null\n readonly releaseId: string | null\n readonly entityId: string | null\n readonly actionId: string | null\n readonly relationshipId: string | null\n readonly pluginConnectionId: string | null\n readonly agentJobId: string | null\n}\n\n/** Workspace-safe inputs for one bounded newest-first Timeline page. */\nexport interface ReadTimelinePageInput {\n readonly actorKind: TimelineActorKind | null\n readonly before: TimelineCursor | null\n readonly entityId: EntityId | null\n readonly from: UtcTimestamp | null\n readonly limit: number\n readonly to: UtcTimestamp | null\n readonly workspaceId: WorkspaceId\n}\n\nconst compareRecords = (left: TimelineRecord, right: TimelineRecord): number => {\n const leftTime = DateTime.toEpochMillis(left.occurredAt)\n const rightTime = DateTime.toEpochMillis(right.occurredAt)\n if (leftTime !== rightTime) return rightTime - leftTime\n return left.eventKey < right.eventKey ? 1 : left.eventKey > right.eventKey ? -1 : 0\n}\n\nconst makeTimelineRepository = Effect.gen(function*() {\n const { sql } = yield* Database\n\n const execute = Effect.fn(\"TimelineRepository.execute\")(function*(\n plans: ReturnType<typeof renderTimelineQueries>\n ) {\n const sourceRows = yield* Effect.forEach(plans, (plan) =>\n sql.unsafe(plan.sql, [...plan.params]).pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(Schema.Array(TimelineRow)))\n ), { concurrency: 4 })\n return yield* Effect.forEach(sourceRows.flat(), (row) =>\n Effect.gen(function*() {\n const occurredAt = yield* Schema.decodeUnknownEffect(\n Schema.DateTimeUtcFromString\n )(row.occurredAt)\n const actorKind = yield* Schema.decodeUnknownEffect(\n Schema.Literals([\"agent\", \"human\", \"plugin\", \"system\"])\n )(row.actorKind)\n const sourceKind = yield* Schema.decodeUnknownEffect(\n Schema.Literals([\"action\", \"plugin-sync\", \"relationship\", \"system\"])\n )(row.sourceKind)\n const service = yield* Schema.decodeUnknownEffect(\n Schema.NullOr(Schema.Literals([\"codecommit\", \"codepipeline\", \"jira\", \"confluence\", \"clockify\"]))\n )(row.service)\n return { ...row, actorKind, occurredAt, service, sourceKind } satisfies TimelineRecord\n }))\n })\n\n return {\n page: Effect.fn(\"TimelineRepository.page\")(function*(input: ReadTimelinePageInput) {\n const sourceLimit = Math.min(Math.max(input.limit, 1), 100) + 1\n const plans = renderTimelineQueries({\n actorKind: input.actorKind,\n before: input.before === null\n ? null\n : { eventKey: input.before.eventKey, occurredAt: DateTime.formatIso(input.before.occurredAt) },\n entityId: input.entityId,\n from: input.from === null ? null : DateTime.formatIso(input.from),\n limit: sourceLimit,\n to: input.to === null ? null : DateTime.formatIso(input.to),\n workspaceId: input.workspaceId\n })\n const records = yield* execute(plans)\n return records.sort(compareRecords).slice(0, sourceLimit)\n }, mapPersistenceOperation(\"timeline.page\")),\n detail: Effect.fn(\"TimelineRepository.detail\")(function*(input: {\n readonly workspaceId: WorkspaceId\n readonly eventKey: string\n }) {\n const records = yield* execute(renderTimelineDetailQueries(input))\n if (records.length > 1) return yield* Effect.die(\"Timeline event key resolved more than once\")\n return records[0] ?? null\n }, mapPersistenceOperation(\"timeline.detail\"))\n }\n})\n\n/** Deep persistence interface for the merged durable activity Timeline. */\nexport interface TimelineRepositoryService extends Success<typeof makeTimelineRepository> {}\n\n/** Effect service exposing bounded Timeline reads. */\nexport class TimelineRepository extends Context.Service<TimelineRepository, TimelineRepositoryService>()(\n \"@knpkv/control-center/TimelineRepository\"\n) {\n /** Layer binding Timeline reads to the shared database. */\n static readonly layer = Layer.effect(TimelineRepository, makeTimelineRepository)\n}\n","import * as Context from \"effect/Context\"\nimport * as Crypto from \"effect/Crypto\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport type { Success } from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\"\n\nimport { WorkspaceId } from \"../../../domain/identifiers.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\nimport { Database } from \"../Database.js\"\nimport { PersistedRecordError, RecordNotFoundError } from \"../errors.js\"\nimport {\n mapAlreadyExists,\n mapPersistenceOperation,\n readChanges,\n resolveCasFailure,\n revisionLookup\n} from \"./internal.js\"\nimport { RecordRevision, WorkspaceName, WorkspaceRecord } from \"./models.js\"\nimport { makePersistedRowQuarantine } from \"./persistedRowQuarantine.js\"\nimport { QuarantineRepository } from \"./quarantineRepository.js\"\n\nconst CreateWorkspaceRequest = Schema.Struct({\n workspaceId: WorkspaceId,\n displayName: WorkspaceName,\n createdAt: UtcTimestamp\n})\n\nconst UpdateWorkspaceRequest = Schema.Struct({\n workspaceId: WorkspaceId,\n displayName: WorkspaceName,\n expectedRevision: RecordRevision,\n updatedAt: UtcTimestamp\n})\n\nconst makeWorkspaceRepository = Effect.gen(function*() {\n const cryptoService = yield* Crypto.Crypto\n const database = yield* Database\n const quarantine = yield* QuarantineRepository\n const quarantineRow = makePersistedRowQuarantine(cryptoService, quarantine)\n const sql = database.sql\n\n const findRows = ({ workspaceId }: { readonly workspaceId: WorkspaceId }) =>\n sql<Record<string, unknown>>`SELECT\n workspace_id AS workspaceId,\n display_name AS displayName,\n revision,\n created_at AS createdAt,\n updated_at AS updatedAt\n FROM workspaces\n WHERE workspace_id = ${workspaceId}`\n\n const get = Effect.fn(\"WorkspaceRepository.get\")(function*(workspaceId: WorkspaceId) {\n const rows = yield* findRows({ workspaceId }).pipe(mapPersistenceOperation(\"workspace.get\"))\n if (rows.length === 0) {\n return yield* new RecordNotFoundError({\n workspaceId,\n recordKind: \"workspace\",\n recordKey: workspaceId\n })\n }\n const decoded = Schema.decodeUnknownResult(WorkspaceRecord)(rows[0])\n if (Result.isSuccess(decoded)) return decoded.success\n const observedAt = yield* DateTime.now\n yield* quarantineRow({\n workspaceId,\n recordKind: \"workspace\",\n recordKey: workspaceId,\n diagnosticCode: \"workspace-schema-invalid\",\n diagnosticSummary: \"Stored workspace failed schema validation.\",\n observedAt,\n row: rows[0]\n })\n return yield* new PersistedRecordError({\n workspaceId,\n recordKind: \"workspace\",\n recordKey: workspaceId,\n diagnosticCode: \"workspace-schema-invalid\"\n })\n })\n\n const insert = SqlSchema.void({\n Request: CreateWorkspaceRequest,\n execute: ({ createdAt, displayName, workspaceId }) =>\n sql`INSERT INTO workspaces (\n workspace_id, display_name, revision, created_at, updated_at\n ) VALUES (${workspaceId}, ${displayName}, 1, ${createdAt}, ${createdAt})`\n })\n\n const update = SqlSchema.void({\n Request: UpdateWorkspaceRequest,\n execute: ({ displayName, expectedRevision, updatedAt, workspaceId }) =>\n sql`UPDATE workspaces\n SET display_name = ${displayName},\n revision = revision + 1,\n updated_at = ${updatedAt}\n WHERE workspace_id = ${workspaceId}\n AND revision = ${expectedRevision}`\n })\n\n return {\n create: Effect.fn(\"WorkspaceRepository.create\")(function*(\n workspaceId: WorkspaceId,\n input: { readonly displayName: WorkspaceName; readonly createdAt: UtcTimestamp }\n ) {\n yield* insert({ workspaceId, ...input }).pipe(\n mapAlreadyExists({ workspaceId, recordKind: \"workspace\", recordKey: workspaceId }),\n mapPersistenceOperation(\"workspace.create\")\n )\n return yield* get(workspaceId)\n }),\n get,\n updateDisplayName: Effect.fn(\"WorkspaceRepository.updateDisplayName\")(function*(\n workspaceId: WorkspaceId,\n input: {\n readonly displayName: WorkspaceName\n readonly expectedRevision: RecordRevision\n readonly updatedAt: UtcTimestamp\n }\n ) {\n yield* database.transaction(\n Effect.gen(function*() {\n yield* update({ workspaceId, ...input })\n const changes = yield* readChanges(sql)\n if (changes === 0) {\n return yield* resolveCasFailure({\n workspaceId,\n recordKind: \"workspace\",\n recordKey: workspaceId,\n expectedRevision: input.expectedRevision,\n findActualRevision: revisionLookup(() =>\n sql`SELECT revision FROM workspaces WHERE workspace_id = ${workspaceId}`\n )\n })\n }\n })\n ).pipe(mapPersistenceOperation(\"workspace.update\"))\n return yield* get(workspaceId)\n })\n }\n})\n\n/** Workspace-scoped persistence with optimistic-concurrency updates. */\nexport interface WorkspaceRepositoryService extends Success<typeof makeWorkspaceRepository> {}\n\n/** Effect service for workspace records. */\nexport class WorkspaceRepository extends Context.Service<WorkspaceRepository, WorkspaceRepositoryService>()(\n \"@knpkv/control-center/WorkspaceRepository\"\n) {\n /** Layer that binds SQL queries to the shared database at construction. */\n static readonly layer = Layer.effect(WorkspaceRepository, makeWorkspaceRepository)\n}\n","import type { FileSystem, Path } from \"effect\"\nimport { Context, Crypto, Effect, Layer, Predicate, Result } from \"effect\"\nimport type { Success } from \"effect/Effect\"\n\nimport type { BackupFailure, SchemaWriteBarrierError } from \"./backup/index.js\"\nimport { ContentStore, type ContentStoreService, type ReproduciblePutContentInput } from \"./ContentStore.js\"\nimport { Database, databaseLayer, type DatabaseShape } from \"./Database.js\"\nimport {\n type ContentMetadataMismatchError,\n type DatabaseInitializationError,\n type PersistedRecordError,\n type PersistenceConfigError,\n PersistenceOperationError,\n type PluginConnectionLimitError,\n type QuarantineWriteError,\n type RecordAlreadyExistsError,\n type RecordNotFoundError,\n type ReproducibleContentUnavailableError,\n type RevisionConflictError,\n type SecretReferenceScopeConflictError,\n type SourceIdentityMismatchError,\n type WorkspaceSettingsGovernanceError,\n type WorkspaceSettingsMutationConflictError,\n type WorkspaceSettingsNoChangesError\n} from \"./errors.js\"\nimport { BlobStore } from \"./object-store/BlobStore.js\"\nimport type { BlobStoreError } from \"./object-store/BlobStoreError.js\"\nimport { decodePersistenceConfig } from \"./PersistenceConfig.js\"\nimport {\n type AgentJobInputError,\n AgentJobRepository,\n type AgentJobRepositoryService,\n type AuthorizedShareInputError,\n AuthorizedShareRepository,\n type AuthorizedShareRepositoryService,\n ContentBlobMetadataRepository,\n type DeliveryGraphInputError,\n DeliveryGraphRepository,\n type DeliveryGraphRepositoryService,\n DiffContentCacheRepository,\n type DiffContentCacheRepositoryService,\n DomainEventRepository,\n type DomainEventRepositoryService,\n EntityRepository,\n type EntityRepositoryService,\n type GovernedActionInputError,\n GovernedActionRepository,\n type GovernedActionRepositoryService,\n PeopleRepository,\n type PeopleRepositoryService,\n PluginConfigurationRepository,\n type PluginConfigurationRepositoryService,\n PluginConnectionRepository,\n type PluginConnectionRepositoryService,\n PluginRuntimeRepository,\n type PluginRuntimeRepositoryService,\n type ProviderAccountInputError,\n ProviderAccountRepository,\n type ProviderAccountRepositoryService,\n QuarantineRepository,\n type ReadinessInputError,\n ReadinessRepository,\n type ReadinessRepositoryService,\n type RelationshipRepairProposalInputError,\n RelationshipRepairProposalRepository,\n type RelationshipRepairProposalRepositoryService,\n ReleaseRepository,\n type ReleaseRepositoryService,\n RetentionRepository,\n type RetentionRepositoryService,\n type TimelineExportAuditInputError,\n TimelineExportAuditRepository,\n type TimelineExportAuditRepositoryService,\n TimelineRepository,\n type TimelineRepositoryService,\n WorkspaceRepository,\n type WorkspaceRepositoryService,\n WorkspaceSettingsRepository,\n type WorkspaceSettingsRepositoryService\n} from \"./repositories/index.js\"\nimport { mapPersistenceOperation } from \"./repositories/internal.js\"\n\n/** Typed failures that may cross the public persistence operation boundary. */\nexport type PersistenceOperationFailure =\n | AgentJobInputError\n | AuthorizedShareInputError\n | BlobStoreError\n | ContentMetadataMismatchError\n | DeliveryGraphInputError\n | GovernedActionInputError\n | PersistedRecordError\n | PluginConnectionLimitError\n | ProviderAccountInputError\n | PersistenceOperationError\n | QuarantineWriteError\n | ReadinessInputError\n | RelationshipRepairProposalInputError\n | RecordAlreadyExistsError\n | RecordNotFoundError\n | ReproducibleContentUnavailableError\n | RevisionConflictError\n | SecretReferenceScopeConflictError\n | SourceIdentityMismatchError\n | TimelineExportAuditInputError\n | WorkspaceSettingsGovernanceError\n | WorkspaceSettingsMutationConflictError\n | WorkspaceSettingsNoChangesError\n\nconst PUBLIC_OPERATION_ERROR_TAGS = new Set([\n \"AgentJobInputError\",\n \"AuthorizedShareInputError\",\n \"BlobContainmentError\",\n \"BlobIntegrityError\",\n \"BlobNotFoundError\",\n \"BlobStoreInputError\",\n \"BlobStoreIoError\",\n \"BlobTooLargeError\",\n \"BlobUnexpectedEofError\",\n \"ContentMetadataMismatchError\",\n \"DeliveryGraphInputError\",\n \"GovernedActionInputError\",\n \"PersistedRecordError\",\n \"PluginConnectionLimitError\",\n \"ProviderAccountInputError\",\n \"PersistenceOperationError\",\n \"QuarantineWriteError\",\n \"ReadinessInputError\",\n \"RelationshipRepairProposalInputError\",\n \"RecordAlreadyExistsError\",\n \"RecordNotFoundError\",\n \"ReproducibleContentUnavailableError\",\n \"RevisionConflictError\",\n \"SecretReferenceScopeConflictError\",\n \"SourceIdentityMismatchError\",\n \"TimelineExportAuditInputError\",\n \"WorkspaceSettingsGovernanceError\",\n \"WorkspaceSettingsMutationConflictError\",\n \"WorkspaceSettingsNoChangesError\"\n])\n\nconst isPersistenceOperationFailure = (error: unknown): error is PersistenceOperationFailure =>\n Predicate.hasProperty(error, \"_tag\") &&\n typeof error._tag === \"string\" &&\n PUBLIC_OPERATION_ERROR_TAGS.has(error._tag)\n\nconst publicOperation = <Value, Failure, Requirements>(\n operation: string,\n effect: Effect.Effect<Value, Failure, Requirements>\n): Effect.Effect<Value, PersistenceOperationFailure, Requirements> =>\n Effect.catch(\n effect,\n (error): Effect.Effect<never, PersistenceOperationFailure> =>\n isPersistenceOperationFailure(error)\n ? Effect.fail<PersistenceOperationFailure>(error)\n : Effect.logError(\"Control Center persistence boundary rejected an internal error\", {\n operation\n }).pipe(\n Effect.andThen(\n Effect.fail<PersistenceOperationFailure>(new PersistenceOperationError({ operation }))\n )\n )\n )\n\n/** Reclaim a bounded durable batch while publication holds the same writer lock. */\nexport const sweepDiffContentCacheCleanup = Effect.fn(\"Persistence.sweepDiffContentCacheCleanup\")(\n function*(\n database: DatabaseShape,\n content: Pick<ContentStoreService, \"removeReproducible\">,\n diffContentCache: DiffContentCacheRepositoryService\n ) {\n const candidates = yield* diffContentCache.pendingCleanup()\n for (const candidate of candidates) {\n yield* database.transaction(\n Effect.gen(function*() {\n yield* database.sql`UPDATE workspaces\n SET workspace_id = workspace_id\n WHERE workspace_id = ${candidate.workspaceId}`\n if (yield* diffContentCache.isReferenced(candidate.workspaceId, candidate.digest)) {\n yield* diffContentCache.cancelCleanup(candidate.workspaceId, candidate.digest)\n return\n }\n yield* content.removeReproducible(candidate.workspaceId, candidate.digest)\n yield* diffContentCache.completeCleanup(candidate.workspaceId, candidate.digest)\n })\n ).pipe(\n mapPersistenceOperation(\"diff-content-cache.cleanup\"),\n Effect.catch(() =>\n diffContentCache.deferCleanup(candidate.workspaceId, candidate.digest).pipe(\n Effect.catch(() => Effect.logWarning(\"A diff content cache cleanup retry could not be rescheduled\")),\n Effect.andThen(\n Effect.logWarning(\"One deferred diff content cache cleanup remains pending\")\n )\n )\n )\n )\n }\n }\n)\n\n/** Keep deferred blob reclamation outside the outcome of an already committed write. @internal */\nexport const completeDeferredCleanupBestEffort = Effect.fn(\n \"Persistence.completeDeferredCleanupBestEffort\"\n)(function*<Requirements>(\n cleanup: Effect.Effect<void, unknown, Requirements>\n) {\n yield* cleanup.pipe(\n Effect.catch(() =>\n Effect.logWarning(\n \"Deferred diff content cache cleanup remains pending for a later retry\"\n )\n )\n )\n})\n\n/** Publish a mapping, persist orphan intent even on failure, then drain one retryable batch. */\nexport const putAndSweepDiffContentCache = Effect.fn(\"Persistence.putAndSweepDiffContentCache\")(\n function*(\n database: DatabaseShape,\n content: ContentStoreService,\n diffContentCache: DiffContentCacheRepositoryService,\n ...args: Parameters<DiffContentCacheRepositoryService[\"put\"]>\n ) {\n const [key, digest] = args\n const publication = yield* Effect.uninterruptible(\n database.transaction(\n Effect.gen(function*() {\n yield* database.sql`UPDATE workspaces\n SET workspace_id = workspace_id\n WHERE workspace_id = ${key.workspaceId}`\n const requestResult = yield* diffContentCache.requestCleanup(\n key.workspaceId,\n digest\n ).pipe(Effect.result)\n const putResult = yield* diffContentCache.put(...args).pipe(Effect.result)\n return { requestResult, putResult }\n })\n ).pipe(mapPersistenceOperation(\"diff-content-cache.publish\"))\n )\n const cleanupResult = yield* sweepDiffContentCacheCleanup(\n database,\n content,\n diffContentCache\n ).pipe(Effect.result)\n if (Result.isFailure(publication.requestResult)) return yield* publication.requestResult.failure\n if (Result.isFailure(publication.putResult)) return yield* publication.putResult.failure\n if (Result.isFailure(cleanupResult)) return yield* cleanupResult.failure\n return yield* Effect.void\n }\n)\n\n/** Atomically publish metadata, cleanup intent, and the diff ownership mapping. */\nexport const putContentAndSweepDiffContentCache = Effect.fn(\n \"Persistence.putContentAndSweepDiffContentCache\"\n)(function*(\n database: DatabaseShape,\n content: ContentStoreService,\n diffContentCache: DiffContentCacheRepositoryService,\n key: Parameters<DiffContentCacheRepositoryService[\"put\"]>[0],\n input: ReproduciblePutContentInput\n) {\n const staged = yield* Effect.uninterruptible(\n database.transaction(\n Effect.gen(function*() {\n yield* database.sql`UPDATE workspaces\n SET workspace_id = workspace_id\n WHERE workspace_id = ${key.workspaceId}`\n const published = yield* content.put(key.workspaceId, input)\n yield* diffContentCache.requestCleanup(\n key.workspaceId,\n published.metadata.digest\n )\n const putResult = yield* diffContentCache.put(\n key,\n published.metadata.digest\n ).pipe(Effect.result)\n return { published, putResult }\n })\n ).pipe(mapPersistenceOperation(\"diff-content-cache.stage-content\"))\n )\n const cleanupResult = yield* sweepDiffContentCacheCleanup(\n database,\n content,\n diffContentCache\n ).pipe(Effect.result)\n if (Result.isFailure(staged.putResult)) return yield* staged.putResult.failure\n if (Result.isFailure(cleanupResult)) return yield* cleanupResult.failure\n return staged.published\n})\n\n/** Failures possible while acquiring the durable persistence service. */\nexport type PersistenceLayerError =\n | BackupFailure\n | BlobStoreError\n | DatabaseInitializationError\n | SchemaWriteBarrierError\n | PersistenceConfigError\n\nconst makePersistence = Effect.gen(function*() {\n const cryptoService = yield* Crypto.Crypto\n const database = yield* Database\n const agentJobs = yield* AgentJobRepository\n const authorizedShares = yield* AuthorizedShareRepository\n const content = yield* ContentStore\n const diffContentCache = yield* DiffContentCacheRepository\n const deliveryGraph = yield* DeliveryGraphRepository\n const events = yield* DomainEventRepository\n const governedActions = yield* GovernedActionRepository\n const entities = yield* EntityRepository\n const people = yield* PeopleRepository\n const pluginConnections = yield* PluginConnectionRepository\n const pluginConfigurations = yield* PluginConfigurationRepository\n const pluginRuntime = yield* PluginRuntimeRepository\n const providerAccounts = yield* ProviderAccountRepository\n const readiness = yield* ReadinessRepository\n const relationshipRepairProposals = yield* RelationshipRepairProposalRepository\n const releases = yield* ReleaseRepository\n const retention = yield* RetentionRepository\n const timeline = yield* TimelineRepository\n const timelineExportAudits = yield* TimelineExportAuditRepository\n const workspaces = yield* WorkspaceRepository\n const workspaceSettings = yield* WorkspaceSettingsRepository\n\n yield* completeDeferredCleanupBestEffort(\n sweepDiffContentCacheCleanup(database, content, diffContentCache)\n )\n\n return {\n agentJobs: {\n appendEvent: (...args: Parameters<AgentJobRepositoryService[\"appendEvent\"]>) =>\n publicOperation(\"agent-job.append-event\", agentJobs.appendEvent(...args)),\n appendReviewSuggestionRevision: (\n ...args: Parameters<\n AgentJobRepositoryService[\"appendReviewSuggestionRevision\"]\n >\n ) =>\n publicOperation(\n \"agent-job.append-review-suggestion-revision\",\n agentJobs.appendReviewSuggestionRevision(...args)\n ),\n claimNext: (...args: Parameters<AgentJobRepositoryService[\"claimNext\"]>) =>\n publicOperation(\"agent-job.claim-next\", agentJobs.claimNext(...args)),\n completeReview: (...args: Parameters<AgentJobRepositoryService[\"completeReview\"]>) =>\n publicOperation(\"agent-job.complete-review\", agentJobs.completeReview(...args)),\n recordReviewProgress: (...args: Parameters<AgentJobRepositoryService[\"recordReviewProgress\"]>) =>\n publicOperation(\"agent-job.record-review-progress\", agentJobs.recordReviewProgress(...args)),\n enqueue: (...args: Parameters<AgentJobRepositoryService[\"enqueue\"]>) =>\n publicOperation(\"agent-job.enqueue\", agentJobs.enqueue(...args)),\n failAttempt: (...args: Parameters<AgentJobRepositoryService[\"failAttempt\"]>) =>\n publicOperation(\"agent-job.fail-attempt\", agentJobs.failAttempt(...args)),\n latestReview: (...args: Parameters<AgentJobRepositoryService[\"latestReview\"]>) =>\n publicOperation(\"agent-job.latest-review\", agentJobs.latestReview(...args)),\n latestReviewForPullRequest: (\n ...args: Parameters<AgentJobRepositoryService[\"latestReview\"]>\n ) =>\n publicOperation(\n \"agent-job.latest-review-for-pull-request\",\n agentJobs.latestReview({ ...args[0], allowDifferentHead: true })\n ),\n listRunningPrReviewAttempts: (\n ...args: Parameters<AgentJobRepositoryService[\"listRunningPrReviewAttempts\"]>\n ) =>\n publicOperation(\n \"agent-job.list-running-pr-review-attempts\",\n agentJobs.listRunningPrReviewAttempts(...args)\n ),\n attachRunningPrReviewSession: (\n ...args: Parameters<AgentJobRepositoryService[\"attachRunningPrReviewSession\"]>\n ) =>\n publicOperation(\n \"agent-job.attach-running-pr-review-session\",\n agentJobs.attachRunningPrReviewSession(...args)\n ),\n readReviewSuggestionPublication: (\n ...args: Parameters<AgentJobRepositoryService[\"readReviewSuggestionPublication\"]>\n ) =>\n publicOperation(\n \"agent-job.read-review-suggestion-publication\",\n agentJobs.readReviewSuggestionPublication(...args)\n ),\n releaseReviewSuggestionPublication: (\n ...args: Parameters<AgentJobRepositoryService[\"releaseReviewSuggestionPublication\"]>\n ) =>\n publicOperation(\n \"agent-job.release-review-suggestion-publication\",\n agentJobs.releaseReviewSuggestionPublication(...args)\n ),\n reserveReviewSuggestionPublication: (\n ...args: Parameters<AgentJobRepositoryService[\"reserveReviewSuggestionPublication\"]>\n ) =>\n publicOperation(\n \"agent-job.reserve-review-suggestion-publication\",\n agentJobs.reserveReviewSuggestionPublication(...args)\n ),\n recordReviewSuggestionPublication: (\n ...args: Parameters<AgentJobRepositoryService[\"recordReviewSuggestionPublication\"]>\n ) =>\n publicOperation(\n \"agent-job.record-review-suggestion-publication\",\n agentJobs.recordReviewSuggestionPublication(...args)\n ),\n reviewBudget: (...args: Parameters<AgentJobRepositoryService[\"reviewBudget\"]>) =>\n publicOperation(\"agent-job.review-budget\", agentJobs.reviewBudget(...args)),\n requestCancellation: (...args: Parameters<AgentJobRepositoryService[\"requestCancellation\"]>) =>\n publicOperation(\"agent-job.request-cancellation\", agentJobs.requestCancellation(...args)),\n extendReviewBudget: (...args: Parameters<AgentJobRepositoryService[\"extendReviewBudget\"]>) =>\n publicOperation(\"agent-job.extend-review-budget\", agentJobs.extendReviewBudget(...args)),\n interruptRunningReviews: (\n ...args: Parameters<AgentJobRepositoryService[\"interruptRunningReviews\"]>\n ) =>\n publicOperation(\n \"agent-job.interrupt-running-reviews\",\n agentJobs.interruptRunningReviews(...args)\n ),\n reviewThreadAfter: (...args: Parameters<AgentJobRepositoryService[\"reviewThreadAfter\"]>) =>\n publicOperation(\"agent-job.review-thread-after\", agentJobs.reviewThreadAfter(...args)),\n reviewThreadBefore: (...args: Parameters<AgentJobRepositoryService[\"reviewThreadBefore\"]>) =>\n publicOperation(\"agent-job.review-thread-before\", agentJobs.reviewThreadBefore(...args)),\n reviewThreadTail: (...args: Parameters<AgentJobRepositoryService[\"reviewThreadTail\"]>) =>\n publicOperation(\"agent-job.review-thread-tail\", agentJobs.reviewThreadTail(...args)),\n reviewResult: (...args: Parameters<AgentJobRepositoryService[\"reviewResult\"]>) =>\n publicOperation(\"agent-job.review-result\", agentJobs.reviewResult(...args)),\n reviewSuggestionRevisions: (\n ...args: Parameters<AgentJobRepositoryService[\"reviewSuggestionRevisions\"]>\n ) =>\n publicOperation(\n \"agent-job.review-suggestion-revisions\",\n agentJobs.reviewSuggestionRevisions(...args)\n ),\n threadAfter: (...args: Parameters<AgentJobRepositoryService[\"threadAfter\"]>) =>\n publicOperation(\"agent-job.thread-after\", agentJobs.threadAfter(...args))\n },\n authorizedShares: {\n create: (...args: Parameters<AuthorizedShareRepositoryService[\"create\"]>) =>\n publicOperation(\"authorized-share.create\", authorizedShares.create(...args)),\n get: (...args: Parameters<AuthorizedShareRepositoryService[\"get\"]>) =>\n publicOperation(\"authorized-share.get\", authorizedShares.get(...args)),\n revoke: (...args: Parameters<AuthorizedShareRepositoryService[\"revoke\"]>) =>\n publicOperation(\"authorized-share.revoke\", authorizedShares.revoke(...args))\n },\n transact: <Success, Failure, Requirements>(\n effect: Effect.Effect<Success, Failure, Requirements>\n ) => database.transaction(effect).pipe(mapPersistenceOperation(\"persistence.transaction\")),\n content: {\n put: (...args: Parameters<ContentStoreService[\"put\"]>) => publicOperation(\"content.put\", content.put(...args)),\n getMetadata: (...args: Parameters<ContentStoreService[\"getMetadata\"]>) =>\n publicOperation(\"content.get-metadata\", content.getMetadata(...args)),\n listMetadata: (...args: Parameters<ContentStoreService[\"listMetadata\"]>) =>\n publicOperation(\"content.list-metadata\", content.listMetadata(...args)),\n readAll: (...args: Parameters<ContentStoreService[\"readAll\"]>) =>\n publicOperation(\"content.read-all\", content.readAll(...args)),\n readRange: (...args: Parameters<ContentStoreService[\"readRange\"]>) =>\n publicOperation(\"content.read-range\", content.readRange(...args)),\n readStream: (...args: Parameters<ContentStoreService[\"readStream\"]>) =>\n publicOperation(\"content.read-stream\", content.readStream(...args)),\n verify: (...args: Parameters<ContentStoreService[\"verify\"]>) =>\n publicOperation(\"content.verify\", content.verify(...args))\n },\n diffContentCache: {\n get: (...args: Parameters<DiffContentCacheRepositoryService[\"get\"]>) =>\n publicOperation(\"diff-content-cache.get\", diffContentCache.get(...args)),\n put: (...args: Parameters<DiffContentCacheRepositoryService[\"put\"]>) =>\n publicOperation(\n \"diff-content-cache.put\",\n putAndSweepDiffContentCache(database, content, diffContentCache, ...args).pipe(Effect.asVoid)\n ),\n putContent: (\n key: Parameters<DiffContentCacheRepositoryService[\"put\"]>[0],\n input: ReproduciblePutContentInput\n ) =>\n publicOperation(\n \"diff-content-cache.put-content\",\n putContentAndSweepDiffContentCache(\n database,\n content,\n diffContentCache,\n key,\n input\n )\n )\n },\n deliveryGraph: {\n read: (...args: Parameters<DeliveryGraphRepositoryService[\"read\"]>) =>\n publicOperation(\"delivery-graph.read\", deliveryGraph.read(...args)),\n write: (...args: Parameters<DeliveryGraphRepositoryService[\"write\"]>) =>\n publicOperation(\"delivery-graph.write\", deliveryGraph.write(...args))\n },\n entities: {\n create: (...args: Parameters<EntityRepositoryService[\"create\"]>) =>\n publicOperation(\"entity.create\", entities.create(...args)),\n findBySourceIdentity: (...args: Parameters<EntityRepositoryService[\"findBySourceIdentity\"]>) =>\n publicOperation(\"entity.find-by-source-identity\", entities.findBySourceIdentity(...args)),\n get: (...args: Parameters<EntityRepositoryService[\"get\"]>) =>\n publicOperation(\"entity.get\", entities.get(...args)),\n list: (...args: Parameters<EntityRepositoryService[\"list\"]>) =>\n publicOperation(\"entity.list\", entities.list(...args)),\n updateSourceRevision: (...args: Parameters<EntityRepositoryService[\"updateSourceRevision\"]>) =>\n publicOperation(\"entity.update\", entities.updateSourceRevision(...args))\n },\n events: {\n append: (...args: Parameters<DomainEventRepositoryService[\"append\"]>) =>\n publicOperation(\"domain-event.append\", events.append(...args)),\n pageAfter: (...args: Parameters<DomainEventRepositoryService[\"pageAfter\"]>) =>\n publicOperation(\"domain-event.page-after\", events.pageAfter(...args)),\n prune: (...args: Parameters<DomainEventRepositoryService[\"prune\"]>) =>\n publicOperation(\"domain-event.prune\", events.prune(...args)),\n streamState: (...args: Parameters<DomainEventRepositoryService[\"streamState\"]>) =>\n publicOperation(\"domain-event.stream-state\", events.streamState(...args))\n },\n governedActions: {\n commit: (...args: Parameters<GovernedActionRepositoryService[\"commit\"]>) =>\n publicOperation(\"governed-action.commit\", governedActions.commit(...args)),\n read: (...args: Parameters<GovernedActionRepositoryService[\"read\"]>) =>\n publicOperation(\"governed-action.read\", governedActions.read(...args)),\n readByIdempotencyKey: (\n ...args: Parameters<GovernedActionRepositoryService[\"readByIdempotencyKey\"]>\n ) =>\n publicOperation(\n \"governed-action.read-by-idempotency-key\",\n governedActions.readByIdempotencyKey(...args)\n ),\n readLatestTerminalByTarget: (\n ...args: Parameters<GovernedActionRepositoryService[\"readLatestTerminalByTarget\"]>\n ) =>\n publicOperation(\n \"governed-action.read-latest-terminal-by-target\",\n governedActions.readLatestTerminalByTarget(...args)\n ),\n readLatestTerminalReleasePublications: (\n ...args: Parameters<GovernedActionRepositoryService[\"readLatestTerminalReleasePublications\"]>\n ) =>\n publicOperation(\n \"governed-action.read-latest-terminal-release-publications\",\n governedActions.readLatestTerminalReleasePublications(...args)\n )\n },\n people: {\n createPerson: (...args: Parameters<PeopleRepositoryService[\"createPerson\"]>) =>\n publicOperation(\"people.create-person\", people.createPerson(...args)),\n createRoleAssignment: (...args: Parameters<PeopleRepositoryService[\"createRoleAssignment\"]>) =>\n publicOperation(\"people.create-role\", people.createRoleAssignment(...args)),\n getPerson: (...args: Parameters<PeopleRepositoryService[\"getPerson\"]>) =>\n publicOperation(\"people.get-person\", people.getPerson(...args)),\n findPersonBySourceIdentity: (...args: Parameters<PeopleRepositoryService[\"findPersonBySourceIdentity\"]>) =>\n publicOperation(\"people.find-person-by-source-identity\", people.findPersonBySourceIdentity(...args)),\n getRoleAssignment: (...args: Parameters<PeopleRepositoryService[\"getRoleAssignment\"]>) =>\n publicOperation(\"people.get-role\", people.getRoleAssignment(...args)),\n listRoleAssignments: (...args: Parameters<PeopleRepositoryService[\"listRoleAssignments\"]>) =>\n publicOperation(\"people.list-roles\", people.listRoleAssignments(...args)),\n updatePerson: (...args: Parameters<PeopleRepositoryService[\"updatePerson\"]>) =>\n publicOperation(\"people.update-person\", people.updatePerson(...args)),\n updateRoleAssignment: (...args: Parameters<PeopleRepositoryService[\"updateRoleAssignment\"]>) =>\n publicOperation(\"people.update-role\", people.updateRoleAssignment(...args))\n },\n pluginConnections: {\n create: (...args: Parameters<PluginConnectionRepositoryService[\"create\"]>) =>\n publicOperation(\"plugin-connection.create\", pluginConnections.create(...args)),\n createBounded: (...args: Parameters<PluginConnectionRepositoryService[\"createBounded\"]>) =>\n publicOperation(\"plugin-connection.create-bounded\", pluginConnections.createBounded(...args)),\n bindResource: (...args: Parameters<PluginConnectionRepositoryService[\"bindResource\"]>) =>\n publicOperation(\"plugin-connection.bind-resource\", pluginConnections.bindResource(...args)),\n get: (...args: Parameters<PluginConnectionRepositoryService[\"get\"]>) =>\n publicOperation(\"plugin-connection.get\", pluginConnections.get(...args)),\n list: (...args: Parameters<PluginConnectionRepositoryService[\"list\"]>) =>\n publicOperation(\"plugin-connection.list\", pluginConnections.list(...args)),\n updateMetadata: (...args: Parameters<PluginConnectionRepositoryService[\"updateMetadata\"]>) =>\n publicOperation(\"plugin-connection.update\", pluginConnections.updateMetadata(...args))\n },\n pluginConfigurations: {\n completeSecretCleanup: (...args: Parameters<PluginConfigurationRepositoryService[\"completeSecretCleanup\"]>) =>\n publicOperation(\n \"plugin-configuration.complete-secret-cleanup\",\n pluginConfigurations.completeSecretCleanup(...args)\n ),\n get: (...args: Parameters<PluginConfigurationRepositoryService[\"get\"]>) =>\n publicOperation(\"plugin-configuration.get\", pluginConfigurations.get(...args)),\n pendingSecretCleanup: (...args: Parameters<PluginConfigurationRepositoryService[\"pendingSecretCleanup\"]>) =>\n publicOperation(\n \"plugin-configuration.pending-secret-cleanup\",\n pluginConfigurations.pendingSecretCleanup(...args)\n ),\n requestSecretCleanup: (...args: Parameters<PluginConfigurationRepositoryService[\"requestSecretCleanup\"]>) =>\n publicOperation(\n \"plugin-configuration.request-secret-cleanup\",\n pluginConfigurations.requestSecretCleanup(...args)\n ),\n update: (...args: Parameters<PluginConfigurationRepositoryService[\"update\"]>) =>\n publicOperation(\"plugin-configuration.update\", pluginConfigurations.update(...args))\n },\n pluginRuntime: {\n acceptPluginDescriptor: (...args: Parameters<PluginRuntimeRepositoryService[\"acceptPluginDescriptor\"]>) =>\n publicOperation(\"plugin-runtime.accept-plugin-descriptor\", pluginRuntime.acceptPluginDescriptor(...args)),\n beginSyncAttempt: (...args: Parameters<PluginRuntimeRepositoryService[\"beginSyncAttempt\"]>) =>\n publicOperation(\"plugin-runtime.begin-sync-attempt\", pluginRuntime.beginSyncAttempt(...args)),\n claimSync: (...args: Parameters<PluginRuntimeRepositoryService[\"claimSync\"]>) =>\n publicOperation(\"plugin-runtime.claim-sync\", pluginRuntime.claimSync(...args)),\n commitNormalizedPage: (...args: Parameters<PluginRuntimeRepositoryService[\"commitNormalizedPage\"]>) =>\n publicOperation(\"plugin-runtime.commit-normalized-page\", pluginRuntime.commitNormalizedPage(...args)),\n commitNormalizedPageReceipt: (\n ...args: Parameters<PluginRuntimeRepositoryService[\"commitNormalizedPageReceipt\"]>\n ) =>\n publicOperation(\n \"plugin-runtime.commit-normalized-page-receipt\",\n pluginRuntime.commitNormalizedPageReceipt(...args)\n ),\n completeSyncAttempt: (...args: Parameters<PluginRuntimeRepositoryService[\"completeSyncAttempt\"]>) =>\n publicOperation(\"plugin-runtime.complete-sync-attempt\", pluginRuntime.completeSyncAttempt(...args)),\n getCache: (...args: Parameters<PluginRuntimeRepositoryService[\"getCache\"]>) =>\n publicOperation(\"plugin-runtime.get-cache\", pluginRuntime.getCache(...args)),\n getCodePipelineCacheBeforeTombstones: (\n ...args: Parameters<PluginRuntimeRepositoryService[\"getCodePipelineCacheBeforeTombstones\"]>\n ) =>\n publicOperation(\n \"plugin-runtime.get-codepipeline-cache-before-tombstones\",\n pluginRuntime.getCodePipelineCacheBeforeTombstones(...args)\n ),\n getCodePipelineCache: (...args: Parameters<PluginRuntimeRepositoryService[\"getCodePipelineCache\"]>) =>\n publicOperation(\"plugin-runtime.get-codepipeline-cache\", pluginRuntime.getCodePipelineCache(...args)),\n getLastSuccessfulHealth: (...args: Parameters<PluginRuntimeRepositoryService[\"getLastSuccessfulHealth\"]>) =>\n publicOperation(\n \"plugin-runtime.get-last-successful-health\",\n pluginRuntime.getLastSuccessfulHealth(...args)\n ),\n getRuntime: (...args: Parameters<PluginRuntimeRepositoryService[\"getRuntime\"]>) =>\n publicOperation(\"plugin-runtime.get\", pluginRuntime.getRuntime(...args)),\n getSyncAttemptState: (...args: Parameters<PluginRuntimeRepositoryService[\"getSyncAttemptState\"]>) =>\n publicOperation(\"plugin-runtime.get-sync-attempt-state\", pluginRuntime.getSyncAttemptState(...args)),\n getStream: (...args: Parameters<PluginRuntimeRepositoryService[\"getStream\"]>) =>\n publicOperation(\"plugin-runtime.get-stream\", pluginRuntime.getStream(...args)),\n listEvidence: (...args: Parameters<PluginRuntimeRepositoryService[\"listEvidence\"]>) =>\n publicOperation(\"plugin-runtime.list-evidence\", pluginRuntime.listEvidence(...args)),\n listSyncAttempts: (...args: Parameters<PluginRuntimeRepositoryService[\"listSyncAttempts\"]>) =>\n publicOperation(\"plugin-runtime.list-sync-attempts\", pluginRuntime.listSyncAttempts(...args)),\n reconcileSyncAttempts: (...args: Parameters<PluginRuntimeRepositoryService[\"reconcileSyncAttempts\"]>) =>\n publicOperation(\"plugin-runtime.reconcile-sync-attempts\", pluginRuntime.reconcileSyncAttempts(...args)),\n releaseSyncClaim: (...args: Parameters<PluginRuntimeRepositoryService[\"releaseSyncClaim\"]>) =>\n publicOperation(\"plugin-runtime.release-sync-claim\", pluginRuntime.releaseSyncClaim(...args)),\n recordHealth: (...args: Parameters<PluginRuntimeRepositoryService[\"recordHealth\"]>) =>\n publicOperation(\"plugin-runtime.record-health\", pluginRuntime.recordHealth(...args))\n },\n providerAccounts: {\n create: (...args: Parameters<ProviderAccountRepositoryService[\"create\"]>) =>\n publicOperation(\"provider-account.create\", providerAccounts.create(...args)),\n followResource: (...args: Parameters<ProviderAccountRepositoryService[\"followResource\"]>) =>\n publicOperation(\"provider-account.follow-resource\", providerAccounts.followResource(...args)),\n get: (...args: Parameters<ProviderAccountRepositoryService[\"get\"]>) =>\n publicOperation(\"provider-account.get\", providerAccounts.get(...args)),\n getResource: (...args: Parameters<ProviderAccountRepositoryService[\"getResource\"]>) =>\n publicOperation(\"provider-account.get-resource\", providerAccounts.getResource(...args)),\n list: (...args: Parameters<ProviderAccountRepositoryService[\"list\"]>) =>\n publicOperation(\"provider-account.list\", providerAccounts.list(...args)),\n listResources: (...args: Parameters<ProviderAccountRepositoryService[\"listResources\"]>) =>\n publicOperation(\"provider-account.list-resources\", providerAccounts.listResources(...args)),\n updateMetadata: (...args: Parameters<ProviderAccountRepositoryService[\"updateMetadata\"]>) =>\n publicOperation(\"provider-account.update\", providerAccounts.updateMetadata(...args)),\n updateResourceMetadata: (...args: Parameters<ProviderAccountRepositoryService[\"updateResourceMetadata\"]>) =>\n publicOperation(\"provider-account.update-resource\", providerAccounts.updateResourceMetadata(...args))\n },\n readiness: {\n claimInvalidation: (...args: Parameters<ReadinessRepositoryService[\"claimInvalidation\"]>) =>\n publicOperation(\"readiness.claim-invalidation\", readiness.claimInvalidation(...args)),\n commitEnvironment: (...args: Parameters<ReadinessRepositoryService[\"commitEnvironment\"]>) =>\n publicOperation(\"readiness.commit-environment\", readiness.commitEnvironment(...args)),\n commitRelease: (...args: Parameters<ReadinessRepositoryService[\"commitRelease\"]>) =>\n publicOperation(\"readiness.commit-release\", readiness.commitRelease(...args)),\n enqueueAffected: (...args: Parameters<ReadinessRepositoryService[\"enqueueAffected\"]>) =>\n publicOperation(\"readiness.enqueue-affected\", readiness.enqueueAffected(...args)),\n enqueueDue: (...args: Parameters<ReadinessRepositoryService[\"enqueueDue\"]>) =>\n publicOperation(\"readiness.enqueue-due\", readiness.enqueueDue(...args)),\n enqueueInvalidation: (...args: Parameters<ReadinessRepositoryService[\"enqueueInvalidation\"]>) =>\n publicOperation(\"readiness.enqueue-invalidation\", readiness.enqueueInvalidation(...args)),\n readCurrent: (...args: Parameters<ReadinessRepositoryService[\"readCurrent\"]>) =>\n publicOperation(\"readiness.read-current\", readiness.readCurrent(...args)).pipe(\n Effect.provideService(Crypto.Crypto, cryptoService)\n ),\n readCurrentReleases: (...args: Parameters<ReadinessRepositoryService[\"readCurrentReleases\"]>) =>\n publicOperation(\"readiness.read-current-releases\", readiness.readCurrentReleases(...args)).pipe(\n Effect.provideService(Crypto.Crypto, cryptoService)\n ),\n readHistory: (...args: Parameters<ReadinessRepositoryService[\"readHistory\"]>) =>\n publicOperation(\"readiness.read-history\", readiness.readHistory(...args)),\n registerRule: (...args: Parameters<ReadinessRepositoryService[\"registerRule\"]>) =>\n publicOperation(\"readiness.register-rule\", readiness.registerRule(...args))\n },\n relationshipRepairProposals: {\n application: (...args: Parameters<RelationshipRepairProposalRepositoryService[\"application\"]>) =>\n publicOperation(\"relationship-repair-proposal.application\", relationshipRepairProposals.application(...args)),\n create: (...args: Parameters<RelationshipRepairProposalRepositoryService[\"create\"]>) =>\n publicOperation(\"relationship-repair-proposal.create\", relationshipRepairProposals.create(...args)),\n get: (...args: Parameters<RelationshipRepairProposalRepositoryService[\"get\"]>) =>\n publicOperation(\"relationship-repair-proposal.get\", relationshipRepairProposals.get(...args)),\n list: (...args: Parameters<RelationshipRepairProposalRepositoryService[\"list\"]>) =>\n publicOperation(\"relationship-repair-proposal.list\", relationshipRepairProposals.list(...args)),\n listApplications: (...args: Parameters<RelationshipRepairProposalRepositoryService[\"listApplications\"]>) =>\n publicOperation(\n \"relationship-repair-proposal.list-applications\",\n relationshipRepairProposals.listApplications(...args)\n ),\n review: (...args: Parameters<RelationshipRepairProposalRepositoryService[\"review\"]>) =>\n publicOperation(\"relationship-repair-proposal.review\", relationshipRepairProposals.review(...args)),\n recordApplication: (...args: Parameters<RelationshipRepairProposalRepositoryService[\"recordApplication\"]>) =>\n publicOperation(\n \"relationship-repair-proposal.record-application\",\n relationshipRepairProposals.recordApplication(...args)\n )\n },\n releases: {\n append: (...args: Parameters<ReleaseRepositoryService[\"append\"]>) =>\n publicOperation(\"release.append\", releases.append(...args)),\n create: (...args: Parameters<ReleaseRepositoryService[\"create\"]>) =>\n publicOperation(\"release.create\", releases.create(...args)),\n get: (...args: Parameters<ReleaseRepositoryService[\"get\"]>) =>\n publicOperation(\"release.get\", releases.get(...args)),\n list: (...args: Parameters<ReleaseRepositoryService[\"list\"]>) =>\n publicOperation(\"release.list\", releases.list(...args))\n },\n retention: {\n listRuns: (...args: Parameters<RetentionRepositoryService[\"listRuns\"]>) =>\n publicOperation(\"retention.list-runs\", retention.listRuns(...args)),\n recordSandboxReconciliation: (\n ...args: Parameters<\n RetentionRepositoryService[\"recordSandboxReconciliation\"]\n >\n ) =>\n publicOperation(\n \"retention.record-sandbox-reconciliation\",\n retention.recordSandboxReconciliation(...args)\n ),\n sweepWorkspace: (...args: Parameters<RetentionRepositoryService[\"sweepWorkspace\"]>) =>\n publicOperation(\n \"retention.sweep-workspace\",\n retention.sweepWorkspace(...args).pipe(\n Effect.tap(() =>\n completeDeferredCleanupBestEffort(\n sweepDiffContentCacheCleanup(database, content, diffContentCache)\n )\n )\n )\n )\n },\n timeline: {\n detail: (...args: Parameters<TimelineRepositoryService[\"detail\"]>) =>\n publicOperation(\"timeline.detail\", timeline.detail(...args)),\n page: (...args: Parameters<TimelineRepositoryService[\"page\"]>) =>\n publicOperation(\"timeline.page\", timeline.page(...args))\n },\n timelineExportAudits: {\n record: (...args: Parameters<TimelineExportAuditRepositoryService[\"record\"]>) =>\n publicOperation(\"timeline-export-audit.record\", timelineExportAudits.record(...args))\n },\n workspaces: {\n create: (...args: Parameters<WorkspaceRepositoryService[\"create\"]>) =>\n publicOperation(\"workspace.create\", workspaces.create(...args)),\n get: (...args: Parameters<WorkspaceRepositoryService[\"get\"]>) =>\n publicOperation(\"workspace.get\", workspaces.get(...args)),\n updateDisplayName: (...args: Parameters<WorkspaceRepositoryService[\"updateDisplayName\"]>) =>\n publicOperation(\"workspace.update\", workspaces.updateDisplayName(...args))\n },\n workspaceSettings: {\n audits: (...args: Parameters<WorkspaceSettingsRepositoryService[\"audits\"]>) =>\n publicOperation(\"workspace-settings.audits\", workspaceSettings.audits(...args)),\n get: (...args: Parameters<WorkspaceSettingsRepositoryService[\"get\"]>) =>\n publicOperation(\"workspace-settings.get\", workspaceSettings.get(...args)),\n readAtomically: workspaceSettings.readAtomically,\n update: (...args: Parameters<WorkspaceSettingsRepositoryService[\"update\"]>) =>\n publicOperation(\"workspace-settings.update\", workspaceSettings.update(...args)),\n updateAtomically: (...args: Parameters<WorkspaceSettingsRepositoryService[\"updateAtomically\"]>) =>\n publicOperation(\"workspace-settings.update-atomically\", workspaceSettings.updateAtomically(...args))\n }\n }\n})\n\n/** Public repository collection exposed to authenticated server workflows. */\nexport interface PersistenceService extends Omit<Success<typeof makePersistence>, \"agentJobs\"> {\n readonly agentJobs:\n & Omit<Success<typeof makePersistence>[\"agentJobs\"], \"attachRunningPrReviewSession\" | \"interruptRunningReviews\">\n & {\n readonly attachRunningPrReviewSession?: Success<\n typeof makePersistence\n >[\"agentJobs\"][\"attachRunningPrReviewSession\"]\n readonly interruptRunningReviews?: Success<typeof makePersistence>[\"agentJobs\"][\"interruptRunningReviews\"]\n }\n}\n\n/** Server-only durable state boundary; the database and filesystem stay private. */\nexport class Persistence extends Context.Service<Persistence, PersistenceService>()(\n \"@knpkv/control-center/Persistence\"\n) {}\n\nconst PersistenceFromServices = Layer.effect(Persistence, makePersistence)\n\n/** Build persistence repositories from a caller-owned shared database service. */\nexport const persistenceLayerFromDatabase = (\n input: unknown\n): Layer.Layer<\n Persistence,\n BlobStoreError | PersistenceConfigError,\n Crypto.Crypto | Database | FileSystem.FileSystem | Path.Path\n> =>\n Layer.unwrap(\n decodePersistenceConfig(input).pipe(\n Effect.map((config) => {\n const foundation = QuarantineRepository.layer\n const agentJobs = AgentJobRepository.layer\n const authorizedShares = AuthorizedShareRepository.layer\n const contentMetadata = ContentBlobMetadataRepository.layer.pipe(\n Layer.provide(foundation)\n )\n const entities = EntityRepository.layer.pipe(Layer.provide(foundation))\n const deliveryGraph = DeliveryGraphRepository.layer.pipe(Layer.provide(foundation))\n const events = DomainEventRepository.layer.pipe(Layer.provide(foundation))\n const governedActions = GovernedActionRepository.layer.pipe(Layer.provide(foundation))\n const people = PeopleRepository.layer.pipe(Layer.provide(foundation))\n const pluginConnections = PluginConnectionRepository.layer.pipe(Layer.provide(foundation))\n const pluginConfigurations = PluginConfigurationRepository.layer.pipe(Layer.provide(foundation))\n const pluginRuntime = PluginRuntimeRepository.layer.pipe(Layer.provide(foundation))\n const providerAccounts = ProviderAccountRepository.layer.pipe(Layer.provide(foundation))\n const readiness = ReadinessRepository.layer.pipe(Layer.provide(foundation))\n const relationshipRepairProposals = RelationshipRepairProposalRepository.layer\n const release = ReleaseRepository.layer.pipe(Layer.provide(foundation))\n const timeline = TimelineRepository.layer\n const timelineExportAudits = TimelineExportAuditRepository.layer\n const workspaces = WorkspaceRepository.layer.pipe(Layer.provide(foundation))\n const workspaceSettings = WorkspaceSettingsRepository.layer.pipe(Layer.provide(foundation))\n const retention = RetentionRepository.layer.pipe(Layer.provide(workspaceSettings))\n const blobs = BlobStore.layer({ blobRoot: config.blobRoot })\n const diffContentCache = DiffContentCacheRepository.layer\n const content = ContentStore.layer.pipe(\n Layer.provide(Layer.merge(contentMetadata, blobs))\n )\n const services = Layer.mergeAll(\n foundation,\n agentJobs,\n authorizedShares,\n contentMetadata,\n deliveryGraph,\n diffContentCache,\n entities,\n events,\n governedActions,\n people,\n pluginConnections,\n pluginConfigurations,\n pluginRuntime,\n providerAccounts,\n readiness,\n relationshipRepairProposals,\n release,\n retention,\n timeline,\n timelineExportAudits,\n content,\n workspaces,\n workspaceSettings\n )\n return PersistenceFromServices.pipe(Layer.provide(services))\n })\n )\n )\n\n/** Build one shared libSQL client and owner-only blob service from decoded input. */\nexport const persistenceLayer = (\n input: unknown\n): Layer.Layer<\n Persistence,\n PersistenceLayerError,\n Crypto.Crypto | FileSystem.FileSystem | Path.Path\n> => persistenceLayerFromDatabase(input).pipe(Layer.provide(databaseLayer(input)))\n","import * as Context from \"effect/Context\"\nimport type * as Effect from \"effect/Effect\"\nimport type * as Option from \"effect/Option\"\nimport type * as Stream from \"effect/Stream\"\n\nimport type { PluginHealth } from \"../../domain/freshness.js\"\nimport type {\n DiffContentRangeRequestV1,\n DiffContentRangeRequestV2,\n DiffContentRangeV1,\n DiffInventoryPageRequestV1,\n DiffInventoryPageRequestV2,\n DiffInventoryPageV1,\n NegotiatedPluginDescriptorV1,\n PluginActionActorIdentityV1,\n PluginActionProposalV1,\n PluginDiscoveryV1,\n PluginPipelineArtifactRangeRequestV1,\n PluginPipelineArtifactRangeV1,\n PluginPipelineLogPageRequestV1,\n PluginPipelineLogPageV1,\n PluginSyncPageV1,\n PluginSyncRequestV1,\n ProposePluginActionRequestV1,\n ReadPluginEntityRequestV1,\n ReadPluginEntityResultV1\n} from \"../../domain/plugins/index.js\"\nimport type { PluginFailure } from \"./failures.js\"\n\n/** Optional complete-diff reads negotiated independently from entity reads. */\nexport interface PluginDiffReaderV1 {\n readonly readInventoryPage: (\n request: DiffInventoryPageRequestV1\n ) => Effect.Effect<DiffInventoryPageV1, PluginFailure>\n readonly readContentRange: (\n request: DiffContentRangeRequestV1\n ) => Effect.Effect<DiffContentRangeV1, PluginFailure>\n readonly readInventoryPageV2?: (\n request: DiffInventoryPageRequestV2\n ) => Effect.Effect<DiffInventoryPageV1, PluginFailure>\n readonly readContentRangeV2?: (\n request: DiffContentRangeRequestV2\n ) => Effect.Effect<DiffContentRangeV1, PluginFailure>\n}\n\n/** Optional bounded pipeline evidence reads negotiated independently from entity reads. */\nexport interface PluginPipelineReaderV1 {\n readonly readLogPage: (\n request: PluginPipelineLogPageRequestV1\n ) => Effect.Effect<PluginPipelineLogPageV1, PluginFailure>\n readonly readArtifactRange: (\n request: PluginPipelineArtifactRangeRequestV1\n ) => Effect.Effect<PluginPipelineArtifactRangeV1, PluginFailure>\n}\n\n/** Safe plugin surface available to application reads and action proposals. */\nexport interface PluginConnectionV1 {\n readonly descriptor: NegotiatedPluginDescriptorV1\n readonly actionActorIdentity?: Effect.Effect<PluginActionActorIdentityV1, PluginFailure>\n readonly discover: Effect.Effect<PluginDiscoveryV1, PluginFailure>\n readonly health: Effect.Effect<PluginHealth, PluginFailure>\n readonly sync: (\n request: PluginSyncRequestV1\n ) => Stream.Stream<PluginSyncPageV1, PluginFailure>\n readonly readEntity: (\n request: ReadPluginEntityRequestV1\n ) => Effect.Effect<ReadPluginEntityResultV1, PluginFailure>\n readonly diff: Option.Option<PluginDiffReaderV1>\n readonly pipeline?: Option.Option<PluginPipelineReaderV1>\n readonly proposeAction: (\n request: ProposePluginActionRequestV1\n ) => Effect.Effect<PluginActionProposalV1, PluginFailure>\n}\n\n/** Effect service for one scoped, capability-negotiated plugin connection. */\nexport class PluginConnection extends Context.Service<PluginConnection, PluginConnectionV1>()(\n \"@knpkv/control-center/PluginConnection\"\n) {}\n","import * as Context from \"effect/Context\"\nimport type * as Effect from \"effect/Effect\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Scope from \"effect/Scope\"\nimport type * as Stream from \"effect/Stream\"\n\nimport type {\n AgentHistoryMessage,\n AgentPrompt,\n AgentProvider,\n AgentProviderCatalog,\n DismissReviewSuggestionRequest,\n DismissReviewSuggestionResponse,\n EditReviewSuggestionRequest,\n EditReviewSuggestionResponse,\n EnqueuePullRequestReviewRequest,\n EnqueuePullRequestReviewResponse,\n EnqueueReleaseAgentJobRequest,\n EnqueueReleaseAgentJobResponse,\n PublishedReviewComment,\n PublishReviewSuggestionRequest,\n PullRequestReviewState,\n PullRequestReviewThreadPage,\n ReleaseAgentThreadCursor,\n ReleaseAgentThreadPage,\n ReleaseAgentTurnResponse,\n ReviewSuggestionPublicationPreview,\n ReviewSuggestionRevisionPage,\n TargetReviewSuggestionRequest,\n TargetReviewSuggestionResponse\n} from \"../../api/agent.js\"\nimport type {\n ApplyRelationshipRepairProposalResponse,\n CreateRelationshipRepairProposalRequest,\n EvidenceInspection,\n RelationshipHistoryInspection,\n RelationshipRepairCandidates,\n RelationshipRepairProposalDraft,\n RelationshipRepairProposalList,\n ReleaseDeliveryGraphInspection,\n ReviewRelationshipRepairProposalRequest,\n WorkspaceEntityInspection,\n WorkspaceEntityProjectionIndex\n} from \"../../api/deliveryGraph.js\"\nimport type { CompleteDiffContentRange, CompleteDiffInventory, CompleteDiffInventoryEntry } from \"../../api/diff.js\"\nimport type { ControlCenterLiveEvent } from \"../../api/liveEvents.js\"\nimport type { OpaqueMediaId, SafeMediaContentType } from \"../../api/media.js\"\nimport type {\n AtlassianOAuthClientConfiguration,\n AtlassianOAuthGrantExchangeResponse,\n AtlassianOAuthGrantId,\n AtlassianOAuthGrantStartResponse,\n AtlassianOAuthProviderIntent,\n AtlassianProfileDiscoveryResponse,\n AwsProfileDiscoveryResponse,\n AwsResourceDiscoveryRequest,\n AwsResourceDiscoveryResponse,\n CreatePluginConnectionRequest,\n CreatePluginConnectionResponse,\n CreatePluginConnectionsResponse,\n DiscoveredAtlassianProfile,\n PatchPluginConfigurationRequest,\n PatchProviderAccountRequest,\n PluginConfiguration,\n PluginConfigurationMetadata,\n PluginConnectionAdministration,\n PluginConnectionSummary,\n PluginConnectionTestResult,\n PluginCredentialReplacement,\n PluginHealthResponse,\n PluginSynchronizationState,\n ProviderAccountSummary\n} from \"../../api/plugins.js\"\nimport type { PortfolioSnapshot } from \"../../api/portfolio.js\"\nimport type {\n AuthorizedShareResolution,\n AuthorizedShareSummary,\n CreateAuthorizedShareRequest\n} from \"../../api/shares.js\"\nimport type { UpdateWorkspaceSettingsRequest, WorkspaceSettingsReadModel } from \"../../api/workspaceSettings.js\"\nimport type { Actor } from \"../../domain/actors.js\"\nimport type {\n DeliveryEntityKind,\n DeliveryEntityService,\n DeliveryEntityStatusGroup,\n DeliveryRelationship,\n LedgerRevision\n} from \"../../domain/deliveryGraph.js\"\nimport type {\n EntityId,\n EnvironmentId,\n EventCursor,\n EvidenceId,\n JobId,\n PersonId,\n PluginConnectionId,\n ProviderAccountId,\n RelationshipId,\n RelationshipRepairProposalId,\n ReleaseId,\n SessionId,\n ShareId,\n WorkspaceId\n} from \"../../domain/identifiers.js\"\nimport type {\n PluginPipelineArtifactRangeRequestV1,\n PluginPipelineLogPageRequestV1,\n PluginPipelineLogPageV1\n} from \"../../domain/plugins/index.js\"\nimport type { PrReviewSuggestionId } from \"../../domain/prReview.js\"\nimport type {\n PrReviewSuggestionRevisionPageSize,\n PrReviewSuggestionRevisionSequence\n} from \"../../domain/prReviewRevision.js\"\nimport type { RelationshipRepairProposal } from \"../../domain/relationshipRepair.js\"\nimport type { Revision, VendorImmutableId } from \"../../domain/sourceRevision.js\"\nimport type { TimelineActorKind, TimelineCursor, TimelineEventDetail, TimelinePage } from \"../../domain/timeline.js\"\nimport { UtcTimestamp } from \"../../domain/utcTimestamp.js\"\nimport type { SessionSummary } from \"../auth/models.js\"\n\n/** An authenticated resource does not exist within the caller's workspace. */\nexport class ApplicationResourceNotFound extends Schema.TaggedErrorClass<ApplicationResourceNotFound>()(\n \"ApplicationResourceNotFound\",\n {}\n) {}\n\n/** A bounded application operation cannot currently be served. */\nexport class ApplicationServiceUnavailable extends Schema.TaggedErrorClass<ApplicationServiceUnavailable>()(\n \"ApplicationServiceUnavailable\",\n { retryAt: Schema.NullOr(UtcTimestamp) }\n) {}\n\n/** A provider-specific read budget was exhausted. */\nexport class ApplicationRateLimited extends Schema.TaggedErrorClass<ApplicationRateLimited>()(\n \"ApplicationRateLimited\",\n { retryAt: Schema.NullOr(UtcTimestamp) }\n) {}\n\n/** Durable state changed since the caller read its compare-and-swap revision. */\nexport class ApplicationConflict extends Schema.TaggedErrorClass<ApplicationConflict>()(\n \"ApplicationConflict\",\n {}\n) {}\n\n/** An application-level mutation failed validation after transport decoding. */\nexport class ApplicationInvalidRequest extends Schema.TaggedErrorClass<ApplicationInvalidRequest>()(\n \"ApplicationInvalidRequest\",\n {}\n) {}\n\n/** Authenticated read and owner-only compare-and-swap mutation boundary for workspace settings. */\nexport class WorkspaceSettingsAdministration extends Context.Service<\n WorkspaceSettingsAdministration,\n {\n readonly read: (\n workspaceId: WorkspaceId\n ) => Effect.Effect<WorkspaceSettingsReadModel, ApplicationServiceUnavailable>\n readonly update: (input: {\n readonly workspaceId: WorkspaceId\n readonly request: UpdateWorkspaceSettingsRequest\n readonly session: SessionSummary\n }) => Effect.Effect<\n WorkspaceSettingsReadModel,\n ApplicationConflict | ApplicationInvalidRequest | ApplicationServiceUnavailable\n >\n }\n>()(\"@knpkv/control-center/server/api/WorkspaceSettingsAdministration\") {}\n\nexport type PluginAdministrationError =\n | ApplicationRateLimited\n | ApplicationResourceNotFound\n | ApplicationServiceUnavailable\n\n/** Secret-free plugin administration seam. Executor processes are deliberately absent. */\nexport interface PluginAdministrationService {\n readonly list: (\n workspaceId: WorkspaceId\n ) => Effect.Effect<ReadonlyArray<PluginConnectionSummary>, ApplicationServiceUnavailable>\n readonly accounts?: (\n workspaceId: WorkspaceId\n ) => Effect.Effect<ReadonlyArray<ProviderAccountSummary>, ApplicationServiceUnavailable>\n readonly patchProviderAccount?: (input: {\n readonly workspaceId: WorkspaceId\n readonly providerAccountId: ProviderAccountId\n readonly patch: PatchProviderAccountRequest\n }) => Effect.Effect<\n ProviderAccountSummary,\n ApplicationConflict | ApplicationInvalidRequest | PluginAdministrationError\n >\n readonly discoverAwsProfiles?: () => Effect.Effect<AwsProfileDiscoveryResponse, ApplicationServiceUnavailable>\n readonly discoverAwsResources?: (\n request: AwsResourceDiscoveryRequest\n ) => Effect.Effect<\n AwsResourceDiscoveryResponse,\n ApplicationInvalidRequest | ApplicationRateLimited | ApplicationServiceUnavailable\n >\n readonly discoverAtlassianProfiles?: () => Effect.Effect<\n AtlassianProfileDiscoveryResponse,\n ApplicationServiceUnavailable\n >\n readonly startAtlassianOAuthGrant?: (input: {\n readonly workspaceId: WorkspaceId\n readonly sessionId: SessionId\n readonly providers: AtlassianOAuthProviderIntent\n readonly configuration?: AtlassianOAuthClientConfiguration\n }) => Effect.Effect<\n AtlassianOAuthGrantStartResponse,\n ApplicationConflict | ApplicationServiceUnavailable\n >\n readonly exchangeAtlassianOAuthGrant?: (input: {\n readonly workspaceId: WorkspaceId\n readonly sessionId: SessionId\n readonly grantId: AtlassianOAuthGrantId\n readonly code: string\n }) => Effect.Effect<\n AtlassianOAuthGrantExchangeResponse,\n ApplicationInvalidRequest | PluginAdministrationError\n >\n readonly completeAtlassianOAuthGrant?: (input: {\n readonly workspaceId: WorkspaceId\n readonly sessionId: SessionId\n readonly grantId: AtlassianOAuthGrantId\n readonly cloudId: string\n }) => Effect.Effect<\n DiscoveredAtlassianProfile,\n ApplicationInvalidRequest | PluginAdministrationError\n >\n readonly connectAndTest?: (input: {\n readonly workspaceId: WorkspaceId\n readonly request: CreatePluginConnectionRequest\n }) => Effect.Effect<\n CreatePluginConnectionResponse,\n ApplicationConflict | ApplicationInvalidRequest | PluginAdministrationError\n >\n readonly connectAndTestBatch?: (input: {\n readonly workspaceId: WorkspaceId\n readonly requests: ReadonlyArray<CreatePluginConnectionRequest>\n }) => Effect.Effect<CreatePluginConnectionsResponse>\n readonly setConnectionEnabled?: (input: {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n readonly isEnabled: boolean\n }) => Effect.Effect<\n PluginConnectionSummary,\n ApplicationConflict | ApplicationInvalidRequest | PluginAdministrationError\n >\n readonly health: (input: {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n }) => Effect.Effect<typeof PluginHealthResponse.Type, PluginAdministrationError>\n readonly testConnection: (input: {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n }) => Effect.Effect<PluginConnectionTestResult, PluginAdministrationError>\n readonly synchronization?: (input: {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n }) => Effect.Effect<\n PluginSynchronizationState,\n ApplicationInvalidRequest | PluginAdministrationError\n >\n readonly synchronizeConnection?: (input: {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n }) => Effect.Effect<\n PluginSynchronizationState,\n ApplicationInvalidRequest | PluginAdministrationError\n >\n readonly administration?: (input: {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n }) => Effect.Effect<\n PluginConnectionAdministration,\n ApplicationInvalidRequest | PluginAdministrationError\n >\n readonly reauthorizeConnection?: (input: {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n readonly expectedRevision: number\n readonly credentials: ReadonlyArray<PluginCredentialReplacement>\n }) => Effect.Effect<\n CreatePluginConnectionResponse,\n ApplicationConflict | ApplicationInvalidRequest | PluginAdministrationError\n >\n readonly revokeConnection?: (input: {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n readonly expectedRevision: number\n }) => Effect.Effect<\n PluginConnectionSummary,\n ApplicationConflict | ApplicationInvalidRequest | PluginAdministrationError\n >\n readonly configurationMetadata: (input: {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n }) => Effect.Effect<PluginConfigurationMetadata, PluginAdministrationError>\n readonly configuration: (input: {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n }) => Effect.Effect<typeof PluginConfiguration.Type, PluginAdministrationError>\n readonly patchConfiguration: (input: {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n readonly patch: typeof PatchPluginConfigurationRequest.Type\n }) => Effect.Effect<\n typeof PluginConfiguration.Type,\n | ApplicationConflict\n | ApplicationInvalidRequest\n | PluginAdministrationError\n >\n}\n\n/** Injectable plugin query boundary used by the HTTP handlers. */\nexport class PluginAdministration extends Context.Service<\n PluginAdministration,\n PluginAdministrationService\n>()(\"@knpkv/control-center/server/api/PluginAdministration\") {}\n\nexport type CompleteDiffReadError =\n | ApplicationConflict\n | ApplicationRateLimited\n | ApplicationResourceNotFound\n | ApplicationServiceUnavailable\n\n/** Workspace-scoped application boundary for complete immutable diff reads. */\nexport class CompleteDiffReads extends Context.Service<CompleteDiffReads, {\n readonly content: (input: {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n readonly vendorImmutableId: VendorImmutableId\n readonly revision: Revision\n readonly anchor: CompleteDiffInventoryEntry[\"anchor\"]\n readonly path: CompleteDiffInventoryEntry[\"path\"]\n readonly previousPath: CompleteDiffInventoryEntry[\"previousPath\"]\n readonly status: CompleteDiffInventoryEntry[\"status\"]\n readonly side: \"before\" | \"after\"\n readonly offset: number\n readonly length: number\n }) => Effect.Effect<CompleteDiffContentRange, CompleteDiffReadError>\n readonly inventory: (input: {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n readonly vendorImmutableId: VendorImmutableId\n readonly revision: Revision\n }) => Effect.Effect<CompleteDiffInventory, CompleteDiffReadError>\n}>()(\"@knpkv/control-center/server/api/CompleteDiffReads\") {}\n\n/** Fully authorized artifact bytes with provider storage coordinates removed. */\nexport interface CodePipelineArtifactRead {\n readonly body: Stream.Stream<Uint8Array>\n readonly contentLength: number\n readonly filename: string\n readonly offset: number\n readonly totalBytes: number\n}\n\n/** Workspace-scoped bounded CodePipeline evidence reads. */\nexport class CodePipelineReads extends Context.Service<CodePipelineReads, {\n readonly logs: (input: {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n readonly request: PluginPipelineLogPageRequestV1\n }) => Effect.Effect<PluginPipelineLogPageV1, CompleteDiffReadError>\n readonly artifact: (input: {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n readonly request: PluginPipelineArtifactRangeRequestV1\n }) => Effect.Effect<CodePipelineArtifactRead, CompleteDiffReadError>\n}>()(\"@knpkv/control-center/server/api/CodePipelineReads\") {}\n\n/** Injectable bird's-eye portfolio projection boundary. */\nexport class PortfolioSnapshots extends Context.Service<PortfolioSnapshots, {\n readonly snapshot: (\n workspaceId: WorkspaceId\n ) => Effect.Effect<PortfolioSnapshot, ApplicationServiceUnavailable>\n}>()(\"@knpkv/control-center/server/api/PortfolioSnapshots\") {}\n\n/** Injectable, default-redacted workspace Timeline read boundary. */\nexport class TimelineReads extends Context.Service<TimelineReads, {\n readonly page: (input: {\n readonly workspaceId: WorkspaceId\n readonly actorKind: TimelineActorKind | null\n readonly before: TimelineCursor | null\n readonly from: UtcTimestamp | null\n readonly limit: number\n readonly to: UtcTimestamp | null\n }) => Effect.Effect<TimelinePage, ApplicationServiceUnavailable>\n readonly detail: (input: {\n readonly workspaceId: WorkspaceId\n readonly eventKey: string\n }) => Effect.Effect<\n TimelineEventDetail,\n ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n}>()(\"@knpkv/control-center/server/api/TimelineReads\") {}\n\n/** Durable attribution boundary for successfully collected Timeline downloads. */\nexport class TimelineExportAudits extends Context.Service<TimelineExportAudits, {\n readonly record: (input: {\n readonly workspaceId: WorkspaceId\n readonly personId: PersonId\n readonly sessionId: SessionId\n readonly format: \"csv\" | \"json\"\n readonly actorKind: TimelineActorKind | null\n readonly from: UtcTimestamp | null\n readonly to: UtcTimestamp | null\n readonly requestedLimit: number\n readonly returnedCount: number\n readonly truncated: boolean\n }) => Effect.Effect<void, ApplicationServiceUnavailable>\n}>()(\"@knpkv/control-center/server/api/TimelineExportAudits\") {}\n\n/** Exact-entity authenticated share creation, resolution, and revocation boundary. */\nexport class AuthorizedShares extends Context.Service<AuthorizedShares, {\n readonly create: (input: {\n readonly workspaceId: WorkspaceId\n readonly request: CreateAuthorizedShareRequest\n readonly createdByPersonId: PersonId\n readonly sessionId: SessionId\n }) => Effect.Effect<\n AuthorizedShareSummary,\n ApplicationConflict | ApplicationInvalidRequest | ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n readonly resolve: (input: {\n readonly workspaceId: WorkspaceId\n readonly shareId: ShareId\n readonly actor: Actor\n }) => Effect.Effect<\n AuthorizedShareResolution,\n ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n readonly revoke: (input: {\n readonly workspaceId: WorkspaceId\n readonly shareId: ShareId\n readonly revokedByPersonId: PersonId\n readonly sessionId: SessionId\n }) => Effect.Effect<void, ApplicationResourceNotFound | ApplicationServiceUnavailable>\n}>()(\"@knpkv/control-center/server/api/AuthorizedShares\") {}\n\n/** Workspace-scoped read boundary for relationship, lifecycle, and evidence inspection. */\nexport class DeliveryGraphInspection extends Context.Service<DeliveryGraphInspection, {\n readonly workspaceEntity: (input: {\n readonly workspaceId: WorkspaceId\n readonly entityId: EntityId\n }) => Effect.Effect<\n WorkspaceEntityInspection,\n ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n readonly workspaceEntityProjections: (\n input: {\n readonly workspaceId: WorkspaceId\n readonly owner: PersonId | null\n readonly query: string | null\n readonly service: DeliveryEntityService | null\n readonly status: DeliveryEntityStatusGroup | null\n readonly type: DeliveryEntityKind | null\n }\n ) => Effect.Effect<\n WorkspaceEntityProjectionIndex,\n ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n readonly releaseSlice: (input: {\n readonly workspaceId: WorkspaceId\n readonly releaseId: ReleaseId\n readonly environmentId: EnvironmentId | null\n }) => Effect.Effect<\n ReleaseDeliveryGraphInspection,\n ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n readonly repairCandidates: (input: {\n readonly workspaceId: WorkspaceId\n readonly releaseId: ReleaseId\n readonly environmentId: EnvironmentId | null\n }) => Effect.Effect<\n RelationshipRepairCandidates,\n ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n readonly repairProposalDraft: (input: {\n readonly workspaceId: WorkspaceId\n readonly releaseId: ReleaseId\n readonly environmentId: EnvironmentId | null\n readonly relationshipId: RelationshipId\n readonly revision: LedgerRevision\n }) => Effect.Effect<\n RelationshipRepairProposalDraft,\n ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n readonly relationship: (input: {\n readonly workspaceId: WorkspaceId\n readonly relationshipId: RelationshipId\n readonly revision: LedgerRevision | null\n }) => Effect.Effect<\n DeliveryRelationship,\n ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n readonly relationshipHistory: (input: {\n readonly workspaceId: WorkspaceId\n readonly relationshipId: RelationshipId\n }) => Effect.Effect<\n RelationshipHistoryInspection,\n ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n readonly evidence: (input: {\n readonly workspaceId: WorkspaceId\n readonly evidenceId: EvidenceId\n }) => Effect.Effect<\n EvidenceInspection,\n ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n}>()(\"@knpkv/control-center/server/api/DeliveryGraphInspection\") {}\n\n/** Authenticated mutation boundary for durable relationship-repair proposals. */\nexport class RelationshipRepairProposals extends Context.Service<RelationshipRepairProposals, {\n readonly create: (input: {\n readonly workspaceId: WorkspaceId\n readonly releaseId: ReleaseId\n readonly relationshipId: RelationshipId\n readonly request: CreateRelationshipRepairProposalRequest\n readonly actor: Actor\n readonly sessionId: SessionId\n }) => Effect.Effect<\n RelationshipRepairProposal,\n ApplicationConflict | ApplicationInvalidRequest | ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n readonly get: (input: {\n readonly workspaceId: WorkspaceId\n readonly proposalId: RelationshipRepairProposalId\n }) => Effect.Effect<\n RelationshipRepairProposal,\n ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n readonly list: (input: {\n readonly workspaceId: WorkspaceId\n readonly releaseId: ReleaseId\n readonly environmentId: EnvironmentId | null\n readonly status: RelationshipRepairProposal[\"status\"] | null\n }) => Effect.Effect<\n RelationshipRepairProposalList,\n ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n readonly review: (input: {\n readonly workspaceId: WorkspaceId\n readonly proposalId: RelationshipRepairProposalId\n readonly request: ReviewRelationshipRepairProposalRequest\n readonly actor: Actor\n readonly sessionId: SessionId\n }) => Effect.Effect<\n RelationshipRepairProposal,\n ApplicationConflict | ApplicationInvalidRequest | ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n readonly apply: (input: {\n readonly workspaceId: WorkspaceId\n readonly proposalId: RelationshipRepairProposalId\n readonly actor: Actor\n readonly sessionId: SessionId\n }) => Effect.Effect<\n ApplyRelationshipRepairProposalResponse,\n ApplicationConflict | ApplicationInvalidRequest | ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n}>()(\"@knpkv/control-center/server/api/RelationshipRepairProposals\") {}\n\n/**\n * Release-aware conversational boundary. Implementations own context projection,\n * provider selection, prompt hardening, cancellation, and provider error redaction.\n */\nexport interface ReleaseAgentTurnAdmission {\n readonly eventCursor: ReleaseAgentTurnResponse[\"eventCursor\"]\n readonly provider: ReleaseAgentTurnResponse[\"provider\"]\n readonly release: ReleaseAgentTurnResponse[\"release\"]\n readonly releaseId: ReleaseAgentTurnResponse[\"releaseId\"]\n readonly workspaceId: WorkspaceId\n}\n\nexport class ReleaseAgentTurns extends Context.Service<ReleaseAgentTurns, {\n readonly admitTurn?: (input: {\n readonly workspaceId: WorkspaceId\n readonly releaseId: ReleaseId\n readonly provider: AgentProvider\n }) => Effect.Effect<\n ReleaseAgentTurnAdmission,\n ApplicationInvalidRequest | ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n readonly runTurn: (input: {\n readonly admission?: ReleaseAgentTurnAdmission\n readonly workspaceId: WorkspaceId\n readonly releaseId: ReleaseId\n readonly originPath?: string\n readonly provider: AgentProvider\n readonly prompt: AgentPrompt\n readonly history: ReadonlyArray<AgentHistoryMessage>\n readonly publicationResult?: string\n }) => Effect.Effect<\n ReleaseAgentTurnResponse,\n ApplicationInvalidRequest | ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n}>()(\"@knpkv/control-center/server/api/ReleaseAgentTurns\") {}\n\n/**\n * Provider-neutral durable release-agent boundary. Implementations derive job,\n * context, and workspace ownership server-side and return only browser-safe events.\n */\nexport class ReleaseAgentJobs extends Context.Service<ReleaseAgentJobs, {\n readonly enqueue: (input: {\n readonly workspaceId: WorkspaceId\n readonly releaseId: ReleaseId\n readonly request: EnqueueReleaseAgentJobRequest\n }) => Effect.Effect<\n EnqueueReleaseAgentJobResponse,\n ApplicationInvalidRequest | ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n readonly providers: (workspaceId: WorkspaceId) => Effect.Effect<\n AgentProviderCatalog,\n ApplicationServiceUnavailable\n >\n readonly replay: (input: {\n readonly workspaceId: WorkspaceId\n readonly releaseId: ReleaseId\n readonly after: ReleaseAgentThreadCursor\n readonly limit: number\n }) => Effect.Effect<\n ReleaseAgentThreadPage,\n ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n}>()(\"@knpkv/control-center/server/api/ReleaseAgentJobs\") {}\n\n/** Server-owned orchestration for one exact immutable pull-request review. */\nexport class PullRequestReviews extends Context.Service<PullRequestReviews, {\n readonly thread: (input: {\n readonly workspaceId: WorkspaceId\n readonly entityId: EntityId\n readonly after: ReleaseAgentThreadCursor | null\n readonly before?: ReleaseAgentThreadCursor | null\n readonly limit: number\n }) => Effect.Effect<\n PullRequestReviewThreadPage,\n ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n readonly current: (input: {\n readonly workspaceId: WorkspaceId\n readonly entityId: EntityId\n }) => Effect.Effect<\n PullRequestReviewState,\n ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n readonly enqueue: (input: {\n readonly workspaceId: WorkspaceId\n readonly entityId: EntityId\n readonly request: EnqueuePullRequestReviewRequest\n }) => Effect.Effect<\n EnqueuePullRequestReviewResponse,\n ApplicationInvalidRequest | ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n readonly cancel: (input: {\n readonly workspaceId: WorkspaceId\n readonly entityId: EntityId\n readonly jobId: JobId\n }) => Effect.Effect<\n PullRequestReviewState,\n ApplicationInvalidRequest | ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n readonly extendBudget: (input: {\n readonly workspaceId: WorkspaceId\n readonly entityId: EntityId\n readonly jobId: JobId\n }) => Effect.Effect<\n PullRequestReviewState,\n ApplicationInvalidRequest | ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n readonly revisions: (input: {\n readonly workspaceId: WorkspaceId\n readonly entityId: EntityId\n readonly jobId: JobId\n readonly suggestionId: PrReviewSuggestionId\n readonly beforeSequence: PrReviewSuggestionRevisionSequence | null\n readonly limit: PrReviewSuggestionRevisionPageSize\n }) => Effect.Effect<\n ReviewSuggestionRevisionPage,\n ApplicationInvalidRequest | ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n readonly editSuggestion: (input: {\n readonly workspaceId: WorkspaceId\n readonly entityId: EntityId\n readonly jobId: JobId\n readonly suggestionId: PrReviewSuggestionId\n readonly request: EditReviewSuggestionRequest\n readonly session: SessionSummary\n }) => Effect.Effect<\n EditReviewSuggestionResponse,\n | ApplicationConflict\n | ApplicationInvalidRequest\n | ApplicationResourceNotFound\n | ApplicationServiceUnavailable\n >\n readonly targetSuggestion: (input: {\n readonly workspaceId: WorkspaceId\n readonly entityId: EntityId\n readonly jobId: JobId\n readonly suggestionId: PrReviewSuggestionId\n readonly request: TargetReviewSuggestionRequest\n }) => Effect.Effect<\n TargetReviewSuggestionResponse,\n | ApplicationConflict\n | ApplicationInvalidRequest\n | ApplicationResourceNotFound\n | ApplicationServiceUnavailable\n >\n readonly dismissSuggestion: (input: {\n readonly workspaceId: WorkspaceId\n readonly entityId: EntityId\n readonly jobId: JobId\n readonly suggestionId: PrReviewSuggestionId\n readonly request: DismissReviewSuggestionRequest\n readonly session: SessionSummary\n }) => Effect.Effect<\n DismissReviewSuggestionResponse,\n | ApplicationConflict\n | ApplicationInvalidRequest\n | ApplicationResourceNotFound\n | ApplicationServiceUnavailable\n >\n readonly previewPublication: (input: {\n readonly workspaceId: WorkspaceId\n readonly entityId: EntityId\n readonly jobId: PublishReviewSuggestionRequest[\"jobId\"]\n readonly suggestionId: PublishReviewSuggestionRequest[\"suggestionId\"]\n readonly revisionId: PublishReviewSuggestionRequest[\"revisionId\"]\n readonly operation?: PublishReviewSuggestionRequest[\"operation\"]\n readonly commentId?: PublishReviewSuggestionRequest[\"commentId\"]\n readonly publishingOperator: Extract<Actor, { readonly _tag: \"human\" }>[\"personId\"]\n }) => Effect.Effect<\n ReviewSuggestionPublicationPreview,\n ApplicationInvalidRequest | ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n readonly publishSuggestion: (input: {\n readonly workspaceId: WorkspaceId\n readonly entityId: EntityId\n readonly request: PublishReviewSuggestionRequest\n readonly session: SessionSummary\n }) => Effect.Effect<\n PublishedReviewComment,\n ApplicationInvalidRequest | ApplicationResourceNotFound | ApplicationServiceUnavailable\n >\n}>()(\"@knpkv/control-center/server/api/PullRequestReviews\") {}\n\n/** Injectable durable replay boundary used by the authenticated SSE handler. */\nexport class LiveEvents extends Context.Service<LiveEvents, {\n readonly open: (input: {\n readonly workspaceId: WorkspaceId\n readonly after: EventCursor | undefined\n }) => Effect.Effect<Stream.Stream<ControlCenterLiveEvent>, ApplicationServiceUnavailable, Scope.Scope>\n}>()(\"@knpkv/control-center/server/api/LiveEvents\") {}\n\n/** Fully authorized media stream whose provider address and storage key remain private. */\nexport interface MediaRead {\n readonly body: Stream.Stream<Uint8Array>\n readonly contentLength: number\n readonly contentType: SafeMediaContentType\n}\n\n/** Injectable opaque media boundary; implementations must authorize before returning a stream. */\nexport class MediaReads extends Context.Service<MediaReads, {\n readonly read: (input: {\n readonly workspaceId: WorkspaceId\n readonly mediaId: OpaqueMediaId\n }) => Effect.Effect<MediaRead, ApplicationResourceNotFound | ApplicationServiceUnavailable>\n}>()(\"@knpkv/control-center/server/api/MediaReads\") {}\n","/** Schema-owned Confluence page normalization boundary. @module */\nimport * as Result from \"effect/Result\"\nimport * as Schema from \"effect/Schema\"\n\nimport { hasMaximumPluginJsonBytes, MaximumPluginPayloadBytes } from \"../../../domain/plugins/bounds.js\"\nimport { UtcTimestamp } from \"../../../domain/utcTimestamp.js\"\n\nconst boundedString = (maximum: number) =>\n Schema.String.check(Schema.isTrimmed(), Schema.isNonEmpty(), Schema.isMaxLength(maximum))\nconst timestampString = Schema.String.check(\n Schema.makeFilter(\n (value) => Result.isSuccess(Schema.decodeUnknownResult(UtcTimestamp)(value)),\n { expected: \"an ISO-8601 UTC timestamp\" }\n )\n)\n\n/** @internal */\nexport const RawConfluenceVersion = Schema.Struct({\n number: Schema.Int.check(Schema.isGreaterThan(0)),\n createdAt: timestampString,\n message: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(2_000))),\n minorEdit: Schema.optionalKey(Schema.Boolean),\n authorId: Schema.optionalKey(boundedString(512))\n})\n\n/** Required subset of the current-page response, decoded again at the adapter boundary. @internal */\nexport const RawConfluencePage = Schema.Struct({\n id: boundedString(512),\n status: Schema.Literal(\"current\"),\n title: boundedString(500),\n spaceId: boundedString(512),\n parentId: Schema.optionalKey(Schema.NullOr(boundedString(512))),\n authorId: Schema.optionalKey(boundedString(512)),\n ownerId: Schema.optionalKey(Schema.NullOr(boundedString(512))),\n createdAt: timestampString,\n version: RawConfluenceVersion,\n body: Schema.optionalKey(Schema.Struct({\n atlas_doc_format: Schema.optionalKey(Schema.Struct({\n representation: Schema.optionalKey(Schema.Literal(\"atlas_doc_format\")),\n value: Schema.String.check(Schema.isMaxLength(1_048_576))\n }))\n })),\n _links: Schema.optionalKey(Schema.Struct({\n webui: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(4_096)))\n }))\n})\n\n/** Decoded current Confluence page. @internal */\nexport type RawConfluencePage = typeof RawConfluencePage.Type\n\n/** Required subset of a visible Confluence page draft. @internal */\nexport const RawConfluenceDraftPage = Schema.Struct({\n id: boundedString(512),\n status: Schema.Literal(\"draft\"),\n spaceId: boundedString(512)\n})\n\n/** Decoded Confluence page draft. @internal */\nexport type RawConfluenceDraftPage = typeof RawConfluenceDraftPage.Type\n\n/** One bounded page of current pages from exactly one configured space. @internal */\nexport const RawConfluenceSpacePage = Schema.Struct({\n results: Schema.optionalKey(Schema.Array(RawConfluencePage).check(Schema.isMaxLength(25))),\n _links: Schema.optionalKey(Schema.Struct({\n next: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(4_096)))\n }))\n})\n\n/** Decoded current-page listing for one space. @internal */\nexport type RawConfluenceSpacePage = typeof RawConfluenceSpacePage.Type\n\n/** Attachment metadata retained without loading attachment bytes. @internal */\nexport const RawConfluenceAttachment = Schema.Struct({\n id: boundedString(512),\n status: Schema.Literal(\"current\"),\n title: boundedString(500),\n createdAt: timestampString,\n pageId: boundedString(512),\n mediaType: Schema.optionalKey(Schema.String.check(Schema.isTrimmed(), Schema.isMaxLength(255))),\n fileSize: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n version: Schema.optionalKey(Schema.Struct({\n number: Schema.Int.check(Schema.isGreaterThan(0))\n }))\n})\n\n/** One bounded attachment metadata page. @internal */\nexport const RawConfluenceAttachmentPage = Schema.Struct({\n results: Schema.optionalKey(Schema.Array(RawConfluenceAttachment).check(Schema.isMaxLength(25))),\n _links: Schema.optionalKey(Schema.Struct({\n next: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(4_096)))\n }))\n})\n\n/** Decoded attachment metadata page. @internal */\nexport type RawConfluenceAttachmentPage = typeof RawConfluenceAttachmentPage.Type\n\n/** One bounded watcher page from the legacy page-notification read endpoint. @internal */\nexport const RawConfluenceWatcherPage = Schema.Struct({\n results: Schema.Array(Schema.Struct({\n type: boundedString(100),\n contentId: Schema.Number.check(\n Schema.makeFilter(Number.isInteger, { expected: \"a JSON integer\" }),\n Schema.isGreaterThan(0)\n ),\n watcher: Schema.Struct({\n accountId: Schema.NullOr(boundedString(512))\n })\n })).check(Schema.isMaxLength(50)),\n start: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n limit: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 50 })),\n size: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 50 }))\n})\n\n/** Decoded page watcher metadata. @internal */\nexport type RawConfluenceWatcherPage = typeof RawConfluenceWatcherPage.Type\n\n/** One decoded page of version history. @internal */\nexport const RawConfluenceVersionPage = Schema.Struct({\n results: Schema.optionalKey(Schema.Array(RawConfluenceVersion).check(Schema.isMaxLength(100))),\n _links: Schema.optionalKey(Schema.Struct({\n next: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(4_096)))\n }))\n})\n\n/** Decoded page of version history. @internal */\nexport type RawConfluenceVersionPage = typeof RawConfluenceVersionPage.Type\n\n/** Decoded Confluence page version. @internal */\nexport type RawConfluenceVersion = typeof RawConfluenceVersion.Type\n\n/** Privacy-limited profile returned by the current-user endpoint. @internal */\nexport const RawConfluenceCurrentUser = Schema.Struct({\n accountId: boundedString(512),\n displayName: Schema.optionalKey(Schema.NullOr(Schema.String.check(Schema.isMaxLength(200)))),\n publicName: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(200)))\n})\n\n/** Decoded current Confluence user. @internal */\nexport type RawConfluenceCurrentUser = typeof RawConfluenceCurrentUser.Type\n\n/** Bounded Confluence user returned by current-user and bulk-user reads. @internal */\nexport const RawConfluenceUser = Schema.Struct({\n accountId: boundedString(512),\n displayName: Schema.optionalKey(Schema.NullOr(boundedString(200))),\n accountStatus: Schema.optionalKey(Schema.Literals([\"active\", \"inactive\", \"closed\", \"unknown\"])),\n isExternalCollaborator: Schema.optionalKey(Schema.Boolean)\n})\n\n/** Decoded result from one bounded bulk user lookup. @internal */\nexport const RawConfluenceUsers = Schema.Struct({\n results: Schema.optionalKey(Schema.Array(RawConfluenceUser).check(Schema.isMaxLength(250)))\n})\n\n/** Decoded Confluence user. @internal */\nexport type RawConfluenceUser = typeof RawConfluenceUser.Type\n\nconst NormalizedVersion = Schema.Struct({\n number: Schema.Int.check(Schema.isGreaterThan(0)),\n createdAt: timestampString,\n message: Schema.NullOr(Schema.String.check(Schema.isMaxLength(2_000))),\n minorEdit: Schema.Boolean,\n authorId: Schema.NullOr(boundedString(512))\n})\n\nconst NormalizedContributor = Schema.Struct({\n accountId: boundedString(512),\n displayName: boundedString(200),\n active: Schema.Boolean,\n external: Schema.Boolean,\n resolved: Schema.Boolean,\n roles: Schema.Array(Schema.Literals([\"owner\", \"author\", \"contributor\", \"watcher\"])).check(\n Schema.isNonEmpty(),\n Schema.isUnique()\n )\n})\n\n/** Versioned vendor-neutral payload stored on a normalized Confluence page entity. @internal */\nexport const ConfluencePageAttributesV1 = Schema.Struct({\n schemaVersion: Schema.Literal(1),\n status: Schema.Literal(\"current\"),\n spaceId: boundedString(512),\n parentId: Schema.NullOr(boundedString(512)),\n createdAt: timestampString,\n updatedAt: timestampString,\n currentVersion: Schema.Int.check(Schema.isGreaterThan(0)),\n content: Schema.NullOr(Schema.Struct({\n representation: Schema.Literal(\"safe-markdown\"),\n markdown: Schema.String.check(Schema.isMaxLength(262_144))\n })),\n versions: Schema.Array(NormalizedVersion).check(Schema.isMaxLength(500)),\n versionHistory: Schema.Struct({\n complete: Schema.Boolean,\n pagesFetched: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 5 }))\n }),\n contributors: Schema.Array(NormalizedContributor).check(Schema.isMaxLength(502)),\n attachments: Schema.optionalKey(\n Schema.Array(Schema.Struct({\n id: boundedString(512),\n title: boundedString(500),\n createdAt: timestampString,\n mediaType: Schema.NullOr(Schema.String.check(Schema.isTrimmed(), Schema.isMaxLength(255))),\n fileSize: Schema.NullOr(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n version: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0)))\n })).check(Schema.isMaxLength(50))\n ),\n attachmentInventory: Schema.optionalKey(Schema.Struct({\n complete: Schema.Boolean,\n pagesFetched: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 2 }))\n })),\n watcherInventory: Schema.optionalKey(Schema.Struct({\n complete: Schema.Boolean,\n pagesFetched: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 2 }))\n })),\n contentState: Schema.optionalKey(Schema.Literals([\"loaded\", \"lazy\"]))\n}).check(hasMaximumPluginJsonBytes(MaximumPluginPayloadBytes))\n\n/** Decoded normalized Confluence page attributes. @internal */\nexport type ConfluencePageAttributesV1 = typeof ConfluencePageAttributesV1.Type\n","import type { NegotiatedPluginDescriptorV1 } from \"../../domain/plugins/descriptor.js\"\nimport type { ProviderId } from \"../../domain/sourceRevision.js\"\nimport { hasPluginCapability } from \"./negotiation.js\"\n\nconst FIRST_PARTY_SYNC_STREAMS: Readonly<Record<ProviderId, string>> = {\n codecommit: \"pull-requests\",\n codepipeline: \"executions\",\n jira: \"project-issues\",\n clockify: \"time-entries\",\n confluence: \"pages\"\n}\n\n/** Resolve the production synchronization stream owned by a first-party provider. */\nexport const firstPartySyncStreamKey = (providerId: ProviderId): string => FIRST_PARTY_SYNC_STREAMS[providerId]\n\n/** Apply first-party runtime migration policy to persisted synchronization descriptors. */\nexport const supportsFirstPartySynchronization = (\n _providerId: ProviderId,\n negotiated: typeof NegotiatedPluginDescriptorV1.Type\n): boolean => hasPluginCapability(negotiated, \"sync.incremental\", 1)\n","import * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as PubSub from \"effect/PubSub\"\nimport * as Stream from \"effect/Stream\"\n\nimport type { WorkspaceId } from \"../../domain/identifiers.js\"\n\n/** Maximum lossy wake hints retained while the durable journal remains authoritative. */\nexport const DOMAIN_EVENT_WAKEUP_CAPACITY = 64\n\nconst makeDomainEventWakeups = Effect.gen(function*() {\n const pubsub = yield* PubSub.sliding<WorkspaceId>({ capacity: DOMAIN_EVENT_WAKEUP_CAPACITY })\n yield* Effect.addFinalizer(() => PubSub.shutdown(pubsub))\n\n return {\n notify: Effect.fn(\"DomainEventWakeups.notify\")(function*(workspaceId: WorkspaceId) {\n yield* PubSub.publish(pubsub, workspaceId)\n }),\n subscribe: Effect.fn(\"DomainEventWakeups.subscribe\")(function*(workspaceId: WorkspaceId) {\n const subscription = yield* PubSub.subscribe(pubsub)\n return Stream.fromSubscription(subscription).pipe(\n Stream.filter((candidate) => candidate === workspaceId)\n )\n })\n }\n})\n\n/**\n * Lossy, bounded wake hints for durable event consumers.\n *\n * The database journal remains authoritative. Missing a wake only delays the\n * next poll and can never lose a committed event.\n */\nexport class DomainEventWakeups extends Context.Service<\n DomainEventWakeups,\n Effect.Success<typeof makeDomainEventWakeups>\n>()(\"@knpkv/control-center/server/runtime/DomainEventWakeups\") {\n /** One process-local bounded wake channel shared by writers and SSE readers. */\n static readonly layer = Layer.effect(DomainEventWakeups, makeDomainEventWakeups)\n}\n","import * as Crypto from \"effect/Crypto\"\nimport * as Effect from \"effect/Effect\"\nimport * as Schema from \"effect/Schema\"\n\nimport type { PortfolioInvalidationReason } from \"../../domain/domainEvent.js\"\nimport { DomainEventId, type PluginConnectionId, type ReleaseId, type WorkspaceId } from \"../../domain/identifiers.js\"\nimport type { UtcTimestamp } from \"../../domain/utcTimestamp.js\"\nimport { PersistenceOperationError } from \"../persistence/errors.js\"\nimport { Persistence } from \"../persistence/Persistence.js\"\nimport { DomainEventDedupeKey } from \"../persistence/repositories/domainEventModels.js\"\n\n/** Append the durable event consumed by live portfolio projections. */\nexport const appendPortfolioInvalidation = Effect.fn(\n \"PortfolioInvalidation.append\"\n)(function*(input: {\n readonly workspaceId: WorkspaceId\n readonly pluginConnectionId: PluginConnectionId\n readonly releaseId: ReleaseId | null\n readonly occurredAt: UtcTimestamp\n readonly reason: PortfolioInvalidationReason\n}) {\n const cryptoService = yield* Crypto.Crypto\n const persistence = yield* Persistence\n const eventId = yield* cryptoService.randomUUIDv7.pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"domain-event.random-id\" })),\n Effect.flatMap((value) =>\n Schema.decodeUnknownEffect(DomainEventId)(value).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"domain-event.random-id\" }))\n )\n )\n )\n return yield* persistence.events.append(input.workspaceId, {\n dedupeKey: DomainEventDedupeKey.make(eventId),\n schemaVersion: 1,\n eventId,\n eventType: \"portfolio-invalidated\",\n occurredAt: input.occurredAt,\n causationId: null,\n correlationId: null,\n metadata: {\n ...(input.releaseId === null ? {} : { releaseId: input.releaseId }),\n pluginConnectionId: input.pluginConnectionId\n },\n payload: { reason: input.reason }\n })\n})\n","import type {\n DeliveryEntityKind,\n DeliveryEntityProjection,\n DeliveryRelationship,\n RelationshipEndpointKind,\n RelationshipKind\n} from \"../../domain/deliveryGraph.js\"\nimport type { EntityId, GraphNodeId, ReleaseId } from \"../../domain/identifiers.js\"\n\n/** One current canonical entity exposed to provider-neutral relationship rules. */\nexport interface RelationshipInferenceEntity {\n readonly nodeId: GraphNodeId\n readonly projection: DeliveryEntityProjection\n readonly releaseIds: ReadonlyArray<ReleaseId>\n}\n\n/** One canonical release exposed without provider-specific version objects. */\nexport interface RelationshipInferenceRelease {\n readonly nodeId: GraphNodeId\n readonly releaseId: ReleaseId\n readonly version: string\n}\n\nexport type RelationshipInferenceEndpoint =\n | Readonly<{ readonly _tag: \"resolved\"; readonly kind: RelationshipEndpointKind; readonly nodeId: GraphNodeId }>\n | Readonly<{\n readonly _tag: \"missing\"\n readonly identityKey: string\n readonly kind: DeliveryEntityKind\n readonly missingKey: string\n }>\n\n/** Explainable candidate ready for evidence and ledger materialization. */\nexport interface RelationshipInferenceCandidate {\n readonly confidence: Readonly<{ readonly score: number; readonly rationale: string }> | null\n readonly evidenceEntityId: EntityId | null\n readonly identityKey: string\n readonly kind: RelationshipKind\n readonly lifecycle: \"inferred\" | \"missing\"\n readonly observationKey: string\n readonly releaseId: ReleaseId\n readonly ruleId: string\n readonly source: RelationshipInferenceEndpoint\n readonly target: RelationshipInferenceEndpoint\n}\n\nexport interface RelationshipInferenceResult {\n readonly candidates: ReadonlyArray<RelationshipInferenceCandidate>\n readonly obsoleteGapIdentityKeys: ReadonlyArray<string>\n readonly obsoleteRelationshipIds: ReadonlyArray<DeliveryRelationship[\"relationshipId\"]>\n readonly truncated: boolean\n}\n\nconst MAXIMUM_INFERENCE_CANDIDATES = 2_000\n\ninterface CandidateAccumulator {\n readonly candidates: Array<RelationshipInferenceCandidate>\n readonly minimumConfidenceScore: number\n truncated: boolean\n}\n\nconst addCandidate = (\n accumulator: CandidateAccumulator,\n candidate: RelationshipInferenceCandidate\n): boolean => {\n if (\n candidate.lifecycle === \"inferred\" &&\n candidate.confidence !== null &&\n candidate.confidence.score < accumulator.minimumConfidenceScore\n ) return false\n if (accumulator.candidates.length >= MAXIMUM_INFERENCE_CANDIDATES) {\n accumulator.truncated = true\n return false\n }\n accumulator.candidates.push(candidate)\n return true\n}\n\nconst OWNED_RULE_IDS = new Set([\n \"codepipeline-trigger-revision-v1\",\n \"confluence-jira-link-v1\",\n \"confluence-release-link-v1\",\n \"jira-key-in-clockify-description-v1\",\n \"jira-key-in-confluence-metadata-v1\",\n \"jira-key-in-pull-request-metadata-v1\",\n \"release-in-confluence-metadata-v1\"\n])\n\nconst present = (entity: RelationshipInferenceEntity): boolean => entity.projection.entityState === \"present\"\n\nconst resolved = (kind: RelationshipEndpointKind, nodeId: GraphNodeId): RelationshipInferenceEndpoint => ({\n _tag: \"resolved\",\n kind,\n nodeId\n})\n\nconst missing = (\n kind: DeliveryEntityKind,\n missingKey: string,\n identityKey: string\n): RelationshipInferenceEndpoint => ({\n _tag: \"missing\",\n identityKey,\n kind,\n missingKey\n})\n\nconst currentRelationship = (relationship: DeliveryRelationship): boolean =>\n relationship.lifecycle._tag !== \"missing\" &&\n relationship.lifecycle._tag !== \"rejected\" &&\n relationship.lifecycle._tag !== \"superseded\"\n\nconst currentExternalRelationship = (relationship: DeliveryRelationship): boolean =>\n currentRelationship(relationship) &&\n !(\n relationship.lifecycle._tag === \"inferred\" &&\n relationship.provenance._tag === \"rule\" &&\n OWNED_RULE_IDS.has(relationship.provenance.ruleId)\n )\n\nconst currentOwnedRelationship = (relationship: DeliveryRelationship): boolean =>\n currentRelationship(relationship) &&\n relationship.lifecycle._tag === \"inferred\" &&\n relationship.provenance._tag === \"rule\" &&\n OWNED_RULE_IDS.has(relationship.provenance.ruleId)\n\nconst currentInferenceRelationship = (relationship: DeliveryRelationship): boolean =>\n relationship.lifecycle._tag !== \"rejected\" &&\n relationship.lifecycle._tag !== \"superseded\" &&\n relationship.provenance._tag === \"rule\" &&\n (relationship.provenance.ruleId === \"delivery-gap-v1\" || OWNED_RULE_IDS.has(relationship.provenance.ruleId))\n\nconst relationshipInRelease = (relationship: DeliveryRelationship, releaseId: ReleaseId): boolean =>\n relationship.scope?._tag === \"release\" && relationship.scope.releaseId === releaseId\n\nconst containsToken = (text: string, token: string): boolean => {\n const normalizedText = text.toUpperCase()\n const normalizedToken = token.toUpperCase()\n let offset = normalizedText.indexOf(normalizedToken)\n while (offset >= 0) {\n const before = normalizedText[offset - 1]\n const after = normalizedText[offset + normalizedToken.length]\n const boundary = (character: string | undefined) => character === undefined || !/[A-Z0-9]/u.test(character)\n if (boundary(before) && boundary(after)) return true\n offset = normalizedText.indexOf(normalizedToken, offset + normalizedToken.length)\n }\n return false\n}\n\nconst containsReleaseVersion = (text: string, version: string): boolean => {\n const normalizedText = text.toUpperCase()\n const normalizedVersion = version.toUpperCase()\n let offset = normalizedText.indexOf(normalizedVersion)\n while (offset >= 0) {\n const before = normalizedText[offset - 1]\n const after = normalizedText[offset + normalizedVersion.length]\n const boundary = (character: string | undefined) => character === undefined || !/[A-Z0-9._+-]/u.test(character)\n if (boundary(before) && boundary(after)) return true\n offset = normalizedText.indexOf(normalizedVersion, offset + normalizedVersion.length)\n }\n return false\n}\n\nconst metadata = (entity: RelationshipInferenceEntity): string => {\n const details = entity.projection.details\n return details._tag === \"pull-request\"\n ? [entity.projection.title, entity.projection.displayKey, details.sourceBranch, details.targetBranch].join(\"\\n\")\n : details._tag === \"time-entry\"\n ? [entity.projection.title, entity.projection.displayKey, details.description ?? \"\"].join(\"\\n\")\n : [entity.projection.title, entity.projection.displayKey].join(\"\\n\")\n}\n\nconst observationKey = (...entities: ReadonlyArray<RelationshipInferenceEntity>): string =>\n entities\n .map(({ projection }) => `${projection.entityId}@${String(projection.projectionRevision)}`)\n .sort()\n .join(\"+\")\n\nconst inferred = (input: Omit<RelationshipInferenceCandidate, \"lifecycle\">): RelationshipInferenceCandidate => ({\n ...input,\n lifecycle: \"inferred\"\n})\n\nconst gap = (input: {\n readonly identityKey: string\n readonly kind: RelationshipKind\n readonly releaseId: ReleaseId\n readonly source: RelationshipInferenceEndpoint\n readonly target: RelationshipInferenceEndpoint\n}): RelationshipInferenceCandidate => ({\n ...input,\n confidence: null,\n evidenceEntityId: null,\n lifecycle: \"missing\",\n observationKey: input.identityKey,\n ruleId: \"delivery-gap-v1\"\n})\n\nconst candidateIdentity = (\n kind: RelationshipKind,\n releaseId: ReleaseId,\n source: GraphNodeId,\n target: GraphNodeId\n): string => `relationship:${kind}:${releaseId}:${source}:${target}`\n\nconst issueGapIdentity = (releaseId: ReleaseId, issueNodeId: GraphNodeId): string =>\n `gap:implements:${releaseId}:${issueNodeId}`\n\nconst pipelineGapIdentity = (releaseId: ReleaseId, pullRequestNodeId: GraphNodeId): string =>\n `gap:delivered-by:${releaseId}:${pullRequestNodeId}`\n\nconst candidateGapKey = (candidate: RelationshipInferenceCandidate): string | null => {\n if (candidate.lifecycle !== \"missing\") return null\n if (candidate.kind === \"implements\" && candidate.target._tag === \"resolved\") {\n return `${candidate.kind}:${candidate.releaseId}:${candidate.target.nodeId}`\n }\n if (candidate.kind === \"delivered-by\" && candidate.source._tag === \"resolved\") {\n return `${candidate.kind}:${candidate.releaseId}:${candidate.source.nodeId}`\n }\n return null\n}\n\nconst relationshipGapKey = (relationship: DeliveryRelationship): string | null => {\n if (\n relationship.lifecycle._tag !== \"missing\" ||\n relationship.provenance._tag !== \"rule\" ||\n relationship.provenance.ruleId !== \"delivery-gap-v1\" ||\n relationship.scope?._tag !== \"release\"\n ) return null\n if (relationship.kind === \"implements\") {\n return `${relationship.kind}:${relationship.scope.releaseId}:${relationship.targetNodeId}`\n }\n if (relationship.kind === \"delivered-by\") {\n return `${relationship.kind}:${relationship.scope.releaseId}:${relationship.sourceNodeId}`\n }\n return null\n}\n\nconst hasRelationship = (\n relationships: ReadonlyArray<DeliveryRelationship>,\n releaseId: ReleaseId,\n kind: RelationshipKind,\n sourceNodeId: GraphNodeId | null,\n targetNodeId: GraphNodeId | null\n): boolean =>\n relationships.some(\n (relationship) =>\n currentExternalRelationship(relationship) &&\n relationshipInRelease(relationship, releaseId) &&\n relationship.kind === kind &&\n (sourceNodeId === null || relationship.sourceNodeId === sourceNodeId) &&\n (targetNodeId === null || relationship.targetNodeId === targetNodeId)\n )\n\nconst addIssueAndTimeCandidates = (\n entities: ReadonlyArray<RelationshipInferenceEntity>,\n accumulator: CandidateAccumulator\n) => {\n const issues = entities.filter((entity) => entity.projection.details._tag === \"issue\")\n const timeEntries = entities.filter((entity) => entity.projection.details._tag === \"time-entry\")\n for (const timeEntry of timeEntries) {\n for (const issue of issues) {\n const details = issue.projection.details\n if (details._tag !== \"issue\" || !containsToken(metadata(timeEntry), details.key)) continue\n for (const releaseId of issue.releaseIds) {\n addCandidate(\n accumulator,\n inferred({\n confidence: { score: 0.95, rationale: `The Clockify description contains Jira key ${details.key}.` },\n evidenceEntityId: timeEntry.projection.entityId,\n identityKey: candidateIdentity(\"tracks-time-for\", releaseId, timeEntry.nodeId, issue.nodeId),\n kind: \"tracks-time-for\",\n observationKey: observationKey(timeEntry, issue),\n releaseId,\n ruleId: \"jira-key-in-clockify-description-v1\",\n source: resolved(\"time-entry\", timeEntry.nodeId),\n target: resolved(\"issue\", issue.nodeId)\n })\n )\n }\n }\n }\n}\n\nconst addDocumentationCandidates = (\n entities: ReadonlyArray<RelationshipInferenceEntity>,\n releases: ReadonlyArray<RelationshipInferenceRelease>,\n accumulator: CandidateAccumulator\n) => {\n const issues = entities.filter((entity) => entity.projection.details._tag === \"issue\")\n const releaseVersionCounts = new Map<string, number>()\n for (const release of releases) {\n const version = release.version.toUpperCase()\n releaseVersionCounts.set(version, (releaseVersionCounts.get(version) ?? 0) + 1)\n }\n const pages = entities.filter(\n (entity) => entity.projection.details._tag === \"page\" && entity.projection.details.status === \"current\"\n )\n for (const page of pages) {\n const pageDetails = page.projection.details\n if (pageDetails._tag !== \"page\") continue\n const pageMetadata = metadata(page)\n for (const issue of issues) {\n const details = issue.projection.details\n if (details._tag !== \"issue\") continue\n const explicitLink = pageDetails.linkedIssueKeys?.some((key) =>\n key.toUpperCase() === details.key.toUpperCase()\n ) ?? false\n if (!explicitLink && !containsToken(pageMetadata, details.key)) continue\n for (const releaseId of issue.releaseIds) {\n addCandidate(\n accumulator,\n inferred({\n confidence: {\n score: explicitLink ? 0.97 : 0.9,\n rationale: explicitLink\n ? `Confluence metadata links Jira key ${details.key}.`\n : `Confluence page metadata contains Jira key ${details.key}.`\n },\n evidenceEntityId: page.projection.entityId,\n identityKey: candidateIdentity(\"documented-by\", releaseId, issue.nodeId, page.nodeId),\n kind: \"documented-by\",\n observationKey: observationKey(page, issue),\n releaseId,\n ruleId: explicitLink ? \"confluence-jira-link-v1\" : \"jira-key-in-confluence-metadata-v1\",\n source: resolved(\"issue\", issue.nodeId),\n target: resolved(\"page\", page.nodeId)\n })\n )\n }\n }\n for (const release of releases) {\n if ((releaseVersionCounts.get(release.version.toUpperCase()) ?? 0) > 1) continue\n const explicitLink = pageDetails.linkedReleaseVersions?.some(\n (version) => version.toUpperCase() === release.version.toUpperCase()\n ) ?? false\n if (!explicitLink && !containsReleaseVersion(pageMetadata, release.version)) continue\n addCandidate(\n accumulator,\n inferred({\n confidence: {\n score: explicitLink ? 0.96 : 0.88,\n rationale: explicitLink\n ? `Confluence metadata links release ${release.version}.`\n : `Confluence page metadata contains release ${release.version}.`\n },\n evidenceEntityId: page.projection.entityId,\n identityKey: candidateIdentity(\"documented-by\", release.releaseId, release.nodeId, page.nodeId),\n kind: \"documented-by\",\n observationKey: observationKey(page),\n releaseId: release.releaseId,\n ruleId: explicitLink ? \"confluence-release-link-v1\" : \"release-in-confluence-metadata-v1\",\n source: resolved(\"release\", release.nodeId),\n target: resolved(\"page\", page.nodeId)\n })\n )\n }\n }\n}\n\n/**\n * Infer a deterministic relationship set from current canonical facts. Rules\n * only propose `inferred` or `missing`; confirmation remains governed.\n */\nexport const deriveRelationshipInference = (input: {\n readonly entities: ReadonlyArray<RelationshipInferenceEntity>\n readonly minimumConfidenceScore?: number\n readonly rejectedCandidateIdentityKeys?: ReadonlySet<string>\n readonly releases: ReadonlyArray<RelationshipInferenceRelease>\n readonly relationships: ReadonlyArray<DeliveryRelationship>\n}): RelationshipInferenceResult => {\n const entities = input.entities.filter(present).map((entity) => ({\n ...entity,\n releaseIds: entity.releaseIds.filter((releaseId) => {\n const touchesEntity = (relationship: DeliveryRelationship) =>\n relationshipInRelease(relationship, releaseId) &&\n (relationship.sourceNodeId === entity.nodeId || relationship.targetNodeId === entity.nodeId)\n const inferenceMembership = input.relationships.some(\n (relationship) => currentInferenceRelationship(relationship) && touchesEntity(relationship)\n )\n return !inferenceMembership ||\n input.relationships.some((relationship) =>\n currentExternalRelationship(relationship) &&\n touchesEntity(relationship)\n )\n })\n }))\n const issues = entities.filter((entity) => entity.projection.details._tag === \"issue\")\n const pullRequests = entities.filter((entity) => entity.projection.details._tag === \"pull-request\")\n const pipelines = entities.filter((entity) => entity.projection.details._tag === \"pipeline-execution\")\n const accumulator: CandidateAccumulator = {\n candidates: [],\n minimumConfidenceScore: input.minimumConfidenceScore ?? 0,\n truncated: false\n }\n const obsoleteGaps = new Set<string>()\n const inferredIssueLinks = new Set<string>()\n const pullRequestReleases = new Map<GraphNodeId, Set<ReleaseId>>()\n\n for (const pullRequest of pullRequests) {\n const details = pullRequest.projection.details\n if (details._tag !== \"pull-request\") continue\n const releaseIds = new Set(\n pullRequest.releaseIds.filter((releaseId) => {\n const touchesPullRequest = (relationship: DeliveryRelationship) =>\n relationshipInRelease(relationship, releaseId) &&\n (relationship.sourceNodeId === pullRequest.nodeId || relationship.targetNodeId === pullRequest.nodeId)\n const ownedMembership = input.relationships.some(\n (relationship) => currentOwnedRelationship(relationship) && touchesPullRequest(relationship)\n )\n return !ownedMembership || input.relationships.some(\n (relationship) => currentExternalRelationship(relationship) && touchesPullRequest(relationship)\n )\n })\n )\n for (const issue of issues) {\n const issueDetails = issue.projection.details\n if (issueDetails._tag !== \"issue\" || !containsToken(metadata(pullRequest), issueDetails.key)) continue\n for (const releaseId of issue.releaseIds) {\n const identityKey = candidateIdentity(\"implements\", releaseId, pullRequest.nodeId, issue.nodeId)\n const accepted = addCandidate(\n accumulator,\n inferred({\n confidence: {\n score: containsToken(pullRequest.projection.title, issueDetails.key) ? 0.98 : 0.94,\n rationale: `The immutable pull-request metadata contains Jira key ${issueDetails.key}.`\n },\n evidenceEntityId: pullRequest.projection.entityId,\n identityKey,\n kind: \"implements\",\n observationKey: observationKey(pullRequest, issue),\n releaseId,\n ruleId: \"jira-key-in-pull-request-metadata-v1\",\n source: resolved(\"pull-request\", pullRequest.nodeId),\n target: resolved(\"issue\", issue.nodeId)\n })\n )\n if (accepted && !(input.rejectedCandidateIdentityKeys?.has(identityKey) ?? false)) {\n releaseIds.add(releaseId)\n inferredIssueLinks.add(`${releaseId}:${issue.nodeId}`)\n obsoleteGaps.add(issueGapIdentity(releaseId, issue.nodeId))\n }\n }\n }\n for (const relationship of input.relationships) {\n if (\n currentExternalRelationship(relationship) &&\n relationship.kind === \"implements\" &&\n relationship.sourceNodeId === pullRequest.nodeId &&\n relationship.scope?._tag === \"release\"\n ) {\n releaseIds.add(relationship.scope.releaseId)\n }\n }\n pullRequestReleases.set(pullRequest.nodeId, releaseIds)\n }\n\n for (const issue of issues) {\n for (const releaseId of issue.releaseIds) {\n const identityKey = issueGapIdentity(releaseId, issue.nodeId)\n if (\n inferredIssueLinks.has(`${releaseId}:${issue.nodeId}`) ||\n hasRelationship(input.relationships, releaseId, \"implements\", null, issue.nodeId)\n ) {\n obsoleteGaps.add(identityKey)\n } else {\n const details = issue.projection.details\n if (details._tag !== \"issue\") continue\n addCandidate(\n accumulator,\n gap({\n identityKey,\n kind: \"implements\",\n releaseId,\n source: missing(\"pull-request\", `${details.key}:pull-request`, issue.nodeId),\n target: resolved(\"issue\", issue.nodeId)\n })\n )\n }\n }\n }\n\n const inferredPipelineLinks = new Set<string>()\n for (const pullRequest of pullRequests) {\n const pullRequestDetails = pullRequest.projection.details\n if (pullRequestDetails._tag !== \"pull-request\") continue\n for (const pipeline of pipelines) {\n const pipelineDetails = pipeline.projection.details\n if (\n pipelineDetails._tag !== \"pipeline-execution\" ||\n pipelineDetails.triggerRevision !== pullRequestDetails.headRevision\n ) {\n continue\n }\n for (const releaseId of pullRequestReleases.get(pullRequest.nodeId) ?? []) {\n const identityKey = candidateIdentity(\"delivered-by\", releaseId, pullRequest.nodeId, pipeline.nodeId)\n const accepted = addCandidate(\n accumulator,\n inferred({\n confidence: {\n score: 0.99,\n rationale:\n `The pipeline trigger revision exactly matches pull-request head ${pullRequestDetails.headRevision}.`\n },\n evidenceEntityId: pipeline.projection.entityId,\n identityKey,\n kind: \"delivered-by\",\n observationKey: observationKey(pullRequest, pipeline),\n releaseId,\n ruleId: \"codepipeline-trigger-revision-v1\",\n source: resolved(\"pull-request\", pullRequest.nodeId),\n target: resolved(\"pipeline-execution\", pipeline.nodeId)\n })\n )\n if (accepted && !(input.rejectedCandidateIdentityKeys?.has(identityKey) ?? false)) {\n inferredPipelineLinks.add(`${releaseId}:${pullRequest.nodeId}`)\n obsoleteGaps.add(pipelineGapIdentity(releaseId, pullRequest.nodeId))\n }\n }\n }\n }\n\n for (const pullRequest of pullRequests) {\n for (const releaseId of pullRequestReleases.get(pullRequest.nodeId) ?? []) {\n const identityKey = pipelineGapIdentity(releaseId, pullRequest.nodeId)\n if (\n inferredPipelineLinks.has(`${releaseId}:${pullRequest.nodeId}`) ||\n hasRelationship(input.relationships, releaseId, \"delivered-by\", pullRequest.nodeId, null) ||\n hasRelationship(input.relationships, releaseId, \"verified-by\", pullRequest.nodeId, null)\n ) {\n obsoleteGaps.add(identityKey)\n } else {\n addCandidate(\n accumulator,\n gap({\n identityKey,\n kind: \"delivered-by\",\n releaseId,\n source: resolved(\"pull-request\", pullRequest.nodeId),\n target: missing(\n \"pipeline-execution\",\n `${pullRequest.projection.displayKey}:pipeline-execution`,\n pullRequest.nodeId\n )\n })\n )\n }\n }\n }\n\n addIssueAndTimeCandidates(entities, accumulator)\n addDocumentationCandidates(entities, input.releases, accumulator)\n const unique = new Map(accumulator.candidates.map((candidate) => [candidate.identityKey, candidate]))\n const candidateEdges = new Set(\n [...unique.values()].flatMap((candidate) =>\n candidate.lifecycle === \"inferred\" && candidate.source._tag === \"resolved\" && candidate.target._tag === \"resolved\"\n ? [`${candidate.kind}:${candidate.releaseId}:${candidate.source.nodeId}:${candidate.target.nodeId}`]\n : []\n )\n )\n const candidateGaps = new Set(\n [...unique.values()].flatMap((candidate) => {\n const key = candidateGapKey(candidate)\n return key === null ? [] : [key]\n })\n )\n const obsoleteRelationshipIds = input.relationships.flatMap((relationship) => {\n const gapKey = relationshipGapKey(relationship)\n const obsoleteInference = relationship.lifecycle._tag === \"inferred\" &&\n relationship.provenance._tag === \"rule\" &&\n OWNED_RULE_IDS.has(relationship.provenance.ruleId) &&\n relationship.scope?._tag === \"release\" &&\n !candidateEdges.has(\n `${relationship.kind}:${relationship.scope.releaseId}:${relationship.sourceNodeId}:${relationship.targetNodeId}`\n )\n const obsoleteGap = gapKey !== null && !candidateGaps.has(gapKey)\n return obsoleteInference || obsoleteGap ? [relationship.relationshipId] : []\n })\n return {\n candidates: [...unique.values()].sort((left, right) => left.identityKey.localeCompare(right.identityKey)),\n obsoleteGapIdentityKeys: [...obsoleteGaps].sort(),\n obsoleteRelationshipIds: [...new Set(obsoleteRelationshipIds)].sort(),\n truncated: accumulator.truncated\n }\n}\n","import type * 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 {\n type DeliveryNode,\n type DeliveryRelationship,\n type EvidenceClaim,\n type EvidenceItem,\n LedgerRevision\n} from \"../../domain/deliveryGraph.js\"\nimport type { Freshness, PluginHealth } from \"../../domain/freshness.js\"\nimport { EvidenceClaimId, EvidenceId, GraphNodeId, RelationshipId, type WorkspaceId } from \"../../domain/identifiers.js\"\nimport type { UtcTimestamp } from \"../../domain/utcTimestamp.js\"\nimport type { WorkspaceSettingsV1 } from \"../../domain/workspaceSettings.js\"\nimport { PersistenceOperationError } from \"../persistence/errors.js\"\nimport type { PersistenceOperationFailure, PersistenceService } from \"../persistence/Persistence.js\"\nimport { DeliveryGraphWriteBatch } from \"../persistence/repositories/deliveryGraphRepository.js\"\nimport type { EntityRecord } from \"../persistence/repositories/models.js\"\nimport { PluginStreamKey } from \"../persistence/repositories/pluginRuntimeModels.js\"\nimport { firstPartySyncStreamKey } from \"../plugins/firstPartySynchronization.js\"\nimport {\n deriveRelationshipInference,\n type RelationshipInferenceCandidate,\n type RelationshipInferenceEndpoint,\n type RelationshipInferenceEntity,\n type RelationshipInferenceRelease\n} from \"./relationshipInference.js\"\n\nconst MAXIMUM_INFERENCE_ENTITIES = 500\nconst MAXIMUM_INFERENCE_RELEASES = 50\nconst MAXIMUM_INFERENCE_RELATIONSHIPS = 2_000\nconst COMPONENT = \"relationship-inference\"\n\nexport interface RelationshipInferenceMaterializationScope {\n readonly committedAt: UtcTimestamp\n readonly streamKey: PluginStreamKey\n readonly successfulHealth: Extract<PluginHealth, { readonly _tag: \"healthy\" | \"degraded\" }>\n readonly workspaceId: WorkspaceId\n}\n\nexport interface RelationshipInferenceMaterializationReceipt {\n readonly evidenceClaimCount: number\n readonly evidenceItemCount: number\n readonly nodeCount: number\n readonly relationshipCount: number\n readonly skippedDueToBounds: boolean\n}\n\ntype StableIdentity<IdentityError> = (identity: string) => Effect.Effect<string, IdentityError>\n\nconst readRelationship = Effect.fn(\"RelationshipInferenceMaterialization.readRelationship\")(function*(\n persistence: PersistenceService,\n workspaceId: WorkspaceId,\n relationshipId: RelationshipId\n) {\n const result = yield* persistence.deliveryGraph\n .read(workspaceId, {\n _tag: \"relationship\",\n relationshipId,\n revision: null\n })\n .pipe(Effect.result)\n if (Result.isFailure(result)) {\n if (result.failure._tag === \"RecordNotFoundError\") return null\n return yield* result.failure\n }\n return result.success._tag === \"relationship\" ? result.success.value : null\n})\n\nconst nodeExists = Effect.fn(\"RelationshipInferenceMaterialization.nodeExists\")(function*(\n persistence: PersistenceService,\n workspaceId: WorkspaceId,\n nodeId: GraphNodeId\n) {\n const result = yield* persistence.deliveryGraph\n .read(workspaceId, {\n _tag: \"node\",\n nodeId\n })\n .pipe(Effect.result)\n if (Result.isSuccess(result)) return true\n if (result.failure._tag === \"RecordNotFoundError\") return false\n return yield* result.failure\n})\n\nconst writeGraph = Effect.fn(\"RelationshipInferenceMaterialization.writeGraph\")(function*(\n persistence: PersistenceService,\n workspaceId: WorkspaceId,\n batch: typeof DeliveryGraphWriteBatch.Type\n) {\n const encoded = yield* Schema.encodeEffect(DeliveryGraphWriteBatch)(batch).pipe(\n Effect.mapError(() => new PersistenceOperationError({ operation: \"relationship-inference.encode\" }))\n )\n return yield* persistence.deliveryGraph.write(workspaceId, encoded)\n})\n\nconst relationshipIdentity = (workspaceId: WorkspaceId, identityKey: string): string =>\n `${workspaceId}\\u0000relationship-inference\\u0000relationship\\u0000${identityKey}`\n\nconst missingNodeIdentity = (workspaceId: WorkspaceId, endpointKind: string, missingKey: string): string =>\n `${workspaceId}\\u0000relationship-inference\\u0000missing-node\\u0000${endpointKind}\\u0000${missingKey}`\n\nconst evidenceIdentity = (\n workspaceId: WorkspaceId,\n identityKey: string,\n observationKey: string,\n kind: \"claim\" | \"item\"\n): string =>\n `${workspaceId}\\u0000relationship-inference\\u0000evidence-${kind}\\u0000${identityKey}\\u0000${observationKey}`\n\nconst entityNodeIdentity = (workspaceId: WorkspaceId, entity: EntityRecord): string => {\n const source = entity.sourceRevision\n return `${workspaceId}\\u0000${source.pluginConnectionId}\\u0000${source.providerId}\\u0000entity-node\\u0000${source.vendorImmutableId}`\n}\n\nconst releaseNodeIdentity = (\n workspaceId: WorkspaceId,\n pluginConnectionId: string,\n providerId: string,\n vendorImmutableId: string\n): string => `${workspaceId}\\u0000${pluginConnectionId}\\u0000${providerId}\\u0000release-node\\u0000${vendorImmutableId}`\n\nconst relationshipIdFor = <IdentityError>(\n identity: StableIdentity<IdentityError>,\n workspaceId: WorkspaceId,\n identityKey: string\n) => identity(relationshipIdentity(workspaceId, identityKey)).pipe(Effect.map(RelationshipId.make))\n\nconst endpointNode = <IdentityError>(\n identity: StableIdentity<IdentityError>,\n scope: RelationshipInferenceMaterializationScope,\n endpoint: RelationshipInferenceEndpoint\n) =>\n endpoint._tag === \"resolved\"\n ? Effect.succeed({ node: null, nodeId: endpoint.nodeId })\n : identity(missingNodeIdentity(scope.workspaceId, endpoint.kind, endpoint.identityKey)).pipe(\n Effect.map((value) => {\n const nodeId = GraphNodeId.make(value)\n const node: DeliveryNode = {\n workspaceId: scope.workspaceId,\n nodeId,\n endpointKind: endpoint.kind,\n resolution: {\n _tag: \"missing\",\n expectedKind: \"entity\",\n expectedEntityKind: endpoint.kind,\n missingKey: endpoint.missingKey\n },\n createdAt: scope.committedAt\n }\n return {\n nodeId,\n node\n }\n })\n )\n\nconst evidenceFor = Effect.fn(\"RelationshipInferenceMaterialization.evidenceFor\")(function*<IdentityError>(\n persistence: PersistenceService,\n identity: StableIdentity<IdentityError>,\n scope: RelationshipInferenceMaterializationScope,\n settings: WorkspaceSettingsV1,\n candidate: RelationshipInferenceCandidate,\n sourceNodeId: GraphNodeId,\n targetNodeId: GraphNodeId,\n entity: EntityRecord\n): Effect.fn.Return<\n { readonly claim: EvidenceClaim; readonly item: EvidenceItem },\n IdentityError | PersistenceOperationFailure\n> {\n const evidenceId = EvidenceId.make(\n yield* identity(evidenceIdentity(scope.workspaceId, candidate.identityKey, candidate.observationKey, \"item\"))\n )\n const evidenceClaimId = EvidenceClaimId.make(\n yield* identity(evidenceIdentity(scope.workspaceId, candidate.identityKey, candidate.observationKey, \"claim\"))\n )\n const source = entity.sourceRevision\n const sourceStreamKey = yield* Schema.decodeUnknownEffect(PluginStreamKey)(\n firstPartySyncStreamKey(source.providerId)\n ).pipe(Effect.mapError(() => new PersistenceOperationError({ operation: \"relationship-inference.source-stream\" })))\n const pluginHealth = yield* persistence.pluginRuntime.getLastSuccessfulHealth(\n scope.workspaceId,\n source.pluginConnectionId,\n sourceStreamKey\n )\n if (pluginHealth === null) {\n return yield* new PersistenceOperationError({ operation: \"relationship-inference.source-health\" })\n }\n const sourceAgeSeconds = Math.max(\n 0,\n (DateTime.toEpochMillis(scope.committedAt) - DateTime.toEpochMillis(source.lastObservedAt)) / 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,\n provenance: { _tag: \"provider\", sourceRevision: source },\n sourceObservedAt: source.lastObservedAt,\n staleAfterSeconds,\n synchronizedAt: source.synchronizedAt\n }\n : {\n _tag: \"stale\",\n evaluatedAt: scope.committedAt,\n pluginHealth,\n provenance: {\n _tag: \"cache\",\n cachedAt: source.synchronizedAt,\n sourceRevision: source\n },\n sourceObservedAt: source.lastObservedAt,\n staleAfterSeconds,\n synchronizedAt: source.synchronizedAt\n }\n return {\n item: {\n workspaceId: scope.workspaceId,\n evidenceId,\n schemaVersion: 1,\n attribution: { _tag: \"system\", component: COMPONENT },\n verifier: { _tag: \"system\", component: COMPONENT },\n observedAt: source.lastObservedAt,\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 claim: {\n workspaceId: scope.workspaceId,\n evidenceClaimId,\n evidenceId,\n subjectNodeId: sourceNodeId,\n predicate: \"relationship-observed\",\n value: { _tag: \"reference\", targetNodeId },\n recordedAt: scope.committedAt,\n supersedesEvidenceClaimId: null\n }\n }\n})\n\nconst unchanged = (\n previous: DeliveryRelationship | null,\n candidate: RelationshipInferenceCandidate,\n sourceNodeId: GraphNodeId,\n targetNodeId: GraphNodeId,\n claimId: EvidenceClaimId | null\n): boolean =>\n previous !== null &&\n previous.kind === candidate.kind &&\n previous.sourceNodeId === sourceNodeId &&\n previous.targetNodeId === targetNodeId &&\n previous.scope?._tag === \"release\" &&\n previous.scope.releaseId === candidate.releaseId &&\n previous.lifecycle._tag === candidate.lifecycle &&\n (claimId === null || previous.evidenceClaimIds.includes(claimId))\n\nconst protectedByDecision = (previous: DeliveryRelationship | null): boolean =>\n previous?.lifecycle._tag === \"governed\" ||\n previous?.lifecycle._tag === \"verified\" ||\n previous?.lifecycle._tag === \"rejected\"\n\nconst materializeCandidate = Effect.fn(\"RelationshipInferenceMaterialization.materializeCandidate\")(function*<\n IdentityError\n>(\n persistence: PersistenceService,\n identity: StableIdentity<IdentityError>,\n scope: RelationshipInferenceMaterializationScope,\n settings: WorkspaceSettingsV1,\n candidate: RelationshipInferenceCandidate,\n entityById: ReadonlyMap<string, EntityRecord>\n): Effect.fn.Return<RelationshipInferenceMaterializationReceipt, IdentityError | PersistenceOperationFailure> {\n const relationshipId = yield* relationshipIdFor(identity, scope.workspaceId, candidate.identityKey)\n const previous = yield* readRelationship(persistence, scope.workspaceId, relationshipId)\n if (protectedByDecision(previous)) {\n return {\n evidenceClaimCount: 0,\n evidenceItemCount: 0,\n nodeCount: 0,\n relationshipCount: 0,\n skippedDueToBounds: false\n }\n }\n const source = yield* endpointNode(identity, scope, candidate.source)\n const target = yield* endpointNode(identity, scope, candidate.target)\n const evidenceEntity = candidate.evidenceEntityId === null\n ? null\n : (entityById.get(candidate.evidenceEntityId) ?? null)\n const evidence = evidenceEntity === null\n ? null\n : yield* evidenceFor(\n persistence,\n identity,\n scope,\n settings,\n candidate,\n source.nodeId,\n target.nodeId,\n evidenceEntity\n )\n const evidenceClaimId = evidence?.claim.evidenceClaimId ?? null\n // Evidence IDs are content-derived and evidence rows are immutable, so restoring a\n // relationship reuses the original retention metadata. The current evidenceDays\n // policy applies only to newly materialized evidence; M5.3 owns lifecycle sweeps.\n const reusesEvidence = evidenceClaimId !== null &&\n previous?.evidenceClaimIds.includes(evidenceClaimId) === true\n if (unchanged(previous, candidate, source.nodeId, target.nodeId, evidenceClaimId)) {\n return {\n evidenceClaimCount: 0,\n evidenceItemCount: 0,\n nodeCount: 0,\n relationshipCount: 0,\n skippedDueToBounds: false\n }\n }\n const nodes = []\n if (source.node !== null && !(yield* nodeExists(persistence, scope.workspaceId, source.nodeId))) {\n nodes.push(source.node)\n }\n if (target.node !== null && !(yield* nodeExists(persistence, scope.workspaceId, target.nodeId))) {\n nodes.push(target.node)\n }\n const confidence: DeliveryRelationship[\"confidence\"] = candidate.confidence === null\n ? { _tag: \"unknown\", rationale: \"No matching provider evidence is currently synchronized.\" }\n : { _tag: \"inferred\", ...candidate.confidence }\n const relationship: DeliveryRelationship = {\n workspaceId: scope.workspaceId,\n relationshipId,\n relationshipSchemaVersion: 1,\n revision: LedgerRevision.make((previous?.revision ?? 0) + 1),\n supersedesRevision: previous?.revision ?? null,\n kind: candidate.kind,\n sourceNodeId: source.nodeId,\n sourceNodeKind: candidate.source.kind,\n targetNodeId: target.nodeId,\n targetNodeKind: candidate.target.kind,\n scope: { _tag: \"release\", releaseId: candidate.releaseId },\n lifecycle: candidate.lifecycle === \"missing\"\n ? {\n _tag: \"missing\",\n effectiveAt: scope.committedAt,\n reason: \"No synchronized provider evidence currently resolves this required delivery link.\"\n }\n : { _tag: \"inferred\", effectiveAt: scope.committedAt },\n confidence,\n provenance: {\n _tag: \"rule\",\n ruleId: candidate.ruleId,\n ruleVersion: 1,\n rationale: candidate.confidence?.rationale ?? \"Required delivery link has no synchronized match.\"\n },\n recordedBy: { _tag: \"system\", component: COMPONENT },\n evidenceClaimIds: evidenceClaimId === null ? [] : [evidenceClaimId],\n recordedAt: scope.committedAt\n }\n const receipt = yield* writeGraph(persistence, scope.workspaceId, {\n entityProjections: [],\n nodes,\n evidenceItems: evidence === null || reusesEvidence ? [] : [evidence.item],\n evidenceClaims: evidence === null || reusesEvidence ? [] : [evidence.claim],\n relationships: [relationship]\n })\n return { ...receipt, skippedDueToBounds: false }\n})\n\nconst supersedeObsoleteGap = Effect.fn(\"RelationshipInferenceMaterialization.supersedeObsoleteGap\")(function*<\n IdentityError\n>(\n persistence: PersistenceService,\n identity: StableIdentity<IdentityError>,\n scope: RelationshipInferenceMaterializationScope,\n identityKey: string\n): Effect.fn.Return<number, IdentityError | PersistenceOperationFailure> {\n const relationshipId = yield* relationshipIdFor(identity, scope.workspaceId, identityKey)\n const previous = yield* readRelationship(persistence, scope.workspaceId, relationshipId)\n if (previous?.lifecycle._tag !== \"missing\") return 0\n const relationship: DeliveryRelationship = {\n ...previous,\n revision: LedgerRevision.make(previous.revision + 1),\n supersedesRevision: previous.revision,\n lifecycle: {\n _tag: \"superseded\",\n effectiveAt: scope.committedAt,\n reason: \"New synchronized evidence resolved the previously missing link.\"\n },\n recordedAt: scope.committedAt\n }\n return (yield* writeGraph(persistence, scope.workspaceId, {\n entityProjections: [],\n nodes: [],\n evidenceItems: [],\n evidenceClaims: [],\n relationships: [relationship]\n })).relationshipCount\n})\n\nconst supersedeObsoleteRelationship = Effect.fn(\"RelationshipInferenceMaterialization.supersedeObsoleteRelationship\")(\n function*(\n persistence: PersistenceService,\n scope: RelationshipInferenceMaterializationScope,\n relationshipId: RelationshipId,\n reason?: string\n ) {\n const previous = yield* readRelationship(persistence, scope.workspaceId, relationshipId)\n if (previous?.lifecycle._tag !== \"inferred\" && previous?.lifecycle._tag !== \"missing\") return 0\n const relationship: DeliveryRelationship = {\n ...previous,\n revision: LedgerRevision.make(previous.revision + 1),\n supersedesRevision: previous.revision,\n lifecycle: {\n _tag: \"superseded\",\n effectiveAt: scope.committedAt,\n reason: reason ?? (previous.lifecycle._tag === \"missing\"\n ? \"The entity is no longer in the release scope that required this missing link.\"\n : \"Current synchronized metadata no longer supports this inferred link.\")\n },\n recordedAt: scope.committedAt\n }\n return (yield* writeGraph(persistence, scope.workspaceId, {\n entityProjections: [],\n nodes: [],\n evidenceItems: [],\n evidenceClaims: [],\n relationships: [relationship]\n })).relationshipCount\n }\n)\n\nconst emptyReceipt = (skippedDueToBounds: boolean): RelationshipInferenceMaterializationReceipt => ({\n evidenceClaimCount: 0,\n evidenceItemCount: 0,\n nodeCount: 0,\n relationshipCount: 0,\n skippedDueToBounds\n})\n\nconst retireInferenceForReleases = Effect.fn(\n \"RelationshipInferenceMaterialization.retireInferenceForReleases\"\n)(function*(\n persistence: PersistenceService,\n scope: RelationshipInferenceMaterializationScope,\n releaseIds: ReadonlyArray<RelationshipInferenceRelease[\"releaseId\"]> | null,\n reason: string,\n skippedDueToBounds = false\n) {\n const reads = yield* Effect.forEach(\n releaseIds ?? [null],\n (releaseId) =>\n persistence.deliveryGraph.read(scope.workspaceId, {\n _tag: \"componentRelationships\",\n releaseId,\n component: COMPONENT,\n limit: MAXIMUM_INFERENCE_RELATIONSHIPS\n })\n )\n if (\n reads.some((read) => read._tag !== \"componentRelationships\" || read.value.truncated)\n ) return emptyReceipt(true)\n const relationshipIds = new Set(\n reads.flatMap((read) =>\n read._tag === \"componentRelationships\"\n ? read.value.relationships.map(({ relationshipId }) => relationshipId)\n : []\n )\n )\n let relationshipCount = 0\n for (const relationshipId of relationshipIds) {\n relationshipCount += yield* supersedeObsoleteRelationship(\n persistence,\n scope,\n relationshipId,\n reason\n )\n }\n return { ...emptyReceipt(skippedDueToBounds), relationshipCount }\n})\n\nconst retireInferenceAtEntityBound = Effect.fn(\n \"RelationshipInferenceMaterialization.retireInferenceAtEntityBound\"\n)(function*(\n persistence: PersistenceService,\n scope: RelationshipInferenceMaterializationScope\n) {\n return yield* retireInferenceForReleases(\n persistence,\n scope,\n null,\n \"Inference inputs exceeded the bounded workspace snapshot, so this relationship can no longer be proven.\",\n true\n )\n})\n\n/** Persist current rule candidates after a normalized page has committed. */\nexport const materializeRelationshipInference = Effect.fn(\"RelationshipInferenceMaterialization.reconcile\")(function*<\n IdentityError\n>(\n persistence: PersistenceService,\n identity: StableIdentity<IdentityError>,\n scope: RelationshipInferenceMaterializationScope,\n settings: WorkspaceSettingsV1\n): Effect.fn.Return<RelationshipInferenceMaterializationReceipt, IdentityError | PersistenceOperationFailure> {\n if (!settings.inference.enabled) {\n return yield* retireInferenceForReleases(\n persistence,\n scope,\n null,\n \"Workspace relationship inference is disabled.\"\n )\n }\n const projectionResult = yield* persistence.deliveryGraph.read(scope.workspaceId, {\n _tag: \"workspaceEntityProjections\",\n owner: null,\n query: null,\n service: null,\n status: null,\n type: null,\n limit: MAXIMUM_INFERENCE_ENTITIES\n })\n if (projectionResult._tag !== \"workspaceEntityProjections\") return emptyReceipt(true)\n if (projectionResult.value.truncated) return yield* retireInferenceAtEntityBound(persistence, scope)\n const records = yield* Effect.forEach(\n projectionResult.value.items,\n ({ projection }) => persistence.entities.get(scope.workspaceId, projection.entityId),\n { concurrency: 10 }\n )\n const entityById = new Map(records.map((record) => [record.entityId, record]))\n const entities: Array<RelationshipInferenceEntity> = []\n for (const item of projectionResult.value.items) {\n const entity = entityById.get(item.projection.entityId)\n if (entity === undefined) continue\n entities.push({\n projection: item.projection,\n releaseIds: item.releaseIds,\n nodeId: GraphNodeId.make(yield* identity(entityNodeIdentity(scope.workspaceId, entity)))\n })\n }\n const releases = yield* persistence.releases.list(scope.workspaceId, MAXIMUM_INFERENCE_RELEASES + 1)\n if (releases.length > MAXIMUM_INFERENCE_RELEASES) {\n return yield* retireInferenceAtEntityBound(persistence, scope)\n }\n const inferenceReleases: Array<{\n readonly inferenceRelease: RelationshipInferenceRelease\n readonly node: DeliveryNode | null\n }> = []\n for (const { release } of releases) {\n const candidates = yield* Effect.forEach(release.sourceRevisions, (source) =>\n Effect.gen(function*() {\n const nodeId = GraphNodeId.make(\n yield* identity(\n releaseNodeIdentity(\n scope.workspaceId,\n source.pluginConnectionId,\n source.providerId,\n source.vendorImmutableId\n )\n )\n )\n return { exists: yield* nodeExists(persistence, scope.workspaceId, nodeId), nodeId }\n }))\n const selected = candidates.find(({ exists }) => exists) ?? candidates[0]\n if (selected === undefined) continue\n inferenceReleases.push({\n inferenceRelease: { nodeId: selected.nodeId, releaseId: release.id, version: release.version },\n node: selected.exists\n ? null\n : {\n workspaceId: scope.workspaceId,\n nodeId: selected.nodeId,\n endpointKind: \"release\",\n resolution: { _tag: \"resolved\", target: { _tag: \"release\", releaseId: release.id } },\n createdAt: scope.committedAt\n }\n })\n }\n const releaseIds = releases.map(({ release }) => release.id)\n const slices = yield* Effect.forEach(releaseIds, (releaseId) =>\n persistence.deliveryGraph.read(scope.workspaceId, {\n _tag: \"releaseSlice\",\n releaseId,\n environmentId: null,\n limit: MAXIMUM_INFERENCE_ENTITIES\n }))\n const truncatedReleaseIds = slices.flatMap((slice, index) => {\n const releaseId = releaseIds[index]\n return releaseId !== undefined && (slice._tag !== \"releaseSlice\" || slice.value.truncated) ? [releaseId] : []\n })\n if (truncatedReleaseIds.length > 0) {\n return yield* retireInferenceForReleases(\n persistence,\n scope,\n truncatedReleaseIds,\n \"The bounded release relationship snapshot was incomplete, so this inference can no longer be proven.\",\n true\n )\n }\n const relationships = slices.flatMap((slice) => (slice._tag === \"releaseSlice\" ? slice.value.relationships : []))\n const inferenceInput = {\n entities,\n minimumConfidenceScore: settings.inference.minimumConfidencePercent / 100,\n releases: inferenceReleases.map(({ inferenceRelease }) => inferenceRelease),\n relationships\n }\n const initialInference = deriveRelationshipInference(inferenceInput)\n const rejectedCandidateIdentityKeys = new Set<string>()\n for (const candidate of initialInference.candidates) {\n if (candidate.lifecycle !== \"inferred\") continue\n const relationshipId = yield* relationshipIdFor(identity, scope.workspaceId, candidate.identityKey)\n const previous = yield* readRelationship(persistence, scope.workspaceId, relationshipId)\n if (previous?.lifecycle._tag === \"rejected\") rejectedCandidateIdentityKeys.add(candidate.identityKey)\n }\n const inference = rejectedCandidateIdentityKeys.size === 0\n ? initialInference\n : deriveRelationshipInference({ ...inferenceInput, rejectedCandidateIdentityKeys })\n if (inference.truncated) return yield* retireInferenceAtEntityBound(persistence, scope)\n let receipt = emptyReceipt(false)\n const missingReleaseNodes = inferenceReleases.flatMap(({ node }) => node === null ? [] : [node])\n if (missingReleaseNodes.length > 0) {\n const current = yield* writeGraph(persistence, scope.workspaceId, {\n entityProjections: [],\n nodes: missingReleaseNodes,\n evidenceItems: [],\n evidenceClaims: [],\n relationships: []\n })\n receipt = { ...receipt, nodeCount: current.nodeCount }\n }\n for (const candidate of inference.candidates) {\n const current = yield* materializeCandidate(\n persistence,\n identity,\n scope,\n settings,\n candidate,\n entityById\n )\n receipt = {\n evidenceClaimCount: receipt.evidenceClaimCount + current.evidenceClaimCount,\n evidenceItemCount: receipt.evidenceItemCount + current.evidenceItemCount,\n nodeCount: receipt.nodeCount + current.nodeCount,\n relationshipCount: receipt.relationshipCount + current.relationshipCount,\n skippedDueToBounds: false\n }\n }\n for (const identityKey of inference.obsoleteGapIdentityKeys) {\n receipt = {\n ...receipt,\n relationshipCount: receipt.relationshipCount +\n (yield* supersedeObsoleteGap(persistence, identity, scope, identityKey))\n }\n }\n for (const relationshipId of inference.obsoleteRelationshipIds) {\n receipt = {\n ...receipt,\n relationshipCount: receipt.relationshipCount +\n (yield* supersedeObsoleteRelationship(persistence, scope, relationshipId))\n }\n }\n return receipt\n})\n\n/** Derive the stable UUID namespace used by relationship-inference graph records. */\nexport const stableRelationshipInferenceIdentity = Effect.fn(\n \"RelationshipInferenceMaterialization.stableIdentity\"\n)(function*(\n cryptoService: Crypto.Crypto,\n identity: string\n) {\n const bytes = yield* Effect.fromResult(\n Encoding.decodeBase64(Encoding.encodeBase64(identity))\n ).pipe(\n Effect.mapError(() =>\n new PersistenceOperationError({\n operation: \"relationship-inference.identity-encoding\"\n })\n )\n )\n const digest = yield* cryptoService.digest(\"SHA-256\", bytes).pipe(\n Effect.mapError(() =>\n new PersistenceOperationError({\n operation: \"relationship-inference.identity-digest\"\n })\n )\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\n/**\n * Re-run the complete bounded inference fold when workspace policy changes.\n * A bounded read must either produce the graph-equivalent new state or fail so\n * the surrounding settings transaction rolls back atomically.\n */\nexport const reconcileRelationshipInferencePolicy = Effect.fn(\n \"RelationshipInferenceMaterialization.reconcilePolicy\"\n)(function*(\n persistence: PersistenceService,\n cryptoService: Crypto.Crypto,\n workspaceId: WorkspaceId,\n committedAt: UtcTimestamp,\n settings: WorkspaceSettingsV1\n) {\n const receipt = yield* materializeRelationshipInference(\n persistence,\n (identity) => stableRelationshipInferenceIdentity(cryptoService, identity),\n {\n workspaceId,\n committedAt,\n streamKey: PluginStreamKey.make(\"workspace-settings\"),\n successfulHealth: { _tag: \"healthy\", checkedAt: committedAt }\n },\n settings\n )\n if (receipt.skippedDueToBounds) {\n return yield* new PersistenceOperationError({\n operation: \"relationship-inference.reconcile-policy-bounds\"\n })\n }\n return receipt\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,IAAa,aAAa,OAAO,OAAO,MACtC,OAAO,UAAU,kBAA2B,EAC1C,UAAU,0CACZ,CAAC,CACH,CAAC,CAAC,KAAK,OAAO,MAAM,YAAY,CAAC;;;ACJjC,IAAM,kBAAkB,OAAO,OAAO,MACpC,OAAO,UAAU,GACjB,OAAO,WAAW,GAClB,OAAO,YAAY,GAAG,CACxB;;AAGA,IAAa,mBAAb,cAAsC,OAAO,iBAAmC,CAAC,CAAC,oBAAoB;CACpG,WAAW;CACX,QAAQ,OAAO,SAAS;EAAC;EAAkB;EAAgB;EAAW;CAAc,CAAC;AACvF,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa,mBAAb,cAAsC,OAAO,iBAAmC,CAAC,CAAC,oBAAoB;CACpG,UAAU,OAAO,SAAS;EAAC;EAAQ;EAAY;C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,UAAU;CACV,WAAW;CACX,WAAW;AACb,CAAC;;AAMD,IAAa,wBAAwB,SAAO,OAAO;CACjD,SAAS;CACT,UAAU;AACZ,CAAC;;AAMD,IAAa,oBAAoB;;AAMjC,IAAa,0BAA0B;;AAMvC,IAAa,sBAAsB,SAAO,OAAO;CAC/C,aAAa;CACb,QAAQ;CACR,cAAc;CACd,UAAU,SAAO,MAAM,CACrB,SAAO,OAAO,MAAM,SAAO,UAAU,GAAG,SAAO,WAAW,GAAG,SAAO,YAAY,GAAG,CAAC,GACpF,SAAO,IACT,CAAC;CACD,YAAY,SAAO,OAAO,MAAM,SAAO,MAAM,GAAG,SAAO,uBAAuB,CAAC,CAAC;CAChF,WAAW;CACX,gBAAgB,SAAO,MAAM,CAAC,cAAc,SAAO,IAAI,CAAC;AAC1D,CAAC;;AAMD,IAAa,uBAAuB,SAAO,SAAS;CAClD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAMD,IAAa,uBAAuB,SAAO,SAAS;CAClD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAMD,IAAa,8BAA8B,SAAO,SAAS;CACzD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;C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