package file→ .shtukbase/packages/hooks/test/hooks.test.ts
test/hooks.test.ts
224 lines, 10.1 KB.
- import { afterEach, beforeEach, expect, test } from 'bun:test';
- import { spawnSync } from 'node:child_process';
- import {
- existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync,
- } from 'node:fs';
- import { tmpdir } from 'node:os';
- import { dirname, join } from 'node:path';
- const source = dirname(import.meta.dir);
- const norm = 'norms/rules/hooks/HK-R03.md';
- const gitEnv = { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' };
- let temp: string;
- let repo: string;
- let project: string;
- function git(...args: string[]): string {
- const result = spawnSync('git', args, { cwd: repo, env: gitEnv, encoding: 'utf8' });
- if (result.status !== 0) throw new Error(result.stderr || String(result.error));
- return result.stdout.trimEnd();
- }
- function write(file: string, content: string, mode?: number): void {
- mkdirSync(dirname(file), { recursive: true });
- writeFileSync(file, content, { mode });
- }
- function run(script: string, args: string[] = [], env: NodeJS.ProcessEnv = {}, input = '') {
- return spawnSync(process.execPath, [join(source, script), ...args], {
- cwd: project, input, encoding: 'utf8', env: { ...gitEnv, ...env }, timeout: 10_000,
- });
- }
- function requireSuccess(result: ReturnType<typeof run>): void {
- if (result.status !== 0) throw new Error(result.stderr || result.stdout || String(result.error));
- }
- const read = (file: string) => readFileSync(file, 'utf8');
- const settings = () => join(repo, '.claude/settings.json');
- const stubs = () => git('rev-parse', '--path-format=absolute', '--git-path', 'hooks');
- const blockCount = (file: string) => read(file).split('# >>> shtuk hook >>>').length - 1;
- beforeEach(() => {
- temp = mkdtempSync(join(realpathSync(tmpdir()), 'shtuk-hooks-'));
- repo = join(temp, 'repo');
- mkdirSync(repo);
- git('init', '-q');
- git('config', 'user.name', 'Hook Test');
- git('config', 'user.email', 'hooks@example.invalid');
- project = join(repo, 'workspace', 'projects', 'site');
- mkdirSync(join(project, '.shtukbase', 'packages'), { recursive: true });
- });
- afterEach(() => rmSync(temp, { recursive: true, force: true }));
- test('nested installs share one pair of stubs and one set of repo-level settings', () => {
- expect(run('installed.ts').status).toBe(1);
- requireSuccess(run('sync.ts'));
- for (const event of ['pre-commit', 'commit-msg']) {
- const file = join(stubs(), event);
- expect(blockCount(file)).toBe(1);
- expect(statSync(file).mode & 0o100).toBe(0o100);
- }
- expect(read(join(stubs(), 'commit-msg'))).toContain('shtuk hook commit-msg "$1"');
- const initialSettings = read(settings());
- project = join(repo, 'workspace', 'projects', 'cloud');
- mkdirSync(join(project, '.shtukbase'), { recursive: true });
- requireSuccess(run('sync.ts'));
- requireSuccess(run('installed.ts'));
- expect(read(settings())).toBe(initialSettings);
- const claude = JSON.parse(initialSettings);
- expect(Object.keys(claude.hooks)).toEqual(['SessionStart', 'PreToolUse', 'PostToolUse', 'Stop']);
- for (const [event, groups] of Object.entries(claude.hooks)) {
- expect(groups).toEqual([expect.objectContaining({
- hooks: [expect.objectContaining({ command: `shtuk hook agent:${event}` })],
- })]);
- }
- expect(existsSync(join(project, '.claude'))).toBe(false);
- requireSuccess(run('remove.ts'));
- expect(existsSync(join(stubs(), 'pre-commit'))).toBe(false);
- expect(existsSync(join(stubs(), 'commit-msg'))).toBe(false);
- expect(JSON.parse(read(settings()))).toEqual({});
- });
- test('foreign hooks and Claude entries survive sync and remove', () => {
- const file = join(stubs(), 'pre-commit');
- const foreign = '#!/bin/sh\nprintf "foreign\n"';
- write(file, foreign, 0o644);
- const otherHook = { type: 'command', command: 'other-command', timeout: 8 };
- const existing = {
- permissions: { allow: ['Read'] },
- hooks: {
- PreToolUse: [{
- matcher: 'Write', hooks: [
- otherHook, { type: 'command', command: 'bun "$CLAUDE_PROJECT_DIR/.shtukbase/packages/hooks/run.ts" PreToolUse' },
- ],
- }],
- },
- };
- write(settings(), JSON.stringify(existing));
- requireSuccess(run('sync.ts'));
- const synced = read(file);
- expect(synced.startsWith(foreign + '\n')).toBe(true);
- expect(blockCount(file)).toBe(1);
- expect(statSync(file).mode & 0o100).toBe(0o100);
- requireSuccess(run('sync.ts'));
- expect(read(file)).toBe(synced);
- requireSuccess(run('installed.ts'));
- writeFileSync(file, synced + synced.slice(foreign.length));
- expect(run('installed.ts').stdout).toContain('Git pre-commit');
- requireSuccess(run('sync.ts'));
- expect(read(file)).toBe(synced);
- const claude = JSON.parse(read(settings()));
- claude.hooks.PreToolUse.push(claude.hooks.PreToolUse[1]);
- write(settings(), JSON.stringify(claude));
- expect(run('installed.ts').stdout).toContain('PreToolUse of the package hooks stands 2 times');
- requireSuccess(run('sync.ts'));
- requireSuccess(run('remove.ts'));
- expect(read(file)).toBe(foreign);
- expect(statSync(file).mode & 0o111).toBe(0);
- existing.hooks.PreToolUse[0].hooks.pop();
- expect(JSON.parse(read(settings()))).toEqual(existing);
- });
- test('Git uses relative core.hooksPath and passes the commit message path', () => {
- git('config', 'core.hooksPath', 'custom hooks');
- expect(stubs()).toBe(join(repo, 'custom hooks'));
- write(join(stubs(), 'pre-commit'), '#!/bin/sh\nprintf "existing\n" >> "$HOOK_LOG"\ntest ! -e reject\n', 0o755);
- requireSuccess(run('sync.ts'));
- const log = join(temp, 'hook log');
- const bin = join(temp, 'bin');
- write(join(bin, 'shtuk'), '#!/bin/sh\nprintf "<%s>\n" "$@" >> "$HOOK_LOG"\n', 0o755);
- const commit = () => spawnSync('git', ['commit', '-qm', 'test hooks', '--allow-empty'], {
- cwd: repo, encoding: 'utf8', env: { ...gitEnv, HOOK_LOG: log, PATH: bin + ':' + gitEnv.PATH },
- });
- const result = commit();
- if (result.status !== 0) throw new Error(result.stderr);
- expect(read(log)).toBe('existing\n<hook>\n<pre-commit>\n<hook>\n<commit-msg>\n<.git/COMMIT_EDITMSG>\n');
- expect(existsSync(join(repo, '.git/hooks/pre-commit'))).toBe(false);
- write(join(repo, 'reject'), '');
- expect(commit().status).toBe(1);
- expect(read(log)).toEndWith('<.git/COMMIT_EDITMSG>\nexisting\n');
- });
- test('the .git file in a linked worktree selects its Claude settings', () => {
- git('commit', '-qm', 'initial', '--allow-empty');
- const worktree = join(temp, 'linked');
- git('worktree', 'add', '-qb', 'linked', worktree);
- project = join(worktree, 'project');
- mkdirSync(join(project, '.shtukbase'), { recursive: true });
- requireSuccess(run('sync.ts'));
- requireSuccess(run('installed.ts'));
- expect(existsSync(join(worktree, '.claude/settings.json'))).toBe(true);
- expect(existsSync(settings())).toBe(false);
- expect(existsSync(join(stubs(), 'pre-commit'))).toBe(true);
- });
- test('invalid Claude settings are kept intact', () => {
- write(settings(), '{broken');
- expect(run('sync.ts').status).toBe(1);
- expect(read(settings())).toBe('{broken');
- expect(existsSync(join(stubs(), 'pre-commit'))).toBe(false);
- });
- test('HK-R03 observes mixed owners by default and blocks in enforce mode', () => {
- symlinkSync(source, join(project, '.shtukbase/packages/hooks'), 'dir');
- const page = join(project, norm);
- const initial = read(join(source, 'pages', norm));
- write(page, initial);
- const files = 'apps/site/file.txt';
- const mixed = { [files]: 'site', 'cloud/file.txt': 'cloud', 'README.md': null };
- const observed = run('run.ts', ['pre-commit'], { SHTUK_FILES: files, SHTUK_OWNERS: JSON.stringify(mixed) });
- requireSuccess(observed);
- expect(observed.stdout).toContain('HK-R03');
- expect(observed.stdout).toContain('(cloud, site)');
- write(page, initial.replace('mode: observe', 'mode: enforce'));
- const blocked = run('run.ts', ['pre-commit'], { SHTUK_FILES: files, SHTUK_OWNERS: JSON.stringify(mixed) });
- expect(blocked.status).toBe(2);
- expect(blocked.stderr).toContain('HK-R03');
- const clean = run('run.ts', ['pre-commit'], {
- SHTUK_FILES: files, SHTUK_OWNERS: JSON.stringify({ ...mixed, 'cloud/file.txt': 'site' }),
- });
- requireSuccess(clean);
- expect(clean.stdout).toBe('');
- });
- test('except filters each Git hook independently and preserves unowned files and event args', () => {
- const pkg = join(project, '.shtukbase/packages/sample');
- write(join(pkg, 'package.md'), `---
- hooks:
- - {name: filtered, event: commit-msg, run: filtered.ts, norm: /norms/sample.md}
- - {name: all, event: commit-msg, run: all.ts}
- - {name: other-event, event: pre-commit, run: missing.ts}
- ---
- `);
- write(join(pkg, 'filtered.ts'), 'console.log(JSON.stringify([process.env.SHTUK_FILES, ...process.argv.slice(2)]))');
- write(join(pkg, 'all.ts'), 'console.log(JSON.stringify(["all", process.env.SHTUK_FILES]))');
- write(join(project, 'norms/sample.md'), '---\nexcept: [cloud]\n---\n');
- const args = ['commit-msg', 'path with spaces/COMMIT_EDITMSG'];
- const owners = JSON.stringify({ 'cloud/file': 'cloud', 'site/file': 'site', README: null });
- const files = 'cloud/file\nsite/file\nREADME';
- const result = run('run.ts', args, { SHTUK_FILES: files, SHTUK_OWNERS: owners, SHTUK_ROOT: repo });
- requireSuccess(result);
- expect(result.stdout.trim().split('\n\n').map((line) => JSON.parse(line))).toEqual([
- ['site/file\nREADME', join(repo, args[1])], ['all', files],
- ]);
- const skipped = run('run.ts', args, { SHTUK_FILES: 'cloud/file', SHTUK_OWNERS: owners });
- requireSuccess(skipped);
- expect(JSON.parse(skipped.stdout)).toEqual(['all', 'cloud/file']);
- });
- test('a dispatched Claude event uses the selected project and the original tool payload', () => {
- const pkg = join(project, '.shtukbase/packages/sample');
- write(join(pkg, 'package.md'), '---\nhooks: [{event: PreToolUse, tools: [Write], run: capture.ts}]\n---\n');
- write(join(pkg, 'capture.ts'), `
- const payload = await Bun.stdin.json();
- console.log(JSON.stringify([process.env.CLAUDE_PROJECT_DIR, payload]));
- `);
- const payload = { tool_name: 'Write', cwd: repo, tool_input: { file_path: 'note.md' } };
- const result = run('run.ts', ['agent:PreToolUse'], { CLAUDE_PROJECT_DIR: repo }, JSON.stringify(payload));
- requireSuccess(result);
- expect(JSON.parse(result.stdout)).toEqual([project, payload]);
- });