#!/bin/sh
# tests/run.sh - offline checks for plugin_memory across all its modes.
#
# Everything runs against ./plugin_memory with MEMORY_FILE_PATH pointing at a
# throwaway file, so the suite never touches anyone's real graph. It proves the
# public contract end to end:
#
#   --meta           the connector metadata the router and /plugins read
#   --mcp            a full JSON-RPC 2.0 session, all nine tools, the
#                    skip/not-found/dedupe semantics, notifications, bad JSON
#   CGI JSON API     the same nine operations behind ?action= and POST, with
#                    the node password on every one of them
#   HTML             the page, with no CDN and no <script src=>
#   persistence      a value written by one process read back by the next,
#                    unreadable lines preserved verbatim, no .tmp left behind
#   safety           no popen/system/network, the ASan+fortify build clean
#   history          no LAN IP, no token, no internal hostname in git history
#
# Exit code 0 = everything passed.

set -u

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

BIN=./plugin_memory
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 500)"
    fi
}

check_not() { # check_not <desc> <forbidden-substring> <actual>
    if printf '%s' "$3" | grep -F -q -- "$2"; then
        fail "$1 (must NOT contain: $2)"; printf '       got: %s\n' "$(printf '%s' "$3" | head -c 400)"
    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|Content-Disposition):/) { 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 500)"
    fi
}

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

# 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)"
}

# mcp <lines...> - run a JSON-RPC session and print one response per line.
mcp() {
    printf '%s\n' "$@" | $BIN --mcp
}

# seed - read a heredoc of requests on stdin and discard the responses. Used by
# the sections that need a graph in place before they assert on it. It has to
# be its own function: `mcp >/dev/null <<EOF` sends the heredoc to the helper's
# printf, not to the binary, and the seed silently does nothing.
seed() {
    $BIN --mcp >/dev/null 2>&1
}

# mcp_result <line> - the .result of the single response to one request
mcp_result() {
    mcp "$1" | python3 -c "import json,sys
for l in sys.stdin:
    l=l.strip()
    if not l: continue
    d=json.loads(l)
    print(json.dumps(d.get('result', d.get('error'))))
    break"
}

# mcp_text <line> - the first content[].text of the response (the tool result)
mcp_text() {
    mcp "$1" | python3 -c "import json,sys
for l in sys.stdin:
    l=l.strip()
    if not l: continue
    d=json.loads(l)
    c=d.get('result',{}).get('content',[])
    print(c[0]['text'] if c else '')
    break"
}

# mcp_call <tool> <arguments-json> - call one tool, print its result object
mcp_call() {
    mcp "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"$1\",\"arguments\":$2}}" \
        | head -1
}

# tool_struct <tool> <arguments-json> - the structuredContent of one call
tool_struct() {
    mcp_call "$1" "$2" | python3 -c "import json,sys
d=json.loads(sys.stdin.read())
print(json.dumps(d.get('result',{}).get('structuredContent')))"
}

# ---------------------------------------------------------------- build
section "build"
if [ ! -x "$BIN" ]; then
    echo "  building native binary..."
    make native >/dev/null 2>&1 || { 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/pm_$$)
mkdir -p "$WORK"
export MEMORY_FILE_PATH="$WORK/memory.jsonl"
export MEMORY_CONNECTOR_DIR="$WORK"

# Empty the store. Every section starts from here so an assertion can never
# pass because of something a previous section left behind.
reset_graph() {
    rm -f "$WORK"/memory.jsonl "$WORK"/memory.jsonl.tmp.* "$WORK"/memory.jsonl.lock 2>/dev/null
}

# ---------------------------------------------------------------- meta
section "mode 1 - discovery metadata"
M=$(body "$($BIN --meta)")
json_ok "--meta is valid JSON" "$M" "d['name']=='memory'"
check "--meta name is exactly memory" '"name":"memory"' "$M"
check "--meta desc is exactly Knowledge graph" '"desc":"Knowledge graph"' "$M"
json_ok "--meta kind is mcp" "$M" "d['kind']=='mcp'"
json_ok "--meta mcp is true" "$M" "d['mcp'] is True"
json_ok "--meta daemon is false" "$M" "d['daemon'] is False"
json_ok "--meta menus is false (connectors must not flood the dropdowns)" "$M" "d['menus'] is False"
json_ok "--meta verified is live" "$M" "d['verified']=='live'"
json_ok "--meta category is devtools" "$M" "d['category']=='devtools'"
json_ok "--meta version is 1.0.0" "$M" "d['version']=='1.0.0'"
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":"memory"' "$M2"
check_not "--meta emits no HTML" '<html' "$M"
V=$(body "$($BIN --version)")
check "--version names the binary" 'plugin_memory' "$V"
H=$(body "$($BIN --help)")
check "--help lists the modes" '--mcp' "$H"

