import json 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): 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) 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), '') 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')) 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') 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) 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()