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
@@ -0,0 +1,10 @@
|
||||
[CmdletBinding()]
|
||||
param()
|
||||
# Best effort: without Python 3.11+ this hook is a silent no-op; doctor reports that case.
|
||||
try {
|
||||
$ErrorActionPreference = 'Stop'
|
||||
. (Join-Path $PSScriptRoot 'Resolve-Python.ps1')
|
||||
$python = Get-PythonCommand
|
||||
if ($python) { & $python.Path @($python.Arguments) (Join-Path $PSScriptRoot 'agent-guards.py') search 2>$null }
|
||||
} catch {}
|
||||
exit 0
|
||||
@@ -1,9 +1,11 @@
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
MAX_EVENT_BYTES = 1048576
|
||||
MAX_PROMPT_CHARS = 2000
|
||||
@@ -28,6 +30,16 @@ CORRECTION_CONTEXT = ('This prompt may correct you. If it reveals a durable rule
|
||||
'in one line and ask for approval. After approval, store it in the user\'s configuration repository: '
|
||||
'`shared/` for all clients, or `scripts/commands/add-instruction` for one client. Ask for the '
|
||||
'repository path if unknown. Never change instructions without approval.')
|
||||
QMD_SEARCH = '.my-ai-configuration/qmd/qmd-search.mjs'
|
||||
SEARCH_TOOLS = ('Grep', 'Glob')
|
||||
# shortcut: matches command text, not parsed shells; a wrapped or aliased search slips through, which only skips a reminder.
|
||||
SEARCH_COMMAND = re.compile(r'(?:^|[\s;&|(])(?:rg|grep|egrep|fgrep|findstr|find|fd|ag|ack|select-string|sls|git\s+grep|'
|
||||
r'(?:get-childitem|gci|ls|dir)\b[^|;&]*\s-(?:recurse|r)\b)(?=\s|$)', re.I)
|
||||
SEARCH_CONTEXT = ('Search reminder (once per session): for open searches - unknown locations or identifiers, behavior '
|
||||
'questions, discovery, or claims that something is absent - run `semantic-search` first: '
|
||||
'node "$HOME/' + QMD_SEARCH + '" --query "<full question>" --top-k 5. Known paths, symbols, and exact '
|
||||
'strings may use rg/Grep directly. An empty pattern search does not prove absence.')
|
||||
MARKER_MAX_AGE = 7 * 24 * 3600
|
||||
|
||||
|
||||
def read_event():
|
||||
@@ -65,8 +77,41 @@ def show_correction(event):
|
||||
print(json.dumps({'hookSpecificOutput': {'hookEventName': 'UserPromptSubmit', 'additionalContext': CORRECTION_CONTEXT}}))
|
||||
|
||||
|
||||
def search_marker(session):
|
||||
directory = Path.home() / '.my-ai-configuration/state/search-reminder'
|
||||
if any(part.is_symlink() for part in (directory.parent, directory)):
|
||||
raise OSError('Search reminder state path contains a link.')
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
return directory / hashlib.sha256(session.encode('utf-8')).hexdigest()[:32]
|
||||
|
||||
|
||||
def prune_markers(directory, now):
|
||||
for path in directory.iterdir():
|
||||
if path.is_file() and not path.is_symlink() and now - path.stat().st_mtime > MARKER_MAX_AGE:
|
||||
path.unlink()
|
||||
|
||||
|
||||
def remind_search(event):
|
||||
session, tool, tool_input = event.get('session_id'), event.get('tool_name'), event.get('tool_input')
|
||||
if not isinstance(session, str) or not session or not isinstance(tool_input, dict) or not (Path.home() / QMD_SEARCH).is_file():
|
||||
return
|
||||
command = tool_input.get('command') if tool in ('Bash', 'PowerShell') else None
|
||||
if not isinstance(command, str):
|
||||
command = ''
|
||||
used_qmd = 'qmd-search.mjs' in command
|
||||
if not used_qmd and tool not in SEARCH_TOOLS and not SEARCH_COMMAND.search(command):
|
||||
return
|
||||
marker = search_marker(session)
|
||||
if marker.is_symlink() or marker.exists():
|
||||
return
|
||||
prune_markers(marker.parent, time.time())
|
||||
marker.touch()
|
||||
if not used_qmd:
|
||||
print(json.dumps({'hookSpecificOutput': {'hookEventName': 'PreToolUse', 'additionalContext': SEARCH_CONTEXT}}))
|
||||
|
||||
|
||||
def main():
|
||||
handlers = {'stop': check_completion, 'prompt': show_correction}
|
||||
handlers = {'stop': check_completion, 'prompt': show_correction, 'search': remind_search}
|
||||
try:
|
||||
handlers[sys.argv[1]](read_event())
|
||||
except (IndexError, KeyError, ValueError, OSError, RecursionError, subprocess.SubprocessError):
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
set -uo pipefail
|
||||
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
|
||||
# Best effort: without Python 3.11+ this hook is a silent no-op; doctor reports that case.
|
||||
. "$script_dir/resolve-python.sh"
|
||||
if resolve_python; then run_python "$script_dir/agent-guards.py" search 2>/dev/null || true; fi
|
||||
Reference in new issue
Block a user