@chainlesschain/personal-data-hub 0.2.4 → 0.3.0

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 (55) hide show
  1. package/__tests__/adapters/browser-history-chrome.test.js +377 -0
  2. package/__tests__/adapters/browser-history-edge.test.js +159 -0
  3. package/__tests__/adapters/git-activity.test.js +216 -0
  4. package/__tests__/adapters/local-files.test.js +264 -0
  5. package/__tests__/adapters/shell-history.test.js +180 -0
  6. package/__tests__/adapters/system-data-android.test.js +104 -3
  7. package/__tests__/adapters/vscode.test.js +299 -0
  8. package/__tests__/adapters/win-recent.test.js +192 -0
  9. package/__tests__/analysis.test.js +840 -1
  10. package/__tests__/categories.test.js +92 -0
  11. package/__tests__/e2e/local-data-adapters-cli.e2e.test.js +146 -0
  12. package/__tests__/entity-resolver-vault.test.js +5 -2
  13. package/__tests__/integration/local-data-adapters-pipeline.test.js +373 -0
  14. package/__tests__/query-parser.test.js +66 -0
  15. package/__tests__/registry.test.js +114 -0
  16. package/__tests__/sidecar-contacts-cross-validate.test.js +24 -1
  17. package/__tests__/sidecar-supervisor.test.js +9 -1
  18. package/__tests__/social-kuaishou-snapshot.test.js +55 -2
  19. package/__tests__/social-toutiao-snapshot.test.js +54 -2
  20. package/__tests__/vault-search-helpers.test.js +104 -0
  21. package/__tests__/vault-search.test.js +423 -0
  22. package/__tests__/vault.test.js +77 -3
  23. package/lib/adapters/browser-history-chrome/adapter.js +247 -0
  24. package/lib/adapters/browser-history-chrome/bookmarks-reader.js +79 -0
  25. package/lib/adapters/browser-history-chrome/chrome-db-reader.js +223 -0
  26. package/lib/adapters/browser-history-chrome/index.js +23 -0
  27. package/lib/adapters/browser-history-edge/adapter.js +34 -0
  28. package/lib/adapters/browser-history-edge/index.js +13 -0
  29. package/lib/adapters/git-activity/adapter.js +155 -0
  30. package/lib/adapters/git-activity/git-reader.js +125 -0
  31. package/lib/adapters/git-activity/index.js +17 -0
  32. package/lib/adapters/local-files/adapter.js +149 -0
  33. package/lib/adapters/local-files/file-walker.js +125 -0
  34. package/lib/adapters/local-files/index.js +18 -0
  35. package/lib/adapters/shell-history/adapter.js +137 -0
  36. package/lib/adapters/shell-history/index.js +17 -0
  37. package/lib/adapters/shell-history/shell-reader.js +100 -0
  38. package/lib/adapters/social-kuaishou/index.js +57 -1
  39. package/lib/adapters/social-toutiao/index.js +59 -1
  40. package/lib/adapters/system-data-android/adapter.js +220 -3
  41. package/lib/adapters/vscode/adapter.js +285 -0
  42. package/lib/adapters/vscode/index.js +18 -0
  43. package/lib/adapters/vscode/vscode-reader.js +191 -0
  44. package/lib/adapters/win-recent/adapter.js +150 -0
  45. package/lib/adapters/win-recent/index.js +16 -0
  46. package/lib/adapters/win-recent/win-recent-reader.js +72 -0
  47. package/lib/analysis.js +227 -9
  48. package/lib/categories.js +101 -0
  49. package/lib/index.js +61 -0
  50. package/lib/migrations.js +146 -0
  51. package/lib/query-parser.js +74 -0
  52. package/lib/registry.js +162 -0
  53. package/lib/vault.js +363 -2
  54. package/package.json +2 -1
  55. package/scripts/run-native-tests-sandbox.sh +53 -0
