#!/bin/sh
# tests/run.sh - offline checks for plugin_logs across all 3 modes.
#
# Runs against ./plugin_logs (native build) on the live machine. Journal output
# is replayed from a captured fixture so the parser is tested on the real
# `journalctl -o json` layout without needing a running journald, and the file
# reader is pointed at fixture logs through the SX_LOGS_EXTRA_ROOT knob. The
# last section audits the whole git history for secrets and internal addresses.
#
# Exit code 0 = everything passed.

set -u

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

BIN=./plugin_logs
PASS=0
FAIL=0
TMP=$(mktemp -d 2>/dev/null || echo /tmp/logs_test_$$)
mkdir -p "$TMP"
trap 'rm -rf "$TMP"' EXIT

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'; }

# ---------------------------------------------------------------- fixtures
# A journal stream in the exact shape journalctl -o json emits (one object per
# line, microsecond epoch timestamps, string PRIORITY, arrays for binary fields).
JFIX="$TMP/journal.jsonl"
cat > "$JFIX" <<'JSONL'
{"__REALTIME_TIMESTAMP":"1762923001000000","PRIORITY":"3","_SYSTEMD_UNIT":"nginx.service","MESSAGE":"upstream timed out while reading response header"}
{"__REALTIME_TIMESTAMP":"1762923002000000","PRIORITY":"4","_SYSTEMD_UNIT":"systemd","MESSAGE":"Some unit is deprecated"}
{"__REALTIME_TIMESTAMP":"1762923003000000","PRIORITY":"6","SYSLOG_IDENTIFIER":"kernel","MESSAGE":"eth0 link up"}
{"__REALTIME_TIMESTAMP":"1762923004000000","PRIORITY":"6","_SYSTEMD_UNIT":"cron.service","MESSAGE":["multi","line"]}
{"__REALTIME_TIMESTAMP":"1762923005000000","PRIORITY":"6","_SYSTEMD_UNIT":"sshd.service","MESSAGE":"Accepted publickey for root"}
JSONL

FROOT="$TMP/fixtures"
mkdir -p "$FROOT/sub/deeper"
printf 'Nov 12 06:30:01 host sshd[123]: error: failed login\nNov 12 06:30:02 host cron[9]: (root) CMD ok\n' > "$FROOT/sub/app.log"
cat > "$FROOT/sub/deeper/iso.log" <<'LOG'
2026-11-12T06:31:00Z warn: something is deprecated
2026-11-12T06:31:05Z FATAL: disk controller panic
plain line with no timestamp at all
LOG
printf 'not a log file\n' > "$FROOT/sub/notes.txt"
ZEROS="$FROOT/sub/deeper/empty.log"
: > "$ZEROS"

export SX_LOGS_JOURNAL_FIXTURE="$JFIX"
export SX_LOGS_EXTRA_ROOT="$FROOT"

jq_() { # jq_ <desc> <python-expression using d> <json>
    printf '%s' "$3" > "$TMP/_j.json"
    if python3 - "$TMP/_j.json" "$2" <<'PY' 2>/dev/null
import json, sys
d = json.load(open(sys.argv[1]))
assert eval(sys.argv[2], {"d": d}), sys.argv[2]
PY
    then pass "$1"; else fail "$1"; fi
}

# ---------------------------------------------------------------- build
section "build"
if [ ! -x "$BIN" ]; then
    echo "  building native binary..."
    cc -O2 -std=c99 -Wall -Wextra -I src -o "$BIN" src/plugin_logs.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 logs"          '"name":"logs"'           "$META"
check      "meta emits desc Log viewer"    '"desc":"Log viewer"'     "$META"
METAENV=$(SX_PLUGIN_META=1 "$BIN")
check      "SX_PLUGIN_META=1 yields same meta" '"name":"logs"'       "$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 2 ] && pass "name is at most two words" || fail "name has too many words"
check      "--version prints version"      '1.0.0'                  "$("$BIN" --version)"
check      "--help is available"           'usage:'                 "$("$BIN" --help)"
META_AUTH=$(BOT_PASSWORD=secret "$BIN" --meta)
check      "meta still works when BOT_PASSWORD is set" '"name":"logs"' "$META_AUTH"

