Skip to content

armgit / ODS

Public Imported from GitHub
0

ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.

37.2 KB
Raw Blame
import importlib.util
import json
import os
from pathlib import Path
import subprocess
import shlex
import sys
from types import SimpleNamespace

import pytest


ROOT = Path(__file__).resolve().parents[1]
SPEC = importlib.util.spec_from_file_location('native_install',
    ROOT / 'installers/macos/lib/pixel-native-install.py')
module = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(module)


@pytest.mark.parametrize('code', [0, 1])
def test_pixel_diagnostic_reaches_install_log_without_hiding_failure(tmp_path, code):
    script = (ROOT / 'installers/macos/install-macos.sh').read_text()
    start = script.index('        if ! /usr/bin/python3 "$LIB_DIR/pixel-native-install.py"')
    end = script.index('\n        fi', start) + len('\n        fi')
    command = script[start:end].replace('/usr/bin/python3', shlex.quote(sys.executable))
    helper = tmp_path / 'pixel-native-install.py'
    helper.write_text('import sys\nprint("public-health-diagnostic", file=sys.stderr)\nsys.exit(' + str(code) + ')\n')
    log = tmp_path / 'install.log'
    shell = 'set -euo pipefail\nai_err() { printf "%s\\n" "$*"; }\n_pixel_install_args=(--fixture)\n' + command
    result = subprocess.run(['/bin/bash', '-c', shell], text=True, capture_output=True,
        env={**os.environ, 'LIB_DIR': str(tmp_path), 'ODS_LOG_FILE': str(log)})
    assert result.returncode == code
    assert 'public-health-diagnostic' in result.stdout
    assert log.read_text() == 'public-health-diagnostic\n'


@pytest.mark.parametrize('code,detail', [
    ('native-compose-health-timeout', 'pixel-native-ingress, pixel-workspace-preview, pixel-edge'),
    ('compose-security-policy-missing', 'scripts/compose-cache-policy.py'),
])
def test_main_reports_allowlisted_activation_failures(monkeypatch, capsys, code, detail):
    def fail(**kwargs):
        raise ValueError(code)
    monkeypatch.setattr(module, 'install', fail)
    monkeypatch.setattr(module.sys, 'argv', ['pixel-native-install.py',
        '--install-dir', '/unused', '--ods-source', '/unused'])
    assert module.main() == 1
    captured = capsys.readouterr()
    assert captured.out == ''
    assert 'Native Pixel installation stopped (ValueError).' in captured.err
    assert '[' + code + ']' in captured.err
    assert detail in captured.err
    assert 'do not reset receipts or repeat activation automatically' in captured.err


@pytest.mark.parametrize('code,detail', [
    ('native-sandbox-build-failed', 'pinned Node.js runtime from nodejs.org'),
    ('native-sandbox-execution-proof-failed', 'no npm, npx or corepack'),
    ('invalid-sandbox-node-runtime', 'leave PIXEL_SOURCE_REF unset'),
])
def test_main_reports_sandbox_image_failures_with_recovery(monkeypatch, capsys, code, detail):
    def fail(**kwargs):
        raise ValueError(code)
    monkeypatch.setattr(module, 'install', fail)
    monkeypatch.setattr(module.sys, 'argv', ['pixel-native-install.py',
        '--install-dir', '/unused', '--ods-source', '/unused'])
    assert module.main() == 1
    captured = capsys.readouterr()
    assert '[' + code + ']' in captured.err
    assert detail in captured.err
    assert 'https://discord.gg/4ntNp9MAwC' in captured.err


def test_main_reports_individual_health_without_docker_output(monkeypatch, capsys):
    compose = module.helper('compose')
    states = {name: {'state': 'running', 'health': 'healthy'} for name in compose.SERVICES}
    states['pixel-workspace-preview'] = {'state': 'restarting', 'health': 'unhealthy'}
    def fail(**kwargs):
        raise compose.NativeHealthTimeout(states)
    monkeypatch.setattr(module, 'install', fail)
    monkeypatch.setattr(module.sys, 'argv', ['pixel-native-install.py',
        '--install-dir', '/unused', '--ods-source', '/unused'])
    assert module.main() == 1
    output = capsys.readouterr()
    assert output.out == ''
    assert 'pixel-workspace-preview=restarting/unhealthy' in output.err
    assert 'pixel-native-ingress=running/healthy' in output.err
    assert 'pixel-edge=running/healthy' in output.err


@pytest.mark.parametrize('error', [
    ValueError('secret-canary-value'),
    ValueError('native-compose-health-timeout secret-canary-near-match'),
    OSError('secret-canary-path'),
    KeyError('secret-canary-key'),
    subprocess.CalledProcessError(1, ['secret-canary-argument'],
        output='secret-canary-output', stderr='secret-canary-stderr'),
])
def test_main_does_not_disclose_unknown_exception_details(monkeypatch, capsys, error):
    def fail(**kwargs):
        raise error
    monkeypatch.setattr(module, 'install', fail)
    monkeypatch.setattr(module.sys, 'argv', ['pixel-native-install.py',
        '--install-dir', '/unused', '--ods-source', '/unused'])
    assert module.main() == 1
    captured = capsys.readouterr()
    assert captured.out == ''
    assert 'secret-canary' not in captured.err
    assert '[' not in captured.err
    assert 'Check prerequisites and private preparation/activation receipts' in captured.err


