@codemem/server 0.50.0-beta.1 → 0.50.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { closeSync, existsSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { basename, dirname, isAbsolute, join, posix, resolve, win32 } from "node:path";
3
- import { ACCESS_CLEANUP_OP_TYPE, CodememConfigMutationError, CoordinatorAccountLinkError, CoordinatorReciprocalApprovalRequestChangedError, DEFAULT_TIME_WINDOW_S, FILE_CONTEXT_TRANSPORT_MAX_BYTES, LEGACY_SHARED_REVIEW_SCOPE_ID, LOCAL_DEFAULT_SCOPE_ID, LOCAL_SYNC_CAPABILITY, LOCAL_SYNC_FEATURES, LegacyTeamSetupAdditiveConvergenceError, LegacyTeamSetupRosterCapacityError, LocalIdentitySupersededError, MEMORY_FILTER_FIELD_TYPES, MEMORY_FILTER_NAMES, MEMORY_KIND_DESCRIPTIONS, MemoryStore, ObserverClient, PROMPT_TRANSPORT_PROTOCOL_RANGE, REMEMBER_MEMORY_KINDS, RICH_TIER_ANTHROPIC_DEFAULTS, RICH_TIER_DEFAULTS, RawEventIngestValidationError, RecipientPolicyEdgeRequestError, RecipientPolicyTeamCreateError, RecipientPolicyTeamRenameError, RemoteCoordinatorRequestError, SCOPE_MEMBERSHIP_REVOCATION_LIMITATION, SIMPLE_TIER_ANTHROPIC_DEFAULTS, SIMPLE_TIER_DEFAULTS, SYNC_AUTHORIZATION_REFRESH_HEADER, SYNC_CAPABILITY_HEADER, SYNC_FEATURES_HEADER, SYNC_SCOPE_QUERY_PARAM, VERSION, VERSION as VERSION$1, VIEWER_IDENTITY_TARGET_KEYS, VIEWER_SERVICE_DISCRIMINATOR, addSyncScopeToBoundary, analyzeProjectScopeMappingChangeGuardrails, analyzeProjectScopeMappingChangesGuardrails, analyzeProjectScopeMappingDeletionGuardrails, applyLegacyTeamSetupCompletionManifest, applyLegacyTeamSetupCompletionManifestAndReturnActivation, applyLocalIdentitySwitch, applyPeerReplicationOps, areLegacyTeamSetupCompletionPolicyFactsAdditivelyCompatible, assertNoLocalIdentityOverride, automaticRecallHealth, buildAuthHeaders, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildFilterBranchesWithContext, buildFilterClausesWithContext, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromCodexHook, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildViewerIdentityTarget, canonicalCoordinatorLegacyTeamCompletionManifestJson, canonicalKeyId, canonicalMemoryKind, canonicalRepositoryProjectIdentity, canonicalWorkspaceIdentity, captureAccountOwnerProfilePins, changeCoordinatorAccount, claimRecipientPolicyActorMutations, claimRecipientPolicyPublicationMutation, classifyRecordedSyncFailure, cleanupNonces, clearLegacyTeamSetupDeviceDecision, clonePromptPackAttempt, coerceObserverCommand, commitDeviceIdentityBindings, commitRecipientPolicyEdges, commitViewerDeviceRemoval, completeCoordinatorDeviceSetup, completeLocalIdentitySwitch, containLegacyTeamSetupCompletionConflict, convertLegacyPairingAssignments, coordinatorAdminReadiness, coordinatorArchiveGroupAction, coordinatorAuthControllerReviewAction, coordinatorCreateAddDeviceInviteAction, coordinatorCreateGroupAction, coordinatorCreateInviteAction, coordinatorCreateLegacyTeamCompletionAction, coordinatorCreateScopeAction, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorGetLegacyTeamCompletionAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListConsumedTeamInvitesAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListRemovedDevicesAction, coordinatorListReviewedRecipientInviteEvidenceAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorRenameGroupAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeDeviceAction, coordinatorRevokeScopeMembershipAction, coordinatorStatusSnapshot, coordinatorUnarchiveGroupAction, coordinatorUpdateScopeAction, countShareableProjectMemories, countUnattributedImportedProjectMemories, createCoordinatorReciprocalApproval, createRecipientPolicyTeam, decodeInvitePayload, dedupeOrderedIds, defaultSpaceScopeIdForGroup, deleteProjectScopeSettingsMapping, deriveLegacyTeamSetupCompletionManifest, detectInstallKind, deterministicPolicyTeamId, diagnoseStalePeerReceivedRows, discoverLegacyTeamCandidates, dispatchFileContextTransport, ensureDeviceIdentity, executeShareProvisioning, extractInvitePayload, extractReplicationOps, filterReplicationOpsForSyncWithStatus, fingerprintPublicKey, formatHostPort, friendlyDeviceName, fromJson, generateWithOpenCodeV2, getCodememConfigPath, getCodememEnvOverrideValues, getCodememEnvOverrides, getCoordinatorEnrollmentReconciliationIssueSummary, getCoordinatorGroupPreference, getEffectiveCachedScopeAuthorization, getLegacyTeamSetupDraft, getRecipientPolicyAuthorityState, getSemanticIndexDiagnostics, getSyncResetState, getUpdateStatus, ingestRawEvents, inspectFreshLegacyTeamSetupActivation, inspectLegacyTeamSetupActivation, inviteTokenDigest, isAutomaticRecallMeasurement, isCoordinatorAdminDevice, isLegacyTeamCandidateSelectable, isLegacyTeamSetupProjectMappingIdentity, isPeerTrustBindingCompatible, isProjectScopeWithdrawn, isProjectSyncEnablementError, isScopedSyncCapability, judgeDistillReport, legacyDecisionCountsAsOwner, legacyPairingAssignmentsConverted, legacyTeamCandidateId, legacyTeamCandidateProjectInventory, legacyTeamCanonicalProjectRef, legacyTeamDeviceRef, legacyTeamResolvedProjectRef, legacyTeamSetupApiErrorCode, legacyTeamSetupCompletionActorIds, legacyTeamSetupFailureCheck, linkCoordinatorAccount, listAuthorizedScopesForPeer, listCoordinatorJoinRequests, listDeviceIdentityInventory, listInboundScopeRejections, listLegacyRecipientPolicyProjections, listMaintenanceJobs, listObserverProviderOptions, listOpenCodeV2Models, listPerPeerScopeSyncState, listProjectScopeCandidates, listProjectScopeInventory, listProjectScopeSettingsMappings, listRecipientPolicyIntent, listRecipientPolicyReview, listSharingDomainSettingsScopes, loadMemorySnapshotPageForPeer, loadPrivateKey, loadPublicKey, loadReplicationOpsForPeer, loadRuntimeSigningPublicKey, lookupCoordinatorPeers, markLocalIdentitySwitchBound, markLocalIdentitySwitchNotCommitted, memoryFilterValueMatchesType, mergeAddresses, migrateRecipientPolicyIntent, mutateCodememConfigFile, negotiateSyncCapability, newPairingFiltersNeedAdmin, normalizeAddress, normalizeCoordinatorAccountLinkOrigin, normalizeCoordinatorLegacyTeamCompletionManifest, normalizeHumanPresentationName, normalizeSyncCapability, normalizeSyncFeatures, normalizeTeammateName, parseAcceptedProjectIntent, parseBootstrapExpiry, parseFileContextTransportRequest, parsePositiveMemoryId, parseReassignScopePayload, parseRecipientPolicyEdgeCommitRequest, parseStrictInteger, parseSyncScopeRequest, persistShareOperation, personalScopeGrantStatusForPeer, planShareOperation, previewDeviceIdentityBindings, previewLegacyTeamSetupActivation, previewRecipientPolicyEdges, previewRecipientPolicyOnboarding, previewRecipientPolicyOnboardingFromReviewedIntent, probeAvailableCredentials, projectMatchesFilter, projectScopeMappingSavesOnlyNarrow, projectShareLifecycle, projectWithdrawalStates, promptPackArtifactFingerprint, queryPeerRemoval, readAccountLinkDevice, readAccountOwnerAssociation, readAccountOwnerAssociationRetainedAtMs, readCodememConfigFile, readCodememConfigFileForMutation, readCompletedLocalIdentitySwitches, readCoordinatorAccountChangeCapabilities, readCoordinatorAccountLinkStatus, readCoordinatorDeviceRejoinEvents, readCoordinatorDeviceSetup, readCoordinatorRejoinDiscovery, readCoordinatorResolvedAccountOwnerReceiptStatus, readCoordinatorResolvedAccountOwnerStatus, readCoordinatorSyncConfig, readOpenLocalIdentitySwitch, readPeerSyncActivity, readRepositoryIdentitySnapshot, reassignProjectScopeInventoryProject, recipientInviteAuthoritativeIdentityId, recipientPolicyDigest, recipientReviewedIntentDigest, reconcileCoordinatorEnrollmentSnapshot, reconcileRecipientPolicyProject, reconcileShareOperationAcceptance, reconstructLegacyTeamSetupCompletionManifest, recordAutomaticRecall, recordHighestObservedDirectSignatureVersion, recordLocalIdentitySwitch, recordNonce, recordPromptPackArtifacts, recordPromptPackTerminal, recordSyncAttempt, recordSyncTransferObservation, refreshAuthorizedCoordinatorPeerTrust, refreshConfiguredScopeMembershipCache, refreshLegacyTeamCandidate, rejectInboundScopeFailures, removePairingState, removePeerFromThisDevice, removeRevokedPeers, renameRecipientPolicyTeam, replayLegacyTeamSetupActivation, repositoryIdentitiesByWorkspace, repositoryIdentityForWorkspace, requestJson, requireLegacyTeamSetupAccessDeltaWithinLimit, resolveCodememConfigPath, resolveDbPath, resolveObserverDefaultModel, resolveObserverRuntime, resolveProject, resolveProjectRoot, resolveRecipientPolicyReview, resolveRecipientPolicyReviewBulk, resolveRetireTarget, resolveVisibleScopeIds, resumeDeviceRebind, resumeProjectOnThisDevice, retireDeviceLocally, runDeviceRebind, runSyncPass, schema, scopeAuthorizationFailureReason, searchPiSessions, serializeRecipientPolicyActorMutations, serializeRecipientPolicyCoordinatorGroupMutation, serializeRecipientPolicyPublicationMutation, serializeRecipientPolicyTeamMutation, setLegacyTeamSetupDeviceAssignment, setLegacyTeamSetupDeviceDecision, setLegacyTeamSetupProjectMapping, setLocalSyncFeature, setPeerProjectFilterChecked, stopProjectOnThisDevice, summarizeInboundScopeRejections, summaryLikeSqlPredicate, supportsSyncFeature, syncScopeResetRequiredPayload, toJson, tryUpdateRetrievalDelivery, updatePeerAddresses, upsertCoordinatorGroupPreference, upsertProjectScopeSettingsMappings, validateLegacyTeamSetupCompletionManifest, validateLegacyTeamSetupCompletionManifestBinding, validateRawEvents, verifiedLocalKeyId, verifyDirectPeerSignature, verifyRecipientReviewedIntent, verifySignature, wakeRecipientPoliciesForIdentities, wakeRecipientPoliciesForProjectIdentities } from "@codemem/core";
3
+ import { ACCESS_CLEANUP_OP_TYPE, CodememConfigMutationError, CoordinatorAccountLinkError, CoordinatorReciprocalApprovalRequestChangedError, DEFAULT_TIME_WINDOW_S, FILE_CONTEXT_TRANSPORT_MAX_BYTES, LEGACY_SHARED_REVIEW_SCOPE_ID, LOCAL_DEFAULT_SCOPE_ID, LOCAL_SYNC_CAPABILITY, LOCAL_SYNC_FEATURES, LegacyTeamSetupAdditiveConvergenceError, LegacyTeamSetupDeviceRemovalsUnavailableError, LegacyTeamSetupRosterCapacityError, LocalIdentitySupersededError, MEMORY_FILTER_FIELD_TYPES, MEMORY_FILTER_NAMES, MEMORY_KIND_DESCRIPTIONS, MemoryStore, ObserverClient, PROMPT_TRANSPORT_PROTOCOL_RANGE, RECIPIENT_POLICY_SHARED_SCOPE_CODE, REMEMBER_MEMORY_KINDS, RICH_TIER_ANTHROPIC_DEFAULTS, RICH_TIER_DEFAULTS, RawEventIngestValidationError, RecipientPolicyEdgeRequestError, RecipientPolicyTeamCreateError, RecipientPolicyTeamRenameError, RemoteCoordinatorRequestError, SCOPE_MEMBERSHIP_REVOCATION_LIMITATION, SIMPLE_TIER_ANTHROPIC_DEFAULTS, SIMPLE_TIER_DEFAULTS, SYNC_AUTHORIZATION_REFRESH_HEADER, SYNC_CAPABILITY_HEADER, SYNC_FEATURES_HEADER, SYNC_SCOPE_QUERY_PARAM, VERSION, VERSION as VERSION$1, VIEWER_IDENTITY_TARGET_KEYS, VIEWER_SERVICE_DISCRIMINATOR, addSyncScopeToBoundary, analyzeProjectScopeMappingChangeGuardrails, analyzeProjectScopeMappingChangesGuardrails, analyzeProjectScopeMappingDeletionGuardrails, applyLegacyTeamSetupCompletionManifest, applyLegacyTeamSetupCompletionManifestAndReturnActivation, applyLocalIdentitySwitch, applyPeerReplicationOps, areLegacyTeamSetupCompletionPolicyFactsAdditivelyCompatible, assertNoLocalIdentityOverride, automaticRecallHealth, buildAuthHeaders, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildFilterBranchesWithContext, buildFilterClausesWithContext, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromCodexHook, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildViewerIdentityTarget, canonicalCoordinatorLegacyTeamCompletionManifestJson, canonicalKeyId, canonicalMemoryKind, canonicalRepositoryProjectIdentity, canonicalWorkspaceIdentity, captureAccountOwnerProfilePins, changeCoordinatorAccount, claimRecipientPolicyActorMutations, claimRecipientPolicyPublicationMutation, classifyRecordedSyncFailure, cleanupNonces, clearLegacyTeamSetupDeviceDecision, clonePromptPackAttempt, coerceObserverCommand, commitDeviceIdentityBindings, commitRecipientPolicyEdges, commitViewerDeviceRemoval, completeCoordinatorDeviceSetup, completeLocalIdentitySwitch, containLegacyTeamSetupCompletionConflict, convertLegacyPairingAssignments, coordinatorAdminReadiness, coordinatorArchiveGroupAction, coordinatorAuthControllerReviewAction, coordinatorCreateAddDeviceInviteAction, coordinatorCreateGroupAction, coordinatorCreateInviteAction, coordinatorCreateLegacyTeamCompletionAction, coordinatorCreateScopeAction, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorGetLegacyTeamCompletionAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListConsumedTeamInvitesAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListRemovedDevicesAction, coordinatorListReviewedRecipientInviteEvidenceAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorListTeamMemberRemovalsAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorRenameGroupAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeDeviceAction, coordinatorRevokeScopeMembershipAction, coordinatorStatusSnapshot, coordinatorUnarchiveGroupAction, coordinatorUpdateScopeAction, countShareableProjectMemories, countUnattributedImportedProjectMemories, createCoordinatorReciprocalApproval, createRecipientPolicyBoundaryInspector, createRecipientPolicyTeam, decodeInvitePayload, dedupeOrderedIds, defaultSpaceScopeIdForGroup, deleteProjectScopeSettingsMapping, deriveLegacyTeamSetupCompletionManifest, detectInstallKind, deterministicPolicyTeamId, diagnoseStalePeerReceivedRows, discoverLegacyTeamCandidates, dispatchFileContextTransport, ensureDeviceIdentity, executeShareProvisioning, extractInvitePayload, extractReplicationOps, fetchPeerRemovalLookup, filterReplicationOpsForSyncWithStatus, fingerprintPublicKey, formatHostPort, friendlyDeviceName, fromJson, generateWithOpenCodeV2, getCodememConfigPath, getCodememEnvOverrideValues, getCodememEnvOverrides, getCoordinatorEnrollmentReconciliationIssueSummary, getCoordinatorGroupPreference, getEffectiveCachedScopeAuthorization, getLegacyTeamSetupDraft, getRecipientPolicyAuthorityState, getSemanticIndexDiagnostics, getSyncResetState, getUpdateStatus, ingestRawEvents, inspectFreshLegacyTeamSetupActivation, inspectLegacyTeamSetupActivation, inviteTokenDigest, isAutomaticRecallMeasurement, isCoordinatorAdminDevice, isLegacyTeamCandidateSelectable, isLegacyTeamSetupProjectMappingIdentity, isPeerTrustBindingCompatible, isProjectScopeWithdrawn, isProjectSyncEnablementError, isScopedSyncCapability, judgeDistillReport, legacyDecisionCountsAsOwner, legacyPairingAssignmentsConverted, legacyTeamCandidateId, legacyTeamCandidateProjectInventory, legacyTeamCanonicalProjectRef, legacyTeamDeviceRef, legacyTeamResolvedProjectRef, legacyTeamSetupApiErrorCode, legacyTeamSetupCompletionActorIds, legacyTeamSetupFailureCheck, linkCoordinatorAccount, listAuthorizedScopesForPeer, listCoordinatorJoinRequests, listDeviceIdentityInventory, listInboundScopeRejections, listLegacyRecipientPolicyProjections, listMaintenanceJobs, listObserverProviderOptions, listOpenCodeV2Models, listPerPeerScopeSyncState, listProjectScopeCandidates, listProjectScopeInventory, listProjectScopeSettingsMappings, listRecipientPolicyIntent, listRecipientPolicyReview, listSharingDomainSettingsScopes, loadMemorySnapshotPageForPeer, loadPrivateKey, loadPublicKey, loadReplicationOpsForPeer, loadRuntimeSigningPublicKey, lookupCoordinatorPeers, markLocalIdentitySwitchBound, markLocalIdentitySwitchNotCommitted, memoryFilterValueMatchesType, mergeAddresses, migrateRecipientPolicyIntent, mutateCodememConfigFile, negotiateSyncCapability, newPairingFiltersNeedAdmin, normalizeAddress, normalizeCoordinatorAccountLinkOrigin, normalizeCoordinatorLegacyTeamCompletionManifest, normalizeHumanPresentationName, normalizeSyncCapability, normalizeSyncFeatures, normalizeTeammateName, parseAcceptedProjectIntent, parseBootstrapExpiry, parseFileContextTransportRequest, parsePositiveMemoryId, parseReassignScopePayload, parseRecipientPolicyEdgeCommitRequest, parseStrictInteger, parseSyncScopeRequest, peerFacingScopeResetReason, persistShareOperation, personalScopeGrantStatusForPeer, planShareOperation, previewDeviceIdentityBindings, previewLegacyTeamSetupActivation, previewRecipientPolicyEdges, previewRecipientPolicyOnboarding, previewRecipientPolicyOnboardingFromReviewedIntent, probeAvailableCredentials, projectMatchesFilter, projectScopeMappingSavesOnlyNarrow, projectShareLifecycle, projectWithdrawalStates, promptPackArtifactFingerprint, queryPeerRemoval, readAccountLinkDevice, readAccountOwnerAssociation, readAccountOwnerAssociationRetainedAtMs, readCodememConfigFile, readCodememConfigFileForMutation, readCompletedLocalIdentitySwitches, readCoordinatorAccountChangeCapabilities, readCoordinatorAccountLinkStatus, readCoordinatorDeviceRejoinEvents, readCoordinatorDeviceSetup, readCoordinatorRejoinDiscovery, readCoordinatorResolvedAccountOwnerReceiptStatus, readCoordinatorResolvedAccountOwnerStatus, readCoordinatorSyncConfig, readOpenLocalIdentitySwitch, readPeerSyncActivity, readRepositoryIdentitySnapshot, reassignProjectScopeInventoryProject, recipientInviteAuthoritativeIdentityId, recipientPolicyDigest, recipientReviewedIntentDigest, reconcileCoordinatorEnrollmentSnapshot, reconcileRecipientPolicyProject, reconcileShareOperationAcceptance, reconstructLegacyTeamSetupCompletionManifest, recordAutomaticRecall, recordHighestObservedDirectSignatureVersion, recordLocalIdentitySwitch, recordNonce, recordPromptPackArtifacts, recordPromptPackTerminal, recordSyncAttempt, recordSyncTransferObservation, refreshAuthorizedCoordinatorPeerTrust, refreshConfiguredScopeMembershipCache, refreshLegacyTeamCandidate, rejectInboundScopeFailures, removePairingState, removePeerFromThisDevice, removeRevokedPeers, renameRecipientPolicyTeam, replayLegacyTeamSetupActivation, repositoryIdentitiesByWorkspace, repositoryIdentityForWorkspace, requestJson, requireLegacyTeamSetupAccessDeltaWithinLimit, resolveCodememConfigPath, resolveDbPath, resolveObserverDefaultModel, resolveObserverRuntime, resolveProject, resolveProjectRoot, resolveRecipientPolicyReview, resolveRecipientPolicyReviewBulk, resolveRetireTarget, resolveVisibleScopeIds, resumeDeviceRebind, resumeProjectOnThisDevice, retireDeviceLocally, runDeviceRebind, runSyncPass, schema, scopeAuthorizationFailureReason, scopesWrittenByInboundOp, searchPiSessions, serializeRecipientPolicyActorMutations, serializeRecipientPolicyCoordinatorGroupMutation, serializeRecipientPolicyPublicationMutation, serializeRecipientPolicyTeamMutation, setLegacyTeamSetupDeviceAssignment, setLegacyTeamSetupDeviceDecision, setLegacyTeamSetupProjectMapping, setLocalSyncFeature, setPeerProjectFilterChecked, stopProjectOnThisDevice, summarizeInboundScopeRejections, summaryLikeSqlPredicate, supportsSyncFeature, syncScopeResetRequiredPayload, toJson, tryUpdateRetrievalDelivery, updatePeerAddresses, upsertCoordinatorGroupPreference, upsertProjectScopeSettingsMappings, validateLegacyTeamSetupCompletionManifest, validateLegacyTeamSetupCompletionManifestBinding, validateRawEvents, verifiedLocalKeyId, verifyDirectPeerSignature, verifyRecipientReviewedIntent, verifySignature, wakeRecipientPoliciesForIdentities, wakeRecipientPoliciesForProjectIdentities } from "@codemem/core";
4
4
  import { serveStatic } from "@hono/node-server/serve-static";
5
5
  import { Hono } from "hono";
6
6
  import { createCipheriv, createDecipheriv, createHash, createPrivateKey, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
@@ -1801,7 +1801,7 @@ var DEFAULTS = {
1801
1801
  observer_auth_timeout_ms: 1500,
1802
1802
  observer_auth_cache_ttl_s: 300,
1803
1803
  observer_headers: {},
1804
- observer_max_chars: 12e3,
1804
+ observer_max_chars: 24e3,
1805
1805
  pack_observation_limit: 50,
1806
1806
  pack_session_limit: 10,
1807
1807
  sync_enabled: false,
@@ -4696,6 +4696,309 @@ function memoryToolCallRoutes(getStore, call) {
4696
4696
  return app;
4697
4697
  }
4698
4698
  //#endregion
4699
+ //#region ../memory-tools/src/json-schema.ts
4700
+ function withDescription(schema, description) {
4701
+ return description ? {
4702
+ ...schema,
4703
+ description
4704
+ } : schema;
4705
+ }
4706
+ function string(description) {
4707
+ return withDescription({ type: "string" }, description);
4708
+ }
4709
+ function boolean(description) {
4710
+ return withDescription({ type: "boolean" }, description);
4711
+ }
4712
+ function number(options = {}) {
4713
+ const { description, ...bounds } = options;
4714
+ return withDescription({
4715
+ type: "number",
4716
+ ...bounds
4717
+ }, description);
4718
+ }
4719
+ function integer$1(options = {}) {
4720
+ const { description, ...bounds } = options;
4721
+ return withDescription({
4722
+ type: "integer",
4723
+ ...bounds
4724
+ }, description);
4725
+ }
4726
+ function stringArray(description) {
4727
+ return withDescription({
4728
+ type: "array",
4729
+ items: { type: "string" }
4730
+ }, description);
4731
+ }
4732
+ function integerArray(options = {}) {
4733
+ const { description, ...bounds } = options;
4734
+ return withDescription({
4735
+ type: "array",
4736
+ items: { type: "integer" },
4737
+ ...bounds
4738
+ }, description);
4739
+ }
4740
+ function stringEnum(values, description) {
4741
+ return withDescription({
4742
+ type: "string",
4743
+ enum: [...values]
4744
+ }, description);
4745
+ }
4746
+ function anyOf(variants, description) {
4747
+ return withDescription({ anyOf: variants }, description);
4748
+ }
4749
+ function withDefault(schema, value) {
4750
+ return {
4751
+ ...schema,
4752
+ default: value
4753
+ };
4754
+ }
4755
+ /** Build an object schema; `required` lists the properties without defaults that callers must send. */
4756
+ function object(properties, required = []) {
4757
+ const schema = {
4758
+ type: "object",
4759
+ properties
4760
+ };
4761
+ if (required.length > 0) schema.required = required;
4762
+ return schema;
4763
+ }
4764
+ function clampSearchIndexLimit(limit) {
4765
+ if (Number.isNaN(limit)) return 8;
4766
+ return Math.min(50, Math.max(1, Math.trunc(limit)));
4767
+ }
4768
+ function clipJsonString(value, maxBytes) {
4769
+ if (value.length <= maxBytes - 2 && Buffer.byteLength(JSON.stringify(value)) <= maxBytes) return value;
4770
+ let remaining = maxBytes - 5;
4771
+ let prefix = "";
4772
+ for (const character of value) {
4773
+ remaining -= Buffer.byteLength(JSON.stringify(character)) - 2;
4774
+ if (remaining < 0) break;
4775
+ prefix += character;
4776
+ }
4777
+ return `${prefix}…`;
4778
+ }
4779
+ function isInteger(value) {
4780
+ return typeof value === "number" && Number.isSafeInteger(value);
4781
+ }
4782
+ function wideningLabels(value) {
4783
+ if (value === null || typeof value !== "object") return {};
4784
+ const metadata = value;
4785
+ return {
4786
+ ...metadata.widened_from_project === true ? { widened_from_project: true } : {},
4787
+ ...metadata.widened_from_shared === true ? { widened_from_shared: true } : {},
4788
+ ...metadata.widened_from_project === true && typeof metadata.source_project === "string" ? { source_project: clipJsonString(metadata.source_project, 48) } : {}
4789
+ };
4790
+ }
4791
+ function indexItem(value) {
4792
+ if (value === null || typeof value !== "object") return [];
4793
+ const { id, kind, title, score, created_at, session_id, metadata } = value;
4794
+ if (!isInteger(id) || !isInteger(session_id)) return [];
4795
+ if (typeof score !== "number" || !Number.isFinite(score)) return [];
4796
+ if (typeof kind !== "string" || typeof title !== "string" || typeof created_at !== "string") return [];
4797
+ return [{
4798
+ id,
4799
+ kind: clipJsonString(kind, 48),
4800
+ title: clipJsonString(title, 256),
4801
+ score,
4802
+ created_at: clipJsonString(created_at, 48),
4803
+ session_id,
4804
+ metadata: wideningLabels(metadata)
4805
+ }];
4806
+ }
4807
+ /** Keep ranked results and label widening without copying stored metadata wholesale. */
4808
+ function projectSearchIndex(rows, limit) {
4809
+ return { items: rows.slice(0, clampSearchIndexLimit(limit)).flatMap(indexItem) };
4810
+ }
4811
+ //#endregion
4812
+ //#region ../memory-tools/src/contracts.ts
4813
+ /**
4814
+ * Memory tool contracts shared by every thin host (OpenCode plugin, pi
4815
+ * extension). Names, descriptions, and input schemas mirror the MCP server
4816
+ * registrations in packages/mcp-server/src/tools/*; the parity test in
4817
+ * packages/mcp-server/src/tool-contract-parity.test.ts fails CI on drift.
4818
+ *
4819
+ * This module has no runtime dependencies and never imports @codemem/core.
4820
+ */
4821
+ /** Memory kinds `memory_remember` accepts; mirrors core REMEMBER_MEMORY_KINDS. */
4822
+ var REMEMBER_MEMORY_KINDS$1 = [
4823
+ "discovery",
4824
+ "change",
4825
+ "feature",
4826
+ "bugfix",
4827
+ "refactor",
4828
+ "decision",
4829
+ "exploration"
4830
+ ];
4831
+ var scopeFilterProperties = {
4832
+ scope_id: string("Filter by a single sharing domain scope_id"),
4833
+ include_scope_ids: stringArray("Sharing domain scope_ids to include"),
4834
+ exclude_scope_ids: stringArray("Sharing domain scope_ids to exclude")
4835
+ };
4836
+ /** Mirrors packages/mcp-server/src/schemas.ts filterSchema, in declaration order. */
4837
+ var FILTER_PROPERTIES = {
4838
+ kind: string("Filter by memory kind"),
4839
+ project: string("Filter by project scope (matches sessions.project)"),
4840
+ ...scopeFilterProperties,
4841
+ visibility: stringArray(),
4842
+ include_visibility: stringArray(),
4843
+ exclude_visibility: stringArray(),
4844
+ include_workspace_ids: stringArray(),
4845
+ exclude_workspace_ids: stringArray(),
4846
+ include_workspace_kinds: stringArray(),
4847
+ exclude_workspace_kinds: stringArray(),
4848
+ include_actor_ids: stringArray(),
4849
+ exclude_actor_ids: stringArray(),
4850
+ include_trust_states: stringArray(),
4851
+ exclude_trust_states: stringArray(),
4852
+ ownership_scope: string(),
4853
+ personal_first: anyOf([boolean(), string()]),
4854
+ trust_bias: string(),
4855
+ widen_shared_when_weak: anyOf([boolean(), string()]),
4856
+ widen_shared_min_personal_results: integer$1(),
4857
+ widen_shared_min_personal_score: number()
4858
+ };
4859
+ Object.keys(FILTER_PROPERTIES).toSorted();
4860
+ var depthProperties = (beforeLabel, afterLabel) => ({
4861
+ depth_before: withDefault(integer$1({
4862
+ minimum: 0,
4863
+ description: beforeLabel
4864
+ }), 3),
4865
+ depth_after: withDefault(integer$1({
4866
+ minimum: 0,
4867
+ description: afterLabel
4868
+ }), 3)
4869
+ });
4870
+ object({
4871
+ query: string("Search query"),
4872
+ limit: withDefault(integer$1({
4873
+ minimum: 1,
4874
+ maximum: 50,
4875
+ description: "Max results"
4876
+ }), 5),
4877
+ ...FILTER_PROPERTIES
4878
+ }, ["query"]);
4879
+ object({
4880
+ query: string("Search query"),
4881
+ limit: withDefault(integer$1({
4882
+ minimum: 1,
4883
+ maximum: 50,
4884
+ description: "Max results"
4885
+ }), 8),
4886
+ ...FILTER_PROPERTIES
4887
+ }, ["query"]);
4888
+ object({
4889
+ query: string("Search query"),
4890
+ ids: integerArray({
4891
+ maxItems: 200,
4892
+ description: "Specific memory IDs to explain"
4893
+ }),
4894
+ limit: withDefault(integer$1({
4895
+ minimum: 1,
4896
+ maximum: 50,
4897
+ description: "Max results"
4898
+ }), 10),
4899
+ include_pack_context: withDefault(boolean("Include formatted pack context"), false),
4900
+ ...FILTER_PROPERTIES
4901
+ });
4902
+ object({
4903
+ limit: withDefault(integer$1({
4904
+ minimum: 1,
4905
+ maximum: 100,
4906
+ description: "Max results"
4907
+ }), 8),
4908
+ ...FILTER_PROPERTIES
4909
+ });
4910
+ object({
4911
+ context: string("Context description to search for"),
4912
+ limit: integer$1({
4913
+ minimum: 1,
4914
+ maximum: 50,
4915
+ description: "Max items to include"
4916
+ }),
4917
+ compact: boolean("When true, render a scannable index of all items with full detail only for the top N (default 3). Saves tokens when broad overview matters more than per-item detail."),
4918
+ compact_detail_count: integer$1({
4919
+ minimum: 0,
4920
+ maximum: 50,
4921
+ description: "Number of items to show in full detail in compact mode (default 3)"
4922
+ }),
4923
+ compression_mode: stringEnum([
4924
+ "off",
4925
+ "compact",
4926
+ "ids"
4927
+ ], "Near-related compression mode: off disables it, compact applies only to compact rendering, ids applies in all modes. Defaults to CODEMEM_PACK_COMPRESSION or compact."),
4928
+ ...FILTER_PROPERTIES
4929
+ }, ["context"]);
4930
+ object({
4931
+ query: string("Search query to find anchor"),
4932
+ memory_id: integer$1({ description: "Anchor memory ID" }),
4933
+ ...depthProperties("Items before anchor", "Items after anchor"),
4934
+ ...FILTER_PROPERTIES
4935
+ });
4936
+ object({
4937
+ ids: {
4938
+ type: "array",
4939
+ items: anyOf([number(), string()]),
4940
+ maxItems: 200,
4941
+ description: "Memory IDs to expand"
4942
+ },
4943
+ ...depthProperties("Timeline items before", "Timeline items after"),
4944
+ include_observations: withDefault(boolean("Include full observation details"), false),
4945
+ ...FILTER_PROPERTIES
4946
+ }, ["ids"]);
4947
+ object({
4948
+ memory_id: integer$1({ description: "Memory ID" }),
4949
+ ...FILTER_PROPERTIES
4950
+ }, ["memory_id"]);
4951
+ object({
4952
+ ids: integerArray({
4953
+ maxItems: 200,
4954
+ description: "Memory IDs to fetch"
4955
+ }),
4956
+ compact: boolean("Return only id, kind, title, body_text, and project"),
4957
+ ...FILTER_PROPERTIES
4958
+ }, ["ids"]);
4959
+ object({
4960
+ kind: stringEnum(REMEMBER_MEMORY_KINDS$1, "Memory kind"),
4961
+ title: string("Short title"),
4962
+ body: string("Body text (high-signal content)"),
4963
+ confidence: withDefault(number({
4964
+ minimum: 0,
4965
+ maximum: 1,
4966
+ description: "Confidence 0-1"
4967
+ }), .5),
4968
+ project: string("Project identifier")
4969
+ }, [
4970
+ "kind",
4971
+ "title",
4972
+ "body"
4973
+ ]);
4974
+ object({
4975
+ memory_id: integer$1({ description: "Memory ID to forget" }),
4976
+ ...FILTER_PROPERTIES
4977
+ }, ["memory_id"]);
4978
+ object({
4979
+ limit: withDefault(integer$1({
4980
+ minimum: 1,
4981
+ maximum: 50,
4982
+ description: "Max candidates"
4983
+ }), 10),
4984
+ min_recurrence: withDefault(integer$1({
4985
+ minimum: 1,
4986
+ maximum: 50,
4987
+ description: "Minimum member count per candidate"
4988
+ }), 2),
4989
+ all_projects: withDefault(boolean("Mine memories across all projects"), false),
4990
+ include_documented: withDefault(boolean("Include candidates already represented in context files"), false),
4991
+ max_evidence_items: withDefault(integer$1({
4992
+ minimum: 1,
4993
+ maximum: 20,
4994
+ description: "Evidence snippets per candidate"
4995
+ }), 5),
4996
+ judge: withDefault(boolean("Judge candidates with the observer model and drop routine-activity clusters (on by default; falls back to unjudged output when no observer model is configured)"), true),
4997
+ ...FILTER_PROPERTIES
4998
+ });
4999
+ object({});
5000
+ object({});
5001
+ //#endregion
4699
5002
  //#region src/routes/memory-tools.ts
4700
5003
  /**
4701
5004
  * Memory tool-support routes — HTTP twins of MCP tools that the viewer
@@ -4891,17 +5194,6 @@ function buildDistillFilters(args, defaultProject) {
4891
5194
  };
4892
5195
  return buildFilters(args, args.all_projects ? null : defaultProject);
4893
5196
  }
4894
- function mapSearchIndexItem(m) {
4895
- return {
4896
- id: m.id,
4897
- kind: m.kind,
4898
- title: m.title,
4899
- score: m.score,
4900
- created_at: m.created_at,
4901
- session_id: m.session_id,
4902
- metadata: m.metadata
4903
- };
4904
- }
4905
5197
  function expandMemories(store, args) {
4906
5198
  const resolvedProject = args.filters?.project ?? null;
4907
5199
  const { ordered: orderedIds, invalid: invalidIds } = dedupeOrderedIds(args.ids);
@@ -5103,11 +5395,10 @@ function memoryToolRoutes(getStore) {
5103
5395
  const store = getStore();
5104
5396
  const query = c.req.query("query") ?? "";
5105
5397
  if (!query.trim()) return c.json({ error: "query required" }, 400);
5106
- const limit = clampInt(queryInt(c.req.query("limit"), 8), 1, 50);
5398
+ const limit = clampSearchIndexLimit(queryInt(c.req.query("limit"), 8));
5107
5399
  const parsedFilters = parseGetFilters((name) => c.req.query(name));
5108
5400
  if (!parsedFilters.ok) return c.json({ error: parsedFilters.error }, 400);
5109
- const items = store.search(query, limit, parsedFilters.filters).map(mapSearchIndexItem);
5110
- return c.json({ items });
5401
+ return c.json(projectSearchIndex(store.search(query, limit, parsedFilters.filters), limit));
5111
5402
  });
5112
5403
  app.post("/api/memories/explain", async (c) => {
5113
5404
  const store = getStore();
@@ -5523,7 +5814,7 @@ function validatePackRequest(value) {
5523
5814
  }
5524
5815
  function ledgerFailureStatus(reason) {
5525
5816
  if (reason === "idempotency_conflict") return 409;
5526
- if (reason === "attempt_not_found") return 422;
5817
+ if (reason === "attempt_not_found" || reason === "attempt_incomplete") return 422;
5527
5818
  if (reason === "storage_unavailable") return 503;
5528
5819
  return 400;
5529
5820
  }
@@ -5978,6 +6269,15 @@ async function advancePendingProjectSharesOperation(store, options) {
5978
6269
  var RECIPIENT_POLICY_MAINTENANCE_MAX_LIMIT = 10;
5979
6270
  var RECIPIENT_POLICY_MAINTENANCE_DEFAULT_LIMIT = 3;
5980
6271
  var RECIPIENT_POLICY_MAINTENANCE_BACKOFF_MS = 6e4;
6272
+ /**
6273
+ * A legacy Project in a shared multi-Project scope gets the same answer on every attempt until
6274
+ * its scope mapping or the scope's Projects change, so it is not retried on a timer. A wake
6275
+ * (which clears last_attempt_at) still runs it. The check reads only local mappings and scopes:
6276
+ * a coordinator refresh that changes the scope updates those rows, and the next check sees it.
6277
+ */
6278
+ function waitsForSharedScopeChange(authority, projectId, boundaryBlocker) {
6279
+ return authority.authority_state === "legacy" && authority.safe_error_code === RECIPIENT_POLICY_SHARED_SCOPE_CODE && boundaryBlocker(projectId) === RECIPIENT_POLICY_SHARED_SCOPE_CODE;
6280
+ }
5981
6281
  function recipientPolicyMaintenanceCandidates(store, retryBefore, limit) {
5982
6282
  const repositoryIdentities = repositoryIdentitiesByWorkspace(store.db);
5983
6283
  const canonicalize = (projectId) => canonicalRepositoryProjectIdentity(repositoryIdentities, projectId);
@@ -6000,9 +6300,12 @@ function recipientPolicyMaintenanceCandidates(store, retryBefore, limit) {
6000
6300
  }
6001
6301
  if (String(row.last_attempt_at ?? "") > String(current.last_attempt_at ?? "")) authorityByProject.set(projectId, row);
6002
6302
  }
6303
+ const boundaryBlocker = createRecipientPolicyBoundaryInspector(store.db);
6003
6304
  return [...new Set(projectIds.map((row) => canonicalize(row.canonical_project_identity)))].filter((projectId) => {
6004
6305
  const authority = authorityByProject.get(projectId);
6005
- return authority == null || authority.last_attempt_at == null || authority.safe_error_code == null && authority.authority_state !== "active" || authority.last_attempt_at <= retryBefore;
6306
+ if (authority == null || authority.last_attempt_at == null) return true;
6307
+ if (waitsForSharedScopeChange(authority, projectId, boundaryBlocker)) return false;
6308
+ return authority.safe_error_code == null && authority.authority_state !== "active" || authority.last_attempt_at <= retryBefore;
6006
6309
  }).toSorted((left, right) => {
6007
6310
  const leftAttempt = authorityByProject.get(left)?.last_attempt_at;
6008
6311
  const rightAttempt = authorityByProject.get(right)?.last_attempt_at;
@@ -7023,6 +7326,9 @@ function completionFailureHandlers(options) {
7023
7326
  reportFailure
7024
7327
  };
7025
7328
  }
7329
+ function isNonDivergentApplyFailure(error) {
7330
+ return error instanceof LegacyTeamSetupAdditiveConvergenceError || error instanceof LegacyTeamSetupDeviceRemovalsUnavailableError;
7331
+ }
7026
7332
  function completionConflictError(cause) {
7027
7333
  return new Error("team_setup_completion_conflict", { cause });
7028
7334
  }
@@ -7040,18 +7346,52 @@ function groupCompletionFailureHandler(groups, handleFailure) {
7040
7346
  if (group) handleFailure(group, error);
7041
7347
  };
7042
7348
  }
7349
+ /** The safe cause behind a retryable completion failure, when one is known. */
7350
+ function completionFailureReason(error) {
7351
+ return errorChain(error).some((item) => item instanceof LegacyTeamSetupDeviceRemovalsUnavailableError) ? "device_removals_unavailable" : void 0;
7352
+ }
7353
+ function completionBlocker(error) {
7354
+ const code = apiErrorCode(new Error(completionApiError(error)));
7355
+ const reason = completionFailureReason(error);
7356
+ return reason && code === "team_setup_completion_unavailable" ? {
7357
+ code,
7358
+ reason
7359
+ } : { code };
7360
+ }
7361
+ /** A detail read failure, with the safe completion cause when one is known. */
7362
+ function detailFailure(error, route) {
7363
+ const failure = teamSetupFailure(error, route);
7364
+ const { reason } = completionBlocker(error);
7365
+ return {
7366
+ body: reason ? {
7367
+ error: failure.code,
7368
+ reason
7369
+ } : { error: failure.code },
7370
+ status: failure.status
7371
+ };
7372
+ }
7043
7373
  function summaryReconciliationOptions(blockingErrors) {
7044
7374
  return {
7045
7375
  isolateApplyFailures: true,
7046
7376
  onFailure: (group, error) => {
7047
- blockingErrors.set(legacyTeamCandidateId(group.coordinatorId, group.groupId), apiErrorCode(new Error(completionApiError(error))));
7377
+ blockingErrors.set(legacyTeamCandidateId(group.coordinatorId, group.groupId), completionBlocker(error));
7048
7378
  }
7049
7379
  };
7050
7380
  }
7381
+ function lookupPeerRemovalsAsDaemon(store, config) {
7382
+ const keysDir = process.env.CODEMEM_KEYS_DIR?.trim() || void 0;
7383
+ const [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir });
7384
+ return fetchPeerRemovalLookup(store, config, {
7385
+ localDeviceId,
7386
+ keysDir
7387
+ });
7388
+ }
7051
7389
  var defaultCompletionDependencies = {
7052
7390
  create: coordinatorCreateLegacyTeamCompletionAction,
7053
7391
  get: coordinatorGetLegacyTeamCompletionAction,
7054
- list: coordinatorListLegacyTeamCompletionsAction
7392
+ list: coordinatorListLegacyTeamCompletionsAction,
7393
+ listRemovals: coordinatorListRemovedDevicesAction,
7394
+ lookupPeerRemovals: lookupPeerRemovalsAsDaemon
7055
7395
  };
7056
7396
  var defaultSnapshotLoaderDependencies = {
7057
7397
  readConfig: readCoordinatorSyncConfig,
@@ -7388,13 +7728,17 @@ function candidateFromDraft(draft) {
7388
7728
  unresolvedProjectCount: draft.unresolvedProjectCount
7389
7729
  };
7390
7730
  }
7391
- function blockedCandidateSummary(store, group, blockingError) {
7731
+ function blockedCandidateSummary(store, group, blocker) {
7392
7732
  const candidateRef = legacyTeamCandidateId(group.coordinatorId, group.groupId);
7393
7733
  const draft = getLegacyTeamSetupDraft(store.db, candidateRef);
7734
+ const blocking = {
7735
+ blockingError: blocker.code,
7736
+ ...blocker.reason ? { blockingReason: blocker.reason } : {}
7737
+ };
7394
7738
  if (draft) return {
7395
7739
  ...candidateSummary(candidateFromDraft(draft)),
7396
7740
  status: "stale",
7397
- blockingError
7741
+ ...blocking
7398
7742
  };
7399
7743
  const forbiddenIds = [
7400
7744
  group.coordinatorId,
@@ -7410,7 +7754,7 @@ function blockedCandidateSummary(store, group, blockingError) {
7410
7754
  candidateRef,
7411
7755
  displayName: safeChoiceLabel(group.displayName, "Legacy Team", forbiddenIds),
7412
7756
  status: "stale",
7413
- blockingError,
7757
+ ...blocking,
7414
7758
  deviceCount: group.devices.length,
7415
7759
  projectCount: 0,
7416
7760
  unresolvedDeviceCount: 0,
@@ -8184,6 +8528,81 @@ function saveDeviceAssignment(store, input) {
8184
8528
  releaseMutation();
8185
8529
  }
8186
8530
  }
8531
+ function readCompletionAuthorization(options) {
8532
+ const config = (options.readCoordinatorConfig ?? options.snapshotLoaderDependencies?.readConfig ?? readCoordinatorSyncConfig)();
8533
+ const remoteUrl = buildBaseUrl(config.syncCoordinatorUrl);
8534
+ if (!remoteUrl || !config.syncCoordinatorAdminSecret) return null;
8535
+ const configuredCoordinatorId = normalizedCoordinatorId(remoteUrl);
8536
+ if (!configuredCoordinatorId) return null;
8537
+ let currentGroupIds;
8538
+ try {
8539
+ currentGroupIds = new Set(configuredGroupIds$1(config.syncCoordinatorGroups));
8540
+ } catch {
8541
+ return null;
8542
+ }
8543
+ return {
8544
+ config,
8545
+ remoteUrl,
8546
+ configuredCoordinatorId,
8547
+ currentGroupIds
8548
+ };
8549
+ }
8550
+ /** One daemon lookup per reconciliation, read only when a missing device needs it. */
8551
+ function peerRemovalReader(dependencies, store, config) {
8552
+ let lookup;
8553
+ return () => {
8554
+ const read = dependencies.lookupPeerRemovals;
8555
+ if (!read) return Promise.resolve(void 0);
8556
+ lookup ??= Promise.resolve().then(() => read(store, config)).then((result) => result.status === "checked" ? {
8557
+ status: "read",
8558
+ removed: result.removed,
8559
+ enrolled: result.enrolled,
8560
+ generation: result.generation
8561
+ } : { status: "unavailable" }, () => ({ status: "unavailable" }));
8562
+ return lookup;
8563
+ };
8564
+ }
8565
+ function completionReadActions(dependencies, { authorization, store }, timeoutS, deadlineMs) {
8566
+ const { config, remoteUrl } = authorization;
8567
+ const adminSecret = config.syncCoordinatorAdminSecret;
8568
+ let removals;
8569
+ const listRemovals = () => {
8570
+ const read = dependencies.listRemovals;
8571
+ if (!read) return Promise.resolve(void 0);
8572
+ removals ??= read({
8573
+ includeBlocked: true,
8574
+ remote: {
8575
+ url: remoteUrl,
8576
+ adminSecret,
8577
+ timeoutS,
8578
+ deadlineMs
8579
+ }
8580
+ }).then((items) => ({
8581
+ status: "read",
8582
+ removals: items
8583
+ }), () => ({ status: "unavailable" }));
8584
+ return removals;
8585
+ };
8586
+ const listCompletionRecords = (groupIds) => retryTransientCoordinatorRead((attemptTimeoutS) => dependencies.list({
8587
+ groupIds,
8588
+ remoteUrl,
8589
+ adminSecret,
8590
+ timeoutS: attemptTimeoutS
8591
+ }), timeoutS, deadlineMs);
8592
+ return {
8593
+ listCompletionRecords,
8594
+ removalReads: {
8595
+ listRemovals,
8596
+ lookupPeerRemovals: peerRemovalReader(dependencies, store, config)
8597
+ }
8598
+ };
8599
+ }
8600
+ async function readRemovalEvidence(reads) {
8601
+ return {
8602
+ deviceRemovals: await reads.listRemovals(),
8603
+ peerRemovals: await reads.lookupPeerRemovals()
8604
+ };
8605
+ }
8187
8606
  function authorizesGroup(authorization, group) {
8188
8607
  return authorization.currentGroupIds.has(group.groupId) && normalizedCoordinatorId(group.coordinatorId) === authorization.configuredCoordinatorId;
8189
8608
  }
@@ -8238,30 +8657,7 @@ function teamSetupRoutes(options) {
8238
8657
  const loadedSummarySnapshots = createLoadedSummarySnapshotCache(loadedSnapshots, options);
8239
8658
  options.registerSummaryInvalidator?.(() => loadedSummarySnapshots.invalidate());
8240
8659
  const completionDependencies = options.completionDependencies === void 0 ? defaultCompletionDependencies : options.completionDependencies;
8241
- /**
8242
- * Reads the live coordinator configuration and the groups it currently
8243
- * authorizes. Returns null when completion I/O is not configured or current
8244
- * authorization cannot be proven.
8245
- */
8246
- function currentCompletionAuthorization() {
8247
- const config = (options.readCoordinatorConfig ?? options.snapshotLoaderDependencies?.readConfig ?? readCoordinatorSyncConfig)();
8248
- const remoteUrl = buildBaseUrl(config.syncCoordinatorUrl);
8249
- if (!remoteUrl || !config.syncCoordinatorAdminSecret) return null;
8250
- const configuredCoordinatorId = normalizedCoordinatorId(remoteUrl);
8251
- if (!configuredCoordinatorId) return null;
8252
- let currentGroupIds;
8253
- try {
8254
- currentGroupIds = new Set(configuredGroupIds$1(config.syncCoordinatorGroups));
8255
- } catch {
8256
- return null;
8257
- }
8258
- return {
8259
- config,
8260
- remoteUrl,
8261
- configuredCoordinatorId,
8262
- currentGroupIds
8263
- };
8264
- }
8660
+ const currentCompletionAuthorization = () => readCompletionAuthorization(options);
8265
8661
  function hasDraftEditAuthority(store, candidateRef) {
8266
8662
  const authorization = currentCompletionAuthorization();
8267
8663
  const group = persistedCompletionGroup(store, candidateRef);
@@ -8319,7 +8715,9 @@ function teamSetupRoutes(options) {
8319
8715
  * let a group removed while reconciliation waited on another policy
8320
8716
  * mutation still be applied once the queues open.
8321
8717
  */
8322
- async function applyCanonicalManifestIfStillAuthorized(store, authorization, group, manifest, freshRoster) {
8718
+ async function applyCanonicalManifestIfStillAuthorized(store, authorization, group, manifest, freshRoster, reads) {
8719
+ const freshIds = new Set(freshRoster.map((device) => device.deviceId));
8720
+ const removalEvidence = manifest.device_decisions.some((device) => device.decision === "included" && !freshIds.has(device.device_id)) ? await readRemovalEvidence(reads) : {};
8323
8721
  let outcome = "unauthorized";
8324
8722
  return await runCandidateMutation(store.db, legacyTeamCandidateId(group.coordinatorId, group.groupId), () => serializeCanonicalManifestMutation(store, group.groupId, manifest, async (actorIds) => {
8325
8723
  if (!stillAuthorizesGroup(authorization, group)) return;
@@ -8328,6 +8726,7 @@ function teamSetupRoutes(options) {
8328
8726
  groupId: group.groupId,
8329
8727
  manifest,
8330
8728
  freshRoster,
8729
+ ...removalEvidence,
8331
8730
  recipientPolicyLocksHeld: completionRecipientPolicyLocksHeld(actorIds)
8332
8731
  });
8333
8732
  outcome = "applied";
@@ -8349,13 +8748,11 @@ function teamSetupRoutes(options) {
8349
8748
  const timeoutS = Math.max(1, config.syncCoordinatorTimeoutS);
8350
8749
  try {
8351
8750
  const reconciliationDeadlineMs = Date.now() + COORDINATOR_ROSTER_READ_BUDGET_MS;
8751
+ const { listCompletionRecords, removalReads } = completionReadActions(completionDependencies, {
8752
+ authorization,
8753
+ store
8754
+ }, timeoutS, reconciliationDeadlineMs);
8352
8755
  const groupById = new Map(scopedGroups.map((group) => [group.groupId, group]));
8353
- const listCompletionRecords = (groupIds) => retryTransientCoordinatorRead((attemptTimeoutS) => completionDependencies.list({
8354
- groupIds,
8355
- remoteUrl,
8356
- adminSecret: config.syncCoordinatorAdminSecret,
8357
- timeoutS: attemptTimeoutS
8358
- }), timeoutS, reconciliationDeadlineMs);
8359
8756
  const scopedGroupIds = [...new Set(scopedGroups.map((group) => group.groupId))];
8360
8757
  let records;
8361
8758
  try {
@@ -8471,7 +8868,7 @@ function teamSetupRoutes(options) {
8471
8868
  }
8472
8869
  throw new Error("team_setup_completion_invalid");
8473
8870
  }
8474
- if (await applyCanonicalManifestIfStillAuthorized(store, authorization, group, canonicalManifest, freshGroup.devices) !== "applied") continue;
8871
+ if (await applyCanonicalManifestIfStillAuthorized(store, authorization, group, canonicalManifest, freshGroup.devices, removalReads) !== "applied") continue;
8475
8872
  } catch (error) {
8476
8873
  handleFailure(group, error);
8477
8874
  }
@@ -8537,9 +8934,9 @@ function teamSetupRoutes(options) {
8537
8934
  try {
8538
8935
  const freshGroup = await loadFreshGroupSnapshot(group, remoteUrl, reconciliationDeadlineMs);
8539
8936
  if (!freshGroup) throw new Error("team_setup_roster_unavailable");
8540
- if (await applyCanonicalManifestIfStillAuthorized(store, authorization, group, canonicalManifest, freshGroup.devices) !== "applied") continue;
8937
+ if (await applyCanonicalManifestIfStillAuthorized(store, authorization, group, canonicalManifest, freshGroup.devices, removalReads) !== "applied") continue;
8541
8938
  } catch (applyError) {
8542
- if (applyError instanceof LegacyTeamSetupAdditiveConvergenceError) {
8939
+ if (isNonDivergentApplyFailure(applyError)) {
8543
8940
  handleFailure(group, applyError);
8544
8941
  continue;
8545
8942
  }
@@ -8648,8 +9045,8 @@ function teamSetupRoutes(options) {
8648
9045
  if (completionGroups) candidate = candidateFromDraft(draft);
8649
9046
  return c.json(detailResponse(store, draft, candidate, detailAccess(store, candidateRef)));
8650
9047
  } catch (error) {
8651
- const failure = teamSetupFailure(error, `${c.req.method} ${c.req.routePath}`);
8652
- return c.json({ error: failure.code }, failure.status);
9048
+ const failure = detailFailure(error, `${c.req.method} ${c.req.routePath}`);
9049
+ return c.json(failure.body, failure.status);
8653
9050
  }
8654
9051
  });
8655
9052
  app.put("/api/sync/team-setup/v1/:candidateRef/devices/:deviceRef/assignment", async (c) => {
@@ -9438,6 +9835,41 @@ function mappingGuardrailChallenge(warnings, missing) {
9438
9835
  guardrail_warnings: warnings
9439
9836
  };
9440
9837
  }
9838
+ /**
9839
+ * Whether the bulk mapping save accepts these mappings. It cannot carry confirmations, so any
9840
+ * warning that requires one refuses it, and the person saves those entries one at a time.
9841
+ */
9842
+ function bulkProjectMappingVerdict(store, mappingInputs, deviceId) {
9843
+ const analyses = analyzeProjectScopeMappingChangesGuardrails(store.db, mappingInputs.map((input) => ({
9844
+ ...input,
9845
+ deviceId
9846
+ })));
9847
+ const warnings = analyses.flatMap((analysis) => analysis.warnings);
9848
+ const unmapped = analyses.find((analysis) => analysis.requested_workspace_identity?.startsWith("unmapped:"));
9849
+ if (unmapped) return {
9850
+ warnings,
9851
+ refusal: {
9852
+ status: 400,
9853
+ body: {
9854
+ error: "unmapped_project_local_only",
9855
+ message: "Unmapped projects need a stable path, git remote, or workspace id before assigning a Sharing domain.",
9856
+ guardrail_warnings: unmapped.warnings
9857
+ }
9858
+ }
9859
+ };
9860
+ const missing = analyses.flatMap((analysis) => missingGuardrailConfirmations(analysis.warnings, []));
9861
+ if (missing.length === 0) return {
9862
+ refusal: null,
9863
+ warnings
9864
+ };
9865
+ return {
9866
+ warnings,
9867
+ refusal: {
9868
+ status: 409,
9869
+ body: mappingGuardrailChallenge(warnings, missing)
9870
+ }
9871
+ };
9872
+ }
9441
9873
  function parseViewerProjectMappingInput(body) {
9442
9874
  const id = optionalViewerInteger(body, "id");
9443
9875
  const priority = optionalViewerInteger(body, "priority");
@@ -9733,7 +10165,7 @@ function resolveProjectInviteSelection(store, requestedIds, initiatingDeviceId)
9733
10165
  return requestedIds.map((projectId) => {
9734
10166
  const project = byIdentity.get(projectId);
9735
10167
  if (!project) throw new Error("project_selection_unknown");
9736
- if (project.guardrail_warnings.some((warning) => warning.code === "basename_collision_review" && warning.requires_confirmation)) throw new Error("project_selection_ambiguous");
10168
+ if (project.ambiguous_name === true || project.guardrail_warnings.some((warning) => warning.code === "basename_collision_review" && warning.requires_confirmation)) throw new Error("project_selection_ambiguous");
9737
10169
  if (project.read_only || project.identity_source === "unmapped" || project.memory_count == null || project.guardrail_warnings.some((warning) => warning.requires_confirmation)) throw new Error("project_selection_unsupported");
9738
10170
  return {
9739
10171
  canonicalIdentity: project.workspace_identity,
@@ -10164,7 +10596,8 @@ function coordinatorEnrollmentFailureCode(error) {
10164
10596
  "coordinator_id_invalid",
10165
10597
  "coordinator_invite_group_mismatch",
10166
10598
  "coordinator_invite_list_malformed",
10167
- "reconciliation_time_invalid"
10599
+ "reconciliation_time_invalid",
10600
+ "team_member_removal_invalid"
10168
10601
  ])).has(message)) return message;
10169
10602
  if (/timeout|timed out|abort/iu.test(message)) return "request_timeout";
10170
10603
  if (/fetch failed|network|econn|enotfound/iu.test(message)) return "network_error";
@@ -10228,6 +10661,7 @@ async function reconcileConfiguredCoordinatorGroup(store, groupId, config, optio
10228
10661
  const adminSecret = config.syncCoordinatorAdminSecret.trim();
10229
10662
  const listDevices = options.listDevices ?? coordinatorListDevicesAction;
10230
10663
  const listInvites = options.listConsumedTeamInvites ?? coordinatorListConsumedTeamInvitesAction;
10664
+ const listRemovals = options.listTeamMemberRemovals ?? coordinatorListTeamMemberRemovalsAction;
10231
10665
  const reconcile = options.reconcileSnapshot ?? ((input) => reconcileCoordinatorEnrollmentSnapshot(store.db, input));
10232
10666
  let stage = "complete_device_setup";
10233
10667
  try {
@@ -10255,6 +10689,11 @@ async function reconcileConfiguredCoordinatorGroup(store, groupId, config, optio
10255
10689
  remoteUrl,
10256
10690
  adminSecret
10257
10691
  });
10692
+ const teamMemberRemovals = await listRemovals({
10693
+ groupId,
10694
+ remoteUrl,
10695
+ adminSecret
10696
+ }).catch(() => void 0);
10258
10697
  stage = "complete_device_setup";
10259
10698
  context.assertCurrent();
10260
10699
  stage = "reconcile_snapshot";
@@ -10263,6 +10702,7 @@ async function reconcileConfiguredCoordinatorGroup(store, groupId, config, optio
10263
10702
  groupId,
10264
10703
  enrollments,
10265
10704
  consumedTeamInvites: invites,
10705
+ teamMemberRemovals,
10266
10706
  localDeviceId: store.deviceId
10267
10707
  }) };
10268
10708
  } catch (error) {
@@ -10595,6 +11035,7 @@ async function reconcileRecipientPolicyProjects(store, options = {}) {
10595
11035
  function recipientPolicyReadState(authority) {
10596
11036
  if (!authority) return "pending";
10597
11037
  if (authority.safeErrorCode && RECIPIENT_POLICY_WAITING_ERRORS.has(authority.safeErrorCode)) return "waiting";
11038
+ if (authority.authorityState === "legacy" && authority.safeErrorCode === RECIPIENT_POLICY_SHARED_SCOPE_CODE) return "legacy_scope";
10598
11039
  if (authority.safeErrorCode || authority.authorityState === "rolled_back") return "needs_attention";
10599
11040
  if (authority.authorityState === "active") return "active";
10600
11041
  if (authority.authorityState === "eligible") return "verifying";
@@ -10613,6 +11054,10 @@ function recipientPolicyReadCopy(state) {
10613
11054
  label: "Waiting to reconcile",
10614
11055
  explanation: "Waiting for devices or a fresh coordinator snapshot. No partial grant is applied."
10615
11056
  };
11057
+ if (state === "legacy_scope") return {
11058
+ label: "Shared scope controls access",
11059
+ explanation: "Access for this Project is still controlled by the shared scope it belongs to. Nothing is required."
11060
+ };
10616
11061
  if (state === "needs_attention") return {
10617
11062
  label: "Reconciliation needs attention",
10618
11063
  explanation: "Legacy scope enforcement remains in control until this Project is safe to retry."
@@ -10975,7 +11420,32 @@ function bootstrapSeedMatchesLocalIdentity(store, seed) {
10975
11420
  return false;
10976
11421
  }
10977
11422
  }
10978
- async function authorizeBootstrapGrantRequest(store, request, body) {
11423
+ /**
11424
+ * Whether the scope is one of the grant group's coordinator scopes in this
11425
+ * machine's cache. A grant proves enrollment in one group only, so it must not
11426
+ * open a scope that this machine caches for the device through another group.
11427
+ */
11428
+ function isBootstrapGrantGroupScope(store, scopeId, grant, coordinatorUrl) {
11429
+ const cleanScopeId = scopeId.trim();
11430
+ if (!cleanScopeId) return false;
11431
+ return !!store.db.prepare(`SELECT 1 FROM replication_scopes
11432
+ WHERE scope_id = ? AND group_id = ? AND coordinator_id = ?
11433
+ AND authority_type = 'coordinator' LIMIT 1`).get(cleanScopeId, grant.group_id, buildBaseUrl(coordinatorUrl));
11434
+ }
11435
+ /** Why the verified grant does not authorize this request here, or null when it does. */
11436
+ function bootstrapGrantFailureReason(store, verification, request) {
11437
+ const { grant } = verification;
11438
+ const groups = request.config.syncCoordinatorGroups;
11439
+ if (groups.length > 0 && !groups.includes(grant.group_id)) return "bootstrap_grant_group_mismatch";
11440
+ if (grant.worker_device_id !== request.deviceId) return "bootstrap_grant_worker_mismatch";
11441
+ if (grant.seed_device_id !== request.localDeviceId) return "bootstrap_grant_seed_mismatch";
11442
+ if (parseBootstrapExpiry(grant.expires_at) <= Date.now()) return "bootstrap_grant_expired";
11443
+ if (!bootstrapSeedMatchesLocalIdentity(store, verification.seed_enrollment)) return "bootstrap_grant_seed_identity_invalid";
11444
+ const scopeId = request.requestedScopeId;
11445
+ if (scopeId !== void 0 && !isBootstrapGrantGroupScope(store, scopeId, grant, request.config.syncCoordinatorUrl)) return "bootstrap_grant_scope_outside_group";
11446
+ return null;
11447
+ }
11448
+ async function authorizeBootstrapGrantRequest(store, request, body, options = {}) {
10979
11449
  const grantId = (request.header("X-Codemem-Bootstrap-Grant") ?? "").trim();
10980
11450
  const deviceId = (request.header("X-Opencode-Device") ?? "").trim();
10981
11451
  const signature = request.header("X-Opencode-Signature") ?? "";
@@ -11039,36 +11509,20 @@ async function authorizeBootstrapGrantRequest(store, request, body) {
11039
11509
  deviceId
11040
11510
  };
11041
11511
  }
11042
- const grant = verification.grant;
11043
- const seedEnrollment = verification.seed_enrollment;
11044
- const workerEnrollment = verification.worker_enrollment;
11045
- if (config.syncCoordinatorGroups.length > 0 && !config.syncCoordinatorGroups.includes(grant.group_id)) return {
11512
+ const grantFailure = bootstrapGrantFailureReason(store, verification, {
11513
+ config,
11514
+ deviceId,
11515
+ localDeviceId,
11516
+ requestedScopeId: options.requestedScopeId
11517
+ });
11518
+ if (grantFailure) return {
11046
11519
  ok: false,
11047
- reason: "bootstrap_grant_group_mismatch",
11520
+ reason: grantFailure,
11048
11521
  deviceId
11049
11522
  };
11523
+ const workerEnrollment = verification.worker_enrollment;
11050
11524
  const workerPublicKey = workerEnrollment.public_key;
11051
11525
  const workerFingerprint = workerEnrollment.fingerprint;
11052
- if (grant.worker_device_id !== deviceId) return {
11053
- ok: false,
11054
- reason: "bootstrap_grant_worker_mismatch",
11055
- deviceId
11056
- };
11057
- if (grant.seed_device_id !== localDeviceId) return {
11058
- ok: false,
11059
- reason: "bootstrap_grant_seed_mismatch",
11060
- deviceId
11061
- };
11062
- if (parseBootstrapExpiry(grant.expires_at) <= Date.now()) return {
11063
- ok: false,
11064
- reason: "bootstrap_grant_expired",
11065
- deviceId
11066
- };
11067
- if (!bootstrapSeedMatchesLocalIdentity(store, seedEnrollment)) return {
11068
- ok: false,
11069
- reason: "bootstrap_grant_seed_identity_invalid",
11070
- deviceId
11071
- };
11072
11526
  const existingPeer = store.db.prepare(`SELECT highest_observed_direct_signature_version
11073
11527
  FROM sync_peer_signature_state WHERE peer_device_id = ? LIMIT 1`).get(deviceId);
11074
11528
  let signatureVerification;
@@ -12183,8 +12637,12 @@ function validateManagedScopes(scopeIds, context) {
12183
12637
  expectedPublicKey: context.localSigningPublicKey?.trim() ?? ""
12184
12638
  });
12185
12639
  const authority = localAuthorization.scope?.authority_type;
12186
- if (authority === "manual" || authority === "invite" || authority === "local") continue;
12187
- if (authority !== "coordinator") return {
12640
+ if (authority === "local") continue;
12641
+ if (!authority || ![
12642
+ "coordinator",
12643
+ "manual",
12644
+ "invite"
12645
+ ].includes(authority)) return {
12188
12646
  scopeId,
12189
12647
  reason: "missing_scope"
12190
12648
  };
@@ -12206,30 +12664,17 @@ function validateManagedScopes(scopeIds, context) {
12206
12664
  }
12207
12665
  return null;
12208
12666
  }
12209
- function addExistingMutationScopes(db, ops, scopeIds) {
12210
- const existingScopes = db.prepare("SELECT DISTINCT scope_id FROM memory_items WHERE import_key = ?");
12211
- for (const op of ops) {
12212
- if (![
12213
- "upsert",
12214
- "delete",
12215
- "reassign_scope"
12216
- ].includes(op.op_type)) continue;
12217
- const rows = existingScopes.all(op.entity_id);
12218
- for (const { scope_id: scope } of rows) if (typeof scope === "string" && scope.trim()) scopeIds.add(scope.trim());
12219
- }
12220
- }
12221
12667
  function cleanOpScopeId(op) {
12222
12668
  return typeof op.scope_id === "string" ? op.scope_id.trim() : "";
12223
12669
  }
12224
- /** Every scope a batch touches, including both sides of a reassignment. Payloads are already parsed. */
12225
- function mutationScopeIds(ops) {
12670
+ /**
12671
+ * Every scope a pushed batch touches: each op's own scope, and each scope of a stored copy
12672
+ * the op would change, by the rule the pull path uses. A move's new side needs only its new
12673
+ * scope unless this device stores a copy elsewhere, and its old side needs its old scope.
12674
+ */
12675
+ function inboundWriteScopeIds(db, ops, senderId) {
12226
12676
  const scopeIds = new Set(ops.map(cleanOpScopeId));
12227
- for (const op of ops) {
12228
- if (op.op_type !== "reassign_scope") continue;
12229
- const reassignment = parseReassignScopePayload(op);
12230
- scopeIds.add(reassignment.old_scope_id);
12231
- scopeIds.add(reassignment.new_scope_id);
12232
- }
12677
+ for (const op of ops) for (const scopeId of scopesWrittenByInboundOp(db, op, senderId)) scopeIds.add(scopeId);
12233
12678
  return scopeIds;
12234
12679
  }
12235
12680
  function rejectUnauthorizedInboundBatch(c, ops, context, options) {
@@ -12239,20 +12684,38 @@ function rejectUnauthorizedInboundBatch(c, ops, context, options) {
12239
12684
  });
12240
12685
  if (rejected) {
12241
12686
  recordInboundScopeFailure(context);
12687
+ const rejections = peerFacingRejections(ops, rejected.rejections);
12242
12688
  return c.json({
12243
12689
  error: "scope_rejected",
12244
- reason: rejected.rejections[0]?.reason ?? "scope_mismatch",
12245
- rejections: rejected.rejections,
12690
+ reason: rejections[0]?.reason ?? "scope_mismatch",
12691
+ rejections,
12246
12692
  sync_capability: LOCAL_SYNC_CAPABILITY,
12247
12693
  scope_id: options.scopeId
12248
12694
  }, 403);
12249
12695
  }
12250
- const scopeIds = new Set(options.managedScopeIds);
12251
- addExistingMutationScopes(context.db, ops, scopeIds);
12252
- const failure = validateManagedScopes(scopeIds, context);
12696
+ const failure = validateManagedScopes(inboundWriteScopeIds(context.db, ops, context.peerDeviceId), context);
12253
12697
  if (!failure) return null;
12254
12698
  recordInboundScopeFailure(context);
12255
- return c.json(syncScopeResetRequiredPayload(getSyncResetState(context.db), failure.reason, LOCAL_SYNC_CAPABILITY, failure.scopeId), 409);
12699
+ const reason = peerFacingScopeResetReason(failure.reason);
12700
+ const scopeId = (/* @__PURE__ */ new Set([options.scopeId, ...ops.map(cleanOpScopeId)])).has(failure.scopeId) ? failure.scopeId : options.scopeId;
12701
+ if (reason !== failure.reason || scopeId !== failure.scopeId) logWithheldScopeDenial(failure.reason, failure.scopeId);
12702
+ return c.json(syncScopeResetRequiredPayload(getSyncResetState(context.db), reason, LOCAL_SYNC_CAPABILITY, scopeId), 409);
12703
+ }
12704
+ /** Records locally what a scope denial withheld from the peer's answer. */
12705
+ function logWithheldScopeDenial(reason, scopeId) {
12706
+ console.warn(`[sync] scope denied to peer: reason=${reason} scope=${scopeId ?? "none"}`);
12707
+ }
12708
+ /**
12709
+ * Rejections as a peer may see them: each names its op's own scope, never the scope of a
12710
+ * stored copy, and membership and scope state collapse into one reason.
12711
+ */
12712
+ function peerFacingRejections(ops, rejections) {
12713
+ const declared = new Map(ops.map((op) => [op.op_id, cleanOpScopeId(op) || null]));
12714
+ return rejections.map((rejection) => ({
12715
+ ...rejection,
12716
+ scope_id: declared.get(rejection.op_id) ?? null,
12717
+ reason: rejection.reason === "scope_mismatch" ? rejection.reason : "missing_scope"
12718
+ }));
12256
12719
  }
12257
12720
  function recordInboundScopeFailure(context) {
12258
12721
  recordSyncTransferObservation(context.db, context.peerDeviceId, "receive", {
@@ -12266,6 +12729,10 @@ function parseInboundScopeRequest(body, context, options) {
12266
12729
  negotiatedCapability: options.negotiated
12267
12730
  });
12268
12731
  }
12732
+ /** The scope a snapshot request names, for checks made before it is authorized. */
12733
+ function scopeOf(c) {
12734
+ return { requestedScopeId: c.req.query(SYNC_SCOPE_QUERY_PARAM) };
12735
+ }
12269
12736
  function serveAuthorizedSnapshot(c, store, auth, options = {}) {
12270
12737
  const peerDeviceId = auth.deviceId;
12271
12738
  try {
@@ -12329,7 +12796,9 @@ function serveChannelRead(c, options) {
12329
12796
  function syncScopeProvided(provided, syncChannelPeerPin) {
12330
12797
  return syncChannelPeerPin !== void 0 || provided;
12331
12798
  }
12332
- function syncScopeResetResponse(c, store, reason, syncChannelPeerPin) {
12799
+ function syncScopeResetResponse(c, store, preciseReason, syncChannelPeerPin) {
12800
+ const reason = peerFacingScopeResetReason(preciseReason);
12801
+ if (reason !== preciseReason) logWithheldScopeDenial(preciseReason, c.req.query(SYNC_SCOPE_QUERY_PARAM) ?? null);
12333
12802
  if (syncChannelPeerPin !== void 0) return c.json({
12334
12803
  error: "reset_required",
12335
12804
  reset_required: true,
@@ -12524,7 +12993,7 @@ function syncProtocolRoutes(getStore, opts = {}) {
12524
12993
  if (unauthLimited) return unauthLimited;
12525
12994
  }
12526
12995
  deviceAuthReason = auth.reason;
12527
- auth = await authorizeBootstrapGrantRequest(store, c.req, Buffer.alloc(0));
12996
+ auth = await authorizeBootstrapGrantRequest(store, c.req, Buffer.alloc(0), scopeOf(c));
12528
12997
  bootstrapAttempted = true;
12529
12998
  }
12530
12999
  if (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);
@@ -12591,11 +13060,9 @@ function syncProtocolRoutes(getStore, opts = {}) {
12591
13060
  applyScopeFilter: false,
12592
13061
  supportsReassignScope: peerFeatures.includes("reassign_scope")
12593
13062
  });
12594
- const validatedOps = normalizedOps.filter((op) => !isProjectScopeWithdrawn(scopeContext.db, cleanOpScopeId(op)));
12595
- const rejected = rejectUnauthorizedInboundBatch(c, validatedOps, scopeContext, {
13063
+ const rejected = rejectUnauthorizedInboundBatch(c, normalizedOps.filter((op) => !isProjectScopeWithdrawn(scopeContext.db, cleanOpScopeId(op))), scopeContext, {
12596
13064
  enabled: negotiated !== "unsupported",
12597
- scopeId: scopeRequest.scope_id,
12598
- managedScopeIds: mutationScopeIds(validatedOps)
13065
+ scopeId: scopeRequest.scope_id
12599
13066
  });
12600
13067
  if (rejected) return rejected;
12601
13068
  const result = applyInboundSyncOps(store, filtered.allowed, localDeviceId, peerDeviceId);
@@ -13045,6 +13512,11 @@ async function revokeBootstrapGrantRoute(c) {
13045
13512
  return c.json({ error: message }, 500);
13046
13513
  }
13047
13514
  }
13515
+ /** Only `false` or `0` prunes, so clients that omit the parameter keep the full list. */
13516
+ function includeEmptyProjectsParam(value) {
13517
+ const normalized = value?.trim().toLowerCase();
13518
+ return normalized !== "false" && normalized !== "0";
13519
+ }
13048
13520
  async function projectScopeInventoryRoute(c, store) {
13049
13521
  const limit = Math.max(1, queryInt(c.req.query("limit"), 50));
13050
13522
  const offset = Math.max(0, queryInt(c.req.query("offset"), 0));
@@ -13052,6 +13524,7 @@ async function projectScopeInventoryRoute(c, store) {
13052
13524
  const inventory = listProjectScopeInventory(store.db, {
13053
13525
  repositoryIdentitySnapshot,
13054
13526
  identitySource: c.req.query("identity_source"),
13527
+ includeEmpty: includeEmptyProjectsParam(c.req.query("include_empty")),
13055
13528
  limit,
13056
13529
  offset,
13057
13530
  query: c.req.query("q"),
@@ -14237,22 +14710,12 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
14237
14710
  const mappingInputs = parseViewerProjectMappingInputs(body);
14238
14711
  releasePublicationMutation = await claimRecipientPolicyPublicationMutation(store.db);
14239
14712
  const [deviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
14240
- const analyses = analyzeProjectScopeMappingChangesGuardrails(store.db, mappingInputs.map((input) => ({
14241
- ...input,
14242
- deviceId
14243
- })));
14244
- const unmapped = analyses.find((analysis) => analysis.requested_workspace_identity?.startsWith("unmapped:"));
14245
- if (unmapped) return c.json({
14246
- error: "unmapped_project_local_only",
14247
- message: "Unmapped projects need a stable path, git remote, or workspace id before assigning a Sharing domain.",
14248
- guardrail_warnings: unmapped.warnings
14249
- }, 400);
14250
- const missingConfirmations = analyses.flatMap((analysis) => missingGuardrailConfirmations(analysis.warnings, []));
14251
- if (missingConfirmations.length > 0) return c.json(mappingGuardrailChallenge(analyses.flatMap((analysis) => analysis.warnings), missingConfirmations), 409);
14713
+ const verdict = bulkProjectMappingVerdict(store, mappingInputs, deviceId);
14714
+ if (verdict.refusal) return c.json(verdict.refusal.body, verdict.refusal.status);
14252
14715
  return c.json({
14253
14716
  ok: true,
14254
14717
  mappings: saveProjectMappingsAndWakePolicies(store, deviceId, mappingInputs),
14255
- guardrail_warnings: analyses.flatMap((analysis) => analysis.warnings)
14718
+ guardrail_warnings: verdict.warnings
14256
14719
  });
14257
14720
  } catch (error) {
14258
14721
  return c.json({ error: error instanceof Error ? error.message : String(error) }, 400);
@@ -14260,6 +14723,24 @@ function syncRoutes(getStore, getSyncRuntimeStatus, options = {}) {
14260
14723
  releasePublicationMutation?.();
14261
14724
  }
14262
14725
  });
14726
+ app.post("/api/sync/sharing-domains/project-mappings/bulk/check", async (c) => {
14727
+ const store = getStore();
14728
+ const body = await parseViewerJsonBody(c);
14729
+ if (!body) return c.json({ error: "invalid json" }, 400);
14730
+ try {
14731
+ const mappingInputs = parseViewerProjectMappingInputs(body);
14732
+ const [deviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });
14733
+ const verdict = bulkProjectMappingVerdict(store, mappingInputs, deviceId);
14734
+ return c.json({
14735
+ ok: true,
14736
+ accepted: verdict.refusal === null,
14737
+ refusal: verdict.refusal?.body ?? null,
14738
+ guardrail_warnings: verdict.warnings
14739
+ });
14740
+ } catch (error) {
14741
+ return c.json({ error: error instanceof Error ? error.message : String(error) }, 400);
14742
+ }
14743
+ });
14263
14744
  app.delete("/api/sync/sharing-domains/project-mappings/:id", (c) => deleteProjectScopeMappingRoute(c, getStore()));
14264
14745
  app.post("/api/sync/peers/identity", async (c) => {
14265
14746
  const store = getStore();
@@ -17772,7 +18253,11 @@ var retrievalExposures = sqliteTable("retrieval_exposures", {
17772
18253
  memory_deleted_at: text("memory_deleted_at"),
17773
18254
  score_summary_json: text("score_summary_json"),
17774
18255
  reason_codes_json: text("reason_codes_json")
17775
- }, (table) => [uniqueIndex("idx_retrieval_exposures_attempt_rank").on(table.attempt_id, table.rank), index("idx_retrieval_exposures_memory").on(table.memory_id)]);
18256
+ }, (table) => [
18257
+ uniqueIndex("idx_retrieval_exposures_attempt_rank").on(table.attempt_id, table.rank),
18258
+ index("idx_retrieval_exposures_memory").on(table.memory_id),
18259
+ index("idx_retrieval_exposures_not_selected").on(table.attempt_id).where(sql`${table.disposition} <> 'selected'`)
18260
+ ]);
17776
18261
  var outcomeEvidence = sqliteTable("outcome_evidence", {
17777
18262
  evidence_id: text("evidence_id").primaryKey(),
17778
18263
  contract_version: integer("contract_version").notNull(),
@@ -18053,6 +18538,7 @@ sqliteTable("sync_attempts", {
18053
18538
  transport: text("transport")
18054
18539
  }, (table) => [
18055
18540
  index("idx_sync_attempts_peer_started").on(table.peer_device_id, table.started_at),
18541
+ index("idx_sync_attempts_peer_kind_started").on(table.peer_device_id, table.ok, table.failure_category, table.started_at),
18056
18542
  index("idx_sync_attempts_occurred").on(sql`CASE WHEN ${table.finished_at} IS NULL THEN ${table.started_at} ELSE ${table.finished_at} END`, table.id),
18057
18543
  index("idx_sync_attempts_error_occurred").on(sql`CASE WHEN ${table.finished_at} IS NULL THEN ${table.started_at} ELSE ${table.finished_at} END`, table.id).where(sql`${table.ok} = 0`),
18058
18544
  index("idx_sync_attempts_success_occurred").on(sql`CASE WHEN ${table.finished_at} IS NULL THEN ${table.started_at} ELSE ${table.finished_at} END`, table.id).where(sql`${table.ok} <> 0`)
@@ -18224,6 +18710,21 @@ sqliteTable("policy_team_device_decisions", {
18224
18710
  created_at: text("created_at").notNull(),
18225
18711
  updated_at: text("updated_at").notNull()
18226
18712
  }, (table) => [primaryKey({ columns: [table.team_id, table.device_id] }), index("idx_policy_team_device_decisions_device").on(table.device_id)]);
18713
+ sqliteTable("policy_team_member_removals", {
18714
+ team_id: text("team_id").notNull(),
18715
+ identity_id: text("identity_id").notNull(),
18716
+ coordinator_id: text("coordinator_id").notNull(),
18717
+ group_id: text("group_id").notNull(),
18718
+ removal_seq: integer("removal_seq").notNull(),
18719
+ removed_at: text("removed_at").notNull(),
18720
+ removed_by_device_id: text("removed_by_device_id"),
18721
+ recorded_at: text("recorded_at").notNull()
18722
+ }, (table) => [primaryKey({ columns: [
18723
+ table.coordinator_id,
18724
+ table.group_id,
18725
+ table.team_id,
18726
+ table.identity_id
18727
+ ] })]);
18227
18728
  sqliteTable("identity_devices", {
18228
18729
  device_id: text("device_id").primaryKey(),
18229
18730
  identity_id: text("identity_id").notNull(),