#!/usr/bin/env python3
"""Report ungated X access, agent sessions outside the harness, and installed tool drift."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import shlex
import subprocess
import sys

if 'vendor_check' not in globals():
    sys.path.insert(0, str(Path(__file__).resolve().parent))
    from skills_vendor_integrity import vendor_check

DEFAULT_LAUNCHERS = ['launch.sh', 'lane-session', 'run.sh', 'agent_executor.py',
                     '~/.local/bin/claude', '~/.local/bin/codex']


def command(argv, errors, optional=False):
    try:
        result = subprocess.run(argv, capture_output=True, text=True, timeout=30)
        if result.returncode:
            if optional and any(s in result.stderr.lower() for s in ('no server running', 'error connecting')):
                return ''
            raise ValueError('exit {}'.format(result.returncode))
        return result.stdout
    except (OSError, ValueError, subprocess.SubprocessError) as exc:
        errors.append('{}: {}'.format(' '.join(argv[:2]), type(exc).__name__))
        return ''


def ps_rows(text):
    rows = {}
    for line in text.splitlines():
        match = re.match(r'^\s*(\d+)\s+(\d+)\s+(.+)$', line)
        if match:
            pid, ppid, cmd = match.groups()
            rows[int(pid)] = {'pid': int(pid), 'ppid': int(ppid), 'command': cmd}
    return rows


def words(cmd):
    try:
        return shlex.split(cmd)
    except ValueError:
        return cmd.split()


def is_agent(cmd):
    tokens = words(cmd)
    if not tokens:
        return False
    executable = Path(tokens[0]).name
    if executable in ('claude', 'codex'):
        return True
    # Node-based CLIs have node as argv[0], followed by the CLI's script.
    if executable in ('node', 'bun', 'python', 'python3'):
        return any(Path(t).name in ('claude', 'codex', 'claude.js', 'codex.js') or
                   t.endswith('/claude-code/cli.js') for t in tokens[1:3])
    return False


def process_path(text):
    match = re.search(r'(?:^|\s)PATH=(.*?)(?=\s+[A-Za-z_][A-Za-z_0-9]*=|$)', text.strip())
    return match.group(1) if match else None


def digest(path):
    h = hashlib.sha256()
    with Path(path).open('rb') as stream:
        for chunk in iter(lambda: stream.read(65536), b''):
            h.update(chunk)
    return h.hexdigest()


def expand(value):
    return str(Path(value).expanduser())


def shell_paths(errors):
    shells = []
    for mode in ('-lc', '-ic'):
        resolved = command(['zsh', mode, 'whence -p xurl'], errors).strip().splitlines()
        path = command(['zsh', mode, 'print -r -- "$PATH"'], errors).strip().splitlines()
        shells.append({'shell': 'zsh ' + mode,
                       'xurl': str(Path(resolved[-1]).resolve()) if resolved else None,
                       'path': path[-1] if path else None})
    return shells


def path_xurls(paths, errors):
    """Inventory every executable xurl, including ones shadowed by the wrapper."""
    directories = set()
    for path in paths:
        if path is None:
            continue
        for directory in path.split(os.pathsep):
            if not Path(directory).is_absolute():
                errors.append('relative PATH entry cannot be inspected: ' + repr(directory))
                continue
            directories.add(os.path.abspath(directory))
    found = []
    for directory in sorted(directories):
        candidate = Path(directory) / 'xurl'
        if candidate.is_file() and os.access(candidate, os.X_OK):
            found.append({'path': str(candidate), 'resolved': str(candidate.resolve())})
    return found


def registry_sessions(path):
    """Registry JSON: a list of session names, or {sessions: [name | {tmux_session: name}]}.

    A lane-root directory is also supported: its lanes/*/SESSION.json files use the same format.
    """
    path = Path(path).expanduser()
    if path.is_dir():
        return [name for p in sorted(path.glob('lanes/*/SESSION.json')) for name in registry_sessions(p)]
    data = json.loads(path.read_text())
    entries = data.get('sessions', [data] if 'tmux_session' in data else []) if isinstance(data, dict) else data
    if not isinstance(entries, list):
        raise ValueError('lane registry sessions must be a list')
    out = []
    for item in entries:
        name = item.get('tmux_session') if isinstance(item, dict) else item
        if not isinstance(name, str) or not name:
            raise ValueError('lane registry entry needs a tmux session name')
        out.append(name)
    return out


