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

/status shows the last 30 days for each component as one cell per day, from the forge's own samples #15629

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/15621-status-shows-the-last-30-days-for-each-c → main 0 commits fork 11 threads · 11 unresolved

  • Merged. scout/15621-status-shows-the-last-30-days-for-each-c was merged into main as cf4bb2f.

Review

Sign in to review this change.
11 files changed +443 −9
docs/design/areas/settings.md +3
@@ -87,6 +87,9 @@ full width, when it has rows. Styled in `src/web/style/components.ts`.
8787
8888 - `.status-rows` — the `<dl>` of those rows, ruled by hairlines.
8989 - `.status-row` — one row: label, state, action; one column on a phone, three from 640px.
90 - `.status-days` — /status's 30 day cells (`<i>`, titled when measured; the strip's own title names a hollow cell) in a row's action slot (#15621), oldest first, at most 240px wide;
91 `.sd-ok`, `.sd-degraded`, `.sd-down` fill with the tone tokens, `.sd-none` is a hollow hairline box, never a
92 colour. Hidden from screen readers, which read the row's one `.sr-only` sentence instead; a `.hint` after it names the row's worst day for touch and keyboard.
9093 - `.status-act` — a row's actions, at its end; absent when there are none.
9194 - `.settings-block` — a titled block of a settings page that is not a card: a small heading and its content.
9295 - `.segmented` — a few mutually exclusive states side by side, the one on pressed; each other state is a one-button form.
docs/features/status-time.md +12
@@ -12,4 +12,16 @@ words were read (held at most 10 s). A row that is slow or down says since when:
1212 `Accept: application/json` gives `asOf` (ISO) and, per row, `{ "state", "since" }`;
1313 `since` is absent on an ok row, and where no time is known (billing records, a restart).
1414
15 ## The last 30 days
16
17 Each row ends with its last 30 UTC days, oldest first, one cell a day: ok, degraded
18 (some minutes slow), down (some minutes down) or no data (a hollow box, never green).
19 Hover a measured cell for its day and minutes slow or down (a hollow cell's hover says
20 "no data"); under the strip, a row that had an off day names its worst one with its minutes,
21 so touch and keyboard read them too; a screen reader hears one sentence per row, naming the
22 off days with their minutes. Days come from the forge's own two-minute tick
23 (`status_day`, 31 days kept, `src/core/status_days.ts`), each sample crediting the minutes
24 measured since the one before, at most 10; before the first sample the page says `history starts <date>`.
25 The terminal screen prints the same days as `#` ok, `~` degraded, `!` down, `.` no data.
26
1527 The page and the terminal read one function (`src/core/status_words.ts`).
src/core/migration-pins/20261122120000-status-day.pin added +1
@@ -0,0 +1,1 @@
1 4c49951404cf8eaa5efbd7ccc58a913cac328fd22368873ca63a1ed89f0d7d2e
src/core/migrations/20261122120000-status-day.ts added +14
@@ -0,0 +1,14 @@
1 // /status's 30-day record (#15621): per UTC day and status row, the minutes the forge's own
2 // two-minute tick saw that row ok, slow or down. Only the row's state is kept, never a cause or
3 // any detail. `src/core/status_days.ts` writes it and keeps 31 days; every read takes the
4 // window (at most 93 rows) by the primary key.
5 export default `
6 CREATE TABLE status_day (
7 day TEXT NOT NULL,
8 row TEXT NOT NULL,
9 ok INTEGER NOT NULL DEFAULT 0,
10 slow INTEGER NOT NULL DEFAULT 0,
11 down INTEGER NOT NULL DEFAULT 0,
12 PRIMARY KEY (day, row)
13 ) WITHOUT ROWID;
14 `;
src/core/status_days.ts added +157
@@ -0,0 +1,157 @@
1 /**
2 * /status's record (#15621): the last 30 UTC days of each status row, one cell a day, from the
3 * forge's own samples. The serving thread's two-minute asks tick (`main.ts`, `tickAsks`) hands
4 * the words it reads (`statusWords`) to `statusSampler`, which adds the minutes measured since
5 * the last sample to that day's ok, slow or down count (`status_day`); nothing new polls.
6 *
7 * A day with no sample is `none`, never `ok`: an "ok" nobody measured is worse than a gap. A day
8 * with any minute down is `down`, any minute slow `degraded`. Only the row's state is kept: no
9 * cause, host or sentence reaches the table or a cell.
10 */
11
12 import type { Database } from "bun:sqlite";
13 import type { App } from "../app.ts";
14 import { ROWS, statusWords, type Row, type StatusWords } from "./status_words.ts";
15
16 export type DayState = "ok" | "degraded" | "down" | "none";
17
18 export interface Day {
19 /** `2026-11-22` (UTC). */
20 readonly day: string;
21 readonly state: DayState;
22 /** Minutes slow or down that day (0 on a day with no data). */
23 readonly degraded: number;
24 }
25
26 export interface StatusHistory {
27 /** The first day any sample was kept, or null when none is. */
28 readonly start: string | null;
29 readonly rows: readonly { readonly name: Row; readonly days: readonly Day[] }[];
30 }
31
32 export const HISTORY_DAYS = 30;
33 /** How long the tick that samples waits between samples (`main.ts`, the asks tick). */
34 export const SAMPLE_MINUTES = 2;
35 /**
36 * The most one sample may credit: a tick that comes late after a stall credits what it measured
37 * up to this, not the whole gap it did not see.
38 */
39 export const SAMPLE_CAP_MINUTES = 10;
40 const KEEP_DAYS = HISTORY_DAYS + 1;
41 const DAY_MS = 86_400_000;
42
43 const dayOf = (ms: number): string => new Date(ms).toISOString().slice(0, 10);
outdated

