@edihasaj/recall 2.0.16 → 2.0.18

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.
Files changed (84) hide show
  1. package/README.md +34 -4
  2. package/dist/{chunk-MLC3KO2O.js → chunk-2YFC2U6M.js} +7 -7
  3. package/dist/{chunk-YELXEWKH.js → chunk-CGZP6FXD.js} +3 -3
  4. package/dist/{chunk-LEOXFQJJ.js → chunk-EJNIQVIJ.js} +2 -2
  5. package/dist/{chunk-EKFOHVHS.js → chunk-HKA2KAB2.js} +233 -28
  6. package/dist/chunk-HKA2KAB2.js.map +1 -0
  7. package/dist/{chunk-VRAG5V66.js → chunk-JMAWDCQM.js} +1091 -48
  8. package/dist/chunk-JMAWDCQM.js.map +1 -0
  9. package/dist/{chunk-GDN44ZC7.js → chunk-LGM46TRO.js} +2 -2
  10. package/dist/{chunk-SEXZABB2.js → chunk-MXF255YS.js} +5 -5
  11. package/dist/{chunk-GCMP2YYN.js → chunk-OIIAMDOT.js} +4 -3
  12. package/dist/{chunk-GCMP2YYN.js.map → chunk-OIIAMDOT.js.map} +1 -1
  13. package/dist/{chunk-FYMMTODQ.js → chunk-PVEH3GEI.js} +2 -2
  14. package/dist/{chunk-FYMMTODQ.js.map → chunk-PVEH3GEI.js.map} +1 -1
  15. package/dist/{chunk-DAW6FUGL.js → chunk-SARDP34D.js} +5 -5
  16. package/dist/{chunk-SYSSACWJ.js → chunk-SHS4CTN3.js} +43 -20
  17. package/dist/chunk-SHS4CTN3.js.map +1 -0
  18. package/dist/{chunk-DOYTMHDI.js → chunk-SYYBKTWO.js} +2 -2
  19. package/dist/{chunk-Q2F7EQCA.js → chunk-UNKEHYFD.js} +2 -2
  20. package/dist/{chunk-7UWVXXTU.js → chunk-VNKQBRLB.js} +3 -3
  21. package/dist/{chunk-QPR77YXP.js → chunk-XBYAK7LC.js} +13 -11
  22. package/dist/chunk-XBYAK7LC.js.map +1 -0
  23. package/dist/{chunk-THC7QOAK.js → chunk-XOKSI4EY.js} +7 -7
  24. package/dist/{chunk-DVLQYARZ.js → chunk-YFK2AD34.js} +3 -3
  25. package/dist/{chunk-ZF23OPYV.js → chunk-Z2NS4E63.js} +31 -38
  26. package/dist/chunk-Z2NS4E63.js.map +1 -0
  27. package/dist/{cleanup-WJFE6IVP.js → cleanup-PYF3MQXT.js} +11 -11
  28. package/dist/cli.js +58 -191
  29. package/dist/cli.js.map +1 -1
  30. package/dist/{codex-trust-3BFTJFRD.js → codex-trust-JTJSVDJ4.js} +4 -4
  31. package/dist/daemon.js +1213 -188
  32. package/dist/daemon.js.map +1 -1
  33. package/dist/dispatcher-JZKQYPLF.js +22 -0
  34. package/dist/{embeddings-H352GFKD.js → embeddings-3NAF5DFW.js} +5 -5
  35. package/dist/ingest-KWIQFV6X.js +20 -0
  36. package/dist/{keychain-A2Z7D7YE.js → keychain-FLEYJZCO.js} +3 -3
  37. package/dist/mcp.js +15 -15
  38. package/dist/{memory-value-M3TA7SEK.js → memory-value-DT5DNGJA.js} +11 -11
  39. package/dist/{provenance-CXU6LZK7.js → provenance-ZBYCDVTO.js} +9 -9
  40. package/dist/quality-UQME7OTQ.js +25 -0
  41. package/dist/retrieval-V7TY5HRU.js +15 -0
  42. package/dist/{store-YCVWABSH.js → store-UQFDKVUA.js} +4 -4
  43. package/dist/sync-server.js +2 -2
  44. package/dist/{tasks-4UL2FIAQ.js → tasks-2LMQ3ZXB.js} +11 -11
  45. package/dist/{usage-HZ27RG53.js → usage-ZXD4DO5J.js} +4 -4
  46. package/package.json +2 -1
  47. package/vendor/recall-cloud-sync/PROVENANCE.md +40 -0
  48. package/vendor/recall-cloud-sync/managed-worker.mjs +48 -0
  49. package/vendor/recall-cloud-sync/private-token.mjs +95 -0
  50. package/vendor/recall-cloud-sync/recall-sync-local.mjs +415 -0
  51. package/vendor/recall-cloud-sync/recall-sync.mjs +1300 -0
  52. package/dist/chunk-EKFOHVHS.js.map +0 -1
  53. package/dist/chunk-QPR77YXP.js.map +0 -1
  54. package/dist/chunk-SYSSACWJ.js.map +0 -1
  55. package/dist/chunk-VRAG5V66.js.map +0 -1
  56. package/dist/chunk-ZF23OPYV.js.map +0 -1
  57. package/dist/dispatcher-5JVGZNWT.js +0 -22
  58. package/dist/ingest-NVYEOSVZ.js +0 -20
  59. package/dist/quality-4CG6U273.js +0 -25
  60. package/dist/retrieval-42CPYUDW.js +0 -15
  61. /package/dist/{chunk-MLC3KO2O.js.map → chunk-2YFC2U6M.js.map} +0 -0
  62. /package/dist/{chunk-YELXEWKH.js.map → chunk-CGZP6FXD.js.map} +0 -0
  63. /package/dist/{chunk-LEOXFQJJ.js.map → chunk-EJNIQVIJ.js.map} +0 -0
  64. /package/dist/{chunk-GDN44ZC7.js.map → chunk-LGM46TRO.js.map} +0 -0
  65. /package/dist/{chunk-SEXZABB2.js.map → chunk-MXF255YS.js.map} +0 -0
  66. /package/dist/{chunk-DAW6FUGL.js.map → chunk-SARDP34D.js.map} +0 -0
  67. /package/dist/{chunk-DOYTMHDI.js.map → chunk-SYYBKTWO.js.map} +0 -0
  68. /package/dist/{chunk-Q2F7EQCA.js.map → chunk-UNKEHYFD.js.map} +0 -0
  69. /package/dist/{chunk-7UWVXXTU.js.map → chunk-VNKQBRLB.js.map} +0 -0
  70. /package/dist/{chunk-THC7QOAK.js.map → chunk-XOKSI4EY.js.map} +0 -0
  71. /package/dist/{chunk-DVLQYARZ.js.map → chunk-YFK2AD34.js.map} +0 -0
  72. /package/dist/{cleanup-WJFE6IVP.js.map → cleanup-PYF3MQXT.js.map} +0 -0
  73. /package/dist/{codex-trust-3BFTJFRD.js.map → codex-trust-JTJSVDJ4.js.map} +0 -0
  74. /package/dist/{dispatcher-5JVGZNWT.js.map → dispatcher-JZKQYPLF.js.map} +0 -0
  75. /package/dist/{embeddings-H352GFKD.js.map → embeddings-3NAF5DFW.js.map} +0 -0
  76. /package/dist/{ingest-NVYEOSVZ.js.map → ingest-KWIQFV6X.js.map} +0 -0
  77. /package/dist/{keychain-A2Z7D7YE.js.map → keychain-FLEYJZCO.js.map} +0 -0
  78. /package/dist/{memory-value-M3TA7SEK.js.map → memory-value-DT5DNGJA.js.map} +0 -0
  79. /package/dist/{provenance-CXU6LZK7.js.map → provenance-ZBYCDVTO.js.map} +0 -0
  80. /package/dist/{quality-4CG6U273.js.map → quality-UQME7OTQ.js.map} +0 -0
  81. /package/dist/{retrieval-42CPYUDW.js.map → retrieval-V7TY5HRU.js.map} +0 -0
  82. /package/dist/{store-YCVWABSH.js.map → store-UQFDKVUA.js.map} +0 -0
  83. /package/dist/{tasks-4UL2FIAQ.js.map → tasks-2LMQ3ZXB.js.map} +0 -0
  84. /package/dist/{usage-HZ27RG53.js.map → usage-ZXD4DO5J.js.map} +0 -0