# ---------------------------------------------------------------- auth
section "node auth"
AUTHNONE=$(BOT_PASSWORD=testpw QUERY_STRING='action=sources' "$BIN")
check      "no credentials -> 401"          'Status: 401'            "$AUTHNONE"
check      "401 body is json"               'invalid node password'  "$AUTHNONE"
AUTHH=$(body "$(BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw QUERY_STRING='action=sources' "$BIN")")
check      "X-Bot-Password accepted"        '"ok":true'              "$AUTHH"
AUTHB=$(body "$(BOT_PASSWORD=testpw HTTP_AUTHORIZATION='Bearer testpw' QUERY_STRING='action=sources' "$BIN")")
check      "Authorization Bearer accepted"  '"ok":true'              "$AUTHB"
AUTHQ=$(body "$(BOT_PASSWORD=testpw QUERY_STRING='action=sources&pwd=testpw' "$BIN")")
check      "?pwd= accepted (plugin iframe)" '"ok":true'              "$AUTHQ"
AUTHBAD=$(BOT_PASSWORD=testpw QUERY_STRING='action=sources&pwd=wrong' "$BIN")
check      "wrong ?pwd= -> 401"             'Status: 401'            "$AUTHBAD"
META_NOAUTH=$(BOT_PASSWORD=testpw "$BIN" --meta)
check      "--meta is never gated by auth"  '"name":"logs"'          "$META_NOAUTH"

# ---------------------------------------------------------------- sources
section "mode 2 action=sources"
SRCJSON=$(body "$(QUERY_STRING='action=sources' "$BIN")")
check      "sources ok:true"                '"ok":true'              "$SRCJSON"
check      "sources echoes the action"      '"action":"sources"'     "$SRCJSON"
check      "sources reports journal availability" '"journal_available":' "$SRCJSON"
check      "sources carries the plugin id"  '"plugin":"plugin_logs"' "$SRCJSON"
check      "sources reports truncation flag" '"truncated":'          "$SRCJSON"
check      "fixture log listed"             "file:$FROOT/sub/app.log" "$SRCJSON"
check      "nested fixture log listed"      "deeper/iso.log"         "$SRCJSON"
check_not  "non-.log fixture is not listed" "notes.txt"              "$SRCJSON"
jq_ 'sources has one entry per listed item' 'd["count"] == len(d["sources"])' "$SRCJSON"
jq_ 'every source has id/label/kind' 'all(s.get("id") and s.get("label") and s.get("kind") for s in d["sources"])' "$SRCJSON"
jq_ 'file sources carry a positive size' 'all(s["size"] > 0 for s in d["sources"] if s["kind"] == "file")' "$SRCJSON"
jq_ 'every source path is inside an allowlisted root' 'all((s["id"].startswith("file:/var/log/") or s["id"].startswith("file:/workspace/") or s["id"].startswith("file:" + __import__("os").environ["HOME"] + "/.scorpiox/") or s["id"].startswith("file:'"$FROOT"'/") or s["id"] in ("journal",) or s["id"].startswith("event:")) for s in d["sources"])' "$SRCJSON"

# ---------------------------------------------------------------- tail (journal)
section "mode 2 action=tail (journal fixture)"
JT=$(body "$(QUERY_STRING='action=tail&src=journal&lines=10' "$BIN")")
check      "journal tail ok:true"           '"ok":true'              "$JT"
check      "journal tail echoes src"        '"src":"journal"'        "$JT"
check      "journal tail kind journal"      '"kind":"journal"'       "$JT"
check      "journal severity err from PRIORITY=3" '"sev":"err"'      "$JT"
check      "journal severity warn from PRIORITY=4" '"sev":"warn"'    "$JT"
check      "journal unit extracted"         '"unit":"nginx.service"' "$JT"
check      "journal message extracted"      'upstream timed out'     "$JT"
check      "binary MESSAGE rendered as a placeholder" '"(binary)"'   "$JT"
check      "SYSLOG_IDENTIFIER used when no unit" '"unit":"kernel"'   "$JT"
jq_ 'journal tail returns exactly the fixture entries' 'd["count"] == 5 and len(d["entries"]) == 5' "$JT"
jq_ 'journal timestamps are formatted' 'all(len(e["ts"]) >= 8 for e in d["entries"])' "$JT"
jq_ 'journal severities are one of info/warn/err' 'all(e["sev"] in ("info","warn","err") for e in d["entries"])' "$JT"
jq_ 'journal text is never empty' 'all(e["text"] != "" for e in d["entries"])' "$JT"

J1=$(body "$(QUERY_STRING='action=tail&src=journal&lines=1' "$BIN")")
jq_ 'lines=1 limits the fixture window to one entry' 'd["count"] >= 1 and d["requested"] == 1' "$J1"
JBIG=$(body "$(QUERY_STRING='action=tail&src=journal&lines=999999' "$BIN")")
check      "absurd lines still answers ok"  '"ok":true'              "$JBIG"
check      "absurd lines is capped"         '"requested":2000'       "$JBIG"
JZERO=$(body "$(QUERY_STRING='action=tail&src=journal&lines=0' "$BIN")")
check      "lines=0 falls back to the default" '"requested":200'     "$JZERO"

# ---------------------------------------------------------------- tail (file)
section "mode 2 action=tail (log file)"
FSRC="file:$FROOT/sub/app.log"
FT=$(body "$(QUERY_STRING="action=tail&src=$FSRC&lines=10" "$BIN")")
check      "file tail ok:true"              '"ok":true'              "$FT"
check      "file tail kind file"            '"kind":"file"'          "$FT"
check      "syslog timestamp parsed"        '"ts":"Nov 12 06:30:01"' "$FT"
check      "syslog unit parsed"             '"unit":"sshd[123]"'     "$FT"
check      "syslog message parsed"          'error: failed login'    "$FT"
check      "error line is severity err"     '"sev":"err"'            "$FT"
jq_ 'file tail returns every fixture line' 'd["count"] == 2'         "$FT"

ISRC="file:$FROOT/sub/deeper/iso.log"
IT=$(body "$(QUERY_STRING="action=tail&src=$ISRC&lines=10" "$BIN")")
check      "ISO-8601 timestamp parsed"      '"ts":"2026-11-12T06:31:00Z"' "$IT"
check      "FATAL line is severity err"     'disk controller panic' "$IT"
check      "plain line still has text"      'plain line with no timestamp' "$IT"
jq_ 'plain line carries no timestamp' 'any(e["ts"] == "" for e in d["entries"])' "$IT"

ESRC="file:$FROOT/sub/deeper/empty.log"
ET=$(body "$(QUERY_STRING="action=tail&src=$ESRC&lines=5" "$BIN")")
check      "empty file answers ok (or is simply not listed)" '"ok":' "$ET"

# ---------------------------------------------------------------- search
section "mode 2 action=search"
ST=$(body "$(QUERY_STRING="action=search&src=$FSRC&q=FAILED" "$BIN")")
check      "search is case-insensitive"     'error: failed login'    "$ST"
check      "search echoes the query"        '"q":"FAILED"'           "$ST"
check      "search reports scanned count"   '"scanned":'             "$ST"
jq_ 'case-insensitive search finds exactly the failing line' 'd["count"] == 1' "$ST"
jq_ 'search response carries hit objects' 'all("ts" in h and "sev" in h and "text" in h for h in d["hits"])' "$ST"

SMISS=$(body "$(QUERY_STRING="action=search&src=$FSRC&q=zzzznotthere" "$BIN")")
jq_ 'a query with no match returns zero hits' 'd["ok"] is True and d["count"] == 0' "$SMISS"
check      "no-match is not an error"       '"ok":true'              "$SMISS"

JS=$(body "$(QUERY_STRING='action=search&src=journal&q=deprecated' "$BIN")")
jq_ 'journal search filters the fixture' 'd["count"] == 1 and d["scanned"] == 5' "$JS"
check      "journal search keeps severity"  '"sev":"warn"'           "$JS"

NOQ=$(body "$(QUERY_STRING="action=search&src=$FSRC" "$BIN")")
check      "search without q is rejected"   'missing_query'          "$NOQ"

# ---------------------------------------------------------------- refusals
section "mode 2 refusals (read allowlist)"
for bad in 'file:/etc/passwd' 'file:/etc/shadow' 'file:/proc/self/environ' \
           '../../../../etc/passwd' 'journal:../../etc' 'file:' ''; do
    R=$(body "$(QUERY_STRING="action=tail&src=$bad&lines=5" "$BIN")")
    if printf '%s' "$R" | grep -F -q 'source_not_allowed' || printf '%s' "$R" | grep -F -q 'source_unavailable'; then
        pass "refused: ${bad:-<empty>}"
    else
        fail "should have refused: ${bad:-<empty>}"
        printf '       got: %s\n' "$(printf '%s' "$R" | head -c 200)"
    fi
done
R=$(body "$(QUERY_STRING='action=tail&src=file:/workspace' "$BIN")")
check_not  "a directory is never opened as a log" '"ok":true'        "$R"
RU=$(body "$(QUERY_STRING='action=tail&src=journal:--help' "$BIN")")
check_not  "a unit name starting with '-' is refused" '"ok":true'    "$RU"
RU2=$(body "$(QUERY_STRING='action=tail&src=journal:nginx.service;rm -rf /' "$BIN")")
check_not  "a unit name with shell text is refused" '"ok":true'      "$RU2"

UNK=$(body "$(QUERY_STRING='action=bogus' "$BIN")")
check      "unknown action rejected"        'unknown_action'         "$UNK"
check      "unknown action lists supported" '"supported":["sources","tail","search","units","info"]' "$UNK"
check      "unknown action echoes request"  '"requested":"bogus"'    "$UNK"

# ---------------------------------------------------------------- units / info
section "mode 2 action=units and action=info"
UNITS=$(body "$(QUERY_STRING='action=units' "$BIN")")
check      "units ok:true"                  '"ok":true'              "$UNITS"
check      "units reports availability"     '"available":'           "$UNITS"
jq_ 'units count matches the array' 'd["count"] == len(d["units"])'  "$UNITS"
jq_ 'every unit offers a journal:<name> src' 'all(u["src"].startswith("journal:") for u in d["units"])' "$UNITS"

INFO=$(body "$(QUERY_STRING='action=info' "$BIN")")
check      "info ok:true"                   '"ok":true'              "$INFO"
check      "info action info"               '"action":"info"'        "$INFO"
check      "info declares zero network"     '"zero_network":true'    "$INFO"
check      "info declares read-only"        '"read_only":true'       "$INFO"
check      "info node_auth false when unset" '"node_auth":false'     "$INFO"
check      "info publishes the line cap"    '"lines_max":2000'       "$INFO"
check      "info publishes the hit cap"     '"search_hits_max":500'  "$INFO"
INFOAUTH=$(body "$(BOT_PASSWORD=pw QUERY_STRING='action=info&pwd=pw' "$BIN")")
check      "info node_auth true when set"   '"node_auth":true'       "$INFOAUTH"
printf '%s' "$INFO" | python3 -c 'import json,sys; json.load(sys.stdin)' 2>/dev/null \
    && pass "info body is valid JSON" || fail "info body JSON invalid"
check      "format=json works as an alias"  '"ok":true'              "$(body "$(QUERY_STRING='format=json&action=info' "$BIN")")"

