@chainlesschain/personal-data-hub 0.4.28 → 0.4.30

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 (204) hide show
  1. package/README.md +13 -5
  2. package/lib/adapters/social-douyin-adb/usage-profile-reader.js +253 -0
  3. package/lib/adapters/social-douyin-adb/watch-history-reader.js +104 -31
  4. package/lib/adapters/social-toutiao-adb/article-reader.js +202 -0
  5. package/lib/analysis-skills/overview.js +24 -4
  6. package/lib/analysis-skills/spending.js +63 -2
  7. package/lib/analysis-skills/timeline.js +11 -6
  8. package/lib/prompt-builder.js +15 -1
  9. package/lib/query-parser.js +38 -8
  10. package/package.json +4 -1
  11. package/__tests__/adapter-guide.test.js +0 -47
  12. package/__tests__/adapter-spec.test.js +0 -78
  13. package/__tests__/adapters/ai-chat-cookie-capture-spec.test.js +0 -211
  14. package/__tests__/adapters/ai-chat-health-checker.test.js +0 -262
  15. package/__tests__/adapters/ai-chat-history.test.js +0 -396
  16. package/__tests__/adapters/ai-chat-http-client.test.js +0 -242
  17. package/__tests__/adapters/ai-chat-vendors.test.js +0 -874
  18. package/__tests__/adapters/alipay-bill-adapter.test.js +0 -538
  19. package/__tests__/adapters/apple-health.test.js +0 -95
  20. package/__tests__/adapters/bank-family.test.js +0 -125
  21. package/__tests__/adapters/biz-tianyancha.test.js +0 -159
  22. package/__tests__/adapters/browser-history-chrome.test.js +0 -377
  23. package/__tests__/adapters/browser-history-edge.test.js +0 -159
  24. package/__tests__/adapters/car-mercedesme.test.js +0 -74
  25. package/__tests__/adapters/doc-baidu-netdisk.test.js +0 -102
  26. package/__tests__/adapters/doc-camscanner.test.js +0 -147
  27. package/__tests__/adapters/doc-platforms.test.js +0 -177
  28. package/__tests__/adapters/edu-huawei-learning-live.test.js +0 -198
  29. package/__tests__/adapters/edu-zuoyebang-live.test.js +0 -226
  30. package/__tests__/adapters/email-adapter-snapshot.test.js +0 -237
  31. package/__tests__/adapters/email-adapter.test.js +0 -742
  32. package/__tests__/adapters/email-classifier.test.js +0 -347
  33. package/__tests__/adapters/email-imap-session.test.js +0 -334
  34. package/__tests__/adapters/email-parser.test.js +0 -244
  35. package/__tests__/adapters/email-pdf-extractor.test.js +0 -529
  36. package/__tests__/adapters/email-providers.test.js +0 -84
  37. package/__tests__/adapters/email-retry-progress.test.js +0 -294
  38. package/__tests__/adapters/email-templates.test.js +0 -822
  39. package/__tests__/adapters/family-23-collectors-scaffold.test.js +0 -182
  40. package/__tests__/adapters/finance-alipay-live.test.js +0 -258
  41. package/__tests__/adapters/finance-dcep.test.js +0 -74
  42. package/__tests__/adapters/fitness-joyrun.test.js +0 -82
  43. package/__tests__/adapters/game-genshin-live.test.js +0 -238
  44. package/__tests__/adapters/game-genshin-scaffold.test.js +0 -108
  45. package/__tests__/adapters/game-honor-of-kings-live.test.js +0 -230
  46. package/__tests__/adapters/git-activity.test.js +0 -222
  47. package/__tests__/adapters/gov-12123.test.js +0 -103
  48. package/__tests__/adapters/gov-ixiamen.test.js +0 -150
  49. package/__tests__/adapters/gov-tax.test.js +0 -135
  50. package/__tests__/adapters/health-meiyou.test.js +0 -125
  51. package/__tests__/adapters/local-files.test.js +0 -264
  52. package/__tests__/adapters/local-im-pc.test.js +0 -154
  53. package/__tests__/adapters/messaging-whatsapp.test.js +0 -289
  54. package/__tests__/adapters/music-kugou.test.js +0 -187
  55. package/__tests__/adapters/music-qq.test.js +0 -112
  56. package/__tests__/adapters/netease-music-live.test.js +0 -244
  57. package/__tests__/adapters/netease-music.test.js +0 -74
  58. package/__tests__/adapters/pc-local-discovery.test.js +0 -141
  59. package/__tests__/adapters/qq-pc-direct-read.test.js +0 -227
  60. package/__tests__/adapters/reading-family.test.js +0 -108
  61. package/__tests__/adapters/recruit-boss.test.js +0 -180
  62. package/__tests__/adapters/shell-history.test.js +0 -180
  63. package/__tests__/adapters/shopping-base.test.js +0 -179
  64. package/__tests__/adapters/shopping-dianping.test.js +0 -239
  65. package/__tests__/adapters/social-bilibili-adb-api-client.test.js +0 -721
  66. package/__tests__/adapters/social-bilibili-adb-chromium-cookies-reader.test.js +0 -346
  67. package/__tests__/adapters/social-bilibili-adb-collector.test.js +0 -284
  68. package/__tests__/adapters/social-bilibili-adb-cookies-extension.test.js +0 -343
  69. package/__tests__/adapters/social-bilibili-adb-snapshot-builder.test.js +0 -296
  70. package/__tests__/adapters/social-csdn.test.js +0 -175
  71. package/__tests__/adapters/social-dongchedi.test.js +0 -165
  72. package/__tests__/adapters/social-douyin-adb-aweme-detail.test.js +0 -165
  73. package/__tests__/adapters/social-douyin-adb-collector.test.js +0 -254
  74. package/__tests__/adapters/social-douyin-adb-db-extension.test.js +0 -114
  75. package/__tests__/adapters/social-douyin-adb-im-db-parser.test.js +0 -304
  76. package/__tests__/adapters/social-douyin-adb-snapshot-builder.test.js +0 -216
  77. package/__tests__/adapters/social-douyin-adb-watch-history.test.js +0 -192
  78. package/__tests__/adapters/social-kuaishou-adb-api-client.test.js +0 -496
  79. package/__tests__/adapters/social-kuaishou-adb-collector.test.js +0 -276
  80. package/__tests__/adapters/social-kuaishou-adb-cookies-extension.test.js +0 -152
  81. package/__tests__/adapters/social-kuaishou-adb-snapshot-builder.test.js +0 -178
  82. package/__tests__/adapters/social-toutiao-adb-account-reader.test.js +0 -135
  83. package/__tests__/adapters/social-toutiao-adb-api-client.test.js +0 -626
  84. package/__tests__/adapters/social-toutiao-adb-collector.test.js +0 -378
  85. package/__tests__/adapters/social-toutiao-adb-cookies-extension.test.js +0 -193
  86. package/__tests__/adapters/social-toutiao-adb-snapshot-builder.test.js +0 -196
  87. package/__tests__/adapters/social-toutiao-kuaishou-scaffold.test.js +0 -311
  88. package/__tests__/adapters/social-weibo-adb-api-client.test.js +0 -362
  89. package/__tests__/adapters/social-weibo-adb-collector.test.js +0 -201
  90. package/__tests__/adapters/social-weibo-adb-cookies-extension.test.js +0 -167
  91. package/__tests__/adapters/social-weibo-adb-snapshot-builder.test.js +0 -189
  92. package/__tests__/adapters/social-xiaohongshu-adb-api-client.test.js +0 -431
  93. package/__tests__/adapters/social-xiaohongshu-adb-collector.test.js +0 -207
  94. package/__tests__/adapters/social-xiaohongshu-adb-cookies-extension.test.js +0 -0
  95. package/__tests__/adapters/social-xiaohongshu-adb-sign-provider-injection.test.js +0 -351
  96. package/__tests__/adapters/social-xiaohongshu-adb-sign.test.js +0 -130
  97. package/__tests__/adapters/social-xiaohongshu-adb-snapshot-builder.test.js +0 -200
  98. package/__tests__/adapters/social-zhihu.test.js +0 -246
  99. package/__tests__/adapters/system-data-adapter.test.js +0 -443
  100. package/__tests__/adapters/system-data-android-ingest.test.js +0 -144
  101. package/__tests__/adapters/system-data-android.test.js +0 -519
  102. package/__tests__/adapters/system-data-disclosure.test.js +0 -153
  103. package/__tests__/adapters/travel-12306.test.js +0 -512
  104. package/__tests__/adapters/travel-amap.test.js +0 -219
  105. package/__tests__/adapters/travel-baidu-map.test.js +0 -305
  106. package/__tests__/adapters/travel-base.test.js +0 -205
  107. package/__tests__/adapters/travel-ctrip.test.js +0 -377
  108. package/__tests__/adapters/travel-didi-consumer.test.js +0 -66
  109. package/__tests__/adapters/travel-didi.test.js +0 -204
  110. package/__tests__/adapters/travel-tencent-map.test.js +0 -207
  111. package/__tests__/adapters/travel-tongcheng.test.js +0 -289
  112. package/__tests__/adapters/video-platforms.test.js +0 -152
  113. package/__tests__/adapters/video-xigua.test.js +0 -106
  114. package/__tests__/adapters/vscode.test.js +0 -299
  115. package/__tests__/adapters/wechat-bootstrap.test.js +0 -240
  116. package/__tests__/adapters/wechat-env-probe.test.js +0 -162
  117. package/__tests__/adapters/wechat-frida-agent.test.js +0 -322
  118. package/__tests__/adapters/wechat-frida-integration.test.js +0 -149
  119. package/__tests__/adapters/wechat-frida-key-provider.test.js +0 -188
  120. package/__tests__/adapters/wechat-md5-key-provider.test.js +0 -101
  121. package/__tests__/adapters/wechat-pc-direct-read.test.js +0 -365
  122. package/__tests__/adapters/wechat-pc-group-topic.test.js +0 -63
  123. package/__tests__/adapters/wechat-pc-v4-sidecar.test.js +0 -72
  124. package/__tests__/adapters/weread.test.js +0 -123
  125. package/__tests__/adapters/wework-pc.test.js +0 -124
  126. package/__tests__/adapters/win-recent.test.js +0 -192
  127. package/__tests__/analysis-skills.test.js +0 -679
  128. package/__tests__/analysis.test.js +0 -1845
  129. package/__tests__/audio-ximalaya-snapshot.test.js +0 -279
  130. package/__tests__/batch.test.js +0 -133
  131. package/__tests__/bridges-cc-kg.test.js +0 -231
  132. package/__tests__/bridges-cc-llm.test.js +0 -191
  133. package/__tests__/bridges-cc-rag.test.js +0 -162
  134. package/__tests__/categories.test.js +0 -92
  135. package/__tests__/e2e/ai-chat-cross-source-journey.test.js +0 -213
  136. package/__tests__/e2e/full-user-journey.test.js +0 -188
  137. package/__tests__/e2e/local-data-adapters-cli.e2e.test.js +0 -146
  138. package/__tests__/entity-resolver-ingest-hook.test.js +0 -177
  139. package/__tests__/entity-resolver-stages.test.js +0 -411
  140. package/__tests__/entity-resolver-vault.test.js +0 -249
  141. package/__tests__/entity-resolver.test.js +0 -526
  142. package/__tests__/fitness-keep-snapshot.test.js +0 -224
  143. package/__tests__/fixtures/entity-resolver-200-mock.json +0 -96
  144. package/__tests__/ids.test.js +0 -45
  145. package/__tests__/integration/ai-chat-history-registry.test.js +0 -228
  146. package/__tests__/integration/aichat-wizard-end-to-end.test.js +0 -282
  147. package/__tests__/integration/cross-adapter-pipelines.test.js +0 -396
  148. package/__tests__/integration/local-data-adapters-pipeline.test.js +0 -373
  149. package/__tests__/integration/social-bilibili-pipeline.test.js +0 -261
  150. package/__tests__/integration/wechat-bootstrap-end-to-end.test.js +0 -390
  151. package/__tests__/key-providers.test.js +0 -126
  152. package/__tests__/kg-derive.test.js +0 -219
  153. package/__tests__/llm-client.test.js +0 -122
  154. package/__tests__/longtail-adapters.test.js +0 -281
  155. package/__tests__/messaging-qq-snapshot.test.js +0 -294
  156. package/__tests__/mobile-extractor-encrypted.test.js +0 -460
  157. package/__tests__/mobile-extractor.test.js +0 -288
  158. package/__tests__/mock-adapter.test.js +0 -93
  159. package/__tests__/prompt-builder.test.js +0 -249
  160. package/__tests__/query-parser.test.js +0 -302
  161. package/__tests__/rag-derive.test.js +0 -169
  162. package/__tests__/registry-readiness.test.js +0 -292
  163. package/__tests__/registry.test.js +0 -420
  164. package/__tests__/salvage-ingest.test.js +0 -97
  165. package/__tests__/schemas.test.js +0 -331
  166. package/__tests__/shopping-adapters.test.js +0 -392
  167. package/__tests__/shopping-eleme-snapshot.test.js +0 -454
  168. package/__tests__/shopping-pinduoduo-snapshot.test.js +0 -484
  169. package/__tests__/shopping-snapshot.test.js +0 -438
  170. package/__tests__/shopping-vipshop-snapshot.test.js +0 -425
  171. package/__tests__/shopping-xianyu-snapshot.test.js +0 -451
  172. package/__tests__/sidecar-contacts-cross-validate.test.js +0 -186
  173. package/__tests__/sidecar-supervisor.test.js +0 -128
  174. package/__tests__/sign-providers.test.js +0 -62
  175. package/__tests__/social-adapters.test.js +0 -280
  176. package/__tests__/social-bilibili-snapshot.test.js +0 -278
  177. package/__tests__/social-douban-snapshot.test.js +0 -351
  178. package/__tests__/social-douyin-im-direct-read.test.js +0 -377
  179. package/__tests__/social-douyin-salvage-collector.test.js +0 -98
  180. package/__tests__/social-douyin-salvage-mapper.test.js +0 -90
  181. package/__tests__/social-douyin-snapshot.test.js +0 -256
  182. package/__tests__/social-kuaishou-snapshot.test.js +0 -362
  183. package/__tests__/social-toutiao-snapshot.test.js +0 -366
  184. package/__tests__/social-weibo-snapshot.test.js +0 -234
  185. package/__tests__/social-weibo-sqlite-device.test.js +0 -174
  186. package/__tests__/social-xiaohongshu-snapshot.test.js +0 -232
  187. package/__tests__/sqlite-leaf-salvage.test.js +0 -97
  188. package/__tests__/travel-adapters.test.js +0 -483
  189. package/__tests__/travel-maps-snapshot.test.js +0 -426
  190. package/__tests__/vault-driver-error.test.js +0 -74
  191. package/__tests__/vault-search-helpers.test.js +0 -104
  192. package/__tests__/vault-search.test.js +0 -423
  193. package/__tests__/vault.test.js +0 -767
  194. package/__tests__/wechat-adapter.test.js +0 -594
  195. package/__tests__/whatsapp-adapter.test.js +0 -138
  196. package/scripts/_make-fixture-all.js +0 -126
  197. package/scripts/_make-fixture-contacts.js +0 -84
  198. package/scripts/evaluate-entity-resolver.js +0 -213
  199. package/scripts/run-native-tests-sandbox.sh +0 -55
  200. package/scripts/smoke-phase-5-5.js +0 -196
  201. package/scripts/smoke-phase-5-7.js +0 -181
  202. package/scripts/smoke-system-data-contacts.js +0 -309
  203. package/scripts/smoke-system-data.js +0 -312
  204. package/vitest.config.js +0 -88