def test_main_keeps_preflight_guidance(monkeypatch, capsys):
    def fail(*args, **kwargs):
        raise ValueError('native-apple-silicon-owner-required')
    monkeypatch.setattr(module, 'preflight', fail)
    monkeypatch.setattr(module.sys, 'argv', ['pixel-native-install.py',
        '--install-dir', '/unused', '--preflight-only'])
    assert module.main() == 1
    assert '[native-apple-silicon-owner-required] Run as the signed-in owner' in capsys.readouterr().err


@pytest.mark.parametrize('fault', [None, 'root', 'intel', 'linux', 'existing', 'partial', 'relative'])
def test_preflight_never_mutates_existing_installations(tmp_path, monkeypatch, fault):
    monkeypatch.setattr(module.sys, 'platform', 'linux' if fault == 'linux' else 'darwin')
    monkeypatch.setattr(module.platform, 'machine', lambda: 'x86_64' if fault == 'intel' else 'arm64')
    monkeypatch.setattr(module.os, 'geteuid', lambda: 0 if fault == 'root' else 501)
    checked = []
    def exists(path):
        checked.append(str(path))
        return ((fault == 'existing' and str(path).endswith('pixel-access.json')) or
                (fault == 'partial' and str(path).endswith('pixel-native')))
    monkeypatch.setattr(module.os.path, 'lexists', exists)
    args = dict(install_dir='relative' if fault == 'relative' else tmp_path / 'ods')
    if fault:
        with pytest.raises(ValueError): module.preflight(**args)
    else:
        assert module.preflight(**args) == tmp_path / 'ods'
        assert len(checked) == 2 + len(module.NATIVE_RESIDUE_PATHS)
    assert not list(tmp_path.iterdir())


@pytest.mark.parametrize('verified', [True, False])
def test_preflight_retained_identity_requires_root_proof(tmp_path, monkeypatch, verified):
    monkeypatch.setattr(module.sys, 'platform', 'darwin')
    monkeypatch.setattr(module.platform, 'machine', lambda: 'arm64')
    monkeypatch.setattr(module.os, 'geteuid', lambda: 501)
    monkeypatch.setattr(module.os.path, 'lexists',
        lambda path: str(path) == '/private/var/lib/ods-pixel-access')
    calls = []
    monkeypatch.setattr(module, 'retained_identity_only',
        lambda **kwargs: calls.append(kwargs) or verified)
    if verified:
        assert module.preflight(tmp_path / 'fresh-ods') == tmp_path / 'fresh-ods'
    else:
        with pytest.raises(ValueError, match='retained-pixel-identity-rejected'):
            module.preflight(tmp_path / 'fresh-ods')
    assert calls == [{'empty_home': False, 'prompt_for_sudo': False}]
    assert not list(tmp_path.iterdir())


@pytest.mark.parametrize('residue', [path for path in module.NATIVE_RESIDUE_PATHS
    if path != module.RETAINED_OPS_HOME])
def test_preflight_refuses_any_other_native_global_state(
        tmp_path, monkeypatch, residue):
    monkeypatch.setattr(module.sys, 'platform', 'darwin')
    monkeypatch.setattr(module.platform, 'machine', lambda: 'arm64')
    monkeypatch.setattr(module.os, 'geteuid', lambda: 501)
    monkeypatch.setattr(module.os.path, 'lexists',
        lambda path: str(path) in (str(residue), '/private/var/lib/ods-pixel-access'))
    monkeypatch.setattr(module, 'retained_identity_only',
        lambda: pytest.fail('residue must be rejected before account proof'))
    with pytest.raises(ValueError, match='existing-native-pixel'):
        module.preflight(tmp_path / 'fresh-ods')


@pytest.mark.parametrize('receipt, verified', [(False, False), (True, False), (True, True)])
def test_preflight_allows_only_root_verified_empty_retained_home(
        tmp_path, monkeypatch, receipt, verified):
    monkeypatch.setattr(module.sys, 'platform', 'darwin')
    monkeypatch.setattr(module.platform, 'machine', lambda: 'arm64')
    monkeypatch.setattr(module.os, 'geteuid', lambda: 501)
    monkeypatch.setattr(module.os.path, 'lexists', lambda path:
        str(path) == str(module.RETAINED_OPS_HOME) or
        (receipt and str(path) == '/private/var/lib/ods-pixel-access'))
    calls = []
    monkeypatch.setattr(module, 'retained_identity_only',
        lambda **kwargs: calls.append(kwargs) or verified)
    if receipt and verified:
        assert module.preflight(tmp_path / 'fresh-ods') == tmp_path / 'fresh-ods'
    else:
        # A home without the identity receipt is leftover state; a receipt
        # whose proof fails is a rejected identity, not existing Pixel state.
        with pytest.raises(ValueError, match='retained-pixel-identity-rejected' if receipt
                else 'existing-native-pixel'):
            module.preflight(tmp_path / 'fresh-ods')
    assert calls == ([{'empty_home': True, 'prompt_for_sudo': False}] if receipt else [])


