@tearleads/client-sdk 0.1.243 → 0.1.246

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 (200) hide show
  1. package/client/organizations/principalMutations.d.ts +5 -0
  2. package/data/containers/shared/mutationAcknowledgement.d.ts +1 -1
  3. package/data/containers/shared/mutationAcknowledgement.js +3 -8
  4. package/data/containers/shared/mutationAcknowledgement.js.map +1 -1
  5. package/data/documents/shared/sync/mutationAcknowledgement.js +11 -2
  6. package/data/documents/shared/sync/mutationAcknowledgement.js.map +1 -1
  7. package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.d.ts +26 -0
  8. package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.js +46 -0
  9. package/data/keyingProjectionVerification/checkpoints/heldBundleRecovery.js.map +1 -0
  10. package/data/keyingProjectionVerification/container/containerDestinationVerification.d.ts +7 -4
  11. package/data/keyingProjectionVerification/container/containerDestinationVerification.js +5 -1
  12. package/data/keyingProjectionVerification/container/containerDestinationVerification.js.map +1 -1
  13. package/data/keyingProjectionVerification/container/containerProjectionVerification.js +9 -2
  14. package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -1
  15. package/data/keyingProjectionVerification/document/documentContainerProjections.js +2 -1
  16. package/data/keyingProjectionVerification/document/documentContainerProjections.js.map +1 -1
  17. package/data/keyingProjectionVerification/document/documentProjectionVerification.js +9 -2
  18. package/data/keyingProjectionVerification/document/documentProjectionVerification.js.map +1 -1
  19. package/data/keyingProjectionVerification/index.d.ts +1 -0
  20. package/data/keyingProjectionVerification/index.js +1 -0
  21. package/data/keyingProjectionVerification/index.js.map +1 -1
  22. package/data/persistence/container-contents/containerContentsPersistence.js +2 -0
  23. package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
  24. package/data/persistence/container-contents/containerContentsPersistenceTypes.d.ts +2 -1
  25. package/data/persistence/container-contents/containerContentsPersistenceTypes.js.map +1 -1
  26. package/data/persistence/container-contents/containerMetadataRevalidations.d.ts +22 -0
  27. package/data/persistence/container-contents/containerMetadataRevalidations.js +52 -0
  28. package/data/persistence/container-contents/containerMetadataRevalidations.js.map +1 -0
  29. package/data/persistence/keyingCheckpoints/keyingCheckpointRepository.js +16 -4
  30. package/data/persistence/keyingCheckpoints/keyingCheckpointRepository.js.map +1 -1
  31. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.d.ts +13 -0
  32. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js +11 -0
  33. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -1
  34. package/data/persistence/verifiedCitations/authoredBundleCitation.d.ts +20 -0
  35. package/data/persistence/verifiedCitations/authoredBundleCitation.js +32 -0
  36. package/data/persistence/verifiedCitations/authoredBundleCitation.js.map +1 -0
  37. package/data/persistence/verifiedManifestBundlePersistence.d.ts +10 -0
  38. package/data/persistence/verifiedManifestBundlePersistence.js +95 -9
  39. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
  40. package/data/sqlite/schema/containerSchema.d.ts +173 -0
  41. package/data/sqlite/schema/containerSchema.js +18 -0
  42. package/data/sqlite/schema/containerSchema.js.map +1 -1
  43. package/data/sqlite/schema/index.d.ts +84 -1
  44. package/data/sqlite/schema/index.js +1 -1
  45. package/data/sqlite/schema/index.js.map +1 -1
  46. package/internal/api-client/ApiClient.d.ts +56 -8
  47. package/internal/api-client/client/apiClientContext.d.ts +1 -0
  48. package/internal/api-client/client/containerMutations.d.ts +11 -0
  49. package/internal/api-client/client/containerReads.d.ts +1 -0
  50. package/internal/api-client/client/documents.d.ts +5 -0
  51. package/internal/api-client/client/organizations.d.ts +20 -0
  52. package/internal/api-client/client/principalPolicies.d.ts +9 -0
  53. package/internal/api-client/client/session.d.ts +10 -0
  54. package/internal/api-client/principalPolicyRequests.d.ts +7 -0
  55. package/internal/api-client/writerProjectionCitations.d.ts +3 -0
  56. package/internal/api-client/writerProjectionCitations.js +12 -0
  57. package/internal/api-client/writerProjectionCitations.js.map +1 -1
  58. package/internal/crypto/index.d.ts +1 -1
  59. package/internal/crypto/index.js +1 -1
  60. package/internal/crypto/index.js.map +1 -1
  61. package/internal/crypto/keying/accessManifestVerificationTypes.d.ts +8 -2
  62. package/internal/crypto/keying/accessManifestVerificationTypes.js.map +1 -1
  63. package/internal/crypto/keying/canonicalJsonGuard.d.ts +13 -0
  64. package/internal/crypto/keying/canonicalJsonGuard.js +23 -0
  65. package/internal/crypto/keying/canonicalJsonGuard.js.map +1 -1
  66. package/internal/crypto/keying/containerAccess.js +1 -1
  67. package/internal/crypto/keying/containerAccess.js.map +1 -1
  68. package/internal/crypto/keying/documentAccess.js +1 -1
  69. package/internal/crypto/keying/documentAccess.js.map +1 -1
  70. package/internal/crypto/keying/index.d.ts +1 -1
  71. package/internal/crypto/keying/index.js +1 -1
  72. package/internal/crypto/keying/index.js.map +1 -1
  73. package/internal/crypto/keying/keyingHashDomains.d.ts +1 -1
  74. package/internal/crypto/keying/keyingHashDomains.js.map +1 -1
  75. package/internal/crypto/organizationReplacement.js +5 -6
  76. package/internal/crypto/organizationReplacement.js.map +1 -1
  77. package/internal/loro/document.d.ts +5 -0
  78. package/internal/loro/document.js +17 -0
  79. package/internal/loro/document.js.map +1 -1
  80. package/internal/loro/index.d.ts +1 -1
  81. package/internal/loro/index.js +1 -1
  82. package/internal/loro/index.js.map +1 -1
  83. package/internal/validators/operation/attachments.d.ts +0 -12
  84. package/internal/validators/operation/auth.d.ts +40 -76
  85. package/internal/validators/operation/containerMutations.d.ts +45 -49
  86. package/internal/validators/operation/containerMutations.js +1 -1
  87. package/internal/validators/operation/containerMutations.js.map +1 -1
  88. package/internal/validators/operation/containerReads.d.ts +2 -0
  89. package/internal/validators/operation/documentMutations.d.ts +12 -24
  90. package/internal/validators/operation/documentSync.d.ts +0 -4
  91. package/internal/validators/operation/organizations.d.ts +48 -88
  92. package/internal/validators/operation/principals.d.ts +16 -16
  93. package/internal/validators/request/blob.d.ts +0 -12
  94. package/internal/validators/request/container.d.ts +0 -16
  95. package/internal/validators/request/container.js +0 -2
  96. package/internal/validators/request/container.js.map +1 -1
  97. package/internal/validators/request/containerMetadata.d.ts +0 -20
  98. package/internal/validators/request/document.d.ts +0 -22
  99. package/internal/validators/request/document.js +0 -1
  100. package/internal/validators/request/document.js.map +1 -1
  101. package/internal/validators/request/documentSyncSchema.d.ts +0 -4
  102. package/internal/validators/request/documentSyncSchema.js +0 -1
  103. package/internal/validators/request/documentSyncSchema.js.map +1 -1
  104. package/internal/validators/request/organization.d.ts +0 -16
  105. package/internal/validators/request/organizationProvisioning.d.ts +0 -242
  106. package/internal/validators/request/principal.d.ts +0 -20
  107. package/internal/validators/request/registration.d.ts +0 -76
  108. package/internal/validators/response/areas/containers.d.ts +1 -1
  109. package/internal/validators/response/areas/containers.js +1 -1
  110. package/internal/validators/response/areas/containers.js.map +1 -1
  111. package/internal/validators/response/container.d.ts +24 -0
  112. package/internal/validators/response/container.js +4 -0
  113. package/internal/validators/response/container.js.map +1 -1
  114. package/internal/validators/response/containerMetadata.d.ts +8 -0
  115. package/internal/validators/response/containerParentLanes.d.ts +2 -0
  116. package/internal/validators/response/documentMutation.d.ts +8 -0
  117. package/internal/validators/response/documentMutation.js +2 -1
  118. package/internal/validators/response/documentMutation.js.map +1 -1
  119. package/internal/validators/response/organization.d.ts +8 -0
  120. package/internal/validators/response/organizationProvisioning.d.ts +113 -0
  121. package/internal/validators/response/organizationProvisioning.js +2 -1
  122. package/internal/validators/response/organizationProvisioning.js.map +1 -1
  123. package/internal/validators/response/principal.d.ts +16 -0
  124. package/internal/validators/response/registration.d.ts +40 -0
  125. package/internal/validators/response/writerProjectionWire.d.ts +25 -0
  126. package/internal/validators/response/writerProjectionWire.js +109 -3
  127. package/internal/validators/response/writerProjectionWire.js.map +1 -1
  128. package/package.json +1 -1
  129. package/stores/container-contents/containerContentsStore.js +2 -0
  130. package/stores/container-contents/containerContentsStore.js.map +1 -1
  131. package/stores/container-contents/hydration/startupHydration.js +6 -2
  132. package/stores/container-contents/hydration/startupHydration.js.map +1 -1
  133. package/stores/container-contents/state.js +5 -1
  134. package/stores/container-contents/state.js.map +1 -1
  135. package/stores/container-contents/syncAgent/metadataRevalidation.js +79 -0
  136. package/stores/container-contents/syncAgent/metadataRevalidation.js.map +1 -0
  137. package/stores/container-contents/syncAgent/syncAgentTypes.d.ts +6 -0
  138. package/stores/container-contents/syncAgent/syncAgentTypes.js.map +1 -1
  139. package/stores/container-contents/syncAgent/syncLaneIteration.js +110 -23
  140. package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -1
  141. package/stores/documents/documentStore/rotation/index.js +3 -1
  142. package/stores/documents/documentStore/rotation/index.js.map +1 -1
  143. package/stores/documents/documentStore/sync/syncAttachments.js +4 -1
  144. package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
  145. package/stores/documents/documentStore/sync/syncDetachedAttachments.js +3 -1
  146. package/stores/documents/documentStore/sync/syncDetachedAttachments.js.map +1 -1
  147. package/stores/documents/documentStore/sync/syncRequest.js +3 -1
  148. package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
  149. package/workflows/container-contents/container-state/create/createAdoption.js +11 -3
  150. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  151. package/workflows/container-contents/container-state/create/createWithMetadata.js +2 -2
  152. package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
  153. package/workflows/container-contents/container-state/move/acceptedMoveSettlement.js +3 -0
  154. package/workflows/container-contents/container-state/move/acceptedMoveSettlement.js.map +1 -1
  155. package/workflows/container-contents/container-state/projectionCache.js +3 -0
  156. package/workflows/container-contents/container-state/projectionCache.js.map +1 -1
  157. package/workflows/container-contents/container-state/remote.js +3 -0
  158. package/workflows/container-contents/container-state/remote.js.map +1 -1
  159. package/workflows/container-contents/containerPersistence.d.ts +1 -0
  160. package/workflows/container-contents/containerPersistence.js.map +1 -1
  161. package/workflows/container-contents/metadata/index.js +9 -3
  162. package/workflows/container-contents/metadata/index.js.map +1 -1
  163. package/workflows/container-contents/metadata/metadataSyncFollowup.js +9 -0
  164. package/workflows/container-contents/metadata/metadataSyncFollowup.js.map +1 -1
  165. package/workflows/container-contents/metadata/metadataTypes.d.ts +2 -0
  166. package/workflows/container-contents/metadata/metadataTypes.js.map +1 -1
  167. package/workflows/container-contents/remoteHydration/index.js +9 -0
  168. package/workflows/container-contents/remoteHydration/index.js.map +1 -1
  169. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +31 -0
  170. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
  171. package/workflows/container-contents/remoteHydration/types.d.ts +9 -1
  172. package/workflows/container-contents/remoteHydration/types.js.map +1 -1
  173. package/workflows/containers/child/mutationRequestCore.js +1 -1
  174. package/workflows/containers/child/mutationRequestCore.js.map +1 -1
  175. package/workflows/containers/child/recite.js +4 -2
  176. package/workflows/containers/child/recite.js.map +1 -1
  177. package/workflows/containers/child/recitePlan.js +0 -1
  178. package/workflows/containers/child/recitePlan.js.map +1 -1
  179. package/workflows/containers/root/create.js +0 -1
  180. package/workflows/containers/root/create.js.map +1 -1
  181. package/workflows/documents/create/createAdoption.js +11 -2
  182. package/workflows/documents/create/createAdoption.js.map +1 -1
  183. package/workflows/documents/create/createResponse.js +1 -0
  184. package/workflows/documents/create/createResponse.js.map +1 -1
  185. package/workflows/documents/linkSet/index.js +0 -1
  186. package/workflows/documents/linkSet/index.js.map +1 -1
  187. package/workflows/documents/linkSet/linkSetRemote.js +1 -0
  188. package/workflows/documents/linkSet/linkSetRemote.js.map +1 -1
  189. package/workflows/documents/sync/syncAttemptPlanning.js +8 -2
  190. package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
  191. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js +3 -2
  192. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
  193. package/workflows/documents/syncRekeys/syncContainerRekeyProjection.js +3 -2
  194. package/workflows/documents/syncRekeys/syncContainerRekeyProjection.js.map +1 -1
  195. package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js +17 -10
  196. package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js.map +1 -1
  197. package/workflows/registration/organizationCreation/organizationCreationIntent.d.ts +10 -0
  198. package/workflows/registration/provisioningAcknowledgement.js +16 -11
  199. package/workflows/registration/provisioningAcknowledgement.js.map +1 -1
  200. package/workflows/registration/provisioningBootstrapBuilders.d.ts +0 -2
