@tearleads/client-sdk 0.1.225 → 0.1.230

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (375) hide show
  1. package/Tearleads.js +1 -1
  2. package/Tearleads.js.map +1 -1
  3. package/client/containerContents/documentDiscovery.js +4 -1
  4. package/client/containerContents/documentDiscovery.js.map +1 -1
  5. package/client/containerContents/index.d.ts +1 -1
  6. package/client/containerContents/index.js +4 -2
  7. package/client/containerContents/index.js.map +1 -1
  8. package/client/deviceFirst/index.js +1 -1
  9. package/client/deviceFirst/index.js.map +1 -1
  10. package/client/documents/index.js +6 -2
  11. package/client/documents/index.js.map +1 -1
  12. package/client/identity/index.js +1 -1
  13. package/client/identity/index.js.map +1 -1
  14. package/client/identity/userIdentities.d.ts +1 -1
  15. package/client/identity/userIdentities.js +1 -1
  16. package/client/identity/userIdentities.js.map +1 -1
  17. package/client/index.d.ts +2 -0
  18. package/client/index.js +2 -0
  19. package/client/index.js.map +1 -1
  20. package/client/organizations/index.js +1 -1
  21. package/client/organizations/index.js.map +1 -1
  22. package/client/organizations/organizationMemberships.d.ts +1 -1
  23. package/client/organizations/organizationMemberships.js +1 -1
  24. package/client/organizations/organizationMemberships.js.map +1 -1
  25. package/client/organizations/principalContainerMutations.js.map +1 -1
  26. package/client/organizations/principalMutations.js +1 -1
  27. package/client/organizations/principalMutations.js.map +1 -1
  28. package/client/organizations/recipientAdmission.d.ts +1 -1
  29. package/client/organizations/recipientAdmission.js +2 -2
  30. package/client/organizations/recipientAdmission.js.map +1 -1
  31. package/client/organizations/rosterAdmissionEvidence.js +1 -1
  32. package/client/organizations/rosterAdmissionEvidence.js.map +1 -1
  33. package/client/runtime/apiVersion.js +1 -1
  34. package/client/runtime/apiVersion.js.map +1 -1
  35. package/client/runtime/containerContentsRuntime.d.ts +8 -0
  36. package/client/runtime/containerContentsRuntime.js +14 -0
  37. package/client/runtime/containerContentsRuntime.js.map +1 -0
  38. package/client/runtime/database.js +1 -1
  39. package/client/runtime/database.js.map +1 -1
  40. package/client/runtime/documentsRuntime.d.ts +5 -0
  41. package/client/runtime/documentsRuntime.js +10 -0
  42. package/client/runtime/documentsRuntime.js.map +1 -0
  43. package/client/runtime/events.js +1 -1
  44. package/client/runtime/events.js.map +1 -1
  45. package/client/runtime/network.js +1 -1
  46. package/client/runtime/network.js.map +1 -1
  47. package/client/runtime/runtimeIdentityResolution.js +1 -1
  48. package/client/runtime/runtimeIdentityResolution.js.map +1 -1
  49. package/client/runtime/syncBillingGate.js +1 -1
  50. package/client/runtime/syncBillingGate.js.map +1 -1
  51. package/client/runtime/workflowRuntime.d.ts +5 -2
  52. package/client/runtime/workflowRuntime.js +6 -2
  53. package/client/runtime/workflowRuntime.js.map +1 -1
  54. package/client/securityIncidents/index.d.ts +1 -1
  55. package/client/securityIncidents/index.js +2 -2
  56. package/client/securityIncidents/index.js.map +1 -1
  57. package/client/session/index.js +1 -1
  58. package/client/session/index.js.map +1 -1
  59. package/client/session/sessionLoginRefusal.js +1 -1
  60. package/client/session/sessionLoginRefusal.js.map +1 -1
  61. package/client/session/sessionRootAuthority.js +1 -1
  62. package/client/session/sessionRootAuthority.js.map +1 -1
  63. package/data/containers/shared/authorAccess.d.ts +1 -1
  64. package/data/containers/shared/authorAccess.js.map +1 -1
  65. package/data/containers/shared/principalPolicies.js.map +1 -1
  66. package/data/containers/shared/types.d.ts +1 -1
  67. package/data/containers/shared/types.js.map +1 -1
  68. package/data/documents/shared/projection/freshProjectionRetry.js +1 -1
  69. package/data/documents/shared/projection/freshProjectionRetry.js.map +1 -1
  70. package/data/keyingProjectionVerification/checkpoints/accessManifestCheckpointEnforcement.js.map +1 -1
  71. package/data/keyingProjectionVerification/checkpoints/checkpointContext.d.ts +1 -1
  72. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js +1 -1
  73. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
  74. package/data/keyingProjectionVerification/checkpoints/heldContainerHeads.js.map +1 -0
  75. package/data/keyingProjectionVerification/container/containerProjectionVerification.d.ts +1 -1
  76. package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -1
  77. package/data/keyingProjectionVerification/documentPurge/documentPurgePrincipalEvidence.js +1 -1
  78. package/data/keyingProjectionVerification/documentPurge/documentPurgePrincipalEvidence.js.map +1 -1
  79. package/data/keyingProjectionVerification/error.js +1 -57
  80. package/data/keyingProjectionVerification/error.js.map +1 -1
  81. package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.js +1 -1
  82. package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.js.map +1 -1
  83. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +2 -2
  84. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
  85. package/data/keyingProjectionVerification/principalPolicy/principalPolicySigners.js +2 -2
  86. package/data/keyingProjectionVerification/principalPolicy/principalPolicySigners.js.map +1 -1
  87. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.d.ts +1 -1
  88. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +4 -4
  89. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
  90. package/data/keyingProjectionVerification/types.d.ts +1 -1
  91. package/data/keyingProjectionVerification/types.js.map +1 -1
  92. package/data/persistence/container-contents/documentContainerProjectionPersistence.d.ts +6 -2
  93. package/data/persistence/container-contents/documentContainerProjectionPersistence.js +10 -1
  94. package/data/persistence/container-contents/documentContainerProjectionPersistence.js.map +1 -1
  95. package/data/persistence/documents/documentDeletionPort.d.ts +28 -0
  96. package/data/persistence/documents/documentDeletionPort.js +2 -0
  97. package/data/persistence/documents/documentDeletionPort.js.map +1 -0
  98. package/data/persistence/documents/documentsPersistence.d.ts +1 -0
  99. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  100. package/data/persistence/documents/internal/documentDeletionPersistence.js +7 -7
  101. package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
  102. package/data/persistence/documents/types.d.ts +2 -15
  103. package/data/persistence/documents/types.js.map +1 -1
  104. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js +1 -1
  105. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js.map +1 -1
  106. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js +1 -1
  107. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -1
  108. package/data/persistence/keyingCheckpoints/organizationReplacementCheckpointPersistence.js +1 -1
  109. package/data/persistence/keyingCheckpoints/organizationReplacementCheckpointPersistence.js.map +1 -1
  110. package/data/persistence/organizationFounderPersistence.js +1 -1
  111. package/data/persistence/organizationFounderPersistence.js.map +1 -1
  112. package/data/persistence/principalCurrentAcknowledgementPersistence.js +1 -1
  113. package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -1
  114. package/data/persistence/principalPolicy/heldPrincipalState.js +1 -1
  115. package/data/persistence/principalPolicy/heldPrincipalState.js.map +1 -1
  116. package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js +1 -1
  117. package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js.map +1 -1
  118. package/data/persistence/principalPolicy/principalPolicyBundleRepository.js.map +1 -1
  119. package/data/persistence/principalPolicy/principalPolicyReferenceCheckpoint.js +1 -1
  120. package/data/persistence/principalPolicy/principalPolicyReferenceCheckpoint.js.map +1 -1
  121. package/data/persistence/principalPolicy/principalPolicyReferenceIndexPersistence.js +1 -1
  122. package/data/persistence/principalPolicy/principalPolicyReferenceIndexPersistence.js.map +1 -1
  123. package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js +1 -1
  124. package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js.map +1 -1
  125. package/data/principals/organizationGroupRoles.js +1 -1
  126. package/data/principals/organizationGroupRoles.js.map +1 -1
  127. package/data/shared/securityIncidents.d.ts +18 -1
  128. package/data/shared/securityIncidents.js +58 -1
  129. package/data/shared/securityIncidents.js.map +1 -1
  130. package/index.d.ts +5 -5
  131. package/index.js +3 -3
  132. package/index.js.map +1 -1
  133. package/package.json +1 -1
  134. package/stores/container-contents/hydration/backgroundHydration.js +1 -1
  135. package/stores/container-contents/hydration/backgroundHydration.js.map +1 -1
  136. package/stores/container-contents/operations/reportShareFailure.js +1 -1
  137. package/stores/container-contents/operations/reportShareFailure.js.map +1 -1
  138. package/stores/container-contents/operations/shareOperations.js +1 -1
  139. package/stores/container-contents/operations/shareOperations.js.map +1 -1
  140. package/stores/container-contents/systemContainers/systemContainerHydration.js +1 -1
  141. package/stores/container-contents/systemContainers/systemContainerHydration.js.map +1 -1
  142. package/stores/documents/documentStore/attachmentUpload/attachmentUploadAttempt.js +1 -1
  143. package/stores/documents/documentStore/attachmentUpload/attachmentUploadAttempt.js.map +1 -1
  144. package/stores/documents/documentStore/persistence.js +1 -0
  145. package/stores/documents/documentStore/persistence.js.map +1 -1
  146. package/stores/documents/documentStore/sync/index.js +1 -1
  147. package/stores/documents/documentStore/sync/index.js.map +1 -1
  148. package/stores/documents/documentStore/sync/syncRequest.js +1 -0
  149. package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
  150. package/workflows/blobs/hydration/hydrationResults.js +2 -1
  151. package/workflows/blobs/hydration/hydrationResults.js.map +1 -1
  152. package/workflows/blobs/verification/attachmentDecryptor.js +1 -1
  153. package/workflows/blobs/verification/attachmentDecryptor.js.map +1 -1
  154. package/workflows/container-contents/container-state/create/createAdoption.js +1 -1
  155. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  156. package/workflows/container-contents/container-state/create/createIntentSync.js +1 -1
  157. package/workflows/container-contents/container-state/create/createIntentSync.js.map +1 -1
  158. package/workflows/container-contents/container-state/move/moveIntentSync.js +1 -1
  159. package/workflows/container-contents/container-state/move/moveIntentSync.js.map +1 -1
  160. package/workflows/container-contents/container-state/organizationHost.d.ts +54 -0
  161. package/workflows/container-contents/container-state/organizationHost.js +2 -0
  162. package/workflows/container-contents/container-state/organizationHost.js.map +1 -0
  163. package/workflows/container-contents/container-state/purge/purgeTreeScope.js +1 -1
  164. package/workflows/container-contents/container-state/purge/purgeTreeScope.js.map +1 -1
  165. package/workflows/container-contents/container-state/remote.js +2 -4
  166. package/workflows/container-contents/container-state/remote.js.map +1 -1
  167. package/workflows/container-contents/container-state/share/groupGrantVerification.js +1 -2
  168. package/workflows/container-contents/container-state/share/groupGrantVerification.js.map +1 -1
  169. package/workflows/container-contents/container-state/share/groupShareEpoch.js +1 -2
  170. package/workflows/container-contents/container-state/share/groupShareEpoch.js.map +1 -1
  171. package/workflows/container-contents/container-state/types.js.map +1 -1
  172. package/workflows/container-contents/documentLinks/index.js +1 -1
  173. package/workflows/container-contents/documentLinks/index.js.map +1 -1
  174. package/workflows/container-contents/documentMove/documentMoveIntentSync.js +1 -1
  175. package/workflows/container-contents/documentMove/documentMoveIntentSync.js.map +1 -1
  176. package/workflows/container-contents/index.d.ts +1 -0
  177. package/workflows/container-contents/index.js.map +1 -1
  178. package/workflows/container-contents/info/documentInfo.d.ts +1 -1
  179. package/workflows/container-contents/info/documentInfo.js +1 -1
  180. package/workflows/container-contents/info/documentInfo.js.map +1 -1
  181. package/workflows/container-contents/metadata/metadataSyncErrors.js +1 -1
  182. package/workflows/container-contents/metadata/metadataSyncErrors.js.map +1 -1
  183. package/workflows/container-contents/remoteHydration/destination/destinationRootReload.js +1 -2
  184. package/workflows/container-contents/remoteHydration/destination/destinationRootReload.js.map +1 -1
  185. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +3 -4
  186. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
  187. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +1 -1
  188. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
  189. package/workflows/container-contents/remoteHydration/types.d.ts +1 -1
  190. package/workflows/container-contents/remoteHydration/types.js.map +1 -1
  191. package/workflows/container-contents/runtime.d.ts +5 -0
  192. package/workflows/container-contents/runtime.js +3 -0
  193. package/workflows/container-contents/runtime.js.map +1 -1
  194. package/workflows/container-contents/syncPause/documentRemoval.js +2 -0
  195. package/workflows/container-contents/syncPause/documentRemoval.js.map +1 -1
  196. package/workflows/container-contents/tombstones/documentPurge.js +5 -2
  197. package/workflows/container-contents/tombstones/documentPurge.js.map +1 -1
  198. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +1 -1
  199. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  200. package/workflows/containers/child/create/index.js.map +1 -1
  201. package/workflows/containers/child/move/moveRequest.js.map +1 -1
  202. package/workflows/containers/child/move/moveWraps.js.map +1 -1
  203. package/workflows/containers/child/mutationRequestCore.js.map +1 -1
  204. package/workflows/containers/child/mutationSubmit.d.ts +1 -1
  205. package/workflows/containers/child/mutationSubmit.js +1 -1
  206. package/workflows/containers/child/mutationSubmit.js.map +1 -1
  207. package/workflows/containers/child/recite.js +1 -1
  208. package/workflows/containers/child/recite.js.map +1 -1
  209. package/workflows/containers/child/recitePlan.js.map +1 -1
  210. package/workflows/containers/child/rekey/carriedDescendantRekeys.d.ts +1 -1
  211. package/workflows/containers/child/rekey/carriedDescendantRekeys.js.map +1 -1
  212. package/workflows/containers/child/rekey/index.d.ts +1 -1
  213. package/workflows/containers/child/rekey/index.js.map +1 -1
  214. package/workflows/containers/child/revoke.d.ts +1 -1
  215. package/workflows/containers/child/revoke.js.map +1 -1
  216. package/workflows/containers/child/rotation/replacementPrincipalPolicyReferences.js.map +1 -1
  217. package/workflows/containers/child/rotation/rotationPrincipalPolicies.js.map +1 -1
  218. package/workflows/containers/child/rotation/rotationWraps.js.map +1 -1
  219. package/workflows/containers/child/share/sharePlanCore.d.ts +1 -1
  220. package/workflows/containers/child/share/sharePlanCore.js.map +1 -1
  221. package/workflows/containers/rematerialization/acknowledgePrincipalContainerRematerialization.js +1 -1
  222. package/workflows/containers/rematerialization/acknowledgePrincipalContainerRematerialization.js.map +1 -1
  223. package/workflows/containers/rematerialization/authoredPrincipalPolicyWarmer.js +1 -1
  224. package/workflows/containers/rematerialization/authoredPrincipalPolicyWarmer.js.map +1 -1
  225. package/workflows/containers/rematerialization/principalContainerRematerializationPlanning.js.map +1 -1
  226. package/workflows/containers/rematerialization/principalContainerRematerializationTargets.js.map +1 -1
  227. package/workflows/documents/documentMutationCommit.d.ts +2 -1
  228. package/workflows/documents/documentMutationCommit.js +1 -0
  229. package/workflows/documents/documentMutationCommit.js.map +1 -1
  230. package/workflows/documents/documentPersistGuards.js +2 -1
  231. package/workflows/documents/documentPersistGuards.js.map +1 -1
  232. package/workflows/documents/linkSet/linkSetAuthority.js.map +1 -1
  233. package/workflows/documents/purge/persistedDocumentRemoval.d.ts +2 -1
  234. package/workflows/documents/purge/persistedDocumentRemoval.js +2 -2
  235. package/workflows/documents/purge/persistedDocumentRemoval.js.map +1 -1
  236. package/workflows/documents/runtime.d.ts +5 -0
  237. package/workflows/documents/runtime.js +1 -0
  238. package/workflows/documents/runtime.js.map +1 -1
  239. package/workflows/documents/sync/syncSubmittedResult.js +1 -1
  240. package/workflows/documents/sync/syncSubmittedResult.js.map +1 -1
  241. package/workflows/documents/syncPlan/syncContentKeys.js +1 -1
  242. package/workflows/documents/syncPlan/syncContentKeys.js.map +1 -1
  243. package/workflows/organizations/containerContentsHost.js +14 -0
  244. package/workflows/organizations/containerContentsHost.js.map +1 -0
  245. package/workflows/organizations/currentOrganizationAuthority.d.ts +1 -1
  246. package/workflows/organizations/currentOrganizationAuthority.js +1 -1
  247. package/workflows/organizations/currentOrganizationAuthority.js.map +1 -1
  248. package/workflows/organizations/groupMetadata/currentGroupMetadataAuthority.js +1 -1
  249. package/workflows/organizations/groupMetadata/currentGroupMetadataAuthority.js.map +1 -1
  250. package/workflows/organizations/groupMetadata/groupMetadataBinding.js.map +1 -1
  251. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js +2 -2
  252. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js.map +1 -1
  253. package/workflows/organizations/groupMetadata/groupMetadataRootBinding.js +2 -2
  254. package/workflows/organizations/groupMetadata/groupMetadataRootBinding.js.map +1 -1
  255. package/workflows/organizations/groupNames/groupNameUniqueness.js +2 -2
  256. package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -1
  257. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js +2 -2
  258. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js.map +1 -1
  259. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js +1 -1
  260. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js.map +1 -1
  261. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js +1 -1
  262. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -1
  263. package/workflows/organizations/groupPolicy/groupPolicyRequests.js +1 -1
  264. package/workflows/organizations/groupPolicy/groupPolicyRequests.js.map +1 -1
  265. package/workflows/organizations/groupPolicy/groupPolicyVerification.js +1 -1
  266. package/workflows/organizations/groupPolicy/groupPolicyVerification.js.map +1 -1
  267. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js +1 -1
  268. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js.map +1 -1
  269. package/workflows/organizations/groupShare/sharePrincipalPolicy.js +2 -2
  270. package/workflows/organizations/groupShare/sharePrincipalPolicy.js.map +1 -1
  271. package/workflows/organizations/groups/createCurrentOrganizationGroup.js +1 -1
  272. package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
  273. package/workflows/organizations/groups/organizationGroupDirectory.js +1 -1
  274. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  275. package/workflows/organizations/memberships/leaveRequestMembersEvidence.js +1 -1
  276. package/workflows/organizations/memberships/leaveRequestMembersEvidence.js.map +1 -1
  277. package/workflows/organizations/policyHistory/loadPolicyHistoryDetails.js +1 -1
  278. package/workflows/organizations/policyHistory/loadPolicyHistoryDetails.js.map +1 -1
  279. package/workflows/organizations/policyHistory/organizationPolicyHistoryDetails.js.map +1 -1
  280. package/workflows/organizations/policyHistory/organizationPolicyHistoryVerification.js +1 -1
  281. package/workflows/organizations/policyHistory/organizationPolicyHistoryVerification.js.map +1 -1
  282. package/workflows/organizations/principalMutations/acknowledgedDirectoryBindings.js +1 -1
  283. package/workflows/organizations/principalMutations/acknowledgedDirectoryBindings.js.map +1 -1
  284. package/workflows/organizations/principalMutations/currentOrganizationMutationAuthority.js +1 -1
  285. package/workflows/organizations/principalMutations/currentOrganizationMutationAuthority.js.map +1 -1
  286. package/workflows/organizations/principalMutations/currentOrganizationMutationRetention.js +1 -1
  287. package/workflows/organizations/principalMutations/currentOrganizationMutationRetention.js.map +1 -1
  288. package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js +1 -1
  289. package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js.map +1 -1
  290. package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js +1 -1
  291. package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js.map +1 -1
  292. package/workflows/organizations/principalPolicy/principalPolicyRecipients.js +1 -1
  293. package/workflows/organizations/principalPolicy/principalPolicyRecipients.js.map +1 -1
  294. package/workflows/organizations/principalPolicy/principalPolicyRequest.js +1 -1
  295. package/workflows/organizations/principalPolicy/principalPolicyRequest.js.map +1 -1
  296. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js +2 -2
  297. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js.map +1 -1
  298. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js +1 -1
  299. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js.map +1 -1
  300. package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js +1 -1
  301. package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js.map +1 -1
  302. package/workflows/principals/externalAdminPolicy.d.ts +1 -1
  303. package/workflows/principals/externalAdminPolicy.js +2 -2
  304. package/workflows/principals/externalAdminPolicy.js.map +1 -1
  305. package/workflows/principals/historyRecovery/principalHistoryRecoveryAuthority.js +1 -1
  306. package/workflows/principals/historyRecovery/principalHistoryRecoveryAuthority.js.map +1 -1
  307. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js +1 -1
  308. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js.map +1 -1
  309. package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js +1 -1
  310. package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js.map +1 -1
  311. package/workflows/principals/historyRecovery/recoverScopedPrincipalPolicyHistory.js +1 -1
  312. package/workflows/principals/historyRecovery/recoverScopedPrincipalPolicyHistory.js.map +1 -1
  313. package/workflows/principals/policyCache/index.d.ts +1 -1
  314. package/workflows/principals/policyCache/index.js +3 -2
  315. package/workflows/principals/policyCache/index.js.map +1 -1
  316. package/workflows/principals/policyCache/principalPolicyCacheValidation.js +1 -1
  317. package/workflows/principals/policyCache/principalPolicyCacheValidation.js.map +1 -1
  318. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +2 -2
  319. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
  320. package/workflows/principals/policyVerification.js +1 -1
  321. package/workflows/principals/policyVerification.js.map +1 -1
  322. package/workflows/principals/principalPolicyService.js +1 -1
  323. package/workflows/principals/principalPolicyService.js.map +1 -1
  324. package/workflows/principals/publicHistory/publicPrincipalHistoryAuthority.js +1 -1
  325. package/workflows/principals/publicHistory/publicPrincipalHistoryAuthority.js.map +1 -1
  326. package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js +1 -1
  327. package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js.map +1 -1
  328. package/workflows/principals/publicHistory/publicProjectionDirectory.js +1 -1
  329. package/workflows/principals/publicHistory/publicProjectionDirectory.js.map +1 -1
  330. package/workflows/principals/publicHistory/publicProjectionPrincipal.js +1 -1
  331. package/workflows/principals/publicHistory/publicProjectionPrincipal.js.map +1 -1
  332. package/workflows/principals/publicHistory/recoverProjectionPolicyHistory.js +1 -1
  333. package/workflows/principals/publicHistory/recoverProjectionPolicyHistory.js.map +1 -1
  334. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js +2 -2
  335. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js.map +1 -1
  336. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js +1 -1
  337. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js.map +1 -1
  338. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.d.ts +1 -1
  339. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js +1 -1
  340. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js.map +1 -1
  341. package/workflows/principals/recoveryOperation/principalRecoveryLocalPreference.js +1 -1
  342. package/workflows/principals/recoveryOperation/principalRecoveryLocalPreference.js.map +1 -1
  343. package/workflows/principals/recoveryOperation/principalRecoveryMemo.js +1 -1
  344. package/workflows/principals/recoveryOperation/principalRecoveryMemo.js.map +1 -1
  345. package/workflows/principals/runtimePolicyRecovery.d.ts +1 -1
  346. package/workflows/principals/runtimePolicyRecovery.js +1 -1
  347. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  348. package/workflows/principals/runtimeProjectionPolicyRecovery.js +1 -1
  349. package/workflows/principals/runtimeProjectionPolicyRecovery.js.map +1 -1
  350. package/workflows/registration/organizationProvisioning.js +2 -2
  351. package/workflows/registration/organizationProvisioning.js.map +1 -1
  352. package/workflows/registration/persistRegistrationBootstrap.js +2 -0
  353. package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
  354. package/workflows/registration/provisionedPrincipalHistory.js +1 -1
  355. package/workflows/registration/provisionedPrincipalHistory.js.map +1 -1
  356. package/workflows/registration/registrationAccessHeadPersistence.js +1 -1
  357. package/workflows/registration/registrationAccessHeadPersistence.js.map +1 -1
  358. package/data/containers/shared/heldContainerHeads.js.map +0 -1
  359. /package/data/{containers/shared → keyingProjectionVerification/checkpoints}/heldContainerHeads.js +0 -0
  360. /package/data/persistence/{principalKeys → principalContracts}/principalGrantRetirementPersistence.js +0 -0
  361. /package/data/persistence/{principalKeys → principalContracts}/principalGrantRetirementPersistence.js.map +0 -0
  362. /package/data/{principals → principalContracts}/organizationAuthorityDescriptor.d.ts +0 -0
  363. /package/data/{principals → principalContracts}/organizationAuthorityDescriptor.js +0 -0
  364. /package/data/{principals → principalContracts}/organizationAuthorityDescriptor.js.map +0 -0
  365. /package/data/{principals → principalContracts}/principalIdentityCommitments.js +0 -0
  366. /package/data/{principals → principalContracts}/principalIdentityCommitments.js.map +0 -0
  367. /package/data/{principals → principalContracts}/principalPolicyAdminSigners.js +0 -0
  368. /package/data/{principals → principalContracts}/principalPolicyAdminSigners.js.map +0 -0
  369. /package/data/{principals → principalContracts}/principalPolicyEvidence.d.ts +0 -0
  370. /package/data/{principals → principalContracts}/principalPolicyEvidence.js +0 -0
  371. /package/data/{principals → principalContracts}/principalPolicyEvidence.js.map +0 -0
  372. /package/data/{principals → principalContracts}/principalPolicyStates.js +0 -0
  373. /package/data/{principals → principalContracts}/principalPolicyStates.js.map +0 -0
  374. /package/{client/runtime → data/shared}/listenerSet.js +0 -0
  375. /package/{client/runtime → data/shared}/listenerSet.js.map +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"documentDeletionPersistence.js","sourceRoot":"","sources":["documentDeletionPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,EACL,gCAAgC,EAChC,0BAA0B,EAC1B,6BAA6B,GAC9B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE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AAI,wBAAwB,CACzD,aAAa,CACd,CAAC,kBAAkB,CAAC;gBACnB,OAAO,EAAE,kBAAkB;gBAC3B,OAAO;aACR,CAAC,CAAC;YACH,IAAI,gBAAgB;gBAAE,OAAO,KAAK,CAAC;YACnC,IACE,kBAAkB;gBAClB,CAAC,MAAM,uBAAuB,CAAC;oBAC7B,UAAU,EAAE,kBAAkB;oBAC9B,OAAO;oBACP,EAAE;iBACH,CAAC,CAAC,EACH,CAAC;gBACD,OAAO,KAAK,CAAC;YACf,CAAC;YAED,MAAM,wBAAwB,CAAC;gBAC7B,kBAAkB,EAAE,kBAAkB;gBACtC,OAAO;gBACP,aAAa;gBACb,EAAE;aACH,CAAC,CAAC;YACH,MAAM,sBAAsB,CAAC,aAAa,CAAC,CAAC;YAC5C,OAAO,IAAI,CAAC;QACd,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, eq, ne } from \"drizzle-orm\";\nimport { DOCUMENTS_APP_KIND } from \"../../../documents/documentConstants\";\nimport {\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n documentPlacementIntentTables,\n} from \"../../../sqlite/schema\";\nimport {\n documentProjection,\n documentProjectionText,\n} from \"../../../sqlite/schema/documentProjectionSchema\";\nimport { documents } from \"../../../sqlite/schema/documentRecordSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../../sqlite/sqlSchema\";\nimport {\n deleteDocumentPlacementIntentsInTransaction,\n deleteDocumentPlacementRowsByDocumentIds,\n} from \"../../container-contents/documentContainerProjectionPersistence\";\nimport { DocumentRecordRepository } from \"../records\";\nimport type { StoredDocumentRecord } from \"../types\";\nimport { sameCanonicalDocumentSecurityIdentity } from \"./documentRecordIdentity\";\nimport { getDocumentScope } from \"./documentRows\";\nimport { queueDocumentAttachmentBlobReclaims } from \"./orphanSideRows\";\n\nasync function deleteStoredDocumentRows(input: {\n existingDocumentId: string | null;\n localId: string;\n lockedExecSql: ExecSql;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { existingDocumentId, localId, lockedExecSql, tx } = input;\n await queueDocumentAttachmentBlobReclaims({\n localWhere: eq(documentAttachmentBlobProjection.localId, localId),\n pendingWhere: eq(documentPendingAttachments.localId, localId),\n tx,\n });\n await tx\n .delete(documentProjection)\n .where(eq(documentProjection.localId, localId))\n .run();\n await tx\n .delete(documentProjectionText)\n .where(eq(documentProjectionText.localId, localId))\n .run();\n await tx\n .delete(documentPendingAttachments)\n .where(eq(documentPendingAttachments.localId, localId))\n .run();\n await tx\n .delete(documentAttachmentBlobProjection)\n .where(eq(documentAttachmentBlobProjection.localId, localId))\n .run();\n if (existingDocumentId) {\n // Placement rows and their tombstone holds, then queued placement intents.\n await deleteDocumentPlacementRowsByDocumentIds(tx, [existingDocumentId]);\n await deleteDocumentPlacementIntentsInTransaction(tx, existingDocumentId);\n }\n const scope = getDocumentScope(localId);\n const records = new DocumentRecordRepository(lockedExecSql);\n await records.deleteDocumentHistory(scope);\n await records.clearDocumentSyncFailure(scope);\n await records.deleteDocumentRecord(scope);\n}\n\nasync function ensureDocumentDeletionTables(execSql: ExecSql): Promise<void> {\n // Move intents live in the container-contents schema, which document-only\n // callers may not have initialized yet.\n await ensureSqlTables(execSql, documentPlacementIntentTables);\n}\n\nasync function hasAnotherDocumentAlias(input: {\n documentId: string;\n localId: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<boolean> {\n const rows = await input.tx\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.documentId, input.documentId),\n ne(documents.localId, input.localId),\n ),\n )\n .limit(1);\n return rows.length > 0;\n}\n\nexport async function deleteStoredDocument(\n execSql: ExecSql,\n localId: string,\n): Promise<void> {\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureDocumentDeletionTables(lockedExecSql);\n await getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const existingDocument = await new DocumentRecordRepository(\n lockedExecSql,\n ).loadDocumentRecord({\n appKind: DOCUMENTS_APP_KIND,\n localId,\n });\n await deleteStoredDocumentRows({\n existingDocumentId: existingDocument?.documentId ?? null,\n localId,\n lockedExecSql,\n tx,\n });\n },\n { behavior: \"immediate\" },\n );\n });\n}\n\nexport async function deleteStoredDocumentIfMatches(\n execSql: ExecSql,\n expectedRecord: StoredDocumentRecord,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n): Promise<boolean> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureDocumentDeletionTables(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const existingDocument = await new DocumentRecordRepository(\n lockedExecSql,\n ).loadDocumentRecord({\n appKind: DOCUMENTS_APP_KIND,\n localId: expectedRecord.id,\n });\n if (\n !existingDocument ||\n !sameCanonicalDocumentSecurityIdentity(\n existingDocument,\n expectedRecord,\n )\n ) {\n return false;\n }\n const [placement] = await tx\n .select({ containerId: documentProjection.containerId })\n .from(documentProjection)\n .where(eq(documentProjection.localId, expectedRecord.id))\n .limit(1);\n if ((placement?.containerId ?? null) !== expectedRecord.containerId)\n return false;\n if (\n existingDocument.documentId &&\n (await hasAnotherDocumentAlias({\n documentId: existingDocument.documentId,\n localId: expectedRecord.id,\n tx,\n }))\n ) {\n return false;\n }\n await deleteStoredDocumentRows({\n existingDocumentId: existingDocument.documentId ?? null,\n localId: expectedRecord.id,\n lockedExecSql,\n tx,\n });\n await deleteClientProjection(lockedExecSql);\n return true;\n },\n { behavior: \"immediate\" },\n );\n });\n}\n\nexport async function deleteStoredDocumentSideRowsIfAbsent(\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string | null,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n): Promise<boolean> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureDocumentDeletionTables(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const existingDocument = await new DocumentRecordRepository(\n lockedExecSql,\n ).loadDocumentRecord({\n appKind: DOCUMENTS_APP_KIND,\n localId,\n });\n if (existingDocument) return false;\n if (\n expectedDocumentId &&\n (await hasAnotherDocumentAlias({\n documentId: expectedDocumentId,\n localId,\n tx,\n }))\n ) {\n return false;\n }\n\n await deleteStoredDocumentRows({\n existingDocumentId: expectedDocumentId,\n localId,\n lockedExecSql,\n tx,\n });\n await deleteClientProjection(lockedExecSql);\n return true;\n },\n { behavior: \"immediate\" },\n );\n });\n}\n"]}