# ---------------------------------------------------------------- auth
section "mode 2a - node authentication"
A0=$(BOT_PASSWORD=secret QUERY_STRING='action=graph' $BIN)
check "unauthenticated graph is 401" 'Status: 401 Unauthorized' "$A0"
A1=$(BOT_PASSWORD=secret QUERY_STRING='action=search&q=x' $BIN)
check "unauthenticated search is 401" 'Status: 401 Unauthorized' "$A1"
A2=$(BOT_PASSWORD=secret QUERY_STRING='' $BIN)
check "unauthenticated HTML page is 401" 'Status: 401 Unauthorized' "$A2"
_len=2
A3=$(printf '{}' | BOT_PASSWORD=secret REQUEST_METHOD=POST CONTENT_LENGTH="$_len" QUERY_STRING='action=add_entity' $BIN)
check "unauthenticated POST is 401" 'Status: 401 Unauthorized' "$A3"
A4=$(BOT_PASSWORD=secret QUERY_STRING='action=export' $BIN)
check "unauthenticated export is 401" 'Status: 401 Unauthorized' "$A4"
A5=$(BOT_PASSWORD=secret HTTP_X_BOT_PASSWORD=secret QUERY_STRING='action=graph' $BIN)
json_ok "X-Bot-Password header authenticates" "$(body "$A5")" "d['ok'] is True"
A6=$(BOT_PASSWORD=secret HTTP_AUTHORIZATION='Bearer secret' QUERY_STRING='action=graph' $BIN)
json_ok "Authorization Bearer authenticates" "$(body "$A6")" "d['ok'] is True"
A7=$(BOT_PASSWORD=secret QUERY_STRING='action=graph&pwd=secret' $BIN)
json_ok "?pwd= authenticates" "$(body "$A7")" "d['ok'] is True"
A8=$(BOT_PASSWORD=secret HTTP_X_BOT_PASSWORD=wrong QUERY_STRING='action=graph' $BIN)
check "a wrong password is still 401" 'Status: 401 Unauthorized' "$A8"
AM=$(body "$(BOT_PASSWORD=secret $BIN --meta)")
check "--meta stays unauthenticated" '"name":"memory"' "$AM"
# --mcp is a stdio server the node spawns itself; the CGI password must not
# stop it, or the router could never reach an installed connector.
AMC=$(printf '{"jsonrpc":"2.0","id":1,"method":"ping"}' | BOT_PASSWORD=secret $BIN --mcp)
check "--mcp runs even with BOT_PASSWORD set" '"id":1' "$AMC"

# ---------------------------------------------------------------- mcp handshake
section "mode 3 - MCP JSON-RPC handshake"
reset_graph
INIT=$(mcp '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}')
json_ok "initialize answers valid JSON" "$INIT" "True"
json_ok "initialize echoes the id" "$INIT" "d['id']==1"
json_ok "initialize carries protocolVersion" "$INIT" "'protocolVersion' in d['result']"
json_ok "initialize advertises tools" "$INIT" "'tools' in d['result']['capabilities']"
json_ok "initialize names the server" "$INIT" "d['result']['serverInfo']['name']=='memory-server'"
PING=$(mcp '{"jsonrpc":"2.0","id":7,"method":"ping"}')
json_ok "ping answers an empty result" "$PING" "d['result']=={} and d['id']==7"
NOTIF=$(mcp '{"jsonrpc":"2.0","method":"notifications/initialized"}')
[ -z "$NOTIF" ] && pass "a notification gets no response" || fail "notification answered: $NOTIF"
BAD=$(mcp 'this is not json')
check "bad JSON is a parse error (-32700)" '"code":-32700' "$BAD"
NOM=$(mcp '{"jsonrpc":"2.0","id":9}')
check "a request with no method is -32600" '"code":-32600' "$NOM"
UNK=$(mcp '{"jsonrpc":"2.0","id":10,"method":"bogus/method"}')
check "an unknown method is -32601" '"code":-32601' "$UNK"
RESP=$(mcp '{"jsonrpc":"2.0","id":11,"result":{}}')
[ -z "$RESP" ] && pass "an inbound response is ignored" || fail "answered a response: $RESP"
IDSTR=$(mcp '{"jsonrpc":"2.0","id":"abc","method":"ping"}')
check "a string id is echoed as a string" '"id":"abc"' "$IDSTR"

TL=$(mcp '{"jsonrpc":"2.0","id":2,"method":"tools/list"}')
json_ok "tools/list is valid JSON" "$TL" "True"
json_ok "tools/list has exactly nine tools" "$TL" "len(d['result']['tools'])==9"
json_ok "tools/list has the reference names" "$TL" \
  "sorted(t['name'] for t in d['result']['tools'])==['add_observations','create_entities','create_relations','delete_entities','delete_observations','delete_relations','open_nodes','read_graph','search_nodes']"
json_ok "every tool has an inputSchema" "$TL" \
  "all('inputSchema' in t and t['inputSchema'].get('type')=='object' for t in d['result']['tools'])"
json_ok "read_graph is marked readOnly" "$TL" \
  "[t for t in d['result']['tools'] if t['name']=='read_graph'][0]['annotations']['readOnlyHint'] is True"
json_ok "delete_entities is marked destructive" "$TL" \
  "[t for t in d['result']['tools'] if t['name']=='delete_entities'][0]['annotations']['destructiveHint'] is True"
check "create_entities description warns about skipping" "is skipped and its observations are not added" "$TL"
check "delete_entities description points at delete_relations" "use delete_relations" "$TL"
check "delete_relations says all three fields must match" "exactly on all three fields" "$TL"
SCHEMA=$(body "$($BIN --schema)")
json_ok "--schema is the same nine tools" "$SCHEMA" "len(d)==9"

RL=$(mcp '{"jsonrpc":"2.0","id":3,"method":"resources/list"}')
check "resources/list serves the graph URI" 'memory://knowledge-graph' "$RL"
RR=$(mcp '{"jsonrpc":"2.0","id":4,"method":"resources/read","params":{"uri":"memory://knowledge-graph"}}')
json_ok "resources/read returns contents" "$RR" "len(d['result']['contents'])==1"
json_ok "resources/read text parses as a graph" "$RR" \
  "json.loads(d['result']['contents'][0]['text'])=={'entities':[],'relations':[]}"
