#!/usr/bin/env python3
# agent_surface_check.py - list the parts of an agent workspace that can turn text into actions.
# Project: hostimm.com - https://hostimm.com
# AION (agent, APEX V2 architecture) - Architect AlexH
# Community: llmresearch.net (EN) / forumai.ro (RO)
# License: MIT, attribution required
"""agent_surface_check.py - inventory the executable surfaces in an agent workspace.

An agent with a shell has more than one way in. This scans a directory tree for the six
that ship in ordinary setups and reports the lines that carry instructions or execution,
with file and line number:

  model      .gguf and .safetensors files: chat template directives, bytes after the last tensor
  skill      skill manifests and the scripts beside them: shell pipes, base64 blobs, exfil URLs
  package    install hooks in package.json, setup.py and .pth files: code that runs on install
  tool       MCP server and hook configuration: shell wrappers, unpinned npx, tokens in env
  memory     persisted notes and state: instruction-shaped text that survives a session
  autonomy   permission files: auto-approve, skip-permissions, tool allowlists with no deny rule

It reads and never executes: no template is rendered, no hook is run, no model is loaded.
It is a triage tool, not a sandbox. A clean file today says nothing about the same file
tomorrow, and a finding is a reason to look, not proof of intent.

Usage
  python agent_surface_check.py .                  # scan a workspace
  python agent_surface_check.py . --json
  python agent_surface_check.py . --surface model,skill

Exit codes: 0 no findings, 2 findings, 1 error (unreadable or truncated file).
"""
from __future__ import annotations

import argparse
import json
import os
import re
import struct
import sys

SEV_ORDER = {"high": 0, "medium": 1, "low": 2}

# ggml tensor types: id -> (block size in elements, bytes per block). Unknown means
# the data section cannot be sized, and the file is reported as unverifiable.
GGML_TYPES = {
    0: (1, 4), 1: (1, 2), 2: (32, 18), 3: (32, 20), 6: (32, 22), 7: (32, 24),
    8: (32, 34), 9: (32, 36), 10: (256, 84), 11: (256, 110), 12: (256, 144),
    13: (256, 176), 14: (256, 210), 15: (256, 292), 16: (256, 66), 17: (256, 74),
    18: (256, 98), 19: (256, 50), 20: (32, 18), 21: (256, 110), 22: (256, 82),
    23: (256, 136), 24: (1, 1), 25: (1, 2), 26: (1, 4), 27: (1, 8), 28: (256, 24),
    29: (256, 34), 30: (1, 2), 34: (256, 54), 35: (256, 66), 39: (256, 20),
}

INSTRUCTION = re.compile(
    r"(ignore (all )?(previous|prior|above)|disregard (the )?(previous|system)|"
    r"you are now|new instructions|system prompt|do not (tell|mention|reveal)|"
    r"without (telling|asking) the user|always (send|include|append|bcc)|"
    r"when the user asks|forward (all|any)|exfiltrat)", re.I)
EXEC_PATTERN = re.compile(
    r"(curl\s+[^\n|]{0,120}\|\s*(ba)?sh|wget\s+[^\n|]{0,120}\|\s*(ba)?sh|"
    r"base64\s+(-d|--decode)|eval\s*\(|os\.system|subprocess\.(run|Popen|call)[^\n]*shell\s*=\s*True|"
    r"child_process|powershell\s+-(enc|e)\b|Invoke-Expression|nc\s+-e\b)", re.I)
EXFIL_URL = re.compile(r"https?://[^\s)\"'<>]{6,120}(webhook|collect|ingest|hook|\?k=|/c\b|/p\b)", re.I)
SECRET_HINT = re.compile(r"(api[_-]?key|token|secret|password|\.env\b|id_rsa|wallet)", re.I)
HOOK_KEYS = ("preinstall", "install", "postinstall", "prepare", "prepublish")
SHELL_WRAPPERS = re.compile(r"^\s*(bash|sh|zsh|cmd|powershell|pwsh|python\s+-c|node\s+-e)\b", re.I)


