codemem 0.50.0-beta.3 → 0.50.0-beta.4
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 +446 -123
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { ACCOUNT_CONNECTION_MIGRATION_STATEMENTS, ACCOUNT_UNLINK_MIGRATION_STATEMENTS, ALLOWED_MEMORY_KINDS, AUTH_LINK_AUTHORITY_CUTOVER_SQL, ContextOnlyReplayError, CoordinatorAccountLinkError, DEDUP_KEY_BACKFILL_JOB, DEFAULT_COORDINATOR_DB_PATH, DEFAULT_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, requestJson, 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, viewerUrl, withDiagnosticStoreSnapshot, writeCodememConfigFile } from "@codemem/core";
|
|
2
|
+
import { ACCOUNT_CONNECTION_MIGRATION_STATEMENTS, ACCOUNT_UNLINK_MIGRATION_STATEMENTS, ALLOWED_MEMORY_KINDS, AUTH_LINK_AUTHORITY_CUTOVER_SQL, ContextOnlyReplayError, CoordinatorAccountLinkError, DEDUP_KEY_BACKFILL_JOB, DEFAULT_COORDINATOR_DB_PATH, DEFAULT_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, ReplicationBackfillRunner, SCOPE_BACKFILL_JOB, SESSION_CONTEXT_BACKFILL_JOB, SUMMARY_DEDUP_BACKFILL_JOB, ScopeBackfillRunner, SessionContextBackfillRunner, SummaryDedupBackfillRunner, SyncAttemptRetentionRunner, SyncRetentionRunner, TRUSTED_HOOK_MAPPER_OPTIONS, VERSION, VectorModelMigrationRunner, ViewerWriterLockHeldError, ViewerWriterLockUnavailableError, acquireViewerWriterLock, aiBackfillStructuredContent, applyBootstrapSnapshot, applyDistillRule, arePromptTransportProtocolRangesCompatible, atomicReplaceConfigFile, backfillMemoryDedupKeys, backfillNarrativeFromBody, backfillTagsText, backfillVectors, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, 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, planReplicationOpsAgePrune, probeCodememViewerLiveness, probeCodememViewerLiveness as probeCodememViewerLiveness$1, probeRequiredNativeRuntime, projectMatchesFilter, promptPackArtifactFingerprint, pruneReplicationOpsUntilCaughtUp, rawEventsGate, readAccountLinkDevice, readCodememConfigFile, readCodememConfigFileAtPath, readCoordinatorAccountLinkStatus, readCoordinatorOwnerReviewLocalEvidence, readCoordinatorSyncConfig, readImportPayload, readPeerProjectFilterAuthority, readViewerPidFile, readViewerWriterLockOwner, recordAutomaticRecall, recordPromptPackArtifacts, recordPromptPackTerminal, refreshCoordinatorForDaemon, rememberPeerProjectFilterManagement, removePeerFromThisDevice, renderUnifiedDiff, replayBatchExtraction, replayBatchExtractionWithTierRouting, requestJson, 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, 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";
|
|
@@ -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");
|
|
@@ -9676,6 +9681,11 @@ function createRetentionRunners(dbPath, syncConfig, logger, signal) {
|
|
|
9676
9681
|
signal,
|
|
9677
9682
|
logger
|
|
9678
9683
|
}));
|
|
9684
|
+
runners.push(new ReplicationBackfillRunner({
|
|
9685
|
+
dbPath,
|
|
9686
|
+
signal,
|
|
9687
|
+
logger
|
|
9688
|
+
}));
|
|
9679
9689
|
return runners;
|
|
9680
9690
|
}
|
|
9681
9691
|
function startMaintenanceWorkerRuntime(options = {}) {
|
|
@@ -11339,6 +11349,143 @@ function resolveStopRestartInvocation(mode, opts) {
|
|
|
11339
11349
|
background: mode === "restart"
|
|
11340
11350
|
};
|
|
11341
11351
|
}
|
|
11352
|
+
function unavailableMessage(error) {
|
|
11353
|
+
return `Cannot create the viewer lock at ${error.path} (${error.code}). Check that ${dirname(error.path)} exists and is writable.`;
|
|
11354
|
+
}
|
|
11355
|
+
/**
|
|
11356
|
+
* What the lock's owner record says about the holder, and how to stop it. The
|
|
11357
|
+
* record is a hint: nothing here checks that the recorded process still holds
|
|
11358
|
+
* the lock, so nothing acts on it.
|
|
11359
|
+
*/
|
|
11360
|
+
function viewerLockHolderHint(owner, platform = process.platform) {
|
|
11361
|
+
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.";
|
|
11362
|
+
const started = owner.started ? `, started ${owner.started}` : "";
|
|
11363
|
+
const kill = platform === "win32" ? `taskkill /PID ${owner.pid}` : `kill ${owner.pid}`;
|
|
11364
|
+
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}\`).`;
|
|
11365
|
+
}
|
|
11366
|
+
function heldMessage(dbPath, owner, answering) {
|
|
11367
|
+
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.`;
|
|
11368
|
+
}
|
|
11369
|
+
/** One attempt: the claim's result, or null while another process holds the lock. */
|
|
11370
|
+
function tryClaim(dbPath, target) {
|
|
11371
|
+
try {
|
|
11372
|
+
return {
|
|
11373
|
+
status: "acquired",
|
|
11374
|
+
lock: acquireViewerWriterLock(dbPath, { owner: target })
|
|
11375
|
+
};
|
|
11376
|
+
} catch (error) {
|
|
11377
|
+
if (error instanceof ViewerWriterLockUnavailableError) return {
|
|
11378
|
+
status: "refused",
|
|
11379
|
+
message: unavailableMessage(error)
|
|
11380
|
+
};
|
|
11381
|
+
if (error instanceof ViewerWriterLockHeldError) return null;
|
|
11382
|
+
throw error;
|
|
11383
|
+
}
|
|
11384
|
+
}
|
|
11385
|
+
/**
|
|
11386
|
+
* Takes the database's Viewer lock and records this process as its owner. When a
|
|
11387
|
+
* Viewer answers at the recorded holder's address, the start is refused at once.
|
|
11388
|
+
* Any other holder, such as a Viewer still shutting down, gets `waitMs` to
|
|
11389
|
+
* release it.
|
|
11390
|
+
*/
|
|
11391
|
+
async function claimViewerWriterLock(dbPath, target, dependencies, options = {}) {
|
|
11392
|
+
const deadline = Date.now() + (options.waitMs ?? 1e4);
|
|
11393
|
+
for (;;) {
|
|
11394
|
+
const attempt = tryClaim(dbPath, target);
|
|
11395
|
+
if (attempt) return attempt;
|
|
11396
|
+
const owner = readViewerWriterLockOwner(dbPath);
|
|
11397
|
+
if (owner && await dependencies.isLiveViewer(owner)) return {
|
|
11398
|
+
status: "refused",
|
|
11399
|
+
message: heldMessage(dbPath, owner, true)
|
|
11400
|
+
};
|
|
11401
|
+
if (Date.now() >= deadline) return {
|
|
11402
|
+
status: "refused",
|
|
11403
|
+
message: heldMessage(dbPath, owner, false)
|
|
11404
|
+
};
|
|
11405
|
+
await dependencies.sleep(options.pollMs ?? 250);
|
|
11406
|
+
}
|
|
11407
|
+
}
|
|
11408
|
+
/** Waits until no process holds the database's Viewer lock. */
|
|
11409
|
+
async function waitForViewerWriterLockRelease(dbPath, dependencies, options) {
|
|
11410
|
+
const deadline = Date.now() + options.timeoutMs;
|
|
11411
|
+
while (dependencies.isLockHeld(dbPath)) {
|
|
11412
|
+
if (Date.now() >= deadline) return false;
|
|
11413
|
+
await dependencies.sleep(options.pollMs ?? 200);
|
|
11414
|
+
}
|
|
11415
|
+
return true;
|
|
11416
|
+
}
|
|
11417
|
+
var STARTUP_MESSAGE_TYPE = "codemem-viewer-startup";
|
|
11418
|
+
/**
|
|
11419
|
+
* Set only by a background start for the Viewer it spawns. Any other parent with
|
|
11420
|
+
* an IPC channel, such as a test runner's worker pool, gets no startup messages.
|
|
11421
|
+
*/
|
|
11422
|
+
var VIEWER_STARTUP_REPORT_ENV = "CODEMEM_VIEWER_STARTUP_REPORT";
|
|
11423
|
+
/**
|
|
11424
|
+
* Tells a waiting background parent how this start went. A no-op unless a
|
|
11425
|
+
* background start spawned this process. The channel closes after the final
|
|
11426
|
+
* result, so the Viewer does not depend on the parent.
|
|
11427
|
+
*/
|
|
11428
|
+
function reportViewerStartup(event) {
|
|
11429
|
+
if (process.env["CODEMEM_VIEWER_STARTUP_REPORT"] !== "1") return;
|
|
11430
|
+
if (!process.send || !process.connected) return;
|
|
11431
|
+
const final = event.state !== "lock_acquired";
|
|
11432
|
+
process.send({
|
|
11433
|
+
type: STARTUP_MESSAGE_TYPE,
|
|
11434
|
+
...event
|
|
11435
|
+
}, void 0, {}, () => {
|
|
11436
|
+
if (final && process.connected) process.disconnect();
|
|
11437
|
+
});
|
|
11438
|
+
}
|
|
11439
|
+
function startupEvent(message) {
|
|
11440
|
+
const event = message;
|
|
11441
|
+
if (event?.type !== STARTUP_MESSAGE_TYPE) return null;
|
|
11442
|
+
if (event.state === "lock_acquired" || event.state === "listening") return { state: event.state };
|
|
11443
|
+
if (event.state === "failed") return {
|
|
11444
|
+
state: "failed",
|
|
11445
|
+
message: typeof event.message === "string" ? event.message : "Viewer failed to start"
|
|
11446
|
+
};
|
|
11447
|
+
return null;
|
|
11448
|
+
}
|
|
11449
|
+
/**
|
|
11450
|
+
* Waits for a background Viewer's startup result. `starting`: it holds the lock
|
|
11451
|
+
* but was not serving yet when the wait ended.
|
|
11452
|
+
*/
|
|
11453
|
+
function waitForViewerStartup(child, timeoutMs) {
|
|
11454
|
+
return new Promise((resolve) => {
|
|
11455
|
+
let lockAcquired = false;
|
|
11456
|
+
const finish = (result) => {
|
|
11457
|
+
clearTimeout(timer);
|
|
11458
|
+
child.off("message", onMessage);
|
|
11459
|
+
child.off("exit", onExit);
|
|
11460
|
+
child.off("error", onError);
|
|
11461
|
+
if (child.connected) child.disconnect();
|
|
11462
|
+
resolve(result);
|
|
11463
|
+
};
|
|
11464
|
+
const onMessage = (message) => {
|
|
11465
|
+
const event = startupEvent(message);
|
|
11466
|
+
if (event?.state === "lock_acquired") lockAcquired = true;
|
|
11467
|
+
else if (event) finish(event);
|
|
11468
|
+
};
|
|
11469
|
+
const onExit = (code, signal) => finish({
|
|
11470
|
+
state: "failed",
|
|
11471
|
+
message: `The viewer exited during startup (${signal ?? `exit code ${code ?? "unknown"}`}).`
|
|
11472
|
+
});
|
|
11473
|
+
const onError = (error) => finish({
|
|
11474
|
+
state: "failed",
|
|
11475
|
+
message: `Could not start the viewer: ${error.message}`
|
|
11476
|
+
});
|
|
11477
|
+
const timer = setTimeout(() => {
|
|
11478
|
+
if (lockAcquired) finish({ state: "starting" });
|
|
11479
|
+
else finish({
|
|
11480
|
+
state: "failed",
|
|
11481
|
+
message: `The viewer did not report startup within ${Math.ceil(timeoutMs / 1e3)}s.`
|
|
11482
|
+
});
|
|
11483
|
+
}, timeoutMs);
|
|
11484
|
+
child.on("message", onMessage);
|
|
11485
|
+
child.on("exit", onExit);
|
|
11486
|
+
child.on("error", onError);
|
|
11487
|
+
});
|
|
11488
|
+
}
|
|
11342
11489
|
//#endregion
|
|
11343
11490
|
//#region src/commands/serve.ts
|
|
11344
11491
|
function extractViewerPid(payload) {
|
|
@@ -11409,13 +11556,12 @@ function isTrustedViewerPid(pid, target, listenerPid) {
|
|
|
11409
11556
|
return isLikelyViewerCommand(command);
|
|
11410
11557
|
}
|
|
11411
11558
|
function pidFilePath(dbPath) {
|
|
11412
|
-
return join(
|
|
11559
|
+
return join(viewerRuntimeDir(dbPath), "viewer.pid");
|
|
11413
11560
|
}
|
|
11414
11561
|
function maintenanceWorkerPidFilePath(dbPath) {
|
|
11415
|
-
return join(
|
|
11562
|
+
return join(viewerRuntimeDir(dbPath), "maintenance-worker.pid");
|
|
11416
11563
|
}
|
|
11417
|
-
function
|
|
11418
|
-
const pidPath = maintenanceWorkerPidFilePath(dbPath);
|
|
11564
|
+
function readMaintenanceWorkerPidRecordAt(pidPath) {
|
|
11419
11565
|
if (!existsSync(pidPath)) return null;
|
|
11420
11566
|
const raw = readFileSync(pidPath, "utf-8").trim();
|
|
11421
11567
|
try {
|
|
@@ -11449,8 +11595,20 @@ function commandHasExactDbPath(command, dbPath) {
|
|
|
11449
11595
|
const escapedPath = escapeRegExp(resolveDbPath(dbPath));
|
|
11450
11596
|
return new RegExp(`(?:^|\\s)--db-path(?:=|\\s+)${escapedPath}(?:\\s|$)`).test(command);
|
|
11451
11597
|
}
|
|
11598
|
+
/** The PID records for this database: the current location, then where earlier releases wrote it. */
|
|
11599
|
+
function readViewerPidRecords(dbPath) {
|
|
11600
|
+
return viewerPidFilePaths(resolveDbPath(dbPath)).flatMap((path) => {
|
|
11601
|
+
const record = readViewerPidRecordAt(path);
|
|
11602
|
+
return record ? [{
|
|
11603
|
+
path,
|
|
11604
|
+
record
|
|
11605
|
+
}] : [];
|
|
11606
|
+
});
|
|
11607
|
+
}
|
|
11452
11608
|
function readViewerPidRecord(dbPath) {
|
|
11453
|
-
|
|
11609
|
+
return readViewerPidRecordAt(pidFilePath(dbPath));
|
|
11610
|
+
}
|
|
11611
|
+
function readViewerPidRecordAt(pidPath) {
|
|
11454
11612
|
if (!existsSync(pidPath)) return null;
|
|
11455
11613
|
const parsed = parseViewerPidRecord(readFileSync(pidPath, "utf-8"));
|
|
11456
11614
|
if (parsed.state === "valid") return parsed.record;
|
|
@@ -11472,13 +11630,14 @@ function normalizeViewerHost(host) {
|
|
|
11472
11630
|
if (normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1" || normalized === "[::1]") return "loopback";
|
|
11473
11631
|
return normalized;
|
|
11474
11632
|
}
|
|
11633
|
+
/** A live Viewer for this database at another address, from either PID record location. */
|
|
11475
11634
|
async function findRuntimeViewerConflict(dbPath, target) {
|
|
11476
|
-
const record
|
|
11477
|
-
|
|
11478
|
-
|
|
11479
|
-
|
|
11480
|
-
|
|
11481
|
-
return
|
|
11635
|
+
for (const { record } of readViewerPidRecords(dbPath)) {
|
|
11636
|
+
if (normalizeViewerHost(record.host) === normalizeViewerHost(target.host) && record.port === target.port) continue;
|
|
11637
|
+
if (!isProcessRunning(record.pid)) continue;
|
|
11638
|
+
if (await respondsLikeCodememViewer(record)) return record;
|
|
11639
|
+
}
|
|
11640
|
+
return null;
|
|
11482
11641
|
}
|
|
11483
11642
|
function isProcessRunning(pid) {
|
|
11484
11643
|
try {
|
|
@@ -11548,25 +11707,32 @@ async function terminateProcessPid(pid, timeouts = {}) {
|
|
|
11548
11707
|
async function terminateTrustedViewerPid(pid, timeouts = {}) {
|
|
11549
11708
|
return terminateProcessPid(pid, timeouts);
|
|
11550
11709
|
}
|
|
11710
|
+
/**
|
|
11711
|
+
* Stops a leftover maintenance worker for this database. Reads the current PID
|
|
11712
|
+
* record and the one an older release left beside the database path as given,
|
|
11713
|
+
* where a worker that outlived a Viewer started through a symlink recorded
|
|
11714
|
+
* itself. False when a recorded worker is not trusted or did not stop.
|
|
11715
|
+
*/
|
|
11551
11716
|
async function terminateTrustedMaintenanceWorker(dbPath, timeouts = {}) {
|
|
11552
|
-
const
|
|
11553
|
-
|
|
11717
|
+
const paths = [.../* @__PURE__ */ new Set([maintenanceWorkerPidFilePath(dbPath), join(dirname(resolveDbPath(dbPath)), "maintenance-worker.pid")])];
|
|
11718
|
+
let allStopped = true;
|
|
11719
|
+
for (const pidPath of paths) if (!await terminateRecordedMaintenanceWorker(pidPath, dbPath, timeouts)) allStopped = false;
|
|
11720
|
+
return allStopped;
|
|
11721
|
+
}
|
|
11722
|
+
async function terminateRecordedMaintenanceWorker(pidPath, dbPath, timeouts) {
|
|
11723
|
+
const record = readMaintenanceWorkerPidRecordAt(pidPath);
|
|
11554
11724
|
if (!record) return true;
|
|
11555
|
-
const
|
|
11556
|
-
if (record.dbPath && record.dbPath
|
|
11725
|
+
const isThisDb = (path) => path !== null && canonicalViewerDbPath(path) === canonicalViewerDbPath(dbPath);
|
|
11726
|
+
if (record.dbPath && !isThisDb(record.dbPath)) return false;
|
|
11557
11727
|
if (!isProcessRunning(record.pid)) {
|
|
11558
|
-
|
|
11559
|
-
rmSync(pidPath);
|
|
11560
|
-
} catch {}
|
|
11728
|
+
removeFile(pidPath);
|
|
11561
11729
|
return true;
|
|
11562
11730
|
}
|
|
11563
11731
|
const command = readProcessCommand(record.pid);
|
|
11564
11732
|
if (!command || !isLikelyMaintenanceWorkerCommand(command)) return false;
|
|
11565
|
-
if (record.dbPath
|
|
11733
|
+
if (!isThisDb(record.dbPath) || !commandHasExactDbPath(command, record.dbPath)) return false;
|
|
11566
11734
|
const stopped = await terminateProcessPid(record.pid, timeouts);
|
|
11567
|
-
if (stopped)
|
|
11568
|
-
rmSync(pidPath);
|
|
11569
|
-
} catch {}
|
|
11735
|
+
if (stopped) removeFile(pidPath);
|
|
11570
11736
|
return stopped;
|
|
11571
11737
|
}
|
|
11572
11738
|
async function waitForPortRelease(host, port, timeoutMs = 1e4) {
|
|
@@ -11577,9 +11743,16 @@ async function waitForPortRelease(host, port, timeoutMs = 1e4) {
|
|
|
11577
11743
|
}
|
|
11578
11744
|
return false;
|
|
11579
11745
|
}
|
|
11746
|
+
var viewerLockDependencies = {
|
|
11747
|
+
isLockHeld: isViewerWriterLockHeld,
|
|
11748
|
+
isLiveViewer: (owner) => respondsLikeCodememViewer({
|
|
11749
|
+
pid: owner.pid,
|
|
11750
|
+
host: owner.host,
|
|
11751
|
+
port: owner.port
|
|
11752
|
+
}),
|
|
11753
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
11754
|
+
};
|
|
11580
11755
|
async function stopExistingViewer(dbPath, target) {
|
|
11581
|
-
const pidPath = pidFilePath(dbPath);
|
|
11582
|
-
const record = readViewerPidRecord(dbPath);
|
|
11583
11756
|
const viewerPidFromStats = await lookupViewerPidFromStats(target.host, target.port);
|
|
11584
11757
|
const listenerPid = lookupListeningPid(target.host, target.port);
|
|
11585
11758
|
const viewerPid = pickViewerPidCandidate(viewerPidFromStats, listenerPid);
|
|
@@ -11588,39 +11761,46 @@ async function stopExistingViewer(dbPath, target) {
|
|
|
11588
11761
|
stopped: false,
|
|
11589
11762
|
pid: viewerPid
|
|
11590
11763
|
};
|
|
11591
|
-
|
|
11592
|
-
rmSync(pidPath);
|
|
11593
|
-
} catch {}
|
|
11764
|
+
removeStoppedViewerPidRecords(dbPath, viewerPid);
|
|
11594
11765
|
return {
|
|
11595
11766
|
stopped: true,
|
|
11596
11767
|
pid: viewerPid
|
|
11597
11768
|
};
|
|
11598
11769
|
}
|
|
11599
|
-
|
|
11770
|
+
for (const { path, record } of readViewerPidRecords(dbPath)) {
|
|
11771
|
+
const result = await stopRecordedViewer(record);
|
|
11772
|
+
if (!result) continue;
|
|
11773
|
+
if (result.stopped) removeFile(path);
|
|
11774
|
+
return result;
|
|
11775
|
+
}
|
|
11776
|
+
return {
|
|
11600
11777
|
stopped: false,
|
|
11601
11778
|
pid: null
|
|
11602
11779
|
};
|
|
11780
|
+
}
|
|
11781
|
+
/** Stops the Viewer a PID record names when it answers and its process is trusted; else null. */
|
|
11782
|
+
async function stopRecordedViewer(record) {
|
|
11603
11783
|
const recordListenerPid = lookupListeningPid(record.host, record.port);
|
|
11604
|
-
if (await respondsLikeCodememViewer(record)
|
|
11784
|
+
if (!await respondsLikeCodememViewer(record) || !isTrustedViewerPid(record.pid, {
|
|
11605
11785
|
host: record.host,
|
|
11606
11786
|
port: record.port
|
|
11607
|
-
}, recordListenerPid))
|
|
11608
|
-
if (!await terminateTrustedViewerPid(record.pid)) return {
|
|
11609
|
-
stopped: false,
|
|
11610
|
-
pid: record.pid
|
|
11611
|
-
};
|
|
11612
|
-
} else return {
|
|
11613
|
-
stopped: false,
|
|
11614
|
-
pid: null
|
|
11615
|
-
};
|
|
11616
|
-
try {
|
|
11617
|
-
rmSync(pidPath);
|
|
11618
|
-
} catch {}
|
|
11787
|
+
}, recordListenerPid)) return null;
|
|
11619
11788
|
return {
|
|
11620
|
-
stopped:
|
|
11789
|
+
stopped: await terminateTrustedViewerPid(record.pid),
|
|
11621
11790
|
pid: record.pid
|
|
11622
11791
|
};
|
|
11623
11792
|
}
|
|
11793
|
+
function removeFile(path) {
|
|
11794
|
+
try {
|
|
11795
|
+
rmSync(path);
|
|
11796
|
+
} catch {}
|
|
11797
|
+
}
|
|
11798
|
+
/** After a stop: the current PID record, and an older release's record for the same process. */
|
|
11799
|
+
function removeStoppedViewerPidRecords(dbPath, pid) {
|
|
11800
|
+
const [current, ...older] = viewerPidFilePaths(resolveDbPath(dbPath));
|
|
11801
|
+
if (current) removeFile(current);
|
|
11802
|
+
for (const path of older) if (readViewerPidRecordAt(path)?.pid === pid) removeFile(path);
|
|
11803
|
+
}
|
|
11624
11804
|
function buildForegroundRunnerArgs(scriptPath, invocation, execArgv = process.execArgv) {
|
|
11625
11805
|
const args = [
|
|
11626
11806
|
...execArgv,
|
|
@@ -11746,13 +11926,22 @@ async function nativeRuntimeAllowsServeStart(invocation) {
|
|
|
11746
11926
|
if (invocation.mode !== "start" && invocation.mode !== "restart") return true;
|
|
11747
11927
|
const preflight = await preflightServeNativeRuntime(invocation);
|
|
11748
11928
|
if (preflight.state === "already_running") {
|
|
11749
|
-
|
|
11929
|
+
const message = `Viewer already running at http://${invocation.host}:${invocation.port}`;
|
|
11930
|
+
p.log.warn(message);
|
|
11931
|
+
reportViewerStartup({
|
|
11932
|
+
state: "failed",
|
|
11933
|
+
message
|
|
11934
|
+
});
|
|
11750
11935
|
if (!invocation.background) process.exitCode = 1;
|
|
11751
11936
|
return false;
|
|
11752
11937
|
}
|
|
11753
11938
|
if (preflight.state === "ready") return true;
|
|
11754
11939
|
p.intro("codemem viewer");
|
|
11755
11940
|
for (const line of preflight.diagnostics) p.log.error(line);
|
|
11941
|
+
reportViewerStartup({
|
|
11942
|
+
state: "failed",
|
|
11943
|
+
message: preflight.diagnostics.join(" ")
|
|
11944
|
+
});
|
|
11756
11945
|
process.exitCode = 1;
|
|
11757
11946
|
return false;
|
|
11758
11947
|
}
|
|
@@ -11811,22 +12000,37 @@ async function startBackgroundViewer(invocation) {
|
|
|
11811
12000
|
const child = spawn(process.execPath, buildForegroundRunnerArgs(scriptPath, invocation), {
|
|
11812
12001
|
cwd: process.cwd(),
|
|
11813
12002
|
detached: true,
|
|
11814
|
-
stdio:
|
|
12003
|
+
stdio: [
|
|
12004
|
+
"ignore",
|
|
12005
|
+
"ignore",
|
|
12006
|
+
"ignore",
|
|
12007
|
+
"ipc"
|
|
12008
|
+
],
|
|
11815
12009
|
env: {
|
|
11816
12010
|
...process.env,
|
|
11817
12011
|
...invocation.dbPath ? { CODEMEM_DB: invocation.dbPath } : {},
|
|
11818
|
-
...invocation.configPath ? { CODEMEM_CONFIG: invocation.configPath } : {}
|
|
12012
|
+
...invocation.configPath ? { CODEMEM_CONFIG: invocation.configPath } : {},
|
|
12013
|
+
[VIEWER_STARTUP_REPORT_ENV]: "1"
|
|
11819
12014
|
}
|
|
11820
12015
|
});
|
|
12016
|
+
const startup = await waitForViewerStartup(child, BACKGROUND_STARTUP_WAIT_MS);
|
|
11821
12017
|
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
12018
|
p.intro("codemem viewer");
|
|
11828
|
-
|
|
12019
|
+
if (startup.state === "failed") {
|
|
12020
|
+
p.log.error(startup.message);
|
|
12021
|
+
process.exitCode = 1;
|
|
12022
|
+
return;
|
|
12023
|
+
}
|
|
12024
|
+
const url = `http://${invocation.host}:${invocation.port}`;
|
|
12025
|
+
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
12026
|
}
|
|
12027
|
+
/**
|
|
12028
|
+
* How long a background start waits for the Viewer's startup result. It covers
|
|
12029
|
+
* the Viewer's own wait for a releasing lock holder and stays under the plugin's
|
|
12030
|
+
* default 20-second command timeout. A Viewer that holds the lock but is still
|
|
12031
|
+
* preparing its database at that point counts as starting.
|
|
12032
|
+
*/
|
|
12033
|
+
var BACKGROUND_STARTUP_WAIT_MS = 15e3;
|
|
11830
12034
|
function startRawEventProcessing(dbPath, store, observer, createInbox) {
|
|
11831
12035
|
const sweeper = new RawEventSweeper(store, { observer });
|
|
11832
12036
|
const observerRuntime = new ObserverRuntimeController(observer, sweeper, () => new ObserverClient());
|
|
@@ -12051,6 +12255,8 @@ async function callMemoryToolForHost(store, name, args, caller) {
|
|
|
12051
12255
|
const { callCodememToolLocally } = await import("@codemem/mcp");
|
|
12052
12256
|
return callCodememToolLocally(store, name, args, caller);
|
|
12053
12257
|
}
|
|
12258
|
+
/** How often the running service checks Team setup completions with the coordinator. */
|
|
12259
|
+
var TEAM_SETUP_RECONCILIATION_INTERVAL_MS = 3e5;
|
|
12054
12260
|
function foregroundAppOptions(store, rawEventOptions, options) {
|
|
12055
12261
|
return {
|
|
12056
12262
|
accountLink: options.accountLink.options,
|
|
@@ -12058,7 +12264,8 @@ function foregroundAppOptions(store, rawEventOptions, options) {
|
|
|
12058
12264
|
syncReachability: options.relay?.reachability,
|
|
12059
12265
|
...rawEventOptions,
|
|
12060
12266
|
...options.coordinatorRefresh,
|
|
12061
|
-
getSyncRuntimeStatus: () => options.syncRuntimeStatus
|
|
12267
|
+
getSyncRuntimeStatus: () => options.syncRuntimeStatus,
|
|
12268
|
+
teamSetupReconciliationIntervalMs: TEAM_SETUP_RECONCILIATION_INTERVAL_MS
|
|
12062
12269
|
};
|
|
12063
12270
|
}
|
|
12064
12271
|
function createBoundApp(createApp, options, listener) {
|
|
@@ -12079,6 +12286,34 @@ function createBoundApp(createApp, options, listener) {
|
|
|
12079
12286
|
}
|
|
12080
12287
|
};
|
|
12081
12288
|
}
|
|
12289
|
+
/** Referenced for the process lifetime, so its connection, and the lock, stay open. */
|
|
12290
|
+
var heldViewerWriterLock = null;
|
|
12291
|
+
/**
|
|
12292
|
+
* Takes the database's Viewer lock, then stops a leftover maintenance worker;
|
|
12293
|
+
* false when another Viewer holds the lock. The pid file check before it is
|
|
12294
|
+
* advisory and can race. The lock cannot, so two Viewers never interleave Team
|
|
12295
|
+
* setup changes whose locks only work inside one process.
|
|
12296
|
+
*/
|
|
12297
|
+
async function takeOverViewerRuntime(dbPath, target) {
|
|
12298
|
+
const claim = await claimViewerWriterLock(dbPath, target, viewerLockDependencies);
|
|
12299
|
+
if (claim.status === "refused") {
|
|
12300
|
+
reportViewerStartup({
|
|
12301
|
+
state: "failed",
|
|
12302
|
+
message: claim.message
|
|
12303
|
+
});
|
|
12304
|
+
p.intro("codemem viewer");
|
|
12305
|
+
p.log.error(claim.message);
|
|
12306
|
+
process.exitCode = 1;
|
|
12307
|
+
return false;
|
|
12308
|
+
}
|
|
12309
|
+
heldViewerWriterLock = claim.lock;
|
|
12310
|
+
reportViewerStartup({ state: "lock_acquired" });
|
|
12311
|
+
if (!await terminateTrustedMaintenanceWorker(dbPath, {
|
|
12312
|
+
gracefulMs: 1e3,
|
|
12313
|
+
forceMs: 5e3
|
|
12314
|
+
})) p.log.warn("Existing maintenance worker is not trusted or did not stop; starting viewer anyway");
|
|
12315
|
+
return true;
|
|
12316
|
+
}
|
|
12082
12317
|
async function startForegroundViewer(invocation) {
|
|
12083
12318
|
const serverModule = await import("@codemem/server");
|
|
12084
12319
|
const { createApp, createSyncApp, closeStoreAsync, createViewerRawEventInbox, getStore } = serverModule;
|
|
@@ -12089,10 +12324,7 @@ async function startForegroundViewer(invocation) {
|
|
|
12089
12324
|
if (invocation.configPath) process.env.CODEMEM_CONFIG = invocation.configPath;
|
|
12090
12325
|
warnIfViewerExposed(invocation.host, invocation.port);
|
|
12091
12326
|
const dbPath = resolveDbPath(invocation.dbPath ?? void 0);
|
|
12092
|
-
if (!await
|
|
12093
|
-
gracefulMs: 1e3,
|
|
12094
|
-
forceMs: 5e3
|
|
12095
|
-
})) p.log.warn("Existing maintenance worker is not trusted or did not stop; starting viewer anyway");
|
|
12327
|
+
if (!await takeOverViewerRuntime(dbPath, invocation)) return;
|
|
12096
12328
|
const preparedDb = prepareViewerDatabase(invocation.dbPath);
|
|
12097
12329
|
const observer = new ObserverClient();
|
|
12098
12330
|
let store;
|
|
@@ -12168,6 +12400,7 @@ async function startForegroundViewer(invocation) {
|
|
|
12168
12400
|
preparedDb,
|
|
12169
12401
|
info
|
|
12170
12402
|
});
|
|
12403
|
+
reportViewerStartup({ state: "listening" });
|
|
12171
12404
|
maintenanceWorker = startMaintenanceWorkerProcess(invocation);
|
|
12172
12405
|
if (syncEnabled) scheduleServeSyncDaemon({
|
|
12173
12406
|
invocation,
|
|
@@ -12181,8 +12414,7 @@ async function startForegroundViewer(invocation) {
|
|
|
12181
12414
|
});
|
|
12182
12415
|
});
|
|
12183
12416
|
server.on("error", (err) => {
|
|
12184
|
-
|
|
12185
|
-
else p.log.error(err.message);
|
|
12417
|
+
reportViewerListenError(err, invocation);
|
|
12186
12418
|
requestShutdown(1);
|
|
12187
12419
|
});
|
|
12188
12420
|
let shutdownPromise;
|
|
@@ -12215,6 +12447,7 @@ async function startForegroundViewer(invocation) {
|
|
|
12215
12447
|
shutdownExitCode = 1;
|
|
12216
12448
|
logViewerShutdownError(error);
|
|
12217
12449
|
}
|
|
12450
|
+
heldViewerWriterLock?.release();
|
|
12218
12451
|
}
|
|
12219
12452
|
process.exit(shutdownExitCode);
|
|
12220
12453
|
};
|
|
@@ -12227,6 +12460,22 @@ async function startForegroundViewer(invocation) {
|
|
|
12227
12460
|
process.on("SIGINT", () => requestShutdown());
|
|
12228
12461
|
process.on("SIGTERM", () => requestShutdown());
|
|
12229
12462
|
}
|
|
12463
|
+
function reportViewerListenError(err, invocation) {
|
|
12464
|
+
if (err.code === "EADDRINUSE") {
|
|
12465
|
+
const message = `Viewer already running at http://${invocation.host}:${invocation.port}`;
|
|
12466
|
+
p.log.warn(message);
|
|
12467
|
+
reportViewerStartup({
|
|
12468
|
+
state: "failed",
|
|
12469
|
+
message
|
|
12470
|
+
});
|
|
12471
|
+
return;
|
|
12472
|
+
}
|
|
12473
|
+
p.log.error(err.message);
|
|
12474
|
+
reportViewerStartup({
|
|
12475
|
+
state: "failed",
|
|
12476
|
+
message: err.message
|
|
12477
|
+
});
|
|
12478
|
+
}
|
|
12230
12479
|
function logViewerShutdownError(error) {
|
|
12231
12480
|
p.log.error(error instanceof Error ? error.message : String(error));
|
|
12232
12481
|
}
|
|
@@ -12261,60 +12510,86 @@ async function runServeInvocation(invocation, dependencies = {
|
|
|
12261
12510
|
port: invocation.port
|
|
12262
12511
|
});
|
|
12263
12512
|
if (runtimeConflict) {
|
|
12513
|
+
const message = `Database runtime at ${viewerRuntimeDir(dbPath)} is already managed by viewer ${runtimeConflict.host}:${runtimeConflict.port} (pid ${runtimeConflict.pid})`;
|
|
12264
12514
|
p.intro("codemem viewer");
|
|
12265
|
-
p.log.error(
|
|
12515
|
+
p.log.error(message);
|
|
12266
12516
|
p.log.info("Use the matching --host/--port, stop the existing viewer first, or use a separate db/runtime folder for another viewer.");
|
|
12517
|
+
reportViewerStartup({
|
|
12518
|
+
state: "failed",
|
|
12519
|
+
message
|
|
12520
|
+
});
|
|
12267
12521
|
process.exitCode = 1;
|
|
12268
12522
|
return;
|
|
12269
12523
|
}
|
|
12270
12524
|
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
|
-
|
|
12297
|
-
|
|
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
|
-
}
|
|
12525
|
+
if ((invocation.mode === "stop" || invocation.mode === "restart") && !await stopBeforeStart(invocation, dbPath, dependencies.stopExistingViewer)) return;
|
|
12526
|
+
if (invocation.mode === "start" || invocation.mode === "restart") await (dependencies.startViewer ?? startViewer)({
|
|
12527
|
+
...invocation,
|
|
12528
|
+
dbPath
|
|
12529
|
+
});
|
|
12530
|
+
}
|
|
12531
|
+
async function stopMaintenanceWorkerAfterStop(dbPath) {
|
|
12532
|
+
if (!await terminateTrustedMaintenanceWorker(dbPath, {
|
|
12533
|
+
gracefulMs: 5e3,
|
|
12534
|
+
forceMs: 5e3
|
|
12535
|
+
})) p.log.warn("Maintenance worker pidfile exists but did not match trusted worker command");
|
|
12536
|
+
}
|
|
12537
|
+
/**
|
|
12538
|
+
* Stops the existing Viewer for `stop` and `restart`. Returns true when a restart
|
|
12539
|
+
* may start the new Viewer: the old one has stopped, its port is free or reported,
|
|
12540
|
+
* and it no longer holds the database's lock.
|
|
12541
|
+
*/
|
|
12542
|
+
async function stopBeforeStart(invocation, dbPath, stop) {
|
|
12543
|
+
const result = await stop(dbPath, {
|
|
12544
|
+
host: invocation.host,
|
|
12545
|
+
port: invocation.port
|
|
12546
|
+
});
|
|
12547
|
+
if (result.pid && !result.stopped) {
|
|
12548
|
+
p.intro("codemem viewer");
|
|
12549
|
+
p.log.error(`Viewer is still shutting down (pid ${result.pid})`);
|
|
12550
|
+
process.exitCode = 1;
|
|
12551
|
+
return false;
|
|
12304
12552
|
}
|
|
12305
|
-
if (
|
|
12306
|
-
if (invocation.
|
|
12307
|
-
|
|
12308
|
-
|
|
12309
|
-
|
|
12310
|
-
|
|
12311
|
-
return;
|
|
12312
|
-
}
|
|
12313
|
-
await startForegroundViewer({
|
|
12314
|
-
...invocation,
|
|
12315
|
-
dbPath
|
|
12316
|
-
});
|
|
12553
|
+
if (!result.stopped) {
|
|
12554
|
+
if (invocation.mode !== "stop") return true;
|
|
12555
|
+
p.intro("codemem viewer");
|
|
12556
|
+
await stopMaintenanceWorkerAfterStop(dbPath);
|
|
12557
|
+
reportNothingStopped(dbPath);
|
|
12558
|
+
return false;
|
|
12317
12559
|
}
|
|
12560
|
+
p.intro("codemem viewer");
|
|
12561
|
+
p.log.success(`Stopped viewer${result.pid ? ` (pid ${result.pid})` : ""}`);
|
|
12562
|
+
await stopMaintenanceWorkerAfterStop(dbPath);
|
|
12563
|
+
if (invocation.mode === "stop") {
|
|
12564
|
+
p.outro("done");
|
|
12565
|
+
return false;
|
|
12566
|
+
}
|
|
12567
|
+
return waitForStoppedViewer(invocation, dbPath);
|
|
12568
|
+
}
|
|
12569
|
+
/**
|
|
12570
|
+
* After a stop that found no Viewer to stop: whether something still holds the
|
|
12571
|
+
* database. The owner record is only reported; nothing is signalled because of it.
|
|
12572
|
+
*/
|
|
12573
|
+
function reportNothingStopped(dbPath) {
|
|
12574
|
+
if (!isViewerWriterLockHeld(dbPath)) {
|
|
12575
|
+
p.outro("No background viewer found");
|
|
12576
|
+
return;
|
|
12577
|
+
}
|
|
12578
|
+
const owner = readViewerWriterLockOwner(dbPath);
|
|
12579
|
+
const holder = owner ? `pid ${owner.pid}, unverified` : "no holder recorded";
|
|
12580
|
+
p.log.error(`The database is locked by another process (${holder}).`);
|
|
12581
|
+
p.log.info(viewerLockHolderHint(owner));
|
|
12582
|
+
process.exitCode = 1;
|
|
12583
|
+
}
|
|
12584
|
+
async function waitForStoppedViewer(invocation, dbPath) {
|
|
12585
|
+
if (!await waitForPortRelease(invocation.host, invocation.port)) p.log.warn(`Port ${invocation.port} still in use after stop — restart may fail`);
|
|
12586
|
+
if (await waitForViewerWriterLockRelease(dbPath, viewerLockDependencies, { timeoutMs: 1e4 })) return true;
|
|
12587
|
+
p.log.error(`The stopped viewer still holds ${dbPath}; not starting another one.`);
|
|
12588
|
+
process.exitCode = 1;
|
|
12589
|
+
return false;
|
|
12590
|
+
}
|
|
12591
|
+
function startViewer(invocation) {
|
|
12592
|
+
return invocation.background ? startBackgroundViewer(invocation) : startForegroundViewer(invocation);
|
|
12318
12593
|
}
|
|
12319
12594
|
var serveCmd = new Command("serve").configureHelp(helpStyle).description("Run the local service (compatibility entrypoint; see service)").argument("[action]", "lifecycle action (start|stop|restart)");
|
|
12320
12595
|
addDbOption(serveCmd);
|
|
@@ -12340,7 +12615,12 @@ var serveCommand = serveCmd.action(async (action, opts) => {
|
|
|
12340
12615
|
}
|
|
12341
12616
|
await runServeInvocation(resolveServeInvocation(normalizedAction, opts));
|
|
12342
12617
|
} catch (err) {
|
|
12343
|
-
|
|
12618
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
12619
|
+
p.log.error(message);
|
|
12620
|
+
reportViewerStartup({
|
|
12621
|
+
state: "failed",
|
|
12622
|
+
message
|
|
12623
|
+
});
|
|
12344
12624
|
process.exitCode = 1;
|
|
12345
12625
|
}
|
|
12346
12626
|
});
|
|
@@ -12438,22 +12718,59 @@ function boundAttention(items) {
|
|
|
12438
12718
|
message: item.message.slice(0, 500)
|
|
12439
12719
|
}));
|
|
12440
12720
|
}
|
|
12441
|
-
|
|
12442
|
-
|
|
12443
|
-
|
|
12444
|
-
if (
|
|
12721
|
+
/** How long before `checkedAt` an ISO time was, such as "3h"; null when unparseable. */
|
|
12722
|
+
function ageBefore(iso, checkedAt) {
|
|
12723
|
+
const parsed = Date.parse(iso ?? "");
|
|
12724
|
+
if (!Number.isFinite(parsed)) return null;
|
|
12725
|
+
const seconds = Math.max(0, Math.round((checkedAt.getTime() - parsed) / 1e3));
|
|
12726
|
+
if (seconds < 60) return `${seconds}s`;
|
|
12727
|
+
const minutes = Math.round(seconds / 60);
|
|
12728
|
+
if (minutes < 60) return `${minutes}m`;
|
|
12729
|
+
const hours = Math.round(minutes / 60);
|
|
12730
|
+
if (hours < 48) return `${hours}h`;
|
|
12731
|
+
return `${Math.round(hours / 24)}d`;
|
|
12732
|
+
}
|
|
12733
|
+
function plural(count, singular, pluralForm) {
|
|
12734
|
+
return `${count} ${count === 1 ? singular : pluralForm}`;
|
|
12735
|
+
}
|
|
12736
|
+
/**
|
|
12737
|
+
* A daemon error is a sync error only while no peer has synced since. When peers
|
|
12738
|
+
* sync after it, the error came from other daemon work, such as coordinator
|
|
12739
|
+
* maintenance, and syncing itself works.
|
|
12740
|
+
*/
|
|
12741
|
+
function peersSyncedSinceDaemonError(sync) {
|
|
12742
|
+
const errorAt = Date.parse(sync.daemon_error_at ?? "");
|
|
12743
|
+
const syncedAt = Date.parse(sync.latest_peer_sync_at ?? "");
|
|
12744
|
+
return Number.isFinite(errorAt) && Number.isFinite(syncedAt) && syncedAt > errorAt;
|
|
12745
|
+
}
|
|
12746
|
+
function projectDaemonError(sync, checkedAt, attention) {
|
|
12747
|
+
const age = ageBefore(sync.daemon_error_at, checkedAt);
|
|
12748
|
+
const when = age ? ` ${age} ago` : "";
|
|
12749
|
+
if (!sync.needs_attention && peersSyncedSinceDaemonError(sync)) {
|
|
12750
|
+
const syncedAge = ageBefore(sync.latest_peer_sync_at, checkedAt);
|
|
12445
12751
|
attention.push({
|
|
12446
|
-
code: "
|
|
12447
|
-
severity: "
|
|
12448
|
-
message:
|
|
12752
|
+
code: "sync_daemon_warning",
|
|
12753
|
+
severity: "warning",
|
|
12754
|
+
message: `The sync daemon reported a problem${when}, but peers have synced since (last ${syncedAge} ago); run \`codemem sync doctor\``
|
|
12449
12755
|
});
|
|
12450
|
-
return "
|
|
12756
|
+
return "degraded";
|
|
12451
12757
|
}
|
|
12758
|
+
attention.push({
|
|
12759
|
+
code: "sync_daemon_error",
|
|
12760
|
+
severity: "error",
|
|
12761
|
+
message: sync.needs_attention ? "Sync requires attention; run `codemem sync doctor`" : `Sync has not succeeded since an error${when}; run \`codemem sync doctor\``
|
|
12762
|
+
});
|
|
12763
|
+
return "error";
|
|
12764
|
+
}
|
|
12765
|
+
function projectSync(enabled, snapshot, checkedAt, attention) {
|
|
12766
|
+
if (!enabled) return "disabled";
|
|
12767
|
+
if (!snapshot) return "unknown";
|
|
12768
|
+
if (snapshot.sync.daemon_error || snapshot.sync.needs_attention) return projectDaemonError(snapshot.sync, checkedAt, attention);
|
|
12452
12769
|
if (snapshot.sync.peer_errors > 0) {
|
|
12453
12770
|
attention.push({
|
|
12454
12771
|
code: "sync_degraded",
|
|
12455
12772
|
severity: "warning",
|
|
12456
|
-
message: "
|
|
12773
|
+
message: `${plural(snapshot.sync.peer_errors, "peer", "peers")} failed the last sync attempt; run \`codemem sync peers\` or \`codemem sync doctor\``
|
|
12457
12774
|
});
|
|
12458
12775
|
return "degraded";
|
|
12459
12776
|
}
|
|
@@ -12501,7 +12818,7 @@ function addRuntimeAttention(runtime, attention) {
|
|
|
12501
12818
|
}[runtime.attention_code]
|
|
12502
12819
|
});
|
|
12503
12820
|
}
|
|
12504
|
-
function projectDatabaseSubsystems(snapshot, configuredObserver, attention) {
|
|
12821
|
+
function projectDatabaseSubsystems(snapshot, configuredObserver, checkedAt, attention) {
|
|
12505
12822
|
if (!snapshot) return {
|
|
12506
12823
|
maintenance: { state: "unknown" },
|
|
12507
12824
|
semantic_index: { state: "unknown" },
|
|
@@ -12567,7 +12884,7 @@ function projectDatabaseSubsystems(snapshot, configuredObserver, attention) {
|
|
|
12567
12884
|
attention.push({
|
|
12568
12885
|
code: "observer_recent_failures",
|
|
12569
12886
|
severity: "warning",
|
|
12570
|
-
message:
|
|
12887
|
+
message: recentObserverFailureMessage(snapshot.observer, checkedAt)
|
|
12571
12888
|
});
|
|
12572
12889
|
}
|
|
12573
12890
|
return {
|
|
@@ -12580,6 +12897,12 @@ function projectDatabaseSubsystems(snapshot, configuredObserver, attention) {
|
|
|
12580
12897
|
observer: { state: observerState }
|
|
12581
12898
|
};
|
|
12582
12899
|
}
|
|
12900
|
+
/** "Recently" is the last 24 hours; the message says how many failed and how long ago. */
|
|
12901
|
+
function recentObserverFailureMessage(observer, checkedAt) {
|
|
12902
|
+
const failed = plural(observer.recent_failed_batches, "observer batch", "observer batches");
|
|
12903
|
+
const age = ageBefore(observer.latest_recent_failure_at, checkedAt);
|
|
12904
|
+
return `${failed} failed in the last 24 hours${age ? `, most recently ${age} ago` : ""}. Run \`codemem diagnostics capture status\``;
|
|
12905
|
+
}
|
|
12583
12906
|
async function collectStatusReport(opts, deps = defaultDependencies) {
|
|
12584
12907
|
const checkedAt = deps.now();
|
|
12585
12908
|
const config = deps.readConfig(opts.config);
|
|
@@ -12603,16 +12926,15 @@ async function collectStatusReport(opts, deps = defaultDependencies) {
|
|
|
12603
12926
|
db.close();
|
|
12604
12927
|
}
|
|
12605
12928
|
}
|
|
12606
|
-
const
|
|
12607
|
-
const runtime = await observeViewerRuntime(parseViewerPidRecord(deps.exists(pidPath) ? deps.readText(pidPath) : null), {
|
|
12929
|
+
const runtime = await observeViewerRuntime(parseViewerPidRecord(readViewerPidFile(dbPath, (path) => deps.exists(path) ? deps.readText(path) : null)), {
|
|
12608
12930
|
fetch: deps.fetch,
|
|
12609
12931
|
isProcessRunning: deps.isProcessRunning
|
|
12610
12932
|
}, viewerDefaultTarget(deps.env));
|
|
12611
12933
|
const attention = [];
|
|
12612
12934
|
addDatabaseAttention(databaseState, attention);
|
|
12613
12935
|
addRuntimeAttention(runtime, attention);
|
|
12614
|
-
const sync = projectSync(syncEnabled(config, deps.env), snapshot, attention);
|
|
12615
|
-
const subsystems = projectDatabaseSubsystems(snapshot, observerConfigured(config, deps.env), attention);
|
|
12936
|
+
const sync = projectSync(syncEnabled(config, deps.env), snapshot, checkedAt, attention);
|
|
12937
|
+
const subsystems = projectDatabaseSubsystems(snapshot, observerConfigured(config, deps.env), checkedAt, attention);
|
|
12616
12938
|
const ok = !attention.some((item) => item.severity === "error");
|
|
12617
12939
|
const boundedAttention = boundAttention(attention);
|
|
12618
12940
|
return {
|
|
@@ -14845,7 +15167,8 @@ async function portOpen(host, port) {
|
|
|
14845
15167
|
}
|
|
14846
15168
|
function readViewerBinding(dbPath) {
|
|
14847
15169
|
try {
|
|
14848
|
-
const raw =
|
|
15170
|
+
const raw = readViewerPidFile(dbPath);
|
|
15171
|
+
if (raw === null) return null;
|
|
14849
15172
|
const parsed = JSON.parse(raw);
|
|
14850
15173
|
if (typeof parsed.host === "string" && typeof parsed.port === "number") return {
|
|
14851
15174
|
host: parsed.host,
|