# ---------------------------------------------------------------- html
section "mode 3 HTML"
HTML=$(QUERY_STRING='' "$BIN")
check      "html content-type"              'Content-Type: text/html; charset=utf-8' "$HTML"
check_not  "html has no Content-Length"     'Content-Length'         "$HTML"
check      "html has viewport meta"         'width=device-width'     "$HTML"
check      "html title logs"                '<title>logs</title>'    "$HTML"
check      "html back-link present"         'Back to Bot'            "$HTML"
check      "html theme switch hook"         'bot_theme'              "$HTML"
check      "html source picker present"     "id='srcSel'"            "$HTML"
check      "html log viewport present"      "id='log'"               "$HTML"
check      "html search input present"      "id='q'"                 "$HTML"
check      "html follow toggle present"     "id='btnFollow'"         "$HTML"
check      "html wrap toggle present"       "id='btnWrap'"           "$HTML"
check      "html copy button present"       "id='btnCopy'"           "$HTML"
check      "html line-count segmented control" 'data-n='             "$HTML"
check      "html calls action=sources"      'action=sources'         "$HTML"
check      "html calls action=tail"         'action=tail'            "$HTML"
check      "html calls action=search"       'action=search'          "$HTML"
check      "html uses /plugins?plugin= route" "/plugins?plugin="     "$HTML"
check      "html falls back to /plugin_logs" "/plugin_logs"          "$HTML"
check      "html highlights matches with mark" "'mark'"              "$HTML"
check      "html polls every 3s when following" '3000'               "$HTML"
check      "html pauses when the tab is hidden" 'visibilitychange'   "$HTML"
check      "html closes document"           '</html>'                "$HTML"
check      "html declares read-only local read" 'read-only'          "$HTML"

# ---- theme handoff (bot_theme_plugin.h) ----
check      "html reads ?theme= before paint"  'theme=(light|dark)'           "$HTML"
check      "html has the sx-theme listener"   "type==='sx-theme'"            "$HTML"
check      "html asks the host for its theme" 'sx-theme-request'             "$HTML"
check      "html uses the shared bot_theme key" "localStorage.getItem('bot_theme')" "$HTML"
check      "html carries bot theme tokens"    '--bg-card'                    "$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"

EMB=$(QUERY_STRING='embed=1' "$BIN")
check_not  "embed=1 strips the back-link"   'Back to Bot'           "$EMB"
check      "embed=1 still renders the UI"   "id='log'"              "$EMB"
EMBT=$(QUERY_STRING='embed=true' "$BIN")
check_not  "embed=true also strips back-link" 'Back to Bot'         "$EMBT"

ZEROEMOJI=$(printf '%s' "$HTML" | python3 -c '
import sys
s = sys.stdin.read()
bad = [c for c in s if ord(c) > 0x2600 and ord(c) not in (0x2014, 0x2013, 0x2026)]
print(len(bad))
')
[ "$ZEROEMOJI" = "0" ] && pass "HTML contains no emoji glyphs" || fail "HTML has $ZEROEMOJI emoji glyph(s)"

check_not  "html has no <script src=>"      '<script src='          "$HTML"
check_not  "html has no CDN reference"      'cdnjs'                 "$HTML"
check_not  "html has no external font"      'fonts.googleapis'      "$HTML"
PK="pico""bot"
check_not  "html has no internal fleet paths" "$PK"                 "$HTML"
check_not  "html has no private IPs"        "192.168."              "$HTML"
check_not  "html has no ssh/sshpass"        "sshpass"               "$HTML"

section "responsive markup"
check      "html has a 760px breakpoint"    '@media(max-width:760px)' "$HTML"
check      "html has a 480px breakpoint"    '@media(max-width:480px)' "$HTML"
check      "html hides the unit column on mobile" 'ln .un{display:none}' "$HTML"
check      "html scrolls the log viewport"  'overflow:auto'          "$HTML"

# ---------------------------------------------------------------- source audit
section "no sockets, no user-controlled shell"
SRCCAT=$(cat src/plugin_logs.c)
check_not "source opens no sockets"         'socket('                "$SRCCAT"
check_not "source has no curl or wget"      'wget'                   "$SRCCAT"
check_not "source has no ssh invocation"    'ssh '                   "$SRCCAT"
check_not "source has no sshpass"           'sshpass'                "$SRCCAT"
check_not "source never calls system()"     'system('                "$SRCCAT"
check      "journal argv is built with snprintf" 'journalctl -o json --no-pager' "$SRCCAT"
check      "macOS log is called by absolute path" '/usr/bin/log show --style compact' "$SRCCAT"
check      "wevtutil argv names the channel"  'wevtutil qe %s /c:%d /rd:true /f:text' "$SRCCAT"
# the journal kind means journalctl on Linux and `log show` on macOS, so the
# platform branch must come BEFORE the generic kind check in both collectors
check      "platform branch precedes the journalctl branch" \
           'if defined(__APPLE__)
    if (strcmp(s->kind, "journal") == 0)' "$(printf '%s' "$SRCCAT" | sed -n '/static int collect_tail/,/^}/p')"
