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:
Julian LechnerandClaude Opus 5.5 committed 2026-11-19 09:02:47 +01:00
1 parent 63a36d90e0
commit b35e2254b3
48 files changed
+1059 -98

No files matched your search

+63
View File
@@ -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()
+33 -2
View File
@@ -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__':
+10
View File
@@ -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'
+122
View File
@@ -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'
+1 -1
View File
@@ -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
+3 -1
View File
@@ -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"; }
+23 -2
View File
@@ -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 }));
+24 -5
View File
@@ -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) => {
+4 -1
View File
@@ -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" }
+7 -2
View File
@@ -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"
+210
View 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)
+10
View File
@@ -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',