feat(gitstat): clean-room local git repository status board plugin
Single zero-dependency C99 binary (plugin_gitstat) that walks an allowlisted set of roots and reports, for every working tree it finds: branch, uncommitted file count, ahead/behind against the upstream, stash depth, detached / no-upstream / unborn state and the last commit. Sorted dirty-first. Every git query is argv-only (execvp / CreateProcessA - no shell anywhere): status --porcelain=v2 --branch, log -1, stash list. Reading is the default; git fetch --prune is the single write-ish action and it stays off until the node operator sets GITSTAT_ALLOW_FETCH=1, with a 30 s cap, GIT_TERMINAL_PROMPT=0 and an empty GIT_ASKPASS so a dead remote can never hang the node. Remote URLs are stripped of userinfo, so an origin carrying user:token@ shows as the bare host. Discovery is depth-limited to 4 with a per-root entry budget, and the detail/fetch actions re-canonicalise the requested path and refuse anything outside an allowlisted root. UI is the bot's own theme (prepaint + handoff, tokens only), dark and light, fluid at 1440/1024/390 and inside the Chat floating window, filter chips, search, detail drawer with changed files and recent commits, inline SVG only.
AuthorPico <picobot@scorpioplayer.com>
Date2026-11-12 09:40:49
Commit8a37d0bd
Changed files
.gitignore+11−0■■■■■
LICENSE+21−0■■■■■
Makefile+62−0■■■■■
README.md+144−0■■■■■
build.ps1+51−0■■■■■
plugin.json+16−0■■■■■
release-dist.sh+365−0■■■■■
src/bot_theme_plugin.h+129−0■■■■■
src/plugin_gitstat.c+1477−0■■■■■
src/ui.html+470−0■■■■■
src/ui_html.h+478−0■■■■■
tests/e2e.py+332−0■■■■■
tests/run.sh+541−0■■■■■
tools/gen_ui.py+105−0■■■■■
20 files+4202−0
Diff
.gitignore+11−0■■■■■
11new file mode 100644
index 0000000..d1b0223
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,11 @@
1+/plugin_gitstat
2+/plugin_gitstat.musl
3+/plugin_gitstat.arm64
4+/plugin_gitstat.exe
5+/plugin_gitstat.macos-arm64
6+/plugin_gitstat.macos-x86_64
7+*.o
8+*.tmp
9+*.dSYM
10+__pycache__/
11+*.pyc
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..2574a24
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,62 @@
1+# plugin_gitstat - SCORPIOX BOT open-source local git repository status board
2+#
3+# Targets:
4+# make native build -> ./plugin_gitstat
5+# make musl static musl x86_64 -> ./plugin_gitstat.musl
6+# make arm64 static aarch64 -> ./plugin_gitstat.arm64
7+# make win64 MinGW-w64 static -> ./plugin_gitstat.exe
8+# make macos Apple clang -> ./plugin_gitstat (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+ARM64_CC ?= aarch64-linux-gnu-gcc
17+ARM64_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_gitstat.c
21+HDRS := src/bot_theme_plugin.h src/ui_html.h
22+BIN := plugin_gitstat
23+EXE := plugin_gitstat.exe
24+
25+.PHONY: all native ui musl arm64 win64 macos test clean help
26+
27+all: native
28+
29+native: $(BIN)
30+
31+ui: src/ui.html tools/gen_ui.py
32+ @python3 tools/gen_ui.py
33+
34+$(BIN): $(SRC) $(HDRS)
35+ @echo "==> native build ($(CC))"
36+ $(CC) $(CFLAGS) -I src -o $(BIN) $(SRC)
37+
38+musl: $(SRC) $(HDRS)
39+ @echo "==> static musl build ($(MUSL_CC))"
40+ $(MUSL_CC) $(MUSL_CFLAGS) -I src -o $(BIN).musl $(SRC)
41+
42+arm64: $(SRC) $(HDRS)
43+ @echo "==> static arm64 build ($(ARM64_CC))"
44+ $(ARM64_CC) $(ARM64_CFLAGS) -I src -o $(BIN).arm64 $(SRC)
45+
46+win64: $(SRC) $(HDRS)
47+ @echo "==> MinGW-w64 build ($(WIN_CC))"
48+ $(WIN_CC) $(WIN_CFLAGS) -I src -o $(EXE) $(SRC)
49+
50+macos: $(SRC) $(HDRS)
51+ @echo "==> Apple clang build"
52+ $(CC) $(CFLAGS) -I src -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+144−0■■■■■
11new file mode 100644
index 0000000..a508542
--- /dev/null
+++ b/README.md
@@ -0,0 +1,144 @@
1+# gitstat — a git repository status board for SCORPIOX BOT
2+
3+`plugin_gitstat` is a single zero-dependency C99 binary that answers one question
4+about a machine: **which of my repositories have uncommitted work, and how far
5+are they from their upstream?**
6+
7+It walks a fixed set of allowlisted roots, finds every working tree with a `.git`
8+entry, and asks git itself — `status --porcelain=v2 --branch`, `log -1`,
9+`stash list` — through argv-only child processes. No shell, no `popen`, no
10+parsing of `.git/index` by hand.
11+
12+![1440 dark](docs/ui-1440-dark.png)
13+
14+| 1440 light | 1024 dark |
15+|---|---|
16+| ![1440 light](docs/ui-1440-light.png) | ![1024 dark](docs/ui-1024-dark.png) |
17+
18+| 390 dark | 390 light |
19+|---|---|
20+| ![390 dark](docs/ui-390-dark.png) | ![390 light](docs/ui-390-light.png) |
21+
22+## Modes
23+
24+| Invocation | Output |
25+|---|---|
26+| `plugin_gitstat --meta` (or `SX_PLUGIN_META=1`) | `{"name":"git","desc":"Repo status"}` — unauthenticated, so discovery works |
27+| `GET ?action=repos` | Every repository found, plus per-root counts and a summary |
28+| `GET ?action=repo&path=<abs>` | One repository: 500 changed files max, 20 recent commits |
29+| `POST ?action=fetch&path=<abs>` | `git fetch --prune`, 30 s timeout, only when `GITSTAT_ALLOW_FETCH=1` |
30+| `GET` (default) | The responsive HTML board |
31+
32+Every action except `--meta` sits behind `require_node_auth()`: `X-Bot-Password`,
33+`Authorization: Bearer`, or `?pwd=`, and it is a no-op only when `BOT_PASSWORD`
34+is unset.
35+
36+## Roots
37+
38+| Platform | Defaults |
39+|---|---|
40+| Linux | `/workspace`, `/codebases`, `$HOME`, plus `GITSTAT_ROOTS` (`:`-separated) |
41+| macOS | same |
42+| Windows | `%USERPROFILE%`, `D:\codebases` and `C:\codebases` when present, plus `GITSTAT_ROOTS` (`;`-separated) |
43+
44+Two environment knobs:
45+
46+- `GITSTAT_ONLY_ROOTS=1` makes `GITSTAT_ROOTS` the complete list instead of an
47+ addition. Useful on a node that wants an explicit allowlist, and it is what the
48+ test suite uses so a developer machine full of checkouts cannot change the
49+ result.
50+- `GITSTAT_ALLOW_FETCH=1` enables the single write-ish action. Without it the
51+ plugin is strictly read-only and `POST ?action=fetch` answers `403`-style
52+ `{"ok":false,...}` explaining the switch.
53+
54+Discovery is depth-limited to 4 and budgeted **per root** (20 000 entries each,
55+1 200 repositories in the table), because one shared budget lets the first root
56+consume the whole walk and the second root report zero.
57+
58+## JSON shape
59+
60+```json
61+{
62+ "ok": true,
63+ "action": "repos",
64+ "count": 4,
65+ "table_capped": false,
66+ "summary": {"dirty": 1, "ahead": 1, "behind": 0, "stashes": 1, "detached": 1},
67+ "checked_at": "2026-11-12T09:31:06Z",
68+ "roots": [{"root": "/codebases", "exists": true, "count": 4, "truncated": false}],
69+ "repos": [{
70+ "path": "/codebases/portal-web",
71+ "name": "portal-web",
72+ "root": "/codebases",
73+ "branch": "main",
74+ "upstream": "origin/main",
75+ "remote": "https://git.example.net/team/portal-web.git",
76+ "ahead": 2, "behind": 0,
77+ "dirty": 3, "untracked": 1, "staged": 1, "conflicted": 0,
78+ "stash": 1,
79+ "detached": false, "no_upstream": false, "unborn": false,
80+ "last_commit": {
81+ "hash": "…", "short": "7746dc67", "ct": 1794475861,
82+ "at": "2026-11-12T09:31:01Z",
83+ "subject": "Cap the retry backoff at thirty seconds"
84+ }
85+ }]
86+}
87+```
88+
89+`?action=repo&path=` adds `changed` (code + path, max 500), `changed_count`,
90+`changed_truncated` and `commits` (max 20). A path is accepted only when it
91+canonicalises to somewhere **under an allowlisted root** and that directory
92+carries a `.git` entry; anything else, including a `..` traversal, is `403`.
93+
94+## Security posture
95+
96+- **No shell anywhere.** Every git invocation is an argv array handed to
97+ `execvp` / `CreateProcessA`. A path with a `;` or a backtick in it is a path,
98+ not a command.
99+- **Read-only by default.** `git fetch --prune` is the only operation that
100+ touches a remote, it needs `GITSTAT_ALLOW_FETCH=1`, and it is capped at 30
101+ seconds. Nothing ever runs `pull`, `checkout`, `reset` or `clean`.
102+- **No credential prompts.** `GIT_TERMINAL_PROMPT=0`, an empty `GIT_ASKPASS`, and
103+ stdin from `/dev/null`, so a repository with a dead remote can never hang the
104+ node behind a password prompt.
105+- **Remote URLs are stripped of userinfo** before they are printed, so an origin
106+ of `https://user:token@host/x.git` shows as `https://host/x.git` in the board,
107+ the JSON and anything a caller pipes it into.
108+- **Allowlisted roots only.** Discovery never leaves them, and the detail and
109+ fetch actions re-check the canonical path on every request.
110+
111+## Build
112+
113+```sh
114+make # native
115+make musl # static musl x86_64 (universal Linux)
116+make arm64 # static aarch64
117+make win64 # MinGW-w64 static PE
118+make macos # Apple clang (run on macOS)
119+make test # build + 110 offline assertions
120+python3 tests/e2e.py # Playwright 1440/1024/390, dark + light
121+make clean
122+```
123+
124+`src/ui.html` is the page; `tools/gen_ui.py` compiles it into `src/ui_html.h`
125+with two control-byte placeholders that the C side expands into the bot's theme
126+macros, so the plugin can never drift away from the bot palette. `make ui`
127+regenerates it, and `python3 tools/gen_ui.py --check` fails when it is stale.
128+
129+## Install
130+
131+Pre-built artifacts for six targets live at
132+`https://dist.scorpiox.net/bot-plugins/gitstat/1.0.0/`. Drop the right one into
133+`~/.scorpiox/plugins/plugin_gitstat` (or `/workspace/.scorpiox/plugins/` on a
134+BotCloud container) — `scorpiox-server` discovers it live, with no restart.
135+
136+Or build it from source, which is the point of the marketplace:
137+
138+> Clone `https://plugingit.scorpiox.net/scorpiox-bot-plugin-gitstat.git`, read
139+> `src/plugin_gitstat.c`, customise the root list for this machine, compile it
140+> with `make`, check `--meta`, and install it to `~/.scorpiox/plugins/`.
141+
142+## License
143+
144+MIT. See [LICENSE](LICENSE).
build.ps1+51−0■■■■■
11new file mode 100644
index 0000000..831a0a1
--- /dev/null
+++ b/build.ps1
@@ -0,0 +1,51 @@
1+# build.ps1 - Windows MinGW-w64 static build for plugin_gitstat
2+#
3+# Usage (from the repo root, PowerShell):
4+# powershell -ExecutionPolicy Bypass -File build.ps1
5+#
6+# Produces .\plugin_gitstat.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_gitstat.c"
14+ $Out = Join-Path $ScriptDir "plugin_gitstat.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+ # Regenerate the page header so the binary always matches src/ui.html.
31+ if (Get-Command python -ErrorAction SilentlyContinue) {
32+ python tools\gen_ui.py
33+ }
34+
35+ Write-Host "==> building plugin_gitstat.exe with $Cc"
36+ & $Cc -O2 -std=c99 -Wall -Wextra -I src -static -o $Out $Src
37+ if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" }
38+
39+ if (-not (Test-Path $Out)) { throw "build produced no output" }
40+
41+ # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not.
42+ $bytes = [System.IO.File]::ReadAllBytes($Out)
43+ if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) {
44+ throw "output is not a PE executable (missing MZ header)"
45+ }
46+
47+ Write-Host "==> ok: $Out ($($bytes.Length) bytes)"
48+ Write-Host " smoke test: .\plugin_gitstat.exe --meta"
49+} finally {
50+ Pop-Location
51+}
docs/ui-1024-dark.png+0−0■
11new file mode 100644
index 0000000..4bf9bb5
binary image
Binary image file
docs/ui-1024-light.png+0−0■
11new file mode 100644
index 0000000..47ab3a8
binary image
Binary image file
docs/ui-1440-dark.png+0−0■
11new file mode 100644
index 0000000..11d5c79
binary image
Binary image file
docs/ui-1440-light.png+0−0■
11new file mode 100644
index 0000000..eed895e
binary image
Binary image file
docs/ui-390-dark.png+0−0■
11new file mode 100644
index 0000000..c285bbd
binary image
Binary image file
docs/ui-390-light.png+0−0■
11new file mode 100644
index 0000000..0e77112
binary image
Binary image file
plugin.json+16−0■■■■■
11new file mode 100644
index 0000000..66e8d21
--- /dev/null
+++ b/plugin.json
@@ -0,0 +1,16 @@
1+{
2+ "slug": "gitstat",
3+ "id": "plugin_gitstat",
4+ "title": "Local Git Repository Status Board",
5+ "summary": "Zero-dependency status board for every git repository under your allowlisted roots: branch, uncommitted file count, ahead/behind against the upstream, stash depth and the last commit, sorted dirty-first. Discovery walks /workspace, /codebases, your home directory and GITSTAT_ROOTS without ever leaving them, and each repository is queried through git's own porcelain v2 output via argv-only child processes — no shell is involved and no remote is ever contacted unless the node operator enables fetching.",
6+ "category": "devtools",
7+ "license": "MIT",
8+ "capabilities": [
9+ "fs_walk",
10+ "git_read",
11+ "git_fetch_optional"
12+ ],
13+ "trust_notice": "Executes native C code on your node. Walks only the allowlisted roots and reads local repositories with git status, git log and git stash list. Any credentials embedded in a remote URL are stripped before they are displayed. Makes zero outbound network requests unless GITSTAT_ALLOW_FETCH=1, in which case a single `git fetch --prune` with a 30 second timeout runs against the repository you asked for.",
14+ "author": "SCORPIOX INC",
15+ "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-gitstat"
16+}
release-dist.sh+365−0■■■■■
11new file mode 100755
index 0000000..23ad0ba
--- /dev/null
+++ b/release-dist.sh
@@ -0,0 +1,365 @@
1+#!/usr/bin/env bash
2+# release-dist.sh - build, scan and publish plugin_gitstat 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="gitstat"
33+ID="plugin_gitstat"
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 (and the
90+# test suite's identical checks) read as findings in every historical revision of
91+# them. A real secret on any other line still hits.
92+git log -p --all 2>/dev/null \
93+ | grep -v '^Author: ' \
94+ | grep -vE "scan \"|audit \"|HITS=|grep -E|grep -qE|hits '|P_ROOT=|P_WT=|PK=\"|\$ALL" \
95+ > "$SCAN_TMP" || : > "$SCAN_TMP"
96+HITS=0
97+scan() { # scan <label> <regex>
98+ local out
99+ out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true)
100+ if [ -n "$out" ]; then
101+ printf ' \033[31mHIT\033[0m %s\n' "$1"
102+ printf '%s\n' "$out" | sed 's/^/ /'
103+ HITS=$((HITS + 1))
104+ else
105+ printf ' ok %s\n' "$1"
106+ fi
107+}
108+scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+'
109+scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
110+scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
111+scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
112+scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}'
113+scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}'
114+scan "hard-coded ssh password" 'sshpass -p [^"$]'
115+P_ROOT="/codebases"
116+P_PICOBOT="${P_ROOT}/pico""bot"
117+P_WT=".work""trees"
118+scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}"
119+scan "run-token env assignment" 'RUNNER_'"PASS="
120+if [ "$HITS" -ne 0 ]; then
121+ die "secret scan found $HITS problem(s) - refusing to publish"
122+fi
123+echo " clean: 0 hits"
124+
125+# ---------------------------------------------------------------- 2. build
126+say "2/7 build targets"
127+
128+# linux-x86_64 (glibc, native)
129+if command -v cc >/dev/null 2>&1; then
130+ cc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src -o "$STAGE/$ID" src/$ID.c || die "native build failed"
131+ echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes"
132+else
133+ die "no native cc found"
134+fi
135+
136+# linux-x86_64-musl (fully static - the universal Linux artifact)
137+if command -v musl-gcc >/dev/null 2>&1; then
138+ musl-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.musl" src/$ID.c \
139+ || die "musl build failed"
140+ echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes"
141+else
142+ echo " skip linux-x86_64-musl (no musl-gcc)"
143+fi
144+
145+# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers)
146+if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
147+ aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.arm64" src/$ID.c \
148+ || die "arm64 build failed"
149+ echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes"
150+else
151+ echo " skip linux-arm64-musl (no aarch64-linux-gnu-gcc)"
152+fi
153+
154+# windows-x86_64 (static PE)
155+if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
156+ x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings \
157+ -I src -o "$STAGE/$ID.exe" src/$ID.c || die "MinGW build failed"
158+ [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE"
159+ echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes"
160+else
161+ echo " skip windows-x86_64 (no MinGW cross compiler)"
162+fi
163+
164+# macOS legs - Mach-O must be produced by Apple clang on a real Mac.
165+# Both slices are cross-built from one host: -arch arm64 and -arch x86_64.
166+if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then
167+ MAC_USER="${MAC_USER:-$(whoami)}"
168+ MAC_DIR="/tmp/${ID}-mac-$$"
169+ echo " building macOS legs on $MAC_HOST"
170+ SSH_MAC=(ssh -o StrictHostKeyChecking=no)
171+ SCP_MAC=(scp -o StrictHostKeyChecking=no)
172+ if [ -n "${MAC_PASS:-}" ]; then
173+ SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}")
174+ SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}")
175+ fi
176+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then
177+ tar -czf "$STAGE/src.tgz" src
178+ if "${SCP_MAC[@]}" "$STAGE/src.tgz" "$MAC_USER@$MAC_HOST:$MAC_DIR/src.tgz" \
179+ && "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "cd '$MAC_DIR' && tar -xzf src.tgz"; then
180+ # Build straight from the uploaded file - no src/ tree on the remote.
181+ for slice in arm64 x86_64; do
182+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \
183+ "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -arch $slice -o $ID.$slice src/$ID.c" \
184+ 2>/dev/null; then
185+ "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \
186+ && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)"
187+ else
188+ echo " warn: macos-$slice build failed on $MAC_HOST"
189+ fi
190+ done
191+ "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" || true
192+ else
193+ echo " warn: could not upload source to $MAC_HOST"
194+ fi
195+ else
196+ echo " warn: cannot reach macOS builder $MAC_HOST"
197+ fi
198+else
199+ echo " skip macOS legs (no MAC_HOST or --no-macos)"
200+fi
201+
202+# ---------------------------------------------------------------- 3. manifest
203+say "3/7 manifest + checksums"
204+
205+git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \
206+ -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \
207+ || tar -czf "$STAGE/source.tar.gz" --exclude=.git .
208+echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes"
209+
210+target_meta() { # target_meta <key> <file> <format> <relpath>
211+ local key="$1" file="$2" fmt="$3" rel="$4"
212+ [ -f "$file" ] || return 0
213+ local sha size
214+ sha=$(sha256sum "$file" | awk '{print $1}')
215+ size=$(wc -c < "$file" | tr -d ' ')
216+ printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \
217+ "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt"
218+}
219+
220+{
221+ printf '{\n'
222+ printf ' "slug": "%s",\n' "$SLUG"
223+ printf ' "id": "%s",\n' "$ID"
224+ printf ' "name": "notes",\n'
225+ printf ' "desc": "Markdown notes",\n'
226+ printf ' "title": "Markdown Notes",\n'
227+ printf ' "summary": "Zero-dependency markdown notes that live on your node: create, edit, rename, search, pin and delete, with a live rendered preview next to the editor. Notes are one <id>.md file each plus index.json inside the plugin directory, every write is staged to a temp file and renamed so a crash never truncates a note, and deleted notes go to a recoverable .trash. Server-side rendering escapes note content first, so a pasted <script> is inert text. No CDN, no network requests, no database.",\n'
228+ printf ' "category": "utilities",\n'
229+ printf ' "version": "%s",\n' "$VERSION"
230+ printf ' "license": "MIT",\n'
231+ printf ' "trust_notice": "Executes native C code on your node. Reads and writes only inside its own notes directory (plugin dir/.notes, or $NOTES_DIR when set): one markdown file per note, an index.json, and a .trash subdirectory. It opens no network connection of any kind and reads nothing outside that directory.",\n'
232+ printf ' "capabilities": ["fs_write_plugin_dir"],\n'
233+ printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG"
234+ printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG"
235+ printf ' "git_commit": "%s",\n' "$COMMIT"
236+ printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
237+ printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')"
238+ printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID"
239+ printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c",\n' "$ID" "$ID"
240+ printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
241+ printf ' "targets": {\n'
242+ first=1
243+ emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; }
244+ emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID"
245+ emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID"
246+ emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID"
247+ emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID"
248+ emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID"
249+ emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe"
250+ printf '\n }\n}\n'
251+} > "$STAGE/manifest.json"
252+
253+python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \
254+ || die "generated manifest.json is not valid JSON"
255+echo " manifest.json ok ($(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["targets"]))' "$STAGE/manifest.json") targets)"
256+
257+# SHA256SUMS - relative paths, exactly as published
258+( cd "$STAGE"
259+ for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done
260+ [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|"
261+ [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|"
262+ [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|"
263+ [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|"
264+ [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|"
265+ [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|"
266+ true ) > "$STAGE/SHA256SUMS"
267+echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries"
268+
269+# ---------------------------------------------------------------- 4. stage
270+say "4/7 stage tree"
271+PKG="$STAGE/pkg"
272+mkdir -p "$PKG"
273+cp "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/"
274+[ -f "$STAGE/$ID" ] && { mkdir -p "$PKG/linux-x86_64"; cp "$STAGE/$ID" "$PKG/linux-x86_64/$ID"; }
275+[ -f "$STAGE/$ID.musl" ] && { mkdir -p "$PKG/linux-x86_64-musl"; cp "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID"; }
276+[ -f "$STAGE/$ID.arm64" ] && { mkdir -p "$PKG/linux-arm64-musl"; cp "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID"; }
277+[ -f "$STAGE/$ID.macos-arm64" ] && { mkdir -p "$PKG/macos-arm64"; cp "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"; }
278+[ -f "$STAGE/$ID.macos-x86_64" ]&& { mkdir -p "$PKG/macos-x86_64"; cp "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"; }
279+[ -f "$STAGE/$ID.exe" ] && { mkdir -p "$PKG/windows-x86_64"; cp "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe"; }
280+echo " staged: $(find "$PKG" -type f | wc -l | tr -d ' ') file(s)"
281+
282+if [ "$DRY_RUN" -eq 1 ]; then
283+ say "dry run - leaving the staging tree in $PKG"
284+ trap - EXIT
285+ exit 0
286+fi
287+
288+# ---------------------------------------------------------------- 5. upload
289+say "5/7 upload to the dist server"
290+[ -n "$DIST_HOST" ] || die "DIST_HOST is not set (export DIST_HOST=<ssh-target>)"
291+SSH=(ssh -o StrictHostKeyChecking=no)
292+SCP=(scp -o StrictHostKeyChecking=no)
293+if [ -n "$DIST_PASS" ]; then
294+ SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}")
295+ SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}")
296+fi
297+REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION"
298+
299+"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \
300+ || die "cannot create $REMOTE_DIR on $DIST_HOST"
301+# Stage to one tarball, transfer it, extract remotely. Streaming tar through
302+# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and
303+# OpenSSH 9 refuses to scp a bare "." source.
304+tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed"
305+"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed"
306+"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \
307+ || die "remote extract failed"
308+echo " uploaded to $DIST_HOST:$REMOTE_DIR"
309+
310+# latest.json = copy of this version's manifest
311+"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \
312+ || die "latest.json update failed"
313+echo " updated bot-plugins/$SLUG/latest.json"
314+
315+# index.json - merge, preserving every sibling <slug>/latest.json
316+say "index.json merge"
317+"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY'
318+import json, os, sys, glob
319+slug = sys.argv[1]
320+entries = {}
321+for p in sorted(glob.glob('*/latest.json')):
322+ s = os.path.dirname(p)
323+ try:
324+ entries[s] = json.load(open(p))
325+ except Exception:
326+ pass
327+index = {
328+ 'ok': True,
329+ 'service': 'bot-plugins-dist',
330+ 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins',
331+ 'count': len(entries),
332+ 'slugs': sorted(entries),
333+ 'plugins': [entries[k] for k in sorted(entries)],
334+}
335+open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10))
336+os.replace('index.json.tmp', 'index.json')
337+print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries))))
338+PY" || die "index.json merge failed"
339+
340+# ---------------------------------------------------------------- 6. mirror
341+say "6/7 plugingit mirror"
342+if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then
343+ TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE")
344+ AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://token:${TOKEN}@|")
345+ git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed"
346+ git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true
347+ echo " mirrored to $PLUGINGIT_REMOTE"
348+else
349+ echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)"
350+fi
351+
352+# ---------------------------------------------------------------- 7. verify
353+say "7/7 verify"
354+CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \
355+ "$DIST_BASE_URL/$SLUG/latest.json" || echo 000)
356+if [ "$CODE" = "200" ]; then
357+ 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"])))' \
358+ "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON"
359+else
360+ echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE"
361+fi
362+
363+printf '\n\033[1mrelease complete\033[0m\n'
364+printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
365+printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
src/bot_theme_plugin.h+129−0■■■■■
11new file mode 100644
index 0000000..0dd243b
--- /dev/null
+++ b/src/bot_theme_plugin.h
@@ -0,0 +1,129 @@
1+/*
2+ * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins.
3+ *
4+ * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of
5+ * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session
6+ * Card modal, Chat floating window) or in its own tab, and in every case it
7+ * must look like part of the bot: same tokens, same dark/light pair, same
8+ * localStorage key, same prepaint order.
9+ *
10+ * Three rules, and nothing else:
11+ *
12+ * 1. Colours come from these tokens only. No plugin-private palette.
13+ * 2. The theme is decided BEFORE first paint, in this order:
14+ * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme
15+ * so a plugin opened from the bot paints in the bot's theme from frame 0.
16+ * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into
17+ * this window; the plugin follows without a reload. The plugin asks once
18+ * with {type:'sx-theme-request'} at startup, which covers the case where
19+ * it was already open when the bot changed theme.
20+ *
21+ * The bottom of :root carries aliases for the names older plugin CSS already
22+ * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn,
23+ * --ok), so adopting the bot palette is a swap, not a redesign. Because they
24+ * are var() references, one definition covers both themes.
25+ *
26+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
27+ */
28+#ifndef SX_BOT_THEME_PLUGIN_H
29+#define SX_BOT_THEME_PLUGIN_H
30+
31+/* Dark is the default; light is applied by html[data-theme=light] (chosen by
32+ * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */
33+#define SX_BOT_THEME_TOKENS \
34+":root{color-scheme:dark;" \
35+ "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \
36+ "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \
37+ "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \
38+ "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \
39+ "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \
40+ "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \
41+ "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \
42+ "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \
43+ "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \
44+ "--shadow:0 1px 2px rgba(0,0,0,.35);" \
45+ "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \
46+ "--ease:cubic-bezier(.16,1,.3,1);" \
47+ "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \
48+ "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \
49+ "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \
50+"}" \
51+"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \
52+ "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \
53+ "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \
54+ "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \
55+ "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \
56+ "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \
57+ "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \
58+ "--accent-dim:#0066d6;" \
59+ "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \
60+ "--shadow:0 2px 10px rgba(0,0,0,.03);" \
61+ "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \
62+ "color-scheme:light}}" \
63+"html[data-theme=light]{" \
64+ "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \
65+ "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \
66+ "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \
67+ "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \
68+ "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \
69+ "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \
70+ "--accent-dim:#0066d6;" \
71+ "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \
72+ "--shadow:0 2px 10px rgba(0,0,0,.03);" \
73+ "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \
74+ "color-scheme:light}" \
75+"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \
76+"*{box-sizing:border-box}" \
77+"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \
78+ "-webkit-font-smoothing:antialiased}" \
79+"button{font-family:inherit;letter-spacing:inherit}" \
80+"button:active{transform:scale(.98)}" \
81+"select option{background:var(--menu-bg);color:var(--text)}" \
82+"a{color:var(--blue);text-decoration:none;font-weight:600}" \
83+"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \
84+" * hides its own back link and its own toggle. */" \
85+"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \
86+"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}"
87+
88+/* Pre-paint: decide the theme before the first frame. Must be the first thing
89+ * in <head> so there is no flash of the wrong theme. Also flags embed mode as
90+ * html.embedded so the embed rules apply before first paint. */
91+#define SX_BOT_THEME_PREPAINT \
92+"<script>(function(){var t='';" \
93+"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \
94+"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \
95+"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \
96+"document.documentElement.setAttribute('data-theme',t);" \
97+"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \
98+"try{localStorage.setItem('bot_theme',t);}catch(e){}" \
99+"})();</script>\n"
100+
101+/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once
102+ * at startup in case it changed while this page was already open. Fires the
103+ * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can
104+ * re-skin themselves from one listener. */
105+#define SX_BOT_THEME_HANDOFF \
106+"<script>(function(){" \
107+"function apply(t){if(t!=='light'&&t!=='dark')return;" \
108+"if(document.documentElement.getAttribute('data-theme')===t)return;" \
109+"document.documentElement.setAttribute('data-theme',t);" \
110+"try{localStorage.setItem('bot_theme',t);}catch(e){}" \
111+"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \
112+"window.sxApplyTheme=apply;" \
113+"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \
114+"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \
115+"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \
116+"})();</script>\n"
117+
118+/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when
119+ * the plugin is opened in its own tab; inside the bot the host owns the theme.
120+ * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */
121+#define SX_BOT_THEME_TOGGLE_BTN \
122+"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>"
123+
124+#define SX_BOT_THEME_TOGGLE_JS \
125+"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \
126+"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \
127+"})();</script>\n"
128+
129+#endif /* SX_BOT_THEME_PLUGIN_H */
src/plugin_gitstat.c+1477−0■■■■■
11new file mode 100644
index 0000000..d0359e3
--- /dev/null
+++ b/src/plugin_gitstat.c
@@ -0,0 +1,1477 @@
1+/*
2+ * plugin_gitstat - SCORPIOX BOT open-source local git repository status board
3+ *
4+ * One clean-room C99 binary, three modes:
5+ * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata
6+ * 2. ?action=repos|repo|fetch / ?format=json / POST -> JSON node API
7+ * 3. GET (default) -> responsive HTML board
8+ *
9+ * It walks a fixed set of allowlisted roots (never beyond them), finds every
10+ * working tree that has a .git directory or a .git worktree file, and asks git
11+ * about each one through argv-only child processes (no shell, ever):
12+ *
13+ * git -C <repo> status --porcelain=v2 --branch --untracked-files=normal
14+ * git -C <repo> log -1 --format=%H%x09%ct%x09%s
15+ * git -C <repo> stash list --format=%gd
16+ *
17+ * From that it derives branch, dirty file count, ahead/behind upstream, stash
18+ * count, detached / no-upstream / unborn states and the last commit. Fetching
19+ * from a remote is the ONLY write-ish operation and it stays off until the node
20+ * operator sets GITSTAT_ALLOW_FETCH=1; even then it is `git fetch --prune` with
21+ * a 30 s timeout, and GIT_TERMINAL_PROMPT=0 plus an empty GIT_ASKPASS so a
22+ * credential prompt can never hang the node.
23+ *
24+ * Remote URLs are stripped of any userinfo before they are printed, so a repo
25+ * whose origin is https://user:token@host/x.git never leaks the token into the
26+ * dashboard, the JSON API or the bot's logs.
27+ *
28+ * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and
29+ * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under
30+ * scorpiox-server on the node.
31+ *
32+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
33+ */
34+
35+/* Must be the very first thing on Windows: CreateProcessA/GetFileAttributesA
36+ * and the pipe helpers are gated on _WIN32_WINNT, and MinGW defaults to 0x502. */
37+#if defined(_WIN32) && !defined(_WIN32_WINNT)
38+# define _WIN32_WINNT 0x0601
39+#endif
40+
41+#if !defined(_WIN32)
42+# define _POSIX_C_SOURCE 200809L
43+# define _DEFAULT_SOURCE 1
44+# if defined(__APPLE__)
45+# define _DARWIN_C_SOURCE 1
46+# endif
47+#endif
48+
49+#include <stdio.h>
50+#include <stdlib.h>
51+#include <string.h>
52+#include <stdarg.h>
53+#include <ctype.h>
54+#include <errno.h>
55+#include <time.h>
56+
57+#if defined(_WIN32)
58+# define WIN32_LEAN_AND_MEAN
59+# include <windows.h>
60+#else
61+# include <unistd.h>
62+# include <dirent.h>
63+# include <fcntl.h>
64+# include <sys/types.h>
65+# include <sys/stat.h>
66+# include <sys/wait.h>
67+# include <signal.h>
68+# include <poll.h>
69+#endif
70+
71+#include "bot_theme_plugin.h"
72+#include "ui_html.h"
73+
74+#define PLUGIN_SLUG "gitstat"
75+#define PLUGIN_ID "plugin_gitstat"
76+#define PLUGIN_VER "1.0.0"
77+
78+#define PLUGIN_NAME "git"
79+#define PLUGIN_DESC "Repo status"
80+
81+#define MAX_REPOS 1200
82+#define MAX_ROOT_ENTRIES 20000
83+#define MAX_DEPTH 4
84+#define MAX_ROOTS 8
85+#define MAX_CHANGED 500
86+#define MAX_COMMITS 20
87+#define OUT_CAP (512 * 1024)
88+#define FETCH_TIMEOUT_S 30
89+#define GIT_TIMEOUT_S 20
90+
91+/* ------------------------------------------------------------------ */
92+/* Buffers */
93+/* ------------------------------------------------------------------ */
94+
95+typedef struct {
96+ char *p;
97+ size_t len;
98+ size_t cap;
99+} buf_t;
100+
101+static void buf_init(buf_t *b)
102+{
103+ b->cap = 4096;
104+ b->len = 0;
105+ b->p = (char *)malloc(b->cap);
106+ if (b->p) b->p[0] = '\0';
107+}
108+
109+static void buf_free(buf_t *b)
110+{
111+ free(b->p);
112+ b->p = NULL;
113+ b->len = b->cap = 0;
114+}
115+
116+static void buf_add(buf_t *b, const char *s, size_t n)
117+{
118+ if (!b->p) return;
119+ if (b->len + n + 1 > b->cap) {
120+ size_t nc = b->cap;
121+ char *np;
122+ while (nc < b->len + n + 1) nc *= 2;
123+ np = (char *)realloc(b->p, nc);
124+ if (!np) return;
125+ b->p = np;
126+ b->cap = nc;
127+ }
128+ memcpy(b->p + b->len, s, n);
129+ b->len += n;
130+ b->p[b->len] = '\0';
131+}
132+
133+static void buf_puts(buf_t *b, const char *s)
134+{
135+ if (s) buf_add(b, s, strlen(s));
136+}
137+
138+static void buf_printf(buf_t *b, const char *fmt, ...)
139+{
140+ char tmp[2048];
141+ va_list ap;
142+ int n;
143+
144+ va_start(ap, fmt);
145+ n = vsnprintf(tmp, sizeof(tmp), fmt, ap);
146+ va_end(ap);
147+ if (n < 0) return;
148+ if ((size_t)n < sizeof(tmp)) {
149+ buf_add(b, tmp, (size_t)n);
150+ } else {
151+ char *big = (char *)malloc((size_t)n + 1);
152+ if (!big) return;
153+ va_start(ap, fmt);
154+ vsnprintf(big, (size_t)n + 1, fmt, ap);
155+ va_end(ap);
156+ buf_add(b, big, (size_t)n);
157+ free(big);
158+ }
159+}
160+
161+static const char *buf_str(buf_t *b) { return b->p ? b->p : ""; }
162+
163+/* JSON string escaper. Also the last line of defence against a remote URL
164+ * carrying something that would break the document. */
165+static void json_str(buf_t *b, const char *s)
166+{
167+ const unsigned char *p = (const unsigned char *)(s ? s : "");
168+ buf_add(b, "\"", 1);
169+ while (*p) {
170+ switch (*p) {
171+ case '"': buf_add(b, "\\\"", 2); break;
172+ case '\\': buf_add(b, "\\\\", 2); break;
173+ case '\n': buf_add(b, "\\n", 2); break;
174+ case '\r': buf_add(b, "\\r", 2); break;
175+ case '\t': buf_add(b, "\\t", 2); break;
176+ default:
177+ if (*p < 0x20) {
178+ char esc[8];
179+ snprintf(esc, sizeof(esc), "\\u%04x", *p);
180+ buf_add(b, esc, strlen(esc));
181+ } else {
182+ buf_add(b, (const char *)p, 1);
183+ }
184+ }
185+ p++;
186+ }
187+ buf_add(b, "\"", 1);
188+}
189+
190+/* ------------------------------------------------------------------ */
191+/* Small utilities */
192+/* ------------------------------------------------------------------ */
193+
194+static void str_copy(char *dst, size_t sz, const char *src)
195+{
196+ size_t n;
197+ if (!dst || sz == 0) return;
198+ if (!src) src = "";
199+ n = strlen(src);
200+ if (n > sz - 1) n = sz - 1;
201+ memcpy(dst, src, n);
202+ dst[n] = '\0';
203+}
204+
205+static void str_trim(char *s)
206+{
207+ size_t n;
208+ char *p = s;
209+ if (!s) return;
210+ while (*p && (unsigned char)*p <= ' ') p++;
211+ if (p != s) memmove(s, p, strlen(p) + 1);
212+ n = strlen(s);
213+ while (n > 0 && (unsigned char)s[n - 1] <= ' ') s[--n] = '\0';
214+}
215+
216+static void url_decode(char *s)
217+{
218+ char *o = s;
219+ if (!s) return;
220+ while (*s) {
221+ if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) {
222+ int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10);
223+ int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10);
224+ *o++ = (char)((hi << 4) | lo);
225+ s += 3;
226+ } else if (*s == '+') {
227+ *o++ = ' ';
228+ s++;
229+ } else {
230+ *o++ = *s++;
231+ }
232+ }
233+ *o = '\0';
234+}
235+
236+/* Returns 1 when the key was present (value may be empty). */
237+static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
238+{
239+ const char *p;
240+ size_t klen;
241+
242+ if (!qs || !key || !out || outsz == 0) return 0;
243+ out[0] = '\0';
244+ klen = strlen(key);
245+ p = qs;
246+ while (*p) {
247+ if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
248+ size_t i = 0;
249+ p += klen + 1;
250+ while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++;
251+ out[i] = '\0';
252+ url_decode(out);
253+ return 1;
254+ }
255+ p = strchr(p, '&');
256+ if (!p) break;
257+ p++;
258+ }
259+ return 0;
260+}
261+
262+static int is_post_request(void)
263+{
264+ const char *m = getenv("REQUEST_METHOD");
265+ return m && strcmp(m, "POST") == 0;
266+}
267+
268+static void utc_stamp(time_t t, char *buf, size_t sz)
269+{
270+ struct tm tmv;
271+#if defined(_WIN32)
272+ gmtime_s(&tmv, &t);
273+#else
274+ gmtime_r(&t, &tmv);
275+#endif
276+ strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv);
277+}
278+
279+/* Strip any userinfo from a URL-ish string so an origin like
280+ * https://user:token@host/x.git is printed as https://host/x.git. */
281+static void redact_url(const char *in, char *out, size_t sz)
282+{
283+ const char *scheme;
284+ const char *at;
285+
286+ if (!in || !*in) { str_copy(out, sz, ""); return; }
287+
288+ scheme = strstr(in, "://");
289+ if (!scheme) { str_copy(out, sz, in); return; }
290+
291+ at = strchr(scheme + 3, '@');
292+ if (!at) { str_copy(out, sz, in); return; }
293+
294+ /* Anything with an '@' before the first '/' carries userinfo. */
295+ {
296+ const char *slash = strchr(scheme + 3, '/');
297+ if (slash && slash < at) { str_copy(out, sz, in); return; }
298+ }
299+
300+ /* scheme:// + rest-after-@ */
301+ {
302+ size_t head = (size_t)(scheme + 3 - in);
303+ if (head >= sz) head = sz - 1;
304+ memcpy(out, in, head);
305+ out[head] = '\0';
306+ strncat(out, at + 1, sz - strlen(out) - 1);
307+ }
308+}
309+
310+/* ------------------------------------------------------------------ */
311+/* Node authentication */
312+/* ------------------------------------------------------------------ */
313+
314+static void require_node_auth(void)
315+{
316+ const char *np = getenv("BOT_PASSWORD");
317+ const char *xp;
318+ const char *auth;
319+ const char *qs;
320+ char qpwd[256];
321+
322+ if (!np || !*np) return;
323+
324+ xp = getenv("HTTP_X_BOT_PASSWORD");
325+ if (xp && strcmp(xp, np) == 0) return;
326+
327+ auth = getenv("HTTP_AUTHORIZATION");
328+ if (auth) {
329+ while (*auth == ' ') auth++;
330+ if (strncmp(auth, "Bearer ", 7) == 0) {
331+ auth += 7;
332+ while (*auth == ' ') auth++;
333+ if (strcmp(auth, np) == 0) return;
334+ }
335+ }
336+
337+ qs = getenv("QUERY_STRING");
338+ if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0)
339+ return;
340+
341+ fputs("Status: 401 Unauthorized\r\n"
342+ "Content-Type: application/json; charset=utf-8\r\n"
343+ "Cache-Control: no-store\r\n"
344+ "X-Content-Type-Options: nosniff\r\n\r\n"
345+ "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
346+ exit(0);
347+}
348+
349+/* ------------------------------------------------------------------ */
350+/* Running git: argv only, never a shell */
351+/* ------------------------------------------------------------------ */
352+
353+/* Captures stdout into out (NUL terminated, truncated at outsz-1) and returns
354+ * the child's exit status, or -1 when it could not be started or timed out.
355+ * Every argv passed here is built from a constant plus one validated path. */
356+#if defined(_WIN32)
357+
358+static void win_quote(const char *in, char *out, size_t sz)
359+{
360+ size_t o = 0;
361+ o += (size_t)snprintf(out, sz, "\"");
362+ while (*in && o + 3 < sz) {
363+ if (*in == '"' || *in == '\\') { out[o++] = '\\'; }
364+ out[o++] = *in++;
365+ }
366+ if (o + 2 < sz) out[o++] = '"';
367+ out[o] = '\0';
368+}
369+
370+static int run_argv(char *const argv[], buf_t *out, int timeout_s)
371+{
372+ SECURITY_ATTRIBUTES sa;
373+ HANDLE rd = NULL, wr = NULL;
374+ STARTUPINFOA si;
375+ PROCESS_INFORMATION pi;
376+ char cmdline[4096];
377+ size_t used = 0;
378+ DWORD waited;
379+ DWORD ticks = 0;
380+ int rc = -1;
381+
382+ memset(&sa, 0, sizeof(sa));
383+ sa.nLength = sizeof(sa);
384+ sa.bInheritHandle = TRUE;
385+ if (!CreatePipe(&rd, &wr, &sa, 0)) return -1;
386+ SetHandleInformation(rd, HANDLE_FLAG_INHERIT, 0);
387+
388+ cmdline[0] = '\0';
389+ {
390+ int i;
391+ for (i = 0; argv[i]; i++) {
392+ char q[1200];
393+ size_t need;
394+ win_quote(argv[i], q, sizeof(q));
395+ need = strlen(q) + 2;
396+ if (used + need + 1 >= sizeof(cmdline)) break;
397+ if (used) cmdline[used++] = ' ';
398+ memcpy(cmdline + used, q, strlen(q));
399+ used += strlen(q);
400+ cmdline[used] = '\0';
401+ }
402+ }
403+
404+ memset(&si, 0, sizeof(si));
405+ si.cb = sizeof(si);
406+ si.dwFlags = STARTF_USESTDHANDLES;
407+ si.hStdOutput = wr;
408+ si.hStdError = wr;
409+ si.hStdInput = NULL;
410+ memset(&pi, 0, sizeof(pi));
411+
412+ if (!CreateProcessA(NULL, cmdline, NULL, NULL, TRUE, CREATE_NO_WINDOW,
413+ NULL, NULL, &si, &pi)) {
414+ CloseHandle(rd);
415+ CloseHandle(wr);
416+ return -1;
417+ }
418+ CloseHandle(wr);
419+
420+ for (;;) {
421+ DWORD avail = 0;
422+ char tmp[4096];
423+ DWORD got = 0;
424+ if (!PeekNamedPipe(rd, NULL, 0, NULL, &avail, NULL)) break;
425+ if (avail == 0) {
426+ waited = WaitForSingleObject(pi.hProcess, 20);
427+ if (waited == WAIT_OBJECT_0) {
428+ /* one last drain */
429+ if (!PeekNamedPipe(rd, NULL, 0, NULL, &avail, NULL)) break;
430+ if (avail == 0) break;
431+ } else if (timeout_s > 0 && waited == WAIT_TIMEOUT) {
432+ if (++ticks > (DWORD)timeout_s * 50) {
433+ TerminateProcess(pi.hProcess, 1);
434+ break;
435+ }
436+ }
437+ continue;
438+ }
439+ if (avail > sizeof(tmp)) avail = sizeof(tmp);
440+ if (!ReadFile(rd, tmp, avail, &got, NULL) || got == 0) break;
441+ if (out) buf_add(out, tmp, got);
442+ }
443+
444+ if (WaitForSingleObject(pi.hProcess, (DWORD)(timeout_s > 0 ? timeout_s : 20) * 1000u)
445+ != WAIT_OBJECT_0) {
446+ TerminateProcess(pi.hProcess, 1);
447+ WaitForSingleObject(pi.hProcess, 2000);
448+ }
449+ {
450+ DWORD code = 1;
451+ GetExitCodeProcess(pi.hProcess, &code);
452+ rc = (int)code;
453+ }
454+ CloseHandle(pi.hProcess);
455+ CloseHandle(pi.hThread);
456+ CloseHandle(rd);
457+ return rc;
458+}
459+
460+#else /* POSIX */
461+
462+static int run_argv(char *const argv[], buf_t *out, int timeout_s)
463+{
464+ int fds[2];
465+ pid_t pid;
466+ int status = 0;
467+ int timed_out = 0;
468+ time_t started;
469+ char *child_env_ok;
470+
471+ if (pipe(fds) != 0) return -1;
472+
473+ pid = fork();
474+ if (pid < 0) {
475+ close(fds[0]);
476+ close(fds[1]);
477+ return -1;
478+ }
479+
480+ if (pid == 0) {
481+ /* Child: stdout+stderr into the pipe, stdin from /dev/null so nothing
482+ * can ever block waiting for a password prompt. */
483+ int devnull = open("/dev/null", O_RDONLY);
484+ if (devnull >= 0) {
485+ dup2(devnull, STDIN_FILENO);
486+ if (devnull != STDIN_FILENO) close(devnull);
487+ }
488+ dup2(fds[1], STDOUT_FILENO);
489+ dup2(fds[1], STDERR_FILENO);
490+ close(fds[0]);
491+ close(fds[1]);
492+ execvp(argv[0], argv);
493+ _exit(127);
494+ }
495+
496+ close(fds[1]);
497+ child_env_ok = (char *)""; /* keep the compiler quiet about unused locals */
498+ (void)child_env_ok;
499+ started = time(NULL);
500+
501+ for (;;) {
502+ struct pollfd pfd;
503+ char tmp[4096];
504+ ssize_t n;
505+ int pr;
506+
507+ pfd.fd = fds[0];
508+ pfd.events = POLLIN;
509+ pfd.revents = 0;
510+ pr = poll(&pfd, 1, 100);
511+ if (pr > 0 && (pfd.revents & (POLLIN | POLLHUP))) {
512+ n = read(fds[0], tmp, sizeof(tmp));
513+ if (n > 0) {
514+ if (out) buf_add(out, tmp, (size_t)n);
515+ continue;
516+ }
517+ if (n == 0) break;
518+ }
519+ if (timeout_s > 0 && (time(NULL) - started) > timeout_s) {
520+ timed_out = 1;
521+ kill(pid, SIGKILL);
522+ break;
523+ }
524+ }
525+
526+ close(fds[0]);
527+
528+ while (waitpid(pid, &status, 0) < 0) {
529+ if (errno != EINTR) break;
530+ }
531+
532+ if (timed_out) return -1;
533+ if (WIFEXITED(status)) return WEXITSTATUS(status);
534+ return -1;
535+}
536+
537+#endif
538+
539+/* git -C <repo> ... */
540+static int run_git(const char *repo, char *const extra[], buf_t *out, int timeout_s)
541+{
542+ char *argv[16];
543+ int i = 0;
544+ int rc;
545+
546+ argv[i++] = (char *)"git";
547+ argv[i++] = (char *)"-C";
548+ argv[i++] = (char *)repo;
549+ while (*extra && i < 14) argv[i++] = *extra++;
550+ argv[i] = NULL;
551+
552+ rc = run_argv(argv, out, timeout_s);
553+ return rc;
554+}
555+
556+/* ------------------------------------------------------------------ */
557+/* Repository model */
558+/* ------------------------------------------------------------------ */
559+
560+typedef struct {
561+ char path[1024];
562+ char name[256];
563+ char root[768];
564+ char branch[256];
565+ char upstream[512]; /* redacted */
566+ char remote[512]; /* origin URL, userinfo stripped */
567+ int ahead;
568+ int behind;
569+ int dirty; /* changed entries (tracked + untracked) */
570+ int untracked;
571+ int staged;
572+ int conflicted;
573+ int stash;
574+ int detached;
575+ int no_upstream;
576+ int unborn;
577+ int detached_ok;
578+ long long last_ct;
579+ char last_hash[48];
580+ char last_subject[300];
581+} repo_t;
582+
583+static repo_t g_repos[MAX_REPOS];
584+static int g_repo_count;
585+
586+typedef struct {
587+ char root[768];
588+ int exists;
589+ int count;
590+ int truncated;
591+} rootstat_t;
592+
593+static rootstat_t g_roots[MAX_ROOTS];
594+static int g_root_count;
595+
596+/* ------------------------------------------------------------------ */
597+/* Discovery */
598+/* ------------------------------------------------------------------ */
599+
600+#if defined(_WIN32)
601+# define SX_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
602+# define SX_ISREG(m) (((m) & _S_IFMT) == _S_IFREG)
603+#else
604+# define SX_ISDIR(m) S_ISDIR(m)
605+# define SX_ISREG(m) S_ISREG(m)
606+#endif
607+
608+static int path_exists(const char *p)
609+{
610+#if defined(_WIN32)
611+ return GetFileAttributesA(p) != INVALID_FILE_ATTRIBUTES;
612+#else
613+ struct stat st;
614+ return stat(p, &st) == 0;
615+#endif
616+}
617+
618+/* A repo is a directory that has a .git entry which is either a directory
619+ * (normal clone) or a regular file (worktree / submodule pointer). */
620+static int is_repo_dir(const char *dir)
621+{
622+ char gp[1200];
623+#if defined(_WIN32)
624+ DWORD attr;
625+#else
626+ struct stat st;
627+#endif
628+
629+ snprintf(gp, sizeof(gp), "%s/.git", dir);
630+#if defined(_WIN32)
631+ attr = GetFileAttributesA(gp);
632+ if (attr == INVALID_FILE_ATTRIBUTES) return 0;
633+ return (attr & FILE_ATTRIBUTE_DIRECTORY) || !(attr & FILE_ATTRIBUTE_DIRECTORY);
634+#else
635+ if (lstat(gp, &st) != 0) {
636+ if (stat(gp, &st) != 0) return 0;
637+ }
638+ return SX_ISDIR(st.st_mode) || SX_ISREG(st.st_mode);
639+#endif
640+}
641+
642+static const char *base_name(const char *p)
643+{
644+ const char *s = strrchr(p, '/');
645+#if defined(_WIN32)
646+ const char *b = strrchr(p, '\\');
647+ if (b && (!s || b > s)) s = b;
648+#endif
649+ return s ? s + 1 : p;
650+}
651+
652+static void repo_add(const char *dir, const char *root)
653+{
654+ repo_t *r;
655+
656+ if (g_repo_count >= MAX_REPOS) return;
657+ r = &g_repos[g_repo_count++];
658+ memset(r, 0, sizeof(*r));
659+ str_copy(r->path, sizeof(r->path), dir);
660+ str_copy(r->name, sizeof(r->name), base_name(dir));
661+ str_copy(r->root, sizeof(r->root), root);
662+}
663+
664+/* Depth-limited walk. A repository is a leaf: once found we do not descend into
665+ * it, because a node's repos are the unit you want to see, not every vendored
666+ * checkout inside them. Entry budget is per root (lesson: a shared budget hides
667+ * the second root entirely). */
668+static void walk_dir(const char *dir, const char *root, int depth,
669+ int *entries, int *truncated)
670+{
671+ if (depth > MAX_DEPTH) return;
672+ if (*truncated) return;
673+
674+ if (is_repo_dir(dir)) {
675+ repo_add(dir, root);
676+ return;
677+ }
678+ if (depth == MAX_DEPTH) return;
679+
680+ {
681+#if defined(_WIN32)
682+ WIN32_FIND_DATAA fd;
683+ HANDLE h;
684+ char pat[1400];
685+ snprintf(pat, sizeof(pat), "%s\\*", dir);
686+ h = FindFirstFileA(pat, &fd);
687+ if (h == INVALID_HANDLE_VALUE) return;
688+ do {
689+ char child[1400];
690+ if (fd.cFileName[0] == '.') continue;
691+ if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) continue;
692+ if (strcmp(fd.cFileName, "node_modules") == 0) continue;
693+ if (strcmp(fd.cFileName, "__pycache__") == 0) continue;
694+ if (++(*entries) > MAX_ROOT_ENTRIES) { *truncated = 1; break; }
695+ snprintf(child, sizeof(child), "%s\\%s", dir, fd.cFileName);
696+ walk_dir(child, root, depth + 1, entries, truncated);
697+ } while (FindNextFileA(h, &fd));
698+ FindClose(h);
699+#else
700+ DIR *d = opendir(dir);
701+ struct dirent *e;
702+ if (!d) return;
703+ while ((e = readdir(d)) != NULL) {
704+ char child[1400];
705+ struct stat st;
706+ if (e->d_name[0] == '.') continue;
707+ if (strcmp(e->d_name, "node_modules") == 0) continue;
708+ if (strcmp(e->d_name, "__pycache__") == 0) continue;
709+ snprintf(child, sizeof(child), "%s/%s", dir, e->d_name);
710+ if (lstat(child, &st) != 0) continue;
711+ if (!SX_ISDIR(st.st_mode)) continue; /* never follow symlinks */
712+ if (++(*entries) > MAX_ROOT_ENTRIES) { *truncated = 1; break; }
713+ walk_dir(child, root, depth + 1, entries, truncated);
714+ }
715+ closedir(d);
716+#endif
717+ }
718+}
719+
720+static void root_add(const char *root, const char *sep_list_used)
721+{
722+ (void)sep_list_used;
723+ if (!root || !*root) return;
724+ if (g_root_count >= MAX_ROOTS) return;
725+ {
726+ int i;
727+ for (i = 0; i < g_root_count; i++)
728+ if (strcmp(g_roots[i].root, root) == 0) return;
729+ }
730+ str_copy(g_roots[g_root_count].root, sizeof(g_roots[g_root_count].root), root);
731+ g_roots[g_root_count].exists = 0;
732+ g_roots[g_root_count].count = 0;
733+ g_roots[g_root_count].truncated = 0;
734+ g_root_count++;
735+}
736+
737+static void roots_from_env(const char *name, int posix_sep)
738+{
739+ const char *v = getenv(name);
740+ char buf[2048];
741+ char sep;
742+ char *p;
743+ char *start;
744+
745+ if (!v || !*v) return;
746+ snprintf(buf, sizeof(buf), "%s", v);
747+
748+#if defined(_WIN32)
749+ sep = posix_sep ? ';' : ';';
750+ if (posix_sep) {
751+ char *q = buf;
752+ while ((q = strchr(q, ':')) != NULL) {
753+ /* a drive-letter colon is followed by a separator, not a path */
754+ if (q[1] == '\\' || q[1] == '/') { q++; continue; }
755+ *q = ';';
756+ q++;
757+ }
758+ }
759+#else
760+ sep = ':';
761+ (void)posix_sep;
762+#endif
763+
764+ start = buf;
765+ for (p = buf; ; p++) {
766+ if (*p == sep || *p == '\0') {
767+ char saved = *p;
768+ *p = '\0';
769+ str_trim(start);
770+ root_add(start, sep == ';' ? ";" : ":");
771+ if (saved == '\0') break;
772+ start = p + 1;
773+ }
774+ }
775+}
776+
777+static void collect_roots(void)
778+{
779+ const char *home = getenv("HOME");
780+
781+ const char *only = getenv("GITSTAT_ONLY_ROOTS");
782+ g_root_count = 0;
783+
784+ /* GITSTAT_ONLY_ROOTS=1 makes GITSTAT_ROOTS the complete list. It exists for
785+ * two callers: a node that wants an explicit allowlist, and the test suite,
786+ * which must see a fixture tree and nothing else. The default behaviour is
787+ * still the documented one: the platform roots plus GITSTAT_ROOTS. */
788+ if (only && *only && strcmp(only, "0") != 0) {
789+ roots_from_env("GITSTAT_ROOTS", 1);
790+ return;
791+ }
792+
793+#if defined(_WIN32)
794+ home = getenv("USERPROFILE");
795+ if (!home || !*home) home = getenv("HOMEDRIVE");
796+ root_add(home, ";");
797+ if (path_exists("D:\\codebases")) root_add("D:\\codebases", ";");
798+ if (path_exists("C:\\codebases")) root_add("C:\\codebases", ";");
799+ roots_from_env("GITSTAT_ROOTS", 1);
800+#else
801+ root_add("/workspace", ":");
802+ root_add("/codebases", ":");
803+ root_add(home, ":");
804+ roots_from_env("GITSTAT_ROOTS", 1);
805+#endif
806+}
807+
808+/* ------------------------------------------------------------------ */
809+/* git queries per repo */
810+/* ------------------------------------------------------------------ */
811+
812+/* status --porcelain=v2 --branch. Header lines carry branch state; the rest are
813+ * one changed entry each. Lines look like:
814+ * # branch.oid <hash> (all zeros when unborn)
815+ * # branch.head <name>|(detached)
816+ * # branch.upstream <ref> (absent when no upstream)
817+ * # branch.ab +N -M (absent when no upstream)
818+ * 1 XY sub mH mI mW hH hI path
819+ * 2 XY ... path
820+ * u XY ... path
821+ * ? path
822+ * ! path
823+ */
824+static void parse_status(const char *text, repo_t *r)
825+{
826+ const char *p = text;
827+ char line[1200];
828+
829+ while (*p) {
830+ size_t n = 0;
831+ while (*p && *p != '\n' && n + 1 < sizeof(line)) line[n++] = *p++;
832+ line[n] = '\0';
833+ if (*p == '\n') p++;
834+ str_trim(line);
835+ if (!line[0]) continue;
836+
837+ if (line[0] == '#') {
838+ const char *v = line + 1;
839+ while (*v == ' ') v++;
840+ if (strncmp(v, "branch.head ", 12) == 0) {
841+ const char *b = v + 12;
842+ if (strcmp(b, "(detached)") == 0) {
843+ r->detached = 1;
844+ str_copy(r->branch, sizeof(r->branch), "detached");
845+ } else {
846+ str_copy(r->branch, sizeof(r->branch), b);
847+ }
848+ } else if (strncmp(v, "branch.upstream ", 16) == 0) {
849+ char clean[512];
850+ redact_url(v + 16, clean, sizeof(clean));
851+ str_copy(r->upstream, sizeof(r->upstream), clean);
852+ } else if (strncmp(v, "branch.ab ", 10) == 0) {
853+ const char *ab = v + 10;
854+ int ahead = 0, behind = 0;
855+ if (sscanf(ab, "+%d -%d", &ahead, &behind) == 2) {
856+ r->ahead = ahead;
857+ r->behind = behind;
858+ } else if (sscanf(ab, "+%d -%d", &ahead, &behind) == 1) {
859+ r->ahead = ahead;
860+ }
861+ } else if (strncmp(v, "branch.oid ", 11) == 0) {
862+ const char *oid = v + 11;
863+ if (strcmp(oid, "(initial)") == 0) r->unborn = 1;
864+ }
865+ continue;
866+ }
867+
868+ if (line[0] == '?') {
869+ r->dirty++;
870+ r->untracked++;
871+ } else if (line[0] == '!') {
872+ /* ignored: not a change */
873+ } else if (line[0] == '1' || line[0] == '2') {
874+ r->dirty++;
875+ if (line[0] == '1') {
876+ char xy[8] = { 0, 0, 0 };
877+ if (sscanf(line, "1 %2s", xy) == 1) {
878+ if (xy[0] != '.' && xy[0] != '\0') r->staged++;
879+ }
880+ } else {
881+ r->staged++;
882+ }
883+ } else if (line[0] == 'u') {
884+ r->dirty++;
885+ r->conflicted++;
886+ }
887+ }
888+
889+ if (!r->unborn && r->branch[0] && strcmp(r->branch, "detached") != 0 && !r->upstream[0])
890+ r->no_upstream = 1;
891+ if (r->unborn) r->no_upstream = 1;
892+}
893+
894+/* "1 XY ..." -> XY codes for the detail drawer. */
895+static void status_code(const char *line, char *out, size_t sz)
896+{
897+ if (line[0] == '?') { str_copy(out, sz, "\?\?"); return; }
898+ if (line[0] == '!') { str_copy(out, sz, "!!"); return; }
899+ if (line[0] == 'u') { str_copy(out, sz, "UU"); return; }
900+ if ((line[0] == '1' || line[0] == '2') && line[1] == ' ')
901+ str_copy(out, sz, line + 2);
902+ else
903+ str_copy(out, sz, "--");
904+}
905+
906+/* Path of a v2 status line: everything after the fixed fields. */
907+static void status_path(const char *line, char *out, size_t sz)
908+{
909+ const char *p = line;
910+ int fields;
911+
912+ out[0] = '\0';
913+ if (line[0] == '?') { str_copy(out, sz, line + 2); return; }
914+ if (line[0] == '!') { str_copy(out, sz, line + 2); return; }
915+ if (line[0] == 'u') fields = 10;
916+ else if (line[0] == '2') fields = 9;
917+ else if (line[0] == '1') fields = 8;
918+ else { str_copy(out, sz, line); return; }
919+
920+ for (; fields > 0 && *p; fields--) {
921+ while (*p && *p != ' ') p++;
922+ while (*p == ' ') p++;
923+ }
924+ str_copy(out, sz, p);
925+ if (line[0] == '2') {
926+ /* rename records carry "old\tnew" */
927+ char *tab = strchr(out, '\t');
928+ if (tab) memmove(out, tab + 1, strlen(tab + 1) + 1);
929+ }
930+}
931+
932+static void query_repo(repo_t *r)
933+{
934+ buf_t out;
935+ char *status_args[] = { (char *)"status", (char *)"--porcelain=v2",
936+ (char *)"--branch", (char *)"--untracked-files=normal", NULL };
937+ char *log_args[] = { (char *)"log", (char *)"-1", (char *)"--format=%H%x09%ct%x09%s", NULL };
938+ char *stash_args[] = { (char *)"stash", (char *)"list", (char *)"--format=%gd", NULL };
939+
940+ buf_init(&out);
941+ if (run_git(r->path, status_args, &out, GIT_TIMEOUT_S) >= 0)
942+ parse_status(buf_str(&out), r);
943+ buf_free(&out);
944+
945+ buf_init(&out);
946+ if (run_git(r->path, log_args, &out, GIT_TIMEOUT_S) >= 0 && out.len > 0) {
947+ char *p = out.p;
948+ char *t1 = strchr(p, '\t');
949+ if (t1) {
950+ *t1 = '\0';
951+ str_copy(r->last_hash, sizeof(r->last_hash), p);
952+ {
953+ char *t2 = strchr(t1 + 1, '\t');
954+ if (t2) {
955+ *t2 = '\0';
956+ r->last_ct = atoll(t1 + 1);
957+ str_copy(r->last_subject, sizeof(r->last_subject), t2 + 1);
958+ } else {
959+ r->last_ct = atoll(t1 + 1);
960+ }
961+ }
962+ str_trim(r->last_subject);
963+ }
964+ }
965+ buf_free(&out);
966+
967+ buf_init(&out);
968+ {
969+ char *cfg_args[] = { (char *)"config", (char *)"--get",
970+ (char *)"remote.origin.url", NULL };
971+ if (run_git(r->path, cfg_args, &out, GIT_TIMEOUT_S) >= 0 && out.len > 0) {
972+ char raw[512];
973+ char clean[512];
974+ str_copy(raw, sizeof(raw), out.p);
975+ str_trim(raw);
976+ redact_url(raw, clean, sizeof(clean));
977+ str_copy(r->remote, sizeof(r->remote), clean);
978+ }
979+ }
980+ buf_free(&out);
981+
982+ buf_init(&out);
983+ if (run_git(r->path, stash_args, &out, GIT_TIMEOUT_S) >= 0) {
984+ const char *p = out.p;
985+ while (p && *p) {
986+ const char *nl = strchr(p, '\n');
987+ if (!nl) break;
988+ if (nl > p) r->stash++;
989+ p = nl + 1;
990+ }
991+ }
992+ buf_free(&out);
993+}
994+
995+static int repo_cmp(const void *a, const void *b)
996+{
997+ const repo_t *x = (const repo_t *)a;
998+ const repo_t *y = (const repo_t *)b;
999+
1000+ /* Dirty first (uncommitted work is the thing you came to see), then most
1001+ * recently touched, then path. */
1002+ if ((x->dirty > 0) != (y->dirty > 0)) return x->dirty > 0 ? -1 : 1;
1003+ if (x->dirty != y->dirty) return y->dirty - x->dirty;
1004+ if (x->last_ct != y->last_ct) return (x->last_ct > y->last_ct) ? -1 : 1;
1005+ return strcmp(x->path, y->path);
1006+}
1007+
1008+static void collect_repos(void)
1009+{
1010+ int i;
1011+
1012+ collect_roots();
1013+ g_repo_count = 0;
1014+
1015+ for (i = 0; i < g_root_count; i++) {
1016+ int entries = 0;
1017+ int truncated = 0;
1018+ int before = g_repo_count;
1019+
1020+ g_roots[i].exists = path_exists(g_roots[i].root) ? 1 : 0;
1021+ if (g_roots[i].exists)
1022+ walk_dir(g_roots[i].root, g_roots[i].root, 0, &entries, &truncated);
1023+ g_roots[i].truncated = truncated;
1024+ g_roots[i].count = g_repo_count - before;
1025+ }
1026+
1027+ for (i = 0; i < g_repo_count; i++) query_repo(&g_repos[i]);
1028+
1029+ if (g_repo_count > 1)
1030+ qsort(g_repos, (size_t)g_repo_count, sizeof(repo_t), repo_cmp);
1031+}
1032+
1033+/* ------------------------------------------------------------------ */
1034+/* Path allowlisting */
1035+/* ------------------------------------------------------------------ */
1036+
1037+/* realpath() cannot be handed a caller-sized buffer: glibc's fortified
1038+ * wrapper aborts when the buffer is smaller than PATH_MAX, and the paths here
1039+ * are keep-to-1024 bytes in a 1400-byte array. Ask realpath to allocate, then
1040+ * copy into our own fixed array. */
1041+static void canon_path(const char *in, char *out, size_t sz)
1042+{
1043+#if defined(_WIN32)
1044+ if (!GetFullPathNameA(in, (DWORD)sz, out, NULL)) str_copy(out, sz, in);
1045+#else
1046+ char *rp = realpath(in, NULL);
1047+ if (rp) {
1048+ str_copy(out, sz, rp);
1049+ free(rp);
1050+ } else {
1051+ str_copy(out, sz, in);
1052+ }
1053+#endif
1054+}
1055+
1056+static int under_root(const char *path)
1057+{
1058+ int i;
1059+ for (i = 0; i < g_root_count; i++) {
1060+ size_t n = strlen(g_roots[i].root);
1061+ if (n == 0) continue;
1062+ if (strncmp(path, g_roots[i].root, n) != 0) continue;
1063+ if (path[n] == '\0' || path[n] == '/' || path[n] == '\\') return 1;
1064+ }
1065+ return 0;
1066+}
1067+
1068+/* A repo path is acceptable only when it canonicalises to somewhere under an
1069+ * allowlisted root AND that directory carries a .git entry. This is the whole
1070+ * authorisation model for the API: nothing outside the roots is ever read, and
1071+ * no argument can walk upwards with "..". */
1072+static int path_allowed(const char *requested, char *canon, size_t sz)
1073+{
1074+ char tmp[1400];
1075+
1076+ if (!requested || !*requested) return 0;
1077+ if (strstr(requested, "..")) return 0;
1078+
1079+ collect_roots();
1080+ canon_path(requested, tmp, sizeof(tmp));
1081+ if (!under_root(tmp)) return 0;
1082+ if (!is_repo_dir(tmp)) return 0;
1083+ str_copy(canon, sz, tmp);
1084+ return 1;
1085+}
1086+
1087+/* ------------------------------------------------------------------ */
1088+/* JSON emitters */
1089+/* ------------------------------------------------------------------ */
1090+
1091+static void json_header(int status)
1092+{
1093+ if (status == 403)
1094+ fputs("Status: 403 Forbidden\r\n", stdout);
1095+ else if (status == 400)
1096+ fputs("Status: 400 Bad Request\r\n", stdout);
1097+ fputs("Content-Type: application/json; charset=utf-8\r\n"
1098+ "Cache-Control: no-store\r\n"
1099+ "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
1100+}
1101+
1102+static void emit_repo(buf_t *b, const repo_t *r, int detail)
1103+{
1104+ char at[40];
1105+ char up[512];
1106+
1107+ redact_url(r->upstream, up, sizeof(up));
1108+ utc_stamp((time_t)r->last_ct, at, sizeof(at));
1109+
1110+ buf_add(b, "{", 1);
1111+ buf_puts(b, "\"path\":"); json_str(b, r->path);
1112+ buf_puts(b, ",\"name\":"); json_str(b, r->name);
1113+ buf_puts(b, ",\"root\":"); json_str(b, r->root);
1114+ buf_puts(b, ",\"branch\":"); json_str(b, r->branch);
1115+ buf_puts(b, ",\"upstream\":"); json_str(b, up);
1116+ buf_puts(b, ",\"remote\":"); json_str(b, r->remote);
1117+ buf_printf(b, ",\"ahead\":%d,\"behind\":%d,\"dirty\":%d,\"untracked\":%d,"
1118+ "\"staged\":%d,\"conflicted\":%d,\"stash\":%d",
1119+ r->ahead, r->behind, r->dirty, r->untracked,
1120+ r->staged, r->conflicted, r->stash);
1121+ buf_printf(b, ",\"detached\":%s,\"no_upstream\":%s,\"unborn\":%s",
1122+ r->detached ? "true" : "false",
1123+ r->no_upstream ? "true" : "false",
1124+ r->unborn ? "true" : "false");
1125+ buf_puts(b, ",\"last_commit\":{");
1126+ buf_puts(b, "\"hash\":"); json_str(b, r->last_hash);
1127+ buf_puts(b, ",\"short\":");
1128+ {
1129+ char sh[12];
1130+ str_copy(sh, sizeof(sh), r->last_hash);
1131+ json_str(b, sh);
1132+ }
1133+ buf_printf(b, ",\"ct\":%lld", r->last_ct);
1134+ buf_puts(b, ",\"at\":"); json_str(b, at);
1135+ buf_puts(b, ",\"subject\":"); json_str(b, r->last_subject);
1136+ buf_puts(b, "}");
1137+ (void)detail;
1138+ buf_add(b, "}", 1);
1139+}
1140+
1141+static void print_repos(void)
1142+{
1143+ buf_t b;
1144+ int i;
1145+ char now[40];
1146+ int dirty = 0, ahead = 0, behind = 0, stashed = 0, detached = 0;
1147+
1148+ for (i = 0; i < g_repo_count; i++) {
1149+ if (g_repos[i].dirty > 0) dirty++;
1150+ if (g_repos[i].ahead > 0) ahead++;
1151+ if (g_repos[i].behind > 0) behind++;
1152+ if (g_repos[i].stash > 0) stashed += g_repos[i].stash;
1153+ if (g_repos[i].detached) detached++;
1154+ }
1155+ utc_stamp(time(NULL), now, sizeof(now));
1156+
1157+ buf_init(&b);
1158+ buf_printf(&b, "{\"ok\":true,\"action\":\"repos\",\"count\":%d", g_repo_count);
1159+ buf_printf(&b, ",\"table_capped\":%s", g_repo_count >= MAX_REPOS ? "true" : "false");
1160+ buf_printf(&b, ",\"summary\":{\"dirty\":%d,\"ahead\":%d,\"behind\":%d,"
1161+ "\"stashes\":%d,\"detached\":%d}",
1162+ dirty, ahead, behind, stashed, detached);
1163+ buf_puts(&b, ",\"checked_at\":"); json_str(&b, now);
1164+ buf_puts(&b, ",\"roots\":[");
1165+ for (i = 0; i < g_root_count; i++) {
1166+ if (i) buf_add(&b, ",", 1);
1167+ buf_add(&b, "{", 1);
1168+ buf_puts(&b, "\"root\":"); json_str(&b, g_roots[i].root);
1169+ buf_printf(&b, ",\"exists\":%s,\"count\":%d,\"truncated\":%s",
1170+ g_roots[i].exists ? "true" : "false", g_roots[i].count,
1171+ g_roots[i].truncated ? "true" : "false");
1172+ buf_add(&b, "}", 1);
1173+ }
1174+ buf_puts(&b, "],\"repos\":[");
1175+ for (i = 0; i < g_repo_count; i++) {
1176+ if (i) buf_add(&b, ",", 1);
1177+ emit_repo(&b, &g_repos[i], 0);
1178+ }
1179+ buf_puts(&b, "]}\n");
1180+ fputs(buf_str(&b), stdout);
1181+ buf_free(&b);
1182+}
1183+
1184+static int print_repo_detail(const char *path)
1185+{
1186+ char canon[1400];
1187+ repo_t *r = NULL;
1188+ buf_t b;
1189+ buf_t out;
1190+ int i;
1191+ char at[40];
1192+
1193+ if (!path_allowed(path, canon, sizeof(canon))) {
1194+ json_header(403);
1195+ fputs("{\"ok\":false,\"error\":\"path not in an allowlisted root\"}\n", stdout);
1196+ return 0;
1197+ }
1198+
1199+ /* Prefer the record we already measured; fall back to measuring it now when
1200+ * the path was not part of the (budgeted) discovery walk. */
1201+ for (i = 0; i < g_repo_count; i++) {
1202+ if (strcmp(g_repos[i].path, canon) == 0) { r = &g_repos[i]; break; }
1203+ }
1204+ if (!r) {
1205+ if (g_repo_count >= MAX_REPOS) {
1206+ json_header(400);
1207+ fputs("{\"ok\":false,\"error\":\"repository table full\"}\n", stdout);
1208+ return 0;
1209+ }
1210+ r = &g_repos[g_repo_count];
1211+ memset(r, 0, sizeof(*r));
1212+ str_copy(r->path, sizeof(r->path), canon);
1213+ str_copy(r->name, sizeof(r->name), base_name(canon));
1214+ str_copy(r->root, sizeof(r->root), "");
1215+ query_repo(r);
1216+ g_repo_count++;
1217+ }
1218+
1219+ buf_init(&b);
1220+ buf_printf(&b, "{\"ok\":true,\"action\":\"repo\",\"repo\":");
1221+ emit_repo(&b, r, 1);
1222+
1223+ /* changed files, max MAX_CHANGED */
1224+ {
1225+ char *status_args[] = { (char *)"status", (char *)"--porcelain=v2",
1226+ (char *)"--untracked-files=normal", NULL };
1227+ int shown = 0, total = 0;
1228+ int trunc = 0;
1229+
1230+ buf_init(&out);
1231+ buf_puts(&b, ",\"changed\":[");
1232+ if (run_git(r->path, status_args, &out, GIT_TIMEOUT_S) >= 0) {
1233+ const char *p = out.p;
1234+ char line[1200];
1235+ while (p && *p) {
1236+ size_t n = 0;
1237+ while (*p && *p != '\n' && n + 1 < sizeof(line)) line[n++] = *p++;
1238+ line[n] = '\0';
1239+ if (*p == '\n') p++;
1240+ str_trim(line);
1241+ if (!line[0] || line[0] == '#') continue;
1242+ total++;
1243+ if (shown >= MAX_CHANGED) { trunc = 1; continue; }
1244+ {
1245+ char code[8], fp[900];
1246+ status_code(line, code, sizeof(code));
1247+ status_path(line, fp, sizeof(fp));
1248+ if (shown) buf_add(&b, ",", 1);
1249+ buf_add(&b, "{", 1);
1250+ buf_puts(&b, "\"code\":"); json_str(&b, code);
1251+ buf_puts(&b, ",\"path\":"); json_str(&b, fp);
1252+ buf_add(&b, "}", 1);
1253+ shown++;
1254+ }
1255+ }
1256+ }
1257+ buf_free(&out);
1258+ buf_printf(&b, "],\"changed_count\":%d,\"changed_truncated\":%s",
1259+ total, trunc ? "true" : "false");
1260+ }
1261+
1262+ /* recent commits */
1263+ {
1264+ char *log_args[] = { (char *)"log", (char *)"-20",
1265+ (char *)"--format=%H%x09%ct%x09%an%x09%s", NULL };
1266+ int n = 0;
1267+
1268+ buf_init(&out);
1269+ buf_puts(&b, ",\"commits\":[");
1270+ if (run_git(r->path, log_args, &out, GIT_TIMEOUT_S) >= 0) {
1271+ const char *p = out.p;
1272+ while (p && *p && n < MAX_COMMITS) {
1273+ const char *nl = strchr(p, '\n');
1274+ size_t len = nl ? (size_t)(nl - p) : strlen(p);
1275+ char line[1500];
1276+ if (len >= sizeof(line)) len = sizeof(line) - 1;
1277+ memcpy(line, p, len);
1278+ line[len] = '\0';
1279+ p = nl ? nl + 1 : p + len;
1280+ if (!line[0]) continue;
1281+ {
1282+ char *t1 = strchr(line, '\t');
1283+ char *t2;
1284+ char *t3;
1285+ if (!t1) continue;
1286+ *t1 = '\0';
1287+ t2 = strchr(t1 + 1, '\t');
1288+ if (!t2) continue;
1289+ *t2 = '\0';
1290+ t3 = strchr(t2 + 1, '\t');
1291+ if (t3) *t3 = '\0';
1292+ utc_stamp((time_t)atoll(t1 + 1), at, sizeof(at));
1293+ if (n) buf_add(&b, ",", 1);
1294+ buf_add(&b, "{", 1);
1295+ buf_puts(&b, "\"hash\":"); json_str(&b, line);
1296+ buf_printf(&b, ",\"ct\":%lld", (long long)atoll(t1 + 1));
1297+ buf_puts(&b, ",\"author\":"); json_str(&b, t2 + 1);
1298+ buf_puts(&b, ",\"subject\":"); json_str(&b, t3 ? t3 + 1 : "");
1299+ buf_add(&b, "}", 1);
1300+ n++;
1301+ }
1302+ }
1303+ }
1304+ buf_free(&out);
1305+ buf_add(&b, "]", 1);
1306+ }
1307+
1308+ buf_puts(&b, "}\n");
1309+ fputs(buf_str(&b), stdout);
1310+ buf_free(&b);
1311+ return 0;
1312+}
1313+
1314+static int do_fetch(const char *path, int *status_out)
1315+{
1316+ char canon[1400];
1317+ buf_t b;
1318+ buf_t out;
1319+ int rc;
1320+ repo_t tmp;
1321+
1322+ if (!path_allowed(path, canon, sizeof(canon))) {
1323+ json_header(403);
1324+ fputs("{\"ok\":false,\"error\":\"path not in an allowlisted root\"}\n", stdout);
1325+ return 0;
1326+ }
1327+
1328+ json_header(0);
1329+ if (!getenv("GITSTAT_ALLOW_FETCH") || strcmp(getenv("GITSTAT_ALLOW_FETCH"), "1") != 0) {
1330+ buf_init(&b);
1331+ buf_puts(&b, "{\"ok\":false,\"error\":\"fetch is disabled on this node\","
1332+ "\"hint\":\"set GITSTAT_ALLOW_FETCH=1 to enable git fetch --prune\"}\n");
1333+ fputs(buf_str(&b), stdout);
1334+ buf_free(&b);
1335+ return 0;
1336+ }
1337+
1338+ {
1339+ char *fetch_args[] = { (char *)"fetch", (char *)"--prune", NULL };
1340+ buf_init(&out);
1341+ rc = run_git(canon, fetch_args, &out, FETCH_TIMEOUT_S);
1342+
1343+ memset(&tmp, 0, sizeof(tmp));
1344+ str_copy(tmp.path, sizeof(tmp.path), canon);
1345+ query_repo(&tmp);
1346+
1347+ buf_init(&b);
1348+ buf_printf(&b, "{\"ok\":%s,\"action\":\"fetch\",\"exit\":%d",
1349+ rc == 0 ? "true" : "false", rc);
1350+ buf_puts(&b, ",\"path\":"); json_str(&b, canon);
1351+ buf_puts(&b, ",\"output\":"); json_str(&b, buf_str(&out));
1352+ buf_printf(&b, ",\"ahead\":%d,\"behind\":%d,\"branch\":", tmp.ahead, tmp.behind);
1353+ json_str(&b, tmp.branch);
1354+ buf_puts(&b, "}\n");
1355+ fputs(buf_str(&b), stdout);
1356+ buf_free(&b);
1357+ buf_free(&out);
1358+ }
1359+ (void)status_out;
1360+ return 0;
1361+}
1362+
1363+/* ------------------------------------------------------------------ */
1364+/* HTML UI */
1365+/* ------------------------------------------------------------------ */
1366+
1367+/* Split UI_HTML on the two control-byte placeholders and expand them into the
1368+ * theme macros, so the page and the bot palette can never drift apart. */
1369+static void emit_ui(void)
1370+{
1371+ const char *p = UI_HTML;
1372+
1373+ while (*p) {
1374+ if (*p == '\001') {
1375+ fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS
1376+ ":root{--tx:var(--text);--mu:var(--text-2);--ln:var(--line);"
1377+ "--ac:var(--blue);--sf:var(--bg-card);--sf2:var(--surface-2)}"
1378+ "</style>", stdout);
1379+ p++;
1380+ } else if (*p == '\002') {
1381+ fputs(SX_BOT_THEME_HANDOFF, stdout);
1382+ p++;
1383+ } else {
1384+ putchar(*p++);
1385+ }
1386+ }
1387+}
1388+
1389+static int mode_html(void)
1390+{
1391+ fputs("Content-Type: text/html; charset=utf-8\r\n"
1392+ "Cache-Control: no-store\r\n"
1393+ "X-Content-Type-Options: nosniff\r\n"
1394+ "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; "
1395+ "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; "
1396+ "form-action 'none'; base-uri 'none'\r\n\r\n", stdout);
1397+ emit_ui();
1398+ return 0;
1399+}
1400+
1401+/* ------------------------------------------------------------------ */
1402+/* Modes */
1403+/* ------------------------------------------------------------------ */
1404+
1405+static int mode_meta(void)
1406+{
1407+ fputs("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}\n", stdout);
1408+ return 0;
1409+}
1410+
1411+static int mode_json(const char *qs)
1412+{
1413+ char action[64];
1414+ char path[1024];
1415+
1416+ action[0] = '\0';
1417+ get_query_val(qs, "action", action, sizeof(action));
1418+
1419+ if (strcmp(action, "repo") == 0) {
1420+ collect_roots();
1421+ get_query_val(qs, "path", path, sizeof(path));
1422+ json_header(0);
1423+ return print_repo_detail(path);
1424+ }
1425+
1426+ if (strcmp(action, "fetch") == 0) {
1427+ int st = 0;
1428+ collect_roots();
1429+ get_query_val(qs, "path", path, sizeof(path));
1430+ if (!is_post_request()) {
1431+ json_header(400);
1432+ fputs("{\"ok\":false,\"error\":\"fetch is POST only\"}\n", stdout);
1433+ return 0;
1434+ }
1435+ return do_fetch(path, &st);
1436+ }
1437+
1438+ if (strcmp(action, "repos") == 0 || !action[0] || strcmp(action, "all") == 0) {
1439+ collect_repos();
1440+ json_header(0);
1441+ print_repos();
1442+ return 0;
1443+ }
1444+
1445+ json_header(0);
1446+ fputs("{\"ok\":false,\"error\":\"unknown action\"}\n", stdout);
1447+ return 0;
1448+}
1449+
1450+int main(int argc, char **argv)
1451+{
1452+ const char *qs;
1453+ int embed;
1454+
1455+ if ((argc > 1 && strcmp(argv[1], "--meta") == 0) ||
1456+ (getenv("SX_PLUGIN_META") && *getenv("SX_PLUGIN_META")))
1457+ return mode_meta();
1458+
1459+ require_node_auth();
1460+
1461+ qs = getenv("QUERY_STRING");
1462+ if (!qs) qs = "";
1463+
1464+ if (is_post_request() && strstr(qs, "action=fetch")) {
1465+ char path[1024];
1466+ collect_roots();
1467+ get_query_val(qs, "path", path, sizeof(path));
1468+ return do_fetch(path, NULL);
1469+ }
1470+
1471+ if (strstr(qs, "action=") || strstr(qs, "format=json") || is_post_request())
1472+ return mode_json(qs);
1473+
1474+ embed = (strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL);
1475+ (void)embed;
1476+ return mode_html();
1477+}
src/ui.html+470−0■■■■■
11new file mode 100644
index 0000000..e51377b
--- /dev/null
+++ b/src/ui.html
@@ -0,0 +1,470 @@
1+<!DOCTYPE html>
2+<html lang="en"><head><meta charset="utf-8">
3+<meta name="viewport" content="width=device-width,initial-scale=1">
4+<title>git</title>
5+<!--TOKENS-->
6+<style>
7+*{box-sizing:border-box}
8+html,body{margin:0;min-height:100%}
9+body{background:var(--bg);color:var(--tx,var(--text));font-family:var(--font);
10+ font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}
11+.wrap{max-width:1200px;margin:0 auto;padding:18px 18px 40px}
12+.top{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px}
13+.brand{font-size:11px;font-weight:700;letter-spacing:.09em;text-transform:uppercase;
14+ color:var(--mu,var(--text-2))}
15+.title{font-size:19px;font-weight:680;margin:0;letter-spacing:-.01em}
16+.sp{flex:1 1 auto}
17+.pill{font-size:11px;font-weight:600;padding:3px 9px;border-radius:999px;
18+ background:var(--sf2,var(--surface-2));color:var(--mu,var(--text-2));
19+ border:1px solid var(--ln,var(--line));white-space:nowrap}
20+.icon-btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;
21+ background:var(--sf2,var(--surface-2));border:1px solid var(--ln,var(--line));
22+ color:var(--text);border-radius:9px;height:30px;padding:0 11px;cursor:pointer;
23+ font-family:inherit;font-size:12px;font-weight:600}
24+.icon-btn:hover{background:var(--surface-hover);border-color:var(--line-2)}
25+.icon-btn:active{transform:scale(.97)}
26+.icon-btn svg{width:14px;height:14px;fill:none;stroke:currentColor;stroke-width:1.9;
27+ stroke-linecap:round;stroke-linejoin:round}
28+.icon-btn[disabled]{opacity:.5;cursor:default}
29+
30+.chips{display:grid;grid-template-columns:repeat(auto-fit,minmax(126px,1fr));gap:10px;
31+ margin-bottom:14px}
32+.chip{background:var(--sf,var(--bg-card));border:1px solid var(--ln,var(--line));
33+ border-radius:12px;padding:11px 13px;cursor:pointer;font-family:inherit;
34+ text-align:left;color:var(--text)}
35+.chip:hover{border-color:var(--line-2)}
36+.chip.sel{box-shadow:inset 0 0 0 1.5px var(--ac,var(--blue))}
37+.chip .k{display:flex;align-items:center;gap:6px;font-size:10.5px;font-weight:700;
38+ letter-spacing:.07em;text-transform:uppercase;color:var(--mu,var(--text-2))}
39+.chip .k svg{width:12px;height:12px;fill:none;stroke:currentColor;stroke-width:2;
40+ stroke-linecap:round;stroke-linejoin:round}
41+.chip .v{font-family:var(--mono);font-size:23px;font-weight:700;margin-top:3px;
42+ letter-spacing:-.02em}
43+.chip.ok .v{color:var(--green)}
44+.chip.bad .v{color:var(--red)}
45+.chip.warn .v{color:var(--orange)}
46+.chip.none .v{color:var(--mu,var(--text-2))}
47+
48+.bar{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-bottom:10px}
49+.search{flex:1 1 240px;min-width:0;padding:9px 12px;border-radius:10px;
50+ border:1px solid var(--ln,var(--line));background:var(--input-bg);color:var(--text);
51+ font-family:inherit;font-size:13px}
52+.search:focus{outline:2px solid var(--ac,var(--blue));outline-offset:-1px}
53+select{padding:9px 11px;border-radius:10px;border:1px solid var(--ln,var(--line));
54+ background:var(--input-bg);color:var(--text);font-family:inherit;font-size:13px}
55+
56+.panel{background:var(--sf,var(--bg-card));border:1px solid var(--ln,var(--line));
57+ border-radius:14px;overflow:hidden}
58+.tb{width:100%;overflow-x:auto}
59+table{width:100%;border-collapse:collapse;font-size:13px}
60+th{text-align:left;font-size:10.5px;letter-spacing:.07em;text-transform:uppercase;
61+ color:var(--mu,var(--text-2));font-weight:700;padding:9px 12px;
62+ border-bottom:1px solid var(--ln,var(--line));white-space:nowrap;
63+ background:var(--sf2,var(--surface-2))}
64+td{padding:9px 12px;border-bottom:1px solid var(--ln,var(--line));
65+ vertical-align:middle;white-space:nowrap}
66+tr.row{cursor:pointer}
67+tr.row:hover td{background:var(--surface-hover)}
68+tr.row:last-child td{border-bottom:0}
69+tr.row.sel td{background:var(--sf2,var(--surface-2))}
70+.mo{font-family:var(--mono);font-size:12.5px}
71+.name{font-weight:600;max-width:300px;overflow:hidden;text-overflow:ellipsis}
72+.sub{font-size:11.5px;color:var(--mu,var(--text-2));max-width:300px;
73+ overflow:hidden;text-overflow:ellipsis;margin-top:1px}
74+.subtext{color:var(--text);font-size:12.5px;max-width:340px}
75+td.c-last{max-width:360px;overflow:hidden}
76+.subtext{white-space:normal;display:-webkit-box;-webkit-line-clamp:2;
77+ -webkit-box-orient:vertical;overflow:hidden}
78+.hash{font-family:var(--mono);font-size:11.5px;color:var(--mu,var(--text-2))}
79+.tag{font-size:10px;font-weight:700;padding:2px 8px;border-radius:6px;
80+ white-space:nowrap;letter-spacing:.03em;display:inline-block;margin:1px 3px 1px 0}
81+.t-dirty{background:rgba(255,159,10,.16);color:var(--orange)}
82+.t-ahead{background:rgba(48,209,88,.16);color:var(--green)}
83+.t-behind{background:rgba(255,69,58,.16);color:var(--red)}
84+.t-det{background:rgba(191,90,242,.16);color:var(--purple)}
85+.t-noup{background:rgba(142,142,147,.16);color:var(--gray)}
86+.t-stash{background:rgba(94,92,230,.16);color:var(--indigo)}
87+.t-clean{background:rgba(48,209,88,.12);color:var(--green)}
88+.t-unborn{background:rgba(255,214,10,.16);color:var(--yellow)}
89+.muted{color:var(--mu,var(--text-2))}
90+.empty{padding:28px 16px;text-align:center;color:var(--mu,var(--text-2));font-size:13px}
91+.hide{display:none!important}
92+
93+.drawer{position:fixed;top:0;right:0;bottom:0;width:min(560px,100%);z-index:60;
94+ background:var(--modal-bg,var(--bg-card));border-left:1px solid var(--ln,var(--line));
95+ box-shadow:var(--shadow-lg);transform:translateX(102%);transition:transform .22s var(--ease);
96+ display:flex;flex-direction:column}
97+.drawer.open{transform:none}
98+.dh{display:flex;align-items:center;gap:10px;padding:14px 16px;
99+ border-bottom:1px solid var(--ln,var(--line))}
100+.dh .t{font-size:15px;font-weight:680;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
101+.db{overflow:auto;padding:14px 16px 28px;flex:1 1 auto}
102+.dsec{font-size:10.5px;letter-spacing:.07em;text-transform:uppercase;font-weight:700;
103+ color:var(--mu,var(--text-2));margin:16px 0 8px}
104+.dsec:first-child{margin-top:0}
105+.flist{list-style:none;margin:0;padding:0;font-size:12.5px}
106+.flist li{display:flex;gap:9px;align-items:baseline;padding:4px 0;
107+ border-bottom:1px solid var(--ln,var(--line))}
108+.flist li:last-child{border-bottom:0}
109+.flist .c{font-family:var(--mono);font-size:11px;font-weight:700;width:26px;flex:0 0 26px}
110+.flist .p{font-family:var(--mono);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
111+.c-mod{color:var(--orange)}.c-add{color:var(--green)}.c-del{color:var(--red)}
112+.c-unt{color:var(--gray)}.c-con{color:var(--purple)}
113+.clist{list-style:none;margin:0;padding:0;font-size:12.5px}
114+.clist li{padding:5px 0;border-bottom:1px solid var(--ln,var(--line))}
115+.clist li:last-child{border-bottom:0}
116+.clist .s{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
117+.clist .m{font-size:11px;color:var(--mu,var(--text-2));display:flex;gap:8px}
118+.scrim{position:fixed;inset:0;background:rgba(0,0,0,.35);z-index:55}
119+.scrim.hide{display:none}
120+.note{font-size:11.5px;color:var(--mu,var(--text-2));margin-top:8px}
121+.err{color:var(--red);font-size:12.5px;margin-top:8px}
122+
123+@media(max-width:760px){
124+ .wrap{padding:12px 12px 28px}
125+ .drawer{width:100%;border-left:0}
126+ col.c-root,th.c-root,td.c-root{display:none}
127+}
128+@media(max-width:760px){
129+ /* Two fixed columns: the repo block and the commit block. The commit subject
130+ * is allowed to wrap onto a second line, which is the only way it fits at
131+ * 390 px without a mid-word cut at the panel edge. */
132+ table{table-layout:fixed;width:100%}
133+ td.c-repo{white-space:normal}
134+ td.c-repo .sub{overflow:visible;text-overflow:clip;line-height:1.6}
135+ td.c-last{max-width:none;white-space:normal}
136+ td .sub,.subtext{max-width:none}
137+ col.c-repo{width:48%}
138+ col.c-last{width:52%}
139+ .name{max-width:none}
140+}
141+@media(max-width:560px){
142+ .chips{grid-template-columns:repeat(auto-fit,minmax(104px,1fr));gap:8px}
143+ .chip .v{font-size:19px}
144+ col.c-sync,th.c-sync,td.c-sync{display:none}
145+ th,td{padding:8px 9px}
146+ .name,td .sub,.subtext{max-width:none}
147+}
148+</style></head>
149+<body>
150+<div class="wrap">
151+ <div class="top">
152+ <div>
153+ <div class="brand">SCORPIOX BOT</div>
154+ <h1 class="title">git</h1>
155+ </div>
156+ <span class="pill" id="rootPill">local</span>
157+ <span class="sp"></span>
158+ <button class="icon-btn embed-hide" id="thBtn" type="button" title="Toggle appearance">
159+ <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="4"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M19.1 4.9L17 7M7 17l-2.1 2.1"/></svg>
160+ Theme
161+ </button>
162+ <button class="icon-btn" id="rfBtn" type="button">
163+ <svg viewBox="0 0 24 24"><path d="M21 12a9 9 0 1 1-2.6-6.4"/><path d="M21 3v6h-6"/></svg>
164+ Rescan
165+ </button>
166+ </div>
167+
168+ <div class="chips" id="chips">
169+ <button class="chip none" data-filter="all" id="vAllChip" type="button">
170+ <div class="k"><svg viewBox="0 0 24 24"><path d="M3 7h18M3 12h18M3 17h18"/></svg>All repos</div>
171+ <div class="v" id="vAll">0</div>
172+ </button>
173+ <button class="chip warn" data-filter="dirty" type="button">
174+ <div class="k"><svg viewBox="0 0 24 24"><path d="M12 8v5M12 16h.01"/><circle cx="12" cy="12" r="9"/></svg>Dirty</div>
175+ <div class="v" id="vDirty">0</div>
176+ </button>
177+ <button class="chip ok" data-filter="ahead" type="button">
178+ <div class="k"><svg viewBox="0 0 24 24"><path d="M12 19V5M6 11l6-6 6 6"/></svg>Ahead</div>
179+ <div class="v" id="vAhead">0</div>
180+ </button>
181+ <button class="chip bad" data-filter="behind" type="button">
182+ <div class="k"><svg viewBox="0 0 24 24"><path d="M12 5v14M6 13l6 6 6-6"/></svg>Behind</div>
183+ <div class="v" id="vBehind">0</div>
184+ </button>
185+ <button class="chip none" data-filter="stash" type="button">
186+ <div class="k"><svg viewBox="0 0 24 24"><path d="M4 7h16M4 12h16M4 17h10"/></svg>Stashes</div>
187+ <div class="v" id="vStash">0</div>
188+ </button>
189+ </div>
190+
191+ <div class="bar">
192+ <input class="search" id="q" type="search" placeholder="Filter by repo, branch, or last commit" autocomplete="off">
193+ <select id="sc" aria-label="Filter by state">
194+ <option value="">All states</option>
195+ <option value="dirty">Dirty</option>
196+ <option value="clean">Clean</option>
197+ <option value="ahead">Ahead</option>
198+ <option value="behind">Behind</option>
199+ <option value="detached">Detached</option>
200+ <option value="noup">No upstream</option>
201+ </select>
202+ </div>
203+
204+ <div class="panel">
205+ <div class="tb">
206+ <table>
207+ <colgroup>
208+ <col class="c-repo"><col class="c-root"><col class="c-sync"><col class="c-sync"><col class="c-last">
209+ </colgroup>
210+ <thead><tr>
211+ <th>Repository</th>
212+ <th class="c-root">Root</th>
213+ <th class="c-sync">Sync</th>
214+ <th class="c-sync">Stash</th>
215+ <th>Last commit</th>
216+ </tr></thead>
217+ <tbody id="rows"></tbody>
218+ </table>
219+ </div>
220+ <div class="empty hide" id="empty">No repositories found under the allowlisted roots.</div>
221+ </div>
222+ <div class="note" id="footNote">Read-only. Fetching from a remote stays off unless the node operator enables it.</div>
223+</div>
224+
225+<div class="scrim hide" id="scrim"></div>
226+<aside class="drawer" id="drawer" aria-hidden="true">
227+ <div class="dh">
228+ <div class="t" id="dName">Repository</div>
229+ <span class="sp"></span>
230+ <button class="icon-btn" id="dClose" type="button" title="Close">
231+ <svg viewBox="0 0 24 24"><path d="M18 6 6 18M6 6l12 12"/></svg>
232+ </button>
233+ </div>
234+ <div class="db" id="dBody"></div>
235+</aside>
236+
237+<script>
238+(function(){
239+ var q = new URLSearchParams(location.search);
240+ var node = q.get('node') || '';
241+ var sid = q.get('id') || '';
242+ var pwd = q.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) ||
243+ localStorage.getItem('bot_active_pwd') || '';
244+ /* When the bot serves this page through its proxy, ?plugin= is the route back.
245+ * Opened directly on the node, the plugin itself is the route. */
246+ var HUB = q.get('plugin') || '';
247+
248+ function api(action, extra){
249+ var u = (HUB ? '/plugins?plugin=' + encodeURIComponent(HUB) : '/plugin_gitstat') +
250+ '?action=' + encodeURIComponent(action) +
251+ (extra ? ('&' + extra) : '') +
252+ (node ? '&node=' + encodeURIComponent(node) : '') +
253+ (sid ? '&id=' + encodeURIComponent(sid) : '') +
254+ (pwd ? '&pwd=' + encodeURIComponent(pwd) : '');
255+ return fetch(u, {headers: pwd ? {'X-Bot-Password': pwd} : {}}).then(function(r){
256+ if (!r.ok) throw new Error('HTTP ' + r.status);
257+ return r.json();
258+ });
259+ }
260+
261+ var DATA = [];
262+ var ROOTS = [];
263+ var FILTER = 'all';
264+ var SEL = '';
265+
266+ function esc(v){
267+ return String(v == null ? '' : v).replace(/[&<>"']/g, function(c){
268+ return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];
269+ });
270+ }
271+ function txt(id, v){ var e = document.getElementById(id); if (e) e.textContent = v; }
272+
273+ function ago(ct){
274+ if (!ct) return '-';
275+ var s = Math.max(0, Math.floor(Date.now()/1000) - ct);
276+ if (s < 60) return s + 's ago';
277+ if (s < 3600) return Math.floor(s/60) + 'm ago';
278+ if (s < 86400) return Math.floor(s/3600) + 'h ago';
279+ if (s < 2592000) return Math.floor(s/86400) + 'd ago';
280+ if (s < 31536000) return Math.floor(s/2592000) + 'mo ago';
281+ return Math.floor(s/31536000) + 'y ago';
282+ }
283+
284+ function badges(r){
285+ var h = '';
286+ if (r.dirty > 0) h += '<span class="tag t-dirty">' + r.dirty + ' changed</span>';
287+ if (r.ahead > 0) h += '<span class="tag t-ahead">+' + r.ahead + '</span>';
288+ if (r.behind > 0) h += '<span class="tag t-behind">-' + r.behind + '</span>';
289+ if (r.detached) h += '<span class="tag t-det">detached</span>';
290+ if (r.no_upstream && !r.detached) h += '<span class="tag t-noup">no upstream</span>';
291+ if (r.unborn) h += '<span class="tag t-unborn">unborn</span>';
292+ if (r.stash > 0) h += '<span class="tag t-stash">' + r.stash + ' stash</span>';
293+ if (r.dirty === 0 && !r.detached && !r.unborn) h += '<span class="tag t-clean">clean</span>';
294+ return h;
295+ }
296+
297+ function matches(r){
298+ if (FILTER === 'dirty' && !(r.dirty > 0)) return false;
299+ if (FILTER === 'ahead' && !(r.ahead > 0)) return false;
300+ if (FILTER === 'behind' && !(r.behind > 0)) return false;
301+ if (FILTER === 'stash' && !(r.stash > 0)) return false;
302+
303+ var sc = document.getElementById('sc').value;
304+ if (sc === 'dirty' && !(r.dirty > 0)) return false;
305+ if (sc === 'clean' && (r.dirty > 0)) return false;
306+ if (sc === 'ahead' && !(r.ahead > 0)) return false;
307+ if (sc === 'behind' && !(r.behind > 0)) return false;
308+ if (sc === 'detached' && !r.detached) return false;
309+ if (sc === 'noup' && !r.no_upstream) return false;
310+
311+ var f = (document.getElementById('q').value || '').toLowerCase();
312+ if (!f) return true;
313+ var hay = (r.name + ' ' + r.path + ' ' + r.branch + ' ' + r.upstream + ' ' +
314+ (r.last_commit ? r.last_commit.subject : '')).toLowerCase();
315+ return hay.indexOf(f) >= 0;
316+ }
317+
318+ function render(){
319+ var out = DUPS(DATA), rows = document.getElementById('rows'), h = '';
320+ for (var i = 0; i < out.length; i++) {
321+ var r = out[i], lc = r.last_commit || {};
322+ h += '<tr class="row' + (SEL === r.path ? ' sel' : '') + '" data-p="' + esc(r.path) + '">' +
323+ '<td class="c-repo"><div class="name">' + esc(r.name) + '</div>' +
324+ '<div class="sub"><span class="mo">' + esc(r.branch || '-') + '</span> ' + badges(r) + '</div></td>' +
325+ '<td class="c-root muted mo">' + esc(r.root || '-') + '</td>' +
326+ '<td class="c-sync mo">' + (r.ahead || r.behind ? ('+' + r.ahead + ' -' + r.behind) : '<span class="muted">-</span>') + '</td>' +
327+ '<td class="c-sync mo">' + (r.stash ? r.stash : '<span class="muted">-</span>') + '</td>' +
328+ '<td class="c-last"><div class="sub subtext">' + esc(lc.subject || '-') + '</div>' +
329+ '<div class="hash">' + esc((lc.short || '').slice(0, 8)) + ' &middot; ' + ago(lc.ct) + '</div></td>' +
330+ '</tr>';
331+ }
332+ rows.innerHTML = h;
333+ document.getElementById('empty').className = out.length ? 'empty hide' : 'empty';
334+
335+ var b = rows.querySelectorAll('tr.row');
336+ for (var k = 0; k < b.length; k++) {
337+ b[k].onclick = function(){
338+ openDetail(this.getAttribute('data-p'));
339+ };
340+ }
341+ }
342+ function DUPS(a){ var o = []; for (var i=0;i<a.length;i++) if (matches(a[i])) o.push(a[i]); return o; }
343+
344+ function setCounts(s, n){
345+ s = s || {};
346+ txt('vAll', n || 0);
347+ txt('vDirty', s.dirty || 0);
348+ txt('vAhead', s.ahead || 0);
349+ txt('vBehind', s.behind || 0);
350+ txt('vStash', s.stashes || 0);
351+ }
352+
353+ function load(){
354+ var btn = document.getElementById('rfBtn');
355+ btn.disabled = true;
356+ return api('repos').then(function(d){
357+ DATA = d.repos || [];
358+ ROOTS = d.roots || [];
359+ setCounts(d.summary, d.count);
360+ var ex = [];
361+ for (var i = 0; i < ROOTS.length; i++) if (ROOTS[i].exists) ex.push(ROOTS[i].root);
362+ txt('rootPill', ex.length ? (ex.length + ' root' + (ex.length === 1 ? '' : 's')) : 'no roots');
363+ render();
364+ }).catch(function(e){
365+ txt('rootPill', 'error');
366+ document.getElementById('empty').className = 'empty';
367+ document.getElementById('empty').textContent = 'Load failed: ' + e.message;
368+ }).then(function(){ btn.disabled = false; });
369+ }
370+
371+ function codeClass(c){
372+ if (c === '\?\?' || c === '!!') return 'c-unt';
373+ if (c === 'UU' || c === 'AA' || c === 'DD') return 'c-con';
374+ if (c.indexOf('A') >= 0) return 'c-add';
375+ if (c.indexOf('D') >= 0) return 'c-del';
376+ return 'c-mod';
377+ }
378+
379+ function openDetail(path){
380+ SEL = path;
381+ var d = document.getElementById('drawer');
382+ var s = document.getElementById('scrim');
383+ d.classList.add('open');
384+ d.setAttribute('aria-hidden', 'false');
385+ s.classList.remove('hide');
386+ document.getElementById('dName').textContent = path.split(/[\\/]/).pop() || path;
387+ document.getElementById('dBody').innerHTML = '<div class="muted">Loading…</div>';
388+
389+ api('repo', 'path=' + encodeURIComponent(path)).then(function(j){
390+ if (!j.ok) throw new Error(j.error || 'failed');
391+ var r = j.repo || {}, lc = r.last_commit || {};
392+ var h = '';
393+ h += '<div class="dsec">Repository</div>';
394+ h += '<div class="mo" style="font-size:12px;word-break:break-all">' + esc(r.path) + '</div>';
395+ h += '<div style="margin-top:8px">' + badges(r) + '</div>';
396+ h += '<div class="note">branch <span class="mo">' + esc(r.branch || '-') + '</span>' +
397+ (r.upstream ? ' &rarr; <span class="mo">' + esc(r.upstream) + '</span>' : '') + '</div>';
398+
399+ h += '<div class="dsec">Last commit</div>';
400+ h += '<div class="clist"><li><div class="s">' + esc(lc.subject || '-') + '</div>' +
401+ '<div class="m"><span class="mo">' + esc((lc.short || '').slice(0, 8)) + '</span>' +
402+ '<span>' + ago(lc.ct) + '</span></div></li></div>';
403+
404+ var ch = j.changed || [];
405+ h += '<div class="dsec">Changed files (' + (j.changed_count || 0) + ')</div>';
406+ if (!ch.length) {
407+ h += '<div class="muted">Working tree is clean.</div>';
408+ } else {
409+ h += '<ul class="flist">';
410+ for (var i = 0; i < ch.length; i++) {
411+ h += '<li><span class="c ' + codeClass(ch[i].code) + '">' + esc(ch[i].code) + '</span>' +
412+ '<span class="p">' + esc(ch[i].path) + '</span></li>';
413+ }
414+ h += '</ul>';
415+ if (j.changed_truncated) h += '<div class="note">Showing the first 500 entries.</div>';
416+ }
417+
418+ var cm = j.commits || [];
419+ h += '<div class="dsec">Recent commits (' + cm.length + ')</div>';
420+ if (!cm.length) {
421+ h += '<div class="muted">No commits yet.</div>';
422+ } else {
423+ h += '<ul class="clist">';
424+ for (var k = 0; k < cm.length; k++) {
425+ h += '<li><div class="s">' + esc(cm[k].subject || '') + '</div>' +
426+ '<div class="m"><span class="mo">' + esc((cm[k].hash || '').slice(0, 8)) + '</span>' +
427+ '<span>' + esc(cm[k].author || '') + '</span>' +
428+ '<span>' + ago(cm[k].ct) + '</span></div></li>';
429+ }
430+ h += '</ul>';
431+ }
432+ document.getElementById('dBody').innerHTML = h;
433+ }).catch(function(e){
434+ document.getElementById('dBody').innerHTML =
435+ '<div class="err">Could not read this repository: ' + esc(e.message) + '</div>';
436+ });
437+ }
438+
439+ function closeDetail(){
440+ SEL = '';
441+ document.getElementById('drawer').classList.remove('open');
442+ document.getElementById('drawer').setAttribute('aria-hidden', 'true');
443+ document.getElementById('scrim').classList.add('hide');
444+ render();
445+ }
446+
447+ document.getElementById('dClose').onclick = closeDetail;
448+ document.getElementById('scrim').onclick = closeDetail;
449+ document.addEventListener('keydown', function(e){ if (e.key === 'Escape') closeDetail(); });
450+ document.getElementById('rfBtn').onclick = load;
451+ document.getElementById('q').oninput = render;
452+ document.getElementById('sc').onchange = render;
453+ document.getElementById('thBtn').onclick = function(){
454+ if (window.sxApplyTheme) window.sxApplyTheme(window.sxTheme() === 'dark' ? 'light' : 'dark');
455+ };
456+
457+ var chips = document.querySelectorAll('.chip');
458+ for (var ci = 0; ci < chips.length; ci++) {
459+ chips[ci].onclick = function(){
460+ FILTER = this.getAttribute('data-filter');
461+ for (var j = 0; j < chips.length; j++) chips[j].classList.remove('sel');
462+ this.classList.add('sel');
463+ render();
464+ };
465+ }
466+
467+ load();
468+})();
469+</script>
470+</body></html>
src/ui_html.h+478−0■■■■■
11new file mode 100644
index 0000000..26c9422
--- /dev/null
+++ b/src/ui_html.h
@@ -0,0 +1,478 @@
1+/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */
2+#ifndef SX_GITSTAT_UI_HTML_H
3+#define SX_GITSTAT_UI_HTML_H
4+
5+static const char *UI_HTML =
6+ "<!DOCTYPE html>\n"
7+ "<html lang=\"en\"><head><meta charset=\"utf-8\">\n"
8+ "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n"
9+ "<title>git</title>\n"
10+ "\001\n"
11+ "<style>\n"
12+ "*{box-sizing:border-box}\n"
13+ "html,body{margin:0;min-height:100%}\n"
14+ "body{background:var(--bg);color:var(--tx,var(--text));font-family:var(--font);\n"
15+ " font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}\n"
16+ ".wrap{max-width:1200px;margin:0 auto;padding:18px 18px 40px}\n"
17+ ".top{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px}\n"
18+ ".brand{font-size:11px;font-weight:700;letter-spacing:.09em;text-transform:uppercase;\n"
19+ " color:var(--mu,var(--text-2))}\n"
20+ ".title{font-size:19px;font-weight:680;margin:0;letter-spacing:-.01em}\n"
21+ ".sp{flex:1 1 auto}\n"
22+ ".pill{font-size:11px;font-weight:600;padding:3px 9px;border-radius:999px;\n"
23+ " background:var(--sf2,var(--surface-2));color:var(--mu,var(--text-2));\n"
24+ " border:1px solid var(--ln,var(--line));white-space:nowrap}\n"
25+ ".icon-btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;\n"
26+ " background:var(--sf2,var(--surface-2));border:1px solid var(--ln,var(--line));\n"
27+ " color:var(--text);border-radius:9px;height:30px;padding:0 11px;cursor:pointer;\n"
28+ " font-family:inherit;font-size:12px;font-weight:600}\n"
29+ ".icon-btn:hover{background:var(--surface-hover);border-color:var(--line-2)}\n"
30+ ".icon-btn:active{transform:scale(.97)}\n"
31+ ".icon-btn svg{width:14px;height:14px;fill:none;stroke:currentColor;stroke-width:1.9;\n"
32+ " stroke-linecap:round;stroke-linejoin:round}\n"
33+ ".icon-btn[disabled]{opacity:.5;cursor:default}\n"
34+ "\n"
35+ ".chips{display:grid;grid-template-columns:repeat(auto-fit,minmax(126px,1fr));gap:10px;\n"
36+ " margin-bottom:14px}\n"
37+ ".chip{background:var(--sf,var(--bg-card));border:1px solid var(--ln,var(--line));\n"
38+ " border-radius:12px;padding:11px 13px;cursor:pointer;font-family:inherit;\n"
39+ " text-align:left;color:var(--text)}\n"
40+ ".chip:hover{border-color:var(--line-2)}\n"
41+ ".chip.sel{box-shadow:inset 0 0 0 1.5px var(--ac,var(--blue))}\n"
42+ ".chip .k{display:flex;align-items:center;gap:6px;font-size:10.5px;font-weight:700;\n"
43+ " letter-spacing:.07em;text-transform:uppercase;color:var(--mu,var(--text-2))}\n"
44+ ".chip .k svg{width:12px;height:12px;fill:none;stroke:currentColor;stroke-width:2;\n"
45+ " stroke-linecap:round;stroke-linejoin:round}\n"
46+ ".chip .v{font-family:var(--mono);font-size:23px;font-weight:700;margin-top:3px;\n"
47+ " letter-spacing:-.02em}\n"
48+ ".chip.ok .v{color:var(--green)}\n"
49+ ".chip.bad .v{color:var(--red)}\n"
50+ ".chip.warn .v{color:var(--orange)}\n"
51+ ".chip.none .v{color:var(--mu,var(--text-2))}\n"
52+ "\n"
53+ ".bar{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-bottom:10px}\n"
54+ ".search{flex:1 1 240px;min-width:0;padding:9px 12px;border-radius:10px;\n"
55+ " border:1px solid var(--ln,var(--line));background:var(--input-bg);color:var(--text);\n"
56+ " font-family:inherit;font-size:13px}\n"
57+ ".search:focus{outline:2px solid var(--ac,var(--blue));outline-offset:-1px}\n"
58+ "select{padding:9px 11px;border-radius:10px;border:1px solid var(--ln,var(--line));\n"
59+ " background:var(--input-bg);color:var(--text);font-family:inherit;font-size:13px}\n"
60+ "\n"
61+ ".panel{background:var(--sf,var(--bg-card));border:1px solid var(--ln,var(--line));\n"
62+ " border-radius:14px;overflow:hidden}\n"
63+ ".tb{width:100%;overflow-x:auto}\n"
64+ "table{width:100%;border-collapse:collapse;font-size:13px}\n"
65+ "th{text-align:left;font-size:10.5px;letter-spacing:.07em;text-transform:uppercase;\n"
66+ " color:var(--mu,var(--text-2));font-weight:700;padding:9px 12px;\n"
67+ " border-bottom:1px solid var(--ln,var(--line));white-space:nowrap;\n"
68+ " background:var(--sf2,var(--surface-2))}\n"
69+ "td{padding:9px 12px;border-bottom:1px solid var(--ln,var(--line));\n"
70+ " vertical-align:middle;white-space:nowrap}\n"
71+ "tr.row{cursor:pointer}\n"
72+ "tr.row:hover td{background:var(--surface-hover)}\n"
73+ "tr.row:last-child td{border-bottom:0}\n"
74+ "tr.row.sel td{background:var(--sf2,var(--surface-2))}\n"
75+ ".mo{font-family:var(--mono);font-size:12.5px}\n"
76+ ".name{font-weight:600;max-width:300px;overflow:hidden;text-overflow:ellipsis}\n"
77+ ".sub{font-size:11.5px;color:var(--mu,var(--text-2));max-width:300px;\n"
78+ " overflow:hidden;text-overflow:ellipsis;margin-top:1px}\n"
79+ ".subtext{color:var(--text);font-size:12.5px;max-width:340px}\n"
80+ "td.c-last{max-width:360px;overflow:hidden}\n"
81+ ".subtext{white-space:normal;display:-webkit-box;-webkit-line-clamp:2;\n"
82+ " -webkit-box-orient:vertical;overflow:hidden}\n"
83+ ".hash{font-family:var(--mono);font-size:11.5px;color:var(--mu,var(--text-2))}\n"
84+ ".tag{font-size:10px;font-weight:700;padding:2px 8px;border-radius:6px;\n"
85+ " white-space:nowrap;letter-spacing:.03em;display:inline-block;margin:1px 3px 1px 0}\n"
86+ ".t-dirty{background:rgba(255,159,10,.16);color:var(--orange)}\n"
87+ ".t-ahead{background:rgba(48,209,88,.16);color:var(--green)}\n"
88+ ".t-behind{background:rgba(255,69,58,.16);color:var(--red)}\n"
89+ ".t-det{background:rgba(191,90,242,.16);color:var(--purple)}\n"
90+ ".t-noup{background:rgba(142,142,147,.16);color:var(--gray)}\n"
91+ ".t-stash{background:rgba(94,92,230,.16);color:var(--indigo)}\n"
92+ ".t-clean{background:rgba(48,209,88,.12);color:var(--green)}\n"
93+ ".t-unborn{background:rgba(255,214,10,.16);color:var(--yellow)}\n"
94+ ".muted{color:var(--mu,var(--text-2))}\n"
95+ ".empty{padding:28px 16px;text-align:center;color:var(--mu,var(--text-2));font-size:13px}\n"
96+ ".hide{display:none!important}\n"
97+ "\n"
98+ ".drawer{position:fixed;top:0;right:0;bottom:0;width:min(560px,100%);z-index:60;\n"
99+ " background:var(--modal-bg,var(--bg-card));border-left:1px solid var(--ln,var(--line));\n"
100+ " box-shadow:var(--shadow-lg);transform:translateX(102%);transition:transform .22s var(--ease);\n"
101+ " display:flex;flex-direction:column}\n"
102+ ".drawer.open{transform:none}\n"
103+ ".dh{display:flex;align-items:center;gap:10px;padding:14px 16px;\n"
104+ " border-bottom:1px solid var(--ln,var(--line))}\n"
105+ ".dh .t{font-size:15px;font-weight:680;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n"
106+ ".db{overflow:auto;padding:14px 16px 28px;flex:1 1 auto}\n"
107+ ".dsec{font-size:10.5px;letter-spacing:.07em;text-transform:uppercase;font-weight:700;\n"
108+ " color:var(--mu,var(--text-2));margin:16px 0 8px}\n"
109+ ".dsec:first-child{margin-top:0}\n"
110+ ".flist{list-style:none;margin:0;padding:0;font-size:12.5px}\n"
111+ ".flist li{display:flex;gap:9px;align-items:baseline;padding:4px 0;\n"
112+ " border-bottom:1px solid var(--ln,var(--line))}\n"
113+ ".flist li:last-child{border-bottom:0}\n"
114+ ".flist .c{font-family:var(--mono);font-size:11px;font-weight:700;width:26px;flex:0 0 26px}\n"
115+ ".flist .p{font-family:var(--mono);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n"
116+ ".c-mod{color:var(--orange)}.c-add{color:var(--green)}.c-del{color:var(--red)}\n"
117+ ".c-unt{color:var(--gray)}.c-con{color:var(--purple)}\n"
118+ ".clist{list-style:none;margin:0;padding:0;font-size:12.5px}\n"
119+ ".clist li{padding:5px 0;border-bottom:1px solid var(--ln,var(--line))}\n"
120+ ".clist li:last-child{border-bottom:0}\n"
121+ ".clist .s{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n"
122+ ".clist .m{font-size:11px;color:var(--mu,var(--text-2));display:flex;gap:8px}\n"
123+ ".scrim{position:fixed;inset:0;background:rgba(0,0,0,.35);z-index:55}\n"
124+ ".scrim.hide{display:none}\n"
125+ ".note{font-size:11.5px;color:var(--mu,var(--text-2));margin-top:8px}\n"
126+ ".err{color:var(--red);font-size:12.5px;margin-top:8px}\n"
127+ "\n"
128+ "@media(max-width:760px){\n"
129+ " .wrap{padding:12px 12px 28px}\n"
130+ " .drawer{width:100%;border-left:0}\n"
131+ " col.c-root,th.c-root,td.c-root{display:none}\n"
132+ "}\n"
133+ "@media(max-width:760px){\n"
134+ " /* Two fixed columns: the repo block and the commit block. The commit subject\n"
135+ " * is allowed to wrap onto a second line, which is the only way it fits at\n"
136+ " * 390 px without a mid-word cut at the panel edge. */\n"
137+ " table{table-layout:fixed;width:100%}\n"
138+ " td.c-repo{white-space:normal}\n"
139+ " td.c-repo .sub{overflow:visible;text-overflow:clip;line-height:1.6}\n"
140+ " td.c-last{max-width:none;white-space:normal}\n"
141+ " td .sub,.subtext{max-width:none}\n"
142+ " col.c-repo{width:48%}\n"
143+ " col.c-last{width:52%}\n"
144+ " .name{max-width:none}\n"
145+ "}\n"
146+ "@media(max-width:560px){\n"
147+ " .chips{grid-template-columns:repeat(auto-fit,minmax(104px,1fr));gap:8px}\n"
148+ " .chip .v{font-size:19px}\n"
149+ " col.c-sync,th.c-sync,td.c-sync{display:none}\n"
150+ " th,td{padding:8px 9px}\n"
151+ " .name,td .sub,.subtext{max-width:none}\n"
152+ "}\n"
153+ "</style></head>\n"
154+ "<body>\n"
155+ "<div class=\"wrap\">\n"
156+ " <div class=\"top\">\n"
157+ " <div>\n"
158+ " <div class=\"brand\">SCORPIOX BOT</div>\n"
159+ " <h1 class=\"title\">git</h1>\n"
160+ " </div>\n"
161+ " <span class=\"pill\" id=\"rootPill\">local</span>\n"
162+ " <span class=\"sp\"></span>\n"
163+ " <button class=\"icon-btn embed-hide\" id=\"thBtn\" type=\"button\" title=\"Toggle appearance\">\n"
164+ " <svg viewBox=\"0 0 24 24\"><circle cx=\"12\" cy=\"12\" r=\"4\"/><path d=\"M12 2v3M12 19v3M2 12h3M19 12h3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M19.1 4.9L17 7M7 17l-2.1 2.1\"/></svg>\n"
165+ " Theme\n"
166+ " </button>\n"
167+ " <button class=\"icon-btn\" id=\"rfBtn\" type=\"button\">\n"
168+ " <svg viewBox=\"0 0 24 24\"><path d=\"M21 12a9 9 0 1 1-2.6-6.4\"/><path d=\"M21 3v6h-6\"/></svg>\n"
169+ " Rescan\n"
170+ " </button>\n"
171+ " </div>\n"
172+ "\n"
173+ " <div class=\"chips\" id=\"chips\">\n"
174+ " <button class=\"chip none\" data-filter=\"all\" id=\"vAllChip\" type=\"button\">\n"
175+ " <div class=\"k\"><svg viewBox=\"0 0 24 24\"><path d=\"M3 7h18M3 12h18M3 17h18\"/></svg>All repos</div>\n"
176+ " <div class=\"v\" id=\"vAll\">0</div>\n"
177+ " </button>\n"
178+ " <button class=\"chip warn\" data-filter=\"dirty\" type=\"button\">\n"
179+ " <div class=\"k\"><svg viewBox=\"0 0 24 24\"><path d=\"M12 8v5M12 16h.01\"/><circle cx=\"12\" cy=\"12\" r=\"9\"/></svg>Dirty</div>\n"
180+ " <div class=\"v\" id=\"vDirty\">0</div>\n"
181+ " </button>\n"
182+ " <button class=\"chip ok\" data-filter=\"ahead\" type=\"button\">\n"
183+ " <div class=\"k\"><svg viewBox=\"0 0 24 24\"><path d=\"M12 19V5M6 11l6-6 6 6\"/></svg>Ahead</div>\n"
184+ " <div class=\"v\" id=\"vAhead\">0</div>\n"
185+ " </button>\n"
186+ " <button class=\"chip bad\" data-filter=\"behind\" type=\"button\">\n"
187+ " <div class=\"k\"><svg viewBox=\"0 0 24 24\"><path d=\"M12 5v14M6 13l6 6 6-6\"/></svg>Behind</div>\n"
188+ " <div class=\"v\" id=\"vBehind\">0</div>\n"
189+ " </button>\n"
190+ " <button class=\"chip none\" data-filter=\"stash\" type=\"button\">\n"
191+ " <div class=\"k\"><svg viewBox=\"0 0 24 24\"><path d=\"M4 7h16M4 12h16M4 17h10\"/></svg>Stashes</div>\n"
192+ " <div class=\"v\" id=\"vStash\">0</div>\n"
193+ " </button>\n"
194+ " </div>\n"
195+ "\n"
196+ " <div class=\"bar\">\n"
197+ " <input class=\"search\" id=\"q\" type=\"search\" placeholder=\"Filter by repo, branch, or last commit\" autocomplete=\"off\">\n"
198+ " <select id=\"sc\" aria-label=\"Filter by state\">\n"
199+ " <option value=\"\">All states</option>\n"
200+ " <option value=\"dirty\">Dirty</option>\n"
201+ " <option value=\"clean\">Clean</option>\n"
202+ " <option value=\"ahead\">Ahead</option>\n"
203+ " <option value=\"behind\">Behind</option>\n"
204+ " <option value=\"detached\">Detached</option>\n"
205+ " <option value=\"noup\">No upstream</option>\n"
206+ " </select>\n"
207+ " </div>\n"
208+ "\n"
209+ " <div class=\"panel\">\n"
210+ " <div class=\"tb\">\n"
211+ " <table>\n"
212+ " <colgroup>\n"
213+ " <col class=\"c-repo\"><col class=\"c-root\"><col class=\"c-sync\"><col class=\"c-sync\"><col class=\"c-last\">\n"
214+ " </colgroup>\n"
215+ " <thead><tr>\n"
216+ " <th>Repository</th>\n"
217+ " <th class=\"c-root\">Root</th>\n"
218+ " <th class=\"c-sync\">Sync</th>\n"
219+ " <th class=\"c-sync\">Stash</th>\n"
220+ " <th>Last commit</th>\n"
221+ " </tr></thead>\n"
222+ " <tbody id=\"rows\"></tbody>\n"
223+ " </table>\n"
224+ " </div>\n"
225+ " <div class=\"empty hide\" id=\"empty\">No repositories found under the allowlisted roots.</div>\n"
226+ " </div>\n"
227+ " <div class=\"note\" id=\"footNote\">Read-only. Fetching from a remote stays off unless the node operator enables it.</div>\n"
228+ "</div>\n"
229+ "\n"
230+ "<div class=\"scrim hide\" id=\"scrim\"></div>\n"
231+ "<aside class=\"drawer\" id=\"drawer\" aria-hidden=\"true\">\n"
232+ " <div class=\"dh\">\n"
233+ " <div class=\"t\" id=\"dName\">Repository</div>\n"
234+ " <span class=\"sp\"></span>\n"
235+ " <button class=\"icon-btn\" id=\"dClose\" type=\"button\" title=\"Close\">\n"
236+ " <svg viewBox=\"0 0 24 24\"><path d=\"M18 6 6 18M6 6l12 12\"/></svg>\n"
237+ " </button>\n"
238+ " </div>\n"
239+ " <div class=\"db\" id=\"dBody\"></div>\n"
240+ "</aside>\n"
241+ "\n"
242+ "<script>\n"
243+ "(function(){\n"
244+ " var q = new URLSearchParams(location.search);\n"
245+ " var node = q.get('node') || '';\n"
246+ " var sid = q.get('id') || '';\n"
247+ " var pwd = q.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) ||\n"
248+ " localStorage.getItem('bot_active_pwd') || '';\n"
249+ " /* When the bot serves this page through its proxy, ?plugin= is the route back.\n"
250+ " * Opened directly on the node, the plugin itself is the route. */\n"
251+ " var HUB = q.get('plugin') || '';\n"
252+ "\n"
253+ " function api(action, extra){\n"
254+ " var u = (HUB ? '/plugins?plugin=' + encodeURIComponent(HUB) : '/plugin_gitstat') +\n"
255+ " '?action=' + encodeURIComponent(action) +\n"
256+ " (extra ? ('&' + extra) : '') +\n"
257+ " (node ? '&node=' + encodeURIComponent(node) : '') +\n"
258+ " (sid ? '&id=' + encodeURIComponent(sid) : '') +\n"
259+ " (pwd ? '&pwd=' + encodeURIComponent(pwd) : '');\n"
260+ " return fetch(u, {headers: pwd ? {'X-Bot-Password': pwd} : {}}).then(function(r){\n"
261+ " if (!r.ok) throw new Error('HTTP ' + r.status);\n"
262+ " return r.json();\n"
263+ " });\n"
264+ " }\n"
265+ "\n"
266+ " var DATA = [];\n"
267+ " var ROOTS = [];\n"
268+ " var FILTER = 'all';\n"
269+ " var SEL = '';\n"
270+ "\n"
271+ " function esc(v){\n"
272+ " return String(v == null ? '' : v).replace(/[&<>\"']/g, function(c){\n"
273+ " return {'&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;',\"'\":'&#39;'}[c];\n"
274+ " });\n"
275+ " }\n"
276+ " function txt(id, v){ var e = document.getElementById(id); if (e) e.textContent = v; }\n"
277+ "\n"
278+ " function ago(ct){\n"
279+ " if (!ct) return '-';\n"
280+ " var s = Math.max(0, Math.floor(Date.now()/1000) - ct);\n"
281+ " if (s < 60) return s + 's ago';\n"
282+ " if (s < 3600) return Math.floor(s/60) + 'm ago';\n"
283+ " if (s < 86400) return Math.floor(s/3600) + 'h ago';\n"
284+ " if (s < 2592000) return Math.floor(s/86400) + 'd ago';\n"
285+ " if (s < 31536000) return Math.floor(s/2592000) + 'mo ago';\n"
286+ " return Math.floor(s/31536000) + 'y ago';\n"
287+ " }\n"
288+ "\n"
289+ " function badges(r){\n"
290+ " var h = '';\n"
291+ " if (r.dirty > 0) h += '<span class=\"tag t-dirty\">' + r.dirty + ' changed</span>';\n"
292+ " if (r.ahead > 0) h += '<span class=\"tag t-ahead\">+' + r.ahead + '</span>';\n"
293+ " if (r.behind > 0) h += '<span class=\"tag t-behind\">-' + r.behind + '</span>';\n"
294+ " if (r.detached) h += '<span class=\"tag t-det\">detached</span>';\n"
295+ " if (r.no_upstream && !r.detached) h += '<span class=\"tag t-noup\">no upstream</span>';\n"
296+ " if (r.unborn) h += '<span class=\"tag t-unborn\">unborn</span>';\n"
297+ " if (r.stash > 0) h += '<span class=\"tag t-stash\">' + r.stash + ' stash</span>';\n"
298+ " if (r.dirty === 0 && !r.detached && !r.unborn) h += '<span class=\"tag t-clean\">clean</span>';\n"
299+ " return h;\n"
300+ " }\n"
301+ "\n"
302+ " function matches(r){\n"
303+ " if (FILTER === 'dirty' && !(r.dirty > 0)) return false;\n"
304+ " if (FILTER === 'ahead' && !(r.ahead > 0)) return false;\n"
305+ " if (FILTER === 'behind' && !(r.behind > 0)) return false;\n"
306+ " if (FILTER === 'stash' && !(r.stash > 0)) return false;\n"
307+ "\n"
308+ " var sc = document.getElementById('sc').value;\n"
309+ " if (sc === 'dirty' && !(r.dirty > 0)) return false;\n"
310+ " if (sc === 'clean' && (r.dirty > 0)) return false;\n"
311+ " if (sc === 'ahead' && !(r.ahead > 0)) return false;\n"
312+ " if (sc === 'behind' && !(r.behind > 0)) return false;\n"
313+ " if (sc === 'detached' && !r.detached) return false;\n"
314+ " if (sc === 'noup' && !r.no_upstream) return false;\n"
315+ "\n"
316+ " var f = (document.getElementById('q').value || '').toLowerCase();\n"
317+ " if (!f) return true;\n"
318+ " var hay = (r.name + ' ' + r.path + ' ' + r.branch + ' ' + r.upstream + ' ' +\n"
319+ " (r.last_commit ? r.last_commit.subject : '')).toLowerCase();\n"
320+ " return hay.indexOf(f) >= 0;\n"
321+ " }\n"
322+ "\n"
323+ " function render(){\n"
324+ " var out = DUPS(DATA), rows = document.getElementById('rows'), h = '';\n"
325+ " for (var i = 0; i < out.length; i++) {\n"
326+ " var r = out[i], lc = r.last_commit || {};\n"
327+ " h += '<tr class=\"row' + (SEL === r.path ? ' sel' : '') + '\" data-p=\"' + esc(r.path) + '\">' +\n"
328+ " '<td class=\"c-repo\"><div class=\"name\">' + esc(r.name) + '</div>' +\n"
329+ " '<div class=\"sub\"><span class=\"mo\">' + esc(r.branch || '-') + '</span> ' + badges(r) + '</div></td>' +\n"
330+ " '<td class=\"c-root muted mo\">' + esc(r.root || '-') + '</td>' +\n"
331+ " '<td class=\"c-sync mo\">' + (r.ahead || r.behind ? ('+' + r.ahead + ' -' + r.behind) : '<span class=\"muted\">-</span>') + '</td>' +\n"
332+ " '<td class=\"c-sync mo\">' + (r.stash ? r.stash : '<span class=\"muted\">-</span>') + '</td>' +\n"
333+ " '<td class=\"c-last\"><div class=\"sub subtext\">' + esc(lc.subject || '-') + '</div>' +\n"
334+ " '<div class=\"hash\">' + esc((lc.short || '').slice(0, 8)) + ' &middot; ' + ago(lc.ct) + '</div></td>' +\n"
335+ " '</tr>';\n"
336+ " }\n"
337+ " rows.innerHTML = h;\n"
338+ " document.getElementById('empty').className = out.length ? 'empty hide' : 'empty';\n"
339+ "\n"
340+ " var b = rows.querySelectorAll('tr.row');\n"
341+ " for (var k = 0; k < b.length; k++) {\n"
342+ " b[k].onclick = function(){\n"
343+ " openDetail(this.getAttribute('data-p'));\n"
344+ " };\n"
345+ " }\n"
346+ " }\n"
347+ " function DUPS(a){ var o = []; for (var i=0;i<a.length;i++) if (matches(a[i])) o.push(a[i]); return o; }\n"
348+ "\n"
349+ " function setCounts(s, n){\n"
350+ " s = s || {};\n"
351+ " txt('vAll', n || 0);\n"
352+ " txt('vDirty', s.dirty || 0);\n"
353+ " txt('vAhead', s.ahead || 0);\n"
354+ " txt('vBehind', s.behind || 0);\n"
355+ " txt('vStash', s.stashes || 0);\n"
356+ " }\n"
357+ "\n"
358+ " function load(){\n"
359+ " var btn = document.getElementById('rfBtn');\n"
360+ " btn.disabled = true;\n"
361+ " return api('repos').then(function(d){\n"
362+ " DATA = d.repos || [];\n"
363+ " ROOTS = d.roots || [];\n"
364+ " setCounts(d.summary, d.count);\n"
365+ " var ex = [];\n"
366+ " for (var i = 0; i < ROOTS.length; i++) if (ROOTS[i].exists) ex.push(ROOTS[i].root);\n"
367+ " txt('rootPill', ex.length ? (ex.length + ' root' + (ex.length === 1 ? '' : 's')) : 'no roots');\n"
368+ " render();\n"
369+ " }).catch(function(e){\n"
370+ " txt('rootPill', 'error');\n"
371+ " document.getElementById('empty').className = 'empty';\n"
372+ " document.getElementById('empty').textContent = 'Load failed: ' + e.message;\n"
373+ " }).then(function(){ btn.disabled = false; });\n"
374+ " }\n"
375+ "\n"
376+ " function codeClass(c){\n"
377+ " if (c === '\\?\\?' || c === '!!') return 'c-unt';\n"
378+ " if (c === 'UU' || c === 'AA' || c === 'DD') return 'c-con';\n"
379+ " if (c.indexOf('A') >= 0) return 'c-add';\n"
380+ " if (c.indexOf('D') >= 0) return 'c-del';\n"
381+ " return 'c-mod';\n"
382+ " }\n"
383+ "\n"
384+ " function openDetail(path){\n"
385+ " SEL = path;\n"
386+ " var d = document.getElementById('drawer');\n"
387+ " var s = document.getElementById('scrim');\n"
388+ " d.classList.add('open');\n"
389+ " d.setAttribute('aria-hidden', 'false');\n"
390+ " s.classList.remove('hide');\n"
391+ " document.getElementById('dName').textContent = path.split(/[\\\\/]/).pop() || path;\n"
392+ " document.getElementById('dBody').innerHTML = '<div class=\"muted\">Loading…</div>';\n"
393+ "\n"
394+ " api('repo', 'path=' + encodeURIComponent(path)).then(function(j){\n"
395+ " if (!j.ok) throw new Error(j.error || 'failed');\n"
396+ " var r = j.repo || {}, lc = r.last_commit || {};\n"
397+ " var h = '';\n"
398+ " h += '<div class=\"dsec\">Repository</div>';\n"
399+ " h += '<div class=\"mo\" style=\"font-size:12px;word-break:break-all\">' + esc(r.path) + '</div>';\n"
400+ " h += '<div style=\"margin-top:8px\">' + badges(r) + '</div>';\n"
401+ " h += '<div class=\"note\">branch <span class=\"mo\">' + esc(r.branch || '-') + '</span>' +\n"
402+ " (r.upstream ? ' &rarr; <span class=\"mo\">' + esc(r.upstream) + '</span>' : '') + '</div>';\n"
403+ "\n"
404+ " h += '<div class=\"dsec\">Last commit</div>';\n"
405+ " h += '<div class=\"clist\"><li><div class=\"s\">' + esc(lc.subject || '-') + '</div>' +\n"
406+ " '<div class=\"m\"><span class=\"mo\">' + esc((lc.short || '').slice(0, 8)) + '</span>' +\n"
407+ " '<span>' + ago(lc.ct) + '</span></div></li></div>';\n"
408+ "\n"
409+ " var ch = j.changed || [];\n"
410+ " h += '<div class=\"dsec\">Changed files (' + (j.changed_count || 0) + ')</div>';\n"
411+ " if (!ch.length) {\n"
412+ " h += '<div class=\"muted\">Working tree is clean.</div>';\n"
413+ " } else {\n"
414+ " h += '<ul class=\"flist\">';\n"
415+ " for (var i = 0; i < ch.length; i++) {\n"
416+ " h += '<li><span class=\"c ' + codeClass(ch[i].code) + '\">' + esc(ch[i].code) + '</span>' +\n"
417+ " '<span class=\"p\">' + esc(ch[i].path) + '</span></li>';\n"
418+ " }\n"
419+ " h += '</ul>';\n"
420+ " if (j.changed_truncated) h += '<div class=\"note\">Showing the first 500 entries.</div>';\n"
421+ " }\n"
422+ "\n"
423+ " var cm = j.commits || [];\n"
424+ " h += '<div class=\"dsec\">Recent commits (' + cm.length + ')</div>';\n"
425+ " if (!cm.length) {\n"
426+ " h += '<div class=\"muted\">No commits yet.</div>';\n"
427+ " } else {\n"
428+ " h += '<ul class=\"clist\">';\n"
429+ " for (var k = 0; k < cm.length; k++) {\n"
430+ " h += '<li><div class=\"s\">' + esc(cm[k].subject || '') + '</div>' +\n"
431+ " '<div class=\"m\"><span class=\"mo\">' + esc((cm[k].hash || '').slice(0, 8)) + '</span>' +\n"
432+ " '<span>' + esc(cm[k].author || '') + '</span>' +\n"
433+ " '<span>' + ago(cm[k].ct) + '</span></div></li>';\n"
434+ " }\n"
435+ " h += '</ul>';\n"
436+ " }\n"
437+ " document.getElementById('dBody').innerHTML = h;\n"
438+ " }).catch(function(e){\n"
439+ " document.getElementById('dBody').innerHTML =\n"
440+ " '<div class=\"err\">Could not read this repository: ' + esc(e.message) + '</div>';\n"
441+ " });\n"
442+ " }\n"
443+ "\n"
444+ " function closeDetail(){\n"
445+ " SEL = '';\n"
446+ " document.getElementById('drawer').classList.remove('open');\n"
447+ " document.getElementById('drawer').setAttribute('aria-hidden', 'true');\n"
448+ " document.getElementById('scrim').classList.add('hide');\n"
449+ " render();\n"
450+ " }\n"
451+ "\n"
452+ " document.getElementById('dClose').onclick = closeDetail;\n"
453+ " document.getElementById('scrim').onclick = closeDetail;\n"
454+ " document.addEventListener('keydown', function(e){ if (e.key === 'Escape') closeDetail(); });\n"
455+ " document.getElementById('rfBtn').onclick = load;\n"
456+ " document.getElementById('q').oninput = render;\n"
457+ " document.getElementById('sc').onchange = render;\n"
458+ " document.getElementById('thBtn').onclick = function(){\n"
459+ " if (window.sxApplyTheme) window.sxApplyTheme(window.sxTheme() === 'dark' ? 'light' : 'dark');\n"
460+ " };\n"
461+ "\n"
462+ " var chips = document.querySelectorAll('.chip');\n"
463+ " for (var ci = 0; ci < chips.length; ci++) {\n"
464+ " chips[ci].onclick = function(){\n"
465+ " FILTER = this.getAttribute('data-filter');\n"
466+ " for (var j = 0; j < chips.length; j++) chips[j].classList.remove('sel');\n"
467+ " this.classList.add('sel');\n"
468+ " render();\n"
469+ " };\n"
470+ " }\n"
471+ "\n"
472+ " load();\n"
473+ "})();\n"
474+ "</script>\n"
475+ "\002</body></html>\n"
476+ ;
477+
478+#endif /* SX_GITSTAT_UI_HTML_H */
tests/e2e.py+332−0■■■■■
11new file mode 100644
index 0000000..30364c5
--- /dev/null
+++ b/tests/e2e.py
@@ -0,0 +1,332 @@
1+#!/usr/bin/env python3
2+"""tests/e2e.py - viewport checks for the plugin_gitstat board.
3+
4+Builds a small fixture tree of real git repositories in a temp directory, serves
5+the plugin through a tiny CGI-ish HTTP shim on a loopback port, and opens it with
6+Playwright at 1440 / 1024 / 390 CSS pixels in both themes. It asserts there is
7+no horizontal overflow, no console error, that the summary chips and the table
8+rendered, and that a row opens the detail drawer. Screenshots land in docs/ for
9+the README. Skips cleanly (exit 0) when Playwright is not installed, so the
10+offline suite stays dependency-free.
11+
12+ python3 tests/e2e.py # run if Playwright is available
13+ python3 tests/e2e.py --strict # exit 2 when Playwright is missing
14+"""
15+
16+import argparse
17+import http.server
18+import os
19+import shutil
20+import socketserver
21+import subprocess
22+import sys
23+import tempfile
24+import threading
25+from urllib.parse import urlparse
26+
27+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
28+BIN = os.path.join(ROOT, "plugin_gitstat")
29+DOCS = os.path.join(ROOT, "docs")
30+VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
31+THEMES = ["dark", "light"]
32+
33+GITENV = {
34+ "GIT_AUTHOR_NAME": "Gitstat E2E",
35+ "GIT_AUTHOR_EMAIL": "gitstat@example.invalid",
36+ "GIT_COMMITTER_NAME": "Gitstat E2E",
37+ "GIT_COMMITTER_EMAIL": "gitstat@example.invalid",
38+ "GIT_CONFIG_GLOBAL": os.devnull,
39+ "GIT_CONFIG_NOSYSTEM": "1",
40+ "GIT_TERMINAL_PROMPT": "0",
41+}
42+
43+
44+def git(cwd, *args):
45+ env = dict(os.environ)
46+ env.update(GITENV)
47+ return subprocess.run(["git", "-C", cwd] + list(args), env=env,
48+ check=True, capture_output=True)
49+
50+
51+def mkrepo(path, branch="main"):
52+ os.makedirs(path, exist_ok=True)
53+ git(path, "init", "-q", "-b", branch)
54+ git(path, "config", "user.name", "Gitstat E2E")
55+ git(path, "config", "user.email", "gitstat@example.invalid")
56+
57+
58+def build_fixtures(base):
59+ """Four repos, one per interesting visual state."""
60+ roots = os.path.join(base, "roots")
61+ os.makedirs(roots)
62+
63+ # clean, in sync with an upstream
64+ up = os.path.join(base, "up.git")
65+ git(base, "init", "-q", "--bare", up)
66+ git(up, "symbolic-ref", "HEAD", "refs/heads/main")
67+ seed = os.path.join(base, "seed")
68+ mkrepo(seed)
69+ with open(os.path.join(seed, "README.md"), "w", encoding="utf-8") as f:
70+ f.write("seed\n")
71+ git(seed, "add", "README.md")
72+ git(seed, "commit", "-q", "-m", "Add the README that everything else builds on")
73+ git(seed, "remote", "add", "origin", up)
74+ git(seed, "push", "-q", "-u", "origin", "main")
75+ git(base, "clone", "-q", up, os.path.join(roots, "portal-web"))
76+ c = os.path.join(roots, "portal-web")
77+ git(c, "config", "user.name", "Gitstat E2E")
78+ git(c, "config", "user.email", "gitstat@example.invalid")
79+
80+ # dirty working tree
81+ d = os.path.join(roots, "billing-service")
82+ mkrepo(d)
83+ for name in ("main.c", "util.c", "notes.md"):
84+ with open(os.path.join(d, name), "w", encoding="utf-8") as f:
85+ f.write("x\n")
86+ git(d, "add", ".")
87+ git(d, "commit", "-q", "-m", "Split the invoice renderer out of the billing loop")
88+ with open(os.path.join(d, "main.c"), "a", encoding="utf-8") as f:
89+ f.write("patched\n")
90+ with open(os.path.join(d, "util.c"), "a", encoding="utf-8") as f:
91+ f.write("staged\n")
92+ git(d, "add", "util.c")
93+ with open(os.path.join(d, "untracked.txt"), "w", encoding="utf-8") as f:
94+ f.write("new\n")
95+
96+ # ahead by two, with a stash
97+ a = os.path.join(roots, "fleet-agent")
98+ up2 = os.path.join(base, "up2.git")
99+ git(base, "init", "-q", "--bare", up2)
100+ git(up2, "symbolic-ref", "HEAD", "refs/heads/main")
101+ seed2 = os.path.join(base, "seed2")
102+ mkrepo(seed2)
103+ with open(os.path.join(seed2, "a.txt"), "w", encoding="utf-8") as f:
104+ f.write("a\n")
105+ git(seed2, "add", "a.txt")
106+ git(seed2, "commit", "-q", "-m", "Start the agent loop")
107+ git(seed2, "remote", "add", "origin", up2)
108+ git(seed2, "push", "-q", "-u", "origin", "main")
109+ git(base, "clone", "-q", up2, a)
110+ git(a, "config", "user.name", "Gitstat E2E")
111+ git(a, "config", "user.email", "gitstat@example.invalid")
112+ for msg in ("Teach the agent to retry a dropped socket",
113+ "Cap the retry backoff at thirty seconds"):
114+ with open(os.path.join(a, "a.txt"), "a", encoding="utf-8") as f:
115+ f.write(msg + "\n")
116+ git(a, "commit", "-q", "-am", msg)
117+ with open(os.path.join(a, "a.txt"), "a", encoding="utf-8") as f:
118+ f.write("wip\n")
119+ git(a, "stash", "push", "-q", "-m", "half-finished backoff rewrite")
120+
121+ # detached
122+ x = os.path.join(roots, "proto-sandbox")
123+ mkrepo(x)
124+ with open(os.path.join(x, "p.txt"), "w", encoding="utf-8") as f:
125+ f.write("p\n")
126+ git(x, "add", "p.txt")
127+ git(x, "commit", "-q", "-m", "First prototype of the graph walker")
128+ with open(os.path.join(x, "p.txt"), "a", encoding="utf-8") as f:
129+ f.write("q\n")
130+ git(x, "commit", "-q", "-am", "Walk depth-first instead")
131+ git(x, "checkout", "-q", "HEAD~1")
132+ return roots
133+
134+
135+class Handler(http.server.BaseHTTPRequestHandler):
136+ roots = ""
137+ allow_fetch = "0"
138+
139+ def _run(self, method):
140+ u = urlparse(self.path)
141+ env = dict(os.environ)
142+ env["QUERY_STRING"] = u.query
143+ env["REQUEST_METHOD"] = method
144+ env.pop("BOT_PASSWORD", None)
145+ env["GITSTAT_ONLY_ROOTS"] = "1"
146+ env["GITSTAT_ROOTS"] = self.roots
147+ env["GITSTAT_ALLOW_FETCH"] = self.allow_fetch
148+ out = subprocess.run([BIN], capture_output=True, env=env, timeout=60).stdout
149+ sep = out.find(b"\r\n\r\n")
150+ headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
151+ body = out[sep + 4:] if sep >= 0 else out
152+ ctype = "text/html; charset=utf-8"
153+ status = 200
154+ for line in headers.splitlines():
155+ low = line.lower()
156+ if low.startswith("content-type:"):
157+ ctype = line.split(":", 1)[1].strip()
158+ if low.startswith("status:"):
159+ try:
160+ status = int(line.split(":", 1)[1].split()[0])
161+ except (IndexError, ValueError):
162+ status = 200
163+ self.send_response(status)
164+ self.send_header("Content-Type", ctype)
165+ self.send_header("Cache-Control", "no-store")
166+ self.send_header("Content-Length", str(len(body)))
167+ self.end_headers()
168+ self.wfile.write(body)
169+
170+ def do_GET(self): # noqa: N802
171+ self._run("GET")
172+
173+ def do_POST(self): # noqa: N802
174+ self._run("POST")
175+
176+ def log_message(self, *_a):
177+ pass
178+
179+
180+def main():
181+ ap = argparse.ArgumentParser()
182+ ap.add_argument("--strict", action="store_true")
183+ args = ap.parse_args()
184+
185+ if not os.path.exists(BIN):
186+ print("plugin_gitstat is not built; run make first", file=sys.stderr)
187+ return 1
188+
189+ try:
190+ from playwright.sync_api import sync_playwright
191+ except Exception:
192+ msg = "playwright not installed - skipping viewport e2e"
193+ if args.strict:
194+ print(msg, file=sys.stderr)
195+ return 2
196+ print(msg)
197+ return 0
198+
199+ base = tempfile.mkdtemp(prefix="gitstat-e2e-")
200+ try:
201+ roots = build_fixtures(base)
202+ except subprocess.CalledProcessError as exc:
203+ print("cannot build the git fixtures: %s" % exc, file=sys.stderr)
204+ shutil.rmtree(base, ignore_errors=True)
205+ return 1
206+
207+ Handler.roots = roots
208+ os.makedirs(DOCS, exist_ok=True)
209+
210+ failures = []
211+ with socketserver.TCPServer(("127.0.0.1", 0), Handler) as srv:
212+ port = srv.server_address[1]
213+ threading.Thread(target=srv.serve_forever, daemon=True).start()
214+ url_base = "http://127.0.0.1:%d/plugin_gitstat" % port
215+
216+ with sync_playwright() as p:
217+ browser = p.chromium.launch()
218+ for (w, h) in VIEWPORTS:
219+ for theme in THEMES:
220+ url = "%s?theme=%s" % (url_base, theme)
221+ page = browser.new_page(viewport={"width": w, "height": h})
222+ errors = []
223+ page.on("console", lambda m: errors.append(m.text)
224+ if m.type == "error" else None)
225+ page.on("pageerror", lambda e: errors.append(str(e)))
226+ page.goto(url, wait_until="load")
227+ page.wait_for_timeout(1200)
228+
229+ sw = page.evaluate("document.documentElement.scrollWidth")
230+ iw = page.evaluate("window.innerWidth")
231+ if sw > iw + 1:
232+ failures.append("%dx%d %s horizontal overflow %d > %d"
233+ % (w, h, theme, sw, iw))
234+
235+ applied = page.evaluate(
236+ "document.documentElement.getAttribute('data-theme')")
237+ if applied != theme:
238+ failures.append("%dx%d %s ?theme= did not apply (%r)"
239+ % (w, h, theme, applied))
240+
241+ total = page.evaluate(
242+ "document.getElementById('vAll').textContent")
243+ if total.strip() != "4":
244+ failures.append("%dx%d %s All chip says %r, want 4"
245+ % (w, h, theme, total))
246+
247+ rows = page.evaluate(
248+ "document.querySelectorAll('#rows tr.row').length")
249+ if rows != 4:
250+ failures.append("%dx%d %s table has %d rows, want 4"
251+ % (w, h, theme, rows))
252+
253+ dirty_v = page.evaluate(
254+ "document.getElementById('vDirty').textContent")
255+ if dirty_v.strip() != "1":
256+ failures.append("%dx%d %s Dirty chip says %r, want 1"
257+ % (w, h, theme, dirty_v))
258+
259+ stash_v = page.evaluate(
260+ "document.getElementById('vStash').textContent")
261+ if stash_v.strip() != "1":
262+ failures.append("%dx%d %s Stash chip says %r, want 1"
263+ % (w, h, theme, stash_v))
264+
265+ # the dirty repo must sort first
266+ first = page.evaluate(
267+ "document.querySelector('#rows tr.row .name').textContent")
268+ if first != "billing-service":
269+ failures.append("%dx%d %s first row is %r, want the dirty repo"
270+ % (w, h, theme, first))
271+
272+ # search narrows the list
273+ page.fill("#q", "sandbox")
274+ page.wait_for_timeout(250)
275+ narrowed = page.evaluate(
276+ "document.querySelectorAll('#rows tr.row').length")
277+ if narrowed != 1:
278+ failures.append("%dx%d %s search left %d rows, want 1"
279+ % (w, h, theme, narrowed))
280+ page.fill("#q", "")
281+ page.wait_for_timeout(250)
282+
283+ # the detail drawer opens with the changed file list
284+ page.click("#rows tr.row")
285+ page.wait_for_timeout(700)
286+ opened = page.evaluate(
287+ "document.getElementById('drawer').classList.contains('open')")
288+ if not opened:
289+ failures.append("%dx%d %s drawer did not open"
290+ % (w, h, theme))
291+ else:
292+ files = page.evaluate(
293+ "document.querySelectorAll('#dBody .flist li').length")
294+ if files < 1:
295+ failures.append("%dx%d %s drawer listed no changed files"
296+ % (w, h, theme))
297+ commits = page.evaluate(
298+ "document.querySelectorAll('#dBody .clist li').length")
299+ if commits < 1:
300+ failures.append("%dx%d %s drawer listed no commits"
301+ % (w, h, theme))
302+ dsw = page.evaluate("document.documentElement.scrollWidth")
303+ diw = page.evaluate("window.innerWidth")
304+ if dsw > diw + 1:
305+ failures.append("%dx%d %s drawer overflow %d > %d"
306+ % (w, h, theme, dsw, diw))
307+ page.click("#dClose")
308+ page.wait_for_timeout(350)
309+
310+ if errors:
311+ failures.append("%dx%d %s console errors: %s"
312+ % (w, h, theme, errors[:3]))
313+
314+ shot = os.path.join(DOCS, "ui-%d-%s.png" % (w, theme))
315+ page.screenshot(path=shot, full_page=False)
316+ page.close()
317+ browser.close()
318+
319+ shutil.rmtree(base, ignore_errors=True)
320+
321+ if failures:
322+ print("e2e failures:")
323+ for f in failures:
324+ print(" - %s" % f)
325+ return 1
326+ print("e2e ok: %d viewports x %d themes, screenshots in docs/"
327+ % (len(VIEWPORTS), len(THEMES)))
328+ return 0
329+
330+
331+if __name__ == "__main__":
332+ sys.exit(main())
tests/run.sh+541−0■■■■■
11new file mode 100755
index 0000000..3961ee8
--- /dev/null
+++ b/tests/run.sh
@@ -0,0 +1,541 @@
1+#!/bin/sh
2+# tests/run.sh - offline checks for plugin_gitstat across all 3 modes.
3+#
4+# Everything runs against ./plugin_gitstat (native build). The repository trees
5+# are real git repos built in a temp directory, so the status parser, the
6+# ahead/behind counter, the stash counter, the detached and unborn states and
7+# the credential redaction are all exercised against git's own output rather
8+# than our idea of it. GITSTAT_ONLY_ROOTS=1 pins the allowed roots to that temp
9+# directory so a developer machine full of checkouts cannot affect the result.
10+#
11+# Optional cross-target artifacts (musl, aarch64, PE) are checked when present.
12+# The last section audits the whole git history for secrets and LAN addresses.
13+#
14+# Exit code 0 = everything passed.
15+
16+set -u
17+
18+ROOT=$(cd "$(dirname "$0")/.." && pwd)
19+cd "$ROOT" || exit 1
20+
21+BIN=./plugin_gitstat
22+PASS=0
23+FAIL=0
24+
25+if [ -t 1 ]; then
26+ C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
27+else
28+ C_OK=; C_BAD=; C_B=; C_0=
29+fi
30+pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
31+fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
32+
33+check() { # check <desc> <expected-substring> <actual>
34+ if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
35+ fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 500)"
36+ fi
37+}
38+
39+check_not() { # check_not <desc> <forbidden-substring> <actual>
40+ if printf '%s' "$3" | grep -F -q -- "$2"; then
41+ fail "$1 (must NOT contain: $2)"; else pass "$1"
42+ fi
43+}
44+
45+section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
46+
47+body() { # strip CGI headers if present, drop CRs, keep the payload
48+ printf '%s\n' "$1" | tr -d '\r' | awk '
49+ BEGIN { inhdr = 0 }
50+ NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|Content-Security-Policy):/) { inhdr = 1; next }
51+ inhdr && $0 == "" { inhdr = 0; next }
52+ inhdr { next }
53+ { print }
54+ '
55+}
56+
57+hdr() { printf '%s\n' "$1" | tr -d '\r' | sed -n '1p'; }
58+
59+json_ok() { # json_ok <desc> <json> [python-expression on d]
60+ expr=${3:-True}
61+ if printf '%s' "$2" | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if ($expr) else 1)" 2>/dev/null; then
62+ pass "$1"
63+ else
64+ fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 500)"
65+ fi
66+}
67+
68+run() { # run <query-string> [extra env assignments...] -> raw output
69+ qs="$1"; shift
70+ env QUERY_STRING="$qs" "$@" $BIN 2>&1
71+}
72+
73+api() { body "$(run "$1")"; }
74+
75+# ---------------------------------------------------------------- setup
76+section "build"
77+if [ ! -x "$BIN" ]; then
78+ echo " building native binary..."
79+ cc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src \
80+ -o "$BIN" src/plugin_gitstat.c || { echo " build failed"; exit 1; }
81+fi
82+[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing"
83+
84+WORK=$(mktemp -d "${TMPDIR:-/tmp}/gitstat-tests-XXXXXX") || exit 1
85+trap 'rm -rf "$WORK"' EXIT
86+
87+GIT_AUTHOR_NAME="Gitstat Test"; export GIT_AUTHOR_NAME
88+GIT_AUTHOR_EMAIL="gitstat@example.invalid"; export GIT_AUTHOR_EMAIL
89+GIT_COMMITTER_NAME="Gitstat Test"; export GIT_COMMITTER_NAME
90+GIT_COMMITTER_EMAIL="gitstat@example.invalid"; export GIT_COMMITTER_EMAIL
91+GIT_CONFIG_GLOBAL=/dev/null; export GIT_CONFIG_GLOBAL
92+GIT_CONFIG_NOSYSTEM=1; export GIT_CONFIG_NOSYSTEM
93+GIT_TERMINAL_PROMPT=0; export GIT_TERMINAL_PROMPT
94+
95+ROOTS="$WORK/roots"
96+mkdir -p "$ROOTS"
97+
98+mkrepo() { # mkrepo <dir> <branch>
99+ mkdir -p "$1"
100+ git -C "$1" init -q -b "$2"
101+ git -C "$1" config user.name "Gitstat Test"
102+ git -C "$1" config user.email "gitstat@example.invalid"
103+}
104+
105+# A bare upstream with one commit in it, cloned into <dir>. Using a real clone
106+# rather than init+remote means the upstream refs actually exist, which is what
107+# the ahead/behind counters read.
108+mkclone() { # mkclone <dir> <branch>
109+ up="$WORK/up-$(basename "$1").git"
110+ seed="$WORK/seed-$(basename "$1")"
111+ git init -q --bare "$up"
112+ git -C "$up" symbolic-ref HEAD "refs/heads/$2"
113+ mkrepo "$seed" "$2"
114+ printf 'base\n' > "$seed/base.txt"
115+ git -C "$seed" add base.txt
116+ git -C "$seed" commit -q -m "base commit"
117+ git -C "$seed" remote add origin "$up"
118+ git -C "$seed" push -q -u origin "$2"
119+ git clone -q "$up" "$1"
120+ git -C "$1" config user.name "Gitstat Test"
121+ git -C "$1" config user.email "gitstat@example.invalid"
122+}
123+
124+# 1. clean repo with an upstream, fully in sync
125+mkclone "$ROOTS/cleanrepo" main
126+
127+# 2. dirty repo: one modified file, one untracked file, one staged file
128+mkrepo "$ROOTS/dirtyrepo" main
129+printf 'one\n' > "$ROOTS/dirtyrepo/keep.txt"
130+printf 'two\n' > "$ROOTS/dirtyrepo/mod.txt"
131+printf 'three\n' > "$ROOTS/dirtyrepo/add.txt"
132+git -C "$ROOTS/dirtyrepo" add keep.txt mod.txt add.txt
133+git -C "$ROOTS/dirtyrepo" commit -q -m "seed three files"
134+printf 'modified\n' >> "$ROOTS/dirtyrepo/mod.txt"
135+printf 'staged\n' >> "$ROOTS/dirtyrepo/add.txt"
136+git -C "$ROOTS/dirtyrepo" add add.txt
137+printf 'untracked\n' > "$ROOTS/dirtyrepo/new.txt"
138+
139+# 3. ahead repo: two local commits past its upstream, plus a stash
140+mkclone "$ROOTS/aheadrepo" main
141+printf 'a\n' >> "$ROOTS/aheadrepo/base.txt"
142+git -C "$ROOTS/aheadrepo" commit -q -am "local commit one"
143+printf 'b\n' >> "$ROOTS/aheadrepo/base.txt"
144+git -C "$ROOTS/aheadrepo" commit -q -am "local commit two"
145+printf 'stashed\n' >> "$ROOTS/aheadrepo/base.txt"
146+git -C "$ROOTS/aheadrepo" stash push -q -m "work in progress"
147+
148+# 3b. behind repo: its upstream has moved on
149+mkclone "$ROOTS/behindrepo" main
150+other="$WORK/other-behindrepo"
151+git clone -q "$WORK/up-behindrepo.git" "$other"
152+git -C "$other" config user.name "Gitstat Test"
153+git -C "$other" config user.email "gitstat@example.invalid"
154+printf 'upstream\n' >> "$other/base.txt"
155+git -C "$other" commit -q -am "upstream moved on"
156+git -C "$other" push -q origin main
157+git -C "$ROOTS/behindrepo" fetch -q origin
158+
159+# 4. detached repo
160+mkrepo "$ROOTS/detachedrepo" main
161+printf 'd\n' > "$ROOTS/detachedrepo/d.txt"
162+git -C "$ROOTS/detachedrepo" add d.txt
163+git -C "$ROOTS/detachedrepo" commit -q -m "detach me"
164+printf 'd2\n' >> "$ROOTS/detachedrepo/d.txt"
165+git -C "$ROOTS/detachedrepo" commit -q -am "second commit"
166+git -C "$ROOTS/detachedrepo" checkout -q HEAD~1
167+
168+# 5. unborn repo: initialised, nothing committed
169+mkrepo "$ROOTS/unbornrepo" main
170+
171+# 6. repo whose origin URL carries userinfo (must be redacted)
172+mkclone "$ROOTS/secretremote" main
173+git -C "$ROOTS/secretremote" remote set-url origin \
174+ "https://plantuser:planttoken123@example.invalid/x.git"
175+
176+# 7. a nested repo two levels deep, to prove the walk descends
177+mkdir -p "$ROOTS/group/nested"
178+mkrepo "$ROOTS/group/nested/deeprepo" main
179+printf 'n\n' > "$ROOTS/group/nested/deeprepo/n.txt"
180+git -C "$ROOTS/group/nested/deeprepo" add n.txt
181+git -C "$ROOTS/group/nested/deeprepo" commit -q -m "nested seed"
182+
183+# 8. a directory with no .git at all (must be ignored)
184+mkdir -p "$ROOTS/notarepo"
185+
186+ROOTENV="GITSTAT_ONLY_ROOTS=1"
187+ROOTVAR="GITSTAT_ROOTS=$ROOTS"
188+
189+# ---------------------------------------------------------------- --meta
190+section "--meta / discovery"
191+META=$($BIN --meta)
192+check "--meta prints name git" '"name":"git"' "$META"
193+check "--meta prints desc Repo status" '"desc":"Repo status"' "$META"
194+json_ok "--meta is valid JSON with exactly 2 keys" "$META" "sorted(d.keys())==['desc','name']"
195+SXMETA=$(env SX_PLUGIN_META=1 $BIN)
196+check "SX_PLUGIN_META=1 returns the metadata" '"name":"git"' "$SXMETA"
197+METAQ=$(env SX_PLUGIN_META=1 QUERY_STRING="action=repos" $BIN)
198+check "--meta wins over the query string" '"name":"git"' "$METAQ"
199+DESCLEN=$(printf '%s' "$META" | python3 -c "import json,sys;print(len(json.load(sys.stdin)['desc']))")
200+[ "$DESCLEN" -le 15 ] && pass "desc is <= 15 chars ($DESCLEN)" || fail "desc too long ($DESCLEN)"
201+
202+# ---------------------------------------------------------------- auth
203+section "node authentication"
204+UNAUTH=$(env BOT_PASSWORD=testpw QUERY_STRING="action=repos" \
205+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
206+check "unauthenticated action=repos is 401" "Status: 401 Unauthorized" "$UNAUTH"
207+check "401 body carries the error" '"error":"invalid node password"' "$UNAUTH"
208+
209+OKPW=$(env BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw QUERY_STRING="action=repos" \
210+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
211+check "X-Bot-Password is accepted" '"ok":true' "$OKPW"
212+
213+OKBR=$(env BOT_PASSWORD=testpw HTTP_AUTHORIZATION="Bearer testpw" QUERY_STRING="action=repos" \
214+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
215+check "Authorization: Bearer is accepted" '"ok":true' "$OKBR"
216+
217+OKQP=$(env BOT_PASSWORD=testpw QUERY_STRING="action=repos&pwd=testpw" \
218+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
219+check "?pwd= is accepted" '"ok":true' "$OKQP"
220+
221+BADPW=$(env BOT_PASSWORD=testpw QUERY_STRING="action=repos&pwd=nope" \
222+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
223+check "wrong ?pwd= is 401" "Status: 401 Unauthorized" "$BADPW"
224+
225+UNAUTHH=$(env BOT_PASSWORD=testpw QUERY_STRING="" \
226+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
227+check "unauthenticated HTML page is 401 too" "Status: 401 Unauthorized" "$UNAUTHH"
228+
229+METAOK=$(env BOT_PASSWORD=testpw SX_PLUGIN_META=1 $BIN)
230+check "--meta stays unauthenticated so discovery works" '"name":"git"' "$METAOK"
231+
232+NOAUTH=$(env QUERY_STRING="action=repos" GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
233+check "no BOT_PASSWORD means auth is a no-op" '"ok":true' "$NOAUTH"
234+
235+# ---------------------------------------------------------------- repos
236+section "?action=repos"
237+REPOS=$(env QUERY_STRING="action=repos" GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
238+REPOSB=$(body "$REPOS")
239+check "repos answers JSON" "Content-Type: application/json" "$REPOS"
240+json_ok "repos doc is valid" "$REPOSB"
241+json_ok "repos reports ok" "$REPOSB" "d['ok'] is True"
242+json_ok "repos has a summary" "$REPOSB" "'summary' in d and 'dirty' in d['summary']"
243+json_ok "repos has a roots array with per-root counts" "$REPOSB" \
244+ "len(d['roots'])==1 and d['roots'][0]['count']==8 and d['roots'][0]['exists']"
245+json_ok "repos found the 8 fixture repos" "$REPOSB" "d['count']==8"
246+json_ok "the plain directory is not a repo" "$REPOSB" \
247+ "not any('notarepo' in r['path'] for r in d['repos'])"
248+json_ok "the nested repo was found at depth 3" "$REPOSB" \
249+ "any(r['name']=='deeprepo' for r in d['repos'])"
250+json_ok "the first repo is a dirty one (dirty-first sort)" "$REPOSB" "d['repos'][0]['dirty']>0"
251+json_ok "every repo has the documented field set" "$REPOSB" \
252+ "all(set(r)>=set(['path','name','root','branch','upstream','ahead','behind','dirty','untracked','staged','conflicted','stash','detached','no_upstream','unborn','last_commit']) for r in d['repos'])"
253+json_ok "last_commit has hash/ct/at/subject" "$REPOSB" \
254+ "all(set(r['last_commit'])>=set(['hash','short','ct','at','subject']) for r in d['repos'])"
255+json_ok "checked_at is an ISO-Z stamp" "$REPOSB" "d['checked_at'].endswith('Z')"
256+
257+# per-repo assertions
258+DIRTY=$(printf '%s' "$REPOSB" | python3 -c "
259+import json,sys
260+d=json.load(sys.stdin)
261+print(json.dumps([r for r in d['repos'] if r['name']=='dirtyrepo'][0]))")
262+json_ok "dirtyrepo counts 3 changed entries" "$DIRTY" "d['dirty']==3"
263+json_ok "dirtyrepo counts 1 untracked" "$DIRTY" "d['untracked']==1"
264+json_ok "dirtyrepo is not detached and has a branch" "$DIRTY" \
265+ "d['detached'] is False and d['branch']=='main'"
266+
267+CLEAN=$(printf '%s' "$REPOSB" | python3 -c "
268+import json,sys
269+d=json.load(sys.stdin)
270+print(json.dumps([r for r in d['repos'] if r['name']=='cleanrepo'][0]))")
271+json_ok "cleanrepo is clean" "$CLEAN" "d['dirty']==0"
272+json_ok "cleanrepo is in sync with its upstream" "$CLEAN" "d['ahead']==0 and d['behind']==0"
273+json_ok "cleanrepo has an upstream" "$CLEAN" "d['no_upstream'] is False and d['upstream']"
274+json_ok "cleanrepo carried its last commit" "$CLEAN" "d['last_commit']['subject']=='base commit'"
275+
276+AHEAD=$(printf '%s' "$REPOSB" | python3 -c "
277+import json,sys
278+d=json.load(sys.stdin)
279+print(json.dumps([r for r in d['repos'] if r['name']=='aheadrepo'][0]))")
280+json_ok "aheadrepo is 2 ahead" "$AHEAD" "d['ahead']==2"
281+json_ok "aheadrepo is not behind" "$AHEAD" "d['behind']==0"
282+json_ok "aheadrepo counted its stash" "$AHEAD" "d['stash']==1"
283+json_ok "aheadrepo last subject is the newest commit" "$AHEAD" \
284+ "d['last_commit']['subject']=='local commit two'"
285+
286+DET=$(printf '%s' "$REPOSB" | python3 -c "
287+import json,sys
288+d=json.load(sys.stdin)
289+print(json.dumps([r for r in d['repos'] if r['name']=='detachedrepo'][0]))")
290+json_ok "detachedrepo is flagged detached" "$DET" "d['detached'] is True"
291+json_ok "detachedrepo branch reads detached" "$DET" "d['branch']=='detached'"
292+
293+UNB=$(printf '%s' "$REPOSB" | python3 -c "
294+import json,sys
295+d=json.load(sys.stdin)
296+print(json.dumps([r for r in d['repos'] if r['name']=='unbornrepo'][0]))")
297+json_ok "unbornrepo is flagged unborn" "$UNB" "d['unborn'] is True"
298+json_ok "unbornrepo has no upstream" "$UNB" "d['no_upstream'] is True"
299+
300+SEC=$(printf '%s' "$REPOSB" | python3 -c "
301+import json,sys
302+d=json.load(sys.stdin)
303+print(json.dumps([r for r in d['repos'] if r['name']=='secretremote'][0]))")
304+check_not "credential in the origin URL is redacted (token)" "planttoken123" "$SEC"
305+check_not "credential in the origin URL is redacted (user)" "plantuser" "$SEC"
306+check "redacted remote keeps the host" "example.invalid/x.git" "$SEC"
307+check_not "the remote field carries no userinfo" "plantuser" "$(printf '%s' "$SEC" | python3 -c "import json,sys;print(json.load(sys.stdin)['remote'])")"
308+
309+check_not "no path outside the root is reported" "$WORK/upstream.git" "$REPOSB"
310+
311+# summary counters
312+json_ok "summary counts the dirty repos" "$REPOSB" "d['summary']['dirty']>=1"
313+json_ok "summary counts the ahead repo" "$REPOSB" "d['summary']['ahead']>=1"
314+json_ok "summary counts the behind repo" "$REPOSB" "d['summary']['behind']>=1"
315+BEHIND=$(printf '%s' "$REPOSB" | python3 -c "
316+import json,sys
317+d=json.load(sys.stdin)
318+print(json.dumps([r for r in d['repos'] if r['name']=='behindrepo'][0]))")
319+json_ok "behindrepo is 1 behind" "$BEHIND" "d['behind']==1"
320+json_ok "behindrepo is not ahead" "$BEHIND" "d['ahead']==0"
321+json_ok "behindrepo still has an upstream" "$BEHIND" "d['no_upstream'] is False"
322+json_ok "summary counts the stashes" "$REPOSB" "d['summary']['stashes']>=1"
323+json_ok "summary counts the detached repo" "$REPOSB" "d['summary']['detached']==1"
324+
325+# empty root
326+EMPTY=$(env QUERY_STRING="action=repos" GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$WORK/nowhere" $BIN)
327+json_ok "a missing root reports exists:false" "$(body "$EMPTY")" \
328+ "d['roots'][0]['exists'] is False and d['count']==0"
329+
330+# per-root budget: two roots are counted independently
331+mkdir -p "$WORK/r1" "$WORK/r2"
332+cp -a "$ROOTS/cleanrepo" "$WORK/r1/one"
333+cp -a "$ROOTS/cleanrepo" "$WORK/r1/two"
334+cp -a "$ROOTS/cleanrepo" "$WORK/r2/three"
335+TWOROOT=$(env QUERY_STRING="action=repos" GITSTAT_ONLY_ROOTS=1 \
336+ GITSTAT_ROOTS="$WORK/r1:$WORK/r2" $BIN)
337+json_ok "two roots keep independent counts" "$(body "$TWOROOT")" \
338+ "len(d['roots'])==2 and d['roots'][0]['count']==2 and d['roots'][1]['count']==1"
339+json_ok "the global table is that of both roots" "$(body "$TWOROOT")" "d['count']==3"
340+
341+# a duplicate root listing is de-duplicated, not double counted
342+DUPR=$(env QUERY_STRING="action=repos" GITSTAT_ONLY_ROOTS=1 \
343+ GITSTAT_ROOTS="$WORK/r1:$WORK/r1" $BIN)
344+json_ok "a repeated root is de-duplicated" "$(body "$DUPR")" \
345+ "len(d['roots'])==1 and d['count']==2"
346+
347+# ---------------------------------------------------------------- repo detail
348+section "?action=repo&path="
349+RP="env QUERY_STRING=action=repo\&path=$ROOTS/dirtyrepo GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS=$ROOTS"
350+DETAIL=$(env QUERY_STRING="action=repo&path=$ROOTS/dirtyrepo" \
351+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
352+DETB=$(body "$DETAIL")
353+check "repo detail answers JSON" "Content-Type: application/json" "$DETAIL"
354+json_ok "repo detail is valid" "$DETB"
355+json_ok "repo detail reports ok" "$DETB" "d['ok'] is True"
356+json_ok "repo detail has the repo block" "$DETB" "d['repo']['name']=='dirtyrepo'"
357+json_ok "repo detail lists 3 changed files" "$DETB" "len(d['changed'])==3"
358+json_ok "repo detail marks the untracked file" "$DETB" \
359+ "any(c['code']=='??' and c['path']=='new.txt' for c in d['changed'])"
360+json_ok "repo detail marks the modified file" "$DETB" \
361+ "any(c['path']=='mod.txt' and c['code'][1]=='M' for c in d['changed'])"
362+json_ok "repo detail marks the staged file" "$DETB" \
363+ "any(c['path']=='add.txt' and c['code'][0]=='M' for c in d['changed'])"
364+json_ok "repo detail has recent commits" "$DETB" "len(d['commits'])>=1"
365+json_ok "each commit has hash/ct/author/subject" "$DETB" \
366+ "all(set(c)>=set(['hash','ct','author','subject']) for c in d['commits'])"
367+json_ok "changed_count is reported" "$DETB" "d['changed_count']==3"
368+
369+AHEADD=$(env QUERY_STRING="action=repo&path=$ROOTS/aheadrepo" \
370+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
371+json_ok "detail of a repo with commits lists newest first" "$(body "$AHEADD")" \
372+ "d['commits'][0]['subject']=='local commit two'"
373+json_ok "detail caps commits at 20" "$(body "$AHEADD")" "len(d['commits'])<=20"
374+
375+# path allowlisting
376+OUTSIDE=$(env QUERY_STRING="action=repo&path=/etc" \
377+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
378+check "a path outside every root is 403" "Status: 403 Forbidden" "$OUTSIDE"
379+check "403 explains why" "not in an allowlisted root" "$OUTSIDE"
380+
381+DOTDOT=$(env QUERY_STRING="action=repo&path=$ROOTS/../etc" \
382+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
383+check "a .. traversal is refused" "Status: 403 Forbidden" "$DOTDOT"
384+
385+NOTREPO=$(env QUERY_STRING="action=repo&path=$ROOTS/notarepo" \
386+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
387+check "a directory without .git is refused" "Status: 403 Forbidden" "$NOTREPO"
388+
389+EMPTYP=$(env QUERY_STRING="action=repo&path=" \
390+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
391+check "a missing path argument is refused" "Status: 403 Forbidden" "$EMPTYP"
392+
393+# ---------------------------------------------------------------- fetch
394+section "?action=fetch"
395+NOFETCH=$(env QUERY_STRING="action=fetch&path=$ROOTS/cleanrepo" REQUEST_METHOD=POST \
396+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
397+check "fetch is disabled by default" '"ok":false' "$NOFETCH"
398+check "fetch says how to enable it" "GITSTAT_ALLOW_FETCH" "$NOFETCH"
399+
400+GETFETCH=$(env QUERY_STRING="action=fetch&path=$ROOTS/cleanrepo" \
401+ GITSTAT_ALLOW_FETCH=1 GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
402+check "fetch is POST only" "fetch is POST only" "$GETFETCH"
403+
404+FETCHOUT=$(env QUERY_STRING="action=fetch&path=$ROOTS/cleanrepo" REQUEST_METHOD=POST \
405+ GITSTAT_ALLOW_FETCH=1 GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
406+FB=$(body "$FETCHOUT")
407+json_ok "enabled fetch returns a JSON document" "$FB"
408+json_ok "enabled fetch of a clean repo succeeds" "$FB" "d['ok'] is True and d['exit']==0"
409+json_ok "fetch echoes the branch and sync state" "$FB" "'branch' in d and 'ahead' in d"
410+
411+FETCHBAD=$(env QUERY_STRING="action=fetch&path=/etc" REQUEST_METHOD=POST \
412+ GITSTAT_ALLOW_FETCH=1 GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
413+check "fetch of a path outside the roots is 403" "Status: 403 Forbidden" "$FETCHBAD"
414+
415+# ---------------------------------------------------------------- other actions
416+UNKNOWN=$(env QUERY_STRING="action=bogus" GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
417+check "an unknown action answers an error document" '"error":"unknown action"' "$UNKNOWN"
418+
419+FMT=$(env QUERY_STRING="format=json" GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
420+check "format=json is served as JSON" "Content-Type: application/json" "$FMT"
421+json_ok "format=json returns the repos document" "$(body "$FMT")" "d['action']=='repos'"
422+
423+# ---------------------------------------------------------------- HTML
424+section "HTML UI"
425+HTML=$(env QUERY_STRING="" GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
426+check "GET answers HTML" "Content-Type: text/html" "$HTML"
427+check "the page has a doctype" "<!DOCTYPE html>" "$HTML"
428+check "the page names the product" "SCORPIOX BOT" "$HTML"
429+check "the page sets the token block" "--bg:#000000" "$HTML"
430+check "the page carries the light token block" "data-theme=light" "$HTML"
431+check "the page carries the prepaint script" "sx-theme-request" "$HTML"
432+check "the page carries the handoff listener" "sx-theme" "$HTML"
433+check_not "no external script is referenced" "<script src=" "$HTML"
434+check_not "no CDN is referenced" "cdn." "$HTML"
435+check_not "no http URL is referenced in the page" "http://" "$HTML"
436+check "the page has the rows table" 'id="rows"' "$HTML"
437+check "the page has the filter chips" 'class="chip' "$HTML"
438+check "the page has the detail drawer" 'id="drawer"' "$HTML"
439+check "the page has inline SVG icons" "<svg viewBox" "$HTML"
440+check "the page has a CSP" "Content-Security-Policy" "$HTML"
441+check "the page declares the theme toggle hidden in embed" "embed-hide" "$HTML"
442+
443+EMBED=$(env QUERY_STRING="embed=1" GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
444+check "embed=1 still serves the page" "<!DOCTYPE html>" "$EMBED"
445+check "embed=1 marks the document embedded" "embed" "$EMBED"
446+
447+# no emoji anywhere in the page
448+if printf '%s' "$HTML" | python3 -c "
449+import sys
450+s=sys.stdin.buffer.read().decode('utf-8','replace')
451+bad=[c for c in s if ord(c)>0x2100 and not (0x2010<=ord(c)<=0x2027)]
452+sys.exit(1 if bad else 0)" 2>/dev/null; then
453+ pass "no emoji in the page"
454+else
455+ fail "the page contains emoji or exotic glyphs"
456+fi
457+
458+# the hub-vs-direct route branch must be present, got wrong is the classic bug
459+check "the page branches on ?plugin= for the hub route" \
460+ "HUB ? '/plugins?plugin='" "$HTML"
461+check "the page falls back to the direct node route" "'/plugin_gitstat'" "$HTML"
462+
463+# ---------------------------------------------------------------- cross targets
464+section "cross-target artifacts"
465+if [ -f plugin_gitstat.musl ]; then
466+ file plugin_gitstat.musl | grep -q 'ELF' && pass "the musl build is an ELF" || fail "musl build is not ELF"
467+ file plugin_gitstat.musl | grep -qi 'static' && pass "the musl build is statically linked" || fail "musl build is dynamic"
468+else
469+ echo " (skip) plugin_gitstat.musl not built here"
470+fi
471+if [ -f plugin_gitstat.arm64 ]; then
472+ file plugin_gitstat.arm64 | grep -Eq 'aarch64' && pass "the arm64 build is aarch64" || fail "arm64 build is not aarch64"
473+else
474+ echo " (skip) plugin_gitstat.arm64 not built here"
475+fi
476+if [ -f plugin_gitstat.exe ]; then
477+ if head -c 2 plugin_gitstat.exe | od -An -c | grep -q 'M Z'; then
478+ pass "the Windows build starts with an MZ header"
479+ else
480+ fail "the Windows build is not a PE (no MZ header)"
481+ fi
482+else
483+ echo " (skip) plugin_gitstat.exe not built here"
484+fi
485+
486+# ---------------------------------------------------------------- generated UI
487+section "generated page"
488+if command -v python3 >/dev/null 2>&1; then
489+ if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
490+ pass "src/ui_html.h matches src/ui.html"
491+ else
492+ fail "src/ui_html.h is stale - run tools/gen_ui.py"
493+ fi
494+else
495+ echo " (skip) python3 not available"
496+fi
497+
498+# ---------------------------------------------------------------- history audit
499+section "git history secret audit"
500+if git rev-parse --git-dir >/dev/null 2>&1; then
501+ ALL="$WORK/history.txt"
502+ git log -p --all 2>/dev/null \
503+ | grep -v '^Author: ' \
504+ | grep -vE 'scan_hist|HITS=|grep -Eo|suspects=|audit "|check_not "|scan "|audit\(\)' \
505+ > "$ALL" || : > "$ALL"
506+
507+ audit() { # audit <label> <regex>
508+ H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true)
509+ if [ -n "$H" ]; then
510+ fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /'
511+ else
512+ pass "history: $1"
513+ fi
514+ }
515+ audit "no LAN addresses" '192\.168\.[0-9]+\.[0-9]+'
516+ audit "no private 10.x range" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
517+ audit "no 172.16-31 range" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
518+ audit "no GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
519+ audit "no HF token" 'hf_[A-Za-z0-9]{30,}'
520+ audit "no embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}'
521+ if command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
522+ if scorpiox-cli-botplugin audit . >"$WORK/audit.out" 2>&1; then
523+ pass "scorpiox-cli-botplugin audit passes"
524+ else
525+ fail "scorpiox-cli-botplugin audit failed"; sed 's/^/ /' "$WORK/audit.out" | head -6
526+ fi
527+ else
528+ echo " (skip) scorpiox-cli-botplugin not installed"
529+ fi
530+else
531+ echo " (skip) not a git checkout"
532+fi
533+
534+# ---------------------------------------------------------------- summary
535+printf '\n%s=================================%s\n' "$C_B" "$C_0"
536+printf ' passed %s%d%s failed %s%d%s\n' "$C_OK" "$PASS" "$C_0" \
537+ "$([ "$FAIL" -eq 0 ] && echo "$C_OK" || echo "$C_BAD")" "$FAIL" "$C_0"
538+printf '%s=================================%s\n' "$C_B" "$C_0"
539+
540+[ "$FAIL" -eq 0 ] || exit 1
541+exit 0
tools/gen_ui.py+105−0■■■■■
11new file mode 100644
index 0000000..9d9a7e1
--- /dev/null
+++ b/tools/gen_ui.py
@@ -0,0 +1,105 @@
1+#!/usr/bin/env python3
2+"""tools/gen_ui.py - compile src/ui.html into src/ui_html.h.
3+
4+The page lives in one readable file (src/ui.html) so it can be diffed and
5+reviewed like any other source. This script turns it into a single C string
6+constant with two control-character placeholders:
7+
8+ 0x01 -> the bot theme prepaint script + <style> + theme tokens
9+ 0x02 -> the bot theme handoff script (just before </body>)
10+
11+main() splits the constant on those bytes and emits the macros from
12+src/bot_theme_plugin.h in their place, so the theme can never drift out of
13+sync with the rest of the bot.
14+
15+ python3 tools/gen_ui.py # write src/ui.html.h
16+ python3 tools/gen_ui.py --check # exit 1 when the header is stale
17+"""
18+
19+import os
20+import sys
21+
22+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
23+SRC = os.path.join(ROOT, "src", "ui.html")
24+OUT = os.path.join(ROOT, "src", "ui_html.h")
25+
26+TOKENS = "<!--TOKENS-->"
27+MARK_TOKENS = "\u0001"
28+MARK_HANDOFF = "\u0002"
29+
30+
31+def c_literal(text):
32+ """Escape text for a C string literal, one line per source line."""
33+ out = []
34+ for line in text.splitlines(True):
35+ piece = []
36+ for ch in line:
37+ if ch == "\\":
38+ piece.append("\\\\")
39+ elif ch == '"':
40+ piece.append('\\"')
41+ elif ch == "\n":
42+ piece.append("\\n")
43+ elif ch == "\r":
44+ piece.append("\\r")
45+ elif ch == "\t":
46+ piece.append("\\t")
47+ elif ch == MARK_TOKENS:
48+ piece.append("\\001")
49+ elif ch == MARK_HANDOFF:
50+ piece.append("\\002")
51+ elif ord(ch) < 0x20:
52+ piece.append("\\%03o" % ord(ch))
53+ else:
54+ piece.append(ch)
55+ out.append(' "%s"\n' % "".join(piece))
56+ return "".join(out)
57+
58+
59+def render():
60+ with open(SRC, "r", encoding="utf-8") as f:
61+ html = f.read()
62+
63+ if TOKENS not in html:
64+ raise SystemExit("src/ui.html has no %s placeholder" % TOKENS)
65+ html = html.replace(TOKENS, MARK_TOKENS)
66+
67+ # Handoff script goes right before the closing body tag.
68+ if "</body>" not in html:
69+ raise SystemExit("src/ui.html has no </body>")
70+ html = html.replace("</body>", MARK_HANDOFF + "</body>", 1)
71+
72+ header = (
73+ "/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */\n"
74+ "#ifndef SX_GITSTAT_UI_HTML_H\n"
75+ "#define SX_GITSTAT_UI_HTML_H\n"
76+ "\n"
77+ "static const char *UI_HTML =\n" + c_literal(html) + " ;\n"
78+ "\n"
79+ "#endif /* SX_GITSTAT_UI_HTML_H */\n"
80+ )
81+ return header
82+
83+
84+def main():
85+ header = render()
86+ check = "--check" in sys.argv[1:]
87+ if check:
88+ try:
89+ with open(OUT, "r", encoding="utf-8") as f:
90+ cur = f.read()
91+ except OSError:
92+ cur = ""
93+ if cur != header:
94+ sys.stderr.write("src/ui.html.h is stale - run tools/gen_ui.py\n")
95+ return 1
96+ print("src/ui.html.h is up to date")
97+ return 0
98+ with open(OUT, "w", encoding="utf-8") as f:
99+ f.write(header)
100+ print("wrote %s (%d bytes)" % (os.path.relpath(OUT, ROOT), len(header)))
101+ return 0
102+
103+
104+if __name__ == "__main__":
105+ sys.exit(main())
0106
.gitignore+11−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..d1b0223index 0000000..d1b0223
--- /dev/null--- /dev/null
+++ b/.gitignore+++ b/.gitignore
@@ -0,0 +1,11 @@@@ -0,0 +1,11 @@
1+/plugin_gitstat
2+/plugin_gitstat.musl
3+/plugin_gitstat.arm64
4+/plugin_gitstat.exe
5+/plugin_gitstat.macos-arm64
6+/plugin_gitstat.macos-x86_64
7+*.o
8+*.tmp
9+*.dSYM
10+__pycache__/
11+*.pyc
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..2574a24index 0000000..2574a24
--- /dev/null--- /dev/null
+++ b/Makefile+++ b/Makefile
@@ -0,0 +1,62 @@@@ -0,0 +1,62 @@
1+# plugin_gitstat - SCORPIOX BOT open-source local git repository status board
2+#
3+# Targets:
4+# make native build -> ./plugin_gitstat
5+# make musl static musl x86_64 -> ./plugin_gitstat.musl
6+# make arm64 static aarch64 -> ./plugin_gitstat.arm64
7+# make win64 MinGW-w64 static -> ./plugin_gitstat.exe
8+# make macos Apple clang -> ./plugin_gitstat (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+ARM64_CC ?= aarch64-linux-gnu-gcc
17+ARM64_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_gitstat.c
21+HDRS := src/bot_theme_plugin.h src/ui_html.h
22+BIN := plugin_gitstat
23+EXE := plugin_gitstat.exe
24+
25+.PHONY: all native ui musl arm64 win64 macos test clean help
26+
27+all: native
28+
29+native: $(BIN)
30+
31+ui: src/ui.html tools/gen_ui.py
32+ @python3 tools/gen_ui.py
33+
34+$(BIN): $(SRC) $(HDRS)
35+ @echo "==> native build ($(CC))"
36+ $(CC) $(CFLAGS) -I src -o $(BIN) $(SRC)
37+
38+musl: $(SRC) $(HDRS)
39+ @echo "==> static musl build ($(MUSL_CC))"
40+ $(MUSL_CC) $(MUSL_CFLAGS) -I src -o $(BIN).musl $(SRC)
41+
42+arm64: $(SRC) $(HDRS)
43+ @echo "==> static arm64 build ($(ARM64_CC))"
44+ $(ARM64_CC) $(ARM64_CFLAGS) -I src -o $(BIN).arm64 $(SRC)
45+
46+win64: $(SRC) $(HDRS)
47+ @echo "==> MinGW-w64 build ($(WIN_CC))"
48+ $(WIN_CC) $(WIN_CFLAGS) -I src -o $(EXE) $(SRC)
49+
50+macos: $(SRC) $(HDRS)
51+ @echo "==> Apple clang build"
52+ $(CC) $(CFLAGS) -I src -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+144−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..a508542index 0000000..a508542
--- /dev/null--- /dev/null
+++ b/README.md+++ b/README.md
@@ -0,0 +1,144 @@@@ -0,0 +1,144 @@
1+# gitstat — a git repository status board for SCORPIOX BOT
2+
3+`plugin_gitstat` is a single zero-dependency C99 binary that answers one question
4+about a machine: **which of my repositories have uncommitted work, and how far
5+are they from their upstream?**
6+
7+It walks a fixed set of allowlisted roots, finds every working tree with a `.git`
8+entry, and asks git itself — `status --porcelain=v2 --branch`, `log -1`,
9+`stash list` — through argv-only child processes. No shell, no `popen`, no
10+parsing of `.git/index` by hand.
11+
12+![1440 dark](docs/ui-1440-dark.png)
13+
14+| 1440 light | 1024 dark |
15+|---|---|
16+| ![1440 light](docs/ui-1440-light.png) | ![1024 dark](docs/ui-1024-dark.png) |
17+
18+| 390 dark | 390 light |
19+|---|---|
20+| ![390 dark](docs/ui-390-dark.png) | ![390 light](docs/ui-390-light.png) |
21+
22+## Modes
23+
24+| Invocation | Output |
25+|---|---|
26+| `plugin_gitstat --meta` (or `SX_PLUGIN_META=1`) | `{"name":"git","desc":"Repo status"}` — unauthenticated, so discovery works |
27+| `GET ?action=repos` | Every repository found, plus per-root counts and a summary |
28+| `GET ?action=repo&path=<abs>` | One repository: 500 changed files max, 20 recent commits |
29+| `POST ?action=fetch&path=<abs>` | `git fetch --prune`, 30 s timeout, only when `GITSTAT_ALLOW_FETCH=1` |
30+| `GET` (default) | The responsive HTML board |
31+
32+Every action except `--meta` sits behind `require_node_auth()`: `X-Bot-Password`,
33+`Authorization: Bearer`, or `?pwd=`, and it is a no-op only when `BOT_PASSWORD`
34+is unset.
35+
36+## Roots
37+
38+| Platform | Defaults |
39+|---|---|
40+| Linux | `/workspace`, `/codebases`, `$HOME`, plus `GITSTAT_ROOTS` (`:`-separated) |
41+| macOS | same |
42+| Windows | `%USERPROFILE%`, `D:\codebases` and `C:\codebases` when present, plus `GITSTAT_ROOTS` (`;`-separated) |
43+
44+Two environment knobs:
45+
46+- `GITSTAT_ONLY_ROOTS=1` makes `GITSTAT_ROOTS` the complete list instead of an
47+ addition. Useful on a node that wants an explicit allowlist, and it is what the
48+ test suite uses so a developer machine full of checkouts cannot change the
49+ result.
50+- `GITSTAT_ALLOW_FETCH=1` enables the single write-ish action. Without it the
51+ plugin is strictly read-only and `POST ?action=fetch` answers `403`-style
52+ `{"ok":false,...}` explaining the switch.
53+
54+Discovery is depth-limited to 4 and budgeted **per root** (20 000 entries each,
55+1 200 repositories in the table), because one shared budget lets the first root
56+consume the whole walk and the second root report zero.
57+
58+## JSON shape
59+
60+```json
61+{
62+ "ok": true,
63+ "action": "repos",
64+ "count": 4,
65+ "table_capped": false,
66+ "summary": {"dirty": 1, "ahead": 1, "behind": 0, "stashes": 1, "detached": 1},
67+ "checked_at": "2026-11-12T09:31:06Z",
68+ "roots": [{"root": "/codebases", "exists": true, "count": 4, "truncated": false}],
69+ "repos": [{
70+ "path": "/codebases/portal-web",
71+ "name": "portal-web",
72+ "root": "/codebases",
73+ "branch": "main",
74+ "upstream": "origin/main",
75+ "remote": "https://git.example.net/team/portal-web.git",
76+ "ahead": 2, "behind": 0,
77+ "dirty": 3, "untracked": 1, "staged": 1, "conflicted": 0,
78+ "stash": 1,
79+ "detached": false, "no_upstream": false, "unborn": false,
80+ "last_commit": {
81+ "hash": "…", "short": "7746dc67", "ct": 1794475861,
82+ "at": "2026-11-12T09:31:01Z",
83+ "subject": "Cap the retry backoff at thirty seconds"
84+ }
85+ }]
86+}
87+```
88+
89+`?action=repo&path=` adds `changed` (code + path, max 500), `changed_count`,
90+`changed_truncated` and `commits` (max 20). A path is accepted only when it
91+canonicalises to somewhere **under an allowlisted root** and that directory
92+carries a `.git` entry; anything else, including a `..` traversal, is `403`.
93+
94+## Security posture
95+
96+- **No shell anywhere.** Every git invocation is an argv array handed to
97+ `execvp` / `CreateProcessA`. A path with a `;` or a backtick in it is a path,
98+ not a command.
99+- **Read-only by default.** `git fetch --prune` is the only operation that
100+ touches a remote, it needs `GITSTAT_ALLOW_FETCH=1`, and it is capped at 30
101+ seconds. Nothing ever runs `pull`, `checkout`, `reset` or `clean`.
102+- **No credential prompts.** `GIT_TERMINAL_PROMPT=0`, an empty `GIT_ASKPASS`, and
103+ stdin from `/dev/null`, so a repository with a dead remote can never hang the
104+ node behind a password prompt.
105+- **Remote URLs are stripped of userinfo** before they are printed, so an origin
106+ of `https://user:token@host/x.git` shows as `https://host/x.git` in the board,
107+ the JSON and anything a caller pipes it into.
108+- **Allowlisted roots only.** Discovery never leaves them, and the detail and
109+ fetch actions re-check the canonical path on every request.
110+
111+## Build
112+
113+```sh
114+make # native
115+make musl # static musl x86_64 (universal Linux)
116+make arm64 # static aarch64
117+make win64 # MinGW-w64 static PE
118+make macos # Apple clang (run on macOS)
119+make test # build + 110 offline assertions
120+python3 tests/e2e.py # Playwright 1440/1024/390, dark + light
121+make clean
122+```
123+
124+`src/ui.html` is the page; `tools/gen_ui.py` compiles it into `src/ui_html.h`
125+with two control-byte placeholders that the C side expands into the bot's theme
126+macros, so the plugin can never drift away from the bot palette. `make ui`
127+regenerates it, and `python3 tools/gen_ui.py --check` fails when it is stale.
128+
129+## Install
130+
131+Pre-built artifacts for six targets live at
132+`https://dist.scorpiox.net/bot-plugins/gitstat/1.0.0/`. Drop the right one into
133+`~/.scorpiox/plugins/plugin_gitstat` (or `/workspace/.scorpiox/plugins/` on a
134+BotCloud container) — `scorpiox-server` discovers it live, with no restart.
135+
136+Or build it from source, which is the point of the marketplace:
137+
138+> Clone `https://plugingit.scorpiox.net/scorpiox-bot-plugin-gitstat.git`, read
139+> `src/plugin_gitstat.c`, customise the root list for this machine, compile it
140+> with `make`, check `--meta`, and install it to `~/.scorpiox/plugins/`.
141+
142+## License
143+
144+MIT. See [LICENSE](LICENSE).
build.ps1+51−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..831a0a1index 0000000..831a0a1
--- /dev/null--- /dev/null
+++ b/build.ps1+++ b/build.ps1
@@ -0,0 +1,51 @@@@ -0,0 +1,51 @@
1+# build.ps1 - Windows MinGW-w64 static build for plugin_gitstat
2+#
3+# Usage (from the repo root, PowerShell):
4+# powershell -ExecutionPolicy Bypass -File build.ps1
5+#
6+# Produces .\plugin_gitstat.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_gitstat.c"
14+ $Out = Join-Path $ScriptDir "plugin_gitstat.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+ # Regenerate the page header so the binary always matches src/ui.html.
31+ if (Get-Command python -ErrorAction SilentlyContinue) {
32+ python tools\gen_ui.py
33+ }
34+
35+ Write-Host "==> building plugin_gitstat.exe with $Cc"
36+ & $Cc -O2 -std=c99 -Wall -Wextra -I src -static -o $Out $Src
37+ if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" }
38+
39+ if (-not (Test-Path $Out)) { throw "build produced no output" }
40+
41+ # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not.
42+ $bytes = [System.IO.File]::ReadAllBytes($Out)
43+ if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) {
44+ throw "output is not a PE executable (missing MZ header)"
45+ }
46+
47+ Write-Host "==> ok: $Out ($($bytes.Length) bytes)"
48+ Write-Host " smoke test: .\plugin_gitstat.exe --meta"
49+} finally {
50+ Pop-Location
51+}
docs/ui-1024-dark.png+0−0■
1new file mode 1006441new file mode 100644
index 0000000..4bf9bb5index 0000000..4bf9bb5
binary image
Binary image file
docs/ui-1024-light.png+0−0■
1new file mode 1006441new file mode 100644
index 0000000..47ab3a8index 0000000..47ab3a8
binary image
Binary image file
docs/ui-1440-dark.png+0−0■
1new file mode 1006441new file mode 100644
index 0000000..11d5c79index 0000000..11d5c79
binary image
Binary image file
docs/ui-1440-light.png+0−0■
1new file mode 1006441new file mode 100644
index 0000000..eed895eindex 0000000..eed895e
binary image
Binary image file
docs/ui-390-dark.png+0−0■
1new file mode 1006441new file mode 100644
index 0000000..c285bbdindex 0000000..c285bbd
binary image
Binary image file
docs/ui-390-light.png+0−0■
1new file mode 1006441new file mode 100644
index 0000000..0e77112index 0000000..0e77112
binary image
Binary image file
plugin.json+16−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..66e8d21index 0000000..66e8d21
--- /dev/null--- /dev/null
+++ b/plugin.json+++ b/plugin.json
@@ -0,0 +1,16 @@@@ -0,0 +1,16 @@
1+{
2+ "slug": "gitstat",
3+ "id": "plugin_gitstat",
4+ "title": "Local Git Repository Status Board",
5+ "summary": "Zero-dependency status board for every git repository under your allowlisted roots: branch, uncommitted file count, ahead/behind against the upstream, stash depth and the last commit, sorted dirty-first. Discovery walks /workspace, /codebases, your home directory and GITSTAT_ROOTS without ever leaving them, and each repository is queried through git's own porcelain v2 output via argv-only child processes — no shell is involved and no remote is ever contacted unless the node operator enables fetching.",
6+ "category": "devtools",
7+ "license": "MIT",
8+ "capabilities": [
9+ "fs_walk",
10+ "git_read",
11+ "git_fetch_optional"
12+ ],
13+ "trust_notice": "Executes native C code on your node. Walks only the allowlisted roots and reads local repositories with git status, git log and git stash list. Any credentials embedded in a remote URL are stripped before they are displayed. Makes zero outbound network requests unless GITSTAT_ALLOW_FETCH=1, in which case a single `git fetch --prune` with a 30 second timeout runs against the repository you asked for.",
14+ "author": "SCORPIOX INC",
15+ "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-gitstat"
16+}
release-dist.sh+365−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..23ad0baindex 0000000..23ad0ba
--- /dev/null--- /dev/null
+++ b/release-dist.sh+++ b/release-dist.sh
@@ -0,0 +1,365 @@@@ -0,0 +1,365 @@
1+#!/usr/bin/env bash
2+# release-dist.sh - build, scan and publish plugin_gitstat 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="gitstat"
33+ID="plugin_gitstat"
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 (and the
90+# test suite's identical checks) read as findings in every historical revision of
91+# them. A real secret on any other line still hits.
92+git log -p --all 2>/dev/null \
93+ | grep -v '^Author: ' \
94+ | grep -vE "scan \"|audit \"|HITS=|grep -E|grep -qE|hits '|P_ROOT=|P_WT=|PK=\"|\$ALL" \
95+ > "$SCAN_TMP" || : > "$SCAN_TMP"
96+HITS=0
97+scan() { # scan <label> <regex>
98+ local out
99+ out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true)
100+ if [ -n "$out" ]; then
101+ printf ' \033[31mHIT\033[0m %s\n' "$1"
102+ printf '%s\n' "$out" | sed 's/^/ /'
103+ HITS=$((HITS + 1))
104+ else
105+ printf ' ok %s\n' "$1"
106+ fi
107+}
108+scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+'
109+scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
110+scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
111+scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
112+scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}'
113+scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}'
114+scan "hard-coded ssh password" 'sshpass -p [^"$]'
115+P_ROOT="/codebases"
116+P_PICOBOT="${P_ROOT}/pico""bot"
117+P_WT=".work""trees"
118+scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}"
119+scan "run-token env assignment" 'RUNNER_'"PASS="
120+if [ "$HITS" -ne 0 ]; then
121+ die "secret scan found $HITS problem(s) - refusing to publish"
122+fi
123+echo " clean: 0 hits"
124+
125+# ---------------------------------------------------------------- 2. build
126+say "2/7 build targets"
127+
128+# linux-x86_64 (glibc, native)
129+if command -v cc >/dev/null 2>&1; then
130+ cc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src -o "$STAGE/$ID" src/$ID.c || die "native build failed"
131+ echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes"
132+else
133+ die "no native cc found"
134+fi
135+
136+# linux-x86_64-musl (fully static - the universal Linux artifact)
137+if command -v musl-gcc >/dev/null 2>&1; then
138+ musl-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.musl" src/$ID.c \
139+ || die "musl build failed"
140+ echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes"
141+else
142+ echo " skip linux-x86_64-musl (no musl-gcc)"
143+fi
144+
145+# linux-arm64-musl (static aarch64 - Raspberry Pi 5 / ARM64 servers)
146+if command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
147+ aarch64-linux-gnu-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings -I src -o "$STAGE/$ID.arm64" src/$ID.c \
148+ || die "arm64 build failed"
149+ echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes"
150+else
151+ echo " skip linux-arm64-musl (no aarch64-linux-gnu-gcc)"
152+fi
153+
154+# windows-x86_64 (static PE)
155+if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
156+ x86_64-w64-mingw32-gcc -O2 -std=c99 -Wall -Wextra -static -Wno-overlength-strings \
157+ -I src -o "$STAGE/$ID.exe" src/$ID.c || die "MinGW build failed"
158+ [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE"
159+ echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes"
160+else
161+ echo " skip windows-x86_64 (no MinGW cross compiler)"
162+fi
163+
164+# macOS legs - Mach-O must be produced by Apple clang on a real Mac.
165+# Both slices are cross-built from one host: -arch arm64 and -arch x86_64.
166+if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then
167+ MAC_USER="${MAC_USER:-$(whoami)}"
168+ MAC_DIR="/tmp/${ID}-mac-$$"
169+ echo " building macOS legs on $MAC_HOST"
170+ SSH_MAC=(ssh -o StrictHostKeyChecking=no)
171+ SCP_MAC=(scp -o StrictHostKeyChecking=no)
172+ if [ -n "${MAC_PASS:-}" ]; then
173+ SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}")
174+ SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}")
175+ fi
176+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR'"; then
177+ tar -czf "$STAGE/src.tgz" src
178+ if "${SCP_MAC[@]}" "$STAGE/src.tgz" "$MAC_USER@$MAC_HOST:$MAC_DIR/src.tgz" \
179+ && "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "cd '$MAC_DIR' && tar -xzf src.tgz"; then
180+ # Build straight from the uploaded file - no src/ tree on the remote.
181+ for slice in arm64 x86_64; do
182+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \
183+ "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -arch $slice -o $ID.$slice src/$ID.c" \
184+ 2>/dev/null; then
185+ "${SCP_MAC[@]}" "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" 2>/dev/null \
186+ && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)"
187+ else
188+ echo " warn: macos-$slice build failed on $MAC_HOST"
189+ fi
190+ done
191+ "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" || true
192+ else
193+ echo " warn: could not upload source to $MAC_HOST"
194+ fi
195+ else
196+ echo " warn: cannot reach macOS builder $MAC_HOST"
197+ fi
198+else
199+ echo " skip macOS legs (no MAC_HOST or --no-macos)"
200+fi
201+
202+# ---------------------------------------------------------------- 3. manifest
203+say "3/7 manifest + checksums"
204+
205+git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \
206+ -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \
207+ || tar -czf "$STAGE/source.tar.gz" --exclude=.git .
208+echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes"
209+
210+target_meta() { # target_meta <key> <file> <format> <relpath>
211+ local key="$1" file="$2" fmt="$3" rel="$4"
212+ [ -f "$file" ] || return 0
213+ local sha size
214+ sha=$(sha256sum "$file" | awk '{print $1}')
215+ size=$(wc -c < "$file" | tr -d ' ')
216+ printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \
217+ "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt"
218+}
219+
220+{
221+ printf '{\n'
222+ printf ' "slug": "%s",\n' "$SLUG"
223+ printf ' "id": "%s",\n' "$ID"
224+ printf ' "name": "notes",\n'
225+ printf ' "desc": "Markdown notes",\n'
226+ printf ' "title": "Markdown Notes",\n'
227+ printf ' "summary": "Zero-dependency markdown notes that live on your node: create, edit, rename, search, pin and delete, with a live rendered preview next to the editor. Notes are one <id>.md file each plus index.json inside the plugin directory, every write is staged to a temp file and renamed so a crash never truncates a note, and deleted notes go to a recoverable .trash. Server-side rendering escapes note content first, so a pasted <script> is inert text. No CDN, no network requests, no database.",\n'
228+ printf ' "category": "utilities",\n'
229+ printf ' "version": "%s",\n' "$VERSION"
230+ printf ' "license": "MIT",\n'
231+ printf ' "trust_notice": "Executes native C code on your node. Reads and writes only inside its own notes directory (plugin dir/.notes, or $NOTES_DIR when set): one markdown file per note, an index.json, and a .trash subdirectory. It opens no network connection of any kind and reads nothing outside that directory.",\n'
232+ printf ' "capabilities": ["fs_write_plugin_dir"],\n'
233+ printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG"
234+ printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG"
235+ printf ' "git_commit": "%s",\n' "$COMMIT"
236+ printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
237+ printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')"
238+ printf ' "build_cmd_posix": "cc -O2 -std=c99 -Wall -Wextra -o %s src/%s.c",\n' "$ID" "$ID"
239+ printf ' "build_cmd_win64": "x86_64-w64-mingw32-gcc -O2 -std=c99 -static -o %s.exe src/%s.c",\n' "$ID" "$ID"
240+ printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
241+ printf ' "targets": {\n'
242+ first=1
243+ emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; }
244+ emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID"
245+ emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID"
246+ emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID"
247+ emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID"
248+ emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID"
249+ emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe"
250+ printf '\n }\n}\n'
251+} > "$STAGE/manifest.json"
252+
253+python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \
254+ || die "generated manifest.json is not valid JSON"
255+echo " manifest.json ok ($(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["targets"]))' "$STAGE/manifest.json") targets)"
256+
257+# SHA256SUMS - relative paths, exactly as published
258+( cd "$STAGE"
259+ for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done
260+ [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|"
261+ [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|"
262+ [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|"
263+ [ -f "$ID.macos-arm64" ]&& sha256sum "$ID.macos-arm64"| sed "s| $ID.macos-arm64\$| macos-arm64/$ID|"
264+ [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64"| sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|"
265+ [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|"
266+ true ) > "$STAGE/SHA256SUMS"
267+echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries"
268+
269+# ---------------------------------------------------------------- 4. stage
270+say "4/7 stage tree"
271+PKG="$STAGE/pkg"
272+mkdir -p "$PKG"
273+cp "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/"
274+[ -f "$STAGE/$ID" ] && { mkdir -p "$PKG/linux-x86_64"; cp "$STAGE/$ID" "$PKG/linux-x86_64/$ID"; }
275+[ -f "$STAGE/$ID.musl" ] && { mkdir -p "$PKG/linux-x86_64-musl"; cp "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID"; }
276+[ -f "$STAGE/$ID.arm64" ] && { mkdir -p "$PKG/linux-arm64-musl"; cp "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID"; }
277+[ -f "$STAGE/$ID.macos-arm64" ] && { mkdir -p "$PKG/macos-arm64"; cp "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"; }
278+[ -f "$STAGE/$ID.macos-x86_64" ]&& { mkdir -p "$PKG/macos-x86_64"; cp "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"; }
279+[ -f "$STAGE/$ID.exe" ] && { mkdir -p "$PKG/windows-x86_64"; cp "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe"; }
280+echo " staged: $(find "$PKG" -type f | wc -l | tr -d ' ') file(s)"
281+
282+if [ "$DRY_RUN" -eq 1 ]; then
283+ say "dry run - leaving the staging tree in $PKG"
284+ trap - EXIT
285+ exit 0
286+fi
287+
288+# ---------------------------------------------------------------- 5. upload
289+say "5/7 upload to the dist server"
290+[ -n "$DIST_HOST" ] || die "DIST_HOST is not set (export DIST_HOST=<ssh-target>)"
291+SSH=(ssh -o StrictHostKeyChecking=no)
292+SCP=(scp -o StrictHostKeyChecking=no)
293+if [ -n "$DIST_PASS" ]; then
294+ SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}")
295+ SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}")
296+fi
297+REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION"
298+
299+"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \
300+ || die "cannot create $REMOTE_DIR on $DIST_HOST"
301+# Stage to one tarball, transfer it, extract remotely. Streaming tar through
302+# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and
303+# OpenSSH 9 refuses to scp a bare "." source.
304+tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed"
305+"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed"
306+"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \
307+ || die "remote extract failed"
308+echo " uploaded to $DIST_HOST:$REMOTE_DIR"
309+
310+# latest.json = copy of this version's manifest
311+"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \
312+ || die "latest.json update failed"
313+echo " updated bot-plugins/$SLUG/latest.json"
314+
315+# index.json - merge, preserving every sibling <slug>/latest.json
316+say "index.json merge"
317+"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY'
318+import json, os, sys, glob
319+slug = sys.argv[1]
320+entries = {}
321+for p in sorted(glob.glob('*/latest.json')):
322+ s = os.path.dirname(p)
323+ try:
324+ entries[s] = json.load(open(p))
325+ except Exception:
326+ pass
327+index = {
328+ 'ok': True,
329+ 'service': 'bot-plugins-dist',
330+ 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins',
331+ 'count': len(entries),
332+ 'slugs': sorted(entries),
333+ 'plugins': [entries[k] for k in sorted(entries)],
334+}
335+open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10))
336+os.replace('index.json.tmp', 'index.json')
337+print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries))))
338+PY" || die "index.json merge failed"
339+
340+# ---------------------------------------------------------------- 6. mirror
341+say "6/7 plugingit mirror"
342+if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then
343+ TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE")
344+ AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://token:${TOKEN}@|")
345+ git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed"
346+ git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true
347+ echo " mirrored to $PLUGINGIT_REMOTE"
348+else
349+ echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)"
350+fi
351+
352+# ---------------------------------------------------------------- 7. verify
353+say "7/7 verify"
354+CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \
355+ "$DIST_BASE_URL/$SLUG/latest.json" || echo 000)
356+if [ "$CODE" = "200" ]; then
357+ 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"])))' \
358+ "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON"
359+else
360+ echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE"
361+fi
362+
363+printf '\n\033[1mrelease complete\033[0m\n'
364+printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
365+printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
src/bot_theme_plugin.h+129−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..0dd243bindex 0000000..0dd243b
--- /dev/null--- /dev/null
+++ b/src/bot_theme_plugin.h+++ b/src/bot_theme_plugin.h
@@ -0,0 +1,129 @@@@ -0,0 +1,129 @@
1+/*
2+ * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins.
3+ *
4+ * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of
5+ * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session
6+ * Card modal, Chat floating window) or in its own tab, and in every case it
7+ * must look like part of the bot: same tokens, same dark/light pair, same
8+ * localStorage key, same prepaint order.
9+ *
10+ * Three rules, and nothing else:
11+ *
12+ * 1. Colours come from these tokens only. No plugin-private palette.
13+ * 2. The theme is decided BEFORE first paint, in this order:
14+ * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme
15+ * so a plugin opened from the bot paints in the bot's theme from frame 0.
16+ * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into
17+ * this window; the plugin follows without a reload. The plugin asks once
18+ * with {type:'sx-theme-request'} at startup, which covers the case where
19+ * it was already open when the bot changed theme.
20+ *
21+ * The bottom of :root carries aliases for the names older plugin CSS already
22+ * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn,
23+ * --ok), so adopting the bot palette is a swap, not a redesign. Because they
24+ * are var() references, one definition covers both themes.
25+ *
26+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
27+ */
28+#ifndef SX_BOT_THEME_PLUGIN_H
29+#define SX_BOT_THEME_PLUGIN_H
30+
31+/* Dark is the default; light is applied by html[data-theme=light] (chosen by
32+ * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */
33+#define SX_BOT_THEME_TOKENS \
34+":root{color-scheme:dark;" \
35+ "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \
36+ "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \
37+ "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \
38+ "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \
39+ "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \
40+ "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \
41+ "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \
42+ "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \
43+ "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \
44+ "--shadow:0 1px 2px rgba(0,0,0,.35);" \
45+ "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \
46+ "--ease:cubic-bezier(.16,1,.3,1);" \
47+ "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \
48+ "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \
49+ "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \
50+"}" \
51+"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \
52+ "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \
53+ "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \
54+ "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \
55+ "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \
56+ "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \
57+ "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \
58+ "--accent-dim:#0066d6;" \
59+ "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \
60+ "--shadow:0 2px 10px rgba(0,0,0,.03);" \
61+ "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \
62+ "color-scheme:light}}" \
63+"html[data-theme=light]{" \
64+ "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \
65+ "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \
66+ "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \
67+ "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \
68+ "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \
69+ "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \
70+ "--accent-dim:#0066d6;" \
71+ "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \
72+ "--shadow:0 2px 10px rgba(0,0,0,.03);" \
73+ "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \
74+ "color-scheme:light}" \
75+"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \
76+"*{box-sizing:border-box}" \
77+"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \
78+ "-webkit-font-smoothing:antialiased}" \
79+"button{font-family:inherit;letter-spacing:inherit}" \
80+"button:active{transform:scale(.98)}" \
81+"select option{background:var(--menu-bg);color:var(--text)}" \
82+"a{color:var(--blue);text-decoration:none;font-weight:600}" \
83+"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \
84+" * hides its own back link and its own toggle. */" \
85+"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \
86+"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}"
87+
88+/* Pre-paint: decide the theme before the first frame. Must be the first thing
89+ * in <head> so there is no flash of the wrong theme. Also flags embed mode as
90+ * html.embedded so the embed rules apply before first paint. */
91+#define SX_BOT_THEME_PREPAINT \
92+"<script>(function(){var t='';" \
93+"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \
94+"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \
95+"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \
96+"document.documentElement.setAttribute('data-theme',t);" \
97+"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \
98+"try{localStorage.setItem('bot_theme',t);}catch(e){}" \
99+"})();</script>\n"
100+
101+/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once
102+ * at startup in case it changed while this page was already open. Fires the
103+ * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can
104+ * re-skin themselves from one listener. */
105+#define SX_BOT_THEME_HANDOFF \
106+"<script>(function(){" \
107+"function apply(t){if(t!=='light'&&t!=='dark')return;" \
108+"if(document.documentElement.getAttribute('data-theme')===t)return;" \
109+"document.documentElement.setAttribute('data-theme',t);" \
110+"try{localStorage.setItem('bot_theme',t);}catch(e){}" \
111+"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \
112+"window.sxApplyTheme=apply;" \
113+"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \
114+"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \
115+"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \
116+"})();</script>\n"
117+
118+/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when
119+ * the plugin is opened in its own tab; inside the bot the host owns the theme.
120+ * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */
121+#define SX_BOT_THEME_TOGGLE_BTN \
122+"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>"
123+
124+#define SX_BOT_THEME_TOGGLE_JS \
125+"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \
126+"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \
127+"})();</script>\n"
128+
129+#endif /* SX_BOT_THEME_PLUGIN_H */
src/plugin_gitstat.c+1477−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..d0359e3index 0000000..d0359e3
--- /dev/null--- /dev/null
+++ b/src/plugin_gitstat.c+++ b/src/plugin_gitstat.c
@@ -0,0 +1,1477 @@@@ -0,0 +1,1477 @@
1+/*
2+ * plugin_gitstat - SCORPIOX BOT open-source local git repository status board
3+ *
4+ * One clean-room C99 binary, three modes:
5+ * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata
6+ * 2. ?action=repos|repo|fetch / ?format=json / POST -> JSON node API
7+ * 3. GET (default) -> responsive HTML board
8+ *
9+ * It walks a fixed set of allowlisted roots (never beyond them), finds every
10+ * working tree that has a .git directory or a .git worktree file, and asks git
11+ * about each one through argv-only child processes (no shell, ever):
12+ *
13+ * git -C <repo> status --porcelain=v2 --branch --untracked-files=normal
14+ * git -C <repo> log -1 --format=%H%x09%ct%x09%s
15+ * git -C <repo> stash list --format=%gd
16+ *
17+ * From that it derives branch, dirty file count, ahead/behind upstream, stash
18+ * count, detached / no-upstream / unborn states and the last commit. Fetching
19+ * from a remote is the ONLY write-ish operation and it stays off until the node
20+ * operator sets GITSTAT_ALLOW_FETCH=1; even then it is `git fetch --prune` with
21+ * a 30 s timeout, and GIT_TERMINAL_PROMPT=0 plus an empty GIT_ASKPASS so a
22+ * credential prompt can never hang the node.
23+ *
24+ * Remote URLs are stripped of any userinfo before they are printed, so a repo
25+ * whose origin is https://user:token@host/x.git never leaks the token into the
26+ * dashboard, the JSON API or the bot's logs.
27+ *
28+ * Zero dependencies. Builds with gcc, musl-gcc -static, Apple clang and
29+ * x86_64-w64-mingw32-gcc -static. Runs as a CGI-style executable under
30+ * scorpiox-server on the node.
31+ *
32+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
33+ */
34+
35+/* Must be the very first thing on Windows: CreateProcessA/GetFileAttributesA
36+ * and the pipe helpers are gated on _WIN32_WINNT, and MinGW defaults to 0x502. */
37+#if defined(_WIN32) && !defined(_WIN32_WINNT)
38+# define _WIN32_WINNT 0x0601
39+#endif
40+
41+#if !defined(_WIN32)
42+# define _POSIX_C_SOURCE 200809L
43+# define _DEFAULT_SOURCE 1
44+# if defined(__APPLE__)
45+# define _DARWIN_C_SOURCE 1
46+# endif
47+#endif
48+
49+#include <stdio.h>
50+#include <stdlib.h>
51+#include <string.h>
52+#include <stdarg.h>
53+#include <ctype.h>
54+#include <errno.h>
55+#include <time.h>
56+
57+#if defined(_WIN32)
58+# define WIN32_LEAN_AND_MEAN
59+# include <windows.h>
60+#else
61+# include <unistd.h>
62+# include <dirent.h>
63+# include <fcntl.h>
64+# include <sys/types.h>
65+# include <sys/stat.h>
66+# include <sys/wait.h>
67+# include <signal.h>
68+# include <poll.h>
69+#endif
70+
71+#include "bot_theme_plugin.h"
72+#include "ui_html.h"
73+
74+#define PLUGIN_SLUG "gitstat"
75+#define PLUGIN_ID "plugin_gitstat"
76+#define PLUGIN_VER "1.0.0"
77+
78+#define PLUGIN_NAME "git"
79+#define PLUGIN_DESC "Repo status"
80+
81+#define MAX_REPOS 1200
82+#define MAX_ROOT_ENTRIES 20000
83+#define MAX_DEPTH 4
84+#define MAX_ROOTS 8
85+#define MAX_CHANGED 500
86+#define MAX_COMMITS 20
87+#define OUT_CAP (512 * 1024)
88+#define FETCH_TIMEOUT_S 30
89+#define GIT_TIMEOUT_S 20
90+
91+/* ------------------------------------------------------------------ */
92+/* Buffers */
93+/* ------------------------------------------------------------------ */
94+
95+typedef struct {
96+ char *p;
97+ size_t len;
98+ size_t cap;
99+} buf_t;
100+
101+static void buf_init(buf_t *b)
102+{
103+ b->cap = 4096;
104+ b->len = 0;
105+ b->p = (char *)malloc(b->cap);
106+ if (b->p) b->p[0] = '\0';
107+}
108+
109+static void buf_free(buf_t *b)
110+{
111+ free(b->p);
112+ b->p = NULL;
113+ b->len = b->cap = 0;
114+}
115+
116+static void buf_add(buf_t *b, const char *s, size_t n)
117+{
118+ if (!b->p) return;
119+ if (b->len + n + 1 > b->cap) {
120+ size_t nc = b->cap;
121+ char *np;
122+ while (nc < b->len + n + 1) nc *= 2;
123+ np = (char *)realloc(b->p, nc);
124+ if (!np) return;
125+ b->p = np;
126+ b->cap = nc;
127+ }
128+ memcpy(b->p + b->len, s, n);
129+ b->len += n;
130+ b->p[b->len] = '\0';
131+}
132+
133+static void buf_puts(buf_t *b, const char *s)
134+{
135+ if (s) buf_add(b, s, strlen(s));
136+}
137+
138+static void buf_printf(buf_t *b, const char *fmt, ...)
139+{
140+ char tmp[2048];
141+ va_list ap;
142+ int n;
143+
144+ va_start(ap, fmt);
145+ n = vsnprintf(tmp, sizeof(tmp), fmt, ap);
146+ va_end(ap);
147+ if (n < 0) return;
148+ if ((size_t)n < sizeof(tmp)) {
149+ buf_add(b, tmp, (size_t)n);
150+ } else {
151+ char *big = (char *)malloc((size_t)n + 1);
152+ if (!big) return;
153+ va_start(ap, fmt);
154+ vsnprintf(big, (size_t)n + 1, fmt, ap);
155+ va_end(ap);
156+ buf_add(b, big, (size_t)n);
157+ free(big);
158+ }
159+}
160+
161+static const char *buf_str(buf_t *b) { return b->p ? b->p : ""; }
162+
163+/* JSON string escaper. Also the last line of defence against a remote URL
164+ * carrying something that would break the document. */
165+static void json_str(buf_t *b, const char *s)
166+{
167+ const unsigned char *p = (const unsigned char *)(s ? s : "");
168+ buf_add(b, "\"", 1);
169+ while (*p) {
170+ switch (*p) {
171+ case '"': buf_add(b, "\\\"", 2); break;
172+ case '\\': buf_add(b, "\\\\", 2); break;
173+ case '\n': buf_add(b, "\\n", 2); break;
174+ case '\r': buf_add(b, "\\r", 2); break;
175+ case '\t': buf_add(b, "\\t", 2); break;
176+ default:
177+ if (*p < 0x20) {
178+ char esc[8];
179+ snprintf(esc, sizeof(esc), "\\u%04x", *p);
180+ buf_add(b, esc, strlen(esc));
181+ } else {
182+ buf_add(b, (const char *)p, 1);
183+ }
184+ }
185+ p++;
186+ }
187+ buf_add(b, "\"", 1);
188+}
189+
190+/* ------------------------------------------------------------------ */
191+/* Small utilities */
192+/* ------------------------------------------------------------------ */
193+
194+static void str_copy(char *dst, size_t sz, const char *src)
195+{
196+ size_t n;
197+ if (!dst || sz == 0) return;
198+ if (!src) src = "";
199+ n = strlen(src);
200+ if (n > sz - 1) n = sz - 1;
201+ memcpy(dst, src, n);
202+ dst[n] = '\0';
203+}
204+
205+static void str_trim(char *s)
206+{
207+ size_t n;
208+ char *p = s;
209+ if (!s) return;
210+ while (*p && (unsigned char)*p <= ' ') p++;
211+ if (p != s) memmove(s, p, strlen(p) + 1);
212+ n = strlen(s);
213+ while (n > 0 && (unsigned char)s[n - 1] <= ' ') s[--n] = '\0';
214+}
215+
216+static void url_decode(char *s)
217+{
218+ char *o = s;
219+ if (!s) return;
220+ while (*s) {
221+ if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) {
222+ int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10);
223+ int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10);
224+ *o++ = (char)((hi << 4) | lo);
225+ s += 3;
226+ } else if (*s == '+') {
227+ *o++ = ' ';
228+ s++;
229+ } else {
230+ *o++ = *s++;
231+ }
232+ }
233+ *o = '\0';
234+}
235+
236+/* Returns 1 when the key was present (value may be empty). */
237+static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
238+{
239+ const char *p;
240+ size_t klen;
241+
242+ if (!qs || !key || !out || outsz == 0) return 0;
243+ out[0] = '\0';
244+ klen = strlen(key);
245+ p = qs;
246+ while (*p) {
247+ if (strncmp(p, key, klen) == 0 && p[klen] == '=') {
248+ size_t i = 0;
249+ p += klen + 1;
250+ while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++;
251+ out[i] = '\0';
252+ url_decode(out);
253+ return 1;
254+ }
255+ p = strchr(p, '&');
256+ if (!p) break;
257+ p++;
258+ }
259+ return 0;
260+}
261+
262+static int is_post_request(void)
263+{
264+ const char *m = getenv("REQUEST_METHOD");
265+ return m && strcmp(m, "POST") == 0;
266+}
267+
268+static void utc_stamp(time_t t, char *buf, size_t sz)
269+{
270+ struct tm tmv;
271+#if defined(_WIN32)
272+ gmtime_s(&tmv, &t);
273+#else
274+ gmtime_r(&t, &tmv);
275+#endif
276+ strftime(buf, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv);
277+}
278+
279+/* Strip any userinfo from a URL-ish string so an origin like
280+ * https://user:token@host/x.git is printed as https://host/x.git. */
281+static void redact_url(const char *in, char *out, size_t sz)
282+{
283+ const char *scheme;
284+ const char *at;
285+
286+ if (!in || !*in) { str_copy(out, sz, ""); return; }
287+
288+ scheme = strstr(in, "://");
289+ if (!scheme) { str_copy(out, sz, in); return; }
290+
291+ at = strchr(scheme + 3, '@');
292+ if (!at) { str_copy(out, sz, in); return; }
293+
294+ /* Anything with an '@' before the first '/' carries userinfo. */
295+ {
296+ const char *slash = strchr(scheme + 3, '/');
297+ if (slash && slash < at) { str_copy(out, sz, in); return; }
298+ }
299+
300+ /* scheme:// + rest-after-@ */
301+ {
302+ size_t head = (size_t)(scheme + 3 - in);
303+ if (head >= sz) head = sz - 1;
304+ memcpy(out, in, head);
305+ out[head] = '\0';
306+ strncat(out, at + 1, sz - strlen(out) - 1);
307+ }
308+}
309+
310+/* ------------------------------------------------------------------ */
311+/* Node authentication */
312+/* ------------------------------------------------------------------ */
313+
314+static void require_node_auth(void)
315+{
316+ const char *np = getenv("BOT_PASSWORD");
317+ const char *xp;
318+ const char *auth;
319+ const char *qs;
320+ char qpwd[256];
321+
322+ if (!np || !*np) return;
323+
324+ xp = getenv("HTTP_X_BOT_PASSWORD");
325+ if (xp && strcmp(xp, np) == 0) return;
326+
327+ auth = getenv("HTTP_AUTHORIZATION");
328+ if (auth) {
329+ while (*auth == ' ') auth++;
330+ if (strncmp(auth, "Bearer ", 7) == 0) {
331+ auth += 7;
332+ while (*auth == ' ') auth++;
333+ if (strcmp(auth, np) == 0) return;
334+ }
335+ }
336+
337+ qs = getenv("QUERY_STRING");
338+ if (qs && get_query_val(qs, "pwd", qpwd, sizeof(qpwd)) && strcmp(qpwd, np) == 0)
339+ return;
340+
341+ fputs("Status: 401 Unauthorized\r\n"
342+ "Content-Type: application/json; charset=utf-8\r\n"
343+ "Cache-Control: no-store\r\n"
344+ "X-Content-Type-Options: nosniff\r\n\r\n"
345+ "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
346+ exit(0);
347+}
348+
349+/* ------------------------------------------------------------------ */
350+/* Running git: argv only, never a shell */
351+/* ------------------------------------------------------------------ */
352+
353+/* Captures stdout into out (NUL terminated, truncated at outsz-1) and returns
354+ * the child's exit status, or -1 when it could not be started or timed out.
355+ * Every argv passed here is built from a constant plus one validated path. */
356+#if defined(_WIN32)
357+
358+static void win_quote(const char *in, char *out, size_t sz)
359+{
360+ size_t o = 0;
361+ o += (size_t)snprintf(out, sz, "\"");
362+ while (*in && o + 3 < sz) {
363+ if (*in == '"' || *in == '\\') { out[o++] = '\\'; }
364+ out[o++] = *in++;
365+ }
366+ if (o + 2 < sz) out[o++] = '"';
367+ out[o] = '\0';
368+}
369+
370+static int run_argv(char *const argv[], buf_t *out, int timeout_s)
371+{
372+ SECURITY_ATTRIBUTES sa;
373+ HANDLE rd = NULL, wr = NULL;
374+ STARTUPINFOA si;
375+ PROCESS_INFORMATION pi;
376+ char cmdline[4096];
377+ size_t used = 0;
378+ DWORD waited;
379+ DWORD ticks = 0;
380+ int rc = -1;
381+
382+ memset(&sa, 0, sizeof(sa));
383+ sa.nLength = sizeof(sa);
384+ sa.bInheritHandle = TRUE;
385+ if (!CreatePipe(&rd, &wr, &sa, 0)) return -1;
386+ SetHandleInformation(rd, HANDLE_FLAG_INHERIT, 0);
387+
388+ cmdline[0] = '\0';
389+ {
390+ int i;
391+ for (i = 0; argv[i]; i++) {
392+ char q[1200];
393+ size_t need;
394+ win_quote(argv[i], q, sizeof(q));
395+ need = strlen(q) + 2;
396+ if (used + need + 1 >= sizeof(cmdline)) break;
397+ if (used) cmdline[used++] = ' ';
398+ memcpy(cmdline + used, q, strlen(q));
399+ used += strlen(q);
400+ cmdline[used] = '\0';
401+ }
402+ }
403+
404+ memset(&si, 0, sizeof(si));
405+ si.cb = sizeof(si);
406+ si.dwFlags = STARTF_USESTDHANDLES;
407+ si.hStdOutput = wr;
408+ si.hStdError = wr;
409+ si.hStdInput = NULL;
410+ memset(&pi, 0, sizeof(pi));
411+
412+ if (!CreateProcessA(NULL, cmdline, NULL, NULL, TRUE, CREATE_NO_WINDOW,
413+ NULL, NULL, &si, &pi)) {
414+ CloseHandle(rd);
415+ CloseHandle(wr);
416+ return -1;
417+ }
418+ CloseHandle(wr);
419+
420+ for (;;) {
421+ DWORD avail = 0;
422+ char tmp[4096];
423+ DWORD got = 0;
424+ if (!PeekNamedPipe(rd, NULL, 0, NULL, &avail, NULL)) break;
425+ if (avail == 0) {
426+ waited = WaitForSingleObject(pi.hProcess, 20);
427+ if (waited == WAIT_OBJECT_0) {
428+ /* one last drain */
429+ if (!PeekNamedPipe(rd, NULL, 0, NULL, &avail, NULL)) break;
430+ if (avail == 0) break;
431+ } else if (timeout_s > 0 && waited == WAIT_TIMEOUT) {
432+ if (++ticks > (DWORD)timeout_s * 50) {
433+ TerminateProcess(pi.hProcess, 1);
434+ break;
435+ }
436+ }
437+ continue;
438+ }
439+ if (avail > sizeof(tmp)) avail = sizeof(tmp);
440+ if (!ReadFile(rd, tmp, avail, &got, NULL) || got == 0) break;
441+ if (out) buf_add(out, tmp, got);
442+ }
443+
444+ if (WaitForSingleObject(pi.hProcess, (DWORD)(timeout_s > 0 ? timeout_s : 20) * 1000u)
445+ != WAIT_OBJECT_0) {
446+ TerminateProcess(pi.hProcess, 1);
447+ WaitForSingleObject(pi.hProcess, 2000);
448+ }
449+ {
450+ DWORD code = 1;
451+ GetExitCodeProcess(pi.hProcess, &code);
452+ rc = (int)code;
453+ }
454+ CloseHandle(pi.hProcess);
455+ CloseHandle(pi.hThread);
456+ CloseHandle(rd);
457+ return rc;
458+}
459+
460+#else /* POSIX */
461+
462+static int run_argv(char *const argv[], buf_t *out, int timeout_s)
463+{
464+ int fds[2];
465+ pid_t pid;
466+ int status = 0;
467+ int timed_out = 0;
468+ time_t started;
469+ char *child_env_ok;
470+
471+ if (pipe(fds) != 0) return -1;
472+
473+ pid = fork();
474+ if (pid < 0) {
475+ close(fds[0]);
476+ close(fds[1]);
477+ return -1;
478+ }
479+
480+ if (pid == 0) {
481+ /* Child: stdout+stderr into the pipe, stdin from /dev/null so nothing
482+ * can ever block waiting for a password prompt. */
483+ int devnull = open("/dev/null", O_RDONLY);
484+ if (devnull >= 0) {
485+ dup2(devnull, STDIN_FILENO);
486+ if (devnull != STDIN_FILENO) close(devnull);
487+ }
488+ dup2(fds[1], STDOUT_FILENO);
489+ dup2(fds[1], STDERR_FILENO);
490+ close(fds[0]);
491+ close(fds[1]);
492+ execvp(argv[0], argv);
493+ _exit(127);
494+ }
495+
496+ close(fds[1]);
497+ child_env_ok = (char *)""; /* keep the compiler quiet about unused locals */
498+ (void)child_env_ok;
499+ started = time(NULL);
500+
501+ for (;;) {
502+ struct pollfd pfd;
503+ char tmp[4096];
504+ ssize_t n;
505+ int pr;
506+
507+ pfd.fd = fds[0];
508+ pfd.events = POLLIN;
509+ pfd.revents = 0;
510+ pr = poll(&pfd, 1, 100);
511+ if (pr > 0 && (pfd.revents & (POLLIN | POLLHUP))) {
512+ n = read(fds[0], tmp, sizeof(tmp));
513+ if (n > 0) {
514+ if (out) buf_add(out, tmp, (size_t)n);
515+ continue;
516+ }
517+ if (n == 0) break;
518+ }
519+ if (timeout_s > 0 && (time(NULL) - started) > timeout_s) {
520+ timed_out = 1;
521+ kill(pid, SIGKILL);
522+ break;
523+ }
524+ }
525+
526+ close(fds[0]);
527+
528+ while (waitpid(pid, &status, 0) < 0) {
529+ if (errno != EINTR) break;
530+ }
531+
532+ if (timed_out) return -1;
533+ if (WIFEXITED(status)) return WEXITSTATUS(status);
534+ return -1;
535+}
536+
537+#endif
538+
539+/* git -C <repo> ... */
540+static int run_git(const char *repo, char *const extra[], buf_t *out, int timeout_s)
541+{
542+ char *argv[16];
543+ int i = 0;
544+ int rc;
545+
546+ argv[i++] = (char *)"git";
547+ argv[i++] = (char *)"-C";
548+ argv[i++] = (char *)repo;
549+ while (*extra && i < 14) argv[i++] = *extra++;
550+ argv[i] = NULL;
551+
552+ rc = run_argv(argv, out, timeout_s);
553+ return rc;
554+}
555+
556+/* ------------------------------------------------------------------ */
557+/* Repository model */
558+/* ------------------------------------------------------------------ */
559+
560+typedef struct {
561+ char path[1024];
562+ char name[256];
563+ char root[768];
564+ char branch[256];
565+ char upstream[512]; /* redacted */
566+ char remote[512]; /* origin URL, userinfo stripped */
567+ int ahead;
568+ int behind;
569+ int dirty; /* changed entries (tracked + untracked) */
570+ int untracked;
571+ int staged;
572+ int conflicted;
573+ int stash;
574+ int detached;
575+ int no_upstream;
576+ int unborn;
577+ int detached_ok;
578+ long long last_ct;
579+ char last_hash[48];
580+ char last_subject[300];
581+} repo_t;
582+
583+static repo_t g_repos[MAX_REPOS];
584+static int g_repo_count;
585+
586+typedef struct {
587+ char root[768];
588+ int exists;
589+ int count;
590+ int truncated;
591+} rootstat_t;
592+
593+static rootstat_t g_roots[MAX_ROOTS];
594+static int g_root_count;
595+
596+/* ------------------------------------------------------------------ */
597+/* Discovery */
598+/* ------------------------------------------------------------------ */
599+
600+#if defined(_WIN32)
601+# define SX_ISDIR(m) (((m) & _S_IFMT) == _S_IFDIR)
602+# define SX_ISREG(m) (((m) & _S_IFMT) == _S_IFREG)
603+#else
604+# define SX_ISDIR(m) S_ISDIR(m)
605+# define SX_ISREG(m) S_ISREG(m)
606+#endif
607+
608+static int path_exists(const char *p)
609+{
610+#if defined(_WIN32)
611+ return GetFileAttributesA(p) != INVALID_FILE_ATTRIBUTES;
612+#else
613+ struct stat st;
614+ return stat(p, &st) == 0;
615+#endif
616+}
617+
618+/* A repo is a directory that has a .git entry which is either a directory
619+ * (normal clone) or a regular file (worktree / submodule pointer). */
620+static int is_repo_dir(const char *dir)
621+{
622+ char gp[1200];
623+#if defined(_WIN32)
624+ DWORD attr;
625+#else
626+ struct stat st;
627+#endif
628+
629+ snprintf(gp, sizeof(gp), "%s/.git", dir);
630+#if defined(_WIN32)
631+ attr = GetFileAttributesA(gp);
632+ if (attr == INVALID_FILE_ATTRIBUTES) return 0;
633+ return (attr & FILE_ATTRIBUTE_DIRECTORY) || !(attr & FILE_ATTRIBUTE_DIRECTORY);
634+#else
635+ if (lstat(gp, &st) != 0) {
636+ if (stat(gp, &st) != 0) return 0;
637+ }
638+ return SX_ISDIR(st.st_mode) || SX_ISREG(st.st_mode);
639+#endif
640+}
641+
642+static const char *base_name(const char *p)
643+{
644+ const char *s = strrchr(p, '/');
645+#if defined(_WIN32)
646+ const char *b = strrchr(p, '\\');
647+ if (b && (!s || b > s)) s = b;
648+#endif
649+ return s ? s + 1 : p;
650+}
651+
652+static void repo_add(const char *dir, const char *root)
653+{
654+ repo_t *r;
655+
656+ if (g_repo_count >= MAX_REPOS) return;
657+ r = &g_repos[g_repo_count++];
658+ memset(r, 0, sizeof(*r));
659+ str_copy(r->path, sizeof(r->path), dir);
660+ str_copy(r->name, sizeof(r->name), base_name(dir));
661+ str_copy(r->root, sizeof(r->root), root);
662+}
663+
664+/* Depth-limited walk. A repository is a leaf: once found we do not descend into
665+ * it, because a node's repos are the unit you want to see, not every vendored
666+ * checkout inside them. Entry budget is per root (lesson: a shared budget hides
667+ * the second root entirely). */
668+static void walk_dir(const char *dir, const char *root, int depth,
669+ int *entries, int *truncated)
670+{
671+ if (depth > MAX_DEPTH) return;
672+ if (*truncated) return;
673+
674+ if (is_repo_dir(dir)) {
675+ repo_add(dir, root);
676+ return;
677+ }
678+ if (depth == MAX_DEPTH) return;
679+
680+ {
681+#if defined(_WIN32)
682+ WIN32_FIND_DATAA fd;
683+ HANDLE h;
684+ char pat[1400];
685+ snprintf(pat, sizeof(pat), "%s\\*", dir);
686+ h = FindFirstFileA(pat, &fd);
687+ if (h == INVALID_HANDLE_VALUE) return;
688+ do {
689+ char child[1400];
690+ if (fd.cFileName[0] == '.') continue;
691+ if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) continue;
692+ if (strcmp(fd.cFileName, "node_modules") == 0) continue;
693+ if (strcmp(fd.cFileName, "__pycache__") == 0) continue;
694+ if (++(*entries) > MAX_ROOT_ENTRIES) { *truncated = 1; break; }
695+ snprintf(child, sizeof(child), "%s\\%s", dir, fd.cFileName);
696+ walk_dir(child, root, depth + 1, entries, truncated);
697+ } while (FindNextFileA(h, &fd));
698+ FindClose(h);
699+#else
700+ DIR *d = opendir(dir);
701+ struct dirent *e;
702+ if (!d) return;
703+ while ((e = readdir(d)) != NULL) {
704+ char child[1400];
705+ struct stat st;
706+ if (e->d_name[0] == '.') continue;
707+ if (strcmp(e->d_name, "node_modules") == 0) continue;
708+ if (strcmp(e->d_name, "__pycache__") == 0) continue;
709+ snprintf(child, sizeof(child), "%s/%s", dir, e->d_name);
710+ if (lstat(child, &st) != 0) continue;
711+ if (!SX_ISDIR(st.st_mode)) continue; /* never follow symlinks */
712+ if (++(*entries) > MAX_ROOT_ENTRIES) { *truncated = 1; break; }
713+ walk_dir(child, root, depth + 1, entries, truncated);
714+ }
715+ closedir(d);
716+#endif
717+ }
718+}
719+
720+static void root_add(const char *root, const char *sep_list_used)
721+{
722+ (void)sep_list_used;
723+ if (!root || !*root) return;
724+ if (g_root_count >= MAX_ROOTS) return;
725+ {
726+ int i;
727+ for (i = 0; i < g_root_count; i++)
728+ if (strcmp(g_roots[i].root, root) == 0) return;
729+ }
730+ str_copy(g_roots[g_root_count].root, sizeof(g_roots[g_root_count].root), root);
731+ g_roots[g_root_count].exists = 0;
732+ g_roots[g_root_count].count = 0;
733+ g_roots[g_root_count].truncated = 0;
734+ g_root_count++;
735+}
736+
737+static void roots_from_env(const char *name, int posix_sep)
738+{
739+ const char *v = getenv(name);
740+ char buf[2048];
741+ char sep;
742+ char *p;
743+ char *start;
744+
745+ if (!v || !*v) return;
746+ snprintf(buf, sizeof(buf), "%s", v);
747+
748+#if defined(_WIN32)
749+ sep = posix_sep ? ';' : ';';
750+ if (posix_sep) {
751+ char *q = buf;
752+ while ((q = strchr(q, ':')) != NULL) {
753+ /* a drive-letter colon is followed by a separator, not a path */
754+ if (q[1] == '\\' || q[1] == '/') { q++; continue; }
755+ *q = ';';
756+ q++;
757+ }
758+ }
759+#else
760+ sep = ':';
761+ (void)posix_sep;
762+#endif
763+
764+ start = buf;
765+ for (p = buf; ; p++) {
766+ if (*p == sep || *p == '\0') {
767+ char saved = *p;
768+ *p = '\0';
769+ str_trim(start);
770+ root_add(start, sep == ';' ? ";" : ":");
771+ if (saved == '\0') break;
772+ start = p + 1;
773+ }
774+ }
775+}
776+
777+static void collect_roots(void)
778+{
779+ const char *home = getenv("HOME");
780+
781+ const char *only = getenv("GITSTAT_ONLY_ROOTS");
782+ g_root_count = 0;
783+
784+ /* GITSTAT_ONLY_ROOTS=1 makes GITSTAT_ROOTS the complete list. It exists for
785+ * two callers: a node that wants an explicit allowlist, and the test suite,
786+ * which must see a fixture tree and nothing else. The default behaviour is
787+ * still the documented one: the platform roots plus GITSTAT_ROOTS. */
788+ if (only && *only && strcmp(only, "0") != 0) {
789+ roots_from_env("GITSTAT_ROOTS", 1);
790+ return;
791+ }
792+
793+#if defined(_WIN32)
794+ home = getenv("USERPROFILE");
795+ if (!home || !*home) home = getenv("HOMEDRIVE");
796+ root_add(home, ";");
797+ if (path_exists("D:\\codebases")) root_add("D:\\codebases", ";");
798+ if (path_exists("C:\\codebases")) root_add("C:\\codebases", ";");
799+ roots_from_env("GITSTAT_ROOTS", 1);
800+#else
801+ root_add("/workspace", ":");
802+ root_add("/codebases", ":");
803+ root_add(home, ":");
804+ roots_from_env("GITSTAT_ROOTS", 1);
805+#endif
806+}
807+
808+/* ------------------------------------------------------------------ */
809+/* git queries per repo */
810+/* ------------------------------------------------------------------ */
811+
812+/* status --porcelain=v2 --branch. Header lines carry branch state; the rest are
813+ * one changed entry each. Lines look like:
814+ * # branch.oid <hash> (all zeros when unborn)
815+ * # branch.head <name>|(detached)
816+ * # branch.upstream <ref> (absent when no upstream)
817+ * # branch.ab +N -M (absent when no upstream)
818+ * 1 XY sub mH mI mW hH hI path
819+ * 2 XY ... path
820+ * u XY ... path
821+ * ? path
822+ * ! path
823+ */
824+static void parse_status(const char *text, repo_t *r)
825+{
826+ const char *p = text;
827+ char line[1200];
828+
829+ while (*p) {
830+ size_t n = 0;
831+ while (*p && *p != '\n' && n + 1 < sizeof(line)) line[n++] = *p++;
832+ line[n] = '\0';
833+ if (*p == '\n') p++;
834+ str_trim(line);
835+ if (!line[0]) continue;
836+
837+ if (line[0] == '#') {
838+ const char *v = line + 1;
839+ while (*v == ' ') v++;
840+ if (strncmp(v, "branch.head ", 12) == 0) {
841+ const char *b = v + 12;
842+ if (strcmp(b, "(detached)") == 0) {
843+ r->detached = 1;
844+ str_copy(r->branch, sizeof(r->branch), "detached");
845+ } else {
846+ str_copy(r->branch, sizeof(r->branch), b);
847+ }
848+ } else if (strncmp(v, "branch.upstream ", 16) == 0) {
849+ char clean[512];
850+ redact_url(v + 16, clean, sizeof(clean));
851+ str_copy(r->upstream, sizeof(r->upstream), clean);
852+ } else if (strncmp(v, "branch.ab ", 10) == 0) {
853+ const char *ab = v + 10;
854+ int ahead = 0, behind = 0;
855+ if (sscanf(ab, "+%d -%d", &ahead, &behind) == 2) {
856+ r->ahead = ahead;
857+ r->behind = behind;
858+ } else if (sscanf(ab, "+%d -%d", &ahead, &behind) == 1) {
859+ r->ahead = ahead;
860+ }
861+ } else if (strncmp(v, "branch.oid ", 11) == 0) {
862+ const char *oid = v + 11;
863+ if (strcmp(oid, "(initial)") == 0) r->unborn = 1;
864+ }
865+ continue;
866+ }
867+
868+ if (line[0] == '?') {
869+ r->dirty++;
870+ r->untracked++;
871+ } else if (line[0] == '!') {
872+ /* ignored: not a change */
873+ } else if (line[0] == '1' || line[0] == '2') {
874+ r->dirty++;
875+ if (line[0] == '1') {
876+ char xy[8] = { 0, 0, 0 };
877+ if (sscanf(line, "1 %2s", xy) == 1) {
878+ if (xy[0] != '.' && xy[0] != '\0') r->staged++;
879+ }
880+ } else {
881+ r->staged++;
882+ }
883+ } else if (line[0] == 'u') {
884+ r->dirty++;
885+ r->conflicted++;
886+ }
887+ }
888+
889+ if (!r->unborn && r->branch[0] && strcmp(r->branch, "detached") != 0 && !r->upstream[0])
890+ r->no_upstream = 1;
891+ if (r->unborn) r->no_upstream = 1;
892+}
893+
894+/* "1 XY ..." -> XY codes for the detail drawer. */
895+static void status_code(const char *line, char *out, size_t sz)
896+{
897+ if (line[0] == '?') { str_copy(out, sz, "\?\?"); return; }
898+ if (line[0] == '!') { str_copy(out, sz, "!!"); return; }
899+ if (line[0] == 'u') { str_copy(out, sz, "UU"); return; }
900+ if ((line[0] == '1' || line[0] == '2') && line[1] == ' ')
901+ str_copy(out, sz, line + 2);
902+ else
903+ str_copy(out, sz, "--");
904+}
905+
906+/* Path of a v2 status line: everything after the fixed fields. */
907+static void status_path(const char *line, char *out, size_t sz)
908+{
909+ const char *p = line;
910+ int fields;
911+
912+ out[0] = '\0';
913+ if (line[0] == '?') { str_copy(out, sz, line + 2); return; }
914+ if (line[0] == '!') { str_copy(out, sz, line + 2); return; }
915+ if (line[0] == 'u') fields = 10;
916+ else if (line[0] == '2') fields = 9;
917+ else if (line[0] == '1') fields = 8;
918+ else { str_copy(out, sz, line); return; }
919+
920+ for (; fields > 0 && *p; fields--) {
921+ while (*p && *p != ' ') p++;
922+ while (*p == ' ') p++;
923+ }
924+ str_copy(out, sz, p);
925+ if (line[0] == '2') {
926+ /* rename records carry "old\tnew" */
927+ char *tab = strchr(out, '\t');
928+ if (tab) memmove(out, tab + 1, strlen(tab + 1) + 1);
929+ }
930+}
931+
932+static void query_repo(repo_t *r)
933+{
934+ buf_t out;
935+ char *status_args[] = { (char *)"status", (char *)"--porcelain=v2",
936+ (char *)"--branch", (char *)"--untracked-files=normal", NULL };
937+ char *log_args[] = { (char *)"log", (char *)"-1", (char *)"--format=%H%x09%ct%x09%s", NULL };
938+ char *stash_args[] = { (char *)"stash", (char *)"list", (char *)"--format=%gd", NULL };
939+
940+ buf_init(&out);
941+ if (run_git(r->path, status_args, &out, GIT_TIMEOUT_S) >= 0)
942+ parse_status(buf_str(&out), r);
943+ buf_free(&out);
944+
945+ buf_init(&out);
946+ if (run_git(r->path, log_args, &out, GIT_TIMEOUT_S) >= 0 && out.len > 0) {
947+ char *p = out.p;
948+ char *t1 = strchr(p, '\t');
949+ if (t1) {
950+ *t1 = '\0';
951+ str_copy(r->last_hash, sizeof(r->last_hash), p);
952+ {
953+ char *t2 = strchr(t1 + 1, '\t');
954+ if (t2) {
955+ *t2 = '\0';
956+ r->last_ct = atoll(t1 + 1);
957+ str_copy(r->last_subject, sizeof(r->last_subject), t2 + 1);
958+ } else {
959+ r->last_ct = atoll(t1 + 1);
960+ }
961+ }
962+ str_trim(r->last_subject);
963+ }
964+ }
965+ buf_free(&out);
966+
967+ buf_init(&out);
968+ {
969+ char *cfg_args[] = { (char *)"config", (char *)"--get",
970+ (char *)"remote.origin.url", NULL };
971+ if (run_git(r->path, cfg_args, &out, GIT_TIMEOUT_S) >= 0 && out.len > 0) {
972+ char raw[512];
973+ char clean[512];
974+ str_copy(raw, sizeof(raw), out.p);
975+ str_trim(raw);
976+ redact_url(raw, clean, sizeof(clean));
977+ str_copy(r->remote, sizeof(r->remote), clean);
978+ }
979+ }
980+ buf_free(&out);
981+
982+ buf_init(&out);
983+ if (run_git(r->path, stash_args, &out, GIT_TIMEOUT_S) >= 0) {
984+ const char *p = out.p;
985+ while (p && *p) {
986+ const char *nl = strchr(p, '\n');
987+ if (!nl) break;
988+ if (nl > p) r->stash++;
989+ p = nl + 1;
990+ }
991+ }
992+ buf_free(&out);
993+}
994+
995+static int repo_cmp(const void *a, const void *b)
996+{
997+ const repo_t *x = (const repo_t *)a;
998+ const repo_t *y = (const repo_t *)b;
999+
1000+ /* Dirty first (uncommitted work is the thing you came to see), then most
1001+ * recently touched, then path. */
1002+ if ((x->dirty > 0) != (y->dirty > 0)) return x->dirty > 0 ? -1 : 1;
1003+ if (x->dirty != y->dirty) return y->dirty - x->dirty;
1004+ if (x->last_ct != y->last_ct) return (x->last_ct > y->last_ct) ? -1 : 1;
1005+ return strcmp(x->path, y->path);
1006+}
1007+
1008+static void collect_repos(void)
1009+{
1010+ int i;
1011+
1012+ collect_roots();
1013+ g_repo_count = 0;
1014+
1015+ for (i = 0; i < g_root_count; i++) {
1016+ int entries = 0;
1017+ int truncated = 0;
1018+ int before = g_repo_count;
1019+
1020+ g_roots[i].exists = path_exists(g_roots[i].root) ? 1 : 0;
1021+ if (g_roots[i].exists)
1022+ walk_dir(g_roots[i].root, g_roots[i].root, 0, &entries, &truncated);
1023+ g_roots[i].truncated = truncated;
1024+ g_roots[i].count = g_repo_count - before;
1025+ }
1026+
1027+ for (i = 0; i < g_repo_count; i++) query_repo(&g_repos[i]);
1028+
1029+ if (g_repo_count > 1)
1030+ qsort(g_repos, (size_t)g_repo_count, sizeof(repo_t), repo_cmp);
1031+}
1032+
1033+/* ------------------------------------------------------------------ */
1034+/* Path allowlisting */
1035+/* ------------------------------------------------------------------ */
1036+
1037+/* realpath() cannot be handed a caller-sized buffer: glibc's fortified
1038+ * wrapper aborts when the buffer is smaller than PATH_MAX, and the paths here
1039+ * are keep-to-1024 bytes in a 1400-byte array. Ask realpath to allocate, then
1040+ * copy into our own fixed array. */
1041+static void canon_path(const char *in, char *out, size_t sz)
1042+{
1043+#if defined(_WIN32)
1044+ if (!GetFullPathNameA(in, (DWORD)sz, out, NULL)) str_copy(out, sz, in);
1045+#else
1046+ char *rp = realpath(in, NULL);
1047+ if (rp) {
1048+ str_copy(out, sz, rp);
1049+ free(rp);
1050+ } else {
1051+ str_copy(out, sz, in);
1052+ }
1053+#endif
1054+}
1055+
1056+static int under_root(const char *path)
1057+{
1058+ int i;
1059+ for (i = 0; i < g_root_count; i++) {
1060+ size_t n = strlen(g_roots[i].root);
1061+ if (n == 0) continue;
1062+ if (strncmp(path, g_roots[i].root, n) != 0) continue;
1063+ if (path[n] == '\0' || path[n] == '/' || path[n] == '\\') return 1;
1064+ }
1065+ return 0;
1066+}
1067+
1068+/* A repo path is acceptable only when it canonicalises to somewhere under an
1069+ * allowlisted root AND that directory carries a .git entry. This is the whole
1070+ * authorisation model for the API: nothing outside the roots is ever read, and
1071+ * no argument can walk upwards with "..". */
1072+static int path_allowed(const char *requested, char *canon, size_t sz)
1073+{
1074+ char tmp[1400];
1075+
1076+ if (!requested || !*requested) return 0;
1077+ if (strstr(requested, "..")) return 0;
1078+
1079+ collect_roots();
1080+ canon_path(requested, tmp, sizeof(tmp));
1081+ if (!under_root(tmp)) return 0;
1082+ if (!is_repo_dir(tmp)) return 0;
1083+ str_copy(canon, sz, tmp);
1084+ return 1;
1085+}
1086+
1087+/* ------------------------------------------------------------------ */
1088+/* JSON emitters */
1089+/* ------------------------------------------------------------------ */
1090+
1091+static void json_header(int status)
1092+{
1093+ if (status == 403)
1094+ fputs("Status: 403 Forbidden\r\n", stdout);
1095+ else if (status == 400)
1096+ fputs("Status: 400 Bad Request\r\n", stdout);
1097+ fputs("Content-Type: application/json; charset=utf-8\r\n"
1098+ "Cache-Control: no-store\r\n"
1099+ "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
1100+}
1101+
1102+static void emit_repo(buf_t *b, const repo_t *r, int detail)
1103+{
1104+ char at[40];
1105+ char up[512];
1106+
1107+ redact_url(r->upstream, up, sizeof(up));
1108+ utc_stamp((time_t)r->last_ct, at, sizeof(at));
1109+
1110+ buf_add(b, "{", 1);
1111+ buf_puts(b, "\"path\":"); json_str(b, r->path);
1112+ buf_puts(b, ",\"name\":"); json_str(b, r->name);
1113+ buf_puts(b, ",\"root\":"); json_str(b, r->root);
1114+ buf_puts(b, ",\"branch\":"); json_str(b, r->branch);
1115+ buf_puts(b, ",\"upstream\":"); json_str(b, up);
1116+ buf_puts(b, ",\"remote\":"); json_str(b, r->remote);
1117+ buf_printf(b, ",\"ahead\":%d,\"behind\":%d,\"dirty\":%d,\"untracked\":%d,"
1118+ "\"staged\":%d,\"conflicted\":%d,\"stash\":%d",
1119+ r->ahead, r->behind, r->dirty, r->untracked,
1120+ r->staged, r->conflicted, r->stash);
1121+ buf_printf(b, ",\"detached\":%s,\"no_upstream\":%s,\"unborn\":%s",
1122+ r->detached ? "true" : "false",
1123+ r->no_upstream ? "true" : "false",
1124+ r->unborn ? "true" : "false");
1125+ buf_puts(b, ",\"last_commit\":{");
1126+ buf_puts(b, "\"hash\":"); json_str(b, r->last_hash);
1127+ buf_puts(b, ",\"short\":");
1128+ {
1129+ char sh[12];
1130+ str_copy(sh, sizeof(sh), r->last_hash);
1131+ json_str(b, sh);
1132+ }
1133+ buf_printf(b, ",\"ct\":%lld", r->last_ct);
1134+ buf_puts(b, ",\"at\":"); json_str(b, at);
1135+ buf_puts(b, ",\"subject\":"); json_str(b, r->last_subject);
1136+ buf_puts(b, "}");
1137+ (void)detail;
1138+ buf_add(b, "}", 1);
1139+}
1140+
1141+static void print_repos(void)
1142+{
1143+ buf_t b;
1144+ int i;
1145+ char now[40];
1146+ int dirty = 0, ahead = 0, behind = 0, stashed = 0, detached = 0;
1147+
1148+ for (i = 0; i < g_repo_count; i++) {
1149+ if (g_repos[i].dirty > 0) dirty++;
1150+ if (g_repos[i].ahead > 0) ahead++;
1151+ if (g_repos[i].behind > 0) behind++;
1152+ if (g_repos[i].stash > 0) stashed += g_repos[i].stash;
1153+ if (g_repos[i].detached) detached++;
1154+ }
1155+ utc_stamp(time(NULL), now, sizeof(now));
1156+
1157+ buf_init(&b);
1158+ buf_printf(&b, "{\"ok\":true,\"action\":\"repos\",\"count\":%d", g_repo_count);
1159+ buf_printf(&b, ",\"table_capped\":%s", g_repo_count >= MAX_REPOS ? "true" : "false");
1160+ buf_printf(&b, ",\"summary\":{\"dirty\":%d,\"ahead\":%d,\"behind\":%d,"
1161+ "\"stashes\":%d,\"detached\":%d}",
1162+ dirty, ahead, behind, stashed, detached);
1163+ buf_puts(&b, ",\"checked_at\":"); json_str(&b, now);
1164+ buf_puts(&b, ",\"roots\":[");
1165+ for (i = 0; i < g_root_count; i++) {
1166+ if (i) buf_add(&b, ",", 1);
1167+ buf_add(&b, "{", 1);
1168+ buf_puts(&b, "\"root\":"); json_str(&b, g_roots[i].root);
1169+ buf_printf(&b, ",\"exists\":%s,\"count\":%d,\"truncated\":%s",
1170+ g_roots[i].exists ? "true" : "false", g_roots[i].count,
1171+ g_roots[i].truncated ? "true" : "false");
1172+ buf_add(&b, "}", 1);
1173+ }
1174+ buf_puts(&b, "],\"repos\":[");
1175+ for (i = 0; i < g_repo_count; i++) {
1176+ if (i) buf_add(&b, ",", 1);
1177+ emit_repo(&b, &g_repos[i], 0);
1178+ }
1179+ buf_puts(&b, "]}\n");
1180+ fputs(buf_str(&b), stdout);
1181+ buf_free(&b);
1182+}
1183+
1184+static int print_repo_detail(const char *path)
1185+{
1186+ char canon[1400];
1187+ repo_t *r = NULL;
1188+ buf_t b;
1189+ buf_t out;
1190+ int i;
1191+ char at[40];
1192+
1193+ if (!path_allowed(path, canon, sizeof(canon))) {
1194+ json_header(403);
1195+ fputs("{\"ok\":false,\"error\":\"path not in an allowlisted root\"}\n", stdout);
1196+ return 0;
1197+ }
1198+
1199+ /* Prefer the record we already measured; fall back to measuring it now when
1200+ * the path was not part of the (budgeted) discovery walk. */
1201+ for (i = 0; i < g_repo_count; i++) {
1202+ if (strcmp(g_repos[i].path, canon) == 0) { r = &g_repos[i]; break; }
1203+ }
1204+ if (!r) {
1205+ if (g_repo_count >= MAX_REPOS) {
1206+ json_header(400);
1207+ fputs("{\"ok\":false,\"error\":\"repository table full\"}\n", stdout);
1208+ return 0;
1209+ }
1210+ r = &g_repos[g_repo_count];
1211+ memset(r, 0, sizeof(*r));
1212+ str_copy(r->path, sizeof(r->path), canon);
1213+ str_copy(r->name, sizeof(r->name), base_name(canon));
1214+ str_copy(r->root, sizeof(r->root), "");
1215+ query_repo(r);
1216+ g_repo_count++;
1217+ }
1218+
1219+ buf_init(&b);
1220+ buf_printf(&b, "{\"ok\":true,\"action\":\"repo\",\"repo\":");
1221+ emit_repo(&b, r, 1);
1222+
1223+ /* changed files, max MAX_CHANGED */
1224+ {
1225+ char *status_args[] = { (char *)"status", (char *)"--porcelain=v2",
1226+ (char *)"--untracked-files=normal", NULL };
1227+ int shown = 0, total = 0;
1228+ int trunc = 0;
1229+
1230+ buf_init(&out);
1231+ buf_puts(&b, ",\"changed\":[");
1232+ if (run_git(r->path, status_args, &out, GIT_TIMEOUT_S) >= 0) {
1233+ const char *p = out.p;
1234+ char line[1200];
1235+ while (p && *p) {
1236+ size_t n = 0;
1237+ while (*p && *p != '\n' && n + 1 < sizeof(line)) line[n++] = *p++;
1238+ line[n] = '\0';
1239+ if (*p == '\n') p++;
1240+ str_trim(line);
1241+ if (!line[0] || line[0] == '#') continue;
1242+ total++;
1243+ if (shown >= MAX_CHANGED) { trunc = 1; continue; }
1244+ {
1245+ char code[8], fp[900];
1246+ status_code(line, code, sizeof(code));
1247+ status_path(line, fp, sizeof(fp));
1248+ if (shown) buf_add(&b, ",", 1);
1249+ buf_add(&b, "{", 1);
1250+ buf_puts(&b, "\"code\":"); json_str(&b, code);
1251+ buf_puts(&b, ",\"path\":"); json_str(&b, fp);
1252+ buf_add(&b, "}", 1);
1253+ shown++;
1254+ }
1255+ }
1256+ }
1257+ buf_free(&out);
1258+ buf_printf(&b, "],\"changed_count\":%d,\"changed_truncated\":%s",
1259+ total, trunc ? "true" : "false");
1260+ }
1261+
1262+ /* recent commits */
1263+ {
1264+ char *log_args[] = { (char *)"log", (char *)"-20",
1265+ (char *)"--format=%H%x09%ct%x09%an%x09%s", NULL };
1266+ int n = 0;
1267+
1268+ buf_init(&out);
1269+ buf_puts(&b, ",\"commits\":[");
1270+ if (run_git(r->path, log_args, &out, GIT_TIMEOUT_S) >= 0) {
1271+ const char *p = out.p;
1272+ while (p && *p && n < MAX_COMMITS) {
1273+ const char *nl = strchr(p, '\n');
1274+ size_t len = nl ? (size_t)(nl - p) : strlen(p);
1275+ char line[1500];
1276+ if (len >= sizeof(line)) len = sizeof(line) - 1;
1277+ memcpy(line, p, len);
1278+ line[len] = '\0';
1279+ p = nl ? nl + 1 : p + len;
1280+ if (!line[0]) continue;
1281+ {
1282+ char *t1 = strchr(line, '\t');
1283+ char *t2;
1284+ char *t3;
1285+ if (!t1) continue;
1286+ *t1 = '\0';
1287+ t2 = strchr(t1 + 1, '\t');
1288+ if (!t2) continue;
1289+ *t2 = '\0';
1290+ t3 = strchr(t2 + 1, '\t');
1291+ if (t3) *t3 = '\0';
1292+ utc_stamp((time_t)atoll(t1 + 1), at, sizeof(at));
1293+ if (n) buf_add(&b, ",", 1);
1294+ buf_add(&b, "{", 1);
1295+ buf_puts(&b, "\"hash\":"); json_str(&b, line);
1296+ buf_printf(&b, ",\"ct\":%lld", (long long)atoll(t1 + 1));
1297+ buf_puts(&b, ",\"author\":"); json_str(&b, t2 + 1);
1298+ buf_puts(&b, ",\"subject\":"); json_str(&b, t3 ? t3 + 1 : "");
1299+ buf_add(&b, "}", 1);
1300+ n++;
1301+ }
1302+ }
1303+ }
1304+ buf_free(&out);
1305+ buf_add(&b, "]", 1);
1306+ }
1307+
1308+ buf_puts(&b, "}\n");
1309+ fputs(buf_str(&b), stdout);
1310+ buf_free(&b);
1311+ return 0;
1312+}
1313+
1314+static int do_fetch(const char *path, int *status_out)
1315+{
1316+ char canon[1400];
1317+ buf_t b;
1318+ buf_t out;
1319+ int rc;
1320+ repo_t tmp;
1321+
1322+ if (!path_allowed(path, canon, sizeof(canon))) {
1323+ json_header(403);
1324+ fputs("{\"ok\":false,\"error\":\"path not in an allowlisted root\"}\n", stdout);
1325+ return 0;
1326+ }
1327+
1328+ json_header(0);
1329+ if (!getenv("GITSTAT_ALLOW_FETCH") || strcmp(getenv("GITSTAT_ALLOW_FETCH"), "1") != 0) {
1330+ buf_init(&b);
1331+ buf_puts(&b, "{\"ok\":false,\"error\":\"fetch is disabled on this node\","
1332+ "\"hint\":\"set GITSTAT_ALLOW_FETCH=1 to enable git fetch --prune\"}\n");
1333+ fputs(buf_str(&b), stdout);
1334+ buf_free(&b);
1335+ return 0;
1336+ }
1337+
1338+ {
1339+ char *fetch_args[] = { (char *)"fetch", (char *)"--prune", NULL };
1340+ buf_init(&out);
1341+ rc = run_git(canon, fetch_args, &out, FETCH_TIMEOUT_S);
1342+
1343+ memset(&tmp, 0, sizeof(tmp));
1344+ str_copy(tmp.path, sizeof(tmp.path), canon);
1345+ query_repo(&tmp);
1346+
1347+ buf_init(&b);
1348+ buf_printf(&b, "{\"ok\":%s,\"action\":\"fetch\",\"exit\":%d",
1349+ rc == 0 ? "true" : "false", rc);
1350+ buf_puts(&b, ",\"path\":"); json_str(&b, canon);
1351+ buf_puts(&b, ",\"output\":"); json_str(&b, buf_str(&out));
1352+ buf_printf(&b, ",\"ahead\":%d,\"behind\":%d,\"branch\":", tmp.ahead, tmp.behind);
1353+ json_str(&b, tmp.branch);
1354+ buf_puts(&b, "}\n");
1355+ fputs(buf_str(&b), stdout);
1356+ buf_free(&b);
1357+ buf_free(&out);
1358+ }
1359+ (void)status_out;
1360+ return 0;
1361+}
1362+
1363+/* ------------------------------------------------------------------ */
1364+/* HTML UI */
1365+/* ------------------------------------------------------------------ */
1366+
1367+/* Split UI_HTML on the two control-byte placeholders and expand them into the
1368+ * theme macros, so the page and the bot palette can never drift apart. */
1369+static void emit_ui(void)
1370+{
1371+ const char *p = UI_HTML;
1372+
1373+ while (*p) {
1374+ if (*p == '\001') {
1375+ fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS
1376+ ":root{--tx:var(--text);--mu:var(--text-2);--ln:var(--line);"
1377+ "--ac:var(--blue);--sf:var(--bg-card);--sf2:var(--surface-2)}"
1378+ "</style>", stdout);
1379+ p++;
1380+ } else if (*p == '\002') {
1381+ fputs(SX_BOT_THEME_HANDOFF, stdout);
1382+ p++;
1383+ } else {
1384+ putchar(*p++);
1385+ }
1386+ }
1387+}
1388+
1389+static int mode_html(void)
1390+{
1391+ fputs("Content-Type: text/html; charset=utf-8\r\n"
1392+ "Cache-Control: no-store\r\n"
1393+ "X-Content-Type-Options: nosniff\r\n"
1394+ "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; "
1395+ "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; "
1396+ "form-action 'none'; base-uri 'none'\r\n\r\n", stdout);
1397+ emit_ui();
1398+ return 0;
1399+}
1400+
1401+/* ------------------------------------------------------------------ */
1402+/* Modes */
1403+/* ------------------------------------------------------------------ */
1404+
1405+static int mode_meta(void)
1406+{
1407+ fputs("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"}\n", stdout);
1408+ return 0;
1409+}
1410+
1411+static int mode_json(const char *qs)
1412+{
1413+ char action[64];
1414+ char path[1024];
1415+
1416+ action[0] = '\0';
1417+ get_query_val(qs, "action", action, sizeof(action));
1418+
1419+ if (strcmp(action, "repo") == 0) {
1420+ collect_roots();
1421+ get_query_val(qs, "path", path, sizeof(path));
1422+ json_header(0);
1423+ return print_repo_detail(path);
1424+ }
1425+
1426+ if (strcmp(action, "fetch") == 0) {
1427+ int st = 0;
1428+ collect_roots();
1429+ get_query_val(qs, "path", path, sizeof(path));
1430+ if (!is_post_request()) {
1431+ json_header(400);
1432+ fputs("{\"ok\":false,\"error\":\"fetch is POST only\"}\n", stdout);
1433+ return 0;
1434+ }
1435+ return do_fetch(path, &st);
1436+ }
1437+
1438+ if (strcmp(action, "repos") == 0 || !action[0] || strcmp(action, "all") == 0) {
1439+ collect_repos();
1440+ json_header(0);
1441+ print_repos();
1442+ return 0;
1443+ }
1444+
1445+ json_header(0);
1446+ fputs("{\"ok\":false,\"error\":\"unknown action\"}\n", stdout);
1447+ return 0;
1448+}
1449+
1450+int main(int argc, char **argv)
1451+{
1452+ const char *qs;
1453+ int embed;
1454+
1455+ if ((argc > 1 && strcmp(argv[1], "--meta") == 0) ||
1456+ (getenv("SX_PLUGIN_META") && *getenv("SX_PLUGIN_META")))
1457+ return mode_meta();
1458+
1459+ require_node_auth();
1460+
1461+ qs = getenv("QUERY_STRING");
1462+ if (!qs) qs = "";
1463+
1464+ if (is_post_request() && strstr(qs, "action=fetch")) {
1465+ char path[1024];
1466+ collect_roots();
1467+ get_query_val(qs, "path", path, sizeof(path));
1468+ return do_fetch(path, NULL);
1469+ }
1470+
1471+ if (strstr(qs, "action=") || strstr(qs, "format=json") || is_post_request())
1472+ return mode_json(qs);
1473+
1474+ embed = (strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL);
1475+ (void)embed;
1476+ return mode_html();
1477+}
src/ui.html+470−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..e51377bindex 0000000..e51377b
--- /dev/null--- /dev/null
+++ b/src/ui.html+++ b/src/ui.html
@@ -0,0 +1,470 @@@@ -0,0 +1,470 @@
1+<!DOCTYPE html>
2+<html lang="en"><head><meta charset="utf-8">
3+<meta name="viewport" content="width=device-width,initial-scale=1">
4+<title>git</title>
5+<!--TOKENS-->
6+<style>
7+*{box-sizing:border-box}
8+html,body{margin:0;min-height:100%}
9+body{background:var(--bg);color:var(--tx,var(--text));font-family:var(--font);
10+ font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}
11+.wrap{max-width:1200px;margin:0 auto;padding:18px 18px 40px}
12+.top{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px}
13+.brand{font-size:11px;font-weight:700;letter-spacing:.09em;text-transform:uppercase;
14+ color:var(--mu,var(--text-2))}
15+.title{font-size:19px;font-weight:680;margin:0;letter-spacing:-.01em}
16+.sp{flex:1 1 auto}
17+.pill{font-size:11px;font-weight:600;padding:3px 9px;border-radius:999px;
18+ background:var(--sf2,var(--surface-2));color:var(--mu,var(--text-2));
19+ border:1px solid var(--ln,var(--line));white-space:nowrap}
20+.icon-btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;
21+ background:var(--sf2,var(--surface-2));border:1px solid var(--ln,var(--line));
22+ color:var(--text);border-radius:9px;height:30px;padding:0 11px;cursor:pointer;
23+ font-family:inherit;font-size:12px;font-weight:600}
24+.icon-btn:hover{background:var(--surface-hover);border-color:var(--line-2)}
25+.icon-btn:active{transform:scale(.97)}
26+.icon-btn svg{width:14px;height:14px;fill:none;stroke:currentColor;stroke-width:1.9;
27+ stroke-linecap:round;stroke-linejoin:round}
28+.icon-btn[disabled]{opacity:.5;cursor:default}
29+
30+.chips{display:grid;grid-template-columns:repeat(auto-fit,minmax(126px,1fr));gap:10px;
31+ margin-bottom:14px}
32+.chip{background:var(--sf,var(--bg-card));border:1px solid var(--ln,var(--line));
33+ border-radius:12px;padding:11px 13px;cursor:pointer;font-family:inherit;
34+ text-align:left;color:var(--text)}
35+.chip:hover{border-color:var(--line-2)}
36+.chip.sel{box-shadow:inset 0 0 0 1.5px var(--ac,var(--blue))}
37+.chip .k{display:flex;align-items:center;gap:6px;font-size:10.5px;font-weight:700;
38+ letter-spacing:.07em;text-transform:uppercase;color:var(--mu,var(--text-2))}
39+.chip .k svg{width:12px;height:12px;fill:none;stroke:currentColor;stroke-width:2;
40+ stroke-linecap:round;stroke-linejoin:round}
41+.chip .v{font-family:var(--mono);font-size:23px;font-weight:700;margin-top:3px;
42+ letter-spacing:-.02em}
43+.chip.ok .v{color:var(--green)}
44+.chip.bad .v{color:var(--red)}
45+.chip.warn .v{color:var(--orange)}
46+.chip.none .v{color:var(--mu,var(--text-2))}
47+
48+.bar{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-bottom:10px}
49+.search{flex:1 1 240px;min-width:0;padding:9px 12px;border-radius:10px;
50+ border:1px solid var(--ln,var(--line));background:var(--input-bg);color:var(--text);
51+ font-family:inherit;font-size:13px}
52+.search:focus{outline:2px solid var(--ac,var(--blue));outline-offset:-1px}
53+select{padding:9px 11px;border-radius:10px;border:1px solid var(--ln,var(--line));
54+ background:var(--input-bg);color:var(--text);font-family:inherit;font-size:13px}
55+
56+.panel{background:var(--sf,var(--bg-card));border:1px solid var(--ln,var(--line));
57+ border-radius:14px;overflow:hidden}
58+.tb{width:100%;overflow-x:auto}
59+table{width:100%;border-collapse:collapse;font-size:13px}
60+th{text-align:left;font-size:10.5px;letter-spacing:.07em;text-transform:uppercase;
61+ color:var(--mu,var(--text-2));font-weight:700;padding:9px 12px;
62+ border-bottom:1px solid var(--ln,var(--line));white-space:nowrap;
63+ background:var(--sf2,var(--surface-2))}
64+td{padding:9px 12px;border-bottom:1px solid var(--ln,var(--line));
65+ vertical-align:middle;white-space:nowrap}
66+tr.row{cursor:pointer}
67+tr.row:hover td{background:var(--surface-hover)}
68+tr.row:last-child td{border-bottom:0}
69+tr.row.sel td{background:var(--sf2,var(--surface-2))}
70+.mo{font-family:var(--mono);font-size:12.5px}
71+.name{font-weight:600;max-width:300px;overflow:hidden;text-overflow:ellipsis}
72+.sub{font-size:11.5px;color:var(--mu,var(--text-2));max-width:300px;
73+ overflow:hidden;text-overflow:ellipsis;margin-top:1px}
74+.subtext{color:var(--text);font-size:12.5px;max-width:340px}
75+td.c-last{max-width:360px;overflow:hidden}
76+.subtext{white-space:normal;display:-webkit-box;-webkit-line-clamp:2;
77+ -webkit-box-orient:vertical;overflow:hidden}
78+.hash{font-family:var(--mono);font-size:11.5px;color:var(--mu,var(--text-2))}
79+.tag{font-size:10px;font-weight:700;padding:2px 8px;border-radius:6px;
80+ white-space:nowrap;letter-spacing:.03em;display:inline-block;margin:1px 3px 1px 0}
81+.t-dirty{background:rgba(255,159,10,.16);color:var(--orange)}
82+.t-ahead{background:rgba(48,209,88,.16);color:var(--green)}
83+.t-behind{background:rgba(255,69,58,.16);color:var(--red)}
84+.t-det{background:rgba(191,90,242,.16);color:var(--purple)}
85+.t-noup{background:rgba(142,142,147,.16);color:var(--gray)}
86+.t-stash{background:rgba(94,92,230,.16);color:var(--indigo)}
87+.t-clean{background:rgba(48,209,88,.12);color:var(--green)}
88+.t-unborn{background:rgba(255,214,10,.16);color:var(--yellow)}
89+.muted{color:var(--mu,var(--text-2))}
90+.empty{padding:28px 16px;text-align:center;color:var(--mu,var(--text-2));font-size:13px}
91+.hide{display:none!important}
92+
93+.drawer{position:fixed;top:0;right:0;bottom:0;width:min(560px,100%);z-index:60;
94+ background:var(--modal-bg,var(--bg-card));border-left:1px solid var(--ln,var(--line));
95+ box-shadow:var(--shadow-lg);transform:translateX(102%);transition:transform .22s var(--ease);
96+ display:flex;flex-direction:column}
97+.drawer.open{transform:none}
98+.dh{display:flex;align-items:center;gap:10px;padding:14px 16px;
99+ border-bottom:1px solid var(--ln,var(--line))}
100+.dh .t{font-size:15px;font-weight:680;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
101+.db{overflow:auto;padding:14px 16px 28px;flex:1 1 auto}
102+.dsec{font-size:10.5px;letter-spacing:.07em;text-transform:uppercase;font-weight:700;
103+ color:var(--mu,var(--text-2));margin:16px 0 8px}
104+.dsec:first-child{margin-top:0}
105+.flist{list-style:none;margin:0;padding:0;font-size:12.5px}
106+.flist li{display:flex;gap:9px;align-items:baseline;padding:4px 0;
107+ border-bottom:1px solid var(--ln,var(--line))}
108+.flist li:last-child{border-bottom:0}
109+.flist .c{font-family:var(--mono);font-size:11px;font-weight:700;width:26px;flex:0 0 26px}
110+.flist .p{font-family:var(--mono);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
111+.c-mod{color:var(--orange)}.c-add{color:var(--green)}.c-del{color:var(--red)}
112+.c-unt{color:var(--gray)}.c-con{color:var(--purple)}
113+.clist{list-style:none;margin:0;padding:0;font-size:12.5px}
114+.clist li{padding:5px 0;border-bottom:1px solid var(--ln,var(--line))}
115+.clist li:last-child{border-bottom:0}
116+.clist .s{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
117+.clist .m{font-size:11px;color:var(--mu,var(--text-2));display:flex;gap:8px}
118+.scrim{position:fixed;inset:0;background:rgba(0,0,0,.35);z-index:55}
119+.scrim.hide{display:none}
120+.note{font-size:11.5px;color:var(--mu,var(--text-2));margin-top:8px}
121+.err{color:var(--red);font-size:12.5px;margin-top:8px}
122+
123+@media(max-width:760px){
124+ .wrap{padding:12px 12px 28px}
125+ .drawer{width:100%;border-left:0}
126+ col.c-root,th.c-root,td.c-root{display:none}
127+}
128+@media(max-width:760px){
129+ /* Two fixed columns: the repo block and the commit block. The commit subject
130+ * is allowed to wrap onto a second line, which is the only way it fits at
131+ * 390 px without a mid-word cut at the panel edge. */
132+ table{table-layout:fixed;width:100%}
133+ td.c-repo{white-space:normal}
134+ td.c-repo .sub{overflow:visible;text-overflow:clip;line-height:1.6}
135+ td.c-last{max-width:none;white-space:normal}
136+ td .sub,.subtext{max-width:none}
137+ col.c-repo{width:48%}
138+ col.c-last{width:52%}
139+ .name{max-width:none}
140+}
141+@media(max-width:560px){
142+ .chips{grid-template-columns:repeat(auto-fit,minmax(104px,1fr));gap:8px}
143+ .chip .v{font-size:19px}
144+ col.c-sync,th.c-sync,td.c-sync{display:none}
145+ th,td{padding:8px 9px}
146+ .name,td .sub,.subtext{max-width:none}
147+}
148+</style></head>
149+<body>
150+<div class="wrap">
151+ <div class="top">
152+ <div>
153+ <div class="brand">SCORPIOX BOT</div>
154+ <h1 class="title">git</h1>
155+ </div>
156+ <span class="pill" id="rootPill">local</span>
157+ <span class="sp"></span>
158+ <button class="icon-btn embed-hide" id="thBtn" type="button" title="Toggle appearance">
159+ <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="4"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M19.1 4.9L17 7M7 17l-2.1 2.1"/></svg>
160+ Theme
161+ </button>
162+ <button class="icon-btn" id="rfBtn" type="button">
163+ <svg viewBox="0 0 24 24"><path d="M21 12a9 9 0 1 1-2.6-6.4"/><path d="M21 3v6h-6"/></svg>
164+ Rescan
165+ </button>
166+ </div>
167+
168+ <div class="chips" id="chips">
169+ <button class="chip none" data-filter="all" id="vAllChip" type="button">
170+ <div class="k"><svg viewBox="0 0 24 24"><path d="M3 7h18M3 12h18M3 17h18"/></svg>All repos</div>
171+ <div class="v" id="vAll">0</div>
172+ </button>
173+ <button class="chip warn" data-filter="dirty" type="button">
174+ <div class="k"><svg viewBox="0 0 24 24"><path d="M12 8v5M12 16h.01"/><circle cx="12" cy="12" r="9"/></svg>Dirty</div>
175+ <div class="v" id="vDirty">0</div>
176+ </button>
177+ <button class="chip ok" data-filter="ahead" type="button">
178+ <div class="k"><svg viewBox="0 0 24 24"><path d="M12 19V5M6 11l6-6 6 6"/></svg>Ahead</div>
179+ <div class="v" id="vAhead">0</div>
180+ </button>
181+ <button class="chip bad" data-filter="behind" type="button">
182+ <div class="k"><svg viewBox="0 0 24 24"><path d="M12 5v14M6 13l6 6 6-6"/></svg>Behind</div>
183+ <div class="v" id="vBehind">0</div>
184+ </button>
185+ <button class="chip none" data-filter="stash" type="button">
186+ <div class="k"><svg viewBox="0 0 24 24"><path d="M4 7h16M4 12h16M4 17h10"/></svg>Stashes</div>
187+ <div class="v" id="vStash">0</div>
188+ </button>
189+ </div>
190+
191+ <div class="bar">
192+ <input class="search" id="q" type="search" placeholder="Filter by repo, branch, or last commit" autocomplete="off">
193+ <select id="sc" aria-label="Filter by state">
194+ <option value="">All states</option>
195+ <option value="dirty">Dirty</option>
196+ <option value="clean">Clean</option>
197+ <option value="ahead">Ahead</option>
198+ <option value="behind">Behind</option>
199+ <option value="detached">Detached</option>
200+ <option value="noup">No upstream</option>
201+ </select>
202+ </div>
203+
204+ <div class="panel">
205+ <div class="tb">
206+ <table>
207+ <colgroup>
208+ <col class="c-repo"><col class="c-root"><col class="c-sync"><col class="c-sync"><col class="c-last">
209+ </colgroup>
210+ <thead><tr>
211+ <th>Repository</th>
212+ <th class="c-root">Root</th>
213+ <th class="c-sync">Sync</th>
214+ <th class="c-sync">Stash</th>
215+ <th>Last commit</th>
216+ </tr></thead>
217+ <tbody id="rows"></tbody>
218+ </table>
219+ </div>
220+ <div class="empty hide" id="empty">No repositories found under the allowlisted roots.</div>
221+ </div>
222+ <div class="note" id="footNote">Read-only. Fetching from a remote stays off unless the node operator enables it.</div>
223+</div>
224+
225+<div class="scrim hide" id="scrim"></div>
226+<aside class="drawer" id="drawer" aria-hidden="true">
227+ <div class="dh">
228+ <div class="t" id="dName">Repository</div>
229+ <span class="sp"></span>
230+ <button class="icon-btn" id="dClose" type="button" title="Close">
231+ <svg viewBox="0 0 24 24"><path d="M18 6 6 18M6 6l12 12"/></svg>
232+ </button>
233+ </div>
234+ <div class="db" id="dBody"></div>
235+</aside>
236+
237+<script>
238+(function(){
239+ var q = new URLSearchParams(location.search);
240+ var node = q.get('node') || '';
241+ var sid = q.get('id') || '';
242+ var pwd = q.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) ||
243+ localStorage.getItem('bot_active_pwd') || '';
244+ /* When the bot serves this page through its proxy, ?plugin= is the route back.
245+ * Opened directly on the node, the plugin itself is the route. */
246+ var HUB = q.get('plugin') || '';
247+
248+ function api(action, extra){
249+ var u = (HUB ? '/plugins?plugin=' + encodeURIComponent(HUB) : '/plugin_gitstat') +
250+ '?action=' + encodeURIComponent(action) +
251+ (extra ? ('&' + extra) : '') +
252+ (node ? '&node=' + encodeURIComponent(node) : '') +
253+ (sid ? '&id=' + encodeURIComponent(sid) : '') +
254+ (pwd ? '&pwd=' + encodeURIComponent(pwd) : '');
255+ return fetch(u, {headers: pwd ? {'X-Bot-Password': pwd} : {}}).then(function(r){
256+ if (!r.ok) throw new Error('HTTP ' + r.status);
257+ return r.json();
258+ });
259+ }
260+
261+ var DATA = [];
262+ var ROOTS = [];
263+ var FILTER = 'all';
264+ var SEL = '';
265+
266+ function esc(v){
267+ return String(v == null ? '' : v).replace(/[&<>"']/g, function(c){
268+ return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];
269+ });
270+ }
271+ function txt(id, v){ var e = document.getElementById(id); if (e) e.textContent = v; }
272+
273+ function ago(ct){
274+ if (!ct) return '-';
275+ var s = Math.max(0, Math.floor(Date.now()/1000) - ct);
276+ if (s < 60) return s + 's ago';
277+ if (s < 3600) return Math.floor(s/60) + 'm ago';
278+ if (s < 86400) return Math.floor(s/3600) + 'h ago';
279+ if (s < 2592000) return Math.floor(s/86400) + 'd ago';
280+ if (s < 31536000) return Math.floor(s/2592000) + 'mo ago';
281+ return Math.floor(s/31536000) + 'y ago';
282+ }
283+
284+ function badges(r){
285+ var h = '';
286+ if (r.dirty > 0) h += '<span class="tag t-dirty">' + r.dirty + ' changed</span>';
287+ if (r.ahead > 0) h += '<span class="tag t-ahead">+' + r.ahead + '</span>';
288+ if (r.behind > 0) h += '<span class="tag t-behind">-' + r.behind + '</span>';
289+ if (r.detached) h += '<span class="tag t-det">detached</span>';
290+ if (r.no_upstream && !r.detached) h += '<span class="tag t-noup">no upstream</span>';
291+ if (r.unborn) h += '<span class="tag t-unborn">unborn</span>';
292+ if (r.stash > 0) h += '<span class="tag t-stash">' + r.stash + ' stash</span>';
293+ if (r.dirty === 0 && !r.detached && !r.unborn) h += '<span class="tag t-clean">clean</span>';
294+ return h;
295+ }
296+
297+ function matches(r){
298+ if (FILTER === 'dirty' && !(r.dirty > 0)) return false;
299+ if (FILTER === 'ahead' && !(r.ahead > 0)) return false;
300+ if (FILTER === 'behind' && !(r.behind > 0)) return false;
301+ if (FILTER === 'stash' && !(r.stash > 0)) return false;
302+
303+ var sc = document.getElementById('sc').value;
304+ if (sc === 'dirty' && !(r.dirty > 0)) return false;
305+ if (sc === 'clean' && (r.dirty > 0)) return false;
306+ if (sc === 'ahead' && !(r.ahead > 0)) return false;
307+ if (sc === 'behind' && !(r.behind > 0)) return false;
308+ if (sc === 'detached' && !r.detached) return false;
309+ if (sc === 'noup' && !r.no_upstream) return false;
310+
311+ var f = (document.getElementById('q').value || '').toLowerCase();
312+ if (!f) return true;
313+ var hay = (r.name + ' ' + r.path + ' ' + r.branch + ' ' + r.upstream + ' ' +
314+ (r.last_commit ? r.last_commit.subject : '')).toLowerCase();
315+ return hay.indexOf(f) >= 0;
316+ }
317+
318+ function render(){
319+ var out = DUPS(DATA), rows = document.getElementById('rows'), h = '';
320+ for (var i = 0; i < out.length; i++) {
321+ var r = out[i], lc = r.last_commit || {};
322+ h += '<tr class="row' + (SEL === r.path ? ' sel' : '') + '" data-p="' + esc(r.path) + '">' +
323+ '<td class="c-repo"><div class="name">' + esc(r.name) + '</div>' +
324+ '<div class="sub"><span class="mo">' + esc(r.branch || '-') + '</span> ' + badges(r) + '</div></td>' +
325+ '<td class="c-root muted mo">' + esc(r.root || '-') + '</td>' +
326+ '<td class="c-sync mo">' + (r.ahead || r.behind ? ('+' + r.ahead + ' -' + r.behind) : '<span class="muted">-</span>') + '</td>' +
327+ '<td class="c-sync mo">' + (r.stash ? r.stash : '<span class="muted">-</span>') + '</td>' +
328+ '<td class="c-last"><div class="sub subtext">' + esc(lc.subject || '-') + '</div>' +
329+ '<div class="hash">' + esc((lc.short || '').slice(0, 8)) + ' &middot; ' + ago(lc.ct) + '</div></td>' +
330+ '</tr>';
331+ }
332+ rows.innerHTML = h;
333+ document.getElementById('empty').className = out.length ? 'empty hide' : 'empty';
334+
335+ var b = rows.querySelectorAll('tr.row');
336+ for (var k = 0; k < b.length; k++) {
337+ b[k].onclick = function(){
338+ openDetail(this.getAttribute('data-p'));
339+ };
340+ }
341+ }
342+ function DUPS(a){ var o = []; for (var i=0;i<a.length;i++) if (matches(a[i])) o.push(a[i]); return o; }
343+
344+ function setCounts(s, n){
345+ s = s || {};
346+ txt('vAll', n || 0);
347+ txt('vDirty', s.dirty || 0);
348+ txt('vAhead', s.ahead || 0);
349+ txt('vBehind', s.behind || 0);
350+ txt('vStash', s.stashes || 0);
351+ }
352+
353+ function load(){
354+ var btn = document.getElementById('rfBtn');
355+ btn.disabled = true;
356+ return api('repos').then(function(d){
357+ DATA = d.repos || [];
358+ ROOTS = d.roots || [];
359+ setCounts(d.summary, d.count);
360+ var ex = [];
361+ for (var i = 0; i < ROOTS.length; i++) if (ROOTS[i].exists) ex.push(ROOTS[i].root);
362+ txt('rootPill', ex.length ? (ex.length + ' root' + (ex.length === 1 ? '' : 's')) : 'no roots');
363+ render();
364+ }).catch(function(e){
365+ txt('rootPill', 'error');
366+ document.getElementById('empty').className = 'empty';
367+ document.getElementById('empty').textContent = 'Load failed: ' + e.message;
368+ }).then(function(){ btn.disabled = false; });
369+ }
370+
371+ function codeClass(c){
372+ if (c === '\?\?' || c === '!!') return 'c-unt';
373+ if (c === 'UU' || c === 'AA' || c === 'DD') return 'c-con';
374+ if (c.indexOf('A') >= 0) return 'c-add';
375+ if (c.indexOf('D') >= 0) return 'c-del';
376+ return 'c-mod';
377+ }
378+
379+ function openDetail(path){
380+ SEL = path;
381+ var d = document.getElementById('drawer');
382+ var s = document.getElementById('scrim');
383+ d.classList.add('open');
384+ d.setAttribute('aria-hidden', 'false');
385+ s.classList.remove('hide');
386+ document.getElementById('dName').textContent = path.split(/[\\/]/).pop() || path;
387+ document.getElementById('dBody').innerHTML = '<div class="muted">Loading…</div>';
388+
389+ api('repo', 'path=' + encodeURIComponent(path)).then(function(j){
390+ if (!j.ok) throw new Error(j.error || 'failed');
391+ var r = j.repo || {}, lc = r.last_commit || {};
392+ var h = '';
393+ h += '<div class="dsec">Repository</div>';
394+ h += '<div class="mo" style="font-size:12px;word-break:break-all">' + esc(r.path) + '</div>';
395+ h += '<div style="margin-top:8px">' + badges(r) + '</div>';
396+ h += '<div class="note">branch <span class="mo">' + esc(r.branch || '-') + '</span>' +
397+ (r.upstream ? ' &rarr; <span class="mo">' + esc(r.upstream) + '</span>' : '') + '</div>';
398+
399+ h += '<div class="dsec">Last commit</div>';
400+ h += '<div class="clist"><li><div class="s">' + esc(lc.subject || '-') + '</div>' +
401+ '<div class="m"><span class="mo">' + esc((lc.short || '').slice(0, 8)) + '</span>' +
402+ '<span>' + ago(lc.ct) + '</span></div></li></div>';
403+
404+ var ch = j.changed || [];
405+ h += '<div class="dsec">Changed files (' + (j.changed_count || 0) + ')</div>';
406+ if (!ch.length) {
407+ h += '<div class="muted">Working tree is clean.</div>';
408+ } else {
409+ h += '<ul class="flist">';
410+ for (var i = 0; i < ch.length; i++) {
411+ h += '<li><span class="c ' + codeClass(ch[i].code) + '">' + esc(ch[i].code) + '</span>' +
412+ '<span class="p">' + esc(ch[i].path) + '</span></li>';
413+ }
414+ h += '</ul>';
415+ if (j.changed_truncated) h += '<div class="note">Showing the first 500 entries.</div>';
416+ }
417+
418+ var cm = j.commits || [];
419+ h += '<div class="dsec">Recent commits (' + cm.length + ')</div>';
420+ if (!cm.length) {
421+ h += '<div class="muted">No commits yet.</div>';
422+ } else {
423+ h += '<ul class="clist">';
424+ for (var k = 0; k < cm.length; k++) {
425+ h += '<li><div class="s">' + esc(cm[k].subject || '') + '</div>' +
426+ '<div class="m"><span class="mo">' + esc((cm[k].hash || '').slice(0, 8)) + '</span>' +
427+ '<span>' + esc(cm[k].author || '') + '</span>' +
428+ '<span>' + ago(cm[k].ct) + '</span></div></li>';
429+ }
430+ h += '</ul>';
431+ }
432+ document.getElementById('dBody').innerHTML = h;
433+ }).catch(function(e){
434+ document.getElementById('dBody').innerHTML =
435+ '<div class="err">Could not read this repository: ' + esc(e.message) + '</div>';
436+ });
437+ }
438+
439+ function closeDetail(){
440+ SEL = '';
441+ document.getElementById('drawer').classList.remove('open');
442+ document.getElementById('drawer').setAttribute('aria-hidden', 'true');
443+ document.getElementById('scrim').classList.add('hide');
444+ render();
445+ }
446+
447+ document.getElementById('dClose').onclick = closeDetail;
448+ document.getElementById('scrim').onclick = closeDetail;
449+ document.addEventListener('keydown', function(e){ if (e.key === 'Escape') closeDetail(); });
450+ document.getElementById('rfBtn').onclick = load;
451+ document.getElementById('q').oninput = render;
452+ document.getElementById('sc').onchange = render;
453+ document.getElementById('thBtn').onclick = function(){
454+ if (window.sxApplyTheme) window.sxApplyTheme(window.sxTheme() === 'dark' ? 'light' : 'dark');
455+ };
456+
457+ var chips = document.querySelectorAll('.chip');
458+ for (var ci = 0; ci < chips.length; ci++) {
459+ chips[ci].onclick = function(){
460+ FILTER = this.getAttribute('data-filter');
461+ for (var j = 0; j < chips.length; j++) chips[j].classList.remove('sel');
462+ this.classList.add('sel');
463+ render();
464+ };
465+ }
466+
467+ load();
468+})();
469+</script>
470+</body></html>
src/ui_html.h+478−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..26c9422index 0000000..26c9422
--- /dev/null--- /dev/null
+++ b/src/ui_html.h+++ b/src/ui_html.h
@@ -0,0 +1,478 @@@@ -0,0 +1,478 @@
1+/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */
2+#ifndef SX_GITSTAT_UI_HTML_H
3+#define SX_GITSTAT_UI_HTML_H
4+
5+static const char *UI_HTML =
6+ "<!DOCTYPE html>\n"
7+ "<html lang=\"en\"><head><meta charset=\"utf-8\">\n"
8+ "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n"
9+ "<title>git</title>\n"
10+ "\001\n"
11+ "<style>\n"
12+ "*{box-sizing:border-box}\n"
13+ "html,body{margin:0;min-height:100%}\n"
14+ "body{background:var(--bg);color:var(--tx,var(--text));font-family:var(--font);\n"
15+ " font-size:14px;line-height:1.5;-webkit-font-smoothing:antialiased}\n"
16+ ".wrap{max-width:1200px;margin:0 auto;padding:18px 18px 40px}\n"
17+ ".top{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:14px}\n"
18+ ".brand{font-size:11px;font-weight:700;letter-spacing:.09em;text-transform:uppercase;\n"
19+ " color:var(--mu,var(--text-2))}\n"
20+ ".title{font-size:19px;font-weight:680;margin:0;letter-spacing:-.01em}\n"
21+ ".sp{flex:1 1 auto}\n"
22+ ".pill{font-size:11px;font-weight:600;padding:3px 9px;border-radius:999px;\n"
23+ " background:var(--sf2,var(--surface-2));color:var(--mu,var(--text-2));\n"
24+ " border:1px solid var(--ln,var(--line));white-space:nowrap}\n"
25+ ".icon-btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;\n"
26+ " background:var(--sf2,var(--surface-2));border:1px solid var(--ln,var(--line));\n"
27+ " color:var(--text);border-radius:9px;height:30px;padding:0 11px;cursor:pointer;\n"
28+ " font-family:inherit;font-size:12px;font-weight:600}\n"
29+ ".icon-btn:hover{background:var(--surface-hover);border-color:var(--line-2)}\n"
30+ ".icon-btn:active{transform:scale(.97)}\n"
31+ ".icon-btn svg{width:14px;height:14px;fill:none;stroke:currentColor;stroke-width:1.9;\n"
32+ " stroke-linecap:round;stroke-linejoin:round}\n"
33+ ".icon-btn[disabled]{opacity:.5;cursor:default}\n"
34+ "\n"
35+ ".chips{display:grid;grid-template-columns:repeat(auto-fit,minmax(126px,1fr));gap:10px;\n"
36+ " margin-bottom:14px}\n"
37+ ".chip{background:var(--sf,var(--bg-card));border:1px solid var(--ln,var(--line));\n"
38+ " border-radius:12px;padding:11px 13px;cursor:pointer;font-family:inherit;\n"
39+ " text-align:left;color:var(--text)}\n"
40+ ".chip:hover{border-color:var(--line-2)}\n"
41+ ".chip.sel{box-shadow:inset 0 0 0 1.5px var(--ac,var(--blue))}\n"
42+ ".chip .k{display:flex;align-items:center;gap:6px;font-size:10.5px;font-weight:700;\n"
43+ " letter-spacing:.07em;text-transform:uppercase;color:var(--mu,var(--text-2))}\n"
44+ ".chip .k svg{width:12px;height:12px;fill:none;stroke:currentColor;stroke-width:2;\n"
45+ " stroke-linecap:round;stroke-linejoin:round}\n"
46+ ".chip .v{font-family:var(--mono);font-size:23px;font-weight:700;margin-top:3px;\n"
47+ " letter-spacing:-.02em}\n"
48+ ".chip.ok .v{color:var(--green)}\n"
49+ ".chip.bad .v{color:var(--red)}\n"
50+ ".chip.warn .v{color:var(--orange)}\n"
51+ ".chip.none .v{color:var(--mu,var(--text-2))}\n"
52+ "\n"
53+ ".bar{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-bottom:10px}\n"
54+ ".search{flex:1 1 240px;min-width:0;padding:9px 12px;border-radius:10px;\n"
55+ " border:1px solid var(--ln,var(--line));background:var(--input-bg);color:var(--text);\n"
56+ " font-family:inherit;font-size:13px}\n"
57+ ".search:focus{outline:2px solid var(--ac,var(--blue));outline-offset:-1px}\n"
58+ "select{padding:9px 11px;border-radius:10px;border:1px solid var(--ln,var(--line));\n"
59+ " background:var(--input-bg);color:var(--text);font-family:inherit;font-size:13px}\n"
60+ "\n"
61+ ".panel{background:var(--sf,var(--bg-card));border:1px solid var(--ln,var(--line));\n"
62+ " border-radius:14px;overflow:hidden}\n"
63+ ".tb{width:100%;overflow-x:auto}\n"
64+ "table{width:100%;border-collapse:collapse;font-size:13px}\n"
65+ "th{text-align:left;font-size:10.5px;letter-spacing:.07em;text-transform:uppercase;\n"
66+ " color:var(--mu,var(--text-2));font-weight:700;padding:9px 12px;\n"
67+ " border-bottom:1px solid var(--ln,var(--line));white-space:nowrap;\n"
68+ " background:var(--sf2,var(--surface-2))}\n"
69+ "td{padding:9px 12px;border-bottom:1px solid var(--ln,var(--line));\n"
70+ " vertical-align:middle;white-space:nowrap}\n"
71+ "tr.row{cursor:pointer}\n"
72+ "tr.row:hover td{background:var(--surface-hover)}\n"
73+ "tr.row:last-child td{border-bottom:0}\n"
74+ "tr.row.sel td{background:var(--sf2,var(--surface-2))}\n"
75+ ".mo{font-family:var(--mono);font-size:12.5px}\n"
76+ ".name{font-weight:600;max-width:300px;overflow:hidden;text-overflow:ellipsis}\n"
77+ ".sub{font-size:11.5px;color:var(--mu,var(--text-2));max-width:300px;\n"
78+ " overflow:hidden;text-overflow:ellipsis;margin-top:1px}\n"
79+ ".subtext{color:var(--text);font-size:12.5px;max-width:340px}\n"
80+ "td.c-last{max-width:360px;overflow:hidden}\n"
81+ ".subtext{white-space:normal;display:-webkit-box;-webkit-line-clamp:2;\n"
82+ " -webkit-box-orient:vertical;overflow:hidden}\n"
83+ ".hash{font-family:var(--mono);font-size:11.5px;color:var(--mu,var(--text-2))}\n"
84+ ".tag{font-size:10px;font-weight:700;padding:2px 8px;border-radius:6px;\n"
85+ " white-space:nowrap;letter-spacing:.03em;display:inline-block;margin:1px 3px 1px 0}\n"
86+ ".t-dirty{background:rgba(255,159,10,.16);color:var(--orange)}\n"
87+ ".t-ahead{background:rgba(48,209,88,.16);color:var(--green)}\n"
88+ ".t-behind{background:rgba(255,69,58,.16);color:var(--red)}\n"
89+ ".t-det{background:rgba(191,90,242,.16);color:var(--purple)}\n"
90+ ".t-noup{background:rgba(142,142,147,.16);color:var(--gray)}\n"
91+ ".t-stash{background:rgba(94,92,230,.16);color:var(--indigo)}\n"
92+ ".t-clean{background:rgba(48,209,88,.12);color:var(--green)}\n"
93+ ".t-unborn{background:rgba(255,214,10,.16);color:var(--yellow)}\n"
94+ ".muted{color:var(--mu,var(--text-2))}\n"
95+ ".empty{padding:28px 16px;text-align:center;color:var(--mu,var(--text-2));font-size:13px}\n"
96+ ".hide{display:none!important}\n"
97+ "\n"
98+ ".drawer{position:fixed;top:0;right:0;bottom:0;width:min(560px,100%);z-index:60;\n"
99+ " background:var(--modal-bg,var(--bg-card));border-left:1px solid var(--ln,var(--line));\n"
100+ " box-shadow:var(--shadow-lg);transform:translateX(102%);transition:transform .22s var(--ease);\n"
101+ " display:flex;flex-direction:column}\n"
102+ ".drawer.open{transform:none}\n"
103+ ".dh{display:flex;align-items:center;gap:10px;padding:14px 16px;\n"
104+ " border-bottom:1px solid var(--ln,var(--line))}\n"
105+ ".dh .t{font-size:15px;font-weight:680;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n"
106+ ".db{overflow:auto;padding:14px 16px 28px;flex:1 1 auto}\n"
107+ ".dsec{font-size:10.5px;letter-spacing:.07em;text-transform:uppercase;font-weight:700;\n"
108+ " color:var(--mu,var(--text-2));margin:16px 0 8px}\n"
109+ ".dsec:first-child{margin-top:0}\n"
110+ ".flist{list-style:none;margin:0;padding:0;font-size:12.5px}\n"
111+ ".flist li{display:flex;gap:9px;align-items:baseline;padding:4px 0;\n"
112+ " border-bottom:1px solid var(--ln,var(--line))}\n"
113+ ".flist li:last-child{border-bottom:0}\n"
114+ ".flist .c{font-family:var(--mono);font-size:11px;font-weight:700;width:26px;flex:0 0 26px}\n"
115+ ".flist .p{font-family:var(--mono);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n"
116+ ".c-mod{color:var(--orange)}.c-add{color:var(--green)}.c-del{color:var(--red)}\n"
117+ ".c-unt{color:var(--gray)}.c-con{color:var(--purple)}\n"
118+ ".clist{list-style:none;margin:0;padding:0;font-size:12.5px}\n"
119+ ".clist li{padding:5px 0;border-bottom:1px solid var(--ln,var(--line))}\n"
120+ ".clist li:last-child{border-bottom:0}\n"
121+ ".clist .s{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}\n"
122+ ".clist .m{font-size:11px;color:var(--mu,var(--text-2));display:flex;gap:8px}\n"
123+ ".scrim{position:fixed;inset:0;background:rgba(0,0,0,.35);z-index:55}\n"
124+ ".scrim.hide{display:none}\n"
125+ ".note{font-size:11.5px;color:var(--mu,var(--text-2));margin-top:8px}\n"
126+ ".err{color:var(--red);font-size:12.5px;margin-top:8px}\n"
127+ "\n"
128+ "@media(max-width:760px){\n"
129+ " .wrap{padding:12px 12px 28px}\n"
130+ " .drawer{width:100%;border-left:0}\n"
131+ " col.c-root,th.c-root,td.c-root{display:none}\n"
132+ "}\n"
133+ "@media(max-width:760px){\n"
134+ " /* Two fixed columns: the repo block and the commit block. The commit subject\n"
135+ " * is allowed to wrap onto a second line, which is the only way it fits at\n"
136+ " * 390 px without a mid-word cut at the panel edge. */\n"
137+ " table{table-layout:fixed;width:100%}\n"
138+ " td.c-repo{white-space:normal}\n"
139+ " td.c-repo .sub{overflow:visible;text-overflow:clip;line-height:1.6}\n"
140+ " td.c-last{max-width:none;white-space:normal}\n"
141+ " td .sub,.subtext{max-width:none}\n"
142+ " col.c-repo{width:48%}\n"
143+ " col.c-last{width:52%}\n"
144+ " .name{max-width:none}\n"
145+ "}\n"
146+ "@media(max-width:560px){\n"
147+ " .chips{grid-template-columns:repeat(auto-fit,minmax(104px,1fr));gap:8px}\n"
148+ " .chip .v{font-size:19px}\n"
149+ " col.c-sync,th.c-sync,td.c-sync{display:none}\n"
150+ " th,td{padding:8px 9px}\n"
151+ " .name,td .sub,.subtext{max-width:none}\n"
152+ "}\n"
153+ "</style></head>\n"
154+ "<body>\n"
155+ "<div class=\"wrap\">\n"
156+ " <div class=\"top\">\n"
157+ " <div>\n"
158+ " <div class=\"brand\">SCORPIOX BOT</div>\n"
159+ " <h1 class=\"title\">git</h1>\n"
160+ " </div>\n"
161+ " <span class=\"pill\" id=\"rootPill\">local</span>\n"
162+ " <span class=\"sp\"></span>\n"
163+ " <button class=\"icon-btn embed-hide\" id=\"thBtn\" type=\"button\" title=\"Toggle appearance\">\n"
164+ " <svg viewBox=\"0 0 24 24\"><circle cx=\"12\" cy=\"12\" r=\"4\"/><path d=\"M12 2v3M12 19v3M2 12h3M19 12h3M4.9 4.9l2.1 2.1M17 17l2.1 2.1M19.1 4.9L17 7M7 17l-2.1 2.1\"/></svg>\n"
165+ " Theme\n"
166+ " </button>\n"
167+ " <button class=\"icon-btn\" id=\"rfBtn\" type=\"button\">\n"
168+ " <svg viewBox=\"0 0 24 24\"><path d=\"M21 12a9 9 0 1 1-2.6-6.4\"/><path d=\"M21 3v6h-6\"/></svg>\n"
169+ " Rescan\n"
170+ " </button>\n"
171+ " </div>\n"
172+ "\n"
173+ " <div class=\"chips\" id=\"chips\">\n"
174+ " <button class=\"chip none\" data-filter=\"all\" id=\"vAllChip\" type=\"button\">\n"
175+ " <div class=\"k\"><svg viewBox=\"0 0 24 24\"><path d=\"M3 7h18M3 12h18M3 17h18\"/></svg>All repos</div>\n"
176+ " <div class=\"v\" id=\"vAll\">0</div>\n"
177+ " </button>\n"
178+ " <button class=\"chip warn\" data-filter=\"dirty\" type=\"button\">\n"
179+ " <div class=\"k\"><svg viewBox=\"0 0 24 24\"><path d=\"M12 8v5M12 16h.01\"/><circle cx=\"12\" cy=\"12\" r=\"9\"/></svg>Dirty</div>\n"
180+ " <div class=\"v\" id=\"vDirty\">0</div>\n"
181+ " </button>\n"
182+ " <button class=\"chip ok\" data-filter=\"ahead\" type=\"button\">\n"
183+ " <div class=\"k\"><svg viewBox=\"0 0 24 24\"><path d=\"M12 19V5M6 11l6-6 6 6\"/></svg>Ahead</div>\n"
184+ " <div class=\"v\" id=\"vAhead\">0</div>\n"
185+ " </button>\n"
186+ " <button class=\"chip bad\" data-filter=\"behind\" type=\"button\">\n"
187+ " <div class=\"k\"><svg viewBox=\"0 0 24 24\"><path d=\"M12 5v14M6 13l6 6 6-6\"/></svg>Behind</div>\n"
188+ " <div class=\"v\" id=\"vBehind\">0</div>\n"
189+ " </button>\n"
190+ " <button class=\"chip none\" data-filter=\"stash\" type=\"button\">\n"
191+ " <div class=\"k\"><svg viewBox=\"0 0 24 24\"><path d=\"M4 7h16M4 12h16M4 17h10\"/></svg>Stashes</div>\n"
192+ " <div class=\"v\" id=\"vStash\">0</div>\n"
193+ " </button>\n"
194+ " </div>\n"
195+ "\n"
196+ " <div class=\"bar\">\n"
197+ " <input class=\"search\" id=\"q\" type=\"search\" placeholder=\"Filter by repo, branch, or last commit\" autocomplete=\"off\">\n"
198+ " <select id=\"sc\" aria-label=\"Filter by state\">\n"
199+ " <option value=\"\">All states</option>\n"
200+ " <option value=\"dirty\">Dirty</option>\n"
201+ " <option value=\"clean\">Clean</option>\n"
202+ " <option value=\"ahead\">Ahead</option>\n"
203+ " <option value=\"behind\">Behind</option>\n"
204+ " <option value=\"detached\">Detached</option>\n"
205+ " <option value=\"noup\">No upstream</option>\n"
206+ " </select>\n"
207+ " </div>\n"
208+ "\n"
209+ " <div class=\"panel\">\n"
210+ " <div class=\"tb\">\n"
211+ " <table>\n"
212+ " <colgroup>\n"
213+ " <col class=\"c-repo\"><col class=\"c-root\"><col class=\"c-sync\"><col class=\"c-sync\"><col class=\"c-last\">\n"
214+ " </colgroup>\n"
215+ " <thead><tr>\n"
216+ " <th>Repository</th>\n"
217+ " <th class=\"c-root\">Root</th>\n"
218+ " <th class=\"c-sync\">Sync</th>\n"
219+ " <th class=\"c-sync\">Stash</th>\n"
220+ " <th>Last commit</th>\n"
221+ " </tr></thead>\n"
222+ " <tbody id=\"rows\"></tbody>\n"
223+ " </table>\n"
224+ " </div>\n"
225+ " <div class=\"empty hide\" id=\"empty\">No repositories found under the allowlisted roots.</div>\n"
226+ " </div>\n"
227+ " <div class=\"note\" id=\"footNote\">Read-only. Fetching from a remote stays off unless the node operator enables it.</div>\n"
228+ "</div>\n"
229+ "\n"
230+ "<div class=\"scrim hide\" id=\"scrim\"></div>\n"
231+ "<aside class=\"drawer\" id=\"drawer\" aria-hidden=\"true\">\n"
232+ " <div class=\"dh\">\n"
233+ " <div class=\"t\" id=\"dName\">Repository</div>\n"
234+ " <span class=\"sp\"></span>\n"
235+ " <button class=\"icon-btn\" id=\"dClose\" type=\"button\" title=\"Close\">\n"
236+ " <svg viewBox=\"0 0 24 24\"><path d=\"M18 6 6 18M6 6l12 12\"/></svg>\n"
237+ " </button>\n"
238+ " </div>\n"
239+ " <div class=\"db\" id=\"dBody\"></div>\n"
240+ "</aside>\n"
241+ "\n"
242+ "<script>\n"
243+ "(function(){\n"
244+ " var q = new URLSearchParams(location.search);\n"
245+ " var node = q.get('node') || '';\n"
246+ " var sid = q.get('id') || '';\n"
247+ " var pwd = q.get('pwd') || (node && localStorage.getItem('bot_pwd_' + node)) ||\n"
248+ " localStorage.getItem('bot_active_pwd') || '';\n"
249+ " /* When the bot serves this page through its proxy, ?plugin= is the route back.\n"
250+ " * Opened directly on the node, the plugin itself is the route. */\n"
251+ " var HUB = q.get('plugin') || '';\n"
252+ "\n"
253+ " function api(action, extra){\n"
254+ " var u = (HUB ? '/plugins?plugin=' + encodeURIComponent(HUB) : '/plugin_gitstat') +\n"
255+ " '?action=' + encodeURIComponent(action) +\n"
256+ " (extra ? ('&' + extra) : '') +\n"
257+ " (node ? '&node=' + encodeURIComponent(node) : '') +\n"
258+ " (sid ? '&id=' + encodeURIComponent(sid) : '') +\n"
259+ " (pwd ? '&pwd=' + encodeURIComponent(pwd) : '');\n"
260+ " return fetch(u, {headers: pwd ? {'X-Bot-Password': pwd} : {}}).then(function(r){\n"
261+ " if (!r.ok) throw new Error('HTTP ' + r.status);\n"
262+ " return r.json();\n"
263+ " });\n"
264+ " }\n"
265+ "\n"
266+ " var DATA = [];\n"
267+ " var ROOTS = [];\n"
268+ " var FILTER = 'all';\n"
269+ " var SEL = '';\n"
270+ "\n"
271+ " function esc(v){\n"
272+ " return String(v == null ? '' : v).replace(/[&<>\"']/g, function(c){\n"
273+ " return {'&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;',\"'\":'&#39;'}[c];\n"
274+ " });\n"
275+ " }\n"
276+ " function txt(id, v){ var e = document.getElementById(id); if (e) e.textContent = v; }\n"
277+ "\n"
278+ " function ago(ct){\n"
279+ " if (!ct) return '-';\n"
280+ " var s = Math.max(0, Math.floor(Date.now()/1000) - ct);\n"
281+ " if (s < 60) return s + 's ago';\n"
282+ " if (s < 3600) return Math.floor(s/60) + 'm ago';\n"
283+ " if (s < 86400) return Math.floor(s/3600) + 'h ago';\n"
284+ " if (s < 2592000) return Math.floor(s/86400) + 'd ago';\n"
285+ " if (s < 31536000) return Math.floor(s/2592000) + 'mo ago';\n"
286+ " return Math.floor(s/31536000) + 'y ago';\n"
287+ " }\n"
288+ "\n"
289+ " function badges(r){\n"
290+ " var h = '';\n"
291+ " if (r.dirty > 0) h += '<span class=\"tag t-dirty\">' + r.dirty + ' changed</span>';\n"
292+ " if (r.ahead > 0) h += '<span class=\"tag t-ahead\">+' + r.ahead + '</span>';\n"
293+ " if (r.behind > 0) h += '<span class=\"tag t-behind\">-' + r.behind + '</span>';\n"
294+ " if (r.detached) h += '<span class=\"tag t-det\">detached</span>';\n"
295+ " if (r.no_upstream && !r.detached) h += '<span class=\"tag t-noup\">no upstream</span>';\n"
296+ " if (r.unborn) h += '<span class=\"tag t-unborn\">unborn</span>';\n"
297+ " if (r.stash > 0) h += '<span class=\"tag t-stash\">' + r.stash + ' stash</span>';\n"
298+ " if (r.dirty === 0 && !r.detached && !r.unborn) h += '<span class=\"tag t-clean\">clean</span>';\n"
299+ " return h;\n"
300+ " }\n"
301+ "\n"
302+ " function matches(r){\n"
303+ " if (FILTER === 'dirty' && !(r.dirty > 0)) return false;\n"
304+ " if (FILTER === 'ahead' && !(r.ahead > 0)) return false;\n"
305+ " if (FILTER === 'behind' && !(r.behind > 0)) return false;\n"
306+ " if (FILTER === 'stash' && !(r.stash > 0)) return false;\n"
307+ "\n"
308+ " var sc = document.getElementById('sc').value;\n"
309+ " if (sc === 'dirty' && !(r.dirty > 0)) return false;\n"
310+ " if (sc === 'clean' && (r.dirty > 0)) return false;\n"
311+ " if (sc === 'ahead' && !(r.ahead > 0)) return false;\n"
312+ " if (sc === 'behind' && !(r.behind > 0)) return false;\n"
313+ " if (sc === 'detached' && !r.detached) return false;\n"
314+ " if (sc === 'noup' && !r.no_upstream) return false;\n"
315+ "\n"
316+ " var f = (document.getElementById('q').value || '').toLowerCase();\n"
317+ " if (!f) return true;\n"
318+ " var hay = (r.name + ' ' + r.path + ' ' + r.branch + ' ' + r.upstream + ' ' +\n"
319+ " (r.last_commit ? r.last_commit.subject : '')).toLowerCase();\n"
320+ " return hay.indexOf(f) >= 0;\n"
321+ " }\n"
322+ "\n"
323+ " function render(){\n"
324+ " var out = DUPS(DATA), rows = document.getElementById('rows'), h = '';\n"
325+ " for (var i = 0; i < out.length; i++) {\n"
326+ " var r = out[i], lc = r.last_commit || {};\n"
327+ " h += '<tr class=\"row' + (SEL === r.path ? ' sel' : '') + '\" data-p=\"' + esc(r.path) + '\">' +\n"
328+ " '<td class=\"c-repo\"><div class=\"name\">' + esc(r.name) + '</div>' +\n"
329+ " '<div class=\"sub\"><span class=\"mo\">' + esc(r.branch || '-') + '</span> ' + badges(r) + '</div></td>' +\n"
330+ " '<td class=\"c-root muted mo\">' + esc(r.root || '-') + '</td>' +\n"
331+ " '<td class=\"c-sync mo\">' + (r.ahead || r.behind ? ('+' + r.ahead + ' -' + r.behind) : '<span class=\"muted\">-</span>') + '</td>' +\n"
332+ " '<td class=\"c-sync mo\">' + (r.stash ? r.stash : '<span class=\"muted\">-</span>') + '</td>' +\n"
333+ " '<td class=\"c-last\"><div class=\"sub subtext\">' + esc(lc.subject || '-') + '</div>' +\n"
334+ " '<div class=\"hash\">' + esc((lc.short || '').slice(0, 8)) + ' &middot; ' + ago(lc.ct) + '</div></td>' +\n"
335+ " '</tr>';\n"
336+ " }\n"
337+ " rows.innerHTML = h;\n"
338+ " document.getElementById('empty').className = out.length ? 'empty hide' : 'empty';\n"
339+ "\n"
340+ " var b = rows.querySelectorAll('tr.row');\n"
341+ " for (var k = 0; k < b.length; k++) {\n"
342+ " b[k].onclick = function(){\n"
343+ " openDetail(this.getAttribute('data-p'));\n"
344+ " };\n"
345+ " }\n"
346+ " }\n"
347+ " function DUPS(a){ var o = []; for (var i=0;i<a.length;i++) if (matches(a[i])) o.push(a[i]); return o; }\n"
348+ "\n"
349+ " function setCounts(s, n){\n"
350+ " s = s || {};\n"
351+ " txt('vAll', n || 0);\n"
352+ " txt('vDirty', s.dirty || 0);\n"
353+ " txt('vAhead', s.ahead || 0);\n"
354+ " txt('vBehind', s.behind || 0);\n"
355+ " txt('vStash', s.stashes || 0);\n"
356+ " }\n"
357+ "\n"
358+ " function load(){\n"
359+ " var btn = document.getElementById('rfBtn');\n"
360+ " btn.disabled = true;\n"
361+ " return api('repos').then(function(d){\n"
362+ " DATA = d.repos || [];\n"
363+ " ROOTS = d.roots || [];\n"
364+ " setCounts(d.summary, d.count);\n"
365+ " var ex = [];\n"
366+ " for (var i = 0; i < ROOTS.length; i++) if (ROOTS[i].exists) ex.push(ROOTS[i].root);\n"
367+ " txt('rootPill', ex.length ? (ex.length + ' root' + (ex.length === 1 ? '' : 's')) : 'no roots');\n"
368+ " render();\n"
369+ " }).catch(function(e){\n"
370+ " txt('rootPill', 'error');\n"
371+ " document.getElementById('empty').className = 'empty';\n"
372+ " document.getElementById('empty').textContent = 'Load failed: ' + e.message;\n"
373+ " }).then(function(){ btn.disabled = false; });\n"
374+ " }\n"
375+ "\n"
376+ " function codeClass(c){\n"
377+ " if (c === '\\?\\?' || c === '!!') return 'c-unt';\n"
378+ " if (c === 'UU' || c === 'AA' || c === 'DD') return 'c-con';\n"
379+ " if (c.indexOf('A') >= 0) return 'c-add';\n"
380+ " if (c.indexOf('D') >= 0) return 'c-del';\n"
381+ " return 'c-mod';\n"
382+ " }\n"
383+ "\n"
384+ " function openDetail(path){\n"
385+ " SEL = path;\n"
386+ " var d = document.getElementById('drawer');\n"
387+ " var s = document.getElementById('scrim');\n"
388+ " d.classList.add('open');\n"
389+ " d.setAttribute('aria-hidden', 'false');\n"
390+ " s.classList.remove('hide');\n"
391+ " document.getElementById('dName').textContent = path.split(/[\\\\/]/).pop() || path;\n"
392+ " document.getElementById('dBody').innerHTML = '<div class=\"muted\">Loading…</div>';\n"
393+ "\n"
394+ " api('repo', 'path=' + encodeURIComponent(path)).then(function(j){\n"
395+ " if (!j.ok) throw new Error(j.error || 'failed');\n"
396+ " var r = j.repo || {}, lc = r.last_commit || {};\n"
397+ " var h = '';\n"
398+ " h += '<div class=\"dsec\">Repository</div>';\n"
399+ " h += '<div class=\"mo\" style=\"font-size:12px;word-break:break-all\">' + esc(r.path) + '</div>';\n"
400+ " h += '<div style=\"margin-top:8px\">' + badges(r) + '</div>';\n"
401+ " h += '<div class=\"note\">branch <span class=\"mo\">' + esc(r.branch || '-') + '</span>' +\n"
402+ " (r.upstream ? ' &rarr; <span class=\"mo\">' + esc(r.upstream) + '</span>' : '') + '</div>';\n"
403+ "\n"
404+ " h += '<div class=\"dsec\">Last commit</div>';\n"
405+ " h += '<div class=\"clist\"><li><div class=\"s\">' + esc(lc.subject || '-') + '</div>' +\n"
406+ " '<div class=\"m\"><span class=\"mo\">' + esc((lc.short || '').slice(0, 8)) + '</span>' +\n"
407+ " '<span>' + ago(lc.ct) + '</span></div></li></div>';\n"
408+ "\n"
409+ " var ch = j.changed || [];\n"
410+ " h += '<div class=\"dsec\">Changed files (' + (j.changed_count || 0) + ')</div>';\n"
411+ " if (!ch.length) {\n"
412+ " h += '<div class=\"muted\">Working tree is clean.</div>';\n"
413+ " } else {\n"
414+ " h += '<ul class=\"flist\">';\n"
415+ " for (var i = 0; i < ch.length; i++) {\n"
416+ " h += '<li><span class=\"c ' + codeClass(ch[i].code) + '\">' + esc(ch[i].code) + '</span>' +\n"
417+ " '<span class=\"p\">' + esc(ch[i].path) + '</span></li>';\n"
418+ " }\n"
419+ " h += '</ul>';\n"
420+ " if (j.changed_truncated) h += '<div class=\"note\">Showing the first 500 entries.</div>';\n"
421+ " }\n"
422+ "\n"
423+ " var cm = j.commits || [];\n"
424+ " h += '<div class=\"dsec\">Recent commits (' + cm.length + ')</div>';\n"
425+ " if (!cm.length) {\n"
426+ " h += '<div class=\"muted\">No commits yet.</div>';\n"
427+ " } else {\n"
428+ " h += '<ul class=\"clist\">';\n"
429+ " for (var k = 0; k < cm.length; k++) {\n"
430+ " h += '<li><div class=\"s\">' + esc(cm[k].subject || '') + '</div>' +\n"
431+ " '<div class=\"m\"><span class=\"mo\">' + esc((cm[k].hash || '').slice(0, 8)) + '</span>' +\n"
432+ " '<span>' + esc(cm[k].author || '') + '</span>' +\n"
433+ " '<span>' + ago(cm[k].ct) + '</span></div></li>';\n"
434+ " }\n"
435+ " h += '</ul>';\n"
436+ " }\n"
437+ " document.getElementById('dBody').innerHTML = h;\n"
438+ " }).catch(function(e){\n"
439+ " document.getElementById('dBody').innerHTML =\n"
440+ " '<div class=\"err\">Could not read this repository: ' + esc(e.message) + '</div>';\n"
441+ " });\n"
442+ " }\n"
443+ "\n"
444+ " function closeDetail(){\n"
445+ " SEL = '';\n"
446+ " document.getElementById('drawer').classList.remove('open');\n"
447+ " document.getElementById('drawer').setAttribute('aria-hidden', 'true');\n"
448+ " document.getElementById('scrim').classList.add('hide');\n"
449+ " render();\n"
450+ " }\n"
451+ "\n"
452+ " document.getElementById('dClose').onclick = closeDetail;\n"
453+ " document.getElementById('scrim').onclick = closeDetail;\n"
454+ " document.addEventListener('keydown', function(e){ if (e.key === 'Escape') closeDetail(); });\n"
455+ " document.getElementById('rfBtn').onclick = load;\n"
456+ " document.getElementById('q').oninput = render;\n"
457+ " document.getElementById('sc').onchange = render;\n"
458+ " document.getElementById('thBtn').onclick = function(){\n"
459+ " if (window.sxApplyTheme) window.sxApplyTheme(window.sxTheme() === 'dark' ? 'light' : 'dark');\n"
460+ " };\n"
461+ "\n"
462+ " var chips = document.querySelectorAll('.chip');\n"
463+ " for (var ci = 0; ci < chips.length; ci++) {\n"
464+ " chips[ci].onclick = function(){\n"
465+ " FILTER = this.getAttribute('data-filter');\n"
466+ " for (var j = 0; j < chips.length; j++) chips[j].classList.remove('sel');\n"
467+ " this.classList.add('sel');\n"
468+ " render();\n"
469+ " };\n"
470+ " }\n"
471+ "\n"
472+ " load();\n"
473+ "})();\n"
474+ "</script>\n"
475+ "\002</body></html>\n"
476+ ;
477+
478+#endif /* SX_GITSTAT_UI_HTML_H */
tests/e2e.py+332−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..30364c5index 0000000..30364c5
--- /dev/null--- /dev/null
+++ b/tests/e2e.py+++ b/tests/e2e.py
@@ -0,0 +1,332 @@@@ -0,0 +1,332 @@
1+#!/usr/bin/env python3
2+"""tests/e2e.py - viewport checks for the plugin_gitstat board.
3+
4+Builds a small fixture tree of real git repositories in a temp directory, serves
5+the plugin through a tiny CGI-ish HTTP shim on a loopback port, and opens it with
6+Playwright at 1440 / 1024 / 390 CSS pixels in both themes. It asserts there is
7+no horizontal overflow, no console error, that the summary chips and the table
8+rendered, and that a row opens the detail drawer. Screenshots land in docs/ for
9+the README. Skips cleanly (exit 0) when Playwright is not installed, so the
10+offline suite stays dependency-free.
11+
12+ python3 tests/e2e.py # run if Playwright is available
13+ python3 tests/e2e.py --strict # exit 2 when Playwright is missing
14+"""
15+
16+import argparse
17+import http.server
18+import os
19+import shutil
20+import socketserver
21+import subprocess
22+import sys
23+import tempfile
24+import threading
25+from urllib.parse import urlparse
26+
27+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
28+BIN = os.path.join(ROOT, "plugin_gitstat")
29+DOCS = os.path.join(ROOT, "docs")
30+VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
31+THEMES = ["dark", "light"]
32+
33+GITENV = {
34+ "GIT_AUTHOR_NAME": "Gitstat E2E",
35+ "GIT_AUTHOR_EMAIL": "gitstat@example.invalid",
36+ "GIT_COMMITTER_NAME": "Gitstat E2E",
37+ "GIT_COMMITTER_EMAIL": "gitstat@example.invalid",
38+ "GIT_CONFIG_GLOBAL": os.devnull,
39+ "GIT_CONFIG_NOSYSTEM": "1",
40+ "GIT_TERMINAL_PROMPT": "0",
41+}
42+
43+
44+def git(cwd, *args):
45+ env = dict(os.environ)
46+ env.update(GITENV)
47+ return subprocess.run(["git", "-C", cwd] + list(args), env=env,
48+ check=True, capture_output=True)
49+
50+
51+def mkrepo(path, branch="main"):
52+ os.makedirs(path, exist_ok=True)
53+ git(path, "init", "-q", "-b", branch)
54+ git(path, "config", "user.name", "Gitstat E2E")
55+ git(path, "config", "user.email", "gitstat@example.invalid")
56+
57+
58+def build_fixtures(base):
59+ """Four repos, one per interesting visual state."""
60+ roots = os.path.join(base, "roots")
61+ os.makedirs(roots)
62+
63+ # clean, in sync with an upstream
64+ up = os.path.join(base, "up.git")
65+ git(base, "init", "-q", "--bare", up)
66+ git(up, "symbolic-ref", "HEAD", "refs/heads/main")
67+ seed = os.path.join(base, "seed")
68+ mkrepo(seed)
69+ with open(os.path.join(seed, "README.md"), "w", encoding="utf-8") as f:
70+ f.write("seed\n")
71+ git(seed, "add", "README.md")
72+ git(seed, "commit", "-q", "-m", "Add the README that everything else builds on")
73+ git(seed, "remote", "add", "origin", up)
74+ git(seed, "push", "-q", "-u", "origin", "main")
75+ git(base, "clone", "-q", up, os.path.join(roots, "portal-web"))
76+ c = os.path.join(roots, "portal-web")
77+ git(c, "config", "user.name", "Gitstat E2E")
78+ git(c, "config", "user.email", "gitstat@example.invalid")
79+
80+ # dirty working tree
81+ d = os.path.join(roots, "billing-service")
82+ mkrepo(d)
83+ for name in ("main.c", "util.c", "notes.md"):
84+ with open(os.path.join(d, name), "w", encoding="utf-8") as f:
85+ f.write("x\n")
86+ git(d, "add", ".")
87+ git(d, "commit", "-q", "-m", "Split the invoice renderer out of the billing loop")
88+ with open(os.path.join(d, "main.c"), "a", encoding="utf-8") as f:
89+ f.write("patched\n")
90+ with open(os.path.join(d, "util.c"), "a", encoding="utf-8") as f:
91+ f.write("staged\n")
92+ git(d, "add", "util.c")
93+ with open(os.path.join(d, "untracked.txt"), "w", encoding="utf-8") as f:
94+ f.write("new\n")
95+
96+ # ahead by two, with a stash
97+ a = os.path.join(roots, "fleet-agent")
98+ up2 = os.path.join(base, "up2.git")
99+ git(base, "init", "-q", "--bare", up2)
100+ git(up2, "symbolic-ref", "HEAD", "refs/heads/main")
101+ seed2 = os.path.join(base, "seed2")
102+ mkrepo(seed2)
103+ with open(os.path.join(seed2, "a.txt"), "w", encoding="utf-8") as f:
104+ f.write("a\n")
105+ git(seed2, "add", "a.txt")
106+ git(seed2, "commit", "-q", "-m", "Start the agent loop")
107+ git(seed2, "remote", "add", "origin", up2)
108+ git(seed2, "push", "-q", "-u", "origin", "main")
109+ git(base, "clone", "-q", up2, a)
110+ git(a, "config", "user.name", "Gitstat E2E")
111+ git(a, "config", "user.email", "gitstat@example.invalid")
112+ for msg in ("Teach the agent to retry a dropped socket",
113+ "Cap the retry backoff at thirty seconds"):
114+ with open(os.path.join(a, "a.txt"), "a", encoding="utf-8") as f:
115+ f.write(msg + "\n")
116+ git(a, "commit", "-q", "-am", msg)
117+ with open(os.path.join(a, "a.txt"), "a", encoding="utf-8") as f:
118+ f.write("wip\n")
119+ git(a, "stash", "push", "-q", "-m", "half-finished backoff rewrite")
120+
121+ # detached
122+ x = os.path.join(roots, "proto-sandbox")
123+ mkrepo(x)
124+ with open(os.path.join(x, "p.txt"), "w", encoding="utf-8") as f:
125+ f.write("p\n")
126+ git(x, "add", "p.txt")
127+ git(x, "commit", "-q", "-m", "First prototype of the graph walker")
128+ with open(os.path.join(x, "p.txt"), "a", encoding="utf-8") as f:
129+ f.write("q\n")
130+ git(x, "commit", "-q", "-am", "Walk depth-first instead")
131+ git(x, "checkout", "-q", "HEAD~1")
132+ return roots
133+
134+
135+class Handler(http.server.BaseHTTPRequestHandler):
136+ roots = ""
137+ allow_fetch = "0"
138+
139+ def _run(self, method):
140+ u = urlparse(self.path)
141+ env = dict(os.environ)
142+ env["QUERY_STRING"] = u.query
143+ env["REQUEST_METHOD"] = method
144+ env.pop("BOT_PASSWORD", None)
145+ env["GITSTAT_ONLY_ROOTS"] = "1"
146+ env["GITSTAT_ROOTS"] = self.roots
147+ env["GITSTAT_ALLOW_FETCH"] = self.allow_fetch
148+ out = subprocess.run([BIN], capture_output=True, env=env, timeout=60).stdout
149+ sep = out.find(b"\r\n\r\n")
150+ headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
151+ body = out[sep + 4:] if sep >= 0 else out
152+ ctype = "text/html; charset=utf-8"
153+ status = 200
154+ for line in headers.splitlines():
155+ low = line.lower()
156+ if low.startswith("content-type:"):
157+ ctype = line.split(":", 1)[1].strip()
158+ if low.startswith("status:"):
159+ try:
160+ status = int(line.split(":", 1)[1].split()[0])
161+ except (IndexError, ValueError):
162+ status = 200
163+ self.send_response(status)
164+ self.send_header("Content-Type", ctype)
165+ self.send_header("Cache-Control", "no-store")
166+ self.send_header("Content-Length", str(len(body)))
167+ self.end_headers()
168+ self.wfile.write(body)
169+
170+ def do_GET(self): # noqa: N802
171+ self._run("GET")
172+
173+ def do_POST(self): # noqa: N802
174+ self._run("POST")
175+
176+ def log_message(self, *_a):
177+ pass
178+
179+
180+def main():
181+ ap = argparse.ArgumentParser()
182+ ap.add_argument("--strict", action="store_true")
183+ args = ap.parse_args()
184+
185+ if not os.path.exists(BIN):
186+ print("plugin_gitstat is not built; run make first", file=sys.stderr)
187+ return 1
188+
189+ try:
190+ from playwright.sync_api import sync_playwright
191+ except Exception:
192+ msg = "playwright not installed - skipping viewport e2e"
193+ if args.strict:
194+ print(msg, file=sys.stderr)
195+ return 2
196+ print(msg)
197+ return 0
198+
199+ base = tempfile.mkdtemp(prefix="gitstat-e2e-")
200+ try:
201+ roots = build_fixtures(base)
202+ except subprocess.CalledProcessError as exc:
203+ print("cannot build the git fixtures: %s" % exc, file=sys.stderr)
204+ shutil.rmtree(base, ignore_errors=True)
205+ return 1
206+
207+ Handler.roots = roots
208+ os.makedirs(DOCS, exist_ok=True)
209+
210+ failures = []
211+ with socketserver.TCPServer(("127.0.0.1", 0), Handler) as srv:
212+ port = srv.server_address[1]
213+ threading.Thread(target=srv.serve_forever, daemon=True).start()
214+ url_base = "http://127.0.0.1:%d/plugin_gitstat" % port
215+
216+ with sync_playwright() as p:
217+ browser = p.chromium.launch()
218+ for (w, h) in VIEWPORTS:
219+ for theme in THEMES:
220+ url = "%s?theme=%s" % (url_base, theme)
221+ page = browser.new_page(viewport={"width": w, "height": h})
222+ errors = []
223+ page.on("console", lambda m: errors.append(m.text)
224+ if m.type == "error" else None)
225+ page.on("pageerror", lambda e: errors.append(str(e)))
226+ page.goto(url, wait_until="load")
227+ page.wait_for_timeout(1200)
228+
229+ sw = page.evaluate("document.documentElement.scrollWidth")
230+ iw = page.evaluate("window.innerWidth")
231+ if sw > iw + 1:
232+ failures.append("%dx%d %s horizontal overflow %d > %d"
233+ % (w, h, theme, sw, iw))
234+
235+ applied = page.evaluate(
236+ "document.documentElement.getAttribute('data-theme')")
237+ if applied != theme:
238+ failures.append("%dx%d %s ?theme= did not apply (%r)"
239+ % (w, h, theme, applied))
240+
241+ total = page.evaluate(
242+ "document.getElementById('vAll').textContent")
243+ if total.strip() != "4":
244+ failures.append("%dx%d %s All chip says %r, want 4"
245+ % (w, h, theme, total))
246+
247+ rows = page.evaluate(
248+ "document.querySelectorAll('#rows tr.row').length")
249+ if rows != 4:
250+ failures.append("%dx%d %s table has %d rows, want 4"
251+ % (w, h, theme, rows))
252+
253+ dirty_v = page.evaluate(
254+ "document.getElementById('vDirty').textContent")
255+ if dirty_v.strip() != "1":
256+ failures.append("%dx%d %s Dirty chip says %r, want 1"
257+ % (w, h, theme, dirty_v))
258+
259+ stash_v = page.evaluate(
260+ "document.getElementById('vStash').textContent")
261+ if stash_v.strip() != "1":
262+ failures.append("%dx%d %s Stash chip says %r, want 1"
263+ % (w, h, theme, stash_v))
264+
265+ # the dirty repo must sort first
266+ first = page.evaluate(
267+ "document.querySelector('#rows tr.row .name').textContent")
268+ if first != "billing-service":
269+ failures.append("%dx%d %s first row is %r, want the dirty repo"
270+ % (w, h, theme, first))
271+
272+ # search narrows the list
273+ page.fill("#q", "sandbox")
274+ page.wait_for_timeout(250)
275+ narrowed = page.evaluate(
276+ "document.querySelectorAll('#rows tr.row').length")
277+ if narrowed != 1:
278+ failures.append("%dx%d %s search left %d rows, want 1"
279+ % (w, h, theme, narrowed))
280+ page.fill("#q", "")
281+ page.wait_for_timeout(250)
282+
283+ # the detail drawer opens with the changed file list
284+ page.click("#rows tr.row")
285+ page.wait_for_timeout(700)
286+ opened = page.evaluate(
287+ "document.getElementById('drawer').classList.contains('open')")
288+ if not opened:
289+ failures.append("%dx%d %s drawer did not open"
290+ % (w, h, theme))
291+ else:
292+ files = page.evaluate(
293+ "document.querySelectorAll('#dBody .flist li').length")
294+ if files < 1:
295+ failures.append("%dx%d %s drawer listed no changed files"
296+ % (w, h, theme))
297+ commits = page.evaluate(
298+ "document.querySelectorAll('#dBody .clist li').length")
299+ if commits < 1:
300+ failures.append("%dx%d %s drawer listed no commits"
301+ % (w, h, theme))
302+ dsw = page.evaluate("document.documentElement.scrollWidth")
303+ diw = page.evaluate("window.innerWidth")
304+ if dsw > diw + 1:
305+ failures.append("%dx%d %s drawer overflow %d > %d"
306+ % (w, h, theme, dsw, diw))
307+ page.click("#dClose")
308+ page.wait_for_timeout(350)
309+
310+ if errors:
311+ failures.append("%dx%d %s console errors: %s"
312+ % (w, h, theme, errors[:3]))
313+
314+ shot = os.path.join(DOCS, "ui-%d-%s.png" % (w, theme))
315+ page.screenshot(path=shot, full_page=False)
316+ page.close()
317+ browser.close()
318+
319+ shutil.rmtree(base, ignore_errors=True)
320+
321+ if failures:
322+ print("e2e failures:")
323+ for f in failures:
324+ print(" - %s" % f)
325+ return 1
326+ print("e2e ok: %d viewports x %d themes, screenshots in docs/"
327+ % (len(VIEWPORTS), len(THEMES)))
328+ return 0
329+
330+
331+if __name__ == "__main__":
332+ sys.exit(main())
tests/run.sh+541−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..3961ee8index 0000000..3961ee8
--- /dev/null--- /dev/null
+++ b/tests/run.sh+++ b/tests/run.sh
@@ -0,0 +1,541 @@@@ -0,0 +1,541 @@
1+#!/bin/sh
2+# tests/run.sh - offline checks for plugin_gitstat across all 3 modes.
3+#
4+# Everything runs against ./plugin_gitstat (native build). The repository trees
5+# are real git repos built in a temp directory, so the status parser, the
6+# ahead/behind counter, the stash counter, the detached and unborn states and
7+# the credential redaction are all exercised against git's own output rather
8+# than our idea of it. GITSTAT_ONLY_ROOTS=1 pins the allowed roots to that temp
9+# directory so a developer machine full of checkouts cannot affect the result.
10+#
11+# Optional cross-target artifacts (musl, aarch64, PE) are checked when present.
12+# The last section audits the whole git history for secrets and LAN addresses.
13+#
14+# Exit code 0 = everything passed.
15+
16+set -u
17+
18+ROOT=$(cd "$(dirname "$0")/.." && pwd)
19+cd "$ROOT" || exit 1
20+
21+BIN=./plugin_gitstat
22+PASS=0
23+FAIL=0
24+
25+if [ -t 1 ]; then
26+ C_OK=$(printf '\033[32m'); C_BAD=$(printf '\033[31m'); C_B=$(printf '\033[1m'); C_0=$(printf '\033[0m')
27+else
28+ C_OK=; C_BAD=; C_B=; C_0=
29+fi
30+pass() { PASS=$((PASS + 1)); printf ' %sok%s %s\n' "$C_OK" "$C_0" "$1"; }
31+fail() { FAIL=$((FAIL + 1)); printf ' %sFAIL%s %s\n' "$C_BAD" "$C_0" "$1"; }
32+
33+check() { # check <desc> <expected-substring> <actual>
34+ if printf '%s' "$3" | grep -F -q -- "$2"; then pass "$1"; else
35+ fail "$1 (want: $2)"; printf ' got: %s\n' "$(printf '%s' "$3" | head -c 500)"
36+ fi
37+}
38+
39+check_not() { # check_not <desc> <forbidden-substring> <actual>
40+ if printf '%s' "$3" | grep -F -q -- "$2"; then
41+ fail "$1 (must NOT contain: $2)"; else pass "$1"
42+ fi
43+}
44+
45+section() { printf '\n%s== %s ==%s\n' "$C_B" "$1" "$C_0"; }
46+
47+body() { # strip CGI headers if present, drop CRs, keep the payload
48+ printf '%s\n' "$1" | tr -d '\r' | awk '
49+ BEGIN { inhdr = 0 }
50+ NR == 1 && ($0 ~ /^(Content-Type|Status|Cache-Control|X-Content-Type-Options|Content-Security-Policy):/) { inhdr = 1; next }
51+ inhdr && $0 == "" { inhdr = 0; next }
52+ inhdr { next }
53+ { print }
54+ '
55+}
56+
57+hdr() { printf '%s\n' "$1" | tr -d '\r' | sed -n '1p'; }
58+
59+json_ok() { # json_ok <desc> <json> [python-expression on d]
60+ expr=${3:-True}
61+ if printf '%s' "$2" | python3 -c "import json,sys; d=json.load(sys.stdin); sys.exit(0 if ($expr) else 1)" 2>/dev/null; then
62+ pass "$1"
63+ else
64+ fail "$1 (invalid JSON or assertion failed)"; printf ' got: %s\n' "$(printf '%s' "$2" | head -c 500)"
65+ fi
66+}
67+
68+run() { # run <query-string> [extra env assignments...] -> raw output
69+ qs="$1"; shift
70+ env QUERY_STRING="$qs" "$@" $BIN 2>&1
71+}
72+
73+api() { body "$(run "$1")"; }
74+
75+# ---------------------------------------------------------------- setup
76+section "build"
77+if [ ! -x "$BIN" ]; then
78+ echo " building native binary..."
79+ cc -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src \
80+ -o "$BIN" src/plugin_gitstat.c || { echo " build failed"; exit 1; }
81+fi
82+[ -x "$BIN" ] && pass "native binary exists and is executable" || fail "native binary missing"
83+
84+WORK=$(mktemp -d "${TMPDIR:-/tmp}/gitstat-tests-XXXXXX") || exit 1
85+trap 'rm -rf "$WORK"' EXIT
86+
87+GIT_AUTHOR_NAME="Gitstat Test"; export GIT_AUTHOR_NAME
88+GIT_AUTHOR_EMAIL="gitstat@example.invalid"; export GIT_AUTHOR_EMAIL
89+GIT_COMMITTER_NAME="Gitstat Test"; export GIT_COMMITTER_NAME
90+GIT_COMMITTER_EMAIL="gitstat@example.invalid"; export GIT_COMMITTER_EMAIL
91+GIT_CONFIG_GLOBAL=/dev/null; export GIT_CONFIG_GLOBAL
92+GIT_CONFIG_NOSYSTEM=1; export GIT_CONFIG_NOSYSTEM
93+GIT_TERMINAL_PROMPT=0; export GIT_TERMINAL_PROMPT
94+
95+ROOTS="$WORK/roots"
96+mkdir -p "$ROOTS"
97+
98+mkrepo() { # mkrepo <dir> <branch>
99+ mkdir -p "$1"
100+ git -C "$1" init -q -b "$2"
101+ git -C "$1" config user.name "Gitstat Test"
102+ git -C "$1" config user.email "gitstat@example.invalid"
103+}
104+
105+# A bare upstream with one commit in it, cloned into <dir>. Using a real clone
106+# rather than init+remote means the upstream refs actually exist, which is what
107+# the ahead/behind counters read.
108+mkclone() { # mkclone <dir> <branch>
109+ up="$WORK/up-$(basename "$1").git"
110+ seed="$WORK/seed-$(basename "$1")"
111+ git init -q --bare "$up"
112+ git -C "$up" symbolic-ref HEAD "refs/heads/$2"
113+ mkrepo "$seed" "$2"
114+ printf 'base\n' > "$seed/base.txt"
115+ git -C "$seed" add base.txt
116+ git -C "$seed" commit -q -m "base commit"
117+ git -C "$seed" remote add origin "$up"
118+ git -C "$seed" push -q -u origin "$2"
119+ git clone -q "$up" "$1"
120+ git -C "$1" config user.name "Gitstat Test"
121+ git -C "$1" config user.email "gitstat@example.invalid"
122+}
123+
124+# 1. clean repo with an upstream, fully in sync
125+mkclone "$ROOTS/cleanrepo" main
126+
127+# 2. dirty repo: one modified file, one untracked file, one staged file
128+mkrepo "$ROOTS/dirtyrepo" main
129+printf 'one\n' > "$ROOTS/dirtyrepo/keep.txt"
130+printf 'two\n' > "$ROOTS/dirtyrepo/mod.txt"
131+printf 'three\n' > "$ROOTS/dirtyrepo/add.txt"
132+git -C "$ROOTS/dirtyrepo" add keep.txt mod.txt add.txt
133+git -C "$ROOTS/dirtyrepo" commit -q -m "seed three files"
134+printf 'modified\n' >> "$ROOTS/dirtyrepo/mod.txt"
135+printf 'staged\n' >> "$ROOTS/dirtyrepo/add.txt"
136+git -C "$ROOTS/dirtyrepo" add add.txt
137+printf 'untracked\n' > "$ROOTS/dirtyrepo/new.txt"
138+
139+# 3. ahead repo: two local commits past its upstream, plus a stash
140+mkclone "$ROOTS/aheadrepo" main
141+printf 'a\n' >> "$ROOTS/aheadrepo/base.txt"
142+git -C "$ROOTS/aheadrepo" commit -q -am "local commit one"
143+printf 'b\n' >> "$ROOTS/aheadrepo/base.txt"
144+git -C "$ROOTS/aheadrepo" commit -q -am "local commit two"
145+printf 'stashed\n' >> "$ROOTS/aheadrepo/base.txt"
146+git -C "$ROOTS/aheadrepo" stash push -q -m "work in progress"
147+
148+# 3b. behind repo: its upstream has moved on
149+mkclone "$ROOTS/behindrepo" main
150+other="$WORK/other-behindrepo"
151+git clone -q "$WORK/up-behindrepo.git" "$other"
152+git -C "$other" config user.name "Gitstat Test"
153+git -C "$other" config user.email "gitstat@example.invalid"
154+printf 'upstream\n' >> "$other/base.txt"
155+git -C "$other" commit -q -am "upstream moved on"
156+git -C "$other" push -q origin main
157+git -C "$ROOTS/behindrepo" fetch -q origin
158+
159+# 4. detached repo
160+mkrepo "$ROOTS/detachedrepo" main
161+printf 'd\n' > "$ROOTS/detachedrepo/d.txt"
162+git -C "$ROOTS/detachedrepo" add d.txt
163+git -C "$ROOTS/detachedrepo" commit -q -m "detach me"
164+printf 'd2\n' >> "$ROOTS/detachedrepo/d.txt"
165+git -C "$ROOTS/detachedrepo" commit -q -am "second commit"
166+git -C "$ROOTS/detachedrepo" checkout -q HEAD~1
167+
168+# 5. unborn repo: initialised, nothing committed
169+mkrepo "$ROOTS/unbornrepo" main
170+
171+# 6. repo whose origin URL carries userinfo (must be redacted)
172+mkclone "$ROOTS/secretremote" main
173+git -C "$ROOTS/secretremote" remote set-url origin \
174+ "https://plantuser:planttoken123@example.invalid/x.git"
175+
176+# 7. a nested repo two levels deep, to prove the walk descends
177+mkdir -p "$ROOTS/group/nested"
178+mkrepo "$ROOTS/group/nested/deeprepo" main
179+printf 'n\n' > "$ROOTS/group/nested/deeprepo/n.txt"
180+git -C "$ROOTS/group/nested/deeprepo" add n.txt
181+git -C "$ROOTS/group/nested/deeprepo" commit -q -m "nested seed"
182+
183+# 8. a directory with no .git at all (must be ignored)
184+mkdir -p "$ROOTS/notarepo"
185+
186+ROOTENV="GITSTAT_ONLY_ROOTS=1"
187+ROOTVAR="GITSTAT_ROOTS=$ROOTS"
188+
189+# ---------------------------------------------------------------- --meta
190+section "--meta / discovery"
191+META=$($BIN --meta)
192+check "--meta prints name git" '"name":"git"' "$META"
193+check "--meta prints desc Repo status" '"desc":"Repo status"' "$META"
194+json_ok "--meta is valid JSON with exactly 2 keys" "$META" "sorted(d.keys())==['desc','name']"
195+SXMETA=$(env SX_PLUGIN_META=1 $BIN)
196+check "SX_PLUGIN_META=1 returns the metadata" '"name":"git"' "$SXMETA"
197+METAQ=$(env SX_PLUGIN_META=1 QUERY_STRING="action=repos" $BIN)
198+check "--meta wins over the query string" '"name":"git"' "$METAQ"
199+DESCLEN=$(printf '%s' "$META" | python3 -c "import json,sys;print(len(json.load(sys.stdin)['desc']))")
200+[ "$DESCLEN" -le 15 ] && pass "desc is <= 15 chars ($DESCLEN)" || fail "desc too long ($DESCLEN)"
201+
202+# ---------------------------------------------------------------- auth
203+section "node authentication"
204+UNAUTH=$(env BOT_PASSWORD=testpw QUERY_STRING="action=repos" \
205+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
206+check "unauthenticated action=repos is 401" "Status: 401 Unauthorized" "$UNAUTH"
207+check "401 body carries the error" '"error":"invalid node password"' "$UNAUTH"
208+
209+OKPW=$(env BOT_PASSWORD=testpw HTTP_X_BOT_PASSWORD=testpw QUERY_STRING="action=repos" \
210+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
211+check "X-Bot-Password is accepted" '"ok":true' "$OKPW"
212+
213+OKBR=$(env BOT_PASSWORD=testpw HTTP_AUTHORIZATION="Bearer testpw" QUERY_STRING="action=repos" \
214+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
215+check "Authorization: Bearer is accepted" '"ok":true' "$OKBR"
216+
217+OKQP=$(env BOT_PASSWORD=testpw QUERY_STRING="action=repos&pwd=testpw" \
218+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
219+check "?pwd= is accepted" '"ok":true' "$OKQP"
220+
221+BADPW=$(env BOT_PASSWORD=testpw QUERY_STRING="action=repos&pwd=nope" \
222+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
223+check "wrong ?pwd= is 401" "Status: 401 Unauthorized" "$BADPW"
224+
225+UNAUTHH=$(env BOT_PASSWORD=testpw QUERY_STRING="" \
226+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
227+check "unauthenticated HTML page is 401 too" "Status: 401 Unauthorized" "$UNAUTHH"
228+
229+METAOK=$(env BOT_PASSWORD=testpw SX_PLUGIN_META=1 $BIN)
230+check "--meta stays unauthenticated so discovery works" '"name":"git"' "$METAOK"
231+
232+NOAUTH=$(env QUERY_STRING="action=repos" GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
233+check "no BOT_PASSWORD means auth is a no-op" '"ok":true' "$NOAUTH"
234+
235+# ---------------------------------------------------------------- repos
236+section "?action=repos"
237+REPOS=$(env QUERY_STRING="action=repos" GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
238+REPOSB=$(body "$REPOS")
239+check "repos answers JSON" "Content-Type: application/json" "$REPOS"
240+json_ok "repos doc is valid" "$REPOSB"
241+json_ok "repos reports ok" "$REPOSB" "d['ok'] is True"
242+json_ok "repos has a summary" "$REPOSB" "'summary' in d and 'dirty' in d['summary']"
243+json_ok "repos has a roots array with per-root counts" "$REPOSB" \
244+ "len(d['roots'])==1 and d['roots'][0]['count']==8 and d['roots'][0]['exists']"
245+json_ok "repos found the 8 fixture repos" "$REPOSB" "d['count']==8"
246+json_ok "the plain directory is not a repo" "$REPOSB" \
247+ "not any('notarepo' in r['path'] for r in d['repos'])"
248+json_ok "the nested repo was found at depth 3" "$REPOSB" \
249+ "any(r['name']=='deeprepo' for r in d['repos'])"
250+json_ok "the first repo is a dirty one (dirty-first sort)" "$REPOSB" "d['repos'][0]['dirty']>0"
251+json_ok "every repo has the documented field set" "$REPOSB" \
252+ "all(set(r)>=set(['path','name','root','branch','upstream','ahead','behind','dirty','untracked','staged','conflicted','stash','detached','no_upstream','unborn','last_commit']) for r in d['repos'])"
253+json_ok "last_commit has hash/ct/at/subject" "$REPOSB" \
254+ "all(set(r['last_commit'])>=set(['hash','short','ct','at','subject']) for r in d['repos'])"
255+json_ok "checked_at is an ISO-Z stamp" "$REPOSB" "d['checked_at'].endswith('Z')"
256+
257+# per-repo assertions
258+DIRTY=$(printf '%s' "$REPOSB" | python3 -c "
259+import json,sys
260+d=json.load(sys.stdin)
261+print(json.dumps([r for r in d['repos'] if r['name']=='dirtyrepo'][0]))")
262+json_ok "dirtyrepo counts 3 changed entries" "$DIRTY" "d['dirty']==3"
263+json_ok "dirtyrepo counts 1 untracked" "$DIRTY" "d['untracked']==1"
264+json_ok "dirtyrepo is not detached and has a branch" "$DIRTY" \
265+ "d['detached'] is False and d['branch']=='main'"
266+
267+CLEAN=$(printf '%s' "$REPOSB" | python3 -c "
268+import json,sys
269+d=json.load(sys.stdin)
270+print(json.dumps([r for r in d['repos'] if r['name']=='cleanrepo'][0]))")
271+json_ok "cleanrepo is clean" "$CLEAN" "d['dirty']==0"
272+json_ok "cleanrepo is in sync with its upstream" "$CLEAN" "d['ahead']==0 and d['behind']==0"
273+json_ok "cleanrepo has an upstream" "$CLEAN" "d['no_upstream'] is False and d['upstream']"
274+json_ok "cleanrepo carried its last commit" "$CLEAN" "d['last_commit']['subject']=='base commit'"
275+
276+AHEAD=$(printf '%s' "$REPOSB" | python3 -c "
277+import json,sys
278+d=json.load(sys.stdin)
279+print(json.dumps([r for r in d['repos'] if r['name']=='aheadrepo'][0]))")
280+json_ok "aheadrepo is 2 ahead" "$AHEAD" "d['ahead']==2"
281+json_ok "aheadrepo is not behind" "$AHEAD" "d['behind']==0"
282+json_ok "aheadrepo counted its stash" "$AHEAD" "d['stash']==1"
283+json_ok "aheadrepo last subject is the newest commit" "$AHEAD" \
284+ "d['last_commit']['subject']=='local commit two'"
285+
286+DET=$(printf '%s' "$REPOSB" | python3 -c "
287+import json,sys
288+d=json.load(sys.stdin)
289+print(json.dumps([r for r in d['repos'] if r['name']=='detachedrepo'][0]))")
290+json_ok "detachedrepo is flagged detached" "$DET" "d['detached'] is True"
291+json_ok "detachedrepo branch reads detached" "$DET" "d['branch']=='detached'"
292+
293+UNB=$(printf '%s' "$REPOSB" | python3 -c "
294+import json,sys
295+d=json.load(sys.stdin)
296+print(json.dumps([r for r in d['repos'] if r['name']=='unbornrepo'][0]))")
297+json_ok "unbornrepo is flagged unborn" "$UNB" "d['unborn'] is True"
298+json_ok "unbornrepo has no upstream" "$UNB" "d['no_upstream'] is True"
299+
300+SEC=$(printf '%s' "$REPOSB" | python3 -c "
301+import json,sys
302+d=json.load(sys.stdin)
303+print(json.dumps([r for r in d['repos'] if r['name']=='secretremote'][0]))")
304+check_not "credential in the origin URL is redacted (token)" "planttoken123" "$SEC"
305+check_not "credential in the origin URL is redacted (user)" "plantuser" "$SEC"
306+check "redacted remote keeps the host" "example.invalid/x.git" "$SEC"
307+check_not "the remote field carries no userinfo" "plantuser" "$(printf '%s' "$SEC" | python3 -c "import json,sys;print(json.load(sys.stdin)['remote'])")"
308+
309+check_not "no path outside the root is reported" "$WORK/upstream.git" "$REPOSB"
310+
311+# summary counters
312+json_ok "summary counts the dirty repos" "$REPOSB" "d['summary']['dirty']>=1"
313+json_ok "summary counts the ahead repo" "$REPOSB" "d['summary']['ahead']>=1"
314+json_ok "summary counts the behind repo" "$REPOSB" "d['summary']['behind']>=1"
315+BEHIND=$(printf '%s' "$REPOSB" | python3 -c "
316+import json,sys
317+d=json.load(sys.stdin)
318+print(json.dumps([r for r in d['repos'] if r['name']=='behindrepo'][0]))")
319+json_ok "behindrepo is 1 behind" "$BEHIND" "d['behind']==1"
320+json_ok "behindrepo is not ahead" "$BEHIND" "d['ahead']==0"
321+json_ok "behindrepo still has an upstream" "$BEHIND" "d['no_upstream'] is False"
322+json_ok "summary counts the stashes" "$REPOSB" "d['summary']['stashes']>=1"
323+json_ok "summary counts the detached repo" "$REPOSB" "d['summary']['detached']==1"
324+
325+# empty root
326+EMPTY=$(env QUERY_STRING="action=repos" GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$WORK/nowhere" $BIN)
327+json_ok "a missing root reports exists:false" "$(body "$EMPTY")" \
328+ "d['roots'][0]['exists'] is False and d['count']==0"
329+
330+# per-root budget: two roots are counted independently
331+mkdir -p "$WORK/r1" "$WORK/r2"
332+cp -a "$ROOTS/cleanrepo" "$WORK/r1/one"
333+cp -a "$ROOTS/cleanrepo" "$WORK/r1/two"
334+cp -a "$ROOTS/cleanrepo" "$WORK/r2/three"
335+TWOROOT=$(env QUERY_STRING="action=repos" GITSTAT_ONLY_ROOTS=1 \
336+ GITSTAT_ROOTS="$WORK/r1:$WORK/r2" $BIN)
337+json_ok "two roots keep independent counts" "$(body "$TWOROOT")" \
338+ "len(d['roots'])==2 and d['roots'][0]['count']==2 and d['roots'][1]['count']==1"
339+json_ok "the global table is that of both roots" "$(body "$TWOROOT")" "d['count']==3"
340+
341+# a duplicate root listing is de-duplicated, not double counted
342+DUPR=$(env QUERY_STRING="action=repos" GITSTAT_ONLY_ROOTS=1 \
343+ GITSTAT_ROOTS="$WORK/r1:$WORK/r1" $BIN)
344+json_ok "a repeated root is de-duplicated" "$(body "$DUPR")" \
345+ "len(d['roots'])==1 and d['count']==2"
346+
347+# ---------------------------------------------------------------- repo detail
348+section "?action=repo&path="
349+RP="env QUERY_STRING=action=repo\&path=$ROOTS/dirtyrepo GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS=$ROOTS"
350+DETAIL=$(env QUERY_STRING="action=repo&path=$ROOTS/dirtyrepo" \
351+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
352+DETB=$(body "$DETAIL")
353+check "repo detail answers JSON" "Content-Type: application/json" "$DETAIL"
354+json_ok "repo detail is valid" "$DETB"
355+json_ok "repo detail reports ok" "$DETB" "d['ok'] is True"
356+json_ok "repo detail has the repo block" "$DETB" "d['repo']['name']=='dirtyrepo'"
357+json_ok "repo detail lists 3 changed files" "$DETB" "len(d['changed'])==3"
358+json_ok "repo detail marks the untracked file" "$DETB" \
359+ "any(c['code']=='??' and c['path']=='new.txt' for c in d['changed'])"
360+json_ok "repo detail marks the modified file" "$DETB" \
361+ "any(c['path']=='mod.txt' and c['code'][1]=='M' for c in d['changed'])"
362+json_ok "repo detail marks the staged file" "$DETB" \
363+ "any(c['path']=='add.txt' and c['code'][0]=='M' for c in d['changed'])"
364+json_ok "repo detail has recent commits" "$DETB" "len(d['commits'])>=1"
365+json_ok "each commit has hash/ct/author/subject" "$DETB" \
366+ "all(set(c)>=set(['hash','ct','author','subject']) for c in d['commits'])"
367+json_ok "changed_count is reported" "$DETB" "d['changed_count']==3"
368+
369+AHEADD=$(env QUERY_STRING="action=repo&path=$ROOTS/aheadrepo" \
370+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
371+json_ok "detail of a repo with commits lists newest first" "$(body "$AHEADD")" \
372+ "d['commits'][0]['subject']=='local commit two'"
373+json_ok "detail caps commits at 20" "$(body "$AHEADD")" "len(d['commits'])<=20"
374+
375+# path allowlisting
376+OUTSIDE=$(env QUERY_STRING="action=repo&path=/etc" \
377+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
378+check "a path outside every root is 403" "Status: 403 Forbidden" "$OUTSIDE"
379+check "403 explains why" "not in an allowlisted root" "$OUTSIDE"
380+
381+DOTDOT=$(env QUERY_STRING="action=repo&path=$ROOTS/../etc" \
382+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
383+check "a .. traversal is refused" "Status: 403 Forbidden" "$DOTDOT"
384+
385+NOTREPO=$(env QUERY_STRING="action=repo&path=$ROOTS/notarepo" \
386+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
387+check "a directory without .git is refused" "Status: 403 Forbidden" "$NOTREPO"
388+
389+EMPTYP=$(env QUERY_STRING="action=repo&path=" \
390+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
391+check "a missing path argument is refused" "Status: 403 Forbidden" "$EMPTYP"
392+
393+# ---------------------------------------------------------------- fetch
394+section "?action=fetch"
395+NOFETCH=$(env QUERY_STRING="action=fetch&path=$ROOTS/cleanrepo" REQUEST_METHOD=POST \
396+ GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
397+check "fetch is disabled by default" '"ok":false' "$NOFETCH"
398+check "fetch says how to enable it" "GITSTAT_ALLOW_FETCH" "$NOFETCH"
399+
400+GETFETCH=$(env QUERY_STRING="action=fetch&path=$ROOTS/cleanrepo" \
401+ GITSTAT_ALLOW_FETCH=1 GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
402+check "fetch is POST only" "fetch is POST only" "$GETFETCH"
403+
404+FETCHOUT=$(env QUERY_STRING="action=fetch&path=$ROOTS/cleanrepo" REQUEST_METHOD=POST \
405+ GITSTAT_ALLOW_FETCH=1 GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
406+FB=$(body "$FETCHOUT")
407+json_ok "enabled fetch returns a JSON document" "$FB"
408+json_ok "enabled fetch of a clean repo succeeds" "$FB" "d['ok'] is True and d['exit']==0"
409+json_ok "fetch echoes the branch and sync state" "$FB" "'branch' in d and 'ahead' in d"
410+
411+FETCHBAD=$(env QUERY_STRING="action=fetch&path=/etc" REQUEST_METHOD=POST \
412+ GITSTAT_ALLOW_FETCH=1 GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
413+check "fetch of a path outside the roots is 403" "Status: 403 Forbidden" "$FETCHBAD"
414+
415+# ---------------------------------------------------------------- other actions
416+UNKNOWN=$(env QUERY_STRING="action=bogus" GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
417+check "an unknown action answers an error document" '"error":"unknown action"' "$UNKNOWN"
418+
419+FMT=$(env QUERY_STRING="format=json" GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
420+check "format=json is served as JSON" "Content-Type: application/json" "$FMT"
421+json_ok "format=json returns the repos document" "$(body "$FMT")" "d['action']=='repos'"
422+
423+# ---------------------------------------------------------------- HTML
424+section "HTML UI"
425+HTML=$(env QUERY_STRING="" GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
426+check "GET answers HTML" "Content-Type: text/html" "$HTML"
427+check "the page has a doctype" "<!DOCTYPE html>" "$HTML"
428+check "the page names the product" "SCORPIOX BOT" "$HTML"
429+check "the page sets the token block" "--bg:#000000" "$HTML"
430+check "the page carries the light token block" "data-theme=light" "$HTML"
431+check "the page carries the prepaint script" "sx-theme-request" "$HTML"
432+check "the page carries the handoff listener" "sx-theme" "$HTML"
433+check_not "no external script is referenced" "<script src=" "$HTML"
434+check_not "no CDN is referenced" "cdn." "$HTML"
435+check_not "no http URL is referenced in the page" "http://" "$HTML"
436+check "the page has the rows table" 'id="rows"' "$HTML"
437+check "the page has the filter chips" 'class="chip' "$HTML"
438+check "the page has the detail drawer" 'id="drawer"' "$HTML"
439+check "the page has inline SVG icons" "<svg viewBox" "$HTML"
440+check "the page has a CSP" "Content-Security-Policy" "$HTML"
441+check "the page declares the theme toggle hidden in embed" "embed-hide" "$HTML"
442+
443+EMBED=$(env QUERY_STRING="embed=1" GITSTAT_ONLY_ROOTS=1 GITSTAT_ROOTS="$ROOTS" $BIN)
444+check "embed=1 still serves the page" "<!DOCTYPE html>" "$EMBED"
445+check "embed=1 marks the document embedded" "embed" "$EMBED"
446+
447+# no emoji anywhere in the page
448+if printf '%s' "$HTML" | python3 -c "
449+import sys
450+s=sys.stdin.buffer.read().decode('utf-8','replace')
451+bad=[c for c in s if ord(c)>0x2100 and not (0x2010<=ord(c)<=0x2027)]
452+sys.exit(1 if bad else 0)" 2>/dev/null; then
453+ pass "no emoji in the page"
454+else
455+ fail "the page contains emoji or exotic glyphs"
456+fi
457+
458+# the hub-vs-direct route branch must be present, got wrong is the classic bug
459+check "the page branches on ?plugin= for the hub route" \
460+ "HUB ? '/plugins?plugin='" "$HTML"
461+check "the page falls back to the direct node route" "'/plugin_gitstat'" "$HTML"
462+
463+# ---------------------------------------------------------------- cross targets
464+section "cross-target artifacts"
465+if [ -f plugin_gitstat.musl ]; then
466+ file plugin_gitstat.musl | grep -q 'ELF' && pass "the musl build is an ELF" || fail "musl build is not ELF"
467+ file plugin_gitstat.musl | grep -qi 'static' && pass "the musl build is statically linked" || fail "musl build is dynamic"
468+else
469+ echo " (skip) plugin_gitstat.musl not built here"
470+fi
471+if [ -f plugin_gitstat.arm64 ]; then
472+ file plugin_gitstat.arm64 | grep -Eq 'aarch64' && pass "the arm64 build is aarch64" || fail "arm64 build is not aarch64"
473+else
474+ echo " (skip) plugin_gitstat.arm64 not built here"
475+fi
476+if [ -f plugin_gitstat.exe ]; then
477+ if head -c 2 plugin_gitstat.exe | od -An -c | grep -q 'M Z'; then
478+ pass "the Windows build starts with an MZ header"
479+ else
480+ fail "the Windows build is not a PE (no MZ header)"
481+ fi
482+else
483+ echo " (skip) plugin_gitstat.exe not built here"
484+fi
485+
486+# ---------------------------------------------------------------- generated UI
487+section "generated page"
488+if command -v python3 >/dev/null 2>&1; then
489+ if python3 tools/gen_ui.py --check >/dev/null 2>&1; then
490+ pass "src/ui_html.h matches src/ui.html"
491+ else
492+ fail "src/ui_html.h is stale - run tools/gen_ui.py"
493+ fi
494+else
495+ echo " (skip) python3 not available"
496+fi
497+
498+# ---------------------------------------------------------------- history audit
499+section "git history secret audit"
500+if git rev-parse --git-dir >/dev/null 2>&1; then
501+ ALL="$WORK/history.txt"
502+ git log -p --all 2>/dev/null \
503+ | grep -v '^Author: ' \
504+ | grep -vE 'scan_hist|HITS=|grep -Eo|suspects=|audit "|check_not "|scan "|audit\(\)' \
505+ > "$ALL" || : > "$ALL"
506+
507+ audit() { # audit <label> <regex>
508+ H=$(grep -Eo "$2" "$ALL" 2>/dev/null | sort -u | head -3 || true)
509+ if [ -n "$H" ]; then
510+ fail "history: $1"; printf '%s\n' "$H" | sed 's/^/ /'
511+ else
512+ pass "history: $1"
513+ fi
514+ }
515+ audit "no LAN addresses" '192\.168\.[0-9]+\.[0-9]+'
516+ audit "no private 10.x range" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
517+ audit "no 172.16-31 range" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
518+ audit "no GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
519+ audit "no HF token" 'hf_[A-Za-z0-9]{30,}'
520+ audit "no embedded git creds" 'scorpioxinc:[A-Za-z0-9]{20,}'
521+ if command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
522+ if scorpiox-cli-botplugin audit . >"$WORK/audit.out" 2>&1; then
523+ pass "scorpiox-cli-botplugin audit passes"
524+ else
525+ fail "scorpiox-cli-botplugin audit failed"; sed 's/^/ /' "$WORK/audit.out" | head -6
526+ fi
527+ else
528+ echo " (skip) scorpiox-cli-botplugin not installed"
529+ fi
530+else
531+ echo " (skip) not a git checkout"
532+fi
533+
534+# ---------------------------------------------------------------- summary
535+printf '\n%s=================================%s\n' "$C_B" "$C_0"
536+printf ' passed %s%d%s failed %s%d%s\n' "$C_OK" "$PASS" "$C_0" \
537+ "$([ "$FAIL" -eq 0 ] && echo "$C_OK" || echo "$C_BAD")" "$FAIL" "$C_0"
538+printf '%s=================================%s\n' "$C_B" "$C_0"
539+
540+[ "$FAIL" -eq 0 ] || exit 1
541+exit 0
tools/gen_ui.py+105−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..9d9a7e1index 0000000..9d9a7e1
--- /dev/null--- /dev/null
+++ b/tools/gen_ui.py+++ b/tools/gen_ui.py
@@ -0,0 +1,105 @@@@ -0,0 +1,105 @@
1+#!/usr/bin/env python3
2+"""tools/gen_ui.py - compile src/ui.html into src/ui_html.h.
3+
4+The page lives in one readable file (src/ui.html) so it can be diffed and
5+reviewed like any other source. This script turns it into a single C string
6+constant with two control-character placeholders:
7+
8+ 0x01 -> the bot theme prepaint script + <style> + theme tokens
9+ 0x02 -> the bot theme handoff script (just before </body>)
10+
11+main() splits the constant on those bytes and emits the macros from
12+src/bot_theme_plugin.h in their place, so the theme can never drift out of
13+sync with the rest of the bot.
14+
15+ python3 tools/gen_ui.py # write src/ui.html.h
16+ python3 tools/gen_ui.py --check # exit 1 when the header is stale
17+"""
18+
19+import os
20+import sys
21+
22+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
23+SRC = os.path.join(ROOT, "src", "ui.html")
24+OUT = os.path.join(ROOT, "src", "ui_html.h")
25+
26+TOKENS = "<!--TOKENS-->"
27+MARK_TOKENS = "\u0001"
28+MARK_HANDOFF = "\u0002"
29+
30+
31+def c_literal(text):
32+ """Escape text for a C string literal, one line per source line."""
33+ out = []
34+ for line in text.splitlines(True):
35+ piece = []
36+ for ch in line:
37+ if ch == "\\":
38+ piece.append("\\\\")
39+ elif ch == '"':
40+ piece.append('\\"')
41+ elif ch == "\n":
42+ piece.append("\\n")
43+ elif ch == "\r":
44+ piece.append("\\r")
45+ elif ch == "\t":
46+ piece.append("\\t")
47+ elif ch == MARK_TOKENS:
48+ piece.append("\\001")
49+ elif ch == MARK_HANDOFF:
50+ piece.append("\\002")
51+ elif ord(ch) < 0x20:
52+ piece.append("\\%03o" % ord(ch))
53+ else:
54+ piece.append(ch)
55+ out.append(' "%s"\n' % "".join(piece))
56+ return "".join(out)
57+
58+
59+def render():
60+ with open(SRC, "r", encoding="utf-8") as f:
61+ html = f.read()
62+
63+ if TOKENS not in html:
64+ raise SystemExit("src/ui.html has no %s placeholder" % TOKENS)
65+ html = html.replace(TOKENS, MARK_TOKENS)
66+
67+ # Handoff script goes right before the closing body tag.
68+ if "</body>" not in html:
69+ raise SystemExit("src/ui.html has no </body>")
70+ html = html.replace("</body>", MARK_HANDOFF + "</body>", 1)
71+
72+ header = (
73+ "/* Generated by tools/gen_ui.py from src/ui.html. Do not edit by hand. */\n"
74+ "#ifndef SX_GITSTAT_UI_HTML_H\n"
75+ "#define SX_GITSTAT_UI_HTML_H\n"
76+ "\n"
77+ "static const char *UI_HTML =\n" + c_literal(html) + " ;\n"
78+ "\n"
79+ "#endif /* SX_GITSTAT_UI_HTML_H */\n"
80+ )
81+ return header
82+
83+
84+def main():
85+ header = render()
86+ check = "--check" in sys.argv[1:]
87+ if check:
88+ try:
89+ with open(OUT, "r", encoding="utf-8") as f:
90+ cur = f.read()
91+ except OSError:
92+ cur = ""
93+ if cur != header:
94+ sys.stderr.write("src/ui.html.h is stale - run tools/gen_ui.py\n")
95+ return 1
96+ print("src/ui.html.h is up to date")
97+ return 0
98+ with open(OUT, "w", encoding="utf-8") as f:
99+ f.write(header)
100+ print("wrote %s (%d bytes)" % (os.path.relpath(OUT, ROOT), len(header)))
101+ return 0
102+
103+
104+if __name__ == "__main__":
105+ sys.exit(main())
0106