codemem 0.50.0-beta.3 → 0.50.0-beta.5
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 +1512 -702
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
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_LEDGER_RETENTION_BATCH_SIZE, 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, LedgerRetentionRunner, MUTATING_TOOL_NAMES, MemoryStore, NON_SELECTED_EXPOSURE_RETENTION_DAYS, 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, SyncAttemptRetentionRunner, 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,
|
|
2
|
+
import { ACCOUNT_CONNECTION_MIGRATION_STATEMENTS, ACCOUNT_UNLINK_MIGRATION_STATEMENTS, ALLOWED_MEMORY_KINDS, AUTH_LINK_AUTHORITY_CUTOVER_SQL, BetterSqliteCoordinatorStore, COORDINATOR_FREE_BINDING_UNVERIFIED, COORDINATOR_FREE_WITNESS_UNAVAILABLE, COORDINATOR_JOIN_CONFIRMATION_REQUIRED, ContextOnlyReplayError, CoordinatorAccountLinkError, DEDUP_KEY_BACKFILL_JOB, DEFAULT_COORDINATOR_DB_PATH, DEFAULT_LEDGER_RETENTION_BATCH_SIZE, DEFAULT_RAW_EVENT_FLUSH_MAX_EVENTS, DedupKeyBackfillRunner, DeviceIdentityError, EXTRACTION_BENCHMARK_QUALITY_WEIGHTS, FILE_CONTEXT_TRANSPORT_MAX_BYTES, FILE_CONTEXT_TRANSPORT_PROFILE, INVITE_TOKEN_LOOKUP_VERSION, InviteTokenRefusal, LEGACY_OWNER_RESOLUTION_SCHEMA_STATEMENTS, LedgerRetentionRunner, MUTATING_TOOL_NAMES, MemoryStore, NON_SELECTED_EXPOSURE_RETENTION_DAYS, ObserverClient, ObserverOutputError, ObserverOutputTransportError, OwnerProfileEnrollmentError, PROMPT_TRANSPORT_PROTOCOL_RANGE, REF_BACKFILL_JOB, RawEventIngestValidationError, RawEventSweeper, RefBackfillRunner, RemoteCoordinatorRequestError, ReplicationBackfillRunner, SCOPE_BACKFILL_JOB, SESSION_CONTEXT_BACKFILL_JOB, SUMMARY_DEDUP_BACKFILL_JOB, ScopeBackfillRunner, SessionContextBackfillRunner, SessionRepositoryIdentityRunner, SummaryDedupBackfillRunner, SyncAttemptRetentionRunner, SyncRetentionRunner, TRUSTED_HOOK_MAPPER_OPTIONS, VERSION, VectorModelMigrationRunner, ViewerWriterLockHeldError, ViewerWriterLockUnavailableError, acquireViewerWriterLock, aiBackfillStructuredContent, applyBootstrapSnapshot, applyDistillRule, arePromptTransportProtocolRangesCompatible, atomicReplaceConfigFile, backfillMemoryDedupKeys, backfillNarrativeFromBody, backfillTagsText, backfillVectors, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildPairingPayload, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildTieredObserverSelection, buildViewerIdentityTarget, canonicalViewerDbPath, classifyPromptTransportFailure, clonePromptPackAttempt, collectOperationalStatus, compareMemoryRoleReports, connect, connectReadOnly, coordinatorAuthControllerReviewAction, coordinatorAuthStageBaselineSql, coordinatorCreateGroupAction, coordinatorCreateScopeAction, coordinatorD1ApplyOnlyMigrations, 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, isViewerWriterLockHeld, judgeDistillReport, legacyTeamCandidateId, linkCoordinatorAccount, linkCoordinatorAccountHeadless, listMaintenanceJobs, listPerPeerScopeSyncState, listRetentionScopeIds, loadObserverConfig, loadPublicKey, loadRuntimeSigningPublicKey, loadSqliteVec, mdnsEnabled, mutateCodememConfigFile, normalizeCoordinatorAccountLinkOrigin, normalizePromptTransportProtocolRange, observerBaseUrlForProviderOverride, parseControllerHistoryEvidence, parseFileContextTransportRequest, peerProjectFilterChangeOnlyNarrows, peerTransportBlocker, peerTransportExecutor, planReplicationOpsAgePrune, probeCodememViewerLiveness, probeCodememViewerLiveness as probeCodememViewerLiveness$1, probeRequiredNativeRuntime, processStartIdentity, projectMatchesFilter, promptPackArtifactFingerprint, pruneReplicationOpsUntilCaughtUp, rawEventsGate, readAccountLinkDevice, readCodememConfigFile, readCodememConfigFileAtPath, readCodememConfigFileForMutation, readCoordinatorAccountLinkStatus, readCoordinatorOwnerReviewLocalEvidence, readCoordinatorSyncConfig, readDeviceStorageShape, readImportPayload, readLocalProjectMigrationReport, readPeerProjectFilterAuthority, readViewerPidFile, readViewerWriterLockOwner, recordAutomaticRecall, recordConfiguredCoordinatorHistory, recordPairingTransportEvidence, recordPromptPackArtifacts, recordPromptPackTerminal, refreshCoordinatorForDaemon, rememberPeerProjectFilterManagement, removePeerFromThisDevice, renderUnifiedDiff, replayBatchExtraction, replayBatchExtractionWithTierRouting, resolveCodememConfigPath, resolveComparablePath, resolveDbPath, resolveHookProject, resolveKeyPaths, resolvePiAgentDir, resolvePiObserverConfig, resolveProject, resolveProjectRoot, retrievalLedgerStats, retryRawEventFailures, runDeviceRejoin, runLedgerRetentionPass, runSyncDaemon, runSyncPass, sanitizeHookPayload, scanSecretsRetroactive, schema, scoreExtractionBenchmarkOutput, searchPiSessions, setPeerProjectFilterChecked, syncPassPreflight, tryUpdateRetrievalDelivery, updatePeerAddresses, upgradeCoordinatorAccountSchemaFile, upgradeCoordinatorAuthSchemaFile, upgradeCoordinatorOwnerResolutionSchemaFile, vacuumDatabase, viewerPidFilePaths, viewerRuntimeDir, viewerUrl, viewerUrl as viewerUrl$1, 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";
|
|
6
6
|
import { homedir, networkInterfaces } from "node:os";
|
|
7
|
-
import { dirname, isAbsolute, join, posix, relative, resolve, sep, win32 } from "node:path";
|
|
7
|
+
import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep, win32 } from "node:path";
|
|
8
8
|
import { isDeepStrictEqual, styleText } from "node:util";
|
|
9
9
|
import { createHash, randomInt, randomUUID } from "node:crypto";
|
|
10
10
|
import { isUtf8 } from "node:buffer";
|
|
@@ -1816,14 +1816,14 @@ async function nativeDeliveryAcknowledgement(deliver, serialized) {
|
|
|
1816
1816
|
}
|
|
1817
1817
|
function assertNativeRecoverySnapshot(snapshot) {
|
|
1818
1818
|
const { dir, dirFd, path, fd, details, serialized, lock } = snapshot;
|
|
1819
|
-
if (!sameInode(requireSafeSpoolDirectory(dir), fstatSync(dirFd))) fail$
|
|
1819
|
+
if (!sameInode(requireSafeSpoolDirectory(dir), fstatSync(dirFd))) fail$3("unsafe_directory");
|
|
1820
1820
|
assertLock(lock);
|
|
1821
1821
|
for (const current of [fstatSync(fd), lstatSync(path)]) {
|
|
1822
1822
|
requireFile(current);
|
|
1823
|
-
if (!sameSnapshot(details, current)) fail$
|
|
1823
|
+
if (!sameSnapshot(details, current)) fail$3("changed_during_read");
|
|
1824
1824
|
}
|
|
1825
|
-
if (!readLimited(fd, 16777216)?.equals(Buffer.from(serialized, "utf8")) || !sameSnapshot(details, fstatSync(fd)) || !sameSnapshot(details, lstatSync(path))) fail$
|
|
1826
|
-
if (!sameInode(requireSafeSpoolDirectory(dir), fstatSync(dirFd))) fail$
|
|
1825
|
+
if (!readLimited(fd, 16777216)?.equals(Buffer.from(serialized, "utf8")) || !sameSnapshot(details, fstatSync(fd)) || !sameSnapshot(details, lstatSync(path))) fail$3("changed_during_read");
|
|
1826
|
+
if (!sameInode(requireSafeSpoolDirectory(dir), fstatSync(dirFd))) fail$3("unsafe_directory");
|
|
1827
1827
|
assertLock(lock);
|
|
1828
1828
|
}
|
|
1829
1829
|
function finishNativeRecovery(snapshot, keepReceipt) {
|
|
@@ -1884,11 +1884,11 @@ async function recoverNativeHookReceipt({ provider, receipt, deliver, keepReceip
|
|
|
1884
1884
|
let result;
|
|
1885
1885
|
try {
|
|
1886
1886
|
const metadata = parseReceipt(receipt);
|
|
1887
|
-
if (typeof deliver !== "function") fail$
|
|
1887
|
+
if (typeof deliver !== "function") fail$3("invalid_delivery");
|
|
1888
1888
|
const dir = providerDirectory(provider);
|
|
1889
1889
|
const directory = requireSafeSpoolDirectory(dir);
|
|
1890
1890
|
dirFd = openSync(dir, flags | (constants.O_DIRECTORY ?? 0));
|
|
1891
|
-
if (!sameInode(directory, fstatSync(dirFd))) fail$
|
|
1891
|
+
if (!sameInode(directory, fstatSync(dirFd))) fail$3("unsafe_directory");
|
|
1892
1892
|
lock = acquireLock(dir, receipt.slice(`rejected-${metadata.status}-${metadata.reason}-`.length, -9), dirFd);
|
|
1893
1893
|
result = await deliverNativeRecovery({
|
|
1894
1894
|
dir,
|
|
@@ -1914,7 +1914,7 @@ function inspectionError(code) {
|
|
|
1914
1914
|
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.";
|
|
1915
1915
|
return new RawEventSpoolInspectionError(code, message);
|
|
1916
1916
|
}
|
|
1917
|
-
function fail$
|
|
1917
|
+
function fail$3(code) {
|
|
1918
1918
|
throw inspectionError(code);
|
|
1919
1919
|
}
|
|
1920
1920
|
function hasCode(error, code) {
|
|
@@ -1927,17 +1927,17 @@ function sameSnapshot(a, b) {
|
|
|
1927
1927
|
return sameInode(a, b) && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs;
|
|
1928
1928
|
}
|
|
1929
1929
|
function requireFile(stat) {
|
|
1930
|
-
if (!stat.isFile() || stat.isSymbolicLink() || posix$1 && (stat.mode & 18) !== 0) fail$
|
|
1930
|
+
if (!stat.isFile() || stat.isSymbolicLink() || posix$1 && (stat.mode & 18) !== 0) fail$3("unsafe_entry");
|
|
1931
1931
|
}
|
|
1932
1932
|
function requireDirectory(dir) {
|
|
1933
1933
|
const stat = lstatSync(dir);
|
|
1934
|
-
if (!stat.isDirectory() || stat.isSymbolicLink()) fail$
|
|
1934
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) fail$3("unsafe_directory");
|
|
1935
1935
|
return stat;
|
|
1936
1936
|
}
|
|
1937
1937
|
function requireSafeSpoolDirectory(dir) {
|
|
1938
1938
|
const stat = requireDirectory(dir);
|
|
1939
1939
|
const parent = requireDirectory(dirname(resolve(dir)));
|
|
1940
|
-
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$
|
|
1940
|
+
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$3("unsafe_directory");
|
|
1941
1941
|
return stat;
|
|
1942
1942
|
}
|
|
1943
1943
|
function openFile(path) {
|
|
@@ -1947,7 +1947,7 @@ function openFile(path) {
|
|
|
1947
1947
|
try {
|
|
1948
1948
|
for (const actual of [fstatSync(fd), lstatSync(path)]) {
|
|
1949
1949
|
requireFile(actual);
|
|
1950
|
-
if (!sameInode(actual, expected)) fail$
|
|
1950
|
+
if (!sameInode(actual, expected)) fail$3("unsafe_entry");
|
|
1951
1951
|
}
|
|
1952
1952
|
return fd;
|
|
1953
1953
|
} catch (error) {
|
|
@@ -1969,9 +1969,9 @@ function readLimited(fd, limit) {
|
|
|
1969
1969
|
return null;
|
|
1970
1970
|
}
|
|
1971
1971
|
function parseReceipt(receipt) {
|
|
1972
|
-
if (typeof receipt !== "string" || receipt.includes("/") || receipt.includes("\\")) fail$
|
|
1972
|
+
if (typeof receipt !== "string" || receipt.includes("/") || receipt.includes("\\")) fail$3("invalid_receipt");
|
|
1973
1973
|
const match = retainedPattern.exec(receipt);
|
|
1974
|
-
if (!match?.[2] || match[0] !== receipt || !isOriginalName(match[2])) fail$
|
|
1974
|
+
if (!match?.[2] || match[0] !== receipt || !isOriginalName(match[2])) fail$3("invalid_receipt");
|
|
1975
1975
|
if (match[1] === "400-invalid_payload") return {
|
|
1976
1976
|
receipt,
|
|
1977
1977
|
status: 400,
|
|
@@ -1987,7 +1987,7 @@ function providerDirectory(provider) {
|
|
|
1987
1987
|
if (provider === "claude") return spoolDir();
|
|
1988
1988
|
if (provider === "codex") return codexHookSpoolDir();
|
|
1989
1989
|
if (provider === "pi") return piHookSpoolDir();
|
|
1990
|
-
return fail$
|
|
1990
|
+
return fail$3("invalid_provider");
|
|
1991
1991
|
}
|
|
1992
1992
|
function safeFailure(error, lock) {
|
|
1993
1993
|
let failure;
|
|
@@ -2105,9 +2105,9 @@ function classifyLock(path, receipt) {
|
|
|
2105
2105
|
try {
|
|
2106
2106
|
const before = fstatSync(fd);
|
|
2107
2107
|
const bytes = before.size <= 1024 ? readLimited(fd, 1024) : null;
|
|
2108
|
-
if (!bytes || !sameSnapshot(before, fstatSync(fd)) || !sameSnapshot(before, lstatSync(path))) fail$
|
|
2108
|
+
if (!bytes || !sameSnapshot(before, fstatSync(fd)) || !sameSnapshot(before, lstatSync(path))) fail$3(code);
|
|
2109
2109
|
const record = JSON.parse(bytes.toString("utf8"));
|
|
2110
|
-
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$
|
|
2110
|
+
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$3(code);
|
|
2111
2111
|
try {
|
|
2112
2112
|
process.kill(record.pid, 0);
|
|
2113
2113
|
code = "lock_busy";
|
|
@@ -2118,7 +2118,7 @@ function classifyLock(path, receipt) {
|
|
|
2118
2118
|
closeSync(fd);
|
|
2119
2119
|
}
|
|
2120
2120
|
} catch {}
|
|
2121
|
-
return fail$
|
|
2121
|
+
return fail$3(code);
|
|
2122
2122
|
}
|
|
2123
2123
|
function cleanupNewLock(fd, path, dirFd) {
|
|
2124
2124
|
try {
|
|
@@ -2141,7 +2141,7 @@ function acquireLock(dir, receipt, dirFd) {
|
|
|
2141
2141
|
fd = openSync(path, constants.O_CREAT | constants.O_EXCL | constants.O_RDWR | (constants.O_NOFOLLOW ?? 0), 384);
|
|
2142
2142
|
} catch (error) {
|
|
2143
2143
|
if (hasCode(error, "EEXIST")) return classifyLock(path, receipt);
|
|
2144
|
-
return fail$
|
|
2144
|
+
return fail$3("lock_failed");
|
|
2145
2145
|
}
|
|
2146
2146
|
try {
|
|
2147
2147
|
const serialized = JSON.stringify({
|
|
@@ -2152,11 +2152,11 @@ function acquireLock(dir, receipt, dirFd) {
|
|
|
2152
2152
|
token: randomUUID()
|
|
2153
2153
|
});
|
|
2154
2154
|
const data = Buffer.from(serialized);
|
|
2155
|
-
if (writeSync(fd, data) !== data.length) fail$
|
|
2155
|
+
if (writeSync(fd, data) !== data.length) fail$3("lock_repair_required");
|
|
2156
2156
|
fsyncSync(fd);
|
|
2157
2157
|
const details = fstatSync(fd);
|
|
2158
2158
|
requireFile(details);
|
|
2159
|
-
if (!sameSnapshot(details, lstatSync(path))) fail$
|
|
2159
|
+
if (!sameSnapshot(details, lstatSync(path))) fail$3("lock_repair_required");
|
|
2160
2160
|
return {
|
|
2161
2161
|
fd,
|
|
2162
2162
|
path,
|
|
@@ -2164,12 +2164,12 @@ function acquireLock(dir, receipt, dirFd) {
|
|
|
2164
2164
|
details
|
|
2165
2165
|
};
|
|
2166
2166
|
} catch {
|
|
2167
|
-
return fail$
|
|
2167
|
+
return fail$3(cleanupNewLock(fd, path, dirFd) ? "lock_failed" : "lock_repair_required");
|
|
2168
2168
|
}
|
|
2169
2169
|
}
|
|
2170
2170
|
function assertLock(lock) {
|
|
2171
2171
|
const bytes = readLimited(lock.fd, 1024);
|
|
2172
|
-
if (!bytes || bytes.toString("utf8") !== lock.serialized || !sameSnapshot(lock.details, fstatSync(lock.fd)) || !sameSnapshot(lock.details, lstatSync(lock.path))) fail$
|
|
2172
|
+
if (!bytes || bytes.toString("utf8") !== lock.serialized || !sameSnapshot(lock.details, fstatSync(lock.fd)) || !sameSnapshot(lock.details, lstatSync(lock.path))) fail$3("lock_repair_required");
|
|
2173
2173
|
}
|
|
2174
2174
|
function releaseLock(lock, dirFd) {
|
|
2175
2175
|
try {
|
|
@@ -2206,17 +2206,17 @@ function linkIfAbsent(source, target) {
|
|
|
2206
2206
|
function requireLinkedSnapshot(path, before) {
|
|
2207
2207
|
const current = lstatSync(path);
|
|
2208
2208
|
requireFile(current);
|
|
2209
|
-
if (!sameInode(before, current)) fail$
|
|
2210
|
-
if (before.size !== current.size || before.mtimeMs !== current.mtimeMs) fail$
|
|
2209
|
+
if (!sameInode(before, current)) fail$3("retention_conflict");
|
|
2210
|
+
if (before.size !== current.size || before.mtimeMs !== current.mtimeMs) fail$3("unsafe_entry");
|
|
2211
2211
|
}
|
|
2212
2212
|
function retainLinked(dir, dirFd, receipt, metadata, assertOwnership) {
|
|
2213
2213
|
const source = join(dir, receipt);
|
|
2214
2214
|
const target = join(dir, metadata.receipt);
|
|
2215
2215
|
const alternateStatus = metadata.status === 400 ? "413-payload_too_large" : "400-invalid_payload";
|
|
2216
|
-
if (statIfPresent(join(dir, `rejected-${alternateStatus}-${receipt}.retained`))) fail$
|
|
2216
|
+
if (statIfPresent(join(dir, `rejected-${alternateStatus}-${receipt}.retained`))) fail$3("retention_conflict");
|
|
2217
2217
|
const existing = statIfPresent(target);
|
|
2218
2218
|
if (!statIfPresent(source)) {
|
|
2219
|
-
if (!existing) fail$
|
|
2219
|
+
if (!existing) fail$3("receipt_not_found");
|
|
2220
2220
|
const fd = openFile(target);
|
|
2221
2221
|
try {
|
|
2222
2222
|
assertOwnership();
|
|
@@ -2234,9 +2234,9 @@ function retainLinked(dir, dirFd, receipt, metadata, assertOwnership) {
|
|
|
2234
2234
|
const fd = openFile(source);
|
|
2235
2235
|
try {
|
|
2236
2236
|
const before = fstatSync(fd);
|
|
2237
|
-
if (existing && !sameInode(existing, before)) fail$
|
|
2237
|
+
if (existing && !sameInode(existing, before)) fail$3("retention_conflict");
|
|
2238
2238
|
fsyncSync(fd);
|
|
2239
|
-
if (!sameSnapshot(before, lstatSync(source))) fail$
|
|
2239
|
+
if (!sameSnapshot(before, lstatSync(source))) fail$3("unsafe_entry");
|
|
2240
2240
|
assertOwnership();
|
|
2241
2241
|
if (!existing) linkIfAbsent(source, target);
|
|
2242
2242
|
fsyncSync(dirFd);
|
|
@@ -2256,17 +2256,17 @@ function retainLinked(dir, dirFd, receipt, metadata, assertOwnership) {
|
|
|
2256
2256
|
/** Delivery callers must also hold the provider's ingest lock to coordinate ordinary drain cleanup. */
|
|
2257
2257
|
function retainNativeHookReceipt({ dir, receipt, status, reason }) {
|
|
2258
2258
|
try {
|
|
2259
|
-
if (typeof receipt !== "string" || !isOriginalName(receipt)) fail$
|
|
2259
|
+
if (typeof receipt !== "string" || !isOriginalName(receipt)) fail$3("invalid_receipt");
|
|
2260
2260
|
const metadata = parseReceipt(`rejected-${status}-${reason}-${receipt}.retained`);
|
|
2261
2261
|
const directory = requireSafeSpoolDirectory(dir);
|
|
2262
2262
|
const dirFd = openSync(dir, flags | (constants.O_DIRECTORY ?? 0));
|
|
2263
2263
|
try {
|
|
2264
|
-
if (!sameInode(directory, fstatSync(dirFd))) fail$
|
|
2264
|
+
if (!sameInode(directory, fstatSync(dirFd))) fail$3("unsafe_directory");
|
|
2265
2265
|
const lock = acquireLock(dir, receipt, dirFd);
|
|
2266
2266
|
let result;
|
|
2267
2267
|
try {
|
|
2268
2268
|
result = retainLinked(dir, dirFd, receipt, metadata, () => {
|
|
2269
|
-
if (!sameInode(directory, requireSafeSpoolDirectory(dir))) fail$
|
|
2269
|
+
if (!sameInode(directory, requireSafeSpoolDirectory(dir))) fail$3("unsafe_directory");
|
|
2270
2270
|
assertLock(lock);
|
|
2271
2271
|
});
|
|
2272
2272
|
} catch (error) {
|
|
@@ -3827,6 +3827,11 @@ var STAGES = [
|
|
|
3827
3827
|
"prior_extension",
|
|
3828
3828
|
"current"
|
|
3829
3829
|
];
|
|
3830
|
+
/** Names the migrations a baseline leaves for `wrangler d1 migrations apply`, which must run their data steps. */
|
|
3831
|
+
function applyOnlyMigrationsText(stage) {
|
|
3832
|
+
if (stage !== "current") return "";
|
|
3833
|
+
return `-- Never records ${coordinatorD1ApplyOnlyMigrations().join(" or ")}, even when its objects exist: wrangler d1 migrations apply runs it, including its data steps.\n`;
|
|
3834
|
+
}
|
|
3830
3835
|
/** Names the migrations that the statement records only when their objects exist. */
|
|
3831
3836
|
function conditionalMigrationsText(stage) {
|
|
3832
3837
|
const conditional = coordinatorD1ConditionalBaselineMigrations(stage);
|
|
@@ -3846,7 +3851,7 @@ function exportBaseline(options) {
|
|
|
3846
3851
|
}
|
|
3847
3852
|
const conditional = coordinatorD1ConditionalBaselineMigrations(options.stage);
|
|
3848
3853
|
const always = migrations.filter((name) => !conditional.includes(name));
|
|
3849
|
-
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`);
|
|
3854
|
+
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)}${applyOnlyMigrationsText(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`);
|
|
3850
3855
|
}
|
|
3851
3856
|
function buildCoordinatorD1BaselineCommand() {
|
|
3852
3857
|
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");
|
|
@@ -3953,7 +3958,7 @@ function buildCoordinatorDiagnoseTeamSetupCommand() {
|
|
|
3953
3958
|
}
|
|
3954
3959
|
//#endregion
|
|
3955
3960
|
//#region src/commands/coordinator-enable-device.ts
|
|
3956
|
-
function fail$
|
|
3961
|
+
function fail$2(options, code, message) {
|
|
3957
3962
|
if (options.json) return emitJsonError(code, message);
|
|
3958
3963
|
p.log.error(message);
|
|
3959
3964
|
process.exitCode = 1;
|
|
@@ -3968,7 +3973,7 @@ async function enableDevice(group, device, options) {
|
|
|
3968
3973
|
dbPath: resolveDbOpt(options),
|
|
3969
3974
|
remoteUrl: "",
|
|
3970
3975
|
adminSecret: ""
|
|
3971
|
-
})) return fail$
|
|
3976
|
+
})) return fail$2(options, "device_not_enabled", "The device was not enabled. It has no enrollment in this group, or it is permanently blocked.");
|
|
3972
3977
|
if (options.json) {
|
|
3973
3978
|
console.log(JSON.stringify({
|
|
3974
3979
|
ok: true,
|
|
@@ -3980,9 +3985,9 @@ async function enableDevice(group, device, options) {
|
|
|
3980
3985
|
p.log.success("Device enabled.");
|
|
3981
3986
|
} catch (error) {
|
|
3982
3987
|
const code = error instanceof Error ? error.message : "";
|
|
3983
|
-
if (code === "device_removed") return fail$
|
|
3984
|
-
if (code === "device_revoked") return fail$
|
|
3985
|
-
return fail$
|
|
3988
|
+
if (code === "device_removed") return fail$2(options, code, "This device was removed. It must rejoin before it can be enabled.");
|
|
3989
|
+
if (code === "device_revoked") return fail$2(options, code, "This device is permanently blocked.");
|
|
3990
|
+
return fail$2(options, "enable_failed", "Could not enable the device. Check the coordinator database and device IDs.");
|
|
3986
3991
|
}
|
|
3987
3992
|
}
|
|
3988
3993
|
function buildCoordinatorEnableDeviceCommand() {
|
|
@@ -4021,7 +4026,7 @@ function reportUsageError(options, message) {
|
|
|
4021
4026
|
}
|
|
4022
4027
|
return false;
|
|
4023
4028
|
}
|
|
4024
|
-
function usage(options) {
|
|
4029
|
+
function usage$1(options) {
|
|
4025
4030
|
if (options.prepare === options.resume || options.prepare && (options.capability || options.reviewDigest || options.accountAdmission) || options.accountAdmission && options.capability !== void 0 || options.resume && !options.reviewDigest || options.resume && (options.json || !process.stderr.isTTY)) return reportUsageError(options, "Use --prepare first, then review its device, current Identity, capture counts and digest. Resume interactively with --resume --review-digest; use either --capability for operator admission or --account-admission for signed-in account admission, never both.");
|
|
4026
4031
|
if (options.capability !== void 0 && !/^[A-Za-z0-9._-]{1,512}$/.test(options.capability)) return reportUsageError(options, "Supply --capability exactly as issued, without whitespace or unsupported characters, and at most 512 characters. The prepared attempt has not been consumed.");
|
|
4027
4032
|
if (options.reviewDigest !== void 0 && !/^[0-9a-f]{64}$/.test(options.reviewDigest)) return reportUsageError(options, "Supply --review-digest as the exact 64-character lowercase hexadecimal digest from --prepare. Enrollment has not started.");
|
|
@@ -4108,7 +4113,7 @@ function resolveEnrollmentProfile(options) {
|
|
|
4108
4113
|
};
|
|
4109
4114
|
}
|
|
4110
4115
|
async function enroll(groupId, options) {
|
|
4111
|
-
if (!usage(options)) return;
|
|
4116
|
+
if (!usage$1(options)) return;
|
|
4112
4117
|
if (!groupUsage(options, groupId)) return;
|
|
4113
4118
|
if (!pathEnvironmentUsage(options, {
|
|
4114
4119
|
config: options.config,
|
|
@@ -4332,7 +4337,7 @@ function invitationFailure(raw) {
|
|
|
4332
4337
|
const described = describeFailure(raw);
|
|
4333
4338
|
return new InvitationCreateError(described.code, described.message);
|
|
4334
4339
|
}
|
|
4335
|
-
function fail(code, message) {
|
|
4340
|
+
function fail$1(code, message) {
|
|
4336
4341
|
const exitCode = USAGE_ERRORS.has(code) ? 2 : 1;
|
|
4337
4342
|
if (message) throw new InvitationCreateError(code, message, exitCode);
|
|
4338
4343
|
const described = describeFailure(code);
|
|
@@ -4345,12 +4350,12 @@ function resolveTeamId(store, team) {
|
|
|
4345
4350
|
const key = team.normalize("NFC").toLowerCase();
|
|
4346
4351
|
const byName = rows.filter((row) => row.display_name.normalize("NFC").toLowerCase() === key);
|
|
4347
4352
|
if (byName.length === 1 && byName[0]) return byName[0].team_id;
|
|
4348
|
-
if (byName.length > 1) fail("team_ambiguous", `More than one Team is named "${team}". Pass its Team ID instead.`);
|
|
4349
|
-
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.`);
|
|
4353
|
+
if (byName.length > 1) fail$1("team_ambiguous", `More than one Team is named "${team}". Pass its Team ID instead.`);
|
|
4354
|
+
return fail$1("team_not_found", `No active Team named "${team}" on this device. Create it in Sharing, or run this on a device where it exists.`);
|
|
4350
4355
|
}
|
|
4351
4356
|
function requestBody(store, opts, legacyArgs) {
|
|
4352
|
-
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`.");
|
|
4353
|
-
if (opts.review && opts.reviewedOnboardingDigest !== void 0) fail("usage_error", "Use --review or --reviewed-onboarding-digest, not both.");
|
|
4357
|
+
if (legacyArgs.length > 0 || Boolean(opts.team) === Boolean(opts.addDevice)) fail$1("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`.");
|
|
4358
|
+
if (opts.review && opts.reviewedOnboardingDigest !== void 0) fail$1("usage_error", "Use --review or --reviewed-onboarding-digest, not both.");
|
|
4354
4359
|
return {
|
|
4355
4360
|
...opts.team ? {
|
|
4356
4361
|
kind: "team_member",
|
|
@@ -4366,7 +4371,7 @@ function requestBody(store, opts, legacyArgs) {
|
|
|
4366
4371
|
}
|
|
4367
4372
|
function unwrap(outcome) {
|
|
4368
4373
|
if (outcome.httpStatus === 200) return outcome.body;
|
|
4369
|
-
return fail(String(outcome.body.error ?? "invitation_create_failed"));
|
|
4374
|
+
return fail$1(String(outcome.body.error ?? "invitation_create_failed"));
|
|
4370
4375
|
}
|
|
4371
4376
|
function printReview(body, opts) {
|
|
4372
4377
|
const preview = body.preview;
|
|
@@ -4407,7 +4412,7 @@ async function runInvitationCreate(opts, legacyArgs, deps) {
|
|
|
4407
4412
|
printReview(unwrap(await deps.preview(store, body)), opts);
|
|
4408
4413
|
return;
|
|
4409
4414
|
}
|
|
4410
|
-
if (!opts.reviewedOnboardingDigest) fail("reviewed_onboarding_digest_required");
|
|
4415
|
+
if (!opts.reviewedOnboardingDigest) fail$1("reviewed_onboarding_digest_required");
|
|
4411
4416
|
printCreated(unwrap(await deps.create(store, body)), opts);
|
|
4412
4417
|
} finally {
|
|
4413
4418
|
store.close();
|
|
@@ -4861,6 +4866,83 @@ function buildCoordinatorQualifyOwnerCommand() {
|
|
|
4861
4866
|
return command;
|
|
4862
4867
|
}
|
|
4863
4868
|
//#endregion
|
|
4869
|
+
//#region src/commands/coordinator-record-token-floor.ts
|
|
4870
|
+
/** Sealing batches before the command stops and asks for another run. */
|
|
4871
|
+
var MAX_BATCHES = 1e3;
|
|
4872
|
+
function fail(options, code, message) {
|
|
4873
|
+
if (options.json) return emitJsonError(code, message);
|
|
4874
|
+
p.log.error(message);
|
|
4875
|
+
process.exitCode = 1;
|
|
4876
|
+
}
|
|
4877
|
+
var REFUSALS = {
|
|
4878
|
+
coordinator_metadata_unavailable: "This coordinator database has no metadata table. Start `codemem coordinator serve` on it once, then try again.",
|
|
4879
|
+
invite_token_key_unavailable: "No invitation token key is available. Configure CODEMEM_INVITE_TOKEN_KEY, or let the coordinator create its key file.",
|
|
4880
|
+
invite_token_key_invalid: "The configured invitation token key is not a 32-byte key."
|
|
4881
|
+
};
|
|
4882
|
+
function refusalMessage(error) {
|
|
4883
|
+
return REFUSALS[error.code] ?? error.message;
|
|
4884
|
+
}
|
|
4885
|
+
/** Seals the tokens stored before the floor, batch by batch, until none remain. */
|
|
4886
|
+
async function sealStoredTokens(store) {
|
|
4887
|
+
let progress = await store.sealStoredInviteTokens(100);
|
|
4888
|
+
for (let batch = 1; batch < MAX_BATCHES; batch += 1) {
|
|
4889
|
+
if (progress.remaining_plaintext_invites + progress.remaining_plaintext_join_requests + progress.remaining_spent_ciphertext === 0) break;
|
|
4890
|
+
progress = await store.sealStoredInviteTokens(100);
|
|
4891
|
+
}
|
|
4892
|
+
return progress;
|
|
4893
|
+
}
|
|
4894
|
+
/** Why this coordinator could not seal with its key, or null when it can. */
|
|
4895
|
+
function keyRefusal(store) {
|
|
4896
|
+
return store.prepareInviteTokenKey().then(() => null, (error) => {
|
|
4897
|
+
if (error instanceof InviteTokenRefusal) return error;
|
|
4898
|
+
throw error;
|
|
4899
|
+
});
|
|
4900
|
+
}
|
|
4901
|
+
/** The coordinator store at `dbPath`, or null when the file is not a readable coordinator database. */
|
|
4902
|
+
function openStore(dbPath) {
|
|
4903
|
+
try {
|
|
4904
|
+
return new BetterSqliteCoordinatorStore(dbPath);
|
|
4905
|
+
} catch {
|
|
4906
|
+
return null;
|
|
4907
|
+
}
|
|
4908
|
+
}
|
|
4909
|
+
async function recordFloor(versionText, options) {
|
|
4910
|
+
const version = Number(versionText);
|
|
4911
|
+
if (!/^\d+$/u.test(versionText.trim()) || !Number.isSafeInteger(version) || version < 1) return fail(options, "invalid_version", "Enter the lookup version as a whole number, such as 1.");
|
|
4912
|
+
if (version > INVITE_TOKEN_LOOKUP_VERSION) return fail(options, "version_above_build", `This codemem release has invitation token lookup version ${INVITE_TOKEN_LOOKUP_VERSION}. It cannot record a higher floor.`);
|
|
4913
|
+
const dbPath = resolveDbOpt(options) ?? DEFAULT_COORDINATOR_DB_PATH;
|
|
4914
|
+
if (!existsSync(dbPath)) return fail(options, "coordinator_database_missing", `No coordinator database at ${dbPath}.`);
|
|
4915
|
+
const store = openStore(dbPath);
|
|
4916
|
+
if (!store) return fail(options, "coordinator_database_unreadable", `Could not open ${dbPath} as a coordinator database.`);
|
|
4917
|
+
try {
|
|
4918
|
+
const keyRefused = await keyRefusal(store);
|
|
4919
|
+
if (keyRefused) return fail(options, keyRefused.code, `${refusalMessage(keyRefused)} The floor was not recorded.`);
|
|
4920
|
+
const fence = await store.raiseInviteTokenLookupFloor(version);
|
|
4921
|
+
const progress = await sealStoredTokens(store);
|
|
4922
|
+
if (options.json) {
|
|
4923
|
+
console.log(JSON.stringify({
|
|
4924
|
+
ok: true,
|
|
4925
|
+
...fence,
|
|
4926
|
+
...progress
|
|
4927
|
+
}, null, 2));
|
|
4928
|
+
return;
|
|
4929
|
+
}
|
|
4930
|
+
p.log.success(`Recorded invitation token lookup floor ${fence.min_serving_lookup_version}. This coordinator now encrypts invitation tokens.`);
|
|
4931
|
+
p.log.info(`Sealed ${progress.sealed_invites} stored invitations in the last batch; ${progress.remaining_plaintext_invites} still hold their token.`);
|
|
4932
|
+
} catch (error) {
|
|
4933
|
+
if (error instanceof InviteTokenRefusal) return fail(options, error.code, refusalMessage(error));
|
|
4934
|
+
return fail(options, "record_floor_failed", "Could not record the floor. Check the coordinator database.");
|
|
4935
|
+
} finally {
|
|
4936
|
+
await store.close();
|
|
4937
|
+
}
|
|
4938
|
+
}
|
|
4939
|
+
function buildCoordinatorRecordTokenFloorCommand() {
|
|
4940
|
+
const command = new Command("record-floor").configureHelp(helpStyle).description("Confirm that no codemem release older than this invitation token lookup version opens the coordinator database, then encrypt its stored invitation tokens").argument("<version>", `lookup version; at most ${INVITE_TOKEN_LOOKUP_VERSION} for this release`);
|
|
4941
|
+
addDbOption(command);
|
|
4942
|
+
addJsonOption(command);
|
|
4943
|
+
return command.action(recordFloor);
|
|
4944
|
+
}
|
|
4945
|
+
//#endregion
|
|
4864
4946
|
//#region src/commands/coordinator-review-device-owner.ts
|
|
4865
4947
|
var REVIEW_REASONS = [
|
|
4866
4948
|
"group_unavailable",
|
|
@@ -5346,7 +5428,8 @@ function inviteImportProfile(invite, opts) {
|
|
|
5346
5428
|
keysDir: opts.keysDir ?? null,
|
|
5347
5429
|
configPath: opts.config ?? null,
|
|
5348
5430
|
recipientDisplayName: opts.recipientName?.trim() || null,
|
|
5349
|
-
deviceDisplayName: opts.deviceName?.trim() || null
|
|
5431
|
+
deviceDisplayName: opts.deviceName?.trim() || null,
|
|
5432
|
+
confirmCoordinatorJoin: opts.confirmCoordinatorJoin === true
|
|
5350
5433
|
};
|
|
5351
5434
|
}
|
|
5352
5435
|
async function acceptInviteWithProfileCheck(profile, reviewedOnboardingDigest) {
|
|
@@ -5359,6 +5442,37 @@ async function acceptInviteWithProfileCheck(profile, reviewedOnboardingDigest) {
|
|
|
5359
5442
|
reviewedOnboardingDigest: digest
|
|
5360
5443
|
});
|
|
5361
5444
|
}
|
|
5445
|
+
var COORDINATOR_JOIN_WARNING = "Joining a coordinator permanently turns off syncing without a coordinator for this device's key, including other codemem profiles that use the same key.";
|
|
5446
|
+
function addInviteAcceptOptions(command) {
|
|
5447
|
+
addDbOption(command);
|
|
5448
|
+
addConfigOption(command);
|
|
5449
|
+
addJsonOption(command);
|
|
5450
|
+
command.option("--confirm-coordinator-join", "Join even though it permanently turns off syncing without a coordinator for this device's key");
|
|
5451
|
+
}
|
|
5452
|
+
/** The invitation is fine; this device couldn't record the join before sending it. */
|
|
5453
|
+
function explainRecordFailure(error) {
|
|
5454
|
+
if (error instanceof Error && error.message === COORDINATOR_FREE_WITNESS_UNAVAILABLE) throw new Error("codemem couldn't save this device's coordinator record. Unlock or repair the keychain, or make the codemem keys folder writable, then try again.");
|
|
5455
|
+
if (error instanceof Error && error.message === COORDINATOR_FREE_BINDING_UNVERIFIED) throw new Error("codemem couldn't check this device's coordinator record because a file in the codemem keys folder is missing or damaged. Restore the keys folder that belongs with this database, then try again.");
|
|
5456
|
+
throw error;
|
|
5457
|
+
}
|
|
5458
|
+
/** Accepts after the user confirms a join that turns off syncing without a coordinator. */
|
|
5459
|
+
async function acceptInviteWithJoinConfirmation(profile, opts) {
|
|
5460
|
+
const accept = (accepted) => acceptInviteWithProfileCheck(accepted, opts.reviewedOnboardingDigest).catch(explainRecordFailure);
|
|
5461
|
+
try {
|
|
5462
|
+
return await accept(profile);
|
|
5463
|
+
} catch (error) {
|
|
5464
|
+
if (!(error instanceof Error) || error.message !== COORDINATOR_JOIN_CONFIRMATION_REQUIRED) throw error;
|
|
5465
|
+
if (opts.json || !process.stdin.isTTY) throw new Error(`${COORDINATOR_JOIN_WARNING} To join, run the command again with --confirm-coordinator-join.`);
|
|
5466
|
+
if (await p.confirm({
|
|
5467
|
+
message: `${COORDINATOR_JOIN_WARNING} Join this coordinator?`,
|
|
5468
|
+
initialValue: false
|
|
5469
|
+
}) !== true) throw new Error("Invitation not accepted.");
|
|
5470
|
+
return accept({
|
|
5471
|
+
...profile,
|
|
5472
|
+
confirmCoordinatorJoin: true
|
|
5473
|
+
});
|
|
5474
|
+
}
|
|
5475
|
+
}
|
|
5362
5476
|
function rejectConflictingInviteReviewOptions(opts) {
|
|
5363
5477
|
if (!opts.review || opts.reviewedOnboardingDigest === void 0) return false;
|
|
5364
5478
|
const message = "Use --review or --reviewed-onboarding-digest, not both.";
|
|
@@ -5973,9 +6087,7 @@ function buildCoordinatorCommand() {
|
|
|
5973
6087
|
grant.addCommand(revokeBootstrapGrantCmd);
|
|
5974
6088
|
invitation.addCommand(buildCoordinatorInvitationCreateCommand());
|
|
5975
6089
|
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");
|
|
5976
|
-
|
|
5977
|
-
addConfigOption(importInviteCmd);
|
|
5978
|
-
addJsonOption(importInviteCmd);
|
|
6090
|
+
addInviteAcceptOptions(importInviteCmd);
|
|
5979
6091
|
importInviteCmd.action(async (invite, opts) => {
|
|
5980
6092
|
try {
|
|
5981
6093
|
if (rejectConflictingInviteReviewOptions(opts)) return;
|
|
@@ -5984,7 +6096,7 @@ function buildCoordinatorCommand() {
|
|
|
5984
6096
|
printInviteReview(await coordinatorReviewInviteAction(profile), opts);
|
|
5985
6097
|
return;
|
|
5986
6098
|
}
|
|
5987
|
-
const result = await
|
|
6099
|
+
const result = await acceptInviteWithJoinConfirmation(profile, opts);
|
|
5988
6100
|
if (opts.json) {
|
|
5989
6101
|
console.log(JSON.stringify(result, null, 2));
|
|
5990
6102
|
return;
|
|
@@ -6004,7 +6116,7 @@ function buildCoordinatorCommand() {
|
|
|
6004
6116
|
process.exitCode = 1;
|
|
6005
6117
|
}
|
|
6006
6118
|
});
|
|
6007
|
-
invitation.addCommand(importInviteCmd);
|
|
6119
|
+
invitation.addCommand(importInviteCmd).addCommand(buildCoordinatorRecordTokenFloorCommand());
|
|
6008
6120
|
const listJoinRequestsCmd = new Command("list").configureHelp(helpStyle).description("List pending coordinator join requests").argument("[group]", "group id").option("--group <group>", "group id").option("--remote-url <url>", "remote coordinator URL override").option("--admin-secret <secret>", "remote coordinator admin secret override");
|
|
6009
6121
|
addDbOption(listJoinRequestsCmd);
|
|
6010
6122
|
addJsonOption(listJoinRequestsCmd);
|
|
@@ -6433,9 +6545,8 @@ function estimateReplicationOpsBytes(db) {
|
|
|
6433
6545
|
try {
|
|
6434
6546
|
const row = db.prepare(`SELECT COALESCE(SUM(pgsize), 0) AS total_bytes
|
|
6435
6547
|
FROM dbstat
|
|
6436
|
-
WHERE name =
|
|
6437
|
-
|
|
6438
|
-
OR name LIKE 'sqlite_autoindex_replication_ops_%'`).get();
|
|
6548
|
+
WHERE name IN (SELECT name FROM sqlite_schema WHERE tbl_name =
|
|
6549
|
+
COALESCE((SELECT tbl_name FROM sqlite_schema WHERE name='idx_replication_ops_created'),'replication_ops'))`).get();
|
|
6439
6550
|
return Number(row?.total_bytes ?? 0);
|
|
6440
6551
|
} catch {
|
|
6441
6552
|
return 0;
|
|
@@ -7021,6 +7132,10 @@ var runMemoryRedactSecrets = (opts) => {
|
|
|
7021
7132
|
});
|
|
7022
7133
|
p.log.info(`Affected memories:\n${lines.join("\n")}`);
|
|
7023
7134
|
}
|
|
7135
|
+
if (result.unpropagatedRedactions.length > 0) {
|
|
7136
|
+
const ids = result.unpropagatedRedactions.map((entry) => `#${entry.id}`).join(", ");
|
|
7137
|
+
p.log.warn(`Redacted here only: ${result.unpropagatedRedactions.length} memories in synced scopes that this device cannot show it created, so peers that received them keep the unredacted copy: ${ids}. Redact them on the device that wrote them, or remove them from the peers.`);
|
|
7138
|
+
}
|
|
7024
7139
|
p.outro("Re-run with no changes to confirm idempotency");
|
|
7025
7140
|
} catch (error) {
|
|
7026
7141
|
p.log.error(error instanceof Error ? error.message : String(error));
|
|
@@ -9676,6 +9791,16 @@ function createRetentionRunners(dbPath, syncConfig, logger, signal) {
|
|
|
9676
9791
|
signal,
|
|
9677
9792
|
logger
|
|
9678
9793
|
}));
|
|
9794
|
+
runners.push(new SessionRepositoryIdentityRunner({
|
|
9795
|
+
dbPath,
|
|
9796
|
+
signal,
|
|
9797
|
+
logger
|
|
9798
|
+
}));
|
|
9799
|
+
runners.push(new ReplicationBackfillRunner({
|
|
9800
|
+
dbPath,
|
|
9801
|
+
signal,
|
|
9802
|
+
logger
|
|
9803
|
+
}));
|
|
9679
9804
|
return runners;
|
|
9680
9805
|
}
|
|
9681
9806
|
function startMaintenanceWorkerRuntime(options = {}) {
|
|
@@ -9843,7 +9968,7 @@ async function pruneUntilDone(db, batchSize) {
|
|
|
9843
9968
|
if (pass.complete || !progressed) return totals;
|
|
9844
9969
|
}
|
|
9845
9970
|
}
|
|
9846
|
-
function reportFailure$
|
|
9971
|
+
function reportFailure$2(opts, code, message, exitCode) {
|
|
9847
9972
|
if (opts.json) {
|
|
9848
9973
|
emitJsonError(code, message, exitCode);
|
|
9849
9974
|
return;
|
|
@@ -9862,7 +9987,7 @@ function reportHuman(purged) {
|
|
|
9862
9987
|
async function runPruneRetrievalLedger(opts) {
|
|
9863
9988
|
const batchSize = parseBatchSize(opts.batchSize);
|
|
9864
9989
|
if (batchSize === null) {
|
|
9865
|
-
reportFailure$
|
|
9990
|
+
reportFailure$2(opts, "invalid_batch_size", `--batch-size must be an integer from 1 to 10000 (got "${opts.batchSize}")`, 2);
|
|
9866
9991
|
return;
|
|
9867
9992
|
}
|
|
9868
9993
|
let db = null;
|
|
@@ -9885,7 +10010,7 @@ async function runPruneRetrievalLedger(opts) {
|
|
|
9885
10010
|
}, null, 2));
|
|
9886
10011
|
} else reportHuman(purged);
|
|
9887
10012
|
} catch (error) {
|
|
9888
|
-
reportFailure$
|
|
10013
|
+
reportFailure$2(opts, "prune_retrieval_ledger_failed", error instanceof Error ? error.message : String(error), 1);
|
|
9889
10014
|
} finally {
|
|
9890
10015
|
db?.close();
|
|
9891
10016
|
}
|
|
@@ -11339,53 +11464,175 @@ function resolveStopRestartInvocation(mode, opts) {
|
|
|
11339
11464
|
background: mode === "restart"
|
|
11340
11465
|
};
|
|
11341
11466
|
}
|
|
11342
|
-
|
|
11343
|
-
|
|
11344
|
-
function extractViewerPid(payload) {
|
|
11345
|
-
if (!payload || typeof payload !== "object") return null;
|
|
11346
|
-
const rawPid = payload.viewer_pid;
|
|
11347
|
-
if (typeof rawPid !== "number" || !Number.isFinite(rawPid) || rawPid <= 0) return null;
|
|
11348
|
-
return Math.trunc(rawPid);
|
|
11467
|
+
function unavailableMessage(error) {
|
|
11468
|
+
return `Cannot create the viewer lock at ${error.path} (${error.code}). Check that ${dirname(error.path)} exists and is writable.`;
|
|
11349
11469
|
}
|
|
11350
|
-
|
|
11351
|
-
|
|
11352
|
-
|
|
11470
|
+
/**
|
|
11471
|
+
* What the lock's owner record says about the holder, and how to stop it. The
|
|
11472
|
+
* record is a hint: nothing here checks that the recorded process still holds
|
|
11473
|
+
* the lock, so nothing acts on it.
|
|
11474
|
+
*/
|
|
11475
|
+
function viewerLockHolderHint(owner, platform = process.platform) {
|
|
11476
|
+
if (!owner) return "No holder was recorded. If it is a running codemem viewer, stop it with `codemem serve stop` using the same --db-path and --port; otherwise end the process that holds the lock.";
|
|
11477
|
+
const started = owner.started ? `, started ${owner.started}` : "";
|
|
11478
|
+
const kill = platform === "win32" ? `taskkill /PID ${owner.pid}` : `kill ${owner.pid}`;
|
|
11479
|
+
return `Recorded holder (unverified): pid ${owner.pid}${started}, port ${owner.port}. If it is a running codemem viewer, stop it with \`codemem serve stop\` using the same --db-path and --port ${owner.port}; otherwise end that process (\`${kill}\`).`;
|
|
11353
11480
|
}
|
|
11354
|
-
function
|
|
11355
|
-
return
|
|
11481
|
+
function heldMessage(dbPath, owner, answering) {
|
|
11482
|
+
return `${answering ? `Another codemem viewer is already using ${dbPath}.` : `Another process holds the viewer lock for ${dbPath}.`} ${viewerLockHolderHint(owner)} To run another viewer, give it its own database.`;
|
|
11356
11483
|
}
|
|
11357
|
-
|
|
11358
|
-
|
|
11359
|
-
|
|
11484
|
+
/** One attempt: the claim's result, or null while another process holds the lock. */
|
|
11485
|
+
function tryClaim(dbPath, target) {
|
|
11486
|
+
try {
|
|
11487
|
+
return {
|
|
11488
|
+
status: "acquired",
|
|
11489
|
+
lock: acquireViewerWriterLock(dbPath, { owner: target })
|
|
11490
|
+
};
|
|
11491
|
+
} catch (error) {
|
|
11492
|
+
if (error instanceof ViewerWriterLockUnavailableError) return {
|
|
11493
|
+
status: "refused",
|
|
11494
|
+
message: unavailableMessage(error)
|
|
11495
|
+
};
|
|
11496
|
+
if (error instanceof ViewerWriterLockHeldError) return null;
|
|
11497
|
+
throw error;
|
|
11498
|
+
}
|
|
11360
11499
|
}
|
|
11361
|
-
|
|
11362
|
-
|
|
11363
|
-
|
|
11364
|
-
|
|
11500
|
+
/**
|
|
11501
|
+
* Takes the database's Viewer lock and records this process as its owner. When a
|
|
11502
|
+
* Viewer answers at the recorded holder's address, the start is refused at once.
|
|
11503
|
+
* Any other holder, such as a Viewer still shutting down, gets `waitMs` to
|
|
11504
|
+
* release it.
|
|
11505
|
+
*/
|
|
11506
|
+
async function claimViewerWriterLock(dbPath, target, dependencies, options = {}) {
|
|
11507
|
+
const deadline = Date.now() + (options.waitMs ?? 1e4);
|
|
11508
|
+
for (;;) {
|
|
11509
|
+
const attempt = tryClaim(dbPath, target);
|
|
11510
|
+
if (attempt) return attempt;
|
|
11511
|
+
const owner = readViewerWriterLockOwner(dbPath);
|
|
11512
|
+
if (owner && await dependencies.isLiveViewer(owner)) return {
|
|
11513
|
+
status: "refused",
|
|
11514
|
+
message: heldMessage(dbPath, owner, true)
|
|
11515
|
+
};
|
|
11516
|
+
if (Date.now() >= deadline) return {
|
|
11517
|
+
status: "refused",
|
|
11518
|
+
message: heldMessage(dbPath, owner, false)
|
|
11519
|
+
};
|
|
11520
|
+
await dependencies.sleep(options.pollMs ?? 250);
|
|
11521
|
+
}
|
|
11365
11522
|
}
|
|
11366
|
-
|
|
11367
|
-
|
|
11523
|
+
/** Waits until no process holds the database's Viewer lock. */
|
|
11524
|
+
async function waitForViewerWriterLockRelease(dbPath, dependencies, options) {
|
|
11525
|
+
const deadline = Date.now() + options.timeoutMs;
|
|
11526
|
+
while (dependencies.isLockHeld(dbPath)) {
|
|
11527
|
+
if (Date.now() >= deadline) return false;
|
|
11528
|
+
await dependencies.sleep(options.pollMs ?? 200);
|
|
11529
|
+
}
|
|
11530
|
+
return true;
|
|
11368
11531
|
}
|
|
11369
|
-
|
|
11370
|
-
|
|
11371
|
-
|
|
11532
|
+
var STARTUP_MESSAGE_TYPE = "codemem-viewer-startup";
|
|
11533
|
+
/**
|
|
11534
|
+
* Set only by a background start for the Viewer it spawns. Any other parent with
|
|
11535
|
+
* an IPC channel, such as a test runner's worker pool, gets no startup messages.
|
|
11536
|
+
*/
|
|
11537
|
+
var VIEWER_STARTUP_REPORT_ENV = "CODEMEM_VIEWER_STARTUP_REPORT";
|
|
11538
|
+
/**
|
|
11539
|
+
* Tells a waiting background parent how this start went. A no-op unless a
|
|
11540
|
+
* background start spawned this process. The channel closes after the final
|
|
11541
|
+
* result, so the Viewer does not depend on the parent.
|
|
11542
|
+
*/
|
|
11543
|
+
function reportViewerStartup(event) {
|
|
11544
|
+
if (process.env["CODEMEM_VIEWER_STARTUP_REPORT"] !== "1") return;
|
|
11545
|
+
if (!process.send || !process.connected) return;
|
|
11546
|
+
const final = event.state !== "lock_acquired";
|
|
11547
|
+
process.send({
|
|
11548
|
+
type: STARTUP_MESSAGE_TYPE,
|
|
11549
|
+
...event
|
|
11550
|
+
}, void 0, {}, () => {
|
|
11551
|
+
if (final && process.connected) process.disconnect();
|
|
11552
|
+
});
|
|
11372
11553
|
}
|
|
11373
|
-
function
|
|
11374
|
-
|
|
11375
|
-
|
|
11376
|
-
|
|
11377
|
-
|
|
11378
|
-
|
|
11379
|
-
"
|
|
11380
|
-
|
|
11381
|
-
|
|
11382
|
-
|
|
11554
|
+
function startupEvent(message) {
|
|
11555
|
+
const event = message;
|
|
11556
|
+
if (event?.type !== STARTUP_MESSAGE_TYPE) return null;
|
|
11557
|
+
if (event.state === "lock_acquired" || event.state === "listening") return { state: event.state };
|
|
11558
|
+
if (event.state === "failed") return {
|
|
11559
|
+
state: "failed",
|
|
11560
|
+
message: typeof event.message === "string" ? event.message : "Viewer failed to start"
|
|
11561
|
+
};
|
|
11562
|
+
return null;
|
|
11563
|
+
}
|
|
11564
|
+
/**
|
|
11565
|
+
* Waits for a background Viewer's startup result. `starting`: it holds the lock
|
|
11566
|
+
* but was not serving yet when the wait ended.
|
|
11567
|
+
*/
|
|
11568
|
+
function waitForViewerStartup(child, timeoutMs) {
|
|
11569
|
+
return new Promise((resolve) => {
|
|
11570
|
+
let lockAcquired = false;
|
|
11571
|
+
const finish = (result) => {
|
|
11572
|
+
clearTimeout(timer);
|
|
11573
|
+
child.off("message", onMessage);
|
|
11574
|
+
child.off("exit", onExit);
|
|
11575
|
+
child.off("error", onError);
|
|
11576
|
+
if (child.connected) child.disconnect();
|
|
11577
|
+
resolve(result);
|
|
11578
|
+
};
|
|
11579
|
+
const onMessage = (message) => {
|
|
11580
|
+
const event = startupEvent(message);
|
|
11581
|
+
if (event?.state === "lock_acquired") lockAcquired = true;
|
|
11582
|
+
else if (event) finish(event);
|
|
11583
|
+
};
|
|
11584
|
+
const onExit = (code, signal) => finish({
|
|
11585
|
+
state: "failed",
|
|
11586
|
+
message: `The viewer exited during startup (${signal ?? `exit code ${code ?? "unknown"}`}).`
|
|
11587
|
+
});
|
|
11588
|
+
const onError = (error) => finish({
|
|
11589
|
+
state: "failed",
|
|
11590
|
+
message: `Could not start the viewer: ${error.message}`
|
|
11591
|
+
});
|
|
11592
|
+
const timer = setTimeout(() => {
|
|
11593
|
+
if (lockAcquired) finish({ state: "starting" });
|
|
11594
|
+
else finish({
|
|
11595
|
+
state: "failed",
|
|
11596
|
+
message: `The viewer did not report startup within ${Math.ceil(timeoutMs / 1e3)}s.`
|
|
11597
|
+
});
|
|
11598
|
+
}, timeoutMs);
|
|
11599
|
+
child.on("message", onMessage);
|
|
11600
|
+
child.on("exit", onExit);
|
|
11601
|
+
child.on("error", onError);
|
|
11383
11602
|
});
|
|
11384
|
-
|
|
11385
|
-
|
|
11386
|
-
|
|
11387
|
-
|
|
11388
|
-
|
|
11603
|
+
}
|
|
11604
|
+
//#endregion
|
|
11605
|
+
//#region src/commands/viewer-stop-verification.ts
|
|
11606
|
+
/**
|
|
11607
|
+
* Which process `codemem serve stop` and `restart` may signal for a database.
|
|
11608
|
+
*
|
|
11609
|
+
* A Viewer is signalled only when it is shown to serve this database, and only while its
|
|
11610
|
+
* pid still names the process that was shown to. Verification happens once and records the
|
|
11611
|
+
* process's identity (start time and command line) and which proof it passed. Right
|
|
11612
|
+
* before each signal, that same proof runs again without HTTP, then the identity is read
|
|
11613
|
+
* again and must match exactly, so the last thing checked before a signal is which process
|
|
11614
|
+
* the pid names.
|
|
11615
|
+
*
|
|
11616
|
+
* A Viewer must be the process listening on its port. A CLI or MCP process that has the
|
|
11617
|
+
* database open, or that an answer at the port names, is never a candidate.
|
|
11618
|
+
*
|
|
11619
|
+
* Proofs:
|
|
11620
|
+
* - A Viewer that holds the database's lock records itself as its owner. The record must
|
|
11621
|
+
* name the pid, its start time and the canonical database, and the lock must be held.
|
|
11622
|
+
* - A Viewer from a release before the lock records nothing. It must be the process
|
|
11623
|
+
* listening on its port, report this database in its prompt-pack profile, and have the
|
|
11624
|
+
* database file or its write-ahead log open, as `lsof` shows. Each is required: a
|
|
11625
|
+
* process can have a database open without serving it. Those releases cannot read a
|
|
11626
|
+
* transitioned store, so for one only the lock proof is accepted.
|
|
11627
|
+
*
|
|
11628
|
+
* On macOS and Linux, a check that needs `lsof` refuses when `lsof` cannot run. On native
|
|
11629
|
+
* Windows there is no `lsof` or `ps`: a Viewer there cannot be identified at all, and the
|
|
11630
|
+
* database proofs that need `lsof` are not asked of it.
|
|
11631
|
+
*/
|
|
11632
|
+
function isLikelyViewerCommand(command) {
|
|
11633
|
+
const lowered = command.toLowerCase();
|
|
11634
|
+
if (!/\b(?:serve|service)\s+start\b/.test(lowered)) return false;
|
|
11635
|
+
return lowered.includes("codemem") || lowered.includes("packages/cli/dist/index.js") || lowered.includes("/cli/dist/index.js") || lowered.includes("packages/cli/src/index.ts");
|
|
11389
11636
|
}
|
|
11390
11637
|
function readProcessCommand(pid) {
|
|
11391
11638
|
const result = spawnSync("ps", [
|
|
@@ -11401,21 +11648,220 @@ function readProcessCommand(pid) {
|
|
|
11401
11648
|
const cmd = (result.stdout || "").trim();
|
|
11402
11649
|
return cmd.length > 0 ? cmd : null;
|
|
11403
11650
|
}
|
|
11404
|
-
function
|
|
11405
|
-
|
|
11406
|
-
if (listenerPid && listenerPid !== pid) return false;
|
|
11651
|
+
function readProcessIdentity(pid) {
|
|
11652
|
+
const started = processStartIdentity(pid);
|
|
11407
11653
|
const command = readProcessCommand(pid);
|
|
11408
|
-
|
|
11409
|
-
|
|
11654
|
+
return started && command ? {
|
|
11655
|
+
started,
|
|
11656
|
+
command
|
|
11657
|
+
} : null;
|
|
11658
|
+
}
|
|
11659
|
+
function sameProcess(a, b) {
|
|
11660
|
+
return a.started === b.started && a.command === b.command;
|
|
11661
|
+
}
|
|
11662
|
+
var LSOF_TIMEOUT_MS = 2e3;
|
|
11663
|
+
/** Why `lsof` could not answer, from the error Node reports for the attempt. */
|
|
11664
|
+
function lsofFailure(error) {
|
|
11665
|
+
if (error.code === "ENOENT") return "lsof is not installed or not on PATH";
|
|
11666
|
+
if (error.code === "ETIMEDOUT") return `lsof did not answer within ${LSOF_TIMEOUT_MS} ms`;
|
|
11667
|
+
if (error.code === "EACCES" || error.code === "EPERM") return "lsof could not be run (permission denied)";
|
|
11668
|
+
return `lsof could not be run (${error.code ?? error.message})`;
|
|
11669
|
+
}
|
|
11670
|
+
/**
|
|
11671
|
+
* The lines `lsof` prints, or why it could not run. `lsof` exits 1 when it finds nothing
|
|
11672
|
+
* to list; that is an answer, and the lines are then empty. With `-w` it prints no
|
|
11673
|
+
* warnings, so anything on stderr then is a failure.
|
|
11674
|
+
*/
|
|
11675
|
+
function runLsof(args) {
|
|
11676
|
+
const result = spawnSync("lsof", ["-w", ...args], {
|
|
11677
|
+
encoding: "utf-8",
|
|
11678
|
+
timeout: LSOF_TIMEOUT_MS
|
|
11679
|
+
});
|
|
11680
|
+
if (result.error) return {
|
|
11681
|
+
ok: false,
|
|
11682
|
+
reason: lsofFailure(result.error)
|
|
11683
|
+
};
|
|
11684
|
+
if (result.signal) return {
|
|
11685
|
+
ok: false,
|
|
11686
|
+
reason: `lsof was stopped by ${result.signal}`
|
|
11687
|
+
};
|
|
11688
|
+
const stderr = (result.stderr || "").trim();
|
|
11689
|
+
if (result.status !== 0 && (result.status !== 1 || stderr)) {
|
|
11690
|
+
const detail = stderr.split(/\r?\n/)[0];
|
|
11691
|
+
return {
|
|
11692
|
+
ok: false,
|
|
11693
|
+
reason: `lsof failed with status ${result.status}${detail ? `: ${detail}` : ""}`
|
|
11694
|
+
};
|
|
11695
|
+
}
|
|
11696
|
+
return {
|
|
11697
|
+
ok: true,
|
|
11698
|
+
lines: (result.stdout || "").split(/\r?\n/).filter((line) => line.length > 0)
|
|
11699
|
+
};
|
|
11700
|
+
}
|
|
11701
|
+
/** The pid listening on TCP `port`, null when none is, or why that could not be read. */
|
|
11702
|
+
function listeningPid(port) {
|
|
11703
|
+
const result = runLsof([
|
|
11704
|
+
"-nP",
|
|
11705
|
+
`-iTCP:${port}`,
|
|
11706
|
+
"-sTCP:LISTEN",
|
|
11707
|
+
"-t"
|
|
11708
|
+
]);
|
|
11709
|
+
if (!result.ok) return result;
|
|
11710
|
+
const first = result.lines.map((line) => line.trim()).find((line) => line.length > 0);
|
|
11711
|
+
const parsed = first ? Number.parseInt(first, 10) : NaN;
|
|
11712
|
+
return {
|
|
11713
|
+
ok: true,
|
|
11714
|
+
pid: Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null
|
|
11715
|
+
};
|
|
11716
|
+
}
|
|
11717
|
+
/**
|
|
11718
|
+
* Whether process `pid` has the database file, or its write-ahead log, open. A name `lsof`
|
|
11719
|
+
* marks ` (deleted)`, as Linux does for a file removed while open, is another file than the
|
|
11720
|
+
* one at the path now and does not count. Names are resolved as the database's is.
|
|
11721
|
+
*/
|
|
11722
|
+
function holdsDatabaseOpen(pid, canonical) {
|
|
11723
|
+
const result = runLsof([
|
|
11724
|
+
"-p",
|
|
11725
|
+
String(pid),
|
|
11726
|
+
"-Fn"
|
|
11727
|
+
]);
|
|
11728
|
+
if (!result.ok) return result;
|
|
11729
|
+
const wanted = /* @__PURE__ */ new Set([canonical, `${canonical}-wal`]);
|
|
11730
|
+
const names = /* @__PURE__ */ new Set([basename(canonical), `${basename(canonical)}-wal`]);
|
|
11731
|
+
return {
|
|
11732
|
+
ok: true,
|
|
11733
|
+
open: result.lines.some((line) => {
|
|
11734
|
+
if (!line.startsWith("n/")) return false;
|
|
11735
|
+
const file = line.slice(1);
|
|
11736
|
+
if (!names.has(basename(file))) return false;
|
|
11737
|
+
return wanted.has(canonicalViewerDbPath(file));
|
|
11738
|
+
})
|
|
11739
|
+
};
|
|
11740
|
+
}
|
|
11741
|
+
/** The database a Viewer reports in its prompt-pack profile, or null when it reports none. */
|
|
11742
|
+
async function reportedDatabase(address, fetchImpl) {
|
|
11743
|
+
try {
|
|
11744
|
+
const response = await fetchImpl(viewerUrl(address, "/api/prompt-pack-profile"), { signal: AbortSignal.timeout(1e3) });
|
|
11745
|
+
if (!response.ok) return null;
|
|
11746
|
+
const payload = await response.json();
|
|
11747
|
+
return typeof payload?.db_path === "string" && payload.db_path ? payload.db_path : null;
|
|
11748
|
+
} catch {
|
|
11749
|
+
return null;
|
|
11750
|
+
}
|
|
11751
|
+
}
|
|
11752
|
+
function lockProof(pid, identity, dbPath) {
|
|
11753
|
+
const owner = readViewerWriterLockOwner(dbPath);
|
|
11754
|
+
return owner?.pid === pid && owner.db_path === canonicalViewerDbPath(dbPath) && owner.started === identity.started && isViewerWriterLockHeld(dbPath);
|
|
11755
|
+
}
|
|
11756
|
+
function refuse(reason) {
|
|
11757
|
+
return {
|
|
11758
|
+
ok: false,
|
|
11759
|
+
reason
|
|
11760
|
+
};
|
|
11761
|
+
}
|
|
11762
|
+
/** The listener and open-file proofs of a Viewer from before the lock; a reason when they fail. */
|
|
11763
|
+
function openDatabaseProof(pid, port, canonical) {
|
|
11764
|
+
const listener = listeningPid(port);
|
|
11765
|
+
if (!listener.ok) return listener.reason;
|
|
11766
|
+
if (listener.pid !== pid) return `it is not the process listening on port ${port}`;
|
|
11767
|
+
const open = holdsDatabaseOpen(pid, canonical);
|
|
11768
|
+
if (!open.ok) return open.reason;
|
|
11769
|
+
return open.open ? null : "it does not have the database open";
|
|
11770
|
+
}
|
|
11771
|
+
/** Why the process is not a codemem Viewer listening at its address, or null when it is. */
|
|
11772
|
+
function viewerProcessFailure(pid, identity, port, platform) {
|
|
11773
|
+
if (!identity) return "its process could not be identified";
|
|
11774
|
+
if (!isLikelyViewerCommand(identity.command)) return "its process does not look like a codemem viewer";
|
|
11775
|
+
if (platform === "win32") return null;
|
|
11776
|
+
const listener = listeningPid(port);
|
|
11777
|
+
if (!listener.ok) return listener.reason;
|
|
11778
|
+
return listener.pid === pid ? null : `it is not the process listening on port ${port}`;
|
|
11779
|
+
}
|
|
11780
|
+
function verified(pid, identity, proof, recheck) {
|
|
11781
|
+
return {
|
|
11782
|
+
ok: true,
|
|
11783
|
+
viewer: {
|
|
11784
|
+
pid,
|
|
11785
|
+
identity,
|
|
11786
|
+
proof,
|
|
11787
|
+
recheck
|
|
11788
|
+
}
|
|
11789
|
+
};
|
|
11790
|
+
}
|
|
11791
|
+
/**
|
|
11792
|
+
* Why a Viewer without the lock cannot be serving this database, or null. Releases
|
|
11793
|
+
* from before the lock cannot read a transitioned store, so for one the lock is the
|
|
11794
|
+
* only proof. A store whose names cannot be read is refused rather than guessed.
|
|
11795
|
+
*/
|
|
11796
|
+
function transitionedStoreRefusal(dbPath) {
|
|
11797
|
+
if (!existsSync(dbPath)) return null;
|
|
11798
|
+
try {
|
|
11799
|
+
if (readDeviceStorageShape(dbPath) === "legacy") return null;
|
|
11800
|
+
return "it does not hold the database's lock, and only a Viewer that holds it can serve this database's storage format";
|
|
11801
|
+
} catch (error) {
|
|
11802
|
+
return `the database's storage format could not be read (${error instanceof Error ? error.message : String(error)})`;
|
|
11803
|
+
}
|
|
11804
|
+
}
|
|
11805
|
+
/** The proof for a Viewer from before the lock: listener, open database, reported database. */
|
|
11806
|
+
async function verifyPreLockViewer(pid, identity, address, canonical, fetchImpl) {
|
|
11807
|
+
const failed = openDatabaseProof(pid, address.port, canonical);
|
|
11808
|
+
if (failed) return refuse(failed);
|
|
11809
|
+
const reported = await reportedDatabase(address, fetchImpl);
|
|
11810
|
+
if (reported === null) return refuse("it did not report which database it serves");
|
|
11811
|
+
if (canonicalViewerDbPath(reported) !== canonical) return refuse("it reports another database");
|
|
11812
|
+
return verified(pid, identity, "open-database", () => {
|
|
11813
|
+
return openDatabaseProof(pid, address.port, canonical) === null;
|
|
11814
|
+
});
|
|
11815
|
+
}
|
|
11816
|
+
/**
|
|
11817
|
+
* Whether the codemem Viewer `pid`, answering at `address`, serves the database at
|
|
11818
|
+
* `dbPath`. Returns what to recheck before each signal, or why it is refused.
|
|
11819
|
+
*/
|
|
11820
|
+
async function verifyViewerForDatabase(pid, address, dbPath, deps = {}) {
|
|
11821
|
+
const identity = (deps.readIdentity ?? readProcessIdentity)(pid);
|
|
11822
|
+
const platform = deps.platform ?? process.platform;
|
|
11823
|
+
const notViewer = viewerProcessFailure(pid, identity, address.port, platform);
|
|
11824
|
+
if (notViewer || !identity) return refuse(notViewer ?? "its process could not be identified");
|
|
11825
|
+
const owner = readViewerWriterLockOwner(dbPath);
|
|
11826
|
+
if (owner?.pid === pid) {
|
|
11827
|
+
if (!lockProof(pid, identity, dbPath)) return refuse("the database's lock record names it with another start time or database, or the lock is not held");
|
|
11828
|
+
return verified(pid, identity, "lock", () => lockProof(pid, identity, dbPath));
|
|
11829
|
+
}
|
|
11830
|
+
if (owner && isViewerWriterLockHeld(dbPath)) return refuse("another process holds the database's lock");
|
|
11831
|
+
const format = transitionedStoreRefusal(dbPath);
|
|
11832
|
+
if (format) return refuse(format);
|
|
11833
|
+
if (platform === "win32") return verified(pid, identity, "unidentifiable-platform", () => true);
|
|
11834
|
+
return verifyPreLockViewer(pid, identity, address, canonicalViewerDbPath(dbPath), deps.fetch ?? fetch);
|
|
11835
|
+
}
|
|
11836
|
+
//#endregion
|
|
11837
|
+
//#region src/commands/serve.ts
|
|
11838
|
+
function extractViewerPid(payload) {
|
|
11839
|
+
if (!payload || typeof payload !== "object") return null;
|
|
11840
|
+
const rawPid = payload.viewer_pid;
|
|
11841
|
+
if (typeof rawPid !== "number" || !Number.isFinite(rawPid) || rawPid <= 0) return null;
|
|
11842
|
+
return Math.trunc(rawPid);
|
|
11843
|
+
}
|
|
11844
|
+
function isLocalHost(host) {
|
|
11845
|
+
const normalized = host.trim().toLowerCase();
|
|
11846
|
+
return normalized === "127.0.0.1" || normalized === "localhost" || normalized === "::1" || normalized === "0.0.0.0" || normalized === "::";
|
|
11847
|
+
}
|
|
11848
|
+
function isLoopbackOnlyHost(host) {
|
|
11849
|
+
return isLoopbackHost(host);
|
|
11850
|
+
}
|
|
11851
|
+
function warnIfViewerExposed(host, port) {
|
|
11852
|
+
if (isLoopbackOnlyHost(host)) return;
|
|
11853
|
+
p.log.warn(`Viewer bound to ${host}:${port}. codemem's viewer trust model assumes localhost-only access; do not expose it through a reverse proxy, tunnel, or public bind without adding your own auth layer.`);
|
|
11854
|
+
}
|
|
11855
|
+
function prepareViewerDatabase(dbPath) {
|
|
11856
|
+
return initDatabase(dbPath ?? void 0).path;
|
|
11410
11857
|
}
|
|
11411
11858
|
function pidFilePath(dbPath) {
|
|
11412
|
-
return join(
|
|
11859
|
+
return join(viewerRuntimeDir(dbPath), "viewer.pid");
|
|
11413
11860
|
}
|
|
11414
11861
|
function maintenanceWorkerPidFilePath(dbPath) {
|
|
11415
|
-
return join(
|
|
11862
|
+
return join(viewerRuntimeDir(dbPath), "maintenance-worker.pid");
|
|
11416
11863
|
}
|
|
11417
|
-
function
|
|
11418
|
-
const pidPath = maintenanceWorkerPidFilePath(dbPath);
|
|
11864
|
+
function readMaintenanceWorkerPidRecordAt(pidPath) {
|
|
11419
11865
|
if (!existsSync(pidPath)) return null;
|
|
11420
11866
|
const raw = readFileSync(pidPath, "utf-8").trim();
|
|
11421
11867
|
try {
|
|
@@ -11449,8 +11895,20 @@ function commandHasExactDbPath(command, dbPath) {
|
|
|
11449
11895
|
const escapedPath = escapeRegExp(resolveDbPath(dbPath));
|
|
11450
11896
|
return new RegExp(`(?:^|\\s)--db-path(?:=|\\s+)${escapedPath}(?:\\s|$)`).test(command);
|
|
11451
11897
|
}
|
|
11898
|
+
/** The PID records for this database: the current location, then where earlier releases wrote it. */
|
|
11899
|
+
function readViewerPidRecords(dbPath) {
|
|
11900
|
+
return viewerPidFilePaths(resolveDbPath(dbPath)).flatMap((path) => {
|
|
11901
|
+
const record = readViewerPidRecordAt(path);
|
|
11902
|
+
return record ? [{
|
|
11903
|
+
path,
|
|
11904
|
+
record
|
|
11905
|
+
}] : [];
|
|
11906
|
+
});
|
|
11907
|
+
}
|
|
11452
11908
|
function readViewerPidRecord(dbPath) {
|
|
11453
|
-
|
|
11909
|
+
return readViewerPidRecordAt(pidFilePath(dbPath));
|
|
11910
|
+
}
|
|
11911
|
+
function readViewerPidRecordAt(pidPath) {
|
|
11454
11912
|
if (!existsSync(pidPath)) return null;
|
|
11455
11913
|
const parsed = parseViewerPidRecord(readFileSync(pidPath, "utf-8"));
|
|
11456
11914
|
if (parsed.state === "valid") return parsed.record;
|
|
@@ -11472,13 +11930,14 @@ function normalizeViewerHost(host) {
|
|
|
11472
11930
|
if (normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1" || normalized === "[::1]") return "loopback";
|
|
11473
11931
|
return normalized;
|
|
11474
11932
|
}
|
|
11933
|
+
/** A live Viewer for this database at another address, from either PID record location. */
|
|
11475
11934
|
async function findRuntimeViewerConflict(dbPath, target) {
|
|
11476
|
-
const record
|
|
11477
|
-
|
|
11478
|
-
|
|
11479
|
-
|
|
11480
|
-
|
|
11481
|
-
return
|
|
11935
|
+
for (const { record } of readViewerPidRecords(dbPath)) {
|
|
11936
|
+
if (normalizeViewerHost(record.host) === normalizeViewerHost(target.host) && record.port === target.port) continue;
|
|
11937
|
+
if (!isProcessRunning(record.pid)) continue;
|
|
11938
|
+
if (await respondsLikeCodememViewer(record)) return record;
|
|
11939
|
+
}
|
|
11940
|
+
return null;
|
|
11482
11941
|
}
|
|
11483
11942
|
function isProcessRunning(pid) {
|
|
11484
11943
|
try {
|
|
@@ -11496,7 +11955,7 @@ async function respondsLikeCodememViewer(record, fetchImpl = fetch) {
|
|
|
11496
11955
|
}
|
|
11497
11956
|
async function lookupViewerPidFromStats(host, port) {
|
|
11498
11957
|
try {
|
|
11499
|
-
const res = await fetch(viewerUrl({
|
|
11958
|
+
const res = await fetch(viewerUrl$1({
|
|
11500
11959
|
host,
|
|
11501
11960
|
port
|
|
11502
11961
|
}, "/api/stats"), { signal: AbortSignal.timeout(1e3) });
|
|
@@ -11531,42 +11990,116 @@ async function waitForProcessExit(pid, timeoutMs = 3e4) {
|
|
|
11531
11990
|
}
|
|
11532
11991
|
return !isProcessRunning(pid);
|
|
11533
11992
|
}
|
|
11534
|
-
|
|
11993
|
+
/**
|
|
11994
|
+
* Whether `pid` still names the verified process. The proof that chose it runs first and
|
|
11995
|
+
* the identity read last, so nothing is checked between that read and the signal.
|
|
11996
|
+
* "changed" means the pid names another process now: the verified one has exited.
|
|
11997
|
+
*/
|
|
11998
|
+
function confirmVerified(viewer, readIdentity) {
|
|
11999
|
+
const proven = viewer.recheck();
|
|
12000
|
+
const now = readIdentity(viewer.pid);
|
|
12001
|
+
if (now && !sameProcess(now, viewer.identity)) return "changed";
|
|
12002
|
+
if (!proven) return "not-target";
|
|
12003
|
+
return now ? "same" : "unknown";
|
|
12004
|
+
}
|
|
12005
|
+
/**
|
|
12006
|
+
* Stops a verified process: SIGTERM, then after the wait SIGKILL. Each signal is sent only
|
|
12007
|
+
* when the pid still names the process as it was verified and it still passes its proof.
|
|
12008
|
+
* A process that exited during the wait, whose pid may name another process now, is
|
|
12009
|
+
* never signalled again.
|
|
12010
|
+
*/
|
|
12011
|
+
async function terminateVerified(viewer, options = {}) {
|
|
12012
|
+
const readIdentity = options.readIdentity ?? readProcessIdentity;
|
|
12013
|
+
const { pid } = viewer;
|
|
12014
|
+
if (confirmVerified(viewer, readIdentity) !== "same") return {
|
|
12015
|
+
signalled: false,
|
|
12016
|
+
stopped: false
|
|
12017
|
+
};
|
|
11535
12018
|
try {
|
|
11536
12019
|
process.kill(pid, "SIGTERM");
|
|
11537
12020
|
} catch {
|
|
11538
|
-
return
|
|
12021
|
+
return {
|
|
12022
|
+
signalled: true,
|
|
12023
|
+
stopped: true
|
|
12024
|
+
};
|
|
11539
12025
|
}
|
|
11540
|
-
if (await waitForProcessExit(pid,
|
|
12026
|
+
if (await waitForProcessExit(pid, options.gracefulMs ?? 3e4)) return {
|
|
12027
|
+
signalled: true,
|
|
12028
|
+
stopped: true
|
|
12029
|
+
};
|
|
12030
|
+
const confirmation = confirmVerified(viewer, readIdentity);
|
|
12031
|
+
if (confirmation === "changed") return {
|
|
12032
|
+
signalled: true,
|
|
12033
|
+
stopped: true
|
|
12034
|
+
};
|
|
12035
|
+
if (confirmation !== "same") return {
|
|
12036
|
+
signalled: true,
|
|
12037
|
+
stopped: false
|
|
12038
|
+
};
|
|
11541
12039
|
try {
|
|
11542
12040
|
process.kill(pid, "SIGKILL");
|
|
11543
12041
|
} catch {
|
|
11544
|
-
return
|
|
12042
|
+
return {
|
|
12043
|
+
signalled: true,
|
|
12044
|
+
stopped: true
|
|
12045
|
+
};
|
|
12046
|
+
}
|
|
12047
|
+
return {
|
|
12048
|
+
signalled: true,
|
|
12049
|
+
stopped: await waitForProcessExit(pid, options.forceMs ?? 5e3)
|
|
12050
|
+
};
|
|
12051
|
+
}
|
|
12052
|
+
/**
|
|
12053
|
+
* Stops a process its caller has just checked, such as a maintenance worker. Its identity
|
|
12054
|
+
* is read once before SIGTERM and must match again before SIGKILL; when it cannot be read,
|
|
12055
|
+
* SIGTERM is the only signal.
|
|
12056
|
+
*/
|
|
12057
|
+
async function terminateProcessPid(pid, options = {}) {
|
|
12058
|
+
const identity = (options.readIdentity ?? readProcessIdentity)(pid);
|
|
12059
|
+
if (!identity) {
|
|
12060
|
+
try {
|
|
12061
|
+
process.kill(pid, "SIGTERM");
|
|
12062
|
+
} catch {
|
|
12063
|
+
return true;
|
|
12064
|
+
}
|
|
12065
|
+
return waitForProcessExit(pid, options.gracefulMs ?? 3e4);
|
|
11545
12066
|
}
|
|
11546
|
-
return
|
|
12067
|
+
return (await terminateVerified({
|
|
12068
|
+
pid,
|
|
12069
|
+
identity,
|
|
12070
|
+
recheck: () => true
|
|
12071
|
+
}, options)).stopped;
|
|
11547
12072
|
}
|
|
11548
|
-
|
|
11549
|
-
|
|
12073
|
+
/** Stops a Viewer that `verifyViewerForDatabase` verified. */
|
|
12074
|
+
async function terminateVerifiedViewer(viewer, options = {}) {
|
|
12075
|
+
return terminateVerified(viewer, options);
|
|
11550
12076
|
}
|
|
12077
|
+
/**
|
|
12078
|
+
* Stops a leftover maintenance worker for this database. Reads the current PID
|
|
12079
|
+
* record and the one an older release left beside the database path as given,
|
|
12080
|
+
* where a worker that outlived a Viewer started through a symlink recorded
|
|
12081
|
+
* itself. False when a recorded worker is not trusted or did not stop.
|
|
12082
|
+
*/
|
|
11551
12083
|
async function terminateTrustedMaintenanceWorker(dbPath, timeouts = {}) {
|
|
11552
|
-
const
|
|
11553
|
-
|
|
12084
|
+
const paths = [.../* @__PURE__ */ new Set([maintenanceWorkerPidFilePath(dbPath), join(dirname(resolveDbPath(dbPath)), "maintenance-worker.pid")])];
|
|
12085
|
+
let allStopped = true;
|
|
12086
|
+
for (const pidPath of paths) if (!await terminateRecordedMaintenanceWorker(pidPath, dbPath, timeouts)) allStopped = false;
|
|
12087
|
+
return allStopped;
|
|
12088
|
+
}
|
|
12089
|
+
async function terminateRecordedMaintenanceWorker(pidPath, dbPath, timeouts) {
|
|
12090
|
+
const record = readMaintenanceWorkerPidRecordAt(pidPath);
|
|
11554
12091
|
if (!record) return true;
|
|
11555
|
-
const
|
|
11556
|
-
if (record.dbPath && record.dbPath
|
|
12092
|
+
const isThisDb = (path) => path !== null && canonicalViewerDbPath(path) === canonicalViewerDbPath(dbPath);
|
|
12093
|
+
if (record.dbPath && !isThisDb(record.dbPath)) return false;
|
|
11557
12094
|
if (!isProcessRunning(record.pid)) {
|
|
11558
|
-
|
|
11559
|
-
rmSync(pidPath);
|
|
11560
|
-
} catch {}
|
|
12095
|
+
removeFile(pidPath);
|
|
11561
12096
|
return true;
|
|
11562
12097
|
}
|
|
11563
12098
|
const command = readProcessCommand(record.pid);
|
|
11564
12099
|
if (!command || !isLikelyMaintenanceWorkerCommand(command)) return false;
|
|
11565
|
-
if (record.dbPath
|
|
12100
|
+
if (!isThisDb(record.dbPath) || !commandHasExactDbPath(command, record.dbPath)) return false;
|
|
11566
12101
|
const stopped = await terminateProcessPid(record.pid, timeouts);
|
|
11567
|
-
if (stopped)
|
|
11568
|
-
rmSync(pidPath);
|
|
11569
|
-
} catch {}
|
|
12102
|
+
if (stopped) removeFile(pidPath);
|
|
11570
12103
|
return stopped;
|
|
11571
12104
|
}
|
|
11572
12105
|
async function waitForPortRelease(host, port, timeoutMs = 1e4) {
|
|
@@ -11577,49 +12110,91 @@ async function waitForPortRelease(host, port, timeoutMs = 1e4) {
|
|
|
11577
12110
|
}
|
|
11578
12111
|
return false;
|
|
11579
12112
|
}
|
|
11580
|
-
|
|
11581
|
-
|
|
11582
|
-
|
|
11583
|
-
|
|
11584
|
-
|
|
11585
|
-
|
|
11586
|
-
|
|
11587
|
-
|
|
11588
|
-
|
|
11589
|
-
|
|
11590
|
-
|
|
11591
|
-
|
|
11592
|
-
|
|
11593
|
-
|
|
11594
|
-
|
|
11595
|
-
|
|
11596
|
-
|
|
11597
|
-
|
|
12113
|
+
var viewerLockDependencies = {
|
|
12114
|
+
isLockHeld: isViewerWriterLockHeld,
|
|
12115
|
+
isLiveViewer: (owner) => respondsLikeCodememViewer({
|
|
12116
|
+
pid: owner.pid,
|
|
12117
|
+
host: owner.host,
|
|
12118
|
+
port: owner.port
|
|
12119
|
+
}),
|
|
12120
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
12121
|
+
};
|
|
12122
|
+
/**
|
|
12123
|
+
* The codemem Viewer to consider at `target`: on macOS and Linux the process listening on
|
|
12124
|
+
* the port, else the pid its answer names, which verification then refuses because it is
|
|
12125
|
+
* not the listener. Null when no codemem Viewer is there, so that an unrelated listener is
|
|
12126
|
+
* not reported.
|
|
12127
|
+
*/
|
|
12128
|
+
async function viewerCandidateAt(target, options) {
|
|
12129
|
+
if (!isLocalHost(target.host)) return null;
|
|
12130
|
+
const statsPid = await lookupViewerPidFromStats(target.host, target.port);
|
|
12131
|
+
if ((options.platform ?? process.platform) === "win32") return statsPid ? { pid: statsPid } : null;
|
|
12132
|
+
const listener = listeningPid(target.port);
|
|
12133
|
+
const pid = (listener.ok ? listener.pid : null) ?? statsPid;
|
|
12134
|
+
if (!pid) return null;
|
|
12135
|
+
const command = (options.readIdentity ?? readProcessIdentity)(pid)?.command;
|
|
12136
|
+
return command && isLikelyViewerCommand(command) ? { pid } : null;
|
|
12137
|
+
}
|
|
12138
|
+
/** Verifies that Viewer `pid` at `address` serves this database, then stops it. */
|
|
12139
|
+
async function stopVerifiedViewer(pid, address, dbPath, options) {
|
|
12140
|
+
const verification = await verifyViewerForDatabase(pid, address, dbPath, options);
|
|
12141
|
+
if (!verification.ok) return { refused: {
|
|
12142
|
+
pid,
|
|
12143
|
+
...address,
|
|
12144
|
+
reason: verification.reason
|
|
12145
|
+
} };
|
|
12146
|
+
const termination = await terminateVerifiedViewer(verification.viewer, options);
|
|
12147
|
+
if (!termination.signalled) return { refused: {
|
|
12148
|
+
pid,
|
|
12149
|
+
...address,
|
|
12150
|
+
reason: "its process changed or stopped serving the database before it could be signalled"
|
|
12151
|
+
} };
|
|
12152
|
+
return {
|
|
12153
|
+
stopped: termination.stopped,
|
|
12154
|
+
pid
|
|
12155
|
+
};
|
|
12156
|
+
}
|
|
12157
|
+
/** Tries the Viewers this database's PID records name; the first stopped, or the first refusal. */
|
|
12158
|
+
async function stopRecordedViewers(dbPath, options) {
|
|
12159
|
+
let refusal = null;
|
|
12160
|
+
for (const { path, record } of readViewerPidRecords(dbPath)) {
|
|
12161
|
+
if (!isLocalHost(record.host) || !await respondsLikeCodememViewer(record)) continue;
|
|
12162
|
+
const attempt = await stopVerifiedViewer(record.pid, record, dbPath, options);
|
|
12163
|
+
if ("refused" in attempt) {
|
|
12164
|
+
refusal ??= attempt;
|
|
12165
|
+
continue;
|
|
12166
|
+
}
|
|
12167
|
+
if (attempt.stopped) removeFile(path);
|
|
12168
|
+
return attempt;
|
|
11598
12169
|
}
|
|
11599
|
-
|
|
11600
|
-
|
|
11601
|
-
|
|
11602
|
-
|
|
11603
|
-
const
|
|
11604
|
-
if (
|
|
11605
|
-
|
|
11606
|
-
|
|
11607
|
-
}
|
|
11608
|
-
|
|
11609
|
-
|
|
11610
|
-
|
|
11611
|
-
|
|
11612
|
-
} else return {
|
|
12170
|
+
return refusal;
|
|
12171
|
+
}
|
|
12172
|
+
async function stopExistingViewer(dbPath, target, options = {}) {
|
|
12173
|
+
const candidate = await viewerCandidateAt(target, options);
|
|
12174
|
+
const atPort = candidate ? await stopVerifiedViewer(candidate.pid, target, dbPath, options) : null;
|
|
12175
|
+
if (atPort && !("refused" in atPort)) {
|
|
12176
|
+
if (atPort.stopped) removeStoppedViewerPidRecords(dbPath, atPort.pid);
|
|
12177
|
+
return atPort;
|
|
12178
|
+
}
|
|
12179
|
+
const recorded = await stopRecordedViewers(dbPath, options);
|
|
12180
|
+
if (recorded && !("refused" in recorded)) return recorded;
|
|
12181
|
+
const refusal = atPort ?? recorded;
|
|
12182
|
+
return {
|
|
11613
12183
|
stopped: false,
|
|
11614
|
-
pid: null
|
|
12184
|
+
pid: null,
|
|
12185
|
+
...refusal && "refused" in refusal ? { refused: refusal.refused } : {}
|
|
11615
12186
|
};
|
|
12187
|
+
}
|
|
12188
|
+
function removeFile(path) {
|
|
11616
12189
|
try {
|
|
11617
|
-
rmSync(
|
|
12190
|
+
rmSync(path);
|
|
11618
12191
|
} catch {}
|
|
11619
|
-
|
|
11620
|
-
|
|
11621
|
-
|
|
11622
|
-
|
|
12192
|
+
}
|
|
12193
|
+
/** After a stop: the current PID record, and an older release's record for the same process. */
|
|
12194
|
+
function removeStoppedViewerPidRecords(dbPath, pid) {
|
|
12195
|
+
const [current, ...older] = viewerPidFilePaths(resolveDbPath(dbPath));
|
|
12196
|
+
if (current) removeFile(current);
|
|
12197
|
+
for (const path of older) if (readViewerPidRecordAt(path)?.pid === pid) removeFile(path);
|
|
11623
12198
|
}
|
|
11624
12199
|
function buildForegroundRunnerArgs(scriptPath, invocation, execArgv = process.execArgv) {
|
|
11625
12200
|
const args = [
|
|
@@ -11746,13 +12321,22 @@ async function nativeRuntimeAllowsServeStart(invocation) {
|
|
|
11746
12321
|
if (invocation.mode !== "start" && invocation.mode !== "restart") return true;
|
|
11747
12322
|
const preflight = await preflightServeNativeRuntime(invocation);
|
|
11748
12323
|
if (preflight.state === "already_running") {
|
|
11749
|
-
|
|
12324
|
+
const message = `Viewer already running at http://${invocation.host}:${invocation.port}`;
|
|
12325
|
+
p.log.warn(message);
|
|
12326
|
+
reportViewerStartup({
|
|
12327
|
+
state: "failed",
|
|
12328
|
+
message
|
|
12329
|
+
});
|
|
11750
12330
|
if (!invocation.background) process.exitCode = 1;
|
|
11751
12331
|
return false;
|
|
11752
12332
|
}
|
|
11753
12333
|
if (preflight.state === "ready") return true;
|
|
11754
12334
|
p.intro("codemem viewer");
|
|
11755
12335
|
for (const line of preflight.diagnostics) p.log.error(line);
|
|
12336
|
+
reportViewerStartup({
|
|
12337
|
+
state: "failed",
|
|
12338
|
+
message: preflight.diagnostics.join(" ")
|
|
12339
|
+
});
|
|
11756
12340
|
process.exitCode = 1;
|
|
11757
12341
|
return false;
|
|
11758
12342
|
}
|
|
@@ -11811,22 +12395,37 @@ async function startBackgroundViewer(invocation) {
|
|
|
11811
12395
|
const child = spawn(process.execPath, buildForegroundRunnerArgs(scriptPath, invocation), {
|
|
11812
12396
|
cwd: process.cwd(),
|
|
11813
12397
|
detached: true,
|
|
11814
|
-
stdio:
|
|
12398
|
+
stdio: [
|
|
12399
|
+
"ignore",
|
|
12400
|
+
"ignore",
|
|
12401
|
+
"ignore",
|
|
12402
|
+
"ipc"
|
|
12403
|
+
],
|
|
11815
12404
|
env: {
|
|
11816
12405
|
...process.env,
|
|
11817
12406
|
...invocation.dbPath ? { CODEMEM_DB: invocation.dbPath } : {},
|
|
11818
|
-
...invocation.configPath ? { CODEMEM_CONFIG: invocation.configPath } : {}
|
|
12407
|
+
...invocation.configPath ? { CODEMEM_CONFIG: invocation.configPath } : {},
|
|
12408
|
+
[VIEWER_STARTUP_REPORT_ENV]: "1"
|
|
11819
12409
|
}
|
|
11820
12410
|
});
|
|
12411
|
+
const startup = await waitForViewerStartup(child, BACKGROUND_STARTUP_WAIT_MS);
|
|
11821
12412
|
child.unref();
|
|
11822
|
-
if (invocation.dbPath) writeFileSync(pidFilePath(invocation.dbPath), JSON.stringify({
|
|
11823
|
-
pid: child.pid,
|
|
11824
|
-
host: invocation.host,
|
|
11825
|
-
port: invocation.port
|
|
11826
|
-
}), "utf-8");
|
|
11827
12413
|
p.intro("codemem viewer");
|
|
11828
|
-
|
|
12414
|
+
if (startup.state === "failed") {
|
|
12415
|
+
p.log.error(startup.message);
|
|
12416
|
+
process.exitCode = 1;
|
|
12417
|
+
return;
|
|
12418
|
+
}
|
|
12419
|
+
const url = `http://${invocation.host}:${invocation.port}`;
|
|
12420
|
+
p.outro(startup.state === "listening" ? `Viewer started in background (pid ${child.pid}) at ${url}` : `Viewer is starting in background (pid ${child.pid}) at ${url}`);
|
|
11829
12421
|
}
|
|
12422
|
+
/**
|
|
12423
|
+
* How long a background start waits for the Viewer's startup result. It covers
|
|
12424
|
+
* the Viewer's own wait for a releasing lock holder and stays under the plugin's
|
|
12425
|
+
* default 20-second command timeout. A Viewer that holds the lock but is still
|
|
12426
|
+
* preparing its database at that point counts as starting.
|
|
12427
|
+
*/
|
|
12428
|
+
var BACKGROUND_STARTUP_WAIT_MS = 15e3;
|
|
11830
12429
|
function startRawEventProcessing(dbPath, store, observer, createInbox) {
|
|
11831
12430
|
const sweeper = new RawEventSweeper(store, { observer });
|
|
11832
12431
|
const observerRuntime = new ObserverRuntimeController(observer, sweeper, () => new ObserverClient());
|
|
@@ -12051,6 +12650,8 @@ async function callMemoryToolForHost(store, name, args, caller) {
|
|
|
12051
12650
|
const { callCodememToolLocally } = await import("@codemem/mcp");
|
|
12052
12651
|
return callCodememToolLocally(store, name, args, caller);
|
|
12053
12652
|
}
|
|
12653
|
+
/** How often the running service checks Team setup completions with the coordinator. */
|
|
12654
|
+
var TEAM_SETUP_RECONCILIATION_INTERVAL_MS = 3e5;
|
|
12054
12655
|
function foregroundAppOptions(store, rawEventOptions, options) {
|
|
12055
12656
|
return {
|
|
12056
12657
|
accountLink: options.accountLink.options,
|
|
@@ -12058,7 +12659,8 @@ function foregroundAppOptions(store, rawEventOptions, options) {
|
|
|
12058
12659
|
syncReachability: options.relay?.reachability,
|
|
12059
12660
|
...rawEventOptions,
|
|
12060
12661
|
...options.coordinatorRefresh,
|
|
12061
|
-
getSyncRuntimeStatus: () => options.syncRuntimeStatus
|
|
12662
|
+
getSyncRuntimeStatus: () => options.syncRuntimeStatus,
|
|
12663
|
+
teamSetupReconciliationIntervalMs: TEAM_SETUP_RECONCILIATION_INTERVAL_MS
|
|
12062
12664
|
};
|
|
12063
12665
|
}
|
|
12064
12666
|
function createBoundApp(createApp, options, listener) {
|
|
@@ -12079,34 +12681,97 @@ function createBoundApp(createApp, options, listener) {
|
|
|
12079
12681
|
}
|
|
12080
12682
|
};
|
|
12081
12683
|
}
|
|
12082
|
-
|
|
12083
|
-
|
|
12084
|
-
|
|
12085
|
-
|
|
12086
|
-
|
|
12087
|
-
|
|
12088
|
-
|
|
12089
|
-
|
|
12090
|
-
|
|
12091
|
-
const
|
|
12684
|
+
/** Referenced for the process lifetime, so its connection, and the lock, stay open. */
|
|
12685
|
+
var heldViewerWriterLock = null;
|
|
12686
|
+
/**
|
|
12687
|
+
* Takes the database's Viewer lock, then stops a leftover maintenance worker;
|
|
12688
|
+
* false when another Viewer holds the lock. The pid file check before it is
|
|
12689
|
+
* advisory and can race. The lock cannot, so two Viewers never interleave Team
|
|
12690
|
+
* setup changes whose locks only work inside one process.
|
|
12691
|
+
*/
|
|
12692
|
+
async function takeOverViewerRuntime(dbPath, target) {
|
|
12693
|
+
const claim = await claimViewerWriterLock(dbPath, target, viewerLockDependencies);
|
|
12694
|
+
if (claim.status === "refused") {
|
|
12695
|
+
reportViewerStartup({
|
|
12696
|
+
state: "failed",
|
|
12697
|
+
message: claim.message
|
|
12698
|
+
});
|
|
12699
|
+
p.intro("codemem viewer");
|
|
12700
|
+
p.log.error(claim.message);
|
|
12701
|
+
process.exitCode = 1;
|
|
12702
|
+
return false;
|
|
12703
|
+
}
|
|
12704
|
+
heldViewerWriterLock = claim.lock;
|
|
12705
|
+
reportViewerStartup({ state: "lock_acquired" });
|
|
12092
12706
|
if (!await terminateTrustedMaintenanceWorker(dbPath, {
|
|
12093
12707
|
gracefulMs: 1e3,
|
|
12094
12708
|
forceMs: 5e3
|
|
12095
12709
|
})) p.log.warn("Existing maintenance worker is not trusted or did not stop; starting viewer anyway");
|
|
12096
|
-
|
|
12097
|
-
|
|
12710
|
+
return true;
|
|
12711
|
+
}
|
|
12712
|
+
/**
|
|
12713
|
+
* Open the Viewer's store. When sqlite-vec cannot load, the Viewer starts with embeddings
|
|
12714
|
+
* disabled. The Viewer answers requests while packs are built, so its store assembles
|
|
12715
|
+
* packs in a worker thread.
|
|
12716
|
+
*/
|
|
12717
|
+
async function openViewerStore(dbPath, server) {
|
|
12098
12718
|
let store;
|
|
12099
12719
|
try {
|
|
12100
|
-
store = getStore();
|
|
12720
|
+
store = server.getStore();
|
|
12101
12721
|
} catch (err) {
|
|
12102
12722
|
if (isEmbeddingDisabled() || !isSqliteVecLoadFailure(err)) throw err;
|
|
12103
12723
|
p.log.warn("sqlite-vec failed to load; retrying viewer startup with embeddings disabled");
|
|
12104
|
-
for (const line of sqliteVecFailureDiagnostics(err,
|
|
12724
|
+
for (const line of sqliteVecFailureDiagnostics(err, dbPath)) p.log.warn(`sqlite-vec diagnostic: ${line}`);
|
|
12105
12725
|
process.env.CODEMEM_EMBEDDING_DISABLED = "1";
|
|
12106
|
-
await closeStoreAsync();
|
|
12107
|
-
store = getStore();
|
|
12726
|
+
await server.closeStoreAsync();
|
|
12727
|
+
store = server.getStore();
|
|
12108
12728
|
p.log.warn("Embeddings disabled for this viewer process; raw-event ingestion remains active.");
|
|
12109
12729
|
}
|
|
12730
|
+
store.enablePackWorker();
|
|
12731
|
+
recordConfiguredCoordinatorHistory(store.db, readCoordinatorSyncConfig());
|
|
12732
|
+
return store;
|
|
12733
|
+
}
|
|
12734
|
+
/**
|
|
12735
|
+
* The sync listener is network-facing, so it runs on the guarded server. Its
|
|
12736
|
+
* routes and any direct Noise streams share one request limiter.
|
|
12737
|
+
*/
|
|
12738
|
+
function syncListenerOptions(serverModule, appOpts, syncConfig) {
|
|
12739
|
+
const limiter = serverModule.createSyncListenerLimiter();
|
|
12740
|
+
const syncApp = serverModule.createSyncApp({
|
|
12741
|
+
...appOpts,
|
|
12742
|
+
syncRequestRateLimit: { limiter }
|
|
12743
|
+
});
|
|
12744
|
+
const keysDir = process.env.CODEMEM_KEYS_DIR?.trim() || void 0;
|
|
12745
|
+
return {
|
|
12746
|
+
fetch: syncApp.fetch,
|
|
12747
|
+
hostname: syncConfig.syncHost,
|
|
12748
|
+
port: syncConfig.syncPort,
|
|
12749
|
+
createServer: serverModule.createGuardedSyncServer({
|
|
12750
|
+
limiter,
|
|
12751
|
+
directNoise: {
|
|
12752
|
+
storeFactory: appOpts.storeFactory,
|
|
12753
|
+
keysDir
|
|
12754
|
+
}
|
|
12755
|
+
})
|
|
12756
|
+
};
|
|
12757
|
+
}
|
|
12758
|
+
async function startForegroundViewer(invocation) {
|
|
12759
|
+
const serverModule = await import("@codemem/server");
|
|
12760
|
+
const { createApp, closeStoreAsync, createViewerRawEventInbox, getStore } = serverModule;
|
|
12761
|
+
const createRawEventInbox = createViewerRawEventInbox;
|
|
12762
|
+
const coordinatorMaintenanceDependencies = createServeCoordinatorMaintenanceDependencies(serverModule);
|
|
12763
|
+
const { serve } = await import("@hono/node-server");
|
|
12764
|
+
if (invocation.dbPath) process.env.CODEMEM_DB = invocation.dbPath;
|
|
12765
|
+
if (invocation.configPath) process.env.CODEMEM_CONFIG = invocation.configPath;
|
|
12766
|
+
warnIfViewerExposed(invocation.host, invocation.port);
|
|
12767
|
+
const dbPath = resolveDbPath(invocation.dbPath ?? void 0);
|
|
12768
|
+
if (!await takeOverViewerRuntime(dbPath, invocation)) return;
|
|
12769
|
+
const preparedDb = prepareViewerDatabase(invocation.dbPath);
|
|
12770
|
+
const observer = new ObserverClient();
|
|
12771
|
+
const store = await openViewerStore(dbPath, {
|
|
12772
|
+
getStore,
|
|
12773
|
+
closeStoreAsync
|
|
12774
|
+
});
|
|
12110
12775
|
const rawEventProcessing = startRawEventProcessing(dbPath, store, observer, createRawEventInbox);
|
|
12111
12776
|
const syncAbort = new AbortController();
|
|
12112
12777
|
const config = invocation.configPath ? readCodememConfigFileAtPath(invocation.configPath) : readCodememConfigFile();
|
|
@@ -12143,11 +12808,7 @@ async function startForegroundViewer(invocation) {
|
|
|
12143
12808
|
let syncServer = null;
|
|
12144
12809
|
let syncListenerReady = false;
|
|
12145
12810
|
if (syncEnabled) {
|
|
12146
|
-
syncServer = serve({
|
|
12147
|
-
fetch: createSyncApp(appOpts).fetch,
|
|
12148
|
-
hostname: syncConfig.syncHost,
|
|
12149
|
-
port: syncConfig.syncPort
|
|
12150
|
-
}, (info) => {
|
|
12811
|
+
syncServer = serve(syncListenerOptions(serverModule, appOpts, syncConfig), (info) => {
|
|
12151
12812
|
syncListenerReady = true;
|
|
12152
12813
|
p.log.step(`Sync protocol listening on http://${info.address}:${info.port}`);
|
|
12153
12814
|
});
|
|
@@ -12168,6 +12829,7 @@ async function startForegroundViewer(invocation) {
|
|
|
12168
12829
|
preparedDb,
|
|
12169
12830
|
info
|
|
12170
12831
|
});
|
|
12832
|
+
reportViewerStartup({ state: "listening" });
|
|
12171
12833
|
maintenanceWorker = startMaintenanceWorkerProcess(invocation);
|
|
12172
12834
|
if (syncEnabled) scheduleServeSyncDaemon({
|
|
12173
12835
|
invocation,
|
|
@@ -12181,8 +12843,7 @@ async function startForegroundViewer(invocation) {
|
|
|
12181
12843
|
});
|
|
12182
12844
|
});
|
|
12183
12845
|
server.on("error", (err) => {
|
|
12184
|
-
|
|
12185
|
-
else p.log.error(err.message);
|
|
12846
|
+
reportViewerListenError(err, invocation);
|
|
12186
12847
|
requestShutdown(1);
|
|
12187
12848
|
});
|
|
12188
12849
|
let shutdownPromise;
|
|
@@ -12215,6 +12876,7 @@ async function startForegroundViewer(invocation) {
|
|
|
12215
12876
|
shutdownExitCode = 1;
|
|
12216
12877
|
logViewerShutdownError(error);
|
|
12217
12878
|
}
|
|
12879
|
+
heldViewerWriterLock?.release();
|
|
12218
12880
|
}
|
|
12219
12881
|
process.exit(shutdownExitCode);
|
|
12220
12882
|
};
|
|
@@ -12227,6 +12889,22 @@ async function startForegroundViewer(invocation) {
|
|
|
12227
12889
|
process.on("SIGINT", () => requestShutdown());
|
|
12228
12890
|
process.on("SIGTERM", () => requestShutdown());
|
|
12229
12891
|
}
|
|
12892
|
+
function reportViewerListenError(err, invocation) {
|
|
12893
|
+
if (err.code === "EADDRINUSE") {
|
|
12894
|
+
const message = `Viewer already running at http://${invocation.host}:${invocation.port}`;
|
|
12895
|
+
p.log.warn(message);
|
|
12896
|
+
reportViewerStartup({
|
|
12897
|
+
state: "failed",
|
|
12898
|
+
message
|
|
12899
|
+
});
|
|
12900
|
+
return;
|
|
12901
|
+
}
|
|
12902
|
+
p.log.error(err.message);
|
|
12903
|
+
reportViewerStartup({
|
|
12904
|
+
state: "failed",
|
|
12905
|
+
message: err.message
|
|
12906
|
+
});
|
|
12907
|
+
}
|
|
12230
12908
|
function logViewerShutdownError(error) {
|
|
12231
12909
|
p.log.error(error instanceof Error ? error.message : String(error));
|
|
12232
12910
|
}
|
|
@@ -12261,60 +12939,97 @@ async function runServeInvocation(invocation, dependencies = {
|
|
|
12261
12939
|
port: invocation.port
|
|
12262
12940
|
});
|
|
12263
12941
|
if (runtimeConflict) {
|
|
12942
|
+
const message = `Database runtime at ${viewerRuntimeDir(dbPath)} is already managed by viewer ${runtimeConflict.host}:${runtimeConflict.port} (pid ${runtimeConflict.pid})`;
|
|
12264
12943
|
p.intro("codemem viewer");
|
|
12265
|
-
p.log.error(
|
|
12944
|
+
p.log.error(message);
|
|
12266
12945
|
p.log.info("Use the matching --host/--port, stop the existing viewer first, or use a separate db/runtime folder for another viewer.");
|
|
12946
|
+
reportViewerStartup({
|
|
12947
|
+
state: "failed",
|
|
12948
|
+
message
|
|
12949
|
+
});
|
|
12267
12950
|
process.exitCode = 1;
|
|
12268
12951
|
return;
|
|
12269
12952
|
}
|
|
12270
12953
|
if (!await dependencies.nativeRuntimeAllowsServeStart(invocation)) return;
|
|
12271
|
-
if (invocation.mode === "stop" || invocation.mode === "restart")
|
|
12272
|
-
|
|
12273
|
-
|
|
12274
|
-
|
|
12275
|
-
|
|
12276
|
-
|
|
12277
|
-
|
|
12278
|
-
|
|
12279
|
-
|
|
12280
|
-
|
|
12281
|
-
|
|
12282
|
-
|
|
12283
|
-
|
|
12284
|
-
|
|
12285
|
-
|
|
12286
|
-
|
|
12287
|
-
|
|
12288
|
-
|
|
12289
|
-
|
|
12290
|
-
|
|
12291
|
-
|
|
12292
|
-
|
|
12293
|
-
|
|
12294
|
-
|
|
12295
|
-
|
|
12296
|
-
gracefulMs: 5e3,
|
|
12297
|
-
forceMs: 5e3
|
|
12298
|
-
});
|
|
12299
|
-
p.intro("codemem viewer");
|
|
12300
|
-
if (!workerStopped) p.log.warn("Maintenance worker pidfile exists but did not match trusted worker command");
|
|
12301
|
-
p.outro("No background viewer found");
|
|
12302
|
-
return;
|
|
12303
|
-
}
|
|
12954
|
+
if ((invocation.mode === "stop" || invocation.mode === "restart") && !await stopBeforeStart(invocation, dbPath, dependencies.stopExistingViewer)) return;
|
|
12955
|
+
if (invocation.mode === "start" || invocation.mode === "restart") await (dependencies.startViewer ?? startViewer)({
|
|
12956
|
+
...invocation,
|
|
12957
|
+
dbPath
|
|
12958
|
+
});
|
|
12959
|
+
}
|
|
12960
|
+
async function stopMaintenanceWorkerAfterStop(dbPath) {
|
|
12961
|
+
if (!await terminateTrustedMaintenanceWorker(dbPath, {
|
|
12962
|
+
gracefulMs: 5e3,
|
|
12963
|
+
forceMs: 5e3
|
|
12964
|
+
})) p.log.warn("Maintenance worker pidfile exists but did not match trusted worker command");
|
|
12965
|
+
}
|
|
12966
|
+
/**
|
|
12967
|
+
* Stops the existing Viewer for `stop` and `restart`. Returns true when a restart
|
|
12968
|
+
* may start the new Viewer: the old one has stopped, its port is free or reported,
|
|
12969
|
+
* and it no longer holds the database's lock.
|
|
12970
|
+
*/
|
|
12971
|
+
async function stopBeforeStart(invocation, dbPath, stop) {
|
|
12972
|
+
const result = await stop(dbPath, {
|
|
12973
|
+
host: invocation.host,
|
|
12974
|
+
port: invocation.port
|
|
12975
|
+
});
|
|
12976
|
+
if (result.refused) {
|
|
12977
|
+
reportRefusedViewer(dbPath, result.refused);
|
|
12978
|
+
return false;
|
|
12304
12979
|
}
|
|
12305
|
-
if (
|
|
12306
|
-
|
|
12307
|
-
|
|
12308
|
-
|
|
12309
|
-
|
|
12310
|
-
|
|
12311
|
-
|
|
12312
|
-
|
|
12313
|
-
|
|
12314
|
-
|
|
12315
|
-
|
|
12316
|
-
|
|
12980
|
+
if (result.pid && !result.stopped) {
|
|
12981
|
+
p.intro("codemem viewer");
|
|
12982
|
+
p.log.error(`Viewer is still shutting down (pid ${result.pid})`);
|
|
12983
|
+
process.exitCode = 1;
|
|
12984
|
+
return false;
|
|
12985
|
+
}
|
|
12986
|
+
if (!result.stopped) {
|
|
12987
|
+
if (invocation.mode !== "stop") return true;
|
|
12988
|
+
p.intro("codemem viewer");
|
|
12989
|
+
await stopMaintenanceWorkerAfterStop(dbPath);
|
|
12990
|
+
reportNothingStopped(dbPath);
|
|
12991
|
+
return false;
|
|
12992
|
+
}
|
|
12993
|
+
p.intro("codemem viewer");
|
|
12994
|
+
p.log.success(`Stopped viewer${result.pid ? ` (pid ${result.pid})` : ""}`);
|
|
12995
|
+
await stopMaintenanceWorkerAfterStop(dbPath);
|
|
12996
|
+
if (invocation.mode === "stop") {
|
|
12997
|
+
p.outro("done");
|
|
12998
|
+
return false;
|
|
12999
|
+
}
|
|
13000
|
+
return waitForStoppedViewer(invocation, dbPath);
|
|
13001
|
+
}
|
|
13002
|
+
/** A Viewer that answered but was not shown to serve this database. Nothing was signalled. */
|
|
13003
|
+
function reportRefusedViewer(dbPath, viewer) {
|
|
13004
|
+
p.intro("codemem viewer");
|
|
13005
|
+
p.log.error(`The viewer at ${viewer.host}:${viewer.port} (pid ${viewer.pid}) could not be confirmed to serve ${dbPath}: ${viewer.reason}. Nothing was stopped.`);
|
|
13006
|
+
p.log.info("It may serve another database, or come from a release that does not record its database. Pass the --db-path and --port it was started with, or stop it yourself after checking it.");
|
|
13007
|
+
process.exitCode = 1;
|
|
13008
|
+
}
|
|
13009
|
+
/**
|
|
13010
|
+
* After a stop that found no Viewer to stop: whether something still holds the
|
|
13011
|
+
* database. The owner record is only reported; nothing is signalled because of it.
|
|
13012
|
+
*/
|
|
13013
|
+
function reportNothingStopped(dbPath) {
|
|
13014
|
+
if (!isViewerWriterLockHeld(dbPath)) {
|
|
13015
|
+
p.outro("No background viewer found");
|
|
13016
|
+
return;
|
|
12317
13017
|
}
|
|
13018
|
+
const owner = readViewerWriterLockOwner(dbPath);
|
|
13019
|
+
const holder = owner ? `pid ${owner.pid}, unverified` : "no holder recorded";
|
|
13020
|
+
p.log.error(`The database is locked by another process (${holder}).`);
|
|
13021
|
+
p.log.info(viewerLockHolderHint(owner));
|
|
13022
|
+
process.exitCode = 1;
|
|
13023
|
+
}
|
|
13024
|
+
async function waitForStoppedViewer(invocation, dbPath) {
|
|
13025
|
+
if (!await waitForPortRelease(invocation.host, invocation.port)) p.log.warn(`Port ${invocation.port} still in use after stop — restart may fail`);
|
|
13026
|
+
if (await waitForViewerWriterLockRelease(dbPath, viewerLockDependencies, { timeoutMs: 1e4 })) return true;
|
|
13027
|
+
p.log.error(`The stopped viewer still holds ${dbPath}; not starting another one.`);
|
|
13028
|
+
process.exitCode = 1;
|
|
13029
|
+
return false;
|
|
13030
|
+
}
|
|
13031
|
+
function startViewer(invocation) {
|
|
13032
|
+
return invocation.background ? startBackgroundViewer(invocation) : startForegroundViewer(invocation);
|
|
12318
13033
|
}
|
|
12319
13034
|
var serveCmd = new Command("serve").configureHelp(helpStyle).description("Run the local service (compatibility entrypoint; see service)").argument("[action]", "lifecycle action (start|stop|restart)");
|
|
12320
13035
|
addDbOption(serveCmd);
|
|
@@ -12340,7 +13055,12 @@ var serveCommand = serveCmd.action(async (action, opts) => {
|
|
|
12340
13055
|
}
|
|
12341
13056
|
await runServeInvocation(resolveServeInvocation(normalizedAction, opts));
|
|
12342
13057
|
} catch (err) {
|
|
12343
|
-
|
|
13058
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
13059
|
+
p.log.error(message);
|
|
13060
|
+
reportViewerStartup({
|
|
13061
|
+
state: "failed",
|
|
13062
|
+
message
|
|
13063
|
+
});
|
|
12344
13064
|
process.exitCode = 1;
|
|
12345
13065
|
}
|
|
12346
13066
|
});
|
|
@@ -12438,22 +13158,59 @@ function boundAttention(items) {
|
|
|
12438
13158
|
message: item.message.slice(0, 500)
|
|
12439
13159
|
}));
|
|
12440
13160
|
}
|
|
12441
|
-
|
|
12442
|
-
|
|
12443
|
-
|
|
12444
|
-
if (
|
|
13161
|
+
/** How long before `checkedAt` an ISO time was, such as "3h"; null when unparseable. */
|
|
13162
|
+
function ageBefore(iso, checkedAt) {
|
|
13163
|
+
const parsed = Date.parse(iso ?? "");
|
|
13164
|
+
if (!Number.isFinite(parsed)) return null;
|
|
13165
|
+
const seconds = Math.max(0, Math.round((checkedAt.getTime() - parsed) / 1e3));
|
|
13166
|
+
if (seconds < 60) return `${seconds}s`;
|
|
13167
|
+
const minutes = Math.round(seconds / 60);
|
|
13168
|
+
if (minutes < 60) return `${minutes}m`;
|
|
13169
|
+
const hours = Math.round(minutes / 60);
|
|
13170
|
+
if (hours < 48) return `${hours}h`;
|
|
13171
|
+
return `${Math.round(hours / 24)}d`;
|
|
13172
|
+
}
|
|
13173
|
+
function plural(count, singular, pluralForm) {
|
|
13174
|
+
return `${count} ${count === 1 ? singular : pluralForm}`;
|
|
13175
|
+
}
|
|
13176
|
+
/**
|
|
13177
|
+
* A daemon error is a sync error only while no peer has synced since. When peers
|
|
13178
|
+
* sync after it, the error came from other daemon work, such as coordinator
|
|
13179
|
+
* maintenance, and syncing itself works.
|
|
13180
|
+
*/
|
|
13181
|
+
function peersSyncedSinceDaemonError(sync) {
|
|
13182
|
+
const errorAt = Date.parse(sync.daemon_error_at ?? "");
|
|
13183
|
+
const syncedAt = Date.parse(sync.latest_peer_sync_at ?? "");
|
|
13184
|
+
return Number.isFinite(errorAt) && Number.isFinite(syncedAt) && syncedAt > errorAt;
|
|
13185
|
+
}
|
|
13186
|
+
function projectDaemonError(sync, checkedAt, attention) {
|
|
13187
|
+
const age = ageBefore(sync.daemon_error_at, checkedAt);
|
|
13188
|
+
const when = age ? ` ${age} ago` : "";
|
|
13189
|
+
if (!sync.needs_attention && peersSyncedSinceDaemonError(sync)) {
|
|
13190
|
+
const syncedAge = ageBefore(sync.latest_peer_sync_at, checkedAt);
|
|
12445
13191
|
attention.push({
|
|
12446
|
-
code: "
|
|
12447
|
-
severity: "
|
|
12448
|
-
message:
|
|
13192
|
+
code: "sync_daemon_warning",
|
|
13193
|
+
severity: "warning",
|
|
13194
|
+
message: `The sync daemon reported a problem${when}, but peers have synced since (last ${syncedAge} ago); run \`codemem sync doctor\``
|
|
12449
13195
|
});
|
|
12450
|
-
return "
|
|
13196
|
+
return "degraded";
|
|
12451
13197
|
}
|
|
13198
|
+
attention.push({
|
|
13199
|
+
code: "sync_daemon_error",
|
|
13200
|
+
severity: "error",
|
|
13201
|
+
message: sync.needs_attention ? "Sync requires attention; run `codemem sync doctor`" : `Sync has not succeeded since an error${when}; run \`codemem sync doctor\``
|
|
13202
|
+
});
|
|
13203
|
+
return "error";
|
|
13204
|
+
}
|
|
13205
|
+
function projectSync(enabled, snapshot, checkedAt, attention) {
|
|
13206
|
+
if (!enabled) return "disabled";
|
|
13207
|
+
if (!snapshot) return "unknown";
|
|
13208
|
+
if (snapshot.sync.daemon_error || snapshot.sync.needs_attention) return projectDaemonError(snapshot.sync, checkedAt, attention);
|
|
12452
13209
|
if (snapshot.sync.peer_errors > 0) {
|
|
12453
13210
|
attention.push({
|
|
12454
13211
|
code: "sync_degraded",
|
|
12455
13212
|
severity: "warning",
|
|
12456
|
-
message: "
|
|
13213
|
+
message: `${plural(snapshot.sync.peer_errors, "peer", "peers")} failed the last sync attempt; run \`codemem sync peers\` or \`codemem sync doctor\``
|
|
12457
13214
|
});
|
|
12458
13215
|
return "degraded";
|
|
12459
13216
|
}
|
|
@@ -12501,7 +13258,7 @@ function addRuntimeAttention(runtime, attention) {
|
|
|
12501
13258
|
}[runtime.attention_code]
|
|
12502
13259
|
});
|
|
12503
13260
|
}
|
|
12504
|
-
function projectDatabaseSubsystems(snapshot, configuredObserver, attention) {
|
|
13261
|
+
function projectDatabaseSubsystems(snapshot, configuredObserver, checkedAt, attention) {
|
|
12505
13262
|
if (!snapshot) return {
|
|
12506
13263
|
maintenance: { state: "unknown" },
|
|
12507
13264
|
semantic_index: { state: "unknown" },
|
|
@@ -12567,7 +13324,7 @@ function projectDatabaseSubsystems(snapshot, configuredObserver, attention) {
|
|
|
12567
13324
|
attention.push({
|
|
12568
13325
|
code: "observer_recent_failures",
|
|
12569
13326
|
severity: "warning",
|
|
12570
|
-
message:
|
|
13327
|
+
message: recentObserverFailureMessage(snapshot.observer, checkedAt)
|
|
12571
13328
|
});
|
|
12572
13329
|
}
|
|
12573
13330
|
return {
|
|
@@ -12580,6 +13337,12 @@ function projectDatabaseSubsystems(snapshot, configuredObserver, attention) {
|
|
|
12580
13337
|
observer: { state: observerState }
|
|
12581
13338
|
};
|
|
12582
13339
|
}
|
|
13340
|
+
/** "Recently" is the last 24 hours; the message says how many failed and how long ago. */
|
|
13341
|
+
function recentObserverFailureMessage(observer, checkedAt) {
|
|
13342
|
+
const failed = plural(observer.recent_failed_batches, "observer batch", "observer batches");
|
|
13343
|
+
const age = ageBefore(observer.latest_recent_failure_at, checkedAt);
|
|
13344
|
+
return `${failed} failed in the last 24 hours${age ? `, most recently ${age} ago` : ""}. Run \`codemem diagnostics capture status\``;
|
|
13345
|
+
}
|
|
12583
13346
|
async function collectStatusReport(opts, deps = defaultDependencies) {
|
|
12584
13347
|
const checkedAt = deps.now();
|
|
12585
13348
|
const config = deps.readConfig(opts.config);
|
|
@@ -12603,16 +13366,15 @@ async function collectStatusReport(opts, deps = defaultDependencies) {
|
|
|
12603
13366
|
db.close();
|
|
12604
13367
|
}
|
|
12605
13368
|
}
|
|
12606
|
-
const
|
|
12607
|
-
const runtime = await observeViewerRuntime(parseViewerPidRecord(deps.exists(pidPath) ? deps.readText(pidPath) : null), {
|
|
13369
|
+
const runtime = await observeViewerRuntime(parseViewerPidRecord(readViewerPidFile(dbPath, (path) => deps.exists(path) ? deps.readText(path) : null)), {
|
|
12608
13370
|
fetch: deps.fetch,
|
|
12609
13371
|
isProcessRunning: deps.isProcessRunning
|
|
12610
13372
|
}, viewerDefaultTarget(deps.env));
|
|
12611
13373
|
const attention = [];
|
|
12612
13374
|
addDatabaseAttention(databaseState, attention);
|
|
12613
13375
|
addRuntimeAttention(runtime, attention);
|
|
12614
|
-
const sync = projectSync(syncEnabled(config, deps.env), snapshot, attention);
|
|
12615
|
-
const subsystems = projectDatabaseSubsystems(snapshot, observerConfigured(config, deps.env), attention);
|
|
13376
|
+
const sync = projectSync(syncEnabled(config, deps.env), snapshot, checkedAt, attention);
|
|
13377
|
+
const subsystems = projectDatabaseSubsystems(snapshot, observerConfigured(config, deps.env), checkedAt, attention);
|
|
12616
13378
|
const ok = !attention.some((item) => item.severity === "error");
|
|
12617
13379
|
const boundedAttention = boundAttention(attention);
|
|
12618
13380
|
return {
|
|
@@ -14488,6 +15250,225 @@ var setupCommand = new Command("setup").configureHelp(helpStyle).description("In
|
|
|
14488
15250
|
runSetup(opts);
|
|
14489
15251
|
});
|
|
14490
15252
|
//#endregion
|
|
15253
|
+
//#region src/commands/sync-bootstrap.ts
|
|
15254
|
+
function reportError(opts, code, message, exitCode = 1) {
|
|
15255
|
+
if (opts.json) {
|
|
15256
|
+
emitJsonError(code, message, exitCode);
|
|
15257
|
+
return;
|
|
15258
|
+
}
|
|
15259
|
+
p.log.error(message);
|
|
15260
|
+
process.exitCode = exitCode;
|
|
15261
|
+
}
|
|
15262
|
+
/** The pinned peer to bootstrap from, or null after reporting why it can't be used. */
|
|
15263
|
+
function bootstrapPeer(store, peerDeviceId, opts) {
|
|
15264
|
+
const peer = drizzle(store.db, { schema }).select().from(schema.syncPeers).where(eq(schema.syncPeers.peer_device_id, peerDeviceId)).get();
|
|
15265
|
+
if (!peer) {
|
|
15266
|
+
reportError(opts, "peer_not_found", `Peer ${peerDeviceId} not found in sync_peers.`);
|
|
15267
|
+
return null;
|
|
15268
|
+
}
|
|
15269
|
+
if (!peer.pinned_fingerprint) {
|
|
15270
|
+
reportError(opts, "peer_not_pinned", `Peer ${peerDeviceId} has no pinned fingerprint. Accept it first.`);
|
|
15271
|
+
return null;
|
|
15272
|
+
}
|
|
15273
|
+
return peer;
|
|
15274
|
+
}
|
|
15275
|
+
/**
|
|
15276
|
+
* Once direct Noise is on, a peer pinned by fingerprint alone can't be
|
|
15277
|
+
* reached. Say how to fix it before any request, including a grant's, leaves.
|
|
15278
|
+
*/
|
|
15279
|
+
function peerKeyReady(store, peer, opts, transport) {
|
|
15280
|
+
if (!peerTransportBlocker(store.db, peer.peer_device_id, transport.directNoise)) return true;
|
|
15281
|
+
reportError(opts, "peer_key_missing", `Peer ${peer.name || peer.peer_device_id} has no saved public key, so codemem can't open an encrypted connection to it. On that device, run \`codemem sync pair --payload-only\` and save the output. Then run \`codemem sync pair --accept-file <file>\` here. The payload's public key must match the pinned fingerprint.`);
|
|
15282
|
+
return false;
|
|
15283
|
+
}
|
|
15284
|
+
function localStateIsClean(store, opts) {
|
|
15285
|
+
if (opts.force) return true;
|
|
15286
|
+
const dirty = hasUnsyncedSharedMemoryChanges(store.db);
|
|
15287
|
+
if (!dirty.dirty) return true;
|
|
15288
|
+
reportError(opts, "local_unsynced_changes", `${dirty.count} unsynced shared memory change(s) would be lost. Use --force to override.`);
|
|
15289
|
+
return false;
|
|
15290
|
+
}
|
|
15291
|
+
function resetBoundary(payload) {
|
|
15292
|
+
const reset = payload.sync_reset;
|
|
15293
|
+
if (!reset || typeof reset.generation !== "number" || typeof reset.snapshot_id !== "string") return null;
|
|
15294
|
+
return {
|
|
15295
|
+
generation: reset.generation,
|
|
15296
|
+
snapshot_id: reset.snapshot_id,
|
|
15297
|
+
baseline_cursor: typeof reset.baseline_cursor === "string" ? reset.baseline_cursor : null
|
|
15298
|
+
};
|
|
15299
|
+
}
|
|
15300
|
+
/** Asks one address for its status. Returns the reset boundary or why the address failed. */
|
|
15301
|
+
async function statusAt(context, peer, baseUrl) {
|
|
15302
|
+
const statusUrl = `${baseUrl}/v1/status`;
|
|
15303
|
+
const headers = buildDirectPeerAuthHeaders({
|
|
15304
|
+
deviceId: context.deviceId,
|
|
15305
|
+
recipientId: context.peerDeviceId,
|
|
15306
|
+
dbPath: context.store.dbPath,
|
|
15307
|
+
method: "GET",
|
|
15308
|
+
url: statusUrl,
|
|
15309
|
+
bodyBytes: Buffer.alloc(0),
|
|
15310
|
+
bootstrapGrantId: context.opts.bootstrapGrant,
|
|
15311
|
+
keysDir: context.keysDir
|
|
15312
|
+
});
|
|
15313
|
+
try {
|
|
15314
|
+
const [code, payload] = await context.execute("GET", statusUrl, {
|
|
15315
|
+
operation: "status",
|
|
15316
|
+
headers
|
|
15317
|
+
});
|
|
15318
|
+
if (code !== 200 || !payload) return `status ${code}`;
|
|
15319
|
+
if (payload.fingerprint !== peer.pinned_fingerprint) return "fingerprint mismatch";
|
|
15320
|
+
return resetBoundary(payload) ?? "missing sync_reset boundary";
|
|
15321
|
+
} catch (err) {
|
|
15322
|
+
return err instanceof Error ? err.message : String(err);
|
|
15323
|
+
}
|
|
15324
|
+
}
|
|
15325
|
+
async function findBoundary(context, peer, addresses) {
|
|
15326
|
+
const addressResults = [];
|
|
15327
|
+
for (const address of addresses) {
|
|
15328
|
+
const baseUrl = buildBaseUrl(address);
|
|
15329
|
+
if (!baseUrl) continue;
|
|
15330
|
+
const outcome = await statusAt(context, peer, baseUrl);
|
|
15331
|
+
if (typeof outcome === "string") {
|
|
15332
|
+
addressResults.push({
|
|
15333
|
+
address: baseUrl,
|
|
15334
|
+
result: outcome
|
|
15335
|
+
});
|
|
15336
|
+
continue;
|
|
15337
|
+
}
|
|
15338
|
+
addressResults.push({
|
|
15339
|
+
address: baseUrl,
|
|
15340
|
+
result: "ok"
|
|
15341
|
+
});
|
|
15342
|
+
return {
|
|
15343
|
+
boundary: outcome,
|
|
15344
|
+
baseUrl,
|
|
15345
|
+
addressResults
|
|
15346
|
+
};
|
|
15347
|
+
}
|
|
15348
|
+
return {
|
|
15349
|
+
boundary: null,
|
|
15350
|
+
baseUrl: "",
|
|
15351
|
+
addressResults
|
|
15352
|
+
};
|
|
15353
|
+
}
|
|
15354
|
+
function reportUnreachable(opts, addressResults) {
|
|
15355
|
+
const summary = addressResults.map((r) => `${r.address}: ${r.result}`).join("; ");
|
|
15356
|
+
const detail = summary ? `no reachable peer with valid reset boundary. Tried: ${summary}` : "peer unreachable or missing reset boundary";
|
|
15357
|
+
if (opts.json) console.log(JSON.stringify({
|
|
15358
|
+
ok: false,
|
|
15359
|
+
error: detail,
|
|
15360
|
+
addresses: addressResults
|
|
15361
|
+
}));
|
|
15362
|
+
else p.log.error(detail);
|
|
15363
|
+
process.exitCode = 1;
|
|
15364
|
+
}
|
|
15365
|
+
function reportApplied(opts, result) {
|
|
15366
|
+
if (opts.json) {
|
|
15367
|
+
const { ok, applied, deleted } = result;
|
|
15368
|
+
console.log(JSON.stringify({
|
|
15369
|
+
ok,
|
|
15370
|
+
applied,
|
|
15371
|
+
deleted,
|
|
15372
|
+
error: result.error ?? null
|
|
15373
|
+
}));
|
|
15374
|
+
} else {
|
|
15375
|
+
if (result.ok) p.log.success(`Applied ${result.applied} memories (removed ${result.deleted} stale).`);
|
|
15376
|
+
else p.log.error(result.error || "Bootstrap apply failed.");
|
|
15377
|
+
p.outro(result.ok ? "Bootstrap complete" : "Bootstrap failed");
|
|
15378
|
+
}
|
|
15379
|
+
if (!result.ok) process.exitCode = 1;
|
|
15380
|
+
}
|
|
15381
|
+
async function copyFromPeer(context, peer, boundary, baseUrl) {
|
|
15382
|
+
const { opts, store, peerDeviceId } = context;
|
|
15383
|
+
if (!opts.json) {
|
|
15384
|
+
p.intro("codemem sync bootstrap");
|
|
15385
|
+
p.log.step(`Bootstrapping from ${peer.name || peerDeviceId}...`);
|
|
15386
|
+
}
|
|
15387
|
+
const resetInfo = {
|
|
15388
|
+
...boundary,
|
|
15389
|
+
retained_floor_cursor: null,
|
|
15390
|
+
reset_required: true,
|
|
15391
|
+
reason: "initial_bootstrap"
|
|
15392
|
+
};
|
|
15393
|
+
const { items } = await fetchAllSnapshotPages(baseUrl, resetInfo, context.deviceId, {
|
|
15394
|
+
keysDir: context.keysDir,
|
|
15395
|
+
dbPath: store.dbPath,
|
|
15396
|
+
bootstrapGrantId: opts.bootstrapGrant,
|
|
15397
|
+
recipientId: peerDeviceId,
|
|
15398
|
+
pageSize: Math.max(1, Number.parseInt(opts.pageSize, 10) || 2e3),
|
|
15399
|
+
requestExecutor: context.execute
|
|
15400
|
+
});
|
|
15401
|
+
reportApplied(opts, applyBootstrapSnapshot(store.db, peerDeviceId, items, resetInfo, store.scanner));
|
|
15402
|
+
}
|
|
15403
|
+
/**
|
|
15404
|
+
* Every request goes through the shared transport policy. A bootstrap grant
|
|
15405
|
+
* rides along so a noise_required seed can pin this device before Noise.
|
|
15406
|
+
*/
|
|
15407
|
+
function bootstrapExecutor(store, ids, opts, transport) {
|
|
15408
|
+
const grant = opts.bootstrapGrant?.trim();
|
|
15409
|
+
return peerTransportExecutor({
|
|
15410
|
+
db: store.db,
|
|
15411
|
+
peerDeviceId: ids.peerDeviceId,
|
|
15412
|
+
localDeviceId: ids.deviceId,
|
|
15413
|
+
keysDir: opts.keysDir,
|
|
15414
|
+
dbPath: store.dbPath,
|
|
15415
|
+
bootstrapGrantId: grant || void 0,
|
|
15416
|
+
...transport.directNoise
|
|
15417
|
+
});
|
|
15418
|
+
}
|
|
15419
|
+
async function bootstrapStore(store, peerDeviceId, opts, transport) {
|
|
15420
|
+
const peer = bootstrapPeer(store, peerDeviceId, opts);
|
|
15421
|
+
if (!peer || !peerKeyReady(store, peer, opts, transport)) return;
|
|
15422
|
+
if (!localStateIsClean(store, opts)) return;
|
|
15423
|
+
const keysDir = opts.keysDir ?? void 0;
|
|
15424
|
+
const [deviceId] = ensureDeviceIdentity(store.db, { keysDir });
|
|
15425
|
+
const addresses = JSON.parse(String(peer.addresses_json ?? "[]"));
|
|
15426
|
+
if (!addresses.length) {
|
|
15427
|
+
reportError(opts, "no_peer_addresses", "Peer has no known addresses. Run a sync first or add addresses.");
|
|
15428
|
+
return;
|
|
15429
|
+
}
|
|
15430
|
+
const context = {
|
|
15431
|
+
store,
|
|
15432
|
+
opts,
|
|
15433
|
+
peerDeviceId,
|
|
15434
|
+
deviceId,
|
|
15435
|
+
keysDir,
|
|
15436
|
+
execute: bootstrapExecutor(store, {
|
|
15437
|
+
peerDeviceId,
|
|
15438
|
+
deviceId
|
|
15439
|
+
}, opts, transport)
|
|
15440
|
+
};
|
|
15441
|
+
const found = await findBoundary(context, peer, addresses);
|
|
15442
|
+
if (!found.boundary || !found.baseUrl) {
|
|
15443
|
+
reportUnreachable(opts, found.addressResults);
|
|
15444
|
+
return;
|
|
15445
|
+
}
|
|
15446
|
+
await copyFromPeer(context, peer, found.boundary, found.baseUrl);
|
|
15447
|
+
}
|
|
15448
|
+
async function runSyncBootstrap(peerArg, opts, transport = {}) {
|
|
15449
|
+
const peerDeviceId = (peerArg || opts.peer || "").trim();
|
|
15450
|
+
if (!peerDeviceId) {
|
|
15451
|
+
reportError(opts, "usage_error", "missing required argument: <peer-device-id>", 2);
|
|
15452
|
+
return;
|
|
15453
|
+
}
|
|
15454
|
+
const store = new MemoryStore(resolveDbPath(resolveDbOpt(opts)));
|
|
15455
|
+
try {
|
|
15456
|
+
await bootstrapStore(store, peerDeviceId, opts, transport);
|
|
15457
|
+
} catch (error) {
|
|
15458
|
+
reportError(opts, error instanceof DeviceIdentityError ? error.code : "bootstrap_failed", error instanceof Error ? error.message : "Bootstrap failed");
|
|
15459
|
+
} finally {
|
|
15460
|
+
store.close();
|
|
15461
|
+
}
|
|
15462
|
+
}
|
|
15463
|
+
function buildSyncBootstrapCommand() {
|
|
15464
|
+
const command = new Command("bootstrap").configureHelp(helpStyle).description("Copy existing memories from a peer").argument("[peer-device-id]", "peer device ID to bootstrap from").option("--bootstrap-grant <grant-id>", "bootstrap grant id for seed-authorized bootstrap").option("--page-size <n>", "items per snapshot page (default: 2000)", "2000").option("--keys-dir <path>", "keys directory").option("--force", "skip dirty-local-state safety check");
|
|
15465
|
+
addDbOption(command);
|
|
15466
|
+
addJsonOption(command);
|
|
15467
|
+
command.addOption(new Option("--peer <device-id>", "peer device ID").hideHelp());
|
|
15468
|
+
command.action((peerArg, opts) => runSyncBootstrap(peerArg, opts));
|
|
15469
|
+
return command;
|
|
15470
|
+
}
|
|
15471
|
+
//#endregion
|
|
14491
15472
|
//#region src/commands/sync-helpers.ts
|
|
14492
15473
|
function formatSyncAttempt(row) {
|
|
14493
15474
|
const status = row.ok ? "ok" : "error";
|
|
@@ -14527,11 +15508,249 @@ function collectAdvertiseAddresses(explicitAddress, configuredHost, port, interf
|
|
|
14527
15508
|
return [...new Set(addresses)];
|
|
14528
15509
|
}
|
|
14529
15510
|
//#endregion
|
|
14530
|
-
//#region src/commands/sync-
|
|
14531
|
-
function
|
|
14532
|
-
|
|
14533
|
-
|
|
14534
|
-
|
|
15511
|
+
//#region src/commands/sync-migration.ts
|
|
15512
|
+
function reportText(report) {
|
|
15513
|
+
switch (report.state) {
|
|
15514
|
+
case "off": return "Project migration reporting is off.";
|
|
15515
|
+
case "not_applicable": return "This device uses basic peer sync. No Project migration is needed.";
|
|
15516
|
+
case "waiting_for_coordinator": return "Coordinator settings are missing. Existing sharing stays in effect.";
|
|
15517
|
+
case "local_report": {
|
|
15518
|
+
const counts = report.projects;
|
|
15519
|
+
return `${counts ? `Project candidates: ${counts.candidate_projects}. Projects in multiple setups: ${counts.multiple_sources}. Locally authored rows in those setups: ${counts.own_source_rows}.` : "The local Project inventory is unavailable."}\nLocal filter evidence: ${report.local_filters}. Other devices have not been checked.\n${report.maintenance_window}\n${report.storage_fence}`;
|
|
15520
|
+
}
|
|
15521
|
+
}
|
|
15522
|
+
}
|
|
15523
|
+
function migrationStatus(opts) {
|
|
15524
|
+
try {
|
|
15525
|
+
const config = readCodememConfigFileForMutation(opts.config ?? getCodememConfigPath());
|
|
15526
|
+
if (config.status !== "valid" && (config.status !== "missing" || opts.config || process.env.CODEMEM_CONFIG)) throw new Error("migration_config_unavailable");
|
|
15527
|
+
const db = connectReadOnly(resolveDbPath(resolveDbOpt(opts)));
|
|
15528
|
+
try {
|
|
15529
|
+
const report = readLocalProjectMigrationReport(db, config.status === "valid" ? config.data : {});
|
|
15530
|
+
if (opts.json) process.stdout.write(`${JSON.stringify(report)}\n`);
|
|
15531
|
+
else p.log.info(reportText(report));
|
|
15532
|
+
} finally {
|
|
15533
|
+
db.close();
|
|
15534
|
+
}
|
|
15535
|
+
} catch {
|
|
15536
|
+
const message = "Could not read the migration report. Check the database and configuration paths.";
|
|
15537
|
+
if (opts.json) emitJsonError("migration_report_unavailable", message);
|
|
15538
|
+
else {
|
|
15539
|
+
p.log.error(message);
|
|
15540
|
+
process.exitCode = 1;
|
|
15541
|
+
}
|
|
15542
|
+
}
|
|
15543
|
+
}
|
|
15544
|
+
function buildSyncMigrationCommand() {
|
|
15545
|
+
const status = new Command("status").configureHelp(helpStyle).description("Report local Project sharing data without changing access");
|
|
15546
|
+
addDbOption(status);
|
|
15547
|
+
addConfigOption(status);
|
|
15548
|
+
addJsonOption(status);
|
|
15549
|
+
status.action(migrationStatus);
|
|
15550
|
+
return new Command("migration").configureHelp(helpStyle).description("Inspect the Project sharing migration").addCommand(status);
|
|
15551
|
+
}
|
|
15552
|
+
//#endregion
|
|
15553
|
+
//#region src/commands/sync-pair.ts
|
|
15554
|
+
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.";
|
|
15555
|
+
var STALE_PIN = "Pairing payload conflicts with the existing trusted fingerprint for this device. Remove or repair the old peer before accepting this pairing payload.";
|
|
15556
|
+
/** A refusal with its JSON error code. Usage errors exit 2 in JSON mode, like other commands. */
|
|
15557
|
+
var PairRefusal = class extends Error {
|
|
15558
|
+
code;
|
|
15559
|
+
jsonExitCode;
|
|
15560
|
+
constructor(code, message, jsonExitCode = 1) {
|
|
15561
|
+
super(message);
|
|
15562
|
+
this.code = code;
|
|
15563
|
+
this.jsonExitCode = jsonExitCode;
|
|
15564
|
+
}
|
|
15565
|
+
};
|
|
15566
|
+
var usage = (message) => new PairRefusal("usage_error", message, 2);
|
|
15567
|
+
function reportFailure$1(opts, error) {
|
|
15568
|
+
const code = error instanceof PairRefusal || error instanceof DeviceIdentityError ? error.code : "pairing_failed";
|
|
15569
|
+
const message = error instanceof Error ? error.message : "Pairing failed";
|
|
15570
|
+
const jsonExitCode = error instanceof PairRefusal ? error.jsonExitCode : 1;
|
|
15571
|
+
if (opts.json) {
|
|
15572
|
+
emitJsonError(code, message, jsonExitCode);
|
|
15573
|
+
return;
|
|
15574
|
+
}
|
|
15575
|
+
p.log.error(message);
|
|
15576
|
+
process.exitCode = 1;
|
|
15577
|
+
}
|
|
15578
|
+
/** The filters the pair flags ask for, or null when no filter flag was given. */
|
|
15579
|
+
function pairFilterChange(opts) {
|
|
15580
|
+
if (opts.default) return {
|
|
15581
|
+
include: null,
|
|
15582
|
+
exclude: null
|
|
15583
|
+
};
|
|
15584
|
+
if (opts.all) return {
|
|
15585
|
+
include: [],
|
|
15586
|
+
exclude: []
|
|
15587
|
+
};
|
|
15588
|
+
if (!opts.include && !opts.exclude) return null;
|
|
15589
|
+
return {
|
|
15590
|
+
include: parseProjectList(opts.include),
|
|
15591
|
+
exclude: parseProjectList(opts.exclude)
|
|
15592
|
+
};
|
|
15593
|
+
}
|
|
15594
|
+
function checkModeFlags(opts) {
|
|
15595
|
+
const acceptRequested = opts.accept != null || opts.acceptFile != null;
|
|
15596
|
+
if (opts.payloadOnly && acceptRequested) throw usage("--payload-only cannot be combined with --accept or --accept-file");
|
|
15597
|
+
if (opts.accept && opts.acceptFile) throw usage("Use only one of --accept or --accept-file");
|
|
15598
|
+
}
|
|
15599
|
+
function readStdin() {
|
|
15600
|
+
return new Promise((resolve, reject) => {
|
|
15601
|
+
let text = "";
|
|
15602
|
+
process.stdin.setEncoding("utf8");
|
|
15603
|
+
process.stdin.on("data", (chunk) => {
|
|
15604
|
+
text += chunk;
|
|
15605
|
+
});
|
|
15606
|
+
process.stdin.on("end", () => resolve(text));
|
|
15607
|
+
process.stdin.on("error", reject);
|
|
15608
|
+
});
|
|
15609
|
+
}
|
|
15610
|
+
async function readAcceptText(opts) {
|
|
15611
|
+
if (!opts.acceptFile) return opts.accept;
|
|
15612
|
+
try {
|
|
15613
|
+
return opts.acceptFile === "-" ? await readStdin() : readFileSync(opts.acceptFile, "utf8");
|
|
15614
|
+
} catch (error) {
|
|
15615
|
+
const detail = error instanceof Error ? `: ${error.message}` : "";
|
|
15616
|
+
throw new PairRefusal("read_error", `Failed to read pairing payload from ${opts.acceptFile}${detail}`);
|
|
15617
|
+
}
|
|
15618
|
+
}
|
|
15619
|
+
function checkFilterFlags(opts, acceptText) {
|
|
15620
|
+
if ((opts.accept != null || opts.acceptFile != null) && !(acceptText ?? "").trim()) throw usage("Empty pairing payload; provide JSON via --accept or --accept-file");
|
|
15621
|
+
const filtered = opts.include || opts.exclude || opts.all || opts.default;
|
|
15622
|
+
if (!acceptText && filtered) throw usage("Project filters are outbound-only and must be set on the device running --accept");
|
|
15623
|
+
if (!acceptText?.trim()) return;
|
|
15624
|
+
if (opts.all && opts.default) throw usage("Use only one of --all or --default");
|
|
15625
|
+
if ((opts.all || opts.default) && (opts.include || opts.exclude)) throw usage("--include/--exclude cannot be combined with --all/--default");
|
|
15626
|
+
}
|
|
15627
|
+
function payloadAddresses(opts, payload) {
|
|
15628
|
+
if (opts.address?.trim()) return [opts.address.trim()];
|
|
15629
|
+
if (!Array.isArray(payload.addresses)) return [];
|
|
15630
|
+
return payload.addresses.filter((item) => typeof item === "string" && item.trim().length > 0).map((item) => item.trim());
|
|
15631
|
+
}
|
|
15632
|
+
function parsePayload(opts, text) {
|
|
15633
|
+
let payload;
|
|
15634
|
+
try {
|
|
15635
|
+
payload = JSON.parse(text);
|
|
15636
|
+
} catch (error) {
|
|
15637
|
+
throw new PairRefusal("invalid_payload", `Invalid pairing payload${error instanceof Error ? `: ${error.message}` : ""}`);
|
|
15638
|
+
}
|
|
15639
|
+
const deviceId = String(payload.device_id || "").trim();
|
|
15640
|
+
const fingerprint = String(payload.fingerprint || "").trim();
|
|
15641
|
+
const publicKey = String(payload.public_key || "").trim();
|
|
15642
|
+
const addresses = payloadAddresses(opts, payload);
|
|
15643
|
+
if (!deviceId || !fingerprint || !publicKey || addresses.length === 0) throw new PairRefusal("invalid_payload", "Pairing payload missing device_id, fingerprint, public_key, or addresses");
|
|
15644
|
+
if (fingerprintPublicKey(publicKey) !== fingerprint) throw new PairRefusal("fingerprint_mismatch", "Pairing payload fingerprint mismatch");
|
|
15645
|
+
return {
|
|
15646
|
+
payload,
|
|
15647
|
+
deviceId,
|
|
15648
|
+
fingerprint,
|
|
15649
|
+
publicKey,
|
|
15650
|
+
addresses
|
|
15651
|
+
};
|
|
15652
|
+
}
|
|
15653
|
+
function refuseStalePin(store, pairing) {
|
|
15654
|
+
const pinned = store.db.prepare("SELECT pinned_fingerprint FROM sync_peers WHERE peer_device_id = ?").pluck().get(pairing.deviceId);
|
|
15655
|
+
const existing = String(pinned ?? "").trim();
|
|
15656
|
+
if (existing && existing !== pairing.fingerprint) throw new PairRefusal("peer_conflict", STALE_PIN);
|
|
15657
|
+
}
|
|
15658
|
+
/**
|
|
15659
|
+
* The conflict check, the pin, the transport evidence and the checked filter
|
|
15660
|
+
* write share one immediate transaction. A re-pin from another process waits
|
|
15661
|
+
* for it or is seen by it, and a refused filter write rolls back the pin.
|
|
15662
|
+
*/
|
|
15663
|
+
function savePairing(store, opts, pairing) {
|
|
15664
|
+
const { deviceId } = pairing;
|
|
15665
|
+
const db = store.db;
|
|
15666
|
+
const change = pairFilterChange(opts);
|
|
15667
|
+
db.transaction(() => {
|
|
15668
|
+
refuseStalePin(store, pairing);
|
|
15669
|
+
if (change !== null && !peerProjectFilterChangeOnlyNarrows(db, deviceId, change) && !readPeerProjectFilterAuthority(db)) throw new Error(PAIR_FILTERS_REFUSED);
|
|
15670
|
+
updatePeerAddresses(db, deviceId, pairing.addresses, {
|
|
15671
|
+
name: opts.name,
|
|
15672
|
+
pinnedFingerprint: pairing.fingerprint,
|
|
15673
|
+
publicKey: pairing.publicKey,
|
|
15674
|
+
replaceTrust: true
|
|
15675
|
+
});
|
|
15676
|
+
recordPairingTransportEvidence(db, deviceId, pairing.payload);
|
|
15677
|
+
if (change && setPeerProjectFilterChecked(db, deviceId, change) !== "saved") throw new Error(PAIR_FILTERS_REFUSED);
|
|
15678
|
+
}).immediate();
|
|
15679
|
+
}
|
|
15680
|
+
function acceptPairing(store, opts, text) {
|
|
15681
|
+
const pairing = parsePayload(opts, text);
|
|
15682
|
+
savePairing(store, opts, pairing);
|
|
15683
|
+
if (opts.json) {
|
|
15684
|
+
console.log(JSON.stringify({
|
|
15685
|
+
ok: true,
|
|
15686
|
+
peer_device_id: pairing.deviceId
|
|
15687
|
+
}));
|
|
15688
|
+
return;
|
|
15689
|
+
}
|
|
15690
|
+
p.log.success(`Paired with ${pairing.deviceId}`);
|
|
15691
|
+
}
|
|
15692
|
+
function readCliConfig$1(configPath) {
|
|
15693
|
+
return configPath ? readCodememConfigFileAtPath(configPath) : readCodememConfigFile();
|
|
15694
|
+
}
|
|
15695
|
+
function localPairingPayload(store, opts) {
|
|
15696
|
+
const keysDir = process.env.CODEMEM_KEYS_DIR?.trim() || void 0;
|
|
15697
|
+
const [deviceId, fingerprint] = ensureDeviceIdentity(store.db, { keysDir });
|
|
15698
|
+
const publicKey = loadPublicKey(keysDir);
|
|
15699
|
+
if (!publicKey) throw new PairRefusal("missing_key", "Public key missing");
|
|
15700
|
+
const config = readCliConfig$1(opts.config);
|
|
15701
|
+
const addresses = collectAdvertiseAddresses(opts.address?.trim() ?? null, typeof config.sync_host === "string" ? config.sync_host : null, typeof config.sync_port === "number" ? config.sync_port : 7337, networkInterfaces());
|
|
15702
|
+
return JSON.stringify(buildPairingPayload({
|
|
15703
|
+
deviceId,
|
|
15704
|
+
fingerprint,
|
|
15705
|
+
publicKey,
|
|
15706
|
+
addresses
|
|
15707
|
+
}));
|
|
15708
|
+
}
|
|
15709
|
+
function printPairingPayload(store, opts) {
|
|
15710
|
+
const payloadText = localPairingPayload(store, opts);
|
|
15711
|
+
if (opts.payloadOnly || opts.json) {
|
|
15712
|
+
process.stdout.write(`${payloadText}\n`);
|
|
15713
|
+
return;
|
|
15714
|
+
}
|
|
15715
|
+
const escaped = payloadText.replaceAll("'", "'\\''");
|
|
15716
|
+
console.log("Pairing payload");
|
|
15717
|
+
console.log(payloadText);
|
|
15718
|
+
console.log("On the other device, save this JSON to pairing.json, then run:");
|
|
15719
|
+
console.log(" codemem sync pair --accept-file pairing.json");
|
|
15720
|
+
console.log("If you prefer inline JSON, run:");
|
|
15721
|
+
console.log(` codemem sync pair --accept '${escaped}'`);
|
|
15722
|
+
console.log("For machine-friendly output next time, run:");
|
|
15723
|
+
console.log(" codemem sync pair --payload-only");
|
|
15724
|
+
console.log("On the accepting device, --include/--exclude control both what it sends and what it accepts from that peer.");
|
|
15725
|
+
}
|
|
15726
|
+
async function runPair(opts) {
|
|
15727
|
+
const store = new MemoryStore(resolveDbPath(resolveDbOpt(opts)));
|
|
15728
|
+
try {
|
|
15729
|
+
checkModeFlags(opts);
|
|
15730
|
+
const acceptText = await readAcceptText(opts);
|
|
15731
|
+
checkFilterFlags(opts, acceptText);
|
|
15732
|
+
if (acceptText?.trim()) acceptPairing(store, opts, acceptText);
|
|
15733
|
+
else printPairingPayload(store, opts);
|
|
15734
|
+
} catch (error) {
|
|
15735
|
+
reportFailure$1(opts, error);
|
|
15736
|
+
} finally {
|
|
15737
|
+
store.close();
|
|
15738
|
+
}
|
|
15739
|
+
}
|
|
15740
|
+
function buildSyncPairCommand() {
|
|
15741
|
+
const command = 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");
|
|
15742
|
+
addDbOption(command);
|
|
15743
|
+
addConfigOption(command);
|
|
15744
|
+
addJsonOption(command);
|
|
15745
|
+
command.action(runPair);
|
|
15746
|
+
return command;
|
|
15747
|
+
}
|
|
15748
|
+
//#endregion
|
|
15749
|
+
//#region src/commands/sync-rejoin.ts
|
|
15750
|
+
function readProfile(options) {
|
|
15751
|
+
const config = options.config ? readCodememConfigFileAtPath(options.config) : readCodememConfigFile();
|
|
15752
|
+
const coordinatorUrl = normalizeCoordinatorAccountLinkOrigin(readCoordinatorSyncConfig(config).syncCoordinatorUrl);
|
|
15753
|
+
if (!coordinatorUrl) return null;
|
|
14535
15754
|
const dbPath = resolveDbPath(resolveDbOpt(options));
|
|
14536
15755
|
const before = statSync(dbPath, { bigint: true });
|
|
14537
15756
|
const device = readAccountLinkDevice(dbPath);
|
|
@@ -14845,7 +16064,8 @@ async function portOpen(host, port) {
|
|
|
14845
16064
|
}
|
|
14846
16065
|
function readViewerBinding(dbPath) {
|
|
14847
16066
|
try {
|
|
14848
|
-
const raw =
|
|
16067
|
+
const raw = readViewerPidFile(dbPath);
|
|
16068
|
+
if (raw === null) return null;
|
|
14849
16069
|
const parsed = JSON.parse(raw);
|
|
14850
16070
|
if (typeof parsed.host === "string" && typeof parsed.port === "number") return {
|
|
14851
16071
|
host: parsed.host,
|
|
@@ -15006,251 +16226,7 @@ onceCmd.action(async (opts) => {
|
|
|
15006
16226
|
}
|
|
15007
16227
|
});
|
|
15008
16228
|
syncCommand.addCommand(onceCmd);
|
|
15009
|
-
|
|
15010
|
-
/** The filters the pair flags ask for, or null when no filter flag was given. */
|
|
15011
|
-
function pairFilterChange(opts) {
|
|
15012
|
-
if (opts.default) return {
|
|
15013
|
-
include: null,
|
|
15014
|
-
exclude: null
|
|
15015
|
-
};
|
|
15016
|
-
if (opts.all) return {
|
|
15017
|
-
include: [],
|
|
15018
|
-
exclude: []
|
|
15019
|
-
};
|
|
15020
|
-
if (!opts.include && !opts.exclude) return null;
|
|
15021
|
-
return {
|
|
15022
|
-
include: parseProjectList(opts.include),
|
|
15023
|
-
exclude: parseProjectList(opts.exclude)
|
|
15024
|
-
};
|
|
15025
|
-
}
|
|
15026
|
-
/** What the running `sync pair` asked for. Set before its handler runs and cleared after it. */
|
|
15027
|
-
var pairRun = null;
|
|
15028
|
-
function beginPairRun(opts) {
|
|
15029
|
-
pairRun = pairFilterChange(opts);
|
|
15030
|
-
}
|
|
15031
|
-
/** Stores an accepted pairing, unless its filter flags would widen on a device that may not. */
|
|
15032
|
-
function updatePeerAddresses$1(...args) {
|
|
15033
|
-
const [db, peerDeviceId] = args;
|
|
15034
|
-
if (pairRun !== null && !readPeerProjectFilterAuthority(db) && !peerProjectFilterChangeOnlyNarrows(db, peerDeviceId, pairRun)) throw new Error(PAIR_FILTERS_REFUSED);
|
|
15035
|
-
updatePeerAddresses(...args);
|
|
15036
|
-
}
|
|
15037
|
-
/** The filter write of an accepted pairing rechecks authority inside the transaction. */
|
|
15038
|
-
function setPeerProjectFilter(db, peerDeviceId, lists) {
|
|
15039
|
-
if (setPeerProjectFilterChecked(db, peerDeviceId, lists) !== "saved") throw new Error(PAIR_FILTERS_REFUSED);
|
|
15040
|
-
}
|
|
15041
|
-
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");
|
|
15042
|
-
addDbOption(pairCmd);
|
|
15043
|
-
addConfigOption(pairCmd);
|
|
15044
|
-
addJsonOption(pairCmd);
|
|
15045
|
-
pairCmd.hook("preAction", (_command, action) => beginPairRun(action.opts()));
|
|
15046
|
-
pairCmd.hook("postAction", () => {
|
|
15047
|
-
pairRun = null;
|
|
15048
|
-
});
|
|
15049
|
-
pairCmd.action(async (opts) => {
|
|
15050
|
-
const store = new MemoryStore(resolveDbPath(resolveDbOpt(opts)));
|
|
15051
|
-
try {
|
|
15052
|
-
const acceptModeRequested = opts.accept != null || opts.acceptFile != null;
|
|
15053
|
-
if (opts.payloadOnly && acceptModeRequested) {
|
|
15054
|
-
if (opts.json) {
|
|
15055
|
-
emitJsonError("usage_error", "--payload-only cannot be combined with --accept or --accept-file", 2);
|
|
15056
|
-
return;
|
|
15057
|
-
}
|
|
15058
|
-
p.log.error("--payload-only cannot be combined with --accept or --accept-file");
|
|
15059
|
-
process.exitCode = 1;
|
|
15060
|
-
return;
|
|
15061
|
-
}
|
|
15062
|
-
if (opts.accept && opts.acceptFile) {
|
|
15063
|
-
if (opts.json) {
|
|
15064
|
-
emitJsonError("usage_error", "Use only one of --accept or --accept-file", 2);
|
|
15065
|
-
return;
|
|
15066
|
-
}
|
|
15067
|
-
p.log.error("Use only one of --accept or --accept-file");
|
|
15068
|
-
process.exitCode = 1;
|
|
15069
|
-
return;
|
|
15070
|
-
}
|
|
15071
|
-
let acceptText = opts.accept;
|
|
15072
|
-
if (opts.acceptFile) try {
|
|
15073
|
-
acceptText = opts.acceptFile === "-" ? await new Promise((resolve, reject) => {
|
|
15074
|
-
let text = "";
|
|
15075
|
-
process.stdin.setEncoding("utf8");
|
|
15076
|
-
process.stdin.on("data", (chunk) => {
|
|
15077
|
-
text += chunk;
|
|
15078
|
-
});
|
|
15079
|
-
process.stdin.on("end", () => resolve(text));
|
|
15080
|
-
process.stdin.on("error", reject);
|
|
15081
|
-
}) : readFileSync(opts.acceptFile, "utf8");
|
|
15082
|
-
} catch (error) {
|
|
15083
|
-
const msg = error instanceof Error ? `Failed to read pairing payload from ${opts.acceptFile}: ${error.message}` : `Failed to read pairing payload from ${opts.acceptFile}`;
|
|
15084
|
-
if (opts.json) {
|
|
15085
|
-
emitJsonError("read_error", msg);
|
|
15086
|
-
return;
|
|
15087
|
-
}
|
|
15088
|
-
p.log.error(msg);
|
|
15089
|
-
process.exitCode = 1;
|
|
15090
|
-
return;
|
|
15091
|
-
}
|
|
15092
|
-
if (acceptModeRequested && !(acceptText ?? "").trim()) {
|
|
15093
|
-
if (opts.json) {
|
|
15094
|
-
emitJsonError("usage_error", "Empty pairing payload; provide JSON via --accept or --accept-file", 2);
|
|
15095
|
-
return;
|
|
15096
|
-
}
|
|
15097
|
-
p.log.error("Empty pairing payload; provide JSON via --accept or --accept-file");
|
|
15098
|
-
process.exitCode = 1;
|
|
15099
|
-
return;
|
|
15100
|
-
}
|
|
15101
|
-
if (!acceptText && (opts.include || opts.exclude || opts.all || opts.default)) {
|
|
15102
|
-
if (opts.json) {
|
|
15103
|
-
emitJsonError("usage_error", "Project filters are outbound-only and must be set on the device running --accept", 2);
|
|
15104
|
-
return;
|
|
15105
|
-
}
|
|
15106
|
-
p.log.error("Project filters are outbound-only and must be set on the device running --accept");
|
|
15107
|
-
process.exitCode = 1;
|
|
15108
|
-
return;
|
|
15109
|
-
}
|
|
15110
|
-
if (acceptText?.trim()) {
|
|
15111
|
-
if (opts.all && opts.default) {
|
|
15112
|
-
if (opts.json) {
|
|
15113
|
-
emitJsonError("usage_error", "Use only one of --all or --default", 2);
|
|
15114
|
-
return;
|
|
15115
|
-
}
|
|
15116
|
-
p.log.error("Use only one of --all or --default");
|
|
15117
|
-
process.exitCode = 1;
|
|
15118
|
-
return;
|
|
15119
|
-
}
|
|
15120
|
-
if ((opts.all || opts.default) && (opts.include || opts.exclude)) {
|
|
15121
|
-
if (opts.json) {
|
|
15122
|
-
emitJsonError("usage_error", "--include/--exclude cannot be combined with --all/--default", 2);
|
|
15123
|
-
return;
|
|
15124
|
-
}
|
|
15125
|
-
p.log.error("--include/--exclude cannot be combined with --all/--default");
|
|
15126
|
-
process.exitCode = 1;
|
|
15127
|
-
return;
|
|
15128
|
-
}
|
|
15129
|
-
let payload;
|
|
15130
|
-
try {
|
|
15131
|
-
payload = JSON.parse(acceptText);
|
|
15132
|
-
} catch (error) {
|
|
15133
|
-
const msg = error instanceof Error ? `Invalid pairing payload: ${error.message}` : "Invalid pairing payload";
|
|
15134
|
-
if (opts.json) {
|
|
15135
|
-
emitJsonError("invalid_payload", msg);
|
|
15136
|
-
return;
|
|
15137
|
-
}
|
|
15138
|
-
p.log.error(msg);
|
|
15139
|
-
process.exitCode = 1;
|
|
15140
|
-
return;
|
|
15141
|
-
}
|
|
15142
|
-
const deviceId = String(payload.device_id || "").trim();
|
|
15143
|
-
const fingerprint = String(payload.fingerprint || "").trim();
|
|
15144
|
-
const publicKey = String(payload.public_key || "").trim();
|
|
15145
|
-
const resolvedAddresses = opts.address?.trim() ? [opts.address.trim()] : Array.isArray(payload.addresses) ? payload.addresses.filter((item) => typeof item === "string" && item.trim().length > 0).map((item) => item.trim()) : [];
|
|
15146
|
-
if (!deviceId || !fingerprint || !publicKey || resolvedAddresses.length === 0) {
|
|
15147
|
-
const msg = "Pairing payload missing device_id, fingerprint, public_key, or addresses";
|
|
15148
|
-
if (opts.json) {
|
|
15149
|
-
emitJsonError("invalid_payload", msg);
|
|
15150
|
-
return;
|
|
15151
|
-
}
|
|
15152
|
-
p.log.error(msg);
|
|
15153
|
-
process.exitCode = 1;
|
|
15154
|
-
return;
|
|
15155
|
-
}
|
|
15156
|
-
if (fingerprintPublicKey(publicKey) !== fingerprint) {
|
|
15157
|
-
if (opts.json) {
|
|
15158
|
-
emitJsonError("fingerprint_mismatch", "Pairing payload fingerprint mismatch");
|
|
15159
|
-
return;
|
|
15160
|
-
}
|
|
15161
|
-
p.log.error("Pairing payload fingerprint mismatch");
|
|
15162
|
-
process.exitCode = 1;
|
|
15163
|
-
return;
|
|
15164
|
-
}
|
|
15165
|
-
const existingPeer = drizzle(store.db, { schema }).select({ pinned_fingerprint: schema.syncPeers.pinned_fingerprint }).from(schema.syncPeers).where(eq(schema.syncPeers.peer_device_id, deviceId)).get();
|
|
15166
|
-
const existingFingerprint = String(existingPeer?.pinned_fingerprint ?? "").trim();
|
|
15167
|
-
if (existingFingerprint && existingFingerprint !== fingerprint) {
|
|
15168
|
-
const msg = "Pairing payload conflicts with the existing trusted fingerprint for this device. Remove or repair the old peer before accepting this pairing payload.";
|
|
15169
|
-
if (opts.json) {
|
|
15170
|
-
emitJsonError("peer_conflict", msg);
|
|
15171
|
-
return;
|
|
15172
|
-
}
|
|
15173
|
-
p.log.error(msg);
|
|
15174
|
-
process.exitCode = 1;
|
|
15175
|
-
return;
|
|
15176
|
-
}
|
|
15177
|
-
updatePeerAddresses$1(store.db, deviceId, resolvedAddresses, {
|
|
15178
|
-
name: opts.name,
|
|
15179
|
-
pinnedFingerprint: fingerprint,
|
|
15180
|
-
publicKey,
|
|
15181
|
-
replaceTrust: true
|
|
15182
|
-
});
|
|
15183
|
-
if (opts.default) setPeerProjectFilter(store.db, deviceId, {
|
|
15184
|
-
include: null,
|
|
15185
|
-
exclude: null
|
|
15186
|
-
});
|
|
15187
|
-
else if (opts.all || opts.include || opts.exclude) setPeerProjectFilter(store.db, deviceId, {
|
|
15188
|
-
include: opts.all ? [] : parseProjectList(opts.include),
|
|
15189
|
-
exclude: opts.all ? [] : parseProjectList(opts.exclude)
|
|
15190
|
-
});
|
|
15191
|
-
if (opts.json) {
|
|
15192
|
-
console.log(JSON.stringify({
|
|
15193
|
-
ok: true,
|
|
15194
|
-
peer_device_id: deviceId
|
|
15195
|
-
}));
|
|
15196
|
-
return;
|
|
15197
|
-
}
|
|
15198
|
-
p.log.success(`Paired with ${deviceId}`);
|
|
15199
|
-
return;
|
|
15200
|
-
}
|
|
15201
|
-
const keysDir = process.env.CODEMEM_KEYS_DIR?.trim() || void 0;
|
|
15202
|
-
const [deviceId, fingerprint] = ensureDeviceIdentity(store.db, { keysDir });
|
|
15203
|
-
const publicKey = loadPublicKey(keysDir);
|
|
15204
|
-
if (!publicKey) {
|
|
15205
|
-
if (opts.json) {
|
|
15206
|
-
emitJsonError("missing_key", "Public key missing");
|
|
15207
|
-
return;
|
|
15208
|
-
}
|
|
15209
|
-
p.log.error("Public key missing");
|
|
15210
|
-
process.exitCode = 1;
|
|
15211
|
-
return;
|
|
15212
|
-
}
|
|
15213
|
-
const config = readCliConfig(opts.config);
|
|
15214
|
-
const explicitAddress = opts.address?.trim();
|
|
15215
|
-
const configuredHost = typeof config.sync_host === "string" ? config.sync_host : null;
|
|
15216
|
-
const configuredPort = typeof config.sync_port === "number" ? config.sync_port : 7337;
|
|
15217
|
-
const addresses = collectAdvertiseAddresses(explicitAddress ?? null, configuredHost, configuredPort, networkInterfaces());
|
|
15218
|
-
const payloadObj = {
|
|
15219
|
-
device_id: deviceId,
|
|
15220
|
-
fingerprint,
|
|
15221
|
-
public_key: publicKey,
|
|
15222
|
-
address: addresses[0] ?? "",
|
|
15223
|
-
addresses
|
|
15224
|
-
};
|
|
15225
|
-
const payloadText = JSON.stringify(payloadObj);
|
|
15226
|
-
if (opts.payloadOnly || opts.json) {
|
|
15227
|
-
process.stdout.write(`${payloadText}\n`);
|
|
15228
|
-
return;
|
|
15229
|
-
}
|
|
15230
|
-
const escaped = payloadText.replaceAll("'", "'\\''");
|
|
15231
|
-
console.log("Pairing payload");
|
|
15232
|
-
console.log(payloadText);
|
|
15233
|
-
console.log("On the other device, save this JSON to pairing.json, then run:");
|
|
15234
|
-
console.log(" codemem sync pair --accept-file pairing.json");
|
|
15235
|
-
console.log("If you prefer inline JSON, run:");
|
|
15236
|
-
console.log(` codemem sync pair --accept '${escaped}'`);
|
|
15237
|
-
console.log("For machine-friendly output next time, run:");
|
|
15238
|
-
console.log(" codemem sync pair --payload-only");
|
|
15239
|
-
console.log("On the accepting device, --include/--exclude control both what it sends and what it accepts from that peer.");
|
|
15240
|
-
} catch (error) {
|
|
15241
|
-
const code = error instanceof DeviceIdentityError ? error.code : "pairing_failed";
|
|
15242
|
-
const message = error instanceof Error ? error.message : "Pairing failed";
|
|
15243
|
-
if (opts.json) {
|
|
15244
|
-
emitJsonError(code, message);
|
|
15245
|
-
return;
|
|
15246
|
-
}
|
|
15247
|
-
p.log.error(message);
|
|
15248
|
-
process.exitCode = 1;
|
|
15249
|
-
} finally {
|
|
15250
|
-
store.close();
|
|
15251
|
-
}
|
|
15252
|
-
});
|
|
15253
|
-
syncCommand.addCommand(pairCmd);
|
|
16229
|
+
syncCommand.addCommand(buildSyncPairCommand());
|
|
15254
16230
|
var doctorCmd = new Command("doctor").configureHelp(helpStyle).description("Check sync configuration and connectivity");
|
|
15255
16231
|
addDbOption(doctorCmd);
|
|
15256
16232
|
addConfigOption(doctorCmd);
|
|
@@ -15501,16 +16477,19 @@ peersCommand.action((opts) => {
|
|
|
15501
16477
|
store.close();
|
|
15502
16478
|
}
|
|
15503
16479
|
});
|
|
15504
|
-
/**
|
|
15505
|
-
|
|
15506
|
-
|
|
15507
|
-
|
|
15508
|
-
|
|
16480
|
+
/**
|
|
16481
|
+
* What the user is told after unpairing. With a coordinator, codemem can pair the devices
|
|
16482
|
+
* again, so Remove device is named as the way to stop everywhere. Without one, nothing
|
|
16483
|
+
* pairs them again.
|
|
16484
|
+
*/
|
|
16485
|
+
function peerRemovalNotices(label, coordinatorConfigured) {
|
|
16486
|
+
if (!coordinatorConfigured) return [`This device stops syncing with ${label}. ${label} keeps syncing with your other devices.`];
|
|
16487
|
+
return [`This device stops syncing with ${label}. If both devices share a Team Project, codemem can pair them again automatically.`, `To stop syncing with ${label} on all your devices, use Remove device.`];
|
|
15509
16488
|
}
|
|
15510
16489
|
function reportPeerRemoved(match, result, options) {
|
|
15511
16490
|
const label = match.name || match.peer_device_id;
|
|
15512
16491
|
const { binding, removed } = result;
|
|
15513
|
-
const notices = peerRemovalNotices(label,
|
|
16492
|
+
const notices = peerRemovalNotices(label, Boolean(readCoordinatorSyncConfig().syncCoordinatorUrl.trim()));
|
|
15514
16493
|
if (options.json) {
|
|
15515
16494
|
const payload = {
|
|
15516
16495
|
ok: true,
|
|
@@ -15524,24 +16503,20 @@ function reportPeerRemoved(match, result, options) {
|
|
|
15524
16503
|
identity_devices: removed.identityDevices
|
|
15525
16504
|
},
|
|
15526
16505
|
binding,
|
|
15527
|
-
|
|
16506
|
+
remove_from_projects: "needs_admin_device",
|
|
15528
16507
|
notice: notices.join(" ")
|
|
15529
16508
|
};
|
|
15530
16509
|
console.log(JSON.stringify(payload, null, 2));
|
|
15531
16510
|
return;
|
|
15532
16511
|
}
|
|
15533
16512
|
p.intro("codemem sync peers remove");
|
|
15534
|
-
p.log.success(
|
|
16513
|
+
p.log.success(`Unpaired this device from ${label}.`);
|
|
15535
16514
|
const progressRows = removed.replicationCursors + removed.replicationCursorsV2 + removed.syncChannelProgress;
|
|
15536
|
-
p.log.message([
|
|
15537
|
-
` pairing: ${removed.syncPeers}`,
|
|
15538
|
-
` sync progress rows: ${progressRows}`,
|
|
15539
|
-
` Identity bindings ended: ${removed.identityDevices}`
|
|
15540
|
-
].join("\n"));
|
|
16515
|
+
p.log.message([` pairing: ${removed.syncPeers}`, ` sync progress rows: ${progressRows}`].join("\n"));
|
|
15541
16516
|
for (const notice of notices) p.log.warn(notice);
|
|
15542
16517
|
p.outro(match.peer_device_id);
|
|
15543
16518
|
}
|
|
15544
|
-
async function removeSyncPeer(peerRef, opts
|
|
16519
|
+
async function removeSyncPeer(peerRef, opts) {
|
|
15545
16520
|
const store = new MemoryStore(resolveDbPath(resolveDbOpt(opts)));
|
|
15546
16521
|
try {
|
|
15547
16522
|
const match = resolvePeerMatch(drizzle(store.db, { schema }), peerRef);
|
|
@@ -15566,10 +16541,9 @@ async function removeSyncPeer(peerRef, opts, dependencies = {}) {
|
|
|
15566
16541
|
const label = match.name || match.peer_device_id;
|
|
15567
16542
|
let result;
|
|
15568
16543
|
try {
|
|
15569
|
-
result =
|
|
16544
|
+
result = removePeerFromThisDevice(store.db, {
|
|
15570
16545
|
localDeviceId: store.deviceId,
|
|
15571
|
-
peerDeviceId: match.peer_device_id
|
|
15572
|
-
lookupCoordinatorAnswer: dependencies.lookupCoordinatorAnswer
|
|
16546
|
+
peerDeviceId: match.peer_device_id
|
|
15573
16547
|
});
|
|
15574
16548
|
} catch {
|
|
15575
16549
|
const message = `Could not remove peer ${label}. Nothing was changed.`;
|
|
@@ -15586,7 +16560,7 @@ async function removeSyncPeer(peerRef, opts, dependencies = {}) {
|
|
|
15586
16560
|
store.close();
|
|
15587
16561
|
}
|
|
15588
16562
|
}
|
|
15589
|
-
var peersRemoveCmd = new Command("remove").configureHelp(helpStyle).description("
|
|
16563
|
+
var peersRemoveCmd = new Command("remove").configureHelp(helpStyle).description("Unpair this device from a sync peer by device id or exact name").argument("<peer>", "peer device id or exact name");
|
|
15590
16564
|
addDbOption(peersRemoveCmd);
|
|
15591
16565
|
addJsonOption(peersRemoveCmd);
|
|
15592
16566
|
peersRemoveCmd.action((peerRef, opts) => removeSyncPeer(peerRef, opts));
|
|
@@ -15594,172 +16568,7 @@ peersCommand.addCommand(peersRemoveCmd);
|
|
|
15594
16568
|
syncCommand.addCommand(peersCommand);
|
|
15595
16569
|
syncCommand.addCommand(relayKeysCommand);
|
|
15596
16570
|
syncCommand.addCommand(approveRelayKeyCommand);
|
|
15597
|
-
|
|
15598
|
-
addDbOption(bootstrapCmd);
|
|
15599
|
-
addJsonOption(bootstrapCmd);
|
|
15600
|
-
bootstrapCmd.addOption(new Option("--peer <device-id>", "peer device ID").hideHelp());
|
|
15601
|
-
bootstrapCmd.action(async (peerArg, opts) => {
|
|
15602
|
-
const peerDeviceId = (peerArg || opts.peer || "").trim();
|
|
15603
|
-
if (!peerDeviceId) {
|
|
15604
|
-
if (opts.json) {
|
|
15605
|
-
emitJsonError("usage_error", "missing required argument: <peer-device-id>", 2);
|
|
15606
|
-
return;
|
|
15607
|
-
}
|
|
15608
|
-
p.log.error("missing required argument: <peer-device-id>");
|
|
15609
|
-
process.exitCode = 2;
|
|
15610
|
-
return;
|
|
15611
|
-
}
|
|
15612
|
-
const dbPath = resolveDbPath(resolveDbOpt(opts));
|
|
15613
|
-
const store = new MemoryStore(dbPath);
|
|
15614
|
-
try {
|
|
15615
|
-
const pageSize = Math.max(1, Number.parseInt(opts.pageSize, 10) || 2e3);
|
|
15616
|
-
const keysDir = opts.keysDir ?? void 0;
|
|
15617
|
-
const peer = drizzle(store.db, { schema }).select().from(schema.syncPeers).where(eq(schema.syncPeers.peer_device_id, peerDeviceId)).get();
|
|
15618
|
-
if (!peer) {
|
|
15619
|
-
if (opts.json) emitJsonError("peer_not_found", `Peer ${peerDeviceId} not found in sync_peers.`);
|
|
15620
|
-
else p.log.error(`Peer ${peerDeviceId} not found in sync_peers.`);
|
|
15621
|
-
process.exitCode = 1;
|
|
15622
|
-
return;
|
|
15623
|
-
}
|
|
15624
|
-
if (!peer.pinned_fingerprint) {
|
|
15625
|
-
if (opts.json) emitJsonError("peer_not_pinned", `Peer ${peerDeviceId} has no pinned fingerprint. Accept it first.`);
|
|
15626
|
-
else p.log.error(`Peer ${peerDeviceId} has no pinned fingerprint. Accept it first.`);
|
|
15627
|
-
process.exitCode = 1;
|
|
15628
|
-
return;
|
|
15629
|
-
}
|
|
15630
|
-
if (!opts.force) {
|
|
15631
|
-
const dirty = hasUnsyncedSharedMemoryChanges(store.db);
|
|
15632
|
-
if (dirty.dirty) {
|
|
15633
|
-
if (opts.json) emitJsonError("local_unsynced_changes", `${dirty.count} unsynced shared memory change(s) would be lost. Use --force to override.`);
|
|
15634
|
-
else p.log.error(`${dirty.count} unsynced shared memory change(s) would be lost. Use --force to override.`);
|
|
15635
|
-
process.exitCode = 1;
|
|
15636
|
-
return;
|
|
15637
|
-
}
|
|
15638
|
-
}
|
|
15639
|
-
const [deviceId] = ensureDeviceIdentity(store.db, { keysDir });
|
|
15640
|
-
const addresses = JSON.parse(String(peer.addresses_json ?? "[]"));
|
|
15641
|
-
if (!addresses.length) {
|
|
15642
|
-
if (opts.json) emitJsonError("no_peer_addresses", "Peer has no known addresses. Run a sync first or add addresses.");
|
|
15643
|
-
else p.log.error("Peer has no known addresses. Run a sync first or add addresses.");
|
|
15644
|
-
process.exitCode = 1;
|
|
15645
|
-
return;
|
|
15646
|
-
}
|
|
15647
|
-
let boundary = null;
|
|
15648
|
-
let baseUrl = "";
|
|
15649
|
-
const addressResults = [];
|
|
15650
|
-
for (const address of addresses) {
|
|
15651
|
-
const candidate = buildBaseUrl(address);
|
|
15652
|
-
if (!candidate) continue;
|
|
15653
|
-
const statusUrl = `${candidate}/v1/status`;
|
|
15654
|
-
const headers = buildDirectPeerAuthHeaders({
|
|
15655
|
-
deviceId,
|
|
15656
|
-
recipientId: peerDeviceId,
|
|
15657
|
-
dbPath: store.dbPath,
|
|
15658
|
-
method: "GET",
|
|
15659
|
-
url: statusUrl,
|
|
15660
|
-
bodyBytes: Buffer.alloc(0),
|
|
15661
|
-
bootstrapGrantId: opts.bootstrapGrant,
|
|
15662
|
-
keysDir
|
|
15663
|
-
});
|
|
15664
|
-
try {
|
|
15665
|
-
const [code, payload] = await requestJson("GET", statusUrl, { headers });
|
|
15666
|
-
if (code !== 200 || !payload) {
|
|
15667
|
-
addressResults.push({
|
|
15668
|
-
address: candidate,
|
|
15669
|
-
result: `status ${code}`
|
|
15670
|
-
});
|
|
15671
|
-
continue;
|
|
15672
|
-
}
|
|
15673
|
-
if (payload.fingerprint !== peer.pinned_fingerprint) {
|
|
15674
|
-
addressResults.push({
|
|
15675
|
-
address: candidate,
|
|
15676
|
-
result: "fingerprint mismatch"
|
|
15677
|
-
});
|
|
15678
|
-
continue;
|
|
15679
|
-
}
|
|
15680
|
-
const reset = payload.sync_reset;
|
|
15681
|
-
if (reset && typeof reset.generation === "number" && typeof reset.snapshot_id === "string") {
|
|
15682
|
-
boundary = {
|
|
15683
|
-
generation: reset.generation,
|
|
15684
|
-
snapshot_id: reset.snapshot_id,
|
|
15685
|
-
baseline_cursor: typeof reset.baseline_cursor === "string" ? reset.baseline_cursor : null
|
|
15686
|
-
};
|
|
15687
|
-
baseUrl = candidate;
|
|
15688
|
-
addressResults.push({
|
|
15689
|
-
address: candidate,
|
|
15690
|
-
result: "ok"
|
|
15691
|
-
});
|
|
15692
|
-
break;
|
|
15693
|
-
}
|
|
15694
|
-
addressResults.push({
|
|
15695
|
-
address: candidate,
|
|
15696
|
-
result: "missing sync_reset boundary"
|
|
15697
|
-
});
|
|
15698
|
-
} catch (err) {
|
|
15699
|
-
addressResults.push({
|
|
15700
|
-
address: candidate,
|
|
15701
|
-
result: err instanceof Error ? err.message : String(err)
|
|
15702
|
-
});
|
|
15703
|
-
}
|
|
15704
|
-
}
|
|
15705
|
-
if (!boundary || !baseUrl) {
|
|
15706
|
-
const summary = addressResults.map((r) => `${r.address}: ${r.result}`).join("; ");
|
|
15707
|
-
const detail = summary ? `no reachable peer with valid reset boundary. Tried: ${summary}` : "peer unreachable or missing reset boundary";
|
|
15708
|
-
if (opts.json) console.log(JSON.stringify({
|
|
15709
|
-
ok: false,
|
|
15710
|
-
error: detail,
|
|
15711
|
-
addresses: addressResults
|
|
15712
|
-
}));
|
|
15713
|
-
else p.log.error(detail);
|
|
15714
|
-
process.exitCode = 1;
|
|
15715
|
-
return;
|
|
15716
|
-
}
|
|
15717
|
-
if (!opts.json) {
|
|
15718
|
-
p.intro("codemem sync bootstrap");
|
|
15719
|
-
p.log.step(`Bootstrapping from ${peer.name || peerDeviceId}...`);
|
|
15720
|
-
}
|
|
15721
|
-
const resetInfo = {
|
|
15722
|
-
generation: boundary.generation,
|
|
15723
|
-
snapshot_id: boundary.snapshot_id,
|
|
15724
|
-
baseline_cursor: boundary.baseline_cursor,
|
|
15725
|
-
retained_floor_cursor: null,
|
|
15726
|
-
reset_required: true,
|
|
15727
|
-
reason: "initial_bootstrap"
|
|
15728
|
-
};
|
|
15729
|
-
const { items } = await fetchAllSnapshotPages(baseUrl, resetInfo, deviceId, {
|
|
15730
|
-
keysDir,
|
|
15731
|
-
dbPath: store.dbPath,
|
|
15732
|
-
bootstrapGrantId: opts.bootstrapGrant,
|
|
15733
|
-
recipientId: peerDeviceId,
|
|
15734
|
-
pageSize
|
|
15735
|
-
});
|
|
15736
|
-
const result = applyBootstrapSnapshot(store.db, peerDeviceId, items, resetInfo, store.scanner);
|
|
15737
|
-
if (opts.json) console.log(JSON.stringify({
|
|
15738
|
-
ok: result.ok,
|
|
15739
|
-
applied: result.applied,
|
|
15740
|
-
deleted: result.deleted,
|
|
15741
|
-
error: result.error ?? null
|
|
15742
|
-
}));
|
|
15743
|
-
else {
|
|
15744
|
-
if (result.ok) p.log.success(`Applied ${result.applied} memories (removed ${result.deleted} stale).`);
|
|
15745
|
-
else p.log.error(result.error || "Bootstrap apply failed.");
|
|
15746
|
-
p.outro(result.ok ? "Bootstrap complete" : "Bootstrap failed");
|
|
15747
|
-
}
|
|
15748
|
-
if (!result.ok) process.exitCode = 1;
|
|
15749
|
-
} catch (error) {
|
|
15750
|
-
const code = error instanceof DeviceIdentityError ? error.code : "bootstrap_failed";
|
|
15751
|
-
const message = error instanceof Error ? error.message : "Bootstrap failed";
|
|
15752
|
-
if (opts.json) {
|
|
15753
|
-
emitJsonError(code, message);
|
|
15754
|
-
return;
|
|
15755
|
-
}
|
|
15756
|
-
p.log.error(message);
|
|
15757
|
-
process.exitCode = 1;
|
|
15758
|
-
} finally {
|
|
15759
|
-
store.close();
|
|
15760
|
-
}
|
|
15761
|
-
});
|
|
15762
|
-
syncCommand.addCommand(bootstrapCmd);
|
|
16571
|
+
syncCommand.addCommand(buildSyncBootstrapCommand());
|
|
15763
16572
|
function targetsRuntimeConfig(path) {
|
|
15764
16573
|
if (!path) return true;
|
|
15765
16574
|
const runtime = getCodememConfigPath();
|
|
@@ -15801,6 +16610,7 @@ connectCmd.action((url, opts) => {
|
|
|
15801
16610
|
});
|
|
15802
16611
|
syncCommand.addCommand(connectCmd);
|
|
15803
16612
|
syncCommand.addCommand(buildSyncRejoinCommand());
|
|
16613
|
+
syncCommand.addCommand(buildSyncMigrationCommand());
|
|
15804
16614
|
var syncCoordinatorAlias = buildCoordinatorCommand();
|
|
15805
16615
|
syncCoordinatorAlias.hook("preAction", (_thisCmd, actionCmd) => {
|
|
15806
16616
|
if (actionCmd.optsWithGlobals().json) return;
|