@codemem/server 0.50.0-beta.1 → 0.50.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,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, 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, 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, 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";
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";
@@ -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();
@@ -7023,6 +7314,9 @@ function completionFailureHandlers(options) {
7023
7314
  reportFailure
7024
7315
  };
7025
7316
  }
7317
+ function isNonDivergentApplyFailure(error) {
7318
+ return error instanceof LegacyTeamSetupAdditiveConvergenceError || error instanceof LegacyTeamSetupDeviceRemovalsUnavailableError;
7319
+ }
7026
7320
  function completionConflictError(cause) {
7027
7321
  return new Error("team_setup_completion_conflict", { cause });
7028
7322
  }
@@ -7040,18 +7334,52 @@ function groupCompletionFailureHandler(groups, handleFailure) {
7040
7334
  if (group) handleFailure(group, error);
7041
7335
  };
7042
7336
  }
7337
+ /** The safe cause behind a retryable completion failure, when one is known. */
7338
+ function completionFailureReason(error) {
7339
+ return errorChain(error).some((item) => item instanceof LegacyTeamSetupDeviceRemovalsUnavailableError) ? "device_removals_unavailable" : void 0;
7340
+ }
7341
+ function completionBlocker(error) {
7342
+ const code = apiErrorCode(new Error(completionApiError(error)));
7343
+ const reason = completionFailureReason(error);
7344
+ return reason && code === "team_setup_completion_unavailable" ? {
7345
+ code,
7346
+ reason
7347
+ } : { code };
7348
+ }
7349
+ /** A detail read failure, with the safe completion cause when one is known. */
7350
+ function detailFailure(error, route) {
7351
+ const failure = teamSetupFailure(error, route);
7352
+ const { reason } = completionBlocker(error);
7353
+ return {
7354
+ body: reason ? {
7355
+ error: failure.code,
7356
+ reason
7357
+ } : { error: failure.code },
7358
+ status: failure.status
7359
+ };
7360
+ }
7043
7361
  function summaryReconciliationOptions(blockingErrors) {
7044
7362
  return {
7045
7363
  isolateApplyFailures: true,
7046
7364
  onFailure: (group, error) => {
7047
- blockingErrors.set(legacyTeamCandidateId(group.coordinatorId, group.groupId), apiErrorCode(new Error(completionApiError(error))));
7365
+ blockingErrors.set(legacyTeamCandidateId(group.coordinatorId, group.groupId), completionBlocker(error));
7048
7366
  }
7049
7367
  };
7050
7368
  }
7369
+ function lookupPeerRemovalsAsDaemon(store, config) {
7370
+ const keysDir = process.env.CODEMEM_KEYS_DIR?.trim() || void 0;
7371
+ const [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir });
7372
+ return fetchPeerRemovalLookup(store, config, {
7373
+ localDeviceId,
7374
+ keysDir
7375
+ });
7376
+ }
7051
7377
  var defaultCompletionDependencies = {
7052
7378
  create: coordinatorCreateLegacyTeamCompletionAction,
7053
7379
  get: coordinatorGetLegacyTeamCompletionAction,
7054
- list: coordinatorListLegacyTeamCompletionsAction
7380
+ list: coordinatorListLegacyTeamCompletionsAction,
7381
+ listRemovals: coordinatorListRemovedDevicesAction,
7382
+ lookupPeerRemovals: lookupPeerRemovalsAsDaemon
7055
7383
  };
7056
7384
  var defaultSnapshotLoaderDependencies = {
7057
7385
  readConfig: readCoordinatorSyncConfig,
@@ -7388,13 +7716,17 @@ function candidateFromDraft(draft) {
7388
7716
  unresolvedProjectCount: draft.unresolvedProjectCount
7389
7717
  };
7390
7718
  }
