@tearleads/client-sdk 0.1.209 → 0.1.211

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 (28) hide show
  1. package/client/organizations/index.js +5 -5
  2. package/client/organizations/index.js.map +1 -1
  3. package/client/organizations/principalMutationScope.js +7 -1
  4. package/client/organizations/principalMutationScope.js.map +1 -1
  5. package/client/organizations/principalMutations.d.ts +8 -6
  6. package/client/organizations/principalMutations.js +8 -8
  7. package/client/organizations/principalMutations.js.map +1 -1
  8. package/client/organizations/recipientAdmission.d.ts +2 -1
  9. package/client/organizations/recipientAdmission.js +2 -2
  10. package/client/organizations/recipientAdmission.js.map +1 -1
  11. package/client/runtime/workflowRuntime.d.ts +2 -1
  12. package/client/runtime/workflowRuntime.js +1 -1
  13. package/client/runtime/workflowRuntime.js.map +1 -1
  14. package/data/persistence/container-contents/documentMoveIntentPersistence.js +47 -30
  15. package/data/persistence/container-contents/documentMoveIntentPersistence.js.map +1 -1
  16. package/data/persistence/container-contents/documentPlacementIntentEnqueue.js +6 -14
  17. package/data/persistence/container-contents/documentPlacementIntentEnqueue.js.map +1 -1
  18. package/package.json +1 -1
  19. package/workflows/container-contents/documentMove/documentMoveIntentErrors.js +2 -2
  20. package/workflows/container-contents/documentMove/documentMoveIntentErrors.js.map +1 -1
  21. package/workflows/container-contents/documentMove/documentMoveIntentSettlement.js +3 -2
  22. package/workflows/container-contents/documentMove/documentMoveIntentSettlement.js.map +1 -1
  23. package/workflows/container-contents/documentMove/documentMoveIntentSync.js +4 -3
  24. package/workflows/container-contents/documentMove/documentMoveIntentSync.js.map +1 -1
  25. package/workflows/container-contents/pendingWrites/index.js +3 -3
  26. package/workflows/container-contents/pendingWrites/index.js.map +1 -1
  27. package/workflows/container-contents/recovery/accessRestoration.js +4 -7
  28. package/workflows/container-contents/recovery/accessRestoration.js.map +1 -1
@@ -1,5 +1,5 @@
1
1
  import { reportAndRethrowKeyingVerificationError } from "../../../data/keyingProjectionVerification/error.js";
2
- import { DOCUMENT_LINK_INTENT_TYPE, sqlDocumentMoveIntentPersistence, } from "../../../data/persistence/container-contents/documentMoveIntentPersistence.js";
2
+ import { DOCUMENT_LINK_INTENT_TYPE, DocumentMoveIntentRepository, } from "../../../data/persistence/container-contents/documentMoveIntentPersistence.js";
3
3
  import { errorMessage } from "../../../data/shared/errorMessage.js";
4
4
  import { defaultDocumentsPersistence, } from "../../documents/index.js";
5
5
  import { availableDocumentLinkIntent } from "../documentLinks/availableDocumentLinkIntent.js";