check      "search collector dispatches by platform too" \
           '/usr/bin/log show' "$SRCCAT"
check      "unit names are validated"        'valid_unit'            "$SRCCAT"
check      "files are opened read-only"      '"rb"'                  "$SRCCAT"
check      "tail reads are bounded"          'FILE_TAIL_BYTES'       "$SRCCAT"
check      "walks have a per-root budget"    'ROOT_BUDGET'           "$SRCCAT"
check      "symlinks are never followed"     'S_ISLNK'               "$SRCCAT"

# ---------------------------------------------------------------- optional targets
section "optional cross builds"
if [ -f plugin_logs.musl ]; then
    M=$(./plugin_logs.musl --meta)
    check  "musl build --meta"              '"name":"logs"'          "$M"
    case $(head -c 4 plugin_logs.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_logs.arm64 ]; then
    case $(head -c 20 plugin_logs.arm64 | od -An -tx1 | tr -d ' \n') in
        7f454c46*e500b700*|7f454c46*b700*) pass "arm64 artifact is an aarch64 ELF" ;;
        7f454c46*) 
            if od -An -tx1 -j18 -N2 plugin_logs.arm64 | tr -d ' \n' | grep -q 'b7'; then
                pass "arm64 artifact is an aarch64 ELF"
            else
                fail "arm64 artifact is not aarch64"
            fi ;;
        *) fail "arm64 artifact is not ELF" ;;
    esac
else
    echo "  skip arm64 (not built)"
fi
if [ -f plugin_logs.exe ]; then
    MAGIC=$(head -c 2 plugin_logs.exe)
    [ "$MAGIC" = "MZ" ] && pass "windows artifact has MZ header" || fail "windows artifact missing MZ"
    SZ=$(wc -c < plugin_logs.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
if [ -f plugin_logs.macos-arm64 ]; then
    case $(head -c 4 plugin_logs.macos-arm64 | od -An -tx1 | tr -d ' \n') in
        cffaedfe|cefaedfe) pass "macos-arm64 artifact is Mach-O" ;;
        *) fail "macos-arm64 artifact is not Mach-O" ;;
    esac
else
    echo "  skip macos-arm64 (not built)"
fi
if [ -f plugin_logs.macos-x86_64 ]; then
    case $(head -c 4 plugin_logs.macos-x86_64 | od -An -tx1 | tr -d ' \n') in
        cffaedfe|cefaedfe) pass "macos-x86_64 artifact is Mach-O" ;;
        *) fail "macos-x86_64 artifact is not Mach-O" ;;
    esac
else
    echo "  skip macos-x86_64 (not built)"
fi

# ---------------------------------------------------------------- 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. Detector literals are also assembled from fragments below.
    git log -p --all 2>/dev/null \
      | grep -v '^Author: ' \
      | grep -vE 'audit "|HITS=|grep -E|scan "' \
      > "$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,}'
    PK2="pico""bot"; WT=".work""trees"
    audit "fleet path"           "/codebases/${PK2}|${WT}/"
    audit "internal hostname"    'intel-ultra''2|macmini''2018i5|laza''rus'
else
    echo "  skip history audit (not a git checkout)"
fi

# ---------------------------------------------------------------- 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: FAILED%s\n' "$C_BAD" "$C_0"
    exit 1
fi
printf '  %sRESULT: ALL PASSED%s\n' "$C_OK" "$C_0"
exit 0
