Public: anyone can read this; the crew can change it.
A release keeps the forge's log and each child forge's up and down history, so "was it down?" has an answer #17913
Merged 21h 30m ago, live in production
scout/forge:scout/17909-a-release-keeps-the-forge-s-log-and-each → main 0 commits fork 2 threads · 2 unresolved
14 files
changed +380
−8
- docs/design/areas/forges.md
- docs/features/forge-state-history.md
- scripts/forge-log.ts
- src/core/migration-pins/20261203050000-forge-state.pin
- src/core/migrations/20261203050000-forge-state.ts
- src/main.ts
- src/perf/kept_log.ts
- src/spawn/clients.ts
- src/spawn/state_history.ts
- src/tui/screens/forges.ts
- src/web/pages/forges.ts
- src/web/style/components.ts
- test/forge-state-history.test.ts
- test/job-slices.test.ts
docs/design/areas/forges.md added +3
| @@ -0,0 +1,3 @@ | ||
| 1 | # Forges | |
| 2 | ||
| 3 | `.state-strip` is the line on each /forges row giving a forge's last 24 hours (src/spawn/state_history.ts): `.state-strip-marks`, one monospace mark an hour (■ up, · asleep, ✕ down) from the first recorded hour, then the totals in words ("Last 24 h: up 20 h, asleep 3 h"). Tokens only, no accent; its own line, never wrapped (it scrolls sideways before it breaks through the marks). The marks are `aria-hidden`; the words carry the meaning, so nothing is said twice. |
docs/features/forge-state-history.md added +13
| @@ -0,0 +1,13 @@ | ||
| 1 | --- | |
| 2 | topic: Hosting forges for others, and getting paid | |
| 3 | row: A hosted forge's up, asleep and down history, and the forge's kept log | |
| 4 | --- | |
| 5 | # A hosted forge's up, asleep and down history, and the forge's kept log | |
| 6 | ||
| 7 | "Was it down, or only asleep?" is answered from `/forges` after any number of releases (#17909). | |
| 8 | ||
| 9 | - **State rows.** Each minute the forge reads every finished child's state and writes a row (`forge_state`: name, state, time) only when it changed: `up`, `asleep`, `woken` (up again after asleep) or `down` (running, but its public addresses did not answer, `src/spawn/reach.ts`). Rows older than 8 days are dropped. The finest it tells is a minute, and the stretch a release itself was down is not seen from inside. | |
| 10 | - **The strip.** `/forges` shows, on each forge's row, its own line (`.state-strip`, `docs/design/areas/forges.md`): one mark an hour from the first recorded hour, oldest first (`■` up, `·` asleep, `✕` down, an hour with any down in it), then "Last 24 h: up 20 h, asleep 3 h, down 1 h" and, for a new forge, when recording began. The terminal's forges screen (`src/tui/screens/forges.ts`) says the same after `24 h`. To see it on a preview: send a forge at `/forges/new`, wait two minutes for a sample, open `/forges` as an admin. | |
| 11 | - **The log.** Every log line, the child forges' too, is also appended to `<data>/log/forge.log`, a file a day and 8 MiB at most, files past a week dropped (about 250 MiB at the very most). Read it, across every release the files hold, with `bun scripts/forge-log.ts [data dir] [text]` (`text` keeps only the lines that contain it). The stall and memory lines keep their own file (`perf/loop.log`). | |
| 12 | ||
| 13 | Code: `src/spawn/state_history.ts`, `src/perf/kept_log.ts` (`FORGE_LOG`), `scripts/forge-log.ts`. Test: `test/forge-state-history.test.ts`. |
scripts/forge-log.ts added +11
| @@ -0,0 +1,11 @@ | ||
| 1 | /** | |
| 2 | * `bun scripts/forge-log.ts [data dir] [text]`: the forge's own log, kept across releases | |
| 3 | * (`perf/kept_log.ts` FORGE_LOG, #17909), oldest first: a week of it, every boot's lines and every | |
| 4 | * child forge's. With `text`, only the lines that contain it (`asleep`, a forge's name). The data | |
| 5 | * directory defaults to FORGE_DATA, as the forge's own. | |
| 6 | */ | |
| 7 | import { dataDirOf } from "../src/kernel/preflight.ts"; | |
| 8 | import { FORGE_LOG, readKept } from "../src/perf/kept_log.ts"; | |
| 9 | ||
| 10 | const [dir, text] = process.argv.slice(2); | |
| 11 | for (const line of readKept(dir ?? dataDirOf(process.env), FORGE_LOG.keep, FORGE_LOG.file)) if (text === undefined || line.includes(text)) console.log(line); |
src/core/migration-pins/20261203050000-forge-state.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 844a3e68b564e15fc900d90452e687694cf9022a28b28dad1a1d204ebe1916a7 |
src/core/migrations/20261203050000-forge-state.ts added +13
| @@ -0,0 +1,13 @@ | ||
| 1 | // A child forge's up, asleep, woken and down changes (#17909): one row when the state changes, with | |
| 2 | // the time, so "was it down or asleep?" is answered after the container that saw it is gone. | |
| 3 | // Additive: a new table, 8 days kept (`spawn/state_history.ts`). The reads walk (name, at); the | |
| 4 | // prune walks (at). | |
| 5 | export default ` | |
| 6 | CREATE TABLE IF NOT EXISTS forge_state ( | |
| 7 | name TEXT NOT NULL, | |
| 8 | state TEXT NOT NULL, | |
| 9 | at INTEGER NOT NULL | |
| 10 | ); | |
| 11 | CREATE INDEX IF NOT EXISTS forge_state_name_at ON forge_state (name, at); | |
| 12 | CREATE INDEX IF NOT EXISTS forge_state_at ON forge_state (at); | |
| 13 | `; |
src/main.ts +14 −2
| @@ -54,6 +54,7 @@ import { startUpstreamWatch } from "./spawn/upstream.ts"; | ||
| 54 | 54 | import { startAdvisoryFeed } from "./core/advisory_feed.ts"; |
| 55 | 55 | import { followTick, watchLandings } from "./spawn/app_follow.ts"; |
| 56 | 56 | import { startReachWatch } from "./spawn/reach.ts"; |
| 57 | import { startStateWatch } from "./spawn/state_history.ts"; | |
| 57 | 58 | import { isHookName, runHookClient } from "./git/hooks.ts"; |
| 58 | 59 | import { drainBudgets } from "./drain.ts"; |
| 59 | 60 | import { drainStreams } from "./http/sse.ts"; |
| @@ -125,7 +126,7 @@ import { census, censusWords, processRows } from "./kernel/census.ts"; | ||
| 125 | 126 | import { reapLeftoverBridges } from "./crew/leftovers.ts"; |
| 126 | 127 | import { crewRoot } from "./crew/workdir.ts"; |
| 127 | 128 | import { createLog, teeLines } from "./kernel/log.ts"; |
| 128 | import { keptLine, keptLog } from "./perf/kept_log.ts"; | |
| 129 | import { FORGE_LOG, keptLine, keptLog } from "./perf/kept_log.ts"; | |
| 129 | 130 | import { startLoopWatchdog } from "./kernel/loop_watchdog.ts"; |
| 130 | 131 | import { loadOrNone, startService } from "./kernel/start_service.ts"; |
| 131 | 132 | import { METER_EVERY_MS, newMeterWatch } from "./crew/meter_watch.ts"; |
| @@ -240,10 +241,17 @@ if (!readOnly) setLedgerDir(join(dataDir, "ledger")); | ||
| 240 | 241 | // the container and its log every half hour, and these are the forge's performance history. |
| 241 | 242 | if (!readOnly) { |
| 242 | 243 | const kept = keptLog(dataDir); |
| 244 | // ...and every line, the child forges' too (#17909): "was it down?" is asked days later, after | |
| 245 | // several releases. A week of it, a file a day, bounded by size as well (`FORGE_LOG`). | |
| 246 | const whole = keptLog(dataDir, FORGE_LOG); | |
| 243 | 247 | teeLines((scope, message, line) => { |
| 244 | 248 | if (keptLine(scope, message)) kept.add(line); |
| 249 | whole.add(line); | |
| 250 | }); | |
| 251 | process.on("exit", () => { | |
| 252 | kept.stop(); | |
| 253 | whole.stop(); | |
| 245 | 254 | }); |
| 246 | process.on("exit", () => kept.stop()); | |
| 247 | 255 | } |
| 248 | 256 | // One answer for boot and `--preflight` (kernel/preflight.ts): the data |
| 249 | 257 | // directory is not the tree itself (#622: a database or a host key there is |
| @@ -889,6 +897,9 @@ const advisoryTimer = inert ? undefined : startAdvisoryFeed(app); | ||
| 889 | 897 | // ...and this forge asks every child's public addresses what a visitor would get, every few minutes |
| 890 | 898 | // (spawn/reach.ts). |
| 891 | 899 | const reachTimer = inert ? undefined : startReachWatch(app, undefined, (name) => !childAwake(app, name)); |
| 900 | // ...and records each one's up, asleep, woken and down changes, so "was it down?" has an answer | |
| 901 | // after a release (spawn/state_history.ts, #17909). | |
| 902 | const stateTimer = inert ? undefined : startStateWatch(app, (name) => childAwake(app, name)); | |
| 892 | 903 | // ...and the list of them (/forges, the `forges` tool, the terminal) asks none that is asleep. |
| 893 | 904 | useSleepers(app, (name) => !childAwake(app, name)); |
| 894 | 905 | // Prompts from Instagram (docs/APPS.md): once a day, for each repository |
| @@ -1329,6 +1340,7 @@ function drain(signal: NodeJS.Signals): Promise<unknown> { | ||
| 1329 | 1340 | clearInterval(upstreamTimer); |
| 1330 | 1341 | clearInterval(advisoryTimer); |
| 1331 | 1342 | clearInterval(reachTimer); |
| 1343 | clearInterval(stateTimer); | |
| 1332 | 1344 | clearInterval(syncTimer); |
| 1333 | 1345 | clearInterval(staleTimer); |
| 1334 | 1346 | clearInterval(deskTimer); |
src/perf/kept_log.ts +37 −5
| @@ -32,6 +32,12 @@ export const FLUSH_MS = 2_000; | ||
| 32 | 32 | /** A buffer this big is written at once. */ |
| 33 | 33 | export const FLUSH_BYTES = 64 * 1024; |
| 34 | 34 | |
| 35 | /** | |
| 36 | * The forge's whole log (#17909), `<data>/log/forge.log`: a file a day, a week kept, 8 MiB a file | |
| 37 | * at most and 30 files, so about 250 MiB is the ceiling however noisy a day is. | |
| 38 | */ | |
| 39 | export const FORGE_LOG = { file: join("log", "forge.log"), maxBytes: 8 * 1024 * 1024, keep: 30, maxAgeMs: 7 * 86_400_000 } as const; | |
| 40 | ||
| 35 | 41 | /** Whether a log line is one the history keeps: the loop's stalls, and the minute memory lines. */ |
| 36 | 42 | export function keptLine(scope: string, message: string): boolean { |
| 37 | 43 | return scope === "loop" || ((scope === "forge" || scope === "memory") && /^memory (main|holds)\b/.test(message)); |
| @@ -47,19 +53,40 @@ export interface KeptLog { | ||
| 47 | 53 | } |
| 48 | 54 | |
| 49 | 55 | /** The kept log of `dataDir`: buffered appends, rotated by size. */ |
| 50 | export function keptLog(dataDir: string, o: { maxBytes?: number; keep?: number; flushMs?: number; file?: string } = {}): KeptLog { | |
| 56 | export function keptLog( | |
| 57 | dataDir: string, | |
| 58 | o: { maxBytes?: number; keep?: number; flushMs?: number; file?: string; maxAgeMs?: number; now?: () => number } = {}, | |
| 59 | ): KeptLog { | |
| 60 | const now = o.now ?? Date.now; | |
| 51 | 61 | const maxBytes = o.maxBytes ?? MAX_BYTES; |
| 52 | 62 | const keep = o.keep ?? KEEP; |
| 53 | 63 | const file = join(dataDir, o.file ?? KEPT_FILE); |
| 54 | 64 | let buffer: string[] = []; |
| 55 | 65 | let bytes = 0; |
| 56 | 66 | let size: number | undefined; |
| 67 | /** | |
| 68 | * The UTC day of the live file's last write: a new day starts a new file, so age is by the day. | |
| 69 | */ | |
| 70 | let day: number | undefined; | |
| 71 | const dayOf = (ms: number): number => Math.floor(ms / 86_400_000); | |
| 72 | /** Old files whose newest line is past `maxAgeMs` go (the oldest are the highest numbers). */ | |
| 73 | const prune = (): void => { | |
| 74 | if (o.maxAgeMs === undefined) return; | |
| 75 | for (let n = keep; n >= 1; n--) { | |
| 76 | try { | |
| 77 | if (now() - statSync(`${file}.${n}`).mtimeMs > o.maxAgeMs) rmSync(`${file}.${n}`, { force: true }); | |
| 78 | } catch { | |
| 79 | // not there | |
| 80 | } | |
| 81 | } | |
| 82 | }; | |
| 57 | 83 | const rotate = (): void => { |
| 58 | 84 | rmSync(`${file}.${keep}`, { force: true }); |
| 59 | 85 | for (let n = keep - 1; n >= 1; n--) if (existsSync(`${file}.${n}`)) renameSync(`${file}.${n}`, `${file}.${n + 1}`); |
| 60 | 86 | if (keep >= 1) renameSync(file, `${file}.1`); |
| 61 | 87 | else rmSync(file, { force: true }); |
| 62 | 88 | size = 0; |
| 89 | prune(); | |
| 63 | 90 | }; |
| 64 | 91 | const flush = (): void => { |
| 65 | 92 | if (buffer.length === 0) return; |
| @@ -69,12 +96,17 @@ export function keptLog(dataDir: string, o: { maxBytes?: number; keep?: number; | ||
| 69 | 96 | try { |
| 70 | 97 | if (size === undefined) { |
| 71 | 98 | mkdirSync(dirname(file), { recursive: true }); |
| 72 | size = existsSync(file) ? statSync(file).size : 0; | |
| 99 | const there = existsSync(file) ? statSync(file) : undefined; | |
| 100 | size = there?.size ?? 0; | |
| 101 | day = there === undefined ? undefined : dayOf(there.mtimeMs); | |
| 102 | prune(); | |
| 73 | 103 | } |
| 74 | 104 | const add = Buffer.byteLength(text); |
| 75 | if (size > 0 && size + add > maxBytes) rotate(); | |
| 105 | const today = dayOf(now()); | |
| 106 | if (size > 0 && (size + add > maxBytes || (o.maxAgeMs !== undefined && day !== undefined && day !== today))) rotate(); | |
| 76 | 107 | appendFileSync(file, text); |
| 77 | 108 | size += add; |
| 109 | day = today; | |
| 78 | 110 | } catch { |
| 79 | 111 | size = undefined; |
| 80 | 112 | } |
| @@ -97,8 +129,8 @@ export function keptLog(dataDir: string, o: { maxBytes?: number; keep?: number; | ||
| 97 | 129 | } |
| 98 | 130 | |
| 99 | 131 | /** Every kept line of `dataDir`, oldest file first, as written; [] when none was kept. */ |
| 100 | export function readKept(dataDir: string, keep = KEEP): string[] { | |
| 101 | const file = join(dataDir, KEPT_FILE); | |
| 132 | export function readKept(dataDir: string, keep = KEEP, name = KEPT_FILE): string[] { | |
| 133 | const file = join(dataDir, name); | |
| 102 | 134 | const out: string[] = []; |
| 103 | 135 | for (let n = keep; n >= 0; n--) { |
| 104 | 136 | const path = n === 0 ? file : `${file}.${n}`; |
src/spawn/clients.ts +7
| @@ -41,6 +41,7 @@ import { appLinkLines, type AppLinkLine } from "./app_links.ts"; | ||
| 41 | 41 | import { madeFromOf, type MadeFrom } from "./template_record.ts"; |
| 42 | 42 | import { NO_KEY_HELD, NO_KEY_HOST_LINE } from "../crew/no_key.ts"; |
| 43 | 43 | import { servedWindow } from "./served_window.ts"; |
| 44 | import { stateRows, stripWords } from "./state_history.ts"; | |
| 44 | 45 | |
| 45 | 46 | /** What a spawned forge says about itself to anyone: nothing more. */ |
| 46 | 47 | export interface ForgeState { |
| @@ -105,6 +106,11 @@ export interface ClientRow { | ||
| 105 | 106 | readonly awake?: boolean; |
| 106 | 107 | /** Why the host stopped it, while that explains its state (spawn/stopped.ts); a sentence. */ |
| 107 | 108 | readonly stopped?: string | null; |
| 109 | /** | |
| 110 | * The last 24 hours of its up, asleep and down changes as one mark an hour (`state_history.ts`, | |
| 111 | * #17909); null when none was recorded yet. | |
| 112 | */ | |
| 113 | readonly history?: { readonly marks: string; readonly says: string } | null; | |
| 108 | 114 | /** The apps this parent runs for the child; null when it runs none here. */ |
| 109 | 115 | readonly running: ChildAppsSummary | null; |
| 110 | 116 | /** |
| @@ -449,6 +455,7 @@ export async function clientRows(app: App, options: { probe?: boolean } = {}): P | ||
| 449 | 455 | keepBytes: reads[i]!.keep, |
| 450 | 456 | awake: childAwake(app, c.name), |
| 451 | 457 | stopped: stoppedWords(app, c), |
| 458 | history: stripWords(stateRows(app.db, c.name, Date.now()), Date.now()), | |
| 452 | 459 | running: hostedChildApps(app, c.name) ?? null, |
| 453 | 460 | reach: reachOf(app, c.name) ?? null, |
| 454 | 461 | spendTodayUsd: beats[i]?.beat.spendTodayUsd ?? null, |
src/spawn/state_history.ts added +118
| @@ -0,0 +1,118 @@ | ||
| 1 | /** | |
| 2 | * Each child forge's up, asleep, woken and down changes as rows with times (#17909), so "was it | |
| 3 | * down, or only asleep?" has an answer after a release replaced the container that saw it. | |
| 4 | * | |
| 5 | * - states: `up` (awake, and what a visitor gets is proved), `asleep` (not running; it wakes on | |
| 6 | * its next request), `woken` (up again after asleep), `down` (running, and its public addresses | |
| 7 | * do not answer: `reach.ts`'s proof); | |
| 8 | * - kept: a row only when the state changes, sampled each minute (`startStateWatch`), so a quiet | |
| 9 | * forge costs nothing and a day is a handful of rows; rows older than 8 days are dropped; | |
| 10 | * - read: `/forges` shows the last 24 hours of each as a strip, one mark an hour, and the terminal | |
| 11 | * says the same words (`stripWords`). A minute is the finest it tells; the stretch a release | |
| 12 | * itself was down is not seen from inside (the forge was not there to sample). | |
| 13 | */ | |
| 14 | import type { Database } from "bun:sqlite"; | |
| 15 | import type { App } from "../app.ts"; | |
| 16 | import { listChildren } from "../actions/spawn.ts"; | |
| 17 | import { background } from "../perf/jobs.ts"; | |
| 18 | import { reachOf } from "./reach.ts"; | |
| 19 | ||
| 20 | export type ForgeStateKind = "up" | "asleep" | "woken" | "down"; | |
| 21 | ||
| 22 | const SAMPLE_MS = 60_000; | |
| 23 | const HOUR = 3_600_000; | |
| 24 | const KEEP_MS = 8 * 24 * HOUR; | |
| 25 | const HOURS = 24; | |
| 26 | ||
| 27 | /** The state to record for a child, given what is known now. */ | |
| 28 | export function stateNow(awake: boolean, reachOk: boolean | undefined): ForgeStateKind { | |
| 29 | if (!awake) return "asleep"; | |
| 30 | return reachOk === false ? "down" : "up"; | |
| 31 | } | |
| 32 | ||
| 33 | /** | |
| 34 | * Record `state` for `name` when it differs from the last one (`woken` counts as `up`); true when a | |
| 35 | * row was written. | |
| 36 | */ | |
| 37 | export function noteState(db: Database, name: string, state: ForgeStateKind, at: number): boolean { | |
| 38 | const last = db.query("SELECT state FROM forge_state WHERE name = ?1 ORDER BY at DESC LIMIT 1").get(name) as { state: string } | null; | |
| 39 | if (last !== null) { | |
| 40 | if (last.state === state || (last.state === "woken" && state === "up")) return false; | |
| 41 | if (last.state === "asleep" && state === "up") state = "woken"; | |
| 42 | } | |
| 43 | db.query("INSERT INTO forge_state (name, state, at) VALUES (?1, ?2, ?3)").run(name, state, at); | |
| 44 | return true; | |
| 45 | } | |
| 46 | ||
| 47 | /** One pass: record every finished child's state, and drop what is past the 8 days. */ | |
| 48 | export async function sampleStates(app: App, awake: (name: string) => boolean, now = Date.now()): Promise<number> { | |
| 49 | let changed = 0; | |
| 50 | for (const child of await listChildren(app)) { | |
| 51 | if (!child.done) continue; | |
| 52 | if (noteState(app.db, child.name, stateNow(awake(child.name), reachOf(app, child.name)?.ok), now)) changed++; | |
| 53 | } | |
| 54 | app.db.query("DELETE FROM forge_state WHERE at < ?1").run(now - KEEP_MS); | |
| 55 | return changed; | |
| 56 | } | |
| 57 | ||
| 58 | /** Sample on a schedule, the first pass soon after boot. Returns the timer to clear. */ | |
| 59 | export function startStateWatch(app: App, awake: (name: string) => boolean, everyMs = SAMPLE_MS): ReturnType<typeof setInterval> { | |
| 60 | const first = setTimeout(() => void background("forge-state", () => sampleStates(app, awake), undefined, app), 5_000); | |
| 61 | app.closing.signal.addEventListener("abort", () => clearTimeout(first), { once: true }); | |
| 62 | return setInterval(() => void background("forge-state", () => sampleStates(app, awake), undefined, app), everyMs); | |
| 63 | } | |
| 64 | ||
| 65 | export interface StateRow { | |
| 66 | readonly state: ForgeStateKind; | |
| 67 | readonly at: number; | |
| 68 | } | |
| 69 | ||
| 70 | /** What the last 24 hours held for a forge: the last row before them, and every row in them. */ | |
| 71 | export function stateRows(db: Database, name: string, now: number): StateRow[] { | |
| 72 | const from = now - HOURS * HOUR; | |
| 73 | const before = db.query("SELECT state, at FROM forge_state WHERE name = ?1 AND at < ?2 ORDER BY at DESC LIMIT 1").get(name, from) as StateRow | null; | |
| 74 | const within = db.query("SELECT state, at FROM forge_state WHERE name = ?1 AND at >= ?2 AND at <= ?3 ORDER BY at").all(name, from, now) as StateRow[]; | |
| 75 | return before === null ? within : [before, ...within]; | |
| 76 | } | |
| 77 | ||
| 78 | const MARK: Record<ForgeStateKind | "none", string> = { up: "■", woken: "■", asleep: "·", down: "✕", none: " " }; | |
| 79 | ||
| 80 | /** | |
| 81 | * The strip's hours, oldest first: down if it was down at all in the hour, else what most of it | |
| 82 | * was. | |
| 83 | */ | |
| 84 | function strip(rows: readonly StateRow[], now: number): (ForgeStateKind | "none")[] { | |
| 85 | const out: (ForgeStateKind | "none")[] = []; | |
| 86 | for (let h = HOURS - 1; h >= 0; h--) { | |
| 87 | const end = now - h * HOUR; | |
| 88 | const start = end - HOUR; | |
| 89 | const spent: Record<string, number> = {}; | |
| 90 | for (let i = 0; i < rows.length; i++) { | |
| 91 | const row = rows[i]!; | |
| 92 | const next = rows[i + 1]?.at ?? now; | |
| 93 | const overlap = Math.min(next, end) - Math.max(row.at, start); | |
| 94 | if (overlap > 0) spent[row.state === "woken" ? "up" : row.state] = (spent[row.state === "woken" ? "up" : row.state] ?? 0) + overlap; | |
| 95 | } | |
| 96 | if ((spent["down"] ?? 0) > 0) out.push("down"); | |
| 97 | else if ((spent["up"] ?? 0) + (spent["asleep"] ?? 0) === 0) out.push("none"); | |
| 98 | else out.push((spent["up"] ?? 0) >= (spent["asleep"] ?? 0) ? "up" : "asleep"); | |
| 99 | } | |
| 100 | return out; | |
| 101 | } | |
| 102 | ||
| 103 | /** | |
| 104 | * The strip as text, oldest hour first, and the totals in words; null when nothing was recorded in | |
| 105 | * the day. | |
| 106 | */ | |
| 107 | export function stripWords(rows: readonly StateRow[], now: number): { readonly marks: string; readonly says: string } | null { | |
| 108 | const all = strip(rows, now); | |
| 109 | // Only the hours since the first row are marked: a forge's first day is not a day of question | |
| 110 | // marks. | |
| 111 | const first = all.findIndex((h) => h !== "none"); | |
| 112 | if (first < 0) return null; | |
| 113 | const hours = all.slice(first); | |
| 114 | const count = (k: string): number => hours.filter((h) => h === k).length; | |
| 115 | const parts = [`up ${count("up")} h`, `asleep ${count("asleep")} h`, `down ${count("down")} h`].filter((p) => !p.endsWith(" 0 h")); | |
| 116 | const began = first === 0 ? "" : `; recording began ${hours.length} h ago`; | |
| 117 | return { marks: hours.map((h) => MARK[h]).join(""), says: `${parts.join(", ")}${began}` }; | |
| 118 | } |
src/tui/screens/forges.ts +1 −1
| @@ -47,7 +47,7 @@ export function forgeLines(rows: readonly ClientRow[], sender = false, now = Dat | ||
| 47 | 47 | if (rows.length === 0) return [["", "You have not sent a forge yet"]]; |
| 48 | 48 | return rows.flatMap((r): [string, string][] => [[ |
| 49 | 49 | r.name, |
| 50 | [r.made ? (r.awake === true ? "awake" : "asleep") : null, r.made && r.where.inProcess ? r.where.says : null, r.stopped ?? null, crewHeldWords(r), r.attention === null ? null : ATTENTION_WORDS[r.attention], sender ? sentWords(r, now) : null, r.for === null ? null : `for ${r.for}`, CLAIM_WORDS[claimState(r)], linkWords(r.link, claimState(r) === "no" ? now : null), runningWords(r), seenLine(r, sender) !== null && r.stage?.key !== "tell" && r.stage?.key !== "crew" && r.stage?.resend !== true ? null : r.stage?.words ?? null, r.stage?.key === "crew" && r.nextStep.lastTellAt !== null ? `last tell ${timeAgo(r.nextStep.lastTellAt)}` : null, crewCountWords(r.crew), seenLine(r, sender), r.nextStep.words, spendWords(r)?.words ?? null, monthWords(r)?.words ?? null, creditWords(r), graceWords(r), useLine(r.size, r.use), r.made ? diskWords(r.disk) : null, activityPiece(r, sender, now), claimedWords(r), keepWords(r), r.archive === null || r.archive === undefined ? null : `proposed for archive: ${r.archive.why}`, r.lastHeartbeatAt === null ? "not checked in yet" : `checked in ${timeAgo(r.lastHeartbeatAt)}`] | |
| 50 | [r.made ? (r.awake === true ? "awake" : "asleep") : null, r.made && r.where.inProcess ? r.where.says : null, r.stopped ?? null, r.history === null || r.history === undefined ? null : `24 h ${r.history.marks} ${r.history.says}`, crewHeldWords(r), r.attention === null ? null : ATTENTION_WORDS[r.attention], sender ? sentWords(r, now) : null, r.for === null ? null : `for ${r.for}`, CLAIM_WORDS[claimState(r)], linkWords(r.link, claimState(r) === "no" ? now : null), runningWords(r), seenLine(r, sender) !== null && r.stage?.key !== "tell" && r.stage?.key !== "crew" && r.stage?.resend !== true ? null : r.stage?.words ?? null, r.stage?.key === "crew" && r.nextStep.lastTellAt !== null ? `last tell ${timeAgo(r.nextStep.lastTellAt)}` : null, crewCountWords(r.crew), seenLine(r, sender), r.nextStep.words, spendWords(r)?.words ?? null, monthWords(r)?.words ?? null, creditWords(r), graceWords(r), useLine(r.size, r.use), r.made ? diskWords(r.disk) : null, activityPiece(r, sender, now), claimedWords(r), keepWords(r), r.archive === null || r.archive === undefined ? null : `proposed for archive: ${r.archive.why}`, r.lastHeartbeatAt === null ? "not checked in yet" : `checked in ${timeAgo(r.lastHeartbeatAt)}`] | |
| 51 | 51 | .filter((m): m is string => m !== null) |
| 52 | 52 | .join(" · "), |
| 53 | 53 | ], ...firstScreenLines(r), ...appLinkLines(r), ...addressLines(r)]); |
src/web/pages/forges.ts +1
| @@ -109,6 +109,7 @@ export function forgeRow(r: ClientRow, now: number, reach?: ForgeReach, bill = f | ||
| 109 | 109 | r.made ? html`<span data-placement="${r.placement}"${r.where.inProcess ? html` data-in-process` : null}>${r.where.inProcess ? badge("in this forge's process", { tone: "attn" }) : null} ${r.where.says}</span>` : null, |
| 110 | 110 | r.made ? html`${sizeWords(r.size)}` : null, |
| 111 | 111 | r.made ? html`<span data-disk="${r.disk.own ? "own" : "shared"}">${diskWords(r.disk)}</span>` : null, |
| 112 | r.history === null || r.history === undefined ? null : html`<span class="state-strip" data-state-strip><span class="state-strip-marks" aria-hidden="true">${r.history.marks}</span> <span>Last 24 h: ${r.history.says}</span></span>`, | |
| 112 | 113 | runningNote(r), |
| 113 | 114 | spendNote(r), |
| 114 | 115 | monthNote(r), |
src/web/style/components.ts +4
| @@ -464,6 +464,10 @@ kbd { | ||
| 464 | 464 | .disk-line[data-tone="attn"] { color: color-mix(in srgb, var(--attn) 30%, var(--fg)); } |
| 465 | 465 | .disk-line[data-tone="attn"] svg { color: var(--attn); } |
| 466 | 466 | |
| 467 | /* ---- state-strip: a forge's last 24 hours, one mark an hour, on its own line (docs/design/areas/forges.md) */ | |
| 468 | .state-strip { display: block; white-space: nowrap; overflow-x: auto; color: var(--muted-fg); } | |
| 469 | .state-strip-marks { font-family: var(--mono); letter-spacing: 0.05em; color: var(--fg); } | |
| 470 | ||
| 467 | 471 | /* ---- look: a picture the forge took, in a hairline frame ---- |
| 468 | 472 | A strip sets a phone beside a desktop: the phone keeps a phone's |
| 469 | 473 | narrowness, the desktop takes what is left, never more than its own size; |
test/forge-state-history.test.ts added +155
| @@ -0,0 +1,155 @@ | ||
| 1 | /** | |
| 2 | * A child forge's up, asleep, woken and down changes are rows with times (#17909), and a forge's | |
| 3 | * log is kept across a restart, a file a day, a week of it (`perf/kept_log.ts` FORGE_LOG). | |
| 4 | */ | |
| 5 | import { afterAll, expect, test } from "bun:test"; | |
| 6 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 7 | import { existsSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { Database } from "bun:sqlite"; | |
| 11 | import { migrationFiles } from "../src/core/schema.ts"; | |
| 12 | import { migrate } from "../src/kernel/migrate.ts"; | |
| 13 | import { FORGE_LOG, keptLog, readKept } from "../src/perf/kept_log.ts"; | |
| 14 | import { noteState, sampleStates, stateNow, stateRows, stripWords } from "../src/spawn/state_history.ts"; | |
| 15 | ||
| 16 | const dirs: string[] = []; | |
| 17 | afterAll(async () => { | |
| 18 | for (const dir of dirs) await rm(dir, { recursive: true, force: true }); | |
| 19 | }); | |
| 20 | const fresh = async (): Promise<string> => { | |
| 21 | const dir = await mkdtemp(join(tmpdir(), "forge-state-")); | |
| 22 | dirs.push(dir); | |
| 23 | return dir; | |
| 24 | }; | |
| 25 | ||
| 26 | const HOUR = 3_600_000; | |
| 27 | const NOW = Date.UTC(2026, 11, 3, 12, 0, 0); | |
| 28 | ||
| 29 | async function database(dir: string): Promise<Database> { | |
| 30 | const db = new Database(join(dir, "forge.db")); | |
| 31 | migrate(db, migrationFiles); | |
| 32 | return db; | |
| 33 | } | |
| 34 | ||
| 35 | test("a state is a row only when it changes; asleep then up reads woken", async () => { | |
| 36 | const db = await database(await fresh()); | |
| 37 | expect(noteState(db, "grokbot", "up", NOW - 5 * HOUR)).toBe(true); | |
| 38 | expect(noteState(db, "grokbot", "up", NOW - 4 * HOUR)).toBe(false); | |
| 39 | expect(noteState(db, "grokbot", "asleep", NOW - 3 * HOUR)).toBe(true); | |
| 40 | expect(noteState(db, "grokbot", "up", NOW - 2 * HOUR)).toBe(true); | |
| 41 | expect(noteState(db, "grokbot", "up", NOW - HOUR)).toBe(false); | |
| 42 | expect(noteState(db, "grokbot", "down", NOW - 30 * 60_000)).toBe(true); | |
| 43 | expect(stateRows(db, "grokbot", NOW).map((r) => r.state)).toEqual(["up", "asleep", "woken", "down"]); | |
| 44 | expect(stateNow(true, false)).toBe("down"); | |
| 45 | expect(stateNow(false, false)).toBe("asleep"); | |
| 46 | expect(stateNow(true, undefined)).toBe("up"); | |
| 47 | }); | |
| 48 | ||
| 49 | test("the strip says down hours, asleep hours and what was not recorded", async () => { | |
| 50 | const db = await database(await fresh()); | |
| 51 | noteState(db, "a", "up", NOW - 10 * HOUR); | |
| 52 | noteState(db, "a", "asleep", NOW - 6 * HOUR); | |
| 53 | noteState(db, "a", "down", NOW - 3 * HOUR - 30 * 60_000); | |
| 54 | noteState(db, "a", "up", NOW - 2 * HOUR); | |
| 55 | const words = stripWords(stateRows(db, "a", NOW), NOW)!; | |
| 56 | // Only the ten hours since the first row are marked, and the words say when recording began. | |
| 57 | expect(words.marks).toBe("■■■■··✕✕■■"); | |
| 58 | expect(words.says).toBe("up 6 h, asleep 2 h, down 2 h; recording began 10 h ago"); | |
| 59 | expect(stripWords([], NOW)).toBeNull(); | |
| 60 | }); | |
| 61 | ||
| 62 | test("a restart keeps the previous run's state history and log lines", async () => { | |
| 63 | const dir = await fresh(); | |
| 64 | // The first run: a forge goes down, the log says so. | |
| 65 | let db = await database(dir); | |
| 66 | noteState(db, "grokbot", "up", NOW - 4 * HOUR); | |
| 67 | noteState(db, "grokbot", "down", NOW - 2 * HOUR); | |
| 68 | const first = keptLog(dir, { ...FORGE_LOG, now: () => NOW }); | |
| 69 | first.add("2026-12-03T10:00:00.000Z WARN [forge] child forge did not answer name=grokbot"); | |
| 70 | first.stop(); | |
| 71 | db.close(); | |
| 72 | // The next run, a release later, reads both. | |
| 73 | db = await database(dir); | |
| 74 | const second = keptLog(dir, { ...FORGE_LOG, now: () => NOW + 60_000 }); | |
| 75 | second.add("2026-12-03T12:01:00.000Z INFO [forge] forge is up"); | |
| 76 | second.stop(); | |
| 77 | expect(stateRows(db, "grokbot", NOW).map((r) => r.state)).toEqual(["up", "down"]); | |
| 78 | const lines = readKept(dir, FORGE_LOG.keep, FORGE_LOG.file); | |
| 79 | expect(lines).toHaveLength(2); | |
| 80 | expect(lines[0]).toContain("did not answer name=grokbot"); | |
| 81 | expect(lines[1]).toContain("forge is up"); | |
| 82 | }); | |
| 83 | ||
| 84 | test("the log is a file a day, and files past a week are dropped", async () => { | |
| 85 | const dir = await fresh(); | |
| 86 | let now = NOW; | |
| 87 | const log = keptLog(dir, { ...FORGE_LOG, now: () => now }); | |
| 88 | log.add("day one"); | |
| 89 | log.flush(); | |
| 90 | const live = join(dir, FORGE_LOG.file); | |
| 91 | utimesSync(live, new Date(NOW), new Date(NOW)); | |
| 92 | now = NOW + 86_400_000; | |
| 93 | log.add("day two"); | |
| 94 | log.flush(); | |
| 95 | expect(existsSync(`${live}.1`)).toBe(true); | |
| 96 | expect(readKept(dir, FORGE_LOG.keep, FORGE_LOG.file)).toEqual(["day one", "day two"]); | |
| 97 | // A rotated file whose newest line is eight days old goes at the next rotation. | |
| 98 | writeFileSync(`${live}.1`, "old\n"); | |
| 99 | utimesSync(`${live}.1`, new Date(NOW - 8 * 86_400_000), new Date(NOW - 8 * 86_400_000)); | |
| 100 | utimesSync(live, new Date(now), new Date(now)); | |
| 101 | now += 86_400_000; | |
| 102 | log.add("day three"); | |
| 103 | log.stop(); | |
| 104 | const all = readKept(dir, FORGE_LOG.keep, FORGE_LOG.file); | |
| 105 | expect(all).not.toContain("old"); | |
| 106 | expect(all).toEqual(["day two", "day three"]); | |
| 107 | }); | |
| 108 | ||
| 109 | // The sampler, the page and the terminal, over a real child. | |
| 110 | import { spawnForge } from "../src/actions/spawn.ts"; | |
| 111 | import { createApp, type App } from "../src/app.ts"; | |
| 112 | import type { Ctx } from "../src/http/context.ts"; | |
| 113 | import { createUser, type User } from "../src/core/users.ts"; | |
| 114 | import { hostedPlacement } from "../src/spawn/placement.ts"; | |
| 115 | import { clientRows } from "../src/spawn/clients.ts"; | |
| 116 | import { forgesPage } from "../src/web/pages/forges.ts"; | |
| 117 | import { forgeLines } from "../src/tui/screens/forges.ts"; | |
| 118 | ||
| 119 | test("a sample records each child's state, /forges and the terminal show the strip", async () => { | |
| 120 | const dir = mkdtempSync(join(tmpdir(), "forge-state-app-")); | |
| 121 | dirs.push(dir); | |
| 122 | const app: App = createApp({ dataDir: dir, url: "https://forge.test", port: 0 }); | |
| 123 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", isAdmin: true }); | |
| 124 | if (!made.ok) throw new Error("user"); | |
| 125 | const admin: User = made.value; | |
| 126 | const s = await spawnForge( | |
| 127 | app, | |
| 128 | admin, | |
| 129 | { name: "grokbot", org: "grokbot", apps: [], carryBriefs: false, carrySubscriptions: false }, | |
| 130 | { catalog: [], briefs: [], subscriptions: [] }, | |
| 131 | { | |
| 132 | placement: hostedPlacement({ host: "forge.test" }), | |
| 133 | request: new Request("https://forge.test/spawn", { method: "POST", headers: { origin: "https://forge.test" } }), | |
| 134 | url: new URL("https://forge.test/spawn"), | |
| 135 | }, | |
| 136 | ); | |
| 137 | if (!s.ok) throw new Error(JSON.stringify(s.error)); | |
| 138 | const now = Date.now(); | |
| 139 | expect(await sampleStates(app, () => true, now - 2 * HOUR)).toBe(1); | |
| 140 | expect(await sampleStates(app, () => true, now - HOUR)).toBe(0); | |
| 141 | expect(await sampleStates(app, () => false, now - 30 * 60_000)).toBe(1); | |
| 142 | expect((app.db.query("SELECT state FROM forge_state ORDER BY at").all() as { state: string }[]).map((r) => r.state)).toEqual(["up", "asleep"]); | |
| 143 | const request = new Request("https://forge.test/forges"); | |
| 144 | const ctx: Ctx = { app, request, url: new URL(request.url), params: {}, auth: { user: admin, scope: "rw", via: "session" }, theme: undefined }; | |
| 145 | const body = await (await forgesPage(ctx)).text(); | |
| 146 | expect(body).toContain("data-state-strip"); | |
| 147 | expect(body).toContain('class="state-strip"'); | |
| 148 | expect(body).toContain("■"); | |
| 149 | expect(body).toContain("Last 24 h: "); | |
| 150 | expect(body).not.toContain("not recorded"); | |
| 151 | expect(body).not.toContain(" title=\"Last 24"); | |
| 152 | const lines = forgeLines(await clientRows(app)).map((l) => l[1]).join("\n"); | |
| 153 | expect(lines).toMatch(/24 h \S+ .*recording began/); | |
| 154 | rmSync(dir, { recursive: true, force: true }); | |
| 155 | }); |
test/job-slices.test.ts +2
| @@ -37,6 +37,7 @@ import { runAheadReads } from "../src/origins/ahead.ts"; | ||
| 37 | 37 | import { runGuardSweep } from "../src/origins/credential.ts"; |
| 38 | 38 | import { sweepMirrorPulls } from "../src/origins/mirror-pulls.ts"; |
| 39 | 39 | import { sweepReach } from "../src/spawn/reach.ts"; |
| 40 | import { sampleStates } from "../src/spawn/state_history.ts"; | |
| 40 | 41 | import { checkUpstream as checkParent } from "../src/spawn/upstream.ts"; |
| 41 | 42 | import { census, censusWords, processRows } from "../src/kernel/census.ts"; |
| 42 | 43 | import { runDelivery } from "../src/core/webhooks.ts"; |
| @@ -216,6 +217,7 @@ function jobs(): Record<string, () => unknown> { | ||
| 216 | 217 | "guard-sweep": () => runGuardSweep(app), |
| 217 | 218 | "mirror-pulls": () => sweepMirrorPulls(app), |
| 218 | 219 | reach: () => sweepReach(app), |
| 220 | "forge-state": () => sampleStates(app, () => false), | |
| 219 | 221 | upstream: () => checkParent(app), |
| 220 | 222 | // Its first pass on start tells and pages everyone (`tell(id, true)`, then `page`), a superset |
| 221 | 223 | // of the clock's tick. |
new above
offline
Principle 2: before the first recorded row every hour is
?, so a new forge shows a day of question marks. Start the strip at the first row and say when recording began in words.