#!/bin/sh
# tests/run.sh - offline checks for plugin_seqthink across all 4 modes.
#
# Runs against ./plugin_seqthink (native build) on the live machine. The --mcp
# leg is driven with a scripted JSON-RPC session on stdin; the CGI leg is
# driven through QUERY_STRING / REQUEST_METHOD / CONTENT_LENGTH; the chain
# store is pointed at a scratch directory through SEQTHINK_STATE_DIR so the
# real node directory is never touched. 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_seqthink
PASS=0
FAIL=0
TMP=$(mktemp -d 2>/dev/null || echo /tmp/seqthink_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'; }

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
}

mcp() { # mcp <state-dir> [env assignments...] -- feeds $TMP/in.jsonl
    local dir="$1"; shift
    SEQTHINK_STATE_DIR="$dir" env "$@" "$BIN" --mcp < "$TMP/in.jsonl" 2>"$TMP/err.txt"
}

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

SRC=src/plugin_seqthink.c
SRC_TXT=$(cat "$SRC")

# ---------------------------------------------------------------- mode 1: --meta
section "mode 1 --meta (must work without auth - discovery)"
META=$("$BIN" --meta)
check      "meta emits name seqthink"      '"name":"seqthink"'        "$META"
check      "meta emits desc"               '"desc":"Thought chains"'  "$META"
check      "meta declares kind mcp"        '"kind":"mcp"'             "$META"
check      "meta declares mcp true"        '"mcp":true'               "$META"
check      "meta declares daemon false"    '"daemon":false'           "$META"
check      "meta declares menus false"     '"menus":false'            "$META"
check      "meta declares verified"        '"verified":"live"'        "$META"
METAENV=$(SX_PLUGIN_META=1 "$BIN")
check      "SX_PLUGIN_META=1 yields same meta" '"name":"seqthink"'    "$METAENV"
[ "$META" = "$METAENV" ] && pass "argv and env meta identical" || fail "argv and env meta differ"
if [ "$(printf '%s\n' "$META" | wc -l)" -eq 1 ]; then pass "meta is exactly one line"; else fail "meta is more than one line"; fi
check      "--version names the plugin"    "plugin_seqthink"          "$("$BIN" --version)"
check      "--schema is the input schema"  '"required":["thought","nextThoughtNeeded","thoughtNumber","totalThoughts"]' \
                                            "$("$BIN" --schema)"

section "plugin.json agrees with --meta"
PJ=$(cat plugin.json)
jq_ "plugin.json slug/id"        "d['slug']=='seqthink' and d['id']=='plugin_seqthink'" "$PJ"
jq_ "plugin.json category"       "d['category']=='devtools'"                            "$PJ"
jq_ "plugin.json kind/mcp"       "d['kind']=='mcp' and d['mcp'] is True"                "$PJ"
jq_ "plugin.json daemon/menus"   "d['daemon'] is False and d['menus'] is False"          "$PJ"
jq_ "plugin.json verified"       "d['verified']=='live'"                                 "$PJ"
jq_ "plugin.json has title/summary/trust" "d['title'] and len(d['summary'])>80 and d['trust_notice']" "$PJ"
check_not "plugin.json has no LAN address" "192.168." "$PJ"

# ---------------------------------------------------------------- mode 2: --mcp
section "mode 2 --mcp handshake"
cat > "$TMP/in.jsonl" <<'JSONL'
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"probe","version":"1"}}}
{"jsonrpc":"2.0","method":"notifications/initialized"}
{"jsonrpc":"2.0","id":2,"method":"tools/list"}
{"jsonrpc":"2.0","id":3,"method":"ping"}
{"jsonrpc":"2.0","id":4,"method":"not/a/method"}
JSONL
OUT=$(mcp "$TMP/m_hand" env)
R1=$(printf '%s' "$OUT" | sed -n 1p)
R2=$(printf '%s' "$OUT" | sed -n 2p)
R3=$(printf '%s' "$OUT" | sed -n 3p)
R4=$(printf '%s' "$OUT" | sed -n 4p)
check      "initialize answers jsonrpc 2.0" '"jsonrpc":"2.0"'  "$R1"
check      "initialize echoes id"           '"id":1'           "$R1"
check      "initialize carries protocol"    '"protocolVersion":"2024-11-05"' "$R1"
check      "initialize advertises tools"    '"capabilities":{"tools":{}}'    "$R1"
check      "initialize names the server"    '"name":"seqthink"'              "$R1"
check      "notifications get no reply"     '"id":2'                          "$R2"
check      "tools/list offers sequentialthinking" '"name":"sequentialthinking"' "$R2"
check      "tool carries a title"          '"title":"Sequential Thinking"'   "$R2"
check      "tool carries annotations"      '"readOnlyHint":false'            "$R2"
check      "annotations not idempotent"    '"idempotentHint":false'          "$R2"
check      "tool carries inputSchema"      '"inputSchema"'                   "$R2"
check      "inputSchema requires 4 fields" '"required":["thought","nextThoughtNeeded","thoughtNumber","totalThoughts"]' "$R2"
check      "inputSchema minimum on thoughtNumber" '"thoughtNumber":{"type":"integer"' "$R2"
check      "tool carries outputSchema"     '"thoughtHistoryLength":{"type":"number"}' "$R2"
check      "ping answered empty result"    '"result":{}'                     "$R3"
check      "unknown method -> -32601"       '"code":-32601'                   "$R4"

