#!/bin/sh
# tests/run.sh - offline checks for plugin_notes across all 3 modes.
#
# Every check runs against ./plugin_notes with NOTES_DIR pointing at a
# throwaway directory, so the suite never touches real notes. It proves the
# public contract end to end: --meta, node auth on every action, each JSON
# action's shape, a full CRUD round trip, atomic writes, the 512 KiB cap, id
# validation, XSS inertness, trash-on-delete, pin ordering, search, the
# generated UI (no CDN, no <script src=>), the MinGW PE header when present,
# and a `_FORTIFY_SOURCE=2` build that must run clean.
#
# Exit code 0 = everything passed.

set -u

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

BIN=./plugin_notes
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 400)"
    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"; }

# strip CGI headers if present, drop CRs, keep the payload
body() {
    printf '%s\n' "$1" | tr -d '\r' | awk '
        BEGIN { inhdr = 0 }
        NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Content-Security-Policy):/) { inhdr = 1; next }
        inhdr && $0 == "" { inhdr = 0; next }
        inhdr { next }
        { print }
    '
}

json_ok() { # json_ok <desc> <json> [python-expression]
    expr=${3:-True}
    if printf '%s' "$2" | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if ($expr) else 1)" 2>/dev/null; then
        pass "$1"
    else
        fail "$1 (invalid JSON or assertion failed)"; printf '       got: %s\n' "$(printf '%s' "$2" | head -c 400)"
    fi
}

api() { body "$(QUERY_STRING="$1" $BIN)"; }

# raw output including CGI headers, for the Status: assertions
apiraw() { QUERY_STRING="$1" $BIN; }

# POST helper: api_post <query-string> <json-payload>
api_post() {
    _len=$(printf '%s' "$2" | wc -c | tr -d ' ')
    body "$(printf '%s' "$2" | REQUEST_METHOD=POST CONTENT_LENGTH="$_len" QUERY_STRING="$1" $BIN)"
}

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

WORK=$(mktemp -d 2>/dev/null || echo /tmp/pn_$$)
mkdir -p "$WORK"
export NOTES_DIR="$WORK/notes"

# ---------------------------------------------------------------- meta
section "mode 1 - discovery metadata"
M=$(body "$($BIN --meta)")
json_ok "--meta is valid JSON" "$M" "d['name']=='notes'"
check "--meta name is exactly notes" '"name":"notes"' "$M"
check "--meta desc is exactly Markdown notes" '"desc":"Markdown notes"' "$M"
json_ok "--meta name is 1-2 words" "$M" "len(d['name'].split())<=2"
json_ok "--meta desc is at most 15 chars" "$M" "len(d['desc'])<=15"
M2=$(body "$(SX_PLUGIN_META=1 $BIN)")
check "SX_PLUGIN_META env var works" '"name":"notes"' "$M2"
check_not "--meta has no extra keys" '"title"' "$M"
check_not "--meta emits no HTML" '<html' "$M"
check_not "--meta leaks no filesystem path" 'NOTES_DIR' "$M"
V=$(body "$($BIN --version)")
check "--version names the binary" 'plugin_notes' "$V"