@@ -0,0 +1,1300 @@
1
+ #!/usr/bin/env node
2
+ import Database from "better-sqlite3";
3
+ import { execFileSync } from "node:child_process";
4
+ import { createCipheriv, createDecipheriv, createHash, randomBytes, scryptSync } from "node:crypto";
5
+ import {
6
+ existsSync,
7
+ mkdirSync,
8
+ readFileSync,
9
+ realpathSync,
10
+ rmSync
11
+ } from "node:fs";
12
+ import { homedir, hostname } from "node:os";
13
+ import { dirname, join, resolve } from "node:path";
14
+ import { fileURLToPath, pathToFileURL } from "node:url";
15
+ import {
16
+ applyPulledRecords,
17
+ decryptCloudPayload,
18
+ canonicalExternalId,
19
+ cloudExternalIdForRow
20
+ } from "./recall-sync-local.mjs";
21
+ import {
22
+ normalizeToken,
23
+ readPrivateTokenFile,
24
+ validateApiUrl,
25
+ validatePrivateFile,
26
+ writePrivateFileAtomic,
27
+ writePrivateTokenFile
28
+ } from "./private-token.mjs";
29
+
30
+ const DEFAULT_DB = join(homedir(), ".recall", "recall.db");
31
+ const SELF = fileURLToPath(import.meta.url);
32
+ const LAUNCHD_LABEL = "dev.recallmemory.cloud-sync";
33
+ const SYSTEMD_UNIT = "recall-cloud-sync.service";
34
+ const WINDOWS_TASK = "Recall Cloud Sync";
35
+ const TOKEN_FILE = join(homedir(), ".config", "recall-cloud", "token");
36
+ const SYNC_STATE_FILE = join(homedir(), ".config", "recall-cloud", "sync-state.json");
37
+ // transient is deliberately excluded: it is by definition not durable, and the
38
+ // pull side has no inverse for the push-time transient→candidate coercion, so
39
+ // syncing it silently promoted local transient rows to candidate on the next
40
+ // pull. rejected IS synced — cross-device rejection propagation depends on it;
41
+ // the billing count excludes rejected server-side instead.
42
+ const DEFAULT_PUSH_STATUSES = "active,candidate,rejected";
43
+ const DEFAULT_WATCH_STATUSES = "active,candidate,rejected";
44
+ const DEFAULT_FULL_RECONCILE_SECONDS = 86_400;
45
+
46
+ // --- E2EE (zero-knowledge) client-side encryption -------------------------
47
+ // A deterministic content key is derived from the user's passphrase so every
48
+ // device that knows the passphrase derives the SAME key — no server key
49
+ // exchange needed. The server only ever sees ciphertext + nonce; it never sees
50
+ // the passphrase, the derived key, or plaintext. AES-256-GCM (via Node crypto);
51
+ // the server treats the blobs as opaque, so the exact AEAD is a client choice.
52
+ const E2EE_KDF_SALT = "recall-cloud-e2ee-v1";
53
+ const E2EE_KEY_ID = "pp-v1";
54
+ const GCM_TAG_BYTES = 16;
55
+
56
+ function e2eeKey(passphrase) {
57
+ return scryptSync(Buffer.from(String(passphrase), "utf8"), E2EE_KDF_SALT, 32);
58
+ }
59
+
60
+ function e2eeEncrypt(key, plaintext) {
61
+ const iv = randomBytes(12);
62
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
63
+ const body = Buffer.concat([cipher.update(Buffer.from(plaintext, "utf8")), cipher.final()]);
64
+ // store ciphertext||authTag as one opaque blob; nonce travels alongside.
65
+ const blob = Buffer.concat([body, cipher.getAuthTag()]);
66
+ return { ciphertext: blob.toString("base64"), nonce: iv.toString("base64") };
67
+ }
68
+
69
+ function e2eeDecrypt(key, ciphertextB64, nonceB64) {
70
+ const blob = Buffer.from(String(ciphertextB64), "base64");
71
+ const iv = Buffer.from(String(nonceB64), "base64");
72
+ const body = blob.subarray(0, blob.length - GCM_TAG_BYTES);
73
+ const tag = blob.subarray(blob.length - GCM_TAG_BYTES);
74
+ const decipher = createDecipheriv("aes-256-gcm", key, iv);
75
+ decipher.setAuthTag(tag);
76
+ return Buffer.concat([decipher.update(body), decipher.final()]).toString("utf8");
77
+ }
78
+
79
+ // Resolve E2EE config from flags/env. Returns null when off; throws if enabled
80
+ // without a passphrase (fail closed rather than silently sync plaintext).
81
+ function resolveE2ee(options) {
82
+ if (!options.e2ee) return null;
83
+ const passphrase = options.e2eePassphrase ?? process.env.RECALL_CLOUD_E2EE_PASSPHRASE;
84
+ if (!passphrase) {
85
+ throw new Error("--e2ee requires a passphrase (--e2ee-passphrase or RECALL_CLOUD_E2EE_PASSPHRASE)");
86
+ }
87
+ return { key: e2eeKey(passphrase) };
88
+ }
89
+
90
+ // Run main() only when executed directly, so the module can be imported by
91
+ // tests. Compare realpath-resolved paths so a symlinked location (e.g. macOS
92
+ // /var -> /private/var) still counts as "invoked directly".
93
+ let INVOKED_DIRECTLY = false;
94
+ try {
95
+ INVOKED_DIRECTLY = Boolean(process.argv[1]) && realpathSync(SELF) === realpathSync(process.argv[1]);
96
+ } catch {
97
+ INVOKED_DIRECTLY = process.argv[1] ? import.meta.url === pathToFileURL(process.argv[1]).href : false;
98
+ }
99
+ if (INVOKED_DIRECTLY) {
100
+ main().catch((error) => {
101
+ console.error(error instanceof Error ? error.message : String(error));
102
+ process.exit(1);
103
+ });
104
+ }
105
+
106
+ export {
107
+ DEFAULT_PUSH_STATUSES,
108
+ DEFAULT_WATCH_STATUSES,
109
+ applyPulledRecords,
110
+ canonicalExternalId,
111
+ cloudExternalIdForRow,
112
+ e2eeKey,
113
+ e2eeEncrypt,
114
+ e2eeDecrypt,
115
+ resolveE2ee,
116
+ buildPlist,
117
+ buildSystemdUnit,
118
+ buildWindowsLauncher,
119
+ launchAgentArgs,
120
+ parseDeviceAliases,
121
+ deviceAliasesFromArgs,
122
+ resolveDeviceAliases,
123
+ deviceIdFromArgs,
124
+ legacyTokenFromArgs,
125
+ loadSyncState,
126
+ readPrivateTokenFile,
127
+ readRecallMemories,
128
+ toCloudRecord
129
+ };
130
+
131
+ async function main() {
132
+ const [command, ...args] = process.argv.slice(2);
133
+ const options = parseOptions(args);
134
+
135
+ switch (command) {
136
+ case "push":
137
+ await push(options);
138
+ break;
139
+ case "pull":
140
+ await pull(options);
141
+ break;
142
+ case "verify":
143
+ await verify(options);
144
+ break;
145
+ case "memories":
146
+ case "list-all":
147
+ await memories(options);
148
+ break;
149
+ case "watch":
150
+ await watch(options);
151
+ break;
152
+ case "install":
153
+ await installAgent(options);
154
+ break;
155
+ case "uninstall":
156
+ await uninstallAgent(options);
157
+ break;
158
+ default:
159
+ usage();
160
+ process.exit(command ? 1 : 0);
161
+ }
162
+ }
163
+
164
+ async function push(options, { verifiedE2ee = false } = {}) {
165
+ const api = requiredApi(options.api ?? process.env.RECALL_CLOUD_API);
166
+ const token = resolveToken(options);
167
+ const dbPath = resolve(expandHome(options.db ?? process.env.RECALL_DB ?? DEFAULT_DB));
168
+ const statusSet = new Set((options.status ?? DEFAULT_PUSH_STATUSES).split(",").map((value) => value.trim()).filter(Boolean));
169
+ const deviceId = options.deviceId ?? hostnameLabel();
170
+ const deviceAliases = resolveDeviceAliases(options);
171
+ const limit = parseInteger(options.limit, 5000);
172
+ const dryRun = Boolean(options.dryRun);
173
+ const e2ee = resolveE2ee(options);
174
+
175
+ const rows = readRecallMemories(dbPath, statusSet, limit, {
176
+ after: options.after,
177
+ afterId: options.afterId
178
+ });
179
+ const records = rows.map((row) => toCloudRecord(row, deviceId, e2ee, deviceAliases));
180
+
181
+ if (dryRun) {
182
+ console.log(JSON.stringify(dryRunPushPayload(records, {
183
+ dbPath,
184
+ api,
185
+ deviceId,
186
+ e2ee: Boolean(e2ee),
187
+ statuses: [...statusSet],
188
+ includeSample: Boolean(options.sample)
189
+ }), null, 2));
190
+ return;
191
+ }
192
+
193
+ // A mistyped key on a new device must not overwrite existing ciphertext.
194
+ // Watch verifies through its preceding pull; standalone push verifies here.
195
+ if (e2ee && !verifiedE2ee) await verifyRemoteEncryption(api, token, e2ee);
196
+
197
+ let accepted = 0;
198
+ // Rows the server actually wrote. `accepted` only counts records that
199
+ // survived the ACL filter; the updated_at guard can still drop stale ones,
200
+ // so "pushed=500" could mean zero writes.
201
+ let applied = 0;
202
+ let aliasesReconciled = 0;
203
+ const batches = chunks(records, 500);
204
+ if (batches.length === 0 && Object.keys(deviceAliases).length > 0) batches.push([]);
205
+ for (const [index, batch] of batches.entries()) {
206
+ const result = await fetchJson(`${api}/v1/sync/push`, {
207
+ method: "POST",
208
+ token,
209
+ body: syncPushRequest(batch, index === 0 ? deviceAliases : {})
210
+ });
211
+ accepted += Number(result.accepted ?? 0);
212
+ // Older servers don't report `applied`; fall back to accepted so the
213
+ // number never reads as a spurious zero.
214
+ applied += Number(result.applied ?? result.accepted ?? 0);
215
+ aliasesReconciled += Number(result.aliasesReconciled ?? 0);
216
+ }
217
+
218
+ if (options.quiet) {
219
+ console.log(`[${new Date().toISOString()}] push ok applied=${applied} accepted=${accepted} selected=${records.length} aliases=${aliasesReconciled} device=${deviceId}`);
220
+ } else {
221
+ console.log(JSON.stringify({
222
+ pushed: accepted,
223
+ applied,
224
+ selected: records.length,
225
+ dbPath,
226
+ api,
227
+ deviceId,
228
+ aliasesReconciled,
229
+ statuses: [...statusSet]
230
+ }, null, 2));
231
+ }
232
+ const last = rows.at(-1);
233
+ return {
234
+ pushed: accepted,
235
+ applied,
236
+ selected: records.length,
237
+ aliasesReconciled,
238
+ cursor: last ? { updatedAt: last.updated_at, id: last.id } : null
239
+ };
240
+ }
241
+
242
+ export function syncPushRequest(records, deviceAliases = {}) {
243
+ const body = { records };
244
+ if (Object.keys(deviceAliases).length > 0) body.deviceAliases = deviceAliases;
245
+ return body;
246
+ }
247
+
248
+ export function dryRunPushPayload(records, { dbPath, api, deviceId, e2ee, statuses, includeSample = false }) {
249
+ const payload = {
250
+ dryRun: true,
251
+ dbPath,
252
+ api,
253
+ deviceId,
254
+ e2ee,
255
+ selected: records.length,
256
+ statuses
257
+ };
258
+ if (includeSample) payload.sample = records.slice(0, 3);
259
+ return payload;
260
+ }
261
+
262
+ async function pull(options) {
263
+ const api = requiredApi(options.api ?? process.env.RECALL_CLOUD_API);
264
+ const token = resolveToken(options);
265
+ const dbPath = resolve(expandHome(options.db ?? process.env.RECALL_DB ?? DEFAULT_DB));
266
+ const deviceId = options.deviceId ?? hostnameLabel();
267
+ const deviceAliases = resolveDeviceAliases(options);
268
+ const max = parseInteger(options.limit, 100000);
269
+ const records = await fetchAllSyncRecords({
270
+ api,
271
+ token,
272
+ since: options.since,
273
+ sinceId: options.sinceId,
274
+ max
275
+ });
276
+ const applied = options.dryRun
277
+ ? {
278
+ imported: 0,
279
+ updated: 0,
280
+ unchanged: 0,
281
+ skippedEncrypted: records.filter((record) => record.encryptionMode === "e2ee").length,
282
+ skippedDuplicate: 0,
283
+ skippedExpiredTombstone: 0
284
+ }
285
+ : applyPulledRecords(dbPath, records, {
286
+ deviceId,
287
+ deviceAliases,
288
+ e2ee: resolveE2ee(options),
289
+ decrypt: e2eeDecrypt,
290
+ rejectedRetentionDays: parseNonNegativeInteger(
291
+ options.rejectedRetentionDays ?? process.env.RECALL_REJECTED_RETENTION_DAYS,
292
+ 90
293
+ )
294
+ });
295
+
296
+ if (options.quiet) {
297
+ console.log(
298
+ `[${new Date().toISOString()}] pull ok fetched=${records.length} imported=${applied.imported} updated=${applied.updated} unchanged=${applied.unchanged} skipped=${applied.skippedEncrypted + applied.skippedDuplicate + applied.skippedExpiredTombstone}`
299
+ );
300
+ } else {
301
+ console.log(JSON.stringify({
302
+ fetched: records.length,
303
+ dbPath,
304
+ dryRun: Boolean(options.dryRun),
305
+ ...applied
306
+ }, null, 2));
307
+ }
308
+ const last = records.at(-1);
309
+ return {
310
+ fetched: records.length,
311
+ ...applied,
312
+ cursor: last?.updatedAt && last?.externalId
313
+ ? { updatedAt: last.updatedAt, id: last.externalId }
314
+ : null
315
+ };
316
+ }
317
+
318
+ async function verify(options) {
319
+ const api = requiredApi(options.api ?? process.env.RECALL_CLOUD_API);
320
+ const token = resolveToken(options);
321
+ const query = options.query ?? "recall";
322
+ const limit = parseInteger(options.limit, 10);
323
+
324
+ const result = await fetchJson(`${api}/v1/compile`, {
325
+ method: "POST",
326
+ token,
327
+ body: { query, limit }
328
+ });
329
+
330
+ const memories = Array.isArray(result.memories) ? result.memories : [];
331
+ console.log(JSON.stringify({
332
+ query,
333
+ matched: memories.length,
334
+ mode: result.mode,
335
+ sample: memories.slice(0, 5)
336
+ }, null, 2));
337
+ }
338
+
339
+ async function memories(options) {
340
+ const api = requiredApi(options.api ?? process.env.RECALL_CLOUD_API);
341
+ const token = resolveToken(options);
342
+ const queryFilter = (options.query ?? "").toLowerCase();
343
+ const deviceFilter = options.device ?? null;
344
+ const max = parseInteger(options.limit, 100000);
345
+
346
+ const all = await fetchAllSyncRecords({
347
+ api,
348
+ token,
349
+ since: options.since,
350
+ max
351
+ });
352
+
353
+ // With a passphrase, decrypt e2ee rows client-side so they are readable/
354
+ // searchable locally (the server never could). Rows that don't decrypt with
355
+ // this passphrase are left as-is (shown as [encrypted]).
356
+ const e2ee = resolveE2ee(options);
357
+ let rows = all;
358
+ if (e2ee) {
359
+ rows = rows.map((r) => {
360
+ if (r.encryptionMode !== "e2ee" || !r.contentCiphertext) return r;
361
+ try {
362
+ const payload = JSON.parse(e2eeDecrypt(e2ee.key, r.contentCiphertext, r.contentNonce));
363
+ return { ...r, contentPlaintext: payload.text, metadata: { ...(r.metadata ?? {}), recall: payload.recall } };
364
+ } catch {
365
+ return { ...r, contentPlaintext: "[encrypted: wrong passphrase]" };
366
+ }
367
+ });
368
+ }
369
+ if (deviceFilter) rows = rows.filter((r) => String(r.externalId ?? "").split(":")[0] === deviceFilter);
370
+ if (queryFilter) rows = rows.filter((r) => String(r.contentPlaintext ?? "").toLowerCase().includes(queryFilter));
371
+
372
+ const show = parseNonNegativeInteger(options.show, 40);
373
+ if (options.json) {
374
+ console.log(JSON.stringify(memoryRowsForOutput(rows, options.show == null ? null : show), null, 2));
375
+ return;
376
+ }
377
+
378
+ const byDevice = {};
379
+ for (const r of rows) {
380
+ const device = String(r.externalId ?? "?").split(":")[0];
381
+ byDevice[device] = (byDevice[device] ?? 0) + 1;
382
+ }
383
+ console.log(`Memories: ${rows.length}${queryFilter ? ` matching "${queryFilter}"` : ""}${deviceFilter ? ` on ${deviceFilter}` : ""} across ${Object.keys(byDevice).length} device(s)`);
384
+ console.log(Object.entries(byDevice).sort((a, b) => b[1] - a[1]).map(([d, n]) => ` ${d}: ${n}`).join("\n"));
385
+ console.log("");
386
+ if (show === 0) return;
387
+ for (const r of rows.slice(0, show)) {
388
+ const device = String(r.externalId ?? "?").split(":")[0];
389
+ const conf = Number(r.confidence ?? 0).toFixed(2);
390
+ const text = String(r.contentPlaintext ?? "").replace(/\s+/g, " ").slice(0, 96);
391
+ console.log(` [${device}] (${r.kind}/${conf}) ${text}`);
392
+ }
393
+ if (rows.length > show) console.log(` … and ${rows.length - show} more (use --show N or --json)`);
394
+ }
395
+
396
+ export function memoryRowsForOutput(rows, show) {
397
+ if (show == null) return rows;
398
+ return rows.slice(0, show);
399
+ }
400
+
401
+ async function watch(options) {
402
+ const api = requiredApi(options.api ?? process.env.RECALL_CLOUD_API);
403
+ const token = resolveToken(options);
404
+ const intervalSeconds = parseInteger(options.interval, 300);
405
+ const fullReconcileSeconds = parseInteger(
406
+ options.fullReconcileInterval,
407
+ DEFAULT_FULL_RECONCILE_SECONDS
408
+ );
409
+ const loopOptions = { ...options, token, tokenFile: undefined, tokenStdin: undefined, quiet: true };
410
+ // Rejected rows are tombstones: uploading their status transition removes
411
+ // formerly-active memories from hosted search instead of leaving stale cloud
412
+ // copies behind forever.
413
+ if (!loopOptions.status) loopOptions.status = DEFAULT_WATCH_STATUSES;
414
+ const dbPath = resolve(expandHome(options.db ?? process.env.RECALL_DB ?? DEFAULT_DB));
415
+ const deviceId = options.deviceId ?? hostnameLabel();
416
+ const deviceAliases = resolveDeviceAliases(options);
417
+ loopOptions.deviceAlias = Object.entries(deviceAliases).map(([from, to]) => `${from}=${to}`);
418
+ const statePath = resolve(expandHome(options.stateFile ?? SYNC_STATE_FILE));
419
+ const stateKey = createHash("sha256")
420
+ .update(`${api}\0${deviceId}\0${dbPath}`)
421
+ .digest("hex");
422
+ const state = loadSyncState(statePath);
423
+ const cursor = state.entries[stateKey] ?? {
424
+ api,
425
+ deviceId,
426
+ dbPath,
427
+ push: null,
428
+ pull: null,
429
+ fullReconciledAt: null
430
+ };
431
+
432
+ console.log(
433
+ `[recall-cloud] watch started api=${api} db=${dbPath} interval=${intervalSeconds}s device=${deviceId}`
434
+ );
435
+
436
+ let running = true;
437
+ const stop = (signal) => {
438
+ console.log(`[recall-cloud] received ${signal}, stopping watch`);
439
+ running = false;
440
+ };
441
+ process.on("SIGINT", () => stop("SIGINT"));
442
+ process.on("SIGTERM", () => stop("SIGTERM"));
443
+
444
+ const privateSync = resolveE2ee(loopOptions);
445
+ let needsKeyVerification = Boolean(privateSync);
446
+ while (running) {
447
+ try {
448
+ const lastFullMs = Date.parse(String(cursor.fullReconciledAt ?? ""));
449
+ const fullReconcile = needsKeyVerification || !Number.isFinite(lastFullMs)
450
+ || Date.now() - lastFullMs >= fullReconcileSeconds * 1000;
451
+ // Verify/import encrypted data before any upload, even with saved cursors.
452
+ // Failed decryption rolls back the pull and never advances its cursor.
453
+ if (privateSync) {
454
+ // Key verification must not inherit the user's incremental batch limit.
455
+ if (needsKeyVerification) await retryTransientSync(() => verifyRemoteEncryption(api, token, privateSync));
456
+ const verified = await retryTransientSync(() => retrySqliteBusy(() => pull({
457
+ ...loopOptions,
458
+ since: fullReconcile ? undefined : cursor.pull?.updatedAt,
459
+ sinceId: fullReconcile ? undefined : cursor.pull?.id
460
+ })));
461
+ if (verified.cursor) cursor.pull = verified.cursor;
462
+ needsKeyVerification = false;
463
+ }
464
+ const pushResult = await retryTransientSync(() => push({
465
+ ...loopOptions,
466
+ after: fullReconcile ? undefined : cursor.push?.updatedAt,
467
+ afterId: fullReconcile ? undefined : cursor.push?.id
468
+ }, { verifiedE2ee: Boolean(privateSync) }));
469
+ if (pushResult?.cursor) cursor.push = pushResult.cursor;
470
+ state.entries[stateKey] = cursor;
471
+ saveSyncState(statePath, state);
472
+
473
+ const pullResult = await retryTransientSync(
474
+ () => retrySqliteBusy(() => pull({
475
+ ...loopOptions,
476
+ since: fullReconcile ? undefined : cursor.pull?.updatedAt,
477
+ sinceId: fullReconcile ? undefined : cursor.pull?.id
478
+ }))
479
+ );
480
+ if (pullResult?.cursor) cursor.pull = pullResult.cursor;
481
+ if (fullReconcile) cursor.fullReconciledAt = new Date().toISOString();
482
+ state.entries[stateKey] = cursor;
483
+ saveSyncState(statePath, state);
484
+ } catch (error) {
485
+ console.error(`[${new Date().toISOString()}] sync error: ${error instanceof Error ? error.message : error}`);
486
+ }
487
+ if (!running) break;
488
+ await sleep(intervalSeconds * 1000, () => running);
489
+ }
490
+ console.log("[recall-cloud] watch stopped");
491
+ }
492
+
493
+ export async function retrySqliteBusy(operation, { attempts = 3, delayMs = 1000 } = {}) {
494
+ for (let attempt = 1; attempt <= attempts; attempt++) {
495
+ try {
496
+ return await operation();
497
+ } catch (error) {
498
+ const message = error instanceof Error ? error.message : String(error);
499
+ const retryable = /(?:database is locked|SQLITE_BUSY)/i.test(message);
500
+ if (!retryable || attempt === attempts) throw error;
501
+ console.warn(
502
+ `[${new Date().toISOString()}] local database busy; retrying pull (${attempt}/${attempts})`
503
+ );
504
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, delayMs));
505
+ }
506
+ }
507
+ throw new Error("unreachable SQLite retry state");
508
+ }
509
+
510
+ export async function retryTransientSync(operation, { attempts = 3, delayMs = 1000 } = {}) {
511
+ for (let attempt = 1; attempt <= attempts; attempt++) {
512
+ try {
513
+ return await operation();
514
+ } catch (error) {
515
+ const message = error instanceof Error ? error.message : String(error);
516
+ const retryable =
517
+ /failed (?:408|425|429|5\d\d)\b/i.test(message) ||
518
+ /(?:fetch failed|network error|invalid JSON response)/i.test(message);
519
+ if (!retryable || attempt === attempts) throw error;
520
+ console.warn(
521
+ `[${new Date().toISOString()}] cloud temporarily unavailable; retrying sync (${attempt}/${attempts})`
522
+ );
523
+ await new Promise((resolvePromise) => setTimeout(resolvePromise, delayMs));
524
+ }
525
+ }
526
+ throw new Error("unreachable transient sync retry state");
527
+ }
528
+
529
+ // process.execPath is the versioned Homebrew Cellar path (…/Cellar/node@24/24.x/bin/node),
530
+ // which disappears when Homebrew upgrades that formula — breaking the launchd
531
+ // agent (exit 78). Map it to the same formula's stable opt symlink instead:
532
+ // it survives patch upgrades and keeps the Node major that built
533
+ // better-sqlite3, so the native module ABI still matches. (The unversioned
534
+ // /opt/homebrew/bin/node is avoided: it can jump majors under the agent.)
535
+ export function stableNodeBin(execPath = process.execPath, exists = existsSync) {
536
+ const match = execPath.match(/^(.*)\/Cellar\/([^/]+)\/[^/]+\/bin\/node$/);
537
+ if (match) {
538
+ const optNode = `${match[1]}/opt/${match[2]}/bin/node`;
539
+ if (exists(optNode)) return optNode;
540
+ }
541
+ return execPath;
542
+ }
543
+
544
+ async function installAgent(options) {
545
+ const api = requiredApi(options.api ?? process.env.RECALL_CLOUD_API);
546
+ const plistPath = process.platform === "darwin" ? launchAgentPath() : undefined;
547
+ const token = resolveToken(options, { legacyPlistPath: plistPath });
548
+ const intervalSeconds = String(parseInteger(options.interval, 300));
549
+ const deviceId = options.deviceId ?? hostnameLabel();
550
+ const deviceAliases = resolveDeviceAliases(options, { plistPath });
551
+ const dbPath = resolve(expandHome(options.db ?? process.env.RECALL_DB ?? DEFAULT_DB));
552
+ const nodeBin = process.platform === "darwin" ? stableNodeBin() : process.execPath;
553
+
554
+ if (plistPath && existsSync(plistPath) && !options.forceDeviceId) {
555
+ const installedDeviceId = installedDeviceIdFromPlist(plistPath);
556
+ if (installedDeviceId && installedDeviceId !== deviceId) {
557
+ throw new Error(
558
+ `installed sync agent uses device id ${installedDeviceId}; refusing to change to ${deviceId} without --force-device-id`
559
+ );
560
+ }
561
+ }
562
+
563
+ writePrivateTokenFile(TOKEN_FILE, token);
564
+ if (process.platform === "linux") {
565
+ installSystemdAgent({ api, intervalSeconds, deviceId, dbPath, nodeBin, deviceAliases });
566
+ return;
567
+ }
568
+ if (process.platform === "win32") {
569
+ installWindowsAgent({ api, intervalSeconds, deviceId, dbPath, nodeBin, deviceAliases });
570
+ return;
571
+ }
572
+ if (process.platform !== "darwin") {
573
+ throw new Error(`install is not supported on ${process.platform}`);
574
+ }
575
+
576
+ const logDir = join(homedir(), "Library", "Logs");
577
+ mkdirSync(logDir, { recursive: true });
578
+ const logFile = join(logDir, "recall-cloud-sync.log");
579
+ mkdirSync(dirname(plistPath), { recursive: true });
580
+
581
+ const args = launchAgentArgs({
582
+ self: SELF,
583
+ api,
584
+ tokenFile: TOKEN_FILE,
585
+ intervalSeconds,
586
+ deviceId,
587
+ dbPath,
588
+ deviceAliases
589
+ });
590
+ const plist = buildPlist({ nodeBin, args, logFile });
591
+ writePrivateFileAtomic(plistPath, plist);
592
+
593
+ try {
594
+ execFileSync("launchctl", ["unload", plistPath], { stdio: "ignore" });
595
+ } catch {
596
+ // not loaded yet
597
+ }
598
+ execFileSync("launchctl", ["load", plistPath], { stdio: "inherit" });
599
+
600
+ console.log(
601
+ JSON.stringify(
602
+ { installed: true, label: LAUNCHD_LABEL, plist: plistPath, log: logFile, intervalSeconds: Number(intervalSeconds), deviceId, dbPath },
603
+ null,
604
+ 2
605
+ )
606
+ );
607
+ }
608
+
609
+ async function uninstallAgent() {
610
+ if (process.platform === "linux") {
611
+ uninstallSystemdAgent();
612
+ } else if (process.platform === "win32") {
613
+ uninstallWindowsAgent();
614
+ } else if (process.platform === "darwin") {
615
+ const plistPath = launchAgentPath();
616
+ try {
617
+ execFileSync("launchctl", ["unload", plistPath], { stdio: "ignore" });
618
+ } catch {
619
+ // already unloaded
620
+ }
621
+ if (existsSync(plistPath)) {
622
+ rmSync(plistPath);
623
+ }
624
+ } else {
625
+ throw new Error(`uninstall is not supported on ${process.platform}`);
626
+ }
627
+ if (existsSync(TOKEN_FILE)) {
628
+ validatePrivateFile(TOKEN_FILE);
629
+ rmSync(TOKEN_FILE);
630
+ }
631
+ console.log(JSON.stringify({ uninstalled: true, platform: process.platform }, null, 2));
632
+ }
633
+
634
+ function launchAgentPath() {
635
+ return join(homedir(), "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
636
+ }
637
+
638
+ function buildPlist({ nodeBin, args, logFile }) {
639
+ const programArgs = [nodeBin, ...args]
640
+ .map((value) => ` <string>${escapeXml(String(value))}</string>`)
641
+ .join("\n");
642
+ return `<?xml version="1.0" encoding="UTF-8"?>
643
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
644
+ <plist version="1.0">
645
+ <dict>
646
+ <key>Label</key>
647
+ <string>${LAUNCHD_LABEL}</string>
648
+ <key>ProgramArguments</key>
649
+ <array>
650
+ ${programArgs}
651
+ </array>
652
+ <key>RunAtLoad</key>
653
+ <true/>
654
+ <key>KeepAlive</key>
655
+ <true/>
656
+ <key>StandardOutPath</key>
657
+ <string>${escapeXml(logFile)}</string>
658
+ <key>StandardErrorPath</key>
659
+ <string>${escapeXml(logFile)}</string>
660
+ </dict>
661
+ </plist>
662
+ `;
663
+ }
664
+
665
+ function installSystemdAgent({ api, intervalSeconds, deviceId, dbPath, nodeBin, deviceAliases }) {
666
+ const unitDir = join(homedir(), ".config", "systemd", "user");
667
+ const unitPath = join(unitDir, SYSTEMD_UNIT);
668
+ mkdirSync(unitDir, { recursive: true, mode: 0o700 });
669
+ const args = launchAgentArgs({
670
+ self: SELF,
671
+ api,
672
+ tokenFile: TOKEN_FILE,
673
+ intervalSeconds,
674
+ deviceId,
675
+ dbPath,
676
+ deviceAliases
677
+ });
678
+ writePrivateFileAtomic(unitPath, buildSystemdUnit({ nodeBin, args }));
679
+ execFileSync("systemctl", ["--user", "daemon-reload"], { stdio: "inherit" });
680
+ execFileSync("systemctl", ["--user", "enable", "--now", SYSTEMD_UNIT], { stdio: "inherit" });
681
+ console.log(JSON.stringify({
682
+ installed: true,
683
+ platform: "linux",
684
+ service: SYSTEMD_UNIT,
685
+ unit: unitPath,
686
+ logs: `journalctl --user -u ${SYSTEMD_UNIT} -f`,
687
+ intervalSeconds: Number(intervalSeconds),
688
+ deviceId,
689
+ dbPath
690
+ }, null, 2));
691
+ }
692
+
693
+ function uninstallSystemdAgent() {
694
+ const unitPath = join(homedir(), ".config", "systemd", "user", SYSTEMD_UNIT);
695
+ try {
696
+ execFileSync("systemctl", ["--user", "disable", "--now", SYSTEMD_UNIT], { stdio: "ignore" });
697
+ } catch {
698
+ // already stopped or user systemd unavailable
699
+ }
700
+ if (existsSync(unitPath)) rmSync(unitPath);
701
+ try {
702
+ execFileSync("systemctl", ["--user", "daemon-reload"], { stdio: "ignore" });
703
+ } catch {
704
+ // nothing left to reload
705
+ }
706
+ }
707
+
708
+ function buildSystemdUnit({ nodeBin, args }) {
709
+ const command = [nodeBin, ...args].map(systemdQuote).join(" ");
710
+ return `[Unit]
711
+ Description=Recall Cloud memory sync
712
+ After=network-online.target
713
+ Wants=network-online.target
714
+
715
+ [Service]
716
+ Type=simple
717
+ ExecStart=${command}
718
+ Restart=always
719
+ RestartSec=10
720
+
721
+ [Install]
722
+ WantedBy=default.target
723
+ `;
724
+ }
725
+
726
+ function systemdQuote(value) {
727
+ return `"${String(value).replace(/([\\"])/g, "\\$1")}"`;
728
+ }
729
+
730
+ function installWindowsAgent({ api, intervalSeconds, deviceId, dbPath, nodeBin, deviceAliases }) {
731
+ const configDir = dirname(TOKEN_FILE);
732
+ secureWindowsConfigDirectory(configDir);
733
+ const launcherPath = join(configDir, "watch.ps1");
734
+ const logFile = join(configDir, "sync.log");
735
+ const args = launchAgentArgs({
736
+ self: SELF,
737
+ api,
738
+ tokenFile: TOKEN_FILE,
739
+ intervalSeconds,
740
+ deviceId,
741
+ dbPath,
742
+ deviceAliases
743
+ });
744
+ writePrivateFileAtomic(
745
+ launcherPath,
746
+ buildWindowsLauncher({ nodeBin, args, logFile })
747
+ );
748
+ const escapedLauncherPath = launcherPath.replace(/"/g, '\\"');
749
+ const taskArgs = `-NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File "${escapedLauncherPath}"`;
750
+ const command = [
751
+ "$identity=[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",
752
+ `$action=New-ScheduledTaskAction -Execute 'powershell.exe' -Argument ${powerShellQuote(taskArgs)}`,
753
+ "if ($identity -eq 'NT AUTHORITY\\SYSTEM') { $trigger=New-ScheduledTaskTrigger -AtStartup; $principal=New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest } else { $trigger=New-ScheduledTaskTrigger -AtLogOn -User $identity; $principal=New-ScheduledTaskPrincipal -UserId $identity -LogonType Interactive -RunLevel Limited }",
754
+ "$settings=New-ScheduledTaskSettingsSet -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1) -ExecutionTimeLimit ([TimeSpan]::Zero) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries",
755
+ `Register-ScheduledTask -TaskName ${powerShellQuote(WINDOWS_TASK)} -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force | Out-Null`,
756
+ `Start-ScheduledTask -TaskName ${powerShellQuote(WINDOWS_TASK)}`
757
+ ].join("; ");
758
+ execFileSync(
759
+ "powershell.exe",
760
+ ["-NoProfile", "-NonInteractive", "-Command", command],
761
+ { stdio: "inherit" }
762
+ );
763
+ console.log(JSON.stringify({
764
+ installed: true,
765
+ platform: "win32",
766
+ task: WINDOWS_TASK,
767
+ launcher: launcherPath,
768
+ log: logFile,
769
+ intervalSeconds: Number(intervalSeconds),
770
+ deviceId,
771
+ dbPath
772
+ }, null, 2));
773
+ }
774
+
775
+ function secureWindowsConfigDirectory(configDir) {
776
+ const command = [
777
+ "$identity=[System.Security.Principal.WindowsIdentity]::GetCurrent().Name",
778
+ "$acl=New-Object System.Security.AccessControl.DirectorySecurity",
779
+ "$acl.SetAccessRuleProtection($true,$false)",
780
+ "$rule=New-Object System.Security.AccessControl.FileSystemAccessRule($identity,'FullControl','ContainerInherit,ObjectInherit','None','Allow')",
781
+ "$acl.SetOwner([System.Security.Principal.NTAccount]$identity)",
782
+ "$acl.SetAccessRule($rule)",
783
+ `Set-Acl -LiteralPath ${powerShellQuote(configDir)} -AclObject $acl`
784
+ ].join("; ");
785
+ execFileSync(
786
+ "powershell.exe",
787
+ ["-NoProfile", "-NonInteractive", "-Command", command],
788
+ { stdio: "inherit" }
789
+ );
790
+ }
791
+
792
+ function uninstallWindowsAgent() {
793
+ const command = [
794
+ `$task=Get-ScheduledTask -TaskName ${powerShellQuote(WINDOWS_TASK)} -ErrorAction SilentlyContinue`,
795
+ `if ($task) { Stop-ScheduledTask -TaskName ${powerShellQuote(WINDOWS_TASK)} -ErrorAction SilentlyContinue; Unregister-ScheduledTask -TaskName ${powerShellQuote(WINDOWS_TASK)} -Confirm:$false }`
796
+ ].join("; ");
797
+ execFileSync(
798
+ "powershell.exe",
799
+ ["-NoProfile", "-NonInteractive", "-Command", command],
800
+ { stdio: "ignore" }
801
+ );
802
+ const launcherPath = join(dirname(TOKEN_FILE), "watch.ps1");
803
+ if (existsSync(launcherPath)) rmSync(launcherPath);
804
+ }
805
+
806
+ function buildWindowsLauncher({ nodeBin, args, logFile }) {
807
+ const invoke = [nodeBin, ...args].map(powerShellQuote).join(" ");
808
+ return `$ErrorActionPreference = 'Continue'
809
+ while ($true) {
810
+ & ${invoke} *>> ${powerShellQuote(logFile)}
811
+ Start-Sleep -Seconds 10
812
+ }
813
+ `;
814
+ }
815
+
816
+ function powerShellQuote(value) {
817
+ return `'${String(value).replace(/'/g, "''")}'`;
818
+ }
819
+
820
+ function launchAgentArgs({ self, api, tokenFile, intervalSeconds, deviceId, dbPath, deviceAliases = {} }) {
821
+ const args = [
822
+ self,
823
+ "watch",
824
+ "--api",
825
+ api,
826
+ "--token-file",
827
+ tokenFile,
828
+ "--interval",
829
+ intervalSeconds,
830
+ "--device-id",
831
+ deviceId,
832
+ "--db",
833
+ dbPath
834
+ ];
835
+ for (const [from, to] of Object.entries(deviceAliases).sort(([a], [b]) => a.localeCompare(b))) {
836
+ args.push("--device-alias", `${from}=${to}`);
837
+ }
838
+ return args;
839
+ }
840
+
841
+ function resolveToken(options, { legacyPlistPath } = {}) {
842
+ const explicitSources = [
843
+ options.token ? "token" : null,
844
+ options.tokenFile ? "token-file" : null,
845
+ options.tokenStdin ? "token-stdin" : null
846
+ ].filter(Boolean);
847
+ if (explicitSources.length > 1) {
848
+ throw new Error(`Use only one token source, received: ${explicitSources.join(", ")}`);
849
+ }
850
+ if (options.token) return normalizeToken(options.token);
851
+ if (options.tokenFile) return readPrivateTokenFile(options.tokenFile);
852
+ if (options.tokenStdin) return normalizeToken(readFileSync(0, "utf8"));
853
+ if (process.env.RECALL_CLOUD_TOKEN) return normalizeToken(process.env.RECALL_CLOUD_TOKEN);
854
+ if (legacyPlistPath && existsSync(legacyPlistPath)) {
855
+ const token = legacyTokenFromPlist(legacyPlistPath);
856
+ if (token) return token;
857
+ }
858
+ throw new Error("--token-file, --token-stdin, or RECALL_CLOUD_TOKEN is required");
859
+ }
860
+
861
+ function legacyTokenFromPlist(plistPath) {
862
+ validatePrivateFile(plistPath);
863
+ const output = execFileSync(
864
+ "/usr/bin/plutil",
865
+ ["-extract", "ProgramArguments", "json", "-o", "-", plistPath],
866
+ { encoding: "utf8", maxBuffer: 1024 * 1024 }
867
+ );
868
+ return legacyTokenFromArgs(JSON.parse(output));
869
+ }
870
+
871
+ function resolveDeviceAliases(options, { plistPath } = {}) {
872
+ const explicit = parseDeviceAliases(options.deviceAlias);
873
+ if (Object.keys(explicit).length > 0) return explicit;
874
+ if (!plistPath && process.platform === "darwin") {
875
+ plistPath = launchAgentPath();
876
+ }
877
+ if (!plistPath || !existsSync(plistPath)) return {};
878
+ return installedDeviceAliasesFromPlist(plistPath);
879
+ }
880
+
881
+ function installedDeviceAliasesFromPlist(plistPath) {
882
+ validatePrivateFile(plistPath);
883
+ const output = execFileSync(
884
+ "/usr/bin/plutil",
885
+ ["-extract", "ProgramArguments", "json", "-o", "-", plistPath],
886
+ { encoding: "utf8", maxBuffer: 1024 * 1024 }
887
+ );
888
+ return deviceAliasesFromArgs(JSON.parse(output));
889
+ }
890
+
891
+ function installedDeviceIdFromPlist(plistPath) {
892
+ validatePrivateFile(plistPath);
893
+ const output = execFileSync(
894
+ "/usr/bin/plutil",
895
+ ["-extract", "ProgramArguments", "json", "-o", "-", plistPath],
896
+ { encoding: "utf8", maxBuffer: 1024 * 1024 }
897
+ );
898
+ return deviceIdFromArgs(JSON.parse(output));
899
+ }
900
+
901
+ function deviceAliasesFromArgs(args) {
902
+ if (!Array.isArray(args)) return {};
903
+ const values = [];
904
+ for (let index = 0; index < args.length; index++) {
905
+ if (args[index] === "--device-alias" && typeof args[index + 1] === "string") {
906
+ values.push(args[index + 1]);
907
+ index++;
908
+ }
909
+ }
910
+ return parseDeviceAliases(values);
911
+ }
912
+
913
+ function deviceIdFromArgs(args) {
914
+ if (!Array.isArray(args)) return null;
915
+ const index = args.indexOf("--device-id");
916
+ if (index === -1 || typeof args[index + 1] !== "string") return null;
917
+ return args[index + 1];
918
+ }
919
+
920
+ function legacyTokenFromArgs(args) {
921
+ if (!Array.isArray(args)) return null;
922
+ const index = args.indexOf("--token");
923
+ if (index === -1 || typeof args[index + 1] !== "string") return null;
924
+ return normalizeToken(args[index + 1]);
925
+ }
926
+
927
+ function escapeXml(value) {
928
+ return value
929
+ .replace(/&/g, "&amp;")
930
+ .replace(/</g, "&lt;")
931
+ .replace(/>/g, "&gt;");
932
+ }
933
+
934
+ function sleep(ms, keepGoing) {
935
+ return new Promise((resolveSleep) => {
936
+ const step = 1000;
937
+ let elapsed = 0;
938
+ const timer = setInterval(() => {
939
+ elapsed += step;
940
+ if (elapsed >= ms || (keepGoing && !keepGoing())) {
941
+ clearInterval(timer);
942
+ resolveSleep();
943
+ }
944
+ }, step);
945
+ });
946
+ }
947
+
948
+ function readRecallMemories(dbPath, statusSet, limit, cursor = {}) {
949
+ if (!existsSync(dbPath)) {
950
+ throw new Error(`Recall DB not found: ${dbPath}`);
951
+ }
952
+
953
+ const db = new Database(dbPath, { readonly: true, fileMustExist: true });
954
+ try {
955
+ db.pragma("query_only = ON");
956
+ const columns = new Set(db.prepare("PRAGMA table_info(memories)").all().map((column) => column.name));
957
+ const note = columns.has("note") ? ", note" : "";
958
+ const placeholders = [...statusSet].map(() => "?").join(",");
959
+ const cursorClause = cursor.after
960
+ ? "AND (updated_at > ? OR (updated_at = ? AND id > ?))"
961
+ : "";
962
+ const params = [...statusSet];
963
+ if (cursor.after) {
964
+ params.push(cursor.after, cursor.after, cursor.afterId ?? "");
965
+ }
966
+ params.push(limit);
967
+ return db.prepare(`
968
+ SELECT
969
+ id, type, text, scope, path_scope, repo, status, confidence, source,
970
+ evidence, capture_context, supersedes, created_at, updated_at,
971
+ last_validated_at, last_injected_at, injection_count, override_count,
972
+ repetition_count, team_id, sync_version, auto_inject, dedupe_key${note}
973
+ FROM memories
974
+ WHERE status IN (${placeholders})
975
+ ${cursorClause}
976
+ ORDER BY updated_at ASC
977
+ , id ASC
978
+ LIMIT ?
979
+ `).all(...params);
980
+ } finally {
981
+ db.close();
982
+ }
983
+ }
984
+
985
+ function loadSyncState(statePath) {
986
+ if (!existsSync(statePath)) return { version: 1, entries: {} };
987
+ validatePrivateFile(statePath);
988
+ try {
989
+ const value = JSON.parse(readFileSync(statePath, "utf8"));
990
+ if (
991
+ value?.version === 1
992
+ && value.entries
993
+ && typeof value.entries === "object"
994
+ && !Array.isArray(value.entries)
995
+ ) {
996
+ return value;
997
+ }
998
+ } catch {
999
+ // Fail safe: a corrupt cursor causes one full reconciliation, not data loss.
1000
+ }
1001
+ return { version: 1, entries: {} };
1002
+ }
1003
+
1004
+ function saveSyncState(statePath, state) {
1005
+ mkdirSync(dirname(statePath), { recursive: true, mode: 0o700 });
1006
+ writePrivateFileAtomic(statePath, `${JSON.stringify(state, null, 2)}\n`);
1007
+ validatePrivateFile(statePath);
1008
+ }
1009
+
1010
+ // The record's "source" for the cloud Sources page (privacy-toggle unit). Group
1011
+ // by repo/project when known (e.g. "edihasaj/recall"); fall back to the local
1012
+ // capture channel (e.g. "capture:user_correction"), else a generic "local"
1013
+ // bucket. The cloud registers one source per distinct ref and attributes each
1014
+ // memory to it (memory_records.source_id), which is what the Sources page lists.
1015
+ function sourceRefFor(row) {
1016
+ const repo = row.repo ? String(row.repo).trim() : "";
1017
+ if (repo) return repo;
1018
+ const src = row.source ? String(row.source).trim() : "";
1019
+ if (src) return `capture:${src}`;
1020
+ return "local";
1021
+ }
1022
+
1023
+ function toCloudRecord(row, deviceId, e2ee = null, deviceAliases = {}) {
1024
+ const recall = {
1025
+ type: row.type,
1026
+ ...(Object.hasOwn(row, "note") ? { note: typeof row.note === "string" ? row.note.replace(/\s+/g, " ").trim() || null : null } : {}),
1027
+ scope: row.scope,
1028
+ pathScope: row.path_scope,
1029
+ repo: row.repo,
1030
+ source: row.source,
1031
+ evidence: parseJson(row.evidence, []),
1032
+ captureContext: parseJson(row.capture_context, null),
1033
+ supersedes: row.supersedes,
1034
+ lastValidatedAt: row.last_validated_at,
1035
+ lastInjectedAt: row.last_injected_at,
1036
+ injectionCount: row.injection_count,
1037
+ overrideCount: row.override_count,
1038
+ repetitionCount: row.repetition_count,
1039
+ teamId: row.team_id,
1040
+ syncVersion: row.sync_version,
1041
+ autoInject: Boolean(row.auto_inject),
1042
+ dedupeKey: row.dedupe_key
1043
+ };
1044
+
1045
+ const base = {
1046
+ externalId: cloudExternalIdForRow(row, deviceId, deviceAliases),
1047
+ status: normalizeStatus(row.status),
1048
+ kind: row.type,
1049
+ confidence: clampConfidence(row.confidence),
1050
+ createdAt: row.created_at,
1051
+ updatedAt: row.updated_at
1052
+ };
1053
+
1054
+ if (e2ee) {
1055
+ // Zero-knowledge: encrypt BOTH the text and the rich metadata (evidence /
1056
+ // capture context carry plaintext), and omit the repo-based sourceId so the
1057
+ // server never learns which projects the memories came from. Only opaque
1058
+ // ciphertext + structural fields (kind/confidence/timestamps) are sent.
1059
+ const { ciphertext, nonce } = e2eeEncrypt(e2ee.key, JSON.stringify({ text: row.text, recall }));
1060
+ return {
1061
+ ...base,
1062
+ encryptionMode: "e2ee",
1063
+ contentCiphertext: ciphertext,
1064
+ contentNonce: nonce,
1065
+ contentKeyId: E2EE_KEY_ID,
1066
+ metadata: { e2ee: true, source: "recall-local-sqlite", localMemoryId: row.id, deviceId }
1067
+ };
1068
+ }
1069
+
1070
+ return {
1071
+ ...base,
1072
+ sourceId: sourceRefFor(row),
1073
+ encryptionMode: "synced",
1074
+ contentPlaintext: row.text,
1075
+ metadata: { source: "recall-local-sqlite", localMemoryId: row.id, deviceId, recall }
1076
+ };
1077
+ }
1078
+
1079
+ async function verifyRemoteEncryption(api, token, e2ee) {
1080
+ const remote = await fetchAllSyncRecords({ api, token, max: 100001 });
1081
+ if (remote.length > 100000) throw new Error("E2EE verification exceeded the safe record limit; sync was stopped.");
1082
+ for (const record of remote) {
1083
+ if (record.encryptionMode === "e2ee") decryptCloudPayload(record, e2ee, e2eeDecrypt);
1084
+ }
1085
+ }
1086
+
1087
+ async function fetchAllSyncRecords({ api, token, since = null, sinceId = null, max = 100000 }) {
1088
+ const all = [];
1089
+ let cursorTime = since ?? null;
1090
+ let cursorId = sinceId ?? null;
1091
+
1092
+ while (all.length < max) {
1093
+ const pageSize = Math.min(500, max - all.length);
1094
+ const result = await fetchJson(`${api}/v1/sync/pull`, {
1095
+ method: "POST",
1096
+ token,
1097
+ body: { since: cursorTime, sinceId: cursorId, limit: pageSize }
1098
+ });
1099
+ if (!Array.isArray(result.records)) throw new Error("Invalid Cloud sync response: records are missing");
1100
+ const batch = result.records;
1101
+ if (batch.length === 0) break;
1102
+ all.push(...batch);
1103
+ const last = batch[batch.length - 1];
1104
+ if (!last?.updatedAt || !last?.externalId) throw new Error("Invalid Cloud sync response: cursor is missing");
1105
+ if (batch.length < pageSize) break;
1106
+ if (last.updatedAt === cursorTime && last.externalId === cursorId) throw new Error("Invalid Cloud sync response: cursor did not advance");
1107
+ cursorTime = last.updatedAt;
1108
+ cursorId = last.externalId;
1109
+ }
1110
+
1111
+ return all;
1112
+ }
1113
+
1114
+ async function fetchJson(url, { method, token, body }) {
1115
+ const headers = { "content-type": "application/json" };
1116
+ if (token) headers.authorization = `Bearer ${token}`;
1117
+
1118
+ const response = await fetch(url, {
1119
+ method,
1120
+ headers,
1121
+ body: JSON.stringify(body ?? {})
1122
+ });
1123
+ const text = await response.text();
1124
+ if (!response.ok) {
1125
+ let detail = response.statusText;
1126
+ try {
1127
+ const parsed = text ? JSON.parse(text) : {};
1128
+ if (typeof parsed.error === "string") detail = parsed.error;
1129
+ else if (typeof parsed.detail === "string") detail = parsed.detail;
1130
+ } catch {
1131
+ // HTML proxy errors are intentionally not echoed into long-lived logs.
1132
+ }
1133
+ throw new Error(`${method} ${url} failed ${response.status}: ${detail}`);
1134
+ }
1135
+
1136
+ try {
1137
+ return text ? JSON.parse(text) : {};
1138
+ } catch {
1139
+ throw new Error(`${method} ${url} returned invalid JSON response (${response.status})`);
1140
+ }
1141
+ }
1142
+
1143
+ function normalizeStatus(status) {
1144
+ if (status === "active" || status === "candidate" || status === "rejected") return status;
1145
+ if (status === "transient") return "candidate";
1146
+ throw new Error(`Unsupported Recall status: ${status}`);
1147
+ }
1148
+
1149
+ function clampConfidence(value) {
1150
+ const number = Number(value ?? 0);
1151
+ if (!Number.isFinite(number)) return 0;
1152
+ return Math.max(0, Math.min(1, number));
1153
+ }
1154
+
1155
+ function parseJson(value, fallback) {
1156
+ if (value == null || value === "") return fallback;
1157
+ if (typeof value !== "string") return value;
1158
+ try {
1159
+ return JSON.parse(value);
1160
+ } catch {
1161
+ return fallback;
1162
+ }
1163
+ }
1164
+
1165
+ function chunks(values, size) {
1166
+ const result = [];
1167
+ for (let index = 0; index < values.length; index += size) {
1168
+ result.push(values.slice(index, index + size));
1169
+ }
1170
+ return result;
1171
+ }
1172
+
1173
+ function parseOptions(args) {
1174
+ const options = {};
1175
+ for (let index = 0; index < args.length; index++) {
1176
+ const arg = args[index];
1177
+ if (!arg.startsWith("--")) {
1178
+ throw new Error(`Unexpected argument: ${arg}`);
1179
+ }
1180
+ const key = camelCase(arg.slice(2));
1181
+ if (
1182
+ key === "dryRun"
1183
+ || key === "json"
1184
+ || key === "quiet"
1185
+ || key === "e2ee"
1186
+ || key === "sample"
1187
+ || key === "tokenStdin"
1188
+ || key === "forceDeviceId"
1189
+ ) {
1190
+ options[key] = true;
1191
+ continue;
1192
+ }
1193
+ const value = args[index + 1];
1194
+ if (!value || value.startsWith("--")) {
1195
+ throw new Error(`Missing value for ${arg}`);
1196
+ }
1197
+ if (options[key] == null) {
1198
+ options[key] = value;
1199
+ } else if (Array.isArray(options[key])) {
1200
+ options[key].push(value);
1201
+ } else {
1202
+ options[key] = [options[key], value];
1203
+ }
1204
+ index++;
1205
+ }
1206
+ return options;
1207
+ }
1208
+
1209
+ function parseDeviceAliases(value) {
1210
+ const aliases = {};
1211
+ const values = Array.isArray(value) ? value : value == null ? [] : [value];
1212
+ for (const entry of values) {
1213
+ const text = String(entry);
1214
+ const separator = text.indexOf("=");
1215
+ if (separator <= 0 || separator === text.length - 1) {
1216
+ throw new Error(`Invalid --device-alias value: ${text}`);
1217
+ }
1218
+ const from = text.slice(0, separator).trim();
1219
+ const to = text.slice(separator + 1).trim();
1220
+ if (!from || !to || from.includes(":") || to.includes(":")) {
1221
+ throw new Error(`Invalid --device-alias value: ${text}`);
1222
+ }
1223
+ aliases[from] = to;
1224
+ }
1225
+ return aliases;
1226
+ }
1227
+
1228
+ function camelCase(value) {
1229
+ return value.replace(/-([a-z])/g, (_, char) => char.toUpperCase());
1230
+ }
1231
+
1232
+ function required(value, flag) {
1233
+ if (!value) {
1234
+ throw new Error(`${flag} is required`);
1235
+ }
1236
+ return value;
1237
+ }
1238
+
1239
+ function requiredApi(value) {
1240
+ return validateApiUrl(required(value, "--api"));
1241
+ }
1242
+
1243
+ function parseInteger(value, fallback) {
1244
+ if (value == null) return fallback;
1245
+ const parsed = Number.parseInt(String(value), 10);
1246
+ if (!Number.isInteger(parsed) || parsed < 1) {
1247
+ throw new Error(`Invalid integer: ${value}`);
1248
+ }
1249
+ return parsed;
1250
+ }
1251
+
1252
+ export function parseNonNegativeInteger(value, fallback) {
1253
+ if (value == null) return fallback;
1254
+ const parsed = Number.parseInt(String(value), 10);
1255
+ if (!Number.isInteger(parsed) || parsed < 0) {
1256
+ throw new Error(`Invalid integer: ${value}`);
1257
+ }
1258
+ return parsed;
1259
+ }
1260
+
1261
+ function expandHome(value) {
1262
+ if (value === "~") return homedir();
1263
+ if (value.startsWith("~/")) return join(homedir(), value.slice(2));
1264
+ return value;
1265
+ }
1266
+
1267
+ function hostnameLabel() {
1268
+ return process.env.RECALL_CLOUD_DEVICE_ID
1269
+ ?? process.env.HOSTNAME
1270
+ ?? hostname()
1271
+ ?? "local-device";
1272
+ }
1273
+
1274
+ function usage() {
1275
+ console.log(`Usage:
1276
+ node scripts/recall-sync.mjs push --api <url> --token-file <0600-file> [--db ~/.recall/recall.db] [--status active,candidate] [--dry-run] [--sample]
1277
+ node scripts/recall-sync.mjs pull --api <url> --token-file <0600-file> [--db ~/.recall/recall.db] [--since <iso>] [--limit 100000] [--rejected-retention-days 90] [--dry-run]
1278
+ node scripts/recall-sync.mjs verify --api <url> --token-file <0600-file> [--query recall]
1279
+ node scripts/recall-sync.mjs memories --api <url> --token-file <0600-file> [--query <text>] [--device <id>] [--show 40] [--json]
1280
+ node scripts/recall-sync.mjs watch --api <url> --token-file <0600-file> [--interval 300] [--full-reconcile-interval 86400] [--status active,candidate] [--device-id <id>] [--device-alias old=new]
1281
+ printf '%s' "$RECALL_CLOUD_TOKEN" | node scripts/recall-sync.mjs install --api <url> --token-stdin [--interval 300] [--device-id <id>] [--device-alias old=new] [--force-device-id]
1282
+ node scripts/recall-sync.mjs uninstall # remove launchd auto-sync
1283
+
1284
+ E2EE (zero-knowledge): add --e2ee (with --e2ee-passphrase <secret> or RECALL_CLOUD_E2EE_PASSPHRASE)
1285
+ to push/pull/watch to encrypt or decrypt content + metadata client-side; the server stores only
1286
+ ciphertext and cannot search/compile/profile those memories. Add --e2ee to 'memories' to decrypt
1287
+ and read them back locally. Use the SAME passphrase on every device. Tradeoff: e2ee memories are
1288
+ invisible to the web portal, hosted MCP, and server-side search.
1289
+
1290
+ Token sources: --token-file (preferred), --token-stdin (install/one-off), or RECALL_CLOUD_TOKEN.
1291
+ The legacy --token flag remains compatible for one-off commands but exposes its value in process listings.
1292
+ Env fallbacks: RECALL_CLOUD_API, RECALL_CLOUD_TOKEN, RECALL_DB, RECALL_CLOUD_DEVICE_ID, RECALL_CLOUD_E2EE_PASSPHRASE
1293
+ Install refuses accidental device-id changes because local-origin records use it
1294
+ in cloud external IDs; use --force-device-id only for an intentional migration.
1295
+ Use --device-alias old=new during a migration so imported rows that still remember
1296
+ old cloud origins are pushed under the canonical device id.
1297
+ Dry-run push output is count-only by default; add --sample only when plaintext
1298
+ record samples are intentionally needed for debugging.
1299
+ `);
1300
+ }