section "mode 2 --mcp tool: happy path, revision, branch"
cat > "$TMP/in.jsonl" <<'JSONL'
{"jsonrpc":"2.0","id":11,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"break the problem down","nextThoughtNeeded":true,"thoughtNumber":1,"totalThoughts":3}}}
{"jsonrpc":"2.0","id":12,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"question an earlier step","nextThoughtNeeded":"true","isRevision":true,"revisesThought":1,"thoughtNumber":2,"totalThoughts":3,"needsMoreThoughts":true}}}
{"jsonrpc":"2.0","id":13,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"an alternative path","nextThoughtNeeded":"false","branchFromThought":1,"branchId":"alt-route","thoughtNumber":3,"totalThoughts":3}}}
{"jsonrpc":"2.0","id":14,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"past the estimate","nextThoughtNeeded":false,"thoughtNumber":9,"totalThoughts":3}}}
JSONL
OUT=$(mcp "$TMP/m_ok" env)
L11=$(printf '%s' "$OUT" | sed -n 1p)
L12=$(printf '%s' "$OUT" | sed -n 2p)
L13=$(printf '%s' "$OUT" | sed -n 3p)
L14=$(printf '%s' "$OUT" | sed -n 4p)
check      "call 1 content is text"      '"type":"text"'                "$L11"
check      "call 1 reports thoughtNumber" 'thoughtNumber\":1'         "$L11"
check      "call 1 history length 1"      'thoughtHistoryLength\":1}' "$L11"
check      "call 1 not an error"          '"isError":false'              "$L11"
check      "call 1 has structuredContent" '"structuredContent":{"thoughtNumber":1' "$L11"
check      "call 2 accepted a string bool" '"isError":false'             "$L12"
check      "call 2 history length 2"      'thoughtHistoryLength\":2}' "$L12"
check      "call 3 records the branch"    'branches\":[\"alt-route\"' "$L13"
check      "call 4 raised totalThoughts"  'totalThoughts\":9'          "$L14"
check      "call 4 kept the branch list"  'alt-route'                    "$L14"
check      "stderr logged thought 1"      'Thought 1/3'                  "$(cat "$TMP/err.txt")"
check      "stderr marked the revision"   'Revision 2/3 (revising thought 1)' "$(cat "$TMP/err.txt")"
check      "stderr marked the branch"     'Branch 3/3 (from thought 1, ID: alt-route)' "$(cat "$TMP/err.txt")"
# (structuredContent parity is asserted in detail below)
printf '%s' "$L11" > "$TMP/_c.json"
if python3 - "$TMP/_c.json" <<'PY' 2>/dev/null
import json, sys
d = json.load(open(sys.argv[1]))
r = d["result"]
sc = r["structuredContent"]
txt = json.loads(r["content"][0]["text"])
assert sc == txt, (sc, txt)
assert sorted(sc) == ["branches", "nextThoughtNeeded", "thoughtHistoryLength",
                      "thoughtNumber", "totalThoughts"], sorted(sc)
assert sc["thoughtNumber"] == 1 and sc["totalThoughts"] == 3
assert sc["nextThoughtNeeded"] is True
assert sc["branches"] == [] and sc["thoughtHistoryLength"] == 1
PY
then pass "structuredContent == parsed content text, exactly 5 fields"
else fail "structuredContent == parsed content text, exactly 5 fields"
fi

