#!/usr/bin/env python3
# agent-sec-audit version 1.0 | Python 3.8+ | MIT, © 2026 Anonyfox e. K.
# Reads agent instruction/config files in Downloads, Desktop, temp and --scan roots;
# user Codex/Claude config; persistence definitions; npm IOC indexes; selected URL
# environment keys. Runs only npm root -g and crontab -l. Never loads agent code.
# Writes nothing without --fix or the separate explicit --write-baseline option.
# --fix moves stray instruction files and backs up config before narrow edits.
"""Deterministic local triage. A finding requires review; a clean scan is not proof.

No network calls. Symlinks, secret filenames and browser/credential directories
are skipped. Files over 2 MiB and scan trees over depth 8 / 50,000 files generate
coverage errors. Baselines approve exact MCP definitions by SHA-256 and hosts;
review these manually before use. High-risk MCP commands cannot be allowlisted.
"""
import argparse
import ast
import datetime
import hashlib
import json
import os
from pathlib import Path
import plistlib
import re
import shlex
import shutil
import stat
import subprocess
import sys
import time
from urllib.parse import urlsplit

VERSION = '1.0'
MAX_BYTES = 2 * 1024 * 1024
SKIP = {'.git', '.ssh', '.secrets', 'secrets', 'credentials', 'profiles',
        'Default', 'Profile 1', 'agent-sec-quarantine', '__pycache__'}
NAMES = {'AGENTS.md', 'AGENTS.override.md', 'CLAUDE.md', 'CLAUDE.local.md',
         '.cursorrules', '.mcp.json'}
INDICATORS = re.compile(r'config\.toml|settings(?:\.local)?\.json|ANTHROPIC_BASE_URL|'
                        r'mcp_servers|npx|npm\s+install|curl\s*\|\s*(?:ba)?sh|'
                        r'dangerously-[\w-]*|launchctl', re.I)
URL_KEYS = {'ANTHROPIC_BASE_URL',
            'ANTHROPIC_FOUNDRY_BASE_URL', 'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY'}
CURL_PIPE = re.compile(r'\bcurl\b[^\n|]*\|\s*(?:(?:/usr)?/bin/)?(?:ba)?sh\b', re.I)
HIGH_COMMANDS = {'launchctl', 'sh', 'bash', 'zsh', 'curl', 'wget', 'osascript'}
PERSIST = re.compile(r'\b(?:npm|npx|node|curl)\b|/tmp/|\b(?:ba|z)?sh\s+(?:[^\n]*\s)?-[a-z]*c[a-z]*\b', re.I)
SOURCES = {
    'instruction': 'https://developers.openai.com/codex/guides/agents-md/',
    'codex-mcp': 'https://developers.openai.com/codex/config-reference/',
    'codex-url': 'https://developers.openai.com/codex/config-reference/',
    'claude-url': 'https://code.claude.com/docs/en/env-vars',
    'claude-helper': 'https://code.claude.com/docs/en/settings-reference',
    'claude-mcp': 'https://code.claude.com/docs/en/mcp',
    'persistence-launchd': 'https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html',
    'persistence-systemd': 'https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html',
    'persistence-autostart': 'https://specifications.freedesktop.org/autostart/latest/',
    'persistence-cron': 'https://man7.org/linux/man-pages/man1/crontab.1.html',
    'ioc-function-color': 'https://forever.security/blog/hijacking-ai-agents-via-downloads-folder/'
}


def safe(value):
    """Redact paths/names too: credentials can appear in arbitrary filenames."""
    value = str(value)
    value = re.sub(r'(?i)(?:sk-|gh[pousr]_|xox[baprs]-)[A-Za-z0-9_-]+', '[REDACTED]', value)
    value = re.sub(r'(?i)((?:token|password|secret|api[_-]?key)[=: /_-]+)[^\s/]+', r'\1[REDACTED]', value)
    value = re.sub(r'(?<![A-Za-z0-9])[A-Za-z0-9_+=-]{32,}(?![A-Za-z0-9])', '[REDACTED]', value)
    return ''.join(c if c.isprintable() else '?' for c in value)[:600]