@@ -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,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,IAAI,CAAC,YAAY;SAChC,CAAC;QACF,oBAAoB,EAAE,IAAI,CAAC,QAAQ,CAAC,oBAAoB;KACzD,CAAC;AACJ,CAAC;AAED,SAAS,wBAAwB,CAC/B,IAA2C,EAC3C,eAAgD;IAEhD,IAAI,CAAC,eAAe,EAAE,CAAC;QACrB,IAAI,IAAI,CAAC,UAAU,CAAC,KAAK,KAAK,CAAC,IAAI,IAAI,CAAC,oBAAoB,KAAK,IAAI,EAAE,CAAC;YACtE,MAAM,IAAI,uBAAuB,CAC/B,mBAAmB,EACnB,gEAAgE,CACjE,CAAC;QACJ,CAAC;QACD,OAAO;IACT,C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,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
+ {"version":3,"file":"locallyAcknowledgedCheckpointPersistence.js","sourceRoot":"","sources":["locallyAcknowledgedCheckpointPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,oCAAoC,EACpC,uBAAuB,EAEvB,mCAAmC,GACpC,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAEL,0BAA0B,GAC3B,MAAM,6CAA6C,CAAC;AAIrD,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;AAYvC,MAAM,UAAU,iCAAiC,CAAC,IAGjD;IACC,OAAO;QACL,UAAU,EAAE,oCAAoC,CAAC;YAC/C,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,YAAY,EAAE,IAAI,CAAC,YAAY;SAChC,CAAC;QACF,oBAAoB,EAAE,IAAI,CAAC,QAAQ,CAAC,oBAAoB;KACzD,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,+BAA+B,CACnD,IAA4B,EAC5B,YAAoB;IAEpB,OAAO;QACL,GAAG,iCAAiC,CAAC,IAAI,CAAC;QAC1C,YAAY,EAAE,MAAM,0BAA0B,CAAC,IAAI,EAAE,YAAY,CAAC;KACnE,CAAC;AACJ,CAAC;AAED,SAAS,wBAAwB,CAC/B,IA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C,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 { ServedAccessManifestBundleWireResponse } from \"@tearleads/validators/util\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport {\n type AuthoredManifestBundle,\n acknowledgedAuthoredBundle,\n} from \"../verifiedCitations/authoredBundleCitation\";\n\nexport type { AuthoredManifestBundle } from \"../verifiedCitations/authoredBundleCitation\";\n\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 * The head's bundle as a projection serves it, when the acknowledgement's\n * digest matched the plan; stored for citation with the checkpoint.\n */\n readonly servedBundle?: ServedAccessManifestBundleWireResponse | 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\n/**\n * An authored head with its served bundle for citation, when the\n * acknowledgement's digest names exactly the bundle the plan builds.\n */\nexport async function locallyAcknowledgedAuthoredHead(\n plan: AuthoredManifestBundle,\n bundleDigest: string,\n): Promise<LocallyAcknowledgedAccessManifestHead> {\n return {\n ...locallyAuthoredAccessManifestHead(plan),\n servedBundle: await acknowledgedAuthoredBundle(plan, bundleDigest),\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"]}
@@ -0,0 +1,20 @@
1
+ import { type AccessEvent, type AccessManifest } from "../../../internal/crypto/index.js";
2
+ import { type ServedAccessManifestBundleWireResponse } from "../../../internal/validators/util/index.js";
3
+ /** The signed parts and derived state of a head this client authored. */
4
+ export interface AuthoredManifestBundle {
5
+ readonly body: unknown;
6
+ readonly event: AccessEvent;
7
+ readonly eventHash: string;
8
+ readonly manifest: AccessManifest;
9
+ readonly manifestHash: string;
10
+ readonly state: object;
11
+ }
12
+ /**
13
+ * The bundle a writer projection serves for a head this client authored,
14
+ * built from its own signed plan, when it has exactly the citation digest
15
+ * the acknowledgement named. A projection request may then cite it instead
16
+ * of downloading it back. Any difference only means the next read carries
17
+ * those bytes: a cited projection is verified from scratch, and a stored
18
+ * bundle that fails verification is dropped and read again uncited.
19
+ */
20
+ export declare function acknowledgedAuthoredBundle(plan: AuthoredManifestBundle, bundleDigest: string): Promise<ServedAccessManifestBundleWireResponse | null>;
@@ -0,0 +1,32 @@
1
+ import { computeAccessManifestBundleDigest, readKeyingCanonicalJson, } from "../../../internal/crypto/index.js";
2
+ import { toServedAccessManifestBundle, } from "../../../internal/validators/util/index.js";
3
+ import { readCanonicalRecord } from "../../keying/canonicalJson.js";
4
+ /**
5
+ * The bundle a writer projection serves for a head this client authored,
6
+ * built from its own signed plan, when it has exactly the citation digest
7
+ * the acknowledgement named. A projection request may then cite it instead
8
+ * of downloading it back. Any difference only means the next read carries
9
+ * those bytes: a cited projection is verified from scratch, and a stored
10
+ * bundle that fails verification is dropped and read again uncited.
11
+ */
12
+ export async function acknowledgedAuthoredBundle(plan, bundleDigest) {
13
+ try {
14
+ const served = toServedAccessManifestBundle({
15
+ event: {
16
+ body: readKeyingCanonicalJson(plan.body, "Authored event body"),
17
+ event: readCanonicalRecord({ ...plan.event }, "Authored event"),
18
+ eventHash: plan.eventHash,
19
+ },
20
+ manifest: readCanonicalRecord({ ...plan.manifest }, "Authored manifest"),
21
+ manifestHash: plan.manifestHash,
22
+ state: readCanonicalRecord({ ...plan.state }, "Authored state"),
23
+ });
24
+ return (await computeAccessManifestBundleDigest(served)) === bundleDigest
25
+ ? served
26
+ : null;
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }
32
+ //# sourceMappingURL=authoredBundleCitation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authoredBundleCitation.js","sourceRoot":"","sources":["authoredBundleCitation.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,iCAAiC,EACjC,uBAAuB,GACxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAEL,4BAA4B,GAC7B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAYjE;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,0BAA0B,CAC9C,IAA4B,EAC5B,YAAoB;IAEpB,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,4BAA4B,CAAC;YAC1C,KAAK,EAAE;gBACL,IAAI,EAAE,uBAAuB,CAAC,IAAI,CAAC,IAAI,EAAE,qBAAqB,CAAC;gBAC/D,KAAK,EAAE,mBAAmB,CAAC,EAAE,GAAG,IAAI,CAAC,KAAK,EAAE,EAAE,gBAAgB,CAAC;gBAC/D,SAAS,EAAE,IAAI,CAAC,SAAS;aAC1B;YACD,QAAQ,EAAE,mBAAmB,CAAC,EAAE,GAAG,IAAI,CAAC,QAAQ,EAAE,EAAE,mBAAmB,CAAC;YACxE,YAAY,EAAE,IAAI,CAAC,YAAY;YAC/B,KAAK,EAAE,mBAAmB,CAAC,EAAE,GAAG,IAAI,CAAC,KAAK,EAAE,EAAE,gBAAgB,CAAC;SAChE,CAAC,CAAC;QACH,OAAO,CAAC,MAAM,iCAAiC,CAAC,MAAM,CAAC,CAAC,KAAK,YAAY;YACvE,CAAC,CAAC,MAAM;YACR,CAAC,CAAC,IAAI,CAAC;IACX,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessEvent,\n type AccessManifest,\n computeAccessManifestBundleDigest,\n readKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport {\n type ServedAccessManifestBundleWireResponse,\n toServedAccessManifestBundle,\n} from \"@tearleads/validators/util\";\nimport { readCanonicalRecord } from \"../../keying/canonicalJson\";\n\n/** The signed parts and derived state of a head this client authored. */\nexport interface AuthoredManifestBundle {\n readonly body: unknown;\n readonly event: AccessEvent;\n readonly eventHash: string;\n readonly manifest: AccessManifest;\n readonly manifestHash: string;\n readonly state: object;\n}\n\n/**\n * The bundle a writer projection serves for a head this client authored,\n * built from its own signed plan, when it has exactly the citation digest\n * the acknowledgement named. A projection request may then cite it instead\n * of downloading it back. Any difference only means the next read carries\n * those bytes: a cited projection is verified from scratch, and a stored\n * bundle that fails verification is dropped and read again uncited.\n */\nexport async function acknowledgedAuthoredBundle(\n plan: AuthoredManifestBundle,\n bundleDigest: string,\n): Promise<ServedAccessManifestBundleWireResponse | null> {\n try {\n const served = toServedAccessManifestBundle({\n event: {\n body: readKeyingCanonicalJson(plan.body, \"Authored event body\"),\n event: readCanonicalRecord({ ...plan.event }, \"Authored event\"),\n eventHash: plan.eventHash,\n },\n manifest: readCanonicalRecord({ ...plan.manifest }, \"Authored manifest\"),\n manifestHash: plan.manifestHash,\n state: readCanonicalRecord({ ...plan.state }, \"Authored state\"),\n });\n return (await computeAccessManifestBundleDigest(served)) === bundleDigest\n ? served\n : null;\n } catch {\n return null;\n }\n}\n"]}
@@ -48,6 +48,16 @@ export declare function writeVerifiedManifestBundlesInTransaction(tx: ClientSQLi
48
48
  * dropped.
49
49
  */
50
50
  export declare function loadVerifiedManifestCitations(execSql: ExecSql, target: WriterProjectionTarget, requestedLimit?: number): Promise<HeldProjectionCitation[]>;
51
+ /** Keeps these held bundles out of citations until the release runs. */
52
+ export declare function suppressHeldCitations(manifestHashes: readonly string[]): () => void;
53
+ /**
54
+ * Drops the stored rows of held bundles a projection that cited them failed
55
+ * to verify with, so the next read fetches them from the server. Only a row
56
+ * still holding the exact bytes cited goes, so a newer verified copy written
57
+ * meanwhile stays; nothing is dropped once `stillCurrent` turns false.
58
+ * Resolves whether the drop committed.
59
+ */
60
+ export declare function dropHeldManifestBundles(execSql: ExecSql, heldBundles: readonly ServedAccessManifestBundleWireResponse[], stillCurrent?: () => boolean): Promise<boolean>;
51
61
  /** Cites from whichever database the signed-in identity currently uses. */
52
62
  export declare function createVerifiedManifestCitations(resolveExecSql: () => ExecSql | null): VerifiedManifestCitations;
53
63
  /** Drops an organization's verified bundles when a remote reset forgets it. */
@@ -167,6 +167,18 @@ export async function loadVerifiedManifestCitations(execSql, target, requestedLi
167
167
  const limit = Math.min(KNOWN_MANIFEST_HINT_LIMIT, Math.floor(requestedLimit));
168
168
  if (!(limit > 0))
169
169
  return [];
170
+ const loadGeneration = evictionGeneration;
171
+ citationLoadsInFlight += 1;
172
+ try {
173
+ return await loadCitableManifestCitations(execSql, target, limit).then((cited) => cited.filter((citation) => citable(citation, loadGeneration)));
174
+ }
175
+ finally {
176
+ citationLoadsInFlight -= 1;
177
+ if (citationLoadsInFlight === 0)
178
+ evictedInGeneration.clear();
179
+ }
180
+ }
181
+ async function loadCitableManifestCitations(execSql, target, limit) {
170
182
  await ensureSqlTables(execSql, [
171
183
  ...verifiedManifestBundleTables,
172
184
  ...containerTables,
@@ -181,17 +193,91 @@ export async function loadVerifiedManifestCitations(execSql, target, requestedLi
181
193
  return [];
182
194
  const { cited, damaged } = await collectVerifiedManifestCitations(db, organizationId, objects, target, limit);
183
195
  if (damaged.length > 0)
184
- await getClientSQLitePersistenceRuntime(execSql)
185
- .runMutation(async (handle) => {
186
- for (const batch of batches([...new Set(damaged)]))
187
- await handle
188
- .delete(bundles)
189
- .where(inArray(bundles.manifestHash, batch))
190
- .run();
191
- })
192
- .catch(() => undefined);
196
+ await dropVerifiedManifestBundles(execSql, damaged).catch(() => undefined);
193
197
  return cited;
194
198
  }
199
+ // Manifest hashes whose held rows a refused read is dropping: no read cites
200
+ // them meanwhile, so none can be rebuilt from the bytes being dropped. Each
201
+ // eviction also advances a generation, so a citation load that started
202
+ // before it never returns the rows it read: they may already be gone.
203
+ const suppressedCitations = new Map();
204
+ const evictedInGeneration = new Map();
205
+ let evictionGeneration = 0;
206
+ // Loads in flight; once none overlap, the eviction log has nothing to guard.
207
+ let citationLoadsInFlight = 0;
208
+ /** Keeps these held bundles out of citations until the release runs. */
209
+ export function suppressHeldCitations(manifestHashes) {
210
+ evictionGeneration += 1;
211
+ for (const hash of manifestHashes) {
212
+ suppressedCitations.set(hash, (suppressedCitations.get(hash) ?? 0) + 1);
213
+ evictedInGeneration.set(hash, evictionGeneration);
214
+ }
215
+ return () => {
216
+ // The drop is complete: a load that started before now may hold the
217
+ // dropped bytes, so it is newer than none of them.
218
+ evictionGeneration += 1;
219
+ for (const hash of manifestHashes) {
220
+ evictedInGeneration.set(hash, evictionGeneration);
221
+ const count = (suppressedCitations.get(hash) ?? 1) - 1;
222
+ if (count > 0)
223
+ suppressedCitations.set(hash, count);
224
+ else
225
+ suppressedCitations.delete(hash);
226
+ }
227
+ };
228
+ }
229
+ function citable(citation, loadGeneration) {
230
+ if (!("manifestHash" in citation))
231
+ return true;
232
+ const { manifestHash } = citation;
233
+ return (!suppressedCitations.has(manifestHash) &&
234
+ (evictedInGeneration.get(manifestHash) ?? 0) <= loadGeneration);
235
+ }
236
+ /**
237
+ * Drops the stored rows of held bundles a projection that cited them failed
238
+ * to verify with, so the next read fetches them from the server. Only a row
239
+ * still holding the exact bytes cited goes, so a newer verified copy written
240
+ * meanwhile stays; nothing is dropped once `stillCurrent` turns false.
241
+ * Resolves whether the drop committed.
242
+ */
243
+ export async function dropHeldManifestBundles(execSql, heldBundles, stillCurrent) {
244
+ if (heldBundles.length === 0)
245
+ return true;
246
+ const cited = await Promise.all(heldBundles.map(async (bundle) => ({
247
+ manifestHash: bundle.manifestHash,
248
+ bundleDigest: await sha256Hex(JSON.stringify(bundle)),
249
+ })));
250
+ await ensureSqlTables(execSql, verifiedManifestBundleTables);
251
+ const runtime = getClientSQLitePersistenceRuntime(execSql);
252
+ const drop = async (tx) => {
253
+ for (const row of cited)
254
+ await tx
255
+ .delete(bundles)
256
+ .where(and(eq(bundles.manifestHash, row.manifestHash), eq(bundles.bundleDigest, row.bundleDigest)))
257
+ .run();
258
+ };
259
+ if (!stillCurrent) {
260
+ await runtime.transaction(drop, { behavior: "immediate" });
261
+ return true;
262
+ }
263
+ const { committed } = await runtime.guardedTransaction(drop, stillCurrent, {
264
+ behavior: "immediate",
265
+ });
266
+ return committed;
267
+ }
268
+ /** Drops damaged stored rows so no later read cites them. */
269
+ async function dropVerifiedManifestBundles(execSql, manifestHashes) {
270
+ if (manifestHashes.length === 0)
271
+ return;
272
+ await ensureSqlTables(execSql, verifiedManifestBundleTables);
273
+ await getClientSQLitePersistenceRuntime(execSql).runMutation(async (handle) => {
274
+ for (const batch of batches([...new Set(manifestHashes)]))
275
+ await handle
276
+ .delete(bundles)
277
+ .where(inArray(bundles.manifestHash, batch))
278
+ .run();
279
+ });
280
+ }
195
281
  /** Cites from whichever database the signed-in identity currently uses. */
196
282
  export function createVerifiedManifestCitations(resolveExecSql) {
197
283
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"verifiedManifestBundlePersistence.js","sourceRoot":"","sources":["verifiedManifestBundlePersistence.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EACL,yBAAyB,GAE1B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACtE,OAAO,EACL,iCAAiC,EACjC,wBAAwB,GACzB,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,6BAA6B,IAAI,OAAO,EACxC,4BAA4B,GAC7B,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAEL,iCAAiC,GA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AAC;IACF,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC;QACpB,MAAM,iCAAiC,CAAC,OAAO,CAAC;aAC7C,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE;YAC5B,KAAK,MAAM,KAAK,IAAI,OAAO,CAAC,CAAC,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC;gBAChD,MAAM,MAAM;qBACT,MAAM,CAAC,OAAO,CAAC;qBACf,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC;qBAC3C,GAAG,EAAE,CAAC;QACb,CAAC,CAAC;aACD,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IAC5B,OAAO,KAAK,CAAC;AACf,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,+BAA+B,CAC7C,cAAoC;IAEpC,OAAO;QACL,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE;YACrB,MAAM,OAAO,GAAG,cAAc,EAAE,CAAC;YACjC,OAAO,OAAO,CAAC,CAAC,CAAC,6BAA6B,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QACvE,CAAC;KACF,CAAC;AACJ,CAAC;AAED,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,4CAA4C,CAChE,EAAgC,EAChC,cAAsB;IAEtB,MAAM,EAAE;SACL,MAAM,CAAC,OAAO,CAAC;SACf,KAAK,CAAC,EAAE,CAAC,OAAO,CAAC,cAAc,EAAE,cAAc,CAAC,CAAC;SACjD,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import type {\n HeldProjectionCitation,\n VerifiedManifestCitations,\n WriterProjectionTarget,\n} from \"@tearleads/api-client\";\nimport { toFingerprint } from \"@tearleads/crypto\";\nimport {\n KNOWN_MANIFEST_HINT_LIMIT,\n type ServedAccessManifestBundleWireResponse,\n} from \"@tearleads/validators/util\";\nimport { and, asc, eq, inArray, notInArray, sql } from \"drizzle-orm\";\nimport { containerTables, localIntentTables } from \"../sqlite/schema\";\nimport {\n documentContainerProjectionTables,\n documentProjectionTables,\n} from \"../sqlite/schema/documentProjectionSchema\";\nimport {\n verifiedAccessManifestBundles as bundles,\n verifiedManifestBundleTables,\n} from \"../sqlite/schema/verifiedManifestBundleSchema\";\nimport { sqliteInsertBatchSize } from \"../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { excludedValue } from \"../sqlite/sqliteUpsert\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport { collectVerifiedManifestCitations } from \"./verifiedCitations/citationCollection\";\nimport {\n citedObjects,\n targetOrganization,\n} from \"./verifiedCitations/citationScope\";\nimport {\n KEK_LEVEL_OBJECT_KIND,\n kekLevelRow,\n type VerifiedKekLevel,\n} from \"./verifiedCitations/kekLevelCitations\";\n\n/**\n * Bounds local bytes (a bundle is ~10–20 KB). Evicting the least recently\n * verified rows only makes a later read carry those bundles again.\n */\nexport const MAX_VERIFIED_MANIFEST_BUNDLES = 1024;\nconst STATEMENT_BATCH = 200;\n\ninterface VerifiedBundle {\n /** The served bytes; the decoded state is rebuilt from them on refill. */\n readonly bundle: ServedAccessManifestBundleWireResponse;\n readonly checkpoint: {\n readonly objectKind: string;\n readonly organizationId: string;\n readonly objectId: string;\n readonly epoch: number;\n };\n}\n\n/** Bytes a projection verification accepted: a bundle or a KEK level. */\nexport type VerifiedManifestBundle = VerifiedBundle | VerifiedKekLevel;\n\nfunction sha256Hex(text: string): Promise<string> {\n return toFingerprint(new TextEncoder().encode(text));\n}\n\nconst BUNDLE_WRITE_BATCH_SIZE = sqliteInsertBatchSize(bundles);\n\nfunction slices<T>(values: readonly T[], size: number): T[][] {\n const result: T[][] = [];\n for (let index = 0; index < values.length; index += size)\n result.push(values.slice(index, index + size));\n return result;\n}\n\nfunction batches<T>(values: readonly T[]): T[][] {\n return slices(values, STATEMENT_BATCH);\n}\n\nasync function pruneInTransaction(\n tx: ClientSQLiteTransactionScope,\n): Promise<void> {\n const [row] = await tx.select({ count: sql<number>`count(*)` }).from(bundles);\n const excess = (row?.count ?? 0) - MAX_VERIFIED_MANIFEST_BUNDLES;\n if (excess <= 0) return;\n const evicted = await tx\n .select({ manifestHash: bundles.manifestHash })\n .from(bundles)\n .orderBy(asc(bundles.verifiedAt), asc(bundles.manifestHash))\n .limit(excess);\n for (const batch of batches(evicted.map((entry) => entry.manifestHash)))\n await tx.delete(bundles).where(inArray(bundles.manifestHash, batch)).run();\n}\n\n/** A verified bundle's exact JSON and that JSON's digest. */\nexport type VerifiedManifestBundleRow = Omit<\n typeof bundles.$inferInsert,\n \"verifiedAt\"\n>;\n\n/**\n * Prepares rows for bundles and KEK levels that just passed projection\n * verification. The digests are computed here, before the checkpoint\n * transaction that writes them begins.\n */\nexport async function verifiedManifestBundleRows(\n entries: readonly VerifiedManifestBundle[],\n): Promise<VerifiedManifestBundleRow[]> {\n const bundleEntries: VerifiedBundle[] = [];\n const levelEntries: VerifiedKekLevel[] = [];\n for (const entry of entries)\n if (\"kekLevel\" in entry) levelEntries.push(entry);\n else bundleEntries.push(entry);\n // One level per container: its newest epoch, the last one seen on a tie.\n const levelRows = new Map<string, VerifiedManifestBundleRow>();\n for (const level of levelEntries) {\n const row = await kekLevelRow(level);\n const held = row && levelRows.get(row.objectId);\n if (row && (!held || held.epoch <= row.epoch))\n levelRows.set(row.objectId, row);\n }\n return [...(await bundleRows(bundleEntries)), ...levelRows.values()];\n}\n\nfunction bundleRows(\n entries: readonly VerifiedBundle[],\n): Promise<VerifiedManifestBundleRow[]> {\n const unique = new Map(\n entries.map((entry) => [entry.bundle.manifestHash, entry]),\n );\n return Promise.all(\n [...unique.values()].map(async ({ bundle, checkpoint }) => {\n const bundleJson = JSON.stringify(bundle);\n return {\n manifestHash: bundle.manifestHash,\n organizationId: checkpoint.organizationId,\n objectKind: checkpoint.objectKind,\n objectId: checkpoint.objectId,\n epoch: checkpoint.epoch,\n bundleJson,\n bundleDigest: await sha256Hex(bundleJson),\n };\n }),\n );\n}\n\n/**\n * Records verified bundles inside the transaction that finalizes their\n * projection's checkpoints, so they commit or roll back with it and no cache\n * work outlives the verification. Freshly verified bytes replace any stored\n * copy.\n */\nexport async function writeVerifiedManifestBundlesInTransaction(\n tx: ClientSQLiteTransactionScope,\n rows: readonly VerifiedManifestBundleRow[],\n verifiedAt: string,\n): Promise<void> {\n if (rows.length === 0) return;\n const stored = await touchStoredDigests(\n tx,\n rows.map((row) => row.manifestHash),\n verifiedAt,\n );\n // A repeated hash keeps its last changed row, as sequential upserts would.\n const changed = new Map(\n rows\n .filter((row) => stored.get(row.manifestHash) !== row.bundleDigest)\n .map((row) => [row.manifestHash, { ...row, verifiedAt }]),\n );\n for (const batch of slices([...changed.values()], BUNDLE_WRITE_BATCH_SIZE))\n await tx\n .insert(bundles)\n .values(batch)\n .onConflictDoUpdate({\n target: bundles.manifestHash,\n set: {\n organizationId: excludedValue(bundles.organizationId),\n objectKind: excludedValue(bundles.objectKind),\n objectId: excludedValue(bundles.objectId),\n epoch: excludedValue(bundles.epoch),\n bundleJson: excludedValue(bundles.bundleJson),\n bundleDigest: excludedValue(bundles.bundleDigest),\n verifiedAt: excludedValue(bundles.verifiedAt),\n },\n })\n .run();\n // All incremental SDK level writes pass here. Both checkpoint callers\n // prepare them with verifiedManifestBundleRows (one level per container),\n // then write and drop siblings in the same serialized transaction. Thus an\n // unchanged level already removed its siblings; eviction/reset only delete.\n // Restored caches must preserve that invariant too: this fast path does not\n // repair externally injected stale siblings.\n await dropSupersededKekLevels(tx, [...changed.values()]);\n // Replacing or touching existing rows cannot grow the bounded cache.\n if (rows.some((row) => !stored.has(row.manifestHash))) {\n await pruneInTransaction(tx);\n }\n}\n\n/**\n * A container keeps only its latest verified level: the API serves its\n * current level, so an older one can never be cited usefully again.\n */\nasync function dropSupersededKekLevels(\n tx: ClientSQLiteTransactionScope,\n rows: readonly VerifiedManifestBundleRow[],\n): Promise<void> {\n const levels = rows.filter((row) => row.objectKind === KEK_LEVEL_OBJECT_KIND);\n for (const batch of batches(levels))\n await tx\n .delete(bundles)\n .where(\n and(\n eq(bundles.objectKind, KEK_LEVEL_OBJECT_KIND),\n inArray(\n bundles.objectId,\n batch.map((row) => row.objectId),\n ),\n notInArray(\n bundles.manifestHash,\n batch.map((row) => row.manifestHash),\n ),\n ),\n )\n .run();\n}\n\nasync function touchStoredDigests(\n tx: ClientSQLiteTransactionScope,\n manifestHashes: readonly string[],\n verifiedAt: string,\n): Promise<Map<string, string>> {\n const digests = new Map<string, string>();\n for (const batch of batches(manifestHashes)) {\n const rows = await tx\n .update(bundles)\n .set({ verifiedAt })\n .where(inArray(bundles.manifestHash, batch))\n .returning({\n bundleDigest: bundles.bundleDigest,\n manifestHash: bundles.manifestHash,\n });\n for (const row of rows) digests.set(row.manifestHash, row.bundleDigest);\n }\n return digests;\n}\n\n/**\n * The latest verified KEK level of each container the target's projection\n * walks (supplemented by organization-recency levels for a pending move,\n * or when the lineage has no stored level); then verified bundles of those\n * objects, newest epochs first; then\n * the most recently verified bundles of its organization, since a\n * just-verified parent is the likeliest part of a new child's projection.\n * Citations never leave the target's organization: an object whose\n * organization the device cannot place cites nothing. Damaged rows are\n * dropped.\n */\nexport async function loadVerifiedManifestCitations(\n execSql: ExecSql,\n target: WriterProjectionTarget,\n requestedLimit = KNOWN_MANIFEST_HINT_LIMIT,\n): Promise<HeldProjectionCitation[]> {\n const limit = Math.min(KNOWN_MANIFEST_HINT_LIMIT, Math.floor(requestedLimit));\n if (!(limit > 0)) return [];\n await ensureSqlTables(execSql, [\n ...verifiedManifestBundleTables,\n ...containerTables,\n ...documentContainerProjectionTables,\n ...documentProjectionTables,\n ...localIntentTables,\n ]);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const objects = await citedObjects(db, target);\n const organizationId = await targetOrganization(db, target, objects);\n if (organizationId === null) return [];\n const { cited, damaged } = await collectVerifiedManifestCitations(\n db,\n organizationId,\n objects,\n target,\n limit,\n );\n if (damaged.length > 0)\n await getClientSQLitePersistenceRuntime(execSql)\n .runMutation(async (handle) => {\n for (const batch of batches([...new Set(damaged)]))\n await handle\n .delete(bundles)\n .where(inArray(bundles.manifestHash, batch))\n .run();\n })\n .catch(() => undefined);\n return cited;\n}\n\n/** Cites from whichever database the signed-in identity currently uses. */\nexport function createVerifiedManifestCitations(\n resolveExecSql: () => ExecSql | null,\n): VerifiedManifestCitations {\n return {\n cite: async (target) => {\n const execSql = resolveExecSql();\n return execSql ? loadVerifiedManifestCitations(execSql, target) : [];\n },\n };\n}\n\n/** Drops an organization's verified bundles when a remote reset forgets it. */\nexport async function deleteVerifiedManifestBundlesForOrganization(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<void> {\n await tx\n .delete(bundles)\n .where(eq(bundles.organizationId, organizationId))\n .run();\n}\n"]}
1
+ {"version":3,"file":"verifiedManifestBundlePersistence.js","sourceRoot":"","sources":["verifiedManifestBundlePersistence.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAClD,OAAO,EACL,yBAAyB,GAE1B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,UAAU,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACtE,OAAO,EACL,iCAAiC,EACjC,wBAAwB,GACzB,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,6BAA6B,IAAI,OAAO,EACxC,4BAA4B,GAC7B,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAEL,iCAAiC,GAClC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE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vD,MAAM,MAAM;iBACT,MAAM,CAAC,OAAO,CAAC;iBACf,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,YAAY,EAAE,KAAK,CAAC,CAAC;iBAC3C,GAAG,EAAE,CAAC;IACb,CAAC,CACF,CAAC;AACJ,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,+BAA+B,CAC7C,cAAoC;IAEpC,OAAO;QACL,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE;YACrB,MAAM,OAAO,GAAG,cAAc,EAAE,CAAC;YACjC,OAAO,OAAO,CAAC,CAAC,CAAC,6BAA6B,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QACvE,CAAC;KACF,CAAC;AACJ,CAAC;AAED,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,4CAA4C,CAChE,EAAgC,EAChC,cAAsB;IAEtB,MAAM,EAAE;SACL,MAAM,CAAC,OAAO,CAAC;SACf,KAAK,CAAC,EAAE,CAAC,OAAO,CAAC,cAAc,EAAE,cAAc,CAAC,CAAC;SACjD,GAAG,EAAE,CAAC;AACX,CAAC","sourcesContent":["import type {\n HeldProjectionCitation,\n VerifiedManifestCitations,\n WriterProjectionTarget,\n} from \"@tearleads/api-client\";\nimport { toFingerprint } from \"@tearleads/crypto\";\nimport {\n KNOWN_MANIFEST_HINT_LIMIT,\n type ServedAccessManifestBundleWireResponse,\n} from \"@tearleads/validators/util\";\nimport { and, asc, eq, inArray, notInArray, sql } from \"drizzle-orm\";\nimport { containerTables, localIntentTables } from \"../sqlite/schema\";\nimport {\n documentContainerProjectionTables,\n documentProjectionTables,\n} from \"../sqlite/schema/documentProjectionSchema\";\nimport {\n verifiedAccessManifestBundles as bundles,\n verifiedManifestBundleTables,\n} from \"../sqlite/schema/verifiedManifestBundleSchema\";\nimport { sqliteInsertBatchSize } from \"../sqlite/sqliteBindBudget\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { excludedValue } from \"../sqlite/sqliteUpsert\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport { collectVerifiedManifestCitations } from \"./verifiedCitations/citationCollection\";\nimport {\n citedObjects,\n targetOrganization,\n} from \"./verifiedCitations/citationScope\";\nimport {\n KEK_LEVEL_OBJECT_KIND,\n kekLevelRow,\n type VerifiedKekLevel,\n} from \"./verifiedCitations/kekLevelCitations\";\n\n/**\n * Bounds local bytes (a bundle is ~10–20 KB). Evicting the least recently\n * verified rows only makes a later read carry those bundles again.\n */\nexport const MAX_VERIFIED_MANIFEST_BUNDLES = 1024;\nconst STATEMENT_BATCH = 200;\n\ninterface VerifiedBundle {\n /** The served bytes; the decoded state is rebuilt from them on refill. */\n readonly bundle: ServedAccessManifestBundleWireResponse;\n readonly checkpoint: {\n readonly objectKind: string;\n readonly organizationId: string;\n readonly objectId: string;\n readonly epoch: number;\n };\n}\n\n/** Bytes a projection verification accepted: a bundle or a KEK level. */\nexport type VerifiedManifestBundle = VerifiedBundle | VerifiedKekLevel;\n\nfunction sha256Hex(text: string): Promise<string> {\n return toFingerprint(new TextEncoder().encode(text));\n}\n\nconst BUNDLE_WRITE_BATCH_SIZE = sqliteInsertBatchSize(bundles);\n\nfunction slices<T>(values: readonly T[], size: number): T[][] {\n const result: T[][] = [];\n for (let index = 0; index < values.length; index += size)\n result.push(values.slice(index, index + size));\n return result;\n}\n\nfunction batches<T>(values: readonly T[]): T[][] {\n return slices(values, STATEMENT_BATCH);\n}\n\nasync function pruneInTransaction(\n tx: ClientSQLiteTransactionScope,\n): Promise<void> {\n const [row] = await tx.select({ count: sql<number>`count(*)` }).from(bundles);\n const excess = (row?.count ?? 0) - MAX_VERIFIED_MANIFEST_BUNDLES;\n if (excess <= 0) return;\n const evicted = await tx\n .select({ manifestHash: bundles.manifestHash })\n .from(bundles)\n .orderBy(asc(bundles.verifiedAt), asc(bundles.manifestHash))\n .limit(excess);\n for (const batch of batches(evicted.map((entry) => entry.manifestHash)))\n await tx.delete(bundles).where(inArray(bundles.manifestHash, batch)).run();\n}\n\n/** A verified bundle's exact JSON and that JSON's digest. */\nexport type VerifiedManifestBundleRow = Omit<\n typeof bundles.$inferInsert,\n \"verifiedAt\"\n>;\n\n/**\n * Prepares rows for bundles and KEK levels that just passed projection\n * verification. The digests are computed here, before the checkpoint\n * transaction that writes them begins.\n */\nexport async function verifiedManifestBundleRows(\n entries: readonly VerifiedManifestBundle[],\n): Promise<VerifiedManifestBundleRow[]> {\n const bundleEntries: VerifiedBundle[] = [];\n const levelEntries: VerifiedKekLevel[] = [];\n for (const entry of entries)\n if (\"kekLevel\" in entry) levelEntries.push(entry);\n else bundleEntries.push(entry);\n // One level per container: its newest epoch, the last one seen on a tie.\n const levelRows = new Map<string, VerifiedManifestBundleRow>();\n for (const level of levelEntries) {\n const row = await kekLevelRow(level);\n const held = row && levelRows.get(row.objectId);\n if (row && (!held || held.epoch <= row.epoch))\n levelRows.set(row.objectId, row);\n }\n return [...(await bundleRows(bundleEntries)), ...levelRows.values()];\n}\n\nfunction bundleRows(\n entries: readonly VerifiedBundle[],\n): Promise<VerifiedManifestBundleRow[]> {\n const unique = new Map(\n entries.map((entry) => [entry.bundle.manifestHash, entry]),\n );\n return Promise.all(\n [...unique.values()].map(async ({ bundle, checkpoint }) => {\n const bundleJson = JSON.stringify(bundle);\n return {\n manifestHash: bundle.manifestHash,\n organizationId: checkpoint.organizationId,\n objectKind: checkpoint.objectKind,\n objectId: checkpoint.objectId,\n epoch: checkpoint.epoch,\n bundleJson,\n bundleDigest: await sha256Hex(bundleJson),\n };\n }),\n );\n}\n\n/**\n * Records verified bundles inside the transaction that finalizes their\n * projection's checkpoints, so they commit or roll back with it and no cache\n * work outlives the verification. Freshly verified bytes replace any stored\n * copy.\n */\nexport async function writeVerifiedManifestBundlesInTransaction(\n tx: ClientSQLiteTransactionScope,\n rows: readonly VerifiedManifestBundleRow[],\n verifiedAt: string,\n): Promise<void> {\n if (rows.length === 0) return;\n const stored = await touchStoredDigests(\n tx,\n rows.map((row) => row.manifestHash),\n verifiedAt,\n );\n // A repeated hash keeps its last changed row, as sequential upserts would.\n const changed = new Map(\n rows\n .filter((row) => stored.get(row.manifestHash) !== row.bundleDigest)\n .map((row) => [row.manifestHash, { ...row, verifiedAt }]),\n );\n for (const batch of slices([...changed.values()], BUNDLE_WRITE_BATCH_SIZE))\n await tx\n .insert(bundles)\n .values(batch)\n .onConflictDoUpdate({\n target: bundles.manifestHash,\n set: {\n organizationId: excludedValue(bundles.organizationId),\n objectKind: excludedValue(bundles.objectKind),\n objectId: excludedValue(bundles.objectId),\n epoch: excludedValue(bundles.epoch),\n bundleJson: excludedValue(bundles.bundleJson),\n bundleDigest: excludedValue(bundles.bundleDigest),\n verifiedAt: excludedValue(bundles.verifiedAt),\n },\n })\n .run();\n // All incremental SDK level writes pass here. Both checkpoint callers\n // prepare them with verifiedManifestBundleRows (one level per container),\n // then write and drop siblings in the same serialized transaction. Thus an\n // unchanged level already removed its siblings; eviction/reset only delete.\n // Restored caches must preserve that invariant too: this fast path does not\n // repair externally injected stale siblings.\n await dropSupersededKekLevels(tx, [...changed.values()]);\n // Replacing or touching existing rows cannot grow the bounded cache.\n if (rows.some((row) => !stored.has(row.manifestHash))) {\n await pruneInTransaction(tx);\n }\n}\n\n/**\n * A container keeps only its latest verified level: the API serves its\n * current level, so an older one can never be cited usefully again.\n */\nasync function dropSupersededKekLevels(\n tx: ClientSQLiteTransactionScope,\n rows: readonly VerifiedManifestBundleRow[],\n): Promise<void> {\n const levels = rows.filter((row) => row.objectKind === KEK_LEVEL_OBJECT_KIND);\n for (const batch of batches(levels))\n await tx\n .delete(bundles)\n .where(\n and(\n eq(bundles.objectKind, KEK_LEVEL_OBJECT_KIND),\n inArray(\n bundles.objectId,\n batch.map((row) => row.objectId),\n ),\n notInArray(\n bundles.manifestHash,\n batch.map((row) => row.manifestHash),\n ),\n ),\n )\n .run();\n}\n\nasync function touchStoredDigests(\n tx: ClientSQLiteTransactionScope,\n manifestHashes: readonly string[],\n verifiedAt: string,\n): Promise<Map<string, string>> {\n const digests = new Map<string, string>();\n for (const batch of batches(manifestHashes)) {\n const rows = await tx\n .update(bundles)\n .set({ verifiedAt })\n .where(inArray(bundles.manifestHash, batch))\n .returning({\n bundleDigest: bundles.bundleDigest,\n manifestHash: bundles.manifestHash,\n });\n for (const row of rows) digests.set(row.manifestHash, row.bundleDigest);\n }\n return digests;\n}\n\n/**\n * The latest verified KEK level of each container the target's projection\n * walks (supplemented by organization-recency levels for a pending move,\n * or when the lineage has no stored level); then verified bundles of those\n * objects, newest epochs first; then\n * the most recently verified bundles of its organization, since a\n * just-verified parent is the likeliest part of a new child's projection.\n * Citations never leave the target's organization: an object whose\n * organization the device cannot place cites nothing. Damaged rows are\n * dropped.\n */\nexport async function loadVerifiedManifestCitations(\n execSql: ExecSql,\n target: WriterProjectionTarget,\n requestedLimit = KNOWN_MANIFEST_HINT_LIMIT,\n): Promise<HeldProjectionCitation[]> {\n const limit = Math.min(KNOWN_MANIFEST_HINT_LIMIT, Math.floor(requestedLimit));\n if (!(limit > 0)) return [];\n const loadGeneration = evictionGeneration;\n citationLoadsInFlight += 1;\n try {\n return await loadCitableManifestCitations(execSql, target, limit).then(\n (cited) => cited.filter((citation) => citable(citation, loadGeneration)),\n );\n } finally {\n citationLoadsInFlight -= 1;\n if (citationLoadsInFlight === 0) evictedInGeneration.clear();\n }\n}\n\nasync function loadCitableManifestCitations(\n execSql: ExecSql,\n target: WriterProjectionTarget,\n limit: number,\n): Promise<HeldProjectionCitation[]> {\n await ensureSqlTables(execSql, [\n ...verifiedManifestBundleTables,\n ...containerTables,\n ...documentContainerProjectionTables,\n ...documentProjectionTables,\n ...localIntentTables,\n ]);\n const { db } = getClientSQLitePersistenceRuntime(execSql);\n const objects = await citedObjects(db, target);\n const organizationId = await targetOrganization(db, target, objects);\n if (organizationId === null) return [];\n const { cited, damaged } = await collectVerifiedManifestCitations(\n db,\n organizationId,\n objects,\n target,\n limit,\n );\n if (damaged.length > 0)\n await dropVerifiedManifestBundles(execSql, damaged).catch(() => undefined);\n return cited;\n}\n\n// Manifest hashes whose held rows a refused read is dropping: no read cites\n// them meanwhile, so none can be rebuilt from the bytes being dropped. Each\n// eviction also advances a generation, so a citation load that started\n// before it never returns the rows it read: they may already be gone.\nconst suppressedCitations = new Map<string, number>();\nconst evictedInGeneration = new Map<string, number>();\nlet evictionGeneration = 0;\n// Loads in flight; once none overlap, the eviction log has nothing to guard.\nlet citationLoadsInFlight = 0;\n\n/** Keeps these held bundles out of citations until the release runs. */\nexport function suppressHeldCitations(\n manifestHashes: readonly string[],\n): () => void {\n evictionGeneration += 1;\n for (const hash of manifestHashes) {\n suppressedCitations.set(hash, (suppressedCitations.get(hash) ?? 0) + 1);\n evictedInGeneration.set(hash, evictionGeneration);\n }\n return () => {\n // The drop is complete: a load that started before now may hold the\n // dropped bytes, so it is newer than none of them.\n evictionGeneration += 1;\n for (const hash of manifestHashes) {\n evictedInGeneration.set(hash, evictionGeneration);\n const count = (suppressedCitations.get(hash) ?? 1) - 1;\n if (count > 0) suppressedCitations.set(hash, count);\n else suppressedCitations.delete(hash);\n }\n };\n}\n\nfunction citable(\n citation: HeldProjectionCitation,\n loadGeneration: number,\n): boolean {\n if (!(\"manifestHash\" in citation)) return true;\n const { manifestHash } = citation;\n return (\n !suppressedCitations.has(manifestHash) &&\n (evictedInGeneration.get(manifestHash) ?? 0) <= loadGeneration\n );\n}\n\n/**\n * Drops the stored rows of held bundles a projection that cited them failed\n * to verify with, so the next read fetches them from the server. Only a row\n * still holding the exact bytes cited goes, so a newer verified copy written\n * meanwhile stays; nothing is dropped once `stillCurrent` turns false.\n * Resolves whether the drop committed.\n */\nexport async function dropHeldManifestBundles(\n execSql: ExecSql,\n heldBundles: readonly ServedAccessManifestBundleWireResponse[],\n stillCurrent?: () => boolean,\n): Promise<boolean> {\n if (heldBundles.length === 0) return true;\n const cited = await Promise.all(\n heldBundles.map(async (bundle) => ({\n manifestHash: bundle.manifestHash,\n bundleDigest: await sha256Hex(JSON.stringify(bundle)),\n })),\n );\n await ensureSqlTables(execSql, verifiedManifestBundleTables);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const drop = async (tx: ClientSQLiteTransactionScope) => {\n for (const row of cited)\n await tx\n .delete(bundles)\n .where(\n and(\n eq(bundles.manifestHash, row.manifestHash),\n eq(bundles.bundleDigest, row.bundleDigest),\n ),\n )\n .run();\n };\n if (!stillCurrent) {\n await runtime.transaction(drop, { behavior: \"immediate\" });\n return true;\n }\n const { committed } = await runtime.guardedTransaction(drop, stillCurrent, {\n behavior: \"immediate\",\n });\n return committed;\n}\n\n/** Drops damaged stored rows so no later read cites them. */\nasync function dropVerifiedManifestBundles(\n execSql: ExecSql,\n manifestHashes: readonly string[],\n): Promise<void> {\n if (manifestHashes.length === 0) return;\n await ensureSqlTables(execSql, verifiedManifestBundleTables);\n await getClientSQLitePersistenceRuntime(execSql).runMutation(\n async (handle) => {\n for (const batch of batches([...new Set(manifestHashes)]))\n await handle\n .delete(bundles)\n .where(inArray(bundles.manifestHash, batch))\n .run();\n },\n );\n}\n\n/** Cites from whichever database the signed-in identity currently uses. */\nexport function createVerifiedManifestCitations(\n resolveExecSql: () => ExecSql | null,\n): VerifiedManifestCitations {\n return {\n cite: async (target) => {\n const execSql = resolveExecSql();\n return execSql ? loadVerifiedManifestCitations(execSql, target) : [];\n },\n };\n}\n\n/** Drops an organization's verified bundles when a remote reset forgets it. */\nexport async function deleteVerifiedManifestBundlesForOrganization(\n tx: ClientSQLiteTransactionScope,\n organizationId: string,\n): Promise<void> {\n await tx\n .delete(bundles)\n .where(eq(bundles.organizationId, organizationId))\n .run();\n}\n"]}
@@ -611,8 +611,181 @@ export declare const dormantMetadataSweepRequests: import("drizzle-orm/sqlite-co
611
611
  };
612
612
  dialect: "sqlite";
613
613
  }>;
614
+ /**
615
+ * Container metadata documents a listing showed may have moved since this
616
+ * client last read them, and that still owe a read. A hint lost before this
617
+ * client subscribed, or while it was offline, is otherwise never recovered for
618
+ * a clean metadata document. Written before the listing's timestamps and lane
619
+ * watermark advance, so a restart before the read still owes it.
620
+ */
621
+ export declare const containerMetadataRevalidations: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
622
+ name: "container_metadata_revalidations";
623
+ schema: undefined;
624
+ columns: {
625
+ documentId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
626
+ name: "document_id";
627
+ tableName: "container_metadata_revalidations";
628
+ dataType: "string";
629
+ columnType: "SQLiteText";
630
+ data: string;
631
+ driverParam: string;
632
+ notNull: true;
633
+ hasDefault: false;
634
+ isPrimaryKey: false;
635
+ isAutoincrement: false;
636
+ hasRuntimeDefault: false;
637
+ enumValues: [string, ...string[]];
638
+ baseColumn: never;
639
+ identity: undefined;
640
+ generated: undefined;
641
+ }, {}, {
642
+ length: number | undefined;
643
+ }>;
644
+ advertisedVersionVector: import("drizzle-orm/sqlite-core").SQLiteColumn<{
645
+ name: "advertised_version_vector";
646
+ tableName: "container_metadata_revalidations";
647
+ dataType: "string";
648
+ columnType: "SQLiteText";
649
+ data: string;
650
+ driverParam: string;
651
+ notNull: true;
652
+ hasDefault: false;
653
+ isPrimaryKey: false;
654
+ isAutoincrement: false;
655
+ hasRuntimeDefault: false;
656
+ enumValues: [string, ...string[]];
657
+ baseColumn: never;
658
+ identity: undefined;
659
+ generated: undefined;
660
+ }, {}, {
661
+ length: number | undefined;
662
+ }>;
663
+ revision: import("drizzle-orm/sqlite-core").SQLiteColumn<{
664
+ name: "revision";
665
+ tableName: "container_metadata_revalidations";
666
+ dataType: "string";
667
+ columnType: "SQLiteText";
668
+ data: string;
669
+ driverParam: string;
670
+ notNull: true;
671
+ hasDefault: false;
672
+ isPrimaryKey: false;
673
+ isAutoincrement: false;
674
+ hasRuntimeDefault: false;
675
+ enumValues: [string, ...string[]];
676
+ baseColumn: never;
677
+ identity: undefined;
678
+ generated: undefined;
679
+ }, {}, {
680
+ length: number | undefined;
681
+ }>;
682
+ requestedAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
683
+ name: "requested_at";
684
+ tableName: "container_metadata_revalidations";
685
+ dataType: "string";
686
+ columnType: "SQLiteText";
687
+ data: string;
688
+ driverParam: string;
689
+ notNull: true;
690
+ hasDefault: false;
691
+ isPrimaryKey: false;
692
+ isAutoincrement: false;
693
+ hasRuntimeDefault: false;
694
+ enumValues: [string, ...string[]];
695
+ baseColumn: never;
696
+ identity: undefined;
697
+ generated: undefined;
698
+ }, {}, {
699
+ length: number | undefined;
700
+ }>;
701
+ };
702
+ dialect: "sqlite";
703
+ }>;
614
704
  export declare const containerTableSchemas: ReadonlyArray<SqlTableSchema>;
615
705
  export declare const containerSQLiteSchema: {
706
+ containerMetadataRevalidations: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
707
+ name: "container_metadata_revalidations";
708
+ schema: undefined;
709
+ columns: {
710
+ documentId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
711
+ name: "document_id";
712
+ tableName: "container_metadata_revalidations";
713
+ dataType: "string";
714
+ columnType: "SQLiteText";
715
+ data: string;
716
+ driverParam: string;
717
+ notNull: true;
718
+ hasDefault: false;
719
+ isPrimaryKey: false;
720
+ isAutoincrement: false;
721
+ hasRuntimeDefault: false;
722
+ enumValues: [string, ...string[]];
723
+ baseColumn: never;
724
+ identity: undefined;
725
+ generated: undefined;
726
+ }, {}, {
727
+ length: number | undefined;
728
+ }>;
729
+ advertisedVersionVector: import("drizzle-orm/sqlite-core").SQLiteColumn<{
730
+ name: "advertised_version_vector";
731
+ tableName: "container_metadata_revalidations";
732
+ dataType: "string";
733
+ columnType: "SQLiteText";
734
+ data: string;
735
+ driverParam: string;
736
+ notNull: true;
737
+ hasDefault: false;
738
+ isPrimaryKey: false;
739
+ isAutoincrement: false;
740
+ hasRuntimeDefault: false;
741
+ enumValues: [string, ...string[]];
742
+ baseColumn: never;
743
+ identity: undefined;
744
+ generated: undefined;
745
+ }, {}, {
746
+ length: number | undefined;
747
+ }>;
748
+ revision: import("drizzle-orm/sqlite-core").SQLiteColumn<{
749
+ name: "revision";
750
+ tableName: "container_metadata_revalidations";
751
+ dataType: "string";
752
+ columnType: "SQLiteText";
753
+ data: string;
754
+ driverParam: string;
755
+ notNull: true;
756
+ hasDefault: false;
757
+ isPrimaryKey: false;
758
+ isAutoincrement: false;
759
+ hasRuntimeDefault: false;
760
+ enumValues: [string, ...string[]];
761
+ baseColumn: never;
762
+ identity: undefined;
763
+ generated: undefined;
764
+ }, {}, {
765
+ length: number | undefined;
766
+ }>;
767
+ requestedAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
768
+ name: "requested_at";
769
+ tableName: "container_metadata_revalidations";
770
+ dataType: "string";
771
+ columnType: "SQLiteText";
772
+ data: string;
773
+ driverParam: string;
774
+ notNull: true;
775
+ hasDefault: false;
776
+ isPrimaryKey: false;
777
+ isAutoincrement: false;
778
+ hasRuntimeDefault: false;
779
+ enumValues: [string, ...string[]];
780
+ baseColumn: never;
781
+ identity: undefined;
782
+ generated: undefined;
783
+ }, {}, {
784
+ length: number | undefined;
785
+ }>;
786
+ };
787
+ dialect: "sqlite";
788
+ }>;
616
789
  containers: import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
