#!/bin/sh
# tests/run.sh - the offline proof for plugin_websearch.
#
# Everything runs against ./plugin_websearch with the connector state directory
# pointed at a scratch dir and every provider pointed at tests/mockapi.py on
# loopback, so the suite never touches a real search service, never needs a real
# credential, and never depends on the internet.
#
# Sections:
#   --meta      the node's chip contract (1-2 word name, <= 15 char desc,
#               kind/mcp/daemon/menus) and SX_PLUGIN_META=1 agreeing
#   --schema    the tool array is valid JSON, both tools carry an inputSchema
#   --mcp       initialize / notifications/initialized / ping / tools/list /
#               tools/call and the JSON-RPC error shapes
#   requests    every provider is compared against what the mock actually
#               RECEIVED: method, path, query, credential and JSON body
#   errors      a wrong key is the provider's own 401 text, an unreachable host
#               is a clean error, an unknown provider is a tool error
#   config      config.json round-trips at 0600, the environment overrides it,
#               and no response ever contains a key
#   CGI         a missing node password is 401, ?theme=/?embed= are honoured,
#               and the page has no <script src= and no CDN reference
#   source      no popen/system, no credential literal, no LAN address
#
# Exit code 0 = everything passed.

set -u

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

BIN=${BIN:-./plugin_websearch}
WORK=$(mktemp -d "${TMPDIR:-/tmp}/ws-suite.XXXXXX")
PORTFILE="$WORK/port"
LOG="$WORK/req.jsonl"
CFGDIR="$WORK/cfg"
MOCK_PID=""

cleanup() {
    [ -n "$MOCK_PID" ] && kill "$MOCK_PID" 2>/dev/null
    rm -rf "$WORK"
}
trap cleanup EXIT INT TERM

PASS=0
FAIL=0
SKIP=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"; }
skip() { SKIP=$((SKIP + 1)); printf '  --   %s (skipped: %s)\n' "$1" "$2"; }
section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }

check() { # check <label> <expected-substring> <text|file>
    if [ -f "$3" ]; then set -- "$1" "$2" "$(cat "$3")"; fi
    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 <label> <forbidden-substring> <text|file>
    if [ -f "$3" ]; then set -- "$1" "$2" "$(cat "$3")"; fi
    if printf '%s' "${3:-}" | grep -F -q -- "$2"; then
        fail "$1 (must NOT contain: $2)"
        printf '       got: %s\n' "$(printf '%s' "${3:-}" | head -c 300)"
    else pass "$1"; fi
}
json_ok() { # json_ok <label> <json> [python expr over `d`]
    expr=${3:-True}
    printf '%s' "${2:-}" > "$WORK/j.json"
    if python3 -c "import json,sys; d=json.load(open(sys.argv[1])); sys.exit(0 if ($expr) else 1)" \
            "$WORK/j.json" 2>/dev/null; then
        pass "$1"
    else
        fail "$1 (invalid JSON or failed assertion)"
        printf '       got: %s\n' "$(printf '%s' "${2:-}" | head -c 300)"
    fi
}
body() { # strip the CGI header block, keep the payload
    printf '%s\n' "${1:-}" | tr -d '\r' | awk 'p{print} /^$/{p=1}'
}
mcp() { # mcp <json-lines-file> -> stdout
    ( cd "$ROOT" && "$BIN" --mcp < "$1" )
}
call() { # call <id> <tool> <args-json> -> the structuredContent / error line
    printf '{"jsonrpc":"2.0","id":%s,"method":"tools/call","params":{"name":"%s","arguments":%s}}\n' \
        "$1" "$2" "$3" > "$WORK/one.jsonl"
    mcp "$WORK/one.jsonl" | python3 -c '
import json,sys
d=json.loads(sys.stdin.readline())
r=d.get("result") or {}
if r.get("isError"):
    print("ERROR " + json.dumps(r.get("structuredContent") or {}))
else:
    print(json.dumps(r.get("structuredContent") or {}))
'
}
cgi() { # cgi <query> [method] [body] -> full stdout
    qs="$1"; m="${2:-GET}"; data="${3:-}"
    printf '%s' "$data" > "$WORK/in.bin"
    QUERY_STRING="$qs" REQUEST_METHOD="$m" CONTENT_LENGTH="${#data}" \
      BOT_PASSWORD="" SWEBSEARCH_CONFIG_DIR="$CFGDIR" \
      WEBSEARCH_MOCK_BASE="$MOCK" "$BIN" < "$WORK/in.bin"
}