section "mode 2 --mcp tool: validation errors mirror upstream"
cat > "$TMP/in.jsonl" <<'JSONL'
{"jsonrpc":"2.0","id":21,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"","nextThoughtNeeded":true,"thoughtNumber":1,"totalThoughts":1}}}
{"jsonrpc":"2.0","id":22,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"nextThoughtNeeded":true,"thoughtNumber":1,"totalThoughts":1}}}
{"jsonrpc":"2.0","id":23,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"thoughtNumber":0,"totalThoughts":1}}}
{"jsonrpc":"2.0","id":24,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"thoughtNumber":"abc","totalThoughts":1}}}
{"jsonrpc":"2.0","id":25,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"thoughtNumber":1,"totalThoughts":0}}}
{"jsonrpc":"2.0","id":26,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":"yes","thoughtNumber":1,"totalThoughts":1}}}
{"jsonrpc":"2.0","id":27,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","thoughtNumber":1,"totalThoughts":1}}}
{"jsonrpc":"2.0","id":28,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"isRevision":"maybe","thoughtNumber":1,"totalThoughts":1}}}
{"jsonrpc":"2.0","id":29,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"revisesThought":0,"thoughtNumber":1,"totalThoughts":1}}}
{"jsonrpc":"2.0","id":30,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"branchFromThought":-2,"thoughtNumber":1,"totalThoughts":1}}}
{"jsonrpc":"2.0","id":31,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"branchId":42,"thoughtNumber":1,"totalThoughts":1}}}
{"jsonrpc":"2.0","id":32,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"x","nextThoughtNeeded":true,"needsMoreThoughts":"perhaps","thoughtNumber":1,"totalThoughts":1}}}
{"jsonrpc":"2.0","id":33,"method":"tools/call","params":{"name":"nope","arguments":{}}}
{"jsonrpc":"2.0","id":34,"method":"tools/call","params":{"name":"sequentialthinking"}}
JSONL
OUT=$(mcp "$TMP/m_err" env)
E1=$(printf '%s' "$OUT" | sed -n 1p)
E2=$(printf '%s' "$OUT" | sed -n 2p)
E3=$(printf '%s' "$OUT" | sed -n 3p)
E4=$(printf '%s' "$OUT" | sed -n 4p)
E5=$(printf '%s' "$OUT" | sed -n 5p)
E6=$(printf '%s' "$OUT" | sed -n 6p)
E7=$(printf '%s' "$OUT" | sed -n 7p)
E8=$(printf '%s' "$OUT" | sed -n 8p)
E9=$(printf '%s' "$OUT" | sed -n 9p)
E10=$(printf '%s' "$OUT" | sed -n 10p)
E11=$(printf '%s' "$OUT" | sed -n 11p)
E12=$(printf '%s' "$OUT" | sed -n 12p)
E13=$(printf '%s' "$OUT" | sed -n 13p)
E14=$(printf '%s' "$OUT" | sed -n 14p)
check "empty thought refused"      'Invalid thought: must be a string'          "$E1"
check "missing thought refused"    'Invalid thought: must be a string'          "$E2"
check "thoughtNumber 0 refused"    'Invalid thoughtNumber: must be a number'    "$E3"
check "non-numeric thoughtNumber"  'Invalid thoughtNumber: must be a number'    "$E4"
check "totalThoughts 0 refused"    'Invalid totalThoughts: must be a number'    "$E5"
check "bad nextThoughtNeeded"      'Invalid nextThoughtNeeded: must be a boolean' "$E6"
check "missing nextThoughtNeeded"  'Invalid nextThoughtNeeded: must be a boolean' "$E7"
check "bad isRevision"             'Invalid isRevision: must be a boolean'      "$E8"
check "bad revisesThought"         'Invalid revisesThought: must be a number'   "$E9"
check "bad branchFromThought"      'Invalid branchFromThought: must be a number' "$E10"
check "branchId must be a string"  'Invalid branchId: must be a string'         "$E11"
check "bad needsMoreThoughts"      'Invalid needsMoreThoughts: must be a boolean' "$E12"
check "all refusals set isError"   '"isError":true'                              "$E1"
check "all refusals say failed"    '"status\":\"failed\"'                      "$E1"
check "unknown tool -> -32602"     '"code":-32602'                               "$E13"
check "missing arguments refused"  'Invalid thought: must be a string'          "$E14"
cat > "$TMP/in.jsonl" <<'JSONL'
{"jsonrpc":"2.0","id":41,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"coerce me","nextThoughtNeeded":"TRUE","thoughtNumber":"2","totalThoughts":"4"}}}
JSONL
OUT=$(mcp "$TMP/m_coerce" env)
check "string numbers coerce (upstream z.coerce)" 'totalThoughts\":4' "$OUT"
check "string TRUE coerces to true"               'nextThoughtNeeded\":true' "$OUT"

section "mode 2 --mcp: history cap and branch eviction"
python3 - > "$TMP/in.jsonl" <<'PY'
import json
print(json.dumps({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"base","nextThoughtNeeded":True,"thoughtNumber":1,"totalThoughts":9}}}))
for i in range(2, 7):
    print(json.dumps({"jsonrpc":"2.0","id":i,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"beta%d" % i,"nextThoughtNeeded":True,"branchFromThought":1,"branchId":"beta","thoughtNumber":i,"totalThoughts":9}}}))
