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) # Searches without qmd-search before the reminder repeats; covers long sessions and context lost to compaction. REMIND_EVERY = 10 SEARCH_CONTEXT = ('Search reminder: 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 "" --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(): return if marker.exists(): try: count = int(marker.read_text(encoding='utf-8') or '0') + 1 except ValueError: count = 1 else: prune_markers(marker.parent, time.time()) count = REMIND_EVERY remind = not used_qmd and count >= REMIND_EVERY marker.write_text('0' if used_qmd or remind else str(count), encoding='utf-8') if remind: 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()