taskIndexRepoOffPeakMarker.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. // D48 一等行打点:offPeakTaskId 作为持久 task meta 字段的仓库契约(MR1,无 UI 行为变化)。
  2. // 镜像 cronAutomationId 的三条不变量:meta_json 为准 + 索引列兜底、运行态快照不带标记时
  3. // 保全已有值、bootstrap 幂等回填存量 off-peak 会话。
  4. import { mkdtempSync, rmSync } from "node:fs";
  5. import { tmpdir } from "node:os";
  6. import { join } from "node:path";
  7. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  8. import type { ZCodeTaskMeta } from "@zcode/shared";
  9. import { setDataBaseDir } from "#src/paths.js";
  10. import { TaskIndexRepo } from "#src/session/taskIndexRepo.js";
  11. import { OffPeakTaskRepo } from "#src/session/offPeakTaskRepo.js";
  12. let repo: TaskIndexRepo;
  13. let tempDir: string;
  14. beforeEach(() => {
  15. tempDir = mkdtempSync(join(tmpdir(), "zcode-task-index-off-peak-marker-"));
  16. setDataBaseDir(tempDir);
  17. repo = new TaskIndexRepo();
  18. });
  19. afterEach(async () => {
  20. repo.close();
  21. setDataBaseDir(null);
  22. // Windows 需要等待 SQLite 释放文件句柄,避免临时目录清理出现 EPERM。
  23. await new Promise((resolve) => setTimeout(resolve, 50));
  24. rmSync(tempDir, { recursive: true, force: true });
  25. });
  26. function task(params: { taskId: string; offPeakTaskId?: string }): ZCodeTaskMeta {
  27. return {
  28. taskId: params.taskId,
  29. traceId: `trace-${params.taskId}`,
  30. title: params.taskId,
  31. workspacePath: "/workspace/project",
  32. createdAt: 10,
  33. updatedAt: 20,
  34. mode: "default",
  35. status: "running",
  36. ...(params.offPeakTaskId ? { offPeakTaskId: params.offPeakTaskId } : {}),
  37. };
  38. }
  39. function getRepoDatabase(target: TaskIndexRepo): {
  40. prepare(sql: string): {
  41. run(...params: unknown[]): unknown;
  42. get(...params: unknown[]): unknown;
  43. };
  44. } {
  45. return (
  46. target as unknown as {
  47. getDatabase(): {
  48. prepare(sql: string): {
  49. run(...params: unknown[]): unknown;
  50. get(...params: unknown[]): unknown;
  51. };
  52. };
  53. }
  54. ).getDatabase();
  55. }
  56. describe("TaskIndexRepo off-peak marker (D48)", () => {
  57. it("syncTaskMeta 持久化 offPeakTaskId 并投影到索引列", async () => {
  58. await repo.syncTaskMeta({ meta: task({ taskId: "s-1", offPeakTaskId: "offpeak-1" }) });
  59. const meta = await repo.getTaskMeta({
  60. workspacePath: "/workspace/project",
  61. taskId: "s-1",
  62. });
  63. expect(meta?.offPeakTaskId).toBe("offpeak-1");
  64. const row = getRepoDatabase(repo)
  65. .prepare(`SELECT off_peak_task_id FROM tasks WHERE task_id = ?`)
  66. .get("s-1") as { off_peak_task_id: string | null };
  67. expect(row.off_peak_task_id).toBe("offpeak-1");
  68. });
  69. it("运行态快照不带标记时保全已有 offPeakTaskId", async () => {
  70. await repo.syncTaskMeta({ meta: task({ taskId: "s-2", offPeakTaskId: "offpeak-2" }) });
  71. // 运行态 protocol snapshot 的 meta 不携带 off-peak 标记;同步不得把归属冲掉。
  72. await repo.syncTaskMeta({ meta: task({ taskId: "s-2" }) });
  73. const meta = await repo.getTaskMeta({
  74. workspacePath: "/workspace/project",
  75. taskId: "s-2",
  76. });
  77. expect(meta?.offPeakTaskId).toBe("offpeak-2");
  78. });
  79. it("meta_json 缺字段时以索引列兜底(backfill 只写列即可生效)", async () => {
  80. await repo.syncTaskMeta({ meta: task({ taskId: "s-3" }) });
  81. getRepoDatabase(repo)
  82. .prepare(`UPDATE tasks SET off_peak_task_id = ? WHERE task_id = ?`)
  83. .run("offpeak-3", "s-3");
  84. const meta = await repo.getTaskMeta({
  85. workspacePath: "/workspace/project",
  86. taskId: "s-3",
  87. });
  88. expect(meta?.offPeakTaskId).toBe("offpeak-3");
  89. });
  90. it("bootstrap 幂等回填存量 off-peak 会话的标记", async () => {
  91. // 存量形态:off_peak_tasks 已绑定 session,但 tasks 行诞生于打点之前、无标记。
  92. // 先做一次 repo 操作触发懒初始化,getRepoDatabase 才能拿到句柄。
  93. await repo.syncTaskMeta({ meta: task({ taskId: "s-legacy" }) });
  94. const offPeakRepo = new OffPeakTaskRepo();
  95. await offPeakRepo.create(
  96. {
  97. title: "legacy",
  98. prompt: "legacy",
  99. permissionMode: "build",
  100. workspacePath: "/workspace/project",
  101. modelSelection: { providerId: "account:zai-offpeak-idle-plan", modelId: "GLM-5.2" },
  102. },
  103. { offPeakTaskId: "offpeak-legacy" },
  104. );
  105. getRepoDatabase(repo)
  106. .prepare(`UPDATE off_peak_tasks SET session_id = ? WHERE off_peak_task_id = ?`)
  107. .run("s-legacy", "offpeak-legacy");
  108. getRepoDatabase(repo)
  109. .prepare(`UPDATE tasks SET off_peak_task_id = NULL WHERE task_id = ?`)
  110. .run("s-legacy");
  111. repo.close();
  112. // 重新 bootstrap(等价于升级后首次启动):回填必须命中且可重复执行。
  113. repo = new TaskIndexRepo();
  114. const meta = await repo.getTaskMeta({
  115. workspacePath: "/workspace/project",
  116. taskId: "s-legacy",
  117. });
  118. expect(meta?.offPeakTaskId).toBe("offpeak-legacy");
  119. offPeakRepo.close();
  120. });
  121. it("回填不覆盖已有标记且对无关任务无副作用", async () => {
  122. // 已有显式标记的任务(值不同)与普通任务都不得被回填改写。
  123. await repo.syncTaskMeta({ meta: task({ taskId: "s-4", offPeakTaskId: "offpeak-explicit" }) });
  124. await repo.syncTaskMeta({ meta: task({ taskId: "s-plain" }) });
  125. const offPeakRepo = new OffPeakTaskRepo();
  126. await offPeakRepo.create(
  127. {
  128. title: "other",
  129. prompt: "other",
  130. permissionMode: "build",
  131. workspacePath: "/workspace/project",
  132. modelSelection: { providerId: "account:zai-offpeak-idle-plan", modelId: "GLM-5.2" },
  133. },
  134. { offPeakTaskId: "offpeak-other" },
  135. );
  136. getRepoDatabase(repo)
  137. .prepare(`UPDATE off_peak_tasks SET session_id = ? WHERE off_peak_task_id = ?`)
  138. .run("s-4", "offpeak-other");
  139. repo.close();
  140. repo = new TaskIndexRepo();
  141. const explicit = await repo.getTaskMeta({
  142. workspacePath: "/workspace/project",
  143. taskId: "s-4",
  144. });
  145. expect(explicit?.offPeakTaskId).toBe("offpeak-explicit");
  146. const plain = await repo.getTaskMeta({
  147. workspacePath: "/workspace/project",
  148. taskId: "s-plain",
  149. });
  150. expect(plain?.offPeakTaskId).toBeUndefined();
  151. offPeakRepo.close();
  152. });
  153. });
  154. // D48-A:首次获得标记时归入闲时系统分组(照抄 ensureCronGroupMembership),
  155. // 以及 bootstrap 对 MR1 列回填存量的成员关系补齐。
  156. describe("TaskIndexRepo off-peak group membership (D48-A)", () => {
  157. const OFF_PEAK_GROUP_ID = "zcode-default-group-off-peak";
  158. function membershipRow(taskId: string): { group_id: string } | undefined {
  159. return getRepoDatabase(repo)
  160. .prepare(`SELECT group_id FROM task_group_members WHERE task_id = ?`)
  161. .get(taskId) as { group_id: string } | undefined;
  162. }
  163. it("首次获得标记时写入分组行、顶层排序与成员关系", async () => {
  164. await repo.syncTaskMeta({ meta: task({ taskId: "m-1", offPeakTaskId: "offpeak-m1" }) });
  165. const group = getRepoDatabase(repo)
  166. .prepare(`SELECT group_id, title, color FROM task_groups WHERE group_id = ?`)
  167. .get(OFF_PEAK_GROUP_ID) as { title: string; color: string } | undefined;
  168. expect(group?.title).toBe("off-peak");
  169. expect(group?.color).toBe("purple");
  170. expect(membershipRow("m-1")?.group_id).toBe(OFF_PEAK_GROUP_ID);
  171. const order = getRepoDatabase(repo)
  172. .prepare(
  173. `SELECT node_key FROM task_group_view_node_orders WHERE node_type = 'group' AND node_key = ?`,
  174. )
  175. .get(OFF_PEAK_GROUP_ID);
  176. expect(order).toBeTruthy();
  177. });
  178. it("用户已手动分组的任务不被拖回闲时组", async () => {
  179. await repo.syncTaskMeta({ meta: task({ taskId: "m-2" }) });
  180. getRepoDatabase(repo)
  181. .prepare(
  182. `INSERT INTO task_groups (group_id, title, color, created_at, updated_at)
  183. VALUES ('custom-group', 'Custom', 'green', 1, 1)`,
  184. )
  185. .run();
  186. getRepoDatabase(repo)
  187. .prepare(
  188. `INSERT INTO task_group_members (
  189. group_id, workspace_key, workspace_path, workspace_identity, task_id,
  190. sort_order, added_at, created_at, updated_at
  191. ) VALUES ('custom-group', '/workspace/project', '/workspace/project', NULL, 'm-2', NULL, 1, 1, 1)`,
  192. )
  193. .run();
  194. // 首次获得标记:OR IGNORE 不得覆盖用户手动整理的成员关系。
  195. await repo.syncTaskMeta({ meta: task({ taskId: "m-2", offPeakTaskId: "offpeak-m2" }) });
  196. expect(membershipRow("m-2")?.group_id).toBe("custom-group");
  197. });
  198. it("bootstrap 为 MR1 列回填的存量标记行补成员关系", async () => {
  199. // 存量形态:标记只在投影列(MR1 回填),meta_json 无字段、成员关系从未写入。
  200. await repo.syncTaskMeta({ meta: task({ taskId: "m-3" }) });
  201. getRepoDatabase(repo)
  202. .prepare(`UPDATE tasks SET off_peak_task_id = ? WHERE task_id = ?`)
  203. .run("offpeak-m3", "m-3");
  204. expect(membershipRow("m-3")).toBeUndefined();
  205. repo.close();
  206. repo = new TaskIndexRepo();
  207. await repo.getTaskMeta({ workspacePath: "/workspace/project", taskId: "m-3" });
  208. expect(membershipRow("m-3")?.group_id).toBe(OFF_PEAK_GROUP_ID);
  209. });
  210. it("远程 workspace 存量行不回填成员关系(暂不支持远程闲时任务)", async () => {
  211. // CR-01 场景:存量远程行 workspace_key 已是远端 identity,但 workspace_identity
  212. // 列缺失。若回填不跳过,会用 workspacePath 重算出本地 key 造成成员关系串写。
  213. const remoteKey = "remote:ssh:10.0.0.8:2222:dev:/workspace/project";
  214. await repo.syncTaskMeta({ meta: task({ taskId: "m-remote" }) });
  215. getRepoDatabase(repo)
  216. .prepare(
  217. `UPDATE tasks SET workspace_key = ?, workspace_identity = NULL, off_peak_task_id = ?
  218. WHERE task_id = ?`,
  219. )
  220. .run(remoteKey, "offpeak-remote", "m-remote");
  221. repo.close();
  222. repo = new TaskIndexRepo();
  223. // 触发懒初始化让 bootstrap 回填跑完;断言既无远端 key 成员,也无串写的本地 key 成员。
  224. await repo.getTaskMeta({ workspacePath: "/workspace/project", taskId: "m-remote" });
  225. expect(membershipRow("m-remote")).toBeUndefined();
  226. });
  227. it("远程 workspace 会话首次获得标记也不归组(暂不支持远程闲时任务)", async () => {
  228. await repo.syncTaskMeta({
  229. meta: {
  230. ...task({ taskId: "m-remote-sync", offPeakTaskId: "offpeak-remote-sync" }),
  231. workspaceIdentity: "remote:ssh:10.0.0.8:2222:dev:/workspace/project",
  232. },
  233. });
  234. expect(membershipRow("m-remote-sync")).toBeUndefined();
  235. });
  236. });