RBAD=$(mcp '{"jsonrpc":"2.0","id":5,"method":"resources/read","params":{"uri":"other://x"}}')
check "an unknown resource uri is refused" 'Unknown resource' "$RBAD"

# ---------------------------------------------------------------- create_entities
section "create_entities"
reset_graph
R=$(tool_struct create_entities '{"entities":[{"name":"Alice","entityType":"person","observations":["likes tea"]}]}')
json_ok "one entity created" "$R" "len(d['entities'])==1 and d['entities'][0]['name']=='Alice'"
json_ok "observations are stored" "$R" "d['entities'][0]['observations']==['likes tea']"
R=$(tool_struct create_entities '{"entities":[{"name":"Alice","entityType":"person","observations":["dup"]},{"name":"Bob","entityType":"person","observations":[]}]}')
json_ok "an existing name is skipped" "$R" "len(d['entities'])==1 and d['entities'][0]['name']=='Bob'"
json_ok "the skip is reported in skipped" "$R" "d['skipped']==['Alice']"
NOTICE=$(mcp_call create_entities '{"entities":[{"name":"Bob","entityType":"person","observations":["x"]}]}' \
    | python3 -c "import json,sys;d=json.loads(sys.stdin.read());c=d['result']['content'];print(c[1]['text'] if len(c)>1 else '')")
check "the skip is also said in plain words" "Skipped 1 entity that already exists: Bob" "$NOTICE"
check "the notice tells the agent to use add_observations" "add_observations" "$NOTICE"
R=$(tool_struct create_entities '{"entities":[{"name":"Cara","entityType":"p","observations":["a"]},{"name":"Cara","entityType":"p","observations":["b"]}]}')
json_ok "a repeat within one batch is skipped once" "$R" \
  "len(d['entities'])==1 and d['entities'][0]['name']=='Cara'"
json_ok "the in-batch repeat is in skipped" "$R" "d['skipped']==['Cara']"
R=$(tool_struct create_entities '{"entities":[{"name":"Cara","entityType":"p","observations":["c"]}]}')
json_ok "Cara kept only the first observation" "$R" \
  "d['entities']==[]"
R=$(tool_struct create_entities '{"entities":[{"name":"Cara","entityType":"p","observations":["c"]}]}')
json_ok "a re-submit creates nothing" "$R" "d['entities']==[]"
ERR=$(mcp_call create_entities '{"wrong":[1]}' \
    | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['isError'],d['result']['content'][0]['text'])")
check "missing entities is an error" "Missing required parameter: entities" "$ERR"
ERR=$(mcp_call create_entities '{"entities":[{"name":"Q"}]}' \
    | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['isError'],d['result']['content'][0]['text'])")
check "an entity with no entityType is refused" "True" "$ERR"
check "and the message says why" "non-empty name and entityType" "$ERR"
ERR2=$(mcp_call create_entities '{"entities":"nope"}' \
    | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['content'][0]['text'])")
check "entities must be an array" "Missing required parameter: entities" "$ERR2"

# ---------------------------------------------------------------- create_relations
section "create_relations"
reset_graph
seed <<'EOF'
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"create_entities","arguments":{"entities":[{"name":"Alice","entityType":"person","observations":[]},{"name":"Bob","entityType":"person","observations":[]}]}}}
EOF
R=$(tool_struct create_relations '{"relations":[{"from":"Alice","to":"Bob","relationType":"knows"}]}')
json_ok "relation created" "$R" "len(d['relations'])==1 and d['relations'][0]['relationType']=='knows'"
R=$(tool_struct create_relations '{"relations":[{"from":"Alice","to":"Bob","relationType":"knows"}]}')
json_ok "the same triple is not added twice" "$R" "d['relations']==[]"
R=$(tool_struct create_relations '{"relations":[{"from":"Alice","to":"Ghost","relationType":"knows"}]}')
# a failed tool call carries no structuredContent, so tool_struct prints the
# JSON null - the shape that means "this call errored, look at the text".
[ "$R" = "null" ] && pass "a missing 'to' is an error" || fail "missing to: $R"
ERR=$(mcp_call create_relations '{"relations":[{"from":"Alice","to":"Ghost","relationType":"knows"}]}' \
    | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['content'][0]['text'])")
check "the error names the missing entity" "Entity with name Ghost not found" "$ERR"
ERR=$(mcp_call create_relations '{"relations":[{"from":"Ghost","to":"Alice","relationType":"knows"}]}' \
    | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['content'][0]['text'])")
check "and it names a missing 'from' too" "Entity with name Ghost not found" "$ERR"
# nothing written by the failed call
G=$(tool_struct read_graph '{}')
json_ok "a failed create_relations wrote nothing" "$G" "len(d['relations'])==1"
R=$(tool_struct create_relations '{"relations":[{"from":"Alice","to":"Bob","relationType":"likes"},{"from":"Alice","to":"Bob","relationType":"likes"}]}')
json_ok "an in-batch duplicate is added once" "$R" "len(d['relations'])==1"
G=$(tool_struct read_graph '{}')
json_ok "so the graph has two relations now" "$G" "len(d['relations'])==2"

# ---------------------------------------------------------------- add_observations
section "add_observations"
R=$(tool_struct add_observations '{"observations":[{"entityName":"Alice","contents":["runs","runs","reads"]}]}')
json_ok "a repeat inside one call is added once" "$R" \
  "d['results'][0]['addedObservations']==['runs','reads']"