def executable(command):
    if not isinstance(command, str):
        return '(invalid command type)'
    try:
        parts = shlex.split(str(command))
        if parts and '=' in parts[0]:
            return '(environment assignment; value withheld)'
        name = Path(parts[0]).name if parts else '(remote)'
    except ValueError:
        name = '(unparseable)'
    return safe(name)


def host(value):
    if not isinstance(value, str):
        return ''
    try:
        parsed = urlsplit(str(value) if '://' in str(value) else '//' + str(value))
        return (parsed.hostname or '').lower().rstrip('.')
    except ValueError:
        return ''


def digest(value):
    return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':')).encode()).hexdigest()


def sections(text):
    """Small conservative fallback: sections plus scalar/array values; no execution.

    Unsupported/multiline TOML is an error, rather than a silently clean result.
    tomllib handles full TOML on Python 3.11+; fallback covers normal MCP blocks.
    """
    out, current = {}, {}
    out[''] = current
    for raw in text.splitlines():
        line = raw.strip()
        if not line or line.startswith('#'):
            continue
        match = re.match(r'^\[([^\[\]]+)\]\s*(?:#.*)?$', line)
        if match:
            key = '.'.join(part.strip().strip('"\'') for part in match.group(1).split('.'))
            current = out.setdefault(key, {})
            continue
        match = re.match(r'^([\w"\'-]+)\s*=\s*(.*)$', line)
        if not match:
            raise ValueError('unsupported TOML; use Python 3.11+ for full TOML support')
        key, raw_value = match.groups()
        # Strip inline comments outside quotes via a small lexical pass.
        quote, escaped, kept = None, False, []
        for char in raw_value:
            if char == '#' and quote is None:
                break
            kept.append(char)
            if char == '\\' and quote == '"' and not escaped:
                escaped = True
                continue
            if char in ('"', "'") and not escaped:
                quote = None if quote == char else (char if quote is None else quote)
            escaped = False
        raw_value = ''.join(kept).strip()
        try:
            if raw_value in ('true', 'false'):
                value = raw_value == 'true'
            elif raw_value.startswith(('[', '"', "'")):
                value = ast.literal_eval(raw_value)
            elif re.fullmatch(r'[+-]?[\d_.]+', raw_value):
                value = raw_value
            elif raw_value.startswith('{'):
                # Inline tables may contain env secrets; fail rather than miss keys.
                raise ValueError('inline TOML table requires Python 3.11+')
            else:
                raise ValueError('unsupported TOML value')
        except (SyntaxError, ValueError) as exc:
            raise ValueError('unsupported TOML; use Python 3.11+') from exc
        current[key.strip('"\'')] = value
    return out


def parse_toml(text):
    try:
        import tomllib
    except ImportError:
        return sections(text)
    data = tomllib.loads(text)
    result = {}

    def flatten(obj, prefix=''):
        result[prefix] = {k: v for k, v in obj.items() if not isinstance(v, dict)}
        for key, value in obj.items():
            if isinstance(value, dict):
                flatten(value, prefix + '.' + key if prefix else key)
    flatten(data)
    return result


def section_parts(header):
    """Split dotted TOML paths without splitting quoted server names."""
    def decode(value):
        value = value.strip()
        if len(value) >= 2 and value[0] == value[-1] == "'":
            return value[1:-1]
        if len(value) >= 2 and value[0] == value[-1] == '"':
            return ast.literal_eval(value)
        return value
    parts, current, quote, escaped = [], [], None, False
    for char in header:
        if char == '.' and quote is None:
            parts.append(decode(''.join(current)))
            current = []
            continue
        current.append(char)
        if char == '\\' and quote == '"' and not escaped:
            escaped = True
            continue
        if char in ('"', "'") and not escaped:
            quote = None if quote == char else (char if quote is None else quote)
        escaped = False
    parts.append(decode(''.join(current)))
    return tuple(parts)


