File size: 12,349 Bytes
7a1ad33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import { describe, it, expect, vi, beforeEach } from 'vitest';
import { HookPlanner } from './hookPlanner.js';
import type { HookRegistry, HookRegistryEntry } from './hookRegistry.js';
import { ConfigSource, HookEventName, HookType } from './types.js';

// Mock debugLogger using vi.hoisted
const mockDebugLogger = vi.hoisted(() => ({
  log: vi.fn(),
  warn: vi.fn(),
  error: vi.fn(),
  debug: vi.fn(),
}));

vi.mock('../utils/debugLogger.js', () => ({
  debugLogger: mockDebugLogger,
}));

describe('HookPlanner', () => {
  let hookPlanner: HookPlanner;
  let mockHookRegistry: HookRegistry;

  beforeEach(() => {
    vi.resetAllMocks();

    mockHookRegistry = {
      getHooksForEvent: vi.fn(),
    } as unknown as HookRegistry;

    hookPlanner = new HookPlanner(mockHookRegistry);
  });

  describe('createExecutionPlan', () => {
    it('should return empty plan when no hooks registered', () => {
      vi.mocked(mockHookRegistry.getHooksForEvent).mockReturnValue([]);

      const plan = hookPlanner.createExecutionPlan(HookEventName.BeforeTool);

      expect(plan).toBeNull();
    });

    it('should create plan for hooks without matchers', () => {
      const mockEntries: HookRegistryEntry[] = [
        {
          config: { type: HookType.Command, command: './hook1.sh' },
          source: ConfigSource.Project,
          eventName: HookEventName.BeforeTool,
          enabled: true,
        },
        {
          config: {
            type: HookType.Command,
            command: './test-hook.sh',
          },
          source: ConfigSource.User,
          eventName: HookEventName.BeforeTool,
          enabled: true,
        },
      ];

      vi.mocked(mockHookRegistry.getHooksForEvent).mockReturnValue(mockEntries);

      const plan = hookPlanner.createExecutionPlan(HookEventName.BeforeTool);

      expect(plan).not.toBeNull();
      expect(plan!.hookConfigs).toHaveLength(2);
      expect(plan!.hookConfigs[0].command).toBe('./hook1.sh');
      expect(plan!.hookConfigs[1].command).toBe('./test-hook.sh');
    });

    it('should filter hooks by tool name matcher', () => {
      const mockEntries: HookRegistryEntry[] = [
        {
          config: { type: HookType.Command, command: './edit_hook.sh' },
          source: ConfigSource.Project,
          eventName: HookEventName.BeforeTool,
          matcher: 'EditTool',
          enabled: true,
        },
        {
          config: { type: HookType.Command, command: './general_hook.sh' },
          source: ConfigSource.Project,
          eventName: HookEventName.BeforeTool,
          enabled: true,
        },
      ];

      vi.mocked(mockHookRegistry.getHooksForEvent).mockReturnValue(mockEntries);

      // Test with EditTool context
      const plan = hookPlanner.createExecutionPlan(HookEventName.BeforeTool, {
        toolName: 'EditTool',
      });

      expect(plan).not.toBeNull();
      expect(plan!.hookConfigs).toHaveLength(2); // Both should match (one specific, one general)
    });

    it('should filter hooks by regex matcher', () => {
      const mockEntries: HookRegistryEntry[] = [
        {
          config: { type: HookType.Command, command: './edit_hook.sh' },
          source: ConfigSource.Project,
          eventName: HookEventName.BeforeTool,
          matcher: 'Edit|Write',
          enabled: true,
        },
        {
          config: { type: HookType.Command, command: './read_hook.sh' },
          source: ConfigSource.Project,
          eventName: HookEventName.BeforeTool,
          matcher: 'ReadTool',
          enabled: true,
        },
      ];

      vi.mocked(mockHookRegistry.getHooksForEvent).mockReturnValue(mockEntries);

      // Test with EditTool - should match first hook
      const editPlan = hookPlanner.createExecutionPlan(
        HookEventName.BeforeTool,
        { toolName: 'EditTool' },
      );
      expect(editPlan).not.toBeNull();
      expect(editPlan!.hookConfigs).toHaveLength(1);
      expect(editPlan!.hookConfigs[0].command).toBe('./edit_hook.sh');

      // Test with WriteTool - should match first hook
      const writePlan = hookPlanner.createExecutionPlan(
        HookEventName.BeforeTool,
        { toolName: 'WriteTool' },
      );
      expect(writePlan).not.toBeNull();
      expect(writePlan!.hookConfigs).toHaveLength(1);
      expect(writePlan!.hookConfigs[0].command).toBe('./edit_hook.sh');

      // Test with ReadTool - should match second hook
      const readPlan = hookPlanner.createExecutionPlan(
        HookEventName.BeforeTool,
        { toolName: 'ReadTool' },
      );
      expect(readPlan).not.toBeNull();
      expect(readPlan!.hookConfigs).toHaveLength(1);
      expect(readPlan!.hookConfigs[0].command).toBe('./read_hook.sh');

      // Test with unmatched tool - should match no hooks
      const otherPlan = hookPlanner.createExecutionPlan(
        HookEventName.BeforeTool,
        { toolName: 'OtherTool' },
      );
      expect(otherPlan).toBeNull();
    });

    it('should handle wildcard matcher', () => {
      const mockEntries: HookRegistryEntry[] = [
        {
          config: { type: HookType.Command, command: './wildcard_hook.sh' },
          source: ConfigSource.Project,
          eventName: HookEventName.BeforeTool,
          matcher: '*',
          enabled: true,
        },
      ];

      vi.mocked(mockHookRegistry.getHooksForEvent).mockReturnValue(mockEntries);

      const plan = hookPlanner.createExecutionPlan(HookEventName.BeforeTool, {
        toolName: 'AnyTool',
      });

      expect(plan).not.toBeNull();
      expect(plan!.hookConfigs).toHaveLength(1);
    });

    it('should handle empty string matcher', () => {
      const mockEntries: HookRegistryEntry[] = [
        {
          config: {
            type: HookType.Command,
            command: './empty_matcher_hook.sh',
          },
          source: ConfigSource.Project,
          eventName: HookEventName.BeforeTool,
          matcher: '',
          enabled: true,
        },
      ];

      vi.mocked(mockHookRegistry.getHooksForEvent).mockReturnValue(mockEntries);

      const plan = hookPlanner.createExecutionPlan(HookEventName.BeforeTool, {
        toolName: 'AnyTool',
      });

      expect(plan).not.toBeNull();
      expect(plan!.hookConfigs).toHaveLength(1);
    });

    it('should handle invalid regex matcher gracefully', () => {
      const mockEntries: HookRegistryEntry[] = [
        {
          config: {
            type: HookType.Command,
            command: './invalid_regex_hook.sh',
          },
          source: ConfigSource.Project,
          eventName: HookEventName.BeforeTool,
          matcher: '[invalid-regex',
          enabled: true,
        },
      ];

      vi.mocked(mockHookRegistry.getHooksForEvent).mockReturnValue(mockEntries);

      // Should match when toolName exactly equals the invalid regex pattern
      const plan = hookPlanner.createExecutionPlan(HookEventName.BeforeTool, {
        toolName: '[invalid-regex',
      });

      expect(plan).not.toBeNull();
      expect(plan!.hookConfigs).toHaveLength(1); // Should fall back to exact match

      // Should not match when toolName doesn't exactly equal the pattern
      const planNoMatch = hookPlanner.createExecutionPlan(
        HookEventName.BeforeTool,
        {
          toolName: 'other-tool',
        },
      );

      expect(planNoMatch).toBeNull();
    });

    it('should deduplicate identical hooks', () => {
      const mockEntries: HookRegistryEntry[] = [
        {
          config: { type: HookType.Command, command: './same_hook.sh' },
          source: ConfigSource.Project,
          eventName: HookEventName.BeforeTool,
          enabled: true,
        },
        {
          config: { type: HookType.Command, command: './same_hook.sh' },
          source: ConfigSource.User,
          eventName: HookEventName.BeforeTool,
          enabled: true,
        },
        {
          config: {
            type: HookType.Command,
            command: './test-hook.sh',
          },
          source: ConfigSource.Project,
          eventName: HookEventName.BeforeTool,
          enabled: true,
        },
        {
          config: {
            type: HookType.Command,
            command: './test-hook.sh',
          },
          source: ConfigSource.User,
          eventName: HookEventName.BeforeTool,
          enabled: true,
        },
      ];

      vi.mocked(mockHookRegistry.getHooksForEvent).mockReturnValue(mockEntries);

      const plan = hookPlanner.createExecutionPlan(HookEventName.BeforeTool);

      expect(plan).not.toBeNull();
      expect(plan!.hookConfigs).toHaveLength(2); // Should be deduplicated to 2 unique hooks
      expect(mockDebugLogger.debug).toHaveBeenCalledWith(
        expect.stringContaining('Deduplicated hook'),
      );
    });

    it('should deduplicate based on both name and command', () => {
      const mockEntries: HookRegistryEntry[] = [
        {
          config: {
            name: 'hook1',
            type: HookType.Command,
            command: './same.sh',
          },
          source: ConfigSource.Project,
          eventName: HookEventName.BeforeTool,
          enabled: true,
        },
        {
          config: {
            name: 'hook1',
            type: HookType.Command,
            command: './same.sh',
          },
          source: ConfigSource.User,
          eventName: HookEventName.BeforeTool,
          enabled: true,
        }, // Same name, same command -> deduplicate
        {
          config: {
            name: 'hook2',
            type: HookType.Command,
            command: './same.sh',
          },
          source: ConfigSource.Project,
          eventName: HookEventName.BeforeTool,
          enabled: true,
        }, // Different name, same command -> distinct
        {
          config: {
            name: 'hook1',
            type: HookType.Command,
            command: './different.sh',
          },
          source: ConfigSource.Project,
          eventName: HookEventName.BeforeTool,
          enabled: true,
        }, // Same name, different command -> distinct
        {
          config: { type: HookType.Command, command: './no-name.sh' },
          source: ConfigSource.Project,
          eventName: HookEventName.BeforeTool,
          enabled: true,
        },
        {
          config: { type: HookType.Command, command: './no-name.sh' },
          source: ConfigSource.User,
          eventName: HookEventName.BeforeTool,
          enabled: true,
        }, // No name, same command -> deduplicate
      ];

      vi.mocked(mockHookRegistry.getHooksForEvent).mockReturnValue(mockEntries);

      const plan = hookPlanner.createExecutionPlan(HookEventName.BeforeTool);

      expect(plan).not.toBeNull();
      // hook1:same.sh (deduped), hook2:same.sh, hook1:different.sh, :no-name.sh (deduped)
      expect(plan!.hookConfigs).toHaveLength(4);
    });

    it('should match trigger for session events', () => {
      const mockEntries: HookRegistryEntry[] = [
        {
          config: { type: HookType.Command, command: './startup_hook.sh' },
          source: ConfigSource.Project,
          eventName: HookEventName.SessionStart,
          matcher: 'startup',
          enabled: true,
        },
        {
          config: { type: HookType.Command, command: './resume_hook.sh' },
          source: ConfigSource.Project,
          eventName: HookEventName.SessionStart,
          matcher: 'resume',
          enabled: true,
        },
      ];

      vi.mocked(mockHookRegistry.getHooksForEvent).mockReturnValue(mockEntries);

      // Test startup trigger
      const startupPlan = hookPlanner.createExecutionPlan(
        HookEventName.SessionStart,
        { trigger: 'startup' },
      );
      expect(startupPlan).not.toBeNull();
      expect(startupPlan!.hookConfigs).toHaveLength(1);
      expect(startupPlan!.hookConfigs[0].command).toBe('./startup_hook.sh');

      // Test resume trigger
      const resumePlan = hookPlanner.createExecutionPlan(
        HookEventName.SessionStart,
        { trigger: 'resume' },
      );
      expect(resumePlan).not.toBeNull();
      expect(resumePlan!.hookConfigs).toHaveLength(1);
      expect(resumePlan!.hookConfigs[0].command).toBe('./resume_hook.sh');
    });
  });
});