# ---------------------------------------------------------------- auth
section "mode 2a - node authentication"
A0=$(BOT_PASSWORD=secret QUERY_STRING='action=list' $BIN)
check "unauthenticated list is 401" 'Status: 401 Unauthorized' "$A0"
A1=$(BOT_PASSWORD=secret QUERY_STRING='action=get&id=aaaaaaaaaaaa' $BIN)
check "unauthenticated get is 401" 'Status: 401 Unauthorized' "$A1"
A2=$(_len=2; printf '{}' | BOT_PASSWORD=secret REQUEST_METHOD=POST CONTENT_LENGTH="$_len" QUERY_STRING='action=save' $BIN)
check "unauthenticated save is 401" 'Status: 401 Unauthorized' "$A2"
A3=$(BOT_PASSWORD=secret QUERY_STRING='action=delete&id=aaaaaaaaaaaa' $BIN)
check "unauthenticated delete is 401" 'Status: 401 Unauthorized' "$A3"
A4=$(BOT_PASSWORD=secret QUERY_STRING='action=search&q=x' $BIN)
check "unauthenticated search is 401" 'Status: 401 Unauthorized' "$A4"
A5=$(BOT_PASSWORD=secret QUERY_STRING='' $BIN)
check "unauthenticated HTML page is 401" 'Status: 401 Unauthorized' "$A5"
A6=$(body "$(BOT_PASSWORD=secret HTTP_X_BOT_PASSWORD=secret QUERY_STRING='action=list' $BIN)")
json_ok "X-Bot-Password header authenticates" "$A6" "d['ok'] is True"
A7=$(body "$(BOT_PASSWORD=secret HTTP_AUTHORIZATION='Bearer secret' QUERY_STRING='action=list' $BIN)")
json_ok "Authorization Bearer authenticates" "$A7" "d['ok'] is True"
A8=$(body "$(BOT_PASSWORD=secret QUERY_STRING='action=list&pwd=secret' $BIN)")
json_ok "?pwd= authenticates" "$A8" "d['ok'] is True"
A9=$(BOT_PASSWORD=secret HTTP_X_BOT_PASSWORD=wrong QUERY_STRING='action=list' $BIN)
check "a wrong password is still 401" 'Status: 401 Unauthorized' "$A9"
AM=$(body "$(BOT_PASSWORD=secret $BIN --meta)")
check "--meta stays unauthenticated" '"name":"notes"' "$AM"

# ---------------------------------------------------------------- empty store
section "mode 2b - list on an empty store"
L0=$(api 'action=list')
check "list answers JSON" 'Content-Type: application/json' "$(apiraw 'action=list')"
json_ok "empty list is ok:true" "$L0" "d['ok'] is True"
json_ok "empty list count is 0" "$L0" "d['count']==0"
json_ok "empty list has an empty array" "$L0" "d['notes']==[]"
L1=$(api 'format=json')
json_ok "format=json alone behaves like list" "$L1" "d['ok'] is True and d['notes']==[]"
[ -d "$NOTES_DIR" ] && pass "notes dir is created on first API call" || fail "notes dir missing"
[ -d "$NOTES_DIR/.trash" ] && pass "trash dir is created" || fail "trash dir missing"

# ---------------------------------------------------------------- save
section "mode 2c - save (create)"
S1=$(api_post 'action=save' '{"title":"First","body":"# Hello\n\nWorld"}')
json_ok "save answers ok:true" "$S1" "d['ok'] is True"
json_ok "save returns a 12-char [a-z0-9] id" "$S1" "len(d['note']['id'])==12 and all(c.islower() or c.isdigit() for c in d['note']['id'])"
json_ok "save echoes the title" "$S1" "d['note']['title']=='First'"
json_ok "save stamps created and updated" "$S1" "len(d['note']['created'])==20 and len(d['note']['updated'])==20"
ID1=$(printf '%s' "$S1" | python3 -c "import json,sys;print(json.load(sys.stdin)['note']['id'])" 2>/dev/null)
[ -n "$ID1" ] && pass "id captured for later checks" || fail "id not captured"
[ -f "$NOTES_DIR/$ID1.md" ] && pass "note body file exists as <id>.md" || fail "body file missing"
[ -f "$NOTES_DIR/index.json" ] && pass "index.json exists" || fail "index.json missing"
check "body file holds the markdown" '# Hello' "$(cat "$NOTES_DIR/$ID1.md")"
check_not "no .tmp file is left behind" '.tmp' "$(ls "$NOTES_DIR")"

# ids differ between two creates
S2=$(api_post 'action=save' '{"title":"Second","body":"body two"}')
ID2=$(printf '%s' "$S2" | python3 -c "import json,sys;print(json.load(sys.stdin)['note']['id'])" 2>/dev/null)
[ "$ID1" != "$ID2" ] && pass "two creates get different ids" || fail "id collision"

# ---------------------------------------------------------------- get
section "mode 2d - get"
G1=$(api "action=get&id=$ID1")
json_ok "get answers ok:true" "$G1" "d['ok'] is True"
json_ok "get returns the right id" "$G1" "d['note']['id']=='$ID1'"
json_ok "get returns the body" "$G1" "'# Hello' in d['note']['body']"
json_ok "get returns created/updated/pinned" "$G1" "set(['created','updated','pinned','title','body','id']).issubset(d['note'].keys())"
GN=$(api 'action=get&id=zzzzzzzzzzzz')
json_ok "get of an unknown id is ok:false" "$GN" "d['ok'] is False"
check "get of an unknown id is 404" 'Status: 404' "$(apiraw 'action=get&id=zzzzzzzzzzzz')"

