@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,415 @@
1
+ import Database from "better-sqlite3";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { existsSync } from "node:fs";
4
+
5
+ export function cloudExternalIdForRow(row, deviceId, deviceAliases = {}) {
6
+ const captureContext = parseJson(row.capture_context, null);
7
+ const importedExternalId = captureContext
8
+ && typeof captureContext === "object"
9
+ && !Array.isArray(captureContext)
10
+ && captureContext.recallCloudSync
11
+ && typeof captureContext.recallCloudSync === "object"
12
+ ? captureContext.recallCloudSync.externalId
13
+ : null;
14
+ return importedExternalId
15
+ ? canonicalExternalId(String(importedExternalId), deviceAliases)
16
+ : `${deviceId}:${row.id}`;
17
+ }
18
+
19
+ export function applyPulledRecords(
20
+ dbPath,
21
+ records,
22
+ {
23
+ deviceId,
24
+ e2ee = null,
25
+ decrypt = null,
26
+ deviceAliases = {},
27
+ rejectedRetentionDays = 90,
28
+ now = Date.now()
29
+ }
30
+ ) {
31
+ if (!existsSync(dbPath)) {
32
+ throw new Error(`Recall DB not found: ${dbPath}`);
33
+ }
34
+
35
+ const db = new Database(dbPath, { fileMustExist: true });
36
+ db.pragma("busy_timeout = 5000");
37
+ db.pragma("foreign_keys = ON");
38
+
39
+ try {
40
+ assertRecallSchema(db);
41
+ const hasNote = db.prepare("PRAGMA table_info(memories)").all().some((column) => column.name === "note");
42
+ const findById = db.prepare("SELECT * FROM memories WHERE id = ?");
43
+ const findByDedupe = db.prepare(
44
+ "SELECT * FROM memories WHERE dedupe_key = ? LIMIT 1"
45
+ );
46
+ const insert = db.prepare(`
47
+ INSERT INTO memories (
48
+ id, type, text, scope, path_scope, repo, status, confidence, source,
49
+ evidence, capture_context, supersedes, created_at, updated_at,
50
+ last_validated_at, last_injected_at, injection_count, override_count,
51
+ repetition_count, team_id, sync_version, auto_inject, dedupe_key${hasNote ? ", note" : ""}
52
+ ) VALUES (
53
+ @id, @type, @text, @scope, @path_scope, @repo, @status, @confidence, @source,
54
+ @evidence, @capture_context, @supersedes, @created_at, @updated_at,
55
+ @last_validated_at, @last_injected_at, @injection_count, @override_count,
56
+ @repetition_count, @team_id, @sync_version, @auto_inject, @dedupe_key${hasNote ? ", @note" : ""}
57
+ )
58
+ `);
59
+ const update = db.prepare(`
60
+ UPDATE memories SET
61
+ type = @type,
62
+ text = @text,
63
+ scope = @scope,
64
+ path_scope = @path_scope,
65
+ repo = @repo,
66
+ status = @status,
67
+ confidence = @confidence,
68
+ source = @source,
69
+ evidence = @evidence,
70
+ capture_context = @capture_context,
71
+ supersedes = @supersedes,
72
+ updated_at = @updated_at,
73
+ last_validated_at = @last_validated_at,
74
+ last_injected_at = @last_injected_at,
75
+ injection_count = @injection_count,
76
+ override_count = @override_count,
77
+ repetition_count = @repetition_count,
78
+ team_id = @team_id,
79
+ auto_inject = @auto_inject,
80
+ dedupe_key = @dedupe_key${hasNote ? ", note = @note" : ""}
81
+ WHERE id = @id
82
+ `);
83
+ const stats = {
84
+ imported: 0,
85
+ updated: 0,
86
+ unchanged: 0,
87
+ skippedEncrypted: 0,
88
+ skippedDuplicate: 0,
89
+ skippedExpiredTombstone: 0
90
+ };
91
+
92
+ const apply = db.transaction(() => {
93
+ for (const record of records) {
94
+ const local = cloudRecordToLocalRow(record, { deviceId, e2ee, decrypt, deviceAliases });
95
+ if (!local) {
96
+ stats.skippedEncrypted++;
97
+ continue;
98
+ }
99
+
100
+ // Quarantine foreign promotions: a record captured on another device
101
+ // arrives here as candidate at most. Local gates (repetition, verify,
102
+ // explicit confirm) are the only paths to active on this device —
103
+ // trusting a remote 'active' imported 0.99-confidence LLM-worker
104
+ // prompt extractions straight into the injection set, with no audit.
105
+ const isForeign = Boolean(parseJson(local.capture_context, null)?.recallCloudSync);
106
+ const quarantined = isForeign && local.status === "active";
107
+ if (quarantined) local.status = "candidate";
108
+ // The no-demote/merge guards below may reinstate "active"; the audit
109
+ // reason must describe what actually happened, so it is finalized at
110
+ // write time via auditReason(), not here.
111
+ const baseReason = `pull:${canonicalExternalId(String(record.externalId), deviceAliases)}`;
112
+ const auditReason = (finalStatus) => {
113
+ if (!quarantined) return baseReason;
114
+ return finalStatus === "candidate"
115
+ ? `${baseReason} quarantined:active->candidate`
116
+ : `${baseReason} quarantine-reinstated:local-active`;
117
+ };
118
+
119
+ const existing = findById.get(local.id);
120
+ if (!hasNote) local.note = null;
121
+ else if (!local.note_present) local.note = existing?.note ?? null;
122
+ if (!existing) {
123
+ // Recall intentionally removes rejected rows after local retention.
124
+ // Keep applying old tombstones to rows that still exist, but do not
125
+ // recreate a missing expired row on every full cloud reconciliation.
126
+ if (isExpiredRejectedTombstone(local, rejectedRetentionDays, now)) {
127
+ stats.skippedExpiredTombstone++;
128
+ continue;
129
+ }
130
+ const duplicate = local.dedupe_key
131
+ ? findByDedupe.get(local.dedupe_key)
132
+ : null;
133
+ if (duplicate) {
134
+ if (preferDuplicateQuality(local, duplicate)) {
135
+ const merged = {
136
+ ...local,
137
+ id: duplicate.id,
138
+ created_at: duplicate.created_at,
139
+ capture_context: duplicate.capture_context
140
+ };
141
+ if (hasNote && !local.note_present) merged.note = duplicate.note ?? null;
142
+ if (duplicate.status === "active" && merged.status === "candidate") {
143
+ merged.status = "active";
144
+ }
145
+ update.run(merged);
146
+ syncLocalSearchIndexes(db, merged, duplicate.text !== merged.text || (duplicate.note ?? null) !== merged.note);
147
+ recordSyncAudit(db, "edited", merged, duplicate, auditReason(merged.status));
148
+ stats.updated++;
149
+ } else {
150
+ stats.skippedDuplicate++;
151
+ }
152
+ continue;
153
+ }
154
+ insert.run(local);
155
+ syncLocalSearchIndexes(db, local, true);
156
+ recordSyncAudit(db, "created", local, null, auditReason(local.status));
157
+ stats.imported++;
158
+ continue;
159
+ }
160
+
161
+ if (!isRemoteNewer(local.updated_at, existing.updated_at)) {
162
+ stats.unchanged++;
163
+ continue;
164
+ }
165
+
166
+ // A pull never demotes a locally-promoted active back to candidate;
167
+ // rejection (an explicit user decision on any device) still applies.
168
+ if (existing.status === "active" && local.status === "candidate") {
169
+ local.status = "active";
170
+ }
171
+
172
+ if (
173
+ local.dedupe_key
174
+ && local.dedupe_key !== existing.dedupe_key
175
+ && findByDedupe.get(local.dedupe_key)
176
+ ) {
177
+ local.dedupe_key = null;
178
+ }
179
+ update.run(local);
180
+ syncLocalSearchIndexes(db, local, existing.text !== local.text || (existing.note ?? null) !== local.note);
181
+ recordSyncAudit(db, "edited", local, existing, auditReason(local.status));
182
+ stats.updated++;
183
+ }
184
+ });
185
+ apply();
186
+ return stats;
187
+ } finally {
188
+ db.close();
189
+ }
190
+ }
191
+
192
+ function isExpiredRejectedTombstone(row, retentionDays, now) {
193
+ if (row.status !== "rejected") return false;
194
+ const updatedMs = Date.parse(String(row.updated_at));
195
+ if (!Number.isFinite(updatedMs)) return false;
196
+ return updatedMs < now - retentionDays * 86_400_000;
197
+ }
198
+
199
+ export function decryptCloudPayload(record, e2ee, decrypt) {
200
+ try {
201
+ if (!record.contentCiphertext || !record.contentNonce || !decrypt) throw new Error();
202
+ const payload = JSON.parse(decrypt(e2ee.key, record.contentCiphertext, record.contentNonce));
203
+ if (!payload || typeof payload.text !== "string" || !payload.text.trim()
204
+ || !payload.recall || typeof payload.recall !== "object" || Array.isArray(payload.recall)) {
205
+ throw new Error();
206
+ }
207
+ return payload;
208
+ } catch {
209
+ // Do not leak crypto errors, record contents, or keys to engine logs.
210
+ throw new Error("E2EE verification failed. Check the original passphrase; encrypted data may also be damaged. Sync was stopped.");
211
+ }
212
+ }
213
+
214
+ function cloudRecordToLocalRow(record, { deviceId, e2ee, decrypt, deviceAliases }) {
215
+ let text = record.contentPlaintext;
216
+ let metadata = record.metadata && typeof record.metadata === "object" ? record.metadata : {};
217
+ if (record.encryptionMode === "e2ee") {
218
+ if (!e2ee) return null;
219
+ const payload = decryptCloudPayload(record, e2ee, decrypt);
220
+ text = payload.text;
221
+ metadata = { ...metadata, recall: payload.recall };
222
+ }
223
+ if (typeof text !== "string" || !text.trim()) return null;
224
+
225
+ const recall = metadata.recall && typeof metadata.recall === "object" ? metadata.recall : {};
226
+ const localMemoryId = typeof metadata.localMemoryId === "string" && metadata.localMemoryId
227
+ ? metadata.localMemoryId
228
+ : `cloud-${createHash("sha256").update(String(record.externalId)).digest("hex").slice(0, 32)}`;
229
+ const captureContext = recall.captureContext
230
+ && typeof recall.captureContext === "object"
231
+ && !Array.isArray(recall.captureContext)
232
+ ? { ...recall.captureContext }
233
+ : {};
234
+ const externalId = canonicalExternalId(String(record.externalId), deviceAliases);
235
+ const metadataDeviceId = canonicalDeviceId(metadata.deviceId ?? null, deviceAliases);
236
+ const isOwnRecord = externalId === `${deviceId}:${localMemoryId}`;
237
+ if (!isOwnRecord) {
238
+ captureContext.recallCloudSync = {
239
+ externalId,
240
+ deviceId: metadataDeviceId
241
+ };
242
+ }
243
+
244
+ const status = record.status === "deleted" ? "rejected" : normalizeStatus(record.status);
245
+ const updatedAt = String(record.updatedAt ?? new Date().toISOString());
246
+ return {
247
+ id: localMemoryId,
248
+ type: String(recall.type ?? record.kind ?? "decision"),
249
+ text,
250
+ note: typeof recall.note === "string" ? recall.note.replace(/\s+/g, " ").trim() || null : null,
251
+ note_present: Object.hasOwn(recall, "note") ? 1 : 0,
252
+ scope: String(recall.scope ?? (recall.repo ? "repo" : "global")),
253
+ path_scope: nullableString(recall.pathScope),
254
+ repo: nullableString(recall.repo),
255
+ status,
256
+ confidence: clampConfidence(record.confidence),
257
+ source: String(recall.source ?? metadata.source ?? "cloud_sync"),
258
+ evidence: JSON.stringify(Array.isArray(recall.evidence) ? recall.evidence : []),
259
+ capture_context: Object.keys(captureContext).length ? JSON.stringify(captureContext) : null,
260
+ supersedes: nullableString(recall.supersedes),
261
+ created_at: String(record.createdAt ?? updatedAt),
262
+ updated_at: updatedAt,
263
+ last_validated_at: nullableString(recall.lastValidatedAt),
264
+ last_injected_at: nullableString(recall.lastInjectedAt),
265
+ injection_count: safeInteger(recall.injectionCount),
266
+ override_count: safeInteger(recall.overrideCount),
267
+ repetition_count: safeInteger(recall.repetitionCount),
268
+ team_id: nullableString(recall.teamId),
269
+ sync_version: safeInteger(recall.syncVersion),
270
+ auto_inject: recall.autoInject === false ? 0 : 1,
271
+ dedupe_key: nullableString(recall.dedupeKey)
272
+ };
273
+ }
274
+
275
+ export function canonicalExternalId(externalId, deviceAliases = {}) {
276
+ const value = String(externalId);
277
+ const index = value.indexOf(":");
278
+ if (index === -1) return value;
279
+ const prefix = value.slice(0, index);
280
+ return `${canonicalDeviceId(prefix, deviceAliases)}${value.slice(index)}`;
281
+ }
282
+
283
+ function canonicalDeviceId(deviceId, deviceAliases = {}) {
284
+ if (deviceId == null) return null;
285
+ const value = String(deviceId);
286
+ return Object.prototype.hasOwnProperty.call(deviceAliases, value)
287
+ ? String(deviceAliases[value])
288
+ : value;
289
+ }
290
+
291
+ function assertRecallSchema(db) {
292
+ const columns = new Set(db.prepare("PRAGMA table_info(memories)").all().map((row) => row.name));
293
+ for (const requiredColumn of ["id", "type", "text", "status", "updated_at", "dedupe_key"]) {
294
+ if (!columns.has(requiredColumn)) {
295
+ throw new Error(`Recall DB schema is incompatible: memories.${requiredColumn} is missing`);
296
+ }
297
+ }
298
+ }
299
+
300
+ function syncLocalSearchIndexes(db, row, textChanged) {
301
+ if (tableExists(db, "fts_memory_index")) {
302
+ db.prepare("DELETE FROM fts_memory_index WHERE memory_id = ?").run(row.id);
303
+ if (row.status !== "rejected" && row.status !== "transient") {
304
+ db.prepare(`
305
+ INSERT INTO fts_memory_index (
306
+ memory_id, text, repo, status, type, scope, path_scope
307
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
308
+ `).run(
309
+ row.id,
310
+ row.note ? `${row.text} Affects: ${row.note}` : row.text,
311
+ row.repo ?? "",
312
+ row.status,
313
+ row.type,
314
+ row.scope,
315
+ row.path_scope ?? ""
316
+ );
317
+ }
318
+ }
319
+ if (textChanged && tableExists(db, "memory_embeddings")) {
320
+ db.prepare("DELETE FROM memory_embeddings WHERE memory_id = ?").run(row.id);
321
+ }
322
+ }
323
+
324
+ // Pull writes previously left no trace in audit_trail, so imported memories
325
+ // were unexplainable after the fact. Best-effort: skipped when the local DB
326
+ // predates the audit_trail table.
327
+ function recordSyncAudit(db, action, after, before, reason) {
328
+ if (!tableExists(db, "audit_trail")) return;
329
+ db.prepare(`
330
+ INSERT INTO audit_trail (
331
+ id, memory_id, action, actor, before_snapshot, after_snapshot, reason, timestamp
332
+ ) VALUES (?, ?, ?, 'cloud-sync', ?, ?, ?, ?)
333
+ `).run(
334
+ randomUUID(),
335
+ after.id,
336
+ action,
337
+ before ? JSON.stringify(before) : null,
338
+ JSON.stringify(after),
339
+ reason,
340
+ new Date().toISOString()
341
+ );
342
+ }
343
+
344
+ function tableExists(db, name) {
345
+ return Boolean(
346
+ db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name)
347
+ );
348
+ }
349
+
350
+ function isRemoteNewer(remote, local) {
351
+ const remoteMs = Date.parse(String(remote));
352
+ const localMs = Date.parse(String(local));
353
+ if (Number.isFinite(remoteMs) && Number.isFinite(localMs)) return remoteMs > localMs;
354
+ return String(remote) > String(local);
355
+ }
356
+
357
+ function preferDuplicateQuality(remote, local) {
358
+ const remoteQuality = [
359
+ statusRank(remote.status),
360
+ Number(remote.auto_inject === 1),
361
+ Number(remote.confidence ?? 0),
362
+ safeInteger(remote.injection_count),
363
+ Date.parse(String(remote.updated_at)) || 0
364
+ ];
365
+ const localQuality = [
366
+ statusRank(local.status),
367
+ Number(local.auto_inject === 1),
368
+ Number(local.confidence ?? 0),
369
+ safeInteger(local.injection_count),
370
+ Date.parse(String(local.updated_at)) || 0
371
+ ];
372
+ for (let index = 0; index < remoteQuality.length; index++) {
373
+ if (remoteQuality[index] !== localQuality[index]) {
374
+ return remoteQuality[index] > localQuality[index];
375
+ }
376
+ }
377
+ return false;
378
+ }
379
+
380
+ function statusRank(status) {
381
+ if (status === "active") return 3;
382
+ if (status === "candidate") return 2;
383
+ return 1;
384
+ }
385
+
386
+ function normalizeStatus(status) {
387
+ if (status === "active" || status === "candidate" || status === "rejected") return status;
388
+ if (status === "transient") return "candidate";
389
+ throw new Error(`Unsupported Recall status: ${status}`);
390
+ }
391
+
392
+ function clampConfidence(value) {
393
+ const number = Number(value ?? 0);
394
+ if (!Number.isFinite(number)) return 0;
395
+ return Math.max(0, Math.min(1, number));
396
+ }
397
+
398
+ function nullableString(value) {
399
+ return value == null || value === "" ? null : String(value);
400
+ }
401
+
402
+ function safeInteger(value) {
403
+ const number = Number(value ?? 0);
404
+ return Number.isSafeInteger(number) && number >= 0 ? number : 0;
405
+ }
406
+
407
+ function parseJson(value, fallback) {
408
+ if (value == null || value === "") return fallback;
409
+ if (typeof value !== "string") return value;
410
+ try {
411
+ return JSON.parse(value);
412
+ } catch {
413
+ return fallback;
414
+ }
415
+ }