workspaceHookMutation.test.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
  2. import { readdir, rm } from "node:fs/promises";
  3. import { join } from "node:path";
  4. import { tmpdir } from "node:os";
  5. import { afterEach, describe, expect, it } from "vitest";
  6. import {
  7. buildWorkspaceHookBundleSnapshot,
  8. createWorkspaceHookSourceInput,
  9. } from "../src/workspace-hook-discovery.js";
  10. import {
  11. atomicWriteWorkspaceHookConfig,
  12. writeWorkspaceHookConfiguredToggle,
  13. } from "../src/workspace-hook-mutation.js";
  14. const roots: string[] = [];
  15. function makeRoot(): string {
  16. const root = mkdtempSync(join(tmpdir(), "workspace-hook-mutation-"));
  17. roots.push(root);
  18. return root;
  19. }
  20. function writeJson(path: string, value: unknown): void {
  21. mkdirSync(join(path, ".."), { recursive: true });
  22. writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`, "utf8");
  23. }
  24. afterEach(async () => {
  25. await Promise.all(roots.splice(0).map((root) => rm(root, { force: true, recursive: true })));
  26. });
  27. describe("workspace Hook atomic mutation", () => {
  28. it("只改变 snapshot 指向 declaration 的 enabled gate,并保留其他 config 与 passthrough 字段", async () => {
  29. const workspace = makeRoot();
  30. const configPath = join(workspace, ".zcode", "config.json");
  31. const original = {
  32. model: "model-test",
  33. customTopLevel: { keep: true },
  34. hooks: {
  35. enabled: true,
  36. timeoutMs: 1234,
  37. events: {
  38. SessionStart: [
  39. {
  40. hooks: [
  41. {
  42. type: "command",
  43. command: "echo first",
  44. enabled: true,
  45. customHookField: { keep: "yes" },
  46. },
  47. {
  48. type: "process",
  49. command: "node",
  50. args: ["second.mjs"],
  51. enabled: true,
  52. },
  53. ],
  54. },
  55. ],
  56. },
  57. },
  58. };
  59. writeJson(configPath, original);
  60. const source = createWorkspaceHookSourceInput({
  61. path: configPath,
  62. workingDirectory: workspace,
  63. hooks: original.hooks,
  64. discoveryOrder: 0,
  65. explicitProjectConfig: false,
  66. });
  67. const snapshot = buildWorkspaceHookBundleSnapshot({
  68. workspaceIdentity: "workspace:test",
  69. workspacePath: workspace,
  70. sources: [source],
  71. runtimeRoot: { enabled: true, timeoutMs: 60_000, maxOutputBytes: 32_768 },
  72. });
  73. await writeWorkspaceHookConfiguredToggle({
  74. configPath,
  75. snapshot,
  76. reviewItemId: snapshot.hooks[1]!.reviewItemId,
  77. enabled: false,
  78. });
  79. const saved = JSON.parse(readFileSync(configPath, "utf8"));
  80. expect(saved).toEqual({
  81. ...original,
  82. hooks: {
  83. ...original.hooks,
  84. events: {
  85. SessionStart: [
  86. {
  87. hooks: [
  88. original.hooks.events.SessionStart[0]!.hooks[0],
  89. {
  90. ...original.hooks.events.SessionStart[0]!.hooks[1],
  91. enabled: false,
  92. },
  93. ],
  94. },
  95. ],
  96. },
  97. },
  98. });
  99. });
  100. it("拒绝 snapshot 中非当前 .zcode/config.json 或非 editable declaration,且不写文件", async () => {
  101. const workspace = makeRoot();
  102. const configPath = join(workspace, ".zcode", "config.json");
  103. const ancestorPath = join(workspace, "zcode.json");
  104. const config = {
  105. hooks: {
  106. enabled: true,
  107. events: {
  108. Stop: [{ hooks: [{ type: "command" as const, command: "echo readonly" }] }],
  109. },
  110. },
  111. };
  112. writeJson(ancestorPath, config);
  113. writeJson(configPath, { hooks: { enabled: true, events: {} } });
  114. const source = createWorkspaceHookSourceInput({
  115. path: ancestorPath,
  116. workingDirectory: workspace,
  117. hooks: config.hooks,
  118. discoveryOrder: 0,
  119. explicitProjectConfig: false,
  120. });
  121. const snapshot = buildWorkspaceHookBundleSnapshot({
  122. workspaceIdentity: "workspace:test",
  123. workspacePath: workspace,
  124. sources: [source],
  125. runtimeRoot: { enabled: true, timeoutMs: 60_000, maxOutputBytes: 32_768 },
  126. });
  127. const before = readFileSync(configPath, "utf8");
  128. await expect(
  129. writeWorkspaceHookConfiguredToggle({
  130. configPath,
  131. snapshot,
  132. reviewItemId: snapshot.hooks[0]!.reviewItemId,
  133. enabled: false,
  134. }),
  135. ).rejects.toMatchObject({ code: "workspace_hooks_snapshot_mismatch" });
  136. expect(readFileSync(configPath, "utf8")).toBe(before);
  137. });
  138. it("磁盘 declaration 已变化时拒绝批准 A/修改 B", async () => {
  139. const workspace = makeRoot();
  140. const configPath = join(workspace, ".zcode", "config.json");
  141. const hooks = {
  142. enabled: true,
  143. events: {
  144. Stop: [{ hooks: [{ type: "command" as const, command: "echo before" }] }],
  145. },
  146. };
  147. writeJson(configPath, { hooks });
  148. const source = createWorkspaceHookSourceInput({
  149. path: configPath,
  150. workingDirectory: workspace,
  151. hooks,
  152. discoveryOrder: 0,
  153. explicitProjectConfig: false,
  154. });
  155. const snapshot = buildWorkspaceHookBundleSnapshot({
  156. workspaceIdentity: "workspace:test",
  157. workspacePath: workspace,
  158. sources: [source],
  159. runtimeRoot: { enabled: true, timeoutMs: 60_000, maxOutputBytes: 32_768 },
  160. });
  161. writeJson(configPath, {
  162. hooks: {
  163. ...hooks,
  164. events: {
  165. Stop: [{ hooks: [{ type: "command", command: "echo changed" }] }],
  166. },
  167. },
  168. });
  169. await expect(
  170. writeWorkspaceHookConfiguredToggle({
  171. configPath,
  172. snapshot,
  173. reviewItemId: snapshot.hooks[0]!.reviewItemId,
  174. enabled: false,
  175. }),
  176. ).rejects.toMatchObject({ code: "workspace_hooks_snapshot_mismatch" });
  177. expect(readFileSync(configPath, "utf8")).toContain("echo changed");
  178. });
  179. it("已知边界:root default 变化不触发 declaration mismatch(admission 侧仍按当前 snapshot 评估)", async () => {
  180. const workspace = makeRoot();
  181. const configPath = join(workspace, ".zcode", "config.json");
  182. const hooks = {
  183. enabled: true,
  184. timeoutMs: 5000,
  185. events: {
  186. Stop: [{ hooks: [{ type: "command" as const, command: "echo boundary" }] }],
  187. },
  188. };
  189. writeJson(configPath, { hooks });
  190. const source = createWorkspaceHookSourceInput({
  191. path: configPath,
  192. workingDirectory: workspace,
  193. hooks,
  194. discoveryOrder: 0,
  195. explicitProjectConfig: false,
  196. });
  197. const snapshot = buildWorkspaceHookBundleSnapshot({
  198. workspaceIdentity: "workspace:test",
  199. workspacePath: workspace,
  200. sources: [source],
  201. runtimeRoot: { enabled: true, timeoutMs: 5000, maxOutputBytes: 32_768 },
  202. });
  203. // 磁盘上仅修改 root 级 hooks.timeoutMs,不触碰 declaration 本体。
  204. writeJson(configPath, {
  205. hooks: { ...hooks, timeoutMs: 99_999 },
  206. });
  207. // 该守卫把 entry.resolvedTimeoutMs(review 时解析到的旧值)回填为 digest 的 default,
  208. // 因此重算 digest 必然与 entry.hookDeclarationDigest 相等——root default 变化不被捕获。
  209. // 这是有意的已知边界,此处 LOCK 以防回归时误改。
  210. await expect(
  211. writeWorkspaceHookConfiguredToggle({
  212. configPath,
  213. snapshot,
  214. reviewItemId: snapshot.hooks[0]!.reviewItemId,
  215. enabled: false,
  216. }),
  217. ).resolves.toBeUndefined();
  218. const saved = JSON.parse(readFileSync(configPath, "utf8"));
  219. expect(saved.hooks.timeoutMs).toBe(99_999);
  220. expect(saved.hooks.events.Stop[0]!.hooks[0]!.enabled).toBe(false);
  221. });
  222. it("rename 前失败保留原文件并清理 temp file", async () => {
  223. const workspace = makeRoot();
  224. const configPath = join(workspace, ".zcode", "config.json");
  225. writeJson(configPath, { hooks: { enabled: false, events: {} } });
  226. await expect(
  227. atomicWriteWorkspaceHookConfig(
  228. configPath,
  229. { hooks: { enabled: true, events: {} } },
  230. {
  231. beforeRename() {
  232. throw new Error("injected failure");
  233. },
  234. },
  235. ),
  236. ).rejects.toThrow("injected failure");
  237. expect(JSON.parse(readFileSync(configPath, "utf8"))).toEqual({
  238. hooks: { enabled: false, events: {} },
  239. });
  240. await expect(readdir(join(workspace, ".zcode"))).resolves.toEqual(["config.json"]);
  241. });
  242. });