@@ -0,0 +1,423 @@
1
+ "use strict";
2
+
3
+ import { describe, it, expect, beforeEach, afterEach } from "vitest";
4
+
5
+ const fs = require("node:fs");
6
+ const os = require("node:os");
7
+ const path = require("node:path");
8
+
9
+ const { newId } = require("../lib/ids");
10
+ const { generateKeyHex } = require("../lib/key-providers");
11
+ const { LocalVault } = require("../lib/vault");
12
+ const { TARGET_VERSION, getFtsMode } = require("../lib/migrations");
13
+
14
+ // ─── Fixtures ─────────────────────────────────────────────────────────────
15
+
16
+ const source = (adapter = "test", overrides = {}) => ({
17
+ adapter,
18
+ adapterVersion: "0.1.0",
19
+ capturedAt: Date.now(),
20
+ capturedBy: "manual",
21
+ ...overrides,
22
+ });
23
+
24
+ const eventOk = (overrides = {}) => ({
25
+ id: newId(),
26
+ type: "event",
27
+ subtype: "message",
28
+ occurredAt: Date.now(),
29
+ ingestedAt: Date.now(),
30
+ content: { text: "Hello" },
31
+ source: source(),
32
+ ...overrides,
33
+ });
34
+
35
+ // Realistic per-category seed data — one event per major category so the
36
+ // browser sidebar can be exercised end-to-end. CJK + ASCII mixed.
37
+ function seedMixedCategories(vault, baseTime = 1700000000000) {
38
+ const seeds = [
39
+ {
40
+ adapter: "wechat",
41
+ subtype: "message",
42
+ content: { text: "妈妈让我记得带钥匙" },
43
+ actor: "wxid_self",
44
+ },
45
+ {
46
+ adapter: "messaging-qq",
47
+ subtype: "message",
48
+ content: { text: "晚上一起吃火锅吗" },
49
+ actor: "qq_1234",
50
+ },
51
+ {
52
+ adapter: "social-bilibili",
53
+ subtype: "media",
54
+ content: { title: "支付宝年度账单怎么看", url: "https://b23.tv/x" },
55
+ },
56
+ {
57
+ adapter: "social-weibo",
58
+ subtype: "post",
59
+ content: { text: "今天天气真好" },
60
+ },
61
+ {
62
+ adapter: "email-imap-qq",
63
+ subtype: "message",
64
+ content: { subject: "招商银行账单提醒", from: "noreply@cmbchina.com" },
65
+ },
66
+ {
67
+ adapter: "shopping-taobao",
68
+ subtype: "order",
69
+ content: {
70
+ title: "罗技 MX Master 3S",
71
+ amount: { value: 729.0, currency: "CNY", direction: "out" },
72
+ },
73
+ extra: { merchant: "罗技旗舰店", orderNo: "TAO-2024-09-001" },
74
+ },
75
+ {
76
+ adapter: "alipay-bill",
77
+ subtype: "transfer",
78
+ content: {
79
+ amount: { value: 25.5, currency: "CNY", direction: "out" },
80
+ counterparty: "瑞幸咖啡",
81
+ },
82
+ },
83
+ {
84
+ adapter: "travel-12306",
85
+ subtype: "trip",
86
+ content: { from: "厦门北", to: "上海虹桥", trainNo: "G3204" },
87
+ place: "厦门北",
88
+ },
89
+ {
90
+ adapter: "system-data-android",
91
+ subtype: "other",
92
+ content: { name: "李雷", phone: "13800000000" },
93
+ },
94
+ {
95
+ adapter: "ai-chat-history",
96
+ subtype: "ai-message",
97
+ content: { prompt: "帮我写一段 Kotlin 代码", model: "deepseek-r1" },
98
+ },
99
+ {
100
+ adapter: "unknown-collector",
101
+ subtype: "other",
102
+ content: { x: 1 },
103
+ },
104
+ ];
105
+ let i = 0;
106
+ for (const seed of seeds) {
107
+ // schema-aware fixture: omit place/extra/actor when nullish so validator
108
+ // accepts (it rejects explicit null on optional-typed fields)
109
+ const ev = {
110
+ id: `seed-${i.toString().padStart(3, "0")}-${seed.adapter}`,
111
+ subtype: seed.subtype,
112
+ occurredAt: baseTime + i * 1000,
113
+ content: seed.content,
114
+ source: source(seed.adapter),
115
+ };
116
+ if (seed.actor) ev.actor = seed.actor;
117
+ if (seed.place) ev.place = seed.place;
118
+ if (seed.extra) ev.extra = seed.extra;
119
+ vault.putEvent(eventOk(ev));
120
+ i++;
121
+ }
122
+ return i;
123
+ }
124
+
125
+ // ─── Test scaffolding ─────────────────────────────────────────────────────
126
+
127
+ let tmpDir;
128
+ let vaultPath;
129
+ let vault;
130
+ let key;
131
+
132
+ function freshVault() {
133
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "pdh-vault-search-"));
134
+ vaultPath = path.join(tmpDir, "vault.db");
135
+ key = generateKeyHex();
136
+ vault = new LocalVault({ path: vaultPath, key, skipAudit: true });
137
+ vault.open();
138
+ }
139
+
140
+ afterEach(() => {
141
+ if (vault) {
142
+ try {
143
+ vault.close();
144
+ } catch (_e) {}
145
+ vault = null;
146
+ }
147
+ if (tmpDir && fs.existsSync(tmpDir)) {
148
+ fs.rmSync(tmpDir, { recursive: true, force: true });
149
+ }
150
+ });
151
+
152
+ // ─── Migration 3 — FTS5 / LIKE mode setup ─────────────────────────────────
153
+
154
+ describe("Migration v3 — events_fts setup", () => {
155
+ it("schemaVersion reaches TARGET_VERSION", () => {
156
+ freshVault();
157
+ expect(vault.schemaVersion()).toBe(TARGET_VERSION);
158
+ });
159
+
160
+ it("records fts_mode = 'fts5' or 'like' in _meta", () => {
161
+ freshVault();
162
+ const mode = vault.ftsMode();
163
+ expect(["fts5", "like"]).toContain(mode);
164
+ // Cross-check against the underlying _meta query
165
+ expect(getFtsMode(vault.db)).toBe(mode);
166
+ });
167
+
168
+ it("creates events_fts virtual table when fts_mode = 'fts5'", () => {
169
+ freshVault();
170
+ if (vault.ftsMode() !== "fts5") return; // env without FTS5/trigram — skip
171
+ const row = vault.db
172
+ .prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='events_fts'")
173
+ .get();
174
+ expect(row).toBeTruthy();
175
+ });
176
+
177
+ it("triggers events_ai / events_au / events_ad exist when fts_mode = 'fts5'", () => {
178
+ freshVault();
179
+ if (vault.ftsMode() !== "fts5") return;
180
+ const names = vault.db
181
+ .prepare("SELECT name FROM sqlite_master WHERE type='trigger' AND tbl_name='events'")
182
+ .all()
183
+ .map((r) => r.name);
184
+ expect(names).toContain("events_ai");
185
+ expect(names).toContain("events_au");
186
+ expect(names).toContain("events_ad");
187
+ });
188
+ });
189
+
190
+ // ─── searchEvents — keyword / adapter / category / cursor ─────────────────
191
+
192
+ describe("vault.searchEvents", () => {
193
+ beforeEach(() => freshVault());
194
+
195
+ it("returns no rows when vault is empty", () => {
196
+ const r = vault.searchEvents({});
197
+ expect(r.rows).toEqual([]);
198
+ expect(r.nextCursor).toBeNull();
199
+ expect(["fts5", "like"]).toContain(r.mode);
200
+ });
201
+
202
+ it("returns all events newest-first when no filter given", () => {
203
+ seedMixedCategories(vault);
204
+ const r = vault.searchEvents({ limit: 20 });
205
+ expect(r.rows.length).toBe(11);
206
+ // Newest first ⇒ first row's occurredAt > last
207
+ expect(r.rows[0].occurredAt).toBeGreaterThan(r.rows[r.rows.length - 1].occurredAt);
208
+ });
209
+
210
+ it("filters by exact adapter", () => {
211
+ seedMixedCategories(vault);
212
+ const r = vault.searchEvents({ adapter: "wechat" });
213
+ expect(r.rows.length).toBe(1);
214
+ expect(r.rows[0].source.adapter).toBe("wechat");
215
+ });
216
+
217
+ it("filters by category 'chat' (wechat + messaging-*)", () => {
218
+ seedMixedCategories(vault);
219
+ const r = vault.searchEvents({ category: "chat" });
220
+ const adapters = r.rows.map((e) => e.source.adapter).sort();
221
+ expect(adapters).toEqual(["messaging-qq", "wechat"]);
222
+ });
223
+
224
+ it("filters by category 'social' (social-*)", () => {
225
+ seedMixedCategories(vault);
226
+ const r = vault.searchEvents({ category: "social" });
227
+ const adapters = r.rows.map((e) => e.source.adapter).sort();
228
+ expect(adapters).toEqual(["social-bilibili", "social-weibo"]);
229
+ });
230
+
231
+ it("filters by category 'shopping' (shopping-* + alipay-*)", () => {
232
+ seedMixedCategories(vault);
233
+ const r = vault.searchEvents({ category: "shopping" });
234
+ const adapters = r.rows.map((e) => e.source.adapter).sort();
235
+ expect(adapters).toEqual(["alipay-bill", "shopping-taobao"]);
236
+ });
237
+
238
+ it("filters by category 'other' (no-prefix adapters)", () => {
239
+ seedMixedCategories(vault);
240
+ const r = vault.searchEvents({ category: "other" });
241
+ const adapters = r.rows.map((e) => e.source.adapter);
242
+ expect(adapters).toEqual(["unknown-collector"]);
243
+ });
244
+
245
+ it("filters by date range (since/until)", () => {
246
+ seedMixedCategories(vault, 1700000000000);
247
+ // Seed adds 1 row per second; first 3 rows are at base, base+1000, base+2000
248
+ const r = vault.searchEvents({
249
+ since: 1700000000000,
250
+ until: 1700000002000,
251
+ });
252
+ expect(r.rows.length).toBe(3);
253
+ });
254
+
255
+ it("keyword search finds CJK content (FTS5 trigram path)", () => {
256
+ seedMixedCategories(vault);
257
+ if (vault.ftsMode() !== "fts5") return; // skip on LIKE-only envs
258
+ const r = vault.searchEvents({ q: "支付宝" });
259
+ // Should match the bilibili video (title contains 支付宝)
260
+ expect(r.rows.some((e) => e.source.adapter === "social-bilibili")).toBe(true);
261
+ });
262
+
263
+ it("keyword search finds ASCII content", () => {
264
+ seedMixedCategories(vault);
265
+ const r = vault.searchEvents({ q: "Kotlin" });
266
+ expect(r.rows.some((e) => e.source.adapter === "ai-chat-history")).toBe(true);
267
+ });
268
+
269
+ it("reports shortQuery=true for sub-3-char query in FTS5 mode", () => {
270
+ seedMixedCategories(vault);
271
+ if (vault.ftsMode() !== "fts5") return;
272
+ const r = vault.searchEvents({ q: "钥" });
273
+ expect(r.shortQuery).toBe(true);
274
+ expect(r.rows.length).toBe(11); // all rows — q was dropped
275
+ });
276
+
277
+ it("LIKE-mode search matches 1-char CJK (no min length)", () => {
278
+ seedMixedCategories(vault);
279
+ if (vault.ftsMode() !== "like") return; // FTS5 mode covered separately
280
+ const r = vault.searchEvents({ q: "妈" });
281
+ expect(r.shortQuery).toBe(false);
282
+ expect(r.rows.some((e) => e.source.adapter === "wechat")).toBe(true);
283
+ });
284
+
285
+ it("cursor pagination yields stable non-overlapping pages", () => {
286
+ seedMixedCategories(vault, 1700000000000);
287
+ const page1 = vault.searchEvents({ limit: 5 });
288
+ expect(page1.rows.length).toBe(5);
289
+ expect(page1.nextCursor).toBeTruthy();
290
+
291
+ const page2 = vault.searchEvents({ limit: 5, cursor: page1.nextCursor });
292
+ const page1Ids = new Set(page1.rows.map((e) => e.id));
293
+ for (const e of page2.rows) {
294
+ expect(page1Ids.has(e.id)).toBe(false);
295
+ }
296
+ // Page2 rows are strictly older than page1's last
297
+ const p1Last = page1.rows[page1.rows.length - 1].occurredAt;
298
+ for (const e of page2.rows) {
299
+ expect(e.occurredAt).toBeLessThanOrEqual(p1Last);
300
+ }
301
+ });
302
+
303
+ it("nextCursor is null on final page", () => {
304
+ seedMixedCategories(vault);
305
+ const r = vault.searchEvents({ limit: 100 });
306
+ expect(r.rows.length).toBe(11);
307
+ expect(r.nextCursor).toBeNull();
308
+ });
309
+
310
+ it("combines q + category + date filters (AND)", () => {
311
+ seedMixedCategories(vault, 1700000000000);
312
+ if (vault.ftsMode() !== "fts5") return;
313
+ const r = vault.searchEvents({
314
+ q: "支付宝",
315
+ category: "social",
316
+ since: 1700000000000,
317
+ until: 1700000005000,
318
+ });
319
+ expect(r.rows.length).toBe(1);
320
+ expect(r.rows[0].source.adapter).toBe("social-bilibili");
321
+ });
322
+ });
323
+
324
+ // ─── facetCounts — sidebar / chip badges ──────────────────────────────────
325
+
326
+ describe("vault.facetCounts", () => {
327
+ beforeEach(() => freshVault());
328
+
329
+ it("returns zero counts on empty vault", () => {
330
+ const r = vault.facetCounts({});
331
+ expect(r.byCategory).toEqual({});
332
+ expect(r.byAdapter).toEqual({});
333
+ expect(r.total).toBe(0);
334
+ });
335
+
336
+ it("groups events by category", () => {
337
+ seedMixedCategories(vault);
338
+ const r = vault.facetCounts({});
339
+ expect(r.byCategory.chat).toBe(2);
340
+ expect(r.byCategory.social).toBe(2);
341
+ expect(r.byCategory.email).toBe(1);
342
+ expect(r.byCategory.shopping).toBe(2);
343
+ expect(r.byCategory.travel).toBe(1);
344
+ expect(r.byCategory.system).toBe(1);
345
+ expect(r.byCategory["ai-chat"]).toBe(1);
346
+ expect(r.byCategory.other).toBe(1);
347
+ expect(r.total).toBe(11);
348
+ });
349
+
350
+ it("groups events by adapter (one per seed)", () => {
351
+ seedMixedCategories(vault);
352
+ const r = vault.facetCounts({});
353
+ expect(r.byAdapter.wechat).toBe(1);
354
+ expect(r.byAdapter["social-bilibili"]).toBe(1);
355
+ expect(r.byAdapter["alipay-bill"]).toBe(1);
356
+ });
357
+
358
+ it("groups events by subtype", () => {
359
+ seedMixedCategories(vault);
360
+ const r = vault.facetCounts({});
361
+ expect(r.bySubtype["message"]).toBe(3); // wechat + qq + email-imap-qq (all "message" subtype)
362
+ expect(r.bySubtype["order"]).toBe(1);
363
+ });
364
+
365
+ it("respects since/until + keyword filters", () => {
366
+ seedMixedCategories(vault, 1700000000000);
367
+ const r = vault.facetCounts({ since: 1700000005000 });
368
+ expect(r.total).toBeLessThan(11);
369
+ expect(r.total).toBeGreaterThan(0);
370
+ });
371
+ });
372
+
373
+ // ─── Trigger sync — putEvent / delete / update propagates to events_fts ──
374
+
375
+ describe("events_fts triggers (FTS5 mode only)", () => {
376
+ beforeEach(() => freshVault());
377
+
378
+ it("new putEvent becomes findable via FTS5 immediately", () => {
379
+ if (vault.ftsMode() !== "fts5") return;
380
+ vault.putEvent(
381
+ eventOk({
382
+ id: "trigger-test-001",
383
+ content: { text: "蛋白粉到货了" },
384
+ source: source("shopping-jd"),
385
+ })
386
+ );
387
+ const r = vault.searchEvents({ q: "蛋白粉" });
388
+ expect(r.rows.length).toBe(1);
389
+ expect(r.rows[0].id).toBe("trigger-test-001");
390
+ });
391
+
392
+ it("UPDATE to event re-indexes the new content", () => {
393
+ if (vault.ftsMode() !== "fts5") return;
394
+ const id = "trigger-test-002";
395
+ vault.putEvent(
396
+ eventOk({ id, content: { text: "原始文本" }, source: source("wechat") })
397
+ );
398
+ // Searching for new keyword first → 0 hits
399
+ expect(vault.searchEvents({ q: "更新后" }).rows.length).toBe(0);
400
+ // Update the same event (UPSERT via putEvent uses ON CONFLICT)
401
+ vault.putEvent(
402
+ eventOk({
403
+ id,
404
+ content: { text: "更新后的新内容" },
405
+ source: source("wechat"),
406
+ })
407
+ );
408
+ expect(vault.searchEvents({ q: "更新后" }).rows.length).toBe(1);
409
+ // Old text no longer findable
410
+ expect(vault.searchEvents({ q: "原始文本" }).rows.length).toBe(0);
411
+ });
412
+
413
+ it("DELETE removes event from FTS5 index", () => {
414
+ if (vault.ftsMode() !== "fts5") return;
415
+ const id = "trigger-test-003";
416
+ vault.putEvent(
417
+ eventOk({ id, content: { text: "待删除" }, source: source("wechat") })
418
+ );
419
+ expect(vault.searchEvents({ q: "待删除" }).rows.length).toBe(1);
420
+ vault.db.prepare("DELETE FROM events WHERE id = ?").run(id);
421
+ expect(vault.searchEvents({ q: "待删除" }).rows.length).toBe(0);
422
+ });
423
+ });
@@ -9,6 +9,7 @@ const path = require("node:path");
9
9
  const { newId } = require("../lib/ids");
