sourceServerWorkspaceAliasRepo.projections.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. import { mkdtemp, rm } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { DatabaseSync } from "node:sqlite";
  5. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  6. import type { ZCodeTaskMeta } from "@zcode/shared";
  7. import { SourceServerWorkspaceAliasRepo } from "#src/session/sourceServerWorkspaceAliasRepo.js";
  8. import { TaskIndexRepo } from "#src/session/taskIndexRepo.js";
  9. import { seedTaskIndex } from "./helpers/taskIndexFixture.js";
  10. const workspacePath = "/srv/project";
  11. const canonicalKey = "remote:ssh:canonical.example:22:dev:/srv/project";
  12. const sourceKey = "remote:ssh:source.example:22:dev:/srv/project";
  13. let root: string;
  14. let taskDbPath: string;
  15. let index: TaskIndexRepo;
  16. let aliases: SourceServerWorkspaceAliasRepo;
  17. function task(key: string, patch: Partial<ZCodeTaskMeta> = {}): ZCodeTaskMeta {
  18. return {
  19. taskId: "shared-task",
  20. traceId: "trace-shared",
  21. title: "Shared task",
  22. workspacePath,
  23. workspaceIdentity: key,
  24. createdAt: 10,
  25. updatedAt: 100,
  26. mode: "default",
  27. status: "completed",
  28. ...patch,
  29. };
  30. }
  31. /** CLI 事实与组织态由夹具分别写入;正文索引随展示投影一起落库。 */
  32. async function seed(meta: ZCodeTaskMeta, searchableText?: string): Promise<void> {
  33. await seedTaskIndex(index, { meta, searchableText });
  34. }
  35. /**
  36. * 把夹具退回项目化前的旧库形态(host_id/cli_* 为空、带旧 ACP wrapper 列),再重开索引走
  37. * 真实启动链:项目化按旧列初始化 cli_*,随后旧 ACP ID 合并只抬高 wrapperKey 下的 updated_at。
  38. */
  39. async function restartFromPreProjectionLegacyDb(wrapperKey: string): Promise<void> {
  40. index.close();
  41. const db = new DatabaseSync(taskDbPath);
  42. try {
  43. db.exec(`UPDATE tasks SET host_id = NULL, cli_title = NULL, cli_title_source = NULL,
  44. cli_created_at = NULL, cli_updated_at = NULL, cli_last_outcome = NULL, cli_deleted = NULL,
  45. handoff_pending = 0`);
  46. db.exec("ALTER TABLE tasks ADD COLUMN acp_session_id TEXT");
  47. db.prepare(
  48. "UPDATE tasks SET acp_session_id = 'shared-task' WHERE workspace_key = ? AND task_id = 'legacy-wrapper'",
  49. ).run(wrapperKey);
  50. } finally {
  51. db.close();
  52. }
  53. await index.ensureReady();
  54. }
  55. beforeEach(async () => {
  56. root = await mkdtemp(join(tmpdir(), "zcode-alias-projections-"));
  57. taskDbPath = join(root, "tasks-index.sqlite");
  58. index = new TaskIndexRepo(undefined, undefined, taskDbPath);
  59. await index.ensureReady();
  60. aliases = new SourceServerWorkspaceAliasRepo({
  61. taskDbPath,
  62. sessionDbPath: join(root, "absent-session.sqlite"),
  63. backupRoot: join(root, "backups"),
  64. });
  65. // 固定已发布 canonical,任务自身的新旧顺序不应改变线路选举。
  66. await aliases.resolveCanonicalWorkspaceKey({ workspacePath, legacyRouteHint: canonicalKey });
  67. });
  68. afterEach(async () => {
  69. index.close();
  70. await rm(root, { recursive: true, force: true });
  71. });
  72. describe("Source Server duplicate task projections", () => {
  73. it.each(["source-newer", "canonical-newer", "same-time"] as const)(
  74. "projects merged metadata using the newer record: %s",
  75. async (order) => {
  76. await seed(
  77. task(canonicalKey, {
  78. updatedAt: order === "canonical-newer" ? 600 : 100,
  79. status: "error",
  80. model: "model-old",
  81. }),
  82. );
  83. await seed(
  84. task(sourceKey, {
  85. title: "Source title",
  86. createdAt: 5,
  87. updatedAt: order === "same-time" ? 100 : 500,
  88. status: "completed",
  89. provider: "glm",
  90. mode: "plan",
  91. model: "model-new",
  92. migrationSource: "claudeCode",
  93. forkedFromTaskId: "parent-task",
  94. cronAutomationId: "automation-1",
  95. offPeakTaskId: "off-peak-1",
  96. }),
  97. );
  98. await aliases.resolveCanonicalWorkspaceKey({ workspacePath });
  99. const sourceWins = order !== "canonical-newer";
  100. const expectedMeta = {
  101. status: sourceWins ? "completed" : "error",
  102. provider: "glm",
  103. mode: sourceWins ? "plan" : "default",
  104. model: sourceWins ? "model-new" : "model-old",
  105. migrationSource: "claudeCode",
  106. forkedFromTaskId: "parent-task",
  107. cronAutomationId: "automation-1",
  108. offPeakTaskId: "off-peak-1",
  109. };
  110. const db = new DatabaseSync(taskDbPath);
  111. try {
  112. const row = db
  113. .prepare(`SELECT task_status, provider, mode, model, migration_source,
  114. forked_from_task_id, cron_automation_id, off_peak_task_id, meta_json
  115. FROM tasks WHERE workspace_key = ? AND task_id = 'shared-task'`)
  116. .get(canonicalKey)!;
  117. expect(JSON.parse(String(row.meta_json))).toMatchObject(expectedMeta);
  118. expect(row).toMatchObject({
  119. task_status: expectedMeta.status,
  120. provider: expectedMeta.provider,
  121. mode: expectedMeta.mode,
  122. model: expectedMeta.model,
  123. migration_source: expectedMeta.migrationSource,
  124. forked_from_task_id: expectedMeta.forkedFromTaskId,
  125. cron_automation_id: expectedMeta.cronAutomationId,
  126. off_peak_task_id: expectedMeta.offPeakTaskId,
  127. });
  128. } finally {
  129. db.close();
  130. }
  131. // 项目化索引从 cli_* 列投影标题、时间与状态;只合并旧列会让较新的 CLI 事实丢失。
  132. await expect(index.getTaskMeta(task(canonicalKey))).resolves.toMatchObject({
  133. ...expectedMeta,
  134. title: sourceWins ? "Source title" : "Shared task",
  135. createdAt: 5,
  136. updatedAt: order === "canonical-newer" ? 600 : order === "same-time" ? 100 : 500,
  137. });
  138. await expect(aliases.resolveCanonicalWorkspaceKey({ workspacePath })).resolves.toEqual({
  139. canonicalKey,
  140. mergedKeys: [],
  141. });
  142. },
  143. );
  144. // Bug 原因:旧 ACP ID 合并只抬高 updated_at、不改 cli_*,按 updated_at 选 CLI 胜者会把
  145. // 较旧的状态/标题配上较新的 cli_updated_at。CLI 事实只能按自身 cli_updated_at 裁决。
  146. it.each([
  147. ["source", sourceKey, canonicalKey],
  148. ["canonical", canonicalKey, sourceKey],
  149. ] as const)(
  150. "keeps the newer CLI facts when the legacy ACP merge inflates the %s index time",
  151. async (_side, olderKey, newerKey) => {
  152. await seed(task(newerKey, { title: "Newer title", updatedAt: 200, status: "error" }));
  153. await seed(task(olderKey, { title: "Older title", updatedAt: 100, status: "completed" }));
  154. await seed(task(olderKey, { taskId: "legacy-wrapper", updatedAt: 300 }));
  155. await restartFromPreProjectionLegacyDb(olderKey);
  156. const db = new DatabaseSync(taskDbPath);
  157. try {
  158. // 前置条件:真实启动迁移链已让较旧一侧的两种时间分叉。
  159. expect(
  160. db
  161. .prepare(
  162. "SELECT updated_at, cli_updated_at FROM tasks WHERE workspace_key = ? AND task_id = 'shared-task'",
  163. )
  164. .get(olderKey),
  165. ).toEqual({ updated_at: 300, cli_updated_at: 100 });
  166. } finally {
  167. db.close();
  168. }
  169. await aliases.resolveCanonicalWorkspaceKey({ workspacePath });
  170. await expect(index.getTaskMeta(task(canonicalKey))).resolves.toMatchObject({
  171. title: "Newer title",
  172. updatedAt: 200,
  173. status: "error",
  174. });
  175. },
  176. );
  177. it("does not let a side without CLI facts replace the other side's facts", async () => {
  178. await seed(task(canonicalKey, { title: "Canonical title", status: "error" }));
  179. await seed(task(sourceKey, { updatedAt: 500 }));
  180. const db = new DatabaseSync(taskDbPath);
  181. try {
  182. // 只有身份与组织态、尚无 CLI 事实的行,旧索引时间再新也不能清空对方的标题和状态。
  183. db.prepare(
  184. "UPDATE tasks SET cli_title = NULL, cli_title_source = NULL, cli_created_at = NULL, cli_updated_at = NULL, cli_last_outcome = NULL, cli_deleted = NULL WHERE workspace_key = ?",
  185. ).run(sourceKey);
  186. } finally {
  187. db.close();
  188. }
  189. await aliases.resolveCanonicalWorkspaceKey({ workspacePath });
  190. await expect(index.getTaskMeta(task(canonicalKey))).resolves.toMatchObject({
  191. title: "Canonical title",
  192. updatedAt: 100,
  193. status: "error",
  194. });
  195. });
  196. it("retains an older optional field when the newer metadata omits it", async () => {
  197. await seed(task(canonicalKey, { model: "retained-model" }));
  198. await seed(task(sourceKey, { updatedAt: 500 }));
  199. await aliases.resolveCanonicalWorkspaceKey({ workspacePath });
  200. await expect(index.getTaskMeta(task(canonicalKey))).resolves.toMatchObject({
  201. model: "retained-model",
  202. });
  203. const db = new DatabaseSync(taskDbPath);
  204. try {
  205. expect(
  206. db.prepare("SELECT model FROM tasks WHERE workspace_key = ?").get(canonicalKey),
  207. ).toEqual({ model: "retained-model" });
  208. } finally {
  209. db.close();
  210. }
  211. });
  212. it("preserves legacy cron and off-peak markers stored only in projection columns", async () => {
  213. await seed(task(canonicalKey));
  214. await seed(task(sourceKey, { updatedAt: 500 }));
  215. const db = new DatabaseSync(taskDbPath);
  216. try {
  217. // 旧版本回填先更新索引列,后续 snapshot 同步才补齐 meta_json。
  218. db.prepare(
  219. "UPDATE tasks SET cron_automation_id = 'legacy-auto', off_peak_task_id = 'legacy-off-peak' WHERE workspace_key = ?",
  220. ).run(sourceKey);
  221. } finally {
  222. db.close();
  223. }
  224. await aliases.resolveCanonicalWorkspaceKey({ workspacePath });
  225. await expect(index.getTaskMeta(task(canonicalKey))).resolves.toMatchObject({
  226. cronAutomationId: "legacy-auto",
  227. offPeakTaskId: "legacy-off-peak",
  228. });
  229. });
  230. it.each(["cron_automation_id", "off_peak_task_id", "forked_from_task_id"] as const)(
  231. "rejects incompatible legacy %s markers before deleting either row",
  232. async (column) => {
  233. await seed(task(canonicalKey));
  234. await seed(task(sourceKey));
  235. const db = new DatabaseSync(taskDbPath);
  236. try {
  237. const { workspaceIdentity: _identity, ...legacyMeta } = task(canonicalKey);
  238. // 两份旧 meta 相同,但索引已分别回填不同身份;相同 JSON 不能绕过身份预检。
  239. db.prepare("UPDATE tasks SET meta_json = ?").run(JSON.stringify(legacyMeta));
  240. db.prepare(`UPDATE tasks SET ${column} = ? WHERE workspace_key = ?`).run(
  241. "target-id",
  242. canonicalKey,
  243. );
  244. db.prepare(`UPDATE tasks SET ${column} = ? WHERE workspace_key = ?`).run(
  245. "source-id",
  246. sourceKey,
  247. );
  248. const before = db.prepare("SELECT * FROM tasks ORDER BY workspace_key").all();
  249. await expect(aliases.resolveCanonicalWorkspaceKey({ workspacePath })).rejects.toMatchObject(
  250. {
  251. code: "workspace-task-identity-conflict",
  252. },
  253. );
  254. expect(db.prepare("SELECT * FROM tasks ORDER BY workspace_key").all()).toEqual(before);
  255. expect(
  256. db.prepare("SELECT canonical_key FROM workspace_alias WHERE path = ?").get(workspacePath),
  257. ).toEqual({ canonical_key: canonicalKey });
  258. } finally {
  259. db.close();
  260. }
  261. },
  262. );
  263. it.each([false, true])(
  264. "preserves searchable content (canonical indexed: %s)",
  265. async (indexed) => {
  266. await seed(task(canonicalKey), indexed ? "canonicalbody" : undefined);
  267. await seed(task(sourceKey), "sourcebody");
  268. await aliases.resolveCanonicalWorkspaceKey({ workspacePath });
  269. const result = await index.queryTaskList({
  270. workspaceScopes: [{ workspacePath, workspaceIdentity: canonicalKey }],
  271. kind: "normal",
  272. search: indexed ? "canonicalbody" : "sourcebody",
  273. });
  274. expect(result.items.map((item) => item.taskId)).toEqual(["shared-task"]);
  275. const db = new DatabaseSync(taskDbPath);
  276. try {
  277. expect(
  278. db.prepare("SELECT COUNT(*) AS count FROM tasks WHERE workspace_key = ?").get(sourceKey),
  279. ).toEqual({ count: 0 });
  280. } finally {
  281. db.close();
  282. }
  283. },
  284. );
  285. it.each([
  286. [undefined, 450, 450],
  287. [500, 450, 500],
  288. [400, 450, 450],
  289. ])("retains unread markers %s / %s", async (canonicalUnread, sourceUnread, expected) => {
  290. await seed(task(canonicalKey, { unreadAt: canonicalUnread }));
  291. await seed(task(sourceKey, { unreadAt: sourceUnread }));
  292. await aliases.resolveCanonicalWorkspaceKey({ workspacePath });
  293. await expect(index.getTaskMeta(task(canonicalKey))).resolves.toMatchObject({
  294. unreadAt: expected,
  295. });
  296. const db = new DatabaseSync(taskDbPath);
  297. try {
  298. expect(
  299. db
  300. .prepare("SELECT unread_at, last_unread_at FROM tasks WHERE workspace_key = ?")
  301. .get(canonicalKey),
  302. ).toEqual({ unread_at: expected, last_unread_at: expected });
  303. } finally {
  304. db.close();
  305. }
  306. });
  307. it("keeps the source unread watermark after that marker was cleared", async () => {
  308. await seed(task(canonicalKey));
  309. await seed(task(sourceKey, { unreadAt: 450 }));
  310. await expect(
  311. index.clearTaskUnreadIfMatches({ ...task(sourceKey), expectedUnreadAt: 450 }),
  312. ).resolves.toMatchObject({ cleared: true });
  313. await aliases.resolveCanonicalWorkspaceKey({ workspacePath });
  314. const db = new DatabaseSync(taskDbPath);
  315. try {
  316. expect(
  317. db
  318. .prepare("SELECT unread_at, last_unread_at FROM tasks WHERE workspace_key = ?")
  319. .get(canonicalKey),
  320. ).toEqual({ unread_at: null, last_unread_at: 450 });
  321. } finally {
  322. db.close();
  323. }
  324. });
  325. });