def process_cwd(pid, errors):
    path = Path('/proc/{}/cwd'.format(pid))
    if path.exists():
        return str(path.resolve())
    output = command(['lsof', '-a', '-p', str(pid), '-d', 'cwd', '-Fn'], errors)
    paths = [line[1:] for line in output.splitlines() if line.startswith('n/')]
    if not paths:
        errors.append('cannot inspect cwd for pid={}'.format(pid))
        return None
    return paths[0]


def skill_inventory(settings, cwds):
    """Read skill names and vendor markers on this host, without loading skill code."""
    if not isinstance(settings, dict):
        raise ValueError('skills must be an object')
    denied = settings.get('denied', [])
    allowed = settings.get('allowed_dirs', [])
    if not isinstance(denied, list) or not all(isinstance(n, str) and n for n in denied):
        raise ValueError('skills.denied must be a list of names')
    if not isinstance(allowed, list) or not all(isinstance(n, str) and n for n in allowed):
        raise ValueError('skills.allowed_dirs must be a list of directories')
    allowed = [Path(p).expanduser() for p in allowed]
    if any(not p.is_absolute() for p in allowed):
        raise ValueError('skills.allowed_dirs must be absolute or home-relative')
    allowed = [p.resolve() for p in allowed]
    roots = {Path.home() / agent / 'skills' for agent in ('.claude', '.codex', '.agents')}
    roots.update(Path(cwd) / '.claude/skills' for cwd in cwds)
    inventory, packs, bad, seen = [], [], [], set()

    def issue(path, detail):
        bad.append({'check': 'skills', 'subject': str(path), 'detail': detail})

    def fail(exc):
        issue(exc.filename or 'skill directory', 'unreadable: ' + type(exc).__name__)

    for root in sorted(roots):
        if not root.exists():
            if root.is_symlink():
                issue(root, 'broken skill directory link')
            continue
        if not root.is_dir():
            issue(root, 'skill location is not a directory')
            continue
        for current, dirs, files in os.walk(root, followlinks=True, onerror=fail):
            path = Path(current)
            real = path.resolve()
            duplicate = real in seen
            if duplicate:
                dirs[:] = []
            seen.add(real)
            if path.name in denied or 'SKILL.md' in files:
                name = path.name
                names = {name}
                if 'SKILL.md' in files:
                    try:
                        with (path / 'SKILL.md').open(encoding='utf-8') as stream:
                            head = stream.read(8192)
                        match = re.search(r'^name:\s*[\"\x27]?([^\s\"\x27]+)', head, re.MULTILINE)
                        if match:
                            names.add(match.group(1))
                    except (OSError, UnicodeError) as exc:
                        issue(path, 'unreadable skill name: ' + type(exc).__name__)
                inventory.append({'path': str(path), 'names': sorted(names)})
                for name in sorted(names.intersection(denied)):
                    issue(path, 'denied skill: ' + name)
            if '.skills-vendor.json' in files:
                row = {'path': str(path), 'ok': False}
                if not any(real == a or a in real.parents for a in allowed):
                    issue(path, 'vendored pack outside skills.allowed_dirs')
                try:
                    manifest = vendor_check(path)
                    row.update(ok=True, commit=manifest['commit'])
                except (OSError, ValueError, KeyError, TypeError) as exc:
                    issue(path, 'installed pack check failed: ' + str(exc))
                packs.append(row)
    return {'roots': [str(r) for r in sorted(roots)], 'directories': inventory,
            'packs': packs, 'findings': bad}