R=$(tool_struct add_observations '{"observations":[{"entityName":"Alice","contents":["runs"]}]}')
json_ok "an observation the entity already has is not added" "$R" \
  "d['results'][0]['addedObservations']==[]"
ERR=$(mcp_call add_observations '{"observations":[{"entityName":"Ghost","contents":["x"]}]}' \
    | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['content'][0]['text'])")
check "an unknown entity is an error" "Entity with name Ghost not found" "$ERR"
# all-or-nothing: the second group is unknown, so the first must not persist
G0=$(tool_struct read_graph '{}' )
ERR=$(mcp_call add_observations '{"observations":[{"entityName":"Alice","contents":["should-not-stick"]},{"entityName":"Ghost","contents":["x"]}]}' \
    | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['content'][0]['text'])")
check "one unknown entity fails the whole call" "Entity with name Ghost not found" "$ERR"
G=$(tool_struct read_graph '{}')
json_ok "and nothing is written" "$G" \
  "all('should-not-stick' not in e['observations'] for e in d['entities'])"

# ---------------------------------------------------------------- read tools
section "read_graph / search_nodes / open_nodes"
reset_graph
seed <<'EOF'
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"create_entities","arguments":{"entities":[{"name":"Tea","entityType":"drink","observations":["Earl Grey","hot"]},{"name":"Cup","entityType":"object","observations":["ceramic"]},{"name":"Zebra","entityType":"animal","observations":["striped"]}]}}}
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"create_relations","arguments":{"relations":[{"from":"Tea","to":"Cup","relationType":"served_in"},{"from":"Zebra","to":"Cup","relationType":"knocked_over"}]}}}
EOF
G=$(tool_struct read_graph '{}')
json_ok "read_graph returns every entity" "$G" "len(d['entities'])==3"
json_ok "read_graph returns every relation" "$G" "len(d['relations'])==2"
G=$(tool_struct read_graph '{"entityTypes":["drink"]}')
json_ok "entityTypes filters to that type" "$G" "len(d['entities'])==1 and d['entities'][0]['name']=='Tea'"
json_ok "entityTypes keeps relations touching a kept entity" "$G" \
  "len(d['relations'])==1 and d['relations'][0]['from']=='Tea'"
G=$(tool_struct read_graph '{"observationLimit":0}')
json_ok "observationLimit 0 returns no observations" "$G" \
  "all(e['observations']==[] for e in d['entities'])"
json_ok "observationLimit 0 still gives the count" "$G" \
  "[e for e in d['entities'] if e['name']=='Tea'][0]['observationCount']==2"
G=$(tool_struct read_graph '{}')
json_ok "without the option there is no observationCount key" "$G" \
  "all('observationCount' not in e for e in d['entities'])"
G=$(tool_struct read_graph '{"observationLimit":1}')
json_ok "observationLimit 1 truncates to the first" "$G" \
  "[e for e in d['entities'] if e['name']=='Tea'][0]['observations']==['Earl Grey']"
ERR=$(mcp_call read_graph '{"observationLimit":-1}' \
    | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['content'][0]['text'])")
check "a negative observationLimit is refused" "integer >= 0" "$ERR"
ERR=$(mcp_call read_graph '{"entityTypes":[]}' \
    | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['content'][0]['text'])")
check "an empty entityTypes is refused" "non-empty array" "$ERR"

S=$(tool_struct search_nodes '{"query":"earl"}')
json_ok "search matches an observation, case-insensitively" "$S" \
  "len(d['entities'])==1 and d['entities'][0]['name']=='Tea'"
S=$(tool_struct search_nodes '{"query":"DRINK"}')
json_ok "search matches the type, case-insensitively" "$S" \
  "len(d['entities'])==1 and d['entities'][0]['name']=='Tea'"
S=$(tool_struct search_nodes '{"query":"ze"}')
json_ok "search matches a substring of a name" "$S" \
  "len(d['entities'])==1 and d['entities'][0]['name']=='Zebra'"
S=$(tool_struct search_nodes '{"query":"Earl Grey"}')
json_ok "search includes relations touching a match" "$S" \
  "len(d['relations'])==1 and d['relations'][0]['from']=='Tea'"
S=$(tool_struct search_nodes '{"query":"ceramic"}')
json_ok "a match found only by observation still brings its relations" "$S" \
  "any(r['to']=='Cup' for r in d['relations'])"
S=$(tool_struct search_nodes '{"query":"striped"}')
json_ok "either-endpoint rule: a relation to an unrequested node survives" "$S" \
  "len(d['relations'])==1 and d['relations'][0]['from']=='Zebra'"
S=$(tool_struct search_nodes '{"query":"e","limit":1}')
json_ok "limit caps the matches, first in stored order" "$S" \
  "len(d['entities'])==1 and d['entities'][0]['name']=='Tea'"
S=$(tool_struct search_nodes '{"query":"nothing-matches-this"}')
json_ok "a search with no match is an empty graph, not an error" "$S" \
  "d['entities']==[] and d['relations']==[]"
ERR=$(mcp_call search_nodes '{"q":"x"}' \
    | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['content'][0]['text'])")
check "search_nodes needs query" "Missing required parameter: query" "$ERR"
ERR=$(mcp_call search_nodes '{"query":"x","limit":0}' \
    | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['content'][0]['text'])")
check "limit 0 is refused (min 1)" "integer >= 1" "$ERR"

