@chainlesschain/personal-data-hub 0.1.0 → 0.2.1

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 (154) hide show
  1. package/__tests__/adapters/ai-chat-cookie-capture-spec.test.js +211 -0
  2. package/__tests__/adapters/ai-chat-health-checker.test.js +262 -0
  3. package/__tests__/adapters/ai-chat-history.test.js +396 -0
  4. package/__tests__/adapters/ai-chat-http-client.test.js +242 -0
  5. package/__tests__/adapters/ai-chat-vendors.test.js +874 -0
  6. package/__tests__/adapters/alipay-bill-adapter.test.js +538 -0
  7. package/__tests__/adapters/email-adapter.test.js +138 -1
  8. package/__tests__/adapters/email-classifier.test.js +347 -0
  9. package/__tests__/adapters/email-pdf-extractor.test.js +529 -0
  10. package/__tests__/adapters/email-retry-progress.test.js +294 -0
  11. package/__tests__/adapters/email-templates.test.js +699 -0
  12. package/__tests__/adapters/social-toutiao-kuaishou-scaffold.test.js +269 -0
  13. package/__tests__/adapters/system-data-adapter.test.js +440 -0
  14. package/__tests__/adapters/system-data-android-ingest.test.js +144 -0
  15. package/__tests__/adapters/system-data-android.test.js +387 -0
  16. package/__tests__/adapters/system-data-disclosure.test.js +153 -0
  17. package/__tests__/adapters/wechat-bootstrap.test.js +240 -0
  18. package/__tests__/adapters/wechat-env-probe.test.js +162 -0
  19. package/__tests__/adapters/wechat-frida-agent.test.js +191 -0
  20. package/__tests__/adapters/wechat-frida-integration.test.js +149 -0
  21. package/__tests__/adapters/wechat-frida-key-provider.test.js +188 -0
  22. package/__tests__/adapters/wechat-md5-key-provider.test.js +101 -0
  23. package/__tests__/analysis-skills.test.js +556 -0
  24. package/__tests__/analysis.test.js +329 -1
  25. package/__tests__/e2e/ai-chat-cross-source-journey.test.js +213 -0
  26. package/__tests__/e2e/full-user-journey.test.js +188 -0
  27. package/__tests__/entity-resolver-ingest-hook.test.js +177 -0
  28. package/__tests__/entity-resolver-stages.test.js +411 -0
  29. package/__tests__/entity-resolver-vault.test.js +246 -0
  30. package/__tests__/entity-resolver.test.js +526 -0
  31. package/__tests__/fixtures/entity-resolver-200-mock.json +96 -0
  32. package/__tests__/integration/ai-chat-history-registry.test.js +228 -0
  33. package/__tests__/integration/aichat-wizard-end-to-end.test.js +282 -0
  34. package/__tests__/integration/cross-adapter-pipelines.test.js +396 -0
  35. package/__tests__/integration/wechat-bootstrap-end-to-end.test.js +390 -0
  36. package/__tests__/longtail-adapters.test.js +217 -0
  37. package/__tests__/mobile-extractor.test.js +288 -0
  38. package/__tests__/registry.test.js +4 -2
  39. package/__tests__/shopping-adapters.test.js +296 -0
  40. package/__tests__/sidecar-contacts-cross-validate.test.js +163 -0
  41. package/__tests__/sidecar-supervisor.test.js +120 -0
  42. package/__tests__/social-adapters.test.js +206 -0
  43. package/__tests__/travel-adapters.test.js +325 -0
  44. package/__tests__/vault.test.js +3 -3
  45. package/__tests__/wechat-adapter.test.js +476 -0
  46. package/__tests__/whatsapp-adapter.test.js +135 -0
  47. package/lib/adapter-spec.js +12 -0
  48. package/lib/adapters/_python-sidecar-base.js +207 -0
  49. package/lib/adapters/ai-chat-history/ai-chat-adapter.js +374 -0
  50. package/lib/adapters/ai-chat-history/cookie-auth.js +109 -0
  51. package/lib/adapters/ai-chat-history/cookie-capture-spec.js +331 -0
  52. package/lib/adapters/ai-chat-history/health-checker.js +210 -0
  53. package/lib/adapters/ai-chat-history/http-client.js +211 -0
  54. package/lib/adapters/ai-chat-history/index.js +28 -0
  55. package/lib/adapters/ai-chat-history/schema-map.js +258 -0
  56. package/lib/adapters/ai-chat-history/vendor-spec.js +86 -0
  57. package/lib/adapters/ai-chat-history/vendors/coze.js +179 -0
  58. package/lib/adapters/ai-chat-history/vendors/deepseek.js +199 -0
  59. package/lib/adapters/ai-chat-history/vendors/doubao.js +255 -0
  60. package/lib/adapters/ai-chat-history/vendors/dreamina.js +174 -0
  61. package/lib/adapters/ai-chat-history/vendors/hunyuan.js +176 -0
  62. package/lib/adapters/ai-chat-history/vendors/kimi.js +182 -0
  63. package/lib/adapters/ai-chat-history/vendors/qianfan.js +160 -0
  64. package/lib/adapters/ai-chat-history/vendors/tongyi.js +193 -0
  65. package/lib/adapters/ai-chat-history/vendors/zhipu.js +202 -0
  66. package/lib/adapters/ai-chat-history/wizard-controller.js +473 -0
  67. package/lib/adapters/alipay-bill/alipay-bill-adapter.js +311 -0
  68. package/lib/adapters/alipay-bill/counterparty.js +129 -0
  69. package/lib/adapters/alipay-bill/csv-parser.js +217 -0
  70. package/lib/adapters/alipay-bill/index.js +41 -0
  71. package/lib/adapters/alipay-bill/zip-decryptor.js +111 -0
  72. package/lib/adapters/email-imap/classifier.js +495 -0
  73. package/lib/adapters/email-imap/email-adapter.js +419 -8
  74. package/lib/adapters/email-imap/index.js +42 -0
  75. package/lib/adapters/email-imap/pdf-extractor.js +192 -0
  76. package/lib/adapters/email-imap/templates/bill.js +232 -0
  77. package/lib/adapters/email-imap/templates/government.js +120 -0
  78. package/lib/adapters/email-imap/templates/index.js +78 -0
  79. package/lib/adapters/email-imap/templates/order.js +186 -0
  80. package/lib/adapters/email-imap/templates/other.js +114 -0
  81. package/lib/adapters/email-imap/templates/register.js +113 -0
  82. package/lib/adapters/email-imap/templates/travel.js +157 -0
  83. package/lib/adapters/email-imap/templates/utils.js +275 -0
  84. package/lib/adapters/email-imap/transactions.js +234 -0
  85. package/lib/adapters/messaging-qq/index.js +158 -0
  86. package/lib/adapters/messaging-telegram/index.js +142 -0
  87. package/lib/adapters/messaging-whatsapp/index.js +189 -0
  88. package/lib/adapters/shopping-base/index.js +208 -0
  89. package/lib/adapters/shopping-jd/index.js +150 -0
  90. package/lib/adapters/shopping-meituan/index.js +154 -0
  91. package/lib/adapters/shopping-taobao/index.js +176 -0
  92. package/lib/adapters/social-bilibili/index.js +171 -0
  93. package/lib/adapters/social-douyin/index.js +116 -0
  94. package/lib/adapters/social-kuaishou/index.js +237 -0
  95. package/lib/adapters/social-toutiao/index.js +236 -0
  96. package/lib/adapters/social-weibo/index.js +164 -0
  97. package/lib/adapters/social-xiaohongshu/index.js +96 -0
  98. package/lib/adapters/system-data/disclosure.js +166 -0
  99. package/lib/adapters/system-data/index.js +34 -0
  100. package/lib/adapters/system-data/system-data-adapter.js +344 -0
  101. package/lib/adapters/system-data-android/adapter.js +348 -0
  102. package/lib/adapters/system-data-android/index.js +76 -0
  103. package/lib/adapters/travel-12306/index.js +151 -0
  104. package/lib/adapters/travel-amap/index.js +164 -0
  105. package/lib/adapters/travel-baidu-map/index.js +162 -0
  106. package/lib/adapters/travel-base/index.js +240 -0
  107. package/lib/adapters/travel-ctrip/index.js +151 -0
  108. package/lib/adapters/wechat/bootstrap.js +146 -0
  109. package/lib/adapters/wechat/content-parser.js +326 -0
  110. package/lib/adapters/wechat/db-reader.js +209 -0
  111. package/lib/adapters/wechat/env-probe.js +218 -0
  112. package/lib/adapters/wechat/frida-agent/loader.js +67 -0
  113. package/lib/adapters/wechat/frida-agent/wechat-key-hook.js +126 -0
  114. package/lib/adapters/wechat/index.js +37 -0
  115. package/lib/adapters/wechat/key-extractor.js +158 -0
  116. package/lib/adapters/wechat/key-providers/frida-key-provider.js +244 -0
  117. package/lib/adapters/wechat/key-providers/index.js +22 -0
  118. package/lib/adapters/wechat/key-providers/key-provider-base.js +44 -0
  119. package/lib/adapters/wechat/key-providers/md5-key-provider.js +81 -0
  120. package/lib/adapters/wechat/normalize.js +220 -0
  121. package/lib/adapters/wechat/wechat-adapter.js +205 -0
  122. package/lib/analysis-skills/base.js +113 -0
  123. package/lib/analysis-skills/footprint.js +167 -0
  124. package/lib/analysis-skills/index.js +58 -0
  125. package/lib/analysis-skills/interests.js +161 -0
  126. package/lib/analysis-skills/relations.js +226 -0
  127. package/lib/analysis-skills/spending.js +219 -0
  128. package/lib/analysis-skills/timeline.js +167 -0
  129. package/lib/analysis.js +191 -2
  130. package/lib/entity-resolver/embedding-stage.js +198 -0
  131. package/lib/entity-resolver/entity-resolver.js +384 -0
  132. package/lib/entity-resolver/index.js +42 -0
  133. package/lib/entity-resolver/llm-stage.js +191 -0
  134. package/lib/entity-resolver/rule-stage.js +208 -0
  135. package/lib/entity-resolver/worker.js +149 -0
  136. package/lib/index.js +131 -0
  137. package/lib/migrations.js +73 -0
  138. package/lib/mobile-extractor/android.js +193 -0
  139. package/lib/mobile-extractor/index.js +9 -0
  140. package/lib/mobile-extractor/ios.js +223 -0
  141. package/lib/prompt-builder.js +11 -1
  142. package/lib/query-parser.js +7 -1
  143. package/lib/registry.js +42 -0
  144. package/lib/sidecar/index.js +15 -0
  145. package/lib/sidecar/supervisor.js +359 -0
  146. package/lib/vault.js +343 -0
  147. package/package.json +36 -3
  148. package/scripts/_make-fixture-all.js +126 -0
  149. package/scripts/_make-fixture-contacts.js +84 -0
  150. package/scripts/evaluate-entity-resolver.js +213 -0
  151. package/scripts/smoke-phase-5-5.js +196 -0
  152. package/scripts/smoke-phase-5-7.js +181 -0
  153. package/scripts/smoke-system-data-contacts.js +309 -0
  154. package/scripts/smoke-system-data.js +312 -0