@@ -1,246 +0,0 @@
1
- "use strict";
2
-
3
- import { describe, it, expect } from "vitest";
4
- const fs = require("node:fs");
5
- const path = require("node:path");
6
- const os = require("node:os");
7
- const crypto = require("node:crypto");
8
-
9
- const {
10
- ZhihuAdapter,
11
- extractData,
12
- NAME,
13
- VERSION,
14
- SNAPSHOT_SCHEMA_VERSION,
15
- } = require("../../lib/adapters/social-zhihu");
16
-
17
- function writeTmp(content) {
18
- const p = path.join(os.tmpdir(), `cc-zhihu-${crypto.randomUUID()}.json`);
19
- fs.writeFileSync(p, content, "utf-8");
20
- return p;
21
- }
22
-
23
- async function collect(gen) {
24
- const out = [];
25
- for await (const x of gen) out.push(x);
26
- return out;
27
- }
28
-
29
- const COOKIES = "z_c0=abc; d_c0=xyz";
30
-
31
- const SNAPSHOT = JSON.stringify({
32
- schemaVersion: 1,
33
- snapshottedAt: 1716383000000,
34
- account: { urlToken: "alice", name: "Alice" },
35
- events: [
36
- {
37
- kind: "answer",
38
- id: "answer-101",
39
- answerId: "101",
40
- questionTitle: "如何评价 X?",
41
- excerpt: "<p>我认为 X 很好</p>",
42
- voteupCount: 42,
43
- commentCount: 3,
44
- createdTime: 1716300000,
45
- url: "https://www.zhihu.com/answer/101",
46
- },
47
- {
48
- kind: "favourite",
49
- id: "fav-202",
50
- itemId: "202",
51
- title: "好文收藏",
52
- collectionName: "技术",
53
- capturedAt: 1716310000000,
54
- },
55
- {
56
- kind: "follow",
57
- id: "follow-bob",
58
- memberToken: "bob",
59
- name: "Bob",
60
- headline: "工程师",
61
- avatarUrl: "https://pic/bob.jpg",
62
- capturedAt: 1716320000000,
63
- },
64
- ],
65
- });
66
-
67
- describe("constants", () => {
68
- it("exposes name/version/schema", () => {
69
- expect(NAME).toBe("social-zhihu");
70
- expect(VERSION).toBe("0.1.0");
71
- expect(SNAPSHOT_SCHEMA_VERSION).toBe(1);
72
- });
73
- });
74
-
75
- describe("extractData", () => {
76
- it("pulls data/items arrays; tolerant of bad shapes", () => {
77
- expect(extractData({ data: [{ id: 1 }] })).toHaveLength(1);
78
- expect(extractData({ items: [{ id: 1 }] })).toHaveLength(1);
79
- expect(extractData({})).toEqual([]);
80
- expect(extractData(null)).toEqual([]);
81
- });
82
- });
83
-
84
- describe("ZhihuAdapter snapshot mode", () => {
85
- it("authenticate validates inputPath readability", async () => {
86
- const p = writeTmp(SNAPSHOT);
87
- try {
88
- const a = new ZhihuAdapter();
89
- expect((await a.authenticate({ inputPath: p })).mode).toBe("snapshot-file");
90
- const bad = await a.authenticate({ inputPath: path.join(os.tmpdir(), "nope-z.json") });
91
- expect(bad.ok).toBe(false);
92
- expect(bad.reason).toBe("INPUT_PATH_UNREADABLE");
93
- } finally {
94
- fs.unlinkSync(p);
95
- }
96
- });
97
-
98
- it("sync yields all 3 kinds + normalize answer→post, favourite→like, follow→person", async () => {
99
- const p = writeTmp(SNAPSHOT);
100
- try {
101
- const a = new ZhihuAdapter();
102
- const real = await collect(a.sync({ inputPath: p }));
103
- expect(real).toHaveLength(3);
104
- expect(real.map((x) => x.kind)).toEqual(["answer", "favourite", "follow"]);
105
-
106
- const ans = a.normalize(real[0]);
107
- expect(ans.events[0].subtype).toBe("post");
108
- expect(ans.events[0].content.text).toBe("我认为 X 很好"); // html stripped
109
- expect(ans.events[0].extra.voteupCount).toBe(42);
110
- expect(ans.events[0].extra.questionTitle).toBe("如何评价 X?");
111
-
112
- const fav = a.normalize(real[1]);
113
- expect(fav.events[0].subtype).toBe("like");
114
- expect(fav.events[0].content.title).toBe("好文收藏");
115
-
116
- const fol = a.normalize(real[2]);
117
- expect(fol.persons[0].subtype).toBe("contact");
118
- expect(fol.persons[0].names).toEqual(["Bob"]);
119
- expect(fol.persons[0].identifiers["zhihu-token"]).toEqual(["bob"]);
120
- } finally {
121
- fs.unlinkSync(p);
122
- }
123
- });
124
-
125
- it("respects include filter + limit", async () => {
126
- const p = writeTmp(SNAPSHOT);
127
- try {
128
- const a = new ZhihuAdapter();
129
- const onlyFollow = await collect(a.sync({ inputPath: p, include: { answer: false, favourite: false } }));
130
- expect(onlyFollow.map((x) => x.kind)).toEqual(["follow"]);
131
- const limited = await collect(a.sync({ inputPath: p, limit: 1 }));
132
- expect(limited).toHaveLength(1);
133
- } finally {
134
- fs.unlinkSync(p);
135
- }
136
- });
137
-
138
- it("schemaVersion mismatch throws", async () => {
139
- const p = writeTmp(JSON.stringify({ schemaVersion: 9, events: [] }));
140
- try {
141
- const a = new ZhihuAdapter();
142
- await expect(collect(a.sync({ inputPath: p }))).rejects.toThrow(/schemaVersion mismatch/);
143
- } finally {
144
- fs.unlinkSync(p);
145
- }
146
- });
147
-
148
- it("normalize throws on unknown kind", () => {
149
- const a = new ZhihuAdapter();
150
- expect(() => a.normalize({ kind: "bogus", payload: {} })).toThrow(/unknown kind/);
151
- });
152
- });
153
-
154
- describe("ZhihuAdapter cookie-api mode", () => {
155
- it("authenticate cookie mode requires urlToken", async () => {
156
- const noTok = new ZhihuAdapter({ account: { cookies: COOKIES } });
157
- expect((await noTok.authenticate()).reason).toBe("NO_ACCOUNT_URL_TOKEN");
158
- const ok = new ZhihuAdapter({ account: { cookies: COOKIES, urlToken: "alice" } });
159
- expect(await ok.authenticate()).toEqual({ ok: true, account: "alice", mode: "cookie" });
160
- });
161
-
162
- it("sync fetches answers/followees/collections, paginates, normalizes", async () => {
163
- const byUrl = (url) => {
164
- if (url.includes("/answers")) return "answers";
165
- if (url.includes("/followees")) return "followees";
166
- if (url.includes("/collections")) return "collections";
167
- return "?";
168
- };
169
- const data = {
170
- answers: [
171
- { id: "A1", question: { title: "Q1" }, excerpt: "ans1", voteup_count: 9, created_time: 1716300000 },
172
- ],
173
- followees: [{ url_token: "bob", name: "Bob", headline: "eng" }],
174
- collections: [{ id: "C1", title: "我的收藏", is_public: true }],
175
- };
176
- const calls = [];
177
- const fetchFn = async ({ url, cookies, query, sign }) => {
178
- const k = byUrl(url);
179
- calls.push({ k, cookies, offset: query.offset, sign });
180
- // single page each
181
- return { data: query.offset === 0 ? data[k] : [], paging: { is_end: query.offset !== 0 } };
182
- };
183
- const a = new ZhihuAdapter({ account: { cookies: COOKIES, urlToken: "alice" }, fetchFn });
184
- const items = await collect(a.sync({}));
185
- expect(items.map((x) => x.kind).sort()).toEqual(["answer", "favourite", "follow"]);
186
- expect(calls.every((c) => c.cookies === COOKIES)).toBe(true);
187
- expect(calls.every((c) => c.sign === null)).toBe(true);
188
-
189
- const ans = a.normalize(items.find((x) => x.kind === "answer"));
190
- expect(ans.events[0].content.title).toBe("Q1");
191
- expect(ans.events[0].extra.voteupCount).toBe(9);
192
- const fol = a.normalize(items.find((x) => x.kind === "follow"));
193
- expect(fol.persons[0].names).toEqual(["Bob"]);
194
- expect(fol.persons[0].identifiers["zhihu-token"]).toEqual(["bob"]);
195
- const fav = a.normalize(items.find((x) => x.kind === "favourite"));
196
- expect(fav.events[0].content.title).toBe("我的收藏");
197
- });
198
-
199
- it("invokes signProvider when configured", async () => {
200
- const signCalls = [];
201
- const a = new ZhihuAdapter({
202
- account: { cookies: COOKIES, urlToken: "alice" },
203
- fetchFn: async ({ query }) =>
204
- query.offset === 0 ? { data: [{ id: "A1", question: { title: "Q" }, excerpt: "x" }], paging: { is_end: true } } : { data: [], paging: { is_end: true } },
205
- signProvider: async (ctx) => {
206
- signCalls.push(ctx);
207
- return "x-zse-96-value";
208
- },
209
- // only answers to keep it short
210
- });
211
- const items = await collect(a.sync({ include: { follow: false, favourite: false } }));
212
- expect(items.length).toBeGreaterThan(0);
213
- expect(signCalls.length).toBeGreaterThan(0);
214
- expect(signCalls[0].cookies).toBe(COOKIES);
215
- });
216
-
217
- it("respects opts.limit across kinds", async () => {
218
- const a = new ZhihuAdapter({
219
- account: { cookies: COOKIES, urlToken: "alice" },
220
- fetchFn: async ({ query }) =>
221
- query.offset === 0
222
- ? { data: [{ id: "A1", question: { title: "Q" }, excerpt: "x" }, { id: "A2", question: { title: "Q2" }, excerpt: "y" }], paging: { is_end: true } }
223
- : { data: [], paging: { is_end: true } },
224
- });
225
- const items = await collect(a.sync({ limit: 1 }));
226
- expect(items).toHaveLength(1);
227
- });
228
-
229
- it("is_end stops pagination; empty data yields zero (no crash)", async () => {
230
- const a = new ZhihuAdapter({
231
- account: { cookies: COOKIES, urlToken: "alice" },
232
- fetchFn: async () => "not-json-login-redirect",
233
- });
234
- expect(await collect(a.sync({}))).toEqual([]);
235
- });
236
-
237
- it("default fetch throws when no fetchFn", async () => {
238
- const a = new ZhihuAdapter({ account: { cookies: COOKIES, urlToken: "alice" } });
239
- await expect(collect(a.sync({}))).rejects.toThrow(/no fetchFn configured/);
240
- });
241
-
242
- it("sync with no input/cookie throws", async () => {
243
- const a = new ZhihuAdapter();
244
- await expect(collect(a.sync({}))).rejects.toThrow(/needs opts.inputPath/);
245
- });
246
- });
@@ -1,443 +0,0 @@
1
- "use strict";
2
-
3
- /**
4
- * Unit tests for SystemDataAdapter (Phase 4.5.5).
5
- *
6
- * Uses a hand-rolled FakeSupervisor — we don't spawn Python here. The supervisor
7
- * boundary is verified separately by the integration tests in
8
- * `sidecar-supervisor.test.js` + `sidecar-contacts-cross-validate.test.js`.
9
- * Here we want fast, deterministic, full-coverage exercise of the adapter's
10
- * orchestration logic (include flags / dataPaths fallback / progress events /
11
- * authenticate gating / etc).
12
- */
13
-
14
- import { describe, it, expect, beforeEach } from "vitest";
15
-
16
- const {
17
- SystemDataAdapter,
18
- SYSTEM_DATA_ADAPTER_NAME,
19
- SYSTEM_DATA_ADAPTER_VERSION,
20
- DEFAULT_INCLUDE,
21
- } = require("../../lib/adapters/system-data");
22
- const { assertAdapter } = require("../../lib/adapter-spec");
23
-
24
- /**
25
- * Minimal supervisor stub: pluggable per-method handlers + recorded calls.
26
- */
27
- class FakeSupervisor {
28
- constructor(handlers = {}) {
29
- this.handlers = handlers;
30
- this.calls = [];
31
- }
32
-
33
- async invoke(method, params = {}, opts = {}) {
34
- this.calls.push({ method, params, opts });
35
- const handler = this.handlers[method];
36
- if (!handler) throw Object.assign(new Error(`unhandled method: ${method}`), { code: "TEST_NO_HANDLER" });
37
- return await handler(params, opts);
38
- }
39
- }
40
-
41
- /** Make a chunk-emitting handler whose `onChunk` is fed by `chunks`. */
42
- function chunkingHandler(chunks, result) {
43
- return async (_params, opts) => {
44
- for (const c of chunks) {
45
- if (opts && typeof opts.onChunk === "function") opts.onChunk(c);
46
- }
47
- return result;
48
- };
49
- }
50
-
51
- function personPayload(rawContactId, name, phones = []) {
52
- return {
53
- id: `person:system:android:${rawContactId}`,
54
- type: "person",
55
- subtype: "contact",
56
- names: [name],
57
- identifiers: phones.length ? { phone: phones } : undefined,
58
- ingestedAt: 1_700_000_000_000,
59
- confidence: 1.0,
60
- source: {
61
- adapter: "system-data",
62
- adapterVersion: "0.1.0",
63
- originalId: String(rawContactId),
64
- capturedAt: 1_700_000_000_000,
65
- capturedBy: "sqlite",
66
- },
67
- extra: { starred: false },
68
- };
69
- }
70
-
71
- function callEventPayload(callId, occurredAt = 1_700_000_000_000) {
72
- return {
73
- id: `event:system:call:${callId}`,
74
- type: "event",
75
- subtype: "call",
76
- occurredAt,
77
- actor: "person:self",
78
- participants: ["person:system:android:1"],
79
- content: {},
80
- ingestedAt: occurredAt,
81
- confidence: 1.0,
82
- source: {
83
- adapter: "system-data",
84
- adapterVersion: "0.1.0",
85
- originalId: String(callId),
86
- capturedAt: occurredAt,
87
- capturedBy: "sqlite",
88
- },
89
- extra: { callType: "outgoing", callTypeCode: 2, isRead: true, rawNumber: "13800001111" },
90
- };
91
- }
92
-
93
- function placePayload(name) {
94
- return {
95
- id: `place:wifi:${name.toLowerCase()}`,
96
- type: "place",
97
- name,
98
- category: "wifi",
99
- aliases: [],
100
- ingestedAt: 1_700_000_000_000,
101
- confidence: 0.95,
102
- source: {
103
- adapter: "system-data",
104
- adapterVersion: "0.1.0",
105
- originalId: name,
106
- capturedAt: 1_700_000_000_000,
107
- capturedBy: "manual",
108
- },
109
- extra: { securityType: "WPA/WPA2", hidden: false, passwordStored: true },
110
- };
111
- }
112
-
113
- // ---------------------------------------------------------------------------
114
- // Suite
115
- // ---------------------------------------------------------------------------
116
-
117
- describe("SystemDataAdapter contract", () => {
118
- it("conforms to PersonalDataAdapter contract", () => {
119
- const adapter = new SystemDataAdapter({ supervisor: new FakeSupervisor() });
120
- const result = assertAdapter(adapter);
121
- expect(result).toEqual({ ok: true });
122
- });
123
-
124
- it("exposes constants and version", () => {
125
- expect(SYSTEM_DATA_ADAPTER_NAME).toBe("system-data");
126
- expect(SYSTEM_DATA_ADAPTER_VERSION).toMatch(/^\d+\.\d+\.\d+/);
127
- });
128
-
129
- it("declares correct default include flags (SMS opt-out)", () => {
130
- expect(DEFAULT_INCLUDE).toEqual({
131
- contacts: true,
132
- calllog: true,
133
- sms: false,
134
- wifi: true,
135
- });
136
- });
137
-
138
- it("dataDisclosure is high-sensitivity + legalGate ON", () => {
139
- const adapter = new SystemDataAdapter({ supervisor: new FakeSupervisor() });
140
- expect(adapter.dataDisclosure.sensitivity).toBe("high");
141
- expect(adapter.dataDisclosure.legalGate).toBe(true);
142
- expect(adapter.dataDisclosure.notice).toMatch(/不向任何服务器上传/);
143
- expect(adapter.dataDisclosure.fields.some((f) => f.startsWith("sms:"))).toBe(true);
144
- });
145
- });
146
-
147
- describe("SystemDataAdapter.authenticate", () => {
148
- it("returns offline mode when dataPaths are provided", async () => {
149
- const sup = new FakeSupervisor({
150
- "sidecar.ping": async () => ({ version: "0.1.0", pythonVersion: "3.12" }),
151
- });
152
- const adapter = new SystemDataAdapter({ supervisor: sup });
153
-
154
- const out = await adapter.authenticate({ dataPaths: { contacts: "/tmp/c.db" } });
155
- expect(out).toEqual({ ok: true, mode: "offline", sidecarVersion: "0.1.0" });
156
- expect(sup.calls.map((c) => c.method)).toEqual(["sidecar.ping"]);
157
- });
158
-
159
- it("fails when sidecar is down", async () => {
160
- const sup = new FakeSupervisor({
161
- "sidecar.ping": async () => {
162
- throw Object.assign(new Error("sidecar gone"), {
163
- code: "SIDECAR_NOT_RUNNING",
164
- });
165
- },
166
- });
167
- const adapter = new SystemDataAdapter({ supervisor: sup });
168
- await expect(adapter.authenticate({ dataPaths: { contacts: "/x" } })).rejects.toThrow();
169
- });
170
-
171
- it("device mode lists devices and accepts any authorized one", async () => {
172
- const sup = new FakeSupervisor({
173
- "sidecar.ping": async () => ({ version: "0.1.0", pythonVersion: "3.12" }),
174
- "android.list_devices": async () => ({
175
- devices: [
176
- { serial: "abc", state: "device", model: "Redmi" },
177
- { serial: "xyz", state: "unauthorized" },
178
- ],
179
- }),
180
- });
181
- const adapter = new SystemDataAdapter({ supervisor: sup });
182
-
183
- const out = await adapter.authenticate({});
184
- expect(out.ok).toBe(true);
185
- expect(out.mode).toBe("device");
186
- expect(out.devices).toHaveLength(1);
187
- expect(out.devices[0].serial).toBe("abc");
188
- });
189
-
190
- it("device mode fails when no authorized device matches", async () => {
191
- const sup = new FakeSupervisor({
192
- "sidecar.ping": async () => ({ version: "0.1.0", pythonVersion: "3.12" }),
193
- "android.list_devices": async () => ({
194
- devices: [{ serial: "xyz", state: "unauthorized" }],
195
- }),
196
- });
197
- const adapter = new SystemDataAdapter({ supervisor: sup });
198
- const out = await adapter.authenticate({});
199
- expect(out.ok).toBe(false);
200
- expect(out.reason).toMatch(/no authorized/i);
201
- });
202
-
203
- it("device mode targets a specific serial when provided", async () => {
204
- const sup = new FakeSupervisor({
205
- "sidecar.ping": async () => ({ version: "0.1.0", pythonVersion: "3.12" }),
206
- "android.list_devices": async () => ({
207
- devices: [
208
- { serial: "abc", state: "device" },
209
- { serial: "xyz", state: "device" },
210
- ],
211
- }),
212
- });
213
- const adapter = new SystemDataAdapter({ supervisor: sup });
214
- const out = await adapter.authenticate({ serial: "xyz" });
215
- expect(out.ok).toBe(true);
216
- expect(out.devices).toEqual([{ serial: "xyz", state: "device" }]);
217
- });
218
- });
219
-
220
- describe("SystemDataAdapter.sync via dataPaths (no ADB)", () => {
221
- let sup;
222
- let adapter;
223
-
224
- beforeEach(() => {
225
- sup = new FakeSupervisor({
226
- "system.parse_contacts": chunkingHandler(
227
- [{ events: [], persons: [personPayload(1, "妈妈", ["138"])], places: [], items: [] }],
228
- { status: "ok", totalPersons: 1, watermark: null, stats: { with_phone: 1, with_email: 0, starred: 0 } },
229
- ),
230
- "system.parse_calllog": chunkingHandler(
231
- [{
232
- events: [callEventPayload(101)],
233
- persons: [personPayload("unknown:139", "139")],
234
- places: [],
235
- items: [],
236
- }],
237
- { status: "ok", totalEvents: 1, totalPersonsCreated: 1, watermark: null, stats: {} },
238
- ),
239
- "system.parse_wifi": chunkingHandler(
240
- [{ events: [], persons: [], places: [placePayload("HomeWiFi")], items: [] }],
241
- { status: "ok", totalPlaces: 1, watermark: null, stats: {} },
242
- ),
243
- });
244
- adapter = new SystemDataAdapter({ supervisor: sup });
245
- });
246
-
247
- it("yields raws in entityType-tagged envelope shape", async () => {
248
- const raws = [];
249
- for await (const raw of adapter.sync({
250
- dataPaths: {
251
- contacts: "/tmp/contacts2.db",
252
- calllog: "/tmp/calls.db",
253
- wifi: "/tmp/wifi-dir",
254
- },
255
- })) {
256
- raws.push(raw);
257
- }
258
-
259
- // 1 person (contacts) + 1 event + 1 unknown person (calllog) + 1 place
260
- expect(raws).toHaveLength(4);
261
- const types = raws.map((r) => r.entityType);
262
- expect(types.sort()).toEqual(["event", "person", "person", "place"]);
263
-
264
- // Envelope shape
265
- for (const r of raws) {
266
- expect(typeof r.originalId).toBe("string");
267
- expect(typeof r.capturedAt).toBe("number");
268
- expect(r.payload && r.payload.type).toBe(r.entityType);
269
- }
270
- });
271
-
272
- it("normalize() places one entity into its correct bucket", () => {
273
- const raw = {
274
- entityType: "person",
275
- originalId: "1",
276
- capturedAt: 1,
277
- payload: personPayload(1, "X"),
278
- };
279
- const batch = adapter.normalize(raw);
280
- expect(batch).toEqual({
281
- events: [],
282
- persons: [raw.payload],
283
- places: [],
284
- items: [],
285
- topics: [],
286
- });
287
- });
288
-
289
- it("normalize() returns empty buckets for unknown entityType", () => {
290
- const batch = adapter.normalize({ entityType: "???", payload: {} });
291
- expect(batch.events).toEqual([]);
292
- expect(batch.persons).toEqual([]);
293
- });
294
-
295
- it("respects include flag — disabling SMS skips parse_sms entirely", async () => {
296
- // sms enabled in this run; we have no parse_sms handler, so enabling
297
- // it would crash. Default has it off — sync should succeed.
298
- const raws = [];
299
- for await (const raw of adapter.sync({
300
- dataPaths: {
301
- contacts: "/tmp/c.db",
302
- calllog: "/tmp/cl.db",
303
- wifi: "/tmp/wifi",
304
- },
305
- })) {
306
- raws.push(raw);
307
- }
308
- expect(sup.calls.find((c) => c.method === "system.parse_sms")).toBeUndefined();
309
- expect(raws.length).toBeGreaterThan(0);
310
- });
311
-
312
- it("explicitly disabling every source yields zero raws and zero sidecar calls", async () => {
313
- const raws = [];
314
- for await (const raw of adapter.sync({
315
- include: { contacts: false, calllog: false, sms: false, wifi: false },
316
- dataPaths: {},
317
- })) {
318
- raws.push(raw);
319
- }
320
- expect(raws).toEqual([]);
321
- expect(sup.calls).toEqual([]);
322
- });
323
-
324
- it("forwards onProgress events from adapter scope", async () => {
325
- const events = [];
326
- const iter = adapter.sync({
327
- dataPaths: { contacts: "/c", calllog: "/cl", wifi: "/w" },
328
- onProgress: (msg) => events.push(msg),
329
- });
330
- for await (const _ of iter) { /* drain */ }
331
-
332
- const phases = events.map((e) => `${e.source}:${e.phase}`);
333
- expect(phases).toContain("contacts:parsing");
334
- expect(phases).toContain("calllog:parsing");
335
- expect(phases).toContain("wifi:parsing");
336
- });
337
- });
338
-
339
- describe("SystemDataAdapter.sync ADB pull flow", () => {
340
- it("invokes android.pull_file per enabled source when no dataPaths given", async () => {
341
- const pullCalls = [];
342
- const sup = new FakeSupervisor({
343
- "android.pull_file": async (params) => {
344
- pullCalls.push(params.remote_path);
345
- return { remote: params.remote_path, local: `/scratch/${pullCalls.length}.db`, bytes: 100 };
346
- },
347
- "system.parse_contacts": chunkingHandler([], { status: "ok", totalPersons: 0, watermark: null, stats: {} }),
348
- "system.parse_calllog": chunkingHandler([], { status: "ok", totalEvents: 0, totalPersonsCreated: 0, watermark: null, stats: {} }),
349
- "system.parse_wifi": chunkingHandler([], { status: "ok", totalPlaces: 0, watermark: null, stats: {} }),
350
- });
351
- const adapter = new SystemDataAdapter({ supervisor: sup });
352
-
353
- // No scratchDir → adapter defaults to fs.mkdtempSync(os.tmpdir()). Don't pass
354
- // an absolute "/scratch": it mkdir's at FS root, which is EACCES on Linux CI
355
- // (passed on Windows where /scratch maps to a creatable drive-relative path).
356
- const iter = adapter.sync({ serial: "redmi" });
357
- for await (const _ of iter) { /* drain */ }
358
-
359
- expect(pullCalls).toEqual([
360
- "/data/data/com.android.providers.contacts/databases/contacts2.db",
361
- "/data/data/com.android.providers.contacts/databases/calllog.db",
362
- "/data/misc/wifi/",
363
- ]);
364
- });
365
-
366
- it("sdcard mode uses /sdcard/Download/ paths", async () => {
367
- const pullCalls = [];
368
- const sup = new FakeSupervisor({
369
- "android.pull_file": async (params) => {
370
- pullCalls.push(params.remote_path);
371
- return { remote: params.remote_path, local: `/scratch/${pullCalls.length}`, bytes: 100 };
372
- },
373
- "system.parse_contacts": chunkingHandler([], { status: "ok", totalPersons: 0, watermark: null, stats: {} }),
374
- "system.parse_calllog": chunkingHandler([], { status: "ok", totalEvents: 0, totalPersonsCreated: 0, watermark: null, stats: {} }),
375
- "system.parse_wifi": chunkingHandler([], { status: "ok", totalPlaces: 0, watermark: null, stats: {} }),
376
- });
377
- const adapter = new SystemDataAdapter({ supervisor: sup });
378
-
379
- const iter = adapter.sync({ serial: "redmi", extractMode: "sdcard" });
380
- for await (const _ of iter) { /* drain */ }
381
-
382
- for (const p of pullCalls) expect(p).toMatch(/^\/sdcard\/Download\//);
383
- });
384
-
385
- it("throws when a source is enabled but neither serial nor dataPaths present", async () => {
386
- const sup = new FakeSupervisor();
387
- const adapter = new SystemDataAdapter({ supervisor: sup });
388
- const iter = adapter.sync({ include: { contacts: true, calllog: false, sms: false, wifi: false } });
389
- await expect((async () => {
390
- for await (const _ of iter) { /* */ }
391
- })()).rejects.toThrow(/no serial.*dataPaths/i);
392
- });
393
-
394
- it("skips wifi gracefully when pull_file fails with EXTRACT_PERMISSION_DENIED", async () => {
395
- const sup = new FakeSupervisor({
396
- "android.pull_file": async (params) => {
397
- if (params.remote_path.startsWith("/data/misc/wifi")) {
398
- throw Object.assign(new Error("denied"), {
399
- code: "EXTRACT_PERMISSION_DENIED",
400
- });
401
- }
402
- return { remote: params.remote_path, local: `/scratch/x`, bytes: 1 };
403
- },
404
- "system.parse_contacts": chunkingHandler([], { status: "ok", totalPersons: 0, watermark: null, stats: {} }),
405
- "system.parse_calllog": chunkingHandler([], { status: "ok", totalEvents: 0, totalPersonsCreated: 0, watermark: null, stats: {} }),
406
- });
407
- const adapter = new SystemDataAdapter({ supervisor: sup });
408
- const events = [];
409
- const iter = adapter.sync({
410
- serial: "redmi",
411
- include: { contacts: true, calllog: true, sms: false, wifi: true },
412
- onProgress: (msg) => events.push(msg),
413
- });
414
- for await (const _ of iter) { /* drain */ }
415
-
416
- const wifiSkipped = events.find((e) => e.source === "wifi" && e.phase === "skipped");
417
- expect(wifiSkipped).toBeDefined();
418
- expect(wifiSkipped.reason).toBe("EXTRACT_PERMISSION_DENIED");
419
- });
420
- });
421
-
422
- describe("SystemDataAdapter.healthCheck", () => {
423
- it("returns ok when sidecar pings", async () => {
424
- const sup = new FakeSupervisor({
425
- "sidecar.ping": async () => ({ version: "0.1.0" }),
426
- });
427
- const adapter = new SystemDataAdapter({ supervisor: sup });
428
- const r = await adapter.healthCheck();
429
- expect(r).toEqual({ ok: true, version: "0.1.0" });
430
- });
431
-
432
- it("returns not-ok with reason when ping fails", async () => {
433
- const sup = new FakeSupervisor({
434
- "sidecar.ping": async () => {
435
- throw Object.assign(new Error("dead"), { code: "TIMEOUT" });
436
- },
437
- });
438
- const adapter = new SystemDataAdapter({ supervisor: sup });
439
- const r = await adapter.healthCheck();
440
- expect(r.ok).toBe(false);
441
- expect(r.reason).toMatch(/TIMEOUT/);
442
- });
443
- });