codemem 0.50.0-beta.2 → 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 CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { ACCOUNT_CONNECTION_MIGRATION_STATEMENTS, ACCOUNT_UNLINK_MIGRATION_STATEMENTS, ALLOWED_MEMORY_KINDS, AUTH_LINK_AUTHORITY_CUTOVER_SQL, ContextOnlyReplayError, CoordinatorAccountLinkError, DEDUP_KEY_BACKFILL_JOB, DEFAULT_COORDINATOR_DB_PATH, DEFAULT_RAW_EVENT_FLUSH_MAX_EVENTS, DedupKeyBackfillRunner, DeviceIdentityError, EXTRACTION_BENCHMARK_QUALITY_WEIGHTS, FILE_CONTEXT_TRANSPORT_MAX_BYTES, FILE_CONTEXT_TRANSPORT_PROFILE, LEGACY_OWNER_RESOLUTION_SCHEMA_STATEMENTS, MUTATING_TOOL_NAMES, MemoryStore, ObserverClient, ObserverOutputError, ObserverOutputTransportError, OwnerProfileEnrollmentError, PROMPT_TRANSPORT_PROTOCOL_RANGE, REF_BACKFILL_JOB, RawEventIngestValidationError, RawEventSweeper, RefBackfillRunner, RemoteCoordinatorRequestError, SCOPE_BACKFILL_JOB, SESSION_CONTEXT_BACKFILL_JOB, SUMMARY_DEDUP_BACKFILL_JOB, ScopeBackfillRunner, SessionContextBackfillRunner, SummaryDedupBackfillRunner, SyncRetentionRunner, TRUSTED_HOOK_MAPPER_OPTIONS, VERSION, VectorModelMigrationRunner, aiBackfillStructuredContent, applyBootstrapSnapshot, applyDistillRule, arePromptTransportProtocolRangesCompatible, atomicReplaceConfigFile, backfillMemoryDedupKeys, backfillNarrativeFromBody, backfillTagsText, backfillVectors, buildBaseUrl, buildDirectPeerAuthHeaders, buildDistillReport, buildPiFlushSignalFromEvent, buildRawEventEnvelopeFromHook, buildRawEventEnvelopeFromPiEvent, buildTieredObserverSelection, buildViewerIdentityTarget, classifyPromptTransportFailure, clonePromptPackAttempt, collectOperationalStatus, compareMemoryRoleReports, connect, connectReadOnly, coordinatorAuthControllerReviewAction, coordinatorAuthStageBaselineSql, coordinatorCreateGroupAction, coordinatorCreateScopeAction, coordinatorD1BaselineMigrations, coordinatorD1ConditionalBaselineMigrations, coordinatorDisableDeviceAction, coordinatorEnableDeviceAction, coordinatorEnrollDeviceAction, coordinatorGrantIdentityGroupAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListRemovedDevicesAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorQualifyOwnerAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorReviewInviteAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeDeviceAction, coordinatorRevokeScopeMembershipAction, coordinatorUpdateScopeAction, createBetterSqliteCoordinatorApp, createCoordinatorRefreshLifecycle, createFileContextRunner, deactivateLowSignalMemories, dedupNearDuplicateMemories, describePiObserverStatus, detectInstallKind, diagnoseLegacyTeamSetupCompletion, dispatchFileContextTransport, draftDistillRule, enrollOwnerProfile, ensureDeviceIdentity, ensureSchemaBootstrapped, estimateExtractionModelCost, expandUserPath, exportMemories, extractApplyPatchPaths, extractionReplayObserverIdentity, fetchAllSnapshotPages, fingerprintPublicKey, flushRawEvents, formatHostPort, getAttributionDiagnostics, getCodememConfigPath, getExtractionBenchmarkProfile, getExtractionModelPricing, getInjectionEvalScenarioPack, getInjectionEvalScenarioPrompts, getMaintenanceJob, getMemoryArtifactReport, getMemoryRoleReport, getRawEventRelinkPlan, getRawEventRelinkReport, getRawEventStatus, getSessionExtractionEval, getSessionExtractionEvalScenario, getUpdateStatus, getWorkspaceCodememConfigPath, hasPendingDedupKeyBackfill, hasPendingRefBackfill, hasPendingScopeBackfill, hasPendingSessionContextBackfill, hasPendingSummaryDedupBackfill, hasUnsyncedSharedMemoryChanges, importMemories, importPiSessions, ingestRawEvents, initDatabase, isAutomaticRecallMeasurement, isCoordinatorControllerAttestationReference, isEmbeddingDisabled, isExplicitUpdateInstallEligible, isReleaseVersionForChannel, judgeDistillReport, legacyTeamCandidateId, linkCoordinatorAccount, linkCoordinatorAccountHeadless, listMaintenanceJobs, listPerPeerScopeSyncState, listRetentionScopeIds, loadObserverConfig, loadPublicKey, loadRuntimeSigningPublicKey, loadSqliteVec, mdnsEnabled, mutateCodememConfigFile, normalizeCoordinatorAccountLinkOrigin, normalizePromptTransportProtocolRange, observerBaseUrlForProviderOverride, parseControllerHistoryEvidence, parseFileContextTransportRequest, peerProjectFilterChangeOnlyNarrows, planReplicationOpsAgePrune, probeCodememViewerLiveness, probeCodememViewerLiveness as probeCodememViewerLiveness$1, probeRequiredNativeRuntime, projectMatchesFilter, promptPackArtifactFingerprint, pruneReplicationOpsUntilCaughtUp, rawEventsGate, readAccountLinkDevice, readCodememConfigFile, readCodememConfigFileAtPath, readCoordinatorAccountLinkStatus, readCoordinatorOwnerReviewLocalEvidence, readCoordinatorSyncConfig, readImportPayload, readPeerProjectFilterAuthority, recordAutomaticRecall, recordPromptPackArtifacts, recordPromptPackTerminal, refreshCoordinatorForDaemon, rememberPeerProjectFilterManagement, removePeerFromThisDevice, renderUnifiedDiff, replayBatchExtraction, replayBatchExtractionWithTierRouting, requestJson, resolveCodememConfigPath, resolveComparablePath, resolveDbPath, resolveHookProject, resolveKeyPaths, resolvePiAgentDir, resolvePiObserverConfig, resolveProject, resolveProjectRoot, retryRawEventFailures, runDeviceRejoin, runSyncDaemon, runSyncPass, scanSecretsRetroactive, schema, scoreExtractionBenchmarkOutput, searchPiSessions, setPeerProjectFilterChecked, syncPassPreflight, tryUpdateRetrievalDelivery, updatePeerAddresses, upgradeCoordinatorAccountSchemaFile, upgradeCoordinatorAuthSchemaFile, upgradeCoordinatorOwnerResolutionSchemaFile, vacuumDatabase, viewerUrl, withDiagnosticStoreSnapshot, writeCodememConfigFile } from "@codemem/core";
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";
@@ -413,7 +413,7 @@ function spoolLiveHookPayload(dir, payload, logPrefix) {
413
413
  const finalName = `zz-hook-live-${wallTime}-z${monotonicTime}-${suffix}`;
414
414
  const tmpPath = join(dir, tmpName);
415
415
  try {
416
- writeFileSync(tmpPath, JSON.stringify(payload), { encoding: "utf8" });
416
+ writeFileSync(tmpPath, JSON.stringify(sanitizeHookPayload(payload)), { encoding: "utf8" });
417
417
  renameSync(tmpPath, join(dir, finalName));
418
418
  } catch {
419
419
  try {
@@ -745,7 +745,7 @@ function createHookIngestSpool(cfg) {
745
745
  logHookEvent(`${cfg.logPrefix} failed to create spool dir`);
746
746
  return false;
747
747
  }
748
- const payloadText = JSON.stringify(payload);
748
+ const payloadText = JSON.stringify(sanitizeHookPayload(payload));
749
749
  const tmpName = `.hook-tmp-${process.pid}-${Date.now()}-${randomInt(1e3, 1e4)}.json`;
750
750
  const tmpPath = join(dir, tmpName);
751
751
  try {
@@ -1092,7 +1092,8 @@ function extractModifiedPathsFromHook(payload) {
1092
1092
  * or when SessionEnd just cleared the state. Failures are swallowed —
1093
1093
  * hook commands must never crash on state I/O errors.
1094
1094
  */
1095
- function trackHookSessionState(payload) {
1095
+ function trackHookSessionState(nativePayload) {
1096
+ const payload = sanitizeHookPayload(nativePayload);
1096
1097
  const sessionRaw = payload.session_id;
1097
1098
  if (typeof sessionRaw !== "string") return null;
1098
1099
  const sessionId = sessionRaw.trim();
@@ -2695,7 +2696,8 @@ async function spoolClaudeHttpFailure(runtime, httpResult) {
2695
2696
  * Ingest one Claude hook payload through the Viewer queue or local spool.
2696
2697
  * Boundary events retain locked direct ingestion as the terminal fallback.
2697
2698
  */
2698
- async function ingestClaudeHookPayload(payload, opts, deps = {}) {
2699
+ async function ingestClaudeHookPayload(nativePayload, opts, deps = {}) {
2700
+ const payload = sanitizeHookPayload(nativePayload);
2699
2701
  try {
2700
2702
  trackHookSessionState(payload);
2701
2703
  } catch {}
@@ -3123,7 +3125,7 @@ async function ingestCodexHookPayload(payload, opts, deps = {}) {
3123
3125
  const httpIngest = deps.httpIngest ?? tryHttpIngest$1;
3124
3126
  const resolveDb = deps.resolveDb ?? resolveDbPath;
3125
3127
  const port = typeof opts.port === "number" ? opts.port : Number.parseInt(opts.port, 10);
3126
- const ingestPayload = normalizePayloadForIngest(payload);
3128
+ const ingestPayload = normalizePayloadForIngest(sanitizeHookPayload(payload));
3127
3129
  let cachedDbPath = null;
3128
3130
  const getDbPath = () => {
3129
3131
  if (cachedDbPath === null) cachedDbPath = resolveDb(resolveDbOpt(opts));
@@ -3825,6 +3827,11 @@ var STAGES = [
3825
3827
  "prior_extension",
3826
3828
  "current"
3827
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
+ }
3828
3835
  /** Names the migrations that the statement records only when their objects exist. */
3829
3836
  function conditionalMigrationsText(stage) {
3830
3837
  const conditional = coordinatorD1ConditionalBaselineMigrations(stage);
@@ -3844,7 +3851,7 @@ function exportBaseline(options) {
3844
3851
  }
3845
3852
  const conditional = coordinatorD1ConditionalBaselineMigrations(options.stage);
3846
3853
  const always = migrations.filter((name) => !conditional.includes(name));
3847
- process.stdout.write(`-- Records ${always.length} migrations, ${always[0]} through ${always.at(-1)}, in the existing d1_migrations ledger\n-- only if auth-stage ${options.stage} readiness and the remaining table and column names match.\n${conditionalMigrationsText(options.stage)}-- The inventory does not check types, constraints, indexes, triggers or row validity. Compare the schema before applying.\n-- Otherwise it records nothing or fails to compile. "no such table: d1_migrations" means the ledger must be created first.\n-- Nothing has been applied.\n${statement};\n`);
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`);
3848
3855
  }
3849
3856
  function buildCoordinatorD1BaselineCommand() {
3850
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");
@@ -8151,6 +8158,15 @@ function renderAttributionDiagnostics(report) {
8151
8158
  ...report.limitations.map((limitation) => `- ${limitation}`)
8152
8159
  ].join("\n");
8153
8160
  }
8161
+ function renderRetrievalLedger(ledger) {
8162
+ const oldest = ledger.oldest_retrieval_attempt_started_at ?? "none";
8163
+ return [
8164
+ "Retrieval ledger",
8165
+ ` Attempts: ${ledger.retrieval_attempts.toLocaleString()} (${ledger.expired_retrieval_attempts.toLocaleString()} past retention), oldest ${oldest}`,
8166
+ ` Exposures: ${ledger.retrieval_exposures.toLocaleString()} (${ledger.non_selected_retrieval_exposures.toLocaleString()} not selected, ${ledger.stale_non_selected_retrieval_exposures.toLocaleString()} of them older than ${NON_SELECTED_EXPOSURE_RETENTION_DAYS} days)`,
8167
+ ` Outcome evidence: ${ledger.outcome_evidence.toLocaleString()} (${ledger.expired_outcome_evidence.toLocaleString()} past retention)`
8168
+ ].join("\n");
8169
+ }
8154
8170
  var statsAction = (opts) => {
8155
8171
  const store = new MemoryStore(resolveDbPath(resolveDbOpt(opts)));
8156
8172
  try {
@@ -8159,7 +8175,10 @@ var statsAction = (opts) => {
8159
8175
  console.log(opts.json ? JSON.stringify(report, null, 2) : renderAttributionDiagnostics(report));
8160
8176
  return;
8161
8177
  }
8162
- const result = store.stats();
8178
+ const result = {
8179
+ ...store.stats(),
8180
+ retrieval_ledger: retrievalLedgerStats(store.db)
8181
+ };
8163
8182
  if (opts.json) {
8164
8183
  console.log(JSON.stringify(result, null, 2));
8165
8184
  return;
@@ -8176,6 +8195,7 @@ var statsAction = (opts) => {
8176
8195
  `Vectors: ${db.vector_rows.toLocaleString()} (${fmtPct(db.vector_coverage)} coverage)`,
8177
8196
  `Raw events: ${db.raw_events.toLocaleString()}`
8178
8197
  ].join("\n"));
8198
+ p.log.step(renderRetrievalLedger(result.retrieval_ledger));
8179
8199
  if (result.usage.events.length > 0) {
8180
8200
  const provenanceByEvent = new Map(result.usage.provenance.events.map((event) => [event.event, event]));
8181
8201
  const lines = result.usage.events.map((event) => formatUsageEvent(event, provenanceByEvent.get(event.event)));
@@ -8681,7 +8701,7 @@ function createMemoryExtractionReplayCommand() {
8681
8701
  `Observer: ${result.observer.provider}/${result.observer.model}`,
8682
8702
  `Tier: ${result.observer.tier ?? "manual"}`,
8683
8703
  `OpenAI Responses: ${result.observer.openaiUseResponses ? "yes" : "no"}`,
8684
- `Reasoning effort: ${result.observer.reasoningEffort ?? "none"}`,
8704
+ `Reasoning effort: ${formatTransmittedReasoningEffort(result.observer)}`,
8685
8705
  `Classification: ${result.classification.status}`,
8686
8706
  `Pass: ${result.evaluation.pass ? "yes" : "no"}`
8687
8707
  ].join("\n"));
@@ -8690,13 +8710,7 @@ function createMemoryExtractionReplayCommand() {
8690
8710
  p.log.warn("Failure reasons:");
8691
8711
  for (const reason of result.evaluation.failureReasons) p.log.message(` - ${reason}`);
8692
8712
  }
8693
- p.log.info([
8694
- `Fresh summaries: ${result.evaluation.counts.summaries}`,
8695
- `Fresh observations: ${result.evaluation.counts.observations}`,
8696
- `Summary thread coverage: ${result.evaluation.coverage.summaryThreadCoverage}`,
8697
- `Observation thread coverage: ${result.evaluation.coverage.observationThreadCoverage}`,
8698
- `Total thread coverage: ${result.evaluation.coverage.totalThreadCoverage}`
8699
- ].join("\n"));
8713
+ p.log.info(replayCoverageLines(result).join("\n"));
8700
8714
  p.outro("done");
8701
8715
  } catch (error) {
8702
8716
  if (error instanceof ContextOnlyReplayError) {
@@ -8737,6 +8751,76 @@ function reconcileExtractionBenchmarkStatus(input) {
8737
8751
  initialQuality: input.initialQuality
8738
8752
  };
8739
8753
  }
8754
+ /** Transports whose requests never carry a max output token limit. */
8755
+ var UNSENT_REQUEST_LIMIT_TRANSPORTS = /* @__PURE__ */ new Set(["codex_consumer", "opencode_v2"]);
8756
+ /** The effort a replayed request sent, and the requested effort when it was not sent. */
8757
+ function formatTransmittedReasoningEffort(observer) {
8758
+ if (observer.reasoningEffort) return observer.reasoningEffort;
8759
+ if (!observer.requestedReasoningEffort) return "not transmitted";
8760
+ const reason = observer.reasoningEffortFallbackReason;
8761
+ return `not transmitted (requested ${observer.requestedReasoningEffort}${reason ? `; ${reason}` : ""})`;
8762
+ }
8763
+ function benchmarkEffortFields(observer) {
8764
+ return {
8765
+ reasoningEffort: observer.reasoningEffort,
8766
+ requestedReasoningEffort: observer.requestedReasoningEffort,
8767
+ reasoningEffortFallbackApplied: observer.reasoningEffortFallbackApplied,
8768
+ reasoningEffortFallbackReason: observer.reasoningEffortFallbackReason
8769
+ };
8770
+ }
8771
+ /** Applied reasoning settings across runs, plus what was requested and how often it fell back. */
8772
+ function summarizeBenchmarkReasoningReport(runs, observer) {
8773
+ const requested = new Set(runs.map((run) => run.requestedReasoningEffort));
8774
+ return {
8775
+ ...summarizeBenchmarkReasoning(runs, observer),
8776
+ requestedReasoningEffort: requested.size > 1 ? "mixed" : runs[0]?.requestedReasoningEffort ?? observer.reasoningEffort,
8777
+ reasoningEffortFallbackRuns: runs.filter((run) => run.reasoningEffortFallbackApplied).length
8778
+ };
8779
+ }
8780
+ function formatBenchmarkReasoningEffort(summary) {
8781
+ const applied = summary.reasoningEffort ?? "not transmitted";
8782
+ if (summary.reasoningEffortFallbackRuns === 0) return applied;
8783
+ return `${applied} (requested ${summary.requestedReasoningEffort}; ${summary.reasoningEffortFallbackRuns} run(s) used the service default)`;
8784
+ }
8785
+ function replayCoverageLines(result) {
8786
+ return [
8787
+ `Prompt: ${formatPromptBudget(result.observer.promptBudget)}`,
8788
+ `Fresh summaries: ${result.evaluation.counts.summaries}`,
8789
+ `Fresh observations: ${result.evaluation.counts.observations}`,
8790
+ `Summary thread coverage: ${result.evaluation.coverage.summaryThreadCoverage}`,
8791
+ `Observation thread coverage: ${result.evaluation.coverage.observationThreadCoverage}`,
8792
+ `Total thread coverage: ${result.evaluation.coverage.totalThreadCoverage}`
8793
+ ];
8794
+ }
8795
+ /** One call's prompt lengths, for example "instructions 10419, content 12000 -> 3000 (clipped) of budget 12000". */
8796
+ function formatPromptBudget(budget) {
8797
+ if (!budget) return "not measured";
8798
+ const clipped = budget.contentClipped ? " (clipped)" : "";
8799
+ const over = budget.instructionsOverBudget ? "; instructions exceed the budget" : "";
8800
+ const sections = budget.sections ? `; sections ${budget.sections.map((section) => `${section.name} ${section.chars} -> ${section.sentChars}`).join(", ")}` : "";
8801
+ return `instructions ${budget.instructionChars}, content ${budget.contentChars} -> ${budget.sentContentChars}${clipped} of budget ${budget.maxChars}${over}${sections}`;
8802
+ }
8803
+ /** The budget across benchmark runs and how many runs clipped content or overran it. */
8804
+ function formatBenchmarkPromptBudget(runs) {
8805
+ const budgets = runs.flatMap((run) => run.promptBudget ? [run.promptBudget] : []);
8806
+ if (budgets.length === 0) return "not measured";
8807
+ const limits = new Set(budgets.map((budget) => budget.maxChars));
8808
+ const clipped = budgets.filter((budget) => budget.contentClipped).length;
8809
+ const over = budgets.filter((budget) => budget.instructionsOverBudget).length;
8810
+ return `${limits.size === 1 ? String(budgets[0]?.maxChars) : "mixed"}; content clipped in ${clipped}/${budgets.length} run(s); instructions over budget in ${over}`;
8811
+ }
8812
+ function benchmarkRunObserver(observer) {
8813
+ return {
8814
+ provider: observer.provider,
8815
+ model: observer.model,
8816
+ transport: observer.transport,
8817
+ requestedModel: observer.requestedModel,
8818
+ resolvedModel: observer.resolvedModel,
8819
+ modelFallbackApplied: observer.modelFallbackApplied,
8820
+ modelFallbackReason: observer.modelFallbackReason,
8821
+ promptBudget: observer.promptBudget
8822
+ };
8823
+ }
8740
8824
  function summarizeBenchmarkReasoning(runs, fallback) {
8741
8825
  const source = runs[0] ?? fallback;
8742
8826
  const reasoningEfforts = new Set(runs.map((run) => run.reasoningEffort));
@@ -8951,6 +9035,7 @@ function createMemoryExtractionBenchmarkCommand() {
8951
9035
  const outputFailures = [];
8952
9036
  const runs = [];
8953
9037
  const contextOnlySkips = [];
9038
+ const callFailures = [];
8954
9039
  for (let iteration = 1; iteration <= repetitions; iteration += 1) for (const batch of benchmark.batches) {
8955
9040
  const scenarioId = batch.scenarioId ?? benchmark.scenarioId;
8956
9041
  let selectedObserver = extractionReplayObserverIdentity(observer, null);
@@ -8980,7 +9065,10 @@ function createMemoryExtractionBenchmarkCommand() {
8980
9065
  });
8981
9066
  continue;
8982
9067
  }
8983
- if (!(error instanceof ObserverOutputError) && !(error instanceof ObserverOutputTransportError)) throw error;
9068
+ if (!(error instanceof ObserverOutputError) && !(error instanceof ObserverOutputTransportError)) {
9069
+ callFailures.push(benchmarkCallFailure(error, iteration, batch));
9070
+ continue;
9071
+ }
8984
9072
  if (opts.observerTierRouting !== true) selectedObserver = extractionReplayObserverIdentity(observer, null);
8985
9073
  const failureCost = estimateBenchmarkAttemptCost(selectedObserver.model, error.telemetry.totalUsage);
8986
9074
  outputFailures.push({
@@ -9077,18 +9165,12 @@ function createMemoryExtractionBenchmarkCommand() {
9077
9165
  status: reconciled.status,
9078
9166
  reason: reconciled.reason,
9079
9167
  tier: result.observer.tier ?? "manual",
9080
- provider: result.observer.provider,
9081
- model: result.observer.model,
9082
- transport: result.observer.transport,
9083
- requestedModel: result.observer.requestedModel,
9084
- resolvedModel: result.observer.resolvedModel,
9085
- modelFallbackApplied: result.observer.modelFallbackApplied,
9086
- modelFallbackReason: result.observer.modelFallbackReason,
9168
+ ...benchmarkRunObserver(result.observer),
9087
9169
  requestedOutputMode: result.observer.requestedOutputMode,
9088
9170
  actualOutputMode: result.observer.actualOutputMode,
9089
9171
  outputValidation: result.observer.outputValidation,
9090
9172
  openaiUseResponses: result.observer.openaiUseResponses,
9091
- reasoningEffort: result.observer.reasoningEffort,
9173
+ ...benchmarkEffortFields(result.observer),
9092
9174
  reasoningSummary: result.observer.reasoningSummary,
9093
9175
  maxOutputTokens: result.observer.maxOutputTokens,
9094
9176
  temperature: result.observer.temperature,
@@ -9164,22 +9246,21 @@ function createMemoryExtractionBenchmarkCommand() {
9164
9246
  knownElapsedRuns: knownElapsedRuns.length,
9165
9247
  totalKnownElapsedMs: knownElapsedRuns.reduce((sum, run) => sum + (run.telemetry.totalElapsedMs ?? 0), 0),
9166
9248
  output: summarizeExtractionBenchmarkReporting(attempts),
9167
- outputFailures
9249
+ outputFailures,
9250
+ callFailed: callFailures.length,
9251
+ callFailures
9168
9252
  };
9253
+ if (callFailures.length > 0) process.exitCode = 1;
9169
9254
  const uniqueObserverKeys = Array.from(new Set(attempts.map((run) => `${run.provider}::${run.model}::${run.transport}`)));
9170
9255
  const firstObserver = attempts[0];
9171
- const benchmarkReasoning = summarizeBenchmarkReasoning(attempts, {
9172
- reasoningEffort: observer.reasoningEffort,
9173
- reasoningSummary: observer.reasoningSummary
9174
- });
9256
+ const benchmarkReasoning = summarizeBenchmarkReasoningReport(attempts, observer);
9175
9257
  const observerSummary = opts.observerTierRouting === true ? {
9176
9258
  provider: uniqueObserverKeys.length === 1 ? firstObserver?.provider ?? observer.provider : "mixed",
9177
9259
  model: uniqueObserverKeys.length === 1 ? firstObserver?.model ?? observer.model : "mixed",
9178
9260
  transport: uniqueObserverKeys.length === 1 ? firstObserver?.transport ?? "unknown" : "mixed",
9179
9261
  tierRouting: true,
9180
9262
  openaiUseResponses: uniqueObserverKeys.length === 1 ? firstObserver?.openaiUseResponses ?? observer.openaiUseResponses : null,
9181
- reasoningEffort: benchmarkReasoning.reasoningEffort,
9182
- reasoningSummary: benchmarkReasoning.reasoningSummary,
9263
+ ...benchmarkReasoning,
9183
9264
  maxOutputTokens: uniqueObserverKeys.length === 1 ? firstObserver?.maxOutputTokens ?? null : null,
9184
9265
  temperature: uniqueObserverKeys.length === 1 ? firstObserver?.temperature ?? null : null,
9185
9266
  transcriptBudget: transcriptBudget ?? null,
@@ -9190,8 +9271,7 @@ function createMemoryExtractionBenchmarkCommand() {
9190
9271
  transport: firstObserver?.transport ?? observer.getStatus().runtime,
9191
9272
  tierRouting: false,
9192
9273
  openaiUseResponses: observer.openaiUseResponses,
9193
- reasoningEffort: benchmarkReasoning.reasoningEffort,
9194
- reasoningSummary: benchmarkReasoning.reasoningSummary,
9274
+ ...benchmarkReasoning,
9195
9275
  maxOutputTokens: firstObserver?.maxOutputTokens ?? null,
9196
9276
  temperature: firstObserver?.temperature ?? null,
9197
9277
  transcriptBudget: transcriptBudget ?? null,
@@ -9219,11 +9299,12 @@ function createMemoryExtractionBenchmarkCommand() {
9219
9299
  `Transport: ${observerSummary.transport}`,
9220
9300
  `Tier routing: ${opts.observerTierRouting === true ? "yes" : "no"}`,
9221
9301
  `OpenAI Responses: ${observerSummary.openaiUseResponses === null ? "mixed" : observerSummary.openaiUseResponses ? "yes" : "no"}`,
9222
- `Reasoning effort: ${observerSummary.reasoningEffort ?? "not transmitted"}`,
9302
+ `Reasoning effort: ${formatBenchmarkReasoningEffort(observerSummary)}`,
9223
9303
  `Reasoning summary: ${observerSummary.reasoningSummary ?? "not transmitted"}`,
9224
- `Max output tokens: ${observerSummary.transport === "codex_consumer" ? "not transmitted" : observerSummary.maxOutputTokens ?? "mixed"}`,
9304
+ `Max output tokens: ${UNSENT_REQUEST_LIMIT_TRANSPORTS.has(observerSummary.transport) ? "not transmitted" : observerSummary.maxOutputTokens ?? "mixed"}`,
9225
9305
  `Temperature: ${observerSummary.transport === "mixed" ? "mixed" : observerSummary.temperature ?? "not transmitted"}`,
9226
9306
  `Transcript budget override: ${transcriptBudget ?? "default"}`,
9307
+ `Prompt budget: ${formatBenchmarkPromptBudget(attempts)}`,
9227
9308
  `Repetitions: ${summary.repetitions}`,
9228
9309
  `Context-only skips: ${summary.contextOnlySkipped} (${summary.scheduledTotal} scheduled; ${summary.total} observer attempts)`,
9229
9310
  `Shape-quality passes: ${summary.shapeQualityPasses}/${summary.shapeQualityTotal}`,
@@ -9247,12 +9328,8 @@ function createMemoryExtractionBenchmarkCommand() {
9247
9328
  const missingRequired = run.quality?.requiredRecall.missingLabelIds.join(",") || "none";
9248
9329
  p.log.message(` [${run.batchId}#${run.iteration}] ${run.status.padEnd(18)} ${run.complexity.padEnd(10)} tier=${run.tier.padEnd(6)} expected=${(run.expectedTier ?? "n/a").padEnd(6)} mode=${run.requestedOutputMode}/${run.actualOutputMode} valid=${run.outputValidation} disposition=${run.quality?.summaryDisposition.actual ?? "n/a"}/${run.expectedSummaryDisposition} span=${String(run.analysis.eventSpan).padEnd(3)} prompts=${run.analysis.promptCount} tools=${String(run.analysis.toolCount).padEnd(2)} transcript=${run.analysis.transcriptLength} ${run.provider}/${run.model} [${run.transport}] initial=${run.initial.summaries}s/${run.initial.observations}o final=${run.summaries}s/${run.observations}o quality=${qualityLabel} coverage=${run.quality?.weightedQualityCoverage?.toFixed(3) ?? "n/a"} required_missing=${missingRequired} cost=${costLabel} latency=${latencyLabel} schema_loss=${run.initial.diagnostics?.dataLoss === true ? "yes" : "no"} fallback=${run.modelFallbackApplied ? "yes" : "no"} repair=${run.repairApplied ? "yes" : "no"} retry=${run.retryAttempted ? run.retryReason ?? "yes" : "no"} — ${run.label}`);
9249
9330
  }
9250
- for (const failure of outputFailures.toSorted((left, right) => left.iteration - right.iteration || left.batchId - right.batchId)) {
9251
- const costLabel = failure.cost.total == null ? "n/a" : `$${failure.cost.total.totalCostUsd.toFixed(6)}`;
9252
- const latencyLabel = failure.telemetry.totalElapsedMs == null ? "n/a" : `${failure.telemetry.totalElapsedMs}ms`;
9253
- p.log.error(` [${failure.batchId}#${failure.iteration}] output_failure tier=${failure.tier ?? "n/a"} expected=${failure.expectedTier ?? "n/a"} mode=${failure.requestedOutputMode}/${failure.actualOutputMode} model=${failure.model ?? "unresolved"} cost=${costLabel} latency=${latencyLabel} — ${failure.reason}`);
9254
- }
9255
- p.outro("done");
9331
+ logBenchmarkFailures(outputFailures, callFailures);
9332
+ p.outro(callFailures.length > 0 ? `done with ${callFailures.length} failed call(s)` : "done");
9256
9333
  } catch (error) {
9257
9334
  const message = error instanceof Error ? error.message : "Extraction benchmark failed";
9258
9335
  if (opts.json) emitJsonError("extraction_benchmark_failed", message);
@@ -9342,6 +9419,27 @@ function createMemoryCommand() {
9342
9419
  function createMemoryDiagnosticsCommand() {
9343
9420
  return new Command("memory").configureHelp(helpStyle).description("Inspect memory quality and session links").addCommand(createMemoryRoleReportCommand().name("roles")).addCommand(createMemoryRoleCompareCommand().name("compare")).addCommand(createMemoryArtifactReportCommand().name("artifacts")).addCommand(createMemoryRelinkReportCommand().name("relink")).addCommand(createMemoryRelinkPlanCommand());
9344
9421
  }
9422
+ /** Text-mode lines for batches whose output or observer call failed. */
9423
+ function logBenchmarkFailures(outputFailures, callFailures) {
9424
+ for (const failure of outputFailures.toSorted((left, right) => left.iteration - right.iteration || left.batchId - right.batchId)) {
9425
+ const costLabel = failure.cost.total == null ? "n/a" : `$${failure.cost.total.totalCostUsd.toFixed(6)}`;
9426
+ const latencyLabel = failure.telemetry.totalElapsedMs == null ? "n/a" : `${failure.telemetry.totalElapsedMs}ms`;
9427
+ p.log.error(` [${failure.batchId}#${failure.iteration}] output_failure tier=${failure.tier ?? "n/a"} expected=${failure.expectedTier ?? "n/a"} mode=${failure.requestedOutputMode}/${failure.actualOutputMode} model=${failure.model ?? "unresolved"} cost=${costLabel} latency=${latencyLabel} — ${failure.reason}`);
9428
+ }
9429
+ for (const failure of callFailures) p.log.error(` [${failure.batchId}#${failure.iteration}] call_failure ${failure.error} — ${failure.message}`);
9430
+ }
9431
+ var MAX_CALL_FAILURE_MESSAGE_CHARS = 500;
9432
+ function benchmarkCallFailure(error, iteration, batch) {
9433
+ const message = error instanceof Error ? error.message : String(error);
9434
+ return {
9435
+ iteration,
9436
+ batchId: batch.batchId,
9437
+ purpose: batch.purpose,
9438
+ status: "call_failure",
9439
+ error: error instanceof Error ? error.name : "Error",
9440
+ message: message.slice(0, MAX_CALL_FAILURE_MESSAGE_CHARS)
9441
+ };
9442
+ }
9345
9443
  function createExtractionDiagnosticsCommand() {
9346
9444
  return new Command("extraction").configureHelp(helpStyle).description("Evaluate memory extraction").addCommand(createMemoryExtractionReportCommand().name("report")).addCommand(createMemoryExtractionReplayCommand().name("replay")).addCommand(createMemoryExtractionBenchmarkCommand().name("benchmark"));
9347
9445
  }
@@ -9556,20 +9654,47 @@ function createVectorMigrationRunner(dbPath, signal) {
9556
9654
  tickBudgetMs: 5e3
9557
9655
  });
9558
9656
  }
9559
- function startMaintenanceWorkerRuntime(options = {}) {
9560
- const logger = options.logger ?? defaultLogger;
9561
- const dbPath = resolveDbPath(options.dbPath ?? void 0);
9562
- const store = new MemoryStore(dbPath);
9563
- const syncConfig = readWorkerSyncConfig(options.configPath);
9564
- const runners = [];
9565
- const walCheckpointTimer = setInterval(() => {
9657
+ function startWalCheckpointTimer(store, logger) {
9658
+ const timer = setInterval(() => {
9566
9659
  try {
9567
9660
  checkpointWalWithoutBlocking(store.db, logger);
9568
9661
  } catch (error) {
9569
9662
  logger.warn(`WAL checkpoint failed: ${error instanceof Error ? error.message : String(error)}`);
9570
9663
  }
9571
9664
  }, 3e5);
9572
- walCheckpointTimer.unref();
9665
+ timer.unref();
9666
+ return timer;
9667
+ }
9668
+ function createRetentionRunners(dbPath, syncConfig, logger, signal) {
9669
+ const runners = [];
9670
+ if (syncConfig.syncRetentionEnabled) runners.push(new SyncRetentionRunner({
9671
+ dbPath,
9672
+ signal
9673
+ }));
9674
+ runners.push(new LedgerRetentionRunner({
9675
+ dbPath,
9676
+ signal,
9677
+ logger
9678
+ }));
9679
+ runners.push(new SyncAttemptRetentionRunner({
9680
+ dbPath,
9681
+ signal,
9682
+ logger
9683
+ }));
9684
+ runners.push(new ReplicationBackfillRunner({
9685
+ dbPath,
9686
+ signal,
9687
+ logger
9688
+ }));
9689
+ return runners;
9690
+ }
9691
+ function startMaintenanceWorkerRuntime(options = {}) {
9692
+ const logger = options.logger ?? defaultLogger;
9693
+ const dbPath = resolveDbPath(options.dbPath ?? void 0);
9694
+ const store = new MemoryStore(dbPath);
9695
+ const syncConfig = readWorkerSyncConfig(options.configPath);
9696
+ const runners = [];
9697
+ const walCheckpointTimer = startWalCheckpointTimer(store, logger);
9573
9698
  if (!isEmbeddingDisabled()) runners.push(createVectorMigrationRunner(dbPath, options.signal));
9574
9699
  runners.push(createSequentialBackfillCoordinator(store, [
9575
9700
  {
@@ -9622,10 +9747,7 @@ function startMaintenanceWorkerRuntime(options = {}) {
9622
9747
  signal: options.signal,
9623
9748
  logger
9624
9749
  }));
9625
- if (syncConfig.syncRetentionEnabled) runners.push(new SyncRetentionRunner({
9626
- dbPath,
9627
- signal: options.signal
9628
- }));
9750
+ runners.push(...createRetentionRunners(dbPath, syncConfig, logger, options.signal));
9629
9751
  for (const runner of runners) runner.start();
9630
9752
  logger.step("Maintenance worker started");
9631
9753
  return {
@@ -9689,6 +9811,96 @@ function createEmbeddingsCommand(name = "embeddings") {
9689
9811
  }
9690
9812
  createEmbeddingsCommand("embed");
9691
9813
  //#endregion
9814
+ //#region src/commands/prune-retrieval-ledger.ts
9815
+ function createDatabasePruneRetrievalLedgerCommand() {
9816
+ const cmd = new Command("prune-retrieval-ledger").configureHelp(helpStyle).description(`Delete retrieval history and outcome evidence past their retention date, and candidates an attempt did not select after ${NON_SELECTED_EXPOSURE_RETENTION_DAYS} days (pinned rows are kept)`).option("--dry-run", "show what is past retention without deleting").option("--batch-size <n>", "retrieval attempts deleted per transaction", String(DEFAULT_LEDGER_RETENTION_BATCH_SIZE));
9817
+ addDbOption(cmd);
9818
+ addJsonOption(cmd);
9819
+ return cmd.action(runPruneRetrievalLedger);
9820
+ }
9821
+ function parseBatchSize(raw) {
9822
+ const value = raw.trim();
9823
+ if (!/^\d+$/.test(value)) return null;
9824
+ const parsed = Number.parseInt(value, 10);
9825
+ return parsed >= 1 && parsed <= 1e4 ? parsed : null;
9826
+ }
9827
+ function describeStats(stats) {
9828
+ return [
9829
+ `Retrieval attempts: ${stats.retrieval_attempts.toLocaleString()} (${stats.expired_retrieval_attempts.toLocaleString()} past retention, removed with their candidates)`,
9830
+ `Retrieval exposures: ${stats.retrieval_exposures.toLocaleString()}`,
9831
+ ` Not selected: ${stats.non_selected_retrieval_exposures.toLocaleString()} (${stats.stale_non_selected_retrieval_exposures.toLocaleString()} older than ${NON_SELECTED_EXPOSURE_RETENTION_DAYS} days)`,
9832
+ `Outcome evidence: ${stats.outcome_evidence.toLocaleString()} (${stats.expired_outcome_evidence.toLocaleString()} past retention)`
9833
+ ].join("\n");
9834
+ }
9835
+ async function pruneUntilDone(db, batchSize) {
9836
+ const now = (/* @__PURE__ */ new Date()).toISOString();
9837
+ const totals = {
9838
+ retrieval_attempts: 0,
9839
+ non_selected_retrieval_exposures: 0,
9840
+ outcome_evidence: 0,
9841
+ batches: 0
9842
+ };
9843
+ for (;;) {
9844
+ const pass = await runLedgerRetentionPass(db, {
9845
+ now,
9846
+ batchSize
9847
+ });
9848
+ totals.retrieval_attempts += pass.retrievalAttemptsPurged;
9849
+ totals.non_selected_retrieval_exposures += pass.nonSelectedExposuresPurged;
9850
+ totals.outcome_evidence += pass.outcomeEvidencePurged;
9851
+ totals.batches += pass.batches;
9852
+ const progressed = pass.retrievalAttemptsPurged + pass.nonSelectedExposuresPurged + pass.outcomeEvidencePurged > 0;
9853
+ if (pass.complete || !progressed) return totals;
9854
+ }
9855
+ }
9856
+ function reportFailure$1(opts, code, message, exitCode) {
9857
+ if (opts.json) {
9858
+ emitJsonError(code, message, exitCode);
9859
+ return;
9860
+ }
9861
+ p.log.error(message);
9862
+ process.exitCode = exitCode;
9863
+ }
9864
+ function reportHuman(purged) {
9865
+ if (!purged) {
9866
+ p.outro("Dry run only; no changes made");
9867
+ return;
9868
+ }
9869
+ p.log.success(`Deleted ${purged.retrieval_attempts.toLocaleString()} retrieval attempts with their exposures, ${purged.non_selected_retrieval_exposures.toLocaleString()} candidates that older attempts did not select, and ${purged.outcome_evidence.toLocaleString()} outcome evidence rows`);
9870
+ p.outro("Done. The database file keeps its size until `maintenance database vacuum`.");
9871
+ }
9872
+ async function runPruneRetrievalLedger(opts) {
9873
+ const batchSize = parseBatchSize(opts.batchSize);
9874
+ if (batchSize === null) {
9875
+ reportFailure$1(opts, "invalid_batch_size", `--batch-size must be an integer from 1 to 10000 (got "${opts.batchSize}")`, 2);
9876
+ return;
9877
+ }
9878
+ let db = null;
9879
+ try {
9880
+ db = connect(resolveDbPath(resolveDbOpt(opts)));
9881
+ const before = retrievalLedgerStats(db);
9882
+ if (!opts.json) {
9883
+ p.intro("codemem maintenance database prune-retrieval-ledger");
9884
+ p.log.info(describeStats(before));
9885
+ }
9886
+ const purged = opts.dryRun ? null : await pruneUntilDone(db, batchSize);
9887
+ const after = purged ? retrievalLedgerStats(db) : before;
9888
+ if (opts.json) {
9889
+ const dryRun = Boolean(opts.dryRun);
9890
+ console.log(JSON.stringify({
9891
+ dry_run: dryRun,
9892
+ before,
9893
+ purged,
9894
+ after
9895
+ }, null, 2));
9896
+ } else reportHuman(purged);
9897
+ } catch (error) {
9898
+ reportFailure$1(opts, "prune_retrieval_ledger_failed", error instanceof Error ? error.message : String(error), 1);
9899
+ } finally {
9900
+ db?.close();
9901
+ }
9902
+ }
9903
+ //#endregion
9692
9904
  //#region src/commands/maintenance.ts
9693
9905
  var maintenanceCmd = new Command("maintenance").configureHelp(helpStyle).description("Inspect jobs and repair stored data");
9694
9906
  var statusCmd = new Command("status").configureHelp(helpStyle).description("Show maintenance job status");
@@ -9754,7 +9966,7 @@ workerCmd.action(async (opts) => {
9754
9966
  maintenanceCmd.addCommand(statusCmd);
9755
9967
  maintenanceCmd.addCommand(workerCmd, { hidden: true });
9756
9968
  maintenanceCmd.addCommand(createEmbeddingsCommand());
9757
- maintenanceCmd.addCommand(new Command("database").configureHelp(helpStyle).description("Inspect and clean up database storage").addCommand(createDatabaseInitCommand()).addCommand(createDatabaseVacuumCommand()).addCommand(createDatabaseStatsCommand()).addCommand(createDatabasePruneEventsCommand()).addCommand(createDatabasePruneHistoryCommand()));
9969
+ maintenanceCmd.addCommand(new Command("database").configureHelp(helpStyle).description("Inspect and clean up database storage").addCommand(createDatabaseInitCommand()).addCommand(createDatabaseVacuumCommand()).addCommand(createDatabaseStatsCommand()).addCommand(createDatabasePruneEventsCommand()).addCommand(createDatabasePruneHistoryCommand()).addCommand(createDatabasePruneRetrievalLedgerCommand()));
9758
9970
  maintenanceCmd.addCommand(new Command("memory").configureHelp(helpStyle).description("Deactivate low-quality memories or redact secrets").addCommand(createMemoryPruneCommand()).addCommand(createMemoryDeduplicateCommand()).addCommand(createMemoryRedactSecretsCommand()));
9759
9971
  maintenanceCmd.addCommand(new Command("project").configureHelp(helpStyle).description("Repair project names in stored history").addCommand(createProjectRenameCommand()).addCommand(createProjectNormalizeCommand()));
9760
9972
  maintenanceCmd.addCommand(new Command("backfill").configureHelp(helpStyle).description("Repair missing fields in historical memories").addCommand(createBackfillTagsCommand()).addCommand(createBackfillDedupKeysCommand()).addCommand(createBackfillNarrativeCommand()).addCommand(createBackfillStructuredCommand()));
@@ -10377,7 +10589,7 @@ async function ingestPiWithoutBacklog(runtime, boundaryRequested) {
10377
10589
  }
10378
10590
  /** Ingest one Pi event through the Viewer queue or local spool. */
10379
10591
  async function ingestPiHookPayload(payload, opts, deps = {}) {
10380
- const { [BOUNDARY_CEILING_FIELD]: _ignoredCeiling, ...livePayload } = payload;
10592
+ const { [BOUNDARY_CEILING_FIELD]: _ignoredCeiling, ...livePayload } = sanitizeHookPayload(payload);
10381
10593
  const stablePayload = stabilizePiBoundaryPayload(livePayload);
10382
10594
  const runtime = createPiIngestRuntime(stablePayload, opts, deps);
10383
10595
  const boundaryRequested = shouldForcePiBoundaryFlush(stablePayload);
@@ -10886,6 +11098,14 @@ function forwardChildStderr(source, options) {
10886
11098
  }
10887
11099
  //#endregion
10888
11100
  //#region src/observer-runtime-controller.ts
11101
+ function appliedReasoning(status) {
11102
+ if (status?.reasoningEffortRequestSucceeded == null) return void 0;
11103
+ return {
11104
+ effort: status.actualReasoningEffort ?? null,
11105
+ requestSucceeded: status.reasoningEffortRequestSucceeded,
11106
+ fallbackReason: status.reasoningEffortFallbackReason ?? null
11107
+ };
11108
+ }
10889
11109
  /** Keep the live observer and saved config separate until in-flight work has drained. */
10890
11110
  var ObserverRuntimeController = class {
10891
11111
  sweeper;
@@ -10913,11 +11133,13 @@ var ObserverRuntimeController = class {
10913
11133
  observer: {},
10914
11134
  reasons: []
10915
11135
  }).observer : config;
11136
+ const applied = appliedReasoning(config.observerTierRoutingEnabled ? active.tierReasoningEfforts?.[tier] : active);
10916
11137
  return {
10917
11138
  provider: selected.observerProvider ?? active.provider,
10918
11139
  model: selected.observerModel ?? active.model,
10919
11140
  runtime: selected.observerRuntime ?? active.runtime,
10920
- reasoningEffort: selected.observerReasoningEffort ?? null
11141
+ reasoningEffort: selected.observerReasoningEffort ?? null,
11142
+ ...applied ? { appliedReasoning: applied } : {}
10921
11143
  };
10922
11144
  };
10923
11145
  return {
@@ -11127,6 +11349,143 @@ function resolveStopRestartInvocation(mode, opts) {
11127
11349
  background: mode === "restart"
11128
11350
  };
11129
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
+ }
11130
11489
  //#endregion
11131
11490
  //#region src/commands/serve.ts
11132
11491
  function extractViewerPid(payload) {
@@ -11197,13 +11556,12 @@ function isTrustedViewerPid(pid, target, listenerPid) {
11197
11556
  return isLikelyViewerCommand(command);
11198
11557
  }
11199
11558
  function pidFilePath(dbPath) {
11200
- return join(dirname(dbPath), "viewer.pid");
11559
+ return join(viewerRuntimeDir(dbPath), "viewer.pid");
11201
11560
  }
11202
11561
  function maintenanceWorkerPidFilePath(dbPath) {
11203
- return join(dirname(dbPath), "maintenance-worker.pid");
11562
+ return join(viewerRuntimeDir(dbPath), "maintenance-worker.pid");
11204
11563
  }
11205
- function readMaintenanceWorkerPidRecord(dbPath) {
11206
- const pidPath = maintenanceWorkerPidFilePath(dbPath);
11564
+ function readMaintenanceWorkerPidRecordAt(pidPath) {
11207
11565
  if (!existsSync(pidPath)) return null;
11208
11566
  const raw = readFileSync(pidPath, "utf-8").trim();
11209
11567
  try {
@@ -11237,8 +11595,20 @@ function commandHasExactDbPath(command, dbPath) {
11237
11595
  const escapedPath = escapeRegExp(resolveDbPath(dbPath));
11238
11596
  return new RegExp(`(?:^|\\s)--db-path(?:=|\\s+)${escapedPath}(?:\\s|$)`).test(command);
11239
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
+ }
11240
11608
  function readViewerPidRecord(dbPath) {
11241
- const pidPath = pidFilePath(dbPath);
11609
+ return readViewerPidRecordAt(pidFilePath(dbPath));
11610
+ }
11611
+ function readViewerPidRecordAt(pidPath) {
11242
11612
  if (!existsSync(pidPath)) return null;
11243
11613
  const parsed = parseViewerPidRecord(readFileSync(pidPath, "utf-8"));
11244
11614
  if (parsed.state === "valid") return parsed.record;
@@ -11260,13 +11630,14 @@ function normalizeViewerHost(host) {
11260
11630
  if (normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1" || normalized === "[::1]") return "loopback";
11261
11631
  return normalized;
11262
11632
  }
11633
+ /** A live Viewer for this database at another address, from either PID record location. */
11263
11634
  async function findRuntimeViewerConflict(dbPath, target) {
11264
- const record = readViewerPidRecord(dbPath);
11265
- if (!record) return null;
11266
- if (normalizeViewerHost(record.host) === normalizeViewerHost(target.host) && record.port === target.port) return null;
11267
- if (!isProcessRunning(record.pid)) return null;
11268
- if (!await respondsLikeCodememViewer(record)) return null;
11269
- return record;
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;
11270
11641
  }
11271
11642
  function isProcessRunning(pid) {
11272
11643
  try {
@@ -11336,25 +11707,32 @@ async function terminateProcessPid(pid, timeouts = {}) {
11336
11707
  async function terminateTrustedViewerPid(pid, timeouts = {}) {
11337
11708
  return terminateProcessPid(pid, timeouts);
11338
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
+ */
11339
11716
  async function terminateTrustedMaintenanceWorker(dbPath, timeouts = {}) {
11340
- const pidPath = maintenanceWorkerPidFilePath(dbPath);
11341
- const record = readMaintenanceWorkerPidRecord(dbPath);
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);
11342
11724
  if (!record) return true;
11343
- const expectedDbPath = resolveDbPath(dbPath);
11344
- if (record.dbPath && record.dbPath !== expectedDbPath) return false;
11725
+ const isThisDb = (path) => path !== null && canonicalViewerDbPath(path) === canonicalViewerDbPath(dbPath);
11726
+ if (record.dbPath && !isThisDb(record.dbPath)) return false;
11345
11727
  if (!isProcessRunning(record.pid)) {
11346
- try {
11347
- rmSync(pidPath);
11348
- } catch {}
11728
+ removeFile(pidPath);
11349
11729
  return true;
11350
11730
  }
11351
11731
  const command = readProcessCommand(record.pid);
11352
11732
  if (!command || !isLikelyMaintenanceWorkerCommand(command)) return false;
11353
- if (record.dbPath !== expectedDbPath || !commandHasExactDbPath(command, expectedDbPath)) return false;
11733
+ if (!isThisDb(record.dbPath) || !commandHasExactDbPath(command, record.dbPath)) return false;
11354
11734
  const stopped = await terminateProcessPid(record.pid, timeouts);
11355
- if (stopped) try {
11356
- rmSync(pidPath);
11357
- } catch {}
11735
+ if (stopped) removeFile(pidPath);
11358
11736
  return stopped;
11359
11737
  }
11360
11738
  async function waitForPortRelease(host, port, timeoutMs = 1e4) {
@@ -11365,9 +11743,16 @@ async function waitForPortRelease(host, port, timeoutMs = 1e4) {
11365
11743
  }
11366
11744
  return false;
11367
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
+ };
11368
11755
  async function stopExistingViewer(dbPath, target) {
11369
- const pidPath = pidFilePath(dbPath);
11370
- const record = readViewerPidRecord(dbPath);
11371
11756
  const viewerPidFromStats = await lookupViewerPidFromStats(target.host, target.port);
11372
11757
  const listenerPid = lookupListeningPid(target.host, target.port);
11373
11758
  const viewerPid = pickViewerPidCandidate(viewerPidFromStats, listenerPid);
@@ -11376,39 +11761,46 @@ async function stopExistingViewer(dbPath, target) {
11376
11761
  stopped: false,
11377
11762
  pid: viewerPid
11378
11763
  };
11379
- try {
11380
- rmSync(pidPath);
11381
- } catch {}
11764
+ removeStoppedViewerPidRecords(dbPath, viewerPid);
11382
11765
  return {
11383
11766
  stopped: true,
11384
11767
  pid: viewerPid
11385
11768
  };
11386
11769
  }
11387
- if (!record) return {
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 {
11388
11777
  stopped: false,
11389
11778
  pid: null
11390
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) {
11391
11783
  const recordListenerPid = lookupListeningPid(record.host, record.port);
11392
- if (await respondsLikeCodememViewer(record) && isTrustedViewerPid(record.pid, {
11784
+ if (!await respondsLikeCodememViewer(record) || !isTrustedViewerPid(record.pid, {
11393
11785
  host: record.host,
11394
11786
  port: record.port
11395
- }, recordListenerPid)) {
11396
- if (!await terminateTrustedViewerPid(record.pid)) return {
11397
- stopped: false,
11398
- pid: record.pid
11399
- };
11400
- } else return {
11401
- stopped: false,
11402
- pid: null
11403
- };
11404
- try {
11405
- rmSync(pidPath);
11406
- } catch {}
11787
+ }, recordListenerPid)) return null;
11407
11788
  return {
11408
- stopped: true,
11789
+ stopped: await terminateTrustedViewerPid(record.pid),
11409
11790
  pid: record.pid
11410
11791
  };
11411
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
+ }
11412
11804
  function buildForegroundRunnerArgs(scriptPath, invocation, execArgv = process.execArgv) {
11413
11805
  const args = [
11414
11806
  ...execArgv,
@@ -11534,13 +11926,22 @@ async function nativeRuntimeAllowsServeStart(invocation) {
11534
11926
  if (invocation.mode !== "start" && invocation.mode !== "restart") return true;
11535
11927
  const preflight = await preflightServeNativeRuntime(invocation);
11536
11928
  if (preflight.state === "already_running") {
11537
- p.log.warn(`Viewer already running at http://${invocation.host}:${invocation.port}`);
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
+ });
11538
11935
  if (!invocation.background) process.exitCode = 1;
11539
11936
  return false;
11540
11937
  }
11541
11938
  if (preflight.state === "ready") return true;
11542
11939
  p.intro("codemem viewer");
11543
11940
  for (const line of preflight.diagnostics) p.log.error(line);
11941
+ reportViewerStartup({
11942
+ state: "failed",
11943
+ message: preflight.diagnostics.join(" ")
11944
+ });
11544
11945
  process.exitCode = 1;
11545
11946
  return false;
11546
11947
  }
@@ -11599,22 +12000,37 @@ async function startBackgroundViewer(invocation) {
11599
12000
  const child = spawn(process.execPath, buildForegroundRunnerArgs(scriptPath, invocation), {
11600
12001
  cwd: process.cwd(),
11601
12002
  detached: true,
11602
- stdio: "ignore",
12003
+ stdio: [
12004
+ "ignore",
12005
+ "ignore",
12006
+ "ignore",
12007
+ "ipc"
12008
+ ],
11603
12009
  env: {
11604
12010
  ...process.env,
11605
12011
  ...invocation.dbPath ? { CODEMEM_DB: invocation.dbPath } : {},
11606
- ...invocation.configPath ? { CODEMEM_CONFIG: invocation.configPath } : {}
12012
+ ...invocation.configPath ? { CODEMEM_CONFIG: invocation.configPath } : {},
12013
+ [VIEWER_STARTUP_REPORT_ENV]: "1"
11607
12014
  }
11608
12015
  });
12016
+ const startup = await waitForViewerStartup(child, BACKGROUND_STARTUP_WAIT_MS);
11609
12017
  child.unref();
11610
- if (invocation.dbPath) writeFileSync(pidFilePath(invocation.dbPath), JSON.stringify({
11611
- pid: child.pid,
11612
- host: invocation.host,
11613
- port: invocation.port
11614
- }), "utf-8");
11615
12018
  p.intro("codemem viewer");
11616
- p.outro(`Viewer started in background (pid ${child.pid}) at http://${invocation.host}:${invocation.port}`);
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}`);
11617
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;
11618
12034
  function startRawEventProcessing(dbPath, store, observer, createInbox) {
11619
12035
  const sweeper = new RawEventSweeper(store, { observer });
11620
12036
  const observerRuntime = new ObserverRuntimeController(observer, sweeper, () => new ObserverClient());
@@ -11839,6 +12255,8 @@ async function callMemoryToolForHost(store, name, args, caller) {
11839
12255
  const { callCodememToolLocally } = await import("@codemem/mcp");
11840
12256
  return callCodememToolLocally(store, name, args, caller);
11841
12257
  }
12258
+ /** How often the running service checks Team setup completions with the coordinator. */
12259
+ var TEAM_SETUP_RECONCILIATION_INTERVAL_MS = 3e5;
11842
12260
  function foregroundAppOptions(store, rawEventOptions, options) {
11843
12261
  return {
11844
12262
  accountLink: options.accountLink.options,
@@ -11846,7 +12264,8 @@ function foregroundAppOptions(store, rawEventOptions, options) {
11846
12264
  syncReachability: options.relay?.reachability,
11847
12265
  ...rawEventOptions,
11848
12266
  ...options.coordinatorRefresh,
11849
- getSyncRuntimeStatus: () => options.syncRuntimeStatus
12267
+ getSyncRuntimeStatus: () => options.syncRuntimeStatus,
12268
+ teamSetupReconciliationIntervalMs: TEAM_SETUP_RECONCILIATION_INTERVAL_MS
11850
12269
  };
11851
12270
  }
11852
12271
  function createBoundApp(createApp, options, listener) {
@@ -11867,6 +12286,34 @@ function createBoundApp(createApp, options, listener) {
11867
12286
  }
11868
12287
  };
11869
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
+ }
11870
12317
  async function startForegroundViewer(invocation) {
11871
12318
  const serverModule = await import("@codemem/server");
11872
12319
  const { createApp, createSyncApp, closeStoreAsync, createViewerRawEventInbox, getStore } = serverModule;
@@ -11877,10 +12324,7 @@ async function startForegroundViewer(invocation) {
11877
12324
  if (invocation.configPath) process.env.CODEMEM_CONFIG = invocation.configPath;
11878
12325
  warnIfViewerExposed(invocation.host, invocation.port);
11879
12326
  const dbPath = resolveDbPath(invocation.dbPath ?? void 0);
11880
- if (!await terminateTrustedMaintenanceWorker(dbPath, {
11881
- gracefulMs: 1e3,
11882
- forceMs: 5e3
11883
- })) p.log.warn("Existing maintenance worker is not trusted or did not stop; starting viewer anyway");
12327
+ if (!await takeOverViewerRuntime(dbPath, invocation)) return;
11884
12328
  const preparedDb = prepareViewerDatabase(invocation.dbPath);
11885
12329
  const observer = new ObserverClient();
11886
12330
  let store;
@@ -11956,6 +12400,7 @@ async function startForegroundViewer(invocation) {
11956
12400
  preparedDb,
11957
12401
  info
11958
12402
  });
12403
+ reportViewerStartup({ state: "listening" });
11959
12404
  maintenanceWorker = startMaintenanceWorkerProcess(invocation);
11960
12405
  if (syncEnabled) scheduleServeSyncDaemon({
11961
12406
  invocation,
@@ -11969,8 +12414,7 @@ async function startForegroundViewer(invocation) {
11969
12414
  });
11970
12415
  });
11971
12416
  server.on("error", (err) => {
11972
- if (err.code === "EADDRINUSE") p.log.warn(`Viewer already running at http://${invocation.host}:${invocation.port}`);
11973
- else p.log.error(err.message);
12417
+ reportViewerListenError(err, invocation);
11974
12418
  requestShutdown(1);
11975
12419
  });
11976
12420
  let shutdownPromise;
@@ -12003,6 +12447,7 @@ async function startForegroundViewer(invocation) {
12003
12447
  shutdownExitCode = 1;
12004
12448
  logViewerShutdownError(error);
12005
12449
  }
12450
+ heldViewerWriterLock?.release();
12006
12451
  }
12007
12452
  process.exit(shutdownExitCode);
12008
12453
  };
@@ -12015,6 +12460,22 @@ async function startForegroundViewer(invocation) {
12015
12460
  process.on("SIGINT", () => requestShutdown());
12016
12461
  process.on("SIGTERM", () => requestShutdown());
12017
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
+ }
12018
12479
  function logViewerShutdownError(error) {
12019
12480
  p.log.error(error instanceof Error ? error.message : String(error));
12020
12481
  }
@@ -12049,60 +12510,86 @@ async function runServeInvocation(invocation, dependencies = {
12049
12510
  port: invocation.port
12050
12511
  });
12051
12512
  if (runtimeConflict) {
12513
+ const message = `Database runtime at ${viewerRuntimeDir(dbPath)} is already managed by viewer ${runtimeConflict.host}:${runtimeConflict.port} (pid ${runtimeConflict.pid})`;
12052
12514
  p.intro("codemem viewer");
12053
- p.log.error(`Database runtime at ${dirname(dbPath)} is already managed by viewer ${runtimeConflict.host}:${runtimeConflict.port} (pid ${runtimeConflict.pid})`);
12515
+ p.log.error(message);
12054
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
+ });
12055
12521
  process.exitCode = 1;
12056
12522
  return;
12057
12523
  }
12058
12524
  if (!await dependencies.nativeRuntimeAllowsServeStart(invocation)) return;
12059
- if (invocation.mode === "stop" || invocation.mode === "restart") {
12060
- const result = await dependencies.stopExistingViewer(dbPath, {
12061
- host: invocation.host,
12062
- port: invocation.port
12063
- });
12064
- if (result.stopped) {
12065
- const workerStopped = await terminateTrustedMaintenanceWorker(dbPath, {
12066
- gracefulMs: 5e3,
12067
- forceMs: 5e3
12068
- });
12069
- p.intro("codemem viewer");
12070
- p.log.success(`Stopped viewer${result.pid ? ` (pid ${result.pid})` : ""}`);
12071
- if (!workerStopped) p.log.warn("Maintenance worker pidfile exists but did not match trusted worker command");
12072
- if (invocation.mode === "stop") {
12073
- p.outro("done");
12074
- return;
12075
- }
12076
- if (!await waitForPortRelease(invocation.host, invocation.port)) p.log.warn(`Port ${invocation.port} still in use after stop — restart may fail`);
12077
- } else if (result.pid) {
12078
- p.intro("codemem viewer");
12079
- p.log.error(`Viewer is still shutting down (pid ${result.pid})`);
12080
- process.exitCode = 1;
12081
- return;
12082
- } else if (invocation.mode === "stop") {
12083
- const workerStopped = await terminateTrustedMaintenanceWorker(dbPath, {
12084
- gracefulMs: 5e3,
12085
- forceMs: 5e3
12086
- });
12087
- p.intro("codemem viewer");
12088
- if (!workerStopped) p.log.warn("Maintenance worker pidfile exists but did not match trusted worker command");
12089
- p.outro("No background viewer found");
12090
- return;
12091
- }
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;
12092
12552
  }
12093
- if (invocation.mode === "start" || invocation.mode === "restart") {
12094
- if (invocation.background) {
12095
- await startBackgroundViewer({
12096
- ...invocation,
12097
- dbPath
12098
- });
12099
- return;
12100
- }
12101
- await startForegroundViewer({
12102
- ...invocation,
12103
- dbPath
12104
- });
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;
12105
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);
12106
12593
  }
12107
12594
  var serveCmd = new Command("serve").configureHelp(helpStyle).description("Run the local service (compatibility entrypoint; see service)").argument("[action]", "lifecycle action (start|stop|restart)");
12108
12595
  addDbOption(serveCmd);
@@ -12128,7 +12615,12 @@ var serveCommand = serveCmd.action(async (action, opts) => {
12128
12615
  }
12129
12616
  await runServeInvocation(resolveServeInvocation(normalizedAction, opts));
12130
12617
  } catch (err) {
12131
- p.log.error(err instanceof Error ? err.message : String(err));
12618
+ const message = err instanceof Error ? err.message : String(err);
12619
+ p.log.error(message);
12620
+ reportViewerStartup({
12621
+ state: "failed",
12622
+ message
12623
+ });
12132
12624
  process.exitCode = 1;
12133
12625
  }
12134
12626
  });
@@ -12226,22 +12718,59 @@ function boundAttention(items) {
12226
12718
  message: item.message.slice(0, 500)
12227
12719
  }));
12228
12720
  }
12229
- function projectSync(enabled, snapshot, attention) {
12230
- if (!enabled) return "disabled";
12231
- if (!snapshot) return "unknown";
12232
- if (snapshot.sync.daemon_error || snapshot.sync.needs_attention) {
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);
12233
12751
  attention.push({
12234
- code: "sync_daemon_error",
12235
- severity: "error",
12236
- message: "Sync requires attention; run `codemem sync doctor`"
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\``
12237
12755
  });
12238
- return "error";
12756
+ return "degraded";
12239
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);
12240
12769
  if (snapshot.sync.peer_errors > 0) {
12241
12770
  attention.push({
12242
12771
  code: "sync_degraded",
12243
12772
  severity: "warning",
12244
- message: "Sync has recent peer failures; run `codemem sync peers` or `codemem sync doctor`"
12773
+ message: `${plural(snapshot.sync.peer_errors, "peer", "peers")} failed the last sync attempt; run \`codemem sync peers\` or \`codemem sync doctor\``
12245
12774
  });
12246
12775
  return "degraded";
12247
12776
  }
@@ -12289,7 +12818,7 @@ function addRuntimeAttention(runtime, attention) {
12289
12818
  }[runtime.attention_code]
12290
12819
  });
12291
12820
  }
12292
- function projectDatabaseSubsystems(snapshot, configuredObserver, attention) {
12821
+ function projectDatabaseSubsystems(snapshot, configuredObserver, checkedAt, attention) {
12293
12822
  if (!snapshot) return {
12294
12823
  maintenance: { state: "unknown" },
12295
12824
  semantic_index: { state: "unknown" },
@@ -12355,7 +12884,7 @@ function projectDatabaseSubsystems(snapshot, configuredObserver, attention) {
12355
12884
  attention.push({
12356
12885
  code: "observer_recent_failures",
12357
12886
  severity: "warning",
12358
- message: "Observer batches failed recently. Run `codemem diagnostics capture status`"
12887
+ message: recentObserverFailureMessage(snapshot.observer, checkedAt)
12359
12888
  });
12360
12889
  }
12361
12890
  return {
@@ -12368,6 +12897,12 @@ function projectDatabaseSubsystems(snapshot, configuredObserver, attention) {
12368
12897
  observer: { state: observerState }
12369
12898
  };
12370
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
+ }
12371
12906
  async function collectStatusReport(opts, deps = defaultDependencies) {
12372
12907
  const checkedAt = deps.now();
12373
12908
  const config = deps.readConfig(opts.config);
@@ -12391,16 +12926,15 @@ async function collectStatusReport(opts, deps = defaultDependencies) {
12391
12926
  db.close();
12392
12927
  }
12393
12928
  }
12394
- const pidPath = join(dirname(dbPath), "viewer.pid");
12395
- 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)), {
12396
12930
  fetch: deps.fetch,
12397
12931
  isProcessRunning: deps.isProcessRunning
12398
12932
  }, viewerDefaultTarget(deps.env));
12399
12933
  const attention = [];
12400
12934
  addDatabaseAttention(databaseState, attention);
12401
12935
  addRuntimeAttention(runtime, attention);
12402
- const sync = projectSync(syncEnabled(config, deps.env), snapshot, attention);
12403
- 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);
12404
12938
  const ok = !attention.some((item) => item.severity === "error");
12405
12939
  const boundedAttention = boundAttention(attention);
12406
12940
  return {
@@ -14633,7 +15167,8 @@ async function portOpen(host, port) {
14633
15167
  }
14634
15168
  function readViewerBinding(dbPath) {
14635
15169
  try {
14636
- const raw = readFileSync(join(dirname(dbPath), "viewer.pid"), "utf8");
15170
+ const raw = readViewerPidFile(dbPath);
15171
+ if (raw === null) return null;
14637
15172
  const parsed = JSON.parse(raw);
14638
15173
  if (typeof parsed.host === "string" && typeof parsed.port === "number") return {
14639
15174
  host: parsed.host,