1
+ {"version":3,"file":"documentDeletionPersistence.js","sourceRoot":"","sources":["documentDeletionPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,EACL,gCAAgC,EAChC,0BAA0B,EAC1B,6BAA6B,GAC9B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,6CAA6C,CAAC;AACxE,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAEL,eAAe,EACf,wBAAwB,GACzB,MAAM,2BAA2B,CAAC;AAEnC,OAAO,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AAEtD,OAAO,EAAE,qCAAqC,EAAE,MAAM,0BAA0B,CAAC;AACjF,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,mCAAmC,EAAE,MAAM,kBAAkB,CAAC;AAE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aACH,CAAC,CAAC;YACH,MAAM,sBAAsB,CAAC,aAAa,CAAC,CAAC;YAC5C,OAAO,IAAI,CAAC;QACd,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, eq, ne } from \"drizzle-orm\";\nimport { DOCUMENTS_APP_KIND } from \"../../../documents/documentConstants\";\nimport {\n documentAttachmentBlobProjection,\n documentPendingAttachments,\n documentPlacementIntentTables,\n} from \"../../../sqlite/schema\";\nimport {\n documentProjection,\n documentProjectionText,\n} from \"../../../sqlite/schema/documentProjectionSchema\";\nimport { documents } from \"../../../sqlite/schema/documentRecordSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type ExecSql,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../../sqlite/sqlSchema\";\nimport type { DocumentPlacementCleanup } from \"../documentDeletionPort\";\nimport { DocumentRecordRepository } from \"../records\";\nimport type { StoredDocumentRecord } from \"../types\";\nimport { sameCanonicalDocumentSecurityIdentity } from \"./documentRecordIdentity\";\nimport { getDocumentScope } from \"./documentRows\";\nimport { queueDocumentAttachmentBlobReclaims } from \"./orphanSideRows\";\n\nasync function deleteStoredDocumentRows(input: {\n deleteDocumentPlacements: DocumentPlacementCleanup;\n existingDocumentId: string | null;\n localId: string;\n lockedExecSql: ExecSql;\n tx: ClientSQLiteTransactionScope;\n}): Promise<void> {\n const { existingDocumentId, localId, lockedExecSql, tx } = input;\n await queueDocumentAttachmentBlobReclaims({\n localWhere: eq(documentAttachmentBlobProjection.localId, localId),\n pendingWhere: eq(documentPendingAttachments.localId, localId),\n tx,\n });\n await tx\n .delete(documentProjection)\n .where(eq(documentProjection.localId, localId))\n .run();\n await tx\n .delete(documentProjectionText)\n .where(eq(documentProjectionText.localId, localId))\n .run();\n await tx\n .delete(documentPendingAttachments)\n .where(eq(documentPendingAttachments.localId, localId))\n .run();\n await tx\n .delete(documentAttachmentBlobProjection)\n .where(eq(documentAttachmentBlobProjection.localId, localId))\n .run();\n if (existingDocumentId) {\n await input.deleteDocumentPlacements(tx, existingDocumentId);\n }\n const scope = getDocumentScope(localId);\n const records = new DocumentRecordRepository(lockedExecSql);\n await records.deleteDocumentHistory(scope);\n await records.clearDocumentSyncFailure(scope);\n await records.deleteDocumentRecord(scope);\n}\n\nasync function ensureDocumentDeletionTables(execSql: ExecSql): Promise<void> {\n // Move intents live in the container-contents schema, which document-only\n // callers may not have initialized yet.\n await ensureSqlTables(execSql, documentPlacementIntentTables);\n}\n\nasync function hasAnotherDocumentAlias(input: {\n documentId: string;\n localId: string;\n tx: ClientSQLiteTransactionScope;\n}): Promise<boolean> {\n const rows = await input.tx\n .select({ localId: documents.localId })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n eq(documents.documentId, input.documentId),\n ne(documents.localId, input.localId),\n ),\n )\n .limit(1);\n return rows.length > 0;\n}\n\nexport async function deleteStoredDocument(\n execSql: ExecSql,\n localId: string,\n deleteDocumentPlacements: DocumentPlacementCleanup,\n): Promise<void> {\n await runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureDocumentDeletionTables(lockedExecSql);\n await getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const existingDocument = await new DocumentRecordRepository(\n lockedExecSql,\n ).loadDocumentRecord({\n appKind: DOCUMENTS_APP_KIND,\n localId,\n });\n await deleteStoredDocumentRows({\n deleteDocumentPlacements,\n existingDocumentId: existingDocument?.documentId ?? null,\n localId,\n lockedExecSql,\n tx,\n });\n },\n { behavior: \"immediate\" },\n );\n });\n}\n\nexport async function deleteStoredDocumentIfMatches(\n execSql: ExecSql,\n expectedRecord: StoredDocumentRecord,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n deleteDocumentPlacements: DocumentPlacementCleanup,\n): Promise<boolean> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureDocumentDeletionTables(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const existingDocument = await new DocumentRecordRepository(\n lockedExecSql,\n ).loadDocumentRecord({\n appKind: DOCUMENTS_APP_KIND,\n localId: expectedRecord.id,\n });\n if (\n !existingDocument ||\n !sameCanonicalDocumentSecurityIdentity(\n existingDocument,\n expectedRecord,\n )\n ) {\n return false;\n }\n const [placement] = await tx\n .select({ containerId: documentProjection.containerId })\n .from(documentProjection)\n .where(eq(documentProjection.localId, expectedRecord.id))\n .limit(1);\n if ((placement?.containerId ?? null) !== expectedRecord.containerId)\n return false;\n if (\n existingDocument.documentId &&\n (await hasAnotherDocumentAlias({\n documentId: existingDocument.documentId,\n localId: expectedRecord.id,\n tx,\n }))\n ) {\n return false;\n }\n await deleteStoredDocumentRows({\n deleteDocumentPlacements,\n existingDocumentId: existingDocument.documentId ?? null,\n localId: expectedRecord.id,\n lockedExecSql,\n tx,\n });\n await deleteClientProjection(lockedExecSql);\n return true;\n },\n { behavior: \"immediate\" },\n );\n });\n}\n\nexport async function deleteStoredDocumentSideRowsIfAbsent(\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string | null,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n deleteDocumentPlacements: DocumentPlacementCleanup,\n): Promise<boolean> {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n await ensureDocumentDeletionTables(lockedExecSql);\n return getClientSQLitePersistenceRuntime(lockedExecSql).transaction(\n async (tx) => {\n const existingDocument = await new DocumentRecordRepository(\n lockedExecSql,\n ).loadDocumentRecord({\n appKind: DOCUMENTS_APP_KIND,\n localId,\n });\n if (existingDocument) return false;\n if (\n expectedDocumentId &&\n (await hasAnotherDocumentAlias({\n documentId: expectedDocumentId,\n localId,\n tx,\n }))\n ) {\n return false;\n }\n\n await deleteStoredDocumentRows({\n deleteDocumentPlacements,\n existingDocumentId: expectedDocumentId,\n localId,\n lockedExecSql,\n tx,\n });\n await deleteClientProjection(lockedExecSql);\n return true;\n },\n { behavior: \"immediate\" },\n );\n });\n}\n"]}
@@ -3,6 +3,7 @@ import type { DiscoveredDocumentInput, DocumentSummary } from "../../documents/d
3
3
  import type { DocumentSyncPullContinuation } from "../../documents/shared/sync/pullContinuation.js";
4
4
  import type { ExecSql } from "../../sqlite/sqlSchema.js";
5
5
  import type { DocumentBirthResult } from "./documentBirthResult.js";
6
+ import type { DocumentDeletionPort } from "./documentDeletionPort.js";
6
7
  import type { DocumentOrphanBlobPersistence } from "./orphanBlobPersistence.js";
7
8
  import type { QueuedPendingUpdateReplacementPort } from "./queuedUpdateReplacementPort.js";
8
9
  import type { DocumentRecord as BaseDocumentRecord, PendingUpdateFields, QueuedPendingUpdateRecord } from "./records/index.js";
@@ -105,7 +106,7 @@ export interface DocumentSummaryList {
105
106
  readonly rows: ReadonlyArray<DocumentSummary>;
106
107
  readonly totalCount: number;
107
108
  }