7391
- function blockedCandidateSummary(store, group, blockingError) {
7719
+ function blockedCandidateSummary(store, group, blocker) {
7392
7720
  const candidateRef = legacyTeamCandidateId(group.coordinatorId, group.groupId);
7393
7721
  const draft = getLegacyTeamSetupDraft(store.db, candidateRef);
7722
+ const blocking = {
7723
+ blockingError: blocker.code,
7724
+ ...blocker.reason ? { blockingReason: blocker.reason } : {}
7725
+ };
7394
7726
  if (draft) return {
7395
7727
  ...candidateSummary(candidateFromDraft(draft)),
7396
7728
  status: "stale",
7397
- blockingError
7729
+ ...blocking
7398
7730
  };
7399
7731
  const forbiddenIds = [
7400
7732
  group.coordinatorId,
@@ -7410,7 +7742,7 @@ function blockedCandidateSummary(store, group, blockingError) {
7410
7742
  candidateRef,
7411
7743
  displayName: safeChoiceLabel(group.displayName, "Legacy Team", forbiddenIds),
7412
7744
  status: "stale",
7413
- blockingError,
7745
+ ...blocking,
7414
7746
  deviceCount: group.devices.length,
7415
7747
  projectCount: 0,
7416
7748
  unresolvedDeviceCount: 0,
@@ -8184,6 +8516,81 @@ function saveDeviceAssignment(store, input) {
8184
8516
  releaseMutation();
8185
8517
  }
8186
8518
  }
8519
+ function readCompletionAuthorization(options) {
8520
+ const config = (options.readCoordinatorConfig ?? options.snapshotLoaderDependencies?.readConfig ?? readCoordinatorSyncConfig)();
8521
+ const remoteUrl = buildBaseUrl(config.syncCoordinatorUrl);
8522
+ if (!remoteUrl || !config.syncCoordinatorAdminSecret) return null;
8523
+ const configuredCoordinatorId = normalizedCoordinatorId(remoteUrl);
8524
+ if (!configuredCoordinatorId) return null;
8525
+ let currentGroupIds;
8526
+ try {
8527
+ currentGroupIds = new Set(configuredGroupIds$1(config.syncCoordinatorGroups));
8528
+ } catch {
8529
+ return null;
8530
+ }
8531
+ return {
8532
+ config,
8533
+ remoteUrl,
8534
+ configuredCoordinatorId,
8535
+ currentGroupIds
8536
+ };
8537
+ }
8538
+ /** One daemon lookup per reconciliation, read only when a missing device needs it. */
8539
+ function peerRemovalReader(dependencies, store, config) {
8540
+ let lookup;
8541
+ return () => {
8542
+ const read = dependencies.lookupPeerRemovals;
8543
+ if (!read) return Promise.resolve(void 0);
8544
+ lookup ??= Promise.resolve().then(() => read(store, config)).then((result) => result.status === "checked" ? {
8545
+ status: "read",
8546
+ removed: result.removed,
8547
+ enrolled: result.enrolled,
8548
+ generation: result.generation
8549
+ } : { status: "unavailable" }, () => ({ status: "unavailable" }));
8550
+ return lookup;
8551
+ };
8552
+ }
8553
+ function completionReadActions(dependencies, { authorization, store }, timeoutS, deadlineMs) {
8554
+ const { config, remoteUrl } = authorization;
8555
+ const adminSecret = config.syncCoordinatorAdminSecret;
8556
+ let removals;
8557
+ const listRemovals = () => {
8558
+ const read = dependencies.listRemovals;
8559
+ if (!read) return Promise.resolve(void 0);
8560
+ removals ??= read({
8561
+ includeBlocked: true,
8562
+ remote: {
8563
+ url: remoteUrl,
8564
+ adminSecret,
8565
+ timeoutS,
8566
+ deadlineMs
8567
+ }
8568
+ }).then((items) => ({
8569
+ status: "read",
8570
+ removals: items
8571
+ }), () => ({ status: "unavailable" }));
8572
+ return removals;
8573
+ };
8574
+ const listCompletionRecords = (groupIds) => retryTransientCoordinatorRead((attemptTimeoutS) => dependencies.list({
8575
+ groupIds,
8576
+ remoteUrl,
8577
+ adminSecret,
8578
+ timeoutS: attemptTimeoutS
8579
+ }), timeoutS, deadlineMs);
8580
+ return {
8581
+ listCompletionRecords,
8582
+ removalReads: {
8583
+ listRemovals,
8584
+ lookupPeerRemovals: peerRemovalReader(dependencies, store, config)
8585
+ }
8586
+ };
8587
+ }
8588
+ async function readRemovalEvidence(reads) {
8589
+ return {
8590
+ deviceRemovals: await reads.listRemovals(),
8591
+ peerRemovals: await reads.lookupPeerRemovals()
8592
+ };
8593
+ }
8187
8594
  function authorizesGroup(authorization, group) {
8188
8595
  return authorization.currentGroupIds.has(group.groupId) && normalizedCoordinatorId(group.coordinatorId) === authorization.configuredCoordinatorId;
8189
8596
  }
@@ -8238,30 +8645,7 @@ function teamSetupRoutes(options) {
8238
8645
  const loadedSummarySnapshots = createLoadedSummarySnapshotCache(loadedSnapshots, options);
8239
8646
  options.registerSummaryInvalidator?.(() => loadedSummarySnapshots.invalidate());
8240
8647
  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
- }
8648
+ const currentCompletionAuthorization = () => readCompletionAuthorization(options);
8265
8649
  function hasDraftEditAuthority(store, candidateRef) {
8266
8650
  const authorization = currentCompletionAuthorization();
8267
8651
  const group = persistedCompletionGroup(store, candidateRef);
@@ -8319,7 +8703,9 @@ function teamSetupRoutes(options) {
8319
8703
  * let a group removed while reconciliation waited on another policy
8320
8704
  * mutation still be applied once the queues open.
8321
8705
  */
8322
- async function applyCanonicalManifestIfStillAuthorized(store, authorization, group, manifest, freshRoster) {
8706
+ async function applyCanonicalManifestIfStillAuthorized(store, authorization, group, manifest, freshRoster, reads) {
8707
+ const freshIds = new Set(freshRoster.map((device) => device.deviceId));
8708
+ const removalEvidence = manifest.device_decisions.some((device) => device.decision === "included" && !freshIds.has(device.device_id)) ? await readRemovalEvidence(reads) : {};
8323
8709
  let outcome = "unauthorized";
8324
8710
  return await runCandidateMutation(store.db, legacyTeamCandidateId(group.coordinatorId, group.groupId), () => serializeCanonicalManifestMutation(store, group.groupId, manifest, async (actorIds) => {
8325
8711
  if (!stillAuthorizesGroup(authorization, group)) return;
@@ -8328,6 +8714,7 @@ function teamSetupRoutes(options) {
8328
8714
  groupId: group.groupId,
8329
8715
  manifest,
8330
8716
  freshRoster,
8717
+ ...removalEvidence,
8331
8718
  recipientPolicyLocksHeld: completionRecipientPolicyLocksHeld(actorIds)
8332
8719
  });
8333
8720
  outcome = "applied";
@@ -8349,13 +8736,11 @@ function teamSetupRoutes(options) {
8349
8736
  const timeoutS = Math.max(1, config.syncCoordinatorTimeoutS);
8350
8737
  try {
8351
8738
  const reconciliationDeadlineMs = Date.now() + COORDINATOR_ROSTER_READ_BUDGET_MS;
8739
+ const { listCompletionRecords, removalReads } = completionReadActions(completionDependencies, {
8740
+ authorization,
8741
+ store
8742
+ }, timeoutS, reconciliationDeadlineMs);
8352
8743
  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
8744
  const scopedGroupIds = [...new Set(scopedGroups.map((group) => group.groupId))];
8360
8745
  let records;
8361
8746
  try {
@@ -8471,7 +8856,7 @@ function teamSetupRoutes(options) {
8471
8856
  }
8472
8857
  throw new Error("team_setup_completion_invalid");
8473
8858
  }
8474
- if (await applyCanonicalManifestIfStillAuthorized(store, authorization, group, canonicalManifest, freshGroup.devices) !== "applied") continue;
8859
+ if (await applyCanonicalManifestIfStillAuthorized(store, authorization, group, canonicalManifest, freshGroup.devices, removalReads) !== "applied") continue;
8475
8860
  } catch (error) {
8476
8861
  handleFailure(group, error);
8477
8862
  }
@@ -8537,9 +8922,9 @@ function teamSetupRoutes(options) {
8537
8922
  try {
8538
8923
  const freshGroup = await loadFreshGroupSnapshot(group, remoteUrl, reconciliationDeadlineMs);
8539
8924
  if (!freshGroup) throw new Error("team_setup_roster_unavailable");
8540
- if (await applyCanonicalManifestIfStillAuthorized(store, authorization, group, canonicalManifest, freshGroup.devices) !== "applied") continue;
8925
+ if (await applyCanonicalManifestIfStillAuthorized(store, authorization, group, canonicalManifest, freshGroup.devices, removalReads) !== "applied") continue;
8541
8926
  } catch (applyError) {
8542
- if (applyError instanceof LegacyTeamSetupAdditiveConvergenceError) {
8927
+ if (isNonDivergentApplyFailure(applyError)) {
8543
8928
  handleFailure(group, applyError);
8544
8929
  continue;
8545
8930
  }
@@ -8648,8 +9033,8 @@ function teamSetupRoutes(options) {
8648
9033
  if (completionGroups) candidate = candidateFromDraft(draft);
8649
9034
  return c.json(detailResponse(store, draft, candidate, detailAccess(store, candidateRef)));
8650
9035
  } catch (error) {
8651
- const failure = teamSetupFailure(error, `${c.req.method} ${c.req.routePath}`);
8652
- return c.json({ error: failure.code }, failure.status);
9036
+ const failure = detailFailure(error, `${c.req.method} ${c.req.routePath}`);
9037
+ return c.json(failure.body, failure.status);
8653
9038
  }
8654
9039
  });
8655
9040
  app.put("/api/sync/team-setup/v1/:candidateRef/devices/:deviceRef/assignment", async (c) => {
@@ -10975,7 +11360,32 @@ function bootstrapSeedMatchesLocalIdentity(store, seed) {
10975
11360
  return false;
10976
11361
  }
10977
11362
  }
10978
- async function authorizeBootstrapGrantRequest(store, request, body) {
11363
+ /**
11364
+ * Whether the scope is one of the grant group's coordinator scopes in this
11365
+ * machine's cache. A grant proves enrollment in one group only, so it must not
11366
+ * open a scope that this machine caches for the device through another group.
11367
+ */
11368
+ function isBootstrapGrantGroupScope(store, scopeId, grant, coordinatorUrl) {
11369
+ const cleanScopeId = scopeId.trim();
11370
+ if (!cleanScopeId) return false;
11371
+ return !!store.db.prepare(`SELECT 1 FROM replication_scopes
11372
+ WHERE scope_id = ? AND group_id = ? AND coordinator_id = ?
11373
+ AND authority_type = 'coordinator' LIMIT 1`).get(cleanScopeId, grant.group_id, buildBaseUrl(coordinatorUrl));
11374
+ }
11375
+ /** Why the verified grant does not authorize this request here, or null when it does. */
11376
+ function bootstrapGrantFailureReason(store, verification, request) {
11377
+ const { grant } = verification;
11378
+ const groups = request.config.syncCoordinatorGroups;
11379
+ if (groups.length > 0 && !groups.includes(grant.group_id)) return "bootstrap_grant_group_mismatch";
11380
+ if (grant.worker_device_id !== request.deviceId) return "bootstrap_grant_worker_mismatch";
11381
+ if (grant.seed_device_id !== request.localDeviceId) return "bootstrap_grant_seed_mismatch";
11382
+ if (parseBootstrapExpiry(grant.expires_at) <= Date.now()) return "bootstrap_grant_expired";
11383
+ if (!bootstrapSeedMatchesLocalIdentity(store, verification.seed_enrollment)) return "bootstrap_grant_seed_identity_invalid";
11384
+ const scopeId = request.requestedScopeId;
11385
+ if (scopeId !== void 0 && !isBootstrapGrantGroupScope(store, scopeId, grant, request.config.syncCoordinatorUrl)) return "bootstrap_grant_scope_outside_group";
11386
+ return null;
11387
+ }
11388
+ async function authorizeBootstrapGrantRequest(store, request, body, options = {}) {
10979
11389
  const grantId = (request.header("X-Codemem-Bootstrap-Grant") ?? "").trim();
10980
11390
  const deviceId = (request.header("X-Opencode-Device") ?? "").trim();
10981
11391
  const signature = request.header("X-Opencode-Signature") ?? "";
@@ -11039,36 +11449,20 @@ async function authorizeBootstrapGrantRequest(store, request, body) {
11039
11449
  deviceId
11040
11450
  };
11041
11451
  }
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 {
11452
+ const grantFailure = bootstrapGrantFailureReason(store, verification, {
11453
+ config,
11454
+ deviceId,
11455
+ localDeviceId,
11456
+ requestedScopeId: options.requestedScopeId
11457
+ });
11458
+ if (grantFailure) return {
11046
11459
  ok: false,
11047
- reason: "bootstrap_grant_group_mismatch",
11460
+ reason: grantFailure,
11048
11461
  deviceId
11049
11462
  };
11463
+ const workerEnrollment = verification.worker_enrollment;
11050
11464
  const workerPublicKey = workerEnrollment.public_key;
11051
11465
  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
11466
  const existingPeer = store.db.prepare(`SELECT highest_observed_direct_signature_version
11073
11467
  FROM sync_peer_signature_state WHERE peer_device_id = ? LIMIT 1`).get(deviceId);
11074
11468
  let signatureVerification;
@@ -12183,8 +12577,12 @@ function validateManagedScopes(scopeIds, context) {
12183
12577
  expectedPublicKey: context.localSigningPublicKey?.trim() ?? ""
12184
12578
  });
12185
12579
  const authority = localAuthorization.scope?.authority_type;
12186
- if (authority === "manual" || authority === "invite" || authority === "local") continue;
12187
- if (authority !== "coordinator") return {
12580
+ if (authority === "local") continue;
12581
+ if (!authority || ![
12582
+ "coordinator",
12583
+ "manual",
12584
+ "invite"
12585
+ ].includes(authority)) return {
12188
12586
  scopeId,
12189
12587
  reason: "missing_scope"
12190
12588
  };
@@ -12266,6 +12664,10 @@ function parseInboundScopeRequest(body, context, options) {
12266
12664
  negotiatedCapability: options.negotiated
12267
12665
  });
12268
12666
  }
12667
+ /** The scope a snapshot request names, for checks made before it is authorized. */
12668
+ function scopeOf(c) {
12669
+ return { requestedScopeId: c.req.query(SYNC_SCOPE_QUERY_PARAM) };
12670
+ }
12269
12671
  function serveAuthorizedSnapshot(c, store, auth, options = {}) {
12270
12672
  const peerDeviceId = auth.deviceId;
12271
12673
  try {
@@ -12524,7 +12926,7 @@ function syncProtocolRoutes(getStore, opts = {}) {
12524
12926
  if (unauthLimited) return unauthLimited;
12525
12927
  }
12526
12928
  deviceAuthReason = auth.reason;
12527
- auth = await authorizeBootstrapGrantRequest(store, c.req, Buffer.alloc(0));
12929
+ auth = await authorizeBootstrapGrantRequest(store, c.req, Buffer.alloc(0), scopeOf(c));
12528
12930
  bootstrapAttempted = true;
12529
12931
  }
12530
12932
  if (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);
@@ -13045,6 +13447,11 @@ async function revokeBootstrapGrantRoute(c) {
13045
13447
  return c.json({ error: message }, 500);
13046
13448
  }
13047
13449
  }
13450
+ /** Only `false` or `0` prunes, so clients that omit the parameter keep the full list. */
13451
+ function includeEmptyProjectsParam(value) {
13452
+ const normalized = value?.trim().toLowerCase();
13453
+ return normalized !== "false" && normalized !== "0";
13454
+ }
13048
13455
  async function projectScopeInventoryRoute(c, store) {
13049
13456
  const limit = Math.max(1, queryInt(c.req.query("limit"), 50));
13050
13457
  const offset = Math.max(0, queryInt(c.req.query("offset"), 0));
@@ -13052,6 +13459,7 @@ async function projectScopeInventoryRoute(c, store) {
13052
13459
  const inventory = listProjectScopeInventory(store.db, {
13053
13460
  repositoryIdentitySnapshot,
13054
13461
  identitySource: c.req.query("identity_source"),
13462
+ includeEmpty: includeEmptyProjectsParam(c.req.query("include_empty")),
13055
13463
  limit,
13056
13464
  offset,
13057
13465
  query: c.req.query("q"),