codemem 0.47.5 → 0.48.0

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, AUTH_LINK_AUTHORITY_CUTOVER_SQL, ContextOnlyReplayError, CoordinatorAccountLinkError, DEDUP_KEY_BACKFILL_JOB, DEFAULT_COORDINATOR_DB_PATH, 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, coordinatorCreateGroupAction, coordinatorCreateInviteAction, coordinatorCreateScopeAction, coordinatorDisableDeviceAction, coordinatorEnrollDeviceAction, coordinatorGrantIdentityGroupAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorQualifyOwnerAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorReviewInviteAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeDeviceAction, coordinatorRevokeScopeMembershipAction, coordinatorUpdateScopeAction, createBetterSqliteCoordinatorApp, createFileContextRunner, deactivateLowSignalMemories, deactivateLowSignalObservations, 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, getSemanticIndexDiagnostics, getSessionExtractionEval, getSessionExtractionEvalScenario, getUpdateStatus, getWorkspaceCodememConfigPath, hasPendingDedupKeyBackfill, hasPendingRefBackfill, hasPendingScopeBackfill, hasPendingSessionContextBackfill, hasPendingSummaryDedupBackfill, hasUnsyncedSharedMemoryChanges, importMemories, importPiSessions, ingestRawEvents, initDatabase, isAutomaticRecallMeasurement, isCoordinatorControllerAttestationReference, isEmbeddingDisabled, isExplicitUpdateInstallEligible, isReleaseVersionForChannel, judgeDistillReport, legacyTeamCandidateId, linkCoordinatorAccount, listMaintenanceJobs, listPerPeerScopeSyncState, listRetentionScopeIds, loadObserverConfig, loadPublicKey, loadRuntimeSigningPublicKey, loadSqliteVec, mdnsEnabled, mutateCodememConfigFile, normalizeCoordinatorAccountLinkOrigin, normalizePromptTransportProtocolRange, observerBaseUrlForProviderOverride, parseControllerHistoryEvidence, parseFileContextTransportRequest, planReplicationOpsAgePrune, probeCodememViewerLiveness, probeCodememViewerLiveness as probeCodememViewerLiveness$1, probeRequiredNativeRuntime, projectMatchesFilter, promptPackArtifactFingerprint, pruneReplicationOpsUntilCaughtUp, rawEventsGate, readAccountLinkDevice, readCodememConfigFile, readCodememConfigFileAtPath, readCoordinatorAccountLinkStatus, readCoordinatorOwnerReviewLocalEvidence, readCoordinatorSyncConfig, readImportPayload, recordAutomaticRecall, recordPromptPackArtifacts, recordPromptPackTerminal, renderUnifiedDiff, replayBatchExtraction, replayBatchExtractionWithTierRouting, requestJson, resolveCodememConfigPath, resolveComparablePath, resolveDbPath, resolveHookProject, resolveKeyPaths, resolvePiAgentDir, resolvePiObserverConfig, resolveProject, resolveProjectRoot, retryRawEventFailures, runSyncDaemon, runSyncPass, scanSecretsRetroactive, schema, scoreExtractionBenchmarkOutput, searchPiSessions, setPeerProjectFilter, syncPassPreflight, tryUpdateRetrievalDelivery, updatePeerAddresses, upgradeCoordinatorAccountSchemaFile, upgradeCoordinatorAuthSchemaFile, upgradeCoordinatorOwnerResolutionSchemaFile, vacuumDatabase, viewerUrl, withDiagnosticStoreSnapshot, writeCodememConfigFile } from "@codemem/core";
2
+ import { ACCOUNT_CONNECTION_MIGRATION_STATEMENTS, ACCOUNT_UNLINK_MIGRATION_STATEMENTS, 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, coordinatorCreateGroupAction, coordinatorCreateInviteAction, coordinatorCreateScopeAction, coordinatorDisableDeviceAction, coordinatorEnrollDeviceAction, coordinatorGrantIdentityGroupAction, coordinatorGrantScopeMembershipAction, coordinatorImportInviteAction, coordinatorListBootstrapGrantsAction, coordinatorListDevicesAction, coordinatorListGroupsAction, coordinatorListJoinRequestsAction, coordinatorListLegacyTeamCompletionsAction, coordinatorListScopeMembershipsAction, coordinatorListScopesAction, coordinatorQualifyOwnerAction, coordinatorRemoveDeviceAction, coordinatorRenameDeviceAction, coordinatorReviewInviteAction, coordinatorReviewJoinRequestAction, coordinatorRevokeBootstrapGrantAction, coordinatorRevokeDeviceAction, coordinatorRevokeScopeMembershipAction, coordinatorUpdateScopeAction, createBetterSqliteCoordinatorApp, createFileContextRunner, deactivateLowSignalMemories, deactivateLowSignalObservations, 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, getSemanticIndexDiagnostics, getSessionExtractionEval, getSessionExtractionEvalScenario, getUpdateStatus, getWorkspaceCodememConfigPath, hasPendingDedupKeyBackfill, hasPendingRefBackfill, hasPendingScopeBackfill, hasPendingSessionContextBackfill, hasPendingSummaryDedupBackfill, hasUnsyncedSharedMemoryChanges, importMemories, importPiSessions, ingestRawEvents, initDatabase, isAutomaticRecallMeasurement, isCoordinatorControllerAttestationReference, isEmbeddingDisabled, isExplicitUpdateInstallEligible, isReleaseVersionForChannel, judgeDistillReport, legacyTeamCandidateId, linkCoordinatorAccount, linkCoordinatorAccountHeadless, listMaintenanceJobs, listPerPeerScopeSyncState, listRetentionScopeIds, loadObserverConfig, loadPublicKey, loadRuntimeSigningPublicKey, loadSqliteVec, mdnsEnabled, mutateCodememConfigFile, normalizeCoordinatorAccountLinkOrigin, normalizePromptTransportProtocolRange, observerBaseUrlForProviderOverride, parseControllerHistoryEvidence, parseFileContextTransportRequest, planReplicationOpsAgePrune, probeCodememViewerLiveness, probeCodememViewerLiveness as probeCodememViewerLiveness$1, probeRequiredNativeRuntime, projectMatchesFilter, promptPackArtifactFingerprint, pruneReplicationOpsUntilCaughtUp, rawEventsGate, readAccountLinkDevice, readCodememConfigFile, readCodememConfigFileAtPath, readCoordinatorAccountLinkStatus, readCoordinatorOwnerReviewLocalEvidence, readCoordinatorSyncConfig, readImportPayload, recordAutomaticRecall, recordPromptPackArtifacts, recordPromptPackTerminal, renderUnifiedDiff, replayBatchExtraction, replayBatchExtractionWithTierRouting, requestJson, resolveCodememConfigPath, resolveComparablePath, resolveDbPath, resolveHookProject, resolveKeyPaths, resolvePiAgentDir, resolvePiObserverConfig, resolveProject, resolveProjectRoot, retryRawEventFailures, runSyncDaemon, runSyncPass, scanSecretsRetroactive, schema, scoreExtractionBenchmarkOutput, searchPiSessions, setPeerProjectFilter, syncPassPreflight, tryUpdateRetrievalDelivery, updatePeerAddresses, upgradeCoordinatorAccountSchemaFile, upgradeCoordinatorAuthSchemaFile, upgradeCoordinatorOwnerResolutionSchemaFile, vacuumDatabase, viewerUrl, withDiagnosticStoreSnapshot, writeCodememConfigFile } from "@codemem/core";
3
3
  import { Command, Option } from "commander";
4
4
  import omelette from "omelette";