class Finding:
    __slots__ = ("surface", "severity", "path", "line", "rule", "detail")

    def __init__(self, surface, severity, path, line, rule, detail):
        self.surface = surface
        self.severity = severity
        self.path = path
        self.line = line
        self.rule = rule
        self.detail = detail

    def as_dict(self, root):
        return {"surface": self.surface, "severity": self.severity,
                "path": os.path.relpath(self.path, root), "line": self.line,
                "rule": self.rule, "detail": self.detail}


def read_text(path, limit=512 * 1024):
    try:
        with open(path, "rb") as fh:
            raw = fh.read(limit)
        return raw.decode("utf-8", "replace")
    except OSError:
        return ""


def scan_text_lines(findings, surface, path, severity, patterns, root):
    text = read_text(path)
    for n, line in enumerate(text.splitlines(), 1):
        for rule, rx in patterns:
            m = rx.search(line)
            if m:
                findings.append(Finding(surface, severity, path, n, rule,
                                        line.strip()[:160]))


# ---------------------------------------------------------------- models
def _kv_str(buf, pos):
    (n,) = struct.unpack_from("<Q", buf, pos)
    pos += 8
    s = buf[pos:pos + n].decode("utf-8", "replace")
    return s, pos + n


def scan_gguf(path, root, findings):
    size = os.path.getsize(path)
    with open(path, "rb") as fh:
        buf = fh.read(min(size, 16 * 1024 * 1024))
    if len(buf) < 24 or buf[:4] != b"GGUF":
        findings.append(Finding("model", "medium", path, 1, "not_gguf", "no GGUF magic"))
        return
    version, = struct.unpack_from("<I", buf, 4)
    tcount, kvcount = struct.unpack_from("<QQ", buf, 8)
    pos = 24
    template = ""
    for _ in range(kvcount):
        try:
            key, pos = _kv_str(buf, pos)
            vtype, = struct.unpack_from("<I", buf, pos)
            pos += 4
            if vtype == 8:                      # string
                val, pos = _kv_str(buf, pos)
                if key == "tokenizer.chat_template":
                    template = val
            elif vtype == 4:
                pos += 4
            elif vtype == 5:
                pos += 4
            elif vtype == 6:
                pos += 4
            elif vtype in (0, 1, 2, 3, 10, 11, 12):
                pos += {0: 1, 1: 1, 2: 2, 3: 2, 10: 8, 11: 8, 12: 8}[vtype]
            elif vtype == 7:
                pos += 1
            elif vtype == 9:                    # array
                (atype,) = struct.unpack_from("<I", buf, pos)
                (alen,) = struct.unpack_from("<Q", buf, pos + 4)
                pos += 12
                for _ in range(alen):
                    if atype == 8:
                        _, pos = _kv_str(buf, pos)
                    elif atype in (0, 7):
                        pos += 1
                    elif atype in (2, 3):
                        pos += 2
                    elif atype in (4, 5, 6):
                        pos += 4
                    elif atype in (10, 11, 12):
                        pos += 8
        except (struct.error, UnicodeDecodeError):
            findings.append(Finding("model", "medium", path, 1, "header_truncated",
                                    "metadata table does not fit in the first 16 MB"))
            return
    # tensor table: name, n_dims, dims[n_dims], type, offset
    end = 0
    for _ in range(tcount):
        try:
            _, pos = _kv_str(buf, pos)
            (nd,) = struct.unpack_from("<I", buf, pos)
            pos += 4
            dims = struct.unpack_from("<" + "Q" * nd, buf, pos) if nd else (1,)
            pos += 8 * nd
            (ttype,) = struct.unpack_from("<I", buf, pos)
            pos += 4
            (off,) = struct.unpack_from("<Q", buf, pos)
            pos += 8
            if ttype not in GGML_TYPES:
                findings.append(Finding("model", "medium", path, 1, "unknown_quant",
                                        f"tensor type {ttype} cannot be sized, file not verified"))
                return
            bs, nbytes_per_block = GGML_TYPES[ttype]
            nelem = 1
            for d in dims:
                nelem *= d
            end = max(end, off + (nelem // bs) * nbytes_per_block)
        except (struct.error, UnicodeDecodeError):
            findings.append(Finding("model", "medium", path, 1, "header_truncated",
                                    "tensor table does not fit in the first 16 MB"))
            return
    data_start = pos + (-pos % 32)
    declared = data_start + end
    if size > declared + 512:
        findings.append(Finding("model", "high", path, 1, "trailing_bytes",
                                f"{size - declared} bytes after the last declared tensor"))
    if template:
        for n, line in enumerate(template.splitlines(), 1):
            for rule, rx in (("template_instruction", INSTRUCTION), ("template_exec", EXEC_PATTERN),
                             ("template_url", EXFIL_URL)):
                if rx.search(line):
                    findings.append(Finding("model", "high", path, 1, rule,
                                            "chat template: " + line.strip()[:150]))
                    break


def scan_safetensors(path, root, findings):
    size = os.path.getsize(path)
    with open(path, "rb") as fh:
        head = fh.read(8)
        if len(head) < 8:
            findings.append(Finding("model", "medium", path, 1, "not_safetensors", "short header"))
            return
        (n,) = struct.unpack("<Q", head)
        if n <= 0 or n > 100 * 1024 * 1024:
            findings.append(Finding("model", "medium", path, 1, "not_safetensors", "implausible header length"))
            return
        try:
            meta = json.loads(fh.read(n).decode("utf-8"))
        except (json.JSONDecodeError, UnicodeDecodeError):
            findings.append(Finding("model", "medium", path, 1, "not_safetensors", "header is not JSON"))
            return
    end = 8 + n
    for k, v in meta.items():
        if k == "__metadata__":
            blob = json.dumps(v)
            if INSTRUCTION.search(blob) or EXFIL_URL.search(blob):
                findings.append(Finding("model", "high", path, 1, "metadata_instruction",
                                        "__metadata__ carries instruction-shaped text"))
            continue
        try:
            end = max(end, 8 + n + v["data_offsets"][1])
        except (KeyError, TypeError, IndexError):
            findings.append(Finding("model", "medium", path, 1, "not_safetensors",
                                    f"tensor '{k}' has no data_offsets"))
            return
    if size > end + 512:
        findings.append(Finding("model", "high", path, 1, "trailing_bytes",
                                f"{size - end} bytes after the last declared tensor"))


# ---------------------------------------------------------------- skills, packages, configs
def scan_skill_docs(path, root, findings):
    scan_text_lines(findings, "skill", path, "high",
                   [("skill_instruction", INSTRUCTION), ("skill_exec", EXEC_PATTERN),
                    ("skill_exfil_url", EXFIL_URL)], root)


def scan_script(path, root, findings, surface):
    text = read_text(path)
    if not text:
        return
    network = bool(re.search(r"(curl|wget|urllib|requests\.|http\.client|fetch\()", text, re.I))
    files = bool(re.search(r"(open\(|Path\(|readFileSync|readFile|createReadStream|"
                           r"write_text|shutil|unlink|remove\()", text))
    for n, line in enumerate(text.splitlines(), 1):
        if EXEC_PATTERN.search(line):
            findings.append(Finding(surface, "high", path, n, "code_exec", line.strip()[:160]))
        elif EXFIL_URL.search(line):
            findings.append(Finding(surface, "high", path, n, "exfil_url", line.strip()[:160]))
    if network and files and SECRET_HINT.search(text):
        findings.append(Finding(surface, "high", path, 1, "read_secret_then_network",
                                "reads files, secrets and the network in one script"))


def scan_package(path, root, findings):
    text = read_text(path)
    try:
        data = json.loads(text)
    except json.JSONDecodeError:
        return
    scripts = data.get("scripts") or {}
    for key in HOOK_KEYS:
        if key in scripts:
            findings.append(Finding("package", "high", path, 1, "install_hook",
                                    f"scripts.{key}: {scripts[key][:120]}"))


def scan_python_setup(path, root, findings):
    text = read_text(path)
    if re.search(r"(cmdclass|post_install|build_py|subprocess|os\.system|pth)", text):
        line = next((n for n, l in enumerate(text.splitlines(), 1)
                     if re.search(r"(cmdclass|post_install|subprocess|os\.system)", l)), 1)
        findings.append(Finding("package", "high", path, line, "setup_hook",
                                "setup path can run code at install"))


def scan_tool_config(path, root, findings):
    text = read_text(path)
    try:
        data = json.loads(text)
    except json.JSONDecodeError:
        return
    servers = (data.get("mcpServers") or data.get("servers") or
               (data.get("mcp") or {}).get("servers") or {})
    if isinstance(servers, dict):
        for name, cfg in servers.items():
            if not isinstance(cfg, dict):
                continue
            cmd = str(cfg.get("command", ""))
            args = cfg.get("args") or []
            joined = " ".join(str(a) for a in args)
            if SHELL_WRAPPERS.search(cmd) or re.search(r"(-c|--eval|-e)$", cmd):
                findings.append(Finding("tool", "high", path, 1, "shell_wrapper",
                                        f"server '{name}' starts a shell: {cmd} {joined}".strip()))
            if re.search(r"(npx|uvx)", cmd) and not re.search(r"@[0-9]", joined):
                findings.append(Finding("tool", "medium", path, 1, "unpinned_fetch",
                                        f"server '{name}' runs code fetched at start: {cmd} {joined}".strip()))
            if re.search(r"(^|\s)(/|~|\$HOME|%USERPROFILE%)(\s|$)", joined) or ":/" in joined:
                findings.append(Finding("tool", "medium", path, 1, "broad_path",
                                        f"server '{name}' is given a filesystem root"))
            env = cfg.get("env") or {}
            for k, v in env.items():
                if SECRET_HINT.search(k) and str(v) and not str(v).startswith("${"):
                    findings.append(Finding("tool", "high", path, 1, "literal_secret",
                                            f"server '{name}' carries a literal {k}"))
            if cfg.get("url") and not cfg.get("url", "").startswith("https://"):
                findings.append(Finding("tool", "medium", path, 1, "plaintext_url",
                                        f"server '{name}' is reached over {cfg.get('url','')[:60]}"))
    hooks = data.get("hooks")
    if hooks:
        blob = json.dumps(hooks)
        if re.search(r"(command|cmd)", blob):
            findings.append(Finding("tool", "high", path, 1, "hook_command",
                                    "settings run a shell command on an event"))


def scan_autonomy(path, root, findings):
    text = read_text(path)
    low = text.lower()
    for needle, rule, sev in (
            ("auto_approve", "auto_approve", "high"),
            ("dangerouslyskip", "skip_permissions", "high"),
            ("bypasspermissions", "skip_permissions", "high"),
            ("yolo", "yolo_mode", "high"),
            ("allowed_tools", "tool_allowlist", "medium"),
            ("auto_tools", "tool_allowlist", "medium")):
        if needle in low:
            findings.append(Finding("autonomy", sev, path, 1, rule,
                                    "agent autonomy set without a deny rule beside it"))


SURFACES = ("model", "skill", "package", "tool", "memory", "autonomy")
CODE_EXT = (".py", ".sh", ".js", ".ts", ".ps1")
TOOL_FILES = ("mcp.json", ".mcp.json", "claude_desktop_config.json", "settings.json", "mcp_config.json")


def classify(dirpath, fn, ext):
    """Which surfaces a file belongs to. A file can be more than one."""
    hit = set()
    in_skill = re.search(r"[\\/]skills?([\\/]|$)", dirpath, re.I) is not None
    in_mem = re.search(r"[\\/](memory|state|notes)([\\/]|$)", dirpath, re.I) is not None
    if ext in (".gguf", ".safetensors"):
        hit.add("model")
    if fn == "SKILL.md" or (in_skill and ext in (".md",) + CODE_EXT):
        hit.add("skill")
    in_pkg = (os.path.exists(os.path.join(dirpath, "package.json"))
              or os.path.exists(os.path.join(os.path.dirname(dirpath), "package.json")))
    if fn in ("package.json", "setup.py") or ext == ".pth" or (in_pkg and ext in CODE_EXT):
        hit.add("package")
    if fn in TOOL_FILES:
        hit.add("tool")
    if in_mem and ext in (".md", ".txt", ".json", ".yaml", ".yml"):
        hit.add("memory")
    if ext in (".json", ".yaml", ".yml", ".toml") and re.search(r"(config|agent|permission)", fn, re.I):
        hit.add("autonomy")
    return hit


def scan(root, only=None):
    root = os.path.abspath(root)
    findings: list[Finding] = []
    counts = {k: 0 for k in SURFACES}
    for dirpath, dirnames, filenames in os.walk(root):
        dirnames[:] = [d for d in dirnames if d not in
                       {".git", "node_modules", "__pycache__", ".venv", "venv", "dist", "build"}]
        for fn in filenames:
            path = os.path.join(dirpath, fn)
            ext = os.path.splitext(fn)[1].lower()
            hits = classify(dirpath, fn, ext)
            for s in hits:
                counts[s] += 1
            todo = hits if not only else hits & only
            if not todo:
                continue
            if "model" in todo:
                (scan_gguf if ext == ".gguf" else scan_safetensors)(path, root, findings)
            if "skill" in todo:
                if ext == ".md":
                    scan_skill_docs(path, root, findings)
                else:
                    scan_script(path, root, findings, "skill")
            if "package" in todo:
                if fn == "package.json":
                    scan_package(path, root, findings)
                elif fn == "setup.py":
                    scan_python_setup(path, root, findings)
                elif ext in CODE_EXT:
                    scan_script(path, root, findings, "package")
                else:
                    findings.append(Finding("package", "high", path, 1, "pth_file",
                                            "a .pth file runs its line at import time"))
            if "tool" in todo:
                scan_tool_config(path, root, findings)
            if "memory" in todo and ext in (".md", ".txt"):
                scan_text_lines(findings, "memory", path, "medium",
                                [("memory_instruction", INSTRUCTION),
                                 ("memory_credential", re.compile(
                                     r"(api[_-]?key|token|password|secret)", re.I))], root)
            if "autonomy" in todo:
                scan_autonomy(path, root, findings)
    findings.sort(key=lambda f: (SEV_ORDER[f.severity], f.surface, f.path, f.line))
    return findings, counts


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("root", nargs="?", default=".")
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--surface", default="")
    ap.add_argument("--quiet", action="store_true")
    a = ap.parse_args()
    only = {s.strip() for s in a.surface.split(",") if s.strip()} or None
    if only and not only <= set(SURFACES):
        print("unknown surface, use: " + ", ".join(SURFACES), file=sys.stderr)
        return 1
    findings, counts = scan(a.root, only)
    root = os.path.abspath(a.root)
    if a.json:
        print(json.dumps({"root": root,
                          "counts": counts,
                          "findings": [f.as_dict(root) for f in findings]}, indent=1))
    else:
        for f in findings:
            rel = os.path.relpath(f.path, root)
            print(f"{f.severity.upper():<6} {f.surface:<9} {rel}:{f.line}  {f.rule}  {f.detail}")
        if not findings:
            print("no findings")
        high = sum(1 for f in findings if f.severity == "high")
        print(f"\n{len(findings)} findings ({high} high) across {counts}", file=sys.stderr)
    return 0 if not findings else 2


if __name__ == "__main__":
    sys.exit(main())