O=$(tool_struct open_nodes '{"names":["Tea","Ghost"]}')
json_ok "open_nodes returns the exact names" "$O" \
  "len(d['entities'])==1 and d['entities'][0]['name']=='Tea'"
json_ok "open_nodes keeps relations to nodes not asked for" "$O" \
  "any(r['from']=='Tea' and r['to']=='Cup' for r in d['relations'])"
O=$(tool_struct open_nodes '{"names":["Cup"]}')
json_ok "open_nodes brings BOTH directions" "$O" \
  "len(d['relations'])==2"
O=$(tool_struct open_nodes '{"names":["Ghost","Nowhere"]}')
json_ok "names that miss are skipped, not an error" "$O" "d['entities']==[] and d['relations']==[]"

# ---------------------------------------------------------------- delete tools
section "delete_entities / delete_observations / delete_relations"
reset_graph
seed <<'EOF'
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"create_entities","arguments":{"entities":[{"name":"A","entityType":"x","observations":["o1","o2","o3"]},{"name":"B","entityType":"x","observations":[]},{"name":"C","entityType":"x","observations":[]}]}}}
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"create_relations","arguments":{"relations":[{"from":"A","to":"B","relationType":"k"},{"from":"C","to":"A","relationType":"k2"},{"from":"B","to":"C","relationType":"k3"}]}}}
EOF
M=$(mcp '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"delete_entities","arguments":{"entityNames":["A","Ghost"]}}}' | head -1)
MSG=$(printf '%s' "$M" | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['structuredContent']['message'])")
check "delete_entities reports deleted and not found" "Deleted 1 of 2 entities. Not found: Ghost" "$MSG"
G=$(tool_struct read_graph '{}')
json_ok "the entity is gone" "$G" "all(e['name']!='A' for e in d['entities'])"
json_ok "relations touching it are cascaded" "$G" "len(d['relations'])==1"
M=$(mcp '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"delete_entities","arguments":{"entityNames":["B"]}}}' | head -1)
MSG=$(printf '%s' "$M" | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['structuredContent']['message'])")
check "a clean delete says so" "Entities deleted successfully" "$MSG"
M=$(mcp '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"delete_observations","arguments":{"deletions":[{"entityName":"C","observations":["nope"]},{"entityName":"Ghost","observations":["x"]}]}}}' | head -1)
MSG=$(printf '%s' "$M" | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['structuredContent']['message'])")
check "delete_observations counts and names the missing entity" \
  "Deleted 0 of 2 observations. Entities not found: Ghost" "$MSG"
reset_graph
seed <<'EOF'
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"create_entities","arguments":{"entities":[{"name":"A","entityType":"x","observations":["keep","drop","drop2"]}]}}}
EOF
M=$(mcp '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"delete_observations","arguments":{"deletions":[{"entityName":"A","observations":["drop","nope"]}]}}}' | head -1)
MSG=$(printf '%s' "$M" | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['structuredContent']['message'])")
check "delete_observations reports the partial count" "Deleted 1 of 2 observations" "$MSG"
check_not "a partial count with a known entity names none missing" "Entities not found" "$MSG"
M=$(mcp '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"delete_observations","arguments":{"deletions":[{"entityName":"A","observations":["keep"]}]}}}' | head -1)
MSG=$(printf '%s' "$M" | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['structuredContent']['message'])")
check "a clean observation delete says so" "Observations deleted successfully" "$MSG"
reset_graph
seed <<'EOF'
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"create_entities","arguments":{"entities":[{"name":"A","entityType":"x","observations":[]},{"name":"B","entityType":"x","observations":[]}]}}}
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"create_relations","arguments":{"relations":[{"from":"A","to":"B","relationType":"k"}]}}}
EOF
M=$(mcp '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"delete_relations","arguments":{"relations":[{"from":"A","to":"B","relationType":"nope"},{"from":"B","to":"A","relationType":"k"}]}}}' | head -1)
MSG=$(printf '%s' "$M" | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['structuredContent']['message'])")
check "delete_relations counts what actually matched" "Deleted 0 of 2 relations. The rest matched nothing." "$MSG"
M=$(mcp '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"delete_relations","arguments":{"relations":[{"from":"A","to":"B","relationType":"k"}]}}}' | head -1)
MSG=$(printf '%s' "$M" | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['structuredContent']['message'])")
check "a clean relation delete says so" "Relations deleted successfully" "$MSG"
G=$(tool_struct read_graph '{}')
json_ok "delete_relations keeps the entities" "$G" "len(d['entities'])==2"

# a tool failure is a RESULT with isError, never a JSON-RPC error
ERRLINE=$(mcp '{"jsonrpc":"2.0","id":42,"method":"tools/call","params":{"name":"read_graph","arguments":{"observationLimit":-5}}}' | head -1)
check "a tool failure still answers with a result" '"result"' "$ERRLINE"
check "and marks isError" '"isError":true' "$ERRLINE"
check "and keeps the id" '"id":42' "$ERRLINE"
UNKNOWNTOOL=$(mcp '{"jsonrpc":"2.0","id":43,"method":"tools/call","params":{"name":"no_such_tool"}}' | head -1)
check "an unknown tool name is a JSON-RPC error" '"code":-32602' "$UNKNOWNTOOL"

