create-workspace-hook-trust-uat-fixture.mjs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. import { mkdir, mkdtemp, readFile, stat, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join, resolve } from "node:path";
  4. import { parseArgs } from "node:util";
  5. const usage = `Usage:
  6. node scripts/create-workspace-hook-trust-uat-fixture.mjs [--target <new-directory>] [--json]
  7. node scripts/create-workspace-hook-trust-uat-fixture.mjs --verify <existing-workspace> [--json]
  8. Creates a harmless Workspace Hook Trust manual-acceptance workspace.
  9. The target directory must not already exist. Without --target, a new directory is created under the OS temp directory.
  10. --verify asserts an existing fixture is still pristine before a UAT round: every
  11. declaration must be enabled and no Hook may have produced evidence yet. Exits
  12. non-zero when the fixture drifted, so a polluted workspace fails in seconds
  13. instead of invalidating a whole manual round.
  14. `;
  15. const parsed = parseArgs({
  16. args: process.argv.slice(2),
  17. options: {
  18. help: { type: "boolean", short: "h" },
  19. json: { type: "boolean" },
  20. target: { type: "string" },
  21. verify: { type: "string" },
  22. },
  23. strict: true,
  24. });
  25. if (parsed.values.help) {
  26. process.stdout.write(usage);
  27. process.exit(0);
  28. }
  29. if (parsed.values.verify !== undefined) {
  30. if (parsed.values.target !== undefined) {
  31. process.stderr.write("--verify cannot be combined with --target.\n");
  32. process.exit(2);
  33. }
  34. await verifyFixture(resolve(parsed.values.verify), parsed.values.json === true);
  35. }
  36. const workspacePath = parsed.values.target
  37. ? resolve(parsed.values.target)
  38. : await mkdtemp(join(tmpdir(), "zcode-workspace-hook-trust-uat-"));
  39. if (parsed.values.target) {
  40. await mkdir(workspacePath);
  41. }
  42. const zcodeDirectory = join(workspacePath, ".zcode");
  43. const recorderPath = join(zcodeDirectory, "workspace-hook-trust-uat-recorder.mjs");
  44. const configPath = join(zcodeDirectory, "config.json");
  45. const evidencePath = join(workspacePath, ".workspace-hook-trust-uat", "executions.jsonl");
  46. await mkdir(zcodeDirectory, { recursive: true });
  47. const recorder = `import { appendFile, mkdir } from "node:fs/promises";
  48. import { join } from "node:path";
  49. const event = process.argv[2] ?? "unknown";
  50. const label = process.argv[3] ?? "unknown";
  51. const outputDirectory = join(process.cwd(), ".workspace-hook-trust-uat");
  52. const outputPath = join(outputDirectory, "executions.jsonl");
  53. await mkdir(outputDirectory, { recursive: true });
  54. await appendFile(
  55. outputPath,
  56. JSON.stringify({ event, label, executedAt: new Date().toISOString(), cwd: process.cwd() }) + "\\n",
  57. "utf8",
  58. );
  59. process.stdout.write(\`workspace-hook-trust-uat:\${event}:\${label}\\n\`);
  60. `;
  61. const config = {
  62. hooks: {
  63. enabled: true,
  64. timeoutMs: 10_000,
  65. maxOutputBytes: 32_768,
  66. events: {
  67. SessionStart: [
  68. {
  69. matcher: "startup",
  70. hooks: [
  71. {
  72. type: "process",
  73. command: "node",
  74. args: [
  75. ".zcode/workspace-hook-trust-uat-recorder.mjs",
  76. "SessionStart",
  77. "session-start-a",
  78. ],
  79. enabled: true,
  80. timeoutMs: 10_000,
  81. statusMessage: "Workspace Hook Trust UAT — SessionStart A",
  82. },
  83. {
  84. type: "process",
  85. command: "node",
  86. args: [
  87. ".zcode/workspace-hook-trust-uat-recorder.mjs",
  88. "SessionStart",
  89. "session-start-b",
  90. ],
  91. enabled: true,
  92. timeoutMs: 10_000,
  93. statusMessage: "Workspace Hook Trust UAT — SessionStart B",
  94. },
  95. ],
  96. },
  97. ],
  98. UserPromptSubmit: [
  99. {
  100. hooks: [
  101. {
  102. type: "process",
  103. command: "node",
  104. args: [
  105. ".zcode/workspace-hook-trust-uat-recorder.mjs",
  106. "UserPromptSubmit",
  107. "prompt-submit",
  108. ],
  109. enabled: true,
  110. timeoutMs: 10_000,
  111. statusMessage: "Workspace Hook Trust UAT — UserPromptSubmit",
  112. },
  113. ],
  114. },
  115. ],
  116. },
  117. },
  118. };
  119. const readme = `# Workspace Hook Trust manual acceptance fixture
  120. This workspace contains three harmless project Hook declarations:
  121. - SessionStart / session-start-a
  122. - SessionStart / session-start-b
  123. - UserPromptSubmit / prompt-submit
  124. Each admitted Hook appends one JSON line to:
  125. \`${evidencePath}\`
  126. Before Trust admission, that file must not be created by these Hooks.
  127. Follow the repository checklist:
  128. \`docs/testing/workspace-hook-trust-manual-acceptance.md\`
  129. `;
  130. await Promise.all([
  131. writeFile(recorderPath, recorder, "utf8"),
  132. writeFile(configPath, `${JSON.stringify(config, null, 2)}\n`, "utf8"),
  133. writeFile(join(workspacePath, "README.md"), readme, "utf8"),
  134. ]);
  135. const result = { workspacePath, configPath, recorderPath, evidencePath };
  136. if (parsed.values.json) {
  137. process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
  138. } else {
  139. process.stdout.write(
  140. [
  141. "Workspace Hook Trust UAT fixture created.",
  142. `workspace: ${workspacePath}`,
  143. `config: ${configPath}`,
  144. `evidence: ${evidencePath}`,
  145. "",
  146. "Open the workspace in ZCode Desktop, then follow:",
  147. "docs/testing/workspace-hook-trust-manual-acceptance.md",
  148. "",
  149. ].join("\n"),
  150. );
  151. }
  152. /**
  153. * UAT 现场校验。
  154. *
  155. * 背景(2026-08-10 实测):一次诊断脚本直接对正在验收的 fixture 调用了
  156. * writeWorkspaceHookConfiguredToggle,把三条声明写成 enabled:false。由于
  157. * runtime admission 只在存在「已启用且待授信」的声明时才开审核流程,全部关闭后
  158. * 审核面板不再出现——验收者据此误判为产品缺陷,损失一整轮人工验收。
  159. * 这里在每轮开始前做廉价断言,让污染在数秒内暴露,而不是等测完才发现。
  160. */
  161. async function verifyFixture(workspacePath, asJson) {
  162. const targetConfigPath = join(workspacePath, ".zcode", "config.json");
  163. const targetEvidencePath = join(workspacePath, ".workspace-hook-trust-uat", "executions.jsonl");
  164. const problems = [];
  165. let declarations = [];
  166. let raw;
  167. try {
  168. raw = JSON.parse(await readFile(targetConfigPath, "utf8"));
  169. } catch (error) {
  170. problems.push(`配置无法读取或不是合法 JSON:${targetConfigPath}(${error.message})`);
  171. }
  172. if (raw) {
  173. const hooks = raw.hooks;
  174. if (!hooks || typeof hooks !== "object") {
  175. problems.push("配置缺少 hooks 根对象。");
  176. } else {
  177. if (hooks.enabled !== true) {
  178. problems.push(`hooks.enabled 应为 true,实际为 ${JSON.stringify(hooks.enabled)}。`);
  179. }
  180. for (const [event, matchers] of Object.entries(hooks.events ?? {})) {
  181. for (const [matcherIndex, matcher] of (matchers ?? []).entries()) {
  182. for (const [hookIndex, hook] of (matcher?.hooks ?? []).entries()) {
  183. const label =
  184. `${event}[${matcherIndex}][${hookIndex}] ${hook?.statusMessage ?? ""}`.trim();
  185. declarations.push({ label, enabled: hook?.enabled });
  186. // enabled 缺省即视为启用(runtime 语义是 enabled !== false);只有显式 false 才算漂移。
  187. if (hook?.enabled === false) {
  188. problems.push(`声明已被关闭,应为启用:${label}`);
  189. }
  190. }
  191. }
  192. }
  193. if (declarations.length === 0) {
  194. problems.push("配置中没有任何 Hook 声明。");
  195. }
  196. }
  197. }
  198. // 未授信前 Hook 不得执行,因此证据文件在干净现场下必须不存在。
  199. try {
  200. await stat(targetEvidencePath);
  201. problems.push(`上一轮的执行证据仍在,需重新生成 fixture:${targetEvidencePath}`);
  202. } catch {
  203. // 不存在即符合预期。
  204. }
  205. const ok = problems.length === 0;
  206. if (asJson) {
  207. process.stdout.write(
  208. `${JSON.stringify({ ok, workspacePath, problems, declarations }, null, 2)}\n`,
  209. );
  210. } else if (ok) {
  211. process.stdout.write(
  212. [
  213. "Workspace Hook Trust UAT fixture 现场干净,可以开始本轮验收。",
  214. `workspace: ${workspacePath}`,
  215. `declarations: ${declarations.length} 条,全部启用`,
  216. "",
  217. ].join("\n"),
  218. );
  219. } else {
  220. process.stderr.write(
  221. [
  222. "Workspace Hook Trust UAT fixture 已漂移,请勿在此现场继续验收:",
  223. ...problems.map((item) => ` - ${item}`),
  224. "",
  225. "重新生成干净现场:",
  226. " node scripts/create-workspace-hook-trust-uat-fixture.mjs",
  227. "",
  228. ].join("\n"),
  229. );
  230. }
  231. process.exit(ok ? 0 : 1);
  232. }