feat(hooks): remind agents to use semantic search before open searches
CI / CI configuration security checks (push) Successful in 2s
CI / Capabilities and shell quality (push) Successful in 16s
CI / Python tests and compilation (push) Successful in 29s
CI / QMD unit tests (push) Successful in 5s
CI / Build and inspect generated packages (push) Successful in 17s
CI / PowerShell tests on Ubuntu (push) Successful in 1m10s
CI / Installed client configuration smoke tests (push) Successful in 34s
CI / Bash integration and installation guards (push) Successful in 1m9s
CI / CI configuration security checks (push) Successful in 2s
CI / Capabilities and shell quality (push) Successful in 16s
CI / Python tests and compilation (push) Successful in 29s
CI / QMD unit tests (push) Successful in 5s
CI / Build and inspect generated packages (push) Successful in 17s
CI / PowerShell tests on Ubuntu (push) Successful in 1m10s
CI / Installed client configuration smoke tests (push) Successful in 34s
CI / Bash integration and installation guards (push) Successful in 1m9s
Add a PreToolUse hook (Show-SearchReminder/show-search-reminder.sh via agent-guards.py) that, once per session, reminds the agent to run semantic-search before the first open search. It fires on Grep/Glob and on shell search commands, never blocks, stays silent once the session ran qmd-search.mjs, and does nothing unless QMD is installed. Per-session markers are hashed and pruned after seven days. Claude matches Grep|Glob|Bash|PowerShell; Codex matches Bash. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
cb22d56539
commit
305bcdeb54
13 files changed
+146
-11
No files matched your search
@@ -1,4 +1,5 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
@@ -11,10 +12,10 @@ SCRIPTS = ROOT / 'shared/hooks/scripts'
|
||||
GUARDS = SCRIPTS / 'agent-guards.py'
|
||||
|
||||
|
||||
def guard(mode, event, cwd=None):
|
||||
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)
|
||||
encoding='utf-8', timeout=20, env=env)
|
||||
assert result.returncode == 0, result.stderr
|
||||
return result.stdout
|
||||
|
||||
@@ -86,11 +87,66 @@ class CorrectionPromptTests(unittest.TestCase):
|
||||
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'))
|
||||
(('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
|
||||
@@ -98,12 +154,14 @@ class EntryPointTests(unittest.TestCase):
|
||||
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)
|
||||
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', {}))
|
||||
|
||||
@@ -61,7 +61,7 @@ foreach ($shell in @('powershell','bash')) {
|
||||
if ($shell -eq 'powershell' -and $content -match 'WindowStyle\s+Hidden') { throw "PowerShell hook hides the terminal in $package" }
|
||||
if ($client -eq 'codex') {
|
||||
$events = @([regex]::Matches($content, '(?m)^\[\[hooks\.([^.\]]+)\]\]\s*$') | ForEach-Object { $_.Groups[1].Value })
|
||||
if ((($events | Sort-Object) -join ',') -ne 'PostToolUse,PreToolUse,SessionStart,Stop,Stop,Stop,UserPromptSubmit' -or $content -match 'flashbang-if-input' -or $content -match '(?m)^async\s*=\s*true\s*$') { throw "Codex finish hook is incorrect in $package" }
|
||||
if ((($events | Sort-Object) -join ',') -ne 'PostToolUse,PreToolUse,PreToolUse,SessionStart,Stop,Stop,Stop,UserPromptSubmit' -or $content -match 'flashbang-if-input' -or $content -match '(?m)^async\s*=\s*true\s*$') { throw "Codex finish hook is incorrect in $package" }
|
||||
if ($content -notmatch 'approvals_reviewer\s*=\s*"auto_review"') { throw "Codex auto review is missing in $package" }
|
||||
if ($content -notmatch '(?m)^sandbox_mode\s*=\s*"danger-full-access"\s*$') { throw "Codex full access is missing in $package" }
|
||||
if ($content -notmatch '(?m)^max_depth\s*=\s*1\s*$') { throw "Codex agent depth limit is missing in $package" }
|
||||
|
||||
@@ -80,7 +80,7 @@ for shell in powershell bash; do
|
||||
grep -q 'bash .*flashbang.sh' "$package/$file"
|
||||
fi
|
||||
if [ "$client" = codex ]; then
|
||||
[ "$(sed -n 's/^\[\[hooks\.\([^].]*\)\]\][[:space:]]*$/\1/p' "$package/$file" | sort)" = $'PostToolUse\nPreToolUse\nSessionStart\nStop\nStop\nStop\nUserPromptSubmit' ]
|
||||
[ "$(sed -n 's/^\[\[hooks\.\([^].]*\)\]\][[:space:]]*$/\1/p' "$package/$file" | sort)" = $'PostToolUse\nPreToolUse\nPreToolUse\nSessionStart\nStop\nStop\nStop\nUserPromptSubmit' ]
|
||||
! grep -q 'flashbang-if-input' "$package/$file"
|
||||
! grep -Eq '^async[[:space:]]*=[[:space:]]*true[[:space:]]*$' "$package/$file"
|
||||
grep -q 'approvals_reviewer[[:space:]]*=[[:space:]]*"auto_review"' "$package/$file"
|
||||
|
||||
Reference in new issue
Block a user