workspaceHookDiscoveryAlignment.test.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import { createHooksService } from "../src/hooks/hooksService.js";
  6. import { atomicWriteWorkspaceHookConfig } from "../src/hooks/workspaceHookConfigMutation.js";
  7. const roots: string[] = [];
  8. function makeRoot(): string {
  9. const root = mkdtempSync(join(tmpdir(), "zcode-hook-settings-phase1-"));
  10. roots.push(root);
  11. return root;
  12. }
  13. function writeJson(path: string, value: unknown): void {
  14. mkdirSync(join(path, ".."), { recursive: true });
  15. writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`, "utf8");
  16. }
  17. afterEach(async () => {
  18. const { rm } = await import("node:fs/promises");
  19. await Promise.all(roots.splice(0).map((root) => rm(root, { force: true, recursive: true })));
  20. vi.unstubAllEnvs();
  21. });
  22. describe("workspace hook Settings/Runtime discovery alignment", () => {
  23. it("无 task 的 Settings Trust 只向注入的 workspace authority 转发精确目标", async () => {
  24. const grantWorkspaceHookTrust = vi.fn(async () => ({ accepted: true }));
  25. const service = createHooksService({ grantWorkspaceHookTrust });
  26. const target = {
  27. workspacePath: "/repo",
  28. workspaceIdentity: "remote:ssh:host:/repo",
  29. bundleDigest: "b".repeat(64),
  30. hookDeclarationDigest: "a".repeat(64),
  31. };
  32. await expect(service.grantWorkspaceHookTrust?.(target)).resolves.toEqual({ accepted: true });
  33. expect(grantWorkspaceHookTrust).toHaveBeenCalledWith(target);
  34. });
  35. it("Settings 使用权威 snapshot,祖先/zcode.json 只读且 compatibility rows 不进入 snapshot", async () => {
  36. const home = makeRoot();
  37. const repo = join(makeRoot(), "repo");
  38. const workspace = join(repo, "packages", "app");
  39. mkdirSync(join(repo, ".git"), { recursive: true });
  40. mkdirSync(workspace, { recursive: true });
  41. writeJson(join(repo, "zcode.json"), {
  42. hooks: {
  43. enabled: true,
  44. events: {
  45. Stop: [{ hooks: [{ type: "command", command: "echo zcode-json" }] }],
  46. },
  47. },
  48. });
  49. writeJson(join(workspace, ".zcode", "config.json"), {
  50. hooks: {
  51. enabled: true,
  52. events: {
  53. SessionStart: [
  54. {
  55. hooks: [{ type: "process", command: "node", args: ["hook.mjs"] }],
  56. },
  57. ],
  58. },
  59. },
  60. });
  61. writeJson(join(workspace, ".agents", "settings.json"), {
  62. hooks: {
  63. Stop: [{ hooks: [{ type: "command", command: "echo agents" }] }],
  64. },
  65. });
  66. vi.stubEnv("HOME", home);
  67. vi.stubEnv("USERPROFILE", home);
  68. const loaded = await createHooksService().loadHooks({
  69. workspacePath: workspace,
  70. workspaceIdentity: "workspace:settings-test",
  71. });
  72. expect(loaded.workspaceHookSnapshot?.workspaceIdentity).toBe("workspace:settings-test");
  73. expect(loaded.workspaceHookSnapshot?.hooks).toHaveLength(2);
  74. expect(loaded.workspaceHookSnapshot?.sourceFiles.map((source) => source.editable)).toEqual([
  75. false,
  76. true,
  77. ]);
  78. const projectZCodeHooks = loaded.hooks.filter(
  79. (hook) => hook.location?.source === "zcode" && hook.location.scope === "project",
  80. );
  81. expect(projectZCodeHooks).toHaveLength(2);
  82. expect(projectZCodeHooks.map((hook) => hook.editable)).toEqual([false, true]);
  83. expect(projectZCodeHooks.every((hook) => Boolean(hook.workspaceHook))).toBe(true);
  84. const compatibility = loaded.hooks.find((hook) => hook.location?.source === "agents");
  85. expect(compatibility).toMatchObject({ enabled: false, editable: false });
  86. expect(compatibility?.workspaceHook).toBeUndefined();
  87. await createHooksService().saveHooks({
  88. workspacePath: workspace,
  89. hooks: loaded.hooks,
  90. });
  91. const savedCurrent = JSON.parse(readFileSync(join(workspace, ".zcode", "config.json"), "utf8"));
  92. expect(savedCurrent.hooks.events.SessionStart).toHaveLength(1);
  93. expect(savedCurrent.hooks.events.Stop).toBeUndefined();
  94. expect(readFileSync(join(repo, "zcode.json"), "utf8")).toContain("echo zcode-json");
  95. });
  96. it("Settings 只读 discovery 叠加 exact persistent Trust record", async () => {
  97. const home = makeRoot();
  98. const workspace = makeRoot();
  99. mkdirSync(join(workspace, ".git"));
  100. writeJson(join(home, ".zcode", "cli", "config.json"), {
  101. hooks: { enabled: true },
  102. });
  103. writeJson(join(workspace, ".zcode", "config.json"), {
  104. hooks: {
  105. enabled: true,
  106. events: {
  107. Stop: [{ hooks: [{ type: "command", command: "echo trust" }] }],
  108. },
  109. },
  110. });
  111. vi.stubEnv("HOME", home);
  112. vi.stubEnv("USERPROFILE", home);
  113. const first = await createHooksService().loadHooks({
  114. workspacePath: workspace,
  115. });
  116. const digest = first.workspaceHookSnapshot?.hooks[0]?.hookDeclarationDigest;
  117. if (!digest) throw new Error("expected declaration digest");
  118. // 修复原因:CR-01 后 trust store 使用完整 strict schema(单源在 shared 的
  119. // workspace-hook-trust-store-file.ts),record 必须包含全部必填字段;旧用例只写
  120. // identity+digest 恰好依赖了被修复的局部校验 bug,会被 fail-closed 判为 invalid。
  121. writeJson(join(home, ".zcode", "security", "workspace-hook-trust-v1.json"), {
  122. schemaVersion: 1,
  123. records: [
  124. {
  125. workspaceIdentity: workspace,
  126. hookDeclarationDigest: digest,
  127. digestAlgorithm: "sha256",
  128. decision: "trusted",
  129. grantedAt: "2026-08-17T09:00:00.000Z",
  130. eventAtGrant: "Stop",
  131. displayCommandAtGrant: "echo trust",
  132. sourcePathAtGrant: ".zcode/config.json",
  133. },
  134. ],
  135. });
  136. const trusted = await createHooksService().loadHooks({
  137. workspacePath: workspace,
  138. });
  139. expect(trusted.hooks[0]?.workspaceHook?.trustState).toBe("trusted_persistent");
  140. });
  141. it("hooks.enabled 缺省暴露 source/runtime/configured 三层 gate,不由 hooksService 自行猜测", async () => {
  142. const home = makeRoot();
  143. const workspace = makeRoot();
  144. mkdirSync(join(workspace, ".git"));
  145. writeJson(join(workspace, ".zcode", "config.json"), {
  146. hooks: {
  147. events: {
  148. SessionStart: [{ hooks: [{ type: "command", command: "echo missing-enabled" }] }],
  149. },
  150. },
  151. });
  152. vi.stubEnv("HOME", home);
  153. vi.stubEnv("USERPROFILE", home);
  154. const service = createHooksService();
  155. const disabled = await service.loadHooks({ workspacePath: workspace });
  156. expect(disabled.hooks[0]).toMatchObject({
  157. enabled: false,
  158. workspaceHook: {
  159. sourceRootEnabled: true,
  160. declarationEnabled: true,
  161. runtimeHooksEnabled: false,
  162. configuredEnabled: false,
  163. },
  164. });
  165. writeJson(join(home, ".zcode", "cli", "config.json"), {
  166. hooks: { enabled: true, events: {} },
  167. });
  168. const enabled = await service.loadHooks({ workspacePath: workspace });
  169. const projectHook = enabled.hooks.find((hook) => hook.location?.scope === "project");
  170. expect(projectHook).toMatchObject({
  171. enabled: true,
  172. workspaceHook: {
  173. sourceRootEnabled: true,
  174. declarationEnabled: true,
  175. runtimeHooksEnabled: true,
  176. configuredEnabled: true,
  177. },
  178. });
  179. });
  180. });
  181. describe("workspace hook config atomic mutation", () => {
  182. it("temp file flush/close 后 atomic rename 成功提交完整 JSON", async () => {
  183. const root = makeRoot();
  184. const path = join(root, ".zcode", "config.json");
  185. await atomicWriteWorkspaceHookConfig(path, {
  186. hooks: { enabled: true, events: {} },
  187. });
  188. expect(JSON.parse(readFileSync(path, "utf8"))).toEqual({
  189. hooks: { enabled: true, events: {} },
  190. });
  191. });
  192. it("rename 前失败时保留原文件且清理 temp file", async () => {
  193. const root = makeRoot();
  194. const path = join(root, ".zcode", "config.json");
  195. writeJson(path, { hooks: { enabled: false, events: {} } });
  196. await expect(
  197. atomicWriteWorkspaceHookConfig(
  198. path,
  199. { hooks: { enabled: true, events: {} } },
  200. {
  201. beforeRename() {
  202. throw new Error("injected failure");
  203. },
  204. },
  205. ),
  206. ).rejects.toThrow("injected failure");
  207. expect(JSON.parse(readFileSync(path, "utf8"))).toEqual({
  208. hooks: { enabled: false, events: {} },
  209. });
  210. const entries = (await import("node:fs/promises")).readdir(join(root, ".zcode"));
  211. await expect(entries).resolves.toEqual(["config.json"]);
  212. });
  213. });