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

+4 -2
View File
@@ -183,7 +183,8 @@ def codex_provenance(arm, args, cwd):
server = AppServer(codex_env(arm, args), cwd)
try:
config = server.call('config/read', {})['config']
listing = lambda: server.call('skills/list', {'cwds': [str(cwd)], 'forceReload': True})['data'][0]['skills']
def listing():
return server.call('skills/list', {'cwds': [str(cwd)], 'forceReload': True})['data'][0]['skills']
skills = listing()
if arm == 'baseline':
# Codex reads ~/.agents/skills from the real profile even with another CODEX_HOME; disable those skills there.
@@ -396,7 +397,8 @@ def summarize(results):
category = json.loads(spec.read_text(encoding='utf-8')).get('category', '?') if spec.is_file() else '?'
groups.setdefault((category, result['client'], result['arm']), []).append(result)
for (category, client, arm), runs in sorted(groups.items()):
median = lambda key: statistics.median(run[key] for run in runs)
def median(key):
return statistics.median(run[key] for run in runs)
lines.append(f'| {category} | {client} | {arm} | {len(runs)} | {sum(run["passed"] for run in runs) / len(runs):.0%} | '
f'{sum(run["first_try"] for run in runs) / len(runs):.0%} | {sum(run["rework_turns"] for run in runs)} | '
f'{median("seconds"):.0f} | {median("input_tokens"):.0f} | {median("output_tokens"):.0f} | {median("tool_calls"):.0f} | '
+3 -3
View File
@@ -10,7 +10,7 @@ $root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
. (Join-Path $root 'scripts/lib/install-targets.ps1')
$selectedClient = $Client
$selectedKey = $Key
. (Join-Path $root 'scripts/lib/credentials.ps1')
. (Join-Path $root 'scripts/lib/with-credential.ps1')
$Client = $selectedClient
$Key = $selectedKey
@@ -28,8 +28,8 @@ if ($ValueFromStdin) {
$bin = Join-Path $HomePath '.my-ai-configuration/bin'
New-Item -ItemType Directory -Path $bin -Force | Out-Null
foreach ($source in @('credentials.ps1', 'with-credential.sh')) {
$destination = Join-Path $bin $(if ($source -eq 'credentials.ps1') { 'with-credential.ps1' } else { $source })
foreach ($source in @('with-credential.ps1', 'with-credential.sh')) {
$destination = Join-Path $bin $source
if (-not (Test-Path -LiteralPath $destination)) { Copy-Item (Join-Path $root "scripts/lib/$source") $destination }
}
foreach ($target in $(if ($Client -eq 'Both') { @('Codex', 'Claude') } else { @($Client) })) {
+2 -1
View File
@@ -6,6 +6,7 @@ param(
)
$ErrorActionPreference = 'Stop'
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
. (Join-Path $root 'shared/hooks/scripts/Resolve-Python.ps1')
. (Join-Path $root 'scripts/lib/install-targets.ps1')
if (-not $Client) { $Client = Read-InstallClient -Client $Client }
@@ -19,7 +20,7 @@ foreach ($target in $(if ($Client -eq 'Both') { @('codex','claude') } else { @($
$path = Join-Path $directory "$target.md"
$prefix = if ((Test-Path -LiteralPath $path) -and (Get-Item -LiteralPath $path).Length -gt 0 -and -not (Get-Content -LiteralPath $path -Raw).EndsWith([Environment]::NewLine)) { [Environment]::NewLine } else { '' }
[System.IO.File]::AppendAllText($path, $prefix + $Instruction.TrimEnd() + [Environment]::NewLine, [System.Text.UTF8Encoding]::new($false))
& python (Join-Path $root 'scripts/lib/personal_instructions.py') --home $HomePath --client $target
Invoke-Python (Join-Path $root 'scripts/lib/personal_instructions.py') --home $HomePath --client $target
if ($LASTEXITCODE -ne 0) { throw 'Could not refresh the personal instruction rule.' }
Write-Output "Instruction added for $target."
}
+4 -3
View File
@@ -34,13 +34,14 @@ case "$home_path" in /*|[A-Za-z]:[\\/]*) ;; *) printf 'Home path must be absolut
directory="$home_path/.my-ai-configuration/instructions"
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
python_command=$(command -v python || command -v python3 || true)
[ -n "$python_command" ] || { printf 'Python is required to add instructions.\n' >&2; exit 1; }
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
. "$script_dir/../../shared/hooks/scripts/resolve-python.sh"
resolve_python || { python_missing_message >&2; exit 1; }
mkdir -p -- "$directory"
for target in "${targets[@]}"; do
path="$directory/$target.md"
[ ! -s "$path" ] || [ "$(tail -c 1 -- "$path" | wc -l)" -eq 1 ] || printf '\n' >> "$path"
printf '%s\n' "$instruction" >> "$path"
"$python_command" "$script_dir/../lib/personal_instructions.py" --home "$home_path" --client "$target"
run_python "$script_dir/../lib/personal_instructions.py" --home "$home_path" --client "$target"
printf 'Instruction added for %s.\n' "$target"
done
+2 -1
View File
@@ -1,4 +1,5 @@
$ErrorActionPreference = 'Stop'
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
& python (Join-Path $root 'scripts/benchmarks/ab.py') @args
. (Join-Path $root 'shared/hooks/scripts/Resolve-Python.ps1')
Invoke-Python (Join-Path $root 'scripts/benchmarks/ab.py') @args
exit $LASTEXITCODE
+4 -1
View File
@@ -1,4 +1,7 @@
#!/usr/bin/env bash
set -euo pipefail
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
exec python3 "$root/scripts/benchmarks/ab.py" "$@"
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
. "$root/shared/hooks/scripts/resolve-python.sh"
resolve_python || { python_missing_message >&2; exit 127; }
run_python "$root/scripts/benchmarks/ab.py" "$@"
+28 -31
View File
@@ -2,12 +2,15 @@
param([switch]$Summary)
$ErrorActionPreference = 'Stop'
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
. (Join-Path $root 'shared/hooks/scripts/Resolve-Python.ps1')
$shared = Join-Path $root 'shared'
$final = Join-Path $root 'generated'
# Keep the name short: it lengthens every generated path, and Windows PowerShell 5.1 fails beyond 260 characters.
$output = Join-Path $root ("generated.build-ps$PID-" + [Guid]::NewGuid().ToString('N').Substring(0, 6))
# A trap covers the whole script scope, so every terminating error discards this run's tree.
trap { Remove-Item -LiteralPath $output -Recurse -Force -ErrorAction SilentlyContinue; break }
# Fail early with an actionable message instead of a generic validation error after the build.
$null = Get-PythonCommand -Required
$sandboxSupported = [Environment]::OSVersion.Platform -eq [PlatformID]::Unix
if ($sandboxSupported) {
$kernel = (& uname -r 2>$null | Out-String).Trim()
@@ -16,6 +19,21 @@ if ($sandboxSupported) {
$claudeSandbox = if ($sandboxSupported) { '{"enabled": true, "allowUnsandboxedCommands": false, "failIfUnavailable": true, "network": {"allowedDomains": ["mcp.context7.com"]}}' } else { '{"enabled": false}' }
$pluginManifest = Join-Path $root 'adapters/plugins.tsv'
$capabilityManifest = Join-Path $root 'adapters/claude/capabilities.tsv'
$placeholderManifest = Join-Path $root 'adapters/placeholders.tsv'
# Shell-specific template values live in one table shared with build.sh, so adding a hook or
# script means adding one row instead of editing both builds.
if (-not (Test-Path -LiteralPath $placeholderManifest)) { throw "Missing placeholder manifest: $placeholderManifest" }
$placeholders = @(Import-Csv -LiteralPath $placeholderManifest -Delimiter ([char]9))
foreach ($placeholder in $placeholders) {
if ($placeholder.placeholder -cnotmatch '^__[A-Z0-9_]+__$' -or [string]::IsNullOrEmpty($placeholder.powershell) -or [string]::IsNullOrEmpty($placeholder.bash)) {
throw "Invalid placeholder manifest row: $($placeholder.placeholder)"
}
}
function Expand-ShellPlaceholders([string]$text, [string]$shell) {
foreach ($placeholder in $placeholders) { $text = $text.Replace($placeholder.placeholder, $placeholder.$shell) }
return $text
}
if (-not (Test-Path -LiteralPath $pluginManifest)) { throw "Missing plugin manifest: $pluginManifest" }
$pluginEntries = @(Import-Csv -LiteralPath $pluginManifest -Delimiter ([char]9))
@@ -158,17 +176,11 @@ foreach ($shell in @('powershell','bash')) {
}
}
$sharedTemplate = Get-Content (Join-Path $shared 'global-instructions.md') -Raw
$generalContent = Get-Content (Join-Path $shared 'rules/general.md') -Raw
$credentialHelperExtension = if ($shell -eq 'powershell') { 'ps1' } else { 'sh' }
$agentsContent = $sharedTemplate.Replace('__CLIENT__', 'codex').Replace('__SHELL__', $credentialHelperExtension)
$agentsContent = $agentsContent.TrimEnd() + "`r`n`r`n---`r`n`r`n$generalContent"
Set-Content (Join-Path $output "codex-$shell/AGENTS.md") $agentsContent -Encoding UTF8
$claudeContent = $sharedTemplate.Replace('__CLIENT__', 'claude').Replace('__SHELL__', $credentialHelperExtension)
$claudeContent = $claudeContent.TrimEnd() + "`r`n`r`n---`r`n`r`n$generalContent"
Set-Content (Join-Path $output "claude-$shell/CLAUDE.md") $claudeContent -Encoding UTF8
$instructionsContent = Expand-ShellPlaceholders (Get-Content (Join-Path $shared 'global-instructions.md') -Raw) $shell
$instructionsContent = $instructionsContent.TrimEnd() + "`r`n`r`n---`r`n`r`n$generalContent"
Set-Content (Join-Path $output "codex-$shell/AGENTS.md") $instructionsContent -Encoding UTF8
Set-Content (Join-Path $output "claude-$shell/CLAUDE.md") $instructionsContent -Encoding UTF8
Copy-Item (Join-Path $root 'adapters/codex/config/config.toml') (Join-Path $output "codex-$shell/config.toml") -Force
Copy-Item (Join-Path $root 'adapters/claude/config/settings.json') (Join-Path $output "claude-$shell/settings.json") -Force
@@ -185,9 +197,8 @@ foreach ($shell in @('powershell','bash')) {
if ($client -eq 'codex') {
Set-Content (Join-Path $agentsOutput "$name.toml") "name = $(Quote-Toml $name)`r`ndescription = $(Quote-Toml $description)`r`ndeveloper_instructions = $(Quote-Toml $instructions)" -Encoding UTF8
} else {
$shellTool = if ($shell -eq 'powershell') { 'PowerShell' } else { 'Bash' }
$tools = $agentTools[$name]
if ($tools) { $tools = $tools.Replace('__SHELL__', $shellTool) }
if ($tools) { $tools = Expand-ShellPlaceholders $tools $shell }
$frontmatter = "---`r`nname: $name`r`ndescription: $description`r`n"
if ($tools) { $frontmatter += "tools: $tools`r`n" }
Set-Content (Join-Path $agentsOutput "$name.md") ($frontmatter + "---`r`n`r`n$instructions") -Encoding UTF8
@@ -195,30 +206,16 @@ foreach ($shell in @('powershell','bash')) {
}
}
foreach ($client in @('codex','claude')) {
$file = if ($client -eq 'codex') { 'config.toml' } else { 'settings.json' }
$path = Join-Path $output "$client-$shell/$file"
$command = if ($shell -eq 'powershell') { '__POWERSHELL_COMMAND__' } else { 'bash' }
$script = if ($shell -eq 'powershell') { 'flashbang.ps1' } else { 'flashbang.sh' }
$statusLineScript = if ($shell -eq 'powershell') { 'statusline.ps1' } else { 'statusline.sh' }
$content = Get-Content -LiteralPath $path -Raw
# Claude can offer both shell tools on Windows, so every package denies the destructive commands in both.
$denyRules = @('PowerShell(git reset --hard*)','PowerShell(git clean*)','PowerShell(Remove-Item *-Recurse*)','Bash(git reset --hard*)','Bash(git clean*)','Bash(rm -rf*)')
$denyRulesJson = ConvertTo-Json -InputObject $denyRules -Compress
$shellTool = if ($shell -eq 'powershell') { 'PowerShell' } else { 'Bash' }
$allowRulesJson = ConvertTo-Json -InputObject @('Agent', "$shellTool(mcporter call context7.*)") -Compress
$compactScript = if ($shell -eq 'powershell') { 'Record-Compact.ps1' } else { 'record-compact.sh' }
$pointerScript = if ($shell -eq 'powershell') { 'Show-SessionStatePointer.ps1' } else { 'show-session-state-pointer.sh' }
$qmdWarmScript = if ($shell -eq 'powershell') { 'Start-QmdWarm.ps1' } else { 'qmd-warm.sh' }
$correctionPromptScript = if ($shell -eq 'powershell') { 'Show-CorrectionPrompt.ps1' } else { 'show-correction-prompt.sh' }
$completionEvidenceScript = if ($shell -eq 'powershell') { 'Check-CompletionEvidence.ps1' } else { 'check-completion-evidence.sh' }
$content = $content.Replace('__HOOK_COMMAND__', $command).Replace('__POWERSHELL_HOOK_COMMAND__', $command).Replace('__HOOK_SCRIPT__', $script).Replace('__POWERSHELL_HOOK_SCRIPT__', $script).Replace('__COMPACT_SCRIPT__', $compactScript).Replace('__SESSION_POINTER_SCRIPT__', $pointerScript).Replace('__QMD_WARM_SCRIPT__', $qmdWarmScript).Replace('__CORRECTION_PROMPT_SCRIPT__', $correctionPromptScript).Replace('__COMPLETION_EVIDENCE_SCRIPT__', $completionEvidenceScript).Replace('__STATUSLINE_COMMAND__', $command).Replace('__STATUSLINE_SCRIPT__', $statusLineScript).Replace('__CLAUDE_SANDBOX__', $claudeSandbox).Replace('__CLAUDE_DENY_RULES__', $denyRulesJson).Replace('__CLAUDE_ALLOW_RULES__', $allowRulesJson)
foreach ($path in @((Join-Path $output "codex-$shell/config.toml"), (Join-Path $output "claude-$shell/settings.json"))) {
$content = Expand-ShellPlaceholders (Get-Content -LiteralPath $path -Raw) $shell
# The sandbox depends on the build platform, not the shell, so it is not part of the placeholder table.
$content = $content.Replace('__CLAUDE_SANDBOX__', $claudeSandbox)
Set-Content -LiteralPath $path -Value $content -Encoding UTF8
}
$tomlPath = Join-Path $output "codex-$shell/config.toml"
$settingsPath = Join-Path $output "claude-$shell/settings.json"
& python (Join-Path $root 'scripts/checks/validate-config.py') $tomlPath $settingsPath
Invoke-Python (Join-Path $root 'scripts/checks/validate-config.py') $tomlPath $settingsPath
if ($LASTEXITCODE -ne 0) { throw "Generated configuration validation failed for $shell." }
Test-CodexSchema $tomlPath
}
+39 -60
View File
@@ -9,6 +9,10 @@ while [ $# -gt 0 ]; do
done
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
. "$root/shared/hooks/scripts/resolve-python.sh"
# Fail early with an actionable message instead of a generic validation error after the build.
resolve_python || { python_missing_message >&2; exit 1; }
shared="$root/shared"
final="$root/generated"
sandbox_supported=false
@@ -27,6 +31,32 @@ sandbox='{"enabled": false}'
[ "$sandbox_supported" != true ] || sandbox='{"enabled": true, "allowUnsandboxedCommands": false, "failIfUnavailable": true, "network": {"allowedDomains": ["mcp.context7.com"]}}'
plugin_manifest="$root/adapters/plugins.tsv"
capability_manifest="$root/adapters/claude/capabilities.tsv"
placeholder_manifest="$root/adapters/placeholders.tsv"
# Shell-specific template values live in one table shared with build.ps1, so adding a hook or
# script means adding one row instead of editing both builds.
[ -f "$placeholder_manifest" ] || { printf 'Missing placeholder manifest: %s\n' "$placeholder_manifest" >&2; exit 1; }
placeholder_names=()
placeholder_powershell=()
placeholder_bash=()
while IFS=$'\t' read -r placeholder powershell_value bash_value; do
bash_value=${bash_value%$'\r'}
[ "$placeholder" != placeholder ] || continue
[ -n "$placeholder" ] || continue
[[ "$placeholder" =~ ^__[A-Z0-9_]+__$ ]] && [ -n "$powershell_value" ] && [ -n "$bash_value" ] || { printf 'Invalid placeholder manifest row: %s\n' "$placeholder" >&2; exit 1; }
placeholder_names+=("$placeholder")
placeholder_powershell+=("$powershell_value")
placeholder_bash+=("$bash_value")
done < "$placeholder_manifest"
expand_shell_placeholders() {
local text=$1 shell=$2 index value
for index in "${!placeholder_names[@]}"; do
if [ "$shell" = powershell ]; then value=${placeholder_powershell[$index]}; else value=${placeholder_bash[$index]}; fi
text=${text//"${placeholder_names[$index]}"/"$value"}
done
printf '%s' "$text"
}
[ -f "$plugin_manifest" ] || { printf 'Missing plugin manifest: %s\n' "$plugin_manifest" >&2; exit 1; }
awk -F '\t' 'NR == 1 { next } NF == 0 { next } $1 == "" || $3 == "" || $6 == "" { print "Invalid plugin manifest row." > "/dev/stderr"; exit 1 } seen[$1]++ { print "Duplicate plugin name in manifest: " $1 > "/dev/stderr"; exit 1 }' "$plugin_manifest"
@@ -151,18 +181,10 @@ while IFS= read -r rule_path; do
fi
done < <(find "$shared/rules" -mindepth 1 -type f -name '*.md' -printf '%P\n' | sort)
shared_template=$(<"$shared/global-instructions.md")
instructions_content=$(expand_shell_placeholders "$(<"$shared/global-instructions.md")" "$shell")
general_content=$(<"$shared/rules/general.md")
credential_helper_extension='sh'
[ "$shell" != powershell ] || credential_helper_extension='ps1'
agents_content=${shared_template//__CLIENT__/codex}
agents_content=${agents_content//__SHELL__/$credential_helper_extension}
printf '%s\n\n---\n\n%s\n' "${agents_content%$'\n'}" "$general_content" > "$output/codex-$shell/AGENTS.md"
claude_content=${shared_template//__CLIENT__/claude}
claude_content=${claude_content//__SHELL__/$credential_helper_extension}
printf '%s\n\n---\n\n%s\n' "${claude_content%$'\n'}" "$general_content" > "$output/claude-$shell/CLAUDE.md"
printf '%s\n\n---\n\n%s\n' "${instructions_content%$'\n'}" "$general_content" > "$output/codex-$shell/AGENTS.md"
printf '%s\n\n---\n\n%s\n' "${instructions_content%$'\n'}" "$general_content" > "$output/claude-$shell/CLAUDE.md"
cp "$root/adapters/codex/config/config.toml" "$output/codex-$shell/config.toml"
cp "$root/adapters/claude/config/settings.json" "$output/claude-$shell/settings.json"
@@ -178,65 +200,22 @@ for client in codex claude; do
if [ "$client" = codex ]; then
printf 'name = %s\ndescription = %s\ndeveloper_instructions = %s\n' "$(quote_toml "$name")" "$(quote_toml "$description")" "$(quote_toml "$instructions")" > "$agents_output/$name.toml"
else
tools=${agent_tools[$name]:-}
shell_tool=Bash
[ "$shell" != powershell ] || shell_tool=PowerShell
tools=${tools//__SHELL__/$shell_tool}
tools=$(expand_shell_placeholders "${agent_tools[$name]:-}" "$shell")
if [ -n "$tools" ]; then printf '%s\nname: %s\ndescription: %s\ntools: %s\n%s\n\n%s\n' '---' "$name" "$description" "$tools" '---' "$instructions" > "$agents_output/$name.md"; else printf '%s\nname: %s\ndescription: %s\n%s\n\n%s\n' '---' "$name" "$description" '---' "$instructions" > "$agents_output/$name.md"; fi
fi
done
done
for client in codex claude; do
file=config.toml
[ "$client" != claude ] || file=settings.json
command=bash
script=flashbang.sh
statusline_script=statusline.sh
compact_script=record-compact.sh
pointer_script=show-session-state-pointer.sh
qmd_warm_script=qmd-warm.sh
correction_prompt_script=show-correction-prompt.sh
completion_evidence_script=check-completion-evidence.sh
if [ "$shell" = powershell ]; then
command='__POWERSHELL_COMMAND__'
script=flashbang.ps1
statusline_script=statusline.ps1
compact_script=Record-Compact.ps1
pointer_script=Show-SessionStatePointer.ps1
qmd_warm_script=Start-QmdWarm.ps1
correction_prompt_script=Show-CorrectionPrompt.ps1
completion_evidence_script=Check-CompletionEvidence.ps1
fi
path="$output/$client-$shell/$file"
content=$(<"$path")
# Claude can offer both shell tools on Windows, so every package denies the destructive commands in both.
deny_rules='["PowerShell(git reset --hard*)","PowerShell(git clean*)","PowerShell(Remove-Item *-Recurse*)","Bash(git reset --hard*)","Bash(git clean*)","Bash(rm -rf*)"]'
if [ "$shell" = powershell ]; then
allow_rules='["Agent","PowerShell(mcporter call context7.*)"]'
else
allow_rules='["Agent","Bash(mcporter call context7.*)"]'
fi
content=${content//__HOOK_COMMAND__/$command}
content=${content//__POWERSHELL_HOOK_COMMAND__/$command}
content=${content//__HOOK_SCRIPT__/$script}
content=${content//__POWERSHELL_HOOK_SCRIPT__/$script}
content=${content//__COMPACT_SCRIPT__/$compact_script}
content=${content//__SESSION_POINTER_SCRIPT__/$pointer_script}
content=${content//__QMD_WARM_SCRIPT__/$qmd_warm_script}
content=${content//__CORRECTION_PROMPT_SCRIPT__/$correction_prompt_script}
content=${content//__COMPLETION_EVIDENCE_SCRIPT__/$completion_evidence_script}
content=${content//__STATUSLINE_COMMAND__/$command}
content=${content//__STATUSLINE_SCRIPT__/$statusline_script}
content=${content//__CLAUDE_SANDBOX__/$sandbox}
content=${content//__CLAUDE_DENY_RULES__/$deny_rules}
content=${content//__CLAUDE_ALLOW_RULES__/$allow_rules}
for path in "$output/codex-$shell/config.toml" "$output/claude-$shell/settings.json"; do
content=$(expand_shell_placeholders "$(<"$path")" "$shell")
# The sandbox depends on the build platform, not the shell, so it is not part of the placeholder table.
content=${content//__CLAUDE_SANDBOX__/"$sandbox"}
printf '%s\n' "$content" > "$path"
done
toml_path="$output/codex-$shell/config.toml"
settings_path="$output/claude-$shell/settings.json"
python3 "$root/scripts/checks/validate-config.py" "$toml_path" "$settings_path"
run_python "$root/scripts/checks/validate-config.py" "$toml_path" "$settings_path"
if command -v codex >/dev/null; then
schema_home=$(mktemp -d)
cp "$toml_path" "$schema_home/config.toml"
+6 -8
View File
@@ -11,14 +11,12 @@ function Check-Version([string]$name, [string]$version, [version]$minimum) { if
Check-Version 'PowerShell' $PSVersionTable.PSVersion.ToString() ([version]'5.1')
if (Get-Command jq -ErrorAction SilentlyContinue) { Pass 'jq available for Claude Bash status line' }
else { Write-Warning 'jq unavailable; Claude Bash status line is disabled' }
$pythonVersion = $null
foreach ($python in @('python', 'python3')) {
if (-not (Get-Command $python -ErrorAction SilentlyContinue)) { continue }
$candidate = & $python --version 2>$null
$pythonExitCode = $LASTEXITCODE
if ($pythonExitCode -eq 0) { $pythonVersion = $candidate -replace '^Python\s+', ''; break }
}
if ($null -ne $pythonVersion) { Check-Version 'Python' $pythonVersion ([version]'3.11') } else { Fail 'Python 3.11 or newer is required' }
. (Join-Path (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent) 'shared/hooks/scripts/Resolve-Python.ps1')
$python = Get-PythonCommand
if ($python) {
$pythonVersion = (& $python.Path @($python.Arguments) -c 'import platform; print(platform.python_version())' 2>$null | Out-String).Trim()
Check-Version 'Python' $pythonVersion ([version]'3.11')
} else { Fail (Get-PythonMissingMessage) }
if ($failed) { Write-Error 'Capability check: FAIL'; exit 1 }
Write-Output 'Capability check: PASS'
+6 -5
View File
@@ -8,7 +8,7 @@ require_command() {
if command -v "$1" >/dev/null 2>&1; then pass "$1 available"; else fail "$1 is required"; fi
}
version_at_least() {
awk -F. -v required="$2" 'BEGIN { split(required,r) } { split($1,v); if (v[1]+0 > r[1]+0 || (v[1]+0 == r[1]+0 && v[2]+0 >= r[2]+0)) exit 0; exit 1 }' <<<"$1"
awk -v required="$2" 'BEGIN { split(required,r,".") } { split($0,v,"."); if (v[1]+0 > r[1]+0 || (v[1]+0 == r[1]+0 && v[2]+0 >= r[2]+0)) exit 0; exit 1 }' <<<"$1"
}
check_version() {
local name=$1 version=$2 required=$3
@@ -18,11 +18,12 @@ check_version() {
check_version Bash "${BASH_VERSINFO[0]}.${BASH_VERSINFO[1]}" 4.3
require_command awk; require_command sed; require_command sha256sum
if command -v jq >/dev/null 2>&1; then pass 'jq available for Claude Bash status line'; else printf 'WARN jq unavailable; Claude Bash status line is disabled\n' >&2; fi
require_command python3
if command -v python3 >/dev/null 2>&1 && python3 -c 'import sys; raise SystemExit(sys.version_info < (3, 11))' >/dev/null 2>&1; then
pass "Python $(python3 --version 2>&1 | awk '{print $2}') (minimum 3.11)"
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
. "$(dirname -- "${BASH_SOURCE[0]}")/../../shared/hooks/scripts/resolve-python.sh"
if resolve_python; then
check_version Python "$(run_python -c 'import platform; print(platform.python_version())')" 3.11
else
fail 'Python 3.11 or newer is required'
fail "$(python_missing_message)"
fi
if [ "$failed" = true ]; then printf 'Capability check: FAIL\n' >&2; exit 1; fi
+2 -1
View File
@@ -1,4 +1,5 @@
$ErrorActionPreference = 'Stop'
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
& python (Join-Path $root 'scripts/benchmarks/context.py') @args
. (Join-Path $root 'shared/hooks/scripts/Resolve-Python.ps1')
Invoke-Python (Join-Path $root 'scripts/benchmarks/context.py') @args
exit $LASTEXITCODE
+4 -1
View File
@@ -1,4 +1,7 @@
#!/usr/bin/env bash
set -euo pipefail
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
exec python3 "$root/scripts/benchmarks/context.py" "$@"
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
. "$root/shared/hooks/scripts/resolve-python.sh"
resolve_python || { python_missing_message >&2; exit 127; }
run_python "$root/scripts/benchmarks/context.py" "$@"
+9 -2
View File
@@ -3,6 +3,7 @@ param([switch]$Summary)
$ErrorActionPreference = 'Stop'
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
. (Join-Path $root 'scripts/lib/manifest.ps1')
. (Join-Path $root 'shared/hooks/scripts/Resolve-Python.ps1')
$homePath = [Environment]::GetFolderPath('UserProfile')
if ([string]::IsNullOrWhiteSpace($homePath)) { $homePath = $HOME }
$script:fail = $false
@@ -37,6 +38,9 @@ foreach ($tool in @('codex','claude')) {
} else { Result 'WARN' "$tool unavailable" }
}
if (Get-Command jq -ErrorAction SilentlyContinue) { Result 'PASS' 'jq available for Claude Bash status line' } else { Result 'WARN' 'jq unavailable; Claude Bash status line is disabled' }
$python = Get-PythonCommand
if ($python) { Result 'PASS' "Python available ($($python.Display))" }
else { Result 'FAIL' "$(Get-PythonMissingMessage) Without it, build validation fails and the completion-evidence, correction-prompt, and session-state hooks are silently skipped." }
$sourceAgentCount = @(Get-ChildItem (Join-Path $root 'shared/agents') -Directory -ErrorAction SilentlyContinue).Count
$sourceSkillCount = @(Get-ChildItem (Join-Path $root 'shared/skills') -Filter 'SKILL.md' -Recurse -ErrorAction SilentlyContinue).Count
@@ -71,8 +75,11 @@ if (Test-Path -LiteralPath $settingsPath) {
}
$configTomlPath = Join-Path $homePath '.codex/config.toml'
if (Test-Path -LiteralPath $configTomlPath) {
$parseResult = Invoke-DoctorCommand -Command 'python' -Arguments @('-c', "import sys,tomllib,pathlib; tomllib.loads(pathlib.Path(sys.argv[1]).read_text(encoding='utf-8-sig'))", $configTomlPath)
if ($parseResult.ExitCode -eq 0) { Result 'PASS' 'installed .codex/config.toml parses as TOML' } else { Result 'FAIL' "installed .codex/config.toml is invalid TOML: $($parseResult.Output -join ' ')" }
if (-not $python) { Result 'WARN' 'Python unavailable; skipped installed .codex/config.toml TOML check' }
else {
$parseResult = Invoke-DoctorCommand -Command $python.Path -Arguments (@($python.Arguments) + @('-c', "import sys,tomllib,pathlib; tomllib.loads(pathlib.Path(sys.argv[1]).read_text(encoding='utf-8-sig'))", $configTomlPath))
if ($parseResult.ExitCode -eq 0) { Result 'PASS' 'installed .codex/config.toml parses as TOML' } else { Result 'FAIL' "installed .codex/config.toml is invalid TOML: $($parseResult.Output -join ' ')" }
}
if (Get-Command codex -ErrorAction SilentlyContinue) {
$previousCodexHome = $env:CODEX_HOME
try {
+13 -3
View File
@@ -10,6 +10,9 @@ while [ $# -gt 0 ]; do
done
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
. "$root/shared/hooks/scripts/resolve-python.sh"
resolve_python || true
. "$root/scripts/lib/manifest.sh"
home_path=${HOME:?HOME is required}
failed=false
@@ -33,6 +36,11 @@ for tool in codex claude; do
else result WARN "$tool unavailable"; fi
done
command -v jq >/dev/null && result PASS 'jq available for Claude Bash status line' || result WARN 'jq unavailable; Claude Bash status line is disabled'
if resolve_python; then
result PASS "Python available ($(python_display))"
else
result FAIL "$(python_missing_message) Without it, build validation fails and the completion-evidence, correction-prompt, and session-state hooks are silently skipped."
fi
source_agent_count=$(find "$root/shared/agents" -mindepth 1 -maxdepth 1 -type d 2>/dev/null | wc -l)
source_skill_count=$(find "$root/shared/skills" -name SKILL.md | wc -l)
@@ -62,8 +70,8 @@ done
if [ -f "$home_path/.claude/settings.json" ]; then
if command -v jq >/dev/null 2>&1; then
if jq empty "$home_path/.claude/settings.json" >/dev/null 2>&1; then result PASS 'installed .claude/settings.json is valid JSON'; else result FAIL 'installed .claude/settings.json is not valid JSON'; fi
elif command -v python3 >/dev/null 2>&1 && python3 --version >/dev/null 2>&1; then
if python3 -c 'import json,sys; json.load(open(sys.argv[1], encoding="utf-8"))' "$home_path/.claude/settings.json" 2>/dev/null; then
elif resolve_python; then
if run_python -c 'import json,sys; json.load(open(sys.argv[1], encoding="utf-8"))' "$home_path/.claude/settings.json" 2>/dev/null; then
result PASS 'installed .claude/settings.json is valid JSON'
else
result FAIL 'installed .claude/settings.json is not valid JSON'
@@ -71,7 +79,9 @@ if [ -f "$home_path/.claude/settings.json" ]; then
fi
fi
if [ -f "$home_path/.codex/config.toml" ]; then
if python3 -c 'import sys,tomllib,pathlib; tomllib.loads(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8-sig"))' "$home_path/.codex/config.toml"; then
if ! resolve_python; then
result WARN 'Python unavailable; skipped installed .codex/config.toml TOML check'
elif run_python -c 'import sys,tomllib,pathlib; tomllib.loads(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8-sig"))' "$home_path/.codex/config.toml"; then
result PASS 'installed .codex/config.toml parses as TOML'
else
result FAIL 'installed .codex/config.toml is invalid TOML'
+3 -2
View File
@@ -2,11 +2,12 @@
param([switch]$Summary)
$ErrorActionPreference = 'Stop'
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
. (Join-Path $root 'shared/hooks/scripts/Resolve-Python.ps1')
$budgetScript = Join-Path $root 'scripts/lib/prompt-budget.py'
$budgetArgs = @()
if ($Summary) { $budgetArgs += '--summary' }
& python $budgetScript @budgetArgs
Invoke-Python $budgetScript @budgetArgs
$budgetExit = $LASTEXITCODE
& python (Join-Path $root 'scripts/lib/prompt-inventory.py') --home ([Environment]::GetFolderPath('UserProfile'))
Invoke-Python (Join-Path $root 'scripts/lib/prompt-inventory.py') --home ([Environment]::GetFolderPath('UserProfile'))
if ($LASTEXITCODE -ne 0) { throw 'Prompt inventory failed.' }
exit $budgetExit
+5 -2
View File
@@ -3,9 +3,12 @@ set -euo pipefail
summary=false
for arg in "$@"; do case "$arg" in --summary) summary=true;; *) printf 'Unknown argument: %s\n' "$arg" >&2; exit 1;; esac; done
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
. "$root/shared/hooks/scripts/resolve-python.sh"
resolve_python || true
budget_args=()
[ "$summary" = false ] || budget_args+=(--summary)
budget_status=0
python3 "$root/scripts/lib/prompt-budget.py" "${budget_args[@]}" || budget_status=$?
python3 "$root/scripts/lib/prompt-inventory.py" --home "${HOME:?HOME is required}"
run_python "$root/scripts/lib/prompt-budget.py" "${budget_args[@]}" || budget_status=$?
run_python "$root/scripts/lib/prompt-inventory.py" --home "${HOME:?HOME is required}"
exit "$budget_status"
+1 -1
View File
@@ -8,7 +8,7 @@ $root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
. (Join-Path $root 'scripts/lib/install-targets.ps1')
$selectedClient = $Client
$selectedKey = $Key
. (Join-Path $root 'scripts/lib/credentials.ps1')
. (Join-Path $root 'scripts/lib/with-credential.ps1')
$Client = $selectedClient
$Key = $selectedKey
+2 -1
View File
@@ -6,10 +6,11 @@ param(
)
$ErrorActionPreference = 'Stop'
$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
. (Join-Path $root 'shared/hooks/scripts/Resolve-Python.ps1')
. (Join-Path $root 'scripts/lib/install-targets.ps1')
if (-not $Client) { $Client = Read-InstallClient -Client $Client }
if (-not $PSBoundParameters.ContainsKey('Instruction')) { $Instruction = Read-Host 'Instruction to remove' }
if ([string]::IsNullOrWhiteSpace($Instruction) -or $Instruction.Length -gt 65536) { throw 'Instruction must contain between 1 and 65536 characters.' }
& python (Join-Path $root 'scripts/lib/remove-instruction.py') --client $Client.ToLowerInvariant() --instruction $Instruction.TrimEnd() --home $HomePath
Invoke-Python (Join-Path $root 'scripts/lib/remove-instruction.py') --client $Client.ToLowerInvariant() --instruction $Instruction.TrimEnd() --home $HomePath
if ($LASTEXITCODE -ne 0) { throw 'Instruction removal failed.' }
+4 -3
View File
@@ -19,6 +19,7 @@ case "$client" in codex|Codex|claude|Claude|both|Both) ;; *) printf 'Unknown --c
case "$home_path" in /*|[A-Za-z]:[\\/]*) ;; *) printf 'Home path must be absolute.\n' >&2; exit 1 ;; esac
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
python_command=$(command -v python || command -v python3 || true)
[ -n "$python_command" ] || { printf 'Python is required to remove instructions.\n' >&2; exit 1; }
"$python_command" "$script_dir/../lib/remove-instruction.py" --client "${client,,}" --instruction "$instruction" --home "$home_path"
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
. "$script_dir/../../shared/hooks/scripts/resolve-python.sh"
resolve_python || { python_missing_message >&2; exit 1; }
run_python "$script_dir/../lib/remove-instruction.py" --client "${client,,}" --instruction "$instruction" --home "$home_path"
+3 -1
View File
@@ -27,5 +27,7 @@ if ($Pointer) { $arguments += '--pointer' }
if ($Reset) { $arguments += '--reset' }
$payload = $values | ConvertTo-Json -Depth 4 -Compress
$payload = [regex]::Replace($payload, '[^\x00-\x7F]', { param($match) '\u{0:x4}' -f [int][char]$match.Value })
$payload | & python @arguments
. (Join-Path $PSScriptRoot '../../shared/hooks/scripts/Resolve-Python.ps1')
$python = Get-PythonCommand -Required
$payload | & $python.Path @($python.Arguments) @arguments
exit $LASTEXITCODE
+4 -1
View File
@@ -1,6 +1,9 @@
#!/usr/bin/env bash
set -euo pipefail
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
. "$root/shared/hooks/scripts/resolve-python.sh"
resolve_python || true
arguments=()
if [ "${AI_TASK_GOAL+x}" = x ]; then arguments+=(--goal "$AI_TASK_GOAL"); fi
python3 "$root/shared/hooks/scripts/session-state.py" "${arguments[@]}" "$@"
run_python "$root/shared/hooks/scripts/session-state.py" "${arguments[@]}" "$@"
+5 -2
View File
@@ -2,10 +2,13 @@
set -euo pipefail
[ "${AI_CONFIG_TELEMETRY:-1}" = 0 ] && exit 0
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd); dir="$root/.ai-session"; path="$dir/telemetry.jsonl"; mkdir -p "$dir"
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
. "$root/shared/hooks/scripts/resolve-python.sh"
resolve_python || true
action=${1:-record}; shift || true
case "$action" in
rotate) [ -f "$path" ] && mv -f "$path" "$path.1"; exit 0;;
summary) [ -f "$path" ] || { printf 'Telemetry: no events\n'; exit 0; }; python3 - "$path" <<'PY' || exit 0
summary) [ -f "$path" ] || { printf 'Telemetry: no events\n'; exit 0; }; run_python - "$path" <<'PY' || exit 0
import json,sys,statistics
rows=[]
for line in open(sys.argv[1],encoding='utf-8',errors='replace'):
@@ -20,7 +23,7 @@ PY
exit 0;;
record) event=${1:?event required}; shift;; *) printf 'Unknown action: %s\n' "$action" >&2; exit 1;;
esac
python3 - "$path" "$event" "$@" <<'PY' || exit 0
run_python - "$path" "$event" "$@" <<'PY' || exit 0
import json,sys,datetime
path,event=sys.argv[1:3]; args=sys.argv[3:]
record={'event':event,'timestamp':datetime.datetime.now(datetime.timezone.utc).isoformat()}
+8 -4
View File
@@ -8,13 +8,17 @@ import tomllib
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)\.(?:ps1|sh)'
def is_flashbang(hook):
return any(re.search(r'(?:[/\\\s"\x27]|^)flashbang\.(?:ps1|sh)(?:[\s"\x27]|$)', str(hook.get(key, '')), re.I)
for key in ('command', 'command_windows'))
def is_qmd_warm(hook):
return any(re.search(r'(?:[/\\\s"\x27]|^)(?:qmd-warm\.sh|Start-QmdWarm\.ps1)(?:[\s"\x27]|$)', str(hook.get(key, '')), re.I)
return any(re.search(r'(?:[/\\\s"\x27]|^)(?:(?:start-)?qmd-warm\.sh|Start-QmdWarm\.ps1)(?:[\s"\x27]|$)', str(hook.get(key, '')), re.I)
for key in ('command', 'command_windows'))
@@ -108,7 +112,7 @@ def merge_json(current, managed):
for key, value in managed.items():
if key == 'hooks' and isinstance(value, dict) and isinstance(result.get(key), dict):
hooks = dict(result[key])
for event in set(value) | {'Stop', 'SessionStart', 'UserPromptSubmit'}:
for event in set(value) | {'Stop', 'SessionStart', 'UserPromptSubmit', 'PreToolUse'}:
groups = value.get(event, [])
old_groups = hooks.get(event, [])
if isinstance(groups, list) and isinstance(old_groups, list):
@@ -118,7 +122,7 @@ def merge_json(current, managed):
retained.append(group)
continue
foreign = [hook for hook in group['hooks'] if not (isinstance(hook, dict) and re.search(
r'(?:flashbang|statusline|record-compact|session-state-pointer|qmd-warm|Start-QmdWarm|completion-?evidence|correction-?prompt)\.(?:ps1|sh)',
OWNED_HOOK_PATTERN,
str(hook.get('command', '')) + str(hook.get('command_windows', '')), re.I))]
if foreign:
retained.append(dict(group, hooks=foreign))
@@ -167,7 +171,7 @@ def merge_toml(current_text, managed_text, statusline_enabled=True):
managed_headers = {header for header, _ in managed_sections}
extras = []
fields_by_header = {}
owned_pattern = r'(?:flashbang|statusline|record-compact|session-state-pointer|qmd-warm|Start-QmdWarm|completion-?evidence|correction-?prompt)\.(?:ps1|sh)'
owned_pattern = OWNED_HOOK_PATTERN
for index, (header, block) in enumerate(current_sections):
plugin_table = re.match(r'^\[(?:plugins|marketplaces)(?:\.|\])', header)
array_table = header.startswith('[[')
+4 -1
View File
@@ -1,4 +1,7 @@
#!/usr/bin/env bash
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
. "$(dirname -- "${BASH_SOURCE[0]}")/../../shared/hooks/scripts/resolve-python.sh"
resolve_python || true
# shellcheck disable=SC2154
read_install_boolean() {
@@ -22,7 +25,7 @@ read_install_options() {
semantic_retrieval=false
local saved key value
if [ -f "$home_path/.my-ai-configuration/selection.json" ]; then
if saved=$(python3 "$root/scripts/lib/selection-state.py" read --home "$home_path" --manifest "$root/adapters/plugins.tsv" --format tsv --allow-legacy); then
if saved=$(run_python "$root/scripts/lib/selection-state.py" read --home "$home_path" --manifest "$root/adapters/plugins.tsv" --format tsv --allow-legacy); then
while IFS=$'\t' read -r key value; do
value=${value%$'\r'}
case "$key" in flashbang) flashbang=$value ;; statusline) statusline=$value ;; semantic_retrieval) semantic_retrieval=$value ;; esac
+7 -3
View File
@@ -333,7 +333,8 @@ class Manager:
if client == 'claude' and item.get('enabled') is False:
self.command([client, 'plugin', 'enable', selector])
if record is not None and item.get('version') is not None:
record['version'] = item['version']; self.save()
record['version'] = item['version']
self.save()
return
if item is not None and client == 'claude':
self.command([client, 'plugin', 'marketplace', 'update', selector.rsplit('@', 1)[1]])
@@ -343,7 +344,9 @@ class Manager:
if record is not None:
self.cache.pop(client, None)
version = self.installed(client).get(selector, {}).get('version')
if version is not None: record['version'] = version; self.save()
if version is not None:
record['version'] = version
self.save()
return
marketplace = entry[client + '_marketplace']
if marketplace not in ('', '-', 'openai-curated-remote'):
@@ -363,7 +366,8 @@ class Manager:
resolved_version = self.installed(client).get(selector, {}).get('version')
if record is None:
record = dict(client=client, name=entry['name'], kind='plugin', selector=selector, source=entry.get(client + '_marketplace', '-'))
if resolved_version is not None: record['version'] = resolved_version
if resolved_version is not None:
record['version'] = resolved_version
self.state['resources'].append(record)
self.save()
self.cache[client][selector] = {'scope': 'user'}
+2 -1
View File
@@ -1,3 +1,4 @@
. (Join-Path $PSScriptRoot '../../shared/hooks/scripts/Resolve-Python.ps1')
function Get-ManagedManifestPath {
param([Parameter(Mandatory=$true)][string]$Destination)
return (Join-Path $Destination '.ai-config-manifest.tsv')
@@ -117,7 +118,7 @@ function Invoke-InstallOptions {
[System.IO.File]::WriteAllBytes($managedPath, $Managed)
$Arguments += @('--managed', $managedPath)
}
& python (Join-Path $PSScriptRoot 'install-options.py') @Arguments --output $outputPath
Invoke-Python (Join-Path $PSScriptRoot 'install-options.py') @Arguments --output $outputPath
if ($LASTEXITCODE -ne 0) { throw $ErrorMessage }
return [System.IO.File]::ReadAllText($outputPath, (New-Object System.Text.UTF8Encoding($false)))
} finally {
+8 -5
View File
@@ -1,4 +1,7 @@
#!/usr/bin/env bash
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
. "$(dirname -- "${BASH_SOURCE[0]}")/../../shared/hooks/scripts/resolve-python.sh"
resolve_python || true
# Managed-file manifest: tracks every file this setup previously installed into a
# destination so a later run can detect stale files (removed from the source) or
# locally modified files (changed on disk since the last install) without ever
@@ -146,7 +149,7 @@ run_managed_sync() {
local entries entry entry_action entry_path entry_backup entry_hash entry_target
local -a journal_lines
# One stamp line, then one unit-separated line per file (an empty field must survive read).
entries=$(python3 -c '
entries=$(run_python -c '
import json, sys
journal = json.load(open(sys.argv[1], encoding="utf-8-sig"))
lines = [str(journal["stamp"])]
@@ -211,12 +214,12 @@ sys.stdout.buffer.write(("\n".join(lines) + "\n").encode("utf-8"))
content=${content%$'\034'}
needs_sub=false
if { [ "$flashbang_enabled" = false ] || [ "$statusline_enabled" = false ] || [ "$semantic_retrieval_enabled" = false ]; } && [[ "$relative" = settings.json || "$relative" = config.toml ]]; then
content=$(python3 "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" filter --path "$source_file" --flashbang "$flashbang_enabled" --statusline "$statusline_enabled" --semantic-retrieval "$semantic_retrieval_enabled" && printf '\034') || return
content=$(run_python "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" filter --path "$source_file" --flashbang "$flashbang_enabled" --statusline "$statusline_enabled" --semantic-retrieval "$semantic_retrieval_enabled" && printf '\034') || return
content=${content%$'\034'}
needs_sub=true
fi
if [[ "$relative" = CLAUDE.md || "$relative" = AGENTS.md ]] || { [ "$semantic_retrieval_enabled" = false ] && [ "$relative" = rules/general.md ]; }; then
content=$(python3 "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" filter-instructions --path "$source_file" --destination "$destination" --semantic-retrieval "$semantic_retrieval_enabled" && printf '\034') || return
content=$(run_python "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" filter-instructions --path "$source_file" --destination "$destination" --semantic-retrieval "$semantic_retrieval_enabled" && printf '\034') || return
content=${content%$'\034'}
needs_sub=true
fi
@@ -234,12 +237,12 @@ sys.stdout.buffer.write(("\n".join(lines) + "\n").encode("utf-8"))
new_hash=$(sha256_of_file "$source_file")
fi
if [ "$relative" = config.toml ] && [ -f "$target" ]; then
content=$(printf '%s' "$content" | python3 "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" merge-toml --current "$target" --statusline "$statusline_enabled") || return
content=$(printf '%s' "$content" | run_python "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" merge-toml --current "$target" --statusline "$statusline_enabled") || return
needs_sub=true
new_hash=$(sha256_of_string "$content")
fi
if [ "$relative" = settings.json ] && [ -f "$target" ]; then
content=$(printf '%s' "$content" | python3 "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" merge-json --current "$target") || return
content=$(printf '%s' "$content" | run_python "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" merge-json --current "$target") || return
needs_sub=true
new_hash=$(sha256_of_string "$content")
fi
+2 -1
View File
@@ -1,3 +1,4 @@
. (Join-Path $PSScriptRoot '../../shared/hooks/scripts/Resolve-Python.ps1')
function Invoke-PluginCommand {
param(
[Parameter(Mandatory=$true)][string]$Command,
@@ -161,7 +162,7 @@ function Invoke-ManagedExtensions {
if ($Update) { $arguments += '--update' }
if ($Summary) { $arguments += '--summary' }
if ($PSBoundParameters.ContainsKey('Entries')) { $arguments += '--selected'; $arguments += @($Entries | ForEach-Object { $_.name }) }
& python @arguments
Invoke-Python @arguments
if ($LASTEXITCODE -ne 0) { throw 'Managed extension reconciliation failed.' }
}
+6 -3
View File
@@ -1,4 +1,7 @@
#!/usr/bin/env bash
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
. "$(dirname -- "${BASH_SOURCE[0]}")/../../shared/hooks/scripts/resolve-python.sh"
resolve_python || true
set -euo pipefail
plugin_installed() {
@@ -6,7 +9,7 @@ plugin_installed() {
local inventory
command -v "$client" >/dev/null 2>&1 || return 1
inventory=$("$client" plugin list --json) || return 2
printf '%s' "$inventory" | python3 -c '
printf '%s' "$inventory" | run_python -c '
import json, sys
try:
client, plugin = sys.argv[1:]
@@ -70,7 +73,7 @@ mcporter_server_installed() {
local path="$1/.mcporter/mcporter.json" server=$2 url=$3
if [ -L "$1/.mcporter" ] || [ -L "$path" ]; then printf 'MCPorter configuration path contains a link.\n' >&2; return 2; fi
[ -f "$path" ] || return 1
python3 -c '
run_python -c '
import json, sys
try:
with open(sys.argv[1], encoding="utf-8-sig") as stream:
@@ -193,7 +196,7 @@ managed_extensions() {
local -n extension_names_ref=$selected_name
arguments+=(--selected "${extension_names_ref[@]}")
fi
python3 "${arguments[@]}"
run_python "${arguments[@]}"
}
sync_configured_plugins() {
+3 -2
View File
@@ -1,9 +1,10 @@
. (Join-Path $PSScriptRoot '../../shared/hooks/scripts/Resolve-Python.ps1')
function Sync-Qmd {
param([Parameter(Mandatory=$true)][string]$RepositoryRoot,[Parameter(Mandatory=$true)][string]$HomePath,[ValidateSet('Codex','Claude','Both')][Parameter(Mandatory=$true)][string]$Client,[Parameter(Mandatory=$true)][bool]$Enabled,[switch]$DryRun,[switch]$Update,[switch]$Summary)
$arguments = @((Join-Path $PSScriptRoot 'qmd.py'), 'sync', '--root', $RepositoryRoot, '--home', $HomePath, '--client', $Client.ToLowerInvariant(), '--enabled', $Enabled.ToString().ToLowerInvariant())
if ($DryRun) { $arguments += '--dry-run' }; if ($Update) { $arguments += '--update' }
if ($Summary) { $arguments += '--summary' }
& python @arguments
Invoke-Python @arguments
if ($LASTEXITCODE -ne 0) { throw 'QMD local search reconciliation failed.' }
}
@@ -11,7 +12,7 @@ function Test-QmdDevice {
param([Parameter(Mandatory=$true)][string]$RepositoryRoot,[Parameter(Mandatory=$true)][string]$HomePath,[switch]$Summary)
$arguments = @((Join-Path $PSScriptRoot 'qmd.py'), 'benchmark', '--root', $RepositoryRoot, '--home', $HomePath)
if ($Summary) { $arguments += '--summary' }
& python @arguments | Write-Host
Invoke-Python @arguments | Write-Host
if ($LASTEXITCODE -eq 0) { return $true }
if ($LASTEXITCODE -eq 2) { return $false }
throw 'QMD benchmark failed.'
+5 -2
View File
@@ -1,4 +1,7 @@
#!/usr/bin/env bash
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
. "$(dirname -- "${BASH_SOURCE[0]}")/../../shared/hooks/scripts/resolve-python.sh"
resolve_python || true
sync_qmd() {
local root=$1 client=$2 home_path=$3 enabled=$4 dry_run=$5 update=$6 summary=${7:-false}
@@ -6,7 +9,7 @@ sync_qmd() {
[ "$dry_run" != true ] || arguments+=(--dry-run)
[ "$update" != true ] || arguments+=(--update)
[ "$summary" != true ] || arguments+=(--summary)
python3 "${arguments[@]}"
run_python "${arguments[@]}"
}
test_qmd_device() {
@@ -14,7 +17,7 @@ test_qmd_device() {
local arguments=("$root/scripts/lib/qmd.py" benchmark --root "$root" --home "$home_path")
[ "$summary" != true ] || arguments+=(--summary)
local status
if python3 "${arguments[@]}" >&2; then return 0; else status=$?; fi
if run_python "${arguments[@]}" >&2; then return 0; else status=$?; fi
[ "$status" -eq 2 ] && return 1
return 2
}
+3 -2
View File
@@ -1,8 +1,9 @@
. (Join-Path $PSScriptRoot '../../shared/hooks/scripts/Resolve-Python.ps1')
function Read-UpdateSelection {
param([string]$HomePath, [string]$RepositoryRoot, [switch]$AllowLegacy)
$arguments = @((Join-Path $PSScriptRoot 'selection-state.py'), 'read', '--home', $HomePath, '--manifest', (Join-Path $RepositoryRoot 'adapters/plugins.tsv'))
if ($AllowLegacy) { $arguments += '--allow-legacy' }
$output = & python @arguments
$output = Invoke-Python @arguments
if ($LASTEXITCODE -ne 0) { throw 'Could not load the saved selection.' }
return ($output | Out-String | ConvertFrom-Json)
}
@@ -14,6 +15,6 @@ function Save-UpdateSelection {
$arguments += @($Plugins.Selected | ForEach-Object { $_.name })
$arguments += '--deselected'
$arguments += @($Plugins.Deselected | ForEach-Object { $_.name })
& python @arguments
Invoke-Python @arguments
if ($LASTEXITCODE -ne 0) { throw 'Could not save the selection.' }
}
+5 -2
View File
@@ -1,9 +1,12 @@
#!/usr/bin/env bash
# shellcheck source=../../shared/hooks/scripts/resolve-python.sh
. "$(dirname -- "${BASH_SOURCE[0]}")/../../shared/hooks/scripts/resolve-python.sh"
resolve_python || true
# shellcheck disable=SC2154
read_update_selection() {
local saved key value
saved=$(python3 "$root/scripts/lib/selection-state.py" read --home "$home_path" --manifest "$root/adapters/plugins.tsv" --format tsv) || return
saved=$(run_python "$root/scripts/lib/selection-state.py" read --home "$home_path" --manifest "$root/adapters/plugins.tsv" --format tsv) || return
selected_plugins=()
deselected_plugins=()
while IFS=$'\t' read -r key value; do
@@ -21,7 +24,7 @@ read_update_selection() {
}
save_update_selection() {
python3 "$root/scripts/lib/selection-state.py" write --home "$home_path" --manifest "$root/adapters/plugins.tsv" \
run_python "$root/scripts/lib/selection-state.py" write --home "$home_path" --manifest "$root/adapters/plugins.tsv" \
--shell "$shell" --client "$client" --flashbang "$flashbang" --statusline "${statusline:-true}" --semantic-retrieval "${semantic_retrieval:-false}" \
--selected "${selected_plugins[@]}" --deselected "${deselected_plugins[@]}"
}
File renamed without changes.
+1 -1
View File
@@ -7,7 +7,7 @@ shift 2
[ $# -gt 0 ] || { printf 'Child command is required.\n' >&2; exit 1; }
case "$client" in codex|Codex) client=Codex ;; claude|Claude) client=Claude ;; *) printf 'Unknown client: %s\n' "$client" >&2; exit 1 ;; esac
case "$key" in [A-Za-z_][A-Za-z0-9_]* ) ;; *) printf 'Credential key must be an environment-variable-compatible name.\n' >&2; exit 1 ;; esac
[[ "$key" =~ ^[A-Za-z_][A-Za-z0-9_]{0,127}$ ]] || { printf 'Credential key must be an environment-variable-compatible name.\n' >&2; exit 1; }
powershell_command=$(command -v powershell.exe || command -v powershell || command -v pwsh || true)
[ -n "$powershell_command" ] || { printf 'PowerShell is required to read the Windows credential store.\n' >&2; exit 1; }
+27 -4
View File
@@ -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' }
+23
View File
@@ -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
+129
View File
@@ -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()
-1
View File
@@ -12,7 +12,6 @@ from pathlib import Path
import queue
import shutil
import subprocess
import sys
import tempfile
import threading
import time
+3
View File
@@ -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()
+1 -1
View File
@@ -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):
+1 -1
View File
@@ -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.' }
}
+2 -2
View File
@@ -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"
+1 -1
View File
@@ -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"
+2
View 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)
+1 -1
View File
@@ -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)