codemem 0.47.5 → 0.48.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,20 +1,253 @@
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
- import { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
5
+ import { isUtf8 } from "node:buffer";
6
+ import { createHash, randomInt, randomUUID } from "node:crypto";
7
+ import { appendFileSync, constants, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
8
+ import { lstat, mkdir, open, readFile, readdir, stat, unlink } from "node:fs/promises";
6
9
  import { homedir, networkInterfaces } from "node:os";
7
10
  import { dirname, isAbsolute, join, posix, relative, resolve, sep, win32 } from "node:path";
8
11
  import { isDeepStrictEqual, styleText } from "node:util";
9
- import { randomInt, randomUUID } from "node:crypto";
10
12
  import * as p from "@clack/prompts";
11
13
  import { serve } from "@hono/node-server";
12
14
  import { execFileSync, spawn, spawnSync } from "node:child_process";
13
15
  import net from "node:net";
16
+ import { createInterface } from "node:readline";
14
17
  import { applyEdits, createScanner, findNodeAtLocation, modify, parse, parseTree, printParseErrorCode } from "jsonc-parser";
15
18
  import { desc, eq } from "drizzle-orm";
16
19
  import { drizzle } from "drizzle-orm/better-sqlite3";
17
- import { mkdir, open, readFile, stat, unlink } from "node:fs/promises";
20
+ import { approveRelayServiceKey, canonicalRelayServiceKey, listRelayServicePins, readRelayServicePin, relayCoordinatorEndpoint } from "@codemem/core/internal/relay-runtime";
21
+ //#region ../opencode-plugin/.opencode/lib/raw-event-spool.js
22
+ var MAX_REJECTED_RAW_EVENT_INSPECTION_BYTES = 16777216;
23
+ var INSPECTION_READ_CHUNK_BYTES = 65536;
24
+ var RAW_EVENT_SPOOL_CONFLICT_CODE = "raw_event_spool_conflict";
25
+ var SPOOL_DIRECTORY_NAME = "opencode-raw-event-spool";
26
+ var resolveSpoolDirectory = (homeDir = homedir()) => join(homeDir, ".codemem", SPOOL_DIRECTORY_NAME);
27
+ var spoolFilename = (eventId) => {
28
+ return `${createHash("sha256").update(String(eventId)).digest("hex")}.json`;
29
+ };
30
+ var rejectedReasons = /* @__PURE__ */ new Map([[400, "invalid_payload"], [413, "payload_too_large"]]);
31
+ var parseRejectedFilename = (name) => {
32
+ const match = /^rejected-([a-f0-9]{64})-(400|413)-(invalid_payload|payload_too_large)\.json$/.exec(name);
33
+ if (!match) return null;
34
+ const status = Number(match[2]);
35
+ if (rejectedReasons.get(status) !== match[3]) return null;
36
+ return {
37
+ digest: match[1],
38
+ status,
39
+ reason: match[3]
40
+ };
41
+ };
42
+ var requirePrivateSpoolDirectory = async (directory) => {
43
+ for (const path of [dirname(directory), directory]) {
44
+ const details = await lstat(path);
45
+ if (!details.isDirectory() || details.isSymbolicLink()) throw new Error("raw event spool requires a real directory");
46
+ }
47
+ };
48
+ var readRegularSpoolFile = async (path, { makePrivate = false } = {}) => {
49
+ const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
50
+ try {
51
+ const details = await handle.stat();
52
+ if (!details.isFile()) throw new Error("raw event spool requires a regular file");
53
+ const bytes = await handle.readFile();
54
+ if (!isUtf8(bytes)) throw new Error("raw event spool requires UTF-8 JSON");
55
+ const serialized = bytes.toString("utf8");
56
+ if (makePrivate) {
57
+ await handle.chmod(384);
58
+ await handle.sync();
59
+ }
60
+ return {
61
+ serialized,
62
+ details
63
+ };
64
+ } finally {
65
+ await handle.close();
66
+ }
67
+ };
68
+ var requireMatchingIdentity = (serialized, filename) => {
69
+ let envelope;
70
+ try {
71
+ envelope = JSON.parse(serialized);
72
+ } catch (error) {
73
+ error.spoolConflict = {
74
+ branch: "rejected_identity",
75
+ reason: "invalid_json"
76
+ };
77
+ throw error;
78
+ }
79
+ let eventId;
80
+ try {
81
+ eventId = requireEventId(envelope);
82
+ } catch (error) {
83
+ error.spoolConflict = {
84
+ branch: "rejected_identity",
85
+ reason: "invalid_shape"
86
+ };
87
+ throw error;
88
+ }
89
+ if (spoolFilename(eventId) !== filename) throw conflictingEntry({
90
+ branch: "rejected_identity",
91
+ reason: "identity_mismatch"
92
+ });
93
+ };
94
+ var rejectedMetadata = (name, entry, bytes) => ({
95
+ receipt: name,
96
+ bytes,
97
+ status: entry.status,
98
+ reason: entry.reason
99
+ });
100
+ var requireEventId = (envelope) => {
101
+ const eventId = typeof envelope?.event_id === "string" ? envelope.event_id.trim() : "";
102
+ if (!eventId) throw new Error("raw event spool requires event_id");
103
+ return eventId;
104
+ };
105
+ var conflictingEntry = (diagnostic) => {
106
+ const error = /* @__PURE__ */ new Error("raw event spool entry conflicts with existing event_id");
107
+ error.code = RAW_EVENT_SPOOL_CONFLICT_CODE;
108
+ if (diagnostic) error.spoolConflict = diagnostic;
109
+ return error;
110
+ };
111
+ var RawEventSpoolInspectionError = class extends Error {
112
+ constructor(code, message) {
113
+ super(message);
114
+ this.name = "RawEventSpoolInspectionError";
115
+ this.code = code;
116
+ }
117
+ };
118
+ var inspectionFailure = () => new RawEventSpoolInspectionError("inspection_failed", "Could not inspect retained events. Files were left untouched.");
119
+ var requireInspectionRegularFile = (details) => {
120
+ if (!details.isFile() || details.isSymbolicLink()) throw new RawEventSpoolInspectionError("unsafe_entry", "Receipt must name a regular file.");
121
+ };
122
+ var openRejectedEntryForInspection = async (path) => {
123
+ const expected = await lstat(path);
124
+ requireInspectionRegularFile(expected);
125
+ const flags = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
126
+ const handle = await open(path, flags);
127
+ try {
128
+ for (const actual of [await handle.stat(), await lstat(path)]) {
129
+ requireInspectionRegularFile(actual);
130
+ if (actual.dev !== expected.dev || actual.ino !== expected.ino) throw new RawEventSpoolInspectionError("unsafe_entry", "Receipt changed while opening. Retry inspection.");
131
+ }
132
+ return handle;
133
+ } catch (error) {
134
+ await handle.close().catch(() => {});
135
+ throw error;
136
+ }
137
+ };
138
+ var readWithinInspectionLimit = async (handle, maxBytes, { position = null } = {}) => {
139
+ const chunks = [];
140
+ let total = 0;
141
+ while (total <= maxBytes) {
142
+ const buffer = Buffer.alloc(Math.min(INSPECTION_READ_CHUNK_BYTES, maxBytes + 1 - total));
143
+ const offset = position === null ? null : position + total;
144
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, offset);
145
+ if (bytesRead === 0) return Buffer.concat(chunks, total);
146
+ total += bytesRead;
147
+ if (total > maxBytes) return null;
148
+ chunks.push(buffer.subarray(0, bytesRead));
149
+ }
150
+ return null;
151
+ };
152
+ var inspectOpenedRejectedEntry = async (handle, receipt, entry, maxBytes) => {
153
+ const before = await handle.stat();
154
+ requireInspectionRegularFile(before);
155
+ const metadata = rejectedMetadata(receipt, entry, before.size);
156
+ if (before.size > maxBytes) return {
157
+ ...metadata,
158
+ validation: "read_limit_exceeded"
159
+ };
160
+ const bytes = await readWithinInspectionLimit(handle, maxBytes);
161
+ const after = await handle.stat();
162
+ if (!bytes || after.size > maxBytes) return {
163
+ ...metadata,
164
+ bytes: after.size,
165
+ validation: "read_limit_exceeded"
166
+ };
167
+ if (before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) return {
168
+ ...metadata,
169
+ validation: "changed_during_read"
170
+ };
171
+ try {
172
+ if (!isUtf8(bytes)) return {
173
+ ...metadata,
174
+ validation: "invalid"
175
+ };
176
+ const serialized = bytes.toString("utf8");
177
+ requireMatchingIdentity(serialized, `${entry.digest}.json`);
178
+ return {
179
+ ...metadata,
180
+ validation: "valid",
181
+ serialized
182
+ };
183
+ } catch {
184
+ return {
185
+ ...metadata,
186
+ validation: "invalid"
187
+ };
188
+ }
189
+ };
190
+ var inspectRejectedRawEventSpoolEntry = async ({ receipt, homeDir = homedir(), maxBytes = MAX_REJECTED_RAW_EVENT_INSPECTION_BYTES }) => {
191
+ const entry = typeof receipt === "string" ? parseRejectedFilename(receipt) : null;
192
+ if (!entry) throw new RawEventSpoolInspectionError("invalid_receipt", "Use a receipt from capture list-rejected.");
193
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 16777216) throw new RawEventSpoolInspectionError("invalid_limit", "Inspection limit must be between 1 byte and 16 MiB.");
194
+ let handle;
195
+ try {
196
+ const directory = resolveSpoolDirectory(homeDir);
197
+ await requirePrivateSpoolDirectory(directory);
198
+ handle = await openRejectedEntryForInspection(join(directory, receipt));
199
+ return await inspectOpenedRejectedEntry(handle, receipt, entry, maxBytes);
200
+ } catch (error) {
201
+ if (error instanceof RawEventSpoolInspectionError) throw error;
202
+ if (error?.code === "ENOENT") throw new RawEventSpoolInspectionError("receipt_not_found", "Retained receipt was not found. Run capture list-rejected again.");
203
+ throw inspectionFailure();
204
+ } finally {
205
+ await handle?.close().catch(() => {});
206
+ }
207
+ };
208
+ var listRejectedEntries = async ({ homeDir, validation }) => {
209
+ const directory = resolveSpoolDirectory(homeDir);
210
+ let names;
211
+ try {
212
+ await requirePrivateSpoolDirectory(directory);
213
+ names = await readdir(directory, { withFileTypes: true });
214
+ } catch (error) {
215
+ if (error?.code === "ENOENT") return [];
216
+ throw error;
217
+ }
218
+ const entries = [];
219
+ for (const candidate of names) {
220
+ const entry = parseRejectedFilename(candidate.name);
221
+ if (!candidate.isFile() || !entry) continue;
222
+ try {
223
+ if (validation === "metadata") {
224
+ const details = await lstat(join(directory, candidate.name));
225
+ if (details.isFile()) entries.push({
226
+ ...rejectedMetadata(candidate.name, entry, details.size),
227
+ validation: "not_checked"
228
+ });
229
+ continue;
230
+ }
231
+ const retained = await readRegularSpoolFile(join(directory, candidate.name));
232
+ requireMatchingIdentity(retained.serialized, `${entry.digest}.json`);
233
+ entries.push(rejectedMetadata(candidate.name, entry, retained.details.size));
234
+ } catch {}
235
+ }
236
+ return entries.sort((left, right) => left.receipt.localeCompare(right.receipt));
237
+ };
238
+ var listRejectedRawEventSpoolEntries = async ({ homeDir = homedir(), validation = "payload" } = {}) => {
239
+ if (!["metadata", "payload"].includes(validation)) throw new RawEventSpoolInspectionError("invalid_validation", "Unsupported inspection mode.");
240
+ try {
241
+ return await listRejectedEntries({
242
+ homeDir,
243
+ validation
244
+ });
245
+ } catch (error) {
246
+ if (validation === "payload") throw error;
247
+ throw inspectionFailure();
248
+ }
249
+ };
250
+ //#endregion
18
251
  //#region src/help-style.ts