108
- export interface DocumentsPersistence extends QueuedPendingUpdateReplacementPort {
109
+ export interface DocumentsPersistence extends QueuedPendingUpdateReplacementPort, DocumentDeletionPort<StoredDocumentRecord> {
109
110
  readonly orphanBlobs: DocumentOrphanBlobPersistence;
110
111
  /**
111
112
  * The adapter guarantees that recovery checkpoint replacement, selection of
@@ -262,20 +263,6 @@ export interface DocumentsPersistence extends QueuedPendingUpdateReplacementPort
262
263
  saveDocumentAndDeletePendingUpdates: (execSql: ExecSql, document: StoredDocumentRecord, pendingUpdateIds: readonly string[], options?: {
263
264
  updatedAt?: string;
264
265
  }) => Promise<string>;
265
- deleteDocument: (execSql: ExecSql, localId: string) => Promise<void>;
266
- /**
267
- * Delete the canonical row and every side row only when its security identity
268
- * and container placement still match the captured record. The comparison,
269
- * deletes, and client
270
- * projection callback must share one write transaction.
271
- */
272
- deleteDocumentIfMatches: (execSql: ExecSql, expectedRecord: StoredDocumentRecord, deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>) => Promise<boolean>;
273
- /**
274
- * Delete orphaned side rows only if the canonical document is still absent.
275
- * The absence check, row cleanup, and client projection callback must share
276
- * one write transaction so a concurrent create is preserved.
277
- */
278
- deleteDocumentSideRowsIfAbsent: (execSql: ExecSql, localId: string, expectedDocumentId: string | null, deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>) => Promise<boolean>;
279
266
  upsertDiscoveredDocument: (execSql: ExecSql, input: DiscoveredDocumentInput) => Promise<DocumentSummary>;
280
267
  relinkPersistedDocument: (execSql: ExecSql, input: RelinkPersistedDocumentInput) => Promise<DocumentSummary | null>;
281
268
  listPendingUpdates: (execSql: ExecSql, localId: string) => Promise<QueuedPendingUpdateRecord[]>;
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n DocumentProjectorRegistryInput,\n StoredDocumentKind,\n} from \"../../documents/documentKinds\";\nimport type {\n DiscoveredDocumentInput,\n DocumentSummary,\n} from \"../../documents/documentSummary\";\nimport type { DocumentSyncPullContinuation } from \"../../documents/shared/sync/pullContinuation\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type { DocumentBirthResult } from \"./documentBirthResult\";\nimport type { DocumentOrphanBlobPersistence } from \"./orphanBlobPersistence\";\nimport type { QueuedPendingUpdateReplacementPort } from \"./queuedUpdateReplacementPort\";\nimport type {\n DocumentRecord as BaseDocumentRecord,\n PendingUpdateFields,\n QueuedPendingUpdateRecord,\n} from \"./records\";\n\nexport interface StoredDocumentRecord extends BaseDocumentRecord {\n containerId: string | null;\n documentKind?: StoredDocumentKind;\n text: string;\n title?: string;\n}\n\nexport type DiscardDocumentToShellResult =\n | { discarded: false }\n | {\n discarded: true;\n documentKind: StoredDocumentKind;\n };\n\nexport interface PendingUpdateInsert extends PendingUpdateFields {\n localId: string;\n}\n\n/**\n * The identity a pending attachment upload reuses across attempts so a retry\n * (next sync pass or after a restart) reproduces byte-identical encrypted bytes\n * and resumes the same multipart stage instead of orphaning it. `contentKey` and\n * the chunk `nonceSeed` are base64. `partSize`/`stageId` are filled in once the\n * multipart stage has been opened and remain null before that.\n */\nexport interface PendingAttachmentUploadIdentity {\n blobId: string;\n contentKey: string;\n contentKeyEpoch: number;\n nonceSeed: string;\n partSize: number | null;\n plaintextSha256: string;\n stageId: string | null;\n}\n\nexport interface PendingAttachmentRecord {\n byteLength: number;\n contentSha256: string;\n localId: string;\n mimeType: string | null;\n name: string;\n slotId: string;\n storageKey: string;\n upload?: PendingAttachmentUploadIdentity | null;\n}\n\nexport interface LocalAttachmentRecord {\n blobId: string | null;\n byteLength: number;\n // Plaintext digest of the bytes at `storageKey`. Compared with the digest\n // the document content records for the slot: a held copy that differs is a\n // validly signed served binding the document has not recorded (yet).\n contentSha256: string;\n // Set once the slot is unlinked from a synced document and cleared when the\n // slot is written again. The record survives the unlink so the next sync can\n // still detach the remote binding; `detachedAt` is what keeps the local read\n // models from reporting the slot as a live blob reference in the meantime.\n detachedAt: string | null;\n localId: string;\n mimeType: string | null;\n slotId: string;\n storageKey: string;\n}\n\nexport interface AttachmentStagingRows {\n localAttachments: ReadonlyArray<LocalAttachmentRecord>;\n pendingAttachments: ReadonlyArray<PendingAttachmentRecord>;\n}\n\nexport interface AttachmentRemovalRows {\n mode: \"delete\" | \"detach\";\n slotId: string;\n storageKey: string;\n}\n\nexport interface DocumentHistoryRestoreState {\n snapshot: string;\n tailUpdates: readonly {\n origin: \"local\" | \"remote\";\n updateData: string;\n }[];\n}\n\nexport interface RelinkPersistedDocumentInput {\n accessEpoch: number;\n accessStateHash?: string | null;\n containerId: string;\n documentId: string | null;\n localId: string;\n}\n\nexport interface ContainerDocumentTombstoneInput {\n containerId: string;\n documentId: string;\n /** Epoch of the verified head; apply refuses a head below local state. */\n accessEpoch: number;\n /** Verified head link set (omits `containerId`); apply needs signed evidence. */\n linkedContainerIds: ReadonlyArray<string>;\n updatedAt: string;\n}\n\nexport type DocumentSummarySortDirection = \"asc\" | \"desc\";\nexport type DocumentSummarySortKey = \"kind\" | \"title\" | \"updated\";\n\nexport interface DocumentSummarySort {\n readonly direction: DocumentSummarySortDirection;\n readonly key: DocumentSummarySortKey;\n}\n\nexport interface ListDocumentSummariesInput {\n documentKind?: StoredDocumentKind | undefined;\n limit?: number | undefined;\n offset?: number | undefined;\n sort?: DocumentSummarySort | undefined;\n}\n\nexport interface DocumentSummaryList {\n readonly rows: ReadonlyArray<DocumentSummary>;\n readonly totalCount: number;\n}\n\nexport interface DocumentsPersistence\n extends QueuedPendingUpdateReplacementPort {\n readonly orphanBlobs: DocumentOrphanBlobPersistence;\n /**\n * The adapter guarantees that recovery checkpoint replacement, selection of\n * covered local history, rejection of unproven ordinary pending rows, and\n * quarantine of every queued checkpoint artifact share the guarded\n * `commitDocumentMutation` transaction, which also advances the canonical\n * recovery generation. An unrelated history tail not covered by the rebuild\n * must abort that transaction.\n */\n readonly supportsAtomicRecoveryHistoryPruning: boolean;\n /**\n * Atomically create the canonical row, standard projections, and birth\n * checkpoint. Returns null when another initializer already owns localId.\n * A remote-alias result refuses a second birth; discovery alone is not\n * authority to adopt the existing record or replace its history.\n */\n createDocumentWithHistoryCheckpoint: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n historyCheckpoint: {\n endVersionVector: string;\n snapshot: string;\n },\n options:\n | {\n pendingUpdate?: PendingUpdateFields;\n /** Recheck volatile caller ownership inside the create transaction. */\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string;\n }\n | undefined,\n saveClientProjection: (\n transactionExecSql: ExecSql,\n updatedAt: string,\n ) => Promise<void>,\n ) => Promise<DocumentBirthResult>;\n /**\n * Conditionally commit one already-prepared mutation against the exact\n * durable record it was derived from. The identity/progress comparison,\n * attachment and history writes, accepted-queue settlement,\n * canonical/projection save, and client projection callback must share one\n * adapter transaction.\n */\n commitDocumentMutation: (\n execSql: ExecSql,\n input: {\n acceptedPendingUpdateIds: readonly string[];\n attachmentRemoval?: AttachmentRemovalRows | undefined;\n attachmentStaging?: AttachmentStagingRows | undefined;\n clearSyncFailure?: boolean | undefined;\n document: StoredDocumentRecord;\n expectedRecord: StoredDocumentRecord;\n historyCheckpoint?:\n | {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n pruneCoveredLocalState: boolean;\n snapshot: string;\n }\n | undefined;\n historyUpdateOrigin?: \"local\" | \"remote\" | undefined;\n historyUpdates?: readonly string[] | undefined;\n pendingUpdate?: PendingUpdateFields | undefined;\n settleAcceptedPendingOnConflict: boolean;\n /**\n * Recheck volatile caller ownership inside the adapter transaction,\n * before any durable side effect. A false result aborts the commit.\n */\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string | undefined;\n },\n saveClientProjection: (\n transactionExecSql: ExecSql,\n updatedAt: string,\n ) => Promise<void>,\n ) => Promise<\n | { committed: true; updatedAt: string }\n | { committed: false; currentRecord: StoredDocumentRecord | null }\n >;\n /** Settle acknowledged rows while the response's identity, apart from access state, survives. */\n settleAcceptedPendingUpdates: (\n execSql: ExecSql,\n input: {\n expectedRecord: StoredDocumentRecord;\n pendingUpdateIds: readonly string[];\n },\n ) => Promise<StoredDocumentRecord | null>;\n ensureSchema: (execSql: ExecSql) => Promise<void>;\n listDocuments: (execSql: ExecSql) => Promise<DocumentSummary[]>;\n listDocumentSummaries: (\n execSql: ExecSql,\n input?: ListDocumentSummariesInput,\n ) => Promise<DocumentSummaryList>;\n listDocumentsByContainerIdsOrDocumentIds: (\n execSql: ExecSql,\n input: {\n containerIds: ReadonlyArray<string>;\n documentIds: ReadonlyArray<string>;\n },\n ) => Promise<DocumentSummary[]>;\n findDocumentLocalIdsByContainerId: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<string[]>;\n /**\n * Select one local row for a remote document identity. Prefer any row with\n * queued updates or a deferred-sync frontier, then break duplicates by\n * updatedAt and localId descending.\n */\n findLocalIdByDocumentId: (\n execSql: ExecSql,\n documentId: string,\n ) => Promise<string | null>;\n /** Canonical-row probe; false authorizes destructive orphan teardown. */\n hasDocument: (execSql: ExecSql, localId: string) => Promise<boolean>;\n /** Observe whether the canonical row still names the expected remote stream. */\n documentIdentityMatches: (\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string | null,\n expectedRecoveryGeneration: number,\n ) => Promise<boolean>;\n loadDocument: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<StoredDocumentRecord | null>;\n /** Read the canonical record and its history from one database snapshot. */\n loadDocumentWithHistoryRestoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n document: StoredDocumentRecord | null;\n historyRestoreState: DocumentHistoryRestoreState | null;\n }>;\n /** Read every document-store startup row from one database snapshot. */\n loadDocumentStoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n document: StoredDocumentRecord | null;\n historyRestoreState: DocumentHistoryRestoreState | null;\n localAttachments: LocalAttachmentRecord[];\n pendingAttachments: PendingAttachmentRecord[];\n }>;\n /**\n * Atomically replace the exact rejected pull continuation with the durable\n * recovery marker when every supplied sync-identity field still matches.\n * Return the authoritative current record after the compare-and-set, or\n * null when the canonical row no longer exists. A CAS loss returns the\n * winning record so the live store can adopt its newer progress.\n */\n invalidatePullContinuation: (\n execSql: ExecSql,\n input: {\n accessEpoch: number;\n accessStateHash: string | null;\n continuation: DocumentSyncPullContinuation;\n contentKeyBundle: string | null;\n documentId: string;\n documentKekTargets: string | null;\n documentManifestBundle: string | null;\n lastCommitLsn: string | null;\n localId: string;\n },\n ) => Promise<{\n historyRestoreState: DocumentHistoryRestoreState | null;\n record: StoredDocumentRecord;\n } | null>;\n // Read the authoritative container placement for a locally persisted document\n // straight from its projection row. Returns `undefined` when no projection row\n // exists yet (a first create/discovery persist), so a caller can distinguish\n // that from a row that legitimately carries a null container (a document\n // unlinked from every container). Container placement is owned by the\n // link/tombstone/discovery layer, so a content-metadata persist reads this to\n // avoid republishing a stale in-memory container.\n loadDocumentContainer: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{ containerId: string | null } | undefined>;\n saveDocument: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n options?: {\n updatedAt?: string;\n },\n ) => Promise<string>;\n /**\n * Durable full-history support (checkpoint + append-only tail) — the ONLY\n * persisted content source. REQUIRED: a persistence without these could\n * report successful writes whose documents reopen empty.\n */\n appendHistoryUpdates: (\n execSql: ExecSql,\n input: {\n localId: string;\n origin: \"local\" | \"remote\";\n updates: readonly string[];\n },\n ) => Promise<void>;\n loadHistoryRestoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<DocumentHistoryRestoreState | null>;\n readHistoryTailSize: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n byteLength: number;\n hasCheckpoint: boolean;\n rowCount: number;\n }>;\n listHistoryTailEntries: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{ id: string; updateData: string }[]>;\n replaceHistoryCheckpoint: (\n execSql: ExecSql,\n input: {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n force?: boolean;\n localId: string;\n snapshot: string;\n stillCurrent?: () => boolean;\n },\n ) => Promise<void>;\n saveDocumentAndDeletePendingUpdates: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n pendingUpdateIds: readonly string[],\n options?: {\n updatedAt?: string;\n },\n ) => Promise<string>;\n deleteDocument: (execSql: ExecSql, localId: string) => Promise<void>;\n /**\n * Delete the canonical row and every side row only when its security identity\n * and container placement still match the captured record. The comparison,\n * deletes, and client\n * projection callback must share one write transaction.\n */\n deleteDocumentIfMatches: (\n execSql: ExecSql,\n expectedRecord: StoredDocumentRecord,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n ) => Promise<boolean>;\n /**\n * Delete orphaned side rows only if the canonical document is still absent.\n * The absence check, row cleanup, and client projection callback must share\n * one write transaction so a concurrent create is preserved.\n */\n deleteDocumentSideRowsIfAbsent: (\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string | null,\n deleteClientProjection: (transactionExecSql: ExecSql) => Promise<void>,\n ) => Promise<boolean>;\n upsertDiscoveredDocument: (\n execSql: ExecSql,\n input: DiscoveredDocumentInput,\n ) => Promise<DocumentSummary>;\n relinkPersistedDocument: (\n execSql: ExecSql,\n input: RelinkPersistedDocumentInput,\n ) => Promise<DocumentSummary | null>;\n listPendingUpdates: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<QueuedPendingUpdateRecord[]>;\n rekeyPendingUpdate: (execSql: ExecSql, id: string) => Promise<string | null>;\n listPendingAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<PendingAttachmentRecord[]>;\n listLocalAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<LocalAttachmentRecord[]>;\n /**\n * Durably append the outgoing row and matching local-history tail entry.\n * When expectations are supplied, compare the document identity and recovery\n * generation with the canonical row inside that same mutation and return\n * false on absence or mismatch. Adapters must not insert either row.\n */\n enqueuePendingUpdate: (\n execSql: ExecSql,\n pendingUpdate: PendingUpdateInsert,\n options?: {\n expectedDocumentId: string | null;\n expectedRecoveryGeneration: number;\n },\n ) => Promise<boolean>;\n /** Replace a hydrated copy only if its observed durable slot and live document still match. */\n saveHydratedAttachment: (\n execSql: ExecSql,\n input: {\n attachment: LocalAttachmentRecord;\n expectedStorageKey: string | null;\n expectedSnapshotEndVersion: string | null;\n stillCurrent: () => boolean;\n },\n ) => Promise<boolean>;\n saveLocalAttachment: (\n execSql: ExecSql,\n attachment: LocalAttachmentRecord,\n ) => Promise<void>;\n deleteLocalAttachment: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n markLocalAttachmentDetached: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n savePendingAttachment: (\n execSql: ExecSql,\n attachment: PendingAttachmentRecord,\n ) => Promise<void>;\n deletePendingUpdate: (execSql: ExecSql, id: string) => Promise<void>;\n deletePendingUpdates: (execSql: ExecSql, localId: string) => Promise<void>;\n deletePendingAttachment: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n deletePendingAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<void>;\n /**\n * Atomically convert a stuck document's local state to the\n * freshly-discovered-share shell (see the SQL implementation's doc\n * comment). The projector registry clears the document-kind client\n * projection in the same transaction — those tables live with the app's\n * projector definitions, so the CALLER'S registry is required (the default\n * registry knows no app kinds, and a discard that silently kept a\n * contact's or card's projected fields would leak the discarded values).\n * The method itself is optional: implementations without the full document\n * schema (container metadata, simple doubles) simply do not offer the\n * discard escape hatch.\n */\n /**\n * `expectedDocumentId` is revalidated against the loaded record inside the\n * serialized mutation: a stale caller (or a relink that raced the request)\n * must never discard a different identity's edits.\n */\n discardDocumentToShell?: (\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string,\n documentProjectors: DocumentProjectorRegistryInput,\n ) => Promise<DiscardDocumentToShellResult>;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n DocumentProjectorRegistryInput,\n StoredDocumentKind,\n} from \"../../documents/documentKinds\";\nimport type {\n DiscoveredDocumentInput,\n DocumentSummary,\n} from \"../../documents/documentSummary\";\nimport type { DocumentSyncPullContinuation } from \"../../documents/shared/sync/pullContinuation\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type { DocumentBirthResult } from \"./documentBirthResult\";\nimport type { DocumentDeletionPort } from \"./documentDeletionPort\";\nimport type { DocumentOrphanBlobPersistence } from \"./orphanBlobPersistence\";\nimport type { QueuedPendingUpdateReplacementPort } from \"./queuedUpdateReplacementPort\";\nimport type {\n DocumentRecord as BaseDocumentRecord,\n PendingUpdateFields,\n QueuedPendingUpdateRecord,\n} from \"./records\";\n\nexport interface StoredDocumentRecord extends BaseDocumentRecord {\n containerId: string | null;\n documentKind?: StoredDocumentKind;\n text: string;\n title?: string;\n}\n\nexport type DiscardDocumentToShellResult =\n | { discarded: false }\n | {\n discarded: true;\n documentKind: StoredDocumentKind;\n };\n\nexport interface PendingUpdateInsert extends PendingUpdateFields {\n localId: string;\n}\n\n/**\n * The identity a pending attachment upload reuses across attempts so a retry\n * (next sync pass or after a restart) reproduces byte-identical encrypted bytes\n * and resumes the same multipart stage instead of orphaning it. `contentKey` and\n * the chunk `nonceSeed` are base64. `partSize`/`stageId` are filled in once the\n * multipart stage has been opened and remain null before that.\n */\nexport interface PendingAttachmentUploadIdentity {\n blobId: string;\n contentKey: string;\n contentKeyEpoch: number;\n nonceSeed: string;\n partSize: number | null;\n plaintextSha256: string;\n stageId: string | null;\n}\n\nexport interface PendingAttachmentRecord {\n byteLength: number;\n contentSha256: string;\n localId: string;\n mimeType: string | null;\n name: string;\n slotId: string;\n storageKey: string;\n upload?: PendingAttachmentUploadIdentity | null;\n}\n\nexport interface LocalAttachmentRecord {\n blobId: string | null;\n byteLength: number;\n // Plaintext digest of the bytes at `storageKey`. Compared with the digest\n // the document content records for the slot: a held copy that differs is a\n // validly signed served binding the document has not recorded (yet).\n contentSha256: string;\n // Set once the slot is unlinked from a synced document and cleared when the\n // slot is written again. The record survives the unlink so the next sync can\n // still detach the remote binding; `detachedAt` is what keeps the local read\n // models from reporting the slot as a live blob reference in the meantime.\n detachedAt: string | null;\n localId: string;\n mimeType: string | null;\n slotId: string;\n storageKey: string;\n}\n\nexport interface AttachmentStagingRows {\n localAttachments: ReadonlyArray<LocalAttachmentRecord>;\n pendingAttachments: ReadonlyArray<PendingAttachmentRecord>;\n}\n\nexport interface AttachmentRemovalRows {\n mode: \"delete\" | \"detach\";\n slotId: string;\n storageKey: string;\n}\n\nexport interface DocumentHistoryRestoreState {\n snapshot: string;\n tailUpdates: readonly {\n origin: \"local\" | \"remote\";\n updateData: string;\n }[];\n}\n\nexport interface RelinkPersistedDocumentInput {\n accessEpoch: number;\n accessStateHash?: string | null;\n containerId: string;\n documentId: string | null;\n localId: string;\n}\n\nexport interface ContainerDocumentTombstoneInput {\n containerId: string;\n documentId: string;\n /** Epoch of the verified head; apply refuses a head below local state. */\n accessEpoch: number;\n /** Verified head link set (omits `containerId`); apply needs signed evidence. */\n linkedContainerIds: ReadonlyArray<string>;\n updatedAt: string;\n}\n\nexport type DocumentSummarySortDirection = \"asc\" | \"desc\";\nexport type DocumentSummarySortKey = \"kind\" | \"title\" | \"updated\";\n\nexport interface DocumentSummarySort {\n readonly direction: DocumentSummarySortDirection;\n readonly key: DocumentSummarySortKey;\n}\n\nexport interface ListDocumentSummariesInput {\n documentKind?: StoredDocumentKind | undefined;\n limit?: number | undefined;\n offset?: number | undefined;\n sort?: DocumentSummarySort | undefined;\n}\n\nexport interface DocumentSummaryList {\n readonly rows: ReadonlyArray<DocumentSummary>;\n readonly totalCount: number;\n}\n\nexport interface DocumentsPersistence\n extends QueuedPendingUpdateReplacementPort,\n DocumentDeletionPort<StoredDocumentRecord> {\n readonly orphanBlobs: DocumentOrphanBlobPersistence;\n /**\n * The adapter guarantees that recovery checkpoint replacement, selection of\n * covered local history, rejection of unproven ordinary pending rows, and\n * quarantine of every queued checkpoint artifact share the guarded\n * `commitDocumentMutation` transaction, which also advances the canonical\n * recovery generation. An unrelated history tail not covered by the rebuild\n * must abort that transaction.\n */\n readonly supportsAtomicRecoveryHistoryPruning: boolean;\n /**\n * Atomically create the canonical row, standard projections, and birth\n * checkpoint. Returns null when another initializer already owns localId.\n * A remote-alias result refuses a second birth; discovery alone is not\n * authority to adopt the existing record or replace its history.\n */\n createDocumentWithHistoryCheckpoint: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n historyCheckpoint: {\n endVersionVector: string;\n snapshot: string;\n },\n options:\n | {\n pendingUpdate?: PendingUpdateFields;\n /** Recheck volatile caller ownership inside the create transaction. */\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string;\n }\n | undefined,\n saveClientProjection: (\n transactionExecSql: ExecSql,\n updatedAt: string,\n ) => Promise<void>,\n ) => Promise<DocumentBirthResult>;\n /**\n * Conditionally commit one already-prepared mutation against the exact\n * durable record it was derived from. The identity/progress comparison,\n * attachment and history writes, accepted-queue settlement,\n * canonical/projection save, and client projection callback must share one\n * adapter transaction.\n */\n commitDocumentMutation: (\n execSql: ExecSql,\n input: {\n acceptedPendingUpdateIds: readonly string[];\n attachmentRemoval?: AttachmentRemovalRows | undefined;\n attachmentStaging?: AttachmentStagingRows | undefined;\n clearSyncFailure?: boolean | undefined;\n document: StoredDocumentRecord;\n expectedRecord: StoredDocumentRecord;\n historyCheckpoint?:\n | {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n pruneCoveredLocalState: boolean;\n snapshot: string;\n }\n | undefined;\n historyUpdateOrigin?: \"local\" | \"remote\" | undefined;\n historyUpdates?: readonly string[] | undefined;\n pendingUpdate?: PendingUpdateFields | undefined;\n settleAcceptedPendingOnConflict: boolean;\n /**\n * Recheck volatile caller ownership inside the adapter transaction,\n * before any durable side effect. A false result aborts the commit.\n */\n stillCurrent?: (() => boolean) | undefined;\n updatedAt?: string | undefined;\n },\n saveClientProjection: (\n transactionExecSql: ExecSql,\n updatedAt: string,\n ) => Promise<void>,\n ) => Promise<\n | { committed: true; updatedAt: string }\n | { committed: false; currentRecord: StoredDocumentRecord | null }\n >;\n /** Settle acknowledged rows while the response's identity, apart from access state, survives. */\n settleAcceptedPendingUpdates: (\n execSql: ExecSql,\n input: {\n expectedRecord: StoredDocumentRecord;\n pendingUpdateIds: readonly string[];\n },\n ) => Promise<StoredDocumentRecord | null>;\n ensureSchema: (execSql: ExecSql) => Promise<void>;\n listDocuments: (execSql: ExecSql) => Promise<DocumentSummary[]>;\n listDocumentSummaries: (\n execSql: ExecSql,\n input?: ListDocumentSummariesInput,\n ) => Promise<DocumentSummaryList>;\n listDocumentsByContainerIdsOrDocumentIds: (\n execSql: ExecSql,\n input: {\n containerIds: ReadonlyArray<string>;\n documentIds: ReadonlyArray<string>;\n },\n ) => Promise<DocumentSummary[]>;\n findDocumentLocalIdsByContainerId: (\n execSql: ExecSql,\n containerId: string,\n ) => Promise<string[]>;\n /**\n * Select one local row for a remote document identity. Prefer any row with\n * queued updates or a deferred-sync frontier, then break duplicates by\n * updatedAt and localId descending.\n */\n findLocalIdByDocumentId: (\n execSql: ExecSql,\n documentId: string,\n ) => Promise<string | null>;\n /** Canonical-row probe; false authorizes destructive orphan teardown. */\n hasDocument: (execSql: ExecSql, localId: string) => Promise<boolean>;\n /** Observe whether the canonical row still names the expected remote stream. */\n documentIdentityMatches: (\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string | null,\n expectedRecoveryGeneration: number,\n ) => Promise<boolean>;\n loadDocument: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<StoredDocumentRecord | null>;\n /** Read the canonical record and its history from one database snapshot. */\n loadDocumentWithHistoryRestoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n document: StoredDocumentRecord | null;\n historyRestoreState: DocumentHistoryRestoreState | null;\n }>;\n /** Read every document-store startup row from one database snapshot. */\n loadDocumentStoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n document: StoredDocumentRecord | null;\n historyRestoreState: DocumentHistoryRestoreState | null;\n localAttachments: LocalAttachmentRecord[];\n pendingAttachments: PendingAttachmentRecord[];\n }>;\n /**\n * Atomically replace the exact rejected pull continuation with the durable\n * recovery marker when every supplied sync-identity field still matches.\n * Return the authoritative current record after the compare-and-set, or\n * null when the canonical row no longer exists. A CAS loss returns the\n * winning record so the live store can adopt its newer progress.\n */\n invalidatePullContinuation: (\n execSql: ExecSql,\n input: {\n accessEpoch: number;\n accessStateHash: string | null;\n continuation: DocumentSyncPullContinuation;\n contentKeyBundle: string | null;\n documentId: string;\n documentKekTargets: string | null;\n documentManifestBundle: string | null;\n lastCommitLsn: string | null;\n localId: string;\n },\n ) => Promise<{\n historyRestoreState: DocumentHistoryRestoreState | null;\n record: StoredDocumentRecord;\n } | null>;\n // Read the authoritative container placement for a locally persisted document\n // straight from its projection row. Returns `undefined` when no projection row\n // exists yet (a first create/discovery persist), so a caller can distinguish\n // that from a row that legitimately carries a null container (a document\n // unlinked from every container). Container placement is owned by the\n // link/tombstone/discovery layer, so a content-metadata persist reads this to\n // avoid republishing a stale in-memory container.\n loadDocumentContainer: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{ containerId: string | null } | undefined>;\n saveDocument: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n options?: {\n updatedAt?: string;\n },\n ) => Promise<string>;\n /**\n * Durable full-history support (checkpoint + append-only tail) — the ONLY\n * persisted content source. REQUIRED: a persistence without these could\n * report successful writes whose documents reopen empty.\n */\n appendHistoryUpdates: (\n execSql: ExecSql,\n input: {\n localId: string;\n origin: \"local\" | \"remote\";\n updates: readonly string[];\n },\n ) => Promise<void>;\n loadHistoryRestoreState: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<DocumentHistoryRestoreState | null>;\n readHistoryTailSize: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{\n byteLength: number;\n hasCheckpoint: boolean;\n rowCount: number;\n }>;\n listHistoryTailEntries: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<{ id: string; updateData: string }[]>;\n replaceHistoryCheckpoint: (\n execSql: ExecSql,\n input: {\n coveredTailIds: readonly string[];\n endVersionVector: string;\n force?: boolean;\n localId: string;\n snapshot: string;\n stillCurrent?: () => boolean;\n },\n ) => Promise<void>;\n saveDocumentAndDeletePendingUpdates: (\n execSql: ExecSql,\n document: StoredDocumentRecord,\n pendingUpdateIds: readonly string[],\n options?: {\n updatedAt?: string;\n },\n ) => Promise<string>;\n upsertDiscoveredDocument: (\n execSql: ExecSql,\n input: DiscoveredDocumentInput,\n ) => Promise<DocumentSummary>;\n relinkPersistedDocument: (\n execSql: ExecSql,\n input: RelinkPersistedDocumentInput,\n ) => Promise<DocumentSummary | null>;\n listPendingUpdates: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<QueuedPendingUpdateRecord[]>;\n rekeyPendingUpdate: (execSql: ExecSql, id: string) => Promise<string | null>;\n listPendingAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<PendingAttachmentRecord[]>;\n listLocalAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<LocalAttachmentRecord[]>;\n /**\n * Durably append the outgoing row and matching local-history tail entry.\n * When expectations are supplied, compare the document identity and recovery\n * generation with the canonical row inside that same mutation and return\n * false on absence or mismatch. Adapters must not insert either row.\n */\n enqueuePendingUpdate: (\n execSql: ExecSql,\n pendingUpdate: PendingUpdateInsert,\n options?: {\n expectedDocumentId: string | null;\n expectedRecoveryGeneration: number;\n },\n ) => Promise<boolean>;\n /** Replace a hydrated copy only if its observed durable slot and live document still match. */\n saveHydratedAttachment: (\n execSql: ExecSql,\n input: {\n attachment: LocalAttachmentRecord;\n expectedStorageKey: string | null;\n expectedSnapshotEndVersion: string | null;\n stillCurrent: () => boolean;\n },\n ) => Promise<boolean>;\n saveLocalAttachment: (\n execSql: ExecSql,\n attachment: LocalAttachmentRecord,\n ) => Promise<void>;\n deleteLocalAttachment: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n markLocalAttachmentDetached: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n savePendingAttachment: (\n execSql: ExecSql,\n attachment: PendingAttachmentRecord,\n ) => Promise<void>;\n deletePendingUpdate: (execSql: ExecSql, id: string) => Promise<void>;\n deletePendingUpdates: (execSql: ExecSql, localId: string) => Promise<void>;\n deletePendingAttachment: (\n execSql: ExecSql,\n localId: string,\n slotId: string,\n storageKey: string,\n ) => Promise<void>;\n deletePendingAttachments: (\n execSql: ExecSql,\n localId: string,\n ) => Promise<void>;\n /**\n * Atomically convert a stuck document's local state to the\n * freshly-discovered-share shell (see the SQL implementation's doc\n * comment). The projector registry clears the document-kind client\n * projection in the same transaction — those tables live with the app's\n * projector definitions, so the CALLER'S registry is required (the default\n * registry knows no app kinds, and a discard that silently kept a\n * contact's or card's projected fields would leak the discarded values).\n * The method itself is optional: implementations without the full document\n * schema (container metadata, simple doubles) simply do not offer the\n * discard escape hatch.\n */\n /**\n * `expectedDocumentId` is revalidated against the loaded record inside the\n * serialized mutation: a stale caller (or a relink that raced the request)\n * must never discard a different identity's edits.\n */\n discardDocumentToShell?: (\n execSql: ExecSql,\n localId: string,\n expectedDocumentId: string,\n documentProjectors: DocumentProjectorRegistryInput,\n ) => Promise<DiscardDocumentToShellResult>;\n}\n"]}
@@ -2,7 +2,7 @@ import { KeyingVerificationError, verifyAccessManifestLocalCheckpoint, verifyPri
2
2
  import { keyingCheckpointTables } from "../../sqlite/schema/keyingCheckpointSchema.js";
3
3
  import { principalPolicyTables } from "../../sqlite/schema/principalPolicySchema.js";
4
4
  import { verifiedManifestBundleTables } from "../../sqlite/schema/verifiedManifestBundleSchema.js";
5
- import { loadContainerRetirementCheck } from "../principalKeys/principalGrantRetirementPersistence.js";
5
+ import { loadContainerRetirementCheck } from "../principalContracts/principalGrantRetirementPersistence.js";
6
6
  import { writeVerifiedManifestBundlesInTransaction, } from "../verifiedManifestBundlePersistence.js";
7
7
  import { storeDocumentPurgeCheckpointInTransaction, } from "./documentPurgeCheckpointPersistence.js";
8
8
  import { validateAccessManifestCheckpointEvidence } from "./keyingCheckpointEvidence.js";
@@ -1 +1 @@
1
- {"version":3,"file":"keyingCheckpointAdvancePersistence.js","sourceRoot":"","sources":["keyingCheckpointAdvancePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,uBAAuB,EAIvB,mCAAmC,EACnC,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,sBAAsB,EAAE,MAAM,4CAA4C,CAAC;AACpF,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,EAAE,4BAA4B,EAAE,MAAM,kDAAkD,CAAC;AAEhG,OAAO,EAAE,4BAA4B,EAAE,MAAM,sDAAsD,CAAC;AACpG,OAAO,EAGL,yCAAyC,GAC1C,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAEL,yCAAyC,GAC1C,MAAM,sC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CACV,CAAC;IACJ,CAAC;IACD,MAAM,yCAAyC,CAAC,EAAE,EAAE,UAAU,EAAE,SAAS,CAAC,CAAC;AAC7E,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n type AnyVerifiedPrincipalPolicy,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedPrincipalPolicyCurrent,\n type VerifiedPrincipalPolicySelection,\n verifyAccessManifestLocalCheckpoint,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport { keyingCheckpointTables } from \"../../sqlite/schema/keyingCheckpointSchema\";\nimport { principalPolicyTables } from \"../../sqlite/schema/principalPolicySchema\";\nimport { verifiedManifestBundleTables } from \"../../sqlite/schema/verifiedManifestBundleSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { loadContainerRetirementCheck } from \"../principalKeys/principalGrantRetirementPersistence\";\nimport {\n type VerifiedManifestBundle,\n type VerifiedManifestBundleRow,\n writeVerifiedManifestBundlesInTransaction,\n} from \"../verifiedManifestBundlePersistence\";\nimport {\n type DocumentPurgeCheckpoint,\n storeDocumentPurgeCheckpointInTransaction,\n} from \"./documentPurgeCheckpointPersistence\";\nimport { validateAccessManifestCheckpointEvidence } from \"./keyingCheckpointEvidence\";\nimport {\n accessManifestObjectKey,\n loadAccessManifestCheckpointRows,\n loadStoredPrincipalPolicyCheckpoints,\n principalPolicyKey,\n upsertAccessManifestCheckpointsInTransaction,\n upsertPrincipalPolicyCheckpointsInTransaction,\n} from \"./keyingCheckpointPersistence\";\nimport { validatePrincipalAuthorizationCheckpoints } from \"./principalAuthorizationCheckpoints\";\n\nexport interface AccessManifestCheckpointAdvance {\n readonly head: VerifiedAccessManifestCheckpointEvidence;\n readonly predecessors: readonly VerifiedAccessManifestCheckpointEvidence[];\n}\n\ntype CheckpointPolicy =\n | AnyVerifiedPrincipalPolicy\n | VerifiedPrincipalPolicyCurrent;\n\n/** A verified batch of checkpoint candidates; the repository supplies the executor. */\nexport interface KeyingCheckpointBatch {\n readonly access: readonly AccessManifestCheckpointAdvance[];\n readonly policies: readonly CheckpointPolicy[];\n readonly authorizationPolicies?:\n | readonly VerifiedPrincipalPolicySelection[]\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n /**\n * Bundles this projection verified. They are stored for later citation in\n * the same transaction, so they commit only with the batch they verified.\n */\n readonly verifiedBundles?: readonly VerifiedManifestBundle[] | undefined;\n}\n\nexport interface KeyingCheckpointAdvanceBatch extends KeyingCheckpointBatch {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly organizationId?: string | undefined;\n}\n\ninterface PendingAccessCheckpoint {\n readonly changed: boolean;\n readonly checkpoint: AccessManifestCheckpoint;\n}\n\nfunction validateAccessAdvance(\n advance: AccessManifestCheckpointAdvance,\n localCheckpoint: AccessManifestCheckpoint | null,\n): PendingAccessCheckpoint {\n const current = {\n ...advance.head.checkpoint,\n previousManifestHash: advance.head.manifest.previousManifestHash,\n };\n const predecessors = [...advance.predecessors].sort(\n (left, right) => left.checkpoint.epoch - right.checkpoint.epoch,\n );\n\n if (localCheckpoint && current.epoch <= localCheckpoint.epoch) {\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: undefined,\n });\n }\n\n validateAccessManifestCheckpointEvidence({\n head: advance.head,\n predecessors,\n localCheckpoint,\n });\n\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: predecessors.filter(\n (manifest) =>\n localCheckpoint !== null &&\n manifest.checkpoint.epoch > localCheckpoint.epoch &&\n manifest.checkpoint.epoch < current.epoch,\n ),\n });\n\n return {\n changed:\n localCheckpoint?.epoch !== current.epoch ||\n localCheckpoint.manifestHash !== current.manifestHash,\n checkpoint: advance.head.checkpoint,\n };\n}\n\nasync function validateAccessAdvances(\n tx: ClientSQLiteTransactionScope,\n advances: readonly AccessManifestCheckpointAdvance[],\n): Promise<Map<string, PendingAccessCheckpoint>> {\n const pending = new Map<string, PendingAccessCheckpoint>();\n if (advances.length === 0) return pending;\n // Set reads first; the checks then replay in order, so the same advance\n // fails first with the same error.\n const heads = advances.map((advance) => advance.head.checkpoint);\n const assertNotRetired = await loadContainerRetirementCheck(tx, heads);\n const stored = await loadAccessManifestCheckpointRows(tx, heads);\n\n for (const advance of advances) {\n assertNotRetired(advance.head.checkpoint);\n const key = accessManifestObjectKey(advance.head.checkpoint);\n if (pending.has(key)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `projection declares multiple access checkpoint heads for ${key}`,\n );\n }\n const row = stored.get(key);\n const localCheckpoint = row ? { ...advance.head.checkpoint, ...row } : null;\n pending.set(key, validateAccessAdvance(advance, localCheckpoint));\n }\n\n return pending;\n}\n\nfunction extendsObservedPolicy(\n head: CheckpointPolicy,\n candidate: CheckpointPolicy,\n): boolean {\n const history =\n \"retainedHistory\" in head ? head.retainedHistory : head.history;\n return (\n history?.some(\n ({ state }) =>\n state.principalType === candidate.principalType &&\n state.principalId === candidate.principalId &&\n state.version === candidate.version &&\n state.stateHash === candidate.stateHash,\n ) ?? false\n );\n}\n\n/** The newest candidate, which must be unique and extend every other one. */\nfunction selectPrincipalPolicyHead(\n key: string,\n candidates: readonly CheckpointPolicy[],\n): CheckpointPolicy | null {\n const maxVersion = Math.max(...candidates.map((policy) => policy.version));\n const heads = candidates.filter((policy) => policy.version === maxVersion);\n const head = heads[0];\n if (!head) {\n return null;\n }\n if (heads.some((candidate) => candidate.stateHash !== head.stateHash)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `principal policy declares conflicting heads for ${key}`,\n );\n }\n for (const candidate of candidates) {\n if (candidate.version === head.version) {\n continue;\n }\n if (!extendsObservedPolicy(head, candidate)) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n `principal policy head does not extend observed state for ${key}`,\n );\n }\n }\n return head;\n}\n\n/**\n * Checks, inside the caller's transaction, that each principal's newest policy\n * extends every other candidate and its durable checkpoint. Returns the heads\n * to pin, keyed by principal.\n */\nexport async function validatePrincipalPolicyCheckpointAdvances(\n tx: ClientSQLiteTransactionScope,\n policies: readonly CheckpointPolicy[],\n): Promise<Map<string, CheckpointPolicy>> {\n const policiesByPrincipal = new Map<string, CheckpointPolicy[]>();\n for (const policy of policies) {\n const key = principalPolicyKey(policy);\n const candidates = policiesByPrincipal.get(key) ?? [];\n candidates.push(policy);\n policiesByPrincipal.set(key, candidates);\n }\n\n const pending = new Map<string, CheckpointPolicy>();\n const stored = await loadStoredPrincipalPolicyCheckpoints(tx, policies);\n for (const key of [...policiesByPrincipal.keys()].sort()) {\n const head = selectPrincipalPolicyHead(\n key,\n policiesByPrincipal.get(key) ?? [],\n );\n if (!head) {\n continue;\n }\n\n const localCheckpoint = stored.get(key) ?? null;\n verifyPrincipalPolicyCheckpoint({\n chain:\n \"retainedHistory\" in head ? head.retainedHistory : (head.history ?? []),\n currentState: head.state,\n localCheckpoint,\n });\n pending.set(key, head);\n }\n\n return pending;\n}\n\nasync function writeAccessCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, PendingAccessCheckpoint>,\n updatedAt: string,\n): Promise<void> {\n await upsertAccessManifestCheckpointsInTransaction(\n tx,\n [...pending.values()]\n .filter(({ changed }) => changed)\n .map(({ checkpoint }) => checkpoint),\n updatedAt,\n );\n}\n\n/** Pins the heads `validatePrincipalPolicyCheckpointAdvances` returned. */\nexport async function writePrincipalPolicyCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, CheckpointPolicy>,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n await upsertPrincipalPolicyCheckpointsInTransaction(\n tx,\n [...pending.values()].map((policy) => policy.checkpoint),\n updatedAt,\n organizationId,\n );\n}\n\n/** Every table a batch touches, ensured before its transaction begins. */\nexport function keyingCheckpointBatchTables(\n batch: KeyingCheckpointBatch,\n bundleRows: readonly VerifiedManifestBundleRow[],\n) {\n return [\n ...(batch.policies.length > 0 ||\n (batch.authorizationPolicies?.length ?? 0) > 0\n ? principalPolicyTables\n : []),\n ...keyingCheckpointTables,\n ...(bundleRows.length > 0 ? verifiedManifestBundleTables : []),\n ];\n}\n\n/**\n * Re-checks verified candidates against durable pins without advancing them.\n * Only the verified bundles' citation rows are written.\n */\nexport async function validateKeyingCheckpointsInTransaction(\n tx: ClientSQLiteTransactionScope,\n batch: KeyingCheckpointBatch,\n bundleRows: readonly VerifiedManifestBundleRow[],\n verifiedAt: string,\n): Promise<void> {\n await validateAccessAdvances(tx, batch.access);\n await validatePrincipalPolicyCheckpointAdvances(tx, batch.policies);\n await validatePrincipalAuthorizationCheckpoints(\n tx,\n batch.authorizationPolicies ?? [],\n );\n await writeVerifiedManifestBundlesInTransaction(tx, bundleRows, verifiedAt);\n}\n\n/**\n * Re-check every verified projection candidate against the latest durable pins\n * and advance the complete batch. Signature verification and remote fetching\n * happen before the short transaction this runs in; only checkpoint comparison\n * and persistence, with the batch's verified bundles, are serialized here.\n */\nexport async function advanceKeyingCheckpointsInTransaction(\n tx: ClientSQLiteTransactionScope,\n batch: KeyingCheckpointAdvanceBatch,\n bundleRows: readonly VerifiedManifestBundleRow[],\n updatedAt: string,\n): Promise<void> {\n const access = await validateAccessAdvances(tx, batch.access);\n const policies = await validatePrincipalPolicyCheckpointAdvances(\n tx,\n batch.policies,\n );\n await validatePrincipalAuthorizationCheckpoints(\n tx,\n batch.authorizationPolicies ?? [],\n );\n\n await writeAccessCheckpoints(tx, access, updatedAt);\n await writePrincipalPolicyCheckpoints(\n tx,\n policies,\n updatedAt,\n batch.organizationId,\n );\n if (batch.documentPurgeCheckpoint) {\n await storeDocumentPurgeCheckpointInTransaction(\n tx,\n batch.documentPurgeCheckpoint,\n updatedAt,\n );\n }\n await writeVerifiedManifestBundlesInTransaction(tx, bundleRows, updatedAt);\n}\n"]}
1
+ {"version":3,"file":"keyingCheckpointAdvancePersistence.js","sourceRoot":"","sources":["keyingCheckpointAdvancePersistence.ts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AAyC,CAC9D,EAAE,EACF,KAAK,CAAC,QAAQ,CACf,CAAC;IACF,MAAM,yCAAyC,CAC7C,EAAE,EACF,KAAK,CAAC,qBAAqB,IAAI,EAAE,CAClC,CAAC;IAEF,MAAM,sBAAsB,CAAC,EAAE,EAAE,MAAM,EAAE,SAAS,CAAC,CAAC;IACpD,MAAM,+BAA+B,CACnC,EAAE,EACF,QAAQ,EACR,SAAS,EACT,KAAK,CAAC,cAAc,CACrB,CAAC;IACF,IAAI,KAAK,CAAC,uBAAuB,EAAE,CAAC;QAClC,MAAM,yCAAyC,CAC7C,EAAE,EACF,KAAK,CAAC,uBAAuB,EAC7B,SAAS,CACV,CAAC;IACJ,CAAC;IACD,MAAM,yCAAyC,CAAC,EAAE,EAAE,UAAU,EAAE,SAAS,CAAC,CAAC;AAC7E,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n type AnyVerifiedPrincipalPolicy,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedPrincipalPolicyCurrent,\n type VerifiedPrincipalPolicySelection,\n verifyAccessManifestLocalCheckpoint,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport { keyingCheckpointTables } from \"../../sqlite/schema/keyingCheckpointSchema\";\nimport { principalPolicyTables } from \"../../sqlite/schema/principalPolicySchema\";\nimport { verifiedManifestBundleTables } from \"../../sqlite/schema/verifiedManifestBundleSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { loadContainerRetirementCheck } from \"../principalContracts/principalGrantRetirementPersistence\";\nimport {\n type VerifiedManifestBundle,\n type VerifiedManifestBundleRow,\n writeVerifiedManifestBundlesInTransaction,\n} from \"../verifiedManifestBundlePersistence\";\nimport {\n type DocumentPurgeCheckpoint,\n storeDocumentPurgeCheckpointInTransaction,\n} from \"./documentPurgeCheckpointPersistence\";\nimport { validateAccessManifestCheckpointEvidence } from \"./keyingCheckpointEvidence\";\nimport {\n accessManifestObjectKey,\n loadAccessManifestCheckpointRows,\n loadStoredPrincipalPolicyCheckpoints,\n principalPolicyKey,\n upsertAccessManifestCheckpointsInTransaction,\n upsertPrincipalPolicyCheckpointsInTransaction,\n} from \"./keyingCheckpointPersistence\";\nimport { validatePrincipalAuthorizationCheckpoints } from \"./principalAuthorizationCheckpoints\";\n\nexport interface AccessManifestCheckpointAdvance {\n readonly head: VerifiedAccessManifestCheckpointEvidence;\n readonly predecessors: readonly VerifiedAccessManifestCheckpointEvidence[];\n}\n\ntype CheckpointPolicy =\n | AnyVerifiedPrincipalPolicy\n | VerifiedPrincipalPolicyCurrent;\n\n/** A verified batch of checkpoint candidates; the repository supplies the executor. */\nexport interface KeyingCheckpointBatch {\n readonly access: readonly AccessManifestCheckpointAdvance[];\n readonly policies: readonly CheckpointPolicy[];\n readonly authorizationPolicies?:\n | readonly VerifiedPrincipalPolicySelection[]\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n /**\n * Bundles this projection verified. They are stored for later citation in\n * the same transaction, so they commit only with the batch they verified.\n */\n readonly verifiedBundles?: readonly VerifiedManifestBundle[] | undefined;\n}\n\nexport interface KeyingCheckpointAdvanceBatch extends KeyingCheckpointBatch {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly organizationId?: string | undefined;\n}\n\ninterface PendingAccessCheckpoint {\n readonly changed: boolean;\n readonly checkpoint: AccessManifestCheckpoint;\n}\n\nfunction validateAccessAdvance(\n advance: AccessManifestCheckpointAdvance,\n localCheckpoint: AccessManifestCheckpoint | null,\n): PendingAccessCheckpoint {\n const current = {\n ...advance.head.checkpoint,\n previousManifestHash: advance.head.manifest.previousManifestHash,\n };\n const predecessors = [...advance.predecessors].sort(\n (left, right) => left.checkpoint.epoch - right.checkpoint.epoch,\n );\n\n if (localCheckpoint && current.epoch <= localCheckpoint.epoch) {\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: undefined,\n });\n }\n\n validateAccessManifestCheckpointEvidence({\n head: advance.head,\n predecessors,\n localCheckpoint,\n });\n\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: predecessors.filter(\n (manifest) =>\n localCheckpoint !== null &&\n manifest.checkpoint.epoch > localCheckpoint.epoch &&\n manifest.checkpoint.epoch < current.epoch,\n ),\n });\n\n return {\n changed:\n localCheckpoint?.epoch !== current.epoch ||\n localCheckpoint.manifestHash !== current.manifestHash,\n checkpoint: advance.head.checkpoint,\n };\n}\n\nasync function validateAccessAdvances(\n tx: ClientSQLiteTransactionScope,\n advances: readonly AccessManifestCheckpointAdvance[],\n): Promise<Map<string, PendingAccessCheckpoint>> {\n const pending = new Map<string, PendingAccessCheckpoint>();\n if (advances.length === 0) return pending;\n // Set reads first; the checks then replay in order, so the same advance\n // fails first with the same error.\n const heads = advances.map((advance) => advance.head.checkpoint);\n const assertNotRetired = await loadContainerRetirementCheck(tx, heads);\n const stored = await loadAccessManifestCheckpointRows(tx, heads);\n\n for (const advance of advances) {\n assertNotRetired(advance.head.checkpoint);\n const key = accessManifestObjectKey(advance.head.checkpoint);\n if (pending.has(key)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `projection declares multiple access checkpoint heads for ${key}`,\n );\n }\n const row = stored.get(key);\n const localCheckpoint = row ? { ...advance.head.checkpoint, ...row } : null;\n pending.set(key, validateAccessAdvance(advance, localCheckpoint));\n }\n\n return pending;\n}\n\nfunction extendsObservedPolicy(\n head: CheckpointPolicy,\n candidate: CheckpointPolicy,\n): boolean {\n const history =\n \"retainedHistory\" in head ? head.retainedHistory : head.history;\n return (\n history?.some(\n ({ state }) =>\n state.principalType === candidate.principalType &&\n state.principalId === candidate.principalId &&\n state.version === candidate.version &&\n state.stateHash === candidate.stateHash,\n ) ?? false\n );\n}\n\n/** The newest candidate, which must be unique and extend every other one. */\nfunction selectPrincipalPolicyHead(\n key: string,\n candidates: readonly CheckpointPolicy[],\n): CheckpointPolicy | null {\n const maxVersion = Math.max(...candidates.map((policy) => policy.version));\n const heads = candidates.filter((policy) => policy.version === maxVersion);\n const head = heads[0];\n if (!head) {\n return null;\n }\n if (heads.some((candidate) => candidate.stateHash !== head.stateHash)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `principal policy declares conflicting heads for ${key}`,\n );\n }\n for (const candidate of candidates) {\n if (candidate.version === head.version) {\n continue;\n }\n if (!extendsObservedPolicy(head, candidate)) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n `principal policy head does not extend observed state for ${key}`,\n );\n }\n }\n return head;\n}\n\n/**\n * Checks, inside the caller's transaction, that each principal's newest policy\n * extends every other candidate and its durable checkpoint. Returns the heads\n * to pin, keyed by principal.\n */\nexport async function validatePrincipalPolicyCheckpointAdvances(\n tx: ClientSQLiteTransactionScope,\n policies: readonly CheckpointPolicy[],\n): Promise<Map<string, CheckpointPolicy>> {\n const policiesByPrincipal = new Map<string, CheckpointPolicy[]>();\n for (const policy of policies) {\n const key = principalPolicyKey(policy);\n const candidates = policiesByPrincipal.get(key) ?? [];\n candidates.push(policy);\n policiesByPrincipal.set(key, candidates);\n }\n\n const pending = new Map<string, CheckpointPolicy>();\n const stored = await loadStoredPrincipalPolicyCheckpoints(tx, policies);\n for (const key of [...policiesByPrincipal.keys()].sort()) {\n const head = selectPrincipalPolicyHead(\n key,\n policiesByPrincipal.get(key) ?? [],\n );\n if (!head) {\n continue;\n }\n\n const localCheckpoint = stored.get(key) ?? null;\n verifyPrincipalPolicyCheckpoint({\n chain:\n \"retainedHistory\" in head ? head.retainedHistory : (head.history ?? []),\n currentState: head.state,\n localCheckpoint,\n });\n pending.set(key, head);\n }\n\n return pending;\n}\n\nasync function writeAccessCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, PendingAccessCheckpoint>,\n updatedAt: string,\n): Promise<void> {\n await upsertAccessManifestCheckpointsInTransaction(\n tx,\n [...pending.values()]\n .filter(({ changed }) => changed)\n .map(({ checkpoint }) => checkpoint),\n updatedAt,\n );\n}\n\n/** Pins the heads `validatePrincipalPolicyCheckpointAdvances` returned. */\nexport async function writePrincipalPolicyCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, CheckpointPolicy>,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n await upsertPrincipalPolicyCheckpointsInTransaction(\n tx,\n [...pending.values()].map((policy) => policy.checkpoint),\n updatedAt,\n organizationId,\n );\n}\n\n/** Every table a batch touches, ensured before its transaction begins. */\nexport function keyingCheckpointBatchTables(\n batch: KeyingCheckpointBatch,\n bundleRows: readonly VerifiedManifestBundleRow[],\n) {\n return [\n ...(batch.policies.length > 0 ||\n (batch.authorizationPolicies?.length ?? 0) > 0\n ? principalPolicyTables\n : []),\n ...keyingCheckpointTables,\n ...(bundleRows.length > 0 ? verifiedManifestBundleTables : []),\n ];\n}\n\n/**\n * Re-checks verified candidates against durable pins without advancing them.\n * Only the verified bundles' citation rows are written.\n */\nexport async function validateKeyingCheckpointsInTransaction(\n tx: ClientSQLiteTransactionScope,\n batch: KeyingCheckpointBatch,\n bundleRows: readonly VerifiedManifestBundleRow[],\n verifiedAt: string,\n): Promise<void> {\n await validateAccessAdvances(tx, batch.access);\n await validatePrincipalPolicyCheckpointAdvances(tx, batch.policies);\n await validatePrincipalAuthorizationCheckpoints(\n tx,\n batch.authorizationPolicies ?? [],\n );\n await writeVerifiedManifestBundlesInTransaction(tx, bundleRows, verifiedAt);\n}\n\n/**\n * Re-check every verified projection candidate against the latest durable pins\n * and advance the complete batch. Signature verification and remote fetching\n * happen before the short transaction this runs in; only checkpoint comparison\n * and persistence, with the batch's verified bundles, are serialized here.\n */\nexport async function advanceKeyingCheckpointsInTransaction(\n tx: ClientSQLiteTransactionScope,\n batch: KeyingCheckpointAdvanceBatch,\n bundleRows: readonly VerifiedManifestBundleRow[],\n updatedAt: string,\n): Promise<void> {\n const access = await validateAccessAdvances(tx, batch.access);\n const policies = await validatePrincipalPolicyCheckpointAdvances(\n tx,\n batch.policies,\n );\n await validatePrincipalAuthorizationCheckpoints(\n tx,\n batch.authorizationPolicies ?? [],\n );\n\n await writeAccessCheckpoints(tx, access, updatedAt);\n await writePrincipalPolicyCheckpoints(\n tx,\n policies,\n updatedAt,\n batch.organizationId,\n );\n if (batch.documentPurgeCheckpoint) {\n await storeDocumentPurgeCheckpointInTransaction(\n tx,\n batch.documentPurgeCheckpoint,\n updatedAt,\n );\n }\n await writeVerifiedManifestBundlesInTransaction(tx, bundleRows, updatedAt);\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { accessManifestCheckpointFromManifest, KeyingVerificationError, verifyAccessManifestLocalCheckpoint, } from "../../../internal/crypto/index.js";
2
- import { loadContainerRetirementCheck } from "../principalKeys/principalGrantRetirementPersistence.js";
2
+ import { loadContainerRetirementCheck } from "../principalContracts/principalGrantRetirementPersistence.js";
3
3
  import { accessManifestObjectKey, loadAccessManifestCheckpointRows, loadPrincipalPolicyCheckpointRows, principalPolicyKey, storedPrincipalPolicyPin, upsertAccessManifestCheckpointsInTransaction, } from "./keyingCheckpointPersistence.js";
4
4
  export function locallyAuthoredAccessManifestHead(plan) {
5
5
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"locallyAcknowledgedCheckpointPersistence.js","sourceRoot":"","sources":["locallyAcknowledgedCheckpointPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,oCAAoC,EACpC,uBAAuB,EAEvB,mCAAmC,GACpC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,4BAA4B,EAAE,MAAM,sDAAsD,CAAC;AACpG,OAAO,EACL,uBAAuB,EACvB,gCAAgC,EAChC,iCAAiC,EACjC,kBAAkB,EAClB,wBAAwB,EACxB,4CAA4C,GAC7C,MAAM,+BAA+B,CAAC;AAOvC,MAAM,UAAU,iCAAiC,CAAC,IAGjD;IACC,OAAO;QACL,UAAU,EAAE,oCAAoC,CAAC;YAC/C,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB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AkB,CAAC,QAAQ,CAAC,CAAC,CAC3C,CAAC;QACF,IACE,OAAO,EAAE,OAAO,KAAK,QAAQ,CAAC,OAAO;YACrC,OAAO,CAAC,SAAS,KAAK,QAAQ,CAAC,SAAS,EACxC,CAAC;YACD,MAAM,IAAI,uBAAuB,CAC/B,mBAAmB,EACnB,0EAA0E,CAC3E,CAAC;QACJ,CAAC;IACH,CAAC;IACD,MAAM,OAAO,GAAG,MAAM,yBAAyB,CAAC,EAAE,EAAE,OAAO,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC3E,MAAM,4CAA4C,CAChD,EAAE,EACF,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EACrB,SAAS,CACV,CAAC;AACJ,CAAC","sourcesContent":["import {\n type AccessManifest,\n type AccessManifestCheckpoint,\n accessManifestCheckpointFromManifest,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n verifyAccessManifestLocalCheckpoint,\n} from \"@tearleads/crypto\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { loadContainerRetirementCheck } from \"../principalKeys/principalGrantRetirementPersistence\";\nimport {\n accessManifestObjectKey,\n loadAccessManifestCheckpointRows,\n loadPrincipalPolicyCheckpointRows,\n principalPolicyKey,\n storedPrincipalPolicyPin,\n upsertAccessManifestCheckpointsInTransaction,\n} from \"./keyingCheckpointPersistence\";\n\nexport interface LocallyAcknowledgedAccessManifestHead {\n readonly checkpoint: AccessManifestCheckpoint;\n readonly previousManifestHash: string | null;\n}\n\nexport function locallyAuthoredAccessManifestHead(plan: {\n readonly manifest: AccessManifest;\n readonly manifestHash: string;\n}): LocallyAcknowledgedAccessManifestHead {\n return {\n checkpoint: accessManifestCheckpointFromManifest({\n manifest: plan.manifest,\n manifestHash: plan.manifestHash,\n }),\n previousManifestHash: plan.manifest.previousManifestHash,\n };\n}\n\nfunction validateAcknowledgedHead(\n head: LocallyAcknowledgedAccessManifestHead,\n localCheckpoint: AccessManifestCheckpoint | null,\n): void {\n if (!localCheckpoint) {\n if (head.checkpoint.epoch !== 1 || head.previousManifestHash !== null) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"locally acknowledged access manifest does not begin at epoch 1\",\n );\n }\n return;\n }\n\n verifyAccessManifestLocalCheckpoint({\n checkpointPredecessors: [],\n current: {\n ...head.checkpoint,\n previousManifestHash: head.previousManifestHash,\n },\n localCheckpoint,\n });\n}\n\nasync function validateAcknowledgedHeads(\n tx: ClientSQLiteTransactionScope,\n heads: readonly LocallyAcknowledgedAccessManifestHead[],\n stored: Awaited<ReturnType<typeof loadAccessManifestCheckpointRows>>,\n): Promise<Map<string, AccessManifestCheckpoint>> {\n const pending = new Map<string, AccessManifestCheckpoint>();\n const assertNotRetired = await loadContainerRetirementCheck(\n tx,\n heads.map((head) => head.checkpoint),\n );\n for (const head of heads) {\n assertNotRetired(head.checkpoint);\n const key = accessManifestObjectKey(head.checkpoint);\n if (pending.has(key)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `locally acknowledged batch contains multiple heads for ${key}`,\n );\n }\n const row = stored.get(key);\n validateAcknowledgedHead(head, row ? { ...head.checkpoint, ...row } : null);\n pending.set(key, head.checkpoint);\n }\n return pending;\n}\n\n/** Heads this client authored, with the pins its plan read. */\nexport interface LocallyAcknowledgedAdvance {\n readonly heads: readonly LocallyAcknowledgedAccessManifestHead[];\n /** Optional optimistic read dependencies, checked inside the write transaction. */\n readonly expectedAccessManifestCheckpoints?: readonly AccessManifestCheckpoint[];\n readonly expectedPrincipalPolicyCheckpoints?: readonly PrincipalPolicyCheckpoint[];\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\n/**\n * Commits only heads authored and signed by this client after an exact remote\n * acknowledgement check. Every non-initial head must directly extend the\n * latest durable pin; arbitrary remote projections must use the verified\n * projection checkpoint path instead.\n */\nexport async function acknowledgeLocallyAuthoredHeadsInTransaction(\n tx: ClientSQLiteTransactionScope,\n advance: LocallyAcknowledgedAdvance,\n updatedAt: string,\n): Promise<void> {\n const expectedAccess = advance.expectedAccessManifestCheckpoints ?? [];\n const expectedPolicies = advance.expectedPrincipalPolicyCheckpoints ?? [];\n const stored = await loadAccessManifestCheckpointRows(tx, [\n ...advance.heads.map((head) => head.checkpoint),\n ...expectedAccess,\n ]);\n for (const expected of expectedAccess) {\n const current = stored.get(accessManifestObjectKey(expected));\n if (\n current?.epoch !== expected.epoch ||\n current.manifestHash !== expected.manifestHash\n ) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"A re-citation container checkpoint changed before acknowledgement\",\n );\n }\n }\n const policies = await loadPrincipalPolicyCheckpointRows(\n tx,\n expectedPolicies,\n );\n for (const expected of expectedPolicies) {\n const current = storedPrincipalPolicyPin(\n policies.get(principalPolicyKey(expected)),\n );\n if (\n current?.version !== expected.version ||\n current.stateHash !== expected.stateHash\n ) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"A re-citation principal policy checkpoint changed before acknowledgement\",\n );\n }\n }\n const pending = await validateAcknowledgedHeads(tx, advance.heads, stored);\n await upsertAccessManifestCheckpointsInTransaction(\n tx,\n [...pending.values()],\n updatedAt,\n );\n}\n"]}
1
+ {"version":3,"file":"locallyAcknowledgedCheckpointPersistence.js","sourceRoot":"","sources":["locallyAcknowledgedCheckpointPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,oCAAoC,EACpC,uBAAuB,EAEvB,mCAAmC,GACpC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,4BAA4B,EAAE,MAAM,2DAA2D,CAAC;AACzG,OAAO,EACL,uBAAuB,EACvB,gCAAgC,EAChC,iCAAiC,EACjC,kBAAkB,EAClB,wBAAwB,EACxB,4CAA4C,GAC7C,MAAM,+BAA+B,CAAC;AAOvC,MAAM,UAAU,iCAAiC,CAAC,IAGjD;IACC,OAAO;QACL,UAAU,EAAE,oCAAoC,CAAC;YAC/C,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,YAAY,EAAE,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AQ,CAAC,CAAC,CAC3C,CAAC;QACF,IACE,OAAO,EAAE,OAAO,KAAK,QAAQ,CAAC,OAAO;YACrC,OAAO,CAAC,SAAS,KAAK,QAAQ,CAAC,SAAS,EACxC,CAAC;YACD,MAAM,IAAI,uBAAuB,CAC/B,mBAAmB,EACnB,0EAA0E,CAC3E,CAAC;QACJ,CAAC;IACH,CAAC;IACD,MAAM,OAAO,GAAG,MAAM,yBAAyB,CAAC,EAAE,EAAE,OAAO,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IAC3E,MAAM,4CAA4C,CAChD,EAAE,EACF,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EACrB,SAAS,CACV,CAAC;AACJ,CAAC","sourcesContent":["import {\n type AccessManifest,\n type AccessManifestCheckpoint,\n accessManifestCheckpointFromManifest,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n verifyAccessManifestLocalCheckpoint,\n} from \"@tearleads/crypto\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { loadContainerRetirementCheck } from \"../principalContracts/principalGrantRetirementPersistence\";\nimport {\n accessManifestObjectKey,\n loadAccessManifestCheckpointRows,\n loadPrincipalPolicyCheckpointRows,\n principalPolicyKey,\n storedPrincipalPolicyPin,\n upsertAccessManifestCheckpointsInTransaction,\n} from \"./keyingCheckpointPersistence\";\n\nexport interface LocallyAcknowledgedAccessManifestHead {\n readonly checkpoint: AccessManifestCheckpoint;\n readonly previousManifestHash: string | null;\n}\n\nexport function locallyAuthoredAccessManifestHead(plan: {\n readonly manifest: AccessManifest;\n readonly manifestHash: string;\n}): LocallyAcknowledgedAccessManifestHead {\n return {\n checkpoint: accessManifestCheckpointFromManifest({\n manifest: plan.manifest,\n manifestHash: plan.manifestHash,\n }),\n previousManifestHash: plan.manifest.previousManifestHash,\n };\n}\n\nfunction validateAcknowledgedHead(\n head: LocallyAcknowledgedAccessManifestHead,\n localCheckpoint: AccessManifestCheckpoint | null,\n): void {\n if (!localCheckpoint) {\n if (head.checkpoint.epoch !== 1 || head.previousManifestHash !== null) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"locally acknowledged access manifest does not begin at epoch 1\",\n );\n }\n return;\n }\n\n verifyAccessManifestLocalCheckpoint({\n checkpointPredecessors: [],\n current: {\n ...head.checkpoint,\n previousManifestHash: head.previousManifestHash,\n },\n localCheckpoint,\n });\n}\n\nasync function validateAcknowledgedHeads(\n tx: ClientSQLiteTransactionScope,\n heads: readonly LocallyAcknowledgedAccessManifestHead[],\n stored: Awaited<ReturnType<typeof loadAccessManifestCheckpointRows>>,\n): Promise<Map<string, AccessManifestCheckpoint>> {\n const pending = new Map<string, AccessManifestCheckpoint>();\n const assertNotRetired = await loadContainerRetirementCheck(\n tx,\n heads.map((head) => head.checkpoint),\n );\n for (const head of heads) {\n assertNotRetired(head.checkpoint);\n const key = accessManifestObjectKey(head.checkpoint);\n if (pending.has(key)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `locally acknowledged batch contains multiple heads for ${key}`,\n );\n }\n const row = stored.get(key);\n validateAcknowledgedHead(head, row ? { ...head.checkpoint, ...row } : null);\n pending.set(key, head.checkpoint);\n }\n return pending;\n}\n\n/** Heads this client authored, with the pins its plan read. */\nexport interface LocallyAcknowledgedAdvance {\n readonly heads: readonly LocallyAcknowledgedAccessManifestHead[];\n /** Optional optimistic read dependencies, checked inside the write transaction. */\n readonly expectedAccessManifestCheckpoints?: readonly AccessManifestCheckpoint[];\n readonly expectedPrincipalPolicyCheckpoints?: readonly PrincipalPolicyCheckpoint[];\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\n/**\n * Commits only heads authored and signed by this client after an exact remote\n * acknowledgement check. Every non-initial head must directly extend the\n * latest durable pin; arbitrary remote projections must use the verified\n * projection checkpoint path instead.\n */\nexport async function acknowledgeLocallyAuthoredHeadsInTransaction(\n tx: ClientSQLiteTransactionScope,\n advance: LocallyAcknowledgedAdvance,\n updatedAt: string,\n): Promise<void> {\n const expectedAccess = advance.expectedAccessManifestCheckpoints ?? [];\n const expectedPolicies = advance.expectedPrincipalPolicyCheckpoints ?? [];\n const stored = await loadAccessManifestCheckpointRows(tx, [\n ...advance.heads.map((head) => head.checkpoint),\n ...expectedAccess,\n ]);\n for (const expected of expectedAccess) {\n const current = stored.get(accessManifestObjectKey(expected));\n if (\n current?.epoch !== expected.epoch ||\n current.manifestHash !== expected.manifestHash\n ) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"A re-citation container checkpoint changed before acknowledgement\",\n );\n }\n }\n const policies = await loadPrincipalPolicyCheckpointRows(\n tx,\n expectedPolicies,\n );\n for (const expected of expectedPolicies) {\n const current = storedPrincipalPolicyPin(\n policies.get(principalPolicyKey(expected)),\n );\n if (\n current?.version !== expected.version ||\n current.stateHash !== expected.stateHash\n ) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"A re-citation principal policy checkpoint changed before acknowledgement\",\n );\n }\n }\n const pending = await validateAcknowledgedHeads(tx, advance.heads, stored);\n await upsertAccessManifestCheckpointsInTransaction(\n tx,\n [...pending.values()],\n updatedAt,\n );\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
- import { assertContainerNotRetired } from "../principalKeys/principalGrantRetirementPersistence.js";
2
+ import { assertContainerNotRetired } from "../principalContracts/principalGrantRetirementPersistence.js";
3
3
  import { loadStoredAccessManifestCheckpoint, loadStoredPrincipalPolicyCheckpoint, upsertAccessManifestCheckpointInTransaction, upsertPrincipalPolicyCheckpointInTransaction, } from "./keyingCheckpointPersistence.js";
4
4
  import { recordPrincipalPolicyOrganizationInTransaction } from "./principalPolicyOrganizationPersistence.js";
5
5
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"organizationReplacementCheckpointPersistence.js","sourceRoot":"","sources":["organizationReplacementCheckpointPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAGxB,MAAM,mBAA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AC/D,CAAC;IACJ,IAAI,CAAC,UAAU;QACb,MAAM,2CAA2C,CAAC,EAAE,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC;IACzE,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACnC,MAAM,8CAA8C,CAAC,EAAE,EAAE;YACvD,WAAW,EAAE,SAAS,CAAC,WAAW;YAClC,aAAa,EAAE,SAAS,CAAC,aAAa;YACtC,cAAc;SACf,CAAC,CAAC;QACH,MAAM,MAAM,GAAG,MAAM,mCAAmC,CAAC,EAAE,EAAE,SAAS,CAAC,CAAC;QACxE,IAAI,MAAM,EAAE,OAAO,KAAK,CAAC,IAAI,MAAM,CAAC,SAAS,KAAK,SAAS,CAAC,SAAS;YACnE,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,gEAAgE,CACjE,CAAC;QACJ,IAAI,CAAC,MAAM;YACT,MAAM,4CAA4C,CAChD,EAAE,EACF,SAAS,EACT,SAAS,EACT,cAAc,CACf,CAAC;IACN,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedOrganizationReplacementAuthorization,\n} from \"@tearleads/crypto\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { assertContainerNotRetired } from \"../principalKeys/principalGrantRetirementPersistence\";\nimport {\n loadStoredAccessManifestCheckpoint,\n loadStoredPrincipalPolicyCheckpoint,\n upsertAccessManifestCheckpointInTransaction,\n upsertPrincipalPolicyCheckpointInTransaction,\n} from \"./keyingCheckpointPersistence\";\nimport { recordPrincipalPolicyOrganizationInTransaction } from \"./principalPolicyOrganizationPersistence\";\n\n/**\n * A verified authorization from this identity also authenticates the winning\n * device's genesis. Seed first-sight pins before adopting its IDs; retain any\n * later observations rather than rolling them back to the provisioning epoch.\n */\nexport async function seedOrganizationReplacementCheckpointsInTransaction(\n tx: ClientSQLiteTransactionScope,\n authorization: VerifiedOrganizationReplacementAuthorization,\n updatedAt: string,\n): Promise<void> {\n const organizationId = authorization.organizationId;\n const root: AccessManifestCheckpoint = {\n objectKind: \"container\",\n objectId: authorization.rootContainerId,\n organizationId,\n epoch: 1,\n manifestHash: authorization.rootManifestHash,\n };\n const principals: PrincipalPolicyCheckpoint[] = [\n {\n principalType: \"organization\",\n principalId: organizationId,\n version: 1,\n stateHash: authorization.organizationStateHash,\n },\n {\n principalType: \"group\",\n principalId: authorization.adminGroupId,\n version: 1,\n stateHash: authorization.adminGroupStateHash,\n },\n {\n principalType: \"group\",\n principalId: authorization.memberGroupId,\n version: 1,\n stateHash: authorization.memberGroupStateHash,\n },\n ];\n await assertContainerNotRetired(tx, root);\n const storedRoot = await loadStoredAccessManifestCheckpoint(tx, root);\n if (storedRoot?.epoch === 1 && storedRoot.manifestHash !== root.manifestHash)\n throw new KeyingVerificationError(\n \"equivocation\",\n \"Replacement root conflicts with its local genesis checkpoint\",\n );\n if (!storedRoot)\n await upsertAccessManifestCheckpointInTransaction(tx, root, updatedAt);\n for (const principal of principals) {\n await recordPrincipalPolicyOrganizationInTransaction(tx, {\n principalId: principal.principalId,\n principalType: principal.principalType,\n organizationId,\n });\n const stored = await loadStoredPrincipalPolicyCheckpoint(tx, principal);\n if (stored?.version === 1 && stored.stateHash !== principal.stateHash)\n throw new KeyingVerificationError(\n \"equivocation\",\n \"Replacement policy conflicts with its local genesis checkpoint\",\n );\n if (!stored)\n await upsertPrincipalPolicyCheckpointInTransaction(\n tx,\n principal,\n updatedAt,\n organizationId,\n );\n }\n}\n"]}
1
+ {"version":3,"file":"organizationReplacementCheckpointPersistence.js","sourceRoot":"","sources":["organizationReplacementCheckpointPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,2DAA2D,CAAC;AACtG,OAAO,EACL,kCAAkC,EAClC,mCAAmC,EACnC,2CAA2C,EA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,SAAS,IAAI,UAAU,EAAE,CAAC;QACnC,MAAM,8CAA8C,CAAC,EAAE,EAAE;YACvD,WAAW,EAAE,SAAS,CAAC,WAAW;YAClC,aAAa,EAAE,SAAS,CAAC,aAAa;YACtC,cAAc;SACf,CAAC,CAAC;QACH,MAAM,MAAM,GAAG,MAAM,mCAAmC,CAAC,EAAE,EAAE,SAAS,CAAC,CAAC;QACxE,IAAI,MAAM,EAAE,OAAO,KAAK,CAAC,IAAI,MAAM,CAAC,SAAS,KAAK,SAAS,CAAC,SAAS;YACnE,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,gEAAgE,CACjE,CAAC;QACJ,IAAI,CAAC,MAAM;YACT,MAAM,4CAA4C,CAChD,EAAE,EACF,SAAS,EACT,SAAS,EACT,cAAc,CACf,CAAC;IACN,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedOrganizationReplacementAuthorization,\n} from \"@tearleads/crypto\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { assertContainerNotRetired } from \"../principalContracts/principalGrantRetirementPersistence\";\nimport {\n loadStoredAccessManifestCheckpoint,\n loadStoredPrincipalPolicyCheckpoint,\n upsertAccessManifestCheckpointInTransaction,\n upsertPrincipalPolicyCheckpointInTransaction,\n} from \"./keyingCheckpointPersistence\";\nimport { recordPrincipalPolicyOrganizationInTransaction } from \"./principalPolicyOrganizationPersistence\";\n\n/**\n * A verified authorization from this identity also authenticates the winning\n * device's genesis. Seed first-sight pins before adopting its IDs; retain any\n * later observations rather than rolling them back to the provisioning epoch.\n */\nexport async function seedOrganizationReplacementCheckpointsInTransaction(\n tx: ClientSQLiteTransactionScope,\n authorization: VerifiedOrganizationReplacementAuthorization,\n updatedAt: string,\n): Promise<void> {\n const organizationId = authorization.organizationId;\n const root: AccessManifestCheckpoint = {\n objectKind: \"container\",\n objectId: authorization.rootContainerId,\n organizationId,\n epoch: 1,\n manifestHash: authorization.rootManifestHash,\n };\n const principals: PrincipalPolicyCheckpoint[] = [\n {\n principalType: \"organization\",\n principalId: organizationId,\n version: 1,\n stateHash: authorization.organizationStateHash,\n },\n {\n principalType: \"group\",\n principalId: authorization.adminGroupId,\n version: 1,\n stateHash: authorization.adminGroupStateHash,\n },\n {\n principalType: \"group\",\n principalId: authorization.memberGroupId,\n version: 1,\n stateHash: authorization.memberGroupStateHash,\n },\n ];\n await assertContainerNotRetired(tx, root);\n const storedRoot = await loadStoredAccessManifestCheckpoint(tx, root);\n if (storedRoot?.epoch === 1 && storedRoot.manifestHash !== root.manifestHash)\n throw new KeyingVerificationError(\n \"equivocation\",\n \"Replacement root conflicts with its local genesis checkpoint\",\n );\n if (!storedRoot)\n await upsertAccessManifestCheckpointInTransaction(tx, root, updatedAt);\n for (const principal of principals) {\n await recordPrincipalPolicyOrganizationInTransaction(tx, {\n principalId: principal.principalId,\n principalType: principal.principalType,\n organizationId,\n });\n const stored = await loadStoredPrincipalPolicyCheckpoint(tx, principal);\n if (stored?.version === 1 && stored.stateHash !== principal.stateHash)\n throw new KeyingVerificationError(\n \"equivocation\",\n \"Replacement policy conflicts with its local genesis checkpoint\",\n );\n if (!stored)\n await upsertPrincipalPolicyCheckpointInTransaction(\n tx,\n principal,\n updatedAt,\n organizationId,\n );\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { KeyingVerificationError, } from "../../internal/crypto/index.js";
2
2
  import { eq } from "drizzle-orm";
3
- import { principalPolicyEvidenceEntries } from "../principals/principalPolicyEvidence.js";
3
+ import { principalPolicyEvidenceEntries } from "../principalContracts/principalPolicyEvidence.js";
4
4
  import { keyingCheckpointTables } from "../sqlite/schema/keyingCheckpointSchema.js";
5
5
  import { organizationFounders } from "../sqlite/schema/organizationFounderSchema.js";
6
6
  import { getClientSQLitePersistenceRuntime } from "../sqlite/sqlitePersistenceRuntime.js";
@@ -1 +1 @@
1
- {"version":3,"file":"organizationF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AAC;aACf,mBAAmB,EAAE;aACrB,GAAG,EAAE,CAAC;IACX,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyAuthorization,\n} from \"@tearleads/crypto\";\nimport { eq } from \"drizzle-orm\";\nimport { principalPolicyEvidenceEntries } from \"../principals/principalPolicyEvidence\";\nimport { keyingCheckpointTables } from \"../sqlite/schema/keyingCheckpointSchema\";\nimport { organizationFounders } from \"../sqlite/schema/organizationFounderSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\n\nfunction assertSameFounder(\n stored: typeof organizationFounders.$inferSelect,\n founder: typeof organizationFounders.$inferInsert,\n): void {\n if (\n stored.userId !== founder.userId ||\n stored.signingKeyFingerprint !== founder.signingKeyFingerprint ||\n stored.genesisStateHash !== founder.genesisStateHash\n )\n throw new KeyingVerificationError(\n \"equivocation\",\n \"Organization founder conflicts with its durable genesis binding\",\n );\n}\n\nexport async function loadOrganizationFounder(\n execSql: ExecSql,\n organizationId: string,\n): Promise<typeof organizationFounders.$inferSelect | null> {\n await ensureSqlTables(execSql, keyingCheckpointTables);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const [stored] = await runtime.db\n .select()\n .from(organizationFounders)\n .where(eq(organizationFounders.organizationId, organizationId))\n .limit(1);\n return stored ?? null;\n}\n\n/** Pin verified genesis, never a later administrator or a folder's creator. */\nexport async function rememberOrganizationFounder(input: {\n readonly execSql: ExecSql;\n readonly organization: PrincipalPolicyAuthorization;\n}): Promise<void> {\n const genesis = principalPolicyEvidenceEntries(input.organization).find(\n ({ state }) => state.version === 1,\n )?.state;\n if (\n genesis?.principalType !== \"organization\" ||\n genesis.prevStateHash !== null\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization founder requires verified genesis\",\n );\n const founder = {\n organizationId: genesis.principalId,\n userId: genesis.signerUserId,\n signingKeyFingerprint: genesis.signerUserKeyFingerprint,\n genesisStateHash: genesis.stateHash,\n };\n const held = await loadOrganizationFounder(\n input.execSql,\n founder.organizationId,\n );\n if (held) {\n assertSameFounder(held, founder);\n return;\n }\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n await runtime.transaction(\n async (tx) => {\n const [stored] = await tx\n .select()\n .from(organizationFounders)\n .where(eq(organizationFounders.organizationId, founder.organizationId))\n .limit(1);\n if (stored) {\n assertSameFounder(stored, founder);\n return;\n }\n await tx\n .insert(organizationFounders)\n .values(founder)\n .onConflictDoNothing()\n .run();\n },\n { behavior: \"immediate\" },\n );\n}\n"]}
1
+ {"version":3,"file":"organizationFounderPersistence.js","sourceRoot":"","sources":["organizationFounderPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,8BAA8B,EAAE,MAAM,+CAA+C,CAAC;AAC/F,OAAO,EAAE,sBAAsB,EAAE,MAAM,yCAAyC,CAAC;AACjF,OAAO,EAAE,oBAAoB,EAAE,MAAM,4CAA4C,CAAC;AAClF,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEpE,SAAS,iBAAiB,CACxB,MAAgD,EAChD,OAAiD;IAEjD,IACE,MAAM,CAAC,MAAM,KAAK,OAAO,CAAC,MAAM;QAChC,MAAM,CAAC,qBAAqB,KAAK,OAAO,CAAC,qBAAqB;QAC9D,MAAM,CAAC,gBAAgB,KAAK,OAAO,CAAC,gBAAgB;QAEpD,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,iEAAiE,CAClE,CAAC;AACN,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAC3C,OAAgB,EAChB,cA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IACjE,MAAM,OAAO,CAAC,WAAW,CACvB,KAAK,EAAE,EAAE,EAAE,EAAE;QACX,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,EAAE;aACtB,MAAM,EAAE;aACR,IAAI,CAAC,oBAAoB,CAAC;aAC1B,KAAK,CAAC,EAAE,CAAC,oBAAoB,CAAC,cAAc,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC;aACtE,KAAK,CAAC,CAAC,CAAC,CAAC;QACZ,IAAI,MAAM,EAAE,CAAC;YACX,iBAAiB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;YACnC,OAAO;QACT,CAAC;QACD,MAAM,EAAE;aACL,MAAM,CAAC,oBAAoB,CAAC;aAC5B,MAAM,CAAC,OAAO,CAAC;aACf,mBAAmB,EAAE;aACrB,GAAG,EAAE,CAAC;IACX,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyAuthorization,\n} from \"@tearleads/crypto\";\nimport { eq } from \"drizzle-orm\";\nimport { principalPolicyEvidenceEntries } from \"../principalContracts/principalPolicyEvidence\";\nimport { keyingCheckpointTables } from \"../sqlite/schema/keyingCheckpointSchema\";\nimport { organizationFounders } from \"../sqlite/schema/organizationFounderSchema\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\n\nfunction assertSameFounder(\n stored: typeof organizationFounders.$inferSelect,\n founder: typeof organizationFounders.$inferInsert,\n): void {\n if (\n stored.userId !== founder.userId ||\n stored.signingKeyFingerprint !== founder.signingKeyFingerprint ||\n stored.genesisStateHash !== founder.genesisStateHash\n )\n throw new KeyingVerificationError(\n \"equivocation\",\n \"Organization founder conflicts with its durable genesis binding\",\n );\n}\n\nexport async function loadOrganizationFounder(\n execSql: ExecSql,\n organizationId: string,\n): Promise<typeof organizationFounders.$inferSelect | null> {\n await ensureSqlTables(execSql, keyingCheckpointTables);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const [stored] = await runtime.db\n .select()\n .from(organizationFounders)\n .where(eq(organizationFounders.organizationId, organizationId))\n .limit(1);\n return stored ?? null;\n}\n\n/** Pin verified genesis, never a later administrator or a folder's creator. */\nexport async function rememberOrganizationFounder(input: {\n readonly execSql: ExecSql;\n readonly organization: PrincipalPolicyAuthorization;\n}): Promise<void> {\n const genesis = principalPolicyEvidenceEntries(input.organization).find(\n ({ state }) => state.version === 1,\n )?.state;\n if (\n genesis?.principalType !== \"organization\" ||\n genesis.prevStateHash !== null\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization founder requires verified genesis\",\n );\n const founder = {\n organizationId: genesis.principalId,\n userId: genesis.signerUserId,\n signingKeyFingerprint: genesis.signerUserKeyFingerprint,\n genesisStateHash: genesis.stateHash,\n };\n const held = await loadOrganizationFounder(\n input.execSql,\n founder.organizationId,\n );\n if (held) {\n assertSameFounder(held, founder);\n return;\n }\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n await runtime.transaction(\n async (tx) => {\n const [stored] = await tx\n .select()\n .from(organizationFounders)\n .where(eq(organizationFounders.organizationId, founder.organizationId))\n .limit(1);\n if (stored) {\n assertSameFounder(stored, founder);\n return;\n }\n await tx\n .insert(organizationFounders)\n .values(founder)\n .onConflictDoNothing()\n .run();\n },\n { behavior: \"immediate\" },\n );\n}\n"]}
@@ -3,11 +3,11 @@ import { eq } from "drizzle-orm";
3
3
  import { principalHistoryPrefixes } from "../sqlite/schema/principalHistoryEvidenceSchema.js";
4
4
  import { principalHistoryStages } from "../sqlite/schema/principalHistoryStageSchema.js";
5
5
  import { loadStoredPrincipalPolicyCheckpoint, principalPolicyKey, upsertPrincipalPolicyCheckpointInTransaction, } from "./keyingCheckpoints/keyingCheckpointPersistence.js";
6
+ import { storePrincipalGrantRetirements } from "./principalContracts/principalGrantRetirementPersistence.js";
6
7
  import { writePrincipalHistoryEvidencePage, } from "./principalHistory/principalHistoryEvidencePersistence.js";
7
8
  import { reclaimPrincipalHistoryNodes } from "./principalHistory/principalHistoryNodeRetention.js";
8
9
  import { principalHistoryPrefixRootOwnerColumns, principalHistoryRootRetention, principalHistoryStageRootOwnerColumns, writePrincipalHistoryRootEdges, } from "./principalHistory/principalHistoryRootOwnership.js";
9
10
  import { reclaimCompletedPrincipalHistoryStages, touchPrincipalHistoryStage, } from "./principalHistory/principalHistoryStageRetention.js";
10
- import { storePrincipalGrantRetirements } from "./principalKeys/principalGrantRetirementPersistence.js";
11
11
  import { archivePrincipalHistoryKeyEnvelopes } from "./principalKeys/principalKeyEnvelopeArchivePersistence.js";
12
12
  /** A local writer won the CAS; retry the same authenticated receipt without HTTP. */
13
13
  export class PrincipalAcknowledgementChangedError extends Error {
@@ -1 +1 @@
1
- {"version":3,"file":"principalCurrentAcknowledgementPersistence.js","sourceRoot":"","sources":["principalCurrentAcknowledgementPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,wBAAwB,EAAE,MAAM,iDAAiD,CAAC;AAC3F,OAAO,EAAE,sBAAsB,EAAE,MAAM,8CAA8C,CAAC;AAEtF,OAAO,EACL,mCAAmC,EACnC,kBAAkB,EAClB,4CAA4C,GAC7C,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAEL,iCAAiC,GAClC,MAAM,wDAAwD,CAAC;AAChE,OAAO,EAAE,4BAA4B,EAAE,MAAM,kDAAkD,CAAC;AAEhG,OAAO,EACL,sCAAsC,EACtC,6BAA6B,EAC7B,qCAAqC,EACrC,8BAA8B,GAC/B,MAAM,kDAAkD,CAAC;AAE1D,OAAO,EACL,sCAAsC,EACtC,0BAA0B,GAC3B,MAAM,mDAAmD,CAAC;AAC3D,OAAO,EAAE,8BAA8B,EAAE,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AAC;IACnD,IAAI,CAAC,KAAK,CAAC,cAAc;QAAE,MAAM,sBAAsB,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;IACnE,MAAM,sCAAsC,CAAC,EAAE,EAAE,KAAK,CAAC,cAAc,CAAC,CAAC;IACvE,MAAM,4BAA4B,CAAC,EAAE,EAAE,KAAK,CAAC,cAAc,CAAC,CAAC;IAC7D,IACE,CAAC,KAAK,CAAC,kBAAkB;QACzB,KAAK,CAAC,kBAAkB,CAAC,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,OAAO;QAEvD,MAAM,4CAA4C,CAChD,EAAE,EACF,KAAK,CAAC,MAAM,CAAC,UAAU,EACvB,GAAG,EAAE,CAAC,WAAW,EAAE,EACnB,cAAc,CACf,CAAC;AACN,CAAC;AAWD;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,iDAAiD,CACrE,EAAgC,EAChC,KAIC,EACD,GAAe;IAEf,MAAM,EAAE,OAAO,EAAE,cAAc,EAAE,GAAG,KAAK,CAAC;IAC1C,KAAK,MAAM,KAAK,IAAI,OAAO;QAAE,MAAM,mBAAmB,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;IAClE,KAAK,MAAM,UAAU,IAAI,KAAK,CAAC,WAAW,EAAE,CAAC;QAC3C,MAAM,eAAe,CAAC,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,cAAc,CAAC,CAAC;IACjE,CAAC;IACD,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC5B,MAAM,4BAA4B,CAAC,EAAE,EAAE,KAAK,EAAE,cAAc,EAAE,GAAG,CAAC,CAAC;IACrE,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedPrincipalPolicyCurrent,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport { eq } from \"drizzle-orm\";\nimport { principalHistoryPrefixes } from \"../sqlite/schema/principalHistoryEvidenceSchema\";\nimport { principalHistoryStages } from \"../sqlite/schema/principalHistoryStageSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../sqlite/sqlitePersistenceRuntime\";\nimport {\n loadStoredPrincipalPolicyCheckpoint,\n principalPolicyKey,\n upsertPrincipalPolicyCheckpointInTransaction,\n} from \"./keyingCheckpoints/keyingCheckpointPersistence\";\nimport {\n type PrincipalHistoryEvidencePage,\n writePrincipalHistoryEvidencePage,\n} from \"./principalHistory/principalHistoryEvidencePersistence\";\nimport { reclaimPrincipalHistoryNodes } from \"./principalHistory/principalHistoryNodeRetention\";\nimport type { PrincipalHistoryPrefix } from \"./principalHistory/principalHistoryPrefixPersistence\";\nimport {\n principalHistoryPrefixRootOwnerColumns,\n principalHistoryRootRetention,\n principalHistoryStageRootOwnerColumns,\n writePrincipalHistoryRootEdges,\n} from \"./principalHistory/principalHistoryRootOwnership\";\nimport type { PrincipalHistoryStage } from \"./principalHistory/principalHistoryStagePersistence\";\nimport {\n reclaimCompletedPrincipalHistoryStages,\n touchPrincipalHistoryStage,\n} from \"./principalHistory/principalHistoryStageRetention\";\nimport { storePrincipalGrantRetirements } from \"./principalKeys/principalGrantRetirementPersistence\";\nimport { archivePrincipalHistoryKeyEnvelopes } from \"./principalKeys/principalKeyEnvelopeArchivePersistence\";\n\n/** Owned output of authenticated prefix extension and exact receipt verification. */\nexport interface AcknowledgedPrincipalCurrentPublication {\n readonly policy: VerifiedPrincipalPolicyCurrent;\n readonly prefix: PrincipalHistoryPrefix;\n readonly previousPrefixProgress: string | null;\n readonly stage: PrincipalHistoryStage;\n readonly predecessorStage: PrincipalHistoryStage | null;\n readonly predecessorIndexRootHash: string | null;\n readonly evidence: PrincipalHistoryEvidencePage;\n}\n\nexport interface ReconciledPrincipalCurrentPublication\n extends AcknowledgedPrincipalCurrentPublication {\n readonly preservePrefix: boolean;\n readonly observedPrefixProgress: string | null;\n readonly observedCheckpoint: PrincipalPolicyCheckpoint | null;\n readonly retainedPrefix: PrincipalHistoryPrefix;\n readonly checkpointPolicy: VerifiedPrincipalPolicyCurrent;\n}\n\n/** A local writer won the CAS; retry the same authenticated receipt without HTTP. */\nexport class PrincipalAcknowledgementChangedError extends Error {\n constructor() {\n super(\n \"Authenticated principal progress changed during acknowledgement; retry retention\",\n );\n this.name = \"PrincipalAcknowledgementChangedError\";\n }\n}\n\nexport interface AcknowledgedPrincipalCurrentRetirement {\n readonly principalId: string;\n readonly principalType: VerifiedPrincipalPolicyCurrent[\"principalType\"];\n readonly containerIds: readonly string[];\n}\n\nexport function assertPublicationScope(\n entries: readonly AcknowledgedPrincipalCurrentPublication[],\n organizationId: string,\n) {\n const seen = new Set<string>();\n for (const entry of entries) {\n const key = principalPolicyKey(entry.policy);\n if (seen.has(key))\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n \"Acknowledged current batch repeats a principal\",\n );\n seen.add(key);\n if (\n entry.prefix.organizationId !== organizationId ||\n (entry.predecessorStage === null) !==\n (entry.predecessorIndexRootHash === null) ||\n entry.stage.organizationId !== organizationId ||\n (entry.predecessorStage\n ? entry.predecessorStage.organizationId !== organizationId ||\n !entry.predecessorStage.complete ||\n entry.predecessorStage.afterVersion !== entry.policy.version - 2\n : entry.policy.principalType !== \"group\" ||\n entry.policy.version !== 1 ||\n entry.policy.state.prevStateHash !== null ||\n entry.previousPrefixProgress !== null) ||\n entry.evidence.organizationId !== organizationId ||\n entry.prefix.scopeId !== entry.evidence.scopeId ||\n entry.prefix.version !== entry.policy.version ||\n entry.stage.afterVersion !== entry.policy.version - 1 ||\n !entry.stage.complete ||\n entry.stage.currentJson !== entry.prefix.currentJson\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Acknowledged current publication is outside its scope\",\n );\n }\n}\n\nasync function validatePublication(\n tx: ClientSQLiteTransactionScope,\n entry: ReconciledPrincipalCurrentPublication,\n) {\n const checkpoint = await loadStoredPrincipalPolicyCheckpoint(\n tx,\n entry.policy,\n );\n if (\n checkpoint?.version !== entry.observedCheckpoint?.version ||\n checkpoint?.stateHash !== entry.observedCheckpoint?.stateHash\n )\n throw new PrincipalAcknowledgementChangedError();\n verifyPrincipalPolicyCheckpoint({\n chain: entry.checkpointPolicy.retainedHistory,\n currentState: entry.checkpointPolicy.state,\n localCheckpoint: checkpoint,\n });\n if (\n (!checkpoint && entry.policy.version !== 1) ||\n (checkpoint && entry.policy.version > checkpoint.version + 1)\n )\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"Acknowledged current policy must directly extend its durable checkpoint\",\n );\n const [prefix] = await tx\n .select()\n .from(principalHistoryPrefixes)\n .where(eq(principalHistoryPrefixes.scopeId, entry.prefix.scopeId))\n .limit(1);\n if ((prefix?.progress ?? null) !== entry.observedPrefixProgress)\n throw new PrincipalAcknowledgementChangedError();\n}\n\nasync function archiveAcknowledgedStageKeys(\n tx: ClientSQLiteTransactionScope,\n entry: AcknowledgedPrincipalCurrentPublication,\n now: () => Date,\n) {\n for (const stage of [entry.predecessorStage, entry.stage]) {\n if (!stage) continue;\n await touchPrincipalHistoryStage(\n tx,\n { id: stage.id, scopeId: entry.prefix.scopeId },\n now().getTime(),\n );\n await archivePrincipalHistoryKeyEnvelopes(tx, {\n ...stage,\n version: stage.afterVersion + 1,\n });\n }\n}\n\nasync function loadStageRootOwner(\n tx: ClientSQLiteTransactionScope,\n id: string,\n) {\n const [owner] = await tx\n .select(principalHistoryStageRootOwnerColumns)\n .from(principalHistoryStages)\n .where(eq(principalHistoryStages.id, id))\n .limit(1);\n return owner;\n}\n\nasync function retainPredecessorStage(\n tx: ClientSQLiteTransactionScope,\n entry: AcknowledgedPrincipalCurrentPublication,\n now: () => Date,\n) {\n // Preserve a prefix-only predecessor without replacing an existing completion.\n if (!entry.predecessorStage || !entry.predecessorIndexRootHash) return;\n const root = {\n scopeId: entry.prefix.scopeId,\n organizationId: entry.prefix.organizationId,\n rootHash: entry.predecessorIndexRootHash,\n };\n const previous = await loadStageRootOwner(tx, entry.predecessorStage.id);\n const row = {\n ...entry.predecessorStage,\n ...root,\n touchedAt: now().getTime(),\n };\n const written = await tx\n .insert(principalHistoryStages)\n .values(row)\n .onConflictDoUpdate({\n target: principalHistoryStages.id,\n set: row,\n setWhere: eq(principalHistoryStages.complete, false),\n })\n .returning({ id: principalHistoryStages.id });\n // An existing completion keeps its row, so it also keeps its root.\n if (written.length > 0)\n await writePrincipalHistoryRootEdges(\n tx,\n principalHistoryRootRetention(previous, root),\n );\n}\n\n// A fully authenticated publication supersedes an in-flight stage for this\n// exact head. Its other writer fails its progress CAS and resumes.\nasync function saveAcknowledgedStage(\n tx: ClientSQLiteTransactionScope,\n entry: AcknowledgedPrincipalCurrentPublication,\n now: () => Date,\n) {\n const root = {\n scopeId: entry.prefix.scopeId,\n organizationId: entry.stage.organizationId,\n rootHash: entry.evidence.indexRootHash,\n };\n const previous = await loadStageRootOwner(tx, entry.stage.id);\n const row = { ...entry.stage, ...root, touchedAt: now().getTime() };\n await tx\n .insert(principalHistoryStages)\n .values(row)\n .onConflictDoUpdate({ target: principalHistoryStages.id, set: row })\n .run();\n await writePrincipalHistoryRootEdges(\n tx,\n principalHistoryRootRetention(previous, root),\n );\n}\n\nasync function saveAcknowledgedPrefix(\n tx: ClientSQLiteTransactionScope,\n entry: AcknowledgedPrincipalCurrentPublication,\n) {\n const root = {\n scopeId: entry.prefix.scopeId,\n organizationId: entry.prefix.organizationId,\n rootHash: entry.evidence.indexRootHash,\n };\n const [previous] = await tx\n .select(principalHistoryPrefixRootOwnerColumns)\n .from(principalHistoryPrefixes)\n .where(eq(principalHistoryPrefixes.scopeId, root.scopeId))\n .limit(1);\n const row = { ...entry.prefix, rootHash: root.rootHash };\n await tx\n .insert(principalHistoryPrefixes)\n .values(row)\n .onConflictDoUpdate({ target: principalHistoryPrefixes.scopeId, set: row })\n .run();\n await writePrincipalHistoryRootEdges(\n tx,\n principalHistoryRootRetention(previous, root),\n );\n}\n\nasync function storeRetirement(\n tx: ClientSQLiteTransactionScope,\n entries: readonly ReconciledPrincipalCurrentPublication[],\n retirement: AcknowledgedPrincipalCurrentRetirement,\n organizationId: string,\n) {\n const policy = entries.find(\n (entry) =>\n entry.policy.principalId === retirement.principalId &&\n entry.policy.principalType === retirement.principalType,\n )?.policy;\n if (!policy)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Retirement must accompany its acknowledged principal\",\n );\n await storePrincipalGrantRetirements(\n tx,\n { ...retirement, policy, organizationId },\n entries.map((entry) => entry.policy),\n organizationId,\n );\n}\n\nasync function storeAcknowledgedPublication(\n tx: ClientSQLiteTransactionScope,\n entry: ReconciledPrincipalCurrentPublication,\n organizationId: string,\n now: () => Date,\n) {\n await writePrincipalHistoryEvidencePage(tx, entry.evidence);\n await retainPredecessorStage(tx, entry, now);\n await saveAcknowledgedStage(tx, entry, now);\n await archiveAcknowledgedStageKeys(tx, entry, now);\n if (!entry.preservePrefix) await saveAcknowledgedPrefix(tx, entry);\n await reclaimCompletedPrincipalHistoryStages(tx, entry.retainedPrefix);\n await reclaimPrincipalHistoryNodes(tx, entry.retainedPrefix);\n if (\n !entry.observedCheckpoint ||\n entry.observedCheckpoint.version < entry.policy.version\n )\n await upsertPrincipalPolicyCheckpointInTransaction(\n tx,\n entry.policy.checkpoint,\n now().toISOString(),\n organizationId,\n );\n}\n\nexport interface AcknowledgedPrincipalCurrents {\n readonly organizationId: string;\n readonly entries: readonly ReconciledPrincipalCurrentPublication[];\n readonly retirements?:\n | readonly AcknowledgedPrincipalCurrentRetirement[]\n | undefined;\n readonly stillCurrent: () => boolean;\n}\n\n/**\n * Validates owned, scope-checked publications against their observed pins and\n * stores them. `now` is read where each row's timestamp is written.\n */\nexport async function persistAcknowledgedPrincipalCurrentsInTransaction(\n tx: ClientSQLiteTransactionScope,\n input: {\n readonly organizationId: string;\n readonly entries: readonly ReconciledPrincipalCurrentPublication[];\n readonly retirements: readonly AcknowledgedPrincipalCurrentRetirement[];\n },\n now: () => Date,\n): Promise<void> {\n const { entries, organizationId } = input;\n for (const entry of entries) await validatePublication(tx, entry);\n for (const retirement of input.retirements) {\n await storeRetirement(tx, entries, retirement, organizationId);\n }\n for (const entry of entries) {\n await storeAcknowledgedPublication(tx, entry, organizationId, now);\n }\n}\n"]}
1
+ {"version":3,"file":"principalCurrentAcknowledgementPersistence.js","sourceRoot":"","sources":["principalCurrentAcknowledgementPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,wBAAwB,EAAE,MAAM,iDAAiD,CAAC;AAC3F,OAAO,EAAE,sBAAsB,EAAE,MAAM,8CAA8C,CAAC;AAEtF,OAAO,EACL,mCAAmC,EACnC,kBAAkB,EAClB,4CAA4C,GAC7C,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,8BAA8B,EAAE,MAAM,0DAA0D,CAAC;AAC1G,OAAO,EAEL,iCAAiC,GAClC,MAAM,wDAAwD,CAAC;AAChE,OAAO,EAAE,4BAA4B,EAAE,MAAM,kDAAkD,CAAC;AAEhG,OAAO,EACL,sCAAsC,EACtC,6BAA6B,EAC7B,qCAAqC,EACrC,8BAA8B,GAC/B,MAAM,kDAAkD,CAAC;AAE1D,OAAO,EACL,sCAAsC,EACtC,0BAA0B,GAC3B,MAAM,mDAAmD,CAAC;AAC3D,OAAO,EAAE,mCAAmC,EAAE,MAAM,wDAAwD,CAAC;AAsB7G,qFAAqF;AACrF,MAAM,OAAO,oCAAqC,SAAQ,KAAK;IAC7D;QACE,KAAK,CACH,kFAAkF,CACnF,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,sCAAsC,CAAC;IACrD,CAAC;CACF;AAQD,MAAM,UAAU,sBAAsB,CACpC,OAA2D,EAC3D,cAAsB;IAEtB,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC5B,MAAM,GAAG,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AAC,UAAU,EACvB,GAAG,EAAE,CAAC,WAAW,EAAE,EACnB,cAAc,CACf,CAAC;AACN,CAAC;AAWD;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,iDAAiD,CACrE,EAAgC,EAChC,KAIC,EACD,GAAe;IAEf,MAAM,EAAE,OAAO,EAAE,cAAc,EAAE,GAAG,KAAK,CAAC;IAC1C,KAAK,MAAM,KAAK,IAAI,OAAO;QAAE,MAAM,mBAAmB,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;IAClE,KAAK,MAAM,UAAU,IAAI,KAAK,CAAC,WAAW,EAAE,CAAC;QAC3C,MAAM,eAAe,CAAC,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,cAAc,CAAC,CAAC;IACjE,CAAC;IACD,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC5B,MAAM,4BAA4B,CAAC,EAAE,EAAE,KAAK,EAAE,cAAc,EAAE,GAAG,CAAC,CAAC;IACrE,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedPrincipalPolicyCurrent,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport { eq } from \"drizzle-orm\";\nimport { principalHistoryPrefixes } from \"../sqlite/schema/principalHistoryEvidenceSchema\";\nimport { principalHistoryStages } from \"../sqlite/schema/principalHistoryStageSchema\";\nimport type { ClientSQLiteTransactionScope } from \"../sqlite/sqlitePersistenceRuntime\";\nimport {\n loadStoredPrincipalPolicyCheckpoint,\n principalPolicyKey,\n upsertPrincipalPolicyCheckpointInTransaction,\n} from \"./keyingCheckpoints/keyingCheckpointPersistence\";\nimport { storePrincipalGrantRetirements } from \"./principalContracts/principalGrantRetirementPersistence\";\nimport {\n type PrincipalHistoryEvidencePage,\n writePrincipalHistoryEvidencePage,\n} from \"./principalHistory/principalHistoryEvidencePersistence\";\nimport { reclaimPrincipalHistoryNodes } from \"./principalHistory/principalHistoryNodeRetention\";\nimport type { PrincipalHistoryPrefix } from \"./principalHistory/principalHistoryPrefixPersistence\";\nimport {\n principalHistoryPrefixRootOwnerColumns,\n principalHistoryRootRetention,\n principalHistoryStageRootOwnerColumns,\n writePrincipalHistoryRootEdges,\n} from \"./principalHistory/principalHistoryRootOwnership\";\nimport type { PrincipalHistoryStage } from \"./principalHistory/principalHistoryStagePersistence\";\nimport {\n reclaimCompletedPrincipalHistoryStages,\n touchPrincipalHistoryStage,\n} from \"./principalHistory/principalHistoryStageRetention\";\nimport { archivePrincipalHistoryKeyEnvelopes } from \"./principalKeys/principalKeyEnvelopeArchivePersistence\";\n\n/** Owned output of authenticated prefix extension and exact receipt verification. */\nexport interface AcknowledgedPrincipalCurrentPublication {\n readonly policy: VerifiedPrincipalPolicyCurrent;\n readonly prefix: PrincipalHistoryPrefix;\n readonly previousPrefixProgress: string | null;\n readonly stage: PrincipalHistoryStage;\n readonly predecessorStage: PrincipalHistoryStage | null;\n readonly predecessorIndexRootHash: string | null;\n readonly evidence: PrincipalHistoryEvidencePage;\n}\n\nexport interface ReconciledPrincipalCurrentPublication\n extends AcknowledgedPrincipalCurrentPublication {\n readonly preservePrefix: boolean;\n readonly observedPrefixProgress: string | null;\n readonly observedCheckpoint: PrincipalPolicyCheckpoint | null;\n readonly retainedPrefix: PrincipalHistoryPrefix;\n readonly checkpointPolicy: VerifiedPrincipalPolicyCurrent;\n}\n\n/** A local writer won the CAS; retry the same authenticated receipt without HTTP. */\nexport class PrincipalAcknowledgementChangedError extends Error {\n constructor() {\n super(\n \"Authenticated principal progress changed during acknowledgement; retry retention\",\n );\n this.name = \"PrincipalAcknowledgementChangedError\";\n }\n}\n\nexport interface AcknowledgedPrincipalCurrentRetirement {\n readonly principalId: string;\n readonly principalType: VerifiedPrincipalPolicyCurrent[\"principalType\"];\n readonly containerIds: readonly string[];\n}\n\nexport function assertPublicationScope(\n entries: readonly AcknowledgedPrincipalCurrentPublication[],\n organizationId: string,\n) {\n const seen = new Set<string>();\n for (const entry of entries) {\n const key = principalPolicyKey(entry.policy);\n if (seen.has(key))\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n \"Acknowledged current batch repeats a principal\",\n );\n seen.add(key);\n if (\n entry.prefix.organizationId !== organizationId ||\n (entry.predecessorStage === null) !==\n (entry.predecessorIndexRootHash === null) ||\n entry.stage.organizationId !== organizationId ||\n (entry.predecessorStage\n ? entry.predecessorStage.organizationId !== organizationId ||\n !entry.predecessorStage.complete ||\n entry.predecessorStage.afterVersion !== entry.policy.version - 2\n : entry.policy.principalType !== \"group\" ||\n entry.policy.version !== 1 ||\n entry.policy.state.prevStateHash !== null ||\n entry.previousPrefixProgress !== null) ||\n entry.evidence.organizationId !== organizationId ||\n entry.prefix.scopeId !== entry.evidence.scopeId ||\n entry.prefix.version !== entry.policy.version ||\n entry.stage.afterVersion !== entry.policy.version - 1 ||\n !entry.stage.complete ||\n entry.stage.currentJson !== entry.prefix.currentJson\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Acknowledged current publication is outside its scope\",\n );\n }\n}\n\nasync function validatePublication(\n tx: ClientSQLiteTransactionScope,\n entry: ReconciledPrincipalCurrentPublication,\n) {\n const checkpoint = await loadStoredPrincipalPolicyCheckpoint(\n tx,\n entry.policy,\n );\n if (\n checkpoint?.version !== entry.observedCheckpoint?.version ||\n checkpoint?.stateHash !== entry.observedCheckpoint?.stateHash\n )\n throw new PrincipalAcknowledgementChangedError();\n verifyPrincipalPolicyCheckpoint({\n chain: entry.checkpointPolicy.retainedHistory,\n currentState: entry.checkpointPolicy.state,\n localCheckpoint: checkpoint,\n });\n if (\n (!checkpoint && entry.policy.version !== 1) ||\n (checkpoint && entry.policy.version > checkpoint.version + 1)\n )\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"Acknowledged current policy must directly extend its durable checkpoint\",\n );\n const [prefix] = await tx\n .select()\n .from(principalHistoryPrefixes)\n .where(eq(principalHistoryPrefixes.scopeId, entry.prefix.scopeId))\n .limit(1);\n if ((prefix?.progress ?? null) !== entry.observedPrefixProgress)\n throw new PrincipalAcknowledgementChangedError();\n}\n\nasync function archiveAcknowledgedStageKeys(\n tx: ClientSQLiteTransactionScope,\n entry: AcknowledgedPrincipalCurrentPublication,\n now: () => Date,\n) {\n for (const stage of [entry.predecessorStage, entry.stage]) {\n if (!stage) continue;\n await touchPrincipalHistoryStage(\n tx,\n { id: stage.id, scopeId: entry.prefix.scopeId },\n now().getTime(),\n );\n await archivePrincipalHistoryKeyEnvelopes(tx, {\n ...stage,\n version: stage.afterVersion + 1,\n });\n }\n}\n\nasync function loadStageRootOwner(\n tx: ClientSQLiteTransactionScope,\n id: string,\n) {\n const [owner] = await tx\n .select(principalHistoryStageRootOwnerColumns)\n .from(principalHistoryStages)\n .where(eq(principalHistoryStages.id, id))\n .limit(1);\n return owner;\n}\n\nasync function retainPredecessorStage(\n tx: ClientSQLiteTransactionScope,\n entry: AcknowledgedPrincipalCurrentPublication,\n now: () => Date,\n) {\n // Preserve a prefix-only predecessor without replacing an existing completion.\n if (!entry.predecessorStage || !entry.predecessorIndexRootHash) return;\n const root = {\n scopeId: entry.prefix.scopeId,\n organizationId: entry.prefix.organizationId,\n rootHash: entry.predecessorIndexRootHash,\n };\n const previous = await loadStageRootOwner(tx, entry.predecessorStage.id);\n const row = {\n ...entry.predecessorStage,\n ...root,\n touchedAt: now().getTime(),\n };\n const written = await tx\n .insert(principalHistoryStages)\n .values(row)\n .onConflictDoUpdate({\n target: principalHistoryStages.id,\n set: row,\n setWhere: eq(principalHistoryStages.complete, false),\n })\n .returning({ id: principalHistoryStages.id });\n // An existing completion keeps its row, so it also keeps its root.\n if (written.length > 0)\n await writePrincipalHistoryRootEdges(\n tx,\n principalHistoryRootRetention(previous, root),\n );\n}\n\n// A fully authenticated publication supersedes an in-flight stage for this\n// exact head. Its other writer fails its progress CAS and resumes.\nasync function saveAcknowledgedStage(\n tx: ClientSQLiteTransactionScope,\n entry: AcknowledgedPrincipalCurrentPublication,\n now: () => Date,\n) {\n const root = {\n scopeId: entry.prefix.scopeId,\n organizationId: entry.stage.organizationId,\n rootHash: entry.evidence.indexRootHash,\n };\n const previous = await loadStageRootOwner(tx, entry.stage.id);\n const row = { ...entry.stage, ...root, touchedAt: now().getTime() };\n await tx\n .insert(principalHistoryStages)\n .values(row)\n .onConflictDoUpdate({ target: principalHistoryStages.id, set: row })\n .run();\n await writePrincipalHistoryRootEdges(\n tx,\n principalHistoryRootRetention(previous, root),\n );\n}\n\nasync function saveAcknowledgedPrefix(\n tx: ClientSQLiteTransactionScope,\n entry: AcknowledgedPrincipalCurrentPublication,\n) {\n const root = {\n scopeId: entry.prefix.scopeId,\n organizationId: entry.prefix.organizationId,\n rootHash: entry.evidence.indexRootHash,\n };\n const [previous] = await tx\n .select(principalHistoryPrefixRootOwnerColumns)\n .from(principalHistoryPrefixes)\n .where(eq(principalHistoryPrefixes.scopeId, root.scopeId))\n .limit(1);\n const row = { ...entry.prefix, rootHash: root.rootHash };\n await tx\n .insert(principalHistoryPrefixes)\n .values(row)\n .onConflictDoUpdate({ target: principalHistoryPrefixes.scopeId, set: row })\n .run();\n await writePrincipalHistoryRootEdges(\n tx,\n principalHistoryRootRetention(previous, root),\n );\n}\n\nasync function storeRetirement(\n tx: ClientSQLiteTransactionScope,\n entries: readonly ReconciledPrincipalCurrentPublication[],\n retirement: AcknowledgedPrincipalCurrentRetirement,\n organizationId: string,\n) {\n const policy = entries.find(\n (entry) =>\n entry.policy.principalId === retirement.principalId &&\n entry.policy.principalType === retirement.principalType,\n )?.policy;\n if (!policy)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Retirement must accompany its acknowledged principal\",\n );\n await storePrincipalGrantRetirements(\n tx,\n { ...retirement, policy, organizationId },\n entries.map((entry) => entry.policy),\n organizationId,\n );\n}\n\nasync function storeAcknowledgedPublication(\n tx: ClientSQLiteTransactionScope,\n entry: ReconciledPrincipalCurrentPublication,\n organizationId: string,\n now: () => Date,\n) {\n await writePrincipalHistoryEvidencePage(tx, entry.evidence);\n await retainPredecessorStage(tx, entry, now);\n await saveAcknowledgedStage(tx, entry, now);\n await archiveAcknowledgedStageKeys(tx, entry, now);\n if (!entry.preservePrefix) await saveAcknowledgedPrefix(tx, entry);\n await reclaimCompletedPrincipalHistoryStages(tx, entry.retainedPrefix);\n await reclaimPrincipalHistoryNodes(tx, entry.retainedPrefix);\n if (\n !entry.observedCheckpoint ||\n entry.observedCheckpoint.version < entry.policy.version\n )\n await upsertPrincipalPolicyCheckpointInTransaction(\n tx,\n entry.policy.checkpoint,\n now().toISOString(),\n organizationId,\n );\n}\n\nexport interface AcknowledgedPrincipalCurrents {\n readonly organizationId: string;\n readonly entries: readonly ReconciledPrincipalCurrentPublication[];\n readonly retirements?:\n | readonly AcknowledgedPrincipalCurrentRetirement[]\n | undefined;\n readonly stillCurrent: () => boolean;\n}\n\n/**\n * Validates owned, scope-checked publications against their observed pins and\n * stores them. `now` is read where each row's timestamp is written.\n */\nexport async function persistAcknowledgedPrincipalCurrentsInTransaction(\n tx: ClientSQLiteTransactionScope,\n input: {\n readonly organizationId: string;\n readonly entries: readonly ReconciledPrincipalCurrentPublication[];\n readonly retirements: readonly AcknowledgedPrincipalCurrentRetirement[];\n },\n now: () => Date,\n): Promise<void> {\n const { entries, organizationId } = input;\n for (const entry of entries) await validatePublication(tx, entry);\n for (const retirement of input.retirements) {\n await storeRetirement(tx, entries, retirement, organizationId);\n }\n for (const entry of entries) {\n await storeAcknowledgedPublication(tx, entry, organizationId, now);\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { isPrincipalStateResponse, } from "../../../internal/validators/response/index.js";
2
2
  import { and, eq, inArray, or } from "drizzle-orm";
3
- import { principalHeadMatchesReference } from "../../principals/organizationAuthorityDescriptor.js";
3
+ import { principalHeadMatchesReference } from "../../principalContracts/organizationAuthorityDescriptor.js";
4
4
  import { principalPolicyBundleReferences, principalPolicyBundles, } from "../../sqlite/schema/index.js";
5
5
  import { principalHistoryEntries, principalHistoryEntryStateHashJson, } from "../../sqlite/schema/principalHistoryEvidenceSchema.js";
6
6
  /** Candidate rows per source; equal hashes rarely repeat across scopes. */
@@ -1 +1 @@
1
- {"version":3,"file":"heldPrincipalState.js","sourceRoot":"","sources":["heldPrincipalState.ts"],"names":[],"mappings":"AACA,OAAO,EACL,wBAAwB,GAEzB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AACjG,OAAO,EACL,+BAA+B,EAC/B,sBAAsB,GACvB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,uBAAuB,EACvB,kCAAkC,GACnC,MAAM,oDAAoD,CAAC;AAG5D,2EAA2E;AAC3E,MAAM,qBAAqB,GAAG,CAAC,CAAC;AAEhC,SAAS,UAAU,CAAC,IAAY;IAC9B,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC1B,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,SAAS,OAAO,CAAC,KAAc;IAC7B,OAAO,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ;QACvC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,CAAC;QAC7B,CAAC,CAAC,IAAI,CAAC;AACX,CAAC;AAED,SAAS,UAAU,CACjB,KAAc,EACd,IAA6B;IAE7B,OAAO,wBAAwB,CAAC,KAAK,CAAC;QACpC,6BAA6B,CAAC,KAAK,EAAE,IAAI,CAAC;QAC1C,CAAC,CAAC,KAAK;QACP,CAAC,CAAC,IAAI,CAAC;AACX,CAAC;AAED,2EAA2E;AAC3E,KAAK,UAAU,aAAa,CAC1B,EAAwB,EACxB,IAA6B;IAE7B,MAAM,IAAI,GAAG,MAAM,EAAE;SAClB,MAAM,CAA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CAAC,EAAE,EAAE,IAAI,CAAC,CAAC,IAAI,WAAW,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;AAClE,CAAC","sourcesContent":["import type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport {\n isPrincipalStateResponse,\n type PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { and, eq, inArray, or } from \"drizzle-orm\";\nimport { principalHeadMatchesReference } from \"../../principals/organizationAuthorityDescriptor\";\nimport {\n principalPolicyBundleReferences,\n principalPolicyBundles,\n} from \"../../sqlite/schema\";\nimport {\n principalHistoryEntries,\n principalHistoryEntryStateHashJson,\n} from \"../../sqlite/schema/principalHistoryEvidenceSchema\";\nimport type { ClientSQLiteDatabase } from \"../../sqlite/sqlitePersistenceRuntime\";\n\n/** Candidate rows per source; equal hashes rarely repeat across scopes. */\nconst HELD_STATE_CANDIDATES = 8;\n\nfunction parsedJson(json: string): unknown {\n try {\n return JSON.parse(json);\n } catch {\n return null;\n }\n}\n\nfunction stateOf(entry: unknown): unknown {\n return entry && typeof entry === \"object\"\n ? Reflect.get(entry, \"state\")\n : null;\n}\n\nfunction exactState(\n state: unknown,\n head: ReferencedPrincipalHead,\n): PrincipalStateResponse | null {\n return isPrincipalStateResponse(state) &&\n principalHeadMatchesReference(state, head)\n ? state\n : null;\n}\n\n/** States this device stored as signed history evidence, by state hash. */\nasync function evidenceState(\n db: ClientSQLiteDatabase,\n head: ReferencedPrincipalHead,\n): Promise<PrincipalStateResponse | null> {\n const rows = await db\n .select({ entryJson: principalHistoryEntries.entryJson })\n .from(principalHistoryEntries)\n .where(\n eq(\n principalHistoryEntryStateHashJson(principalHistoryEntries.entryJson),\n head.stateHash,\n ),\n )\n .limit(HELD_STATE_CANDIDATES);\n for (const { entryJson } of rows) {\n const state = exactState(stateOf(parsedJson(entryJson)), head);\n if (state) return state;\n }\n return null;\n}\n\n/** A bundle row holds the head itself, or a predecessor at its version index. */\nfunction bundleRowState(\n row: {\n readonly stateHash: string;\n readonly currentStateJson: string;\n readonly previousStatesJson: string;\n },\n head: ReferencedPrincipalHead,\n): unknown {\n if (row.stateHash === head.stateHash) return parsedJson(row.currentStateJson);\n const previous = parsedJson(row.previousStatesJson);\n return Array.isArray(previous) ? stateOf(previous[head.version - 1]) : null;\n}\n\n/**\n * States in a cached policy bundle chain, current or retained: its head, or a\n * predecessor the reference index names.\n */\nasync function bundleState(\n db: ClientSQLiteDatabase,\n head: ReferencedPrincipalHead,\n): Promise<PrincipalStateResponse | null> {\n const indexed = db\n .selectDistinct({\n bundleStateHash: principalPolicyBundleReferences.bundleStateHash,\n })\n .from(principalPolicyBundleReferences)\n .where(\n and(\n eq(principalPolicyBundleReferences.principalType, head.principalType),\n eq(principalPolicyBundleReferences.principalId, head.principalId),\n eq(principalPolicyBundleReferences.version, head.version),\n eq(principalPolicyBundleReferences.stateHash, head.stateHash),\n eq(principalPolicyBundleReferences.keyEpoch, head.keyEpoch),\n eq(principalPolicyBundleReferences.keyFingerprint, head.keyFingerprint),\n ),\n )\n .limit(HELD_STATE_CANDIDATES);\n const rows = await db\n .select({\n stateHash: principalPolicyBundles.stateHash,\n currentStateJson: principalPolicyBundles.currentStateJson,\n previousStatesJson: principalPolicyBundles.previousStatesJson,\n })\n .from(principalPolicyBundles)\n .where(\n and(\n eq(principalPolicyBundles.principalType, head.principalType),\n eq(principalPolicyBundles.principalId, head.principalId),\n or(\n eq(principalPolicyBundles.stateHash, head.stateHash),\n inArray(principalPolicyBundles.stateHash, indexed),\n ),\n ),\n );\n for (const row of rows) {\n const state = exactState(bundleRowState(row, head), head);\n if (state) return state;\n }\n return null;\n}\n\n/** History evidence first, then cached bundle chains; tables already ensured. */\nexport async function selectHeldPrincipalState(\n db: ClientSQLiteDatabase,\n head: ReferencedPrincipalHead,\n): Promise<PrincipalStateResponse | null> {\n return (await evidenceState(db, head)) ?? bundleState(db, head);\n}\n"]}
1
+ {"version":3,"file":"heldPrincipalState.js","sourceRoot":"","sources":["heldPrincipalState.ts"],"names":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type PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { and, eq, inArray, or } from \"drizzle-orm\";\nimport { principalHeadMatchesReference } from \"../../principalContracts/organizationAuthorityDescriptor\";\nimport {\n principalPolicyBundleReferences,\n principalPolicyBundles,\n} from \"../../sqlite/schema\";\nimport {\n principalHistoryEntries,\n principalHistoryEntryStateHashJson,\n} from \"../../sqlite/schema/principalHistoryEvidenceSchema\";\nimport type { ClientSQLiteDatabase } from \"../../sqlite/sqlitePersistenceRuntime\";\n\n/** Candidate rows per source; equal hashes rarely repeat across scopes. */\nconst HELD_STATE_CANDIDATES = 8;\n\nfunction parsedJson(json: string): unknown {\n try {\n return JSON.parse(json);\n } catch {\n return null;\n }\n}\n\nfunction stateOf(entry: unknown): unknown {\n return entry && typeof entry === \"object\"\n ? Reflect.get(entry, \"state\")\n : null;\n}\n\nfunction exactState(\n state: unknown,\n head: ReferencedPrincipalHead,\n): PrincipalStateResponse | null {\n return isPrincipalStateResponse(state) &&\n principalHeadMatchesReference(state, head)\n ? state\n : null;\n}\n\n/** States this device stored as signed history evidence, by state hash. */\nasync function evidenceState(\n db: ClientSQLiteDatabase,\n head: ReferencedPrincipalHead,\n): Promise<PrincipalStateResponse | null> {\n const rows = await db\n .select({ entryJson: principalHistoryEntries.entryJson })\n .from(principalHistoryEntries)\n .where(\n eq(\n principalHistoryEntryStateHashJson(principalHistoryEntries.entryJson),\n head.stateHash,\n ),\n )\n .limit(HELD_STATE_CANDIDATES);\n for (const { entryJson } of rows) {\n const state = exactState(stateOf(parsedJson(entryJson)), head);\n if (state) return state;\n }\n return null;\n}\n\n/** A bundle row holds the head itself, or a predecessor at its version index. */\nfunction bundleRowState(\n row: {\n readonly stateHash: string;\n readonly currentStateJson: string;\n readonly previousStatesJson: string;\n },\n head: ReferencedPrincipalHead,\n): unknown {\n if (row.stateHash === head.stateHash) return parsedJson(row.currentStateJson);\n const previous = parsedJson(row.previousStatesJson);\n return Array.isArray(previous) ? stateOf(previous[head.version - 1]) : null;\n}\n\n/**\n * States in a cached policy bundle chain, current or retained: its head, or a\n * predecessor the reference index names.\n */\nasync function bundleState(\n db: ClientSQLiteDatabase,\n head: ReferencedPrincipalHead,\n): Promise<PrincipalStateResponse | null> {\n const indexed = db\n .selectDistinct({\n bundleStateHash: principalPolicyBundleReferences.bundleStateHash,\n })\n .from(principalPolicyBundleReferences)\n .where(\n and(\n eq(principalPolicyBundleReferences.principalType, head.principalType),\n eq(principalPolicyBundleReferences.principalId, head.principalId),\n eq(principalPolicyBundleReferences.version, head.version),\n eq(principalPolicyBundleReferences.stateHash, head.stateHash),\n eq(principalPolicyBundleReferences.keyEpoch, head.keyEpoch),\n eq(principalPolicyBundleReferences.keyFingerprint, head.keyFingerprint),\n ),\n )\n .limit(HELD_STATE_CANDIDATES);\n const rows = await db\n .select({\n stateHash: principalPolicyBundles.stateHash,\n currentStateJson: principalPolicyBundles.currentStateJson,\n previousStatesJson: principalPolicyBundles.previousStatesJson,\n })\n .from(principalPolicyBundles)\n .where(\n and(\n eq(principalPolicyBundles.principalType, head.principalType),\n eq(principalPolicyBundles.principalId, head.principalId),\n or(\n eq(principalPolicyBundles.stateHash, head.stateHash),\n inArray(principalPolicyBundles.stateHash, indexed),\n ),\n ),\n );\n for (const row of rows) {\n const state = exactState(bundleRowState(row, head), head);\n if (state) return state;\n }\n return null;\n}\n\n/** History evidence first, then cached bundle chains; tables already ensured. */\nexport async function selectHeldPrincipalState(\n db: ClientSQLiteDatabase,\n head: ReferencedPrincipalHead,\n): Promise<PrincipalStateResponse | null> {\n return (await evidenceState(db, head)) ?? bundleState(db, head);\n}\n"]}