def test_retained_identity_proof_is_read_only_and_fails_closed(monkeypatch):
    calls = []
    def run(argv, **kwargs):
        calls.append((argv, kwargs))
        return SimpleNamespace(returncode=0)
    monkeypatch.setattr(module.subprocess, 'run', run)
    assert module.retained_identity_only() is True
    argv, kwargs = calls[0]
    assert argv == ['/usr/bin/sudo', '-n', '/usr/bin/python3',
        str(module.HERE / 'pixel-native-ops-account.py'), '--verify-identity-only']
    assert kwargs['stdin'] == subprocess.DEVNULL and kwargs['check'] is False
    assert len(calls) == 1
    assert module.retained_identity_only(empty_home=True) is True
    assert calls[1][0][-1] == '--verify-empty-home-only'
    monkeypatch.setattr(module.subprocess, 'run',
        lambda *args, **kwargs: SimpleNamespace(returncode=os.EX_DATAERR, stderr=None))
    assert module.retained_identity_only() is False


@pytest.mark.parametrize('prompt,tty,stderr_tty,interactive', [
    (False, True, True, False), (True, False, True, False),
    (False, True, False, False), (True, False, False, False),
    (True, True, False, True), (True, True, True, True)])
def test_identity_prompt_requires_explicit_opt_in_and_terminal(
        monkeypatch, prompt, tty, stderr_tty, interactive):
    # `curl ... | bash` leaves stdin a pipe; sudo still prompts on /dev/tty.
    monkeypatch.setattr(module.sys.stdin, 'isatty', lambda: False)
    monkeypatch.setattr(module.sys.stderr, 'isatty', lambda: stderr_tty)
    monkeypatch.setattr(module, 'controlling_terminal', lambda: tty)
    calls = []
    monkeypatch.setattr(module.subprocess, 'run', lambda argv, **kw:
        calls.append((argv, kw)) or SimpleNamespace(returncode=0))
    assert module.retained_identity_only(prompt_for_sudo=prompt)
    argv, kw = calls[0]
    assert ('-n' not in argv) == interactive
    assert kw['stdin'] == subprocess.DEVNULL
    assert kw['stderr'] == (None if interactive else subprocess.PIPE)
    assert argv[-1] == '--verify-identity-only'


@pytest.mark.skipif(os.name != 'posix', reason='requires a POSIX controlling terminal')
def test_identity_prompt_survives_shipped_installer_logging_pipeline(tmp_path):
    import fcntl
    import pty
    import termios

    installer = (ROOT / 'installers/macos/install-macos.sh').read_text()
    start = installer.index('        if ! /usr/bin/python3 "$LIB_DIR/pixel-native-install.py"')
    end = installer.index('\n        fi', start) + len('\n        fi')
    command = installer[start:end].replace('/usr/bin/python3', shlex.quote(sys.executable))
    helper = tmp_path / 'pixel-native-install.py'
    source = ROOT / 'installers/macos/lib/pixel-native-install.py'
    # Only sudo execution is replaced. Terminal detection and the installer's
    # actual stderr/stdout logging pipeline run in a real child process.
    helper.write_text(f'''import importlib.util, json, sys
from types import SimpleNamespace
spec = importlib.util.spec_from_file_location('native', {str(source)!r})
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
def sudo(argv, **kwargs):
    print(json.dumps({{'argv': argv, 'stdin_tty': sys.stdin.isatty(),
                      'stderr_tty': sys.stderr.isatty(),
                      'controlling_tty': module.controlling_terminal()}}))
    return SimpleNamespace(returncode=0)
module.subprocess.run = sudo
assert module.retained_identity_only(prompt_for_sudo='--prompt-for-sudo' in sys.argv)
''')
    log = tmp_path / 'install.log'
    shell = 'set -euo pipefail\nai_err() { printf "%s\\n" "$*"; }\n_pixel_install_args=(--prompt-for-sudo)\n' + command
    master, slave = pty.openpty()

    def acquire_terminal():
        os.setsid()
        fcntl.ioctl(slave, termios.TIOCSCTTY, 0)

    try:
        result = subprocess.run(['/bin/bash', '-c', shell], input='', text=True,
            capture_output=True, timeout=10, preexec_fn=acquire_terminal,
            pass_fds=(slave,), env={**os.environ, 'LIB_DIR': str(tmp_path), 'ODS_LOG_FILE': str(log)})
    finally:
        os.close(slave)
        os.close(master)
    assert result.returncode == 0, result.stderr
    observed = json.loads(result.stdout)
    assert observed['controlling_tty'] is True
    assert observed['stdin_tty'] is False
    assert observed['stderr_tty'] is False
    assert '-n' not in observed['argv']
    assert log.read_text() == result.stdout


