@codemem/server 0.47.3 → 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.
@@ -0,0 +1,51 @@
1
+ import { type MemoryStore } from "@codemem/core";
2
+ export interface DirectionEvidence {
3
+ lastAttemptAt: string | null;
4
+ lastSuccessAt: string | null;
5
+ operations24h: number | null;
6
+ errorCode: string | null;
7
+ snapshotItems24h?: number | null;
8
+ observedSince?: string | null;
9
+ }
10
+ export interface DirectionSyncHealth {
11
+ state: "succeeded" | "not_verified" | "stale" | "needs_attention";
12
+ last_attempt_at: string | null;
13
+ last_success_at: string | null;
14
+ operations_24h: number | null;
15
+ pending_count: number | null;
16
+ reason_code: string | null;
17
+ snapshot_items_24h?: number | null;
18
+ observed_since?: string | null;
19
+ }
20
+ export interface PeerSyncHealth {
21
+ state: "exchange_succeeded" | "not_verified" | "stale" | "needs_attention";
22
+ send: DirectionSyncHealth;
23
+ receive: DirectionSyncHealth;
24
+ }
25
+ export declare function directionSyncHealth(evidence: DirectionEvidence | undefined, options: {
26
+ now: number;
27
+ staleAfterMs?: number;
28
+ }): DirectionSyncHealth;
29
+ export declare function peerSyncHealth(evidence: {
30
+ send: DirectionEvidence;
31
+ receive: DirectionEvidence;
32
+ } | undefined, options: {
33
+ now: number;
34
+ failedAt?: string | null;
35
+ staleAfterMs?: number;
36
+ }): PeerSyncHealth;
37
+ export declare function readPeerSyncHealth(store: MemoryStore, peerIds: string[]): Map<string, PeerSyncHealth>;
38
+ export declare function overallSyncHealth(peers: Array<{
39
+ pinned?: unknown;
40
+ sync_health?: unknown;
41
+ }>, options: {
42
+ enabled: boolean;
43
+ daemonState?: unknown;
44
+ }): {
45
+ state: string;
46
+ peer_count: number;
47
+ attention_count: number;
48
+ unverified_count: number;
49
+ stale_count: number;
50
+ };
51
+ //# sourceMappingURL=sync-health.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sync-health.d.ts","sourceRoot":"","sources":["../../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B,CAAC,EAAE,MAAM,iBAAiB,GAAG,IAAI,CAAC;IACtD,UAAU,EAAE,oBAAoB,CAAC;CACjC;AAqBD,UAAU,mBAAmB;IAC5B,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC;IACjC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC9B;AAmGD,wBAAgB,mBAAmB,CAClC,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAClC,qBAAqB,GAAG,mBAAmB,GAAG,IAAI,CAMpD;AAkND,wBAAgB,mBAAmB,CAClC,KAAK,EAAE,WAAW,EAClB,aAAa,EAAE,GAAG,CAAC,MAAM,CAAC,EAC1B,WAAW,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,OAAO,GACtC,GAAG,CAAC,MAAM,CAAC,CA2Bb;AAmBD,wBAAgB,mBAAmB,CAClC,KAAK,EAAE,mBAAmB,EAC1B,aAAa,EAAE,GAAG,CAAC,MAAM,CAAC,GACxB,MAAM,CAYR;AAwDD,wBAAsB,uBAAuB,CAC5C,KAAK,EAAE,eAAe,GACpB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAqDlC"}
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, 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, 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, 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";
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),
@@ -10578,8 +10687,11 @@ function staleRowsForCleanupDiagnostics(store, localDeviceId) {
10578
10687
  maxRows: CLEANUP_DIAGNOSTICS_MAX_ROWS
10579
10688
  });
10580
10689
  }
10581
- function applyInboundSyncOps(store, ops, localDeviceId) {
10582
- 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
+ });
10583
10695
  }
10584
10696
  function cleanupDiagnostics(store, localDeviceId, showDiag) {
10585
10697
  const opRows = store.db.prepare(`SELECT
@@ -11110,11 +11222,15 @@ function createPeerScopeDiagnosticKeyLoader() {
11110
11222
  }
11111
11223
  function readPeerScopeDiagnostics(store, showDiag) {
11112
11224
  const rows = store.db.prepare(PEERS_QUERY).all();
11225
+ const health = readPeerSyncHealth(store, rows.map((row) => String(row.peer_device_id)));
11113
11226
  const recentOpsByPeer = recentPeerOps(store);
11114
11227
  const scopeRejectionsByPeer = recentScopeRejectionsByPeer(store);
11115
11228
  const localDeviceId = drizzle(store.db, { schema }).select({ device_id: schema.syncDevice.device_id }).from(schema.syncDevice).limit(1).get()?.device_id ?? null;
11116
11229
  const loadDiagnosticKey = createPeerScopeDiagnosticKeyLoader();
11117
- 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
+ }));
11118
11234
  }
11119
11235
  function validateManagedScopes(scopeIds, context) {
11120
11236
  for (const scopeId of scopeIds) {
@@ -11165,19 +11281,33 @@ function rejectUnauthorizedInboundBatch(c, ops, context, options) {
11165
11281
  enabled: options.enabled,
11166
11282
  peerDeviceId: context.peerDeviceId
11167
11283
  });
11168
- if (rejected) return c.json({
11169
- error: "scope_rejected",
11170
- reason: rejected.rejections[0]?.reason ?? "scope_mismatch",
11171
- rejections: rejected.rejections,
11172
- sync_capability: LOCAL_SYNC_CAPABILITY,
11173
- scope_id: options.scopeId
11174
- }, 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
+ }
11175
11294
  const scopeIds = new Set(options.managedScopeIds);
11176
11295
  addExistingMutationScopes(context.db, ops, scopeIds);
11177
11296
  const failure = validateManagedScopes(scopeIds, context);
11178
11297
  if (!failure) return null;
11298
+ recordInboundScopeFailure(context);
11179
11299
  return c.json(syncScopeResetRequiredPayload(getSyncResetState(context.db), failure.reason, LOCAL_SYNC_CAPABILITY, failure.scopeId), 409);
11180
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
+ }
11181
11311
  function serveAuthorizedSnapshot(c, store, auth) {
11182
11312
  const peerDeviceId = auth.deviceId;
11183
11313
  try {
@@ -11405,7 +11535,7 @@ function syncProtocolRoutes(getStore, opts = {}) {
11405
11535
  ...scopeContext,
11406
11536
  negotiatedCapability: negotiated
11407
11537
  });
11408
- 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);
11409
11539
  if (!Array.isArray(body.ops)) return c.json({ error: "invalid_ops" }, 400);
11410
11540
  if (body.ops.length > MAX_SYNC_OPS) return c.json({ error: "too_many_ops" }, 413);
11411
11541
  const normalizedOps = extractReplicationOps(body);
@@ -11437,7 +11567,7 @@ function syncProtocolRoutes(getStore, opts = {}) {
11437
11567
  managedScopeIds: scopeIds
11438
11568
  });
11439
11569
  if (rejected) return rejected;
11440
- const result = applyInboundSyncOps(store, filtered.allowed, localDeviceId);
11570
+ const result = applyInboundSyncOps(store, filtered.allowed, localDeviceId, peerDeviceId);
11441
11571
  const skipped = result.skipped + filtered.skipped;
11442
11572
  return c.json({
11443
11573
  ...result,