@codemem/server 0.47.2 → 0.47.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, LegacyTeamSetupRosterCapacityError, 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, 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, applyReplicationOps, areLegacyTeamSetupCompletionPolicyFactsAdditivelyCompatible, assertNoLocalIdentityOverride, automaticRecallHealth, buildAuthHeaders, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildFilterBranchesWithContext, buildFilterClausesWithContext, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromCodexHook, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildViewerIdentityTarget, canonicalCoordinatorLegacyTeamCompletionManifestJson, canonicalMemoryKind, canonicalRepositoryProjectIdentity, canonicalWorkspaceIdentity, captureAccountOwnerProfilePins, changeCoordinatorAccount, claimRecipientPolicyActorMutations, claimRecipientPolicyPublicationMutation, classifyRecordedSyncFailure, cleanupNonces, clearLegacyTeamSetupDeviceDecision, clonePromptPackAttempt, coerceObserverCommand, commitDeviceIdentityBindings, commitRecipientPolicyEdges, completeLocalIdentitySwitch, containLegacyTeamSetupCompletionConflict, coordinatorArchiveGroupAction, coordinatorAuthControllerReviewAction, coordinatorCreateAddDeviceInviteAction, coordinatorCreateGroupAction, coordinatorCreateInviteAction, coordinatorCreateLegacyTeamCompletionAction, coordinatorCreateScopeAction, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorGetLegacyTeamCompletionAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListConsumedTeamInvitesAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListReviewedRecipientInviteEvidenceAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorRenameGroupAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeScopeMembershipAction, coordinatorStatusSnapshot, coordinatorUnarchiveGroupAction, coordinatorUpdateScopeAction, countShareableProjectMemories, createCoordinatorReciprocalApproval, decodeInvitePayload, dedupeOrderedIds, defaultSpaceScopeIdForGroup, deleteProjectScopeSettingsMapping, deriveLegacyTeamSetupCompletionManifest, detectInstallKind, deterministicPolicyTeamId, diagnoseStalePeerReceivedRows, discoverLegacyTeamCandidates, dispatchFileContextTransport, ensureDeviceIdentity, executeShareProvisioning, extractInvitePayload, extractReplicationOps, filterReplicationOpsForSyncWithStatus, fingerprintPublicKey, formatHostPort, friendlyDeviceName, fromJson, generateWithOpenCodeV2, getCodememConfigPath, getCodememEnvOverrideValues, getCodememEnvOverrides, getCoordinatorEnrollmentReconciliationIssueSummary, getCoordinatorGroupPreference, getEffectiveCachedScopeAuthorization, getLegacyTeamSetupDraft, getRecipientPolicyAuthorityState, getSemanticIndexDiagnostics, getSyncResetState, getUpdateStatus, ingestRawEvents, inspectFreshLegacyTeamSetupActivation, inspectLegacyTeamSetupActivation, inviteTokenDigest, isAutomaticRecallMeasurement, isLegacyTeamCandidateSelectable, isLegacyTeamSetupProjectMappingIdentity, isPeerTrustBindingCompatible, isProjectSyncEnablementError, isScopedSyncCapability, judgeDistillReport, legacyDecisionCountsAsOwner, legacyTeamCandidateId, legacyTeamCandidateProjectInventory, legacyTeamCanonicalProjectRef, legacyTeamDeviceRef, legacyTeamResolvedProjectRef, legacyTeamSetupApiErrorCode, linkCoordinatorAccount, listAuthorizedScopesForPeer, listCoordinatorJoinRequests, listDeviceIdentityInventory, listInboundScopeRejections, listLegacyRecipientPolicyProjections, listMaintenanceJobs, listObserverProviderOptions, listOpenCodeV2Models, listPerPeerScopeSyncState, listProjectScopeCandidates, listProjectScopeInventory, listProjectScopeSettingsMappings, listRecipientPolicyIntent, listRecipientPolicyReview, listSharingDomainSettingsScopes, loadMemorySnapshotPageForPeer, loadPublicKey, loadReplicationOpsForPeer, loadRuntimeSigningPublicKey, lookupCoordinatorPeers, markLocalIdentitySwitchBound, markLocalIdentitySwitchNotCommitted, memoryFilterValueMatchesType, mergeAddresses, migrateRecipientPolicyIntent, mutateCodememConfigFile, negotiateSyncCapability, 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, projectShareLifecycle, promptPackArtifactFingerprint, readAccountLinkDevice, readAccountOwnerAssociation, readAccountOwnerAssociationRetainedAtMs, readCodememConfigFile, readCompletedLocalIdentitySwitches, readCoordinatorAccountChangeCapabilities, readCoordinatorAccountLinkStatus, readCoordinatorResolvedAccountOwnerReceiptStatus, readCoordinatorResolvedAccountOwnerStatus, readCoordinatorSyncConfig, readOpenLocalIdentitySwitch, reassignProjectScopeInventoryProject, recipientInviteAuthoritativeIdentityId, recipientPolicyDigest, recipientReviewedIntentDigest, reconcileCoordinatorEnrollmentSnapshot, reconcileRecipientPolicyProject, reconcileShareOperationAcceptance, reconstructLegacyTeamSetupCompletionManifest, recordAutomaticRecall, recordHighestObservedDirectSignatureVersion, recordLocalIdentitySwitch, recordNonce, recordPromptPackArtifacts, recordPromptPackTerminal, refreshAuthorizedCoordinatorPeerTrust, refreshConfiguredScopeMembershipCache, refreshLegacyTeamCandidate, rejectInboundScopeFailures, renameRecipientPolicyTeam, replayLegacyTeamSetupActivation, repositoryIdentitiesByWorkspace, repositoryIdentityForWorkspace, requestJson, requireLegacyTeamSetupAccessDeltaWithinLimit, resolveCodememConfigPath, resolveDbPath, resolveObserverDefaultModel, resolveObserverRuntime, resolveProject, resolveProjectRoot, resolveRecipientPolicyReview, resolveRecipientPolicyReviewBulk, resolveVisibleScopeIds, resumeDeviceRebind, runDeviceRebind, runSyncPass, schema, scopeAuthorizationFailureReason, searchPiSessions, serializeRecipientPolicyCoordinatorGroupMutation, serializeRecipientPolicyPublicationMutation, serializeRecipientPolicyTeamMutation, setLegacyTeamSetupDeviceAssignment, setLegacyTeamSetupDeviceDecision, setLegacyTeamSetupProjectMapping, summarizeInboundScopeRejections, summaryLikeSqlPredicate, supportsSyncFeature, syncScopeResetRequiredPayload, toJson, tryUpdateRetrievalDelivery, updatePeerAddresses, upsertCoordinatorGroupPreference, upsertProjectScopeSettingsMappings, validateLegacyTeamSetupCompletionManifest, validateLegacyTeamSetupCompletionManifestBinding, validateRawEvents, 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, LegacyTeamSetupRosterCapacityError, 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, 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, canonicalMemoryKind, canonicalRepositoryProjectIdentity, canonicalWorkspaceIdentity, captureAccountOwnerProfilePins, changeCoordinatorAccount, claimRecipientPolicyActorMutations, claimRecipientPolicyPublicationMutation, classifyRecordedSyncFailure, cleanupNonces, clearLegacyTeamSetupDeviceDecision, clonePromptPackAttempt, coerceObserverCommand, commitDeviceIdentityBindings, commitRecipientPolicyEdges, completeLocalIdentitySwitch, containLegacyTeamSetupCompletionConflict, coordinatorArchiveGroupAction, coordinatorAuthControllerReviewAction, coordinatorCreateAddDeviceInviteAction, coordinatorCreateGroupAction, coordinatorCreateInviteAction, coordinatorCreateLegacyTeamCompletionAction, coordinatorCreateScopeAction, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorGetLegacyTeamCompletionAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListConsumedTeamInvitesAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListReviewedRecipientInviteEvidenceAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorRenameGroupAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeScopeMembershipAction, coordinatorStatusSnapshot, coordinatorUnarchiveGroupAction, coordinatorUpdateScopeAction, countShareableProjectMemories, createCoordinatorReciprocalApproval, decodeInvitePayload, dedupeOrderedIds, defaultSpaceScopeIdForGroup, deleteProjectScopeSettingsMapping, deriveLegacyTeamSetupCompletionManifest, detectInstallKind, deterministicPolicyTeamId, diagnoseStalePeerReceivedRows, discoverLegacyTeamCandidates, dispatchFileContextTransport, ensureDeviceIdentity, executeShareProvisioning, extractInvitePayload, extractReplicationOps, filterReplicationOpsForSyncWithStatus, fingerprintPublicKey, formatHostPort, friendlyDeviceName, fromJson, generateWithOpenCodeV2, getCodememConfigPath, getCodememEnvOverrideValues, getCodememEnvOverrides, getCoordinatorEnrollmentReconciliationIssueSummary, getCoordinatorGroupPreference, getEffectiveCachedScopeAuthorization, getLegacyTeamSetupDraft, getRecipientPolicyAuthorityState, getSemanticIndexDiagnostics, getSyncResetState, getUpdateStatus, ingestRawEvents, inspectFreshLegacyTeamSetupActivation, inspectLegacyTeamSetupActivation, inviteTokenDigest, isAutomaticRecallMeasurement, isLegacyTeamCandidateSelectable, isLegacyTeamSetupProjectMappingIdentity, isPeerTrustBindingCompatible, isProjectSyncEnablementError, isScopedSyncCapability, judgeDistillReport, legacyDecisionCountsAsOwner, 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, loadPublicKey, loadReplicationOpsForPeer, loadRuntimeSigningPublicKey, lookupCoordinatorPeers, markLocalIdentitySwitchBound, markLocalIdentitySwitchNotCommitted, memoryFilterValueMatchesType, mergeAddresses, migrateRecipientPolicyIntent, mutateCodememConfigFile, negotiateSyncCapability, 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, projectShareLifecycle, promptPackArtifactFingerprint, readAccountLinkDevice, readAccountOwnerAssociation, readAccountOwnerAssociationRetainedAtMs, readCodememConfigFile, readCompletedLocalIdentitySwitches, readCoordinatorAccountChangeCapabilities, readCoordinatorAccountLinkStatus, readCoordinatorResolvedAccountOwnerReceiptStatus, readCoordinatorResolvedAccountOwnerStatus, readCoordinatorSyncConfig, readOpenLocalIdentitySwitch, readPeerSyncActivity, reassignProjectScopeInventoryProject, recipientInviteAuthoritativeIdentityId, recipientPolicyDigest, recipientReviewedIntentDigest, reconcileCoordinatorEnrollmentSnapshot, reconcileRecipientPolicyProject, reconcileShareOperationAcceptance, reconstructLegacyTeamSetupCompletionManifest, recordAutomaticRecall, recordHighestObservedDirectSignatureVersion, recordLocalIdentitySwitch, recordNonce, recordPromptPackArtifacts, recordPromptPackTerminal, recordSyncTransferObservation, refreshAuthorizedCoordinatorPeerTrust, refreshConfiguredScopeMembershipCache, refreshLegacyTeamCandidate, rejectInboundScopeFailures, renameRecipientPolicyTeam, replayLegacyTeamSetupActivation, repositoryIdentitiesByWorkspace, repositoryIdentityForWorkspace, requestJson, requireLegacyTeamSetupAccessDeltaWithinLimit, resolveCodememConfigPath, resolveDbPath, resolveObserverDefaultModel, resolveObserverRuntime, resolveProject, resolveProjectRoot, resolveRecipientPolicyReview, resolveRecipientPolicyReviewBulk, resolveVisibleScopeIds, resumeDeviceRebind, runDeviceRebind, runSyncPass, schema, scopeAuthorizationFailureReason, searchPiSessions, serializeRecipientPolicyActorMutations, serializeRecipientPolicyCoordinatorGroupMutation, serializeRecipientPolicyPublicationMutation, serializeRecipientPolicyTeamMutation, setLegacyTeamSetupDeviceAssignment, setLegacyTeamSetupDeviceDecision, setLegacyTeamSetupProjectMapping, summarizeInboundScopeRejections, summaryLikeSqlPredicate, supportsSyncFeature, syncScopeResetRequiredPayload, toJson, tryUpdateRetrievalDelivery, updatePeerAddresses, upsertCoordinatorGroupPreference, upsertProjectScopeSettingsMappings, validateLegacyTeamSetupCompletionManifest, validateLegacyTeamSetupCompletionManifestBinding, validateRawEvents, 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, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
@@ -1296,7 +1296,7 @@ function recoveryRecord(value) {
1296
1296
  function exactRecoveryFields(row, fields) {
1297
1297
  requireRecovery(Object.keys(row).length === fields.length && fields.every((key) => Object.hasOwn(row, key)));
1298
1298
  }
1299
- function timestamp(value) {
1299
+ function timestamp$1(value) {
1300
1300
  return typeof value === "string" && Number.isFinite(Date.parse(value));
1301
1301
  }
1302
1302
  function readWeakLabel(value) {
@@ -1323,7 +1323,7 @@ function readWeakLabel(value) {
1323
1323
  }
1324
1324
  function historyRows$1(value, selection, labels) {
1325
1325
  const row = recoveryRecord(value);
1326
- requireRecovery(recoveryId(row.group_id) && recoveryId(row.candidate_ref) && timestamp(row.created_at));
1326
+ requireRecovery(recoveryId(row.group_id) && recoveryId(row.candidate_ref) && timestamp$1(row.created_at));
1327
1327
  const manifest = normalizeCoordinatorLegacyTeamCompletionManifest(row.manifest);
1328
1328
  requireRecovery(manifest.coordinator_id === selection.profile.coordinatorId && manifest.candidate_ref === row.candidate_ref && manifest.version === row.manifest_version && manifest.completed_at === row.completed_at && legacyTeamCandidateId(manifest.coordinator_id, row.group_id) === manifest.candidate_ref && canonicalCoordinatorLegacyTeamCompletionManifestJson(manifest) === row.manifest_json);
1329
1329
  const groupId = row.group_id;
@@ -1352,7 +1352,7 @@ function receiptPart(value, idField) {
1352
1352
  "created_at"
1353
1353
  ]);
1354
1354
  const id = row[idField];
1355
- requireRecovery(recoveryId(id) && recoveryHash(row.evidence_digest) && timestamp(row.created_at) && (row.disposition === "created" || row.disposition === "reused"));
1355
+ requireRecovery(recoveryId(id) && recoveryHash(row.evidence_digest) && timestamp$1(row.created_at) && (row.disposition === "created" || row.disposition === "reused"));
1356
1356
  return {
1357
1357
  id,
1358
1358
  digest: row.evidence_digest
@@ -5782,6 +5782,100 @@ async function reconcileRecipientPolicyProjectsOperation(store, options) {
5782
5782
  return result;
5783
5783
  }
5784
5784
  //#endregion
5785
+ //#region src/application/sync-health.ts
5786
+ var STALE_AFTER_MS = 6e5;
5787
+ function timestamp(value) {
5788
+ if (!value) return null;
5789
+ const parsed = Date.parse(value);
5790
+ return Number.isFinite(parsed) ? parsed : null;
5791
+ }
5792
+ function safeReasonCode(value) {
5793
+ if (!value) return null;
5794
+ if ([
5795
+ "transfer_failed",
5796
+ "apply_failed",
5797
+ "snapshot_failed",
5798
+ "scope_rejected"
5799
+ ].includes(value)) return value;
5800
+ return "transfer_failed";
5801
+ }
5802
+ function directionSyncHealth(evidence, options) {
5803
+ return {
5804
+ state: directionState(evidence, options),
5805
+ last_attempt_at: evidence?.lastAttemptAt ?? null,
5806
+ last_success_at: evidence?.lastSuccessAt ?? null,
5807
+ operations_24h: evidence?.operations24h ?? null,
5808
+ snapshot_items_24h: evidence?.snapshotItems24h ?? null,
5809
+ observed_since: evidence?.observedSince ?? null,
5810
+ pending_count: null,
5811
+ reason_code: safeReasonCode(evidence?.errorCode)
5812
+ };
5813
+ }
5814
+ function directionState(evidence, options) {
5815
+ if (evidence?.errorCode) return "needs_attention";
5816
+ const success = timestamp(evidence?.lastSuccessAt ?? null);
5817
+ if (success === null || success > options.now) return "not_verified";
5818
+ return options.now - success <= (options.staleAfterMs ?? STALE_AFTER_MS) ? "succeeded" : "stale";
5819
+ }
5820
+ function unresolvedExchangeFailure(send, receive, options) {
5821
+ const failedAt = timestamp(options.failedAt ?? null);
5822
+ if (failedAt === null || failedAt > options.now) return false;
5823
+ return failedAt >= Math.min(timestamp(send.last_success_at) ?? 0, timestamp(receive.last_success_at) ?? 0);
5824
+ }
5825
+ function peerSyncHealth(evidence, options) {
5826
+ const send = directionSyncHealth(evidence?.send, options);
5827
+ const receive = directionSyncHealth(evidence?.receive, options);
5828
+ const states = [send.state, receive.state];
5829
+ let state = "exchange_succeeded";
5830
+ if (states.includes("needs_attention") || unresolvedExchangeFailure(send, receive, options)) state = "needs_attention";
5831
+ else if (states.includes("not_verified")) state = "not_verified";
5832
+ else if (states.includes("stale")) state = "stale";
5833
+ return {
5834
+ state,
5835
+ send,
5836
+ receive
5837
+ };
5838
+ }
5839
+ function readPeerSyncHealth(store, peerIds) {
5840
+ const now = Date.now();
5841
+ const staleAfterMs = Math.max(STALE_AFTER_MS, readCoordinatorSyncConfig().syncIntervalS * 3e3);
5842
+ const activity = readPeerSyncActivity(store.db, peerIds, { now: new Date(now).toISOString() });
5843
+ const latest = store.db.prepare(`
5844
+ SELECT p.peer_device_id, a.ok, a.finished_at FROM sync_peers p
5845
+ JOIN sync_attempts a ON a.id = (
5846
+ SELECT id FROM sync_attempts WHERE peer_device_id = p.peer_device_id
5847
+ ORDER BY started_at DESC, id DESC LIMIT 1
5848
+ )`);
5849
+ const failed = /* @__PURE__ */ new Map();
5850
+ for (const row of latest.all()) if (!row.ok && row.finished_at) failed.set(row.peer_device_id, row.finished_at);
5851
+ return new Map(peerIds.map((id) => [id, peerSyncHealth(activity.get(id), {
5852
+ now,
5853
+ staleAfterMs,
5854
+ failedAt: failed.get(id)
5855
+ })]));
5856
+ }
5857
+ function overallSyncHealth(peers, options) {
5858
+ const paired = peers.filter((peer) => peer.pinned);
5859
+ const states = paired.map((peer) => peer.sync_health?.state);
5860
+ const attention = states.filter((state) => state === "needs_attention").length;
5861
+ const unverified = states.filter((state) => !state || state === "not_verified").length;
5862
+ const stale = states.filter((state) => state === "stale").length;
5863
+ const daemonFailed = ["error", "needs_attention"].includes(String(options.daemonState));
5864
+ let state = "exchange_succeeded";
5865
+ if (!options.enabled) state = "disabled";
5866
+ else if (daemonFailed || attention > 0) state = "needs_attention";
5867
+ else if (paired.length === 0) state = "no_peers";
5868
+ else if (unverified > 0) state = "not_verified";
5869
+ else if (stale > 0) state = "stale";
5870
+ return {
5871
+ state,
5872
+ peer_count: paired.length,
5873
+ attention_count: attention,
5874
+ unverified_count: unverified,
5875
+ stale_count: stale
5876
+ };
5877
+ }
5878
+ //#endregion
5785
5879
  //#region src/application/sync-status.ts
5786
5880
  var SAFE_RUNTIME_DETAILS = {
5787
5881
  starting: "Running initial sync in background",
@@ -5942,9 +6036,11 @@ function readPeerStatus(input, localDeviceId) {
5942
6036
  const rows = traceSync("peerRows", () => input.store.db.prepare(PEERS_QUERY$1).all());
5943
6037
  const recentOperations = traceSync("recentPeerOps", () => input.operations.recentPeerOps(input.store));
5944
6038
  const scopeRejections = traceSync("recentScopeRejectionsByPeer", () => input.operations.recentScopeRejectionsByPeer(input.store));
6039
+ const health = readPeerSyncHealth(input.store, rows.map((row) => String(row.peer_device_id)));
5945
6040
  const items = rows.map((row) => {
5946
6041
  const peer = input.operations.mapPeerRow(input.store, row, input.showDiagnostics, recentOperations, scopeRejections, localDeviceId);
5947
6042
  peer.status = input.operations.peerStatus(peer);
6043
+ peer.sync_health = health.get(String(peer.peer_device_id));
5948
6044
  return peer;
5949
6045
  });
5950
6046
  const byId = {};
@@ -6040,6 +6136,20 @@ async function readJoinRequests(input, config) {
6040
6136
  return [];
6041
6137
  }
6042
6138
  }
6139
+ function addSyncHealth(base, peers, status) {
6140
+ const health = overallSyncHealth(peers.items, {
6141
+ enabled: base.config.syncEnabled,
6142
+ daemonState: status.daemon_state
6143
+ });
6144
+ status.sync_health = health;
6145
+ return health;
6146
+ }
6147
+ function markPeerFailures(peers, failedPeerIds) {
6148
+ for (const peer of peers.items) {
6149
+ const status = peer.status;
6150
+ status.recent_failed_attempt = failedPeerIds.has(String(peer.peer_device_id ?? ""));
6151
+ }
6152
+ }
6043
6153
  async function buildSyncStatusResponse(input) {
6044
6154
  const base = readBaseStatus(input);
6045
6155
  const coordinatorSnapshot = await coordinatorStatusSnapshot(input.store, base.config);
@@ -6048,10 +6158,7 @@ async function buildSyncStatusResponse(input) {
6048
6158
  const attempts = readAttemptStatus(input);
6049
6159
  const activePeerIds = new Set(peers.items.map((peer) => String(peer.peer_device_id ?? "")));
6050
6160
  const failedPeerIds = latestFailedPeerIds(input.store, activePeerIds, input.operations.isRecentIso);
6051
- for (const peer of peers.items) {
6052
- const status = peer.status;
6053
- status.recent_failed_attempt = failedPeerIds.has(String(peer.peer_device_id ?? ""));
6054
- }
6161
+ markPeerFailures(peers, failedPeerIds);
6055
6162
  const statusBlock = {
6056
6163
  ...base.statusPayload,
6057
6164
  background_maintenance: input.operations.summarizeMaintenanceJobs(listMaintenanceJobs(input.store.db), input.showDiagnostics),
@@ -6066,8 +6173,10 @@ async function buildSyncStatusResponse(input) {
6066
6173
  const recipientPolicyReconciliation = traceSync("recipientPolicyReconciliation", () => input.operations.listRecipientPolicyReconciliationStatus(input.store));
6067
6174
  const joinRequests = await readJoinRequests(input, base.config);
6068
6175
  applyDerivedDaemonState(base, peers, attempts, failedPeerIds, statusBlock);
6176
+ const syncHealth = addSyncHealth(base, peers, statusBlock);
6069
6177
  const response = {
6070
6178
  ...base.statusPayload,
6179
+ sync_health: syncHealth,
6071
6180
  status: statusBlock,
6072
6181
  peers: peers.items,
6073
6182
  attempts: attempts.items.slice(0, 5),
@@ -6360,6 +6469,23 @@ var MAX_PROJECT_MAPPING_METADATA_ROWS = 1e4;
6360
6469
  var MAX_MUTATION_BODY_BYTES = 8192;
6361
6470
  var SUMMARY_SNAPSHOT_CACHE_TTL_MS = 3e4;
6362
6471
  var COORDINATOR_ROSTER_READ_BUDGET_MS = 6e4;
6472
+ function serializeCanonicalManifestMutation(store, groupId, manifest, operation) {
6473
+ return serializeRecipientPolicyPublicationMutation(store.db, () => {
6474
+ const actorIds = legacyTeamSetupCompletionActorIds(store.db, manifest);
6475
+ return serializeRecipientPolicyActorMutations(store.db, actorIds, () => serializeRecipientPolicyTeamMutation(store.db, manifest.team_id, () => serializeRecipientPolicyCoordinatorGroupMutation(store.db, groupId, () => operation(actorIds))));
6476
+ });
6477
+ }
6478
+ function finishDraftActorIds(draft) {
6479
+ return draft.devices.flatMap((device) => [...device.decision === "included" && device.targetIdentityId ? [device.targetIdentityId] : [], ...device.existingIdentityId ? [device.existingIdentityId] : []]);
6480
+ }
6481
+ function completionRecipientPolicyLocksHeld(actorIds) {
6482
+ return {
6483
+ publication: true,
6484
+ actors: actorIds,
6485
+ team: true,
6486
+ coordinatorGroup: true
6487
+ };
6488
+ }
6363
6489
  var TEAM_SETUP_ROUTE_PREFIX = "/api/sync/team-setup/v1";
6364
6490
  var CANDIDATE_REF_PATTERN = /^legacy-team-candidate:[0-9a-f]{32}$/u;
6365
6491
  var DEVICE_REF_PATTERN = /^legacy-team-device-ref-v1:[0-9a-f]{64}$/u;
@@ -6405,6 +6531,47 @@ async function runCandidateMutation(db, candidateRef, operation) {
6405
6531
  release();
6406
6532
  }
6407
6533
  }
6534
+ function completionFailureHandlers(options) {
6535
+ const handledGroupIds = /* @__PURE__ */ new Set();
6536
+ const reportFailure = (group, error) => {
6537
+ handledGroupIds.add(group.groupId);
6538
+ options.onFailure?.(group, error);
6539
+ };
6540
+ const handleFailure = (group, error) => {
6541
+ if (!options.isolateApplyFailures) throw error;
6542
+ reportFailure(group, error);
6543
+ };
6544
+ return {
6545
+ handledGroupIds,
6546
+ handleFailure,
6547
+ reportFailure
6548
+ };
6549
+ }
6550
+ function completionConflictError(cause) {
6551
+ return new Error("team_setup_completion_conflict", { cause });
6552
+ }
6553
+ function addFreshCompletionGroups(index, groups, keyOf) {
6554
+ for (const group of groups) {
6555
+ if (!group) continue;
6556
+ const key = keyOf(group);
6557
+ if (index.has(key)) throw new Error("team_setup_completion_invalid");
6558
+ index.set(key, group);
6559
+ }
6560
+ }
6561
+ function groupCompletionFailureHandler(groups, handleFailure) {
6562
+ return (groupId, error) => {
6563
+ const group = groups.get(groupId);
6564
+ if (group) handleFailure(group, error);
6565
+ };
6566
+ }
6567
+ function summaryReconciliationOptions(blockingErrors) {
6568
+ return {
6569
+ isolateApplyFailures: true,
6570
+ onFailure: (group, error) => {
6571
+ blockingErrors.set(legacyTeamCandidateId(group.coordinatorId, group.groupId), apiErrorCode(new Error(completionApiError(error))));
6572
+ }
6573
+ };
6574
+ }
6408
6575
  var defaultCompletionDependencies = {
6409
6576
  create: coordinatorCreateLegacyTeamCompletionAction,
6410
6577
  get: coordinatorGetLegacyTeamCompletionAction,
@@ -6496,13 +6663,17 @@ function isUnsupportedCompletionQuery(error) {
6496
6663
  function isUnattributableCompletionBatchError(error) {
6497
6664
  return error instanceof Error && (error.message === "coordinator_completion_response_malformed" || error.message === "coordinator_completion_group_mismatch");
6498
6665
  }
6499
- async function listCompletionRecordsPerGroup(groupIds, list) {
6500
- if (groupIds.length < 2) return [];
6666
+ async function listCompletionRecordsPerGroup(groupIds, list, onFailure, batchError) {
6667
+ if (groupIds.length === 1) {
6668
+ onFailure(groupIds[0], batchError);
6669
+ return [];
6670
+ }
6501
6671
  const records = [];
6502
6672
  for (const groupId of groupIds) try {
6503
6673
  records.push(...await list([groupId]));
6504
6674
  } catch (error) {
6505
6675
  if (!isUnattributableCompletionBatchError(error)) throw error;
6676
+ onFailure(groupId, error);
6506
6677
  }
6507
6678
  return records;
6508
6679
  }
@@ -6736,6 +6907,55 @@ function candidateFromDraft(draft) {
6736
6907
  unresolvedProjectCount: draft.unresolvedProjectCount
6737
6908
  };
6738
6909
  }
6910
+ function blockedCandidateSummary(store, group, blockingError) {
6911
+ const candidateRef = legacyTeamCandidateId(group.coordinatorId, group.groupId);
6912
+ const draft = getLegacyTeamSetupDraft(store.db, candidateRef);
6913
+ if (draft) return {
6914
+ ...candidateSummary(candidateFromDraft(draft)),
6915
+ status: "stale",
6916
+ blockingError
6917
+ };
6918
+ const forbiddenIds = [
6919
+ group.coordinatorId,
6920
+ group.groupId,
6921
+ candidateRef,
6922
+ ...group.devices.flatMap((device) => [
6923
+ device.deviceId,
6924
+ device.fingerprint,
6925
+ ...device.labelRedactionIds ?? []
6926
+ ])
6927
+ ];
6928
+ return {
6929
+ candidateRef,
6930
+ displayName: safeChoiceLabel(group.displayName, "Legacy Team", forbiddenIds),
6931
+ status: "stale",
6932
+ blockingError,
6933
+ deviceCount: group.devices.length,
6934
+ projectCount: 0,
6935
+ unresolvedDeviceCount: 0,
6936
+ unresolvedProjectCount: 0
6937
+ };
6938
+ }
6939
+ function pendingCandidateSummaries(store, groups, blockingErrors) {
6940
+ const pending = readPureCandidateViews(store, groups.filter((group) => !blockingErrors.has(legacyTeamCandidateId(group.coordinatorId, group.groupId)))).map(candidateSummary).filter((candidate) => candidate.status !== "ready");
6941
+ const blocked = groups.flatMap((group) => {
6942
+ const error = blockingErrors.get(legacyTeamCandidateId(group.coordinatorId, group.groupId));
6943
+ return error ? [blockedCandidateSummary(store, group, error)] : [];
6944
+ });
6945
+ return [...pending, ...blocked].toSorted((left, right) => {
6946
+ if (left.candidateRef < right.candidateRef) return -1;
6947
+ return left.candidateRef > right.candidateRef ? 1 : 0;
6948
+ });
6949
+ }
6950
+ async function reconcileSummaryCandidates(store, groups, reconcile) {
6951
+ readPureCandidateViews(store, groups);
6952
+ const blockingErrors = /* @__PURE__ */ new Map();
6953
+ await reconcile(store, groups, summaryReconciliationOptions(blockingErrors));
6954
+ return {
6955
+ version: TEAM_SETUP_VERSION,
6956
+ candidates: pendingCandidateSummaries(store, groups, blockingErrors)
6957
+ };
6958
+ }
6739
6959
  function readPureCandidateViews(store, groups) {
6740
6960
  const existing = [];
6741
6961
  const discoverable = [];
@@ -7100,6 +7320,20 @@ function apiErrorCode(error) {
7100
7320
  const code = legacyTeamSetupApiErrorCode(error);
7101
7321
  return code === "team_setup_projection_changed" ? "team_setup_conflict" : code;
7102
7322
  }
7323
+ /**
7324
+ * Maps a setup failure to its API code and logs the internal check that raised
7325
+ * it. Dozens of checks share each public code, so the log is the only place an
7326
+ * operator can see which one failed.
7327
+ */
7328
+ function teamSetupFailure(error, route) {
7329
+ const code = apiErrorCode(error);
7330
+ const check = legacyTeamSetupFailureCheck(error);
7331
+ console.warn(`[team-setup] route=${route} apiCode=${code}${check ? ` check=${check}` : ""}`);
7332
+ return {
7333
+ code,
7334
+ status: errorStatus$1(code)
7335
+ };
7336
+ }
7103
7337
  function completionApiError(error) {
7104
7338
  const code = legacyTeamSetupApiErrorCode(error);
7105
7339
  return code === "team_setup_failed" ? "team_setup_completion_unavailable" : code;
@@ -7438,29 +7672,26 @@ function teamSetupRoutes(options) {
7438
7672
  */
7439
7673
  async function applyCanonicalManifestIfStillAuthorized(store, authorization, group, manifest, freshRoster) {
7440
7674
  let outcome = "unauthorized";
7441
- return await runCandidateMutation(store.db, legacyTeamCandidateId(group.coordinatorId, group.groupId), () => serializeRecipientPolicyPublicationMutation(store.db, () => serializeRecipientPolicyTeamMutation(store.db, manifest.team_id, () => serializeRecipientPolicyCoordinatorGroupMutation(store.db, group.groupId, async () => {
7675
+ return await runCandidateMutation(store.db, legacyTeamCandidateId(group.coordinatorId, group.groupId), () => serializeCanonicalManifestMutation(store, group.groupId, manifest, async (actorIds) => {
7442
7676
  if (!stillAuthorizesGroup(authorization, group)) return;
7443
7677
  await applyLegacyTeamSetupCompletionManifest(store.db, {
7444
7678
  coordinatorId: group.coordinatorId,
7445
7679
  groupId: group.groupId,
7446
7680
  manifest,
7447
7681
  freshRoster,
7448
- recipientPolicyLocksHeld: {
7449
- publication: true,
7450
- team: true,
7451
- coordinatorGroup: true
7452
- }
7682
+ recipientPolicyLocksHeld: completionRecipientPolicyLocksHeld(actorIds)
7453
7683
  });
7454
7684
  outcome = "applied";
7455
- })))) ? outcome : "claimed";
7685
+ })) ? outcome : "claimed";
7456
7686
  }
7457
7687
  async function reconcileCompletions(store, groups, reconciliationOptions = {}) {
7688
+ const { handledGroupIds, handleFailure, reportFailure } = completionFailureHandlers(reconciliationOptions);
7458
7689
  if (!completionDependencies || groups.length === 0) return;
7459
7690
  let authorization;
7460
7691
  try {
7461
7692
  authorization = currentCompletionAuthorization();
7462
7693
  } catch (error) {
7463
- throw new Error(completionApiError(error));
7694
+ throw new Error(completionApiError(error), { cause: error });
7464
7695
  }
7465
7696
  if (!authorization) return;
7466
7697
  const { config, remoteUrl } = authorization;
@@ -7482,30 +7713,25 @@ function teamSetupRoutes(options) {
7482
7713
  records = await listCompletionRecords(scopedGroupIds);
7483
7714
  } catch (error) {
7484
7715
  if (isUnsupportedCompletionQuery(error)) records = [];
7485
- else if (reconciliationOptions.isolateApplyFailures && isUnattributableCompletionBatchError(error)) records = await listCompletionRecordsPerGroup(scopedGroupIds, listCompletionRecords);
7716
+ else if (reconciliationOptions.isolateApplyFailures && isUnattributableCompletionBatchError(error)) records = await listCompletionRecordsPerGroup(scopedGroupIds, listCompletionRecords, groupCompletionFailureHandler(groupById, handleFailure), error);
7486
7717
  else throw error;
7487
7718
  }
7488
7719
  const freshGroupByKey = /* @__PURE__ */ new Map();
7489
7720
  if (records.length > 0) try {
7490
7721
  const onlyGroup = scopedGroups.length === 1 ? scopedGroups[0] : void 0;
7491
- const freshGroups = onlyGroup ? [await loadFreshGroupSnapshot(onlyGroup, remoteUrl, reconciliationDeadlineMs)] : await loadedSnapshots(void 0, reconciliationDeadlineMs);
7492
- for (const freshGroup of freshGroups) {
7493
- if (!freshGroup) continue;
7494
- const key = freshGroupKey(freshGroup);
7495
- if (freshGroupByKey.has(key)) throw new Error("team_setup_completion_invalid");
7496
- freshGroupByKey.set(key, freshGroup);
7497
- }
7722
+ addFreshCompletionGroups(freshGroupByKey, onlyGroup ? [await loadFreshGroupSnapshot(onlyGroup, remoteUrl, reconciliationDeadlineMs)] : await loadedSnapshots(void 0, reconciliationDeadlineMs), freshGroupKey);
7498
7723
  } catch (error) {
7499
7724
  for (const record of records) {
7500
7725
  const group = groupById.get(record.group_id);
7501
7726
  if (!group || !belongsToGroupCandidate(record, group)) continue;
7727
+ reportFailure(group, error);
7502
7728
  try {
7503
7729
  validateLegacyTeamSetupCompletionManifestBinding(record.manifest, {
7504
7730
  coordinatorId: group.coordinatorId,
7505
7731
  groupId: group.groupId
7506
7732
  });
7507
7733
  } catch (bindingError) {
7508
- if (!reconciliationOptions.isolateApplyFailures) throw bindingError;
7734
+ handleFailure(group, bindingError);
7509
7735
  continue;
7510
7736
  }
7511
7737
  let canonicalManifest;
@@ -7515,16 +7741,17 @@ function teamSetupRoutes(options) {
7515
7741
  groupId: group.groupId
7516
7742
  });
7517
7743
  } catch (validationError) {
7744
+ reportFailure(group, validationError);
7518
7745
  try {
7519
7746
  if (!await runCandidateMutation(store.db, legacyTeamCandidateId(group.coordinatorId, group.groupId), () => containLegacyTeamSetupCompletionConflict(store.db, {
7520
7747
  coordinatorId: group.coordinatorId,
7521
7748
  groupId: group.groupId
7522
7749
  }))) {
7523
- if (!reconciliationOptions.isolateApplyFailures) throw validationError;
7750
+ handleFailure(group, validationError);
7524
7751
  continue;
7525
7752
  }
7526
7753
  } catch (containmentError) {
7527
- if (!reconciliationOptions.isolateApplyFailures) throw containmentError;
7754
+ handleFailure(group, containmentError);
7528
7755
  }
7529
7756
  if (!reconciliationOptions.isolateApplyFailures) throw validationError;
7530
7757
  continue;
@@ -7540,13 +7767,12 @@ function teamSetupRoutes(options) {
7540
7767
  groupId: group.groupId
7541
7768
  }));
7542
7769
  } catch (containmentError) {
7543
- if (!reconciliationOptions.isolateApplyFailures) throw containmentError;
7770
+ handleFailure(group, containmentError);
7544
7771
  }
7545
7772
  }
7546
7773
  if (!reconciliationOptions.isolateApplyFailures) throw error;
7547
7774
  return;
7548
7775
  }
7549
- const coordinatorCompletionGroupIds = /* @__PURE__ */ new Set();
7550
7776
  for (const record of records) {
7551
7777
  const group = groupById.get(record.group_id);
7552
7778
  if (!group) throw new Error("team_setup_completion_invalid");
@@ -7557,7 +7783,7 @@ function teamSetupRoutes(options) {
7557
7783
  groupId: group.groupId
7558
7784
  });
7559
7785
  } catch (bindingError) {
7560
- if (!reconciliationOptions.isolateApplyFailures) throw bindingError;
7786
+ handleFailure(group, bindingError);
7561
7787
  continue;
7562
7788
  }
7563
7789
  let canonicalManifest;
@@ -7567,18 +7793,19 @@ function teamSetupRoutes(options) {
7567
7793
  groupId: group.groupId
7568
7794
  });
7569
7795
  } catch (validationError) {
7796
+ reportFailure(group, validationError);
7570
7797
  try {
7571
7798
  await runCandidateMutation(store.db, legacyTeamCandidateId(group.coordinatorId, group.groupId), () => containLegacyTeamSetupCompletionConflict(store.db, {
7572
7799
  coordinatorId: group.coordinatorId,
7573
7800
  groupId: group.groupId
7574
7801
  }));
7575
7802
  } catch (containmentError) {
7576
- if (!reconciliationOptions.isolateApplyFailures) throw containmentError;
7803
+ handleFailure(group, containmentError);
7577
7804
  }
7578
7805
  if (!reconciliationOptions.isolateApplyFailures) throw validationError;
7579
7806
  continue;
7580
7807
  }
7581
- coordinatorCompletionGroupIds.add(record.group_id);
7808
+ handledGroupIds.add(record.group_id);
7582
7809
  try {
7583
7810
  let freshGroup = freshGroupByKey.get(freshGroupKey(group));
7584
7811
  if (!freshGroup && scopedGroups.length > 1) {
@@ -7590,18 +7817,18 @@ function teamSetupRoutes(options) {
7590
7817
  coordinatorId: group.coordinatorId,
7591
7818
  groupId: group.groupId
7592
7819
  }))) {
7593
- if (!reconciliationOptions.isolateApplyFailures) throw new Error("team_setup_completion_invalid");
7820
+ handleFailure(group, /* @__PURE__ */ new Error("team_setup_completion_invalid"));
7594
7821
  continue;
7595
7822
  }
7596
7823
  throw new Error("team_setup_completion_invalid");
7597
7824
  }
7598
7825
  if (await applyCanonicalManifestIfStillAuthorized(store, authorization, group, canonicalManifest, freshGroup.devices) !== "applied") continue;
7599
7826
  } catch (error) {
7600
- if (!reconciliationOptions.isolateApplyFailures) throw error;
7827
+ handleFailure(group, error);
7601
7828
  }
7602
7829
  }
7603
7830
  for (const group of scopedGroups) {
7604
- if (coordinatorCompletionGroupIds.has(group.groupId)) continue;
7831
+ if (handledGroupIds.has(group.groupId)) continue;
7605
7832
  const publicationTimeoutS = remainingCoordinatorTimeoutS(timeoutS, reconciliationDeadlineMs);
7606
7833
  if (publicationTimeoutS == null) break;
7607
7834
  if (!hasCompletedLegacyTeamSetup(store, legacyTeamCandidateId(group.coordinatorId, group.groupId))) continue;
@@ -7648,14 +7875,14 @@ function teamSetupRoutes(options) {
7648
7875
  coordinatorId: group.coordinatorId,
7649
7876
  groupId: group.groupId
7650
7877
  }))) {
7651
- if (!reconciliationOptions.isolateApplyFailures) throw new Error("team_setup_completion_conflict");
7878
+ handleFailure(group, /* @__PURE__ */ new Error("team_setup_completion_conflict"));
7652
7879
  continue;
7653
7880
  }
7654
7881
  } catch (containmentError) {
7655
- if (!reconciliationOptions.isolateApplyFailures) throw containmentError;
7882
+ handleFailure(group, containmentError);
7656
7883
  continue;
7657
7884
  }
7658
- if (!reconciliationOptions.isolateApplyFailures) throw new Error("team_setup_completion_conflict");
7885
+ handleFailure(group, /* @__PURE__ */ new Error("team_setup_completion_conflict"));
7659
7886
  continue;
7660
7887
  }