for i in range(7, 9):
    print(json.dumps({"jsonrpc":"2.0","id":i,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"gamma%d" % i,"nextThoughtNeeded":True,"branchFromThought":1,"branchId":"gamma","thoughtNumber":i,"totalThoughts":9}}}))
PY
OUT=$(mcp "$TMP/m_cap1" MAX_THOUGHT_HISTORY=1)
LAST=$(printf '%s' "$OUT" | tail -1)
check "cap 1 keeps one thought"      'thoughtHistoryLength\":1}' "$LAST"
check "cap 1 emptied beta dropped"   'branches\":[\"gamma\"]'    "$LAST"
check_not "cap 1 does not list beta" '\"beta\"'                    "$LAST"
OUT=$(mcp "$TMP/m_cap2" MAX_THOUGHT_HISTORY=3)
LAST=$(printf '%s' "$OUT" | tail -1)
check "cap 3 keeps three thoughts"   'thoughtHistoryLength\":3}' "$LAST"
check "cap 3 still lists beta"       'beta'                        "$LAST"
OUT=$(mcp "$TMP/m_bad" MAX_THOUGHT_HISTORY=abc)
check "bad cap warns on stderr"      'MAX_THOUGHT_HISTORY must be a positive integer' "$(cat "$TMP/err.txt")"
check "bad cap falls back to default" "thoughtHistoryLength\\\":1}" "$OUT"
OUT=$(mcp "$TMP/m_neg" MAX_THOUGHT_HISTORY=0)
check "zero cap rejected too"        'must be a positive integer'  "$(cat "$TMP/err.txt")"

section "mode 2 --mcp: DISABLE_THOUGHT_LOGGING (upstream parity)"
OUT=$(mcp "$TMP/m_dis" DISABLE_THOUGHT_LOGGING=true)
check "call still succeeds when logging disabled" '"isError":false' "$OUT"
if [ -s "$TMP/err.txt" ]; then fail "logging silenced on stderr"; else pass "logging silenced on stderr"; fi
if [ -f "$TMP/m_dis/chains.json" ]; then fail "logging disabled also skips persistence"; else pass "logging disabled also skips persistence"; fi
OUT=$(mcp "$TMP/m_dis2" DISABLE_THOUGHT_LOGGING=1)
if [ -s "$TMP/err.txt" ]; then fail "DISABLE_THOUGHT_LOGGING=1 silences stderr"; else pass "DISABLE_THOUGHT_LOGGING=1 silences stderr"; fi

section "mode 2 --mcp: chains.json snapshot for the viewer"
CHAINJSON="$TMP/m_ok/chains.json"
[ -f "$CHAINJSON" ] && pass "chains.json written" || fail "chains.json missing"
CJ=$(cat "$CHAINJSON" 2>/dev/null || echo '{}')
jq_ "chains.json has one chain"   "len(d['chains'])==1"        "$CJ"
jq_ "chain keeps 4 thoughts"      "d['chains'][0]['count']==4" "$CJ"
jq_ "chain records the branch"    "d['chains'][0]['branches']==['alt-route']" "$CJ"
jq_ "thought carries fields"      "set(['thought','thought_number','total_thoughts','next_needed','at']) <= set(d['chains'][0]['thoughts'][0])" "$CJ"
jq_ "revision flagged"            "d['chains'][0]['thoughts'][1].get('is_revision') is True" "$CJ"
jq_ "revision target recorded"    "d['chains'][0]['thoughts'][1]['revises']==1" "$CJ"
jq_ "branch flagged"              "d['chains'][0]['thoughts'][2]['branch_id']=='alt-route'" "$CJ"
jq_ "needs_more flagged"          "d['chains'][0]['thoughts'][1]['needs_more'] is True" "$CJ"
# a second process must merge, not clobber
cat > "$TMP/in.jsonl" <<'JSONL'
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"second session","nextThoughtNeeded":false,"thoughtNumber":1,"totalThoughts":1}}}
JSONL
mcp "$TMP/m_ok" env >/dev/null
CJ=$(cat "$CHAINJSON")
jq_ "second session merged"       "len(d['chains'])==2"          "$CJ"
jq_ "first chain untouched"       "any(c['count']==4 for c in d['chains'])" "$CJ"
# malformed store degrades to clean, never a crash or a poisoned file
printf 'not json {{{\n' > "$TMP/m_ok/chains.json"
mcp "$TMP/m_ok" env >/dev/null 2>&1
check "corrupt store recovered"   '"thought"' "$(cat "$TMP/m_ok/chains.json")"
# the file is written .tmp then rename()d
check "persistence uses a temp file" "rename(tmp, path)" "$SRC_TXT"
check_not "persistence never writes the store in place" 'fopen(path, "wb")' "$SRC_TXT"

