@edihasaj/recall 2.0.16 → 2.0.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -4
- package/dist/{chunk-Q2F7EQCA.js → chunk-22AJZ7UQ.js} +2 -2
- package/dist/{chunk-GCMP2YYN.js → chunk-2COJXGP4.js} +2 -2
- package/dist/{chunk-SYSSACWJ.js → chunk-CSBXI3ET.js} +39 -20
- package/dist/chunk-CSBXI3ET.js.map +1 -0
- package/dist/{chunk-QPR77YXP.js → chunk-EY6HIDG2.js} +13 -11
- package/dist/chunk-EY6HIDG2.js.map +1 -0
- package/dist/{chunk-GDN44ZC7.js → chunk-FNIIUNW6.js} +2 -2
- package/dist/{chunk-YELXEWKH.js → chunk-GK7OWVRQ.js} +3 -3
- package/dist/{chunk-7UWVXXTU.js → chunk-KLERXJ47.js} +3 -3
- package/dist/{chunk-THC7QOAK.js → chunk-KVZN35JF.js} +7 -7
- package/dist/{chunk-SEXZABB2.js → chunk-Q22B7YDQ.js} +5 -5
- package/dist/{chunk-VRAG5V66.js → chunk-Q7254IPO.js} +908 -43
- package/dist/chunk-Q7254IPO.js.map +1 -0
- package/dist/{chunk-EKFOHVHS.js → chunk-QQ6YHR7I.js} +11 -11
- package/dist/{chunk-MLC3KO2O.js → chunk-RAQT2OBR.js} +7 -7
- package/dist/{chunk-DVLQYARZ.js → chunk-UDLRBKC3.js} +3 -3
- package/dist/{chunk-DOYTMHDI.js → chunk-VUVFQJWZ.js} +2 -2
- package/dist/{chunk-LEOXFQJJ.js → chunk-XRKUJ5B4.js} +2 -2
- package/dist/{chunk-ZF23OPYV.js → chunk-YIUBD27J.js} +14 -14
- package/dist/chunk-YIUBD27J.js.map +1 -0
- package/dist/{chunk-DAW6FUGL.js → chunk-YIVOTIDF.js} +5 -5
- package/dist/{chunk-FYMMTODQ.js → chunk-ZT67CYDS.js} +2 -2
- package/dist/{chunk-FYMMTODQ.js.map → chunk-ZT67CYDS.js.map} +1 -1
- package/dist/{cleanup-WJFE6IVP.js → cleanup-4TXIHTJT.js} +11 -11
- package/dist/cli.js +55 -36
- package/dist/cli.js.map +1 -1
- package/dist/{codex-trust-3BFTJFRD.js → codex-trust-2JIY66CP.js} +4 -4
- package/dist/daemon.js +1090 -169
- package/dist/daemon.js.map +1 -1
- package/dist/dispatcher-O6NGADCQ.js +22 -0
- package/dist/{embeddings-H352GFKD.js → embeddings-AAS7NKGB.js} +5 -5
- package/dist/ingest-DW3AG4M5.js +20 -0
- package/dist/{keychain-A2Z7D7YE.js → keychain-SHRO7W6J.js} +3 -3
- package/dist/mcp.js +15 -15
- package/dist/{memory-value-M3TA7SEK.js → memory-value-R2C7ZSDF.js} +11 -11
- package/dist/{provenance-CXU6LZK7.js → provenance-I5GIAP7N.js} +9 -9
- package/dist/quality-32MAXPNJ.js +25 -0
- package/dist/retrieval-RKYWWNWC.js +15 -0
- package/dist/{store-YCVWABSH.js → store-X2B6MRBH.js} +4 -4
- package/dist/sync-server.js +2 -2
- package/dist/{tasks-4UL2FIAQ.js → tasks-H4NIS6QO.js} +11 -11
- package/dist/{usage-HZ27RG53.js → usage-35HSDMNT.js} +4 -4
- package/package.json +2 -1
- package/vendor/recall-cloud-sync/PROVENANCE.md +27 -0
- package/vendor/recall-cloud-sync/managed-worker.mjs +48 -0
- package/vendor/recall-cloud-sync/private-token.mjs +95 -0
- package/vendor/recall-cloud-sync/recall-sync-local.mjs +406 -0
- package/vendor/recall-cloud-sync/recall-sync.mjs +1266 -0
- package/dist/chunk-QPR77YXP.js.map +0 -1
- package/dist/chunk-SYSSACWJ.js.map +0 -1
- package/dist/chunk-VRAG5V66.js.map +0 -1
- package/dist/chunk-ZF23OPYV.js.map +0 -1
- package/dist/dispatcher-5JVGZNWT.js +0 -22
- package/dist/ingest-NVYEOSVZ.js +0 -20
- package/dist/quality-4CG6U273.js +0 -25
- package/dist/retrieval-42CPYUDW.js +0 -15
- /package/dist/{chunk-Q2F7EQCA.js.map → chunk-22AJZ7UQ.js.map} +0 -0
- /package/dist/{chunk-GCMP2YYN.js.map → chunk-2COJXGP4.js.map} +0 -0
- /package/dist/{chunk-GDN44ZC7.js.map → chunk-FNIIUNW6.js.map} +0 -0
- /package/dist/{chunk-YELXEWKH.js.map → chunk-GK7OWVRQ.js.map} +0 -0
- /package/dist/{chunk-7UWVXXTU.js.map → chunk-KLERXJ47.js.map} +0 -0
- /package/dist/{chunk-THC7QOAK.js.map → chunk-KVZN35JF.js.map} +0 -0
- /package/dist/{chunk-SEXZABB2.js.map → chunk-Q22B7YDQ.js.map} +0 -0
- /package/dist/{chunk-EKFOHVHS.js.map → chunk-QQ6YHR7I.js.map} +0 -0
- /package/dist/{chunk-MLC3KO2O.js.map → chunk-RAQT2OBR.js.map} +0 -0
- /package/dist/{chunk-DVLQYARZ.js.map → chunk-UDLRBKC3.js.map} +0 -0
- /package/dist/{chunk-DOYTMHDI.js.map → chunk-VUVFQJWZ.js.map} +0 -0
- /package/dist/{chunk-LEOXFQJJ.js.map → chunk-XRKUJ5B4.js.map} +0 -0
- /package/dist/{chunk-DAW6FUGL.js.map → chunk-YIVOTIDF.js.map} +0 -0
- /package/dist/{cleanup-WJFE6IVP.js.map → cleanup-4TXIHTJT.js.map} +0 -0
- /package/dist/{codex-trust-3BFTJFRD.js.map → codex-trust-2JIY66CP.js.map} +0 -0
- /package/dist/{dispatcher-5JVGZNWT.js.map → dispatcher-O6NGADCQ.js.map} +0 -0
- /package/dist/{embeddings-H352GFKD.js.map → embeddings-AAS7NKGB.js.map} +0 -0
- /package/dist/{ingest-NVYEOSVZ.js.map → ingest-DW3AG4M5.js.map} +0 -0
- /package/dist/{keychain-A2Z7D7YE.js.map → keychain-SHRO7W6J.js.map} +0 -0
- /package/dist/{memory-value-M3TA7SEK.js.map → memory-value-R2C7ZSDF.js.map} +0 -0
- /package/dist/{provenance-CXU6LZK7.js.map → provenance-I5GIAP7N.js.map} +0 -0
- /package/dist/{quality-4CG6U273.js.map → quality-32MAXPNJ.js.map} +0 -0
- /package/dist/{retrieval-42CPYUDW.js.map → retrieval-RKYWWNWC.js.map} +0 -0
- /package/dist/{store-YCVWABSH.js.map → store-X2B6MRBH.js.map} +0 -0
- /package/dist/{tasks-4UL2FIAQ.js.map → tasks-H4NIS6QO.js.map} +0 -0
- /package/dist/{usage-HZ27RG53.js.map → usage-35HSDMNT.js.map} +0 -0
|
@@ -0,0 +1,406 @@
|
|
|
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
|
+
function cloudRecordToLocalRow(record, { deviceId, e2ee, decrypt, deviceAliases }) {
|
|
200
|
+
let text = record.contentPlaintext;
|
|
201
|
+
let metadata = record.metadata && typeof record.metadata === "object" ? record.metadata : {};
|
|
202
|
+
if (record.encryptionMode === "e2ee") {
|
|
203
|
+
if (!e2ee || !decrypt || !record.contentCiphertext || !record.contentNonce) return null;
|
|
204
|
+
try {
|
|
205
|
+
const payload = JSON.parse(
|
|
206
|
+
decrypt(e2ee.key, record.contentCiphertext, record.contentNonce)
|
|
207
|
+
);
|
|
208
|
+
text = payload.text;
|
|
209
|
+
metadata = { ...metadata, recall: payload.recall };
|
|
210
|
+
} catch {
|
|
211
|
+
return null;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
if (typeof text !== "string" || !text.trim()) return null;
|
|
215
|
+
|
|
216
|
+
const recall = metadata.recall && typeof metadata.recall === "object" ? metadata.recall : {};
|
|
217
|
+
const localMemoryId = typeof metadata.localMemoryId === "string" && metadata.localMemoryId
|
|
218
|
+
? metadata.localMemoryId
|
|
219
|
+
: `cloud-${createHash("sha256").update(String(record.externalId)).digest("hex").slice(0, 32)}`;
|
|
220
|
+
const captureContext = recall.captureContext
|
|
221
|
+
&& typeof recall.captureContext === "object"
|
|
222
|
+
&& !Array.isArray(recall.captureContext)
|
|
223
|
+
? { ...recall.captureContext }
|
|
224
|
+
: {};
|
|
225
|
+
const externalId = canonicalExternalId(String(record.externalId), deviceAliases);
|
|
226
|
+
const metadataDeviceId = canonicalDeviceId(metadata.deviceId ?? null, deviceAliases);
|
|
227
|
+
const isOwnRecord = externalId === `${deviceId}:${localMemoryId}`;
|
|
228
|
+
if (!isOwnRecord) {
|
|
229
|
+
captureContext.recallCloudSync = {
|
|
230
|
+
externalId,
|
|
231
|
+
deviceId: metadataDeviceId
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const status = record.status === "deleted" ? "rejected" : normalizeStatus(record.status);
|
|
236
|
+
const updatedAt = String(record.updatedAt ?? new Date().toISOString());
|
|
237
|
+
return {
|
|
238
|
+
id: localMemoryId,
|
|
239
|
+
type: String(recall.type ?? record.kind ?? "decision"),
|
|
240
|
+
text,
|
|
241
|
+
note: typeof recall.note === "string" ? recall.note.replace(/\s+/g, " ").trim() || null : null,
|
|
242
|
+
note_present: Object.hasOwn(recall, "note") ? 1 : 0,
|
|
243
|
+
scope: String(recall.scope ?? (recall.repo ? "repo" : "global")),
|
|
244
|
+
path_scope: nullableString(recall.pathScope),
|
|
245
|
+
repo: nullableString(recall.repo),
|
|
246
|
+
status,
|
|
247
|
+
confidence: clampConfidence(record.confidence),
|
|
248
|
+
source: String(recall.source ?? metadata.source ?? "cloud_sync"),
|
|
249
|
+
evidence: JSON.stringify(Array.isArray(recall.evidence) ? recall.evidence : []),
|
|
250
|
+
capture_context: Object.keys(captureContext).length ? JSON.stringify(captureContext) : null,
|
|
251
|
+
supersedes: nullableString(recall.supersedes),
|
|
252
|
+
created_at: String(record.createdAt ?? updatedAt),
|
|
253
|
+
updated_at: updatedAt,
|
|
254
|
+
last_validated_at: nullableString(recall.lastValidatedAt),
|
|
255
|
+
last_injected_at: nullableString(recall.lastInjectedAt),
|
|
256
|
+
injection_count: safeInteger(recall.injectionCount),
|
|
257
|
+
override_count: safeInteger(recall.overrideCount),
|
|
258
|
+
repetition_count: safeInteger(recall.repetitionCount),
|
|
259
|
+
team_id: nullableString(recall.teamId),
|
|
260
|
+
sync_version: safeInteger(recall.syncVersion),
|
|
261
|
+
auto_inject: recall.autoInject === false ? 0 : 1,
|
|
262
|
+
dedupe_key: nullableString(recall.dedupeKey)
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export function canonicalExternalId(externalId, deviceAliases = {}) {
|
|
267
|
+
const value = String(externalId);
|
|
268
|
+
const index = value.indexOf(":");
|
|
269
|
+
if (index === -1) return value;
|
|
270
|
+
const prefix = value.slice(0, index);
|
|
271
|
+
return `${canonicalDeviceId(prefix, deviceAliases)}${value.slice(index)}`;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function canonicalDeviceId(deviceId, deviceAliases = {}) {
|
|
275
|
+
if (deviceId == null) return null;
|
|
276
|
+
const value = String(deviceId);
|
|
277
|
+
return Object.prototype.hasOwnProperty.call(deviceAliases, value)
|
|
278
|
+
? String(deviceAliases[value])
|
|
279
|
+
: value;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function assertRecallSchema(db) {
|
|
283
|
+
const columns = new Set(db.prepare("PRAGMA table_info(memories)").all().map((row) => row.name));
|
|
284
|
+
for (const requiredColumn of ["id", "type", "text", "status", "updated_at", "dedupe_key"]) {
|
|
285
|
+
if (!columns.has(requiredColumn)) {
|
|
286
|
+
throw new Error(`Recall DB schema is incompatible: memories.${requiredColumn} is missing`);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function syncLocalSearchIndexes(db, row, textChanged) {
|
|
292
|
+
if (tableExists(db, "fts_memory_index")) {
|
|
293
|
+
db.prepare("DELETE FROM fts_memory_index WHERE memory_id = ?").run(row.id);
|
|
294
|
+
if (row.status !== "rejected" && row.status !== "transient") {
|
|
295
|
+
db.prepare(`
|
|
296
|
+
INSERT INTO fts_memory_index (
|
|
297
|
+
memory_id, text, repo, status, type, scope, path_scope
|
|
298
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
299
|
+
`).run(
|
|
300
|
+
row.id,
|
|
301
|
+
row.note ? `${row.text} Affects: ${row.note}` : row.text,
|
|
302
|
+
row.repo ?? "",
|
|
303
|
+
row.status,
|
|
304
|
+
row.type,
|
|
305
|
+
row.scope,
|
|
306
|
+
row.path_scope ?? ""
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
if (textChanged && tableExists(db, "memory_embeddings")) {
|
|
311
|
+
db.prepare("DELETE FROM memory_embeddings WHERE memory_id = ?").run(row.id);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// Pull writes previously left no trace in audit_trail, so imported memories
|
|
316
|
+
// were unexplainable after the fact. Best-effort: skipped when the local DB
|
|
317
|
+
// predates the audit_trail table.
|
|
318
|
+
function recordSyncAudit(db, action, after, before, reason) {
|
|
319
|
+
if (!tableExists(db, "audit_trail")) return;
|
|
320
|
+
db.prepare(`
|
|
321
|
+
INSERT INTO audit_trail (
|
|
322
|
+
id, memory_id, action, actor, before_snapshot, after_snapshot, reason, timestamp
|
|
323
|
+
) VALUES (?, ?, ?, 'cloud-sync', ?, ?, ?, ?)
|
|
324
|
+
`).run(
|
|
325
|
+
randomUUID(),
|
|
326
|
+
after.id,
|
|
327
|
+
action,
|
|
328
|
+
before ? JSON.stringify(before) : null,
|
|
329
|
+
JSON.stringify(after),
|
|
330
|
+
reason,
|
|
331
|
+
new Date().toISOString()
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function tableExists(db, name) {
|
|
336
|
+
return Boolean(
|
|
337
|
+
db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name)
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function isRemoteNewer(remote, local) {
|
|
342
|
+
const remoteMs = Date.parse(String(remote));
|
|
343
|
+
const localMs = Date.parse(String(local));
|
|
344
|
+
if (Number.isFinite(remoteMs) && Number.isFinite(localMs)) return remoteMs > localMs;
|
|
345
|
+
return String(remote) > String(local);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function preferDuplicateQuality(remote, local) {
|
|
349
|
+
const remoteQuality = [
|
|
350
|
+
statusRank(remote.status),
|
|
351
|
+
Number(remote.auto_inject === 1),
|
|
352
|
+
Number(remote.confidence ?? 0),
|
|
353
|
+
safeInteger(remote.injection_count),
|
|
354
|
+
Date.parse(String(remote.updated_at)) || 0
|
|
355
|
+
];
|
|
356
|
+
const localQuality = [
|
|
357
|
+
statusRank(local.status),
|
|
358
|
+
Number(local.auto_inject === 1),
|
|
359
|
+
Number(local.confidence ?? 0),
|
|
360
|
+
safeInteger(local.injection_count),
|
|
361
|
+
Date.parse(String(local.updated_at)) || 0
|
|
362
|
+
];
|
|
363
|
+
for (let index = 0; index < remoteQuality.length; index++) {
|
|
364
|
+
if (remoteQuality[index] !== localQuality[index]) {
|
|
365
|
+
return remoteQuality[index] > localQuality[index];
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
return false;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function statusRank(status) {
|
|
372
|
+
if (status === "active") return 3;
|
|
373
|
+
if (status === "candidate") return 2;
|
|
374
|
+
return 1;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function normalizeStatus(status) {
|
|
378
|
+
if (status === "active" || status === "candidate" || status === "rejected") return status;
|
|
379
|
+
if (status === "transient") return "candidate";
|
|
380
|
+
throw new Error(`Unsupported Recall status: ${status}`);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
function clampConfidence(value) {
|
|
384
|
+
const number = Number(value ?? 0);
|
|
385
|
+
if (!Number.isFinite(number)) return 0;
|
|
386
|
+
return Math.max(0, Math.min(1, number));
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function nullableString(value) {
|
|
390
|
+
return value == null || value === "" ? null : String(value);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
function safeInteger(value) {
|
|
394
|
+
const number = Number(value ?? 0);
|
|
395
|
+
return Number.isSafeInteger(number) && number >= 0 ? number : 0;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
function parseJson(value, fallback) {
|
|
399
|
+
if (value == null || value === "") return fallback;
|
|
400
|
+
if (typeof value !== "string") return value;
|
|
401
|
+
try {
|
|
402
|
+
return JSON.parse(value);
|
|
403
|
+
} catch {
|
|
404
|
+
return fallback;
|
|
405
|
+
}
|
|
406
|
+
}
|