@tearleads/client-sdk 0.1.36 → 0.1.38

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 (68) hide show
  1. package/client/Tearleads.d.ts +4 -3
  2. package/client/Tearleads.js +4 -3
  3. package/client/Tearleads.js.map +1 -1
  4. package/client/organizations/organizationGroupHistory.js +1 -1
  5. package/client/organizations/organizationGroupHistory.js.map +1 -1
  6. package/client/organizations/organizationHistory.js +1 -1
  7. package/client/organizations/organizationHistory.js.map +1 -1
  8. package/data/keyingProjectionVerification/principalPolicyVerification.js +1 -2
  9. package/data/keyingProjectionVerification/principalPolicyVerification.js.map +1 -1
  10. package/data/keyingProjectionVerification/resolvedPrincipalPolicy.js +39 -51
  11. package/data/keyingProjectionVerification/resolvedPrincipalPolicy.js.map +1 -1
  12. package/data/keyingProjectionVerification/types.d.ts +1 -1
  13. package/data/keyingProjectionVerification/types.js.map +1 -1
  14. package/data/persistence/organizations/organizationAccessRevocationPersistence.js +4 -0
  15. package/data/persistence/organizations/organizationAccessRevocationPersistence.js.map +1 -1
  16. package/data/persistence/organizations/organizationReadModelPersistence.js +7 -1
  17. package/data/persistence/organizations/organizationReadModelPersistence.js.map +1 -1
  18. package/data/principals/principalRecoveryEpoch.js +18 -0
  19. package/data/principals/principalRecoveryEpoch.js.map +1 -0
  20. package/internal/api-client/ApiClient.d.ts +3 -0
  21. package/internal/api-client/ApiClient.js +10 -7
  22. package/internal/api-client/ApiClient.js.map +1 -1
  23. package/internal/api-client/webSocketTickets.js +45 -0
  24. package/internal/api-client/webSocketTickets.js.map +1 -0
  25. package/internal/validators/operation/auth.d.ts +20 -0
  26. package/internal/validators/realtime/index.js +2 -2
  27. package/internal/validators/realtime/index.js.map +1 -1
  28. package/internal/validators/realtime/wsServerFrames.js +3 -8
  29. package/internal/validators/realtime/wsServerFrames.js.map +1 -1
  30. package/internal/validators/realtime/wsShared.js +6 -0
  31. package/internal/validators/realtime/wsShared.js.map +1 -1
  32. package/internal/validators/response/auth/verify.d.ts +8 -0
  33. package/internal/validators/response/auth/verify.js +3 -0
  34. package/internal/validators/response/auth/verify.js.map +1 -1
  35. package/package.json +1 -1
  36. package/stores/documents/documentStore.js +3 -3
  37. package/stores/documents/documentStore.js.map +1 -1
  38. package/sync/reconciliation/service.js +22 -12
  39. package/sync/reconciliation/service.js.map +1 -1
  40. package/sync/reconciliation/serviceTypes.d.ts +10 -1
  41. package/sync/reconciliation/serviceTypes.js.map +1 -1
  42. package/workflows/organizations/currentGroupPolicyMutationContext.js +5 -5
  43. package/workflows/organizations/currentGroupPolicyMutationContext.js.map +1 -1
  44. package/workflows/principals/principalCurrentRecoveryBatch.js +1 -1
  45. package/workflows/principals/principalCurrentRecoveryBatch.js.map +1 -1
  46. package/workflows/principals/principalRecoveryLocalPreference.js.map +1 -1
  47. package/workflows/principals/principalRecoveryMemo.d.ts +9 -4
  48. package/workflows/principals/principalRecoveryMemo.js +94 -34
  49. package/workflows/principals/principalRecoveryMemo.js.map +1 -1
  50. package/workflows/principals/principalRecoveryMemoValidity.js +33 -0
  51. package/workflows/principals/principalRecoveryMemoValidity.js.map +1 -0
  52. package/workflows/principals/principalRecoveryOutage.js +2 -2
  53. package/workflows/principals/principalRecoveryOutage.js.map +1 -1
  54. package/workflows/principals/recoverCurrentOrganizationPolicy.js +8 -3
  55. package/workflows/principals/recoverCurrentOrganizationPolicy.js.map +1 -1
  56. package/workflows/principals/recoverPrincipalPolicyHistory.js +42 -8
  57. package/workflows/principals/recoverPrincipalPolicyHistory.js.map +1 -1
  58. package/workflows/principals/recoverPublicPrincipalHistory.js +5 -5
  59. package/workflows/principals/recoverPublicPrincipalHistory.js.map +1 -1
  60. package/workflows/principals/recoverScopedPrincipalPolicyHistory.d.ts +9 -2
  61. package/workflows/principals/recoverScopedPrincipalPolicyHistory.js +8 -2
  62. package/workflows/principals/recoverScopedPrincipalPolicyHistory.js.map +1 -1
  63. package/workflows/principals/runtimePolicyRecovery.js +4 -1
  64. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  65. package/workflows/principals/runtimePolicyWarmer.js +12 -4
  66. package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
  67. package/workflows/runtimeInput.d.ts +4 -3
  68. package/workflows/runtimeInput.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"service.js","sourceRoot":"","sources":["service.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gCAAgC,GAEjC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,yBAAyB,EACzB,iBAAiB,EACjB,qCAAqC,EAErC,mBAAmB,GACpB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,0BAA0B,EAAE,MAAM,wBAAwB,CAAC;AACpE,OAAO,EACL,4BAA4B,EAC5B,gCAAgC,EAChC,wBAAwB,EACxB,oBAAoB,GACrB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AACrD,OAAO,EAAE,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AACjE,OAAO,EAAE,oBAAoB,EAA0B,MAAM,SAAS,CAAC;AAOvE,SAAS,YAAY,CAAC,MAAmC;IACvD,OAAO,MAAM,CAAC,QAAQ,KAAK,OAAO,IAAI,MAAM,CAAC,eAAe,IAAI,MAAM,CAAC,MAAM,CAAC;AAChF,CAAC;AAeD,KAAK,UAAU,gBAAgB,CAC7B,IAAwB,EACxB,KAA0B;IAE1B,IAAI,CAAC,KAAK,CAAC,MAAM,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,gBAAgB,EAAE,CAAC,EAAE,CAAC;QAC5D,OAAO;IACT,CAAC;IACD,MAAM,mBAAmB,GAAG,KAAK,CAAC,mBAAmB,CAAC;IAEtD,MAAM,WAAW,GAAG,KAAK,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;IAC1C,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,MAAM,KAAK,CAAC,oBAAoB,CAAC,GAAG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EAAE,CAAC;QACpD,CAAC;QACD,0BAA0B,EAAE,GAAG,EAAE,CAC/B,uBAAuB,CAAC;YACtB,IAAI;YACJ,KAAK;YACL,WAAW,EAAE,IAAI,CAAC,eAAe;YACjC,gBAAgB,EAAE,IAAI,CAAC,oCAAoC;YAC3D,KAAK,EAAE,MAAM;SACd,CAAC;QACJ,YAAY,EAAE,GAAG,EAAE,CACjB,uBAAuB,CAAC;YACtB,IAAI;YACJ,KAAK;YACL,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,gBAAgB,EAAE,GAAG,EAAE,CAAC,2BAA2B,CAAC,IAAI,EAAE,KAAK,CAAC;YAChE,KAAK,EAAE,MAAM;SACd,CAAC;QACJ,IAAI,EAAE,GAAG,EAAE,CAAC,yBAAyB,CAAC,IAAI,EAAE,KAAK,CAAC;KACnD,CAAC;AACJ,CAAC","sourcesContent":["import {\n getOrCreateDomainSyncCoordinator,\n type SyncLane,\n} from \"../../data/sync/syncCoordinator\";\nimport {\n acknowledgeContainerForce,\n activateContainer,\n enqueueKnownContainersForIdleBackfill,\n type IdleBackfillState,\n markContainerForced,\n} from \"./idleBackfill\";\nimport { createInitialDocumentProbe } from \"./initialDocumentProbe\";\nimport {\n clearPendingDiscoveryRetries,\n isCurrentReconciliationLifecycle,\n reconcileMarkedContainer,\n sweepKnownContainers,\n} from \"./knownContainerSweep\";\nimport { rearmFailedContainer } from \"./laneFailure\";\nimport { clearOriginatedDocuments } from \"./originatedDocuments\";\nimport { createReconcileQueue, type ReconcilePriority } from \"./queue\";\nimport type {\n ReconciliationHost,\n ReconciliationRuntimeStatus,\n ReconciliationService,\n} from \"./serviceTypes\";\n\nfunction canReconcile(status: ReconciliationRuntimeStatus): boolean {\n return status.dbStatus === \"ready\" && status.isAuthenticated && status.online;\n}\n\ntype RefreshScope = \"root\" | \"full\";\n\ninterface ReconciliationState extends IdleBackfillState {\n active: boolean;\n lane: SyncLane | null;\n lifecycleGeneration: number;\n probeContinuationCancel: (() => void) | null;\n pendingRefresh: {\n readonly promise: Promise<void>;\n readonly scope: RefreshScope;\n } | null;\n}\n\nasync function runReconcileLane(\n host: ReconciliationHost,\n state: ReconciliationState,\n): Promise<void> {\n if (!state.active || !canReconcile(host.getRuntimeStatus())) {\n return;\n }\n const lifecycleGeneration = state.lifecycleGeneration;\n\n const containerId = state.queue.dequeue();\n if (!containerId) {\n await state.initialDocumentProbe.run();\n scheduleProbeContinuation(host, state);\n return;\n }\n // Double-check at run time: a container may have been discovered (by an\n // explicit refresh or an earlier lane pass) after it was queued. Mark it\n // discovered up front to collapse concurrent re-enqueues into one fetch, but\n // roll the mark back on failure so a transient error can be retried later.\n const forceGeneration = state.forcedContainerGenerations.get(containerId);\n const shouldForce = forceGeneration !== undefined;\n if (shouldForce || !state.discoveredContainerIds.has(containerId)) {\n state.discoveredContainerIds.add(containerId);\n try {\n const reconciled = await reconcileMarkedContainer(\n host,\n state,\n containerId,\n shouldForce,\n );\n if (reconciled) {\n acknowledgeContainerForce(state, containerId, forceGeneration);\n }\n } catch (error) {\n rearmFailedContainer(\n state,\n containerId,\n forceGeneration,\n lifecycleGeneration,\n );\n throw error;\n }\n }\n\n // Keep draining: schedule another pass while the queue holds work.\n if (state.queue.size > 0) {\n state.lane?.requestSync();\n } else {\n scheduleProbeContinuation(host, state);\n }\n}\n\nfunction scheduleProbeContinuation(\n host: ReconciliationHost,\n state: ReconciliationState,\n): void {\n state.probeContinuationCancel?.();\n const canContinue = () =>\n state.active &&\n state.queue.size === 0 &&\n canReconcile(host.getRuntimeStatus()) &&\n state.initialDocumentProbe.hasPendingWork();\n if (!canContinue()) {\n state.probeContinuationCancel = null;\n return;\n }\n const timeout = setTimeout(() => {\n if (canContinue()) {\n state.probeContinuationCancel = null;\n state.lane?.requestSync();\n }\n }, state.initialDocumentProbe.continuationDelayMs());\n state.probeContinuationCancel = () => clearTimeout(timeout);\n}\n\nfunction forgetIneligibleDiscoveredContainers(\n host: ReconciliationHost,\n state: ReconciliationState,\n): void {\n for (const containerId of state.discoveredContainerIds) {\n if (!host.canDiscoverContainerDocuments(containerId)) {\n state.discoveredContainerIds.delete(containerId);\n }\n }\n}\n\nasync function refreshAndReconcileContainers(input: {\n forceAllDocumentContentPulls: boolean;\n host: ReconciliationHost;\n listContainerIds: () => ReadonlyArray<string>;\n refreshTree: () => Promise<void>;\n state: ReconciliationState;\n}): Promise<void> {\n const { host, listContainerIds, refreshTree, state } = input;\n if (!canReconcile(host.getRuntimeStatus())) {\n return;\n }\n const lifecycleGeneration = state.lifecycleGeneration;\n\n if (input.forceAllDocumentContentPulls) {\n state.queue.clear();\n }\n try {\n // A resync_required structural refresh runs independently of this service.\n // If it already removed a container after the forced document lane won its\n // race against the old tree, forget the stale discovered bit before this\n // refresh can re-add the same id.\n forgetIneligibleDiscoveredContainers(host, state);\n await refreshTree();\n if (!isCurrentReconciliationLifecycle(state, lifecycleGeneration)) {\n return;\n }\n // Structural hydration can revoke and remove a container after a targeted\n // force already reconciled it against the old tree. Forget every id that\n // is no longer remotely listable so a later share of the same container id\n // is treated as newly surfaced instead of being suppressed for the rest of\n // the session.\n forgetIneligibleDiscoveredContainers(host, state);\n await sweepKnownContainers({\n forceAllDocumentContentPulls: input.forceAllDocumentContentPulls,\n host,\n knownIds: listContainerIds(),\n lifecycleGeneration,\n state,\n });\n if (!isCurrentReconciliationLifecycle(state, lifecycleGeneration)) {\n return;\n }\n } catch (error) {\n if (!isCurrentReconciliationLifecycle(state, lifecycleGeneration)) {\n return;\n }\n if (!host.isIgnorableError(error)) {\n throw error;\n }\n }\n}\n\n// Sweeps share the queue and discovered set, so they must run serially.\n// Root requests join either kind of sweep; a full request after a root sweep\n// must wait for it and then refresh the whole tree.\nfunction requestContainerRefresh(input: {\n host: ReconciliationHost;\n state: ReconciliationState;\n refreshTree: () => Promise<void>;\n listContainerIds: () => ReadonlyArray<string>;\n scope: RefreshScope;\n}): Promise<void> {\n const { state, scope } = input;\n const pending = state.pendingRefresh;\n if (pending && (scope === \"root\" || pending.scope === \"full\")) {\n return pending.promise;\n }\n\n const promise = (pending?.promise ?? Promise.resolve())\n // A failed root sweep must not prevent the queued full refresh.\n .catch(() => undefined)\n .then(() =>\n refreshAndReconcileContainers({\n forceAllDocumentContentPulls: scope === \"full\",\n host: input.host,\n listContainerIds: input.listContainerIds,\n refreshTree: input.refreshTree,\n state,\n }),\n )\n .finally(() => {\n if (state.pendingRefresh?.promise === promise) {\n state.pendingRefresh = null;\n }\n });\n state.pendingRefresh = { promise, scope };\n return promise;\n}\n\nfunction listFullRefreshContainerIds(\n host: ReconciliationHost,\n state: ReconciliationState,\n): ReadonlyArray<string> {\n const knownIds = host.listKnownContainerIds();\n const activeContainerId = state.activeContainerId;\n if (\n !activeContainerId ||\n knownIds.includes(activeContainerId) ||\n !host.canDiscoverContainerDocuments(activeContainerId)\n ) {\n return knownIds;\n }\n // Explicit refresh also retries an open foreign system container that the\n // background discovery list excludes.\n return [...knownIds, activeContainerId];\n}\n\nfunction startReconciliationLane(\n host: ReconciliationHost,\n state: ReconciliationState,\n): void {\n if (state.active) {\n return;\n }\n state.lifecycleGeneration += 1;\n state.active = true;\n state.lane = getOrCreateDomainSyncCoordinator(host.domainScope).registerLane(\n \"reconciliation:documents\",\n {\n label: \"Device-first document reconciliation\",\n // Document discovery runs in the document phase, after structural\n // container hydration/metadata sync settles for the scope.\n phase: \"document\",\n priority: () => (state.activeContainerId ? -1 : 0),\n onUnexpectedError: (error) => {\n console.error(\"Device-first reconciliation failed:\", error);\n },\n // Fixed literal: no container or document id may reach a report. The\n // mapped stack identifies which lane body threw. Returning the host's\n // result hands a rejection to the lane reporter's wrapper; discarding it\n // would surface as an unhandled rejection instead.\n reportUnexpectedError: (error) =>\n host.logError?.(\"Reconciliation: sync lane failed\", error),\n run: () => runReconcileLane(host, state),\n shouldIgnoreError: host.isIgnorableError,\n },\n );\n}\n\nfunction createReconciliationState(\n host: ReconciliationHost,\n): ReconciliationState {\n return {\n active: false,\n activeContainerId: null,\n automaticRetryGenerations: new Map(),\n discoveredContainerIds: new Set(),\n forcedContainerGenerations: new Map(),\n forcedDocumentIds: new Map(),\n initialDocumentProbe: createInitialDocumentProbe(host),\n lane: null,\n lifecycleGeneration: 0,\n nextForceGeneration: 0,\n probeContinuationCancel: null,\n queue: createReconcileQueue(),\n pendingRefresh: null,\n };\n}\n\nfunction stopReconciliationService(\n host: ReconciliationHost,\n state: ReconciliationState,\n): void {\n clearPendingDiscoveryRetries(state);\n state.active = false;\n state.probeContinuationCancel?.();\n state.probeContinuationCancel = null;\n state.queue.clear();\n state.automaticRetryGenerations.clear();\n state.forcedContainerGenerations.clear();\n state.forcedDocumentIds.clear();\n state.pendingRefresh = null;\n state.initialDocumentProbe.resetPending();\n // Drop the per-session discovered suppression cache too: a stopped\n // reconciler is being torn down (scope/identity change) or paused across\n // a prerequisite loss, after which every container must be re-validated.\n state.discoveredContainerIds.clear();\n // Drop pending self-echo originations too — they are session-scoped and a\n // teardown invalidates them.\n clearOriginatedDocuments(host.domainScope);\n}\n\nexport function createReconciliationService(\n host: ReconciliationHost,\n): ReconciliationService {\n const state = createReconciliationState(host);\n\n const scheduleDrain = () => {\n if (\n !state.active ||\n (state.queue.size === 0 && !state.initialDocumentProbe.canRun())\n ) {\n return;\n }\n if (!canReconcile(host.getRuntimeStatus())) {\n return;\n }\n state.probeContinuationCancel?.();\n state.probeContinuationCancel = null;\n state.lane?.requestSync();\n };\n\n const enqueueContainer = (\n containerId: string,\n priority: ReconcilePriority,\n force = false,\n documentId?: string,\n ) => {\n if (!containerId) {\n return;\n }\n // Skip containers already reconciled this session unless forced. Events\n // force re-discovery; passive active/backfill scheduling does not, so\n // opening Explorer does not re-fetch every container on each navigation.\n if (\n !force &&\n !state.forcedContainerGenerations.has(containerId) &&\n state.discoveredContainerIds.has(containerId)\n ) {\n return;\n }\n if (force) {\n markContainerForced(state, containerId, documentId);\n }\n state.queue.enqueue(containerId, priority);\n scheduleDrain();\n };\n\n const enqueueIdleBackfill = () => {\n enqueueKnownContainersForIdleBackfill({\n host,\n scheduleDrain,\n state,\n });\n };\n\n return {\n start: () => {\n startReconciliationLane(host, state);\n scheduleDrain();\n },\n // Reconcile the active container first; siblings remain lazy until visited.\n setActiveContainer: (containerId) =>\n activateContainer(state, containerId, (activeId) =>\n enqueueContainer(activeId, \"active\"),\n ),\n enqueueContainer,\n enqueueIdleBackfill,\n resetDiscovered: () => {\n state.discoveredContainerIds.clear();\n state.initialDocumentProbe.resetSkippedListings();\n },\n reconcileRootContainersNow: () =>\n requestContainerRefresh({\n host,\n state,\n refreshTree: host.refreshRootTree,\n listContainerIds: host.listAutomaticRootCatchupContainerIds,\n scope: \"root\",\n }),\n reconcileNow: () =>\n requestContainerRefresh({\n host,\n state,\n refreshTree: host.refreshTree,\n listContainerIds: () => listFullRefreshContainerIds(host, state),\n scope: \"full\",\n }),\n stop: () => stopReconciliationService(host, state),\n };\n}\n"]}
