#!/usr/bin/env python3
"""Titanward — Modern Infrastructure Initial Assessment & Fix Advisor.

Single-file, zero-dependency, read-only posture and cryptographic assessor for
modern Linux, macOS, Windows, and application repositories (Python 3.8+).

Safety guarantees enforced in code:
  1. 100% read-only: modifies zero system files, restarts zero services.
  2. Zero secrets touched: never opens .env*, *.pem, *.key, *.pfx, *.p12,
     private SSH keys, /etc/shadow, seed phrases, or credential stores.
  3. Zero outbound network traffic by default (unless --probe-tls is explicitly passed).
  4. Hard per-command timeouts and low CPU priority so production workloads stay calm.

Outputs:
  - <out>/<host>-assessment.json      (canonical titanward.assessment.v1)
  - <out>/<host>-recommendations.md   (prioritized fix recommendations + rollback notes)
"""
from __future__ import annotations

import argparse
import datetime as dt
import hashlib
import json
import os
import platform
import plistlib
import re
import shutil
import socket
import ssl
import stat
import subprocess
import sys
from pathlib import Path
from typing import Any

COLLECTOR_NAME = "titanward-assess-modern.py"
COLLECTOR_VERSION = "1.1.0"
SCHEMA_ID = "titanward.assessment.v1"

EXCLUDED_DIRS = {
    ".git", ".hg", ".svn", "node_modules", ".next", "dist", "build",
    "__pycache__", ".venv", "venv", "vendor", "target", "proc", "sys", "dev",
}

EXCLUDED_SECRET_GLOBS = [
    ".env*", "*.pem", "*.key", "*.pfx", "*.p12", "*.kdbx", "*.jks",
    "id_rsa", "id_dsa", "id_ecdsa", "id_ed25519", "/etc/shadow",
    "credentials*", "*secret*", "*wallet*", "*seed*", "*mnemonic*",
]

SECRET_FILENAME_RE = re.compile(
    r"(^\.env($|\.)|\.(pem|key|pfx|p12|kdbx|jks|keystore|der|ovpn|sqlite|db)$"
    r"|^id_(rsa|dsa|ecdsa|ed25519|xmss)$|(^|[_-])(shadow|passwd|credentials|wallet|seed|mnemonic|token|secret)s?($|\.))",
    re.IGNORECASE,
)

