@codemem/server 0.48.1 → 0.49.0-beta.2

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,13 +1,15 @@
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, 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, loadPrivateKey, 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, readRepositoryIdentitySnapshot, reassignProjectScopeInventoryProject, recipientInviteAuthoritativeIdentityId, recipientPolicyDigest, recipientReviewedIntentDigest, reconcileCoordinatorEnrollmentSnapshot, reconcileRecipientPolicyProject, reconcileShareOperationAcceptance, reconstructLegacyTeamSetupCompletionManifest, recordAutomaticRecall, recordHighestObservedDirectSignatureVersion, recordLocalIdentitySwitch, recordNonce, recordPromptPackArtifacts, recordPromptPackTerminal, recordSyncAttempt, 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, setLocalSyncFeature, 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, LocalIdentitySupersededError, MEMORY_FILTER_FIELD_TYPES, MEMORY_FILTER_NAMES, MEMORY_KIND_DESCRIPTIONS, MemoryStore, ObserverClient, PROMPT_TRANSPORT_PROTOCOL_RANGE, REMEMBER_MEMORY_KINDS, RICH_TIER_ANTHROPIC_DEFAULTS, RICH_TIER_DEFAULTS, RawEventIngestValidationError, RecipientPolicyEdgeRequestError, 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, completeCoordinatorDeviceSetup, 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, loadPrivateKey, 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, readCoordinatorDeviceSetup, readCoordinatorResolvedAccountOwnerReceiptStatus, readCoordinatorResolvedAccountOwnerStatus, readCoordinatorSyncConfig, readOpenLocalIdentitySwitch, readPeerSyncActivity, readRepositoryIdentitySnapshot, reassignProjectScopeInventoryProject, recipientInviteAuthoritativeIdentityId, recipientPolicyDigest, recipientReviewedIntentDigest, reconcileCoordinatorEnrollmentSnapshot, reconcileRecipientPolicyProject, reconcileShareOperationAcceptance, reconstructLegacyTeamSetupCompletionManifest, recordAutomaticRecall, recordHighestObservedDirectSignatureVersion, recordLocalIdentitySwitch, recordNonce, recordPromptPackArtifacts, recordPromptPackTerminal, recordSyncAttempt, recordSyncTransferObservation, refreshAuthorizedCoordinatorPeerTrust, refreshConfiguredScopeMembershipCache, refreshLegacyTeamCandidate, rejectInboundScopeFailures, 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, setLocalSyncFeature, 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, createPrivateKey, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
7
7
  import { createMiddleware } from "hono/factory";
8
8
  import { RateLimiter } from "limiter";
9
+ import { feedFullContextText, projectFeedItem } from "@codemem/core/feed-contract";
9
10
  import { and, count, desc, eq, inArray, max, ne, sql } from "drizzle-orm";
10
11
  import { drizzle } from "drizzle-orm/better-sqlite3";
12
+ import { Buffer as Buffer$1 } from "node:buffer";
11
13
  import { homedir, hostname, networkInterfaces } from "node:os";
12
14
  import * as z from "zod";
13
15
  import { chmod, link, mkdir, open, readFile, readdir, rm, stat } from "node:fs/promises";
@@ -590,6 +592,55 @@ function createAccountLinkRegistry(options) {
590
592
  return new InProcessAccountLinkRegistry(options);
591
593
  }
592
594
  //#endregion
595
+ //#region src/account/device-connection.ts
596
+ /** Eligibility is a signed read. Only an explicit sign-in starts the existing ceremony. */
597
+ async function attachDeviceConnection(options, context, view, signal) {
598
+ if (!options.registry?.supportsSignIn?.() || view.ownerProjection || view.remote.kind !== "status" || view.remote.state !== "linked" || !view.remote.identityMatches) return;
599
+ const read = options.readRemoteDeviceSetup ?? (options.readRemoteStatus ? null : readCoordinatorDeviceSetup);
600
+ if (!read) return;
601
+ const before = options.readContext(context.groupId);
602
+ if ("error" in before || before.setup !== "ready" || !before.context || !sameAuthority(context, before.context)) {
603
+ contextChanged(view);
604
+ return;
605
+ }
606
+ let connectRequired = false;
607
+ try {
608
+ const { dbPath, keysDir, coordinatorUrl, groupId, identityId } = context;
609
+ connectRequired = (await read({
610
+ dbPath,
611
+ keysDir,
612
+ coordinatorUrl,
613
+ groupId,
614
+ currentIdentityId: identityId,
615
+ signal
616
+ })).kind === "connect_required";
617
+ } catch {}
618
+ try {
619
+ const after = options.readContext(context.groupId);
620
+ if (signal.aborted || JSON.stringify(before) !== JSON.stringify(after)) {
621
+ contextChanged(view);
622
+ return;
623
+ }
624
+ } catch {
625
+ contextChanged(view);
626
+ return;
627
+ }
628
+ if (!connectRequired) return;
629
+ view.canConnectDevice = true;
630
+ view.canSignIn = true;
631
+ view.blockedReason = null;
632
+ }
633
+ function contextChanged(view) {
634
+ view.remote = {
635
+ kind: "unavailable",
636
+ code: "context_changed"
637
+ };
638
+ view.blockedReason = "status_unavailable";
639
+ view.canLink = false;
640
+ view.canSignIn = false;
641
+ view.canConnectDevice = false;
642
+ }
643
+ //#endregion
593
644
  //#region src/account/owner-status.ts
594
645
  /** The coordinator ID comes from the first signed actor-status read, never the origin. */
595
646
  function readOwnerAssociation(context, coordinatorId) {
@@ -769,7 +820,7 @@ function withOwnerSignIn(owner, own, context, remote) {
769
820
  };
770
821
  }
771
822
  function attachOperation(input, registry, operationContextId = input.contextId) {
772
- const { canSignIn, signIn, ...rest } = input;
823
+ const { canSignIn, canConnectDevice, signIn, ...rest } = input;
773
824
  const view = registry?.supportsSignIn?.() ? input : rest;
774
825
  const operation = operationContextId ? registry?.forContext(operationContextId) ?? null : null;
775
826
  const operationContext = operation && operationContextId && operationContextId !== view.contextId ? { operationContextId } : {};
@@ -779,6 +830,7 @@ function attachOperation(input, registry, operationContextId = input.contextId)
779
830
  operation,
780
831
  canLink: false,
781
832
  ..."canSignIn" in view ? { canSignIn: false } : {},
833
+ ..."canConnectDevice" in view ? { canConnectDevice: false } : {},
782
834
  blockedReason: "operation_active"
783
835
  };