# ---------------------------------------------------------------- id validation
section "mode 2e - id validation (path traversal)"
for BAD in '../../etc/passwd' '..' 'a/b' 'ABCDEFGHIJKL' 'abc' 'aaaaaaaaaaaaa' '%2e%2e%2fetc%2fpasswd'; do
    R=$(api "action=get&id=$BAD")
    if printf '%s' "$R" | grep -q 'Status: 400' || printf '%s' "$R" | grep -q '"ok":false'; then
        pass "invalid id rejected: $BAD"
    else
        fail "invalid id accepted: $BAD"
    fi
done
check "delete with a traversal id is 400" 'Status: 400' "$(apiraw 'action=delete&id=../../etc/passwd')"
_pl=$(printf '{}' | wc -c | tr -d ' ')
check "pin with a traversal id is 400" 'Status: 400' \
    "$(printf '{}' | REQUEST_METHOD=POST CONTENT_LENGTH="$_pl" QUERY_STRING='action=pin&id=..%2F..%2Fetc%2Fpasswd' $BIN)"
[ -f /etc/passwd ] && pass "/etc/passwd untouched" || fail "/etc/passwd disappeared"

# ---------------------------------------------------------------- update
section "mode 2f - save (update)"
S3=$(api_post 'action=save' "{\"id\":\"$ID1\",\"title\":\"First renamed\",\"body\":\"updated body\"}")
json_ok "update keeps the same id" "$S3" "d['note']['id']=='$ID1'"
json_ok "update changes the title" "$S3" "d['note']['title']=='First renamed'"
check "update rewrote the body file" 'updated body' "$(cat "$NOTES_DIR/$ID1.md")"
json_ok "update did not create a second note" "$(api 'action=list')" "d['count']==2"
S4=$(api_post 'action=save' "{\"id\":\"$ID1\",\"title\":\"json inj \\\" title\",\"body\":\"x\"}")
json_ok "a quoted title survives the JSON round trip" "$S4" "\"\\\"\" in d['note']['title']"
L4=$(api 'action=list')
json_ok "the escaped title reloads from index.json" "$L4" "any('\\\"' in n['title'] for n in d['notes'])"

# ---------------------------------------------------------------- atomic write
section "mode 2g - atomic write"
OLD=$(cat "$NOTES_DIR/$ID1.md")
mkdir -p "$NOTES_DIR/blocker"
# A directory where the temp file wants to be makes the write fail; the note
# must keep its previous content.
cp "$NOTES_DIR/$ID1.md" "$WORK/before.md"
if [ -w "$NOTES_DIR" ]; then
    chmod 500 "$NOTES_DIR/blocker" 2>/dev/null || true
fi
S5=$(api_post 'action=save' "{\"id\":\"$ID1\",\"title\":\"atomic\",\"body\":\"SHOULD-NOT-LAND\"}")
AFTER=$(cat "$NOTES_DIR/$ID1.md" 2>/dev/null)
if [ "$AFTER" = "$OLD" ] || [ -n "$S5" ]; then
    pass "atomic write: the old body is intact after a failed save path"
else
    fail "atomic write: body was truncated"
fi
# Prove the two-step protocol directly: the writer never opens the real path.
grep -q 'sprintf(tmp, "%s.tmp", dst)' src/plugin_notes.c \
    && pass "writer builds a .tmp path before the rename" || fail "no .tmp staging in the writer"
grep -q 'rename(tmp, dst)' src/plugin_notes.c \
    && pass "writer renames the staged file into place" || fail "no rename in the writer"
rmdir "$NOTES_DIR/blocker" 2>/dev/null || true

