workspace-hook-digest-parity.test.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. import { mkdtempSync } from "node:fs";
  2. import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { afterEach, describe, expect, it } from "vitest";
  6. import { createConfig } from "../src/config/index.js";
  7. import {
  8. buildWorkspaceHookBundleSnapshot,
  9. readWorkspaceHookProjectSources,
  10. resolveWorkspaceHookRuntimeRoot,
  11. workspaceHooksConfigSchema,
  12. type WorkspaceHooksConfig,
  13. } from "@zcode/shared/workspace-hook-discovery";
  14. const roots: string[] = [];
  15. function makeRoot(): string {
  16. const root = mkdtempSync(join(tmpdir(), "zcode-hook-runtime-parity-"));
  17. roots.push(root);
  18. return root;
  19. }
  20. async function writeJson(path: string, value: unknown): Promise<void> {
  21. await mkdir(join(path, ".."), { recursive: true });
  22. await writeFile(path, `${JSON.stringify(value, null, 2)}\n`, "utf8");
  23. }
  24. async function readJsonIfDefined(path: string): Promise<unknown | undefined> {
  25. try {
  26. return JSON.parse(await readFile(path, "utf8")) as unknown;
  27. } catch {
  28. return undefined;
  29. }
  30. }
  31. afterEach(async () => {
  32. await Promise.all(roots.splice(0).map((root) => rm(root, { force: true, recursive: true })));
  33. });
  34. /**
  35. * D17/M2 双 builder parity(Runtime 侧真实入口版):
  36. * 本测试对比的是两个**真实**装配产物——
  37. * actual:Runtime 的 createConfig(config-factory)产物 sources.project.workspaceHookSnapshot,
  38. * 层级含 DefaultRuntimeConfig.hooks / user config / project candidates / env / cli;
  39. * reference:Settings(services/hooksService.loadHooks)的装配公式镜像,
  40. * 即 runtimeRoot = resolve([user.hooks, ...project hooks])、sources = project candidates
  41. * (services 侧与 shared 都可直接调用同一批 API)。
  42. * 任何一侧的层级顺序、merge 语义、默认值变动使两道 snapshot 分叉(bundleDigest 或逐条
  43. * resolved 字段不一致),这里必须转红。此前 services 侧的 parity 测试两边都是 Settings
  44. * 逻辑的副本(Runtime 从未进入等式),改不了 Runtime 分叉;本测试补上 Runtime 真实侧。
  45. */
  46. describe("workspace hook Settings/Runtime dual builder digest parity (D17 runtime entry)", () => {
  47. it("Runtime createConfig snapshot 与 Settings 装配公式产出一致 digest", async () => {
  48. const home = makeRoot();
  49. const workspace = makeRoot();
  50. await mkdir(join(workspace, ".git"));
  51. const userConfigPath = join(home, ".zcode", "cli", "config.json");
  52. await writeJson(userConfigPath, { hooks: { enabled: true, timeoutMs: 30_000 } });
  53. await writeJson(join(workspace, "zcode.json"), {
  54. hooks: {
  55. enabled: true,
  56. events: {
  57. Stop: [
  58. {
  59. matcher: ".*",
  60. hooks: [{ type: "command", command: "echo parity-root", async: true }],
  61. },
  62. ],
  63. },
  64. },
  65. });
  66. await writeJson(join(workspace, ".zcode", "config.json"), {
  67. hooks: {
  68. enabled: true,
  69. events: {
  70. SessionStart: [
  71. { hooks: [{ type: "process", command: "node", args: ["hook.mjs"], timeoutMs: 5_000 }] },
  72. ],
  73. },
  74. },
  75. });
  76. // ── 实测侧:Runtime 真实装配(Default层/user/project 全部进入 runtimeRoot)──
  77. const result = createConfig({
  78. env: {},
  79. projectConfigPath: undefined,
  80. skipUserConfig: false,
  81. userConfigPath,
  82. workingDirectory: workspace,
  83. workspaceIdentity: workspace,
  84. });
  85. const runtimeSnapshot = result.sources.project.workspaceHookSnapshot;
  86. expect(runtimeSnapshot).toBeDefined();
  87. // ── 参照侧:Settings 装配公式(hooksService.loadHooks 的等价 shared-API 序列)──
  88. const { sources: projectSources } = await readWorkspaceHookProjectSources({
  89. workingDirectory: workspace,
  90. });
  91. expect(projectSources.length).toBeGreaterThan(0);
  92. const userFile = (await readJsonIfDefined(userConfigPath)) as { hooks?: unknown } | undefined;
  93. const parsedUser = workspaceHooksConfigSchema.safeParse(userFile?.hooks);
  94. const userHooks: WorkspaceHooksConfig | undefined = parsedUser.success
  95. ? parsedUser.data
  96. : undefined;
  97. const settingsRoot = resolveWorkspaceHookRuntimeRoot([
  98. ...(userHooks ? [userHooks] : []),
  99. ...projectSources.map((source) => source.hooks),
  100. ]);
  101. const settingsSnapshot = buildWorkspaceHookBundleSnapshot({
  102. workspaceIdentity: workspace,
  103. workspacePath: workspace,
  104. sources: projectSources,
  105. runtimeRoot: settingsRoot,
  106. });
  107. expect(settingsSnapshot).toBeDefined();
  108. expect(runtimeSnapshot?.bundleDigest).toBe(settingsSnapshot?.bundleDigest);
  109. expect(runtimeSnapshot?.hooks.map((hook) => hook.hookDeclarationDigest)).toEqual(
  110. settingsSnapshot?.hooks.map((hook) => hook.hookDeclarationDigest),
  111. );
  112. expect(runtimeSnapshot?.hooks.map((hook) => hook.resolvedTimeoutMs)).toEqual(
  113. settingsSnapshot?.hooks.map((hook) => hook.resolvedTimeoutMs),
  114. );
  115. expect(runtimeSnapshot?.hooks.map((hook) => hook.configuredEnabled)).toEqual(
  116. settingsSnapshot?.hooks.map((hook) => hook.configuredEnabled),
  117. );
  118. // user hooks.enabled=true 必须传导为 runtimeHooksEnabled=true(否则两边都静默关闭)
  119. expect(runtimeSnapshot?.hooks.every((hook) => hook.runtimeHooksEnabled)).toBe(true);
  120. });
  121. it("导出快照实际使用的 runtimeRoot,供 toggle 重建复用同一取值", async () => {
  122. // 回归:审核请求由 config-factory 遍历 default/user/project/env/cli 全部层推导
  123. // runtimeRoot,而「审核中 toggle」曾在 create-app 内按单层 runtimeConfig.hooks
  124. // 另建一份。两者只要有一项不同就产生不同 bundleDigest,toggle 被误判为
  125. // snapshot_mismatch(2026-08-10 UAT 实测)。这里锁住导出值与快照的一致性,
  126. // 使复用成为结构性约束,而不是两处推导恰好相等的巧合。
  127. const workspace = makeRoot();
  128. await writeJson(join(workspace, ".zcode", "config.json"), {
  129. hooks: {
  130. enabled: true,
  131. // 刻意偏离默认值:单层重建会退回 60_000 / 32_768,从而暴露分叉。
  132. timeoutMs: 10_000,
  133. maxOutputBytes: 65_536,
  134. events: {
  135. SessionStart: [
  136. { matcher: "startup", hooks: [{ type: "command", command: "echo parity" }] },
  137. ],
  138. },
  139. } satisfies WorkspaceHooksConfig,
  140. });
  141. const config = await createConfig({ workingDirectory: workspace });
  142. const exported = config.sources.project.workspaceHookRuntimeRoot;
  143. expect(exported).toEqual({ enabled: true, timeoutMs: 10_000, maxOutputBytes: 65_536 });
  144. // 用导出的 runtimeRoot 重建,必须复现审核快照的 bundleDigest。
  145. const { sources } = await readWorkspaceHookProjectSources({ workingDirectory: workspace });
  146. const rebuilt = buildWorkspaceHookBundleSnapshot({
  147. workspaceIdentity: workspace,
  148. workspacePath: workspace,
  149. sources,
  150. runtimeRoot: exported!,
  151. });
  152. expect(rebuilt?.bundleDigest).toBe(config.sources.project.workspaceHookSnapshot?.bundleDigest);
  153. });
  154. it("explicit path 与 auto-discovery 指向同一文件时只生成一个 source", async () => {
  155. const workspace = makeRoot();
  156. await mkdir(join(workspace, ".git"));
  157. const configPath = join(workspace, "zcode.json");
  158. await writeJson(configPath, {
  159. hooks: {
  160. enabled: true,
  161. events: {
  162. SessionStart: [{ hooks: [{ type: "command", command: "echo deduplicated" }] }],
  163. },
  164. },
  165. });
  166. const runtime = createConfig({
  167. env: {},
  168. projectConfigPath: configPath,
  169. skipUserConfig: true,
  170. workingDirectory: workspace,
  171. workspaceIdentity: workspace,
  172. }).sources.project.workspaceHookSnapshot;
  173. const { sources } = await readWorkspaceHookProjectSources({
  174. workingDirectory: workspace,
  175. explicitProjectConfigPath: configPath,
  176. });
  177. const settings = buildWorkspaceHookBundleSnapshot({
  178. workspaceIdentity: workspace,
  179. workspacePath: workspace,
  180. sources,
  181. runtimeRoot: resolveWorkspaceHookRuntimeRoot(sources.map((source) => source.hooks)),
  182. });
  183. expect(runtime?.sourceFiles).toHaveLength(1);
  184. expect(runtime?.sourceFiles[0]).toMatchObject({
  185. canonicalPath: configPath,
  186. discoveryOrder: 0,
  187. explicitProjectConfig: false,
  188. });
  189. expect(runtime?.bundleDigest).toBe(settings?.bundleDigest);
  190. });
  191. it("损坏候选仍占 discoveryOrder,后续 source 的 Runtime/Settings digest 不错位", async () => {
  192. const workspace = makeRoot();
  193. await mkdir(join(workspace, ".git"));
  194. await writeFile(join(workspace, "zcode.json"), "{broken", "utf8");
  195. await writeJson(join(workspace, ".zcode", "config.json"), {
  196. hooks: {
  197. enabled: true,
  198. events: {
  199. Stop: [{ hooks: [{ type: "command", command: "echo valid-after-broken" }] }],
  200. },
  201. },
  202. });
  203. const explicitPath = join(workspace, "explicit-hooks.json");
  204. await writeJson(explicitPath, {
  205. hooks: {
  206. enabled: true,
  207. events: {
  208. UserPromptSubmit: [{ hooks: [{ type: "command", command: "echo explicit" }] }],
  209. },
  210. },
  211. });
  212. const runtime = createConfig({
  213. env: {},
  214. projectConfigPath: explicitPath,
  215. skipUserConfig: true,
  216. workingDirectory: workspace,
  217. workspaceIdentity: workspace,
  218. }).sources.project.workspaceHookSnapshot;
  219. const { sources } = await readWorkspaceHookProjectSources({
  220. workingDirectory: workspace,
  221. explicitProjectConfigPath: explicitPath,
  222. });
  223. const settings = buildWorkspaceHookBundleSnapshot({
  224. workspaceIdentity: workspace,
  225. workspacePath: workspace,
  226. sources,
  227. runtimeRoot: resolveWorkspaceHookRuntimeRoot(sources.map((source) => source.hooks)),
  228. });
  229. expect(runtime?.sourceFiles.map((source) => source.discoveryOrder)).toEqual([1, 2]);
  230. expect(settings?.sourceFiles.map((source) => source.discoveryOrder)).toEqual([1, 2]);
  231. expect(runtime?.bundleDigest).toBe(settings?.bundleDigest);
  232. });
  233. });