A fixed 2 minutes per call is claimed, not measured; a late or restarted tick makes the minutes slow or down title wrong. Use the elapsed time since the last sample, capped.

44
45 /** Adds one sample of each row's state to today's counts, and forgets days past the window. */
46 export function noteStatusDay(db: Database, words: StatusWords, now: number = Date.now(), minutes = SAMPLE_MINUTES): void {
47 const day = dayOf(now);
48 const add = db.query(
49 `INSERT INTO status_day (day, row, ok, slow, down) VALUES (?1, ?2, ?3, ?4, ?5)
50 ON CONFLICT (day, row) DO UPDATE SET ok = ok + ?3, slow = slow + ?4, down = down + ?5`,
51 );
52 db.transaction(() => {
53 for (const r of words.rows) {
54 add.run(day, r.name, r.state === "ok" ? minutes : 0, r.state === "slow" ? minutes : 0, r.state === "down" ? minutes : 0);
55 }
56 db.query("DELETE FROM status_day WHERE day < ?").run(dayOf(now - KEEP_DAYS * DAY_MS));
57 })();
58 }
59
60 /**
61 * The minutes one sample stands for: the measured time since the previous one, rounded, at
62 * least 1 and at most `SAMPLE_CAP_MINUTES`. The first sample after a start has nothing to
63 * measure from, so it credits the tick's interval.
64 */
65 export function sampleMinutes(last: number | null, now: number): number {
66 if (last === null || now <= last) return SAMPLE_MINUTES;
67 return Math.min(SAMPLE_CAP_MINUTES, Math.max(1, Math.round((now - last) / 60_000)));
68 }
69
70 /**
71 * The tick's hook (`main.ts`): each call reads the words and credits the minutes measured since
72 * the call before.
73 */
74 export function statusSampler(db: Database, read: () => StatusWords): (now?: number) => number {
75 let last: number | null = null;
76 return (now = Date.now()) => {
77 const minutes = sampleMinutes(last, now);
78 noteStatusDay(db, read(), now, minutes);
79 last = now;
80 return minutes;
81 };
82 }
83
84 /**
85 * The tick's hook as `main.ts` calls it: samples the app's own status words and never throws
86 * into the timer; a failed sample is logged and the next tick tries again.
87 */
88 export function statusTick(app: App): () => void {
89 const sample = statusSampler(app.db, () => statusWords(app));
90 return () => {
91 try {
92 sample();
93 } catch (error) {
94 app.log.warn("status day sample failed", { error: String(error) });
95 }
96 };
97 }
98
99 /**
100 * The day with the most minutes slow or down, the latest on a tie; null when no day was.
101 */
102 export function worstDay(days: readonly Day[]): Day | null {
103 let worst: Day | null = null;
104 for (const d of days) if (d.degraded > 0 && (worst === null || d.degraded >= worst.degraded)) worst = d;
105 return worst;
106 }
107
108 /** The pure part: one day's counts to its cell. */
109 export function dayState(c: { ok: number; slow: number; down: number } | undefined): DayState {
110 if (c === undefined || c.ok + c.slow + c.down === 0) return "none";
111 if (c.down > 0) return "down";
112 return c.slow > 0 ? "degraded" : "ok";
113 }
114
115 /** The 30 days ending today, oldest first, for every row. */
116 export function statusHistory(db: Database, now: number = Date.now()): StatusHistory {
117 const days = Array.from({ length: HISTORY_DAYS }, (_, i) => dayOf(now - (HISTORY_DAYS - 1 - i) * DAY_MS));
118 const got = db
119 .query<{ day: string; row: string; ok: number; slow: number; down: number }, [string]>(
120 "SELECT day, row, ok, slow, down FROM status_day WHERE day >= ?",
121 )
122 .all(days[0]!);
123 const by = new Map(got.map((g) => [`${g.day} ${g.row}`, g]));
124 const first = got.filter((g) => g.ok + g.slow + g.down > 0).map((g) => g.day).sort()[0];
125 return {
126 start: first ?? null,
127 rows: ROWS.map((name) => ({
128 name,
129 days: days.map((day) => {
130 const c = by.get(`${day} ${name}`);
131 const state = dayState(c);
132 return { day, state, degraded: state === "none" ? 0 : c!.slow + c!.down };
133 }),
134 })),
135 };
136 }
137
138 /** Each state's word, the one /status, its cells and its sentence use. */
139 export const DAY_WORDS: Readonly<Record<DayState, string>> = { ok: "ok", degraded: "degraded", down: "down", none: "no data" };
140
141 /**
142 * A cell's title and its text for a screen reader: `2026-11-20: degraded, 14 min slow or down`.
143 */
144 export function dayWords(d: Day): string {
145 if (d.state === "none" || d.state === "ok") return `${d.day}: ${DAY_WORDS[d.state]}`;
146 return `${d.day}: ${DAY_WORDS[d.state]}, ${d.degraded} min slow or down`;
147 }
148
149 /** `history starts 2026-11-10`, when the window holds days from before the first sample. */
150 export function historyStartWords(h: StatusHistory, now: number = Date.now()): string | null {
151 const start = h.start ?? dayOf(now);
152 const windowStart = h.rows[0]?.days[0]?.day ?? start;
153 return start > windowStart ? `history starts ${start}` : null;
154 }
155
156 /** One character a day for the terminal: `#` ok, `~` degraded, `!` down, `.` no data. */
157 export const DAY_GLYPH: Readonly<Record<DayState, string>> = { ok: "#", degraded: "~", down: "!", none: "." };
src/main.ts +5
@@ -7,6 +7,7 @@
77 import { join } from "node:path";
88 import { sweepEntitlements } from "./billing/sync.ts";
99 import { sweepDesk } from "./actions/desk.ts";
10 import { statusTick } from "./core/status_days.ts";
1011 import { scanNightly } from "./checks/scan.ts";
1112 import { nightlyDue } from "./checks/scan_store.ts";
1213 import { checkLedger, setLedgerDir } from "./core/ledger.ts";
@@ -837,6 +838,7 @@ void during("guard-sweep", () => runGuardSweep(app), undefined, app);
837838 // unchanged pull costs two ref reads. Never throws into the timer.
838839 // The asks ledger rides the same tick, after the sweep has said what
839840 // expired: what asked each person, and how it ended.
841 const sampleStatus = statusTick(app);
840842 const tickAsks = async (): Promise<void> => {
841843 await sweepStaleAsks(app);
842844 // Repositories ruled "decider" have their hand-overs answered here.
@@ -859,6 +861,9 @@ const tickAsks = async (): Promise<void> => {
859861 app.log.warn("database size reading failed", { error: String(error) });
860862 }
861863 }
864 // /status's 30-day record (#15621): this tick's reading of each row, on the serving thread,
865 // which holds the health the words are read from.
866 sampleStatus();
862867 // A probe forge the release proof could not remove is removed here, before the vitals
863868 // read it (#12550).
864869 await sweepLeftoverProbes({
src/tui/screens/status.ts +15 −3
@@ -1,8 +1,10 @@
11 /**
22 * `/status` in the terminal (#13211): the one sentence and the rows the page
3 * shows, from the same `statusWords`. Anyone may open it; read-only.
3 * shows, from the same `statusWords`. Anyone may open it; read-only. Each row ends with its
4 * last 30 days (#15621), one character a day (`DAY_GLYPH`), from the same `statusHistory`.
45 */
56
7 import { DAY_GLYPH, historyStartWords, statusHistory } from "../../core/status_days.ts";
68 import { asOfWords, rowWords, statusWords } from "../../core/status_words.ts";
79 import { PROOF_ROW, proofStatus } from "../../release/daily_proof.ts";
810 import type { Ctx, Screen } from "../app/app.ts";
@@ -17,9 +19,19 @@ import { pad } from "../term/width.ts";
1719 */
1820 export function statusLines(session: Session, now = Date.now()): string[] {
1921 const w = statusWords(session.app);
22 const h = statusHistory(session.app.db);
23 const strip = new Map(h.rows.map((r) => [r.name, r.days.map((d) => DAY_GLYPH[d.state]).join("")]));
24 const starts = historyStartWords(h);
2025 const proof = proofStatus(session.app.db, now);
21 const rows = w.rows.map((r) => `${pad(r.name, 20)}${rowWords(r)}`);
22 return [w.sentence, asOfWords(w), "", ...rows, ...(proof === undefined ? [] : [`${pad(PROOF_ROW, 20)}${proof.says}`])];
26 return [
27 w.sentence,
28 asOfWords(w),
29 "",
30 ...w.rows.map((r) => `${pad(r.name, 20)}${pad(rowWords(r), 24)}${strip.get(r.name) ?? ""}`),
31 ...(proof === undefined ? [] : [`${pad(PROOF_ROW, 20)}${proof.says}`]),
32 "",
33 `last 30 days, oldest first: # ok ~ degraded ! down . no data${starts === null ? "" : `; ${starts}`}`,
34 ];
2335 }
2436
2537 export function statusScreen(session: Session, ctx: Ctx): Screen {
src/web/pages/status.ts +36 −5
@@ -1,6 +1,7 @@
11 /**
22 * GET /status: is the forge working, in one sentence and three rows (#13211, #13348).
3 * Signed out, always 200, under 6 KB, no script, no polling. Asked with
3 * Signed out, always 200, under 6 KB, no script, no polling. Each row ends with its last 30
4 * days, one cell a day (#15621, `core/status_days.ts`). Asked with
45 * `Accept: application/json` it answers the same words as data.
56 * Once the daily proof of production has run (#15625) a fourth row says how many of its lines
67 * passed and when (`release/daily_proof.ts`); its lines are `GET /api/v1/proof/daily`.
@@ -11,13 +12,14 @@
1112 * inside the window builds nothing.
1213 */
1314
15 import { DAY_WORDS, dayWords, historyStartWords, statusHistory, worstDay, type Day, type StatusHistory } from "../../core/status_days.ts";
1416 import { asOfWords, rowWords, statusJson, statusWords, type StatusWords } from "../../core/status_words.ts";
1517 import type { Ctx } from "../../http/context.ts";
1618 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1719 import { releaseOf, running, shortOf } from "../../kernel/version.ts";
1820 import { PROOF_ROW, proofStatus, type ProofStatus } from "../../release/daily_proof.ts";
1921 import { stylesheetAsset } from "../asset.ts";
20 import { html } from "../html.ts";
22 import { html, type Html } from "../html.ts";
2123 import { brandHead, shareHead, themeColorHead } from "../layout.ts";
2224 import { badge } from "../ui.ts";
2325 import { statusRow } from "./security.ts";
@@ -32,12 +34,40 @@ const built = new WeakMap<StatusWords, { origin: string; proof: string; text: st
3234 /** The status page's description: what it answers, the same on every visit. */
3335 const STATUS_LINE = "Whether Open Platform Forge is working now: pages and sign-in, building, and billing records.";
3436
35 function markup(words: StatusWords, origin: string, proof: ProofStatus | undefined): string {
37 /**
38 * `2 degraded (2026-11-19 3 min, 2026-11-20 14 min)`: how many days were in a state, and which
39 * with their minutes slow or down when dated.
40 */
41 function countOf(days: readonly Day[], state: Day["state"], dated: boolean): string {
42 const of = days.filter((d) => d.state === state);
43 return `${of.length} ${DAY_WORDS[state]}${dated && of.length > 0 ? ` (${of.map((d) => `${d.day} ${d.degraded} min`).join(", ")})` : ""}`;
44 }
45
46 /**
47 * A row's 30 days (#15621): one cell a day, a measured one titled with its day and, when off, its
outdated

Principle 2/8: the sentence gives dates but no minutes, and the cells are aria-hidden, so a screen-reader or touch user never learns how bad a day was. Add the minutes here.

48 * minutes slow or down; a hollow one (no data) untitled, so hovering it shows the strip's own
outdated

Hover-only titles (and none on no-data cells) are the only place minutes appear; unreachable by touch and keyboard. Make the detail visible or focusable without JS.

49 * title, which names a hollow cell as no data (90 titled gaps would cost 2.3 KB of a 6 KB page);
50 * one sentence for a screen reader in place of 30 cells read aloud, naming the off days with their
51 * minutes; and, when a day was off, one visible line naming the worst, so touch and keyboard read
52 * the minutes without a hover.
53 */
54 const STRIP_TITLE = "hollow: no data";
55
56 function daysStrip(days: readonly Day[]): Html {
57 const said = `Last ${days.length} days: ${countOf(days, "ok", false)}, ${countOf(days, "degraded", true)}, ${countOf(days, "down", true)}, ${countOf(days, "none", false)}.`;
58 const worst = worstDay(days);
59 return html`<span class="status-days" aria-hidden="true" title="${STRIP_TITLE}">${days.map((d) => (d.state === "none" ? html`<i class="sd-none"></i>` : html`<i class="sd-${d.state}" title="${dayWords(d)}"></i>`))}</span><span class="sr-only">${said}</span>${worst === null ? null : html`<span class="hint" aria-hidden="true">worst ${dayWords(worst)}</span>`}`;
60 }
61
62 function markup(words: StatusWords, origin: string, proof: ProofStatus | undefined, read: () => StatusHistory): string {
3663 const said = proof?.says ?? "";
3764 const kept = built.get(words);
3865 if (kept !== undefined && kept.origin === origin && kept.proof === said) return kept.text;
3966 statusBuilds.count += 1;
40 const rows = words.rows.map((r) => statusRow(r.name, badge(rowWords(r), { tone: tone[r.state] })));
67 const history = read();
68 const days = new Map(history.rows.map((r) => [r.name, r.days]));
outdated

Principle 1: this legend explains the cells a second time (the title and the sr-only sentence already do). Keep only history starts <date> when it applies.

69 const rows = words.rows.map((r) => statusRow(r.name, badge(rowWords(r), { tone: tone[r.state] }), daysStrip(days.get(r.name) ?? [])));
70 const starts = historyStartWords(history);
4171 // The daily proof of production (#15625): a row once it has run, never an "ok" nobody checked.
4272 const proofRow = proof === undefined ? null : statusRow(PROOF_ROW, badge(proof.says, { tone: proofTone[proof.state] }));
4373 const text = html`<!doctype html>
@@ -56,6 +86,7 @@ ${themeColorHead(undefined)}
5686 <main class="shell" id="main">
5787 <div class="page-head"><h1>${words.sentence}</h1><p class="hint">${asOfWords(words)}</p></div>
5888 <dl class="status-rows">${rows}${proofRow}</dl>
89 ${starts === null ? "" : html`<p class="hint">${starts}</p>`}
5990 </main>
6091 <footer class="foot"><a href="/">forge</a><span class="spacer"></span><a href="/status">Status</a><a href="/privacy">Privacy</a></footer>
6192 </body>
@@ -98,7 +129,7 @@ export function statusPage(ctx: Ctx): Response {
98129 ctx.request,
99130 "render",
100131 () =>
101 new Response(markup(words, ctx.url.origin, proof), {
132 new Response(markup(words, ctx.url.origin, proof, () => statusHistory(ctx.app.db)), {
102133 headers: {
103134 "content-type": "text/html; charset=utf-8",
104135 "cache-control": "public, max-age=10",
src/web/style/components.ts +6
@@ -1244,6 +1244,12 @@ html[data-overlay] { overflow: hidden; }
12441244 .status-row > dd { margin: 0; min-width: 0; }
12451245 .status-act { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 12px; }
12461246 .status-act:empty { display: none; }
1247 .status-days { display: grid; grid-template-columns: repeat(30, minmax(0, 1fr)); gap: 2px; width: min(100%, 240px); height: 16px; margin: 0; padding: 0; }
1248 .status-days > i { border-radius: 1px; }
1249 .status-days > .sd-ok { background: var(--success); }
1250 .status-days > .sd-degraded { background: var(--attn); }
1251 .status-days > .sd-down { background: var(--danger); }
1252 .status-days > .sd-none { box-shadow: inset 0 0 0 1px var(--border); }
12471253 @media (min-width: 640px) {
12481254 .status-row { grid-template-columns: 168px minmax(0, 1fr) auto; }
12491255 .status-act { justify-content: flex-end; }
test/daily-proof.test.ts +1 −1
@@ -188,7 +188,7 @@ describe("the daily proof", () => {
188188 const asJson = (await (await fetch(`${servers.url}/status`, { headers: { accept: "application/json" } })).json()) as { proof: Record<string, unknown> };
189189 expect(asJson.proof).toMatchObject({ pass: total, total, state: "pass", lines: "/api/v1/proof/daily" });
190190 const user = { sshUsername: "git", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: undefined };
191 expect(statusLines(new Session(app, user)).at(-1)).toMatch(new RegExp(`^daily proof\\s+${total} of ${total} pass`));
191 expect(statusLines(new Session(app, user)).find((l) => l.startsWith("daily proof"))).toMatch(new RegExp(`^daily proof\\s+${total} of ${total} pass`));
192192 const res = await fetch(`${servers.url}/api/v1/proof/daily`);
193193 expect(res.status).toBe(200);
194194 const body = (await res.json()) as { pass: number; total: number; lines: Record<string, unknown>[] };
test/status-history.test.ts added +193
@@ -0,0 +1,193 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { mkdtemp, rm } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createApp, type App } from "../src/app.ts";
6 import { serve, type Servers } from "../src/http/server.ts";
7 import { dayState, dayWords, historyStartWords, noteStatusDay, sampleMinutes, statusHistory, statusSampler, statusTick, worstDay } from "../src/core/status_days.ts";
8 import { Session } from "../src/tui/forge.ts";
9 import { statusLines } from "../src/tui/screens/status.ts";
10 import type { StatusWords } from "../src/core/status_words.ts";
11
12 const DAY = 86_400_000;
13 const NOW = Date.parse("2026-11-22T12:00:00Z");
14 const words = (pages: "ok" | "slow" | "down", building: "ok" | "slow" | "down" = "ok"): StatusWords => ({
15 sentence: "x",
16 state: "working",
17 asOf: new Date(NOW).toISOString(),
18 rows: [
19 { name: "pages and sign-in", state: pages },
20 { name: "building", state: building },
21 { name: "billing records", state: "ok" },
22 ],
23 });
24
25 let dir: string;
26 let app: App;
27 beforeAll(async () => {
28 dir = await mkdtemp(join(tmpdir(), "status-history-"));
29 app = createApp({ dataDir: dir, port: 0 });
30 });
31 afterAll(async () => {
32 await rm(dir, { recursive: true, force: true });
33 });
34
35 describe("status days", () => {
36 test("an empty record is all no data, and says history starts today", () => {
37 const h = statusHistory(app.db, NOW);
38 expect(h.start).toBeNull();
39 expect(h.rows.map((r) => r.name)).toEqual(["pages and sign-in", "building", "billing records"]);
40 for (const r of h.rows) {
41 expect(r.days).toHaveLength(30);
42 expect(r.days.every((d) => d.state === "none")).toBe(true);
43 }
44 expect(historyStartWords(h, NOW)).toBe("history starts 2026-11-22");
45 });
46
47 test("30 days of samples roll up to one cell a day, a gap reads as no data, never ok", () => {
48 // Days 29..1 ago and today, except day 5 ago: no sample at all.
49 for (let ago = 29; ago >= 0; ago--) {
50 if (ago === 5) continue;
51 const at = NOW - ago * DAY;
52 noteStatusDay(app.db, words("ok"), at);
53 noteStatusDay(app.db, words("ok"), at + 60_000);
54 }
55 noteStatusDay(app.db, words("slow"), NOW - 3 * DAY + 120_000);
56 noteStatusDay(app.db, words("slow"), NOW - 3 * DAY + 240_000);
57 noteStatusDay(app.db, words("down", "slow"), NOW - 2 * DAY + 120_000);
58
59 const h = statusHistory(app.db, NOW);
60 expect(h.start).toBe("2026-10-24");
61 expect(historyStartWords(h, NOW)).toBeNull();
62 const pages = h.rows[0]!.days;
63 expect(pages[0]!.day).toBe("2026-10-24");
64 expect(pages[29]!.day).toBe("2026-11-22");
65 expect(pages.map((d) => d.state)).toEqual([
66 ...Array(24).fill("ok"), "none", "ok", "degraded", "down", "ok", "ok",
67 ]);
68 expect(pages[26]).toEqual({ day: "2026-11-19", state: "degraded", degraded: 4 });
69 expect(dayWords(pages[26]!)).toBe("2026-11-19: degraded, 4 min slow or down");
70 expect(dayWords(pages[24]!)).toBe("2026-11-17: no data");
71 expect(dayWords(pages[0]!)).toBe("2026-10-24: ok");
72 expect(h.rows[1]!.days[27]!.state).toBe("degraded");
73 expect(h.rows[2]!.days[27]!.state).toBe("ok");
74 });
75
76 test("a day's counts: nothing is none, any down is down, any slow is degraded", () => {
77 expect(dayState(undefined)).toBe("none");
78 expect(dayState({ ok: 0, slow: 0, down: 0 })).toBe("none");
79 expect(dayState({ ok: 900, slow: 0, down: 2 })).toBe("down");
80 expect(dayState({ ok: 900, slow: 2, down: 0 })).toBe("degraded");
81 expect(dayState({ ok: 2, slow: 0, down: 0 })).toBe("ok");
82 });
83
84 test("days past the window are forgotten", () => {
85 noteStatusDay(app.db, words("ok"), NOW - 40 * DAY);
86 noteStatusDay(app.db, words("ok"), NOW);
87 const old = app.db.query("SELECT COUNT(*) AS n FROM status_day WHERE day < '2026-10-22'").get() as { n: number };
88 expect(old.n).toBe(0);
89 });
90 });
91
92 describe("the tick's sample", () => {
93 test("credits the minutes measured since the last sample, capped; the first credits the interval", () => {
94 expect(sampleMinutes(null, NOW)).toBe(2);
95 expect(sampleMinutes(NOW - 120_000, NOW)).toBe(2);
96 expect(sampleMinutes(NOW - 5 * 60_000, NOW)).toBe(5);
97 expect(sampleMinutes(NOW - 10_000, NOW)).toBe(1);
98 expect(sampleMinutes(NOW - 3 * 3_600_000, NOW)).toBe(10);
99 expect(sampleMinutes(NOW, NOW - 1)).toBe(2);
100 });
101
102 test("each call writes the row's state and the elapsed minutes; a late tick says its real minutes", () => {
103 const db = createApp({ dataDir: join(dir, "sampler"), port: 0 }).db;
104 let state: "ok" | "slow" = "ok";
105 const sample = statusSampler(db, () => words(state));
106 const at = NOW - 6 * 3_600_000;
107 expect(sample(at)).toBe(2);
108 state = "slow";
109 expect(sample(at + 7 * 60_000)).toBe(7);
110 const row = db.query("SELECT ok, slow, down FROM status_day WHERE day = '2026-11-22' AND row = 'pages and sign-in'").get();
111 expect(row).toEqual({ ok: 2, slow: 7, down: 0 });
112 expect(dayWords(statusHistory(db, NOW).rows[0]!.days[29]!)).toBe("2026-11-22: degraded, 7 min slow or down");
113 });
114
115 test("the tick's hook (main.ts) writes today's row from the app's own words, and never throws", () => {
116 const own = createApp({ dataDir: join(dir, "tick"), port: 0 });
117 const tick = statusTick(own);
118 tick();
119 const today = new Date().toISOString().slice(0, 10);
120 const rows = own.db.query("SELECT row, ok + slow + down AS minutes FROM status_day WHERE day = ? ORDER BY row").all(today);
121 expect(rows).toEqual([
122 { row: "billing records", minutes: 2 },
123 { row: "building", minutes: 2 },
124 { row: "pages and sign-in", minutes: 2 },
125 ]);
126 own.db.close();
127 expect(() => tick()).not.toThrow();
128 });
129
130 test("the worst day is the one with the most minutes off, the latest on a tie, none when all were ok", () => {
131 const d = (day: string, degraded: number) => ({ day, state: degraded > 0 ? ("degraded" as const) : ("ok" as const), degraded });
132 expect(worstDay([d("2026-11-01", 0), d("2026-11-02", 0)])).toBeNull();
133 expect(worstDay([d("2026-11-01", 9), d("2026-11-02", 3), d("2026-11-03", 9)])?.day).toBe("2026-11-03");
134 });
135 });
136
137 describe("GET /status with a record", () => {
138 let servers: Servers;
139 let base: string;
140 let fresh: App;
141 beforeAll(async () => {
142 fresh = createApp({ dataDir: join(dir, "page"), port: 0 });
143 const now = Date.now();
144 noteStatusDay(fresh.db, words("ok"), now - DAY);
145 noteStatusDay(fresh.db, words("slow"), now - DAY);
146 servers = await serve(fresh);
147 base = `http://127.0.0.1:${servers.port}`;
148 });
149 afterAll(async () => {
150 await servers.stop();
151 });
152
153 test("each row has 30 titled cells and a sentence for a screen reader; no script", async () => {
154 const text = await (await fetch(`${base}/status`)).text();
155 expect((text.match(/<i class="sd-/g) ?? []).length).toBe(90);
156 const yesterday = new Date(Date.now() - DAY).toISOString().slice(0, 10);
157 expect(text).toContain(`<i class="sd-degraded" title="${yesterday}: degraded, 2 min slow or down"></i>`);
158 expect((text.match(/<i class="sd-none"><\/i>/g) ?? []).length).toBe(87);
159 // A gap is untitled; hovering it shows the strip's title, which names it.
160 expect((text.match(/<span class="status-days" aria-hidden="true" title="hollow: no data">/g) ?? []).length).toBe(3);
161 expect(text).toContain(`<span class="sr-only">Last 30 days: 0 ok, 1 degraded (${yesterday} 2 min), 0 down, 29 no data.</span>`);
162 // The minutes are on the page without a hover: one line per row that had an off day.
163 expect((text.match(/<span class="hint" aria-hidden="true">worst /g) ?? []).length).toBe(1);
164 expect(text).toContain(`<span class="hint" aria-hidden="true">worst ${yesterday}: degraded, 2 min slow or down</span>`);
165 expect(text).toContain(`<p class="hint">history starts ${yesterday}</p>`);
166 expect(text).not.toContain("oldest first");
167 expect(text).not.toMatch(/<script/i);
168 });
169
170 test("a record with every day measured and most off stays under 12 KB (the sentence names 60 days with their minutes)", async () => {
171 const full = createApp({ dataDir: join(dir, "full"), port: 0 });
172 for (let ago = 0; ago < 30; ago++) noteStatusDay(full.db, words(ago % 2 ? "slow" : "down", "slow"), Date.now() - ago * DAY, 1234);
173 const s = await serve(full);
174 try {
175 const text = await (await fetch(`http://127.0.0.1:${s.port}/status`)).text();
176 expect((text.match(/title="\d{4}-\d\d-\d\d: (degraded|down), 1234 min slow or down"/g) ?? []).length).toBe(60);
177 expect(Buffer.byteLength(text)).toBeLessThan(12_288);
178 } finally {
179 await s.stop();
180 }
181 });
182
183 test("the terminal prints each row's days as glyphs, a legend, and where history starts", () => {
184 const user = { sshUsername: "git", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: undefined };
185 const lines = statusLines(new Session(fresh, user));
186 const pages = lines.find((l) => l.startsWith("pages and sign-in"))!;
187 expect(pages.endsWith(`${".".repeat(28)}~.`)).toBe(true);
188 const billing = lines.find((l) => l.startsWith("billing records"))!;
189 expect(billing.endsWith(`${".".repeat(28)}#.`)).toBe(true);
190 const yesterday = new Date(Date.now() - DAY).toISOString().slice(0, 10);
191 expect(lines.at(-1)).toBe(`last 30 days, oldest first: # ok ~ degraded ! down . no data; history starts ${yesterday}`);
192 });
193 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs