HostBadger.ps1

<#
.SYNOPSIS
    HostBadger: Windows host hardening analyzer. Reads snapshots written by
    Collect-HostSnapshot.ps1 and writes an HTML report, a findings CSV and,
    optionally, JSON Lines for a SIEM.

.DESCRIPTION
    Collect once on each host (as SYSTEM or as a local administrator, through
    any tool that runs a .ps1: an EDR's live response, an RMM, Configuration
    Manager or Intune, a startup script, PowerShell remoting) and analyze
    anywhere. This script needs no
    module and no rights on the hosts, and it only goes on the network if you
    ask for the optional AI step. Give it one snapshot, a zip or a folder of
    them, and it reports every host in one place.

    If the data for a check couldn't be collected on a host (a section that
    failed, Defender in passive mode, ACLs skipped), the check is listed as
    "not evaluated" for that host. It is never counted as clean.

.PARAMETER Snapshot
    Snapshot files (hostsnapshot_*.json or .zip) or folders holding them
    (searched recursively). Several can be given.
.PARAMETER OutDir
    Folder for the output files. Default .\output. A -OutHtml / -OutCsv /
    -OutJsonl / -OutRemediation given as a bare file name lands here; a name
    with a folder, or an absolute path, is used exactly as given. The folder
    is created if it does not exist.
.PARAMETER OutHtml
    HTML report. Default hostbadger_<time>.html, written in -OutDir (.\output).
.PARAMETER SkipStig
    Leave out the DISA STIG checks (about 500 registry rules, one finding
    each). The other checks are not affected.
.PARAMETER HideCis
    Do not list the CIS-based findings in the HTML report (the compliance
    charts still count them; the CSV and JSON Lines keep them).
.PARAMETER HideStig
    Same for the DISA STIG findings.
.PARAMETER AiIncludeStig
    Also send the DISA STIG findings to Gemini. Without it they stay out of the
    prompt: there can be hundreds per host, and a prompt that large may make
    Gemini time out.
.PARAMETER KevFile
    CISA Known Exploited Vulnerabilities catalog (known_exploited_vulnerabilities.json)
    that you downloaded. Installed software is matched to it by vendor and product;
    the catalog has no version ranges, so a match is a lead to verify, not a verdict.
.PARAMETER KevOnline
    Download that catalog now. One HTTPS GET to
    www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json;
    nothing is sent. The copy is kept next to the report (<report>_kev.json).
.PARAMETER DriversOnline
    Download the LOLDrivers catalog of known vulnerable and malicious drivers now,
    instead of using the copy shipped in data\vulnerable-drivers.json. One HTTPS
    GET of about 30 MB to www.loldrivers.io/api/drivers.json; nothing is sent.
    The converted copy is kept next to the report (<report>_drivers.json).
.PARAMETER DriversFile
    A LOLDrivers catalog you already have, instead of the copy in data\: the
    drivers.json from www.loldrivers.io, or the <report>_drivers.json that
    -DriversOnline keeps next to a report. No network.
.PARAMETER ExtensionsOnline
    Download the current list of browser extensions removed from the Chrome Web
    Store and Edge Add-ons (malicious_extension_sentry by toborrm9, malext.io,
    CC BY 4.0, updated daily) instead of the copy shipped in
    data\malicious-extensions.json. One HTTPS GET of about 2 MB to
    raw.githubusercontent.com; nothing is sent. The converted copy is kept next
    to the report (<report>_extensions.json).
.PARAMETER ExtensionsFile
    A list you already have instead of the shipped copy: the
    malicious_extensions_detailed.csv of malicious_extension_sentry, or the
    <report>_extensions.json that -ExtensionsOnline keeps next to a report. No
    network.
.PARAMETER EolOnline
    Download software lifecycle data from endoflife.date now (MIT licensed): the
    release lines of Python, Node.js, .NET, Office, Exchange, Oracle Java, Firefox,
    Chrome, Notepad++, PowerShell, VirtualBox and Wireshark, with their end of
    support and latest version. One HTTPS GET of about 3 MB to
    endoflife.date/api/v1/products/full; nothing is sent. Turns on
    software_outdated and gives software_eol current dates. The reduced copy is
    kept next to the report (<report>_eol.json).
.PARAMETER EolFile
    endoflife.date data you already have: the <report>_eol.json that -EolOnline
    keeps, or an API v1 response (/products/full or one product). No network.
.PARAMETER ChocoOnline
    Download the version history of programs that endoflife.date does not cover
    (7-Zip, VLC, Git for Windows, GIMP, WinSCP, PuTTY, FileZilla, KeePass,
    Audacity, Mullvad VPN, OBS Studio, AnyDesk) from the Chocolatey community
    repository: a few HTTPS GETs per package to community.chocolatey.org/api/v2/,
    the same list whatever the hosts have; nothing is sent. Turns on
    software_outdated for them. The copy is kept next to the report
    (<report>_choco.json).
.PARAMETER ChocoFile
    The <report>_choco.json that -ChocoOnline keeps. No network.
.PARAMETER CveOnline
    Download the known vulnerabilities (CVEs) of Python, Node.js, .NET, Notepad++,
    PowerShell 7, VirtualBox, Wireshark, 7-Zip, VLC, Git, GIMP, WinSCP, PuTTY,
    FileZilla, KeePass, Audacity, Mullvad VPN and AnyDesk from the NVD CVE API
    (services.nvd.nist.gov, one GET per product and page, by product and never by
    version, the same list whatever the hosts have; about 2.5 minutes without a
    key, faster with an NVD API key in NVD_API_KEY), then the FIRST EPSS daily
    file (epss.empiricalsecurity.com, one GET of about 3 MB). Nothing about the
    hosts is sent. Turns on software_cve. The reduced copy is kept next to the
    report (<report>_cve.json).
.PARAMETER CveFile
    The <report>_cve.json that -CveOnline keeps. No network.
.PARAMETER ExploitsOnline
    Download the public-exploit references and note, next to each CVE that
    software_cve already found by version, whether a Metasploit module or an
    Exploit-DB entry exists. A prioritization signal like KEV and EPSS: only the
    module name and the Exploit-DB id are kept, never exploit code. Two HTTPS
    GETs, nothing is sent: the Metasploit module metadata from
    raw.githubusercontent.com (rapid7/metasploit-framework, BSD-3) and the
    Exploit-DB index from gitlab.com (exploit-database, GPLv2 data), the whole
    lists whatever the hosts have. A ready Metasploit exploit module raises the
    CVE finding to High. The reduced copy is kept next to the report
    (<report>_exploits.json). Has an effect only together with the CVE data.
.PARAMETER ExploitFile
    The <report>_exploits.json that -ExploitsOnline keeps. No network.
.PARAMETER SoftwareGraceDays
    Days a program may take to install a new release before software_outdated
    flags it (default 30).
.PARAMETER SnapshotPassword
    Password of snapshots encrypted with the collector's -EncryptPassword
    (.hbx). Without it, HostBadger asks for it when it finds such a snapshot.
.PARAMETER SnapshotPfx
    A .pfx with the private key for snapshots encrypted with the collector's
    -EncryptCertificate. Without it, the private key is looked for in the
    certificate stores of the current user and of the computer.
.PARAMETER SnapshotPfxPassword
    Password of the .pfx (asked for when needed).
.PARAMETER PerHost
    Also write one HTML report per host next to the fleet report
    (<OutHtml name>_<HOST>.html), when there are two hosts or more.
.PARAMETER OutCsv
    Findings CSV. Default: next to the HTML report.
.PARAMETER OutLog
    Run log: the settings of the run (passwords and the Gemini key left out)
    and everything it prints. Default: next to the HTML report, same name,
    .log.
.PARAMETER NoLog
    Write no run log.
.PARAMETER OutJsonl
    JSON Lines for a SIEM (findings, resolved findings with -CompareTo, one
    summary per host). Not written unless given.
.PARAMETER CompareTo
    Findings CSV of an earlier run: new and resolved findings are shown.
.PARAMETER History
    Score history file (CSV, created when missing): every run adds the score of
    each host, one line per host and snapshot (a snapshot analyzed again
    replaces its line; each host keeps its newest 100). The report then shows
    how each host's score moved over the runs, not only against the previous
    one, and JSON Lines gets score_previous and score_change. The guided menu
    and the window keep it in their output folder (hostbadger-history.csv).
.PARAMETER Threads
    How many hosts to analyze at once. Default 0: up to 4 when there are
    enough hosts to pay for it (from 16 hosts), else one at a time. 1
    analyzes one host at a time. The result is the same either way.
.PARAMETER ExceptionsFile
    JSON list of accepted risks: [{ "type", "host", "object", "reason",
    "owner", "expires" }], host and object accept "*".
.PARAMETER PolicyFile
    The organization's own policy (JSON): { "name": "...", "disabledChecks":
    [ "check_type" | "stig_*" | { "check": "...", "reason": "..." } ] }. The
    checks it turns off do not run, do not count in the score, and the report
    lists them with the reason. A name that matches no check stops the run.
.PARAMETER AllowedAdmins
    Members of the local Administrators group that belong there (names as
    "DOMAIN/Group", the bare name, or SIDs). Domain Admins and the built-in
    Administrator are always expected.
.PARAMETER ExpectedEdr
    The EDR every host should run, for example CrowdStrike or SentinelOne (more than one is
    fine). A host without it gets a High finding. Known names: CrowdStrike, SentinelOne,
    DefenderForEndpoint, CarbonBlack, CortexXDR, Sophos, TrendMicro, Trellix, ESET, Symantec,
    Elastic, Cybereason, Cylance, Bitdefender, Huntress. Any other text is looked for in the
    names of the services. Without it, only a host with no known EDR at all is reported.
.PARAMETER ExtraEdrServices
    Names of services that belong to an EDR that HostBadger does not know, so that they are
    counted as an agent (and flagged if they are stopped).
.PARAMETER AllowedExtensions
    Optional: the browser extensions the organization approves, by id or name
    (wildcards allowed, e.g. 'uBlock Origin', 'nngceckbapebfimnlniiiahkandclblb').
    The other enabled extensions are reported as browser_extension_not_allowed;
    without the list, those that can read every website are reported as Low.
.PARAMETER AllowedRemoteTools
    The remote access tools the organization approves (AnyDesk, TeamViewer, ScreenConnect, VNC,
    NinjaOne...: the tool's key or part of its name). Others found are Medium; without the list,
    every remote access tool found is Low, to be verified.
.PARAMETER MaxPatchAgeDays
    Days without an installed update before updates_stale (default 45).
.PARAMETER MaxSignatureAgeDays
    Days before Defender signatures are stale (default 7).
.PARAMETER SupportWarningDays
    Warn this many days before the OS goes out of support (default 90).
.PARAMETER DormantAccountDays
    Days without a logon before an enabled local account counts as dormant
    (default 180).
.PARAMETER OutRemediation
    Optional folder: besides the fix scripts that the report already shows under
    each check, write one remediate_<host>.ps1 per host with all of that host's
    fixes in one file, for scripted rollouts. It previews unless run with -Apply,
    writes a rollback file, and HostBadger never runs it.
.PARAMETER RemediationProfile
    Optional, with -OutRemediation: add a remediation profile to every
    remediate_<host>.ps1, on top of the fixes of the findings. Essential (CIS
    Level 1 and Essential Eight Maturity Level One settings safe on any machine
    that change nothing the user sees or does: the fixes that would, such as
    CTRL+ALT+DEL, hiding the last user name, screen lock or extra UAC prompts,
    are listed in the script and left to Recommended),
    Recommended (Essential, plus the rest of CIS Level 1 for managed machines and
    Essential Eight Maturity Level Two: attack surface reduction rules in block
    mode) or Strict (Recommended, plus CIS Level 2, Essential Eight Maturity
    Level Three, opinionated hardening and the removal of preinstalled apps).
    The settings come from data\remediation-profiles.json, filtered by the host's
    role; each one quotes its rule. Some Strict changes cannot be undone by the
    rollback file: the script marks them NOT REVERSIBLE.
.PARAMETER RemediationDebloat
    Optional, with -OutRemediation: debloat. Adds the removal of the
    preinstalled apps (games, consumer apps, trials; workstations) and the unused
    consumer services and components (Xbox services, Retail Demo, Windows
    Insider, Windows Fax and Scan, Work Folders, Steps Recorder...: the items
    marked debloat in data\remediation-profiles.json) to the scripts, with or
    without a profile (Strict already includes it). The apps are not
    reversible: they come back only from the Microsoft Store.
.PARAMETER RemediationPrivacy
    Optional, with -OutRemediation: add the privacy and telemetry settings of
    every profile tier (data\remediation-profiles.json, category privacy) to the
    scripts, with or without a profile. With -RemediationDebloat and no profile it
    gives "debloat and telemetry only": no hardening setting is added.
.PARAMETER RemediationNoApps
    Optional, with -OutRemediation: leave the removal of preinstalled apps out of
    the scripts even with -RemediationProfile Strict or -RemediationDebloat. The
    guided menu (option 6) uses it: it lists the apps found on the machine and
    asks for them itself.
.PARAMETER RemediationOnlyProfile
    Optional, with -OutRemediation: leave the safe fixes of the findings out of the
    scripts, so they hold only what -RemediationProfile, -RemediationPrivacy and
    -RemediationDebloat add. "Debloat and telemetry only" in the guided menu uses
    it with -RemediationPrivacy and -RemediationDebloat.
.PARAMETER SendToAI
    Optional: after the report is saved, send the findings to Gemini for an
    executive summary and a remediation plan, and add them to the report.
    Without this switch (or -AiDryRun) nothing is ever sent and HostBadger
    never asks. Host names, domains, accounts, groups, SIDs, paths, service,
    task and autorun names and addresses are replaced by tokens first, the
    collector's error messages are never included, and a leak check refuses
    to send if any real name survived. The exact prompt is saved as
    <report>_ai_prompt.txt, the reply as <report>_ai_response.json.
.PARAMETER AiConfirm
    With -SendToAI: show what will be sent and ask y/N first.
.PARAMETER AiDryRun
    Path: write the exact pseudonymized prompt that would be sent and send
    nothing. Useful for a privacy review before enabling the AI step.
.PARAMETER Nis2Acn
    Optional, for organizations in Italy: add the NIS2 basic security measures
    of the Agenzia per la Cybersicurezza Nazionale (Determinazione 379907/2025,
    D.Lgs. 138/2024) to the report: a dashboard panel with the requirements a
    host shows evidence against, a row in the summary by framework, the
    measures under each check, and acn_unmet / acn_not_judged in JSON Lines.
.PARAMETER AiLater
    Used by the guided menu: without -SendToAI or -AiDryRun, keep the analysis
    in this PowerShell session's memory (never on disk) so that a following
    run with -AiContinue can add the AI step without analyzing again.
.PARAMETER AiContinue
    Run only the AI step (with -SendToAI or -AiDryRun and their options) on
    the analysis kept by an -AiLater run in the same PowerShell session, and
    add its section to that report.
.PARAMETER AiReport
    Run only the AI step (with -SendToAI or -AiDryRun and their options) on a
    report already written: its findings come from the report and its CSV,
    nothing is analyzed and no catalog is read or downloaded, and the AI
    section is added to that report. -Snapshot must still reach the snapshots
    of its hosts, as collected then: their names, accounts and paths are what
    the prompt replaces with tokens, so without them nothing is written or
    sent. A file or folder works; only the files of those hosts are read.
.PARAMETER ApiKey
    Gemini API key. Defaults to $env:GEMINI_API_KEY.
.PARAMETER Model
    Gemini model name. Defaults to gemini-3.8-flash.
.PARAMETER AiMaxAttempts
    How many times to try Gemini on a timeout or a busy server (429/5xx).
    Default 3; 0 keeps trying until it works (Ctrl+C to stop).

.EXAMPLE
    .\HostBadger.ps1 -Snapshot .\snapshots\ -OutHtml fleet.html
.EXAMPLE
    .\HostBadger.ps1 -Snapshot hostsnapshot_PC01_20261006101500.zip -CompareTo last_month.csv -OutJsonl siem.jsonl
#>

[CmdletBinding()]
param(
    [string[]]$Snapshot,
    [string]$OutDir = '',
    [string]$OutHtml = '',
    [string]$OutCsv = '',
    [string]$OutJsonl = '',
    [string]$CompareTo = '',
    [string]$ExceptionsFile = '',
    [string]$PolicyFile = '',
    [string[]]$AllowedAdmins = @(),
    [int]$MaxPatchAgeDays = 45,
    [int]$MaxSignatureAgeDays = 7,
    [int]$SupportWarningDays = 90,
    [int]$DormantAccountDays = 180,
    [int]$MaxCachedLogonsWorkstation = 4,
    [int]$MaxCachedLogonsServer = 1,
    [int]$MinSecurityLogKB = 196608,
    [string[]]$ExpectedEdr = @(),
    [string[]]$ExtraEdrServices = @(),
    [string[]]$AllowedRemoteTools = @(),
    [string[]]$AllowedExtensions = @(),
    [string]$OutRemediation = '',
    [ValidateSet('', 'Essential', 'Recommended', 'Strict')]
    [string]$RemediationProfile = '',
    [switch]$RemediationDebloat,
    [switch]$RemediationPrivacy,
    [switch]$RemediationNoApps,
    [switch]$RemediationOnlyProfile,
    [switch]$PerHost,
    [switch]$SkipStig,
    [string]$KevFile = '',
    [switch]$KevOnline,
    [switch]$DriversOnline,
    [string]$DriversFile = '',
    [switch]$ExtensionsOnline,
    [string]$ExtensionsFile = '',
    [switch]$EolOnline,
    [string]$EolFile = '',
    [switch]$ChocoOnline,
    [string]$ChocoFile = '',
    [switch]$CveOnline,
    [string]$CveFile = '',
    [switch]$ExploitsOnline,
    [string]$ExploitFile = '',
    [int]$SoftwareGraceDays = 30,
    [System.Security.SecureString]$SnapshotPassword,
    [string]$SnapshotPfx = '',
    [System.Security.SecureString]$SnapshotPfxPassword,
    [switch]$HideCis,
    [switch]$HideStig,
    [switch]$AiIncludeStig,
    [switch]$SendToAI,
    [switch]$AiConfirm,
    [string]$AiDryRun = '',
    [switch]$AiLater,
    [switch]$AiContinue,
    [string]$AiReport = '',
    [switch]$Nis2Acn,
    [string]$ApiKey = $env:GEMINI_API_KEY,
    [string]$Model = 'gemini-3.8-flash',
    [int]$AiMaxAttempts = 3,
    [string]$OutLog = '',
    [switch]$NoLog,
    [string]$History = '',
    [ValidateRange(0, 256)]
    [int]$Threads = 0
)

$ErrorActionPreference = 'Stop'
$script:HostBadgerVersion = '3.4'
. (Join-Path $PSScriptRoot 'lib\Common.ps1')
. (Join-Path $PSScriptRoot 'lib\Checks.ps1')
. (Join-Path $PSScriptRoot 'lib\AI.ps1')
. (Join-Path $PSScriptRoot 'lib\Remediation.ps1')
. (Join-Path $PSScriptRoot 'lib\Reporting.ps1')

Write-Host @'
     _.--""--._
   .' | | '.
  / | | \ HostBadger v3.4
 | (o)| |(o) | Windows host hardening
 | | | | read-only snapshots, offline analysis
  \ '.__.' /
   '._ \/ _.'
      '--..--'
'@
 -ForegroundColor DarkYellow

$fmtElapsed = { param($span) if ($span.TotalMinutes -ge 1) { '{0}m {1}s' -f [int][Math]::Floor($span.TotalMinutes), $span.Seconds } else { '{0:N1}s' -f $span.TotalSeconds } }
# The AI step (-SendToAI, -AiDryRun), dot-sourced at the end of the analysis or, with -AiContinue, on
# the analysis a -AiLater run kept in this session's memory.
$aiStep = {
    if (-not $SendToAI -and -not $AiDryRun) { return }
    # The DISA STIG findings can be hundreds per host. They go to Gemini only if asked for (-AiIncludeStig):
    # a prompt that large can make the request time out.
    $aiFindings = if ($AiIncludeStig) { $active } else { @($active | Where-Object { $_.Category -ne 'DISA STIG' }) }
    $stigLeftOut = $active.Count - $aiFindings.Count
    if ($stigLeftOut -gt 0) { Write-Host "AI: $stigLeftOut DISA STIG finding(s) are not part of the prompt (add -AiIncludeStig to send them; a very large prompt may time out)." -ForegroundColor DarkGray }
    if ($AiIncludeStig -and @($active | Where-Object { $_.Category -eq 'DISA STIG' }).Count -gt 0) { Write-Host 'AI: DISA STIG findings included; with this many findings Gemini may time out.' -ForegroundColor Yellow }
    if ($aiFindings.Count -eq 0) { Write-Host 'No findings: AI step skipped (nothing to ground a summary on).'; return }

    # The chains the report drew, computed here exactly as its summary block computes them (every
    # active finding of the host, not just the ones the prompt carries), so that -AiReport, which
    # reads them back from that block, builds the same prompt.
    # @() over the host list would throw "Argument types do not match" on 5.1: it is a List[T].
    $aiByHost = Group-ByHost $active
    foreach ($h in $hosts.ToArray()) {
        $apH = @(Get-AttackPathStatus -Hosts @($h) -Findings @(Get-HostItems $aiByHost $h.Name))
        $chains = @(@($apH | Where-Object { @($_.Complete).Count -gt 0 }) | ForEach-Object {
                $br = $_.Break
                [PSCustomObject]@{
                    Id     = "$($_.Id)"
                    Stages = @(@($_.Steps | Where-Object { $_.State -eq 'open' }) | ForEach-Object { [PSCustomObject]@{ Stage = "$($_.StageId)"; Checks = [string[]]@($_.HitChecks) } })
                    # The stage the tool judged cheapest to close, as the report's summary block carries
                    # it: the model is asked to use it, not to guess one.
                    Break  = $(if ($br) { [PSCustomObject]@{ StageId = "$($br.StageId)"; Checks = [string[]]@($br.Checks); FixCount = [int]$br.FixCount } } else { $null })
                }
            })
        Add-Member -InputObject $h -NotePropertyName AiChains -NotePropertyValue $chains -Force
    }
    $hostOrder = @($hosts | Sort-Object { $_.Score.Score }, Name | ForEach-Object { $_.Name })
    Step-Spinner 'Replacing names with tokens'
    $pz = New-HostPseudonymizer -Snapshots @($latest.Values) -Findings $aiFindings -HostOrder $hostOrder
    Step-Spinner 'Building the AI prompt'
    $userPrompt = New-AiPrompt -Findings $aiFindings -Hosts $hosts.ToArray() -Pz $pz -Comparison $comparison
    Stop-Spinner
    $leaks = @(Test-AiLeak -Pz $pz -Text $userPrompt)
    if ($leaks.Count -gt 0) {
        Write-Host "AI step aborted: identifiers still present after pseudonymization: $($leaks -join ', '). Nothing was sent. Please report this as a bug." -ForegroundColor Red
        return
    }
    $maskedCount = $pz.Reverse.Count

    if ($AiDryRun) {
        Write-AiPromptFile -Path $AiDryRun -UserPrompt $userPrompt
        Write-Host "AI dry run: prompt written to $AiDryRun ($($userPrompt.Length) chars, $maskedCount identifiers pseudonymized). Nothing sent." -ForegroundColor Cyan
        return
    }

    # Written before sending, so it can be read first (and kept as the record of what left).
    $promptFile = Get-AiSidecarPath $htmlFull '_ai_prompt.txt'
    Write-AiPromptFile -Path $promptFile -UserPrompt $userPrompt
    if ($AiConfirm) {
        Write-Host ''
        Write-Host "Optional AI step (Gemini, model $Model):" -ForegroundColor Cyan
        Write-Host " Sent: $($aiFindings.Count) findings grouped by check (max 12 lines per check), host table, coverage gaps, comparison if any."
        Write-Host " Pseudonymized: $maskedCount identifiers (hosts, domains, accounts, groups, SIDs, paths, service/task/autorun/adapter names, addresses). The map never leaves this machine."
        Write-Host " Not sent: the snapshots, ACL dumps, collector error messages."
        Write-Host " Exactly what would be sent: $promptFile" -ForegroundColor Cyan
        $answer = Read-Host 'Open that file if you want, then: send to Gemini for an executive summary and remediation plan? (y/N)'
        if ($answer -notmatch '^[Yy]') { Write-Host "Nothing sent. Deterministic report saved to $OutHtml."; return }
    }
    else { Write-Host "AI prompt kept at $promptFile ($maskedCount identifiers pseudonymized)" }
    if (-not $ApiKey) { Write-Host 'ERROR: no API key (-ApiKey or GEMINI_API_KEY). Deterministic report kept as is.' -ForegroundColor Red; return }

    $aiStarted = Get-Date
    $raw = Invoke-GeminiAnalysis -UserPrompt $userPrompt -ApiKey $ApiKey -Model $Model -MaxAttempts $AiMaxAttempts
    if (-not $raw) { Write-Host "AI step failed; deterministic report kept at $OutHtml." -ForegroundColor Yellow; return }
    $responseFile = Get-AiSidecarPath $htmlFull '_ai_response.json'
    Write-AiResponseFile -Path $responseFile -Raw $raw
    Write-Host "Gemini reply (still pseudonymized) kept at $responseFile"
    $aiResult = ConvertFrom-AiResponse -Raw $raw -Pz $pz -Findings $aiFindings -Model $Model
    # Time spent waiting for Gemini (retries included), shown next to the analysis time.
    $aiResult | Add-Member -NotePropertyName ElapsedText -NotePropertyValue (& $fmtElapsed ((Get-Date) - $aiStarted)) -Force

    $html = if ($aiOnReport) { Add-AiSectionToReportHtml -Html ([System.IO.File]::ReadAllText($htmlFull)) -AiResult $aiResult }
    else { ConvertTo-ReportHtml -Hosts $hosts.ToArray() -Split $split -Comparison $comparison -Config $config -ToolVersion $script:HostBadgerVersion -ElapsedText $elapsedText -AiResult $aiResult -Remediation $remInfo -HideCis:$HideCis -HideStig:$HideStig -KevLoaded:([bool]$config.Kev) }
    [System.IO.File]::WriteAllText($htmlFull, $html, (New-Object System.Text.UTF8Encoding($false)))
    Write-Host "AI section added to $OutHtml ($(@($aiResult.RemediationPlan).Count) remediation items)." -ForegroundColor Green
}

# -AiContinue: only the AI step, on the analysis kept by -AiLater in this PowerShell session (the guided
# menu asks about the AI summary once the report is out, without analyzing again). Never on disk.
if ($AiContinue) {
    # The analysis stays for the next AI step (a dry run then a send, a send that failed); the next
    # analysis replaces it.
    $st = $global:HostBadgerAiPending
    if (-not $st) { Write-Host 'No analysis kept for the AI step in this session: run the analysis again with -SendToAI or -AiDryRun.' -ForegroundColor Yellow; return }
    $active = $st.Active; $hosts = $st.Hosts; $latest = $st.Latest; $comparison = $st.Comparison; $split = $st.Split; $config = $st.Config
    $remInfo = $st.Remediation; $elapsedText = $st.ElapsedText; $htmlFull = $st.HtmlFull; $OutHtml = $st.OutHtml
    $HideCis = [switch]$st.HideCis; $HideStig = [switch]$st.HideStig
    . $aiStep
    return
}
# Encrypted snapshots (.hbx) in $files: the password is asked for once, a .pfx is loaded once.
$openHbx = {
    $encModes = @($files | ForEach-Object { Get-SnapshotEncryption $_ } | Where-Object { $_ } | Sort-Object -Unique)
    if ($encModes -contains 'password') {
        if (-not $SnapshotPassword) { $SnapshotPassword = Read-Host 'Password of the encrypted snapshots' -AsSecureString }
        $script:HbxPassword = $SnapshotPassword
    }
    if ($encModes -contains 'certificate' -and $SnapshotPfx) {
        if (-not $SnapshotPfxPassword) { $SnapshotPfxPassword = Read-Host "Password of $SnapshotPfx" -AsSecureString }
        $script:HbxPfxCerts = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
        $bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SnapshotPfxPassword)
        try {
            $pfxPath = (Resolve-Path -LiteralPath $SnapshotPfx).Path
            # EphemeralKeySet keeps the private key in memory only; without it .NET writes it to the user profile.
            try { $script:HbxPfxCerts.Import($pfxPath, [Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr), [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::EphemeralKeySet) }
            catch { $script:HbxPfxCerts.Import($pfxPath, [Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr), [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::DefaultKeySet) }
        }
        finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr) }
    }
}
# -AiReport: only the AI step, on a report already written. Its findings and scores are read back from
# it; the snapshots of its hosts are read only for the pseudonymizer. "AI report:" lines are what the
# window shows the user when this stops.
if ($AiReport) {
    $aiNo = { param($why) Write-Host "AI report: $why Nothing written or sent." -ForegroundColor Yellow }
    if (-not $SendToAI -and -not $AiDryRun) { & $aiNo '-AiReport needs -SendToAI or -AiDryRun.'; return }
    if (-not (Test-Path -LiteralPath $AiReport)) { & $aiNo "$AiReport not found."; return }
    if (-not $Snapshot -or $Snapshot.Count -eq 0) { & $aiNo '-AiReport needs -Snapshot: the names to replace with tokens come from the snapshots.'; return }
    $htmlFull = (Resolve-Path -LiteralPath $AiReport).Path
    $OutHtml = $AiReport
    try { $fromReport = Import-ReportForAi $htmlFull } catch { & $aiNo "$(Split-Path -Leaf $htmlFull) cannot be used: $($_.Exception.Message)"; return }
    try { $files = @(Get-SnapshotFiles $Snapshot | Select-Object -Unique) } catch { & $aiNo "$($_.Exception.Message)."; return }
    $reportHosts = @{}
    foreach ($rh in $fromReport.Hosts) { $reportHosts[$rh.Name.ToUpper()] = $rh }
    # A folder can hold many other hosts: only the files named after these ones, when each host has one.
    $named = @($files | Where-Object {
            $leaf = Split-Path -Leaf $_
            @($reportHosts.Keys | Where-Object { $leaf.ToUpper().Contains(($_ -replace '[^\w\-]', '_')) }).Count -gt 0
        })
    if ($named.Count -ge $reportHosts.Count) { $files = $named }
    # And only the collections this report is made of: the file name carries the time
    # (hostsnapshot_<host>_<yyyyMMddHHmmss>), and the report keeps the minute. Without this an older
    # snapshot of the same host would be opened for nothing, and an encrypted one would ask for a
    # password this step does not need - in a window, which cannot ask, the step would fail instead.
    # A name without the time (renamed by hand) is kept: only its content can tell.
    $minutes = @($fromReport.Hosts | ForEach-Object { "$($_.Collected)" -replace '\D' } | Where-Object { $_ } | ForEach-Object { if ($_.Length -gt 12) { $_.Substring(0, 12) } else { $_ } })
    if ($minutes.Count -gt 0) {
        $sameTime = @($files | Where-Object {
                $leaf = Split-Path -Leaf $_
                -not ($leaf -match '_(\d{14})\.') -or $minutes -contains $Matches[1].Substring(0, 12)
            })
        if ($sameTime.Count -ge $reportHosts.Count) { $files = $sameTime }
    }
    . $openHbx
    $latest = @{}
    $readIndex = 0
    foreach ($f in $files) {
        $readIndex++
        Step-Spinner "Reading snapshots ($readIndex of $($files.Count))"
        try { $s = Import-HostSnapshot $f }
        catch { Stop-Spinner; Write-Warning $_.Exception.Message; continue }
        $name = (Get-SnapshotHostName $s).ToUpper()
        # The very snapshot of the report (the minute is what the report keeps): another one may not
        # name the same accounts and paths.
        if ($reportHosts.ContainsKey($name) -and ((ConvertTo-UtcDate $s.meta.collectedAtUtc).ToString('yyyyMMddHHmm') -replace '\D') -eq ($reportHosts[$name].Collected -replace '\D')) { $latest[$name] = $s }
    }
    Stop-Spinner
    $missing = @($reportHosts.Keys | Where-Object { -not $latest.ContainsKey($_) } | Sort-Object | ForEach-Object { "$($reportHosts[$_].Name) ($($reportHosts[$_].Collected))" })
    if ($missing.Count) { & $aiNo "the snapshot of this report was not found for $($missing -join ', '). It holds the names to replace with tokens: choose it as the snapshot to analyze, or analyze again."; return }
    $active = $fromReport.Findings; $hosts = $fromReport.Hosts; $comparison = $fromReport.Comparison
    $aiOnReport = $true
    . $aiStep
    return
}
if (-not $Snapshot -or $Snapshot.Count -eq 0) {
    Write-Host 'Usage: .\HostBadger.ps1 -Snapshot <file|zip|folder> [-OutDir .\output] [-OutHtml report.html] [-OutCsv findings.csv] [-OutJsonl siem.jsonl] [-CompareTo old.csv]'
    Write-Host 'Collect first on each host with Collect-HostSnapshot.ps1 (as SYSTEM or administrator). Get-Help .\HostBadger.ps1 -Full for every option.'
    return
}