# ---------------------------------------------------------------- mode 3: JSON API
section "mode 3 JSON API: authentication"
S="$TMP/api"; mkdir -p "$S"
cat > "$TMP/in.jsonl" <<'JSONL'
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"alpha one","nextThoughtNeeded":true,"thoughtNumber":1,"totalThoughts":2}}}
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"alpha two","nextThoughtNeeded":false,"isRevision":true,"revisesThought":1,"thoughtNumber":2,"totalThoughts":2}}}
JSONL
mcp "$S" env >/dev/null
R=$(SEQTHINK_STATE_DIR="$S" BOT_PASSWORD=secretpw QUERY_STRING="action=chains" "$BIN"; true)
check      "401 without a credential"   "Status: 401 Unauthorized" "$R"
check      "401 body says invalid"      "invalid node password"    "$R"
check_not "401 leaks no chains"          '"chains":['              "$R"
R=$(SEQTHINK_STATE_DIR="$S" BOT_PASSWORD=secretpw HTTP_X_BOT_PASSWORD=secretpw QUERY_STRING="action=chains" "$BIN"; true)
check      "header credential accepted" '"chains":['               "$R"
R=$(SEQTHINK_STATE_DIR="$S" BOT_PASSWORD=secretpw HTTP_AUTHORIZATION="Bearer secretpw" QUERY_STRING="action=stats" "$BIN"; true)
check      "bearer credential accepted" '"ok":true'                 "$R"
R=$(SEQTHINK_STATE_DIR="$S" BOT_PASSWORD=secretpw QUERY_STRING="action=chains&pwd=secretpw" "$BIN"; true)
check      "query pwd credential accepted" '"chains":['             "$R"
R=$(SEQTHINK_STATE_DIR="$S" BOT_PASSWORD=secretpw QUERY_STRING="action=chains&pwd=nope" "$BIN"; true)
check      "wrong credential still 401" "Status: 401"               "$R"
R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=chains" "$BIN"; true)
check      "open node (no BOT_PASSWORD) answers" '"chains":[' "$R"
R=$(SEQTHINK_STATE_DIR="$S" BOT_PASSWORD=secretpw "$BIN" --meta; true)
check      "--meta stays unauthenticated" '"name":"seqthink"' "$R"
printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"ping"}' > "$TMP/ping.jsonl"
R=$(SEQTHINK_STATE_DIR="$S" BOT_PASSWORD=secretpw "$BIN" --mcp < "$TMP/ping.jsonl" 2>/dev/null; true)
check      "--mcp stays unauthenticated (stdio)" '"jsonrpc":"2.0"' "$R"
check_not  "--mcp never emits a CGI 401"         "Status: 401"     "$R"
R=$(SEQTHINK_STATE_DIR="$S" BOT_PASSWORD=secretpw "$BIN" < /dev/null; true)
check      "bare HTML GET 401 without a credential" "Status: 401 Unauthorized" "$R"
check_not "401 HTML leaks no page"                   "<!DOCTYPE html>"          "$R"
R=$(SEQTHINK_STATE_DIR="$S" BOT_PASSWORD=secretpw HTTP_X_BOT_PASSWORD=secretpw "$BIN" < /dev/null; true)
check      "HTML renders with a credential"  "<!DOCTYPE html>" "$R"

