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().parent.parent.parent 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) class InstallOptionsTests(unittest.TestCase): def test_codex_update_replaces_old_sandbox_mode_and_preserves_user_settings(self): current = ('sandbox_mode = "workspace-write"\nmodel = "custom-model"\n' '[windows]\nsandbox = "elevated"\n' '[sandbox_workspace_write]\nnetwork_access = false\n' '[mcp_servers.demo]\ncommand = "demo"\n') managed = (ROOT / 'adapters/codex/config/config.toml').read_text(encoding='utf-8') result = tomllib.loads(OPTIONS.merge_toml(current, managed)) self.assertEqual(result['sandbox_mode'], 'danger-full-access') self.assertEqual(result['approval_policy'], 'on-request') self.assertEqual(result['approvals_reviewer'], 'auto_review') self.assertEqual(result['model'], 'custom-model') self.assertEqual(result['mcp_servers']['demo'], {'command': 'demo'}) def test_merge_toml_preserves_local_plugin_table_indentation(self): plugin_state = (' [marketplaces.ponytail]\n' ' source_type = "git"\n' ' source = "https://github.com/DietrichGebert/ponytail.git"\n' ' [plugins."ponytail@ponytail"]\n' ' enabled = true\n' ' [plugins."disabled@market"]\n' ' enabled = false') current = "model = 'old'\napprovals_reviewer = 'user'\n" + plugin_state + '\n' managed = "approvals_reviewer = 'auto_review'\n\n[tui]\n" result = OPTIONS.merge_toml(current, managed) self.assertIn(plugin_state, result) def test_merge_toml_preserves_unmanaged_tables(self): foreign = ('[mcp_servers.demo]\ncommand = "demo"\n\n[mcp_servers.demo.env]\nTOKEN_NAME = "x"\n\n' '[model_providers.custom]\nname = "Custom"\nbase_url = "https://example.invalid"\n') current = "model = 'old'\n\n[tui]\nstatus_line = ['a']\ntheme = 'dark'\n\n" + foreign managed = "model = 'new'\n\n[tui]\nstatus_line = ['b']\n" result = tomllib.loads(OPTIONS.merge_toml(current, managed)) self.assertEqual(result['model'], 'new') self.assertEqual(result['tui'], {'status_line': ['b'], 'theme': 'dark'}) self.assertEqual(result['mcp_servers'], {'demo': {'command': 'demo', 'env': {'TOKEN_NAME': 'x'}}}) self.assertEqual(result['model_providers'], {'custom': {'name': 'Custom', 'base_url': 'https://example.invalid'}}) def test_merge_json_removes_only_owned_hooks_from_mixed_group(self): owned = {'type': 'command', 'command': 'bash "/old/hooks/flashbang.sh"', 'timeout': 8} foreign = {'type': 'command', 'command': 'notify-done', 'timeout': 3} current = {'hooks': {'Stop': [{'matcher': 'custom', 'hooks': [owned, foreign]}], 'PreCompact': [{'hooks': [{'type': 'command', 'command': 'bash "/old/record-compact.sh"'}]}]}} managed_stop = {'hooks': [{'type': 'command', 'command': 'bash "/new/hooks/flashbang.sh"', 'timeout': 8}]} managed = {'hooks': {'Stop': [managed_stop], 'PreCompact': []}} hooks = OPTIONS.merge_json(current, managed)['hooks'] self.assertEqual(hooks['Stop'], [managed_stop, {'matcher': 'custom', 'hooks': [foreign]}]) self.assertNotIn('PreCompact', hooks) def test_merge_cli_accepts_bom_input_and_preserves_non_ascii(self): with tempfile.TemporaryDirectory() as directory: current = Path(directory) / 'config.toml' current.write_text('# Größe\n[mcp_servers.demo]\ncommand = "ä"\n', encoding='utf-8') output = Path(directory) / 'out.toml' script = str(ROOT / 'scripts/lib/install-options.py') managed = 'model = "new"\n'.encode('utf-8') piped = subprocess.run([sys.executable, script, 'merge-toml', '--current', str(current), '--output', str(output)], input=managed) self.assertEqual(piped.returncode, 0) self.assertEqual(tomllib.loads(output.read_text(encoding='utf-8'))['mcp_servers']['demo']['command'], 'ä') managed_path = Path(directory) / 'managed.toml' managed_path.write_bytes(managed) subprocess.run([sys.executable, script, 'merge-toml', '--current', str(current), '--managed', str(managed_path), '--output', str(output)], check=True) self.assertIn('# Größe', output.read_text(encoding='utf-8')) def test_semantic_retrieval_disabled_removes_qmd_session_hook(self): with tempfile.TemporaryDirectory() as directory: settings = Path(directory) / 'settings.json' settings.write_text(json.dumps({'hooks': {'SessionStart': [ {'hooks': [{'type': 'command', 'command': 'bash "/c/hooks/scripts/show-session-state-pointer.sh"'}]}, {'hooks': [{'type': 'command', 'command': 'bash "/c/hooks/scripts/qmd-warm.sh"'}]}]}}), encoding='utf-8') result = json.loads(OPTIONS.filter_options(settings, semantic_retrieval_enabled=False)) 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_semantic_retrieval_disabled_removes_qmd_sandbox_exclusion(self): with tempfile.TemporaryDirectory() as directory: settings = Path(directory) / 'settings.json' qmd = 'node "$HOME/.my-ai-configuration/qmd/qmd-search.mjs" *' settings.write_text(json.dumps({'sandbox': {'enabled': True, 'excludedCommands': [qmd, 'docker *']}}), encoding='utf-8') self.assertEqual(json.loads(OPTIONS.filter_options(settings, semantic_retrieval_enabled=False))['sandbox']['excludedCommands'], ['docker *']) settings.write_text(json.dumps({'sandbox': {'enabled': True, 'excludedCommands': [qmd]}}), encoding='utf-8') self.assertEqual(json.loads(OPTIONS.filter_options(settings, semantic_retrieval_enabled=False))['sandbox'], {'enabled': True}) self.assertEqual(json.loads(OPTIONS.filter_options(settings, semantic_retrieval_enabled=True))['sandbox']['excludedCommands'], [qmd]) current = {'sandbox': {'enabled': True, 'excludedCommands': [qmd, 'docker *']}} self.assertEqual(OPTIONS.merge_json(current, {'sandbox': {'enabled': True}})['sandbox']['excludedCommands'], ['docker *']) self.assertEqual(OPTIONS.merge_json(current, {'sandbox': {'excludedCommands': [qmd]}})['sandbox']['excludedCommands'], [qmd, 'docker *']) def test_semantic_retrieval_disabled_removes_codex_session_hook(self): with tempfile.TemporaryDirectory() as directory: config = Path(directory) / 'config.toml' config.write_text('[features]\nhooks = true\n\n[[hooks.SessionStart]]\n[[hooks.SessionStart.hooks]]\ntype = "command"\n' 'command = \'bash "/c/hooks/scripts/qmd-warm.sh"\'\ncommand_windows = \'pwsh "/c/hooks/scripts/Start-QmdWarm.ps1"\'\ntimeout = 4\n', encoding='utf-8') result = OPTIONS.filter_options(config, semantic_retrieval_enabled=False) self.assertNotIn('qmd-warm', result) self.assertNotIn('hooks.SessionStart', result) def test_codex_merge_registers_impeccable_hooks_once(self): managed = (ROOT / 'adapters/codex/config/config.toml').read_text(encoding='utf-8') managed = managed.replace('__IMPECCABLE_HOOK_SCRIPT__', 'invoke-impeccable-hook.sh') merged = OPTIONS.merge_toml(OPTIONS.merge_toml('', managed), managed) hooks = tomllib.loads(merged)['hooks'] def impeccable(groups): return [group for group in groups if 'impeccable-hook' in group['hooks'][0]['command']] self.assertEqual(1, len(impeccable(hooks['PostToolUse']))) self.assertEqual('Edit|Write|apply_patch', impeccable(hooks['PostToolUse'])[0]['matcher']) self.assertEqual(1, len(impeccable(hooks['Stop']))) def test_impeccable_hook_wrappers_forward_event_or_are_noops(self): scripts = ROOT / 'shared/hooks/scripts' shells = [(shutil.which('bash'), [], 'invoke-impeccable-hook.sh', 'impeccable', 'printf "%s:" "$1"; cat\n')] if os.name == 'nt': shells.append((shutil.which('powershell'), ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File'], 'Invoke-ImpeccableHook.ps1', 'impeccable.cmd', '@echo off\r\n