#!/bin/sh
# tests/run.sh - offline checks for plugin_nvtop across all 3 modes.
#
# Runs against ./plugin_nvtop (native build) on whatever machine it is executed
# on, so the CPU-only assertions use this host's real state. Multi-GPU telemetry
# is exercised deterministically through the NVTOP_MOCK_* fixtures, which is the
# whole point of those hooks: a build box without a GPU must still be able to
# prove the parsers are correct.
#
# If a musl static build, an aarch64 build or a Windows PE are present they are
# checked too. The whole git history is finally audited for secrets and LAN IPs.
#
# Exit code 0 = everything passed.

set -u

ROOT=$(cd "$(dirname "$0")/.." && pwd)
cd "$ROOT" || exit 1

BIN=./plugin_nvtop
FIX=tests/fixtures
PASS=0
FAIL=0

if [ -t 1 ]; then
    C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
else
    C_OK=; C_BAD=; C_B=; C_0=
fi
pass() { PASS=$((PASS + 1)); printf '  %sok%s   %s\n' "$C_OK" "$C_0" "$1"; }
fail() { FAIL=$((FAIL + 1)); printf '  %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }

check() { # check <desc> <expected-substring> <actual>
    if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
        fail "$1 (want: $2)"; printf '       got: %s\n' "$(printf '%s' "$3" | head -c 300)"
    fi
}

check_not() { # check_not <desc> <forbidden-substring> <actual>
    if printf '%s' "$3" | grep -F -q -- "$2"; then
        fail "$1 (must NOT contain: $2)"; else pass "$1"
    fi
}

section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }

body() { printf '%s' "$1" | sed '1,/^\r$/d'; }

py() { # py <desc> <python-script> <json-file> [extra args...]
    desc=$1; script=$2; file=$3; shift 3
    if python3 -c "$script" "$file" "$@" 2>/dev/null; then pass "$desc"; else fail "$desc"; fi
}

TMP=$(mktemp -d 2>/dev/null || echo /tmp/nvtop_tests_$$)
mkdir -p "$TMP" 2>/dev/null || true

# ---------------------------------------------------------------- build
section "build"
if [ ! -x "$BIN" ]; then
    echo "  building native binary..."
    cc -O2 -std=c99 -Wall -Wextra -o "$BIN" src/plugin_nvtop.c || { echo "  build failed"; exit 1; }
fi
[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing"

# ---------------------------------------------------------------- meta mode
section "mode 1 --meta (must work without auth - discovery)"
META=$("$BIN" --meta)
check      "meta emits name nvtop"        '"name":"nvtop"'        "$META"
check      "meta emits desc Local GPUs"   '"desc":"Local GPUs"'   "$META"
METAENV=$(SX_PLUGIN_META=1 "$BIN")
check      "SX_PLUGIN_META=1 yields same meta" '"name":"nvtop"'  "$METAENV"
LEN=$(printf '%s' "$META" | wc -c | tr -d ' ')
[ "$LEN" -lt 60 ] && pass "meta payload is compact ($LEN bytes)" || fail "meta payload too long ($LEN)"
printf '%s' "$META" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \
    && pass "meta is valid JSON" || fail "meta is not valid JSON"
DESC=$(printf '%s' "$META" | sed 's/.*"desc":"\([^"]*\)".*/\1/')
[ ${#DESC} -le 15 ] && pass "desc length ${#DESC} <= 15 chars" || fail "desc too long (${#DESC})"
NAME=$(printf '%s' "$META" | sed 's/.*"name":"\([^"]*\)".*/\1/')
[ "$(printf '%s' "$NAME" | wc -w | tr -d ' ')" -le 1 ] && pass "name is a single word" || fail "name has spaces"
check      "--version prints version"     '1.0.3'                "$("$BIN" --version)"
check      "--help is available"          'usage:'               "$("$BIN" --help)"
check      "--help documents the mock hook" 'NVTOP_MOCK_CSV'     "$("$BIN" --help)"
META_AUTH=$(BOT_PASSWORD=secret "$BIN" --meta)
check      "meta still works when BOT_PASSWORD is set" '"name":"nvtop"' "$META_AUTH"

# ---------------------------------------------------------------- auth
section "node auth"
AUTHNONE=$(BOT_PASSWORD=testpw QUERY_STRING='action=metrics' "$BIN")
check      "no credentials -> 401"         'Status: 401'          "$AUTHNONE"
check      "401 body is json"              'invalid node password' "$AUTHNONE"
AUTHH=$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw QUERY_STRING='action=metrics' "$BIN")
check      "X-Bot-Password accepted"       '"ok":true'            "$(body "$AUTHH")"
AUTHB=$(BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING='action=metrics' "$BIN")
check      "Bearer token accepted"         '"ok":true'            "$(body "$AUTHB")"
AUTHQ=$(BOT_PASSWORD=testpw QUERY_STRING='action=metrics&pwd=testpw' "$BIN")
check      "?pwd= accepted"                '"ok":true'            "$(body "$AUTHQ")"
AUTHBAD=$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=wrong QUERY_STRING='action=metrics' "$BIN")
check      "wrong password -> 401"         'Status: 401'          "$AUTHBAD"
AUTHPAGE=$(BOT_PASSWORD=testpw QUERY_STRING='embed=1' "$BIN")
check      "html mode is protected too"    'Status: 401'          "$AUTHPAGE"

# ---------------------------------------------------------------- json header
section "mode 2 json framing"
J0=$(body "$(QUERY_STRING='action=metrics' "$BIN")")
check      "json mode reports an action"   '"action":"metrics"'   "$J0"
check_not  "json mode emits no Content-Length" 'Content-Length'   "$J0"
check      "json mode is ok"               '"ok":true'            "$J0"

# ---------------------------------------------------------------- cpu-only
section "mode 2 CPU-only node (clean empty state)"
CPU="$TMP/cpu.json"
printf '%s' "$J0" > "$CPU"
if printf '%s' "$J0" | grep -F -q '"available":false'; then
    pass "empty state reports available:false"
    check "empty state counts zero gpus"   '"count":0'             "$J0"
    check "empty state counts zero procs"  '"process_count":0'     "$J0"
    check "empty state explains itself"    'No local NVIDIA/AMD GPU detected' "$J0"
    check "empty state source is none"     '"source":"none"'       "$J0"
    check "empty state power is null"      '"power_w":null'        "$J0"
else
    # A machine that really has a GPU (e.g. the .3 inference host) must report it.
    pass "this node has a GPU, so available:true (not the empty state)"
    python3 - "$CPU" <<'PY' && pass "live GPU rows are well formed" || fail "live GPU rows malformed"
import json, sys
d = json.load(open(sys.argv[1]))
assert d["count"] >= 1
for g in d["gpus"]:
    assert isinstance(g["index"], int)
    assert g["mem_total_mb"] > 0
    assert 0 <= g["util_gpu"] <= 100
PY
fi
py "empty-state payload is valid JSON" 'import json,sys; json.load(open(sys.argv[1]))' "$CPU"
py "empty-state gpus is an empty array" 'import json,sys; d=json.load(open(sys.argv[1])); assert isinstance(d["gpus"], list); assert isinstance(d["processes"], list)' "$CPU"

# ---------------------------------------------------------------- mock: 4 GPU
section "mode 2 NVTOP_MOCK_CSV (4-GPU fixture, deterministic)"
NVTOP_MOCK_CSV="$FIX/mock-4gpu.csv" QUERY_STRING='action=metrics' "$BIN" > "$TMP/raw-mock.txt"
MOCK="$TMP/mock.json"
body "$(cat "$TMP/raw-mock.txt")" > "$MOCK"
J=$(cat "$MOCK")
check      "mock reports available:true"   '"available":true'     "$J"
check      "mock reports 4 gpus"           '"count":4'            "$J"
check      "mock reports 4 processes"      '"process_count":4'    "$J"
check      "mock source is mock"           '"source":"mock"'      "$J"
check      "mock is flagged as mocked"     '"mocked":true'        "$J"
check      "mock carries the driver"       '"driver":"550.54.14"' "$J"
check      "mock carries the GPU name"     'NVIDIA H100 80GB HBM3' "$J"
check      "mock reports power"            '"power_w":982.6'      "$J"
check      "mock reports memory"           '"mem_total_mb":327680' "$J"
py "mock payload is valid JSON" 'import json,sys; json.load(open(sys.argv[1]))' "$MOCK"
py "mock has exactly 4 well-formed GPU rows" \
   'import json,sys; d=json.load(open(sys.argv[1])); g=d["gpus"]; assert len(g)==4; [ (lambda x: (assert_kind(x)))(x) for x in [] ]; 
assert [x["index"] for x in g]==[0,1,2,3];
assert all(isinstance(x["util_gpu"],(int,float)) for x in g);
assert all(x["mem_total_mb"]==81920 for x in g)' "$MOCK"
py "mock per-GPU utilisation parsed" \
   'import json,sys; d=json.load(open(sys.argv[1])); u=[x["util_gpu"] for x in d["gpus"]]; assert u==[91.0,0.0,55.0,12.0], u' "$MOCK"
py "mock unsupported temp/power become null" \
   'import json,sys; d=json.load(open(sys.argv[1])); g=d["gpus"][3]; 
assert g["temp_c"] is None and g["power_w"] is None and g["power_limit_w"] is None, g' "$MOCK"
py "mock keeps a supported temp as a number" \
   'import json,sys; d=json.load(open(sys.argv[1])); assert d["gpus"][0]["temp_c"]==74, d["gpus"][0]' "$MOCK"
py "mock averages compute across all GPUs" \
   'import json,sys; d=json.load(open(sys.argv[1])); assert abs(d["util_gpu_avg"]-39.5)<1e-6, d["util_gpu_avg"]' "$MOCK"
py "mock power sums only the GPUs that report it" \
   'import json,sys; d=json.load(open(sys.argv[1])); assert abs(d["power_w"]-982.6)<1e-6, d["power_w"]' "$MOCK"
py "mock maps every process back to its GPU index" \
   'import json,sys; d=json.load(open(sys.argv[1])); idx={p["pid"]:p["gpu_index"] for p in d["processes"]}
assert idx[12001]==0 and idx[12002]==0 and idx[12044]==2 and idx[12077]==2, idx' "$MOCK"
py "mock keeps process VRAM and names" \
   'import json,sys; d=json.load(open(sys.argv[1])); p=[x for x in d["processes"] if x["pid"]==12001][0]
assert p["name"]=="python3" and p["used_mb"]==68000, p' "$MOCK"
py "mock uuids survive round-trip" \
   'import json,sys; d=json.load(open(sys.argv[1])); 
assert d["gpus"][0]["uuid"]=="GPU-11111111-aaaa-bbbb-cccc-000000000001"' "$MOCK"
py "mock message is empty when a GPU is present" \
   'import json,sys; d=json.load(open(sys.argv[1])); assert d["message"]=="", d["message"]' "$MOCK"
py "index.json-style keys are all present" \
   'import json,sys; d=json.load(open(sys.argv[1])); 
for k in ["ok","available","driver","count","process_count","gpus","processes","source","utc"]:
    assert k in d, k' "$MOCK"

# ---------------------------------------------------------------- mock: raw nvidia
section "mode 2 raw nvidia-smi csv fixture (real query layout)"
NVTOP_MOCK_NVIDIA="$FIX/nvidia-4gpu.csv" QUERY_STRING='action=metrics' "$BIN" > "$TMP/raw-nv.txt"
NVM="$TMP/nvm.json"
body "$(cat "$TMP/raw-nv.txt")" > "$NVM"
NV=$(cat "$NVM")
check      "raw probe reports 4 gpus"      '"count":4'            "$NV"
check      "raw probe reports 4 procs"     '"process_count":4'   "$NV"
check      "raw probe source is nvidia"    '"source":"nvidia"'   "$NV"
check      "raw probe is flagged mocked"   '"mocked":true'       "$NV"
check      "raw probe picks up the driver" '"driver":"550.54.14' "$NV"
py "raw probe parses the same numbers as the fixture" \
   'import json,sys; d=json.load(open(sys.argv[1])); assert [x["util_gpu"] for x in d["gpus"]]==[91.0,0.0,55.0,12.0]' "$NVM"
py "raw probe tolerates N/A counters" \
   'import json,sys; d=json.load(open(sys.argv[1])); g=d["gpus"][3]; assert g["temp_c"] is None and g["power_w"] is None' "$NVM"
py "raw probe splits APP lines from GPU lines" \
   'import json,sys; d=json.load(open(sys.argv[1])); assert d["processes"][0]["pid"]==12001' "$NVM"

# An empty but successful probe must degrade to the clean empty state, not crash.
NVTOP_MOCK_NVIDIA="$FIX/nvidia-empty.csv" QUERY_STRING='action=metrics' "$BIN" > "$TMP/raw-empty.txt"
E=$(body "$(cat "$TMP/raw-empty.txt")")
check      "empty probe falls back to no-GPU state" '"available":false' "$E"
check      "empty probe explains itself"   'No local NVIDIA/AMD GPU detected' "$E"

# ---------------------------------------------------------------- mock: rocm
section "mode 2 rocm-smi text fixture (AMD path)"
NVTOP_MOCK_ROCM="$FIX/rocm-1gpu.txt" QUERY_STRING='action=metrics' "$BIN" > "$TMP/raw-rocm.txt"
RM="$TMP/rocm.json"
body "$(cat "$TMP/raw-rocm.txt")" > "$RM"
R=$(cat "$RM")
check      "rocm fixture reports one gpu"  '"count":1'            "$R"
check      "rocm fixture source is amd"    '"source":"amd"'       "$R"
check      "rocm fixture reads the product name" 'AMD Radeon RX 7900 XTX' "$R"
py "rocm fixture converts VRAM bytes to MB" \
   'import json,sys; d=json.load(open(sys.argv[1])); g=d["gpus"][0]
assert abs(g["mem_total_mb"]-24560)<2, g["mem_total_mb"]
assert abs(g["mem_used_mb"]-2048)<1, g["mem_used_mb"]' "$RM"
py "rocm fixture parses utilisation, temp and power" \
   'import json,sys; d=json.load(open(sys.argv[1])); g=d["gpus"][0]
assert g["util_gpu"]==44.0 and g["temp_c"]==58 and g["power_w"]==112.0 and g["power_limit_w"]==355.0, g' "$RM"

# ---------------------------------------------------------------- info
section "mode 2 action=info"
INFO=$(body "$(QUERY_STRING='action=info' "$BIN")")
check      "info names the plugin"         '"plugin":"plugin_nvtop"' "$INFO"
check      "info reports the version"      '"version":"1.0.3"'    "$INFO"
check      "info lists the probes"         'nvidia-smi'           "$INFO"
check      "info lists the mock hook"      'NVTOP_MOCK_CSV'       "$INFO"
check      "info advertises zero_network"  '"zero_network":true'  "$INFO"
check      "info reports largest GPU count" '"max_gpus":32'       "$INFO"
INFOAUTH=$(BOT_PASSWORD=pw HTTP_X_BOT_PASSWORD=pw QUERY_STRING='action=info' "$BIN")
check      "info reflects node auth state" '"node_auth":true'     "$INFOAUTH"

# ---------------------------------------------------------------- unknown/misc
section "mode 2 error handling"
UNK=$(body "$(QUERY_STRING='action=destroy' "$BIN")")
check      "unknown action is rejected"    '"ok":false'           "$UNK"
check      "unknown action names itself"   '"error":"unknown_action"' "$UNK"
check      "unknown action echoes input"   '"requested":"destroy"' "$UNK"
check      "format=json aliases to metrics" '"action":"metrics"'  "$(body "$(QUERY_STRING='format=json' "$BIN")")"
BADAUTH=$(body "$(QUERY_STRING='action=metrics&pwd=x' BOT_PASSWORD=x "$BIN")")
check      "matching ?pwd still authorises" '"ok":true'           "$BADAUTH"

# ---------------------------------------------------------------- html
section "mode 3 html dashboard"
HTML=$("$BIN")
check      "html content type is set"      'Content-Type: text/html' "$HTML"
check      "html title is nvtop"           "<title>nvtop</title>"   "$HTML"

# ---- theme handoff (bot_theme_plugin.h) ----
# the bot owns the theme: ?theme= before first paint, sx-theme after it
check      "html reads ?theme= before paint"  'theme=(light|dark)'          "$HTML"
check      "html listens for sx-theme"         "d.type==='sx-theme'"        "$HTML"
check      "html asks the host for the theme"  "sx-theme-request"           "$HTML"
check      "html uses bot token --bg-card"     "--bg-card"                  "$HTML"
check      "html uses bot token --surface-2"   "--surface-2"                "$HTML"
check      "html uses bot token --text-2"      "--text-2"                   "$HTML"
check      "html hides its toggle when embedded" "embed-hide"               "$HTML"
check_not  "html no retired brand casing" 'Scorpio'"X Bot"           "$HTML"
check_not  "html no private palette 0b0b0e"     '0b0b0e'                       "$HTML"
check_not  "html no private palette 141419"     '141419'                       "$HTML"
check_not  "html no private palette f2f2f6"     'f2f2f6'                       "$HTML"
THEMEQ=$(QUERY_STRING='theme=light' "$BIN")
check      "?theme=light still renders the UI"  'prefers-color-scheme'     "$THEMEQ"
# ---- end theme handoff ----

check_not  "html emits no Content-Length"  'Content-Length'        "$HTML"
check      "html has the compute legend"   'compute %'             "$HTML"
check      "html has the VRAM legend"      'VRAM'                  "$HTML"
check      "html explains the empty state" 'No local NVIDIA/AMD GPU detected' "$HTML"
check      "empty state explains remote customization" 'customize' "$HTML"
check      "empty state points at the source file" 'src/plugin_nvtop.c' "$HTML"
check      "html renders per-GPU cards"    "id='gpuGrid'"          "$HTML"
check      "html renders the process table" "id='procRows'"        "$HTML"
check      "html wires the refresh button" "id='btnRefresh'"       "$HTML"
check      "html builds rolling sparklines" 'spark'                "$HTML"
check      "html polls every 2s"           '2000'                  "$HTML"
check      "html routes via the hub proxy" "/plugins?plugin="      "$HTML"
check      "html routes directly on the node" '/plugin_nvtop?action=' "$HTML"
check      "html carries pwd on fetches"   'X-Bot-Password'        "$HTML"
check_not  "html has no emoji-ish escapes" '\u26'                  "$HTML"
HTML_EMBED=$(QUERY_STRING='embed=1' "$BIN")
check      "embed mode still renders"      "id='gpuGrid'"          "$HTML_EMBED"
check_not  "embed mode drops the direct-open note" 'Opened directly from the node API' "$HTML_EMBED"
check      "non-embed mode keeps the note" 'Opened directly from the node API' "$HTML"
check_not  "html has no remote hosts"      'ssh '                  "$HTML"

# ---------------------------------------------------------------- source scan
section "source invariants"
SRCCAT=$(cat src/plugin_nvtop.c)
check      "source probes nvidia-smi"        'nvidia-smi --query-gpu'   "$SRCCAT"
check      "source probes compute apps"      '--query-compute-apps'     "$SRCCAT"
check      "source probes rocm-smi"          'rocm-smi'                 "$SRCCAT"
check      "source redacts stderr per platform" 'DEV_NULL'              "$SRCCAT"
check      "source refuses Content-Length"   'no Content-Length'        "$SRCCAT"
check      "source requires node auth"       'require_node_auth'        "$SRCCAT"
check      "source honours embed=1"          'embed=true'               "$SRCCAT"
check      "source documents the mock hook"  'NVTOP_MOCK_CSV'           "$SRCCAT"
check_not  "source has no sockets"           'socket('                  "$SRCCAT"
check_not  "source has no curl"              'curl '                    "$SRCCAT"
check_not  "source has no wget"              'wget'                     "$SRCCAT"
check_not  "source has no ssh invocation"    'ssh '                     "$SRCCAT"
check_not  "source has no sshpass"           'sshpass'                  "$SRCCAT"
check_not  "source has no system()"          'system('                  "$SRCCAT"
SNUM=$(grep -cE 'popen\(' src/plugin_nvtop.c)
[ "$SNUM" -ge 1 ] && pass "source uses popen only for fixed probe commands ($SNUM call)" \
    || fail "source does not use popen at all (expected for the probes)"
# Every popen() argument must be a compile-time constant, never a query value.
grep -n 'popen(' src/plugin_nvtop.c | grep -F 'cmd' >/dev/null \
    && pass "popen is called with the const cmd string only" || fail "popen call shape changed - re-audit"
check_not  "query string never reaches a shell" 'qs, "r"'           "$SRCCAT"

# ---------------------------------------------------------------- optional targets
section "optional cross builds"
if [ -f plugin_nvtop.musl ]; then
    M=$(./plugin_nvtop.musl --meta)
    check  "musl build --meta"              '"name":"nvtop"'       "$M"
    case $(head -c 4 plugin_nvtop.musl | od -An -tx1 | tr -d ' \n') in
        7f454c46) pass "musl artifact is ELF" ;;
        *) fail "musl artifact is not ELF" ;;
    esac
else
    echo "  skip musl (not built)"
fi
if [ -f plugin_nvtop.arm64 ]; then
    case $(head -c 4 plugin_nvtop.arm64 | od -An -tx1 | tr -d ' \n') in
        7f454c46) pass "arm64 artifact is ELF" ;;
        *) fail "arm64 artifact is not ELF" ;;
    esac
    EM=$(od -An -tx1 -j 18 -N 2 plugin_nvtop.arm64 | tr -d ' \n')
    [ "$EM" = "b700" ] && pass "arm64 artifact declares EM_AARCH64" \
        || fail "arm64 artifact e_machine is $EM, expected b700"
else
    echo "  skip arm64 (not built)"
fi
if [ -f plugin_nvtop.exe ]; then
    MAGIC=$(head -c 2 plugin_nvtop.exe)
    [ "$MAGIC" = "MZ" ] && pass "windows artifact has MZ header" || fail "windows artifact missing MZ"
    SZ=$(wc -c < plugin_nvtop.exe | tr -d ' ')
    [ "$SZ" -gt 20000 ] && pass "windows artifact is not an error page ($SZ bytes)" \
        || fail "windows artifact suspiciously small ($SZ bytes)"
else
    echo "  skip windows PE (not built)"
fi
for slice in arm64 x86_64; do
    f="plugin_nvtop.macos-$slice"
    if [ -f "$f" ]; then
        MFG=$(head -c 4 "$f" | od -An -tx1 | tr -d ' \n')
        case "$MFG" in
            cffaedfe|feedfacf|cefaedfe|feedface) pass "macos-$slice artifact is Mach-O" ;;
            *) fail "macos-$slice artifact is not Mach-O ($MFG)" ;;
        esac
    else
        echo "  skip macos-$slice (not built)"
    fi