section "mode 3 JSON API: actions"
R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=chains" "$BIN"; true)
CB=$(body "$R")
jq_ "chains lists one chain"   "d['count']==1"                  "$CB"
jq_ "chains reports the plugin" "d['plugin']=='plugin_seqthink'" "$CB"
jq_ "chain summary has thoughts" "d['chains'][0]['thoughts']==2" "$CB"
jq_ "chain summary has last_head" "d['chains'][0]['last_head']=='alpha two'" "$CB"
jq_ "chain summary lists branches" "isinstance(d['chains'][0]['branches'], list)" "$CB"
jq_ "chains never leaks an absolute state path" "'/' not in d['state_dir_name']" "$CB"
CID=$(printf '%s' "$CB" | python3 -c "import json,sys;print(json.load(sys.stdin)['chains'][0]['id'])")
R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=chain&id=$CID" "$BIN"; true)
DB=$(body "$R")
jq_ "chain returns thoughts"   "len(d['thoughts'])==2"                     "$DB"
jq_ "chain thought text intact" "d['thoughts'][0]['thought']=='alpha one'" "$DB"
jq_ "chain marks the revision" "d['thoughts'][1]['is_revision'] is True"   "$DB"
R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=chain&id=does-not-exist" "$BIN"; true)
check "unknown chain id -> error" 'chain not found' "$(body "$R")"
R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=chain&id=..%2F..%2Fetc%2Fpasswd" "$BIN"; true)
check "path traversal id refused" 'invalid chain id' "$(body "$R")"
R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=chain&id=a%3Brm" "$BIN"; true)
check "shell metacharacter id refused" 'invalid chain id' "$(body "$R")"
R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=stats" "$BIN"; true)
SB=$(body "$R")
jq_ "stats counts thoughts"  "d['thoughts']==2"          "$SB"
jq_ "stats counts chains"    "d['chains']==1"            "$SB"
jq_ "stats counts revisions" "d['revisions']==1"         "$SB"
jq_ "stats reports the cap"  "d['max_chains']==50"       "$SB"
R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=info" "$BIN"; true)
IB=$(body "$R")
jq_ "info declares kind mcp"  "d['kind']=='mcp' and d['mcp'] is True" "$IB"
jq_ "info declares menus false" "d['menus'] is False and d['daemon'] is False" "$IB"
jq_ "info lists the tool"     "d['tools']==['sequentialthinking']"    "$IB"
jq_ "info carries the schema" "'thought' in d['tool_schema']['properties'] and 'branchId' in d['tool_schema']['properties']" "$IB"
jq_ "info schema requires 4"  "sorted(d['tool_schema']['required'])==sorted(['thought','nextThoughtNeeded','thoughtNumber','totalThoughts'])" "$IB"
R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=bogus" "$BIN"; true)
check "unknown action refused" 'unknown action' "$(body "$R")"
R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="format=json" "$BIN"; true)
check "format=json answers JSON" 'Content-Type: application/json' "$R"
R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="format=jsonx" "$BIN"; true)
check "format=jsonx still serves HTML" 'Content-Type: text/html' "$R"
R=$(SEQTHINK_STATE_DIR="$S" QUERY_STRING="action=clear" "$BIN"; true)
check "clear needs confirmation" 'confirm=1 required' "$(body "$R")"
[ -f "$S/chains.json" ] && pass "clear refused left the store" || fail "clear refused wiped the store"
printf '{"action":"clear","confirm":"1"}' > "$S/_body.json"
R=$(SEQTHINK_STATE_DIR="$S" REQUEST_METHOD=POST CONTENT_LENGTH=$(wc -c < "$S/_body.json") \
    HTTP_X_BOT_PASSWORD=sh "$BIN" < "$S/_body.json"; true)
check "POST JSON body clear works" '"cleared":true' "$(body "$R")"
[ -f "$S/chains.json" ] && fail "clear removed the store" || pass "clear removed the store"

section "mode 3 JSON API: bounded store"
S2="$TMP/bound"; mkdir -p "$S2"
i=1
while [ $i -le 55 ]; do
    printf '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"chain %s","nextThoughtNeeded":false,"thoughtNumber":1,"totalThoughts":1}}}\n' "$i" \
        > "$TMP/one.jsonl"
    SEQTHINK_STATE_DIR="$S2" env "$BIN" --mcp < "$TMP/one.jsonl" >/dev/null 2>&1
    i=$((i + 1))
done
BJ=$(cat "$S2/chains.json")
jq_ "store never exceeds 50 chains" "len(d['chains'])<=50"     "$BJ"
jq_ "newest chain survived"         "any(c['thoughts'][0]['thought']=='chain 55' for c in d['chains'])" "$BJ"