784
836
  return {
@@ -979,6 +1031,7 @@ async function finishAccountStatus(options, context, fresh, remote, read) {
979
1031
  return attachOperation(owner, options.registry, context.contextId);
980
1032
  }
981
1033
  }
1034
+ await attachDeviceConnection(options, context, currentView, signal);
982
1035
  await attachManagementActions(options, context, currentView, signal);
983
1036
  if (remote.kind === "status") try {
984
1037
  if (readOwnerAssociation(context, remote.status.coordinatorId)) return attachOperation(ownerUnavailable(accountLocalView(fresh), "context_changed"), options.registry);
@@ -1051,6 +1104,8 @@ async function attachManagementActions(options, context, view, signal) {
1051
1104
  code: "context_changed"
1052
1105
  };
1053
1106
  view.blockedReason = "status_unavailable";
1107
+ view.canSignIn = false;
1108
+ view.canConnectDevice = false;
1054
1109
  return;
1055
1110
  }
1056
1111
  if (capabilities?.kind !== "capabilities" || capabilities.coordinatorId !== view.remote.coordinatorId) return;
@@ -2244,12 +2299,16 @@ function observerSelect(options) {
2244
2299
  updated_at AS occurred_at, status, attempt_count AS metric_a,
2245
2300
  NULL AS metric_b,
2246
2301
  CASE
2302
+ WHEN error_type = 'RawEventObserverOutputError:no_processable_input' THEN 'input preparation'
2303
+ WHEN error_type = 'RawEventObserverOutputError:lossy_repair' THEN 'structural repair'
2304
+ WHEN error_type = 'RawEventObserverOutputError:unstorable_observer_output' THEN 'output validation and filtering'
2247
2305
  WHEN lower(COALESCE(observer_error_code, error_type)) LIKE '%auth%' THEN 'authentication'
2248
2306
  WHEN lower(COALESCE(observer_error_code, error_type)) LIKE '%rate%'
2249
2307
  OR lower(COALESCE(observer_error_code, error_type)) LIKE '%limit%' THEN 'rate limit'
2250
2308
  WHEN lower(COALESCE(observer_error_code, error_type)) LIKE '%timeout%' THEN 'timeout'
2251
2309
  WHEN lower(COALESCE(observer_error_code, error_type)) LIKE '%schema%'
2252
2310
  OR lower(COALESCE(observer_error_code, error_type)) LIKE '%parse%' THEN 'response format'
2311
+ WHEN error_type = 'RawEventObserverOutputError:empty_observer_output' THEN 'empty response'
2253
2312
  ELSE 'unspecified'
2254
2313
  END AS category,
2255
2314
  NULL AS stored_category
@@ -2760,8 +2819,61 @@ function healthRoutes(getStore) {
2760
2819
  });
2761
2820
  return app;
2762
2821
  }
2822
+ function feedCursorFilterKey(options) {
2823
+ return createHash("sha256").update(JSON.stringify([
2824
+ options.classification,
2825
+ options.project ?? null,
2826
+ options.scope ?? null,
2827
+ options.q ?? null,
2828
+ options.actorId,
2829
+ options.dbPath
2830
+ ])).digest("hex");
2831
+ }
2832
+ function isFeedCursorPayload(value) {
2833
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
2834
+ const payload = value;
2835
+ return Object.keys(payload).length === 4 && payload.v === 1 && typeof payload.created_at === "string" && payload.created_at.length <= 256 && typeof payload.id === "number" && Number.isSafeInteger(payload.id) && payload.id > 0 && typeof payload.filter === "string" && /^[a-f0-9]{64}$/.test(payload.filter);
2836
+ }
2837
+ function tryEncodeFeedCursor(options) {
2838
+ const payload = {
2839
+ v: 1,
2840
+ created_at: options.position.created_at,
2841
+ id: options.position.id,
2842
+ filter: options.filter
2843
+ };
2844
+ if (!isFeedCursorPayload(payload)) return null;
2845
+ const token = Buffer$1.from(JSON.stringify(payload), "utf8").toString("base64url");
2846
+ if (token.length > 4096) return null;
2847
+ return token;
2848
+ }
2849
+ function decodeFeedCursor(options) {
2850
+ const { cursor, filter } = options;
2851
+ if (!cursor || cursor.length > 4096 || !/^[A-Za-z0-9_-]+$/.test(cursor)) return null;
2852
+ const bytes = Buffer$1.from(cursor, "base64url");
2853
+ if (bytes.toString("base64url") !== cursor) return null;
2854
+ const text = bytes.toString("utf8");
2855
+ if (!Buffer$1.from(text, "utf8").equals(bytes)) return null;
2856
+ let payload;
2857
+ try {
2858
+ payload = JSON.parse(text);
2859
+ } catch {
2860
+ return null;
2861
+ }
2862
+ if (!isFeedCursorPayload(payload) || payload.filter !== filter) return null;
2863
+ if (tryEncodeFeedCursor({
2864
+ position: payload,
2865
+ filter
2866
+ }) !== cursor) return null;
2867
+ return {
2868
+ created_at: payload.created_at,
2869
+ id: payload.id
2870
+ };
2871
+ }
2763
2872
  //#endregion
2764
2873
  //#region src/routes/memory.ts
2874
+ /**
2875
+ * Memory routes — observations, summaries, sessions, projects, pack, artifacts.
2876
+ */
2765
2877
  var MAX_FEED_QUERY_CODE_UNITS = 256;
2766
2878
  var searchFunctionsRegisteredStores = /* @__PURE__ */ new WeakSet();