def collect(cfg):
    """Read-only host collector. The same source runs locally or via ssh python3."""
    errors = []
    processes = ps_rows(command(['ps', '-axo', 'pid,ppid,command'], errors))
    listing = command(['tmux', 'list-sessions', '-F', '#{session_name}'], errors, optional=True)
    panes_text = command(['tmux', 'list-panes', '-a', '-F',
                          '#{session_name}\t#{pane_pid}\t#{pane_start_command}'], errors, optional=True)
    panes = {}
    for line in panes_text.splitlines():
        parts = line.split('\t', 2)
        if len(parts) == 3 and parts[1].isdigit():
            panes[int(parts[1])] = (parts[0], parts[2])
    sessions = [{'name': s, 'processes': []} for s in listing.splitlines() if s]
    cwd_text = command(['tmux', 'list-panes', '-a', '-F',
                        '#{session_name}\t#{pane_current_path}'], errors, optional=True)
    cwds = {line.split('\t', 1)[1] for line in cwd_text.splitlines()
            if '\t' in line and line.split('\t', 1)[1].startswith('/')}
    session_map = {s['name']: s for s in sessions}
    agents, paths = [], []
    shells = shell_paths(errors)
    paths.extend(shell['path'] for shell in shells)
    for pid, row in processes.items():
        if not is_agent(row['command']):
            continue
        chain, seen, current, session, pane_command = [], set(), pid, None, None
        while current in processes and current not in seen:
            seen.add(current)
            parent = processes[current]
            chain.append(parent['command'])
            if session is None and current in panes:
                session, pane_command = panes[current]
            current = parent['ppid']
        env = command(['ps', 'eww', '-p', str(pid)], errors)
        path = process_path(env)
        paths.append(path)
        agent = dict(row, session=session, chain=chain, path_present=path is not None,
                     pane_command=pane_command)
        agent['cwd'] = process_cwd(pid, errors)
        if agent['cwd']:
            cwds.add(agent['cwd'])
        agents.append(agent)
        if session:
            session_map.setdefault(session, {'name': session, 'processes': []})['processes'].append(row)
    listing = command(['launchctl', 'list'], errors)
    prefix = cfg.get('label_prefix', '')
    jobs = []
    if not prefix:
        errors.append('label_prefix is missing')
    else:
        for line in listing.splitlines():
            parts = line.split(None, 2)
            if len(parts) == 3 and parts[2].startswith(prefix):
                jobs.append({'label': parts[2], 'pid': parts[0], 'exit': parts[1]})
    stamp = None
    stamp_path = cfg.get('harness_stamp')
    try:
        if not stamp_path:
            raise ValueError('harness_stamp is missing')
        stamp = json.loads(Path(stamp_path).expanduser().read_text())['commit']
    except (OSError, ValueError, KeyError, TypeError):
        errors.append('harness install stamp is missing or unreadable')
    installed = []
    install_map = cfg.get('install_map') or {}
    if not install_map:
        errors.append('install_map is empty')
    # PATH must resolve to actual repo gate code, even if the operator omitted it from the map.
    wrapper = Path(cfg.get('wrapper', '~/.local/bin/xurl')).expanduser().absolute()
    targets = {str(Path(target).expanduser().resolve()): source for source, target in install_map.items()}
    targets[str(wrapper.resolve())] = 'rstack/tools/xurl'
    targets[str(wrapper.with_name('xurl-policy').resolve())] = 'rstack/tools/xurl-policy'
    for target, source in sorted(targets.items()):
        row = {'source': source, 'target': target, 'sha256': None}
        try:
            row['sha256'] = digest(target)
        except OSError:
            pass
        installed.append(row)
    registry = []
    if cfg.get('lane_registry'):
        try:
            registry = registry_sessions(cfg['lane_registry'])
        except (OSError, ValueError, TypeError):
            errors.append('lane registry is unreadable')
    return {'sessions': list(session_map.values()), 'agents': agents, 'launchd': jobs,
            'harness_commit': stamp, 'installed': installed,
            'wrapper': str(wrapper.resolve()), 'wrapper_path': str(wrapper),
            'shells': shells, 'xurls': path_xurls(paths, errors),
            'launchers': [expand(p) if '/' in p else p for p in cfg.get('launchers', DEFAULT_LAUNCHERS)],
            'skills': skill_inventory(cfg.get('skills', {}), cwds),
            'registry_sessions': registry, 'errors': errors}


def compare_with_repo(snapshot, repo):
    """Only the controller's checkout is a source, even for SSH-host installs."""
    repo = Path(repo).expanduser()
    for tool in snapshot['installed']:
        try:
            expected = digest(repo / tool['source'])
        except OSError:
            expected = None
        tool['repo_sha256'] = expected
        tool['matches'] = expected is not None and tool['sha256'] == expected
    errors = snapshot['errors']
    snapshot['origin_main_tree'] = command(
        ['git', '-C', str(repo), 'rev-parse', '--verify', 'origin/main:harness'], errors).strip()
    stamp = snapshot['harness_commit']
    snapshot['harness_tree'] = ''
    if isinstance(stamp, str) and re.fullmatch(r'[0-9a-fA-F]{40,64}', stamp):
        snapshot['harness_tree'] = command(
            ['git', '-C', str(repo), 'rev-parse', '--verify', stamp + ':harness'], errors).strip()