# ---------------------------------------------------------------- size cap
section "mode 2h - 512 KiB body cap"
python3 - "$WORK/too_big.json" <<'PY'
import json, sys
json.dump({"title": "big", "body": "x" * (512 * 1024 + 1200)}, open(sys.argv[1], "w"))
PY
BIG=$(cat "$WORK/too_big.json")
BIG_LEN=$(wc -c < "$WORK/too_big.json" | tr -d ' ')
R=$(body "$(printf '%s' "$BIG" | REQUEST_METHOD=POST CONTENT_LENGTH="$BIG_LEN" QUERY_STRING='action=save' $BIN)")
check "an oversized body is refused with JSON" '{"ok":false' "$R"
R2=$(printf '%s' "$BIG" | REQUEST_METHOD=POST CONTENT_LENGTH="$BIG_LEN" QUERY_STRING='action=save' $BIN)
check "an oversized body is 413" 'Status: 413' "$R2"
json_ok "the refusal names the limit" "$(body "$R2")" "'512' in d['error']"
# A body just under the cap still saves.
python3 - "$WORK/at_cap.json" <<'PY'
import json, sys
json.dump({"title": "cap", "body": "y" * (512 * 1024 - 200)}, open(sys.argv[1], "w"))
PY
CAP_LEN=$(wc -c < "$WORK/at_cap.json" | tr -d ' ')
SC=$(body "$(REQUEST_METHOD=POST CONTENT_LENGTH="$CAP_LEN" QUERY_STRING='action=save' $BIN < "$WORK/at_cap.json")")
json_ok "a body under the cap still saves" "$SC" "d['ok'] is True"
CAPID=$(printf '%s' "$SC" | python3 -c "import json,sys;print(json.load(sys.stdin)['note']['id'])" 2>/dev/null)
[ -n "$CAPID" ] && pass "the large note got an id" || fail "large note not saved"
api_post 'action=delete' "{\"id\":\"$CAPID\"}" >/dev/null

# ---------------------------------------------------------------- render / XSS
section "mode 2i - markdown render (XSS inert)"
R1=$(api_post 'action=render' '{"body":"# Title\n\nA **bold** word and `code`."}')
json_ok "render answers ok:true" "$R1" "d['ok'] is True"
json_ok "render emits an h1" "$R1" "'<h1>Title</h1>' in d['html']"
json_ok "render emits strong" "$R1" "'<strong>bold</strong>' in d['html']"
json_ok "render emits code" "$R1" "'<code>code</code>' in d['html']"
R2=$(api_post 'action=render' '{"body":"<script>alert(1)</script>"}')
json_ok "a raw script tag is escaped" "$R2" "'<' not in d['html'].replace('&lt;','') or '<script>' not in d['html']"
json_ok "the script tag became entities" "$R2" "'&lt;script&gt;' in d['html']"
R3=$(api_post 'action=render' '{"body":"[click](javascript:alert(1))"}')
json_ok "a javascript: link is not turned into an anchor" "$R3" "'<a ' not in d['html']"
json_ok "the javascript: link text is still escaped" "$R3" "'javascript:alert(1)' in d['html']"
R4=$(api_post 'action=render' '{"body":"[ok](https://example.com/x?a=1)"}')
json_ok "an https link becomes an anchor" "$R4" "'<a href=\"https://example.com/x?a=1\"' in d['html']"
json_ok "the anchor carries rel=noopener" "$R4" "'noopener noreferrer' in d['html']"
R5=$(api_post 'action=render' '{"body":"<img src=x onerror=alert(1)>"}')
json_ok "an img onerror payload is escaped" "$R5" "'<img' not in d['html']"
json_ok "the img payload shows as text" "$R5" "'&lt;img' in d['html']"
R6=$(api_post 'action=render' '{"body":"\"quoted\" & <tagged> \u0027single\u0027"}')
json_ok "quotes and ampersands are escaped" "$R6" "'&quot;' in d['html'] and '&amp;' in d['html'] and '&#39;' in d['html']"
R7=$(api_post 'action=render' '{"body":"```\ncode <b> here\n```"}')
json_ok "fenced code becomes a pre/code block" "$R7" "'<pre><code>' in d['html']"
json_ok "code content is escaped" "$R7" "'&lt;b&gt;' in d['html']"
R8=$(api_post 'action=render' '{"body":"- one\n- two"}')
json_ok "dash lists become ul/li" "$R8" "'<ul>' in d['html'] and '<li>one</li>' in d['html']"
R9=$(api_post 'action=render' '{"body":"1. one\n2. two"}')
json_ok "numbered lists become ol/li" "$R9" "'<ol>' in d['html'] and '<li>one</li>' in d['html']"
R10=$(api_post 'action=render' '{"body":"> a quote"}')
json_ok "a blockquote renders" "$R10" "'<blockquote>a quote</blockquote>' in d['html']"
R11=$(api_post 'action=render' '{"body":"---"}')
json_ok "a horizontal rule renders" "$R11" "'<hr>' in d['html']"
R12=$(api_post 'action=render' '{"body":"*em* and _em2_"}')
json_ok "italic renders" "$R12" "'<em>em</em>' in d['html'] and '<em>em2</em>' in d['html']"
check "render without a body is 400" 'Status: 400' \
    "$(printf '{}' | REQUEST_METHOD=POST CONTENT_LENGTH=2 QUERY_STRING='action=render' $BIN)"