export SWEBSEARCH_CONFIG_DIR="$CFGDIR"
export BRAVE_API_KEY=BRV-TEST-KEY-1
export TAVILY_API_KEY=TVL-TEST-KEY-1
export EXA_API_KEY=EXA-TEST-KEY-1
export PERPLEXITY_API_KEY=PPX-TEST-KEY-1

mkdir -p "$CFGDIR"
rm -f "$LOG"

if [ ! -x "$BIN" ]; then
    echo "plugin_websearch is not built - run make first" >&2
    exit 1
fi

# ------------------------------------------------------------------ mock
python3 tests/mockapi.py --portfile "$PORTFILE" --log "$LOG" 2>"$WORK/mock.err" &
MOCK_PID=$!
i=0
while [ ! -s "$PORTFILE" ] && [ $i -lt 100 ]; do
    i=$((i + 1)); sleep 0.05
done
if [ ! -s "$PORTFILE" ]; then
    echo "the mock server did not start: $(cat "$WORK/mock.err")" >&2
    exit 1
fi
MOCK="http://127.0.0.1:$(cat "$PORTFILE")"
export WEBSEARCH_MOCK_BASE="$MOCK"
export WEBSEARCH_SEARXNG_BASE="$MOCK/searxng"

# ---------------------------------------------------------------- --meta
section "--meta / discovery"
META=$("$BIN" --meta)
json_ok "--meta is one line of valid JSON" "$META"
json_ok "name is websearch"             "$META" 'd["name"]=="websearch"'
json_ok "desc is <= 15 chars"           "$META" 'len(d["desc"])<=15'
json_ok "kind is mcp, mcp true, menus false" \
        "$META" 'd["kind"]=="mcp" and d["mcp"] is True and d["menus"] is False'
json_ok "daemon is false"               "$META" 'd["daemon"] is False'
json_ok "category is network"           "$META" 'd["category"]=="network"'
json_ok "verified is mock (an honest tier: the suite drives a mock, not a paid key)" \
        "$META" 'd["verified"]=="mock"'
check  "SX_PLUGIN_META=1 agrees"        '"name":"websearch"' "$(SX_PLUGIN_META=1 "$BIN")"
json_ok "--meta version agrees with plugin.json" "$META" \
        'd["version"]==__import__("json").load(open("plugin.json"))["version"]'
VER=$(python3 -c 'import json;print(json.load(open("plugin.json"))["version"])')
check  "--version agrees with plugin.json" "$VER" "$("$BIN" --version)"
check  "--help mentions the tool names" 'web_search' "$("$BIN" --help)"

# -------------------------------------------------------------- --schema
section "--schema / --mcp tool list"
SCHEMA=$("$BIN" --schema)
json_ok "--schema is valid JSON" "$SCHEMA"
json_ok "two tools are declared" "$SCHEMA" 'len(d["tools"])==2'
json_ok "every tool has an inputSchema" \
        "$SCHEMA" 'all("inputSchema" in t and t["inputSchema"].get("type")=="object" for t in d["tools"])'
json_ok "web_search requires query" \
        "$SCHEMA" 'any(t["name"]=="web_search" and t["inputSchema"]["required"]==["query"] for t in d["tools"])'
json_ok "the provider enum lists all six backends" \
        "$SCHEMA" 'len([e for t in d["tools"] if t["name"]=="web_search" for e in t["inputSchema"]["properties"]["provider"]["enum"]])==6'

cat > "$WORK/mcp.jsonl" <<'EOF'
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","clientInfo":{"name":"t","version":"0"}}}
{"jsonrpc":"2.0","method":"notifications/initialized"}
{"jsonrpc":"2.0","id":2,"method":"ping"}
{"jsonrpc":"2.0","id":3,"method":"tools/list"}
{"jsonrpc":"2.0","id":4,"method":"resources/list"}
{"jsonrpc":"2.0","id":5,"method":"prompts/list"}
{"jsonrpc":"2.0","id":6,"method":"no/such/method"}
not json at all
{"jsonrpc":"2.0","id":7}
EOF
MCPOUT=$(mcp "$WORK/mcp.jsonl")
check "initialize answers the protocol version" '"protocolVersion":"2025-06-18"' "$MCPOUT"
check "initialize names the server"             '"name":"websearch-server"' "$MCPOUT"
check "ping answers an empty result"            '"id":2,"result":{}' "$MCPOUT"
check "resources/list is empty, not an error"   '"resources":[]' "$MCPOUT"
check "prompts/list is empty, not an error"     '"prompts":[]' "$MCPOUT"
check "an unknown method is -32601"             '"code":-32601' "$MCPOUT"
check "unparseable input is -32700 with id null" '"id":null,"error":{"code":-32700' "$MCPOUT"
check "a request without a method is -32600"    '"code":-32600' "$MCPOUT"
N_RESP=$(printf '%s\n' "$MCPOUT" | grep -c '^{')
if [ "$N_RESP" = 8 ]; then
    pass "one response per request (7 requests + 1 parse error), none for the notification"