def executable_positions(tokens, depth=0):
    """Executable/script positions, also inside the remote runner's sh -c command."""
    if not tokens or depth > 3:
        return []
    positions = tokens[:1]
    executable = Path(tokens[0]).name
    shells = ('sh', 'bash', 'zsh')
    if executable not in shells + ('python', 'python3'):
        return positions
    for i, token in enumerate(tokens[1:], 1):
        if token.startswith('-'):
            if token == '-c' or (executable in shells and not token.startswith('--') and 'c' in token[1:]):
                if executable in shells and i + 1 < len(tokens):
                    # ps may render the command string without its surrounding quotes.
                    nested = words(tokens[i + 1]) if ' ' in tokens[i + 1] else tokens[i + 1:]
                    positions.extend(executable_positions(nested, depth + 1))
                return positions
            if token == '-m':
                return positions
            continue
        positions.append(token)
        break
    return positions


def launcher_command(cmd, launchers):
    # tmux reports some pane commands quoted whole ("exec ~/.local/bin/codex ..."), 11-14 live run.
    cmd = cmd.strip()
    if len(cmd) > 1 and cmd[0] == cmd[-1] == '"':
        cmd = cmd[1:-1]
    elif cmd.startswith('"') and cmd.count('"') == 1:
        cmd = cmd[1:]
    cmd = cmd.strip()
    if cmd.startswith('exec '):
        cmd = cmd[5:]
    for token in executable_positions(words(cmd)):
        for launcher in launchers:
            if (expand(token) == expand(launcher) if '/' in launcher else Path(token).name == launcher):
                return True
    return False


def codex_args(cmd):
    tokens = words(cmd)
    if tokens and Path(tokens[0]).name == 'codex':
        return tokens[1:]
    if tokens and Path(tokens[0]).name in ('node', 'bun'):
        for i in (1, 2):
            if i < len(tokens) and Path(tokens[i]).name in ('codex', 'codex.js'):
                return tokens[i + 1:]
    return []


def app_server_command(cmd):
    return codex_args(cmd)[:1] == ['app-server']


def attached_codex(cmd):
    args = codex_args(cmd)
    # `resume` may follow the global flags (codex --remote SOCK -c ... -m MODEL resume ID), 11-14 live run.
    return 'resume' in args and any(t == '--remote' or t.startswith('--remote=') for t in args)


def launched(agent, launchers, registered):
    if agent.get('session') in registered:
        return True
    if any(launcher_command(cmd, launchers) for cmd in agent['chain']):
        return True
    # A wrapper can exec/reparent the app-server, disappearing from ps. tmux retains
    # the pane's original command; only app-server sessions/attachments may use it.
    app_server = any(app_server_command(cmd) for cmd in agent['chain'])
    attached = attached_codex(agent.get('command', ''))
    return bool(agent.get('session') and (app_server or attached) and
                launcher_command(agent.get('pane_command') or '', launchers))


def findings(snapshot):
    bad = [{'check': 'collection', 'subject': 'host', 'detail': e} for e in snapshot['errors']]
    bad.extend(snapshot.get('skills', {}).get('findings', []))
    for agent in snapshot['agents']:
        if app_server_command(agent.get('command', '')):
            continue  # the Codex app-server daemon hosts sessions; the sessions attached to it are checked
        subject = 'pid={} session={}'.format(agent['pid'], agent.get('session') or '(outside tmux)')
        if not launched(agent, snapshot['launchers'], snapshot['registry_sessions']):
            bad.append({'check': 'launcher', 'subject': subject, 'detail': 'no harness launcher or registered tmux session'})
    for shell in snapshot['shells']:
        if shell['xurl'] != snapshot['wrapper']:
            bad.append({'check': 'path', 'subject': shell['shell'],
                        'detail': 'xurl resolves to {}; expected {}'.format(
                            shell['xurl'] or '(missing/unresolvable)', snapshot['wrapper'])})
    for executable in snapshot['xurls']:
        if executable['path'] != snapshot['wrapper_path']:
            bad.append({'check': 'path', 'subject': executable['path'], 'detail': 'another xurl exists on PATH'})
    if not snapshot['origin_main_tree'] or snapshot['harness_tree'] != snapshot['origin_main_tree']:
        bad.append({'check': 'harness', 'subject': 'install stamp',
                    'detail': 'installed={} harness tree={} origin/main:harness={}'.format(
                        snapshot['harness_commit'] or '(missing)', snapshot['harness_tree'] or '(unreadable)',
                        snapshot['origin_main_tree'] or '(unreadable)')})
    for tool in snapshot['installed']:
        if not tool['matches']:
            bad.append({'check': 'tools', 'subject': tool['target'], 'detail': 'differs from repo ' + tool['source']})
    return bad