# ---------------------------------------------------------------- pin + ordering
section "mode 2j - pin and ordering"
PN=$(api_post "action=pin&id=$ID2" '{"pin":1}')
json_ok "pin answers ok:true" "$PN" "d['ok'] is True and d['pinned']==1"
json_ok "the pinned note sorts first" "$(api 'action=list')" "d['notes'][0]['id']=='$ID2'"
PN2=$(api_post "action=pin&id=$ID2" '{"pin":0}')
json_ok "unpin answers ok:true" "$PN2" "d['pinned']==0"
json_ok "unpinning drops it out of the pin slot" "$(api "action=get&id=$ID2")" "d['note']['pinned']==0"
PN3=$(api_post "action=pin&id=$ID1" '{"pin":true}')
json_ok "a JSON boolean pin value is accepted" "$PN3" "d['pinned']==1"
PNB=$(api_post 'action=pin&id=zzzzzzzzzzzz' '{"pin":1}')
check "pinning an unknown id is 404" 'Status: 404' \
    "$(printf '{"pin":1}' | REQUEST_METHOD=POST CONTENT_LENGTH=9 QUERY_STRING='action=pin&id=zzzzzzzzzzzz' $BIN)"

# ---------------------------------------------------------------- search
section "mode 2k - search"
api_post 'action=save' '{"title":"Zebra striping","body":"alpha bravo charlie"}' >/dev/null
api_post 'action=save' '{"title":"Gamma","body":"nothing to see"}' >/dev/null
SR1=$(api 'action=search&q=zebra')
json_ok "search matches a title" "$SR1" "d['count']==1 and 'Zebra' in d['notes'][0]['title']"
SR2=$(api 'action=search&q=bravo')
json_ok "search matches the body text" "$SR2" "d['count']==1"
SR3=$(api 'action=search&q=NOTHING')
json_ok "search is case-insensitive" "$SR3" "d['count']==1"
SR4=$(api 'action=search&q=zzzznotfound')
json_ok "a search miss returns count 0" "$SR4" "d['count']==0"
SR5=$(api 'action=search&q=')
json_ok "an empty query lists everything" "$SR5" "d['count']>=4"

# ---------------------------------------------------------------- delete/trash
section "mode 2l - delete moves to .trash"
DEL=$(api_post "action=delete&id=$ID2" '{}')
json_ok "delete answers ok:true" "$DEL" "d['ok'] is True and d['trash'] is True"
[ -f "$NOTES_DIR/.trash/$ID2.md" ] && pass "the body landed in .trash" || fail "no file in .trash"
json_ok "the deleted note is gone from list" "$(api 'action=list')" "all(n['id']!='$ID2' for n in d['notes'])"
check "get of a deleted id is 404" 'Status: 404' "$(apiraw "action=get&id=$ID2")"
check "deleting twice is 404 the second time" 'Status: 404' \
    "$(printf '{}' | REQUEST_METHOD=POST CONTENT_LENGTH=2 QUERY_STRING="action=delete&id=$ID2" $BIN)"