# ---------------------------------------------------------------- persistence
section "persistence across processes"
reset_graph
seed <<'EOF'
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"create_entities","arguments":{"entities":[{"name":"Persist","entityType":"check","observations":["written by process one"]}]}}}
EOF
[ -f "$MEMORY_FILE_PATH" ] && pass "the graph file is created" || fail "graph file missing"
FIRSTLINE=$(head -1 "$MEMORY_FILE_PATH")
check "it is JSONL with a type tag" '"type":"entity"' "$FIRSTLINE"
check "one line holds one entity" '"name":"Persist"' "$FIRSTLINE"
# a completely new process reads it back
G=$(tool_struct read_graph '{}')
json_ok "a second process reads the graph" "$G" \
  "len(d['entities'])==1 and d['entities'][0]['observations']==['written by process one']"
# and so does the HTTP API
S=$(api 'action=stats')
json_ok "the HTTP API sees the same graph" "$S" "d['entities']==1 and d['observations']==1"
# an appended unreadable line survives every write
printf 'this line is not json at all\n' >> "$MEMORY_FILE_PATH"
seed <<'EOF'
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"add_observations","arguments":{"observations":[{"entityName":"Persist","contents":["one more"]}]}}}
EOF
check "an unparseable line is preserved verbatim" "this line is not json at all" "$(cat "$MEMORY_FILE_PATH")"
S=$(api 'action=stats')
json_ok "and counted, so the operator can see it" "$S" "d['unreadable_lines']==1"
LEFT=$(ls "$WORK" | grep -c '\.tmp' || true)
[ "$LEFT" = "0" ] && pass "no temp file is left behind" || fail "$LEFT temp file(s) left"
# a save that keeps the operator's file mode
chmod 600 "$MEMORY_FILE_PATH"
seed <<'EOF'
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"add_observations","arguments":{"observations":[{"entityName":"Persist","contents":["mode probe"]}]}}}
EOF
MODE=$(stat -c '%a' "$MEMORY_FILE_PATH" 2>/dev/null || echo unknown)
[ "$MODE" = "600" ] && pass "a 0600 graph file stays 0600 after a save" || fail "mode became $MODE"
# unicode and punctuation round trip
reset_graph
seed <<'EOF'
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"create_entities","arguments":{"entities":[{"name":"Uni \"quote\" \\ back","entityType":"t","observations":["tab\there","newline\nhere","emoji \u00e9\u00e8"]}]}}}
EOF
G=$(tool_struct read_graph '{}')
json_ok "quotes, backslashes, tabs and newlines round trip" "$G" \
  "d['entities'][0]['name']=='Uni \"quote\" \\\\ back' and d['entities'][0]['observations'][1]=='newline\nhere'"

# ---------------------------------------------------------------- http api
section "mode 2b - the JSON API"
reset_graph
S=$(api 'action=stats')
json_ok "stats on an empty graph is ok" "$S" "d['ok'] is True and d['entities']==0 and d['file_exists'] is False"
check "stats is served as JSON" 'Content-Type: application/json' "$(apiraw 'action=stats')"
AE=$(api_post 'action=add_entity' '{"name":"Api","entityType":"thing","observations":["from json body"]}')
json_ok "add_entity accepts a JSON body" "$AE" "d['ok'] is True and d['entities'][0]['name']=='Api'"
AE=$(api 'action=add_entity&name=Qs&entityType=thing&observations=one|two')
json_ok "add_entity accepts a query string too" "$AE" "d['ok'] is True"
G=$(api 'action=graph')
json_ok "graph returns both" "$G" "len(d['entities'])==2"
S=$(api 'action=search&q=from json')
json_ok "search finds by observation" "$S" "len(d['entities'])==1 and d['entities'][0]['name']=='Api'"
EN=$(api 'action=entity&name=Api')
json_ok "entity returns one" "$EN" "len(d['entities'])==1"
EN=$(api 'action=entity')
json_ok "entity with no name is a 400 shape" "$EN" "d['ok'] is False and 'error' in d"
AO=$(api_post 'action=add_obs' '{"name":"Api","contents":["third","third"]}')
json_ok "add_obs dedupes within one call" "$AO" "d['results'][0]['addedObservations']==['third']"
AR=$(api 'action=add_relation&from=Api&to=Qs&relationType=relates')
json_ok "add_relation works from a query string" "$AR" "len(d['relations'])==1"
AR=$(api 'action=add_relation&from=Api&to=Nope&relationType=relates')
json_ok "add_relation reports the missing end" "$AR" "d['ok'] is False and 'not found' in d['error']"
DR=$(api 'action=delete_relation&from=Api&to=Qs&relationType=relates')
json_ok "delete_relation works" "$DR" "d['ok'] is True"
DO=$(api 'action=delete_obs&name=Api&observations=from json')
json_ok "delete_obs reports the partial count" "$DO" "d['ok'] is True"
DE=$(api 'action=delete_entity&name=Qs')
json_ok "delete_entity reports success" "$DE" "d['ok'] is True"
UA=$(api 'action=bogus')
json_ok "an unknown action is refused" "$UA" "d['ok'] is False"
BN=$(printf 'notjson' | REQUEST_METHOD=POST CONTENT_LENGTH="7" QUERY_STRING='action=add_entity' $BIN)
check "a body that is not JSON is a 400" 'Status: 400 Bad Request' "$BN"
_len=$(printf '%s' '{"name":"Big","entityType":"t","observations":["x"]}' | wc -c | tr -d ' ')
BC=$(printf '%s' '{"name":"Big","entityType":"t","observations":["x"]}' | REQUEST_METHOD=POST CONTENT_LENGTH="$_len" QUERY_STRING='action=add_entity' $BIN)
check "POST with a JSON body works" '"ok":true' "$BC"
# action from the body, not the query
BC2=$(printf '%s' '{"action":"stats"}' | REQUEST_METHOD=POST CONTENT_LENGTH="18" QUERY_STRING='' $BIN)
check "action can arrive in the body" '"ok":true' "$BC2"
# format=json with no action must not clobber anything
FJ=$(body "$(QUERY_STRING='format=json' $BIN)")
json_ok "format=json alone serves the graph" "$FJ" "'entities' in d"
# export
EX=$(QUERY_STRING='action=export' $BIN)
check "export is offered as a download" 'attachment; filename="memory.jsonl"' "$EX"
check "export is text/plain" 'text/plain' "$EX"
check "export carries the JSONL" '"type":"entity"' "$EX"
# tools action
TO=$(api 'action=tools')
json_ok "action=tools lists the nine tools" "$TO" "d['ok'] is True and len(d['tools'])==9"
json_ok "action=tools says it is an mcp connector" "$TO" "d['kind']=='mcp'"