19
252
  /**
20
253
  * Shared Commander help style configuration.
@@ -79,6 +312,106 @@ function emitJsonError(errorCode, message, exitCode = 1) {
79
312
  process.exitCode = exitCode;
80
313
  }
81
314
  //#endregion
315
+ //#region src/commands/capture.ts
316
+ var rejectedEventFormat = {
317
+ name: "opencode-raw-event-v1",
318
+ list: () => listRejectedRawEventSpoolEntries({ validation: "metadata" }),
319
+ inspect: (receipt) => inspectRejectedRawEventSpoolEntry({ receipt })
320
+ };
321
+ function safeJson(value) {
322
+ return JSON.stringify(value).replace(/[\u007f-\u009f\u2028-\u202e\u2066-\u2069]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
323
+ }
324
+ function reportInspectionError(error, opts) {
325
+ let code = "inspection_failed";
326
+ let message = "Could not inspect retained events. Files were left untouched.";
327
+ if (error instanceof RawEventSpoolInspectionError) {
328
+ code = error.code;
329
+ message = error.message;
330
+ }
331
+ process.exitCode = code === "invalid_receipt" ? 2 : 1;
332
+ if (opts.json) {
333
+ process.stdout.write(`${safeJson({
334
+ error: code,
335
+ message
336
+ })}\n`);
337
+ return;
338
+ }
339
+ process.stderr.write(`${message}\n`);
340
+ }
341
+ function printRejectedMetadata(entry) {
342
+ process.stdout.write(`${entry.receipt}\t${entry.bytes} bytes\t${entry.status} ${entry.reason}\t${entry.validation}\n`);
343
+ }
344
+ function rawUnavailableMessage(validation) {
345
+ if (validation === "read_limit_exceeded") return "Raw event text exceeds the 16 MiB inspection limit. The file was left untouched.";
346
+ if (validation === "changed_during_read") return "The file changed while reading. Retry inspection. The file was left untouched.";
347
+ return "Raw event text failed validation. The file was left untouched.";
348
+ }
349
+ async function runListRejected(opts) {
350
+ try {
351
+ const entries = await rejectedEventFormat.list();
352
+ if (opts.json) {
353
+ process.stdout.write(`${safeJson({
354
+ format: rejectedEventFormat.name,
355
+ entries
356
+ })}\n`);
357
+ return;
358
+ }
359
+ if (!entries.length) {
360
+ process.stdout.write("No retained rejected events.\n");
361
+ return;
362
+ }
363
+ for (const entry of entries) printRejectedMetadata(entry);
364
+ } catch (error) {
365
+ reportInspectionError(error, opts);
366
+ }
367
+ }
368
+ async function runShowRejected(receipt, opts) {
369
+ try {
370
+ const entry = await rejectedEventFormat.inspect(receipt);
371
+ const { receipt: name, bytes, status, reason, validation } = entry;
372
+ const result = {
373
+ format: rejectedEventFormat.name,
374
+ receipt: name,
375
+ bytes,
376
+ status,
377
+ reason,
378
+ validation
379
+ };
380
+ if (opts.raw && entry.validation === "valid") {
381
+ process.stdout.write(`${safeJson({
382
+ ...result,
383
+ raw: entry.serialized
384
+ })}\n`);
385
+ return;
386
+ }
387
+ if (opts.raw) {
388
+ const message = rawUnavailableMessage(entry.validation);
389
+ process.stdout.write(`${safeJson({
390
+ ...result,
391
+ error: "raw_unavailable",
392
+ message
393
+ })}\n`);
394
+ process.exitCode = 1;
395
+ return;
396
+ }
397
+ if (opts.json) {
398
+ process.stdout.write(`${safeJson(result)}\n`);
399
+ return;
400
+ }
401
+ printRejectedMetadata(result);
402
+ } catch (error) {
403
+ reportInspectionError(error, { json: opts.json || opts.raw });
404
+ }
405
+ }
406
+ var captureCommand = new Command("capture").configureHelp(helpStyle).description("Inspect retained capture events");
407
+ var listRejectedCommand = new Command("list-rejected").configureHelp(helpStyle).description("List retained OpenCode rejections without reading payloads");
408
+ addJsonOption(listRejectedCommand);
409
+ listRejectedCommand.action(runListRejected);
410
+ var showRejectedCommand = new Command("show-rejected").configureHelp(helpStyle).description("Inspect one retained OpenCode rejection without modifying it").argument("<receipt>", "receipt from list-rejected").option("-r, --raw", "include private text as a JSON string (always output JSON)").addHelpText("after", "\n--raw also emits errors as JSON. If the file changes, retry inspection.\nFiles remain untouched.");
411
+ addJsonOption(showRejectedCommand);
412
+ showRejectedCommand.action(runShowRejected);
413
+ captureCommand.addCommand(listRejectedCommand).addCommand(showRejectedCommand);
414
+ //#endregion
82
415
  //#region src/commands/claude-hook-file-context-transport.ts
83
416
  /** Internal packaged-hook transport. Normal CLI invocation keeps its original guards/output. */
