feat(extensions): add Roast Room, bring Codex to parity, fix audit findings
Roast Room is installed as a managed Git clone under ~/.my-ai-configuration/roast-room, shared by Claude and Codex. A personal launcher skill runs it from any folder, starts its live room when needed, and only runs when invoked by name (/roast-room, $roast-room). Codex now gets what was Claude-only before: the Caveman skill with a SessionStart hook that keeps it on, PreCompact and session-pointer hooks, execpolicy deny rules mirroring Claude's permissions.deny, and Impeccable's custom agents registered in ~/.codex/agents. The command-safety hook checks both shell dialects for Codex on Windows, where PowerShell text arrives as Bash, in both the PowerShell and Bash packages. Audit fixes: - command-safety blocks git checkout -- / restore / push --force / stash clear and find -delete, and treats heredoc bodies as text - removing a clone clears read-only Git files, git errors no longer abort the extension sync, and a lock left by a dead process is replaced - with-credential passes child flags such as -k or -d through unchanged and resolves commands from PATH - uninstall strips only owned hooks from settings.json and config.toml and keeps the selection while another client is installed; update keeps CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY; Bash merges write the same bytes as PowerShell - qmd no longer trusts a stale daemon.json after a lost start race and prunes collections of deleted repositories - Bash scripts avoid GNU-only find -printf Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
63a36d90e0
commit
b35e2254b3
48 files changed
+1059
-98
No files matched your search
@@ -186,6 +186,8 @@ foreach ($shell in @('powershell','bash')) {
|
||||
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
|
||||
# Codex loads every *.rules file under ~/.codex/rules as execpolicy rules; the Markdown rules there are ignored.
|
||||
Copy-Item (Join-Path $root 'adapters/codex/rules/my-ai-configuration.rules') (Join-Path $output "codex-$shell/rules/my-ai-configuration.rules") -Force
|
||||
Copy-Item (Join-Path $root 'adapters/claude/config/settings.json') (Join-Path $output "claude-$shell/settings.json") -Force
|
||||
|
||||
foreach ($client in @('codex','claude')) {
|
||||
|
||||
@@ -183,7 +183,7 @@ while IFS= read -r rule_path; do
|
||||
if [ -n "$references_dir" ] && [ -d "$references_dir" ]; then
|
||||
copy_directory "$references_dir" "$skill_dir/references"
|
||||
fi
|
||||
done < <(find "$shared/rules" -mindepth 1 -type f -name '*.md' -printf '%P\n' | sort)
|
||||
done < <(cd "$shared/rules" && find . -mindepth 1 -type f -name '*.md' | sed 's|^\./||' | sort)
|
||||
|
||||
instructions_content=$(expand_shell_placeholders "$(<"$shared/global-instructions.md")" "$shell")
|
||||
general_content=$(<"$shared/rules/general.md")
|
||||
@@ -191,6 +191,8 @@ printf '%s\n\n---\n\n%s\n' "${instructions_content%$'\n'}" "$general_content" >
|
||||
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"
|
||||
# Codex loads every *.rules file under ~/.codex/rules as execpolicy rules; the Markdown rules there are ignored.
|
||||
cp "$root/adapters/codex/rules/my-ai-configuration.rules" "$output/codex-$shell/rules/my-ai-configuration.rules"
|
||||
cp "$root/adapters/claude/config/settings.json" "$output/claude-$shell/settings.json"
|
||||
|
||||
for client in codex claude; do
|
||||
|
||||
@@ -8,6 +8,6 @@ while IFS= read -r file; do key_input+="\n$file:$(sha256sum "$file" | awk '{prin
|
||||
key=$(printf '%s' "$key_input" | sha256sum | awk '{print $1}')
|
||||
if [ "$force" = false ] && [ -f "$cache_path" ] && grep -Fq "\"invalidationKey\": \"$key\"" "$cache_path"; then [ "$summary" = true ] && printf 'Repository context: unchanged\n'; exit 0; fi
|
||||
mapfile -t languages < <(find "$root" -type f ! -path '*/generated/*' ! -path '*/.git/*' ! -path '*/node_modules/*' ! -path '*/.ai-session/*' | awk -F. 'NF>1 {print $NF}' | sort -u | awk 'BEGIN{a["cs"]="csharp";a["ts"]="typescript";a["tsx"]="typescript";a["py"]="python";a["ps1"]="powershell";a["sh"]="bash"} a[$1]!=""{print a[$1]}' | sort -u)
|
||||
solutions=$(find "$root" -type f -name '*.sln' ! -path '*/generated/*' -printf '"%f",' | sed 's/,$//'); tests=$(find "$root" -type f ! -path '*/generated/*' ! -path '*/.git/*' -iname '*test*' -printf '"%f",' | sed 's/,$//'); manager=null; [ -f "$root/pnpm-lock.yaml" ] && manager='"pnpm"'; [ -f "$root/package-lock.json" ] && manager='"npm"'; [ -f "$root/yarn.lock" ] && manager='"yarn"'
|
||||
solutions=$(find "$root" -type f -name '*.sln' ! -path '*/generated/*' | sed 's|.*/||; s/.*/"&",/' | tr -d '\n' | sed 's/,$//'); tests=$(find "$root" -type f ! -path '*/generated/*' ! -path '*/.git/*' -iname '*test*' | sed 's|.*/||; s/.*/"&",/' | tr -d '\n' | sed 's/,$//'); manager=null; [ -f "$root/pnpm-lock.yaml" ] && manager='"pnpm"'; [ -f "$root/package-lock.json" ] && manager='"npm"'; [ -f "$root/yarn.lock" ] && manager='"yarn"'
|
||||
mkdir -p "$cache_dir"; printf '{\n "invalidationKey": "%s",\n "head": "%s",\n "languages": [%s],\n "frameworks": [],\n "solutions": [%s],\n "testProjects": [%s],\n "packageManager": %s,\n "buildCommands": {}\n}\n' "$key" "$head" "$(printf '"%s",' "${languages[@]}" | sed 's/,$//')" "$solutions" "$tests" "$manager" > "$cache_path"
|
||||
if [ "$summary" = true ]; then printf 'Repository context: refreshed | %s languages | %s solutions\n' "${#languages[@]}" "$(find "$root" -type f -name '*.sln' ! -path '*/generated/*' | wc -l)"; else printf '%s\n' "$cache_path"; fi
|
||||
@@ -60,7 +60,8 @@ Sync-ConfiguredPlugins -RepositoryRoot $root -HomePath $homePath -Client $Client
|
||||
Sync-Qmd -RepositoryRoot $root -HomePath $homePath -Client $Client -Enabled $false -DryRun:$DryRun -Summary:$Summary
|
||||
|
||||
if (-not $DryRun) {
|
||||
$remaining = @($targets | Where-Object { Test-Path -LiteralPath (Get-ManagedManifestPath $_.Destination) })
|
||||
# Keep the shared selection while the other client is still installed.
|
||||
$remaining = @(Get-InstallTargets -Generated $generated -HomePath $homePath -Shell 'bash' -Client 'Both' | Where-Object { Test-Path -LiteralPath (Get-ManagedManifestPath $_.Destination) })
|
||||
if ($remaining.Count -eq 0) {
|
||||
$configRoot = Join-Path $homePath '.my-ai-configuration'
|
||||
$selectionPath = Join-Path $configRoot 'selection.json'
|
||||
|
||||
@@ -79,9 +79,10 @@ sync_qmd "$root" "$client" "$home_path" false "$dry_run" false "$summary"
|
||||
|
||||
if [ "$dry_run" = false ]; then
|
||||
remaining=0
|
||||
for target_pair in "${targets[@]}"; do
|
||||
# Keep the shared selection while the other client is still installed.
|
||||
while IFS= read -r target_pair; do
|
||||
[ -f "$(manifest_path "${target_pair#*|}")" ] && remaining=$((remaining + 1))
|
||||
done
|
||||
done < <(get_install_targets "$generated" "$home_path" bash both)
|
||||
if [ "$remaining" -eq 0 ]; then
|
||||
config_root="$home_path/.my-ai-configuration"
|
||||
rm -f -- "$config_root/selection.json"
|
||||
|
||||
@@ -15,6 +15,9 @@ $root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
|
||||
. (Join-Path $root 'scripts/lib/install-options.ps1')
|
||||
. (Join-Path $root 'scripts/lib/qmd.ps1')
|
||||
|
||||
$claudeConcurrency = if ($env:CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY) { $env:CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY } else { '5' }
|
||||
if ($claudeConcurrency -notmatch '^[1-9][0-9]?$' -or [int]$claudeConcurrency -gt 10) { throw 'CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY must be an integer from 1 to 10.' }
|
||||
|
||||
$homePath = [Environment]::GetFolderPath('UserProfile')
|
||||
if ($Quick) {
|
||||
$saved = Read-UpdateSelection -HomePath $homePath -RepositoryRoot $root
|
||||
@@ -51,7 +54,7 @@ $plugins = if ($Quick) {
|
||||
|
||||
foreach ($item in (Get-InstallTargets -Generated $generated -HomePath $homePath -Shell $shell -Client $Client)) {
|
||||
Sync-ManagedDestination -Source $item.Source -Destination $item.Destination -Stamp $stamp `
|
||||
-AiConfigRoot $item.Destination.Replace('\','/') -ShellCommand $shellCommand -PowerShellCommand $powerShellCommand -FlashbangEnabled $options.flashbang -StatusLineEnabled $options.statusline -SemanticRetrievalEnabled $options.semantic_retrieval -DryRun:$DryRun -Summary:$Summary
|
||||
-AiConfigRoot $item.Destination.Replace('\','/') -ShellCommand $shellCommand -PowerShellCommand $powerShellCommand -ClaudeConcurrency $claudeConcurrency -FlashbangEnabled $options.flashbang -StatusLineEnabled $options.statusline -SemanticRetrievalEnabled $options.semantic_retrieval -DryRun:$DryRun -Summary:$Summary
|
||||
}
|
||||
|
||||
Sync-Qmd -RepositoryRoot $root -HomePath $homePath -Client $Client -Enabled $options.semantic_retrieval -DryRun:$DryRun -Update -Summary:$Summary
|
||||
|
||||
@@ -25,6 +25,9 @@ root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
. "$root/scripts/lib/install-options.sh"
|
||||
. "$root/scripts/lib/qmd.sh"
|
||||
|
||||
claude_concurrency=${CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY:-5}
|
||||
[[ "$claude_concurrency" =~ ^[1-9][0-9]?$ ]] && [ "$claude_concurrency" -le 10 ] || { printf 'CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY must be an integer from 1 to 10.\n' >&2; exit 1; }
|
||||
|
||||
home_path=${HOME:?HOME is required}
|
||||
selected_plugins=()
|
||||
deselected_plugins=()
|
||||
@@ -64,7 +67,7 @@ fi
|
||||
while IFS='|' read -r source destination; do
|
||||
ai_config_root=$destination
|
||||
command -v cygpath >/dev/null && ai_config_root=$(cygpath -m "$destination")
|
||||
sync_managed_destination "$source" "$destination" "$stamp" "$ai_config_root" "$shell_command" "$powershell_command" "$dry_run" "$summary" "$flashbang" 5 "$statusline" "$semantic_retrieval"
|
||||
sync_managed_destination "$source" "$destination" "$stamp" "$ai_config_root" "$shell_command" "$powershell_command" "$dry_run" "$summary" "$flashbang" "$claude_concurrency" "$statusline" "$semantic_retrieval"
|
||||
done < <(get_install_targets "$generated" "$home_path" "$shell" "$client")
|
||||
|
||||
sync_qmd "$root" "$client" "$home_path" "$semantic_retrieval" "$dry_run" true "$summary"
|
||||
|
||||
@@ -9,7 +9,7 @@ from personal_instructions import CLIENT_FILES, render
|
||||
|
||||
|
||||
# Hook scripts this configuration installs; merges replace these and keep any foreign hooks.
|
||||
OWNED_HOOK_PATTERN = r'(?:flashbang|statusline|record-compact|session-state-pointer|qmd-warm|Start-QmdWarm|completion-?evidence|correction-?prompt|command-?safety|impeccable-?hook|search-?reminder)\.(?:ps1|sh)'
|
||||
OWNED_HOOK_PATTERN = r'(?:flashbang|statusline|record-compact|session-?state-?pointer|caveman-?mode|qmd-warm|Start-QmdWarm|completion-?evidence|correction-?prompt|command-?safety|impeccable-?hook|search-?reminder)\.(?:ps1|sh)'
|
||||
|
||||
|
||||
def is_flashbang(hook):
|
||||
@@ -109,17 +109,35 @@ def filter_flashbang(path):
|
||||
return filter_options(path, flashbang_enabled=False)
|
||||
|
||||
|
||||
def without_owned_hooks(groups):
|
||||
retained = []
|
||||
for group in groups:
|
||||
if not isinstance(group, dict) or not isinstance(group.get('hooks'), list):
|
||||
retained.append(group)
|
||||
continue
|
||||
foreign = [hook for hook in group['hooks'] if not (isinstance(hook, dict) and re.search(
|
||||
OWNED_HOOK_PATTERN,
|
||||
str(hook.get('command', '')) + str(hook.get('command_windows', '')), re.I))]
|
||||
if foreign:
|
||||
retained.append(dict(group, hooks=foreign))
|
||||
return retained
|
||||
|
||||
|
||||
def without_qmd_exclusion(settings):
|
||||
sandbox = settings.get('sandbox')
|
||||
if isinstance(sandbox, dict) and isinstance(sandbox.get('excludedCommands'), list):
|
||||
# The QMD exclusion is owned; managed settings re-add it only while semantic retrieval is enabled.
|
||||
excluded = [command for command in sandbox['excludedCommands'] if 'qmd-search.mjs' not in str(command)]
|
||||
settings['sandbox'] = dict(sandbox, excludedCommands=excluded) if excluded else {k: v for k, v in sandbox.items() if k != 'excludedCommands'}
|
||||
|
||||
|
||||
def merge_json(current, managed):
|
||||
if not isinstance(current, dict) or not isinstance(managed, dict):
|
||||
return managed
|
||||
result = dict(current)
|
||||
if 'statusLine' not in managed:
|
||||
result.pop('statusLine', None)
|
||||
sandbox = result.get('sandbox')
|
||||
if isinstance(sandbox, dict) and isinstance(sandbox.get('excludedCommands'), list):
|
||||
# The QMD exclusion is owned; managed settings re-add it only while semantic retrieval is enabled.
|
||||
excluded = [command for command in sandbox['excludedCommands'] if 'qmd-search.mjs' not in str(command)]
|
||||
result['sandbox'] = dict(sandbox, excludedCommands=excluded) if excluded else {k: v for k, v in sandbox.items() if k != 'excludedCommands'}
|
||||
without_qmd_exclusion(result)
|
||||
for key, value in managed.items():
|
||||
if key == 'hooks' and isinstance(value, dict) and isinstance(result.get(key), dict):
|
||||
hooks = dict(result[key])
|
||||
@@ -127,16 +145,7 @@ def merge_json(current, managed):
|
||||
groups = value.get(event, [])
|
||||
old_groups = hooks.get(event, [])
|
||||
if isinstance(groups, list) and isinstance(old_groups, list):
|
||||
retained = []
|
||||
for group in old_groups:
|
||||
if not isinstance(group, dict) or not isinstance(group.get('hooks'), list):
|
||||
retained.append(group)
|
||||
continue
|
||||
foreign = [hook for hook in group['hooks'] if not (isinstance(hook, dict) and re.search(
|
||||
OWNED_HOOK_PATTERN,
|
||||
str(hook.get('command', '')) + str(hook.get('command_windows', '')), re.I))]
|
||||
if foreign:
|
||||
retained.append(dict(group, hooks=foreign))
|
||||
retained = without_owned_hooks(old_groups)
|
||||
merged = groups + [group for group in retained if group not in groups]
|
||||
if merged:
|
||||
hooks[event] = merged
|
||||
@@ -236,9 +245,46 @@ def merge_toml(current_text, managed_text, statusline_enabled=True):
|
||||
return result
|
||||
|
||||
|
||||
def strip_json(current):
|
||||
"""Remove only what this setup owns (hooks, status line, QMD exclusion); keep everything else."""
|
||||
if not isinstance(current, dict):
|
||||
return current
|
||||
result = dict(current)
|
||||
status = result.get('statusLine')
|
||||
if isinstance(status, dict) and re.search(OWNED_HOOK_PATTERN, str(status.get('command', '')), re.I):
|
||||
del result['statusLine']
|
||||
without_qmd_exclusion(result)
|
||||
if isinstance(result.get('hooks'), dict):
|
||||
hooks = {}
|
||||
for event, groups in result['hooks'].items():
|
||||
remaining = without_owned_hooks(groups) if isinstance(groups, list) else groups
|
||||
if remaining:
|
||||
hooks[event] = remaining
|
||||
if hooks:
|
||||
result['hooks'] = hooks
|
||||
else:
|
||||
del result['hooks']
|
||||
return result
|
||||
|
||||
|
||||
def strip_toml(current_text):
|
||||
# Merging with an empty managed file drops owned hook tables and keeps every other line.
|
||||
result = merge_toml(current_text, '').lstrip('\r\n')
|
||||
return result if result.strip() else ''
|
||||
|
||||
|
||||
def strip_file(path):
|
||||
"""Return path's content without owned entries, or '' when nothing else remains."""
|
||||
content = path.read_text(encoding='utf-8-sig')
|
||||
if path.name == 'config.toml':
|
||||
return strip_toml(content)
|
||||
result = strip_json(json.loads(content))
|
||||
return json.dumps(result, indent=2, ensure_ascii=False) + '\n' if result else ''
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('action', choices=('filter', 'filter-instructions', 'merge-json', 'merge-toml'))
|
||||
parser.add_argument('action', choices=('filter', 'filter-instructions', 'merge-json', 'merge-toml', 'strip'))
|
||||
parser.add_argument('--path', type=Path)
|
||||
parser.add_argument('--current', type=Path)
|
||||
parser.add_argument('--flashbang', choices=('true', 'false'))
|
||||
@@ -256,6 +302,8 @@ if __name__ == '__main__':
|
||||
if args.destination and args.path.name in CLIENT_FILES.values():
|
||||
client = next(client for client, name in CLIENT_FILES.items() if name == args.path.name)
|
||||
result = render(result, args.destination.parent, client)
|
||||
elif args.action == 'strip':
|
||||
result = strip_file(args.current)
|
||||
else:
|
||||
managed = args.managed.read_text(encoding='utf-8-sig') if args.managed else sys.stdin.buffer.read().decode('utf-8-sig')
|
||||
current = args.current.read_text(encoding='utf-8-sig')
|
||||
|
||||
@@ -193,7 +193,7 @@ class Manager:
|
||||
raise ValueError('Invalid extension ownership ledger.')
|
||||
identities = set()
|
||||
for resource in self.state['resources']:
|
||||
if not isinstance(resource, dict) or resource.get('client') not in ('codex', 'claude', 'shared') or resource.get('kind') not in ('plugin', 'skill', 'qmd', 'cli', 'mcp'):
|
||||
if not isinstance(resource, dict) or resource.get('client') not in ('codex', 'claude', 'shared') or resource.get('kind') not in ('plugin', 'skill', 'qmd', 'cli', 'mcp', 'clone'):
|
||||
raise ValueError('Invalid extension ownership record.')
|
||||
if not isinstance(resource.get('name'), str) or not resource['name']:
|
||||
raise ValueError('Invalid extension ownership name.')
|
||||
@@ -220,6 +220,13 @@ class Manager:
|
||||
if not relative.startswith(directory + '/') or not re.fullmatch(r'[a-f0-9]{64}', value):
|
||||
raise ValueError('Invalid owned skill file record.')
|
||||
safe_path(self.home, relative)
|
||||
for relative, value in resource.get('agents', {}).items():
|
||||
if resource['client'] != 'codex' or not re.fullmatch(r'\.codex/agents/[A-Za-z0-9_-]+\.toml', relative) or not re.fullmatch(r'[a-f0-9]{64}', value):
|
||||
raise ValueError('Invalid owned skill agent record.')
|
||||
elif resource['kind'] == 'clone':
|
||||
if resource['client'] != 'shared' or not re.fullmatch(r'\.my-ai-configuration/[A-Za-z0-9_-]+', resource.get('directory', '')):
|
||||
raise ValueError('Invalid owned clone record.')
|
||||
safe_path(self.home, resource['directory'])
|
||||
elif resource['kind'] == 'qmd' and (resource.get('package') != '@tobilu/qmd' or resource['client'] not in ('codex', 'shared')):
|
||||
raise ValueError('Invalid owned QMD record.')
|
||||
elif resource['kind'] == 'cli' and not re.fullmatch(r'[a-z0-9@/_.-]+', resource.get('package', '')):
|
||||
@@ -297,6 +304,14 @@ class Manager:
|
||||
self.command(arguments)
|
||||
self.cache[client].pop(selector, None)
|
||||
elif record['kind'] == 'skill':
|
||||
for relative, expected in list(record.get('agents', {}).items()):
|
||||
path = safe_path(self.home, relative)
|
||||
if path.exists() and (not path.is_file() or digest(path) != expected):
|
||||
print(f'WARN Preserving modified agent file: {relative}')
|
||||
continue
|
||||
path.unlink(missing_ok=True)
|
||||
del record['agents'][relative]
|
||||
self.save()
|
||||
empty_candidates = set()
|
||||
for relative, expected in list(record['files'].items()):
|
||||
path = safe_path(self.home, relative)
|
||||
@@ -326,6 +341,22 @@ class Manager:
|
||||
pass
|
||||
if record['files']:
|
||||
return
|
||||
elif record['kind'] == 'clone':
|
||||
directory = safe_path(self.home, record['directory'])
|
||||
if directory.exists():
|
||||
# Saved sessions, .env files, and local edits live in the clone; never delete them.
|
||||
try:
|
||||
status = run_command(['git', '-C', str(directory), 'status', '--porcelain', '--ignored', '--untracked-files=all'], True, self.home)
|
||||
except ValueError as error:
|
||||
print(f'WARN Preserving {record["directory"]}: cannot read its Git status ({str(error).splitlines()[0]}).')
|
||||
return
|
||||
local = [line for line in status.splitlines() if not line[3:].startswith('node_modules/')]
|
||||
if local:
|
||||
print(f'WARN Preserving {record["directory"]}: it holds local files ({len(local)}); delete it yourself if they are not needed.')
|
||||
return
|
||||
# Git marks pack files read-only, which Windows refuses to delete.
|
||||
retry = lambda _, path, __: (os.chmod(path, stat.S_IWRITE), os.unlink(path))
|
||||
shutil.rmtree(directory, **({'onexc': retry} if sys.version_info >= (3, 12) else {'onerror': retry}))
|
||||
elif record['kind'] == 'mcp':
|
||||
self.command(['mcporter', '--config', str(self.home / '.mcporter/mcporter.json'), 'config', 'remove', record['server']])
|
||||
else:
|
||||
@@ -338,6 +369,9 @@ class Manager:
|
||||
if entry['codex_method'] == 'cli':
|
||||
self.ensure_cli(client, entry)
|
||||
return
|
||||
if entry['codex_method'] == 'clone':
|
||||
self.ensure_clone(client, entry)
|
||||
return
|
||||
# A Claude row without a plugin ('-') reuses the skill payload from codex_source.
|
||||
skill = entry['codex_method'] == 'skill' and (client == 'codex' or entry['claude_plugin'] == '-')
|
||||
kind = 'skill' if skill else 'plugin'
|
||||
@@ -429,6 +463,42 @@ class Manager:
|
||||
self.state['resources'].append(dict(client='shared', name=entry['name'], kind='cli', package=package, clients=[client]))
|
||||
self.save()
|
||||
|
||||
def ensure_clone(self, client, entry):
|
||||
"""Keep a project repository (skills, agents, app) cloned under ~/.my-ai-configuration, shared by both clients."""
|
||||
source, folder = entry['codex_source'], entry['codex_skill']
|
||||
if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', source) or not re.fullmatch(r'[A-Za-z0-9_-]+', folder):
|
||||
raise ValueError('Invalid clone source or folder.')
|
||||
directory = '.my-ai-configuration/' + folder
|
||||
target = safe_path(self.home, directory)
|
||||
record = next((r for r in self.state['resources'] if r['client'] == 'shared' and r['name'] == entry['name']), None)
|
||||
if record is None and target.exists():
|
||||
if not self.summary:
|
||||
print(f'PASS Preserving pre-existing folder: {directory}')
|
||||
return
|
||||
if self.dry_run:
|
||||
if not self.summary:
|
||||
print(f'DRYRUN ensure {client} clone: {entry["name"]}')
|
||||
return
|
||||
if record is not None and client not in record['clients']:
|
||||
record['clients'] = sorted(set(record['clients']) | {client})
|
||||
self.save()
|
||||
if not target.exists():
|
||||
self.command(['git', 'clone', '--depth', '1', f'https://github.com/{source}.git', str(target)])
|
||||
elif self.update and entry['name'] not in self.updated_packages:
|
||||
# Both clients share the folder; check and pull it once per run. A broken clone must not stop the other extensions.
|
||||
self.updated_packages.add(entry['name'])
|
||||
try:
|
||||
changed = run_command(['git', '-C', str(target), 'status', '--porcelain', '--untracked-files=no'], True, self.home)
|
||||
if changed.strip():
|
||||
print(f'WARN Not updating {directory}: tracked files were changed locally.')
|
||||
else:
|
||||
self.command(['git', '-C', str(target), 'pull', '--ff-only', '--quiet'])
|
||||
except ValueError as error:
|
||||
print(f'WARN Not updating {directory}: {str(error).splitlines()[0]}')
|
||||
if record is None:
|
||||
self.state['resources'].append(dict(client='shared', name=entry['name'], kind='clone', directory=directory, source=source, clients=[client]))
|
||||
self.save()
|
||||
|
||||
def ensure_ponytail_mode(self):
|
||||
# Same lookup as Ponytail's hooks/ponytail-config.js; PONYTAIL_DEFAULT_MODE still wins over this file.
|
||||
if os.environ.get('XDG_CONFIG_HOME'):
|
||||
@@ -552,9 +622,33 @@ class Manager:
|
||||
path.unlink(missing_ok=True)
|
||||
del record['files'][relative]
|
||||
self.save()
|
||||
if client == 'codex':
|
||||
self.sync_skill_agents(record, files)
|
||||
record['complete'] = True
|
||||
self.save()
|
||||
|
||||
def sync_skill_agents(self, record, files):
|
||||
"""Codex loads custom agents only from ~/.codex/agents, so register the skill's agents/*.toml there."""
|
||||
agents = {'.codex/agents/' + name.split('/', 1)[1]: content for name, (content, _) in files.items()
|
||||
if re.fullmatch(r'agents/[A-Za-z0-9_-]+\.toml', name)}
|
||||
owned = record.setdefault('agents', {})
|
||||
for relative, content in agents.items():
|
||||
path = safe_path(self.home, relative)
|
||||
if path.exists() and (relative not in owned or not path.is_file() or digest(path) != owned[relative]):
|
||||
print(f'WARN Preserving modified or foreign agent file: {relative}')
|
||||
continue
|
||||
atomic_write(path, content)
|
||||
owned[relative] = hashlib.sha256(content).hexdigest()
|
||||
self.save()
|
||||
for relative in [name for name in owned if name not in agents]:
|
||||
path = safe_path(self.home, relative)
|
||||
if path.exists() and (not path.is_file() or digest(path) != owned[relative]):
|
||||
print(f'WARN Preserving modified stale agent file: {relative}')
|
||||
continue
|
||||
path.unlink(missing_ok=True)
|
||||
del owned[relative]
|
||||
self.save()
|
||||
|
||||
def sync(self, entries, clients, selected, action='sync'):
|
||||
self.normalize_global_records()
|
||||
desired = {entry['name']: entry for entry in entries if entry['name'] in selected}
|
||||
@@ -590,6 +684,47 @@ class Manager:
|
||||
print('EXTENSIONS: reconciliation complete' + (' (dry run)' if self.dry_run else ''))
|
||||
|
||||
|
||||
def process_alive(pid):
|
||||
if os.name == 'nt':
|
||||
import ctypes
|
||||
kernel32 = ctypes.windll.kernel32
|
||||
handle = kernel32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
|
||||
if not handle:
|
||||
return False
|
||||
code = ctypes.c_ulong()
|
||||
try:
|
||||
return bool(kernel32.GetExitCodeProcess(handle, ctypes.byref(code))) and code.value == 259 # STILL_ACTIVE
|
||||
finally:
|
||||
kernel32.CloseHandle(handle)
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
except ProcessLookupError:
|
||||
return False
|
||||
except PermissionError:
|
||||
return True
|
||||
return True
|
||||
|
||||
|
||||
def acquire_lock(lock):
|
||||
"""Create the lock with this PID; replace a lock whose process is gone (closed terminal, kill)."""
|
||||
for _ in range(2):
|
||||
try:
|
||||
descriptor = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
||||
except FileExistsError:
|
||||
try:
|
||||
pid = int(lock.read_text(encoding='utf-8').strip() or 0)
|
||||
except (OSError, ValueError):
|
||||
pid = 0
|
||||
if pid and process_alive(pid):
|
||||
raise ValueError(f'Another install or update is running (PID {pid}). If it is not, delete {lock}.')
|
||||
lock.unlink(missing_ok=True)
|
||||
continue
|
||||
with os.fdopen(descriptor, 'w', encoding='utf-8') as stream:
|
||||
stream.write(str(os.getpid()))
|
||||
return
|
||||
raise ValueError(f'Cannot acquire {lock}.')
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('action', choices=('sync', 'install', 'remove'))
|
||||
@@ -616,9 +751,8 @@ def main():
|
||||
return
|
||||
lock = safe_path(manager.home, '.my-ai-configuration/extensions.lock')
|
||||
lock.parent.mkdir(parents=True, exist_ok=True)
|
||||
descriptor = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
||||
acquire_lock(lock)
|
||||
try:
|
||||
os.close(descriptor)
|
||||
manager = Manager(args.home, args.dry_run, args.update, args.summary)
|
||||
manager.sync(entries, clients, selected, args.action)
|
||||
finally:
|
||||
|
||||
@@ -268,14 +268,23 @@ function Invoke-ManagedSync {
|
||||
if (-not (Test-Path -LiteralPath $target)) { continue }
|
||||
# A stale file changed locally is backed up but kept; only an unmodified one is removed.
|
||||
$action = if ((Get-Sha256Hash $target) -eq $oldManifest[$relative]) { 'REMOVE' } else { 'KEEP' }
|
||||
$null = $plan.Add([pscustomobject]@{ Relative = $relative; Target = $target; Action = $action; Bytes = $null; Hash = $null })
|
||||
$bytes = $null
|
||||
$hash = $null
|
||||
if ($action -eq 'KEEP' -and $relative -in @('settings.json', 'config.toml')) {
|
||||
# Client plugin commands edit these after install; drop only the entries this setup owns.
|
||||
$stripped = Invoke-InstallOptions -Arguments @('strip', '--current', $target) -ErrorMessage "Could not remove managed entries from $relative."
|
||||
$action = if ($stripped) { 'STRIP' } else { 'REMOVE' }
|
||||
$bytes = (New-Object System.Text.UTF8Encoding($false)).GetBytes($stripped)
|
||||
$hash = Get-Sha256HashOfBytes $bytes
|
||||
}
|
||||
$null = $plan.Add([pscustomobject]@{ Relative = $relative; Target = $target; Action = $action; Bytes = $bytes; Hash = $hash })
|
||||
}
|
||||
|
||||
if (-not $DryRun) {
|
||||
$journalEntries = @(foreach ($item in $plan) {
|
||||
switch ($item.Action) {
|
||||
'CREATE' { [ordered]@{ path = $item.Relative; action = 'create'; sha256 = $item.Hash } }
|
||||
'UPDATE' { [ordered]@{ path = $item.Relative; action = 'update'; backup = "$Stamp/$($item.Relative)"; sha256 = $item.Hash } }
|
||||
{ $_ -in @('UPDATE', 'STRIP') } { [ordered]@{ path = $item.Relative; action = 'update'; backup = "$Stamp/$($item.Relative)"; sha256 = $item.Hash } }
|
||||
'REMOVE' { [ordered]@{ path = $item.Relative; action = 'remove'; backup = "$Stamp/$($item.Relative)" } }
|
||||
}
|
||||
})
|
||||
|
||||
+34
-13
@@ -119,6 +119,16 @@ acquire_managed_lock() {
|
||||
return 1
|
||||
}
|
||||
|
||||
# run_install_options <arguments...>: print install-options.py output byte-exact.
|
||||
# Python writes a file, because a captured stdout gets CRLF on Windows and differs from PowerShell's bytes.
|
||||
run_install_options() {
|
||||
local output status=0
|
||||
output=$(mktemp) || return 1
|
||||
{ run_python "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" "$@" --output "$output" && cat -- "$output"; } || status=$?
|
||||
rm -f -- "$output"
|
||||
return "$status"
|
||||
}
|
||||
|
||||
# sync_managed_destination: same arguments as run_managed_sync; holds the destination lock unless dry-running.
|
||||
sync_managed_destination() {
|
||||
[ "$7" != true ] || { run_managed_sync "$@"; return; }
|
||||
@@ -214,12 +224,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=$(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=$(run_install_options 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=$(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=$(run_install_options filter-instructions --path "$source_file" --destination "$destination" --semantic-retrieval "$semantic_retrieval_enabled" && printf '\034') || return
|
||||
content=${content%$'\034'}
|
||||
needs_sub=true
|
||||
fi
|
||||
@@ -236,13 +246,14 @@ sys.stdout.buffer.write(("\n".join(lines) + "\n").encode("utf-8"))
|
||||
else
|
||||
new_hash=$(sha256_of_file "$source_file")
|
||||
fi
|
||||
if [ "$relative" = config.toml ] && [ -f "$target" ]; then
|
||||
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" | run_python "$(dirname -- "${BASH_SOURCE[0]}")/install-options.py" merge-json --current "$target") || return
|
||||
if [[ "$relative" = config.toml || "$relative" = settings.json ]] && [ -f "$target" ]; then
|
||||
local managed_file merge_action=merge-json
|
||||
[ "$relative" = settings.json ] || merge_action=merge-toml
|
||||
managed_file=$(mktemp) || return 1
|
||||
printf '%s' "$content" > "$managed_file" || { rm -f -- "$managed_file"; return 1; }
|
||||
content=$(run_install_options "$merge_action" --current "$target" --managed "$managed_file" --statusline "$statusline_enabled" && printf '\034') || { rm -f -- "$managed_file"; return 1; }
|
||||
rm -f -- "$managed_file"
|
||||
content=${content%$'\034'}
|
||||
needs_sub=true
|
||||
new_hash=$(sha256_of_string "$content")
|
||||
fi
|
||||
@@ -265,10 +276,20 @@ sys.stdout.buffer.write(("\n".join(lines) + "\n").encode("utf-8"))
|
||||
target=$(managed_target "$destination" "$relative") || return 1
|
||||
[ -f "$target" ] || continue
|
||||
# A stale file changed locally is backed up but kept; only an unmodified one is removed.
|
||||
local stripped='' stripped_hash=''
|
||||
action=KEEP
|
||||
[ "$(sha256_of_file "$target")" != "${old_manifest[$relative]}" ] || action=REMOVE
|
||||
plan_relative+=("$relative"); plan_target+=("$target"); plan_action+=("$action"); plan_hash+=('')
|
||||
plan_source+=(''); plan_sub+=(false); plan_content+=('')
|
||||
if [ "$(sha256_of_file "$target")" = "${old_manifest[$relative]}" ]; then
|
||||
action=REMOVE
|
||||
elif [[ "$relative" = settings.json || "$relative" = config.toml ]]; then
|
||||
# Client plugin commands edit these after install; drop only the entries this setup owns.
|
||||
stripped=$(run_install_options strip --current "$target" && printf '\034') || return 1
|
||||
stripped=${stripped%$'\034'}
|
||||
action=STRIP
|
||||
[ -n "$stripped" ] || action=REMOVE
|
||||
stripped_hash=$(sha256_of_string "$stripped")
|
||||
fi
|
||||
plan_relative+=("$relative"); plan_target+=("$target"); plan_action+=("$action"); plan_hash+=("$stripped_hash")
|
||||
plan_source+=(''); plan_sub+=(true); plan_content+=("$stripped")
|
||||
done
|
||||
|
||||
local index entry journal_content first_entry=true
|
||||
@@ -279,7 +300,7 @@ sys.stdout.buffer.write(("\n".join(lines) + "\n").encode("utf-8"))
|
||||
for index in "${!plan_action[@]}"; do
|
||||
case "${plan_action[$index]}" in
|
||||
CREATE) entry=$(printf '{"path": %s, "action": "create", "sha256": "%s"}' "$(json_string "${plan_relative[$index]}")" "${plan_hash[$index]}") ;;
|
||||
UPDATE) entry=$(printf '{"path": %s, "action": "update", "backup": %s, "sha256": "%s"}' "$(json_string "${plan_relative[$index]}")" "$(json_string "$stamp/${plan_relative[$index]}")" "${plan_hash[$index]}") ;;
|
||||
UPDATE|STRIP) entry=$(printf '{"path": %s, "action": "update", "backup": %s, "sha256": "%s"}' "$(json_string "${plan_relative[$index]}")" "$(json_string "$stamp/${plan_relative[$index]}")" "${plan_hash[$index]}") ;;
|
||||
REMOVE) entry=$(printf '{"path": %s, "action": "remove", "backup": %s}' "$(json_string "${plan_relative[$index]}")" "$(json_string "$stamp/${plan_relative[$index]}")") ;;
|
||||
*) continue ;;
|
||||
esac
|
||||
|
||||
@@ -134,6 +134,7 @@ function Select-ConfiguredPlugins {
|
||||
$checked = @($toggleable | ForEach-Object {
|
||||
if ($Mode -eq 'Install') { $true; return }
|
||||
if ($_.codex_method -eq 'cli') { return Test-CliCommand -Name $_.codex_source }
|
||||
if ($_.codex_method -eq 'clone') { return Test-Path -LiteralPath (Join-Path $HomePath ('.my-ai-configuration/' + $_.codex_skill)) }
|
||||
$entry = $_
|
||||
$found = if ($entry.mcporter_name -and $entry.mcporter_url) {
|
||||
Test-InstalledMCPServer -HomePath $HomePath -Name $entry.mcporter_name -Url $entry.mcporter_url
|
||||
|
||||
@@ -171,6 +171,10 @@ select_configured_plugins() {
|
||||
if cli_installed "$(plugin_field "$root" "$name" codex_source)"; then checked+=(true); else checked+=(false); fi
|
||||
continue
|
||||
fi
|
||||
if [ "$(plugin_field "$root" "$name" codex_method)" = clone ]; then
|
||||
if [ -d "${home_path:-$HOME}/.my-ai-configuration/$(plugin_field "$root" "$name" codex_skill)" ]; then checked+=(true); else checked+=(false); fi
|
||||
continue
|
||||
fi
|
||||
found=false
|
||||
local mcporter_name mcporter_url status
|
||||
mcporter_name=$(plugin_field "$root" "$name" mcporter_name)
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[ValidateSet('Codex', 'Claude')][string]$Client,
|
||||
[string]$Key,
|
||||
[Parameter(Position = 2)][string]$FilePath,
|
||||
[Parameter(Position = 3, ValueFromRemainingArguments = $true)][string[]]$ArgumentList
|
||||
)
|
||||
# Usage: with-credential.ps1 -Client <Codex|Claude> -Key <NAME> -FilePath <command> [child arguments...]
|
||||
# No param() block: PowerShell would bind abbreviated child flags such as -k or -d to -Key or -Debug.
|
||||
# Only the exact names below are read; everything after the command goes to the child unchanged.
|
||||
# Own variable names: scripts that dot-source this file keep their own $Client and $Key.
|
||||
$credentialClient = $null
|
||||
$credentialKey = $null
|
||||
$childPath = $null
|
||||
$childArguments = @()
|
||||
for ($index = 0; $index -lt $args.Count; $index++) {
|
||||
$token = [string]$args[$index]
|
||||
if ($null -ne $childPath) { $childArguments = @($args[$index..($args.Count - 1)] | ForEach-Object { [string]$_ }); break }
|
||||
if ($token -eq '-Client' -and $index + 1 -lt $args.Count) { $credentialClient = [string]$args[++$index] }
|
||||
elseif ($token -eq '-Key' -and $index + 1 -lt $args.Count) { $credentialKey = [string]$args[++$index] }
|
||||
elseif ($token -eq '-FilePath' -and $index + 1 -lt $args.Count) { $childPath = [string]$args[++$index] }
|
||||
else { $childPath = $token }
|
||||
}
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
@@ -106,7 +115,10 @@ function Remove-ManagedCredential {
|
||||
function Invoke-WithManagedCredential {
|
||||
param([ValidateSet('Codex', 'Claude')][string]$Client, [string]$Key, [string]$FilePath, [string[]]$ArgumentList)
|
||||
Assert-CredentialKey $Key
|
||||
if (-not (Test-Path -LiteralPath $FilePath -PathType Leaf)) { throw 'Child command was not found.' }
|
||||
# Accept a full path or a command name on PATH (gh, curl.exe).
|
||||
$command = Get-Command -Name $FilePath -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
if (-not $command) { throw 'Child command was not found.' }
|
||||
$FilePath = $command.Source
|
||||
$prior = [Environment]::GetEnvironmentVariable($Key, 'Process')
|
||||
$value = Get-ManagedCredential $Client $Key
|
||||
try {
|
||||
@@ -119,8 +131,8 @@ function Invoke-WithManagedCredential {
|
||||
}
|
||||
}
|
||||
|
||||
if ($FilePath) {
|
||||
if (-not $Client -or -not $Key) { throw 'Client and key are required.' }
|
||||
Invoke-WithManagedCredential $Client $Key $FilePath $ArgumentList
|
||||
if ($childPath) {
|
||||
if (-not $credentialClient -or -not $credentialKey) { throw 'Client and key are required.' }
|
||||
Invoke-WithManagedCredential $credentialClient $credentialKey $childPath $childArguments
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SCRIPTS = ROOT / 'shared/hooks/scripts'
|
||||
SKILL = '---\nname: caveman\ndescription: Terse style.\n---\n\n# caveman\n\nRespond terse like smart caveman.\n'
|
||||
|
||||
|
||||
def wrappers():
|
||||
found = []
|
||||
for name in ('pwsh', 'powershell'):
|
||||
executable = shutil.which(name)
|
||||
if executable:
|
||||
found.append((name, [executable, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(SCRIPTS / 'Show-CavemanMode.ps1')]))
|
||||
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:
|
||||
found.append(('bash', [bash, str(SCRIPTS / 'show-caveman-mode.sh')]))
|
||||
return found
|
||||
|
||||
|
||||
class CavemanHookTests(unittest.TestCase):
|
||||
def run_hook(self, command, home, mode=None):
|
||||
environment = dict(os.environ, HOME=str(home), USERPROFILE=str(home))
|
||||
environment.pop('CAVEMAN_DEFAULT_MODE', None)
|
||||
if mode:
|
||||
environment['CAVEMAN_DEFAULT_MODE'] = mode
|
||||
return subprocess.run(command, capture_output=True, encoding='utf-8', timeout=60, env=environment)
|
||||
|
||||
def test_prints_installed_skill_without_frontmatter_and_respects_off(self):
|
||||
available = wrappers()
|
||||
if not available:
|
||||
self.skipTest('No supported shell is available.')
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
home = Path(directory)
|
||||
for name, command in available:
|
||||
with self.subTest(shell=name, case='missing skill'):
|
||||
result = self.run_hook(command, home)
|
||||
self.assertEqual((0, ''), (result.returncode, result.stdout))
|
||||
skill = home / '.agents/skills/caveman/SKILL.md'
|
||||
skill.parent.mkdir(parents=True)
|
||||
skill.write_text(SKILL, encoding='utf-8')
|
||||
for name, command in available:
|
||||
with self.subTest(shell=name, case='installed'):
|
||||
result = self.run_hook(command, home)
|
||||
self.assertEqual(0, result.returncode, result.stderr)
|
||||
self.assertIn('CAVEMAN MODE ACTIVE (mode: caveman)', result.stdout)
|
||||
self.assertIn('Respond terse like smart caveman.', result.stdout)
|
||||
self.assertNotIn('description: Terse style.', result.stdout)
|
||||
with self.subTest(shell=name, case='off'):
|
||||
result = self.run_hook(command, home, 'off')
|
||||
self.assertEqual((0, ''), (result.returncode, result.stdout))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -12,9 +12,10 @@ SCRIPTS = ROOT / 'shared/hooks/scripts'
|
||||
SAFETY = SCRIPTS / 'command-safety.py'
|
||||
|
||||
|
||||
def hook(command, tool='Bash'):
|
||||
def hook(command, tool='Bash', shell=None):
|
||||
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,
|
||||
extra = ['--shell', shell] if shell else []
|
||||
return subprocess.run([sys.executable, str(SAFETY), '--hook', *extra], input=payload, capture_output=True,
|
||||
encoding='utf-8', timeout=20)
|
||||
|
||||
|
||||
@@ -61,6 +62,26 @@ class HookTests(unittest.TestCase):
|
||||
self.assertBlocked(command)
|
||||
self.assertBlocked('Remove-Item build `\n -Recurse -Force', 'PowerShell')
|
||||
|
||||
def test_blocks_git_and_find_forms_that_discard_work(self):
|
||||
for command in ('git checkout -- .', 'git checkout -- src/app.ts', 'git checkout HEAD -- a.txt', 'git checkout .',
|
||||
'git restore .', 'git restore --worktree src', 'git push --force', 'git push -f origin main',
|
||||
'git push --force-with-lease', 'git push origin +main', 'git stash clear',
|
||||
'find . -name "*.tmp" -delete'):
|
||||
with self.subTest(command=command):
|
||||
self.assertBlocked(command)
|
||||
for command in ('git checkout main', 'git checkout -b feat/x', 'git restore --staged file.txt', 'git push',
|
||||
'git push origin main', 'git stash list', 'find . -name "*.tmp"'):
|
||||
with self.subTest(command=command):
|
||||
self.assertAllowed(command)
|
||||
|
||||
def test_heredoc_bodies_are_text_not_commands(self):
|
||||
for command in ("cat > c.sh <<'EOF'\nrm -rf \"$tmp\"\nEOF", 'git commit -F - <<EOF\nfix: avoid git reset --hard\nEOF',
|
||||
'cat <<-END\n\trm -rf x\n\tEND'):
|
||||
with self.subTest(command=command):
|
||||
self.assertAllowed(command)
|
||||
self.assertBlocked('cat > a.txt <<EOF\nhello\nEOF\nrm -rf build')
|
||||
self.assertBlocked('cat <<EOF; rm -rf build\nbody\nEOF')
|
||||
|
||||
def test_allows_comments_and_hashes_that_are_not_commands(self):
|
||||
for command in ('ls # rm -rf x', 'git commit -m "fix #12; rm -rf is bad"', 'echo a#b', 'echo "\\"rm -rf x\\""'):
|
||||
with self.subTest(command=command):
|
||||
@@ -81,6 +102,13 @@ class HookTests(unittest.TestCase):
|
||||
self.assertAllowed('Remove-Item build/file.txt', 'PowerShell')
|
||||
self.assertAllowed('Remove-Item build -Recurse:$false', 'PowerShell')
|
||||
|
||||
def test_shell_override_checks_codex_windows_powershell_text_reported_as_bash(self):
|
||||
for command in ('rm -r build', 'Remove-Item build -Recurse', 'ri build -recurse', 'rm -rf build'):
|
||||
with self.subTest(command=command):
|
||||
self.assertEqual(2, hook(command, 'Bash', 'unknown').returncode)
|
||||
self.assertEqual(0, hook('rm -r build', 'Bash').returncode, 'Claude Git Bash keeps the POSIX meaning of rm -r')
|
||||
self.assertEqual(0, hook('Get-ChildItem build', 'Bash', 'unknown').returncode)
|
||||
|
||||
def test_unknown_shell_checks_both_dialects(self):
|
||||
self.assertBlocked('rm -r build', 'shell')
|
||||
self.assertBlocked('rm -rf build', 'shell')
|
||||
@@ -148,6 +176,9 @@ class WrapperTests(unittest.TestCase):
|
||||
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)
|
||||
# Codex hook commands pass -Shell; the wrapper must stay in hook mode and read the event.
|
||||
codex = json.dumps({'tool_name': 'Bash', 'tool_input': {'command': 'rm -r build'}})
|
||||
self.assertEqual(2, self.run_wrapper(command + ['-Shell', 'unknown'], codex).returncode, name)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -99,6 +99,16 @@ class InstallOptionsTests(unittest.TestCase):
|
||||
commands = [hook['command'] for group in result['hooks']['SessionStart'] for hook in group['hooks']]
|
||||
self.assertEqual(commands, ['bash "/c/hooks/scripts/show-session-state-pointer.sh"'])
|
||||
|
||||
def test_managed_powershell_session_hooks_are_replaced_not_duplicated(self):
|
||||
pointer = {'hooks': [{'type': 'command', 'command': 'pwsh -File "C:/c/hooks/scripts/Show-SessionStatePointer.ps1"'}]}
|
||||
caveman = {'hooks': [{'type': 'command', 'command': 'pwsh -File "C:/c/hooks/scripts/Show-CavemanMode.ps1"'}]}
|
||||
managed = {'hooks': {'SessionStart': [pointer, caveman]}}
|
||||
merged = OPTIONS.merge_json(OPTIONS.merge_json({}, managed), managed)
|
||||
self.assertEqual([pointer, caveman], merged['hooks']['SessionStart'])
|
||||
toml = ('[[hooks.SessionStart]]\n[[hooks.SessionStart.hooks]]\ntype = "command"\n'
|
||||
"command = 'bash \"/c/hooks/scripts/show-caveman-mode.sh\"'\n")
|
||||
self.assertEqual(1, OPTIONS.merge_toml(toml, toml).count('show-caveman-mode.sh'))
|
||||
|
||||
def test_semantic_retrieval_disabled_removes_qmd_sandbox_exclusion(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
settings = Path(directory) / 'settings.json'
|
||||
|
||||
@@ -6,7 +6,9 @@ import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
@@ -37,7 +39,14 @@ def mcp():
|
||||
mcporter_url='https://mcp.context7.com/mcp')
|
||||
|
||||
|
||||
def clone():
|
||||
return dict(name='Roast Room', codex_method='clone', codex_source='nateherkai/roast-room', codex_skill='roast-room',
|
||||
codex_plugin='-', codex_marketplace='-', claude_plugin='-', claude_marketplace='-')
|
||||
|
||||
|
||||
class ManagedExtensionTests(unittest.TestCase):
|
||||
git_status = ''
|
||||
|
||||
def setUp(self):
|
||||
self.temporary = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
@@ -56,6 +65,8 @@ class ManagedExtensionTests(unittest.TestCase):
|
||||
if args[:2] == ['npm', 'list']:
|
||||
return '{"dependencies":{}}'
|
||||
self.commands.append(args)
|
||||
if args[0] == 'git' and 'status' in args:
|
||||
return self.git_status
|
||||
if len(args) > 3 and args[2] in ('add', 'install') and args[1] == 'plugin':
|
||||
self.installed[args[0]][args[3]] = {'scope': 'user'}
|
||||
if args[2] in ('remove', 'uninstall'):
|
||||
@@ -243,6 +254,117 @@ class ManagedExtensionTests(unittest.TestCase):
|
||||
self.assertEqual([['codex', 'plugin', 'remove', 'caveman@test']], [c for c in self.commands[installed:] if c[0] == 'codex'])
|
||||
self.assertEqual(['claude'], [r['client'] for r in self.manager().state['resources']])
|
||||
|
||||
def test_codex_skill_agents_are_registered_and_removed_with_the_skill(self):
|
||||
payload = {'SKILL.md': (b'skill', False), 'agents/impeccable_finish_reviewer.toml': (b'name = "x"\n', False),
|
||||
'agents/openai.yaml': (b'policy: {}\n', False)}
|
||||
agent = self.home / '.codex/agents/impeccable_finish_reviewer.toml'
|
||||
entry = dict(skill(), name='Impeccable', codex_skill='impeccable', claude_plugin='-', claude_marketplace='-')
|
||||
with patch.object(extensions, 'fetch_skill', return_value=('impeccable', payload)):
|
||||
self.manager().sync([entry], ['claude', 'codex'], {'Impeccable'})
|
||||
self.assertEqual(b'name = "x"\n', agent.read_bytes())
|
||||
self.assertFalse((self.home / '.codex/agents/openai.yaml').exists())
|
||||
self.assertFalse((self.home / '.claude/agents').exists(), 'Claude gets its agents from the plugin')
|
||||
self.manager().sync([], ['codex'], set())
|
||||
self.assertFalse(agent.exists())
|
||||
|
||||
def test_foreign_codex_agent_file_is_preserved(self):
|
||||
payload = {'SKILL.md': (b'skill', False), 'agents/impeccable_finish_reviewer.toml': (b'upstream', False)}
|
||||
agent = self.home / '.codex/agents/impeccable_finish_reviewer.toml'
|
||||
agent.parent.mkdir(parents=True)
|
||||
agent.write_bytes(b'mine')
|
||||
with patch.object(extensions, 'fetch_skill', return_value=('impeccable', payload)):
|
||||
self.manager().sync([dict(skill(), name='Impeccable', codex_skill='impeccable')], ['codex'], {'Impeccable'})
|
||||
self.manager().sync([], ['codex'], set())
|
||||
self.assertEqual(b'mine', agent.read_bytes())
|
||||
|
||||
def test_clone_is_shared_by_both_clients_and_cloned_once(self):
|
||||
target = self.home / '.my-ai-configuration/roast-room'
|
||||
original = self.command
|
||||
|
||||
def clone_creates_folder(args, summary, home=None):
|
||||
if args[:2] == ['git', 'clone']:
|
||||
target.mkdir(parents=True)
|
||||
return original(args, summary, home)
|
||||
with patch.object(extensions, 'run_command', side_effect=clone_creates_folder):
|
||||
self.manager().sync([clone()], ['claude', 'codex'], {'Roast Room'})
|
||||
self.assertEqual([['git', 'clone', '--depth', '1', 'https://github.com/nateherkai/roast-room.git', str(target)]], self.commands)
|
||||
records = self.manager().state['resources']
|
||||
self.assertEqual([('shared', 'clone', ['claude', 'codex'])], [(r['client'], r['kind'], r['clients']) for r in records])
|
||||
self.manager(update=True).sync([clone()], ['claude', 'codex'], {'Roast Room'})
|
||||
self.assertEqual(1, sum(1 for command in self.commands if 'pull' in command))
|
||||
self.manager().sync([], ['claude'], set())
|
||||
self.assertTrue(target.is_dir(), 'the clone stays while Codex still uses it')
|
||||
self.assertEqual(['codex'], self.manager().state['resources'][0]['clients'])
|
||||
|
||||
def test_pre_existing_clone_folder_is_not_claimed(self):
|
||||
(self.home / '.my-ai-configuration/roast-room').mkdir(parents=True)
|
||||
self.manager(update=True).sync([clone()], ['claude'], {'Roast Room'})
|
||||
self.assertEqual([], self.commands)
|
||||
self.assertEqual([], self.manager().state['resources'])
|
||||
|
||||
def test_clone_update_pulls_only_when_tracked_files_are_unchanged(self):
|
||||
self.manager().sync([clone()], ['claude'], {'Roast Room'})
|
||||
(self.home / '.my-ai-configuration/roast-room').mkdir(parents=True)
|
||||
self.git_status = ' M .claude/skills/roast-room/SKILL.md\n'
|
||||
self.manager(update=True).sync([clone()], ['claude'], {'Roast Room'})
|
||||
self.assertNotIn('pull', [part for command in self.commands for part in command])
|
||||
self.git_status = ''
|
||||
self.manager(update=True).sync([clone()], ['claude'], {'Roast Room'})
|
||||
self.assertEqual('pull', self.commands[-1][3])
|
||||
|
||||
def test_clone_removal_keeps_local_sessions_and_removes_clean_clone(self):
|
||||
target = self.home / '.my-ai-configuration/roast-room'
|
||||
self.manager().sync([clone()], ['claude'], {'Roast Room'})
|
||||
target.mkdir(parents=True)
|
||||
self.git_status = '?? sessions/2026-11-19-pricing/brief.md\n!! node_modules/x/index.js\n'
|
||||
self.manager().sync([], ['claude'], set())
|
||||
self.assertTrue(target.is_dir())
|
||||
self.assertEqual(1, len(self.manager().state['resources']))
|
||||
self.git_status = '!! node_modules/x/index.js\n'
|
||||
self.manager().sync([], ['claude'], set())
|
||||
self.assertFalse(target.exists())
|
||||
self.assertEqual([], self.manager().state['resources'])
|
||||
|
||||
def test_clean_clone_with_read_only_git_objects_is_removed(self):
|
||||
target = self.home / '.my-ai-configuration/roast-room'
|
||||
self.manager().sync([clone()], ['claude'], {'Roast Room'})
|
||||
pack = target / '.git/objects/pack/pack-1.idx'
|
||||
pack.parent.mkdir(parents=True)
|
||||
pack.write_text('x')
|
||||
os.chmod(pack, stat.S_IREAD)
|
||||
self.manager().sync([], ['claude'], set())
|
||||
self.assertFalse(target.exists())
|
||||
self.assertEqual([], self.manager().state['resources'])
|
||||
|
||||
def test_clone_git_failure_warns_and_does_not_stop_other_extensions(self):
|
||||
target = self.home / '.my-ai-configuration/roast-room'
|
||||
self.manager().sync([clone()], ['claude'], {'Roast Room'})
|
||||
target.mkdir(parents=True)
|
||||
original = self.command
|
||||
|
||||
def git_fails(args, summary, home=None):
|
||||
if args[0] == 'git':
|
||||
raise ValueError('fatal: not a git repository')
|
||||
return original(args, summary, home)
|
||||
with patch.object(extensions, 'run_command', side_effect=git_fails):
|
||||
self.manager(update=True).sync([clone(), plugin()], ['claude'], {'Roast Room', 'Example'})
|
||||
self.assertIn(['claude', 'plugin', 'install', 'example@test', '--scope', 'user'], self.commands)
|
||||
self.manager().sync([], ['claude'], set())
|
||||
self.assertTrue(target.is_dir(), 'an unreadable clone is never deleted')
|
||||
self.assertEqual(['Roast Room'], [r['name'] for r in self.manager().state['resources']])
|
||||
|
||||
def test_stale_lock_from_a_dead_process_is_replaced(self):
|
||||
lock = self.home / '.my-ai-configuration/extensions.lock'
|
||||
lock.parent.mkdir(parents=True)
|
||||
dead = subprocess.Popen([sys.executable, '-c', 'pass'])
|
||||
dead.wait()
|
||||
lock.write_text(str(dead.pid))
|
||||
extensions.acquire_lock(lock)
|
||||
self.assertEqual(str(os.getpid()), lock.read_text())
|
||||
lock.write_text(str(os.getpid()))
|
||||
with self.assertRaisesRegex(ValueError, 'Another install or update is running'):
|
||||
extensions.acquire_lock(lock)
|
||||
|
||||
def test_selected_adhd_enables_always_on_flag_once(self):
|
||||
config = self.home / '.claude'
|
||||
flag = config / '.i-have-adhd-always'
|
||||
|
||||
@@ -48,7 +48,7 @@ if ([Environment]::GetEnvironmentVariable('CODEX_HOME', 'Process') -ne $previous
|
||||
$script:answers.Enqueue('done')
|
||||
$selection = Select-ConfiguredPlugins -RepositoryRoot (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent) -Client Codex -Mode Update
|
||||
if (@($selection.Selected | Where-Object { $_.codex_method -eq 'plugin' }).Count -ne 4) { throw 'All installed Codex plugins must start checked when updating.' }
|
||||
if (@($selection.Selected + $selection.Deselected | Where-Object { $_.name -eq 'Caveman' }).Count) { throw 'Claude-only extensions must not be offered for Codex.' }
|
||||
if (@($selection.Selected + $selection.Deselected | Where-Object { $_.name -in @('Caveman', 'Roast Room') }).Count -ne 2) { throw 'Caveman and Roast Room must be offered for Codex too.' }
|
||||
$script:answers.Enqueue('4')
|
||||
$script:answers.Enqueue('done')
|
||||
$selection = Select-ConfiguredPlugins -RepositoryRoot (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent) -Client Codex -Mode Update
|
||||
|
||||
@@ -48,7 +48,9 @@ select_configured_plugins "$root" codex Update true selected deselected
|
||||
printf '%s\n' '{"mcpServers":{"context7":{"baseUrl":"https://example.invalid/mcp"}}}' > "$test_home/.mcporter/mcporter.json"
|
||||
select_configured_plugins "$root" codex Update true selected deselected
|
||||
[[ " ${deselected[*]} " == *' Context7 '* ]] || { printf 'A different MCPorter server must not select Context7.\n' >&2; exit 1; }
|
||||
[[ " ${selected[*]} ${deselected[*]} " != *' Caveman '* ]] || { printf 'Claude-only extensions must not be offered for Codex.\n' >&2; exit 1; }
|
||||
for name in Caveman 'Roast Room'; do
|
||||
[[ " ${selected[*]} ${deselected[*]} " == *" $name "* ]] || { printf '%s must be offered for Codex too.\n' "$name" >&2; exit 1; }
|
||||
done
|
||||
npm_prefix=$(mktemp -d "$root/.npm-test.XXXXXX")
|
||||
cli_name="ai-config-test-cli-${npm_prefix##*.}"
|
||||
npm() { printf '%s\n' "$npm_prefix"; }
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { existsSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs';
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { INDEX_EXCLUDES, acquireStartLock, createServer, gitFingerprint, ignoreGlobs, indexIgnores, keepModelsLoaded } from '../../shared/qmd/qmd-daemon.mjs';
|
||||
import { INDEX_EXCLUDES, acquireStartLock, createServer, gitFingerprint, ignoreGlobs, indexIgnores, keepModelsLoaded, pruneCollections } from '../../shared/qmd/qmd-daemon.mjs';
|
||||
import { collectionName } from '../../shared/qmd/qmd-lib.mjs';
|
||||
|
||||
const defaultHits = () => [{ displayPath: `${collectionName('/r')}/src/a.ts`, body: 'x\nretry here', bestChunkPos: 2, bestChunk: 'retry here', score: 0.91 }];
|
||||
@@ -222,6 +222,27 @@ test('git ignored paths reach addCollection and are persisted only when they cha
|
||||
assert.equal(s.store.calls.filter((c) => c[0] === 'update').length, 3);
|
||||
});
|
||||
|
||||
test('daemon start prunes recorded repo collections whose path is gone and keeps the rest', async (t) => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'qmd-prune-'));
|
||||
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
||||
const collectionsFile = join(dir, 'collections.json');
|
||||
const gone = join(dir, 'deleted-worktree');
|
||||
const recorded = ['repo-aaaaaaaaaaaa', 'repo-bbbbbbbbbbbb', 'repo-cccccccccccc', 'repo-dddddddddddd'];
|
||||
writeFileSync(collectionsFile, JSON.stringify(recorded));
|
||||
const store = { listCollections: async () => [
|
||||
{ name: 'notes', pwd: gone }, { name: 'repo-aaaaaaaaaaaa', pwd: gone }, { name: 'repo-bbbbbbbbbbbb', pwd: dir }, { name: 'repo-cccccccccccc', pwd: gone },
|
||||
] };
|
||||
const removed = [];
|
||||
const logged = [];
|
||||
await pruneCollections({ store, collectionsFile, log: (line) => logged.push(line), remove: (name) => {
|
||||
if (name === 'repo-cccccccccccc') throw new Error('locked');
|
||||
removed.push(name);
|
||||
} });
|
||||
assert.deepEqual(removed, ['repo-aaaaaaaaaaaa'], 'only a missing path is removed; foreign collections are never touched');
|
||||
assert.deepEqual(JSON.parse(readFileSync(collectionsFile, 'utf8')), ['repo-bbbbbbbbbbbb', 'repo-cccccccccccc', 'repo-dddddddddddd']);
|
||||
assert.equal(logged.length, 1, 'a failed removal is logged and kept for the next start');
|
||||
});
|
||||
|
||||
test('the start lock admits one launcher and is taken over after 2 minutes', (t) => {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'qmd-lock-'));
|
||||
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
||||
|
||||
@@ -95,13 +95,32 @@ function tempDaemonFile(t, value) {
|
||||
return file;
|
||||
}
|
||||
|
||||
const losingChild = () => {
|
||||
const child = new EventEmitter(); child.unref = () => {}; child.pid = 1;
|
||||
setImmediate(() => child.emit('exit', 0));
|
||||
return child;
|
||||
};
|
||||
|
||||
test('startDaemon resolves when its child loses the start race to a running daemon', async (t) => {
|
||||
const file = tempDaemonFile(t, { port: 4000, token: 'other', pid: 999 });
|
||||
await startDaemon({ file, spawnChild: () => {
|
||||
const child = new EventEmitter(); child.unref = () => {}; child.pid = 1;
|
||||
setImmediate(() => child.emit('exit', 0));
|
||||
return child;
|
||||
} });
|
||||
const fetchImpl = async (url, options) => {
|
||||
assert.equal(url, 'http://127.0.0.1:4000/health');
|
||||
assert.equal(options.headers['x-qmd-token'], 'other');
|
||||
return { ok: true, json: async () => ({ service: 'ai-config-qmd' }) };
|
||||
};
|
||||
await startDaemon({ file, fetchImpl, spawnChild: losingChild });
|
||||
});
|
||||
|
||||
test('after a lost race a stale daemon.json from a crashed daemon is not used until a new token appears', async (t) => {
|
||||
const file = tempDaemonFile(t, { port: 4000, token: 'crashed', pid: 999 });
|
||||
let checks = 0;
|
||||
const fetchImpl = async () => { checks += 1; throw new TypeError('fetch failed'); };
|
||||
let rewritten = false;
|
||||
const timer = setTimeout(() => { rewritten = true; writeFileSync(file, JSON.stringify({ port: 4001, token: 'fresh', pid: 998 })); }, 1200);
|
||||
t.after(() => clearTimeout(timer));
|
||||
await startDaemon({ file, fetchImpl, spawnChild: losingChild });
|
||||
assert.ok(rewritten, 'resolved on the stale daemon.json');
|
||||
assert.ok(checks >= 1, 'the stale token was health-checked');
|
||||
});
|
||||
|
||||
test('a 403 means a stale token: daemon.json is deleted and one new daemon is started', async (t) => {
|
||||
|
||||
@@ -52,6 +52,9 @@ foreach ($shell in @('powershell','bash')) {
|
||||
}
|
||||
}
|
||||
$expectedSkillCount = if ($client -eq 'claude') { $sourceSkillCount + $ruleSkillCount } else { $sourceSkillCount }
|
||||
$launcher = if ($client -eq 'claude') { 'skills/roast-room' } else { 'skills/extensions/roast-room' }
|
||||
if (-not (Test-Path "$package/$launcher/SKILL.md") -or -not (Test-Path "$package/$launcher/agents/openai.yaml")) { throw "Missing roast-room launcher in $package" }
|
||||
if ($client -eq 'codex' -and -not (Test-Path "$package/rules/my-ai-configuration.rules")) { throw "Missing Codex execpolicy rules in $package" }
|
||||
if (@(Get-ChildItem "$package/skills" -Filter SKILL.md -Recurse).Count -ne $expectedSkillCount) { throw "Missing skills in $package" }
|
||||
$securityReview = if ($client -eq 'claude') { 'skills/security-review/SKILL.md' } else { 'skills/reviews/security-review/SKILL.md' }
|
||||
if ($client -eq 'claude' -and @(Get-ChildItem "$package/skills" -Filter SKILL.md -Recurse | Where-Object { $_.Directory.Parent.FullName -ne (Resolve-Path "$package/skills").Path }).Count) { throw "Nested Claude skills in $package" }
|
||||
@@ -63,7 +66,7 @@ foreach ($shell in @('powershell','bash')) {
|
||||
if ($shell -eq 'powershell' -and $content -match 'WindowStyle\s+Hidden') { throw "PowerShell hook hides the terminal in $package" }
|
||||
if ($client -eq 'codex') {
|
||||
$events = @([regex]::Matches($content, '(?m)^\[\[hooks\.([^.\]]+)\]\]\s*$') | ForEach-Object { $_.Groups[1].Value })
|
||||
if ((($events | Sort-Object) -join ',') -ne 'PostToolUse,PreToolUse,PreToolUse,SessionStart,Stop,Stop,Stop,UserPromptSubmit' -or $content -match 'flashbang-if-input' -or $content -match '(?m)^async\s*=\s*true\s*$') { throw "Codex finish hook is incorrect in $package" }
|
||||
if ((($events | Sort-Object) -join ',') -ne 'PostToolUse,PreCompact,PreToolUse,PreToolUse,SessionStart,SessionStart,SessionStart,Stop,Stop,Stop,UserPromptSubmit' -or $content -match 'flashbang-if-input' -or $content -match '(?m)^async\s*=\s*true\s*$') { throw "Codex finish hook is incorrect in $package" }
|
||||
if ($content -notmatch 'approvals_reviewer\s*=\s*"auto_review"') { throw "Codex auto review is missing in $package" }
|
||||
if ($content -notmatch '(?m)^sandbox_mode\s*=\s*"danger-full-access"\s*$') { throw "Codex full access is missing in $package" }
|
||||
if ($content -notmatch '(?m)^max_depth\s*=\s*1\s*$') { throw "Codex agent depth limit is missing in $package" }
|
||||
|
||||
@@ -21,7 +21,7 @@ case "$(uname -s 2>/dev/null || true)" in
|
||||
esac
|
||||
source_agent_count=$(find "$root/shared/agents" -mindepth 1 -maxdepth 1 -type d | wc -l)
|
||||
source_skill_count=$(find "$root/shared/skills" -name SKILL.md | wc -l)
|
||||
mapfile -t rule_paths < <(find "$root/shared/rules" -mindepth 1 -type f -name '*.md' ! -name general.md -printf '%P\n' | sort)
|
||||
mapfile -t rule_paths < <(cd "$root/shared/rules" && find . -mindepth 1 -type f -name '*.md' ! -name general.md | sed 's|^\./||' | sort)
|
||||
rule_skill_count=${#rule_paths[@]}
|
||||
global_instructions=$(<"$root/shared/global-instructions.md")
|
||||
rule_skill_name() {
|
||||
@@ -75,6 +75,11 @@ for shell in powershell bash; do
|
||||
[ "$client" != claude ] || diagnostics="$package/skills"
|
||||
test -f "$diagnostics/incident-investigation/SKILL.md"
|
||||
test -f "$diagnostics/performance-measure/SKILL.md"
|
||||
launcher="$package/skills/extensions/roast-room"
|
||||
[ "$client" != claude ] || launcher="$package/skills/roast-room"
|
||||
test -f "$launcher/SKILL.md"
|
||||
test -f "$launcher/agents/openai.yaml"
|
||||
[ "$client" = claude ] || test -f "$package/rules/my-ai-configuration.rules"
|
||||
test ! -e "$package/skills/marketing-plan/SKILL.md"
|
||||
test ! -e "$package/skills/social/SKILL.md"
|
||||
if [ "$shell" = powershell ]; then
|
||||
@@ -84,7 +89,7 @@ for shell in powershell bash; do
|
||||
grep -q 'bash .*flashbang.sh' "$package/$file"
|
||||
fi
|
||||
if [ "$client" = codex ]; then
|
||||
[ "$(sed -n 's/^\[\[hooks\.\([^].]*\)\]\][[:space:]]*$/\1/p' "$package/$file" | sort)" = $'PostToolUse\nPreToolUse\nPreToolUse\nSessionStart\nStop\nStop\nStop\nUserPromptSubmit' ]
|
||||
[ "$(sed -n 's/^\[\[hooks\.\([^].]*\)\]\][[:space:]]*$/\1/p' "$package/$file" | sort)" = $'PostToolUse\nPreCompact\nPreToolUse\nPreToolUse\nSessionStart\nSessionStart\nSessionStart\nStop\nStop\nStop\nUserPromptSubmit' ]
|
||||
! grep -q 'flashbang-if-input' "$package/$file"
|
||||
! grep -Eq '^async[[:space:]]*=[[:space:]]*true[[:space:]]*$' "$package/$file"
|
||||
grep -q 'approvals_reviewer[[:space:]]*=[[:space:]]*"auto_review"' "$package/$file"
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import tomllib
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
TEST_ROOT = ROOT / '.ai-session' / 'test-uninstall'
|
||||
sys.path.insert(0, str(ROOT / 'scripts/lib'))
|
||||
SPEC = importlib.util.spec_from_file_location('install_options', ROOT / 'scripts/lib/install-options.py')
|
||||
OPTIONS = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(OPTIONS)
|
||||
|
||||
OWNED_SETTINGS = {
|
||||
'permissions': {'allow': ['Agent']},
|
||||
'statusLine': {'type': 'command', 'command': 'bash "/home/.claude/statusline/statusline.sh"'},
|
||||
'sandbox': {'enabled': True, 'excludedCommands': ['node */qmd-search.mjs *']},
|
||||
'hooks': {
|
||||
'Stop': [{'hooks': [{'type': 'command', 'command': 'bash "/home/.claude/hooks/flashbang.sh"'}]}],
|
||||
'PreCompact': [{'hooks': [{'type': 'command', 'command': 'bash "/home/.claude/hooks/scripts/record-compact.sh"'}]}],
|
||||
},
|
||||
}
|
||||
OWNED_TOML = ('approval_policy = "on-request"\n\n[features]\nhooks = true\n\n'
|
||||
'[[hooks.Stop]]\n[[hooks.Stop.hooks]]\ntype = "command"\n'
|
||||
"command = 'bash \"/home/.codex/hooks/flashbang.sh\"'\ntimeout = 8\n")
|
||||
|
||||
|
||||
def find_bash():
|
||||
if os.name == 'nt':
|
||||
candidate = Path(os.environ.get('ProgramFiles', 'C:/Program Files')) / 'Git/bin/bash.exe'
|
||||
return str(candidate) if candidate.exists() else None
|
||||
return shutil.which('bash')
|
||||
|
||||
|
||||
def find_powershell():
|
||||
return shutil.which('powershell') or shutil.which('pwsh')
|
||||
|
||||
|
||||
class UninstallTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
TEST_ROOT.mkdir(parents=True, exist_ok=True)
|
||||
self.temporary = tempfile.TemporaryDirectory(dir=TEST_ROOT)
|
||||
self.addCleanup(self.temporary.cleanup)
|
||||
self.work = Path(self.temporary.name)
|
||||
self.environment = dict(os.environ, AI_CONFIG_NO_INTERACTIVE='1')
|
||||
for name in ('TEMP', 'TMP', 'TMPDIR'):
|
||||
self.environment[name] = str(self.work)
|
||||
|
||||
def run_process(self, arguments, environment=None, timeout=120):
|
||||
return subprocess.run(arguments, env=environment or self.environment, stdin=subprocess.DEVNULL,
|
||||
capture_output=True, text=True, timeout=timeout)
|
||||
|
||||
def bash_sync(self, source, destination):
|
||||
shell = find_bash() or self.skipTest('Bash unavailable')
|
||||
result = self.run_process([shell, '-c', 'set -euo pipefail; . "$1/scripts/lib/manifest.sh"; '
|
||||
'run_managed_sync "$2" "$3" stamp /root "" "" false true',
|
||||
'test', ROOT.as_posix(), source.as_posix(), destination.as_posix()])
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
return result.stdout
|
||||
|
||||
def powershell_sync(self, source, destination):
|
||||
shell = find_powershell() or self.skipTest('PowerShell unavailable')
|
||||
environment = dict(self.environment, TEST_ROOT=str(ROOT), TEST_SOURCE=str(source), TEST_DESTINATION=str(destination))
|
||||
if Path(shell).stem.lower() == 'powershell':
|
||||
environment = {key: value for key, value in environment.items() if key.upper() != 'PSMODULEPATH'} # Windows PowerShell 5.1 cannot load pwsh 7 module paths
|
||||
result = self.run_process([shell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command',
|
||||
"$ErrorActionPreference = 'Stop'; . (Join-Path $env:TEST_ROOT 'scripts/lib/manifest.ps1'); "
|
||||
"Invoke-ManagedSync -Source $env:TEST_SOURCE -Destination $env:TEST_DESTINATION -Stamp stamp "
|
||||
"-AiConfigRoot /root -ShellCommand '' -PowerShellCommand '' -Summary"], environment)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
return result.stdout
|
||||
|
||||
def make_source(self, files):
|
||||
source = self.work / 'source'
|
||||
shutil.rmtree(source, ignore_errors=True)
|
||||
source.mkdir()
|
||||
for name, content in files.items():
|
||||
(source / name).write_bytes(content.encode('utf-8'))
|
||||
return source
|
||||
|
||||
# Bug 1: plugin installs change settings.json after install; uninstall must still remove owned hooks.
|
||||
def check_uninstall_strips_owned_entries(self, sync):
|
||||
destination = self.work / 'home/.claude'
|
||||
sync(self.make_source({'settings.json': json.dumps(OWNED_SETTINGS, indent=2) + '\n', 'config.toml': OWNED_TOML}), destination)
|
||||
settings = json.loads((destination / 'settings.json').read_text(encoding='utf-8'))
|
||||
settings['enabledPlugins'] = {'demo@market': True}
|
||||
settings['hooks']['Stop'].append({'hooks': [{'type': 'command', 'command': 'foreign-hook'}]})
|
||||
(destination / 'settings.json').write_text(json.dumps(settings, indent=2) + '\n', encoding='utf-8')
|
||||
|
||||
sync(self.make_source({}), destination)
|
||||
|
||||
self.assertFalse((destination / 'config.toml').exists(), 'an unmodified managed file is removed')
|
||||
remaining = json.loads((destination / 'settings.json').read_text(encoding='utf-8'))
|
||||
self.assertEqual(remaining['enabledPlugins'], {'demo@market': True})
|
||||
self.assertEqual(remaining['permissions'], {'allow': ['Agent']})
|
||||
self.assertNotIn('statusLine', remaining)
|
||||
self.assertEqual(remaining['sandbox'], {'enabled': True})
|
||||
self.assertEqual(remaining['hooks'], {'Stop': [{'hooks': [{'type': 'command', 'command': 'foreign-hook'}]}]})
|
||||
self.assertTrue((destination / 'backups/stamp/settings.json').exists())
|
||||
|
||||
def test_bash_uninstall_strips_owned_entries_from_changed_settings(self):
|
||||
self.check_uninstall_strips_owned_entries(self.bash_sync)
|
||||
|
||||
def test_powershell_uninstall_strips_owned_entries_from_changed_settings(self):
|
||||
self.check_uninstall_strips_owned_entries(self.powershell_sync)
|
||||
|
||||
def test_strip_removes_owned_toml_hooks_and_keeps_user_tables(self):
|
||||
current = OWNED_TOML + '\n[plugins."demo@market"]\nenabled = true\n'
|
||||
result = OPTIONS.strip_toml(current)
|
||||
parsed = tomllib.loads(result)
|
||||
self.assertNotIn('hooks', parsed)
|
||||
self.assertEqual(parsed['plugins'], {'demo@market': {'enabled': True}})
|
||||
self.assertEqual(parsed['approval_policy'], 'on-request')
|
||||
self.assertEqual(OPTIONS.strip_toml(OWNED_TOML[OWNED_TOML.index('[[hooks'):]), '')
|
||||
|
||||
def test_strip_json_returns_empty_when_only_owned_entries_remain(self):
|
||||
owned = {key: OWNED_SETTINGS[key] for key in ('statusLine', 'hooks')}
|
||||
self.assertEqual(OPTIONS.strip_json(owned), {})
|
||||
|
||||
# Bug 4: Bash must write the same merged bytes as PowerShell.
|
||||
def test_bash_and_powershell_write_identical_merged_files(self):
|
||||
files = {'settings.json': json.dumps(OWNED_SETTINGS, indent=2) + '\n', 'config.toml': OWNED_TOML, 'CLAUDE.md': '# Title\n\nBody\n'}
|
||||
current = {'settings.json': '{"model": "x"}\n', 'config.toml': 'model = "x"\n', 'CLAUDE.md': 'old\n'}
|
||||
written = {}
|
||||
for name, sync in (('bash', self.bash_sync), ('powershell', self.powershell_sync)):
|
||||
destination = self.work / name / '.claude'
|
||||
destination.mkdir(parents=True)
|
||||
for file, content in current.items():
|
||||
(destination / file).write_bytes(content.encode('utf-8'))
|
||||
sync(self.make_source(files), destination)
|
||||
written[name] = {file: (destination / file).read_bytes() for file in files}
|
||||
for file, content in written[name].items():
|
||||
self.assertNotIn(b'\r', content, f'{name} {file}')
|
||||
self.assertTrue(content.endswith(b'\n'), f'{name} {file}')
|
||||
self.assertEqual(written['bash'], written['powershell'])
|
||||
|
||||
# Bug 2: uninstalling one client must keep the selection while the other client is installed.
|
||||
def uninstall_copy(self, suffix, replacements):
|
||||
source = (ROOT / f'scripts/commands/uninstall{suffix}').read_text(encoding='utf-8-sig')
|
||||
for old, new in replacements:
|
||||
self.assertIn(old, source)
|
||||
source = source.replace(old, new)
|
||||
with tempfile.NamedTemporaryFile(mode='w', suffix=f'.tmp{suffix}', dir=ROOT / 'scripts/commands',
|
||||
encoding='utf-8', newline='\n', delete=False) as stream:
|
||||
stream.write(source)
|
||||
entry = Path(stream.name)
|
||||
self.addCleanup(entry.unlink)
|
||||
return entry
|
||||
|
||||
def make_installed_home(self):
|
||||
home = self.work / 'home'
|
||||
for destination in ('.claude', '.codex', '.agents/skills'):
|
||||
(home / destination).mkdir(parents=True)
|
||||
(home / destination / '.ai-config-manifest.tsv').write_text('path\tsha256\n', encoding='utf-8')
|
||||
selection = home / '.my-ai-configuration/selection.json'
|
||||
selection.parent.mkdir()
|
||||
selection.write_text('{}', encoding='utf-8')
|
||||
return home, selection
|
||||
|
||||
def test_bash_uninstall_one_client_keeps_selection(self):
|
||||
shell = find_bash() or self.skipTest('Bash unavailable')
|
||||
home, selection = self.make_installed_home()
|
||||
entry = self.uninstall_copy('.sh', [('sync_configured_plugins "$root"', ': '), ('sync_qmd "$root"', ': ')])
|
||||
result = self.run_process([shell, str(entry), '--client', 'claude', '--force', '--summary'],
|
||||
dict(self.environment, HOME=home.as_posix()))
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertFalse((home / '.claude/.ai-config-manifest.tsv').exists())
|
||||
self.assertTrue(selection.exists())
|
||||
|
||||
def test_powershell_uninstall_one_client_keeps_selection(self):
|
||||
shell = find_powershell() or self.skipTest('PowerShell unavailable')
|
||||
home, selection = self.make_installed_home()
|
||||
entry = self.uninstall_copy('.ps1', [("[Environment]::GetFolderPath('UserProfile')", '$env:TEST_HOME'),
|
||||
('Sync-ConfiguredPlugins -RepositoryRoot', '# '), ('Sync-Qmd -RepositoryRoot', '# ')])
|
||||
environment = dict(self.environment, TEST_HOME=str(home))
|
||||
if Path(shell).stem.lower() == 'powershell':
|
||||
environment = {key: value for key, value in environment.items() if key.upper() != 'PSMODULEPATH'}
|
||||
result = self.run_process([shell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(entry),
|
||||
'-Client', 'Claude', '-Force', '-Summary'], environment)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertFalse((home / '.claude/.ai-config-manifest.tsv').exists())
|
||||
self.assertTrue(selection.exists())
|
||||
|
||||
# Bug 3: update must validate CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY like install does.
|
||||
def test_bash_update_rejects_invalid_claude_concurrency(self):
|
||||
shell = find_bash() or self.skipTest('Bash unavailable')
|
||||
result = self.run_process([shell, str(ROOT / 'scripts/commands/update.sh'), '--dry-run', '--client', 'claude', '--shell', 'bash'],
|
||||
dict(self.environment, HOME=self.work.as_posix(), CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY='11'))
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn('CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY must be an integer from 1 to 10.', result.stderr)
|
||||
|
||||
def test_powershell_update_rejects_invalid_claude_concurrency(self):
|
||||
shell = find_powershell() or self.skipTest('PowerShell unavailable')
|
||||
environment = dict(self.environment, CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY='0')
|
||||
if Path(shell).stem.lower() == 'powershell':
|
||||
environment = {key: value for key, value in environment.items() if key.upper() != 'PSMODULEPATH'}
|
||||
result = self.run_process([shell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(ROOT / 'scripts/commands/update.ps1'),
|
||||
'-DryRun', '-Client', 'Claude', '-Shell', 'Bash'], environment)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn('CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY must be an integer from 1 to 10.', result.stdout + result.stderr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(argv=[sys.argv[0]], verbosity=2)
|
||||
@@ -1,6 +1,7 @@
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import uuid
|
||||
@@ -88,6 +89,15 @@ class UserCustomizationTests(unittest.TestCase):
|
||||
], capture_output=True, text=True, timeout=20)
|
||||
self.assertEqual(3, injected.returncode, injected.stderr)
|
||||
self.assertIn('child-output', injected.stdout)
|
||||
helper_call = [powershell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(helper), '-Client', 'Codex', '-Key', key]
|
||||
# Child flags that abbreviate helper or common parameters (-k, -d, -v, -c) must reach the child unchanged.
|
||||
echoed = subprocess.run(helper_call + ['-FilePath', sys.executable, '-c', 'import sys; print(chr(124).join(sys.argv[1:]))',
|
||||
'-k', '-d', '-v', '-Key', 'x'], capture_output=True, text=True, timeout=20)
|
||||
self.assertEqual(0, echoed.returncode, echoed.stderr)
|
||||
self.assertEqual('-k|-d|-v|-Key|x', echoed.stdout.strip())
|
||||
# A command name found on PATH works without a full path.
|
||||
on_path = subprocess.run(helper_call + ['-FilePath', 'cmd.exe', '/c', 'exit', '4'], capture_output=True, text=True, timeout=20)
|
||||
self.assertEqual(4, on_path.returncode, on_path.stderr)
|
||||
finally:
|
||||
cleanup = subprocess.run([
|
||||
powershell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command',
|
||||
|
||||
Reference in new issue
Block a user