#!/usr/bin/env python3
# Copyright 2026 TrackSec. All rights reserved.
# SPDX-License-Identifier: LicenseRef-TrackSec-Proprietary
#
# GENERATED by scripts/gen_laptop_scan_script.py from Track's discovery collectors;
# do not edit. Published at https://assess.tracksec.io/laptop-scan.py with its SHA-256.
"""Track laptop scan: the AI clients, MCP servers, coding agents' settings and
extensions, local model runtimes and AI browser extensions on THIS machine, as STRUCTURE ONLY.

    python3 laptop-scan.py                 # writes track-laptop-scan.json here
    python3 laptop-scan.py --out FILE      # writes FILE instead
    python3 laptop-scan.py --no-runtimes   # does not probe 127.0.0.1 for model runtimes
    python3 laptop-scan.py --upload        # also sends that file, after showing it and asking
    python3 laptop-scan.py --upload https://assess.tracksec.io/a/<id>   # adds it to that report

What it reads: the configuration files AI clients keep in your home directory, the
settings, rules files, skills, subagents, commands, plugins and hooks of the coding agents
(Claude Code, Codex, Gemini CLI, Cursor, GitHub Copilot CLI) in your home directory and
the projects they list, the model list a runtime publishes on 127.0.0.1, and the
manifests of installed browser extensions. What it writes: client and server names,
transports, command FILE NAMES, argument COUNTS, the capability words found in the
arguments, a remote server's HOST, environment variable NAMES, each coding agent's
permission mode, its permission rules as TOOL NAMES only (Bash(git push) is sent as
Bash(…); a wildcard such as Bash(*) as written), COUNTS of its deny and ask rules,
sandbox and managed-policy switches and COUNTS of hidden characters in its rules files,
each extension's name, kind, the TOOL NAMES it may use, the tool names a hook applies to,
counts, SHA-256 digests and a hook's program FILE NAME and URL HOST, the runtimes and
model names, and the AI browser extensions' ids, names, versions and permissions. It
never writes a path, a value from a configuration file, a file's text, a prompt or a
credential; paths and the machine's name appear only as hashes salted afresh on every
run. Without --upload it
makes no network call except to 127.0.0.1 and sends nothing: read the file it writes,
then upload it at https://assess.tracksec.io/ if you choose to. With --upload it shows
what it found, asks, and only on a yes sends that same file, and nothing else, to the
assessment service over https. Needs Python 3.9 or later and nothing else.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import os
import platform
import re
import secrets
import socket
import sys
import types
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

try:
    import tomllib as _TOMLLIB
except ImportError:  # Python 3.9 and 3.10: a TOML file reads as unreadable
    _TOMLLIB = None
SCHEMA = 'track-laptop-scan/2'

# ── tables baked from packages/compliance/local_agent_discovery.py ──────────

CANDIDATE_PATHS = (
    'Library/Application Support/Claude/claude_desktop_config.json',
    '.config/Claude/claude_desktop_config.json',
    'AppData/Roaming/Claude/claude_desktop_config.json',
    '.claude.json',
    '.claude/settings.json',
    '.cursor/mcp.json',
    '.continue/config.json',
    '.continue/config.yaml',
    '.continue/mcpServers',
    '.codex/config.json',
    '.config/codex/config.json',
    '.codex/config.toml',
    '.codeium/windsurf/mcp_config.json',
    '.windsurf/mcp.json',
    '.config/zed/settings.json',
    'Library/Application Support/Zed/settings.json',
    'AppData/Roaming/Zed/settings.json',
    'Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json',
    '.config/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json',
    'AppData/Roaming/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json',
    '.cline/mcp.json',
    'Library/Application Support/Code/User/globalStorage/rooveterinaryinc.roo-cline/settings/mcp_settings.json',
    '.config/Code/User/globalStorage/rooveterinaryinc.roo-cline/settings/mcp_settings.json',
    'AppData/Roaming/Code/User/globalStorage/rooveterinaryinc.roo-cline/settings/mcp_settings.json',
    'Library/Application Support/Code/User/mcp.json',
    '.config/Code/User/mcp.json',
    'AppData/Roaming/Code/User/mcp.json',
    'Library/Application Support/Code/User/profiles',
    '.config/Code/User/profiles',
    'AppData/Roaming/Code/User/profiles',
    '.copilot/mcp-config.json',
    '.config/goose/config.yaml',
    'AppData/Roaming/Block/goose/config/config.yaml',
    '.aider.conf.yml',
    '.config/JetBrains/mcp.json',
    '.junie/mcp/mcp.json',
    '.gemini/settings.json',
    '.hermes/config.yaml',
    '.openclaw/openclaw.json',
    '.config/librechat/librechat.yaml',
)
CONFIG_FILENAMES = frozenset({
    '.aider.conf.yml',
    '.claude.json',
    'claude_desktop_config.json',
    'cline_mcp_settings.json',
    'config.json',
    'config.jsonc',
    'config.toml',
    'config.yaml',
    'config.yml',
    'librechat.yaml',
    'mcp-config.json',
    'mcp.json',
    'mcp_config.json',
    'mcp_settings.json',
})
_WALK_SUFFIXES = frozenset({
    '.json',
    '.toml',
    '.yaml',
    '.yml',
})
_CLIENT_DIRS = frozenset({
    '.claude',
    '.codeium',
    '.codex',
    '.continue',
    '.cursor',
    '.windsurf',
    'claude',
    'codex',
    'continue',
    'cursor',
    'goose',
    'jetbrains',
    'librechat',
    'rooveterinaryinc.roo-cline',
    'saoudrizwan.claude-dev',
    'windsurf',
    'zed',
})
_PRODUCT_BY_FILENAME = {
    '.aider.conf.yml': 'aider',
    '.claude.json': 'claude_code',
    'claude_desktop_config.json': 'claude_desktop',
    'cline_mcp_settings.json': 'cline',
    'librechat.yaml': 'librechat',
    'mcp_config.json': 'windsurf',
}
_PRODUCT_BY_DIR = {
    '.claude': 'claude_code',
    '.cline': 'cline',
    '.codeium': 'windsurf',
    '.codex': 'codex',
    '.continue': 'continue',
    '.copilot': 'copilot_cli',
    '.cursor': 'cursor',
    '.gemini': 'gemini_cli',
    '.hermes': 'hermes_agent',
    '.junie': 'jetbrains',
    '.openclaw': 'openclaw',
    '.roo': 'roo',
    '.vscode': 'vscode',
    '.windsurf': 'windsurf',
    'JetBrains': 'jetbrains',
    'Zed': 'zed',
    'claude': 'claude_desktop',
    'codex': 'codex',
    'continue': 'continue',
    'cursor': 'cursor',
    'goose': 'goose',
    'jetbrains': 'jetbrains',
    'librechat': 'librechat',
    'rooveterinaryinc.roo-cline': 'roo',
    'saoudrizwan.claude-dev': 'cline',
    'windsurf': 'windsurf',
    'zed': 'zed',
}
_GOOSE_SERVER_TYPES = frozenset({
    'sse',
    'stdio',
    'streamable_http',
})
ARGS_CAPABILITY_WORDS = (
    'filesystem',
    'shell',
    'exec',
    'docker',
    'browser',
)
WRAP_KEPT_COPY_SUFFIX = '.track-original.json'

# ── table baked from packages/compliance/browser_agent_discovery.py ─────────

AGENTIC_EXTENSION_KEYWORDS = (
    'ai agent',
    'ai assistant',
    'ai copilot',
    'ai sidebar',
    'bard',
    'chatbot',
    'chatgpt',
    'claude',
    'comet',
    'copilot',
    'gemini',
    'github copilot',
    'glasp',
    'google ai',
    'gpt for google',
    'gpt-4',
    'harpa',
    'jasper',
    'max ai',
    'maxai',
    'merlin',
    'monica',
    'openai',
    'perplexity',
    'sider',
    'wiseone',
    'you.com',
    'youchat',
)

# ── browser profile roots (scripts/gen_laptop_scan_script.py) ─────────────

BROWSER_ROOTS = {
    'darwin': ('Library/Application Support/Google/Chrome', 'Library/Application Support/Microsoft Edge', 'Library/Application Support/BraveSoftware/Brave-Browser', 'Library/Application Support/Chromium'),
    'linux': ('.config/google-chrome', '.config/microsoft-edge', '.config/BraveSoftware/Brave-Browser', '.config/chromium'),
    'windows': ('AppData/Local/Google/Chrome/User Data', 'AppData/Local/Microsoft/Edge/User Data', 'AppData/Local/BraveSoftware/Brave-Browser/User Data'),
}

# ── the host reader, copied from packages/action_facts/mcp_address.py ───────

from urllib.parse import urlsplit

_DEFAULT_PORTS = {
    'http': 80,
    'https': 443,
}
def _parts(url: object) -> tuple[str, str, int | None, str] | None:
    if not isinstance(url, str) or not url.strip():
        return None
    try:
        parsed = urlsplit(url.strip())
        port = parsed.port
    except ValueError:
        return None
    scheme = (parsed.scheme or "").lower()
    host = (parsed.hostname or "").lower()
    if scheme not in _DEFAULT_PORTS or not host:
        return None
    return scheme, host, port, parsed.path or ""


def url_host(url: object) -> str | None:
    """``host[:port]`` of an http(s) URL with no user info, or ``None``."""
    parts = _parts(url)
    if parts is None:
        return None
    _scheme, host, port, _path = parts
    shown = f"[{host}]" if ":" in host else host
    return f"{shown}:{port}" if port is not None else shown



# ── functions copied from packages/compliance/local_agent_discovery.py ──────

def _strip_json_comments(text: str) -> str:
    """*text* without its ``//`` and ``/* */`` comments, and then without a comma that only
    whitespace separates from the ``}`` or ``]`` after it (a trailing comma), outside strings.
    One function, because the assessment's laptop scan copies it whole
    (``scripts/gen_laptop_scan_script.py``)."""
    out: list[str] = []
    in_string = False
    escaped = False
    i = 0
    while i < len(text):
        ch = text[i]
        nxt = text[i + 1] if i + 1 < len(text) else ""
        if ch == '"' and not escaped:
            in_string = not in_string
        if not in_string and ch == "/" and nxt == "/":
            while i < len(text) and text[i] not in "\r\n":
                i += 1
            continue
        if not in_string and ch == "/" and nxt == "*":
            i += 2
            while i + 1 < len(text) and not (text[i] == "*" and text[i + 1] == "/"):
                i += 1
            i += 2
            continue
        out.append(ch)
        escaped = ch == "\\" and not escaped
        if ch != "\\":
            escaped = False
        i += 1
    text = "".join(out)
    out = []
    in_string = False
    escaped = False
    n = len(text)
    for i, ch in enumerate(text):
        if in_string:
            if escaped:
                escaped = False
            elif ch == "\\":
                escaped = True
            elif ch == '"':
                in_string = False
        elif ch == '"':
            in_string = True
        elif ch == ",":
            j = i + 1
            while j < n and text[j] in " \t\r\n":
                j += 1
            if j < n and text[j] in "}]":
                continue
        out.append(ch)
    return "".join(out)


def _iter_mcp_servers(
    data: dict[str, Any], *, product: str = "", filename: str = "",
) -> list[tuple[str, dict[str, Any]]]:
    """Every MCP server a client's config declares, in each client's own documented key.

    A4-25 (measured: 1 of 8 documented configs' servers found): the scan read only a
    DICT under ``mcpServers``/``mcp_servers``/``mcp``, so it missed —

    * VS Code's ``mcp.json``: "a top-level ``servers`` object"
      (https://code.visualstudio.com/docs/agents/reference/mcp-configuration);
    * Zed's ``settings.json``: ``"context_servers": {…}`` (https://zed.dev/docs/ai/mcp);
    * Continue's YAML: ``mcpServers:`` as a LIST of ``{name, command, args}``
      (https://docs.continue.dev/customize/deep-dives/mcp);
    * Claude Code's local scope: "stored in ~/.claude.json under that project's path"
      — ``projects.<path>.mcpServers`` (https://code.claude.com/docs/en/mcp);
    * Goose's ``extensions:`` with ``cmd``/``args``/``envs``/``uri``
      (https://goose-docs.ai/docs/guides/config-files/).

    A server named twice (the same name in two projects) is reported once. Values are
    never read beyond what ``discover_local_agent_configs`` already keeps: environment
    variable NAMES, never their values.
    """
    found: dict[str, dict[str, Any]] = {}

    def take(name: Any, cfg: Any) -> None:
        if isinstance(cfg, dict) and name not in (None, "") and str(name) not in found:
            found[str(name)] = cfg

    def take_block(block: Any) -> None:
        if isinstance(block, dict):
            for name, cfg in block.items():
                take(name, cfg)
        elif isinstance(block, list):
            for cfg in block:
                if isinstance(cfg, dict):
                    take(cfg.get("name"), cfg)

    for key in ("mcpServers", "mcp_servers", "mcp"):
        if key == "mcp" and product == "openclaw":
            continue  # OpenClaw's "mcp" holds settings; its servers are "mcp.servers"
        take_block(data.get(key))
    if product == "openclaw" and isinstance(data.get("mcp"), dict):
        take_block(data["mcp"].get("servers"))
    if filename.lower() == "mcp.json" or product == "vscode":
        take_block(data.get("servers"))
    take_block(data.get("context_servers"))
    if product == "claude_code" or filename.lower() == ".claude.json":
        projects = data.get("projects")
        if isinstance(projects, dict):
            for project in projects.values():
                if isinstance(project, dict):
                    take_block(project.get("mcpServers"))
    if product == "goose" and isinstance(data.get("extensions"), dict):
        for name, ext in data["extensions"].items():
            if not isinstance(ext, dict) or str(ext.get("type") or "").lower() not in _GOOSE_SERVER_TYPES:
                continue
            env_names = [str(k) for k in (ext.get("env_keys") or []) if isinstance(k, str)]
            if isinstance(ext.get("envs"), dict):
                env_names += [str(k) for k in ext["envs"]]
            take(name, {"command": ext.get("cmd"), "args": ext.get("args") or [],
                        "env": {k: "" for k in env_names}, "url": ext.get("uri")})
    return list(found.items())


def _product_for_path(path: Path) -> str:
    """Identify the product from the config's filename, else from the nearest
    enclosing directory that names one.

    Never substring-matches the whole path: a Cursor config under /Users/claude
    or in a repo named claude-tools belongs to Cursor, and the nearest directory
    is the one that says so.
    """
    product = _PRODUCT_BY_FILENAME.get(path.name.lower())
    if product is not None:
        return product
    for part in reversed(path.parent.parts):
        product = _PRODUCT_BY_DIR.get(part.lower())
        if product is not None:
            return product
    # VS Code's own user directory (``…/Code/User/…``, a profile included). Matched as the
    # PAIR, never on ``Code`` alone: a checkout under ~/code must not become VS Code.
    lowered = [part.lower() for part in path.parent.parts]
    if any(a == "code" and b == "user" for a, b in zip(lowered, lowered[1:])):
        return "vscode"
    return "local_agent_config"


def _server_command(server_cfg: dict[str, Any]) -> str | None:
    command = server_cfg.get("command")
    if isinstance(command, dict):
        # Zed's earlier schema: ``"command": {"path": …, "args": […], "env": {…}}``.
        command = command.get("path")
    return str(command) if command else None


def _server_url(server_cfg: dict[str, Any]) -> str | None:
    # ``httpUrl``: Gemini CLI's streamable HTTP server (https://geminicli.com/docs/tools/mcp-server/).
    url = (server_cfg.get("url") or server_cfg.get("serverUrl") or server_cfg.get("endpoint")
           or server_cfg.get("httpUrl"))
    return str(url) if url else None


def _host_from_url(url: str | None) -> str | None:
    # Host and port only: ``urlparse().netloc`` keeps ``user:token@``, which is the token.
    return url_host(url)


def _is_candidate_file(path: Path) -> bool:
    name = path.name.lower()
    if name.endswith(WRAP_KEPT_COPY_SUFFIX):
        return False
    suffix = path.suffix.lower()
    parts = {part.lower() for part in path.parts}
    return (
        name in CONFIG_FILENAMES
        or name.endswith(".jsonc")
        or (suffix in _WALK_SUFFIXES and bool(_CLIENT_DIRS & parts))
    )


def _expand_paths(paths: list[Path]) -> list[Path]:
    out: list[Path] = []
    for path in paths:
        if path.is_dir():
            for child in path.rglob("*"):
                if child.is_file() and _is_candidate_file(child):
                    out.append(child)
        elif path.exists() or _is_candidate_file(path):
            out.append(path)
    return sorted(set(out), key=lambda p: str(p))


# ── the loopback probe, copied from packages/compliance/local_inference_discovery.py ──

LOOPBACK = '127.0.0.1'
DEFAULT_TIMEOUT = 0.35


@dataclass(frozen=True)
class RuntimeProbe:
    port: int
    runtime: str
    product: str
    #: Endpoint that lists loaded models. Unauthenticated on every runtime here by
    #: default, which is itself part of the finding.
    probe_path: str
    #: Whether the port alone is rare enough to be worth reporting unconfirmed.
    #: False for 8000/8080/3000 — see the calibration note in the module docstring.
    distinctive: bool


LOCAL_RUNTIMES = (
    RuntimeProbe(11434, 'ollama', 'Ollama', '/api/tags', True),
    RuntimeProbe(1234, 'lm_studio', 'LM Studio', '/v1/models', True),
    RuntimeProbe(7860, 'text_generation_webui', 'text-generation-webui', '/v1/models', True),
    RuntimeProbe(8000, 'vllm', 'vLLM', '/v1/models', False),
    RuntimeProbe(8001, 'vllm', 'vLLM', '/v1/models', False),
    RuntimeProbe(8080, 'llama_cpp', 'llama.cpp / LocalAI', '/v1/models', False),
    RuntimeProbe(5000, 'text_generation_webui', 'text-generation-webui', '/v1/models', False),
    RuntimeProbe(3000, 'open_webui', 'Open WebUI', '/api/models', False),
)


class _RefuseRedirects(urllib.request.HTTPRedirectHandler):
    """Answer a 3xx by refusing it rather than by following it.

    Returning ``None`` from ``redirect_request`` is urllib's documented way to
    decline a redirect: the 3xx falls through to the default error handler and
    surfaces as an ``HTTPError`` (a ``URLError`` subclass), which ``_probe_models``
    already treats as "did not answer as an inference API".
    """

    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


_OPENER = urllib.request.build_opener(_RefuseRedirects, urllib.request.ProxyHandler({}))


def _port_open(port: int, *, host: str = LOOPBACK, timeout: float = DEFAULT_TIMEOUT) -> bool:
    try:
        with socket.create_connection((host, port), timeout=timeout):
            return True
    except OSError:
        return False


def _probe_models(port: int, path: str, *, host: str = LOOPBACK,
                  timeout: float = DEFAULT_TIMEOUT) -> list[str] | None:
    """Ask the runtime what it has loaded. ``None`` when it did not answer as an
    inference API — which is what keeps a dev server on :8000 off the board."""
    url = f"http://{host}:{port}{path}"
    try:
        # _OPENER, never urlopen: the default opener follows redirects and proxies,
        # either of which would take this off the fixed loopback address.
        with _OPENER.open(url, timeout=timeout) as response:
            body = json.loads(response.read().decode("utf-8", errors="replace"))
    except (urllib.error.URLError, OSError, ValueError, json.JSONDecodeError):
        return None
    return _model_names(body)


def _model_names(body: Any) -> list[str] | None:
    """Extract model names from the two shapes these runtimes use, and only those.

    Returning ``None`` for an unrecognised shape is what makes the probe a
    *confirmation* rather than a liveness check: any JSON-serving process would
    pass a liveness check.
    """
    if not isinstance(body, dict):
        return None
    # OpenAI-compatible: {"data": [{"id": "..."}]}
    data = body.get("data")
    if isinstance(data, list):
        names = [str(m.get("id") or m.get("name")) for m in data if isinstance(m, dict)]
        return sorted(n for n in names if n and n != "None")
    # Ollama native: {"models": [{"name": "llama3:8b"}]}
    models = body.get("models")
    if isinstance(models, list):
        names = [str(m.get("name") or m.get("model")) for m in models if isinstance(m, dict)]
        return sorted(n for n in names if n and n != "None")
    return None


def scan_local_runtimes(
    *,
    host: str = LOOPBACK,
    timeout: float = DEFAULT_TIMEOUT,
    probes: tuple[RuntimeProbe, ...] = LOCAL_RUNTIMES,
) -> list[dict[str, Any]]:
    """Detected runtimes, each with why it was reported. Pure I/O on loopback."""
    found: list[dict[str, Any]] = []
    for probe in probes:
        if not _port_open(probe.port, host=host, timeout=timeout):
            continue
        models = _probe_models(probe.port, probe.probe_path, host=host, timeout=timeout)
        confirmed = models is not None
        if not confirmed and not probe.distinctive:
            # A common port with nothing confirming it is a dev server until proven
            # otherwise. Reporting it would bury the real findings.
            continue
        found.append({
            "runtime": probe.runtime,
            "product": probe.product,
            "port": probe.port,
            "confirmed": confirmed,
            "models": models or [],
            "reason": (
                f"{probe.product} answered its model-list API on port {probe.port}"
                if confirmed else
                f"port {probe.port} is open and is the default for {probe.product}, "
                "but its model-list API did not respond"
            ),
        })
    return found


# ── the helpers the coding-agent scans import, copied from local_agent_discovery.py ──

PARSE_ERROR_CODES = frozenset({
    'not_a_mapping',
    'not_utf8',
    'unparsable',
    'unreadable',
})
RUNTIME_FAMILY = 'mcp_runtime'
PRODUCT_FAMILY = {
    'aider': 'mcp_runtime',
    'claude_code': 'mcp_runtime',
    'claude_desktop': 'mcp_runtime',
    'cline': 'cursor_windsurf_continue',
    'codex': 'mcp_runtime',
    'continue': 'cursor_windsurf_continue',
    'copilot_cli': 'mcp_runtime',
    'cursor': 'cursor_windsurf_continue',
    'gemini_cli': 'mcp_runtime',
    'goose': 'mcp_runtime',
    'hermes_agent': 'mcp_runtime',
    'jetbrains': 'cursor_windsurf_continue',
    'librechat': 'mcp_runtime',
    'openclaw': 'mcp_runtime',
    'roo': 'cursor_windsurf_continue',
    'vscode': 'cursor_windsurf_continue',
    'windsurf': 'cursor_windsurf_continue',
    'zed': 'cursor_windsurf_continue',
}
_PATH_HASH_CHARS = frozenset({
    '0',
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    'a',
    'b',
    'c',
    'd',
    'e',
    'f',
})


def _product_name(product: str) -> str:
    return {
        "claude_desktop": "Claude Desktop",
        "claude_code": "Claude Code",
        "cursor": "Cursor",
        "continue": "Continue",
        "codex": "Codex",
        "windsurf": "Windsurf",
        "zed": "Zed",
        "cline": "Cline",
        "roo": "Roo Code",
        "goose": "Goose",
        "aider": "Aider",
        "jetbrains": "JetBrains AI",
        "librechat": "LibreChat",
        "vscode": "VS Code",
        "copilot_cli": "GitHub Copilot CLI",
        "gemini_cli": "Gemini CLI",
        "hermes_agent": "Hermes Agent",
        "openclaw": "OpenClaw",
    }.get(product, "Local Agent Config")


def product_name(product: str) -> str:
    """The product's own name (``claude_code`` reads "Claude Code"): the label a place carries."""
    return _product_name(product)


def product_family(product: str) -> str:
    """The card a product's findings belong to; an unattributed config is a runtime one."""
    return PRODUCT_FAMILY.get(product, RUNTIME_FAMILY)


def config_path_hash(path: str | Path) -> str:
    """The hash this collector gives a config file's path (``config_path_hash`` on the agent).

    The resolved path when the file exists, the path as given otherwise, so a scan that
    reads a file and one that only names it hash it the same way.
    """
    p = Path(path).expanduser()
    return _hash(str(p.resolve() if p.exists() else p))


def agent_entity_id(product: str, path_hash_or_path: str | Path) -> str:
    """The id of the agent node for *product* configured at a path.

    Every laptop collector that says something about the same agent (the MCP client
    walk here, the posture scan, the extensions scan) attaches it to this one id, so
    the console draws one agent per product and config file. Takes either the path
    itself or its :func:`config_path_hash` (64 lower-case hex characters, or the
    16-character prefix the id is built from); the id is
    ``local_agent:<sha1(product|path_hash[:16])[:20]>``, byte-identical to the ids
    this collector has always written.
    """
    if isinstance(path_hash_or_path, str) and len(path_hash_or_path) in (16, 64) and set(path_hash_or_path) <= _PATH_HASH_CHARS:
        path_hash = path_hash_or_path
    else:
        path_hash = config_path_hash(path_hash_or_path)
    return _entity_id("local_agent", product, path_hash[:16])


def _entity_id(kind: str, *parts: str) -> str:
    raw = "|".join(parts)
    return f"{kind}:{hashlib.sha1(raw.encode('utf-8'), usedforsecurity=False).hexdigest()[:20]}"


def _endpoint_fingerprint() -> str:
    return f"{platform.system()}|{platform.node()}|{os.getuid() if hasattr(os, 'getuid') else ''}"


def _now_iso() -> str:
    """The scan's own time, in the one form every discovery ``last_seen`` uses.

    Local rather than imported from ``discovery_time``: this module ships in the
    ``tracksec-tools`` wheel and keeps its import closure to the standard library.
    """
    from datetime import datetime, timezone

    return datetime.now(timezone.utc).replace(microsecond=0).strftime("%Y-%m-%dT%H:%M:%SZ")


def _parse_json_text(path: Path) -> Any:
    """JSON with comments and trailing commas (Zed's and Gemini CLI's settings, VS Code's files):
    the reading ``track mcp-wrap``'s editor (``packages/cli/jsonc_edit.py``) gives every file it
    accepts, held to it by ``tests/test_mcp_wrap_paths_match_the_collector.py``."""
    return json.loads(_strip_json_comments(path.read_text(encoding="utf-8")))


def _parse_yaml_text(path: Path) -> Any:
    import yaml  # lazy — the discovery collectors stay stdlib-only to IMPORT

    return yaml.safe_load(path.read_text(encoding="utf-8")) or {}


def _parse_toml_text(path: Path) -> Any:
    import tomllib  # stdlib at the 3.11 floor; lazy for symmetry with the others

    # Read BINARY. ``tomllib.load`` is specified over bytes, so no newline
    # translation can alter a multi-line basic string on the way in.
    with path.open("rb") as handle:
        return tomllib.load(handle)


def _load_config(path: Path) -> tuple[dict[str, Any] | None, str | None]:
    """Parse one candidate file. Returns ``(config, error_code)`` and NEVER raises.

    Fault isolation is the load-bearing half. This walk crosses a whole home
    directory, so one unreadable or unparsable file taking the scan down deletes the
    MCP inventory for that device — and a device that reports no MCP servers is
    indistinguishable from one that has none. The parser table above says which
    formats are understood; this says that not understanding one costs a row.
    """
    if not path.exists() or not path.is_file():
        return None, None
    parser = _CONFIG_PARSERS.get(path.suffix.lower(), _FALLBACK_PARSER)
    try:
        data = parser(path)
    except UnicodeDecodeError:  # a ValueError — must precede the catch-all below
        return None, "not_utf8"
    except OSError:
        return None, "unreadable"
    except Exception:  # noqa: BLE001 — every parser's own error type, plus whatever a
        # parser added later raises. The CATEGORY is what a reader can act on; the
        # message is what would leak the file.
        return None, "unparsable"
    if not isinstance(data, dict):
        return None, "not_a_mapping"
    return data, None


_CONFIG_PARSERS = {
    '.json': _parse_json_text,
    '.jsonc': _parse_json_text,
    '.yaml': _parse_yaml_text,
    '.yml': _parse_yaml_text,
    '.toml': _parse_toml_text,
}
_FALLBACK_PARSER = _parse_json_text


# ── packages/compliance/invisible_text.py, copied whole ─────────────────────

#: Zero-width and invisible-formatting characters: separators an attacker interleaves
#: between visible letters so a keyword reads as two words to a regex and one to a model.
ZERO_WIDTH_CODEPOINTS: frozenset[int] = frozenset({
    0x00AD,  # SOFT HYPHEN
    0x200B,  # ZERO WIDTH SPACE
    0x200C,  # ZERO WIDTH NON-JOINER
    0x200D,  # ZERO WIDTH JOINER
    0x2060,  # WORD JOINER
    0x2061,  # FUNCTION APPLICATION
    0x2062,  # INVISIBLE TIMES
    0x2063,  # INVISIBLE SEPARATOR
    0x2064,  # INVISIBLE PLUS
    0xFEFF,  # ZERO WIDTH NO-BREAK SPACE (BOM)
})

#: Bidirectional controls: what is rendered is not the order the model reads.
BIDI_CODEPOINTS: frozenset[int] = frozenset({
    0x200E,  # LEFT-TO-RIGHT MARK
    0x200F,  # RIGHT-TO-LEFT MARK
    0x202A,  # LEFT-TO-RIGHT EMBEDDING
    0x202B,  # RIGHT-TO-LEFT EMBEDDING
    0x202C,  # POP DIRECTIONAL FORMATTING
    0x202D,  # LEFT-TO-RIGHT OVERRIDE
    0x202E,  # RIGHT-TO-LEFT OVERRIDE
    0x2066,  # LEFT-TO-RIGHT ISOLATE
    0x2067,  # RIGHT-TO-LEFT ISOLATE
    0x2068,  # FIRST STRONG ISOLATE
    0x2069,  # POP DIRECTIONAL ISOLATE
})

#: The Unicode Tags block (U+E0000 to U+E007F): invisible mirrors of printable ASCII.
TAG_CODEPOINTS: frozenset[int] = frozenset(range(0xE0000, 0xE0080))

#: Every codepoint the node strips before matching; equal to the inspector's set.
INVISIBLE_CODEPOINTS: frozenset[int] = ZERO_WIDTH_CODEPOINTS | BIDI_CODEPOINTS | TAG_CODEPOINTS

#: The framing a poisoned tool description or rules file hides an instruction behind.
#: Same pattern and flags as ``tool_description_injection._HIDDEN_MARKER``.
HIDDEN_MARKER = re.compile(
    r"<\s*(important|system|secret|admin|instructions?)\s*>"
    r"|\[\s*(important|system|secret)\s*\]"
    r"|\bIMPORTANT\s*:"
    r"|<!--",
    re.IGNORECASE,
)

#: The keys :func:`count_invisible` answers, in a fixed order.
INVISIBLE_CLASSES: tuple[str, ...] = ("zero_width", "bidi", "tag", "total")


def count_invisible(text: str) -> dict[str, int]:
    """How many invisible characters of each class *text* carries; never the characters.

    ``total`` is the sum of the three classes. A non-string reads as empty text.
    """
    counts = {"zero_width": 0, "bidi": 0, "tag": 0, "total": 0}
    if not isinstance(text, str) or not text:
        return counts
    for ch in text:
        cp = ord(ch)
        if cp in ZERO_WIDTH_CODEPOINTS:
            counts["zero_width"] += 1
        elif cp in BIDI_CODEPOINTS:
            counts["bidi"] += 1
        elif cp in TAG_CODEPOINTS:
            counts["tag"] += 1
    counts["total"] = counts["zero_width"] + counts["bidi"] + counts["tag"]
    return counts


def count_hidden_markers(text: str) -> int:
    """How many hidden-instruction framings (:data:`HIDDEN_MARKER`) *text* carries."""
    if not isinstance(text, str) or not text:
        return 0
    return sum(1 for _ in HIDDEN_MARKER.finditer(text))


# ── packages/compliance/agent_config_posture.py, copied whole ───────────────

def _agent_config_posture_module():
    """packages.compliance.agent_config_posture, copied whole; answers its module namespace."""
    import os  # noqa: F401
    import re  # noqa: F401
    import sys  # noqa: F401
    import unicodedata  # noqa: F401
    from collections.abc import Iterable, Mapping  # noqa: F401
    from pathlib import Path  # noqa: F401
    from typing import Any  # noqa: F401


    #: The snapshot category, read by ``endpoint_sensor_scans`` and the ingest route's accept list.
    SNAPSHOT_CATEGORY = "agent_runtime"

    #: The finding kinds the node mints from this scan's facts, and only from them.
    FINDING_KINDS: tuple[str, ...] = (
        "agent_permission_bypass",
        "agent_wildcard_tool_rule",
        "agent_sandbox_disabled",
        "agent_bypass_mode_unlocked",
        "agent_project_mcp_auto_approved",
        "agent_rules_file_hidden_text",
        "agent_managed_hooks_unlocked",
    )

    #: ``config.scan`` on this scan's snapshot: the node answers ``[]`` (clear everything) for a
    #: complete posture scan that found nothing, and ``None`` for any other snapshot.
    SCAN_MARKER = "agent_config_posture"

    #: The version of the ``attrs.posture`` shape. The node refuses a posture of another version.
    POSTURE_SCHEMA = 1

    #: Bounds. A rules file past ``MAX_RULES_FILE_BYTES`` is counted over what was read and says
    #: ``truncated``; the projects past ``MAX_PROJECTS`` are not read and the config says so.
    MAX_PROJECTS = 50
    MAX_RULES_FILES_PER_PROJECT = 20
    MAX_RULES_FILE_BYTES = 1 << 20
    MAX_ALLOW_RULES = 200
    MAX_RULE_CHARS = 512

    #: The permission-mode vocabulary across products (Claude Code ``permissions.defaultMode``;
    #: Codex ``approval_policy``; Gemini CLI ``general.defaultApprovalMode``). Anything else
    #: a file writes reads ``unknown``.
    PERMISSION_MODES: frozenset[str] = frozenset({
        "default", "acceptEdits", "plan", "auto", "dontAsk", "bypassPermissions",
        "on-request", "never", "granular", "yolo", "auto_edit", "unknown",
    })
    PERMISSION_MODE_SOURCES: frozenset[str] = frozenset({"managed", "user", "project", "flag_unknown"})
    FILE_SCOPES: frozenset[str] = frozenset({"managed", "user", "project", "system"})
    SANDBOX_MODES: frozenset[str] = frozenset({"read-only", "workspace-write", "danger-full-access"})
    SETTINGS_SCHEMAS: frozenset[str] = frozenset({"nested", "flat"})

    #: The products this scan reads, with the display name the agent node carries.
    PRODUCTS: dict[str, str] = {
        "claude_code": "Claude Code",
        "codex": "Codex",
        "gemini_cli": "Gemini CLI",
        "cursor": "Cursor",
        "copilot_cli": "GitHub Copilot CLI",
    }

    #: The file each product's agent node is keyed on (``agent_entity_id(product, <this path>)``),
    #: relative to the home directory: the same file the MCP client walk keys that product's
    #: agent on, so both scans describe ONE node. Gemini CLI is not in that walk; its user
    #: settings file is its key.
    ANCHOR_FILES: dict[str, str] = {
        "claude_code": ".claude.json",
        "codex": ".codex/config.toml",
        "gemini_cli": ".gemini/settings.json",
        "cursor": ".cursor/mcp.json",
        "copilot_cli": ".copilot/mcp-config.json",
    }

    #: Where each product's files live: relative to the home directory, ``$CODEX_HOME`` (the
    #: ``CODEX_*`` user names) or a project. ONE definition, read by the readers below and by
    #: ``agent_file_contents`` (which locates the same files to read their text when a tenant asks),
    #: so the two can never name different files. ``tests/test_agent_file_contents_reader.py`` spies
    #: on every file this scan opens and requires each to be a kind of that table or a named exclusion.
    CLAUDE_STATE_FILE = ".claude.json"
    CLAUDE_USER_SETTINGS = ".claude/settings.json"
    CLAUDE_PROJECT_SETTINGS: tuple[str, ...] = (".claude/settings.local.json", ".claude/settings.json")
    CLAUDE_USER_RULES = ".claude/CLAUDE.md"
    CLAUDE_PROJECT_RULES: tuple[str, ...] = ("CLAUDE.md", ".claude/CLAUDE.md")
    CODEX_USER_CONFIG = "config.toml"
    CODEX_USER_HOOKS = "hooks.json"
    CODEX_USER_RULES = "AGENTS.md"
    CODEX_PROJECT_CONFIG = ".codex/config.toml"
    CODEX_PROJECT_RULES: tuple[str, ...] = ("AGENTS.md",)
    GEMINI_USER_SETTINGS = ".gemini/settings.json"
    GEMINI_PROJECT_SETTINGS = ".gemini/settings.json"
    GEMINI_TRUSTED_FOLDERS = ".gemini/trustedFolders.json"
    GEMINI_USER_RULES = ".gemini/GEMINI.md"
    GEMINI_PROJECT_RULES: tuple[str, ...] = ("GEMINI.md",)
    CURSOR_USER_CLI = ".cursor/cli-config.json"
    CURSOR_PROJECT_CLI = ".cursor/cli.json"
    CURSOR_USER_HOOKS = ".cursor/hooks.json"
    CURSOR_PROJECT_HOOKS = ".cursor/hooks.json"
    CURSOR_PROJECT_RULES: tuple[str, ...] = (".cursor/rules/*.mdc", ".cursorrules", "AGENTS.md")
    COPILOT_USER_CONFIG = ".copilot/config.json"
    COPILOT_USER_MCP = ".copilot/mcp-config.json"

    #: The per-user directory (or file) whose presence says the product is installed for this user.
    PRODUCT_HOMES: dict[str, str] = {
        "claude_code": ".claude",
        "codex": ".codex",
        "gemini_cli": ".gemini",
        "cursor": ".cursor",
        "copilot_cli": ".copilot",
    }

    #: Token shapes replaced by ``[redacted]`` in every rule string before it leaves: provider
    #: API keys (``sk-``), GitHub (``ghp_``/``gho_``/``ghu_``/``ghs_``/``ghr_``, ``github_pat_``),
    #: GitLab (``glpat-``), Slack (``xox?-``), AWS access key ids, a JWT, a bearer value, and any
    #: run of 32 or more hex characters.
    _TOKEN = re.compile(
        r"sk-[A-Za-z0-9_\-]{8,}"
        r"|gh[pousr]_[A-Za-z0-9]{16,}"
        r"|github_pat_[A-Za-z0-9_]{20,}"
        r"|glpat-[A-Za-z0-9_\-]{16,}"
        r"|xox[abposr]-[A-Za-z0-9\-]{10,}"
        r"|(?:AKIA|ASIA|A3T[A-Z0-9])[A-Z0-9]{16}"
        r"|eyJ[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}\.[A-Za-z0-9_\-]{8,}"
        r"|(?i:bearer)\s+[A-Za-z0-9._~+/\-]{12,}=*"
        r"|(?<![0-9A-Fa-f])[0-9A-Fa-f]{32,}(?![0-9A-Fa-f])"
    )
    #: An environment assignment whose NAME says it holds a secret: the name is kept, the value is not.
    _SECRET_ASSIGNMENT = re.compile(
        r"(?i)\b([A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_?KEY|ACCESS_?KEY|PRIVATE_?KEY|CREDENTIAL)[A-Z0-9_]*)"
        r"(\s*=\s*)(\"[^\"]*\"|'[^']*'|[^\s)\"']+)"
    )
    REDACTED = "[redacted]"


    def redact_rule(rule: str) -> str:
        """A rule string as it may leave the laptop: secret-shaped values replaced, length capped."""
        text = _SECRET_ASSIGNMENT.sub(lambda m: f"{m.group(1)}{m.group(2)}{REDACTED}", rule)
        text = _TOKEN.sub(REDACTED, text)
        if len(text) > MAX_RULE_CHARS:
            text = text[:MAX_RULE_CHARS] + "…"
        return text


    def empty_posture() -> dict[str, Any]:
        """Every posture key, each ``None`` or empty: a product reader fills what it has."""
        return {
            "schema": POSTURE_SCHEMA,
            "files_read": [],
            "permission_mode": None,
            "permission_mode_source": None,
            "allow_rules": None,
            "deny_rules_count": None,
            "ask_rules_count": None,
            "bypass_mode_disabled": None,
            "bypass_mode_disabled_source": None,
            "skip_dangerous_prompt": None,
            "sandbox": {"enabled": None, "auto_allow": None, "unsandboxed_retry": None, "mode": None, "network_access": None},
            "project_mcp_auto_approved": None,
            "project_mcp_auto_approved_source": None,
            "managed_settings_present": False,
            "managed_hooks_only": None,
            "managed_permission_rules_only": None,
            "hooks_configured_count": 0,
            "trusted_projects_count": None,
            "folder_trust_enabled": None,
            "rules_files": [],
            "ide_auto_run": None,
            "settings_schema": None,
        }


    # --- Hidden text: the narrow reading a finding rests on -----------------------------------------
    #
    # A MIRROR of ``agent_extensions_discovery.hidden_text_facts``'s two narrow counts (that module
    # measured why: a framing marker sits in 8.1 % and an HTML comment in 5.6 % of ordinary
    # markdown on a developer laptop, so the broad counts cannot carry a finding). Mirrored rather
    # than imported so this scan's import closure stays the three stdlib-only modules it names;
    # ``tests/test_agent_config_posture.py`` holds the two equal on a table of texts.

    _ZWJ = 0x200D
    _BOM = 0xFEFF
    _COMMENT_RE = re.compile(r"<!--(.*?)(?:-->|$)", re.DOTALL)


    def _emoji_side(ch: str) -> bool:
        cp = ord(ch)
        return unicodedata.category(ch) in ("So", "Sk") or cp == 0xFE0F or 0x1F3FB <= cp <= 0x1F3FF


    def invisible_suspect(text: str, total: int) -> int:
        """Invisible characters other than a joiner between two emoji parts and a leading byte-order mark."""
        suspect = total
        if suspect and isinstance(text, str):
            for i, ch in enumerate(text):
                cp = ord(ch)
                if cp == _BOM and i == 0:
                    suspect -= 1
                elif cp == _ZWJ and 0 < i < len(text) - 1 and _emoji_side(text[i - 1]) and _emoji_side(text[i + 1]):
                    suspect -= 1
        return max(suspect, 0)


    def markers_in_comments(text: str) -> int:
        """Framing markers INSIDE an HTML comment: the text a rendered view hides and the model reads."""
        if not isinstance(text, str) or not text:
            return 0
        return sum(count_hidden_markers(m.group(1)) for m in _COMMENT_RE.finditer(text))


    # --- Reading files ----------------------------------------------------------------------------


    class _Scan:
        """What one scan read: the per-product posture lists and the snapshot's config lists."""

        def __init__(self, *, include_paths: bool) -> None:
            self.include_paths = include_paths
            self.scanned_files: list[dict[str, Any]] = []
            self.degraded: list[str] = []
            self._seen: set[str] = set()
            #: A bound stopped the scan before a file it would have read (a project past
            #: ``MAX_PROJECTS``, a rules file past ``MAX_RULES_FILES_PER_PROJECT``). The node then
            #: clears nothing: a file never reached is not one that was fixed.
            self.truncated = False

        def _note(self, path: Path, *, parsed: bool, error: str | None, kind: str) -> str:
            path_hash = config_path_hash(path)
            key = f"{kind}:{path_hash}"
            if key not in self._seen:
                self._seen.add(key)
                self.scanned_files.append({
                    "path_hash": path_hash,
                    "path": str(path) if self.include_paths else None,
                    "filename": path.name,
                    "exists": True,
                    "parsed": parsed,
                    "error": error,
                })
            if error:
                note = f"{path.name}: {error}"
                if note not in self.degraded:
                    self.degraded.append(note)
            return path_hash

        def config(self, path: Path, scope: str, posture: dict[str, Any]) -> dict[str, Any] | None:
            """Parse one settings file; record it on *posture*; ``None`` when absent or unreadable.

            Never raises: one file that cannot be read costs that file, never the scan.
            """
            try:
                if not path.is_file():
                    return None
            except OSError:
                return None
            if any(f["path_hash"] == config_path_hash(path) for f in posture["files_read"]):
                return None  # already read for this product: one file counts once
            if path.suffix.lower() == ".plist":
                data, error = _load_plist(path)
            else:
                data, error = _load_config(path)
            if error is not None and error not in PARSE_ERROR_CODES:
                error = "unparsable"
            path_hash = self._note(path, parsed=data is not None, error=error, kind="config")
            posture["files_read"].append({
                "path_hash": path_hash, "filename": path.name, "scope": scope,
                "parsed": data is not None, "error": error,
            })
            return data

        def rules_file(self, path: Path, scope: str, posture: dict[str, Any]) -> None:
            """Count what one rules file hides; record it on *posture*. Never its text."""
            try:
                if not path.is_file():
                    return
                size = path.stat().st_size
                with path.open("rb") as handle:
                    raw = handle.read(MAX_RULES_FILE_BYTES + 1)
            except OSError:
                self._note(path, parsed=False, error="unreadable", kind="rules")
                return
            truncated = len(raw) > MAX_RULES_FILE_BYTES
            text = raw[:MAX_RULES_FILE_BYTES].decode("utf-8", errors="replace")
            path_hash = self._note(path, parsed=True, error=None, kind="rules")
            if any(r["path_hash"] == path_hash for r in posture["rules_files"]):
                return  # one file reached twice (a symlinked checkout) is one file
            invisible = count_invisible(text)
            posture["rules_files"].append({
                "path_hash": path_hash,
                "filename": path.name,
                "scope": scope,
                "bytes": int(size),
                "truncated": truncated,
                # The inspectors' broad counts, for parity with them; the node's finding rests on
                # the two narrow ones below.
                "invisible": invisible,
                "hidden_markers": count_hidden_markers(text),
                "invisible_suspect": invisible_suspect(text, invisible["total"]),
                "markers_in_comments": markers_in_comments(text),
            })


    def _load_plist(path: Path) -> tuple[dict[str, Any] | None, str | None]:
        """A macOS managed-preferences plist, in the same closed error vocabulary as every file."""
        import plistlib

        try:
            with path.open("rb") as handle:
                data = plistlib.load(handle)
        except OSError:
            return None, "unreadable"
        except Exception:  # noqa: BLE001 — the parser's own error; its message would quote content
            return None, "unparsable"
        if not isinstance(data, dict):
            return None, "not_a_mapping"
        return data, None


    def _read_windows_registry_settings() -> dict[str, Any] | None:
        """Claude Code's ``HKLM\\SOFTWARE\\Policies\\ClaudeCode`` value ``Settings`` (JSON), or ``None``.

        "the JSON as a REG_SZ or REG_EXPAND_SZ value named Settings under
        HKLM\\SOFTWARE\\Policies\\ClaudeCode" (https://code.claude.com/docs/en/managed-settings).
        Read only on Windows; never raises.
        """
        if sys.platform != "win32":
            return None
        try:
            import json
            import winreg  # type: ignore[import-not-found]

            with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Policies\ClaudeCode") as key:  # type: ignore[attr-defined]
                value, _ = winreg.QueryValueEx(key, "Settings")  # type: ignore[attr-defined]
            data = json.loads(str(value))
        except Exception:  # noqa: BLE001 — absent key, unreadable value, bad JSON: no policy read
            return None
        return data if isinstance(data, dict) else None


    # --- Helpers over parsed documents -------------------------------------------------------------


    def _get(doc: Mapping[str, Any] | None, *path: str) -> Any:
        node: Any = doc
        for part in path:
            if not isinstance(node, Mapping):
                return None
            node = node.get(part)
        return node


    def _str_list(value: Any) -> list[str]:
        return [str(v) for v in value if isinstance(v, (str, int, float)) and not isinstance(v, bool)] if isinstance(value, list) else []


    def _count_hooks(block: Any) -> int:
        """How many hook COMMANDS a hooks block configures, in each vendor's documented shape.

        Claude Code, Codex and Gemini CLI: ``{Event: [{matcher, hooks: [{type, command}]}]}``;
        Cursor: ``{"version": 1, "hooks": {event: [{command}]}}``.
        """
        if not isinstance(block, Mapping):
            return 0
        if isinstance(block.get("hooks"), Mapping) and ("version" in block or not any(
            isinstance(v, list) for k, v in block.items() if k != "hooks"
        )):
            block = block["hooks"]
        total = 0
        for value in block.values():
            if not isinstance(value, list):
                continue
            for item in value:
                if not isinstance(item, Mapping):
                    continue
                inner = item.get("hooks")
                if isinstance(inner, list):
                    total += sum(1 for h in inner if isinstance(h, Mapping))
                elif item.get("command") or item.get("type"):
                    total += 1
        return total


    class _Most:
        """The most permissive value seen, by a rank table, with the scope it came from."""

        def __init__(self, rank: Mapping[str, float]) -> None:
            self.rank = rank
            self.value: str | None = None
            self.source: str | None = None

        def offer(self, value: str | None, source: str) -> None:
            if value is None:
                return
            if self.value is None or self.rank.get(value, 0) > self.rank.get(self.value, 0):
                self.value, self.source = value, source


    def _rule_list(rules: Iterable[str]) -> list[str]:
        out: list[str] = []
        for rule in rules:
            r = redact_rule(rule)
            if r not in out:
                out.append(r)
            if len(out) >= MAX_ALLOW_RULES:
                break
        return out


    # --- Where things are ----------------------------------------------------------------------------


    def _system_path(system_root: Path | None, absolute: str) -> Path:
        """An absolute system path, re-rooted under *system_root* when one is given (tests)."""
        if system_root is None:
            return Path(absolute)
        relative = absolute.replace("\\", "/")
        if len(relative) > 1 and relative[1] == ":":
            relative = relative[2:]
        return system_root / relative.lstrip("/")


    def _claude_managed_paths(platform_name: str, system_root: Path | None) -> list[tuple[Path, str]]:
        """Claude Code's managed sources, highest rank first.

        "macOS configuration profile: the com.anthropic.claudecode managed preferences
        domain"; "File-based: managed-settings.json, an optional managed-settings.d/ directory
        … /Library/Application Support/ClaudeCode/ on macOS, /etc/claude-code/ on Linux and
        WSL, and C:\\Program Files\\ClaudeCode\\ on Windows. Claude Code doesn't read the legacy
        Windows path C:\\ProgramData\\ClaudeCode\\managed-settings.json"
        (https://code.claude.com/docs/en/managed-settings, "Where each mechanism stores the policy").
        """
        if platform_name == "darwin":
            directory = "/Library/Application Support/ClaudeCode"
            out = [(_system_path(system_root, "/Library/Managed Preferences/com.anthropic.claudecode.plist"), "plist")]
        elif platform_name == "win32":
            directory = "C:/Program Files/ClaudeCode"
            out = []
        else:
            directory = "/etc/claude-code"
            out = []
        base = _system_path(system_root, directory)
        out.append((base / "managed-settings.json", "file"))
        drop_in = base / "managed-settings.d"
        try:
            if drop_in.is_dir():
                out.extend((p, "file") for p in sorted(drop_in.glob("*.json")))
        except OSError:
            pass
        return out


    def _codex_requirements_path(platform_name: str, system_root: Path | None, env: Mapping[str, str]) -> Path:
        """Codex's managed ``requirements.toml``: ``/etc/codex/requirements.toml``, Windows
        ``%ProgramData%\\OpenAI\\Codex\\requirements.toml``
        (https://learn.chatgpt.com/docs/config-file/config-reference, "requirements.toml")."""
        if platform_name == "win32":
            program_data = env.get("ProgramData") or "C:/ProgramData"
            return _system_path(system_root, f"{program_data}/OpenAI/Codex/requirements.toml")
        return _system_path(system_root, "/etc/codex/requirements.toml")


    def _gemini_system_path(platform_name: str, system_root: Path | None, env: Mapping[str, str]) -> Path:
        """Gemini CLI's system settings: ``GEMINI_CLI_SYSTEM_SETTINGS_PATH``, else the per-OS default
        (Linux ``/etc/gemini-cli/settings.json``, macOS ``/Library/Application Support/GeminiCli/
        settings.json``, Windows ``C:\\ProgramData\\gemini-cli\\settings.json``)."""
        override = env.get("GEMINI_CLI_SYSTEM_SETTINGS_PATH")
        if override:
            return Path(override)
        if platform_name == "darwin":
            return _system_path(system_root, "/Library/Application Support/GeminiCli/settings.json")
        if platform_name == "win32":
            return _system_path(system_root, "C:/ProgramData/gemini-cli/settings.json")
        return _system_path(system_root, "/etc/gemini-cli/settings.json")


    def _cursor_enterprise_hooks(platform_name: str, system_root: Path | None) -> Path:
        if platform_name == "darwin":
            return _system_path(system_root, "/Library/Application Support/Cursor/hooks.json")
        if platform_name == "win32":
            return _system_path(system_root, "C:/ProgramData/Cursor/hooks.json")
        return _system_path(system_root, "/etc/cursor/hooks.json")


    def codex_home_dir(home: Path, env: Mapping[str, str]) -> Path:
        """Codex's home: ``$CODEX_HOME`` when set, else ``~/.codex``."""
        return Path(env["CODEX_HOME"]).expanduser() if env.get("CODEX_HOME") else home / ".codex"


    def _read_known_projects(home: Path, env: Mapping[str, str]) -> tuple[dict[str, Any] | None, list[Path], dict[str, Any]]:
        """``(~/.claude.json parsed, the projects, the projects note)``: the project list every
        product's project files are read from. Parses ``~/.claude.json`` for its ``projects`` keys."""
        claude_global, _ = _load_config(home / CLAUDE_STATE_FILE)
        codex_user, _ = _load_config(codex_home_dir(home, env) / CODEX_USER_CONFIG)
        projects, note = _known_projects(claude_global, codex_user, home)
        return claude_global, projects, note


    def known_projects(home: Path, env: Mapping[str, str] | None = None) -> tuple[list[Path], dict[str, Any]]:
        """The projects this scan reads project files from, newest first, at most
        :data:`MAX_PROJECTS`, and the note that says whether the cap left some out."""
        _, projects, note = _read_known_projects(home, os.environ if env is None else env)
        return projects, note


    def _known_projects(claude_global: Mapping[str, Any] | None, codex_user: Mapping[str, Any] | None,
                        home: Path | None = None) -> tuple[list[Path], dict[str, Any]]:
        """The project directories every product's project files are read from, bounded.

        The home directory itself is not a project: a session started there names it in
        ``~/.claude.json``, and reading it as one would count the USER files twice.
        """
        names: list[str] = []
        for doc in (claude_global, codex_user):
            projects = _get(doc, "projects")
            if isinstance(projects, Mapping):
                names.extend(str(k) for k in projects if isinstance(k, str) and k)
        existing: list[tuple[float, Path]] = []
        seen: set[str] = set()
        resolved_seen: set[Path] = set()
        home_resolved = home.resolve() if home is not None else None
        for name in names:
            if name in seen:
                continue
            seen.add(name)
            path = Path(name).expanduser()
            try:
                if not (path.is_absolute() and path.is_dir()):
                    continue
                resolved = path.resolve()
                # One checkout named twice (a symlink, a trailing alias) is one project.
                if resolved == home_resolved or resolved in resolved_seen:
                    continue
                resolved_seen.add(resolved)
                existing.append((path.stat().st_mtime, path))
            except OSError:
                continue
        existing.sort(key=lambda t: (-t[0], str(t[1])))
        chosen = [p for _, p in existing[:MAX_PROJECTS]]
        return chosen, {"named": len(seen), "existing": len(existing), "read": len(chosen),
                        "truncated": len(existing) > MAX_PROJECTS}


    def project_rule_paths(project: Path, relatives: Iterable[str]) -> tuple[list[Path], int]:
        """A project's rules files present, at most :data:`MAX_RULES_FILES_PER_PROJECT` of them, and
        how many the cap left out (a cap reached exactly leaves none)."""
        present: list[Path] = []
        for rel in relatives:
            try:
                if rel.endswith("/*.mdc"):
                    directory = project / rel[: -len("/*.mdc")]
                    present.extend(sorted(directory.glob("*.mdc")) if directory.is_dir() else [])
                elif (project / rel).is_file():
                    present.append(project / rel)
            except OSError:
                continue
        return present[:MAX_RULES_FILES_PER_PROJECT], max(0, len(present) - MAX_RULES_FILES_PER_PROJECT)


    def _project_rules(scan: _Scan, posture: dict[str, Any], project: Path, relatives: Iterable[str]) -> None:
        """Read a project's rules files, at most :data:`MAX_RULES_FILES_PER_PROJECT` of them.

        A file past the cap marks the scan ``truncated``; a cap reached exactly does not.
        """
        present, left_out = project_rule_paths(project, relatives)
        if left_out:
            scan.truncated = True
        for path in present:
            scan.rules_file(path, "project", posture)


    # --- The products --------------------------------------------------------------------------------

    #: Claude Code ``permissions.defaultMode``, least to most permissive. ``dontAsk`` auto-DENIES
    #: every call that would prompt ("Claude Code auto-denies every call that would otherwise
    #: prompt", https://code.claude.com/docs/en/settings-reference#permissions-defaultmode), so
    #: it ranks below ``default``. ``manual`` is an alias for ``default`` (same page).
    _CLAUDE_MODE_RANK = {"plan": 0, "dontAsk": 1, "default": 2, "unknown": 2.5, "acceptEdits": 3, "auto": 4,
                         "bypassPermissions": 5}


    def _claude_mode(value: Any) -> str | None:
        if not isinstance(value, str) or not value:
            return None
        if value == "manual":
            return "default"
        return value if value in _CLAUDE_MODE_RANK else "unknown"


    def _read_claude_code(scan: _Scan, home: Path, projects: list[Path], claude_global: Mapping[str, Any] | None,
                          *, platform_name: str, system_root: Path | None) -> dict[str, Any]:
        posture = empty_posture()
        posture["allow_rules"] = []
        posture["deny_rules_count"] = 0
        posture["ask_rules_count"] = 0
        posture["bypass_mode_disabled"] = False
        posture["skip_dangerous_prompt"] = False
        posture["project_mcp_auto_approved"] = False
        posture["trusted_projects_count"] = 0

        # (doc, file scope) in precedence order: managed, project local, project shared, user.
        managed: list[dict[str, Any]] = []
        registry = _read_windows_registry_settings() if platform_name == "win32" and system_root is None else None
        if registry is not None:
            managed.append(registry)
            posture["files_read"].append({"path_hash": _hash("HKLM\\SOFTWARE\\Policies\\ClaudeCode"),
                                          "filename": "Settings (HKLM registry)", "scope": "managed",
                                          "parsed": True, "error": None})
        for path, _ in _claude_managed_paths(platform_name, system_root):
            doc = scan.config(path, "managed", posture)
            if doc is not None:
                managed.append(doc)
        others: list[tuple[dict[str, Any], str]] = []
        for project in projects:
            for rel in CLAUDE_PROJECT_SETTINGS:
                doc = scan.config(project / rel, "project", posture)
                if doc is not None:
                    others.append((doc, "project"))
        user = scan.config(home / CLAUDE_USER_SETTINGS, "user", posture)
        if user is not None:
            others.append((user, "user"))
        # ~/.claude.json is read by the caller (it names the projects); recorded here.
        if claude_global is not None or (home / CLAUDE_STATE_FILE).is_file():
            scan.config(home / CLAUDE_STATE_FILE, "user", posture)

        posture["managed_settings_present"] = bool(managed)

        def first_managed(*path: str) -> Any:
            for doc in managed:
                value = _get(doc, *path)
                if value is not None:
                    return value
            return None

        # Permission mode: a managed value wins; else the most permissive user/project value.
        managed_mode = _claude_mode(first_managed("permissions", "defaultMode"))
        if managed_mode is not None:
            posture["permission_mode"], posture["permission_mode_source"] = managed_mode, "managed"
        else:
            most = _Most(_CLAUDE_MODE_RANK)
            for doc, scope in others:
                most.offer(_claude_mode(_get(doc, "permissions", "defaultMode")), scope)
            posture["permission_mode"], posture["permission_mode_source"] = most.value, most.source

        # Rules: merged across every scope, unless managed settings are the only source of them
        # ("Make managed settings the only settings source of permission rules … ignores allow,
        # ask, and deny rules in user, project, local", settings-reference#allowmanagedpermissionrulesonly).
        rules_only = first_managed("allowManagedPermissionRulesOnly")
        posture["managed_permission_rules_only"] = (rules_only is True) if managed else None
        rule_docs: list[Any] = list(managed)
        if rules_only is not True:
            rule_docs += [doc for doc, _ in others]
        allow: list[str] = []
        for doc in rule_docs:
            allow += _str_list(_get(doc, "permissions", "allow"))
            posture["deny_rules_count"] += len(_str_list(_get(doc, "permissions", "deny")))
            posture["ask_rules_count"] += len(_str_list(_get(doc, "permissions", "ask")))
        projects_state = _get(claude_global, "projects")
        if rules_only is not True and isinstance(projects_state, Mapping):
            # Per-project "allowedTools" Claude Code keeps in ~/.claude.json.
            for state in projects_state.values():
                allow += _str_list(_get(state, "allowedTools"))
        posture["allow_rules"] = _rule_list(allow)

        # Bypass mode locked off: "the string "disable"", scope "Any file"
        # (settings-reference#permissions-disablebypasspermissionsmode).
        for doc, scope in [*((d, "managed") for d in managed), *others]:
            if _get(doc, "permissions", "disableBypassPermissionsMode") == "disable":
                posture["bypass_mode_disabled"], posture["bypass_mode_disabled_source"] = True, scope
                break
        # skipDangerousModePermissionPrompt: "User, local, or managed".
        for doc, scope in [*((d, "managed") for d in managed), *others]:
            if _get(doc, "skipDangerousModePermissionPrompt") is True:
                posture["skip_dangerous_prompt"] = True
                break

        # Sandbox: the value as WRITTEN. allowUnsandboxedCommands defaults to true
        # (settings-reference#sandbox-allowunsandboxedcommands), but a default nobody wrote is not a
        # weakening, so it reads None here and the node raises nothing for it.
        def sandbox_value(key: str) -> Any:
            value = first_managed("sandbox", key)
            if value is not None:
                return value
            for doc, _ in others:
                value = _get(doc, "sandbox", key)
                if isinstance(value, bool):
                    return value
            return None

        for fact, key in (("enabled", "enabled"), ("auto_allow", "autoAllowBashIfSandboxed"),
                          ("unsandboxed_retry", "allowUnsandboxedCommands")):
            value = sandbox_value(key)
            posture["sandbox"][fact] = value if isinstance(value, bool) else None

        for doc, scope in [*((d, "managed") for d in managed), *others]:
            if _get(doc, "enableAllProjectMcpServers") is True:
                posture["project_mcp_auto_approved"] = True
                posture["project_mcp_auto_approved_source"] = scope
                break

        hooks_only = first_managed("allowManagedHooksOnly")
        posture["managed_hooks_only"] = (hooks_only is True) if managed else None
        posture["hooks_configured_count"] = sum(_count_hooks(_get(doc, "hooks")) for doc in [*managed, *(d for d, _ in others)])

        if isinstance(projects_state, Mapping):
            posture["trusted_projects_count"] = sum(
                1 for state in projects_state.values() if _get(state, "hasTrustDialogAccepted") is True
            )

        scan.rules_file(home / CLAUDE_USER_RULES, "user", posture)
        for project in projects:
            _project_rules(scan, posture, project, CLAUDE_PROJECT_RULES)
        return posture


    #: Codex ``approval_policy`` and ``sandbox_mode``, least to most permissive
    #: (https://learn.chatgpt.com/docs/config-file/config-reference: approval_policy
    #: "on-request | never | { granular = {…} }"; sandbox_mode "read-only | workspace-write |
    #: danger-full-access").
    _CODEX_MODE_RANK = {"on-request": 1, "unknown": 1.5, "granular": 2, "never": 3}
    _CODEX_SANDBOX_RANK = {"read-only": 1, "workspace-write": 2, "danger-full-access": 3}


    def _codex_mode(value: Any) -> str | None:
        if isinstance(value, Mapping) and "granular" in value:
            return "granular"
        if isinstance(value, str) and value:
            return value if value in ("on-request", "never") else "unknown"
        return None


    def _read_codex(scan: _Scan, home: Path, projects: list[Path],
                    *, platform_name: str, system_root: Path | None, env: Mapping[str, str]) -> dict[str, Any]:
        posture = empty_posture()
        codex_home = codex_home_dir(home, env)
        requirements = scan.config(_codex_requirements_path(platform_name, system_root, env), "managed", posture)
        user = scan.config(codex_home / CODEX_USER_CONFIG, "user", posture)
        posture["managed_settings_present"] = requirements is not None

        trusted: list[Path] = []
        projects_table = _get(user, "projects")
        if isinstance(projects_table, Mapping):
            posture["trusted_projects_count"] = sum(
                1 for state in projects_table.values() if _get(state, "trust_level") == "trusted"
            )
            trusted_names = {str(k) for k, v in projects_table.items() if _get(v, "trust_level") == "trusted"}
            trusted = [p for p in projects if str(p) in trusted_names]
        # "Untrusted projects skip project-scoped .codex/ layers" (config-reference, projects.<path>.trust_level).
        docs: list[tuple[dict[str, Any], str]] = []
        for project in trusted:
            doc = scan.config(project / CODEX_PROJECT_CONFIG, "project", posture)
            if doc is not None:
                docs.append((doc, "project"))
        if isinstance(user, dict):
            docs.append((user, "user"))

        allowed_policies = _str_list(_get(requirements, "allowed_approval_policies")) or None
        allowed_sandboxes = _str_list(_get(requirements, "allowed_sandbox_modes")) or None
        mode = _Most(_CODEX_MODE_RANK)
        sandbox = _Most(_CODEX_SANDBOX_RANK)
        for doc, scope in docs:
            value = _codex_mode(_get(doc, "approval_policy"))
            # A value the managed requirements do not allow never takes effect.
            if value is not None and (allowed_policies is None or value in allowed_policies):
                mode.offer(value, scope)
            sb = _get(doc, "sandbox_mode")
            if isinstance(sb, str) and sb in SANDBOX_MODES and (allowed_sandboxes is None or sb in allowed_sandboxes):
                sandbox.offer(sb, scope)
        posture["permission_mode"], posture["permission_mode_source"] = mode.value, mode.source
        posture["sandbox"]["mode"] = sandbox.value
        if sandbox.value is not None:
            posture["sandbox"]["enabled"] = sandbox.value != "danger-full-access"
        for doc, _ in docs:
            network = _get(doc, "sandbox_workspace_write", "network_access")
            if isinstance(network, bool):
                posture["sandbox"]["network_access"] = network
                break
        if allowed_policies is not None:
            posture["bypass_mode_disabled"] = "never" not in allowed_policies
            posture["bypass_mode_disabled_source"] = "managed"
        if requirements is not None:
            posture["managed_hooks_only"] = _get(requirements, "allow_managed_hooks_only") is True
        hooks = sum(_count_hooks(_get(doc, "hooks")) for doc, _ in docs)
        hooks_json = scan.config(codex_home / CODEX_USER_HOOKS, "user", posture)
        if hooks_json is not None:
            hooks += _count_hooks(hooks_json.get("hooks") if isinstance(hooks_json.get("hooks"), Mapping) else hooks_json)
        posture["hooks_configured_count"] = hooks

        scan.rules_file(codex_home / CODEX_USER_RULES, "user", posture)
        for project in projects:
            _project_rules(scan, posture, project, CODEX_PROJECT_RULES)
        return posture


    #: Gemini CLI ``general.defaultApprovalMode`` ("'default', 'auto_edit', 'plan'"; "YOLO mode …
    #: can only be enabled via command line"), least to most permissive
    #: (https://raw.githubusercontent.com/google-gemini/gemini-cli/main/schemas/settings.schema.json).
    _GEMINI_MODE_RANK = {"plan": 0, "default": 1, "unknown": 1.5, "auto_edit": 2, "yolo": 3}
    #: Top-level objects that mark the NESTED settings layout (the shipped schema's).
    _GEMINI_NESTED_KEYS = ("general", "tools", "mcp", "security")
    #: The legacy FLAT spellings this scan reads.
    _GEMINI_FLAT_KEYS = ("autoAccept", "sandbox", "allowMCPServers")


    def _gemini_mode(value: Any) -> str | None:
        if not isinstance(value, str) or not value:
            return None
        return value if value in _GEMINI_MODE_RANK else "unknown"


    def _gemini_sandbox(value: Any) -> bool | None:
        """``tools.sandbox``: "Set to a boolean …, provide a string path to a sandbox profile, or
        specify an …" object (settings.schema.json). Any non-empty profile means on."""
        if isinstance(value, bool):
            return value
        if isinstance(value, str):
            return value.strip().lower() not in ("", "false", "0", "no", "off")
        if isinstance(value, Mapping):
            return bool(value)
        return None


    def _read_gemini(scan: _Scan, home: Path, projects: list[Path], *, platform_name: str,
                     system_root: Path | None, env: Mapping[str, str]) -> dict[str, Any]:
        posture = empty_posture()
        posture["allow_rules"] = []
        posture["deny_rules_count"] = 0
        system = scan.config(_gemini_system_path(platform_name, system_root, env), "system", posture)
        docs: list[tuple[dict[str, Any], str]] = []
        for project in projects:
            doc = scan.config(project / GEMINI_PROJECT_SETTINGS, "project", posture)
            if doc is not None:
                docs.append((doc, "project"))
        user = scan.config(home / GEMINI_USER_SETTINGS, "user", posture)
        if user is not None:
            docs.append((user, "user"))
        every = ([(system, "managed")] if system is not None else []) + docs
        posture["managed_settings_present"] = system is not None

        nested = any(isinstance(doc.get(k), Mapping) for doc, _ in every for k in _GEMINI_NESTED_KEYS)
        flat = any(k in doc for doc, _ in every for k in _GEMINI_FLAT_KEYS)
        posture["settings_schema"] = "nested" if nested else ("flat" if flat else None)

        system_mode = _gemini_mode(_get(system, "general", "defaultApprovalMode"))
        if system_mode is not None:
            posture["permission_mode"], posture["permission_mode_source"] = system_mode, "managed"
        else:
            most = _Most(_GEMINI_MODE_RANK)
            for doc, scope in docs:
                most.offer(_gemini_mode(_get(doc, "general", "defaultApprovalMode")), scope)
            posture["permission_mode"], posture["permission_mode_source"] = most.value, most.source

        allow: list[str] = []
        for doc, _ in every:
            # tools.allowed: "Tool names that bypass the confirmation dialog".
            allow += _str_list(_get(doc, "tools", "allowed"))
            posture["deny_rules_count"] += len(_str_list(_get(doc, "tools", "exclude")))
        posture["allow_rules"] = _rule_list(allow)

        for doc, scope in every:
            if _get(doc, "security", "disableYoloMode") is True:
                posture["bypass_mode_disabled"], posture["bypass_mode_disabled_source"] = True, scope
                break
        else:
            posture["bypass_mode_disabled"] = False if every else None

        for doc, _ in every:
            value = _gemini_sandbox(_get(doc, "tools", "sandbox"))
            if value is None:
                value = _gemini_sandbox(doc.get("sandbox"))  # the legacy flat spelling
            if value is not None:
                posture["sandbox"]["enabled"] = value
                break
        for doc, _ in every:
            network = _get(doc, "tools", "sandboxNetworkAccess")
            if isinstance(network, bool):
                posture["sandbox"]["network_access"] = network
                break
        for doc, _ in every:
            trust = _get(doc, "security", "folderTrust", "enabled")
            if isinstance(trust, bool):
                posture["folder_trust_enabled"] = trust
                break
        posture["hooks_configured_count"] = sum(_count_hooks(_get(doc, "hooks")) for doc, _ in every)
        # ``managed_hooks_only`` stays None: Gemini CLI has no such setting (re-read at
        # google-gemini/gemini-cli 60f8082b14ff, 2026-11-26). The system file's hooks run beside the
        # person's (``MergeStrategy.CONCAT``), and the person can still switch one off by name.

        # ~/.gemini/trustedFolders.json: {path: "TRUST_FOLDER" | "TRUST_PARENT" | "DO_NOT_TRUST"}.
        trusted = scan.config(home / GEMINI_TRUSTED_FOLDERS, "user", posture)
        if trusted is not None:
            posture["trusted_projects_count"] = sum(1 for v in trusted.values() if v in ("TRUST_FOLDER", "TRUST_PARENT"))

        scan.rules_file(home / GEMINI_USER_RULES, "user", posture)
        for project in projects:
            _project_rules(scan, posture, project, GEMINI_PROJECT_RULES)
        return posture


    def _read_cursor(scan: _Scan, home: Path, projects: list[Path], *, platform_name: str,
                     system_root: Path | None) -> dict[str, Any]:
        """Cursor's CLI agent permissions and hooks, and the rules files of known projects.

        "~/.cursor/cli-config.json (global) or <project>/.cursor/cli.json (project-specific)",
        a ``permissions`` object with ``allow`` and ``deny`` lists of ``Shell(…)``, ``Read(…)``,
        ``Write(…)``, ``WebFetch(…)``, ``Mcp(server:tool)`` tokens
        (https://cursor.com/docs/cli/reference/permissions). The IDE's own auto-run setting lives in
        the application's state store and is not read: ``ide_auto_run`` says so.
        """
        posture = empty_posture()
        posture["allow_rules"] = []
        posture["deny_rules_count"] = 0
        posture["ide_auto_run"] = "unread"
        docs: list[dict[str, Any]] = []
        for project in projects:
            doc = scan.config(project / CURSOR_PROJECT_CLI, "project", posture)
            if doc is not None:
                docs.append(doc)
        user = scan.config(home / CURSOR_USER_CLI, "user", posture)
        if user is not None:
            docs.append(user)
        allow: list[str] = []
        for doc in docs:
            allow += _str_list(_get(doc, "permissions", "allow"))
            posture["deny_rules_count"] += len(_str_list(_get(doc, "permissions", "deny")))
        posture["allow_rules"] = _rule_list(allow)
        hooks = 0
        enterprise = scan.config(_cursor_enterprise_hooks(platform_name, system_root), "managed", posture)
        if enterprise is not None:
            posture["managed_settings_present"] = True
            hooks += _count_hooks(enterprise)
        user_hooks = scan.config(home / CURSOR_USER_HOOKS, "user", posture)
        if user_hooks is not None:
            hooks += _count_hooks(user_hooks)
        for project in projects:
            doc = scan.config(project / CURSOR_PROJECT_HOOKS, "project", posture)
            if doc is not None:
                hooks += _count_hooks(doc)
        posture["hooks_configured_count"] = hooks
        for project in projects:
            _project_rules(scan, posture, project, CURSOR_PROJECT_RULES)
        return posture


    def _read_copilot(scan: _Scan, home: Path) -> dict[str, Any]:
        """GitHub Copilot CLI: ``~/.copilot/config.json`` (its ``trusted_folders``) and its MCP file, counted."""
        posture = empty_posture()
        config = scan.config(home / COPILOT_USER_CONFIG, "user", posture)
        scan.config(home / COPILOT_USER_MCP, "user", posture)
        folders = _get(config, "trusted_folders")
        if isinstance(folders, list):
            posture["trusted_projects_count"] = len(folders)
        return posture


    # --- The snapshot ----------------------------------------------------------------------------


    def discover_agent_config_posture(
        tenant_id: str = "default",
        source_id: str = "agent-config-posture",
        *,
        include_paths: bool = False,
        home: Path | None = None,
        system_root: Path | None = None,
        platform_name: str | None = None,
        env: Mapping[str, str] | None = None,
    ) -> dict[str, Any]:
        """Scan this machine's coding-agent settings; return a discovery snapshot of facts.

        ``home``, ``system_root`` (re-roots every system path), ``platform_name`` and ``env``
        exist for tests; the sensor passes none of them.
        """
        root = home or Path.home()
        platform_name = platform_name or sys.platform
        env = os.environ if env is None else env
        scan = _Scan(include_paths=include_paths)
        observed_at = _now_iso()

        claude_global, projects, projects_note = _read_known_projects(root, env)
        codex_home = codex_home_dir(root, env)

        readers = {
            "claude_code": lambda: _read_claude_code(scan, root, projects, claude_global,
                                                     platform_name=platform_name, system_root=system_root),
            "codex": lambda: _read_codex(scan, root, projects, platform_name=platform_name,
                                         system_root=system_root, env=env),
            "gemini_cli": lambda: _read_gemini(scan, root, projects, platform_name=platform_name,
                                               system_root=system_root, env=env),
            "cursor": lambda: _read_cursor(scan, root, projects, platform_name=platform_name, system_root=system_root),
            "copilot_cli": lambda: _read_copilot(scan, root),
        }

        # The device's ``endpoint`` node is the MCP client walk's (it emits it on every scan, in
        # the same report); this scan draws its ``runs_local_agent`` edge to the same id and
        # mints no second copy of the node.
        endpoint_id = _entity_id("endpoint", _endpoint_fingerprint())
        entities: list[dict[str, Any]] = []
        edges: list[dict[str, Any]] = []
        for product, read in readers.items():
            try:
                posture = read()
            except Exception:  # noqa: BLE001 — one product's reader must not cost the others
                note = f"{PRODUCTS[product]}: reader_failed"
                if note not in scan.degraded:
                    scan.degraded.append(note)
                continue
            # A product is reported when it is INSTALLED for this user (its own directory or file
            # exists) or the organisation manages it here. A shared rules file (``AGENTS.md``) in a
            # project is not evidence that every product that could read it is installed.
            home_marker = codex_home if product == "codex" else root / PRODUCT_HOMES[product]
            managed_read = any(f["scope"] in ("managed", "system") for f in posture["files_read"])
            try:
                installed = home_marker.exists() or (product == "claude_code" and (root / ".claude.json").exists())
            except OSError:
                installed = False
            if not (installed or managed_read):
                continue
            anchor = root / ANCHOR_FILES[product]
            if product == "codex" and env.get("CODEX_HOME"):
                anchor = codex_home / "config.toml"
            path_hash = config_path_hash(anchor)
            agent_id = agent_entity_id(product, path_hash)
            attrs: dict[str, Any] = {
                "product": product,
                "connector_id": product_family(product),
                "last_seen": observed_at,
                "config_path_hash": path_hash,
                "config_filename": anchor.name,
                "provenance": "local_client_observed",
                "posture": posture,
            }
            entities.append({
                # Its own row beside the MCP walk's (``…:posture``): the store keys a row by its
                # external id and REPLACES its attrs, so sharing the walk's would erase one scan's
                # facts with the other's. The estate read folds both rows by ``entity_id``.
                "external_id": f"{product}:{path_hash[:16]}:posture",
                "entity_id": agent_id,
                "entity_type": "agent",
                "name": PRODUCTS[product],
                "platform": product,
                "source": source_id,
                "risk_score": 35,
                "last_seen": observed_at,
                "attrs": attrs,
            })
            edge_id = _entity_id("edge", endpoint_id, "runs_local_agent", agent_id)
            edges.append({"edge_id": edge_id, "from": endpoint_id, "to": agent_id,
                          "edge_type": "runs_local_agent", "attrs": {"product": product}})
        return {
            "tenant_id": tenant_id,
            "source_id": source_id,
            "connector_id": RUNTIME_FAMILY,
            "name": "Coding agent configuration posture",
            "category": SNAPSHOT_CATEGORY,
            "status": "active",
            "config": {
                "scan": SCAN_MARKER,
                "include_paths": include_paths,
                "scanned_files": scan.scanned_files,
                "degraded": scan.degraded,
                "projects": projects_note,
                "truncated": scan.truncated or bool(projects_note["truncated"]),
            },
            "entities": entities,
            "edges": edges,
            "findings": [],
        }

    return types.SimpleNamespace(**locals())


# ── a plugin's supply facts, copied from packages/compliance/mcp_launch.py (the least the
# extensions scan needs; the plaintext credential count is not copied, see its stand-in) ──

VERB_TABLE = (
    ('pypi', 'runner', 'uv\\s+tool\\s+run\\b'),
    ('pypi', 'runner', 'uvx\\b'),
    ('pypi', 'runner', 'pipx\\s+run\\b'),
    ('npm', 'runner', '(?:npx|bunx)\\b'),
    ('npm', 'runner', '(?:pnpm|yarn)\\s+dlx\\b'),
    ('npm', 'runner', 'npm\\s+(?:exec|x)\\b'),
    ('npm', 'runner', 'bun\\s+x\\b'),
    ('go', 'runner', 'go\\s+run\\b'),
)


import shlex


from collections.abc import Iterable, Mapping


MAX_ARGS = 256


MAX_NAME_CHARS = 214


MAX_DEPENDENCIES = 50


_RUNNERS: tuple[tuple[str, re.Pattern[str]], ...] = tuple(
    (eco, re.compile(r"(?:" + verb + r")", re.IGNORECASE)) for eco, kind, verb in VERB_TABLE if kind == "runner"
)


_CONTAINER_RUNTIMES = frozenset({"docker", "podman", "nerdctl"})


_SHELLS = frozenset({"sh", "bash", "zsh", "dash", "ash"})


_WINDOWS_SHELLS = frozenset({"cmd", "cmd.exe"})


_EXEC_SUFFIXES = (".cmd", ".exe", ".bat", ".ps1")


_PACKAGE_FLAGS = {"npm": frozenset({"-p", "--package"}), "pypi": frozenset({"--from", "--spec"}), "go": frozenset()}


_VALUE_FLAGS = {
    "npm": frozenset({"--node-options", "--registry", "--cache", "--userconfig", "--globalconfig", "--prefix",
                      "--workspace", "-w", "--call", "-c", "--loglevel", "--script-shell"}),
    "pypi": frozenset({"--with", "--with-editable", "--with-requirements", "--python", "-p", "--index",
                       "--index-url", "-i", "--extra-index-url", "--default-index", "--find-links", "-f",
                       "--constraints", "--constraint", "-c", "--overrides", "--cache-dir", "--directory",
                       "--project", "--config-file", "--pip-args", "--env-file", "--refresh-package",
                       "--reinstall-package", "--upgrade-package", "-P", "--index-strategy", "--keyring-provider",
                       "--resolution", "--prerelease", "--exclude-newer", "--link-mode", "--python-preference"}),
    "go": frozenset({"-exec", "-ldflags", "-tags", "-C", "-modfile", "-overlay", "-pgo", "-mod", "-o"}),
}


_CONTAINER_VALUE_FLAGS = frozenset({
    "-a", "--attach", "--add-host", "--annotation", "--blkio-weight", "--cap-add", "--cap-drop", "--cgroup-parent",
    "--cgroupns", "--cidfile", "--cpu-period", "--cpu-quota", "--cpu-shares", "-c", "--cpus", "--cpuset-cpus",
    "--cpuset-mems", "--device", "--device-cgroup-rule", "--dns", "--dns-option", "--dns-search", "--domainname",
    "--entrypoint", "-e", "--env", "--env-file", "--expose", "--gpus", "--group-add", "--health-cmd",
    "--health-interval", "--health-retries", "--health-start-period", "--health-timeout", "-h", "--hostname",
    "--ip", "--ip6", "--ipc", "--isolation", "--kernel-memory", "-l", "--label", "--label-file", "--link",
    "--log-driver", "--log-opt", "--mac-address", "-m", "--memory", "--memory-reservation", "--memory-swap",
    "--memory-swappiness", "--mount", "--name", "--network", "--net", "--network-alias", "--pid", "--pids-limit",
    "--platform", "-p", "--publish", "--pull", "--restart", "--runtime", "--security-opt", "--shm-size",
    "--stop-signal", "--stop-timeout", "--storage-opt", "--sysctl", "--tmpfs", "--ulimit", "-u", "--user",
    "--userns", "--uts", "-v", "--volume", "--volume-driver", "--volumes-from", "-w", "--workdir",
})


_NPM_NAME = re.compile(r"^(?:@[a-z0-9][a-z0-9._~-]*/)?[a-z0-9][a-z0-9._~-]*$")


_PYPI_NAME = re.compile(r"^[a-z0-9](?:[a-z0-9._-]*[a-z0-9])?$")


_GO_MODULE = re.compile(r"^[a-z0-9][a-z0-9._~-]*(?:/[A-Za-z0-9._~-]+)+$")


_SEMVER = re.compile(r"^v?=?(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)$")


_PEP440 = re.compile(r"^\d+(?:\.\d+)*(?:(?:a|b|rc)\d+)?(?:\.post\d+)?(?:\.dev\d+)?(?:\+[0-9a-z.]+)?$", re.IGNORECASE)


_RANGE_CHARS = frozenset("^~<>=*|, ")


_IMAGE_DIGEST = re.compile(r"^sha256:[0-9a-f]{64}$")


_IMAGE_REPO = re.compile(r"^[a-z0-9][a-z0-9._/:-]*$")


def _base(word: str) -> str:
    name = word.replace("\\", "/").rsplit("/", 1)[-1].lower()
    for suffix in _EXEC_SUFFIXES:
        if name.endswith(suffix):
            return name[: -len(suffix)]
    return name


def _split(line: str) -> list[str]:
    try:
        return shlex.split(line, posix=True)
    except ValueError:
        return line.split()


def _argv(command: str, args: Iterable[Any]) -> list[str]:
    """The program and its words, through the wrappers a client's config uses to start one: a
    Windows ``cmd /c``, a POSIX shell's ``-c``, ``env`` with its assignments."""
    words = [command, *(a for a in list(args)[:MAX_ARGS] if isinstance(a, str))]
    for _ in range(4):  # a wrapper inside a wrapper, bounded
        if not words:
            return []
        head = _base(words[0])
        rest = words[1:]
        if head in _WINDOWS_SHELLS and rest and rest[0].lower() in ("/c", "/k", "/s"):
            rest = [w for w in rest if w.lower() not in ("/c", "/k", "/s", "/d", "/q")]
            words = _split(rest[0]) + rest[1:] if len(rest) == 1 else rest
            continue
        if head in _SHELLS and rest and rest[0].startswith("-") and "c" in rest[0][1:] and len(rest) >= 2:
            words = _split(rest[1])
            continue
        if head == "env":
            rest = [w for w in rest if not (("=" in w and not w.startswith("-")) or w.startswith("-"))]
            words = rest
            continue
        break
    return [_base(words[0]), *words[1:]] if words else []


def _npm_spec(token: str) -> tuple[str | None, str, str | None, str]:
    """``(name, version_spec_kind, exact version, source)`` of an npm package word."""
    if token.startswith(("file:", "./", "../", "/", "~", ".")) or token.endswith((".tgz", ".tar.gz")):
        return None, "none", None, "local"
    if token.startswith(("git+", "git:", "github:", "gitlab:", "bitbucket:", "gist:")):
        return None, "none", None, "vcs"
    if token.startswith(("http://", "https://")):
        return None, "none", None, "url"
    at = token.find("@", 1)
    name, spec = (token[:at], token[at + 1:]) if at > 0 else (token, "")
    name = name.lower()
    if "/" in name and not name.startswith("@"):
        return None, "none", None, "vcs"  # user/repo is a GitHub repository to npm
    if len(name) > MAX_NAME_CHARS or not _NPM_NAME.fullmatch(name):
        return None, "none", None, "unreadable"
    return (name, *_semver_kind(spec), "registry")


def _semver_kind(spec: str) -> tuple[str, str | None]:
    if not spec:
        return "none", None
    exact = _SEMVER.fullmatch(spec)
    if exact:
        return "exact", exact.group(1)
    if any(c in _RANGE_CHARS for c in spec) or spec[0].isdigit() or spec.lower() in ("x", "*"):
        return "range", None
    return "dist_tag", None


def pep503(name: str) -> str:
    return re.sub(r"[-_.]+", "-", name).lower()


def _pypi_spec(token: str) -> tuple[str | None, str, str | None, str]:
    """``(name, version_spec_kind, exact version, source)`` of a PyPI requirement word."""
    if token.startswith(("./", "../", "/", "~", ".", "file:")) or token.endswith((".whl", ".tar.gz", ".zip")):
        return None, "none", None, "local"
    if token.startswith(("git+", "hg+", "svn+", "bzr+")):
        return None, "none", None, "vcs"
    if token.startswith(("http://", "https://")) or " @ " in token:
        return None, "none", None, "url"
    match = re.match(r"^([A-Za-z0-9][A-Za-z0-9._-]*)(\[[^\]]{0,200}\])?(.*)$", token)
    if not match or len(match.group(1)) > MAX_NAME_CHARS:
        return None, "none", None, "unreadable"
    name, spec = pep503(match.group(1)), match.group(3).strip()
    if not _PYPI_NAME.fullmatch(name):
        return None, "none", None, "unreadable"
    if not spec:
        return name, "none", None, "registry"
    if spec.startswith("@"):  # uv's ``tool@version`` / ``tool@latest``
        version = spec[1:]
        if _PEP440.fullmatch(version):
            return name, "exact", version, "registry"
        return name, "dist_tag", None, "registry"
    for op in ("===", "=="):
        if spec.startswith(op) and "," not in spec and "*" not in spec and _PEP440.fullmatch(spec[len(op):].strip()):
            return name, "exact", spec[len(op):].strip(), "registry"
    return name, "range", None, "registry"


def _go_spec(token: str) -> tuple[str | None, str, str | None, str]:
    if token.startswith((".", "/")):
        return None, "none", None, "local"
    module, _, version = token.partition("@")
    if not _GO_MODULE.fullmatch(module) or len(module) > MAX_NAME_CHARS:
        return None, "none", None, "unreadable"
    if not version:
        return module, "none", None, "registry"
    if version.startswith("v") and _SEMVER.fullmatch(version):
        return module, "exact", version, "registry"
    return module, "dist_tag", None, "registry"


_SPEC_READERS = {"npm": _npm_spec, "pypi": _pypi_spec, "go": _go_spec}


def _runner_package(eco: str, words: list[str]) -> str | None:
    """The package word a runner fetches: a package flag's value, else its first word."""
    named: str | None = None
    pending: str | None = None
    calls = False
    for word in words:
        if pending is not None:
            what, pending = pending, None
            if what == "package" and named is None:
                named = word
            continue
        if word == "--":
            continue
        if word.startswith("-"):
            flag, eq, value = word.partition("=")
            if flag in _PACKAGE_FLAGS.get(eco, ()):
                if eq:
                    named = named or value
                else:
                    pending = "package"
            elif flag in ("--call", "-c") and eco == "npm":
                calls = True
                pending = None if eq else "value"
            elif flag in _VALUE_FLAGS.get(eco, ()) and not eq:
                pending = "value"
            continue
        return named or word
    return named if (named or calls) else None


def _image_ref(ref: str) -> dict[str, Any]:
    """An image reference as ``repository``, ``tag`` and whether a digest pins it."""
    repo, _, digest = ref.partition("@")
    tag = None
    slash = repo.rfind("/")
    colon = repo.rfind(":")
    if colon > slash:
        repo, tag = repo[:colon], repo[colon + 1:]
    repo = repo.lower()
    if not repo or len(repo) > 255 or not _IMAGE_REPO.fullmatch(repo):
        return {"package": None, "source": "unreadable", "version": None, "version_spec_kind": "none",
                "pinned": None}
    if digest and _IMAGE_DIGEST.fullmatch(digest):
        return {"package": repo, "source": "registry", "version": tag, "image_digest": digest,
                "version_spec_kind": "digest", "pinned": True}
    return {"package": repo, "source": "registry", "version": tag, "image_digest": None,
            "version_spec_kind": "tag" if tag else "none", "pinned": False}


def _container(runtime: str, words: list[str]) -> dict[str, Any] | None:
    if not words or words[0] not in ("run", "container"):
        return None
    words = words[1:]
    if words and words[0] == "run":
        words = words[1:]
    pending = False
    for word in words:
        if pending:
            pending = False
            continue
        if word.startswith("-"):
            flag, eq, _ = word.partition("=")
            pending = flag in _CONTAINER_VALUE_FLAGS and not eq
            continue
        return {"launch_kind": "container", "runner": f"{runtime} run", "ecosystem": "docker", **_image_ref(word)}
    return None


def launch_facts(command: Any, args: Any = None, url: Any = None) -> dict[str, Any]:
    """What one MCP server's launch resolves to. Pure, never raises; keeps no argument text."""
    out: dict[str, Any] = {
        "launch_kind": "unknown", "runner": None, "program": None, "ecosystem": None, "package": None,
        "version": None, "version_spec_kind": None, "pinned": None, "source": None,
    }
    if not isinstance(command, str) or not command.strip():
        if isinstance(url, str) and url.strip():
            out["launch_kind"] = "remote"
        return out
    argv = _argv(command, args if isinstance(args, list) else [])
    if not argv:
        return out
    out["program"] = argv[0][:64]
    if argv[0] in _CONTAINER_RUNTIMES:
        found = _container(argv[0], argv[1:])
        if found is not None:
            out.update(found)
            return out
    head = " ".join(argv[:3])
    for eco, rx in _RUNNERS:
        match = rx.match(head)
        if match is None or (match.end() < len(head) and head[match.end()] != " "):
            continue
        taken = len(match.group(0).split())
        word = _runner_package(eco, argv[taken:])
        out.update({"launch_kind": "package_runner", "runner": " ".join(match.group(0).lower().split()),
                    "ecosystem": eco})
        if word is None:
            out.update({"source": "unreadable", "version_spec_kind": "none"})
            return out
        name, spec_kind, version, source = _SPEC_READERS[eco](word)
        out.update({"package": name, "version": version, "source": source,
                    "version_spec_kind": spec_kind if name else None,
                    "pinned": (spec_kind == "exact") if name else None})
        return out
    out["launch_kind"] = "binary"
    return out


def server_supply_facts(server_cfg: Any) -> dict[str, Any]:
    """:func:`launch_facts` and :func:`plaintext_secret_facts` of one server config."""
    cfg = server_cfg if isinstance(server_cfg, Mapping) else {}
    command = cfg.get("command")
    args = cfg.get("args")
    if isinstance(command, Mapping):
        args = args if isinstance(args, list) else command.get("args")
        command = command.get("path")
    url = cfg.get("url") or cfg.get("serverUrl") or cfg.get("endpoint")
    return {"launch": launch_facts(command, args, url), **plaintext_secret_facts(cfg)}


def _short(value: Any) -> str | None:
    return value[:200] if isinstance(value, str) and value else None


def plugin_dependency_facts(manifest: Any) -> list[dict[str, Any]]:
    """A plugin manifest's declared ``dependencies``: each ``{name, marketplace, version}``."""
    deps = manifest.get("dependencies") if isinstance(manifest, Mapping) else None
    out: list[dict[str, Any]] = []
    for dep in deps if isinstance(deps, list) else []:
        if len(out) >= MAX_DEPENDENCIES:
            break
        if isinstance(dep, str) and dep:
            name, _, marketplace = dep.partition("@")
            out.append({"name": _short(name), "marketplace": _short(marketplace), "version": None})
        elif isinstance(dep, Mapping) and _short(dep.get("name")):
            out.append({"name": _short(dep.get("name")), "marketplace": _short(dep.get("marketplace")),
                        "version": _short(dep.get("version"))})
    return out


def supply_digest(launches: Iterable[Mapping[str, Any]], dependencies: Iterable[Mapping[str, Any]]) -> str | None:
    """A digest of what a plugin fetches and depends on, or ``None`` when it states neither.

    The extension approvals record keeps it beside an approved plugin's manifest digest, so a
    plugin whose MCP server now launches another package or version is asked about again
    (``packages/compliance/extension_approvals``)."""
    keys = ("server_name", "launch_kind", "runner", "ecosystem", "package", "version", "version_spec_kind")
    rows = sorted(json.dumps({k: launch.get(k) for k in keys}, sort_keys=True) for launch in launches)
    deps = sorted(json.dumps(dict(d), sort_keys=True) for d in dependencies)
    if not rows and not deps:
        return None
    return hashlib.sha256(json.dumps({"launches": rows, "dependencies": deps}).encode("utf-8")).hexdigest()


def plaintext_secret_facts(server_cfg: Any) -> dict[str, Any]:
    """``mcp_launch.plaintext_secret_facts`` is not copied (it needs the secret bank) and the
    bundle never carries its count: this reads no value and counts nothing."""
    return {"plaintext_secret_count": 0, "plaintext_secret_locations": [], "plaintext_secret_kinds": [],
            "plaintext_secrets_truncated": False}


# ── packages/compliance/agent_extensions_discovery.py, copied whole ─────────

def _agent_extensions_module():
    """packages.compliance.agent_extensions_discovery, copied whole; answers its module namespace."""
    import hashlib  # noqa: F401
    import json  # noqa: F401
    import os  # noqa: F401
    import plistlib  # noqa: F401
    import re  # noqa: F401
    import shlex  # noqa: F401
    import sys  # noqa: F401
    tomllib = _TOMLLIB
    import unicodedata  # noqa: F401
    from pathlib import Path  # noqa: F401
    from typing import Any, Iterable, Mapping  # noqa: F401


    #: The snapshot category, read by ``endpoint_sensor_scans`` and the ingest route's accept list.
    SNAPSHOT_CATEGORY = "agent_runtime"

    #: The finding kinds the node mints from this scan's facts, and only from them.
    FINDING_KINDS: tuple[str, ...] = (
        "agent_hook_suspicious",
        "agent_hook_unmanaged",
        "agent_skill_hidden_text",
        "agent_skill_broad_tools",
        "agent_skill_runs_shell",
        "agent_plugin_unknown_marketplace",
    )

    #: ``config.scan`` on this scan's snapshot: how the node tells a COMPLETE extensions scan
    #: that found nothing (its findings clear) from another scan's ``agent_runtime`` snapshot.
    SCAN_MARKER = "agent_extensions"

    EXTENSION_KINDS: tuple[str, ...] = ("skill", "subagent", "command", "plugin", "hook")
    SCOPES: tuple[str, ...] = ("managed", "user", "project", "plugin")
    HOOK_TYPES: frozenset[str] = frozenset({"command", "http", "prompt", "mcp_tool", "agent"})

    #: The file whose ``agent_entity_id`` each product's extensions attach to: the config
    #: ``local_agent_discovery`` reads first for that product, so the extension hangs off the
    #: agent node the MCP client walk already draws.
    PRIMARY_CONFIG: dict[str, str] = {
        "claude_code": ".claude.json",
        "cursor": ".cursor/mcp.json",
        "codex": ".codex/config.toml",
    }

    #: Hook events that fire before the model reads anything of the session: a hook here
    #: shapes what the model is told, or sees every prompt.
    BEFORE_MODEL_READS_EVENTS: frozenset[str] = frozenset({
        "SessionStart", "UserPromptSubmit", "UserPromptExpansion", "Setup", "InstructionsLoaded",
        "sessionStart", "beforeSubmitPrompt",
    })

    NETWORK_RE = re.compile(
        r"\b(?:curl|wget|nc|ncat|socat|Invoke-WebRequest|iwr|irm|Invoke-RestMethod)\b|/dev/tcp/",
        re.IGNORECASE,
    )
    EVAL_RE = re.compile(
        r"\beval\b|\biex\b|Invoke-Expression|base64\s+(?:-d|--decode|-D)\b|\bpython3?\s+-c\b"
        r"|\s-enc(?:odedcommand)?\b|\b(?:sh|bash|zsh)\s+-c\b|\|\s*(?:sudo\s+)?(?:sh|bash|zsh)\b",
        re.IGNORECASE,
    )
    #: ``!`command``` at a line start or after whitespace, and a fenced block opened with ```!.
    _INLINE_SHELL_RE = re.compile(r"(?:^|(?<=\s))!`[^`\n]+`", re.MULTILINE)
    _FENCED_SHELL_RE = re.compile(r"^[ \t]*```!", re.MULTILINE)

    MAX_EXTENSIONS = 500
    MAX_TEXT_BYTES = 64 * 1024
    MAX_DIGEST_BYTES = 8 * 1024 * 1024
    MAX_CONFIG_BYTES = 32 * 1024 * 1024
    MAX_PROJECTS = 50
    MAX_DIR_ENTRIES = 200
    MAX_COMMAND_DEPTH = 3
    MAX_SCANNED_FILES = 400
    MAX_LIST_ITEMS = 50
    _LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1", "[::1]"})


    # --- Where things live ------------------------------------------------------------------


    def default_system_paths() -> dict[str, list[Path]]:
        """The machine-wide locations, per OS; a test passes its own."""
        if sys.platform == "darwin":
            claude = [Path("/Library/Application Support/ClaudeCode")]
            plist = [Path("/Library/Managed Preferences/com.anthropic.claudecode.plist")]
            user = os.environ.get("USER")
            if user:
                plist.insert(0, Path("/Library/Managed Preferences") / user / "com.anthropic.claudecode.plist")
            cursor = [Path("/Library/Application Support/Cursor/hooks.json")]
            codex = [Path("/etc/codex/requirements.toml")]
        elif os.name == "nt":
            pf = Path(os.environ.get("ProgramFiles") or r"C:\Program Files")
            pd = Path(os.environ.get("ProgramData") or r"C:\ProgramData")
            claude = [pf / "ClaudeCode"]
            plist = []
            cursor = [pd / "Cursor" / "hooks.json"]
            codex = [pd / "OpenAI" / "Codex" / "requirements.toml"]
        else:
            claude = [Path("/etc/claude-code")]
            plist = []
            cursor = [Path("/etc/cursor/hooks.json")]
            codex = [Path("/etc/codex/requirements.toml")]
        return {"claude_managed_dirs": claude, "claude_managed_plists": plist,
                "cursor_enterprise_hooks": cursor, "codex_requirements": codex}


    # --- Hidden text ----------------------------------------------------------------------------

    _ZWJ = 0x200D
    _BOM = 0xFEFF
    _COMMENT_RE = re.compile(r"<!--(.*?)(?:-->|$)", re.DOTALL)


    def _emoji_side(ch: str) -> bool:
        cp = ord(ch)
        return unicodedata.category(ch) in ("So", "Sk") or cp == 0xFE0F or 0x1F3FB <= cp <= 0x1F3FF


    def hidden_text_facts(text: str) -> dict[str, Any]:
        """Counts of text a reviewer does not see; never the text.

        ``invisible`` and ``hidden_markers`` are the node inspectors' own counts
        (``invisible_text``). Two narrower counts are what a finding rests on, because the
        broad ones fire on ordinary files (measured 2026-10-14 over 546 installed and
        marketplace markdown files on a developer laptop: a framing marker in 8.1 % (the
        visible ``IMPORTANT:``), an HTML comment in 5.6 %, zero-width characters in 2, both
        of them the joiner inside an emoji sequence):

        * ``invisible_suspect``: invisible characters other than a zero-width joiner between
          two emoji parts and a byte-order mark at the very start;
        * ``markers_in_comments``: framing markers INSIDE an HTML comment, the text a
          rendered view hides and the model reads (0 of the 546).
        """
        inv = count_invisible(text)
        suspect = inv["total"]
        if suspect and isinstance(text, str):
            for i, ch in enumerate(text):
                cp = ord(ch)
                if cp == _BOM and i == 0:
                    suspect -= 1
                elif cp == _ZWJ and 0 < i < len(text) - 1 and _emoji_side(text[i - 1]) and _emoji_side(text[i + 1]):
                    suspect -= 1
        forms = {"colon": 0, "bracket": 0, "tag": 0, "comment": 0}
        in_comments = 0
        if isinstance(text, str) and text:
            for m in HIDDEN_MARKER.finditer(text):
                g = m.group(0)
                forms["comment" if g.startswith("<!--") else "tag" if g.startswith("<")
                      else "bracket" if g.startswith("[") else "colon"] += 1
            for m in _COMMENT_RE.finditer(text):
                in_comments += count_hidden_markers(m.group(1))
        return {
            "invisible": inv,
            "invisible_suspect": max(suspect, 0),
            "hidden_markers": count_hidden_markers(text),
            "hidden_marker_forms": forms,
            "markers_in_comments": in_comments,
        }


    # --- Small readers ----------------------------------------------------------------------


    def _sha256(data: bytes) -> str:
        return hashlib.sha256(data).hexdigest()


    def _id_hash(*parts: str) -> str:
        return hashlib.sha1("|".join(parts).encode("utf-8"), usedforsecurity=False).hexdigest()


    class _Scan:
        """One scan's accumulators and bounds."""

        def __init__(self, *, home: Path, include_paths: bool, observed_at: str, source_id: str) -> None:
            self.home = home
            self.include_paths = include_paths
            self.observed_at = observed_at
            self.source_id = source_id
            self.entities: dict[str, dict[str, Any]] = {}
            self.edges: dict[str, dict[str, Any]] = {}
            self.agents: dict[str, str] = {}
            self.scanned: list[dict[str, Any]] = []
            self.degraded: list[str] = []
            self.truncated = False
            self.policy: dict[str, dict[str, Any]] = {}

        # -- bookkeeping --
        def note(self, path: Path, error: str | None, *, parsed: bool) -> None:
            if len(self.scanned) < MAX_SCANNED_FILES:
                self.scanned.append({
                    "path_hash": config_path_hash(path),
                    "path": str(path) if self.include_paths else None,
                    "filename": path.name,
                    "exists": True,
                    "parsed": parsed,
                    "error": error,
                })
            if error:
                msg = f"{path.name}: {error}"
                if msg not in self.degraded:
                    self.degraded.append(msg)

        def full(self) -> bool:
            if len(self.entities) >= MAX_EXTENSIONS:
                if not self.truncated:
                    self.truncated = True
                    self.degraded.append(f"extension cap reached: {MAX_EXTENSIONS} reported, the rest not read")
                return True
            return False

        def agent_for(self, product: str) -> str:
            if product in self.agents:
                return self.agents[product]
            primary = self.home / PRIMARY_CONFIG.get(product, ".claude.json")
            path_hash = config_path_hash(primary)
            agent_id = agent_entity_id(product, path_hash)
            self.agents[product] = agent_id
            family = product_family(product)
            attrs: dict[str, Any] = {
                "product": product,
                "connector_id": family,
                "last_seen": self.observed_at,
                "config_path_hash": path_hash,
                "config_filename": primary.name,
                "provenance": "local_client_observed",
            }
            # A distinct external id, so this row never overwrites the client walk's own row
            # for the agent (the store keys rows on it); the merged read folds the two by id.
            self.entities[agent_id] = {
                "external_id": f"{product}:{path_hash[:16]}:extensions",
                "entity_id": agent_id,
                "entity_type": "agent",
                "name": product_name(product),
                "platform": product,
                "source": self.source_id,
                "risk_score": 35,
                "last_seen": self.observed_at,
                "attrs": attrs,
            }
            return agent_id

        def add(self, draft: dict[str, Any], *, product: str, kind: str, scope: str,
                discriminator: str) -> dict[str, Any] | None:
            """Add one extension from its ``{"name", "attrs"}`` draft; a second copy counts as ``copies``.

            Each caller writes its draft's ``attrs`` as a literal dict, so the console's attrs-key
            inventory (``scripts/gen_discovery_attrs_fixture.py``) reads every key this scan sends.
            """
            if self.full():
                return None
            digest = _id_hash(product, kind, scope, discriminator)
            entity_id = f"agent_extension:{digest[:20]}"
            existing = self.entities.get(entity_id)
            if existing is not None:
                existing["attrs"]["copies"] = int(existing["attrs"].get("copies") or 1) + 1
                return existing
            agent_id = self.agent_for(product)
            name = str(draft.get("name") or "?")[:200]
            # A mapping or nothing: a scalar attrs would be returned by ``or {}`` and raise
            # on the first key written below (tests/test_discovery_attrs_is_always_a_mapping.py).
            draft_attrs = draft.get("attrs")
            entity: dict[str, Any] = {
                "external_id": f"{product}:{kind}:{name}:{digest[:12]}",
                "entity_id": entity_id,
                "entity_type": "agent_extension",
                "name": name,
                "platform": product,
                "source": self.source_id,
                "risk_score": 0,
                "last_seen": self.observed_at,
                "attrs": dict(draft_attrs) if isinstance(draft_attrs, Mapping) else {},
            }
            entity["attrs"]["extension_kind"] = kind
            entity["attrs"]["product"] = product
            entity["attrs"]["connector_id"] = product_family(product)
            entity["attrs"]["scope"] = scope
            entity["attrs"]["agent_entity_id"] = agent_id
            entity["attrs"]["provenance"] = "local_client_observed"
            entity["attrs"]["last_seen"] = self.observed_at
            self.entities[entity_id] = entity
            edge_id = "edge:" + _id_hash(agent_id, "loads_extension", entity_id)[:20]
            self.edges[edge_id] = {
                "edge_id": edge_id, "from": agent_id, "to": entity_id, "edge_type": "loads_extension",
                "attrs": {"extension_kind": kind, "scope": scope},
            }
            return entity


    def _read_bytes(path: Path) -> tuple[bytes | None, int, str | None, bool]:
        """``(head, size, digest, digest_truncated)``; head is at most ``MAX_TEXT_BYTES``. Never raises."""
        try:
            size = path.stat().st_size
            h = hashlib.sha256()
            head = b""
            read = 0
            with path.open("rb") as fh:
                while read < MAX_DIGEST_BYTES:
                    chunk = fh.read(min(65536, MAX_DIGEST_BYTES - read))
                    if not chunk:
                        break
                    if len(head) < MAX_TEXT_BYTES:
                        head += chunk[: MAX_TEXT_BYTES - len(head)]
                    h.update(chunk)
                    read += len(chunk)
            over = size > MAX_DIGEST_BYTES
            return head, size, (None if over else h.hexdigest()), over
        except OSError:
            return None, 0, None, False


    def _load_mapping(scan: _Scan, path: Path, *, fmt: str = "json") -> dict[str, Any] | None:
        """Parse one JSON/TOML file into a mapping; a failure is a closed code on ``degraded``."""
        try:
            if not path.is_file():
                return None
            if path.stat().st_size > MAX_CONFIG_BYTES:
                scan.note(path, "unreadable", parsed=False)
                return None
            raw = path.read_bytes()
        except OSError:
            scan.note(path, "unreadable", parsed=False)
            return None
        try:
            text = raw.decode("utf-8-sig")
        except UnicodeDecodeError:
            scan.note(path, "not_utf8", parsed=False)
            return None
        try:
            data = tomllib.loads(text) if fmt == "toml" else json.loads(_strip_jsonc(text))
        except Exception:  # noqa: BLE001 — the category is what a reader can act on
            scan.note(path, "unparsable", parsed=False)
            return None
        if not isinstance(data, dict):
            scan.note(path, "not_a_mapping", parsed=False)
            return None
        scan.note(path, None, parsed=True)
        return data


    def _strip_jsonc(text: str) -> str:
        """Drop ``//`` and ``/* */`` comments outside strings (settings files allow them)."""
        if "/" not in text:
            return text
        out: list[str] = []
        i, n, in_str = 0, len(text), False
        while i < n:
            ch = text[i]
            if in_str:
                out.append(ch)
                if ch == "\\" and i + 1 < n:
                    out.append(text[i + 1])
                    i += 2
                    continue
                if ch == '"':
                    in_str = False
            elif ch == '"':
                in_str = True
                out.append(ch)
            elif text.startswith("//", i):
                j = text.find("\n", i)
                i = n if j < 0 else j
                continue
            elif text.startswith("/*", i):
                j = text.find("*/", i + 2)
                i = n if j < 0 else j + 2
                continue
            else:
                out.append(ch)
            i += 1
        return "".join(out)


    # --- Frontmatter --------------------------------------------------------------------------

    _KEY_RE = re.compile(r"^([A-Za-z0-9_.-]+)\s*:(.*)$")


    def _scalar(value: str) -> str:
        v = value.strip()
        if len(v) >= 2 and v[0] == v[-1] and v[0] in "'\"":
            return v[1:-1]
        hash_at = v.find(" #")
        if hash_at >= 0:
            v = v[:hash_at].rstrip()
        return v


    def _flow_list(value: str) -> list[str]:
        """``[a, 'b c', Bash(x, y)]``: split on commas outside quotes and parentheses."""
        inner = value.strip()[1:-1]
        parts: list[str] = []
        buf: list[str] = []
        depth, quote = 0, ""
        for ch in inner:
            if quote:
                if ch == quote:
                    quote = ""
            elif ch in "'\"":
                quote = ch
            elif ch == "(":
                depth += 1
            elif ch == ")" and depth:
                depth -= 1
            elif ch == "," and depth == 0:
                parts.append("".join(buf))
                buf = []
                continue
            buf.append(ch)
        parts.append("".join(buf))
        return [_scalar(p) for p in parts if _scalar(p)]


    def read_frontmatter(text: str) -> tuple[dict[str, Any], str]:
        """``(fields, body)`` of a markdown file's ``---`` block, by a tiny YAML-ish reader.

        Understands ``key: value``, ``key: [a, b]``, a ``- item`` list under a key, ``|``/``>``
        block scalars, and keeps any other nested block as ``{"__block__": [lines]}``. Never
        imports ``yaml`` (this module is stdlib-only) and never raises.
        """
        stripped = text.lstrip("\ufeff")
        lines = stripped.split("\n")
        if not lines or lines[0].strip() != "---":
            return {}, text
        end = None
        for i in range(1, min(len(lines), 2000)):
            if lines[i].strip() in ("---", "..."):
                end = i
                break
        if end is None:
            return {}, text
        block = lines[1:end]
        body = "\n".join(lines[end + 1:])
        fields: dict[str, Any] = {}
        i = 0
        while i < len(block):
            line = block[i].rstrip("\r")
            m = _KEY_RE.match(line) if line and not line[0].isspace() and not line.startswith("#") else None
            if not m:
                i += 1
                continue
            key, rest = m.group(1), m.group(2).strip()
            children: list[str] = []
            j = i + 1
            while j < len(block) and (not block[j].strip() or block[j][:1].isspace() or block[j].lstrip().startswith("- ")
                                      and block[j][:1] == "-"):
                children.append(block[j].rstrip("\r"))
                j += 1
            if rest in ("|", ">", "|-", ">-", "|+", ">+"):
                fields[key] = "\n".join(c.strip() for c in children)
            elif rest.startswith("[") and rest.endswith("]"):
                fields[key] = _flow_list(rest)
            elif rest:
                fields[key] = _scalar(rest)
            else:
                items = [c.strip() for c in children if c.strip()]
                if items and all(it.startswith("- ") or it == "-" for it in items):
                    fields[key] = [_scalar(it[1:]) for it in items if _scalar(it[1:])]
                else:
                    fields[key] = {"__block__": children}
            i = j
        return fields, body


    def _split_tools(value: str) -> list[str]:
        """Split a tool list on commas and whitespace, never inside parentheses: ``Bash(git add:*)``."""
        out: list[str] = []
        buf: list[str] = []
        depth = 0
        for ch in value:
            if ch == "(":
                depth += 1
            elif ch == ")" and depth:
                depth -= 1
            if depth == 0 and (ch == "," or ch.isspace()):
                if buf:
                    out.append("".join(buf))
                    buf = []
                continue
            buf.append(ch)
        if buf:
            out.append("".join(buf))
        return [t.strip() for t in out if t.strip()]


    def _tools(value: Any) -> list[str]:
        if isinstance(value, list):
            out: list[str] = []
            for v in value:
                if isinstance(v, str):
                    out.extend(_split_tools(v) if "(" not in v else [v.strip()])
            return out[:MAX_LIST_ITEMS]
        if isinstance(value, str):
            return _split_tools(value)[:MAX_LIST_ITEMS]
        return []


    def _bool(value: Any) -> bool | None:
        if isinstance(value, bool):
            return value
        if isinstance(value, str) and value.strip().lower() in ("true", "yes", "on"):
            return True
        if isinstance(value, str) and value.strip().lower() in ("false", "no", "off"):
            return False
        return None


    # --- Text facts ---------------------------------------------------------------------------


    def _read_text(scan: _Scan, path: Path) -> tuple[str, int, str | None, bool] | None:
        """``(text read, size, digest, truncated)`` of an extension file, or ``None`` if unreadable."""
        head, size, digest, over = _read_bytes(path)
        if head is None:
            scan.note(path, "unreadable", parsed=False)
            return None
        try:
            text = head.decode("utf-8")
            error = None
        except UnicodeDecodeError:
            text = head.decode("utf-8", errors="replace")
            error = "not_utf8"
        scan.note(path, error, parsed=error is None)
        return text, size, digest, size > MAX_TEXT_BYTES or over


    def _markdown_extension(scan: _Scan, path: Path, *, product: str, kind: str, scope: str,
                            plugin: str | None = None, marketplace: str | None = None,
                            default_name: str | None = None) -> None:
        got = _read_text(scan, path)
        if got is None:
            return
        text, size, digest, truncated = got
        fm, body = read_frontmatter(text)
        path_hash = config_path_hash(path)
        name = fm.get("name") if isinstance(fm.get("name"), str) and fm.get("name") else (default_name or path.stem)
        hooks_fm = fm.get("hooks")
        hook_lines = (hooks_fm.get("__block__") or []) if isinstance(hooks_fm, dict) else []
        hook_text = "\n".join(line for line in hook_lines if "command" in line or "url" in line or "prompt" in line)
        attrs: dict[str, Any] = {
            "source_path_hash": path_hash,
            "filename": path.name,
            "content_digest": digest,
            "bytes": size,
            "truncated": truncated,
            **hidden_text_facts(text),
            "plugin": plugin,
            "marketplace": marketplace,
            "allowed_tools": _tools(fm.get("allowed-tools")),
            "disallowed_tools": _tools(fm.get("disallowed-tools") if "disallowed-tools" in fm else fm.get("disallowedTools")),
            "disable_model_invocation": _bool(fm.get("disable-model-invocation")),
            "user_invocable": _bool(fm.get("user-invocable")),
            "shell_frontmatter": "shell" in fm,
            "inline_shell_commands": len(_INLINE_SHELL_RE.findall(body)) + len(_FENCED_SHELL_RE.findall(body)),
            "hooks_in_frontmatter": bool(hooks_fm),
            "frontmatter_hook_references_network": bool(NETWORK_RE.search(hook_text)),
            "frontmatter_hook_references_eval": bool(EVAL_RE.search(hook_text)),
            "context": fm.get("context") if isinstance(fm.get("context"), str) else None,
        }
        if kind == "subagent":
            attrs["tools"] = _tools(fm.get("tools"))
            pm = fm.get("permissionMode")
            attrs["permission_mode"] = pm if isinstance(pm, str) else None
        if scan.include_paths:
            attrs["source_path"] = str(path)
        discriminator = path_hash if scope != "project" else f"{name}|{digest}"
        scan.add({"name": name, "attrs": attrs}, product=product, kind=kind, scope=scope, discriminator=discriminator)


    def _listdir(path: Path) -> list[Path]:
        try:
            return sorted(path.iterdir())[:MAX_DIR_ENTRIES]
        except OSError:
            return []


    def _skills_dir(scan: _Scan, root: Path, *, product: str, scope: str, plugin: str | None = None,
                    marketplace: str | None = None, policy: Mapping[str, Any] | None = None) -> None:
        """``<root>/<name>/SKILL.md`` each; a ``.claude-plugin/plugin.json`` directory is a plugin."""
        for child in _listdir(root):
            if scan.full():
                return
            try:
                if not child.is_dir():
                    continue
                if plugin is None and (child / ".claude-plugin" / "plugin.json").is_file():
                    _plugin_dir(scan, child, plugin_id=None, marketplace="skills-dir",
                                install_scope=scope, policy=policy)
                    continue
                skill = child / "SKILL.md"
                if skill.is_file():
                    _markdown_extension(scan, skill, product=product, kind="skill", scope=scope,
                                        plugin=plugin, marketplace=marketplace, default_name=child.name)
            except OSError:
                continue


    def _markdown_dir(scan: _Scan, root: Path, *, product: str, kind: str, scope: str, plugin: str | None = None,
                      marketplace: str | None = None, depth: int = 0) -> None:
        for child in _listdir(root):
            if scan.full():
                return
            try:
                if child.is_dir() and kind == "command" and depth < MAX_COMMAND_DEPTH:
                    _markdown_dir(scan, child, product=product, kind=kind, scope=scope, plugin=plugin,
                                  marketplace=marketplace, depth=depth + 1)
                elif child.is_file() and child.suffix.lower() == ".md":
                    _markdown_extension(scan, child, product=product, kind=kind, scope=scope,
                                        plugin=plugin, marketplace=marketplace)
            except OSError:
                continue


    # --- Hooks --------------------------------------------------------------------------------


    def iter_hook_handlers(block: Any) -> Iterable[tuple[str, str | None, dict[str, Any]]]:
        """``(event, matcher, handler)`` for every handler in a hooks block, whatever the product.

        Claude Code and Codex nest ``event -> [{matcher, hooks: [handler]}]``; Cursor lists
        handlers directly under the event. A shape that is neither yields nothing.
        """
        if not isinstance(block, Mapping):
            return
        for event, groups in block.items():
            if not isinstance(event, str) or not isinstance(groups, list):
                continue
            for group in groups[:MAX_DIR_ENTRIES]:
                if not isinstance(group, Mapping):
                    continue
                matcher = group.get("matcher") if isinstance(group.get("matcher"), str) else None
                inner = group.get("hooks")
                if isinstance(inner, list):
                    for handler in inner[:MAX_DIR_ENTRIES]:
                        if isinstance(handler, Mapping):
                            yield event, matcher, dict(handler)
                elif any(k in group for k in ("command", "url", "prompt", "type", "server")):
                    yield event, matcher, dict(group)


    def program_basename(command: str) -> str | None:
        """The program a hook command runs, as a basename: ``/usr/bin/python3 x.py`` -> ``python3``."""
        if not isinstance(command, str) or not command.strip():
            return None
        try:
            # A Windows path's backslashes are separators, not escapes: read it the non-POSIX way.
            tokens = shlex.split(command, posix="\\" not in command)
        except ValueError:
            tokens = command.split()
        for tok in (t.strip("'\"") for t in tokens):
            if re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", tok) or tok in ("env", "sudo", "exec", "nohup", "command"):
                continue
            base = re.split(r"[\\/]", tok)[-1]
            return base[:64] or None
        return None


    def _host(url: Any) -> str | None:
        if not isinstance(url, str):
            return None
        m = re.match(r"^[a-zA-Z][a-zA-Z0-9+.-]*://(?:[^/@?#]*@)?(\[[^\]]+\]|[^/:?#]+)", url.strip())
        return m.group(1).lower() if m else None


    def hook_facts(event: str, matcher: str | None, handler: Mapping[str, Any]) -> dict[str, Any]:
        """The facts of one hook handler; never its command line."""
        raw_type = handler.get("type")
        command = handler.get("command") if isinstance(handler.get("command"), str) else None
        hook_type = raw_type if raw_type in HOOK_TYPES else ("command" if command else None)
        url = handler.get("url") if isinstance(handler.get("url"), str) else None
        prompt = handler.get("prompt") if isinstance(handler.get("prompt"), str) else None
        url_host = _host(url)
        text = "\n".join(t for t in (command, prompt, url) if t)
        network = bool(command and NETWORK_RE.search(command)) or (
            hook_type == "http" and url_host is not None and url_host not in _LOOPBACK_HOSTS)
        return {
            "hook_events": [event],
            "hook_matcher": matcher[:200] if matcher else None,
            "hook_type": hook_type,
            "hook_command_program": program_basename(command) if command else None,
            "hook_command_digest": _sha256(command.encode("utf-8")) if command else None,
            "hook_url_host": url_host,
            "hook_mcp_server": handler.get("server") if isinstance(handler.get("server"), str) else None,
            "hook_mcp_tool": handler.get("tool") if isinstance(handler.get("tool"), str) else None,
            "references_network": network,
            "references_eval": bool(command and EVAL_RE.search(command)),
            "runs_before_model_reads": event in BEFORE_MODEL_READS_EVENTS,
            **hidden_text_facts(text),
        }


    def _hooks_block(scan: _Scan, block: Any, *, path: Path, product: str, scope: str,
                     plugin: str | None = None, marketplace: str | None = None) -> None:
        file_hash = config_path_hash(path)
        for event, matcher, handler in iter_hook_handlers(block):
            if scan.full():
                return
            attrs = {
                "source_path_hash": file_hash,
                "filename": path.name,
                "plugin": plugin,
                "marketplace": marketplace,
                **hook_facts(event, matcher, handler),
            }
            if scan.include_paths:
                attrs["source_path"] = str(path)
            key = attrs["hook_command_digest"] or _sha256(json.dumps(handler, sort_keys=True, default=str).encode())
            where = file_hash if scope != "project" else "project"
            scan.add({"name": event, "attrs": attrs}, product=product, kind="hook", scope=scope,
                     discriminator=f"{where}|{event}|{matcher or ''}|{key}")


    # --- Plugins ------------------------------------------------------------------------------


    def _manifest_paths(root: Path, value: Any) -> list[Path]:
        """Component paths a manifest names, kept inside the plugin directory."""
        items = value if isinstance(value, list) else [value]
        out: list[Path] = []
        try:
            base = root.resolve()
        except OSError:
            return out
        for item in items[:MAX_LIST_ITEMS]:
            if not isinstance(item, str) or "\\" in item:
                continue
            try:
                p = (root / item).resolve()
            except OSError:
                continue
            if p == base or base in p.parents:
                out.append(p)
        return out


    def _plugin_dir(scan: _Scan, root: Path, *, plugin_id: str | None, marketplace: str | None,
                    install_scope: str, version: str | None = None, enabled: bool | None = None,
                    policy: Mapping[str, Any] | None = None) -> None:
        """One plugin: its own entity, then its components under scope ``plugin``. Never raises."""
        manifest_path = root / ".claude-plugin" / "plugin.json"
        manifest = _load_mapping(scan, manifest_path) if manifest_path.is_file() else None
        manifest = manifest or {}
        id_name = plugin_id.split("@", 1)[0] if plugin_id else None
        name = id_name or (manifest.get("name") if isinstance(manifest.get("name"), str) else None) or root.name
        product = "claude_code"
        components: dict[str, int] = {k: 0 for k in ("skill", "subagent", "command", "hook")}
        before = {k: sum(1 for e in scan.entities.values()
                         if e.get("entity_type") == "agent_extension" and e["attrs"].get("extension_kind") == k)
                  for k in components}

        skills_roots = _manifest_paths(root, manifest["skills"]) if "skills" in manifest else [root / "skills"]
        for sroot in skills_roots:
            _skills_dir(scan, sroot, product=product, scope="plugin", plugin=name, marketplace=marketplace)
        if not (root / "skills").is_dir() and "skills" not in manifest and (root / "SKILL.md").is_file():
            _markdown_extension(scan, root / "SKILL.md", product=product, kind="skill", scope="plugin",
                                plugin=name, marketplace=marketplace, default_name=name)
        for kind, folder in (("subagent", "agents"), ("command", "commands")):
            roots = _manifest_paths(root, manifest[folder]) if folder in manifest else [root / folder]
            for r in roots:
                if r.is_file():
                    _markdown_extension(scan, r, product=product, kind=kind, scope="plugin", plugin=name,
                                        marketplace=marketplace)
                else:
                    _markdown_dir(scan, r, product=product, kind=kind, scope="plugin", plugin=name,
                                  marketplace=marketplace)
        hooks_value = manifest.get("hooks")
        if isinstance(hooks_value, Mapping):
            _hooks_block(scan, hooks_value.get("hooks", hooks_value), path=manifest_path, product=product,
                         scope="plugin", plugin=name, marketplace=marketplace)
        hook_files = _manifest_paths(root, hooks_value) if isinstance(hooks_value, (str, list)) else []
        if (root / "hooks" / "hooks.json").is_file():
            hook_files.append(root / "hooks" / "hooks.json")
        for hf in hook_files:
            data = _load_mapping(scan, hf)
            if data is not None:
                _hooks_block(scan, data.get("hooks"), path=hf, product=product, scope="plugin",
                             plugin=name, marketplace=marketplace)
        mcp = _load_mapping(scan, root / ".mcp.json") if (root / ".mcp.json").is_file() else None
        servers = mcp.get("mcpServers", mcp) if isinstance(mcp, Mapping) else {}
        if isinstance(manifest.get("mcpServers"), Mapping):
            servers = {**(servers if isinstance(servers, Mapping) else {}), **manifest["mcpServers"]}
        # S5 (supply chain): what each of the plugin's MCP servers launches, the plaintext
        # credentials its configs hold (counted, never sent) and the plugins it depends on.
        launches: list[dict[str, Any]] = []
        plugin_secrets = 0
        for server_name, server_cfg in sorted(servers.items(), key=lambda kv: str(kv[0])) if isinstance(servers, Mapping) else []:
            if len(launches) >= MAX_LIST_ITEMS:
                break
            supply = server_supply_facts(server_cfg)
            plugin_secrets += int(supply["plaintext_secret_count"])
            launches.append({"server_name": str(server_name)[:200], **supply["launch"]})
        dependencies = plugin_dependency_facts(manifest)
        for k in components:
            components[k] = sum(1 for e in scan.entities.values()
                                if e.get("entity_type") == "agent_extension" and e["attrs"].get("extension_kind") == k) - before[k]

        source = (policy or {}).get("marketplace_sources", {}).get(marketplace) if marketplace else None
        allow = (policy or {}).get("strict_known_marketplaces")
        attrs: dict[str, Any] = {
            "source_path_hash": config_path_hash(root),
            "filename": root.name,
            "plugin": name,
            "plugin_id": plugin_id or (f"{name}@{marketplace}" if marketplace else name),
            "marketplace": marketplace,
            "install_scope": install_scope,
            "version": str(version)[:64] if version else (str(manifest.get("version"))[:64] if manifest.get("version") else None),
            "enabled": enabled,
            "manifest_found": bool(manifest),
            "manifest_digest": _read_bytes(manifest_path)[2] if manifest_path.is_file() else None,
            "components": components,
            "mcp_servers": sorted(str(s) for s in servers)[:MAX_LIST_ITEMS] if isinstance(servers, Mapping) else [],
            "marketplace_source": public_source(source),
            "marketplace_registered": bool(marketplace and (
                marketplace in (policy or {}).get("marketplace_sources", {})
                or marketplace in (policy or {}).get("extra_known_marketplaces", []))),
            "marketplace_in_extra_known": bool(marketplace and marketplace in (policy or {}).get("extra_known_marketplaces", [])),
            "strict_known_marketplaces_set": allow is not None,
            "marketplace_allowed": marketplace_allowed(marketplace, source, allow),
            "mcp_server_launches": launches,
            "mcp_server_plaintext_secret_count": plugin_secrets,
            "declared_dependencies": dependencies,
            "supply_digest": supply_digest(launches, dependencies),
        }
        if scan.include_paths:
            attrs["source_path"] = str(root)
        scope = "managed" if (policy or {}).get("managed_enabled_plugins", {}).get(attrs["plugin_id"]) is True else (
            "project" if install_scope in ("project", "local") else "user")
        scan.add({"name": name, "attrs": attrs}, product=product, kind="plugin", scope=scope,
                 discriminator=f"{attrs['plugin_id']}|{install_scope}")


    def public_source(source: Any) -> dict[str, Any] | None:
        """A marketplace source as it may leave the laptop: the repo, a host, or a path HASH."""
        if not isinstance(source, Mapping):
            return None
        kind = source.get("source") if isinstance(source.get("source"), str) else None
        out: dict[str, Any] = {"source": kind}
        if kind == "github" and isinstance(source.get("repo"), str):
            out["repo"] = source["repo"][:200]
        elif kind in ("git", "url"):
            out["host"] = _host(source.get("url"))
        elif kind in ("file", "directory") and isinstance(source.get("path"), str):
            out["path_hash"] = config_path_hash(source["path"])
        return out


    def _source_host(source: Mapping[str, Any]) -> str | None:
        kind = source.get("source")
        if kind == "github":
            return "github.com"
        if kind in ("git", "url"):
            return _host(source.get("url"))
        return None


    def _same(a: Mapping[str, Any], b: Mapping[str, Any], key: str) -> bool:
        return a.get(key) == b.get(key)


    def marketplace_allowed(marketplace: str | None, source: Any, allowlist: Any) -> bool | None:
        """Whether a marketplace's SOURCE passes a ``strictKnownMarketplaces`` allowlist.

        ``None`` when no allowlist is set (nothing to pass). The documented matching rules:
        exact ``repo``/``url``/``path`` with ``ref`` and ``path`` equal or absent on both sides;
        a ``github`` ``owner/*`` wildcard for every repo of that owner; ``hostPattern`` and
        ``pathPattern`` as regular expressions searched in the host or path; ``skills-dir``
        for skills-directory plugins. A source this laptop cannot read matches nothing.
        """
        if not isinstance(allowlist, list):
            return None
        if marketplace == "skills-dir":
            return any(isinstance(e, Mapping) and e.get("source") == "skills-dir" for e in allowlist)
        if not isinstance(source, Mapping):
            return False
        kind = source.get("source")
        for entry in allowlist:
            if not isinstance(entry, Mapping):
                continue
            ek = entry.get("source")
            try:
                if ek == "hostPattern" and isinstance(entry.get("hostPattern"), str):
                    host = _source_host(source)
                    if host and re.search(entry["hostPattern"], host):
                        return True
                elif ek == "pathPattern" and isinstance(entry.get("pathPattern"), str):
                    if kind in ("file", "directory") and isinstance(source.get("path"), str) \
                            and re.search(entry["pathPattern"], source["path"]):
                        return True
                elif ek == kind == "github":
                    repo, want = source.get("repo"), entry.get("repo")
                    if not isinstance(repo, str) or not isinstance(want, str):
                        continue
                    if want.endswith("/*") and "/" in repo and want.count("/") == 1:
                        if repo.split("/", 1)[0] == want[:-2] and _same(entry, source, "ref") and (
                                "path" not in entry or _same(entry, source, "path")):
                            return True
                    elif repo == want and _same(entry, source, "ref") and _same(entry, source, "path"):
                        return True
                elif ek == kind == "git":
                    if _same(entry, source, "url") and _same(entry, source, "ref") and _same(entry, source, "path"):
                        return True
                elif ek == kind == "url":
                    if _same(entry, source, "url"):
                        return True
                elif ek == kind and kind in ("file", "directory"):
                    if _same(entry, source, "path"):
                        return True
            except re.error:
                continue
        return False


    # --- Managed policy -----------------------------------------------------------------------


    def _read_plist(scan: _Scan, path: Path) -> dict[str, Any] | None:
        try:
            if not path.is_file():
                return None
            with path.open("rb") as fh:
                data = plistlib.load(fh)
        except OSError:
            scan.note(path, "unreadable", parsed=False)
            return None
        except Exception:  # noqa: BLE001
            scan.note(path, "unparsable", parsed=False)
            return None
        if not isinstance(data, dict):
            scan.note(path, "not_a_mapping", parsed=False)
            return None
        scan.note(path, None, parsed=True)
        return data


    def _read_windows_policy(scan: _Scan) -> dict[str, Any] | None:
        if os.name != "nt":
            return None
        try:
            import winreg  # stdlib on Windows only
            with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Policies\ClaudeCode") as key:  # type: ignore[attr-defined]
                value, _ = winreg.QueryValueEx(key, "Settings")  # type: ignore[attr-defined]
        except OSError:
            return None
        except Exception:  # noqa: BLE001
            return None
        try:
            data = json.loads(value) if isinstance(value, str) else None
        except ValueError:
            scan.degraded.append("HKLM ClaudeCode Settings: unparsable")
            return None
        return data if isinstance(data, dict) else None


    def claude_managed_documents(scan: _Scan, system: Mapping[str, list[Path]]) -> list[tuple[str, dict[str, Any], Path]]:
        """Every managed document present, in Claude Code's precedence order (OS policy, then files)."""
        docs: list[tuple[str, dict[str, Any], Path]] = []
        for plist in system.get("claude_managed_plists", []):
            data = _read_plist(scan, plist)
            if data is not None:
                docs.append(("plist", data, plist))
        reg = _read_windows_policy(scan)
        if reg is not None:
            docs.append(("hklm", reg, Path("HKLM/SOFTWARE/Policies/ClaudeCode")))
        for root in system.get("claude_managed_dirs", []):
            dropins = root / "managed-settings.d"
            for f in sorted(p for p in _listdir(dropins) if p.suffix.lower() == ".json"):
                data = _load_mapping(scan, f)
                if data is not None:
                    docs.append(("file", data, f))
            main = root / "managed-settings.json"
            data = _load_mapping(scan, main) if main.is_file() else None
            if data is not None:
                docs.append(("file", data, main))
        return docs


    def _first(docs: list[tuple[str, dict[str, Any], Path]], *keys: str) -> Any:
        for _, data, _ in docs:
            for key in keys:
                if key in data:
                    return data[key]
        return None


    # --- The scan ----------------------------------------------------------------------------


    def _known_projects(scan: _Scan, claude_json: Mapping[str, Any] | None, codex: Mapping[str, Any] | None) -> list[Path]:
        names: list[str] = []
        for source in (claude_json, codex):
            projects = source.get("projects") if isinstance(source, Mapping) else None
            if isinstance(projects, Mapping):
                names.extend(str(k) for k in projects)
        out: list[Path] = []
        seen: set[str] = set()
        for name in names:
            if name in seen:
                continue
            seen.add(name)
            p = Path(name).expanduser()
            try:
                if p.is_dir() and p != scan.home:
                    out.append(p)
            except OSError:
                continue
            if len(out) >= MAX_PROJECTS:
                scan.degraded.append(f"project cap reached: the first {MAX_PROJECTS} known projects read")
                break
        return out


    def _claude_settings_hooks(scan: _Scan, path: Path, *, scope: str, data: Mapping[str, Any] | None = None) -> dict[str, Any] | None:
        data = data if data is not None else (_load_mapping(scan, path) if path.is_file() else None)
        if data is not None:
            _hooks_block(scan, data.get("hooks"), path=path, product="claude_code", scope=scope)
        return dict(data) if data is not None else None


    def _scan_claude_code(scan: _Scan, system: Mapping[str, list[Path]], projects: list[Path],
                          claude_json: Mapping[str, Any] | None) -> None:
        home = scan.home
        docs = claude_managed_documents(scan, system)
        user_settings = _load_mapping(scan, home / ".claude" / "settings.json") if (home / ".claude" / "settings.json").is_file() else None
        managed_plugins = _first(docs, "enabledPlugins")
        strict = _first(docs, "strictKnownMarketplaces", "allowedMarketplaces")
        extra: list[str] = []
        for d in [*(doc for _, doc, _ in docs), user_settings or {}]:
            for key in ("extraKnownMarketplaces", "additionalMarketplaces"):
                if isinstance(d.get(key), Mapping):
                    extra.extend(str(k) for k in d[key])
        plugins_root = home / ".claude" / "plugins"
        known = _load_mapping(scan, plugins_root / "known_marketplaces.json") if (plugins_root / "known_marketplaces.json").is_file() else None
        sources: dict[str, Any] = {}
        for name, entry in (known or {}).items():
            if isinstance(entry, Mapping):
                sources[str(name)] = entry.get("source")
        for d in [*(doc for _, doc, _ in docs), user_settings or {}]:
            for key in ("extraKnownMarketplaces", "additionalMarketplaces"):
                for name, entry in (d.get(key) or {}).items() if isinstance(d.get(key), Mapping) else ():
                    if isinstance(entry, Mapping) and str(name) not in sources:
                        sources[str(name)] = entry.get("source")
        strict_custom = _first(docs, "strictPluginOnlyCustomization")
        policy: dict[str, Any] = {
            "managed_settings_present": bool(docs),
            "managed_hooks_only": _bool(_first(docs, "allowManagedHooksOnly")),
            "hooks_disabled_managed": _bool(_first(docs, "disableAllHooks")) is True,
            "hooks_disabled_user": _bool((user_settings or {}).get("disableAllHooks")) is True,
            "skill_shell_disabled": _bool(_first(docs, "disableSkillShellExecution")) is True
            or _bool((user_settings or {}).get("disableSkillShellExecution")) is True,
            "plugin_only_customization": (
                ["skills", "agents", "hooks", "mcp"] if strict_custom is True
                else [str(x) for x in strict_custom if isinstance(x, str)] if isinstance(strict_custom, list) else []),
            "strict_known_marketplaces_set": isinstance(strict, list),
            "extra_known_marketplaces": sorted(set(extra))[:MAX_LIST_ITEMS],
        }
        scan.policy["claude_code"] = policy
        plugin_policy = {
            "marketplace_sources": sources,
            "extra_known_marketplaces": extra,
            "strict_known_marketplaces": strict if isinstance(strict, list) else None,
            "managed_enabled_plugins": managed_plugins if isinstance(managed_plugins, Mapping) else {},
        }

        # Managed: hooks in each managed document, skills/agents/commands under <dir>/.claude.
        for _, data, path in docs:
            _hooks_block(scan, data.get("hooks"), path=path, product="claude_code", scope="managed")
        for mdir in system.get("claude_managed_dirs", []):
            base = mdir / ".claude"
            _skills_dir(scan, base / "skills", product="claude_code", scope="managed", policy=plugin_policy)
            _markdown_dir(scan, base / "agents", product="claude_code", kind="subagent", scope="managed")
            _markdown_dir(scan, base / "commands", product="claude_code", kind="command", scope="managed")

        # User.
        base = home / ".claude"
        _claude_settings_hooks(scan, base / "settings.json", scope="user", data=user_settings)
        _skills_dir(scan, base / "skills", product="claude_code", scope="user", policy=plugin_policy)
        _markdown_dir(scan, base / "agents", product="claude_code", kind="subagent", scope="user")
        _markdown_dir(scan, base / "commands", product="claude_code", kind="command", scope="user")

        # Installed plugins.
        enabled_user = (user_settings or {}).get("enabledPlugins")
        installed = _load_mapping(scan, plugins_root / "installed_plugins.json") if (plugins_root / "installed_plugins.json").is_file() else None
        records = installed.get("plugins", installed) if isinstance(installed, Mapping) else {}
        for plugin_id, entries in (records.items() if isinstance(records, Mapping) else ()):
            if scan.full():
                break
            if not isinstance(plugin_id, str) or plugin_id == "version":
                continue
            marketplace = plugin_id.split("@", 1)[1] if "@" in plugin_id else None
            for entry in (entries if isinstance(entries, list) else [entries])[:10]:
                if not isinstance(entry, Mapping) or not isinstance(entry.get("installPath"), str):
                    continue
                root = Path(entry["installPath"]).expanduser()
                try:
                    if not root.is_dir():
                        scan.degraded.append(f"{plugin_id}: install directory missing")
                        continue
                except OSError:
                    continue
                enabled = None
                if isinstance(managed_plugins, Mapping) and isinstance(managed_plugins.get(plugin_id), bool):
                    enabled = managed_plugins[plugin_id]
                elif isinstance(enabled_user, Mapping) and isinstance(enabled_user.get(plugin_id), bool):
                    enabled = enabled_user[plugin_id]
                _plugin_dir(scan, root, plugin_id=plugin_id, marketplace=marketplace,
                            install_scope=str(entry.get("scope") or "user"), version=entry.get("version"),
                            enabled=enabled, policy=plugin_policy)
        for root in _listdir(plugins_root / "synced"):
            if scan.full():
                break
            if root.is_dir():
                _plugin_dir(scan, root, plugin_id=f"{root.name}@synced", marketplace="synced",
                            install_scope="user", policy=plugin_policy)

        # Projects.
        for project in projects:
            if scan.full():
                break
            base = project / ".claude"
            if not base.is_dir():
                continue
            for fname in ("settings.json", "settings.local.json"):
                _claude_settings_hooks(scan, base / fname, scope="project")
            _skills_dir(scan, base / "skills", product="claude_code", scope="project", policy=plugin_policy)
            _markdown_dir(scan, base / "agents", product="claude_code", kind="subagent", scope="project")
            _markdown_dir(scan, base / "commands", product="claude_code", kind="command", scope="project")


    def _scan_cursor(scan: _Scan, system: Mapping[str, list[Path]], projects: list[Path]) -> None:
        managed = False
        for path in system.get("cursor_enterprise_hooks", []):
            data = _load_mapping(scan, path) if path.is_file() else None
            if data is not None:
                managed = True
                _hooks_block(scan, data.get("hooks"), path=path, product="cursor", scope="managed")
        targets = [(scan.home / ".cursor" / "hooks.json", "user")] + [(p / ".cursor" / "hooks.json", "project") for p in projects]
        for path, scope in targets:
            data = _load_mapping(scan, path) if path.is_file() else None
            if data is not None:
                _hooks_block(scan, data.get("hooks"), path=path, product="cursor", scope=scope)
        # Cursor has no managed-only lock for hooks: the concept is absent, not "off".
        scan.policy["cursor"] = {"managed_settings_present": managed, "managed_hooks_only": None}


    def _scan_codex(scan: _Scan, system: Mapping[str, list[Path]], projects: list[Path],
                    codex_config: Mapping[str, Any] | None) -> None:
        managed_doc: Mapping[str, Any] | None = None
        for path in system.get("codex_requirements", []):
            data = _load_mapping(scan, path, fmt="toml") if path.is_file() else None
            if data is not None:
                managed_doc = data
                _hooks_block(scan, data.get("hooks"), path=path, product="codex", scope="managed")
        home_codex = scan.home / ".codex"
        if codex_config is not None:
            _hooks_block(scan, codex_config.get("hooks"), path=home_codex / "config.toml", product="codex", scope="user")
        targets: list[tuple[Path, str, str]] = [(home_codex / "hooks.json", "user", "json")]
        for p in projects:
            targets += [(p / ".codex" / "hooks.json", "project", "json"), (p / ".codex" / "config.toml", "project", "toml")]
        for path, scope, fmt in targets:
            data = _load_mapping(scan, path, fmt=fmt) if path.is_file() else None
            if data is not None:
                _hooks_block(scan, data.get("hooks"), path=path, product="codex", scope=scope)
        scan.policy["codex"] = {
            "managed_settings_present": managed_doc is not None,
            "managed_hooks_only": _bool((managed_doc or {}).get("allow_managed_hooks_only")) if managed_doc is not None else None,
        }


    def discover_agent_extensions(
        tenant_id: str = "default",
        source_id: str = "agent-extensions",
        *,
        include_paths: bool = False,
        home: Path | str | None = None,
        system_paths: Mapping[str, list[Path]] | None = None,
    ) -> dict[str, Any]:
        """Scan this machine's coding-agent extensions; return a discovery snapshot of facts.

        ``home`` and ``system_paths`` exist for tests (a planted home, planted managed files);
        the sensor passes neither. Never raises: a source that cannot be read is a closed code
        on ``config.degraded`` and the rest of the scan goes on.
        """
        from datetime import datetime, timezone

        root = Path(home).expanduser() if home is not None else Path.home()
        observed_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
        scan = _Scan(home=root, include_paths=include_paths, observed_at=observed_at, source_id=source_id)
        system = system_paths if system_paths is not None else default_system_paths()
        claude_json = None
        codex_config = None
        projects: list[Path] = []
        for step in ("claude_json", "codex_config", "claude_code", "cursor", "codex"):
            try:
                if step == "claude_json":
                    cj = root / ".claude.json"
                    claude_json = _load_mapping(scan, cj) if cj.is_file() else None
                elif step == "codex_config":
                    cc = root / ".codex" / "config.toml"
                    codex_config = _load_mapping(scan, cc, fmt="toml") if cc.is_file() else None
                    projects = _known_projects(scan, claude_json, codex_config)
                elif step == "claude_code":
                    _scan_claude_code(scan, system, projects, claude_json)
                elif step == "cursor":
                    _scan_cursor(scan, system, projects)
                else:
                    _scan_codex(scan, system, projects, codex_config)
            except Exception as exc:  # noqa: BLE001 — one product's failure costs that product only
                scan.degraded.append(f"{step}: scan failed ({type(exc).__name__})")
        # Every agent that loads something carries the policy facts the node reads.
        for product, agent_id in scan.agents.items():
            scan.entities[agent_id]["attrs"]["extension_policy"] = dict(scan.policy.get(product) or {})
        counts = {k: 0 for k in EXTENSION_KINDS}
        for e in scan.entities.values():
            if e["entity_type"] == "agent_extension":
                counts[e["attrs"]["extension_kind"]] += 1
        families = sorted({product_family(p) for p in scan.agents})
        return {
            "tenant_id": tenant_id,
            "source_id": source_id,
            "connector_id": families[0] if len(families) == 1 else RUNTIME_FAMILY,
            "name": "Coding agent extensions",
            "category": SNAPSHOT_CATEGORY,
            "status": "active",
            "config": {
                "scan": SCAN_MARKER,
                "include_paths": include_paths,
                "scanned_files": scan.scanned,
                "degraded": scan.degraded,
                "truncated": scan.truncated,
                "extension_counts": counts,
            },
            "entities": list(scan.entities.values()),
            "edges": list(scan.edges.values()),
            "findings": [],
        }

    return types.SimpleNamespace(**locals())


# ── the reduction and the screen every free string passes, copied from services/assessment/app/laptop_scan.py ──

REDUCED = '…'
WILDCARD_ARGUMENTS = frozenset({
    '*',
    '**',
    '**:*',
    '*:*',
    '*:**',
    '/**',
    '//*',
    '//**',
    '//**/*',
    ':*',
    'domain:*',
    '~/*',
    '~/**',
    '~/**/*',
})
_RULE_FORM = re.compile('\\s*[A-Za-z0-9_*\\-]+\\s*(?:\\((.*)\\))?\\s*', re.S)
_RULE_NAME = re.compile('\\s*([A-Za-z0-9_*\\-]*)')
_MATCHER_ALTERNATIVE = re.compile('[A-Za-z0-9_*^$()\\-]*(?:\\.[*+?][A-Za-z0-9_*^$()\\-]*)*')
_WORD = re.compile('[A-Za-z][A-Za-z0-9_\\-]{0,63}')
POSTURE_RULE_FIELDS = (
    'allow_rules',
)
EXTENSION_RULE_FIELDS = (
    'allowed_tools',
    'disallowed_tools',
    'tools',
)
EXTENSION_WORD_FIELDS = (
    'context',
    'permission_mode',
)
DECLARED_FIELDS = {
    'agent_extension_agents': {'product': None, 'config_filename': None, 'config_hash': None, 'extension_policy': 'extension_policy'},
    'agent_extensions': {'id': None, 'product': None, 'kind': None, 'scope': None, 'name': None, 'attrs': 'extension.attrs'},
    'agent_postures': {'product': None, 'config_filename': None, 'config_hash': None, 'posture': 'posture'},
    'agent_scans': {'scan': None, 'complete': None, 'truncated': None},
    'components': {'skill': None, 'subagent': None, 'command': None, 'hook': None},
    'extension.attrs': {'source_path_hash': None, 'filename': None, 'plugin': None, 'marketplace': None, 'copies': None, 'content_digest': None, 'bytes': None, 'truncated': None, 'invisible': 'invisible', 'invisible_suspect': None, 'hidden_markers': None, 'hidden_marker_forms': 'hidden_marker_forms', 'markers_in_comments': None, 'allowed_tools': None, 'disallowed_tools': None, 'disable_model_invocation': None, 'user_invocable': None, 'shell_frontmatter': None, 'inline_shell_commands': None, 'hooks_in_frontmatter': None, 'frontmatter_hook_references_network': None, 'frontmatter_hook_references_eval': None, 'context': None, 'tools': None, 'permission_mode': None, 'hook_events': None, 'hook_matcher': None, 'hook_type': None, 'hook_command_program': None, 'hook_command_digest': None, 'hook_url_host': None, 'hook_mcp_server': None, 'hook_mcp_tool': None, 'references_network': None, 'references_eval': None, 'runs_before_model_reads': None, 'plugin_id': None, 'install_scope': None, 'version': None, 'enabled': None, 'manifest_found': None, 'manifest_digest': None, 'components': 'components', 'mcp_servers': None, 'marketplace_source': 'marketplace_source', 'marketplace_registered': None, 'marketplace_in_extra_known': None, 'strict_known_marketplaces_set': None, 'marketplace_allowed': None},
    'extension_policy': {'managed_settings_present': None, 'managed_hooks_only': None, 'hooks_disabled_managed': None, 'hooks_disabled_user': None, 'skill_shell_disabled': None, 'plugin_only_customization': None, 'strict_known_marketplaces_set': None, 'extra_known_marketplaces': None},
    'hidden_marker_forms': {'colon': None, 'bracket': None, 'tag': None, 'comment': None},
    'invisible': {'zero_width': None, 'bidi': None, 'tag': None, 'total': None},
    'marketplace_source': {'source': None, 'repo': None, 'host': None, 'path_hash': None},
    'posture': {'schema': None, 'files_read': 'posture.files_read', 'permission_mode': None, 'permission_mode_source': None, 'allow_rules': None, 'deny_rules_count': None, 'ask_rules_count': None, 'bypass_mode_disabled': None, 'bypass_mode_disabled_source': None, 'skip_dangerous_prompt': None, 'sandbox': 'posture.sandbox', 'project_mcp_auto_approved': None, 'project_mcp_auto_approved_source': None, 'managed_settings_present': None, 'managed_hooks_only': None, 'managed_permission_rules_only': None, 'hooks_configured_count': None, 'trusted_projects_count': None, 'folder_trust_enabled': None, 'rules_files': 'posture.rules_files', 'ide_auto_run': None, 'settings_schema': None},
    'posture.files_read': {'path_hash': None, 'filename': None, 'scope': None, 'parsed': None, 'error': None},
    'posture.rules_files': {'path_hash': None, 'filename': None, 'scope': None, 'bytes': None, 'truncated': None, 'invisible': 'invisible', 'hidden_markers': None, 'invisible_suspect': None, 'markers_in_comments': None},
    'posture.sandbox': {'enabled': None, 'auto_allow': None, 'unsandboxed_retry': None, 'mode': None, 'network_access': None},
}


def keep_declared(value: Any, section: str) -> Any:
    """*value* with every key its section does not declare dropped, at every depth.

    The scans the script carries whole write more facts than the bundle carries (a plugin's
    supply facts: the packages and versions its MCP servers launch, a count of plaintext
    credentials in their configs, its declared dependencies, a digest of them). A fact the
    bundle does not declare stays on the laptop: it is dropped here, before anything is
    written, rather than sent for this reader to refuse. Anything not a mapping, or a
    section this table does not hold, is returned as it is (the reader then judges it)."""
    fields = DECLARED_FIELDS.get(section)
    if fields is None or not isinstance(value, dict):
        return value
    out: dict[str, Any] = {}
    for key, item in value.items():
        if key not in fields:
            continue
        child = fields[key]
        if child is not None and isinstance(item, list):
            item = [keep_declared(element, child) for element in item]
        elif child is not None:
            item = keep_declared(item, child)
        out[key] = item
    return out


def reduce_rule(rule: str) -> str:
    """A permission rule or tool entry reduced to its tool name and the shape of its argument."""
    form = _RULE_FORM.fullmatch(rule)
    if form is not None and (form.group(1) is None or form.group(1).strip() in WILDCARD_ARGUMENTS):
        return rule.strip()
    name = _RULE_NAME.match(rule).group(1)  # type: ignore[union-attr]
    return f"{name}({REDUCED})" if name else REDUCED


def reduce_matcher(matcher: str) -> str:
    """A hook matcher with every alternative that is not a tool-name pattern replaced by ``…``."""
    return "|".join(a if _MATCHER_ALTERNATIVE.fullmatch(a) else REDUCED for a in matcher.split("|"))


def reduce_word(value: Any) -> Any:
    """*value* when it is one word, else ``None``."""
    return value if isinstance(value, str) and _WORD.fullmatch(value) else None


def reduce_posture(posture: Any) -> Any:
    """A posture with only its declared facts (:func:`keep_declared`) and every rule list
    reduced (:func:`reduce_rule`)."""
    if not isinstance(posture, dict):
        return posture
    out = keep_declared(posture, "posture")
    for key in POSTURE_RULE_FIELDS:
        if isinstance(out.get(key), list):
            out[key] = [reduce_rule(r) if isinstance(r, str) else r for r in out[key]]
    return out


def reduce_extension_attrs(attrs: Any) -> Any:
    """An extension's declared facts (:func:`keep_declared`) with its tool lists, hook matcher
    and free words reduced."""
    if not isinstance(attrs, dict):
        return attrs
    out = keep_declared(attrs, "extension.attrs")
    for key in EXTENSION_RULE_FIELDS:
        if isinstance(out.get(key), list):
            out[key] = [reduce_rule(r) if isinstance(r, str) else r for r in out[key]]
    if isinstance(out.get("hook_matcher"), str):
        out["hook_matcher"] = reduce_matcher(out["hook_matcher"])
    for key in EXTENSION_WORD_FIELDS:
        if key in out:
            out[key] = reduce_word(out[key])
    return out


def reduce_extension_policy(policy: Any) -> Any:
    """A coding agent's extension policy with only its declared facts (:func:`keep_declared`)."""
    return keep_declared(policy, "extension_policy")


PATH_TOKEN = re.compile('(?<![\\w:/.\\\\~])(?:~|[A-Za-z]:[\\\\/]|/|\\\\\\\\)[^\\s()\'\\"`,;|&<>]*')
PATH_PLACEHOLDER = '[path]'
_CONTROL = re.compile('[\\x00-\\x1f\\x7f]')
EXTENSION_RECOMPUTED_ATTRS = (
    'extension_kind',
    'product',
    'connector_id',
    'scope',
    'agent_entity_id',
    'provenance',
    'last_seen',
)


def screen_text(value: str) -> str:
    """*value* with every path that names something replaced by ``[path]`` and every control
    character by a space."""
    def _one(match: Any) -> str:
        token = match.group(0)
        return PATH_PLACEHOLDER if any(ch.isalnum() for ch in token) else token
    return PATH_TOKEN.sub(_one, _CONTROL.sub(" ", value))


def screen_structure(value: Any) -> Any:
    """*value* with :func:`screen_text` applied to every string in it, keys included."""
    if isinstance(value, str):
        return screen_text(value)
    if isinstance(value, dict):
        return {screen_text(str(k)): screen_structure(v) for k, v in value.items()}
    if isinstance(value, (list, tuple)):
        return [screen_structure(v) for v in value]
    return value


# ── the scan ──────────────────────────────────────────────────────────────────

_SALT = secrets.token_bytes(16)
JSON_SUFFIXES = (".json", ".jsonc")
UNPARSED_SUFFIXES = (".yaml", ".yml", ".toml")
MAX_FILE_BYTES = 4 * 1024 * 1024


def _salted(value: str) -> str:
    return hashlib.sha256(_SALT + value.encode("utf-8")).hexdigest()


def _hash(value: str) -> str:
    """``local_agent_discovery._hash``, SALTED: every path hash the copied scans write
    (``config_path_hash``) is unlinkable across runs and agrees between scans within one."""
    return _salted(value)


def _os_name() -> str:
    system = platform.system().lower()
    return "windows" if system.startswith("win") else ("darwin" if system == "darwin" else "linux")


def _basename(command: Any) -> Any:
    if not command:
        return None
    return str(command).replace("\\", "/").rstrip("/").rsplit("/", 1)[-1] or None


def _bare_host(netloc: Any) -> Any:
    if not netloc:
        return None
    return str(netloc).rsplit("@", 1)[-1] or None


def _load_json(path: Path) -> Any:
    if path.stat().st_size > MAX_FILE_BYTES:
        return None
    try:
        data = json.loads(_strip_json_comments(path.read_text(encoding="utf-8")))
    except (OSError, UnicodeDecodeError, ValueError):
        return None
    return data if isinstance(data, dict) else None


def _load_toml(path: Path) -> Any:
    """A TOML configuration (Codex CLI's config.toml), where this Python can read one:
    tomllib is in the standard library from Python 3.11. ``None`` when it cannot be read."""
    try:
        import tomllib
    except ImportError:
        return None
    if path.stat().st_size > MAX_FILE_BYTES:
        return None
    try:
        with open(path, "rb") as handle:
            data = tomllib.load(handle)
    except (OSError, ValueError):
        return None
    return data if isinstance(data, dict) else None


def _toml_readable() -> bool:
    try:
        import tomllib  # noqa: F401
    except ImportError:
        return False
    return True


def scan_clients(home: Path) -> dict:
    clients, servers, unparsed = [], [], set()
    for path in _expand_paths([home / rel for rel in CANDIDATE_PATHS]):
        if not path.is_file():
            continue
        suffix = path.suffix.lower()
        product = _product_for_path(path)
        if suffix == ".toml" and _toml_readable():
            data = _load_toml(path)
        elif suffix in UNPARSED_SUFFIXES:
            unparsed.add(product)
            continue
        else:
            data = _load_json(path)
        if data is None:
            continue
        config_hash = config_path_hash(path)
        clients.append({"product": product, "config_filename": path.name, "config_hash": config_hash})
        for name, cfg in _iter_mcp_servers(data, product=product, filename=path.name):
            args = cfg.get("args") if isinstance(cfg.get("args"), list) else []
            args_text = " ".join(str(a).lower() for a in args)
            env = cfg.get("env") if isinstance(cfg.get("env"), dict) else {}
            url_host = _bare_host(_host_from_url(_server_url(cfg)))
            servers.append({
                "product": product,
                "config_hash": config_hash,
                "name": str(name),
                "transport": "http" if url_host else "stdio",
                "command_basename": _basename(_server_command(cfg)),
                "args_count": len(args),
                "args_capability_words": [w for w in ARGS_CAPABILITY_WORDS if w in args_text],
                "url_host": url_host,
                "env_key_names": sorted(str(k) for k in env),
            })
    return {"clients": clients, "mcp_servers": servers, "unparsed_clients": sorted(unparsed)}


def _extension_name(version_dir: Path, manifest: dict) -> str:
    name = str(manifest.get("name") or "")
    if name.startswith("__MSG_") and name.endswith("__"):
        key = name[6:-2]
        locale = str(manifest.get("default_locale") or "en")
        messages = version_dir / "_locales" / locale / "messages.json"
        try:
            table = json.loads(messages.read_text(encoding="utf-8"))
        except (OSError, UnicodeDecodeError, ValueError):
            return ""
        for entry_key, entry in table.items() if isinstance(table, dict) else ():
            if entry_key.lower() == key.lower() and isinstance(entry, dict):
                return str(entry.get("message") or "")
        return ""
    return name


def _is_ai_extension(name: str) -> bool:
    low = name.lower()
    return any(keyword in low for keyword in AGENTIC_EXTENSION_KEYWORDS)


def scan_extensions(home: Path, os_name: str) -> list:
    found = {}
    for root in BROWSER_ROOTS.get(os_name, ()):
        base = home / root
        if not base.is_dir():
            continue
        for profile in sorted(base.iterdir()):
            extensions = profile / "Extensions"
            if not extensions.is_dir():
                continue
            for ext_dir in sorted(extensions.iterdir()):
                versions = sorted(v for v in ext_dir.iterdir() if v.is_dir()) if ext_dir.is_dir() else []
                if not versions:
                    continue
                manifest_path = versions[-1] / "manifest.json"
                if not manifest_path.is_file() or manifest_path.stat().st_size > MAX_FILE_BYTES:
                    continue
                try:
                    manifest = json.loads(manifest_path.read_text(encoding="utf-8-sig"))
                except (OSError, UnicodeDecodeError, ValueError):
                    continue
                if not isinstance(manifest, dict):
                    continue
                name = _extension_name(versions[-1], manifest)
                if not name or not _is_ai_extension(name):
                    continue
                permissions = [str(p) for p in (manifest.get("permissions") or []) if isinstance(p, str)]
                permissions += [str(p) for p in (manifest.get("host_permissions") or []) if isinstance(p, str)]
                found[ext_dir.name] = {
                    "id": ext_dir.name,
                    "name": name[:200],
                    "version": str(manifest.get("version") or "")[:64] or None,
                    "permissions": sorted(set(permissions))[:128],
                    "enabled": True,
                }
    return [found[k] for k in sorted(found)]


def scan_agent_posture(home: Path) -> tuple:
    """The posture scan ``track sensor`` runs, as bundle rows: per coding agent its facts."""
    try:
        snapshot = _agent_config_posture_module().discover_agent_config_posture(home=home)
    except Exception:  # noqa: BLE001 - the scan never raises; if it did, the rest of the bundle still goes
        return [], {"scan": "agent_config_posture", "complete": False, "truncated": False}
    rows = []
    for entity in snapshot.get("entities") or []:
        attrs = entity.get("attrs")
        if not isinstance(attrs, dict):  # a row whose attrs bag is not a mapping carries no facts
            continue
        rows.append({
            "product": attrs["product"],
            "config_filename": screen_text(str(attrs["config_filename"])),
            "config_hash": attrs["config_path_hash"],
            "posture": screen_structure(reduce_posture(attrs["posture"])),
        })
    config = snapshot.get("config") or {}
    return rows, {"scan": config.get("scan"), "complete": True, "truncated": bool(config.get("truncated"))}


def scan_agent_extensions(home: Path) -> tuple:
    """The extensions scan ``track sensor`` runs, as bundle rows: the agents that load
    something (with their managed policy) and each skill, subagent, command, plugin or hook."""
    try:
        snapshot = _agent_extensions_module().discover_agent_extensions(home=home)
    except Exception:  # noqa: BLE001
        return [], [], {"scan": "agent_extensions", "complete": False, "truncated": False}
    agents, found = [], []
    for entity in snapshot.get("entities") or []:
        attrs = entity.get("attrs")
        if not isinstance(attrs, dict):  # a row whose attrs bag is not a mapping carries no facts
            continue
        if entity.get("entity_type") == "agent":
            agents.append({
                "product": attrs["product"],
                "config_filename": screen_text(str(attrs["config_filename"])),
                "config_hash": attrs["config_path_hash"],
                "extension_policy": screen_structure(reduce_extension_policy(attrs.get("extension_policy") or {})),
            })
        elif entity.get("entity_type") == "agent_extension":
            found.append({
                "id": entity["entity_id"],
                "product": attrs["product"],
                "kind": attrs["extension_kind"],
                "scope": attrs["scope"],
                "name": screen_text(str(entity["name"])),
                "attrs": screen_structure(reduce_extension_attrs(
                    {k: v for k, v in attrs.items() if k not in EXTENSION_RECOMPUTED_ATTRS})),
            })
    config = snapshot.get("config") or {}
    return agents, found, {"scan": config.get("scan"), "complete": True, "truncated": bool(config.get("truncated"))}


def scan(home: Path, *, runtimes: bool = True, extensions: bool = True, agent_posture: bool = True,
         agent_extensions: bool = True) -> dict:
    os_name = _os_name()
    fingerprint = f"{platform.system()}|{platform.node()}|{os.getuid() if hasattr(os, 'getuid') else ''}"
    bundle = {
        "schema": SCHEMA,
        "generated_at": datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z"),
        "os": os_name,
        "host_hash": _salted(fingerprint),
    }
    bundle.update(scan_clients(home))
    bundle["runtimes"] = scan_local_runtimes() if runtimes else []
    bundle["extensions"] = scan_extensions(home, os_name) if extensions else []
    bundle["agent_postures"], bundle["agent_extension_agents"], bundle["agent_extensions"] = [], [], []
    bundle["agent_scans"] = []
    if agent_posture:
        bundle["agent_postures"], done = scan_agent_posture(home)
        bundle["agent_scans"].append(done)
    if agent_extensions:
        bundle["agent_extension_agents"], bundle["agent_extensions"], done = scan_agent_extensions(home)
        bundle["agent_scans"].append(done)
    return bundle


SERVICE = "https://assess.tracksec.io"
_LOCAL_HOSTS = ("localhost", "127.0.0.1", "::1")


def _target(value: str) -> tuple[str, str | None]:
    """``(service origin, assessment id or None)`` from --upload's argument: the service
    itself (a new report) or a report link (add to that report)."""
    parsed = urllib.parse.urlsplit(value.strip())
    if parsed.scheme not in ("https", "http") or not parsed.hostname:
        raise SystemExit(f"--upload needs a link that starts with https://, not {value!r}")
    if parsed.username is not None or parsed.password is not None or "@" in parsed.netloc:
        # https://assess.tracksec.io@elsewhere.example names the host after the @.
        raise SystemExit("--upload takes a plain https:// address, with no user name or password in it")
    if parsed.scheme == "http" and parsed.hostname not in _LOCAL_HOSTS:
        raise SystemExit("--upload sends only over https")
    origin = f"{parsed.scheme}://{parsed.netloc}"
    parts = [p for p in parsed.path.split("/") if p]
    if len(parts) == 2 and parts[0] == "a" and parts[1].startswith("as_"):
        return origin, parts[1]
    if parts:
        raise SystemExit("--upload takes the service address or a report link (https://.../a/<id>)")
    return origin, None


def _ask(question: str) -> bool:
    """A yes from the person at the keyboard. When the script itself arrived on stdin
    (curl ... | python3 -), stdin is spent, so the answer is read from the terminal."""
    for device in ("/dev/tty", "CON"):
        try:
            with open(device, "r+", encoding="utf-8", errors="replace") as tty:
                tty.write(question)
                tty.flush()
                return tty.readline().strip().lower() in ("y", "yes")
        except OSError:
            continue
    print("No terminal to ask on; nothing was sent. Run again with --yes to send without asking.")
    return False


def _post(url: str, origin: str, body: bytes, content_type: str) -> dict:
    request = urllib.request.Request(url, data=body, method="POST", headers={
        "Origin": origin, "Accept": "application/json", "Content-Type": content_type,
        "User-Agent": "track-laptop-scan/1",
    })
    try:
        with urllib.request.urlopen(request, timeout=60) as response:  # nosec B310 - https (or loopback) only, _target
            return json.loads(response.read(1024 * 1024).decode("utf-8") or "{}")
    except urllib.error.HTTPError as exc:
        try:
            code = json.loads(exc.read(4096).decode("utf-8")).get("error", exc.code)
        except ValueError:
            code = exc.code
        raise SystemExit(f"The service refused the upload ({code}). The file is still here to upload by hand.")
    except (urllib.error.URLError, OSError, ValueError) as exc:
        raise SystemExit(f"Could not reach {origin} ({exc.__class__.__name__}). The file is still here to upload by hand.")


def upload(data: bytes, target: str) -> str:
    """Send the written file; answer the report link."""
    origin, assessment_id = _target(target)
    if assessment_id is None:
        created = _post(f"{origin}/v1/assessments", origin, b"", "application/x-www-form-urlencoded")
        assessment_id = str(created.get("assessment_id") or "")
        if not assessment_id.startswith("as_"):
            raise SystemExit("The service did not start a report. The file is still here to upload by hand.")
    boundary = "----track" + secrets.token_hex(12)
    parts = []
    for name, value in (("kind", "laptop_scan"), ("connector_id", "laptop_scan")):
        parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode())
    parts.append(f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="scan.json"\r\n'
                 "Content-Type: application/json\r\n\r\n".encode() + data + b"\r\n")
    parts.append(f"--{boundary}--\r\n".encode())
    _post(f"{origin}/v1/assessments/{assessment_id}/evidence", origin, b"".join(parts),
          f"multipart/form-data; boundary={boundary}")
    return f"{origin}/a/{assessment_id}"


def main(argv: Any = None) -> int:
    parser = argparse.ArgumentParser(description="Track laptop scan (structure only).")
    parser.add_argument("--out", default="track-laptop-scan.json", help="where to write the file")
    parser.add_argument("--no-runtimes", action="store_true", help="do not probe 127.0.0.1 for model runtimes")
    parser.add_argument("--no-extensions", action="store_true", help="do not read browser extension manifests")
    parser.add_argument("--no-agent-posture", action="store_true",
                        help="do not read the coding agents' permission settings and rules files")
    parser.add_argument("--no-agent-extensions", action="store_true",
                        help="do not read the coding agents' skills, subagents, commands, plugins and hooks")
    parser.add_argument("--upload", nargs="?", const=SERVICE, default=None, metavar="LINK",
                        help="send the file after showing it and asking (default: a new report at " + SERVICE + ")")
    parser.add_argument("--yes", action="store_true", help="with --upload: send without asking")
    args = parser.parse_args(argv)
    if args.upload is not None:
        _target(args.upload)  # refuse a bad address before scanning anything
    bundle = scan(Path.home(), runtimes=not args.no_runtimes, extensions=not args.no_extensions,
                  agent_posture=not args.no_agent_posture, agent_extensions=not args.no_agent_extensions)
    out = Path(args.out)
    text = json.dumps(bundle, indent=2, sort_keys=True) + "\n"
    out.write_text(text, encoding="utf-8")
    print(f"Wrote {out} ({SCHEMA}).")
    print(f"  AI clients with a readable configuration: {len(bundle['clients'])}"
          + (f" ({', '.join(sorted({c['product'] for c in bundle['clients']}))})" if bundle["clients"] else ""))
    print(f"  MCP servers they name: {len(bundle['mcp_servers'])}"
          + (f" ({', '.join(sorted({m['name'] for m in bundle['mcp_servers']})[:12])})" if bundle["mcp_servers"] else ""))
    print(f"  model runtimes answering on 127.0.0.1: {len(bundle['runtimes'])}")
    print(f"  AI browser extensions: {len(bundle['extensions'])}")
    postures = bundle["agent_postures"]
    print(f"  coding agents whose settings were read: {len(postures)}"
          + (f" ({', '.join(sorted(p['product'] for p in postures))})" if postures else ""))
    kinds = {}
    for item in bundle["agent_extensions"]:
        kinds[item["kind"]] = kinds.get(item["kind"], 0) + 1
    by_kind = ", ".join(str(n) + " " + k for k, n in sorted(kinds.items()))
    print(f"  coding agent extensions: {len(bundle['agent_extensions'])}" + (f" ({by_kind})" if by_kind else ""))
    for done in bundle["agent_scans"]:
        if not done["complete"] or done["truncated"]:
            print(f"  {done['scan']}: {'stopped at a bound' if done['complete'] else 'did not finish'}")
    if bundle["unparsed_clients"]:
        print(f"  not read (YAML or TOML configuration): {', '.join(bundle['unparsed_clients'])}")
    print("It holds names, hosts, counts, digests, tool names and key names, never a path, "
          "a value from a configuration file or a file's text.")
    if args.upload is None:
        print("Nothing was uploaded. Read the file, then upload it at " + SERVICE + "/ if you choose to.")
        return 0
    origin, _assessment = _target(args.upload)
    host = urllib.parse.urlsplit(origin).hostname
    print(f"Everything that would be sent is in {out.resolve()}; open it to read it.")
    if not args.yes and not _ask(f"Send it to {host}? [y/N] "):
        print("Nothing was uploaded.")
        return 0
    link = upload(text.encode("utf-8"), args.upload)
    print("Sent. Your report:")
    print(f"  {link}")
    print("Anyone with this link can open the report. Delete it from the report page at any time.")
    return 0


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