@pytest.mark.parametrize('available', [True, False])
def test_controlling_terminal_probes_dev_tty_without_acquiring_it(monkeypatch, available):
    opened, closed = [], []
    def fake_open(path, flags):
        opened.append((path, flags))
        if not available:
            raise OSError('no controlling terminal')
        return 99
    monkeypatch.setattr(module.os, 'open', fake_open)
    monkeypatch.setattr(module.os, 'close', closed.append)
    assert module.controlling_terminal() is available
    assert opened == [('/dev/tty', module.os.O_RDWR | module.os.O_NOCTTY)]
    assert closed == ([99] if available else [])


def test_identity_rejection_relays_only_the_helper_reason_line(monkeypatch, capsys):
    stderr = (b'unrelated diagnostic\n'
        b'Native Pixel Operations identity verification rejected: operations-identity-process-active.\n')
    monkeypatch.setattr(module.subprocess, 'run', lambda *args, **kw:
        SimpleNamespace(returncode=os.EX_DATAERR, stderr=stderr))
    assert module.retained_identity_only() is False
    assert capsys.readouterr().err == (
        'Native Pixel Operations identity verification rejected: operations-identity-process-active.\n')
    guidance = module.ERROR_GUIDANCE['retained-pixel-identity-rejected']
    assert 'launchctl bootout user/' in guidance and 'Existing native Pixel state' not in guidance


@pytest.mark.parametrize('result', [1, 127, -9])
def test_sudo_failure_is_not_reported_as_invalid_existing_state(monkeypatch, result):
    monkeypatch.setattr(module.subprocess, 'run',
        lambda *args, **kw: SimpleNamespace(returncode=result))
    with pytest.raises(ValueError, match='native-identity-authorization-required'):
        module.retained_identity_only()
    guidance = module.ERROR_GUIDANCE['native-identity-authorization-required']
    assert 'sudo -v' in guidance and 'same terminal' in guidance


@pytest.mark.parametrize('error', [OSError('missing'), subprocess.TimeoutExpired('sudo', 60)])
def test_identity_verifier_unavailable_fails_closed(monkeypatch, error):
    def run(*args, **kw):
        raise error
    monkeypatch.setattr(module.subprocess, 'run', run)
    with pytest.raises(ValueError, match='native-identity-verification-unavailable'):
        module.retained_identity_only()


@pytest.mark.parametrize('noninteractive,dryrun,prompt', [
    ('false', 'false', True), ('true', 'false', False),
    ('false', 'true', False), ('true', 'true', False)])
def test_shell_preflight_prompt_policy(noninteractive, dryrun, prompt):
    source = (ROOT / 'installers/macos/install-macos.sh').read_text()
    start = source.index('    _pixel_install_args=(--install-dir')
    stop = source.index('    ENABLE_HERMES=false', start)
    block = source[start:stop].replace('/usr/bin/python3', 'fixture_python')
    script = '''
set -eu
LIB_DIR=/fixture; INSTALL_DIR=/fixture/ods
fixture_python() { printf '%s\n' "$@"; }
''' + f'NON_INTERACTIVE={noninteractive}; DRY_RUN={dryrun}\n' + block
    result = subprocess.run(['bash'], input=script, text=True, capture_output=True, check=True)
    assert ('--prompt-for-sudo' in result.stdout.splitlines()) == prompt
    assert '--preflight-only' in result.stdout.splitlines()


@pytest.mark.parametrize('installed', [True, False])
@pytest.mark.parametrize('fault', [None, 'no-brew', 'version', 'path'])
def test_orbstack_multicall_uses_unlinked_standalone_cli(monkeypatch, installed, fault):
    orb = '/Applications/OrbStack.app/Contents/MacOS/xbin/docker-tools'
    selected = '/opt/homebrew/Cellar/docker/29.8.1/bin/docker'
    calls = []
    monkeypatch.setattr(module.shutil, 'which', lambda name: None if fault == 'no-brew' else '/opt/homebrew/bin/brew')
    def resolve(path, **kwargs):
        if str(path).endswith('xbin/docker'):
            return Path(orb)
        return Path('/tmp/docker' if fault == 'path' else selected)
    monkeypatch.setattr(Path, 'resolve', resolve)
    monkeypatch.setattr(Path, 'is_file', lambda path: installed)
    def command(argv, **kwargs):
        calls.append(argv)
        if '--prefix' in argv:
            return '/opt/homebrew/opt/docker'
        if 'install' in argv:
            assert argv == ['/opt/homebrew/bin/brew', 'install', '--formula', '--skip-link', 'docker']
            return ''
        assert argv == [selected, '--version']
        return 'bad version' if fault == 'version' else 'Docker version 29.8.1, build fixture'
    monkeypatch.setattr(module, 'command', command)
    if fault:
        with pytest.raises(ValueError, match='native-orbstack-standalone-docker'):
            module.native_docker_binary('/Applications/OrbStack.app/Contents/MacOS/xbin/docker')
    else:
        assert module.native_docker_binary('/Applications/OrbStack.app/Contents/MacOS/xbin/docker') == selected
        assert sum('install' in argv for argv in calls) == int(not installed)


def test_ordinary_docker_binary_does_not_provision_another_cli(tmp_path, monkeypatch):
    binary = tmp_path / 'docker'
    binary.touch()
    monkeypatch.setattr(module, 'command', lambda *a, **k: pytest.fail('must not provision'))
    assert module.native_docker_binary(binary) == str(binary.resolve())