1
+ {"version":3,"file":"service.js","sourceRoot":"","sources":["service.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gCAAgC,GAEjC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,yBAAyB,EACzB,iBAAiB,EACjB,qCAAqC,EAErC,mBAAmB,GACpB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,0BAA0B,EAAE,MAAM,wBAAwB,CAAC;AACpE,OAAO,EACL,4BAA4B,EAC5B,gCAAgC,EAChC,wBAAwB,EACxB,oBAAoB,GACrB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AACrD,OAAO,EAAE,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AACjE,OAAO,EAAE,oBAAoB,EAA0B,MAAM,SAAS,CAAC;AAOvE,SAAS,YAAY,CAAC,MAAmC;IACvD,OAAO,MAAM,CAAC,QAAQ,KAAK,OAAO,IAAI,MAAM,CAAC,eAAe,IAAI,MAAM,CAAC,MAAM,CAAC;AAChF,CAAC;AAgBD,KAAK,UAAU,g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Content":["import {\n getOrCreateDomainSyncCoordinator,\n type SyncLane,\n} from \"../../data/sync/syncCoordinator\";\nimport {\n acknowledgeContainerForce,\n activateContainer,\n enqueueKnownContainersForIdleBackfill,\n type IdleBackfillState,\n markContainerForced,\n} from \"./idleBackfill\";\nimport { createInitialDocumentProbe } from \"./initialDocumentProbe\";\nimport {\n clearPendingDiscoveryRetries,\n isCurrentReconciliationLifecycle,\n reconcileMarkedContainer,\n sweepKnownContainers,\n} from \"./knownContainerSweep\";\nimport { rearmFailedContainer } from \"./laneFailure\";\nimport { clearOriginatedDocuments } from \"./originatedDocuments\";\nimport { createReconcileQueue, type ReconcilePriority } from \"./queue\";\nimport type {\n ReconciliationHost,\n ReconciliationRuntimeStatus,\n ReconciliationService,\n} from \"./serviceTypes\";\n\nfunction canReconcile(status: ReconciliationRuntimeStatus): boolean {\n return status.dbStatus === \"ready\" && status.isAuthenticated && status.online;\n}\n\ntype RefreshScope = \"root\" | \"full\";\n\ninterface ReconciliationState extends IdleBackfillState {\n active: boolean;\n lane: SyncLane | null;\n lifecycleGeneration: number;\n probeContinuationCancel: (() => void) | null;\n pendingRefresh: {\n readonly promise: Promise<void>;\n readonly scope: RefreshScope;\n readonly started: { value: boolean };\n } | null;\n}\n\nasync function runReconcileLane(\n host: ReconciliationHost,\n state: ReconciliationState,\n): Promise<void> {\n if (!state.active || !canReconcile(host.getRuntimeStatus())) {\n return;\n }\n const lifecycleGeneration = state.lifecycleGeneration;\n\n const containerId = state.queue.dequeue();\n if (!containerId) {\n await state.initialDocumentProbe.run();\n scheduleProbeContinuation(host, state);\n return;\n }\n // Double-check at run time: a container may have been discovered (by an\n // explicit refresh or an earlier lane pass) after it was queued. Mark it\n // discovered up front to collapse concurrent re-enqueues into one fetch, but\n // roll the mark back on failure so a transient error can be retried later.\n const forceGeneration = state.forcedContainerGenerations.get(containerId);\n const shouldForce = forceGeneration !== undefined;\n if (shouldForce || !state.discoveredContainerIds.has(containerId)) {\n state.discoveredContainerIds.add(containerId);\n try {\n const reconciled = await reconcileMarkedContainer(\n host,\n state,\n containerId,\n shouldForce,\n );\n if (reconciled) {\n acknowledgeContainerForce(state, containerId, forceGeneration);\n }\n } catch (error) {\n rearmFailedContainer(\n state,\n containerId,\n forceGeneration,\n lifecycleGeneration,\n );\n throw error;\n }\n }\n\n // Keep draining: schedule another pass while the queue holds work.\n if (state.queue.size > 0) {\n state.lane?.requestSync();\n } else {\n scheduleProbeContinuation(host, state);\n }\n}\n\nfunction scheduleProbeContinuation(\n host: ReconciliationHost,\n state: ReconciliationState,\n): void {\n state.probeContinuationCancel?.();\n const canContinue = () =>\n state.active &&\n state.queue.size === 0 &&\n canReconcile(host.getRuntimeStatus()) &&\n state.initialDocumentProbe.hasPendingWork();\n if (!canContinue()) {\n state.probeContinuationCancel = null;\n return;\n }\n const timeout = setTimeout(() => {\n if (canContinue()) {\n state.probeContinuationCancel = null;\n state.lane?.requestSync();\n }\n }, state.initialDocumentProbe.continuationDelayMs());\n state.probeContinuationCancel = () => clearTimeout(timeout);\n}\n\nfunction forgetIneligibleDiscoveredContainers(\n host: ReconciliationHost,\n state: ReconciliationState,\n): void {\n for (const containerId of state.discoveredContainerIds) {\n if (!host.canDiscoverContainerDocuments(containerId)) {\n state.discoveredContainerIds.delete(containerId);\n }\n }\n}\n\nasync function refreshAndReconcileContainers(input: {\n forceAllDocumentContentPulls: boolean;\n host: ReconciliationHost;\n listContainerIds: () => ReadonlyArray<string>;\n refreshTree: () => Promise<void>;\n state: ReconciliationState;\n}): Promise<void> {\n const { host, listContainerIds, refreshTree, state } = input;\n if (!canReconcile(host.getRuntimeStatus())) {\n return;\n }\n const lifecycleGeneration = state.lifecycleGeneration;\n\n if (input.forceAllDocumentContentPulls) {\n state.queue.clear();\n }\n try {\n // A resync_required structural refresh runs independently of this service.\n // If it already removed a container after the forced document lane won its\n // race against the old tree, forget the stale discovered bit before this\n // refresh can re-add the same id.\n forgetIneligibleDiscoveredContainers(host, state);\n await refreshTree();\n if (!isCurrentReconciliationLifecycle(state, lifecycleGeneration)) {\n return;\n }\n // Structural hydration can revoke and remove a container after a targeted\n // force already reconciled it against the old tree. Forget every id that\n // is no longer remotely listable so a later share of the same container id\n // is treated as newly surfaced instead of being suppressed for the rest of\n // the session.\n forgetIneligibleDiscoveredContainers(host, state);\n await sweepKnownContainers({\n forceAllDocumentContentPulls: input.forceAllDocumentContentPulls,\n host,\n knownIds: listContainerIds(),\n lifecycleGeneration,\n state,\n });\n if (!isCurrentReconciliationLifecycle(state, lifecycleGeneration)) {\n return;\n }\n } catch (error) {\n if (!isCurrentReconciliationLifecycle(state, lifecycleGeneration)) {\n return;\n }\n if (!host.isIgnorableError(error)) {\n throw error;\n }\n }\n}\n\n// Sweeps share the queue and discovered set, so they must run serially.\n// Root requests join either kind of sweep; a full request after a root sweep\n// must wait for it and then refresh the whole tree. A fresh-listing request\n// joins only a sweep that has not started: one already running may have listed\n// before the event behind the request, so it queues a trailing sweep instead.\nfunction requestContainerRefresh(input: {\n freshListing: boolean;\n host: ReconciliationHost;\n state: ReconciliationState;\n refreshTree: () => Promise<void>;\n listContainerIds: () => ReadonlyArray<string>;\n scope: RefreshScope;\n}): Promise<void> {\n const { state, scope } = input;\n const pending = state.pendingRefresh;\n if (\n pending &&\n (scope === \"root\" || pending.scope === \"full\") &&\n !(input.freshListing && pending.started.value)\n ) {\n return pending.promise;\n }\n\n const started = { value: false };\n const promise = (pending?.promise ?? Promise.resolve())\n // A failed earlier sweep must not prevent the queued refresh.\n .catch(() => undefined)\n .then(() => {\n started.value = true;\n return refreshAndReconcileContainers({\n forceAllDocumentContentPulls: scope === \"full\",\n host: input.host,\n listContainerIds: input.listContainerIds,\n refreshTree: input.refreshTree,\n state,\n });\n })\n .finally(() => {\n if (state.pendingRefresh?.promise === promise) {\n state.pendingRefresh = null;\n }\n });\n state.pendingRefresh = { promise, scope, started };\n return promise;\n}\n\nfunction listFullRefreshContainerIds(\n host: ReconciliationHost,\n state: ReconciliationState,\n): ReadonlyArray<string> {\n const knownIds = host.listKnownContainerIds();\n const activeContainerId = state.activeContainerId;\n if (\n !activeContainerId ||\n knownIds.includes(activeContainerId) ||\n !host.canDiscoverContainerDocuments(activeContainerId)\n ) {\n return knownIds;\n }\n // Explicit refresh also retries an open foreign system container that the\n // background discovery list excludes.\n return [...knownIds, activeContainerId];\n}\n\nfunction startReconciliationLane(\n host: ReconciliationHost,\n state: ReconciliationState,\n): void {\n if (state.active) {\n return;\n }\n state.lifecycleGeneration += 1;\n state.active = true;\n state.lane = getOrCreateDomainSyncCoordinator(host.domainScope).registerLane(\n \"reconciliation:documents\",\n {\n label: \"Device-first document reconciliation\",\n // Document discovery runs in the document phase, after structural\n // container hydration/metadata sync settles for the scope.\n phase: \"document\",\n priority: () => (state.activeContainerId ? -1 : 0),\n onUnexpectedError: (error) => {\n console.error(\"Device-first reconciliation failed:\", error);\n },\n // Fixed literal: no container or document id may reach a report. The\n // mapped stack identifies which lane body threw. Returning the host's\n // result hands a rejection to the lane reporter's wrapper; discarding it\n // would surface as an unhandled rejection instead.\n reportUnexpectedError: (error) =>\n host.logError?.(\"Reconciliation: sync lane failed\", error),\n run: () => runReconcileLane(host, state),\n shouldIgnoreError: host.isIgnorableError,\n },\n );\n}\n\nfunction createReconciliationState(\n host: ReconciliationHost,\n): ReconciliationState {\n return {\n active: false,\n activeContainerId: null,\n automaticRetryGenerations: new Map(),\n discoveredContainerIds: new Set(),\n forcedContainerGenerations: new Map(),\n forcedDocumentIds: new Map(),\n initialDocumentProbe: createInitialDocumentProbe(host),\n lane: null,\n lifecycleGeneration: 0,\n nextForceGeneration: 0,\n probeContinuationCancel: null,\n queue: createReconcileQueue(),\n pendingRefresh: null,\n };\n}\n\nfunction stopReconciliationService(\n host: ReconciliationHost,\n state: ReconciliationState,\n): void {\n clearPendingDiscoveryRetries(state);\n state.active = false;\n state.probeContinuationCancel?.();\n state.probeContinuationCancel = null;\n state.queue.clear();\n state.automaticRetryGenerations.clear();\n state.forcedContainerGenerations.clear();\n state.forcedDocumentIds.clear();\n state.pendingRefresh = null;\n state.initialDocumentProbe.resetPending();\n // Drop the per-session discovered suppression cache too: a stopped\n // reconciler is being torn down (scope/identity change) or paused across\n // a prerequisite loss, after which every container must be re-validated.\n state.discoveredContainerIds.clear();\n // Drop pending self-echo originations too — they are session-scoped and a\n // teardown invalidates them.\n clearOriginatedDocuments(host.domainScope);\n}\n\nexport function createReconciliationService(\n host: ReconciliationHost,\n): ReconciliationService {\n const state = createReconciliationState(host);\n\n const scheduleDrain = () => {\n if (\n !state.active ||\n (state.queue.size === 0 && !state.initialDocumentProbe.canRun())\n ) {\n return;\n }\n if (!canReconcile(host.getRuntimeStatus())) {\n return;\n }\n state.probeContinuationCancel?.();\n state.probeContinuationCancel = null;\n state.lane?.requestSync();\n };\n\n const enqueueContainer = (\n containerId: string,\n priority: ReconcilePriority,\n force = false,\n documentId?: string,\n ) => {\n if (!containerId) {\n return;\n }\n // Skip containers already reconciled this session unless forced. Events\n // force re-discovery; passive active/backfill scheduling does not, so\n // opening Explorer does not re-fetch every container on each navigation.\n if (\n !force &&\n !state.forcedContainerGenerations.has(containerId) &&\n state.discoveredContainerIds.has(containerId)\n ) {\n return;\n }\n if (force) {\n markContainerForced(state, containerId, documentId);\n }\n state.queue.enqueue(containerId, priority);\n scheduleDrain();\n };\n\n const enqueueIdleBackfill = () => {\n enqueueKnownContainersForIdleBackfill({\n host,\n scheduleDrain,\n state,\n });\n };\n\n return {\n start: () => {\n startReconciliationLane(host, state);\n scheduleDrain();\n },\n // Reconcile the active container first; siblings remain lazy until visited.\n setActiveContainer: (containerId) =>\n activateContainer(state, containerId, (activeId) =>\n enqueueContainer(activeId, \"active\"),\n ),\n enqueueContainer,\n enqueueIdleBackfill,\n resetDiscovered: () => {\n state.discoveredContainerIds.clear();\n state.initialDocumentProbe.resetSkippedListings();\n },\n reconcileRootContainersNow: (options) =>\n requestContainerRefresh({\n freshListing: options?.freshListing === true,\n host,\n state,\n refreshTree: host.refreshRootTree,\n listContainerIds: host.listAutomaticRootCatchupContainerIds,\n scope: \"root\",\n }),\n reconcileNow: () =>\n requestContainerRefresh({\n freshListing: false,\n host,\n state,\n refreshTree: host.refreshTree,\n listContainerIds: () => listFullRefreshContainerIds(host, state),\n scope: \"full\",\n }),\n stop: () => stopReconciliationService(host, state),\n };\n}\n"]}
@@ -62,7 +62,16 @@ export interface ReconciliationService {
62
62
  * retries need a fresh opportunity once the server is reachable again.
63
63
  */
64
64
  resetDiscovered: () => void;
65
- reconcileRootContainersNow: () => Promise<void>;
65
+ /**
66
+ * Re-list root containers and reconcile the root catch-up set. By default a
67
+ * request joins a sweep already in flight. With `freshListing`, the returned
68
+ * sweep starts after this call: a discovery event (a root shared with or
69
+ * created for this user) must not be satisfied by a sweep that may have
70
+ * listed roots before the event committed.
71
+ */
72
+ reconcileRootContainersNow: (options?: {
73
+ readonly freshListing?: boolean;
74
+ }) => Promise<void>;
66
75
  reconcileNow: () => Promise<void>;
67
76
  stop: () => void;
68
77
  }
@@ -1 +1 @@
1
- {"version":3,"file":"serviceTypes.js","sourceRoot":"","sources":["serviceTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { DocumentSummary } from \"../../data/documents/documentSummary\";\nimport type { DomainScope } from \"../../data/domainScope\";\nimport type { LocalProjectionReconciledDelta } from \"../../stores/local-projection\";\nimport type { InitialDocumentProbeHost } from \"./initialDocumentProbe\";\nimport type { ReconcilePriority } from \"./queue\";\n\nexport interface ReconciliationRuntimeStatus {\n dbStatus: string;\n isAuthenticated: boolean;\n online: boolean;\n}\n\n/**\n * Host contract injected by the device-first facade. Keeps the reconciler\n * React-free and decoupled from runtime/persistence construction — it only\n * orchestrates *when* these run and routes their results into Layer A.\n */\nexport interface ReconciliationHost extends InitialDocumentProbeHost {\n domainScope: DomainScope;\n getRuntimeStatus: () => ReconciliationRuntimeStatus;\n /** True when this container has enough remote state to list documents. */\n canDiscoverContainerDocuments: (containerId: string) => boolean;\n /** Known container ids eligible for idle document reconciliation. */\n listKnownContainerIds: () => ReadonlyArray<string>;\n /** Known ids eligible after an automatic root-lane discovery hint. */\n listAutomaticRootCatchupContainerIds: () => ReadonlyArray<string>;\n /** Discover + persist documents; `null` means the lane was not fully listed. */\n discoverContainerDocuments: (\n containerId: string,\n onFullListing?: ((documentIds: ReadonlyArray<string>) => void) | undefined,\n onPendingDiscovery?: ((delayMs: number) => void) | undefined,\n ) => Promise<ReadonlyArray<DocumentSummary> | null>;\n /** Read a container's freshly-persisted summaries+links from SQLite. */\n loadContainerDelta: (\n containerId: string,\n ) => Promise<LocalProjectionReconciledDelta>;\n /** Push a reconciled delta into the local projection store. */\n applyReconciled: (delta: LocalProjectionReconciledDelta) => void;\n /**\n * Sync document bodies for a reconciled container. `force` (an explicit\n * refresh) revalidates registered ordinary documents and retries system\n * documents; otherwise only unopened system documents are synced, so a\n * background pass can materialize projection-owned content without eagerly\n * opening every ordinary document. A documentIds set limits forced pulls to\n * hint-named documents while still discovering new system content.\n */\n requestDocumentContentPull: (\n containerId: string,\n documents: ReadonlyArray<DocumentSummary>,\n force: boolean,\n documentIds?: ReadonlySet<string>,\n ) => void;\n /** Refresh the container tree from the server (explicit refresh). */\n refreshTree: () => Promise<void>;\n /** Refresh only the top-level root lane from the server. */\n refreshRootTree: () => Promise<void>;\n /** True if the destroyed-db error should be swallowed rather than surfaced. */\n isIgnorableError: (error: unknown) => boolean;\n /** Host diagnostics sink; bare runtimes do not structure errors. */\n logError?: ((message: string, error: unknown) => void) | undefined;\n}\n\nexport interface ReconciliationService {\n start: () => void;\n setActiveContainer: (containerId: string | null) => void;\n /** Force a listing; documentId limits content revalidation to that hint. */\n enqueueContainer: (\n containerId: string,\n priority: ReconcilePriority,\n force?: boolean,\n documentId?: string,\n ) => void;\n /** Queue known containers at idle priority. */\n enqueueIdleBackfill: () => void;\n /**\n * Forget which containers were reconciled this session so the next enqueue of\n * each re-validates against the server exactly once. Call on the\n * cannot-reconcile → can-reconcile edge (relogin/reconnect): the discovered\n * set is a per-session suppression cache, a previously-visited container may\n * have changed remotely, and initial-probe listings that exhausted their\n * retries need a fresh opportunity once the server is reachable again.\n */\n resetDiscovered: () => void;\n reconcileRootContainersNow: () => Promise<void>;\n reconcileNow: () => Promise<void>;\n stop: () => void;\n}\n"]}
1
+ {"version":3,"file":"serviceTypes.js","sourceRoot":"","sources":["serviceTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { DocumentSummary } from \"../../data/documents/documentSummary\";\nimport type { DomainScope } from \"../../data/domainScope\";\nimport type { LocalProjectionReconciledDelta } from \"../../stores/local-projection\";\nimport type { InitialDocumentProbeHost } from \"./initialDocumentProbe\";\nimport type { ReconcilePriority } from \"./queue\";\n\nexport interface ReconciliationRuntimeStatus {\n dbStatus: string;\n isAuthenticated: boolean;\n online: boolean;\n}\n\n/**\n * Host contract injected by the device-first facade. Keeps the reconciler\n * React-free and decoupled from runtime/persistence construction — it only\n * orchestrates *when* these run and routes their results into Layer A.\n */\nexport interface ReconciliationHost extends InitialDocumentProbeHost {\n domainScope: DomainScope;\n getRuntimeStatus: () => ReconciliationRuntimeStatus;\n /** True when this container has enough remote state to list documents. */\n canDiscoverContainerDocuments: (containerId: string) => boolean;\n /** Known container ids eligible for idle document reconciliation. */\n listKnownContainerIds: () => ReadonlyArray<string>;\n /** Known ids eligible after an automatic root-lane discovery hint. */\n listAutomaticRootCatchupContainerIds: () => ReadonlyArray<string>;\n /** Discover + persist documents; `null` means the lane was not fully listed. */\n discoverContainerDocuments: (\n containerId: string,\n onFullListing?: ((documentIds: ReadonlyArray<string>) => void) | undefined,\n onPendingDiscovery?: ((delayMs: number) => void) | undefined,\n ) => Promise<ReadonlyArray<DocumentSummary> | null>;\n /** Read a container's freshly-persisted summaries+links from SQLite. */\n loadContainerDelta: (\n containerId: string,\n ) => Promise<LocalProjectionReconciledDelta>;\n /** Push a reconciled delta into the local projection store. */\n applyReconciled: (delta: LocalProjectionReconciledDelta) => void;\n /**\n * Sync document bodies for a reconciled container. `force` (an explicit\n * refresh) revalidates registered ordinary documents and retries system\n * documents; otherwise only unopened system documents are synced, so a\n * background pass can materialize projection-owned content without eagerly\n * opening every ordinary document. A documentIds set limits forced pulls to\n * hint-named documents while still discovering new system content.\n */\n requestDocumentContentPull: (\n containerId: string,\n documents: ReadonlyArray<DocumentSummary>,\n force: boolean,\n documentIds?: ReadonlySet<string>,\n ) => void;\n /** Refresh the container tree from the server (explicit refresh). */\n refreshTree: () => Promise<void>;\n /** Refresh only the top-level root lane from the server. */\n refreshRootTree: () => Promise<void>;\n /** True if the destroyed-db error should be swallowed rather than surfaced. */\n isIgnorableError: (error: unknown) => boolean;\n /** Host diagnostics sink; bare runtimes do not structure errors. */\n logError?: ((message: string, error: unknown) => void) | undefined;\n}\n\nexport interface ReconciliationService {\n start: () => void;\n setActiveContainer: (containerId: string | null) => void;\n /** Force a listing; documentId limits content revalidation to that hint. */\n enqueueContainer: (\n containerId: string,\n priority: ReconcilePriority,\n force?: boolean,\n documentId?: string,\n ) => void;\n /** Queue known containers at idle priority. */\n enqueueIdleBackfill: () => void;\n /**\n * Forget which containers were reconciled this session so the next enqueue of\n * each re-validates against the server exactly once. Call on the\n * cannot-reconcile → can-reconcile edge (relogin/reconnect): the discovered\n * set is a per-session suppression cache, a previously-visited container may\n * have changed remotely, and initial-probe listings that exhausted their\n * retries need a fresh opportunity once the server is reachable again.\n */\n resetDiscovered: () => void;\n /**\n * Re-list root containers and reconcile the root catch-up set. By default a\n * request joins a sweep already in flight. With `freshListing`, the returned\n * sweep starts after this call: a discovery event (a root shared with or\n * created for this user) must not be satisfied by a sweep that may have\n * listed roots before the event committed.\n */\n reconcileRootContainersNow: (options?: {\n readonly freshListing?: boolean;\n }) => Promise<void>;\n reconcileNow: () => Promise<void>;\n stop: () => void;\n}\n"]}
@@ -30,6 +30,7 @@ export async function loadCurrentGroupPolicyMutationContext(input) {
30
30
  { head: adminHead, projection: authority.admins.policy.projection },
31
31
  ],
32
32
  };