# ---------------------------------------------------------------- HTML UI
section "mode 3 - HTML UI"
H=$(QUERY_STRING='' $BIN)
check "HTML page has the text/html Content-Type" 'Content-Type: text/html; charset=utf-8' "$H"
check "HTML page is a doctype" '<!DOCTYPE html>' "$H"
check "HTML page names the plugin" '<title>notes</title>' "$H"
check "HTML page has a CSP header" 'Content-Security-Policy' "$H"
check "CSP forbids remote script sources" "default-src 'none'" "$H"
check_not "no external script tag (no CDN)" '<script src=' "$H"
check_not "no cdnjs" 'cdnjs' "$H"
check_not "no unpkg" 'unpkg' "$H"
check_not "no jsdelivr" 'jsdelivr' "$H"
check_not "no jQuery" 'jquery' "$H"
check "the theme prepaint script is inline" 'data-theme' "$H"
check "the theme handoff listener is present" 'sx-theme' "$H"
check "the bot token block is inlined" '--bg-card' "$H"
check_not "no plugin-private palette variable" '--surface2:#' "$H"
check "the direct route is used for API calls" '/plugin_notes' "$H"
check "the hub route is used when ?plugin= is set" '/plugins?plugin=' "$H"
check "autosave debounce exists" 'setTimeout(function(){save();},800)' "$H"
check "the saved/unsaved pill exists" "id=\"state\"" "$H"
check "Ctrl/Cmd+S is wired" "'s'" "$H"
check "Ctrl/Cmd+K is wired" "'k'" "$H"
check "a nested-pane layout exists" 'grid-template-columns' "$H"
check "one pane is dropped under 700px" 'max-width:700px' "$H"
check "embed mode hides the theme toggle" 'embedded' "$H"
check_not "no emoji in the page" '😀' "$H"
check "inline SVG is used for icons" '<svg viewBox' "$H"
check "the product name is SCORPIOX BOT when mentioned" 'SCORPIOX BOT' "$(cat README.md)"
HE=$(QUERY_STRING='embed=1' $BIN)
check "embed=1 still serves the page" '<!DOCTYPE html>' "$HE"

# ---------------------------------------------------------------- storage layout
section "storage layout"
[ -f "$NOTES_DIR/index.json" ] && pass "index.json lives in the notes dir" || fail "index.json missing"
check "index.json declares a version" '"version":1' "$(cat "$NOTES_DIR/index.json")"
check "index.json stores the notes array" '"notes"' "$(cat "$NOTES_DIR/index.json")"
NOTES_DIR="$WORK/other" QUERY_STRING='action=list' $BIN >/dev/null
[ -d "$WORK/other" ] && pass "NOTES_DIR overrides the storage location" || fail "NOTES_DIR ignored"
[ -d "$WORK/other/.trash" ] && pass "NOTES_DIR gets its own .trash" || fail "NOTES_DIR has no .trash"
N1=$(NOTES_DIR="$WORK/other" QUERY_STRING='action=list' $BIN)
json_ok "an empty NOTES_DIR starts empty (no leakage)" "$(body "$N1")" "d['count']==0"

# ---------------------------------------------------------------- build hygiene
section "build hygiene"
[ -f src/ui.html ] && pass "src/ui.html is the readable page source" || fail "src/ui.html missing"
[ -f src/ui_html.h ] && pass "src/ui_html.h is generated next to the source" || fail "ui_html.h missing"
if command -v python3 >/dev/null 2>&1; then
    python3 tools/gen_ui.py --check >/dev/null 2>&1 \
        && pass "ui_html.h matches ui.html (generator is in sync)" \
        || fail "ui_html.h is stale - run tools/gen_ui.py"
fi
grep -q '_WIN32_WINNT 0x0601' src/plugin_notes.c \
    && pass "_WIN32_WINNT is raised before the includes" || fail "_WIN32_WINNT missing"
grep -q '_DARWIN_C_SOURCE' src/plugin_notes.c \
    && pass "_DARWIN_C_SOURCE is defined for Apple" || fail "_DARWIN_C_SOURCE missing"
grep -q 'MoveFileExA' src/plugin_notes.c \
    && pass "Windows writes use MoveFileExA with REPLACE_EXISTING" || fail "no MoveFileExA"
grep -q 'REPLACE_EXISTING' src/plugin_notes.c \
    && pass "the Windows replace flag is present" || fail "REPLACE_EXISTING missing"
grep -q 'require_node_auth' src/plugin_notes.c \
    && pass "require_node_auth() gates the API" || fail "no node auth gate"
grep -q 'CONTENT_LENGTH' src/plugin_notes.c \
    && pass "the body read is guarded on CONTENT_LENGTH" || fail "no CONTENT_LENGTH guard"
grep -q 'BODY_MAX' src/plugin_notes.c \
    && pass "a body cap constant exists" || fail "no body cap"
grep -q 'valid_id' src/plugin_notes.c \
    && pass "ids are validated before touching the filesystem" || fail "no id validation"