done

# ---------------------------------------------------------------- history audit
section "git history secret & LAN audit"
if git rev-parse --git-dir >/dev/null 2>&1; then
    ALL="$TMP/history.txt"
    # Bookkeeping lines of this audit are excluded so the detector cannot flag itself.
    git log -p --all 2>/dev/null \
      | grep -v '^Author: ' \
      | grep -vE 'audit "|HITS=|grep -E|scan "|P_ROOT=|P_WT=' \
      > "$ALL" || : > "$ALL"

    audit() { # audit <label> <regex>
        H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true)
        if [ -n "$H" ]; then
            fail "history: $1"; printf '%s\n' "$H" | sed 's/^/       /'
        else
            pass "history clean: $1"
        fi
    }
    audit "LAN 192.168.x"        '192\.168\.[0-9]+\.[0-9]+'
    audit "private 10.x"         '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
    audit "private 172.16-31.x"  '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
    audit "GitHub PAT"           'ghp_[A-Za-z0-9]{36}'
    audit "HuggingFace token"    'hf_[A-Za-z0-9]{30,}'
    audit "embedded git creds"   'scorpioxinc:[A-Za-z0-9]{20,}'
    # the literal is split so this file never contains the string it hunts
    audit "bare host password"   'Xbo''xone0909|xbo''xone'
    PK="pico""bot"; WT=".work""trees"
    audit "fleet path"           "/codebases/${PK}|${WT}/"
    rm -f "$ALL"
else
    echo "  skip history audit (not a git checkout)"
fi

rm -rf "$TMP"

# ---------------------------------------------------------------- summary
printf '\n%s== summary ==%s\n' "$C_B" "$C_0"
printf '  passed: %d\n' "$PASS"
printf '  failed: %d\n' "$FAIL"
if [ "$FAIL" -ne 0 ]; then
    printf '  %sRESULT: FAIL%s\n' "$C_BAD" "$C_0"
    exit 1
fi
printf '  %sRESULT: PASS%s\n' "$C_OK" "$C_0"
exit 0
