hooks-seven-events.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. import { readFile } from "node:fs/promises";
  2. import { describe, expect, it, vi } from "vitest";
  3. import {
  4. HookEventName,
  5. SessionEventType,
  6. createRootTraceContext,
  7. createSessionId,
  8. createToolCallId,
  9. createTurnId,
  10. type ExecutionPort,
  11. type ExecutionResult,
  12. type HookInput,
  13. type HookJSONOutput,
  14. type SessionEvent,
  15. } from "@zcode/contracts";
  16. import { createConfiguredHookRunner } from "../src/hooks/index.js";
  17. import { matchesHookMatcher } from "../src/hooks/output.js";
  18. const sessionId = createSessionId("hooks-seven-events");
  19. const turnId = createTurnId("hooks-seven-events-turn");
  20. const traceContext = createRootTraceContext({ sessionId, turnId });
  21. const base = {
  22. agentName: "zcode",
  23. cwd: "/workspace",
  24. mode: "build" as const,
  25. sessionId,
  26. timestamp: "2026-07-10T00:00:00.000Z",
  27. traceId: traceContext.traceId,
  28. turnId,
  29. };
  30. type ConfiguredRunner = NonNullable<ReturnType<typeof createConfiguredHookRunner>>;
  31. interface HookCase {
  32. event: HookEventName;
  33. expectedInput: Record<string, unknown>;
  34. input: HookInput;
  35. matcher: string;
  36. output: HookJSONOutput;
  37. verifyResult: (result: Awaited<ReturnType<ConfiguredRunner["run"]>>) => void;
  38. }
  39. const cases: HookCase[] = [
  40. {
  41. event: HookEventName.SessionStart,
  42. expectedInput: { model: "anthropic/opus", source: "startup" },
  43. input: {
  44. ...base,
  45. hookEventName: HookEventName.SessionStart,
  46. model: "anthropic/opus",
  47. source: "startup",
  48. },
  49. matcher: "startup",
  50. output: eventContext(HookEventName.SessionStart, "session-context"),
  51. verifyResult: (result) => expect(result.additionalContexts).toEqual(["session-context"]),
  52. },
  53. {
  54. event: HookEventName.UserPromptSubmit,
  55. expectedInput: { prompt: "ship hooks" },
  56. input: { ...base, hookEventName: HookEventName.UserPromptSubmit, prompt: "ship hooks" },
  57. matcher: "matcher-is-not-applied-to-prompt",
  58. output: eventContext(HookEventName.UserPromptSubmit, "prompt-context"),
  59. verifyResult: (result) => expect(result.additionalContexts).toEqual(["prompt-context"]),
  60. },
  61. {
  62. event: HookEventName.PreToolUse,
  63. expectedInput: {
  64. tool_input: { path: "a.ts" },
  65. tool_name: "Write",
  66. tool_use_id: "tool_hook-call",
  67. },
  68. input: toolInput(HookEventName.PreToolUse),
  69. matcher: "Write|Edit",
  70. output: {
  71. hookSpecificOutput: {
  72. additionalContext: "pre-context",
  73. hookEventName: HookEventName.PreToolUse,
  74. permissionDecision: "allow",
  75. updatedInput: { path: "b.ts" },
  76. },
  77. },
  78. verifyResult: (result) => {
  79. expect(result.permissionBehavior).toBe("allow");
  80. expect(result.updatedInput).toEqual({ path: "b.ts" });
  81. },
  82. },
  83. {
  84. event: HookEventName.PermissionRequest,
  85. expectedInput: { reason: "write requires approval", requestId: "permission-1" },
  86. input: {
  87. ...toolInput(HookEventName.PermissionRequest),
  88. reason: "write requires approval",
  89. requestId: "permission-1",
  90. },
  91. matcher: "Write",
  92. output: {
  93. hookSpecificOutput: {
  94. decision: {
  95. behavior: "allow",
  96. updatedPermissions: [
  97. { type: "addRules", behavior: "allow", rules: [{ toolName: "Write" }] },
  98. ],
  99. },
  100. hookEventName: HookEventName.PermissionRequest,
  101. },
  102. },
  103. verifyResult: (result) => {
  104. expect(result.permissionRequestResult?.behavior).toBe("allow");
  105. expect(result.permissionRequestResult).toHaveProperty("updatedPermissions");
  106. },
  107. },
  108. {
  109. event: HookEventName.PostToolUse,
  110. expectedInput: { tool_response: { ok: true }, toolResultPreview: '{"ok":true}' },
  111. input: {
  112. ...toolInput(HookEventName.PostToolUse),
  113. toolResponse: { ok: true },
  114. toolResultPreview: '{"ok":true}',
  115. },
  116. matcher: "Write",
  117. output: eventContext(HookEventName.PostToolUse, "post-context"),
  118. verifyResult: (result) => expect(result.additionalContexts).toEqual(["post-context"]),
  119. },
  120. {
  121. event: HookEventName.PostToolUseFailure,
  122. expectedInput: { error: "cancelled", is_interrupt: true },
  123. input: {
  124. ...toolInput(HookEventName.PostToolUseFailure),
  125. error: { message: "cancelled", type: "TOOL_CANCELLED" },
  126. isInterrupt: true,
  127. },
  128. matcher: "Write",
  129. output: eventContext(HookEventName.PostToolUseFailure, "failure-context"),
  130. verifyResult: (result) => expect(result.additionalContexts).toEqual(["failure-context"]),
  131. },
  132. {
  133. event: HookEventName.Stop,
  134. expectedInput: { last_assistant_message: "draft answer", stop_hook_active: true },
  135. input: {
  136. ...base,
  137. hookEventName: HookEventName.Stop,
  138. responsePreview: "draft",
  139. responseText: "draft answer",
  140. stopHookActive: true,
  141. toolCallCount: 1,
  142. },
  143. matcher: "matcher-is-not-applied-to-response",
  144. output: { decision: "block", reason: "revise" },
  145. verifyResult: (result) => {
  146. expect(result.stopShouldContinue).toBe(true);
  147. expect(result.additionalContexts).toEqual(["revise"]);
  148. },
  149. },
  150. ];
  151. describe("configured hooks seven-event contract", () => {
  152. it.each(cases)("runs $event with Claude-compatible input and output", async (hookCase) => {
  153. let capturedInput: Record<string, unknown> | undefined;
  154. let transcriptReadable = false;
  155. const runner = createConfiguredHookRunner({
  156. config: {
  157. enabled: true,
  158. events: {
  159. [hookCase.event]: [
  160. {
  161. hooks: [{ type: "process", command: "hook-command" }],
  162. matcher: hookCase.matcher,
  163. },
  164. ],
  165. },
  166. maxOutputBytes: 4096,
  167. timeoutMs: 1000,
  168. },
  169. executionPort: executionPortReturning(hookCase.output, async (stdin) => {
  170. capturedInput = JSON.parse(stdin) as Record<string, unknown>;
  171. await readFile(String(capturedInput.transcript_path), "utf8");
  172. transcriptReadable = true;
  173. }),
  174. getWorkingDirectory: () => "/workspace",
  175. });
  176. const matchValue = getMatchValue(hookCase.input);
  177. const result = await runner!.run(
  178. hookCase.input,
  179. matchValue === undefined ? undefined : { matchValue },
  180. );
  181. expect(transcriptReadable).toBe(true);
  182. expect(capturedInput).toMatchObject({
  183. hook_event_name: hookCase.event,
  184. session_id: sessionId,
  185. transcript_path: expect.any(String),
  186. ...hookCase.expectedInput,
  187. });
  188. hookCase.verifyResult(result);
  189. });
  190. it("uses exact, pipe, wildcard, and regex hook matcher rules", () => {
  191. expect(matchesHookMatcher("Write", "Write")).toBe(true);
  192. expect(matchesHookMatcher("WriteFile", "Write")).toBe(false);
  193. expect(matchesHookMatcher("Edit", "Write|Edit")).toBe(true);
  194. expect(matchesHookMatcher("anything", "*")).toBe(true);
  195. expect(matchesHookMatcher("mcp__docs__read", "^mcp__.*__read$")).toBe(true);
  196. expect(matchesHookMatcher("Write", "[")).toBe(false);
  197. });
  198. it.each([
  199. {
  200. behavior: "deny",
  201. decision: { behavior: "deny" as const, message: "blocked by permission hook" },
  202. expected: { behavior: "deny", message: "blocked by permission hook" },
  203. },
  204. {
  205. behavior: "modify",
  206. decision: {
  207. behavior: "allow" as const,
  208. updatedInput: { path: "approved.ts" },
  209. updatedPermissions: [
  210. { type: "addRules" as const, behavior: "allow" as const, rules: [{ toolName: "Write" }] },
  211. ],
  212. },
  213. expected: { behavior: "allow", updatedInput: { path: "approved.ts" } },
  214. },
  215. ])("maps PermissionRequest $behavior decisions", async ({ decision, expected }) => {
  216. const runner = createConfiguredHookRunner({
  217. config: {
  218. enabled: true,
  219. events: {
  220. PermissionRequest: [
  221. {
  222. hooks: [{ type: "process", command: "permission-hook" }],
  223. matcher: "Write",
  224. },
  225. ],
  226. },
  227. maxOutputBytes: 4096,
  228. timeoutMs: 1000,
  229. },
  230. executionPort: executionPortReturning(
  231. {
  232. hookSpecificOutput: {
  233. decision,
  234. hookEventName: HookEventName.PermissionRequest,
  235. },
  236. },
  237. async () => {},
  238. ),
  239. getWorkingDirectory: () => "/workspace",
  240. });
  241. const result = await runner!.run(cases[3]!.input, { matchValue: "Write" });
  242. expect(result.permissionRequestResult).toMatchObject(expected);
  243. });
  244. it("skips disabled hooks and accepts diagnostic or forward-compatible stdout", async () => {
  245. let callCount = 0;
  246. const outputs = ["plain diagnostic", JSON.stringify({ futureField: true })];
  247. const runner = createConfiguredHookRunner({
  248. config: {
  249. enabled: true,
  250. events: {
  251. SessionStart: [
  252. {
  253. hooks: [
  254. { type: "process", command: "disabled", enabled: false },
  255. { type: "process", command: "diagnostic" },
  256. { type: "process", command: "future-output" },
  257. ],
  258. },
  259. ],
  260. },
  261. maxOutputBytes: 4096,
  262. timeoutMs: 1000,
  263. },
  264. executionPort: executionPortFrom(async () => completed(outputs[callCount++] ?? "")),
  265. getWorkingDirectory: () => "/workspace",
  266. });
  267. const result = await runner!.run(cases[0]!.input, { matchValue: "startup" });
  268. expect(callCount).toBe(2);
  269. expect(result.additionalContexts).toEqual([]);
  270. });
  271. it("backgrounds async command hooks and ignores their decisions", async () => {
  272. const gate = Promise.withResolvers<ExecutionResult>();
  273. const started = Promise.withResolvers<void>();
  274. const events: SessionEvent[] = [];
  275. const runner = createConfiguredHookRunner({
  276. config: {
  277. enabled: true,
  278. events: {
  279. SessionStart: [{ hooks: [{ type: "command", command: "async-hook", async: true }] }],
  280. },
  281. maxOutputBytes: 4096,
  282. timeoutMs: 1000,
  283. },
  284. emitEvent: async (event) => {
  285. events.push(event);
  286. },
  287. executionPort: executionPortFrom(async () => {
  288. started.resolve();
  289. return gate.promise;
  290. }),
  291. getWorkingDirectory: () => "/workspace",
  292. });
  293. const result = await runner!.run(cases[0]!.input, { matchValue: "startup" });
  294. expect(result.additionalContexts).toEqual([]);
  295. await started.promise;
  296. gate.resolve(completed(JSON.stringify({ decision: "block", reason: "too late" })));
  297. await vi.waitFor(() => {
  298. expect(events.map((event) => event.type)).toContain(SessionEventType.HookRunCompleted);
  299. });
  300. expect(events.map((event) => event.type)).not.toContain(SessionEventType.HookRunBlocked);
  301. });
  302. it("cancels background async command hooks with the caller signal", async () => {
  303. const started = Promise.withResolvers<AbortSignal>();
  304. const events: SessionEvent[] = [];
  305. const runner = createConfiguredHookRunner({
  306. config: {
  307. enabled: true,
  308. events: {
  309. SessionStart: [{ hooks: [{ type: "command", command: "async-hook", async: true }] }],
  310. },
  311. maxOutputBytes: 4096,
  312. timeoutMs: 1000,
  313. },
  314. emitEvent: async (event) => {
  315. events.push(event);
  316. },
  317. executionPort: executionPortFrom(async (_request, options) => {
  318. const signal = options?.signal;
  319. expect(signal).toBeDefined();
  320. started.resolve(signal!);
  321. return new Promise<ExecutionResult>((_resolve, reject) => {
  322. signal!.addEventListener("abort", () => reject(new Error("execution aborted")), {
  323. once: true,
  324. });
  325. });
  326. }),
  327. getWorkingDirectory: () => "/workspace",
  328. });
  329. const controller = new AbortController();
  330. const result = await runner!.run(cases[0]!.input, {
  331. matchValue: "startup",
  332. signal: controller.signal,
  333. });
  334. expect(result.additionalContexts).toEqual([]);
  335. const executionSignal = await started.promise;
  336. controller.abort("turn cancelled");
  337. await vi.waitFor(() => {
  338. expect(events).toContainEqual(
  339. expect.objectContaining({
  340. type: SessionEventType.HookRunFailed,
  341. payload: expect.objectContaining({ outcome: "cancelled" }),
  342. }),
  343. );
  344. });
  345. expect(executionSignal.aborted).toBe(true);
  346. });
  347. });
  348. function getMatchValue(input: HookInput): string | undefined {
  349. if ("toolName" in input) return input.toolName;
  350. if (input.hookEventName === HookEventName.SessionStart) return input.source;
  351. return undefined;
  352. }
  353. function toolInput(
  354. event: typeof HookEventName.PreToolUse,
  355. ): Extract<HookInput, { hookEventName: "PreToolUse" }>;
  356. function toolInput(
  357. event: typeof HookEventName.PermissionRequest,
  358. ): Omit<Extract<HookInput, { hookEventName: "PermissionRequest" }>, "reason" | "requestId">;
  359. function toolInput(
  360. event: typeof HookEventName.PostToolUse,
  361. ): Omit<Extract<HookInput, { hookEventName: "PostToolUse" }>, "toolResponse" | "toolResultPreview">;
  362. function toolInput(
  363. event: typeof HookEventName.PostToolUseFailure,
  364. ): Omit<Extract<HookInput, { hookEventName: "PostToolUseFailure" }>, "error">;
  365. function toolInput(event: HookEventName): HookInput {
  366. return {
  367. ...base,
  368. hookEventName: event,
  369. riskLevel: "medium",
  370. sideEffectScope: "workspace",
  371. toolCallId: createToolCallId("hook-call"),
  372. toolInput: { path: "a.ts" },
  373. toolName: "Write",
  374. } as HookInput;
  375. }
  376. function eventContext(event: HookEventName, additionalContext: string): HookJSONOutput {
  377. return { hookSpecificOutput: { hookEventName: event, additionalContext } as never };
  378. }
  379. function executionPortReturning(
  380. output: HookJSONOutput,
  381. capture: (stdin: string) => Promise<void>,
  382. ): ExecutionPort {
  383. return executionPortFrom(async (request) => {
  384. await capture(String(request.stdin));
  385. return completed(JSON.stringify(output));
  386. });
  387. }
  388. function executionPortFrom(run: ExecutionPort["run"]): ExecutionPort {
  389. return { run };
  390. }
  391. function completed(stdout: string): ExecutionResult {
  392. const now = new Date();
  393. return {
  394. cancelled: false,
  395. completedAt: now,
  396. durationMs: 1,
  397. exitCode: 0,
  398. startedAt: now,
  399. status: "completed",
  400. stderr: { bytes: 0, text: "", truncated: false },
  401. stdout: { bytes: Buffer.byteLength(stdout), text: stdout, truncated: false },
  402. timedOut: false,
  403. };
  404. }