@pytest.mark.parametrize('fault', [None, 'no-webui', 'ref', 'compose', 'context', 'remote', 'compose-command', 'project', 'services', 'node', 'pull', 'inspect', 'image', 'probe', 'prepare', 'activate'])
def test_initial_installer_connects_resolved_stack_and_native_activation(tmp_path, monkeypatch, fault):
    install_dir = tmp_path / 'ODS with spaces'
    (install_dir / 'data').mkdir(parents=True)
    files = [install_dir / relative for relative in ('docker-compose.base.yml', *module.FRAGMENTS)]
    for path in files:
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text('fixture')
    binary = tmp_path / 'docker'
    binary.touch()
    socket = tmp_path / 'socket'
    socket.touch()
    monkeypatch.delenv('DOCKER_HOST', raising=False)
    monkeypatch.setenv('DOCKER_CONTEXT', 'inherited-context')
    monkeypatch.setenv('DOCKER_TLS_VERIFY', '1')
    monkeypatch.setenv('DOCKER_CERT_PATH', '/unused-certificates')
    monkeypatch.setattr(module, 'preflight', lambda path, **kw: Path(path))
    monkeypatch.setattr(module.shutil, 'which', lambda name: str(binary))
    def node_tools():
        if fault == 'node':
            raise OSError('private-node-path')
        return '/node', '/npm'
    monkeypatch.setattr(module, 'node_tools', node_tools)
    events = []
    def command(argv, **kwargs):
        argv = list(map(str, argv))
        if 'context' in argv:
            events.append('context')
            if fault == 'context': raise ValueError('private-context-error')
            return json.dumps([{'Endpoints': {'docker': {'Host': 'tcp://remote:2375' if fault == 'remote' else 'unix://' + str(socket)}}}])
        assert kwargs['env']['DOCKER_HOST'] == 'unix://' + str(socket)
        assert not {'DOCKER_CONTEXT', 'DOCKER_TLS_VERIFY', 'DOCKER_CERT_PATH'} & kwargs['env'].keys()
        if 'compose' in argv:
            events.append('compose')
            if fault == 'compose-command': raise subprocess.TimeoutExpired(['private-argument'], 1)
            assert argv[argv.index('--project-directory') + 1] == str(install_dir)
            services = ('dashboard-api', 'model-router') if fault == 'no-webui' else (
                'dashboard-api', 'model-router', 'open-webui')
            return json.dumps({'name': 'INVALID!' if fault == 'project' else 'ods-fixture',
                'services': {} if fault == 'services' else dict.fromkeys(services, {})})
        if 'pull' in argv:
            events.append('pull')
            if fault == 'pull': raise ValueError('native-installer-command-failed')
            return ''
        if 'inspect' in argv:
            events.append('image')
            if fault == 'inspect': return 'private-invalid-json'
            return json.dumps([{'Id': 'sha256:' + 'a' * 64, 'Architecture': 'amd64' if fault == 'image' else 'arm64', 'Os': 'linux'}])
        assert 'run' in argv and '--read-only' in argv and '--network' in argv
        events.append('probe')
        if fault == 'probe': raise ValueError('probe-failed')
        return ''
    monkeypatch.setattr(module, 'command', command)
    def prepare(**kwargs):
        events.append('prepare')
        assert kwargs['compose_project'] == 'ods-fixture'
        assert 'license_authorized' not in kwargs
        assert kwargs['ingress_image'] == 'sha256:' + 'a' * 64
        assert kwargs['native_home'] == install_dir / 'data/pixel-native/home'
        if fault == 'prepare': raise ValueError('prepare-failed')
    def activate(**kwargs):
        events.append('activate')
        assert kwargs['compose_files'] == files
        assert kwargs['configure_stack'] is True
        if fault == 'activate': raise ValueError('activate-failed')
    monkeypatch.setattr(module, 'helper', lambda name: SimpleNamespace(prepare=prepare, activate=activate))
    def run():
        return module.install(install_dir=install_dir, ods_source=install_dir,
            compose_files=[] if fault == 'compose' else files[:1],
            ref='invalid' if fault == 'ref' else module.DEFAULT_REF)
    if fault and fault != 'no-webui':
        with pytest.raises((ValueError, OSError, subprocess.SubprocessError)) as caught: run()
        expected = {
            'ref': 'installation-inputs', 'compose': 'installation-inputs',
            'context': 'docker-context', 'remote': 'docker-context',
            'compose-command': 'base-compose-config', 'project': 'base-compose-config',
            'services': 'base-compose-config', 'node': 'native-node-tools',
            'pull': 'ingress-image-download', 'inspect': 'ingress-image-inspect',
            'image': 'ingress-image-inspect', 'probe': 'ingress-runtime-probe',
            'prepare': 'native-preparation', 'activate': 'native-activation',
        }
        assert caught.value._ods_install_phase == expected[fault]
        if fault not in ('prepare', 'activate'):
            assert not (install_dir / 'data/pixel-native').exists()
    else:
        assert run() == install_dir / 'data/pixel-native/preparation'
        assert events == ['context', 'compose', 'pull', 'image', 'probe', 'prepare', 'activate']


