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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. workspaceIdentity: "workspace:test",
  65. digestAlgorithm: "sha256",
  66. });
  67. expect(snapshot?.sourceFiles).toHaveLength(2);
  68. expect(
  69. snapshot?.sourceFiles.map((source) => [source.configFileKind, source.editable]),
  70. ).toEqual([
  71. ["zcode.json", false],
  72. [".zcode/config.json", true],
  73. ]);
  74. expect(snapshot?.hooks).toHaveLength(2);
  75. expect(snapshot?.hooks[0]).toMatchObject({
  76. type: "command",
  77. command: "echo ancestor",
  78. async: true,
  79. editable: false,
  80. });
  81. expect(snapshot?.hooks[1]).toMatchObject({
  82. type: "process",
  83. command: "node",
  84. args: ["hook.mjs"],
  85. editable: true,
  86. });
  87. expect(Object.isFrozen(snapshot)).toBe(true);
  88. expect(Object.isFrozen(snapshot?.hooks)).toBe(true);
  89. expect(result.config.hooks.enabled).toBe(false);
  90. expect(result.config.hooks.events.SessionStart).toBeUndefined();
  91. expect(result.sources.project.diagnostics).toContainEqual(
  92. expect.objectContaining({ code: "config_project_hooks_pending_trust", path: "hooks" }),
  93. );
  94. } finally {
  95. await rm(root, { force: true, recursive: true });
  96. }
  97. });
  98. it("复用 runner timeout/max-output resolver,并规范化语义等价 timeout", async () => {
  99. const root = await createWorkspace();
  100. try {
  101. const first = await snapshotFor(
  102. root,
  103. projectHooks(
  104. { type: "command", command: "echo timeout", timeout: 30 },
  105. { timeoutMs: 7_000, maxOutputBytes: 4_096 },
  106. ),
  107. );
  108. const firstEntry = first.snapshot?.hooks[0];
  109. expect(firstEntry).toMatchObject({
  110. resolvedTimeoutMs: 30_000,
  111. resolvedMaxOutputBytes: 4_096,
  112. });
  113. const second = await snapshotFor(
  114. root,
  115. projectHooks(
  116. { type: "command", command: "echo timeout", timeoutMs: 30_000 },
  117. { timeoutMs: 7_000, maxOutputBytes: 4_096 },
  118. ),
  119. );
  120. expect(second.snapshot?.hooks[0]?.hookDeclarationDigest).toBe(
  121. firstEntry?.hookDeclarationDigest,
  122. );
  123. const third = await snapshotFor(
  124. root,
  125. projectHooks(
  126. { type: "command", command: "echo timeout" },
  127. { timeoutMs: 8_000, maxOutputBytes: 8_192 },
  128. ),
  129. );
  130. expect(third.snapshot?.hooks[0]).toMatchObject({
  131. resolvedTimeoutMs: 8_000,
  132. resolvedMaxOutputBytes: 8_192,
  133. });
  134. expect(third.snapshot?.hooks[0]?.hookDeclarationDigest).not.toBe(
  135. firstEntry?.hookDeclarationDigest,
  136. );
  137. } finally {
  138. await rm(root, { force: true, recursive: true });
  139. }
  140. });
  141. it("只 hash Runtime 消费字段:status/unknown 不变,async/shell 会改变 declaration digest", async () => {
  142. const root = await createWorkspace();
  143. try {
  144. const base = await snapshotFor(
  145. root,
  146. projectHooks({
  147. type: "command",
  148. command: "echo canonical",
  149. statusMessage: "one",
  150. futureField: "ignored-a",
  151. }),
  152. );
  153. const baseDigest = base.snapshot?.hooks[0]?.hookDeclarationDigest;
  154. const presentationOnly = await snapshotFor(
  155. root,
  156. projectHooks({
  157. futureField: "ignored-b",
  158. statusMessage: "two",
  159. command: "echo canonical",
  160. type: "command",
  161. }),
  162. );
  163. expect(presentationOnly.snapshot?.hooks[0]?.hookDeclarationDigest).toBe(baseDigest);
  164. const asyncChanged = await snapshotFor(
  165. root,
  166. projectHooks({ type: "command", command: "echo canonical", async: true }),
  167. );
  168. expect(asyncChanged.snapshot?.hooks[0]?.hookDeclarationDigest).not.toBe(baseDigest);
  169. const shellChanged = await snapshotFor(
  170. root,
  171. projectHooks({ type: "command", command: "echo canonical", shell: true }),
  172. );
  173. expect(shellChanged.snapshot?.hooks[0]?.hookDeclarationDigest).not.toBe(baseDigest);
  174. expect(shellChanged.snapshot?.hooks[0]?.hookDeclarationDigest).not.toBe(
  175. asyncChanged.snapshot?.hooks[0]?.hookDeclarationDigest,
  176. );
  177. } finally {
  178. await rm(root, { force: true, recursive: true });
  179. }
  180. });
  181. it("configured gates 只改变 bundle digest,且 hooks.enabled 缺省遵循 Runtime 语义", async () => {
  182. const root = await createWorkspace();
  183. try {
  184. const configPath = join(root, ".zcode", "config.json");
  185. await writeJson(configPath, {
  186. hooks: {
  187. events: {
  188. SessionStart: [{ hooks: [{ type: "command", command: "echo gate", enabled: true }] }],
  189. },
  190. },
  191. });
  192. const missingEnabled = createConfig({
  193. env: {},
  194. skipUserConfig: true,
  195. workingDirectory: root,
  196. });
  197. const missingSnapshot = missingEnabled.sources.project.workspaceHookSnapshot;
  198. expect(missingSnapshot?.hooks[0]).toMatchObject({
  199. sourceRootEnabled: true,
  200. declarationEnabled: true,
  201. runtimeHooksEnabled: false,
  202. configuredEnabled: false,
  203. });
  204. await writeJson(configPath, {
  205. hooks: {
  206. enabled: true,
  207. events: {
  208. SessionStart: [{ hooks: [{ type: "command", command: "echo gate", enabled: true }] }],
  209. },
  210. },
  211. });
  212. const enabled = createConfig({ env: {}, skipUserConfig: true, workingDirectory: root });
  213. const enabledSnapshot = enabled.sources.project.workspaceHookSnapshot;
  214. expect(enabledSnapshot?.hooks[0]).toMatchObject({
  215. sourceRootEnabled: true,
  216. declarationEnabled: true,
  217. runtimeHooksEnabled: true,
  218. configuredEnabled: true,
  219. });
  220. expect(enabledSnapshot?.hooks[0]?.hookDeclarationDigest).toBe(
  221. missingSnapshot?.hooks[0]?.hookDeclarationDigest,
  222. );
  223. expect(enabledSnapshot?.bundleDigest).not.toBe(missingSnapshot?.bundleDigest);
  224. } finally {
  225. await rm(root, { force: true, recursive: true });
  226. }
  227. });
  228. it("JSON 空白/key 排列不影响 digest,显式 projectConfigPath 进入 provenance", async () => {
  229. const root = await createWorkspace();
  230. try {
  231. const configPath = join(root, ".zcode", "config.json");
  232. await mkdir(join(root, ".zcode"), { recursive: true });
  233. await writeFile(
  234. configPath,
  235. '{"hooks":{"events":{"SessionStart":[{"hooks":[{"command":"echo stable","type":"command"}]}]},"enabled":true}}',
  236. "utf8",
  237. );
  238. const first = createConfig({ env: {}, skipUserConfig: true, workingDirectory: root });
  239. await writeFile(
  240. configPath,
  241. '{\n "hooks": {\n "enabled": true,\n "events": {\n "SessionStart": [{"hooks": [{"type": "command", "command": "echo stable"}]}]\n }\n }\n}\n',
  242. "utf8",
  243. );
  244. const second = createConfig({ env: {}, skipUserConfig: true, workingDirectory: root });
  245. expect(second.sources.project.workspaceHookSnapshot?.bundleDigest).toBe(
  246. first.sources.project.workspaceHookSnapshot?.bundleDigest,
  247. );
  248. const explicitPath = join(root, "explicit-hooks.json");
  249. await writeJson(explicitPath, projectHooks({ type: "command", command: "echo explicit" }));
  250. const explicit = createConfig({
  251. env: {},
  252. skipUserConfig: true,
  253. workingDirectory: root,
  254. projectConfigPath: explicitPath,
  255. });
  256. expect(explicit.sources.project.workspaceHookSnapshot?.sourceFiles.at(-1)).toMatchObject({
  257. canonicalPath: explicitPath,
  258. configFileKind: "explicit",
  259. explicitProjectConfig: true,
  260. editable: false,
  261. });
  262. } finally {
  263. await rm(root, { force: true, recursive: true });
  264. }
  265. });
  266. it("非 Git workspace 只扫描 cwd,不纳入父目录 project hooks", async () => {
  267. const parent = await createWorkspace({ git: false });
  268. const child = join(parent, "child");
  269. try {
  270. await mkdir(child, { recursive: true });
  271. await writeJson(
  272. join(parent, "zcode.json"),
  273. projectHooks({ type: "command", command: "echo parent" }),
  274. );
  275. await writeJson(
  276. join(child, ".zcode", "config.json"),
  277. projectHooks({ type: "command", command: "echo child" }),
  278. );
  279. const result = createConfig({ env: {}, skipUserConfig: true, workingDirectory: child });
  280. expect(result.sources.project.workspaceHookSnapshot?.hooks).toHaveLength(1);
  281. expect(result.sources.project.workspaceHookSnapshot?.hooks[0]?.command).toBe("echo child");
  282. } finally {
  283. await rm(parent, { force: true, recursive: true });
  284. }
  285. });
  286. it("无效 project Hook schema fail closed,不创建 snapshot", async () => {
  287. const root = await createWorkspace();
  288. try {
  289. const configPath = join(root, ".zcode", "config.json");
  290. await writeJson(configPath, projectHooks({ type: "process", command: "" }));
  291. const result = createConfig({ env: {}, skipUserConfig: true, workingDirectory: root });
  292. expect(result.sources.project.workspaceHookSnapshot).toBeUndefined();
  293. expect(result.sources.project.diagnostics).toContainEqual(
  294. expect.objectContaining({ code: "config_file_invalid", filePath: configPath }),
  295. );
  296. expect(result.config.hooks.events.SessionStart).toBeUndefined();
  297. await expect(readFile(configPath, "utf8")).resolves.toContain('"command": ""');
  298. } finally {
  299. await rm(root, { force: true, recursive: true });
  300. }
  301. });
  302. });