# ---------------------------------------------------------------- mode 4: HTML
section "mode 4 HTML UI"
Q=$(SEQTHINK_STATE_DIR="$TMP/api" QUERY_STRING="embed=1" "$BIN"; true)
check      "html content type"     "Content-Type: text/html; charset=utf-8" "$Q"
check      "html declares charset" "<meta charset="        "$Q"
check      "html has a viewport"   "width=device-width"    "$Q"
check      "html is CSP-locked"    "default-src 'none'"    "$Q"
check      "html sets X-Frame-Options" "X-Frame-Options: SAMEORIGIN" "$Q"
check_not  "html never sends Content-Length" "Content-Length:" "$Q"
check_not  "html has no CDN script"   "<script src="       "$Q"
check_not  "html has no cdnjs"        "cdnjs"              "$Q"
check_not  "html has no googleapis"   "googleapis"         "$Q"
check_not  "html has no private IPs"  "192.168."           "$Q"
check_not  "html has no localhost URL" "http://127.0.0.1"  "$Q"
check      "html has the bot token block" "--bg-card"      "$Q"
check      "html prepaints the theme" "data-theme"         "$Q"
check      "html follows the bot"     "sx-theme"           "$Q"
check      "html asks for the theme"  "sx-theme-request"   "$Q"
check      "html flags embed mode"    "embedded"           "$Q"
check      "html names the plugin"    "Thought Chains"     "$Q"
check      "html branches the API route" "/plugin_seqthink?action=" "$Q"
check      "html supports the hub proxy route" "/plugins?plugin="   "$Q"
check      "html carries the node password" "X-Bot-Password"        "$Q"
check      "html calls the chains API"  "api('chains')"            "$Q"
check_not  "html has no emoji" "💭" "$Q"
check_not  "html has no emoji (revision)" "🔄" "$Q"
check_not  "html has no emoji (branch)" "🌿" "$Q"
if grep -qF "💭" src/ui.html; then fail "ui source has no emoji"; else pass "ui source has no emoji"; fi
grep -c "<script>" src/ui.html >/dev/null 2>&1 && pass "ui has its own script tag" || fail "ui script tag missing"
grep -q "<style>" src/ui.html && pass "ui has its own style tag" || fail "ui style tag missing"
check_not  "ui has no inline hex palette outside tokens" "#123456" "$Q"
if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
    pass "src/ui_html.h is generated from src/ui.html"
else
    fail "src/ui_html.h is stale (run tools/gen_ui.py)"
fi

section "source invariants"
check      "_WIN32 forces binary stdout"        "_setmode(_fileno(stdout), _O_BINARY)" "$SRC_TXT"
check      "_WIN32 gate precedes includes"      "_WIN32_WINNT 0x0601"                  "$SRC_TXT"
check      "Apple needs _DARWIN_C_SOURCE"       "_DARWIN_C_SOURCE"                     "$SRC_TXT"
check      "meta is emitted before auth"        "return run_meta();"                   "$SRC_TXT"
check      "mcp mode is dispatched"             "return run_mcp();"                    "$SRC_TXT"
check      "CGI surface gated before dispatch"  "require_node_auth();"                 "$SRC_TXT"
check_not  "no shell command execution"         "popen("                               "$SRC_TXT"
check_not  "no system()"                        "system("                              "$SRC_TXT"
check_not  "no sockets"                         "socket("                              "$SRC_TXT"
check_not  "no TLS client"                      "mbedtls"                              "$SRC_TXT"
check_not  "no outbound http helper"            "WinHttp"                              "$SRC_TXT"
check      "chain ids are validated"            "valid_chain_id"                       "$SRC_TXT"
check      "history cap is bounded"             "MAX_THOUGHT_HISTORY"                  "$SRC_TXT"
check      "thought text is length-capped"      "THOUGHT_MAX"                          "$SRC_TXT"
check      "branch id is length-capped"         "BRANCHID_MAX"                         "$SRC_TXT"
check      "state dir honours the test override" "SEQTHINK_STATE_DIR"                  "$SRC_TXT"
check      "state dir prefers /workspace"        "/workspace/.scorpiox/connectors/"    "$SRC_TXT"
check      "state dir uses LOCALAPPDATA on win"  "LOCALAPPDATA"                        "$SRC_TXT"
printf '%s' "$SRC_TXT" | grep -q getline && pass "mcp loop reads line-delimited stdio" || fail "mcp loop has no line reader"

section "ASan + fortify (parses files it did not write)"
if [ ! -x ./plugin_seqthink.asan ] || [ "$SRC_TXT" -nt ./plugin_seqthink.asan ]; then
    cc -g -O0 -std=c99 -Wall -Wextra -fsanitize=address -I src -I vendor \
       -o plugin_seqthink.asan src/plugin_seqthink.c vendor/yyjson.c >/dev/null 2>&1 \
        || echo "  note: ASan build unavailable here"
