Public: anyone can read this; the crew can change it.

Boards: Grafana-like dashboards inside the forge — every admin-visible table is a queryable source, editable panels (line, bar, area, number, table, heat), saved boards in git, starting boards for throughput, usage, crew, releases, apps and security #1578

Closed opened this in answer to
Closed without merging

torque/forge:torque/1557-boards-grafana-like-dashboards-inside-th → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
14 files changed +1775 −0
README.md +23
@@ -455,6 +455,29 @@ not as a crew run; AWS audits look at us-east-1 only; over-provisioned
455455 droplets and forgotten DNS records need metrics or resolution and are not
456456 attempted; Backblaze audits find nothing yet. No dependency was added.
457457
458 ## Boards
459
460 **Settings → Boards** (`/boards/data`, admins who are people) treats every
461 table an admin can see as a source: runs, deploys, pulls, reviews, apps,
462 awake (each app's wake-to-sleep stretch), capacity, ledger, spend, crew,
463 sessions, tokens and audit. Each source lists its columns. A panel is one
464 query: a range (the last 1 h to 30 d, or `from`/`to` in the URL), up to
465 eight filters written as `column:op:value` (op is `eq`, `ne`, `gt`, `lt` or
466 `has`), an x axis (a minute, hour or day bucket in UTC, or a column), an
467 optional split, and one aggregate (`count`, `sum`, `avg`, `p50`, `p95`,
468 `max`). It is drawn as a line, bar, stacked area, number with sparkline,
469 table or heat strip. The forge draws the SVG on the server, with no chart
470 library. Changing a select redraws the chart. The URL holds the whole
471 panel, so a link shares it. Every point links to the rows behind it, and
472 those rows come as a page, as CSV (formula characters defused) and as JSON
473 (`GET /api/v1/boards/sources`, `GET|POST /api/v1/boards/query`,
474 `GET /api/v1/boards/rows`). Percentiles are nearest-rank, so a p95 is
475 always a value that occurred. No secret or sealed value is ever returned:
476 password, token and session hashes, sealed values (`*_enc`), a sealed
477 pull's title (it reads `(sealed)`) and event payloads are withheld, and
478 each source names what it withholds. An agent gets 403 whatever its
479 token's scope; anyone else who is not an admin gets 404.
480
458481 ## Share to the forge
459482
460483 Install the forge to your home screen, then Share a link or text to it from
scripts/gate.ts +1
@@ -88,6 +88,7 @@ export const GATE: readonly string[] = [
8888 "test/decide.test.ts",
8989 "test/ledger.test.ts",
9090 "test/capacity.test.ts",
91 "test/boards.test.ts",
9192 "test/guard-new-accounts.test.ts",
9293 "test/checks.test.ts",
9394 "test/dependencies.test.ts",
src/actions/boards.ts added +59
@@ -0,0 +1,59 @@
1 /**
2 * Boards' reads (#1557): every source, a query over one, the rows behind a
3 * point. A forge admin who is a person reads them; an agent is refused
4 * outright (`forbidden`) whatever it was granted — the crew does not get to
5 * watch the forge it works in — and anyone else is told `not_found`, never
6 * that the door exists. Nothing here writes, so nothing appends an event.
7 */
8
9 import type { App } from "../app.ts";
10 import { catalogue } from "../boards/sources.ts";
11 import {
12 parseQuery,
13 queryRows,
14 runQuery,
15 type Query,
16 type QueryResult,
17 } from "../boards/query.ts";
18 import type { User } from "../core/users.ts";
19 import { err, ok, type Result } from "../kernel/result.ts";
20
21 export type BoardsDenied = "forbidden" | "not_found";
22
23 function reader(actor: User | undefined): Result<User, BoardsDenied> {
24 if (actor?.kind === "agent") return err("forbidden");
25 return actor?.isAdmin === true ? ok(actor) : err("not_found");
26 }
27
28 export function boardSources(
29 _app: App,
30 actor: User | undefined,
31 ): Result<ReturnType<typeof catalogue>, BoardsDenied> {
32 const who = reader(actor);
33 return who.ok ? ok(catalogue()) : who;
34 }
35
36 export function boardQuery(
37 app: App,
38 actor: User | undefined,
39 input: Record<string, unknown>,
40 ): Result<{ query: Query; result: QueryResult }, BoardsDenied | string> {
41 const who = reader(actor);
42 if (!who.ok) return who;
43 const q = parseQuery(input);
44 if (!q.ok) return q;
45 return ok({ query: q.value, result: runQuery(app.db, q.value) });
46 }
47
48 export function boardRows(
49 app: App,
50 actor: User | undefined,
51 input: Record<string, unknown>,
52 point: { x?: string; series?: string } = {},
53 ): Result<{ query: Query } & ReturnType<typeof queryRows>, BoardsDenied | string> {
54 const who = reader(actor);
55 if (!who.ok) return who;
56 const q = parseQuery(input);
57 if (!q.ok) return q;
58 return ok({ query: q.value, ...queryRows(app.db, q.value, point) });
59 }
src/boards/charts.ts added +270
@@ -0,0 +1,270 @@
1 /**
2 * A panel's chart, drawn by the forge as inline SVG (#1557) — no chart
3 * library, the same way `web/og/card.ts` draws its cards. A pure function
4 * from a query's result to markup: every text goes through the `html` tag,
5 * so a series named `<script>` is drawn as those characters; numbers are
6 * the only thing placed raw, and they are numbers.
7 *
8 * Every point links to the rows behind it (`href(x, series)`): a circle or
9 * a bar or a heat cell for that one cell, and a full-height column per x
10 * for everything at that x, so even a dense line is one click from its rows.
11 */
12
13 import { html, type Html } from "../web/html.ts";
14 import type { QueryResult } from "./query.ts";
15
16 export const CHARTS = ["line", "bar", "area", "number", "table", "heat"] as const;
17 export type Chart = (typeof CHARTS)[number];
18
19 export const CHART_WORDS: Readonly<Record<Chart, string>> = {
20 line: "Line",
21 bar: "Bar",
22 area: "Stacked area",
23 number: "Number",
24 table: "Table",
25 heat: "Heat strip",
26 };
27
28 /** Rows behind an x value and, when given, one series. */
29 export type HrefFor = (x: string, series?: string) => string;
30
31 const W = 640;
32 const H = 220;
33 const L = 52;
34 const R = 10;
35 const T = 10;
36 const B = 24;
37 const PW = W - L - R;
38 const PH = H - T - B;
39 /** Above this many points, circles give way to the per-x columns alone. */
40 const DOT_CAP = 600;
41 const PALETTE = 8;
42
43 /** A number as a person reads it: whole numbers grouped, others 4 digits. */
44 export function fmt(n: number | null): string {
45 if (n === null || !Number.isFinite(n)) return "–";
46 if (Number.isInteger(n)) return n.toLocaleString("en-US");
47 const a = Math.abs(n);
48 return a >= 1000 ? Math.round(n).toLocaleString("en-US") : String(Number(n.toPrecision(4)));
49 }
50
51 /** An x value as a short label: a time bucket loses what it does not need. */
52 export function xLabel(x: string): string {
53 const m = /^(\d{4}-\d\d-\d\d)T(\d\d:\d\d):00\.000Z$/.exec(x);
54 if (!m) return x === "" ? "(none)" : x;
55 return m[2] === "00:00" ? m[1]! : `${m[1]!.slice(5)} ${m[2]}`;
56 }
57
58 /** A round-ish top for the y axis: 1, 2 or 5 times a power of ten. */
59 export function niceMax(v: number): number {
60 if (!(v > 0)) return 1;
61 const p = 10 ** Math.floor(Math.log10(v));
62 for (const m of [1, 2, 5, 10]) if (m * p >= v) return m * p;
63 return 10 * p;
64 }
65
66 const r1 = (n: number): string => String(Math.round(n * 10) / 10);
67
68 function frame(max: number, xs: readonly string[], body: Html, title: string): Html {
69 const ticks = [0, max / 2, max];
70 const xi = xs.length <= 1 ? [0] : [0, Math.floor((xs.length - 1) / 2), xs.length - 1];
71 const xAt = (i: number): number =>
72 L + (xs.length <= 1 ? PW / 2 : ((i + 0.5) / xs.length) * PW);
73 return html`<svg class="bd-chart" viewBox="0 0 ${String(W)} ${String(H)}" role="img" aria-label="${title}">
74 ${ticks.map(
75 (t) => html`<line class="bd-grid" x1="${String(L)}" x2="${String(W - R)}" y1="${r1(T + PH - (t / max) * PH)}" y2="${r1(T + PH - (t / max) * PH)}" />
76 <text class="bd-tick" x="${String(L - 6)}" y="${r1(T + PH - (t / max) * PH + 4)}" text-anchor="end">${fmt(t)}</text>`,
77 )}
78 ${[...new Set(xi)].map(
79 (i) => html`<text class="bd-tick" x="${r1(xAt(i))}" y="${String(H - 6)}" text-anchor="middle">${xLabel(xs[i] ?? "")}</text>`,
80 )}
81 ${body}
82 </svg>`;
83 }
84
85 /** One transparent column per x: the rows behind everything at that x. */
86 function columns(res: QueryResult, href: HrefFor): Html {
87 const w = PW / Math.max(1, res.xs.length);
88 return html`${res.xs.map(
89 (x, i) => html`<a href="${href(x)}"><rect class="bd-hit" x="${r1(L + i * w)}" y="${String(T)}" width="${r1(w)}" height="${String(PH)}"><title>${xLabel(x)}: ${res.series
90 .map((s) => `${s.name} ${fmt(s.values[i] ?? null)}`)
91 .join(", ")}</title></rect></a>`,
92 )}`;
93 }
94
95 function legend(res: QueryResult): Html {
96 if (res.series.length <= 1) return html``;
97 return html`<ul class="bd-legend">
98 ${res.series.map(
99 (s, i) => html`<li><span class="bd-key bd-s${String(i % PALETTE)}"></span>${s.name === "" ? "(none)" : s.name}</li>`,
100 )}
101 </ul>`;
102 }
103
104 function line(res: QueryResult, href: HrefFor, title: string): Html {
105 const max = niceMax(Math.max(0, ...res.series.flatMap((s) => s.values.map((v) => v ?? 0))));
106 const n = res.xs.length;
107 const xAt = (i: number): number => L + (n <= 1 ? PW / 2 : ((i + 0.5) / n) * PW);
108 const yAt = (v: number): number => T + PH - (v / max) * PH;
109 const dots = n * res.series.length <= DOT_CAP;
110 const body = html`${columns(res, href)}
111 ${res.series.map((s, si) => {
112 // A null is a gap, not a zero: the line breaks there.
113 const runs: string[] = [];
114 let cur: string[] = [];
115 s.values.forEach((v, i) => {
116 if (v === null) {
117 if (cur.length) runs.push(cur.join(" "));
118 cur = [];
119 } else cur.push(`${r1(xAt(i))},${r1(yAt(v))}`);
120 });
121 if (cur.length) runs.push(cur.join(" "));
122 return html`<g class="bd-s${String(si % PALETTE)}">
123 ${runs.map((pts) => html`<polyline class="bd-line" points="${pts}" />`)}
124 ${dots
125 ? s.values.map((v, i) =>
126 v === null
127 ? html``
128 : html`<a href="${href(res.xs[i]!, s.name)}"><circle class="bd-dot" cx="${r1(xAt(i))}" cy="${r1(yAt(v))}" r="3"><title>${s.name} · ${xLabel(res.xs[i]!)}: ${fmt(v)}</title></circle></a>`,
129 )
130 : html``}
131 </g>`;
132 })}`;
133 return html`${frame(max, res.xs, body, title)}${legend(res)}`;
134 }
135
136 function area(res: QueryResult, href: HrefFor, title: string): Html {
137 const n = res.xs.length;
138 const stack = res.series.map(() => new Array<number>(n).fill(0));
139 res.series.forEach((s, si) =>
140 s.values.forEach((v, i) => {
141 stack[si]![i] = (si > 0 ? stack[si - 1]![i]! : 0) + (v ?? 0);
142 }),
143 );
144 const top = stack[stack.length - 1] ?? [];
145 const max = niceMax(Math.max(0, ...top));
146 const xAt = (i: number): number => L + (n <= 1 ? PW / 2 : ((i + 0.5) / n) * PW);
147 const yAt = (v: number): number => T + PH - (v / max) * PH;
148 const body = html`${columns(res, href)}
149 ${res.series.map((s, si) => {
150 const upper = stack[si]!.map((v, i) => `${r1(xAt(i))},${r1(yAt(v))}`);
151 const lower = (si > 0 ? stack[si - 1]! : new Array<number>(n).fill(0))
152 .map((v, i) => `${r1(xAt(i))},${r1(yAt(v))}`)
153 .reverse();
154 return html`<g class="bd-s${String(si % PALETTE)}">
155 <polygon class="bd-area" points="${[...upper, ...lower].join(" ")}"><title>${s.name}</title></polygon>
156 <polyline class="bd-line" points="${upper.join(" ")}" />
157 </g>`;
158 })}`;
159 return html`${frame(max, res.xs, body, title)}${legend(res)}`;
160 }
161
162 function bar(res: QueryResult, href: HrefFor, title: string): Html {
163 const max = niceMax(Math.max(0, ...res.series.flatMap((s) => s.values.map((v) => v ?? 0))));
164 const n = Math.max(1, res.xs.length);
165 const slot = PW / n;
166 const k = Math.max(1, res.series.length);
167 const bw = Math.max(1, (slot * 0.8) / k);
168 const body = html`${res.series.map(
169 (s, si) => html`<g class="bd-s${String(si % PALETTE)}">
170 ${s.values.map((v, i) => {
171 const h = ((v ?? 0) / max) * PH;
172 return html`<a href="${href(res.xs[i]!, s.name)}"><rect class="bd-bar" x="${r1(L + i * slot + slot * 0.1 + si * bw)}" y="${r1(T + PH - h)}" width="${r1(bw)}" height="${r1(h)}"><title>${s.name} · ${xLabel(res.xs[i]!)}: ${fmt(v)}</title></rect></a>`;
173 })}
174 </g>`,
175 )}`;
176 return html`${frame(max, res.xs, body, title)}${legend(res)}`;
177 }
178
179 function heat(res: QueryResult, href: HrefFor, title: string): Html {
180 const rowH = 18;
181 const n = Math.max(1, res.xs.length);
182 const cw = PW / n;
183 const h = T + res.series.length * rowH + B;
184 const max = Math.max(0, ...res.series.flatMap((s) => s.values.map((v) => v ?? 0)));
185 // Five steps, 0 for an empty cell: the strip reads as density, not value.
186 const level = (v: number | null): number =>
187 v === null || v <= 0 || max <= 0 ? 0 : Math.min(4, Math.ceil((v / max) * 4));
188 return html`<svg class="bd-chart" viewBox="0 0 ${String(W)} ${String(h)}" role="img" aria-label="${title}">
189 ${res.series.map(
190 (s, si) => html`<text class="bd-tick" x="${String(L - 6)}" y="${String(T + si * rowH + 13)}" text-anchor="end">${s.name === "" ? "(none)" : s.name.slice(0, 10)}</text>
191 ${s.values.map(
192 (v, i) => html`<a href="${href(res.xs[i]!, s.name)}"><rect class="bd-heat" data-l="${String(level(v))}" x="${r1(L + i * cw)}" y="${String(T + si * rowH)}" width="${r1(Math.max(1, cw - 1))}" height="${String(rowH - 2)}"><title>${s.name} · ${xLabel(res.xs[i]!)}: ${fmt(v)}</title></rect></a>`,
193 )}`,
194 )}
195 ${[0, res.xs.length - 1].filter((i, k, a) => i >= 0 && a.indexOf(i) === k).map(
196 (i) => html`<text class="bd-tick" x="${r1(L + (i + 0.5) * cw)}" y="${String(h - 6)}" text-anchor="middle">${xLabel(res.xs[i] ?? "")}</text>`,
197 )}
198 </svg>`;
199 }
200
201 function number(res: QueryResult, title: string): Html {
202 // The sparkline sums the series at each x; the number is the whole range.
203 const n = res.xs.length;
204 const sums = res.xs.map((_, i) => res.series.reduce((a, s) => a + (s.values[i] ?? 0), 0));
205 const max = Math.max(0, ...sums) || 1;
206 const pts = sums
207 .map((v, i) => `${r1(n <= 1 ? 100 : (i / (n - 1)) * 200)},${r1(38 - (v / max) * 36)}`)
208 .join(" ");
209 return html`<div class="bd-number">
210 <b class="num">${fmt(res.total)}</b>
211 <svg class="bd-spark bd-s0" viewBox="0 0 200 40" role="img" aria-label="${title}, over the range"><polyline class="bd-line" points="${pts}" /></svg>
212 </div>`;
213 }
214
215 function table(res: QueryResult, href: HrefFor): Html {
216 return html`<div class="bd-table-wrap"><table class="table bd-table">
217 <thead><tr><th scope="col">x</th>${res.series.map((s) => html`<th scope="col" class="num">${s.name === "" ? "(none)" : s.name}</th>`)}</tr></thead>
218 <tbody>
219 ${res.xs.map(
220 (x, i) => html`<tr><th scope="row"><a href="${href(x)}">${xLabel(x)}</a></th>${res.series.map(
221 (s) => html`<td class="num"><a href="${href(x, s.name)}">${fmt(s.values[i] ?? null)}</a></td>`,
222 )}</tr>`,
223 )}
224 </tbody>
225 </table></div>`;
226 }
227
228 /** A panel's chart, from its result. `title` names it for a screen reader. */
229 export function drawChart(chart: Chart, res: QueryResult, href: HrefFor, title: string): Html {
230 if (res.xs.length === 0 && chart !== "number")
231 return html`<p class="muted small bd-empty">No rows in this range.</p>`;
232 if (chart === "line") return line(res, href, title);
233 if (chart === "area") return area(res, href, title);
234 if (chart === "bar") return bar(res, href, title);
235 if (chart === "heat") return heat(res, href, title);
236 if (chart === "number") return number(res, title);
237 return table(res, href);
238 }
239
240 const HUES = ["accent", "success", "merged", "attn", "danger", "primary", "muted-fg", "fg"];
241
242 export const chartCss = /* css */ `
243 @layer components {
244 .bd-panel { display: flex; flex-direction: column; gap: 8px; }
245 .bd-chart { width: 100%; height: auto; display: block; }
246 .bd-grid { stroke: var(--border); stroke-width: 1; }
247 .bd-tick { fill: var(--muted-fg); font-size: 11px; font-family: var(--mono); }
248 .bd-hit { fill: transparent; }
249 .bd-hit:hover { fill: var(--muted); }
250 .bd-line { fill: none; stroke-width: 2; stroke-linejoin: round; }
251 .bd-area { fill-opacity: 0.35; stroke: none; }
252 .bd-dot { stroke: var(--card); stroke-width: 1; }
253 .bd-bar:hover, .bd-heat:hover, .bd-dot:hover { opacity: 0.75; }
254 .bd-heat { fill: var(--accent); }
255 .bd-heat[data-l="0"] { fill: var(--muted); }
256 .bd-heat[data-l="1"] { fill-opacity: 0.3; }
257 .bd-heat[data-l="2"] { fill-opacity: 0.5; }
258 .bd-heat[data-l="3"] { fill-opacity: 0.75; }
259 .bd-legend { display: flex; flex-wrap: wrap; gap: 4px 14px; list-style: none; margin: 0; padding: 0; font-size: 12px; color: var(--muted-fg); }
260 .bd-key { display: inline-block; width: 10px; height: 10px; border-radius: 2px; margin-right: 6px; vertical-align: -1px; background: currentColor; }
261 .bd-number { display: flex; align-items: center; gap: 18px; }
262 .bd-number b { font-size: 40px; letter-spacing: -0.03em; }
263 .bd-spark { width: 200px; height: 40px; }
264 .bd-table-wrap { max-height: 360px; overflow: auto; }
265 ${HUES.map(
266 (h, i) =>
267 `.bd-s${i} { color: var(--${h}); } .bd-s${i} .bd-line, .bd-s${i}.bd-spark .bd-line { stroke: var(--${h}); } .bd-s${i} .bd-area, .bd-s${i} .bd-dot, .bd-s${i} .bd-bar { fill: var(--${h}); }`,
268 ).join("\n")}
269 }
270 `;
src/boards/query.ts added +369
@@ -0,0 +1,369 @@
1 /**
2 * A board's query (#1557): one source, a time range, filters, an x axis (a
3 * time bucket or a column), an optional series split, and one aggregate.
4 * `parseQuery` is the boundary — anything from a URL, a form or a JSON body
5 * comes through it — and `runQuery` reads the rows once, with every value
6 * a bound parameter and every column from the source's allowlist, then
7 * aggregates exactly in memory: SQLite has no percentile, and one pass
8 * over at most `ROW_CAP` rows is well under the page's budget.
9 *
10 * Percentiles are nearest-rank (NIST/Hyndman–Fan definition 1): the p-th
11 * percentile of n sorted values is the value at rank ⌈p/100 · n⌉, so it is
12 * always a value that occurred, and p50 of [1,2,3,4] is 2.
13 */
14
15 import type { Database } from "bun:sqlite";
16 import { err, ok, type Result } from "../kernel/result.ts";
17 import { columnOf, sourceNamed, type Column, type Source } from "./sources.ts";
18
19 export const BUCKETS = { minute: 60_000, hour: 3_600_000, day: 86_400_000 } as const;
20 export type Bucket = keyof typeof BUCKETS;
21 export const AGGS = ["count", "sum", "avg", "p50", "p95", "max"] as const;
22 export type Agg = (typeof AGGS)[number];
23 export const OPS = ["eq", "ne", "gt", "lt", "has"] as const;
24 export type Op = (typeof OPS)[number];
25 export const LASTS = { "1h": 3_600_000, "6h": 21_600_000, "24h": 86_400_000, "7d": 604_800_000, "30d": 2_592_000_000 } as const;
26 export type Last = keyof typeof LASTS;
27
28 /** More rows than this and the result says it was cut. */
29 export const ROW_CAP = 200_000;
30 /** More x values than this is not a chart anyone can read. */
31 export const X_CAP = 1_500;
32 /** More series than this folds the rest into "other". */
33 export const SERIES_CAP = 12;
34
35 export interface Filter {
36 readonly column: string;
37 readonly op: Op;
38 readonly value: string;
39 }
40
41 export interface Query {
42 readonly source: string;
43 /** Epoch ms, inclusive. */
44 readonly from: number;
45 /** Epoch ms, exclusive. */
46 readonly to: number;
47 readonly where: readonly Filter[];
48 /** A time bucket, or a column whose values are the x axis. */
49 readonly x: { readonly bucket: Bucket } | { readonly column: string };
50 readonly series?: string;
51 readonly agg: Agg;
52 /** The number column the aggregate reads; unused by count. */
53 readonly of?: string;
54 }
55
56 export interface Series {
57 readonly name: string;
58 /** One per x; null where no row fell (avg, percentiles, max). */
59 readonly values: readonly (number | null)[];
60 /** How many rows are behind each value. */
61 readonly counts: readonly number[];
62 }
63
64 export interface QueryResult {
65 readonly xs: readonly string[];
66 readonly series: readonly Series[];
67 /** The aggregate over every row in range, across all series. */
68 readonly total: number | null;
69 readonly rows: number;
70 readonly truncated: boolean;
71 }
72
73 const isOneOf = <T extends string>(list: readonly T[], v: unknown): v is T =>
74 typeof v === "string" && (list as readonly string[]).includes(v);
75
76 const MAX_RANGE = 400 * 86_400_000;
77 const str = (v: unknown): string | undefined =>
78 typeof v === "string" && v.length <= 200 ? v : undefined;
79
80 function time(v: unknown): number | undefined {
81 if (typeof v === "number" && Number.isFinite(v)) return v;
82 const s = str(v);
83 if (s === undefined || s === "") return undefined;
84 const t = Date.parse(s);
85 return Number.isFinite(t) ? t : undefined;
86 }
87
88 /**
89 * Validate a query from anywhere. `now` anchors a `last` range. Errors are
90 * short codes a page and the API both say.
91 */
92 export function parseQuery(
93 input: Record<string, unknown>,
94 now = Date.now(),
95 ): Result<Query, string> {
96 const source = sourceNamed(str(input.source) ?? "");
97 if (!source) return err("no_such_source");
98 let from: number | undefined;
99 let to: number | undefined;
100 if (input.last !== undefined && input.last !== "") {
101 if (!isOneOf(Object.keys(LASTS) as Last[], input.last)) return err("bad_range");
102 to = now;
103 from = now - LASTS[input.last];
104 } else {
105 from = time(input.from);
106 to = time(input.to) ?? now;
107 }
108 if (from === undefined || to === undefined || !(from < to) || to - from > MAX_RANGE)
109 return err("bad_range");
110
111 const rawWhere = Array.isArray(input.where) ? input.where : [];
112 if (rawWhere.length > 8) return err("too_many_filters");
113 const where: Filter[] = [];
114 for (const f of rawWhere) {
115 if (typeof f !== "object" || f === null) return err("bad_filter");
116 const r = f as Record<string, unknown>;
117 const col = columnOf(source, str(r.column) ?? "");
118 const value = str(r.value);
119 if (!col || !isOneOf(OPS, r.op) || value === undefined) return err("bad_filter");
120 if (col.type === "number" && r.op !== "has" && !Number.isFinite(Number(value)))
121 return err("bad_filter");
122 where.push({ column: col.name, op: r.op, value });
123 }
124
125 let x: Query["x"];
126 const xs = str(input.x) ?? "hour";
127 if (isOneOf(Object.keys(BUCKETS) as Bucket[], xs)) {
128 if ((to - from) / BUCKETS[xs] > X_CAP) return err("too_many_buckets");
129 x = { bucket: xs };
130 } else if (columnOf(source, xs)) x = { column: xs };
131 else return err("bad_x");
132
133 const seriesName = str(input.series) ?? "";
134 if (seriesName !== "" && !columnOf(source, seriesName)) return err("bad_series");
135
136 const agg = input.agg === undefined || input.agg === "" ? "count" : input.agg;
137 if (!isOneOf(AGGS, agg)) return err("bad_agg");
138 const ofName = str(input.of) ?? "";
139 if (agg !== "count") {
140 const of = columnOf(source, ofName);
141 if (!of || of.type !== "number") return err("bad_of");
142 }
143 return ok({
144 source: source.name,
145 from,
146 to,
147 where,
148 x,
149 ...(seriesName === "" ? {} : { series: seriesName }),
150 agg,
151 ...(agg === "count" || ofName === "" ? {} : { of: ofName }),
152 });
153 }
154
155 /** Floor an epoch ms to its bucket's start, in UTC. */
156 export const floorTo = (t: number, b: Bucket): number =>
157 Math.floor(t / BUCKETS[b]) * BUCKETS[b];
158
159 /** The bound WHERE for a query, plus an optional narrowing to one point. */
160 function whereOf(
161 source: Source,
162 q: Query,
163 point?: { x?: string; series?: string },
164 ): { sql: string; params: (string | number)[] } {
165 const parts: string[] = [];
166 const params: (string | number)[] = [];
167 if (source.where !== "") parts.push(`(${source.where})`);
168 let from = q.from;
169 let to = q.to;
170 if (point?.x !== undefined && "bucket" in q.x) {
171 const t = Date.parse(point.x);
172 if (Number.isFinite(t)) {
173 from = Math.max(from, t);
174 to = Math.min(to, t + BUCKETS[q.x.bucket]);
175 }
176 }
177 parts.push(`${source.time} >= ?`, `${source.time} < ?`);
178 params.push(new Date(from).toISOString(), new Date(to).toISOString());
179 for (const f of q.where) {
180 const col = columnOf(source, f.column)!;
181 const v = col.type === "number" && f.op !== "has" ? Number(f.value) : f.value;
182 if (f.op === "eq") parts.push(`${col.sql} = ?`);
183 else if (f.op === "ne") parts.push(`(${col.sql} IS NULL OR ${col.sql} != ?)`);
184 else if (f.op === "gt") parts.push(`${col.sql} > ?`);
185 else if (f.op === "lt") parts.push(`${col.sql} < ?`);
186 else parts.push(`instr(lower(CAST(${col.sql} AS TEXT)), lower(?)) > 0`);
187 params.push(v);
188 }
189 if (point?.x !== undefined && "column" in q.x) {
190 parts.push(`COALESCE(CAST(${columnOf(source, q.x.column)!.sql} AS TEXT), '') = ?`);
191 params.push(point.x);
192 }
193 if (point?.series !== undefined && q.series !== undefined) {
194 parts.push(`COALESCE(CAST(${columnOf(source, q.series)!.sql} AS TEXT), '') = ?`);
195 params.push(point.series);
196 }
197 return { sql: parts.join(" AND "), params };
198 }
199
200 /** Nearest-rank percentile of an ascending array (see the module note). */
201 export function percentile(sorted: readonly number[], p: number): number | null {
202 if (sorted.length === 0) return null;
203 const rank = Math.max(1, Math.ceil((p / 100) * sorted.length));
204 return sorted[rank - 1]!;
205 }
206
207 /** One aggregate over the values that fell in one cell. */
208 export function aggregate(agg: Agg, values: readonly number[], count: number): number | null {
209 if (agg === "count") return count;
210 if (agg === "sum") return values.reduce((a, b) => a + b, 0);
211 if (values.length === 0) return null;
212 if (agg === "avg") return values.reduce((a, b) => a + b, 0) / values.length;
213 if (agg === "max") return values.reduce((a, b) => (b > a ? b : a), -Infinity);
214 const sorted = [...values].sort((a, b) => a - b);
215 return percentile(sorted, agg === "p50" ? 50 : 95);
216 }
217
218 const label = (v: unknown): string => (v === null || v === undefined ? "" : String(v));
219
220 export function runQuery(db: Database, q: Query): QueryResult {
221 const source = sourceNamed(q.source)!;
222 const w = whereOf(source, q);
223 const xCol: Column | undefined = "column" in q.x ? columnOf(source, q.x.column) : undefined;
224 const sCol = q.series === undefined ? undefined : columnOf(source, q.series);
225 const ofCol = q.of === undefined ? undefined : columnOf(source, q.of);
226 const select = [
227 `${source.time} AS t`,
228 xCol ? `${xCol.sql} AS x` : "NULL AS x",
229 sCol ? `${sCol.sql} AS s` : "NULL AS s",
230 ofCol ? `${ofCol.sql} AS v` : "NULL AS v",
231 ].join(", ");
232 const rows = db
233 .query(`SELECT ${select} FROM ${source.from} WHERE ${w.sql} LIMIT ${ROW_CAP + 1}`)
234 .all(...w.params) as { t: string; x: unknown; s: unknown; v: unknown }[];
235 const truncated = rows.length > ROW_CAP;
236 if (truncated) rows.length = ROW_CAP;
237
238 // The x axis: every bucket in range, empty or not; or each value seen.
239 let xs: string[];
240 const xKey: (r: (typeof rows)[number]) => string | undefined =
241 "bucket" in q.x
242 ? ((b: Bucket) => (r) => {
243 const t = Date.parse(r.t);
244 return Number.isFinite(t) ? new Date(floorTo(t, b)).toISOString() : undefined;
245 })(q.x.bucket)
246 : (r) => label(r.x);
247 if ("bucket" in q.x) {
248 xs = [];
249 for (let t = floorTo(q.from, q.x.bucket); t < q.to; t += BUCKETS[q.x.bucket])
250 xs.push(new Date(t).toISOString());
251 } else {
252 const seen = new Map<string, number>();
253 for (const r of rows) {
254 const k = label(r.x);
255 seen.set(k, (seen.get(k) ?? 0) + 1);
256 }
257 xs = [...seen.keys()];
258 if (xCol?.type === "number") xs.sort((a, b) => Number(a) - Number(b));
259 else if (xCol?.type === "time") xs.sort();
260 else xs.sort((a, b) => seen.get(b)! - seen.get(a)! || a.localeCompare(b));
261 xs = xs.slice(0, X_CAP);
262 }
263 const xIndex = new Map(xs.map((x, i) => [x, i]));
264
265 // Series: the biggest by row count, the rest folded into "other".
266 const sCount = new Map<string, number>();
267 for (const r of rows) {
268 const k = sCol ? label(r.s) : "";
269 sCount.set(k, (sCount.get(k) ?? 0) + 1);
270 }
271 const names = [...sCount.keys()].sort(
272 (a, b) => sCount.get(b)! - sCount.get(a)! || a.localeCompare(b),
273 );
274 const kept = names.slice(0, SERIES_CAP);
275 const folded = names.length > SERIES_CAP;
276 if (folded) kept.push("other");
277 if (kept.length === 0) kept.push(sCol ? "" : q.source);
278 const sIndex = new Map(kept.map((s, i) => [s, i]));
279
280 const cells = kept.map(() => xs.map(() => ({ n: 0, v: [] as number[] })));
281 const all: number[] = [];
282 let n = 0;
283 for (const r of rows) {
284 const xi = xIndex.get(xKey(r) ?? "\u0000");
285 if (xi === undefined) continue;
286 const sk = sCol ? label(r.s) : "";
287 const si = sIndex.get(sk) ?? (folded ? kept.length - 1 : sIndex.get(q.source));
288 if (si === undefined) continue;
289 const cell = cells[si]![xi]!;
290 cell.n++;
291 n++;
292 if (typeof r.v === "number" && Number.isFinite(r.v)) {
293 cell.v.push(r.v);
294 all.push(r.v);
295 }
296 }
297 return {
298 xs,
299 series: kept.map((name, si) => ({
300 name: sCol ? name : q.source,
301 values: cells[si]!.map((c) => aggregate(q.agg, c.v, c.n)),
302 counts: cells[si]!.map((c) => c.n),
303 })),
304 total: aggregate(q.agg, all, n),
305 rows: n,
306 truncated,
307 };
308 }
309
310 export const ROWS_CAP = 500;
311
312 /**
313 * The rows behind a query, or behind one of its points (an x value and a
314 * series name), newest first: every column, and where each row lives.
315 */
316 export function queryRows(
317 db: Database,
318 q: Query,
319 point?: { x?: string; series?: string },
320 limit = ROWS_CAP,
321 ): { columns: string[]; rows: Record<string, unknown>[]; href: (string | null)[] } {
322 const source = sourceNamed(q.source)!;
323 const w = whereOf(source, q, point);
324 const cols = source.columns;
325 const select = cols.map((c, i) => `${c.sql} AS c${i}`).join(", ");
326 const href = source.href === "" ? "NULL" : source.href;
327 const got = db
328 .query(
329 `SELECT ${select}, ${href} AS href FROM ${source.from} WHERE ${w.sql} ORDER BY ${source.time} DESC LIMIT ?`,
330 )
331 .all(...w.params, Math.max(1, Math.min(ROWS_CAP, limit))) as Record<string, unknown>[];
332 return {
333 columns: cols.map((c) => c.name),
334 rows: got.map((r) => Object.fromEntries(cols.map((c, i) => [c.name, r[`c${i}`] ?? null]))),
335 href: got.map((r) => (typeof r.href === "string" ? r.href : null)),
336 };
337 }
338
339 /** A query as URL parameters, so a panel's state is a link (and back). */
340 export function queryParams(q: Query, extra: Record<string, string> = {}): URLSearchParams {
341 const p = new URLSearchParams();
342 p.set("source", q.source);
343 p.set("from", new Date(q.from).toISOString());
344 p.set("to", new Date(q.to).toISOString());
345 p.set("x", "bucket" in q.x ? q.x.bucket : q.x.column);
346 if (q.series !== undefined) p.set("series", q.series);
347 p.set("agg", q.agg);
348 if (q.of !== undefined) p.set("of", q.of);
349 for (const f of q.where) p.append("f", `${f.column}:${f.op}:${f.value}`);
350 for (const [k, v] of Object.entries(extra)) p.set(k, v);
351 return p;
352 }
353
354 /** URL parameters as `parseQuery`'s input: `f=column:op:value`, repeated. */
355 export function paramsInput(p: URLSearchParams): Record<string, unknown> {
356 const input: Record<string, unknown> = {};
357 for (const k of ["source", "from", "to", "last", "x", "series", "agg", "of"]) {
358 const v = p.get(k);
359 if (v !== null) input[k] = v;
360 }
361 input.where = p
362 .getAll("f")
363 .filter((f) => f.trim() !== "")
364 .map((f) => {
365 const [column = "", op = "", ...rest] = f.split(":");
366 return { column, op, value: rest.join(":") };
367 });
368 return input;
369 }
src/boards/sources.ts added +389
@@ -0,0 +1,389 @@
1 /**
2 * Every table an admin can see, as a source a board reads (#1557). A source
3 * is a fixed `FROM` and an allowlist of columns, each a fixed SQL
4 * expression: a query names columns, never SQL, so nothing a person types
5 * reaches the statement except as a bound parameter (`boards/query.ts`).
6 *
7 * The one thing no source returns is a secret or a sealed value: password
8 * and token hashes, encrypted values (`*_enc`), webhook secrets, a sealed
9 * issue's title, an event's payload (it can carry a sealed issue's words).
10 * Each source names what it withholds and why, so the page says so instead
11 * of leaving a gap to guess at.
12 */
13
14 export type ColumnType = "text" | "number" | "time";
15
16 export interface Column {
17 readonly name: string;
18 readonly type: ColumnType;
19 /** The SQL expression, over the source's `from` aliases. Never user text. */
20 readonly sql: string;
21 readonly doc: string;
22 }
23
24 export interface Withheld {
25 readonly column: string;
26 readonly why: string;
27 }
28
29 export interface Source {
30 readonly name: string;
31 readonly doc: string;
32 readonly from: string;
33 /** A fixed condition every read of this source carries, or "". */
34 readonly where: string;
35 /** The column a time range and a time bucket read. */
36 readonly time: string;
37 readonly columns: readonly Column[];
38 readonly withheld: readonly Withheld[];
39 /** Where one row lives on the forge, as SQL, or "" when it has no page. */
40 readonly href: string;
41 }
42
43 const text = (name: string, sql: string, doc: string): Column => ({
44 name,
45 type: "text",
46 sql,
47 doc,
48 });
49 const num = (name: string, sql: string, doc: string): Column => ({
50 name,
51 type: "number",
52 sql,
53 doc,
54 });
55 const at = (name: string, sql: string, doc: string): Column => ({
56 name,
57 type: "time",
58 sql,
59 doc,
60 });
61
62 /**
63 * Seconds between two ISO columns, or NULL while either is unset. Julian
64 * days carry float error in the microseconds; the stamps are milliseconds,
65 * so the difference is rounded to them.
66 */
67 const seconds = (from: string, to: string): string =>
68 `CASE WHEN ${to} IS NULL OR ${from} IS NULL THEN NULL ELSE ROUND((julianday(${to}) - julianday(${from})) * 86400.0, 3) END`;
69
70 const REPO = `LEFT JOIN repo p ON p.id = {repo} LEFT JOIN user o ON o.id = p.owner_id`;
71 const repoJoin = (col: string): string => REPO.replace("{repo}", col);
72 const repoName = text("repo", `o.username || '/' || p.name`, "owner/name");
73 const issueHref = `'/' || o.username || '/' || p.name || '/' || CASE WHEN i.kind = 'pull' THEN 'pulls' ELSE 'issues' END || '/' || i.number`;
74 const title = text(
75 "title",
76 `CASE WHEN i.sealed = 1 THEN '(sealed)' ELSE i.title END`,
77 "a sealed issue's title reads (sealed)",
78 );
79
80 const runColumns = (): Column[] => [
81 text("id", "r.id", "run id"),
82 text("kind", "r.kind", "agent, check, deploy, snapshot…"),
83 text("state", "r.state", "queued, running, ok, failed, cancelled"),
84 text("reason", "r.reason", "why it was started"),
85 repoName,
86 text("actor", "a.username", "who or which agent it ran as"),
87 text("env", "r.env", "production or a preview"),
88 text("branch", "r.branch", "the branch it ran on"),
89 num("cost_usd", "r.cost_usd", "US dollars, as reported"),
90 num("turns", "r.turns", "agent turns"),
91 num(
92 "wait_s",
93 seconds("r.created_at", "r.started_at"),
94 "seconds queued before it started",
95 ),
96 num(
97 "duration_s",
98 seconds("r.started_at", "r.finished_at"),
99 "seconds from start to finish",
100 ),
101 at("created_at", "r.created_at", "when it was asked for"),
102 at("started_at", "r.started_at", "when it started"),
103 at("finished_at", "r.finished_at", "when it finished"),
104 ];
105 const RUN_FROM = `run r LEFT JOIN user a ON a.id = r.actor_id ${repoJoin("r.repo_id")}`;
106 const RUN_HREF = `'/' || o.username || '/' || p.name || '/runs/' || r.id`;
107
108 export const SOURCES: readonly Source[] = [
109 {
110 name: "runs",
111 doc: "every run: agent, check, deploy, snapshot",
112 from: RUN_FROM,
113 where: "",
114 time: "r.created_at",
115 columns: runColumns(),
116 withheld: [
117 {
118 column: "budget_reserved_usd, session_id",
119 why: "internal bookkeeping",
120 },
121 ],
122 href: RUN_HREF,
123 },
124 {
125 name: "deploys",
126 doc: "runs of kind deploy",
127 from: RUN_FROM,
128 where: "r.kind = 'deploy'",
129 time: "r.created_at",
130 columns: runColumns(),
131 withheld: [],
132 href: RUN_HREF,
133 },
134 {
135 name: "pulls",
136 doc: "every pull, open and closed",
137 from: `issue i JOIN pull pl ON pl.issue_id = i.id LEFT JOIN user u ON u.id = i.author_id LEFT JOIN user m ON m.id = pl.merged_by ${repoJoin("i.repo_id")}`,
138 where: "i.kind = 'pull'",
139 time: "i.created_at",
140 columns: [
141 num("number", "i.number", "the pull's number"),
142 title,
143 text("state", "i.state", "open or closed"),
144 text(
145 "outcome",
146 "CASE WHEN pl.merged_at IS NOT NULL THEN 'merged' WHEN i.state = 'closed' THEN 'closed' ELSE 'open' END",
147 "merged, closed or open",
148 ),
149 repoName,
150 text("author", "u.username", "who opened it"),
151 text("merged_by", "m.username", "who merged it"),
152 text("base", "pl.base_branch", "base branch"),
153 text("head", "pl.head_branch", "head branch"),
154 num(
155 "open_to_merge_s",
156 seconds("i.created_at", "pl.merged_at"),
157 "seconds from opened to merged",
158 ),
159 at("created_at", "i.created_at", "opened"),
160 at("closed_at", "i.closed_at", "closed"),
161 at("merged_at", "pl.merged_at", "merged"),
162 ],
163 withheld: [
164 { column: "body", why: "long text; read it on the pull" },
165 { column: "title (sealed)", why: "a sealed issue's words stay sealed" },
166 ],
167 href: issueHref,
168 },
169 {
170 name: "reviews",
171 doc: "every review verdict on a pull",
172 from: `review rv JOIN issue i ON i.id = rv.issue_id LEFT JOIN user u ON u.id = rv.author_id ${repoJoin("i.repo_id")}`,
173 where: "",
174 time: "rv.created_at",
175 columns: [
176 text("verdict", "rv.state", "approved, changes_requested, commented"),
177 text("reviewer", "u.username", "who reviewed"),
178 num("pull", "i.number", "the pull's number"),
179 repoName,
180 at("created_at", "rv.created_at", "when"),
181 ],
182 withheld: [{ column: "body", why: "long text; read it on the pull" }],
183 href: issueHref,
184 },
185 {
186 name: "apps",
187 doc: "every app, and when it was made",
188 from: `app ap ${repoJoin("ap.repo_id")}`,
189 where: "",
190 time: "ap.created_at",
191 columns: [
192 text("slug", "ap.slug", "the app's name"),
193 repoName,
194 text("access", "ap.access", "who may open it"),
195 text("preview_data", "ap.preview_data", "what a preview's data starts as"),
196 at("created_at", "ap.created_at", "made"),
197 ],
198 withheld: [{ column: "app_env values", why: "sealed: write-only" }],
199 href: `'/' || ap.slug`,
200 },
201 {
202 name: "awake",
203 doc: "each stretch an app's environment was awake (wake to sleep)",
204 from: `meter mt ${repoJoin("mt.repo_id")}`,
205 where: "",
206 time: "mt.started_at",
207 columns: [
208 repoName,
209 text("env", "mt.env", "production or a preview"),
210 text("placement", "mt.placement", "where it ran"),
211 num(
212 "awake_s",
213 seconds("mt.started_at", "COALESCE(mt.ended_at, mt.beat_at)"),
214 "seconds awake",
215 ),
216 at("started_at", "mt.started_at", "woke"),
217 at("ended_at", "mt.ended_at", "slept"),
218 ],
219 withheld: [],
220 href: "",
221 },
222 {
223 name: "capacity",
224 doc: "every change to the forge's capacity settings",
225 from: `forge_setting_change c LEFT JOIN user u ON u.id = c.actor_id`,
226 where: "",
227 time: "c.at",
228 columns: [
229 text("key", "c.key", "the setting"),
230 text("from", "c.from_value", "before"),
231 text("to", "c.to_value", "after"),
232 text("actor", "u.username", "who changed it"),
233 at("at", "c.at", "when"),
234 ],
235 withheld: [],
236 href: `'/settings/capacity'`,
237 },
238 {
239 name: "ledger",
240 doc: "the decision ledger: what the decider decided, and how it went",
241 from: `decision d ${repoJoin("d.repo_id")}`,
242 where: "",
243 time: "d.created_at",
244 columns: [
245 text("kind", "d.kind", "what was decided"),
246 repoName,
247 text("state", "d.state", "the decision's state"),
248 text("answer", "d.answer", "the answer"),
249 text("by", "d.by", "who or what decided"),
250 num("p", "d.p", "confidence, 0 to 1"),
251 num("ms", "d.ms", "milliseconds to decide"),
252 text("outcome", "d.outcome", "how it turned out"),
253 at("created_at", "d.created_at", "decided"),
254 at("outcome_at", "d.outcome_at", "outcome known"),
255 ],
256 withheld: [],
257 href: "",
258 },
259 {
260 name: "spend",
261 doc: "the spend ledger: what each run spent",
262 from: `usage us LEFT JOIN user g ON g.id = us.agent_id LEFT JOIN subscription sb ON sb.id = us.subscription_id ${repoJoin("us.repo_id")}`,
263 where: "",
264 time: "us.at",
265 columns: [
266 text("run", "us.run_id", "run id"),
267 text("kind", "us.kind", "run kind"),
268 text("agent", "g.username", "which agent"),
269 text("credential", "sb.name", "which subscription paid"),
270 repoName,
271 num("tokens_in", "us.tokens_in", "tokens in"),
272 num("tokens_out", "us.tokens_out", "tokens out"),
273 num("cost_usd", "us.cost_usd", "US dollars, list price"),
274 num("wall_ms", "us.wall_ms", "milliseconds of wall time"),
275 text("outcome", "us.outcome", "how the run ended"),
276 at("at", "us.at", "when"),
277 ],
278 withheld: [{ column: "subscription token", why: "sealed: encrypted at rest" }],
279 href: "",
280 },
281 {
282 name: "crew",
283 doc: "every agent on the crew",
284 from: `agent ag JOIN user u ON u.id = ag.user_id LEFT JOIN user c ON c.id = ag.created_by`,
285 where: "",
286 time: "ag.created_at",
287 columns: [
288 text("agent", "u.username", "the agent"),
289 text("model", "ag.model", "its model"),
290 num("budget_usd", "ag.budget_usd", "its budget, US dollars"),
291 text("made_by", "c.username", "who made it"),
292 text(
293 "status",
294 "CASE WHEN u.removed_at IS NOT NULL THEN 'removed' WHEN u.suspended_at IS NOT NULL THEN 'suspended' ELSE 'active' END",
295 "active, suspended or removed",
296 ),
297 at("created_at", "ag.created_at", "made"),
298 ],
299 withheld: [
300 { column: "brief", why: "long text; read it on the crew page" },
301 { column: "tokens", why: "a run's token is a secret" },
302 ],
303 href: `'/' || u.username`,
304 },
305 {
306 name: "sessions",
307 doc: "every signed-in session",
308 from: `session s JOIN user u ON u.id = s.user_id`,
309 where: "",
310 time: "s.created_at",
311 columns: [
312 text("user", "u.username", "whose session"),
313 text("kind", "u.kind", "person or agent"),
314 at("created_at", "s.created_at", "signed in"),
315 at("last_seen_at", "s.last_seen_at", "last seen"),
316 at("expires_at", "s.expires_at", "expires"),
317 ],
318 withheld: [{ column: "token_hash", why: "a credential" }],
319 href: "",
320 },
321 {
322 name: "tokens",
323 doc: "every access token, by scope and last use",
324 from: `token t JOIN user u ON u.id = t.user_id`,
325 where: "",
326 time: "t.created_at",
327 columns: [
328 text("user", "u.username", "whose token"),
329 text("kind", "u.kind", "person or agent"),
330 text("name", "t.name", "the token's name"),
331 text("scope", "t.scope", "ro, rw or admin"),
332 at("created_at", "t.created_at", "made"),
333 at("last_used_at", "t.last_used_at", "last used"),
334 at("expires_at", "t.expires_at", "expires"),
335 ],
336 withheld: [{ column: "token_hash", why: "a credential" }],
337 href: "",
338 },
339 {
340 name: "audit",
341 doc: "every event the forge recorded",
342 from: `event e LEFT JOIN user u ON u.id = e.actor_id ${repoJoin("e.repo_id")}`,
343 where: "",
344 time: "e.created_at",
345 columns: [
346 text("kind", "e.kind", "what happened"),
347 text("actor", "u.username", "who did it"),
348 text("actor_kind", "u.kind", "person or agent"),
349 repoName,
350 num("seq", "e.seq", "its place in the outbox"),
351 at("created_at", "e.created_at", "when"),
352 ],
353 withheld: [
354 {
355 column: "payload",
356 why: "can carry a sealed issue's words; open the event on /audit",
357 },
358 ],
359 href: `'/audit'`,
360 },
361 ];
362
363 const BY_NAME = new Map(SOURCES.map((s) => [s.name, s]));
364
365 export function sourceNamed(name: string): Source | undefined {
366 return BY_NAME.get(name);
367 }
368
369 export function columnOf(source: Source, name: string): Column | undefined {
370 return source.columns.find((c) => c.name === name);
371 }
372
373 /** The catalogue as plain data: what the API and the page list. */
374 export function catalogue(): {
375 name: string;
376 doc: string;
377 columns: { name: string; type: ColumnType; doc: string }[];
378 withheld: Withheld[];
379 }[] {
380 return SOURCES.map((s) => ({
381 name: s.name,
382 doc: s.doc,
383 columns: s.columns.map((c) => ({ name: c.name, type: c.type, doc: c.doc })),
384 withheld: [
385 ...s.withheld,
386 { column: "secrets", why: "no secret or sealed value is ever returned" },
387 ],
388 }));
389 }
src/core/reserved.ts +1
@@ -63,6 +63,7 @@ export const SYSTEM_NAMES: readonly string[] = [
6363 "audit.csv",
6464 "big",
6565 "board",
66 "boards",
6667 "events",
6768 "explore",
6869 "fleet",
src/http/api.ts +42
@@ -11,6 +11,8 @@
1111 import { askCheck } from "../checks/again.ts";
1212 import { mayView, mayViewId, sealedScope } from "../core/sealed.ts";
1313 import { changeCapacity, listCapacity } from "../actions/capacity.ts";
14 import { boardQuery, boardRows, boardSources } from "../actions/boards.ts";
15 import { paramsInput } from "../boards/query.ts";
1416 import {
1517 accountSignIns,
1618 endAccountSession,
@@ -1270,6 +1272,46 @@ export function apiRoutes(router: Router<Handler>): void {
12701272 );
12711273 });
12721274
1275 // Boards (#1557): every source an admin can query. A person who is a
1276 // forge admin reads them; an agent is refused (403) whatever its token;
1277 // anyone else is told the door is not there.
1278 const boardsDenied = (error: string): Response =>
1279 error === "forbidden"
1280 ? apiError("forbidden", 403, "an agent cannot read a board's sources")
1281 : error === "not_found"
1282 ? notFound()
1283 : apiError(error, 422, "that query is not one a board can run");
1284 router.add("GET", "/api/v1/boards/sources", (ctx) => {
1285 const denied = requireScope(ctx, "ro");
1286 if (denied) return denied;
1287 const listed = boardSources(ctx.app, ctx.auth.user);
1288 return listed.ok ? json({ items: listed.value }) : boardsDenied(listed.error);
1289 });
1290 const boardsQuery = (ctx: Ctx, input: Record<string, unknown>): Response => {
1291 const denied = requireScope(ctx, "ro");
1292 if (denied) return denied;
1293 const ran = boardQuery(ctx.app, ctx.auth.user, input);
1294 return ran.ok ? json(ran.value) : boardsDenied(ran.error);
1295 };
1296 router.add("GET", "/api/v1/boards/query", (ctx) =>
1297 boardsQuery(ctx, paramsInput(ctx.url.searchParams)),
1298 );
1299 router.add("POST", "/api/v1/boards/query", async (ctx) =>
1300 boardsQuery(ctx, await body(ctx.request)),
1301 );
1302 router.add("GET", "/api/v1/boards/rows", (ctx) => {
1303 const denied = requireScope(ctx, "ro");
1304 if (denied) return denied;
1305 const p = ctx.url.searchParams;
1306 const point: { x?: string; series?: string } = {};
1307 const px = p.get("px");
1308 const ps = p.get("ps");
1309 if (px !== null) point.x = px;
1310 if (ps !== null) point.series = ps;
1311 const got = boardRows(ctx.app, ctx.auth.user, paramsInput(p), point);
1312 return got.ok ? json(got.value) : boardsDenied(got.error);
1313 });
1314
12731315 router.add("GET", "/api/v1/admin/accounts", (ctx) => {
12741316 const denied = accountAdmin(ctx, "ro");
12751317 if (denied) return denied;
src/http/server.ts +9
@@ -7,6 +7,11 @@
77
88 import { unsealReleased } from "../actions/sealed.ts";
99 import { capacityPage, capacitySet } from "../web/pages/capacity.ts";
10 import {
11 boardsDataPage,
12 boardsRowsCsv,
13 boardsRowsPage,
14 } from "../web/pages/boards.ts";
1015 import {
1116 closeStreamsOf,
1217 closeStreamsOfSession,
@@ -603,6 +608,10 @@ export function buildRouter(): Router<Handler> {
603608 router.add("GET", "/migrate/jobs/:job", migrationJobPage);
604609 // Every app on one canvas; a literal route, so it must sit above /:owner.
605610 router.add("GET", "/map", globalMapPage);
611 // Boards (#1557): every admin-visible table as a source; literal, above /:owner.
612 router.add("GET", "/boards/data", boardsDataPage);
613 router.add("GET", "/boards/data/rows", boardsRowsPage);
614 router.add("GET", "/boards/data/rows.csv", boardsRowsCsv);
606615 // A selection's spend and runs over time; literal, above /:owner.
607616 router.add("GET", "/fleet/graph", fleetGraphPage);
608617 router.add("GET", "/fleet/graph/live", fleetGraphLive);
src/web/client.ts +8
@@ -1743,6 +1743,14 @@ export const shellJs = /* js */ `
17431743 if (!out) return;
17441744 i.addEventListener('input', function () { out.textContent = i.value; });
17451745 });
1746 // A form that is its own chart's query (\`data-redraw\`, boards): a
1747 // changed select submits it, so the chart redraws as the query changes.
1748 // A text field waits for Enter or "Draw", so typing never reloads.
1749 doc.addEventListener('change', function (e) {
1750 var t = e.target;
1751 if (!t || t.tagName !== 'SELECT' || !t.form || !t.form.hasAttribute('data-redraw')) return;
1752 if (t.form.requestSubmit) t.form.requestSubmit(); else t.form.submit();
1753 });
17461754 })();
17471755 `;
17481756
src/web/pages/boards.ts added +269
@@ -0,0 +1,269 @@
1 /**
2 * Boards' data page (#1557), for a forge admin who is a person: one panel
3 * whose query is a form above its chart — change a field and the chart
4 * redraws (the form submits itself on change; without script, "Draw" does)
5 * — and below it every source with its columns and what it withholds.
6 * The page's whole state is its URL, so a panel is a link to share; the
7 * rows behind any point are one click away, as a page, as CSV and as JSON
8 * (`/api/v1/boards/*`).
9 *
10 * An agent is refused (403); anyone else who is not an admin gets the one
11 * 404, as every admin page does.
12 */
13
14 import { boardQuery, boardRows, boardSources } from "../../actions/boards.ts";
15 import { CHART_WORDS, CHARTS, drawChart, type Chart } from "../../boards/charts.ts";
16 import {
17 AGGS,
18 BUCKETS,
19 LASTS,
20 OPS,
21 paramsInput,
22 queryParams,
23 type Query,
24 } from "../../boards/query.ts";
25 import { columnOf, SOURCES, sourceNamed } from "../../boards/sources.ts";
26 import type { Ctx } from "../../http/context.ts";
27 import { notFoundPage, signInFirst } from "../chrome.ts";
28 import { html, type Html } from "../html.ts";
29 import { page } from "../layout.ts";
30 import { btn, card, icon } from "../ui.ts";
31
32 function denied(ctx: Ctx): Response | undefined {
33 if (!ctx.auth.user) return signInFirst(ctx);
34 if (ctx.auth.user.kind === "agent")
35 return new Response("an agent cannot read a board's sources", {
36 status: 403,
37 headers: { "content-type": "text/plain; charset=utf-8" },
38 });
39 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
40 return undefined;
41 }
42
43 /**
44 * The URL's query, made to fit its source: a source change keeps what
45 * still names a column of the new source and drops the rest, so switching
46 * source redraws rather than erroring.
47 */
48 function fitted(p: URLSearchParams): Record<string, unknown> {
49 const input = paramsInput(p);
50 const source = sourceNamed(String(input.source ?? "")) ?? SOURCES[0]!;
51 input.source = source.name;
52 if (input.from === undefined && input.last === undefined) input.last = "24h";
53 const x = String(input.x ?? "hour");
54 if (!(x in BUCKETS) && !columnOf(source, x)) input.x = "hour";
55 if (input.series !== undefined && !columnOf(source, String(input.series))) delete input.series;
56 const of = columnOf(source, String(input.of ?? ""));
57 if (input.agg !== undefined && input.agg !== "count" && of?.type !== "number") {
58 const first = source.columns.find((c) => c.type === "number");
59 if (first) input.of = first.name;
60 else input.agg = "count";
61 }
62 input.where = (input.where as { column: string }[]).filter((f) => columnOf(source, f.column));
63 return input;
64 }
65
66 const chartOf = (p: URLSearchParams): Chart => {
67 const c = p.get("chart");
68 return (CHARTS as readonly string[]).includes(c ?? "") ? (c as Chart) : "line";
69 };
70
71 function select(name: string, label: string, options: [string, string][], value: string): Html {
72 return html`<label class="bd-field"><span class="muted small">${label}</span>
73 <select class="input" name="${name}">
74 ${options.map(([v, w]) => html`<option value="${v}" ${v === value ? "selected" : ""}>${w}</option>`)}
75 </select></label>`;
76 }
77
78 function editor(input: Record<string, unknown>, chart: Chart, title: string): Html {
79 const source = sourceNamed(String(input.source))!;
80 const cols = source.columns.map((c): [string, string] => [c.name, c.name]);
81 const nums = source.columns
82 .filter((c) => c.type === "number")
83 .map((c): [string, string] => [c.name, c.name]);
84 const where = (input.where as { column: string; op: string; value: string }[]).map(
85 (f) => `${f.column}:${f.op}:${f.value}`,
86 );
87 while (where.length < 3) where.push("");
88 return html`<form class="bd-editor" method="get" action="/boards/data" data-redraw>
89 ${select("source", "Source", SOURCES.map((s) => [s.name, s.name]), source.name)}
90 ${select("last", "Range", Object.keys(LASTS).map((l) => [l, `last ${l}`]), String(input.last ?? ""))}
91 ${select(
92 "x",
93 "X axis",
94 [...Object.keys(BUCKETS).map((b): [string, string] => [b, `per ${b}`]), ...cols],
95 String(input.x ?? "hour"),
96 )}
97 ${select("series", "Split by", [["", "nothing"], ...cols], String(input.series ?? ""))}
98 ${select("agg", "Aggregate", AGGS.map((a) => [a, a]), String(input.agg ?? "count"))}
99 ${select("of", "Of", [["", "—"], ...nums], String(input.of ?? ""))}
100 ${select("chart", "Chart", CHARTS.map((c) => [c, CHART_WORDS[c]]), chart)}
101 <label class="bd-field"><span class="muted small">Title</span>
102 <input class="input" name="title" maxlength="80" value="${title}" /></label>
103 ${where.map(
104 (f, i) => html`<label class="bd-field"><span class="muted small">Filter ${String(i + 1)}</span>
105 <input class="input mono" name="f" value="${f}" placeholder="state:eq:failed" maxlength="200" /></label>`,
106 )}
107 <div class="bd-field">${btn("Draw", { variant: "primary", size: "sm" })}</div>
108 <p class="muted small bd-help">
109 A filter is <span class="mono">column:op:value</span>, op one of
110 ${OPS.join(", ")}. Times are UTC; buckets start on the minute, hour or
111 day. p50 and p95 are nearest-rank: always a value that occurred.
112 </p>
113 </form>`;
114 }
115
116 function rowsHref(q: Query, x?: string, series?: string, path = "/boards/data/rows"): string {
117 const extra: Record<string, string> = {};
118 if (x !== undefined) extra.px = x;
119 if (series !== undefined) extra.ps = series;
120 return `${path}?${queryParams(q, extra).toString()}`;
121 }
122
123 function catalogueView(ctx: Ctx): Html {
124 const listed = boardSources(ctx.app, ctx.auth.user);
125 if (!listed.ok) return html``;
126 return html`<div class="bd-sources" id="sources">
127 ${listed.value.map((s) =>
128 card(
129 html`<p class="muted small">${s.doc}</p>
130 <ul class="bd-cols">
131 ${s.columns.map(
132 (c) => html`<li><span class="mono">${c.name}</span> <span class="muted small">${c.type} · ${c.doc}</span></li>`,
133 )}
134 </ul>
135 <p class="muted small">
136 Withheld: ${s.withheld.map((w, i) => html`${i > 0 ? "; " : ""}<span class="mono">${w.column}</span> (${w.why})`)}
137 </p>`,
138 {
139 head: html`${icon("folder")}
140 <h2><a href="/boards/data?source=${s.name}">${s.name}</a></h2>`,
141 },
142 ),
143 )}
144 </div>`;
145 }
146
147 // GET /boards/data
148 export function boardsDataPage(ctx: Ctx): Response {
149 const no = denied(ctx);
150 if (no) return no;
151 const p = ctx.url.searchParams;
152 const input = fitted(p);
153 const chart = chartOf(p);
154 const ran = boardQuery(ctx.app, ctx.auth.user, input);
155 if (!ran.ok && (ran.error === "not_found" || ran.error === "forbidden"))
156 return notFoundPage(ctx);
157 const title = (p.get("title") ?? "").slice(0, 80) || String(input.source);
158 const panel = ran.ok
159 ? html`<div class="bd-panel">
160 ${drawChart(chart, ran.value.result, (x, s) => rowsHref(ran.value.query, x, s), title)}
161 <p class="muted small">
162 ${ran.value.result.rows.toLocaleString("en-US")} rows in range${ran.value.result
163 .truncated
164 ? " (cut at the row cap)"
165 : ""}
166 · <a href="${rowsHref(ran.value.query)}">rows</a>
167 · <a href="${rowsHref(ran.value.query, undefined, undefined, "/boards/data/rows.csv")}">CSV</a>
168 · <a href="/api/v1/boards/query?${queryParams(ran.value.query).toString()}">JSON</a>
169 </p>
170 </div>`
171 : html`<p class="muted" id="query-error">That query cannot run: <span class="mono">${ran.error}</span>.</p>`;
172 return page({
173 ctx,
174 title: "Boards · data",
175 wide: true,
176 body: html`<div class="page-head"><h1>Boards · data</h1></div>
177 <p class="muted small mb">
178 Every table an admin can see, as a source to query. Secrets and sealed
179 values are never returned; each source says what it withholds.
180 </p>
181 ${editor(input, chart, title)}
182 ${card(panel, { head: html`${icon("activity")}<h2>${title}</h2>`, id: "panel" })}
183 ${catalogueView(ctx)}`,
184 });
185 }
186
187 /** A CSV field: quoted, and a leading formula character defused. */
188 export function csvField(v: unknown): string {
189 const s = v === null || v === undefined ? "" : String(v);
190 const safe = /^[=+\-@\t\r]/.test(s) ? `'${s}` : s;
191 return `"${safe.replace(/"/g, '""')}"`;
192 }
193
194 function pointOf(p: URLSearchParams): { x?: string; series?: string } {
195 const point: { x?: string; series?: string } = {};
196 const px = p.get("px");
197 const ps = p.get("ps");
198 if (px !== null) point.x = px;
199 if (ps !== null) point.series = ps;
200 return point;
201 }
202
203 // GET /boards/data/rows.csv
204 export function boardsRowsCsv(ctx: Ctx): Response {
205 const no = denied(ctx);
206 if (no) return no;
207 const got = boardRows(ctx.app, ctx.auth.user, fitted(ctx.url.searchParams), pointOf(ctx.url.searchParams));
208 if (!got.ok) return notFoundPage(ctx);
209 const lines = [
210 got.value.columns.map(csvField).join(","),
211 ...got.value.rows.map((r) => got.value.columns.map((c) => csvField(r[c])).join(",")),
212 ];
213 return new Response(lines.join("\r\n") + "\r\n", {
214 headers: {
215 "content-type": "text/csv; charset=utf-8",
216 "content-disposition": `attachment; filename="${got.value.query.source}.csv"`,
217 },
218 });
219 }
220
221 // GET /boards/data/rows
222 export function boardsRowsPage(ctx: Ctx): Response {
223 const no = denied(ctx);
224 if (no) return no;
225 const p = ctx.url.searchParams;
226 const point = pointOf(p);
227 const got = boardRows(ctx.app, ctx.auth.user, fitted(p), point);
228 if (!got.ok) return notFoundPage(ctx);
229 const { columns, rows, href, query } = got.value;
230 const back = `/boards/data?${queryParams(query, p.get("chart") ? { chart: p.get("chart")! } : {}).toString()}`;
231 return page({
232 ctx,
233 title: `Boards · ${query.source} rows`,
234 wide: true,
235 body: html`<div class="page-head"><h1>${query.source}: the rows behind it</h1></div>
236 <p class="muted small mb">
237 ${point.x !== undefined ? html`At <span class="mono">${point.x}</span>. ` : null}
238 ${point.series !== undefined ? html`Series <span class="mono">${point.series}</span>. ` : null}
239 Newest first, at most 500. <a href="${back}">Back to the panel</a> ·
240 <a href="${rowsHref(query, point.x, point.series, "/boards/data/rows.csv")}">CSV</a>
241 </p>
242 <div class="bd-table-wrap bd-rows"><table class="table">
243 <thead><tr>${columns.map((c) => html`<th scope="col">${c}</th>`)}</tr></thead>
244 <tbody>
245 ${rows.length === 0
246 ? html`<tr><td colspan="${String(columns.length)}" class="muted">No rows.</td></tr>`
247 : rows.map(
248 (r, i) => html`<tr>${columns.map((c, ci) =>
249 ci === 0 && href[i]
250 ? html`<td><a href="${href[i]!}">${String(r[c] ?? "")}</a></td>`
251 : html`<td>${String(r[c] ?? "")}</td>`,
252 )}</tr>`,
253 )}
254 </tbody>
255 </table></div>`,
256 });
257 }
258
259 export const boardsCss = /* css */ `
260 @layer components {
261 .bd-editor { display: flex; flex-wrap: wrap; gap: 10px 12px; align-items: end; margin-bottom: 16px; }
262 .bd-field { display: flex; flex-direction: column; gap: 4px; min-width: 120px; }
263 .bd-help { flex-basis: 100%; margin: 0; }
264 .bd-sources { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 16px; margin-top: 24px; }
265 .bd-cols { list-style: none; padding: 0; margin: 8px 0; display: flex; flex-direction: column; gap: 2px; }
266 .bd-rows { max-height: none; }
267 @media print { .bd-editor, .bd-sources { display: none; } }
268 }
269 `;
src/web/pages/origins.ts +6
@@ -131,6 +131,12 @@ export function accountSections(
131131 icon: "activity" as const,
132132 current: current === "capacity",
133133 },
134 {
135 label: "Boards",
136 href: "/boards/data",
137 icon: "activity" as const,
138 current: false,
139 },
134140 {
135141 label: "Backups",
136142 href: "/settings/backups",
src/web/style.ts +4
@@ -24,6 +24,8 @@
2424
2525 import { swatchCss, themeCss } from "../design/themes.ts";
2626 import { boardCss } from "./pages/board.ts";
27 import { boardsCss } from "./pages/boards.ts";
28 import { chartCss } from "../boards/charts.ts";
2729 import { base, layers, reset, utilities } from "./style/base.ts";
2830 import { components } from "./style/components.ts";
2931 import { content } from "./style/content.ts";
@@ -48,6 +50,8 @@ export const css = [
4850 avatarHues,
4951 studioCss,
5052 boardCss,
53 chartCss,
54 boardsCss,
5155 content,
5256 utilities,
5357 swatchCss,
test/boards.test.ts added +325
@@ -0,0 +1,325 @@
1 /**
2 * Boards' data (#1557): every admin-visible table is a source, a query
3 * over one aggregates exactly what a hand calculation says, the rows behind
4 * a point are the rows that made it, and the doors hold — an agent is
5 * refused (403) at every source whatever its token, a member is told there
6 * is nothing there, and no source ever returns a secret or a sealed value.
7 */
8
9 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
10 import { mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { createApp, type App } from "../src/app.ts";
14 import { boardQuery, boardRows, boardSources } from "../src/actions/boards.ts";
15 import { createAgent } from "../src/actions/crew.ts";
16 import { createRepo } from "../src/actions/repos.ts";
17 import { drawChart } from "../src/boards/charts.ts";
18 import {
19 aggregate,
20 parseQuery,
21 percentile,
22 queryRows,
23 runQuery,
24 type Query,
25 } from "../src/boards/query.ts";
26 import { SOURCES } from "../src/boards/sources.ts";
27 import type { Repo } from "../src/core/repos.ts";
28 import { setSecret } from "../src/core/secret_store.ts";
29 import { createSession } from "../src/core/sessions.ts";
30 import { createToken } from "../src/core/tokens.ts";
31 import { createUser, type User } from "../src/core/users.ts";
32 import { serve, type Servers } from "../src/http/server.ts";
33 import { csvField } from "../src/web/pages/boards.ts";
34
35 const BASE = Date.parse("2026-10-01T00:00:00.000Z");
36 const at = (min: number): string => new Date(BASE + min * 60_000).toISOString();
37
38 describe("boards: sources, queries, charts and their doors", () => {
39 let dataDir: string;
40 let app: App;
41 let servers: Servers;
42 let alice: User;
43 let bob: User;
44 let agent: User;
45 let repo: Repo;
46 let aliceRo: string;
47 let bobAdmin: string;
48 let agentAdmin: string;
49 const SECRET_VALUE = "sk-live-NEVER-SHOWN-7f3a";
50 const SEALED_TITLE = "SEALED-TITLE-NEVER-SHOWN";
51
52 const api = (token: string, path: string) =>
53 fetch(`${servers.url}/api/v1${path}`, {
54 headers: { authorization: `Bearer ${token}` },
55 });
56
57 const q = (input: Record<string, unknown>): Query => {
58 const parsed = parseQuery({ from: at(0), to: at(180), ...input });
59 if (!parsed.ok) throw new Error(parsed.error);
60 return parsed.value;
61 };
62
63 beforeAll(async () => {
64 dataDir = await mkdtemp(join(tmpdir(), "forge-boards-"));
65 app = createApp({ dataDir, port: 0 });
66 servers = await serve(app);
67 const a = await createUser(app.db, {
68 trusted: true,
69 username: "alice",
70 email: "[email protected]",
71 password: "a-good-passphrase",
72 adminIfFirst: true,
73 });
74 if (!a.ok) throw new Error(a.error);
75 alice = a.value;
76 const b = await createUser(app.db, {
77 trusted: true,
78 username: "bob",
79 email: "[email protected]",
80 password: "a-good-passphrase",
81 });
82 if (!b.ok) throw new Error(b.error);
83 bob = b.value;
84 const made = await createAgent(app, alice, { username: "scout" });
85 if (!made.ok) throw new Error(String(made.error));
86 agent = made.value.user;
87 const r = await createRepo(app, alice, { name: "garden", visibility: "public" });
88 if (!r.ok) throw new Error(String(r.error));
89 repo = r.value;
90 aliceRo = createToken(app.db, alice.id, "t", "ro").token;
91 bobAdmin = createToken(app.db, bob.id, "t", "admin").token;
92 // An agent made an admin by hand still reads nothing.
93 app.db.query("UPDATE user SET is_admin = 1 WHERE id = ?").run(agent.id);
94 agent = { ...agent, isAdmin: true };
95 agentAdmin = createToken(app.db, agent.id, "t", "admin").token;
96
97 // Runs: [minute, kind, state, cost, actor, reason]. Hour 0: two agent
98 // runs ($1, $3); hour 1: one check ($0); hour 2: an agent ($2), a deploy.
99 const runs: [number, string, string, number | null, string, string][] = [
100 [10, "agent", "ok", 1, agent.id, "<script>x</script>"],
101 [40, "agent", "failed", 3, agent.id, "assigned"],
102 [65, "check", "ok", 0, alice.id, "push"],
103 [150, "agent", "ok", 2, agent.id, "assigned"],
104 [165, "deploy", "ok", 0, alice.id, "push"],
105 // Outside the range: never counted.
106 [200, "agent", "ok", 50, agent.id, "assigned"],
107 ];
108 runs.forEach(([min, kind, state, cost, actor, reason], i) =>
109 app.db
110 .query(
111 `INSERT INTO run (id, repo_id, kind, env, state, actor_id, reason, cost_usd, created_at, started_at, finished_at, attempt)
112 VALUES (?1, ?2, ?3, 'production', ?4, ?5, ?6, ?7, ?8, ?9, ?10, 1)`,
113 )
114 .run(`run${i}`, repo.id, kind, state, actor, reason, cost, at(min), at(min + 1), at(min + 11)),
115 );
116 // Pulls: one merged, one open and sealed.
117 const pulls: [number, string, number, number | null][] = [
118 [1, "Add a fence", 0, 90],
119 [2, SEALED_TITLE, 1, null],
120 ];
121 for (const [n, title, sealed, merged] of pulls) {
122 const id = `iss${n}`;
123 app.db
124 .query(
125 `INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, state, sealed, created_at, updated_at)
126 VALUES (?1, ?2, ?3, 'pull', ?4, ?4, ?5, 'open', ?6, ?7, ?7)`,
127 )
128 .run(id, repo.id, n, title, agent.id, sealed, at(20));
129 app.db
130 .query(
131 `INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at)
132 VALUES (?1, 'main', ?2, 'a', 'b', ?3)`,
133 )
134 .run(id, `b${n}`, merged === null ? null : at(merged));
135 }
136 // Things no source may ever show.
137 const s = setSecret(app.db, dataDir, "forge", "", "DEPLOY_KEY", SECRET_VALUE);
138 if (!s.ok) throw new Error(s.error);
139 createSession(app.db, alice.id);
140 });
141
142 afterAll(async () => {
143 servers.stop();
144 app.close();
145 await rm(dataDir, { recursive: true, force: true });
146 });
147
148 test("nearest-rank percentiles and the aggregates match a hand calculation", () => {
149 expect(percentile([1, 2, 3, 4], 50)).toBe(2);
150 expect(percentile([1, 2, 3, 4], 95)).toBe(4);
151 expect(percentile([7], 95)).toBe(7);
152 expect(percentile([], 50)).toBeNull();
153 expect(aggregate("avg", [1, 2, 3, 6], 4)).toBe(3);
154 expect(aggregate("sum", [], 0)).toBe(0);
155 expect(aggregate("max", [], 0)).toBeNull();
156 expect(aggregate("count", [], 3)).toBe(3);
157 });
158
159 test("a query is validated at the boundary", () => {
160 expect(parseQuery({ source: "nope", last: "1h" })).toEqual({ ok: false, error: "no_such_source" });
161 expect(parseQuery({ source: "runs", last: "2y" })).toEqual({ ok: false, error: "bad_range" });
162 expect(parseQuery({ source: "runs", last: "30d", x: "minute" })).toEqual({
163 ok: false,
164 error: "too_many_buckets",
165 });
166 expect(parseQuery({ source: "runs", last: "1h", x: "1; DROP TABLE run" })).toEqual({
167 ok: false,
168 error: "bad_x",
169 });
170 // An aggregate over a text column, or a filter on a column the source lacks.
171 expect(parseQuery({ source: "runs", last: "1h", agg: "sum", of: "state" }).ok).toBe(false);
172 expect(
173 parseQuery({ source: "runs", last: "1h", where: [{ column: "password_hash", op: "eq", value: "x" }] }).ok,
174 ).toBe(false);
175 });
176
177 test("runs per hour, cost per hour, split by kind: the hand-counted numbers", () => {
178 const count = runQuery(app.db, q({ source: "runs", x: "hour" }));
179 expect(count.xs).toEqual([at(0), at(60), at(120)]);
180 expect(count.series[0]!.values).toEqual([2, 1, 2]);
181 expect(count.total).toBe(5);
182
183 const cost = runQuery(app.db, q({ source: "runs", x: "hour", agg: "sum", of: "cost_usd" }));
184 expect(cost.series[0]!.values).toEqual([4, 0, 2]);
185 expect(cost.total).toBe(6);
186 expect(runQuery(app.db, q({ source: "runs", agg: "p95", of: "cost_usd" })).total).toBe(3);
187 expect(runQuery(app.db, q({ source: "runs", agg: "p50", of: "cost_usd" })).total).toBe(1);
188 expect(runQuery(app.db, q({ source: "runs", agg: "avg", of: "cost_usd" })).total).toBe(1.2);
189 expect(runQuery(app.db, q({ source: "runs", agg: "max", of: "duration_s" })).total).toBe(600);
190
191 const byKind = runQuery(app.db, q({ source: "runs", x: "hour", series: "kind" }));
192 const of = (k: string) => byKind.series.find((s) => s.name === k)!.values;
193 expect(of("agent")).toEqual([2, 0, 1]);
194 expect(of("check")).toEqual([0, 1, 0]);
195 expect(of("deploy")).toEqual([0, 0, 1]);
196
197 const filtered = runQuery(
198 app.db,
199 q({ source: "runs", x: "state", where: [{ column: "kind", op: "eq", value: "agent" }] }),
200 );
201 expect(filtered.xs).toEqual(["ok", "failed"]);
202 expect(filtered.series[0]!.values).toEqual([2, 1]);
203 expect(runQuery(app.db, q({ source: "pulls", x: "outcome" })).xs.toSorted()).toEqual(["merged", "open"]);
204 });
205
206 test("the rows behind a point are exactly the rows that made it", () => {
207 const query = q({ source: "runs", x: "hour", series: "kind" });
208 const behind = queryRows(app.db, query, { x: at(0), series: "agent" });
209 expect(behind.rows.map((r) => r.id).sort()).toEqual(["run0", "run1"]);
210 expect(behind.href[0]).toBe("/alice/garden/runs/run1");
211 expect(queryRows(app.db, query, { x: at(120) }).rows.map((r) => r.id).sort()).toEqual(["run3", "run4"]);
212 });
213
214 test("a chart escapes what it draws and links every point to its rows", () => {
215 const query = q({ source: "runs", x: "hour", series: "reason" });
216 const res = runQuery(app.db, query);
217 for (const chart of ["line", "bar", "area", "heat", "table", "number"] as const) {
218 const svg = drawChart(chart, res, (x, s) => `/rows?x=${x}&s=${s ?? ""}`, "t").toString();
219 expect(svg).not.toContain("<script>");
220 if (chart !== "number") expect(svg).toContain("&lt;script&gt;");
221 if (chart !== "number" && chart !== "area") expect(svg).toContain(`/rows?x=${at(0)}&amp;s=assigned`);
222 }
223 });
224
225 test("a CSV field is quoted and a formula is defused", () => {
226 expect(csvField('a"b')).toBe('"a""b"');
227 expect(csvField("=HYPERLINK(1)")).toBe(`"'=HYPERLINK(1)"`);
228 expect(csvField(null)).toBe('""');
229 });
230
231 test("no source returns a secret or a sealed value", async () => {
232 const hashes = app.db
233 .query("SELECT password_hash AS h FROM user WHERE password_hash IS NOT NULL UNION ALL SELECT token_hash FROM token UNION ALL SELECT token_hash FROM session UNION ALL SELECT value_enc FROM secret")
234 .all()
235 .filter((r): r is { h: string } => typeof (r as { h: unknown }).h === "string" && (r as { h: string }).h.length > 16) as { h: string }[];
236 expect(hashes.length).toBeGreaterThan(3);
237 for (const s of SOURCES) {
238 // Every column of every row, over the last 30 days and the seeded day.
239 for (const range of [{ last: "30d" }, { from: at(0), to: at(24 * 60) }]) {
240 const got = boardRows(app, alice, { source: s.name, ...range });
241 if (!got.ok) throw new Error(`${s.name}: ${got.error}`);
242 const text = JSON.stringify(got.value);
243 expect(text).not.toContain(SECRET_VALUE);
244 expect(text).not.toContain(SEALED_TITLE);
245 for (const { h } of hashes) expect(text).not.toContain(h);
246 }
247 }
248 const pulls = boardRows(app, alice, { source: "pulls", from: at(0), to: at(180) });
249 if (!pulls.ok) throw new Error(pulls.error);
250 expect(pulls.value.rows.map((r) => r.title).sort()).toEqual(["(sealed)", "Add a fence"]);
251 });
252
253 test("an agent is refused at every door, a member is told nothing is there", async () => {
254 expect(boardSources(app, agent)).toEqual({ ok: false, error: "forbidden" });
255 expect(boardQuery(app, agent, { source: "runs", last: "1h" })).toEqual({ ok: false, error: "forbidden" });
256 expect(boardRows(app, agent, { source: "runs", last: "1h" })).toEqual({ ok: false, error: "forbidden" });
257 expect(boardSources(app, bob)).toEqual({ ok: false, error: "not_found" });
258 expect(boardSources(app, undefined)).toEqual({ ok: false, error: "not_found" });
259
260 const paths = [
261 "/boards/sources",
262 ...SOURCES.flatMap((s) => [`/boards/query?source=${s.name}&last=24h`, `/boards/rows?source=${s.name}&last=24h`]),
263 ];
264 for (const path of paths) {
265 const res = await api(agentAdmin, path);
266 expect(res.status).toBe(403);
267 expect(((await res.json()) as { error: string }).error).toBe("forbidden");
268 expect((await api(bobAdmin, path)).status).toBe(404);
269 }
270 expect((await fetch(`${servers.url}/api/v1/boards/sources`)).status).toBe(401);
271 });
272
273 test("an admin reads every source, queries one, and gets the page", async () => {
274 const listed = await api(aliceRo, "/boards/sources");
275 expect(listed.status).toBe(200);
276 const items = ((await listed.json()) as { items: { name: string; withheld: unknown[] }[] }).items;
277 expect(items.map((i) => i.name)).toEqual(
278 expect.arrayContaining(["runs", "pulls", "reviews", "deploys", "apps", "capacity", "ledger", "spend", "crew", "sessions", "audit"]),
279 );
280 expect(items.every((i) => i.withheld.length > 0)).toBe(true);
281
282 const ran = await api(aliceRo, `/boards/query?source=runs&from=${at(0)}&to=${at(180)}&x=hour&agg=sum&of=cost_usd`);
283 expect(ran.status).toBe(200);
284 const body = (await ran.json()) as { result: { series: { values: number[] }[] } };
285 expect(body.result.series[0]!.values).toEqual([4, 0, 2]);
286
287 const cookie = await (async () => {
288 const res = await fetch(`${servers.url}/signin`, {
289 method: "POST",
290 redirect: "manual",
291 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
292 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
293 });
294 return (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
295 })();
296 const pageRes = await fetch(
297 `${servers.url}/boards/data?source=runs&from=${at(0)}&to=${at(180)}&x=hour&series=reason&chart=bar`,
298 { headers: { cookie } },
299 );
300 expect(pageRes.status).toBe(200);
301 expect(pageRes.headers.get("content-security-policy")).toBeTruthy();
302 const pageText = await pageRes.text();
303 expect(pageText).toContain("<svg");
304 expect(pageText).toContain("data-redraw");
305 expect(pageText).not.toContain("<script>x</script>");
306 // A source switch keeps the page drawing rather than erroring.
307 const switched = await fetch(`${servers.url}/boards/data?source=pulls&x=reason&series=kind`, { headers: { cookie } });
308 expect(switched.status).toBe(200);
309 expect(await switched.text()).not.toContain("query-error");
310 const csv = await fetch(`${servers.url}/boards/data/rows.csv?source=runs&from=${at(0)}&to=${at(180)}`, { headers: { cookie } });
311 expect(csv.status).toBe(200);
312 expect((await csv.text()).split("\r\n")[0]).toStartWith('"id","kind"');
313
314 const bobCookie = await (async () => {
315 const res = await fetch(`${servers.url}/signin`, {
316 method: "POST",
317 redirect: "manual",
318 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
319 body: new URLSearchParams({ username: "bob", password: "a-good-passphrase" }),
320 });
321 return (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
322 })();
323 expect((await fetch(`${servers.url}/boards/data`, { headers: { cookie: bobCookie } })).status).toBe(404);
324 });
325 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs