codemem 0.49.0 → 0.50.0-beta.1

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,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { ACCOUNT_CONNECTION_MIGRATION_STATEMENTS, ACCOUNT_UNLINK_MIGRATION_STATEMENTS, ALLOWED_MEMORY_KINDS, AUTH_LINK_AUTHORITY_CUTOVER_SQL, ContextOnlyReplayError, CoordinatorAccountLinkError, DEDUP_KEY_BACKFILL_JOB, DEFAULT_COORDINATOR_DB_PATH, DEFAULT_RAW_EVENT_FLUSH_MAX_EVENTS, DedupKeyBackfillRunner, DeviceIdentityError, EXTRACTION_BENCHMARK_QUALITY_WEIGHTS, FILE_CONTEXT_TRANSPORT_MAX_BYTES, FILE_CONTEXT_TRANSPORT_PROFILE, LEGACY_OWNER_RESOLUTION_SCHEMA_STATEMENTS, MUTATING_TOOL_NAMES, MemoryStore, ObserverClient, ObserverOutputError, ObserverOutputTransportError, OwnerProfileEnrollmentError, PROMPT_TRANSPORT_PROTOCOL_RANGE, REF_BACKFILL_JOB, RawEventIngestValidationError, RawEventSweeper, RefBackfillRunner, RemoteCoordinatorRequestError, SCOPE_BACKFILL_JOB, SESSION_CONTEXT_BACKFILL_JOB, SUMMARY_DEDUP_BACKFILL_JOB, ScopeBackfillRunner, SessionContextBackfillRunner, SummaryDedupBackfillRunner, SyncRetentionRunner, TRUSTED_HOOK_MAPPER_OPTIONS, VERSION, VectorModelMigrationRunner, aiBackfillStructuredContent, applyBootstrapSnapshot, applyDistillRule, arePromptTransportProtocolRangesCompatible, atomicReplaceConfigFile, backfillMemoryDedupKeys, backfillNarrativeFromBody, backfillTagsText, backfillVectors, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildTieredObserverSelection, buildViewerIdentityTarget, classifyPromptTransportFailure, clonePromptPackAttempt, collectOperationalStatus, compareMemoryRoleReports, connect, connectReadOnly, coordinatorAuthControllerReviewAction, coordinatorAuthStageBaselineSql, coordinatorCreateGroupAction, coordinatorCreateInviteAction, coordinatorCreateScopeAction, coordinatorD1BaselineMigrations, coordinatorDisableDeviceAction, coordinatorEnrollDeviceAction, coordinatorGrantIdentityGroupAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorQualifyOwnerAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorReviewInviteAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeDeviceAction, coordinatorRevokeScopeMembershipAction, coordinatorUpdateScopeAction, createBetterSqliteCoordinatorApp, createFileContextRunner, deactivateLowSignalMemories, dedupNearDuplicateMemories, describePiObserverStatus, detectInstallKind, diagnoseLegacyTeamSetupCompletion, dispatchFileContextTransport, draftDistillRule, enrollOwnerProfile, ensureDeviceIdentity, ensureSchemaBootstrapped, estimateExtractionModelCost, expandUserPath, exportMemories, extractApplyPatchPaths, extractionReplayObserverIdentity, fetchAllSnapshotPages, fingerprintPublicKey, flushRawEvents, formatHostPort, getAttributionDiagnostics, getCodememConfigPath, getExtractionBenchmarkProfile, getExtractionModelPricing, getInjectionEvalScenarioPack, getInjectionEvalScenarioPrompts, getMaintenanceJob, getMemoryArtifactReport, getMemoryRoleReport, getRawEventRelinkPlan, getRawEventRelinkReport, getRawEventStatus, getSessionExtractionEval, getSessionExtractionEvalScenario, getUpdateStatus, getWorkspaceCodememConfigPath, hasPendingDedupKeyBackfill, hasPendingRefBackfill, hasPendingScopeBackfill, hasPendingSessionContextBackfill, hasPendingSummaryDedupBackfill, hasUnsyncedSharedMemoryChanges, importMemories, importPiSessions, ingestRawEvents, initDatabase, isAutomaticRecallMeasurement, isCoordinatorControllerAttestationReference, isEmbeddingDisabled, isExplicitUpdateInstallEligible, isReleaseVersionForChannel, judgeDistillReport, legacyTeamCandidateId, linkCoordinatorAccount, linkCoordinatorAccountHeadless, listMaintenanceJobs, listPerPeerScopeSyncState, listRetentionScopeIds, loadObserverConfig, loadPublicKey, loadRuntimeSigningPublicKey, loadSqliteVec, mdnsEnabled, mutateCodememConfigFile, normalizeCoordinatorAccountLinkOrigin, normalizePromptTransportProtocolRange, observerBaseUrlForProviderOverride, parseControllerHistoryEvidence, parseFileContextTransportRequest, planReplicationOpsAgePrune, probeCodememViewerLiveness, probeCodememViewerLiveness as probeCodememViewerLiveness$1, probeRequiredNativeRuntime, projectMatchesFilter, promptPackArtifactFingerprint, pruneReplicationOpsUntilCaughtUp, rawEventsGate, readAccountLinkDevice, readCodememConfigFile, readCodememConfigFileAtPath, readCoordinatorAccountLinkStatus, readCoordinatorOwnerReviewLocalEvidence, readCoordinatorSyncConfig, readImportPayload, recordAutomaticRecall, recordPromptPackArtifacts, recordPromptPackTerminal, renderUnifiedDiff, replayBatchExtraction, replayBatchExtractionWithTierRouting, requestJson, resolveCodememConfigPath, resolveComparablePath, resolveDbPath, resolveHookProject, resolveKeyPaths, resolvePiAgentDir, resolvePiObserverConfig, resolveProject, resolveProjectRoot, retryRawEventFailures, runSyncDaemon, runSyncPass, scanSecretsRetroactive, schema, scoreExtractionBenchmarkOutput, searchPiSessions, setPeerProjectFilter, syncPassPreflight, tryUpdateRetrievalDelivery, updatePeerAddresses, upgradeCoordinatorAccountSchemaFile, upgradeCoordinatorAuthSchemaFile, upgradeCoordinatorOwnerResolutionSchemaFile, vacuumDatabase, viewerUrl, withDiagnosticStoreSnapshot, writeCodememConfigFile } from "@codemem/core";
2
+ import { ACCOUNT_CONNECTION_MIGRATION_STATEMENTS, ACCOUNT_UNLINK_MIGRATION_STATEMENTS, ALLOWED_MEMORY_KINDS, AUTH_LINK_AUTHORITY_CUTOVER_SQL, ContextOnlyReplayError, CoordinatorAccountLinkError, DEDUP_KEY_BACKFILL_JOB, DEFAULT_COORDINATOR_DB_PATH, DEFAULT_RAW_EVENT_FLUSH_MAX_EVENTS, DedupKeyBackfillRunner, DeviceIdentityError, EXTRACTION_BENCHMARK_QUALITY_WEIGHTS, FILE_CONTEXT_TRANSPORT_MAX_BYTES, FILE_CONTEXT_TRANSPORT_PROFILE, LEGACY_OWNER_RESOLUTION_SCHEMA_STATEMENTS, MUTATING_TOOL_NAMES, MemoryStore, ObserverClient, ObserverOutputError, ObserverOutputTransportError, OwnerProfileEnrollmentError, PROMPT_TRANSPORT_PROTOCOL_RANGE, REF_BACKFILL_JOB, RawEventIngestValidationError, RawEventSweeper, RefBackfillRunner, RemoteCoordinatorRequestError, SCOPE_BACKFILL_JOB, SESSION_CONTEXT_BACKFILL_JOB, SUMMARY_DEDUP_BACKFILL_JOB, ScopeBackfillRunner, SessionContextBackfillRunner, SummaryDedupBackfillRunner, SyncRetentionRunner, TRUSTED_HOOK_MAPPER_OPTIONS, VERSION, VectorModelMigrationRunner, aiBackfillStructuredContent, applyBootstrapSnapshot, applyDistillRule, arePromptTransportProtocolRangesCompatible, atomicReplaceConfigFile, backfillMemoryDedupKeys, backfillNarrativeFromBody, backfillTagsText, backfillVectors, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildTieredObserverSelection, buildViewerIdentityTarget, classifyPromptTransportFailure, clonePromptPackAttempt, collectOperationalStatus, compareMemoryRoleReports, connect, connectReadOnly, coordinatorAuthControllerReviewAction, coordinatorAuthStageBaselineSql, coordinatorCreateGroupAction, coordinatorCreateScopeAction, coordinatorD1BaselineMigrations, coordinatorD1ConditionalBaselineMigrations, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorEnrollDeviceAction, coordinatorGrantIdentityGroupAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListRemovedDevicesAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorQualifyOwnerAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorReviewInviteAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeDeviceAction, coordinatorRevokeScopeMembershipAction, coordinatorUpdateScopeAction, createBetterSqliteCoordinatorApp, createCoordinatorRefreshLifecycle, createFileContextRunner, deactivateLowSignalMemories, dedupNearDuplicateMemories, describePiObserverStatus, detectInstallKind, diagnoseLegacyTeamSetupCompletion, dispatchFileContextTransport, draftDistillRule, enrollOwnerProfile, ensureDeviceIdentity, ensureSchemaBootstrapped, estimateExtractionModelCost, expandUserPath, exportMemories, extractApplyPatchPaths, extractionReplayObserverIdentity, fetchAllSnapshotPages, fingerprintPublicKey, flushRawEvents, formatHostPort, getAttributionDiagnostics, getCodememConfigPath, getExtractionBenchmarkProfile, getExtractionModelPricing, getInjectionEvalScenarioPack, getInjectionEvalScenarioPrompts, getMaintenanceJob, getMemoryArtifactReport, getMemoryRoleReport, getRawEventRelinkPlan, getRawEventRelinkReport, getRawEventStatus, getSessionExtractionEval, getSessionExtractionEvalScenario, getUpdateStatus, getWorkspaceCodememConfigPath, hasPendingDedupKeyBackfill, hasPendingRefBackfill, hasPendingScopeBackfill, hasPendingSessionContextBackfill, hasPendingSummaryDedupBackfill, hasUnsyncedSharedMemoryChanges, importMemories, importPiSessions, ingestRawEvents, initDatabase, isAutomaticRecallMeasurement, isCoordinatorControllerAttestationReference, isEmbeddingDisabled, isExplicitUpdateInstallEligible, isReleaseVersionForChannel, judgeDistillReport, legacyTeamCandidateId, linkCoordinatorAccount, linkCoordinatorAccountHeadless, listMaintenanceJobs, listPerPeerScopeSyncState, listRetentionScopeIds, loadObserverConfig, loadPublicKey, loadRuntimeSigningPublicKey, loadSqliteVec, mdnsEnabled, mutateCodememConfigFile, normalizeCoordinatorAccountLinkOrigin, normalizePromptTransportProtocolRange, observerBaseUrlForProviderOverride, parseControllerHistoryEvidence, parseFileContextTransportRequest, peerProjectFilterChangeOnlyNarrows, planReplicationOpsAgePrune, probeCodememViewerLiveness, probeCodememViewerLiveness as probeCodememViewerLiveness$1, probeRequiredNativeRuntime, projectMatchesFilter, promptPackArtifactFingerprint, pruneReplicationOpsUntilCaughtUp, rawEventsGate, readAccountLinkDevice, readCodememConfigFile, readCodememConfigFileAtPath, readCoordinatorAccountLinkStatus, readCoordinatorOwnerReviewLocalEvidence, readCoordinatorSyncConfig, readImportPayload, readPeerProjectFilterAuthority, recordAutomaticRecall, recordPromptPackArtifacts, recordPromptPackTerminal, refreshCoordinatorForDaemon, rememberPeerProjectFilterManagement, removePeerFromThisDevice, renderUnifiedDiff, replayBatchExtraction, replayBatchExtractionWithTierRouting, requestJson, resolveCodememConfigPath, resolveComparablePath, resolveDbPath, resolveHookProject, resolveKeyPaths, resolvePiAgentDir, resolvePiObserverConfig, resolveProject, resolveProjectRoot, retryRawEventFailures, runDeviceRejoin, runSyncDaemon, runSyncPass, scanSecretsRetroactive, schema, scoreExtractionBenchmarkOutput, searchPiSessions, setPeerProjectFilterChecked, syncPassPreflight, tryUpdateRetrievalDelivery, updatePeerAddresses, upgradeCoordinatorAccountSchemaFile, upgradeCoordinatorAuthSchemaFile, upgradeCoordinatorOwnerResolutionSchemaFile, vacuumDatabase, viewerUrl, withDiagnosticStoreSnapshot, writeCodememConfigFile } from "@codemem/core";
3
3
  import { Command, Option } from "commander";
4
4
  import omelette from "omelette";
5
5
  import { appendFileSync, closeSync, constants, copyFileSync, existsSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
@@ -1815,14 +1815,14 @@ async function nativeDeliveryAcknowledgement(deliver, serialized) {
1815
1815
  }
1816
1816
  function assertNativeRecoverySnapshot(snapshot) {
1817
1817
  const { dir, dirFd, path, fd, details, serialized, lock } = snapshot;
1818
- if (!sameInode(requireSafeSpoolDirectory(dir), fstatSync(dirFd))) fail("unsafe_directory");
1818
+ if (!sameInode(requireSafeSpoolDirectory(dir), fstatSync(dirFd))) fail$2("unsafe_directory");
1819
1819
  assertLock(lock);
1820
1820
  for (const current of [fstatSync(fd), lstatSync(path)]) {
1821
1821
  requireFile(current);
1822
- if (!sameSnapshot(details, current)) fail("changed_during_read");
1822
+ if (!sameSnapshot(details, current)) fail$2("changed_during_read");
1823
1823
  }
1824
- if (!readLimited(fd, 16777216)?.equals(Buffer.from(serialized, "utf8")) || !sameSnapshot(details, fstatSync(fd)) || !sameSnapshot(details, lstatSync(path))) fail("changed_during_read");
1825
- if (!sameInode(requireSafeSpoolDirectory(dir), fstatSync(dirFd))) fail("unsafe_directory");
1824
+ if (!readLimited(fd, 16777216)?.equals(Buffer.from(serialized, "utf8")) || !sameSnapshot(details, fstatSync(fd)) || !sameSnapshot(details, lstatSync(path))) fail$2("changed_during_read");
1825
+ if (!sameInode(requireSafeSpoolDirectory(dir), fstatSync(dirFd))) fail$2("unsafe_directory");
1826
1826
  assertLock(lock);
1827
1827
  }
1828
1828
  function finishNativeRecovery(snapshot, keepReceipt) {
@@ -1883,11 +1883,11 @@ async function recoverNativeHookReceipt({ provider, receipt, deliver, keepReceip
1883
1883
  let result;
1884
1884
  try {
1885
1885
  const metadata = parseReceipt(receipt);
1886
- if (typeof deliver !== "function") fail("invalid_delivery");
1886
+ if (typeof deliver !== "function") fail$2("invalid_delivery");
1887
1887
  const dir = providerDirectory(provider);
1888
1888
  const directory = requireSafeSpoolDirectory(dir);
1889
1889
  dirFd = openSync(dir, flags | (constants.O_DIRECTORY ?? 0));
1890
- if (!sameInode(directory, fstatSync(dirFd))) fail("unsafe_directory");
1890
+ if (!sameInode(directory, fstatSync(dirFd))) fail$2("unsafe_directory");
1891
1891
  lock = acquireLock(dir, receipt.slice(`rejected-${metadata.status}-${metadata.reason}-`.length, -9), dirFd);
1892
1892
  result = await deliverNativeRecovery({
1893
1893
  dir,
@@ -1913,7 +1913,7 @@ function inspectionError(code) {
1913
1913
  if (code === "unsafe_entry") message = "Stop capture and verify the receipt before retrying. It must remain the same regular file, not a symlink. On POSIX, it must not be group- or other-writable. No permissions were changed.";
1914
1914
  return new RawEventSpoolInspectionError(code, message);
1915
1915
  }
1916
- function fail(code) {
1916
+ function fail$2(code) {
1917
1917
  throw inspectionError(code);
1918
1918
  }
1919
1919
  function hasCode(error, code) {
@@ -1926,17 +1926,17 @@ function sameSnapshot(a, b) {
1926
1926
  return sameInode(a, b) && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs;
1927
1927
  }
1928
1928
  function requireFile(stat) {
1929
- if (!stat.isFile() || stat.isSymbolicLink() || posix$1 && (stat.mode & 18) !== 0) fail("unsafe_entry");
1929
+ if (!stat.isFile() || stat.isSymbolicLink() || posix$1 && (stat.mode & 18) !== 0) fail$2("unsafe_entry");
1930
1930
  }
1931
1931
  function requireDirectory(dir) {
1932
1932
  const stat = lstatSync(dir);
1933
- if (!stat.isDirectory() || stat.isSymbolicLink()) fail("unsafe_directory");
1933
+ if (!stat.isDirectory() || stat.isSymbolicLink()) fail$2("unsafe_directory");
1934
1934
  return stat;
1935
1935
  }
1936
1936
  function requireSafeSpoolDirectory(dir) {
1937
1937
  const stat = requireDirectory(dir);
1938
1938
  const parent = requireDirectory(dirname(resolve(dir)));
1939
- if (posix$1 && (stat.uid !== process.geteuid?.() || (stat.mode & 18) !== 0 || parent.uid !== process.geteuid?.() && parent.uid !== 0 || (parent.mode & 18) !== 0 && (parent.mode & 512) === 0)) fail("unsafe_directory");
1939
+ if (posix$1 && (stat.uid !== process.geteuid?.() || (stat.mode & 18) !== 0 || parent.uid !== process.geteuid?.() && parent.uid !== 0 || (parent.mode & 18) !== 0 && (parent.mode & 512) === 0)) fail$2("unsafe_directory");
1940
1940
  return stat;
1941
1941
  }
1942
1942
  function openFile(path) {
@@ -1946,7 +1946,7 @@ function openFile(path) {
1946
1946
  try {
1947
1947
  for (const actual of [fstatSync(fd), lstatSync(path)]) {
1948
1948
  requireFile(actual);
1949
- if (!sameInode(actual, expected)) fail("unsafe_entry");
1949
+ if (!sameInode(actual, expected)) fail$2("unsafe_entry");
1950
1950
  }
1951
1951
  return fd;
1952
1952
  } catch (error) {
@@ -1968,9 +1968,9 @@ function readLimited(fd, limit) {
1968
1968
  return null;
1969
1969
  }
1970
1970
  function parseReceipt(receipt) {
1971
- if (typeof receipt !== "string" || receipt.includes("/") || receipt.includes("\\")) fail("invalid_receipt");
1971
+ if (typeof receipt !== "string" || receipt.includes("/") || receipt.includes("\\")) fail$2("invalid_receipt");
1972
1972
  const match = retainedPattern.exec(receipt);
1973
- if (!match?.[2] || match[0] !== receipt || !isOriginalName(match[2])) fail("invalid_receipt");
1973
+ if (!match?.[2] || match[0] !== receipt || !isOriginalName(match[2])) fail$2("invalid_receipt");
1974
1974
  if (match[1] === "400-invalid_payload") return {
1975
1975
  receipt,
1976
1976
  status: 400,
@@ -1986,7 +1986,7 @@ function providerDirectory(provider) {
1986
1986
  if (provider === "claude") return spoolDir();
1987
1987
  if (provider === "codex") return codexHookSpoolDir();
1988
1988
  if (provider === "pi") return piHookSpoolDir();
1989
- return fail("invalid_provider");
1989
+ return fail$2("invalid_provider");
1990
1990
  }
1991
1991
  function safeFailure(error, lock) {
1992
1992
  let failure;
@@ -2104,9 +2104,9 @@ function classifyLock(path, receipt) {
2104
2104
  try {
2105
2105
  const before = fstatSync(fd);
2106
2106
  const bytes = before.size <= 1024 ? readLimited(fd, 1024) : null;
2107
- if (!bytes || !sameSnapshot(before, fstatSync(fd)) || !sameSnapshot(before, lstatSync(path))) fail(code);
2107
+ if (!bytes || !sameSnapshot(before, fstatSync(fd)) || !sameSnapshot(before, lstatSync(path))) fail$2(code);
2108
2108
  const record = JSON.parse(bytes.toString("utf8"));
2109
- if (Object.keys(record).sort().join() !== "pid,purpose,receipt,token,version" || record.purpose !== lockPurpose || record.version !== 1 || record.receipt !== receipt || !Number.isSafeInteger(record.pid) || record.pid <= 0 || typeof record.token !== "string" || !/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(record.token)) fail(code);
2109
+ if (Object.keys(record).sort().join() !== "pid,purpose,receipt,token,version" || record.purpose !== lockPurpose || record.version !== 1 || record.receipt !== receipt || !Number.isSafeInteger(record.pid) || record.pid <= 0 || typeof record.token !== "string" || !/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(record.token)) fail$2(code);
2110
2110
  try {
2111
2111
  process.kill(record.pid, 0);
2112
2112
  code = "lock_busy";
@@ -2117,7 +2117,7 @@ function classifyLock(path, receipt) {
2117
2117
  closeSync(fd);
2118
2118
  }
2119
2119
  } catch {}
2120
- return fail(code);
2120
+ return fail$2(code);
2121
2121
  }
2122
2122
  function cleanupNewLock(fd, path, dirFd) {
2123
2123
  try {
@@ -2140,7 +2140,7 @@ function acquireLock(dir, receipt, dirFd) {
2140
2140
  fd = openSync(path, constants.O_CREAT | constants.O_EXCL | constants.O_RDWR | (constants.O_NOFOLLOW ?? 0), 384);
2141
2141
  } catch (error) {
2142
2142
  if (hasCode(error, "EEXIST")) return classifyLock(path, receipt);
2143
- return fail("lock_failed");
2143
+ return fail$2("lock_failed");
2144
2144
  }
2145
2145
  try {
2146
2146
  const serialized = JSON.stringify({
@@ -2151,11 +2151,11 @@ function acquireLock(dir, receipt, dirFd) {
2151
2151
  token: randomUUID()
2152
2152
  });
2153
2153
  const data = Buffer.from(serialized);
2154
- if (writeSync(fd, data) !== data.length) fail("lock_repair_required");
2154
+ if (writeSync(fd, data) !== data.length) fail$2("lock_repair_required");
2155
2155
  fsyncSync(fd);
2156
2156
  const details = fstatSync(fd);
2157
2157
  requireFile(details);
2158
- if (!sameSnapshot(details, lstatSync(path))) fail("lock_repair_required");
2158
+ if (!sameSnapshot(details, lstatSync(path))) fail$2("lock_repair_required");
2159
2159
  return {
2160
2160
  fd,
2161
2161
  path,
@@ -2163,12 +2163,12 @@ function acquireLock(dir, receipt, dirFd) {
2163
2163
  details
2164
2164
  };
2165
2165
  } catch {
2166
- return fail(cleanupNewLock(fd, path, dirFd) ? "lock_failed" : "lock_repair_required");
2166
+ return fail$2(cleanupNewLock(fd, path, dirFd) ? "lock_failed" : "lock_repair_required");
2167
2167
  }
2168
2168
  }
2169
2169
  function assertLock(lock) {
2170
2170
  const bytes = readLimited(lock.fd, 1024);
2171
- if (!bytes || bytes.toString("utf8") !== lock.serialized || !sameSnapshot(lock.details, fstatSync(lock.fd)) || !sameSnapshot(lock.details, lstatSync(lock.path))) fail("lock_repair_required");
2171
+ if (!bytes || bytes.toString("utf8") !== lock.serialized || !sameSnapshot(lock.details, fstatSync(lock.fd)) || !sameSnapshot(lock.details, lstatSync(lock.path))) fail$2("lock_repair_required");
2172
2172
  }
2173
2173
  function releaseLock(lock, dirFd) {
2174
2174
  try {
@@ -2205,17 +2205,17 @@ function linkIfAbsent(source, target) {
2205
2205
  function requireLinkedSnapshot(path, before) {
2206
2206
  const current = lstatSync(path);
2207
2207
  requireFile(current);
2208
- if (!sameInode(before, current)) fail("retention_conflict");
2209
- if (before.size !== current.size || before.mtimeMs !== current.mtimeMs) fail("unsafe_entry");
2208
+ if (!sameInode(before, current)) fail$2("retention_conflict");
2209
+ if (before.size !== current.size || before.mtimeMs !== current.mtimeMs) fail$2("unsafe_entry");
2210
2210
  }
2211
2211
  function retainLinked(dir, dirFd, receipt, metadata, assertOwnership) {
2212
2212
  const source = join(dir, receipt);
2213
2213
  const target = join(dir, metadata.receipt);
2214
2214
  const alternateStatus = metadata.status === 400 ? "413-payload_too_large" : "400-invalid_payload";
2215
- if (statIfPresent(join(dir, `rejected-${alternateStatus}-${receipt}.retained`))) fail("retention_conflict");
2215
+ if (statIfPresent(join(dir, `rejected-${alternateStatus}-${receipt}.retained`))) fail$2("retention_conflict");
2216
2216
  const existing = statIfPresent(target);
2217
2217
  if (!statIfPresent(source)) {
2218
- if (!existing) fail("receipt_not_found");
2218
+ if (!existing) fail$2("receipt_not_found");
2219
2219
  const fd = openFile(target);
2220
2220
  try {
2221
2221
  assertOwnership();
@@ -2233,9 +2233,9 @@ function retainLinked(dir, dirFd, receipt, metadata, assertOwnership) {
2233
2233
  const fd = openFile(source);
2234
2234
  try {
2235
2235
  const before = fstatSync(fd);
2236
- if (existing && !sameInode(existing, before)) fail("retention_conflict");
2236
+ if (existing && !sameInode(existing, before)) fail$2("retention_conflict");
2237
2237
  fsyncSync(fd);
2238
- if (!sameSnapshot(before, lstatSync(source))) fail("unsafe_entry");
2238
+ if (!sameSnapshot(before, lstatSync(source))) fail$2("unsafe_entry");
2239
2239
  assertOwnership();
2240
2240
  if (!existing) linkIfAbsent(source, target);
2241
2241
  fsyncSync(dirFd);
@@ -2255,17 +2255,17 @@ function retainLinked(dir, dirFd, receipt, metadata, assertOwnership) {
2255
2255
  /** Delivery callers must also hold the provider's ingest lock to coordinate ordinary drain cleanup. */
2256
2256
  function retainNativeHookReceipt({ dir, receipt, status, reason }) {
2257
2257
  try {
2258
- if (typeof receipt !== "string" || !isOriginalName(receipt)) fail("invalid_receipt");
2258
+ if (typeof receipt !== "string" || !isOriginalName(receipt)) fail$2("invalid_receipt");
2259
2259
  const metadata = parseReceipt(`rejected-${status}-${reason}-${receipt}.retained`);
2260
2260
  const directory = requireSafeSpoolDirectory(dir);
2261
2261
  const dirFd = openSync(dir, flags | (constants.O_DIRECTORY ?? 0));
2262
2262
  try {
2263
- if (!sameInode(directory, fstatSync(dirFd))) fail("unsafe_directory");
2263
+ if (!sameInode(directory, fstatSync(dirFd))) fail$2("unsafe_directory");
2264
2264
  const lock = acquireLock(dir, receipt, dirFd);
2265
2265
  let result;
2266
2266
  try {
2267
2267
  result = retainLinked(dir, dirFd, receipt, metadata, () => {
2268
- if (!sameInode(directory, requireSafeSpoolDirectory(dir))) fail("unsafe_directory");
2268
+ if (!sameInode(directory, requireSafeSpoolDirectory(dir))) fail$2("unsafe_directory");
2269
2269
  assertLock(lock);
2270
2270
  });
2271
2271
  } catch (error) {
@@ -3825,6 +3825,12 @@ var STAGES = [
3825
3825
  "prior_extension",
3826
3826
  "current"
3827
3827
  ];
3828
+ /** Names the migrations that the statement records only when their objects exist. */
3829
+ function conditionalMigrationsText(stage) {
3830
+ const conditional = coordinatorD1ConditionalBaselineMigrations(stage);
3831
+ if (conditional.length === 0) return "";
3832
+ return `-- Also records ${conditional.join(" and ")}, each only when the objects it adds already exist.\n-- A migration without them stays unrecorded, and wrangler d1 migrations apply runs it.\n`;
3833
+ }
3828
3834
  function exportBaseline(options) {
3829
3835
  const statement = coordinatorAuthStageBaselineSql(options.stage);
3830
3836
  const migrations = coordinatorD1BaselineMigrations(options.stage);
@@ -3836,7 +3842,9 @@ function exportBaseline(options) {
3836
3842
  })}\n`);
3837
3843
  return;
3838
3844
  }
3839
- process.stdout.write(`-- Records ${migrations.length} migrations, ${migrations[0]} through ${migrations.at(-1)}, in the existing d1_migrations ledger\n-- only if auth-stage ${options.stage} readiness and the remaining table and column names match.\n-- The inventory does not check types, constraints, indexes, triggers or row validity. Compare the schema before applying.\n-- Otherwise it records nothing or fails to compile. "no such table: d1_migrations" means the ledger must be created first.\n-- Nothing has been applied.\n${statement};\n`);
3845
+ const conditional = coordinatorD1ConditionalBaselineMigrations(options.stage);
3846
+ const always = migrations.filter((name) => !conditional.includes(name));
3847
+ process.stdout.write(`-- Records ${always.length} migrations, ${always[0]} through ${always.at(-1)}, in the existing d1_migrations ledger\n-- only if auth-stage ${options.stage} readiness and the remaining table and column names match.\n${conditionalMigrationsText(options.stage)}-- The inventory does not check types, constraints, indexes, triggers or row validity. Compare the schema before applying.\n-- Otherwise it records nothing or fails to compile. "no such table: d1_migrations" means the ledger must be created first.\n-- Nothing has been applied.\n${statement};\n`);
3840
3848
  }
3841
3849
  function buildCoordinatorD1BaselineCommand() {
3842
3850
  const command = new Command("baseline-d1").configureHelp(helpStyle).description("Export the guarded D1 ledger baseline for auth migrations already present").addOption(new Option("--stage <stage>", "auth schema stage the D1 database is already at").choices(STAGES).makeOptionMandatory()).addHelpText("after", "\nFor a D1 database whose schema came from outside the numbered migrations, such as schema.sql or an\nexported auth install. Back up and compare the schema before creating the ledger (wrangler d1 migrations list).\nThen run the statement with wrangler d1 execute and apply the rest with wrangler d1 migrations apply.\nThe statement checks auth-stage readiness and remaining table and column names. The inventory does not\ncheck types, constraints, indexes, triggers or row validity. This command opens no database.\n");
@@ -3942,6 +3950,46 @@ function buildCoordinatorDiagnoseTeamSetupCommand() {
3942
3950
  return command;
3943
3951
  }
3944
3952
  //#endregion
3953
+ //#region src/commands/coordinator-enable-device.ts
3954
+ function fail$1(options, code, message) {
3955
+ if (options.json) return emitJsonError(code, message);
3956
+ p.log.error(message);
3957
+ process.exitCode = 1;
3958
+ }
3959
+ async function enableDevice(group, device, options) {
3960
+ const groupId = group.trim();
3961
+ const deviceId = device.trim();
3962
+ try {
3963
+ if (!await coordinatorEnableDeviceAction({
3964
+ groupId,
3965
+ deviceId,
3966
+ dbPath: resolveDbOpt(options),
3967
+ remoteUrl: "",
3968
+ adminSecret: ""
3969
+ })) return fail$1(options, "device_not_enabled", "The device was not enabled. It has no enrollment in this group, or it is permanently blocked.");
3970
+ if (options.json) {
3971
+ console.log(JSON.stringify({
3972
+ ok: true,
3973
+ group_id: groupId,
3974
+ device_id: deviceId
3975
+ }, null, 2));
3976
+ return;
3977
+ }
3978
+ p.log.success("Device enabled.");
3979
+ } catch (error) {
3980
+ const code = error instanceof Error ? error.message : "";
3981
+ if (code === "device_removed") return fail$1(options, code, "This device was removed. It must rejoin before it can be enabled.");
3982
+ if (code === "device_revoked") return fail$1(options, code, "This device is permanently blocked.");
3983
+ return fail$1(options, "enable_failed", "Could not enable the device. Check the coordinator database and device IDs.");
3984
+ }
3985
+ }
3986
+ function buildCoordinatorEnableDeviceCommand() {
3987
+ const command = new Command("enable").configureHelp(helpStyle).description("Enable an existing device enrollment in a local coordinator group").argument("<group>", "group id").argument("<device-id>", "device id");
3988
+ addDbOption(command);
3989
+ addJsonOption(command);
3990
+ return command.action(enableDevice);
3991
+ }
3992
+ //#endregion
3945
3993
  //#region src/commands/coordinator-enroll-owner.ts
3946
3994
  var CAPTURE_WARNING = "Stop OpenCode capture, the Viewer and the sync daemon before preparing or resuming. Keep them stopped until Verified coordinator Identity is shown. Any capture/history change during the browser ceremony can stop local adoption after the server commits, leaving DB and config separate and requiring operator review.";
3947
3995
  function showPrivateBrowserLink$1(privateUrl) {
@@ -4202,6 +4250,188 @@ function buildCoordinatorGrantIdentityGroupCommand() {
4202
4250
  return command;
4203
4251
  }
4204
4252
  //#endregion
4253
+ //#region src/commands/coordinator-invitation-create.ts
4254
+ var defaultDeps = {
4255
+ openStore: (dbPath) => new MemoryStore(dbPath),
4256
+ preview: async (store, body) => (await import("@codemem/server")).previewRecipientInvitation(store, body),
4257
+ create: async (store, body) => (await import("@codemem/server")).createRecipientInvitation(store, body)
4258
+ };
4259
+ var InvitationCreateError = class extends Error {
4260
+ code;
4261
+ exitCode;
4262
+ constructor(code, message, exitCode = 1) {
4263
+ super(message);
4264
+ this.code = code;
4265
+ this.exitCode = exitCode;
4266
+ }
4267
+ };
4268
+ var USAGE_ERRORS = /* @__PURE__ */ new Set([
4269
+ "invitation_kind_required",
4270
+ "usage_error",
4271
+ "reviewed_onboarding_digest_required",
4272
+ "ttl_hours_invalid"
4273
+ ]);
4274
+ var ERROR_MESSAGES = {
4275
+ coordinator_admin_secret_missing: "Team invitations need the coordinator admin secret on this device. Run this on the device that holds it.",
4276
+ coordinator_not_configured: "This device isn't connected to a coordinator. Set the coordinator URL and group in its config, then try again.",
4277
+ coordinator_group_missing: "This device has no coordinator group configured. Set one in its config, then try again.",
4278
+ reviewed_onboarding_stale: "The Projects this invitation shares changed after your review. Run with --review again and use the new digest.",
4279
+ reviewed_onboarding_digest_required: "Review the invitation first with --review, then pass --reviewed-onboarding-digest <digest>.",
4280
+ invite_identity_conflict: "An add-device invitation can only add a device for the person on this device.",
4281
+ ttl_hours_invalid: "--ttl-hours must be a whole number of at least 1.",
4282
+ group_id_required: "This device has no coordinator group configured. Pass --group <group> or set one in its config."
4283
+ };
4284
+ var REMOTE_FAILURE = /^Remote coordinator request failed \((\d+)\): (.*)$/;
4285
+ var TRANSPORT_FAILURE = /fetch failed|timeout|timed out|aborted|ECONNREFUSED|ENOTFOUND|EAI_AGAIN/i;
4286
+ var ADMIN_SECRET_ERRORS = /* @__PURE__ */ new Set(["invalid_admin_secret", "missing_admin_header"]);
4287
+ var DEVICE_AUTH_ERRORS = /* @__PURE__ */ new Set([
4288
+ "unknown_device",
4289
+ "device_disabled",
4290
+ "device_revoked",
4291
+ "invalid_signature",
4292
+ "missing_headers",
4293
+ "signature_verification_error"
4294
+ ]);
4295
+ /** Turns a raw failure from the shared invitation code into a code and next step. */
4296
+ function describeFailure(raw) {
4297
+ const known = ERROR_MESSAGES[raw];
4298
+ if (known) return {
4299
+ code: raw,
4300
+ message: known
4301
+ };
4302
+ const remote = REMOTE_FAILURE.exec(raw);
4303
+ const remoteError = remote?.[2] ?? "";
4304
+ if (ADMIN_SECRET_ERRORS.has(remoteError)) return {
4305
+ code: "coordinator_admin_secret_rejected",
4306
+ message: "The coordinator rejected this device's admin secret, so no invitation was created. Make sure sync_coordinator_admin_secret in this device's config matches the coordinator, then try again."
4307
+ };
4308
+ if (remoteError === "admin_not_configured") return {
4309
+ code: "coordinator_admin_not_configured",
4310
+ message: "The coordinator has no admin secret set, so it can't create Team invitations. Set CODEMEM_SYNC_COORDINATOR_ADMIN_SECRET on the coordinator host, restart it, then try again."
4311
+ };
4312
+ if (DEVICE_AUTH_ERRORS.has(remoteError)) return {
4313
+ code: "coordinator_device_rejected",
4314
+ message: `The coordinator didn't accept this device (${remoteError}), so no invitation was created. Ask a Team admin to check that this device is still active in the coordinator group, or create the invitation on a device that holds the coordinator admin secret.`
4315
+ };
4316
+ if (remote) return {
4317
+ code: "coordinator_request_failed",
4318
+ message: `The coordinator refused the request (HTTP ${remote[1]}: ${remote[2]}), so no invitation was created. Check that the coordinator is running and up to date, then try again.`
4319
+ };
4320
+ if (TRANSPORT_FAILURE.test(raw)) return {
4321
+ code: "coordinator_unreachable",
4322
+ message: "codemem couldn't reach the coordinator, so it can't confirm whether the invitation was created. Check the coordinator URL in this device's config and that the coordinator is running, then try again. An unused invitation expires on its own."
4323
+ };
4324
+ return {
4325
+ code: "invitation_create_failed",
4326
+ message: `codemem couldn't create the invitation (${raw}). Check this device's coordinator settings, then try again.`
4327
+ };
4328
+ }
4329
+ function invitationFailure(raw) {
4330
+ const described = describeFailure(raw);
4331
+ return new InvitationCreateError(described.code, described.message);
4332
+ }
4333
+ function fail(code, message) {
4334
+ const exitCode = USAGE_ERRORS.has(code) ? 2 : 1;
4335
+ if (message) throw new InvitationCreateError(code, message, exitCode);
4336
+ const described = describeFailure(code);
4337
+ throw new InvitationCreateError(described.code, described.message, exitCode);
4338
+ }
4339
+ function resolveTeamId(store, team) {
4340
+ const rows = store.db.prepare("SELECT team_id, display_name FROM policy_teams WHERE status = 'active'").all();
4341
+ const byId = rows.find((row) => row.team_id === team);
4342
+ if (byId) return byId.team_id;
4343
+ const key = team.normalize("NFC").toLowerCase();
4344
+ const byName = rows.filter((row) => row.display_name.normalize("NFC").toLowerCase() === key);
4345
+ if (byName.length === 1 && byName[0]) return byName[0].team_id;
4346
+ if (byName.length > 1) fail("team_ambiguous", `More than one Team is named "${team}". Pass its Team ID instead.`);
4347
+ return fail("team_not_found", `No active Team named "${team}" on this device. Create it in Sharing, or run this on a device where it exists.`);
4348
+ }
4349
+ function requestBody(store, opts, legacyArgs) {
4350
+ if (legacyArgs.length > 0 || Boolean(opts.team) === Boolean(opts.addDevice)) fail("invitation_kind_required", "Choose --team <name> or --add-device. codemem no longer creates invitations that only connect a device. To connect a device without sharing Projects, use `codemem coordinator device enroll`.");
4351
+ if (opts.review && opts.reviewedOnboardingDigest !== void 0) fail("usage_error", "Use --review or --reviewed-onboarding-digest, not both.");
4352
+ return {
4353
+ ...opts.team ? {
4354
+ kind: "team_member",
4355
+ policy_team_id: resolveTeamId(store, opts.team.trim())
4356
+ } : {
4357
+ kind: "add_device",
4358
+ target_identity_id: store.actorId
4359
+ },
4360
+ ...opts.group?.trim() ? { group_id: opts.group.trim() } : {},
4361
+ ttl_hours: opts.ttlHours ?? "24",
4362
+ ...opts.reviewedOnboardingDigest ? { reviewed_onboarding_digest: opts.reviewedOnboardingDigest.trim() } : {}
4363
+ };
4364
+ }
4365
+ function unwrap(outcome) {
4366
+ if (outcome.httpStatus === 200) return outcome.body;
4367
+ return fail(String(outcome.body.error ?? "invitation_create_failed"));
4368
+ }
4369
+ function printReview(body, opts) {
4370
+ const preview = body.preview;
4371
+ if (opts.json) {
4372
+ console.log(JSON.stringify({
4373
+ kind: body.kind,
4374
+ preview
4375
+ }, null, 2));
4376
+ return;
4377
+ }
4378
+ p.intro("codemem coordinator invitation create --review");
4379
+ if (preview.team?.displayName) p.log.message(`Team: ${preview.team.displayName}`);
4380
+ const projects = preview.projects ?? [];
4381
+ p.log.message(projects.length ? "Shares these Projects:" : "Shares no Projects yet.");
4382
+ for (const project of projects) p.log.message(`- ${project.displayName} (${project.existingMemoryCount ?? 0} memories)`);
4383
+ p.log.message(`Create it with --reviewed-onboarding-digest ${preview.reviewedOnboardingDigest}`);
4384
+ p.outro("Review only; nothing was created");
4385
+ }
4386
+ function printCreated(body, opts) {
4387
+ if (opts.json) {
4388
+ console.log(JSON.stringify(body, null, 2));
4389
+ return;
4390
+ }
4391
+ const invite = body.invite ?? {};
4392
+ p.intro("codemem coordinator invitation create");
4393
+ if (typeof invite.link === "string") p.log.message(`- link: ${invite.link}`);
4394
+ if (typeof invite.encoded === "string") p.log.message(`- invite: ${invite.encoded}`);
4395
+ const warnings = Array.isArray(invite.warnings) ? invite.warnings : [];
4396
+ for (const warning of warnings) if (typeof warning === "string") p.log.warn(warning);
4397
+ p.outro("Invitation ready. Send it to the person you are inviting.");
4398
+ }
4399
+ async function runInvitationCreate(opts, legacyArgs, deps) {
4400
+ if (opts.config) process.env.CODEMEM_CONFIG = opts.config;
4401
+ const store = deps.openStore(resolveDbOpt(opts));
4402
+ try {
4403
+ const body = requestBody(store, opts, legacyArgs);
4404
+ if (opts.review) {
4405
+ printReview(unwrap(await deps.preview(store, body)), opts);
4406
+ return;
4407
+ }
4408
+ if (!opts.reviewedOnboardingDigest) fail("reviewed_onboarding_digest_required");
4409
+ printCreated(unwrap(await deps.create(store, body)), opts);
4410
+ } finally {
4411
+ store.close();
4412
+ }
4413
+ }
4414
+ function buildCoordinatorInvitationCreateCommand(deps = defaultDeps) {
4415
+ const cmd = new Command("create").configureHelp(helpStyle).description("Create a Team or add-device invitation from this device").addOption(new Option("--team <team>", "Team name or ID to invite someone to")).addOption(new Option("--add-device", "invite another device for the person on this device")).option("--review", "show the Projects the invitation shares without creating it").option("--reviewed-onboarding-digest <digest>", "create the invitation you reviewed").option("--group <group>", "coordinator group (defaults to the configured group)").option("--ttl-hours <hours>", "invitation lifetime in hours", "24").allowExcessArguments(true);
4416
+ addDbOption(cmd);
4417
+ addConfigOption(cmd);
4418
+ addJsonOption(cmd);
4419
+ cmd.action(async (opts, command) => {
4420
+ try {
4421
+ await runInvitationCreate(opts, command.args, deps);
4422
+ } catch (err) {
4423
+ const failure = err instanceof InvitationCreateError ? err : invitationFailure(err instanceof Error ? err.message : String(err));
4424
+ if (opts.json) {
4425
+ emitJsonError(failure.code, failure.message, failure.exitCode);
4426
+ return;
4427
+ }
4428
+ p.log.error(failure.message);
4429
+ process.exitCode = failure.exitCode;
4430
+ }
4431
+ });
4432
+ return cmd;
4433
+ }
4434
+ //#endregion
4205
4435
  //#region src/commands/coordinator-link-account-headless.ts
4206
4436
  var output = { output: process.stderr };
4207
4437
  var STATE_LINES = {
@@ -4423,6 +4653,92 @@ function buildCoordinatorLinkAccountCommand() {
4423
4653
  return command;
4424
4654
  }
4425
4655
  //#endregion
4656
+ //#region src/commands/coordinator-list-removed.ts
4657
+ function remoteTarget(path) {
4658
+ const config = readCodememConfigFileAtPath(path);
4659
+ const url = normalizeCoordinatorAccountLinkOrigin(config.sync_coordinator_url);
4660
+ const adminSecret = config.sync_coordinator_admin_secret;
4661
+ if (!url || typeof adminSecret !== "string" || !adminSecret.trim() || /[\r\n\0]/u.test(adminSecret)) throw new Error("removal_list_configuration_unavailable");
4662
+ return {
4663
+ url,
4664
+ adminSecret
4665
+ };
4666
+ }
4667
+ function listFailure(options, message) {
4668
+ if (options.json) return emitJsonError("list_devices_failed", message);
4669
+ p.log.error(message);
4670
+ process.exitCode = 1;
4671
+ }
4672
+ function safeLabel(value) {
4673
+ return value.replace(/[\p{Cc}\p{Cf}\p{Cs}\u2028\u2029]/gu, " ");
4674
+ }
4675
+ function removalListError(error) {
4676
+ if (error instanceof RemoteCoordinatorRequestError && error.status === 404) return "Update the coordinator to list removed devices.";
4677
+ if (error instanceof Error && error.message === "removal_list_configuration_unavailable") return "Select a coordinator config with a URL and admin secret.";
4678
+ if (error instanceof RemoteCoordinatorRequestError && error.code === "device_removal_unavailable" || error instanceof Error && error.message === "device_removal_unavailable") return "The coordinator's device removal storage is unavailable.";
4679
+ return "Could not list removed devices. Check the coordinator database or configuration.";
4680
+ }
4681
+ async function listRemovedDevices(groupId, options) {
4682
+ const group = groupId?.trim();
4683
+ if (group === "") return listFailure(options, "Enter a group ID or omit the group filter.");
4684
+ const dbPath = resolveDbOpt(options);
4685
+ if (dbPath && options.config) return listFailure(options, "Choose either --db-path or --config.");
4686
+ try {
4687
+ const rows = await coordinatorListRemovedDevicesAction({
4688
+ groupId: group,
4689
+ dbPath,
4690
+ remote: options.config ? remoteTarget(options.config) : void 0
4691
+ });
4692
+ if (options.json) {
4693
+ console.log(JSON.stringify(rows, null, 2));
4694
+ return;
4695
+ }
4696
+ p.intro("codemem coordinator device list --removed");
4697
+ for (const row of rows) p.log.message(`- ${safeLabel(row.device_id)} (${safeLabel(row.group_id)})`);
4698
+ p.outro(rows.length ? `${rows.length} removed enrollment(s)` : "No removed devices");
4699
+ } catch (error) {
4700
+ listFailure(options, removalListError(error));
4701
+ }
4702
+ }
4703
+ async function listEnrolledDevices(groupId, options) {
4704
+ if (!groupId) return listFailure(options, "Group id required unless --removed is set.");
4705
+ if (options.config) return listFailure(options, "--config requires --removed.");
4706
+ try {
4707
+ const rows = await coordinatorListDevicesAction({
4708
+ groupId,
4709
+ includeDisabled: options.includeDisabled === true,
4710
+ dbPath: resolveDbOpt(options) ?? null
4711
+ });
4712
+ if (options.json) {
4713
+ console.log(JSON.stringify(rows, null, 2));
4714
+ return;
4715
+ }
4716
+ printEnrolledDevices(groupId, rows);
4717
+ } catch (error) {
4718
+ listFailure(options, error instanceof Error ? error.message : String(error));
4719
+ }
4720
+ }
4721
+ function printEnrolledDevices(groupId, rows) {
4722
+ p.intro("codemem coordinator device list");
4723
+ if (rows.length === 0) {
4724
+ p.outro(`No enrolled devices for ${groupId.trim()}`);
4725
+ return;
4726
+ }
4727
+ for (const row of rows) {
4728
+ const label = String(row.display_name ?? row.device_id ?? "").trim() || String(row.device_id ?? "");
4729
+ const enabled = Number(row.enabled ?? 1) === 1 ? "enabled" : "disabled";
4730
+ p.log.message(`- ${label} (${String(row.device_id ?? "")}) ${enabled}`);
4731
+ }
4732
+ p.outro(`${rows.length} device(s)`);
4733
+ }
4734
+ function buildCoordinatorDeviceListCommand() {
4735
+ const command = new Command("list").configureHelp(helpStyle).description("List enrolled or removed coordinator devices").argument("[group]", "group id (required unless --removed is set)").option("--include-disabled", "include disabled devices").option("--removed", "list active removals that have not been permanently blocked");
4736
+ addConfigOption(command);
4737
+ addDbOption(command);
4738
+ addJsonOption(command);
4739
+ return command.action((groupId, options) => options.removed ? listRemovedDevices(groupId, options) : listEnrolledDevices(groupId, options));
4740
+ }
4741
+ //#endregion
4426
4742
  //#region src/commands/coordinator-qualify-owner.ts
4427
4743
  var isAttestation = (value) => typeof value === "string" && /^controller-v1:[a-f0-9]{64}$/u.test(value);
4428
4744
  var isHash$1 = (value) => typeof value === "string" && /^[a-f0-9]{64}$/u.test(value);
@@ -5068,7 +5384,7 @@ function createCoordinatorResources() {
5068
5384
  const owner = coordinatorResource("owner", "Manage device ownership").addCommand(buildCoordinatorEnrollOwnerCommand()).addCommand(buildCoordinatorReviewDeviceOwnerCommand()).addCommand(buildCoordinatorQualifyOwnerCommand());
5069
5385
  const group = coordinatorResource("group", "Manage coordinator groups and enrollment grants");
5070
5386
  group.addCommand(buildCoordinatorGrantIdentityGroupCommand());
5071
- const device = coordinatorResource("device", "Manage device enrollment and revocation").addCommand(buildCoordinatorRevokeDeviceCommand());
5387
+ const device = coordinatorResource("device", "Manage device enrollment and revocation").addCommand(buildCoordinatorRevokeDeviceCommand()).addCommand(buildCoordinatorEnableDeviceCommand());
5072
5388
  const domain = coordinatorResource("domain", "Manage Sharing domains and device access");
5073
5389
  const invitation = coordinatorResource("invitation", "Create, review, and accept coordinator invitations");
5074
5390
  const request = coordinatorResource("request", "List, approve, and deny coordinator join requests");
@@ -5204,41 +5520,7 @@ function buildCoordinatorCommand() {
5204
5520
  }
5205
5521
  });
5206
5522
  device.addCommand(enrollDeviceCmd);
5207
- const listDevicesCmd = new Command("list").configureHelp(helpStyle).description("List enrolled devices in a local coordinator group").argument("<group>", "group id").option("--include-disabled", "include disabled devices");
5208
- addDbOption(listDevicesCmd);
5209
- addJsonOption(listDevicesCmd);
5210
- listDevicesCmd.action(async (groupId, opts) => {
5211
- try {
5212
- const rows = await coordinatorListDevicesAction({
5213
- groupId,
5214
- includeDisabled: opts.includeDisabled === true,
5215
- dbPath: resolveDbOpt(opts) ?? null
5216
- });
5217
- if (opts.json) {
5218
- console.log(JSON.stringify(rows, null, 2));
5219
- return;
5220
- }
5221
- p.intro("codemem coordinator device list");
5222
- if (rows.length === 0) {
5223
- p.outro(`No enrolled devices for ${groupId.trim()}`);
5224
- return;
5225
- }
5226
- for (const row of rows) {
5227
- const label = String(row.display_name ?? row.device_id ?? "").trim() || String(row.device_id ?? "");
5228
- const enabled = Number(row.enabled ?? 1) === 1 ? "enabled" : "disabled";
5229
- p.log.message(`- ${label} (${String(row.device_id ?? "")}) ${enabled}`);
5230
- }
5231
- p.outro(`${rows.length} device(s)`);
5232
- } catch (err) {
5233
- if (opts.json) {
5234
- emitJsonError("list_devices_failed", err instanceof Error ? err.message : String(err));
5235
- return;
5236
- }
5237
- p.log.error(err instanceof Error ? err.message : String(err));
5238
- process.exitCode = 1;
5239
- }
5240
- });
5241
- device.addCommand(listDevicesCmd);
5523
+ device.addCommand(buildCoordinatorDeviceListCommand());
5242
5524
  const listScopesCmd = new Command("list").configureHelp(helpStyle).description("List coordinator Sharing domains for a group").argument("<group>", "group id").option("--include-inactive", "include inactive Sharing domains").option("--remote-url <url>", "remote coordinator URL override").option("--admin-secret <secret>", "remote coordinator admin secret override");
5243
5525
  addDbOption(listScopesCmd);
5244
5526
  addJsonOption(listScopesCmd);
@@ -5687,43 +5969,7 @@ function buildCoordinatorCommand() {
5687
5969
  }
5688
5970
  });
5689
5971
  grant.addCommand(revokeBootstrapGrantCmd);
5690
- const createInviteCmd = new Command("create").configureHelp(helpStyle).description("Create a coordinator group invitation").argument("[group]", "group id").option("--group <group>", "group id").option("--coordinator-url <url>", "coordinator URL override").option("--policy <policy>", "invite policy", "auto_admit").option("--ttl-hours <hours>", "invitation lifetime in hours", "24").option("--remote-url <url>", "remote coordinator URL override").option("--admin-secret <secret>", "remote coordinator admin secret override");
5691
- addDbOption(createInviteCmd);
5692
- addJsonOption(createInviteCmd);
5693
- createInviteCmd.action(async (groupArg, opts) => {
5694
- try {
5695
- const ttlHours = Number.parseInt(String(opts.ttlHours ?? "24"), 10);
5696
- const groupId = String(opts.group ?? "").trim() || String(groupArg ?? "").trim();
5697
- const result = await coordinatorCreateInviteAction({
5698
- groupId,
5699
- coordinatorUrl: opts.coordinatorUrl?.trim() || null,
5700
- policy: String(opts.policy ?? "auto_admit").trim(),
5701
- ttlHours,
5702
- createdBy: null,
5703
- dbPath: resolveDbOpt(opts) ?? null,
5704
- remoteUrl: opts.remoteUrl?.trim() || null,
5705
- adminSecret: opts.adminSecret?.trim() || null
5706
- });
5707
- if (opts.json) {
5708
- console.log(JSON.stringify(result, null, 2));
5709
- return;
5710
- }
5711
- p.intro("codemem coordinator invitation create");
5712
- p.log.success(`Invite created for ${groupId}`);
5713
- if (typeof result.link === "string") p.log.message(`- link: ${result.link}`);
5714
- if (typeof result.encoded === "string") p.log.message(`- invite: ${result.encoded}`);
5715
- for (const warning of Array.isArray(result.warnings) ? result.warnings : []) p.log.warn(String(warning));
5716
- p.outro("Invite ready");
5717
- } catch (err) {
5718
- if (opts.json) {
5719
- emitJsonError("create_invite_failed", err instanceof Error ? err.message : String(err));
5720
- return;
5721
- }
5722
- p.log.error(err instanceof Error ? err.message : String(err));
5723
- process.exitCode = 1;
5724
- }
5725
- });
5726
- invitation.addCommand(createInviteCmd);
5972
+ invitation.addCommand(buildCoordinatorInvitationCreateCommand());
5727
5973
  const importInviteCmd = new Command("accept").configureHelp(helpStyle).description("Accept a coordinator invitation or review recipient access").argument("<invite>", "invite value or link").option("-R, --recipient-name <name>", "recipient Identity display name").option("-N, --device-name <name>", "device display name").option("--review", "Review recipient access without accepting").option("--reviewed-onboarding-digest <digest>", "Accept the reviewed recipient access").option("--keys-dir <path>", "keys directory");
5728
5974
  addDbOption(importInviteCmd);
5729
5975
  addConfigOption(importInviteCmd);
@@ -6727,7 +6973,7 @@ function createBackfillStructuredCommand(name = "structured") {
6727
6973
  }
6728
6974
  const action = opts.dryRun ? "Would update" : "Updated";
6729
6975
  p.intro("codemem maintenance backfill structured");
6730
- p.log.success(`${action} ${result.updated} memories (skipped ${result.skipped}, failed ${result.failed})`);
6976
+ p.log.success(`${action} ${result.updated} memories (skipped ${result.skipped}, failed ${result.failed}, changed during processing ${result.staleWrites})`);
6731
6977
  p.outro(`Checked ${result.checked} memories`);
6732
6978
  } catch (error) {
6733
6979
  p.log.error(error instanceof Error ? error.message : String(error));
@@ -9568,6 +9814,7 @@ function shortAge(iso) {
9568
9814
  //#region src/commands/mcp.ts
9569
9815
  var mcpCmd = new Command("mcp").configureHelp(helpStyle).description("Run an MCP server").summary("Run an MCP server");
9570
9816
  addDbOption(mcpCmd);
9817
+ mcpCmd.addOption(new Option("--caller-context <mode>", "where each call's directory comes from: this process, or an argument the host plugin must add (for a server shared by several directories)").choices(["process", "required"]).default("process"));
9571
9818
  var mcpHttpCmd = new Command("http").configureHelp(helpStyle).description("Run an MCP server over Streamable HTTP").option("--host <host>", "HTTP host").option("--port <port>", "HTTP port").option("--public-url <url>", "public MCP URL used in OAuth metadata").option("--unsafe-public", "allow non-loopback bind without auth");
9572
9819
  addDbOption(mcpHttpCmd);
9573
9820
  mcpHttpCmd.action(async () => {
@@ -9600,6 +9847,7 @@ mcpCmd.addCommand(mcpHttpCmd);
9600
9847
  var mcpCommand = mcpCmd.action(async (opts) => {
9601
9848
  const dbPath = resolveDbOpt(opts);
9602
9849
  if (dbPath) process.env.CODEMEM_DB = dbPath;
9850
+ if (mcpCmd.getOptionValueSource("callerContext") === "cli") process.env.CODEMEM_MCP_CALLER_CONTEXT = opts.callerContext;
9603
9851
  try {
9604
9852
  await import("@codemem/mcp/stdio");
9605
9853
  } catch (err) {
@@ -10809,6 +11057,27 @@ async function observeViewerRuntime(parsed, deps, defaultTarget = {
10809
11057
  };
10810
11058
  }
10811
11059
  //#endregion
11060
+ //#region src/commands/serve-coordinator-refresh.ts
11061
+ var VIEWER_REMOVAL_QUEUE_WAIT_TIMEOUT_MS = 5e3;
11062
+ /** Share one queue between foreground daemon work and each Viewer removal. */
11063
+ function createServeCoordinatorRefresh({ store, signal }, refresh = refreshCoordinatorForDaemon) {
11064
+ const lifecycle = createCoordinatorRefreshLifecycle();
11065
+ const refreshAfterRemoval = async () => {
11066
+ signal.throwIfAborted();
11067
+ if (!(await refresh(store.db, store.dbPath, process.env.CODEMEM_KEYS_DIR?.trim() || void 0)).refreshed) throw new Error("coordinator_refresh_unavailable");
11068
+ };
11069
+ return {
11070
+ daemon: { runCoordinatorRefresh: lifecycle.runRefresh },
11071
+ viewer: {
11072
+ createDeviceRemovalRefreshHooks: () => lifecycle.forRemoval(refreshAfterRemoval, { queueWaitTimeoutMs: VIEWER_REMOVAL_QUEUE_WAIT_TIMEOUT_MS }),
11073
+ runManualCoordinatorRefresh: (work) => lifecycle.runRefresh(() => {
11074
+ signal.throwIfAborted();
11075
+ return work();
11076
+ })
11077
+ }
11078
+ };
11079
+ }
11080
+ //#endregion
10812
11081
  //#region src/commands/serve-invocation.ts
10813
11082
  /**
10814
11083
  * Parse and validate a port string. Throws a user-friendly message (no stack trace)
@@ -11282,6 +11551,7 @@ function createServeCoordinatorMaintenanceDependencies(server) {
11282
11551
  advanceOperation: server.advanceProjectShareOperation
11283
11552
  }),
11284
11553
  reconcileConfiguredCoordinatorEnrollment: server.reconcileConfiguredCoordinatorEnrollment,
11554
+ convertLegacyPairingAssignments: server.convertLegacyPairingAssignmentsOperation,
11285
11555
  reconcileRecipientPolicyProjects: (store, options) => server.reconcileRecipientPolicyProjectsOperation(store, {
11286
11556
  ...options,
11287
11557
  effects: server.createRecipientPolicyReconcilerEffects(store)
@@ -11301,6 +11571,7 @@ async function runServeCoordinatorMaintenance(store, dependencies) {
11301
11571
  const projectShares = await dependencies.advancePendingProjectShares(store, { limit: 3 });
11302
11572
  const coordinatorEnrollment = await dependencies.reconcileConfiguredCoordinatorEnrollment(store);
11303
11573
  const enrollmentIssues = coordinatorEnrollment.issues ?? 0;
11574
+ const legacyPairingAssignments = await dependencies.convertLegacyPairingAssignments(store);
11304
11575
  const recipientPolicies = await dependencies.reconcileRecipientPolicyProjects(store, { limit: 3 });
11305
11576
  if (projectShares.failed > 0) throw new Error(`share operation maintenance failed for ${projectShares.failed} of ${projectShares.processed} operations`);
11306
11577
  if (coordinatorEnrollment.failedGroups > 0) throw new Error(coordinatorEnrollmentFailureMessage(coordinatorEnrollment));
@@ -11309,7 +11580,8 @@ async function runServeCoordinatorMaintenance(store, dependencies) {
11309
11580
  return {
11310
11581
  projectShares,
11311
11582
  coordinatorEnrollment,
11312
- recipientPolicies
11583
+ recipientPolicies,
11584
+ legacyPairingAssignments
11313
11585
  };
11314
11586
  }
11315
11587
  async function startBackgroundViewer(invocation) {
@@ -11534,6 +11806,7 @@ function startServeSyncDaemon(options) {
11534
11806
  host: syncConfig.syncHost,
11535
11807
  port: syncConfig.syncPort,
11536
11808
  signal,
11809
+ ...options.coordinatorRefresh,
11537
11810
  scanner: store.scanner,
11538
11811
  ...serveRelayDaemonOptions(relay, async () => {
11539
11812
  await runServeCoordinatorMaintenance(store, options.maintenance);
@@ -11552,6 +11825,11 @@ function startServeSyncDaemon(options) {
11552
11825
  }
11553
11826
  });
11554
11827
  }
11828
+ function scheduleServeSyncDaemon(options) {
11829
+ const delayMs = 3e3;
11830
+ p.log.step(`Sync daemon will start in background (${delayMs / 1e3}s delay)`);
11831
+ setTimeout(() => startServeSyncDaemon(options), delayMs).unref();
11832
+ }
11555
11833
  /**
11556
11834
  * Runs a memory tool for a thin host through the same in-process MCP handlers
11557
11835
  * as stdio and `codemem memory-tool`. Loaded lazily so viewer startup does not
@@ -11567,6 +11845,7 @@ function foregroundAppOptions(store, rawEventOptions, options) {
11567
11845
  storeFactory: () => store,
11568
11846
  syncReachability: options.relay?.reachability,
11569
11847
  ...rawEventOptions,
11848
+ ...options.coordinatorRefresh,
11570
11849
  getSyncRuntimeStatus: () => options.syncRuntimeStatus
11571
11850
  };
11572
11851
  }
@@ -11633,10 +11912,15 @@ async function startForegroundViewer(invocation) {
11633
11912
  phase: syncEnabled ? "starting" : "disabled",
11634
11913
  detail: syncEnabled ? "Waiting for viewer startup to finish" : "Sync is disabled"
11635
11914
  };
11915
+ const coordinatorRefresh = createServeCoordinatorRefresh({
11916
+ store,
11917
+ signal: syncAbort.signal
11918
+ });
11636
11919
  const appOpts = foregroundAppOptions(store, rawEventProcessing.appOptions, {
11637
11920
  accountLink,
11638
11921
  relay,
11639
- syncRuntimeStatus
11922
+ syncRuntimeStatus,
11923
+ coordinatorRefresh: coordinatorRefresh.viewer
11640
11924
  });
11641
11925
  const { app, setBoundAddress } = createBoundApp(createApp, appOpts, {
11642
11926
  invocation,
@@ -11673,21 +11957,16 @@ async function startForegroundViewer(invocation) {
11673
11957
  info
11674
11958
  });
11675
11959
  maintenanceWorker = startMaintenanceWorkerProcess(invocation);
11676
- if (syncEnabled) {
11677
- const syncStartDelayMs = 3e3;
11678
- p.log.step(`Sync daemon will start in background (${syncStartDelayMs / 1e3}s delay)`);
11679
- setTimeout(() => {
11680
- startServeSyncDaemon({
11681
- invocation,
11682
- syncConfig,
11683
- store,
11684
- signal: syncAbort.signal,
11685
- status: syncRuntimeStatus,
11686
- maintenance: coordinatorMaintenanceDependencies,
11687
- relay
11688
- });
11689
- }, syncStartDelayMs).unref();
11690
- }
11960
+ if (syncEnabled) scheduleServeSyncDaemon({
11961
+ invocation,
11962
+ syncConfig,
11963
+ store,
11964
+ signal: syncAbort.signal,
11965
+ status: syncRuntimeStatus,
11966
+ maintenance: coordinatorMaintenanceDependencies,
11967
+ relay,
11968
+ coordinatorRefresh: coordinatorRefresh.daemon
11969
+ });
11691
11970
  });
11692
11971
  server.on("error", (err) => {
11693
11972
  if (err.code === "EADDRINUSE") p.log.warn(`Viewer already running at http://${invocation.host}:${invocation.port}`);
@@ -12899,6 +13178,61 @@ function removeManagedOpencodeMcp(config, options) {
12899
13178
  if (cleanup.removed.length > 0) dropEmptyContainers(next, cleanup, options);
12900
13179
  return cleanup;
12901
13180
  }
13181
+ var POOLED_FLAGS = ["--caller-context", "required"];
13182
+ var POOLED_PROTOCOL = "2026-07-28";
13183
+ var POOLED_FIELDS = /* @__PURE__ */ new Set([
13184
+ "type",
13185
+ "command",
13186
+ "cwd",
13187
+ "protocol",
13188
+ "pool"
13189
+ ]);
13190
+ /**
13191
+ * The entry `--opencode-mcp pooled` writes: one server process that every
13192
+ * project directory shares. OpenCode shares a process only between identical
13193
+ * entries, so the working directory is fixed rather than per project.
13194
+ */
13195
+ function buildOpencodePooledMcpEntry(launcher, cwd) {
13196
+ return {
13197
+ type: "local",
13198
+ command: [
13199
+ launcher.command,
13200
+ ...launcher.args,
13201
+ ...POOLED_FLAGS
13202
+ ],
13203
+ cwd,
13204
+ protocol: POOLED_PROTOCOL,
13205
+ pool: true
13206
+ };
13207
+ }
13208
+ /**
13209
+ * True for an entry `--opencode-mcp pooled` wrote and the user has not
13210
+ * customized. `cwd` is the directory setup writes; any other working directory
13211
+ * is the user's choice and makes the entry theirs.
13212
+ */
13213
+ function isManagedPooledOpencodeMcpEntry(entry, cwd) {
13214
+ if (!isRecord(entry) || entry.type !== "local" || entry.pool !== true) return false;
13215
+ if (entry.protocol !== POOLED_PROTOCOL || entry.cwd !== cwd) return false;
13216
+ if (Object.keys(entry).some((key) => !POOLED_FIELDS.has(key))) return false;
13217
+ const command = entry.command;
13218
+ if (!Array.isArray(command) || command.length <= POOLED_FLAGS.length) return false;
13219
+ const launcher = command.slice(0, -POOLED_FLAGS.length);
13220
+ return isExactStringArray$1(command.slice(-POOLED_FLAGS.length), POOLED_FLAGS) && isManagedOpencodeMcpCommand(launcher);
13221
+ }
13222
+ function isServerEntry(value) {
13223
+ return isRecord(value) && ("type" in value || "command" in value || "url" in value);
13224
+ }
13225
+ /**
13226
+ * Names of servers defined directly under `mcp`, the OpenCode 1 layout. A
13227
+ * pooled entry needs `mcp.servers`, which that layout would read as a server
13228
+ * named "servers". OpenCode 2 settings that sit beside `mcp.servers`, such as
13229
+ * `mcp.timeout`, are not servers.
13230
+ */
13231
+ function listV1OpencodeMcpServers(config) {
13232
+ const mcp = config.mcp;
13233
+ if (!isRecord(mcp)) return [];
13234
+ return Object.keys(mcp).filter((name) => isServerEntry(mcp[name]));
13235
+ }
12902
13236
  /** The stdio entry `--opencode-mcp stdio` writes, in the file's config shape. */
12903
13237
  function buildOpencodeStdioMcpEntry(shape, launcher) {
12904
13238
  const command = [launcher.command, ...launcher.args];
@@ -13080,6 +13414,7 @@ function installStdioMcp(force, { createBackup = true } = {}) {
13080
13414
  const configPath = resolveOpencodeConfigPath(opencodeConfigDir());
13081
13415
  const config = loadOpencodeConfigOrLog(configPath);
13082
13416
  if (config == null) return false;
13417
+ for (const { container } of locateOpencodeMcpEntries(config)) if (isManagedPooledOpencodeMcpEntry(container.codemem, opencodeConfigDir())) delete container.codemem;
13083
13418
  const migrated = migrateLegacyOpencodeMcp(config);
13084
13419
  if (locateOpencodeMcpEntries(config).length > 0 && !force && !migrated) {
13085
13420
  p.log.info(`MCP entry already exists in ${configPath}`);
@@ -13098,6 +13433,51 @@ function installStdioMcp(force, { createBackup = true } = {}) {
13098
13433
  }
13099
13434
  return true;
13100
13435
  }
13436
+ /** Why the pooled entry cannot replace what the config holds, or null when it can. */
13437
+ function pooledMcpBlocker(config, force) {
13438
+ const otherV1Servers = listV1OpencodeMcpServers(config).filter((name) => name !== "codemem");
13439
+ if (otherV1Servers.length > 0) return `it defines MCP servers directly under "mcp" (${otherV1Servers.join(", ")}), the OpenCode 1 layout. A shared server needs OpenCode 2's "mcp.servers"`;
13440
+ if (force) return null;
13441
+ for (const { container, label } of locateOpencodeMcpEntries(config)) {
13442
+ const entry = container.codemem;
13443
+ if (isManagedPooledOpencodeMcpEntry(entry, opencodeConfigDir())) continue;
13444
+ const reason = describeUnmanagedOpencodeMcpEntry(entry);
13445
+ if (reason != null) return `${label} is customized (${reason}). Use --force to replace it`;
13446
+ }
13447
+ return null;
13448
+ }
13449
+ /** `--opencode-mcp pooled`: one codemem MCP process shared by every project directory. */
13450
+ function installPooledMcp(force, { createBackup = true } = {}) {
13451
+ const configPath = resolveOpencodeConfigPath(opencodeConfigDir());
13452
+ const config = loadOpencodeConfigOrLog(configPath);
13453
+ if (config == null) return false;
13454
+ const blocker = pooledMcpBlocker(config, force);
13455
+ if (blocker != null) {
13456
+ p.log.error(`Did not write a shared MCP entry to ${configPath} because ${blocker}.`);
13457
+ return false;
13458
+ }
13459
+ const entry = buildOpencodePooledMcpEntry(codememMcpLauncher(), opencodeConfigDir());
13460
+ const existing = locateOpencodeMcpEntries(config);
13461
+ if (existing.length === 1 && existing[0]?.shape === "v2" && JSON.stringify(existing[0].container.codemem) === JSON.stringify(entry)) {
13462
+ p.log.info(`Shared MCP entry already exists in ${configPath}`);
13463
+ return true;
13464
+ }
13465
+ for (const { container } of existing) delete container.codemem;
13466
+ const mcp = config.mcp ?? {};
13467
+ config.mcp = mcp;
13468
+ const servers = mcp.servers ?? {};
13469
+ mcp.servers = servers;
13470
+ servers.codemem = entry;
13471
+ try {
13472
+ writeJsonConfig(configPath, config, { createBackup });
13473
+ } catch (err) {
13474
+ p.log.error(`Failed to write ${configPath}: ${err instanceof Error ? err.message : String(err)}`);
13475
+ return false;
13476
+ }
13477
+ p.log.success(`Shared MCP entry installed: ${configPath}`);
13478
+ p.log.info("OpenCode 2.2.6 or later starts one codemem MCP process for all projects. Each project must load the codemem plugin. Run setup with --opencode-mcp stdio to return to one process per project.");
13479
+ return true;
13480
+ }
13101
13481
  function reportKeptOpencodeMcpEntries(configPath, kept) {
13102
13482
  for (const { label, reason } of kept) p.log.warn(`Left the codemem MCP entry ${label} in ${configPath} because ${reason}. The plugin now provides memory tools, so remove that entry unless you still need it.`);
13103
13483
  }
@@ -13829,7 +14209,7 @@ function installPi(options = {}) {
13829
14209
  }
13830
14210
  return ok;
13831
14211
  }
13832
- var OPENCODE_MCP_MODES = ["stdio"];
14212
+ var OPENCODE_MCP_MODES = ["stdio", "pooled"];
13833
14213
  var DEFAULT_OPENCODE_MCP_MODE = "stdio";
13834
14214
  function maybeInstallPi(opts, onlyFlag, force) {
13835
14215
  if (!(opts.piOnly || !onlyFlag && isPiDetected())) return true;
@@ -13845,11 +14225,13 @@ function installOpencodeSetup(force, opencodeMcp) {
13845
14225
  const pluginResult = installPlugin(force);
13846
14226
  if (!pluginResult.ok) return false;
13847
14227
  const createBackup = !pluginResult.wrote;
13848
- if ((opencodeMcp ?? DEFAULT_OPENCODE_MCP_MODE) === "native") {
14228
+ const mode = opencodeMcp ?? DEFAULT_OPENCODE_MCP_MODE;
14229
+ if (mode === "native") {
13849
14230
  p.log.step("Checking OpenCode MCP config...");
13850
14231
  return removeOpencodeMcp({ createBackup });
13851
14232
  }
13852
14233
  p.log.step("Installing OpenCode MCP config...");
14234
+ if (mode === "pooled") return installPooledMcp(force, { createBackup });
13853
14235
  return installStdioMcp(force, { createBackup });
13854
14236
  }
13855
14237
  function installClaudeSetup(force) {
@@ -13890,7 +14272,7 @@ function runSetup(opts) {
13890
14272
  p.outro("Setup completed with warnings");
13891
14273
  process.exitCode = 1;
13892
14274
  }
13893
- var setupCommand = new Command("setup").configureHelp(helpStyle).description("Install agent integrations").option("--force", "overwrite existing installations").option("--opencode-only", "only install for OpenCode").option("--claude-only", "only install for Claude Code").option("--codex-only", "only install for Codex").option("--pi-only", "only install for pi").option("--opencode-mcp <mode>", "OpenCode MCP transport (stdio only)").option("--pi-mcp", "install the Pi MCP adapter (requires pi-mcp-adapter)").option("--pi-extension-path <path>", "use a local Pi extension directory instead of the published package").action((opts) => {
14275
+ var setupCommand = new Command("setup").configureHelp(helpStyle).description("Install agent integrations").option("--force", "overwrite existing installations").option("--opencode-only", "only install for OpenCode").option("--claude-only", "only install for Claude Code").option("--codex-only", "only install for Codex").option("--pi-only", "only install for pi").option("--opencode-mcp <mode>", "OpenCode MCP server: stdio (one process per project, default) or pooled (one shared process, OpenCode 2.2.6+)").option("--pi-mcp", "install the Pi MCP adapter (requires pi-mcp-adapter)").option("--pi-extension-path <path>", "use a local Pi extension directory instead of the published package").action((opts) => {
13894
14276
  runSetup(opts);
13895
14277
  });
13896
14278
  //#endregion
@@ -13933,6 +14315,107 @@ function collectAdvertiseAddresses(explicitAddress, configuredHost, port, interf
13933
14315
  return [...new Set(addresses)];
13934
14316
  }
13935
14317
  //#endregion
14318
+ //#region src/commands/sync-rejoin.ts
14319
+ function readProfile(options) {
14320
+ const config = options.config ? readCodememConfigFileAtPath(options.config) : readCodememConfigFile();
14321
+ const coordinatorUrl = normalizeCoordinatorAccountLinkOrigin(readCoordinatorSyncConfig(config).syncCoordinatorUrl);
14322
+ if (!coordinatorUrl) return null;
14323
+ const dbPath = resolveDbPath(resolveDbOpt(options));
14324
+ const before = statSync(dbPath, { bigint: true });
14325
+ const device = readAccountLinkDevice(dbPath);
14326
+ const after = statSync(dbPath, { bigint: true });
14327
+ const override = process.env.CODEMEM_DEVICE_ID?.trim();
14328
+ if (!before.isFile() || before.dev !== after.dev || before.ino !== after.ino || override && override !== device.deviceId) return null;
14329
+ return {
14330
+ coordinatorUrl,
14331
+ dbPath,
14332
+ keysDir: process.env.CODEMEM_KEYS_DIR?.trim() || void 0,
14333
+ deviceId: device.deviceId,
14334
+ fingerprint: device.fingerprint,
14335
+ file: {
14336
+ dev: after.dev.toString(),
14337
+ ino: after.ino.toString()
14338
+ }
14339
+ };
14340
+ }
14341
+ function currentProfileMatches(options, expected) {
14342
+ try {
14343
+ return JSON.stringify(readProfile(options)) === expected;
14344
+ } catch {
14345
+ return false;
14346
+ }
14347
+ }
14348
+ var REFUSAL_TEXT = {
14349
+ unavailable: "The coordinator could not start or finish rejoin for this device. Check that it supports device rejoin and that this device has an account link.",
14350
+ removal_changed: "The device’s removal or access changed. Start rejoin again.",
14351
+ account_not_linked: "This Google account has no live link for rejoin.",
14352
+ wrong_account: "Sign in with the Google account linked to this device’s Identity.",
14353
+ no_destination: "This device cannot rejoin any of its former groups.",
14354
+ removal_conflict: "This device has removal records for different keys. Ask the coordinator operator to review them.",
14355
+ blocked: "This device is blocked and cannot rejoin.",
14356
+ daily_limit: "This Identity reached its rejoin limit for the last 24 hours.",
14357
+ retry: "The coordinator could not confirm the request. Start again from this terminal."
14358
+ };
14359
+ var FAILURE_TEXT = {
14360
+ device_unavailable: "Codemem could not read the existing device key. Check the local database and key settings.",
14361
+ start_unconfirmed: "The coordinator did not confirm the start. Check its connection and rejoin support.",
14362
+ browser_stopped: "The browser sign-in did not finish. Start again from this terminal.",
14363
+ review_unavailable: "Codemem could not verify the browser review. No finalize request was sent."
14364
+ };
14365
+ function resultText(result) {
14366
+ if (result.kind === "refused") return REFUSAL_TEXT[result.reason];
14367
+ if (result.kind === "failed") return FAILURE_TEXT[result.error];
14368
+ return "Codemem could not confirm whether this device rejoined. Check sync status before starting again.";
14369
+ }
14370
+ async function rejoin(options) {
14371
+ if (options.json) {
14372
+ emitJsonError("interactive_flow_only", "Device rejoin requires a private browser link. Run without --json.", 2);
14373
+ return;
14374
+ }
14375
+ if (!process.stderr.isTTY) {
14376
+ p.log.error("Run device rejoin in a terminal and keep the browser link private.", { output: process.stderr });
14377
+ process.exitCode = 2;
14378
+ return;
14379
+ }
14380
+ const controller = new AbortController();
14381
+ const stop = () => controller.abort();
14382
+ process.once("SIGINT", stop);
14383
+ process.once("SIGTERM", stop);
14384
+ try {
14385
+ const profile = readProfile(options);
14386
+ if (!profile) throw new Error("Device profile unavailable");
14387
+ const snapshot = JSON.stringify(profile);
14388
+ const result = await runDeviceRejoin({
14389
+ ...profile,
14390
+ signal: controller.signal,
14391
+ assertCurrentContext: () => currentProfileMatches(options, snapshot),
14392
+ openBrowser: (url) => {
14393
+ p.log.warn("Keep this link private. Open it in a browser on this device.", { output: process.stderr });
14394
+ p.log.message(url, { output: process.stderr });
14395
+ }
14396
+ });
14397
+ if (result.kind === "finalized") {
14398
+ p.log.success("This device rejoined. Codemem will refresh its sync status on the next coordinator check.", { output: process.stderr });
14399
+ return;
14400
+ }
14401
+ p.log.error(resultText(result), { output: process.stderr });
14402
+ process.exitCode = 1;
14403
+ } catch {
14404
+ p.log.error("Device rejoin is unavailable. Check the existing device key and coordinator settings.", { output: process.stderr });
14405
+ process.exitCode = 1;
14406
+ } finally {
14407
+ process.removeListener("SIGINT", stop);
14408
+ process.removeListener("SIGTERM", stop);
14409
+ }
14410
+ }
14411
+ function buildSyncRejoinCommand() {
14412
+ const command = new Command("rejoin").configureHelp(helpStyle).description("Sign in to rejoin this removed device");
14413
+ addConfigOption(command);
14414
+ addDbOption(command);
14415
+ addJsonOption(command);
14416
+ return command.action(rejoin);
14417
+ }
14418
+ //#endregion
13936
14419
  //#region src/commands/sync-relay-keys.ts
13937
14420
  /**
13938
14421
  * `codemem sync relay-keys` lists relay service key pins, and `codemem sync approve-relay-key` approves a changed key.
@@ -14311,10 +14794,46 @@ onceCmd.action(async (opts) => {
14311
14794
  }
14312
14795
  });
14313
14796
  syncCommand.addCommand(onceCmd);
14797
+ var PAIR_FILTERS_REFUSED = "These filters would send this pairing Projects it does not receive now. Only an administrator's device can do that. This device can send less. Nothing was changed.";
14798
+ /** The filters the pair flags ask for, or null when no filter flag was given. */
14799
+ function pairFilterChange(opts) {
14800
+ if (opts.default) return {
14801
+ include: null,
14802
+ exclude: null
14803
+ };
14804
+ if (opts.all) return {
14805
+ include: [],
14806
+ exclude: []
14807
+ };
14808
+ if (!opts.include && !opts.exclude) return null;
14809
+ return {
14810
+ include: parseProjectList(opts.include),
14811
+ exclude: parseProjectList(opts.exclude)
14812
+ };
14813
+ }
14814
+ /** What the running `sync pair` asked for. Set before its handler runs and cleared after it. */
14815
+ var pairRun = null;
14816
+ function beginPairRun(opts) {
14817
+ pairRun = pairFilterChange(opts);
14818
+ }
14819
+ /** Stores an accepted pairing, unless its filter flags would widen on a device that may not. */
14820
+ function updatePeerAddresses$1(...args) {
14821
+ const [db, peerDeviceId] = args;
14822
+ if (pairRun !== null && !readPeerProjectFilterAuthority(db) && !peerProjectFilterChangeOnlyNarrows(db, peerDeviceId, pairRun)) throw new Error(PAIR_FILTERS_REFUSED);
14823
+ updatePeerAddresses(...args);
14824
+ }
14825
+ /** The filter write of an accepted pairing rechecks authority inside the transaction. */
14826
+ function setPeerProjectFilter(db, peerDeviceId, lists) {
14827
+ if (setPeerProjectFilterChecked(db, peerDeviceId, lists) !== "saved") throw new Error(PAIR_FILTERS_REFUSED);
14828
+ }
14314
14829
  var pairCmd = new Command("pair").configureHelp(helpStyle).description("Create or accept a device pairing request").option("--accept <json>", "accept pairing payload JSON from another device").option("--accept-file <path>", "accept pairing payload from file path, or '-' for stdin").option("--payload-only", "when generating pairing payload, print JSON only").option("--name <name>", "label for the peer").option("--address <host:port>", "override peer address (host:port)").option("--include <projects>", "outbound-only allowlist for accepted peer").option("--exclude <projects>", "outbound-only blocklist for accepted peer").option("--all", "with --accept, push all projects to that peer").option("--default", "with --accept, use default/global push filters");
14315
14830
  addDbOption(pairCmd);
14316
14831
  addConfigOption(pairCmd);
14317
14832
  addJsonOption(pairCmd);
14833
+ pairCmd.hook("preAction", (_command, action) => beginPairRun(action.opts()));
14834
+ pairCmd.hook("postAction", () => {
14835
+ pairRun = null;
14836
+ });
14318
14837
  pairCmd.action(async (opts) => {
14319
14838
  const store = new MemoryStore(resolveDbPath(resolveDbOpt(opts)));
14320
14839
  try {
@@ -14443,7 +14962,7 @@ pairCmd.action(async (opts) => {
14443
14962
  process.exitCode = 1;
14444
14963
  return;
14445
14964
  }
14446
- updatePeerAddresses(store.db, deviceId, resolvedAddresses, {
14965
+ updatePeerAddresses$1(store.db, deviceId, resolvedAddresses, {
14447
14966
  name: opts.name,
14448
14967
  pinnedFingerprint: fingerprint,
14449
14968
  publicKey,
@@ -14770,14 +15289,50 @@ peersCommand.action((opts) => {
14770
15289
  store.close();
14771
15290
  }
14772
15291
  });
14773
- var peersRemoveCmd = new Command("remove").configureHelp(helpStyle).description("Remove a sync peer by device id or exact name").argument("<peer>", "peer device id or exact name");
14774
- addDbOption(peersRemoveCmd);
14775
- addJsonOption(peersRemoveCmd);
14776
- peersRemoveCmd.action((peerRef, opts) => {
15292
+ /** What the user is told after a removal, the access sentence first when the binding was kept. */
15293
+ function peerRemovalNotices(label, binding) {
15294
+ const pairingNotice = [`Other devices still sync with ${label} until they remove it too.`, `If the coordinator still lists ${label}, this device pairs with it again at the next refresh.`].join(" ");
15295
+ if (binding === "ended") return [pairingNotice];
15296
+ return [`${label} was not removed from Projects. An administrator's device can remove it.`, pairingNotice];
15297
+ }
15298
+ function reportPeerRemoved(match, result, options) {
15299
+ const label = match.name || match.peer_device_id;
15300
+ const { binding, removed } = result;
15301
+ const notices = peerRemovalNotices(label, binding);
15302
+ if (options.json) {
15303
+ const payload = {
15304
+ ok: true,
15305
+ peer_device_id: match.peer_device_id,
15306
+ name: match.name,
15307
+ removed: {
15308
+ sync_peers: removed.syncPeers,
15309
+ replication_cursors: removed.replicationCursors,
15310
+ replication_cursors_v2: removed.replicationCursorsV2,
15311
+ sync_channel_progress: removed.syncChannelProgress,
15312
+ identity_devices: removed.identityDevices
15313
+ },
15314
+ binding,
15315
+ ...binding === "kept" ? { remove_from_projects: "needs_admin_device" } : {},
15316
+ notice: notices.join(" ")
15317
+ };
15318
+ console.log(JSON.stringify(payload, null, 2));
15319
+ return;
15320
+ }
15321
+ p.intro("codemem sync peers remove");
15322
+ p.log.success(binding === "kept" ? `Disconnected this device from ${label}` : `Removed peer ${label}`);
15323
+ const progressRows = removed.replicationCursors + removed.replicationCursorsV2 + removed.syncChannelProgress;
15324
+ p.log.message([
15325
+ ` pairing: ${removed.syncPeers}`,
15326
+ ` sync progress rows: ${progressRows}`,
15327
+ ` Identity bindings ended: ${removed.identityDevices}`
15328
+ ].join("\n"));
15329
+ for (const notice of notices) p.log.warn(notice);
15330
+ p.outro(match.peer_device_id);
15331
+ }
15332
+ async function removeSyncPeer(peerRef, opts, dependencies = {}) {
14777
15333
  const store = new MemoryStore(resolveDbPath(resolveDbOpt(opts)));
14778
15334
  try {
14779
- const d = drizzle(store.db, { schema });
14780
- const match = resolvePeerMatch(d, peerRef);
15335
+ const match = resolvePeerMatch(drizzle(store.db, { schema }), peerRef);
14781
15336
  if (match === "ambiguous") {
14782
15337
  if (opts.json) {
14783
15338
  emitJsonError("ambiguous_peer", `Peer name is ambiguous: ${peerRef.trim()}`);
@@ -14796,24 +15351,33 @@ peersRemoveCmd.action((peerRef, opts) => {
14796
15351
  process.exitCode = 1;
14797
15352
  return;
14798
15353
  }
14799
- d.delete(schema.replicationCursors).where(eq(schema.replicationCursors.peer_device_id, match.peer_device_id)).run();
14800
- d.delete(schema.syncPeers).where(eq(schema.syncPeers.peer_device_id, match.peer_device_id)).run();
14801
- const payload = {
14802
- ok: true,
14803
- peer_device_id: match.peer_device_id,
14804
- name: match.name
14805
- };
14806
- if (opts.json) {
14807
- console.log(JSON.stringify(payload, null, 2));
15354
+ const label = match.name || match.peer_device_id;
15355
+ let result;
15356
+ try {
15357
+ result = await removePeerFromThisDevice(store.db, {
15358
+ localDeviceId: store.deviceId,
15359
+ peerDeviceId: match.peer_device_id,
15360
+ lookupCoordinatorAnswer: dependencies.lookupCoordinatorAnswer
15361
+ });
15362
+ } catch {
15363
+ const message = `Could not remove peer ${label}. Nothing was changed.`;
15364
+ if (opts.json) {
15365
+ emitJsonError("peer_remove_failed", message);
15366
+ return;
15367
+ }
15368
+ p.log.error(message);
15369
+ process.exitCode = 1;
14808
15370
  return;
14809
15371
  }
14810
- p.intro("codemem sync peers remove");
14811
- p.log.success(`Removed peer ${match.name || match.peer_device_id}`);
14812
- p.outro(match.peer_device_id);
15372
+ reportPeerRemoved(match, result, { json: opts.json === true });
14813
15373
  } finally {
14814
15374
  store.close();
14815
15375
  }
14816
- });
15376
+ }
15377
+ var peersRemoveCmd = new Command("remove").configureHelp(helpStyle).description("Remove a sync peer by device id or exact name").argument("<peer>", "peer device id or exact name");
15378
+ addDbOption(peersRemoveCmd);
15379
+ addJsonOption(peersRemoveCmd);
15380
+ peersRemoveCmd.action((peerRef, opts) => removeSyncPeer(peerRef, opts));
14817
15381
  peersCommand.addCommand(peersRemoveCmd);
14818
15382
  syncCommand.addCommand(peersCommand);
14819
15383
  syncCommand.addCommand(relayKeysCommand);
@@ -14984,12 +15548,31 @@ bootstrapCmd.action(async (peerArg, opts) => {
14984
15548
  }
14985
15549
  });
14986
15550
  syncCommand.addCommand(bootstrapCmd);
15551
+ function targetsRuntimeConfig(path) {
15552
+ if (!path) return true;
15553
+ const runtime = getCodememConfigPath();
15554
+ return existsSync(runtime) && realpathSync(runtime) === realpathSync(expandUserPath(path));
15555
+ }
15556
+ function rememberCoordinatorBeforeDisconnect(config, opts) {
15557
+ const previousUrl = config.sync_coordinator_url;
15558
+ if (typeof previousUrl !== "string" || !previousUrl.trim()) return;
15559
+ if (!targetsRuntimeConfig(opts.config)) return;
15560
+ const store = new MemoryStore(resolveDbPath(resolveDbOpt(opts)));
15561
+ try {
15562
+ rememberPeerProjectFilterManagement(store.db);
15563
+ } finally {
15564
+ store.close();
15565
+ }
15566
+ }
14987
15567
  var connectCmd = new Command("connect").configureHelp(helpStyle).description("Set the coordinator URL for sync").argument("<url>", "coordinator URL (e.g. https://coordinator.example.com)").option("--group <group>", "sync group ID");
14988
15568
  addConfigOption(connectCmd);
15569
+ addDbOption(connectCmd);
14989
15570
  connectCmd.action((url, opts) => {
15571
+ const nextUrl = url.trim();
14990
15572
  try {
14991
15573
  mutateCliConfig((config) => {
14992
- config.sync_coordinator_url = url.trim();
15574
+ if (!nextUrl) rememberCoordinatorBeforeDisconnect(config, opts);
15575
+ config.sync_coordinator_url = nextUrl;
14993
15576
  if (opts.group) config.sync_coordinator_group = opts.group.trim();
14994
15577
  return config;
14995
15578
  }, opts.config);
@@ -15000,11 +15583,12 @@ connectCmd.action((url, opts) => {
15000
15583
  return;
15001
15584
  }
15002
15585
  p.intro("codemem sync connect");
15003
- p.log.success(`Coordinator: ${url.trim()}`);
15586
+ p.log.success(`Coordinator: ${nextUrl}`);
15004
15587
  if (opts.group) p.log.info(`Group: ${opts.group.trim()}`);
15005
15588
  p.outro("Restart `codemem serve` to activate coordinator sync");
15006
15589
  });
15007
15590
  syncCommand.addCommand(connectCmd);
15591
+ syncCommand.addCommand(buildSyncRejoinCommand());
15008
15592
  var syncCoordinatorAlias = buildCoordinatorCommand();
15009
15593
  syncCoordinatorAlias.hook("preAction", (_thisCmd, actionCmd) => {
15010
15594
  if (actionCmd.optsWithGlobals().json) return;