@@ -294,13 +294,14 @@ export async function syncPendingDocumentMoveIntents(input) {
294
294
  const lifecycleState = input.state;
295
295
  const state = { ...lifecycleState };
296
296
  const execSql = state.runtime.infra.execSql;
297
+ const moveIntents = new DocumentMoveIntentRepository(execSql);
297
298
  if (!deniedReplayMatchesGeneration(lifecycleState, execSql)) {
298
- await sqlDocumentMoveIntentPersistence.resetDeniedMoveIntents(execSql);
299
+ await moveIntents.resetDeniedMoveIntents();
299
300
  if (!input.isCurrent())
300
301
  return 0;
301
302
  markDeniedReplayGeneration(lifecycleState, execSql);
302
303
  }
303
- const pendingIntents = await sqlDocumentMoveIntentPersistence.listPendingMoveIntents(execSql);
304
+ const pendingIntents = await moveIntents.listPendingMoveIntents();
304
305
  if (!input.isCurrent())
305
306
  return 0;
306
307
  let movedCount = 0;
@@ -1 +1 @@
1
- {"version":3,"file":"documentMoveIntentSync.js","sourceRoot":"","sources":["documentMoveIntentSync.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uCAAuC,EAAE,MAAM,kDAAkD,CAAC;AAC3G,OAAO,EACL,yBAAyB,EAEzB,gCAAgC,GACjC,MAAM,4EAA4E,CAAC;AACpF,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,EAGL,2BAA2B,GAC5B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,2BAA2B,EAAE,MAAM,8CAA8C,CAAC;AAC3F,OAAO,EAAE,2BAA2B,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AC,KAAK,CAAC,SAAS,EAAE;YAAE,OAAO,UAAU,CAAC;QAC1C,MAAM,MAAM,GAAG,MAAM,gCAAgC,CAAC;YACpD,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;YAC9C,MAAM;YACN,KAAK;SACN,CAAC,CAAC;QACH,IAAI,MAAM,KAAK,WAAW;YAAE,OAAO,UAAU,CAAC;QAC9C,0EAA0E;QAC1E,qEAAqE;QACrE,sEAAsE;QACtE,yEAAyE;QACzE,kCAAkC;QAClC,IAAI,MAAM,KAAK,OAAO,EAAE,CAAC;YACvB,UAAU,IAAI,CAAC,CAAC;QAClB,CAAC;IACH,CAAC;IAED,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import { reportAndRethrowKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport {\n DOCUMENT_LINK_INTENT_TYPE,\n type DocumentMoveIntentRecord,\n sqlDocumentMoveIntentPersistence,\n} from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport {\n type DocumentLinkSetFailureHandler,\n type DocumentRecord,\n defaultDocumentsPersistence,\n} from \"../../documents\";\nimport { availableDocumentLinkIntent } from \"../documentLinks/availableDocumentLinkIntent\";\nimport { moveRemoteContainerDocument } from \"../documentLinks/documentLinksMove\";\nimport type {\n DocumentStructuralMutationLocalStore,\n DocumentStructuralMutationRelinkInput,\n} from \"../documentQueries/documentStructureTypes\";\nimport type { ContainerContentsProjectionUserKeyResolver } from \"../projectionKeys\";\nimport type { ContainerState } from \"../remoteHydration\";\nimport { hasRemoteContainerMetadataState } from \"../remoteHydration/reconciliation\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\nimport {\n deniedReplayMatchesGeneration,\n markDeniedReplayGeneration,\n} from \"./documentMoveDeniedReplay\";\nimport {\n type DocumentMoveFailureState,\n describeRejectedDocumentMove,\n} from \"./documentMoveFailure\";\nimport { recordPendingDocumentMoveIntentError } from \"./documentMoveIntentErrors\";\nimport { settleDocumentMoveIntent } from \"./documentMoveIntentSettlement\";\nimport { moveWithRotationProof } from \"./documentMoveRotationProof\";\nimport { moveWithVanishedContainerRefresh } from \"./documentMoveVanishedRefresh\";\n\ntype DocumentMoveIntentReplayResult =\n | \"abandoned\"\n | \"moved\"\n | \"partial\"\n | \"blocked\"\n | \"failed\";\n\nexport interface DocumentMoveIntentSyncHost<TRuntime> {\n documentWorkflowRuntime: (containerId: string) => TRuntime;\n openDocumentStore: (input: {\n containerId: string;\n documentId: string | null;\n localId: string;\n }) => DocumentStructuralMutationLocalStore<TRuntime>;\n}\n\ninterface DocumentMoveIntentSyncState {\n containersById: ReadonlyMap<string, ContainerState>;\n lifecycleGeneration?: number | undefined;\n resolveProjectionUserKey: ContainerContentsProjectionUserKeyResolver;\n runtime: ContainerContentsWorkflowRuntime;\n}\n\nasync function relinkMovedDocumentStore<TRuntime>(input: {\n host: DocumentMoveIntentSyncHost<TRuntime>;\n isCurrent: () => boolean;\n intent: DocumentMoveIntentRecord;\n relinkInput: DocumentStructuralMutationRelinkInput;\n targetContainerId: string;\n}): Promise<boolean> {\n if (!input.isCurrent()) return false;\n const documentStore = input.host.openDocumentStore({\n containerId: input.targetContainerId,\n documentId: input.intent.documentId,\n localId: input.intent.localId,\n });\n if (!(await documentStore.ensureInitialized()) || !input.isCurrent()) {\n return false;\n }\n\n const relinked = await documentStore.relink({\n ...input.relinkInput,\n stillCurrent: input.isCurrent,\n });\n if (!relinked || !input.isCurrent()) {\n return false;\n }\n\n documentStore.updateRuntime(\n input.host.documentWorkflowRuntime(input.targetContainerId),\n );\n return input.isCurrent();\n}\n\nasync function persistMovedDocumentReplay<TRuntime>(input: {\n host: DocumentMoveIntentSyncHost<TRuntime>;\n intent: DocumentMoveIntentRecord;\n isCurrent: () => boolean;\n moved: NonNullable<Awaited<ReturnType<typeof moveRemoteContainerDocument>>>;\n state: DocumentMoveIntentSyncState;\n}): Promise<boolean> {\n const { host, intent, moved, state } = input;\n const existingDocument = await defaultDocumentsPersistence.loadDocument(\n state.runtime.infra.execSql,\n intent.localId,\n );\n if (!input.isCurrent() || !existingDocument) {\n return false;\n }\n\n const targetContainerId =\n intent.intentType === DOCUMENT_LINK_INTENT_TYPE &&\n existingDocument.containerId &&\n moved.linkedContainerIds.includes(existingDocument.containerId)\n ? existingDocument.containerId\n : moved.nextContainerId;\n\n const relinkInput: DocumentStructuralMutationRelinkInput = {\n accessEpoch: moved.accessEpoch ?? existingDocument.accessEpoch,\n ...(moved.accessStateHash === null\n ? {}\n : { accessStateHash: moved.accessStateHash }),\n containerId: targetContainerId,\n documentId: intent.documentId,\n localId: intent.localId,\n ...(moved.remoteState ?? {}),\n commitSideEffect: (transactionExecSql) =>\n settleDocumentMoveIntent({\n execSql: transactionExecSql,\n intent,\n isCurrent: input.isCurrent,\n linkedContainerIds: moved.linkedContainerIds,\n partial: moved.status === \"partial\",\n }),\n };\n\n return relinkMovedDocumentStore({\n host,\n isCurrent: input.isCurrent,\n intent,\n relinkInput,\n targetContainerId,\n });\n}\n\nasync function movePendingDocumentIntent<TRuntime>(input: {\n existingContainerId: string | null | undefined;\n host: DocumentMoveIntentSyncHost<TRuntime>;\n isCurrent: () => boolean;\n intent: DocumentMoveIntentRecord;\n onFailure: DocumentLinkSetFailureHandler;\n state: DocumentMoveIntentSyncState;\n}) {\n // Adding links keeps the content key and needs no full-history rotation proof.\n const linkOnly = input.intent.intentType === DOCUMENT_LINK_INTENT_TYPE;\n const move = (\n rotationSnapshot: Uint8Array,\n onFailure: DocumentLinkSetFailureHandler,\n ) =>\n moveRemoteContainerDocument({\n linkOnly,\n additionalLinkContainerIds: input.intent.additionalLinkContainerIds,\n removedLinkContainerIds: input.intent.removedLinkContainerIds,\n currentContainerId:\n input.intent.sourceContainerId ??\n input.existingContainerId ??\n input.intent.targetContainerId,\n documentId: input.intent.documentId,\n isCurrent: input.isCurrent,\n noteId: input.intent.localId,\n onFailure,\n replaceLinkedContainers: input.intent.replaceLinkedContainers,\n resolveProjectionUserKey: input.state.resolveProjectionUserKey,\n rotationSnapshot,\n runtime: input.state.runtime,\n targetContainerId: input.intent.targetContainerId,\n });\n if (linkOnly && !input.intent.removedLinkContainerIds?.length) {\n return move(new Uint8Array(), input.onFailure);\n }\n return moveWithRotationProof({\n ...input,\n attempt: move,\n log: (message) => input.state.runtime.util.log(message),\n });\n}\n\nasync function resolveMoveIntentPreflight(input: {\n isCreatePending: (containerId: string) => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n isCurrent: () => boolean;\n intent: DocumentMoveIntentRecord;\n state: DocumentMoveIntentSyncState;\n}): Promise<\n | { existingDocument: DocumentRecord; result?: undefined }\n | { existingDocument?: undefined; result: DocumentMoveIntentReplayResult }\n> {\n const { intent, state } = input;\n const execSql = state.runtime.infra.execSql;\n const existingDocument = await defaultDocumentsPersistence.loadDocument(\n execSql,\n intent.localId,\n );\n if (!input.isCurrent()) return { result: \"abandoned\" };\n if (!existingDocument || existingDocument.documentId !== intent.documentId) {\n await recordPendingDocumentMoveIntentError({\n blocked: true,\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: \"Document move intent references a missing local document\",\n state,\n });\n return { result: \"blocked\" };\n }\n\n for (const targetId of new Set([\n intent.targetContainerId,\n ...(intent.additionalLinkContainerIds ?? []),\n ])) {\n const targetState = state.containersById.get(targetId);\n if (!targetState) {\n await recordPendingDocumentMoveIntentError({\n blocked: true,\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message:\n \"Document move intent references a missing destination container\",\n state,\n });\n return { result: \"blocked\" };\n }\n if (input.isRemoteSyncBlocked(targetState.container.organizationId)) {\n return { result: \"blocked\" };\n }\n if (\n !hasRemoteContainerMetadataState(targetState) ||\n input.isCreatePending(targetId)\n ) {\n await recordPendingDocumentMoveIntentError({\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: \"Document move destination container is not synced yet\",\n state,\n });\n return { result: \"failed\" };\n }\n }\n return { existingDocument };\n}\n\nasync function recordRejectedDocumentMove(input: {\n failure: DocumentMoveFailureState;\n intent: DocumentMoveIntentRecord;\n isCurrent: () => boolean;\n state: DocumentMoveIntentSyncState;\n unavailable: boolean;\n}): Promise<void> {\n await recordPendingDocumentMoveIntentError({\n // A permission denial parks the intent for the access-restored signal\n // instead of replaying on every structural pass (row 7).\n denied: input.failure.sawPermissionDenial,\n documentId: input.intent.documentId,\n expectedIntentId: input.intent.id,\n expectedUpdatedAt: input.intent.updatedAt,\n isCurrent: input.isCurrent,\n message: describeRejectedDocumentMove(input.failure),\n state: input.state,\n // Terminal only after the vanished-container refresh proved the\n // destination itself gone: the intent can never commit as written and\n // nothing on this device can heal it, so it leaves the replay set instead\n // of re-issuing doomed requests every pass. The tombstone cascade\n // retargets it once hydration tears the deleted container down locally.\n // Every other vanished verdict stays pending for the next pass.\n unavailable: input.unavailable,\n });\n}\n\nfunction logSyncedDocumentMove(\n intent: DocumentMoveIntentRecord,\n state: DocumentMoveIntentSyncState,\n): void {\n state.runtime.util.log(\n `Container contents: synced queued document move ${intent.documentId}`,\n );\n}\n\nasync function settleMovedDocumentIntent<TRuntime>(input: {\n failure: DocumentMoveFailureState;\n host: DocumentMoveIntentSyncHost<TRuntime>;\n intent: DocumentMoveIntentRecord;\n isCurrent: () => boolean;\n moved: NonNullable<Awaited<ReturnType<typeof moveRemoteContainerDocument>>>;\n state: DocumentMoveIntentSyncState;\n unavailable: boolean;\n}): Promise<DocumentMoveIntentReplayResult> {\n const { intent, moved, state } = input;\n if (\n !(await persistMovedDocumentReplay({\n host: input.host,\n intent,\n isCurrent: input.isCurrent,\n moved,\n state,\n }))\n ) {\n if (!input.isCurrent()) return \"abandoned\";\n await recordPendingDocumentMoveIntentError({\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: \"Document move replay could not relink the local document\",\n state,\n });\n return \"failed\";\n }\n if (moved.status === \"partial\") {\n await recordPendingDocumentMoveIntentError({\n // An unlink refused for permissions parks like any other denied\n // move (row 7); other partials keep row 15's replay.\n denied: input.failure.sawPermissionDenial,\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: \"Remote document move partially applied; retry required\",\n state,\n // Terminal only when the refresh proved the destination itself gone\n // after the link had already landed; a vanished unlink alone stays\n // pending with its live link for the next pass to revoke.\n unavailable: input.unavailable,\n });\n return \"partial\";\n }\n\n logSyncedDocumentMove(intent, state);\n return \"moved\";\n}\n\nasync function trySyncPendingDocumentMoveIntent<TRuntime>(input: {\n host: DocumentMoveIntentSyncHost<TRuntime>;\n isCreatePending: (containerId: string) => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n isCurrent: () => boolean;\n intent: DocumentMoveIntentRecord;\n state: DocumentMoveIntentSyncState;\n}): Promise<DocumentMoveIntentReplayResult> {\n const { host, intent, state } = input;\n const available = availableDocumentLinkIntent(intent, (id) =>\n state.containersById.has(id),\n );\n const preflight = await resolveMoveIntentPreflight({\n ...input,\n intent: available.intent,\n });\n if (preflight.result !== undefined) {\n return preflight.result;\n }\n const { existingDocument } = preflight;\n\n try {\n const outcome = await moveWithVanishedContainerRefresh({\n apiClient: state.runtime.apiClient,\n attempt: (onFailure) =>\n movePendingDocumentIntent({\n existingContainerId: existingDocument.containerId,\n host,\n isCurrent: input.isCurrent,\n intent: available.intent,\n onFailure,\n state,\n }),\n execSql: state.runtime.infra.execSql,\n existingContainerId: existingDocument.containerId,\n intent: available.intent,\n isCurrent: input.isCurrent,\n });\n if (outcome === \"abandoned\" || !input.isCurrent()) return \"abandoned\";\n if (!outcome.moved) {\n await recordRejectedDocumentMove({\n failure: outcome.failure,\n intent,\n isCurrent: input.isCurrent,\n state,\n unavailable: outcome.unavailable,\n });\n return \"failed\";\n }\n return await settleMovedDocumentIntent({\n failure: outcome.failure,\n host,\n intent,\n isCurrent: input.isCurrent,\n moved: available.deferred\n ? { ...outcome.moved, status: \"partial\" }\n : outcome.moved,\n state,\n unavailable: outcome.unavailable,\n });\n } catch (error: unknown) {\n if (!input.isCurrent()) return \"abandoned\";\n await reportAndRethrowKeyingVerificationError(\n error,\n state.runtime.util.reportSecurityIncident,\n {\n objectId: intent.documentId,\n objectKind: \"document\",\n operation: \"document.move.replay\",\n },\n );\n if (!input.isCurrent()) return \"abandoned\";\n const message = errorMessage(error);\n await recordPendingDocumentMoveIntentError({\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: `Failed to sync document move: ${message}`,\n state,\n });\n return \"failed\";\n }\n}\n\nexport async function syncPendingDocumentMoveIntents<TRuntime>(input: {\n host: DocumentMoveIntentSyncHost<TRuntime>;\n /** A destination whose create has not settled takes no document yet. */\n isCreatePending: (containerId: string) => boolean;\n isCurrent: () => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n state: DocumentMoveIntentSyncState;\n}): Promise<number> {\n if (!input.isCurrent()) return 0;\n const lifecycleState = input.state;\n const state = { ...lifecycleState };\n const execSql = state.runtime.infra.execSql;\n if (!deniedReplayMatchesGeneration(lifecycleState, execSql)) {\n await sqlDocumentMoveIntentPersistence.resetDeniedMoveIntents(execSql);\n if (!input.isCurrent()) return 0;\n markDeniedReplayGeneration(lifecycleState, execSql);\n }\n const pendingIntents =\n await sqlDocumentMoveIntentPersistence.listPendingMoveIntents(execSql);\n if (!input.isCurrent()) return 0;\n let movedCount = 0;\n\n for (const intent of pendingIntents) {\n if (!input.isCurrent()) return movedCount;\n const result = await trySyncPendingDocumentMoveIntent({\n host: input.host,\n isCreatePending: input.isCreatePending,\n isCurrent: input.isCurrent,\n isRemoteSyncBlocked: input.isRemoteSyncBlocked,\n intent,\n state,\n });\n if (result === \"abandoned\") return movedCount;\n // A \"partial\" result (link applied, unlink still pending) must not count:\n // the caller re-arms this same structural lane whenever the count is\n // positive, so a deterministically failing unlink hot-looped the pump\n // (issue #1744). The intent row stays pending; event-driven, manual, and\n // startup lane requests retry it.\n if (result === \"moved\") {\n movedCount += 1;\n }\n }\n\n return movedCount;\n}\n"]}
1
+ {"version":3,"file":"documentMoveIntentSync.js","sourceRoot":"","sources":["documentMoveIntentSync.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uCAAuC,EAAE,MAAM,kDAAkD,CAAC;AAC3G,OAAO,EACL,yBAAyB,EAEzB,4BAA4B,GAC7B,MAAM,4EAA4E,CAAC;AACpF,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,EAGL,2BAA2B,GAC5B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,2BAA2B,EAAE,MAAM,8CAA8C,CAAC;AAC3F,OAAO,EAAE,2BAA2B,EAAE,MAAM,oCAAoC,CAAC;AAOjF,OAAO,EAAE,+BAA+B,EAAE,MAAM,mCAAmC,CAAC;AAEpF,OAAO,EACL,6BAA6B,EAC7B,0BAA0B,GAC3B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAEL,4BAA4B,GAC7B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,oCAAoC,EAAE,MAAM,4BAA4B,CAAC;AAClF,OAAO,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAC1E,OAAO,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AACpE,OAAO,EAAE,gCAAgC,EAAE,MAAM,+BAA+B,CAAC;AAyBjF,KAAK,UAAU,wBAAwB,CAAW,KAMjD;IACC,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE;QAAE,OAAO,KA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C,CAAC;QAClB,CAAC;IACH,CAAC;IAED,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import { reportAndRethrowKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport {\n DOCUMENT_LINK_INTENT_TYPE,\n type DocumentMoveIntentRecord,\n DocumentMoveIntentRepository,\n} from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport {\n type DocumentLinkSetFailureHandler,\n type DocumentRecord,\n defaultDocumentsPersistence,\n} from \"../../documents\";\nimport { availableDocumentLinkIntent } from \"../documentLinks/availableDocumentLinkIntent\";\nimport { moveRemoteContainerDocument } from \"../documentLinks/documentLinksMove\";\nimport type {\n DocumentStructuralMutationLocalStore,\n DocumentStructuralMutationRelinkInput,\n} from \"../documentQueries/documentStructureTypes\";\nimport type { ContainerContentsProjectionUserKeyResolver } from \"../projectionKeys\";\nimport type { ContainerState } from \"../remoteHydration\";\nimport { hasRemoteContainerMetadataState } from \"../remoteHydration/reconciliation\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\nimport {\n deniedReplayMatchesGeneration,\n markDeniedReplayGeneration,\n} from \"./documentMoveDeniedReplay\";\nimport {\n type DocumentMoveFailureState,\n describeRejectedDocumentMove,\n} from \"./documentMoveFailure\";\nimport { recordPendingDocumentMoveIntentError } from \"./documentMoveIntentErrors\";\nimport { settleDocumentMoveIntent } from \"./documentMoveIntentSettlement\";\nimport { moveWithRotationProof } from \"./documentMoveRotationProof\";\nimport { moveWithVanishedContainerRefresh } from \"./documentMoveVanishedRefresh\";\n\ntype DocumentMoveIntentReplayResult =\n | \"abandoned\"\n | \"moved\"\n | \"partial\"\n | \"blocked\"\n | \"failed\";\n\nexport interface DocumentMoveIntentSyncHost<TRuntime> {\n documentWorkflowRuntime: (containerId: string) => TRuntime;\n openDocumentStore: (input: {\n containerId: string;\n documentId: string | null;\n localId: string;\n }) => DocumentStructuralMutationLocalStore<TRuntime>;\n}\n\ninterface DocumentMoveIntentSyncState {\n containersById: ReadonlyMap<string, ContainerState>;\n lifecycleGeneration?: number | undefined;\n resolveProjectionUserKey: ContainerContentsProjectionUserKeyResolver;\n runtime: ContainerContentsWorkflowRuntime;\n}\n\nasync function relinkMovedDocumentStore<TRuntime>(input: {\n host: DocumentMoveIntentSyncHost<TRuntime>;\n isCurrent: () => boolean;\n intent: DocumentMoveIntentRecord;\n relinkInput: DocumentStructuralMutationRelinkInput;\n targetContainerId: string;\n}): Promise<boolean> {\n if (!input.isCurrent()) return false;\n const documentStore = input.host.openDocumentStore({\n containerId: input.targetContainerId,\n documentId: input.intent.documentId,\n localId: input.intent.localId,\n });\n if (!(await documentStore.ensureInitialized()) || !input.isCurrent()) {\n return false;\n }\n\n const relinked = await documentStore.relink({\n ...input.relinkInput,\n stillCurrent: input.isCurrent,\n });\n if (!relinked || !input.isCurrent()) {\n return false;\n }\n\n documentStore.updateRuntime(\n input.host.documentWorkflowRuntime(input.targetContainerId),\n );\n return input.isCurrent();\n}\n\nasync function persistMovedDocumentReplay<TRuntime>(input: {\n host: DocumentMoveIntentSyncHost<TRuntime>;\n intent: DocumentMoveIntentRecord;\n isCurrent: () => boolean;\n moved: NonNullable<Awaited<ReturnType<typeof moveRemoteContainerDocument>>>;\n state: DocumentMoveIntentSyncState;\n}): Promise<boolean> {\n const { host, intent, moved, state } = input;\n const existingDocument = await defaultDocumentsPersistence.loadDocument(\n state.runtime.infra.execSql,\n intent.localId,\n );\n if (!input.isCurrent() || !existingDocument) {\n return false;\n }\n\n const targetContainerId =\n intent.intentType === DOCUMENT_LINK_INTENT_TYPE &&\n existingDocument.containerId &&\n moved.linkedContainerIds.includes(existingDocument.containerId)\n ? existingDocument.containerId\n : moved.nextContainerId;\n\n const relinkInput: DocumentStructuralMutationRelinkInput = {\n accessEpoch: moved.accessEpoch ?? existingDocument.accessEpoch,\n ...(moved.accessStateHash === null\n ? {}\n : { accessStateHash: moved.accessStateHash }),\n containerId: targetContainerId,\n documentId: intent.documentId,\n localId: intent.localId,\n ...(moved.remoteState ?? {}),\n commitSideEffect: (transactionExecSql) =>\n settleDocumentMoveIntent({\n execSql: transactionExecSql,\n intent,\n isCurrent: input.isCurrent,\n linkedContainerIds: moved.linkedContainerIds,\n partial: moved.status === \"partial\",\n }),\n };\n\n return relinkMovedDocumentStore({\n host,\n isCurrent: input.isCurrent,\n intent,\n relinkInput,\n targetContainerId,\n });\n}\n\nasync function movePendingDocumentIntent<TRuntime>(input: {\n existingContainerId: string | null | undefined;\n host: DocumentMoveIntentSyncHost<TRuntime>;\n isCurrent: () => boolean;\n intent: DocumentMoveIntentRecord;\n onFailure: DocumentLinkSetFailureHandler;\n state: DocumentMoveIntentSyncState;\n}) {\n // Adding links keeps the content key and needs no full-history rotation proof.\n const linkOnly = input.intent.intentType === DOCUMENT_LINK_INTENT_TYPE;\n const move = (\n rotationSnapshot: Uint8Array,\n onFailure: DocumentLinkSetFailureHandler,\n ) =>\n moveRemoteContainerDocument({\n linkOnly,\n additionalLinkContainerIds: input.intent.additionalLinkContainerIds,\n removedLinkContainerIds: input.intent.removedLinkContainerIds,\n currentContainerId:\n input.intent.sourceContainerId ??\n input.existingContainerId ??\n input.intent.targetContainerId,\n documentId: input.intent.documentId,\n isCurrent: input.isCurrent,\n noteId: input.intent.localId,\n onFailure,\n replaceLinkedContainers: input.intent.replaceLinkedContainers,\n resolveProjectionUserKey: input.state.resolveProjectionUserKey,\n rotationSnapshot,\n runtime: input.state.runtime,\n targetContainerId: input.intent.targetContainerId,\n });\n if (linkOnly && !input.intent.removedLinkContainerIds?.length) {\n return move(new Uint8Array(), input.onFailure);\n }\n return moveWithRotationProof({\n ...input,\n attempt: move,\n log: (message) => input.state.runtime.util.log(message),\n });\n}\n\nasync function resolveMoveIntentPreflight(input: {\n isCreatePending: (containerId: string) => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n isCurrent: () => boolean;\n intent: DocumentMoveIntentRecord;\n state: DocumentMoveIntentSyncState;\n}): Promise<\n | { existingDocument: DocumentRecord; result?: undefined }\n | { existingDocument?: undefined; result: DocumentMoveIntentReplayResult }\n> {\n const { intent, state } = input;\n const execSql = state.runtime.infra.execSql;\n const existingDocument = await defaultDocumentsPersistence.loadDocument(\n execSql,\n intent.localId,\n );\n if (!input.isCurrent()) return { result: \"abandoned\" };\n if (!existingDocument || existingDocument.documentId !== intent.documentId) {\n await recordPendingDocumentMoveIntentError({\n blocked: true,\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: \"Document move intent references a missing local document\",\n state,\n });\n return { result: \"blocked\" };\n }\n\n for (const targetId of new Set([\n intent.targetContainerId,\n ...(intent.additionalLinkContainerIds ?? []),\n ])) {\n const targetState = state.containersById.get(targetId);\n if (!targetState) {\n await recordPendingDocumentMoveIntentError({\n blocked: true,\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message:\n \"Document move intent references a missing destination container\",\n state,\n });\n return { result: \"blocked\" };\n }\n if (input.isRemoteSyncBlocked(targetState.container.organizationId)) {\n return { result: \"blocked\" };\n }\n if (\n !hasRemoteContainerMetadataState(targetState) ||\n input.isCreatePending(targetId)\n ) {\n await recordPendingDocumentMoveIntentError({\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: \"Document move destination container is not synced yet\",\n state,\n });\n return { result: \"failed\" };\n }\n }\n return { existingDocument };\n}\n\nasync function recordRejectedDocumentMove(input: {\n failure: DocumentMoveFailureState;\n intent: DocumentMoveIntentRecord;\n isCurrent: () => boolean;\n state: DocumentMoveIntentSyncState;\n unavailable: boolean;\n}): Promise<void> {\n await recordPendingDocumentMoveIntentError({\n // A permission denial parks the intent for the access-restored signal\n // instead of replaying on every structural pass (row 7).\n denied: input.failure.sawPermissionDenial,\n documentId: input.intent.documentId,\n expectedIntentId: input.intent.id,\n expectedUpdatedAt: input.intent.updatedAt,\n isCurrent: input.isCurrent,\n message: describeRejectedDocumentMove(input.failure),\n state: input.state,\n // Terminal only after the vanished-container refresh proved the\n // destination itself gone: the intent can never commit as written and\n // nothing on this device can heal it, so it leaves the replay set instead\n // of re-issuing doomed requests every pass. The tombstone cascade\n // retargets it once hydration tears the deleted container down locally.\n // Every other vanished verdict stays pending for the next pass.\n unavailable: input.unavailable,\n });\n}\n\nfunction logSyncedDocumentMove(\n intent: DocumentMoveIntentRecord,\n state: DocumentMoveIntentSyncState,\n): void {\n state.runtime.util.log(\n `Container contents: synced queued document move ${intent.documentId}`,\n );\n}\n\nasync function settleMovedDocumentIntent<TRuntime>(input: {\n failure: DocumentMoveFailureState;\n host: DocumentMoveIntentSyncHost<TRuntime>;\n intent: DocumentMoveIntentRecord;\n isCurrent: () => boolean;\n moved: NonNullable<Awaited<ReturnType<typeof moveRemoteContainerDocument>>>;\n state: DocumentMoveIntentSyncState;\n unavailable: boolean;\n}): Promise<DocumentMoveIntentReplayResult> {\n const { intent, moved, state } = input;\n if (\n !(await persistMovedDocumentReplay({\n host: input.host,\n intent,\n isCurrent: input.isCurrent,\n moved,\n state,\n }))\n ) {\n if (!input.isCurrent()) return \"abandoned\";\n await recordPendingDocumentMoveIntentError({\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: \"Document move replay could not relink the local document\",\n state,\n });\n return \"failed\";\n }\n if (moved.status === \"partial\") {\n await recordPendingDocumentMoveIntentError({\n // An unlink refused for permissions parks like any other denied\n // move (row 7); other partials keep row 15's replay.\n denied: input.failure.sawPermissionDenial,\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: \"Remote document move partially applied; retry required\",\n state,\n // Terminal only when the refresh proved the destination itself gone\n // after the link had already landed; a vanished unlink alone stays\n // pending with its live link for the next pass to revoke.\n unavailable: input.unavailable,\n });\n return \"partial\";\n }\n\n logSyncedDocumentMove(intent, state);\n return \"moved\";\n}\n\nasync function trySyncPendingDocumentMoveIntent<TRuntime>(input: {\n host: DocumentMoveIntentSyncHost<TRuntime>;\n isCreatePending: (containerId: string) => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n isCurrent: () => boolean;\n intent: DocumentMoveIntentRecord;\n state: DocumentMoveIntentSyncState;\n}): Promise<DocumentMoveIntentReplayResult> {\n const { host, intent, state } = input;\n const available = availableDocumentLinkIntent(intent, (id) =>\n state.containersById.has(id),\n );\n const preflight = await resolveMoveIntentPreflight({\n ...input,\n intent: available.intent,\n });\n if (preflight.result !== undefined) {\n return preflight.result;\n }\n const { existingDocument } = preflight;\n\n try {\n const outcome = await moveWithVanishedContainerRefresh({\n apiClient: state.runtime.apiClient,\n attempt: (onFailure) =>\n movePendingDocumentIntent({\n existingContainerId: existingDocument.containerId,\n host,\n isCurrent: input.isCurrent,\n intent: available.intent,\n onFailure,\n state,\n }),\n execSql: state.runtime.infra.execSql,\n existingContainerId: existingDocument.containerId,\n intent: available.intent,\n isCurrent: input.isCurrent,\n });\n if (outcome === \"abandoned\" || !input.isCurrent()) return \"abandoned\";\n if (!outcome.moved) {\n await recordRejectedDocumentMove({\n failure: outcome.failure,\n intent,\n isCurrent: input.isCurrent,\n state,\n unavailable: outcome.unavailable,\n });\n return \"failed\";\n }\n return await settleMovedDocumentIntent({\n failure: outcome.failure,\n host,\n intent,\n isCurrent: input.isCurrent,\n moved: available.deferred\n ? { ...outcome.moved, status: \"partial\" }\n : outcome.moved,\n state,\n unavailable: outcome.unavailable,\n });\n } catch (error: unknown) {\n if (!input.isCurrent()) return \"abandoned\";\n await reportAndRethrowKeyingVerificationError(\n error,\n state.runtime.util.reportSecurityIncident,\n {\n objectId: intent.documentId,\n objectKind: \"document\",\n operation: \"document.move.replay\",\n },\n );\n if (!input.isCurrent()) return \"abandoned\";\n const message = errorMessage(error);\n await recordPendingDocumentMoveIntentError({\n documentId: intent.documentId,\n expectedIntentId: intent.id,\n expectedUpdatedAt: intent.updatedAt,\n isCurrent: input.isCurrent,\n message: `Failed to sync document move: ${message}`,\n state,\n });\n return \"failed\";\n }\n}\n\nexport async function syncPendingDocumentMoveIntents<TRuntime>(input: {\n host: DocumentMoveIntentSyncHost<TRuntime>;\n /** A destination whose create has not settled takes no document yet. */\n isCreatePending: (containerId: string) => boolean;\n isCurrent: () => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n state: DocumentMoveIntentSyncState;\n}): Promise<number> {\n if (!input.isCurrent()) return 0;\n const lifecycleState = input.state;\n const state = { ...lifecycleState };\n const execSql = state.runtime.infra.execSql;\n const moveIntents = new DocumentMoveIntentRepository(execSql);\n if (!deniedReplayMatchesGeneration(lifecycleState, execSql)) {\n await moveIntents.resetDeniedMoveIntents();\n if (!input.isCurrent()) return 0;\n markDeniedReplayGeneration(lifecycleState, execSql);\n }\n const pendingIntents = await moveIntents.listPendingMoveIntents();\n if (!input.isCurrent()) return 0;\n let movedCount = 0;\n\n for (const intent of pendingIntents) {\n if (!input.isCurrent()) return movedCount;\n const result = await trySyncPendingDocumentMoveIntent({\n host: input.host,\n isCreatePending: input.isCreatePending,\n isCurrent: input.isCurrent,\n isRemoteSyncBlocked: input.isRemoteSyncBlocked,\n intent,\n state,\n });\n if (result === \"abandoned\") return movedCount;\n // A \"partial\" result (link applied, unlink still pending) must not count:\n // the caller re-arms this same structural lane whenever the count is\n // positive, so a deterministically failing unlink hot-looped the pump\n // (issue #1744). The intent row stays pending; event-driven, manual, and\n // startup lane requests retry it.\n if (result === \"moved\") {\n movedCount += 1;\n }\n }\n\n return movedCount;\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { DOCUMENTS_APP_KIND } from "../../../data/documents/documentConstants.js";
2
2
  import { CONTAINER_METADATA_APP_KIND } from "../../../data/persistence/container-contents/containerContentsPersistence.js";
3
- import { sqlDocumentMoveIntentPersistence } from "../../../data/persistence/container-contents/documentMoveIntentPersistence.js";
3
+ import { DocumentMoveIntentRepository } from "../../../data/persistence/container-contents/documentMoveIntentPersistence.js";
4
4
  import { sqlDocumentsPersistence } from "../../../data/persistence/documents/documentsPersistence.js";
5
5
  import { clearDocumentSyncFailure, resetDocumentPendingUpdateRekeyBudget, } from "../../../data/persistence/documents/records/index.js";
6
6
  import { documentPlacementIntentTables, LOCAL_INTENT_LANES, } from "../../../data/sqlite/schema/index.js";
@@ -26,7 +26,7 @@ export function carriesLocalWrites(item) {
26
26
  export async function listPendingWrites(execSql) {
27
27
  await defaultContainerContentsPersistence.ensureSchema(execSql);
28
28
  await sqlDocumentsPersistence.ensureSchema(execSql);
29
- await sqlDocumentMoveIntentPersistence.ensureSchema(execSql);
29
+ await new DocumentMoveIntentRepository(execSql).ensureSchema();
30
30
  const [persisted, deferred] = await Promise.all([
31
31
  listPersistedPendingWriteCandidates(execSql),
32
32
  listDeferredPendingWriteCandidates(execSql),
@@ -59,7 +59,7 @@ export async function resetPendingWriteRetryState(execSql, input) {
59
59
  // A deliberate retry is the rate-limited signal that conditions changed:
60
60
  // a parked permission-denied move (row 7) replays once, like row 11's
61
61
  // re-key budget reset.
62
- await sqlDocumentMoveIntentPersistence.resetDeniedMoveIntents(execSql, {
62
+ await new DocumentMoveIntentRepository(execSql).resetDeniedMoveIntents({
63
63
  localId: input.localId,
64
64
  });
65
65
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,2CAA2C,CAAC;AAC/E,OAAO,EAAE,2BAA2B,EAAE,MAAM,2EAA2E,CAAC;AACxH,OAAO,EAAE,gCAAgC,EAAE,MAAM,4EAA4E,CAAC;AAC9H,OAAO,EAAE,uBAAuB,EAAE,MAAM,0DAA0D,CAAC;AACnG,OAAO,EACL,wBAAwB,EACxB,qCAAqC,GACtC,MAAM,6CAA6C,CAAC;AACrD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ACF,CAAC;IACF,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACpB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,sEAAsE;IACtE,kEAAkE;IAClE,iCAAiC;IACjC,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;AAClD,CAAC","sourcesContent":["import { DOCUMENTS_APP_KIND } from \"../../../data/documents/documentConstants\";\nimport { CONTAINER_METADATA_APP_KIND } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport { sqlDocumentMoveIntentPersistence } from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { sqlDocumentsPersistence } from \"../../../data/persistence/documents/documentsPersistence\";\nimport {\n clearDocumentSyncFailure,\n resetDocumentPendingUpdateRekeyBudget,\n} from \"../../../data/persistence/documents/records\";\nimport {\n documentPlacementIntentTables,\n LOCAL_INTENT_LANES,\n} from \"../../../data/sqlite/schema\";\nimport { documentTables } from \"../../../data/sqlite/schema/documentRecordSchema\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { ensureSqlTables } from \"../../../data/sqlite/sqlSchema\";\nimport { defaultContainerContentsPersistence } from \"../containerPersistence\";\nimport { groupPendingWriteCandidates } from \"./aggregation\";\nimport {\n hasDeferredTailScopeWork,\n listDeferredPendingWriteCandidates,\n} from \"./deferredTails\";\nimport type { PendingWriteQueueItem } from \"./pendingWritesTypes\";\nimport { listPersistedPendingWriteCandidates } from \"./sources\";\n\nexport type {\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n} from \"./pendingWritesTypes\";\n\n/**\n * Whether an item holds local work that still has to upload. A revalidation\n * item only reports a failed read and carries no local writes.\n */\nexport function carriesLocalWrites(item: PendingWriteQueueItem): boolean {\n return item.operations.some((operation) => operation.kind !== \"revalidation\");\n}\n\n/**\n * List identity-wide local state that still requires a remote write. The\n * returned diagnostic contains only navigation/display metadata and aggregate\n * counts; serialized updates, local storage keys, and upload crypto stay below\n * the workflow boundary.\n */\nexport async function listPendingWrites(\n execSql: ExecSql,\n): Promise<ReadonlyArray<PendingWriteQueueItem>> {\n await defaultContainerContentsPersistence.ensureSchema(execSql);\n await sqlDocumentsPersistence.ensureSchema(execSql);\n await sqlDocumentMoveIntentPersistence.ensureSchema(execSql);\n\n const [persisted, deferred] = await Promise.all([\n listPersistedPendingWriteCandidates(execSql),\n listDeferredPendingWriteCandidates(execSql),\n ]);\n return groupPendingWriteCandidates([...persisted, ...deferred]);\n}\n\n/**\n * Explicit manual retry for one write-queue item: reset the durable re-key\n * budget for the item's ACTUAL pending-update scope (container metadata and\n * unknown document namespaces re-key through the same recovery path as\n * ordinary documents) and clear the recorded terminal failure — the next\n * pass re-records both if they still hold. The cap protects against a\n * server driving a network-speed re-key loop; a deliberate user retry is\n * the rate-limited signal that conditions have changed (e.g. an outage that\n * burned the budget has healed). The caller re-arms the sync lanes.\n */\nexport async function resetPendingWriteRetryState(\n execSql: ExecSql,\n input: {\n localId: string;\n /** The item's `namespace` — the unrecognized documents.app_kind, if any. */\n namespace: string | null;\n objectKind: PendingWriteQueueItem[\"objectKind\"];\n },\n): Promise<void> {\n const appKind =\n input.objectKind === \"container\"\n ? CONTAINER_METADATA_APP_KIND\n : (input.namespace ??\n (input.objectKind === \"document\" ? DOCUMENTS_APP_KIND : null));\n if (appKind === null) {\n // An unknown object kind with no namespace: there is no scope to reset,\n // and guessing one could clear an unrelated scope sharing the localId.\n return;\n }\n const scope = { appKind, localId: input.localId };\n await resetDocumentPendingUpdateRekeyBudget(execSql, scope);\n if (appKind === DOCUMENTS_APP_KIND) {\n // A deliberate retry is the rate-limited signal that conditions changed:\n // a parked permission-denied move (row 7) replays once, like row 11's\n // re-key budget reset.\n await sqlDocumentMoveIntentPersistence.resetDeniedMoveIntents(execSql, {\n localId: input.localId,\n });\n }\n // Clearing the failure row is part of the re-key budget reset (edge-case\n // row 11) and only makes sense alongside queued work. A failure-only item\n // (a refused revalidation, row 13) has no queued work: its row is the\n // priming ticket that re-drives the store, so it must survive the retry\n // and clear on the next clean pass instead of vanishing with no request.\n if (await hasQueuedScopeWork(execSql, scope)) {\n await clearDocumentSyncFailure(execSql, scope);\n }\n}\n\n/**\n * Whether ANY durable outbound work exists for the scope — CRDT updates,\n * staged attachment uploads, move intents, a never-created local document, or\n * a deferred write whose only durable content is the history tail ahead of\n * its covered frontier. Mirrors the queue's own document candidate sources,\n * so \"failure-only\" here agrees with the item the panel rendered.\n */\nasync function hasQueuedScopeWork(\n execSql: ExecSql,\n scope: { appKind: string; localId: string },\n): Promise<boolean> {\n await ensureSqlTables(execSql, [\n ...documentTables,\n ...documentPlacementIntentTables,\n ]);\n const rows = await execSql(\n `SELECT 1 AS present\n WHERE EXISTS (\n SELECT 1 FROM document_history_updates pending\n WHERE pending.app_kind = ? AND pending.local_id = ?\n AND pending.update_id IS NOT NULL\n )\n OR EXISTS (\n SELECT 1 FROM document_pending_attachments attachment\n WHERE attachment.local_id = ?\n )\n OR EXISTS (\n SELECT 1 FROM local_intents intent\n WHERE intent.lane = '${LOCAL_INTENT_LANES.documentPlacement}'\n AND intent.local_id = ?\n AND intent.intent_type IN ('document.move', 'document.link')\n )\n OR EXISTS (\n SELECT 1 FROM documents stored\n WHERE stored.app_kind = ? AND stored.local_id = ?\n AND stored.document_id IS NULL\n )\n LIMIT 1`,\n [\n scope.appKind,\n scope.localId,\n scope.localId,\n scope.localId,\n scope.appKind,\n scope.localId,\n ],\n );\n if (rows.length > 0) {\n return true;\n }\n // The queue's deferred-update source has no queued rows to probe: the\n // write lives in the durable history tail, detectable only by the\n // version-vector coverage check.\n return hasDeferredTailScopeWork(execSql, scope);\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,2CAA2C,CAAC;AAC/E,OAAO,E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AM,IAAI,GAAG,MAAM,OAAO,CACxB;;;;;;;;;;;;gCAY4B,kBAAkB,CAAC,iBAAiB;;;;;;;;;aASvD,EACT;QACE,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;QACb,KAAK,CAAC,OAAO;KACd,CACF,CAAC;IACF,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACpB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,sEAAsE;IACtE,kEAAkE;IAClE,iCAAiC;IACjC,OAAO,wBAAwB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;AAClD,CAAC","sourcesContent":["import { DOCUMENTS_APP_KIND } from \"../../../data/documents/documentConstants\";\nimport { CONTAINER_METADATA_APP_KIND } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport { DocumentMoveIntentRepository } from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { sqlDocumentsPersistence } from \"../../../data/persistence/documents/documentsPersistence\";\nimport {\n clearDocumentSyncFailure,\n resetDocumentPendingUpdateRekeyBudget,\n} from \"../../../data/persistence/documents/records\";\nimport {\n documentPlacementIntentTables,\n LOCAL_INTENT_LANES,\n} from \"../../../data/sqlite/schema\";\nimport { documentTables } from \"../../../data/sqlite/schema/documentRecordSchema\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { ensureSqlTables } from \"../../../data/sqlite/sqlSchema\";\nimport { defaultContainerContentsPersistence } from \"../containerPersistence\";\nimport { groupPendingWriteCandidates } from \"./aggregation\";\nimport {\n hasDeferredTailScopeWork,\n listDeferredPendingWriteCandidates,\n} from \"./deferredTails\";\nimport type { PendingWriteQueueItem } from \"./pendingWritesTypes\";\nimport { listPersistedPendingWriteCandidates } from \"./sources\";\n\nexport type {\n PendingWriteQueueItem,\n PendingWriteQueueItemStatus,\n PendingWriteQueueObjectKind,\n PendingWriteQueueOperation,\n PendingWriteQueueOperationKind,\n PendingWriteQueueOperationStatus,\n} from \"./pendingWritesTypes\";\n\n/**\n * Whether an item holds local work that still has to upload. A revalidation\n * item only reports a failed read and carries no local writes.\n */\nexport function carriesLocalWrites(item: PendingWriteQueueItem): boolean {\n return item.operations.some((operation) => operation.kind !== \"revalidation\");\n}\n\n/**\n * List identity-wide local state that still requires a remote write. The\n * returned diagnostic contains only navigation/display metadata and aggregate\n * counts; serialized updates, local storage keys, and upload crypto stay below\n * the workflow boundary.\n */\nexport async function listPendingWrites(\n execSql: ExecSql,\n): Promise<ReadonlyArray<PendingWriteQueueItem>> {\n await defaultContainerContentsPersistence.ensureSchema(execSql);\n await sqlDocumentsPersistence.ensureSchema(execSql);\n await new DocumentMoveIntentRepository(execSql).ensureSchema();\n\n const [persisted, deferred] = await Promise.all([\n listPersistedPendingWriteCandidates(execSql),\n listDeferredPendingWriteCandidates(execSql),\n ]);\n return groupPendingWriteCandidates([...persisted, ...deferred]);\n}\n\n/**\n * Explicit manual retry for one write-queue item: reset the durable re-key\n * budget for the item's ACTUAL pending-update scope (container metadata and\n * unknown document namespaces re-key through the same recovery path as\n * ordinary documents) and clear the recorded terminal failure — the next\n * pass re-records both if they still hold. The cap protects against a\n * server driving a network-speed re-key loop; a deliberate user retry is\n * the rate-limited signal that conditions have changed (e.g. an outage that\n * burned the budget has healed). The caller re-arms the sync lanes.\n */\nexport async function resetPendingWriteRetryState(\n execSql: ExecSql,\n input: {\n localId: string;\n /** The item's `namespace` — the unrecognized documents.app_kind, if any. */\n namespace: string | null;\n objectKind: PendingWriteQueueItem[\"objectKind\"];\n },\n): Promise<void> {\n const appKind =\n input.objectKind === \"container\"\n ? CONTAINER_METADATA_APP_KIND\n : (input.namespace ??\n (input.objectKind === \"document\" ? DOCUMENTS_APP_KIND : null));\n if (appKind === null) {\n // An unknown object kind with no namespace: there is no scope to reset,\n // and guessing one could clear an unrelated scope sharing the localId.\n return;\n }\n const scope = { appKind, localId: input.localId };\n await resetDocumentPendingUpdateRekeyBudget(execSql, scope);\n if (appKind === DOCUMENTS_APP_KIND) {\n // A deliberate retry is the rate-limited signal that conditions changed:\n // a parked permission-denied move (row 7) replays once, like row 11's\n // re-key budget reset.\n await new DocumentMoveIntentRepository(execSql).resetDeniedMoveIntents({\n localId: input.localId,\n });\n }\n // Clearing the failure row is part of the re-key budget reset (edge-case\n // row 11) and only makes sense alongside queued work. A failure-only item\n // (a refused revalidation, row 13) has no queued work: its row is the\n // priming ticket that re-drives the store, so it must survive the retry\n // and clear on the next clean pass instead of vanishing with no request.\n if (await hasQueuedScopeWork(execSql, scope)) {\n await clearDocumentSyncFailure(execSql, scope);\n }\n}\n\n/**\n * Whether ANY durable outbound work exists for the scope — CRDT updates,\n * staged attachment uploads, move intents, a never-created local document, or\n * a deferred write whose only durable content is the history tail ahead of\n * its covered frontier. Mirrors the queue's own document candidate sources,\n * so \"failure-only\" here agrees with the item the panel rendered.\n */\nasync function hasQueuedScopeWork(\n execSql: ExecSql,\n scope: { appKind: string; localId: string },\n): Promise<boolean> {\n await ensureSqlTables(execSql, [\n ...documentTables,\n ...documentPlacementIntentTables,\n ]);\n const rows = await execSql(\n `SELECT 1 AS present\n WHERE EXISTS (\n SELECT 1 FROM document_history_updates pending\n WHERE pending.app_kind = ? AND pending.local_id = ?\n AND pending.update_id IS NOT NULL\n )\n OR EXISTS (\n SELECT 1 FROM document_pending_attachments attachment\n WHERE attachment.local_id = ?\n )\n OR EXISTS (\n SELECT 1 FROM local_intents intent\n WHERE intent.lane = '${LOCAL_INTENT_LANES.documentPlacement}'\n AND intent.local_id = ?\n AND intent.intent_type IN ('document.move', 'document.link')\n )\n OR EXISTS (\n SELECT 1 FROM documents stored\n WHERE stored.app_kind = ? AND stored.local_id = ?\n AND stored.document_id IS NULL\n )\n LIMIT 1`,\n [\n scope.appKind,\n scope.localId,\n scope.localId,\n scope.localId,\n scope.appKind,\n scope.localId,\n ],\n );\n if (rows.length > 0) {\n return true;\n }\n // The queue's deferred-update source has no queued rows to probe: the\n // write lives in the durable history tail, detectable only by the\n // version-vector coverage check.\n return hasDeferredTailScopeWork(execSql, scope);\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { sqlDocumentMoveIntentPersistence } from "../../../data/persistence/container-contents/documentMoveIntentPersistence.js";
1
+ import { DocumentMoveIntentRepository } from "../../../data/persistence/container-contents/documentMoveIntentPersistence.js";
2
2
  import { requestDormantMetadataRestorationSweeps } from "../../../data/persistence/container-contents/dormantMetadataSweep.js";
3
3
  import { hasRecordedTerminalSyncFailures } from "../../../data/persistence/documents/records/index.js";
4
4
  import { requestAllDomainSyncLanes, requestDomainSyncLane, } from "../../../data/sync/syncCoordinator.js";
@@ -8,6 +8,7 @@ export async function recoverOrganizationAccess(input) {
8
8
  const { domainScope, execSql, organizationId, stillCurrent, userId } = input;
9
9
  if (!stillCurrent())
10
10
  return;
11
+ const moveIntents = new DocumentMoveIntentRepository(execSql);
11
12
  // The evidence gate: re-arm only when some queued write actually
12
13
  // recorded a terminal failure. A transient denial during bootstrap
13
14
  // (e.g. a read-model 403 before grants propagate) also flips the
@@ -15,15 +16,11 @@ export async function recoverOrganizationAccess(input) {
15
16
  // A failed pass (`undefined`) proves nothing about restored access,
16
17
  // so it must not re-arm either.
17
18
  if (((await hasRecordedTerminalSyncFailures(execSql)) ||
18
- (await sqlDocumentMoveIntentPersistence.hasDeniedMoveIntents(execSql, {
19
- organizationId,
20
- }))) &&
19
+ (await moveIntents.hasDeniedMoveIntents({ organizationId }))) &&
21
20
  stillCurrent()) {
22
21
  // Parked permission-denied moves (row 7) only replay once flipped
23
22
  // back to pending; restore them before re-arming the lanes.
24
- await sqlDocumentMoveIntentPersistence.resetDeniedMoveIntents(execSql, {
25
- organizationId,
26
- });
23
+ await moveIntents.resetDeniedMoveIntents({ organizationId });
27
24
  if (stillCurrent())
28
25
  requestAllDomainSyncLanes(domainScope);
29
26
  }
@@ -1 +1 @@
1
- {"version":3,"file":"accessRestoration.js","sourceRo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BAAqB,CAAC,WAAW,EAAE,gCAAgC,CAAC,CAAC;QACvE,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { sqlDocumentMoveIntentPersistence } from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { requestDormantMetadataRestorationSweeps } from \"../../../data/persistence/container-contents/dormantMetadataSweep\";\nimport { hasRecordedTerminalSyncFailures } from \"../../../data/persistence/documents/records\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n requestAllDomainSyncLanes,\n requestDomainSyncLane,\n} from \"../../../data/sync/syncCoordinator\";\nimport { CONTAINER_CONTENTS_SYNC_LANE_KEY } from \"../syncLane\";\n\n/** Recover parked work before optional presentation hydration can fail. */\nexport async function recoverOrganizationAccess(input: {\n readonly domainScope: DomainScope;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly stillCurrent: () => boolean;\n readonly userId: string;\n}): Promise<void> {\n const { domainScope, execSql, organizationId, stillCurrent, userId } = input;\n if (!stillCurrent()) return;\n // The evidence gate: re-arm only when some queued write actually\n // recorded a terminal failure. A transient denial during bootstrap\n // (e.g. a read-model 403 before grants propagate) also flips the\n // denied flag, and re-arming then would race the startup sync passes.\n // A failed pass (`undefined`) proves nothing about restored access,\n // so it must not re-arm either.\n if (\n ((await hasRecordedTerminalSyncFailures(execSql)) ||\n (await sqlDocumentMoveIntentPersistence.hasDeniedMoveIntents(execSql, {\n organizationId,\n }))) &&\n stillCurrent()\n ) {\n // Parked permission-denied moves (row 7) only replay once flipped\n // back to pending; restore them before re-arming the lanes.\n await sqlDocumentMoveIntentPersistence.resetDeniedMoveIntents(execSql, {\n organizationId,\n });\n if (stillCurrent()) requestAllDomainSyncLanes(domainScope);\n }\n // Keep dormant cleanup independent from the write-lane evidence gate,\n // but run it afterward so a SQLite failure cannot suppress the\n // pre-existing denied-write and move-intent recovery signal.\n if (stillCurrent()) {\n const requestedDormantSweepCount =\n await requestDormantMetadataRestorationSweeps(execSql, {\n requesterUserId: userId,\n });\n if (requestedDormantSweepCount > 0 && stillCurrent()) {\n requestDomainSyncLane(domainScope, CONTAINER_CONTENTS_SYNC_LANE_KEY);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"accessRestoration.js","sourceRoot":"","sources":["accessRestoration.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,4BAA4B,EAAE,MAAM,4EAA4E,CAAC;AAC1H,OAAO,EAAE,uCAAuC,EAAE,MAAM,mEAAmE,CAAC;AAC5H,OAAO,EAAE,+BAA+B,EAAE,MAAM,6CAA6C,CAAC;AAG9F,OAAO,EACL,yBAAyB,EACzB,qBAAqB,GACtB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,gCAAgC,EAAE,MAAM,aAAa,CAAC;AAE/D,2EAA2E;AAC3E,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAAC,KAM/C;IACC,MAAM,EAAE,WAAW,EAAE,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;IAC7E,IAAI,CAAC,YAAY,EAAE;QAAE,OAAO;IAC5B,MAAM,WAAW,GAAG,IAAI,4BAA4B,CAAC,OAAO,CAAC,CAAC;IAC9D,iEAAiE;IACjE,mEAAmE;IACnE,iEAAiE;IACjE,sEAAsE;IACtE,oEAAoE;IACpE,gCAAgC;IAChC,IACE,CAAC,CAAC,MAAM,+BAA+B,CAAC,OAAO,CAAC,CAAC;QAC/C,CAAC,MAAM,WAAW,CAAC,oBAAoB,CAAC,EAAE,cAAc,EAAE,CAAC,CAAC,CAAC;QAC/D,YAAY,EAAE,EACd,CAAC;QACD,kEAAkE;QAClE,4DAA4D;QAC5D,MAAM,WAAW,CAAC,sBAAsB,CAAC,EAAE,cAAc,EAAE,CAAC,CAAC;QAC7D,IAAI,YAAY,EAAE;YAAE,yBAAyB,CAAC,WAAW,CAAC,CAAC;IAC7D,CAAC;IACD,sEAAsE;IACtE,+DAA+D;IAC/D,6DAA6D;IAC7D,IAAI,YAAY,EAAE,EAAE,CAAC;QACnB,MAAM,0BAA0B,GAC9B,MAAM,uCAAuC,CAAC,OAAO,EAAE;YACrD,eAAe,EAAE,MAAM;SACxB,CAAC,CAAC;QACL,IAAI,0BAA0B,GAAG,CAAC,IAAI,YAAY,EAAE,EAAE,CAAC;YACrD,qBAAqB,CAAC,WAAW,EAAE,gCAAgC,CAAC,CAAC;QACvE,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { DocumentMoveIntentRepository } from \"../../../data/persistence/container-contents/documentMoveIntentPersistence\";\nimport { requestDormantMetadataRestorationSweeps } from \"../../../data/persistence/container-contents/dormantMetadataSweep\";\nimport { hasRecordedTerminalSyncFailures } from \"../../../data/persistence/documents/records\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n requestAllDomainSyncLanes,\n requestDomainSyncLane,\n} from \"../../../data/sync/syncCoordinator\";\nimport { CONTAINER_CONTENTS_SYNC_LANE_KEY } from \"../syncLane\";\n\n/** Recover parked work before optional presentation hydration can fail. */\nexport async function recoverOrganizationAccess(input: {\n readonly domainScope: DomainScope;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly stillCurrent: () => boolean;\n readonly userId: string;\n}): Promise<void> {\n const { domainScope, execSql, organizationId, stillCurrent, userId } = input;\n if (!stillCurrent()) return;\n const moveIntents = new DocumentMoveIntentRepository(execSql);\n // The evidence gate: re-arm only when some queued write actually\n // recorded a terminal failure. A transient denial during bootstrap\n // (e.g. a read-model 403 before grants propagate) also flips the\n // denied flag, and re-arming then would race the startup sync passes.\n // A failed pass (`undefined`) proves nothing about restored access,\n // so it must not re-arm either.\n if (\n ((await hasRecordedTerminalSyncFailures(execSql)) ||\n (await moveIntents.hasDeniedMoveIntents({ organizationId }))) &&\n stillCurrent()\n ) {\n // Parked permission-denied moves (row 7) only replay once flipped\n // back to pending; restore them before re-arming the lanes.\n await moveIntents.resetDeniedMoveIntents({ organizationId });\n if (stillCurrent()) requestAllDomainSyncLanes(domainScope);\n }\n // Keep dormant cleanup independent from the write-lane evidence gate,\n // but run it afterward so a SQLite failure cannot suppress the\n // pre-existing denied-write and move-intent recovery signal.\n if (stillCurrent()) {\n const requestedDormantSweepCount =\n await requestDormantMetadataRestorationSweeps(execSql, {\n requesterUserId: userId,\n });\n if (requestedDormantSweepCount > 0 && stillCurrent()) {\n requestDomainSyncLane(domainScope, CONTAINER_CONTENTS_SYNC_LANE_KEY);\n }\n }\n}\n"]}