workspaceHookDigestParity.test.ts 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
  2. import { readFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { dirname, join } from "node:path";
  5. import { afterEach, describe, expect, it, vi } from "vitest";
  6. import { createHooksService } from "../src/hooks/hooksService.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-digest-parity-"));
  17. roots.push(root);
  18. return root;
  19. }
  20. function writeJson(path: string, value: unknown): void {
  21. mkdirSync(dirname(path), { recursive: true });
  22. writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`, "utf8");
  23. }
  24. async function parseJsonIfExists(path: string): Promise<unknown | undefined> {
  25. if (!existsSync(path)) return undefined;
  26. return JSON.parse(await readFile(path, "utf8")) as unknown;
  27. }
  28. afterEach(async () => {
  29. await Promise.all(
  30. roots
  31. .splice(0)
  32. .map((root) =>
  33. import("node:fs/promises").then(({ rm }) => rm(root, { force: true, recursive: true })),
  34. ),
  35. );
  36. vi.unstubAllEnvs();
  37. });
  38. /**
  39. * D17/M1 digest parity 哨兵(Settings 侧自一致校验):
  40. * 比较的是 Settings builder(hooksService.loadHooks)与其装配公式的 shared-API 镜像,
  41. * 锁定 hooksService 内部装配与 shared 公开 API 的一致性(防内部漂移)。
  42. * 注意:本测试**不覆盖 Runtime(config-factory)装配**——Runtime 入口的 parity 由
  43. * adapters 侧 tests/workspace-hook-digest-parity.test.ts 用真实 createConfig 产物对比,
  44. * 双 builder 分叉由那边负责转红;两处测试配套,改名/删除任一侧都必须同步另一侧。
  45. * 若 env/CLI 未来支持 hooks 或 OR-merge 语义变动导致双 builder 分叉,adapters 侧转红。
  46. */
  47. describe("workspace hook dual builder digest parity (D17)", () => {
  48. it("hooksService snapshot 与 shared 装配规则镜像产出一致 digest", async () => {
  49. const home = makeRoot();
  50. const workspace = makeRoot();
  51. mkdirSync(join(workspace, ".git"), { recursive: true });
  52. writeJson(join(home, ".zcode", "cli", "config.json"), {
  53. hooks: { enabled: true, timeoutMs: 30_000 },
  54. });
  55. writeJson(join(workspace, "zcode.json"), {
  56. hooks: {
  57. enabled: true,
  58. events: {
  59. Stop: [
  60. {
  61. matcher: ".*",
  62. hooks: [{ type: "command", command: "echo parity-root", async: true }],
  63. },
  64. ],
  65. },
  66. },
  67. });
  68. writeJson(join(workspace, ".zcode", "config.json"), {
  69. hooks: {
  70. enabled: true,
  71. events: {
  72. SessionStart: [
  73. { hooks: [{ type: "process", command: "node", args: ["hook.mjs"], timeoutMs: 5_000 }] },
  74. ],
  75. },
  76. },
  77. });
  78. vi.stubEnv("HOME", home);
  79. vi.stubEnv("USERPROFILE", home);
  80. // ── 参照侧:镜像 loadHooksImpl 的装配(project sources + user source → runtimeRoot)──
  81. const { sources: projectSources } = await readWorkspaceHookProjectSources({
  82. workingDirectory: workspace,
  83. });
  84. expect(projectSources.length).toBeGreaterThan(0);
  85. const userFile = (await parseJsonIfExists(join(home, ".zcode", "cli", "config.json"))) as
  86. | { hooks?: unknown }
  87. | undefined;
  88. const parsedUserHooks = workspaceHooksConfigSchema.safeParse(userFile?.hooks);
  89. const userHooks: WorkspaceHooksConfig | undefined = parsedUserHooks.success
  90. ? parsedUserHooks.data
  91. : undefined;
  92. const runtimeRoot = resolveWorkspaceHookRuntimeRoot([
  93. ...(userHooks ? [userHooks] : []),
  94. ...projectSources.map((source) => source.hooks),
  95. ]);
  96. const reference = buildWorkspaceHookBundleSnapshot({
  97. workspaceIdentity: workspace,
  98. workspacePath: workspace,
  99. sources: projectSources,
  100. runtimeRoot,
  101. });
  102. // ── 实测侧:Settings / hooksService ──
  103. const loaded = await createHooksService().loadHooks({ workspacePath: workspace });
  104. const actual = loaded.workspaceHookSnapshot;
  105. expect(actual).toBeDefined();
  106. expect(reference).toBeDefined();
  107. expect(actual?.bundleDigest).toBe(reference?.bundleDigest);
  108. expect(actual?.hooks.map((hook) => hook.hookDeclarationDigest)).toEqual(
  109. reference?.hooks.map((hook) => hook.hookDeclarationDigest),
  110. );
  111. expect(actual?.hooks.map((hook) => hook.resolvedTimeoutMs)).toEqual(
  112. reference?.hooks.map((hook) => hook.resolvedTimeoutMs),
  113. );
  114. expect(actual?.hooks.map((hook) => hook.configuredEnabled)).toEqual(
  115. reference?.hooks.map((hook) => hook.configuredEnabled),
  116. );
  117. // user hooks.enabled=true 必须传导为 runtimeHooksEnabled=true(否则两边都静默关闭)
  118. expect(reference?.hooks.every((hook) => hook.runtimeHooksEnabled)).toBe(true);
  119. });
  120. });