File size: 30,590 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 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 | /**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
import { HookRunner } from './hookRunner.js';
import {
HookEventName,
HookType,
ConfigSource,
type HookConfig,
type HookInput,
} from './types.js';
import type { Readable, Writable } from 'node:stream';
import type { Config } from '../config/config.js';
// Mock type for the child_process spawn
type MockChildProcessWithoutNullStreams = ChildProcessWithoutNullStreams & {
mockStdoutOn: ReturnType<typeof vi.fn>;
mockStderrOn: ReturnType<typeof vi.fn>;
mockProcessOn: ReturnType<typeof vi.fn>;
};
// Mock child_process with importOriginal for partial mocking
vi.mock('node:child_process', async (importOriginal) => {
const actual = await importOriginal();
return {
...(actual as object),
spawn: vi.fn(),
};
});
// 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,
}));
// Mock console methods
const mockConsole = {
log: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
debug: vi.fn(),
};
vi.stubGlobal('console', mockConsole);
describe('HookRunner', () => {
let hookRunner: HookRunner;
let mockSpawn: MockChildProcessWithoutNullStreams;
let mockConfig: Config;
const mockInput: HookInput = {
session_id: 'test-session',
transcript_path: '/path/to/transcript',
cwd: '/test/project',
hook_event_name: 'BeforeTool',
timestamp: '2025-01-01T00:00:00.000Z',
};
beforeEach(() => {
vi.resetAllMocks();
mockConfig = {
isTrustedFolder: vi.fn().mockReturnValue(true),
sanitizationConfig: {
enableEnvironmentVariableRedaction: true,
},
storage: {
getPlansDir: vi.fn().mockReturnValue('/test/project/plans'),
},
} as unknown as Config;
hookRunner = new HookRunner(mockConfig);
// Mock spawn with accessible mock functions
const mockStdoutOn = vi.fn();
const mockStderrOn = vi.fn();
const mockProcessOn = vi.fn();
mockSpawn = {
stdin: {
write: vi.fn(),
end: vi.fn(),
on: vi.fn(),
} as unknown as Writable,
stdout: {
on: mockStdoutOn,
} as unknown as Readable,
stderr: {
on: mockStderrOn,
} as unknown as Readable,
on: mockProcessOn,
kill: vi.fn(),
killed: false,
mockStdoutOn,
mockStderrOn,
mockProcessOn,
} as unknown as MockChildProcessWithoutNullStreams;
vi.mocked(spawn).mockReturnValue(mockSpawn);
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('executeHook', () => {
describe('security checks', () => {
it('should block project hooks in untrusted folders', async () => {
vi.mocked(mockConfig.isTrustedFolder).mockReturnValue(false);
const projectHookConfig: HookConfig = {
type: HookType.Command,
command: './hooks/test.sh',
source: ConfigSource.Project,
};
const result = await hookRunner.executeHook(
projectHookConfig,
HookEventName.BeforeTool,
mockInput,
);
expect(result.success).toBe(false);
expect(result.error?.message).toContain(
'Security: Blocked execution of project hook in untrusted folder',
);
expect(mockDebugLogger.warn).toHaveBeenCalledWith(
expect.stringContaining('Security: Blocked execution'),
);
expect(spawn).not.toHaveBeenCalled();
});
it('should allow project hooks in trusted folders', async () => {
vi.mocked(mockConfig.isTrustedFolder).mockReturnValue(true);
const projectHookConfig: HookConfig = {
type: HookType.Command,
command: './hooks/test.sh',
source: ConfigSource.Project,
};
// Mock successful execution
mockSpawn.mockProcessOn.mockImplementation(
(event: string, callback: (code: number) => void) => {
if (event === 'close') {
setTimeout(() => callback(0), 10);
}
},
);
const result = await hookRunner.executeHook(
projectHookConfig,
HookEventName.BeforeTool,
mockInput,
);
expect(result.success).toBe(true);
expect(spawn).toHaveBeenCalled();
});
it('should allow non-project hooks even in untrusted folders', async () => {
vi.mocked(mockConfig.isTrustedFolder).mockReturnValue(false);
const systemHookConfig: HookConfig = {
type: HookType.Command,
command: './hooks/test.sh',
source: ConfigSource.System,
};
// Mock successful execution
mockSpawn.mockProcessOn.mockImplementation(
(event: string, callback: (code: number) => void) => {
if (event === 'close') {
setTimeout(() => callback(0), 10);
}
},
);
const result = await hookRunner.executeHook(
systemHookConfig,
HookEventName.BeforeTool,
mockInput,
);
expect(result.success).toBe(true);
expect(spawn).toHaveBeenCalled();
});
});
describe('command hooks', () => {
const commandConfig: HookConfig = {
type: HookType.Command,
command: './hooks/test.sh',
timeout: 5000,
};
it('should execute command hook successfully', async () => {
const mockOutput = {
decision: 'allow',
reason: 'All good',
format: 'json',
};
// Mock successful execution
mockSpawn.mockStdoutOn.mockImplementation(
(event: string, callback: (data: Buffer) => void) => {
if (event === 'data') {
setImmediate(() =>
callback(Buffer.from(JSON.stringify(mockOutput))),
);
}
},
);
mockSpawn.mockProcessOn.mockImplementation(
(event: string, callback: (code: number) => void) => {
if (event === 'close') {
setImmediate(() => callback(0));
}
},
);
const result = await hookRunner.executeHook(
commandConfig,
HookEventName.BeforeTool,
mockInput,
);
expect(result.success).toBe(true);
expect(result.output).toEqual(mockOutput);
expect(result.exitCode).toBe(0);
expect(mockSpawn.stdin.write).toHaveBeenCalledWith(
JSON.stringify(mockInput),
);
});
it('should handle command hook failure', async () => {
const errorMessage = 'Command failed';
mockSpawn.mockStderrOn.mockImplementation(
(event: string, callback: (data: Buffer) => void) => {
if (event === 'data') {
setImmediate(() => callback(Buffer.from(errorMessage)));
}
},
);
mockSpawn.mockProcessOn.mockImplementation(
(event: string, callback: (code: number) => void) => {
if (event === 'close') {
setImmediate(() => callback(1));
}
},
);
const result = await hookRunner.executeHook(
commandConfig,
HookEventName.BeforeTool,
mockInput,
);
expect(result.success).toBe(false);
expect(result.exitCode).toBe(1);
expect(result.stderr).toBe(errorMessage);
});
it('should use hook name in error messages if available', async () => {
const namedConfig: HookConfig = {
name: 'my-friendly-hook',
type: HookType.Command,
command: './hooks/fail.sh',
};
// Mock error during spawn
vi.mocked(spawn).mockImplementationOnce(() => {
throw new Error('Spawn error');
});
await hookRunner.executeHook(
namedConfig,
HookEventName.BeforeTool,
mockInput,
);
expect(mockDebugLogger.warn).toHaveBeenCalledWith(
expect.stringContaining(
'(hook: my-friendly-hook): Error: Spawn error',
),
);
});
it('should handle command hook timeout', async () => {
const shortTimeoutConfig: HookConfig = {
type: HookType.Command,
command: './hooks/slow.sh',
timeout: 50, // Very short timeout for testing
};
let closeCallback: ((code: number) => void) | undefined;
let killWasCalled = false;
// Mock a hanging process that registers the close handler but doesn't call it initially
mockSpawn.mockProcessOn.mockImplementation(
(event: string, callback: (code: number) => void) => {
if (event === 'close') {
closeCallback = callback; // Store the callback but don't call it yet
}
},
);
// Mock the kill method to simulate the process being killed
mockSpawn.kill = vi.fn().mockImplementation((_signal: string) => {
killWasCalled = true;
// Simulate that killing the process triggers the close event
if (closeCallback) {
setImmediate(() => {
closeCallback!(128); // Exit code 128 indicates process was killed by signal
});
}
return true;
});
const result = await hookRunner.executeHook(
shortTimeoutConfig,
HookEventName.BeforeTool,
mockInput,
);
expect(result.success).toBe(false);
expect(killWasCalled).toBe(true);
expect(result.error?.message).toContain('timed out');
expect(mockSpawn.kill).toHaveBeenCalledWith('SIGTERM');
});
it('should expand environment variables in commands', async () => {
const configWithEnvVar: HookConfig = {
type: HookType.Command,
command: '$GEMINI_PROJECT_DIR/hooks/test.sh',
};
mockSpawn.mockProcessOn.mockImplementation(
(event: string, callback: (code: number) => void) => {
if (event === 'close') {
setImmediate(() => callback(0));
}
},
);
await hookRunner.executeHook(
configWithEnvVar,
HookEventName.BeforeTool,
mockInput,
);
expect(spawn).toHaveBeenCalledWith(
expect.stringMatching(/bash|pwsh|powershell/),
expect.arrayContaining([
expect.stringMatching(/['"]?\/test\/project['"]?\/hooks\/test\.sh/),
]),
expect.objectContaining({
shell: false,
env: expect.objectContaining({
GEMINI_PROJECT_DIR: '/test/project',
GEMINI_PLANS_DIR: '/test/project/plans',
GEMINI_CWD: '/test/project',
GEMINI_SESSION_ID: 'test-session',
CLAUDE_PROJECT_DIR: '/test/project',
}),
}),
);
});
it('should expand and escape GEMINI_PLANS_DIR in commands', async () => {
const configWithEnvVar: HookConfig = {
type: HookType.Command,
command: 'ls $GEMINI_PLANS_DIR',
};
// Change plans dir to one with spaces
vi.mocked(mockConfig.storage.getPlansDir).mockReturnValue(
'/test/project/plans with spaces',
);
mockSpawn.mockProcessOn.mockImplementation(
(event: string, callback: (code: number) => void) => {
if (event === 'close') {
setImmediate(() => callback(0));
}
},
);
await hookRunner.executeHook(
configWithEnvVar,
HookEventName.BeforeTool,
mockInput,
);
expect(spawn).toHaveBeenCalledWith(
expect.stringMatching(/bash|pwsh|powershell/),
expect.arrayContaining([
expect.stringMatching(
/ls ['"]\/test\/project\/plans with spaces['"]/,
),
]),
expect.any(Object),
);
});
it('should not allow command injection via GEMINI_PROJECT_DIR', async () => {
const maliciousCwd = '/test/project; echo "pwned" > /tmp/pwned';
const mockMaliciousInput: HookInput = {
...mockInput,
cwd: maliciousCwd,
};
const config: HookConfig = {
type: HookType.Command,
command: 'ls $GEMINI_PROJECT_DIR',
};
// Mock the process closing immediately
mockSpawn.mockProcessOn.mockImplementation(
(event: string, callback: (code: number) => void) => {
if (event === 'close') {
setImmediate(() => callback(0));
}
},
);
await hookRunner.executeHook(
config,
HookEventName.BeforeTool,
mockMaliciousInput,
);
// If secure, spawn will be called with the shell executable and escaped command
expect(spawn).toHaveBeenCalledWith(
expect.stringMatching(/bash|pwsh|powershell/),
expect.arrayContaining([
expect.stringMatching(/ls (['"]).*echo.*pwned.*\1/),
]),
expect.objectContaining({ shell: false }),
);
});
});
});
describe('executeHooksParallel', () => {
it('should execute multiple hooks in parallel', async () => {
const configs: HookConfig[] = [
{ type: HookType.Command, command: './hook1.sh' },
{ type: HookType.Command, command: './hook2.sh' },
];
// Mock both commands to succeed
mockSpawn.mockProcessOn.mockImplementation(
(event: string, callback: (code: number) => void) => {
if (event === 'close') {
setImmediate(() => callback(0));
}
},
);
const results = await hookRunner.executeHooksParallel(
configs,
HookEventName.BeforeTool,
mockInput,
);
expect(results).toHaveLength(2);
expect(results.every((r) => r.success)).toBe(true);
expect(spawn).toHaveBeenCalledTimes(2);
});
it('should call onHookStart and onHookEnd callbacks', async () => {
const configs: HookConfig[] = [
{ name: 'hook1', type: HookType.Command, command: './hook1.sh' },
];
mockSpawn.mockProcessOn.mockImplementation(
(event: string, callback: (code: number) => void) => {
if (event === 'close') {
setImmediate(() => callback(0));
}
},
);
const onStart = vi.fn();
const onEnd = vi.fn();
await hookRunner.executeHooksParallel(
configs,
HookEventName.BeforeTool,
mockInput,
onStart,
onEnd,
);
expect(onStart).toHaveBeenCalledWith(configs[0], 0);
expect(onEnd).toHaveBeenCalledWith(
configs[0],
expect.objectContaining({ success: true }),
);
});
it('should handle mixed success and failure', async () => {
const configs: HookConfig[] = [
{ type: HookType.Command, command: './hook1.sh' },
{ type: HookType.Command, command: './hook2.sh' },
];
let callCount = 0;
mockSpawn.mockProcessOn.mockImplementation(
(event: string, callback: (code: number) => void) => {
if (event === 'close') {
const exitCode = callCount++ === 0 ? 0 : 1; // First succeeds, second fails
setImmediate(() => callback(exitCode));
}
},
);
const results = await hookRunner.executeHooksParallel(
configs,
HookEventName.BeforeTool,
mockInput,
);
expect(results).toHaveLength(2);
expect(results[0].success).toBe(true);
expect(results[1].success).toBe(false);
});
});
describe('executeHooksSequential', () => {
it('should execute multiple hooks in sequence', async () => {
const configs: HookConfig[] = [
{ type: HookType.Command, command: './hook1.sh' },
{ type: HookType.Command, command: './hook2.sh' },
];
const executionOrder: string[] = [];
// Mock both commands to succeed
mockSpawn.mockProcessOn.mockImplementation(
(event: string, callback: (code: number) => void) => {
if (event === 'close') {
const args = vi.mocked(spawn).mock.calls[
executionOrder.length
][1] as string[];
let command = args[args.length - 1];
// On Windows, the command is wrapped in PowerShell syntax
if (command.includes('; if ($LASTEXITCODE -ne 0)')) {
command = command.split(';')[0];
}
executionOrder.push(command);
setImmediate(() => callback(0));
}
},
);
const results = await hookRunner.executeHooksSequential(
configs,
HookEventName.BeforeTool,
mockInput,
);
expect(results).toHaveLength(2);
expect(results.every((r) => r.success)).toBe(true);
expect(spawn).toHaveBeenCalledTimes(2);
// Verify they were called sequentially
expect(executionOrder).toEqual(['./hook1.sh', './hook2.sh']);
});
it('should call onHookStart and onHookEnd callbacks sequentially', async () => {
const configs: HookConfig[] = [
{ name: 'hook1', type: HookType.Command, command: './hook1.sh' },
{ name: 'hook2', type: HookType.Command, command: './hook2.sh' },
];
mockSpawn.mockProcessOn.mockImplementation(
(event: string, callback: (code: number) => void) => {
if (event === 'close') {
setImmediate(() => callback(0));
}
},
);
const onStart = vi.fn();
const onEnd = vi.fn();
await hookRunner.executeHooksSequential(
configs,
HookEventName.BeforeTool,
mockInput,
onStart,
onEnd,
);
expect(onStart).toHaveBeenCalledTimes(2);
expect(onEnd).toHaveBeenCalledTimes(2);
expect(onStart).toHaveBeenNthCalledWith(1, configs[0], 0);
expect(onStart).toHaveBeenNthCalledWith(2, configs[1], 1);
});
it('should continue execution even if a hook fails', async () => {
const configs: HookConfig[] = [
{ type: HookType.Command, command: './hook1.sh' },
{ type: HookType.Command, command: './hook2.sh' },
{ type: HookType.Command, command: './hook3.sh' },
];
let callCount = 0;
mockSpawn.mockStderrOn.mockImplementation(
(event: string, callback: (data: Buffer) => void) => {
if (event === 'data' && callCount === 1) {
// Second hook fails
setImmediate(() => callback(Buffer.from('Hook 2 failed')));
}
},
);
mockSpawn.mockProcessOn.mockImplementation(
(event: string, callback: (code: number) => void) => {
if (event === 'close') {
const exitCode = callCount++ === 1 ? 1 : 0; // Second fails, others succeed
setImmediate(() => callback(exitCode));
}
},
);
const results = await hookRunner.executeHooksSequential(
configs,
HookEventName.BeforeTool,
mockInput,
);
expect(results).toHaveLength(3);
expect(results[0].success).toBe(true);
expect(results[1].success).toBe(false);
expect(results[2].success).toBe(true);
expect(spawn).toHaveBeenCalledTimes(3);
});
it('should pass modified input from one hook to the next for BeforeAgent', async () => {
const configs: HookConfig[] = [
{ type: HookType.Command, command: './hook1.sh' },
{ type: HookType.Command, command: './hook2.sh' },
];
const mockBeforeAgentInput = {
...mockInput,
prompt: 'Original prompt',
};
const mockOutput1 = {
decision: 'allow' as const,
hookSpecificOutput: {
additionalContext: 'Context from hook 1',
},
format: 'json',
};
let hookCallCount = 0;
mockSpawn.mockStdoutOn.mockImplementation(
(event: string, callback: (data: Buffer) => void) => {
if (event === 'data') {
if (hookCallCount === 0) {
setImmediate(() =>
callback(Buffer.from(JSON.stringify(mockOutput1))),
);
}
}
},
);
mockSpawn.mockProcessOn.mockImplementation(
(event: string, callback: (code: number) => void) => {
if (event === 'close') {
hookCallCount++;
setImmediate(() => callback(0));
}
},
);
const results = await hookRunner.executeHooksSequential(
configs,
HookEventName.BeforeAgent,
mockBeforeAgentInput,
);
expect(results).toHaveLength(2);
expect(results[0].success).toBe(true);
expect(results[0].output).toEqual(mockOutput1);
// Verify that the second hook received modified input
const secondHookInput = JSON.parse(
vi.mocked(mockSpawn.stdin.write).mock.calls[1][0],
);
expect(secondHookInput.prompt).toContain('Original prompt');
expect(secondHookInput.prompt).toContain('Context from hook 1');
});
it('should pass modified LLM request from one hook to the next for BeforeModel', async () => {
const configs: HookConfig[] = [
{ type: HookType.Command, command: './hook1.sh' },
{ type: HookType.Command, command: './hook2.sh' },
];
const mockBeforeModelInput = {
...mockInput,
llm_request: {
model: 'gemini-1.5-pro',
messages: [{ role: 'user', content: 'Hello' }],
},
};
const mockOutput1 = {
decision: 'allow' as const,
hookSpecificOutput: {
llm_request: {
temperature: 0.7,
},
},
};
let hookCallCount = 0;
mockSpawn.mockStdoutOn.mockImplementation(
(event: string, callback: (data: Buffer) => void) => {
if (event === 'data') {
if (hookCallCount === 0) {
setImmediate(() =>
callback(Buffer.from(JSON.stringify(mockOutput1))),
);
}
}
},
);
mockSpawn.mockProcessOn.mockImplementation(
(event: string, callback: (code: number) => void) => {
if (event === 'close') {
hookCallCount++;
setImmediate(() => callback(0));
}
},
);
const results = await hookRunner.executeHooksSequential(
configs,
HookEventName.BeforeModel,
mockBeforeModelInput,
);
expect(results).toHaveLength(2);
expect(results[0].success).toBe(true);
// Verify that the second hook received modified input
const secondHookInput = JSON.parse(
vi.mocked(mockSpawn.stdin.write).mock.calls[1][0],
);
expect(secondHookInput.llm_request.model).toBe('gemini-1.5-pro');
expect(secondHookInput.llm_request.temperature).toBe(0.7);
});
it('should not modify input if hook fails', async () => {
const configs: HookConfig[] = [
{ type: HookType.Command, command: './hook1.sh' },
{ type: HookType.Command, command: './hook2.sh' },
];
mockSpawn.mockStderrOn.mockImplementation(
(event: string, callback: (data: Buffer) => void) => {
if (event === 'data') {
setImmediate(() => callback(Buffer.from('Hook failed')));
}
},
);
mockSpawn.mockProcessOn.mockImplementation(
(event: string, callback: (code: number) => void) => {
if (event === 'close') {
setImmediate(() => callback(1)); // All hooks fail
}
},
);
const results = await hookRunner.executeHooksSequential(
configs,
HookEventName.BeforeTool,
mockInput,
);
expect(results).toHaveLength(2);
expect(results.every((r) => !r.success)).toBe(true);
// Verify that both hooks received the same original input
const firstHookInput = JSON.parse(
vi.mocked(mockSpawn.stdin.write).mock.calls[0][0],
);
const secondHookInput = JSON.parse(
vi.mocked(mockSpawn.stdin.write).mock.calls[1][0],
);
expect(firstHookInput).toEqual(secondHookInput);
});
});
describe('invalid JSON handling', () => {
const commandConfig: HookConfig = {
type: HookType.Command,
command: './hooks/test.sh',
};
it('should handle invalid JSON output gracefully', async () => {
const invalidJson = '{ "decision": "allow", incomplete';
mockSpawn.mockStdoutOn.mockImplementation(
(event: string, callback: (data: Buffer) => void) => {
if (event === 'data') {
setImmediate(() => callback(Buffer.from(invalidJson)));
}
},
);
mockSpawn.mockProcessOn.mockImplementation(
(event: string, callback: (code: number) => void) => {
if (event === 'close') {
setImmediate(() => callback(0));
}
},
);
const result = await hookRunner.executeHook(
commandConfig,
HookEventName.BeforeTool,
mockInput,
);
expect(result.success).toBe(true);
expect(result.exitCode).toBe(0);
// Should convert plain text to structured output
expect(result.outputFormat).toBe('text');
expect(result.output).toEqual({
decision: 'allow',
systemMessage: invalidJson,
});
});
it('should handle malformed JSON with exit code 0', async () => {
const malformedJson = 'not json at all';
mockSpawn.mockStdoutOn.mockImplementation(
(event: string, callback: (data: Buffer) => void) => {
if (event === 'data') {
setImmediate(() => callback(Buffer.from(malformedJson)));
}
},
);
mockSpawn.mockProcessOn.mockImplementation(
(event: string, callback: (code: number) => void) => {
if (event === 'close') {
setImmediate(() => callback(0));
}
},
);
const result = await hookRunner.executeHook(
commandConfig,
HookEventName.BeforeTool,
mockInput,
);
expect(result.success).toBe(true);
expect(result.outputFormat).toBe('text');
expect(result.output).toEqual({
decision: 'allow',
systemMessage: malformedJson,
});
});
it('should handle invalid JSON with exit code 1 (non-blocking error)', async () => {
const invalidJson = '{ broken json';
mockSpawn.mockStderrOn.mockImplementation(
(event: string, callback: (data: Buffer) => void) => {
if (event === 'data') {
setImmediate(() => callback(Buffer.from(invalidJson)));
}
},
);
mockSpawn.mockProcessOn.mockImplementation(
(event: string, callback: (code: number) => void) => {
if (event === 'close') {
setImmediate(() => callback(1));
}
},
);
const result = await hookRunner.executeHook(
commandConfig,
HookEventName.BeforeTool,
mockInput,
);
expect(result.success).toBe(false);
expect(result.exitCode).toBe(1);
expect(result.outputFormat).toBe('text');
expect(result.output).toEqual({
decision: 'allow',
systemMessage: `Warning: ${invalidJson}`,
});
});
it('should handle invalid JSON with exit code 2 (blocking error)', async () => {
const invalidJson = '{ "error": incomplete';
mockSpawn.mockStderrOn.mockImplementation(
(event: string, callback: (data: Buffer) => void) => {
if (event === 'data') {
setImmediate(() => callback(Buffer.from(invalidJson)));
}
},
);
mockSpawn.mockProcessOn.mockImplementation(
(event: string, callback: (code: number) => void) => {
if (event === 'close') {
setImmediate(() => callback(2));
}
},
);
const result = await hookRunner.executeHook(
commandConfig,
HookEventName.BeforeTool,
mockInput,
);
expect(result.success).toBe(false);
expect(result.exitCode).toBe(2);
expect(result.outputFormat).toBe('text');
expect(result.output).toEqual({
decision: 'deny',
reason: invalidJson,
});
});
it('should handle empty JSON output', async () => {
mockSpawn.mockStdoutOn.mockImplementation(
(event: string, callback: (data: Buffer) => void) => {
if (event === 'data') {
setImmediate(() => callback(Buffer.from('')));
}
},
);
mockSpawn.mockProcessOn.mockImplementation(
(event: string, callback: (code: number) => void) => {
if (event === 'close') {
setImmediate(() => callback(0));
}
},
);
const result = await hookRunner.executeHook(
commandConfig,
HookEventName.BeforeTool,
mockInput,
);
expect(result.success).toBe(true);
expect(result.exitCode).toBe(0);
expect(result.output).toBeUndefined();
});
it('should handle double-encoded JSON string', async () => {
const mockOutput = {
decision: 'allow',
reason: 'All good',
format: 'json',
};
const doubleEncodedJson = JSON.stringify(JSON.stringify(mockOutput));
mockSpawn.mockStdoutOn.mockImplementation(
(event: string, callback: (data: Buffer) => void) => {
if (event === 'data') {
setImmediate(() => callback(Buffer.from(doubleEncodedJson)));
}
},
);
mockSpawn.mockProcessOn.mockImplementation(
(event: string, callback: (code: number) => void) => {
if (event === 'close') {
setImmediate(() => callback(0));
}
},
);
const result = await hookRunner.executeHook(
commandConfig,
HookEventName.BeforeTool,
mockInput,
);
expect(result.success).toBe(true);
expect(result.output).toEqual(mockOutput);
});
});
});
|