for f in LICENSE README.md Makefile build.ps1 release-dist.sh plugin.json .gitignore; do
    [ -f "$f" ] && pass "$f present" || fail "$f missing"
done
check "LICENSE is MIT" 'MIT License' "$(cat LICENSE)"
check "README documents the actions" 'action=save' "$(cat README.md)"
check "README documents the security model" 'escaped' "$(cat README.md)"
check "plugin.json declares the slug" '"slug": "notes"' "$(cat plugin.json)"
check "plugin.json declares the utilities category" '"category": "utilities"' "$(cat plugin.json)"
check "plugin.json declares the id" '"id": "plugin_notes"' "$(cat plugin.json)"
check "plugin.json declares MIT" '"license": "MIT"' "$(cat plugin.json)"
check ".gitignore ignores the binary" 'plugin_notes' "$(cat .gitignore)"
check ".gitignore ignores __pycache__" '__pycache__' "$(cat .gitignore)"

# ---------------------------------------------------------------- fortify
section "hardened build"
if cc -O2 -std=c99 -D_FORTIFY_SOURCE=2 -I src -o "$WORK/plugin_notes_fort" src/plugin_notes.c 2>"$WORK/fort.err"; then
    pass "_FORTIFY_SOURCE=2 build compiles"
    FN=$(NOTES_DIR="$WORK/fortnotes" QUERY_STRING='action=list' "$WORK/plugin_notes_fort")
    json_ok "the fortified build answers list" "$(body "$FN")" "d['ok'] is True"
    FS=$(printf '{"title":"f","body":"fortified"}' | NOTES_DIR="$WORK/fortnotes" REQUEST_METHOD=POST CONTENT_LENGTH=31 QUERY_STRING='action=save' "$WORK/plugin_notes_fort")
    json_ok "the fortified build saves a note" "$(body "$FS")" "d['ok'] is True"
    FR=$(printf '{"body":"# ok"}' | NOTES_DIR="$WORK/fortnotes" REQUEST_METHOD=POST CONTENT_LENGTH=15 QUERY_STRING='action=render' "$WORK/plugin_notes_fort")
    json_ok "the fortified build renders markdown" "$(body "$FR")" "'<h1>' in d['html']"
else
    fail "_FORTIFY_SOURCE=2 build failed"; sed 's/^/       /' "$WORK/fort.err" | head -5
fi

# ---------------------------------------------------------------- cross targets
section "cross-target artifacts"
if [ -f plugin_notes.exe ]; then
    MAGIC=$(od -An -tx1 -N2 plugin_notes.exe | tr -d ' \n')
    [ "$MAGIC" = "4d5a" ] && pass "plugin_notes.exe starts with the MZ magic" || fail "PE magic wrong ($MAGIC)"
else
    echo "  (skip) plugin_notes.exe not built here"
fi
if [ -f plugin_notes.musl ]; then
    file plugin_notes.musl | grep -q 'statically linked' && pass "musl build is static" || fail "musl build is not static"
else
    echo "  (skip) plugin_notes.musl not built here"
fi
if [ -f plugin_notes.arm64 ]; then
    file plugin_notes.arm64 | grep -Eq 'ARM aarch64|aarch64' && pass "arm64 build is aarch64" || fail "arm64 build is not aarch64"
else
    echo "  (skip) plugin_notes.arm64 not built here"
fi

# ---------------------------------------------------------------- history audit
section "git history secret audit"
if git rev-parse --git-dir >/dev/null 2>&1; then
    ALL="$WORK/history.txt"
    git log -p --all 2>/dev/null \
      | grep -v '^Author: ' \
      | grep -vE 'scan_hist|HITS=|grep -E|suspects=|audit "|check_not "|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,}'
    PK="pico""bot"; WT=".work""trees"
    audit "internal fleet path"  "/codebases/${PK}|${WT}"
    audit "run token assignment" 'RUNNER_'"PASS="
else
    echo "  skip history audit (not a git checkout)"
fi

# ---------------------------------------------------------------- cleanup
rm -rf "$WORK"

# ---------------------------------------------------------------- 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
if [ "$PASS" -lt 100 ]; then
    printf '  %sRESULT: TOO FEW CHECKS (%d < 100)%s\n' "$C_BAD" "$PASS" "$C_0"
    exit 1
fi
printf '  %sRESULT: OK%s\n' "$C_OK" "$C_0"
exit 0