else
    fail "expected 8 responses (1 notification silent), got $N_RESP"
fi
json_ok "every response line is valid JSON" \
        "$(printf '%s\n' "$MCPOUT" | python3 -c 'import sys,json; print(json.dumps([json.loads(l) for l in sys.stdin if l.strip()]))')"

# --------------------------------------------------------------- requests
section "each provider sends what its API requires"
: > "$LOG"
R=$(call 1 web_search '{"query":"rust lang","provider":"duckduckgo","count":3}')
json_ok "duckduckgo: ok, 3 results, parsed title/url/snippet" "$R" \
        'd["ok"] and d["count"]==3 and d["results"][0]["url"].startswith("https://example0.test")'
json_ok "duckduckgo: entities decoded and tags stripped" "$R" \
        'd["results"][0]["title"].startswith("Result & 0") and "b>rust" not in d["results"][0]["title"]'
json_ok "duckduckgo: the /l/?uddg= redirect was unwrapped" "$R" \
        'd["results"][1]["url"]=="https://example1.test/page1"'
json_ok "duckduckgo: site is the host" "$R" 'd["results"][0]["site"]=="example0.test"'

R=$(call 2 web_search '{"query":"rust lang","provider":"brave","count":2,"country":"NZ","freshness":"week"}')
json_ok "brave: ok with 2 results" "$R" 'd["ok"] and d["count"]==2'
R=$(call 3 web_search '{"query":"a b","provider":"tavily","count":2}')
json_ok "tavily: ok with 2 results" "$R" 'd["ok"] and d["count"]==2'
R=$(call 4 web_search '{"query":"a b","provider":"exa","count":2}')
json_ok "exa: ok with 2 results" "$R" 'd["ok"] and d["count"]==2'
json_ok "exa: the highlight became the snippet" "$R" 'd["results"][0]["snippet"].startswith("exa highlight")'
R=$(call 5 web_search '{"query":"a b","provider":"perplexity","count":2}')
json_ok "perplexity: ok with 2 results" "$R" 'd["ok"] and d["count"]==2'
R=$(call 6 web_search '{"query":"a b","provider":"searxng","count":2}')
json_ok "searxng: ok with 2 results" "$R" 'd["ok"] and d["count"]==2'

python3 - "$LOG" <<'PY'
import json, sys
reqs = [json.loads(l) for l in open(sys.argv[1]) if l.strip()]
def one(path):
    for r in reqs:
        if r["path"] == path:
            return r
    return None
fails = []
def want(desc, cond, detail=""):
    if cond:
        print("  ok   %s" % desc)
    else:
        fails.append(desc)
        print("  FAIL %s%s" % (desc, (" (" + str(detail)[:200] + ")") if detail else ""))

d = one("/duckduckgo/html/")
want("duckduckgo is a POST to /html/ (a GET gets a challenge page)",
     d and d["method"] == "POST", d)
want("duckduckgo sends the query urlencoded in the form body",
     d and "q=rust%20lang" in (d["body"] or ""), d)
want("duckduckgo sends the safe-search parameter", d and "kp=-1" in (d["body"] or ""), d)

b = one("/brave/res/v1/web/search")
want("brave is a GET to /res/v1/web/search", b and b["method"] == "GET", b)
want("brave sends X-Subscription-Token", b and b["cred"] == "BRV-TEST-KEY-1", b)
want("brave sends count, country and freshness",
     b and b["query"].get("count") == "2" and b["query"].get("country") == "NZ"
     and b["query"].get("freshness") == "week", b)

t = one("/tavily/search")
want("tavily is a POST with a JSON body", t and t["method"] == "POST", t)
want("tavily sends the key as a bearer", t and t["cred"] == "Bearer TVL-TEST-KEY-1", t)
want("tavily sends query and max_results",
     t and t["body"].get("query") == "a b" and t["body"].get("max_results") == 2, t)

