scorpiox-bot-plugin-memory
←run.shbash
706 lines · 42 KBHEADBlameDownload
1#!/bin/sh
2# tests/run.sh - offline checks for plugin_memory across all its modes.
3#
4# Everything runs against ./plugin_memory with MEMORY_FILE_PATH pointing at a
5# throwaway file, so the suite never touches anyone's real graph. It proves the
6# public contract end to end:
7#
8# --meta the connector metadata the router and /plugins read
9# --mcp a full JSON-RPC 2.0 session, all nine tools, the
10# skip/not-found/dedupe semantics, notifications, bad JSON
11# CGI JSON API the same nine operations behind ?action= and POST, with
12# the node password on every one of them
13# HTML the page, with no CDN and no <script src=>
14# persistence a value written by one process read back by the next,
15# unreadable lines preserved verbatim, no .tmp left behind
16# safety no popen/system/network, the ASan+fortify build clean
17# history no LAN IP, no token, no internal hostname in git history
18#
19# Exit code 0 = everything passed.
20
21set -u
22
23ROOT=$(cd "$(dirname "$0")/.." && pwd)
24cd "$ROOT" || exit 1
25
26BIN=./plugin_memory
27PASS=0
28FAIL=0
29
30if [ -t 1 ]; then
31 C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
32else
33 C_OK=; C_BAD=; C_B=; C_0=
34fi
35pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
36fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
37
38check() { # check <desc> <expected-substring> <actual>
39 if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
40 fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 500)"
41 fi
42}
43
44check_not() { # check_not <desc> <forbidden-substring> <actual>
45 if printf '%s' "$3" | grep -F -q -- "$2"; then
46 fail "$1 (must NOT contain: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 400)"
47 else pass "$1"; fi
48}
49
50section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
51
52# strip CGI headers if present, drop CRs, keep the payload
53body() {
54 printf '%s\n' "$1" | tr -d '\r' | awk '
55 BEGIN { inhdr = 0 }
56 NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|X-Frame-Options|Content-Security-Policy|Content-Disposition):/) { inhdr = 1; next }
57 inhdr && $0 == "" { inhdr = 0; next }
58 inhdr { next }
59 { print }
60 '
61}
62
63json_ok() { # json_ok <desc> <json> [python-expression]
64 expr=${3:-True}
65 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
66 pass "$1"
67 else
68 fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 500)"
69 fi
70}
71
72api() { body "$(QUERY_STRING="$1" $BIN)"; }
73apiraw() { QUERY_STRING="$1" $BIN; }
74
75# api_post <query-string> <json-payload>
76api_post() {
77 _len=$(printf '%s' "$2" | wc -c | tr -d ' ')
78 body "$(printf '%s' "$2" | REQUEST_METHOD=POST CONTENT_LENGTH="$_len" QUERY_STRING="$1" $BIN)"
79}
80
81# mcp <lines...> - run a JSON-RPC session and print one response per line.
82mcp() {
83 printf '%s\n' "$@" | $BIN --mcp
84}
85
86# seed - read a heredoc of requests on stdin and discard the responses. Used by
87# the sections that need a graph in place before they assert on it. It has to
88# be its own function: `mcp >/dev/null <<EOF` sends the heredoc to the helper's
89# printf, not to the binary, and the seed silently does nothing.
90seed() {
91 $BIN --mcp >/dev/null 2>&1
92}
93
94# mcp_result <line> - the .result of the single response to one request
95mcp_result() {
96 mcp "$1" | python3 -c "import json,sys
97for l in sys.stdin:
98 l=l.strip()
99 if not l: continue
100 d=json.loads(l)
101 print(json.dumps(d.get('result', d.get('error'))))
102 break"
103}
104
105# mcp_text <line> - the first content[].text of the response (the tool result)
106mcp_text() {
107 mcp "$1" | python3 -c "import json,sys
108for l in sys.stdin:
109 l=l.strip()
110 if not l: continue
111 d=json.loads(l)
112 c=d.get('result',{}).get('content',[])
113 print(c[0]['text'] if c else '')
114 break"
115}
116
117# mcp_call <tool> <arguments-json> - call one tool, print its result object
118mcp_call() {
119 mcp "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"$1\",\"arguments\":$2}}" \
120 | head -1
121}
122
123# tool_struct <tool> <arguments-json> - the structuredContent of one call
124tool_struct() {
125 mcp_call "$1" "$2" | python3 -c "import json,sys
126d=json.loads(sys.stdin.read())
127print(json.dumps(d.get('result',{}).get('structuredContent')))"
128}
129
130# ---------------------------------------------------------------- build
131section "build"
132if [ ! -x "$BIN" ]; then
133 echo " building native binary..."
134 make native >/dev/null 2>&1 || { echo " build failed"; exit 1; }
135fi
136[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing"
137
138WORK=$(mktemp -d 2>/dev/null || echo /tmp/pm_$$)
139mkdir -p "$WORK"
140export MEMORY_FILE_PATH="$WORK/memory.jsonl"
141export MEMORY_CONNECTOR_DIR="$WORK"
142
143# Empty the store. Every section starts from here so an assertion can never
144# pass because of something a previous section left behind.
145reset_graph() {
146 rm -f "$WORK"/memory.jsonl "$WORK"/memory.jsonl.tmp.* "$WORK"/memory.jsonl.lock 2>/dev/null
147}
148
149# ---------------------------------------------------------------- meta
150section "mode 1 - discovery metadata"
151M=$(body "$($BIN --meta)")
152json_ok "--meta is valid JSON" "$M" "d['name']=='memory'"
153check "--meta name is exactly memory" '"name":"memory"' "$M"
154check "--meta desc is exactly Knowledge graph" '"desc":"Knowledge graph"' "$M"
155json_ok "--meta kind is mcp" "$M" "d['kind']=='mcp'"
156json_ok "--meta mcp is true" "$M" "d['mcp'] is True"
157json_ok "--meta daemon is false" "$M" "d['daemon'] is False"
158json_ok "--meta menus is false (connectors must not flood the dropdowns)" "$M" "d['menus'] is False"
159json_ok "--meta verified is live" "$M" "d['verified']=='live'"
160json_ok "--meta category is devtools" "$M" "d['category']=='devtools'"
161json_ok "--meta version is 1.0.0" "$M" "d['version']=='1.0.0'"
162json_ok "--meta name is 1-2 words" "$M" "len(d['name'].split())<=2"
163json_ok "--meta desc is at most 15 chars" "$M" "len(d['desc'])<=15"
164M2=$(body "$(SX_PLUGIN_META=1 $BIN)")
165check "SX_PLUGIN_META env var works" '"name":"memory"' "$M2"
166check_not "--meta emits no HTML" '<html' "$M"
167V=$(body "$($BIN --version)")
168check "--version names the binary" 'plugin_memory' "$V"
169H=$(body "$($BIN --help)")
170check "--help lists the modes" '--mcp' "$H"
171
172# ---------------------------------------------------------------- auth
173section "mode 2a - node authentication"
174A0=$(BOT_PASSWORD=secret QUERY_STRING='action=graph' $BIN)
175check "unauthenticated graph is 401" 'Status: 401 Unauthorized' "$A0"
176A1=$(BOT_PASSWORD=secret QUERY_STRING='action=search&q=x' $BIN)
177check "unauthenticated search is 401" 'Status: 401 Unauthorized' "$A1"
178A2=$(BOT_PASSWORD=secret QUERY_STRING='' $BIN)
179check "unauthenticated HTML page is 401" 'Status: 401 Unauthorized' "$A2"
180_len=2
181A3=$(printf '{}' | BOT_PASSWORD=secret REQUEST_METHOD=POST CONTENT_LENGTH="$_len" QUERY_STRING='action=add_entity' $BIN)
182check "unauthenticated POST is 401" 'Status: 401 Unauthorized' "$A3"
183A4=$(BOT_PASSWORD=secret QUERY_STRING='action=export' $BIN)
184check "unauthenticated export is 401" 'Status: 401 Unauthorized' "$A4"
185A5=$(BOT_PASSWORD=secret HTTP_X_BOT_PASSWORD=secret QUERY_STRING='action=graph' $BIN)
186json_ok "X-Bot-Password header authenticates" "$(body "$A5")" "d['ok'] is True"
187A6=$(BOT_PASSWORD=secret HTTP_AUTHORIZATION='Bearer secret' QUERY_STRING='action=graph' $BIN)
188json_ok "Authorization Bearer authenticates" "$(body "$A6")" "d['ok'] is True"
189A7=$(BOT_PASSWORD=secret QUERY_STRING='action=graph&pwd=secret' $BIN)
190json_ok "?pwd= authenticates" "$(body "$A7")" "d['ok'] is True"
191A8=$(BOT_PASSWORD=secret HTTP_X_BOT_PASSWORD=wrong QUERY_STRING='action=graph' $BIN)
192check "a wrong password is still 401" 'Status: 401 Unauthorized' "$A8"
193AM=$(body "$(BOT_PASSWORD=secret $BIN --meta)")
194check "--meta stays unauthenticated" '"name":"memory"' "$AM"
195# --mcp is a stdio server the node spawns itself; the CGI password must not
196# stop it, or the router could never reach an installed connector.
197AMC=$(printf '{"jsonrpc":"2.0","id":1,"method":"ping"}' | BOT_PASSWORD=secret $BIN --mcp)
198check "--mcp runs even with BOT_PASSWORD set" '"id":1' "$AMC"
199
200# ---------------------------------------------------------------- mcp handshake
201section "mode 3 - MCP JSON-RPC handshake"
202reset_graph
203INIT=$(mcp '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}')
204json_ok "initialize answers valid JSON" "$INIT" "True"
205json_ok "initialize echoes the id" "$INIT" "d['id']==1"
206json_ok "initialize carries protocolVersion" "$INIT" "'protocolVersion' in d['result']"
207json_ok "initialize advertises tools" "$INIT" "'tools' in d['result']['capabilities']"
208json_ok "initialize names the server" "$INIT" "d['result']['serverInfo']['name']=='memory-server'"
209PING=$(mcp '{"jsonrpc":"2.0","id":7,"method":"ping"}')
210json_ok "ping answers an empty result" "$PING" "d['result']=={} and d['id']==7"
211NOTIF=$(mcp '{"jsonrpc":"2.0","method":"notifications/initialized"}')
212[ -z "$NOTIF" ] && pass "a notification gets no response" || fail "notification answered: $NOTIF"
213BAD=$(mcp 'this is not json')
214check "bad JSON is a parse error (-32700)" '"code":-32700' "$BAD"
215NOM=$(mcp '{"jsonrpc":"2.0","id":9}')
216check "a request with no method is -32600" '"code":-32600' "$NOM"
217UNK=$(mcp '{"jsonrpc":"2.0","id":10,"method":"bogus/method"}')
218check "an unknown method is -32601" '"code":-32601' "$UNK"
219RESP=$(mcp '{"jsonrpc":"2.0","id":11,"result":{}}')
220[ -z "$RESP" ] && pass "an inbound response is ignored" || fail "answered a response: $RESP"
221IDSTR=$(mcp '{"jsonrpc":"2.0","id":"abc","method":"ping"}')
222check "a string id is echoed as a string" '"id":"abc"' "$IDSTR"
223
224TL=$(mcp '{"jsonrpc":"2.0","id":2,"method":"tools/list"}')
225json_ok "tools/list is valid JSON" "$TL" "True"
226json_ok "tools/list has exactly nine tools" "$TL" "len(d['result']['tools'])==9"
227json_ok "tools/list has the reference names" "$TL" \
228 "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']"
229json_ok "every tool has an inputSchema" "$TL" \
230 "all('inputSchema' in t and t['inputSchema'].get('type')=='object' for t in d['result']['tools'])"
231json_ok "read_graph is marked readOnly" "$TL" \
232 "[t for t in d['result']['tools'] if t['name']=='read_graph'][0]['annotations']['readOnlyHint'] is True"
233json_ok "delete_entities is marked destructive" "$TL" \
234 "[t for t in d['result']['tools'] if t['name']=='delete_entities'][0]['annotations']['destructiveHint'] is True"
235check "create_entities description warns about skipping" "is skipped and its observations are not added" "$TL"
236check "delete_entities description points at delete_relations" "use delete_relations" "$TL"
237check "delete_relations says all three fields must match" "exactly on all three fields" "$TL"
238SCHEMA=$(body "$($BIN --schema)")
239json_ok "--schema is the same nine tools" "$SCHEMA" "len(d)==9"
240
241RL=$(mcp '{"jsonrpc":"2.0","id":3,"method":"resources/list"}')
242check "resources/list serves the graph URI" 'memory://knowledge-graph' "$RL"
243RR=$(mcp '{"jsonrpc":"2.0","id":4,"method":"resources/read","params":{"uri":"memory://knowledge-graph"}}')
244json_ok "resources/read returns contents" "$RR" "len(d['result']['contents'])==1"
245json_ok "resources/read text parses as a graph" "$RR" \
246 "json.loads(d['result']['contents'][0]['text'])=={'entities':[],'relations':[]}"
247RBAD=$(mcp '{"jsonrpc":"2.0","id":5,"method":"resources/read","params":{"uri":"other://x"}}')
248check "an unknown resource uri is refused" 'Unknown resource' "$RBAD"
249
250# ---------------------------------------------------------------- create_entities
251section "create_entities"
252reset_graph
253R=$(tool_struct create_entities '{"entities":[{"name":"Alice","entityType":"person","observations":["likes tea"]}]}')
254json_ok "one entity created" "$R" "len(d['entities'])==1 and d['entities'][0]['name']=='Alice'"
255json_ok "observations are stored" "$R" "d['entities'][0]['observations']==['likes tea']"
256R=$(tool_struct create_entities '{"entities":[{"name":"Alice","entityType":"person","observations":["dup"]},{"name":"Bob","entityType":"person","observations":[]}]}')
257json_ok "an existing name is skipped" "$R" "len(d['entities'])==1 and d['entities'][0]['name']=='Bob'"
258json_ok "the skip is reported in skipped" "$R" "d['skipped']==['Alice']"
259NOTICE=$(mcp_call create_entities '{"entities":[{"name":"Bob","entityType":"person","observations":["x"]}]}' \
260 | python3 -c "import json,sys;d=json.loads(sys.stdin.read());c=d['result']['content'];print(c[1]['text'] if len(c)>1 else '')")
261check "the skip is also said in plain words" "Skipped 1 entity that already exists: Bob" "$NOTICE"
262check "the notice tells the agent to use add_observations" "add_observations" "$NOTICE"
263R=$(tool_struct create_entities '{"entities":[{"name":"Cara","entityType":"p","observations":["a"]},{"name":"Cara","entityType":"p","observations":["b"]}]}')
264json_ok "a repeat within one batch is skipped once" "$R" \
265 "len(d['entities'])==1 and d['entities'][0]['name']=='Cara'"
266json_ok "the in-batch repeat is in skipped" "$R" "d['skipped']==['Cara']"
267R=$(tool_struct create_entities '{"entities":[{"name":"Cara","entityType":"p","observations":["c"]}]}')
268json_ok "Cara kept only the first observation" "$R" \
269 "d['entities']==[]"
270R=$(tool_struct create_entities '{"entities":[{"name":"Cara","entityType":"p","observations":["c"]}]}')
271json_ok "a re-submit creates nothing" "$R" "d['entities']==[]"
272ERR=$(mcp_call create_entities '{"wrong":[1]}' \
273 | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['isError'],d['result']['content'][0]['text'])")
274check "missing entities is an error" "Missing required parameter: entities" "$ERR"
275ERR=$(mcp_call create_entities '{"entities":[{"name":"Q"}]}' \
276 | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['isError'],d['result']['content'][0]['text'])")
277check "an entity with no entityType is refused" "True" "$ERR"
278check "and the message says why" "non-empty name and entityType" "$ERR"
279ERR2=$(mcp_call create_entities '{"entities":"nope"}' \
280 | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['content'][0]['text'])")
281check "entities must be an array" "Missing required parameter: entities" "$ERR2"
282
283# ---------------------------------------------------------------- create_relations
284section "create_relations"
285reset_graph
286seed <<'EOF'
287{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"create_entities","arguments":{"entities":[{"name":"Alice","entityType":"person","observations":[]},{"name":"Bob","entityType":"person","observations":[]}]}}}
288EOF
289R=$(tool_struct create_relations '{"relations":[{"from":"Alice","to":"Bob","relationType":"knows"}]}')
290json_ok "relation created" "$R" "len(d['relations'])==1 and d['relations'][0]['relationType']=='knows'"
291R=$(tool_struct create_relations '{"relations":[{"from":"Alice","to":"Bob","relationType":"knows"}]}')
292json_ok "the same triple is not added twice" "$R" "d['relations']==[]"
293R=$(tool_struct create_relations '{"relations":[{"from":"Alice","to":"Ghost","relationType":"knows"}]}')
294# a failed tool call carries no structuredContent, so tool_struct prints the
295# JSON null - the shape that means "this call errored, look at the text".
296[ "$R" = "null" ] && pass "a missing 'to' is an error" || fail "missing to: $R"
297ERR=$(mcp_call create_relations '{"relations":[{"from":"Alice","to":"Ghost","relationType":"knows"}]}' \
298 | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['content'][0]['text'])")
299check "the error names the missing entity" "Entity with name Ghost not found" "$ERR"
300ERR=$(mcp_call create_relations '{"relations":[{"from":"Ghost","to":"Alice","relationType":"knows"}]}' \
301 | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['content'][0]['text'])")
302check "and it names a missing 'from' too" "Entity with name Ghost not found" "$ERR"
303# nothing written by the failed call
304G=$(tool_struct read_graph '{}')
305json_ok "a failed create_relations wrote nothing" "$G" "len(d['relations'])==1"
306R=$(tool_struct create_relations '{"relations":[{"from":"Alice","to":"Bob","relationType":"likes"},{"from":"Alice","to":"Bob","relationType":"likes"}]}')
307json_ok "an in-batch duplicate is added once" "$R" "len(d['relations'])==1"
308G=$(tool_struct read_graph '{}')
309json_ok "so the graph has two relations now" "$G" "len(d['relations'])==2"
310
311# ---------------------------------------------------------------- add_observations
312section "add_observations"
313R=$(tool_struct add_observations '{"observations":[{"entityName":"Alice","contents":["runs","runs","reads"]}]}')
314json_ok "a repeat inside one call is added once" "$R" \
315 "d['results'][0]['addedObservations']==['runs','reads']"
316R=$(tool_struct add_observations '{"observations":[{"entityName":"Alice","contents":["runs"]}]}')
317json_ok "an observation the entity already has is not added" "$R" \
318 "d['results'][0]['addedObservations']==[]"
319ERR=$(mcp_call add_observations '{"observations":[{"entityName":"Ghost","contents":["x"]}]}' \
320 | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['content'][0]['text'])")
321check "an unknown entity is an error" "Entity with name Ghost not found" "$ERR"
322# all-or-nothing: the second group is unknown, so the first must not persist
323G0=$(tool_struct read_graph '{}' )
324ERR=$(mcp_call add_observations '{"observations":[{"entityName":"Alice","contents":["should-not-stick"]},{"entityName":"Ghost","contents":["x"]}]}' \
325 | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['content'][0]['text'])")
326check "one unknown entity fails the whole call" "Entity with name Ghost not found" "$ERR"
327G=$(tool_struct read_graph '{}')
328json_ok "and nothing is written" "$G" \
329 "all('should-not-stick' not in e['observations'] for e in d['entities'])"
330
331# ---------------------------------------------------------------- read tools
332section "read_graph / search_nodes / open_nodes"
333reset_graph
334seed <<'EOF'
335{"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"]}]}}}
336{"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"}]}}}
337EOF
338G=$(tool_struct read_graph '{}')
339json_ok "read_graph returns every entity" "$G" "len(d['entities'])==3"
340json_ok "read_graph returns every relation" "$G" "len(d['relations'])==2"
341G=$(tool_struct read_graph '{"entityTypes":["drink"]}')
342json_ok "entityTypes filters to that type" "$G" "len(d['entities'])==1 and d['entities'][0]['name']=='Tea'"
343json_ok "entityTypes keeps relations touching a kept entity" "$G" \
344 "len(d['relations'])==1 and d['relations'][0]['from']=='Tea'"
345G=$(tool_struct read_graph '{"observationLimit":0}')
346json_ok "observationLimit 0 returns no observations" "$G" \
347 "all(e['observations']==[] for e in d['entities'])"
348json_ok "observationLimit 0 still gives the count" "$G" \
349 "[e for e in d['entities'] if e['name']=='Tea'][0]['observationCount']==2"
350G=$(tool_struct read_graph '{}')
351json_ok "without the option there is no observationCount key" "$G" \
352 "all('observationCount' not in e for e in d['entities'])"
353G=$(tool_struct read_graph '{"observationLimit":1}')
354json_ok "observationLimit 1 truncates to the first" "$G" \
355 "[e for e in d['entities'] if e['name']=='Tea'][0]['observations']==['Earl Grey']"
356ERR=$(mcp_call read_graph '{"observationLimit":-1}' \
357 | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['content'][0]['text'])")
358check "a negative observationLimit is refused" "integer >= 0" "$ERR"
359ERR=$(mcp_call read_graph '{"entityTypes":[]}' \
360 | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['content'][0]['text'])")
361check "an empty entityTypes is refused" "non-empty array" "$ERR"
362
363S=$(tool_struct search_nodes '{"query":"earl"}')
364json_ok "search matches an observation, case-insensitively" "$S" \
365 "len(d['entities'])==1 and d['entities'][0]['name']=='Tea'"
366S=$(tool_struct search_nodes '{"query":"DRINK"}')
367json_ok "search matches the type, case-insensitively" "$S" \
368 "len(d['entities'])==1 and d['entities'][0]['name']=='Tea'"
369S=$(tool_struct search_nodes '{"query":"ze"}')
370json_ok "search matches a substring of a name" "$S" \
371 "len(d['entities'])==1 and d['entities'][0]['name']=='Zebra'"
372S=$(tool_struct search_nodes '{"query":"Earl Grey"}')
373json_ok "search includes relations touching a match" "$S" \
374 "len(d['relations'])==1 and d['relations'][0]['from']=='Tea'"
375S=$(tool_struct search_nodes '{"query":"ceramic"}')
376json_ok "a match found only by observation still brings its relations" "$S" \
377 "any(r['to']=='Cup' for r in d['relations'])"
378S=$(tool_struct search_nodes '{"query":"striped"}')
379json_ok "either-endpoint rule: a relation to an unrequested node survives" "$S" \
380 "len(d['relations'])==1 and d['relations'][0]['from']=='Zebra'"
381S=$(tool_struct search_nodes '{"query":"e","limit":1}')
382json_ok "limit caps the matches, first in stored order" "$S" \
383 "len(d['entities'])==1 and d['entities'][0]['name']=='Tea'"
384S=$(tool_struct search_nodes '{"query":"nothing-matches-this"}')
385json_ok "a search with no match is an empty graph, not an error" "$S" \
386 "d['entities']==[] and d['relations']==[]"
387ERR=$(mcp_call search_nodes '{"q":"x"}' \
388 | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['content'][0]['text'])")
389check "search_nodes needs query" "Missing required parameter: query" "$ERR"
390ERR=$(mcp_call search_nodes '{"query":"x","limit":0}' \
391 | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['content'][0]['text'])")
392check "limit 0 is refused (min 1)" "integer >= 1" "$ERR"
393
394O=$(tool_struct open_nodes '{"names":["Tea","Ghost"]}')
395json_ok "open_nodes returns the exact names" "$O" \
396 "len(d['entities'])==1 and d['entities'][0]['name']=='Tea'"
397json_ok "open_nodes keeps relations to nodes not asked for" "$O" \
398 "any(r['from']=='Tea' and r['to']=='Cup' for r in d['relations'])"
399O=$(tool_struct open_nodes '{"names":["Cup"]}')
400json_ok "open_nodes brings BOTH directions" "$O" \
401 "len(d['relations'])==2"
402O=$(tool_struct open_nodes '{"names":["Ghost","Nowhere"]}')
403json_ok "names that miss are skipped, not an error" "$O" "d['entities']==[] and d['relations']==[]"
404
405# ---------------------------------------------------------------- delete tools
406section "delete_entities / delete_observations / delete_relations"
407reset_graph
408seed <<'EOF'
409{"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":[]}]}}}
410{"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"}]}}}
411EOF
412M=$(mcp '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"delete_entities","arguments":{"entityNames":["A","Ghost"]}}}' | head -1)
413MSG=$(printf '%s' "$M" | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['structuredContent']['message'])")
414check "delete_entities reports deleted and not found" "Deleted 1 of 2 entities. Not found: Ghost" "$MSG"
415G=$(tool_struct read_graph '{}')
416json_ok "the entity is gone" "$G" "all(e['name']!='A' for e in d['entities'])"
417json_ok "relations touching it are cascaded" "$G" "len(d['relations'])==1"
418M=$(mcp '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"delete_entities","arguments":{"entityNames":["B"]}}}' | head -1)
419MSG=$(printf '%s' "$M" | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['structuredContent']['message'])")
420check "a clean delete says so" "Entities deleted successfully" "$MSG"
421M=$(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)
422MSG=$(printf '%s' "$M" | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['structuredContent']['message'])")
423check "delete_observations counts and names the missing entity" \
424 "Deleted 0 of 2 observations. Entities not found: Ghost" "$MSG"
425reset_graph
426seed <<'EOF'
427{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"create_entities","arguments":{"entities":[{"name":"A","entityType":"x","observations":["keep","drop","drop2"]}]}}}
428EOF
429M=$(mcp '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"delete_observations","arguments":{"deletions":[{"entityName":"A","observations":["drop","nope"]}]}}}' | head -1)
430MSG=$(printf '%s' "$M" | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['structuredContent']['message'])")
431check "delete_observations reports the partial count" "Deleted 1 of 2 observations" "$MSG"
432check_not "a partial count with a known entity names none missing" "Entities not found" "$MSG"
433M=$(mcp '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"delete_observations","arguments":{"deletions":[{"entityName":"A","observations":["keep"]}]}}}' | head -1)
434MSG=$(printf '%s' "$M" | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['structuredContent']['message'])")
435check "a clean observation delete says so" "Observations deleted successfully" "$MSG"
436reset_graph
437seed <<'EOF'
438{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"create_entities","arguments":{"entities":[{"name":"A","entityType":"x","observations":[]},{"name":"B","entityType":"x","observations":[]}]}}}
439{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"create_relations","arguments":{"relations":[{"from":"A","to":"B","relationType":"k"}]}}}
440EOF
441M=$(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)
442MSG=$(printf '%s' "$M" | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['structuredContent']['message'])")
443check "delete_relations counts what actually matched" "Deleted 0 of 2 relations. The rest matched nothing." "$MSG"
444M=$(mcp '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"delete_relations","arguments":{"relations":[{"from":"A","to":"B","relationType":"k"}]}}}' | head -1)
445MSG=$(printf '%s' "$M" | python3 -c "import json,sys;d=json.loads(sys.stdin.read());print(d['result']['structuredContent']['message'])")
446check "a clean relation delete says so" "Relations deleted successfully" "$MSG"
447G=$(tool_struct read_graph '{}')
448json_ok "delete_relations keeps the entities" "$G" "len(d['entities'])==2"
449
450# a tool failure is a RESULT with isError, never a JSON-RPC error
451ERRLINE=$(mcp '{"jsonrpc":"2.0","id":42,"method":"tools/call","params":{"name":"read_graph","arguments":{"observationLimit":-5}}}' | head -1)
452check "a tool failure still answers with a result" '"result"' "$ERRLINE"
453check "and marks isError" '"isError":true' "$ERRLINE"
454check "and keeps the id" '"id":42' "$ERRLINE"
455UNKNOWNTOOL=$(mcp '{"jsonrpc":"2.0","id":43,"method":"tools/call","params":{"name":"no_such_tool"}}' | head -1)
456check "an unknown tool name is a JSON-RPC error" '"code":-32602' "$UNKNOWNTOOL"
457
458# ---------------------------------------------------------------- persistence
459section "persistence across processes"
460reset_graph
461seed <<'EOF'
462{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"create_entities","arguments":{"entities":[{"name":"Persist","entityType":"check","observations":["written by process one"]}]}}}
463EOF
464[ -f "$MEMORY_FILE_PATH" ] && pass "the graph file is created" || fail "graph file missing"
465FIRSTLINE=$(head -1 "$MEMORY_FILE_PATH")
466check "it is JSONL with a type tag" '"type":"entity"' "$FIRSTLINE"
467check "one line holds one entity" '"name":"Persist"' "$FIRSTLINE"
468# a completely new process reads it back
469G=$(tool_struct read_graph '{}')
470json_ok "a second process reads the graph" "$G" \
471 "len(d['entities'])==1 and d['entities'][0]['observations']==['written by process one']"
472# and so does the HTTP API
473S=$(api 'action=stats')
474json_ok "the HTTP API sees the same graph" "$S" "d['entities']==1 and d['observations']==1"
475# an appended unreadable line survives every write
476printf 'this line is not json at all\n' >> "$MEMORY_FILE_PATH"
477seed <<'EOF'
478{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"add_observations","arguments":{"observations":[{"entityName":"Persist","contents":["one more"]}]}}}
479EOF
480check "an unparseable line is preserved verbatim" "this line is not json at all" "$(cat "$MEMORY_FILE_PATH")"
481S=$(api 'action=stats')
482json_ok "and counted, so the operator can see it" "$S" "d['unreadable_lines']==1"
483LEFT=$(ls "$WORK" | grep -c '\.tmp' || true)
484[ "$LEFT" = "0" ] && pass "no temp file is left behind" || fail "$LEFT temp file(s) left"
485# a save that keeps the operator's file mode
486chmod 600 "$MEMORY_FILE_PATH"
487seed <<'EOF'
488{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"add_observations","arguments":{"observations":[{"entityName":"Persist","contents":["mode probe"]}]}}}
489EOF
490MODE=$(stat -c '%a' "$MEMORY_FILE_PATH" 2>/dev/null || echo unknown)
491[ "$MODE" = "600" ] && pass "a 0600 graph file stays 0600 after a save" || fail "mode became $MODE"
492# unicode and punctuation round trip
493reset_graph
494seed <<'EOF'
495{"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"]}]}}}
496EOF
497G=$(tool_struct read_graph '{}')
498json_ok "quotes, backslashes, tabs and newlines round trip" "$G" \
499 "d['entities'][0]['name']=='Uni \"quote\" \\\\ back' and d['entities'][0]['observations'][1]=='newline\nhere'"
500
501# ---------------------------------------------------------------- http api
502section "mode 2b - the JSON API"
503reset_graph
504S=$(api 'action=stats')
505json_ok "stats on an empty graph is ok" "$S" "d['ok'] is True and d['entities']==0 and d['file_exists'] is False"
506check "stats is served as JSON" 'Content-Type: application/json' "$(apiraw 'action=stats')"
507AE=$(api_post 'action=add_entity' '{"name":"Api","entityType":"thing","observations":["from json body"]}')
508json_ok "add_entity accepts a JSON body" "$AE" "d['ok'] is True and d['entities'][0]['name']=='Api'"
509AE=$(api 'action=add_entity&name=Qs&entityType=thing&observations=one|two')
510json_ok "add_entity accepts a query string too" "$AE" "d['ok'] is True"
511G=$(api 'action=graph')
512json_ok "graph returns both" "$G" "len(d['entities'])==2"
513S=$(api 'action=search&q=from json')
514json_ok "search finds by observation" "$S" "len(d['entities'])==1 and d['entities'][0]['name']=='Api'"
515EN=$(api 'action=entity&name=Api')
516json_ok "entity returns one" "$EN" "len(d['entities'])==1"
517EN=$(api 'action=entity')
518json_ok "entity with no name is a 400 shape" "$EN" "d['ok'] is False and 'error' in d"
519AO=$(api_post 'action=add_obs' '{"name":"Api","contents":["third","third"]}')
520json_ok "add_obs dedupes within one call" "$AO" "d['results'][0]['addedObservations']==['third']"
521AR=$(api 'action=add_relation&from=Api&to=Qs&relationType=relates')
522json_ok "add_relation works from a query string" "$AR" "len(d['relations'])==1"
523AR=$(api 'action=add_relation&from=Api&to=Nope&relationType=relates')
524json_ok "add_relation reports the missing end" "$AR" "d['ok'] is False and 'not found' in d['error']"
525DR=$(api 'action=delete_relation&from=Api&to=Qs&relationType=relates')
526json_ok "delete_relation works" "$DR" "d['ok'] is True"
527DO=$(api 'action=delete_obs&name=Api&observations=from json')
528json_ok "delete_obs reports the partial count" "$DO" "d['ok'] is True"
529DE=$(api 'action=delete_entity&name=Qs')
530json_ok "delete_entity reports success" "$DE" "d['ok'] is True"
531UA=$(api 'action=bogus')
532json_ok "an unknown action is refused" "$UA" "d['ok'] is False"
533BN=$(printf 'notjson' | REQUEST_METHOD=POST CONTENT_LENGTH="7" QUERY_STRING='action=add_entity' $BIN)
534check "a body that is not JSON is a 400" 'Status: 400 Bad Request' "$BN"
535_len=$(printf '%s' '{"name":"Big","entityType":"t","observations":["x"]}' | wc -c | tr -d ' ')
536BC=$(printf '%s' '{"name":"Big","entityType":"t","observations":["x"]}' | REQUEST_METHOD=POST CONTENT_LENGTH="$_len" QUERY_STRING='action=add_entity' $BIN)
537check "POST with a JSON body works" '"ok":true' "$BC"
538# action from the body, not the query
539BC2=$(printf '%s' '{"action":"stats"}' | REQUEST_METHOD=POST CONTENT_LENGTH="18" QUERY_STRING='' $BIN)
540check "action can arrive in the body" '"ok":true' "$BC2"
541# format=json with no action must not clobber anything
542FJ=$(body "$(QUERY_STRING='format=json' $BIN)")
543json_ok "format=json alone serves the graph" "$FJ" "'entities' in d"
544# export
545EX=$(QUERY_STRING='action=export' $BIN)
546check "export is offered as a download" 'attachment; filename="memory.jsonl"' "$EX"
547check "export is text/plain" 'text/plain' "$EX"
548check "export carries the JSONL" '"type":"entity"' "$EX"
549# tools action
550TO=$(api 'action=tools')
551json_ok "action=tools lists the nine tools" "$TO" "d['ok'] is True and len(d['tools'])==9"
552json_ok "action=tools says it is an mcp connector" "$TO" "d['kind']=='mcp'"
553
554# html
555H=$(apiraw '')
556check "GET serves HTML" 'Content-Type: text/html' "$H"
557check "HTML has a CSP" 'Content-Security-Policy' "$H"
558check "HTML is same-origin frameable only" 'X-Frame-Options: SAMEORIGIN' "$H"
559check "HTML declares the bot font token" 'var(--font)' "$H"
560check_not "the page loads no CDN script" '<script src=' "$H"
561check_not "the page references cdnjs" 'cdnjs' "$H"
562if printf '%s' "$H" | python3 -c "
563import sys
564t=sys.stdin.buffer.read().decode('utf-8','replace')
565bad=[c for c in t if ord(c)>0x2100]
566sys.exit(1 if bad else 0)" 2>/dev/null; then pass "the page has no emoji"; else fail "the page has an emoji"; fi
567check "the page talks to the right route" "plugin_memory" "$H"
568check "the page branches on the hub proxy route" "'plugins'" "$H"
569
570# ---------------------------------------------------------------- source guards
571section "source guards"
572SRC_ALL=$(cat src/plugin_memory.c src/graph.c src/tools.c src/api.c src/memory.h)
573check_not "no popen() anywhere" 'popen(' "$SRC_ALL"
574check_not "no system() anywhere" 'system(' "$SRC_ALL"
575check_not "no exec family" 'execv' "$SRC_ALL"
576check_not "no socket()" 'socket(' "$SRC_ALL"
577check_not "no libcurl include" '#include <curl' "$SRC_ALL"
578check_not "no curl_easy calls" 'curl_easy' "$SRC_ALL"
579check_not "no fork()" 'fork()' "$SRC_ALL"
580check_not "no gets()" 'gets(' "$SRC_ALL"
581WIN32=$(cat src/plugin_memory.c)
582check "Windows forces binary stdio" '_O_BINARY' "$WIN32"
583check "the graph dir is under .scorpiox/connectors" '.scorpiox/connectors' "$(cat src/graph.c)"
584check "MEMORY_FILE_PATH overrides the location" 'MEMORY_FILE_PATH' "$(cat src/graph.c)"
585check "/workspace is preferred when present" '/workspace' "$(cat src/graph.c)"
586check "a relative MEMORY_FILE_PATH may not traverse" "may not contain '..'" "$(cat src/graph.c)"
587
588# ---------------------------------------------------------------- sanitizers
589section "sanitizers (ASan + UBSan + _FORTIFY_SOURCE=2)"
590ASAN=./plugin_memory.asan
591if make asan >/dev/null 2>&1 && [ -x "$ASAN" ]; then
592 pass "the sanitizer build compiles"
593 SWORK=$(mktemp -d 2>/dev/null || echo /tmp/pmasan_$$)
594 runasan() {
595 MEMORY_FILE_PATH="$SWORK/g.jsonl" MEMORY_CONNECTOR_DIR="$SWORK" "$ASAN" "$@"
596 }
597 AOUT=$(printf '%s\n' \
598 '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' \
599 '{"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"]}]}}}' \
600 '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"create_relations","arguments":{"relations":[{"from":"A","to":"B","relationType":"k"}]}}}' \
601 '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"create_entities","arguments":{"entities":[{"name":"B","entityType":"x","observations":[]}]}}}' \
602 '{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"create_relations","arguments":{"relations":[{"from":"A","to":"B","relationType":"k"}]}}}' \
603 '{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"add_observations","arguments":{"observations":[{"entityName":"A","contents":["o1","new","new"]}]}}}' \
604 '{"jsonrpc":"2.0","id":7,"method":"tools/call","params":{"name":"delete_entities","arguments":{"entityNames":["A","Ghost","Ghost"]}}}' \
605 '{"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"delete_observations","arguments":{"deletions":[{"entityName":"B","observations":["x"]},{"entityName":"Ghost","observations":["y"]}]}}}' \
606 '{"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"}]}}}' \
607 '{"jsonrpc":"2.0","id":10,"method":"tools/call","params":{"name":"read_graph","arguments":{"observationLimit":0}}}' \
608 '{"jsonrpc":"2.0","id":11,"method":"tools/call","params":{"name":"search_nodes","arguments":{"query":"a","limit":1,"observationLimit":1}}}' \
609 '{"jsonrpc":"2.0","id":12,"method":"tools/call","params":{"name":"open_nodes","arguments":{"names":["A","B","Ghost"],"observationLimit":0}}}' \
610 '{"jsonrpc":"2.0","id":13,"method":"tools/call","params":{"name":"create_entities","arguments":{"entities":[{"name":"Uni \"q\" \\\\ b","entityType":"t","observations":["tab\there"]}]}}}' \
611 '{"jsonrpc":"2.0","id":14,"method":"tools/call","params":{"name":"read_graph","arguments":{}}}' \
612 '{"jsonrpc":"2.0","id":15,"method":"tools/call","params":{"name":"read_graph","arguments":{"entityTypes":["t","x"]}}}' \
613 '{"jsonrpc":"2.0","id":16,"method":"tools/call","params":{"name":"create_relations","arguments":{"relations":"bad"}}}' \
614 '{"jsonrpc":"2.0","id":17,"method":"tools/call","params":{"name":"add_observations","arguments":{}}}' \
615 '{"jsonrpc":"2.0","id":18,"method":"tools/call","params":{"name":"delete_entities","arguments":{}}}' \
616 '{"jsonrpc":"2.0","id":19,"method":"resources/read","params":{"uri":"memory://knowledge-graph"}}' \
617 '{"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":[]}]}}}' \
618 | MEMORY_FILE_PATH="$SWORK/g.jsonl" MEMORY_CONNECTOR_DIR="$SWORK" "$ASAN" --mcp 2>&1)
619 check_not "the sanitizer run reports no leak" 'ERROR: AddressSanitizer' "$AOUT"
620 check_not "the sanitizer run reports no runtime error" 'runtime error:' "$AOUT"
621 check_not "the sanitizer run reports no use-after-free" 'heap-use-after-free' "$AOUT"
622 check_not "the sanitizer run reports no buffer overflow" 'buffer-overflow' "$AOUT"
623 # the fortify build of the CGI path too
624 COUT=$(QUERY_STRING='action=stats' MEMORY_FILE_PATH="$SWORK/c.jsonl" MEMORY_CONNECTOR_DIR="$SWORK" "$ASAN" 2>&1)
625 check_not "the CGI path is clean under ASan too" 'ERROR: AddressSanitizer' "$COUT"
626 POUT=$(printf '%s\n' 'garbage line' '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"read_graph","arguments":{}}}' \
627 | MEMORY_FILE_PATH="$SWORK/p.jsonl" MEMORY_CONNECTOR_DIR="$SWORK" "$ASAN" --mcp 2>&1)
628 check_not "a garbage stdin line is clean under ASan" 'ERROR: AddressSanitizer' "$POUT"
629 rm -rf "$SWORK"
630else
631 fail "the sanitizer build did not produce ./plugin_memory.asan"
632fi
633
634# ---------------------------------------------------------------- cross targets
635section "cross-target builds (when the toolchain is here)"
636if command -v musl-gcc >/dev/null 2>&1; then
637 make musl >/dev/null 2>&1 && pass "musl static build" || fail "musl build"
638 [ -x ./plugin_memory.musl ] && {
639 MOUT=$(MEMORY_FILE_PATH="$WORK/musl.jsonl" ./plugin_memory.musl --meta)
640 check "the musl binary runs --meta" '"kind":"mcp"' "$MOUT"
641 file ./plugin_memory.musl 2>/dev/null | grep -q 'statically linked' \
642 && pass "the musl artifact is static" || fail "the musl artifact is not static"
643 }
644else
645 echo " skip musl (no musl-gcc here)"
646fi
647if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
648 make win64 >/dev/null 2>&1 && pass "MinGW win64 build" || fail "win64 build"
649 [ -f ./plugin_memory.exe ] && {
650 head -c 2 ./plugin_memory.exe | grep -q 'MZ' \
651 && pass "the PE artifact starts with MZ" || fail "the PE header is wrong"
652 }
653else
654 echo " skip win64 (no MinGW here)"
655fi
656if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
657 make arm64 >/dev/null 2>&1 && pass "aarch64 cross build" || fail "arm64 build"
658else
659 echo " skip arm64 (no aarch64-linux-gnu-gcc here)"
660fi
661
662# ---------------------------------------------------------------- history audit
663section "git history secret and IP audit"
664if [ -d .git ]; then
665 ALL=$(mktemp)
666 git log -p --all > "$ALL" 2>/dev/null || : > "$ALL"
667 audit() { # audit <label> <regex>
668 H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true)
669 if [ -n "$H" ]; then
670 fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /'
671 else
672 pass "history clean: $1"
673 fi
674 }
675 audit "LAN 192.168.x" '192\.168\.[0-9]+\.[0-9]+'
676 audit "private 10.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
677 audit "private 172.16-31.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
678 audit "GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
679 audit "HuggingFace token" 'hf_[A-Za-z0-9]{30,}'
680 audit "plugingit token" 'plugingit_[A-Za-z0-9]{20,}'
681 audit "embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}'
682 audit "sshpass default" 'Xbox''one09''09'
683 audit "run token assignment" 'RUNNER_'"PASS="
684 INTERNAL="int""el-ultra""2|macmi""ni2018""i5|laza""rus"
685 audit "internal hostname" "$INTERNAL"
686 rm -f "$ALL"
687else
688 echo " skip history audit (not a git checkout)"
689fi
690
691section "brand casing"
692BRAND=$(cat README.md docs/usage.md plugin.json src/ui.html 2>/dev/null || true)
693BADCASE=$(printf '%s' "$BRAND" | grep -Eo 'Scorpio''x Bot|Scorpio''X Bot|SCORPIO BOT' | sort -u | head -3 || true)
694[ -z "$BADCASE" ] && pass "the product is only ever SCORPIOX BOT" || fail "bad casing: $BADCASE"
695
696# ---------------------------------------------------------------- cleanup
697rm -rf "$WORK"
698
699# ---------------------------------------------------------------- summary
700printf '\n%s== summary ==%s\n' "$C_B" "$C_0"
701printf ' passed: %d\n' "$PASS"
702printf ' failed: %d\n' "$FAIL"
703if [ "$FAIL" -ne 0 ]; then
704 exit 1
705fi
706exit 0