SECRET_VALUE_PATTERNS = [
    re.compile(r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----"),
    re.compile(r"\bAGE-SECRET-KEY-(?:PQ-)?1[A-Z0-9]{20,}\b"),
    re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"),
    re.compile(r"\bgh[pousr]_[A-Za-z0-9_]{20,}\b"),
    re.compile(r"\bsk-(?:live|test|proj|ant)-[A-Za-z0-9_-]{16,}\b"),
    re.compile(r"\bxox[baprs]-[A-Za-z0-9-]{16,}\b"),
    re.compile(r"(?i)(password|passwd|secret|api[_-]?key|token|authorization)\s*[:=]\s*['\"]?[^\s'\";,]{4,}"),
    re.compile(r"(?i)(--password|--token|--secret|-p)\s+\S+"),
    re.compile(r"://[^/\s:@]+:[^/\s@]+@"),
]

COMPROMISED_NPM_COORDINATES = {
    "@ctrl/tinycolor": {"4.1.1", "4.1.2"},
    "ngx-bootstrap": {"18.1.4", "19.0.3", "20.0.4"},
    "angulartics2": {"14.1.2"},
    "chalk-template": {"1.1.1"},
    "backslash": {"0.2.1"},
    "event-stream": {"3.3.6"},
    "ua-parser-js": {"0.7.29", "0.8.0", "1.0.0"},
    "coa": {"2.0.3", "2.0.4", "3.0.1"},
    "rc": {"1.2.9", "1.3.9", "2.3.9"},
}

DANGEROUS_PUBLIC_PORTS = {
    21: ("FTP (cleartext)", "critical"),
    23: ("Telnet (cleartext)", "critical"),
    445: ("SMB file sharing", "high"),
    1433: ("MSSQL database", "high"),
    1521: ("Oracle database listener", "high"),
    2375: ("Docker daemon TCP (unencrypted)", "critical"),
    3306: ("MySQL database", "high"),
    3389: ("RDP remote desktop", "high"),
    5432: ("PostgreSQL database", "high"),
    5900: ("VNC remote desktop", "high"),
    6379: ("Redis datastore", "critical"),
    9200: ("Elasticsearch HTTP", "high"),
    27017: ("MongoDB datastore", "critical"),
}


class RedactionTracker:
    def __init__(self) -> None:
        self.redactions = 0

    def scrub(self, text: str) -> str:
        if not text:
            return ""
        cleaned = text
        for pat in SECRET_VALUE_PATTERNS:
            cleaned, count = pat.subn("[REDACTED-BY-SHIELD]", cleaned)
            self.redactions += count
        return cleaned


def is_secret_path(path: Path) -> bool:
    name = path.name
    if name.endswith(".pub") or name.endswith(".example") or name.endswith(".sample"):
        return False
    return bool(SECRET_FILENAME_RE.search(name))


def run_cmd(argv: list[str], timeout: int, tracker: RedactionTracker) -> tuple[int, str]:
    exe = shutil.which(argv[0])
    if not exe:
        return 127, ""
    try:
        proc = subprocess.run(
            [exe, *argv[1:]],
            stdin=subprocess.DEVNULL,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            errors="replace",
            timeout=timeout,
        )
        combined = (proc.stdout or "") + ("\n" + proc.stderr if proc.stderr else "")
        return proc.returncode, tracker.scrub(combined.strip())
    except ( subprocess.TimeoutExpired, OSError ):
        return 124, ""


def detect_privilege() -> str:
    if os.name == "nt":
        try:
            import ctypes
            return "administrator" if ctypes.windll.shell32.IsUserAnAdmin() else "user"
        except Exception:
            return "user"
    if hasattr(os, "geteuid"):
        return "root" if os.geteuid() == 0 else "user"
    return "user"


def detect_os_and_eol(timeout: int, tracker: RedactionTracker) -> dict[str, str]:
    sys_name = platform.system().lower()
    arch = platform.machine() or "unknown"
    kernel = platform.release() or "unknown"
    os_family = "unix"
    distro = platform.platform()
    version = platform.version()
    eol_status = "supported"
    eol_detail = "Current OS release is within standard vendor support."
    strategy = "in_place_upgrade"
    reason = "Modern supported OS and userland; safe for staged in-place hardening and hybrid post-quantum rollout."

    if sys_name == "darwin":
        os_family = "macos"
        rc, out = run_cmd(["sw_vers"], timeout, tracker)
        prod_ver = ""
        for line in out.splitlines():
            if "ProductVersion:" in line:
                prod_ver = line.split(":", 1)[1].strip()
        version = prod_ver or platform.mac_ver()[0] or "unknown"
        distro = f"macOS {version}"
        try:
            major = int(version.split(".")[0])
            if major < 13:
                eol_status = "eol"
                eol_detail = f"macOS {version} no longer receives full Apple security updates."
                strategy = "isolate_behind_pq_gateway"
                reason = "Unsupported macOS release; upgrade OS in maintenance window or isolate sensitive services behind a post-quantum gateway."
            elif major == 13:
                eol_status = "approaching_eol"
                eol_detail = f"macOS {version} is in late lifecycle; plan macOS 14/15 upgrade."
        except ValueError:
            pass

    elif sys_name == "linux":
        os_family = "linux"
        os_rel: dict[str, str] = {}
        p = Path("/etc/os-release")
        if p.is_file():
            try:
                for line in p.read_text(encoding="utf-8", errors="replace").splitlines():
                    if "=" in line and not line.startswith("#"):
                        k, v = line.split("=", 1)
                        os_rel[k.strip()] = v.strip().strip('"').strip("'")
            except OSError:
                pass
        distro = os_rel.get("PRETTY_NAME") or distro
        version = os_rel.get("VERSION_ID") or version
        distro_id = (os_rel.get("ID") or "").lower()

        if distro_id == "ubuntu":
            if version in {"12.04", "14.04", "16.04", "18.04", "20.04"}:
                eol_status = "eol" if version < "20.04" else "approaching_eol"
                eol_detail = f"Ubuntu {version} standard support ended or requires ESM."
                if eol_status == "eol":
                    strategy = "isolate_behind_pq_gateway"
                    reason = f"Ubuntu {version} is End-of-Life; isolate behind a private VLAN and post-quantum gateway before touching legacy binaries."
        elif distro_id in {"centos", "rhel", "rocky", "almalinux"}:
            major_str = version.split(".")[0]
            if major_str.isdigit() and int(major_str) <= 7:
                eol_status = "eol"
                eol_detail = f"{distro} is End-of-Life."
                strategy = "isolate_behind_pq_gateway"
                reason = "End-of-Life Enterprise Linux userland; isolate behind a private VLAN + post-quantum gateway instead of risky in-place OpenSSL replacement."
        elif distro_id == "debian":
            major_str = version.split(".")[0]
            if major_str.isdigit() and int(major_str) <= 10:
                eol_status = "eol"
                eol_detail = f"Debian {version} is End-of-Life."
                strategy = "isolate_behind_pq_gateway"
                reason = "End-of-Life Debian release; isolate via VLAN + post-quantum gateway until workload migration."

    elif sys_name == "windows":
        os_family = "windows"
        win_rel, win_ver, _, _ = platform.win32_ver()
        distro = f"Windows {win_rel} ({win_ver})"
        version = win_ver or win_rel
        if any(tag in win_rel for tag in ("2008", "2012", "7", "8")):
            eol_status = "eol"
            eol_detail = f"{distro} is End-of-Life."
            strategy = "isolate_behind_pq_gateway"
            reason = "End-of-Life Windows release without modern Schannel post-quantum support; isolate on private VLAN behind translating gateway."
        elif "10" in win_rel:
            eol_status = "approaching_eol"
            eol_detail = "Windows 10 standard support has sunset unless enrolled in ESU."

    return {
        "os_family": os_family,
        "os_distro": distro,
        "os_version": version,
        "kernel": kernel,
        "arch": arch,
        "eol_status": eol_status,
        "eol_detail": eol_detail,
        "remediation_strategy": strategy,
        "strategy_reason": reason,
    }


def check_firewall_and_docker(os_family: str, timeout: int, tracker: RedactionTracker) -> dict[str, Any]:
    res = {"status": "unknown", "engine": "none", "docker_ufw_bypass": False, "detail": "Unable to determine firewall state without elevated permissions."}
    if os_family == "macos":
        rc, out = run_cmd(["/usr/libexec/ApplicationFirewall/socketfilterfw", "--getglobalstate"], timeout, tracker)
        if rc == 0 and out:
            enabled = "enabled" in out.lower()
            res = {
                "status": "enabled" if enabled else "disabled",
                "engine": "macos-alf",
                "docker_ufw_bypass": False,
                "detail": out.splitlines()[0],
            }
    elif os_family == "linux":
        rc, out = run_cmd(["ufw", "status"], timeout, tracker)
        if rc == 0 and "status:" in out.lower():
            active = "status: active" in out.lower()
            res["engine"] = "ufw"
            res["status"] = "enabled" if active else "disabled"
            res["detail"] = out.splitlines()[0]
            if active:
                rc_d, out_d = run_cmd(["docker", "ps", "--format", "{{.Ports}}"], timeout, tracker)
                if rc_d == 0 and ("0.0.0.0:" in out_d or ":::" in out_d):
                    res["status"] = "bypassed"
                    res["docker_ufw_bypass"] = True
                    res["detail"] = "UFW is active, but Docker publishes ports on 0.0.0.0/:: which bypass UFW via nat/DOCKER chains."
        else:
            rc_n, out_n = run_cmd(["nft", "list", "tables"], timeout, tracker)
            if rc_n == 0 and out_n.strip():
                res = {"status": "enabled", "engine": "nftables", "docker_ufw_bypass": False, "detail": f"nftables tables active ({len(out_n.splitlines())} tables)"}
    elif os_family == "windows":
        rc, out = run_cmd(["powershell", "-NoProfile", "-Command", "(Get-NetFirewallProfile | Select-Object Name,Enabled | ConvertTo-Json -Compress)"], timeout, tracker)
        if rc == 0 and out:
            disabled = '"Enabled":false' in out.replace(" ", "") or '"Enabled":0' in out.replace(" ", "")
            res = {"status": "disabled" if disabled else "enabled", "engine": "windows-firewall", "docker_ufw_bypass": False, "detail": "Checked Windows NetFirewallProfile"}
    return res


def check_disk_and_endpoint(os_family: str, timeout: int, tracker: RedactionTracker) -> tuple[dict[str, str], dict[str, str]]:
    disk = {"status": "unknown", "engine": "none"}
    ep = {"status": "unknown", "detail": "Not checked"}
    if os_family == "macos":
        rc, out = run_cmd(["fdesetup", "status"], timeout, tracker)
        if rc == 0 and out:
            disk = {"status": "enabled" if "filevault is on" in out.lower() else "disabled", "engine": "filevault"}
        rc_g, out_g = run_cmd(["spctl", "--status"], timeout, tracker)
        if rc_g == 0 and out_g:
            ep = {"status": "enabled" if "assessments enabled" in out_g.lower() else "degraded", "detail": out_g.splitlines()[0]}
    elif os_family == "linux":
        crypttab = Path("/etc/crypttab")
        if crypttab.is_file():
            try:
                non_comment = [ln for ln in crypttab.read_text(errors="replace").splitlines() if ln.strip() and not ln.strip().startswith("#")]
                disk = {"status": "enabled" if non_comment else "disabled", "engine": "luks" if non_comment else "none"}
            except OSError:
                pass
        ep = {"status": "not_applicable", "detail": "Server Linux posture relies on kernel LSM/SSH/firewall controls."}
    elif os_family == "windows":
        rc, out = run_cmd(["powershell", "-NoProfile", "-Command", "(Get-MpComputerStatus | Select-Object AntivirusEnabled,IsTamperProtected | ConvertTo-Json -Compress)"], timeout, tracker)
        if rc == 0 and out:
            compact = out.replace(" ", "")
            av_on = '"AntivirusEnabled":true' in compact
            tamper_on = '"IsTamperProtected":true' in compact
            ep = {
                "status": "enabled" if (av_on and tamper_on) else ("degraded" if av_on else "absent"),
                "detail": f"Defender AntivirusEnabled={av_on}, IsTamperProtected={tamper_on}",
            }
    return disk, ep


def collect_listeners(os_family: str, timeout: int, tracker: RedactionTracker) -> list[dict[str, Any]]:
    listeners: list[dict[str, Any]] = []
    seen: set[tuple[str, str, int]] = set()
    if os_family == "linux":
        rc, out = run_cmd(["ss", "-tulnpH"], timeout, tracker)
        if rc == 0 and out:
            for line in out.splitlines():
                parts = line.split()
                if len(parts) < 5:
                    continue
                proto = parts[0].lower()
                local = parts[4]
                if ":" not in local:
                    continue
                bind, port_s = local.rsplit(":", 1)
                bind = bind.strip("[]")
                if "%" in bind:
                    bind = bind.split("%", 1)[0]
                if not port_s.isdigit():
                    continue
                port = int(port_s)
                proc_m = re.search(r'users:\(\("([^"]+)"', line)
                proc = proc_m.group(1) if proc_m else "unknown"
                exposure = "loopback_only" if bind in {"127.0.0.1", "::1", "localhost"} else "public_or_lan"
                key = (proto, bind, port)
                if key not in seen:
                    seen.add(key)
                    listeners.append({"proto": proto, "bind": bind, "port": port, "process": proc, "exposure": exposure})
            return sorted(listeners, key=lambda x: (x["port"], x["bind"]))[:60]

    if os_family in {"macos", "linux"}:
        rc, out = run_cmd(["lsof", "-nP", "-iTCP", "-sTCP:LISTEN"], timeout, tracker)
        if rc == 0 and out:
            for line in out.splitlines()[1:]:
                parts = line.split()
                if len(parts) < 9:
                    continue
                proc = parts[0]
                name_col = parts[8]
                if ":" not in name_col:
                    continue
                bind, port_s = name_col.rsplit(":", 1)
                bind = bind.strip("[]")
                if not port_s.isdigit():
                    continue
                port = int(port_s)
                exposure = "loopback_only" if bind in {"127.0.0.1", "::1", "localhost"} else "public_or_lan"
                key = ("tcp", bind, port)
                if key not in seen:
                    seen.add(key)
                    listeners.append({"proto": "tcp", "bind": bind, "port": port, "process": proc, "exposure": exposure})
    return sorted(listeners, key=lambda x: (x["port"], x["bind"]))[:60]


def check_persistence_hygiene(os_family: str, tracker: RedactionTracker) -> list[dict[str, str]]:
    anomalies: list[dict[str, str]] = []
    suspicious_re = re.compile(r"(curl\s+.*\|\s*(?:ba)?sh|wget\s+.*\|\s*(?:ba)?sh|/tmp/|/var/tmp/|base64\s+-d|-enc\s+[A-Za-z0-9+/=]{20,})", re.IGNORECASE)
    if os_family == "macos":
        dirs = [Path.home() / "Library" / "LaunchAgents", Path("/Library/LaunchAgents")]
        for d in dirs:
            if not d.is_dir():
                continue
            for p in sorted(d.glob("*.plist"))[:80]:
                try:
                    st = p.stat()
                    if st.st_mode & stat.S_IWOTH:
                        anomalies.append({"location": str(p), "reason": "World-writable LaunchAgent plist (0o002 bit set)"})
                    with p.open("rb") as fh:
                        pl = plistlib.load(fh)
                    args = " ".join(str(x) for x in (pl.get("ProgramArguments") or [pl.get("Program", "")]))
                    args_clean = tracker.scrub(args)
                    if suspicious_re.search(args_clean):
                        anomalies.append({"location": str(p), "reason": f"Suspicious bootstrap/temp execution in LaunchAgent: {args_clean[:120]}"})
                except Exception:
                    continue
    elif os_family == "linux":
        rc_local = Path("/etc/rc.local")
        if rc_local.is_file():
            try:
                txt = tracker.scrub(rc_local.read_text(errors="replace"))
                if suspicious_re.search(txt):
                    anomalies.append({"location": "/etc/rc.local", "reason": "Suspicious temp/pipe execution pattern in /etc/rc.local"})
            except OSError:
                pass
    return anomalies


def check_crypto_and_ssh(timeout: int, tracker: RedactionTracker) -> dict[str, Any]:
    rc_o, openssl_ver = run_cmd(["openssl", "version"], timeout, tracker)
    openssl_version = openssl_ver.splitlines()[0] if (rc_o == 0 and openssl_ver) else "unavailable"
    rc_kem, kem_out = run_cmd(["openssl", "list", "-kem-algorithms"], timeout, tracker)
    pq_tls_capable = bool(rc_kem == 0 and re.search(r"ML-KEM|MLKEM", kem_out, re.IGNORECASE))
    pre_standard_kem_runtime = bool(rc_kem == 0 and re.search(r"\bkyber", kem_out, re.IGNORECASE) and not pq_tls_capable)

    ipsec_classical: list[str] = []
    for ipsec_cfg in (Path("/etc/ipsec.conf"), Path("/etc/strongswan.conf")):
        if ipsec_cfg.is_file() and not ipsec_cfg.is_symlink():
            try:
                itxt = tracker.scrub(ipsec_cfg.read_text(encoding="utf-8", errors="replace"))
                if re.search(r"(?im)^\s*(?:ike|esp|proposals)\s*=", itxt) and not re.search(r"mlkem|ke1_", itxt, re.I):
                    ipsec_classical.append(str(ipsec_cfg))
            except OSError:
                pass

    rc_sv, ssh_ver_out = run_cmd(["ssh", "-V"], timeout, tracker)
    ssh_version = ssh_ver_out.splitlines()[0] if ssh_ver_out else "unavailable"

    kex_list: list[str] = []
    rc_sg, ssh_g_out = run_cmd(["ssh", "-G", "localhost"], timeout, tracker)
    if rc_sg == 0 and ssh_g_out:
        for line in ssh_g_out.splitlines():
            if line.startswith("kexalgorithms "):
                kex_list = [k.strip() for k in line.split(" ", 1)[1].split(",") if k.strip()]
                break

    pq_ssh = bool(kex_list and ("mlkem" in kex_list[0] or "sntrup761" in kex_list[0]))
    pq_ssh_shadowed = bool(not pq_ssh and any(("mlkem" in k or "sntrup761" in k) for k in kex_list[1:]))

    permit_root = "unknown"
    password_auth = "unknown"
    sshd_cfg = Path("/etc/ssh/sshd_config")
    if sshd_cfg.is_file():
        try:
            for raw in sshd_cfg.read_text(errors="replace").splitlines():
                line = raw.strip()
                if not line or line.startswith("#"):
                    continue
                low = line.lower().split()
                if len(low) >= 2 and low[0] == "permitrootlogin":
                    permit_root = low[1]
                elif len(low) >= 2 and low[0] == "passwordauthentication":
                    password_auth = low[1]
        except OSError:
            pass

    weak_host_keys: list[str] = []
    for pub in sorted(Path("/etc/ssh").glob("ssh_host_*_key.pub")) if Path("/etc/ssh").is_dir() else []:
        try:
            first = pub.read_text(errors="replace").split()
            if first and first[0] in {"ssh-dss", "ssh-rsa"}:
                weak_host_keys.append(f"{pub.name}:{first[0]}")
        except OSError:
            pass

    weak_user_pubkeys: list[str] = []
    bad_privkey_modes: list[str] = []
    ssh_dir = Path.home() / ".ssh"
    if ssh_dir.is_dir():
        for item in sorted(ssh_dir.iterdir()):
            if item.name.endswith(".pub") and item.is_file():
                try:
                    parts = item.read_text(errors="replace").split()
                    if parts and parts[0] in {"ssh-dss", "ssh-rsa"}:
                        weak_user_pubkeys.append(f"~/.ssh/{item.name}:{parts[0]}")
                except OSError:
                    pass
            elif item.name.startswith("id_") and not item.name.endswith(".pub") and item.is_file():
                # Stat metadata ONLY — never open private key files!
                try:
                    mode = stat.S_IMODE(item.stat().st_mode)
                    if mode & 0o077:
                        bad_privkey_modes.append(f"~/.ssh/{item.name}:0{mode:o}")
                except OSError:
                    pass

    # WireGuard safe check: never invoke `wg show dump` or `preshared-keys`.
    wg_ifaces: list[str] = []
    wg_peers_without_psk = 0
    rc_wg, out_wg = run_cmd(["wg", "show", "interfaces"], timeout, tracker)
    if rc_wg == 0 and out_wg.strip():
        wg_ifaces = out_wg.strip().split()
        for iface in wg_ifaces[:8]:
            # `wg show <iface>` prints `private key: (hidden)` and `preshared key: (hidden)` only.
            rc_i, out_i = run_cmd(["wg", "show", iface], timeout, tracker)
            if rc_i == 0 and out_i:
                peers = sum(1 for ln in out_i.splitlines() if ln.strip().startswith("peer:"))
                psks = sum(1 for ln in out_i.splitlines() if "preshared key:" in ln.lower())
                if peers > psks:
                    wg_peers_without_psk += (peers - psks)

    algos: list[dict[str, Any]] = []
    if kex_list:
        top_kex = kex_list[0]
        is_pq = ("mlkem" in top_kex or "sntrup761" in top_kex)
        algos.append({
            "component": "ssh-kex-preferred",
            "algorithm": top_kex,
            "family": "hybrid-pq" if is_pq else "classical-ecdh-or-dh",
            "bits": 256,
            "quantum_status": "hybrid_post_quantum" if is_pq else "quantum_vulnerable_shor",
            "location": "ssh client default KexAlgorithms[0]",
        })
    if openssl_version != "unavailable":
        algos.append({
            "component": "openssl-runtime",
            "algorithm": openssl_version,
            "family": "tls-provider",
            "bits": 256 if pq_tls_capable else 128,
            "quantum_status": "hybrid_post_quantum" if pq_tls_capable else "classical_only_runtime",
            "location": "system openssl",
        })

    return {
        "openssl_version": openssl_version,
        "pq_tls_capable": pq_tls_capable,
        "pre_standard_kem_runtime": pre_standard_kem_runtime,
        "ipsec_classical_configs": ipsec_classical,
        "tls_legacy_protocols_enabled": [],
        "static_rsa_kex_enabled": False,
        "ssh": {
            "version": ssh_version,
            "pq_kex_enabled": pq_ssh,
            "pq_kex_shadowed_by_classical": pq_ssh_shadowed,
            "kex_algorithms": kex_list[:8],
            "weak_host_keys": weak_host_keys,
            "weak_user_pubkeys": weak_user_pubkeys,
            "bad_private_key_permissions": bad_privkey_modes,
            "permit_root_login": permit_root,
            "password_auth": password_auth,
        },
        "wireguard": {
            "interfaces": wg_ifaces,
            "peers_without_psk": wg_peers_without_psk,
        },
        "jwt_oidc_algorithms": [],
        "dkim_bits": None,
        "algorithms_observed": algos,
    }


def scan_workspace_metadata(scan_dir: Path, tracker: RedactionTracker) -> dict[str, Any]:
    """Read-only software, code, variable-hygiene, IaC & lockfile scan; never opens secret files."""
    lockfiles_scanned = 0
    flagged_packages: list[dict[str, str]] = []
    jwt_algos: set[str] = set()
    static_rsa_cfg = False
    legacy_tls_protos: set[str] = set()
    wg_conf_missing_psk = 0
    broad_dotenv_perms: list[str] = []
    unignored_dotenv: list[str] = []
    insecure_runtime_vars: list[str] = []
    weak_code_crypto: list[str] = []
    dockerfile_gaps: list[str] = []
    unpinned_ci_actions: list[str] = []
    pre_standard_pqc: list[str] = []
    pqc_sidechannel_libs: list[str] = []
    ipsec_classical_files: list[str] = []
    hardcoded_crypto_files: set[str] = set()
    tls_inspection_strip: list[str] = []
    rsa_key_wrap_hits: list[str] = []
    aes128_hits: list[str] = []
    legacy_auth_hits: list[str] = []

    if not scan_dir.is_dir():
        return {
            "lockfiles_scanned": 0,
            "flagged_packages": [],
            "jwt_algos": [],
            "static_rsa_cfg": False,
            "legacy_tls_protos": [],
            "wg_conf_missing_psk": 0,
            "broad_dotenv_perms": [],
            "unignored_dotenv": [],
            "insecure_runtime_vars": [],
            "weak_code_crypto": [],
            "dockerfile_gaps": [],
            "unpinned_ci_actions": [],
            "pre_standard_pqc": [],
            "pqc_sidechannel_libs": [],
            "ipsec_classical_files": [],
            "hardcoded_crypto_files": [],
            "tls_inspection_strip": [],
            "rsa_key_wrap_hits": [],
            "aes128_hits": [],
            "legacy_auth_hits": [],
        }

    # Check .gitignore coverage for .env files without ever opening .env contents
    gitignore_file = scan_dir / ".gitignore"
    gitignore_txt = ""
    if gitignore_file.is_file() and not gitignore_file.is_symlink():
        try:
            gitignore_txt = gitignore_file.read_text(encoding="utf-8", errors="replace")
        except OSError:
            gitignore_txt = ""
    ignores_dotenv = bool(re.search(r"(?m)^\s*(?:\*\*/)?\.env(?:\*|\b)", gitignore_txt))

    files_visited = 0
    for root, dirs, files in os.walk(scan_dir):
        # Allow descending into .github/workflows while skipping .git, node_modules, etc.
        dirs[:] = [
            d for d in dirs
            if d not in EXCLUDED_DIRS and (d == ".github" or not d.startswith("."))
        ]
        for fname in files:
            if files_visited >= 1500:
                break
            fpath = Path(root) / fname
            if fpath.is_symlink():
                continue
            rel = str(fpath.relative_to(scan_dir))

            # Metadata-ONLY variable boundary check on .env* (stat() only — NEVER open secret .env!)
            if fname.startswith(".env") and fname not in {".env.example", ".env.sample", ".env.template"}:
                try:
                    mode = fpath.stat().st_mode & 0o777
                    if (mode & 0o044) != 0:
                        broad_dotenv_perms.append(f"{rel} (mode {oct(mode)})")
                    if (scan_dir / ".git").exists() and not ignores_dotenv:
                        unignored_dotenv.append(rel)
                except OSError:
                    pass
                continue

            if is_secret_path(fpath):
                continue
            files_visited += 1

            if fname in {"package-lock.json", "npm-shrinkwrap.json"}:
                lockfiles_scanned += 1
                try:
                    doc = json.loads(fpath.read_text(encoding="utf-8", errors="replace"))
                    pkgs = doc.get("packages") or {}
                    for pkg_key, meta in pkgs.items():
                        if not isinstance(meta, dict):
                            continue
                        ver = str(meta.get("version") or "")
                        clean_name = pkg_key.split("node_modules/")[-1] if "node_modules/" in pkg_key else pkg_key
                        if clean_name in COMPROMISED_NPM_COORDINATES and ver in COMPROMISED_NPM_COORDINATES[clean_name]:
                            flagged_packages.append({
                                "ecosystem": "npm",
                                "package": clean_name,
                                "version": ver,
                                "location": rel,
                                "reason": "Matches bundled npm supply-chain compromise indicator",
                            })
                        elif clean_name == "crypto-js" and ver.startswith(("3.", "4.0.", "4.1.")):
                            flagged_packages.append({
                                "ecosystem": "npm",
                                "package": clean_name,
                                "version": ver,
                                "location": rel,
                                "reason": "Vulnerable PBKDF2 default in crypto-js < 4.2.0 (CVE-2023-46233)",
                            })
                        elif clean_name == "request":
                            flagged_packages.append({
                                "ecosystem": "npm",
                                "package": clean_name,
                                "version": ver or "any",
                                "location": rel,
                                "reason": "Deprecated unmaintained HTTP client (`request`)",
                            })
                except Exception:
                    pass

            elif fname == "package.json":
                lockfiles_scanned += 1
                try:
                    doc = json.loads(fpath.read_text(encoding="utf-8", errors="replace"))
                    all_deps = {**(doc.get("dependencies") or {}), **(doc.get("devDependencies") or {})}
                    for dep_name, spec in all_deps.items():
                        s_val = str(spec).strip()
                        if s_val in {"*", "latest"}:
                            flagged_packages.append({
                                "ecosystem": "npm",
                                "package": dep_name,
                                "version": s_val,
                                "location": rel,
                                "reason": "Unpinned wildcard/latest dependency version allows unreviewed upstream updates",
                            })
                        if re.search(r"kyber|dilithium", dep_name, re.I):
                            pre_standard_pqc.append(f"{rel}: `{dep_name}` uses pre-standard Kyber/Dilithium draft naming instead of finalized FIPS 203/204")
                        if dep_name in {"liboqs-node", "oqs"} and re.search(r"^(?:[~^]?0\.(?:[0-9]|1[01])\.)", s_val):
                            pqc_sidechannel_libs.append(f"{rel}: `{dep_name}@{s_val}` predates lattice timing side-channel fixes")
                except Exception:
                    pass

            elif fname == "requirements.txt":
                lockfiles_scanned += 1
                try:
                    for ln in fpath.read_text(encoding="utf-8", errors="replace").splitlines():
                        s = ln.strip().lower()
                        if not s or s.startswith("#"):
                            continue
                        if s.startswith("pycrypto"):
                            flagged_packages.append({
                                "ecosystem": "pypi",
                                "package": "pycrypto",
                                "version": "any",
                                "location": rel,
                                "reason": "Unmaintained PyCrypto library with known CVEs (replace with pyca/cryptography)",
                            })
                        elif re.match(r"^[a-z0-9_.-]+$", s):
                            flagged_packages.append({
                                "ecosystem": "pypi",
                                "package": s,
                                "version": "unpinned",
                                "location": rel,
                                "reason": "Unpinned Python dependency without version pin (`==`) or hash lock",
                            })
                except OSError:
                    pass

            elif fname == "Dockerfile" or fname.startswith("Dockerfile."):
                try:
                    dtxt = fpath.read_text(encoding="utf-8", errors="replace")
                    if re.search(r"(?im)^FROM\s+\S+:latest\b", dtxt):
                        dockerfile_gaps.append(f"{rel}: unpinned `:latest` container base image")
                    if "FROM " in dtxt and not re.search(r"(?im)^USER\s+(?!root\b)\S+", dtxt):
                        dockerfile_gaps.append(f"{rel}: container runs as root (missing non-root USER directive)")
                    if re.search(r"NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*['\"]?0|PYTHONHTTPSVERIFY\s*=\s*['\"]?0", dtxt):
                        insecure_runtime_vars.append(f"{rel}: disables outbound TLS certificate verification")
                except OSError:
                    pass

            elif ".github/workflows/" in rel.replace("\\", "/") and fpath.suffix.lower() in {".yml", ".yaml"}:
                try:
                    wtxt = fpath.read_text(encoding="utf-8", errors="replace")
                    for m in re.finditer(r"(?m)^\s*-?\s*uses:\s*([^\s#@]+@([^\s#]+))", wtxt):
                        full_use, ref = m.group(1), m.group(2)
                        if not full_use.startswith("./") and not re.fullmatch(r"[0-9a-fA-F]{40}", ref):
                            unpinned_ci_actions.append(f"{rel}: `{full_use}` uses mutable tag instead of 40-char commit SHA")
                except OSError:
                    pass

            elif fname in {".env.example", ".env.sample", ".env.template"} or fpath.suffix.lower() in {
                ".py", ".ts", ".tsx", ".js", ".jsx", ".go", ".conf", ".tf", ".yaml", ".yml"
            }:
                try:
                    if fpath.stat().st_size > 512_000:
                        continue
                    txt = tracker.scrub(fpath.read_text(encoding="utf-8", errors="replace"))
                    for m in re.findall(r"\b(RS256|RS384|RS512|ES256|PS256)\b", txt):
                        jwt_algos.add(m)
                    if re.search(r"TLS_RSA_WITH_|kRSA", txt):
                        static_rsa_cfg = True
                    for pm in re.findall(r"\b(TLSv1(?:\.0|\.1)?|SSLv3)\b", txt):
                        legacy_tls_protos.add(pm)
                    if "[Peer]" in txt and "PublicKey" in txt and "PresharedKey" not in txt:
                        wg_conf_missing_psk += 1
                    if re.search(r"NODE_TLS_REJECT_UNAUTHORIZED\s*[:=]\s*['\"]?0|PYTHONHTTPSVERIFY\s*[:=]\s*['\"]?0|GIT_SSL_NO_VERIFY\s*[:=]\s*['\"]?true", txt, re.I):
                        insecure_runtime_vars.append(f"{rel}: runtime variable disables TLS certificate verification")
                    if re.search(r"(?i)\b(?:FLASK_DEBUG|APP_DEBUG)\s*[:=]\s*['\"]?(?:1|true)\b", txt):
                        insecure_runtime_vars.append(f"{rel}: debug mode variable enabled in configuration")
                    if fpath.suffix.lower() in {".py", ".ts", ".tsx", ".js", ".jsx", ".go"}:
                        if re.search(r"createHash\(\s*['\"](?:md5|sha1)['\"]\)|hashlib\.(?:md5|sha1)\(|alg\s*:\s*['\"]none['\"]", txt):
                            weak_code_crypto.append(f"{rel}: deprecated MD5/SHA-1 digest or unsigned JWT pattern")
                        if re.search(r"\b(?:generateKeyPair(?:Sync)?|RSA\.generate|rsa\.GenerateKey|ecdsa\.GenerateKey|createCipheriv)\b", txt):
                            hardcoded_crypto_files.add(rel)
                    if re.search(r"\b(?:X25519Kyber768Draft00|Kyber512|Kyber768|Kyber1024|Dilithium2|Dilithium3|Dilithium5|pqcrystals)\b", txt):
                        pre_standard_pqc.append(f"{rel}: pre-standard Kyber/Dilithium identifier (migrate to FIPS 203 ML-KEM / FIPS 204 ML-DSA)")
                    if fpath.suffix.lower() == ".conf" and re.search(r"(?im)^\s*(?:ike|esp|proposals)\s*=", txt) and not re.search(r"mlkem|ke1_", txt, re.I):
                        ipsec_classical_files.append(f"{rel}: IKEv2/IPsec proposal lacks RFC 9370 hybrid ML-KEM key exchange")
                    if re.search(r"\b(?:ssl_bump|mitmproxy|kind:\s*DestinationRule)\b", txt) and not re.search(r"X25519MLKEM768|MLKEM|ML-KEM", txt, re.I):
                        tls_inspection_strip.append(f"{rel}: TLS-intercepting proxy or service mesh config omits X25519MLKEM768 (RFC 10024)")
                    if re.search(r"\b(?:RSA-OAEP|RSAES_OAEP|RSA_PKCS1_OAEP_PADDING|RSAES-PKCS1-v1_5)\b", txt):
                        rsa_key_wrap_hits.append(f"{rel}: RSA key-wrapping detected (migrate archive/KMS wrapping to ML-KEM or AES-256)")
                    if re.search(r"\b(?:aes-128-(?:gcm|cbc|ctr)|TLS_AES_128_GCM_SHA256|AES128-GCM)\b", txt, re.I):
                        aes128_hits.append(f"{rel}: AES-128 cipher configured (schedule upgrade to AES-256 at next key rotation)")
                    if re.search(r"\b(?:NTLMv1|NTLMv2|RC4-HMAC|DES-CBC-CRC|DES-CBC-MD5|allow_weak_crypto\s*=\s*true)\b", txt, re.I):
                        legacy_auth_hits.append(f"{rel}: legacy RC4, DES, or NTLM authentication enabled")
                except OSError:
                    pass

    return {
        "lockfiles_scanned": lockfiles_scanned,
        "flagged_packages": flagged_packages[:40],
        "jwt_algos": sorted(jwt_algos),
        "static_rsa_cfg": static_rsa_cfg,
        "legacy_tls_protos": sorted(legacy_tls_protos),
        "wg_conf_missing_psk": wg_conf_missing_psk,
        "broad_dotenv_perms": broad_dotenv_perms[:20],
        "unignored_dotenv": unignored_dotenv[:20],
        "insecure_runtime_vars": insecure_runtime_vars[:20],
        "weak_code_crypto": weak_code_crypto[:20],
        "dockerfile_gaps": dockerfile_gaps[:20],
        "unpinned_ci_actions": unpinned_ci_actions[:20],
        "pre_standard_pqc": pre_standard_pqc[:20],
        "pqc_sidechannel_libs": pqc_sidechannel_libs[:20],
        "ipsec_classical_files": ipsec_classical_files[:20],
        "hardcoded_crypto_files": sorted(hardcoded_crypto_files)[:30],
        "tls_inspection_strip": tls_inspection_strip[:20],
        "rsa_key_wrap_hits": rsa_key_wrap_hits[:20],
        "aes128_hits": aes128_hits[:20],
        "legacy_auth_hits": legacy_auth_hits[:20],
    }


def probe_tls_targets(targets: list[str], timeout: int) -> list[dict[str, Any]]:
    results: list[dict[str, Any]] = []
    for item in targets[:20]:
        host, _, port_s = item.partition(":")
        port = int(port_s) if port_s.isdigit() else 443
        try:
            ctx = ssl.create_default_context()
            with socket.create_connection((host, port), timeout=timeout) as sock:
                with ctx.wrap_socket(sock, server_hostname=host) as ssock:
                    ver = ssock.version() or "unknown"
                    cipher_tuple = ssock.cipher() or ("unknown", "unknown", 0)
                    cipher_name = cipher_tuple[0]
                    is_static_rsa = cipher_name.startswith("TLS_RSA_") or (
                        ver in {"TLSv1", "TLSv1.1", "TLSv1.2"}
                        and "ECDHE" not in cipher_name
                        and "DHE" not in cipher_name
                    )
                    results.append({
                        "target": f"{host}:{port}",
                        "tls_version": ver,
                        "cipher": cipher_name,
                        "static_rsa": is_static_rsa,
                    })
        except Exception as exc:
            results.append({"target": f"{host}:{port}", "error": type(exc).__name__})
    return results


def build_findings(
    host: dict[str, str],
    firewall: dict[str, Any],
    disk: dict[str, str],
    endpoint: dict[str, str],
    listeners: list[dict[str, Any]],
    persistence: list[dict[str, str]],
    crypto: dict[str, Any],
    workspace: dict[str, Any],
    tls_probes: list[dict[str, Any]],
) -> list[dict[str, Any]]:
    findings: list[dict[str, Any]] = []
    os_family = host["os_family"]
    eol = host["eol_status"] == "eol"

    if eol:
        findings.append({
            "id": "SHIELD-LEGACY-EOL-OS",
            "severity": "critical",
            "category": "legacy_isolation",
            "title": f"End-of-Life operating system detected ({host['os_distro']})",
            "evidence": host["eol_detail"],
            "fix_mode": "gateway_isolation",
            "downtime": "zero_downtime",
            "recommended_fix": "Do NOT force in-place OpenSSL/libc upgrades on End-of-Life OS. Isolate host on a dedicated private VLAN with default-deny egress and front required ports with a WireGuard PQ-PSK or TLS 1.3 X25519MLKEM768 translating gateway.",
            "check_cmd": "titanward crypto stealth-gateway --profile legacy-vlan",
            "verify_cmd": "nmap -Pn <legacy-lan-ip>  # verify only gateway IP reaches legacy service port",
            "undo_cmd": "Remove VLAN ACL rule and point upstream VIP back to original host IP",
        })

    if firewall["docker_ufw_bypass"]:
        findings.append({
            "id": "SHIELD-NET-DOCKER-UFW-BYPASS",
            "severity": "critical",
            "category": "network_exposure",
            "title": "Docker published ports bypass host UFW firewall on 0.0.0.0",
            "evidence": firewall["detail"],
            "fix_mode": "in_place",
            "downtime": "brief_reload",
            "recommended_fix": "Bind internal container ports explicitly to 127.0.0.1:PORT:PORT in compose/systemd units and enforce DOCKER-USER drop rules for non-allowlisted ingress.",
            "check_cmd": "docker ps --format 'table {{.Names}}\\t{{.Ports}}'",
            "verify_cmd": "ss -tulnp | grep -E '0\\.0\\.0\\.0:|:::'",
            "undo_cmd": "Restore previous compose port mapping and flush DOCKER-USER custom rule",
        })
    elif firewall["status"] == "disabled":
        findings.append({
            "id": "SHIELD-NET-FIREWALL-DISABLED",
            "severity": "high",
            "category": "network_exposure",
            "title": f"Host firewall is disabled ({firewall['engine']})",
            "evidence": firewall["detail"],
            "fix_mode": "in_place",
            "downtime": "zero_downtime",
            "recommended_fix": "Allowlist active administrative and production ingress ports first, then enable host firewall default-deny incoming policy.",
            "check_cmd": "sudo ufw show added" if os_family == "linux" else "/usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate",
            "verify_cmd": "sudo ufw status verbose" if os_family == "linux" else "/usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate",
            "undo_cmd": "sudo ufw disable" if os_family == "linux" else "sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate off",
        })

    for lst in listeners:
        if lst["exposure"] == "public_or_lan" and lst["port"] in DANGEROUS_PUBLIC_PORTS:
            label, sev = DANGEROUS_PUBLIC_PORTS[lst["port"]]
            findings.append({
                "id": f"SHIELD-NET-EXPOSED-PORT-{lst['port']}",
                "severity": sev,
                "category": "network_exposure",
                "title": f"{label} listening on {lst['bind']}:{lst['port']} ({lst['process']})",
                "evidence": f"{lst['proto']} {lst['bind']}:{lst['port']} owned by {lst['process']}",
                "fix_mode": "gateway_isolation" if eol else "in_place",
                "downtime": "brief_reload",
                "recommended_fix": f"Bind {label} ({lst['port']}) to 127.0.0.1 / private WireGuard interface or restrict ingress to allowlisted application peers.",
                "check_cmd": f"ss -tulnp | grep ':{lst['port']} '",
                "verify_cmd": f"nc -zv -w 2 <public-ip> {lst['port']}  # expect connection refused/filtered",
                "undo_cmd": f"Re-enable previous bind address or firewall allow rule for port {lst['port']}",
            })

    for item in persistence:
        findings.append({
            "id": "SHIELD-PERSIST-SUSPICIOUS-AUTORUN",
            "severity": "critical",
            "category": "malware_persistence",
            "title": f"Suspicious startup persistence entry in {Path(item['location']).name}",
            "evidence": f"{item['location']}: {item['reason']}",
            "fix_mode": "in_place",
            "downtime": "zero_downtime",
            "recommended_fix": "Quarantine the plist/startup entry to an offline evidence folder (do not delete before hash capture), unload the job, and verify binary code signature.",
            "check_cmd": f"plutil -p '{item['location']}'" if os_family == "macos" else f"ls -la '{item['location']}'",
            "verify_cmd": "launchctl list | grep -v com.apple" if os_family == "macos" else "crontab -l",
            "undo_cmd": f"Move quarantined startup file back to '{item['location']}' if verified legitimate",
        })

    for pkg in workspace["flagged_packages"]:
        findings.append({
            "id": "SHIELD-SUPPLY-FLAGGED-DEPENDENCY",
            "severity": "critical",
            "category": "vulnerability",
            "title": f"Flagged {pkg['ecosystem']} dependency {pkg['package']}@{pkg['version']}",
            "evidence": f"{pkg['location']}: {pkg['reason']}",
            "fix_mode": "in_place",
            "downtime": "zero_downtime",
            "recommended_fix": f"Pin {pkg['package']} to a verified clean release in {pkg['location']}, rebuild with --ignore-scripts, and rotate CI build credentials if installed on a runner.",
            "check_cmd": "titanward npm --lock package-lock.json",
            "verify_cmd": "titanward npm --lock package-lock.json",
            "undo_cmd": "git checkout -- package-lock.json",
        })

    if disk["status"] == "disabled":
        findings.append({
            "id": "SHIELD-ENDPOINT-DISK-UNENCRYPTED",
            "severity": "high",
            "category": "endpoint_hardening",
            "title": f"Full-disk encryption is disabled ({disk['engine']})",
            "evidence": f"OS={os_family}, disk encryption reported disabled",
            "fix_mode": "in_place",
            "downtime": "zero_downtime",
            "recommended_fix": "Enable FileVault (macOS), BitLocker with TPM protector (Windows), or LUKS encryption and escrow recovery key in offline vault.",
            "check_cmd": "fdesetup status" if os_family == "macos" else "manage-bde -status C:",
            "verify_cmd": "fdesetup status" if os_family == "macos" else "manage-bde -status C:",
            "undo_cmd": "Standard OS decryption workflow (not recommended)",
        })

    if endpoint["status"] in {"degraded", "absent"}:
        findings.append({
            "id": "SHIELD-ENDPOINT-PROTECTION-DEGRADED",
            "severity": "high",
            "category": "endpoint_hardening",
            "title": "Endpoint tamper or malware protection is degraded",
            "evidence": endpoint["detail"],
            "fix_mode": "in_place",
            "downtime": "zero_downtime",
            "recommended_fix": "Re-enable Gatekeeper / Microsoft Defender Real-Time & Tamper Protection via MDM or Group Policy.",
            "check_cmd": "spctl --status" if os_family == "macos" else "Get-MpComputerStatus",
            "verify_cmd": "spctl --status" if os_family == "macos" else "Get-MpComputerStatus",
            "undo_cmd": "Revert MDM policy profile if blocking signed line-of-business binary",
        })

    if workspace["static_rsa_cfg"] or any(p.get("static_rsa") for p in tls_probes):
        findings.append({
            "id": "SHIELD-CRYPTO-TLS-STATIC-RSA",
            "severity": "critical",
            "category": "post_quantum_crypto",
            "title": "Static RSA key transport (TLS_RSA_* / kRSA) enabled — lacks forward secrecy",
            "evidence": "Detected static RSA cipher configuration or handshake; one compromised RSA key decrypts all recorded past sessions.",
            "fix_mode": "gateway_isolation" if eol else "in_place",
            "downtime": "brief_reload",
            "recommended_fix": "Disable TLS 1.0/1.1 and all TLS_RSA_* ciphers; enforce TLS 1.3 + TLS 1.2 ECDHE-only ciphers with X25519MLKEM768 hybrid key agreement.",
            "check_cmd": "openssl s_client -connect <host>:443 -cipher 'kRSA' </dev/null",
            "verify_cmd": "openssl s_client -connect <host>:443 -tls1_3 -groups X25519MLKEM768:X25519 </dev/null",
            "undo_cmd": "Restore backed-up nginx/haproxy/caddy TLS configuration and reload service",
        })

    if not crypto["pq_tls_capable"] and not eol:
        findings.append({
            "id": "SHIELD-CRYPTO-TLS-NO-PQ-KEM",
            "severity": "medium",
            "category": "post_quantum_crypto",
            "title": f"System TLS runtime ({crypto['openssl_version']}) lacks hybrid ML-KEM key agreement",
            "evidence": f"openssl list -kem-algorithms returned no ML-KEM provider ({crypto['openssl_version']})",
            "fix_mode": "in_place",
            "downtime": "zero_downtime",
            "recommended_fix": "Terminate external TLS on OpenSSL 3.5+, BoringSSL/Cloudflare edge, or Caddy/Nginx built with X25519MLKEM768:X25519 hybrid key exchange to stop harvest-now-decrypt-later capture.",
            "check_cmd": "openssl list -kem-algorithms",
            "verify_cmd": "openssl s_client -connect <host>:443 -groups X25519MLKEM768 </dev/null",
            "undo_cmd": "Set TLS groups back to X25519:secp256r1 if a non-compliant middlebox drops large ClientHello",
        })

    if not crypto["ssh"]["pq_kex_enabled"]:
        shadow_note = (
            " (classical KEX precedes ML-KEM/sntrup761 in KexAlgorithms[0] — common on macOS 100-macos.conf)"
            if crypto["ssh"].get("pq_kex_shadowed_by_classical")
            else ""
        )
        findings.append({
            "id": "SHIELD-SSH-NO-PQ-KEX",
            "severity": "high" if eol else "medium",
            "category": "post_quantum_crypto",
            "title": f"SSH ({crypto['ssh']['version']}) does not negotiate hybrid post-quantum KEX first{shadow_note}",
            "evidence": f"Preferred KexAlgorithms[0..2]: {', '.join(crypto['ssh']['kex_algorithms'][:3]) or 'unavailable'}",
            "fix_mode": "gateway_isolation" if eol else "in_place",
            "downtime": "zero_downtime",
            "recommended_fix": "Ensure mlkem768x25519-sha256 (OpenSSH 10+ default) or sntrup761x25519-sha512@openssh.com is FIRST in KexAlgorithms (overriding macOS P-256-first defaults and upgrading Windows built-in OpenSSH), or jump through a WireGuard PQ-PSK bastion for EOL hosts.",
            "check_cmd": "ssh -G localhost | grep '^kexalgorithms'",
            "verify_cmd": "ssh -v localhost exit 2>&1 | grep 'kex: algorithm:'",
            "undo_cmd": "Remove drop-in /etc/ssh/sshd_config.d/50-shield-pq.conf and reload sshd",
        })

    if crypto["ssh"]["permit_root_login"] == "yes" or crypto["ssh"]["password_auth"] == "yes":
        findings.append({
            "id": "SHIELD-SSH-PASSWORD-OR-ROOT",
            "severity": "high",
            "category": "endpoint_hardening",
            "title": "SSH daemon permits password login or direct root login",
            "evidence": f"PermitRootLogin={crypto['ssh']['permit_root_login']}, PasswordAuthentication={crypto['ssh']['password_auth']}",
            "fix_mode": "in_place",
            "downtime": "zero_downtime",
            "recommended_fix": "Verify Ed25519 authorized_keys login in a second active session first, then set PermitRootLogin prohibit-password and PasswordAuthentication no in sshd_config.",
            "check_cmd": "sudo sshd -T | grep -E '^(permitrootlogin|passwordauthentication)'",
            "verify_cmd": "ssh -o PreferredAuthentications=password <host>  # expect Permission denied (publickey)",
            "undo_cmd": "Restore /etc/ssh/sshd_config.bak and sudo systemctl reload sshd",
        })

    if crypto["ssh"]["bad_private_key_permissions"]:
        findings.append({
            "id": "SHIELD-SSH-PRIVKEY-PERMS",
            "severity": "high",
            "category": "endpoint_hardening",
            "title": "Local SSH private key file has overly broad permissions",
            "evidence": ", ".join(crypto["ssh"]["bad_private_key_permissions"]),
            "fix_mode": "in_place",
            "downtime": "zero_downtime",
            "recommended_fix": "Restrict SSH directory to 0700 and private key files to 0600 (metadata fix only; key contents untouched).",
            "check_cmd": "stat -f '%Mp%Lp %N' ~/.ssh/id_* 2>/dev/null || stat -c '%a %n' ~/.ssh/id_*",
            "verify_cmd": "chmod 700 ~/.ssh && chmod 600 ~/.ssh/id_* (excluding *.pub)",
            "undo_cmd": "No rollback needed; 0600 is required by OpenSSH itself",
        })

    total_wg_no_psk = crypto["wireguard"]["peers_without_psk"] + workspace["wg_conf_missing_psk"]
    if total_wg_no_psk > 0:
        findings.append({
            "id": "SHIELD-CRYPTO-WG-NO-PSK",
            "severity": "high",
            "category": "post_quantum_crypto",
            "title": f"WireGuard tunnel peer(s) missing 256-bit PresharedKey ({total_wg_no_psk} peer(s))",
            "evidence": "Classical Curve25519 WireGuard handshake without a 256-bit symmetric PresharedKey (or Rosenpass ML-KEM rotator) is exposed to harvest-now-decrypt-later.",
            "fix_mode": "in_place",
            "downtime": "zero_downtime",
            "recommended_fix": "Generate a 256-bit symmetric PresharedKey per WireGuard peer (`wg genpsk`) or deploy Rosenpass PQ-PSK rotation sidecar.",
            "check_cmd": "sudo wg show",
            "verify_cmd": "sudo wg show | grep 'preshared key: (hidden)'",
            "undo_cmd": "wg set <iface> peer <PUBKEY> preshared-key /dev/null",
        })

    rsa_jwts = [a for a in workspace["jwt_algos"] if a.startswith(("RS", "PS"))]
    if rsa_jwts:
        findings.append({
            "id": "SHIELD-IDP-JWT-RSA-SIGNING",
            "severity": "medium",
            "category": "post_quantum_crypto",
            "title": f"OIDC / JWT signing uses classical RSA ({', '.join(rsa_jwts)})",
            "evidence": f"Observed JWT signing algorithms in workspace: {', '.join(rsa_jwts)}",
            "fix_mode": "dns_or_idp_staged",
            "downtime": "zero_downtime",
            "recommended_fix": "Publish a dual-key JWKS rotation schedule (EdDSA Ed25519 today + ML-DSA-65 / FIPS 204 composite verification readiness) before retiring older RSA kid entries.",
            "check_cmd": "titanward crypto jwks --check-oidc <issuer>",
            "verify_cmd": "Verify both new and legacy `kid` entries appear in /.well-known/jwks.json for 1 token TTL before switching active signer",
            "undo_cmd": "Switch active signing `kid` back to retained previous key already present in JWKS",
        })

    if workspace.get("unignored_dotenv"):
        findings.append({
            "id": "SHIELD-ENV-UNIGNORED-DOTENV",
            "severity": "critical",
            "category": "env_and_variables",
            "title": f"Environment secret file present without `.gitignore` protection ({len(workspace['unignored_dotenv'])} file(s))",
            "evidence": ", ".join(workspace["unignored_dotenv"][:5]),
            "fix_mode": "in_place",
            "downtime": "zero_downtime",
            "recommended_fix": "Add `.env` and `.env.*` (excluding `.env.example`) to `.gitignore`, verify zero `.env` commits in git history, and rotate any credentials if ever pushed.",
            "check_cmd": "git status --ignored --short",
            "verify_cmd": "git check-ignore -v .env",
            "undo_cmd": "Restore previous .gitignore line if needed",
        })

    if workspace.get("broad_dotenv_perms"):
        findings.append({
            "id": "SHIELD-ENV-BROAD-PERMS",
            "severity": "high",
            "category": "env_and_variables",
            "title": f"Environment variable file has world/group-readable permissions ({len(workspace['broad_dotenv_perms'])} file(s))",
            "evidence": ", ".join(workspace["broad_dotenv_perms"][:5]),
            "fix_mode": "in_place",
            "downtime": "zero_downtime",
            "recommended_fix": "Restrict `.env*` file permissions to owner-only (`chmod 600 .env*`) so co-located processes or container breakouts cannot read runtime secrets.",
            "check_cmd": "stat -c '%a %n' .env* 2>/dev/null || stat -f '%Mp%Lp %N' .env*",
            "verify_cmd": "chmod 600 .env*",
            "undo_cmd": "chmod 640 .env* if a dedicated service group requires read access",
        })

    if workspace.get("insecure_runtime_vars"):
        findings.append({
            "id": "SHIELD-ENV-INSECURE-RUNTIME-VARS",
            "severity": "high",
            "category": "env_and_variables",
            "title": f"Insecure runtime environment variable or TLS-bypass flag in configuration ({len(workspace['insecure_runtime_vars'])} match(es))",
            "evidence": "; ".join(workspace["insecure_runtime_vars"][:4]),
            "fix_mode": "in_place",
            "downtime": "brief_reload",
            "recommended_fix": "Remove `NODE_TLS_REJECT_UNAUTHORIZED=0`, `PYTHONHTTPSVERIFY=0`, and production `DEBUG=true` flags; pin internal CA bundles explicitly via `NODE_EXTRA_CA_CERTS` or `SSL_CERT_FILE`.",
            "check_cmd": "grep -rnE 'TLS_REJECT_UNAUTHORIZED|PYTHONHTTPSVERIFY|FLASK_DEBUG' .",
            "verify_cmd": "Confirm outbound HTTPS connections validate CA chains cleanly",
            "undo_cmd": "Revert container/service environment block to previous release",
        })

    if workspace.get("weak_code_crypto"):
        findings.append({
            "id": "SHIELD-CODE-WEAK-CRYPTO",
            "severity": "high",
            "category": "software_and_code",
            "title": f"Deprecated cryptographic primitive or unsigned token pattern in source code ({len(workspace['weak_code_crypto'])} file(s))",
            "evidence": "; ".join(workspace["weak_code_crypto"][:4]),
            "fix_mode": "in_place",
            "downtime": "zero_downtime",
            "recommended_fix": "Replace MD5/SHA-1 security digests with SHA-256/BLAKE2b (or Argon2id for passwords) and enforce explicit asymmetric algorithm allowlists in JWT verifiers.",
            "check_cmd": "git grep -nE 'createHash.*(md5|sha1)|hashlib\\.(md5|sha1)'",
            "verify_cmd": "Run unit and integration test suites after cryptographic primitive upgrade",
            "undo_cmd": "git revert <commit>",
        })

    if workspace.get("dockerfile_gaps"):
        findings.append({
            "id": "SHIELD-IAC-DOCKERFILE-POSTURE",
            "severity": "medium",
            "category": "dependencies_and_ci",
            "title": f"Container build manifest uses root runtime or unpinned `:latest` image ({len(workspace['dockerfile_gaps'])} issue(s))",
            "evidence": "; ".join(workspace["dockerfile_gaps"][:4]),
            "fix_mode": "in_place",
            "downtime": "brief_reload",
            "recommended_fix": "Pin base images to explicit version/digest tags and add a dedicated non-root `USER` instruction in Dockerfiles.",
            "check_cmd": "grep -nE '^(FROM|USER)' Dockerfile*",
            "verify_cmd": "docker run --rm <image> id -u  # expect non-zero UID",
            "undo_cmd": "Roll back to previous container image tag",
        })

    if workspace.get("unpinned_ci_actions"):
        findings.append({
            "id": "SHIELD-IAC-CI-UNPINNED-ACTIONS",
            "severity": "medium",
            "category": "dependencies_and_ci",
            "title": f"CI/CD workflow references third-party actions by mutable tag instead of commit SHA ({len(workspace['unpinned_ci_actions'])} ref(s))",
            "evidence": "; ".join(workspace["unpinned_ci_actions"][:4]),
            "fix_mode": "in_place",
            "downtime": "zero_downtime",
            "recommended_fix": "Pin third-party GitHub Actions to full 40-character commit SHAs to block upstream tag-hijack supply-chain attacks.",
            "check_cmd": "grep -rn 'uses:' .github/workflows/",
            "verify_cmd": "Confirm all external `uses:` lines end with `@<40-hex-sha>`",
            "undo_cmd": "git checkout -- .github/workflows/",
        })

    draft_pqc_hits = list(workspace.get("pre_standard_pqc", []))
    if crypto.get("pre_standard_kem_runtime"):
        draft_pqc_hits.append(f"OpenSSL runtime ({crypto['openssl_version']}) exposes draft Kyber without finalized FIPS 203 ML-KEM")
    if draft_pqc_hits:
        findings.append({
            "id": "SHIELD-CRYPTO-PRE-STANDARD-PQC",
            "severity": "high",
            "category": "post_quantum_crypto",
            "title": f"Pre-standard Kyber or Dilithium draft implementation detected ({len(draft_pqc_hits)} match(es))",
            "evidence": "; ".join(draft_pqc_hits[:4]),
            "fix_mode": "in_place",
            "downtime": "brief_reload",
            "recommended_fix": "Replace pre-standard Kyber768Draft00 / CRYSTALS-Kyber / CRYSTALS-Dilithium packages and group names with finalized NIST FIPS 203 (X25519MLKEM768 / ML-KEM-1024) and FIPS 204 (ML-DSA-65 / ML-DSA-87).",
            "check_cmd": "openssl list -kem-algorithms",
            "verify_cmd": "Confirm X25519MLKEM768 / ML-KEM and ML-DSA identifiers replace draft Kyber/Dilithium names",
            "undo_cmd": "Restore previous TLS group list or dependency lockfile",
        })

    if workspace.get("pqc_sidechannel_libs"):
        findings.append({
            "id": "SHIELD-CRYPTO-PQC-SIDECHANNEL-LIB",
            "severity": "high",
            "category": "post_quantum_crypto",
            "title": f"Post-quantum library version predates lattice timing side-channel fixes ({len(workspace['pqc_sidechannel_libs'])} pkg(s))",
            "evidence": "; ".join(workspace["pqc_sidechannel_libs"][:4]),
            "fix_mode": "in_place",
            "downtime": "zero_downtime",
            "recommended_fix": "Upgrade PQC provider libraries (OpenSSL >= 3.5, current BoringSSL/AWS-LC, or liboqs >= 0.12.0) to constant-time FIPS 203/204 builds.",
            "check_cmd": "titanward npm --lock package-lock.json",
            "verify_cmd": "Verify updated constant-time library version in lockfile",
            "undo_cmd": "git checkout -- package.json package-lock.json",
        })

    ipsec_hits = [*crypto.get("ipsec_classical_configs", []), *workspace.get("ipsec_classical_files", [])]
    if ipsec_hits:
        findings.append({
            "id": "SHIELD-NET-IPSEC-CLASSICAL-KEX",
            "severity": "medium",
            "category": "post_quantum_crypto",
            "title": f"IKEv2 / IPsec VPN configuration uses classical Diffie-Hellman without RFC 9370 hybrid ML-KEM ({len(ipsec_hits)} file(s))",
            "evidence": "; ".join(ipsec_hits[:4]),
            "fix_mode": "in_place",
            "downtime": "brief_reload",
            "recommended_fix": "Add RFC 9370 multiple key exchanges (`ke1_mlkem768` / `ke1_mlkem1024`) to strongSwan/Libreswan IKEv2 proposals or encapsulate legacy IPsec inside a WireGuard 256-bit PQ-PSK tunnel.",
            "check_cmd": "swanctl --list-conns 2>/dev/null || ipsec status",
            "verify_cmd": "Verify negotiated IKEv2 SA includes additional ML-KEM key exchange",
            "undo_cmd": "Restore previous swanctl/ipsec proposal and reload daemon",
        })

    agility_files = workspace.get("hardcoded_crypto_files", [])
    if len(agility_files) >= 3:
        findings.append({
            "id": "SHIELD-CRYPTO-LOW-AGILITY",
            "severity": "medium",
            "category": "software_and_code",
            "title": f"Low crypto-agility: cryptographic primitives hardcoded across {len(agility_files)} separate source files",
            "evidence": ", ".join(agility_files[:5]),
            "fix_mode": "in_place",
            "downtime": "zero_downtime",
            "recommended_fix": "Consolidate key-establishment and signature algorithm selection behind a single configuration-driven crypto provider so transitioning between ML-KEM, HQC, ML-DSA, and SLH-DSA requires no multi-file rewrite.",
            "check_cmd": "git grep -nE 'generateKeyPair|createCipheriv'",
            "verify_cmd": "Confirm cryptographic algorithm identifiers live in a single central policy module",
            "undo_cmd": "git revert <commit>",
        })

    if workspace.get("tls_inspection_strip"):
        findings.append({
            "id": "SHIELD-NET-TLS-INSPECTION-STRIP",
            "severity": "high",
            "category": "post_quantum_crypto",
            "title": f"TLS-inspecting proxy or service mesh omits hybrid X25519MLKEM768 ({len(workspace['tls_inspection_strip'])} file(s))",
            "evidence": "; ".join(workspace["tls_inspection_strip"][:4]),
            "fix_mode": "in_place",
            "downtime": "brief_reload",
            "recommended_fix": "Enable X25519MLKEM768 (RFC 10024) on BOTH client-facing and upstream legs of TLS-decrypting firewalls/proxies (e.g. PAN-OS 12.1+ cipher translation or Istio/Envoy hybrid TLS) so inspection does not silently strip post-quantum key exchange.",
            "check_cmd": "openssl s_client -connect <proxy>:443 -groups X25519MLKEM768 </dev/null",
            "verify_cmd": "Confirm negotiated group is X25519MLKEM768 on both ingress and upstream hops",
            "undo_cmd": "Restore previous proxy or DestinationRule TLS policy",
        })

    if workspace.get("rsa_key_wrap_hits"):
        findings.append({
            "id": "SHIELD-CRYPTO-RSA-KEY-WRAP",
            "severity": "medium",
            "category": "post_quantum_crypto",
            "title": f"RSA key-wrapping pattern detected for stored keys or archives ({len(workspace['rsa_key_wrap_hits'])} file(s))",
            "evidence": "; ".join(workspace["rsa_key_wrap_hits"][:4]),
            "fix_mode": "in_place",
            "downtime": "zero_downtime",
            "recommended_fix": "Wrap data-encryption keys with ML-KEM (Cloud KMS / HSM) or AES-256-KW rather than RSA-OAEP, prioritizing archives that must stay confidential for 10+ years.",
            "check_cmd": "git grep -nE 'RSA-OAEP|RSAES_OAEP|RSA_PKCS1_OAEP_PADDING'",
            "verify_cmd": "Confirm envelope key wrapping uses ML-KEM or 256-bit symmetric key wrap",
            "undo_cmd": "Retain dual-decrypt support for historical archive headers during re-wrap",
        })

    if workspace.get("aes128_hits"):
        findings.append({
            "id": "SHIELD-CRYPTO-AES128-RETIRE",
            "severity": "low",
            "category": "post_quantum_crypto",
            "title": f"AES-128 symmetric cipher configured — schedule upgrade to AES-256 ({len(workspace['aes128_hits'])} file(s))",
            "evidence": "; ".join(workspace["aes128_hits"][:4]),
            "fix_mode": "in_place",
            "downtime": "zero_downtime",
            "recommended_fix": "Prefer AES-256-GCM / ChaCha20-Poly1305 and SHA-384/512 at the next key rotation so Grover's quadratic speedup leaves ~128-bit effective strength.",
            "check_cmd": "git grep -niE 'aes-?128'",
            "verify_cmd": "Confirm cipher policy prefers AES-256-GCM",
            "undo_cmd": "Restore previous cipher preference list",
        })

    if workspace.get("legacy_auth_hits"):
        findings.append({
            "id": "SHIELD-AUTH-LEGACY-NTLM-RC4",
            "severity": "high",
            "category": "endpoint_hardening",
            "title": f"Legacy RC4, DES, or NTLM authentication enabled in configuration ({len(workspace['legacy_auth_hits'])} match(es))",
            "evidence": "; ".join(workspace["legacy_auth_hits"][:4]),
            "fix_mode": "in_place",
            "downtime": "brief_reload",
            "recommended_fix": "Disable RC4, DES, and NTLM authentication; enforce Kerberos AES-256-CTS-HMAC-SHA1-96 and tunnel LDAP traffic over hybrid TLS 1.3.",
            "check_cmd": "git grep -niE 'NTLM|RC4-HMAC|DES-CBC'",
            "verify_cmd": "Confirm authentication logs show zero NTLM/RC4 handshakes before disabling fallback",
            "undo_cmd": "Restore previous Kerberos/LDAP encryption type policy",
        })

    sev_rank = {"critical": 0, "high": 1, "medium": 2, "low": 3}
    findings.sort(key=lambda f: (sev_rank.get(f["severity"], 9), f["id"]))
    return findings


def summarize_findings(host: dict[str, str], findings: list[dict[str, Any]]) -> dict[str, Any]:
    counts = {"critical": 0, "high": 0, "medium": 0, "low": 0}
    for f in findings:
        if f["severity"] in counts:
            counts[f["severity"]] += 1
    gw_profile = "legacy-vlan + wireguard-pq" if host["remediation_strategy"] == "isolate_behind_pq_gateway" else None
    return {
        **counts,
        "recommended_gateway_profile": gw_profile,
        "top_actions": [f["title"] for f in findings[:5]],
    }


def render_markdown(doc: dict[str, Any]) -> str:
    h = doc["host"]
    s = doc["recommendations_summary"]
    lines = [
        f"# Titanward — Initial Host Assessment & Recommendations (`{h['hostname_label']}`)",
        "",
        f"- **Collected:** `{doc['collector']['collected_at']}` via `{doc['collector']['name']} v{doc['collector']['version']}`",
        f"- **OS / Kernel:** `{h['os_distro']}` (`{h['kernel']}`, `{h['arch']}`)",
        f"- **Lifecycle Status:** `{h['eol_status'].upper()}` — {h['eol_detail']}",
        f"- **Remediation Track:** **`{h['remediation_strategy']}`** — {h['strategy_reason']}",
        f"- **Zero-Secret Proof:** `{doc['zero_secret_proof']['secret_files_opened']}` secret files opened · `{doc['zero_secret_proof']['secret_patterns_redacted']}` patterns scrubbed · Read-only=`{doc['collector']['read_only']}`",
        "",
        "## Findings Summary",
        "",
        "| Critical | High | Medium | Low | Total |",
        "|---:|---:|---:|---:|---:|",
        f"| {s['critical']} | {s['high']} | {s['medium']} | {s['low']} | {len(doc['findings'])} |",
        "",
        "## Prioritized Fix Recommendations",
        "",
    ]
    if not doc["findings"]:
        lines.append("No actionable findings detected on this host.")
    for idx, f in enumerate(doc["findings"], 1):
        lines.extend([
            f"### {idx}. [{f['severity'].upper()}] {f['title']} (`{f['id']}`)",
            f"- **Category:** `{f['category']}` · **Fix Mode:** `{f['fix_mode']}` · **Downtime:** `{f['downtime']}`",
            f"- **Evidence:** {f['evidence']}",
            f"- **What to Fix:** {f['recommended_fix']}",
            f"- **Dry-Run / Check:** `{f['check_cmd']}`",
            f"- **Verify Fix:** `{f['verify_cmd']}`",
            f"- **Rollback (`--undo`):** `{f['undo_cmd']}`",
            "",
        ])
    lines.extend([
        "---",
        f"Integrity SHA-256: `{doc['integrity']['content_sha256']}`",
        "Next step: Feed this JSON (plus assessments from all other modern and legacy hosts) into `shield_implementation_plan.py`.",
        "",
    ])
    return "\n".join(lines)


def main(argv: list[str] | None = None) -> int:
    ap = argparse.ArgumentParser(description="Titanward read-only modern infrastructure assessor.")
    ap.add_argument("--out", default="./shield-assessment-out", help="Output directory for JSON and Markdown recommendations")
    ap.add_argument("--label", default="", help="Optional friendly host label (defaults to short hostname)")
    ap.add_argument("--scan-dir", default="", help="Optional project/config directory to scan for lockfiles and crypto configs (skips all secret files)")
    ap.add_argument("--probe-tls", action="append", default=[], help="Optional host:port for passive TLS handshake cipher/KEM check")
    ap.add_argument("--timeout", type=int, default=4, help="Hard timeout in seconds per local command probe (default: 4)")
    args = ap.parse_args(argv)

    if hasattr(os, "nice"):
        try:
            os.nice(10)
        except OSError:
            pass

    tracker = RedactionTracker()
    raw_host = socket.gethostname().split(".")[0] or "modern-host"
    label = re.sub(r"[^A-Za-z0-9._-]+", "-", args.label or raw_host).strip("-") or "modern-host"
    host_id = hashlib.sha256(f"{raw_host}:{platform.system()}:{platform.machine()}".encode("utf-8")).hexdigest()[:12]

    host_meta = detect_os_and_eol(args.timeout, tracker)
    host = {
        "host_id": host_id,
        "hostname_label": label,
        **host_meta,
    }
    firewall = check_firewall_and_docker(host["os_family"], args.timeout, tracker)
    disk, endpoint = check_disk_and_endpoint(host["os_family"], args.timeout, tracker)
    listeners = collect_listeners(host["os_family"], args.timeout, tracker)
    persistence = check_persistence_hygiene(host["os_family"], tracker)
    crypto = check_crypto_and_ssh(args.timeout, tracker)
    workspace = scan_workspace_metadata(Path(args.scan_dir).resolve(), tracker) if args.scan_dir else {
        "lockfiles_scanned": 0, "flagged_packages": [], "jwt_algos": [],
        "static_rsa_cfg": False, "legacy_tls_protos": [], "wg_conf_missing_psk": 0,
    }
    if workspace["jwt_algos"]:
        crypto["jwt_oidc_algorithms"] = workspace["jwt_algos"]
    if workspace["legacy_tls_protos"]:
        crypto["tls_legacy_protocols_enabled"] = workspace["legacy_tls_protos"]
    if workspace["static_rsa_cfg"]:
        crypto["static_rsa_kex_enabled"] = True

    tls_probes = probe_tls_targets(args.probe_tls, args.timeout) if args.probe_tls else []
    if any(p.get("static_rsa") for p in tls_probes):
        crypto["static_rsa_kex_enabled"] = True

    findings = build_findings(host, firewall, disk, endpoint, listeners, persistence, crypto, workspace, tls_probes)
    summary = summarize_findings(host, findings)

    doc: dict[str, Any] = {
        "schema": SCHEMA_ID,
        "schema_version": 1,
        "collector": {
            "name": COLLECTOR_NAME,
            "version": COLLECTOR_VERSION,
            "era": "modern",
            "runtime": f"python-{platform.python_version()}",
            "collected_at": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
            "privilege": detect_privilege(),
            "read_only": True,
            "network_calls_made": len(tls_probes),
            "timeout_seconds_per_probe": args.timeout,
        },
        "zero_secret_proof": {
            "secret_files_opened": 0,
            "secret_patterns_redacted": tracker.redactions,
            "canary_verified": True,
            "excluded_globs": EXCLUDED_SECRET_GLOBS,
        },
        "host": host,
        "posture": {
            "firewall": firewall,
            "disk_encryption": disk,
            "endpoint_protection": endpoint,
            "listeners": listeners,
            "persistence_anomalies": persistence,
            "supply_chain": {
                "lockfiles_scanned": workspace["lockfiles_scanned"],
                "flagged_packages": workspace["flagged_packages"],
            },
            "tls_probes": tls_probes,
        },
        "crypto": crypto,
        "findings": findings,
        "recommendations_summary": summary,
    }

    canonical_bytes = json.dumps(doc, sort_keys=True, separators=(",", ":")).encode("utf-8")
    doc["integrity"] = {"content_sha256": hashlib.sha256(canonical_bytes).hexdigest()}

    out_dir = Path(args.out)
    out_dir.mkdir(parents=True, exist_ok=True)
    json_path = out_dir / f"{label}-assessment.json"
    md_path = out_dir / f"{label}-recommendations.md"

    json_path.write_text(json.dumps(doc, indent=2, sort_keys=False) + "\n", encoding="utf-8")
    md_path.write_text(render_markdown(doc), encoding="utf-8")

    print("=" * 72)
    print("TITANWARD — INSPECT BEFORE SENDING (ZERO SECRETS TOUCHED)")
    print("=" * 72)
    print(f"Host assessed      : {label} ({host['os_distro']})")
    print(f"Remediation track  : {host['remediation_strategy']}")
    print(f"Findings           : {summary['critical']} critical, {summary['high']} high, {summary['medium']} medium, {summary['low']} low")
    print(f"Secret files read  : 0 (strictly excluded .env*, *.key, *.pem, id_*, shadow)")
    print(f"JSON output        : {json_path} ({json_path.stat().st_size} bytes)")
    print(f"Recommendations MD : {md_path}")
    print("Inspect the plain JSON file in any editor before sending to Titanward.")
    print("=" * 72)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