10
10
  const { generateKeyHex } = require("../lib/key-providers");
11
11
  const { LocalVault } = require("../lib/vault");
12
+ const { TARGET_VERSION } = require("../lib/migrations");
12
13
 
13
14
  // ─── Fixtures ─────────────────────────────────────────────────────────────
14
15
 
@@ -104,7 +105,7 @@ afterEach(() => {
104
105
  describe("LocalVault open + migrations", () => {
105
106
  it("opens a fresh vault and runs initial migrations", () => {
106
107
  freshVault();
107
- expect(vault.schemaVersion()).toBe(2);
108
+ expect(vault.schemaVersion()).toBe(TARGET_VERSION);
108
109
  expect(fs.existsSync(vaultPath)).toBe(true);
109
110
  });
110
111
 
@@ -116,7 +117,7 @@ describe("LocalVault open + migrations", () => {
116
117
 
117
118
  const reopen = new LocalVault({ path: vaultPath, key, skipAudit: true });
118
119
  reopen.open();
119
- expect(reopen.schemaVersion()).toBe(2);
120
+ expect(reopen.schemaVersion()).toBe(TARGET_VERSION);
120
121
  expect(reopen.stats().persons).toBe(1);
121
122
  reopen.close();
122
123
  });
@@ -144,6 +145,79 @@ describe("LocalVault open + migrations", () => {
144
145
  const wrong = new LocalVault({ path: vaultPath, key: generateKeyHex(), skipAudit: true });
145
146
  expect(() => wrong.open()).toThrow();
146
147
  });
148
+
149
+ // ── 2026-05-24 trap #25 — partial-index residue from `IF NOT EXISTS` ─────
150
+ // Older vaults (pre commit 44c4188a8) may have full unique indices on
151
+ // uniq_{events,persons,places,items}_source without the WHERE clause.
152
+ // Migration v4 explicitly DROPs + CREATEs to force partial index, fixing
153
+ // the "2nd ON CONFLICT clause does not match" SQLite error that silently
154
+ // breaks adapter.sync.putEvent path.
155
+ it("migration v4 recreates uniq_*_source as partial indices (WHERE NOT NULL)", () => {
156
+ freshVault();
157
+ const tables = ["events", "persons", "places", "items"];
158
+ for (const t of tables) {
159
+ const row = vault.db
160
+ .prepare(`SELECT sql FROM sqlite_master WHERE type='index' AND name=?`)
161
+ .get(`uniq_${t}_source`);
162
+ expect(row, `index uniq_${t}_source must exist on fresh vault`).toBeTruthy();
163
+ expect(
164
+ row.sql,
165
+ `uniq_${t}_source must include WHERE source_original_id IS NOT NULL`
166
+ ).toContain("source_original_id IS NOT NULL");
167
+ }
168
+ });
169
+
170
+ it("migration v4 fixes pre-existing FULL unique indices (simulated drift)", () => {
171
+ freshVault();
172
+ const tables = ["events", "persons", "places", "items"];
173
+ for (const t of tables) {
174
+ vault.db.exec(`DROP INDEX uniq_${t}_source`);
175
+ vault.db.exec(
176
+ `CREATE UNIQUE INDEX uniq_${t}_source ON ${t}(source_adapter, source_original_id)`
177
+ );
178
+ }
179
+ vault.db
180
+ .prepare(`UPDATE _meta SET value=?, updated_at=? WHERE key='schema_version'`)
181
+ .run("3", Date.now());
182
+ vault.close();
183
+
184
+ const reopen = new LocalVault({ path: vaultPath, key, skipAudit: true });
185
+ reopen.open();
186
+ for (const t of tables) {
187
+ const row = reopen.db
188
+ .prepare(`SELECT sql FROM sqlite_master WHERE name=?`)
189
+ .get(`uniq_${t}_source`);
190
+ expect(
191
+ row.sql,
192
+ `migration v4 must add WHERE clause to uniq_${t}_source`
193
+ ).toContain("source_original_id IS NOT NULL");
194
+ }
195
+ expect(reopen.schemaVersion()).toBe(TARGET_VERSION);
196
+ reopen.close();
197
+ });
198
+
199
+ it("putEvent ON CONFLICT WHERE matches after migration v4 (no SQLite parse error)", () => {
200
+ freshVault();
201
+ vault.db.exec(`DROP INDEX uniq_events_source`);
202
+ vault.db.exec(
203
+ `CREATE UNIQUE INDEX uniq_events_source ON events(source_adapter, source_original_id)`
204
+ );
205
+ vault.db
206
+ .prepare(`UPDATE _meta SET value='3' WHERE key='schema_version'`)
207
+ .run();
208
+ vault.close();
209
+
210
+ const reopen = new LocalVault({ path: vaultPath, key, skipAudit: true });
211
+ reopen.open();
212
+ const baseSource = source({ originalId: "test:dup:1" });
213
+ expect(() => reopen.putEvent(eventOk({ source: baseSource }))).not.toThrow();
214
+ expect(() =>
215
+ reopen.putEvent(
216
+ eventOk({ source: baseSource, content: { text: "updated" } })
217
+ )
218
+ ).not.toThrow();
219
+ reopen.close();
220
+ });
147
221
  });
148
222
 
149
223
  // ─── Entity put/get ───────────────────────────────────────────────────────
@@ -494,7 +568,7 @@ describe("LocalVault.stats", () => {
494
568
  vault.audit("hello");
495
569
 
496
570
  const s = vault.stats();
497
- expect(s.schemaVersion).toBe(2);
571
+ expect(s.schemaVersion).toBe(TARGET_VERSION);
498
572
  expect(s.events).toBe(3);
499
573
  expect(s.persons).toBe(1);
500
574
  expect(s.places).toBe(2);