@pytest.mark.parametrize('phase', ['ingress-image-download', 'ingress-runtime-probe'])
@pytest.mark.parametrize('failure', ['exit', 'timeout', 'missing'])
def test_early_command_failure_names_phase_without_receipts_or_private_output(
        tmp_path, monkeypatch, capsys, phase, failure):
    install_dir = tmp_path / 'ods'
    install_dir.mkdir()
    private = 'secret-canary-command-output'
    if failure == 'missing':
        argv = [str(tmp_path / private)]
    else:
        program = ('import time; time.sleep(10)' if failure == 'timeout' else
            'import sys; print(' + repr(private) + '); print(' + repr(private) +
            ', file=sys.stderr); sys.exit(23)')
        argv = [sys.executable, '-c', program]
    def fail(**kwargs):
        with module.installation_phase(phase):
            module.command(argv, timeout=0.05 if failure == 'timeout' else 10)
    monkeypatch.setattr(module, 'install', fail)
    monkeypatch.setattr(module.sys, 'argv', ['pixel-native-install.py',
        '--install-dir', str(install_dir), '--ods-source', str(install_dir)])
    assert module.main() == 1
    output = capsys.readouterr()
    assert output.out == ''
    assert '[phase:' + phase + ']' in output.err
    assert 'preparation has not started; its receipts may not exist yet' in output.err
    assert private not in output.err and str(tmp_path) not in output.err
    assert not list(install_dir.iterdir())


def test_phase_retains_typed_health_diagnostics(monkeypatch, capsys):
    compose = module.helper('compose')
    states = {name: {'state': 'running', 'health': 'healthy'} for name in compose.SERVICES}
    states['pixel-workspace-preview'] = {'state': 'restarting', 'health': 'unhealthy'}
    error = compose.NativeHealthTimeout(states)
    def fail(**kwargs):
        with module.installation_phase('native-activation'):
            raise error
    monkeypatch.setattr(module, 'install', fail)
    monkeypatch.setattr(module.sys, 'argv', ['pixel-native-install.py',
        '--install-dir', '/unused', '--ods-source', '/unused'])
    assert module.main() == 1
    output = capsys.readouterr().err
    assert '[phase:native-activation]' in output
    assert '[native-compose-health-timeout]' in output
    assert 'pixel-workspace-preview=restarting/unhealthy' in output
    assert 'preparation has not started' not in output


@pytest.mark.parametrize('phase', ['secret-canary-phase', ['ingress-image-download']])
def test_unrecognized_phase_metadata_never_crosses_output_boundary(monkeypatch, capsys, phase):
    error = ValueError('secret-canary-error')
    error._ods_install_phase = phase
    def fail(**kwargs):
        raise error
    monkeypatch.setattr(module, 'install', fail)
    monkeypatch.setattr(module.sys, 'argv', ['pixel-native-install.py',
        '--install-dir', '/unused', '--ods-source', '/unused'])
    assert module.main() == 1
    output = capsys.readouterr().err
    assert 'secret-canary' not in output
    assert '[phase:' not in output


def test_main_shell_routes_pixel_only_after_base_launch_and_before_flag_persistence():
    script = (ROOT / 'installers/macos/install-macos.sh').read_text()
    assert '--pixel)' in script and '--no-pixel)' in script
    assert script.index('--preflight-only') < script.index('# PHASE 1')
    launch = script.index('"$LIB_DIR/pixel-native-install.py" "${_pixel_install_args[@]}"')
    assert script.index('compose_exit="${PIPESTATUS[0]}"') < launch
    save = 'echo "${COMPOSE_FLAGS[*]}" > "${INSTALL_DIR}/.compose-flags"'
    # The base stack is saved before it starts; Pixel's fragments only after it.
    base_launch = script.index('/usr/bin/python3 "$INSTALL_DIR/installers/macos/lib/dashboard-private-state.py"')
    assert script.index(save) < base_launch < script.index('compose_exit="${PIPESTATUS[0]}"') < launch
    assert 'launch --operation install --install-dir "$INSTALL_DIR" --flags="${COMPOSE_FLAGS[*]}"' in script
    assert launch < script.rindex(save)
    shared = (ROOT / 'installers/phases/06-directories.sh').read_text()
    source_contract = (ROOT / 'installers/lib/pixel-integration.sh').read_text()
    assert 'ODS_PIXEL_BUNDLED_REF' in shared
    assert module.DEFAULT_REF in source_contract