def remote_collect(host, cfg):
    # Constant collector code + JSON data, never a command supplied by the registry. No files written
    # remotely; -B suppresses bytecode writes. Only read-only subprocesses in collect() can run.
    source = Path(__file__).resolve().read_text()
    integrity = Path(__file__).resolve().with_name('skills_vendor_integrity.py').read_text()
    code = integrity + '\n' + source.rsplit("if __name__ == '__main__':", 1)[0] + '\nprint(json.dumps(collect(json.loads(sys.argv[1]))))\n'
    remote = shlex.join(['python3', '-B', '-c', code, json.dumps(cfg)])
    result = subprocess.run(['ssh', '-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=yes',
                             '-o', 'ConnectTimeout=10', '--', host, remote],
                            capture_output=True, text=True, check=True, timeout=120)
    return json.loads(result.stdout)


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--config', default=os.environ.get('FLEET_LINT_CONFIG',
                        str(Path.home() / '.config/rstack/fleet-lint.json')))
    parser.add_argument('--json', action='store_true')
    parser.add_argument('--alert', action='store_true')
    args = parser.parse_args(argv)
    result = {'hosts': [], 'findings': []}
    try:
        cfg = json.loads(Path(args.config).expanduser().read_text())
        hosts = cfg.get('hosts')
        if hosts is None:
            hosts = [{'name': 'local'}, {'name': 'ssh', 'ssh': cfg.get('ssh_host') or os.environ.get('FLEET_LINT_SSH_HOST')}]
        if not isinstance(hosts, list) or not hosts:
            raise ValueError('hosts must be a nonempty list')
        for host in hosts:
            name = host['name']
            settings = dict(cfg, **host)
            try:
                if host.get('ssh'):
                    snapshot = remote_collect(host['ssh'], settings)
                elif name == 'ssh':
                    raise ValueError('configure ssh_host or FLEET_LINT_SSH_HOST')
                else:
                    snapshot = collect(settings)
                compare_with_repo(snapshot, cfg['repo'])
                result['hosts'].append({'name': name, **snapshot})
                result['findings'].extend(dict(host=name, **row) for row in findings(snapshot))
            except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError) as exc:
                result['findings'].append({'host': name, 'check': 'collection', 'subject': 'host',
                                           'detail': 'collection failed: {}'.format(type(exc).__name__)})
    except (OSError, ValueError, KeyError, TypeError) as exc:
        result['findings'].append({'host': 'config', 'check': 'collection', 'subject': args.config,
                                   'detail': 'unreadable configuration: {}'.format(type(exc).__name__)})
    if args.json:
        print(json.dumps(result, sort_keys=True))
    else:
        for host in result['hosts']:
            print('HOST {}'.format(host['name']))
            for shell in host['shells']:
                print('  XURL {} {}'.format(shell['shell'], shell['xurl'] or '(missing/unresolvable)'))
            for executable in host['xurls']:
                print('  XURL {}'.format(executable['path']))
            for session in host['sessions']:
                print('  TMUX {}'.format(session['name']))
                for proc in session['processes']:
                    print('    pid={} {}'.format(proc['pid'], proc['command']))
            for skill in host.get('skills', {}).get('directories', []):
                print('  SKILL {} {}'.format(','.join(skill['names']), skill['path']))
            for pack in host.get('skills', {}).get('packs', []):
                print('  SKILL PACK {} check={}'.format(pack['path'], 'OK' if pack['ok'] else 'FAIL'))
            for agent in host['agents']:
                if not agent['session']:
                    print('  OUTSIDE TMUX pid={} {}'.format(agent['pid'], agent['command']))
            for job in host['launchd']:
                print('  LAUNCHD {} pid={} exit={}'.format(job['label'], job['pid'], job['exit']))
        for row in result['findings']:
            print('{host}\t{check}\t{subject}\t{detail}'.format(**row))
    if args.alert:
        try:
            counts = {}
            for row in result['findings']:
                counts[row['check']] = counts.get(row['check'], 0) + 1
            summary = 'fleet-lint: {} findings on {} hosts ({})'.format(len(result['findings']),
                len(result['hosts']), ', '.join('{}={}'.format(k, v) for k, v in sorted(counts.items())) or 'clear')
            subprocess.run(['tell-general', 'fyi', summary], check=True, timeout=30)
        except (OSError, subprocess.SubprocessError):
            print('fleet-lint: alert failed', file=sys.stderr)
            return 1
    return int(bool(result['findings']))


if __name__ == '__main__':
    sys.exit(main())