$started = Get-Date
$config = @{
    AllowedAdmins = @($AllowedAdmins); MaxPatchAgeDays = $MaxPatchAgeDays; MaxSignatureAgeDays = $MaxSignatureAgeDays
    SupportWarningDays = $SupportWarningDays; MaxCachedLogonsWorkstation = $MaxCachedLogonsWorkstation
    MaxCachedLogonsServer = $MaxCachedLogonsServer; MinSecurityLogKB = $MinSecurityLogKB
    ExpectedEdr = @($ExpectedEdr); ExtraEdrServices = @($ExtraEdrServices); SoftwareGraceDays = $SoftwareGraceDays
    AllowedRemoteTools = @($AllowedRemoteTools); AllowedExtensions = @($AllowedExtensions)
    DormantAccountDays = $DormantAccountDays
}
# The organization's policy: read first, so a wrong check name stops the run before any work.
$policy = Import-HostBadgerPolicy $PolicyFile
if ($policy) {
    $config.DisabledChecks = $policy.Disabled
    $config.PolicyName = $policy.Name
    Write-Host "Policy '$($policy.Name)': $($policy.Disabled.Count) check(s) turned off." -ForegroundColor DarkGray
}

$stamp = (Get-Date).ToString('yyyyMMdd_HHmmss')
# Where output goes by default. A bare file name (-OutHtml report.html) lands in -OutDir (default
# .\output); a name with a folder (.\reports\r.html) or an absolute path is left exactly as given.
# Resolved against the current location so every writer gets the same absolute path (.NET's own
# current directory can differ from PowerShell's).
if (-not $OutDir) { $OutDir = 'output' }
$script:OutBase = $PWD.ProviderPath
function Resolve-OutPath([string]$Path) {
    if (-not $Path) { return $Path }
    if (-not [System.IO.Path]::IsPathRooted($Path) -and -not [System.IO.Path]::GetDirectoryName($Path)) { $Path = Join-Path $OutDir $Path }
    if (-not [System.IO.Path]::IsPathRooted($Path)) { $Path = Join-Path $script:OutBase $Path }
    return $Path
}
if (-not $OutHtml) { $OutHtml = "hostbadger_$stamp.html" }
$OutHtml = Resolve-OutPath $OutHtml
if (-not $OutCsv) { $OutCsv = ($OutHtml -replace '\.html?$', '') + '.csv' } else { $OutCsv = Resolve-OutPath $OutCsv }
$OutJsonl = Resolve-OutPath $OutJsonl
$History = Resolve-OutPath $History
$OutRemediation = Resolve-OutPath $OutRemediation
if (($RemediationProfile -or $RemediationDebloat -or $RemediationPrivacy) -and -not $OutRemediation) { Write-Warning '-RemediationProfile, -RemediationDebloat and -RemediationPrivacy shape the per-host fix scripts: add -OutRemediation <folder> to write them.' }
# Create the directories the resolved (absolute) paths need, so a bare name in .\output just works.
foreach ($p in @($OutHtml, $OutCsv, $OutJsonl, $OutRemediation, $History) | Where-Object { $_ }) {
    $dir = Split-Path -Path $p -Parent
    if ($dir -and -not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
}

# Run log: everything this run prints, in a text file next to the report (a PowerShell transcript),
# after the settings of the run. Passwords and the Gemini key are never written, and the progress
# cursor is drawn with [Console]::Write so it stays out of the file. -NoLog turns it off.
$script:RunLogOn = $false
if (-not $NoLog) {
    $OutLog = if ($OutLog) { Resolve-OutPath $OutLog } else { ($OutHtml -replace '\.html?$', '') + '.log' }
    $settings = New-Object System.Collections.Generic.List[string]
    $settings.Add("HostBadger v$($script:HostBadgerVersion) run log")
    $settings.Add("Started: $((Get-Date).ToString('yyyy-MM-dd HH:mm:ss')) ($((Get-Date).ToUniversalTime().ToString('yyyy-MM-dd HH:mm')) UTC)")
    $settings.Add("PowerShell: $($PSVersionTable.PSVersion) ($($PSVersionTable.PSEdition))")
    $settings.Add("Report: $OutHtml")
    $settings.Add("Findings: $OutCsv")
    if ($OutJsonl) { $settings.Add("JSON Lines: $OutJsonl") }
    if ($OutRemediation) { $settings.Add("Fix scripts: $OutRemediation$(if ($RemediationProfile) { " (profile $RemediationProfile)" })$(if ($RemediationDebloat) { ' (with debloat)' })$(if ($RemediationPrivacy) { ' (with privacy and telemetry)' })$(if ($RemediationOnlyProfile) { ' (no finding fixes)' })") }
    $settings.Add('Settings given:')
    foreach ($k in @($PSBoundParameters.Keys | Sort-Object)) {
        $v = $PSBoundParameters[$k]
        $shown = if ($k -in 'SnapshotPassword', 'SnapshotPfxPassword', 'ApiKey') { '(given, not written here)' }
        elseif ($v -is [System.Management.Automation.SwitchParameter]) { "$([bool]$v)" }
        elseif ($v -is [array]) { (@($v) | ForEach-Object { "$_" }) -join ', ' }
        else { "$v" }
        $settings.Add(" -$k $shown")
    }
    $settings.Add("Gemini key: $(if ($ApiKey) { 'set (not written here)' } else { 'not set' })")
    try {
        $logDir = Split-Path -Path $OutLog -Parent
        if ($logDir -and -not (Test-Path -LiteralPath $logDir)) { New-Item -ItemType Directory -Path $logDir -Force | Out-Null }
        [System.IO.File]::WriteAllText($OutLog, (($settings -join [Environment]::NewLine) + [Environment]::NewLine), (New-Object System.Text.UTF8Encoding($false)))
        Start-Transcript -LiteralPath $OutLog -Append | Out-Null
        $script:RunLogOn = $true
    }
    catch { Write-Warning "Run log not written: $($_.Exception.Message)" }
}

# The rest of the run, in try/finally so that the log is closed whichever way it ends (the guided menu
# runs this script in its own session and keeps going afterwards).
try {

    # CISA KEV catalog: a file you give, or a download (the only network call outside the AI step).
    if ($KevFile -or $KevOnline) {
        $kevJson = $null
        if ($KevFile) {
            if (Test-Path -LiteralPath $KevFile) { $kevJson = [System.IO.File]::ReadAllText((Resolve-Path -LiteralPath $KevFile).Path) }
            else { Write-Host "KEV file not found: $KevFile" -ForegroundColor Yellow }
        }
        else {
            $kevJson = Get-KevCatalogOnline
            if ($kevJson) {
                $kevCopy = ([System.IO.Path]::GetFullPath($OutHtml) -replace '\.html?$', '') + '_kev.json'
                [System.IO.File]::WriteAllText($kevCopy, $kevJson, (New-Object System.Text.UTF8Encoding($false)))
                Write-Host "KEV catalog kept at $kevCopy" -ForegroundColor DarkGray
            }
        }
        if ($kevJson) {
            try { $config['Kev'] = @(ConvertFrom-KevCatalog $kevJson); Write-Host "KEV catalog: $(@($config['Kev']).Count) exploited vulnerabilities." -ForegroundColor DarkGray }
            catch { Write-Host "KEV catalog not readable: $($_.Exception.Message)" -ForegroundColor Yellow }
        }
    }

    # LOLDrivers catalog: the copy in data\ unless a file (-DriversFile) or a fresh one (-DriversOnline)
    # was asked for.
    if ($DriversFile) {
        if (Test-Path -LiteralPath $DriversFile) {
            try {
                $drvText = [System.IO.File]::ReadAllText((Resolve-Path -LiteralPath $DriversFile).Path)
                # The converted copy (<report>_drivers.json) has "entries"; the original drivers.json is a list.
                $config['Drivers'] = if ($drvText.TrimStart().StartsWith('{')) { @((ConvertFrom-Json -InputObject $drvText).entries | ForEach-Object { $_ }) } else { @(ConvertFrom-LolDrivers $drvText) }
                Write-Host "LOLDrivers catalog: $(@($config['Drivers']).Count) driver files from $DriversFile" -ForegroundColor DarkGray
            }
            catch { Write-Host "LOLDrivers file not readable, using the copy in data\: $($_.Exception.Message)" -ForegroundColor Yellow; $config.Remove('Drivers') }
        }
        else { Write-Host "LOLDrivers file not found, using the copy in data\: $DriversFile" -ForegroundColor Yellow }
    }
    elseif ($DriversOnline) {
        $drvJson = Get-LolDriversOnline
        if ($drvJson) {
            try {
                $config['Drivers'] = @(ConvertFrom-LolDrivers $drvJson)
                $drvCopy = ([System.IO.Path]::GetFullPath($OutHtml) -replace '\.html?$', '') + '_drivers.json'
                $drvDoc = [ordered]@{ source = "LOLDrivers ($($script:LolDriversUrl)), Apache License 2.0; downloaded $((Get-Date).ToUniversalTime().ToString('yyyy-MM-dd HH:mm')) UTC"; count = @($config['Drivers']).Count; entries = @($config['Drivers']) }
                [System.IO.File]::WriteAllText($drvCopy, ($drvDoc | ConvertTo-Json -Depth 5 -Compress), (New-Object System.Text.UTF8Encoding($false)))
                Write-Host "LOLDrivers catalog: $(@($config['Drivers']).Count) driver files, kept at $drvCopy" -ForegroundColor DarkGray
            }
            catch { Write-Host "LOLDrivers catalog not readable, using the copy in data\: $($_.Exception.Message)" -ForegroundColor Yellow; $config.Remove('Drivers') }
        }
        else { Write-Host 'Using the LOLDrivers copy in data\.' -ForegroundColor Yellow }
    }

    # Browser extensions removed from the stores: the copy in data\ unless a file (-ExtensionsFile) or a
    # fresh one (-ExtensionsOnline) was asked for. Either way the Palant entries of the copy stay.
    if ($ExtensionsFile) {
        if (Test-Path -LiteralPath $ExtensionsFile) {
            try {
                $extText = [System.IO.File]::ReadAllText((Resolve-Path -LiteralPath $ExtensionsFile).Path)
                # The kept copy (<report>_extensions.json) has "entries"; the original is the sentry CSV.
                $config['Extensions'] = if ($extText.TrimStart([char]0xFEFF).TrimStart().StartsWith('{')) { @(foreach ($e in @((ConvertFrom-Json -InputObject $extText).entries)) { foreach ($x in $e) { $x } }) } else { @(ConvertFrom-ExtensionSentryCsv $extText) }
                Write-Host "Browser extension list: $(@($config['Extensions']).Count) extensions from $ExtensionsFile" -ForegroundColor DarkGray
            }
            catch { Write-Host "Browser extension list not readable, using the copy in data\: $($_.Exception.Message)" -ForegroundColor Yellow; $config.Remove('Extensions') }
        }
        else { Write-Host "Browser extension list not found, using the copy in data\: $ExtensionsFile" -ForegroundColor Yellow }
    }
    elseif ($ExtensionsOnline) {
        $extCsv = Get-ExtensionCatalogOnline
        if ($extCsv) {
            try {
                $config['Extensions'] = @(ConvertFrom-ExtensionSentryCsv $extCsv)
                if (-not @($config['Extensions']).Count) { throw 'no extension id in the download' }
                $extCopy = ([System.IO.Path]::GetFullPath($OutHtml) -replace '\.html?$', '') + '_extensions.json'
                $extDoc = [ordered]@{ source = "malicious_extension_sentry ($($script:ExtensionSentryUrl)), extension IOC data from malext.io, CC BY 4.0; downloaded $((Get-Date).ToUniversalTime().ToString('yyyy-MM-dd HH:mm')) UTC"; count = @($config['Extensions']).Count; entries = @($config['Extensions']) }
                [System.IO.File]::WriteAllText($extCopy, ($extDoc | ConvertTo-Json -Depth 5 -Compress), (New-Object System.Text.UTF8Encoding($false)))
                Write-Host "Browser extension list: $(@($config['Extensions']).Count) extensions, kept at $extCopy" -ForegroundColor DarkGray
            }
            catch { Write-Host "Browser extension list not readable, using the copy in data\: $($_.Exception.Message)" -ForegroundColor Yellow; $config.Remove('Extensions') }
        }
        else { Write-Host 'Using the browser extension list in data\.' -ForegroundColor Yellow }
    }

    # Software lifecycle data (endoflife.date): a file you give, or a download. Without it software_eol
    # uses the table in lib\Checks.ps1 and software_outdated is off.
    if ($EolFile -or $EolOnline) {
        $eolJson = $null
        if ($EolFile) {
            if (Test-Path -LiteralPath $EolFile) { $eolJson = [System.IO.File]::ReadAllText((Resolve-Path -LiteralPath $EolFile).Path) }
            else { Write-Host "endoflife.date file not found: $EolFile" -ForegroundColor Yellow }
        }
        else { $eolJson = Get-EolCatalogOnline }
        if ($eolJson) {
            try {
                $config['Eol'] = ConvertFrom-EolCatalog $eolJson
                if (-not $EolFile) {
                    $eolCopy = ([System.IO.Path]::GetFullPath($OutHtml) -replace '\.html?$', '') + '_eol.json'
                    $eolSource = "endoflife.date ($($script:EolApiUrl)), MIT License; downloaded $((Get-Date).ToUniversalTime().ToString('yyyy-MM-dd HH:mm')) UTC"
                    [System.IO.File]::WriteAllText($eolCopy, (ConvertTo-EolCatalogJson $config['Eol'] $eolSource), (New-Object System.Text.UTF8Encoding($false)))
                    Write-Host "endoflife.date data kept at $eolCopy" -ForegroundColor DarkGray
                }
                Write-Host "endoflife.date: $($config['Eol'].Count) products." -ForegroundColor DarkGray
            }
            catch { Write-Host "endoflife.date data not readable, using the lifecycle table in lib\: $($_.Exception.Message)" -ForegroundColor Yellow; $config.Remove('Eol') }
        }
    }

    # Chocolatey package versions: the copy kept by an earlier run, or a download.
    if ($ChocoFile) {
        if (Test-Path -LiteralPath $ChocoFile) {
            try { $config['Choco'] = ConvertFrom-ChocoCatalog ([System.IO.File]::ReadAllText((Resolve-Path -LiteralPath $ChocoFile).Path)); Write-Host "Chocolatey: $($config['Choco'].Count) packages from $ChocoFile" -ForegroundColor DarkGray }
            catch { Write-Host "Chocolatey file not readable: $($_.Exception.Message)" -ForegroundColor Yellow; $config.Remove('Choco') }
        }
        else { Write-Host "Chocolatey file not found: $ChocoFile" -ForegroundColor Yellow }
    }
    elseif ($ChocoOnline) {
        $choco = Get-ChocoCatalogOnline
        if ($choco.Count -gt 0) {
            $config['Choco'] = $choco
            $chocoCopy = ([System.IO.Path]::GetFullPath($OutHtml) -replace '\.html?$', '') + '_choco.json'
            $chocoSource = "Chocolatey community repository ($($script:ChocoApiUrl)); downloaded $((Get-Date).ToUniversalTime().ToString('yyyy-MM-dd HH:mm')) UTC"
            [System.IO.File]::WriteAllText($chocoCopy, (ConvertTo-ChocoCatalogJson $choco $chocoSource), (New-Object System.Text.UTF8Encoding($false)))
            Write-Host "Chocolatey: $($choco.Count) of $(@($script:ChocoProductMap).Count) packages, kept at $chocoCopy" -ForegroundColor DarkGray
        }
        else { Write-Host 'Chocolatey: nothing came back, those programs are not judged.' -ForegroundColor Yellow }
    }

    # Known vulnerabilities (NVD CVEs and EPSS scores): the copy kept by an earlier run, or a download.
    if ($CveFile) {
        if (Test-Path -LiteralPath $CveFile) {
            try { $config['Cve'] = ConvertFrom-CveCatalog ([System.IO.File]::ReadAllText((Resolve-Path -LiteralPath $CveFile).Path)); Write-Host "NVD: $($config['Cve'].Products.Count) products from $CveFile" -ForegroundColor DarkGray }
            catch { Write-Host "CVE file not readable: $($_.Exception.Message)" -ForegroundColor Yellow; $config.Remove('Cve') }
        }
        else { Write-Host "CVE file not found: $CveFile" -ForegroundColor Yellow }
    }
    elseif ($CveOnline) {
        if (-not $env:NVD_API_KEY) { Write-Host 'NVD without an API key allows 5 requests in 30 seconds: this takes about 2.5 minutes (set NVD_API_KEY to go faster).' -ForegroundColor DarkGray }
        $cveCat = Get-CveCatalogOnline
        if ($cveCat.Products.Count -gt 0) {
            $config['Cve'] = $cveCat
            $cveCopy = ([System.IO.Path]::GetFullPath($OutHtml) -replace '\.html?$', '') + '_cve.json'
            $cveSource = "NVD CVE API 2.0 ($($script:NvdApiUrl)) and FIRST EPSS ($($script:EpssUrl)); downloaded $((Get-Date).ToUniversalTime().ToString('yyyy-MM-dd HH:mm')) UTC"
            [System.IO.File]::WriteAllText($cveCopy, (ConvertTo-CveCatalogJson $cveCat $cveSource), (New-Object System.Text.UTF8Encoding($false)))
            Write-Host "NVD: $($cveCat.Products.Count) of $(@($script:CveCpeMap.Keys).Count) products, EPSS scores of $($cveCat.EpssDate), kept at $cveCopy" -ForegroundColor DarkGray
        }
        else { Write-Host 'NVD: nothing came back, software_cve is not judged.' -ForegroundColor Yellow }
    }

    # Public-exploit references (Metasploit modules and Exploit-DB): the copy kept by an earlier run, or
    # a download. It only enriches software_cve, so it is read but does nothing without the CVE data.
    if ($ExploitFile) {
        if (Test-Path -LiteralPath $ExploitFile) {
            try { $config['Exploits'] = ConvertFrom-ExploitCatalog ([System.IO.File]::ReadAllText((Resolve-Path -LiteralPath $ExploitFile).Path)); Write-Host "Public exploits: $($config['Exploits'].Count) CVEs with a reference from $ExploitFile" -ForegroundColor DarkGray }
            catch { Write-Host "Exploit file not readable: $($_.Exception.Message)" -ForegroundColor Yellow; $config.Remove('Exploits') }
        }
        else { Write-Host "Exploit file not found: $ExploitFile" -ForegroundColor Yellow }
    }
    elseif ($ExploitsOnline) {
        $exCat = Get-ExploitCatalogOnline
        if ($exCat.Msf -or $exCat.Edb) {
            try {
                $msf = if ($exCat.Msf) { @(ConvertFrom-MsfMetadata $exCat.Msf) } else { @() }
                $edb = if ($exCat.Edb) { @(ConvertFrom-ExploitDbCsv $exCat.Edb) } else { @() }
                $config['Exploits'] = ConvertTo-ExploitIndex $msf $edb
                if ($config['Exploits'].Count -eq 0) { throw 'no CVE reference in the downloads' }
                $exCopy = ([System.IO.Path]::GetFullPath($OutHtml) -replace '\.html?$', '') + '_exploits.json'
                $exSource = "Metasploit modules ($($script:MsfMetadataUrl), BSD-3) and Exploit-DB ($($script:ExploitDbUrl), GPLv2 data); downloaded $((Get-Date).ToUniversalTime().ToString('yyyy-MM-dd HH:mm')) UTC"
                [System.IO.File]::WriteAllText($exCopy, (ConvertTo-ExploitCatalogJson $config['Exploits'] $exSource), (New-Object System.Text.UTF8Encoding($false)))
                Write-Host "Public exploits: $($config['Exploits'].Count) CVEs with a Metasploit or Exploit-DB reference, kept at $exCopy" -ForegroundColor DarkGray
            }
            catch { Write-Host "Public-exploit references not readable: $($_.Exception.Message)" -ForegroundColor Yellow; $config.Remove('Exploits') }
        }
        else { Write-Host 'Public exploits: nothing came back, CVE findings are not enriched.' -ForegroundColor Yellow }
    }

    $files = @(Get-SnapshotFiles $Snapshot)
    if ($files.Count -eq 0) { Write-Host 'No hostsnapshot_*.json, .zip or .hbx found.' -ForegroundColor Red; return }

    . $openHbx

    # Several snapshots of one host: the newest one counts.
    $latest = @{}
    $latestFile = @{}
    $snapCount = @{}
    $readIndex = 0
    foreach ($f in $files) {
        $readIndex++
        Step-Spinner "Reading snapshots ($readIndex of $($files.Count))"
        try { $s = Import-HostSnapshot $f }
        catch { Stop-Spinner; Write-Warning $_.Exception.Message; continue }
        $name = (Get-SnapshotHostName $s).ToUpper()
        $when = ConvertTo-UtcDate $s.meta.collectedAtUtc
        $snapCount[$name] = 1 + [int]$snapCount[$name]
        if (-not $latest.ContainsKey($name) -or $when -gt (ConvertTo-UtcDate $latest[$name].meta.collectedAtUtc)) {
            $latest[$name] = $s
            $latestFile[$name] = $f
        }
    }
    Stop-Spinner
    foreach ($name in ($snapCount.Keys | Sort-Object)) {
        if ($snapCount[$name] -gt 1) { Write-Host " $name`: $($snapCount[$name]) snapshots, using the newest $($latestFile[$name])" -ForegroundColor DarkGray }
    }
    if ($latest.Count -eq 0) { Write-Host 'No readable snapshot.' -ForegroundColor Red; return }

    $allFindings = New-Object System.Collections.Generic.List[object]
    $hosts = New-Object System.Collections.Generic.List[object]
    $names = @($latest.Keys | Sort-Object)
    # Several hosts at once when there are enough of them to pay for starting the workers (each loads
    # the checks): -Threads 0 picks up to 4 (the workers share one process, and more of them were slower
    # on 16 processors), 1 analyzes one host at a time.
    $threadCount = if ($Threads -gt 0) { $Threads } else { [Math]::Min([Math]::Min(4, [Environment]::ProcessorCount), [Math]::Floor($names.Count / 8)) }
    $threadCount = [int][Math]::Max(1, [Math]::Min($threadCount, $names.Count))
    if ($threadCount -gt 1) {
        $progress = { param($done) Step-Spinner "Analyzing hosts ($done of $($names.Count), $threadCount at once)" }
        $rows = @(Invoke-HostAnalysisParallel -Snapshots $latest -Names $names -Config $config -Threads $threadCount -SkipStig ([bool]$SkipStig) -ExtraEdrServices $ExtraEdrServices -OnProgress $progress)
    }
    else {
        $hostIndex = 0
        $rows = @(foreach ($name in $names) {
                $hostIndex++
                Step-Spinner "Analyzing host $hostIndex of $($names.Count)"
                Invoke-HostAnalysis -Snapshot $latest[$name] -Config $config -SkipStig ([bool]$SkipStig) -ExtraEdrServices $ExtraEdrServices
            })
    }
    for ($i = 0; $i -lt $rows.Count; $i++) {
        $row = $rows[$i]
        foreach ($f in $row.Findings) { $allFindings.Add($f) }
        $hosts.Add($row)
        $meta = $latest[$names[$i]].meta
        if (-not $meta.runningAsSystem -and -not $meta.runningAsAdmin) {
            Stop-Spinner
            Write-Host " $($row.Name): collected as a standard user; $(@($row.NotEvaluated).Count) check(s) not evaluated. Collect as SYSTEM or administrator for full coverage." -ForegroundColor Yellow
        }
    }
    Stop-Spinner
    if ($threadCount -gt 1) { Write-Host "$($names.Count) hosts analyzed, $threadCount at once." -ForegroundColor DarkGray }
    # Fleet checks: findings that need several hosts (shared local passwords, cloned machine SIDs, drift).
    Step-Spinner 'Analyzing the fleet'
    $neByHost = @{}
    # A check the policy turns off is skipped there too.
    foreach ($h in $hosts) { $neByHost[$h.Name] = @(@($h.NotEvaluated | ForEach-Object { $_.Type }) + @($h.PolicyOff) | Where-Object { $_ }) }
    $fleetFindings = @(Invoke-FleetChecks -Snapshots @($latest.Values) -NotEvaluated $neByHost -Config $config)
    foreach ($f in $fleetFindings) { $allFindings.Add($f) }
    $fleetByHost = Group-ByHost $fleetFindings
    foreach ($h in $hosts) { if ($fleetByHost.ContainsKey($h.Name)) { $h.Findings = @($h.Findings) + @(Get-HostItems $fleetByHost $h.Name) } }
    # NIS2 / ACN basic measures (-Nis2Acn), once the fleet findings are in. Drift is only judged among
    # at least five hosts of the same role.
    foreach ($h in @($hosts | Where-Object { $Nis2Acn })) {
        $off = @(@($h.OptionalOff) + @($h.PolicyOff) | Where-Object { $_ })
        if (@($hosts | Where-Object { $_.Role -eq $h.Role }).Count -lt 5) { $off += 'config_drift' }
        $h.Acn = @(Get-AcnStatus -Role $h.Role -Findings $h.Findings -NotEvaluated $h.NotEvaluated -Off $off -Config $config)
    }
    Stop-Spinner
    $script:RunHosts = @($hosts | ForEach-Object { $_.Name })

    $asOf = ($hosts | Sort-Object CollectedUtc -Descending | Select-Object -First 1).CollectedUtc
    $split = Split-FindingsByException -Findings $allFindings.ToArray() -Exceptions (Import-Exceptions $ExceptionsFile) -AsOf $asOf
    $activeByHost = Group-ByHost $split.Active
    foreach ($h in $hosts) { $h.Score = Get-HostScore @(Get-HostItems $activeByHost $h.Name) }
    # The score of every run, kept per host and snapshot (-History): the report shows how each host moved.
    if ($History) {
        $trends = Update-ScoreHistory -Path $History -Hosts $hosts.ToArray() -ActiveByHost $activeByHost -ToolVersion $script:HostBadgerVersion
        if ($trends) {
            foreach ($h in $hosts) { $h.Trend = $trends[$h.Name] }
            Write-Host "Score history: $History ($(@($hosts | Where-Object { $_.Trend -and $_.Trend.Previous }).Count) of $($hosts.Count) host(s) with an earlier score)" -ForegroundColor DarkGray
        }
    }

    $comparison = if ($CompareTo) { Get-FindingsComparison -Findings $split.Active -PreviousCsv $CompareTo } else { $null }

    # Remediation scripts: text files only. HostBadger never runs them.
    $remInfo = $null
    if ($OutRemediation) {
        $remDir = [System.IO.Path]::GetFullPath($OutRemediation)
        if (-not (Test-Path -LiteralPath $remDir)) { New-Item -ItemType Directory -Path $remDir -Force | Out-Null }
        $remInfo = @()
        foreach ($h in $hosts) {
            $r = New-RemediationScript -HostName $h.Name -Role $h.Role -Findings @(Get-HostItems $activeByHost $h.Name) -Config $config -CollectedUtc $h.CollectedUtc.ToString('yyyy-MM-dd HH:mm') -ToolVersion $script:HostBadgerVersion -ProfileName $RemediationProfile -Debloat:$RemediationDebloat -Privacy:$RemediationPrivacy -NoApps:$RemediationNoApps -OnlyProfile:$RemediationOnlyProfile
            $file = ''
            if ($r.ActionCount -gt 0) {
                $file = 'remediate_' + ($h.Name -replace '[^\w\-]', '_') + '.ps1'
                # With a BOM so Windows PowerShell 5.1 reads it as UTF-8.
                [System.IO.File]::WriteAllText((Join-Path $remDir $file), $r.Text, (New-Object System.Text.UTF8Encoding($true)))
            }
            $remInfo += [PSCustomObject]@{ Host = $h.Name; File = $file; Actions = $r.ActionCount; Fixable = $r.FixableFindings; NotFixable = @($r.NotFixable).Count; Total = $r.TotalFindings }
        }
    }

    Step-Spinner 'Writing the findings CSV'
    Export-FindingsCsv -Findings $split.Active -Path $OutCsv
    if ($OutJsonl) { Export-FindingsJsonl -Findings $split.Active -Hosts $hosts -Path $OutJsonl -ToolVersion $script:HostBadgerVersion -Comparison $comparison }
    $elapsedText = & $fmtElapsed ((Get-Date) - $started)
    Step-Spinner 'Building the HTML report'
    $html = ConvertTo-ReportHtml -Hosts $hosts.ToArray() -Split $split -Comparison $comparison -Config $config -ToolVersion $script:HostBadgerVersion -ElapsedText $elapsedText -Remediation $remInfo -HideCis:$HideCis -HideStig:$HideStig -KevLoaded:([bool]$config.Kev)
    $htmlFull = [System.IO.Path]::GetFullPath($OutHtml)
    [System.IO.File]::WriteAllText($htmlFull, $html, (New-Object System.Text.UTF8Encoding($false)))

    # One report per host, next to the fleet report: <name>_<HOST>.html (with one host it would be a copy).
    $perHostFiles = @()
    if ($PerHost -and $hosts.Count -gt 1) {
        $base = $htmlFull -replace '\.html?$', ''
        $acceptedByHost = Group-ByHost $split.Accepted -OfFinding
        $cmpByHost = if ($comparison) { @{ New = (Group-ByHost $comparison.New); Resolved = (Group-ByHost $comparison.Resolved); Persisting = (Group-ByHost $comparison.Persisting) } } else { $null }
        foreach ($h in $hosts) {
            $hn = $h.Name
            $splitH = [PSCustomObject]@{
                Active   = @(Get-HostItems $activeByHost $hn)
                Accepted = @(Get-HostItems $acceptedByHost $hn)
                Expired  = @($split.Expired)
            }
            $cmpH = $null
            if ($comparison) {
                $cmpH = [PSCustomObject]@{
                    PreviousPath = $comparison.PreviousPath
                    New          = @(Get-HostItems $cmpByHost.New $hn)
                    Resolved     = @(Get-HostItems $cmpByHost.Resolved $hn)
                    Persisting   = @(Get-HostItems $cmpByHost.Persisting $hn)
                }
            }
            $remH = if ($remInfo) { @($remInfo | Where-Object { $_.Host -eq $hn }) } else { $null }
            Step-Spinner "Building the report for $hn"
            $htmlH = ConvertTo-ReportHtml -Hosts @($h) -Split $splitH -Comparison $cmpH -Config $config -ToolVersion $script:HostBadgerVersion -ElapsedText $elapsedText -Remediation $remH -HideCis:$HideCis -HideStig:$HideStig -KevLoaded:([bool]$config.Kev)
            $fileH = "$base`_$($hn -replace '[^\w\-]', '_').html"
            [System.IO.File]::WriteAllText($fileH, $htmlH, (New-Object System.Text.UTF8Encoding($false)))
            $perHostFiles += $fileH
        }
    }

    Stop-Spinner
    $active = @($split.Active)
    Write-Host ''
    Write-Host "Hosts analyzed: $($hosts.Count)"
    foreach ($h in ($hosts | Sort-Object { $_.Score.Score })) {
        $hf = @(Get-HostItems $activeByHost $h.Name)
        Write-Host (" {0,-24} {1,-11} {2} {3,3}/100 {4} finding(s), {5} not evaluated" -f $h.Name, $h.Role, $h.Score.Grade, $h.Score.Score, $hf.Count, @($h.NotEvaluated).Count)
    }
    Write-Host ("Findings: {0} ({1} Critical, {2} High, {3} Medium, {4} Low){5}" -f $active.Count,
        @($active | Where-Object { $_.Severity -eq 'Critical' }).Count, @($active | Where-Object { $_.Severity -eq 'High' }).Count,
        @($active | Where-Object { $_.Severity -eq 'Medium' }).Count, @($active | Where-Object { $_.Severity -eq 'Low' }).Count,
        $(if (@($split.Accepted).Count) { ", $(@($split.Accepted).Count) accepted" } else { '' }))
    Write-Host "Report: $OutHtml"
    Write-Host "Findings: $OutCsv"
    foreach ($pf in $perHostFiles) { Write-Host "Host: $pf" }
    if ($OutJsonl) { Write-Host "SIEM: $OutJsonl" }
    if ($remInfo) {
        foreach ($ri in $remInfo) { if ($ri.File) { Write-Host ("Fix: {0} ({1} setting(s) for {2} of {3} finding(s))" -f (Join-Path $remDir $ri.File), $ri.Actions, $ri.Fixable, $ri.Total) } }
        Write-Host " Preview first (it changes nothing without -Apply), try it on a pilot host, then -Apply; -Restore <rollback file> -Apply undoes it." -ForegroundColor DarkGray
    }

    # --------------------------------------------------------------------------
    # Optional AI step. The report is already on disk by now; without -SendToAI or
    # -AiDryRun nothing below runs, and HostBadger never asks. -AiLater (the guided
    # menu) keeps the analysis in this session's memory instead, so the menu can ask
    # about the AI summary and run only this step with -AiContinue.
    # --------------------------------------------------------------------------
    if ($AiLater -and -not $SendToAI -and -not $AiDryRun) {
        $global:HostBadgerAiPending = @{ Active = $active; Hosts = $hosts; Latest = $latest; Comparison = $comparison; Split = $split; Config = $config; Remediation = $remInfo; ElapsedText = $elapsedText; HtmlFull = $htmlFull; OutHtml = $OutHtml; HideCis = [bool]$HideCis; HideStig = [bool]$HideStig }
        return
    }
    . $aiStep
}
finally {
    if ($script:RunLogOn) { try { Stop-Transcript | Out-Null } catch { } ; if ($OutLog) { Write-Host "Run log: $OutLog" -ForegroundColor DarkGray } }
}