@memrosetta/cli 0.4.2 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,42 @@
1
+ // src/version.ts
2
+ import { existsSync, readFileSync } from "fs";
3
+ import { dirname, join } from "path";
4
+ import { fileURLToPath } from "url";
5
+ import { createRequire } from "module";
6
+ function resolveCliVersion() {
7
+ const strategies = [
8
+ () => {
9
+ const require2 = createRequire(import.meta.url);
10
+ return require2("../../package.json").version;
11
+ },
12
+ () => {
13
+ const require2 = createRequire(import.meta.url);
14
+ return require2("@memrosetta/cli/package.json").version;
15
+ },
16
+ () => {
17
+ const dir = dirname(fileURLToPath(import.meta.url));
18
+ for (let d = dir, i = 0; i < 5; i++) {
19
+ const candidate = join(d, "package.json");
20
+ if (existsSync(candidate)) {
21
+ const pkg = JSON.parse(readFileSync(candidate, "utf-8"));
22
+ if (pkg.name?.includes("memrosetta") && pkg.version) {
23
+ return pkg.version;
24
+ }
25
+ }
26
+ d = dirname(d);
27
+ }
28
+ throw new Error("not found");
29
+ }
30
+ ];
31
+ for (const strategy of strategies) {
32
+ try {
33
+ return strategy();
34
+ } catch {
35
+ }
36
+ }
37
+ return "unknown";
38
+ }
39
+
40
+ export {
41
+ resolveCliVersion
42
+ };
package/dist/index.js CHANGED
@@ -56,12 +56,16 @@ Global Options:
56
56
  --version, -v Show version
57
57
 
58
58
  Sync Subcommands:
59
- memrosetta sync enable --server <url> # Enable sync, hidden API key prompt
60
- memrosetta sync enable --server <url> --key-stdin # Read API key from stdin
61
- memrosetta sync disable # Disable sync (keeps server/key)
59
+ memrosetta sync enable --server <url> [key-source]
60
+ Key sources (mutually exclusive, exactly one):
61
+ --key <value> Direct (visible in shell history)
62
+ --key-stdin Read from stdin (echo key | memrosetta ...)
63
+ --key-file <path> Read from file
64
+ MEMROSETTA_SYNC_API_KEY Environment variable (fallback)
65
+ (no flag) POSIX TTY only: hidden prompt
66
+ memrosetta sync disable # Disable (keeps server/key)
62
67
  memrosetta sync status # Show sync state + pending ops
63
- memrosetta sync now # Push + pull now
64
- memrosetta sync now --push-only # Push only
68
+ memrosetta sync now [--push-only | --pull-only]
65
69
  memrosetta sync device-id # Print current device id
66
70
 
67
71
  Examples:
@@ -165,7 +169,7 @@ async function main() {
165
169
  break;
166
170
  }
167
171
  case "status": {
168
- const mod = await import("./status-TVY32MZD.js");
172
+ const mod = await import("./status-HLKL32NP.js");
169
173
  await mod.run(commandOptions);
170
174
  break;
171
175
  }
@@ -180,12 +184,12 @@ async function main() {
180
184
  break;
181
185
  }
182
186
  case "update": {
183
- const mod = await import("./update-M74FBMYN.js");
187
+ const mod = await import("./update-4F3YY2HU.js");
184
188
  await mod.run();
185
189
  break;
186
190
  }
187
191
  case "sync": {
188
- const mod = await import("./sync-7TONPJBY.js");
192
+ const mod = await import("./sync-GMGC66NK.js");
189
193
  await mod.run(commandOptions);
190
194
  break;
191
195
  }