84
417
  function runClaudeFileContextTransport(payload, opts) {
@@ -1281,9 +1614,8 @@ function directEnqueue(payload, dbPath) {
1281
1614
  /**
1282
1615
  * Best-effort boundary flush: write the payload through to the local
1283
1616
  * 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.
1617
+ * raw_events) and then extract at most one batch before the hook exits.
1618
+ * Any remaining events stay durable for the Viewer or a later invocation.
1287
1619
  *
1288
1620
  * Any failure here \u2014 observer construction, store I/O, flush errors,
1289
1621
  * or simply running without observer credentials \u2014 is logged to
@@ -1314,7 +1646,7 @@ async function flushBoundaryRawEvents$1(payload, dbPath) {
1314
1646
  cwd: envelope.cwd ?? null,
1315
1647
  project: envelope.project ?? null,
1316
1648
  startedAt: envelope.started_at ?? null,
1317
- maxEvents: null
1649
+ maxEvents: DEFAULT_RAW_EVENT_FLUSH_MAX_EVENTS
1318
1650
  });
1319
1651
  } catch (err) {
1320
1652
  logHookEvent(`codemem claude-hook-ingest boundary flush raw events failed cause=${err instanceof Error ? err.name : "unknown"}`);
@@ -2000,12 +2332,12 @@ function parsePositiveInt$2(value, fallback) {
2000
2332
  const parsed = Number.parseInt(String(value ?? ""), 10);
2001
2333
  return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
2002
2334
  }
2003
- function isRecord$2(value) {
2335
+ function isRecord$3(value) {
2004
2336
  return value != null && typeof value === "object" && !Array.isArray(value);
2005
2337
  }
2006
2338
  function canonicalJson$1(value) {
2007
2339
  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(",")}}`;
2340
+ if (isRecord$3(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson$1(value[key])}`).join(",")}}`;
2009
2341
  return JSON.stringify(value);
2010
2342
  }
2011
2343
  function viewerBaseUrl$1(env) {
@@ -2026,7 +2358,7 @@ async function responseJson$1(response) {
2026
2358
  }
2027
2359
  }
2028
2360
  function errorCode$1(body) {
2029
- return isRecord$2(body) && isRecord$2(body.error) && typeof body.error.code === "string" ? body.error.code : null;
2361
+ return isRecord$3(body) && isRecord$3(body.error) && typeof body.error.code === "string" ? body.error.code : null;
2030
2362
  }
2031
2363
  function classifyHttpFailure(status, body, compatibleProfile) {
2032
2364
  const code = errorCode$1(body);
@@ -2091,8 +2423,8 @@ async function fetchViewerPack$1(query, project, payload, dbPath, deps) {
2091
2423
  ok: false,
2092
2424
  disposition: classifyHttpFailure(profileResponse.status, profile, false)
2093
2425
  };
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 {
2426
+ const viewerRange = isRecord$3(profile) ? normalizePromptTransportProtocolRange(profile.protocol_version, profile.min_supported_protocol_version) : null;
2427
+ if (!isRecord$3(profile) || profile.service !== "codemem-viewer" || !viewerRange || !arePromptTransportProtocolRangesCompatible(PROMPT_TRANSPORT_PROTOCOL_RANGE, viewerRange)) return {
2096
2428
  ok: false,
2097
2429
  disposition: "fallback"
2098
2430
  };
@@ -2156,7 +2488,7 @@ async function fetchViewerPack$1(query, project, payload, dbPath, deps) {
2156
2488
  ok: false,
2157
2489
  disposition: classifyHttpFailure(packResponse.status, body, true)
2158
2490
  };
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 {
2491
+ 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
2492
  ok: false,
2161
2493
  disposition: "fallback"
2162
2494
  };
@@ -2917,6 +3249,57 @@ function buildCoordinatorGrantIdentityGroupCommand() {
2917
3249
  return command;
2918
3250
  }
2919
3251
  //#endregion
3252
+ //#region src/commands/coordinator-link-account-headless.ts
3253
+ var output = { output: process.stderr };
3254
+ var STATE_LINES = {
3255
+ pending: "Waiting for the code…",
3256
+ browser_claimed: "Code entered, signing in…",
3257
+ oidc_verified: "Reviewing in browser…"
3258
+ };
3259
+ var MAX_SHOWN_LENGTH = 200;
3260
+ /** Account claims come from Google via the coordinator; never let them drive the terminal. */
3261
+ function printable(value) {
3262
+ return value.replace(/[\p{Cc}\p{Cf}\u2028\u2029]/gu, "?").slice(0, MAX_SHOWN_LENGTH);
3263
+ }
3264
+ function formatExpiry(expiresAtMs) {
3265
+ return new Date(expiresAtMs).toLocaleTimeString(void 0, {
3266
+ hour: "numeric",
3267
+ minute: "2-digit",
3268
+ timeZoneName: "short"
3269
+ });
3270
+ }
3271
+ function showHeadlessCode(code) {
3272
+ p.log.step(`On any computer, open ${code.verificationUri} and enter code: ${code.code}`, output);
3273
+ p.log.message(`This device: ${printable(code.deviceId)} · key ${code.fingerprint}`, output);
3274
+ p.log.message(`The code expires at ${formatExpiry(code.expiresAtMs)}.`, output);
3275
+ }
3276
+ function showHeadlessState(state) {
3277
+ const line = STATE_LINES[state];
3278
+ if (line) p.log.info(line, output);
3279
+ }
3280
+ /** The y/N or typed confirmation on this device; anything but an explicit yes declines. */
3281
+ async function confirmHeadlessApproval(identityId, approval, context) {
3282
+ const question = `Link Identity ${printable(identityId)} to this Google account?`;
3283
+ if (approval.email) {
3284
+ const verified = approval.emailVerified === true ? "verified by Google" : "email not verified by Google";
3285
+ p.log.info(`Approved in the browser by ${printable(approval.email)} (${verified})`, output);
3286
+ return await p.confirm({
3287
+ message: `${question} (y/N)`,
3288
+ initialValue: false,
3289
+ signal: context.signal,
3290
+ ...output
3291
+ }) === true;
3292
+ }
3293
+ const who = approval.displayName ? printable(approval.displayName) : "an account with no email";
3294
+ p.log.warn(`Approved in the browser by ${who}`, output);
3295
+ const answer = await p.text({
3296
+ message: `${question} Type link to confirm.`,
3297
+ signal: context.signal,
3298
+ ...output
3299
+ });
3300
+ return !p.isCancel(answer) && answer.trim() === "link";
3301
+ }
3302
+ //#endregion
2920
3303
  //#region src/commands/coordinator-link-account.ts
2921
3304
  function reportLinkFailure(error, coordinatorOrigin) {
2922
3305
  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 +3317,18 @@ function showPrivateBrowserLink(privateUrl) {
2934
3317
  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
3318
  p.log.message(privateUrl, { output: process.stderr });
2936
3319
  }
3320
+ function requireHeadlessTerminal() {
3321
+ if (process.stdin.isTTY && process.stderr.isTTY) return true;
3322
+ 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 });
3323
+ process.exitCode = 2;
3324
+ return false;
3325
+ }
2937
3326
  function requireInteractive(options) {
2938
3327
  if (options.json) {
2939
3328
  emitJsonError("interactive_flow_only", "Account linking is interactive. Run without --json and keep the browser link private.", 2);
2940
3329
  return false;
2941
3330
  }
3331
+ if (options.headless) return requireHeadlessTerminal();
2942
3332
  if (!process.stderr.isTTY) {
2943
3333
  p.log.error("Account linking requires a terminal. Run this command interactively and keep the browser link private.", { output: process.stderr });
2944
3334
  process.exitCode = 2;
@@ -2998,6 +3388,36 @@ function eligibleStatus(remote, identityId) {
2998
3388
  if (status.identityId !== identityId) throw new CoordinatorAccountLinkError("identity_mismatch");
2999
3389
  return status;
3000
3390
  }
3391
+ /** Starts the desktop or headless flow once the Identity is eligible. */
3392
+ async function startLink(options, context) {
3393
+ const { profile, status } = context;
3394
+ const snapshot = JSON.stringify(profile);
3395
+ const request = {
3396
+ ...profile,
3397
+ groupId: context.group,
3398
+ coordinatorUrl: context.selected.coordinatorUrl,
3399
+ expectedAuthority: status.authority,
3400
+ expectedCoordinatorId: status.coordinatorId,
3401
+ assertCurrentContext: () => profileMatches(options, snapshot),
3402
+ signal: context.signal
3403
+ };
3404
+ if (options.headless) {
3405
+ await linkCoordinatorAccountHeadless({
3406
+ ...request,
3407
+ onCode: showHeadlessCode,
3408
+ onState: showHeadlessState,
3409
+ approve: (approval, prompt) => confirmHeadlessApproval(profile.expectedIdentityId, approval, prompt)
3410
+ });
3411
+ p.log.success("Linked.", { output: process.stderr });
3412
+ return;
3413
+ }
3414
+ const result = await linkCoordinatorAccount({
3415
+ ...request,
3416
+ loopbackHost: context.selected.loopbackHost,
3417
+ onBrowserStart: showPrivateBrowserLink
3418
+ });
3419
+ p.log.success(`Coordinator account linked to coordinator Identity ${result.identityId}. Your local Identity has not changed.`, { output: process.stderr });
3420
+ }
3001
3421
  async function linkAccount(group, options) {
3002
3422
  if (!requireInteractive(options)) return;
3003
3423
  const controller = new AbortController();
@@ -3026,19 +3446,13 @@ async function linkAccount(group, options) {
3026
3446
  p.log.success("This Identity is already linked. No account-link request was started.", { output: process.stderr });
3027
3447
  return;
3028
3448
  }
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
3449
+ await startLink(options, {
3450
+ group,
3451
+ selected,
3452
+ profile,
3453
+ status,
3454
+ signal: controller.signal
3040
3455
  });
3041
- p.log.success(`Coordinator account linked to coordinator Identity ${result.identityId}. Your local Identity has not changed.`, { output: process.stderr });
3042
3456
  } catch (error) {
3043
3457
  reportLinkFailure(error, coordinatorOrigin);
3044
3458
  process.exitCode = 1;
@@ -3048,7 +3462,7 @@ async function linkAccount(group, options) {
3048
3462
  }
3049
3463
  }
3050
3464
  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");
3465
+ 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
3466
  addDbOption(command);
3053
3467
  addConfigOption(command);
3054
3468
  addJsonOption(command);
@@ -5518,6 +5932,51 @@ cmd$3.action((inputFile, opts) => {
5518
5932
  p.outro("done");
5519
5933
  });
5520
5934
  var importMemoriesCommand = cmd$3;
5935
+ function isBusy(error) {
5936
+ const code = error?.code;
5937
+ return typeof code === "string" && (code.startsWith("SQLITE_BUSY") || code.startsWith("SQLITE_LOCKED"));
5938
+ }
5939
+ function runCheckpoint(db, mode) {
5940
+ try {
5941
+ return db.pragma(`wal_checkpoint(${mode})`)[0] ?? null;
5942
+ } catch (error) {
5943
+ if (isBusy(error)) return null;
5944
+ throw error;
5945
+ }
5946
+ }
5947
+ /** TRUNCATE takes the writer lock; with no busy wait it gives up instead of stalling writers. */
5948
+ function truncateWithoutWaiting(db) {
5949
+ const timeout = Number(db.pragma("busy_timeout", { simple: true }));
5950
+ db.pragma("busy_timeout = 0");
5951
+ try {
5952
+ const row = runCheckpoint(db, "TRUNCATE");
5953
+ return row !== null && row.busy === 0;
5954
+ } finally {
5955
+ db.pragma(`busy_timeout = ${timeout}`);
5956
+ }
5957
+ }
5958
+ /**
5959
+ * Keep the WAL from growing without blocking other writers.
5960
+ *
5961
+ * A PASSIVE checkpoint copies frames without taking the writer lock. Only once
5962
+ * it has copied every frame does a TRUNCATE try to reset the file, and it runs
5963
+ * with busy_timeout 0, so a busy database skips the truncate until the next run
5964
+ * instead of holding off writers. The old TRUNCATE-only checkpoint waited up to
5965
+ * busy_timeout and blocked new writers while it waited.
5966
+ */
5967
+ function checkpointWalWithoutBlocking(db, logger, now = () => performance.now()) {
5968
+ const started = now();
5969
+ const passive = runCheckpoint(db, "PASSIVE");
5970
+ const truncated = passive !== null && passive.busy === 0 && passive.checkpointed >= passive.log ? truncateWithoutWaiting(db) : false;
5971
+ const elapsedMs = now() - started;
5972
+ const remainingFrames = passive === null ? null : Math.max(0, passive.log - passive.checkpointed);
5973
+ if (elapsedMs >= 250) logger.step(`WAL checkpoint took ${Math.round(elapsedMs)} ms (${remainingFrames ?? "unknown"} frames left, truncated: ${truncated ? "yes" : "no"})`);
5974
+ return {
5975
+ remainingFrames,
5976
+ truncated,
5977
+ elapsedMs
5978
+ };
5979
+ }
5521
5980
  //#endregion
5522
5981
  //#region src/maintenance-worker-runtime.ts
5523
5982
  var defaultLogger = {
@@ -5636,6 +6095,15 @@ function createSequentialBackfillCoordinator(store, jobPlans, options) {
5636
6095
  }
5637
6096
  };
5638
6097
  }
6098
+ function createVectorMigrationRunner(dbPath, signal) {
6099
+ return new VectorModelMigrationRunner({
6100
+ dbPath,
6101
+ signal,
6102
+ batchSize: 10,
6103
+ idleIntervalMs: 6e4,
6104
+ tickBudgetMs: 5e3
6105
+ });
6106
+ }
5639
6107
  function startMaintenanceWorkerRuntime(options = {}) {
5640
6108
  const logger = options.logger ?? defaultLogger;
5641
6109
  const dbPath = resolveDbPath(options.dbPath ?? void 0);
@@ -5644,18 +6112,13 @@ function startMaintenanceWorkerRuntime(options = {}) {
5644
6112
  const runners = [];
5645
6113
  const walCheckpointTimer = setInterval(() => {
5646
6114
  try {
5647
- store.db.pragma("wal_checkpoint(TRUNCATE)");
6115
+ checkpointWalWithoutBlocking(store.db, logger);
5648
6116
  } catch (error) {
5649
6117
  logger.warn(`WAL checkpoint failed: ${error instanceof Error ? error.message : String(error)}`);
5650
6118
  }
5651
6119
  }, 3e5);
5652
6120
  walCheckpointTimer.unref();
5653
- if (!isEmbeddingDisabled()) runners.push(new VectorModelMigrationRunner({
5654
- dbPath,
5655
- signal: options.signal,
5656
- batchSize: 10,
5657
- idleIntervalMs: 6e4
5658
- }));
6121
+ if (!isEmbeddingDisabled()) runners.push(createVectorMigrationRunner(dbPath, options.signal));
5659
6122
  runners.push(createSequentialBackfillCoordinator(store, [
5660
6123
  {
5661
6124
  name: "Sharing-domain",
@@ -5750,6 +6213,7 @@ async function runMaintenanceWorkerCommand(opts) {
5750
6213
  const dbPath = resolveDbPath(resolveDbOpt(opts));
5751
6214
  if (opts.config) process.env.CODEMEM_CONFIG = opts.config;
5752
6215
  process.env.CODEMEM_DB = dbPath;
6216
+ process.stderr.on("error", () => void 0);
5753
6217
  const abort = new AbortController();
5754
6218
  const runtime = startMaintenanceWorkerRuntime({
5755
6219
  dbPath,
@@ -7099,6 +7563,78 @@ memoryCommand.addCommand(createMemoryExtractionBenchmarkCommand());
7099
7563
  memoryCommand.addCommand(createMemoryRelinkReportCommand());
7100
7564
  memoryCommand.addCommand(createMemoryRelinkPlanCommand());
7101
7565
  //#endregion
7566
+ //#region src/commands/memory-tool.ts
7567
+ /**
7568
+ * `codemem memory-tool <name>` — hidden plumbing for thin hosts.
7569
+ *
7570
+ * Runs one codemem memory tool in-process through the same handlers stdio MCP
7571
+ * uses, reading the tool arguments as a JSON object on stdin and printing one
7572
+ * JSON line on stdout:
7573
+ *
7574
+ * {"ok":true,"result":<tool result>}
7575
+ * {"ok":false,"error":"<message>","result":<tool error payload>} exit 0
7576
+ * {"ok":false,"error":"<code>","message":"<detail>"} exit 1
7577
+ *
7578
+ * Exit 0 means the tool ran (its own error included); exit 1 means the
7579
+ * invocation itself was invalid or the store could not be opened. The caller's
7580
+ * working directory supplies the default project, write-session cwd, and
7581
+ * AGENTS.md context exactly as it does for `codemem mcp`.
7582
+ */
7583
+ var MEMORY_TOOL_NAME = /^memory_[a-z_]+$/;
7584
+ async function readProcessStdin() {
7585
+ const chunks = [];
7586
+ for await (const chunk of process.stdin) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
7587
+ return Buffer.concat(chunks).toString("utf-8");
7588
+ }
7589
+ /** Empty stdin means no arguments; anything else must be a JSON object. */
7590
+ function parseToolArguments(raw) {
7591
+ const trimmed = raw.trim();
7592
+ if (!trimmed) return {};
7593
+ const parsed = JSON.parse(trimmed);
7594
+ if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) throw new TypeError("tool arguments must be a JSON object");
7595
+ return parsed;
7596
+ }
7597
+ function invocationError(write, error, message) {
7598
+ write(JSON.stringify({
7599
+ ok: false,
7600
+ error,
7601
+ message
7602
+ }));
7603
+ process.exitCode = 1;
7604
+ }
7605
+ async function runMemoryTool(name, opts, dependencies = {}) {
7606
+ const write = dependencies.write ?? ((line) => console.log(line));
7607
+ if (!MEMORY_TOOL_NAME.test(name)) {
7608
+ invocationError(write, "invalid_tool", `not a memory tool: ${name}`);
7609
+ return;
7610
+ }
7611
+ let args;
7612
+ try {
7613
+ args = parseToolArguments(await (dependencies.readStdin ?? readProcessStdin)());
7614
+ } catch (err) {
7615
+ invocationError(write, "invalid_arguments", err instanceof Error ? err.message : String(err));
7616
+ return;
7617
+ }
7618
+ let store = null;
7619
+ try {
7620
+ const { callCodememToolLocally } = await import("@codemem/mcp");
7621
+ store = new MemoryStore(resolveDbPath(resolveDbOpt(opts)));
7622
+ const outcome = await callCodememToolLocally(store, name, args, {
7623
+ sessionId: opts.sessionId?.trim() || void 0,
7624
+ requestId: opts.requestId?.trim() || void 0,
7625
+ statelessLedger: true
7626
+ });
7627
+ write(JSON.stringify(outcome));
7628
+ } catch (err) {
7629
+ invocationError(write, "tool_failed", err instanceof Error ? err.message : String(err));
7630
+ } finally {
7631
+ await store?.closeAsync();
7632
+ }
7633
+ }
7634
+ 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");
7635
+ addDbOption(memoryToolCmd);
7636
+ var memoryToolCommand = memoryToolCmd.action((name, opts) => runMemoryTool(name, opts));
7637
+ //#endregion
7102
7638
  //#region src/commands/pack.ts
7103
7639
  var MAX_INTERNAL_LEDGER_INPUT_BYTES = 16384;
7104
7640
  var INTERNAL_LEDGER_INPUT_TIMEOUT_MS = 1e3;
@@ -7278,7 +7814,7 @@ function renderPackTrace(trace) {
7278
7814
  lines.push(trace.output.pack_text);
7279
7815
  return lines.join("\n");
7280
7816
  }
7281
- async function withStore(opts, errorCode, run) {
7817
+ async function withStore$1(opts, errorCode, run) {
7282
7818
  let store = null;
7283
7819
  try {
7284
7820
  store = new MemoryStore(resolveDbPath(resolveDbOpt(opts)));
@@ -7312,7 +7848,7 @@ async function readOptionalLedgerPayload() {
7312
7848
  }
7313
7849
  }
7314
7850
  async function packAction(context, opts) {
7315
- await withStore(opts, "pack_failed", async (store) => {
7851
+ await withStore$1(opts, "pack_failed", async (store) => {
7316
7852
  const { limit, budget, filters, renderOptions } = buildPackRequestOptions(opts, { envProject: process.env.CODEMEM_PROJECT });
7317
7853
  let result;
7318
7854
  if (opts.internalLedger) {
@@ -7357,7 +7893,7 @@ function emitPackResult(context, opts, result, ledgerArtifactFingerprint, ledger
7357
7893
  p.outro("done");
7358
7894
  }
7359
7895
  async function traceAction(context, opts) {
7360
- await withStore(opts, "pack_trace_failed", async (store) => {
7896
+ await withStore$1(opts, "pack_trace_failed", async (store) => {
7361
7897
  const { limit, budget, filters, renderOptions } = buildPackRequestOptions(opts, { envProject: process.env.CODEMEM_PROJECT });
7362
7898
  const trace = await store.buildMemoryPackTraceAsync(context, limit, budget, filters, renderOptions);
7363
7899
  if (opts.json) {
@@ -7425,7 +7961,7 @@ function handlePromptPackLifecycle(db, payload) {
7425
7961
  throw new PackUsageError("internal ledger action is invalid");
7426
7962
  }
7427
7963
  async function promptPackLedgerAction(opts) {
7428
- await withStore(opts, "prompt_pack_ledger_failed", async (store) => {
7964
+ await withStore$1(opts, "prompt_pack_ledger_failed", async (store) => {
7429
7965
  const payload = await readInternalLedgerPayload();
7430
7966
  handlePromptPackLedger(store.db, payload);
7431
7967
  });
@@ -7465,7 +8001,7 @@ var hasPiHookSpooledEntries = spool.hasSpooledEntries;
7465
8001
  var hasSpooledPiHookPayload = (receipt) => hasHookIngestSpoolReceipt(spool.spoolDir(), receipt);
7466
8002
  var recoverStalePiHookTmpSpool = spool.recoverStaleTmpSpool;
7467
8003
  var piHookLockTtlSeconds = spool.lockTtlSeconds;
7468
- spool.spoolDir;
8004
+ var piHookSpoolDir = spool.spoolDir;
7469
8005
  /**
7470
8006
  * Boundary flush for pi: compaction and session end both trigger extraction.
7471
8007
  * session_before_compact is observe-only (never stored as transcript).
@@ -7620,10 +8156,10 @@ function directEnqueuePiHook(payload, dbPath) {
7620
8156
  /**
7621
8157
  * Best-effort boundary flush for session_before_compact / session_shutdown.
7622
8158
  * 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.
8159
+ * Returns false until the captured boundary is complete, retaining the receipt
8160
+ * for the next invocation. Each attempt extracts at most one batch.
7625
8161
  */
7626
- async function flushBoundaryRawEvents(payload, dbPath) {
8162
+ async function flushBoundaryRawEvents(payload, dbPath, receipt) {
7627
8163
  const envelope = buildRawEventEnvelopeFromPiEvent(payload);
7628
8164
  const signal = buildPiFlushSignalFromEvent(payload);
7629
8165
  const sessionId = envelope?.session_stream_id ?? signal?.session_id ?? null;
@@ -7647,15 +8183,17 @@ async function flushBoundaryRawEvents(payload, dbPath) {
7647
8183
  return false;
7648
8184
  }
7649
8185
  try {
8186
+ const throughEventSeq = capturePiBoundaryCeiling(store, sessionId, payload, receipt);
7650
8187
  await flushRawEvents(store, { observer }, {
7651
8188
  opencodeSessionId: sessionId,
7652
8189
  source,
7653
8190
  cwd,
7654
8191
  project,
7655
8192
  startedAt,
7656
- maxEvents: null
8193
+ maxEvents: DEFAULT_RAW_EVENT_FLUSH_MAX_EVENTS,
8194
+ throughEventSeq
7657
8195
  });
7658
- return true;
8196
+ return isPiBoundaryComplete(store, sessionId, throughEventSeq);
7659
8197
  } catch (err) {
7660
8198
  logHookEvent(`codemem pi-hook-ingest boundary flush raw events failed: ${err instanceof Error ? err.message : String(err)}`);
7661
8199
  return false;
@@ -7663,6 +8201,33 @@ async function flushBoundaryRawEvents(payload, dbPath) {
7663
8201
  store.close();
7664
8202
  }
7665
8203
  }
8204
+ var BOUNDARY_CEILING_FIELD = "_codememBoundaryThroughEventSeq";
8205
+ function isPiBoundaryComplete(store, sessionId, throughEventSeq) {
8206
+ const cursor = store.rawEventFlushState(sessionId, "pi");
8207
+ return cursor >= throughEventSeq || store.rawEventsSinceBySeq(sessionId, "pi", cursor, 1, throughEventSeq).length === 0;
8208
+ }
8209
+ function capturePiBoundaryCeiling(store, sessionId, payload, receipt) {
8210
+ const saved = payload[BOUNDARY_CEILING_FIELD];
8211
+ if (typeof saved === "number" && Number.isSafeInteger(saved) && saved >= -1) return saved;
8212
+ const ceiling = Number(store.rawEventSessionMeta(sessionId, "pi").last_received_event_seq ?? -1);
8213
+ if (!Number.isSafeInteger(ceiling) || ceiling < -1) throw new Error("invalid Pi boundary event sequence");
8214
+ if (receipt) {
8215
+ const dir = piHookSpoolDir();
8216
+ const temporary = join(dir, `.hook-tmp-boundary-${receipt}.tmp`);
8217
+ try {
8218
+ writeFileSync(temporary, JSON.stringify({
8219
+ ...payload,
8220
+ [BOUNDARY_CEILING_FIELD]: ceiling
8221
+ }));
8222
+ renameSync(temporary, join(dir, receipt));
8223
+ } finally {
8224
+ try {
8225
+ unlinkSync(temporary);
8226
+ } catch {}
8227
+ }
8228
+ }
8229
+ return ceiling;
8230
+ }
7666
8231
  function dbPathGetter(resolveDb, opts) {
7667
8232
  let cached = null;
7668
8233
  return () => {
@@ -7681,11 +8246,13 @@ function tryDirectFallback(runtime, queued) {
7681
8246
  return { ok: false };
7682
8247
  }
7683
8248
  }
7684
- async function writeAndFlushBoundary(runtime, payload) {
8249
+ async function writeAndFlushBoundary(runtime, payload, receipt) {
8250
+ if (runtime.boundaryFlushAttempted) return { ok: false };
7685
8251
  const direct = tryDirectFallback(runtime, payload);
7686
8252
  if (!direct.ok) return direct;
8253
+ runtime.boundaryFlushAttempted = true;
7687
8254
  try {
7688
- if (await runtime.boundaryFlush(payload, runtime.getDbPath()) === false) {
8255
+ if (await runtime.boundaryFlush(payload, runtime.getDbPath(), receipt) === false) {
7689
8256
  logHookEvent("codemem pi-hook-ingest boundary flush failed; keeping spooled payload");
7690
8257
  return { ok: false };
7691
8258
  }
@@ -7711,6 +8278,7 @@ function createPiIngestRuntime(payload, opts, deps) {
7711
8278
  httpIngest: deps.httpIngest ?? tryHttpIngest,
7712
8279
  directIngest: deps.directIngest ?? directEnqueuePiHook,
7713
8280
  boundaryFlush: deps.boundaryFlush ?? flushBoundaryRawEvents,
8281
+ boundaryFlushAttempted: false,
7714
8282
  withLock: deps.withLock ?? withPiHookIngestLock,
7715
8283
  getDbPath,
7716
8284
  httpPayload: (queued) => targetedPiPayload(queued, getDbPath)
@@ -7735,7 +8303,7 @@ function spoolPiPayloadOrThrow(payload) {
7735
8303
  };
7736
8304
  throw new Error("pi-hook-ingest: HTTP and spool failed");
7737
8305
  }
7738
- async function deliverQueuedPiHook(runtime, queuedPayload) {
8306
+ async function deliverQueuedPiHook(runtime, queuedPayload, receipt) {
7739
8307
  const result = await runtime.httpIngest(runtime.httpPayload(queuedPayload), runtime.opts.host, runtime.port);
7740
8308
  const boundaryRequested = shouldForcePiBoundaryFlush(queuedPayload);
7741
8309
  if (result.ok && (result.queued !== void 0 || !boundaryRequested)) return {
@@ -7748,7 +8316,7 @@ async function deliverQueuedPiHook(runtime, queuedPayload) {
7748
8316
  httpResult: result,
7749
8317
  directResult: null
7750
8318
  };
7751
- const boundary = await writeAndFlushBoundary(runtime, queuedPayload);
8319
+ const boundary = await writeAndFlushBoundary(runtime, queuedPayload, receipt);
7752
8320
  if (!boundary.ok) return {
7753
8321
  accepted: false,
7754
8322
  httpResult: result,
@@ -7761,7 +8329,7 @@ async function deliverQueuedPiHook(runtime, queuedPayload) {
7761
8329
  };
7762
8330
  }
7763
8331
  async function ingestPiBoundaryDirect(runtime, receipt) {
7764
- const boundary = await writeAndFlushBoundary(runtime, runtime.payload);
8332
+ const boundary = await writeAndFlushBoundary(runtime, runtime.payload, receipt);
7765
8333
  if (!boundary.ok) return {
7766
8334
  inserted: 0,
7767
8335
  skipped: 0,
@@ -7782,7 +8350,7 @@ async function drainPiBacklog(runtime, currentReceipt) {
7782
8350
  await runtime.withLock(async () => {
7783
8351
  recoverStalePiHookTmpSpool(piHookLockTtlSeconds());
7784
8352
  await drainPiHookSpool(async (queuedPayload, receipt) => {
7785
- const delivery = await deliverQueuedPiHook(runtime, queuedPayload);
8353
+ const delivery = await deliverQueuedPiHook(runtime, queuedPayload, receipt);
7786
8354
  if (receipt === currentReceipt) {
7787
8355
  currentResult = delivery.httpResult;
7788
8356
  currentAccepted = delivery.accepted;
@@ -7831,7 +8399,8 @@ async function retainAndProcessBoundary(runtime) {
7831
8399
  }
7832
8400
  /** Ingest one Pi event through the Viewer queue or local spool. */
7833
8401
  async function ingestPiHookPayload(payload, opts, deps = {}) {
7834
- const stablePayload = stabilizePiBoundaryPayload(payload);
8402
+ const { [BOUNDARY_CEILING_FIELD]: _ignoredCeiling, ...livePayload } = payload;
8403
+ const stablePayload = stabilizePiBoundaryPayload(livePayload);
7835
8404
  const runtime = createPiIngestRuntime(stablePayload, opts, deps);
7836
8405
  const boundaryRequested = shouldForcePiBoundaryFlush(stablePayload);
7837
8406
  if (hasPiHookSpooledEntries()) {
@@ -7989,12 +8558,12 @@ async function buildLocalPack(context, project, dbPath) {
7989
8558
  await store.closeAsync();
7990
8559
  }
7991
8560
  }
7992
- function isRecord$1(value) {
8561
+ function isRecord$2(value) {
7993
8562
  return value != null && typeof value === "object" && !Array.isArray(value);
7994
8563
  }
7995
8564
  function canonicalJson(value) {
7996
8565
  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(",")}}`;
8566
+ if (isRecord$2(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
7998
8567
  return JSON.stringify(value);
7999
8568
  }
8000
8569
  function viewerBaseUrl() {
@@ -8018,7 +8587,7 @@ async function responseJson(response) {
8018
8587
  }
8019
8588
  }
8020
8589
  function errorCode(body) {
8021
- return isRecord$1(body) && isRecord$1(body.error) && typeof body.error.code === "string" ? body.error.code : null;
8590
+ return isRecord$2(body) && isRecord$2(body.error) && typeof body.error.code === "string" ? body.error.code : null;
8022
8591
  }
8023
8592
  function classifyViewerHttpFailure(status, body, compatibleProfile) {
8024
8593
  const code = errorCode(body);
@@ -8071,13 +8640,13 @@ async function targetedViewerPackPost(baseUrl, identity, query, project, dbPath,
8071
8640
  ok: false,
8072
8641
  disposition: classifyViewerHttpFailure(packResponse.status, body, true)
8073
8642
  };
8074
- const packText = isRecord$1(body) ? String(body.pack_text ?? "").trim() : "";
8075
- const metrics = isRecord$1(body) && isRecord$1(body.metrics) ? body.metrics : null;
8643
+ const packText = isRecord$2(body) ? String(body.pack_text ?? "").trim() : "";
8644
+ const metrics = isRecord$2(body) && isRecord$2(body.metrics) ? body.metrics : null;
8076
8645
  return {
8077
8646
  ok: true,
8078
8647
  pack: {
8079
8648
  packText,
8080
- items: isRecord$1(body) && Array.isArray(body.items) ? body.items.length : 0,
8649
+ items: isRecord$2(body) && Array.isArray(body.items) ? body.items.length : 0,
8081
8650
  packTokens: metrics && Number.isFinite(Number(metrics.pack_tokens)) ? Number(metrics.pack_tokens) : 0
8082
8651
  }
8083
8652
  };
@@ -8106,8 +8675,8 @@ async function fetchAndValidateViewerProfile(baseUrl, dbPath, identity, fetchImp
8106
8675
  ok: false,
8107
8676
  disposition: classifyViewerHttpFailure(profileResponse.status, profile, false)
8108
8677
  };
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 {
8678
+ const viewerRange = isRecord$2(profile) ? normalizePromptTransportProtocolRange(profile.protocol_version, profile.min_supported_protocol_version) : null;
8679
+ if (!isRecord$2(profile) || profile.service !== "codemem-viewer" || !viewerRange || !arePromptTransportProtocolRangesCompatible(PROMPT_TRANSPORT_PROTOCOL_RANGE, viewerRange)) return {
8111
8680
  ok: false,
8112
8681
  disposition: "fallback"
8113
8682
  };
@@ -8293,19 +8862,16 @@ async function flushImportedPiSessions(dbPath, observer) {
8293
8862
  extraction.pendingSessions = piPendingSessions(store).length;
8294
8863
  return extraction;
8295
8864
  }
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;
8865
+ const backlog = piPendingSessions(store).map((streamId) => ({
8866
+ streamId,
8867
+ throughEventSeq: Number(store.rawEventSessionMeta(streamId, "pi").last_received_event_seq),
8868
+ initialCursor: store.rawEventFlushState(streamId, "pi")
8869
+ }));
8870
+ for (const stream of backlog) try {
8871
+ await drainImportedPiStream(store, resolved, stream, extraction);
8306
8872
  } catch (err) {
8307
8873
  extraction.failedSessions++;
8308
- extraction.error ??= `session ${streamId}: ${err instanceof Error ? err.message : String(err)}`;
8874
+ extraction.error ??= `session ${stream.streamId}: ${err instanceof Error ? err.message : String(err)}`;
8309
8875
  }
8310
8876
  extraction.pendingSessions = piPendingSessions(store).length;
8311
8877
  return extraction;
@@ -8313,6 +8879,28 @@ async function flushImportedPiSessions(dbPath, observer) {
8313
8879
  store.close();
8314
8880
  }
8315
8881
  }
8882
+ async function drainImportedPiStream(store, observer, stream, extraction) {
8883
+ const { streamId, throughEventSeq, initialCursor } = stream;
8884
+ const maxAttempts = Math.max(0, throughEventSeq - initialCursor);
8885
+ if (!Number.isSafeInteger(throughEventSeq) || !Number.isSafeInteger(initialCursor) || !Number.isSafeInteger(maxAttempts) || throughEventSeq < -1 || initialCursor < -1) throw new Error("invalid Pi import event sequence");
8886
+ let cursor = initialCursor;
8887
+ for (let attempt = 0; attempt < maxAttempts && cursor < throughEventSeq; attempt++) {
8888
+ const result = await flushRawEvents(store, { observer }, {
8889
+ opencodeSessionId: streamId,
8890
+ source: "pi",
8891
+ cwd: null,
8892
+ project: null,
8893
+ startedAt: null,
8894
+ maxEvents: DEFAULT_RAW_EVENT_FLUSH_MAX_EVENTS,
8895
+ throughEventSeq
8896
+ });
8897
+ extraction.flushedEvents += result.flushed;
8898
+ const nextCursor = store.rawEventFlushState(streamId, "pi");
8899
+ if (!Number.isSafeInteger(nextCursor)) throw new Error("invalid Pi import flush cursor");
8900
+ if (nextCursor <= cursor) break;
8901
+ cursor = nextCursor;
8902
+ }
8903
+ }
8316
8904
  /** Pending-flush sessions attributed to source "pi", without a page cap. */
8317
8905
  function piPendingSessions(store) {
8318
8906
  return store.rawEventSessionsPendingFlush(null, "pi").map((session) => session.streamId);
@@ -8532,6 +9120,34 @@ function timeSince(isoDate) {
8532
9120
  return `${Math.floor(days / 30)}mo ago`;
8533
9121
  }
8534
9122
  //#endregion
9123
+ //#region src/child-stderr-forward.ts
9124
+ var defaultWrite = (text) => {
9125
+ process.stderr.write(text);
9126
+ };
9127
+ /**
9128
+ * Copy a child process's stderr into this process's stderr one prefixed line
9129
+ * at a time, so container logs show which process wrote each line.
9130
+ *
9131
+ * The parent reads the pipe from its event loop, so the child only waits when
9132
+ * the pipe buffer (64 KiB on Linux) fills while the parent is busy. Read and
9133
+ * write errors end forwarding instead of crashing either process.
9134
+ */
9135
+ function forwardChildStderr(source, options) {
9136
+ const write = options.write ?? defaultWrite;
9137
+ const lines = createInterface({
9138
+ input: source,
9139
+ crlfDelay: Number.POSITIVE_INFINITY
9140
+ });
9141
+ const ignorePipeError = () => void 0;
9142
+ source.on("error", ignorePipeError);
9143
+ lines.on("error", ignorePipeError);
9144
+ lines.on("line", (line) => {
9145
+ try {
9146
+ write(`${options.prefix}${line}\n`);
9147
+ } catch {}
9148
+ });
9149
+ }
9150
+ //#endregion
8535
9151
  //#region src/observer-runtime-controller.ts
8536
9152
  /** Keep the live observer and saved config separate until in-flight work has drained. */
8537
9153
  var ObserverRuntimeController = class {
@@ -9061,6 +9677,7 @@ function buildMaintenanceWorkerArgs(scriptPath, invocation, execArgv = process.e
9061
9677
  if (invocation.configPath) args.push("--config", invocation.configPath);
9062
9678
  return args;
9063
9679
  }
9680
+ var MAINTENANCE_WORKER_LOG_PREFIX = "[maintenance-worker] ";
9064
9681
  function startMaintenanceWorkerProcess(invocation) {
9065
9682
  const scriptPath = process.argv[1];
9066
9683
  if (!scriptPath) {
@@ -9070,13 +9687,21 @@ function startMaintenanceWorkerProcess(invocation) {
9070
9687
  const dbPath = resolveDbPath(invocation.dbPath ?? void 0);
9071
9688
  const child = spawn(process.execPath, buildMaintenanceWorkerArgs(scriptPath, invocation), {
9072
9689
  cwd: process.cwd(),
9073
- stdio: "ignore",
9690
+ stdio: [
9691
+ "ignore",
9692
+ "ignore",
9693
+ "pipe"
9694
+ ],
9074
9695
  env: {
9075
9696
  ...process.env,
9076
9697
  CODEMEM_DB: dbPath,
9077
9698
  ...invocation.configPath ? { CODEMEM_CONFIG: invocation.configPath } : {}
9078
9699
  }
9079
9700
  });
9701
+ if (child.stderr) {
9702
+ forwardChildStderr(child.stderr, { prefix: MAINTENANCE_WORKER_LOG_PREFIX });
9703
+ child.stderr.unref?.();
9704
+ }
9080
9705
  child.unref();
9081
9706
  if (child.pid) {
9082
9707
  writeFileSync(maintenanceWorkerPidFilePath(dbPath), JSON.stringify({
@@ -9381,6 +10006,99 @@ function announceViewerStartup(options) {
9381
10006
  p.log.info(`Database: ${preparedDb}`);
9382
10007
  p.log.step("Raw event sweeper started");
9383
10008
  }
10009
+ var logRelay = (message, level) => level === "warn" ? p.log.warn(message) : p.log.info(message);
10010
+ /**
10011
+ * Relay additions to the sync daemon options. Without relay this returns the
10012
+ * callback unchanged and no `reachability`, so sync runs exactly as before.
10013
+ * With relay, groups re-resolve after every coordinator refresh, even a failed one.
10014
+ */
10015
+ function serveRelayDaemonOptions(relay, onAfterCoordinatorRefresh) {
10016
+ if (!relay) return { onAfterCoordinatorRefresh };
10017
+ return {
10018
+ reachability: relay.reachability,
10019
+ onAfterCoordinatorRefresh: async (context) => {
10020
+ try {
10021
+ await onAfterCoordinatorRefresh(context);
10022
+ } finally {
10023
+ await relay.refresh();
10024
+ }
10025
+ }
10026
+ };
10027
+ }
10028
+ function applySyncPhase(status, phase) {
10029
+ if (phase === "running") {
10030
+ status.phase = null;
10031
+ status.detail = null;
10032
+ return;
10033
+ }
10034
+ status.phase = phase;
10035
+ status.detail = phase === "starting" ? "Running initial sync in background" : "Stopping sync daemon";
10036
+ }
10037
+ function startServeSyncDaemon(options) {
10038
+ const { syncConfig, store, signal, status, relay } = options;
10039
+ status.phase = "starting";
10040
+ status.detail = "Starting sync in background";
10041
+ relay?.refresh();
10042
+ runSyncDaemon({
10043
+ dbPath: resolveDbPath(options.invocation.dbPath ?? void 0),
10044
+ intervalS: syncConfig.syncIntervalS,
10045
+ host: syncConfig.syncHost,
10046
+ port: syncConfig.syncPort,
10047
+ signal,
10048
+ scanner: store.scanner,
10049
+ ...serveRelayDaemonOptions(relay, async () => {
10050
+ await runServeCoordinatorMaintenance(store, options.maintenance);
10051
+ }),
10052
+ onPhaseChange: (phase) => applySyncPhase(status, phase)
10053
+ }).catch((err) => {
10054
+ const msg = err instanceof Error ? err.message : String(err);
10055
+ status.phase = "error";
10056
+ status.detail = msg;
10057
+ p.log.error(`Sync daemon failed: ${msg}`);
10058
+ }).finally(() => {
10059
+ relay?.close();
10060
+ if (status.phase !== "error") {
10061
+ status.phase = signal.aborted ? "stopping" : null;
10062
+ status.detail = signal.aborted ? "Sync stopped" : null;
10063
+ }
10064
+ });
10065
+ }
10066
+ /**
10067
+ * Runs a memory tool for a thin host through the same in-process MCP handlers
10068
+ * as stdio and `codemem memory-tool`. Loaded lazily so viewer startup does not
10069
+ * pull in the MCP SDK until a host actually calls a tool.
10070
+ */
10071
+ async function callMemoryToolForHost(store, name, args, caller) {
10072
+ const { callCodememToolLocally } = await import("@codemem/mcp");
10073
+ return callCodememToolLocally(store, name, args, caller);
10074
+ }
10075
+ function foregroundAppOptions(store, rawEventOptions, options) {
10076
+ return {
10077
+ accountLink: options.accountLink.options,
10078
+ storeFactory: () => store,
10079
+ syncReachability: options.relay?.reachability,
10080
+ ...rawEventOptions,
10081
+ getSyncRuntimeStatus: () => options.syncRuntimeStatus
10082
+ };
10083
+ }
10084
+ function createBoundApp(createApp, options, listener) {
10085
+ let boundAddress = null;
10086
+ return {
10087
+ app: createApp({
10088
+ ...options,
10089
+ viewerAuthority: { getListenerAddress: () => boundAddress },
10090
+ memoryToolCall: callMemoryToolForHost
10091
+ }),
10092
+ setBoundAddress: (info) => {
10093
+ boundAddress = {
10094
+ host: listener.invocation.host,
10095
+ port: info.port,
10096
+ address: info.address
10097
+ };
10098
+ listener.accountLink.setBoundPort(info.port);
10099
+ }
10100
+ };
10101
+ }
9384
10102
  async function startForegroundViewer(invocation) {
9385
10103
  const serverModule = await import("@codemem/server");
9386
10104
  const { createApp, createSyncApp, closeStoreAsync, createViewerRawEventInbox, getStore } = serverModule;
@@ -9415,17 +10133,26 @@ async function startForegroundViewer(invocation) {
9415
10133
  const syncConfig = readCoordinatorSyncConfig(config);
9416
10134
  const syncEnabled = syncConfig.syncEnabled;
9417
10135
  const accountLink = createViewerAccountLink(store, invocation, serverModule);
10136
+ const relay = syncEnabled ? serverModule.createViewerRelayReachability({
10137
+ store,
10138
+ config,
10139
+ keysDir: process.env.CODEMEM_KEYS_DIR?.trim() || void 0,
10140
+ signal: syncAbort.signal,
10141
+ log: logRelay
10142
+ }) : null;
9418
10143
  const syncRuntimeStatus = {
9419
10144
  phase: syncEnabled ? "starting" : "disabled",
9420
10145
  detail: syncEnabled ? "Waiting for viewer startup to finish" : "Sync is disabled"
9421
10146
  };
9422
- const appOpts = {
9423
- accountLink: accountLink.options,
9424
- storeFactory: () => store,
9425
- ...rawEventProcessing.appOptions,
9426
- getSyncRuntimeStatus: () => syncRuntimeStatus
9427
- };
9428
- const app = createApp(appOpts);
10147
+ const appOpts = foregroundAppOptions(store, rawEventProcessing.appOptions, {
10148
+ accountLink,
10149
+ relay,
10150
+ syncRuntimeStatus
10151
+ });
10152
+ const { app, setBoundAddress } = createBoundApp(createApp, appOpts, {
10153
+ invocation,
10154
+ accountLink
10155
+ });
9429
10156
  const pidPath = pidFilePath(dbPath);
9430
10157
  let maintenanceWorker = null;
9431
10158
  let syncServer = null;
@@ -9449,7 +10176,7 @@ async function startForegroundViewer(invocation) {
9449
10176
  hostname: invocation.host,
9450
10177
  port: invocation.port
9451
10178
  }, (info) => {
9452
- accountLink.setBoundPort(info.port);
10179
+ setBoundAddress(info);
9453
10180
  announceViewerStartup({
9454
10181
  pidPath,
9455
10182
  invocation,
@@ -9461,37 +10188,14 @@ async function startForegroundViewer(invocation) {
9461
10188
  const syncStartDelayMs = 3e3;
9462
10189
  p.log.step(`Sync daemon will start in background (${syncStartDelayMs / 1e3}s delay)`);
9463
10190
  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,
10191
+ startServeSyncDaemon({
10192
+ invocation,
10193
+ syncConfig,
10194
+ store,
9471
10195
  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
- }
10196
+ status: syncRuntimeStatus,
10197
+ maintenance: coordinatorMaintenanceDependencies,
10198
+ relay
9495
10199
  });
9496
10200
  }, syncStartDelayMs).unref();
9497
10201
  }
@@ -9513,6 +10217,7 @@ async function startForegroundViewer(invocation) {
9513
10217
  syncAbort.abort();
9514
10218
  try {
9515
10219
  try {
10220
+ if (relay) await relay.close();
9516
10221
  await accountLink.close();
9517
10222
  await stopMaintenanceWorkerProcess(maintenanceWorker, dbPath);
9518
10223
  } finally {
@@ -9698,7 +10403,7 @@ function loadJsoncConfig(path) {
9698
10403
  if (!existsSync(path)) return {};
9699
10404
  return parseJsoncConfig(readFileSync(path, "utf-8"));
9700
10405
  }
9701
- function isRecord(value) {
10406
+ function isRecord$1(value) {
9702
10407
  return value !== null && typeof value === "object" && !Array.isArray(value);
9703
10408
  }
9704
10409
  function rejectDuplicateKeys(node) {
@@ -9721,7 +10426,7 @@ function parseJsoncConfig(raw) {
9721
10426
  const first = errors[0];
9722
10427
  throw new Error(`${printParseErrorCode(first.error)} at offset ${first.offset}`);
9723
10428
  }
9724
- if (!isRecord(parsed)) throw new Error("OpenCode config must be a JSON object");
10429
+ if (!isRecord$1(parsed)) throw new Error("OpenCode config must be a JSON object");
9725
10430
  const tree = parseTree(raw, [], { allowTrailingComma: true });
9726
10431
  if (tree) rejectDuplicateKeys(tree);
9727
10432
  return parsed;
@@ -9735,7 +10440,7 @@ function collectChanges(before, after, path = []) {
9735
10440
  for (const [key, value] of Object.entries(after)) {
9736
10441
  const nextPath = [...path, key];
9737
10442
  const previous = before[key];
9738
- if (isRecord(previous) && isRecord(value)) {
10443
+ if (isRecord$1(previous) && isRecord$1(value)) {
9739
10444
  changes.push(...collectChanges(previous, value, nextPath));
9740
10445
  continue;
9741
10446
  }
@@ -9756,6 +10461,9 @@ function applyChange(raw, change, { format = true } = {}) {
9756
10461
  if (change.value !== void 0) {
9757
10462
  const appended = appendObjectProperty(raw, change);
9758
10463
  if (appended !== void 0) return appended;
10464
+ } else {
10465
+ const removed = removeObjectProperty(raw, change.path);
10466
+ if (removed !== void 0) return removed;
9759
10467
  }
9760
10468
  const options = format ? { formattingOptions } : {};
9761
10469
  return applyEdits(raw, modify(raw, change.path, change.value, options));
@@ -9807,6 +10515,73 @@ function hasCommaToken(raw, start, end) {
9807
10515
  }
9808
10516
  return false;
9809
10517
  }
10518
+ function findCommaOffset(raw, start, end) {
10519
+ const scanner = createScanner(raw);
10520
+ scanner.setPosition(start);
10521
+ while (scanner.getPosition() < end) {
10522
+ scanner.scan();
10523
+ if (scanner.getTokenLength() === 0) return void 0;
10524
+ const tokenStart = scanner.getTokenOffset();
10525
+ if (tokenStart >= end) return void 0;
10526
+ if (raw[tokenStart] === ",") return tokenStart;
10527
+ }
10528
+ }
10529
+ /** Cut [start, end), widening to the whole line when nothing else is on it. */
10530
+ function cutText(raw, start, end) {
10531
+ const lineStart = raw.lastIndexOf("\n", start - 1) + 1;
10532
+ const lineEnd = raw.indexOf("\n", end);
10533
+ const ownsLine = raw.slice(lineStart, start).trim() === "" && lineEnd !== -1 && raw.slice(end, lineEnd).trim() === "";
10534
+ const from = ownsLine ? lineStart : start;
10535
+ const to = ownsLine ? lineEnd + 1 : end;
10536
+ return applyEdits(raw, [{
10537
+ offset: from,
10538
+ length: to - from,
10539
+ content: ""
10540
+ }]);
10541
+ }
10542
+ /**
10543
+ * Remove an object property as a text cut. jsonc-parser's `modify` leaves a
10544
+ * dangling comma (invalid JSONC) when the only property has a trailing comma,
10545
+ * and its formatting option reflows sibling properties. This cuts the property,
10546
+ * its comma, and its line when nothing else is on it, so siblings and comments
10547
+ * keep their text. Returns undefined when the path is not an object property.
10548
+ */
10549
+ function removeObjectProperty(raw, path) {
10550
+ const tree = parseTree(raw, [], { allowTrailingComma: true });
10551
+ const parentNode = tree ? findNodeAtLocation(tree, path.slice(0, -1)) : void 0;
10552
+ const siblings = parentNode?.type === "object" ? parentNode.children ?? [] : [];
10553
+ const index = siblings.findIndex((property) => property.children?.[0]?.value === path.at(-1));
10554
+ const property = siblings[index];
10555
+ if (!parentNode || !property) return void 0;
10556
+ const propertyEnd = property.offset + property.length;
10557
+ const trailingComma = findCommaOffset(raw, propertyEnd, siblings[index + 1]?.offset ?? parentNode.offset + parentNode.length - 1);
10558
+ if (trailingComma !== void 0) return cutText(raw, property.offset, trailingComma + 1);
10559
+ const previous = siblings[index - 1];
10560
+ const leadingComma = previous ? findCommaOffset(raw, previous.offset + previous.length, property.offset) : void 0;
10561
+ if (leadingComma !== void 0) return applyEdits(raw, [{
10562
+ offset: leadingComma,
10563
+ length: propertyEnd - leadingComma,
10564
+ content: ""
10565
+ }]);
10566
+ return cutText(raw, property.offset, propertyEnd);
10567
+ }
10568
+ /** True when the JSONC value at `path` contains a line or block comment. */
10569
+ function jsoncValueHasComments(raw, path) {
10570
+ const tree = parseTree(raw, [], { allowTrailingComma: true });
10571
+ const node = tree ? findNodeAtLocation(tree, path) : void 0;
10572
+ if (!node) return false;
10573
+ const scanner = createScanner(raw);
10574
+ scanner.setPosition(node.offset);
10575
+ const end = node.offset + node.length;
10576
+ while (scanner.getPosition() < end) {
10577
+ scanner.scan();
10578
+ if (scanner.getTokenLength() === 0) return false;
10579
+ const tokenStart = scanner.getTokenOffset();
10580
+ const prefix = raw.slice(tokenStart, tokenStart + 2);
10581
+ if (prefix === "//" || prefix === "/*") return true;
10582
+ }
10583
+ return false;
10584
+ }
9810
10585
  function appendObjectProperty(raw, change) {
9811
10586
  const key = change.path.at(-1);
9812
10587
  if (typeof key !== "string") return void 0;
@@ -9921,6 +10696,188 @@ function writeJsonConfigWithBackup(path, data) {
9921
10696
  writeJsonConfig(path, data);
9922
10697
  }
9923
10698
  //#endregion
10699
+ //#region src/commands/setup-opencode-mcp.ts
10700
+ /** Commands setup has written for OpenCode, across releases. */
10701
+ var MANAGED_COMMANDS = [
10702
+ ["codemem", "mcp"],
10703
+ [
10704
+ "npx",
10705
+ "-y",
10706
+ "--package",
10707
+ "codemem",
10708
+ "--package",
10709
+ "@codemem/embeddings",
10710
+ "codemem",
10711
+ "mcp"
10712
+ ],
10713
+ [
10714
+ "npx",
10715
+ "-y",
10716
+ "codemem",
10717
+ "mcp"
10718
+ ],
10719
+ [
10720
+ "npx",
10721
+ "codemem",
10722
+ "mcp"
10723
+ ],
10724
+ [
10725
+ "uvx",
10726
+ "codemem",
10727
+ "mcp"
10728
+ ]
10729
+ ];
10730
+ /** Fields setup writes (V1 `enabled`, V2 `disabled`); any other field is user data. */
10731
+ var MANAGED_FIELDS = /* @__PURE__ */ new Set([
10732
+ "type",
10733
+ "command",
10734
+ "enabled",
10735
+ "disabled"
10736
+ ]);
10737
+ var V1_CONTAINER_PATH = ["mcp"];
10738
+ var V2_CONTAINER_PATH = ["mcp", "servers"];
10739
+ function isRecord(value) {
10740
+ return value !== null && typeof value === "object" && !Array.isArray(value);
10741
+ }
10742
+ function isExactStringArray$1(value, expected) {
10743
+ return Array.isArray(value) && value.length === expected.length && value.every((entry, index) => entry === expected[index]);
10744
+ }
10745
+ /**
10746
+ * The uv launcher Python-era setup wrote (opencode_integration_cmds.py). Only
10747
+ * this exact command is upgraded: a uvx command with a version pin or extra
10748
+ * arguments such as `--db-path` is user data and is left alone.
10749
+ */
10750
+ function isLegacyUvOpencodeCommand(command) {
10751
+ return isExactStringArray$1(command, [
10752
+ "uvx",
10753
+ "codemem",
10754
+ "mcp"
10755
+ ]);
10756
+ }
10757
+ /** Older single-package npx launchers that `--opencode-mcp stdio` upgrades in place. */
10758
+ function isSinglePackageNpxOpencodeCommand(command) {
10759
+ return isExactStringArray$1(command, [
10760
+ "npx",
10761
+ "-y",
10762
+ "codemem",
10763
+ "mcp"
10764
+ ]) || isExactStringArray$1(command, [
10765
+ "npx",
10766
+ "codemem",
10767
+ "mcp"
10768
+ ]);
10769
+ }
10770
+ /**
10771
+ * Exact commands setup has written, safe to delete. A command with a version
10772
+ * pin or extra arguments (`--from codemem==0.20.0`, `--db-path ...`) is user
10773
+ * data.
10774
+ */
10775
+ function isManagedOpencodeMcpCommand(command) {
10776
+ return MANAGED_COMMANDS.some((expected) => isExactStringArray$1(command, expected));
10777
+ }
10778
+ /**
10779
+ * True when `mcp.servers` is the V2 server map. V1 configs could in theory name
10780
+ * a server "servers"; a value that itself looks like a server entry is V1.
10781
+ */
10782
+ function isV2ServerMap(value) {
10783
+ return isRecord(value) && !("type" in value) && !("command" in value) && !("url" in value);
10784
+ }
10785
+ function usesV2OpencodeMcpShape(config) {
10786
+ return isRecord(config.mcp) && isV2ServerMap(config.mcp.servers);
10787
+ }
10788
+ /** Find every `codemem` MCP entry in the config, V1 first. */
10789
+ function locateOpencodeMcpEntries(config) {
10790
+ const mcp = config.mcp;
10791
+ if (!isRecord(mcp)) return [];
10792
+ const found = [];
10793
+ if ("codemem" in mcp) found.push({
10794
+ shape: "v1",
10795
+ container: mcp,
10796
+ label: "mcp.codemem"
10797
+ });
10798
+ const servers = mcp.servers;
10799
+ if (isV2ServerMap(servers) && "codemem" in servers) found.push({
10800
+ shape: "v2",
10801
+ container: servers,
10802
+ label: "mcp.servers.codemem"
10803
+ });
10804
+ return found;
10805
+ }
10806
+ /**
10807
+ * Explain why an entry is not one setup manages, or return null when it is.
10808
+ * The reason completes the sentence "Left <entry> in place because ...".
10809
+ */
10810
+ function describeUnmanagedOpencodeMcpEntry(entry) {
10811
+ if (!isRecord(entry)) return "it is not an object";
10812
+ if (entry.type === "remote") return "it points to a remote server";
10813
+ if (entry.type !== void 0 && entry.type !== "local") return `it uses type ${JSON.stringify(entry.type)}`;
10814
+ if ("environment" in entry) return "it sets environment variables";
10815
+ if ("cwd" in entry) return "it sets a working directory";
10816
+ if (!isManagedOpencodeMcpCommand(entry.command)) return "it runs a custom command";
10817
+ const extraFields = Object.keys(entry).filter((key) => !MANAGED_FIELDS.has(key));
10818
+ if (extraFields.length > 0) return `it sets ${extraFields.join(", ")}`;
10819
+ return null;
10820
+ }
10821
+ function dropEmptyContainers(config, cleanup, { canDropEmptyContainer }) {
10822
+ const mcp = config.mcp;
10823
+ if (!isRecord(mcp)) return;
10824
+ const removedV2 = cleanup.removed.includes("mcp.servers.codemem");
10825
+ const servers = mcp.servers;
10826
+ if (removedV2 && isRecord(servers) && Object.keys(servers).length === 0 && canDropEmptyContainer(V2_CONTAINER_PATH)) delete mcp.servers;
10827
+ if (Object.keys(mcp).length === 0 && canDropEmptyContainer(V1_CONTAINER_PATH)) delete config.mcp;
10828
+ }
10829
+ /** Deep-copy the parts of the config this module may edit. */
10830
+ function cloneMcpContainers(config) {
10831
+ if (!isRecord(config.mcp)) return { ...config };
10832
+ const mcp = { ...config.mcp };
10833
+ if (isV2ServerMap(mcp.servers)) mcp.servers = { ...mcp.servers };
10834
+ return {
10835
+ ...config,
10836
+ mcp
10837
+ };
10838
+ }
10839
+ /**
10840
+ * Remove managed codemem MCP entries from both config shapes. Returns a new
10841
+ * config; the input is not mutated. Containers emptied by the removal are
10842
+ * deleted only when they held nothing but the codemem entry and the caller
10843
+ * allows it.
10844
+ */
10845
+ function removeManagedOpencodeMcp(config, options) {
10846
+ const next = cloneMcpContainers(config);
10847
+ const cleanup = {
10848
+ config: next,
10849
+ removed: [],
10850
+ kept: []
10851
+ };
10852
+ for (const location of locateOpencodeMcpEntries(next)) {
10853
+ const reason = describeUnmanagedOpencodeMcpEntry(location.container.codemem);
10854
+ if (reason != null) {
10855
+ cleanup.kept.push({
10856
+ label: location.label,
10857
+ reason
10858
+ });
10859
+ continue;
10860
+ }
10861
+ delete location.container.codemem;
10862
+ cleanup.removed.push(location.label);
10863
+ }
10864
+ if (cleanup.removed.length > 0) dropEmptyContainers(next, cleanup, options);
10865
+ return cleanup;
10866
+ }
10867
+ /** The stdio entry `--opencode-mcp stdio` writes, in the file's config shape. */
10868
+ function buildOpencodeStdioMcpEntry(shape, launcher) {
10869
+ const command = [launcher.command, ...launcher.args];
10870
+ if (shape === "v2") return {
10871
+ type: "local",
10872
+ command
10873
+ };
10874
+ return {
10875
+ type: "local",
10876
+ command,
10877
+ enabled: true
10878
+ };
10879
+ }
10880
+ //#endregion
9924
10881
  //#region src/commands/setup.ts
9925
10882
  /**
9926
10883
  * codemem setup — one-command installation for OpenCode plugin + MCP config.
@@ -9929,7 +10886,9 @@ function writeJsonConfigWithBackup(path, data) {
9929
10886
  *
9930
10887
  * What it does:
9931
10888
  * 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
10889
+ * 2. Writes the per-project OpenCode stdio MCP entry (--opencode-mcp stdio). Removal
10890
+ * of that entry for the plugin's built-in tools is implemented but not offered
10891
+ * until a plugin release ships those tools.
9933
10892
  * 3. For Claude Code: installs MCP config and guides marketplace plugin install
9934
10893
  * 4. For Codex: MCP + hooks via CODEX_HOME
9935
10894
  * 5. For pi: packages entry + observer derivation + optional MCP adapter surface
@@ -9981,34 +10940,27 @@ function migrateLegacyOpencodePlugin() {
9981
10940
  function isExactStringArray(value, expected) {
9982
10941
  return Array.isArray(value) && value.length === expected.length && value.every((entry, index) => entry === expected[index]);
9983
10942
  }
9984
- /** Detect and upgrade legacy uvx/uv or managed single-package MCP entries in OpenCode config. */
10943
+ /**
10944
+ * Detect and upgrade legacy uvx/uv or managed single-package MCP entries in
10945
+ * OpenCode config, in either the V1 (`mcp.codemem`) or V2
10946
+ * (`mcp.servers.codemem`) shape. Used only by `--opencode-mcp stdio`.
10947
+ */
9985
10948
  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) {
10949
+ let migrated = false;
10950
+ for (const { container } of locateOpencodeMcpEntries(config)) {
10951
+ const entry = container.codemem;
10952
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
10953
+ const command = entry.command;
10954
+ if (!isLegacyUvOpencodeCommand(command) && !isSinglePackageNpxOpencodeCommand(command)) continue;
10003
10955
  p.log.step("Upgrading managed MCP entry to the current npm launcher");
10004
10956
  const resolvedLauncher = launcher ?? codememMcpLauncher();
10005
- mcpConfig.codemem = {
10957
+ container.codemem = {
10006
10958
  ...entry,
10007
10959
  command: [resolvedLauncher.command, ...resolvedLauncher.args]
10008
10960
  };
10009
- return true;
10961
+ migrated = true;
10010
10962
  }
10011
- return false;
10963
+ return migrated;
10012
10964
  }
10013
10965
  /** Detect and upgrade legacy uvx or managed single-package MCP entries in Claude settings. */
10014
10966
  function migrateLegacyClaudeMcp(settings, { launcher } = {}) {
@@ -10073,30 +11025,34 @@ function installPlugin(force) {
10073
11025
  };
10074
11026
  }
10075
11027
  }
10076
- function installMcp(force, { createBackup = true } = {}) {
10077
- const configPath = resolveOpencodeConfigPath(opencodeConfigDir());
10078
- let config;
11028
+ function loadOpencodeConfigOrLog(configPath) {
10079
11029
  try {
10080
- config = loadJsoncConfig(configPath);
11030
+ return loadJsoncConfig(configPath);
10081
11031
  } catch (err) {
10082
11032
  p.log.error(`Failed to parse ${configPath}: ${err instanceof Error ? err.message : String(err)}`);
10083
- return false;
11033
+ return null;
10084
11034
  }
10085
- let mcpConfig = config.mcp;
10086
- if (mcpConfig == null || typeof mcpConfig !== "object" || Array.isArray(mcpConfig)) mcpConfig = {};
11035
+ }
11036
+ /** Container for a new stdio entry: `mcp.servers` when the file already uses it. */
11037
+ function opencodeStdioContainer(config) {
11038
+ const mcp = config.mcp != null && typeof config.mcp === "object" && !Array.isArray(config.mcp) ? config.mcp : {};
11039
+ config.mcp = mcp;
11040
+ if (!usesV2OpencodeMcpShape(config)) return mcp;
11041
+ return mcp.servers;
11042
+ }
11043
+ /** `--opencode-mcp stdio`: write the per-project stdio MCP entry as setup used to. */
11044
+ function installStdioMcp(force, { createBackup = true } = {}) {
11045
+ const configPath = resolveOpencodeConfigPath(opencodeConfigDir());
11046
+ const config = loadOpencodeConfigOrLog(configPath);
11047
+ if (config == null) return false;
10087
11048
  const migrated = migrateLegacyOpencodeMcp(config);
10088
- if ("codemem" in mcpConfig && !force && !migrated) {
11049
+ if (locateOpencodeMcpEntries(config).length > 0 && !force && !migrated) {
10089
11050
  p.log.info(`MCP entry already exists in ${configPath}`);
10090
11051
  return true;
10091
11052
  }
10092
11053
  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;
11054
+ const shape = usesV2OpencodeMcpShape(config) ? "v2" : "v1";
11055
+ opencodeStdioContainer(config).codemem = buildOpencodeStdioMcpEntry(shape, codememMcpLauncher());
10100
11056
  }
10101
11057
  try {
10102
11058
  writeJsonConfig(configPath, config, { createBackup });
@@ -10107,6 +11063,35 @@ function installMcp(force, { createBackup = true } = {}) {
10107
11063
  }
10108
11064
  return true;
10109
11065
  }
11066
+ function reportKeptOpencodeMcpEntries(configPath, kept) {
11067
+ 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.`);
11068
+ }
11069
+ /**
11070
+ * Remove the stdio entries setup wrote, for users of the plugin's built-in
11071
+ * memory tools (served through the shared viewer). Reached only through the
11072
+ * internal `native` mode, which the CLI accepts once the plugin ships those tools.
11073
+ */
11074
+ function removeOpencodeMcp({ createBackup = true } = {}) {
11075
+ const configPath = resolveOpencodeConfigPath(opencodeConfigDir());
11076
+ const config = loadOpencodeConfigOrLog(configPath);
11077
+ if (config == null) return false;
11078
+ const raw = existsSync(configPath) ? readFileSync(configPath, "utf-8") : "{}";
11079
+ const cleanup = removeManagedOpencodeMcp(config, { canDropEmptyContainer: (path) => !jsoncValueHasComments(raw, path) });
11080
+ reportKeptOpencodeMcpEntries(configPath, cleanup.kept);
11081
+ if (cleanup.removed.length === 0) {
11082
+ if (cleanup.kept.length === 0) p.log.info("No codemem MCP entry to remove; the plugin's built-in memory tools are used");
11083
+ return true;
11084
+ }
11085
+ try {
11086
+ writeJsonConfig(configPath, cleanup.config, { createBackup });
11087
+ } catch (err) {
11088
+ p.log.error(`Failed to write ${configPath}: ${err instanceof Error ? err.message : String(err)}`);
11089
+ return false;
11090
+ }
11091
+ p.log.success(`Removed the codemem MCP entry ${cleanup.removed.join(" and ")} from ${configPath} (backup: ${configPath}.codemem.bak)`);
11092
+ 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.");
11093
+ return true;
11094
+ }
10110
11095
  function isClaudeHooksPluginInstalled() {
10111
11096
  const pluginDir = join(claudeConfigDir(), "plugins", "codemem");
10112
11097
  if (existsSync(pluginDir)) return true;
@@ -10809,6 +11794,8 @@ function installPi(options = {}) {
10809
11794
  }
10810
11795
  return ok;
10811
11796
  }
11797
+ var OPENCODE_MCP_MODES = ["stdio"];
11798
+ var DEFAULT_OPENCODE_MCP_MODE = "stdio";
10812
11799
  function maybeInstallPi(opts, onlyFlag, force) {
10813
11800
  if (!(opts.piOnly || !onlyFlag && isPiDetected())) return true;
10814
11801
  p.log.step("Configuring pi (extension package + observer)...");
@@ -10818,11 +11805,17 @@ function maybeInstallPi(opts, onlyFlag, force) {
10818
11805
  piExtensionPath: opts.piExtensionPath
10819
11806
  });
10820
11807
  }
10821
- function installOpencodeSetup(force) {
11808
+ function installOpencodeSetup(force, opencodeMcp) {
10822
11809
  p.log.step("Installing OpenCode plugin...");
10823
11810
  const pluginResult = installPlugin(force);
11811
+ if (!pluginResult.ok) return false;
11812
+ const createBackup = !pluginResult.wrote;
11813
+ if ((opencodeMcp ?? DEFAULT_OPENCODE_MCP_MODE) === "native") {
11814
+ p.log.step("Checking OpenCode MCP config...");
11815
+ return removeOpencodeMcp({ createBackup });
11816
+ }
10824
11817
  p.log.step("Installing OpenCode MCP config...");
10825
- return pluginResult.ok && installMcp(force, { createBackup: !pluginResult.wrote });
11818
+ return installStdioMcp(force, { createBackup });
10826
11819
  }
10827
11820
  function installClaudeSetup(force) {
10828
11821
  p.log.step("Installing Claude Code MCP config...");
@@ -10840,12 +11833,20 @@ function installCodexSetup(force) {
10840
11833
  function runSetupInstalls(opts, force) {
10841
11834
  const onlyFlag = Boolean(opts.opencodeOnly || opts.claudeOnly || opts.codexOnly || opts.piOnly);
10842
11835
  let ok = true;
10843
- if (opts.opencodeOnly || !onlyFlag) ok = installOpencodeSetup(force) && ok;
11836
+ if (opts.opencodeOnly || !onlyFlag) ok = installOpencodeSetup(force, opts.opencodeMcp) && ok;
10844
11837
  if (opts.claudeOnly || !onlyFlag) ok = installClaudeSetup(force) && ok;
10845
11838
  if (opts.codexOnly || !onlyFlag && existsSync(codexConfigDir())) ok = installCodexSetup(force) && ok;
10846
11839
  return maybeInstallPi(opts, onlyFlag, force) && ok;
10847
11840
  }
11841
+ function isKnownOpencodeMcpMode(mode) {
11842
+ return mode === void 0 || OPENCODE_MCP_MODES.includes(mode);
11843
+ }
10848
11844
  function runSetup(opts) {
11845
+ if (!isKnownOpencodeMcpMode(opts.opencodeMcp)) {
11846
+ p.log.error(`Unknown --opencode-mcp mode "${opts.opencodeMcp}". Supported: ${OPENCODE_MCP_MODES.join(", ")}`);
11847
+ process.exitCode = 2;
11848
+ return;
11849
+ }
10849
11850
  p.intro(`codemem setup v${VERSION}`);
10850
11851
  if (runSetupInstalls(opts, opts.force ?? false)) {
10851
11852
  p.outro("Setup complete — restart your editor to load the plugin");
@@ -10854,7 +11855,7 @@ function runSetup(opts) {
10854
11855
  p.outro("Setup completed with warnings");
10855
11856
  process.exitCode = 1;
10856
11857
  }
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) => {
11858
+ 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
11859
  runSetup(opts);
10859
11860
  });
10860
11861
  //#endregion
@@ -11327,6 +12328,169 @@ function collectAdvertiseAddresses(explicitAddress, configuredHost, port, interf
11327
12328
  return [...new Set(addresses)];
11328
12329
  }
11329
12330
  //#endregion
12331
+ //#region src/commands/sync-relay-keys.ts
12332
+ /**
12333
+ * `codemem sync relay-keys` lists relay service key pins, and `codemem sync approve-relay-key` approves a changed key.
12334
+ */
12335
+ /** Expected refusal with a stable error code and exit status. */
12336
+ var RelayKeyRefusal = class extends Error {
12337
+ code;
12338
+ exitCode;
12339
+ constructor(code, message, exitCode = 1) {
12340
+ super(message);
12341
+ this.code = code;
12342
+ this.exitCode = exitCode;
12343
+ }
12344
+ };
12345
+ function pinJson(pin) {
12346
+ return {
12347
+ coordinator_id: pin.coordinatorId,
12348
+ group_id: pin.groupId,
12349
+ state: pin.state,
12350
+ pinned_key: pin.pinnedKey,
12351
+ first_seen_at: pin.firstSeenAt,
12352
+ candidate_key: pin.candidateKey,
12353
+ candidate_seen_at: pin.candidateSeenAt,
12354
+ last_candidate_key: pin.lastCandidateKey,
12355
+ last_candidate_seen_at: pin.lastCandidateSeenAt
12356
+ };
12357
+ }
12358
+ function pinText(pin) {
12359
+ const lines = [
12360
+ `${pin.groupId} (${pin.coordinatorId})`,
12361
+ ` state: ${pin.state === "pending_change" ? "paused, key change pending approval" : "pinned"}`,
12362
+ ` pinned key: ${pin.pinnedKey} (since ${pin.firstSeenAt})`
12363
+ ];
12364
+ if (pin.candidateKey) lines.push(` candidate: ${pin.candidateKey} (seen ${pin.candidateSeenAt})`);
12365
+ if (pin.lastCandidateKey) lines.push(` last candidate: ${pin.lastCandidateKey} (seen ${pin.lastCandidateSeenAt}, not approved)`);
12366
+ return lines.join("\n");
12367
+ }
12368
+ function withStore(opts, run) {
12369
+ const store = new MemoryStore(resolveDbPath(resolveDbOpt(opts)));
12370
+ try {
12371
+ return run(store.db);
12372
+ } finally {
12373
+ store.close();
12374
+ }
12375
+ }
12376
+ function reportFailure(opts, error) {
12377
+ const refusal = error instanceof RelayKeyRefusal ? error : new RelayKeyRefusal("relay_keys_failed", error instanceof Error ? error.message : String(error));
12378
+ if (opts.json) {
12379
+ emitJsonError(refusal.code, refusal.message, refusal.exitCode);
12380
+ return;
12381
+ }
12382
+ p.log.error(refusal.message);
12383
+ process.exitCode = refusal.exitCode;
12384
+ }
12385
+ function listPins(opts) {
12386
+ const pins = withStore(opts, listRelayServicePins);
12387
+ if (opts.json) {
12388
+ console.log(JSON.stringify(pins.map(pinJson), null, 2));
12389
+ return;
12390
+ }
12391
+ p.intro("codemem sync relay-keys");
12392
+ if (pins.length === 0) {
12393
+ p.outro("No relay service keys pinned");
12394
+ return;
12395
+ }
12396
+ for (const pin of pins) p.log.message(pinText(pin));
12397
+ const pending = pins.filter((pin) => pin.state === "pending_change").length;
12398
+ p.outro(`${pins.length} pin(s), ${pending} pending approval`);
12399
+ }
12400
+ function configuredCoordinatorId(configPath) {
12401
+ const config = configPath ? readCodememConfigFileAtPath(configPath) : readCodememConfigFile();
12402
+ const endpoint = relayCoordinatorEndpoint(readCoordinatorSyncConfig(config).syncCoordinatorUrl);
12403
+ if (!endpoint) throw new RelayKeyRefusal("coordinator_not_configured", "Relay needs sync_coordinator_url set to an https:// origin with no path.");
12404
+ return endpoint.coordinatorId;
12405
+ }
12406
+ function pendingPin(db, coordinatorId, groupId) {
12407
+ const pin = readRelayServicePin(db, coordinatorId, groupId);
12408
+ if (pin?.state !== "pending_change" || !pin.candidateKey) throw new RelayKeyRefusal("nothing_pending", `No relay service key change is pending for group ${groupId}.`);
12409
+ return {
12410
+ ...pin,
12411
+ candidateKey: pin.candidateKey
12412
+ };
12413
+ }
12414
+ function keysText(pin) {
12415
+ return `pinned key: ${pin.pinnedKey}\ncandidate: ${pin.candidateKey}`;
12416
+ }
12417
+ /** The candidate the user approved: `--key`, or the shown candidate after an interactive confirmation. */
12418
+ async function chosenCandidate(pin, opts) {
12419
+ if (opts.key !== void 0) {
12420
+ const key = canonicalRelayServiceKey(opts.key);
12421
+ if (!key) throw new RelayKeyRefusal("invalid_key", "--key is not an ssh-ed25519 key.", 2);
12422
+ if (key !== pin.candidateKey) throw new RelayKeyRefusal("candidate_mismatch", `--key does not match the pending candidate. Nothing changed.\n${keysText(pin)}`);
12423
+ return key;
12424
+ }
12425
+ 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);
12426
+ p.log.message(keysText(pin), { output: process.stderr });
12427
+ return await p.confirm({
12428
+ message: "Trust the candidate relay service key? Check it with your coordinator operator first.",
12429
+ initialValue: false,
12430
+ output: process.stderr
12431
+ }) === true ? pin.candidateKey : null;
12432
+ }
12433
+ async function approvePin(groupId, opts) {
12434
+ const coordinatorId = configuredCoordinatorId(opts.config);
12435
+ const store = new MemoryStore(resolveDbPath(resolveDbOpt(opts)));
12436
+ try {
12437
+ const pin = pendingPin(store.db, coordinatorId, groupId);
12438
+ const candidateKey = await chosenCandidate(pin, opts);
12439
+ if (!candidateKey) {
12440
+ p.log.info("Nothing changed.", { output: process.stderr });
12441
+ return;
12442
+ }
12443
+ if (!approveRelayServiceKey(store.db, {
12444
+ coordinatorId,
12445
+ groupId,
12446
+ candidateKey
12447
+ })) throw new RelayKeyRefusal("candidate_changed", "The pending candidate changed. Nothing changed; list the pins again.");
12448
+ reportApproved(opts, {
12449
+ coordinatorId,
12450
+ groupId,
12451
+ previousKey: pin.pinnedKey,
12452
+ candidateKey
12453
+ });
12454
+ } finally {
12455
+ store.close();
12456
+ }
12457
+ }
12458
+ function reportApproved(opts, result) {
12459
+ if (opts.json) {
12460
+ console.log(JSON.stringify({
12461
+ ok: true,
12462
+ coordinator_id: result.coordinatorId,
12463
+ group_id: result.groupId,
12464
+ pinned_key: result.candidateKey,
12465
+ previous_key: result.previousKey
12466
+ }, null, 2));
12467
+ return;
12468
+ }
12469
+ p.log.success(`Pinned ${result.candidateKey} for group ${result.groupId}`);
12470
+ p.log.info("A running viewer resumes relay for this group after its next coordinator refresh.");
12471
+ }
12472
+ var relayKeysCommand = new Command("relay-keys").configureHelp(helpStyle).description("List relay service key pins");
12473
+ addDbOption(relayKeysCommand);
12474
+ addJsonOption(relayKeysCommand);
12475
+ relayKeysCommand.action((opts) => {
12476
+ try {
12477
+ listPins(opts);
12478
+ } catch (error) {
12479
+ reportFailure(opts, error);
12480
+ }
12481
+ });
12482
+ 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");
12483
+ addDbOption(approveRelayKeyCommand);
12484
+ addConfigOption(approveRelayKeyCommand);
12485
+ addJsonOption(approveRelayKeyCommand);
12486
+ approveRelayKeyCommand.action(async (groupId, opts) => {
12487
+ try {
12488
+ await approvePin(groupId, opts);
12489
+ } catch (error) {
12490
+ reportFailure(opts, error);
12491
+ }
12492
+ });
12493
+ //#endregion
11330
12494
  //#region src/commands/sync.ts
11331
12495
  /**
11332
12496
  * Sync CLI commands — enable/disable/status/peers/connect.
@@ -12126,6 +13290,8 @@ peersRemoveCmd.action((peerRef, opts) => {
12126
13290
  });
12127
13291
  peersCommand.addCommand(peersRemoveCmd);
12128
13292
  syncCommand.addCommand(peersCommand);
13293
+ syncCommand.addCommand(relayKeysCommand);
13294
+ syncCommand.addCommand(approveRelayKeyCommand);
12129
13295
  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
13296
  addDbOption(bootstrapCmd);
12131
13297
  addJsonOption(bootstrapCmd);
@@ -13129,6 +14295,7 @@ var versionCommand = new Command("version").configureHelp(helpStyle).description
13129
14295
  * until `registerRootCommands` is called.
13130
14296
  */
13131
14297
  var ROOT_COMPLETION_COMMANDS = [
14298
+ "capture",
13132
14299
  "config",
13133
14300
  "coordinator",
13134
14301
  "db",
@@ -13184,6 +14351,7 @@ function registerMemoryGroupWrappers() {
13184
14351
  /** Register every root command (visible and hidden) on the given program. */
13185
14352
  function registerRootCommands(program) {
13186
14353
  registerMemoryGroupWrappers();
14354
+ program.addCommand(captureCommand);
13187
14355
  program.addCommand(serveCommand);
13188
14356
  program.addCommand(configCommand);
13189
14357
  program.addCommand(coordinatorCommand);
@@ -13209,6 +14377,7 @@ function registerRootCommands(program) {
13209
14377
  program.addCommand(piSessionSearchCommand);
13210
14378
  program.addCommand(piImportSessionsCommand);
13211
14379
  program.addCommand(promptPackLedgerCommand, { hidden: true });
14380
+ program.addCommand(memoryToolCommand, { hidden: true });
13212
14381
  program.addCommand(showMemoryCommand, { hidden: true });
13213
14382
  program.addCommand(forgetMemoryCommand, { hidden: true });
13214
14383
  program.addCommand(rememberMemoryCommand, { hidden: true });