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
@@ -15,7 +15,10 @@
|
||||
"command": "__STATUSLINE_COMMAND__ \"__AI_CONFIG_ROOT__/statusline/__STATUSLINE_SCRIPT__\""
|
||||
},
|
||||
"hooks": {
|
||||
"PreToolUse": [{"matcher": "Bash|PowerShell", "hooks": [{"type": "command", "command": "__HOOK_COMMAND__ \"__AI_CONFIG_ROOT__/hooks/scripts/__COMMAND_SAFETY_SCRIPT__\"", "timeout": 6}]}],
|
||||
"PreToolUse": [
|
||||
{"matcher": "Bash|PowerShell", "hooks": [{"type": "command", "command": "__HOOK_COMMAND__ \"__AI_CONFIG_ROOT__/hooks/scripts/__COMMAND_SAFETY_SCRIPT__\"", "timeout": 6}]},
|
||||
{"matcher": "Grep|Glob|Bash|PowerShell", "hooks": [{"type": "command", "command": "__HOOK_COMMAND__ \"__AI_CONFIG_ROOT__/hooks/scripts/__SEARCH_REMINDER_SCRIPT__\"", "timeout": 4}]}
|
||||
],
|
||||
"PreCompact": [{"hooks": [{"type": "command", "command": "__HOOK_COMMAND__ \"__AI_CONFIG_ROOT__/hooks/scripts/__COMPACT_SCRIPT__\"", "timeout": 4}]}],
|
||||
"SessionStart": [
|
||||
{"hooks": [{"type": "command", "command": "__HOOK_COMMAND__ \"__AI_CONFIG_ROOT__/hooks/scripts/__SESSION_POINTER_SCRIPT__\"", "timeout": 4}]},
|
||||
|
||||
@@ -49,6 +49,15 @@ command = '__HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__COMMAND_SAFETY_S
|
||||
command_windows = '__POWERSHELL_HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__COMMAND_SAFETY_SCRIPT__"'
|
||||
timeout = 6
|
||||
|
||||
# Reminds once per session to run semantic-search before open shell searches; a no-op without QMD.
|
||||
[[hooks.PreToolUse]]
|
||||
matcher = "Bash"
|
||||
[[hooks.PreToolUse.hooks]]
|
||||
type = "command"
|
||||
command = '__HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__SEARCH_REMINDER_SCRIPT__"'
|
||||
command_windows = '__POWERSHELL_HOOK_COMMAND__ "__AI_CONFIG_ROOT__/hooks/scripts/__SEARCH_REMINDER_SCRIPT__"'
|
||||
timeout = 4
|
||||
|
||||
# Impeccable's design detector; the wrapper is a no-op unless the Impeccable Codex skill is installed.
|
||||
[[hooks.PostToolUse]]
|
||||
matcher = "Edit|Write|apply_patch"
|
||||
|
||||
@@ -12,5 +12,6 @@ __CORRECTION_PROMPT_SCRIPT__ Show-CorrectionPrompt.ps1 show-correction-prompt.sh
|
||||
__COMPLETION_EVIDENCE_SCRIPT__ Check-CompletionEvidence.ps1 check-completion-evidence.sh
|
||||
__COMMAND_SAFETY_SCRIPT__ Validate-CommandSafety.ps1 validate-command-safety.sh
|
||||
__IMPECCABLE_HOOK_SCRIPT__ Invoke-ImpeccableHook.ps1 invoke-impeccable-hook.sh
|
||||
__SEARCH_REMINDER_SCRIPT__ Show-SearchReminder.ps1 show-search-reminder.sh
|
||||
__SHELL_TOOL__ PowerShell Bash
|
||||
__SCRIPT_EXTENSION__ ps1 sh
|
||||
|
@@ -7,6 +7,7 @@ The adapters register these events:
|
||||
| Client | Event | Action |
|
||||
| --- | --- | --- |
|
||||
| Codex and Claude | `PreToolUse` | Block clearly destructive shell commands (`Validate-CommandSafety`/`validate-command-safety.sh`); Claude matches the `Bash` and `PowerShell` tools. |
|
||||
| Codex and Claude | `PreToolUse` | Once per session, remind the agent to run `semantic-search` before the first open search (`Show-SearchReminder`/`show-search-reminder.sh`); a no-op unless QMD's `qmd-search.mjs` is installed. Claude matches `Grep`, `Glob`, `Bash`, and `PowerShell`; Codex matches `Bash`. |
|
||||
| Codex and Claude | `Stop` | Run the finish notification (`flashbang`). |
|
||||
| Codex and Claude | `Stop` | Push back once on an unbacked completion claim (`Check-CompletionEvidence`/`check-completion-evidence.sh`). |
|
||||
| Codex and Claude | `UserPromptSubmit` | Ask the agent to propose a durable rule when a prompt looks like a correction (`Show-CorrectionPrompt`/`show-correction-prompt.sh`). |
|
||||
@@ -16,6 +17,8 @@ The adapters register these events:
|
||||
|
||||
The main agent alone maintains canonical task state. Hooks never write or summarize it, print its contents, or infer completed verification. The task-state hooks use the hook event's `cwd`, falling back to the process working directory when no workspace is supplied. Malformed event data does not fall back to another project. An absent state file is a successful no-op. Legacy state under the installed configuration root is not automatically adopted; confirm its task before migrating it. The scripts do not grant permissions, bypass approvals, or replace client permission systems.
|
||||
|
||||
The search reminder never blocks a tool call. It fires on `Grep`/`Glob` or on shell commands that look like searches (`rg`, `grep`, `find`, `fd`, `git grep`, `Select-String`, recursive `Get-ChildItem`). It stays silent for the rest of the session once it has fired or once the session ran `qmd-search.mjs`. It matches command text, so wrapped or aliased searches can slip through. Per-session markers are hashed session IDs under `~/.my-ai-configuration/state/search-reminder/`; markers older than seven days are pruned.
|
||||
|
||||
The QMD warm-up hook uses the process working directory and starts only inside a Git repository when Node.js and the installed wrapper are available. It runs detached; wrapper errors are recorded in `~/.my-ai-configuration/qmd/warm.log`. Disabling local search removes its hook registration. See [Local QMD search](configuration.md#local-qmd-search) for daemon behavior and storage.
|
||||
|
||||
When enabled during installation or update, Flashbang runs on `Stop`, after the main agent finishes responding. The default flash lasts about 500 milliseconds. The PowerShell command omits `-WindowStyle Hidden`, which can hide or minimize the shared terminal. The PowerShell hook creates a low-opacity click-through overlay without activating another window when its native GUI APIs are available; unsupported runtimes exit safely. Its native DLL cache is optional: a missing `LOCALAPPDATA` environment variable or an unusable cache falls back to in-process compilation instead of suppressing the notification. The Bash hook uses Python's `tkinter`, uses `xrandr` for multi-monitor bounds when available, and falls back to `notify-send` when the overlay is unavailable. Registered hooks are best effort: errors do not fail a Claude session.
|
||||
|
||||
+1
-1
@@ -79,7 +79,7 @@ On Windows, an unavailable profile-folder lookup falls back to PowerShell's home
|
||||
| `tests/test-qmd-lib.mjs`, `test-qmd-daemon.mjs`, `test-qmd-search.mjs`, `test-qmd-warm.mjs`, `test-qmd-benchmark.mjs` | Model-free QMD unit tests; require the YAML dependency. |
|
||||
| `tests/test-qmd-integration.mjs` | Manual integration test using real QMD and downloaded models; excluded from CI. |
|
||||
| `tests/test-qmd-setup.py` | Validate QMD installation, migration, and removal. |
|
||||
| `tests/test-agent-guards.py` | Validate the completion-evidence and correction-prompt hooks. |
|
||||
| `tests/test-agent-guards.py` | Validate the completion-evidence, correction-prompt, and search-reminder hooks. |
|
||||
| `tests/test-session-state.py` | Validate session-state helpers. |
|
||||
| `tests/test-shell-packages.ps1`, `tests/test-shell-packages.sh` | Validate generated package contents and client settings. |
|
||||
| `tests/test-runtime-status.ps1`, `tests/test-runtime-status.sh` | Validate build summaries and status-line output. |
|
||||
|
||||
@@ -9,7 +9,7 @@ from personal_instructions import CLIENT_FILES, render
|
||||
|
||||
|
||||
# Hook scripts this configuration installs; merges replace these and keep any foreign hooks.
|
||||
OWNED_HOOK_PATTERN = r'(?:flashbang|statusline|record-compact|session-state-pointer|qmd-warm|Start-QmdWarm|completion-?evidence|correction-?prompt|command-?safety|impeccable-?hook)\.(?:ps1|sh)'
|
||||
OWNED_HOOK_PATTERN = r'(?:flashbang|statusline|record-compact|session-state-pointer|qmd-warm|Start-QmdWarm|completion-?evidence|correction-?prompt|command-?safety|impeccable-?hook|search-?reminder)\.(?:ps1|sh)'
|
||||
|
||||
|
||||
def is_flashbang(hook):
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -4,7 +4,7 @@ This directory contains registered hooks and optional utilities. They do not byp
|
||||
|
||||
When Flashbang is enabled, both clients register `Stop` (`flashbang`) for finish notifications. Claude also registers `PreCompact` (`Record-Compact`/`record-compact.sh`) and `SessionStart` (`Show-SessionStatePointer`/`show-session-state-pointer.sh`). PreCompact records its timestamp under the installed configuration root. Both session hooks point to an existing workspace `.ai-session/state.json`, using event `cwd` or the process working directory. The main agent owns that state; hooks never write it or print its contents. Missing state is a successful no-op.
|
||||
|
||||
Both clients register `PreToolUse` (`Validate-CommandSafety`/`validate-command-safety.sh`), which blocks clearly destructive shell commands by exiting 2; it parses command text, so it is a guard rail rather than a security boundary, and it fails open. Both clients also register `Stop` (`Check-CompletionEvidence`/`check-completion-evidence.sh`) and `UserPromptSubmit` (`Show-CorrectionPrompt`/`show-correction-prompt.sh`). Both call `agent-guards.py`, store nothing, and fail open. The first pushes back once on a completion claim without a named check while non-prose changes exist; the second asks the agent to propose a durable rule after a likely correction.
|
||||
Both clients register `PreToolUse` (`Validate-CommandSafety`/`validate-command-safety.sh`), which blocks clearly destructive shell commands by exiting 2; it parses command text, so it is a guard rail rather than a security boundary, and it fails open. Both clients also register `Stop` (`Check-CompletionEvidence`/`check-completion-evidence.sh`) and `UserPromptSubmit` (`Show-CorrectionPrompt`/`show-correction-prompt.sh`). Both call `agent-guards.py`, store nothing, and fail open. The first pushes back once on a completion claim without a named check while non-prose changes exist; the second asks the agent to propose a durable rule after a likely correction. A second `PreToolUse` hook (`Show-SearchReminder`/`show-search-reminder.sh`, also through `agent-guards.py`) reminds the agent once per session to run `semantic-search` before the first open search; it never blocks, stays silent once the session ran `qmd-search.mjs`, does nothing unless QMD is installed, and keeps only hashed per-session markers under `~/.my-ai-configuration/state/search-reminder/`.
|
||||
|
||||
`Invoke-PostChangeVerification`/`invoke-post-change-verification.sh` is not registered or invoked automatically; it runs the repository build only when explicitly invoked. Python-based hooks resolve their interpreter through `Resolve-Python.ps1`/`resolve-python.sh` and are silently skipped without Python 3.11+. `Test-SessionConfig`/`test-session-config.sh` checks repository inputs during a build.
|
||||
|
||||
|
||||
@@ -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