@@ -0,0 +1,184 @@
1
+ import {
2
+ isClaudeCodeConfigured,
3
+ isCodexConfigured,
4
+ isCursorConfigured,
5
+ isGeminiConfigured,
6
+ isGenericMCPConfigured
7
+ } from "./chunk-IS4IKWPL.js";
8
+ import {
9
+ resolveCliVersion
10
+ } from "./chunk-YXK6FDB6.js";
11
+ import {
12
+ getDefaultDbPath
13
+ } from "./chunk-72IW6TAV.js";
14
+ import {
15
+ output
16
+ } from "./chunk-ET6TNQOJ.js";
17
+ import {
18
+ getConfig
19
+ } from "./chunk-SEPYQK3J.js";
20
+
21
+ // src/commands/status.ts
22
+ import { existsSync, statSync } from "fs";
23
+ async function run(options) {
24
+ const { format, db, noEmbeddings } = options;
25
+ const config = getConfig();
26
+ const dbPath = db ?? config.dbPath ?? getDefaultDbPath();
27
+ const exists = existsSync(dbPath);
28
+ let sizeBytes = 0;
29
+ let sizeFormatted = "0B";
30
+ let memoryCount = 0;
31
+ let userList = [];
32
+ let qualityFresh = 0;
33
+ let qualityInvalidated = 0;
34
+ let qualityWithRelations = 0;
35
+ let qualityAvgActivation = 0;
36
+ const embeddingsEnabled = !noEmbeddings && config.enableEmbeddings !== false;
37
+ if (exists) {
38
+ const stat = statSync(dbPath);
39
+ sizeBytes = stat.size;
40
+ sizeFormatted = formatSize(sizeBytes);
41
+ try {
42
+ const Database = (await import("better-sqlite3")).default;
43
+ const dbConn = new Database(dbPath);
44
+ dbConn.pragma("journal_mode = WAL");
45
+ const countRow = dbConn.prepare("SELECT COUNT(*) as count FROM memories").get();
46
+ memoryCount = countRow.count;
47
+ const userRows = dbConn.prepare("SELECT DISTINCT user_id FROM memories ORDER BY user_id").all();
48
+ userList = userRows.map((r) => r.user_id);
49
+ const freshRow = dbConn.prepare(
50
+ "SELECT COUNT(*) as c FROM memories WHERE is_latest = 1 AND invalidated_at IS NULL"
51
+ ).get();
52
+ qualityFresh = freshRow.c;
53
+ const invalidatedRow = dbConn.prepare(
54
+ "SELECT COUNT(*) as c FROM memories WHERE invalidated_at IS NOT NULL"
55
+ ).get();
56
+ qualityInvalidated = invalidatedRow.c;
57
+ const relationsRow = dbConn.prepare(
58
+ "SELECT COUNT(DISTINCT src_memory_id) + COUNT(DISTINCT dst_memory_id) as c FROM memory_relations"
59
+ ).get();
60
+ qualityWithRelations = relationsRow.c;
61
+ const avgRow = dbConn.prepare(
62
+ "SELECT AVG(activation_score) as avg FROM memories WHERE is_latest = 1"
63
+ ).get();
64
+ qualityAvgActivation = avgRow.avg ?? 0;
65
+ dbConn.close();
66
+ } catch {
67
+ }
68
+ }
69
+ const claudeCodeStatus = isClaudeCodeConfigured();
70
+ const cursorStatus = isCursorConfigured();
71
+ const codexStatus = isCodexConfigured();
72
+ const geminiStatus = isGeminiConfigured();
73
+ const mcpStatus = isGenericMCPConfigured();
74
+ if (format === "text") {
75
+ process.stdout.write("MemRosetta Status\n");
76
+ process.stdout.write(`${"=".repeat(40)}
77
+
78
+ `);
79
+ process.stdout.write(
80
+ `Database: ${dbPath} (${exists ? `exists, ${sizeFormatted}` : "not found"})
81
+ `
82
+ );
83
+ process.stdout.write(`Memories: ${memoryCount}
84
+ `);
85
+ if (userList.length > 0) {
86
+ process.stdout.write(
87
+ `Users: ${userList.length} (${userList.join(", ")})
88
+ `
89
+ );
90
+ } else {
91
+ process.stdout.write("Users: 0\n");
92
+ }
93
+ const embeddingModelLabel = getEmbeddingModelLabel();
94
+ process.stdout.write(
95
+ `Embeddings: ${embeddingsEnabled ? `enabled (${embeddingModelLabel})` : "disabled"}
96
+ `
97
+ );
98
+ if (memoryCount > 0) {
99
+ process.stdout.write("\nQuality:\n");
100
+ process.stdout.write(
101
+ ` Fresh (is_latest=1): ${qualityFresh} / ${memoryCount}
102
+ `
103
+ );
104
+ process.stdout.write(` Invalidated: ${qualityInvalidated}
105
+ `);
106
+ process.stdout.write(` With relations: ${qualityWithRelations}
107
+ `);
108
+ process.stdout.write(
109
+ ` Avg activation: ${qualityAvgActivation.toFixed(2)}
110
+ `
111
+ );
112
+ }
113
+ process.stdout.write("\nIntegrations:\n");
114
+ process.stdout.write(
115
+ ` Claude Code: ${claudeCodeStatus ? "configured (hooks + MCP)" : "not configured"}
116
+ `
117
+ );
118
+ process.stdout.write(
119
+ ` Cursor: ${cursorStatus ? "configured (MCP)" : "not configured"}
120
+ `
121
+ );
122
+ process.stdout.write(
123
+ ` Codex: ${codexStatus ? "configured (MCP)" : "not configured"}
124
+ `
125
+ );
126
+ process.stdout.write(
127
+ ` Gemini: ${geminiStatus ? "configured (MCP)" : "not configured"}
128
+ `
129
+ );
130
+ process.stdout.write(
131
+ ` MCP (generic): ${mcpStatus ? "configured" : "not configured"}
132
+ `
133
+ );
134
+ return;
135
+ }
136
+ output(
137
+ {
138
+ version: resolveCliVersion(),
139
+ database: {
140
+ path: dbPath,
141
+ exists,
142
+ sizeBytes,
143
+ sizeFormatted
144
+ },
145
+ memories: memoryCount,
146
+ users: userList,
147
+ quality: {
148
+ fresh: qualityFresh,
149
+ invalidated: qualityInvalidated,
150
+ withRelations: qualityWithRelations,
151
+ avgActivation: qualityAvgActivation
152
+ },
153
+ embeddings: embeddingsEnabled,
154
+ embeddingModel: getEmbeddingModelLabel(),
155
+ embeddingPreset: getConfig().embeddingPreset ?? "en",
156
+ integrations: {
157
+ claudeCode: claudeCodeStatus,
158
+ cursor: cursorStatus,
159
+ codex: codexStatus,
160
+ gemini: geminiStatus,
161
+ mcp: mcpStatus
162
+ }
163
+ },
164
+ format
165
+ );
166
+ }
167
+ function formatSize(bytes) {
168
+ if (bytes < 1024) return `${bytes}B`;
169
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
170
+ return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
171
+ }
172
+ var PRESET_MODEL_LABELS = {
173
+ en: "bge-small-en-v1.5",
174
+ multilingual: "multilingual-e5-small",
175
+ ko: "ko-sroberta-multitask"
176
+ };
177
+ function getEmbeddingModelLabel() {
178
+ const config = getConfig();
179
+ const preset = config.embeddingPreset ?? "en";
180
+ return PRESET_MODEL_LABELS[preset] ?? preset;
181
+ }
182
+ export {
183
+ run
184
+ };
@@ -0,0 +1,386 @@
1
+ import {
2
+ hasFlag,
3
+ optionalOption,
4
+ requireOption
5
+ } from "./chunk-NU5ZJJXP.js";
6
+ import {
7
+ output,
8
+ outputError
9
+ } from "./chunk-ET6TNQOJ.js";
10
+ import {
11
+ getConfig,
12
+ getDefaultDbPath,
13
+ writeConfig
14
+ } from "./chunk-SEPYQK3J.js";
15
+
16
+ // src/commands/sync.ts
17
+ import { randomUUID } from "crypto";
18
+ import { readFileSync } from "fs";
19
+ import { userInfo, platform } from "os";
20
+ import { createInterface } from "readline";
21
+ var ENV_API_KEY = "MEMROSETTA_SYNC_API_KEY";
22
+ var KEY_SOURCE_HINT = [
23
+ "API key required. Use exactly one of:",
24
+ " --key <value> (direct, visible in history)",
25
+ " --key-stdin (pipe from stdin)",
26
+ " --key-file <path> (read from file)",
27
+ ` ${ENV_API_KEY}=<value> (environment variable)`,
28
+ "",
29
+ "On POSIX TTYs an interactive hidden prompt is also available.",
30
+ "See: memrosetta sync enable --help"
31
+ ].join("\n");
32
+ function parseSubcommand(args) {
33
+ const first = args[0];
34
+ if (!first || first.startsWith("--")) return null;
35
+ if (first === "enable" || first === "disable" || first === "status" || first === "now" || first === "device-id") {
36
+ return first;
37
+ }
38
+ return null;
39
+ }
40
+ var CONTROL_CHAR_REGEX = /[\x00-\x1F\x7F]/;
41
+ function validateApiKey(key, sourceLabel) {
42
+ const trimmed = key.trim();
43
+ if (trimmed.length === 0) {
44
+ throw new Error(`API key from ${sourceLabel} is empty.`);
45
+ }
46
+ if (CONTROL_CHAR_REGEX.test(trimmed)) {
47
+ throw new Error(
48
+ `API key from ${sourceLabel} contains control characters. Try --key-file or MEMROSETTA_SYNC_API_KEY instead.`
49
+ );
50
+ }
51
+ return trimmed;
52
+ }
53
+ function readKeyFile(path) {
54
+ try {
55
+ return readFileSync(path, "utf-8");
56
+ } catch (err) {
57
+ const msg = err instanceof Error ? err.message : String(err);
58
+ throw new Error(`Could not read --key-file '${path}': ${msg}`);
59
+ }
60
+ }
61
+ async function resolveApiKey(args) {
62
+ const directKey = optionalOption(args, "--key");
63
+ const keyFile = optionalOption(args, "--key-file");
64
+ const useStdin = hasFlag(args, "--key-stdin");
65
+ const explicitCount = [directKey !== void 0, keyFile !== void 0, useStdin].filter(Boolean).length;
66
+ if (explicitCount > 1) {
67
+ throw new Error(
68
+ "Specify only one of --key, --key-stdin, --key-file."
69
+ );
70
+ }
71
+ if (directKey !== void 0) {
72
+ return validateApiKey(directKey, "--key");
73
+ }
74
+ if (useStdin) {
75
+ const raw = await readStdinKey();
76
+ if (!raw) {
77
+ throw new Error(
78
+ "--key-stdin produced no input. On Windows PowerShell, prefer --key-file or MEMROSETTA_SYNC_API_KEY."
79
+ );
80
+ }
81
+ return validateApiKey(raw, "--key-stdin");
82
+ }
83
+ if (keyFile !== void 0) {
84
+ return validateApiKey(readKeyFile(keyFile), `--key-file ${keyFile}`);
85
+ }
86
+ const envKey = process.env[ENV_API_KEY];
87
+ if (envKey !== void 0 && envKey.length > 0) {
88
+ return validateApiKey(envKey, ENV_API_KEY);
89
+ }
90
+ if (platform() !== "win32" && process.stdin.isTTY) {
91
+ const raw = await readHiddenInput("API key: ");
92
+ return validateApiKey(raw, "hidden prompt");
93
+ }
94
+ throw new Error(KEY_SOURCE_HINT);
95
+ }
96
+ async function readHiddenInput(prompt) {
97
+ const stdin = process.stdin;
98
+ const stdout = process.stdout;
99
+ if (!stdin.isTTY) {
100
+ throw new Error("Interactive input requires a TTY. Use --key-stdin to pipe the key instead.");
101
+ }
102
+ stdout.write(prompt);
103
+ const originalWrite = stdout.write.bind(stdout);
104
+ let muted = true;
105
+ stdout.write = (chunk, ...rest) => {
106
+ if (!muted) {
107
+ return originalWrite(chunk, ...rest);
108
+ }
109
+ const str = typeof chunk === "string" ? chunk : chunk?.toString?.("utf-8") ?? "";
110
+ if (str === "\n" || str === "\r\n" || str === "\r") {
111
+ return originalWrite(chunk, ...rest);
112
+ }
113
+ return true;
114
+ };
115
+ const rl = createInterface({
116
+ input: stdin,
117
+ output: stdout,
118
+ terminal: true
119
+ });
120
+ try {
121
+ const answer = await new Promise((resolve, reject) => {
122
+ rl.once("close", () => {
123
+ reject(new Error("Aborted"));
124
+ });
125
+ rl.question("", (value) => {
126
+ resolve(value);
127
+ });
128
+ });
129
+ return answer;
130
+ } finally {
131
+ muted = false;
132
+ stdout.write = originalWrite;
133
+ rl.close();
134
+ }
135
+ }
136
+ async function readStdinKey() {
137
+ const chunks = [];
138
+ for await (const chunk of process.stdin) {
139
+ chunks.push(chunk);
140
+ }
141
+ return Buffer.concat(chunks).toString("utf-8").trim();
142
+ }
143
+ async function testConnection(serverUrl, apiKey) {
144
+ const url = `${serverUrl.replace(/\/$/, "")}/sync/health`;
145
+ try {
146
+ const res = await fetch(url, {
147
+ headers: { Authorization: `Bearer ${apiKey}` }
148
+ });
149
+ if (!res.ok) {
150
+ throw new Error(`HTTP ${res.status} ${res.statusText}`);
151
+ }
152
+ } catch (err) {
153
+ const msg = err instanceof Error ? err.message : String(err);
154
+ throw new Error(`Sync server health check failed: ${msg}`);
155
+ }
156
+ }
157
+ async function withSyncClient(dbPath, config, fn) {
158
+ const Database = (await import("better-sqlite3")).default;
159
+ const { SyncClient, ensureSyncSchema } = await import("@memrosetta/sync-client");
160
+ if (!config.syncServerUrl || !config.syncApiKey || !config.syncDeviceId) {
161
+ throw new Error("Sync is not configured. Run: memrosetta sync enable --server <url>");
162
+ }
163
+ if (CONTROL_CHAR_REGEX.test(config.syncApiKey)) {
164
+ throw new Error(
165
+ `Stored API key is invalid (contains control characters from a previous terminal input). Re-run with one of:
166
+ memrosetta sync enable --server ${config.syncServerUrl} --key <api-key>
167
+ memrosetta sync enable --server ${config.syncServerUrl} --key-file path/to/key
168
+ $env:${ENV_API_KEY}='<api-key>'; memrosetta sync enable --server ${config.syncServerUrl}`
169
+ );
170
+ }
171
+ const db = new Database(dbPath);
172
+ try {
173
+ ensureSyncSchema(db);
174
+ const client = new SyncClient(db, {
175
+ serverUrl: config.syncServerUrl,
176
+ apiKey: config.syncApiKey,
177
+ deviceId: config.syncDeviceId,
178
+ userId: userInfo().username
179
+ });
180
+ return await fn(client, db);
181
+ } finally {
182
+ db.close();
183
+ }
184
+ }
185
+ async function runEnable(options) {
186
+ const { args, format } = options;
187
+ let serverUrl;
188
+ try {
189
+ serverUrl = requireOption(args, "--server", "server URL");
190
+ } catch (err) {
191
+ outputError(err instanceof Error ? err.message : String(err), format);
192
+ process.exitCode = 1;
193
+ return;
194
+ }
195
+ let apiKey;
196
+ try {
197
+ apiKey = await resolveApiKey(args);
198
+ } catch (err) {
199
+ outputError(err instanceof Error ? err.message : String(err), format);
200
+ process.exitCode = 1;
201
+ return;
202
+ }
203
+ const skipTest = hasFlag(args, "--no-test");
204
+ if (!skipTest) {
205
+ try {
206
+ await testConnection(serverUrl, apiKey);
207
+ } catch (err) {
208
+ outputError(
209
+ `${err instanceof Error ? err.message : String(err)}
210
+ Use --no-test to skip the health check.`,
211
+ format
212
+ );
213
+ process.exitCode = 1;
214
+ return;
215
+ }
216
+ }
217
+ const existing = getConfig();
218
+ const deviceId = existing.syncDeviceId ?? `device-${randomUUID().slice(0, 8)}`;
219
+ writeConfig({
220
+ ...existing,
221
+ syncEnabled: true,
222
+ syncServerUrl: serverUrl,
223
+ syncApiKey: apiKey,
224
+ syncDeviceId: deviceId
225
+ });
226
+ if (format === "text") {
227
+ process.stdout.write("Sync enabled.\n");
228
+ process.stdout.write(` Server: ${serverUrl}
229
+ `);
230
+ process.stdout.write(` DeviceId: ${deviceId}
231
+ `);
232
+ if (skipTest) {
233
+ process.stdout.write(" (health check skipped)\n");
234
+ }
235
+ return;
236
+ }
237
+ output({ enabled: true, serverUrl, deviceId, healthCheckSkipped: skipTest }, format);
238
+ }
239
+ function runDisable(options) {
240
+ const { format } = options;
241
+ const existing = getConfig();
242
+ writeConfig({
243
+ ...existing,
244
+ syncEnabled: false
245
+ });
246
+ if (format === "text") {
247
+ process.stdout.write("Sync disabled. (server URL and API key preserved for re-enable)\n");
248
+ return;
249
+ }
250
+ output({ enabled: false }, format);
251
+ }
252
+ async function runStatus(options) {
253
+ const { format, db } = options;
254
+ const config = getConfig();
255
+ const dbPath = db ?? config.dbPath ?? getDefaultDbPath();
256
+ if (!config.syncEnabled) {
257
+ if (format === "text") {
258
+ process.stdout.write("Sync: disabled\n");
259
+ if (config.syncServerUrl) {
260
+ process.stdout.write(` Server: ${config.syncServerUrl}
261
+ `);
262
+ }
263
+ if (config.syncDeviceId) {
264
+ process.stdout.write(` DeviceId: ${config.syncDeviceId}
265
+ `);
266
+ }
267
+ return;
268
+ }
269
+ output(
270
+ {
271
+ enabled: false,
272
+ serverUrl: config.syncServerUrl ?? null,
273
+ deviceId: config.syncDeviceId ?? null
274
+ },
275
+ format
276
+ );
277
+ return;
278
+ }
279
+ try {
280
+ const status = await withSyncClient(dbPath, config, async (client) => client.getStatus());
281
+ if (format === "text") {
282
+ process.stdout.write("Sync: enabled\n");
283
+ process.stdout.write(` Server: ${status.serverUrl}
284
+ `);
285
+ process.stdout.write(` DeviceId: ${status.deviceId}
286
+ `);
287
+ process.stdout.write(` Pending ops: ${status.pendingOps}
288
+ `);
289
+ process.stdout.write(` Current cursor: ${status.cursor}
290
+ `);
291
+ process.stdout.write(
292
+ ` Last push: ${status.lastPush.successAt ?? "never"}` + (status.lastPush.attemptAt && status.lastPush.attemptAt !== status.lastPush.successAt ? ` (last attempt: ${status.lastPush.attemptAt})` : "") + "\n"
293
+ );
294
+ process.stdout.write(
295
+ ` Last pull: ${status.lastPull.successAt ?? "never"}` + (status.lastPull.attemptAt && status.lastPull.attemptAt !== status.lastPull.successAt ? ` (last attempt: ${status.lastPull.attemptAt})` : "") + "\n"
296
+ );
297
+ return;
298
+ }
299
+ output(status, format);
300
+ } catch (err) {
301
+ outputError(err instanceof Error ? err.message : String(err), format);
302
+ process.exitCode = 1;
303
+ }
304
+ }
305
+ async function runNow(options) {
306
+ const { args, format, db } = options;
307
+ const config = getConfig();
308
+ const dbPath = db ?? config.dbPath ?? getDefaultDbPath();
309
+ if (!config.syncEnabled) {
310
+ outputError("Sync is disabled. Run: memrosetta sync enable --server <url>", format);
311
+ process.exitCode = 1;
312
+ return;
313
+ }
314
+ const pushOnly = hasFlag(args, "--push-only");
315
+ const pullOnly = hasFlag(args, "--pull-only");
316
+ try {
317
+ const result = await withSyncClient(dbPath, config, async (client) => {
318
+ let pushed = 0;
319
+ let pulled = 0;
320
+ if (!pullOnly) {
321
+ const pushResult = await client.push();
322
+ pushed = pushResult.pushed;
323
+ }
324
+ if (!pushOnly) {
325
+ pulled = await client.pull();
326
+ }
327
+ return { pushed, pulled };
328
+ });
329
+ if (format === "text") {
330
+ process.stdout.write(`Sync complete. pushed=${result.pushed} pulled=${result.pulled}
331
+ `);
332
+ return;
333
+ }
334
+ output(result, format);
335
+ } catch (err) {
336
+ outputError(err instanceof Error ? err.message : String(err), format);
337
+ process.exitCode = 1;
338
+ }
339
+ }
340
+ function runDeviceId(options) {
341
+ const { format } = options;
342
+ const config = getConfig();
343
+ if (!config.syncDeviceId) {
344
+ outputError("No deviceId set. Run: memrosetta sync enable --server <url>", format);
345
+ process.exitCode = 1;
346
+ return;
347
+ }
348
+ if (format === "text") {
349
+ process.stdout.write(`${config.syncDeviceId}
350
+ `);
351
+ return;
352
+ }
353
+ output({ deviceId: config.syncDeviceId }, format);
354
+ }
355
+ async function run(options) {
356
+ const sub = parseSubcommand(options.args);
357
+ if (!sub) {
358
+ outputError(
359
+ "Usage: memrosetta sync <enable|disable|status|now|device-id>\n\n enable --server <url> [--key <key> | --key-stdin] [--no-test]\n disable\n status\n now [--push-only | --pull-only]\n device-id\n",
360
+ options.format
361
+ );
362
+ process.exitCode = 1;
363
+ return;
364
+ }
365
+ const rest = { ...options, args: options.args.slice(1) };
366
+ switch (sub) {
367
+ case "enable":
368
+ await runEnable(rest);
369
+ return;
370
+ case "disable":
371
+ runDisable(rest);
372
+ return;
373
+ case "status":
374
+ await runStatus(rest);
375
+ return;
376
+ case "now":
377
+ await runNow(rest);
378
+ return;
379
+ case "device-id":
380
+ runDeviceId(rest);
381
+ return;
382
+ }
383
+ }
384
+ export {
385
+ run
386
+ };
@@ -0,0 +1,79 @@
1
+ import {
2
+ resolveCliVersion
3
+ } from "./chunk-YXK6FDB6.js";
4
+
5
+ // src/commands/update.ts
6
+ import { execSync } from "child_process";
7
+ function parseNpmList(raw) {
8
+ const start = raw.indexOf("{");
9
+ if (start === -1) return {};
10
+ try {
11
+ return JSON.parse(raw.slice(start));
12
+ } catch {
13
+ return {};
14
+ }
15
+ }
16
+ function getInstalledVersion(packageName) {
17
+ try {
18
+ const raw = execSync(`npm list -g ${packageName} --depth=0 --json`, {
19
+ encoding: "utf-8",
20
+ stdio: ["ignore", "pipe", "ignore"]
21
+ });
22
+ const parsed = parseNpmList(raw);
23
+ const deps = parsed.dependencies ?? {};
24
+ return deps[packageName]?.version ?? null;
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+ async function run() {
30
+ const runningVersion = resolveCliVersion();
31
+ const wrapperInstalled = getInstalledVersion("memrosetta");
32
+ const cliInstalled = getInstalledVersion("@memrosetta/cli");
33
+ let packageName;
34
+ let currentVersion;
35
+ if (wrapperInstalled) {
36
+ packageName = "memrosetta";
37
+ currentVersion = wrapperInstalled;
38
+ } else if (cliInstalled) {
39
+ packageName = "@memrosetta/cli";
40
+ currentVersion = cliInstalled;
41
+ } else {
42
+ packageName = "memrosetta";
43
+ currentVersion = runningVersion;
44
+ }
45
+ process.stdout.write(`Current version: ${currentVersion} (${packageName})
46
+ `);
47
+ if (currentVersion !== runningVersion && runningVersion !== "unknown") {
48
+ process.stdout.write(`Running binary: ${runningVersion}
49
+ `);
50
+ }
51
+ process.stdout.write("Checking for updates...\n");
52
+ try {
53
+ const latest = execSync(`npm view ${packageName} version`, {
54
+ encoding: "utf-8"
55
+ }).trim();
56
+ if (latest === currentVersion) {
57
+ process.stdout.write(`Already up to date (${currentVersion}).
58
+ `);
59
+ return;
60
+ }
61
+ process.stdout.write(`New version available: ${latest}
62
+ `);
63
+ process.stdout.write("Updating...\n");
64
+ execSync(`npm install -g ${packageName}@latest --force`, {
65
+ stdio: "inherit"
66
+ });
67
+ process.stdout.write(`
68
+ Updated: ${currentVersion} -> ${latest}
69
+ `);
70
+ } catch (err) {
71
+ const message = err instanceof Error ? err.message : String(err);
72
+ process.stderr.write(`Update failed: ${message}
73
+ `);
74
+ process.exitCode = 1;
75
+ }
76
+ }
77
+ export {
78
+ run
79
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@memrosetta/cli",
3
- "version": "0.4.2",
3
+ "version": "0.4.4",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "bin": {