diff --git a/maintenance/woodpecker-ci.md b/maintenance/woodpecker-ci.md index b0d6fcf..de26116 100644 --- a/maintenance/woodpecker-ci.md +++ b/maintenance/woodpecker-ci.md @@ -68,13 +68,26 @@ CLI, and a pinned MkDocs toolchain at `/opt/docs-venv`. It **runs as root** `POST /api/repos?forge_remote_id=` (query param, not body); a manual run is `POST /api/repos//pipelines` with `{"branch": "..."}`. - **Enabled repos:** `co-op/docs` (id 1), `code/member-portal` (id 2), - `code/admin-panel` (id 3). Note `co-op/member-portal` is a Gitea REDIRECT to + `code/admin-panel` (id 3), `code/member-dashboard` (id 4, enabled + 2026-11-13 with the same push gate + `ci/woodpecker/push/woodpecker` status + check as the panel). Note `co-op/member-portal` is a Gitea REDIRECT to `code/member-portal` — the canonical repo lives in the `code` org (Gitea id 6). -- **Test gating (added 2026-11-11):** `.woodpecker.yml` on both apps' default - branches runs their EXISTING suites on every push (12 portal test files; - admin-panel guest-guard test + 4 page-JS harnesses via the vendored - `tests/check-page-js.sh`). Gitea branch protection on `main` of both repos - now requires the status context `ci/woodpecker/push/woodpecker` to merge. +- **Test gating (added 2026-11-11):** `.woodpecker.yml` on the apps' default + branches runs their EXISTING suites on every push (portal test files; + admin-panel guest-guard + oidc/chart sync pins + 4 page-JS harnesses via the + vendored `tests/check-page-js.sh`; member-dashboard oidc/chart sync pins + 2 + page-JS harnesses). Gitea branch protection on `main` of each app repo + requires the status context `ci/woodpecker/push/woodpecker` to merge. +- **Shared chart module (added 2026-11-13):** `ops-docs/scripts/shared/ + coop_chart.js` is the canonical chart rendering + hover-tooltip module; + byte-identical copies live at `app/coop_chart.js` in both UI apps, spliced + into each PAGE_HTML at import time. `tests/test_chart_sync.py` in each app + pins the copy (same pattern as the oidc client); + `scripts/check-chart-sync.py` is the pre-deploy gate and + `scripts/sync-chart-module.sh` re-copies + re-pins both apps in one step. + The vendored `tests/check-page-js.sh` in BOTH apps splices the module into + the extracted page JS exactly as the app does — keep the two vendored + copies byte-identical to the skill's script (md5 445cdcf59f193ff875bb634f6f790e73). - **Proven with real output:** first push runs green (portal tests step: 439 log lines ending "all portal test suites green"; all four harnesses OK on the panel), and a deliberately broken assertion on a branch (`ci-red-test`) diff --git a/scripts/check-chart-sync.py b/scripts/check-chart-sync.py new file mode 100755 index 0000000..732a965 --- /dev/null +++ b/scripts/check-chart-sync.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Verify the shared chart module is single-sourced and byte-identical. + +Checks, in order, and exits non-zero naming every failure: + + 1. canonical ops-docs/scripts/shared/coop_chart.js + == member-dashboard/app/coop_chart.js (byte-identical, sha256) + == admin-panel/app/coop_chart.js (byte-identical, sha256) + 2. each repo's tests/test_chart_sync.py pins the CANONICAL revision + (so CI — which has no ops-docs checkout — still goes red when a repo + copy is hand-edited). + 3. each repo's app/main.py splices the module into PAGE_HTML + (loader + placeholder replace present). + +Run from anywhere: python3 ops-docs/scripts/check-chart-sync.py +This is the pre-deploy gate for either thin app; sync-chart-module.sh runs it +at the end of every sync. +""" +import hashlib +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent # ops-docs/scripts +REPOS = HERE.parent.parent # ~/repos + +CANONICAL = HERE / "shared" / "coop_chart.js" + +SPLICE = 'PAGE_HTML = PAGE_HTML.replace("/*@@CHART_MODULE@@*/", CHART_MODULE_JS)' +LOADER = 'CHART_MODULE_JS = (Path(__file__).resolve().parent / "coop_chart.js").read_text()' + +APPS = { + "member-dashboard": ("app/coop_chart.js", "tests/test_chart_sync.py", "app/main.py"), + "admin-panel": ("app/coop_chart.js", "tests/test_chart_sync.py", "app/main.py"), +} + + +def sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +failures: list[str] = [] + +if not CANONICAL.exists(): + print(f"FAILED: canonical module missing: {CANONICAL}") + sys.exit(1) + +canonical_sha = sha256(CANONICAL) +print(f"canonical sha256: {canonical_sha}") + +for repo, (copy_rel, test_rel, main_rel) in APPS.items(): + copy = REPOS / repo / copy_rel + test = REPOS / repo / test_rel + main = REPOS / repo / main_rel + + if not copy.exists(): + failures.append(f"{repo}: {copy_rel} missing") + else: + got = sha256(copy) + if got == canonical_sha: + print(f"ok - {repo}: {copy_rel} byte-identical to canonical") + else: + failures.append( + f"{repo}: {copy_rel} DRIFTED from the canonical module\n" + f" canonical {canonical_sha}\n" + f" actual {got}\n" + f" fix: edit the canonical module (ops-docs: scripts/shared/coop_chart.js) " + f"and run ops-docs/scripts/sync-chart-module.sh — never hand-edit the copy.") + + if not test.exists(): + failures.append(f"{repo}: {test_rel} missing") + else: + tsrc = test.read_text() + if canonical_sha in tsrc: + print(f"ok - {repo}: {test_rel} pins the canonical revision") + else: + failures.append( + f"{repo}: {test_rel} does not pin the CURRENT canonical revision " + f"({canonical_sha[:16]}…) — run ops-docs/scripts/sync-chart-module.sh to re-pin.") + + if not main.exists(): + failures.append(f"{repo}: {main_rel} missing") + else: + msrc = main.read_text() + missing = [name for name, needle in (("loader", LOADER), ("splice", SPLICE)) if needle not in msrc] + if missing: + failures.append(f"{repo}: {main_rel} lacks the chart-module {', '.join(missing)}") + else: + print(f"ok - {repo}: {main_rel} loads and splices the module") + +if failures: + print() + for f in failures: + print("FAILED: " + f) + sys.exit(1) +print("chart module sync: OK") diff --git a/scripts/shared/coop_chart.js b/scripts/shared/coop_chart.js new file mode 100644 index 0000000..d1a4953 --- /dev/null +++ b/scripts/shared/coop_chart.js @@ -0,0 +1,261 @@ +/* Inference Cooperative — shared hand-rolled chart module. + * + * Canonical copy: co-op/ops-docs repo, scripts/shared/coop_chart.js. + * Byte-identical copies ship in admin-panel/app/ and member-dashboard/app/ + * (each repo's tests/test_chart_sync.py pins its copy to this revision — CI + * has no ops-docs checkout). Editing a copy by hand is a dead end: edit the + * canonical file and run ops-docs/scripts/sync-chart-module.sh, which + * re-copies and re-pins both repos in one step. + * + * No chart library, no CDN (the co-op's no-external-dependency rule applies + * to charts like everything else). Colors come from each app's CSS vars, so a + * chart matches the tables around it. The module exposes ONE global, + * CoOpChart; each app's page JS destructures the pieces it needs, so call + * sites keep their bare function names. + * + * Tooltips — exact values on hover (the panel's registerChartTips contract): + * 1. At render time, stamp each hoverable data element with + * data-tip-host="" and data-tip-i="" + * 2. registerChartTips("", points) with one point per index: + * { label: "2026-11-07", series: [["Spend", "$12.34"], ...] } + * Values MUST come from the chart's own data arrays (exact), never + * pixel-estimated, and `series` carries EVERY series at that x. + * One delegated listener set on document serves every chart, so innerHTML + * re-renders need no re-binding and new charts join chart-by-chart as they + * render. The box is a fixed-position div with pointer-events:none, clamped + * inside the viewport. NULL points get no stamp and no tooltip (the gap + * rule). Styling lives in each app's .chart-tip CSS block. + * + * Drawing helpers — extracted from the admin panel's chart code so both apps + * produce the same shapes from the same code: + * niceStep(raw, continuous) axis step. continuous=true: the 1/2/5 x 10^k + * rule (money, energy, carbon — ticks read $10, + * not $4.92). false: whole counts rounded up to + * a half power of ten, never below 1 (a + * 2,900-request day reads 3,000; a near-empty + * series still gets an integer axis). + * measuredRuns(vals) contiguous non-null index runs. A NULL metric + * renders as a GAP, never a zero, and the line + * is never drawn through unmeasured history. + * chartFrame(cfg) opens the SVG, draws gridlines + y labels + * (top = one round step x 4 ticks, so labels + * land on round numbers by construction). + * dateMarks(fr, days) 3 x-axis date labels (start/mid/end). + * drawBars(fr, vals, opts) bars; NULLs skipped (no zero bars). + * drawLineRuns(fr, vals, opts) lines broken into measured runs. + * hoverTargets(fr, vals, host) transparent hover circles on measured points. + */ +(function (global) { + "use strict"; + + // HTML escaping, self-contained: identical mapping to both apps' esc() / + // escapeHtml(), so tooltip output bytes match what each app rendered before. + function esc(s) { + return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); + } + + // ---- Chart tooltips: exact values on hover ---- + const chartTipData = {}; // hostId -> [{ label, series: [[name, value], ...] }] + let chartTipBox = null; // the singleton tooltip div, created on first use + let chartTipCur = null; // { host, idx } the point currently shown + + function registerChartTips(hostId, points) { chartTipData[hostId] = points; } + + function chartTipTarget(el) { + return el && el.closest ? el.closest("[data-tip-host]") : null; + } + + function hideChartTip() { + chartTipCur = null; + if (chartTipBox) chartTipBox.style.display = "none"; + } + + function showChartTip(hostId, idx, cx, cy) { + const p = (chartTipData[hostId] || [])[idx]; + if (!p) { hideChartTip(); return; } + if (!chartTipBox) { + chartTipBox = global.document.createElement("div"); + chartTipBox.className = "chart-tip"; + global.document.body.appendChild(chartTipBox); + } + const same = chartTipCur && chartTipCur.host === hostId && chartTipCur.idx === idx; + if (!same) { + let html = '
' + esc(p.label) + "
"; + for (let s = 0; s < p.series.length; s++) { + html += '
' + esc(p.series[s][0]) + "" + esc(p.series[s][1]) + "
"; + } + chartTipBox.innerHTML = html; + chartTipCur = { host: hostId, idx: idx }; + } + chartTipBox.style.display = "block"; + moveChartTip(cx, cy); + } + + // Position beside the pointer, flipped/clamped so the box stays fully inside + // the viewport at chart edges. + function moveChartTip(cx, cy) { + if (!chartTipBox || chartTipBox.style.display === "none") return; + const pad = 12, m = 4; + const w = chartTipBox.offsetWidth, h = chartTipBox.offsetHeight; + let x = cx + pad, y = cy + pad; + if (x + w > window.innerWidth - m) x = cx - pad - w; + if (x < m) x = m; + if (y + h > window.innerHeight - m) y = cy - pad - h; + if (y < m) y = m; + chartTipBox.style.left = x + "px"; + chartTipBox.style.top = y + "px"; + } + + document.addEventListener("pointerover", (e) => { + const t = chartTipTarget(e.target); + if (!t) return; + showChartTip(t.getAttribute("data-tip-host"), parseInt(t.getAttribute("data-tip-i"), 10), e.clientX, e.clientY); + }); + document.addEventListener("pointermove", (e) => { + const t = chartTipTarget(e.target); + if (!t) return; + const host = t.getAttribute("data-tip-host"); + const idx = parseInt(t.getAttribute("data-tip-i"), 10); + const cur = chartTipCur; + if (!cur || cur.host !== host || cur.idx !== idx) showChartTip(host, idx, e.clientX, e.clientY); + else moveChartTip(e.clientX, e.clientY); + }); + document.addEventListener("pointerout", (e) => { + const from = chartTipTarget(e.target); + if (!from) return; + const to = e.relatedTarget ? chartTipTarget(e.relatedTarget) : null; + if (!to || to.getAttribute("data-tip-host") !== from.getAttribute("data-tip-host")) hideChartTip(); + }); + // Basic touch: tap/drag shows and follows, release hides it after a beat. + document.addEventListener("pointerup", (e) => { + if (e.pointerType === "touch") setTimeout(hideChartTip, 1600); + }); + document.addEventListener("pointercancel", hideChartTip); + // Scrolling or resizing moves the chart under a fixed-position box - hide + // rather than show a tooltip for the wrong point. + window.addEventListener("scroll", hideChartTip, { passive: true }); + window.addEventListener("resize", hideChartTip); + + // ---- Axis step (see header: continuous vs count rule) ---- + function niceStep(raw, continuous) { + if (continuous) { + const mag = Math.pow(10, Math.floor(Math.log10(Math.max(raw, 1e-9)))); + const norm = raw / mag; + const nice = norm <= 1 ? 1 : (norm <= 2 ? 2 : (norm <= 5 ? 5 : 10)); + return nice * mag; + } + const p = Math.pow(10, Math.floor(Math.log10(Math.max(raw, 1)))); + return Math.max(1, Math.ceil(raw / (p / 2)) * (p / 2)); + } + + // ---- Contiguous measured runs: a NULL day stays a gap ---- + function measuredRuns(vals) { + const runs = []; + let run = []; + for (let i = 0; i < vals.length; i++) { + if (vals[i] === null || vals[i] === undefined) { if (run.length) runs.push(run); run = []; } + else run.push(i); + } + if (run.length) runs.push(run); + return runs; + } + + // ---- Frame: opens the SVG, draws gridlines + y-tick labels ---- + // cfg: { n, top, step, tickLabel(v)->string, aria, W, H, padL, padR, padT, + // padB, gridStroke }. Defaults match the panel's chart geometry + // (W 1000, H 250, padL 62, padR 14, padT 14, padB 30). + // Axis top = one round step times four ticks: labels land on round numbers + // and the peak still clears the frame. + function chartFrame(cfg) { + const W = cfg.W || 1000, H = cfg.H || 250; + const padL = cfg.padL === undefined ? 62 : cfg.padL; + const padR = cfg.padR === undefined ? 14 : cfg.padR; + const padT = cfg.padT === undefined ? 14 : cfg.padT; + const padB = cfg.padB === undefined ? 30 : cfg.padB; + const plotW = W - padL - padR, plotH = H - padT - padB; + const baseY = padT + plotH; + const n = cfg.n; + const xAt = i => padL + (n <= 1 ? plotW / 2 : (plotW * i) / (n - 1)); + const yAt = v => baseY - (plotH * v) / cfg.top; + const parts = []; + parts.push(''); + for (let g = 0; g <= 4; g++) { + const yy = baseY - (plotH * g) / 4; + parts.push(''); + parts.push('' + cfg.tickLabel(cfg.step * g) + ''); + } + return { W, H, padL, padR, baseY, n, xAt, yAt, parts }; + } + + // ---- X-axis date marks: start / middle / end, day strings YYYY-MM-DD ---- + function dateMarks(fr, days) { + const marks = fr.n > 2 ? [0, Math.floor((fr.n - 1) / 2), fr.n - 1] : [0, fr.n - 1]; + for (let mi = 0; mi < marks.length; mi++) { + const i = marks[mi]; + const anchor = mi === 0 ? "start" : (mi === marks.length - 1 ? "end" : "middle"); + fr.parts.push('' + String(days[i]).slice(5) + ''); + } + } + + // ---- Bars. opts: { color, host } — host stamps the elements for tooltips. + // NULL values are skipped (no zero bars, no tooltip on an unmeasured day). + function drawBars(fr, vals, opts) { + const bw = Math.max(1, (fr.W - fr.padL - fr.padR) / fr.n - 1); + for (let i = 0; i < fr.n; i++) { + const v = vals[i]; + if (v === null || v === undefined) continue; + const yy = fr.yAt(v); + fr.parts.push('"); + } + } + + // ---- Lines broken into contiguous measured runs. opts: + // color stroke (and default fill for single-point dots) + // area draw the fill-under-line area path (panel Trends style) + // areaColor / areaOpacity area fill override (defaults: color / 0.10) + // dotSingle draw a dot (r = dotR, default 3) for a 1-point run instead of + // nothing — a single measured day still shows (money style) + function drawLineRuns(fr, vals, opts) { + const runs = measuredRuns(vals); + for (let s = 0; s < runs.length; s++) { + const r0 = runs[s]; + if (opts.area) { + fr.parts.push(' fr.xAt(i) + "," + fr.yAt(vals[i])).join(" L") + " L" + fr.xAt(r0[r0.length - 1]) + "," + fr.baseY + ' Z" fill="' + (opts.areaColor || opts.color) + '" fill-opacity="' + (opts.areaOpacity === undefined ? "0.10" : opts.areaOpacity) + '"/>'); + } + if (r0.length > 1 || opts.area) { + fr.parts.push(''); + } else if (opts.dotSingle) { + // A single measured day (e.g. the first balance snapshot) still shows. + fr.parts.push(''); + } + } + } + + // ---- Hover targets: one transparent circle per measured point; the + // tooltip lists every series at that x. NULL points get no stamp. + function hoverTargets(fr, vals, host) { + for (let i = 0; i < fr.n; i++) { + const v = vals[i]; + if (v === null || v === undefined) continue; + fr.parts.push(''); + } + } + + // chartTipData is exported for inspection (harnesses assert on the exact + // registered points); treat it as read-only in page code. + global.CoOpChart = { + chartTipData, + registerChartTips, + chartTipTarget, + hideChartTip, + showChartTip, + moveChartTip, + niceStep, + measuredRuns, + chartFrame, + dateMarks, + drawBars, + drawLineRuns, + hoverTargets + }; +})(typeof globalThis !== "undefined" ? globalThis : window); diff --git a/scripts/sync-chart-module.sh b/scripts/sync-chart-module.sh new file mode 100755 index 0000000..328b437 --- /dev/null +++ b/scripts/sync-chart-module.sh @@ -0,0 +1,116 @@ +#!/usr/bin/env bash +# Sync the shared chart module to both thin apps, and re-pin them. +# +# ops-docs/scripts/sync-chart-module.sh +# +# The canonical module is scripts/shared/coop_chart.js in THIS repo. The two +# consumer repos (member-dashboard, admin-panel) ship BYTE-IDENTICAL copies at +# app/coop_chart.js; each app's main.py splices it into PAGE_HTML at import +# time. Editing a copy by hand is a dead end: this script overwrites it, and +# the repo's tests/test_chart_sync.py goes red on any drift from the pinned +# revision. +# +# What this does: +# 1. copies the canonical module over both repos' app/coop_chart.js +# 2. regenerates each repo's tests/test_chart_sync.py with the CURRENT +# canonical sha256 (the pin CI checks, since CI has no ops-docs checkout) +# 3. node --check's the module +# 4. runs check-chart-sync.py as the gate — a red check leaves the working +# tree dirty so nothing can be silently committed half-synced +# +# After it passes: commit all three repos (ops-docs + both apps). +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPOS="$(dirname "$(dirname "$HERE")")" # ops-docs/scripts -> ops-docs -> ~/repos +CANONICAL="$HERE/shared/coop_chart.js" + +[ -f "$CANONICAL" ] || { echo "canonical module missing: $CANONICAL" >&2; exit 1; } + +if command -v node >/dev/null 2>&1; then + node --check "$CANONICAL" && echo "node --check canonical: OK" +else + echo "node not found; skipping node --check (CI runs it)" >&2 +fi + +SHA="$(sha256sum "$CANONICAL" | cut -d' ' -f1)" +echo "canonical sha256: $SHA" + +gen_pin_test() { # + local repo="$1" + local dir="$REPOS/$repo" + mkdir -p "$dir/tests" + cat > "$dir/tests/test_chart_sync.py" < $repo/app/coop_chart.js" +done + +python3 "$HERE/check-chart-sync.py"