@@ -0,0 +1,228 @@
1
+ "use strict";
2
+
3
+ // Integration — AIChatHistoryAdapter end-to-end through AdapterRegistry.
4
+ // Verifies the full chain: register → syncAdapter → real vendor HTTP →
5
+ // raw archive → normalize → partition → vault put → watermark advance →
6
+ // audit log.
7
+
8
+ import { describe, it, expect, afterEach } from "vitest";
9
+
10
+ const fs = require("node:fs");
11
+ const path = require("node:path");
12
+ const os = require("node:os");
13
+
14
+ const {
15
+ LocalVault, generateKeyHex, AdapterRegistry,
16
+ } = require("../../lib");
17
+ const {
18
+ AIChatHistoryAdapter, CookieAuthSession, DEFAULT_VENDOR_SPECS,
19
+ } = require("../../lib/adapters/ai-chat-history");
20
+
21
+ function makeRig() {
22
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pdh-aichat-int-"));
23
+ const vault = new LocalVault({ path: path.join(dir, "v.db"), key: generateKeyHex() });
24
+ vault.open();
25
+ const registry = new AdapterRegistry({ vault });
26
+ return { vault, registry, dir };
27
+ }
28
+
29
+ function cleanup({ vault, dir }) {
30
+ try { vault.close(); } catch (_e) {}
31
+ try { fs.rmSync(dir, { recursive: true, force: true }); } catch (_e) {}
32
+ }
33
+
34
+ function makeResponse({ status = 200, body = {} } = {}) {
35
+ return {
36
+ status,
37
+ ok: status >= 200 && status < 300,
38
+ headers: { get: () => null },
39
+ async json() { return body; },
40
+ async text() { return JSON.stringify(body); },
41
+ };
42
+ }
43
+
44
+ function makeRoutedFetch(routes) {
45
+ const calls = [];
46
+ return {
47
+ calls,
48
+ async fetch(url, init) {
49
+ calls.push({ url, init });
50
+ for (const [pattern, response] of routes) {
51
+ if (typeof pattern === "string" ? url.includes(pattern) : pattern.test(url)) {
52
+ if (typeof response === "function") return response(url, init);
53
+ return response;
54
+ }
55
+ }
56
+ return makeResponse({ status: 404, body: { error: "no route" } });
57
+ },
58
+ };
59
+ }
60
+
61
+ function makeClock() {
62
+ let t = 1700000000_000;
63
+ return {
64
+ now: () => t,
65
+ sleep: async (ms) => { t += ms; },
66
+ };
67
+ }
68
+
69
+ function deepseekFixtures() {
70
+ return [
71
+ ["/get_user_info", makeResponse({ body: { code: 0, data: { biz_data: { user_id: "ds-u1" } } } })],
72
+ [/fetch_page.*before=/, makeResponse({ body: { data: { biz_data: { chat_sessions: [] } } } })],
73
+ ["/chat_session/fetch_page", makeResponse({ body: { data: { biz_data: { chat_sessions: [
74
+ { id: "ds-c1", title: "test ds chat", model: "deepseek-r1", inserted_at: 1700000100, updated_at: 1700000200 },
75
+ ] } } } })],
76
+ ["/chat/history_messages", makeResponse({ body: { data: { biz_data: { chat_messages: [
77
+ { id: "ds-m1", role: "USER", content: "hi deepseek", inserted_at: 1700000100 },
78
+ { id: "ds-m2", role: "ASSISTANT", content: "hi back", inserted_at: 1700000110, model: "deepseek-r1" },
79
+ ] } } } })],
80
+ ];
81
+ }
82
+
83
+ function kimiFixtures() {
84
+ return [
85
+ ["/api/user", makeResponse({ body: { id: "km-u1" } })],
86
+ [/list\?offset=30/, makeResponse({ body: { items: [], total: 1 } })],
87
+ [/list\?offset=0/, makeResponse({ body: { items: [
88
+ { id: "km-c1", name: "test kimi", created_at: 1700000300, updated_at: 1700000400, message_count: 1 },
89
+ ], total: 1 } })],
90
+ [/segment\/scroll/, async (_url, init) => {
91
+ const body = JSON.parse(init.body);
92
+ if (body.last === "0") {
93
+ return makeResponse({ body: {
94
+ items: [{ id: "km-msg-1", role: "user", content: "hi kimi", created_at: 1700000300 }],
95
+ has_more: false,
96
+ } });
97
+ }
98
+ return makeResponse({ body: { items: [], has_more: false } });
99
+ }],
100
+ ];
101
+ }
102
+
103
+ // ─── tests ───────────────────────────────────────────────────────────────
104
+
105
+ describe("Integration — AIChatHistoryAdapter through AdapterRegistry", () => {
106
+ let rig;
107
+ afterEach(() => cleanup(rig));
108
+
109
+ it("registers without contract errors (adapter passes assertAdapter)", () => {
110
+ rig = makeRig();
111
+ const a = new AIChatHistoryAdapter();
112
+ expect(() => rig.registry.register(a)).not.toThrow();
113
+ });
114
+
115
+ it("two-vendor sync writes events to vault with proper raw_events archive", async () => {
116
+ rig = makeRig();
117
+ const clk = makeClock();
118
+ const fetched = makeRoutedFetch([...deepseekFixtures(), ...kimiFixtures()]);
119
+ const a = new AIChatHistoryAdapter({
120
+ fetch: fetched.fetch,
121
+ sleep: clk.sleep,
122
+ now: clk.now,
123
+ });
124
+ a.setSession("deepseek", new CookieAuthSession({ vendor: "deepseek", cookies: [{ name: "userToken", value: "x" }] }));
125
+ a.setSession("kimi", new CookieAuthSession({ vendor: "kimi", cookies: [{ name: "sess", value: "y" }] }));
126
+ rig.registry.register(a);
127
+
128
+ const report = await rig.registry.syncAdapter("ai-chat-history");
129
+ expect(report.status).toBe("ok");
130
+ expect(report.invalidCount).toBe(0); // adapter must yield valid registry envelopes
131
+
132
+ // Each vendor yields: 1 conv + N msgs (deepseek=2, kimi=1) = 5 raws across both
133
+ expect(report.rawCount).toBeGreaterThanOrEqual(5);
134
+
135
+ // Vault has events (2 deepseek msgs + 1 kimi msg)
136
+ const allEvents = rig.vault.queryEvents({ adapter: "ai-chat-history", limit: 1000 });
137
+ expect(allEvents.length).toBeGreaterThanOrEqual(3);
138
+ const vendors = new Set(allEvents.map((e) => e.extra && e.extra.vendor).filter(Boolean));
139
+ expect(vendors.has("deepseek")).toBe(true);
140
+ expect(vendors.has("kimi")).toBe(true);
141
+
142
+ // Vendor Person dedup via raw SQL: only 1 DeepSeek Person + 1 Kimi Person
143
+ const aiAgentCount = rig.vault.db
144
+ .prepare("SELECT COUNT(*) AS n FROM persons WHERE subtype = 'ai-agent'")
145
+ .get().n;
146
+ expect(aiAgentCount).toBe(2);
147
+
148
+ // Topics: 1 conversation Topic per vendor (extra.kind = 'ai-conversation')
149
+ const topicCount = rig.vault.db
150
+ .prepare("SELECT COUNT(*) AS n FROM topics WHERE json_extract(extra, '$.kind') = 'ai-conversation'")
151
+ .get().n;
152
+ expect(topicCount).toBe(2);
153
+ });
154
+
155
+ it("watermark advances after successful sync; second sync is idempotent", async () => {
156
+ rig = makeRig();
157
+ const clk = makeClock();
158
+ const fetched = makeRoutedFetch(deepseekFixtures());
159
+ const a = new AIChatHistoryAdapter({ fetch: fetched.fetch, sleep: clk.sleep, now: clk.now });
160
+ a.setSession("deepseek", new CookieAuthSession({ vendor: "deepseek", cookies: [{ name: "userToken", value: "x" }] }));
161
+ rig.registry.register(a);
162
+
163
+ const r1 = await rig.registry.syncAdapter("ai-chat-history");
164
+ expect(r1.status).toBe("ok");
165
+ const firstWatermark = r1.watermark;
166
+ expect(firstWatermark).toBeTruthy();
167
+
168
+ const eventsAfterFirst = rig.vault.queryEvents({ adapter: "ai-chat-history", limit: 100 }).length;
169
+ expect(eventsAfterFirst).toBeGreaterThanOrEqual(2);
170
+
171
+ // Re-sync same fixtures — should be idempotent (no duplicate events).
172
+ const r2 = await rig.registry.syncAdapter("ai-chat-history");
173
+ expect(r2.status).toBe("ok");
174
+
175
+ // Vault doesn't double-insert thanks to events table PK (id is UUIDv7 so different each time
176
+ // but source.originalId dedup via findBySource semantics applies). At minimum, both syncs
177
+ // succeeded without errors and the watermark moved forward.
178
+ expect(Number(r2.watermark)).toBeGreaterThanOrEqual(Number(firstWatermark));
179
+ });
180
+
181
+ it("vendor-cookie-expired sentinel does not abort the whole sync", async () => {
182
+ rig = makeRig();
183
+ const clk = makeClock();
184
+ // deepseek returns 401, kimi works.
185
+ const fetched = makeRoutedFetch([
186
+ [/chat_session\/fetch_page/, makeResponse({ status: 401 })],
187
+ ...kimiFixtures(),
188
+ ]);
189
+ const a = new AIChatHistoryAdapter({ fetch: fetched.fetch, sleep: clk.sleep, now: clk.now });
190
+ a.setSession("deepseek", new CookieAuthSession({ vendor: "deepseek", cookies: [] }));
191
+ a.setSession("kimi", new CookieAuthSession({ vendor: "kimi", cookies: [] }));
192
+ rig.registry.register(a);
193
+
194
+ const report = await rig.registry.syncAdapter("ai-chat-history");
195
+ expect(report.status).toBe("ok"); // partial success is still ok
196
+
197
+ // Kimi events made it in despite deepseek failure.
198
+ const allEvents = rig.vault.queryEvents({ adapter: "ai-chat-history", limit: 100 });
199
+ const kimiEvents = allEvents.filter((e) => e.extra && e.extra.vendor === "kimi");
200
+ expect(kimiEvents.length).toBeGreaterThan(0);
201
+ });
202
+
203
+ it("no sessions configured → zero events ingested, no error", async () => {
204
+ rig = makeRig();
205
+ const a = new AIChatHistoryAdapter();
206
+ rig.registry.register(a);
207
+
208
+ const report = await rig.registry.syncAdapter("ai-chat-history");
209
+ expect(report.status).toBe("ok");
210
+ expect(report.rawCount).toBe(0);
211
+ expect(rig.vault.queryEvents({ adapter: "ai-chat-history", limit: 10 }).length).toBe(0);
212
+ });
213
+
214
+ it("audit log captures sync.ok with adapter name + scope", async () => {
215
+ rig = makeRig();
216
+ const clk = makeClock();
217
+ const fetched = makeRoutedFetch(deepseekFixtures());
218
+ const a = new AIChatHistoryAdapter({ fetch: fetched.fetch, sleep: clk.sleep, now: clk.now });
219
+ a.setSession("deepseek", new CookieAuthSession({ vendor: "deepseek", cookies: [] }));
220
+ rig.registry.register(a);
221
+
222
+ await rig.registry.syncAdapter("ai-chat-history");
223
+
224
+ const audit = rig.vault.queryAudit({ adapter: "ai-chat-history", limit: 50 });
225
+ const okEntries = audit.filter((a) => a.action === "adapter.sync.ok");
226
+ expect(okEntries.length).toBeGreaterThan(0);
227
+ });
228
+ });
@@ -0,0 +1,282 @@
1
+ /**
2
+ * AIChat WebView 鉴权向导 — end-to-end integration test (Phase 10.3.6).
3
+ *
4
+ * Exercises the full chain WITHOUT any real Electron / real network:
5
+ *
6
+ * cookie-capture-spec
7
+ * ↓
8
+ * wizard-controller (paste-fallback mode)
9
+ * ↓
10
+ * accountsStore (real fs, temp dir)
11
+ * ↓
12
+ * vendor-adapter-bridge (stub validateCookie)
13
+ * ↓
14
+ * health-checker (real periodic logic, injected timers)
15
+ *
16
+ * Three scenarios:
17
+ * - Happy: probe → register → health=ok
18
+ * - Expired: register → mutate stored cookies to "stale" + adapter
19
+ * returns ok=false → health=failed
20
+ * - Version: register at specVersion=1 → bump to specVersion=2 →
21
+ * health marks SPEC_VERSION_MISMATCH
22
+ *
23
+ * Lives in integration/ rather than adapters/ because it spans modules
24
+ * (controller + factory + health-checker + real fs).
25
+ */
26
+
27
+ "use strict";
28
+
29
+ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
30
+ import { mkdtempSync, rmSync, readFileSync, writeFileSync } from "node:fs";
31
+ import { tmpdir } from "node:os";
32
+ import { join } from "node:path";
33
+
34
+ const {
35
+ createAIChatWizardController,
36
+ } = require("../../lib/adapters/ai-chat-history/wizard-controller");
37
+ const {
38
+ createAIChatHealthChecker,
39
+ } = require("../../lib/adapters/ai-chat-history/health-checker");
40
+
41
+ // ─── Helpers ──────────────────────────────────────────────────────────────
42
+
43
+ function makeRealFsAccountsStore({ hubDir }) {
44
+ // A minimal accountsStore that mirrors the shape used by both desktop
45
+ // factory + cli wizard wirings, but uses fs directly so integration is
46
+ // observable on disk.
47
+ const filePath = join(hubDir, "aichat-accounts.json");
48
+ function readAll() {
49
+ try {
50
+ return JSON.parse(readFileSync(filePath, "utf-8")) || {};
51
+ } catch (err) {
52
+ if (err && err.code === "ENOENT") return {};
53
+ return {};
54
+ }
55
+ }
56
+ return {
57
+ get: async (v) => readAll()[v] || null,
58
+ put: async (v, entry) => {
59
+ const all = readAll();
60
+ all[v] = entry;
61
+ writeFileSync(filePath, JSON.stringify(all, null, 2), { mode: 0o600 });
62
+ },
63
+ delete: async (v) => {
64
+ const all = readAll();
65
+ delete all[v];
66
+ writeFileSync(filePath, JSON.stringify(all, null, 2), { mode: 0o600 });
67
+ },
68
+ list: async () => Object.values(readAll()),
69
+ _filePath: filePath,
70
+ };
71
+ }
72
+
73
+ function makeStubVendorAdapter({ behaviorByVendor = {} } = {}) {
74
+ return {
75
+ registerVendor: vi.fn(async (vendor, cookies) => {
76
+ const b = behaviorByVendor[vendor];
77
+ if (typeof b === "function") return b(vendor, cookies);
78
+ return b || { ok: true, userId: "u_" + vendor };
79
+ }),
80
+ };
81
+ }
82
+
83
+ function buildWizard({ accountsStore, vendorAdapter }) {
84
+ // Minimal _deps for paste-fallback mode. classifier/specLookup come
85
+ // from the real spec module.
86
+ const {
87
+ classifyProbedCookies,
88
+ getSpec,
89
+ listVendors,
90
+ COOKIE_SPEC_VERSION,
91
+ } = require("../../lib/adapters/ai-chat-history/cookie-capture-spec");
92
+ return createAIChatWizardController({
93
+ accountsStore,
94
+ vendorAdapter,
95
+ _deps: {
96
+ sessionFactory: () => ({}),
97
+ clock: () => Date.now(),
98
+ logger: { info: () => {}, warn: () => {}, error: () => {} },
99
+ classifier: classifyProbedCookies,
100
+ specLookup: getSpec,
101
+ knownVendors: listVendors(),
102
+ cookieSpecVersion: COOKIE_SPEC_VERSION,
103
+ fallbackMode: "paste",
104
+ },
105
+ });
106
+ }
107
+
108
+ let hubDir;
109
+ beforeEach(() => {
110
+ hubDir = mkdtempSync(join(tmpdir(), "aichat-wiz-e2e-"));
111
+ });
112
+ afterEach(() => {
113
+ rmSync(hubDir, { recursive: true, force: true });
114
+ });
115
+
116
+ // ─── Scenario A: happy path ──────────────────────────────────────────────
117
+
118
+ describe("aichat wizard E2E — happy path", () => {
119
+ it("probe → register → file written → health=ok", async () => {
120
+ const accountsStore = makeRealFsAccountsStore({ hubDir });
121
+ const vendorAdapter = makeStubVendorAdapter({
122
+ behaviorByVendor: { doubao: { ok: true, userId: "u_42" } },
123
+ });
124
+ const wiz = buildWizard({ accountsStore, vendorAdapter });
125
+
126
+ // Step 1: open paste-fallback metadata for doubao
127
+ const opened = await wiz.openVendorLogin({ vendor: "doubao" });
128
+ expect(opened.ok).toBe(true);
129
+ expect(opened.fallbackMode).toBe("paste");
130
+ expect(opened.loginUrl).toMatch(/doubao\.com/);
131
+
132
+ // Step 2: probe a pasted cookie header
133
+ const probed = await wiz.probeCookies({
134
+ vendor: "doubao",
135
+ cookieHeader: "sessionid=abc; sid_guard=xyz",
136
+ });
137
+ expect(probed.ok).toBe(true);
138
+ expect(probed.foundRequired).toEqual(["sessionid"]);
139
+
140
+ // Step 3: register — writes the accounts file on disk
141
+ const registered = await wiz.registerVendor({
142
+ vendor: "doubao",
143
+ cookies: probed.cookies,
144
+ });
145
+ expect(registered.ok).toBe(true);
146
+ expect(registered.accountId).toBe("doubao:u_42");
147
+
148
+ const onDisk = JSON.parse(readFileSync(accountsStore._filePath, "utf-8"));
149
+ expect(onDisk.doubao.userId).toBe("u_42");
150
+ expect(onDisk.doubao.cookieSpecVersion).toBe(1);
151
+ expect(onDisk.doubao.lastHealth.ok).toBe(true);
152
+
153
+ // Step 4: HealthChecker.runOnce should re-validate and stay ok
154
+ const hc = createAIChatHealthChecker({
155
+ accountsStore, vendorAdapter,
156
+ _deps: { logger: { info: () => {}, warn: () => {}, error: () => {} } },
157
+ });
158
+ const r = await hc.runOnce();
159
+ expect(r).toMatchObject({ checked: 1, ok: 1, failed: 0, mismatch: 0 });
160
+ expect(vendorAdapter.registerVendor).toHaveBeenCalledTimes(2);
161
+
162
+ // Stored entry still ok=true; lastHealth.at should have changed.
163
+ const refreshed = JSON.parse(readFileSync(accountsStore._filePath, "utf-8"));
164
+ expect(refreshed.doubao.lastHealth.ok).toBe(true);
165
+ });
166
+ });
167
+
168
+ // ─── Scenario B: cookie expired ──────────────────────────────────────────
169
+
170
+ describe("aichat wizard E2E — expired path", () => {
171
+ it("after stored cookies stop validating, health marks failed", async () => {
172
+ const accountsStore = makeRealFsAccountsStore({ hubDir });
173
+ let isValid = true;
174
+ const vendorAdapter = makeStubVendorAdapter({
175
+ behaviorByVendor: {
176
+ kimi: async () => (isValid
177
+ ? { ok: true, userId: "u_kimi" }
178
+ : { ok: false, reason: "COOKIE_EXPIRED" }),
179
+ },
180
+ });
181
+ const wiz = buildWizard({ accountsStore, vendorAdapter });
182
+
183
+ await wiz.registerVendor({ vendor: "kimi", cookies: { access_token: "ok" } });
184
+
185
+ // Simulate the server invalidating the session.
186
+ isValid = false;
187
+
188
+ const hc = createAIChatHealthChecker({
189
+ accountsStore, vendorAdapter,
190
+ _deps: { logger: { info: () => {}, warn: () => {}, error: () => {} } },
191
+ });
192
+ const r = await hc.runOnce();
193
+ expect(r).toMatchObject({ checked: 1, ok: 0, failed: 1, mismatch: 0 });
194
+
195
+ const refreshed = JSON.parse(readFileSync(accountsStore._filePath, "utf-8"));
196
+ expect(refreshed.kimi.lastHealth).toMatchObject({
197
+ ok: false, reason: "COOKIE_EXPIRED",
198
+ });
199
+ });
200
+ });
201
+
202
+ // ─── Scenario C: spec version mismatch ───────────────────────────────────
203
+
204
+ describe("aichat wizard E2E — spec version mismatch", () => {
205
+ it("bumping specVersion marks old registrations SPEC_VERSION_MISMATCH", async () => {
206
+ const accountsStore = makeRealFsAccountsStore({ hubDir });
207
+ const vendorAdapter = makeStubVendorAdapter();
208
+ const wiz = buildWizard({ accountsStore, vendorAdapter });
209
+
210
+ await wiz.registerVendor({
211
+ vendor: "deepseek",
212
+ cookies: { userToken: "abc" },
213
+ });
214
+
215
+ // Bump spec version by passing 2 to HealthChecker (simulates a future
216
+ // cookie-capture-spec version bump).
217
+ const hc = createAIChatHealthChecker({
218
+ accountsStore, vendorAdapter, specVersion: 2,
219
+ _deps: { logger: { info: () => {}, warn: () => {}, error: () => {} } },
220
+ });
221
+ const r = await hc.runOnce();
222
+ expect(r).toMatchObject({ checked: 1, mismatch: 1, ok: 0, failed: 0 });
223
+
224
+ const refreshed = JSON.parse(readFileSync(accountsStore._filePath, "utf-8"));
225
+ expect(refreshed.deepseek.lastHealth).toMatchObject({
226
+ ok: false, reason: "SPEC_VERSION_MISMATCH",
227
+ });
228
+ // Adapter should NOT have been called for this entry — version gate
229
+ // short-circuits before validateCookie.
230
+ expect(vendorAdapter.registerVendor).toHaveBeenCalledTimes(1); // only register, no health validate
231
+ });
232
+ });
233
+
234
+ // ─── Scenario D: full lifecycle (register → cleanupOrphanPartitions) ─────
235
+
236
+ describe("aichat wizard E2E — orphan partition cleanup", () => {
237
+ it("cleanupOrphanPartitions drops partitions whose vendor was never registered", async () => {
238
+ const accountsStore = makeRealFsAccountsStore({ hubDir });
239
+ const vendorAdapter = makeStubVendorAdapter();
240
+ // For this scenario we use the in-test paste fallback — sessions are
241
+ // simulated. cleanupOrphanPartitions runs against the partition list
242
+ // we pass in, returning the vendors it would have cleared.
243
+ const cleared = new Set();
244
+ const wiz = createAIChatWizardController({
245
+ accountsStore,
246
+ vendorAdapter,
247
+ _deps: {
248
+ sessionFactory: (partName) => ({
249
+ clearStorageData: async () => {
250
+ cleared.add(partName);
251
+ },
252
+ }),
253
+ clock: () => Date.now(),
254
+ logger: { info: () => {}, warn: () => {}, error: () => {} },
255
+ classifier: require("../../lib/adapters/ai-chat-history/cookie-capture-spec").classifyProbedCookies,
256
+ specLookup: require("../../lib/adapters/ai-chat-history/cookie-capture-spec").getSpec,
257
+ knownVendors: require("../../lib/adapters/ai-chat-history/cookie-capture-spec").listVendors(),
258
+ cookieSpecVersion: 1,
259
+ fallbackMode: "browser-view",
260
+ },
261
+ });
262
+
263
+ await wiz.registerVendor({
264
+ vendor: "kimi",
265
+ cookies: { access_token: "x" },
266
+ });
267
+
268
+ const result = await wiz.cleanupOrphanPartitions({
269
+ partitions: [
270
+ "persist:aichat-deepseek", // orphan: no entry in store
271
+ "persist:aichat-kimi", // registered: should NOT be cleared
272
+ "persist:aichat-doubao", // orphan
273
+ "persist:unrelated", // not ours: leave alone
274
+ ],
275
+ });
276
+
277
+ expect(result.ok).toBe(true);
278
+ expect(result.cleared.sort()).toEqual(["deepseek", "doubao"]);
279
+ expect(cleared.has("persist:aichat-kimi")).toBe(false);
280
+ expect(cleared.has("persist:unrelated")).toBe(false);
281
+ });
282
+ });