# html
H=$(apiraw '')
check "GET serves HTML" 'Content-Type: text/html' "$H"
check "HTML has a CSP" 'Content-Security-Policy' "$H"
check "HTML is same-origin frameable only" 'X-Frame-Options: SAMEORIGIN' "$H"
check "HTML declares the bot font token" 'var(--font)' "$H"
check_not "the page loads no CDN script" '<script src=' "$H"
check_not "the page references cdnjs" 'cdnjs' "$H"
if printf '%s' "$H" | python3 -c "
import sys
t=sys.stdin.buffer.read().decode('utf-8','replace')
bad=[c for c in t if ord(c)>0x2100]
sys.exit(1 if bad else 0)" 2>/dev/null; then pass "the page has no emoji"; else fail "the page has an emoji"; fi
check "the page talks to the right route" "plugin_memory" "$H"
check "the page branches on the hub proxy route" "'plugins'" "$H"

# ---------------------------------------------------------------- source guards
section "source guards"
SRC_ALL=$(cat src/plugin_memory.c src/graph.c src/tools.c src/api.c src/memory.h)
check_not "no popen() anywhere" 'popen(' "$SRC_ALL"
check_not "no system() anywhere" 'system(' "$SRC_ALL"
check_not "no exec family" 'execv' "$SRC_ALL"
check_not "no socket()" 'socket(' "$SRC_ALL"
check_not "no libcurl include" '#include <curl' "$SRC_ALL"
check_not "no curl_easy calls" 'curl_easy' "$SRC_ALL"
check_not "no fork()" 'fork()' "$SRC_ALL"
check_not "no gets()" 'gets(' "$SRC_ALL"
WIN32=$(cat src/plugin_memory.c)
check "Windows forces binary stdio" '_O_BINARY' "$WIN32"
check "the graph dir is under .scorpiox/connectors" '.scorpiox/connectors' "$(cat src/graph.c)"
check "MEMORY_FILE_PATH overrides the location" 'MEMORY_FILE_PATH' "$(cat src/graph.c)"
check "/workspace is preferred when present" '/workspace' "$(cat src/graph.c)"
check "a relative MEMORY_FILE_PATH may not traverse" "may not contain '..'" "$(cat src/graph.c)"