@pytest.mark.parametrize('outcome', ['activated', 'failed-before-activation', 'failed-during-activation'])
def test_saved_compose_flags_cover_pixel_containers_after_a_failed_step(tmp_path, outcome):
    script = (ROOT / 'installers/macos/install-macos.sh').read_text()
    start = script.index('    if $ENABLE_PIXEL; then\n        ai "Preparing native Pixel')
    stop = script.index('\n', script.index('    echo "${COMPOSE_FLAGS[*]}" > "${INSTALL_DIR}/.compose-flags"', start))
    block = script[start:stop].replace('/usr/bin/python3', 'fixture_python')
    base = '-f docker-compose.base.yml -f installers/macos/docker-compose.macos.yml'
    (tmp_path / '.compose-flags').write_text(base + '\n')
    shell = f'''set -euo pipefail
INSTALL_DIR={tmp_path}; LIB_DIR=/fixture; ENABLE_PIXEL=true
ODS_LOG_FILE="$INSTALL_DIR/install.log"
COMPOSE_FLAGS=({base}); _pixel_install_args=(--install-dir "$INSTALL_DIR")
ai() {{ :; }}; ai_ok() {{ :; }}; ai_err() {{ :; }}
fixture_python() {{
    printf 'native activation {outcome}\\n'
    case {outcome} in
        activated) return 0 ;;
        failed-before-activation) return 1 ;;
        failed-during-activation)
            mkdir -p "$INSTALL_DIR/data/pixel-native/preparation"
            printf '{{"status":"error"}}\\n' > "$INSTALL_DIR/data/pixel-native/preparation/activation.json"
            return 1 ;;
    esac
}}
''' + block + '\n'
    result = subprocess.run(['bash'], input=shell, text=True, capture_output=True)
    assert result.returncode == (0 if outcome == 'activated' else 1), result.stderr
    assert (tmp_path / 'install.log').read_text() == f'native activation {outcome}\n'
    fragments = ('-f extensions/services/pixel-model-relay/compose.yaml.disabled'
        ' -f extensions/services/pixel-edge/compose.yaml.disabled'
        ' -f installers/macos/pixel-native.compose.yaml.disabled')
    saved = (tmp_path / '.compose-flags').read_text().strip()
    # Without an activation journal no Pixel container was started and its
    # .env bindings may be missing, so the fragments must not be recorded.
    assert saved == (base if outcome == 'failed-before-activation' else base + ' ' + fragments)


@pytest.mark.parametrize('pixel', ['true', 'false'])
def test_core_feature_selection_keeps_pixel_dependencies_without_heavy_services(pixel, tmp_path):
    script = (ROOT / 'installers/macos/install-macos.sh').read_text()
    start = script.index('if ! $NON_INTERACTIVE && ! $ALL_FEATURES && ! $DRY_RUN; then')
    stop = script.index('ai "Features:"', start)
    resolver_start = script.index('_macos_resolve_support_services() {')
    resolver_stop = script.index('\n}', resolver_start) + 2
    shell = '''set -eu
NON_INTERACTIVE=true; ALL_FEATURES=false; DRY_RUN=false
CLOUD_MODE=false; ENABLE_RECOMMENDED=false
ENABLE_HERMES=false; ENABLE_APE=false
ENABLE_PERPLEXICA=false; ENABLE_VOICE=false; ENABLE_RAG=false; ENABLE_WORKFLOWS=false
ENABLE_OPENCODE=false; OPENCODE_ENABLE_EXPLICIT=false; OPENCODE_DISABLE_EXPLICIT=false
OPENCODE_DISABLE_SELECTED=false
ENABLE_OPEN_WEBUI=false; WEBUI_RETAINED=""; WEBUI_ENABLE_EXPLICIT=false; WEBUI_DISABLE_EXPLICIT=false
ENABLE_ODS_PROXY=false
read_env_value() { printf '\\n'; }
ai_err() { printf '%s\\n' "$*" >&2; }
''' + script[resolver_start:resolver_stop] + '\nENABLE_PIXEL=' + pixel + '\n' + script[start:stop] + '''
printf '%s %s %s %s %s %s %s' "$ENABLE_RECOMMENDED" "$ENABLE_LITELLM" "$ENABLE_SEARXNG" "$ENABLE_HERMES" "$ENABLE_VOICE" "$ENABLE_RAG" "$ENABLE_WORKFLOWS"
'''
    result = subprocess.run(['bash'], input=shell, capture_output=True, text=True, check=True,
        env={**os.environ, 'SOURCE_ROOT': str(ROOT), 'INSTALL_DIR': str(tmp_path)})
    assert result.stdout == 'false true false false false false false'


@pytest.mark.parametrize('mode', ['direct', 'volta', 'brew', 'missing-brew', 'bad-brew'])
def test_node_selection_uses_native_executable_and_qualified_npm(tmp_path, monkeypatch, mode):
    node, npm, shim = [tmp_path / name for name in ('node', 'npm', 'volta-shim')]
    for path in (node, npm, shim): path.touch()
    npm_link = tmp_path / 'npm-link'
    npm_link.symlink_to(shim)
    tools = {'node': str(node), 'npm': str(npm_link if mode == 'volta' else npm),
        'volta': '/volta', 'brew': None if mode == 'missing-brew' else '/brew'}
    monkeypatch.setattr(module.shutil, 'which', tools.get)
    events = []
    installed = []
    def command(argv, **kwargs):
        argv = list(map(str, argv))
        events.append(argv)
        if argv[0] == '/brew':
            if argv[1] == 'install':
                installed.append(True)
                return ''
            return str(tmp_path)
        if argv[0] == '/volta':
            assert argv == ['/volta', 'which', 'npm']
            return str(npm)
        if '-p' in argv:
            valid = mode in ('direct', 'volta') or (bool(installed) and mode != 'bad-brew')
            return json.dumps({'platform': 'darwin', 'arch': 'arm64' if valid else 'x64',
                'major': 24, 'execPath': str(node)})
        if argv[-1] == '--version':
            assert argv[0] == str(npm)
            assert kwargs['env']['PATH'].startswith(str(node.parent) + ':')
            return '11.0.0'
        raise AssertionError(argv)
    # The brew prefix exposes npm under bin, as a real Homebrew installation does.
    (tmp_path / 'bin').mkdir()
    (tmp_path / 'bin/npm').symlink_to(npm)
    monkeypatch.setattr(module, 'command', command)
    if mode in ('missing-brew', 'bad-brew'):
        with pytest.raises(ValueError): module.node_tools()
    else:
        assert module.node_tools() == (node, npm)
    assert bool(installed) == (mode in ('brew', 'bad-brew'))