def mcp_tables(text):
    try:
        import tomllib
    except ImportError:
        # Parse each original header separately so quoted dots keep their identity.
        entries, active, body = {}, None, []
        blocks = []
        for line in text.splitlines():
            match = re.match(r'^\s*\[([^\[\]]+)\]\s*(?:#.*)?$', line)
            if match:
                if active is not None:
                    blocks.append((active, body))
                active, body = section_parts(match.group(1)), []
            elif active is not None:
                body.append(line)
        if active is not None:
            blocks.append((active, body))
        for parts, lines in blocks:
            if len(parts) < 2 or parts[0] != 'mcp_servers':
                continue
            values = sections('\n'.join(lines))['']
            entry = entries.setdefault(parts[1], {})
            for component in parts[2:]:
                entry = entry.setdefault(component, {})
            entry.update(values)
        return entries
    value = tomllib.loads(text).get('mcp_servers', {})
    if not isinstance(value, dict):
        raise ValueError('invalid MCP table')
    return value


class Audit:
    def __init__(self, args):
        self.args = args
        self.home = Path(os.environ.get('HOME', str(Path.home()))).absolute()
        self.findings, self.errors, self.inventory = [], [], []
        self.actions, self.seen = {}, set()
        self.state = {'version': 1, 'mcp_servers': [], 'hosts': []}
        self.baseline = {'mcp_servers': [], 'hosts': []}
        if args.baseline:
            try:
                candidate = json.loads(Path(args.baseline).read_text())
                if not isinstance(candidate, dict) or not isinstance(candidate.get('mcp_servers', []), list) or not isinstance(candidate.get('hosts', []), list):
                    raise ValueError('invalid baseline shape')
                self.baseline = candidate
            except (OSError, ValueError, RecursionError):
                self.errors.append('Cannot read baseline JSON (values withheld).')
        self.roots = [self.home / 'Downloads', self.home / 'Desktop', Path('/tmp')]
        for value in (os.environ.get('TMPDIR'), os.environ.get('XDG_DOWNLOAD_DIR')):
            if value:
                self.roots.append(Path(value.replace('$HOME', str(self.home))).expanduser())
        xdg = Path(os.environ.get('XDG_CONFIG_HOME', str(self.home / '.config')))
        user_dirs = self.read(xdg / 'user-dirs.dirs')
        if user_dirs:
            match = re.search(r'^XDG_DOWNLOAD_DIR="([^"]+)"', user_dirs, re.M)
            if match:
                self.roots.append(Path(match.group(1).replace('$HOME', str(self.home))))
        self.roots.extend(Path(p).expanduser().absolute() for p in args.scan)
        self.xdg = xdg

    def error(self, path, kind='Unreadable or unsupported file'):
        message = '{}: {}'.format(kind, safe(path))
        if message not in self.errors:
            self.errors.append(message)

    def read(self, path, binary=False):
        path = Path(path)
        try:
            # Never follow a symlink, including any parent directory.
            if any(p.is_symlink() for p in [path] + list(path.parents)):
                return None
            st = path.stat()
            if not stat.S_ISREG(st.st_mode):
                return None
            if st.st_size > MAX_BYTES:
                self.error(path, 'Skipped file over 2 MiB')
                return None
            return path.read_bytes() if binary else path.read_text(encoding='utf-8', errors='replace')
        except FileNotFoundError:
            return None
        except OSError:
            self.error(path)
            return None

    def add(self, check, severity, path, what, why, todo, action=None):
        finding = {'id': check, 'severity': severity, 'path': safe(path),
                   'what': safe(what), 'why': safe(why), 'what_to_do': safe(todo)}
        self.findings.append(finding)
        if action:
            self.actions[len(self.findings) - 1] = (Path(path), action)

    def walk(self, root):
        if not root.exists() or root.is_symlink():
            return
        if root.is_file():
            yield root
            return
        count = 0
        for directory, dirs, files in os.walk(str(root), followlinks=False,
                                               onerror=lambda e: self.error(root, 'Directory listing failed')):
            parent = Path(directory)
            depth = len(parent.relative_to(root).parts)
            dirs[:] = [d for d in dirs if d not in SKIP and not (parent / d).is_symlink()
                       and not re.search(r'(?i)secret|credential|browser|chromium|firefox|auth', d)]
            if depth >= 8 and dirs:
                self.error(parent, 'Depth limit reached (8)')
                dirs[:] = []
            for name in files:
                count += 1
                if count > 50000:
                    self.error(root, 'File limit reached (50000)')
                    return
                if re.search(r'(?i)auth|secret|credential|token|password|\.pem$|\.key$', name):
                    continue
                path = parent / name
                if not path.is_symlink():
                    yield path

    def command(self, argv):
        # Fixed commands only, no shell. Ignore caller PATH to avoid planted binaries.
        for directory in ('/usr/bin', '/bin', '/usr/local/bin', '/opt/homebrew/bin'):
            path = Path(directory) / argv[0]
            if path.is_file():
                try:
                    proc = subprocess.run([str(path)] + argv[1:], stdout=subprocess.PIPE,
                                          stderr=subprocess.PIPE, timeout=8, check=False,
                                          env={'HOME': str(self.home), 'PATH': '/usr/bin:/bin:/usr/local/bin:/opt/homebrew/bin'})
                    return proc.returncode, proc.stdout.decode('utf-8', 'replace')[:MAX_BYTES]
                except (OSError, subprocess.TimeoutExpired):
                    self.error(argv[0], 'Read-only listing failed')
                    return 2, ''
        self.inventory.append({'listing': argv[0], 'status': 'not installed; skipped'})
        return 127, ''

    def url(self, check, path, key, value, defaults, action=None):
        if not isinstance(value, str):
            self.error(path, 'Invalid URL value type (value withheld)')
            return
        hostname = host(value)
        if not hostname:
            if value:
                self.add(check, 'high', path, key + ' has an unparseable destination (value withheld)',
                         'Cannot verify routing destination.', 'Inspect this key locally; restore the expected endpoint.', action)
            return
        if hostname not in self.state['hosts']:
            self.state['hosts'].append(hostname)
        if hostname not in defaults and hostname not in self.baseline.get('hosts', []):
            self.add(check, 'high', path, '{} host={}'.format(key, safe(hostname)),
                     ('Current Codex ignores provider URL keys in project-local config; review planted intent.' if check == 'codex-url' and Path(path).parent.name == '.codex' and Path(path) != Path(os.environ.get('CODEX_HOME', str(self.home / '.codex'))) / 'config.toml' else 'Traffic or credentials may be routed through this host.'),
                     'Verify ownership; restore expected routing and rotate exposed tokens if unauthorized.', action)

    def mcp(self, check, path, name, entry, action=None):
        if not isinstance(entry, dict):
            self.error(path, 'Invalid MCP entry')
            return
        command, args = entry.get('command', ''), entry.get('args', [])
        if (not isinstance(command, str) or not isinstance(args, list)
                or any(not isinstance(arg, str) for arg in args)
                or not isinstance(entry.get('enabled', True), bool)):
            self.error(path, 'Invalid MCP command, arguments or enabled type (values withheld)')
            return
        try:
            fingerprint = {'name': str(name), 'command': executable(command), 'definition_sha256': digest(entry)}
        except (TypeError, ValueError, RecursionError):
            self.error(path, 'Unsupported MCP value type (values withheld)')
            return
        if fingerprint not in self.state['mcp_servers']:
            self.state['mcp_servers'].append(fingerprint)
        cmdline = str(command) + ' ' + ' '.join(map(str, args if isinstance(args, list) else [args]))
        risky = executable(command) in HIGH_COMMANDS or bool(re.search(r'npm\s+install|\bcurl\b|(?:/tmp/|\$TMPDIR)', cmdline))
        self.inventory.append({'type': 'mcp', 'name': safe(name), 'command': executable(command), 'path': safe(path), 'enabled': entry.get('enabled', True)})
        if entry.get('url'):
            self.url(check, path, 'MCP url', entry['url'], set())
        if risky or fingerprint not in self.baseline.get('mcp_servers', []):
            self.add(check, 'high' if risky else 'medium', path,
                     'MCP {} command={} (arguments withheld)'.format(safe(name), executable(command)),
                     'MCP definitions can start local programs in future agent sessions.',
                     'Review the full command locally; disable an unexpected server before starting the agent.', action)

    def codex(self, path):
        text = self.read(path)
        if text is None:
            return
        try:
            parsed = parse_toml(text)
        except (ValueError, RecursionError):
            self.error(path, 'Cannot parse TOML; use Python 3.11+ for full TOML')
            return
        try:
            for name, entry in mcp_tables(text).items():
                self.mcp('codex-mcp', path, name, entry, ('mcp', name))
        except (ValueError, TypeError, RecursionError):
            self.error(path, 'Cannot parse MCP table')
        for section, values in parsed.items():
            for key in ('chatgpt_base_url', 'openai_base_url', 'base_url'):
                if key in values and (key != 'base_url' or section.startswith('model_providers.')):
                    # Project provider keys are currently ignored, but still expose planted intent.
                    self.url('codex-url', path, section + '.' + key if section else key,
                             values[key], {'api.openai.com', 'chatgpt.com', 'chat.openai.com'})

    def claude(self, path):
        text = self.read(path)
        if text is None:
            return
        try:
            data = json.loads(text)
            if not isinstance(data, dict):
                raise ValueError()
        except (ValueError, RecursionError):
            self.error(path, 'Cannot parse JSON')
            return
        env = data.get('env', {})
        if not isinstance(env, dict):
            self.error(path, 'Invalid env block')
        else:
            for key in URL_KEYS:
                if key in env:
                    self.url('claude-url', path, key, env[key], {'api.anthropic.com'}, ('env', key))
        if data.get('apiKeyHelper') and not isinstance(data['apiKeyHelper'], str):
            self.error(path, 'Invalid apiKeyHelper type (value withheld)')
        elif data.get('apiKeyHelper'):
            self.add('claude-helper', 'info', path,
                     'apiKeyHelper command={} (arguments withheld)'.format(executable(data['apiKeyHelper'])),
                     'This helper obtains credentials by executing a command.', 'Review the full helper command locally.')
        servers = data.get('mcpServers', {})
        if isinstance(servers, dict):
            for name, entry in servers.items():
                self.mcp('claude-mcp', path, name, entry)
        else:
            self.error(path, 'Invalid mcpServers block')
        # Claude local-scope MCP entries can be stored per project in ~/.claude.json.
        projects = data.get('projects', {})
        if isinstance(projects, dict):
            for project in projects.values():
                if isinstance(project, dict) and isinstance(project.get('mcpServers'), dict):
                    for name, entry in project['mcpServers'].items():
                        self.mcp('claude-mcp', path, name, entry)

    def persistence(self, path, check):
        text = self.read(path)
        if text is None:
            return
        label, command = '', text
        if path.suffix == '.plist':
            try:
                data = plistlib.loads(self.read(path, binary=True))
                if not isinstance(data, dict) or not isinstance(data.get('ProgramArguments', []), list):
                    raise ValueError('invalid plist shape')
                label = str(data.get('Label', ''))
                command = str(data.get('Program', '')) + ' ' + ' '.join(map(str, data.get('ProgramArguments', [])))
            except (ValueError, TypeError, plistlib.InvalidFileException):
                self.error(path, 'Cannot parse plist')
                return
        severity = 'high' if label == 'com.ptools.setup' or 'com.ptools.setup' in text else ('medium' if PERSIST.search(command) else 'info')
        if severity != 'info' or time.time() - path.stat().st_mtime < self.args.days * 86400:
            quoted = shlex.quote(str(path))
            if check == 'persistence-launchd':
                domain = 'system' if path.parent.name == 'LaunchDaemons' else 'gui/$(id -u)'
                manual = 'Preserve evidence first. Manual unload after review: launchctl bootout ' + domain + ' ' + quoted
            elif check == 'persistence-systemd':
                manual = 'Preserve evidence first. Manual disable after review: systemctl --user disable --now ' + shlex.quote(path.name)
            else:
                manual = 'Preserve evidence first. Manual disable after review: mv ' + quoted + ' ' + shlex.quote(str(path) + '.disabled')
            self.add(check, severity, path, 'Persistence definition' + ('; com.ptools.setup label' if label == 'com.ptools.setup' else '; suspicious command pattern' if severity == 'medium' else '; recently modified'),
                     'This definition can run programs at login or on a schedule.', manual)

    def ioc(self, path, text=None):
        if text is None:
            text = self.read(path)
        if text is not None and 'function-color' in text:
            self.add('ioc-function-color', 'high', path, 'function-color package name found',
                     'This package name is an IOC in the Forever Security report; a text reference needs context.',
                     'Treat the machine as compromised; rotate tokens. Inspect locally: ' + 'less ' + shlex.quote(str(path)))

    def run(self):
        configs = {Path(os.environ.get('CODEX_HOME', str(self.home / '.codex'))) / 'config.toml'}
        settings = {self.home / '.claude/settings.json', self.home / '.claude.json'}
        if sys.platform == 'darwin':
            settings.add(Path('/Library/Application Support/ClaudeCode/managed-settings.json'))
            settings.update(Path('/Library/Application Support/ClaudeCode/managed-settings.d').glob('*.json'))
        else:
            settings.add(Path('/etc/claude-code/managed-settings.json'))
            settings.update(Path('/etc/claude-code/managed-settings.d').glob('*.json'))
        for root in self.roots:
            for path in self.walk(root):
                if path in self.seen:
                    continue
                self.seen.add(path)
                is_config = path.name == 'config.toml' and path.parent.name == '.codex'
                is_settings = path.name.startswith('settings') and path.suffix == '.json' and path.parent.name == '.claude'
                instruction = path.name in NAMES or is_config or is_settings or ('.cursor' in path.parts and 'rules' in path.parts and path.parts.index('rules') == path.parts.index('.cursor') + 1)
                if instruction:
                    text = self.read(path)
                    if text is not None:
                        evidence = []
                        for number, line in enumerate(text.splitlines(), 1):
                            matches = INDICATORS.findall(line)
                            if CURL_PIPE.search(line):
                                matches.append('curl|sh')
                            if matches:
                                evidence.append('L{}: {} [other content withheld]'.format(number, ' … '.join(sorted(set(matches)))))
                            if len(evidence) == 3:
                                break
                        self.add('instruction', 'high' if evidence else 'medium', path,
                                 'Instruction/config in an untrusted scan folder' + ('; ' + '; '.join(evidence) if evidence else ''),
                                 'An agent started here may load local instructions or settings.',
                                 'Read this file locally; quarantine if unexpected.', ('move', None))
                if is_config:
                    configs.add(path)
                if is_settings or path.name == '.mcp.json':
                    settings.add(path)
                if path.name == 'package-lock.json':
                    self.ioc(path)
                if path.name == 'package.json' and path.parent.name == 'function-color' and path.parent.parent.name == 'node_modules':
                    self.add('ioc-function-color', 'high', path, 'node_modules/function-color package directory found',
                             'Package IOC reported by Forever Security.', 'Treat the machine as compromised; rotate tokens. Preserve evidence. Manual removal after review: npm --prefix ' + shlex.quote(str(path.parent.parent.parent)) + ' uninstall function-color --ignore-scripts')
        for path in sorted(configs):
            self.codex(path)
        for path in sorted(settings):
            self.claude(path)
        for key in URL_KEYS:
            if key in os.environ:
                self.url('claude-url', 'current environment', key, os.environ[key], {'api.anthropic.com'})
        persist_roots = [(self.home / 'Library/LaunchAgents', 'persistence-launchd'),
                         (self.xdg / 'systemd/user', 'persistence-systemd'),
                         (Path(os.environ.get('XDG_DATA_HOME', str(self.home / '.local/share'))) / 'systemd/user', 'persistence-systemd'),
                         (self.xdg / 'autostart', 'persistence-autostart')]
        if sys.platform == 'darwin':
            persist_roots.extend((Path(p), 'persistence-launchd') for p in ('/Library/LaunchAgents', '/Library/LaunchDaemons'))
        for root, check in persist_roots:
            for path in self.walk(root):
                if (check.endswith('launchd') and path.suffix == '.plist') or (check.endswith('autostart') and path.suffix == '.desktop') or (check.endswith('systemd') and path.suffix in ('.service', '.timer', '.socket', '.path', '.target', '.mount', '.automount', '.slice', '.scope', '.swap', '.device')):
                    self.persistence(path, check)
        code, cron = self.command(['crontab', '-l'])
        if code == 0:
            for number, line in enumerate(cron.splitlines(), 1):
                if not line.strip() or line.lstrip().startswith('#'):
                    continue
                self.add('persistence-cron', 'high' if 'com.ptools.setup' in line else 'medium' if PERSIST.search(line) else 'info',
                         'user crontab L{}'.format(number), 'Scheduled task (command withheld)',
                         'A user crontab can persist commands.', 'Review and edit manually: crontab -e')
        elif code not in (1, 127):
            self.error('crontab', 'Cannot list user crontab')
        npm_roots = [self.home / '.npm/_npx']
        code, npm = self.command(['npm', 'root', '-g'])
        if code == 0 and npm.strip() and Path(npm.strip()).is_absolute():
            npm_roots.append(Path(npm.strip()))
        elif code not in (0, 127):
            self.error('npm', 'Cannot list global npm root')
        for root in npm_roots:
            for path in self.walk(root):
                if path.name == 'package.json' and path.parent.name == 'function-color':
                    self.add('ioc-function-color', 'high', path, 'function-color package directory found',
                             'Package IOC reported by Forever Security.', ('Treat the machine as compromised; rotate tokens. Preserve evidence. Inspect cached execution package manually: ls -ld ' + shlex.quote(str(path.parent)) if root == self.home / '.npm/_npx' else 'Treat the machine as compromised; rotate tokens. Preserve evidence. Manual global removal after review: npm uninstall -g function-color --ignore-scripts'))
        for path in self.walk(self.home / '.npm/_cacache/index-v5'):
            self.ioc(path)
        if Path('/tmp/ptools').exists():
            self.add('ioc-function-color', 'high', '/tmp/ptools', 'ptools temporary path exists',
                     'Path IOC reported by Forever Security.', 'Treat the machine as compromised; rotate tokens. Inspect manually: ls -ld /tmp/ptools')

    def fix(self):
        if not self.args.yes and not sys.stdin.isatty():
            self.errors.append('--fix requires a TTY or explicit --yes; nothing changed.')
            return
        timestamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')
        changed, moved = [], set()
        for index, (path, action) in self.actions.items():
            if path in moved or not path.exists():
                continue
            finding = self.findings[index]
            if self.args.yes:
                print('Fix: {} {}'.format(action[0], safe(path)), file=sys.stderr)
            if not self.args.yes:
                print('{} {}: {}'.format(finding['severity'].upper(), finding['path'], finding['what']), file=sys.stderr)
                answer = input('Apply {}? [y/N] '.format(action[0]))
                if answer.strip().lower() != 'y':
                    continue
            text = self.read(path)
            if text is None:
                continue
            try:
                if action[0] == 'move':
                    target_dir = self.home / 'agent-sec-quarantine' / timestamp
                    # No overwrite and no symlink traversal in quarantine destination.
                    if any(p.is_symlink() for p in [target_dir] + list(target_dir.parents)):
                        raise OSError('symlink destination')
                    target_dir.mkdir(parents=True, mode=0o700, exist_ok=True)
                    target = target_dir / (digest(str(path))[:12] + '-' + path.name)
                    if target.exists():
                        raise OSError('destination exists')
                    shutil.move(str(path), str(target))
                    moved.add(path)
                else:
                    updated = text
                    if action[0] == 'env':
                        data = json.loads(text)
                        if not isinstance(data, dict) or not isinstance(data.get('env'), dict):
                            raise ValueError('changed settings shape')
                        data['env'].pop(action[1], None)
                        updated = json.dumps(data, indent=2) + '\n'
                    elif action[0] == 'mcp':
                        # Avoid treating section-looking lines inside multiline strings as headers.
                        if '"""' in text or "'''" in text:
                            self.error(path, 'MCP fix requires manual editing for multiline TOML strings')
                            continue
                        lines, in_block = [], False
                        for line in text.splitlines(keepends=True):
                            match = re.match(r'^\s*(\[{1,2})([^\[\]]+)(\]{1,2})', line)
                            if match:
                                parts = section_parts(match.group(2))
                                in_block = len(match.group(1)) == 1 and len(parts) >= 2 and parts[0] == 'mcp_servers' and parts[1] == action[1]
                            lines.append('# agent-sec-quarantine: ' + line if in_block else line)
                        updated = ''.join(lines)
                        parse_toml(updated)
                    if updated == text:
                        self.error(path, 'No supported matching fix; file left unchanged')
                        continue
                    backup = Path(str(path) + '.' + timestamp + '.bak')
                    with backup.open('xb') as handle:
                        os.chmod(str(backup), 0o600)
                        handle.write(text.encode('utf-8'))
                    path.write_text(updated, encoding='utf-8')
                changed.append({'path': safe(path), 'action': action[0]})
            except (OSError, ValueError, TypeError, SyntaxError, RecursionError):
                self.error(path, 'Fix failed; inspect locally')
        self.inventory.append({'fixes': changed})


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--scan', action='append', default=[], metavar='PATH')
    parser.add_argument('--days', type=int, default=14)
    parser.add_argument('--json', action='store_true')
    parser.add_argument('--baseline', metavar='FILE')
    parser.add_argument('--write-baseline', metavar='FILE')
    parser.add_argument('--fix', action='store_true')
    parser.add_argument('--yes', action='store_true')
    parser.add_argument('--version', action='version', version=VERSION)
    args = parser.parse_args(argv)
    if args.days < 0:
        parser.error('--days must be non-negative')
    audit = Audit(args)
    if sys.platform not in ('linux', 'darwin'):
        audit.errors.append('Platform not covered yet; macOS and Linux only.')
    else:
        try:
            audit.run()
        except OSError:
            audit.errors.append('Filesystem changed or became inaccessible during scan; rerun locally.')
    if args.fix:
        audit.fix()
    if args.write_baseline:
        try:
            # Explicit opt-in, exclusive creation: never overwrite another file.
            with open(args.write_baseline, 'x', encoding='utf-8') as handle:
                os.chmod(args.write_baseline, 0o600)
                json.dump(audit.state, handle, indent=2)
                handle.write('\n')
        except OSError:
            audit.errors.append('Cannot create baseline; target must be a new writable file.')
    result = {'version': VERSION, 'findings': audit.findings, 'errors': audit.errors,
              'inventory': audit.inventory, 'counts': {level: sum(f['severity'] == level for f in audit.findings) for level in ('high', 'medium', 'info')}}
    if args.json:
        print(json.dumps(result, indent=2))
    else:
        print('agent-sec-audit 1.0 | local, deterministic review')
        for item in audit.inventory:
            if item.get('type') == 'mcp':
                print('MCP {name}: command={command} | {path}'.format(**item))
        for item in audit.findings:
            print('\n[{severity}] {id}: {path}\n  {what}\n  Why: {why}\n  Do: {what_to_do}'.format(**item))
        for error in audit.errors:
            print('ERROR: ' + error)
        print('\n{} high, {} medium, {} info; {} coverage errors'.format(result['counts']['high'], result['counts']['medium'], result['counts']['info'], len(audit.errors)))
    return 2 if audit.errors else 1 if audit.findings else 0


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