7661
7888
  try {
@@ -7664,7 +7891,7 @@ function teamSetupRoutes(options) {
7664
7891
  if (await applyCanonicalManifestIfStillAuthorized(store, authorization, group, canonicalManifest, freshGroup.devices) !== "applied") continue;
7665
7892
  } catch (applyError) {
7666
7893
  if (applyError instanceof LegacyTeamSetupAdditiveConvergenceError) {
7667
- if (!reconciliationOptions.isolateApplyFailures) throw applyError;
7894
+ handleFailure(group, applyError);
7668
7895
  continue;
7669
7896
  }
7670
7897
  try {
@@ -7672,19 +7899,19 @@ function teamSetupRoutes(options) {
7672
7899
  coordinatorId: group.coordinatorId,
7673
7900
  groupId: group.groupId
7674
7901
  }))) {
7675
- if (!reconciliationOptions.isolateApplyFailures) throw new Error("team_setup_completion_conflict", { cause: applyError });
7902
+ handleFailure(group, completionConflictError(applyError));
7676
7903
  continue;
7677
7904
  }
7678
7905
  } catch (containmentError) {
7679
- if (!reconciliationOptions.isolateApplyFailures) throw containmentError;
7906
+ handleFailure(group, containmentError);
7680
7907
  continue;
7681
7908
  }