33
+ // A reused citation keeps the lifetime of the read that produced it.
33
34
  const references = new Map();
34
35
  return {
35
36
  adminGroupId: authority.descriptor.adminGroupId,
@@ -60,18 +61,17 @@ export async function loadCurrentGroupPolicyMutationContext(input) {
60
61
  if (oldest !== undefined)
61
62
  references.delete(oldest);
62
63
  }
63
- pending = authority
64
- .readGroup(input.groupId, owned)
65
- .then((selected) => selected.policy);
64
+ pending = authority.readGroup(input.groupId, owned);
66
65
  references.set(key, pending);
67
66
  }
68
- const policy = await pending.catch((error) => {
67
+ const selected = await pending.catch((error) => {
69
68
  if (references.get(key) === pending)
70
69
  references.delete(key);
71
70
  throw error;
72
71
  });
73
72
  assertProjectionVerificationCurrent(stillCurrent);
74
- return policy;
73
+ assertProjectionVerificationCurrent(selected.stillCurrent);
74
+ return selected.policy;
75
75
  },
76
76
  stillCurrent,
77
77
  };
@@ -1 +1 @@
1
- {"version":3,"file":"currentGroupPolicyMutationContext.js","sourceRoot":"","sources":["currentGroupPolicyMutationContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,4BAA4B,GAE7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,kCAAkC,EAAE,MAAM,2DAA2D,CAAC;AAC/G,OAAO,EAAE,4BAA4B,EAAE,MAAM,uDAAuD,CAAC;AAGrG,OAAO,EAAE,mDAAmD,EAAE,MAAM,iCAAiC,CAAC;AACtG,OAAO,EAAE,wCAAwC,EAAE,MAAM,wCAAwC,CAAC;AAClG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wBAAwB,CAAC;AACpE,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAE3E,kFAAkF;AAClF,MAAM,CAAC,KAAK,UAAU,qCAAqC,CAAC,KAY3D;IACC,KAAK,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC;IACrB,MAAM,EAAE,SAAS,EAAE,sBAAsB,EAAE,GACzC,MAAM,wCAAwC,CAAC,KAAK,CAAC,CAAC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pD,IAAI,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,OAAO;oBAAE,UAAU,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBAC5D,MAAM,KAAK,CAAC;YACd,CAAC,CAAC,CAAC;YACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,OAAO,MAAM,CAAC;QAChB,CAAC;QACD,YAAY;KACb,CAAC;AACJ,CAAC","sourcesContent":["import {\n type PrincipalPolicyExternalAuthority,\n type ReferencedPrincipalHead,\n serializeKeyingCanonicalJson,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { advanceKeyingCheckpointsAtomically } from \"../../data/persistence/keyingCheckpointAdvancePersistence\";\nimport { requireOrganizationGroupHead } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { createRuntimePrincipalPolicyCurrentResolver } from \"../principals/runtimePolicyRecovery\";\nimport { createSelectedCurrentGroupMetadataContainerVerifier } from \"./currentGroupMetadataAuthority\";\nimport { loadCurrentOrganizationMutationAuthority } from \"./currentOrganizationMutationAuthority\";\nimport { assertGroupMetadataBinding } from \"./groupMetadataBinding\";\nimport { requireSignerCanManageGroup } from \"./groupMutationAuthorization\";\n\n/** Exact current directory, strict Admins and group evidence for one mutation. */\nexport async function loadCurrentGroupPolicyMutationContext(input: {\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly resolveCurrentPolicy: NonNullable<\n ReturnType<typeof createRuntimePrincipalPolicyCurrentResolver>\n >;\n readonly recoverPendingPrincipalMutation: (\n organizationId: string,\n ) => Promise<void>;\n readonly stillCurrent: () => boolean;\n}) {\n input = { ...input };\n const { authority, currentOrgAdminUserIds } =\n await loadCurrentOrganizationMutationAuthority(input);\n const group = await authority.readGroup(input.groupId);\n const stillCurrent = () =>\n input.stillCurrent() && authority.stillCurrent() && group.stillCurrent();\n assertProjectionVerificationCurrent(stillCurrent);\n assertGroupMetadataBinding(group.current, authority.descriptor);\n requireSignerCanManageGroup(\n group.current,\n currentOrgAdminUserIds,\n input.signerUserId,\n );\n await advanceKeyingCheckpointsAtomically({\n access: [],\n execSql: input.execSql,\n organizationId: input.organizationId,\n policies: [...group.dependencies, group.policy],\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n const adminHead = requireOrganizationGroupHead(\n authority.descriptor,\n authority.descriptor.adminGroupId,\n );\n const externalAuthority: PrincipalPolicyExternalAuthority = {\n currentHead: adminHead,\n states: [\n { head: adminHead, projection: authority.admins.policy.projection },\n ],\n };\n const references = new Map<string, Promise<VerifiedPrincipalPolicyCurrent>>();\n return {\n adminGroupId: authority.descriptor.adminGroupId,\n adminCurrent: authority.admins,\n currentPolicy: group.current,\n verifiedCurrentPolicy: group.policy,\n verifyMetadataContainer:\n createSelectedCurrentGroupMetadataContainerVerifier({\n authority,\n organizationId: input.organizationId,\n stillCurrent,\n }),\n currentOrgAdminUserIds,\n externalAuthority,\n isOrganizationAdminsGroup:\n input.groupId === authority.descriptor.adminGroupId,\n localPolicyCheckpoint: group.policy.checkpoint,\n memberGroupId: authority.descriptor.memberGroupId,\n organizationDescriptor: authority.descriptor,\n organizationCurrent: authority.directory,\n async readPredecessorReference(reference: ReferencedPrincipalHead) {\n assertProjectionVerificationCurrent(stillCurrent);\n const owned = structuredClone(reference);\n const key = serializeKeyingCanonicalJson({ ...owned });\n let pending = references.get(key);\n if (!pending) {\n // Keep at most one bounded selection's citations, even across many paths.\n if (references.size === 128) {\n const oldest = references.keys().next().value;\n if (oldest !== undefined) references.delete(oldest);\n }\n pending = authority\n .readGroup(input.groupId, owned)\n .then((selected) => selected.policy);\n references.set(key, pending);\n }\n const policy = await pending.catch((error: unknown) => {\n if (references.get(key) === pending) references.delete(key);\n throw error;\n });\n assertProjectionVerificationCurrent(stillCurrent);\n return policy;\n },\n stillCurrent,\n };\n}\n"]}
1
+ {"version":3,"file":"currentGroupPolicyMutationContext.js","sourceRoot":"","sources":["currentGroupPolicyMutationContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,4BAA4B,GAE7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,kCAAkC,EAAE,MAAM,2DAA2D,CAAC;AAC/G,OAAO,EAAE,4BAA4B,EAAE,MAAM,uDAAuD,CAAC;AAGrG,OAAO,EAAE,mDAAmD,EAAE,MAAM,iCAAiC,CAAC;AACtG,OAAO,EAAE,wCAAwC,EAAE,MAAM,wCAAwC,CAAC;AAClG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wBAAwB,CAAC;AACpE,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAE3E,kFAAkF;AAClF,MAAM,CAAC,KAAK,UAAU,qCAAqC,CAAC,KAY3D;IACC,KAAK,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC;IACrB,MAAM,EAAE,SAAS,EAAE,sBAAsB,EAAE,GACzC,MAAM,wCAAwC,CAAC,KAAK,CAAC,CAAC;IACxD,MAAM,KAAK,GAAG,MAAM,SAAS,CAAC,SAAS,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACvD,MAAM,YAAY,GAAG,GAAG,EAAE,CACxB,KAAK,CAAC,YAAY,EAAE,IAAI,SAAS,CAAC,YAAY,EAAE,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;IAC3E,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,0BAA0B,CAAC,KAAK,CAAC,OAAO,EAAE,SAAS,CAAC,UAAU,CAAC,CAAC;IAChE,2BAA2B,CACzB,KAAK,CAAC,OAAO,EACb,sBAAsB,EACtB,KAAK,CAAC,YAAY,CACnB,CAAC;IACF,MAAM,kCAAkC,CAAC;QACvC,MAAM,EAAE,EAAE;QACV,OAAO,EAAE,KAAK,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CAAC;YACzC,MAAM,GAAG,GAAG,4BAA4B,CAAC,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC;YACvD,IAAI,OAAO,GAAG,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;YAClC,IAAI,CAAC,OAAO,EAAE,CAAC;gBACb,0EAA0E;gBAC1E,IAAI,UAAU,CAAC,IAAI,KAAK,GAAG,EAAE,CAAC;oBAC5B,MAAM,MAAM,GAAG,UAAU,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC;oBAC9C,IAAI,MAAM,KAAK,SAAS;wBAAE,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;gBACtD,CAAC;gBACD,OAAO,GAAG,SAAS,CAAC,SAAS,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;gBACpD,UAAU,CAAC,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;YAC/B,CAAC;YACD,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;gBACtD,IAAI,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,OAAO;oBAAE,UAAU,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBAC5D,MAAM,KAAK,CAAC;YACd,CAAC,CAAC,CAAC;YACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,mCAAmC,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;YAC3D,OAAO,QAAQ,CAAC,MAAM,CAAC;QACzB,CAAC;QACD,YAAY;KACb,CAAC;AACJ,CAAC","sourcesContent":["import {\n type PrincipalPolicyExternalAuthority,\n type ReferencedPrincipalHead,\n serializeKeyingCanonicalJson,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { advanceKeyingCheckpointsAtomically } from \"../../data/persistence/keyingCheckpointAdvancePersistence\";\nimport { requireOrganizationGroupHead } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { createRuntimePrincipalPolicyCurrentResolver } from \"../principals/runtimePolicyRecovery\";\nimport { createSelectedCurrentGroupMetadataContainerVerifier } from \"./currentGroupMetadataAuthority\";\nimport { loadCurrentOrganizationMutationAuthority } from \"./currentOrganizationMutationAuthority\";\nimport { assertGroupMetadataBinding } from \"./groupMetadataBinding\";\nimport { requireSignerCanManageGroup } from \"./groupMutationAuthorization\";\n\n/** Exact current directory, strict Admins and group evidence for one mutation. */\nexport async function loadCurrentGroupPolicyMutationContext(input: {\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly resolveCurrentPolicy: NonNullable<\n ReturnType<typeof createRuntimePrincipalPolicyCurrentResolver>\n >;\n readonly recoverPendingPrincipalMutation: (\n organizationId: string,\n ) => Promise<void>;\n readonly stillCurrent: () => boolean;\n}) {\n input = { ...input };\n const { authority, currentOrgAdminUserIds } =\n await loadCurrentOrganizationMutationAuthority(input);\n const group = await authority.readGroup(input.groupId);\n const stillCurrent = () =>\n input.stillCurrent() && authority.stillCurrent() && group.stillCurrent();\n assertProjectionVerificationCurrent(stillCurrent);\n assertGroupMetadataBinding(group.current, authority.descriptor);\n requireSignerCanManageGroup(\n group.current,\n currentOrgAdminUserIds,\n input.signerUserId,\n );\n await advanceKeyingCheckpointsAtomically({\n access: [],\n execSql: input.execSql,\n organizationId: input.organizationId,\n policies: [...group.dependencies, group.policy],\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n const adminHead = requireOrganizationGroupHead(\n authority.descriptor,\n authority.descriptor.adminGroupId,\n );\n const externalAuthority: PrincipalPolicyExternalAuthority = {\n currentHead: adminHead,\n states: [\n { head: adminHead, projection: authority.admins.policy.projection },\n ],\n };\n // A reused citation keeps the lifetime of the read that produced it.\n const references = new Map<\n string,\n Promise<{\n readonly policy: VerifiedPrincipalPolicyCurrent;\n readonly stillCurrent: () => boolean;\n }>\n >();\n return {\n adminGroupId: authority.descriptor.adminGroupId,\n adminCurrent: authority.admins,\n currentPolicy: group.current,\n verifiedCurrentPolicy: group.policy,\n verifyMetadataContainer:\n createSelectedCurrentGroupMetadataContainerVerifier({\n authority,\n organizationId: input.organizationId,\n stillCurrent,\n }),\n currentOrgAdminUserIds,\n externalAuthority,\n isOrganizationAdminsGroup:\n input.groupId === authority.descriptor.adminGroupId,\n localPolicyCheckpoint: group.policy.checkpoint,\n memberGroupId: authority.descriptor.memberGroupId,\n organizationDescriptor: authority.descriptor,\n organizationCurrent: authority.directory,\n async readPredecessorReference(reference: ReferencedPrincipalHead) {\n assertProjectionVerificationCurrent(stillCurrent);\n const owned = structuredClone(reference);\n const key = serializeKeyingCanonicalJson({ ...owned });\n let pending = references.get(key);\n if (!pending) {\n // Keep at most one bounded selection's citations, even across many paths.\n if (references.size === 128) {\n const oldest = references.keys().next().value;\n if (oldest !== undefined) references.delete(oldest);\n }\n pending = authority.readGroup(input.groupId, owned);\n references.set(key, pending);\n }\n const selected = await pending.catch((error: unknown) => {\n if (references.get(key) === pending) references.delete(key);\n throw error;\n });\n assertProjectionVerificationCurrent(stillCurrent);\n assertProjectionVerificationCurrent(selected.stillCurrent);\n return selected.policy;\n },\n stillCurrent,\n };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { recoverCurrentOrganizationPolicy } from "./recoverCurrentOrganizationPolicy.js";
2
2
  import { createScopedPrincipalPolicyHistoryBatch } from "./recoverScopedPrincipalPolicyHistory.js";
3
- /** Discovery and selected references share one authenticated collection view. */
3
+ /** Discovery and selected references share one authenticated batch view. */
4
4
  export function createPrincipalCurrentRecoveryBatch() {
5
5
  const memo = {
6
6
  directories: new Map(),
@@ -1 +1 @@
1
- {"version":3,"file":"principalCurrentRecoveryBatch.js","sourceRoot":"","sources":["principalCurrentRecoveryBatch.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gCAAgC,EAAE,MAAM,oCAAoC,CAAC;AACtF,OAAO,EAAE,uCAAuC,EAAE,MAAM,uCAAuC,CAAC;AAEhG,iFAAiF;AACjF,MAAM,UAAU,mCAAmC;IACjD,MAAM,IAAI,GAA0B;QAClC,WAAW,EAAE,IAAI,GAAG,EAAE;QACtB,MAAM,EAAE,IAAI,GAAG,EAAE;KAClB,CAAC;IACF,OAAO;QACL,OAAO,EAAE,uCAAuC,CAAC,IAAI,CAAC;QACtD,QAAQ,EAAE,CAAC,KAA+B,EAAE,EAAE,CAC5C,gCAAgC,CAAC,KAAK,EAAE,IAAI,CAAC;KAChD,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalRecoveryContext } from \"./principalRecoveryDirectory\";\nimport type { PrincipalRecoveryMemo } from \"./principalRecoveryMemo\";\nimport { recoverCurrentOrganizationPolicy } from \"./recoverCurrentOrganizationPolicy\";\nimport { createScopedPrincipalPolicyHistoryBatch } from \"./recoverScopedPrincipalPolicyHistory\";\n\n/** Discovery and selected references share one authenticated collection view. */\nexport function createPrincipalCurrentRecoveryBatch() {\n const memo: PrincipalRecoveryMemo = {\n directories: new Map(),\n admins: new Map(),\n };\n return {\n recover: createScopedPrincipalPolicyHistoryBatch(memo),\n discover: (input: PrincipalRecoveryContext) =>\n recoverCurrentOrganizationPolicy(input, memo),\n };\n}\n"]}
1
+ {"version":3,"file":"principalCurrentRecoveryBatch.js","sourceRoot":"","sources":["principalCurrentRecoveryBatch.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,gCAAgC,EAAE,MAAM,oCAAoC,CAAC;AACtF,OAAO,EAAE,uCAAuC,EAAE,MAAM,uCAAuC,CAAC;AAEhG,4EAA4E;AAC5E,MAAM,UAAU,mCAAmC;IACjD,MAAM,IAAI,GAA0B;QAClC,WAAW,EAAE,IAAI,GAAG,EAAE;QACtB,MAAM,EAAE,IAAI,GAAG,EAAE;KAClB,CAAC;IACF,OAAO;QACL,OAAO,EAAE,uCAAuC,CAAC,IAAI,CAAC;QACtD,QAAQ,EAAE,CAAC,KAA+B,EAAE,EAAE,CAC5C,gCAAgC,CAAC,KAAK,EAAE,IAAI,CAAC;KAChD,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalRecoveryContext } from \"./principalRecoveryDirectory\";\nimport type { PrincipalRecoveryMemo } from \"./principalRecoveryMemo\";\nimport { recoverCurrentOrganizationPolicy } from \"./recoverCurrentOrganizationPolicy\";\nimport { createScopedPrincipalPolicyHistoryBatch } from \"./recoverScopedPrincipalPolicyHistory\";\n\n/** Discovery and selected references share one authenticated batch view. */\nexport function createPrincipalCurrentRecoveryBatch() {\n const memo: PrincipalRecoveryMemo = {\n directories: new Map(),\n admins: new Map(),\n };\n return {\n recover: createScopedPrincipalPolicyHistoryBatch(memo),\n discover: (input: PrincipalRecoveryContext) =>\n recoverCurrentOrganizationPolicy(input, memo),\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"principalRecoveryLocalPreference.js","sourceRoot":"","sources":["principalRecoveryLocalPreference.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AACtG,OAAO,EAAE,iCAAiC,EAAE,MAAM,iCAAiC,CAAC;AACpF,OAAO,EAAE,kCAAkC,EAAE,MAAM,2BAA2B,CAAC;AAG/E,wFAAwF;AACxF,MAAM,CAAC,KAAK,UAAU,mCAAmC,CACvD,OAAmD,EACnD,OAAkE,EAClE,kBAA2B,EAC3B,wBAAwB,GAAG,KAAK;IAEhC,IAAI,kBAAkB,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;QAC3C,IAAI,CAAC;YACH,MAAM,KAAK,GAAG,MAAM,OAAO,CAAC;gBAC1B,GAAG,OAAO;gBACV,OAAO,EAAE,IAAI;aACd,CAAC,CAAC;YACH,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;YAC1D,IACE,wBAAwB;gBACxB,OAAO,CAAC,WAAW;gBACnB,6BAA6B,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,SAAS,CAAC;gBAEpE,OAAO,KAAK,CAAC;QACjB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;YAC1D,IACE,CAAC,CAAC,KAAK,YAAY,iCAAiC,CAAC;gBACrD,CAAC,CACC,KAAK,YAAY,uBAAuB;oBACxC,KAAK,CAAC,IAAI,KAAK,oBAAoB,CACpC;gBAED,MAAM,KAAK,CAAC;QAChB,CAAC;IACH,CAAC;IACD,OAAO,kCAAkC,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;AAC9D,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport { PrincipalHistoryRecoveryRaceError } from \"./principalHistoryRecoveryTypes\";\nimport { recoverWithPrincipalOutageFallback } from \"./principalRecoveryOutage\";\nimport type { recoverScopedPrincipalPolicyHistory } from \"./recoverScopedPrincipalPolicyHistory\";\n\n/** Reuse exact current artifacts, or a proved historical page within a newer prefix. */\nexport async function recoverWithPrincipalLocalPreference(\n recover: typeof recoverScopedPrincipalPolicyHistory,\n options: Parameters<typeof recoverScopedPrincipalPolicyHistory>[0],\n preferLocalCurrent: boolean,\n allowHistoricalReference = false,\n) {\n if (preferLocalCurrent && !options.offline) {\n try {\n const local = await recover({\n ...options,\n offline: true,\n });\n assertProjectionVerificationCurrent(options.stillCurrent);\n if (\n allowHistoricalReference ||\n options.historyPage ||\n principalHeadMatchesReference(local.policy.state, options.reference)\n )\n return local;\n } catch (error) {\n assertProjectionVerificationCurrent(options.stillCurrent);\n if (\n !(error instanceof PrincipalHistoryRecoveryRaceError) &&\n !(\n error instanceof KeyingVerificationError &&\n error.code === \"missing_dependency\"\n )\n )\n throw error;\n }\n }\n return recoverWithPrincipalOutageFallback(recover, options);\n}\n"]}
1
+ {"version":3,"file":"principalRecoveryLocalPreference.js","sourceRoot":"","sources":["principalRecoveryLocalPreference.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AACtG,OAAO,EAAE,iCAAiC,EAAE,MAAM,iCAAiC,CAAC;AACpF,OAAO,EAAE,kCAAkC,EAAE,MAAM,2BAA2B,CAAC;AAM/E,wFAAwF;AACxF,MAAM,CAAC,KAAK,UAAU,mCAAmC,CACvD,OAA2C,EAC3C,OAAmD,EACnD,kBAA2B,EAC3B,wBAAwB,GAAG,KAAK;IAEhC,IAAI,kBAAkB,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;QAC3C,IAAI,CAAC;YACH,MAAM,KAAK,GAAG,MAAM,OAAO,CAAC;gBAC1B,GAAG,OAAO;gBACV,OAAO,EAAE,IAAI;aACd,CAAC,CAAC;YACH,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;YAC1D,IACE,wBAAwB;gBACxB,OAAO,CAAC,WAAW;gBACnB,6BAA6B,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,SAAS,CAAC;gBAEpE,OAAO,KAAK,CAAC;QACjB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;YAC1D,IACE,CAAC,CAAC,KAAK,YAAY,iCAAiC,CAAC;gBACrD,CAAC,CACC,KAAK,YAAY,uBAAuB;oBACxC,KAAK,CAAC,IAAI,KAAK,oBAAoB,CACpC;gBAED,MAAM,KAAK,CAAC;QAChB,CAAC;IACH,CAAC;IACD,OAAO,kCAAkC,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;AAC9D,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport { PrincipalHistoryRecoveryRaceError } from \"./principalHistoryRecoveryTypes\";\nimport { recoverWithPrincipalOutageFallback } from \"./principalRecoveryOutage\";\nimport type {\n RecoverScopedPrincipalPolicyHistoryOptions,\n ScopedPrincipalPolicyRecoveryBatch,\n} from \"./recoverScopedPrincipalPolicyHistory\";\n\n/** Reuse exact current artifacts, or a proved historical page within a newer prefix. */\nexport async function recoverWithPrincipalLocalPreference(\n recover: ScopedPrincipalPolicyRecoveryBatch,\n options: RecoverScopedPrincipalPolicyHistoryOptions,\n preferLocalCurrent: boolean,\n allowHistoricalReference = false,\n) {\n if (preferLocalCurrent && !options.offline) {\n try {\n const local = await recover({\n ...options,\n offline: true,\n });\n assertProjectionVerificationCurrent(options.stillCurrent);\n if (\n allowHistoricalReference ||\n options.historyPage ||\n principalHeadMatchesReference(local.policy.state, options.reference)\n )\n return local;\n } catch (error) {\n assertProjectionVerificationCurrent(options.stillCurrent);\n if (\n !(error instanceof PrincipalHistoryRecoveryRaceError) &&\n !(\n error instanceof KeyingVerificationError &&\n error.code === \"missing_dependency\"\n )\n )\n throw error;\n }\n }\n return recoverWithPrincipalOutageFallback(recover, options);\n}\n"]}
@@ -1,15 +1,20 @@
1
1
  import { type ReferencedPrincipalHead } from "../../internal/crypto/index.js";
2
2
  import type { RecoveredPrincipalPolicyHistory } from "./principalHistoryRecoveryTypes.js";
3
3
  import { type PrincipalRecoveryContext, type RecoveredPolicyDirectory } from "./principalRecoveryDirectory.js";
4
- type Memo<T> = Map<string, Promise<{
5
- value: T;
6
- stillCurrent: () => boolean;
7
- }>>;
4
+ interface MemoEntry<T> {
5
+ readonly value: T;
6
+ /** The producing call's private lease and caller lifetime. */
7
+ readonly stillCurrent: () => boolean;
8
+ /** Organization hint epoch observed before the reads that produced value. */
9
+ readonly epoch: number;
10
+ }
11
+ type Memo<T> = Map<string, Promise<MemoEntry<T>>>;
8
12
  export interface PrincipalRecoveryMemo {
9
13
  readonly directories: Memo<RecoveredPolicyDirectory>;
10
14
  readonly admins: Memo<RecoveredPrincipalPolicyHistory>;
11
15
  }
12
16
  export declare function createPrincipalRecoveryReader(input: PrincipalRecoveryContext, memo?: PrincipalRecoveryMemo): {
17
+ stillCurrent: () => boolean;
13
18
  directory: (references: readonly ReferencedPrincipalHead[]) => Promise<RecoveredPolicyDirectory>;
14
19
  admins: (expectedHead: ReferencedPrincipalHead, retainedReferences?: readonly ReferencedPrincipalHead[]) => Promise<RecoveredPrincipalPolicyHistory>;
15
20
  };
@@ -2,23 +2,81 @@ import { KeyingVerificationError, serializeKeyingCanonicalJson, } from "../../in
2
2
  import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
3
3
  import { principalHeadMatchesReference } from "../../data/principals/organizationAuthorityDescriptor.js";
4
4
  import { recoverPolicyDirectory, } from "./principalRecoveryDirectory.js";
5
+ import { adminsMemoValidity, directoryMemoValidity, } from "./principalRecoveryMemoValidity.js";
5
6
  import { recoverPrincipalPolicyHistory } from "./recoverPrincipalPolicyHistory.js";
6
- /** Only share authenticated results within one projection collection lifetime. */
7
- async function memoPrincipalRecovery(memo, key, stillCurrent, work) {
7
+ /** Synchronous: no hint and no lease end since the entry's reads began. */
8
+ function entryLive(entry, validity) {
9
+ return entry.epoch === validity.epoch() && entry.stillCurrent();
10
+ }
11
+ function evict(memo, key, pending) {
12
+ if (memo?.get(key) === pending)
13
+ memo.delete(key);
14
+ }
15
+ /**
16
+ * Return a live entry, evicting one whose producer lease ended, that predates
17
+ * an organization hint, or that a durable pin has moved past. Liveness is
18
+ * checked again after every await, so a hint or lease end during the pin
19
+ * reads also evicts. The caller rechecks synchronously before use. A pin read
20
+ * is a snapshot; a pin that advances later is caught by the checkpoint reload
21
+ * in recovery, the caller's checkpoint refresh, and atomic admission.
22
+ */
23
+ async function reusableEntry(memo, key, validity) {
24
+ const pending = memo?.get(key);
25
+ if (!pending)
26
+ return undefined;
27
+ const entry = await pending.catch(() => undefined);
28
+ if (entry &&
29
+ entryLive(entry, validity) &&
30
+ (await validity.covers(entry.value)) &&
31
+ entryLive(entry, validity))
32
+ return { entry, pending };
33
+ evict(memo, key, pending);
34
+ return undefined;
35
+ }
36
+ /**
37
+ * Share authenticated results within one workflow operation. A later caller
38
+ * never receives a result whose producer lease ended, that predates an
39
+ * organization hint, or that a durable pin has moved past; it recovers again.
40
+ * A result derived from a reused source keeps the source's epoch, so a hint
41
+ * that arrives before it is stored still evicts it. Every value is handed out
42
+ * with the consumer's lifetime and its producer's, so a producer that expires
43
+ * after hand-out still invalidates the consumer's use.
44
+ */
45
+ async function memoPrincipalRecovery(memo, key, stillCurrent, validity, sourceEpoch, work) {
8
46
  assertProjectionVerificationCurrent(stillCurrent);
9
- let pending = memo?.get(key);
10
- if (!pending) {
11
- pending = work().then((value) => ({ value, stillCurrent }));
12
- memo?.set(key, pending);
47
+ const reused = await reusableEntry(memo, key, validity);
48
+ if (reused) {
49
+ const { entry } = reused;
50
+ if (entryLive(entry, validity)) {
51
+ assertProjectionVerificationCurrent(stillCurrent);
52
+ return {
53
+ value: entry.value,
54
+ stillCurrent: () => stillCurrent() && entry.stillCurrent(),
55
+ };
56
+ }
57
+ evict(memo, key, reused.pending);
13
58
  }
59
+ // Observed before work starts its reads; a derived result keeps its source's.
60
+ const epoch = sourceEpoch ?? validity.epoch();
61
+ const pending = work().then((value) => ({ value, stillCurrent, epoch }));
62
+ memo?.set(key, pending);
14
63
  const result = await pending.catch((error) => {
15
- if (memo?.get(key) === pending)
16
- memo.delete(key);
64
+ evict(memo, key, pending);
17
65
  throw error;
18
66
  });
67
+ // A hint during production leaves this caller's in-flight view, never a
68
+ // stored one: the stale epoch would evict it anyway.
69
+ if (result.epoch !== validity.epoch())
70
+ evict(memo, key, pending);
19
71
  assertProjectionVerificationCurrent(result.stillCurrent);
20
72
  assertProjectionVerificationCurrent(stillCurrent);
21
- return result.value;
73
+ // stillCurrent already includes the lifetime of a derived value's source.
74
+ return { value: result.value, stillCurrent };
75
+ }
76
+ function fallsBackOnline(input, error) {
77
+ return (!input.offline &&
78
+ error instanceof KeyingVerificationError &&
79
+ error.code === "missing_dependency");
22
80
  }
23
81
  async function readMemoizedAdmins(input, memo, scope, expectedHead, retainedReferences) {
24
82
  // Every recovered Current already retains its own exact head.
@@ -28,10 +86,11 @@ async function readMemoizedAdmins(input, memo, scope, expectedHead, retainedRefe
28
86
  { ...expectedHead },
29
87
  selected.map((reference) => ({ ...reference })),
30
88
  ]);
31
- const known = memo?.get(key([]));
32
- let sourceCurrent = () => true;
89
+ const validity = adminsMemoValidity(input, expectedHead);
90
+ const known = (await reusableEntry(memo, key([]), validity))?.entry;
91
+ const sourceCurrent = known?.stillCurrent ?? (() => true);
33
92
  const current = () => !input.signal?.aborted && input.stillCurrent() && sourceCurrent();
34
- return memoPrincipalRecovery(memo, key(references), current, async () => {
93
+ return memoPrincipalRecovery(memo, key(references), current, validity, known?.epoch, async () => {
35
94
  const options = {
36
95
  ...input,
37
96
  expectedHead,
@@ -40,8 +99,6 @@ async function readMemoizedAdmins(input, memo, scope, expectedHead, retainedRefe
40
99
  stillCurrent: current,
41
100
  };
42
101
  if (known) {
43
- sourceCurrent = (await known).stillCurrent;
44
- assertProjectionVerificationCurrent(current);
45
102
  try {
46
103
  // A freshly verified exact head only needs local proofs for additional
47
104
  // citations; their signature and private-root checks still run.
@@ -52,9 +109,7 @@ async function readMemoizedAdmins(input, memo, scope, expectedHead, retainedRefe
52
109
  }
53
110
  catch (error) {
54
111
  assertProjectionVerificationCurrent(current);
55
- if (input.offline ||
56
- !(error instanceof KeyingVerificationError) ||
57
- error.code !== "missing_dependency")
112
+ if (!fallsBackOnline(input, error))
58
113
  throw error;
59
114
  }
60
115
  }
@@ -62,28 +117,26 @@ async function readMemoizedAdmins(input, memo, scope, expectedHead, retainedRefe
62
117
  });
63
118
  }
64
119
  async function readMemoizedDirectory(input, memo, key, references) {
65
- const known = references.length > 0 ? memo?.get(key([])) : undefined;
66
- let sourceCurrent = () => true;
120
+ const validity = directoryMemoValidity(input);
121
+ const known = references.length > 0
122
+ ? (await reusableEntry(memo, key([]), validity))?.entry
123
+ : undefined;
124
+ const sourceCurrent = known?.stillCurrent ?? (() => true);
67
125
  const current = () => !input.signal?.aborted && input.stillCurrent() && sourceCurrent();
68
- return memoPrincipalRecovery(memo, key(references), current, async () => {
126
+ return memoPrincipalRecovery(memo, key(references), current, validity, known?.epoch, async () => {
69
127
  if (!known)
70
128
  return recoverPolicyDirectory(input, references);
71
- const source = await known;
72
- sourceCurrent = source.stillCurrent;
73
- assertProjectionVerificationCurrent(current);
74
129
  try {
75
- // Add authenticated historical citations to this batch's exact directory
76
- // view. A newer private prefix must not silently replace that view.
77
- return await recoverPolicyDirectory({ ...input, offline: true, stillCurrent: current }, references, source.value);
130
+ // Add authenticated historical citations to this operation's exact
131
+ // directory view. A newer private prefix must not silently replace it.
132
+ return await recoverPolicyDirectory({ ...input, offline: true, stillCurrent: current }, references, known.value);
78
133
  }
79
134
  catch (error) {
80
135
  assertProjectionVerificationCurrent(current);
81
- if (input.offline ||
82
- !(error instanceof KeyingVerificationError) ||
83
- error.code !== "missing_dependency")
136
+ if (!fallsBackOnline(input, error))
84
137
  throw error;
85
138
  }
86
- return recoverPolicyDirectory({ ...input, stillCurrent: current }, references, source.value);
139
+ return recoverPolicyDirectory({ ...input, stillCurrent: current }, references, known.value);
87
140
  });
88
141
  }
89
142
  export function createPrincipalRecoveryReader(input, memo) {
@@ -96,9 +149,17 @@ export function createPrincipalRecoveryReader(input, memo) {
96
149
  ...scope,
97
150
  references.map((reference) => ({ ...reference })),
98
151
  ]);
152
+ // Every lifetime behind a value this reader handed out; its caller must
153
+ // keep checking them at the point of use.
154
+ const lifetimes = [];
155
+ const lease = (leased) => {
156
+ lifetimes.push(leased.stillCurrent);
157
+ return leased.value;
158
+ };
99
159
  return {
160
+ stillCurrent: () => lifetimes.every((current) => current()),
100
161
  directory: async (references) => {
101
- const value = await readMemoizedDirectory(input, memo?.directories, directoryKey, references);
162
+ const value = lease(await readMemoizedDirectory(input, memo?.directories, directoryKey, references));
102
163
  // Retaining extra citations does not prevent this authenticated directory
103
164
  // from satisfying a later read with no selected historical references.
104
165
  const unselectedKey = directoryKey([]);
@@ -107,12 +168,11 @@ export function createPrincipalRecoveryReader(input, memo) {
107
168
  selected &&
108
169
  references.length > 0 &&
109
170
  !memo.directories.has(unselectedKey))
110
- // Keep the original lease: its expiry requires a new batch, even if
111
- // a later caller still has a live lease of its own.
171
+ // The alias keeps the original lease and validity; either ending evicts it.
112
172
  memo.directories.set(unselectedKey, selected);
113
173
  return value;
114
174
  },
115
- admins: (expectedHead, retainedReferences = []) => readMemoizedAdmins(input, memo?.admins, scope, expectedHead, retainedReferences),
175
+ admins: async (expectedHead, retainedReferences = []) => lease(await readMemoizedAdmins(input, memo?.admins, scope, expectedHead, retainedReferences)),
116
176
  };
117
177
  }
118
178
  //# sourceMappingURL=principalRecoveryMemo.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"principalRecoveryMemo.js","sourceRoot":"","sources":["principalRecoveryMemo.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AAEtG,OAAO,EAGL,sBAAsB,GACvB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAShF,kFAAkF;AAClF,KAAK,UA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yingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport type { RecoveredPrincipalPolicyHistory } from \"./principalHistoryRecoveryTypes\";\nimport {\n type PrincipalRecoveryContext,\n type RecoveredPolicyDirectory,\n recoverPolicyDirectory,\n} from \"./principalRecoveryDirectory\";\nimport { recoverPrincipalPolicyHistory } from \"./recoverPrincipalPolicyHistory\";\n\ntype Memo<T> = Map<string, Promise<{ value: T; stillCurrent: () => boolean }>>;\n\nexport interface PrincipalRecoveryMemo {\n readonly directories: Memo<RecoveredPolicyDirectory>;\n readonly admins: Memo<RecoveredPrincipalPolicyHistory>;\n}\n\n/** Only share authenticated results within one projection collection lifetime. */\nasync function memoPrincipalRecovery<T>(\n memo: Memo<T> | undefined,\n key: string,\n stillCurrent: () => boolean,\n work: () => Promise<T>,\n): Promise<T> {\n assertProjectionVerificationCurrent(stillCurrent);\n let pending = memo?.get(key);\n if (!pending) {\n pending = work().then((value) => ({ value, stillCurrent }));\n memo?.set(key, pending);\n }\n const result = await pending.catch((error: unknown) => {\n if (memo?.get(key) === pending) memo.delete(key);\n throw error;\n });\n assertProjectionVerificationCurrent(result.stillCurrent);\n assertProjectionVerificationCurrent(stillCurrent);\n return result.value;\n}\n\nasync function readMemoizedAdmins(\n input: PrincipalRecoveryContext,\n memo: Memo<RecoveredPrincipalPolicyHistory> | undefined,\n scope: readonly (string | boolean)[],\n expectedHead: ReferencedPrincipalHead,\n retainedReferences: readonly ReferencedPrincipalHead[],\n) {\n // Every recovered Current already retains its own exact head.\n const references = retainedReferences.filter(\n (reference) => !principalHeadMatchesReference(expectedHead, reference),\n );\n const key = (selected: readonly ReferencedPrincipalHead[]) =>\n serializeKeyingCanonicalJson([\n ...scope,\n { ...expectedHead },\n selected.map((reference) => ({ ...reference })),\n ]);\n const known = memo?.get(key([]));\n let sourceCurrent = () => true;\n const current = () =>\n !input.signal?.aborted && input.stillCurrent() && sourceCurrent();\n return memoPrincipalRecovery(memo, key(references), current, async () => {\n const options = {\n ...input,\n expectedHead,\n retainedReferences,\n historyVerification: \"direct-admins\" as const,\n stillCurrent: current,\n };\n if (known) {\n sourceCurrent = (await known).stillCurrent;\n assertProjectionVerificationCurrent(current);\n try {\n // A freshly verified exact head only needs local proofs for additional\n // citations; their signature and private-root checks still run.\n return await recoverPrincipalPolicyHistory({\n ...options,\n offline: true,\n });\n } catch (error) {\n assertProjectionVerificationCurrent(current);\n if (\n input.offline ||\n !(error instanceof KeyingVerificationError) ||\n error.code !== \"missing_dependency\"\n )\n throw error;\n }\n }\n return recoverPrincipalPolicyHistory(options);\n });\n}\n\nasync function readMemoizedDirectory(\n input: PrincipalRecoveryContext,\n memo: Memo<RecoveredPolicyDirectory> | undefined,\n key: (references: readonly ReferencedPrincipalHead[]) => string,\n references: readonly ReferencedPrincipalHead[],\n) {\n const known = references.length > 0 ? memo?.get(key([])) : undefined;\n let sourceCurrent = () => true;\n const current = () =>\n !input.signal?.aborted && input.stillCurrent() && sourceCurrent();\n return memoPrincipalRecovery(memo, key(references), current, async () => {\n if (!known) return recoverPolicyDirectory(input, references);\n const source = await known;\n sourceCurrent = source.stillCurrent;\n assertProjectionVerificationCurrent(current);\n try {\n // Add authenticated historical citations to this batch's exact directory\n // view. A newer private prefix must not silently replace that view.\n return await recoverPolicyDirectory(\n { ...input, offline: true, stillCurrent: current },\n references,\n source.value,\n );\n } catch (error) {\n assertProjectionVerificationCurrent(current);\n if (\n input.offline ||\n !(error instanceof KeyingVerificationError) ||\n error.code !== \"missing_dependency\"\n )\n throw error;\n }\n return recoverPolicyDirectory(\n { ...input, stillCurrent: current },\n references,\n source.value,\n );\n });\n}\n\nexport function createPrincipalRecoveryReader(\n input: PrincipalRecoveryContext,\n memo?: PrincipalRecoveryMemo,\n) {\n const scope = [\n input.organizationId,\n input.protection.context,\n input.offline === true,\n ];\n const directoryKey = (references: readonly ReferencedPrincipalHead[]) =>\n serializeKeyingCanonicalJson([\n ...scope,\n references.map((reference) => ({ ...reference })),\n ]);\n return {\n directory: async (references: readonly ReferencedPrincipalHead[]) => {\n const value = await readMemoizedDirectory(\n input,\n memo?.directories,\n directoryKey,\n references,\n );\n // Retaining extra citations does not prevent this authenticated directory\n // from satisfying a later read with no selected historical references.\n const unselectedKey = directoryKey([]);\n const selected = memo?.directories.get(directoryKey(references));\n if (\n memo &&\n selected &&\n references.length > 0 &&\n !memo.directories.has(unselectedKey)\n )\n // Keep the original lease: its expiry requires a new batch, even if\n // a later caller still has a live lease of its own.\n memo.directories.set(unselectedKey, selected);\n return value;\n },\n admins: (\n expectedHead: ReferencedPrincipalHead,\n retainedReferences: readonly ReferencedPrincipalHead[] = [],\n ) =>\n readMemoizedAdmins(\n input,\n memo?.admins,\n scope,\n expectedHead,\n retainedReferences,\n ),\n };\n}\n"]}
1
+ {"version":3,"file":"principalRecoveryMemo.js","sourceRoot":"","sources":["principalRecoveryMemo.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AAEtG,OAAO,EAGL,sBAAsB,GACvB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACL,kBAAkB,EAClB,qBAAqB,GAEtB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAwBhF,2EAA2E;AAC3E,SAAS,SAAS,CAChB,KAAmB,EACnB,QAA0C;IAE1C,OAAO,KAAK,CAAC,KAAK,KAAK,QAAQ,CAAC,KAAK,EAAE,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;AAClE,CAAC;AAED,SAAS,KAAK,CACZ,IAAyB,EACzB,GAAW,EACX,OAA8B;IAE9B,IAA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WAAW,EACjB,YAAY,EACZ,UAAU,CACX,CACF,CAAC;YACF,0EAA0E;YAC1E,uEAAuE;YACvE,MAAM,aAAa,GAAG,YAAY,CAAC,EAAE,CAAC,CAAC;YACvC,MAAM,QAAQ,GAAG,IAAI,EAAE,WAAW,CAAC,GAAG,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC,CAAC;YACjE,IACE,IAAI;gBACJ,QAAQ;gBACR,UAAU,CAAC,MAAM,GAAG,CAAC;gBACrB,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,aAAa,CAAC;gBAEpC,4EAA4E;gBAC5E,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAC;YAChD,OAAO,KAAK,CAAC;QACf,CAAC;QACD,MAAM,EAAE,KAAK,EACX,YAAqC,EACrC,qBAAyD,EAAE,EAC3D,EAAE,CACF,KAAK,CACH,MAAM,kBAAkB,CACtB,KAAK,EACL,IAAI,EAAE,MAAM,EACZ,KAAK,EACL,YAAY,EACZ,kBAAkB,CACnB,CACF;KACJ,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n serializeKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport type { RecoveredPrincipalPolicyHistory } from \"./principalHistoryRecoveryTypes\";\nimport {\n type PrincipalRecoveryContext,\n type RecoveredPolicyDirectory,\n recoverPolicyDirectory,\n} from \"./principalRecoveryDirectory\";\nimport {\n adminsMemoValidity,\n directoryMemoValidity,\n type PrincipalRecoveryMemoValidity,\n} from \"./principalRecoveryMemoValidity\";\nimport { recoverPrincipalPolicyHistory } from \"./recoverPrincipalPolicyHistory\";\n\ninterface MemoEntry<T> {\n readonly value: T;\n /** The producing call's private lease and caller lifetime. */\n readonly stillCurrent: () => boolean;\n /** Organization hint epoch observed before the reads that produced value. */\n readonly epoch: number;\n}\n\ntype Memo<T> = Map<string, Promise<MemoEntry<T>>>;\n\n/** A value handed out with every lifetime it depends on. */\ninterface Leased<T> {\n readonly value: T;\n /** The consumer's lifetime and every producer lifetime behind value. */\n readonly stillCurrent: () => boolean;\n}\n\nexport interface PrincipalRecoveryMemo {\n readonly directories: Memo<RecoveredPolicyDirectory>;\n readonly admins: Memo<RecoveredPrincipalPolicyHistory>;\n}\n\n/** Synchronous: no hint and no lease end since the entry's reads began. */\nfunction entryLive<T>(\n entry: MemoEntry<T>,\n validity: PrincipalRecoveryMemoValidity<T>,\n): boolean {\n return entry.epoch === validity.epoch() && entry.stillCurrent();\n}\n\nfunction evict<T>(\n memo: Memo<T> | undefined,\n key: string,\n pending: Promise<MemoEntry<T>>,\n): void {\n if (memo?.get(key) === pending) memo.delete(key);\n}\n\n/**\n * Return a live entry, evicting one whose producer lease ended, that predates\n * an organization hint, or that a durable pin has moved past. Liveness is\n * checked again after every await, so a hint or lease end during the pin\n * reads also evicts. The caller rechecks synchronously before use. A pin read\n * is a snapshot; a pin that advances later is caught by the checkpoint reload\n * in recovery, the caller's checkpoint refresh, and atomic admission.\n */\nasync function reusableEntry<T>(\n memo: Memo<T> | undefined,\n key: string,\n validity: PrincipalRecoveryMemoValidity<T>,\n): Promise<\n { entry: MemoEntry<T>; pending: Promise<MemoEntry<T>> } | undefined\n> {\n const pending = memo?.get(key);\n if (!pending) return undefined;\n const entry = await pending.catch(() => undefined);\n if (\n entry &&\n entryLive(entry, validity) &&\n (await validity.covers(entry.value)) &&\n entryLive(entry, validity)\n )\n return { entry, pending };\n evict(memo, key, pending);\n return undefined;\n}\n\n/**\n * Share authenticated results within one workflow operation. A later caller\n * never receives a result whose producer lease ended, that predates an\n * organization hint, or that a durable pin has moved past; it recovers again.\n * A result derived from a reused source keeps the source's epoch, so a hint\n * that arrives before it is stored still evicts it. Every value is handed out\n * with the consumer's lifetime and its producer's, so a producer that expires\n * after hand-out still invalidates the consumer's use.\n */\nasync function memoPrincipalRecovery<T>(\n memo: Memo<T> | undefined,\n key: string,\n stillCurrent: () => boolean,\n validity: PrincipalRecoveryMemoValidity<T>,\n sourceEpoch: number | undefined,\n work: () => Promise<T>,\n): Promise<Leased<T>> {\n assertProjectionVerificationCurrent(stillCurrent);\n const reused = await reusableEntry(memo, key, validity);\n if (reused) {\n const { entry } = reused;\n if (entryLive(entry, validity)) {\n assertProjectionVerificationCurrent(stillCurrent);\n return {\n value: entry.value,\n stillCurrent: () => stillCurrent() && entry.stillCurrent(),\n };\n }\n evict(memo, key, reused.pending);\n }\n // Observed before work starts its reads; a derived result keeps its source's.\n const epoch = sourceEpoch ?? validity.epoch();\n const pending = work().then((value) => ({ value, stillCurrent, epoch }));\n memo?.set(key, pending);\n const result = await pending.catch((error: unknown) => {\n evict(memo, key, pending);\n throw error;\n });\n // A hint during production leaves this caller's in-flight view, never a\n // stored one: the stale epoch would evict it anyway.\n if (result.epoch !== validity.epoch()) evict(memo, key, pending);\n assertProjectionVerificationCurrent(result.stillCurrent);\n assertProjectionVerificationCurrent(stillCurrent);\n // stillCurrent already includes the lifetime of a derived value's source.\n return { value: result.value, stillCurrent };\n}\n\nfunction fallsBackOnline(\n input: PrincipalRecoveryContext,\n error: unknown,\n): boolean {\n return (\n !input.offline &&\n error instanceof KeyingVerificationError &&\n error.code === \"missing_dependency\"\n );\n}\n\nasync function readMemoizedAdmins(\n input: PrincipalRecoveryContext,\n memo: Memo<RecoveredPrincipalPolicyHistory> | undefined,\n scope: readonly (string | boolean)[],\n expectedHead: ReferencedPrincipalHead,\n retainedReferences: readonly ReferencedPrincipalHead[],\n) {\n // Every recovered Current already retains its own exact head.\n const references = retainedReferences.filter(\n (reference) => !principalHeadMatchesReference(expectedHead, reference),\n );\n const key = (selected: readonly ReferencedPrincipalHead[]) =>\n serializeKeyingCanonicalJson([\n ...scope,\n { ...expectedHead },\n selected.map((reference) => ({ ...reference })),\n ]);\n const validity = adminsMemoValidity(input, expectedHead);\n const known = (await reusableEntry(memo, key([]), validity))?.entry;\n const sourceCurrent = known?.stillCurrent ?? (() => true);\n const current = () =>\n !input.signal?.aborted && input.stillCurrent() && sourceCurrent();\n return memoPrincipalRecovery(\n memo,\n key(references),\n current,\n validity,\n known?.epoch,\n async () => {\n const options = {\n ...input,\n expectedHead,\n retainedReferences,\n historyVerification: \"direct-admins\" as const,\n stillCurrent: current,\n };\n if (known) {\n try {\n // A freshly verified exact head only needs local proofs for additional\n // citations; their signature and private-root checks still run.\n return await recoverPrincipalPolicyHistory({\n ...options,\n offline: true,\n });\n } catch (error) {\n assertProjectionVerificationCurrent(current);\n if (!fallsBackOnline(input, error)) throw error;\n }\n }\n return recoverPrincipalPolicyHistory(options);\n },\n );\n}\n\nasync function readMemoizedDirectory(\n input: PrincipalRecoveryContext,\n memo: Memo<RecoveredPolicyDirectory> | undefined,\n key: (references: readonly ReferencedPrincipalHead[]) => string,\n references: readonly ReferencedPrincipalHead[],\n) {\n const validity = directoryMemoValidity(input);\n const known =\n references.length > 0\n ? (await reusableEntry(memo, key([]), validity))?.entry\n : undefined;\n const sourceCurrent = known?.stillCurrent ?? (() => true);\n const current = () =>\n !input.signal?.aborted && input.stillCurrent() && sourceCurrent();\n return memoPrincipalRecovery(\n memo,\n key(references),\n current,\n validity,\n known?.epoch,\n async () => {\n if (!known) return recoverPolicyDirectory(input, references);\n try {\n // Add authenticated historical citations to this operation's exact\n // directory view. A newer private prefix must not silently replace it.\n return await recoverPolicyDirectory(\n { ...input, offline: true, stillCurrent: current },\n references,\n known.value,\n );\n } catch (error) {\n assertProjectionVerificationCurrent(current);\n if (!fallsBackOnline(input, error)) throw error;\n }\n return recoverPolicyDirectory(\n { ...input, stillCurrent: current },\n references,\n known.value,\n );\n },\n );\n}\n\nexport function createPrincipalRecoveryReader(\n input: PrincipalRecoveryContext,\n memo?: PrincipalRecoveryMemo,\n) {\n const scope = [\n input.organizationId,\n input.protection.context,\n input.offline === true,\n ];\n const directoryKey = (references: readonly ReferencedPrincipalHead[]) =>\n serializeKeyingCanonicalJson([\n ...scope,\n references.map((reference) => ({ ...reference })),\n ]);\n // Every lifetime behind a value this reader handed out; its caller must\n // keep checking them at the point of use.\n const lifetimes: (() => boolean)[] = [];\n const lease = <T>(leased: Leased<T>): T => {\n lifetimes.push(leased.stillCurrent);\n return leased.value;\n };\n return {\n stillCurrent: () => lifetimes.every((current) => current()),\n directory: async (references: readonly ReferencedPrincipalHead[]) => {\n const value = lease(\n await readMemoizedDirectory(\n input,\n memo?.directories,\n directoryKey,\n references,\n ),\n );\n // Retaining extra citations does not prevent this authenticated directory\n // from satisfying a later read with no selected historical references.\n const unselectedKey = directoryKey([]);\n const selected = memo?.directories.get(directoryKey(references));\n if (\n memo &&\n selected &&\n references.length > 0 &&\n !memo.directories.has(unselectedKey)\n )\n // The alias keeps the original lease and validity; either ending evicts it.\n memo.directories.set(unselectedKey, selected);\n return value;\n },\n admins: async (\n expectedHead: ReferencedPrincipalHead,\n retainedReferences: readonly ReferencedPrincipalHead[] = [],\n ) =>\n lease(\n await readMemoizedAdmins(\n input,\n memo?.admins,\n scope,\n expectedHead,\n retainedReferences,\n ),\n ),\n };\n}\n"]}
@@ -0,0 +1,33 @@
1
+ import { loadPrincipalPolicyCheckpoint } from "../../data/persistence/keyingCheckpointPersistence.js";
2
+ import { principalRecoveryEpoch } from "../../data/principals/principalRecoveryEpoch.js";
3
+ async function pinCovers(input, head) {
4
+ const pin = await loadPrincipalPolicyCheckpoint(input.execSql, head.principalType, head.principalId);
5
+ return (!pin ||
6
+ pin.version < head.version ||
7
+ (pin.version === head.version && pin.stateHash === head.stateHash));
8
+ }
9
+ function organizationEpoch(input) {
10
+ return () => principalRecoveryEpoch(input.execSql, input.organizationId);
11
+ }
12
+ /** A directory names every group head; a newer pin on any of them evicts it. */
13
+ export function directoryMemoValidity(input) {
14
+ return {
15
+ epoch: organizationEpoch(input),
16
+ covers: async (directory) => {
17
+ for (const head of [
18
+ directory.policy.state,
19
+ ...directory.descriptor.groupHeads,
20
+ ])
21
+ if (!(await pinCovers(input, head)))
22
+ return false;
23
+ return true;
24
+ },
25
+ };
26
+ }
27
+ export function adminsMemoValidity(input, expectedHead) {
28
+ return {
29
+ epoch: organizationEpoch(input),
30
+ covers: () => pinCovers(input, expectedHead),
31
+ };
32
+ }
33
+ //# sourceMappingURL=principalRecoveryMemoValidity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalRecoveryMemoValidity.js","sourceRoot":"","sources":["principalRecoveryMemoValidity.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,6BAA6B,EAAE,MAAM,oDAAoD,CAAC;AACnG,OAAO,EAAE,sBAAsB,EAAE,MAAM,8CAA8C,CAAC;AAoBtF,KAAK,UAAU,SAAS,CACtB,KAA+B,EAC/B,IAAgB;IAEhB,MAAM,GAAG,GAAG,MAAM,6BAA6B,CAC7C,KAAK,CAAC,OAAO,EACb,IAAI,CAAC,aAAa,EAClB,IAAI,CAAC,WAAW,CACjB,CAAC;IACF,OAAO,CACL,CAAC,GAAG;QACJ,GAAG,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO;QAC1B,CAAC,GAAG,CAAC,OAAO,KAAK,IAAI,CAAC,OAAO,IAAI,GAAG,CAAC,SAAS,KAAK,IAAI,CAAC,SAAS,CAAC,CACnE,CAAC;AACJ,CAAC;AAED,SAAS,iBAAiB,CAAC,KAA+B;IACxD,OAAO,GAAG,EAAE,CAAC,sBAAsB,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,cAAc,CAAC,CAAC;AAC3E,CAAC;AAED,gFAAgF;AAChF,MAAM,UAAU,qBAAqB,CACnC,KAA+B;IAE/B,OAAO;QACL,KAAK,EAAE,iBAAiB,CAAC,KAAK,CAAC;QAC/B,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,EAAE;YAC1B,KAAK,MAAM,IAAI,IAAI;gBACjB,SAAS,CAAC,MAAM,CAAC,KAAK;gBACtB,GAAG,SAAS,CAAC,UAAU,CAAC,UAAU;aACnC;gBACC,IAAI,CAAC,CAAC,MAAM,SAAS,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;oBAAE,OAAO,KAAK,CAAC;YACpD,OAAO,IAAI,CAAC;QACd,CAAC;KACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,kBAAkB,CAChC,KAA+B,EAC/B,YAAwB;IAExB,OAAO;QACL,KAAK,EAAE,iBAAiB,CAAC,KAAK,CAAC;QAC/B,MAAM,EAAE,GAAG,EAAE,CAAC,SAAS,CAAC,KAAK,EAAE,YAAY,CAAC;KAC7C,CAAC;AACJ,CAAC","sourcesContent":["import type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../data/persistence/keyingCheckpointPersistence\";\nimport { principalRecoveryEpoch } from \"../../data/principals/principalRecoveryEpoch\";\nimport type { RecoveredPrincipalPolicyHistory } from \"./principalHistoryRecoveryTypes\";\nimport type {\n PrincipalRecoveryContext,\n RecoveredPolicyDirectory,\n} from \"./principalRecoveryDirectory\";\n\n/** What keeps a memo entry valid beyond its producer's lease. */\nexport interface PrincipalRecoveryMemoValidity<T> {\n /** Organization hint epoch; production records it before its reads. */\n readonly epoch: () => number;\n /** No durable pin has moved past or forked from a memoized head. */\n readonly covers: (value: T) => Promise<boolean>;\n}\n\ntype PinnedHead = Pick<\n ReferencedPrincipalHead,\n \"principalType\" | \"principalId\" | \"version\" | \"stateHash\"\n>;\n\nasync function pinCovers(\n input: PrincipalRecoveryContext,\n head: PinnedHead,\n): Promise<boolean> {\n const pin = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n head.principalType,\n head.principalId,\n );\n return (\n !pin ||\n pin.version < head.version ||\n (pin.version === head.version && pin.stateHash === head.stateHash)\n );\n}\n\nfunction organizationEpoch(input: PrincipalRecoveryContext) {\n return () => principalRecoveryEpoch(input.execSql, input.organizationId);\n}\n\n/** A directory names every group head; a newer pin on any of them evicts it. */\nexport function directoryMemoValidity(\n input: PrincipalRecoveryContext,\n): PrincipalRecoveryMemoValidity<RecoveredPolicyDirectory> {\n return {\n epoch: organizationEpoch(input),\n covers: async (directory) => {\n for (const head of [\n directory.policy.state,\n ...directory.descriptor.groupHeads,\n ])\n if (!(await pinCovers(input, head))) return false;\n return true;\n },\n };\n}\n\nexport function adminsMemoValidity(\n input: PrincipalRecoveryContext,\n expectedHead: PinnedHead,\n): PrincipalRecoveryMemoValidity<RecoveredPrincipalPolicyHistory> {\n return {\n epoch: organizationEpoch(input),\n covers: () => pinCovers(input, expectedHead),\n };\n}\n"]}