import json import os from pathlib import Path import shutil import subprocess import sys import tempfile import unittest ROOT = Path(__file__).resolve().parents[2] SCRIPTS = ROOT / 'shared/hooks/scripts' GUARDS = SCRIPTS / 'agent-guards.py' def guard(mode, event, cwd=None, env=None): payload = event if isinstance(event, str) else json.dumps(event) result = subprocess.run([sys.executable, str(GUARDS), mode], cwd=cwd, input=payload, capture_output=True, encoding='utf-8', timeout=20, env=env) assert result.returncode == 0, result.stderr return result.stdout def git(workspace, *args): subprocess.run(['git', '-C', str(workspace), *args], check=True, capture_output=True) class CompletionEvidenceTests(unittest.TestCase): def setUp(self): directory = tempfile.TemporaryDirectory() self.addCleanup(directory.cleanup) self.workspace = Path(directory.name) git(self.workspace, 'init', '--quiet') def event(self, message, **overrides): return dict({'cwd': str(self.workspace), 'stop_hook_active': False, 'last_assistant_message': message}, **overrides) def test_blocks_unbacked_claim_with_changed_code(self): (self.workspace / 'app.py').write_text('x = 1\n') for message in ('All done.', 'Fehler ist behoben.'): self.assertEqual(json.loads(guard('stop', self.event(message)))['decision'], 'block') def test_allows_other_stops(self): (self.workspace / 'app.py').write_text('x = 1\n') cases = (self.event('Done. Tests: 12 passed.'), self.event('Fertig, aber nicht getestet.'), self.event('Which option do you prefer?'), self.event('All done.', stop_hook_active=True)) for event in cases: self.assertEqual(guard('stop', event), '') def test_allows_clean_or_prose_only_workspace(self): self.assertEqual(guard('stop', self.event('All done.')), '') (self.workspace / 'notes.md').write_text('text\n') self.assertEqual(guard('stop', self.event('All done.')), '') def test_fails_open_on_malformed_events(self): for event in ('', 'not json', '[]', {'cwd': 7, 'last_assistant_message': 'done'}, {'cwd': str(self.workspace / 'missing'), 'last_assistant_message': 'done'}, {'cwd': str(self.workspace), 'last_assistant_message': None}): self.assertEqual(guard('stop', event, cwd=self.workspace), '') def test_does_not_run_repository_fsmonitor(self): marker = self.workspace / 'fsmonitor-ran' hook = self.workspace / 'monitor.py' hook.write_text(f'open({str(marker)!r}, "w")\n') git(self.workspace, 'config', 'core.fsmonitor', f'{Path(sys.executable).as_posix()} {hook.as_posix()}') guard('stop', self.event('All done.')) self.assertFalse(marker.exists()) class CorrectionPromptTests(unittest.TestCase): def test_flags_corrections(self): for prompt in ('Nein, nimm die andere Datei', 'das ist falsch', 'Er darf niemals pushen', "that's wrong", 'you forgot the tests', 'not what I asked', 'Schon wieder ohne Tests'): output = json.loads(guard('prompt', {'prompt': prompt}))['hookSpecificOutput'] self.assertEqual(output['hookEventName'], 'UserPromptSubmit') self.assertIn('approval', output['additionalContext']) def test_ignores_other_prompts(self): for prompt in ('Add a logout button', 'was würdest du mir stattdessen empfehlen?', '/nein', 'no' + ' x' * 1500, 'Der Test ist nicht grün'): self.assertEqual(guard('prompt', {'prompt': prompt}), '') def test_never_echoes_the_prompt(self): self.assertNotIn('geheim', guard('prompt', {'prompt': 'Nein, das Passwort geheim bleibt'})) def test_fails_open_on_malformed_events(self): for event in ('', 'not json', {}, {'prompt': 3}): self.assertEqual(guard('prompt', event), '') def fake_home(directory, qmd=True): home = Path(directory) if qmd: script = home / '.my-ai-configuration/qmd/qmd-search.mjs' script.parent.mkdir(parents=True) script.write_text('') return dict(os.environ, HOME=str(home), USERPROFILE=str(home)) class SearchReminderTests(unittest.TestCase): def setUp(self): directory = tempfile.TemporaryDirectory() self.addCleanup(directory.cleanup) self.home = Path(directory.name) self.env = fake_home(directory.name) def search(self, session='s1', tool='Grep', command=None, env=None): tool_input = {'command': command} if command is not None else {'pattern': 'x'} return guard('search', {'session_id': session, 'tool_name': tool, 'tool_input': tool_input}, env=env or self.env) def test_reminds_once_per_session(self): output = json.loads(self.search())['hookSpecificOutput'] self.assertEqual(output['hookEventName'], 'PreToolUse') self.assertIn('semantic-search', output['additionalContext']) self.assertEqual(self.search(tool='Glob'), '') self.assertIn('additionalContext', self.search(session='s2', tool='Bash', command='rg Tile')) self.assertNotIn('s1', ' '.join(p.name for p in (self.home / '.my-ai-configuration/state/search-reminder').iterdir())) def test_detects_shell_searches(self): searches = ('rg Tile', 'git grep -n x', 'find . -name "*.csproj"', 'grep -r xunit src', 'Get-ChildItem -Recurse -Filter *.csproj', 'Get-Content a.cs | Select-String Test', 'cd src && fd test') for index, command in enumerate(searches): with self.subTest(command=command): self.assertIn('additionalContext', self.search(f'shell{index}', 'PowerShell', command)) for index, command in enumerate(('git status', 'npm run find-tests', 'dotnet test', 'ls src')): with self.subTest(command=command): self.assertEqual(self.search(f'other{index}', 'Bash', command), '') def test_qmd_use_suppresses_reminder(self): query = 'node "$HOME/.my-ai-configuration/qmd/qmd-search.mjs" --query "Where are tests?" --top-k 5' self.assertEqual(self.search(tool='Bash', command=query), '') self.assertEqual(self.search(tool='Grep'), '') def test_silent_without_qmd(self): with tempfile.TemporaryDirectory() as directory: self.assertEqual(self.search(env=fake_home(directory, qmd=False)), '') def test_fails_open_on_malformed_events(self): for event in ('', 'not json', '[]', {'session_id': 3, 'tool_name': 'Grep', 'tool_input': {}}, {'session_id': 's', 'tool_name': 'Grep'}, {'session_id': 's', 'tool_name': 'Bash', 'tool_input': {'command': 7}}): self.assertEqual(guard('search', event, env=self.env), '') class EntryPointTests(unittest.TestCase): def test_shell_entry_points(self): shells = (('powershell', shutil.which('pwsh') or shutil.which('powershell'), 0), ('bash', shutil.which('bash'), 1)) names = ((('Show-CorrectionPrompt.ps1', 'show-correction-prompt.sh'), {'prompt': 'Nein, anders'}, 'additionalContext'), (('Check-CompletionEvidence.ps1', 'check-completion-evidence.sh'), None, 'decision'), (('Show-SearchReminder.ps1', 'show-search-reminder.sh'), {'session_id': 'entry', 'tool_name': 'Grep', 'tool_input': {'pattern': 'x'}}, 'additionalContext')) for shell, executable, index in shells: if not executable or (shell == 'bash' and sys.platform == 'win32'): continue with self.subTest(shell=shell), tempfile.TemporaryDirectory() as directory: workspace = Path(directory) git(workspace, 'init', '--quiet') (workspace / 'app.py').write_text('x = 1\n') env = fake_home(directory) for scripts, event, expected in names: event = event or {'cwd': str(workspace), 'last_assistant_message': 'All done.'} script = str(SCRIPTS / scripts[index]) command = ([executable, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', script] if shell == 'powershell' else [executable, script]) result = subprocess.run(command, input=json.dumps(event), capture_output=True, encoding='utf-8', timeout=30, env=env) self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(result.stderr, '') self.assertIn(expected, json.loads(result.stdout) | json.loads(result.stdout).get('hookSpecificOutput', {})) if __name__ == '__main__': unittest.main()