@pytest.mark.parametrize('state', ['absent', 'existing', 'broken-link'])
def test_base_reinstall_stops_before_changing_a_native_installation(tmp_path, state):
    native = tmp_path / 'data/pixel-native'
    native.parent.mkdir()
    if state == 'existing':
        native.mkdir()
        (native / 'owner-data').write_text('keep exactly')
    elif state == 'broken-link':
        native.symlink_to(tmp_path / 'missing')
    script = (ROOT / 'installers/macos/install-macos.sh').read_text()
    start = script.index('if ! $PREFLIGHT_ONLY && ! $ENABLE_PIXEL && [[ -e "${INSTALL_DIR}/data/pixel-native"')
    stop = script.index('\nif $ENABLE_PIXEL && ! $PREFLIGHT_ONLY; then', start)
    assert stop < script.index('ods_prepare_install_log "$ODS_LOG_FILE" || exit 1')
    shell = 'set -euo pipefail\nai_err() { echo "$*" >&2; }\nai() { echo "$*"; }\n' + script[start:stop] + '\nprintf reached-base-install\n'

    def run(preflight_only):
        return subprocess.run(['bash'], input=shell, text=True, capture_output=True,
            env={**os.environ, 'ENABLE_PIXEL': 'false', 'PREFLIGHT_ONLY': preflight_only,
                 'INSTALL_DIR': str(tmp_path)})

    def assert_native_unchanged():
        if state == 'existing': assert (native / 'owner-data').read_text() == 'keep exactly'
        elif state == 'broken-link': assert native.is_symlink()
        else: assert not os.path.lexists(native)

    result = run('false')
    if state == 'absent':
        assert result.returncode == 0 and result.stdout == 'reached-base-install'
    else:
        assert result.returncode != 0 and 'reached-base-install' not in result.stdout
        assert 'Existing native Pixel installation detected' in result.stderr
    assert_native_unchanged()

    # get-ods.sh --force runs --preflight-only while the installation it will
    # replace, including native Pixel state its candidate uninstaller retires,
    # is still on disk, so that mode skips this tree-state guard. It must still
    # change nothing: it exits after Phase 1, before hardware detection and
    # before the native Pixel installer can run.
    result = run('true')
    assert result.returncode == 0 and result.stdout == 'reached-base-install'
    assert_native_unchanged()
    preflight_exit = script.index(
        'if $PREFLIGHT_ONLY; then\n    ai_ok "Preflight passed; no changes were made."\n    exit 0\nfi\n')
    assert preflight_exit < script.index('# PHASE 2 -- HARDWARE DETECTION')
    assert preflight_exit < script.index('if ! /usr/bin/python3 "$LIB_DIR/pixel-native-install.py"')


# Run native retirement contracts in the existing cross-platform lifecycle CI
# lane; retain the standalone suite for focused operator validation.
_retirement_spec = importlib.util.spec_from_file_location('native_retirement_contracts',
    ROOT / 'tests/test_macos_pixel_native_uninstall.py')
_retirement_tests = importlib.util.module_from_spec(_retirement_spec)
_retirement_spec.loader.exec_module(_retirement_tests)
RetirementSelection = _retirement_tests.RetirementSelection


# Collect polling regressions in the existing macOS installer CI entrypoint.
# The standalone file remains available for focused operator validation.
_health_poll_spec = importlib.util.spec_from_file_location('native_health_poll_contracts',
    ROOT / 'tests/test_macos_pixel_health_poll.py')
_health_poll_contracts = importlib.util.module_from_spec(_health_poll_spec)
_health_poll_spec.loader.exec_module(_health_poll_contracts)
test_transient_timeout_then_healthy = _health_poll_contracts.test_transient_timeout_then_healthy
test_persistent_timeout_stops_at_90 = _health_poll_contracts.test_persistent_timeout_stops_at_90
test_late_healthy_response_rejected = _health_poll_contracts.test_late_healthy_response_rejected
test_valid_ndjson = _health_poll_contracts.test_valid_ndjson
test_rejected_outputs = _health_poll_contracts.test_rejected_outputs
test_nonzero_returncode_rejected = _health_poll_contracts.test_nonzero_returncode_rejected