feat(sessionstats): clean-room session runtime and turn analytics plugin
A single C99 binary with three modes: --meta discovery, a JSON API (action=summary, action=session, format=json) and a responsive HTML dashboard. Reads meta.json, stats.json and events.jsonl read-only from the node session store and computes wall clock, active agent-run time, idle time, duty cycle, turns, tool-call frequency and profile/model usage. No dependencies, no writes, no network.
AuthorPico <picobot@scorpioplayer.com>
Date2026-11-11 06:55:39
Commitd21ce350
Changed files
.gitignore+9−0■■■■■
LICENSE+21−0■■■■■
Makefile+62−0■■■■■
README.md+175−0■■■■■
build.ps1+53−0■■■■■
plugin.json+12−0■■■■■
release-dist.sh+362−0■■■■■
src/plugin_sessionstats.c+1297−0■■■■■
tests/run.sh+350−0■■■■■
9 files+2341−0
Diff
.gitignore+9−0■■■■■
11new file mode 100644
index 0000000..8837948
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,9 @@
1+/plugin_sessionstats
2+/plugin_sessionstats.musl
3+/plugin_sessionstats.arm64
4+/plugin_sessionstats.exe
5+/plugin_sessionstats.macos-arm64
6+/plugin_sessionstats.macos-x86_64
7+*.o
8+*.tmp
9+*.dSYM
LICENSE+21−0■■■■■
11new file mode 100644
index 0000000..ef80120
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
1+MIT License
2+
3+Copyright (c) 2026 SCORPIOX INC
4+
5+Permission is hereby granted, free of charge, to any person obtaining a copy
6+of this software and associated documentation files (the "Software"), to deal
7+in the Software without restriction, including without limitation the rights
8+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+copies of the Software, and to permit persons to whom the Software is
10+furnished to do so, subject to the following conditions:
11+
12+The above copyright notice and this permission notice shall be included in all
13+copies or substantial portions of the Software.
14+
15+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+SOFTWARE.
Makefile+62−0■■■■■
11new file mode 100644
index 0000000..6404f26
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,62 @@
1+# plugin_sessionstats - ScorpioX Bot open-source session runtime & turn analytics
2+#
3+# Targets:
4+# make native build -> ./plugin_sessionstats
5+# make musl static musl x86_64 -> ./plugin_sessionstats.musl
6+# make arm64 static aarch64 musl -> ./plugin_sessionstats.arm64
7+# make win64 MinGW-w64 static PE -> ./plugin_sessionstats.exe
8+# make macos Apple clang (run on macOS)
9+# make test build + run tests/run.sh
10+# make clean
11+
12+CC ?= cc
13+CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings
14+MUSL_CC ?= musl-gcc
15+MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings
16+ARM_CC ?= aarch64-linux-gnu-gcc
17+ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings
18+WIN_CC ?= x86_64-w64-mingw32-gcc
19+WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings
20+SRC := src/plugin_sessionstats.c
21+BIN := plugin_sessionstats
22+EXE := plugin_sessionstats.exe
23+
24+.PHONY: all native musl arm64 win64 macos test clean help
25+
26+all: native
27+
28+native: $(BIN)
29+
30+$(BIN): $(SRC)
31+ @echo "==> native build ($(CC))"
32+ $(CC) $(CFLAGS) -o $(BIN) $(SRC)
33+
34+# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy)
35+musl: $(SRC)
36+ @echo "==> static musl build ($(MUSL_CC))"
37+ $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC)
38+
39+# Static aarch64 build - Raspberry Pi 5 / ARM64 servers
40+arm64: $(SRC)
41+ @echo "==> static arm64 build ($(ARM_CC))"
42+ $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC)
43+
44+# Native Win64 static PE - runs on any Windows 10/11 x64 node
45+win64: $(SRC)
46+ @echo "==> MinGW-w64 build ($(WIN_CC))"
47+ $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC)
48+
49+# Apple clang build (run this on macOS)
50+macos: $(SRC)
51+ @echo "==> Apple clang build"
52+ $(CC) -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -o $(BIN) $(SRC)
53+
54+test: native
55+ @sh tests/run.sh
56+
57+clean:
58+ rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN).macos-arm64 $(BIN).macos-x86_64
59+ rm -rf bin
60+
61+help:
62+ @echo "make | make musl | make arm64 | make win64 | make macos | make test | make clean"
README.md+175−0■■■■■
11new file mode 100644
index 0000000..b0b7a32
--- /dev/null
+++ b/README.md
@@ -0,0 +1,175 @@
1+# plugin_sessionstats
2+
3+Session runtime and turn analytics for a ScorpioX Bot node — a single clean-room
4+C99 binary, MIT licensed, with no dependency beyond libc.
5+
6+It reads the local session store and reports how long each session ran, how much
7+of that time the agent was actually working versus waiting for a prompt, how many
8+turns it took, which tools were called, and which profile/model did the work.
9+
10+## What it reads
11+
12+Read-only, local only, no network:
13+
14+```
15+<root>/<session>/
16+├── meta.json session id, start time, model, provider, profile, cwd, thread
17+├── stats.json branch and token counters (optional)
18+├── events.jsonl the event stream: run starts, idles, tool calls
19+└── thinking present while the agent is actively working (marker only)
20+```
21+
22+`<root>` is `$SX_SESSIONS_DIR` when set, otherwise `%LOCALAPPDATA%\scorpiox\sessions`
23+or `%USERPROFILE%\.scorpiox\sessions` on Windows, and `~/.scorpiox/sessions` or
24+`/workspace/.scorpiox/sessions` on POSIX.
25+
26+**Active time** is measured from `agent_run_start` to the next
27+`agent_idle` / `agent_complete` / `session_end` / `session_compact`, and a run
28+that is still open counts up to the last event. **Idle time** is the remainder of
29+the wall clock. Timestamps in these files are local wall-clock text, and only
30+differences are used, so no timezone database is needed.
31+
32+## Three modes
33+
34+### 1. Discovery
35+
36+```sh
37+./plugin_sessionstats --meta
38+# {"name":"sessions","desc":"Turn metrics"}
39+```
40+
41+`SX_PLUGIN_META=1` does the same. This route stays unauthenticated so `/plugins`
42+discovery works.
43+
44+### 2. JSON API
45+
46+```sh
47+./plugin_sessionstats ?action=summary
48+./plugin_sessionstats ?action=session&sid=2026_11_10_vibrant_leibniz
49+./plugin_sessionstats ?format=json
50+```
51+
52+`action=summary` returns the aggregate plus every session:
53+
54+```json
55+{
56+ "ok": true,
57+ "plugin": "plugin_sessionstats",
58+ "version": "1.0.0",
59+ "sessions_root": "/root/.scorpiox/sessions",
60+ "root_found": true,
61+ "count": 12,
62+ "active_now": 1,
63+ "total_sec": 91540, "total_fmt": "1d 01h 25m",
64+ "active_sec": 41230, "active_fmt": "11h 27m 10s",
65+ "idle_sec": 50310, "idle_fmt": "13h 58m 30s",
66+ "duty_cycle_pct": 45.04,
67+ "turns": 96,
68+ "tool_events": 1841,
69+ "profiles": [{"profile": "sglang-personal-deepseek", "sessions": 9, "active_sec": 38010, "turns": 74}],
70+ "models": [{"model": "deepseek-v4.1-flash", "sessions": 9, "active_sec": 38010, "turns": 74}],
71+ "sessions": [
72+ {
73+ "id": "2026_11_10_vibrant_leibniz",
74+ "dir": "2026_11_10_vibrant_leibniz",
75+ "model": "deepseek-v4.1-flash",
76+ "provider": "openai",
77+ "profile": "sglang-personal-deepseek",
78+ "branch": "main",
79+ "cwd": "/codebases/x",
80+ "start_time": "2026-11-10 17:40:32",
81+ "first_epoch": 1794332432,
82+ "last_epoch": 1794339727,
83+ "is_active": false,
84+ "total_sec": 7295, "total_fmt": "02h 01m 35s",
85+ "active_sec": 7226, "active_fmt": "02h 00m 26s",
86+ "idle_sec": 69, "idle_fmt": "01m 09s",
87+ "duty_cycle_pct": 99.05,
88+ "turns": 1,
89+ "avg_turn_sec": 7226.0,
90+ "tokens": {"in": 325122, "out": 462, "cache_read": 317568, "cache_write": 7554},
91+ "tools": [{"name": "Bash", "calls": 345}, {"name": "ReadImage", "calls": 11}]
92+ }
93+ ]
94+}
95+```
96+
97+`action=session&sid=<dir-or-full-id>` returns one session plus a small
98+`summary` block, and accepts `sid` older than the scan window. `id=` is an alias
99+for `sid=`. Everything is percent-decoded.
100+
101+### 3. HTML UI
102+
103+`GET` with no action returns a responsive dashboard: KPI cards, an
104+active-versus-idle rail, profile and model time bars, a sortable session table
105+and a per-session tool breakdown. It follows `prefers-color-scheme`, has an
106+explicit theme toggle, and reflows down to 390 px.
107+
108+It also works inside the Chat floating window (`?embed=1`) and pre-selects a
109+session from `?id=`.
110+
111+## Authentication
112+
113+When `BOT_PASSWORD` is set on the node, every route except `--meta` requires one
114+of:
115+
116+* `X-Bot-Password: <password>`
117+* `Authorization: Bearer <password>`
118+* `?pwd=<password>` (what the bot web UI appends)
119+
120+Without `BOT_PASSWORD` the plugin is a no-op on auth, which keeps local
121+development and the offline tests simple.
122+
123+## Build
124+
125+```sh
126+make # native
127+make musl # static x86_64 musl - the universal Linux artifact
128+make arm64 # static aarch64 musl - Raspberry Pi 5 / ARM64 servers
129+make win64 # static Win64 PE via MinGW-w64
130+make macos # Apple clang, run on macOS
131+make test # build + run the offline assertion suite
132+```
133+
134+On Windows: `powershell -ExecutionPolicy Bypass -File build.ps1`.
135+
136+## Install
137+
138+```sh
139+mkdir -p ~/.scorpiox/plugins
140+cp plugin_sessionstats ~/.scorpiox/plugins/
141+chmod +x ~/.scorpiox/plugins/plugin_sessionstats
142+```
143+
144+On a BotCloud container use `/workspace/.scorpiox/plugins` instead — it survives
145+container restarts. No server restart is needed; `scorpiox-server` resolves the
146+plugin directory on every request.
147+
148+## Release
149+
150+`./release-dist.sh` scans the full git history for secrets and private
151+addresses, builds every target it can, writes `manifest.json` + `SHA256SUMS` +
152+`source.tar.gz`, uploads to `dist.scorpiox.net/bot-plugins/sessionstats/1.0.0/`,
153+merges `index.json`, mirrors to plugingit, and verifies `latest.json`.
154+
155+Environment: `DIST_HOST`, `DIST_PASS`, `DIST_PATH`, `MAC_HOST`, `MAC_USER`,
156+`MAC_PASS`, `PLUGINGIT_TOKEN_FILE`.
157+
158+It silently **skips** a target it cannot build, so always check the target count
159+in `latest.json`, not the exit code. Run it on a host that actually has
160+`musl-gcc`, `aarch64-linux-gnu-gcc` and `x86_64-w64-mingw32-gcc`.
161+
162+## Tests
163+
164+`tests/run.sh` builds nothing and needs no network. It creates synthetic session
165+fixtures with fixed timestamps, then asserts exact durations, turn counts, tool
166+frequencies, profile buckets, sort order, the auth matrix, the HTML contract, the
167+read-only guarantee, and a full-history secret/LAN-IP scan.
168+
169+```sh
170+sh tests/run.sh ./plugin_sessionstats
171+```
172+
173+## License
174+
175+MIT. Copyright (c) 2026 SCORPIOX INC.
build.ps1+53−0■■■■■
11new file mode 100644
index 0000000..1059b87
--- /dev/null
+++ b/build.ps1
@@ -0,0 +1,53 @@
1+# build.ps1 - Windows MinGW-w64 static build for plugin_sessionstats
2+#
3+# Usage (from the repo root, PowerShell):
4+# powershell -ExecutionPolicy Bypass -File build.ps1
5+#
6+# Produces .\plugin_sessionstats.exe (static PE, runs on any Windows 10/11 x64 node).
7+# Requires x86_64-w64-mingw32-gcc or a WinLibs/UCRT gcc on PATH (or C:\gcc16\bin).
8+
9+$ErrorActionPreference = "Stop"
10+$ScriptDir = $PSScriptRoot
11+Push-Location $ScriptDir
12+try {
13+ $Src = Join-Path $ScriptDir "src\plugin_sessionstats.c"
14+ $Out = Join-Path $ScriptDir "plugin_sessionstats.exe"
15+ $Cc = "x86_64-w64-mingw32-gcc"
16+
17+ if (-not (Test-Path $Src)) { throw "source not found: $Src" }
18+
19+ # Prefer MinGW-w64, fall back to a plain gcc (WinLibs / MSYS2 UCRT) if present.
20+ if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) {
21+ if (Test-Path "C:\gcc16\bin\gcc.exe") {
22+ $Cc = "C:\gcc16\bin\gcc.exe"
23+ } elseif (Get-Command gcc -ErrorAction SilentlyContinue) {
24+ $Cc = "gcc"
25+ } else {
26+ throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)"
27+ }
28+ }
29+
30+ Write-Host "==> building plugin_sessionstats.exe with $Cc"
31+ & $Cc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -o $Out $Src
32+ if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" }
33+
34+ if (-not (Test-Path $Out)) { throw "build produced no output" }
35+
36+ # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not.
37+ $bytes = [System.IO.File]::ReadAllBytes($Out)
38+ if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) {
39+ throw "output is not a PE executable (missing MZ header)"
40+ }
41+
42+ Write-Host "==> metadata check"
43+ & $Out --meta
44+ if ($LASTEXITCODE -ne 0) { throw "--meta failed" }
45+
46+ $size = (Get-Item $Out).Length
47+ Write-Host ""
48+ Write-Host "Built $Out ($size bytes)"
49+ Write-Host "Install: Copy-Item plugin_sessionstats.exe `"`$env:LOCALAPPDATA\scorpiox\plugins\`""
50+}
51+finally {
52+ Pop-Location
53+}
plugin.json+12−0■■■■■
11new file mode 100644
index 0000000..c5f59f0
--- /dev/null
+++ b/plugin.json
@@ -0,0 +1,12 @@
1+{
2+ "slug": "sessionstats",
3+ "id": "plugin_sessionstats",
4+ "title": "Session Runtime & Turn Analytics",
5+ "summary": "Zero-dependency read-only analytics over the ScorpioX session store: wall-clock duration, active agent-run time versus idle waiting, duty cycle, turn counts, tool-call frequency and profile/model usage for every session on the node. Parses meta.json, stats.json and events.jsonl directly, so it needs no database, no daemon and no network.",
6+ "category": "sessions",
7+ "license": "MIT",
8+ "capabilities": ["local_filesystem_read", "session_store_read"],
9+ "trust_notice": "Executes native C code on your node. Opens session files under the local ScorpioX sessions directory read-only; it never writes, renames or deletes anything and makes zero network requests.",
10+ "author": "SCORPIOX INC",
11+ "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-sessionstats"
12+}
release-dist.sh+362−0■■■■■
11new file mode 100755
index 0000000..4dcf4fd
--- /dev/null
+++ b/release-dist.sh
@@ -0,0 +1,362 @@
1+#!/usr/bin/env bash
2+# release-dist.sh - build, scan and publish plugin_sessionstats to the plugin registry.
3+#
4+# Two paths:
5+# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it
6+# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI.
7+# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz ->
8+# manifest.json + SHA256SUMS -> upload -> latest.json / index.json.
9+#
10+# Nothing here contains a host address or a credential. Everything environment-specific
11+# comes from the environment, so this file stays safe to publish:
12+#
13+# DIST_HOST ssh target for the dist server (required for upload)
14+# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key)
15+# DIST_PATH remote web root of the dist server (default /data/dist)
16+# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64)
17+# MAC_USER / MAC_PASS (optional)
18+# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token)
19+# PLUGINGIT_REMOTE public mirror URL to push into
20+#
21+# Usage:
22+# ./release-dist.sh # full release
23+# ./release-dist.sh --dry-run # build + stage in /tmp, no upload
24+# ./release-dist.sh --no-macos # skip the macOS legs
25+# ./release-dist.sh --no-mirror # skip the plugingit mirror
26+# ./release-dist.sh --standalone # use this script even if the CLI is installed
27+# # (needed for plugins that link extra Win32 libs,
28+# # which the CLI's fixed link line cannot express)
29+
30+set -euo pipefail
31+
32+SLUG="sessionstats"
33+ID="plugin_sessionstats"
34+VERSION="1.0.0"
35+DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins"
36+
37+ROOT="$(cd "$(dirname "$0")" && pwd)"
38+cd "$ROOT"
39+
40+DRY_RUN=0
41+DO_MACOS=1
42+DO_MIRROR=1
43+STANDALONE=0
44+for arg in "$@"; do
45+ case "$arg" in
46+ --standalone) STANDALONE=1 ;;
47+ --dry-run) DRY_RUN=1 ;;
48+ --no-macos) DO_MACOS=0 ;;
49+ --no-mirror) DO_MIRROR=0 ;;
50+ -h|--help) sed -n '2,32p' "$0"; exit 0 ;;
51+ *) echo "unknown argument: $arg" >&2; exit 2 ;;
52+ esac
53+done
54+
55+DIST_HOST="${DIST_HOST:-}"
56+DIST_PASS="${DIST_PASS:-}"
57+DIST_PATH="${DIST_PATH:-/data/dist}"
58+PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}"
59+PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}"
60+
61+STAGE="/tmp/${SLUG}-dist-${VERSION}-$$"
62+mkdir -p "$STAGE"
63+trap 'rm -rf "$STAGE"' EXIT
64+
65+say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; }
66+die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; }
67+
68+# ---------------------------------------------------------------- 0. preflight
69+say "0/7 preflight"
70+
71+if [ "$STANDALONE" -eq 0 ] && command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
72+ say "using scorpiox-cli-botplugin publish"
73+ exec scorpiox-cli-botplugin publish "$ROOT"
74+fi
75+echo " running the standalone pipeline"
76+
77+[ -n "$(git status --porcelain 2>/dev/null)" ] && \
78+ echo " note: working tree is dirty; source.tar.gz comes from the last commit"
79+COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
80+echo " version $VERSION"
81+echo " commit $COMMIT"
82+
83+# ---------------------------------------------------------------- 1. secret scan
84+say "1/7 secret & LAN scan (full history)"
85+
86+SCAN_TMP="$STAGE/history.txt"
87+# Scan every added/removed line of every commit. Two exclusions, both about the
88+# audit rather than the code: the committer identity line, and any line that is
89+# itself a scan definition - otherwise this file's own detector patterns read as
90+# findings in every historical revision of it.
91+git log -p --all 2>/dev/null \
92+ | grep -v '^Author: ' \
93+ | grep -vE 'scan "|audit "|HITS=|grep -E|P_ROOT=|P_WT=|PK="|\$ALL' \
94+ > "$SCAN_TMP" || : > "$SCAN_TMP"
95+HITS=0
96+scan() { # scan <label> <regex>
97+ local out
98+ out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true)
99+ if [ -n "$out" ]; then
100+ printf ' \033[31mHIT\033[0m %s\n' "$1"
101+ printf '%s\n' "$out" | sed 's/^/ /'
102+ HITS=$((HITS + 1))
103+ else
104+ printf ' ok %s\n' "$1"
105+ fi
106+}
107+scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+'
108+scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
109+scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
110+scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
111+scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}'
112+scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}'
113+scan "hard-coded ssh password" 'sshpass -p [^"$]'
114+P_ROOT="/codebases"
115+P_PICOBOT="${P_ROOT}/pico""bot"
116+P_WT=".work""trees"
117+scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}"
118+scan "run-token env assignment" 'RUNNER_'"PASS="
119+if [ "$HITS" -ne 0 ]; then
120+ die "secret scan found $HITS problem(s) - refusing to publish"
121+fi
122+echo " clean: 0 hits"
123+
124+# ---------------------------------------------------------------- 2. build
125+say "2/7 build targets"
126+
127+# linux-x86_64 (glibc, native)
128+if command -v cc >/dev/null 2>&1; then
129+ cc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -o "$STAGE/$ID" src/$ID.c || die "native build failed"
130+ echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes"
131+else
132+ die "no native cc found"
133+fi
134+
135+# linux-x86_64-musl (fully static - the universal Linux artifact)
136+if command -v musl-gcc >/dev/null 2>&1; then
137+ musl-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -o "$STAGE/$ID.musl" src/$ID.c \
138+ || die "musl build failed"
139+ echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes"
140+else
141+ echo " skip linux-x86_64-musl (no musl-gcc)"
142+fi
143+
144+# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers)
145+if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
146+ aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -o "$STAGE/$ID.arm64" src/$ID.c \
147+ || die "arm64 build failed"
148+ echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes"
149+else
150+ echo " skip linux-arm64-musl (no aarch64-linux-gnu-gcc)"
151+fi
152+
153+# windows-x86_64 (static PE)
154+if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
155+ x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings \
156+ -o "$STAGE/$ID.exe" src/$ID.c || die "MinGW build failed"
157+ [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE"
158+ echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes"
159+else
160+ echo " skip windows-x86_64 (no MinGW cross compiler)"
161+fi
162+
163+# macOS legs - Mach-O must be produced by Apple clang on a real Mac.
164+# Both slices are cross-built from one host: -arch arm64 and -arch x86_64.
165+if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then
166+ MAC_USER="${MAC_USER:-$(whoami)}"
167+ MAC_DIR="/tmp/${ID}-mac-$$"
168+ echo " building macOS legs on $MAC_HOST"
169+ SSH_MAC=(ssh -o StrictHostKeyChecking=no)
170+ SCP_MAC=(scp -o StrictHostKeyChecking=no)
171+ if [ -n "${MAC_PASS:-}" ]; then
172+ SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}")
173+ SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}")
174+ fi
175+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then
176+ if "${SCP_MAC[@]}" src/$ID.c "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.c"; then
177+ # Build straight from the uploaded file - no src/ tree on the remote.
178+ for slice in arm64 x86_64; do
179+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \
180+ "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -arch $slice -o $ID.$slice $ID.c" \
181+ 2>/dev/null; then
182+ "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \
183+ && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)"
184+ else
185+ echo " warn: macos-$slice build failed on $MAC_HOST"
186+ fi
187+ done
188+ "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" || true
189+ else
190+ echo " warn: could not upload source to $MAC_HOST"
191+ fi
192+ else
193+ echo " warn: cannot reach macOS builder $MAC_HOST"
194+ fi
195+else
196+ echo " skip macOS legs (no MAC_HOST or --no-macos)"
197+fi
198+
199+# ---------------------------------------------------------------- 3. manifest
200+say "3/7 manifest + checksums"
201+
202+git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \
203+ -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \
204+ || tar -czf "$STAGE/source.tar.gz" --exclude=.git .
205+echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes"
206+
207+target_meta() { # target_meta <key> <file> <format> <relpath>
208+ local key="$1" file="$2" fmt="$3" rel="$4"
209+ [ -f "$file" ] || return 0
210+ local sha size
211+ sha=$(sha256sum "$file" | awk '{print $1}')
212+ size=$(wc -c < "$file" | tr -d ' ')
213+ printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \
214+ "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt"
215+}
216+
217+{
218+ printf '{\n'
219+ printf ' "slug": "%s",\n' "$SLUG"
220+ printf ' "id": "%s",\n' "$ID"
221+ printf ' "name": "sessions",\n'
222+ printf ' "desc": "Turn metrics",\n'
223+ printf ' "title": "Session Runtime & Turn Analytics",\n'
224+ printf ' "summary": "Zero-dependency read-only analytics over the ScorpioX session store: wall-clock duration, active agent-run time versus idle waiting, duty cycle, turn counts, tool-call frequency and profile/model usage for every session on the node. Parses meta.json, stats.json and events.jsonl directly, so it needs no database, no daemon and no network.",\n'
225+ printf ' "category": "sessions",\n'
226+ printf ' "version": "%s",\n' "$VERSION"
227+ printf ' "license": "MIT",\n'
228+ printf ' "trust_notice": "Executes native C code on your node. Opens session files under the local ScorpioX sessions directory read-only; it never writes, renames or deletes anything and makes zero network requests.",\n'
229+ printf ' "capabilities": ["local_filesystem_read", "session_store_read"],\n'
230+ printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG"
231+ printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG"
232+ printf ' "git_commit": "%s",\n' "$COMMIT"
233+ printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
234+ printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')"
235+ printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID"
236+ printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c",\n' "$ID" "$ID"
237+ printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
238+ printf ' "targets": {\n'
239+ first=1
240+ emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; }
241+ emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID"
242+ emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID"
243+ emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID"
244+ emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID"
245+ emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID"
246+ emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe"
247+ printf '\n }\n}\n'
248+} > "$STAGE/manifest.json"
249+
250+python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \
251+ || die "generated manifest.json is not valid JSON"
252+echo " manifest.json ok ($(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["targets"]))' "$STAGE/manifest.json") targets)"
253+
254+# SHA256SUMS - relative paths, exactly as published
255+( cd "$STAGE"
256+ for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done
257+ [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|"
258+ [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|"
259+ [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|"
260+ [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|"
261+ [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|"
262+ [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|"
263+ true ) > "$STAGE/SHA256SUMS"
264+echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries"
265+
266+# ---------------------------------------------------------------- 4. stage
267+say "4/7 stage tree"
268+PKG="$STAGE/pkg"
269+mkdir -p "$PKG"
270+cp "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/"
271+[ -f "$STAGE/$ID" ] && { mkdir -p "$PKG/linux-x86_64"; cp "$STAGE/$ID" "$PKG/linux-x86_64/$ID"; }
272+[ -f "$STAGE/$ID.musl" ] && { mkdir -p "$PKG/linux-x86_64-musl"; cp "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID"; }
273+[ -f "$STAGE/$ID.arm64" ] && { mkdir -p "$PKG/linux-arm64-musl"; cp "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID"; }
274+[ -f "$STAGE/$ID.macos-arm64" ] && { mkdir -p "$PKG/macos-arm64"; cp "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"; }
275+[ -f "$STAGE/$ID.macos-x86_64" ]&& { mkdir -p "$PKG/macos-x86_64"; cp "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"; }
276+[ -f "$STAGE/$ID.exe" ] && { mkdir -p "$PKG/windows-x86_64"; cp "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe"; }
277+echo " staged: $(find "$PKG" -type f | wc -l | tr -d ' ') file(s)"
278+
279+if [ "$DRY_RUN" -eq 1 ]; then
280+ say "dry run - leaving the staging tree in $PKG"
281+ trap - EXIT
282+ exit 0
283+fi
284+
285+# ---------------------------------------------------------------- 5. upload
286+say "5/7 upload to the dist server"
287+[ -n "$DIST_HOST" ] || die "DIST_HOST is not set (export DIST_HOST=<ssh-target>)"
288+SSH=(ssh -o StrictHostKeyChecking=no)
289+SCP=(scp -o StrictHostKeyChecking=no)
290+if [ -n "$DIST_PASS" ]; then
291+ SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}")
292+ SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}")
293+fi
294+REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION"
295+
296+"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \
297+ || die "cannot create $REMOTE_DIR on $DIST_HOST"
298+# Stage to one tarball, transfer it, extract remotely. Streaming tar through
299+# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and
300+# OpenSSH 9 refuses to scp a bare "." source.
301+tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed"
302+"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed"
303+"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \
304+ || die "remote extract failed"
305+echo " uploaded to $DIST_HOST:$REMOTE_DIR"
306+
307+# latest.json = copy of this version's manifest
308+"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \
309+ || die "latest.json update failed"
310+echo " updated bot-plugins/$SLUG/latest.json"
311+
312+# index.json - merge, preserving every sibling <slug>/latest.json
313+say "index.json merge"
314+"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY'
315+import json, os, sys, glob
316+slug = sys.argv[1]
317+entries = {}
318+for p in sorted(glob.glob('*/latest.json')):
319+ s = os.path.dirname(p)
320+ try:
321+ entries[s] = json.load(open(p))
322+ except Exception:
323+ pass
324+index = {
325+ 'ok': True,
326+ 'service': 'bot-plugins-dist',
327+ 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins',
328+ 'count': len(entries),
329+ 'slugs': sorted(entries),
330+ 'plugins': [entries[k] for k in sorted(entries)],
331+}
332+open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10))
333+os.replace('index.json.tmp', 'index.json')
334+print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries))))
335+PY" || die "index.json merge failed"
336+
337+# ---------------------------------------------------------------- 6. mirror
338+say "6/7 plugingit mirror"
339+if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then
340+ TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE")
341+ AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://token:${TOKEN}@|")
342+ git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed"
343+ git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true
344+ echo " mirrored to $PLUGINGIT_REMOTE"
345+else
346+ echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)"
347+fi
348+
349+# ---------------------------------------------------------------- 7. verify
350+say "7/7 verify"
351+CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \
352+ "$DIST_BASE_URL/$SLUG/latest.json" || echo 000)
353+if [ "$CODE" = "200" ]; then
354+ python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK - %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \
355+ "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON"
356+else
357+ echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE"
358+fi
359+
360+printf '\n\033[1mrelease complete\033[0m\n'
361+printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
362+printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
src/plugin_sessionstats.c+1297−0■■■■■
11new file mode 100644
index 0000000..716d9c8
--- /dev/null
+++ b/src/plugin_sessionstats.c
@@ -0,0 +1,1297 @@
1+/*
2+ * plugin_sessionstats - ScorpioX Bot open-source session runtime & turn analytics
3+ *
4+ * A single clean-room C99 binary that serves THREE modes:
5+ * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata
6+ * 2. ?action=summary | ?action=session&sid=... | ?format=json -> JSON node API
7+ * 3. GET (default) -> responsive HTML analytics UI
8+ *
9+ * Everything it reads is LOCAL to the node and read-only: the per-session
10+ * directories under the ScorpioX sessions root (meta.json, stats.json,
11+ * events.jsonl, and the optional "thinking" marker). Nothing is ever written,
12+ * renamed or deleted. There is no parameter anywhere in this file that can
13+ * point it at another host or another path outside the sessions root.
14+ *
15+ * Every timestamp in the session files is local wall-clock text
16+ * ("YYYY-MM-DD HH:MM:SS"). Only differences between timestamps are used, so a
17+ * single deterministic civil-days conversion is sufficient and no timezone
18+ * database is required.
19+ *
20+ * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and
21+ * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under
22+ * scorpiox-server on the node.
23+ *
24+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
25+ */
26+
27+#if defined(_WIN32) && !defined(_WIN32_WINNT)
28+# define _WIN32_WINNT 0x0601
29+#endif
30+
31+#if !defined(_WIN32)
32+# define _POSIX_C_SOURCE 200809L
33+# define _DEFAULT_SOURCE 1
34+# if defined(__APPLE__)
35+# define _DARWIN_C_SOURCE 1
36+# endif
37+#endif
38+
39+#include <stdio.h>
40+#include <stdlib.h>
41+#include <string.h>
42+#include <ctype.h>
43+#include <time.h>
44+#include <errno.h>
45+
46+#if defined(_WIN32)
47+# define WIN32_LEAN_AND_MEAN
48+# include <windows.h>
49+# include <direct.h>
50+# define SX_PATHSEP '\\'
51+#else
52+# include <unistd.h>
53+# include <dirent.h>
54+# include <sys/stat.h>
55+# include <sys/types.h>
56+# define SX_PATHSEP '/'
57+#endif
58+
59+#define PLUGIN_SLUG "sessionstats"
60+#define PLUGIN_ID "plugin_sessionstats"
61+#define PLUGIN_VER "1.0.0"
62+
63+#define NAME_SZ 128
64+#define MAX_SESSIONS 256
65+#define MAX_TOOLS 48
66+#define MAX_ROOTS 4
67+#define LINE_SZ 4096
68+#define FILE_SZ 16384
69+#define PATH_SZ 1024
70+
71+/* ------------------------------------------------------------------ */
72+/* Small string helpers */
73+/* ------------------------------------------------------------------ */
74+
75+static void str_copy(char *dst, size_t sz, const char *src)
76+{
77+ size_t i = 0;
78+ if (!dst || sz == 0) return;
79+ if (!src) { dst[0] = '\0'; return; }
80+ while (i + 1 < sz && src[i]) { dst[i] = src[i]; i++; }
81+ dst[i] = '\0';
82+}
83+
84+static void url_decode(char *s)
85+{
86+ char *o = s;
87+ if (!s) return;
88+ while (*s) {
89+ if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) {
90+ int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10);
91+ int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10);
92+ *o++ = (char)((hi << 4) | lo);
93+ s += 3;
94+ } else if (*s == '+') {
95+ *o++ = ' ';
96+ s++;
97+ } else {
98+ *o++ = *s++;
99+ }
100+ }
101+ *o = '\0';
102+}
103+
104+/* Read one query parameter, percent-decoded. Returns 1 when present. */
105+static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
106+{
107+ size_t klen;
108+ const char *p;
109+
110+ if (!out || outsz == 0) return 0;
111+ out[0] = '\0';
112+ if (!qs || !key) return 0;
113+ klen = strlen(key);
114+
115+ for (p = qs; *p; ) {
116+ if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
117+ const char *v = p + klen + 1;
118+ size_t i = 0;
119+ while (*v && *v != '&' && i + 1 < outsz) out[i++] = *v++;
120+ out[i] = '\0';
121+ url_decode(out);
122+ return 1;
123+ }
124+ p = strchr(p, '&');
125+ if (!p) break;
126+ p++;
127+ }
128+ return 0;
129+}
130+
131+static void json_str(const char *s)
132+{
133+ fputc('"', stdout);
134+ for (; s && *s; s++) {
135+ unsigned char c = (unsigned char)*s;
136+ if (c == '"' || c == '\\') { fputc('\\', stdout); fputc((char)c, stdout); }
137+ else if (c == '\n') fputs("\\n", stdout);
138+ else if (c == '\r') fputs("\\r", stdout);
139+ else if (c == '\t') fputs("\\t", stdout);
140+ else if (c >= 0x20 && c != 0x7f) fputc((char)c, stdout);
141+ }
142+ fputc('"', stdout);
143+}
144+
145+/* ------------------------------------------------------------------ */
146+/* Node security */
147+/* ------------------------------------------------------------------ */
148+
149+static void require_node_auth(void)
150+{
151+ const char *np = getenv("BOT_PASSWORD");
152+ const char *xp, *auth;
153+ char qpwd[128] = {0};
154+
155+ if (!np || !*np) return;
156+
157+ xp = getenv("HTTP_X_BOT_PASSWORD");
158+ if (xp && strcmp(xp, np) == 0) return;
159+
160+ auth = getenv("HTTP_AUTHORIZATION");
161+ if (auth) {
162+ while (*auth == ' ') auth++;
163+ if (strncasecmp(auth, "Bearer ", 7) == 0) {
164+ auth += 7;
165+ while (*auth == ' ') auth++;
166+ if (strcmp(auth, np) == 0) return;
167+ }
168+ }
169+
170+ if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof qpwd)
171+ && strcmp(qpwd, np) == 0) return;
172+
173+ fputs("Status: 401 Unauthorized\r\n"
174+ "Content-Type: application/json; charset=utf-8\r\n\r\n"
175+ "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
176+ exit(0);
177+}
178+
179+/* ------------------------------------------------------------------ */
180+/* Time helpers */
181+/* ------------------------------------------------------------------ */
182+
183+/* Days since 1970-01-01 for a proleptic Gregorian civil date. */
184+static long long days_from_civil(int y, int m, int d)
185+{
186+ long long era, yoe, doy, doe;
187+ y -= (m <= 2);
188+ era = (y >= 0 ? y : y - 399) / 400;
189+ yoe = (long long)(y - era * 400);
190+ doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1;
191+ doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
192+ return era * 146097 + doe - 719468;
193+}
194+
195+/* Parse "YYYY-MM-DD HH:MM:SS". Returns 0 when unparseable. */
196+static long long parse_ts(const char *ts)
197+{
198+ int Y, M, D, h, mi, s;
199+ if (!ts || strlen(ts) < 19) return 0;
200+ if (sscanf(ts, "%d-%d-%d %d:%d:%d", &Y, &M, &D, &h, &mi, &s) != 6) return 0;
201+ if (M < 1 || M > 12 || D < 1 || D > 31) return 0;
202+ return days_from_civil(Y, M, D) * 86400LL + h * 3600LL + mi * 60LL + s;
203+}
204+
205+static void format_duration(long long sec, char *out, size_t outsz)
206+{
207+ long long d, h, m, s;
208+ if (sec < 0) sec = 0;
209+ d = sec / 86400;
210+ sec %= 86400;
211+ h = sec / 3600;
212+ sec %= 3600;
213+ m = sec / 60;
214+ s = sec % 60;
215+ if (d > 0) snprintf(out, outsz, "%lldd %02lldh %02lldm", d, h, m);
216+ else if (h > 0) snprintf(out, outsz, "%02lldh %02lldm %02llds", h, m, s);
217+ else if (m > 0) snprintf(out, outsz, "%02lldm %02llds", m, s);
218+ else snprintf(out, outsz, "%llds", s);
219+}
220+
221+/* ------------------------------------------------------------------ */
222+/* File helpers */
223+/* ------------------------------------------------------------------ */
224+
225+/* Read at most sz-1 bytes of a file into buf. Returns bytes read, -1 if absent. */
226+static int read_file(const char *path, char *buf, size_t sz)
227+{
228+ FILE *f;
229+ size_t n;
230+ if (!buf || sz == 0) return -1;
231+ buf[0] = '\0';
232+ f = fopen(path, "rb");
233+ if (!f) return -1;
234+ n = fread(buf, 1, sz - 1, f);
235+ buf[n] = '\0';
236+ fclose(f);
237+ return (int)n;
238+}
239+
240+static int path_exists(const char *path)
241+{
242+ FILE *f = fopen(path, "rb");
243+ if (f) { fclose(f); return 1; }
244+ return 0;
245+}
246+
247+/* Directory test, portable: fopen() on a directory succeeds on glibc, so a
248+ * real stat-equivalent is needed to answer "is this a sessions root?". */
249+static int sx_is_dir(const char *path)
250+{
251+#if defined(_WIN32)
252+ DWORD a = GetFileAttributesA(path);
253+ return (a != INVALID_FILE_ATTRIBUTES) && (a & FILE_ATTRIBUTE_DIRECTORY);
254+#else
255+ struct stat st;
256+ return (stat(path, &st) == 0) && S_ISDIR(st.st_mode);
257+#endif
258+}
259+
260+/* Extract a JSON string value for an exact top-level key name. */
261+static int json_get_str(const char *json, const char *key, char *out, size_t outsz)
262+{
263+ char needle[96];
264+ const char *p;
265+ size_t i = 0;
266+
267+ if (!json || !key || !out || outsz == 0) return 0;
268+ out[0] = '\0';
269+ if (strlen(key) + 3 >= sizeof needle) return 0;
270+ snprintf(needle, sizeof needle, "\"%s\"", key);
271+
272+ p = strstr(json, needle);
273+ if (!p) return 0;
274+ p += strlen(needle);
275+ while (*p && (*p == ' ' || *p == ':' || *p == '\t')) p++;
276+ if (*p != '"') return 0;
277+ p++;
278+ while (*p && *p != '"' && i + 1 < outsz) {
279+ if (*p == '\\' && p[1]) {
280+ p++;
281+ switch (*p) {
282+ case 'n': out[i++] = '\n'; break;
283+ case 't': out[i++] = '\t'; break;
284+ case 'r': out[i++] = '\r'; break;
285+ default: out[i++] = *p; break;
286+ }
287+ p++;
288+ continue;
289+ }
290+ out[i++] = *p++;
291+ }
292+ out[i] = '\0';
293+ return 1;
294+}
295+
296+/* Extract a numeric JSON value for an exact key name. */
297+static int json_get_num(const char *json, const char *key, double *out)
298+{
299+ char needle[96];
300+ const char *p;
301+ char *end = NULL;
302+
303+ if (!json || !key || !out) return 0;
304+ if (strlen(key) + 3 >= sizeof needle) return 0;
305+ snprintf(needle, sizeof needle, "\"%s\"", key);
306+
307+ p = strstr(json, needle);
308+ if (!p) return 0;
309+ p += strlen(needle);
310+ while (*p && (*p == ' ' || *p == ':' || *p == '\t')) p++;
311+ if (*p != '-' && !isdigit((unsigned char)*p)) return 0;
312+ *out = strtod(p, &end);
313+ return (end != p);
314+}
315+
316+/* ------------------------------------------------------------------ */
317+/* Directory listing (portable, directories only, dotfiles skipped) */
318+/* ------------------------------------------------------------------ */
319+
320+#if defined(_WIN32)
321+static int sx_list_dirs(const char *parent, char names[][NAME_SZ], int max)
322+{
323+ char pattern[PATH_SZ + 8];
324+ WIN32_FIND_DATAA fd;
325+ HANDLE h;
326+ int n = 0;
327+
328+ snprintf(pattern, sizeof pattern, "%s/*", parent);
329+ h = FindFirstFileA(pattern, &fd);
330+ if (h == INVALID_HANDLE_VALUE) return 0;
331+ do {
332+ if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) continue;
333+ if (fd.cFileName[0] == '.') continue;
334+ if (n < max) str_copy(names[n++], NAME_SZ, fd.cFileName);
335+ } while (FindNextFileA(h, &fd));
336+ FindClose(h);
337+ return n;
338+}
339+#else
340+static int sx_list_dirs(const char *parent, char names[][NAME_SZ], int max)
341+{
342+ DIR *d;
343+ struct dirent *de;
344+ int n = 0;
345+
346+ d = opendir(parent);
347+ if (!d) return 0;
348+ while ((de = readdir(d)) != NULL) {
349+ char full[PATH_SZ];
350+ struct stat st;
351+ if (de->d_name[0] == '.') continue;
352+ snprintf(full, sizeof full, "%s/%s", parent, de->d_name);
353+ if (stat(full, &st) != 0 || !S_ISDIR(st.st_mode)) continue;
354+ if (n < max) str_copy(names[n++], NAME_SZ, de->d_name);
355+ }
356+ closedir(d);
357+ return n;
358+}
359+#endif
360+
361+/* ------------------------------------------------------------------ */
362+/* Sessions root discovery */
363+/* ------------------------------------------------------------------ */
364+
365+/*
366+ * Resolve the sessions root. SX_SESSIONS_DIR always wins, which is what makes
367+ * the offline test suite possible and also what lets an operator point the
368+ * plugin at a relocated state directory. Otherwise the standard per-node
369+ * locations are tried in order.
370+ */
371+static int resolve_sessions_root(char *out, size_t outsz)
372+{
373+ const char *env = getenv("SX_SESSIONS_DIR");
374+#if !defined(_WIN32)
375+ const char *home;
376+#endif
377+ char cand[PATH_SZ];
378+
379+ if (env && *env) {
380+ str_copy(out, outsz, env);
381+ return sx_is_dir(env);
382+ }
383+
384+#if defined(_WIN32)
385+ const char *localappdata = getenv("LOCALAPPDATA");
386+ const char *userprofile = getenv("USERPROFILE");
387+ if (localappdata && *localappdata) {
388+ snprintf(cand, sizeof cand, "%s\\scorpiox\\sessions", localappdata);
389+ if (sx_is_dir(cand)) { str_copy(out, outsz, cand); return 1; }
390+ }
391+ if (userprofile && *userprofile) {
392+ snprintf(cand, sizeof cand, "%s\\.scorpiox\\sessions", userprofile);
393+ if (sx_is_dir(cand)) { str_copy(out, outsz, cand); return 1; }
394+ }
395+#else
396+ home = getenv("HOME");
397+ if (home && *home) {
398+ snprintf(cand, sizeof cand, "%s/.scorpiox/sessions", home);
399+ if (sx_is_dir(cand)) { str_copy(out, outsz, cand); return 1; }
400+ }
401+ if (sx_is_dir("/workspace/.scorpiox/sessions")) {
402+ str_copy(out, outsz, "/workspace/.scorpiox/sessions");
403+ return 1;
404+ }
405+#endif
406+
407+ /* Not found: report the most natural path so the UI can say what is missing. */
408+#if defined(_WIN32)
409+ if (localappdata && *localappdata)
410+ snprintf(out, outsz, "%s\\scorpiox\\sessions", localappdata);
411+ else
412+ str_copy(out, outsz, "scorpiox\\sessions");
413+#else
414+ if (home && *home) snprintf(out, outsz, "%s/.scorpiox/sessions", home);
415+ else str_copy(out, outsz, ".scorpiox/sessions");
416+#endif
417+ return 0;
418+}
419+
420+/* ------------------------------------------------------------------ */
421+/* One session */
422+/* ------------------------------------------------------------------ */
423+
424+typedef struct {
425+ char name[NAME_SZ];
426+} tool_use_t;
427+
428+typedef struct {
429+ char id[NAME_SZ]; /* directory name */
430+ char session_id[NAME_SZ];
431+ char start_time[40];
432+ long long start_epoch; /* from meta.json when present */
433+ long long first_ts; /* first event timestamp */
434+ long long last_ts; /* last event timestamp */
435+ long long total_sec;
436+ long long active_sec;
437+ long long idle_sec;
438+ double duty_pct;
439+ int turns;
440+ int is_active;
441+ char model[64];
442+ char provider[64];
443+ char profile[64];
444+ char branch[128];
445+ char cwd[512];
446+ char thread_guid[64];
447+ long long in_tokens;
448+ long long out_tokens;
449+ long long cache_read;
450+ long long cache_write;
451+ tool_use_t tools[MAX_TOOLS];
452+ int tool_count;
453+ int tool_hits[MAX_TOOLS];
454+} session_t;
455+
456+/* Record (and count) one tool name for this session. */
457+static void note_tool(session_t *s, const char *name)
458+{
459+ int i;
460+ if (!name || !*name) return;
461+ for (i = 0; i < s->tool_count; i++) {
462+ if (strcmp(s->tools[i].name, name) == 0) { s->tool_hits[i]++; return; }
463+ }
464+ if (s->tool_count >= MAX_TOOLS) return;
465+ str_copy(s->tools[s->tool_count].name, NAME_SZ, name);
466+ s->tool_hits[s->tool_count] = 1;
467+ s->tool_count++;
468+}
469+
470+/*
471+ * Parse one session directory. Read-only: opens meta.json, stats.json,
472+ * events.jsonl and probes for the "thinking" marker. Any missing file simply
473+ * contributes nothing.
474+ */
475+static int load_session(const char *root, const char *name, session_t *s)
476+{
477+ char path[PATH_SZ];
478+ char buf[FILE_SZ];
479+ double num;
480+
481+ memset(s, 0, sizeof *s);
482+ str_copy(s->id, sizeof s->id, name);
483+ str_copy(s->session_id, sizeof s->session_id, name);
484+
485+ /* Refuse a directory name that is not actually present: the caller uses
486+ * this return value to answer "session not found". */
487+ snprintf(path, sizeof path, "%s/%s", root, name);
488+ if (!sx_is_dir(path)) return 0;
489+
490+ /* --- meta.json --- */
491+ snprintf(path, sizeof path, "%s/%s/meta.json", root, name);
492+ if (read_file(path, buf, sizeof buf) > 0) {
493+ char tmp[NAME_SZ];
494+ if (json_get_str(buf, "id", tmp, sizeof tmp)) str_copy(s->session_id, sizeof s->session_id, tmp);
495+ json_get_str(buf, "start_time", s->start_time, sizeof s->start_time);
496+ json_get_str(buf, "model", s->model, sizeof s->model);
497+ json_get_str(buf, "provider", s->provider, sizeof s->provider);
498+ json_get_str(buf, "profile", s->profile, sizeof s->profile);
499+ json_get_str(buf, "cwd", s->cwd, sizeof s->cwd);
500+ json_get_str(buf, "thread_guid", s->thread_guid, sizeof s->thread_guid);
501+ if (json_get_num(buf, "start_epoch", &num)) s->start_epoch = (long long)num;
502+ }
503+
504+ /* --- stats.json (optional usage block) --- */
505+ snprintf(path, sizeof path, "%s/%s/stats.json", root, name);
506+ if (read_file(path, buf, sizeof buf) > 0) {
507+ if (!s->model[0]) json_get_str(buf, "model", s->model, sizeof s->model);
508+ if (!s->cwd[0]) json_get_str(buf, "cwd", s->cwd, sizeof s->cwd);
509+ json_get_str(buf, "branch", s->branch, sizeof s->branch);
510+ if (json_get_num(buf, "input_tokens", &num)) s->in_tokens = (long long)num;
511+ if (json_get_num(buf, "output_tokens", &num)) s->out_tokens = (long long)num;
512+ if (json_get_num(buf, "cache_read_tokens", &num)) s->cache_read = (long long)num;
513+ if (json_get_num(buf, "cache_creation_tokens", &num))s->cache_write = (long long)num;
514+ }
515+
516+ /* --- thinking / active marker --- */
517+ snprintf(path, sizeof path, "%s/%s/thinking", root, name);
518+ if (path_exists(path)) s->is_active = 1;
519+
520+ /* --- events.jsonl: single streaming pass --- */
521+ snprintf(path, sizeof path, "%s/%s/events.jsonl", root, name);
522+ {
523+ FILE *f = fopen(path, "rb");
524+ char line[LINE_SZ];
525+ long long run_start = 0;
526+ int in_run = 0;
527+
528+ if (f) {
529+ while (fgets(line, sizeof line, f)) {
530+ char ts[40] = {0};
531+ char ev[48] = {0};
532+ long long t;
533+
534+ if (!json_get_str(line, "ts", ts, sizeof ts)) continue;
535+ t = parse_ts(ts);
536+ if (t <= 0) continue;
537+ json_get_str(line, "event", ev, sizeof ev);
538+
539+ if (!s->first_ts) s->first_ts = t;
540+ s->last_ts = t;
541+
542+ if (strcmp(ev, "session_start") == 0) {
543+ if (!s->start_time[0]) str_copy(s->start_time, sizeof s->start_time, ts);
544+ if (!s->model[0]) json_get_str(line, "model", s->model, sizeof s->model);
545+ if (!s->provider[0]) json_get_str(line, "provider", s->provider, sizeof s->provider);
546+ if (!s->profile[0]) json_get_str(line, "profile", s->profile, sizeof s->profile);
547+ } else if (strcmp(ev, "agent_run_start") == 0) {
548+ if (!in_run) { in_run = 1; run_start = t; s->turns++; }
549+ } else if (strcmp(ev, "agent_idle") == 0
550+ || strcmp(ev, "agent_complete") == 0
551+ || strcmp(ev, "session_end") == 0
552+ || strcmp(ev, "session_compact") == 0) {
553+ if (in_run) {
554+ if (t > run_start) s->active_sec += (t - run_start);
555+ in_run = 0;
556+ }
557+ if (strcmp(ev, "agent_complete") == 0) s->is_active = 0;
558+ } else if (strcmp(ev, "user_message") == 0) {
559+ /* A user message ends idleness; the run starts right after. */
560+ if (in_run) {
561+ if (t > run_start) s->active_sec += (t - run_start);
562+ in_run = 0;
563+ }
564+ } else if (strcmp(ev, "tool_use") == 0) {
565+ char tool[NAME_SZ] = {0};
566+ if (json_get_str(line, "tool", tool, sizeof tool)) note_tool(s, tool);
567+ }
568+ }
569+ fclose(f);
570+
571+ /* A run that never closed is still running: count up to the last event. */
572+ if (in_run && s->last_ts > run_start) s->active_sec += (s->last_ts - run_start);
573+ }
574+ }
575+
576+ if (!s->start_time[0] && s->first_ts) {
577+ /* Fall back to the first event timestamp rendered as text is unnecessary:
578+ * we only need a numeric base below. */
579+ }
580+ if (!s->start_epoch) s->start_epoch = s->first_ts;
581+
582+ /* --- durations --- */
583+ if (s->start_epoch > 0) {
584+ long long end = s->last_ts > 0 ? s->last_ts : s->start_epoch;
585+ s->total_sec = end - s->start_epoch;
586+ if (s->total_sec < 0) s->total_sec = 0;
587+ }
588+ if (s->last_ts > s->first_ts && s->last_ts - s->first_ts > s->total_sec)
589+ s->total_sec = s->last_ts - s->first_ts;
590+
591+ if (s->active_sec > s->total_sec) s->active_sec = s->total_sec;
592+ s->idle_sec = s->total_sec - s->active_sec;
593+ s->duty_pct = s->total_sec > 0 ? (100.0 * (double)s->active_sec / (double)s->total_sec) : 0.0;
594+
595+ return 1;
596+}
597+
598+/* Scan every root we were given and append sessions. Returns count. */
599+static int scan_sessions(const char *root, session_t *out, int max)
600+{
601+ static char names[1024][NAME_SZ];
602+ int n = sx_list_dirs(root, names, 1024);
603+ int i, kept = 0;
604+
605+ for (i = 0; i < n && kept < max; i++) {
606+ session_t s;
607+ if (!load_session(root, names[i], &s)) continue;
608+ out[kept++] = s;
609+ }
610+ return kept;
611+}
612+
613+/* ------------------------------------------------------------------ */
614+/* Profile / model aggregation */
615+/* ------------------------------------------------------------------ */
616+
617+typedef struct {
618+ char label[64];
619+ int sessions;
620+ long long active_sec;
621+ int turns;
622+} bucket_t;
623+
624+static void bucket_add(bucket_t *b, int *count, int max, const char *label,
625+ long long active_sec, int turns)
626+{
627+ int i;
628+ const char *key = (label && *label) ? label : "unknown";
629+
630+ for (i = 0; i < *count; i++) {
631+ if (strcmp(b[i].label, key) == 0) {
632+ b[i].sessions++;
633+ b[i].active_sec += active_sec;
634+ b[i].turns += turns;
635+ return;
636+ }
637+ }
638+ if (*count >= max) return;
639+ str_copy(b[*count].label, sizeof b[*count].label, key);
640+ b[*count].sessions = 1;
641+ b[*count].active_sec = active_sec;
642+ b[*count].turns = turns;
643+ (*count)++;
644+}
645+
646+/* ------------------------------------------------------------------ */
647+/* Sorting */
648+/* ------------------------------------------------------------------ */
649+
650+static int cmp_session_desc(const void *a, const void *b)
651+{
652+ const session_t *x = (const session_t *)a;
653+ const session_t *y = (const session_t *)b;
654+ if (x->last_ts != y->last_ts) return x->last_ts < y->last_ts ? 1 : -1;
655+ return strcmp(x->id, y->id);
656+}
657+
658+static int cmp_bucket_desc(const void *a, const void *b)
659+{
660+ const bucket_t *x = (const bucket_t *)a;
661+ const bucket_t *y = (const bucket_t *)b;
662+ if (x->active_sec != y->active_sec) return x->active_sec < y->active_sec ? 1 : -1;
663+ return strcmp(x->label, y->label);
664+}
665+
666+/* Sort tools by hit count while keeping the hits array aligned. */
667+static void sort_tools(session_t *s)
668+{
669+ int i, j;
670+ for (i = 1; i < s->tool_count; i++) {
671+ tool_use_t key = s->tools[i];
672+ int keyhits = s->tool_hits[i];
673+ j = i - 1;
674+ while (j >= 0 && s->tool_hits[j] < keyhits) {
675+ s->tools[j + 1] = s->tools[j];
676+ s->tool_hits[j + 1] = s->tool_hits[j];
677+ j--;
678+ }
679+ s->tools[j + 1] = key;
680+ s->tool_hits[j + 1] = keyhits;
681+ }
682+}
683+
684+/* ------------------------------------------------------------------ */
685+/* Aggregates */
686+/* ------------------------------------------------------------------ */
687+
688+typedef struct {
689+ char root[PATH_SZ];
690+ int root_ok;
691+ int count;
692+ long long total_sec;
693+ long long active_sec;
694+ long long idle_sec;
695+ double duty_pct;
696+ int turns;
697+ int active_now;
698+ int tool_events;
699+ session_t *sessions;
700+} summary_t;
701+
702+static void build_summary(summary_t *sum, session_t *buf, int n)
703+{
704+ int i, j;
705+ memset(sum, 0, sizeof *sum);
706+ sum->sessions = buf;
707+ sum->count = n;
708+
709+ for (i = 0; i < n; i++) {
710+ session_t *s = &buf[i];
711+ sum->total_sec += s->total_sec;
712+ sum->active_sec += s->active_sec;
713+ sum->turns += s->turns;
714+ if (s->is_active) sum->active_now++;
715+ sort_tools(s);
716+ for (j = 0; j < s->tool_count; j++) sum->tool_events += s->tool_hits[j];
717+ }
718+ sum->idle_sec = sum->total_sec - sum->active_sec;
719+ if (sum->idle_sec < 0) sum->idle_sec = 0;
720+ sum->duty_pct = sum->total_sec > 0
721+ ? (100.0 * (double)sum->active_sec / (double)sum->total_sec) : 0.0;
722+}
723+
724+/* ------------------------------------------------------------------ */
725+/* JSON output */
726+/* ------------------------------------------------------------------ */
727+
728+static void json_header(void)
729+{
730+ fputs("Content-Type: application/json; charset=utf-8\r\n"
731+ "Cache-Control: no-store\r\n"
732+ "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
733+}
734+
735+static void print_session_obj(const session_t *s, int with_tools)
736+{
737+ char tot[64], act[64], idl[64];
738+ int i;
739+
740+ format_duration(s->total_sec, tot, sizeof tot);
741+ format_duration(s->active_sec, act, sizeof act);
742+ format_duration(s->idle_sec, idl, sizeof idl);
743+
744+ printf("{");
745+ printf("\"id\":"); json_str(s->session_id);
746+ printf(",\"dir\":"); json_str(s->id);
747+ printf(",\"model\":"); json_str(s->model);
748+ printf(",\"provider\":"); json_str(s->provider);
749+ printf(",\"profile\":"); json_str(s->profile);
750+ printf(",\"branch\":"); json_str(s->branch);
751+ printf(",\"cwd\":"); json_str(s->cwd);
752+ printf(",\"start_time\":"); json_str(s->start_time);
753+ printf(",\"first_epoch\":%lld", s->first_ts);
754+ printf(",\"last_epoch\":%lld", s->last_ts);
755+ printf(",\"is_active\":%s", s->is_active ? "true" : "false");
756+ printf(",\"total_sec\":%lld", s->total_sec);
757+ printf(",\"total_fmt\":"); json_str(tot);
758+ printf(",\"active_sec\":%lld", s->active_sec);
759+ printf(",\"active_fmt\":"); json_str(act);
760+ printf(",\"idle_sec\":%lld", s->idle_sec);
761+ printf(",\"idle_fmt\":"); json_str(idl);
762+ printf(",\"duty_cycle_pct\":%.2f", s->duty_pct);
763+ printf(",\"turns\":%d", s->turns);
764+ printf(",\"avg_turn_sec\":%.1f",
765+ s->turns > 0 ? ((double)s->active_sec / (double)s->turns) : 0.0);
766+ printf(",\"tokens\":{\"in\":%lld,\"out\":%lld,\"cache_read\":%lld,\"cache_write\":%lld}",
767+ s->in_tokens, s->out_tokens, s->cache_read, s->cache_write);
768+ if (with_tools) {
769+ printf(",\"tools\":[");
770+ for (i = 0; i < s->tool_count; i++) {
771+ if (i) printf(",");
772+ printf("{\"name\":"); json_str(s->tools[i].name);
773+ printf(",\"calls\":%d}", s->tool_hits[i]);
774+ }
775+ printf("]");
776+ }
777+ printf("}");
778+}
779+
780+static void print_summary_json(const summary_t *sum)
781+{
782+ bucket_t profiles[64], models[64];
783+ int np = 0, nm = 0, i;
784+ char tot[64], act[64], idl[64];
785+
786+ for (i = 0; i < sum->count; i++) {
787+ const session_t *s = &sum->sessions[i];
788+ bucket_add(profiles, &np, 64, s->profile[0] ? s->profile : "unknown",
789+ s->active_sec, s->turns);
790+ bucket_add(models, &nm, 64, s->model[0] ? s->model : "unknown",
791+ s->active_sec, s->turns);
792+ }
793+ qsort(profiles, (size_t)np, sizeof profiles[0], cmp_bucket_desc);
794+ qsort(models, (size_t)nm, sizeof models[0], cmp_bucket_desc);
795+
796+ format_duration(sum->total_sec, tot, sizeof tot);
797+ format_duration(sum->active_sec, act, sizeof act);
798+ format_duration(sum->idle_sec, idl, sizeof idl);
799+
800+ json_header();
801+ printf("{");
802+ printf("\"ok\":true");
803+ printf(",\"plugin\":\"%s\"", PLUGIN_ID);
804+ printf(",\"version\":\"%s\"", PLUGIN_VER);
805+ printf(",\"sessions_root\":"); json_str(sum->root);
806+ printf(",\"root_found\":%s", sum->root_ok ? "true" : "false");
807+ printf(",\"count\":%d", sum->count);
808+ printf(",\"active_now\":%d", sum->active_now);
809+ printf(",\"total_sec\":%lld", sum->total_sec);
810+ printf(",\"total_fmt\":"); json_str(tot);
811+ printf(",\"active_sec\":%lld", sum->active_sec);
812+ printf(",\"active_fmt\":"); json_str(act);
813+ printf(",\"idle_sec\":%lld", sum->idle_sec);
814+ printf(",\"idle_fmt\":"); json_str(idl);
815+ printf(",\"duty_cycle_pct\":%.2f", sum->duty_pct);
816+ printf(",\"turns\":%d", sum->turns);
817+ printf(",\"tool_events\":%d", sum->tool_events);
818+
819+ printf(",\"profiles\":[");
820+ for (i = 0; i < np; i++) {
821+ if (i) printf(",");
822+ printf("{\"profile\":"); json_str(profiles[i].label);
823+ printf(",\"sessions\":%d,\"active_sec\":%lld,\"turns\":%d}",
824+ profiles[i].sessions, profiles[i].active_sec, profiles[i].turns);
825+ }
826+ printf("]");
827+
828+ printf(",\"models\":[");
829+ for (i = 0; i < nm; i++) {
830+ if (i) printf(",");
831+ printf("{\"model\":"); json_str(models[i].label);
832+ printf(",\"sessions\":%d,\"active_sec\":%lld,\"turns\":%d}",
833+ models[i].sessions, models[i].active_sec, models[i].turns);
834+ }
835+ printf("]");
836+
837+ printf(",\"sessions\":[");
838+ for (i = 0; i < sum->count; i++) {
839+ if (i) printf(",");
840+ print_session_obj(&sum->sessions[i], 1);
841+ }
842+ printf("]}\n");
843+}
844+
845+static void print_session_json(const session_t *s, const char *root)
846+{
847+ char tot[64], act[64], idl[64];
848+ format_duration(s->total_sec, tot, sizeof tot);
849+ format_duration(s->active_sec, act, sizeof act);
850+ format_duration(s->idle_sec, idl, sizeof idl);
851+
852+ json_header();
853+ printf("{\"ok\":true,\"plugin\":\"%s\",\"version\":\"%s\"", PLUGIN_ID, PLUGIN_VER);
854+ printf(",\"sessions_root\":"); json_str(root);
855+ printf(",\"session\":"); print_session_obj(s, 1);
856+ printf(",\"summary\":{\"total_sec\":%lld,\"total_fmt\":", s->total_sec);
857+ json_str(tot);
858+ printf(",\"active_sec\":%lld,\"active_fmt\":", s->active_sec);
859+ json_str(act);
860+ printf(",\"idle_sec\":%lld,\"idle_fmt\":", s->idle_sec);
861+ json_str(idl);
862+ printf(",\"duty_cycle_pct\":%.2f,\"turns\":%d}}\n", s->duty_pct, s->turns);
863+}
864+
865+/* ------------------------------------------------------------------ */
866+/* HTML UI */
867+/* ------------------------------------------------------------------ */
868+
869+static void html_head(int embed, const char *initial_id)
870+{
871+ (void)embed;
872+ (void)initial_id;
873+ fputs(
874+ "Content-Type: text/html; charset=utf-8\r\n"
875+ "Cache-Control: no-store\r\n"
876+ "X-Content-Type-Options: nosniff\r\n"
877+ "\r\n"
878+ "<!DOCTYPE html><html lang='en'><head><meta charset='utf-8'>"
879+ "<meta name='viewport' content='width=device-width,initial-scale=1'>"
880+ "<title>Session Analytics</title>"
881+ "<style>"
882+ ":root{color-scheme:dark light;"
883+ "--bg:#0d0d0f;--surface:#18181b;--surface2:#212125;--text:#f5f5f7;--muted:#8e8e93;"
884+ "--line:rgba(255,255,255,.12);--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;"
885+ "--purple:#bf5af2;--red:#ff453a}"
886+ "@media(prefers-color-scheme:light){:root{--bg:#f5f5f7;--surface:#ffffff;"
887+ "--surface2:#f0f0f4;--text:#1d1d1f;--muted:#6e6e73;--line:rgba(0,0,0,.1);"
888+ "--blue:#0071e3;--green:#28cd41;--orange:#ff9500;--purple:#af52de;--red:#ff3b30}}"
889+ "body.theme-light{--bg:#f5f5f7;--surface:#ffffff;--surface2:#f0f0f4;--text:#1d1d1f;"
890+ "--muted:#6e6e73;--line:rgba(0,0,0,.1);--blue:#0071e3;--green:#28cd41;"
891+ "--orange:#ff9500;--purple:#af52de;--red:#ff3b30}"
892+ "body.theme-dark{--bg:#0d0d0f;--surface:#18181b;--surface2:#212125;--text:#f5f5f7;"
893+ "--muted:#8e8e93;--line:rgba(255,255,255,.12);--blue:#0a84ff;--green:#30d158;"
894+ "--orange:#ff9f0a;--purple:#bf5af2;--red:#ff453a}"
895+ "*{box-sizing:border-box}"
896+ "body{margin:0;padding:14px;background:var(--bg);color:var(--text);"
897+ "font-family:-apple-system,BlinkMacSystemFont,'SF Pro Text','Segoe UI',Roboto,sans-serif;"
898+ "-webkit-font-smoothing:antialiased;font-size:13px;line-height:1.45}"
899+ ".wrap{max-width:1000px;margin:0 auto}"
900+ ".head{display:flex;align-items:center;justify-content:space-between;gap:10px;"
901+ "flex-wrap:wrap;padding-bottom:12px;margin-bottom:14px;border-bottom:1px solid var(--line)}"
902+ ".brand{display:flex;align-items:center;gap:8px;font-size:15px;font-weight:700}"
903+ ".brand svg{width:20px;height:20px;flex:0 0 auto}"
904+ ".pill{font-size:10px;font-weight:700;letter-spacing:.4px;text-transform:uppercase;"
905+ "padding:2px 8px;border-radius:999px;border:1px solid var(--line);color:var(--muted)}"
906+ ".pill.on{color:var(--green);border-color:rgba(48,209,88,.4);background:rgba(48,209,88,.12)}"
907+ ".actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap}"
908+ "button,select{background:var(--surface);color:var(--text);border:1px solid var(--line);"
909+ "border-radius:8px;padding:6px 11px;font-size:12px;font-weight:600;cursor:pointer;"
910+ "font-family:inherit;outline:none}"
911+ "button:hover{background:var(--surface2)}"
912+ "button.primary{background:var(--blue);border-color:var(--blue);color:#fff}"
913+ ".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:10px;margin-bottom:12px}"
914+ ".card{background:var(--surface);border:1px solid var(--line);border-radius:12px;padding:13px}"
915+ ".k{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;"
916+ "color:var(--muted);margin-bottom:5px}"
917+ ".v{font-size:22px;font-weight:700;letter-spacing:-.4px;font-variant-numeric:tabular-nums;"
918+ "overflow:hidden;text-overflow:ellipsis;white-space:nowrap}"
919+ ".v.blue{color:var(--blue)}.v.green{color:var(--green)}.v.orange{color:var(--orange)}"
920+ ".v.purple{color:var(--purple)}"
921+ ".sub{font-size:11px;color:var(--muted);margin-top:3px}"
922+ ".panel{background:var(--surface);border:1px solid var(--line);border-radius:12px;"
923+ "padding:13px;margin-bottom:12px}"
924+ ".panel h2{margin:0 0 9px;font-size:12px;font-weight:700;text-transform:uppercase;"
925+ "letter-spacing:.5px;color:var(--muted)}"
926+ ".rail{height:12px;border-radius:999px;background:var(--surface2);"
927+ "border:1px solid var(--line);overflow:hidden;display:flex}"
928+ ".rail .on{background:linear-gradient(90deg,var(--blue),var(--green));height:100%}"
929+ ".legend{display:flex;gap:14px;flex-wrap:wrap;margin-top:8px;font-size:11px;color:var(--muted)}"
930+ ".legend i{display:inline-block;width:8px;height:8px;border-radius:2px;margin-right:5px}"
931+ ".bars{display:flex;flex-direction:column;gap:7px}"
932+ ".row{display:grid;grid-template-columns:150px 1fr 78px;align-items:center;gap:9px;font-size:12px}"
933+ ".row .nm{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--muted)}"
934+ ".track{height:9px;border-radius:999px;background:var(--surface2);overflow:hidden}"
935+ ".fill{height:100%;border-radius:999px;background:var(--blue);min-width:2px}"
936+ ".val{text-align:right;font-variant-numeric:tabular-nums;font-size:11px;color:var(--muted)}"
937+ ".tbl{width:100%;border-collapse:collapse;font-size:12px}"
938+ ".tbl th{text-align:left;font-size:10px;text-transform:uppercase;letter-spacing:.5px;"
939+ "color:var(--muted);font-weight:700;padding:6px 8px;border-bottom:1px solid var(--line);"
940+ "cursor:pointer;white-space:nowrap;user-select:none}"
941+ ".tbl th:hover{color:var(--text)}"
942+ ".tbl td{padding:7px 8px;border-bottom:1px solid var(--line);vertical-align:top}"
943+ ".tbl tr:last-child td{border-bottom:0}"
944+ ".tbl tr.sel td{background:var(--surface2)}"
945+ ".tbl tr:hover td{background:var(--surface2);cursor:pointer}"
946+ ".mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px}"
947+ ".nowrap{white-space:nowrap}"
948+ ".tag{display:inline-block;padding:1px 6px;border-radius:999px;font-size:10px;"
949+ "font-weight:700;border:1px solid var(--line);color:var(--muted)}"
950+ ".tag.on{color:var(--green);border-color:rgba(48,209,88,.4);background:rgba(48,209,88,.12)}"
951+ ".scroll{overflow-x:auto;-webkit-overflow-scrolling:touch}"
952+ ".empty{padding:26px 12px;text-align:center;color:var(--muted);font-size:12px}"
953+ ".err{color:var(--red)}"
954+ "@media(max-width:640px){"
955+ ".v{font-size:19px}"
956+ ".row{grid-template-columns:100px 1fr 62px}"
957+ ".tbl th:nth-child(4),.tbl td:nth-child(4),"
958+ ".tbl th:nth-child(5),.tbl td:nth-child(5){display:none}"
959+ "body{padding:10px}}"
960+ "@media(max-width:400px){.row{grid-template-columns:80px 1fr 54px}.grid{grid-template-columns:1fr 1fr}}"
961+ "</style></head><body><div class='wrap'>"
962+ "<div class='head'>"
963+ "<div class='brand'>"
964+ "<svg viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='1.8' "
965+ "stroke-linecap='round' stroke-linejoin='round' aria-hidden='true'>"
966+ "<circle cx='12' cy='12' r='9'></circle><path d='M12 7v5l3.5 2'></path></svg>"
967+ "<span>Session Analytics</span>"
968+ "<span class='pill' id='livePill'>idle</span>"
969+ "</div>"
970+ "<div class='actions'>"
971+ "<select id='sortSel' aria-label='Sort sessions'>"
972+ "<option value='recent'>Recent first</option>"
973+ "<option value='active'>Most active</option>"
974+ "<option value='turns'>Most turns</option>"
975+ "<option value='duty'>Highest duty cycle</option>"
976+ "</select>"
977+ "<button id='btnReload' type='button'>Refresh</button>"
978+ "<button id='btnTheme' type='button' aria-label='Toggle theme'>Theme</button>"
979+ "</div></div>"
980+ "<div id='err' class='err'></div>"
981+ "<div class='grid'>"
982+ "<div class='card'><div class='k'>Sessions</div><div class='v blue' id='kSessions'>-</div>"
983+ "<div class='sub' id='kSessionsSub'>&nbsp;</div></div>"
984+ "<div class='card'><div class='k'>Wall clock</div><div class='v' id='kTotal'>-</div>"
985+ "<div class='sub'>All sessions combined</div></div>"
986+ "<div class='card'><div class='k'>Active work</div><div class='v green' id='kActive'>-</div>"
987+ "<div class='sub' id='kActiveSub'>&nbsp;</div></div>"
988+ "<div class='card'><div class='k'>Duty cycle</div><div class='v orange' id='kDuty'>-</div>"
989+ "<div class='sub' id='kDutySub'>&nbsp;</div></div>"
990+ "<div class='card'><div class='k'>Turns</div><div class='v purple' id='kTurns'>-</div>"
991+ "<div class='sub' id='kTurnsSub'>&nbsp;</div></div>"
992+ "</div>"
993+ "<div class='panel'>"
994+ "<h2>Active versus idle</h2>"
995+ "<div class='rail'><div class='on' id='railOn' style='width:0%'></div></div>"
996+ "<div class='legend'>"
997+ "<span><i style='background:var(--green)'></i>Active (agent run)</span>"
998+ "<span><i style='background:var(--surface2);border:1px solid var(--line)'></i>Idle (waiting)</span>"
999+ "<span id='railText'></span>"
1000+ "</div></div>"
1001+ "<div class='panel'><h2>Profile usage by active time</h2>"
1002+ "<div class='bars' id='profBars'><div class='empty'>No data</div></div></div>"
1003+ "<div class='panel'><h2>Model usage by active time</h2>"
1004+ "<div class='bars' id='modelBars'><div class='empty'>No data</div></div></div>"
1005+ "<div class='panel'><h2>Sessions</h2><div class='scroll'>"
1006+ "<table class='tbl' id='tbl'><thead><tr>"
1007+ "<th data-key='id'>Session</th>"
1008+ "<th data-key='profile'>Profile / model</th>"
1009+ "<th data-key='active'>Active</th>"
1010+ "<th data-key='total'>Wall</th>"
1011+ "<th data-key='duty'>Duty</th>"
1012+ "<th data-key='turns'>Turns</th>"
1013+ "</tr></thead><tbody id='tbody'></tbody></table>"
1014+ "</div><div class='empty' id='tblEmpty' style='display:none'>No session directories found</div></div>"
1015+ "<div class='panel'><h2>Selected session</h2>"
1016+ "<div id='detail' class='sub'>Select a row above to inspect tool usage.</div></div>"
1017+ "</div>"
1018+ "<script>", stdout);
1019+}
1020+
1021+static void html_script(const char *initial_id)
1022+{
1023+ fputs(
1024+ "var q=new URLSearchParams(location.search);"
1025+ "var node=q.get('node')||'';"
1026+ "var pretty=q.get('plugin')||'';"
1027+ "var sel=q.get('id')||'", stdout);
1028+ if (initial_id && *initial_id) {
1029+ const char *p;
1030+ for (p = initial_id; *p; p++) {
1031+ if (*p == '\'' || *p == '\\') putchar('\\');
1032+ putchar(*p);
1033+ }
1034+ }
1035+ fputs("';"
1036+ "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))"
1037+ "||localStorage.getItem('bot_active_pwd')||'';"
1038+ "var DATA=null,SORT='recent';"
1039+
1040+ "function api(u){"
1041+ " return fetch(u,{headers:pwd?{'X-Bot-Password':pwd}:{},cache:'no-store'})"
1042+ " .then(function(r){ if(!r.ok) throw new Error('HTTP '+r.status); return r.json(); });"
1043+ "}"
1044+
1045+ /* Two routes: hub proxy when served through bot.scorpiox.net, direct plugin
1046+ route when the page was opened straight from the node. */
1047+ "function url(action,extra){"
1048+ " var base=pretty?('/plugins?plugin='+encodeURIComponent(pretty)+'&action='+encodeURIComponent(action))"
1049+ " :('/plugin_sessionstats?action='+encodeURIComponent(action));"
1050+ " if(extra)base+='&'+extra;"
1051+ " if(node)base+='&node='+encodeURIComponent(node);"
1052+ " if(pwd)base+='&pwd='+encodeURIComponent(pwd);"
1053+ " return base;"
1054+ "}"
1055+
1056+ "function esc(s){return String(s==null?'':s).replace(/[&<>\"]/g,function(c){"
1057+ " return c==='&'?'&amp;':c==='<'?'&lt;':c==='>'?'&gt;':'&quot;';});}"
1058+
1059+ "function fmt(sec){"
1060+ " sec=Math.max(0,Math.floor(sec||0));"
1061+ " var d=Math.floor(sec/86400),r=sec%86400,h=Math.floor(r/3600);"
1062+ " r%=3600;var m=Math.floor(r/60),s=r%60;var p=function(n){return (n<10?'0':'')+n;};"
1063+ " if(d>0)return d+'d '+p(h)+'h '+p(m)+'m';"
1064+ " if(h>0)return p(h)+'h '+p(m)+'m '+p(s)+'s';"
1065+ " if(m>0)return p(m)+'m '+p(s)+'s';"
1066+ " return s+'s';"
1067+ "}"
1068+
1069+ "function setTheme(t){"
1070+ " document.body.className='theme-'+t;"
1071+ " try{localStorage.setItem('sx_sessionstats_theme',t);}catch(e){}"
1072+ "}"
1073+ "document.getElementById('btnTheme').onclick=function(){"
1074+ " setTheme(document.body.classList.contains('theme-light')?'dark':'light');"
1075+ "};"
1076+ "(function(){var t='';try{t=localStorage.getItem('sx_sessionstats_theme')||'';}catch(e){}"
1077+ " if(!t)t=window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches?'light':'dark';"
1078+ " setTheme(t);})();"
1079+
1080+ "function bars(el,arr,key){"
1081+ " if(!arr||!arr.length){el.innerHTML='<div class=\"empty\">No data</div>';return;}"
1082+ " var max=0,i;"
1083+ " for(i=0;i<arr.length;i++)if(arr[i].active_sec>max)max=arr[i].active_sec;"
1084+ " if(max<=0)max=1;"
1085+ " var out='';"
1086+ " for(i=0;i<arr.length;i++){"
1087+ " var r=arr[i],w=Math.max(1,Math.round(100*r.active_sec/max));"
1088+ " out+='<div class=\"row\"><span class=\"nm\" title=\"'+esc(r[key])+'\">'+esc(r[key])+'</span>'"
1089+ " +'<span class=\"track\"><span class=\"fill\" style=\"width:'+w+'%\"></span></span>'"
1090+ " +'<span class=\"val\">'+fmt(r.active_sec)+'</span></div>';"
1091+ " }"
1092+ " el.innerHTML=out;"
1093+ "}"
1094+
1095+ "function rows(){"
1096+ " var a=(DATA&&DATA.sessions)||[];"
1097+ " a=a.slice();"
1098+ " var cmp={"
1099+ " recent:function(x,y){return (y.last_epoch||0)-(x.last_epoch||0);},"
1100+ " active:function(x,y){return (y.active_sec||0)-(x.active_sec||0);},"
1101+ " turns:function(x,y){return (y.turns||0)-(x.turns||0);},"
1102+ " duty:function(x,y){return (y.duty_cycle_pct||0)-(x.duty_cycle_pct||0);}"
1103+ " }[SORT];"
1104+ " a.sort(cmp);"
1105+ " return a;"
1106+ "}"
1107+
1108+ "function render(){"
1109+ " if(!DATA)return;"
1110+ " var d=DATA,s=d.sessions||[];"
1111+ " document.getElementById('kSessions').textContent=d.count;"
1112+ " document.getElementById('kSessionsSub').textContent=(d.active_now||0)+' active now';"
1113+ " document.getElementById('kTotal').textContent=fmt(d.total_sec);"
1114+ " document.getElementById('kTotal').className='v';"
1115+ " document.getElementById('kActive').textContent=fmt(d.active_sec);"
1116+ " document.getElementById('kActiveSub').textContent=fmt(d.idle_sec)+' idle';"
1117+ " document.getElementById('kDuty').textContent=(d.duty_cycle_pct||0).toFixed(1)+'%';"
1118+ " document.getElementById('kDutySub').textContent=(d.tool_events||0)+' tool calls';"
1119+ " document.getElementById('kTurns').textContent=d.turns;"
1120+ " document.getElementById('kTurnsSub').textContent="
1121+ " d.turns>0?((d.active_sec/d.turns).toFixed(1)+'s per turn'):'-';"
1122+ " var pct=d.total_sec>0?(100*d.active_sec/d.total_sec):0;"
1123+ " document.getElementById('railOn').style.width=Math.max(0,Math.min(100,pct))+'%';"
1124+ " document.getElementById('railText').textContent="
1125+ " fmt(d.active_sec)+' active of '+fmt(d.total_sec);"
1126+ " bars(document.getElementById('profBars'),d.profiles,'profile');"
1127+ " bars(document.getElementById('modelBars'),d.models,'model');"
1128+
1129+ " var list=rows(),html='',i;"
1130+ " for(i=0;i<list.length;i++){"
1131+ " var x=list[i];"
1132+ " var tag=x.is_active?'<span class=\"tag on\">live</span>':'<span class=\"tag\">idle</span>';"
1133+ " html+='<tr data-dir=\"'+esc(x.dir)+'\" class=\"'+(x.dir===sel?'sel':'')+'\">'"
1134+ " +'<td><div class=\"mono\">'+esc(x.id)+'</div>"
1135+ " <div class=\"sub\">'+esc(x.start_time||'')+' '+tag+'</div></td>'"
1136+ " +'<td><div>'+esc(x.profile||'-')+'</div>"
1137+ " <div class=\"sub mono\">'+esc(x.model||'-')+'</div></td>'"
1138+ " +'<td class=\"nowrap\">'+esc(x.active_fmt)+'</td>'"
1139+ " +'<td class=\"nowrap\">'+esc(x.total_fmt)+'</td>'"
1140+ " +'<td class=\"nowrap\">'+(x.duty_cycle_pct||0).toFixed(0)+'%</td>'"
1141+ " +'<td class=\"nowrap\">'+x.turns+'</td></tr>';"
1142+ " }"
1143+ " document.getElementById('tbody').innerHTML=html;"
1144+ " document.getElementById('tblEmpty').style.display=list.length?'none':'block';"
1145+ " var trs=document.querySelectorAll('#tbody tr');"
1146+ " for(i=0;i<trs.length;i++){"
1147+ " trs[i].onclick=function(){ select(this.getAttribute('data-dir')); };"
1148+ " }"
1149+ " if(!d.root_found){"
1150+ " document.getElementById('err').textContent="
1151+ " 'Sessions root not found: '+d.sessions_root;"
1152+ " } else { document.getElementById('err').textContent=''; }"
1153+ "}"
1154+
1155+ "function select(dir){"
1156+ " sel=dir;"
1157+ " render();"
1158+ " var el=document.getElementById('detail');"
1159+ " el.innerHTML='<div class=\"empty\">Loading...</div>';"
1160+ " api(url('session','sid='+encodeURIComponent(dir))).then(function(r){"
1161+ " if(!r.ok||!r.session){el.innerHTML='<div class=\"empty\">Session not found</div>';return;}"
1162+ " var s=r.session;"
1163+ " var t='<div class=\"mono\">'+esc(s.id)+'</div>';"
1164+ " t+='<div class=\"sub\">'+esc(s.profile||'-')+' / '+esc(s.model||'-')"
1165+ " +' / '+esc(s.branch||'-')+'</div>';"
1166+ " t+='<div class=\"sub mono\" style=\"word-break:break-all\">'+esc(s.cwd||'')+'</div>';"
1167+ " t+='<div style=\"margin-top:8px\">'+esc(s.active_fmt)+' active, '"
1168+ " +esc(s.idle_fmt)+' idle, duty '+(s.duty_cycle_pct||0).toFixed(1)+'% over '"
1169+ " +s.turns+' turns</div>';"
1170+ " if(s.tools&&s.tools.length){"
1171+ " t+='<div style=\"margin-top:8px\">';"
1172+ " for(var i=0;i<s.tools.length;i++){"
1173+ " t+='<span class=\"tag\" style=\"margin:0 4px 4px 0\">'+esc(s.tools[i].name)"
1174+ " +' x'+s.tools[i].calls+'</span>';"
1175+ " }"
1176+ " t+='</div>';"
1177+ " } else { t+='<div class=\"sub\">No tool calls recorded</div>'; }"
1178+ " el.innerHTML=t;"
1179+ " }).catch(function(e){ el.innerHTML='<div class=\"empty err\">'+esc(e.message)+'</div>'; });"
1180+ "}"
1181+
1182+ "document.getElementById('sortSel').onchange=function(){SORT=this.value;render();};"
1183+ "document.getElementById('btnReload').onclick=function(){load();};"
1184+ "function load(){"
1185+ " var pill=document.getElementById('livePill');"
1186+ " api(url('summary')).then(function(d){"
1187+ " DATA=d;"
1188+ " pill.textContent=(d.active_now>0?'live':'idle');"
1189+ " pill.className='pill'+(d.active_now>0?' on':'');"
1190+ " render();"
1191+ " if(sel)select(sel);"
1192+ " }).catch(function(e){"
1193+ " document.getElementById('err').textContent='Failed to load: '+e.message;"
1194+ " });"
1195+ "}"
1196+ "load();"
1197+ "setInterval(load,20000);"
1198+ "</script></body></html>\n", stdout);
1199+}
1200+
1201+/* ------------------------------------------------------------------ */
1202+/* main */
1203+/* ------------------------------------------------------------------ */
1204+
1205+int main(int argc, char **argv)
1206+{
1207+ static session_t buf[MAX_SESSIONS];
1208+ static char names_big[1024][NAME_SZ];
1209+ summary_t sum;
1210+ char root[PATH_SZ] = {0};
1211+ char action[32] = {0};
1212+ char sid[NAME_SZ] = {0};
1213+ const char *qs;
1214+ int n, i;
1215+ int root_ok;
1216+
1217+ if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
1218+ puts("{\"name\":\"sessions\",\"desc\":\"Turn metrics\"}");
1219+ return 0;
1220+ }
1221+
1222+ require_node_auth();
1223+
1224+ qs = getenv("QUERY_STRING");
1225+ if (!qs) qs = "";
1226+ get_query_val(qs, "action", action, sizeof action);
1227+ get_query_val(qs, "sid", sid, sizeof sid);
1228+ if (!sid[0]) get_query_val(qs, "id", sid, sizeof sid);
1229+
1230+ root_ok = resolve_sessions_root(root, sizeof root);
1231+
1232+ /* ---------------- JSON modes ---------------- */
1233+ {
1234+ char fmt[16] = {0};
1235+ int have_action = action[0] != '\0';
1236+ int have_format = get_query_val(qs, "format", fmt, sizeof fmt);
1237+
1238+ if (have_action || have_format) {
1239+ n = root_ok ? scan_sessions(root, buf, MAX_SESSIONS) : 0;
1240+ (void)names_big;
1241+
1242+ if (have_action && strcmp(action, "session") == 0) {
1243+ session_t one;
1244+ int found = 0;
1245+ for (i = 0; i < n; i++) {
1246+ if (strcmp(buf[i].id, sid) == 0 || strcmp(buf[i].session_id, sid) == 0) {
1247+ found = 1;
1248+ break;
1249+ }
1250+ }
1251+ if (found) {
1252+ one = buf[i];
1253+ sort_tools(&one);
1254+ print_session_json(&one, root);
1255+ } else if (sid[0]) {
1256+ /* Allow inspecting a session older than the scan window. */
1257+ if (load_session(root, sid, &one)) {
1258+ sort_tools(&one);
1259+ print_session_json(&one, root);
1260+ } else {
1261+ json_header();
1262+ printf("{\"ok\":false,\"error\":\"session not found\",\"sid\":");
1263+ json_str(sid);
1264+ printf(",\"sessions_root\":");
1265+ json_str(root);
1266+ printf("}\n");
1267+ }
1268+ } else {
1269+ json_header();
1270+ printf("{\"ok\":false,\"error\":\"missing sid parameter\",\"sessions_root\":");
1271+ json_str(root);
1272+ printf("}\n");
1273+ }
1274+ return 0;
1275+ }
1276+
1277+ qsort(buf, (size_t)n, sizeof buf[0], cmp_session_desc);
1278+ build_summary(&sum, buf, n);
1279+ str_copy(sum.root, sizeof sum.root, root);
1280+ sum.root_ok = root_ok;
1281+ print_summary_json(&sum);
1282+ return 0;
1283+ }
1284+ }
1285+
1286+ /* ---------------- HTML ---------------- */
1287+ {
1288+ int embed = 0;
1289+ char ev[16] = {0};
1290+ if (get_query_val(qs, "embed", ev, sizeof ev)) {
1291+ if (!strcmp(ev, "1") || !strcmp(ev, "true")) embed = 1;
1292+ }
1293+ html_head(embed, sid);
1294+ html_script(sid);
1295+ }
1296+ return 0;
1297+}
tests/run.sh+350−0■■■■■
11new file mode 100755
index 0000000..6a2289f
--- /dev/null
+++ b/tests/run.sh
@@ -0,0 +1,350 @@
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+
12+set -u
13+
14+ROOT=$(cd "$(dirname "$0")/.." && pwd)
15+BIN=${1:-"$ROOT/plugin_sessionstats"}
16+[ -x "$BIN" ] || { echo "binary not built: $BIN" >&2; exit 1; }
17+
18+TMP=$(mktemp -d "${TMPDIR:-/tmp}/sx_sessionstats_XXXXXX")
19+trap 'rm -rf "$TMP"' EXIT
20+
21+PASS=0
22+FAIL=0
23+ok() { PASS=$((PASS+1)); }
24+bad() { FAIL=$((FAIL+1)); printf ' FAIL %s\n' "$1"; }
25+check() { # check <label> <actual> <expected>
26+ if [ "$2" = "$3" ]; then ok; else bad "$1 (got '$2', want '$3')"; fi
27+}
28+
29+# ---------------------------------------------------------------- fixtures
30+S="$TMP/sessions"
31+mkdir -p "$S/s1" "$S/s2" "$S/s3"
32+
33+# --- s1: two complete runs, three tool kinds, a profile and a model
34+cat > "$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+}
45+EOF
46+cat > "$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+}
55+EOF
56+cat > "$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"}
68+EOF
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
73+cat > "$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+}
82+EOF
83+cat > "$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}
89+EOF
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)
94+cat > "$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+}
100+EOF
101+
102+run() { # 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+
107+jsoncheck() { # jsoncheck <label> <json-file> <python-expression on d> <expected>
108+ label="$1"; file="$2"; expr="$3"; want="$4"
109+ got=$(python3 - "$file" "$expr" <<'PY'
110+import json, sys
111+d = json.load(open(sys.argv[1]))
112+try:
113+ v = eval(sys.argv[2], {"d": d, "len": len, "sum": sum, "sorted": sorted})
114+except Exception as e:
115+ v = "ERR:%s" % e
116+print(v)
117+PY
118+)
119+ check "$label" "$got" "$want"
120+}
121+
122+echo "== meta mode"
123+out=$("$BIN" --meta)
124+check "--meta exact JSON" "$out" '{"name":"sessions","desc":"Turn metrics"}'
125+out=$(SX_PLUGIN_META=1 "$BIN")
126+check "SX_PLUGIN_META=1 exact JSON" "$out" '{"name":"sessions","desc":"Turn metrics"}'
127+check "meta name is other field free" "$(printf '%s' "$out" | python3 -c 'import json,sys;d=json.load(sys.stdin);print(len(d))')" "2"
128+check "meta name length <= 2 words" "$(printf '%s' "$out" | python3 -c 'import json,sys;print(len(json.load(sys.stdin)["name"].split()))')" "1"
129+check "meta desc length <= 15" "$(printf '%s' "$out" | python3 -c 'import json,sys;print(len(json.load(sys.stdin)["desc"])<=15)')" "True"
130+
131+echo "== auth gate"
132+code=$(BOT_PASSWORD=pw SX_SESSIONS_DIR="$S" QUERY_STRING=action=summary "$BIN" | head -1 | tr -d '\r')
133+check "401 without credential" "$code" "Status: 401 Unauthorized"
134+code=$(BOT_PASSWORD=pw HTTP_X_BOT_PASSWORD=pw SX_SESSIONS_DIR="$S" QUERY_STRING=action=summary "$BIN" | head -1 | cut -c1-12)
135+check "header credential accepted" "$code" "Content-Type"
136+code=$(BOT_PASSWORD=pw HTTP_AUTHORIZATION="Bearer pw" SX_SESSIONS_DIR="$S" QUERY_STRING=action=summary "$BIN" | head -1 | cut -c1-12)
137+check "bearer credential accepted" "$code" "Content-Type"
138+code=$(BOT_PASSWORD=pw SX_SESSIONS_DIR="$S" QUERY_STRING='action=summary&pwd=pw' "$BIN" | head -1 | cut -c1-12)
139+check "query credential accepted" "$code" "Content-Type"
140+code=$(BOT_PASSWORD=pw SX_SESSIONS_DIR="$S" "$BIN" --meta | cut -c1-10)
141+check "--meta stays unauthenticated" "$code" '{"name":"s'
142+code=$(BOT_PASSWORD=pw SX_SESSIONS_DIR="$S" QUERY_STRING=action=summary "$BIN" | tail -1)
143+check "401 body is JSON error" "$code" '{"ok":false,"error":"invalid node password"}'
144+
145+echo "== summary shape"
146+run 'action=summary' > "$TMP/sum.json"
147+last=$(tail -1 "$TMP/sum.json")
148+check "summary has no Content-Length" "$(printf '%s' "$last" | grep -c 'Content-Length')" "0"
149+printf '%s' "$last" > "$TMP/sum.body.json"
150+jsoncheck "ok" "$TMP/sum.body.json" 'd["ok"]' "True"
151+jsoncheck "plugin id" "$TMP/sum.body.json" 'd["plugin"]' "plugin_sessionstats"
152+jsoncheck "version" "$TMP/sum.body.json" 'd["version"]' "1.0.0"
153+jsoncheck "root_found" "$TMP/sum.body.json" 'd["root_found"]' "True"
154+jsoncheck "session count" "$TMP/sum.body.json" 'd["count"]' "3"
155+jsoncheck "active_now" "$TMP/sum.body.json" 'd["active_now"]' "1"
156+jsoncheck "turns total" "$TMP/sum.body.json" 'd["turns"]' "3"
157+jsoncheck "tool events" "$TMP/sum.body.json" 'd["tool_events"]' "5"
158+jsoncheck "total sec" "$TMP/sum.body.json" 'd["total_sec"]' "410"
159+jsoncheck "active sec" "$TMP/sum.body.json" 'd["active_sec"]' "130"
160+jsoncheck "idle sec" "$TMP/sum.body.json" 'd["idle_sec"]' "280"
161+jsoncheck "idle+active=total" "$TMP/sum.body.json" 'd["idle_sec"]+d["active_sec"]==d["total_sec"]' "True"
162+jsoncheck "duty pct" "$TMP/sum.body.json" 'round(d["duty_cycle_pct"],2)' "31.71"
163+jsoncheck "total_fmt" "$TMP/sum.body.json" 'd["total_fmt"]' "06m 50s"
164+jsoncheck "active_fmt" "$TMP/sum.body.json" 'd["active_fmt"]' "02m 10s"
165+jsoncheck "idle_fmt" "$TMP/sum.body.json" 'd["idle_fmt"]' "04m 40s"
166+jsoncheck "sessions array length" "$TMP/sum.body.json" 'len(d["sessions"])' "3"
167+jsoncheck "profiles present" "$TMP/sum.body.json" 'len(d["profiles"])' "3"
168+jsoncheck "models present" "$TMP/sum.body.json" 'len(d["models"])' "3"
169+jsoncheck "profile alpha leads" "$TMP/sum.body.json" 'd["profiles"][0]["profile"]' "profile-alpha"
170+jsoncheck "profile alpha active" "$TMP/sum.body.json" 'd["profiles"][0]["active_sec"]' "70"
171+jsoncheck "profile beta active" "$TMP/sum.body.json" 'd["profiles"][1]["active_sec"]' "60"
172+jsoncheck "profile alpha sessions" "$TMP/sum.body.json" 'd["profiles"][0]["sessions"]' "1"
173+jsoncheck "unknown profile bucket" "$TMP/sum.body.json" 'd["profiles"][2]["profile"]' "unknown"
174+jsoncheck "model alpha leads" "$TMP/sum.body.json" 'd["models"][0]["model"]' "alpha-1"
175+
176+echo "== summary is sorted newest first"
177+jsoncheck "first session is s2" "$TMP/sum.body.json" 'd["sessions"][0]["id"]' "2026_01_02_bold_lovelace"
178+jsoncheck "second session is s1" "$TMP/sum.body.json" 'd["sessions"][1]["id"]' "2026_01_01_quiet_curie"
179+
180+echo "== per-session numbers (s1)"
181+cat > "$TMP/py_s1.py" <<'PY'
182+import json,sys
183+d=json.load(open(sys.argv[1]))
184+for 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"])
190+PY
191+got=$(python3 "$TMP/py_s1.py" "$TMP/sum.body.json")
192+check "s1 numbers" "$got" "340 70 270 2 20.59 alpha-1 profile-alpha main 1000 250 800 50"
193+
194+cat > "$TMP/py_s1tools.py" <<'PY'
195+import json,sys
196+d=json.load(open(sys.argv[1]))
197+for s in d["sessions"]:
198+ if s["dir"]=="s1":
199+ print(" ".join("%s=%d"%(t["name"],t["calls"]) for t in s["tools"]))
200+PY
201+got=$(python3 "$TMP/py_s1tools.py" "$TMP/sum.body.json")
202+check "s1 tools sorted by calls" "$got" "Bash=2 Read=1 Write=1"
203+
204+cat > "$TMP/py_s1id.py" <<'PY'
205+import json,sys
206+d=json.load(open(sys.argv[1]))
207+for s in d["sessions"]:
208+ if s["dir"]=="s1":
209+ print(s["id"], s["start_time"], s["is_active"], s["avg_turn_sec"])
210+PY
211+got=$(python3 "$TMP/py_s1id.py" "$TMP/sum.body.json")
212+check "s1 identity fields" "$got" "2026_01_01_quiet_curie 2026-01-01 10:00:00 False 35.0"
213+
214+echo "== per-session numbers (s2, still running)"
215+cat > "$TMP/py_s2.py" <<'PY'
216+import json,sys
217+d=json.load(open(sys.argv[1]))
218+for 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"])
221+PY
222+got=$(python3 "$TMP/py_s2.py" "$TMP/sum.body.json")
223+check "s2 numbers" "$got" "70 60 10 1 True"
224+
225+echo "== degenerate session (metadata only)"
226+cat > "$TMP/py_s3.py" <<'PY'
227+import json,sys
228+d=json.load(open(sys.argv[1]))
229+for s in d["sessions"]:
230+ if s["dir"]=="s3":
231+ print(s["total_sec"], s["active_sec"], s["turns"], s["is_active"])
232+PY
233+got=$(python3 "$TMP/py_s3.py" "$TMP/sum.body.json")
234+check "s3 numbers" "$got" "0 0 0 False"
235+
236+echo "== action=session"
237+run 'action=session&sid=s1' | tail -1 > "$TMP/one.json"
238+jsoncheck "session ok" "$TMP/one.json" 'd["ok"]' "True"
239+jsoncheck "session id" "$TMP/one.json" 'd["session"]["id"]' "2026_01_01_quiet_curie"
240+jsoncheck "session active" "$TMP/one.json" 'd["session"]["active_sec"]' "70"
241+jsoncheck "session tools" "$TMP/one.json" 'len(d["session"]["tools"])' "3"
242+jsoncheck "session summary block" "$TMP/one.json" 'd["summary"]["turns"]' "2"
243+run 'action=session&sid=2026_01_02_bold_lovelace' | tail -1 > "$TMP/one2.json"
244+jsoncheck "session by full id" "$TMP/one2.json" 'd["session"]["dir"]' "s2"
245+run 'action=session&sid=nope' | tail -1 > "$TMP/one3.json"
246+jsoncheck "unknown session ok=false" "$TMP/one3.json" 'd["ok"]' "False"
247+jsoncheck "unknown session error" "$TMP/one3.json" 'd["error"]' "session not found"
248+run 'action=session' | tail -1 > "$TMP/one4.json"
249+jsoncheck "missing sid error" "$TMP/one4.json" 'd["error"]' "missing sid parameter"
250+run 'action=session&id=s1' | tail -1 > "$TMP/one5.json"
251+jsoncheck "id= alias accepted" "$TMP/one5.json" 'd["session"]["dir"]' "s1"
252+run 'action=session&sid=%73%31' | tail -1 > "$TMP/one6.json"
253+jsoncheck "percent-decoded sid" "$TMP/one6.json" 'd["session"]["dir"]' "s1"
254+
255+echo "== format=json"
256+run 'format=json' | tail -1 > "$TMP/fmt.json"
257+jsoncheck "format=json returns summary" "$TMP/fmt.json" 'd["count"]' "3"
258+jsoncheck "format=json ok" "$TMP/fmt.json" 'd["ok"]' "True"
259+
260+echo "== unknown action falls back to the summary"
261+run 'action=whatever' | tail -1 > "$TMP/unk.json"
262+jsoncheck "unknown action still JSON" "$TMP/unk.json" 'd["ok"]' "True"
263+
264+echo "== html"
265+run 'embed=1' > "$TMP/html.txt"
266+head -1 "$TMP/html.txt" | grep -q 'Content-Type: text/html' && ok || bad "html content type"
267+grep -q '<!DOCTYPE html>' "$TMP/html.txt" && ok || bad "html doctype"
268+grep -q 'Session Analytics' "$TMP/html.txt" && ok || bad "html title"
269+grep -q "id='kSessions'" "$TMP/html.txt" && ok || bad "kpi card sessions"
270+grep -q "id='railOn'" "$TMP/html.txt" && ok || bad "active rail"
271+grep -q "id='profBars'" "$TMP/html.txt" && ok || bad "profile bars"
272+grep -q "id='modelBars'" "$TMP/html.txt" && ok || bad "model bars"
273+grep -q "id='tbody'" "$TMP/html.txt" && ok || bad "session table"
274+grep -q "btnTheme" "$TMP/html.txt" && ok || bad "theme toggle"
275+grep -q "prefers-color-scheme" "$TMP/html.txt" && ok || bad "dark/light support"
276+grep -q "max-width:400px" "$TMP/html.txt" && ok || bad "narrow breakpoint"
277+grep -q "plugin_sessionstats?action=" "$TMP/html.txt" && ok || bad "direct plugin route"
278+grep -q "plugins?plugin=" "$TMP/html.txt" && ok || bad "hub proxy route"
279+grep -q "bot_active_pwd" "$TMP/html.txt" && ok || bad "pwd bootstrap"
280+grep -q "X-Bot-Password" "$TMP/html.txt" && ok || bad "pwd header"
281+grep -qi 'content-length' "$TMP/html.txt" && bad "html must not emit Content-Length" || ok
282+
283+echo "== initial id is injected and escaped"
284+run 'id=s1' > "$TMP/html2.txt"
285+grep -q "q.get('id')||'s1'" "$TMP/html2.txt" && ok || bad "initial id injected"
286+mkdir -p "$S/bad'name"
287+run "id=x%27y" > "$TMP/html3.txt"
288+grep -q "q.get('id')||'x\\\\'y'" "$TMP/html3.txt" && ok || bad "single quote escaped in initial id"
289+rm -rf "$S/bad'name"
290+
291+echo "== missing sessions root"
292+out=$(SX_SESSIONS_DIR="$TMP/does-not-exist" QUERY_STRING='action=summary' "$BIN" | tail -1)
293+printf '%s' "$out" > "$TMP/noroot.json"
294+jsoncheck "root_found false" "$TMP/noroot.json" 'd["root_found"]' "False"
295+jsoncheck "empty summary ok" "$TMP/noroot.json" 'd["ok"]' "True"
296+jsoncheck "zero sessions" "$TMP/noroot.json" 'd["count"]' "0"
297+jsoncheck "empty profiles" "$TMP/noroot.json" 'd["profiles"]' "[]"
298+
299+echo "== the root must be a directory, not any openable path"
300+: > "$TMP/notadir"
301+out=$(SX_SESSIONS_DIR="$TMP/notadir" QUERY_STRING='action=summary' "$BIN" | tail -1)
302+printf '%s' "$out" > "$TMP/notadir.json"
303+jsoncheck "file root rejected" "$TMP/notadir.json" 'd["root_found"]' "False"
304+
305+echo "== read-only guarantee"
306+before=$(find "$S" -type f | wc -l | tr -d ' ')
307+run 'action=summary' >/dev/null
308+run 'action=session&sid=s1' >/dev/null
309+run 'embed=1' >/dev/null
310+after=$(find "$S" -type f | wc -l | tr -d ' ')
311+check "no files created" "$after" "$before"
312+diff -r "$S" "$S" >/dev/null 2>&1 && ok || bad "fixture tree unchanged"
313+
314+echo "== no emoji anywhere in the source"
315+if grep -qP '[\x{1F300}-\x{1FAFF}\x{2600}-\x{27BF}]' "$ROOT/src/plugin_sessionstats.c" 2>/dev/null; then
316+ bad "source contains emoji"
317+else
318+ ok
319+fi
320+
321+echo "== no private addresses or credentials in the whole history"
322+HIST="$TMP/history.txt"
323+git -C "$ROOT" log -p --all 2>/dev/null \
324+ | grep -v '^Author: ' \
325+ | grep -vE 'scan "|audit "|HITS=|grep -E|P_ROOT=|P_WT=|PK="' > "$HIST" || : > "$HIST"
326+check "no 192.168 in history" "$(grep -Eco '192\.168\.[0-9]+\.[0-9]+' "$HIST" || true)" "0"
327+check "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"
328+check "no 172.16-31 range" "$(grep -Eco '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' "$HIST" || true)" "0"
329+check "no ghp_ token" "$(grep -Eco 'ghp_[A-Za-z0-9]{20,}' "$HIST" || true)" "0"
330+check "no hf_ token" "$(grep -Eco 'hf_[A-Za-z0-9]{20,}' "$HIST" || true)" "0"
331+check "no internal hostnames" "$(grep -Eco 'INTERNAL_HOST_A|INTERNAL_HOST_B|INTERNAL_HOST_C' "$HIST" || true)" "0"
332+check "no default password" "$(grep -Eco 'Xboxone'09'0'9'|TESTPW' "$HIST" || true)" "0"
333+
334+echo "== Windows artifact shape (when the cross build exists)"
335+if [ -f "$ROOT/plugin_sessionstats.exe" ]; then
336+ check "windows artifact starts with MZ" "$(head -c 2 "$ROOT/plugin_sessionstats.exe")" "MZ"
337+else
338+ echo " skip (plugin_sessionstats.exe not built)"
339+fi
340+
341+echo "== musl artifact shape (when the static build exists)"
342+if [ -f "$ROOT/plugin_sessionstats.musl" ]; then
343+ check "musl artifact is a static ELF" "$(head -c 4 "$ROOT/plugin_sessionstats.musl" | od -An -c | tr -d ' \n')" '177ELF'
344+else
345+ echo " skip (plugin_sessionstats.musl not built)"
346+fi
347+
348+echo
349+printf ' %d passed, %d failed\n' "$PASS" "$FAIL"
350+[ "$FAIL" -eq 0 ] || exit 1
0351
.gitignore+9−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..8837948index 0000000..8837948
--- /dev/null--- /dev/null
+++ b/.gitignore+++ b/.gitignore
@@ -0,0 +1,9 @@@@ -0,0 +1,9 @@
1+/plugin_sessionstats
2+/plugin_sessionstats.musl
3+/plugin_sessionstats.arm64
4+/plugin_sessionstats.exe
5+/plugin_sessionstats.macos-arm64
6+/plugin_sessionstats.macos-x86_64
7+*.o
8+*.tmp
9+*.dSYM
LICENSE+21−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..ef80120index 0000000..ef80120
--- /dev/null--- /dev/null
+++ b/LICENSE+++ b/LICENSE
@@ -0,0 +1,21 @@@@ -0,0 +1,21 @@
1+MIT License
2+
3+Copyright (c) 2026 SCORPIOX INC
4+
5+Permission is hereby granted, free of charge, to any person obtaining a copy
6+of this software and associated documentation files (the "Software"), to deal
7+in the Software without restriction, including without limitation the rights
8+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+copies of the Software, and to permit persons to whom the Software is
10+furnished to do so, subject to the following conditions:
11+
12+The above copyright notice and this permission notice shall be included in all
13+copies or substantial portions of the Software.
14+
15+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+SOFTWARE.
Makefile+62−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..6404f26index 0000000..6404f26
--- /dev/null--- /dev/null
+++ b/Makefile+++ b/Makefile
@@ -0,0 +1,62 @@@@ -0,0 +1,62 @@
1+# plugin_sessionstats - ScorpioX Bot open-source session runtime & turn analytics
2+#
3+# Targets:
4+# make native build -> ./plugin_sessionstats
5+# make musl static musl x86_64 -> ./plugin_sessionstats.musl
6+# make arm64 static aarch64 musl -> ./plugin_sessionstats.arm64
7+# make win64 MinGW-w64 static PE -> ./plugin_sessionstats.exe
8+# make macos Apple clang (run on macOS)
9+# make test build + run tests/run.sh
10+# make clean
11+
12+CC ?= cc
13+CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings
14+MUSL_CC ?= musl-gcc
15+MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings
16+ARM_CC ?= aarch64-linux-gnu-gcc
17+ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings
18+WIN_CC ?= x86_64-w64-mingw32-gcc
19+WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings
20+SRC := src/plugin_sessionstats.c
21+BIN := plugin_sessionstats
22+EXE := plugin_sessionstats.exe
23+
24+.PHONY: all native musl arm64 win64 macos test clean help
25+
26+all: native
27+
28+native: $(BIN)
29+
30+$(BIN): $(SRC)
31+ @echo "==> native build ($(CC))"
32+ $(CC) $(CFLAGS) -o $(BIN) $(SRC)
33+
34+# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy)
35+musl: $(SRC)
36+ @echo "==> static musl build ($(MUSL_CC))"
37+ $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRC)
38+
39+# Static aarch64 build - Raspberry Pi 5 / ARM64 servers
40+arm64: $(SRC)
41+ @echo "==> static arm64 build ($(ARM_CC))"
42+ $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRC)
43+
44+# Native Win64 static PE - runs on any Windows 10/11 x64 node
45+win64: $(SRC)
46+ @echo "==> MinGW-w64 build ($(WIN_CC))"
47+ $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRC)
48+
49+# Apple clang build (run this on macOS)
50+macos: $(SRC)
51+ @echo "==> Apple clang build"
52+ $(CC) -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -o $(BIN) $(SRC)
53+
54+test: native
55+ @sh tests/run.sh
56+
57+clean:
58+ rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN).macos-arm64 $(BIN).macos-x86_64
59+ rm -rf bin
60+
61+help:
62+ @echo "make | make musl | make arm64 | make win64 | make macos | make test | make clean"
README.md+175−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..b0b7a32index 0000000..b0b7a32
--- /dev/null--- /dev/null
+++ b/README.md+++ b/README.md
@@ -0,0 +1,175 @@@@ -0,0 +1,175 @@
1+# plugin_sessionstats
2+
3+Session runtime and turn analytics for a ScorpioX Bot node — a single clean-room
4+C99 binary, MIT licensed, with no dependency beyond libc.
5+
6+It reads the local session store and reports how long each session ran, how much
7+of that time the agent was actually working versus waiting for a prompt, how many
8+turns it took, which tools were called, and which profile/model did the work.
9+
10+## What it reads
11+
12+Read-only, local only, no network:
13+
14+```
15+<root>/<session>/
16+├── meta.json session id, start time, model, provider, profile, cwd, thread
17+├── stats.json branch and token counters (optional)
18+├── events.jsonl the event stream: run starts, idles, tool calls
19+└── thinking present while the agent is actively working (marker only)
20+```
21+
22+`<root>` is `$SX_SESSIONS_DIR` when set, otherwise `%LOCALAPPDATA%\scorpiox\sessions`
23+or `%USERPROFILE%\.scorpiox\sessions` on Windows, and `~/.scorpiox/sessions` or
24+`/workspace/.scorpiox/sessions` on POSIX.
25+
26+**Active time** is measured from `agent_run_start` to the next
27+`agent_idle` / `agent_complete` / `session_end` / `session_compact`, and a run
28+that is still open counts up to the last event. **Idle time** is the remainder of
29+the wall clock. Timestamps in these files are local wall-clock text, and only
30+differences are used, so no timezone database is needed.
31+
32+## Three modes
33+
34+### 1. Discovery
35+
36+```sh
37+./plugin_sessionstats --meta
38+# {"name":"sessions","desc":"Turn metrics"}
39+```
40+
41+`SX_PLUGIN_META=1` does the same. This route stays unauthenticated so `/plugins`
42+discovery works.
43+
44+### 2. JSON API
45+
46+```sh
47+./plugin_sessionstats ?action=summary
48+./plugin_sessionstats ?action=session&sid=2026_11_10_vibrant_leibniz
49+./plugin_sessionstats ?format=json
50+```
51+
52+`action=summary` returns the aggregate plus every session:
53+
54+```json
55+{
56+ "ok": true,
57+ "plugin": "plugin_sessionstats",
58+ "version": "1.0.0",
59+ "sessions_root": "/root/.scorpiox/sessions",
60+ "root_found": true,
61+ "count": 12,
62+ "active_now": 1,
63+ "total_sec": 91540, "total_fmt": "1d 01h 25m",
64+ "active_sec": 41230, "active_fmt": "11h 27m 10s",
65+ "idle_sec": 50310, "idle_fmt": "13h 58m 30s",
66+ "duty_cycle_pct": 45.04,
67+ "turns": 96,
68+ "tool_events": 1841,
69+ "profiles": [{"profile": "sglang-personal-deepseek", "sessions": 9, "active_sec": 38010, "turns": 74}],
70+ "models": [{"model": "deepseek-v4.1-flash", "sessions": 9, "active_sec": 38010, "turns": 74}],
71+ "sessions": [
72+ {
73+ "id": "2026_11_10_vibrant_leibniz",
74+ "dir": "2026_11_10_vibrant_leibniz",
75+ "model": "deepseek-v4.1-flash",
76+ "provider": "openai",
77+ "profile": "sglang-personal-deepseek",
78+ "branch": "main",
79+ "cwd": "/codebases/x",
80+ "start_time": "2026-11-10 17:40:32",
81+ "first_epoch": 1794332432,
82+ "last_epoch": 1794339727,
83+ "is_active": false,
84+ "total_sec": 7295, "total_fmt": "02h 01m 35s",
85+ "active_sec": 7226, "active_fmt": "02h 00m 26s",
86+ "idle_sec": 69, "idle_fmt": "01m 09s",
87+ "duty_cycle_pct": 99.05,
88+ "turns": 1,
89+ "avg_turn_sec": 7226.0,
90+ "tokens": {"in": 325122, "out": 462, "cache_read": 317568, "cache_write": 7554},
91+ "tools": [{"name": "Bash", "calls": 345}, {"name": "ReadImage", "calls": 11}]
92+ }
93+ ]
94+}
95+```
96+
97+`action=session&sid=<dir-or-full-id>` returns one session plus a small
98+`summary` block, and accepts `sid` older than the scan window. `id=` is an alias
99+for `sid=`. Everything is percent-decoded.
100+
101+### 3. HTML UI
102+
103+`GET` with no action returns a responsive dashboard: KPI cards, an
104+active-versus-idle rail, profile and model time bars, a sortable session table
105+and a per-session tool breakdown. It follows `prefers-color-scheme`, has an
106+explicit theme toggle, and reflows down to 390 px.
107+
108+It also works inside the Chat floating window (`?embed=1`) and pre-selects a
109+session from `?id=`.
110+
111+## Authentication
112+
113+When `BOT_PASSWORD` is set on the node, every route except `--meta` requires one
114+of:
115+
116+* `X-Bot-Password: <password>`
117+* `Authorization: Bearer <password>`
118+* `?pwd=<password>` (what the bot web UI appends)
119+
120+Without `BOT_PASSWORD` the plugin is a no-op on auth, which keeps local
121+development and the offline tests simple.
122+
123+## Build
124+
125+```sh
126+make # native
127+make musl # static x86_64 musl - the universal Linux artifact
128+make arm64 # static aarch64 musl - Raspberry Pi 5 / ARM64 servers
129+make win64 # static Win64 PE via MinGW-w64
130+make macos # Apple clang, run on macOS
131+make test # build + run the offline assertion suite
132+```
133+
134+On Windows: `powershell -ExecutionPolicy Bypass -File build.ps1`.
135+
136+## Install
137+
138+```sh
139+mkdir -p ~/.scorpiox/plugins
140+cp plugin_sessionstats ~/.scorpiox/plugins/
141+chmod +x ~/.scorpiox/plugins/plugin_sessionstats
142+```
143+
144+On a BotCloud container use `/workspace/.scorpiox/plugins` instead — it survives
145+container restarts. No server restart is needed; `scorpiox-server` resolves the
146+plugin directory on every request.
147+
148+## Release
149+
150+`./release-dist.sh` scans the full git history for secrets and private
151+addresses, builds every target it can, writes `manifest.json` + `SHA256SUMS` +
152+`source.tar.gz`, uploads to `dist.scorpiox.net/bot-plugins/sessionstats/1.0.0/`,
153+merges `index.json`, mirrors to plugingit, and verifies `latest.json`.
154+
155+Environment: `DIST_HOST`, `DIST_PASS`, `DIST_PATH`, `MAC_HOST`, `MAC_USER`,
156+`MAC_PASS`, `PLUGINGIT_TOKEN_FILE`.
157+
158+It silently **skips** a target it cannot build, so always check the target count
159+in `latest.json`, not the exit code. Run it on a host that actually has
160+`musl-gcc`, `aarch64-linux-gnu-gcc` and `x86_64-w64-mingw32-gcc`.
161+
162+## Tests
163+
164+`tests/run.sh` builds nothing and needs no network. It creates synthetic session
165+fixtures with fixed timestamps, then asserts exact durations, turn counts, tool
166+frequencies, profile buckets, sort order, the auth matrix, the HTML contract, the
167+read-only guarantee, and a full-history secret/LAN-IP scan.
168+
169+```sh
170+sh tests/run.sh ./plugin_sessionstats
171+```
172+
173+## License
174+
175+MIT. Copyright (c) 2026 SCORPIOX INC.
build.ps1+53−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..1059b87index 0000000..1059b87
--- /dev/null--- /dev/null
+++ b/build.ps1+++ b/build.ps1
@@ -0,0 +1,53 @@@@ -0,0 +1,53 @@
1+# build.ps1 - Windows MinGW-w64 static build for plugin_sessionstats
2+#
3+# Usage (from the repo root, PowerShell):
4+# powershell -ExecutionPolicy Bypass -File build.ps1
5+#
6+# Produces .\plugin_sessionstats.exe (static PE, runs on any Windows 10/11 x64 node).
7+# Requires x86_64-w64-mingw32-gcc or a WinLibs/UCRT gcc on PATH (or C:\gcc16\bin).
8+
9+$ErrorActionPreference = "Stop"
10+$ScriptDir = $PSScriptRoot
11+Push-Location $ScriptDir
12+try {
13+ $Src = Join-Path $ScriptDir "src\plugin_sessionstats.c"
14+ $Out = Join-Path $ScriptDir "plugin_sessionstats.exe"
15+ $Cc = "x86_64-w64-mingw32-gcc"
16+
17+ if (-not (Test-Path $Src)) { throw "source not found: $Src" }
18+
19+ # Prefer MinGW-w64, fall back to a plain gcc (WinLibs / MSYS2 UCRT) if present.
20+ if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) {
21+ if (Test-Path "C:\gcc16\bin\gcc.exe") {
22+ $Cc = "C:\gcc16\bin\gcc.exe"
23+ } elseif (Get-Command gcc -ErrorAction SilentlyContinue) {
24+ $Cc = "gcc"
25+ } else {
26+ throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)"
27+ }
28+ }
29+
30+ Write-Host "==> building plugin_sessionstats.exe with $Cc"
31+ & $Cc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -o $Out $Src
32+ if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" }
33+
34+ if (-not (Test-Path $Out)) { throw "build produced no output" }
35+
36+ # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not.
37+ $bytes = [System.IO.File]::ReadAllBytes($Out)
38+ if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) {
39+ throw "output is not a PE executable (missing MZ header)"
40+ }
41+
42+ Write-Host "==> metadata check"
43+ & $Out --meta
44+ if ($LASTEXITCODE -ne 0) { throw "--meta failed" }
45+
46+ $size = (Get-Item $Out).Length
47+ Write-Host ""
48+ Write-Host "Built $Out ($size bytes)"
49+ Write-Host "Install: Copy-Item plugin_sessionstats.exe `"`$env:LOCALAPPDATA\scorpiox\plugins\`""
50+}
51+finally {
52+ Pop-Location
53+}
plugin.json+12−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..c5f59f0index 0000000..c5f59f0
--- /dev/null--- /dev/null
+++ b/plugin.json+++ b/plugin.json
@@ -0,0 +1,12 @@@@ -0,0 +1,12 @@
1+{
2+ "slug": "sessionstats",
3+ "id": "plugin_sessionstats",
4+ "title": "Session Runtime & Turn Analytics",
5+ "summary": "Zero-dependency read-only analytics over the ScorpioX session store: wall-clock duration, active agent-run time versus idle waiting, duty cycle, turn counts, tool-call frequency and profile/model usage for every session on the node. Parses meta.json, stats.json and events.jsonl directly, so it needs no database, no daemon and no network.",
6+ "category": "sessions",
7+ "license": "MIT",
8+ "capabilities": ["local_filesystem_read", "session_store_read"],
9+ "trust_notice": "Executes native C code on your node. Opens session files under the local ScorpioX sessions directory read-only; it never writes, renames or deletes anything and makes zero network requests.",
10+ "author": "SCORPIOX INC",
11+ "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-sessionstats"
12+}
release-dist.sh+362−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..4dcf4fdindex 0000000..4dcf4fd
--- /dev/null--- /dev/null
+++ b/release-dist.sh+++ b/release-dist.sh
@@ -0,0 +1,362 @@@@ -0,0 +1,362 @@
1+#!/usr/bin/env bash
2+# release-dist.sh - build, scan and publish plugin_sessionstats to the plugin registry.
3+#
4+# Two paths:
5+# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it
6+# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer CLI.
7+# B. Standalone (this script): secret scan -> multi-target build -> source.tar.gz ->
8+# manifest.json + SHA256SUMS -> upload -> latest.json / index.json.
9+#
10+# Nothing here contains a host address or a credential. Everything environment-specific
11+# comes from the environment, so this file stays safe to publish:
12+#
13+# DIST_HOST ssh target for the dist server (required for upload)
14+# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key)
15+# DIST_PATH remote web root of the dist server (default /data/dist)
16+# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64)
17+# MAC_USER / MAC_PASS (optional)
18+# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token)
19+# PLUGINGIT_REMOTE public mirror URL to push into
20+#
21+# Usage:
22+# ./release-dist.sh # full release
23+# ./release-dist.sh --dry-run # build + stage in /tmp, no upload
24+# ./release-dist.sh --no-macos # skip the macOS legs
25+# ./release-dist.sh --no-mirror # skip the plugingit mirror
26+# ./release-dist.sh --standalone # use this script even if the CLI is installed
27+# # (needed for plugins that link extra Win32 libs,
28+# # which the CLI's fixed link line cannot express)
29+
30+set -euo pipefail
31+
32+SLUG="sessionstats"
33+ID="plugin_sessionstats"
34+VERSION="1.0.0"
35+DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins"
36+
37+ROOT="$(cd "$(dirname "$0")" && pwd)"
38+cd "$ROOT"
39+
40+DRY_RUN=0
41+DO_MACOS=1
42+DO_MIRROR=1
43+STANDALONE=0
44+for arg in "$@"; do
45+ case "$arg" in
46+ --standalone) STANDALONE=1 ;;
47+ --dry-run) DRY_RUN=1 ;;
48+ --no-macos) DO_MACOS=0 ;;
49+ --no-mirror) DO_MIRROR=0 ;;
50+ -h|--help) sed -n '2,32p' "$0"; exit 0 ;;
51+ *) echo "unknown argument: $arg" >&2; exit 2 ;;
52+ esac
53+done
54+
55+DIST_HOST="${DIST_HOST:-}"
56+DIST_PASS="${DIST_PASS:-}"
57+DIST_PATH="${DIST_PATH:-/data/dist}"
58+PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}"
59+PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}"
60+
61+STAGE="/tmp/${SLUG}-dist-${VERSION}-$$"
62+mkdir -p "$STAGE"
63+trap 'rm -rf "$STAGE"' EXIT
64+
65+say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; }
66+die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; }
67+
68+# ---------------------------------------------------------------- 0. preflight
69+say "0/7 preflight"
70+
71+if [ "$STANDALONE" -eq 0 ] && command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
72+ say "using scorpiox-cli-botplugin publish"
73+ exec scorpiox-cli-botplugin publish "$ROOT"
74+fi
75+echo " running the standalone pipeline"
76+
77+[ -n "$(git status --porcelain 2>/dev/null)" ] && \
78+ echo " note: working tree is dirty; source.tar.gz comes from the last commit"
79+COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
80+echo " version $VERSION"
81+echo " commit $COMMIT"
82+
83+# ---------------------------------------------------------------- 1. secret scan
84+say "1/7 secret & LAN scan (full history)"
85+
86+SCAN_TMP="$STAGE/history.txt"
87+# Scan every added/removed line of every commit. Two exclusions, both about the
88+# audit rather than the code: the committer identity line, and any line that is
89+# itself a scan definition - otherwise this file's own detector patterns read as
90+# findings in every historical revision of it.
91+git log -p --all 2>/dev/null \
92+ | grep -v '^Author: ' \
93+ | grep -vE 'scan "|audit "|HITS=|grep -E|P_ROOT=|P_WT=|PK="|\$ALL' \
94+ > "$SCAN_TMP" || : > "$SCAN_TMP"
95+HITS=0
96+scan() { # scan <label> <regex>
97+ local out
98+ out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true)
99+ if [ -n "$out" ]; then
100+ printf ' \033[31mHIT\033[0m %s\n' "$1"
101+ printf '%s\n' "$out" | sed 's/^/ /'
102+ HITS=$((HITS + 1))
103+ else
104+ printf ' ok %s\n' "$1"
105+ fi
106+}
107+scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+'
108+scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
109+scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
110+scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
111+scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}'
112+scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}'
113+scan "hard-coded ssh password" 'sshpass -p [^"$]'
114+P_ROOT="/codebases"
115+P_PICOBOT="${P_ROOT}/pico""bot"
116+P_WT=".work""trees"
117+scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}"
118+scan "run-token env assignment" 'RUNNER_'"PASS="
119+if [ "$HITS" -ne 0 ]; then
120+ die "secret scan found $HITS problem(s) - refusing to publish"
121+fi
122+echo " clean: 0 hits"
123+
124+# ---------------------------------------------------------------- 2. build
125+say "2/7 build targets"
126+
127+# linux-x86_64 (glibc, native)
128+if command -v cc >/dev/null 2>&1; then
129+ cc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -o "$STAGE/$ID" src/$ID.c || die "native build failed"
130+ echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes"
131+else
132+ die "no native cc found"
133+fi
134+
135+# linux-x86_64-musl (fully static - the universal Linux artifact)
136+if command -v musl-gcc >/dev/null 2>&1; then
137+ musl-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -o "$STAGE/$ID.musl" src/$ID.c \
138+ || die "musl build failed"
139+ echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes"
140+else
141+ echo " skip linux-x86_64-musl (no musl-gcc)"
142+fi
143+
144+# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers)
145+if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
146+ aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -o "$STAGE/$ID.arm64" src/$ID.c \
147+ || die "arm64 build failed"
148+ echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes"
149+else
150+ echo " skip linux-arm64-musl (no aarch64-linux-gnu-gcc)"
151+fi
152+
153+# windows-x86_64 (static PE)
154+if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
155+ x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings \
156+ -o "$STAGE/$ID.exe" src/$ID.c || die "MinGW build failed"
157+ [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE"
158+ echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes"
159+else
160+ echo " skip windows-x86_64 (no MinGW cross compiler)"
161+fi
162+
163+# macOS legs - Mach-O must be produced by Apple clang on a real Mac.
164+# Both slices are cross-built from one host: -arch arm64 and -arch x86_64.
165+if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then
166+ MAC_USER="${MAC_USER:-$(whoami)}"
167+ MAC_DIR="/tmp/${ID}-mac-$$"
168+ echo " building macOS legs on $MAC_HOST"
169+ SSH_MAC=(ssh -o StrictHostKeyChecking=no)
170+ SCP_MAC=(scp -o StrictHostKeyChecking=no)
171+ if [ -n "${MAC_PASS:-}" ]; then
172+ SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}")
173+ SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}")
174+ fi
175+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then
176+ if "${SCP_MAC[@]}" src/$ID.c "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.c"; then
177+ # Build straight from the uploaded file - no src/ tree on the remote.
178+ for slice in arm64 x86_64; do
179+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \
180+ "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -arch $slice -o $ID.$slice $ID.c" \
181+ 2>/dev/null; then
182+ "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \
183+ && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)"
184+ else
185+ echo " warn: macos-$slice build failed on $MAC_HOST"
186+ fi
187+ done
188+ "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" || true
189+ else
190+ echo " warn: could not upload source to $MAC_HOST"
191+ fi
192+ else
193+ echo " warn: cannot reach macOS builder $MAC_HOST"
194+ fi
195+else
196+ echo " skip macOS legs (no MAC_HOST or --no-macos)"
197+fi
198+
199+# ---------------------------------------------------------------- 3. manifest
200+say "3/7 manifest + checksums"
201+
202+git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \
203+ -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \
204+ || tar -czf "$STAGE/source.tar.gz" --exclude=.git .
205+echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes"
206+
207+target_meta() { # target_meta <key> <file> <format> <relpath>
208+ local key="$1" file="$2" fmt="$3" rel="$4"
209+ [ -f "$file" ] || return 0
210+ local sha size
211+ sha=$(sha256sum "$file" | awk '{print $1}')
212+ size=$(wc -c < "$file" | tr -d ' ')
213+ printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \
214+ "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt"
215+}
216+
217+{
218+ printf '{\n'
219+ printf ' "slug": "%s",\n' "$SLUG"
220+ printf ' "id": "%s",\n' "$ID"
221+ printf ' "name": "sessions",\n'
222+ printf ' "desc": "Turn metrics",\n'
223+ printf ' "title": "Session Runtime & Turn Analytics",\n'
224+ printf ' "summary": "Zero-dependency read-only analytics over the ScorpioX session store: wall-clock duration, active agent-run time versus idle waiting, duty cycle, turn counts, tool-call frequency and profile/model usage for every session on the node. Parses meta.json, stats.json and events.jsonl directly, so it needs no database, no daemon and no network.",\n'
225+ printf ' "category": "sessions",\n'
226+ printf ' "version": "%s",\n' "$VERSION"
227+ printf ' "license": "MIT",\n'
228+ printf ' "trust_notice": "Executes native C code on your node. Opens session files under the local ScorpioX sessions directory read-only; it never writes, renames or deletes anything and makes zero network requests.",\n'
229+ printf ' "capabilities": ["local_filesystem_read", "session_store_read"],\n'
230+ printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG"
231+ printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG"
232+ printf ' "git_commit": "%s",\n' "$COMMIT"
233+ printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
234+ printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')"
235+ printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID"
236+ printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c",\n' "$ID" "$ID"
237+ printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
238+ printf ' "targets": {\n'
239+ first=1
240+ emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; }
241+ emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID"
242+ emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID"
243+ emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID"
244+ emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID"
245+ emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID"
246+ emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe"
247+ printf '\n }\n}\n'
248+} > "$STAGE/manifest.json"
249+
250+python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \
251+ || die "generated manifest.json is not valid JSON"
252+echo " manifest.json ok ($(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["targets"]))' "$STAGE/manifest.json") targets)"
253+
254+# SHA256SUMS - relative paths, exactly as published
255+( cd "$STAGE"
256+ for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done
257+ [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|"
258+ [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|"
259+ [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|"
260+ [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|"
261+ [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|"
262+ [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|"
263+ true ) > "$STAGE/SHA256SUMS"
264+echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries"
265+
266+# ---------------------------------------------------------------- 4. stage
267+say "4/7 stage tree"
268+PKG="$STAGE/pkg"
269+mkdir -p "$PKG"
270+cp "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/"
271+[ -f "$STAGE/$ID" ] && { mkdir -p "$PKG/linux-x86_64"; cp "$STAGE/$ID" "$PKG/linux-x86_64/$ID"; }
272+[ -f "$STAGE/$ID.musl" ] && { mkdir -p "$PKG/linux-x86_64-musl"; cp "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID"; }
273+[ -f "$STAGE/$ID.arm64" ] && { mkdir -p "$PKG/linux-arm64-musl"; cp "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID"; }
274+[ -f "$STAGE/$ID.macos-arm64" ] && { mkdir -p "$PKG/macos-arm64"; cp "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"; }
275+[ -f "$STAGE/$ID.macos-x86_64" ]&& { mkdir -p "$PKG/macos-x86_64"; cp "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"; }
276+[ -f "$STAGE/$ID.exe" ] && { mkdir -p "$PKG/windows-x86_64"; cp "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe"; }
277+echo " staged: $(find "$PKG" -type f | wc -l | tr -d ' ') file(s)"
278+
279+if [ "$DRY_RUN" -eq 1 ]; then
280+ say "dry run - leaving the staging tree in $PKG"
281+ trap - EXIT
282+ exit 0
283+fi
284+
285+# ---------------------------------------------------------------- 5. upload
286+say "5/7 upload to the dist server"
287+[ -n "$DIST_HOST" ] || die "DIST_HOST is not set (export DIST_HOST=<ssh-target>)"
288+SSH=(ssh -o StrictHostKeyChecking=no)
289+SCP=(scp -o StrictHostKeyChecking=no)
290+if [ -n "$DIST_PASS" ]; then
291+ SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}")
292+ SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}")
293+fi
294+REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION"
295+
296+"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \
297+ || die "cannot create $REMOTE_DIR on $DIST_HOST"
298+# Stage to one tarball, transfer it, extract remotely. Streaming tar through
299+# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and
300+# OpenSSH 9 refuses to scp a bare "." source.
301+tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed"
302+"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed"
303+"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \
304+ || die "remote extract failed"
305+echo " uploaded to $DIST_HOST:$REMOTE_DIR"
306+
307+# latest.json = copy of this version's manifest
308+"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \
309+ || die "latest.json update failed"
310+echo " updated bot-plugins/$SLUG/latest.json"
311+
312+# index.json - merge, preserving every sibling <slug>/latest.json
313+say "index.json merge"
314+"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY'
315+import json, os, sys, glob
316+slug = sys.argv[1]
317+entries = {}
318+for p in sorted(glob.glob('*/latest.json')):
319+ s = os.path.dirname(p)
320+ try:
321+ entries[s] = json.load(open(p))
322+ except Exception:
323+ pass
324+index = {
325+ 'ok': True,
326+ 'service': 'bot-plugins-dist',
327+ 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins',
328+ 'count': len(entries),
329+ 'slugs': sorted(entries),
330+ 'plugins': [entries[k] for k in sorted(entries)],
331+}
332+open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10))
333+os.replace('index.json.tmp', 'index.json')
334+print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries))))
335+PY" || die "index.json merge failed"
336+
337+# ---------------------------------------------------------------- 6. mirror
338+say "6/7 plugingit mirror"
339+if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then
340+ TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE")
341+ AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://token:${TOKEN}@|")
342+ git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed"
343+ git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true
344+ echo " mirrored to $PLUGINGIT_REMOTE"
345+else
346+ echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)"
347+fi
348+
349+# ---------------------------------------------------------------- 7. verify
350+say "7/7 verify"
351+CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \
352+ "$DIST_BASE_URL/$SLUG/latest.json" || echo 000)
353+if [ "$CODE" = "200" ]; then
354+ python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK - %s v%s, %d target(s)" % (d["slug"], d["version"], len(d["targets"])))' \
355+ "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON"
356+else
357+ echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE"
358+fi
359+
360+printf '\n\033[1mrelease complete\033[0m\n'
361+printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
362+printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
src/plugin_sessionstats.c+1297−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..716d9c8index 0000000..716d9c8
--- /dev/null--- /dev/null
+++ b/src/plugin_sessionstats.c+++ b/src/plugin_sessionstats.c
@@ -0,0 +1,1297 @@@@ -0,0 +1,1297 @@
1+/*
2+ * plugin_sessionstats - ScorpioX Bot open-source session runtime & turn analytics
3+ *
4+ * A single clean-room C99 binary that serves THREE modes:
5+ * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata
6+ * 2. ?action=summary | ?action=session&sid=... | ?format=json -> JSON node API
7+ * 3. GET (default) -> responsive HTML analytics UI
8+ *
9+ * Everything it reads is LOCAL to the node and read-only: the per-session
10+ * directories under the ScorpioX sessions root (meta.json, stats.json,
11+ * events.jsonl, and the optional "thinking" marker). Nothing is ever written,
12+ * renamed or deleted. There is no parameter anywhere in this file that can
13+ * point it at another host or another path outside the sessions root.
14+ *
15+ * Every timestamp in the session files is local wall-clock text
16+ * ("YYYY-MM-DD HH:MM:SS"). Only differences between timestamps are used, so a
17+ * single deterministic civil-days conversion is sufficient and no timezone
18+ * database is required.
19+ *
20+ * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and
21+ * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under
22+ * scorpiox-server on the node.
23+ *
24+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
25+ */
26+
27+#if defined(_WIN32) && !defined(_WIN32_WINNT)
28+# define _WIN32_WINNT 0x0601
29+#endif
30+
31+#if !defined(_WIN32)
32+# define _POSIX_C_SOURCE 200809L
33+# define _DEFAULT_SOURCE 1
34+# if defined(__APPLE__)
35+# define _DARWIN_C_SOURCE 1
36+# endif
37+#endif
38+
39+#include <stdio.h>
40+#include <stdlib.h>
41+#include <string.h>
42+#include <ctype.h>
43+#include <time.h>
44+#include <errno.h>
45+
46+#if defined(_WIN32)
47+# define WIN32_LEAN_AND_MEAN
48+# include <windows.h>
49+# include <direct.h>
50+# define SX_PATHSEP '\\'
51+#else
52+# include <unistd.h>
53+# include <dirent.h>
54+# include <sys/stat.h>
55+# include <sys/types.h>
56+# define SX_PATHSEP '/'
57+#endif
58+
59+#define PLUGIN_SLUG "sessionstats"
60+#define PLUGIN_ID "plugin_sessionstats"
61+#define PLUGIN_VER "1.0.0"
62+
63+#define NAME_SZ 128
64+#define MAX_SESSIONS 256
65+#define MAX_TOOLS 48
66+#define MAX_ROOTS 4
67+#define LINE_SZ 4096
68+#define FILE_SZ 16384
69+#define PATH_SZ 1024
70+
71+/* ------------------------------------------------------------------ */
72+/* Small string helpers */
73+/* ------------------------------------------------------------------ */
74+
75+static void str_copy(char *dst, size_t sz, const char *src)
76+{
77+ size_t i = 0;
78+ if (!dst || sz == 0) return;
79+ if (!src) { dst[0] = '\0'; return; }
80+ while (i + 1 < sz && src[i]) { dst[i] = src[i]; i++; }
81+ dst[i] = '\0';
82+}
83+
84+static void url_decode(char *s)
85+{
86+ char *o = s;
87+ if (!s) return;
88+ while (*s) {
89+ if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) {
90+ int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10);
91+ int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10);
92+ *o++ = (char)((hi << 4) | lo);
93+ s += 3;
94+ } else if (*s == '+') {
95+ *o++ = ' ';
96+ s++;
97+ } else {
98+ *o++ = *s++;
99+ }
100+ }
101+ *o = '\0';
102+}
103+
104+/* Read one query parameter, percent-decoded. Returns 1 when present. */
105+static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
106+{
107+ size_t klen;
108+ const char *p;
109+
110+ if (!out || outsz == 0) return 0;
111+ out[0] = '\0';
112+ if (!qs || !key) return 0;
113+ klen = strlen(key);
114+
115+ for (p = qs; *p; ) {
116+ if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
117+ const char *v = p + klen + 1;
118+ size_t i = 0;
119+ while (*v && *v != '&' && i + 1 < outsz) out[i++] = *v++;
120+ out[i] = '\0';
121+ url_decode(out);
122+ return 1;
123+ }
124+ p = strchr(p, '&');
125+ if (!p) break;
126+ p++;
127+ }
128+ return 0;
129+}
130+
131+static void json_str(const char *s)
132+{
133+ fputc('"', stdout);
134+ for (; s && *s; s++) {
135+ unsigned char c = (unsigned char)*s;
136+ if (c == '"' || c == '\\') { fputc('\\', stdout); fputc((char)c, stdout); }
137+ else if (c == '\n') fputs("\\n", stdout);
138+ else if (c == '\r') fputs("\\r", stdout);
139+ else if (c == '\t') fputs("\\t", stdout);
140+ else if (c >= 0x20 && c != 0x7f) fputc((char)c, stdout);
141+ }
142+ fputc('"', stdout);
143+}
144+
145+/* ------------------------------------------------------------------ */
146+/* Node security */
147+/* ------------------------------------------------------------------ */
148+
149+static void require_node_auth(void)
150+{
151+ const char *np = getenv("BOT_PASSWORD");
152+ const char *xp, *auth;
153+ char qpwd[128] = {0};
154+
155+ if (!np || !*np) return;
156+
157+ xp = getenv("HTTP_X_BOT_PASSWORD");
158+ if (xp && strcmp(xp, np) == 0) return;
159+
160+ auth = getenv("HTTP_AUTHORIZATION");
161+ if (auth) {
162+ while (*auth == ' ') auth++;
163+ if (strncasecmp(auth, "Bearer ", 7) == 0) {
164+ auth += 7;
165+ while (*auth == ' ') auth++;
166+ if (strcmp(auth, np) == 0) return;
167+ }
168+ }
169+
170+ if (get_query_val(getenv("QUERY_STRING"), "pwd", qpwd, sizeof qpwd)
171+ && strcmp(qpwd, np) == 0) return;
172+
173+ fputs("Status: 401 Unauthorized\r\n"
174+ "Content-Type: application/json; charset=utf-8\r\n\r\n"
175+ "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
176+ exit(0);
177+}
178+
179+/* ------------------------------------------------------------------ */
180+/* Time helpers */
181+/* ------------------------------------------------------------------ */
182+
183+/* Days since 1970-01-01 for a proleptic Gregorian civil date. */
184+static long long days_from_civil(int y, int m, int d)
185+{
186+ long long era, yoe, doy, doe;
187+ y -= (m <= 2);
188+ era = (y >= 0 ? y : y - 399) / 400;
189+ yoe = (long long)(y - era * 400);
190+ doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1;
191+ doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
192+ return era * 146097 + doe - 719468;
193+}
194+
195+/* Parse "YYYY-MM-DD HH:MM:SS". Returns 0 when unparseable. */
196+static long long parse_ts(const char *ts)
197+{
198+ int Y, M, D, h, mi, s;
199+ if (!ts || strlen(ts) < 19) return 0;
200+ if (sscanf(ts, "%d-%d-%d %d:%d:%d", &Y, &M, &D, &h, &mi, &s) != 6) return 0;
201+ if (M < 1 || M > 12 || D < 1 || D > 31) return 0;
202+ return days_from_civil(Y, M, D) * 86400LL + h * 3600LL + mi * 60LL + s;
203+}
204+
205+static void format_duration(long long sec, char *out, size_t outsz)
206+{
207+ long long d, h, m, s;
208+ if (sec < 0) sec = 0;
209+ d = sec / 86400;
210+ sec %= 86400;
211+ h = sec / 3600;
212+ sec %= 3600;
213+ m = sec / 60;
214+ s = sec % 60;
215+ if (d > 0) snprintf(out, outsz, "%lldd %02lldh %02lldm", d, h, m);
216+ else if (h > 0) snprintf(out, outsz, "%02lldh %02lldm %02llds", h, m, s);
217+ else if (m > 0) snprintf(out, outsz, "%02lldm %02llds", m, s);
218+ else snprintf(out, outsz, "%llds", s);
219+}
220+
221+/* ------------------------------------------------------------------ */
222+/* File helpers */
223+/* ------------------------------------------------------------------ */
224+
225+/* Read at most sz-1 bytes of a file into buf. Returns bytes read, -1 if absent. */
226+static int read_file(const char *path, char *buf, size_t sz)
227+{
228+ FILE *f;
229+ size_t n;
230+ if (!buf || sz == 0) return -1;
231+ buf[0] = '\0';
232+ f = fopen(path, "rb");
233+ if (!f) return -1;
234+ n = fread(buf, 1, sz - 1, f);
235+ buf[n] = '\0';
236+ fclose(f);
237+ return (int)n;
238+}
239+
240+static int path_exists(const char *path)
241+{
242+ FILE *f = fopen(path, "rb");
243+ if (f) { fclose(f); return 1; }
244+ return 0;
245+}
246+
247+/* Directory test, portable: fopen() on a directory succeeds on glibc, so a
248+ * real stat-equivalent is needed to answer "is this a sessions root?". */
249+static int sx_is_dir(const char *path)
250+{
251+#if defined(_WIN32)
252+ DWORD a = GetFileAttributesA(path);
253+ return (a != INVALID_FILE_ATTRIBUTES) && (a & FILE_ATTRIBUTE_DIRECTORY);
254+#else
255+ struct stat st;
256+ return (stat(path, &st) == 0) && S_ISDIR(st.st_mode);
257+#endif
258+}
259+
260+/* Extract a JSON string value for an exact top-level key name. */
261+static int json_get_str(const char *json, const char *key, char *out, size_t outsz)
262+{
263+ char needle[96];
264+ const char *p;
265+ size_t i = 0;
266+
267+ if (!json || !key || !out || outsz == 0) return 0;
268+ out[0] = '\0';
269+ if (strlen(key) + 3 >= sizeof needle) return 0;
270+ snprintf(needle, sizeof needle, "\"%s\"", key);
271+
272+ p = strstr(json, needle);
273+ if (!p) return 0;
274+ p += strlen(needle);
275+ while (*p && (*p == ' ' || *p == ':' || *p == '\t')) p++;
276+ if (*p != '"') return 0;
277+ p++;
278+ while (*p && *p != '"' && i + 1 < outsz) {
279+ if (*p == '\\' && p[1]) {
280+ p++;
281+ switch (*p) {
282+ case 'n': out[i++] = '\n'; break;
283+ case 't': out[i++] = '\t'; break;
284+ case 'r': out[i++] = '\r'; break;
285+ default: out[i++] = *p; break;
286+ }
287+ p++;
288+ continue;
289+ }
290+ out[i++] = *p++;
291+ }
292+ out[i] = '\0';
293+ return 1;
294+}
295+
296+/* Extract a numeric JSON value for an exact key name. */
297+static int json_get_num(const char *json, const char *key, double *out)
298+{
299+ char needle[96];
300+ const char *p;
301+ char *end = NULL;
302+
303+ if (!json || !key || !out) return 0;
304+ if (strlen(key) + 3 >= sizeof needle) return 0;
305+ snprintf(needle, sizeof needle, "\"%s\"", key);
306+
307+ p = strstr(json, needle);
308+ if (!p) return 0;
309+ p += strlen(needle);
310+ while (*p && (*p == ' ' || *p == ':' || *p == '\t')) p++;
311+ if (*p != '-' && !isdigit((unsigned char)*p)) return 0;
312+ *out = strtod(p, &end);
313+ return (end != p);
314+}
315+
316+/* ------------------------------------------------------------------ */
317+/* Directory listing (portable, directories only, dotfiles skipped) */
318+/* ------------------------------------------------------------------ */
319+
320+#if defined(_WIN32)
321+static int sx_list_dirs(const char *parent, char names[][NAME_SZ], int max)
322+{
323+ char pattern[PATH_SZ + 8];
324+ WIN32_FIND_DATAA fd;
325+ HANDLE h;
326+ int n = 0;
327+
328+ snprintf(pattern, sizeof pattern, "%s/*", parent);
329+ h = FindFirstFileA(pattern, &fd);
330+ if (h == INVALID_HANDLE_VALUE) return 0;
331+ do {
332+ if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) continue;
333+ if (fd.cFileName[0] == '.') continue;
334+ if (n < max) str_copy(names[n++], NAME_SZ, fd.cFileName);
335+ } while (FindNextFileA(h, &fd));
336+ FindClose(h);
337+ return n;
338+}
339+#else
340+static int sx_list_dirs(const char *parent, char names[][NAME_SZ], int max)
341+{
342+ DIR *d;
343+ struct dirent *de;
344+ int n = 0;
345+
346+ d = opendir(parent);
347+ if (!d) return 0;
348+ while ((de = readdir(d)) != NULL) {
349+ char full[PATH_SZ];
350+ struct stat st;
351+ if (de->d_name[0] == '.') continue;
352+ snprintf(full, sizeof full, "%s/%s", parent, de->d_name);
353+ if (stat(full, &st) != 0 || !S_ISDIR(st.st_mode)) continue;
354+ if (n < max) str_copy(names[n++], NAME_SZ, de->d_name);
355+ }
356+ closedir(d);
357+ return n;
358+}
359+#endif
360+
361+/* ------------------------------------------------------------------ */
362+/* Sessions root discovery */
363+/* ------------------------------------------------------------------ */
364+
365+/*
366+ * Resolve the sessions root. SX_SESSIONS_DIR always wins, which is what makes
367+ * the offline test suite possible and also what lets an operator point the
368+ * plugin at a relocated state directory. Otherwise the standard per-node
369+ * locations are tried in order.
370+ */
371+static int resolve_sessions_root(char *out, size_t outsz)
372+{
373+ const char *env = getenv("SX_SESSIONS_DIR");
374+#if !defined(_WIN32)
375+ const char *home;
376+#endif
377+ char cand[PATH_SZ];
378+
379+ if (env && *env) {
380+ str_copy(out, outsz, env);
381+ return sx_is_dir(env);
382+ }
383+
384+#if defined(_WIN32)
385+ const char *localappdata = getenv("LOCALAPPDATA");
386+ const char *userprofile = getenv("USERPROFILE");
387+ if (localappdata && *localappdata) {
388+ snprintf(cand, sizeof cand, "%s\\scorpiox\\sessions", localappdata);
389+ if (sx_is_dir(cand)) { str_copy(out, outsz, cand); return 1; }
390+ }
391+ if (userprofile && *userprofile) {
392+ snprintf(cand, sizeof cand, "%s\\.scorpiox\\sessions", userprofile);
393+ if (sx_is_dir(cand)) { str_copy(out, outsz, cand); return 1; }
394+ }
395+#else
396+ home = getenv("HOME");
397+ if (home && *home) {
398+ snprintf(cand, sizeof cand, "%s/.scorpiox/sessions", home);
399+ if (sx_is_dir(cand)) { str_copy(out, outsz, cand); return 1; }
400+ }
401+ if (sx_is_dir("/workspace/.scorpiox/sessions")) {
402+ str_copy(out, outsz, "/workspace/.scorpiox/sessions");
403+ return 1;
404+ }
405+#endif
406+
407+ /* Not found: report the most natural path so the UI can say what is missing. */
408+#if defined(_WIN32)
409+ if (localappdata && *localappdata)
410+ snprintf(out, outsz, "%s\\scorpiox\\sessions", localappdata);
411+ else
412+ str_copy(out, outsz, "scorpiox\\sessions");
413+#else
414+ if (home && *home) snprintf(out, outsz, "%s/.scorpiox/sessions", home);
415+ else str_copy(out, outsz, ".scorpiox/sessions");
416+#endif
417+ return 0;
418+}
419+
420+/* ------------------------------------------------------------------ */
421+/* One session */
422+/* ------------------------------------------------------------------ */
423+
424+typedef struct {
425+ char name[NAME_SZ];
426+} tool_use_t;
427+
428+typedef struct {
429+ char id[NAME_SZ]; /* directory name */
430+ char session_id[NAME_SZ];
431+ char start_time[40];
432+ long long start_epoch; /* from meta.json when present */
433+ long long first_ts; /* first event timestamp */
434+ long long last_ts; /* last event timestamp */
435+ long long total_sec;
436+ long long active_sec;
437+ long long idle_sec;
438+ double duty_pct;
439+ int turns;
440+ int is_active;
441+ char model[64];
442+ char provider[64];
443+ char profile[64];
444+ char branch[128];
445+ char cwd[512];
446+ char thread_guid[64];
447+ long long in_tokens;
448+ long long out_tokens;
449+ long long cache_read;
450+ long long cache_write;
451+ tool_use_t tools[MAX_TOOLS];
452+ int tool_count;
453+ int tool_hits[MAX_TOOLS];
454+} session_t;
455+
456+/* Record (and count) one tool name for this session. */
457+static void note_tool(session_t *s, const char *name)
458+{
459+ int i;
460+ if (!name || !*name) return;
461+ for (i = 0; i < s->tool_count; i++) {
462+ if (strcmp(s->tools[i].name, name) == 0) { s->tool_hits[i]++; return; }
463+ }
464+ if (s->tool_count >= MAX_TOOLS) return;
465+ str_copy(s->tools[s->tool_count].name, NAME_SZ, name);
466+ s->tool_hits[s->tool_count] = 1;
467+ s->tool_count++;
468+}
469+
470+/*
471+ * Parse one session directory. Read-only: opens meta.json, stats.json,
472+ * events.jsonl and probes for the "thinking" marker. Any missing file simply
473+ * contributes nothing.
474+ */
475+static int load_session(const char *root, const char *name, session_t *s)
476+{
477+ char path[PATH_SZ];
478+ char buf[FILE_SZ];
479+ double num;
480+
481+ memset(s, 0, sizeof *s);
482+ str_copy(s->id, sizeof s->id, name);
483+ str_copy(s->session_id, sizeof s->session_id, name);
484+
485+ /* Refuse a directory name that is not actually present: the caller uses
486+ * this return value to answer "session not found". */
487+ snprintf(path, sizeof path, "%s/%s", root, name);
488+ if (!sx_is_dir(path)) return 0;
489+
490+ /* --- meta.json --- */
491+ snprintf(path, sizeof path, "%s/%s/meta.json", root, name);
492+ if (read_file(path, buf, sizeof buf) > 0) {
493+ char tmp[NAME_SZ];
494+ if (json_get_str(buf, "id", tmp, sizeof tmp)) str_copy(s->session_id, sizeof s->session_id, tmp);
495+ json_get_str(buf, "start_time", s->start_time, sizeof s->start_time);
496+ json_get_str(buf, "model", s->model, sizeof s->model);
497+ json_get_str(buf, "provider", s->provider, sizeof s->provider);
498+ json_get_str(buf, "profile", s->profile, sizeof s->profile);
499+ json_get_str(buf, "cwd", s->cwd, sizeof s->cwd);
500+ json_get_str(buf, "thread_guid", s->thread_guid, sizeof s->thread_guid);
501+ if (json_get_num(buf, "start_epoch", &num)) s->start_epoch = (long long)num;
502+ }
503+
504+ /* --- stats.json (optional usage block) --- */
505+ snprintf(path, sizeof path, "%s/%s/stats.json", root, name);
506+ if (read_file(path, buf, sizeof buf) > 0) {
507+ if (!s->model[0]) json_get_str(buf, "model", s->model, sizeof s->model);
508+ if (!s->cwd[0]) json_get_str(buf, "cwd", s->cwd, sizeof s->cwd);
509+ json_get_str(buf, "branch", s->branch, sizeof s->branch);
510+ if (json_get_num(buf, "input_tokens", &num)) s->in_tokens = (long long)num;
511+ if (json_get_num(buf, "output_tokens", &num)) s->out_tokens = (long long)num;
512+ if (json_get_num(buf, "cache_read_tokens", &num)) s->cache_read = (long long)num;
513+ if (json_get_num(buf, "cache_creation_tokens", &num))s->cache_write = (long long)num;
514+ }
515+
516+ /* --- thinking / active marker --- */
517+ snprintf(path, sizeof path, "%s/%s/thinking", root, name);
518+ if (path_exists(path)) s->is_active = 1;
519+
520+ /* --- events.jsonl: single streaming pass --- */
521+ snprintf(path, sizeof path, "%s/%s/events.jsonl", root, name);
522+ {
523+ FILE *f = fopen(path, "rb");
524+ char line[LINE_SZ];
525+ long long run_start = 0;
526+ int in_run = 0;
527+
528+ if (f) {
529+ while (fgets(line, sizeof line, f)) {
530+ char ts[40] = {0};
531+ char ev[48] = {0};
532+ long long t;
533+
534+ if (!json_get_str(line, "ts", ts, sizeof ts)) continue;
535+ t = parse_ts(ts);
536+ if (t <= 0) continue;
537+ json_get_str(line, "event", ev, sizeof ev);
538+
539+ if (!s->first_ts) s->first_ts = t;
540+ s->last_ts = t;
541+
542+ if (strcmp(ev, "session_start") == 0) {
543+ if (!s->start_time[0]) str_copy(s->start_time, sizeof s->start_time, ts);
544+ if (!s->model[0]) json_get_str(line, "model", s->model, sizeof s->model);
545+ if (!s->provider[0]) json_get_str(line, "provider", s->provider, sizeof s->provider);
546+ if (!s->profile[0]) json_get_str(line, "profile", s->profile, sizeof s->profile);
547+ } else if (strcmp(ev, "agent_run_start") == 0) {
548+ if (!in_run) { in_run = 1; run_start = t; s->turns++; }
549+ } else if (strcmp(ev, "agent_idle") == 0
550+ || strcmp(ev, "agent_complete") == 0
551+ || strcmp(ev, "session_end") == 0
552+ || strcmp(ev, "session_compact") == 0) {
553+ if (in_run) {
554+ if (t > run_start) s->active_sec += (t - run_start);
555+ in_run = 0;
556+ }
557+ if (strcmp(ev, "agent_complete") == 0) s->is_active = 0;
558+ } else if (strcmp(ev, "user_message") == 0) {
559+ /* A user message ends idleness; the run starts right after. */
560+ if (in_run) {
561+ if (t > run_start) s->active_sec += (t - run_start);
562+ in_run = 0;
563+ }
564+ } else if (strcmp(ev, "tool_use") == 0) {
565+ char tool[NAME_SZ] = {0};
566+ if (json_get_str(line, "tool", tool, sizeof tool)) note_tool(s, tool);
567+ }
568+ }
569+ fclose(f);
570+
571+ /* A run that never closed is still running: count up to the last event. */
572+ if (in_run && s->last_ts > run_start) s->active_sec += (s->last_ts - run_start);
573+ }
574+ }
575+
576+ if (!s->start_time[0] && s->first_ts) {
577+ /* Fall back to the first event timestamp rendered as text is unnecessary:
578+ * we only need a numeric base below. */
579+ }
580+ if (!s->start_epoch) s->start_epoch = s->first_ts;
581+
582+ /* --- durations --- */
583+ if (s->start_epoch > 0) {
584+ long long end = s->last_ts > 0 ? s->last_ts : s->start_epoch;
585+ s->total_sec = end - s->start_epoch;
586+ if (s->total_sec < 0) s->total_sec = 0;
587+ }
588+ if (s->last_ts > s->first_ts && s->last_ts - s->first_ts > s->total_sec)
589+ s->total_sec = s->last_ts - s->first_ts;
590+
591+ if (s->active_sec > s->total_sec) s->active_sec = s->total_sec;
592+ s->idle_sec = s->total_sec - s->active_sec;
593+ s->duty_pct = s->total_sec > 0 ? (100.0 * (double)s->active_sec / (double)s->total_sec) : 0.0;
594+
595+ return 1;
596+}
597+
598+/* Scan every root we were given and append sessions. Returns count. */
599+static int scan_sessions(const char *root, session_t *out, int max)
600+{
601+ static char names[1024][NAME_SZ];
602+ int n = sx_list_dirs(root, names, 1024);
603+ int i, kept = 0;
604+
605+ for (i = 0; i < n && kept < max; i++) {
606+ session_t s;
607+ if (!load_session(root, names[i], &s)) continue;
608+ out[kept++] = s;
609+ }
610+ return kept;
611+}
612+
613+/* ------------------------------------------------------------------ */
614+/* Profile / model aggregation */
615+/* ------------------------------------------------------------------ */
616+
617+typedef struct {
618+ char label[64];
619+ int sessions;
620+ long long active_sec;
621+ int turns;
622+} bucket_t;
623+
624+static void bucket_add(bucket_t *b, int *count, int max, const char *label,
625+ long long active_sec, int turns)
626+{
627+ int i;
628+ const char *key = (label && *label) ? label : "unknown";
629+
630+ for (i = 0; i < *count; i++) {
631+ if (strcmp(b[i].label, key) == 0) {
632+ b[i].sessions++;
633+ b[i].active_sec += active_sec;
634+ b[i].turns += turns;
635+ return;
636+ }
637+ }
638+ if (*count >= max) return;
639+ str_copy(b[*count].label, sizeof b[*count].label, key);
640+ b[*count].sessions = 1;
641+ b[*count].active_sec = active_sec;
642+ b[*count].turns = turns;
643+ (*count)++;
644+}
645+
646+/* ------------------------------------------------------------------ */
647+/* Sorting */
648+/* ------------------------------------------------------------------ */
649+
650+static int cmp_session_desc(const void *a, const void *b)
651+{
652+ const session_t *x = (const session_t *)a;
653+ const session_t *y = (const session_t *)b;
654+ if (x->last_ts != y->last_ts) return x->last_ts < y->last_ts ? 1 : -1;
655+ return strcmp(x->id, y->id);
656+}
657+
658+static int cmp_bucket_desc(const void *a, const void *b)
659+{
660+ const bucket_t *x = (const bucket_t *)a;
661+ const bucket_t *y = (const bucket_t *)b;
662+ if (x->active_sec != y->active_sec) return x->active_sec < y->active_sec ? 1 : -1;
663+ return strcmp(x->label, y->label);
664+}
665+
666+/* Sort tools by hit count while keeping the hits array aligned. */
667+static void sort_tools(session_t *s)
668+{
669+ int i, j;
670+ for (i = 1; i < s->tool_count; i++) {
671+ tool_use_t key = s->tools[i];
672+ int keyhits = s->tool_hits[i];
673+ j = i - 1;
674+ while (j >= 0 && s->tool_hits[j] < keyhits) {
675+ s->tools[j + 1] = s->tools[j];
676+ s->tool_hits[j + 1] = s->tool_hits[j];
677+ j--;
678+ }
679+ s->tools[j + 1] = key;
680+ s->tool_hits[j + 1] = keyhits;
681+ }
682+}
683+
684+/* ------------------------------------------------------------------ */
685+/* Aggregates */
686+/* ------------------------------------------------------------------ */
687+
688+typedef struct {
689+ char root[PATH_SZ];
690+ int root_ok;
691+ int count;
692+ long long total_sec;
693+ long long active_sec;
694+ long long idle_sec;
695+ double duty_pct;
696+ int turns;
697+ int active_now;
698+ int tool_events;
699+ session_t *sessions;
700+} summary_t;
701+
702+static void build_summary(summary_t *sum, session_t *buf, int n)
703+{
704+ int i, j;
705+ memset(sum, 0, sizeof *sum);
706+ sum->sessions = buf;
707+ sum->count = n;
708+
709+ for (i = 0; i < n; i++) {
710+ session_t *s = &buf[i];
711+ sum->total_sec += s->total_sec;
712+ sum->active_sec += s->active_sec;
713+ sum->turns += s->turns;
714+ if (s->is_active) sum->active_now++;
715+ sort_tools(s);
716+ for (j = 0; j < s->tool_count; j++) sum->tool_events += s->tool_hits[j];
717+ }
718+ sum->idle_sec = sum->total_sec - sum->active_sec;
719+ if (sum->idle_sec < 0) sum->idle_sec = 0;
720+ sum->duty_pct = sum->total_sec > 0
721+ ? (100.0 * (double)sum->active_sec / (double)sum->total_sec) : 0.0;
722+}
723+
724+/* ------------------------------------------------------------------ */
725+/* JSON output */
726+/* ------------------------------------------------------------------ */
727+
728+static void json_header(void)
729+{
730+ fputs("Content-Type: application/json; charset=utf-8\r\n"
731+ "Cache-Control: no-store\r\n"
732+ "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
733+}
734+
735+static void print_session_obj(const session_t *s, int with_tools)
736+{
737+ char tot[64], act[64], idl[64];
738+ int i;
739+
740+ format_duration(s->total_sec, tot, sizeof tot);
741+ format_duration(s->active_sec, act, sizeof act);
742+ format_duration(s->idle_sec, idl, sizeof idl);
743+
744+ printf("{");
745+ printf("\"id\":"); json_str(s->session_id);
746+ printf(",\"dir\":"); json_str(s->id);
747+ printf(",\"model\":"); json_str(s->model);
748+ printf(",\"provider\":"); json_str(s->provider);
749+ printf(",\"profile\":"); json_str(s->profile);
750+ printf(",\"branch\":"); json_str(s->branch);
751+ printf(",\"cwd\":"); json_str(s->cwd);
752+ printf(",\"start_time\":"); json_str(s->start_time);
753+ printf(",\"first_epoch\":%lld", s->first_ts);
754+ printf(",\"last_epoch\":%lld", s->last_ts);
755+ printf(",\"is_active\":%s", s->is_active ? "true" : "false");
756+ printf(",\"total_sec\":%lld", s->total_sec);
757+ printf(",\"total_fmt\":"); json_str(tot);
758+ printf(",\"active_sec\":%lld", s->active_sec);
759+ printf(",\"active_fmt\":"); json_str(act);
760+ printf(",\"idle_sec\":%lld", s->idle_sec);
761+ printf(",\"idle_fmt\":"); json_str(idl);
762+ printf(",\"duty_cycle_pct\":%.2f", s->duty_pct);
763+ printf(",\"turns\":%d", s->turns);
764+ printf(",\"avg_turn_sec\":%.1f",
765+ s->turns > 0 ? ((double)s->active_sec / (double)s->turns) : 0.0);
766+ printf(",\"tokens\":{\"in\":%lld,\"out\":%lld,\"cache_read\":%lld,\"cache_write\":%lld}",
767+ s->in_tokens, s->out_tokens, s->cache_read, s->cache_write);
768+ if (with_tools) {
769+ printf(",\"tools\":[");
770+ for (i = 0; i < s->tool_count; i++) {
771+ if (i) printf(",");
772+ printf("{\"name\":"); json_str(s->tools[i].name);
773+ printf(",\"calls\":%d}", s->tool_hits[i]);
774+ }
775+ printf("]");
776+ }
777+ printf("}");
778+}
779+
780+static void print_summary_json(const summary_t *sum)
781+{
782+ bucket_t profiles[64], models[64];
783+ int np = 0, nm = 0, i;
784+ char tot[64], act[64], idl[64];
785+
786+ for (i = 0; i < sum->count; i++) {
787+ const session_t *s = &sum->sessions[i];
788+ bucket_add(profiles, &np, 64, s->profile[0] ? s->profile : "unknown",
789+ s->active_sec, s->turns);
790+ bucket_add(models, &nm, 64, s->model[0] ? s->model : "unknown",
791+ s->active_sec, s->turns);
792+ }
793+ qsort(profiles, (size_t)np, sizeof profiles[0], cmp_bucket_desc);
794+ qsort(models, (size_t)nm, sizeof models[0], cmp_bucket_desc);
795+
796+ format_duration(sum->total_sec, tot, sizeof tot);
797+ format_duration(sum->active_sec, act, sizeof act);
798+ format_duration(sum->idle_sec, idl, sizeof idl);
799+
800+ json_header();
801+ printf("{");
802+ printf("\"ok\":true");
803+ printf(",\"plugin\":\"%s\"", PLUGIN_ID);
804+ printf(",\"version\":\"%s\"", PLUGIN_VER);
805+ printf(",\"sessions_root\":"); json_str(sum->root);
806+ printf(",\"root_found\":%s", sum->root_ok ? "true" : "false");
807+ printf(",\"count\":%d", sum->count);
808+ printf(",\"active_now\":%d", sum->active_now);
809+ printf(",\"total_sec\":%lld", sum->total_sec);
810+ printf(",\"total_fmt\":"); json_str(tot);
811+ printf(",\"active_sec\":%lld", sum->active_sec);
812+ printf(",\"active_fmt\":"); json_str(act);
813+ printf(",\"idle_sec\":%lld", sum->idle_sec);
814+ printf(",\"idle_fmt\":"); json_str(idl);
815+ printf(",\"duty_cycle_pct\":%.2f", sum->duty_pct);
816+ printf(",\"turns\":%d", sum->turns);
817+ printf(",\"tool_events\":%d", sum->tool_events);
818+
819+ printf(",\"profiles\":[");
820+ for (i = 0; i < np; i++) {
821+ if (i) printf(",");
822+ printf("{\"profile\":"); json_str(profiles[i].label);
823+ printf(",\"sessions\":%d,\"active_sec\":%lld,\"turns\":%d}",
824+ profiles[i].sessions, profiles[i].active_sec, profiles[i].turns);
825+ }
826+ printf("]");
827+
828+ printf(",\"models\":[");
829+ for (i = 0; i < nm; i++) {
830+ if (i) printf(",");
831+ printf("{\"model\":"); json_str(models[i].label);
832+ printf(",\"sessions\":%d,\"active_sec\":%lld,\"turns\":%d}",
833+ models[i].sessions, models[i].active_sec, models[i].turns);
834+ }
835+ printf("]");
836+
837+ printf(",\"sessions\":[");
838+ for (i = 0; i < sum->count; i++) {
839+ if (i) printf(",");
840+ print_session_obj(&sum->sessions[i], 1);
841+ }
842+ printf("]}\n");
843+}
844+
845+static void print_session_json(const session_t *s, const char *root)
846+{
847+ char tot[64], act[64], idl[64];
848+ format_duration(s->total_sec, tot, sizeof tot);
849+ format_duration(s->active_sec, act, sizeof act);
850+ format_duration(s->idle_sec, idl, sizeof idl);
851+
852+ json_header();
853+ printf("{\"ok\":true,\"plugin\":\"%s\",\"version\":\"%s\"", PLUGIN_ID, PLUGIN_VER);
854+ printf(",\"sessions_root\":"); json_str(root);
855+ printf(",\"session\":"); print_session_obj(s, 1);
856+ printf(",\"summary\":{\"total_sec\":%lld,\"total_fmt\":", s->total_sec);
857+ json_str(tot);
858+ printf(",\"active_sec\":%lld,\"active_fmt\":", s->active_sec);
859+ json_str(act);
860+ printf(",\"idle_sec\":%lld,\"idle_fmt\":", s->idle_sec);
861+ json_str(idl);
862+ printf(",\"duty_cycle_pct\":%.2f,\"turns\":%d}}\n", s->duty_pct, s->turns);
863+}
864+
865+/* ------------------------------------------------------------------ */
866+/* HTML UI */
867+/* ------------------------------------------------------------------ */
868+
869+static void html_head(int embed, const char *initial_id)
870+{
871+ (void)embed;
872+ (void)initial_id;
873+ fputs(
874+ "Content-Type: text/html; charset=utf-8\r\n"
875+ "Cache-Control: no-store\r\n"
876+ "X-Content-Type-Options: nosniff\r\n"
877+ "\r\n"
878+ "<!DOCTYPE html><html lang='en'><head><meta charset='utf-8'>"
879+ "<meta name='viewport' content='width=device-width,initial-scale=1'>"
880+ "<title>Session Analytics</title>"
881+ "<style>"
882+ ":root{color-scheme:dark light;"
883+ "--bg:#0d0d0f;--surface:#18181b;--surface2:#212125;--text:#f5f5f7;--muted:#8e8e93;"
884+ "--line:rgba(255,255,255,.12);--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;"
885+ "--purple:#bf5af2;--red:#ff453a}"
886+ "@media(prefers-color-scheme:light){:root{--bg:#f5f5f7;--surface:#ffffff;"
887+ "--surface2:#f0f0f4;--text:#1d1d1f;--muted:#6e6e73;--line:rgba(0,0,0,.1);"
888+ "--blue:#0071e3;--green:#28cd41;--orange:#ff9500;--purple:#af52de;--red:#ff3b30}}"
889+ "body.theme-light{--bg:#f5f5f7;--surface:#ffffff;--surface2:#f0f0f4;--text:#1d1d1f;"
890+ "--muted:#6e6e73;--line:rgba(0,0,0,.1);--blue:#0071e3;--green:#28cd41;"
891+ "--orange:#ff9500;--purple:#af52de;--red:#ff3b30}"
892+ "body.theme-dark{--bg:#0d0d0f;--surface:#18181b;--surface2:#212125;--text:#f5f5f7;"
893+ "--muted:#8e8e93;--line:rgba(255,255,255,.12);--blue:#0a84ff;--green:#30d158;"
894+ "--orange:#ff9f0a;--purple:#bf5af2;--red:#ff453a}"
895+ "*{box-sizing:border-box}"
896+ "body{margin:0;padding:14px;background:var(--bg);color:var(--text);"
897+ "font-family:-apple-system,BlinkMacSystemFont,'SF Pro Text','Segoe UI',Roboto,sans-serif;"
898+ "-webkit-font-smoothing:antialiased;font-size:13px;line-height:1.45}"
899+ ".wrap{max-width:1000px;margin:0 auto}"
900+ ".head{display:flex;align-items:center;justify-content:space-between;gap:10px;"
901+ "flex-wrap:wrap;padding-bottom:12px;margin-bottom:14px;border-bottom:1px solid var(--line)}"
902+ ".brand{display:flex;align-items:center;gap:8px;font-size:15px;font-weight:700}"
903+ ".brand svg{width:20px;height:20px;flex:0 0 auto}"
904+ ".pill{font-size:10px;font-weight:700;letter-spacing:.4px;text-transform:uppercase;"
905+ "padding:2px 8px;border-radius:999px;border:1px solid var(--line);color:var(--muted)}"
906+ ".pill.on{color:var(--green);border-color:rgba(48,209,88,.4);background:rgba(48,209,88,.12)}"
907+ ".actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap}"
908+ "button,select{background:var(--surface);color:var(--text);border:1px solid var(--line);"
909+ "border-radius:8px;padding:6px 11px;font-size:12px;font-weight:600;cursor:pointer;"
910+ "font-family:inherit;outline:none}"
911+ "button:hover{background:var(--surface2)}"
912+ "button.primary{background:var(--blue);border-color:var(--blue);color:#fff}"
913+ ".grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:10px;margin-bottom:12px}"
914+ ".card{background:var(--surface);border:1px solid var(--line);border-radius:12px;padding:13px}"
915+ ".k{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.5px;"
916+ "color:var(--muted);margin-bottom:5px}"
917+ ".v{font-size:22px;font-weight:700;letter-spacing:-.4px;font-variant-numeric:tabular-nums;"
918+ "overflow:hidden;text-overflow:ellipsis;white-space:nowrap}"
919+ ".v.blue{color:var(--blue)}.v.green{color:var(--green)}.v.orange{color:var(--orange)}"
920+ ".v.purple{color:var(--purple)}"
921+ ".sub{font-size:11px;color:var(--muted);margin-top:3px}"
922+ ".panel{background:var(--surface);border:1px solid var(--line);border-radius:12px;"
923+ "padding:13px;margin-bottom:12px}"
924+ ".panel h2{margin:0 0 9px;font-size:12px;font-weight:700;text-transform:uppercase;"
925+ "letter-spacing:.5px;color:var(--muted)}"
926+ ".rail{height:12px;border-radius:999px;background:var(--surface2);"
927+ "border:1px solid var(--line);overflow:hidden;display:flex}"
928+ ".rail .on{background:linear-gradient(90deg,var(--blue),var(--green));height:100%}"
929+ ".legend{display:flex;gap:14px;flex-wrap:wrap;margin-top:8px;font-size:11px;color:var(--muted)}"
930+ ".legend i{display:inline-block;width:8px;height:8px;border-radius:2px;margin-right:5px}"
931+ ".bars{display:flex;flex-direction:column;gap:7px}"
932+ ".row{display:grid;grid-template-columns:150px 1fr 78px;align-items:center;gap:9px;font-size:12px}"
933+ ".row .nm{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--muted)}"
934+ ".track{height:9px;border-radius:999px;background:var(--surface2);overflow:hidden}"
935+ ".fill{height:100%;border-radius:999px;background:var(--blue);min-width:2px}"
936+ ".val{text-align:right;font-variant-numeric:tabular-nums;font-size:11px;color:var(--muted)}"
937+ ".tbl{width:100%;border-collapse:collapse;font-size:12px}"
938+ ".tbl th{text-align:left;font-size:10px;text-transform:uppercase;letter-spacing:.5px;"
939+ "color:var(--muted);font-weight:700;padding:6px 8px;border-bottom:1px solid var(--line);"
940+ "cursor:pointer;white-space:nowrap;user-select:none}"
941+ ".tbl th:hover{color:var(--text)}"
942+ ".tbl td{padding:7px 8px;border-bottom:1px solid var(--line);vertical-align:top}"
943+ ".tbl tr:last-child td{border-bottom:0}"
944+ ".tbl tr.sel td{background:var(--surface2)}"
945+ ".tbl tr:hover td{background:var(--surface2);cursor:pointer}"
946+ ".mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px}"
947+ ".nowrap{white-space:nowrap}"
948+ ".tag{display:inline-block;padding:1px 6px;border-radius:999px;font-size:10px;"
949+ "font-weight:700;border:1px solid var(--line);color:var(--muted)}"
950+ ".tag.on{color:var(--green);border-color:rgba(48,209,88,.4);background:rgba(48,209,88,.12)}"
951+ ".scroll{overflow-x:auto;-webkit-overflow-scrolling:touch}"
952+ ".empty{padding:26px 12px;text-align:center;color:var(--muted);font-size:12px}"
953+ ".err{color:var(--red)}"
954+ "@media(max-width:640px){"
955+ ".v{font-size:19px}"
956+ ".row{grid-template-columns:100px 1fr 62px}"
957+ ".tbl th:nth-child(4),.tbl td:nth-child(4),"
958+ ".tbl th:nth-child(5),.tbl td:nth-child(5){display:none}"
959+ "body{padding:10px}}"
960+ "@media(max-width:400px){.row{grid-template-columns:80px 1fr 54px}.grid{grid-template-columns:1fr 1fr}}"
961+ "</style></head><body><div class='wrap'>"
962+ "<div class='head'>"
963+ "<div class='brand'>"
964+ "<svg viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='1.8' "
965+ "stroke-linecap='round' stroke-linejoin='round' aria-hidden='true'>"
966+ "<circle cx='12' cy='12' r='9'></circle><path d='M12 7v5l3.5 2'></path></svg>"
967+ "<span>Session Analytics</span>"
968+ "<span class='pill' id='livePill'>idle</span>"
969+ "</div>"
970+ "<div class='actions'>"
971+ "<select id='sortSel' aria-label='Sort sessions'>"
972+ "<option value='recent'>Recent first</option>"
973+ "<option value='active'>Most active</option>"
974+ "<option value='turns'>Most turns</option>"
975+ "<option value='duty'>Highest duty cycle</option>"
976+ "</select>"
977+ "<button id='btnReload' type='button'>Refresh</button>"
978+ "<button id='btnTheme' type='button' aria-label='Toggle theme'>Theme</button>"
979+ "</div></div>"
980+ "<div id='err' class='err'></div>"
981+ "<div class='grid'>"
982+ "<div class='card'><div class='k'>Sessions</div><div class='v blue' id='kSessions'>-</div>"
983+ "<div class='sub' id='kSessionsSub'>&nbsp;</div></div>"
984+ "<div class='card'><div class='k'>Wall clock</div><div class='v' id='kTotal'>-</div>"
985+ "<div class='sub'>All sessions combined</div></div>"
986+ "<div class='card'><div class='k'>Active work</div><div class='v green' id='kActive'>-</div>"
987+ "<div class='sub' id='kActiveSub'>&nbsp;</div></div>"
988+ "<div class='card'><div class='k'>Duty cycle</div><div class='v orange' id='kDuty'>-</div>"
989+ "<div class='sub' id='kDutySub'>&nbsp;</div></div>"
990+ "<div class='card'><div class='k'>Turns</div><div class='v purple' id='kTurns'>-</div>"
991+ "<div class='sub' id='kTurnsSub'>&nbsp;</div></div>"
992+ "</div>"
993+ "<div class='panel'>"
994+ "<h2>Active versus idle</h2>"
995+ "<div class='rail'><div class='on' id='railOn' style='width:0%'></div></div>"
996+ "<div class='legend'>"
997+ "<span><i style='background:var(--green)'></i>Active (agent run)</span>"
998+ "<span><i style='background:var(--surface2);border:1px solid var(--line)'></i>Idle (waiting)</span>"
999+ "<span id='railText'></span>"
1000+ "</div></div>"
1001+ "<div class='panel'><h2>Profile usage by active time</h2>"
1002+ "<div class='bars' id='profBars'><div class='empty'>No data</div></div></div>"
1003+ "<div class='panel'><h2>Model usage by active time</h2>"
1004+ "<div class='bars' id='modelBars'><div class='empty'>No data</div></div></div>"
1005+ "<div class='panel'><h2>Sessions</h2><div class='scroll'>"
1006+ "<table class='tbl' id='tbl'><thead><tr>"
1007+ "<th data-key='id'>Session</th>"
1008+ "<th data-key='profile'>Profile / model</th>"
1009+ "<th data-key='active'>Active</th>"
1010+ "<th data-key='total'>Wall</th>"
1011+ "<th data-key='duty'>Duty</th>"
1012+ "<th data-key='turns'>Turns</th>"
1013+ "</tr></thead><tbody id='tbody'></tbody></table>"
1014+ "</div><div class='empty' id='tblEmpty' style='display:none'>No session directories found</div></div>"
1015+ "<div class='panel'><h2>Selected session</h2>"
1016+ "<div id='detail' class='sub'>Select a row above to inspect tool usage.</div></div>"
1017+ "</div>"
1018+ "<script>", stdout);
1019+}
1020+
1021+static void html_script(const char *initial_id)
1022+{
1023+ fputs(
1024+ "var q=new URLSearchParams(location.search);"
1025+ "var node=q.get('node')||'';"
1026+ "var pretty=q.get('plugin')||'';"
1027+ "var sel=q.get('id')||'", stdout);
1028+ if (initial_id && *initial_id) {
1029+ const char *p;
1030+ for (p = initial_id; *p; p++) {
1031+ if (*p == '\'' || *p == '\\') putchar('\\');
1032+ putchar(*p);
1033+ }
1034+ }
1035+ fputs("';"
1036+ "var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))"
1037+ "||localStorage.getItem('bot_active_pwd')||'';"
1038+ "var DATA=null,SORT='recent';"
1039+
1040+ "function api(u){"
1041+ " return fetch(u,{headers:pwd?{'X-Bot-Password':pwd}:{},cache:'no-store'})"
1042+ " .then(function(r){ if(!r.ok) throw new Error('HTTP '+r.status); return r.json(); });"
1043+ "}"
1044+
1045+ /* Two routes: hub proxy when served through bot.scorpiox.net, direct plugin
1046+ route when the page was opened straight from the node. */
1047+ "function url(action,extra){"
1048+ " var base=pretty?('/plugins?plugin='+encodeURIComponent(pretty)+'&action='+encodeURIComponent(action))"
1049+ " :('/plugin_sessionstats?action='+encodeURIComponent(action));"
1050+ " if(extra)base+='&'+extra;"
1051+ " if(node)base+='&node='+encodeURIComponent(node);"
1052+ " if(pwd)base+='&pwd='+encodeURIComponent(pwd);"
1053+ " return base;"
1054+ "}"
1055+
1056+ "function esc(s){return String(s==null?'':s).replace(/[&<>\"]/g,function(c){"
1057+ " return c==='&'?'&amp;':c==='<'?'&lt;':c==='>'?'&gt;':'&quot;';});}"
1058+
1059+ "function fmt(sec){"
1060+ " sec=Math.max(0,Math.floor(sec||0));"
1061+ " var d=Math.floor(sec/86400),r=sec%86400,h=Math.floor(r/3600);"
1062+ " r%=3600;var m=Math.floor(r/60),s=r%60;var p=function(n){return (n<10?'0':'')+n;};"
1063+ " if(d>0)return d+'d '+p(h)+'h '+p(m)+'m';"
1064+ " if(h>0)return p(h)+'h '+p(m)+'m '+p(s)+'s';"
1065+ " if(m>0)return p(m)+'m '+p(s)+'s';"
1066+ " return s+'s';"
1067+ "}"
1068+
1069+ "function setTheme(t){"
1070+ " document.body.className='theme-'+t;"
1071+ " try{localStorage.setItem('sx_sessionstats_theme',t);}catch(e){}"
1072+ "}"
1073+ "document.getElementById('btnTheme').onclick=function(){"
1074+ " setTheme(document.body.classList.contains('theme-light')?'dark':'light');"
1075+ "};"
1076+ "(function(){var t='';try{t=localStorage.getItem('sx_sessionstats_theme')||'';}catch(e){}"
1077+ " if(!t)t=window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches?'light':'dark';"
1078+ " setTheme(t);})();"
1079+
1080+ "function bars(el,arr,key){"
1081+ " if(!arr||!arr.length){el.innerHTML='<div class=\"empty\">No data</div>';return;}"
1082+ " var max=0,i;"
1083+ " for(i=0;i<arr.length;i++)if(arr[i].active_sec>max)max=arr[i].active_sec;"
1084+ " if(max<=0)max=1;"
1085+ " var out='';"
1086+ " for(i=0;i<arr.length;i++){"
1087+ " var r=arr[i],w=Math.max(1,Math.round(100*r.active_sec/max));"
1088+ " out+='<div class=\"row\"><span class=\"nm\" title=\"'+esc(r[key])+'\">'+esc(r[key])+'</span>'"
1089+ " +'<span class=\"track\"><span class=\"fill\" style=\"width:'+w+'%\"></span></span>'"
1090+ " +'<span class=\"val\">'+fmt(r.active_sec)+'</span></div>';"
1091+ " }"
1092+ " el.innerHTML=out;"
1093+ "}"
1094+
1095+ "function rows(){"
1096+ " var a=(DATA&&DATA.sessions)||[];"
1097+ " a=a.slice();"
1098+ " var cmp={"
1099+ " recent:function(x,y){return (y.last_epoch||0)-(x.last_epoch||0);},"
1100+ " active:function(x,y){return (y.active_sec||0)-(x.active_sec||0);},"
1101+ " turns:function(x,y){return (y.turns||0)-(x.turns||0);},"
1102+ " duty:function(x,y){return (y.duty_cycle_pct||0)-(x.duty_cycle_pct||0);}"
1103+ " }[SORT];"
1104+ " a.sort(cmp);"
1105+ " return a;"
1106+ "}"
1107+
1108+ "function render(){"
1109+ " if(!DATA)return;"
1110+ " var d=DATA,s=d.sessions||[];"
1111+ " document.getElementById('kSessions').textContent=d.count;"
1112+ " document.getElementById('kSessionsSub').textContent=(d.active_now||0)+' active now';"
1113+ " document.getElementById('kTotal').textContent=fmt(d.total_sec);"
1114+ " document.getElementById('kTotal').className='v';"
1115+ " document.getElementById('kActive').textContent=fmt(d.active_sec);"
1116+ " document.getElementById('kActiveSub').textContent=fmt(d.idle_sec)+' idle';"
1117+ " document.getElementById('kDuty').textContent=(d.duty_cycle_pct||0).toFixed(1)+'%';"
1118+ " document.getElementById('kDutySub').textContent=(d.tool_events||0)+' tool calls';"
1119+ " document.getElementById('kTurns').textContent=d.turns;"
1120+ " document.getElementById('kTurnsSub').textContent="
1121+ " d.turns>0?((d.active_sec/d.turns).toFixed(1)+'s per turn'):'-';"
1122+ " var pct=d.total_sec>0?(100*d.active_sec/d.total_sec):0;"
1123+ " document.getElementById('railOn').style.width=Math.max(0,Math.min(100,pct))+'%';"
1124+ " document.getElementById('railText').textContent="
1125+ " fmt(d.active_sec)+' active of '+fmt(d.total_sec);"
1126+ " bars(document.getElementById('profBars'),d.profiles,'profile');"
1127+ " bars(document.getElementById('modelBars'),d.models,'model');"
1128+
1129+ " var list=rows(),html='',i;"
1130+ " for(i=0;i<list.length;i++){"
1131+ " var x=list[i];"
1132+ " var tag=x.is_active?'<span class=\"tag on\">live</span>':'<span class=\"tag\">idle</span>';"
1133+ " html+='<tr data-dir=\"'+esc(x.dir)+'\" class=\"'+(x.dir===sel?'sel':'')+'\">'"
1134+ " +'<td><div class=\"mono\">'+esc(x.id)+'</div>"
1135+ " <div class=\"sub\">'+esc(x.start_time||'')+' '+tag+'</div></td>'"
1136+ " +'<td><div>'+esc(x.profile||'-')+'</div>"
1137+ " <div class=\"sub mono\">'+esc(x.model||'-')+'</div></td>'"
1138+ " +'<td class=\"nowrap\">'+esc(x.active_fmt)+'</td>'"
1139+ " +'<td class=\"nowrap\">'+esc(x.total_fmt)+'</td>'"
1140+ " +'<td class=\"nowrap\">'+(x.duty_cycle_pct||0).toFixed(0)+'%</td>'"
1141+ " +'<td class=\"nowrap\">'+x.turns+'</td></tr>';"
1142+ " }"
1143+ " document.getElementById('tbody').innerHTML=html;"
1144+ " document.getElementById('tblEmpty').style.display=list.length?'none':'block';"
1145+ " var trs=document.querySelectorAll('#tbody tr');"
1146+ " for(i=0;i<trs.length;i++){"
1147+ " trs[i].onclick=function(){ select(this.getAttribute('data-dir')); };"
1148+ " }"
1149+ " if(!d.root_found){"
1150+ " document.getElementById('err').textContent="
1151+ " 'Sessions root not found: '+d.sessions_root;"
1152+ " } else { document.getElementById('err').textContent=''; }"
1153+ "}"
1154+
1155+ "function select(dir){"
1156+ " sel=dir;"
1157+ " render();"
1158+ " var el=document.getElementById('detail');"
1159+ " el.innerHTML='<div class=\"empty\">Loading...</div>';"
1160+ " api(url('session','sid='+encodeURIComponent(dir))).then(function(r){"
1161+ " if(!r.ok||!r.session){el.innerHTML='<div class=\"empty\">Session not found</div>';return;}"
1162+ " var s=r.session;"
1163+ " var t='<div class=\"mono\">'+esc(s.id)+'</div>';"
1164+ " t+='<div class=\"sub\">'+esc(s.profile||'-')+' / '+esc(s.model||'-')"
1165+ " +' / '+esc(s.branch||'-')+'</div>';"
1166+ " t+='<div class=\"sub mono\" style=\"word-break:break-all\">'+esc(s.cwd||'')+'</div>';"
1167+ " t+='<div style=\"margin-top:8px\">'+esc(s.active_fmt)+' active, '"
1168+ " +esc(s.idle_fmt)+' idle, duty '+(s.duty_cycle_pct||0).toFixed(1)+'% over '"
1169+ " +s.turns+' turns</div>';"
1170+ " if(s.tools&&s.tools.length){"
1171+ " t+='<div style=\"margin-top:8px\">';"
1172+ " for(var i=0;i<s.tools.length;i++){"
1173+ " t+='<span class=\"tag\" style=\"margin:0 4px 4px 0\">'+esc(s.tools[i].name)"
1174+ " +' x'+s.tools[i].calls+'</span>';"
1175+ " }"
1176+ " t+='</div>';"
1177+ " } else { t+='<div class=\"sub\">No tool calls recorded</div>'; }"
1178+ " el.innerHTML=t;"
1179+ " }).catch(function(e){ el.innerHTML='<div class=\"empty err\">'+esc(e.message)+'</div>'; });"
1180+ "}"
1181+
1182+ "document.getElementById('sortSel').onchange=function(){SORT=this.value;render();};"
1183+ "document.getElementById('btnReload').onclick=function(){load();};"
1184+ "function load(){"
1185+ " var pill=document.getElementById('livePill');"
1186+ " api(url('summary')).then(function(d){"
1187+ " DATA=d;"
1188+ " pill.textContent=(d.active_now>0?'live':'idle');"
1189+ " pill.className='pill'+(d.active_now>0?' on':'');"
1190+ " render();"
1191+ " if(sel)select(sel);"
1192+ " }).catch(function(e){"
1193+ " document.getElementById('err').textContent='Failed to load: '+e.message;"
1194+ " });"
1195+ "}"
1196+ "load();"
1197+ "setInterval(load,20000);"
1198+ "</script></body></html>\n", stdout);
1199+}
1200+
1201+/* ------------------------------------------------------------------ */
1202+/* main */
1203+/* ------------------------------------------------------------------ */
1204+
1205+int main(int argc, char **argv)
1206+{
1207+ static session_t buf[MAX_SESSIONS];
1208+ static char names_big[1024][NAME_SZ];
1209+ summary_t sum;
1210+ char root[PATH_SZ] = {0};
1211+ char action[32] = {0};
1212+ char sid[NAME_SZ] = {0};
1213+ const char *qs;
1214+ int n, i;
1215+ int root_ok;
1216+
1217+ if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) {
1218+ puts("{\"name\":\"sessions\",\"desc\":\"Turn metrics\"}");
1219+ return 0;
1220+ }
1221+
1222+ require_node_auth();
1223+
1224+ qs = getenv("QUERY_STRING");
1225+ if (!qs) qs = "";
1226+ get_query_val(qs, "action", action, sizeof action);
1227+ get_query_val(qs, "sid", sid, sizeof sid);
1228+ if (!sid[0]) get_query_val(qs, "id", sid, sizeof sid);
1229+
1230+ root_ok = resolve_sessions_root(root, sizeof root);
1231+
1232+ /* ---------------- JSON modes ---------------- */
1233+ {
1234+ char fmt[16] = {0};
1235+ int have_action = action[0] != '\0';
1236+ int have_format = get_query_val(qs, "format", fmt, sizeof fmt);
1237+
1238+ if (have_action || have_format) {
1239+ n = root_ok ? scan_sessions(root, buf, MAX_SESSIONS) : 0;
1240+ (void)names_big;
1241+
1242+ if (have_action && strcmp(action, "session") == 0) {
1243+ session_t one;
1244+ int found = 0;
1245+ for (i = 0; i < n; i++) {
1246+ if (strcmp(buf[i].id, sid) == 0 || strcmp(buf[i].session_id, sid) == 0) {
1247+ found = 1;
1248+ break;
1249+ }
1250+ }
1251+ if (found) {
1252+ one = buf[i];
1253+ sort_tools(&one);
1254+ print_session_json(&one, root);
1255+ } else if (sid[0]) {
1256+ /* Allow inspecting a session older than the scan window. */
1257+ if (load_session(root, sid, &one)) {
1258+ sort_tools(&one);
1259+ print_session_json(&one, root);
1260+ } else {
1261+ json_header();
1262+ printf("{\"ok\":false,\"error\":\"session not found\",\"sid\":");
1263+ json_str(sid);
1264+ printf(",\"sessions_root\":");
1265+ json_str(root);
1266+ printf("}\n");
1267+ }
1268+ } else {
1269+ json_header();
1270+ printf("{\"ok\":false,\"error\":\"missing sid parameter\",\"sessions_root\":");
1271+ json_str(root);
1272+ printf("}\n");
1273+ }
1274+ return 0;
1275+ }
1276+
1277+ qsort(buf, (size_t)n, sizeof buf[0], cmp_session_desc);
1278+ build_summary(&sum, buf, n);
1279+ str_copy(sum.root, sizeof sum.root, root);
1280+ sum.root_ok = root_ok;
1281+ print_summary_json(&sum);
1282+ return 0;
1283+ }
1284+ }
1285+
1286+ /* ---------------- HTML ---------------- */
1287+ {
1288+ int embed = 0;
1289+ char ev[16] = {0};
1290+ if (get_query_val(qs, "embed", ev, sizeof ev)) {
1291+ if (!strcmp(ev, "1") || !strcmp(ev, "true")) embed = 1;
1292+ }
1293+ html_head(embed, sid);
1294+ html_script(sid);
1295+ }
1296+ return 0;
1297+}
tests/run.sh+350−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..6a2289findex 0000000..6a2289f
--- /dev/null--- /dev/null
+++ b/tests/run.sh+++ b/tests/run.sh
@@ -0,0 +1,350 @@@@ -0,0 +1,350 @@
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+
12+set -u
13+
14+ROOT=$(cd "$(dirname "$0")/.." && pwd)
15+BIN=${1:-"$ROOT/plugin_sessionstats"}
16+[ -x "$BIN" ] || { echo "binary not built: $BIN" >&2; exit 1; }
17+
18+TMP=$(mktemp -d "${TMPDIR:-/tmp}/sx_sessionstats_XXXXXX")
19+trap 'rm -rf "$TMP"' EXIT
20+
21+PASS=0
22+FAIL=0
23+ok() { PASS=$((PASS+1)); }
24+bad() { FAIL=$((FAIL+1)); printf ' FAIL %s\n' "$1"; }
25+check() { # check <label> <actual> <expected>
26+ if [ "$2" = "$3" ]; then ok; else bad "$1 (got '$2', want '$3')"; fi
27+}
28+
29+# ---------------------------------------------------------------- fixtures
30+S="$TMP/sessions"
31+mkdir -p "$S/s1" "$S/s2" "$S/s3"
32+
33+# --- s1: two complete runs, three tool kinds, a profile and a model
34+cat > "$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+}
45+EOF
46+cat > "$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+}
55+EOF
56+cat > "$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"}
68+EOF
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
73+cat > "$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+}
82+EOF
83+cat > "$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}
89+EOF
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)
94+cat > "$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+}
100+EOF
101+
102+run() { # 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+
107+jsoncheck() { # jsoncheck <label> <json-file> <python-expression on d> <expected>
108+ label="$1"; file="$2"; expr="$3"; want="$4"
109+ got=$(python3 - "$file" "$expr" <<'PY'
110+import json, sys
111+d = json.load(open(sys.argv[1]))
112+try:
113+ v = eval(sys.argv[2], {"d": d, "len": len, "sum": sum, "sorted": sorted})
114+except Exception as e:
115+ v = "ERR:%s" % e
116+print(v)
117+PY
118+)
119+ check "$label" "$got" "$want"
120+}
121+
122+echo "== meta mode"
123+out=$("$BIN" --meta)
124+check "--meta exact JSON" "$out" '{"name":"sessions","desc":"Turn metrics"}'
125+out=$(SX_PLUGIN_META=1 "$BIN")
126+check "SX_PLUGIN_META=1 exact JSON" "$out" '{"name":"sessions","desc":"Turn metrics"}'
127+check "meta name is other field free" "$(printf '%s' "$out" | python3 -c 'import json,sys;d=json.load(sys.stdin);print(len(d))')" "2"
128+check "meta name length <= 2 words" "$(printf '%s' "$out" | python3 -c 'import json,sys;print(len(json.load(sys.stdin)["name"].split()))')" "1"
129+check "meta desc length <= 15" "$(printf '%s' "$out" | python3 -c 'import json,sys;print(len(json.load(sys.stdin)["desc"])<=15)')" "True"
130+
131+echo "== auth gate"
132+code=$(BOT_PASSWORD=pw SX_SESSIONS_DIR="$S" QUERY_STRING=action=summary "$BIN" | head -1 | tr -d '\r')
133+check "401 without credential" "$code" "Status: 401 Unauthorized"
134+code=$(BOT_PASSWORD=pw HTTP_X_BOT_PASSWORD=pw SX_SESSIONS_DIR="$S" QUERY_STRING=action=summary "$BIN" | head -1 | cut -c1-12)
135+check "header credential accepted" "$code" "Content-Type"
136+code=$(BOT_PASSWORD=pw HTTP_AUTHORIZATION="Bearer pw" SX_SESSIONS_DIR="$S" QUERY_STRING=action=summary "$BIN" | head -1 | cut -c1-12)
137+check "bearer credential accepted" "$code" "Content-Type"
138+code=$(BOT_PASSWORD=pw SX_SESSIONS_DIR="$S" QUERY_STRING='action=summary&pwd=pw' "$BIN" | head -1 | cut -c1-12)
139+check "query credential accepted" "$code" "Content-Type"
140+code=$(BOT_PASSWORD=pw SX_SESSIONS_DIR="$S" "$BIN" --meta | cut -c1-10)
141+check "--meta stays unauthenticated" "$code" '{"name":"s'
142+code=$(BOT_PASSWORD=pw SX_SESSIONS_DIR="$S" QUERY_STRING=action=summary "$BIN" | tail -1)
143+check "401 body is JSON error" "$code" '{"ok":false,"error":"invalid node password"}'
144+
145+echo "== summary shape"
146+run 'action=summary' > "$TMP/sum.json"
147+last=$(tail -1 "$TMP/sum.json")
148+check "summary has no Content-Length" "$(printf '%s' "$last" | grep -c 'Content-Length')" "0"
149+printf '%s' "$last" > "$TMP/sum.body.json"
150+jsoncheck "ok" "$TMP/sum.body.json" 'd["ok"]' "True"
151+jsoncheck "plugin id" "$TMP/sum.body.json" 'd["plugin"]' "plugin_sessionstats"
152+jsoncheck "version" "$TMP/sum.body.json" 'd["version"]' "1.0.0"
153+jsoncheck "root_found" "$TMP/sum.body.json" 'd["root_found"]' "True"
154+jsoncheck "session count" "$TMP/sum.body.json" 'd["count"]' "3"
155+jsoncheck "active_now" "$TMP/sum.body.json" 'd["active_now"]' "1"
156+jsoncheck "turns total" "$TMP/sum.body.json" 'd["turns"]' "3"
157+jsoncheck "tool events" "$TMP/sum.body.json" 'd["tool_events"]' "5"
158+jsoncheck "total sec" "$TMP/sum.body.json" 'd["total_sec"]' "410"
159+jsoncheck "active sec" "$TMP/sum.body.json" 'd["active_sec"]' "130"
160+jsoncheck "idle sec" "$TMP/sum.body.json" 'd["idle_sec"]' "280"
161+jsoncheck "idle+active=total" "$TMP/sum.body.json" 'd["idle_sec"]+d["active_sec"]==d["total_sec"]' "True"
162+jsoncheck "duty pct" "$TMP/sum.body.json" 'round(d["duty_cycle_pct"],2)' "31.71"
163+jsoncheck "total_fmt" "$TMP/sum.body.json" 'd["total_fmt"]' "06m 50s"
164+jsoncheck "active_fmt" "$TMP/sum.body.json" 'd["active_fmt"]' "02m 10s"
165+jsoncheck "idle_fmt" "$TMP/sum.body.json" 'd["idle_fmt"]' "04m 40s"
166+jsoncheck "sessions array length" "$TMP/sum.body.json" 'len(d["sessions"])' "3"
167+jsoncheck "profiles present" "$TMP/sum.body.json" 'len(d["profiles"])' "3"
168+jsoncheck "models present" "$TMP/sum.body.json" 'len(d["models"])' "3"
169+jsoncheck "profile alpha leads" "$TMP/sum.body.json" 'd["profiles"][0]["profile"]' "profile-alpha"
170+jsoncheck "profile alpha active" "$TMP/sum.body.json" 'd["profiles"][0]["active_sec"]' "70"
171+jsoncheck "profile beta active" "$TMP/sum.body.json" 'd["profiles"][1]["active_sec"]' "60"
172+jsoncheck "profile alpha sessions" "$TMP/sum.body.json" 'd["profiles"][0]["sessions"]' "1"
173+jsoncheck "unknown profile bucket" "$TMP/sum.body.json" 'd["profiles"][2]["profile"]' "unknown"
174+jsoncheck "model alpha leads" "$TMP/sum.body.json" 'd["models"][0]["model"]' "alpha-1"
175+
176+echo "== summary is sorted newest first"
177+jsoncheck "first session is s2" "$TMP/sum.body.json" 'd["sessions"][0]["id"]' "2026_01_02_bold_lovelace"
178+jsoncheck "second session is s1" "$TMP/sum.body.json" 'd["sessions"][1]["id"]' "2026_01_01_quiet_curie"
179+
180+echo "== per-session numbers (s1)"
181+cat > "$TMP/py_s1.py" <<'PY'
182+import json,sys
183+d=json.load(open(sys.argv[1]))
184+for 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"])
190+PY
191+got=$(python3 "$TMP/py_s1.py" "$TMP/sum.body.json")
192+check "s1 numbers" "$got" "340 70 270 2 20.59 alpha-1 profile-alpha main 1000 250 800 50"
193+
194+cat > "$TMP/py_s1tools.py" <<'PY'
195+import json,sys
196+d=json.load(open(sys.argv[1]))
197+for s in d["sessions"]:
198+ if s["dir"]=="s1":
199+ print(" ".join("%s=%d"%(t["name"],t["calls"]) for t in s["tools"]))
200+PY
201+got=$(python3 "$TMP/py_s1tools.py" "$TMP/sum.body.json")
202+check "s1 tools sorted by calls" "$got" "Bash=2 Read=1 Write=1"
203+
204+cat > "$TMP/py_s1id.py" <<'PY'
205+import json,sys
206+d=json.load(open(sys.argv[1]))
207+for s in d["sessions"]:
208+ if s["dir"]=="s1":
209+ print(s["id"], s["start_time"], s["is_active"], s["avg_turn_sec"])
210+PY
211+got=$(python3 "$TMP/py_s1id.py" "$TMP/sum.body.json")
212+check "s1 identity fields" "$got" "2026_01_01_quiet_curie 2026-01-01 10:00:00 False 35.0"
213+
214+echo "== per-session numbers (s2, still running)"
215+cat > "$TMP/py_s2.py" <<'PY'
216+import json,sys
217+d=json.load(open(sys.argv[1]))
218+for 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"])
221+PY
222+got=$(python3 "$TMP/py_s2.py" "$TMP/sum.body.json")
223+check "s2 numbers" "$got" "70 60 10 1 True"
224+
225+echo "== degenerate session (metadata only)"
226+cat > "$TMP/py_s3.py" <<'PY'
227+import json,sys
228+d=json.load(open(sys.argv[1]))
229+for s in d["sessions"]:
230+ if s["dir"]=="s3":
231+ print(s["total_sec"], s["active_sec"], s["turns"], s["is_active"])
232+PY
233+got=$(python3 "$TMP/py_s3.py" "$TMP/sum.body.json")
234+check "s3 numbers" "$got" "0 0 0 False"
235+
236+echo "== action=session"
237+run 'action=session&sid=s1' | tail -1 > "$TMP/one.json"
238+jsoncheck "session ok" "$TMP/one.json" 'd["ok"]' "True"
239+jsoncheck "session id" "$TMP/one.json" 'd["session"]["id"]' "2026_01_01_quiet_curie"
240+jsoncheck "session active" "$TMP/one.json" 'd["session"]["active_sec"]' "70"
241+jsoncheck "session tools" "$TMP/one.json" 'len(d["session"]["tools"])' "3"
242+jsoncheck "session summary block" "$TMP/one.json" 'd["summary"]["turns"]' "2"
243+run 'action=session&sid=2026_01_02_bold_lovelace' | tail -1 > "$TMP/one2.json"
244+jsoncheck "session by full id" "$TMP/one2.json" 'd["session"]["dir"]' "s2"
245+run 'action=session&sid=nope' | tail -1 > "$TMP/one3.json"
246+jsoncheck "unknown session ok=false" "$TMP/one3.json" 'd["ok"]' "False"
247+jsoncheck "unknown session error" "$TMP/one3.json" 'd["error"]' "session not found"
248+run 'action=session' | tail -1 > "$TMP/one4.json"
249+jsoncheck "missing sid error" "$TMP/one4.json" 'd["error"]' "missing sid parameter"
250+run 'action=session&id=s1' | tail -1 > "$TMP/one5.json"
251+jsoncheck "id= alias accepted" "$TMP/one5.json" 'd["session"]["dir"]' "s1"
252+run 'action=session&sid=%73%31' | tail -1 > "$TMP/one6.json"
253+jsoncheck "percent-decoded sid" "$TMP/one6.json" 'd["session"]["dir"]' "s1"
254+
255+echo "== format=json"
256+run 'format=json' | tail -1 > "$TMP/fmt.json"
257+jsoncheck "format=json returns summary" "$TMP/fmt.json" 'd["count"]' "3"
258+jsoncheck "format=json ok" "$TMP/fmt.json" 'd["ok"]' "True"
259+
260+echo "== unknown action falls back to the summary"
261+run 'action=whatever' | tail -1 > "$TMP/unk.json"
262+jsoncheck "unknown action still JSON" "$TMP/unk.json" 'd["ok"]' "True"
263+
264+echo "== html"
265+run 'embed=1' > "$TMP/html.txt"
266+head -1 "$TMP/html.txt" | grep -q 'Content-Type: text/html' && ok || bad "html content type"
267+grep -q '<!DOCTYPE html>' "$TMP/html.txt" && ok || bad "html doctype"
268+grep -q 'Session Analytics' "$TMP/html.txt" && ok || bad "html title"
269+grep -q "id='kSessions'" "$TMP/html.txt" && ok || bad "kpi card sessions"
270+grep -q "id='railOn'" "$TMP/html.txt" && ok || bad "active rail"
271+grep -q "id='profBars'" "$TMP/html.txt" && ok || bad "profile bars"
272+grep -q "id='modelBars'" "$TMP/html.txt" && ok || bad "model bars"
273+grep -q "id='tbody'" "$TMP/html.txt" && ok || bad "session table"
274+grep -q "btnTheme" "$TMP/html.txt" && ok || bad "theme toggle"
275+grep -q "prefers-color-scheme" "$TMP/html.txt" && ok || bad "dark/light support"
276+grep -q "max-width:400px" "$TMP/html.txt" && ok || bad "narrow breakpoint"
277+grep -q "plugin_sessionstats?action=" "$TMP/html.txt" && ok || bad "direct plugin route"
278+grep -q "plugins?plugin=" "$TMP/html.txt" && ok || bad "hub proxy route"
279+grep -q "bot_active_pwd" "$TMP/html.txt" && ok || bad "pwd bootstrap"
280+grep -q "X-Bot-Password" "$TMP/html.txt" && ok || bad "pwd header"
281+grep -qi 'content-length' "$TMP/html.txt" && bad "html must not emit Content-Length" || ok
282+
283+echo "== initial id is injected and escaped"
284+run 'id=s1' > "$TMP/html2.txt"
285+grep -q "q.get('id')||'s1'" "$TMP/html2.txt" && ok || bad "initial id injected"
286+mkdir -p "$S/bad'name"
287+run "id=x%27y" > "$TMP/html3.txt"
288+grep -q "q.get('id')||'x\\\\'y'" "$TMP/html3.txt" && ok || bad "single quote escaped in initial id"
289+rm -rf "$S/bad'name"
290+
291+echo "== missing sessions root"
292+out=$(SX_SESSIONS_DIR="$TMP/does-not-exist" QUERY_STRING='action=summary' "$BIN" | tail -1)
293+printf '%s' "$out" > "$TMP/noroot.json"
294+jsoncheck "root_found false" "$TMP/noroot.json" 'd["root_found"]' "False"
295+jsoncheck "empty summary ok" "$TMP/noroot.json" 'd["ok"]' "True"
296+jsoncheck "zero sessions" "$TMP/noroot.json" 'd["count"]' "0"
297+jsoncheck "empty profiles" "$TMP/noroot.json" 'd["profiles"]' "[]"
298+
299+echo "== the root must be a directory, not any openable path"
300+: > "$TMP/notadir"
301+out=$(SX_SESSIONS_DIR="$TMP/notadir" QUERY_STRING='action=summary' "$BIN" | tail -1)
302+printf '%s' "$out" > "$TMP/notadir.json"
303+jsoncheck "file root rejected" "$TMP/notadir.json" 'd["root_found"]' "False"
304+
305+echo "== read-only guarantee"
306+before=$(find "$S" -type f | wc -l | tr -d ' ')
307+run 'action=summary' >/dev/null
308+run 'action=session&sid=s1' >/dev/null
309+run 'embed=1' >/dev/null
310+after=$(find "$S" -type f | wc -l | tr -d ' ')
311+check "no files created" "$after" "$before"
312+diff -r "$S" "$S" >/dev/null 2>&1 && ok || bad "fixture tree unchanged"
313+
314+echo "== no emoji anywhere in the source"
315+if grep -qP '[\x{1F300}-\x{1FAFF}\x{2600}-\x{27BF}]' "$ROOT/src/plugin_sessionstats.c" 2>/dev/null; then
316+ bad "source contains emoji"
317+else
318+ ok
319+fi
320+
321+echo "== no private addresses or credentials in the whole history"
322+HIST="$TMP/history.txt"
323+git -C "$ROOT" log -p --all 2>/dev/null \
324+ | grep -v '^Author: ' \
325+ | grep -vE 'scan "|audit "|HITS=|grep -E|P_ROOT=|P_WT=|PK="' > "$HIST" || : > "$HIST"
326+check "no 192.168 in history" "$(grep -Eco '192\.168\.[0-9]+\.[0-9]+' "$HIST" || true)" "0"
327+check "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"
328+check "no 172.16-31 range" "$(grep -Eco '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+' "$HIST" || true)" "0"
329+check "no ghp_ token" "$(grep -Eco 'ghp_[A-Za-z0-9]{20,}' "$HIST" || true)" "0"
330+check "no hf_ token" "$(grep -Eco 'hf_[A-Za-z0-9]{20,}' "$HIST" || true)" "0"
331+check "no internal hostnames" "$(grep -Eco 'INTERNAL_HOST_A|INTERNAL_HOST_B|INTERNAL_HOST_C' "$HIST" || true)" "0"
332+check "no default password" "$(grep -Eco 'Xboxone'09'0'9'|TESTPW' "$HIST" || true)" "0"
333+
334+echo "== Windows artifact shape (when the cross build exists)"
335+if [ -f "$ROOT/plugin_sessionstats.exe" ]; then
336+ check "windows artifact starts with MZ" "$(head -c 2 "$ROOT/plugin_sessionstats.exe")" "MZ"
337+else
338+ echo " skip (plugin_sessionstats.exe not built)"
339+fi
340+
341+echo "== musl artifact shape (when the static build exists)"
342+if [ -f "$ROOT/plugin_sessionstats.musl" ]; then
343+ check "musl artifact is a static ELF" "$(head -c 4 "$ROOT/plugin_sessionstats.musl" | od -An -c | tr -d ' \n')" '177ELF'
344+else
345+ echo " skip (plugin_sessionstats.musl not built)"
346+fi
347+
348+echo
349+printf ' %d passed, %d failed\n' "$PASS" "$FAIL"
350+[ "$FAIL" -eq 0 ] || exit 1
0351