scorpiox-bot-plugin-sessionstats
←run.shbash
360 lines · 16 KBHEADBlameDownload
1#!/bin/sh
2# tests/run.sh - offline assertion suite for plugin_sessionstats.
3#
4# Everything here runs against synthetic session fixtures in a throwaway
5# directory, so no real ~/.scorpiox/sessions is touched and no network, shell
6# tool or real clock is involved. Every timestamp is fixed, so the expected
7# durations are exact.
8#
9# Usage: sh tests/run.sh [path-to-binary]
10# Exit: 0 when every assertion passes.
11
12set -u
13
14ROOT=$(cd "$(dirname "$0")/.." && pwd)
15BIN=${1:-"$ROOT/plugin_sessionstats"}
16[ -x "$BIN" ] || { echo "binary not built: $BIN" >&2; exit 1; }
17
18TMP=$(mktemp -d "${TMPDIR:-/tmp}/sx_sessionstats_XXXXXX")
19trap 'rm -rf "$TMP"' EXIT
20
21PASS=0
22FAIL=0
23ok() { PASS=$((PASS+1)); }
24bad() { FAIL=$((FAIL+1)); printf ' FAIL %s\n' "$1"; }
25check() { # check <label> <actual> <expected>
26 if [ "$2" = "$3" ]; then ok; else bad "$1 (got '$2', want '$3')"; fi
27}
28
29# ---------------------------------------------------------------- fixtures
30S="$TMP/sessions"
31mkdir -p "$S/s1" "$S/s2" "$S/s3"
32
33# --- s1: two complete runs, three tool kinds, a profile and a model
34cat > "$S/s1/meta.json" <<'EOF'
35{
36 "id": "2026_01_01_quiet_curie",
37 "thread_guid": "11111111-2222-3333-4444-555555555555",
38 "start_time": "2026-01-01 10:00:00",
39 "start_epoch": 1767261600,
40 "model": "alpha-1",
41 "provider": "openai",
42 "profile": "profile-alpha",
43 "cwd": "/work/alpha"
44}
45EOF
46cat > "$S/s1/stats.json" <<'EOF'
47{
48 "model": "alpha-1",
49 "branch": "main",
50 "input_tokens": 1000,
51 "output_tokens": 250,
52 "cache_read_tokens": 800,
53 "cache_creation_tokens": 50
54}
55EOF
56cat > "$S/s1/events.jsonl" <<'EOF'
57{"ts":"2026-01-01 10:00:00","event":"session_start","model":"alpha-1","provider":"openai","profile":"profile-alpha"}
58{"ts":"2026-01-01 10:00:05","event":"user_message","len":10}
59{"ts":"2026-01-01 10:00:05","event":"agent_run_start","msg_len":10}
60{"ts":"2026-01-01 10:00:15","event":"tool_use","tool":"Bash","input_len":12}
61{"ts":"2026-01-01 10:00:20","event":"tool_use","tool":"Bash","input_len":20}
62{"ts":"2026-01-01 10:00:30","event":"tool_use","tool":"Read","input_len":5}
63{"ts":"2026-01-01 10:00:35","event":"agent_idle"}
64{"ts":"2026-01-01 10:05:00","event":"user_message","len":8}
65{"ts":"2026-01-01 10:05:00","event":"agent_run_start","msg_len":8}
66{"ts":"2026-01-01 10:05:25","event":"tool_use","tool":"Write","input_len":9}
67{"ts":"2026-01-01 10:05:40","event":"agent_complete"}
68EOF
69# run 1 = 10:00:05 -> 10:00:35 = 30s; run 2 = 10:05:00 -> 10:05:40 = 40s
70# active = 70s, wall = 10:00:00 -> 10:05:40 = 340s, idle = 270s
71
72# --- s2: still running (open run + thinking marker), different profile
73cat > "$S/s2/meta.json" <<'EOF'
74{
75 "id": "2026_01_02_bold_lovelace",
76 "start_time": "2026-01-02 08:00:00",
77 "model": "beta-2",
78 "provider": "anthropic",
79 "profile": "profile-beta",
80 "cwd": "/work/beta"
81}
82EOF
83cat > "$S/s2/events.jsonl" <<'EOF'
84{"ts":"2026-01-02 08:00:00","event":"session_start","model":"beta-2","provider":"anthropic","profile":"profile-beta"}
85{"ts":"2026-01-02 08:00:10","event":"user_message","len":5}
86{"ts":"2026-01-02 08:00:10","event":"agent_run_start","msg_len":5}
87{"ts":"2026-01-02 08:01:00","event":"tool_use","tool":"Bash","input_len":7}
88{"ts":"2026-01-02 08:01:10","event":"api_response","turn":1}
89EOF
90: > "$S/s2/thinking"
91# run still open at last event: active = 08:00:10 -> 08:01:10 = 60s, wall = 70s
92
93# --- s3: metadata only, no events at all (degenerate but must not crash)
94cat > "$S/s3/meta.json" <<'EOF'
95{
96 "id": "2026_01_03_empty_nash",
97 "start_time": "2026-01-03 00:00:00",
98 "start_epoch": 1767398400
99}
100EOF
101
102run() { # run <query-string> [extra env assignments via args 2..]
103 qs="$1"; shift
104 env SX_SESSIONS_DIR="$S" QUERY_STRING="$qs" "$@" "$BIN" 2>/dev/null
105}
106
107jsoncheck() { # jsoncheck <label> <json-file> <python-expression on d> <expected>
108 label="$1"; file="$2"; expr="$3"; want="$4"
109 got=$(python3 - "$file" "$expr" <<'PY'
110import json, sys
111d = json.load(open(sys.argv[1]))
112try:
113 v = eval(sys.argv[2], {"d": d, "len": len, "sum": sum, "sorted": sorted})
114except Exception as e:
115 v = "ERR:%s" % e
116print(v)
117PY
118)
119 check "$label" "$got" "$want"
120}
121
122echo "== meta mode"
123out=$("$BIN" --meta)
124check "--meta exact JSON" "$out" '{"name":"sessions","desc":"Turn metrics"}'
125out=$(SX_PLUGIN_META=1 "$BIN")
126check "SX_PLUGIN_META=1 exact JSON" "$out" '{"name":"sessions","desc":"Turn metrics"}'
127check "meta name is other field free" "$(printf '%s' "$out" | python3 -c 'import json,sys;d=json.load(sys.stdin);print(len(d))')" "2"
128check "meta name length <= 2 words" "$(printf '%s' "$out" | python3 -c 'import json,sys;print(len(json.load(sys.stdin)["name"].split()))')" "1"
129check "meta desc length <= 15" "$(printf '%s' "$out" | python3 -c 'import json,sys;print(len(json.load(sys.stdin)["desc"])<=15)')" "True"
130
131echo "== auth gate"
132code=$(BOT_PASSWORD=pw SX_SESSIONS_DIR="$S" QUERY_STRING=action=summary "$BIN" | head -1 | tr -d '\r')
133check "401 without credential" "$code" "Status: 401 Unauthorized"
134code=$(BOT_PASSWORD=pw HTTP_X_BOT_PASSWORD=pw SX_SESSIONS_DIR="$S" QUERY_STRING=action=summary "$BIN" | head -1 | cut -c1-12)
135check "header credential accepted" "$code" "Content-Type"
136code=$(BOT_PASSWORD=pw HTTP_AUTHORIZATION="Bearer pw" SX_SESSIONS_DIR="$S" QUERY_STRING=action=summary "$BIN" | head -1 | cut -c1-12)
137check "bearer credential accepted" "$code" "Content-Type"
138code=$(BOT_PASSWORD=pw SX_SESSIONS_DIR="$S" QUERY_STRING='action=summary&pwd=pw' "$BIN" | head -1 | cut -c1-12)
139check "query credential accepted" "$code" "Content-Type"
140code=$(BOT_PASSWORD=pw SX_SESSIONS_DIR="$S" "$BIN" --meta | cut -c1-10)
141check "--meta stays unauthenticated" "$code" '{"name":"s'
142code=$(BOT_PASSWORD=pw SX_SESSIONS_DIR="$S" QUERY_STRING=action=summary "$BIN" | tail -1)
143check "401 body is JSON error" "$code" '{"ok":false,"error":"invalid node password"}'
144
145echo "== summary shape"
146run 'action=summary' > "$TMP/sum.json"
147last=$(tail -1 "$TMP/sum.json")
148check "summary has no Content-Length" "$(printf '%s' "$last" | grep -c 'Content-Length')" "0"
149printf '%s' "$last" > "$TMP/sum.body.json"
150jsoncheck "ok" "$TMP/sum.body.json" 'd["ok"]' "True"
151jsoncheck "plugin id" "$TMP/sum.body.json" 'd["plugin"]' "plugin_sessionstats"
152jsoncheck "version" "$TMP/sum.body.json" 'd["version"]' "1.0.1"
153jsoncheck "root_found" "$TMP/sum.body.json" 'd["root_found"]' "True"
154jsoncheck "session count" "$TMP/sum.body.json" 'd["count"]' "3"
155jsoncheck "active_now" "$TMP/sum.body.json" 'd["active_now"]' "1"
156jsoncheck "turns total" "$TMP/sum.body.json" 'd["turns"]' "3"
157jsoncheck "tool events" "$TMP/sum.body.json" 'd["tool_events"]' "5"
158jsoncheck "total sec" "$TMP/sum.body.json" 'd["total_sec"]' "410"
159jsoncheck "active sec" "$TMP/sum.body.json" 'd["active_sec"]' "130"
160jsoncheck "idle sec" "$TMP/sum.body.json" 'd["idle_sec"]' "280"
161jsoncheck "idle+active=total" "$TMP/sum.body.json" 'd["idle_sec"]+d["active_sec"]==d["total_sec"]' "True"
162jsoncheck "duty pct" "$TMP/sum.body.json" 'round(d["duty_cycle_pct"],2)' "31.71"
163jsoncheck "total_fmt" "$TMP/sum.body.json" 'd["total_fmt"]' "06m 50s"
164jsoncheck "active_fmt" "$TMP/sum.body.json" 'd["active_fmt"]' "02m 10s"
165jsoncheck "idle_fmt" "$TMP/sum.body.json" 'd["idle_fmt"]' "04m 40s"
166jsoncheck "sessions array length" "$TMP/sum.body.json" 'len(d["sessions"])' "3"
167jsoncheck "profiles present" "$TMP/sum.body.json" 'len(d["profiles"])' "3"
168jsoncheck "models present" "$TMP/sum.body.json" 'len(d["models"])' "3"
169jsoncheck "profile alpha leads" "$TMP/sum.body.json" 'd["profiles"][0]["profile"]' "profile-alpha"
170jsoncheck "profile alpha active" "$TMP/sum.body.json" 'd["profiles"][0]["active_sec"]' "70"
171jsoncheck "profile beta active" "$TMP/sum.body.json" 'd["profiles"][1]["active_sec"]' "60"
172jsoncheck "profile alpha sessions" "$TMP/sum.body.json" 'd["profiles"][0]["sessions"]' "1"
173jsoncheck "unknown profile bucket" "$TMP/sum.body.json" 'd["profiles"][2]["profile"]' "unknown"
174jsoncheck "model alpha leads" "$TMP/sum.body.json" 'd["models"][0]["model"]' "alpha-1"
175
176echo "== summary is sorted newest first"
177jsoncheck "first session is s2" "$TMP/sum.body.json" 'd["sessions"][0]["id"]' "2026_01_02_bold_lovelace"
178jsoncheck "second session is s1" "$TMP/sum.body.json" 'd["sessions"][1]["id"]' "2026_01_01_quiet_curie"
179
180echo "== per-session numbers (s1)"
181cat > "$TMP/py_s1.py" <<'PY'
182import json,sys
183d=json.load(open(sys.argv[1]))
184for s in d["sessions"]:
185 if s["dir"]=="s1":
186 print(s["total_sec"], s["active_sec"], s["idle_sec"], s["turns"],
187 s["duty_cycle_pct"], s["model"], s["profile"], s["branch"],
188 s["tokens"]["in"], s["tokens"]["out"], s["tokens"]["cache_read"],
189 s["tokens"]["cache_write"])
190PY
191got=$(python3 "$TMP/py_s1.py" "$TMP/sum.body.json")
192check "s1 numbers" "$got" "340 70 270 2 20.59 alpha-1 profile-alpha main 1000 250 800 50"
193
194cat > "$TMP/py_s1tools.py" <<'PY'
195import json,sys
196d=json.load(open(sys.argv[1]))
197for s in d["sessions"]:
198 if s["dir"]=="s1":
199 print(" ".join("%s=%d"%(t["name"],t["calls"]) for t in s["tools"]))
200PY
201got=$(python3 "$TMP/py_s1tools.py" "$TMP/sum.body.json")
202check "s1 tools sorted by calls" "$got" "Bash=2 Read=1 Write=1"
203
204cat > "$TMP/py_s1id.py" <<'PY'
205import json,sys
206d=json.load(open(sys.argv[1]))
207for s in d["sessions"]:
208 if s["dir"]=="s1":
209 print(s["id"], s["start_time"], s["is_active"], s["avg_turn_sec"])
210PY
211got=$(python3 "$TMP/py_s1id.py" "$TMP/sum.body.json")
212check "s1 identity fields" "$got" "2026_01_01_quiet_curie 2026-01-01 10:00:00 False 35.0"
213
214echo "== per-session numbers (s2, still running)"
215cat > "$TMP/py_s2.py" <<'PY'
216import json,sys
217d=json.load(open(sys.argv[1]))
218for s in d["sessions"]:
219 if s["dir"]=="s2":
220 print(s["total_sec"], s["active_sec"], s["idle_sec"], s["turns"], s["is_active"])
221PY
222got=$(python3 "$TMP/py_s2.py" "$TMP/sum.body.json")
223check "s2 numbers" "$got" "70 60 10 1 True"
224
225echo "== degenerate session (metadata only)"
226cat > "$TMP/py_s3.py" <<'PY'
227import json,sys
228d=json.load(open(sys.argv[1]))
229for s in d["sessions"]:
230 if s["dir"]=="s3":
231 print(s["total_sec"], s["active_sec"], s["turns"], s["is_active"])
232PY
233got=$(python3 "$TMP/py_s3.py" "$TMP/sum.body.json")
234check "s3 numbers" "$got" "0 0 0 False"
235
236echo "== action=session"
237run 'action=session&sid=s1' | tail -1 > "$TMP/one.json"
238jsoncheck "session ok" "$TMP/one.json" 'd["ok"]' "True"
239jsoncheck "session id" "$TMP/one.json" 'd["session"]["id"]' "2026_01_01_quiet_curie"
240jsoncheck "session active" "$TMP/one.json" 'd["session"]["active_sec"]' "70"
241jsoncheck "session tools" "$TMP/one.json" 'len(d["session"]["tools"])' "3"
242jsoncheck "session summary block" "$TMP/one.json" 'd["summary"]["turns"]' "2"
243run 'action=session&sid=2026_01_02_bold_lovelace' | tail -1 > "$TMP/one2.json"
244jsoncheck "session by full id" "$TMP/one2.json" 'd["session"]["dir"]' "s2"
245run 'action=session&sid=nope' | tail -1 > "$TMP/one3.json"
246jsoncheck "unknown session ok=false" "$TMP/one3.json" 'd["ok"]' "False"
247jsoncheck "unknown session error" "$TMP/one3.json" 'd["error"]' "session not found"
248run 'action=session' | tail -1 > "$TMP/one4.json"
249jsoncheck "missing sid error" "$TMP/one4.json" 'd["error"]' "missing sid parameter"
250run 'action=session&id=s1' | tail -1 > "$TMP/one5.json"
251jsoncheck "id= alias accepted" "$TMP/one5.json" 'd["session"]["dir"]' "s1"
252run 'action=session&sid=%73%31' | tail -1 > "$TMP/one6.json"
253jsoncheck "percent-decoded sid" "$TMP/one6.json" 'd["session"]["dir"]' "s1"
254
255echo "== format=json"
256run 'format=json' | tail -1 > "$TMP/fmt.json"
257jsoncheck "format=json returns summary" "$TMP/fmt.json" 'd["count"]' "3"
258jsoncheck "format=json ok" "$TMP/fmt.json" 'd["ok"]' "True"
259
260echo "== unknown action falls back to the summary"
261run 'action=whatever' | tail -1 > "$TMP/unk.json"
262jsoncheck "unknown action still JSON" "$TMP/unk.json" 'd["ok"]' "True"
263
264echo "== html"
265run 'embed=1' > "$TMP/html.txt"
266head -1 "$TMP/html.txt" | grep -q 'Content-Type: text/html' && ok || bad "html content type"
267grep -q '<!DOCTYPE html>' "$TMP/html.txt" && ok || bad "html doctype"
268grep -q 'Session Analytics' "$TMP/html.txt" && ok || bad "html title"
269grep -q "id='kSessions'" "$TMP/html.txt" && ok || bad "kpi card sessions"
270grep -q "id='railOn'" "$TMP/html.txt" && ok || bad "active rail"
271grep -q "id='profBars'" "$TMP/html.txt" && ok || bad "profile bars"
272grep -q "id='modelBars'" "$TMP/html.txt" && ok || bad "model bars"
273grep -q "id='tbody'" "$TMP/html.txt" && ok || bad "session table"
274grep -q "btnTheme" "$TMP/html.txt" && ok || bad "theme toggle"
275grep -q "prefers-color-scheme" "$TMP/html.txt" && ok || bad "dark/light support"
276grep -q 'theme=(light|dark)' "$TMP/html.txt" && ok || bad "theme: reads ?theme= before paint"
277grep -q "d.type==='sx-theme'" "$TMP/html.txt" && ok || bad "theme: listens for sx-theme"
278grep -q "sx-theme-request" "$TMP/html.txt" && ok || bad "theme: asks the host for the theme"
279grep -q -- "--bg-card" "$TMP/html.txt" && ok || bad "theme: bot token --bg-card"
280grep -q -- "--surface-2" "$TMP/html.txt" && ok || bad "theme: bot token --surface-2"
281grep -q -- "--text-2" "$TMP/html.txt" && ok || bad "theme: bot token --text-2"
282grep -q "embed-hide" "$TMP/html.txt" && ok || bad "theme: toggle hidden when embedded"
283grep -q 'Scorpio'"X Bot" "$TMP/html.txt" && bad "theme: no retired brand casing" || ok
284grep -q "0d0d0f" "$TMP/html.txt" && bad "theme: no private palette 0d0d0f" || ok
285grep -q "18181b" "$TMP/html.txt" && bad "theme: no private palette 18181b" || ok
286grep -q "max-width:400px" "$TMP/html.txt" && ok || bad "narrow breakpoint"
287grep -q "plugin_sessionstats?action=" "$TMP/html.txt" && ok || bad "direct plugin route"
288grep -q "plugins?plugin=" "$TMP/html.txt" && ok || bad "hub proxy route"
289grep -q "bot_active_pwd" "$TMP/html.txt" && ok || bad "pwd bootstrap"
290grep -q "X-Bot-Password" "$TMP/html.txt" && ok || bad "pwd header"
291grep -qi 'content-length' "$TMP/html.txt" && bad "html must not emit Content-Length" || ok
292
293echo "== initial id is injected and escaped"
294run 'id=s1' > "$TMP/html2.txt"
295grep -q "q.get('id')||'s1'" "$TMP/html2.txt" && ok || bad "initial id injected"
296mkdir -p "$S/bad'name"
297run "id=x%27y" > "$TMP/html3.txt"
298grep -q "q.get('id')||'x\\\\'y'" "$TMP/html3.txt" && ok || bad "single quote escaped in initial id"
299rm -rf "$S/bad'name"
300
301echo "== missing sessions root"
302out=$(SX_SESSIONS_DIR="$TMP/does-not-exist" QUERY_STRING='action=summary' "$BIN" | tail -1)
303printf '%s' "$out" > "$TMP/noroot.json"
304jsoncheck "root_found false" "$TMP/noroot.json" 'd["root_found"]' "False"
305jsoncheck "empty summary ok" "$TMP/noroot.json" 'd["ok"]' "True"
306jsoncheck "zero sessions" "$TMP/noroot.json" 'd["count"]' "0"
307jsoncheck "empty profiles" "$TMP/noroot.json" 'd["profiles"]' "[]"
308
309echo "== the root must be a directory, not any openable path"
310: > "$TMP/notadir"
311out=$(SX_SESSIONS_DIR="$TMP/notadir" QUERY_STRING='action=summary' "$BIN" | tail -1)
312printf '%s' "$out" > "$TMP/notadir.json"
313jsoncheck "file root rejected" "$TMP/notadir.json" 'd["root_found"]' "False"
314
315echo "== read-only guarantee"
316before=$(find "$S" -type f | wc -l | tr -d ' ')
317run 'action=summary' >/dev/null
318run 'action=session&sid=s1' >/dev/null
319run 'embed=1' >/dev/null
320after=$(find "$S" -type f | wc -l | tr -d ' ')
321check "no files created" "$after" "$before"
322diff -r "$S" "$S" >/dev/null 2>&1 && ok || bad "fixture tree unchanged"
323
324echo "== no emoji anywhere in the source"
325if grep -qP '[\x{1F300}-\x{1FAFF}\x{2600}-\x{27BF}]' "$ROOT/src/plugin_sessionstats.c" 2>/dev/null; then
326 bad "source contains emoji"
327else
328 ok
329fi
330
331echo "== no private addresses or credentials in the whole history"
332HIST="$TMP/history.txt"
333git -C "$ROOT" log -p --all 2>/dev/null \
334 | grep -v '^Author: ' \
335 | grep -vE 'scan "|audit "|HITS=|grep -E|P_ROOT=|P_WT=|PK="' > "$HIST" || : > "$HIST"
336check "no 192.168 in history" "$(grep -Eco '192\.168\.[0-9]+\.[0-9]+' "$HIST" || true)" "0"
337check "no 10.x private range" "$(grep -Eco '(^|[^0-9.])10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' "$HIST" || true)" "0"
338check "no 172.16-31 range" "$(grep -Eco '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' "$HIST" || true)" "0"
339check "no ghp_ token" "$(grep -Eco 'ghp_[A-Za-z0-9]{20,}' "$HIST" || true)" "0"
340check "no hf_ token" "$(grep -Eco 'hf_[A-Za-z0-9]{20,}' "$HIST" || true)" "0"
341check "no internal hostnames" "$(grep -Eco 'intel-ultra'"2"'|INTERNAL_HOST_B|INTERNAL_HOST_C' "$HIST" || true)" "0"
342check "no default password" "$(grep -Eco 'Xboxone'0909'|TESTPW' "$HIST" || true)" "0"
343
344echo "== Windows artifact shape (when the cross build exists)"
345if [ -f "$ROOT/plugin_sessionstats.exe" ]; then
346 check "windows artifact starts with MZ" "$(head -c 2 "$ROOT/plugin_sessionstats.exe")" "MZ"
347else
348 echo " skip (plugin_sessionstats.exe not built)"
349fi
350
351echo "== musl artifact shape (when the static build exists)"
352if [ -f "$ROOT/plugin_sessionstats.musl" ]; then
353 check "musl artifact is a static ELF" "$(head -c 4 "$ROOT/plugin_sessionstats.musl" | od -An -c | tr -d ' \n')" '177ELF'
354else
355 echo " skip (plugin_sessionstats.musl not built)"
356fi
357
358echo
359printf ' %d passed, %d failed\n' "$PASS" "$FAIL"
360[ "$FAIL" -eq 0 ] || exit 1