7682
- if (!reconciliationOptions.isolateApplyFailures) throw new Error("team_setup_completion_conflict", { cause: applyError });
7909
+ handleFailure(group, completionConflictError(applyError));
7683
7910
  }
7684
7911
  }
7685
7912
  }
7686
7913
  } catch (error) {
7687
- throw new Error(completionApiError(error));
7914
+ throw new Error(completionApiError(error), { cause: error });
7688
7915
  }
7689
7916
  }
7690
7917
  async function loadedCandidateSnapshots(candidateRef, loadOptions = {}) {
@@ -7718,21 +7945,15 @@ function teamSetupRoutes(options) {
7718
7945
  try {
7719
7946
  groups = await loadedSummarySnapshots();
7720
7947
  } catch (error) {
7721
- const code = apiErrorCode(error);
7722
- return c.json({ error: code }, errorStatus$1(code));
7948
+ const failure = teamSetupFailure(error, `${c.req.method} ${c.req.routePath}`);
7949
+ return c.json({ error: failure.code }, failure.status);
7723
7950
  }
7724
7951
  try {
7725
- const store = options.getStore();
7726
- readPureCandidateViews(store, groups);
7727
- await reconcileCompletions(store, groups, { isolateApplyFailures: true });
7728
- const response = {
7729
- version: TEAM_SETUP_VERSION,
7730
- candidates: readPureCandidateViews(store, groups).map(candidateSummary).filter((candidate) => candidate.status !== "ready")
7731
- };
7952
+ const response = await reconcileSummaryCandidates(options.getStore(), groups, reconcileCompletions);
7732
7953
  return c.json(response);
7733
7954
  } catch (error) {
7734
- const code = apiErrorCode(error);
7735
- return c.json({ error: code }, errorStatus$1(code));
7955
+ const failure = teamSetupFailure(error, `${c.req.method} ${c.req.routePath}`);
7956
+ return c.json({ error: failure.code }, failure.status);
7736
7957
  }
7737
7958
  });
