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>
123 lines
6.3 KiB
Python
123 lines
6.3 KiB
Python
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
|
|
PROSE_SUFFIXES = ('.md', '.mdx', '.rst', '.txt')
|
|
|
|
CLAIM = re.compile(r'\b(?:done|finished|completed?|fixed|implemented|resolved|works|fertig|erledigt|behoben|umgesetzt|'
|
|
r'funktioniert|implementiert|abgeschlossen)\b', re.I)
|
|
# shortcut: matches the wording, not real command output; parse each client's transcript if claims get faked.
|
|
EVIDENCE = re.compile(r'\b(?:tests?|builds?|lint\w*|typecheck\w*|compiled?|pass(?:ed|es)?|fail(?:ed|s|ures?)?|exit|'
|
|
r'verified|verification|not run|skipped|unverified|getestet|geprüft|ungeprüft|doctor|prüfung)\b', re.I)
|
|
CORRECTION = re.compile(r"^\s*(?:nein|nope|no|falsch|wrong)\b"
|
|
r"|\b(?:ist|war) (?:falsch|nicht richtig|nicht korrekt)\b|\b(?:stimmt|passt) nicht\b"
|
|
r"|\b(?:schon wieder|immer noch nicht|nicht so|so nicht|niemals|du sollst (?:nicht|doch)|"
|
|
r"(?:habe|hab|hatte) ich (?:doch )?gesagt|ich (?:sagte|hatte gesagt))\b"
|
|
r"|\b(?:that'?s (?:wrong|not right)|not what i (?:asked|wanted|said)|i (?:said|told you)|"
|
|
r"you (?:forgot|missed|ignored)|you (?:should|must) not|don'?t (?:do|use|add)|"
|
|
r"stop (?:doing|using|adding)|never)\b", re.I)
|
|
|
|
BLOCK_REASON = ('The last message claims completion for changed code but cites no check. Run the cheapest relevant check '
|
|
'and report its real result, or state plainly that it was not run and why.')
|
|
CORRECTION_CONTEXT = ('This prompt may correct you. If it reveals a durable rule rather than a one-off fix, propose that 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():
|
|
raw = '' if sys.stdin.isatty() else sys.stdin.buffer.read(MAX_EVENT_BYTES + 1).decode('utf-8-sig')
|
|
if len(raw) > MAX_EVENT_BYTES or not raw.strip():
|
|
return {}
|
|
event = json.loads(raw)
|
|
return event if isinstance(event, dict) else {}
|
|
|
|
|
|
def has_code_changes(workspace):
|
|
if not isinstance(workspace, str) or not Path(workspace).is_dir():
|
|
return False
|
|
# core.fsmonitor from a repository's config would otherwise run its command here.
|
|
status = subprocess.check_output(['git', '-c', 'core.fsmonitor=false', '-C', workspace, 'status', '--porcelain', '-z'],
|
|
stderr=subprocess.DEVNULL, timeout=3)
|
|
entries = status.decode('utf-8', 'replace').split('\0')
|
|
return any(entry and not entry.lower().endswith(PROSE_SUFFIXES) for entry in entries)
|
|
|
|
|
|
def check_completion(event):
|
|
message = event.get('last_assistant_message')
|
|
# stop_hook_active means this hook already pushed back once; a second block could loop forever.
|
|
if event.get('stop_hook_active') or not isinstance(message, str):
|
|
return
|
|
if CLAIM.search(message) and not EVIDENCE.search(message) and has_code_changes(event.get('cwd', os.getcwd())):
|
|
print(json.dumps({'decision': 'block', 'reason': BLOCK_REASON}))
|
|
|
|
|
|
def show_correction(event):
|
|
prompt = event.get('prompt')
|
|
if not isinstance(prompt, str) or len(prompt) > MAX_PROMPT_CHARS or prompt.lstrip().startswith('/'):
|
|
return
|
|
if CORRECTION.search(prompt):
|
|
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, 'search': remind_search}
|
|
try:
|
|
handlers[sys.argv[1]](read_event())
|
|
except (IndexError, KeyError, ValueError, OSError, RecursionError, subprocess.SubprocessError):
|
|
return
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|