617
790
  name: "containers";
618
791
  schema: undefined;
@@ -87,6 +87,22 @@ export const dormantMetadataSweepRequests = sqliteTable("dormant_metadata_sweep_
87
87
  }, (table) => [
88
88
  primaryKey({ columns: [table.organizationId, table.requesterUserId] }),
89
89
  ]);
90
+ /**
91
+ * Container metadata documents a listing showed may have moved since this
92
+ * client last read them, and that still owe a read. A hint lost before this
93
+ * client subscribed, or while it was offline, is otherwise never recovered for
94
+ * a clean metadata document. Written before the listing's timestamps and lane
95
+ * watermark advance, so a restart before the read still owes it.
96
+ */
97
+ export const containerMetadataRevalidations = sqliteTable("container_metadata_revalidations", {
98
+ documentId: text("document_id").notNull(),
99
+ // The metadata version the listing advertised; a read settles the request
100
+ // only once the local copy covers it.
101
+ advertisedVersionVector: text("advertised_version_vector").notNull(),
102
+ // Replaced on every request, so a read settles only the request it saw.
103
+ revision: text("revision").notNull(),
104
+ requestedAt: text("requested_at").notNull(),
105
+ }, (table) => [primaryKey({ columns: [table.documentId] })]);
90
106
  export const containerTableSchemas = [
91
107
  {
92
108
  ...defineSqlTableSchema(containers),
@@ -96,11 +112,13 @@ export const containerTableSchemas = [
96
112
  ...defineSqlTableSchema(containerHydrationTombstones),
97
113
  requiredColumns: ["cleared"],
98
114
  },
115
+ defineSqlTableSchema(containerMetadataRevalidations),
99
116
  defineSqlTableSchema(dormantContainerMetadata),
100
117
  defineSqlTableSchema(dormantMetadataSweepRequests),
101
118
  defineSqlTableSchema(supersededContainerBindings),
102
119
  ];
103
120
  export const containerSQLiteSchema = {
121
+ containerMetadataRevalidations,
104
122
  containers,
105
123
  containerHydrationTombstones,
106
124
  dormantContainerMetadata,
@@ -1 +1 @@
1
- {"version":3,"file":"containerSchema.js","sourceRoot":"","sources":["containerSchema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EACL,KAAK,EACL,OAAO,EACP,UAAU,EACV,WAAW,EACX,IAAI,GACL,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,oBAAoB,EAAuB,MAAM,mBAAmB,CAAC;AAE9E,MAAM,iBAAiB,GAAG,wBAAwB,CAAC;AAEnD;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,WAAW,CACnC,YAAY,EACZ;IACE,EAAE,EAAE,IAAI,CAAC,IAAI,CAAC;IACd,cAAc,EAAE,IAAI,CAAC,iBAAiB,CAAC,CAAC,OAAO,EAAE;IACjD,QAAQ,EAAE,IAAI,CAAC,WAAW,CAAC;IAC3B,kBAAkB,EAAE,IAAI,CAAC,sBAAsB,CAAC;IAChD,UAAU,EAAE,IAAI,CAAC,aAAa,CAAC;IAC/B,WAAW,EAA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AAC,OAAO,CAAC,CAAC,CAAC;IACtD,YAAY,EAAE,OAAO,CAAC,eAAe,CAAC,CAAC,OAAO,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;IAC3D,eAAe,EAAE,IAAI,CAAC,mBAAmB,CAAC;IAC1C,WAAW,EAAE,IAAI,CAAC,cAAc,CAAC,CAAC,OAAO,EAAE;CAC5C,EACD,CAAC,KAAK,EAAE,EAAE,CAAC;IACT,UAAU,CAAC,EAAE,OAAO,EAAE,CAAC,KAAK,CAAC,cAAc,EAAE,KAAK,CAAC,eAAe,CAAC,EAAE,CAAC;CACvE,CACF,CAAC;AAEF,MAAM,CAAC,MAAM,qBAAqB,GAAkC;IAClE;QACE,GAAG,oBAAoB,CAAC,UAAU,CAAC;QACnC,eAAe,EAAE,CAAC,cAAc,EAAE,MAAM,CAAC;KAC1C;IACD;QACE,GAAG,oBAAoB,CAAC,4BAA4B,CAAC;QACrD,eAAe,EAAE,CAAC,SAAS,CAAC;KAC7B;IACD,oBAAoB,CAAC,wBAAwB,CAAC;IAC9C,oBAAoB,CAAC,4BAA4B,CAAC;IAClD,oBAAoB,CAAC,2BAA2B,CAAC;CAClD,CAAC;AAEF,MAAM,CAAC,MAAM,qBAAqB,GAAG;IACnC,UAAU;IACV,4BAA4B;IAC5B,wBAAwB;IACxB,4BAA4B;IAC5B,2BAA2B;CAC5B,CAAC","sourcesContent":["import { sql } from \"drizzle-orm\";\nimport {\n index,\n integer,\n primaryKey,\n sqliteTable,\n text,\n} from \"drizzle-orm/sqlite-core\";\nimport { defineSqlTableSchema, type SqlTableSchema } from \"../sqlTableSchema\";\n\nconst accessLevelColumn = \"effective_access_level\";\n\n/**\n * Materialized local container tree.\n *\n * Container rows describe the tree and its encrypted metadata document;\n * metadata rows live in `documents`. `id` is the primary key for structural\n * lookups. `metadataDocumentId` is the server metadata-document id when known;\n * `systemSlot` is an optional opaque app-owned slot. `displayName` and `icon`\n * are the decrypted metadata projection lists read: `displayName` stays\n * nullable so presentation falls back to `/` for a root and `Untitled`\n * otherwise. Local timestamps track client storage/structural changes, while\n * server timestamps are populated once the container has synced.\n * `(parentId) where parentId is not null` serves child-folder listings.\n */\nexport const containers = sqliteTable(\n \"containers\",\n {\n id: text(\"id\"),\n organizationId: text(\"organization_id\").notNull(),\n parentId: text(\"parent_id\"),\n metadataDocumentId: text(\"metadata_document_id\"),\n systemSlot: text(\"system_slot\"),\n displayName: text(\"display_name\"),\n icon: text(\"icon\"),\n effectiveAccessLevel: text(accessLevelColumn).notNull().default(\"read\"),\n localCreatedAt: text(\"local_created_at\").notNull(),\n localUpdatedAt: text(\"local_updated_at\").notNull(),\n serverCreatedAt: text(\"server_created_at\"),\n serverUpdatedAt: text(\"server_updated_at\"),\n },\n (table) => [\n primaryKey({ columns: [table.id] }),\n index(\"containers_parent_idx\")\n .on(table.parentId)\n .where(sql`${table.parentId} IS NOT NULL`),\n ],\n);\n\n/**\n * Latest removal observed for each container. Hydration must observe the same\n * generation before fetching verified restoration evidence; unsigned clocks\n * never establish a terminal deletion or bypass a concurrent removal. Cleared\n * observations retain their generation so remove/restore/remove cannot reuse it.\n */\nexport const containerHydrationTombstones = sqliteTable(\n \"container_hydration_tombstones\",\n {\n containerId: text(\"container_id\").notNull(),\n generation: integer(\"generation\").notNull().default(1),\n cleared: integer(\"cleared\", { mode: \"boolean\" }).notNull().default(false),\n reason: text(\"reason\").notNull(),\n updatedAt: text(\"updated_at\").notNull(),\n },\n (table) => [primaryKey({ columns: [table.containerId] })],\n);\n\n/**\n * Organization attribution for container metadata retained after access loss.\n * The container row is removed on revocation, so this marker retains the\n * organization scope needed by a later access-restoration sweep.\n */\nexport const dormantContainerMetadata = sqliteTable(\n \"dormant_container_metadata\",\n {\n containerId: text(\"container_id\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n retainedAt: text(\"retained_at\").notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.containerId] }),\n index(\"dormant_container_metadata_organization_idx\").on(\n table.organizationId,\n table.containerId,\n ),\n ],\n);\n\n/**\n * Organizations a held folder was re-homed away from. Purged-organization\n * recovery re-creates folders under their existing ids and a purged\n * organization never returns, so a later proof binding the folder back to one\n * of these organizations is a replay. Retained across remote resets.\n */\nexport const supersededContainerBindings = sqliteTable(\n \"superseded_container_bindings\",\n {\n containerId: text(\"container_id\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n supersededAt: text(\"superseded_at\").notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.containerId, table.organizationId] }),\n ],\n);\n\n/**\n * Durable request for a post-access-restoration crawl and sweep. Attempt state\n * enforces exponential backoff and a bounded retry budget across restarts.\n */\nexport const dormantMetadataSweepRequests = sqliteTable(\n \"dormant_metadata_sweep_requests\",\n {\n organizationId: text(\"organization_id\").notNull(),\n requesterUserId: text(\"requester_user_id\").notNull(),\n generation: integer(\"generation\").notNull().default(1),\n attemptCount: integer(\"attempt_count\").notNull().default(0),\n lastAttemptedAt: text(\"last_attempted_at\"),\n requestedAt: text(\"requested_at\").notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.organizationId, table.requesterUserId] }),\n ],\n);\n\nexport const containerTableSchemas: ReadonlyArray<SqlTableSchema> = [\n {\n ...defineSqlTableSchema(containers),\n requiredColumns: [\"display_name\", \"icon\"],\n },\n {\n ...defineSqlTableSchema(containerHydrationTombstones),\n requiredColumns: [\"cleared\"],\n },\n defineSqlTableSchema(dormantContainerMetadata),\n defineSqlTableSchema(dormantMetadataSweepRequests),\n defineSqlTableSchema(supersededContainerBindings),\n];\n\nexport const containerSQLiteSchema = {\n containers,\n containerHydrationTombstones,\n dormantContainerMetadata,\n dormantMetadataSweepRequests,\n supersededContainerBindings,\n};\n"]}
1
+ {"version":3,"file":"containerSchema.js","sourceRoot":"","sources":["containerSchema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EACL,KAAK,EACL,OAAO,EACP,UAAU,EACV,WAAW,EACX,IAAI,GACL,MA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K,EAAE,EAAE,CAAC,CAAC,UAAU,CAAC,EAAE,OAAO,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC,CACzD,CAAC;AAEF,MAAM,CAAC,MAAM,qBAAqB,GAAkC;IAClE;QACE,GAAG,oBAAoB,CAAC,UAAU,CAAC;QACnC,eAAe,EAAE,CAAC,cAAc,EAAE,MAAM,CAAC;KAC1C;IACD;QACE,GAAG,oBAAoB,CAAC,4BAA4B,CAAC;QACrD,eAAe,EAAE,CAAC,SAAS,CAAC;KAC7B;IACD,oBAAoB,CAAC,8BAA8B,CAAC;IACpD,oBAAoB,CAAC,wBAAwB,CAAC;IAC9C,oBAAoB,CAAC,4BAA4B,CAAC;IAClD,oBAAoB,CAAC,2BAA2B,CAAC;CAClD,CAAC;AAEF,MAAM,CAAC,MAAM,qBAAqB,GAAG;IACnC,8BAA8B;IAC9B,UAAU;IACV,4BAA4B;IAC5B,wBAAwB;IACxB,4BAA4B;IAC5B,2BAA2B;CAC5B,CAAC","sourcesContent":["import { sql } from \"drizzle-orm\";\nimport {\n index,\n integer,\n primaryKey,\n sqliteTable,\n text,\n} from \"drizzle-orm/sqlite-core\";\nimport { defineSqlTableSchema, type SqlTableSchema } from \"../sqlTableSchema\";\n\nconst accessLevelColumn = \"effective_access_level\";\n\n/**\n * Materialized local container tree.\n *\n * Container rows describe the tree and its encrypted metadata document;\n * metadata rows live in `documents`. `id` is the primary key for structural\n * lookups. `metadataDocumentId` is the server metadata-document id when known;\n * `systemSlot` is an optional opaque app-owned slot. `displayName` and `icon`\n * are the decrypted metadata projection lists read: `displayName` stays\n * nullable so presentation falls back to `/` for a root and `Untitled`\n * otherwise. Local timestamps track client storage/structural changes, while\n * server timestamps are populated once the container has synced.\n * `(parentId) where parentId is not null` serves child-folder listings.\n */\nexport const containers = sqliteTable(\n \"containers\",\n {\n id: text(\"id\"),\n organizationId: text(\"organization_id\").notNull(),\n parentId: text(\"parent_id\"),\n metadataDocumentId: text(\"metadata_document_id\"),\n systemSlot: text(\"system_slot\"),\n displayName: text(\"display_name\"),\n icon: text(\"icon\"),\n effectiveAccessLevel: text(accessLevelColumn).notNull().default(\"read\"),\n localCreatedAt: text(\"local_created_at\").notNull(),\n localUpdatedAt: text(\"local_updated_at\").notNull(),\n serverCreatedAt: text(\"server_created_at\"),\n serverUpdatedAt: text(\"server_updated_at\"),\n },\n (table) => [\n primaryKey({ columns: [table.id] }),\n index(\"containers_parent_idx\")\n .on(table.parentId)\n .where(sql`${table.parentId} IS NOT NULL`),\n ],\n);\n\n/**\n * Latest removal observed for each container. Hydration must observe the same\n * generation before fetching verified restoration evidence; unsigned clocks\n * never establish a terminal deletion or bypass a concurrent removal. Cleared\n * observations retain their generation so remove/restore/remove cannot reuse it.\n */\nexport const containerHydrationTombstones = sqliteTable(\n \"container_hydration_tombstones\",\n {\n containerId: text(\"container_id\").notNull(),\n generation: integer(\"generation\").notNull().default(1),\n cleared: integer(\"cleared\", { mode: \"boolean\" }).notNull().default(false),\n reason: text(\"reason\").notNull(),\n updatedAt: text(\"updated_at\").notNull(),\n },\n (table) => [primaryKey({ columns: [table.containerId] })],\n);\n\n/**\n * Organization attribution for container metadata retained after access loss.\n * The container row is removed on revocation, so this marker retains the\n * organization scope needed by a later access-restoration sweep.\n */\nexport const dormantContainerMetadata = sqliteTable(\n \"dormant_container_metadata\",\n {\n containerId: text(\"container_id\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n retainedAt: text(\"retained_at\").notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.containerId] }),\n index(\"dormant_container_metadata_organization_idx\").on(\n table.organizationId,\n table.containerId,\n ),\n ],\n);\n\n/**\n * Organizations a held folder was re-homed away from. Purged-organization\n * recovery re-creates folders under their existing ids and a purged\n * organization never returns, so a later proof binding the folder back to one\n * of these organizations is a replay. Retained across remote resets.\n */\nexport const supersededContainerBindings = sqliteTable(\n \"superseded_container_bindings\",\n {\n containerId: text(\"container_id\").notNull(),\n organizationId: text(\"organization_id\").notNull(),\n supersededAt: text(\"superseded_at\").notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.containerId, table.organizationId] }),\n ],\n);\n\n/**\n * Durable request for a post-access-restoration crawl and sweep. Attempt state\n * enforces exponential backoff and a bounded retry budget across restarts.\n */\nexport const dormantMetadataSweepRequests = sqliteTable(\n \"dormant_metadata_sweep_requests\",\n {\n organizationId: text(\"organization_id\").notNull(),\n requesterUserId: text(\"requester_user_id\").notNull(),\n generation: integer(\"generation\").notNull().default(1),\n attemptCount: integer(\"attempt_count\").notNull().default(0),\n lastAttemptedAt: text(\"last_attempted_at\"),\n requestedAt: text(\"requested_at\").notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.organizationId, table.requesterUserId] }),\n ],\n);\n\n/**\n * Container metadata documents a listing showed may have moved since this\n * client last read them, and that still owe a read. A hint lost before this\n * client subscribed, or while it was offline, is otherwise never recovered for\n * a clean metadata document. Written before the listing's timestamps and lane\n * watermark advance, so a restart before the read still owes it.\n */\nexport const containerMetadataRevalidations = sqliteTable(\n \"container_metadata_revalidations\",\n {\n documentId: text(\"document_id\").notNull(),\n // The metadata version the listing advertised; a read settles the request\n // only once the local copy covers it.\n advertisedVersionVector: text(\"advertised_version_vector\").notNull(),\n // Replaced on every request, so a read settles only the request it saw.\n revision: text(\"revision\").notNull(),\n requestedAt: text(\"requested_at\").notNull(),\n },\n (table) => [primaryKey({ columns: [table.documentId] })],\n);\n\nexport const containerTableSchemas: ReadonlyArray<SqlTableSchema> = [\n {\n ...defineSqlTableSchema(containers),\n requiredColumns: [\"display_name\", \"icon\"],\n },\n {\n ...defineSqlTableSchema(containerHydrationTombstones),\n requiredColumns: [\"cleared\"],\n },\n defineSqlTableSchema(containerMetadataRevalidations),\n defineSqlTableSchema(dormantContainerMetadata),\n defineSqlTableSchema(dormantMetadataSweepRequests),\n defineSqlTableSchema(supersededContainerBindings),\n];\n\nexport const containerSQLiteSchema = {\n containerMetadataRevalidations,\n containers,\n containerHydrationTombstones,\n dormantContainerMetadata,\n dormantMetadataSweepRequests,\n supersededContainerBindings,\n};\n"]}