7738
7959
  app.get("/api/sync/team-setup/v1/:candidateRef", async (c) => {
@@ -7778,8 +7999,8 @@ function teamSetupRoutes(options) {
7778
7999
  if (completionGroups) candidate = candidateFromDraft(draft);
7779
8000
  return c.json(detailResponse(store, draft, candidate));
7780
8001
  } catch (error) {
7781
- const code = apiErrorCode(error);
7782
- return c.json({ error: code }, errorStatus$1(code));
8002
+ const failure = teamSetupFailure(error, `${c.req.method} ${c.req.routePath}`);
8003
+ return c.json({ error: failure.code }, failure.status);
7783
8004
  }
7784
8005
  });
7785
8006
  app.put("/api/sync/team-setup/v1/:candidateRef/devices/:deviceRef/assignment", async (c) => {
@@ -7824,8 +8045,8 @@ function teamSetupRoutes(options) {
7824
8045
  releaseMutation();
7825
8046
  }
7826
8047
  } catch (error) {
7827
- const code = apiErrorCode(error);
7828
- return c.json({ error: code }, errorStatus$1(code));
8048
+ const failure = teamSetupFailure(error, `${c.req.method} ${c.req.routePath}`);
8049
+ return c.json({ error: failure.code }, failure.status);
7829
8050
  }
7830
8051
  });