e = one("/exa/search")
want("exa is a POST with x-api-key", e and e["method"] == "POST" and e["cred"] == "EXA-TEST-KEY-1", e)
want("exa sends numResults and a contents block",
     e and e["body"].get("numResults") == 2 and e["body"].get("contents", {}).get("highlights") is True, e)

p = one("/perplexity/search")
want("perplexity is a POST with a bearer", p and p["method"] == "POST"
     and p["cred"] == "Bearer PPX-TEST-KEY-1", p)
want("perplexity sends query and max_results",
     p and p["body"].get("query") == "a b" and p["body"].get("max_results") == 2, p)

s = one("/searxng/search")
want("searxng is a GET with format=json", s and s["method"] == "GET"
     and s["query"].get("format") == "json", s)
want("searxng sends the query and categories",
     s and s["query"].get("q") == "a b" and s["query"].get("categories") == "general", s)

sys.exit(1 if fails else 0)
PY
if [ $? -eq 0 ]; then PASS=$((PASS + 1)); else FAIL=$((FAIL + 1)); fi

# ----------------------------------------------------------------- errors
section "failures are reported, never swallowed"
R=$(BRAVE_API_KEY=WRONG call 7 web_search '{"query":"q","provider":"brave"}')
check "a wrong brave key is the provider's own 401" 'HTTP 401' "$R"
check "the 401 text is the provider's message, not ours" 'invalid subscription token' "$R"
R=$(TAVILY_API_KEY=WRONG call 8 web_search '{"query":"q","provider":"tavily"}')
check "a wrong tavily key is a 401 tool error" 'HTTP 401' "$R"
R=$(call 9 web_search '{"query":"q","provider":"nope"}')
check "an unknown provider explains the choices" 'unknown provider' "$R"
R=$(call 10 web_search '{}')
check "a missing query is a tool error" 'query is required' "$R"
R=$(call 11 web_search '{"query":"q","provider":"perplexity"}' )
json_ok "a provider with no key still answers ok when one is set" "$R" 'd["ok"] or "Perplexity" in d.get("error","")'
R=$(PERPLEXITY_API_KEY= WEBSEARCH_PPLX_KEY= call 12 web_search '{"query":"q","provider":"perplexity"}')
check "a provider with no key says so, by name" 'Perplexity needs an API key' "$R"
# WEBSEARCH_MOCK_BASE also fills searxng_base, so it has to be cleared too for
# the "not configured" branch to be reachable at all.
R=$(WEBSEARCH_MOCK_BASE= WEBSEARCH_SEARXNG_BASE= SEARXNG_URL= \
    call 13 web_search '{"query":"q","provider":"searxng"}')
