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)