localUsageEvidence.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { DatabaseSync } from "node:sqlite";
  5. import { afterEach, describe, expect, it, vi } from "vitest";
  6. import {
  7. createHasExistingLocalTask,
  8. hasAnyAgentSessionRow,
  9. resolveAgentSessionDbPath,
  10. } from "../src/onboarding/localUsageEvidence.js";
  11. /**
  12. * 老用户使用证据判定(docs/onboarding-record-spec.md §4 2026-10 修订):
  13. * tasks-index 是同步器的衍生投影,登录瞬间的判定可能早于回填(线上误弹案例:
  14. * 空索引把老用户判成新用户)。判定必须 OR 上磁盘级证据;agent 会话证据按 CLI
  15. * 的解析链定位会话库并查 session 表行数(评审 CR-01:路径有 env/config 覆盖、
  16. * 默认按 homedir 展开,cli/sessions 是工作流输出目录不得作为证据);证据"读
  17. * 不了"(非 ENOENT)不得当成"没有",必须上抛由 UI 保守判不弹(评审 CR-02)。
  18. */
  19. const tempDirs: string[] = [];
  20. function makeTempDir(): string {
  21. const dir = mkdtempSync(join(tmpdir(), "onboarding-usage-"));
  22. tempDirs.push(dir);
  23. return dir;
  24. }
  25. afterEach(() => {
  26. vi.restoreAllMocks();
  27. for (const dir of tempDirs.splice(0)) {
  28. rmSync(dir, { recursive: true, force: true });
  29. }
  30. });
  31. function createFactory(
  32. indexTasks: unknown[],
  33. hasAgentSessionRow: boolean,
  34. legacySessionsDir: string,
  35. ) {
  36. return createHasExistingLocalTask({
  37. listIndexTasks: vi.fn(async () => indexTasks),
  38. hasAgentSessionRow: vi.fn(async () => hasAgentSessionRow),
  39. resolveLegacyTaskSessionsDir: () => legacySessionsDir,
  40. });
  41. }
  42. function createSessionDb(dbPath: string, rows: number): void {
  43. mkdirSync(join(dbPath, ".."), { recursive: true });
  44. const db = new DatabaseSync(dbPath);
  45. db.exec("CREATE TABLE session (id TEXT)");
  46. const insert = db.prepare("INSERT INTO session (id) VALUES (?)");
  47. for (let i = 0; i < rows; i += 1) insert.run(`s${i}`);
  48. db.close();
  49. }
  50. describe("createHasExistingLocalTask", () => {
  51. it("索引有行即存量用户(短路,不查会话库)", async () => {
  52. const emptyDir = makeTempDir();
  53. const check = createFactory([{ id: "t1" }], false, emptyDir);
  54. await expect(check()).resolves.toBe(true);
  55. });
  56. it("索引为空但 agent 会话库有行 → 存量用户(索引回填时序缺陷的回归)", async () => {
  57. const emptyDir = makeTempDir();
  58. const check = createFactory([], true, emptyDir);
  59. await expect(check()).resolves.toBe(true);
  60. });
  61. it("索引与会话库皆空,旧版任务快照非空 → 存量用户", async () => {
  62. const legacySessionsDir = makeTempDir();
  63. writeFileSync(join(legacySessionsDir, "task-1.json"), "{}");
  64. writeFileSync(join(legacySessionsDir, "task-2.deleted.json"), "{}");
  65. const check = createFactory([], false, legacySessionsDir);
  66. await expect(check()).resolves.toBe(true);
  67. });
  68. it("三源全空(目录不存在/为空)→ 新用户", async () => {
  69. const check = createFactory([], false, join(makeTempDir(), "not-exist"));
  70. await expect(check()).resolves.toBe(false);
  71. const emptyDir = makeTempDir();
  72. const checkEmpty = createFactory([], false, emptyDir);
  73. await expect(checkEmpty()).resolves.toBe(false);
  74. });
  75. it("索引查询异常时上抛,由上层保守判不弹", async () => {
  76. const check = createHasExistingLocalTask({
  77. listIndexTasks: vi.fn(async () => {
  78. throw new Error("index db locked");
  79. }),
  80. hasAgentSessionRow: vi.fn(async () => true),
  81. resolveLegacyTaskSessionsDir: () => makeTempDir(),
  82. });
  83. await expect(check()).rejects.toThrow("index db locked");
  84. });
  85. });
  86. describe("hasAnyAgentSessionRow", () => {
  87. it("session 表有行 → true", async () => {
  88. const dbPath = join(makeTempDir(), "db.sqlite");
  89. createSessionDb(dbPath, 2);
  90. await expect(hasAnyAgentSessionRow(dbPath)).resolves.toBe(true);
  91. });
  92. it("session 表存在但为空 → false(空库不得误判存量)", async () => {
  93. const dbPath = join(makeTempDir(), "db.sqlite");
  94. createSessionDb(dbPath, 0);
  95. await expect(hasAnyAgentSessionRow(dbPath)).resolves.toBe(false);
  96. });
  97. it("库文件存在但无 session 表 → false", async () => {
  98. const dbPath = join(makeTempDir(), "db.sqlite");
  99. const db = new DatabaseSync(dbPath);
  100. db.exec("CREATE TABLE other (a TEXT)");
  101. db.close();
  102. await expect(hasAnyAgentSessionRow(dbPath)).resolves.toBe(false);
  103. });
  104. it("库文件不存在(ENOENT)→ false", async () => {
  105. await expect(
  106. hasAnyAgentSessionRow(join(makeTempDir(), "not-exist", "db.sqlite")),
  107. ).resolves.toBe(false);
  108. });
  109. it("WAL 未 checkpoint 的行对只读连接可见(写连接保持打开)", async () => {
  110. // 评审 SG-01:模拟 CLI 持有写连接、行还在 WAL 中未合并的真实场景——
  111. // 这正是线上误弹案例里"判定时刻数据在 WAL"的形态。
  112. const dbPath = join(makeTempDir(), "db.sqlite");
  113. const writer = new DatabaseSync(dbPath);
  114. writer.exec("PRAGMA journal_mode = WAL");
  115. writer.exec("PRAGMA wal_autocheckpoint = 0");
  116. writer.exec("CREATE TABLE session (id TEXT)");
  117. writer.prepare("INSERT INTO session (id) VALUES (?)").run("s1");
  118. try {
  119. await expect(hasAnyAgentSessionRow(dbPath)).resolves.toBe(true);
  120. } finally {
  121. writer.close();
  122. }
  123. });
  124. // Windows libuv 把 ENOTDIR 归一化为 ENOENT,该分支在 POSIX CI 上验证;
  125. // Windows 下同一语义由"库文件损坏 → 上抛"用例覆盖。
  126. (process.platform === "win32" ? it.skip : it)(
  127. "父路径是文件(ENOTDIR)→ 上抛而非静默无证据(评审 CR-02 回归)",
  128. async () => {
  129. const filePath = join(makeTempDir(), "occupied");
  130. writeFileSync(filePath, "not a dir");
  131. await expect(hasAnyAgentSessionRow(join(filePath, "db.sqlite"))).rejects.toThrow();
  132. },
  133. );
  134. it("库文件损坏 → 上抛(读不了 ≠ 没有,交由 UI 保守判不弹)", async () => {
  135. const dbPath = join(makeTempDir(), "db.sqlite");
  136. writeFileSync(dbPath, "definitely not a sqlite file");
  137. await expect(hasAnyAgentSessionRow(dbPath)).rejects.toThrow();
  138. });
  139. });
  140. describe("resolveAgentSessionDbPath(评审三轮 CR-01:不复制解析规则,无法确定按未知跳过)", () => {
  141. function freshHome(): { HOME: string; USER_CONFIG: string } {
  142. const HOME = join(makeTempDir(), "home");
  143. return { HOME, USER_CONFIG: join(HOME, ".zcode", "cli", "config.json") };
  144. }
  145. it("env 单别名:绝对路径原样可用", async () => {
  146. const customDb = join(makeTempDir(), "custom.sqlite");
  147. const { HOME, USER_CONFIG } = freshHome();
  148. await expect(
  149. resolveAgentSessionDbPath({
  150. env: { ZCODE_SESSION_DB_PATH: customDb },
  151. homedirPath: HOME,
  152. userConfigPath: USER_CONFIG,
  153. }),
  154. ).resolves.toBe(customDb);
  155. });
  156. it("env ~/ 值按 homedir 展开", async () => {
  157. const { HOME, USER_CONFIG } = freshHome();
  158. await expect(
  159. resolveAgentSessionDbPath({
  160. env: { ZCODE_SESSION_DB: "~/session-alt.sqlite" },
  161. homedirPath: HOME,
  162. userConfigPath: USER_CONFIG,
  163. }),
  164. ).resolves.toBe(join(HOME, "session-alt.sqlite"));
  165. });
  166. it("双别名并存按 env 键序取后者(与 CLI env adapter 覆盖顺序一致)", async () => {
  167. const dbA = join(makeTempDir(), "a.sqlite");
  168. const dbB = join(makeTempDir(), "b.sqlite");
  169. const { HOME, USER_CONFIG } = freshHome();
  170. // PATH 别名后出现 → PATH 胜出
  171. await expect(
  172. resolveAgentSessionDbPath({
  173. env: { ZCODE_SESSION_DB: dbA, ZCODE_SESSION_DB_PATH: dbB },
  174. homedirPath: HOME,
  175. userConfigPath: USER_CONFIG,
  176. }),
  177. ).resolves.toBe(dbB);
  178. // 交换插入顺序 → DB 别名胜出(固定优先级会在这里产生偏差,评审实证)
  179. await expect(
  180. resolveAgentSessionDbPath({
  181. env: { ZCODE_SESSION_DB_PATH: dbB, ZCODE_SESSION_DB: dbA },
  182. homedirPath: HOME,
  183. userConfigPath: USER_CONFIG,
  184. }),
  185. ).resolves.toBe(dbA);
  186. });
  187. it("env 相对路径 → null(CLI 按工作区 cwd 解析,host 无法镜像)", async () => {
  188. const { HOME, USER_CONFIG } = freshHome();
  189. await expect(
  190. resolveAgentSessionDbPath({
  191. env: { ZCODE_SESSION_DB_PATH: "history/session.sqlite" },
  192. homedirPath: HOME,
  193. userConfigPath: USER_CONFIG,
  194. }),
  195. ).resolves.toBeNull();
  196. });
  197. it("user config(home 默认位置)storage.sessionDbPath 覆盖,~/ 展开", async () => {
  198. const { HOME, USER_CONFIG } = freshHome();
  199. mkdirSync(join(HOME, ".zcode", "cli"), { recursive: true });
  200. writeFileSync(USER_CONFIG, JSON.stringify({ storage: { sessionDbPath: "~/data/s.sqlite" } }));
  201. await expect(
  202. resolveAgentSessionDbPath({ env: {}, homedirPath: HOME, userConfigPath: USER_CONFIG }),
  203. ).resolves.toBe(join(HOME, "data", "s.sqlite"));
  204. });
  205. it("user config 相对路径 → null(不按 host cwd 猜测)", async () => {
  206. const { HOME, USER_CONFIG } = freshHome();
  207. mkdirSync(join(HOME, ".zcode", "cli"), { recursive: true });
  208. writeFileSync(USER_CONFIG, JSON.stringify({ storage: { sessionDbPath: "db/rel.sqlite" } }));
  209. await expect(
  210. resolveAgentSessionDbPath({ env: {}, homedirPath: HOME, userConfigPath: USER_CONFIG }),
  211. ).resolves.toBeNull();
  212. });
  213. it("user config 不存在 → 默认 ~/.zcode/cli/db/db.sqlite(homedir 展开)", async () => {
  214. const { HOME, USER_CONFIG } = freshHome();
  215. await expect(
  216. resolveAgentSessionDbPath({ env: {}, homedirPath: HOME, userConfigPath: USER_CONFIG }),
  217. ).resolves.toBe(join(HOME, ".zcode", "cli", "db", "db.sqlite"));
  218. });
  219. it("默认 userConfigPath 钉住为 {home}/.zcode/cli/config.json(评审 SG-01)", async () => {
  220. // host 侧默认字面量与 CLI file-config.adapter 的 DEFAULT_BASE_DIR 是两处独立
  221. // 硬编码,漂移时镜像策略失效;此处显式锁定 host 侧拼装结果。
  222. const { HOME } = freshHome();
  223. const readPaths: string[] = [];
  224. await resolveAgentSessionDbPath({
  225. env: {},
  226. homedirPath: HOME,
  227. readConfigFile: async (path) => {
  228. readPaths.push(path);
  229. return "{}";
  230. },
  231. });
  232. expect(readPaths).toEqual([join(HOME, ".zcode", "cli", "config.json")]);
  233. });
  234. it("user config 非 ENOENT 读取失败 → 上抛", async () => {
  235. const { HOME, USER_CONFIG } = freshHome();
  236. const eaccs = Object.assign(new Error("read denied"), { code: "EACCES" });
  237. await expect(
  238. resolveAgentSessionDbPath({
  239. env: {},
  240. homedirPath: HOME,
  241. userConfigPath: USER_CONFIG,
  242. readConfigFile: async () => {
  243. throw eaccs;
  244. },
  245. }),
  246. ).rejects.toThrow(eaccs);
  247. });
  248. it("user config 非法 JSON → 上抛", async () => {
  249. const { HOME, USER_CONFIG } = freshHome();
  250. mkdirSync(join(HOME, ".zcode", "cli"), { recursive: true });
  251. writeFileSync(USER_CONFIG, "{broken json");
  252. await expect(
  253. resolveAgentSessionDbPath({ env: {}, homedirPath: HOME, userConfigPath: USER_CONFIG }),
  254. ).rejects.toThrow();
  255. });
  256. });