7831
8052
  app.put("/api/sync/team-setup/v1/:candidateRef/devices/:deviceRef/decision", async (c) => {
@@ -7866,8 +8087,8 @@ function teamSetupRoutes(options) {
7866
8087
  releaseMutation();
7867
8088
  }
7868
8089
  } catch (error) {
7869
- const code = apiErrorCode(error);
7870
- return c.json({ error: code }, errorStatus$1(code));
8090
+ const failure = teamSetupFailure(error, `${c.req.method} ${c.req.routePath}`);
8091
+ return c.json({ error: failure.code }, failure.status);
7871
8092
  }
7872
8093
  });
7873
8094
  app.delete("/api/sync/team-setup/v1/:candidateRef/devices/:deviceRef/decision", async (c) => {
@@ -7897,8 +8118,8 @@ function teamSetupRoutes(options) {
7897
8118
  releaseMutation();
7898
8119
  }
7899
8120
  } catch (error) {
7900
- const code = apiErrorCode(error);
7901
- return c.json({ error: code }, errorStatus$1(code));
8121
+ const failure = teamSetupFailure(error, `${c.req.method} ${c.req.routePath}`);
8122
+ return c.json({ error: failure.code }, failure.status);
7902
8123
  }
7903
8124
  });
7904
8125
  app.put("/api/sync/team-setup/v1/:candidateRef/projects/:projectRef/mapping", async (c) => {
@@ -7933,8 +8154,8 @@ function teamSetupRoutes(options) {
7933
8154
  releaseMutation();
7934
8155
  }
7935
8156
  } catch (error) {
7936
- const code = apiErrorCode(error);
7937
- return c.json({ error: code }, errorStatus$1(code));
8157
+ const failure = teamSetupFailure(error, `${c.req.method} ${c.req.routePath}`);
8158
+ return c.json({ error: failure.code }, failure.status);
7938
8159
  }
7939
8160
  });