check "searxng with no base URL says so, by name" 'SearXNG needs a base URL' "$R"
R=$(WEBSEARCH_MOCK_BASE= WEBSEARCH_DDG_BASE=http://127.0.0.1:1 call 14 web_search '{"query":"q","provider":"duckduckgo"}')
check "an unreachable host is a clean error, not a hang" 'connect' "$R"
R=$(call 15 web_search '{"query":"q","provider":"ddg"}')
check "the provider id is matched exactly" 'unknown provider' "$R"

# --------------------------------------------------------------- config
section "config.json round-trip and secret hygiene"
rm -rf "$CFGDIR"; mkdir -p "$CFGDIR"
SAVE=$(cgi "action=save&format=json" POST \
  '{"action":"save","brave_key":"BRV-SAVED-1","tavily_key":"","exa_key":"EXA-SAVED-1","provider":"exa","count":"7","safe":"strict"}')
json_ok "save answers the provider map" "$(body "$SAVE")" '"providers" in d'
body "$SAVE" > "$WORK/save.json"
json_ok "the saved provider became the active one" "$(cat "$WORK/save.json")" 'd["active"]=="exa"'
json_ok "the saved count round-trips" "$(cat "$WORK/save.json")" 'd["default_count"]==7'
json_ok "the saved safe-search round-trips" "$(cat "$WORK/save.json")" 'd["safe"]=="strict"'
check_not "the save response never echoes the key" 'BRV-SAVED-1' "$SAVE"
check_not "the save response never echoes the other key" 'EXA-SAVED-1' "$SAVE"
if [ -f "$CFGDIR/config.json" ]; then
    pass "config.json was written in the connector dir"
    MODE=$(stat -c '%a' "$CFGDIR/config.json" 2>/dev/null || stat -f '%Lp' "$CFGDIR/config.json")
    if [ "$MODE" = "600" ]; then pass "config.json is mode 0600"; else fail "config.json mode is $MODE, want 600"; fi
    check "the key really is in the file" 'BRV-SAVED-1' "$CFGDIR/config.json"
else
    fail "config.json was not created"
fi
# The environment outranks the file: a saved "" for tavily must still lose to
# TAVILY_API_KEY, and a saved value must lose to a different env value.
PROV=$(SWEBSEARCH_CONFIG_DIR="$CFGDIR" BRAVE_API_KEY=ENV-WINS cgi "action=providers&format=json" GET)
body "$PROV" > "$WORK/prov.json"
json_ok "the env key outranks the saved one (brave has_key still true)" "$(cat "$WORK/prov.json")" \
        'any(p["id"]=="brave" and p["has_key"] for p in d["providers"])'
check_not "the providers response never carries a key" 'ENV-WINS' "$PROV"
check_not "the providers response never carries the saved key" 'BRV-SAVED-1' "$PROV"
CLEAR=$(SWEBSEARCH_CONFIG_DIR="$CFGDIR" BRAVE_API_KEY= cgi "action=save&format=json" POST \
  '{"action":"save","clear_brave_key":1}')
check_not "clearing a key removes it from the file" 'BRV-SAVED-1' "$CFGDIR/config.json"
BAD=$(cgi "action=save&format=json" POST '{"action":"save","brave_base":"ftp://x"}')
check "a non-http base URL is refused" 'must start with http' "$BAD"
UNK=$(cgi "action=nope&format=json" GET)
check "an unknown action is a 404" 'unknown action' "$UNK"

# ------------------------------------------------------------------- CGI
section "the page and its auth gate"
UNAUTH=$(QUERY_STRING="" REQUEST_METHOD=GET BOT_PASSWORD=pw SWEBSEARCH_CONFIG_DIR="$CFGDIR" "$BIN")
check "GET with no credential is 401 when a node password is set" '401 Unauthorized' "$UNAUTH"
AUTHED=$(QUERY_STRING="pwd=pw" REQUEST_METHOD=GET BOT_PASSWORD=pw SWEBSEARCH_CONFIG_DIR="$CFGDIR" "$BIN")
check "GET with ?pwd= is 200" 'Content-Type: text/html' "$AUTHED"
HDR=$(QUERY_STRING="" REQUEST_METHOD=GET BOT_PASSWORD=pw HTTP_X_BOT_PASSWORD=pw \
      SWEBSEARCH_CONFIG_DIR="$CFGDIR" "$BIN")
check "GET with X-Bot-Password is 200" 'Content-Type: text/html' "$HDR"
BEARER=$(QUERY_STRING="" REQUEST_METHOD=GET BOT_PASSWORD=pw HTTP_AUTHORIZATION="Bearer pw" \
         SWEBSEARCH_CONFIG_DIR="$CFGDIR" "$BIN")
check "GET with a bearer token is 200" 'Content-Type: text/html' "$BEARER"
PAGE=$(QUERY_STRING="theme=light&embed=1" REQUEST_METHOD=GET BOT_PASSWORD="" \
       SWEBSEARCH_CONFIG_DIR="$CFGDIR" "$BIN")
check_not "the page has no external script tag" '<script src=' "$PAGE"
check_not "the page references no CDN" 'cdnjs' "$PAGE"
check_not "the page references no unpkg" 'unpkg' "$PAGE"
check "the page carries the bot theme tokens" '--bg:' "$PAGE"
check "the page carries the theme prepaint/handoff script" 'sxApplyTheme' "$PAGE"
check "the page has the provider list container" 'id="providers"' "$PAGE"
check "the page has a search box" 'id="q"' "$PAGE"
check "the page has the key fields" 'id="k_brave"' "$PAGE"
check "the page asks for an sx-theme from its host" 'sx-theme-request' "$PAGE"
json_ok "embed=1 does not break the page (still valid HTML head)" \
        "$(printf '%s' "$PAGE" | grep -c 'DOCTYPE html' >/dev/null && echo '{"ok":1}')"
EMBED=$(printf '%s' "$PAGE" | grep -c 'class="embedded"\|embed-hide')
if [ "$EMBED" -ge 1 ]; then pass "the embed-mode rules are present"; else fail "no embed-mode markup"; fi
INFO=$(cgi "action=info&format=json" GET)
body "$INFO" > "$WORK/info.json"
json_ok "action=info reports the id, kind and providers" "$(cat "$WORK/info.json")" \
        'd["id"]=="plugin_websearch" and d["kind"]=="mcp" and len(d["providers"])==6'
SEARCHAPI=$(cgi "action=search&format=json&q=rust+lang&provider=duckduckgo&count=2" GET)
body "$SEARCHAPI" > "$WORK/api.json"
json_ok "action=search answers real results" "$(cat "$WORK/api.json")" \
        'd["ok"] and d["count"]==2 and d["provider"]=="duckduckgo"'
NOPWD=$(QUERY_STRING="action=providers&format=json" REQUEST_METHOD=GET BOT_PASSWORD=pw \
        SWEBSEARCH_CONFIG_DIR="$CFGDIR" "$BIN")
check "the JSON API is behind the same auth gate" '401 Unauthorized' "$NOPWD"

# ---------------------------------------------------------------- build cmd
section "the advertised build command actually builds the plugin"
# `build_cmd_posix` is what the marketplace's "copy the agent build command"
# button hands to a user's agent, so a wrong string is a broken promise - and
# the CLI's pre-1.4.0 default was a single-source `cc` line that cannot build a
# repo with six sources and two vendored libraries. The author declares it here
# (rule 1 of the CLI's own precedence) and this asserts the declaration is the
# one that works, not merely that it exists.
json_ok "plugin.json declares build_cmd_posix" "$(cat plugin.json)" \
        'd.get("build_cmd_posix")=="make"'
json_ok "plugin.json declares build_cmd_win64" "$(cat plugin.json)" \
        'd.get("build_cmd_win64")=="make win64"'
json_ok "the declared win64 build is a real Makefile target" "$(cat plugin.json)" \
        'open("Makefile").read().find("\nwin64:") >= 0'
# the legacy single-source line is provably wrong here: it neither passes -I nor
# names the vendored translation units. Prove that rather than assert it.
if [ "$(ls src/*.c | wc -l)" -gt 1 ]; then
    pass "repo has more than one translation unit (a one-line cc cannot build it)"
else
    fail "expected more than one source file"
fi
if grep -q -- '-I vendor' Makefile; then
    pass "the Makefile passes -I vendor (the one-line cc does not)"
else
    fail "Makefile does not pass -I vendor"
fi

# ---------------------------------------------------------------- source
section "source guards"
if grep -rn --include='*.c' --include='*.h' -E '\b(popen|system|execv|fork)\s*\(' src/ >/dev/null 2>&1; then
    fail "src/ must not spawn a process"
else pass "src/ spawns no process (no popen/system/exec/fork)"; fi
if grep -rn --include='*.c' --include='*.h' -E 'ghp_[A-Za-z0-9]{10}|hf_[A-Za-z0-9]{10}' src/ >/dev/null 2>&1; then
    fail "src/ carries a credential literal"
else pass "src/ carries no credential literal"; fi
if grep -rn --include='*.c' --include='*.h' -E '192[.]168[.]|10[.][0-9]+[.][0-9]+[.]' src/*.c src/*.h >/dev/null 2>&1; then
    fail "src/ carries a private address"
else pass "src/ carries no private address literal"; fi
if grep -rn --include='*.c' 'yyjson_mut_obj_add_str(' src/ >/dev/null 2>&1; then
    fail "yyjson_mut_obj_add_str stores the caller's pointer - use the strcpy form"
else pass "no non-copying yyjson string constructor is used"; fi
if grep -n 'require_node_auth' src/plugin_websearch.c | grep -q .; then
    pass "the CGI path calls require_node_auth()"
else fail "require_node_auth() is not called"; fi
if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
    pass "src/ui_html.h matches src/ui.html"
else fail "src/ui_html.h is stale (run make ui)"; fi
# A one-line header edit must force a rebuild. `make` used to treat only
# src/*.c and the generated UI header as prerequisites, so a version bump in
# src/ws.h left "Nothing to be done" and the previous binary in place - the
# build reported success with a stale artefact (the failure this project
# keeps paying for). Pin the rule, not the belief.
if grep -q '^HDR ' Makefile && grep -q '\$(HDR)' Makefile; then
    pass "Makefile makes every header a rebuild prerequisite"
else
    fail "Makefile does not depend on src/*.h - a header edit would not rebuild"
fi

# --------------------------------------------------------------- summary
printf '\n%s== summary ==%s\n' "$C_B" "$C_0"
printf 'PASS=%d FAIL=%d SKIP=%d\n' "$PASS" "$FAIL" "$SKIP"
if [ "$FAIL" -ne 0 ]; then
    echo "SUITE-FAIL"
    exit 1
fi
echo "SUITE-OK"
