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:
1 parent
e19aa2e27c
commit
79694fbaa2
95 files changed
+1838
-218
No files matched your search
@@ -1,11 +1,34 @@
|
||||
[CmdletBinding()]
|
||||
param([switch]$Summary)
|
||||
# Checks that Python resolution skips a PATH entry that cannot run Python (such as the Windows
|
||||
# Store app execution alias) and that check-capabilities reports the resolved interpreter.
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
||||
$content = Get-Content (Join-Path $root 'scripts/commands/check-capabilities.ps1') -Raw
|
||||
$stubs = Join-Path ([System.IO.Path]::GetTempPath()) ('capabilities-' + [Guid]::NewGuid().ToString('N'))
|
||||
New-Item $stubs -ItemType Directory | Out-Null
|
||||
$previousPath = $env:PATH
|
||||
try {
|
||||
$onWindows = [Environment]::OSVersion.Platform -eq [PlatformID]::Win32NT
|
||||
# python imitates the Store alias: it is on PATH but only prints an install hint.
|
||||
if ($onWindows) {
|
||||
Set-Content (Join-Path $stubs 'python.cmd') "@echo Python was not found; run without arguments to install from the Microsoft Store 1>&2`r`n@exit /b 9009" -Encoding ASCII
|
||||
Set-Content (Join-Path $stubs 'python3.cmd') "@if `"%~1`"==`"-c`" echo 3.12.0`r`n@exit /b 0" -Encoding ASCII
|
||||
} else {
|
||||
Set-Content (Join-Path $stubs 'python') "#!/bin/sh`necho 'Python was not found' >&2`nexit 9009`n" -NoNewline
|
||||
Set-Content (Join-Path $stubs 'python3') "#!/bin/sh`nfor arg in `"`$@`"; do [ `"`$arg`" != -c ] || { echo 3.12.0; exit 0; }; done`nexit 0`n" -NoNewline
|
||||
& chmod +x (Join-Path $stubs 'python') (Join-Path $stubs 'python3')
|
||||
}
|
||||
$env:PATH = $stubs + [System.IO.Path]::PathSeparator + $previousPath
|
||||
$hostPath = (Get-Process -Id $PID).Path
|
||||
|
||||
if ($content -match '(?s)\(& \$python --version.*?Select-Object.*?\).*?\$LASTEXITCODE') {
|
||||
throw 'Python capability detection must not read $LASTEXITCODE after a pipeline.'
|
||||
$resolved = & $hostPath -NoProfile -ExecutionPolicy Bypass -Command ". '$root/shared/hooks/scripts/Resolve-Python.ps1'; (Get-PythonCommand).Display"
|
||||
if ("$resolved".Trim() -ne 'python3') { throw "Resolver chose '$resolved' instead of skipping the broken python." }
|
||||
|
||||
$output = (& $hostPath -NoProfile -ExecutionPolicy Bypass -File (Join-Path $root 'scripts/commands/check-capabilities.ps1') 2>&1 | Out-String)
|
||||
if ($output -notmatch 'PASS Python 3\.12\.0') { throw "check-capabilities did not use the resolved interpreter:`n$output" }
|
||||
} finally {
|
||||
$env:PATH = $previousPath
|
||||
Remove-Item -LiteralPath $stubs -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
|
||||
if ($Summary) { Write-Output 'Tests: PASS | capabilities' } else { Write-Output 'PASS capabilities: Python exit code is read without a pipeline' }
|
||||
if ($Summary) { Write-Output 'Tests: PASS | capabilities' } else { Write-Output 'PASS capabilities: broken Python aliases are skipped' }
|
||||
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env bash
|
||||
# Checks that Python resolution skips a PATH entry that cannot run Python (such as the Windows
|
||||
# Store app execution alias) and that check-capabilities reports the resolved interpreter.
|
||||
set -euo pipefail
|
||||
summary=false
|
||||
[ "${1:-}" != --summary ] || summary=true
|
||||
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
stubs=$(mktemp -d)
|
||||
trap 'rm -rf -- "$stubs"' EXIT
|
||||
|
||||
# python3 imitates the Store alias: it is on PATH but only prints an install hint.
|
||||
printf '#!/bin/sh\necho "Python was not found; run without arguments to install from the Microsoft Store" >&2\nexit 9009\n' > "$stubs/python3"
|
||||
printf '#!/bin/sh\nfor arg in "$@"; do [ "$arg" != -c ] || { echo 3.12.0; exit 0; }; done\nexit 0\n' > "$stubs/python"
|
||||
chmod +x "$stubs/python3" "$stubs/python"
|
||||
|
||||
# shellcheck disable=SC2016 # Expanded by the child shell.
|
||||
resolved=$(PATH="$stubs:$PATH" bash -c '. "$1/shared/hooks/scripts/resolve-python.sh"; resolve_python && printf "%s" "$(python_display)"' _ "$root")
|
||||
[ "$resolved" = python ] || { printf 'FAIL resolver chose "%s" instead of skipping the broken python3\n' "$resolved" >&2; exit 1; }
|
||||
|
||||
output=$(PATH="$stubs:$PATH" bash "$root/scripts/commands/check-capabilities.sh" 2>&1) || true
|
||||
grep -q 'PASS Python 3.12.0' <<<"$output" || { printf 'FAIL check-capabilities did not use the resolved interpreter:\n%s\n' "$output" >&2; exit 1; }
|
||||
|
||||
if [ "$summary" = true ]; then printf 'Tests: PASS | capabilities\n'; else printf 'PASS capabilities: broken Python aliases are skipped\n'; fi
|
||||
@@ -0,0 +1,129 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SCRIPTS = ROOT / 'shared/hooks/scripts'
|
||||
SAFETY = SCRIPTS / 'command-safety.py'
|
||||
|
||||
|
||||
def hook(command, tool='Bash'):
|
||||
payload = json.dumps({'hook_event_name': 'PreToolUse', 'tool_name': tool, 'tool_input': {'command': command}})
|
||||
return subprocess.run([sys.executable, str(SAFETY), '--hook'], input=payload, capture_output=True,
|
||||
encoding='utf-8', timeout=20)
|
||||
|
||||
|
||||
def check(command, workspace):
|
||||
return subprocess.run([sys.executable, str(SAFETY), '--command', '-', '--workspace', str(workspace)], input=command,
|
||||
capture_output=True, encoding='utf-8', timeout=20)
|
||||
|
||||
|
||||
class HookTests(unittest.TestCase):
|
||||
def assertBlocked(self, command, tool='Bash'):
|
||||
result = hook(command, tool)
|
||||
self.assertEqual(result.returncode, 2, f'{tool}: {command!r} was not blocked')
|
||||
self.assertIn('Blocked by command-safety hook', result.stderr)
|
||||
|
||||
def assertAllowed(self, command, tool='Bash'):
|
||||
result = hook(command, tool)
|
||||
self.assertEqual(result.returncode, 0, f'{tool}: {command!r} was blocked: {result.stderr}')
|
||||
|
||||
def test_blocks_destructive_bash_variants(self):
|
||||
for command in ('rm -rf build', 'rm -fr build', 'rm -r -f build', 'rm --recursive --force build', 'sudo rm -Rf /',
|
||||
'cd x && rm -rf y', 'echo ok; rm -rf y', 'git reset --hard', 'git -C repo reset --hard HEAD~1',
|
||||
'git clean -fdx', 'git clean --force', "bash -c 'rm -rf build'", 'bash -lc "git reset --hard"',
|
||||
'eval "rm -rf build"', 'find . -name x | xargs rm -rf', 'FOO=1 /bin/rm -rf build'):
|
||||
with self.subTest(command=command):
|
||||
self.assertBlocked(command)
|
||||
|
||||
def test_blocks_destructive_powershell_variants(self):
|
||||
for command in ('Remove-Item build -Recurse -Force', 'Remove-Item -Path build -Rec', 'rm -r build', 'ri build -recurse',
|
||||
'Get-ChildItem x | Remove-Item -Recurse', 'git reset --hard', 'cmd /c "rd /s /q build"',
|
||||
'pwsh -NoProfile -Command "Remove-Item build -Recurse"', 'format C:'):
|
||||
with self.subTest(command=command):
|
||||
self.assertBlocked(command, 'PowerShell')
|
||||
|
||||
def test_allows_ordinary_commands(self):
|
||||
for command in ('rm build/file.txt', 'rm -r build', 'git reset HEAD file', 'git reset --soft HEAD~1', 'git clean -n',
|
||||
'git status', 'echo "rm -rf is dangerous"', 'git commit -m "avoid rm -rf; use trash"', 'ls -rf'):
|
||||
with self.subTest(command=command):
|
||||
self.assertAllowed(command)
|
||||
self.assertAllowed('Remove-Item build/file.txt', 'PowerShell')
|
||||
self.assertAllowed('Remove-Item build -Recurse:$false', 'PowerShell')
|
||||
|
||||
def test_unknown_shell_checks_both_dialects(self):
|
||||
self.assertBlocked('rm -r build', 'shell')
|
||||
self.assertBlocked('rm -rf build', 'shell')
|
||||
|
||||
def test_fails_open_on_unusable_input(self):
|
||||
for payload in ('', 'not json', '[]', '{"tool_input": "rm -rf /"}', '{"tool_input": {"command": 5}}'):
|
||||
with self.subTest(payload=payload):
|
||||
result = subprocess.run([sys.executable, str(SAFETY), '--hook'], input=payload, capture_output=True,
|
||||
encoding='utf-8', timeout=20)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
|
||||
class CommandCheckTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(directory.cleanup)
|
||||
self.workspace = Path(directory.name).resolve()
|
||||
|
||||
def test_passes_safe_command_inside_workspace(self):
|
||||
result = check(f'cat "{self.workspace / "file.txt"}"', self.workspace)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn('PASS command safety', result.stdout)
|
||||
|
||||
def test_rejects_destructive_command(self):
|
||||
result = check('git reset --hard', self.workspace)
|
||||
self.assertEqual(result.returncode, 1)
|
||||
self.assertIn('Blocked potentially destructive command', result.stderr)
|
||||
|
||||
def test_rejects_absolute_path_outside_workspace(self):
|
||||
outside = self.workspace.parent / 'elsewhere.txt'
|
||||
result = check(f'cat "{outside}"', self.workspace)
|
||||
self.assertEqual(result.returncode, 1)
|
||||
self.assertIn('outside the workspace', result.stderr)
|
||||
|
||||
def test_ignores_cmd_switches(self):
|
||||
self.assertEqual(check('cmd /c dir', self.workspace).returncode, 0)
|
||||
|
||||
|
||||
class WrapperTests(unittest.TestCase):
|
||||
def run_wrapper(self, arguments, payload=None):
|
||||
return subprocess.run(arguments, input=payload, capture_output=True, encoding='utf-8', timeout=60)
|
||||
|
||||
def test_wrappers_block_in_hook_mode_and_check_in_cli_mode(self):
|
||||
event = json.dumps({'tool_name': 'Bash', 'tool_input': {'command': 'rm -rf build'}})
|
||||
wrappers = []
|
||||
bash = shutil.which('bash')
|
||||
if os.name == 'nt':
|
||||
# System32\bash.exe is WSL; use Git Bash like the other Windows tests.
|
||||
candidate = Path(os.environ.get('ProgramFiles', 'C:/Program Files')) / 'Git/bin/bash.exe'
|
||||
bash = str(candidate) if candidate.exists() else None
|
||||
if bash:
|
||||
wrappers.append(('bash', [bash, str(SCRIPTS / 'validate-command-safety.sh')]))
|
||||
for name in ('pwsh', 'powershell'):
|
||||
executable = shutil.which(name)
|
||||
if executable:
|
||||
wrappers.append((name, [executable, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File',
|
||||
str(SCRIPTS / 'Validate-CommandSafety.ps1')]))
|
||||
if not wrappers:
|
||||
self.skipTest('No supported shell is available.')
|
||||
for name, command in wrappers:
|
||||
with self.subTest(shell=name):
|
||||
blocked = self.run_wrapper(command, event)
|
||||
self.assertEqual(blocked.returncode, 2, blocked.stderr)
|
||||
allowed = self.run_wrapper(command, json.dumps({'tool_name': 'Bash', 'tool_input': {'command': 'git status'}}))
|
||||
self.assertEqual(allowed.returncode, 0, allowed.stderr)
|
||||
cli = command + (['-Command', 'git reset --hard'] if name != 'bash' else ['git reset --hard'])
|
||||
self.assertEqual(self.run_wrapper(cli).returncode, 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -12,7 +12,6 @@ from pathlib import Path
|
||||
import queue
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
|
||||
@@ -228,6 +228,9 @@ class InstallOptionsTests(unittest.TestCase):
|
||||
commands = scripts / 'commands'
|
||||
commands.mkdir(parents=True)
|
||||
shutil.copytree(ROOT / 'scripts/lib', scripts / 'lib', ignore=shutil.ignore_patterns('__pycache__'))
|
||||
(root / 'shared/hooks/scripts').mkdir(parents=True)
|
||||
for resolver in ('resolve-python.sh', 'Resolve-Python.ps1'):
|
||||
shutil.copy(ROOT / 'shared/hooks/scripts' / resolver, root / 'shared/hooks/scripts' / resolver)
|
||||
home = Path(directory) / 'home'
|
||||
home.mkdir()
|
||||
(root / 'adapters').mkdir()
|
||||
|
||||
@@ -10,7 +10,7 @@ import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / 'scripts/lib'))
|
||||
from personal_instructions import CLIENT_FILES, START, refresh, render
|
||||
from personal_instructions import CLIENT_FILES, START, refresh, render # noqa: E402 - needs the sys.path entry above
|
||||
|
||||
|
||||
class PersonalInstructionTests(unittest.TestCase):
|
||||
|
||||
@@ -121,7 +121,7 @@ class RemoveCustomizationTests(unittest.TestCase):
|
||||
for name in ('remove-credentials.ps1', 'remove-credentials.sh'):
|
||||
shutil.copy2(ROOT / 'scripts' / 'commands' / name, commands / name)
|
||||
shutil.copy2(ROOT / 'scripts/lib/install-targets.ps1', library / 'install-targets.ps1')
|
||||
(library / 'credentials.ps1').write_text('''
|
||||
(library / 'with-credential.ps1').write_text('''
|
||||
function Assert-CredentialKey { param([string]$Value)
|
||||
if ($Value -notmatch '^[A-Za-z_][A-Za-z0-9_]{0,127}$') { throw 'Invalid credential key.' }
|
||||
}
|
||||
|
||||
@@ -61,12 +61,12 @@ 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 'SessionStart,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 'PreToolUse,SessionStart,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" }
|
||||
if ($content -notmatch 'status_line\s*=\s*\["model", "reasoning", "fast-mode", "approval-mode", "five-hour-limit", "weekly-limit", "project-name", "git-branch", "context-window-size", "context-used", "used-tokens"\]') { throw "Codex status line is incorrect in $package" }
|
||||
} elseif ((($settings.hooks.PSObject.Properties.Name | Sort-Object) -join ',') -ne 'PreCompact,SessionStart,Stop,UserPromptSubmit' -or $content -match 'flashbang-if-input' -or $settings.hooks.Stop[0].hooks[0].async) {
|
||||
} elseif ((($settings.hooks.PSObject.Properties.Name | Sort-Object) -join ',') -ne 'PreCompact,PreToolUse,SessionStart,Stop,UserPromptSubmit' -or $content -match 'flashbang-if-input' -or $settings.hooks.Stop[0].hooks[0].async) {
|
||||
throw "Claude finish hook is incorrect in $package"
|
||||
} elseif ($content -notmatch '"defaultMode"\s*:\s*"auto"') {
|
||||
throw "Claude auto permission mode is missing in $package"
|
||||
|
||||
@@ -87,7 +87,7 @@ for shell in powershell bash; do
|
||||
grep -Eq '^max_depth[[:space:]]*=[[:space:]]*1[[:space:]]*$' "$package/$file"
|
||||
grep -Fq 'status_line = ["model", "reasoning", "fast-mode", "approval-mode", "five-hour-limit", "weekly-limit", "project-name", "git-branch", "context-window-size", "context-used", "used-tokens"]' "$package/$file"
|
||||
else
|
||||
python3 -c 'import json,sys; settings=json.load(open(sys.argv[1], encoding="utf-8-sig")); assert set(settings["hooks"]) == {"PreCompact", "SessionStart", "Stop", "UserPromptSubmit"}' "$package/$file"
|
||||
python3 -c 'import json,sys; settings=json.load(open(sys.argv[1], encoding="utf-8-sig")); assert set(settings["hooks"]) == {"PreCompact", "PreToolUse", "SessionStart", "Stop", "UserPromptSubmit"}' "$package/$file"
|
||||
! grep -q 'flashbang-if-input' "$package/$file"
|
||||
! grep -q '"async"[[:space:]]*:[[:space:]]*true' "$package/$file"
|
||||
grep -q '"defaultMode"[[:space:]]*:[[:space:]]*"auto"' "$package/$file"
|
||||
|
||||
@@ -23,6 +23,8 @@ class TelemetryTests(unittest.TestCase):
|
||||
script = root / 'scripts/commands/telemetry.sh'
|
||||
script.parent.mkdir(parents=True)
|
||||
shutil.copy(ROOT / 'scripts/commands/telemetry.sh', script)
|
||||
(root / 'shared/hooks/scripts').mkdir(parents=True)
|
||||
shutil.copy(ROOT / 'shared/hooks/scripts/resolve-python.sh', root / 'shared/hooks/scripts/resolve-python.sh')
|
||||
env = dict(os.environ, AI_CONFIG_TELEMETRY='1')
|
||||
result = subprocess.run([bash, str(script), 'record', 'subagent-stop', '--role', 'reviewer', '--filesRead', '3', '--outcome', 'findings'], env=env, capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
@@ -82,7 +82,7 @@ class UserCustomizationTests(unittest.TestCase):
|
||||
finally:
|
||||
cleanup = subprocess.run([
|
||||
powershell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command',
|
||||
f". '{ROOT / 'scripts/lib/credentials.ps1'}'; Remove-ManagedCredential -Client Codex -Key {key}",
|
||||
f". '{ROOT / 'scripts/lib/with-credential.ps1'}'; Remove-ManagedCredential -Client Codex -Key {key}",
|
||||
], capture_output=True, text=True, timeout=20)
|
||||
if stored:
|
||||
self.assertEqual(0, cleanup.returncode, cleanup.stderr)
|
||||
|
||||
Reference in new issue
Block a user