fi
if [ -x ./plugin_seqthink.asan ]; then
    cat > "$TMP/in.jsonl" <<'JSONL'
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"asan thought with \"quotes\" and \\ backslash and \ntab\t","nextThoughtNeeded":true,"isRevision":true,"revisesThought":1,"thoughtNumber":1,"totalThoughts":2}}}
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"sequentialthinking","arguments":{"thought":"unicode ünïcødé and émojis ok","nextThoughtNeeded":false,"branchFromThought":1,"branchId":"ünï","thoughtNumber":2,"totalThoughts":2}}}
JSONL
    AOUT=$(SEQTHINK_STATE_DIR="$TMP/asan" ./plugin_seqthink.asan --mcp < "$TMP/in.jsonl" 2>"$TMP/aerr.txt")
    if grep -q "AddressSanitizer" "$TMP/aerr.txt"; then
        fail "ASan reported a problem"; sed -n 1,12p "$TMP/aerr.txt"
    else
        pass "ASan clean on quotes/backslash/newline/unicode thoughts"
    fi
    check "ASan run still answered" '"isError":false' "$AOUT"
    R=$(SEQTHINK_STATE_DIR="$TMP/asan" QUERY_STRING="action=chains" ./plugin_seqthink.asan; true)
    if grep -q "AddressSanitizer" "$TMP/aerr.txt"; then fail "ASan clean on the CGI read path"
    else pass "ASan clean on the CGI read path"; fi
    printf '{{{ not json' > "$TMP/asan/chains.json"
    SEQTHINK_STATE_DIR="$TMP/asan" QUERY_STRING="action=chains" ./plugin_seqthink.asan >/dev/null 2>>"$TMP/aerr.txt"
    SEQTHINK_STATE_DIR="$TMP/asan" QUERY_STRING="action=chain&id=th-x" ./plugin_seqthink.asan >/dev/null 2>>"$TMP/aerr.txt"
    printf '{"chains":[{"id":42,"thoughts":"not an array"},{"thoughts":[]}]}' > "$TMP/asan/chains.json"
    SEQTHINK_STATE_DIR="$TMP/asan" QUERY_STRING="action=stats" ./plugin_seqthink.asan >/dev/null 2>>"$TMP/aerr.txt"
    if grep -q "AddressSanitizer" "$TMP/aerr.txt"; then fail "ASan clean on malformed stores"
    else pass "ASan clean on malformed stores"; fi
else
    echo "  skip ASan checks (build unavailable)"
fi

if [ ! -x ./plugin_seqthink.fortify ]; then
    cc -O2 -std=c99 -Wall -Wextra -D_FORTIFY_SOURCE=2 -I src -I vendor \
       -o plugin_seqthink.fortify src/plugin_seqthink.c vendor/yyjson.c >/dev/null 2>&1 \
        || echo "  note: fortify build unavailable here"
fi
if [ -x ./plugin_seqthink.fortify ]; then
    SEQTHINK_STATE_DIR="$TMP/fort" ./plugin_seqthink.fortify --mcp < "$TMP/in.jsonl" >/dev/null 2>"$TMP/ferr.txt"
    if grep -qi "buffer overflow" "$TMP/ferr.txt"; then fail "fortify build aborted"
    else pass "fortify build survives the full session"; fi
else
    echo "  skip fortify checks (build unavailable)"
fi

# ---------------------------------------------------------------- audit
section "clean-room audit (working tree + full git history)"
audit() { # audit <label> <regex>
    local out
    out=$(git grep -InE -e "$2" -- . 2>/dev/null | grep -v 'tests/run.sh' | head -5 || true)
    if [ -n "$out" ]; then
        fail "audit: $1"; printf '%s\n' "$out" | sed 's/^/         /'
    else
        pass "audit: $1"
    fi
}
audit "no LAN 192.168 addresses"  '192\.168\.[0-9]+\.[0-9]+'
audit "no private 10.x addresses" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
PAT="gh""p_[A-Za-z0-9]{36}"
audit "no PAT prefix"             "$PAT"
TOK="3e""f2c00c"
audit "no token prefix"           "$TOK"
SFP="ssh""pass -p [A-Za-z0-9]"
audit "no ssh password flag"      "$SFP"
HOSTS="macm""ini|intel-""ultra""2|lazar""us"
audit "no internal hostnames"     "$HOSTS"
if ! git rev-parse HEAD >/dev/null 2>&1; then
    echo "  skip git-history audit (repository has no commits yet)"
elif command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
    if scorpiox-cli-botplugin audit "$ROOT" >/dev/null 2>&1; then
        pass "scorpiox-cli-botplugin audit accepts the repo"
    else
        fail "scorpiox-cli-botplugin audit rejected the repo"
        scorpiox-cli-botplugin audit "$ROOT" 2>&1 | tail -10 | sed 's/^/         /'
    fi
else
    echo "  skip scorpiox-cli-botplugin audit (not installed here)"
fi

printf '\n%s==============================%s\n' "$C_B" "$C_0"
printf '  %s%d passed%s  %s%d failed%s\n' "$C_OK" "$PASS" "$C_0" "$([ "$FAIL" -gt 0 ] && printf '%s' "$C_BAD" || printf '%s')" "$FAIL" "$C_0"
[ "$FAIL" -eq 0 ] || exit 1
exit 0
