@codemem/server 0.50.0-beta.3 → 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, 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, 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, coordinatorListTeamMemberRemovalsAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorRenameGroupAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeDeviceAction, coordinatorRevokeScopeMembershipAction, 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, 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, peerFacingScopeResetReason, 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, scopesWrittenByInboundOp, 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";
@@ -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
  }
@@ -6514,6 +6519,45 @@ function overallSyncHealth(peers, options) {
6514
6519
  };
6515
6520
  }
6516
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
6517
6561
  //#region src/application/sync-status.ts
6518
6562
  var SAFE_RUNTIME_DETAILS = {
6519
6563
  starting: "Running initial sync in background",
@@ -6763,13 +6807,107 @@ function applyDerivedDaemonState(base, peers, attempts, failedPeerIds, statusBlo
6763
6807
  base.statusPayload.daemon_state = state;
6764
6808
  statusBlock.daemon_state = state;
6765
6809
  }
6766
- async function readJoinRequests(input, config) {
6767
- if (!input.includeJoinRequests || !input.showDiagnostics || !config.syncCoordinatorAdminSecret) return [];
6768
- try {
6769
- return await listCoordinatorJoinRequests(config);
6770
- } catch {
6771
- 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);
6772
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 ?? [];
6773
6911
  }
6774
6912
  function addSyncHealth(base, peers, status) {
6775
6913
  const health = overallSyncHealth(peers.items, {
@@ -6787,7 +6925,7 @@ function markPeerFailures(peers, failedPeerIds) {
6787
6925
  }
6788
6926
  async function buildSyncStatusResponse(input) {
6789
6927
  const base = readBaseStatus(input);
6790
- const coordinatorSnapshot = await coordinatorStatusSnapshot(input.store, base.config);
6928
+ const coordinatorSnapshot = await readCoordinatorStatus(input, base);
6791
6929
  const coordinator = traceSync("coordinator", () => input.operations.redactCoordinatorStatus(coordinatorSnapshot, input.showDiagnostics));
6792
6930
  const peers = readPeerStatus(input, base.localDeviceId);
6793
6931
  const attempts = readAttemptStatus(input);
@@ -6806,7 +6944,7 @@ async function buildSyncStatusResponse(input) {
6806
6944
  const legacyReview = traceSync("legacySharedReview", () => input.operations.legacySharedReviewSummary(input.store));
6807
6945
  const sharingReview = traceSync("sharingReview", () => input.store.sharingReviewSummary(input.project));
6808
6946
  const recipientPolicyReconciliation = traceSync("recipientPolicyReconciliation", () => input.operations.listRecipientPolicyReconciliationStatus(input.store));
6809
- const joinRequests = await readJoinRequests(input, base.config);
6947
+ const joinRequests = readJoinRequests(input, base.config);
6810
6948
  applyDerivedDaemonState(base, peers, attempts, failedPeerIds, statusBlock);
6811
6949
  const syncHealth = addSyncHealth(base, peers, statusBlock);
6812
6950
  const response = {
@@ -7133,6 +7271,127 @@ function deviceRetireRoutes(getStore) {
7133
7271
  function deviceRoutes(getStore) {
7134
7272
  return new Hono().route("/", deviceRenameRoutes(getStore)).route("/", deviceRetireRoutes(getStore));
7135
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
+ }
7136
7395
  //#endregion
7137
7396
  //#region src/routes/team-setup-view.ts
7138
7397
  var enabled = {
@@ -7300,9 +7559,17 @@ function claimCandidateMutation(db, candidateRef) {
7300
7559
  function candidateMutationSettled(db, candidateRef) {
7301
7560
  return activeCandidateMutations.get(db)?.get(candidateRef) ?? Promise.resolve();
7302
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();
7303
7567
  async function runCandidateMutation(db, candidateRef, operation) {
7304
7568
  const release = claimCandidateMutation(db, candidateRef);
7305
- if (!release) return false;
7569
+ if (!release) {
7570
+ skippedCandidateMutations.getStore()?.add(candidateRef);
7571
+ return false;
7572
+ }
7306
7573
  try {
7307
7574
  await operation();
7308
7575
  return true;
@@ -7326,8 +7593,19 @@ function completionFailureHandlers(options) {
7326
7593
  reportFailure
7327
7594
  };
7328
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
+ };
7329
7607
  function isNonDivergentApplyFailure(error) {
7330
- return error instanceof LegacyTeamSetupAdditiveConvergenceError || error instanceof LegacyTeamSetupDeviceRemovalsUnavailableError;
7608
+ return error instanceof LegacyTeamSetupAdditiveConvergenceError || error instanceof LegacyTeamSetupDeviceRemovalsUnavailableError || error instanceof TeamMemberRemovalsUnavailableError;
7331
7609
  }
7332
7610
  function completionConflictError(cause) {
7333
7611
  return new Error("team_setup_completion_conflict", { cause });
@@ -7348,7 +7626,9 @@ function groupCompletionFailureHandler(groups, handleFailure) {
7348
7626
  }
7349
7627
  /** The safe cause behind a retryable completion failure, when one is known. */
7350
7628
  function completionFailureReason(error) {
7351
- 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";
7352
7632
  }
7353
7633
  function completionBlocker(error) {
7354
7634
  const code = apiErrorCode(new Error(completionApiError(error)));
@@ -7378,19 +7658,41 @@ function summaryReconciliationOptions(blockingErrors) {
7378
7658
  }
7379
7659
  };
7380
7660
  }
7381
- 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) {
7382
7667
  const keysDir = process.env.CODEMEM_KEYS_DIR?.trim() || void 0;
7383
- 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();
7384
7674
  return fetchPeerRemovalLookup(store, config, {
7385
7675
  localDeviceId,
7386
7676
  keysDir
7387
7677
  });
7388
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
+ }
7389
7690
  var defaultCompletionDependencies = {
7390
7691
  create: coordinatorCreateLegacyTeamCompletionAction,
7391
7692
  get: coordinatorGetLegacyTeamCompletionAction,
7392
7693
  list: coordinatorListLegacyTeamCompletionsAction,
7393
7694
  listRemovals: coordinatorListRemovedDevicesAction,
7695
+ listTeamMemberRemovals: coordinatorListTeamMemberRemovalsAction,
7394
7696
  lookupPeerRemovals: lookupPeerRemovalsAsDaemon
7395
7697
  };
7396
7698
  var defaultSnapshotLoaderDependencies = {
@@ -7761,43 +8063,267 @@ function blockedCandidateSummary(store, group, blocker) {
7761
8063
  unresolvedProjectCount: 0
7762
8064
  };
7763
8065
  }
7764
- function pendingCandidateSummaries(store, groups, blockingErrors) {
7765
- const pending = readPureCandidateViews(store, groups.filter((group) => !blockingErrors.has(legacyTeamCandidateId(group.coordinatorId, group.groupId)))).map(candidateSummary).filter((candidate) => candidate.status !== "ready");
7766
- const blocked = groups.flatMap((group) => {
7767
- const error = blockingErrors.get(legacyTeamCandidateId(group.coordinatorId, group.groupId));
7768
- 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()
7769
8182
  });
7770
- return [...pending, ...blocked].toSorted((left, right) => {
7771
- if (left.candidateRef < right.candidateRef) return -1;
7772
- 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];
7773
8245
  });
7774
8246
  }
7775
- async function reconcileSummaryCandidates(store, groups, reconcile) {
7776
- readPureCandidateViews(store, groups);
7777
- const blockingErrors = /* @__PURE__ */ new Map();
7778
- 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 };
7779
8254
  return {
7780
8255
  version: TEAM_SETUP_VERSION,
7781
- candidates: pendingCandidateSummaries(store, groups, blockingErrors)
8256
+ candidates: read.result ? checkedCandidateSummaries(store, read.result) : localDraftCandidateSummaries(store),
8257
+ reconciliation: read.status
7782
8258
  };
7783
8259
  }
7784
- function readPureCandidateViews(store, groups) {
7785
- const existing = [];
7786
- const discoverable = [];
7787
- for (const group of groups) {
7788
- 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 [];
7789
8270
  const draft = getLegacyTeamSetupDraft(store.db, candidateRef);
7790
- if (hasCompletedLegacyTeamSetup(store, candidateRef)) {
7791
- if (isLegacyTeamCandidateSelectable(store.db, candidateRef)) discoverable.push(group);
7792
- continue;
7793
- }
7794
- if (!draft || draft.state === "completed") {
7795
- discoverable.push(group);
7796
- continue;
7797
- }
7798
- existing.push(candidateFromDraft(draft));
7799
- }
7800
- 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
+ })();
7801
8327
  }
7802
8328
  function hasCompletedLegacyTeamSetup(store, candidateRef) {
7803
8329
  return Boolean(store.db.prepare(`SELECT 1 FROM policy_teams
@@ -8223,6 +8749,36 @@ var TeamSetupFinishError = class extends Error {
8223
8749
  }
8224
8750
  };
8225
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
+ /**
8226
8782
  * The generic `legacy_team_setup_roster_too_large` string is thrown by ten
8227
8783
  * sites for unrelated limits (coordinator roster size, draft device count,
8228
8784
  * local project choices). Only the local project-candidate scan is a
@@ -8593,10 +9149,47 @@ function completionReadActions(dependencies, { authorization, store }, timeoutS,
8593
9149
  listCompletionRecords,
8594
9150
  removalReads: {
8595
9151
  listRemovals,
8596
- 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
+ }
8597
9167
  }
8598
9168
  };
8599
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
+ }
8600
9193
  async function readRemovalEvidence(reads) {
8601
9194
  return {
8602
9195
  deviceRemovals: await reads.listRemovals(),
@@ -8655,7 +9248,7 @@ function teamSetupRoutes(options) {
8655
9248
  }
8656
9249
  }
8657
9250
  const loadedSummarySnapshots = createLoadedSummarySnapshotCache(loadedSnapshots, options);
8658
- options.registerSummaryInvalidator?.(() => loadedSummarySnapshots.invalidate());
9251
+ const reconciliation = createSummaryReconciliation(options, loadedSummarySnapshots, reconcileCompletions);
8659
9252
  const completionDependencies = options.completionDependencies === void 0 ? defaultCompletionDependencies : options.completionDependencies;
8660
9253
  const currentCompletionAuthorization = () => readCompletionAuthorization(options);
8661
9254
  function hasDraftEditAuthority(store, candidateRef) {
@@ -8717,16 +9310,17 @@ function teamSetupRoutes(options) {
8717
9310
  */
8718
9311
  async function applyCanonicalManifestIfStillAuthorized(store, authorization, group, manifest, freshRoster, reads) {
8719
9312
  const freshIds = new Set(freshRoster.map((device) => device.deviceId));
8720
- 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);
8721
9315
  let outcome = "unauthorized";
8722
9316
  return await runCandidateMutation(store.db, legacyTeamCandidateId(group.coordinatorId, group.groupId), () => serializeCanonicalManifestMutation(store, group.groupId, manifest, async (actorIds) => {
8723
9317
  if (!stillAuthorizesGroup(authorization, group)) return;
8724
- await applyLegacyTeamSetupCompletionManifest(store.db, {
9318
+ await applyCompletionAfterTeamMemberRemovals(store, evidence.teamMemberRemovals, {
8725
9319
  coordinatorId: group.coordinatorId,
8726
9320
  groupId: group.groupId,
8727
9321
  manifest,
8728
9322
  freshRoster,
8729
- ...removalEvidence,
9323
+ ...evidence.removalEvidence,
8730
9324
  recipientPolicyLocksHeld: completionRecipientPolicyLocksHeld(actorIds)
8731
9325
  });
8732
9326
  outcome = "applied";
@@ -8986,17 +9580,10 @@ function teamSetupRoutes(options) {
8986
9580
  groupId: row.group_id
8987
9581
  };
8988
9582
  }
8989
- app.get("/api/sync/team-setup/v1", async (c) => {
8990
- let groups;
9583
+ app.get("/api/sync/team-setup/v1", (c) => {
8991
9584
  try {
8992
- groups = await loadedSummarySnapshots();
8993
- } catch (error) {
8994
- const failure = teamSetupFailure(error, `${c.req.method} ${c.req.routePath}`);
8995
- return c.json({ error: failure.code }, failure.status);
8996
- }
8997
- try {
8998
- const response = await reconcileSummaryCandidates(options.getStore(), groups, reconcileCompletions);
8999
- 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);
9000
9587
  } catch (error) {
9001
9588
  const failure = teamSetupFailure(error, `${c.req.method} ${c.req.routePath}`);
9002
9589
  return c.json({ error: failure.code }, failure.status);
@@ -9378,7 +9965,11 @@ function teamSetupRoutes(options) {
9378
9965
  throw error;
9379
9966
  }
9380
9967
  if (!postPublicationGroup) throw new TeamSetupFinishError("team_setup_roster_unavailable", "coordinator_roster_unavailable", false, /* @__PURE__ */ new Error("coordinator roster unavailable"));
9381
- const result = await applyLegacyTeamSetupCompletionManifestAndReturnActivation(store.db, {
9968
+ const result = await applyFinishWinnerAfterRemovals({
9969
+ store,
9970
+ dependencies: completionDependencies,
9971
+ config
9972
+ }, {
9382
9973
  coordinatorId: group.coordinatorId,
9383
9974
  groupId: group.groupId,
9384
9975
  freshRoster: postPublicationGroup.devices,
@@ -10656,12 +11247,42 @@ async function completeCoordinatorEnrollment(context, initial, completeDeviceSet
10656
11247
  if (!hasCanonicalOwnEnrollment(context, enrollments)) throw new Error(setup.kind === "unknown" ? "completion_outcome_unknown" : "device_setup_enrollment_incomplete");
10657
11248
  return enrollments;
10658
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
+ }
10659
11281
  async function reconcileConfiguredCoordinatorGroup(store, groupId, config, options) {
10660
11282
  const remoteUrl = config.syncCoordinatorUrl.trim();
10661
11283
  const adminSecret = config.syncCoordinatorAdminSecret.trim();
10662
11284
  const listDevices = options.listDevices ?? coordinatorListDevicesAction;
10663
11285
  const listInvites = options.listConsumedTeamInvites ?? coordinatorListConsumedTeamInvitesAction;
10664
- const listRemovals = options.listTeamMemberRemovals ?? coordinatorListTeamMemberRemovalsAction;
10665
11286
  const reconcile = options.reconcileSnapshot ?? ((input) => reconcileCoordinatorEnrollmentSnapshot(store.db, input));
10666
11287
  let stage = "complete_device_setup";
10667
11288
  try {
@@ -10689,11 +11310,12 @@ async function reconcileConfiguredCoordinatorGroup(store, groupId, config, optio
10689
11310
  remoteUrl,
10690
11311
  adminSecret
10691
11312
  });
10692
- const teamMemberRemovals = await listRemovals({
11313
+ const { teamMemberRemovals, teamGroupBindings } = await readTeamEvidence(store, options, {
10693
11314
  groupId,
10694
11315
  remoteUrl,
10695
- adminSecret
10696
- }).catch(() => void 0);
11316
+ adminSecret,
11317
+ invites
11318
+ });
10697
11319
  stage = "complete_device_setup";
10698
11320
  context.assertCurrent();
10699
11321
  stage = "reconcile_snapshot";
@@ -10703,6 +11325,7 @@ async function reconcileConfiguredCoordinatorGroup(store, groupId, config, optio
10703
11325
  enrollments,
10704
11326
  consumedTeamInvites: invites,
10705
11327
  teamMemberRemovals,
11328
+ teamGroupBindings,
10706
11329
  localDeviceId: store.deviceId
10707
11330
  }) };
10708
11331
  } catch (error) {
@@ -11123,7 +11746,12 @@ function summarizeMaintenanceJobs(jobs, showDiagnostics) {
11123
11746
  }
11124
11747
  function redactSemanticIndexDiagnostics(diagnostics, showDiagnostics) {
11125
11748
  if (showDiagnostics || !diagnostics.maintenance_job) return diagnostics;
11126
- 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;
11127
11755
  return {
11128
11756
  ...diagnostics,
11129
11757
  summary,
@@ -11640,16 +12268,30 @@ function peerAuthorizedScopes(store, peerDeviceId) {
11640
12268
  function isPendingCaptureActorConflict(error) {
11641
12269
  return error instanceof Error && error.constructor === Error && error.message === "device_adoption_actor_conflict";
11642
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
+ }
11643
12290
  /** False leaves the conflict untouched; callers must check before claiming or merging identity. */
11644
12291
  function ensureLocalActorRecord(store) {
12292
+ if (!store.hasPendingLocalCapture() && localActorRecordCurrent(store)) return localIdentityMayClaimActor(store);
11645
12293
  return store.db.transaction(() => {
11646
- store.assertLocalIdentityCurrent();
11647
- try {
11648
- store.assertPendingLocalCaptureAdoptionActors();
11649
- } catch (error) {
11650
- if (isPendingCaptureActorConflict(error)) return false;
11651
- throw error;
11652
- }
12294
+ if (!localIdentityMayClaimActor(store)) return false;
11653
12295
  persistLocalActorRecord(store);
11654
12296
  return true;
11655
12297
  }).immediate();
@@ -12535,7 +13177,8 @@ function attemptStatus(attempt) {
12535
13177
  }
12536
13178
  function readViewerBinding(dbPath) {
12537
13179
  try {
12538
- const raw = readFileSync(join(dirname(dbPath), "viewer.pid"), "utf8");
13180
+ const raw = readViewerPidFile(dbPath);
13181
+ if (raw === null) return null;
12539
13182
  const parsed = JSON.parse(raw);
12540
13183
  if (typeof parsed.host === "string" && typeof parsed.port === "number") return {
12541
13184
  host: parsed.host,
@@ -13882,12 +14525,32 @@ function previewRecipientInvitation(store, body) {
13882
14525
  };
13883
14526
  }
13884
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
+ }
13885
14542
  async function issueRecipientInvitation(store, body, kind, targetId, preview) {
13886
14543
  const config = readCoordinatorSyncConfig();
13887
14544
  const status = coordinatorAdminStatusPayload(config);
13888
14545
  const reviewedIntent = recipientInviteReviewedIntent(store, kind, targetId, preview);
13889
14546
  const reviewedPreviewDigest = await recipientReviewedIntentDigest(reviewedIntent);
13890
- const groupId = resolveCoordinatorAdminGroup(optionalViewerString(body, "group_id"), status);
14547
+ const groupId = recipientInvitationGroup(store, {
14548
+ body,
14549
+ kind,
14550
+ targetId,
14551
+ config,
14552
+ status
14553
+ });
13891
14554
  const ttlHours = parseInviteTtlHours(body.ttl_hours);
13892
14555
  if (!groupId) throw new Error("group_id_required");
13893
14556
  if (ttlHours == null) throw new Error("ttl_hours_invalid");
@@ -13947,6 +14610,11 @@ async function createRecipientInvitation(store, body) {
13947
14610
  }
13948
14611
  };
13949
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
+ };
13950
14618
  return {
13951
14619
  httpStatus: 400,
13952
14620
  body: { error: error instanceof Error ? error.message : "recipient_invite_failed" }
@@ -17485,8 +18153,18 @@ function teamCreationUnavailable(status) {
17485
18153
  function isCreateTeamBody(body) {
17486
18154
  return Boolean(body) && typeof body === "object" && !Array.isArray(body) && Object.keys(body).length === 1 && typeof body.displayName === "string";
17487
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
+ }
17488
18165
  async function createTeam(c, getStore, readConfig) {
17489
- const unavailable = teamCreationUnavailable(coordinatorAdminStatusPayload(readConfig()));
18166
+ const config = readConfig();
18167
+ const unavailable = teamCreationUnavailable(coordinatorAdminStatusPayload(config));
17490
18168
  if (unavailable) return c.json({ error: unavailable.code }, unavailable.httpStatus);
17491
18169
  const body = await parseViewerJsonBody(c);
17492
18170
  if (!isCreateTeamBody(body)) return c.json({ error: "team_name_invalid" }, 400);
@@ -17496,7 +18174,8 @@ async function createTeam(c, getStore, readConfig) {
17496
18174
  const team = createRecipientPolicyTeam(store.db, {
17497
18175
  displayName: body.displayName,
17498
18176
  creatorIdentityId: store.actorId,
17499
- now: (/* @__PURE__ */ new Date()).toISOString()
18177
+ now: (/* @__PURE__ */ new Date()).toISOString(),
18178
+ coordinatorGroup: invitationGroup(config)
17500
18179
  });
17501
18180
  return c.json(team, 201);
17502
18181
  } catch (error) {
@@ -17510,6 +18189,118 @@ function teamCreateRoutes(getStore, readCoordinatorConfig = readCoordinatorSyncC
17510
18189
  return app;
17511
18190
  }
17512
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
17513
18304
  //#region src/routes/update-status.ts
17514
18305
  function updateStatusRoutes(options = {}) {
17515
18306
  const getUpdateStatus$1 = options.getUpdateStatus ?? getUpdateStatus;
@@ -18148,6 +18939,8 @@ var memoryItems = sqliteTable("memory_items", {
18148
18939
  index("idx_memory_items_active_created").on(table.active, table.created_at),
18149
18940
  index("idx_memory_items_created_id").on(table.created_at, table.id),
18150
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),
18151
18944
  index("idx_memory_items_session").on(table.session_id),
18152
18945
  index("idx_memory_items_project").on(table.project),
18153
18946
  index("idx_memory_items_scope_visibility_created").on(table.scope_id, table.visibility, table.created_at),
@@ -18403,7 +19196,9 @@ sqliteTable("raw_event_flush_batches", {
18403
19196
  index("idx_flush_batches_session_created").on(table.opencode_session_id, table.created_at),
18404
19197
  index("idx_flush_batches_status_updated").on(table.status, table.updated_at),
18405
19198
  index("idx_flush_batches_observer_status_updated").on(table.status, table.updated_at).where(sql`${table.observer_provider} IS NOT NULL`),
18406
- 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`)
18407
19202
  ]);
18408
19203
  sqliteTable("user_prompts", {
18409
19204
  id: integer("id").primaryKey(),
@@ -18725,6 +19520,22 @@ sqliteTable("policy_team_member_removals", {
18725
19520
  table.team_id,
18726
19521
  table.identity_id
18727
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] })]);
18728
19539
  sqliteTable("identity_devices", {
18729
19540
  device_id: text("device_id").primaryKey(),
18730
19541
  identity_id: text("identity_id").notNull(),
@@ -20552,11 +21363,12 @@ function registerStaticRoutes(app) {
20552
21363
  return c.html(indexHtml);
20553
21364
  });
20554
21365
  }
20555
- function registerConfigRoutes(app, opts, sweeper) {
21366
+ function registerConfigRoutes(app, opts, sweeper, onCoordinatorConfigChanged) {
20556
21367
  app.route("/", configRoutes({
20557
21368
  getSweeper: () => sweeper,
20558
21369
  scheduleObserverApply: opts?.scheduleObserverApply,
20559
- getObserverApplyStatus: opts?.getObserverApplyStatus
21370
+ getObserverApplyStatus: opts?.getObserverApplyStatus,
21371
+ onCoordinatorConfigChanged
20560
21372
  }));
20561
21373
  }
20562
21374
  function registerViewerBoundary(app, opts) {
@@ -20665,12 +21477,13 @@ function createApp(opts) {
20665
21477
  getSweeper: () => sweeper,
20666
21478
  getObserver
20667
21479
  }));
20668
- registerConfigRoutes(app, opts, sweeper);
21480
+ registerConfigRoutes(app, opts, sweeper, () => invalidateTeamSetupSummary());
20669
21481
  app.route("/", rawEventsRoutes(storeFactory, sweeper, opts?.rawEventInbox, opts?.rawEventTarget));
20670
21482
  installRecipientAccessChangeGate(app, storeFactory, opts?.readCoordinatorConfig);
20671
21483
  registerViewerSyncRoutes(app, storeFactory, opts, () => invalidateTeamSetupSummary());
20672
21484
  registerViewerDeviceRemoval(app, storeFactory, opts);
20673
21485
  app.route("/", teamCreateRoutes(storeFactory, opts?.readCoordinatorConfig));
21486
+ app.route("/", teamMemberRemovalRoutes(storeFactory, { readCoordinatorConfig: opts?.readCoordinatorConfig }));
20674
21487
  app.route("/", projectWithdrawalRoutes(storeFactory));
20675
21488
  app.route("/", teamSetupRoutes({
20676
21489
  getStore: storeFactory,
@@ -20679,12 +21492,18 @@ function createApp(opts) {
20679
21492
  readCoordinatorConfig: opts?.readCoordinatorConfig,
20680
21493
  registerSummaryInvalidator: (invalidate) => {
20681
21494
  invalidateTeamSetupSummary = invalidate;
20682
- }
21495
+ },
21496
+ registerReconciliation: (reconciliation) => startTeamSetupReconciliation(reconciliation, opts)
20683
21497
  }));
20684
21498
  app.route("/", updateStatusRoutes({ getUpdateStatus: opts?.getUpdateStatus }));
20685
21499
  registerStaticRoutes(app);
20686
21500
  return app;
20687
21501
  }
21502
+ function startTeamSetupReconciliation(reconciliation, opts) {
21503
+ opts?.onTeamSetupReconciliation?.(reconciliation);
21504
+ const intervalMs = opts?.teamSetupReconciliationIntervalMs;
21505
+ if (intervalMs) reconciliation.startPeriodic(intervalMs);
21506
+ }
20688
21507
  /** Preserve the public server options while transport adapters use the narrower factory. */
20689
21508
  function createSyncApp(opts) {
20690
21509
  return createSyncApp$1(opts);