workspace-hook-trust-phase1.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { describe, expect, it } from "vitest";
  5. import { createConfig } from "../src/config/index.js";
  6. async function createWorkspace(options: { git?: boolean } = {}): Promise<string> {
  7. const root = await mkdtemp(join(tmpdir(), "zcode-workspace-hook-phase1-"));
  8. if (options.git !== false) await mkdir(join(root, ".git"));
  9. return root;
  10. }
  11. async function writeJson(path: string, value: unknown): Promise<void> {
  12. await mkdir(join(path, ".."), { recursive: true });
  13. await writeFile(path, `${JSON.stringify(value, null, 2)}\n`, "utf8");
  14. }
  15. function projectHooks(command: Record<string, unknown>, root: Record<string, unknown> = {}) {
  16. return {
  17. hooks: {
  18. enabled: true,
  19. ...root,
  20. events: {
  21. SessionStart: [{ matcher: "startup", hooks: [command] }],
  22. },
  23. },
  24. };
  25. }
  26. async function snapshotFor(
  27. root: string,
  28. value: unknown,
  29. options: { projectConfigPath?: string; workspaceIdentity?: string } = {},
  30. ) {
  31. const path = join(root, ".zcode", "config.json");
  32. await writeJson(path, value);
  33. const result = createConfig({
  34. env: {},
  35. skipUserConfig: true,
  36. workingDirectory: root,
  37. workspaceIdentity: options.workspaceIdentity,
  38. projectConfigPath: options.projectConfigPath,
  39. });
  40. return { path, result, snapshot: result.sources.project.workspaceHookSnapshot };
  41. }
  42. describe("workspace hook trust phase 1 discovery", () => {
  43. it("保留 immutable project candidates 和 provenance,但仍不进入 executable runtime hooks", async () => {
  44. const root = await createWorkspace();
  45. try {
  46. await writeJson(
  47. join(root, "zcode.json"),
  48. projectHooks({ type: "command", command: "echo ancestor", async: true }),
  49. );
  50. await writeJson(
  51. join(root, ".zcode", "config.json"),
  52. projectHooks({ type: "process", command: "node", args: ["hook.mjs"] }),
  53. );
  54. const result = createConfig({
  55. env: {},
  56. skipUserConfig: true,
  57. workingDirectory: root,
  58. workspaceIdentity: "workspace:test",
  59. });
  60. const snapshot = result.sources.project.workspaceHookSnapshot;
  61. expect(snapshot).toBeDefined();
  62. expect(snapshot).toMatchObject({
  63. schemaVersion: 1,
  64. // 非远程的自报 identity 不进入 Hook Trust,按执行目录计算(D23)。
  65. workspaceIdentity: root,
  66. digestAlgorithm: "sha256",
  67. });
  68. expect(snapshot?.sourceFiles).toHaveLength(2);
  69. expect(
  70. snapshot?.sourceFiles.map((source) => [source.configFileKind, source.editable]),
  71. ).toEqual([
  72. ["zcode.json", false],
  73. [".zcode/config.json", true],
  74. ]);
  75. expect(snapshot?.hooks).toHaveLength(2);
  76. expect(snapshot?.hooks[0]).toMatchObject({
  77. type: "command",
  78. command: "echo ancestor",
  79. async: true,
  80. editable: false,
  81. });
  82. expect(snapshot?.hooks[1]).toMatchObject({
  83. type: "process",
  84. command: "node",
  85. args: ["hook.mjs"],
  86. editable: true,
  87. });
  88. expect(Object.isFrozen(snapshot)).toBe(true);
  89. expect(Object.isFrozen(snapshot?.hooks)).toBe(true);
  90. expect(result.config.hooks.enabled).toBe(false);
  91. expect(result.config.hooks.events.SessionStart).toBeUndefined();
  92. expect(result.sources.project.diagnostics).toContainEqual(
  93. expect.objectContaining({ code: "config_project_hooks_pending_trust", path: "hooks" }),
  94. );
  95. } finally {
  96. await rm(root, { force: true, recursive: true });
  97. }
  98. });
  99. it("复用 runner timeout/max-output resolver,并规范化语义等价 timeout", async () => {
  100. const root = await createWorkspace();
  101. try {
  102. const first = await snapshotFor(
  103. root,
  104. projectHooks(
  105. { type: "command", command: "echo timeout", timeout: 30 },
  106. { timeoutMs: 7_000, maxOutputBytes: 4_096 },
  107. ),
  108. );
  109. const firstEntry = first.snapshot?.hooks[0];
  110. expect(firstEntry).toMatchObject({
  111. resolvedTimeoutMs: 30_000,
  112. resolvedMaxOutputBytes: 4_096,
  113. });
  114. const second = await snapshotFor(
  115. root,
  116. projectHooks(
  117. { type: "command", command: "echo timeout", timeoutMs: 30_000 },
  118. { timeoutMs: 7_000, maxOutputBytes: 4_096 },
  119. ),
  120. );
  121. expect(second.snapshot?.hooks[0]?.hookDeclarationDigest).toBe(
  122. firstEntry?.hookDeclarationDigest,
  123. );
  124. const third = await snapshotFor(
  125. root,
  126. projectHooks(
  127. { type: "command", command: "echo timeout" },
  128. { timeoutMs: 8_000, maxOutputBytes: 8_192 },
  129. ),
  130. );
  131. expect(third.snapshot?.hooks[0]).toMatchObject({
  132. resolvedTimeoutMs: 8_000,
  133. resolvedMaxOutputBytes: 8_192,
  134. });
  135. expect(third.snapshot?.hooks[0]?.hookDeclarationDigest).not.toBe(
  136. firstEntry?.hookDeclarationDigest,
  137. );
  138. } finally {
  139. await rm(root, { force: true, recursive: true });
  140. }
  141. });
  142. it("只 hash Runtime 消费字段:status/unknown 不变,async/shell 会改变 declaration digest", async () => {
  143. const root = await createWorkspace();
  144. try {
  145. const base = await snapshotFor(
  146. root,
  147. projectHooks({
  148. type: "command",
  149. command: "echo canonical",
  150. statusMessage: "one",
  151. futureField: "ignored-a",
  152. }),
  153. );
  154. const baseDigest = base.snapshot?.hooks[0]?.hookDeclarationDigest;
  155. const presentationOnly = await snapshotFor(
  156. root,
  157. projectHooks({
  158. futureField: "ignored-b",
  159. statusMessage: "two",
  160. command: "echo canonical",
  161. type: "command",
  162. }),
  163. );
  164. expect(presentationOnly.snapshot?.hooks[0]?.hookDeclarationDigest).toBe(baseDigest);
  165. const asyncChanged = await snapshotFor(
  166. root,
  167. projectHooks({ type: "command", command: "echo canonical", async: true }),
  168. );
  169. expect(asyncChanged.snapshot?.hooks[0]?.hookDeclarationDigest).not.toBe(baseDigest);
  170. const shellChanged = await snapshotFor(
  171. root,
  172. projectHooks({ type: "command", command: "echo canonical", shell: true }),
  173. );
  174. expect(shellChanged.snapshot?.hooks[0]?.hookDeclarationDigest).not.toBe(baseDigest);
  175. expect(shellChanged.snapshot?.hooks[0]?.hookDeclarationDigest).not.toBe(
  176. asyncChanged.snapshot?.hooks[0]?.hookDeclarationDigest,
  177. );
  178. } finally {
  179. await rm(root, { force: true, recursive: true });
  180. }
  181. });
  182. it("configured gates 只改变 bundle digest,且 hooks.enabled 缺省遵循 Runtime 语义", async () => {
  183. const root = await createWorkspace();
  184. try {
  185. const configPath = join(root, ".zcode", "config.json");
  186. await writeJson(configPath, {
  187. hooks: {
  188. events: {
  189. SessionStart: [{ hooks: [{ type: "command", command: "echo gate", enabled: true }] }],
  190. },
  191. },
  192. });
  193. const missingEnabled = createConfig({
  194. env: {},
  195. skipUserConfig: true,
  196. workingDirectory: root,
  197. });
  198. const missingSnapshot = missingEnabled.sources.project.workspaceHookSnapshot;
  199. expect(missingSnapshot?.hooks[0]).toMatchObject({
  200. sourceRootEnabled: true,
  201. declarationEnabled: true,
  202. runtimeHooksEnabled: false,
  203. configuredEnabled: false,
  204. });
  205. await writeJson(configPath, {
  206. hooks: {
  207. enabled: true,
  208. events: {
  209. SessionStart: [{ hooks: [{ type: "command", command: "echo gate", enabled: true }] }],
  210. },
  211. },
  212. });
  213. const enabled = createConfig({ env: {}, skipUserConfig: true, workingDirectory: root });
  214. const enabledSnapshot = enabled.sources.project.workspaceHookSnapshot;
  215. expect(enabledSnapshot?.hooks[0]).toMatchObject({
  216. sourceRootEnabled: true,
  217. declarationEnabled: true,
  218. runtimeHooksEnabled: true,
  219. configuredEnabled: true,
  220. });
  221. expect(enabledSnapshot?.hooks[0]?.hookDeclarationDigest).toBe(
  222. missingSnapshot?.hooks[0]?.hookDeclarationDigest,
  223. );
  224. expect(enabledSnapshot?.bundleDigest).not.toBe(missingSnapshot?.bundleDigest);
  225. } finally {
  226. await rm(root, { force: true, recursive: true });
  227. }
  228. });
  229. it("JSON 空白/key 排列不影响 digest,显式 projectConfigPath 进入 provenance", async () => {
  230. const root = await createWorkspace();
  231. try {
  232. const configPath = join(root, ".zcode", "config.json");
  233. await mkdir(join(root, ".zcode"), { recursive: true });
  234. await writeFile(
  235. configPath,
  236. '{"hooks":{"events":{"SessionStart":[{"hooks":[{"command":"echo stable","type":"command"}]}]},"enabled":true}}',
  237. "utf8",
  238. );
  239. const first = createConfig({ env: {}, skipUserConfig: true, workingDirectory: root });
  240. await writeFile(
  241. configPath,
  242. '{\n "hooks": {\n "enabled": true,\n "events": {\n "SessionStart": [{"hooks": [{"type": "command", "command": "echo stable"}]}]\n }\n }\n}\n',
  243. "utf8",
  244. );
  245. const second = createConfig({ env: {}, skipUserConfig: true, workingDirectory: root });
  246. expect(second.sources.project.workspaceHookSnapshot?.bundleDigest).toBe(
  247. first.sources.project.workspaceHookSnapshot?.bundleDigest,
  248. );
  249. const explicitPath = join(root, "explicit-hooks.json");
  250. await writeJson(explicitPath, projectHooks({ type: "command", command: "echo explicit" }));
  251. const explicit = createConfig({
  252. env: {},
  253. skipUserConfig: true,
  254. workingDirectory: root,
  255. projectConfigPath: explicitPath,
  256. });
  257. expect(explicit.sources.project.workspaceHookSnapshot?.sourceFiles.at(-1)).toMatchObject({
  258. canonicalPath: explicitPath,
  259. configFileKind: "explicit",
  260. explicitProjectConfig: true,
  261. editable: false,
  262. });
  263. } finally {
  264. await rm(root, { force: true, recursive: true });
  265. }
  266. });
  267. it("非 Git workspace 只扫描 cwd,不纳入父目录 project hooks", async () => {
  268. const parent = await createWorkspace({ git: false });
  269. const child = join(parent, "child");
  270. try {
  271. await mkdir(child, { recursive: true });
  272. await writeJson(
  273. join(parent, "zcode.json"),
  274. projectHooks({ type: "command", command: "echo parent" }),
  275. );
  276. await writeJson(
  277. join(child, ".zcode", "config.json"),
  278. projectHooks({ type: "command", command: "echo child" }),
  279. );
  280. const result = createConfig({ env: {}, skipUserConfig: true, workingDirectory: child });
  281. expect(result.sources.project.workspaceHookSnapshot?.hooks).toHaveLength(1);
  282. expect(result.sources.project.workspaceHookSnapshot?.hooks[0]?.command).toBe("echo child");
  283. } finally {
  284. await rm(parent, { force: true, recursive: true });
  285. }
  286. });
  287. it("无效 project Hook schema fail closed,不创建 snapshot", async () => {
  288. const root = await createWorkspace();
  289. try {
  290. const configPath = join(root, ".zcode", "config.json");
  291. await writeJson(configPath, projectHooks({ type: "process", command: "" }));
  292. const result = createConfig({ env: {}, skipUserConfig: true, workingDirectory: root });
  293. expect(result.sources.project.workspaceHookSnapshot).toBeUndefined();
  294. expect(result.sources.project.diagnostics).toContainEqual(
  295. expect.objectContaining({ code: "config_file_invalid", filePath: configPath }),
  296. );
  297. expect(result.config.hooks.events.SessionStart).toBeUndefined();
  298. await expect(readFile(configPath, "utf8")).resolves.toContain('"command": ""');
  299. } finally {
  300. await rm(root, { force: true, recursive: true });
  301. }
  302. });
  303. });