7940
8161
  app.post("/api/sync/team-setup/v1/:candidateRef/refresh", async (c) => {
@@ -7947,15 +8168,15 @@ function teamSetupRoutes(options) {
7947
8168
  store = options.getStore();
7948
8169
  if (getLegacyTeamSetupDraft(store.db, candidateRef)?.state === "completed" || hasCompletedLegacyTeamSetup(store, candidateRef)) return c.json({ error: "team_setup_confirmation_stale" }, 409);
7949
8170
  } catch (error) {
7950
- const code = apiErrorCode(error);
7951
- return c.json({ error: code }, errorStatus$1(code));
8171
+ const failure = teamSetupFailure(error, `${c.req.method} ${c.req.routePath}`);
8172
+ return c.json({ error: failure.code }, failure.status);
7952
8173
  }
7953
8174
  let groups;
7954
8175
  try {
7955
8176
  groups = await loadMutableCandidateSnapshots(store, candidateRef, () => loadedCandidateSnapshots(candidateRef));
7956
8177
  } catch (error) {
7957
- const code = apiErrorCode(error);
7958
- return c.json({ error: code }, errorStatus$1(code));
8178
+ const failure = teamSetupFailure(error, `${c.req.method} ${c.req.routePath}`);
8179
+ return c.json({ error: failure.code }, failure.status);
7959
8180
  }
7960
8181
  if (groups.filter((group) => legacyTeamCandidateId(group.coordinatorId, group.groupId) === candidateRef).length === 0) return c.json({ error: "team_setup_confirmation_stale" }, 404);
7961
8182
  try {
@@ -7973,8 +8194,8 @@ function teamSetupRoutes(options) {
7973
8194
  releaseMutation();
7974
8195
  }
7975
8196
  } catch (error) {
7976
- const code = apiErrorCode(error);
7977
- return c.json({ error: code }, errorStatus$1(code));
8197
+ const failure = teamSetupFailure(error, `${c.req.method} ${c.req.routePath}`);
8198
+ return c.json({ error: failure.code }, failure.status);
7978
8199
  }
7979
8200
  });
