fix(config): resolve Python reliably, add command-safety hook, harden CI

- Resolve Python 3.11+ through shared Resolve-Python.ps1/resolve-python.sh,
  which probe python, python3 and py -3 and skip the Windows Store alias.
  Build and capability checks fail early with an actionable message; doctor
  reports missing Python and the skipped hooks.
- Fix check-capabilities.sh comparing only the major version.
- Register Validate-CommandSafety as a PreToolUse hook for Claude and Codex;
  shared logic in command-safety.py catches rm -rf variants, git reset --hard,
  git clean -f, Remove-Item -Recurse, del/rd /s /q and nested shells.
- Replace duplicated placeholder chains in both builds with
  adapters/placeholders.tsv.
- Restore shell parity: add test-capabilities.sh, rename credentials.ps1 to
  with-credential.ps1 and qmd-warm.sh to start-qmd-warm.sh.
- CI: build once and pass generated/ as an artifact, lint Python with ruff
  and JavaScript modules with node --check, require SHA pins for all actions.
- Add evals for all own skills and update documentation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Julian LechnerandClaude Opus 5.5 committed 2026-11-05 09:34:54 +01:00
1 parent e19aa2e27c
commit 79694fbaa2
95 files changed
+1838 -218

No files matched your search

+3 -3
View File
@@ -4,8 +4,8 @@ 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 `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.
`Validate-CommandSafety`/`validate-command-safety.sh` and `Invoke-PostChangeVerification`/`invoke-post-change-verification.sh` are not registered or invoked automatically. The safety utility checks selected command-text patterns; the verification utility runs the repository build only when explicitly invoked. `Test-SessionConfig`/`test-session-config.sh` checks repository inputs during a build.
`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.
When local QMD search is enabled, both clients also register a `SessionStart` warm-up hook (`Start-QmdWarm.ps1`/`qmd-warm.sh`). It starts the installed Node wrapper in the background from the process working directory, only inside a Git repository. Warm-up errors are recorded in `~/.my-ai-configuration/qmd/warm.log`; they do not fail the session. Disabling local search removes the hook registration.
When local QMD search is enabled, both clients also register a `SessionStart` warm-up hook (`Start-QmdWarm.ps1`/`start-qmd-warm.sh`). It starts the installed Node wrapper in the background from the process working directory, only inside a Git repository. Warm-up errors are recorded in `~/.my-ai-configuration/qmd/warm.log`; they do not fail the session. Disabling local search removes the hook registration.
+5 -2
View File
@@ -5,12 +5,15 @@ set -uo pipefail
# Python's standard tkinter module because Bash itself cannot create windows.
# No third-party Python package is required.
if ! command -v python3 >/dev/null 2>&1; then
hook_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
# shellcheck source=scripts/resolve-python.sh
. "$hook_dir/scripts/resolve-python.sh" 2>/dev/null || resolve_python() { return 1; }
if ! resolve_python; then
command -v notify-send >/dev/null 2>&1 && notify-send 'AI assistant requires attention'
exit 0
fi
python3 - "$@" 2>/dev/null <<'PY' || exit 0
run_python - "$@" 2>/dev/null <<'PY' || exit 0
import argparse
import re
import shutil
@@ -1,7 +1,10 @@
[CmdletBinding()]
param()
# Best effort: without Python 3.11+ this hook is a silent no-op; doctor reports that case.
try {
$ErrorActionPreference = 'Stop'
& python (Join-Path $PSScriptRoot 'agent-guards.py') stop 2>$null
. (Join-Path $PSScriptRoot 'Resolve-Python.ps1')
$python = Get-PythonCommand
if ($python) { & $python.Path @($python.Arguments) (Join-Path $PSScriptRoot 'agent-guards.py') stop 2>$null }
} catch {}
exit 0
+3 -1
View File
@@ -10,6 +10,8 @@ try {
('{"event":"compact","timestamp":"' + (Get-Date).ToUniversalTime().ToString('o') + '"}') | Add-Content $path
if ((Get-Item $path).Length -gt 1048576) { Move-Item $path ($path + '.1') -Force }
}
& python (Join-Path $PSScriptRoot 'session-state.py') --hook 2>$null
. (Join-Path $PSScriptRoot 'Resolve-Python.ps1')
$python = Get-PythonCommand
if ($python) { & $python.Path @($python.Arguments) (Join-Path $PSScriptRoot 'session-state.py') --hook 2>$null }
} catch {}
exit 0
+43
View File
@@ -0,0 +1,43 @@
# Resolves a working Python 3.11+ interpreter for PowerShell scripts and hooks.
# Dot-source this file, then call Get-PythonCommand. Candidates are probed by running them,
# so the Windows Store "App execution alias" stub (which exists on PATH but only prints an
# install hint) is rejected instead of being mistaken for Python. The `py -3` launcher is
# tried last for Windows installations that do not put python.exe on PATH.
$script:ResolvedPythonCommand = $null
function Get-PythonCommand {
param([switch]$Required)
if ($null -ne $script:ResolvedPythonCommand) { return $script:ResolvedPythonCommand }
$previousErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
foreach ($candidate in @(@('python'), @('python3'), @('py', '-3'))) {
$application = Get-Command $candidate[0] -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
if (-not $application) { continue }
$prefix = @($candidate | Select-Object -Skip 1)
try {
& $application.Source @prefix -c 'import sys; sys.exit(0 if sys.version_info >= (3, 11) else 1)' *> $null
$probeExitCode = $LASTEXITCODE
} catch { $probeExitCode = 1 }
if ($probeExitCode -eq 0) {
$script:ResolvedPythonCommand = [pscustomobject]@{ Path = $application.Source; Arguments = $prefix; Display = ($candidate -join ' ') }
return $script:ResolvedPythonCommand
}
}
} finally {
$ErrorActionPreference = $previousErrorActionPreference
}
if ($Required) { throw (Get-PythonMissingMessage) }
return $null
}
function Get-PythonMissingMessage {
return 'Python 3.11 or newer was not found (tried python, python3, py -3). A Windows Store app execution alias does not count; install Python, or disable the python/python3 aliases under Settings > Apps > Advanced app settings > App execution aliases.'
}
# Runs Python with the given arguments; stdin is inherited, so pipe input with Get-PythonCommand instead.
function Invoke-Python {
$python = Get-PythonCommand -Required
& $python.Path @($python.Arguments) @args
}
@@ -1,7 +1,10 @@
[CmdletBinding()]
param()
# Best effort: without Python 3.11+ this hook is a silent no-op; doctor reports that case.
try {
$ErrorActionPreference = 'Stop'
& python (Join-Path $PSScriptRoot 'agent-guards.py') prompt 2>$null
. (Join-Path $PSScriptRoot 'Resolve-Python.ps1')
$python = Get-PythonCommand
if ($python) { & $python.Path @($python.Arguments) (Join-Path $PSScriptRoot 'agent-guards.py') prompt 2>$null }
} catch {}
exit 0
@@ -1,7 +1,10 @@
[CmdletBinding()]
param()
# Best effort: without Python 3.11+ this hook is a silent no-op; doctor reports that case.
try {
$ErrorActionPreference = 'Stop'
& python (Join-Path $PSScriptRoot 'session-state.py') --hook 2>$null
. (Join-Path $PSScriptRoot 'Resolve-Python.ps1')
$python = Get-PythonCommand
if ($python) { & $python.Path @($python.Arguments) (Join-Path $PSScriptRoot 'session-state.py') --hook 2>$null }
} catch {}
exit 0
@@ -1,5 +1,17 @@
param([Parameter(Mandatory=$true)][string]$Command, [string]$Workspace = (Get-Location).Path)
$dangerous = @('git reset --hard','git clean -fd','git clean -fx','Remove-Item -Recurse','rm -rf','format c:','del /s /q')
foreach ($pattern in $dangerous) { if ($Command.IndexOf($pattern, [StringComparison]::OrdinalIgnoreCase) -ge 0) { Write-Error "Blocked potentially destructive command: $pattern"; exit 1 } }
if ($Command -match '(?i)(^|\s)([A-Z]:\\|/)(?!.*' + [regex]::Escape($Workspace) + ')') { Write-Error 'Blocked command containing an absolute path outside the workspace.'; exit 1 }
Write-Output 'PASS command safety'
# Without -Command this runs as a PreToolUse hook: it reads the event from stdin and exits 2 to block.
# With -Command it checks one command and also rejects absolute paths outside -Workspace.
# Pattern checks are a guard rail against accidents, not a security boundary.
param([string]$Command, [string]$Workspace = (Get-Location).Path)
. (Join-Path $PSScriptRoot 'Resolve-Python.ps1')
$python = Get-PythonCommand
$script = Join-Path $PSScriptRoot 'command-safety.py'
if ($PSBoundParameters.ContainsKey('Command')) {
if (-not $python) { Write-Error (Get-PythonMissingMessage); exit 1 }
# Pass the command on stdin: Windows PowerShell 5.1 does not escape embedded quotes in native arguments.
$Command | & $python.Path @($python.Arguments) $script --command - --workspace $Workspace
exit $LASTEXITCODE
}
# Registered hooks fail open without Python; doctor reports that case.
if (-not $python) { exit 0 }
& $python.Path @($python.Arguments) $script --hook
exit $LASTEXITCODE
@@ -1,4 +1,6 @@
#!/usr/bin/env bash
set -uo pipefail
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
python3 "$script_dir/agent-guards.py" stop 2>/dev/null || true
# 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" stop 2>/dev/null || true; fi
+222
View File
@@ -0,0 +1,222 @@
"""Block clearly destructive shell commands.
Hook mode (--hook) reads a Claude or Codex PreToolUse event from stdin and exits 2 with a
reason on stderr to block the tool call; anything it cannot parse is allowed (fail open).
CLI mode (--command) checks one command and additionally rejects absolute paths outside the
workspace. Both modes are guard rails against accidents, not a security boundary: they parse
command text and cannot see what scripts, aliases, or variables expand to at run time.
"""
import argparse
import json
import ntpath
import os
import posixpath
import re
import shlex
import sys
WRAPPERS = {'sudo', 'command', 'builtin', 'exec', 'nohup', 'time', 'env', 'xargs'}
POSIX_SHELLS = {'bash', 'sh', 'zsh', 'dash', 'ksh'}
POWERSHELL_HOSTS = {'pwsh', 'powershell'}
POWERSHELL_REMOVE = {'remove-item', 'ri'}
# In PowerShell these aliases mean Remove-Item; in Bash, rm follows the POSIX rules instead.
POWERSHELL_REMOVE_ALIASES = {'rm', 'del', 'erase', 'rd', 'rmdir'}
CMD_REMOVE = {'del', 'erase', 'rd', 'rmdir'}
RECURSE_PARAMETER = re.compile(r'-r(?:e(?:c(?:u(?:r(?:s(?:e)?)?)?)?)?)?(?::\$true)?')
MAX_DEPTH = 3
def split_segments(command):
"""Split on ;, &, |, &&, || and newlines that are outside quotes."""
segments, current, quote = [], [], None
for character in command:
if quote:
current.append(character)
if character == quote:
quote = None
elif character in '\'"':
quote = character
current.append(character)
elif character in ';&|\n':
segments.append(''.join(current))
current = []
else:
current.append(character)
segments.append(''.join(current))
return [segment.strip() for segment in segments if segment.strip()]
def tokenize(segment):
try:
return shlex.split(segment, posix=True)
except ValueError:
return segment.split()
def program_name(token):
name = re.split(r'[\\/]', token)[-1].lower()
return re.sub(r'\.(exe|cmd|bat)$', '', name)
def strip_wrappers(tokens):
index = 0
while index < len(tokens):
token = tokens[index]
if program_name(token) in WRAPPERS or re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*=.*', token):
index += 1
continue
break
return tokens[index:]
def short_flags(tokens):
flags = set()
for token in tokens:
if re.fullmatch(r'-[A-Za-z]+', token):
flags.update(token[1:])
return flags
def git_subcommand(arguments):
index = 0
while index < len(arguments):
token = arguments[index]
if token in ('-C', '-c', '--git-dir', '--work-tree', '--namespace'):
index += 2
elif token.startswith('-'):
index += 1
else:
return token.lower(), [item.lower() for item in arguments[index + 1:]]
return '', []
def check_tokens(tokens, shell=None):
"""Return why the command is blocked; shell is 'bash', 'powershell', or None when unknown."""
tokens = strip_wrappers(tokens)
if not tokens:
return None
program = program_name(tokens[0])
arguments = tokens[1:]
lowered = [argument.lower() for argument in arguments]
if program == 'rm' and shell != 'powershell':
flags = short_flags(arguments)
recursive = bool(flags & {'r', 'R'}) or '--recursive' in lowered
force = 'f' in flags or '--force' in lowered
if recursive and force:
return 'recursive forced deletion (rm -rf)'
if program == 'git':
subcommand, rest = git_subcommand(arguments)
if subcommand == 'reset' and '--hard' in rest:
return 'discarding work tree changes (git reset --hard)'
if subcommand == 'clean' and ('f' in short_flags(rest) or '--force' in rest):
return 'deleting untracked files (git clean -f)'
powershell_remove = program in POWERSHELL_REMOVE or (shell != 'bash' and program in POWERSHELL_REMOVE_ALIASES)
if powershell_remove and any(RECURSE_PARAMETER.fullmatch(item) for item in lowered):
return 'recursive deletion (Remove-Item -Recurse)'
if program in CMD_REMOVE and '/s' in lowered and '/q' in lowered:
return 'quiet recursive deletion (del /s /q)'
if program == 'format' and any(re.fullmatch(r'[a-z]:', item) for item in lowered):
return 'formatting a drive'
return None
def nested_command(tokens):
"""Return (command, shell) for bash -c, pwsh -Command, cmd /c, and eval; otherwise None."""
tokens = strip_wrappers(tokens)
if not tokens:
return None
program = program_name(tokens[0])
if program == 'eval':
return ' '.join(tokens[1:]), 'bash'
for index, token in enumerate(tokens[1:], start=1):
lowered = token.lower()
nested = ' '.join(tokens[index + 1:])
if program in POSIX_SHELLS and re.fullmatch(r'-[a-z]*c', lowered):
return nested, 'bash'
if program in POWERSHELL_HOSTS and lowered in ('-c', '-command'):
return nested, 'powershell'
if program == 'cmd' and lowered in ('/c', '/k'):
return nested, None
return None
def find_violation(command, shell=None, depth=0):
if depth > MAX_DEPTH:
return None
for segment in split_segments(command):
tokens = tokenize(segment)
reason = check_tokens(tokens, shell)
if reason:
return reason
nested = nested_command(tokens)
if nested:
reason = find_violation(nested[0], nested[1], depth + 1)
if reason:
return reason
return None
def outside_workspace(command, workspace):
workspace = os.path.normcase(os.path.realpath(workspace))
for token in tokenize(command):
candidate = token.split('=', 1)[-1] if token.startswith('-') else token
if re.fullmatch(r'/[A-Za-z?]', candidate):
continue # cmd.exe switches such as /c or /s are not paths.
if not (posixpath.isabs(candidate) or ntpath.isabs(candidate)):
continue
resolved = os.path.normcase(os.path.realpath(candidate))
try:
inside = os.path.commonpath([resolved, workspace]) == workspace
except ValueError:
inside = False
if not inside:
return candidate
return None
def run_hook(data):
try:
event = json.loads(data.decode('utf-8', errors='replace'))
command = event.get('tool_input', {}).get('command')
tool = str(event.get('tool_name', '')).lower()
except (ValueError, AttributeError):
return 0
if not isinstance(command, str):
return 0
shell = tool if tool in ('bash', 'powershell') else None
reason = find_violation(command, shell)
if reason:
print(f'Blocked by command-safety hook: {reason}. Ask the user to run this command themselves if it is intended.', file=sys.stderr)
return 2
return 0
def run_check(command, workspace):
reason = find_violation(command)
if reason:
print(f'Blocked potentially destructive command: {reason}', file=sys.stderr)
return 1
path = outside_workspace(command, workspace)
if path:
print(f'Blocked command containing an absolute path outside the workspace: {path}', file=sys.stderr)
return 1
print('PASS command safety')
return 0
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
mode = parser.add_mutually_exclusive_group(required=True)
mode.add_argument('--hook', action='store_true', help='read a PreToolUse event from stdin')
mode.add_argument('--command', help="command text to check, or '-' to read it from stdin")
parser.add_argument('--workspace', default=os.getcwd())
args = parser.parse_args()
if args.hook:
return run_hook(sys.stdin.buffer.read())
command = sys.stdin.read() if args.command == '-' else args.command
return run_check(command, args.workspace)
if __name__ == '__main__':
sys.exit(main())
+2 -1
View File
@@ -2,4 +2,5 @@
set -uo pipefail
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
[ "${AI_CONFIG_TELEMETRY:-1}" = 0 ] || { mkdir -p "$root/.ai-session" && printf '{"event":"compact","timestamp":"%s"}\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$root/.ai-session/telemetry.jsonl"; [ "$(wc -c < "$root/.ai-session/telemetry.jsonl")" -le 1048576 ] || mv -f "$root/.ai-session/telemetry.jsonl" "$root/.ai-session/telemetry.jsonl.1"; }
python3 "$root/hooks/scripts/session-state.py" --hook 2>/dev/null || true
. "$root/hooks/scripts/resolve-python.sh"
if resolve_python; then run_python "$root/hooks/scripts/session-state.py" --hook 2>/dev/null || true; fi
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env bash
# Resolves a working Python 3.11+ interpreter for Bash scripts and hooks.
# Source this file, then call resolve_python (sets the ai_python array) or run_python.
# Candidates are probed by running them, so the Windows Store "App execution alias" stub
# that Git Bash finds on PATH is rejected instead of being mistaken for Python.
ai_python=()
resolve_python() {
[ "${#ai_python[@]}" -eq 0 ] || return 0
local candidate
for candidate in python3 python 'py -3'; do
# shellcheck disable=SC2086 # 'py -3' is intentionally split into command and argument.
command -v ${candidate%% *} >/dev/null 2>&1 || continue
# shellcheck disable=SC2086
if $candidate -c 'import sys; sys.exit(0 if sys.version_info >= (3, 11) else 1)' >/dev/null 2>&1 </dev/null; then
read -r -a ai_python <<<"$candidate"
return 0
fi
done
return 1
}
python_missing_message() {
printf '%s\n' 'Python 3.11 or newer was not found (tried python3, python, py -3). A Windows Store app execution alias does not count; install Python, or disable the python/python3 aliases under Settings > Apps > Advanced app settings > App execution aliases.'
}
python_display() {
printf '%s' "${ai_python[*]}"
}
run_python() {
resolve_python || { python_missing_message >&2; return 127; }
"${ai_python[@]}" "$@"
}
@@ -1,4 +1,6 @@
#!/usr/bin/env bash
set -uo pipefail
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
python3 "$script_dir/agent-guards.py" prompt 2>/dev/null || true
# 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" prompt 2>/dev/null || true; fi
@@ -1,4 +1,6 @@
#!/usr/bin/env bash
set -uo pipefail
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
python3 "$script_dir/session-state.py" --hook 2>/dev/null || true
# 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/session-state.py" --hook 2>/dev/null || true; fi
File renamed without changes.
@@ -1,8 +1,17 @@
#!/usr/bin/env bash
set -euo pipefail
command_text=${1:?Command is required}
for pattern in 'git reset --hard' 'git clean -fd' 'git clean -fx' 'rm -rf' 'Remove-Item -Recurse' 'format c:' 'del /s /q'; do
[[ ${command_text,,} != *"${pattern,,}"* ]] || { printf 'Blocked potentially destructive command: %s\n' "$pattern" >&2; exit 1; }
done
printf 'PASS command safety\n'
# Without arguments this runs as a PreToolUse hook: it reads the event from stdin and exits 2 to block.
# With a command argument it checks that command and also rejects absolute paths outside the
# workspace (second argument, default: the working directory).
# Pattern checks are a guard rail against accidents, not a security boundary.
set -uo pipefail
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
# shellcheck source=resolve-python.sh
. "$script_dir/resolve-python.sh"
if [ $# -gt 0 ]; then
resolve_python || { python_missing_message >&2; exit 1; }
printf '%s' "$1" | run_python "$script_dir/command-safety.py" --command - --workspace "${2:-$PWD}"
exit $?
fi
# Registered hooks fail open without Python; doctor reports that case.
resolve_python || exit 0
run_python "$script_dir/command-safety.py" --hook