5
5
  import { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
@@ -11,9 +11,11 @@ import * as p from "@clack/prompts";
11
11
  import { serve } from "@hono/node-server";
12
12
  import { execFileSync, spawn, spawnSync } from "node:child_process";
13
13
  import net from "node:net";
14
+ import { createInterface } from "node:readline";
14
15
  import { applyEdits, createScanner, findNodeAtLocation, modify, parse, parseTree, printParseErrorCode } from "jsonc-parser";
15
16
  import { desc, eq } from "drizzle-orm";
16
17
  import { drizzle } from "drizzle-orm/better-sqlite3";
18
+ import { approveRelayServiceKey, canonicalRelayServiceKey, listRelayServicePins, readRelayServicePin, relayCoordinatorEndpoint } from "@codemem/core/internal/relay-runtime";
17
19
  import { mkdir, open, readFile, stat, unlink } from "node:fs/promises";
18
20
  //#region src/help-style.ts
19
21
  /**
@@ -1281,9 +1283,8 @@ function directEnqueue(payload, dbPath) {
1281
1283
  /**
1282
1284
  * Best-effort boundary flush: write the payload through to the local
1283
1285
  * store (so the just-fired SessionEnd / Stop event is durable in
1284
- * raw_events) and then run a synchronous flushRawEvents pass so that
1285
- * the latest memories are extracted before the hook process exits and
1286
- * the user closes their terminal.
1286
+ * raw_events) and then extract at most one batch before the hook exits.
1287
+ * Any remaining events stay durable for the Viewer or a later invocation.
1287
1288
  *
1288
1289
  * Any failure here \u2014 observer construction, store I/O, flush errors,
1289
1290
  * or simply running without observer credentials \u2014 is logged to
@@ -1314,7 +1315,7 @@ async function flushBoundaryRawEvents$1(payload, dbPath) {
1314
1315
  cwd: envelope.cwd ?? null,
1315
1316
  project: envelope.project ?? null,
1316
1317
  startedAt: envelope.started_at ?? null,
1317
- maxEvents: null
1318
+ maxEvents: DEFAULT_RAW_EVENT_FLUSH_MAX_EVENTS
1318
1319
  });
1319
1320
  } catch (err) {
1320
1321
  logHookEvent(`codemem claude-hook-ingest boundary flush raw events failed cause=${err instanceof Error ? err.name : "unknown"}`);
@@ -2000,12 +2001,12 @@ function parsePositiveInt$2(value, fallback) {
2000
2001
  const parsed = Number.parseInt(String(value ?? ""), 10);
2001
2002
  return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
2002
2003
  }
2003
- function isRecord$2(value) {
2004
+ function isRecord$3(value) {
2004
2005
  return value != null && typeof value === "object" && !Array.isArray(value);
2005
2006
  }
2006
2007
  function canonicalJson$1(value) {
2007
2008
  if (Array.isArray(value)) return `[${value.map(canonicalJson$1).join(",")}]`;
2008
- if (isRecord$2(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson$1(value[key])}`).join(",")}}`;
2009
+ if (isRecord$3(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson$1(value[key])}`).join(",")}}`;
2009
2010
  return JSON.stringify(value);
2010
2011
  }
2011
2012
  function viewerBaseUrl$1(env) {
@@ -2026,7 +2027,7 @@ async function responseJson$1(response) {
2026
2027
  }
2027
2028
  }
2028
2029
  function errorCode$1(body) {
2029
- return isRecord$2(body) && isRecord$2(body.error) && typeof body.error.code === "string" ? body.error.code : null;
2030
+ return isRecord$3(body) && isRecord$3(body.error) && typeof body.error.code === "string" ? body.error.code : null;
2030
2031
  }
2031
2032
  function classifyHttpFailure(status, body, compatibleProfile) {
2032
2033
  const code = errorCode$1(body);
@@ -2091,8 +2092,8 @@ async function fetchViewerPack$1(query, project, payload, dbPath, deps) {
2091
2092
  ok: false,
2092
2093
  disposition: classifyHttpFailure(profileResponse.status, profile, false)
2093
2094
  };
2094
- const viewerRange = isRecord$2(profile) ? normalizePromptTransportProtocolRange(profile.protocol_version, profile.min_supported_protocol_version) : null;
2095
- if (!isRecord$2(profile) || profile.service !== "codemem-viewer" || !viewerRange || !arePromptTransportProtocolRangesCompatible(PROMPT_TRANSPORT_PROTOCOL_RANGE, viewerRange)) return {
2095
+ const viewerRange = isRecord$3(profile) ? normalizePromptTransportProtocolRange(profile.protocol_version, profile.min_supported_protocol_version) : null;
2096
+ if (!isRecord$3(profile) || profile.service !== "codemem-viewer" || !viewerRange || !arePromptTransportProtocolRangesCompatible(PROMPT_TRANSPORT_PROTOCOL_RANGE, viewerRange)) return {
2096
2097
  ok: false,
2097
2098
  disposition: "fallback"
2098
2099
  };
@@ -2156,7 +2157,7 @@ async function fetchViewerPack$1(query, project, payload, dbPath, deps) {
2156
2157
  ok: false,
2157
2158
  disposition: classifyHttpFailure(packResponse.status, body, true)
2158
2159
  };
2159
- if (!isRecord$2(body) || typeof body.pack_text !== "string" || !isRecord$2(body.metrics) || !Number.isInteger(body.metrics.total_items) || Number(body.metrics.total_items) < 0) return {
2160
+ if (!isRecord$3(body) || typeof body.pack_text !== "string" || !isRecord$3(body.metrics) || !Number.isInteger(body.metrics.total_items) || Number(body.metrics.total_items) < 0) return {
2160
2161
  ok: false,
2161
2162
  disposition: "fallback"
2162
2163
  };
@@ -2917,6 +2918,57 @@ function buildCoordinatorGrantIdentityGroupCommand() {
2917
2918
  return command;
2918
2919
  }
2919
2920
  //#endregion
2921
+ //#region src/commands/coordinator-link-account-headless.ts
2922
+ var output = { output: process.stderr };
2923
+ var STATE_LINES = {
2924
+ pending: "Waiting for the code…",
2925
+ browser_claimed: "Code entered, signing in…",
2926
+ oidc_verified: "Reviewing in browser…"
2927
+ };
2928
+ var MAX_SHOWN_LENGTH = 200;
2929
+ /** Account claims come from Google via the coordinator; never let them drive the terminal. */
2930
+ function printable(value) {
2931
+ return value.replace(/[\p{Cc}\p{Cf}\u2028\u2029]/gu, "?").slice(0, MAX_SHOWN_LENGTH);
2932
+ }
2933
+ function formatExpiry(expiresAtMs) {
2934
+ return new Date(expiresAtMs).toLocaleTimeString(void 0, {
2935
+ hour: "numeric",
2936
+ minute: "2-digit",
2937
+ timeZoneName: "short"
2938
+ });
2939
+ }
2940
+ function showHeadlessCode(code) {
2941
+ p.log.step(`On any computer, open ${code.verificationUri} and enter code: ${code.code}`, output);
2942
+ p.log.message(`This device: ${printable(code.deviceId)} · key ${code.fingerprint}`, output);
2943
+ p.log.message(`The code expires at ${formatExpiry(code.expiresAtMs)}.`, output);
2944
+ }
2945
+ function showHeadlessState(state) {
2946
+ const line = STATE_LINES[state];
2947
+ if (line) p.log.info(line, output);
2948
+ }
2949
+ /** The y/N or typed confirmation on this device; anything but an explicit yes declines. */
2950
+ async function confirmHeadlessApproval(identityId, approval, context) {
2951
+ const question = `Link Identity ${printable(identityId)} to this Google account?`;
2952
+ if (approval.email) {
2953
+ const verified = approval.emailVerified === true ? "verified by Google" : "email not verified by Google";
2954
+ p.log.info(`Approved in the browser by ${printable(approval.email)} (${verified})`, output);
2955
+ return await p.confirm({
2956
+ message: `${question} (y/N)`,
2957
+ initialValue: false,
2958
+ signal: context.signal,
2959
+ ...output
2960
+ }) === true;
2961
+ }
2962
+ const who = approval.displayName ? printable(approval.displayName) : "an account with no email";
2963
+ p.log.warn(`Approved in the browser by ${who}`, output);
2964
+ const answer = await p.text({
2965
+ message: `${question} Type link to confirm.`,
2966
+ signal: context.signal,
2967
+ ...output
2968
+ });
2969
+ return !p.isCancel(answer) && answer.trim() === "link";
2970
+ }
2971
+ //#endregion
2920
2972
  //#region src/commands/coordinator-link-account.ts
2921
2973
  function reportLinkFailure(error, coordinatorOrigin) {
2922
2974
  const message = error instanceof CoordinatorAccountLinkError ? error.message : "Account linking could not finish. Check your existing device setup and coordinator configuration, then try again.";
@@ -2934,11 +2986,18 @@ function showPrivateBrowserLink(privateUrl) {
2934
2986
  p.log.warn("Keep this browser link private. Open it to review account linking, then return to the coordinator tab to finish.", { output: process.stderr });
2935
2987
  p.log.message(privateUrl, { output: process.stderr });
2936
2988
  }
2989
+ function requireHeadlessTerminal() {
2990
+ if (process.stdin.isTTY && process.stderr.isTTY) return true;
2991
+ p.log.error("Headless linking asks for confirmation in this terminal. Run it interactively, for example with `docker exec -it <container> codemem coordinator link-account <group> --headless`.", { output: process.stderr });
2992
+ process.exitCode = 2;
2993
+ return false;
2994
+ }
2937
2995
  function requireInteractive(options) {
2938
2996
  if (options.json) {
2939
2997
  emitJsonError("interactive_flow_only", "Account linking is interactive. Run without --json and keep the browser link private.", 2);
2940
2998
  return false;
2941
2999
  }
3000
+ if (options.headless) return requireHeadlessTerminal();
2942
3001
  if (!process.stderr.isTTY) {
2943
3002
  p.log.error("Account linking requires a terminal. Run this command interactively and keep the browser link private.", { output: process.stderr });
2944
3003
  process.exitCode = 2;
@@ -2998,6 +3057,36 @@ function eligibleStatus(remote, identityId) {
2998
3057
  if (status.identityId !== identityId) throw new CoordinatorAccountLinkError("identity_mismatch");
2999
3058
  return status;
3000
3059
  }
3060
+ /** Starts the desktop or headless flow once the Identity is eligible. */
3061
+ async function startLink(options, context) {
3062
+ const { profile, status } = context;
3063
+ const snapshot = JSON.stringify(profile);
3064
+ const request = {
3065
+ ...profile,
3066
+ groupId: context.group,
3067
+ coordinatorUrl: context.selected.coordinatorUrl,
3068
+ expectedAuthority: status.authority,
3069
+ expectedCoordinatorId: status.coordinatorId,
3070
+ assertCurrentContext: () => profileMatches(options, snapshot),
3071
+ signal: context.signal
3072
+ };
3073
+ if (options.headless) {
3074
+ await linkCoordinatorAccountHeadless({
3075
+ ...request,
3076
+ onCode: showHeadlessCode,
3077
+ onState: showHeadlessState,
3078
+ approve: (approval, prompt) => confirmHeadlessApproval(profile.expectedIdentityId, approval, prompt)
3079
+ });
3080
+ p.log.success("Linked.", { output: process.stderr });
3081
+ return;
3082
+ }
3083
+ const result = await linkCoordinatorAccount({
3084
+ ...request,
3085
+ loopbackHost: context.selected.loopbackHost,
3086
+ onBrowserStart: showPrivateBrowserLink
3087
+ });
3088
+ p.log.success(`Coordinator account linked to coordinator Identity ${result.identityId}. Your local Identity has not changed.`, { output: process.stderr });
3089
+ }
3001
3090
  async function linkAccount(group, options) {
3002
3091
  if (!requireInteractive(options)) return;
3003
3092
  const controller = new AbortController();
@@ -3026,19 +3115,13 @@ async function linkAccount(group, options) {
3026
3115
  p.log.success("This Identity is already linked. No account-link request was started.", { output: process.stderr });
3027
3116
  return;
3028
3117
  }
3029
- const snapshot = JSON.stringify(profile);
3030
- const result = await linkCoordinatorAccount({
3031
- ...profile,
3032
- groupId: group,
3033
- coordinatorUrl,
3034
- expectedAuthority: status.authority,
3035
- expectedCoordinatorId: status.coordinatorId,
3036
- assertCurrentContext: () => profileMatches(options, snapshot),
3037
- loopbackHost: selected.loopbackHost,
3038
- signal: controller.signal,
3039
- onBrowserStart: showPrivateBrowserLink
3118
+ await startLink(options, {
3119
+ group,
3120
+ selected,
3121
+ profile,
3122
+ status,
3123
+ signal: controller.signal
3040
3124
  });
3041
- p.log.success(`Coordinator account linked to coordinator Identity ${result.identityId}. Your local Identity has not changed.`, { output: process.stderr });
3042
3125
  } catch (error) {
3043
3126
  reportLinkFailure(error, coordinatorOrigin);
3044
3127
  process.exitCode = 1;
@@ -3048,7 +3131,7 @@ async function linkAccount(group, options) {
3048
3131
  }
3049
3132
  }
3050
3133
  function buildCoordinatorLinkAccountCommand() {
3051
- const command = new Command("link-account").configureHelp(helpStyle).description("Link a coordinator account to your existing Identity").argument("<group>", "group id").option("-u, --coordinator <url>", "coordinator HTTPS origin (defaults to saved config)").option("-l, --loopback-host <host>", "literal loopback host", "127.0.0.1");
3134
+ const command = new Command("link-account").configureHelp(helpStyle).description("Link a coordinator account to your existing Identity").argument("<group>", "group id").option("-u, --coordinator <url>", "coordinator HTTPS origin (defaults to saved config)").option("-l, --loopback-host <host>", "literal loopback host", "127.0.0.1").addOption(new Option("-H, --headless", "link from a device without a browser: enter a code on another computer").conflicts("loopbackHost"));
3052
3135
  addDbOption(command);
3053
3136
  addConfigOption(command);
3054
3137
  addJsonOption(command);
@@ -5518,6 +5601,51 @@ cmd$3.action((inputFile, opts) => {
5518
5601
  p.outro("done");
5519
5602
  });
5520
5603
  var importMemoriesCommand = cmd$3;
5604
+ function isBusy(error) {
5605
+ const code = error?.code;
5606
+ return typeof code === "string" && (code.startsWith("SQLITE_BUSY") || code.startsWith("SQLITE_LOCKED"));
5607
+ }
5608
+ function runCheckpoint(db, mode) {
5609
+ try {
5610
+ return db.pragma(`wal_checkpoint(${mode})`)[0] ?? null;
5611
+ } catch (error) {
5612
+ if (isBusy(error)) return null;
5613
+ throw error;
5614
+ }
5615
+ }
5616
+ /** TRUNCATE takes the writer lock; with no busy wait it gives up instead of stalling writers. */
5617
+ function truncateWithoutWaiting(db) {
5618
+ const timeout = Number(db.pragma("busy_timeout", { simple: true }));
5619
+ db.pragma("busy_timeout = 0");
5620
+ try {
5621
+ const row = runCheckpoint(db, "TRUNCATE");
5622
+ return row !== null && row.busy === 0;
5623
+ } finally {
5624
+ db.pragma(`busy_timeout = ${timeout}`);
5625
+ }
5626
+ }
5627
+ /**
5628
+ * Keep the WAL from growing without blocking other writers.
5629
+ *
5630
+ * A PASSIVE checkpoint copies frames without taking the writer lock. Only once
5631
+ * it has copied every frame does a TRUNCATE try to reset the file, and it runs
5632
+ * with busy_timeout 0, so a busy database skips the truncate until the next run
5633
+ * instead of holding off writers. The old TRUNCATE-only checkpoint waited up to
5634
+ * busy_timeout and blocked new writers while it waited.
5635
+ */
5636
+ function checkpointWalWithoutBlocking(db, logger, now = () => performance.now()) {
5637
+ const started = now();
5638
+ const passive = runCheckpoint(db, "PASSIVE");
5639
+ const truncated = passive !== null && passive.busy === 0 && passive.checkpointed >= passive.log ? truncateWithoutWaiting(db) : false;
5640
+ const elapsedMs = now() - started;
5641
+ const remainingFrames = passive === null ? null : Math.max(0, passive.log - passive.checkpointed);
5642
+ if (elapsedMs >= 250) logger.step(`WAL checkpoint took ${Math.round(elapsedMs)} ms (${remainingFrames ?? "unknown"} frames left, truncated: ${truncated ? "yes" : "no"})`);
5643
+ return {
5644
+ remainingFrames,
5645
+ truncated,
5646
+ elapsedMs
5647
+ };
5648
+ }
5521
5649
  //#endregion
5522
5650
  //#region src/maintenance-worker-runtime.ts
5523
5651
  var defaultLogger = {
@@ -5636,6 +5764,15 @@ function createSequentialBackfillCoordinator(store, jobPlans, options) {
5636
5764
  }
5637
5765
  };
5638
5766
  }
5767
+ function createVectorMigrationRunner(dbPath, signal) {
5768
+ return new VectorModelMigrationRunner({
5769
+ dbPath,
5770
+ signal,
5771
+ batchSize: 10,
5772
+ idleIntervalMs: 6e4,
5773
+ tickBudgetMs: 5e3
5774
+ });
5775
+ }
5639
5776
  function startMaintenanceWorkerRuntime(options = {}) {
5640
5777
  const logger = options.logger ?? defaultLogger;
5641
5778
  const dbPath = resolveDbPath(options.dbPath ?? void 0);
@@ -5644,18 +5781,13 @@ function startMaintenanceWorkerRuntime(options = {}) {
5644
5781
  const runners = [];
5645
5782
  const walCheckpointTimer = setInterval(() => {
5646
5783
  try {
5647
- store.db.pragma("wal_checkpoint(TRUNCATE)");
5784
+ checkpointWalWithoutBlocking(store.db, logger);
5648
5785
  } catch (error) {
5649
5786
  logger.warn(`WAL checkpoint failed: ${error instanceof Error ? error.message : String(error)}`);
5650
5787
  }
5651
5788
  }, 3e5);
5652
5789
  walCheckpointTimer.unref();
5653
- if (!isEmbeddingDisabled()) runners.push(new VectorModelMigrationRunner({
5654
- dbPath,
5655
- signal: options.signal,
5656
- batchSize: 10,
5657
- idleIntervalMs: 6e4
5658
- }));
5790
+ if (!isEmbeddingDisabled()) runners.push(createVectorMigrationRunner(dbPath, options.signal));
5659
5791
  runners.push(createSequentialBackfillCoordinator(store, [
5660
5792
  {
5661
5793
  name: "Sharing-domain",
@@ -5750,6 +5882,7 @@ async function runMaintenanceWorkerCommand(opts) {
5750
5882
  const dbPath = resolveDbPath(resolveDbOpt(opts));
5751
5883
  if (opts.config) process.env.CODEMEM_CONFIG = opts.config;
5752
5884
  process.env.CODEMEM_DB = dbPath;
5885
+ process.stderr.on("error", () => void 0);
5753
5886
  const abort = new AbortController();
5754
5887
  const runtime = startMaintenanceWorkerRuntime({
5755
5888
  dbPath,
@@ -7099,6 +7232,78 @@ memoryCommand.addCommand(createMemoryExtractionBenchmarkCommand());
7099
7232
  memoryCommand.addCommand(createMemoryRelinkReportCommand());
7100
7233
  memoryCommand.addCommand(createMemoryRelinkPlanCommand());
7101
7234
  //#endregion
7235
+ //#region src/commands/memory-tool.ts
7236
+ /**
7237
+ * `codemem memory-tool <name>` — hidden plumbing for thin hosts.
7238
+ *
7239
+ * Runs one codemem memory tool in-process through the same handlers stdio MCP
7240
+ * uses, reading the tool arguments as a JSON object on stdin and printing one
7241
+ * JSON line on stdout:
7242
+ *
7243
+ * {"ok":true,"result":<tool result>}
7244
+ * {"ok":false,"error":"<message>","result":<tool error payload>} exit 0
7245
+ * {"ok":false,"error":"<code>","message":"<detail>"} exit 1
7246
+ *
7247
+ * Exit 0 means the tool ran (its own error included); exit 1 means the
7248
+ * invocation itself was invalid or the store could not be opened. The caller's
7249
+ * working directory supplies the default project, write-session cwd, and
7250
+ * AGENTS.md context exactly as it does for `codemem mcp`.
7251
+ */
7252
+ var MEMORY_TOOL_NAME = /^memory_[a-z_]+$/;
7253
+ async function readProcessStdin() {
7254
+ const chunks = [];
7255
+ for await (const chunk of process.stdin) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
7256
+ return Buffer.concat(chunks).toString("utf-8");
7257
+ }
7258
+ /** Empty stdin means no arguments; anything else must be a JSON object. */
7259
+ function parseToolArguments(raw) {
7260
+ const trimmed = raw.trim();
7261
+ if (!trimmed) return {};
7262
+ const parsed = JSON.parse(trimmed);
7263
+ if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) throw new TypeError("tool arguments must be a JSON object");
7264
+ return parsed;
7265
+ }
7266
+ function invocationError(write, error, message) {
7267
+ write(JSON.stringify({
7268
+ ok: false,
7269
+ error,
7270
+ message
7271
+ }));
7272
+ process.exitCode = 1;
7273
+ }
7274
+ async function runMemoryTool(name, opts, dependencies = {}) {
7275
+ const write = dependencies.write ?? ((line) => console.log(line));
7276
+ if (!MEMORY_TOOL_NAME.test(name)) {
7277
+ invocationError(write, "invalid_tool", `not a memory tool: ${name}`);
7278
+ return;
7279
+ }
7280
+ let args;
7281
+ try {
7282
+ args = parseToolArguments(await (dependencies.readStdin ?? readProcessStdin)());
7283
+ } catch (err) {
7284
+ invocationError(write, "invalid_arguments", err instanceof Error ? err.message : String(err));
7285
+ return;
7286
+ }
7287
+ let store = null;
7288
+ try {
7289
+ const { callCodememToolLocally } = await import("@codemem/mcp");
7290
+ store = new MemoryStore(resolveDbPath(resolveDbOpt(opts)));
7291
+ const outcome = await callCodememToolLocally(store, name, args, {
7292
+ sessionId: opts.sessionId?.trim() || void 0,
7293
+ requestId: opts.requestId?.trim() || void 0,
7294
+ statelessLedger: true
7295
+ });
7296
+ write(JSON.stringify(outcome));
7297
+ } catch (err) {
7298
+ invocationError(write, "tool_failed", err instanceof Error ? err.message : String(err));
7299
+ } finally {
7300
+ await store?.closeAsync();
7301
+ }
7302
+ }
7303
+ var memoryToolCmd = new Command("memory-tool").configureHelp(helpStyle).description("Run one memory tool in-process (JSON arguments on stdin)").argument("<name>", "memory tool name, for example memory_search").option("--session-id <id>", "host session ID for retrieval-ledger attribution").option("--request-id <id>", "host tool-call ID; with --session-id, a retried call records one ledger attempt");
7304
+ addDbOption(memoryToolCmd);
7305
+ var memoryToolCommand = memoryToolCmd.action((name, opts) => runMemoryTool(name, opts));
7306
+ //#endregion
7102
7307
  //#region src/commands/pack.ts
7103
7308
  var MAX_INTERNAL_LEDGER_INPUT_BYTES = 16384;
7104
7309
  var INTERNAL_LEDGER_INPUT_TIMEOUT_MS = 1e3;
@@ -7278,7 +7483,7 @@ function renderPackTrace(trace) {
7278
7483
  lines.push(trace.output.pack_text);
7279
7484
  return lines.join("\n");
7280
7485
  }
7281
- async function withStore(opts, errorCode, run) {
7486
+ async function withStore$1(opts, errorCode, run) {
7282
7487
  let store = null;
7283
7488
  try {
7284
7489
  store = new MemoryStore(resolveDbPath(resolveDbOpt(opts)));
@@ -7312,7 +7517,7 @@ async function readOptionalLedgerPayload() {
7312
7517
  }
7313
7518
  }
7314
7519
  async function packAction(context, opts) {
7315
- await withStore(opts, "pack_failed", async (store) => {
7520
+ await withStore$1(opts, "pack_failed", async (store) => {
7316
7521
  const { limit, budget, filters, renderOptions } = buildPackRequestOptions(opts, { envProject: process.env.CODEMEM_PROJECT });
7317
7522
  let result;
7318
7523
  if (opts.internalLedger) {
@@ -7357,7 +7562,7 @@ function emitPackResult(context, opts, result, ledgerArtifactFingerprint, ledger
7357
7562
  p.outro("done");
7358
7563
  }
7359
7564
  async function traceAction(context, opts) {
7360
- await withStore(opts, "pack_trace_failed", async (store) => {
7565
+ await withStore$1(opts, "pack_trace_failed", async (store) => {
7361
7566
  const { limit, budget, filters, renderOptions } = buildPackRequestOptions(opts, { envProject: process.env.CODEMEM_PROJECT });
7362
7567
  const trace = await store.buildMemoryPackTraceAsync(context, limit, budget, filters, renderOptions);
7363
7568
  if (opts.json) {
@@ -7425,7 +7630,7 @@ function handlePromptPackLifecycle(db, payload) {
7425
7630
  throw new PackUsageError("internal ledger action is invalid");
7426
7631
  }
7427
7632
  async function promptPackLedgerAction(opts) {
7428
- await withStore(opts, "prompt_pack_ledger_failed", async (store) => {
7633
+ await withStore$1(opts, "prompt_pack_ledger_failed", async (store) => {
7429
7634
  const payload = await readInternalLedgerPayload();
7430
7635
  handlePromptPackLedger(store.db, payload);
7431
7636
  });
@@ -7465,7 +7670,7 @@ var hasPiHookSpooledEntries = spool.hasSpooledEntries;
7465
7670
  var hasSpooledPiHookPayload = (receipt) => hasHookIngestSpoolReceipt(spool.spoolDir(), receipt);
7466
7671
  var recoverStalePiHookTmpSpool = spool.recoverStaleTmpSpool;
7467
7672
  var piHookLockTtlSeconds = spool.lockTtlSeconds;
7468
- spool.spoolDir;
7673
+ var piHookSpoolDir = spool.spoolDir;
7469
7674
  /**
7470
7675
  * Boundary flush for pi: compaction and session end both trigger extraction.
7471
7676
  * session_before_compact is observe-only (never stored as transcript).
@@ -7620,10 +7825,10 @@ function directEnqueuePiHook(payload, dbPath) {
7620
7825
  /**
7621
7826
  * Best-effort boundary flush for session_before_compact / session_shutdown.
7622
7827
  * Always passes source "pi" — never relies on a helper default.
7623
- * Returns false when observer/store/extraction fail so a recovered-boundary
7624
- * retry can keep the spool; live hook callers stay fail-open and ignore it.
7828
+ * Returns false until the captured boundary is complete, retaining the receipt
7829
+ * for the next invocation. Each attempt extracts at most one batch.
7625
7830
  */
7626
- async function flushBoundaryRawEvents(payload, dbPath) {
7831
+ async function flushBoundaryRawEvents(payload, dbPath, receipt) {
7627
7832
  const envelope = buildRawEventEnvelopeFromPiEvent(payload);
7628
7833
  const signal = buildPiFlushSignalFromEvent(payload);
7629
7834
  const sessionId = envelope?.session_stream_id ?? signal?.session_id ?? null;
@@ -7647,15 +7852,17 @@ async function flushBoundaryRawEvents(payload, dbPath) {
7647
7852
  return false;
7648
7853
  }
7649
7854
  try {
7855
+ const throughEventSeq = capturePiBoundaryCeiling(store, sessionId, payload, receipt);
7650
7856
  await flushRawEvents(store, { observer }, {
7651
7857
  opencodeSessionId: sessionId,
7652
7858
  source,
7653
7859
  cwd,
7654
7860
  project,
7655
7861
  startedAt,
7656
- maxEvents: null
7862
+ maxEvents: DEFAULT_RAW_EVENT_FLUSH_MAX_EVENTS,
7863
+ throughEventSeq
7657
7864
  });
7658
- return true;
7865
+ return isPiBoundaryComplete(store, sessionId, throughEventSeq);
7659
7866
  } catch (err) {
7660
7867
  logHookEvent(`codemem pi-hook-ingest boundary flush raw events failed: ${err instanceof Error ? err.message : String(err)}`);
7661
7868
  return false;
@@ -7663,6 +7870,33 @@ async function flushBoundaryRawEvents(payload, dbPath) {
7663
7870
  store.close();
7664
7871
  }
7665
7872
  }
7873
+ var BOUNDARY_CEILING_FIELD = "_codememBoundaryThroughEventSeq";
7874
+ function isPiBoundaryComplete(store, sessionId, throughEventSeq) {
7875
+ const cursor = store.rawEventFlushState(sessionId, "pi");
7876
+ return cursor >= throughEventSeq || store.rawEventsSinceBySeq(sessionId, "pi", cursor, 1, throughEventSeq).length === 0;
7877
+ }
7878
+ function capturePiBoundaryCeiling(store, sessionId, payload, receipt) {
7879
+ const saved = payload[BOUNDARY_CEILING_FIELD];
7880
+ if (typeof saved === "number" && Number.isSafeInteger(saved) && saved >= -1) return saved;
7881
+ const ceiling = Number(store.rawEventSessionMeta(sessionId, "pi").last_received_event_seq ?? -1);
7882
+ if (!Number.isSafeInteger(ceiling) || ceiling < -1) throw new Error("invalid Pi boundary event sequence");
7883
+ if (receipt) {
7884
+ const dir = piHookSpoolDir();
7885
+ const temporary = join(dir, `.hook-tmp-boundary-${receipt}.tmp`);
7886
+ try {
7887
+ writeFileSync(temporary, JSON.stringify({
7888
+ ...payload,
7889
+ [BOUNDARY_CEILING_FIELD]: ceiling
7890
+ }));
7891
+ renameSync(temporary, join(dir, receipt));
7892
+ } finally {
7893
+ try {
7894
+ unlinkSync(temporary);
7895
+ } catch {}
7896
+ }
7897
+ }
7898
+ return ceiling;
7899
+ }
7666
7900
  function dbPathGetter(resolveDb, opts) {
7667
7901
  let cached = null;
7668
7902
  return () => {
@@ -7681,11 +7915,13 @@ function tryDirectFallback(runtime, queued) {
7681
7915
  return { ok: false };
7682
7916
  }
7683
7917
  }
7684
- async function writeAndFlushBoundary(runtime, payload) {
7918
+ async function writeAndFlushBoundary(runtime, payload, receipt) {
7919
+ if (runtime.boundaryFlushAttempted) return { ok: false };
7685
7920
  const direct = tryDirectFallback(runtime, payload);
7686
7921
  if (!direct.ok) return direct;
7922
+ runtime.boundaryFlushAttempted = true;
7687
7923
  try {
7688
- if (await runtime.boundaryFlush(payload, runtime.getDbPath()) === false) {
7924
+ if (await runtime.boundaryFlush(payload, runtime.getDbPath(), receipt) === false) {
7689
7925
  logHookEvent("codemem pi-hook-ingest boundary flush failed; keeping spooled payload");
7690
7926
  return { ok: false };
7691
7927
  }
@@ -7711,6 +7947,7 @@ function createPiIngestRuntime(payload, opts, deps) {
7711
7947
  httpIngest: deps.httpIngest ?? tryHttpIngest,
7712
7948
  directIngest: deps.directIngest ?? directEnqueuePiHook,
7713
7949
  boundaryFlush: deps.boundaryFlush ?? flushBoundaryRawEvents,
7950
+ boundaryFlushAttempted: false,
7714
7951
  withLock: deps.withLock ?? withPiHookIngestLock,
7715
7952
  getDbPath,
7716
7953
  httpPayload: (queued) => targetedPiPayload(queued, getDbPath)
@@ -7735,7 +7972,7 @@ function spoolPiPayloadOrThrow(payload) {
7735
7972
  };
7736
7973
  throw new Error("pi-hook-ingest: HTTP and spool failed");
7737
7974
  }
7738
- async function deliverQueuedPiHook(runtime, queuedPayload) {
7975
+ async function deliverQueuedPiHook(runtime, queuedPayload, receipt) {
7739
7976
  const result = await runtime.httpIngest(runtime.httpPayload(queuedPayload), runtime.opts.host, runtime.port);
7740
7977
  const boundaryRequested = shouldForcePiBoundaryFlush(queuedPayload);
7741
7978
  if (result.ok && (result.queued !== void 0 || !boundaryRequested)) return {
@@ -7748,7 +7985,7 @@ async function deliverQueuedPiHook(runtime, queuedPayload) {
7748
7985
  httpResult: result,
7749
7986
  directResult: null
7750
7987
  };
7751
- const boundary = await writeAndFlushBoundary(runtime, queuedPayload);
7988
+ const boundary = await writeAndFlushBoundary(runtime, queuedPayload, receipt);
7752
7989
  if (!boundary.ok) return {
7753
7990
  accepted: false,
7754
7991
  httpResult: result,
@@ -7761,7 +7998,7 @@ async function deliverQueuedPiHook(runtime, queuedPayload) {
7761
7998
  };
7762
7999
  }
7763
8000
  async function ingestPiBoundaryDirect(runtime, receipt) {
7764
- const boundary = await writeAndFlushBoundary(runtime, runtime.payload);
8001
+ const boundary = await writeAndFlushBoundary(runtime, runtime.payload, receipt);
7765
8002
  if (!boundary.ok) return {
7766
8003
  inserted: 0,
7767
8004
  skipped: 0,
@@ -7782,7 +8019,7 @@ async function drainPiBacklog(runtime, currentReceipt) {
7782
8019
  await runtime.withLock(async () => {
7783
8020
  recoverStalePiHookTmpSpool(piHookLockTtlSeconds());
7784
8021
  await drainPiHookSpool(async (queuedPayload, receipt) => {
7785
- const delivery = await deliverQueuedPiHook(runtime, queuedPayload);
8022
+ const delivery = await deliverQueuedPiHook(runtime, queuedPayload, receipt);
7786
8023
  if (receipt === currentReceipt) {
7787
8024
  currentResult = delivery.httpResult;
7788
8025
  currentAccepted = delivery.accepted;
@@ -7831,7 +8068,8 @@ async function retainAndProcessBoundary(runtime) {
7831
8068
  }
7832
8069
  /** Ingest one Pi event through the Viewer queue or local spool. */
7833
8070
  async function ingestPiHookPayload(payload, opts, deps = {}) {
7834
- const stablePayload = stabilizePiBoundaryPayload(payload);
8071
+ const { [BOUNDARY_CEILING_FIELD]: _ignoredCeiling, ...livePayload } = payload;
8072
+ const stablePayload = stabilizePiBoundaryPayload(livePayload);
7835
8073
  const runtime = createPiIngestRuntime(stablePayload, opts, deps);
7836
8074
  const boundaryRequested = shouldForcePiBoundaryFlush(stablePayload);
7837
8075
  if (hasPiHookSpooledEntries()) {
@@ -7989,12 +8227,12 @@ async function buildLocalPack(context, project, dbPath) {
7989
8227
  await store.closeAsync();
7990
8228
  }
7991
8229
  }
7992
- function isRecord$1(value) {
8230
+ function isRecord$2(value) {
7993
8231
  return value != null && typeof value === "object" && !Array.isArray(value);
7994
8232
  }
7995
8233
  function canonicalJson(value) {
7996
8234
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
7997
- if (isRecord$1(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
8235
+ if (isRecord$2(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
7998
8236
  return JSON.stringify(value);
7999
8237
  }
8000
8238
  function viewerBaseUrl() {
@@ -8018,7 +8256,7 @@ async function responseJson(response) {
8018
8256
  }
8019
8257
  }
8020
8258
  function errorCode(body) {
8021
- return isRecord$1(body) && isRecord$1(body.error) && typeof body.error.code === "string" ? body.error.code : null;
8259
+ return isRecord$2(body) && isRecord$2(body.error) && typeof body.error.code === "string" ? body.error.code : null;
8022
8260
  }
8023
8261
  function classifyViewerHttpFailure(status, body, compatibleProfile) {
8024
8262
  const code = errorCode(body);
@@ -8071,13 +8309,13 @@ async function targetedViewerPackPost(baseUrl, identity, query, project, dbPath,
8071
8309
  ok: false,
8072
8310
  disposition: classifyViewerHttpFailure(packResponse.status, body, true)
8073
8311
  };
8074
- const packText = isRecord$1(body) ? String(body.pack_text ?? "").trim() : "";
8075
- const metrics = isRecord$1(body) && isRecord$1(body.metrics) ? body.metrics : null;
8312
+ const packText = isRecord$2(body) ? String(body.pack_text ?? "").trim() : "";
8313
+ const metrics = isRecord$2(body) && isRecord$2(body.metrics) ? body.metrics : null;
8076
8314
  return {
8077
8315
  ok: true,
8078
8316
  pack: {
8079
8317
  packText,
8080
- items: isRecord$1(body) && Array.isArray(body.items) ? body.items.length : 0,
8318
+ items: isRecord$2(body) && Array.isArray(body.items) ? body.items.length : 0,
8081
8319
  packTokens: metrics && Number.isFinite(Number(metrics.pack_tokens)) ? Number(metrics.pack_tokens) : 0
8082
8320
  }
8083
8321
  };
@@ -8106,8 +8344,8 @@ async function fetchAndValidateViewerProfile(baseUrl, dbPath, identity, fetchImp
8106
8344
  ok: false,
8107
8345
  disposition: classifyViewerHttpFailure(profileResponse.status, profile, false)
8108
8346
  };
8109
- const viewerRange = isRecord$1(profile) ? normalizePromptTransportProtocolRange(profile.protocol_version, profile.min_supported_protocol_version) : null;
8110
- if (!isRecord$1(profile) || profile.service !== "codemem-viewer" || !viewerRange || !arePromptTransportProtocolRangesCompatible(PROMPT_TRANSPORT_PROTOCOL_RANGE, viewerRange)) return {
8347
+ const viewerRange = isRecord$2(profile) ? normalizePromptTransportProtocolRange(profile.protocol_version, profile.min_supported_protocol_version) : null;
8348
+ if (!isRecord$2(profile) || profile.service !== "codemem-viewer" || !viewerRange || !arePromptTransportProtocolRangesCompatible(PROMPT_TRANSPORT_PROTOCOL_RANGE, viewerRange)) return {
8111
8349
  ok: false,
8112
8350
  disposition: "fallback"
8113
8351
  };
@@ -8293,19 +8531,16 @@ async function flushImportedPiSessions(dbPath, observer) {
8293
8531
  extraction.pendingSessions = piPendingSessions(store).length;
8294
8532
  return extraction;
8295
8533
  }
8296
- for (const streamId of piPendingSessions(store)) try {
8297
- const result = await flushRawEvents(store, { observer: resolved }, {
8298
- opencodeSessionId: streamId,
8299
- source: "pi",
8300
- cwd: null,
8301
- project: null,
8302
- startedAt: null,
8303
- maxEvents: null
8304
- });
8305
- extraction.flushedEvents += result.flushed;
8534
+ const backlog = piPendingSessions(store).map((streamId) => ({
8535
+ streamId,
8536
+ throughEventSeq: Number(store.rawEventSessionMeta(streamId, "pi").last_received_event_seq),
8537
+ initialCursor: store.rawEventFlushState(streamId, "pi")
8538
+ }));
8539
+ for (const stream of backlog) try {
8540
+ await drainImportedPiStream(store, resolved, stream, extraction);
8306
8541
  } catch (err) {
8307
8542
  extraction.failedSessions++;
8308
- extraction.error ??= `session ${streamId}: ${err instanceof Error ? err.message : String(err)}`;
8543
+ extraction.error ??= `session ${stream.streamId}: ${err instanceof Error ? err.message : String(err)}`;
8309
8544
  }
8310
8545
  extraction.pendingSessions = piPendingSessions(store).length;
8311
8546
  return extraction;
@@ -8313,6 +8548,28 @@ async function flushImportedPiSessions(dbPath, observer) {
8313
8548
  store.close();
8314
8549
  }
8315
8550
  }
8551
+ async function drainImportedPiStream(store, observer, stream, extraction) {
8552
+ const { streamId, throughEventSeq, initialCursor } = stream;
8553
+ const maxAttempts = Math.max(0, throughEventSeq - initialCursor);
8554
+ if (!Number.isSafeInteger(throughEventSeq) || !Number.isSafeInteger(initialCursor) || !Number.isSafeInteger(maxAttempts) || throughEventSeq < -1 || initialCursor < -1) throw new Error("invalid Pi import event sequence");
8555
+ let cursor = initialCursor;
8556
+ for (let attempt = 0; attempt < maxAttempts && cursor < throughEventSeq; attempt++) {
8557
+ const result = await flushRawEvents(store, { observer }, {
8558
+ opencodeSessionId: streamId,
8559
+ source: "pi",
8560
+ cwd: null,
8561
+ project: null,
8562
+ startedAt: null,
8563
+ maxEvents: DEFAULT_RAW_EVENT_FLUSH_MAX_EVENTS,
8564
+ throughEventSeq
8565
+ });
8566
+ extraction.flushedEvents += result.flushed;
8567
+ const nextCursor = store.rawEventFlushState(streamId, "pi");
8568
+ if (!Number.isSafeInteger(nextCursor)) throw new Error("invalid Pi import flush cursor");
8569
+ if (nextCursor <= cursor) break;
8570
+ cursor = nextCursor;
8571
+ }
8572
+ }
8316
8573
  /** Pending-flush sessions attributed to source "pi", without a page cap. */
8317
8574
  function piPendingSessions(store) {
8318
8575
  return store.rawEventSessionsPendingFlush(null, "pi").map((session) => session.streamId);
@@ -8532,6 +8789,34 @@ function timeSince(isoDate) {
8532
8789
  return `${Math.floor(days / 30)}mo ago`;
8533
8790
  }
8534
8791
  //#endregion
8792
+ //#region src/child-stderr-forward.ts
8793
+ var defaultWrite = (text) => {
8794
+ process.stderr.write(text);
8795
+ };
8796
+ /**
8797
+ * Copy a child process's stderr into this process's stderr one prefixed line
8798
+ * at a time, so container logs show which process wrote each line.
8799
+ *
8800
+ * The parent reads the pipe from its event loop, so the child only waits when
8801
+ * the pipe buffer (64 KiB on Linux) fills while the parent is busy. Read and
8802
+ * write errors end forwarding instead of crashing either process.
8803
+ */
8804
+ function forwardChildStderr(source, options) {
8805
+ const write = options.write ?? defaultWrite;
8806
+ const lines = createInterface({
8807
+ input: source,
8808
+ crlfDelay: Number.POSITIVE_INFINITY
8809
+ });
8810
+ const ignorePipeError = () => void 0;
8811
+ source.on("error", ignorePipeError);
8812
+ lines.on("error", ignorePipeError);
8813
+ lines.on("line", (line) => {
8814
+ try {
8815
+ write(`${options.prefix}${line}\n`);
8816
+ } catch {}
8817
+ });
8818
+ }
8819
+ //#endregion
8535
8820
  //#region src/observer-runtime-controller.ts
8536
8821
  /** Keep the live observer and saved config separate until in-flight work has drained. */
8537
8822
  var ObserverRuntimeController = class {
@@ -9061,6 +9346,7 @@ function buildMaintenanceWorkerArgs(scriptPath, invocation, execArgv = process.e
9061
9346
  if (invocation.configPath) args.push("--config", invocation.configPath);
9062
9347
  return args;
9063
9348
  }
9349
+ var MAINTENANCE_WORKER_LOG_PREFIX = "[maintenance-worker] ";
9064
9350
  function startMaintenanceWorkerProcess(invocation) {
9065
9351
  const scriptPath = process.argv[1];
9066
9352
  if (!scriptPath) {
@@ -9070,13 +9356,21 @@ function startMaintenanceWorkerProcess(invocation) {
9070
9356
  const dbPath = resolveDbPath(invocation.dbPath ?? void 0);
9071
9357
  const child = spawn(process.execPath, buildMaintenanceWorkerArgs(scriptPath, invocation), {
9072
9358
  cwd: process.cwd(),
9073
- stdio: "ignore",
9359
+ stdio: [
9360
+ "ignore",
9361
+ "ignore",
9362
+ "pipe"
9363
+ ],
9074
9364
  env: {
9075
9365
  ...process.env,
9076
9366
  CODEMEM_DB: dbPath,
9077
9367
  ...invocation.configPath ? { CODEMEM_CONFIG: invocation.configPath } : {}
9078
9368
  }
9079
9369
  });
9370
+ if (child.stderr) {
9371
+ forwardChildStderr(child.stderr, { prefix: MAINTENANCE_WORKER_LOG_PREFIX });
9372
+ child.stderr.unref?.();
9373
+ }
9080
9374
  child.unref();
9081
9375
  if (child.pid) {
9082
9376
  writeFileSync(maintenanceWorkerPidFilePath(dbPath), JSON.stringify({
@@ -9381,6 +9675,90 @@ function announceViewerStartup(options) {
9381
9675
  p.log.info(`Database: ${preparedDb}`);
9382
9676
  p.log.step("Raw event sweeper started");
9383
9677
  }
9678
+ var logRelay = (message, level) => level === "warn" ? p.log.warn(message) : p.log.info(message);
9679
+ /**
9680
+ * Relay additions to the sync daemon options. Without relay this returns the
9681
+ * callback unchanged and no `reachability`, so sync runs exactly as before.
9682
+ * With relay, groups re-resolve after every coordinator refresh, even a failed one.
9683
+ */
9684
+ function serveRelayDaemonOptions(relay, onAfterCoordinatorRefresh) {
9685
+ if (!relay) return { onAfterCoordinatorRefresh };
9686
+ return {
9687
+ reachability: relay.reachability,
9688
+ onAfterCoordinatorRefresh: async (context) => {
9689
+ try {
9690
+ await onAfterCoordinatorRefresh(context);
9691
+ } finally {
9692
+ await relay.refresh();
9693
+ }
9694
+ }
9695
+ };
9696
+ }
9697
+ function applySyncPhase(status, phase) {
9698
+ if (phase === "running") {
9699
+ status.phase = null;
9700
+ status.detail = null;
9701
+ return;
9702
+ }
9703
+ status.phase = phase;
9704
+ status.detail = phase === "starting" ? "Running initial sync in background" : "Stopping sync daemon";
9705
+ }
9706
+ function startServeSyncDaemon(options) {
9707
+ const { syncConfig, store, signal, status, relay } = options;
9708
+ status.phase = "starting";
9709
+ status.detail = "Starting sync in background";
9710
+ relay?.refresh();
9711
+ runSyncDaemon({
9712
+ dbPath: resolveDbPath(options.invocation.dbPath ?? void 0),
9713
+ intervalS: syncConfig.syncIntervalS,
9714
+ host: syncConfig.syncHost,
9715
+ port: syncConfig.syncPort,
9716
+ signal,
9717
+ scanner: store.scanner,
9718
+ ...serveRelayDaemonOptions(relay, async () => {
9719
+ await runServeCoordinatorMaintenance(store, options.maintenance);
9720
+ }),
9721
+ onPhaseChange: (phase) => applySyncPhase(status, phase)
9722
+ }).catch((err) => {
9723
+ const msg = err instanceof Error ? err.message : String(err);
9724
+ status.phase = "error";
9725
+ status.detail = msg;
9726
+ p.log.error(`Sync daemon failed: ${msg}`);
9727
+ }).finally(() => {
9728
+ relay?.close();
9729
+ if (status.phase !== "error") {
9730
+ status.phase = signal.aborted ? "stopping" : null;
9731
+ status.detail = signal.aborted ? "Sync stopped" : null;
9732
+ }
9733
+ });
9734
+ }
9735
+ /**
9736
+ * Runs a memory tool for a thin host through the same in-process MCP handlers
9737
+ * as stdio and `codemem memory-tool`. Loaded lazily so viewer startup does not
9738
+ * pull in the MCP SDK until a host actually calls a tool.
9739
+ */
9740
+ async function callMemoryToolForHost(store, name, args, caller) {
9741
+ const { callCodememToolLocally } = await import("@codemem/mcp");
9742
+ return callCodememToolLocally(store, name, args, caller);
9743
+ }
9744
+ function createBoundApp(createApp, options, listener) {
9745
+ let boundAddress = null;
9746
+ return {
9747
+ app: createApp({
9748
+ ...options,
9749
+ viewerAuthority: { getListenerAddress: () => boundAddress },
9750
+ memoryToolCall: callMemoryToolForHost
9751
+ }),
9752
+ setBoundAddress: (info) => {
9753
+ boundAddress = {
9754
+ host: listener.invocation.host,
9755
+ port: info.port,
9756
+ address: info.address
9757
+ };
9758
+ listener.accountLink.setBoundPort(info.port);
9759
+ }
9760
+ };
9761
+ }
9384
9762
  async function startForegroundViewer(invocation) {
9385
9763
  const serverModule = await import("@codemem/server");
9386
9764
  const { createApp, createSyncApp, closeStoreAsync, createViewerRawEventInbox, getStore } = serverModule;
@@ -9415,6 +9793,13 @@ async function startForegroundViewer(invocation) {
9415
9793
  const syncConfig = readCoordinatorSyncConfig(config);
9416
9794
  const syncEnabled = syncConfig.syncEnabled;
9417
9795
  const accountLink = createViewerAccountLink(store, invocation, serverModule);
9796
+ const relay = syncEnabled ? serverModule.createViewerRelayReachability({
9797
+ store,
9798
+ config,
9799
+ keysDir: process.env.CODEMEM_KEYS_DIR?.trim() || void 0,
9800
+ signal: syncAbort.signal,
9801
+ log: logRelay
9802
+ }) : null;
9418
9803
  const syncRuntimeStatus = {
9419
9804
  phase: syncEnabled ? "starting" : "disabled",
9420
9805
  detail: syncEnabled ? "Waiting for viewer startup to finish" : "Sync is disabled"
@@ -9425,7 +9810,10 @@ async function startForegroundViewer(invocation) {
9425
9810
  ...rawEventProcessing.appOptions,
9426
9811
  getSyncRuntimeStatus: () => syncRuntimeStatus
9427
9812
  };
9428
- const app = createApp(appOpts);
9813
+ const { app, setBoundAddress } = createBoundApp(createApp, appOpts, {
9814
+ invocation,
9815
+ accountLink
9816
+ });
9429
9817
  const pidPath = pidFilePath(dbPath);
9430
9818
  let maintenanceWorker = null;
9431
9819
  let syncServer = null;
@@ -9449,7 +9837,7 @@ async function startForegroundViewer(invocation) {
9449
9837
  hostname: invocation.host,
9450
9838
  port: invocation.port
9451
9839
  }, (info) => {
9452
- accountLink.setBoundPort(info.port);
9840
+ setBoundAddress(info);
9453
9841
  announceViewerStartup({
9454
9842
  pidPath,
9455
9843
  invocation,
@@ -9461,37 +9849,14 @@ async function startForegroundViewer(invocation) {
9461
9849
  const syncStartDelayMs = 3e3;
9462
9850
  p.log.step(`Sync daemon will start in background (${syncStartDelayMs / 1e3}s delay)`);
9463
9851
  setTimeout(() => {
9464
- syncRuntimeStatus.phase = "starting";
9465
- syncRuntimeStatus.detail = "Starting sync in background";
9466
- runSyncDaemon({
9467
- dbPath: resolveDbPath(invocation.dbPath ?? void 0),
9468
- intervalS: syncConfig.syncIntervalS,
9469
- host: syncConfig.syncHost,
9470
- port: syncConfig.syncPort,
9852
+ startServeSyncDaemon({
9853
+ invocation,
9854
+ syncConfig,
9855
+ store,
9471
9856
  signal: syncAbort.signal,
9472
- scanner: store.scanner,
9473
- onAfterCoordinatorRefresh: async () => {
9474
- await runServeCoordinatorMaintenance(store, coordinatorMaintenanceDependencies);
9475
- },
9476
- onPhaseChange: (phase) => {
9477
- if (phase === "running") {
9478
- syncRuntimeStatus.phase = null;
9479
- syncRuntimeStatus.detail = null;
9480
- } else {
9481
- syncRuntimeStatus.phase = phase;
9482
- syncRuntimeStatus.detail = phase === "starting" ? "Running initial sync in background" : "Stopping sync daemon";
9483
- }
9484
- }
9485
- }).catch((err) => {
9486
- const msg = err instanceof Error ? err.message : String(err);
9487
- syncRuntimeStatus.phase = "error";
9488
- syncRuntimeStatus.detail = msg;
9489
- p.log.error(`Sync daemon failed: ${msg}`);
9490
- }).finally(() => {
9491
- if (syncRuntimeStatus.phase !== "error") {
9492
- syncRuntimeStatus.phase = syncAbort.signal.aborted ? "stopping" : null;
9493
- syncRuntimeStatus.detail = syncAbort.signal.aborted ? "Sync stopped" : null;
9494
- }
9857
+ status: syncRuntimeStatus,
9858
+ maintenance: coordinatorMaintenanceDependencies,
9859
+ relay
9495
9860
  });
9496
9861
  }, syncStartDelayMs).unref();
9497
9862
  }
@@ -9513,6 +9878,7 @@ async function startForegroundViewer(invocation) {
9513
9878
  syncAbort.abort();
9514
9879
  try {
9515
9880
  try {
9881
+ if (relay) await relay.close();
9516
9882
  await accountLink.close();
9517
9883
  await stopMaintenanceWorkerProcess(maintenanceWorker, dbPath);
9518
9884
  } finally {
@@ -9698,7 +10064,7 @@ function loadJsoncConfig(path) {
9698
10064
  if (!existsSync(path)) return {};
9699
10065
  return parseJsoncConfig(readFileSync(path, "utf-8"));
9700
10066
  }
9701
- function isRecord(value) {
10067
+ function isRecord$1(value) {
9702
10068
  return value !== null && typeof value === "object" && !Array.isArray(value);
9703
10069
  }
9704
10070
  function rejectDuplicateKeys(node) {
@@ -9721,7 +10087,7 @@ function parseJsoncConfig(raw) {
9721
10087
  const first = errors[0];
9722
10088
  throw new Error(`${printParseErrorCode(first.error)} at offset ${first.offset}`);
9723
10089
  }
9724
- if (!isRecord(parsed)) throw new Error("OpenCode config must be a JSON object");
10090
+ if (!isRecord$1(parsed)) throw new Error("OpenCode config must be a JSON object");
9725
10091
  const tree = parseTree(raw, [], { allowTrailingComma: true });
9726
10092
  if (tree) rejectDuplicateKeys(tree);
9727
10093
  return parsed;
@@ -9735,7 +10101,7 @@ function collectChanges(before, after, path = []) {
9735
10101
  for (const [key, value] of Object.entries(after)) {
9736
10102
  const nextPath = [...path, key];
9737
10103
  const previous = before[key];
9738
- if (isRecord(previous) && isRecord(value)) {
10104
+ if (isRecord$1(previous) && isRecord$1(value)) {
9739
10105
  changes.push(...collectChanges(previous, value, nextPath));
9740
10106
  continue;
9741
10107
  }
@@ -9756,6 +10122,9 @@ function applyChange(raw, change, { format = true } = {}) {
9756
10122
  if (change.value !== void 0) {
9757
10123
  const appended = appendObjectProperty(raw, change);
9758
10124
  if (appended !== void 0) return appended;
10125
+ } else {
10126
+ const removed = removeObjectProperty(raw, change.path);
10127
+ if (removed !== void 0) return removed;
9759
10128
  }
9760
10129
  const options = format ? { formattingOptions } : {};
9761
10130
  return applyEdits(raw, modify(raw, change.path, change.value, options));
@@ -9807,6 +10176,73 @@ function hasCommaToken(raw, start, end) {
9807
10176
  }
9808
10177
  return false;
9809
10178
  }
10179
+ function findCommaOffset(raw, start, end) {
10180
+ const scanner = createScanner(raw);
10181
+ scanner.setPosition(start);
10182
+ while (scanner.getPosition() < end) {
10183
+ scanner.scan();
10184
+ if (scanner.getTokenLength() === 0) return void 0;
10185
+ const tokenStart = scanner.getTokenOffset();
10186
+ if (tokenStart >= end) return void 0;
10187
+ if (raw[tokenStart] === ",") return tokenStart;
10188
+ }
10189
+ }
10190
+ /** Cut [start, end), widening to the whole line when nothing else is on it. */
10191
+ function cutText(raw, start, end) {
10192
+ const lineStart = raw.lastIndexOf("\n", start - 1) + 1;
10193
+ const lineEnd = raw.indexOf("\n", end);
10194
+ const ownsLine = raw.slice(lineStart, start).trim() === "" && lineEnd !== -1 && raw.slice(end, lineEnd).trim() === "";
10195
+ const from = ownsLine ? lineStart : start;
10196
+ const to = ownsLine ? lineEnd + 1 : end;
10197
+ return applyEdits(raw, [{
10198
+ offset: from,
10199
+ length: to - from,
10200
+ content: ""
10201
+ }]);
10202
+ }
10203
+ /**
10204
+ * Remove an object property as a text cut. jsonc-parser's `modify` leaves a
10205
+ * dangling comma (invalid JSONC) when the only property has a trailing comma,
10206
+ * and its formatting option reflows sibling properties. This cuts the property,
10207
+ * its comma, and its line when nothing else is on it, so siblings and comments
10208
+ * keep their text. Returns undefined when the path is not an object property.
10209
+ */
10210
+ function removeObjectProperty(raw, path) {
10211
+ const tree = parseTree(raw, [], { allowTrailingComma: true });
10212
+ const parentNode = tree ? findNodeAtLocation(tree, path.slice(0, -1)) : void 0;
10213
+ const siblings = parentNode?.type === "object" ? parentNode.children ?? [] : [];
10214
+ const index = siblings.findIndex((property) => property.children?.[0]?.value === path.at(-1));
10215
+ const property = siblings[index];
10216
+ if (!parentNode || !property) return void 0;
10217
+ const propertyEnd = property.offset + property.length;
10218
+ const trailingComma = findCommaOffset(raw, propertyEnd, siblings[index + 1]?.offset ?? parentNode.offset + parentNode.length - 1);
10219
+ if (trailingComma !== void 0) return cutText(raw, property.offset, trailingComma + 1);
10220
+ const previous = siblings[index - 1];
10221
+ const leadingComma = previous ? findCommaOffset(raw, previous.offset + previous.length, property.offset) : void 0;
10222
+ if (leadingComma !== void 0) return applyEdits(raw, [{
10223
+ offset: leadingComma,
10224
+ length: propertyEnd - leadingComma,
10225
+ content: ""
10226
+ }]);
10227
+ return cutText(raw, property.offset, propertyEnd);
10228
+ }
10229
+ /** True when the JSONC value at `path` contains a line or block comment. */
10230
+ function jsoncValueHasComments(raw, path) {
10231
+ const tree = parseTree(raw, [], { allowTrailingComma: true });
10232
+ const node = tree ? findNodeAtLocation(tree, path) : void 0;
10233
+ if (!node) return false;
10234
+ const scanner = createScanner(raw);
10235
+ scanner.setPosition(node.offset);
10236
+ const end = node.offset + node.length;
10237
+ while (scanner.getPosition() < end) {
10238
+ scanner.scan();
10239
+ if (scanner.getTokenLength() === 0) return false;
10240
+ const tokenStart = scanner.getTokenOffset();
10241
+ const prefix = raw.slice(tokenStart, tokenStart + 2);
10242
+ if (prefix === "//" || prefix === "/*") return true;
10243
+ }
10244
+ return false;
10245
+ }
9810
10246
  function appendObjectProperty(raw, change) {
9811
10247
  const key = change.path.at(-1);
9812
10248
  if (typeof key !== "string") return void 0;
@@ -9921,6 +10357,188 @@ function writeJsonConfigWithBackup(path, data) {
9921
10357
  writeJsonConfig(path, data);
9922
10358
  }
9923
10359
  //#endregion
10360
+ //#region src/commands/setup-opencode-mcp.ts
10361
+ /** Commands setup has written for OpenCode, across releases. */
10362
+ var MANAGED_COMMANDS = [
10363
+ ["codemem", "mcp"],
10364
+ [
10365
+ "npx",
10366
+ "-y",
10367
+ "--package",
10368
+ "codemem",
10369
+ "--package",
10370
+ "@codemem/embeddings",
10371
+ "codemem",
10372
+ "mcp"
10373
+ ],
10374
+ [
10375
+ "npx",
10376
+ "-y",
10377
+ "codemem",
10378
+ "mcp"
10379
+ ],
10380
+ [
10381
+ "npx",
10382
+ "codemem",
10383
+ "mcp"
10384
+ ],
10385
+ [
10386
+ "uvx",
10387
+ "codemem",
10388
+ "mcp"
10389
+ ]
10390
+ ];
10391
+ /** Fields setup writes (V1 `enabled`, V2 `disabled`); any other field is user data. */
10392
+ var MANAGED_FIELDS = /* @__PURE__ */ new Set([
10393
+ "type",
10394
+ "command",
10395
+ "enabled",
10396
+ "disabled"
10397
+ ]);
10398
+ var V1_CONTAINER_PATH = ["mcp"];
10399
+ var V2_CONTAINER_PATH = ["mcp", "servers"];
10400
+ function isRecord(value) {
10401
+ return value !== null && typeof value === "object" && !Array.isArray(value);
10402
+ }
10403
+ function isExactStringArray$1(value, expected) {
10404
+ return Array.isArray(value) && value.length === expected.length && value.every((entry, index) => entry === expected[index]);
10405
+ }
10406
+ /**
10407
+ * The uv launcher Python-era setup wrote (opencode_integration_cmds.py). Only
10408
+ * this exact command is upgraded: a uvx command with a version pin or extra
10409
+ * arguments such as `--db-path` is user data and is left alone.
10410
+ */
10411
+ function isLegacyUvOpencodeCommand(command) {
10412
+ return isExactStringArray$1(command, [
10413
+ "uvx",
10414
+ "codemem",
10415
+ "mcp"
10416
+ ]);
10417
+ }
10418
+ /** Older single-package npx launchers that `--opencode-mcp stdio` upgrades in place. */
10419
+ function isSinglePackageNpxOpencodeCommand(command) {
10420
+ return isExactStringArray$1(command, [
10421
+ "npx",
10422
+ "-y",
10423
+ "codemem",
10424
+ "mcp"
10425
+ ]) || isExactStringArray$1(command, [
10426
+ "npx",
10427
+ "codemem",
10428
+ "mcp"
10429
+ ]);
10430
+ }
10431
+ /**
10432
+ * Exact commands setup has written, safe to delete. A command with a version
10433
+ * pin or extra arguments (`--from codemem==0.20.0`, `--db-path ...`) is user
10434
+ * data.
10435
+ */
10436
+ function isManagedOpencodeMcpCommand(command) {
10437
+ return MANAGED_COMMANDS.some((expected) => isExactStringArray$1(command, expected));
10438
+ }
10439
+ /**
10440
+ * True when `mcp.servers` is the V2 server map. V1 configs could in theory name
10441
+ * a server "servers"; a value that itself looks like a server entry is V1.
10442
+ */
10443
+ function isV2ServerMap(value) {
10444
+ return isRecord(value) && !("type" in value) && !("command" in value) && !("url" in value);
10445
+ }
10446
+ function usesV2OpencodeMcpShape(config) {
10447
+ return isRecord(config.mcp) && isV2ServerMap(config.mcp.servers);
10448
+ }
10449
+ /** Find every `codemem` MCP entry in the config, V1 first. */
10450
+ function locateOpencodeMcpEntries(config) {
10451
+ const mcp = config.mcp;
10452
+ if (!isRecord(mcp)) return [];
10453
+ const found = [];
10454
+ if ("codemem" in mcp) found.push({
10455
+ shape: "v1",
10456
+ container: mcp,
10457
+ label: "mcp.codemem"
10458
+ });
10459
+ const servers = mcp.servers;
10460
+ if (isV2ServerMap(servers) && "codemem" in servers) found.push({
10461
+ shape: "v2",
10462
+ container: servers,
10463
+ label: "mcp.servers.codemem"
10464
+ });
10465
+ return found;
10466
+ }
10467
+ /**
10468
+ * Explain why an entry is not one setup manages, or return null when it is.
10469
+ * The reason completes the sentence "Left <entry> in place because ...".
10470
+ */
10471
+ function describeUnmanagedOpencodeMcpEntry(entry) {
10472
+ if (!isRecord(entry)) return "it is not an object";
10473
+ if (entry.type === "remote") return "it points to a remote server";
10474
+ if (entry.type !== void 0 && entry.type !== "local") return `it uses type ${JSON.stringify(entry.type)}`;
10475
+ if ("environment" in entry) return "it sets environment variables";
10476
+ if ("cwd" in entry) return "it sets a working directory";
10477
+ if (!isManagedOpencodeMcpCommand(entry.command)) return "it runs a custom command";
10478
+ const extraFields = Object.keys(entry).filter((key) => !MANAGED_FIELDS.has(key));
10479
+ if (extraFields.length > 0) return `it sets ${extraFields.join(", ")}`;
10480
+ return null;
10481
+ }
10482
+ function dropEmptyContainers(config, cleanup, { canDropEmptyContainer }) {
10483
+ const mcp = config.mcp;
10484
+ if (!isRecord(mcp)) return;
10485
+ const removedV2 = cleanup.removed.includes("mcp.servers.codemem");
10486
+ const servers = mcp.servers;
10487
+ if (removedV2 && isRecord(servers) && Object.keys(servers).length === 0 && canDropEmptyContainer(V2_CONTAINER_PATH)) delete mcp.servers;
10488
+ if (Object.keys(mcp).length === 0 && canDropEmptyContainer(V1_CONTAINER_PATH)) delete config.mcp;
10489
+ }
10490
+ /** Deep-copy the parts of the config this module may edit. */
10491
+ function cloneMcpContainers(config) {
10492
+ if (!isRecord(config.mcp)) return { ...config };
10493
+ const mcp = { ...config.mcp };
10494
+ if (isV2ServerMap(mcp.servers)) mcp.servers = { ...mcp.servers };
10495
+ return {
10496
+ ...config,
10497
+ mcp
10498
+ };
10499
+ }
10500
+ /**
10501
+ * Remove managed codemem MCP entries from both config shapes. Returns a new
10502
+ * config; the input is not mutated. Containers emptied by the removal are
10503
+ * deleted only when they held nothing but the codemem entry and the caller
10504
+ * allows it.
10505
+ */
10506
+ function removeManagedOpencodeMcp(config, options) {
10507
+ const next = cloneMcpContainers(config);
10508
+ const cleanup = {
10509
+ config: next,
10510
+ removed: [],
10511
+ kept: []
10512
+ };
10513
+ for (const location of locateOpencodeMcpEntries(next)) {
10514
+ const reason = describeUnmanagedOpencodeMcpEntry(location.container.codemem);
10515
+ if (reason != null) {
10516
+ cleanup.kept.push({
10517
+ label: location.label,
10518
+ reason
10519
+ });
10520
+ continue;
10521
+ }
10522
+ delete location.container.codemem;
10523
+ cleanup.removed.push(location.label);
10524
+ }
10525
+ if (cleanup.removed.length > 0) dropEmptyContainers(next, cleanup, options);
10526
+ return cleanup;
10527
+ }
10528
+ /** The stdio entry `--opencode-mcp stdio` writes, in the file's config shape. */
10529
+ function buildOpencodeStdioMcpEntry(shape, launcher) {
10530
+ const command = [launcher.command, ...launcher.args];
10531
+ if (shape === "v2") return {
10532
+ type: "local",
10533
+ command
10534
+ };
10535
+ return {
10536
+ type: "local",
10537
+ command,
10538
+ enabled: true
10539
+ };
10540
+ }
10541
+ //#endregion
9924
10542
  //#region src/commands/setup.ts
9925
10543
  /**
9926
10544
  * codemem setup — one-command installation for OpenCode plugin + MCP config.
@@ -9929,7 +10547,9 @@ function writeJsonConfigWithBackup(path, data) {
9929
10547
  *
9930
10548
  * What it does:
9931
10549
  * 1. Adds "@codemem/opencode-plugin" to the plugin array in ~/.config/opencode/opencode.jsonc
9932
- * 2. Adds/updates the MCP entry in ~/.config/opencode/opencode.jsonc
10550
+ * 2. Writes the per-project OpenCode stdio MCP entry (--opencode-mcp stdio). Removal
10551
+ * of that entry for the plugin's built-in tools is implemented but not offered
10552
+ * until a plugin release ships those tools.
9933
10553
  * 3. For Claude Code: installs MCP config and guides marketplace plugin install
9934
10554
  * 4. For Codex: MCP + hooks via CODEX_HOME
9935
10555
  * 5. For pi: packages entry + observer derivation + optional MCP adapter surface
@@ -9981,34 +10601,27 @@ function migrateLegacyOpencodePlugin() {
9981
10601
  function isExactStringArray(value, expected) {
9982
10602
  return Array.isArray(value) && value.length === expected.length && value.every((entry, index) => entry === expected[index]);
9983
10603
  }
9984
- /** Detect and upgrade legacy uvx/uv or managed single-package MCP entries in OpenCode config. */
10604
+ /**
10605
+ * Detect and upgrade legacy uvx/uv or managed single-package MCP entries in
10606
+ * OpenCode config, in either the V1 (`mcp.codemem`) or V2
10607
+ * (`mcp.servers.codemem`) shape. Used only by `--opencode-mcp stdio`.
10608
+ */
9985
10609
  function migrateLegacyOpencodeMcp(config, { launcher } = {}) {
9986
- const mcpConfig = config.mcp;
9987
- if (!mcpConfig || typeof mcpConfig !== "object") return false;
9988
- const entry = mcpConfig.codemem;
9989
- if (!entry || typeof entry !== "object") return false;
9990
- const command = entry.command;
9991
- const isLegacyUv = Array.isArray(command) && command.some((arg) => typeof arg === "string" && (arg === "uvx" || arg === "uv")) || typeof command === "string" && (command === "uvx" || command === "uv");
9992
- const isManagedSinglePackageNpx = isExactStringArray(command, [
9993
- "npx",
9994
- "-y",
9995
- "codemem",
9996
- "mcp"
9997
- ]) || isExactStringArray(command, [
9998
- "npx",
9999
- "codemem",
10000
- "mcp"
10001
- ]);
10002
- if (isLegacyUv || isManagedSinglePackageNpx) {
10610
+ let migrated = false;
10611
+ for (const { container } of locateOpencodeMcpEntries(config)) {
10612
+ const entry = container.codemem;
10613
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
10614
+ const command = entry.command;
10615
+ if (!isLegacyUvOpencodeCommand(command) && !isSinglePackageNpxOpencodeCommand(command)) continue;
10003
10616
  p.log.step("Upgrading managed MCP entry to the current npm launcher");
10004
10617
  const resolvedLauncher = launcher ?? codememMcpLauncher();
10005
- mcpConfig.codemem = {
10618
+ container.codemem = {
10006
10619
  ...entry,
10007
10620
  command: [resolvedLauncher.command, ...resolvedLauncher.args]
10008
10621
  };
10009
- return true;
10622
+ migrated = true;
10010
10623
  }
10011
- return false;
10624
+ return migrated;
10012
10625
  }
10013
10626
  /** Detect and upgrade legacy uvx or managed single-package MCP entries in Claude settings. */
10014
10627
  function migrateLegacyClaudeMcp(settings, { launcher } = {}) {
@@ -10073,30 +10686,34 @@ function installPlugin(force) {
10073
10686
  };
10074
10687
  }
10075
10688
  }
10076
- function installMcp(force, { createBackup = true } = {}) {
10077
- const configPath = resolveOpencodeConfigPath(opencodeConfigDir());
10078
- let config;
10689
+ function loadOpencodeConfigOrLog(configPath) {
10079
10690
  try {
10080
- config = loadJsoncConfig(configPath);
10691
+ return loadJsoncConfig(configPath);
10081
10692
  } catch (err) {
10082
10693
  p.log.error(`Failed to parse ${configPath}: ${err instanceof Error ? err.message : String(err)}`);
10083
- return false;
10694
+ return null;
10084
10695
  }
10085
- let mcpConfig = config.mcp;
10086
- if (mcpConfig == null || typeof mcpConfig !== "object" || Array.isArray(mcpConfig)) mcpConfig = {};
10696
+ }
10697
+ /** Container for a new stdio entry: `mcp.servers` when the file already uses it. */
10698
+ function opencodeStdioContainer(config) {
10699
+ const mcp = config.mcp != null && typeof config.mcp === "object" && !Array.isArray(config.mcp) ? config.mcp : {};
10700
+ config.mcp = mcp;
10701
+ if (!usesV2OpencodeMcpShape(config)) return mcp;
10702
+ return mcp.servers;
10703
+ }
10704
+ /** `--opencode-mcp stdio`: write the per-project stdio MCP entry as setup used to. */
10705
+ function installStdioMcp(force, { createBackup = true } = {}) {
10706
+ const configPath = resolveOpencodeConfigPath(opencodeConfigDir());
10707
+ const config = loadOpencodeConfigOrLog(configPath);
10708
+ if (config == null) return false;
10087
10709
  const migrated = migrateLegacyOpencodeMcp(config);
10088
- if ("codemem" in mcpConfig && !force && !migrated) {
10710
+ if (locateOpencodeMcpEntries(config).length > 0 && !force && !migrated) {
10089
10711
  p.log.info(`MCP entry already exists in ${configPath}`);
10090
10712
  return true;
10091
10713
  }
10092
10714
  if (!migrated) {
10093
- const launcher = codememMcpLauncher();
10094
- mcpConfig.codemem = {
10095
- type: "local",
10096
- command: [launcher.command, ...launcher.args],
10097
- enabled: true
10098
- };
10099
- config.mcp = mcpConfig;
10715
+ const shape = usesV2OpencodeMcpShape(config) ? "v2" : "v1";
10716
+ opencodeStdioContainer(config).codemem = buildOpencodeStdioMcpEntry(shape, codememMcpLauncher());
10100
10717
  }
10101
10718
  try {
10102
10719
  writeJsonConfig(configPath, config, { createBackup });
@@ -10107,6 +10724,35 @@ function installMcp(force, { createBackup = true } = {}) {
10107
10724
  }
10108
10725
  return true;
10109
10726
  }
10727
+ function reportKeptOpencodeMcpEntries(configPath, kept) {
10728
+ for (const { label, reason } of kept) p.log.warn(`Left the codemem MCP entry ${label} in ${configPath} because ${reason}. The plugin now provides memory tools, so remove that entry unless you still need it.`);
10729
+ }
10730
+ /**
10731
+ * Remove the stdio entries setup wrote, for users of the plugin's built-in
10732
+ * memory tools (served through the shared viewer). Reached only through the
10733
+ * internal `native` mode, which the CLI accepts once the plugin ships those tools.
10734
+ */
10735
+ function removeOpencodeMcp({ createBackup = true } = {}) {
10736
+ const configPath = resolveOpencodeConfigPath(opencodeConfigDir());
10737
+ const config = loadOpencodeConfigOrLog(configPath);
10738
+ if (config == null) return false;
10739
+ const raw = existsSync(configPath) ? readFileSync(configPath, "utf-8") : "{}";
10740
+ const cleanup = removeManagedOpencodeMcp(config, { canDropEmptyContainer: (path) => !jsoncValueHasComments(raw, path) });
10741
+ reportKeptOpencodeMcpEntries(configPath, cleanup.kept);
10742
+ if (cleanup.removed.length === 0) {
10743
+ if (cleanup.kept.length === 0) p.log.info("No codemem MCP entry to remove; the plugin's built-in memory tools are used");
10744
+ return true;
10745
+ }
10746
+ try {
10747
+ writeJsonConfig(configPath, cleanup.config, { createBackup });
10748
+ } catch (err) {
10749
+ p.log.error(`Failed to write ${configPath}: ${err instanceof Error ? err.message : String(err)}`);
10750
+ return false;
10751
+ }
10752
+ p.log.success(`Removed the codemem MCP entry ${cleanup.removed.join(" and ")} from ${configPath} (backup: ${configPath}.codemem.bak)`);
10753
+ p.log.info("OpenCode no longer starts a codemem MCP process for each project; the codemem plugin provides the memory tools. Run setup with --opencode-mcp stdio to restore the entry.");
10754
+ return true;
10755
+ }
10110
10756
  function isClaudeHooksPluginInstalled() {
10111
10757
  const pluginDir = join(claudeConfigDir(), "plugins", "codemem");
10112
10758
  if (existsSync(pluginDir)) return true;
@@ -10809,6 +11455,8 @@ function installPi(options = {}) {
10809
11455
  }
10810
11456
  return ok;
10811
11457
  }
11458
+ var OPENCODE_MCP_MODES = ["stdio"];
11459
+ var DEFAULT_OPENCODE_MCP_MODE = "stdio";
10812
11460
  function maybeInstallPi(opts, onlyFlag, force) {
10813
11461
  if (!(opts.piOnly || !onlyFlag && isPiDetected())) return true;
10814
11462
  p.log.step("Configuring pi (extension package + observer)...");
@@ -10818,11 +11466,17 @@ function maybeInstallPi(opts, onlyFlag, force) {
10818
11466
  piExtensionPath: opts.piExtensionPath
10819
11467
  });
10820
11468
  }
10821
- function installOpencodeSetup(force) {
11469
+ function installOpencodeSetup(force, opencodeMcp) {
10822
11470
  p.log.step("Installing OpenCode plugin...");
10823
11471
  const pluginResult = installPlugin(force);
11472
+ if (!pluginResult.ok) return false;
11473
+ const createBackup = !pluginResult.wrote;
11474
+ if ((opencodeMcp ?? DEFAULT_OPENCODE_MCP_MODE) === "native") {
11475
+ p.log.step("Checking OpenCode MCP config...");
11476
+ return removeOpencodeMcp({ createBackup });
11477
+ }
10824
11478
  p.log.step("Installing OpenCode MCP config...");
10825
- return pluginResult.ok && installMcp(force, { createBackup: !pluginResult.wrote });
11479
+ return installStdioMcp(force, { createBackup });
10826
11480
  }
10827
11481
  function installClaudeSetup(force) {
10828
11482
  p.log.step("Installing Claude Code MCP config...");
@@ -10840,12 +11494,20 @@ function installCodexSetup(force) {
10840
11494
  function runSetupInstalls(opts, force) {
10841
11495
  const onlyFlag = Boolean(opts.opencodeOnly || opts.claudeOnly || opts.codexOnly || opts.piOnly);
10842
11496
  let ok = true;
10843
- if (opts.opencodeOnly || !onlyFlag) ok = installOpencodeSetup(force) && ok;
11497
+ if (opts.opencodeOnly || !onlyFlag) ok = installOpencodeSetup(force, opts.opencodeMcp) && ok;
10844
11498
  if (opts.claudeOnly || !onlyFlag) ok = installClaudeSetup(force) && ok;
10845
11499
  if (opts.codexOnly || !onlyFlag && existsSync(codexConfigDir())) ok = installCodexSetup(force) && ok;
10846
11500
  return maybeInstallPi(opts, onlyFlag, force) && ok;
10847
11501
  }
11502
+ function isKnownOpencodeMcpMode(mode) {
11503
+ return mode === void 0 || OPENCODE_MCP_MODES.includes(mode);
11504
+ }
10848
11505
  function runSetup(opts) {
11506
+ if (!isKnownOpencodeMcpMode(opts.opencodeMcp)) {
11507
+ p.log.error(`Unknown --opencode-mcp mode "${opts.opencodeMcp}". Supported: ${OPENCODE_MCP_MODES.join(", ")}`);
11508
+ process.exitCode = 2;
11509
+ return;
11510
+ }
10849
11511
  p.intro(`codemem setup v${VERSION}`);
10850
11512
  if (runSetupInstalls(opts, opts.force ?? false)) {
10851
11513
  p.outro("Setup complete — restart your editor to load the plugin");
@@ -10854,7 +11516,7 @@ function runSetup(opts) {
10854
11516
  p.outro("Setup completed with warnings");
10855
11517
  process.exitCode = 1;
10856
11518
  }
10857
- var setupCommand = new Command("setup").configureHelp(helpStyle).description("Install codemem plugin + MCP config for OpenCode, Claude Code, Codex, and pi").option("--force", "overwrite existing installations").option("--opencode-only", "only install for OpenCode").option("--claude-only", "only install for Claude Code").option("--codex-only", "only install for Codex").option("--pi-only", "only install for pi").option("--pi-mcp", "opt into pi MCP adapter surface (requires pi-mcp-adapter)").option("--pi-extension-path <path>", "dev: write a local path packages entry instead of the npm pin").action((opts) => {
11519
+ var setupCommand = new Command("setup").configureHelp(helpStyle).description("Install codemem plugin + MCP config for OpenCode, Claude Code, Codex, and pi").option("--force", "overwrite existing installations").option("--opencode-only", "only install for OpenCode").option("--claude-only", "only install for Claude Code").option("--codex-only", "only install for Codex").option("--pi-only", "only install for pi").option("--opencode-mcp <mode>", "OpenCode memory tools: stdio (per-project MCP entry, the default and only mode)").option("--pi-mcp", "opt into pi MCP adapter surface (requires pi-mcp-adapter)").option("--pi-extension-path <path>", "dev: write a local path packages entry instead of the npm pin").action((opts) => {
10858
11520
  runSetup(opts);
10859
11521
  });
10860
11522
  //#endregion
@@ -11327,6 +11989,169 @@ function collectAdvertiseAddresses(explicitAddress, configuredHost, port, interf
11327
11989
  return [...new Set(addresses)];
11328
11990
  }
11329
11991
  //#endregion
11992
+ //#region src/commands/sync-relay-keys.ts
11993
+ /**
11994
+ * `codemem sync relay-keys` lists relay service key pins, and `codemem sync approve-relay-key` approves a changed key.
11995
+ */
11996
+ /** Expected refusal with a stable error code and exit status. */
11997
+ var RelayKeyRefusal = class extends Error {
11998
+ code;
11999
+ exitCode;
12000
+ constructor(code, message, exitCode = 1) {
12001
+ super(message);
12002
+ this.code = code;
12003
+ this.exitCode = exitCode;
12004
+ }
12005
+ };
12006
+ function pinJson(pin) {
12007
+ return {
12008
+ coordinator_id: pin.coordinatorId,
12009
+ group_id: pin.groupId,
12010
+ state: pin.state,
12011
+ pinned_key: pin.pinnedKey,
12012
+ first_seen_at: pin.firstSeenAt,
12013
+ candidate_key: pin.candidateKey,
12014
+ candidate_seen_at: pin.candidateSeenAt,
12015
+ last_candidate_key: pin.lastCandidateKey,
12016
+ last_candidate_seen_at: pin.lastCandidateSeenAt
12017
+ };
12018
+ }
12019
+ function pinText(pin) {
12020
+ const lines = [
12021
+ `${pin.groupId} (${pin.coordinatorId})`,
12022
+ ` state: ${pin.state === "pending_change" ? "paused, key change pending approval" : "pinned"}`,
12023
+ ` pinned key: ${pin.pinnedKey} (since ${pin.firstSeenAt})`
12024
+ ];
12025
+ if (pin.candidateKey) lines.push(` candidate: ${pin.candidateKey} (seen ${pin.candidateSeenAt})`);
12026
+ if (pin.lastCandidateKey) lines.push(` last candidate: ${pin.lastCandidateKey} (seen ${pin.lastCandidateSeenAt}, not approved)`);
12027
+ return lines.join("\n");
12028
+ }
12029
+ function withStore(opts, run) {
12030
+ const store = new MemoryStore(resolveDbPath(resolveDbOpt(opts)));
12031
+ try {
12032
+ return run(store.db);
12033
+ } finally {
12034
+ store.close();
12035
+ }
12036
+ }
12037
+ function reportFailure(opts, error) {
12038
+ const refusal = error instanceof RelayKeyRefusal ? error : new RelayKeyRefusal("relay_keys_failed", error instanceof Error ? error.message : String(error));
12039
+ if (opts.json) {
12040
+ emitJsonError(refusal.code, refusal.message, refusal.exitCode);
12041
+ return;
12042
+ }
12043
+ p.log.error(refusal.message);
12044
+ process.exitCode = refusal.exitCode;
12045
+ }
12046
+ function listPins(opts) {
12047
+ const pins = withStore(opts, listRelayServicePins);
12048
+ if (opts.json) {
12049
+ console.log(JSON.stringify(pins.map(pinJson), null, 2));
12050
+ return;
12051
+ }
12052
+ p.intro("codemem sync relay-keys");
12053
+ if (pins.length === 0) {
12054
+ p.outro("No relay service keys pinned");
12055
+ return;
12056
+ }
12057
+ for (const pin of pins) p.log.message(pinText(pin));
12058
+ const pending = pins.filter((pin) => pin.state === "pending_change").length;
12059
+ p.outro(`${pins.length} pin(s), ${pending} pending approval`);
12060
+ }
12061
+ function configuredCoordinatorId(configPath) {
12062
+ const config = configPath ? readCodememConfigFileAtPath(configPath) : readCodememConfigFile();
12063
+ const endpoint = relayCoordinatorEndpoint(readCoordinatorSyncConfig(config).syncCoordinatorUrl);
12064
+ if (!endpoint) throw new RelayKeyRefusal("coordinator_not_configured", "Relay needs sync_coordinator_url set to an https:// origin with no path.");
12065
+ return endpoint.coordinatorId;
12066
+ }
12067
+ function pendingPin(db, coordinatorId, groupId) {
12068
+ const pin = readRelayServicePin(db, coordinatorId, groupId);
12069
+ if (pin?.state !== "pending_change" || !pin.candidateKey) throw new RelayKeyRefusal("nothing_pending", `No relay service key change is pending for group ${groupId}.`);
12070
+ return {
12071
+ ...pin,
12072
+ candidateKey: pin.candidateKey
12073
+ };
12074
+ }
12075
+ function keysText(pin) {
12076
+ return `pinned key: ${pin.pinnedKey}\ncandidate: ${pin.candidateKey}`;
12077
+ }
12078
+ /** The candidate the user approved: `--key`, or the shown candidate after an interactive confirmation. */
12079
+ async function chosenCandidate(pin, opts) {
12080
+ if (opts.key !== void 0) {
12081
+ const key = canonicalRelayServiceKey(opts.key);
12082
+ if (!key) throw new RelayKeyRefusal("invalid_key", "--key is not an ssh-ed25519 key.", 2);
12083
+ if (key !== pin.candidateKey) throw new RelayKeyRefusal("candidate_mismatch", `--key does not match the pending candidate. Nothing changed.\n${keysText(pin)}`);
12084
+ return key;
12085
+ }
12086
+ if (opts.json || !process.stdin.isTTY || !process.stderr.isTTY) throw new RelayKeyRefusal("key_required", `Pass the candidate with --key to approve it without a prompt.\n${keysText(pin)}`, 2);
12087
+ p.log.message(keysText(pin), { output: process.stderr });
12088
+ return await p.confirm({
12089
+ message: "Trust the candidate relay service key? Check it with your coordinator operator first.",
12090
+ initialValue: false,
12091
+ output: process.stderr
12092
+ }) === true ? pin.candidateKey : null;
12093
+ }
12094
+ async function approvePin(groupId, opts) {
12095
+ const coordinatorId = configuredCoordinatorId(opts.config);
12096
+ const store = new MemoryStore(resolveDbPath(resolveDbOpt(opts)));
12097
+ try {
12098
+ const pin = pendingPin(store.db, coordinatorId, groupId);
12099
+ const candidateKey = await chosenCandidate(pin, opts);
12100
+ if (!candidateKey) {
12101
+ p.log.info("Nothing changed.", { output: process.stderr });
12102
+ return;
12103
+ }
12104
+ if (!approveRelayServiceKey(store.db, {
12105
+ coordinatorId,
12106
+ groupId,
12107
+ candidateKey
12108
+ })) throw new RelayKeyRefusal("candidate_changed", "The pending candidate changed. Nothing changed; list the pins again.");
12109
+ reportApproved(opts, {
12110
+ coordinatorId,
12111
+ groupId,
12112
+ previousKey: pin.pinnedKey,
12113
+ candidateKey
12114
+ });
12115
+ } finally {
12116
+ store.close();
12117
+ }
12118
+ }
12119
+ function reportApproved(opts, result) {
12120
+ if (opts.json) {
12121
+ console.log(JSON.stringify({
12122
+ ok: true,
12123
+ coordinator_id: result.coordinatorId,
12124
+ group_id: result.groupId,
12125
+ pinned_key: result.candidateKey,
12126
+ previous_key: result.previousKey
12127
+ }, null, 2));
12128
+ return;
12129
+ }
12130
+ p.log.success(`Pinned ${result.candidateKey} for group ${result.groupId}`);
12131
+ p.log.info("A running viewer resumes relay for this group after its next coordinator refresh.");
12132
+ }
12133
+ var relayKeysCommand = new Command("relay-keys").configureHelp(helpStyle).description("List relay service key pins");
12134
+ addDbOption(relayKeysCommand);
12135
+ addJsonOption(relayKeysCommand);
12136
+ relayKeysCommand.action((opts) => {
12137
+ try {
12138
+ listPins(opts);
12139
+ } catch (error) {
12140
+ reportFailure(opts, error);
12141
+ }
12142
+ });
12143
+ var approveRelayKeyCommand = new Command("approve-relay-key").configureHelp(helpStyle).description("Approve a changed relay service key for a group").argument("<group>", "coordinator group id").option("--key <candidate>", "the pending candidate key, exactly as listed");
12144
+ addDbOption(approveRelayKeyCommand);
12145
+ addConfigOption(approveRelayKeyCommand);
12146
+ addJsonOption(approveRelayKeyCommand);
12147
+ approveRelayKeyCommand.action(async (groupId, opts) => {
12148
+ try {
12149
+ await approvePin(groupId, opts);
12150
+ } catch (error) {
12151
+ reportFailure(opts, error);
12152
+ }
12153
+ });
12154
+ //#endregion
11330
12155
  //#region src/commands/sync.ts
11331
12156
  /**
11332
12157
  * Sync CLI commands — enable/disable/status/peers/connect.
@@ -12126,6 +12951,8 @@ peersRemoveCmd.action((peerRef, opts) => {
12126
12951
  });
12127
12952
  peersCommand.addCommand(peersRemoveCmd);
12128
12953
  syncCommand.addCommand(peersCommand);
12954
+ syncCommand.addCommand(relayKeysCommand);
12955
+ syncCommand.addCommand(approveRelayKeyCommand);
12129
12956
  var bootstrapCmd = new Command("bootstrap").configureHelp(helpStyle).description("Fast-bootstrap memories from a peer (full snapshot transfer)").argument("[peer-device-id]", "peer device ID to bootstrap from").option("--bootstrap-grant <grant-id>", "bootstrap grant id for seed-authorized bootstrap").option("--page-size <n>", "items per snapshot page (default: 2000)", "2000").option("--keys-dir <path>", "keys directory").option("--force", "skip dirty-local-state safety check");
12130
12957
  addDbOption(bootstrapCmd);
12131
12958
  addJsonOption(bootstrapCmd);
@@ -13209,6 +14036,7 @@ function registerRootCommands(program) {
13209
14036
  program.addCommand(piSessionSearchCommand);
13210
14037
  program.addCommand(piImportSessionsCommand);
13211
14038
  program.addCommand(promptPackLedgerCommand, { hidden: true });
14039
+ program.addCommand(memoryToolCommand, { hidden: true });
13212
14040
  program.addCommand(showMemoryCommand, { hidden: true });
13213
14041
  program.addCommand(forgetMemoryCommand, { hidden: true });
13214
14042
  program.addCommand(rememberMemoryCommand, { hidden: true });