7980
8201
  app.post("/api/sync/team-setup/v1/:candidateRef/finish", async (c) => {
@@ -8046,13 +8267,14 @@ function teamSetupRoutes(options) {
8046
8267
  if (!claimedDraft || claimedDraft.attemptId !== attemptId) return c.json({ error: "team_setup_confirmation_stale" }, 409);
8047
8268
  const publicationDeadlineMs = Date.now() + COORDINATOR_ROSTER_READ_BUDGET_MS;
8048
8269
  releasePublicationMutation = await claimRecipientPolicyPublicationMutation(store.db);
8049
- releaseActorMutations = await claimRecipientPolicyActorMutations(store.db, claimedDraft.devices.flatMap((device) => [...device.decision === "included" && device.targetIdentityId ? [device.targetIdentityId] : [], ...device.existingIdentityId ? [device.existingIdentityId] : []]));
8270
+ const claimedActorIds = finishDraftActorIds(claimedDraft);
8271
+ releaseActorMutations = await claimRecipientPolicyActorMutations(store.db, claimedActorIds);
8050
8272
  return await serializeRecipientPolicyTeamMutation(store.db, deterministicPolicyTeamId(candidateRef), () => serializeRecipientPolicyCoordinatorGroupMutation(store.db, group.groupId, async () => {
8051
8273
  let authorization;
8052
8274
  try {
8053
8275
  authorization = currentCompletionAuthorization();
8054
8276
  } catch (error) {
8055
- throw new Error(completionApiError(error));
8277
+ throw new Error(completionApiError(error), { cause: error });
8056
8278
  }
8057
8279
  if (!completionDependencies || !authorization) throw new Error("team_setup_completion_unavailable");
8058
8280
  if (!authorizesGroup(authorization, group)) throw new Error("team_setup_completion_invalid");
@@ -8143,11 +8365,7 @@ function teamSetupRoutes(options) {
8143
8365
  freshRoster: postPublicationGroup.devices,
8144
8366
  manifest: canonicalManifest,
8145
8367
  expectedDraftManifest: proposedManifest,
8146
- recipientPolicyLocksHeld: {
8147
- publication: true,
8148
- team: true,
8149
- coordinatorGroup: true
8150
- }
8368
+ recipientPolicyLocksHeld: completionRecipientPolicyLocksHeld(claimedActorIds)
8151
8369
  });
8152
8370
  return c.json(finishResponse(candidateRef, result));
8153
8371
  }));
@@ -10469,8 +10687,11 @@ function staleRowsForCleanupDiagnostics(store, localDeviceId) {
10469
10687
  maxRows: CLEANUP_DIAGNOSTICS_MAX_ROWS
10470
10688
  });
10471
10689
  }
