@codemem/server 0.50.0-beta.2 → 0.50.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { closeSync, existsSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { basename, dirname, isAbsolute, join, posix, resolve, win32 } from "node:path";
3
- import { ACCESS_CLEANUP_OP_TYPE, CodememConfigMutationError, CoordinatorAccountLinkError, CoordinatorReciprocalApprovalRequestChangedError, DEFAULT_TIME_WINDOW_S, FILE_CONTEXT_TRANSPORT_MAX_BYTES, LEGACY_SHARED_REVIEW_SCOPE_ID, LOCAL_DEFAULT_SCOPE_ID, LOCAL_SYNC_CAPABILITY, LOCAL_SYNC_FEATURES, LegacyTeamSetupAdditiveConvergenceError, LegacyTeamSetupDeviceRemovalsUnavailableError, LegacyTeamSetupRosterCapacityError, LocalIdentitySupersededError, MEMORY_FILTER_FIELD_TYPES, MEMORY_FILTER_NAMES, MEMORY_KIND_DESCRIPTIONS, MemoryStore, ObserverClient, PROMPT_TRANSPORT_PROTOCOL_RANGE, REMEMBER_MEMORY_KINDS, RICH_TIER_ANTHROPIC_DEFAULTS, RICH_TIER_DEFAULTS, RawEventIngestValidationError, RecipientPolicyEdgeRequestError, RecipientPolicyTeamCreateError, RecipientPolicyTeamRenameError, RemoteCoordinatorRequestError, SCOPE_MEMBERSHIP_REVOCATION_LIMITATION, SIMPLE_TIER_ANTHROPIC_DEFAULTS, SIMPLE_TIER_DEFAULTS, SYNC_AUTHORIZATION_REFRESH_HEADER, SYNC_CAPABILITY_HEADER, SYNC_FEATURES_HEADER, SYNC_SCOPE_QUERY_PARAM, VERSION, VERSION as VERSION$1, VIEWER_IDENTITY_TARGET_KEYS, VIEWER_SERVICE_DISCRIMINATOR, addSyncScopeToBoundary, analyzeProjectScopeMappingChangeGuardrails, analyzeProjectScopeMappingChangesGuardrails, analyzeProjectScopeMappingDeletionGuardrails, applyLegacyTeamSetupCompletionManifest, applyLegacyTeamSetupCompletionManifestAndReturnActivation, applyLocalIdentitySwitch, applyPeerReplicationOps, areLegacyTeamSetupCompletionPolicyFactsAdditivelyCompatible, assertNoLocalIdentityOverride, automaticRecallHealth, buildAuthHeaders, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildFilterBranchesWithContext, buildFilterClausesWithContext, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromCodexHook, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildViewerIdentityTarget, canonicalCoordinatorLegacyTeamCompletionManifestJson, canonicalKeyId, canonicalMemoryKind, canonicalRepositoryProjectIdentity, canonicalWorkspaceIdentity, captureAccountOwnerProfilePins, changeCoordinatorAccount, claimRecipientPolicyActorMutations, claimRecipientPolicyPublicationMutation, classifyRecordedSyncFailure, cleanupNonces, clearLegacyTeamSetupDeviceDecision, clonePromptPackAttempt, coerceObserverCommand, commitDeviceIdentityBindings, commitRecipientPolicyEdges, commitViewerDeviceRemoval, completeCoordinatorDeviceSetup, completeLocalIdentitySwitch, containLegacyTeamSetupCompletionConflict, convertLegacyPairingAssignments, coordinatorAdminReadiness, coordinatorArchiveGroupAction, coordinatorAuthControllerReviewAction, coordinatorCreateAddDeviceInviteAction, coordinatorCreateGroupAction, coordinatorCreateInviteAction, coordinatorCreateLegacyTeamCompletionAction, coordinatorCreateScopeAction, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorGetLegacyTeamCompletionAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListConsumedTeamInvitesAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListRemovedDevicesAction, coordinatorListReviewedRecipientInviteEvidenceAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorRenameGroupAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeDeviceAction, coordinatorRevokeScopeMembershipAction, coordinatorStatusSnapshot, coordinatorUnarchiveGroupAction, coordinatorUpdateScopeAction, countShareableProjectMemories, countUnattributedImportedProjectMemories, createCoordinatorReciprocalApproval, createRecipientPolicyTeam, decodeInvitePayload, dedupeOrderedIds, defaultSpaceScopeIdForGroup, deleteProjectScopeSettingsMapping, deriveLegacyTeamSetupCompletionManifest, detectInstallKind, deterministicPolicyTeamId, diagnoseStalePeerReceivedRows, discoverLegacyTeamCandidates, dispatchFileContextTransport, ensureDeviceIdentity, executeShareProvisioning, extractInvitePayload, extractReplicationOps, fetchPeerRemovalLookup, filterReplicationOpsForSyncWithStatus, fingerprintPublicKey, formatHostPort, friendlyDeviceName, fromJson, generateWithOpenCodeV2, getCodememConfigPath, getCodememEnvOverrideValues, getCodememEnvOverrides, getCoordinatorEnrollmentReconciliationIssueSummary, getCoordinatorGroupPreference, getEffectiveCachedScopeAuthorization, getLegacyTeamSetupDraft, getRecipientPolicyAuthorityState, getSemanticIndexDiagnostics, getSyncResetState, getUpdateStatus, ingestRawEvents, inspectFreshLegacyTeamSetupActivation, inspectLegacyTeamSetupActivation, inviteTokenDigest, isAutomaticRecallMeasurement, isCoordinatorAdminDevice, isLegacyTeamCandidateSelectable, isLegacyTeamSetupProjectMappingIdentity, isPeerTrustBindingCompatible, isProjectScopeWithdrawn, isProjectSyncEnablementError, isScopedSyncCapability, judgeDistillReport, legacyDecisionCountsAsOwner, legacyPairingAssignmentsConverted, legacyTeamCandidateId, legacyTeamCandidateProjectInventory, legacyTeamCanonicalProjectRef, legacyTeamDeviceRef, legacyTeamResolvedProjectRef, legacyTeamSetupApiErrorCode, legacyTeamSetupCompletionActorIds, legacyTeamSetupFailureCheck, linkCoordinatorAccount, listAuthorizedScopesForPeer, listCoordinatorJoinRequests, listDeviceIdentityInventory, listInboundScopeRejections, listLegacyRecipientPolicyProjections, listMaintenanceJobs, listObserverProviderOptions, listOpenCodeV2Models, listPerPeerScopeSyncState, listProjectScopeCandidates, listProjectScopeInventory, listProjectScopeSettingsMappings, listRecipientPolicyIntent, listRecipientPolicyReview, listSharingDomainSettingsScopes, loadMemorySnapshotPageForPeer, loadPrivateKey, loadPublicKey, loadReplicationOpsForPeer, loadRuntimeSigningPublicKey, lookupCoordinatorPeers, markLocalIdentitySwitchBound, markLocalIdentitySwitchNotCommitted, memoryFilterValueMatchesType, mergeAddresses, migrateRecipientPolicyIntent, mutateCodememConfigFile, negotiateSyncCapability, newPairingFiltersNeedAdmin, normalizeAddress, normalizeCoordinatorAccountLinkOrigin, normalizeCoordinatorLegacyTeamCompletionManifest, normalizeHumanPresentationName, normalizeSyncCapability, normalizeSyncFeatures, normalizeTeammateName, parseAcceptedProjectIntent, parseBootstrapExpiry, parseFileContextTransportRequest, parsePositiveMemoryId, parseReassignScopePayload, parseRecipientPolicyEdgeCommitRequest, parseStrictInteger, parseSyncScopeRequest, persistShareOperation, personalScopeGrantStatusForPeer, planShareOperation, previewDeviceIdentityBindings, previewLegacyTeamSetupActivation, previewRecipientPolicyEdges, previewRecipientPolicyOnboarding, previewRecipientPolicyOnboardingFromReviewedIntent, probeAvailableCredentials, projectMatchesFilter, projectScopeMappingSavesOnlyNarrow, projectShareLifecycle, projectWithdrawalStates, promptPackArtifactFingerprint, queryPeerRemoval, readAccountLinkDevice, readAccountOwnerAssociation, readAccountOwnerAssociationRetainedAtMs, readCodememConfigFile, readCodememConfigFileForMutation, readCompletedLocalIdentitySwitches, readCoordinatorAccountChangeCapabilities, readCoordinatorAccountLinkStatus, readCoordinatorDeviceRejoinEvents, readCoordinatorDeviceSetup, readCoordinatorRejoinDiscovery, readCoordinatorResolvedAccountOwnerReceiptStatus, readCoordinatorResolvedAccountOwnerStatus, readCoordinatorSyncConfig, readOpenLocalIdentitySwitch, readPeerSyncActivity, readRepositoryIdentitySnapshot, reassignProjectScopeInventoryProject, recipientInviteAuthoritativeIdentityId, recipientPolicyDigest, recipientReviewedIntentDigest, reconcileCoordinatorEnrollmentSnapshot, reconcileRecipientPolicyProject, reconcileShareOperationAcceptance, reconstructLegacyTeamSetupCompletionManifest, recordAutomaticRecall, recordHighestObservedDirectSignatureVersion, recordLocalIdentitySwitch, recordNonce, recordPromptPackArtifacts, recordPromptPackTerminal, recordSyncAttempt, recordSyncTransferObservation, refreshAuthorizedCoordinatorPeerTrust, refreshConfiguredScopeMembershipCache, refreshLegacyTeamCandidate, rejectInboundScopeFailures, removePairingState, removePeerFromThisDevice, removeRevokedPeers, renameRecipientPolicyTeam, replayLegacyTeamSetupActivation, repositoryIdentitiesByWorkspace, repositoryIdentityForWorkspace, requestJson, requireLegacyTeamSetupAccessDeltaWithinLimit, resolveCodememConfigPath, resolveDbPath, resolveObserverDefaultModel, resolveObserverRuntime, resolveProject, resolveProjectRoot, resolveRecipientPolicyReview, resolveRecipientPolicyReviewBulk, resolveRetireTarget, resolveVisibleScopeIds, resumeDeviceRebind, resumeProjectOnThisDevice, retireDeviceLocally, runDeviceRebind, runSyncPass, schema, scopeAuthorizationFailureReason, searchPiSessions, serializeRecipientPolicyActorMutations, serializeRecipientPolicyCoordinatorGroupMutation, serializeRecipientPolicyPublicationMutation, serializeRecipientPolicyTeamMutation, setLegacyTeamSetupDeviceAssignment, setLegacyTeamSetupDeviceDecision, setLegacyTeamSetupProjectMapping, setLocalSyncFeature, setPeerProjectFilterChecked, stopProjectOnThisDevice, summarizeInboundScopeRejections, summaryLikeSqlPredicate, supportsSyncFeature, syncScopeResetRequiredPayload, toJson, tryUpdateRetrievalDelivery, updatePeerAddresses, upsertCoordinatorGroupPreference, upsertProjectScopeSettingsMappings, validateLegacyTeamSetupCompletionManifest, validateLegacyTeamSetupCompletionManifestBinding, validateRawEvents, verifiedLocalKeyId, verifyDirectPeerSignature, verifyRecipientReviewedIntent, verifySignature, wakeRecipientPoliciesForIdentities, wakeRecipientPoliciesForProjectIdentities } from "@codemem/core";
3
+ import { ACCESS_CLEANUP_OP_TYPE, CodememConfigMutationError, CoordinatorAccountLinkError, CoordinatorReciprocalApprovalRequestChangedError, DEFAULT_TIME_WINDOW_S, FILE_CONTEXT_TRANSPORT_MAX_BYTES, LEGACY_SHARED_REVIEW_SCOPE_ID, LOCAL_DEFAULT_SCOPE_ID, LOCAL_SYNC_CAPABILITY, LOCAL_SYNC_FEATURES, LegacyTeamSetupAdditiveConvergenceError, LegacyTeamSetupDeviceRemovalsUnavailableError, LegacyTeamSetupRosterCapacityError, LocalIdentitySupersededError, MEMORY_FILTER_FIELD_TYPES, MEMORY_FILTER_NAMES, MEMORY_KIND_DESCRIPTIONS, MemoryStore, ObserverClient, PROMPT_TRANSPORT_PROTOCOL_RANGE, RECIPIENT_POLICY_SHARED_SCOPE_CODE, REMEMBER_MEMORY_KINDS, RICH_TIER_ANTHROPIC_DEFAULTS, RICH_TIER_DEFAULTS, RawEventIngestValidationError, RecipientPolicyEdgeRequestError, RecipientPolicyTeamCreateError, RecipientPolicyTeamRenameError, RemoteCoordinatorRequestError, SCOPE_MEMBERSHIP_REVOCATION_LIMITATION, SIMPLE_TIER_ANTHROPIC_DEFAULTS, SIMPLE_TIER_DEFAULTS, SYNC_AUTHORIZATION_REFRESH_HEADER, SYNC_CAPABILITY_HEADER, SYNC_FEATURES_HEADER, SYNC_SCOPE_QUERY_PARAM, VERSION, VERSION as VERSION$1, VIEWER_IDENTITY_TARGET_KEYS, VIEWER_SERVICE_DISCRIMINATOR, addSyncScopeToBoundary, analyzeProjectScopeMappingChangeGuardrails, analyzeProjectScopeMappingChangesGuardrails, analyzeProjectScopeMappingDeletionGuardrails, applyLegacyTeamSetupCompletionManifest, applyLegacyTeamSetupCompletionManifestAndReturnActivation, applyLocalIdentitySwitch, applyPeerReplicationOps, applyTeamMemberRemovals, areLegacyTeamSetupCompletionPolicyFactsAdditivelyCompatible, assertNoLocalIdentityOverride, automaticRecallHealth, buildAuthHeaders, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildFilterBranchesWithContext, buildFilterClausesWithContext, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromCodexHook, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildViewerIdentityTarget, canonicalCoordinatorLegacyTeamCompletionManifestJson, canonicalKeyId, canonicalMemoryKind, canonicalRepositoryProjectIdentity, canonicalWorkspaceIdentity, captureAccountOwnerProfilePins, changeCoordinatorAccount, claimRecipientPolicyActorMutations, claimRecipientPolicyPublicationMutation, classifyRecordedSyncFailure, cleanupNonces, clearLegacyTeamSetupDeviceDecision, clonePromptPackAttempt, coerceObserverCommand, commitDeviceIdentityBindings, commitRecipientPolicyEdges, commitTeamMemberRemoval, commitViewerDeviceRemoval, completeCoordinatorDeviceSetup, completeLocalIdentitySwitch, completeMaintenanceJob, containLegacyTeamSetupCompletionConflict, convertLegacyPairingAssignments, coordinatorAdminReadiness, coordinatorArchiveGroupAction, coordinatorAuthControllerReviewAction, coordinatorCreateAddDeviceInviteAction, coordinatorCreateGroupAction, coordinatorCreateInviteAction, coordinatorCreateLegacyTeamCompletionAction, coordinatorCreateScopeAction, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorEnabled, coordinatorGetLegacyTeamCompletionAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListConsumedTeamInvitesAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListRemovedDevicesAction, coordinatorListReviewedRecipientInviteEvidenceAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorListTeamMemberRemovalsAction, coordinatorReadTeamGroupBindingsAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorRenameGroupAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeDeviceAction, coordinatorRevokeScopeMembershipAction, coordinatorStatusCacheIdentity, coordinatorStatusSnapshot, coordinatorUnarchiveGroupAction, coordinatorUpdateScopeAction, countShareableProjectMemories, countUnattributedImportedProjectMemories, createCoordinatorReciprocalApproval, createRecipientPolicyBoundaryInspector, createRecipientPolicyTeam, decodeInvitePayload, dedupeOrderedIds, defaultSpaceScopeIdForGroup, deleteProjectScopeSettingsMapping, deriveLegacyTeamSetupCompletionManifest, detectInstallKind, deterministicPolicyTeamId, diagnoseStalePeerReceivedRows, discoverLegacyTeamCandidates, dispatchFileContextTransport, ensureDeviceIdentity, executeShareProvisioning, extractInvitePayload, extractReplicationOps, fetchPeerRemovalLookup, filterReplicationOpsForSyncWithStatus, fingerprintPublicKey, formatHostPort, friendlyDeviceName, fromJson, generateWithOpenCodeV2, getCodememConfigPath, getCodememEnvOverrideValues, getCodememEnvOverrides, getCoordinatorEnrollmentReconciliationIssueSummary, getCoordinatorGroupPreference, getEffectiveCachedScopeAuthorization, getLegacyTeamSetupDraft, getRecipientPolicyAuthorityState, getSemanticIndexDiagnostics, getSyncResetState, getUpdateStatus, ingestRawEvents, inspectFreshLegacyTeamSetupActivation, inspectLegacyTeamSetupActivation, inviteTokenDigest, isAutomaticRecallMeasurement, isCoordinatorAdminDevice, isLegacyTeamCandidateSelectable, isLegacyTeamSetupProjectMappingIdentity, isPeerTrustBindingCompatible, isProjectScopeWithdrawn, isProjectSyncEnablementError, isScopedSyncCapability, isStrictRecipientPolicyId, judgeDistillReport, legacyDecisionCountsAsOwner, legacyPairingAssignmentsConverted, legacyTeamCandidateId, legacyTeamCandidateProjectInventory, legacyTeamCanonicalProjectRef, legacyTeamDeviceRef, legacyTeamResolvedProjectRef, legacyTeamSetupApiErrorCode, legacyTeamSetupCompletionActorIds, legacyTeamSetupFailureCheck, linkCoordinatorAccount, listAuthorizedScopesForPeer, listCoordinatorJoinRequests, listDeviceIdentityInventory, listInboundScopeRejections, listLegacyRecipientPolicyProjections, listMaintenanceJobs, listObserverProviderOptions, listOpenCodeV2Models, listPerPeerScopeSyncState, listProjectScopeCandidates, listProjectScopeInventory, listProjectScopeSettingsMappings, listRecipientPolicyIntent, listRecipientPolicyReview, listSharingDomainSettingsScopes, loadMemorySnapshotPageForPeer, loadPrivateKey, loadPublicKey, loadReplicationOpsForPeer, loadRuntimeSigningPublicKey, localRemovedDeviceIds, lookupCoordinatorPeers, markLocalIdentitySwitchBound, markLocalIdentitySwitchNotCommitted, memoryFilterValueMatchesType, mergeAddresses, migrateRecipientPolicyIntent, mutateCodememConfigFile, negotiateSyncCapability, newPairingFiltersNeedAdmin, normalizeAddress, normalizeCoordinatorAccountLinkOrigin, normalizeCoordinatorLegacyTeamCompletionManifest, normalizeHumanPresentationName, normalizeSyncCapability, normalizeSyncFeatures, normalizeTeammateName, parseAcceptedProjectIntent, parseBootstrapExpiry, parseFileContextTransportRequest, parsePositiveMemoryId, parseReassignScopePayload, parseRecipientPolicyEdgeCommitRequest, parseStrictInteger, parseSyncScopeRequest, peerFacingScopeResetReason, persistShareOperation, personalScopeGrantStatusForPeer, planShareOperation, previewDeviceIdentityBindings, previewLegacyTeamSetupActivation, previewRecipientPolicyEdges, previewRecipientPolicyOnboarding, previewRecipientPolicyOnboardingFromReviewedIntent, previewTeamMemberRemoval, probeAvailableCredentials, projectMatchesFilter, projectScopeMappingSavesOnlyNarrow, projectShareLifecycle, projectWithdrawalStates, promptPackArtifactFingerprint, queryPeerRemoval, readAccountLinkDevice, readAccountOwnerAssociation, readAccountOwnerAssociationRetainedAtMs, readCodememConfigFile, readCodememConfigFileForMutation, readCompletedLocalIdentitySwitches, readCoordinatorAccountChangeCapabilities, readCoordinatorAccountLinkStatus, readCoordinatorDeviceRejoinEvents, readCoordinatorDeviceSetup, readCoordinatorRejoinDiscovery, readCoordinatorResolvedAccountOwnerReceiptStatus, readCoordinatorResolvedAccountOwnerStatus, readCoordinatorSyncConfig, readOpenLocalIdentitySwitch, readPeerSyncActivity, readRepositoryIdentitySnapshot, readViewerPidFile, reassignProjectScopeInventoryProject, recipientInviteAuthoritativeIdentityId, recipientPolicyDigest, recipientReviewedIntentDigest, reconcileCoordinatorEnrollmentSnapshot, reconcileRecipientPolicyProject, reconcileShareOperationAcceptance, reconstructLegacyTeamSetupCompletionManifest, recordAutomaticRecall, recordHighestObservedDirectSignatureVersion, recordLocalIdentitySwitch, recordNonce, recordPromptPackArtifacts, recordPromptPackTerminal, recordSyncAttempt, recordSyncTransferObservation, refreshAuthorizedCoordinatorPeerTrust, refreshConfiguredScopeMembershipCache, refreshLegacyTeamCandidate, rejectInboundScopeFailures, removePairingState, removePeerFromThisDevice, removeRevokedPeers, renameRecipientPolicyTeam, replayLegacyTeamSetupActivation, repositoryIdentitiesByWorkspace, repositoryIdentityForWorkspace, requestJson, requireLegacyTeamSetupAccessDeltaWithinLimit, resolveCodememConfigPath, resolveDbPath, resolveObserverDefaultModel, resolveObserverRuntime, resolveProject, resolveProjectRoot, resolveRecipientPolicyReview, resolveRecipientPolicyReviewBulk, resolveRetireTarget, resolveVisibleScopeIds, resumeDeviceRebind, resumeProjectOnThisDevice, retireDeviceLocally, revokePendingTeamInvitations, runDeviceRebind, runSyncPass, schema, scopeAuthorizationFailureReason, scopesWrittenByInboundOp, searchPiSessions, serializeRecipientPolicyActorMutations, serializeRecipientPolicyCoordinatorGroupMutation, serializeRecipientPolicyPublicationMutation, serializeRecipientPolicyTeamMutation, setLegacyTeamSetupDeviceAssignment, setLegacyTeamSetupDeviceDecision, setLegacyTeamSetupProjectMapping, setLocalSyncFeature, setPeerProjectFilterChecked, startMaintenanceJob, stopProjectOnThisDevice, summarizeInboundScopeRejections, summaryLikeSqlPredicate, supportsSyncFeature, syncScopeResetRequiredPayload, teamCoordinatorLinkConflicts, teamIdsForBindingRead, teamInvitationGroup, toJson, tryUpdateRetrievalDelivery, updatePeerAddresses, upsertCoordinatorGroupPreference, upsertProjectScopeSettingsMappings, validateLegacyTeamSetupCompletionManifest, validateLegacyTeamSetupCompletionManifestBinding, validateRawEvents, verifiedLocalKeyId, verifyDirectPeerSignature, verifyRecipientReviewedIntent, verifySignature, wakeRecipientPoliciesForIdentities, wakeRecipientPoliciesForProjectIdentities } from "@codemem/core";
4
4
  import { serveStatic } from "@hono/node-server/serve-static";
5
5
  import { Hono } from "hono";
6
6
  import { createCipheriv, createDecipheriv, createHash, createPrivateKey, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
@@ -1801,7 +1801,7 @@ var DEFAULTS = {
1801
1801
  observer_auth_timeout_ms: 1500,
1802
1802
  observer_auth_cache_ttl_s: 300,
1803
1803
  observer_headers: {},
1804
- observer_max_chars: 12e3,
1804
+ observer_max_chars: 24e3,
1805
1805
  pack_observation_limit: 50,
1806
1806
  pack_session_limit: 10,
1807
1807
  sync_enabled: false,
@@ -2030,6 +2030,7 @@ function applyRuntimeEffects(changedKeys, opts) {
2030
2030
  opts.getSweeper?.()?.notifyConfigChanged();
2031
2031
  applied.push("raw_events_sweeper_interval_s");
2032
2032
  }
2033
+ if (changedKeys.some((key) => key.startsWith("sync_coordinator_"))) opts.onCoordinatorConfigChanged?.();
2033
2034
  return applied;
2034
2035
  }
2035
2036
  var ConfigUpdateError = class extends Error {
@@ -3789,10 +3790,14 @@ function fileContextRoutes(getStore) {
3789
3790
  }
3790
3791
  //#endregion
3791
3792
  //#region src/routes/health.ts
3793
+ /**
3794
+ * Whether this process holds an open database connection. Answered from the connection
3795
+ * object in memory: no statement runs, so a busy or locked database, or other work on the
3796
+ * same connection, can never delay the health answer or turn it into a false failure.
3797
+ */
3792
3798
  function databaseReachable(getStore) {
3793
3799
  try {
3794
- getStore().db.pragma("schema_version", { simple: true });
3795
- return true;
3800
+ return getStore().db.open === true;
3796
3801
  } catch {
3797
3802
  return false;
3798
3803
  }
@@ -5814,7 +5819,7 @@ function validatePackRequest(value) {
5814
5819
  }
5815
5820
  function ledgerFailureStatus(reason) {
5816
5821
  if (reason === "idempotency_conflict") return 409;
5817
- if (reason === "attempt_not_found") return 422;
5822
+ if (reason === "attempt_not_found" || reason === "attempt_incomplete") return 422;
5818
5823
  if (reason === "storage_unavailable") return 503;
5819
5824
  return 400;
5820
5825
  }
@@ -6269,6 +6274,15 @@ async function advancePendingProjectSharesOperation(store, options) {
6269
6274
  var RECIPIENT_POLICY_MAINTENANCE_MAX_LIMIT = 10;
6270
6275
  var RECIPIENT_POLICY_MAINTENANCE_DEFAULT_LIMIT = 3;
6271
6276
  var RECIPIENT_POLICY_MAINTENANCE_BACKOFF_MS = 6e4;
6277
+ /**
6278
+ * A legacy Project in a shared multi-Project scope gets the same answer on every attempt until
6279
+ * its scope mapping or the scope's Projects change, so it is not retried on a timer. A wake
6280
+ * (which clears last_attempt_at) still runs it. The check reads only local mappings and scopes:
6281
+ * a coordinator refresh that changes the scope updates those rows, and the next check sees it.
6282
+ */
6283
+ function waitsForSharedScopeChange(authority, projectId, boundaryBlocker) {
6284
+ return authority.authority_state === "legacy" && authority.safe_error_code === RECIPIENT_POLICY_SHARED_SCOPE_CODE && boundaryBlocker(projectId) === RECIPIENT_POLICY_SHARED_SCOPE_CODE;
6285
+ }
6272
6286
  function recipientPolicyMaintenanceCandidates(store, retryBefore, limit) {
6273
6287
  const repositoryIdentities = repositoryIdentitiesByWorkspace(store.db);
6274
6288
  const canonicalize = (projectId) => canonicalRepositoryProjectIdentity(repositoryIdentities, projectId);
@@ -6291,9 +6305,12 @@ function recipientPolicyMaintenanceCandidates(store, retryBefore, limit) {
6291
6305
  }
6292
6306
  if (String(row.last_attempt_at ?? "") > String(current.last_attempt_at ?? "")) authorityByProject.set(projectId, row);
6293
6307
  }
6308
+ const boundaryBlocker = createRecipientPolicyBoundaryInspector(store.db);
6294
6309
  return [...new Set(projectIds.map((row) => canonicalize(row.canonical_project_identity)))].filter((projectId) => {
6295
6310
  const authority = authorityByProject.get(projectId);
6296
- return authority == null || authority.last_attempt_at == null || authority.safe_error_code == null && authority.authority_state !== "active" || authority.last_attempt_at <= retryBefore;
6311
+ if (authority == null || authority.last_attempt_at == null) return true;
6312
+ if (waitsForSharedScopeChange(authority, projectId, boundaryBlocker)) return false;
6313
+ return authority.safe_error_code == null && authority.authority_state !== "active" || authority.last_attempt_at <= retryBefore;
6297
6314
  }).toSorted((left, right) => {
6298
6315
  const leftAttempt = authorityByProject.get(left)?.last_attempt_at;
6299
6316
  const rightAttempt = authorityByProject.get(right)?.last_attempt_at;
@@ -6502,6 +6519,45 @@ function overallSyncHealth(peers, options) {
6502
6519
  };
6503
6520
  }
6504
6521
  //#endregion
6522
+ //#region src/application/background-refresh.ts
6523
+ var entries = /* @__PURE__ */ new Map();
6524
+ function maxAge(setting, value, refreshedAtMs) {
6525
+ return typeof setting === "number" ? setting : setting(value, refreshedAtMs);
6526
+ }
6527
+ /**
6528
+ * The current value for `key`, starting a single background refresh when it is
6529
+ * missing, older than `maxAgeMs`, or loaded for another version.
6530
+ */
6531
+ function readInBackground(options) {
6532
+ const now = options.now ?? Date.now;
6533
+ const version = options.version ?? "";
6534
+ const entry = entries.get(options.key) ?? {
6535
+ value: null,
6536
+ refreshedAtMs: null,
6537
+ version,
6538
+ inFlight: null,
6539
+ error: null
6540
+ };
6541
+ entries.set(options.key, entry);
6542
+ if ((entry.refreshedAtMs == null || entry.version !== version || now() - entry.refreshedAtMs >= maxAge(options.maxAgeMs, entry.value, entry.refreshedAtMs)) && !entry.inFlight) entry.inFlight = options.load().then((value) => {
6543
+ entry.value = value;
6544
+ entry.version = version;
6545
+ entry.error = null;
6546
+ entry.refreshedAtMs = now();
6547
+ }).catch((error) => {
6548
+ entry.error = error instanceof Error ? error.message : String(error);
6549
+ }).finally(() => {
6550
+ entry.inFlight = null;
6551
+ });
6552
+ return {
6553
+ value: entry.value,
6554
+ refreshedAt: entry.refreshedAtMs == null ? null : new Date(entry.refreshedAtMs).toISOString(),
6555
+ ageMs: entry.refreshedAtMs == null ? null : Math.max(0, now() - entry.refreshedAtMs),
6556
+ refreshing: entry.inFlight !== null,
6557
+ error: entry.error
6558
+ };
6559
+ }
6560
+ //#endregion
6505
6561
  //#region src/application/sync-status.ts
6506
6562
  var SAFE_RUNTIME_DETAILS = {
6507
6563
  starting: "Running initial sync in background",
@@ -6751,13 +6807,107 @@ function applyDerivedDaemonState(base, peers, attempts, failedPeerIds, statusBlo
6751
6807
  base.statusPayload.daemon_state = state;
6752
6808
  statusBlock.daemon_state = state;
6753
6809
  }
6754
- async function readJoinRequests(input, config) {
6755
- if (!input.includeJoinRequests || !input.showDiagnostics || !config.syncCoordinatorAdminSecret) return [];
6756
- try {
6757
- return await listCoordinatorJoinRequests(config);
6758
- } catch {
6759
- return [];
6810
+ /** How long a coordinator answer is served before a background refresh starts. */
6811
+ var COORDINATOR_STATUS_MAX_AGE_MS = 3e4;
6812
+ function discoveredDevices(snapshot) {
6813
+ return Array.isArray(snapshot.discovered_devices) ? snapshot.discovered_devices : [];
6814
+ }
6815
+ function expiresAtMs(device) {
6816
+ const parsed = Date.parse(String(device.expires_at ?? ""));
6817
+ return Number.isFinite(parsed) ? parsed : null;
6818
+ }
6819
+ /**
6820
+ * How long one coordinator answer is served, matching the coordinator runtime's own
6821
+ * cache. Answers that need another try are refreshed on the next read: an unenrolled
6822
+ * device, or a failed peer or approval lookup. Others are refreshed after 30 seconds,
6823
+ * or sooner when a fresh peer's presence expires.
6824
+ */
6825
+ function coordinatorStatusMaxAgeMs(snapshot, refreshedAtMs) {
6826
+ if (snapshot.presence_status === "not_enrolled" || Boolean(snapshot.lookup_error) || Boolean(snapshot.reciprocal_approval_error)) return 0;
6827
+ let deadline = refreshedAtMs + COORDINATOR_STATUS_MAX_AGE_MS;
6828
+ for (const device of discoveredDevices(snapshot)) {
6829
+ const expiry = device.stale ? null : expiresAtMs(device);
6830
+ if (expiry !== null) deadline = Math.min(deadline, expiry);
6760
6831
  }
6832
+ return Math.max(0, deadline - refreshedAtMs);
6833
+ }
6834
+ /**
6835
+ * Marks peers whose presence expired since the answer was fetched as stale, so a read
6836
+ * served while the refresh runs never shows an expired peer as fresh.
6837
+ */
6838
+ function withExpiredPeersStale(snapshot, nowMs) {
6839
+ const devices = discoveredDevices(snapshot);
6840
+ const expired = (device) => {
6841
+ const expiry = expiresAtMs(device);
6842
+ return !device.stale && expiry !== null && expiry <= nowMs;
6843
+ };
6844
+ if (!devices.some(expired)) return snapshot;
6845
+ const served = devices.map((device) => expired(device) ? {
6846
+ ...device,
6847
+ stale: true
6848
+ } : device);
6849
+ const stale = served.filter((device) => device.stale).length;
6850
+ return {
6851
+ ...snapshot,
6852
+ discovered_devices: served,
6853
+ fresh_peer_count: served.length - stale,
6854
+ stale_peer_count: stale
6855
+ };
6856
+ }
6857
+ /** The coordinator fields known without asking it, shown until the first answer arrives. */
6858
+ function localCoordinatorSnapshot(config) {
6859
+ return {
6860
+ enabled: true,
6861
+ configured: true,
6862
+ sync_enabled: config.syncEnabled,
6863
+ coordinator_url: config.syncCoordinatorUrl,
6864
+ groups: config.syncCoordinatorGroups,
6865
+ presence_status: "unknown",
6866
+ presence_error: null,
6867
+ advertised_addresses: [],
6868
+ fresh_peer_count: 0,
6869
+ stale_peer_count: 0,
6870
+ discovered_peer_count: 0,
6871
+ discovered_devices: []
6872
+ };
6873
+ }
6874
+ /** When the served answer was fetched, so readers can tell how current it is. */
6875
+ function refreshFields(value) {
6876
+ return {
6877
+ status_refreshed_at: value.refreshedAt,
6878
+ status_age_ms: value.ageMs,
6879
+ status_refreshing: value.refreshing,
6880
+ status_refresh_error: value.error
6881
+ };
6882
+ }
6883
+ /**
6884
+ * The coordinator status, from memory. Asking the coordinator takes several network
6885
+ * round trips and a write transaction, so a background task refreshes the answer and
6886
+ * this read never waits for it.
6887
+ */
6888
+ async function readCoordinatorStatus(input, base) {
6889
+ const { config } = base;
6890
+ if (!coordinatorEnabled(config)) return coordinatorStatusSnapshot(input.store, config);
6891
+ const identity = coordinatorStatusCacheIdentity(input.store, config);
6892
+ const cached = readInBackground({
6893
+ key: `coordinator-status|${identity.key}`,
6894
+ version: String(identity.generation),
6895
+ maxAgeMs: (snapshot, refreshedAtMs) => Math.min(coordinatorStatusMaxAgeMs(snapshot, refreshedAtMs), identity.presenceRenewalMs),
6896
+ load: () => coordinatorStatusSnapshot(input.store, config)
6897
+ });
6898
+ return {
6899
+ ...cached.value ? withExpiredPeersStale(cached.value, Date.now()) : localCoordinatorSnapshot(config),
6900
+ paired_peer_count: Number(base.statusPayload.peer_count ?? 0),
6901
+ ...refreshFields(cached)
6902
+ };
6903
+ }
6904
+ function readJoinRequests(input, config) {
6905
+ if (!input.includeJoinRequests || !input.showDiagnostics || !config.syncCoordinatorAdminSecret) return [];
6906
+ return readInBackground({
6907
+ key: `coordinator-join-requests|${input.store.dbPath}|${config.syncCoordinatorUrl}|${config.syncCoordinatorGroups.join(",")}`,
6908
+ maxAgeMs: COORDINATOR_STATUS_MAX_AGE_MS,
6909
+ load: () => listCoordinatorJoinRequests(config)
6910
+ }).value ?? [];
6761
6911
  }
6762
6912
  function addSyncHealth(base, peers, status) {
6763
6913
  const health = overallSyncHealth(peers.items, {
@@ -6775,7 +6925,7 @@ function markPeerFailures(peers, failedPeerIds) {
6775
6925
  }
6776
6926
  async function buildSyncStatusResponse(input) {
6777
6927
  const base = readBaseStatus(input);
6778
- const coordinatorSnapshot = await coordinatorStatusSnapshot(input.store, base.config);
6928
+ const coordinatorSnapshot = await readCoordinatorStatus(input, base);
6779
6929
  const coordinator = traceSync("coordinator", () => input.operations.redactCoordinatorStatus(coordinatorSnapshot, input.showDiagnostics));
6780
6930
  const peers = readPeerStatus(input, base.localDeviceId);
6781
6931
  const attempts = readAttemptStatus(input);
@@ -6794,7 +6944,7 @@ async function buildSyncStatusResponse(input) {
6794
6944
  const legacyReview = traceSync("legacySharedReview", () => input.operations.legacySharedReviewSummary(input.store));
6795
6945
  const sharingReview = traceSync("sharingReview", () => input.store.sharingReviewSummary(input.project));
6796
6946
  const recipientPolicyReconciliation = traceSync("recipientPolicyReconciliation", () => input.operations.listRecipientPolicyReconciliationStatus(input.store));
6797
- const joinRequests = await readJoinRequests(input, base.config);
6947
+ const joinRequests = readJoinRequests(input, base.config);
6798
6948
  applyDerivedDaemonState(base, peers, attempts, failedPeerIds, statusBlock);
6799
6949
  const syncHealth = addSyncHealth(base, peers, statusBlock);
6800
6950
  const response = {
@@ -7121,6 +7271,127 @@ function deviceRetireRoutes(getStore) {
7121
7271
  function deviceRoutes(getStore) {
7122
7272
  return new Hono().route("/", deviceRenameRoutes(getStore)).route("/", deviceRetireRoutes(getStore));
7123
7273
  }
7274
+ var NOTHING_FAILED = {
7275
+ failedGroups: 0,
7276
+ skippedGroups: 0,
7277
+ errorCode: null
7278
+ };
7279
+ var BackgroundTeamSetupReconciliation = class {
7280
+ options;
7281
+ now;
7282
+ refreshAfterMs;
7283
+ staleAfterMs;
7284
+ lastGood = null;
7285
+ lastAttemptAtMs = null;
7286
+ lastErrorCode = null;
7287
+ lastAssessment = NOTHING_FAILED;
7288
+ retryTimer = null;
7289
+ inFlight = null;
7290
+ rerun = false;
7291
+ timer = null;
7292
+ constructor(options) {
7293
+ this.options = options;
7294
+ this.now = options.now ?? Date.now;
7295
+ this.refreshAfterMs = options.refreshAfterMs ?? 3e4;
7296
+ this.staleAfterMs = options.staleAfterMs ?? 3e5;
7297
+ }
7298
+ read() {
7299
+ const due = this.lastAttemptAtMs === null || this.now() - this.lastAttemptAtMs >= this.refreshAfterMs;
7300
+ if (!this.inFlight && due) this.refresh();
7301
+ return {
7302
+ result: this.lastGood?.result ?? null,
7303
+ status: this.status()
7304
+ };
7305
+ }
7306
+ refresh() {
7307
+ if (this.inFlight) {
7308
+ this.rerun = true;
7309
+ return this.inFlight;
7310
+ }
7311
+ this.inFlight = this.runPasses().finally(() => {
7312
+ this.inFlight = null;
7313
+ });
7314
+ return this.inFlight;
7315
+ }
7316
+ startPeriodic(intervalMs) {
7317
+ if (this.timer) return;
7318
+ this.refresh();
7319
+ this.timer = setInterval(() => void this.refresh(), intervalMs);
7320
+ this.timer.unref?.();
7321
+ }
7322
+ stop() {
7323
+ if (this.timer) clearInterval(this.timer);
7324
+ if (this.retryTimer) clearTimeout(this.retryTimer);
7325
+ this.timer = null;
7326
+ this.retryTimer = null;
7327
+ }
7328
+ async settle() {
7329
+ while (this.inFlight) await this.inFlight;
7330
+ }
7331
+ async runPasses() {
7332
+ do {
7333
+ this.rerun = false;
7334
+ await this.pass();
7335
+ } while (this.rerun);
7336
+ }
7337
+ async pass() {
7338
+ try {
7339
+ const result = await this.options.run(this.lastGood?.result ?? null);
7340
+ this.lastGood = {
7341
+ result,
7342
+ checkedAtMs: this.now()
7343
+ };
7344
+ this.lastAssessment = this.options.assess?.(result) ?? NOTHING_FAILED;
7345
+ this.lastErrorCode = this.lastAssessment.errorCode;
7346
+ if (this.lastAssessment.skippedGroups > 0) this.retrySkippedSoon();
7347
+ } catch (error) {
7348
+ this.lastErrorCode = this.options.errorCode(error);
7349
+ } finally {
7350
+ this.lastAttemptAtMs = this.now();
7351
+ }
7352
+ try {
7353
+ this.options.record?.({
7354
+ ok: this.lastErrorCode === null,
7355
+ checkedAtMs: this.lastGood?.checkedAtMs ?? null,
7356
+ errorCode: this.lastErrorCode
7357
+ });
7358
+ } catch {}
7359
+ }
7360
+ /** One delayed pass for groups skipped because a route held them. */
7361
+ retrySkippedSoon() {
7362
+ if (this.retryTimer) return;
7363
+ this.retryTimer = setTimeout(() => {
7364
+ this.retryTimer = null;
7365
+ this.refresh();
7366
+ }, this.options.retryDelayMs ?? 5e3);
7367
+ this.retryTimer.unref?.();
7368
+ }
7369
+ status() {
7370
+ const lastGood = this.lastGood;
7371
+ if (!lastGood) return {
7372
+ state: "never",
7373
+ refreshing: this.inFlight !== null,
7374
+ checked_at: null,
7375
+ age_ms: null,
7376
+ error_code: this.lastErrorCode,
7377
+ failed_groups: 0,
7378
+ skipped_groups: 0
7379
+ };
7380
+ const ageMs = Math.max(0, this.now() - lastGood.checkedAtMs);
7381
+ return {
7382
+ state: this.lastErrorCode !== null || ageMs >= this.staleAfterMs ? "stale" : "current",
7383
+ refreshing: this.inFlight !== null,
7384
+ checked_at: new Date(lastGood.checkedAtMs).toISOString(),
7385
+ age_ms: ageMs,
7386
+ error_code: this.lastErrorCode,
7387
+ failed_groups: this.lastAssessment.failedGroups,
7388
+ skipped_groups: this.lastAssessment.skippedGroups
7389
+ };
7390
+ }
7391
+ };
7392
+ function createTeamSetupReconciliation(options) {
7393
+ return new BackgroundTeamSetupReconciliation(options);
7394
+ }
7124
7395
  //#endregion
7125
7396
  //#region src/routes/team-setup-view.ts
7126
7397
  var enabled = {
@@ -7288,9 +7559,17 @@ function claimCandidateMutation(db, candidateRef) {
7288
7559
  function candidateMutationSettled(db, candidateRef) {
7289
7560
  return activeCandidateMutations.get(db)?.get(candidateRef) ?? Promise.resolve();
7290
7561
  }
7562
+ /**
7563
+ * Candidates whose mutation a background pass skipped because a draft or finish
7564
+ * route held the claim. The pass retries them instead of reporting a failure.
7565
+ */
7566
+ var skippedCandidateMutations = new AsyncLocalStorage();
7291
7567
  async function runCandidateMutation(db, candidateRef, operation) {
7292
7568
  const release = claimCandidateMutation(db, candidateRef);
7293
- if (!release) return false;
7569
+ if (!release) {
7570
+ skippedCandidateMutations.getStore()?.add(candidateRef);
7571
+ return false;
7572
+ }
7294
7573
  try {
7295
7574
  await operation();
7296
7575
  return true;
@@ -7314,8 +7593,19 @@ function completionFailureHandlers(options) {
7314
7593
  reportFailure
7315
7594
  };
7316
7595
  }
7596
+ /**
7597
+ * The group's Team member removals could not be read, so a completion is not
7598
+ * applied in this pass: it might make a removed person a member again on a
7599
+ * machine that has not recorded the removal. Nothing diverged.
7600
+ */
7601
+ var TeamMemberRemovalsUnavailableError = class extends Error {
7602
+ constructor(cause) {
7603
+ super("team_member_removals_unavailable", cause === void 0 ? void 0 : { cause });
7604
+ this.name = "TeamMemberRemovalsUnavailableError";
7605
+ }
7606
+ };
7317
7607
  function isNonDivergentApplyFailure(error) {
7318
- return error instanceof LegacyTeamSetupAdditiveConvergenceError || error instanceof LegacyTeamSetupDeviceRemovalsUnavailableError;
7608
+ return error instanceof LegacyTeamSetupAdditiveConvergenceError || error instanceof LegacyTeamSetupDeviceRemovalsUnavailableError || error instanceof TeamMemberRemovalsUnavailableError;
7319
7609
  }
7320
7610
  function completionConflictError(cause) {
7321
7611
  return new Error("team_setup_completion_conflict", { cause });
@@ -7336,7 +7626,9 @@ function groupCompletionFailureHandler(groups, handleFailure) {
7336
7626
  }
7337
7627
  /** The safe cause behind a retryable completion failure, when one is known. */
7338
7628
  function completionFailureReason(error) {
7339
- return errorChain(error).some((item) => item instanceof LegacyTeamSetupDeviceRemovalsUnavailableError) ? "device_removals_unavailable" : void 0;
7629
+ const chain = errorChain(error);
7630
+ if (chain.some((item) => item instanceof LegacyTeamSetupDeviceRemovalsUnavailableError)) return "device_removals_unavailable";
7631
+ if (chain.some((item) => item instanceof TeamMemberRemovalsUnavailableError)) return "team_member_removals_unavailable";
7340
7632
  }
7341
7633
  function completionBlocker(error) {
7342
7634
  const code = apiErrorCode(new Error(completionApiError(error)));
@@ -7366,19 +7658,41 @@ function summaryReconciliationOptions(blockingErrors) {
7366
7658
  }
7367
7659
  };
7368
7660
  }
7369
- function lookupPeerRemovalsAsDaemon(store, config) {
7661
+ /**
7662
+ * The daemon's signed lookup, asked with this device's existing identity. A
7663
+ * reconciliation never creates or repairs signing keys: with no usable identity
7664
+ * the lookup is reported unavailable, which keeps every pairing.
7665
+ */
7666
+ async function lookupPeerRemovalsAsDaemon(store, config) {
7370
7667
  const keysDir = process.env.CODEMEM_KEYS_DIR?.trim() || void 0;
7371
- const [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir });
7668
+ const rows = store.db.prepare("SELECT device_id FROM sync_device LIMIT 2").pluck().all();
7669
+ const localDeviceId = rows.length === 1 && typeof rows[0] === "string" ? rows[0] : null;
7670
+ if (!localDeviceId || !loadRuntimeSigningPublicKey(store.db, {
7671
+ deviceId: localDeviceId,
7672
+ keysDir
7673
+ })) return unavailablePeerRemovalLookup();
7372
7674
  return fetchPeerRemovalLookup(store, config, {
7373
7675
  localDeviceId,
7374
7676
  keysDir
7375
7677
  });
7376
7678
  }
7679
+ function unavailablePeerRemovalLookup() {
7680
+ return {
7681
+ status: "failed",
7682
+ revoked: [],
7683
+ removed: [],
7684
+ enrolled: [],
7685
+ removalSeq: null,
7686
+ generation: null,
7687
+ removedFromGroups: []
7688
+ };
7689
+ }
7377
7690
  var defaultCompletionDependencies = {
7378
7691
  create: coordinatorCreateLegacyTeamCompletionAction,
7379
7692
  get: coordinatorGetLegacyTeamCompletionAction,
7380
7693
  list: coordinatorListLegacyTeamCompletionsAction,
7381
7694
  listRemovals: coordinatorListRemovedDevicesAction,
7695
+ listTeamMemberRemovals: coordinatorListTeamMemberRemovalsAction,
7382
7696
  lookupPeerRemovals: lookupPeerRemovalsAsDaemon
7383
7697
  };
7384
7698
  var defaultSnapshotLoaderDependencies = {
@@ -7749,43 +8063,267 @@ function blockedCandidateSummary(store, group, blocker) {
7749
8063
  unresolvedProjectCount: 0
7750
8064
  };
7751
8065
  }
7752
- function pendingCandidateSummaries(store, groups, blockingErrors) {
7753
- const pending = readPureCandidateViews(store, groups.filter((group) => !blockingErrors.has(legacyTeamCandidateId(group.coordinatorId, group.groupId)))).map(candidateSummary).filter((candidate) => candidate.status !== "ready");
7754
- const blocked = groups.flatMap((group) => {
7755
- const error = blockingErrors.get(legacyTeamCandidateId(group.coordinatorId, group.groupId));
7756
- return error ? [blockedCandidateSummary(store, group, error)] : [];
8066
+ var TEAM_SETUP_RECONCILIATION_JOB = "team_setup_reconciliation";
8067
+ /**
8068
+ * One background pass, on fresh evidence only: it loads the roster from the
8069
+ * coordinator, creates drafts for groups that have no local setup at all, then
8070
+ * reads completions and removals. Only after that, for each group that neither
8071
+ * failed nor was skipped, it rediscovers groups with a local completion, the
8072
+ * step that can restore setup-owned Project recipients. Every discovery runs
8073
+ * under the candidate claim, and none runs on a cached roster or after a failed
8074
+ * removal read.
8075
+ */
8076
+ async function runSummaryReconciliation(store, dependencies, previous) {
8077
+ dependencies.loadSnapshots.invalidate();
8078
+ const groups = await dependencies.loadSnapshots();
8079
+ requireBoundedSnapshots(groups);
8080
+ await Promise.all(groups.map((group) => candidateMutationSettled(store.db, summaryCandidateRef(group))));
8081
+ const blockers = /* @__PURE__ */ new Map();
8082
+ const skipped = /* @__PURE__ */ new Set();
8083
+ const views = /* @__PURE__ */ new Map();
8084
+ for (const group of groups) {
8085
+ if (!hasNoLocalSetup(store, summaryCandidateRef(group))) continue;
8086
+ await discoverAfterReconciliation(store, group, dependencies, {
8087
+ views,
8088
+ skipped
8089
+ });
8090
+ }
8091
+ await skippedCandidateMutations.run(skipped, () => dependencies.reconcile(store, groups, summaryReconciliationOptions(blockers)));
8092
+ for (const group of groups) {
8093
+ const candidateRef = summaryCandidateRef(group);
8094
+ if (blockers.has(candidateRef) || skipped.has(candidateRef) || views.has(candidateRef)) continue;
8095
+ let removals = null;
8096
+ if (hasRepairableSetupTeam(store, candidateRef)) {
8097
+ const evidence = await dependencies.readRemovalsForRepair(group);
8098
+ if (evidence.status === "failed") blockers.set(candidateRef, evidence.blocker);
8099
+ if (evidence.status !== "read") continue;
8100
+ removals = evidence;
8101
+ }
8102
+ await discoverAfterReconciliation(store, group, dependencies, {
8103
+ views,
8104
+ skipped
8105
+ }, () => removals ? applyRemovalsBeforeRepair(store, group, removals) : true);
8106
+ }
8107
+ return carrySkippedGroups({
8108
+ groups,
8109
+ views,
8110
+ blockers,
8111
+ skipped
8112
+ }, previous);
8113
+ }
8114
+ /**
8115
+ * Whether rediscovering this candidate can restore setup recipients: core repairs
8116
+ * them only for the setup's Team while it is active, so this is the same check.
8117
+ */
8118
+ function hasRepairableSetupTeam(store, candidateRef) {
8119
+ return Boolean(store.db.prepare("SELECT 1 FROM policy_teams WHERE team_id = ? AND status = 'active' LIMIT 1").pluck().get(deterministicPolicyTeamId(candidateRef)));
8120
+ }
8121
+ var DEVICE_REMOVALS_UNREAD = {
8122
+ code: "team_setup_completion_unavailable",
8123
+ reason: "device_removals_unavailable"
8124
+ };
8125
+ var TEAM_MEMBER_REMOVALS_UNREAD = {
8126
+ code: "team_setup_completion_unavailable",
8127
+ reason: "team_member_removals_unavailable"
8128
+ };
8129
+ /** Fresh removal evidence for one group, read before any recipient repair. */
8130
+ async function readRemovalsForRepair(options, store, group) {
8131
+ const dependencies = options.completionDependencies === void 0 ? defaultCompletionDependencies : options.completionDependencies;
8132
+ const authorization = readCompletionAuthorization(options);
8133
+ if (!(dependencies?.listRemovals && dependencies.listTeamMemberRemovals) || !authorization || !authorizesGroup(authorization, group)) return { status: "unavailable" };
8134
+ const timeoutS = Math.max(1, authorization.config.syncCoordinatorTimeoutS);
8135
+ const deadlineMs = Date.now() + COORDINATOR_ROSTER_READ_BUDGET_MS;
8136
+ const { removalReads } = completionReadActions(dependencies, {
8137
+ authorization,
8138
+ store
8139
+ }, timeoutS, deadlineMs);
8140
+ const devices = await removalReads.listRemovals();
8141
+ if (devices?.status !== "read") return {
8142
+ status: "failed",
8143
+ blocker: DEVICE_REMOVALS_UNREAD
8144
+ };
8145
+ let teamMemberRemovals;
8146
+ try {
8147
+ teamMemberRemovals = await removalReads.listTeamMemberRemovals(group.groupId);
8148
+ } catch {
8149
+ return {
8150
+ status: "failed",
8151
+ blocker: TEAM_MEMBER_REMOVALS_UNREAD
8152
+ };
8153
+ }
8154
+ if (!teamMemberRemovals) return { status: "unavailable" };
8155
+ return {
8156
+ status: "read",
8157
+ deviceRemovals: devices.removals,
8158
+ teamMemberRemovals
8159
+ };
8160
+ }
8161
+ /**
8162
+ * Applies the removals a check read, before rediscovery can restore recipients,
8163
+ * and returns whether the repair may run.
8164
+ *
8165
+ * Team member removals are recorded with their enforcements, as the enrollment
8166
+ * check does. They commit in their own transaction before rediscovery, under the
8167
+ * same candidate claim, so any recipient the repair restores is refused to a
8168
+ * removed person's devices.
8169
+ *
8170
+ * A device removal covers one group, and the device may still be enrolled in
8171
+ * another, so this check does not end device-wide access: the sync daemon's
8172
+ * removal check does that once the device is removed everywhere, and the Team
8173
+ * then goes back to review. While this machine still pins or binds a device
8174
+ * this group removed, under the removed key, the repair waits.
8175
+ */
8176
+ function applyRemovalsBeforeRepair(store, group, evidence) {
8177
+ applyTeamMemberRemovals(store.db, {
8178
+ coordinatorId: group.coordinatorId,
8179
+ groupId: group.groupId,
8180
+ removals: evidence.teamMemberRemovals,
8181
+ now: (/* @__PURE__ */ new Date()).toISOString()
7757
8182
  });
7758
- return [...pending, ...blocked].toSorted((left, right) => {
7759
- if (left.candidateRef < right.candidateRef) return -1;
7760
- return left.candidateRef > right.candidateRef ? 1 : 0;
8183
+ const removed = evidence.deviceRemovals.filter((removal) => removal.group_id === group.groupId);
8184
+ if (removed.length === 0) return true;
8185
+ const localDeviceId = store.db.prepare("SELECT device_id FROM sync_device LIMIT 1").pluck().get() ?? "";
8186
+ const removedLocally = localRemovedDeviceIds(store.db, {
8187
+ enrollments: removed.map(({ device_id, fingerprint }) => ({
8188
+ device_id,
8189
+ fingerprint
8190
+ })),
8191
+ keyId: null
8192
+ }, localDeviceId);
8193
+ const stillServed = store.db.prepare(`SELECT 1 FROM identity_devices WHERE device_id = ? AND status = 'active'
8194
+ UNION ALL SELECT 1 FROM sync_peers WHERE peer_device_id = ? LIMIT 1`);
8195
+ return removedLocally.every((deviceId) => !stillServed.get(deviceId, deviceId));
8196
+ }
8197
+ /** No draft of any state and no completed Team: discovery here only creates a draft. */
8198
+ function hasNoLocalSetup(store, candidateRef) {
8199
+ return getLegacyTeamSetupDraft(store.db, candidateRef) === null && !hasCompletedLegacyTeamSetup(store, candidateRef);
8200
+ }
8201
+ function summaryCandidateRef(group) {
8202
+ return legacyTeamCandidateId(group.coordinatorId, group.groupId);
8203
+ }
8204
+ /** Discovery for one group under its claim; a taken claim marks the group skipped. */
8205
+ async function discoverAfterReconciliation(store, group, dependencies, found, mayRepair = () => true) {
8206
+ const candidateRef = summaryCandidateRef(group);
8207
+ if (!await runCandidateMutation(store.db, candidateRef, async () => {
8208
+ if (!mayRepair()) return;
8209
+ const view = discoveredSummaryView(store, group, dependencies.mayRediscover);
8210
+ if (view) found.views.set(candidateRef, view);
8211
+ })) found.skipped.add(candidateRef);
8212
+ }
8213
+ /** The candidate view the summary lists for one group, discovering it when needed. */
8214
+ function discoveredSummaryView(store, group, mayRediscover) {
8215
+ const candidateRef = summaryCandidateRef(group);
8216
+ const draft = getLegacyTeamSetupDraft(store.db, candidateRef);
8217
+ if (hasCompletedLegacyTeamSetup(store, candidateRef)) {
8218
+ if (!isLegacyTeamCandidateSelectable(store.db, candidateRef)) return null;
8219
+ } else if (draft && draft.state !== "completed") return candidateFromDraft(draft);
8220
+ const [view] = completedTeamDiscoveryAuthority.run(mayRediscover, () => discoverCandidates(store, [group]));
8221
+ return view ?? null;
8222
+ }
8223
+ /** A skipped group keeps what the previous pass found, so a busy route never clears it. */
8224
+ function carrySkippedGroups(result, previous) {
8225
+ for (const candidateRef of result.skipped) {
8226
+ result.blockers.delete(candidateRef);
8227
+ const blocker = previous?.blockers.get(candidateRef);
8228
+ if (blocker) result.blockers.set(candidateRef, blocker);
8229
+ const view = previous?.views.get(candidateRef);
8230
+ if (view) result.views.set(candidateRef, view);
8231
+ }
8232
+ return {
8233
+ ...result,
8234
+ failed: new Set(result.blockers.keys())
8235
+ };
8236
+ }
8237
+ /** Candidates with an unfinished local draft, listed before the coordinator was ever checked. */
8238
+ function localDraftCandidateSummaries(store) {
8239
+ return store.db.prepare(`SELECT DISTINCT candidate_id FROM legacy_team_setup_drafts
8240
+ WHERE state <> 'completed' AND superseded_at IS NULL ORDER BY candidate_id`).pluck().all().flatMap((candidateRef) => {
8241
+ const draft = getLegacyTeamSetupDraft(store.db, candidateRef);
8242
+ if (!draft || draft.state === "completed" || hasCompletedLegacyTeamSetup(store, candidateRef)) return [];
8243
+ const summary = candidateSummary(candidateFromDraft(draft));
8244
+ return summary.status === "ready" ? [] : [summary];
7761
8245
  });
7762
8246
  }
7763
- async function reconcileSummaryCandidates(store, groups, reconcile) {
7764
- readPureCandidateViews(store, groups);
7765
- const blockingErrors = /* @__PURE__ */ new Map();
7766
- await reconcile(store, groups, summaryReconciliationOptions(blockingErrors));
8247
+ /**
8248
+ * The summary from the last reconciliation pass, read from local state only. With
8249
+ * nothing checked yet and the latest check failed, the answer is that failure, as
8250
+ * when the summary checked inline.
8251
+ */
8252
+ function summaryResponse(store, read) {
8253
+ if (!read.result && read.status.error_code) return { error: read.status.error_code };
7767
8254
  return {
7768
8255
  version: TEAM_SETUP_VERSION,
7769
- candidates: pendingCandidateSummaries(store, groups, blockingErrors)
8256
+ candidates: read.result ? checkedCandidateSummaries(store, read.result) : localDraftCandidateSummaries(store),
8257
+ reconciliation: read.status
7770
8258
  };
7771
8259
  }
7772
- function readPureCandidateViews(store, groups) {
7773
- const existing = [];
7774
- const discoverable = [];
7775
- for (const group of groups) {
7776
- const candidateRef = legacyTeamCandidateId(group.coordinatorId, group.groupId);
8260
+ /**
8261
+ * The candidates the last pass found, with local drafts read again so edits show
8262
+ * at once. Reads only: discovery, which can write drafts and access, runs in the pass.
8263
+ */
8264
+ function checkedCandidateSummaries(store, result) {
8265
+ return result.groups.flatMap((group) => {
8266
+ const candidateRef = summaryCandidateRef(group);
8267
+ const blocker = result.blockers.get(candidateRef);
8268
+ if (blocker) return [blockedCandidateSummary(store, group, blocker)];
8269
+ if (hasCompletedLegacyTeamSetup(store, candidateRef)) return [];
7777
8270
  const draft = getLegacyTeamSetupDraft(store.db, candidateRef);
7778
- if (hasCompletedLegacyTeamSetup(store, candidateRef)) {
7779
- if (isLegacyTeamCandidateSelectable(store.db, candidateRef)) discoverable.push(group);
7780
- continue;
7781
- }
7782
- if (!draft || draft.state === "completed") {
7783
- discoverable.push(group);
7784
- continue;
7785
- }
7786
- existing.push(candidateFromDraft(draft));
7787
- }
7788
- return [...existing, ...discoverCandidates(store, discoverable)].filter((candidate) => !hasCompletedLegacyTeamSetup(store, candidate.candidateRef)).toSorted((left, right) => left.candidateRef < right.candidateRef ? -1 : left.candidateRef > right.candidateRef ? 1 : 0);
8271
+ const view = draft && draft.state !== "completed" ? candidateFromDraft(draft) : result.views.get(candidateRef);
8272
+ if (!view || view.status === "ready") return [];
8273
+ return [candidateSummary(view)];
8274
+ }).toSorted((left, right) => compareCandidateRefs(left.candidateRef, right.candidateRef));
8275
+ }
8276
+ function compareCandidateRefs(left, right) {
8277
+ if (left < right) return -1;
8278
+ return left > right ? 1 : 0;
8279
+ }
8280
+ /** The background check behind the summary, refreshed again when coordinator settings change. */
8281
+ function createSummaryReconciliation(options, loadSnapshots, reconcile) {
8282
+ const mayRediscover = (group) => {
8283
+ const authorization = readCompletionAuthorization(options);
8284
+ return Boolean(authorization && authorizesGroup(authorization, group));
8285
+ };
8286
+ const dependencies = {
8287
+ loadSnapshots,
8288
+ reconcile,
8289
+ mayRediscover,
8290
+ readRemovalsForRepair: (group) => readRemovalsForRepair(options, options.getStore(), group)
8291
+ };
8292
+ const reconciliation = createTeamSetupReconciliation({
8293
+ run: (previous) => runSummaryReconciliation(options.getStore(), dependencies, previous),
8294
+ assess: (result) => ({
8295
+ failedGroups: result.failed.size,
8296
+ skippedGroups: result.skipped.size,
8297
+ errorCode: result.blockers.values().next().value?.code ?? null
8298
+ }),
8299
+ retryDelayMs: options.reconciliationRetryDelayMs,
8300
+ errorCode: (error) => teamSetupFailure(error, "background GET /api/sync/team-setup/v1").code,
8301
+ record: (outcome) => recordReconciliationOutcome(options.getStore(), outcome)
8302
+ });
8303
+ options.registerReconciliation?.(reconciliation);
8304
+ options.registerSummaryInvalidator?.(() => {
8305
+ loadSnapshots.invalidate();
8306
+ reconciliation.refresh();
8307
+ });
8308
+ return reconciliation;
8309
+ }
8310
+ /** Shows each pass on the Health tab; a coordinator outage is not a failed job. */
8311
+ function recordReconciliationOutcome(store, outcome) {
8312
+ const checkedAt = outcome.checkedAtMs === null ? null : new Date(outcome.checkedAtMs).toISOString();
8313
+ const message = outcome.ok ? "Checked Team setup with the coordinator" : `Could not check Team setup with the coordinator (${outcome.errorCode}); showing the last check`;
8314
+ store.db.transaction(() => {
8315
+ startMaintenanceJob(store.db, {
8316
+ kind: TEAM_SETUP_RECONCILIATION_JOB,
8317
+ title: "Team setup check",
8318
+ status: "pending",
8319
+ message,
8320
+ metadata: {
8321
+ last_checked_at: checkedAt,
8322
+ last_error_code: outcome.errorCode
8323
+ }
8324
+ });
8325
+ completeMaintenanceJob(store.db, TEAM_SETUP_RECONCILIATION_JOB, { message });
8326
+ })();
7789
8327
  }
7790
8328
  function hasCompletedLegacyTeamSetup(store, candidateRef) {
7791
8329
  return Boolean(store.db.prepare(`SELECT 1 FROM policy_teams
@@ -8211,6 +8749,36 @@ var TeamSetupFinishError = class extends Error {
8211
8749
  }
8212
8750
  };
8213
8751
  /**
8752
+ * Records the group's Team member removals, then applies the coordinator's
8753
+ * winning completion, whether this request published it or recovered it after
8754
+ * a lost response. A removal recorded on another admin device must be known
8755
+ * before the completion runs. When the removals cannot be read, nothing is
8756
+ * applied here; reconciliation applies the published winner later.
8757
+ */
8758
+ async function applyFinishWinnerAfterRemovals({ store, dependencies, config }, input) {
8759
+ const list = dependencies.listTeamMemberRemovals;
8760
+ if (list) {
8761
+ let removals;
8762
+ try {
8763
+ removals = await list({
8764
+ groupId: input.groupId,
8765
+ remoteUrl: buildBaseUrl(config.syncCoordinatorUrl),
8766
+ adminSecret: config.syncCoordinatorAdminSecret,
8767
+ timeoutS: Math.max(1, config.syncCoordinatorTimeoutS)
8768
+ });
8769
+ } catch (error) {
8770
+ throw new TeamSetupFinishError("team_setup_completion_unavailable", "team_member_removals_unavailable", false, error);
8771
+ }
8772
+ applyTeamMemberRemovals(store.db, {
8773
+ coordinatorId: input.coordinatorId,
8774
+ groupId: input.groupId,
8775
+ removals,
8776
+ now: (/* @__PURE__ */ new Date()).toISOString()
8777
+ });
8778
+ }
8779
+ return applyLegacyTeamSetupCompletionManifestAndReturnActivation(store.db, input);
8780
+ }
8781
+ /**
8214
8782
  * The generic `legacy_team_setup_roster_too_large` string is thrown by ten
8215
8783
  * sites for unrelated limits (coordinator roster size, draft device count,
8216
8784
  * local project choices). Only the local project-candidate scan is a
@@ -8581,10 +9149,47 @@ function completionReadActions(dependencies, { authorization, store }, timeoutS,
8581
9149
  listCompletionRecords,
8582
9150
  removalReads: {
8583
9151
  listRemovals,
8584
- lookupPeerRemovals: peerRemovalReader(dependencies, store, config)
9152
+ lookupPeerRemovals: peerRemovalReader(dependencies, store, config),
9153
+ listTeamMemberRemovals: async (groupId) => {
9154
+ const read = dependencies.listTeamMemberRemovals;
9155
+ if (!read) return void 0;
9156
+ try {
9157
+ return await read({
9158
+ groupId,
9159
+ remoteUrl,
9160
+ adminSecret,
9161
+ timeoutS
9162
+ });
9163
+ } catch (error) {
9164
+ throw new TeamMemberRemovalsUnavailableError(error);
9165
+ }
9166
+ }
8585
9167
  }
8586
9168
  };
8587
9169
  }
9170
+ /**
9171
+ * What applying a completion needs from the coordinator: device removal
9172
+ * evidence when an included device is missing, and always the group's Team
9173
+ * member removals. A removal recorded on another admin device must be known
9174
+ * before the completion runs, or applying it could make that person a member
9175
+ * again. A failed removal read throws, so nothing is applied.
9176
+ */
9177
+ async function readCompletionEvidence(reads, groupId, includedDeviceMissing) {
9178
+ return {
9179
+ removalEvidence: includedDeviceMissing ? await readRemovalEvidence(reads) : {},
9180
+ teamMemberRemovals: await reads.listTeamMemberRemovals(groupId)
9181
+ };
9182
+ }
9183
+ /** Records the group's Team member removals, then applies the completion. */
9184
+ async function applyCompletionAfterTeamMemberRemovals(store, teamMemberRemovals, input) {
9185
+ if (teamMemberRemovals) applyTeamMemberRemovals(store.db, {
9186
+ coordinatorId: input.coordinatorId,
9187
+ groupId: input.groupId,
9188
+ removals: teamMemberRemovals,
9189
+ now: (/* @__PURE__ */ new Date()).toISOString()
9190
+ });
9191
+ await applyLegacyTeamSetupCompletionManifest(store.db, input);
9192
+ }
8588
9193
  async function readRemovalEvidence(reads) {
8589
9194
  return {
8590
9195
  deviceRemovals: await reads.listRemovals(),
@@ -8643,7 +9248,7 @@ function teamSetupRoutes(options) {
8643
9248
  }
8644
9249
  }
8645
9250
  const loadedSummarySnapshots = createLoadedSummarySnapshotCache(loadedSnapshots, options);
8646
- options.registerSummaryInvalidator?.(() => loadedSummarySnapshots.invalidate());
9251
+ const reconciliation = createSummaryReconciliation(options, loadedSummarySnapshots, reconcileCompletions);
8647
9252
  const completionDependencies = options.completionDependencies === void 0 ? defaultCompletionDependencies : options.completionDependencies;
8648
9253
  const currentCompletionAuthorization = () => readCompletionAuthorization(options);
8649
9254
  function hasDraftEditAuthority(store, candidateRef) {
@@ -8705,16 +9310,17 @@ function teamSetupRoutes(options) {
8705
9310
  */
8706
9311
  async function applyCanonicalManifestIfStillAuthorized(store, authorization, group, manifest, freshRoster, reads) {
8707
9312
  const freshIds = new Set(freshRoster.map((device) => device.deviceId));
8708
- const removalEvidence = manifest.device_decisions.some((device) => device.decision === "included" && !freshIds.has(device.device_id)) ? await readRemovalEvidence(reads) : {};
9313
+ const missing = manifest.device_decisions.some((device) => device.decision === "included" && !freshIds.has(device.device_id));
9314
+ const evidence = await readCompletionEvidence(reads, group.groupId, missing);
8709
9315
  let outcome = "unauthorized";
8710
9316
  return await runCandidateMutation(store.db, legacyTeamCandidateId(group.coordinatorId, group.groupId), () => serializeCanonicalManifestMutation(store, group.groupId, manifest, async (actorIds) => {
8711
9317
  if (!stillAuthorizesGroup(authorization, group)) return;
8712
- await applyLegacyTeamSetupCompletionManifest(store.db, {
9318
+ await applyCompletionAfterTeamMemberRemovals(store, evidence.teamMemberRemovals, {
8713
9319
  coordinatorId: group.coordinatorId,
8714
9320
  groupId: group.groupId,
8715
9321
  manifest,
8716
9322
  freshRoster,
8717
- ...removalEvidence,
9323
+ ...evidence.removalEvidence,
8718
9324
  recipientPolicyLocksHeld: completionRecipientPolicyLocksHeld(actorIds)
8719
9325
  });
8720
9326
  outcome = "applied";
@@ -8974,17 +9580,10 @@ function teamSetupRoutes(options) {
8974
9580
  groupId: row.group_id
8975
9581
  };
8976
9582
  }
8977
- app.get("/api/sync/team-setup/v1", async (c) => {
8978
- let groups;
9583
+ app.get("/api/sync/team-setup/v1", (c) => {
8979
9584
  try {
8980
- groups = await loadedSummarySnapshots();
8981
- } catch (error) {
8982
- const failure = teamSetupFailure(error, `${c.req.method} ${c.req.routePath}`);
8983
- return c.json({ error: failure.code }, failure.status);
8984
- }
8985
- try {
8986
- const response = await reconcileSummaryCandidates(options.getStore(), groups, reconcileCompletions);
8987
- return c.json(response);
9585
+ const summary = summaryResponse(options.getStore(), reconciliation.read());
9586
+ return "error" in summary ? c.json(summary, errorStatus$1(summary.error)) : c.json(summary);
8988
9587
  } catch (error) {
8989
9588
  const failure = teamSetupFailure(error, `${c.req.method} ${c.req.routePath}`);
8990
9589
  return c.json({ error: failure.code }, failure.status);
@@ -9366,7 +9965,11 @@ function teamSetupRoutes(options) {
9366
9965
  throw error;
9367
9966
  }
9368
9967
  if (!postPublicationGroup) throw new TeamSetupFinishError("team_setup_roster_unavailable", "coordinator_roster_unavailable", false, /* @__PURE__ */ new Error("coordinator roster unavailable"));
9369
- const result = await applyLegacyTeamSetupCompletionManifestAndReturnActivation(store.db, {
9968
+ const result = await applyFinishWinnerAfterRemovals({
9969
+ store,
9970
+ dependencies: completionDependencies,
9971
+ config
9972
+ }, {
9370
9973
  coordinatorId: group.coordinatorId,
9371
9974
  groupId: group.groupId,
9372
9975
  freshRoster: postPublicationGroup.devices,
@@ -9823,6 +10426,41 @@ function mappingGuardrailChallenge(warnings, missing) {
9823
10426
  guardrail_warnings: warnings
9824
10427
  };
9825
10428
  }
10429
+ /**
10430
+ * Whether the bulk mapping save accepts these mappings. It cannot carry confirmations, so any
10431
+ * warning that requires one refuses it, and the person saves those entries one at a time.
10432
+ */
10433
+ function bulkProjectMappingVerdict(store, mappingInputs, deviceId) {
10434
+ const analyses = analyzeProjectScopeMappingChangesGuardrails(store.db, mappingInputs.map((input) => ({
10435
+ ...input,
10436
+ deviceId
10437
+ })));
10438
+ const warnings = analyses.flatMap((analysis) => analysis.warnings);
10439
+ const unmapped = analyses.find((analysis) => analysis.requested_workspace_identity?.startsWith("unmapped:"));
10440
+ if (unmapped) return {
10441
+ warnings,
10442
+ refusal: {
10443
+ status: 400,
10444
+ body: {
10445
+ error: "unmapped_project_local_only",
10446
+ message: "Unmapped projects need a stable path, git remote, or workspace id before assigning a Sharing domain.",
10447
+ guardrail_warnings: unmapped.warnings
10448
+ }
10449
+ }
10450
+ };
10451
+ const missing = analyses.flatMap((analysis) => missingGuardrailConfirmations(analysis.warnings, []));
10452
+ if (missing.length === 0) return {
10453
+ refusal: null,
10454
+ warnings
10455
+ };
10456
+ return {
10457
+ warnings,
10458
+ refusal: {
10459
+ status: 409,
10460
+ body: mappingGuardrailChallenge(warnings, missing)
10461
+ }
10462
+ };
10463
+ }
9826
10464
  function parseViewerProjectMappingInput(body) {
9827
10465
  const id = optionalViewerInteger(body, "id");
9828
10466
  const priority = optionalViewerInteger(body, "priority");
@@ -10118,7 +10756,7 @@ function resolveProjectInviteSelection(store, requestedIds, initiatingDeviceId)
10118
10756
  return requestedIds.map((projectId) => {
10119
10757
  const project = byIdentity.get(projectId);
10120
10758
  if (!project) throw new Error("project_selection_unknown");
10121
- if (project.guardrail_warnings.some((warning) => warning.code === "basename_collision_review" && warning.requires_confirmation)) throw new Error("project_selection_ambiguous");
10759
+ if (project.ambiguous_name === true || project.guardrail_warnings.some((warning) => warning.code === "basename_collision_review" && warning.requires_confirmation)) throw new Error("project_selection_ambiguous");
10122
10760
  if (project.read_only || project.identity_source === "unmapped" || project.memory_count == null || project.guardrail_warnings.some((warning) => warning.requires_confirmation)) throw new Error("project_selection_unsupported");
10123
10761
  return {
10124
10762
  canonicalIdentity: project.workspace_identity,
@@ -10549,7 +11187,8 @@ function coordinatorEnrollmentFailureCode(error) {
10549
11187
  "coordinator_id_invalid",
10550
11188
  "coordinator_invite_group_mismatch",
10551
11189
  "coordinator_invite_list_malformed",
10552
- "reconciliation_time_invalid"
11190
+ "reconciliation_time_invalid",
11191
+ "team_member_removal_invalid"
10553
11192
  ])).has(message)) return message;
10554
11193
  if (/timeout|timed out|abort/iu.test(message)) return "request_timeout";
10555
11194
  if (/fetch failed|network|econn|enotfound/iu.test(message)) return "network_error";
@@ -10608,6 +11247,37 @@ async function completeCoordinatorEnrollment(context, initial, completeDeviceSet
10608
11247
  if (!hasCanonicalOwnEnrollment(context, enrollments)) throw new Error(setup.kind === "unknown" ? "completion_outcome_unknown" : "device_setup_enrollment_incomplete");
10609
11248
  return enrollments;
10610
11249
  }
11250
+ /**
11251
+ * The group's Team member removals and the coordinator's binding of each Team
11252
+ * this check handles, each undefined when its read fails. Read after the
11253
+ * invitations: a removal recorded between the reads is still applied, so no
11254
+ * invitation in this snapshot restores that member. A failed read still
11255
+ * reconciles devices, but grants no Team access from an invitation, and
11256
+ * reconciliation reports each invitation it held back. Each Team's group comes
11257
+ * from its coordinator, never from its invitations.
11258
+ */
11259
+ async function readTeamEvidence(store, options, input) {
11260
+ const { groupId, remoteUrl, adminSecret } = input;
11261
+ const listRemovals = options.listTeamMemberRemovals ?? coordinatorListTeamMemberRemovalsAction;
11262
+ const readBindings = options.readTeamGroupBindings ?? coordinatorReadTeamGroupBindingsAction;
11263
+ const teamMemberRemovals = await listRemovals({
11264
+ groupId,
11265
+ remoteUrl,
11266
+ adminSecret
11267
+ }).catch(() => void 0);
11268
+ const teamIds = teamIdsForBindingRead(store.db, {
11269
+ coordinatorId: buildBaseUrl(remoteUrl),
11270
+ invitedTeamIds: input.invites.filter((invite) => invite.group_id === groupId).map((invite) => invite.policy_team_id)
11271
+ });
11272
+ return {
11273
+ teamMemberRemovals,
11274
+ teamGroupBindings: teamIds.length === 0 ? [] : await readBindings({
11275
+ remoteUrl,
11276
+ adminSecret,
11277
+ teamIds
11278
+ }).catch(() => void 0)
11279
+ };
11280
+ }
10611
11281
  async function reconcileConfiguredCoordinatorGroup(store, groupId, config, options) {
10612
11282
  const remoteUrl = config.syncCoordinatorUrl.trim();
10613
11283
  const adminSecret = config.syncCoordinatorAdminSecret.trim();
@@ -10640,6 +11310,12 @@ async function reconcileConfiguredCoordinatorGroup(store, groupId, config, optio
10640
11310
  remoteUrl,
10641
11311
  adminSecret
10642
11312
  });
11313
+ const { teamMemberRemovals, teamGroupBindings } = await readTeamEvidence(store, options, {
11314
+ groupId,
11315
+ remoteUrl,
11316
+ adminSecret,
11317
+ invites
11318
+ });
10643
11319
  stage = "complete_device_setup";
10644
11320
  context.assertCurrent();
10645
11321
  stage = "reconcile_snapshot";
@@ -10648,6 +11324,8 @@ async function reconcileConfiguredCoordinatorGroup(store, groupId, config, optio
10648
11324
  groupId,
10649
11325
  enrollments,
10650
11326
  consumedTeamInvites: invites,
11327
+ teamMemberRemovals,
11328
+ teamGroupBindings,
10651
11329
  localDeviceId: store.deviceId
10652
11330
  }) };
10653
11331
  } catch (error) {
@@ -10980,6 +11658,7 @@ async function reconcileRecipientPolicyProjects(store, options = {}) {
10980
11658
  function recipientPolicyReadState(authority) {
10981
11659
  if (!authority) return "pending";
10982
11660
  if (authority.safeErrorCode && RECIPIENT_POLICY_WAITING_ERRORS.has(authority.safeErrorCode)) return "waiting";
11661
+ if (authority.authorityState === "legacy" && authority.safeErrorCode === RECIPIENT_POLICY_SHARED_SCOPE_CODE) return "legacy_scope";
10983
11662
  if (authority.safeErrorCode || authority.authorityState === "rolled_back") return "needs_attention";
10984
11663
  if (authority.authorityState === "active") return "active";
10985
11664
  if (authority.authorityState === "eligible") return "verifying";
@@ -10998,6 +11677,10 @@ function recipientPolicyReadCopy(state) {
10998
11677
  label: "Waiting to reconcile",
10999
11678
  explanation: "Waiting for devices or a fresh coordinator snapshot. No partial grant is applied."
11000
11679
  };
11680
+ if (state === "legacy_scope") return {
11681
+ label: "Shared scope controls access",
11682
+ explanation: "Access for this Project is still controlled by the shared scope it belongs to. Nothing is required."
11683
+ };
11001
11684
  if (state === "needs_attention") return {
11002
11685
  label: "Reconciliation needs attention",
11003
11686
  explanation: "Legacy scope enforcement remains in control until this Project is safe to retry."
@@ -11063,7 +11746,12 @@ function summarizeMaintenanceJobs(jobs, showDiagnostics) {
11063
11746
  }
11064
11747
  function redactSemanticIndexDiagnostics(diagnostics, showDiagnostics) {
11065
11748
  if (showDiagnostics || !diagnostics.maintenance_job) return diagnostics;
11066
- const summary = diagnostics.state === "pending" ? "Semantic-index catch-up is pending" : diagnostics.state === "failed" ? "Semantic-index catch-up failed" : diagnostics.state === "degraded" ? "Semantic index is running in degraded mode" : diagnostics.summary;
11749
+ const job = diagnostics.maintenance_job;
11750
+ const summary = {
11751
+ failed: "Semantic-index catch-up failed",
11752
+ degraded: "Semantic index is running in degraded mode",
11753
+ ...job.status === "pending" || job.status === "running" ? { pending: "Semantic-index catch-up is pending" } : {}
11754
+ }[diagnostics.state] ?? diagnostics.summary;
11067
11755
  return {
11068
11756
  ...diagnostics,
11069
11757
  summary,
@@ -11580,16 +12268,30 @@ function peerAuthorizedScopes(store, peerDeviceId) {
11580
12268
  function isPendingCaptureActorConflict(error) {
11581
12269
  return error instanceof Error && error.constructor === Error && error.message === "device_adoption_actor_conflict";
11582
12270
  }
12271
+ /**
12272
+ * Whether this device's identity may claim its actor row. Throws when another
12273
+ * process retired the identity; false preserves a pending capture conflict.
12274
+ */
12275
+ function localIdentityMayClaimActor(store) {
12276
+ store.assertLocalIdentityCurrent();
12277
+ try {
12278
+ store.assertPendingLocalCaptureAdoptionActors();
12279
+ } catch (error) {
12280
+ if (isPendingCaptureActorConflict(error)) return false;
12281
+ throw error;
12282
+ }
12283
+ return true;
12284
+ }
12285
+ /** Exactly one local actor row, and it is this device's actor: the state the repair writes. */
12286
+ function localActorRecordCurrent(store) {
12287
+ const rows = store.db.prepare("SELECT actor_id, is_local FROM actors WHERE is_local = 1 OR actor_id = ?").all(store.actorId);
12288
+ return rows.length === 1 && rows[0]?.actor_id === store.actorId && rows[0]?.is_local === 1;
12289
+ }
11583
12290
  /** False leaves the conflict untouched; callers must check before claiming or merging identity. */
11584
12291
  function ensureLocalActorRecord(store) {
12292
+ if (!store.hasPendingLocalCapture() && localActorRecordCurrent(store)) return localIdentityMayClaimActor(store);
11585
12293
  return store.db.transaction(() => {
11586
- store.assertLocalIdentityCurrent();
11587
- try {
11588
- store.assertPendingLocalCaptureAdoptionActors();
11589
- } catch (error) {
11590
- if (isPendingCaptureActorConflict(error)) return false;
11591
- throw error;
11592
- }
12294
+ if (!localIdentityMayClaimActor(store)) return false;
11593
12295
  persistLocalActorRecord(store);
11594
12296
  return true;
11595
12297
  }).immediate();
@@ -12475,7 +13177,8 @@ function attemptStatus(attempt) {
12475
13177
  }
12476
13178
  function readViewerBinding(dbPath) {
12477
13179
  try {
12478
- const raw = readFileSync(join(dirname(dbPath), "viewer.pid"), "utf8");
13180
+ const raw = readViewerPidFile(dbPath);
13181
+ if (raw === null) return null;
12479
13182
  const parsed = JSON.parse(raw);
12480
13183
  if (typeof parsed.host === "string" && typeof parsed.port === "number") return {
12481
13184
  host: parsed.host,
@@ -12604,30 +13307,17 @@ function validateManagedScopes(scopeIds, context) {
12604
13307
  }
12605
13308
  return null;
12606
13309
  }
12607
- function addExistingMutationScopes(db, ops, scopeIds) {
12608
- const existingScopes = db.prepare("SELECT DISTINCT scope_id FROM memory_items WHERE import_key = ?");
12609
- for (const op of ops) {
12610
- if (![
12611
- "upsert",
12612
- "delete",
12613
- "reassign_scope"
12614
- ].includes(op.op_type)) continue;
12615
- const rows = existingScopes.all(op.entity_id);
12616
- for (const { scope_id: scope } of rows) if (typeof scope === "string" && scope.trim()) scopeIds.add(scope.trim());
12617
- }
12618
- }
12619
13310
  function cleanOpScopeId(op) {
12620
13311
  return typeof op.scope_id === "string" ? op.scope_id.trim() : "";
12621
13312
  }
12622
- /** Every scope a batch touches, including both sides of a reassignment. Payloads are already parsed. */
12623
- function mutationScopeIds(ops) {
13313
+ /**
13314
+ * Every scope a pushed batch touches: each op's own scope, and each scope of a stored copy
13315
+ * the op would change, by the rule the pull path uses. A move's new side needs only its new
13316
+ * scope unless this device stores a copy elsewhere, and its old side needs its old scope.
13317
+ */
13318
+ function inboundWriteScopeIds(db, ops, senderId) {
12624
13319
  const scopeIds = new Set(ops.map(cleanOpScopeId));
12625
- for (const op of ops) {
12626
- if (op.op_type !== "reassign_scope") continue;
12627
- const reassignment = parseReassignScopePayload(op);
12628
- scopeIds.add(reassignment.old_scope_id);
12629
- scopeIds.add(reassignment.new_scope_id);
12630
- }
13320
+ for (const op of ops) for (const scopeId of scopesWrittenByInboundOp(db, op, senderId)) scopeIds.add(scopeId);
12631
13321
  return scopeIds;
12632
13322
  }
12633
13323
  function rejectUnauthorizedInboundBatch(c, ops, context, options) {
@@ -12637,20 +13327,38 @@ function rejectUnauthorizedInboundBatch(c, ops, context, options) {
12637
13327
  });
12638
13328
  if (rejected) {
12639
13329
  recordInboundScopeFailure(context);
13330
+ const rejections = peerFacingRejections(ops, rejected.rejections);
12640
13331
  return c.json({
12641
13332
  error: "scope_rejected",
12642
- reason: rejected.rejections[0]?.reason ?? "scope_mismatch",
12643
- rejections: rejected.rejections,
13333
+ reason: rejections[0]?.reason ?? "scope_mismatch",
13334
+ rejections,
12644
13335
  sync_capability: LOCAL_SYNC_CAPABILITY,
12645
13336
  scope_id: options.scopeId
12646
13337
  }, 403);
12647
13338
  }
12648
- const scopeIds = new Set(options.managedScopeIds);
12649
- addExistingMutationScopes(context.db, ops, scopeIds);
12650
- const failure = validateManagedScopes(scopeIds, context);
13339
+ const failure = validateManagedScopes(inboundWriteScopeIds(context.db, ops, context.peerDeviceId), context);
12651
13340
  if (!failure) return null;
12652
13341
  recordInboundScopeFailure(context);
12653
- return c.json(syncScopeResetRequiredPayload(getSyncResetState(context.db), failure.reason, LOCAL_SYNC_CAPABILITY, failure.scopeId), 409);
13342
+ const reason = peerFacingScopeResetReason(failure.reason);
13343
+ const scopeId = (/* @__PURE__ */ new Set([options.scopeId, ...ops.map(cleanOpScopeId)])).has(failure.scopeId) ? failure.scopeId : options.scopeId;
13344
+ if (reason !== failure.reason || scopeId !== failure.scopeId) logWithheldScopeDenial(failure.reason, failure.scopeId);
13345
+ return c.json(syncScopeResetRequiredPayload(getSyncResetState(context.db), reason, LOCAL_SYNC_CAPABILITY, scopeId), 409);
13346
+ }
13347
+ /** Records locally what a scope denial withheld from the peer's answer. */
13348
+ function logWithheldScopeDenial(reason, scopeId) {
13349
+ console.warn(`[sync] scope denied to peer: reason=${reason} scope=${scopeId ?? "none"}`);
13350
+ }
13351
+ /**
13352
+ * Rejections as a peer may see them: each names its op's own scope, never the scope of a
13353
+ * stored copy, and membership and scope state collapse into one reason.
13354
+ */
13355
+ function peerFacingRejections(ops, rejections) {
13356
+ const declared = new Map(ops.map((op) => [op.op_id, cleanOpScopeId(op) || null]));
13357
+ return rejections.map((rejection) => ({
13358
+ ...rejection,
13359
+ scope_id: declared.get(rejection.op_id) ?? null,
13360
+ reason: rejection.reason === "scope_mismatch" ? rejection.reason : "missing_scope"
13361
+ }));
12654
13362
  }
12655
13363
  function recordInboundScopeFailure(context) {
12656
13364
  recordSyncTransferObservation(context.db, context.peerDeviceId, "receive", {
@@ -12731,7 +13439,9 @@ function serveChannelRead(c, options) {
12731
13439
  function syncScopeProvided(provided, syncChannelPeerPin) {
12732
13440
  return syncChannelPeerPin !== void 0 || provided;
12733
13441
  }
12734
- function syncScopeResetResponse(c, store, reason, syncChannelPeerPin) {
13442
+ function syncScopeResetResponse(c, store, preciseReason, syncChannelPeerPin) {
13443
+ const reason = peerFacingScopeResetReason(preciseReason);
13444
+ if (reason !== preciseReason) logWithheldScopeDenial(preciseReason, c.req.query(SYNC_SCOPE_QUERY_PARAM) ?? null);
12735
13445
  if (syncChannelPeerPin !== void 0) return c.json({
12736
13446
  error: "reset_required",
12737
13447
  reset_required: true,
@@ -12993,11 +13703,9 @@ function syncProtocolRoutes(getStore, opts = {}) {
12993
13703
  applyScopeFilter: false,
12994
13704
  supportsReassignScope: peerFeatures.includes("reassign_scope")
12995
13705
  });
12996
- const validatedOps = normalizedOps.filter((op) => !isProjectScopeWithdrawn(scopeContext.db, cleanOpScopeId(op)));
12997
- const rejected = rejectUnauthorizedInboundBatch(c, validatedOps, scopeContext, {
13706
+ const rejected = rejectUnauthorizedInboundBatch(c, normalizedOps.filter((op) => !isProjectScopeWithdrawn(scopeContext.db, cleanOpScopeId(op))), scopeContext, {
12998
13707
  enabled: negotiated !== "unsupported",
12999
- scopeId: scopeRequest.scope_id,
13000
- managedScopeIds: mutationScopeIds(validatedOps)
13708
+ scopeId: scopeRequest.scope_id
13001
13709
  });
13002
13710
  if (rejected) return rejected;
13003
13711
  const result = applyInboundSyncOps(store, filtered.allowed, localDeviceId, peerDeviceId);
@@ -13817,12 +14525,32 @@ function previewRecipientInvitation(store, body) {
13817
14525
  };
13818
14526
  }
13819
14527
  }
14528
+ /**
14529
+ * The group a recipient invitation goes through. A Team's first invitation
14530
+ * binds it on the coordinator, so a Team whose group is known goes only through
14531
+ * that group; anything else uses the requested or configured group.
14532
+ */
14533
+ function recipientInvitationGroup(store, input) {
14534
+ const requestedGroupId = optionalViewerString(input.body, "group_id");
14535
+ return (input.kind === "team_member" ? teamInvitationGroup(store.db, {
14536
+ teamId: input.targetId,
14537
+ coordinatorId: input.config.syncCoordinatorUrl,
14538
+ configuredGroupIds: input.config.syncCoordinatorGroups,
14539
+ requestedGroupId
14540
+ }) : null) ?? resolveCoordinatorAdminGroup(requestedGroupId, input.status);
14541
+ }
13820
14542
  async function issueRecipientInvitation(store, body, kind, targetId, preview) {
13821
14543
  const config = readCoordinatorSyncConfig();
13822
14544
  const status = coordinatorAdminStatusPayload(config);
13823
14545
  const reviewedIntent = recipientInviteReviewedIntent(store, kind, targetId, preview);
13824
14546
  const reviewedPreviewDigest = await recipientReviewedIntentDigest(reviewedIntent);
13825
- const groupId = resolveCoordinatorAdminGroup(optionalViewerString(body, "group_id"), status);
14547
+ const groupId = recipientInvitationGroup(store, {
14548
+ body,
14549
+ kind,
14550
+ targetId,
14551
+ config,
14552
+ status
14553
+ });
13826
14554
  const ttlHours = parseInviteTtlHours(body.ttl_hours);
13827
14555
  if (!groupId) throw new Error("group_id_required");
13828
14556
  if (ttlHours == null) throw new Error("ttl_hours_invalid");
@@ -13882,6 +14610,11 @@ async function createRecipientInvitation(store, body) {
13882
14610
  }
13883
14611
  };
13884
14612
  } catch (error) {
14613
+ const code = error instanceof Error ? error.message : "";
14614
+ if (code === "team_group_mismatch" || code === "team_link_conflict") return {
14615
+ httpStatus: 409,
14616
+ body: { error: code }
14617
+ };
13885
14618
  return {
13886
14619
  httpStatus: 400,
13887
14620
  body: { error: error instanceof Error ? error.message : "recipient_invite_failed" }
@@ -14645,22 +15378,12 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
14645
15378
  const mappingInputs = parseViewerProjectMappingInputs(body);
14646
15379
  releasePublicationMutation = await claimRecipientPolicyPublicationMutation(store.db);
14647
15380
  const [deviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
14648
- const analyses = analyzeProjectScopeMappingChangesGuardrails(store.db, mappingInputs.map((input) => ({
14649
- ...input,
14650
- deviceId
14651
- })));
14652
- const unmapped = analyses.find((analysis) => analysis.requested_workspace_identity?.startsWith("unmapped:"));
14653
- if (unmapped) return c.json({
14654
- error: "unmapped_project_local_only",
14655
- message: "Unmapped projects need a stable path, git remote, or workspace id before assigning a Sharing domain.",
14656
- guardrail_warnings: unmapped.warnings
14657
- }, 400);
14658
- const missingConfirmations = analyses.flatMap((analysis) => missingGuardrailConfirmations(analysis.warnings, []));
14659
- if (missingConfirmations.length > 0) return c.json(mappingGuardrailChallenge(analyses.flatMap((analysis) => analysis.warnings), missingConfirmations), 409);
15381
+ const verdict = bulkProjectMappingVerdict(store, mappingInputs, deviceId);
15382
+ if (verdict.refusal) return c.json(verdict.refusal.body, verdict.refusal.status);
14660
15383
  return c.json({
14661
15384
  ok: true,
14662
15385
  mappings: saveProjectMappingsAndWakePolicies(store, deviceId, mappingInputs),
14663
- guardrail_warnings: analyses.flatMap((analysis) => analysis.warnings)
15386
+ guardrail_warnings: verdict.warnings
14664
15387
  });
14665
15388
  } catch (error) {
14666
15389
  return c.json({ error: error instanceof Error ? error.message : String(error) }, 400);
@@ -14668,6 +15391,24 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
14668
15391
  releasePublicationMutation?.();
14669
15392
  }
14670
15393
  });
15394
+ app.post("/api/sync/sharing-domains/project-mappings/bulk/check", async (c) => {
15395
+ const store = getStore();
15396
+ const body = await parseViewerJsonBody(c);
15397
+ if (!body) return c.json({ error: "invalid json" }, 400);
15398
+ try {
15399
+ const mappingInputs = parseViewerProjectMappingInputs(body);
15400
+ const [deviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
15401
+ const verdict = bulkProjectMappingVerdict(store, mappingInputs, deviceId);
15402
+ return c.json({
15403
+ ok: true,
15404
+ accepted: verdict.refusal === null,
15405
+ refusal: verdict.refusal?.body ?? null,
15406
+ guardrail_warnings: verdict.warnings
15407
+ });
15408
+ } catch (error) {
15409
+ return c.json({ error: error instanceof Error ? error.message : String(error) }, 400);
15410
+ }
15411
+ });
14671
15412
  app.delete("/api/sync/sharing-domains/project-mappings/:id", (c) => deleteProjectScopeMappingRoute(c, getStore()));
14672
15413
  app.post("/api/sync/peers/identity", async (c) => {
14673
15414
  const store = getStore();
@@ -17412,8 +18153,18 @@ function teamCreationUnavailable(status) {
17412
18153
  function isCreateTeamBody(body) {
17413
18154
  return Boolean(body) && typeof body === "object" && !Array.isArray(body) && Object.keys(body).length === 1 && typeof body.displayName === "string";
17414
18155
  }
18156
+ /** The one configured group the Team's invitations will go through, if there is exactly one. */
18157
+ function invitationGroup(config) {
18158
+ const groups = config.syncCoordinatorGroups;
18159
+ const coordinatorId = buildBaseUrl(config.syncCoordinatorUrl);
18160
+ return groups.length === 1 && groups[0] && coordinatorId ? {
18161
+ coordinatorId,
18162
+ groupId: groups[0]
18163
+ } : void 0;
18164
+ }
17415
18165
  async function createTeam(c, getStore, readConfig) {
17416
- const unavailable = teamCreationUnavailable(coordinatorAdminStatusPayload(readConfig()));
18166
+ const config = readConfig();
18167
+ const unavailable = teamCreationUnavailable(coordinatorAdminStatusPayload(config));
17417
18168
  if (unavailable) return c.json({ error: unavailable.code }, unavailable.httpStatus);
17418
18169
  const body = await parseViewerJsonBody(c);
17419
18170
  if (!isCreateTeamBody(body)) return c.json({ error: "team_name_invalid" }, 400);
@@ -17423,7 +18174,8 @@ async function createTeam(c, getStore, readConfig) {
17423
18174
  const team = createRecipientPolicyTeam(store.db, {
17424
18175
  displayName: body.displayName,
17425
18176
  creatorIdentityId: store.actorId,
17426
- now: (/* @__PURE__ */ new Date()).toISOString()
18177
+ now: (/* @__PURE__ */ new Date()).toISOString(),
18178
+ coordinatorGroup: invitationGroup(config)
17427
18179
  });
17428
18180
  return c.json(team, 201);
17429
18181
  } catch (error) {
@@ -17437,6 +18189,118 @@ function teamCreateRoutes(getStore, readCoordinatorConfig = readCoordinatorSyncC
17437
18189
  return app;
17438
18190
  }
17439
18191
  //#endregion
18192
+ //#region src/routes/team-member-removal.ts
18193
+ var BASE = "/api/sync/recipient-policy/v1/teams/:teamId/member-removals";
18194
+ var STATUS = {
18195
+ invalid_input: 400,
18196
+ team_not_found: 404,
18197
+ member_not_found: 404,
18198
+ team_not_linked: 409,
18199
+ team_link_conflict: 409,
18200
+ team_coordinator_not_configured: 409,
18201
+ member_already_removed: 409,
18202
+ cannot_remove_yourself: 409,
18203
+ removal_preview_stale: 409,
18204
+ invitations_unavailable: 503,
18205
+ coordinator_unavailable: 503
18206
+ };
18207
+ /** The identifier format the policy layer and the coordinator accept. */
18208
+ function isId(value) {
18209
+ return isStrictRecipientPolicyId(value);
18210
+ }
18211
+ function previewBody(body) {
18212
+ const data = body;
18213
+ if (!data || typeof data !== "object" || Array.isArray(data)) return null;
18214
+ if (Object.keys(data).length !== 1 || !isId(data.identityId)) return null;
18215
+ return { identityId: data.identityId };
18216
+ }
18217
+ function commitBody(body) {
18218
+ const data = body;
18219
+ if (!data || typeof data !== "object" || Array.isArray(data)) return null;
18220
+ if (Object.keys(data).toSorted().join(",") !== "expectedDigest,identityId,revokeInvitationIds") return null;
18221
+ const { identityId, expectedDigest, revokeInvitationIds } = data;
18222
+ if (!isId(identityId) || typeof expectedDigest !== "string" || expectedDigest.length > 256) return null;
18223
+ if (!Array.isArray(revokeInvitationIds) || revokeInvitationIds.length > 200) return null;
18224
+ if (!revokeInvitationIds.every(isId)) return null;
18225
+ return {
18226
+ identityId,
18227
+ expectedDigest,
18228
+ revokeInvitationIds
18229
+ };
18230
+ }
18231
+ function revokeBody(body) {
18232
+ const data = body;
18233
+ if (!data || typeof data !== "object" || Array.isArray(data)) return null;
18234
+ if (Object.keys(data).length !== 1 || !Array.isArray(data.inviteIds)) return null;
18235
+ const ids = data.inviteIds;
18236
+ return ids.length > 0 && ids.length <= 200 && ids.every(isId) ? ids : null;
18237
+ }
18238
+ /** The removal context, or null when this device cannot change other people's access. */
18239
+ function removalContext(getStore, options) {
18240
+ const config = (options.readCoordinatorConfig ?? readCoordinatorSyncConfig)();
18241
+ if (!isCoordinatorAdminDevice(config)) return null;
18242
+ const store = getStore();
18243
+ return {
18244
+ coordinator: {
18245
+ remoteUrl: buildBaseUrl(config.syncCoordinatorUrl),
18246
+ adminSecret: config.syncCoordinatorAdminSecret,
18247
+ groupIds: config.syncCoordinatorGroups,
18248
+ timeoutS: Math.max(1, config.syncCoordinatorTimeoutS)
18249
+ },
18250
+ localIdentityId: store.actorId ?? null,
18251
+ localDeviceId: store.deviceId ?? null,
18252
+ actions: options.actions
18253
+ };
18254
+ }
18255
+ function teamMemberRemovalRoutes(getStore, options = {}) {
18256
+ const app = new Hono();
18257
+ const context = () => removalContext(getStore, options);
18258
+ const handle = async (c, run) => {
18259
+ const ctx = context();
18260
+ if (!ctx) return c.json({ error: "coordinator_admin_required" }, 403);
18261
+ const teamId = c.req.param("teamId");
18262
+ if (!isId(teamId)) return c.json({ error: "invalid_input" }, 400);
18263
+ const result = await run(teamId, await parseViewerJsonBody(c), ctx);
18264
+ if (result.state === "rejected" && "error" in result) return c.json({ error: result.error }, STATUS[result.error]);
18265
+ return c.json(result);
18266
+ };
18267
+ app.get("/api/sync/recipient-policy/v1/team-coordinator-link-conflicts", (c) => c.json({ teamIds: teamCoordinatorLinkConflicts(getStore().db) }));
18268
+ app.post(`${BASE}/preview`, (c) => handle(c, async (teamId, body, ctx) => {
18269
+ const input = previewBody(body);
18270
+ if (!input) return {
18271
+ state: "rejected",
18272
+ error: "invalid_input"
18273
+ };
18274
+ return previewTeamMemberRemoval(getStore().db, {
18275
+ teamId,
18276
+ ...input
18277
+ }, ctx);
18278
+ }));
18279
+ app.post(`${BASE}/commit`, (c) => handle(c, async (teamId, body, ctx) => {
18280
+ const input = commitBody(body);
18281
+ if (!input) return {
18282
+ state: "rejected",
18283
+ error: "invalid_input"
18284
+ };
18285
+ return commitTeamMemberRemoval(getStore().db, {
18286
+ teamId,
18287
+ ...input
18288
+ }, ctx);
18289
+ }));
18290
+ app.post("/api/sync/recipient-policy/v1/teams/:teamId/invitations/revoke", (c) => handle(c, async (teamId, body, ctx) => {
18291
+ const inviteIds = revokeBody(body);
18292
+ if (!inviteIds) return {
18293
+ state: "rejected",
18294
+ error: "invalid_input"
18295
+ };
18296
+ return revokePendingTeamInvitations(getStore().db, {
18297
+ teamId,
18298
+ inviteIds
18299
+ }, ctx);
18300
+ }));
18301
+ return app;
18302
+ }
18303
+ //#endregion
17440
18304
  //#region src/routes/update-status.ts
17441
18305
  function updateStatusRoutes(options = {}) {
17442
18306
  const getUpdateStatus$1 = options.getUpdateStatus ?? getUpdateStatus;
@@ -18075,6 +18939,8 @@ var memoryItems = sqliteTable("memory_items", {
18075
18939
  index("idx_memory_items_active_created").on(table.active, table.created_at),
18076
18940
  index("idx_memory_items_created_id").on(table.created_at, table.id),
18077
18941
  index("idx_memory_items_origin_device_active").on(table.origin_device_id, table.active),
18942
+ index("idx_memory_items_origin_active_scope").on(table.origin_device_id, table.active, table.scope_id),
18943
+ index("idx_memory_items_updated_at").on(table.updated_at),
18078
18944
  index("idx_memory_items_session").on(table.session_id),
18079
18945
  index("idx_memory_items_project").on(table.project),
18080
18946
  index("idx_memory_items_scope_visibility_created").on(table.scope_id, table.visibility, table.created_at),
@@ -18180,7 +19046,11 @@ var retrievalExposures = sqliteTable("retrieval_exposures", {
18180
19046
  memory_deleted_at: text("memory_deleted_at"),
18181
19047
  score_summary_json: text("score_summary_json"),
18182
19048
  reason_codes_json: text("reason_codes_json")
18183
- }, (table) => [uniqueIndex("idx_retrieval_exposures_attempt_rank").on(table.attempt_id, table.rank), index("idx_retrieval_exposures_memory").on(table.memory_id)]);
19049
+ }, (table) => [
19050
+ uniqueIndex("idx_retrieval_exposures_attempt_rank").on(table.attempt_id, table.rank),
19051
+ index("idx_retrieval_exposures_memory").on(table.memory_id),
19052
+ index("idx_retrieval_exposures_not_selected").on(table.attempt_id).where(sql`${table.disposition} <> 'selected'`)
19053
+ ]);
18184
19054
  var outcomeEvidence = sqliteTable("outcome_evidence", {
18185
19055
  evidence_id: text("evidence_id").primaryKey(),
18186
19056
  contract_version: integer("contract_version").notNull(),
@@ -18326,7 +19196,9 @@ sqliteTable("raw_event_flush_batches", {
18326
19196
  index("idx_flush_batches_session_created").on(table.opencode_session_id, table.created_at),
18327
19197
  index("idx_flush_batches_status_updated").on(table.status, table.updated_at),
18328
19198
  index("idx_flush_batches_observer_status_updated").on(table.status, table.updated_at).where(sql`${table.observer_provider} IS NOT NULL`),
18329
- index("idx_flush_batches_capture_status_updated").on(table.status, table.updated_at).where(sql`${table.observer_provider} IS NULL`)
19199
+ index("idx_flush_batches_capture_status_updated").on(table.status, table.updated_at).where(sql`${table.observer_provider} IS NULL`),
19200
+ index("idx_flush_batches_auth_missing").on(table.source, table.stream_id, table.created_at).where(sql`${table.observer_error_code} = 'auth_missing' AND ${table.status} IN ('failed', 'gave_up')`),
19201
+ index("idx_flush_batches_recovery_attempts").on(table.updated_at, table.attempt_count).where(sql`${table.extractor_version} = 'raw_events_auth_recovery_v1' AND ${table.attempt_count} > 0`)
18330
19202
  ]);
18331
19203
  sqliteTable("user_prompts", {
18332
19204
  id: integer("id").primaryKey(),
@@ -18461,6 +19333,7 @@ sqliteTable("sync_attempts", {
18461
19333
  transport: text("transport")
18462
19334
  }, (table) => [
18463
19335
  index("idx_sync_attempts_peer_started").on(table.peer_device_id, table.started_at),
19336
+ index("idx_sync_attempts_peer_kind_started").on(table.peer_device_id, table.ok, table.failure_category, table.started_at),
18464
19337
  index("idx_sync_attempts_occurred").on(sql`CASE WHEN ${table.finished_at} IS NULL THEN ${table.started_at} ELSE ${table.finished_at} END`, table.id),
18465
19338
  index("idx_sync_attempts_error_occurred").on(sql`CASE WHEN ${table.finished_at} IS NULL THEN ${table.started_at} ELSE ${table.finished_at} END`, table.id).where(sql`${table.ok} = 0`),
18466
19339
  index("idx_sync_attempts_success_occurred").on(sql`CASE WHEN ${table.finished_at} IS NULL THEN ${table.started_at} ELSE ${table.finished_at} END`, table.id).where(sql`${table.ok} <> 0`)
@@ -18632,6 +19505,37 @@ sqliteTable("policy_team_device_decisions", {
18632
19505
  created_at: text("created_at").notNull(),
18633
19506
  updated_at: text("updated_at").notNull()
18634
19507
  }, (table) => [primaryKey({ columns: [table.team_id, table.device_id] }), index("idx_policy_team_device_decisions_device").on(table.device_id)]);
19508
+ sqliteTable("policy_team_member_removals", {
19509
+ team_id: text("team_id").notNull(),
19510
+ identity_id: text("identity_id").notNull(),
19511
+ coordinator_id: text("coordinator_id").notNull(),
19512
+ group_id: text("group_id").notNull(),
19513
+ removal_seq: integer("removal_seq").notNull(),
19514
+ removed_at: text("removed_at").notNull(),
19515
+ removed_by_device_id: text("removed_by_device_id"),
19516
+ recorded_at: text("recorded_at").notNull()
19517
+ }, (table) => [primaryKey({ columns: [
19518
+ table.coordinator_id,
19519
+ table.group_id,
19520
+ table.team_id,
19521
+ table.identity_id
19522
+ ] })]);
19523
+ sqliteTable("policy_team_coordinator_links", {
19524
+ team_id: text("team_id").notNull(),
19525
+ coordinator_id: text("coordinator_id").notNull(),
19526
+ group_id: text("group_id").notNull(),
19527
+ source: text("source").notNull(),
19528
+ recorded_at: text("recorded_at").notNull()
19529
+ }, (table) => [primaryKey({ columns: [
19530
+ table.team_id,
19531
+ table.coordinator_id,
19532
+ table.group_id
19533
+ ] })]);
19534
+ sqliteTable("policy_team_member_removal_enforcements", {
19535
+ team_id: text("team_id").notNull(),
19536
+ identity_id: text("identity_id").notNull(),
19537
+ enforced_at: text("enforced_at").notNull()
19538
+ }, (table) => [primaryKey({ columns: [table.team_id, table.identity_id] })]);
18635
19539
  sqliteTable("identity_devices", {
18636
19540
  device_id: text("device_id").primaryKey(),
18637
19541
  identity_id: text("identity_id").notNull(),
@@ -20459,11 +21363,12 @@ function registerStaticRoutes(app) {
20459
21363
  return c.html(indexHtml);
20460
21364
  });
20461
21365
  }
20462
- function registerConfigRoutes(app, opts, sweeper) {
21366
+ function registerConfigRoutes(app, opts, sweeper, onCoordinatorConfigChanged) {
20463
21367
  app.route("/", configRoutes({
20464
21368
  getSweeper: () => sweeper,
20465
21369
  scheduleObserverApply: opts?.scheduleObserverApply,
20466
- getObserverApplyStatus: opts?.getObserverApplyStatus
21370
+ getObserverApplyStatus: opts?.getObserverApplyStatus,
21371
+ onCoordinatorConfigChanged
20467
21372
  }));
20468
21373
  }
20469
21374
  function registerViewerBoundary(app, opts) {
@@ -20572,12 +21477,13 @@ function createApp(opts) {
20572
21477
  getSweeper: () => sweeper,
20573
21478
  getObserver
20574
21479
  }));
20575
- registerConfigRoutes(app, opts, sweeper);
21480
+ registerConfigRoutes(app, opts, sweeper, () => invalidateTeamSetupSummary());
20576
21481
  app.route("/", rawEventsRoutes(storeFactory, sweeper, opts?.rawEventInbox, opts?.rawEventTarget));
20577
21482
  installRecipientAccessChangeGate(app, storeFactory, opts?.readCoordinatorConfig);
20578
21483
  registerViewerSyncRoutes(app, storeFactory, opts, () => invalidateTeamSetupSummary());
20579
21484
  registerViewerDeviceRemoval(app, storeFactory, opts);
20580
21485
  app.route("/", teamCreateRoutes(storeFactory, opts?.readCoordinatorConfig));
21486
+ app.route("/", teamMemberRemovalRoutes(storeFactory, { readCoordinatorConfig: opts?.readCoordinatorConfig }));
20581
21487
  app.route("/", projectWithdrawalRoutes(storeFactory));
20582
21488
  app.route("/", teamSetupRoutes({
20583
21489
  getStore: storeFactory,
@@ -20586,12 +21492,18 @@ function createApp(opts) {
20586
21492
  readCoordinatorConfig: opts?.readCoordinatorConfig,
20587
21493
  registerSummaryInvalidator: (invalidate) => {
20588
21494
  invalidateTeamSetupSummary = invalidate;
20589
- }
21495
+ },
21496
+ registerReconciliation: (reconciliation) => startTeamSetupReconciliation(reconciliation, opts)
20590
21497
  }));
20591
21498
  app.route("/", updateStatusRoutes({ getUpdateStatus: opts?.getUpdateStatus }));
20592
21499
  registerStaticRoutes(app);
20593
21500
  return app;
20594
21501
  }
21502
+ function startTeamSetupReconciliation(reconciliation, opts) {
21503
+ opts?.onTeamSetupReconciliation?.(reconciliation);
21504
+ const intervalMs = opts?.teamSetupReconciliationIntervalMs;
21505
+ if (intervalMs) reconciliation.startPeriodic(intervalMs);
21506
+ }
20595
21507
  /** Preserve the public server options while transport adapters use the narrower factory. */
20596
21508
  function createSyncApp(opts) {
20597
21509
  return createSyncApp$1(opts);