workspace-hook-review-mutation.test.ts 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
  2. import { 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 { createWorkspaceHookBundleSnapshot } from "@zcode/contracts";
  7. import {
  8. buildWorkspaceHookBundleSnapshot,
  9. readWorkspaceHookProjectSources,
  10. } from "@zcode/shared/workspace-hook-discovery";
  11. import { createWorkspaceHookReviewMutationPort } from "../src/app/workspace-hook-review-mutation.js";
  12. const roots: string[] = [];
  13. const runtimeRoot = {
  14. enabled: true,
  15. timeoutMs: 60_000,
  16. maxOutputBytes: 32_768,
  17. };
  18. function makeWorkspace(): { workspace: string; configPath: string } {
  19. const workspace = mkdtempSync(join(tmpdir(), "workspace-hook-review-mutation-"));
  20. roots.push(workspace);
  21. mkdirSync(join(workspace, ".git"));
  22. const configPath = join(workspace, ".zcode", "config.json");
  23. mkdirSync(join(workspace, ".zcode"));
  24. writeFileSync(
  25. configPath,
  26. `${JSON.stringify(
  27. {
  28. projectSetting: "keep",
  29. hooks: {
  30. enabled: true,
  31. events: {
  32. SessionStart: [
  33. {
  34. hooks: [{ type: "command", command: "echo reviewed", enabled: true }],
  35. },
  36. ],
  37. },
  38. },
  39. },
  40. null,
  41. 2,
  42. )}\n`,
  43. "utf8",
  44. );
  45. return { workspace, configPath };
  46. }
  47. async function snapshot(workspace: string) {
  48. const { sources, errors } = await readWorkspaceHookProjectSources({
  49. workingDirectory: workspace,
  50. });
  51. expect(errors).toEqual([]);
  52. const value = buildWorkspaceHookBundleSnapshot({
  53. workspaceIdentity: `local:${workspace}`,
  54. workspacePath: workspace,
  55. sources,
  56. runtimeRoot,
  57. });
  58. if (!value) throw new Error("expected snapshot");
  59. return createWorkspaceHookBundleSnapshot(value);
  60. }
  61. afterEach(async () => {
  62. await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
  63. });
  64. describe("real workspace Hook review mutation port", () => {
  65. it("在同一 lock 内 preflight 当前 bundle、atomic write、commit callback、rebuild next snapshot", async () => {
  66. const { workspace, configPath } = makeWorkspace();
  67. const current = await snapshot(workspace);
  68. const events: string[] = [];
  69. const port = createWorkspaceHookReviewMutationPort({
  70. workingDirectory: workspace,
  71. workspaceIdentity: current.workspaceIdentity,
  72. runtimeRoot,
  73. });
  74. const next = await port.toggle(
  75. {
  76. snapshot: current,
  77. reviewItemId: current.hooks[0]!.reviewItemId,
  78. enabled: false,
  79. },
  80. () => {
  81. events.push("committed");
  82. expect(
  83. JSON.parse(readFileSync(configPath, "utf8")).hooks.events.SessionStart[0].hooks[0],
  84. ).toMatchObject({ command: "echo reviewed", enabled: false });
  85. },
  86. );
  87. expect(events).toEqual(["committed"]);
  88. expect(next.bundleDigest).not.toBe(current.bundleDigest);
  89. expect(next.hooks[0]).toMatchObject({
  90. declarationEnabled: false,
  91. configuredEnabled: false,
  92. });
  93. expect(JSON.parse(readFileSync(configPath, "utf8")).projectSetting).toBe("keep");
  94. });
  95. it("process-global workspace lock 使并发旧 bundle mutation 在第一份提交后 fail closed", async () => {
  96. const { workspace, configPath } = makeWorkspace();
  97. const current = await snapshot(workspace);
  98. const portA = createWorkspaceHookReviewMutationPort({
  99. workingDirectory: workspace,
  100. workspaceIdentity: current.workspaceIdentity,
  101. runtimeRoot,
  102. });
  103. const portB = createWorkspaceHookReviewMutationPort({
  104. workingDirectory: workspace,
  105. workspaceIdentity: current.workspaceIdentity,
  106. runtimeRoot,
  107. });
  108. let release!: () => void;
  109. const gate = new Promise<void>((resolve) => {
  110. release = resolve;
  111. });
  112. const first = portA.toggle(
  113. {
  114. snapshot: current,
  115. reviewItemId: current.hooks[0]!.reviewItemId,
  116. enabled: false,
  117. },
  118. () => gate,
  119. );
  120. await expect
  121. .poll(
  122. () =>
  123. JSON.parse(readFileSync(configPath, "utf8")).hooks.events.SessionStart[0].hooks[0]
  124. .enabled,
  125. )
  126. .toBe(false);
  127. const second = portB.toggle(
  128. {
  129. snapshot: current,
  130. reviewItemId: current.hooks[0]!.reviewItemId,
  131. enabled: true,
  132. },
  133. () => undefined,
  134. );
  135. release();
  136. await expect(first).resolves.toMatchObject({
  137. hooks: [expect.objectContaining({ declarationEnabled: false })],
  138. });
  139. await expect(second).rejects.toMatchObject({
  140. // 第一次 toggle 已提交,bundle 确实变了:区别于 identity 不符与配置读失败,
  141. // 此处必须是 bundle_changed,用户才能据此判断是否重新审核。
  142. code: "workspace_hooks_bundle_changed",
  143. });
  144. // 该 message 会经 controller 进入 telemetry.errorMessage(TR27),因此不得含
  145. // 完整 digest 或绝对路径:spec §23.3「不上传完整 workspace path」、
  146. // §23.4「不记录 source path」。此前 message 内嵌完整 identity(即绝对路径)
  147. // 与全长 digest,构成明文泄漏。
  148. const rejection = await second.catch((error: unknown) => error);
  149. const message = rejection instanceof Error ? rejection.message : String(rejection);
  150. expect(message).not.toContain(configPath);
  151. // 摘要保留可诊断性:截断到 12 字符,但不出现全长(64 字符)digest。
  152. expect(message).toMatch(/expected [0-9a-f]{12}, got [0-9a-f]{12}/u);
  153. expect(message).not.toMatch(/[0-9a-f]{64}/u);
  154. expect(
  155. JSON.parse(readFileSync(configPath, "utf8")).hooks.events.SessionStart[0].hooks[0].enabled,
  156. ).toBe(false);
  157. });
  158. });