2767
2879
  function casefold(value) {
@@ -3021,18 +3133,18 @@ function countVisibleArtifactRows(store, project) {
3021
3133
  const row = store.db.prepare(`SELECT COUNT(*) AS total FROM ${from} WHERE ${clauses.join(" AND ")}`).get(...params);
3022
3134
  return Number(row?.total ?? 0);
3023
3135
  }
3024
- function queryMemoryPage(store, options) {
3136
+ function buildMemoryReadQuery(store, options) {
3025
3137
  ensureMemorySearchFunctions(store);
3026
3138
  const filters = {};
3027
3139
  if (options.project) filters.project = options.project;
3028
3140
  if (options.scope) filters.ownership_scope = options.scope;
3029
3141
  const filterResult = buildViewerMemoryFilters(store, filters);
3030
- const summaryPredicate = summaryLikeSqlPredicate();
3031
- const clauses = [
3032
- "memory_items.active = 1",
3033
- options.classification === "summary" ? summaryPredicate : `NOT ${summaryPredicate}`,
3034
- ...filterResult.clauses
3035
- ];
3142
+ const clauses = ["memory_items.active = 1"];
3143
+ if (options.classification) {
3144
+ const summaryPredicate = summaryLikeSqlPredicate();
3145
+ clauses.push(options.classification === "summary" ? summaryPredicate : `NOT ${summaryPredicate}`);
3146
+ }
3147
+ clauses.push(...filterResult.clauses);
3036
3148
  const params = [...filterResult.params];
3037
3149
  if (options.q) {
3038
3150
  const search = memorySearchSql(options.q);
@@ -3040,14 +3152,163 @@ function queryMemoryPage(store, options) {
3040
3152
  params.push(...search.params);
3041
3153
  }
3042
3154
  const where = clauses.join(" AND ");
3043
- const from = filterResult.joinSessions ? "memory_items JOIN sessions ON sessions.id = memory_items.session_id" : "memory_items";
3155
+ return {
3156
+ from: filterResult.joinSessions ? "memory_items JOIN sessions ON sessions.id = memory_items.session_id" : "memory_items",
3157
+ where,
3158
+ params
3159
+ };
3160
+ }
3161
+ function queryMemoryPage(store, options) {
3162
+ const query = buildMemoryReadQuery(store, options);
3163
+ const { from, params } = query;
3164
+ let where = query.where;
3165
+ let limitClause = "LIMIT ?";
3166
+ if (options.paging.mode === "cursor" && options.paging.position) {
3167
+ where += " AND (memory_items.created_at, memory_items.id) < (?, ?)";
3168
+ params.push(options.paging.position.created_at, options.paging.position.id);
3169
+ }
3170
+ params.push(options.limit + 1);
3171
+ if (options.paging.mode === "offset") {
3172
+ limitClause += " OFFSET ?";
3173
+ params.push(options.paging.offset);
3174
+ }
3044
3175
  const rows = store.db.prepare(`SELECT memory_items.* FROM ${from}
3045
3176
  WHERE ${where}
3046
3177
  ORDER BY memory_items.created_at DESC, memory_items.id DESC
3047
- LIMIT ? OFFSET ?`).all(...params, options.limit + 1, options.offset);
3178
+ ${limitClause}`).all(...params);
3048
3179
  const ownedBySelf = store.buildOwnershipPredicate();
3049
3180
  return rows.map((row) => serializeMemoryRow(ownedBySelf, row));
3050
3181
  }
3182
+ function parseMemoryPaging(c, store, options) {
3183
+ if (c.req.query("paging") !== "cursor") return {
3184
+ mode: "offset",
3185
+ offset: Math.max(0, queryInt(c.req.query("offset"), 0))
3186
+ };
3187
+ const offset = c.req.query("offset");
3188
+ if (offset !== void 0 && offset !== "0") return null;
3189
+ const filter = feedCursorFilterKey({
3190
+ ...options,
3191
+ actorId: store.actorId,
3192
+ dbPath: store.dbPath
3193
+ });
3194
+ const cursor = c.req.query("cursor");
3195
+ if (cursor === void 0) return {
3196
+ mode: "cursor",
3197
+ filter,
3198
+ position: null
3199
+ };
3200
+ const position = decodeFeedCursor({
3201
+ cursor,
3202
+ filter
3203
+ });
3204
+ if (!position) return null;
3205
+ return {
3206
+ mode: "cursor",
3207
+ filter,
3208
+ position
3209
+ };
3210
+ }
3211
+ function memoryPagePagination(options) {
3212
+ const { paging, limit, hasMore, items } = options;
3213
+ if (paging.mode === "offset") return {
3214
+ limit,
3215
+ offset: paging.offset,
3216
+ next_offset: hasMore ? paging.offset + items.length : null,
3217
+ has_more: hasMore
3218
+ };
3219
+ const last = items.at(-1);
3220
+ const nextCursor = hasMore && last ? tryEncodeFeedCursor({
3221
+ position: {
3222
+ created_at: last.created_at,
3223
+ id: last.id
3224
+ },
3225
+ filter: paging.filter
3226
+ }) : null;
3227
+ if (hasMore && nextCursor === null) return null;
3228
+ return {
3229
+ limit,
3230
+ offset: null,
3231
+ next_offset: null,
3232
+ has_more: hasMore,
3233
+ paging: "cursor",
3234
+ next_cursor: nextCursor
3235
+ };
3236
+ }
3237
+ function handleMemoryListRequest(c, getStore, options) {
3238
+ if (c.req.query("paging") === "cursor") c.header("Cache-Control", "no-store");
3239
+ const store = getStore();
3240
+ const limit = Math.max(1, queryInt(c.req.query("limit"), options.defaultLimit));
3241
+ const q = normalizeMemorySearchQuery(c.req.query("q"));
3242
+ const readOptions = {
3243
+ project: c.req.query("project") || void 0,
3244
+ scope: normalizeScope(c.req.query("scope")),
3245
+ q,
3246
+ classification: options.classification
3247
+ };
3248
+ const paging = parseMemoryPaging(c, store, readOptions);
3249
+ if (!paging) return c.json({ error: "invalid_cursor" }, 400);
3250
+ const items = queryMemoryPage(store, {
3251
+ ...readOptions,
3252
+ limit,
3253
+ paging
3254
+ });
3255
+ const hasMore = items.length > limit;
3256
+ const result = hasMore ? items.slice(0, limit) : items;
3257
+ const pagination = memoryPagePagination({
3258
+ paging,
3259
+ limit,
3260
+ hasMore,
3261
+ items: result
3262
+ });
3263
+ if (pagination === null) return c.json({ error: "cursor_unavailable" }, 409);
3264
+ attachSessionFields(store, result);
3265
+ attachResolvedIdentityFields(store, result);
3266
+ return c.json({
3267
+ items: c.req.query("view") === "feed" ? feedResponseItems(result, q) : result,
3268
+ pagination
3269
+ });
3270
+ }
3271
+ function fullContextRevision(context) {
3272
+ return createHash("sha256").update(context).digest("hex");
3273
+ }
3274
+ function feedResponseItems(items, query) {
3275
+ return items.map((item) => {
3276
+ const context = feedFullContextText(item);
3277
+ return projectFeedItem({
3278
+ item,
3279
+ query,
3280
+ contextRevision: context === null ? "" : fullContextRevision(context)
3281
+ });
3282
+ });
3283
+ }
3284
+ function queryMemoryContextItem(store, id, options) {
3285
+ const { from, where, params } = buildMemoryReadQuery(store, options);
3286
+ const row = store.db.prepare(`SELECT memory_items.* FROM ${from} WHERE ${where} AND memory_items.id = ?`).get(...params, id);
3287
+ if (!row) return null;
3288
+ return serializeMemoryRow(store.buildOwnershipPredicate(), row);
3289
+ }
3290
+ function handleMemoryContextRequest(c, getStore) {
3291
+ c.header("Cache-Control", "no-store");
3292
+ const rawId = c.req.param("id") ?? "";
3293
+ const id = Number(rawId);
3294
+ if (!/^[1-9][0-9]*$/.test(rawId) || !Number.isSafeInteger(id)) return c.json({ error: "id must be a positive safe integer" }, 400);
3295
+ const classification = c.req.query("classification");
3296
+ if (classification !== void 0 && classification !== "observation" && classification !== "summary") return c.json({ error: "classification must be observation or summary" }, 400);
3297
+ const item = queryMemoryContextItem(getStore(), id, {
3298
+ project: c.req.query("project") || void 0,
3299
+ scope: normalizeScope(c.req.query("scope")),
3300
+ q: normalizeMemorySearchQuery(c.req.query("q")),
3301
+ classification
3302
+ });
3303
+ const context = item ? feedFullContextText(item) : null;
3304
+ if (context === null) return c.json({ error: "memory not found" }, 404);
3305
+ const response = {
3306
+ id,
3307
+ revision: fullContextRevision(context),
3308
+ context
3309
+ };
3310
+ return c.json(response);
3311
+ }
3051
3312
  async function handleLegacyPackRequest(c, getStore) {
3052
3313
  const store = getStore();
3053
3314
  const context = c.req.query("context") || "";
@@ -3094,12 +3355,13 @@ function memoryRoutes(getStore) {
3094
3355
  const clauses = [
3095
3356
  "memory_items.session_id = sessions.id",
3096
3357
  "memory_items.active = 1",
3097
- "sessions.project IS NOT NULL",
3098
3358
  ...filterResult.clauses
3099
3359
  ];
3100
- const rows = store.db.prepare(`SELECT DISTINCT sessions.project AS project FROM sessions
3101
- JOIN memory_items ON memory_items.session_id = sessions.id
3102
- WHERE ${clauses.join(" AND ")}`).all(...filterResult.params);
3360
+ const rows = store.db.prepare(`SELECT candidates.project AS project
3361
+ FROM (SELECT DISTINCT project FROM sessions WHERE project IS NOT NULL) candidates
3362
+ WHERE EXISTS (SELECT 1 FROM sessions
3363
+ WHERE sessions.project = candidates.project
3364
+ AND EXISTS (SELECT 1 FROM memory_items WHERE ${clauses.join(" AND ")}))`).all(...filterResult.params);
3103
3365
  const projects = [...new Set(rows.map((r) => String(r.project ?? "").trim()).filter((p) => p && !p.toLowerCase().startsWith("fatal:")).map((p) => projectBasename(p)).filter(Boolean))].sort();
3104
3366
  return c.json({ projects });
3105
3367
  }
@@ -3108,64 +3370,14 @@ function memoryRoutes(getStore) {
3108
3370
  const search = new URL(c.req.url).search;
3109
3371
  return c.redirect(`/api/observations${search}`, 301);
3110
3372
  });
3111
- app.get("/api/observations", (c) => {
3112
- const store = getStore();
3113
- {
3114
- const limit = Math.max(1, queryInt(c.req.query("limit"), 20));
3115
- const offset = Math.max(0, queryInt(c.req.query("offset"), 0));
3116
- const items = queryMemoryPage(store, {
3117
- limit,
3118
- offset,
3119
- project: c.req.query("project") || void 0,
3120
- scope: normalizeScope(c.req.query("scope")),
3121
- q: normalizeMemorySearchQuery(c.req.query("q")),
3122
- classification: "observation"
3123
- });
3124
- const hasMore = items.length > limit;
3125
- const result = hasMore ? items.slice(0, limit) : items;
3126
- const asRecords = result;
3127
- attachSessionFields(store, asRecords);
3128
- attachResolvedIdentityFields(store, asRecords);
3129
- return c.json({
3130
- items: asRecords,
3131
- pagination: {
3132
- limit,
3133
- offset,
3134
- next_offset: hasMore ? offset + result.length : null,
3135
- has_more: hasMore
3136
- }
3137
- });
3138
- }
3139
- });
3140
- app.get("/api/summaries", (c) => {
3141
- const store = getStore();
3142
- {
3143
- const limit = Math.max(1, queryInt(c.req.query("limit"), 50));
3144
- const offset = Math.max(0, queryInt(c.req.query("offset"), 0));
3145
- const items = queryMemoryPage(store, {
3146
- limit,
3147
- offset,
3148
- project: c.req.query("project") || void 0,
3149
- scope: normalizeScope(c.req.query("scope")),
3150
- q: normalizeMemorySearchQuery(c.req.query("q")),
3151
- classification: "summary"
3152
- });
3153
- const hasMore = items.length > limit;
3154
- const result = hasMore ? items.slice(0, limit) : items;
3155
- const asRecords = result;
3156
- attachSessionFields(store, asRecords);
3157
- attachResolvedIdentityFields(store, asRecords);
3158
- return c.json({
3159
- items: asRecords,
3160
- pagination: {
3161
- limit,
3162
- offset,
3163
- next_offset: hasMore ? offset + result.length : null,
3164
- has_more: hasMore
3165
- }
3166
- });
3167
- }
3168
- });
3373
+ app.get("/api/observations", (c) => handleMemoryListRequest(c, getStore, {
3374
+ classification: "observation",
3375
+ defaultLimit: 20
3376
+ }));
3377
+ app.get("/api/summaries", (c) => handleMemoryListRequest(c, getStore, {
3378
+ classification: "summary",
3379
+ defaultLimit: 50
3380
+ }));
3169
3381
  app.get("/api/session", (c) => {
3170
3382
  const store = getStore();
3171
3383
  {
@@ -3219,6 +3431,7 @@ function memoryRoutes(getStore) {
3219
3431
  ]);
3220
3432
  return c.json(trace);
3221
3433
  });
3434
+ app.get("/api/memory/:id/context", (c) => handleMemoryContextRequest(c, getStore));
3222
3435
  app.get("/api/memory", (c) => {
3223
3436
  const store = getStore();
3224
3437
  {
@@ -5616,6 +5829,85 @@ function healthStats(store) {
5616
5829
  };
5617
5830
  }
5618
5831
  //#endregion
5832
+ //#region src/application/coordinator-enrollment-context.ts
5833
+ function readLocalDevice$1(store, keysDir) {
5834
+ try {
5835
+ const before = statSync(store.dbPath, { bigint: true });
5836
+ const device = readAccountLinkDevice(store.dbPath);
5837
+ const key = loadRuntimeSigningPublicKey(store.db, {
5838
+ deviceId: store.deviceId,
5839
+ keysDir
5840
+ });
5841
+ const after = statSync(store.dbPath, { bigint: true });
5842
+ if (!before.isFile() || before.dev !== after.dev || before.ino !== after.ino || device.deviceId !== store.deviceId || !key || fingerprintPublicKey(key) !== device.fingerprint) throw new Error("device_unavailable");
5843
+ return {
5844
+ device,
5845
+ fileIdentity: `${after.dev}:${after.ino}`
5846
+ };
5847
+ } catch {
5848
+ throw new Error("device_unavailable");
5849
+ }
5850
+ }
5851
+ function identityGeneration(store) {
5852
+ try {
5853
+ return store.db.prepare("SELECT generation, actor_id FROM local_identity_generation WHERE id = 1").get() ?? null;
5854
+ } catch (error) {
5855
+ if (error instanceof Error && error.message.includes("no such table")) return null;
5856
+ throw error;
5857
+ }
5858
+ }
5859
+ function currentOperationConfig(store, options) {
5860
+ store.assertLocalIdentityCurrent();
5861
+ const config = options.readConfig();
5862
+ if (!store.hasCurrentConfiguredIdentity() || config.syncEnabled !== options.config.syncEnabled || config.syncCoordinatorAdminSecret !== options.config.syncCoordinatorAdminSecret || config.syncCoordinatorUrl !== options.config.syncCoordinatorUrl || JSON.stringify(config.syncCoordinatorGroups) !== JSON.stringify(options.config.syncCoordinatorGroups)) throw new Error("device_setup_context_changed");
5863
+ return config;
5864
+ }
5865
+ function captureCoordinatorEnrollmentContext(store, options) {
5866
+ const capture = () => {
5867
+ const config = currentOperationConfig(store, options);
5868
+ const { dbPath, deviceId, actorId } = store;
5869
+ const keysDir = options.keysDir();
5870
+ const { device, fileIdentity } = readLocalDevice$1(store, keysDir);
5871
+ return {
5872
+ dbPath,
5873
+ deviceId,
5874
+ identityId: actorId,
5875
+ keysDir,
5876
+ groupId: options.groupId,
5877
+ coordinatorUrl: config.syncCoordinatorUrl,
5878
+ fingerprint: device.fingerprint,
5879
+ pin: JSON.stringify([
5880
+ dbPath,
5881
+ device,
5882
+ actorId,
5883
+ keysDir,
5884
+ fileIdentity,
5885
+ identityGeneration(store),
5886
+ readCodememConfigFile().actor_id,
5887
+ process.env.CODEMEM_DB,
5888
+ process.env.CODEMEM_CONFIG,
5889
+ process.env.HOME,
5890
+ process.env.CODEMEM_SYNC_KEY_STORE,
5891
+ process.env.CODEMEM_ACTOR_ID,
5892
+ process.env.CODEMEM_DEVICE_ID
5893
+ ])
5894
+ };
5895
+ };
5896
+ const initial = capture();
5897
+ const assertCurrent = () => {
5898
+ try {
5899
+ if (capture().pin === initial.pin) return;
5900
+ } catch (error) {
5901
+ if (error instanceof LocalIdentitySupersededError) throw error;
5902
+ }
5903
+ throw new Error("device_setup_context_changed");
5904
+ };
5905
+ return {
5906
+ ...initial,
5907
+ assertCurrent
5908
+ };
5909
+ }
5910
+ //#endregion
5619
5911
  //#region src/application/coordinator-maintenance.ts
5620
5912
  var AUTOMATIC_SHARE_OPERATION_STATES = [
5621
5913
  "waiting_for_acceptance",
@@ -9564,10 +9856,27 @@ async function advancePendingProjectShares(store, options = {}) {
9564
9856
  });
9565
9857
  }
9566
9858
  function coordinatorEnrollmentFailureCode(error) {
9859
+ if (error instanceof LocalIdentitySupersededError) return error.code;
9567
9860
  const message = (error instanceof Error ? error.message : String(error)).trim();
9568
9861
  const httpStatus = message.match(/\((\d{3})(?::|\))/u)?.[1];
9569
9862
  if (httpStatus) return `http_${httpStatus}`;
9570
9863
  if ((/* @__PURE__ */ new Set([
9864
+ "coordinator_upgrade_required",
9865
+ "completion_outcome_unknown",
9866
+ "device_unavailable",
9867
+ "invalid_input",
9868
+ "coordinator_unreachable",
9869
+ "invalid_response",
9870
+ "coordinator_rejected",
9871
+ "rate_limited",
9872
+ "coordinator_auth_schema_upgrade_required",
9873
+ "coordinator_unavailable",
9874
+ "device_setup_requires_review",
9875
+ "device_setup_connect_required",
9876
+ "device_setup_ready",
9877
+ "device_setup_enrollment_incomplete",
9878
+ "device_setup_context_changed",
9879
+ "local_identity_superseded",
9571
9880
  "coordinator_consumed_team_invite_invalid",
9572
9881
  "coordinator_device_list_malformed",
9573
9882
  "coordinator_group_id_invalid",
@@ -9587,8 +9896,106 @@ function coordinatorEnrollmentFailure(groupId, stage, error) {
9587
9896
  code: coordinatorEnrollmentFailureCode(error)
9588
9897
  };
9589
9898
  }
9899
+ function matchesOwnCoordinatorKey(context, row) {
9900
+ return row.enabled === 1 && row.group_id === context.groupId && row.device_id === context.deviceId && fingerprintPublicKey(row.public_key) === context.fingerprint && row.fingerprint === context.fingerprint;
9901
+ }
9902
+ function hasCanonicalOwnEnrollment(context, rows) {
9903
+ return rows.some((row) => matchesOwnCoordinatorKey(context, row) && row.identity_id === context.identityId && row.ownership_identity_id === context.identityId);
9904
+ }
9905
+ function compatibleOwnCoordinatorEnrollment(context, own) {
9906
+ if (!matchesOwnCoordinatorKey(context, own)) return false;
9907
+ if (own.identity_id !== null && own.identity_id !== context.identityId) return false;
9908
+ return own.ownership_identity_id === void 0 || own.ownership_identity_id === context.identityId;
9909
+ }
9910
+ function hasLegacyOwnIdentity(context, own) {
9911
+ return own.identity_id === context.identityId && own.ownership_identity_id === void 0;
9912
+ }
9913
+ /**
9914
+ * True when the coordinator state cannot have changed: the client sent no request
9915
+ * for this URL, or an older coordinator has no completion route.
9916
+ */
9917
+ function completionNotAttempted(setup) {
9918
+ if (setup.kind === "unavailable") return setup.cause === "invalid_input";
9919
+ return setup.kind === "unsupported";
9920
+ }
9921
+ async function completeCoordinatorEnrollment(context, initial, completeDeviceSetup, readDevices) {
9922
+ const own = initial.find((row) => row.group_id === context.groupId && row.device_id === context.deviceId);
9923
+ if (!own) return initial;
9924
+ if (hasCanonicalOwnEnrollment(context, initial)) return initial;
9925
+ if (!compatibleOwnCoordinatorEnrollment(context, own)) throw new Error("device_setup_enrollment_incomplete");
9926
+ const setup = await completeDeviceSetup({
9927
+ dbPath: context.dbPath,
9928
+ keysDir: context.keysDir,
9929
+ coordinatorUrl: context.coordinatorUrl,
9930
+ groupId: context.groupId,
9931
+ currentIdentityId: context.identityId,
9932
+ fetch: (input, init) => {
9933
+ context.assertCurrent();
9934
+ return globalThis.fetch(input, init);
9935
+ }
9936
+ });
9937
+ context.assertCurrent();
9938
+ if (completionNotAttempted(setup)) return initial;
9939
+ if (setup.kind === "requires_review" && hasLegacyOwnIdentity(context, own)) return initial;
9940
+ if (setup.kind !== "complete" && setup.kind !== "unknown") throw new Error("cause" in setup ? setup.cause : `device_setup_${setup.kind}`);
9941
+ const enrollments = await readDevices();
9942
+ if (!hasCanonicalOwnEnrollment(context, enrollments)) throw new Error(setup.kind === "unknown" ? "completion_outcome_unknown" : "device_setup_enrollment_incomplete");
9943
+ return enrollments;
9944
+ }
9945
+ async function reconcileConfiguredCoordinatorGroup(store, groupId, config, options) {
9946
+ const remoteUrl = config.syncCoordinatorUrl.trim();
9947
+ const adminSecret = config.syncCoordinatorAdminSecret.trim();
9948
+ const listDevices = options.listDevices ?? coordinatorListDevicesAction;
9949
+ const listInvites = options.listConsumedTeamInvites ?? coordinatorListConsumedTeamInvitesAction;
9950
+ const reconcile = options.reconcileSnapshot ?? ((input) => reconcileCoordinatorEnrollmentSnapshot(store.db, input));
9951
+ let stage = "complete_device_setup";
9952
+ try {
9953
+ const context = captureCoordinatorEnrollmentContext(store, {
9954
+ config,
9955
+ readConfig: () => options.config ?? readCoordinatorSyncConfig(),
9956
+ keysDir: syncKeysDir,
9957
+ groupId
9958
+ });
9959
+ const readDevices = async () => {
9960
+ stage = "list_devices";
9961
+ const rows = await listDevices({
9962
+ groupId,
9963
+ remoteUrl,
9964
+ adminSecret
9965
+ });
9966
+ stage = "complete_device_setup";
9967
+ context.assertCurrent();
9968
+ return rows;
9969
+ };
9970
+ const enrollments = await completeCoordinatorEnrollment(context, await readDevices(), options.completeDeviceSetup ?? completeCoordinatorDeviceSetup, readDevices);
9971
+ stage = "list_consumed_team_invites";
9972
+ const invites = await listInvites({
9973
+ groupId,
9974
+ remoteUrl,
9975
+ adminSecret
9976
+ });
9977
+ stage = "complete_device_setup";
9978
+ context.assertCurrent();
9979
+ stage = "reconcile_snapshot";
9980
+ return { result: await reconcile({
9981
+ coordinatorId: buildBaseUrl(remoteUrl),
9982
+ groupId,
9983
+ enrollments,
9984
+ consumedTeamInvites: invites,
9985
+ localDeviceId: store.deviceId
9986
+ }) };
9987
+ } catch (error) {
9988
+ return { failures: [coordinatorEnrollmentFailure(groupId, stage, error)] };
9989
+ }
9990
+ }
9590
9991
  async function reconcileConfiguredCoordinatorEnrollment(store, options = {}) {
9591
- const config = options.config ?? readCoordinatorSyncConfig();
9992
+ const source = options.config ?? readCoordinatorSyncConfig();
9993
+ const config = {
9994
+ syncEnabled: source.syncEnabled,
9995
+ syncCoordinatorUrl: source.syncCoordinatorUrl,
9996
+ syncCoordinatorGroups: [...source.syncCoordinatorGroups],
9997
+ syncCoordinatorAdminSecret: source.syncCoordinatorAdminSecret
9998
+ };
9592
9999
  const remoteUrl = config.syncCoordinatorUrl.trim();
9593
10000
  const adminSecret = config.syncCoordinatorAdminSecret.trim();
9594
10001
  if (!remoteUrl || !adminSecret || config.syncCoordinatorGroups.length === 0) return {
@@ -9602,9 +10009,6 @@ async function reconcileConfiguredCoordinatorEnrollment(store, options = {}) {
9602
10009
  unchanged: 0,
9603
10010
  issues: 0
9604
10011
  };
9605
- const listDevices = options.listDevices ?? coordinatorListDevicesAction;
9606
- const listConsumedTeamInvites = options.listConsumedTeamInvites ?? coordinatorListConsumedTeamInvitesAction;
9607
- const reconcileSnapshot = options.reconcileSnapshot ?? ((input) => reconcileCoordinatorEnrollmentSnapshot(store.db, input));
9608
10012
  const total = {
9609
10013
  skipped: false,
9610
10014
  groupsProcessed: 0,
@@ -9617,39 +10021,19 @@ async function reconcileConfiguredCoordinatorEnrollment(store, options = {}) {
9617
10021
  issues: 0
9618
10022
  };
9619
10023
  for (const groupId of config.syncCoordinatorGroups) {
9620
- const [enrollmentsResult, consumedTeamInvitesResult] = await Promise.allSettled([listDevices({
9621
- groupId,
9622
- remoteUrl,
9623
- adminSecret
9624
- }), listConsumedTeamInvites({
9625
- groupId,
9626
- remoteUrl,
9627
- adminSecret
9628
- })]);
9629
- if (enrollmentsResult.status === "rejected") total.failures.push(coordinatorEnrollmentFailure(groupId, "list_devices", enrollmentsResult.reason));
9630
- if (consumedTeamInvitesResult.status === "rejected") total.failures.push(coordinatorEnrollmentFailure(groupId, "list_consumed_team_invites", consumedTeamInvitesResult.reason));
9631
- if (enrollmentsResult.status === "rejected" || consumedTeamInvitesResult.status === "rejected") {
10024
+ const outcome = await reconcileConfiguredCoordinatorGroup(store, groupId, config, options);
10025
+ if ("failures" in outcome) {
9632
10026
  total.failedGroups += 1;
10027
+ total.failures.push(...outcome.failures);
9633
10028
  continue;
9634
10029
  }
9635
- try {
9636
- const result = await reconcileSnapshot({
9637
- coordinatorId: buildBaseUrl(remoteUrl),
9638
- groupId,
9639
- enrollments: enrollmentsResult.value,
9640
- consumedTeamInvites: consumedTeamInvitesResult.value,
9641
- localDeviceId: store.deviceId
9642
- });
9643
- total.groupsProcessed += 1;
9644
- total.devicesAdded += result.devicesAdded;
9645
- total.membershipsAdded += result.membershipsAdded;
9646
- total.identitiesAdded += result.identitiesAdded;
9647
- total.unchanged += result.unchanged;
9648
- total.issues += result.issues.length;
9649
- } catch (error) {
9650
- total.failedGroups += 1;
9651
- total.failures.push(coordinatorEnrollmentFailure(groupId, "reconcile_snapshot", error));
9652
- }
10030
+ const { result } = outcome;
10031
+ total.groupsProcessed += 1;
10032
+ total.devicesAdded += result.devicesAdded;
10033
+ total.membershipsAdded += result.membershipsAdded;
10034
+ total.identitiesAdded += result.identitiesAdded;
10035
+ total.unchanged += result.unchanged;
10036
+ total.issues += result.issues.length;
9653
10037
  }
9654
10038
  return total;
9655
10039
  }
@@ -9777,9 +10161,17 @@ function createRecipientPolicyReconcilerEffects(store, options = {}) {
9777
10161
  remoteUrl: targetOptions.remoteUrl,
9778
10162
  adminSecret: targetOptions.adminSecret
9779
10163
  })).catch((error) => recipientPolicySnapshotUnavailable("device_enrollments", error));
9780
- const presenceCapabilityExpiries = recipientPolicyPresenceCapabilityExpiries(enrollments, observedAt);
10164
+ const presenceExpiries = recipientPolicyPresenceCapabilityExpiries(enrollments, observedAt);
10165
+ const bindings = /* @__PURE__ */ new Map();
9781
10166
  const mapped = enrollments.map((enrollment) => {
9782
10167
  if (enrollment.group_id !== targetOptions.groupId || !recipientPolicyEnrollmentValueIsValid(enrollment.device_id) || !recipientPolicyEnrollmentValueIsValid(enrollment.public_key) || !recipientPolicyEnrollmentValueIsValid(enrollment.fingerprint) || fingerprintPublicKey(enrollment.public_key) !== enrollment.fingerprint || enrollment.enabled !== 0 && enrollment.enabled !== 1 || enrollment.identity_id !== null && !recipientPolicyEnrollmentValueIsValid(enrollment.identity_id)) throw new Error("recipient_policy_snapshot_invalid");
10168
+ if (enrollment.enabled === 1 && enrollment.identity_id !== null) bindings.set(enrollment.device_id, {
10169
+ identityId: enrollment.identity_id,
10170
+ ownershipIdentityId: enrollment.ownership_identity_id,
10171
+ publicKey: enrollment.public_key,
10172
+ fingerprint: enrollment.fingerprint,
10173
+ presenceCapabilityExpiresAtMs: presenceExpiries.get(enrollment.device_id) ?? null
10174
+ });
9783
10175
  return {
9784
10176
  deviceId: enrollment.device_id,
9785
10177
  identityId: enrollment.identity_id,
@@ -9788,12 +10180,7 @@ function createRecipientPolicyReconcilerEffects(store, options = {}) {
9788
10180
  enabled: enrollment.enabled === 1
9789
10181
  };
9790
10182
  });
9791
- boundaryEnrollments.set(scopeId, new Map(mapped.flatMap((enrollment) => enrollment.enabled && enrollment.identityId !== null ? [[enrollment.deviceId, {
9792
- identityId: enrollment.identityId,
9793
- publicKey: enrollment.publicKey,
9794
- fingerprint: enrollment.fingerprint,
9795
- presenceCapabilityExpiresAtMs: presenceCapabilityExpiries.get(enrollment.deviceId) ?? null
9796
- }]] : [])));
10183
+ boundaryEnrollments.set(scopeId, bindings);
9797
10184
  return mapped;
9798
10185
  },
9799
10186
  probeCapability: async ({ deviceId, scopeId }) => {
@@ -9802,11 +10189,9 @@ function createRecipientPolicyReconcilerEffects(store, options = {}) {
9802
10189
  const enrollment = boundaryEnrollments.get(scopeId)?.get(deviceId);
9803
10190
  if (!enrollment) return "undetermined";
9804
10191
  const peer = store.db.prepare("SELECT pinned_fingerprint, public_key FROM sync_peers WHERE peer_device_id = ?").get(deviceId);
9805
- if (peer) {
9806
- const peerPublicKey = String(peer.public_key ?? "").trim();
9807
- const peerFingerprint = String(peer.pinned_fingerprint ?? "").trim() || (peerPublicKey ? fingerprintPublicKey(peerPublicKey) : "");
9808
- if ((peerFingerprint || peerPublicKey) && (peerFingerprint !== enrollment.fingerprint || peerPublicKey && peerPublicKey !== enrollment.publicKey)) return "undetermined";
9809
- }
10192
+ const peerPublicKey = String(peer?.public_key ?? "").trim();
10193
+ const peerFingerprint = String(peer?.pinned_fingerprint ?? "").trim() || (peerPublicKey ? fingerprintPublicKey(peerPublicKey) : "");
10194
+ if ((peerFingerprint || peerPublicKey) && (peerFingerprint !== enrollment.fingerprint || peerPublicKey && peerPublicKey !== enrollment.publicKey)) return "undetermined";
9810
10195
  const observed = await peerSupportsSyncRequirements(store, deviceId, {
9811
10196
  scoped: true,
9812
10197
  reassignScope: true
@@ -9814,6 +10199,7 @@ function createRecipientPolicyReconcilerEffects(store, options = {}) {
9814
10199
  if (observed !== "undetermined") return observed;
9815
10200
  const observedAtMs = Date.parse(now());
9816
10201
  if (enrollment.presenceCapabilityExpiresAtMs == null || !Number.isFinite(observedAtMs) || enrollment.presenceCapabilityExpiresAtMs <= observedAtMs) return "undetermined";
10202
+ if (enrollment.ownershipIdentityId === enrollment.identityId) return "supported";
9817
10203
  return (await loadReviewedRecipientInviteEvidence(targetOptions.groupId).catch(() => [])).some((invite) => invite.group_id === targetOptions.groupId && invite.bound_device_id === deviceId && invite.recipient_actor_id === enrollment.identityId && invite.bound_public_key === enrollment.publicKey && invite.bound_fingerprint === enrollment.fingerprint) ? "supported" : "undetermined";
9818
10204
  },
9819
10205
  revoke: async (input) => {
@@ -17696,6 +18082,7 @@ function buildClient(deps, config) {
17696
18082
  },
17697
18083
  authorityId: config.authorityId,
17698
18084
  groupId: config.groupId,
18085
+ pairPacing: options.pairPacingByGroup?.get(config.groupId),
17699
18086
  relayAudienceId: config.relayAudienceId,
17700
18087
  externalPathname: config.externalPathname,
17701
18088
  coordinator: createRelayCoordinatorClient({
@@ -18022,6 +18409,17 @@ function registerViewerBoundary(app, opts) {
18022
18409
  registry: options.registry
18023
18410
  }));
18024
18411
  }
18412
+ function registerViewerTargetGuards(options) {
18413
+ const { app, storeFactory } = options;
18414
+ const viewerTargetGuard = viewerTargetQueryGuard(storeFactory);
18415
+ app.use("/api/memories/*", viewerTargetGuard);
18416
+ app.use("/api/memory", viewerTargetGuard);
18417
+ app.use("/api/memory/:id/context", (c, next) => {
18418
+ c.header("Cache-Control", "no-store");
18419
+ return viewerTargetGuard(c, next);
18420
+ });
18421
+ app.use("/api/pi/sessions/search", viewerTargetGuard);
18422
+ }
18025
18423
  function createApp(opts) {
18026
18424
  const storeFactory = opts?.storeFactory ?? getStore;
18027
18425
  const sweeper = opts?.sweeper ?? null;
@@ -18031,10 +18429,10 @@ function createApp(opts) {
18031
18429
  registerViewerBoundary(app, opts);
18032
18430
  app.use("*", preflightHandler());
18033
18431
  app.use("*", originGuard({ unsafeGetPathPrefixes: [TEAM_SETUP_ROUTE_PREFIX] }));
18034
- const viewerTargetGuard = viewerTargetQueryGuard(storeFactory);
18035
- app.use("/api/memories/*", viewerTargetGuard);
18036
- app.use("/api/memory", viewerTargetGuard);
18037
- app.use("/api/pi/sessions/search", viewerTargetGuard);
18432
+ registerViewerTargetGuards({
18433
+ app,
18434
+ storeFactory
18435
+ });
18038
18436
  app.route("/", healthRoutes(storeFactory));
18039
18437
  app.route("/", diagnosticsRoutes(storeFactory));
18040
18438
  app.route("/", statsRoutes(storeFactory));