10472
- function applyInboundSyncOps(store, ops, localDeviceId) {
10473
- return applyReplicationOps(store.db, ops, localDeviceId, store.scanner, { keysDir: syncKeysDir() });
10690
+ function applyInboundSyncOps(store, ops, localDeviceId, peerDeviceId) {
10691
+ return applyPeerReplicationOps(store, ops, localDeviceId, {
10692
+ keysDir: syncKeysDir(),
10693
+ peerDeviceId
10694
+ });
10474
10695
  }
10475
10696
  function cleanupDiagnostics(store, localDeviceId, showDiag) {
10476
10697
  const opRows = store.db.prepare(`SELECT
@@ -11001,11 +11222,15 @@ function createPeerScopeDiagnosticKeyLoader() {
11001
11222
  }
11002
11223
  function readPeerScopeDiagnostics(store, showDiag) {
11003
11224
  const rows = store.db.prepare(PEERS_QUERY).all();
11225
+ const health = readPeerSyncHealth(store, rows.map((row) => String(row.peer_device_id)));
11004
11226
  const recentOpsByPeer = recentPeerOps(store);
11005
11227
  const scopeRejectionsByPeer = recentScopeRejectionsByPeer(store);
11006
11228
  const localDeviceId = drizzle(store.db, { schema }).select({ device_id: schema.syncDevice.device_id }).from(schema.syncDevice).limit(1).get()?.device_id ?? null;
11007
11229
  const loadDiagnosticKey = createPeerScopeDiagnosticKeyLoader();
11008
- return rows.map((row) => mapPeerRow(store, row, showDiag, recentOpsByPeer, scopeRejectionsByPeer, localDeviceId, loadDiagnosticKey));
11230
+ return rows.map((row) => ({
11231
+ ...mapPeerRow(store, row, showDiag, recentOpsByPeer, scopeRejectionsByPeer, localDeviceId, loadDiagnosticKey),
11232
+ sync_health: health.get(String(row.peer_device_id))
11233
+ }));
11009
11234
  }
11010
11235
  function validateManagedScopes(scopeIds, context) {
11011
11236
  for (const scopeId of scopeIds) {
@@ -11056,19 +11281,33 @@ function rejectUnauthorizedInboundBatch(c, ops, context, options) {
11056
11281
  enabled: options.enabled,
11057
11282
  peerDeviceId: context.peerDeviceId
11058
11283
  });
11059
- if (rejected) return c.json({
11060
- error: "scope_rejected",
11061
- reason: rejected.rejections[0]?.reason ?? "scope_mismatch",
11062
- rejections: rejected.rejections,
11063
- sync_capability: LOCAL_SYNC_CAPABILITY,
11064
- scope_id: options.scopeId
11065
- }, 403);
11284
+ if (rejected) {
11285
+ recordInboundScopeFailure(context);
11286
+ return c.json({
11287
+ error: "scope_rejected",
11288
+ reason: rejected.rejections[0]?.reason ?? "scope_mismatch",
11289
+ rejections: rejected.rejections,
11290
+ sync_capability: LOCAL_SYNC_CAPABILITY,
11291
+ scope_id: options.scopeId
11292
+ }, 403);
11293
+ }
11066
11294
  const scopeIds = new Set(options.managedScopeIds);
11067
11295
  addExistingMutationScopes(context.db, ops, scopeIds);
11068
11296
  const failure = validateManagedScopes(scopeIds, context);
11069
11297
  if (!failure) return null;
11298
+ recordInboundScopeFailure(context);
11070
11299
  return c.json(syncScopeResetRequiredPayload(getSyncResetState(context.db), failure.reason, LOCAL_SYNC_CAPABILITY, failure.scopeId), 409);
11071
11300
  }
11301
+ function recordInboundScopeFailure(context) {
11302
+ recordSyncTransferObservation(context.db, context.peerDeviceId, "receive", {
11303
+ errorCode: "scope_rejected",
11304
+ source: "inbound"
11305
+ });
11306
+ }
11307
+ function inboundScopeResetResponse(c, store, reason, context) {
11308
+ recordInboundScopeFailure(context);
11309
+ return c.json(syncScopeResetRequiredPayload(getSyncResetState(store.db), reason, LOCAL_SYNC_CAPABILITY, null), 409);
11310
+ }
11072
11311
  function serveAuthorizedSnapshot(c, store, auth) {
11073
11312
  const peerDeviceId = auth.deviceId;
11074
11313
  try {
@@ -11296,7 +11535,7 @@ function syncProtocolRoutes(getStore, opts = {}) {
11296
11535
  ...scopeContext,
11297
11536
  negotiatedCapability: negotiated
11298
11537
  });
11299
- if (!scopeRequest.ok) return c.json(syncScopeResetRequiredPayload(getSyncResetState(store.db), scopeRequest.reason, LOCAL_SYNC_CAPABILITY, null), 409);
11538
+ if (!scopeRequest.ok) return inboundScopeResetResponse(c, store, scopeRequest.reason, scopeContext);
11300
11539
  if (!Array.isArray(body.ops)) return c.json({ error: "invalid_ops" }, 400);
11301
11540
  if (body.ops.length > MAX_SYNC_OPS) return c.json({ error: "too_many_ops" }, 413);
11302
11541
  const normalizedOps = extractReplicationOps(body);
@@ -11328,7 +11567,7 @@ function syncProtocolRoutes(getStore, opts = {}) {
11328
11567
  managedScopeIds: scopeIds
11329
11568
  });
11330
11569
  if (rejected) return rejected;
11331
- const result = applyInboundSyncOps(store, filtered.allowed, localDeviceId);
11570
+ const result = applyInboundSyncOps(store, filtered.allowed, localDeviceId, peerDeviceId);
11332
11571
  const skipped = result.skipped + filtered.skipped;
11333
11572
  return c.json({
11334
11573
  ...result,