# ---------------------------------------------------------------- sanitizers
section "sanitizers (ASan + UBSan + _FORTIFY_SOURCE=2)"
ASAN=./plugin_memory.asan
if make asan >/dev/null 2>&1 && [ -x "$ASAN" ]; then
    pass "the sanitizer build compiles"
    SWORK=$(mktemp -d 2>/dev/null || echo /tmp/pmasan_$$)
    runasan() {
        MEMORY_FILE_PATH="$SWORK/g.jsonl" MEMORY_CONNECTOR_DIR="$SWORK" "$ASAN" "$@"
    }
    AOUT=$(printf '%s\n' \
      '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' \
      '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"create_entities","arguments":{"entities":[{"name":"A","entityType":"x","observations":["o1","o2","o3"]},{"name":"A","entityType":"x","observations":["dup"]}]}}}' \
      '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"create_relations","arguments":{"relations":[{"from":"A","to":"B","relationType":"k"}]}}}' \
      '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"create_entities","arguments":{"entities":[{"name":"B","entityType":"x","observations":[]}]}}}' \
      '{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"create_relations","arguments":{"relations":[{"from":"A","to":"B","relationType":"k"}]}}}' \
      '{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"add_observations","arguments":{"observations":[{"entityName":"A","contents":["o1","new","new"]}]}}}' \
      '{"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"delete_entities","arguments":{"entityNames":["A","Ghost","Ghost"]}}}' \
      '{"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"delete_observations","arguments":{"deletions":[{"entityName":"B","observations":["x"]},{"entityName":"Ghost","observations":["y"]}]}}}' \
      '{"jsonrpc":"2.0","id":9,"method":"tools/call","params":{"name":"delete_relations","arguments":{"relations":[{"from":"A","to":"B","relationType":"k"},{"from":"X","to":"Y","relationType":"k"}]}}}' \
      '{"jsonrpc":"2.0","id":10,"method":"tools/call","params":{"name":"read_graph","arguments":{"observationLimit":0}}}' \
      '{"jsonrpc":"2.0","id":11,"method":"tools/call","params":{"name":"search_nodes","arguments":{"query":"a","limit":1,"observationLimit":1}}}' \
      '{"jsonrpc":"2.0","id":12,"method":"tools/call","params":{"name":"open_nodes","arguments":{"names":["A","B","Ghost"],"observationLimit":0}}}' \
      '{"jsonrpc":"2.0","id":13,"method":"tools/call","params":{"name":"create_entities","arguments":{"entities":[{"name":"Uni \"q\" \\\\ b","entityType":"t","observations":["tab\there"]}]}}}' \
      '{"jsonrpc":"2.0","id":14,"method":"tools/call","params":{"name":"read_graph","arguments":{}}}' \
      '{"jsonrpc":"2.0","id":15,"method":"tools/call","params":{"name":"read_graph","arguments":{"entityTypes":["t","x"]}}}' \
      '{"jsonrpc":"2.0","id":16,"method":"tools/call","params":{"name":"create_relations","arguments":{"relations":"bad"}}}' \
      '{"jsonrpc":"2.0","id":17,"method":"tools/call","params":{"name":"add_observations","arguments":{}}}' \
      '{"jsonrpc":"2.0","id":18,"method":"tools/call","params":{"name":"delete_entities","arguments":{}}}' \
      '{"jsonrpc":"2.0","id":19,"method":"resources/read","params":{"uri":"memory://knowledge-graph"}}' \
      '{"jsonrpc":"2.0","id":20,"method":"tools/call","params":{"name":"create_entities","arguments":{"entities":[{"name":"A","entityType":"x","observations":[]},{"name":"A","entityType":"x","observations":[]},{"name":"A","entityType":"x","observations":[]}]}}}' \
      | MEMORY_FILE_PATH="$SWORK/g.jsonl" MEMORY_CONNECTOR_DIR="$SWORK" "$ASAN" --mcp 2>&1)
    check_not "the sanitizer run reports no leak" 'ERROR: AddressSanitizer' "$AOUT"
    check_not "the sanitizer run reports no runtime error" 'runtime error:' "$AOUT"
    check_not "the sanitizer run reports no use-after-free" 'heap-use-after-free' "$AOUT"
    check_not "the sanitizer run reports no buffer overflow" 'buffer-overflow' "$AOUT"
    # the fortify build of the CGI path too
    COUT=$(QUERY_STRING='action=stats' MEMORY_FILE_PATH="$SWORK/c.jsonl" MEMORY_CONNECTOR_DIR="$SWORK" "$ASAN" 2>&1)
    check_not "the CGI path is clean under ASan too" 'ERROR: AddressSanitizer' "$COUT"
    POUT=$(printf '%s\n' 'garbage line' '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"read_graph","arguments":{}}}' \
      | MEMORY_FILE_PATH="$SWORK/p.jsonl" MEMORY_CONNECTOR_DIR="$SWORK" "$ASAN" --mcp 2>&1)
    check_not "a garbage stdin line is clean under ASan" 'ERROR: AddressSanitizer' "$POUT"
    rm -rf "$SWORK"
else
    fail "the sanitizer build did not produce ./plugin_memory.asan"
fi

# ---------------------------------------------------------------- cross targets
section "cross-target builds (when the toolchain is here)"
if command -v musl-gcc >/dev/null 2>&1; then
    make musl >/dev/null 2>&1 && pass "musl static build" || fail "musl build"
    [ -x ./plugin_memory.musl ] && {
        MOUT=$(MEMORY_FILE_PATH="$WORK/musl.jsonl" ./plugin_memory.musl --meta)
        check "the musl binary runs --meta" '"kind":"mcp"' "$MOUT"
        file ./plugin_memory.musl 2>/dev/null | grep -q 'statically linked' \
            && pass "the musl artifact is static" || fail "the musl artifact is not static"
    }
else
    echo "  skip musl (no musl-gcc here)"
fi
if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
    make win64 >/dev/null 2>&1 && pass "MinGW win64 build" || fail "win64 build"
    [ -f ./plugin_memory.exe ] && {
        head -c 2 ./plugin_memory.exe | grep -q 'MZ' \
            && pass "the PE artifact starts with MZ" || fail "the PE header is wrong"
    }
else
    echo "  skip win64 (no MinGW here)"
fi
if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
    make arm64 >/dev/null 2>&1 && pass "aarch64 cross build" || fail "arm64 build"
else
    echo "  skip arm64 (no aarch64-linux-gnu-gcc here)"
fi

# ---------------------------------------------------------------- history audit
section "git history secret and IP audit"
if [ -d .git ]; then
    ALL=$(mktemp)
    git log -p --all > "$ALL" 2>/dev/null || : > "$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 "plugingit token"      'plugingit_[A-Za-z0-9]{20,}'
    audit "embedded git creds"   'scorpioxinc:[A-Za-z0-9]{20,}'
    audit "sshpass default"      'Xbox''one09''09'
    audit "run token assignment" 'RUNNER_'"PASS="
    INTERNAL="int""el-ultra""2|macmi""ni2018""i5|laza""rus"
    audit "internal hostname"    "$INTERNAL"
    rm -f "$ALL"
else
    echo "  skip history audit (not a git checkout)"
fi

section "brand casing"
BRAND=$(cat README.md docs/usage.md plugin.json src/ui.html 2>/dev/null || true)
BADCASE=$(printf '%s' "$BRAND" | grep -Eo 'Scorpio''x Bot|Scorpio''X Bot|SCORPIO BOT' | sort -u | head -3 || true)
[ -z "$BADCASE" ] && pass "the product is only ever SCORPIOX BOT" || fail "bad casing: $BADCASE"

# ---------------------------------------------------------------- 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
    exit 1
fi
exit 0
