Public: anyone can read this; the crew can change it.
/system shows one line per maintenance worker: what it found this week and what it did about it #12445
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/12436-system-shows-one-line-per-maintenance-wo → main 11 commits fork 3 threads · 3 unresolved
12 files
changed +349
−8
docs/MCP.md +1 −1
| @@ -215,7 +215,7 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`; | ||
| 215 | 215 | | `subscription_wake` | — | Admin: wake a resting subscription | 168 | |
| 216 | 216 | | `subscriptions` | — | Claude accounts: scopes, budgets | 158 | |
| 217 | 217 | | `sync` | — | Sync a mirror now; `originId` reconnects it | 197 | |
| 218 | | `system` | `csp`, `routes`, `footing`, `offsite`, `size` | The forge machine now: CPU, memory, disk, network | 313 | | |
| 218 | | `system` | `csp`, `routes`, `footing`, `offsite`, `size`, `maintenance` | The forge machine now: CPU, memory, disk, network | 327 | | |
| 219 | 219 | | `take_back` | — | Open the pull that undoes a shipped pull | 219 | |
| 220 | 220 | | `take_updates` | — | Take the parent forge's updates into a fork | 176 | |
| 221 | 221 | | `teams` | — | Crew teams for person admins: charter, dial (0–100) and member agents | 338 | |
docs/design/attention-budget.json +4 −4
| @@ -173,13 +173,13 @@ | ||
| 173 | 173 | }, |
| 174 | 174 | "system": { |
| 175 | 175 | "390": { |
| 176 | "words": 218, | |
| 177 | "blocks": 73, | |
| 176 | "words": 230, | |
| 177 | "blocks": 75, | |
| 178 | 178 | "colours": 0 |
| 179 | 179 | }, |
| 180 | 180 | "1280": { |
| 181 | "words": 218, | |
| 182 | "blocks": 73, | |
| 181 | "words": 230, | |
| 182 | "blocks": 75, | |
| 183 | 183 | "colours": 0 |
| 184 | 184 | }, |
| 185 | 185 | "note": "Measured on the test forge's empty state with the machine reading replaced by an empty one and the two cell-cap sentences fixed (the live page's counts depend on the host's cores, disks, processes and cgroups); nothing seeded or waited for. Blocks 65 -> 67 (#11805): the off-site backup section's heading and one-sentence state stay on first view so a red lane is seen without a click; its rows sit behind the disclosure. Blocks 67 -> 69 (#12010): the database size section's heading and its one-sentence state (the file's size and growth, a badge when either is worth a look) stay on first view, as the off-site lane's do; its fact rows and the table of the ten largest tables and indexes sit behind the disclosure. Words +22, blocks +1 (#12092): the footprint section's heading and its one-sentence state (on an empty forge, not read yet and the memory budget) stay on first view; the measured facts and the optional parts sit behind the disclosure. Words +6, blocks +2 (#12420): the stale-pulls section's heading and \"None.\" on a forge with no quiet pull." |
docs/features/maintenance-week.md added +33
| @@ -0,0 +1,33 @@ | ||
| 1 | # Maintenance, last 7 days (#12436) | |
| 2 | ||
| 3 | One line per maintenance worker: how many things it found in the last seven | |
| 4 | days, how many it acted on, and when it last ran (even if that was before the | |
| 5 | week). A worker that has never run is still a line, reading "not yet run". A | |
| 6 | run stopped by its budget is not counted as a run. | |
| 7 | ||
| 8 | All three doors are for a forge admin, or an agent granted `telemetry:read`. | |
| 9 | ||
| 10 | ## On /system | |
| 11 | ||
| 12 | Under **Maintenance, last 7 days**, one sentence says how many workers found | |
| 13 | something this week. Open it to see each worker's found and acted counts and | |
| 14 | its last run. | |
| 15 | ||
| 16 | ## In the terminal | |
| 17 | ||
| 18 | Open the palette and choose **Maintenance, last 7 days**. The first line is the | |
| 19 | same sentence; below it, a line per worker. `j`/`k` scroll, `esc` closes. | |
| 20 | ||
| 21 | ## Over MCP | |
| 22 | ||
| 23 | json | |
| 24 | { "name": "system", "arguments": { "kind": "maintenance" } } | |
| 25 | ||
| 26 | ||
| 27 | answers `{ workers: [{ name, found, acted, last }] }`, `last` an ISO time or | |
| 28 | null. Anyone without the gate is refused as `forbidden`. | |
| 29 | ||
| 30 | ## Keeping it true | |
| 31 | ||
| 32 | The rows are `weekRows` in `src/maintain/week_line.ts`, one grouped query over | |
| 33 | `maintenance_run`; the page, the terminal and the MCP tool all read it. |
src/http/mcp/tools/system.ts +11 −3
| @@ -11,14 +11,16 @@ import { footing, riskLines } from "../../../system/footing.ts"; | ||
| 11 | 11 | import { laneWords, readOffsiteLane } from "../../../snapshot/offsite_lane.ts"; |
| 12 | 12 | import { largestDirs } from "../../../system/largest_dirs.ts"; |
| 13 | 13 | import { dbSize } from "../../../system/db_size.ts"; |
| 14 | import { weekRows } from "../../../maintain/week_line.ts"; | |
| 15 | import { duties } from "../../../maintain/registry.ts"; | |
| 14 | 16 | import { good, bad, type Tool } from "../shared.ts"; |
| 15 | 17 | |
| 16 | 18 | export const tool: Tool = { |
| 17 | 19 | name: "system", |
| 18 | doc: "the machine the forge runs on, now: CPU, load, memory, disk, network, processes, `largestDirs`: the five largest directories under the forge's data as {at, dirs: [{name, bytes}]} (null while first measured; at most once a minute), `stalls`: the last hour's main-thread stalls by route (`<route> (in flight)` when still running at the wake), or `job:<name>`, as {cause, ms, count}, `readings`: the last 20 minutes' worst loop lag as {at, ms, what} beside `barMs` (100) and `over`, and `readers`: who polls the telemetry and how fast, `{ kind: \"routes\" }`: the 10 slowest budgeted routes as {route, p95Ms, budgetMs, n, slowestPhase}, over budget first; a forge admin, or an agent granted `telemetry:read`. `{ kind: \"csp\" }`: the last 24 h of Content-Security-Policy violations browsers reported, `{ directive, n, newest }` per directive (`newest` the blocked host last counted), most first, counted per UTC hour from `since`, and `scriptErrors` `{ page, where, message, n, last }`, as the security page reads them; a forge admin only. `{ kind: \"footing\" }`: what the forge stands on (#11685), as /system's \"What the forge stands on\": `forgeNode`, and per piece `{ id, need, what, machine, seen, risk, ifDies, issues }` read from the live cluster, with `risks`, one line per piece not on the forge's machine; a forge admin only. `{ kind: \"offsite\" }`: the off-site backup lane (#11805), as /system's \"Off-site backup\" and the terminal's: `{ health, says, where, sealed, lastSuccess, newest, error, drill: { at, verdict, from, offSite, reason } | null }`; a forge admin only. `{ kind: \"size\" }`: the database's size (#12010), as /system's \"Database size\": `{ fileBytes, walBytes, growth: { perDay, days, readings: [{day, bytes}] }, walk: { at, pageSize, freeBytes, tables: [{name, bytes, rows}], indexes: [{name, table, bytes}] } | null }`, ten of each, largest first, the walk at most an hour old (null while the first runs); a forge admin, or an agent granted `telemetry:read`", | |
| 20 | doc: "the machine the forge runs on, now: CPU, load, memory, disk, network, processes, `largestDirs`: the five largest directories under the forge's data as {at, dirs: [{name, bytes}]} (null while first measured; at most once a minute), `stalls`: the last hour's main-thread stalls by route (`<route> (in flight)` when still running at the wake), or `job:<name>`, as {cause, ms, count}, `readings`: the last 20 minutes' worst loop lag as {at, ms, what} beside `barMs` (100) and `over`, and `readers`: who polls the telemetry and how fast, `{ kind: \"routes\" }`: the 10 slowest budgeted routes as {route, p95Ms, budgetMs, n, slowestPhase}, over budget first; a forge admin, or an agent granted `telemetry:read`. `{ kind: \"csp\" }`: the last 24 h of Content-Security-Policy violations browsers reported, `{ directive, n, newest }` per directive (`newest` the blocked host last counted), most first, counted per UTC hour from `since`, and `scriptErrors` `{ page, where, message, n, last }`, as the security page reads them; a forge admin only. `{ kind: \"footing\" }`: what the forge stands on (#11685), as /system's \"What the forge stands on\": `forgeNode`, and per piece `{ id, need, what, machine, seen, risk, ifDies, issues }` read from the live cluster, with `risks`, one line per piece not on the forge's machine; a forge admin only. `{ kind: \"offsite\" }`: the off-site backup lane (#11805), as /system's \"Off-site backup\" and the terminal's: `{ health, says, where, sealed, lastSuccess, newest, error, drill: { at, verdict, from, offSite, reason } | null }`; a forge admin only. `{ kind: \"size\" }`: the database's size (#12010), as /system's \"Database size\": `{ fileBytes, walBytes, growth: { perDay, days, readings: [{day, bytes}] }, walk: { at, pageSize, freeBytes, tables: [{name, bytes, rows}], indexes: [{name, table, bytes}] } | null }`, ten of each, largest first, the walk at most an hour old (null while the first runs); a forge admin, or an agent granted `telemetry:read`. `{ kind: \"maintenance\" }`: one row per maintenance worker, 7 days, `{ name, found, acted, last }` (`last` null: not yet run); admin or `telemetry:read`", | |
| 19 | 21 | description: |
| 20 | 22 | "The forge machine now: CPU, memory, disk, network. Admin or telemetry:read; `kind: csp`: 24 h of CSP violations (admin).", |
| 21 | inputSchema: { type: "object", properties: { kind: { type: "string", enum: ["csp", "routes", "footing", "offsite", "size"] } } }, | |
| 23 | inputSchema: { type: "object", properties: { kind: { type: "string", enum: ["csp", "routes", "footing", "offsite", "size", "maintenance"] } } }, | |
| 22 | 24 | writes: false, |
| 23 | 25 | async run(ctx, user, args) { |
| 24 | 26 | if (args["kind"] !== undefined) { |
| @@ -34,6 +36,12 @@ export const tool: Tool = { | ||
| 34 | 36 | noteRead(ctx.app, user, reader, "system"); |
| 35 | 37 | return good(await dbSize.read(ctx.app.db, ctx.app.config.dataDir, undefined, ctx.app.log)); |
| 36 | 38 | } |
| 39 | if (args["kind"] === "maintenance") { | |
| 40 | const reader = telemetryReader(ctx.app, user); | |
| 41 | if (!reader) return bad("forbidden", "only an admin of this forge, or an agent granted telemetry:read, reads its maintenance workers"); | |
| 42 | noteRead(ctx.app, user, reader, "system"); | |
| 43 | return good({ workers: weekRows(ctx.app.db, duties.map((d) => d.name)) }); | |
| 44 | } | |
| 37 | 45 | if (args["kind"] === "footing") { |
| 38 | 46 | if (!user.isAdmin) return bad("forbidden", "only an admin of this forge reads what it stands on"); |
| 39 | 47 | const f = await footing.read(); |
| @@ -44,7 +52,7 @@ export const tool: Tool = { | ||
| 44 | 52 | const lane = readOffsiteLane(ctx.app.config.dataDir, ctx.app.db); |
| 45 | 53 | return good({ ...lane, says: laneWords(lane) }); |
| 46 | 54 | } |
| 47 | if (args["kind"] !== "csp") return bad("invalid", "kind is csp, routes, footing, offsite, size, or absent for the machine"); | |
| 55 | if (args["kind"] !== "csp") return bad("invalid", "kind is csp, routes, footing, offsite, size, maintenance, or absent for the machine"); | |
| 48 | 56 | if (!user.isAdmin) return bad("forbidden", "only an admin of this forge reads its CSP violations"); |
| 49 | 57 | const now = new Date(); |
| 50 | 58 | return good({ hours: 24, since: windowStart(24, now).toISOString(), directives: violationsByDirective(ctx.app.db, 24, now), scriptErrors: scriptErrorCounts(ctx.app.db, 24, now) }); |
src/maintain/week_line.ts added +58
| @@ -0,0 +1,58 @@ | ||
| 1 | /** One line per maintenance worker for the last seven days (#12436): what it found, what it did, | |
| 2 | * when it last ran. */ | |
| 3 | ||
| 4 | import type { Database } from "bun:sqlite"; | |
| 5 | ||
| 6 | export const WEEK_MS = 7 * 24 * 60 * 60 * 1000; | |
| 7 | ||
| 8 | /** What `maintenance_run` holds for one worker, summed by the database. */ | |
| 9 | export interface WorkerTally { | |
| 10 | readonly duty: string; | |
| 11 | /** Findings and actions over runs that started inside the window. */ | |
| 12 | readonly found: number; | |
| 13 | readonly acted: number; | |
| 14 | /** The worker's newest real start (ISO), in the window or not; null when it never ran. */ | |
| 15 | readonly last: string | null; | |
| 16 | } | |
| 17 | ||
| 18 | export interface WeekRow { | |
| 19 | readonly name: string; | |
| 20 | readonly found: number; | |
| 21 | readonly acted: number; | |
| 22 | /** ISO time of the last run; null reads "not yet run". */ | |
| 23 | readonly last: string | null; | |
| 24 | } | |
| 25 | ||
| 26 | /** One grouped, index-served statement: every duty's sums, a budget stop not counting as a run. */ | |
| 27 | export function tallies(db: Database, now: Date): WorkerTally[] { | |
| 28 | const since = new Date(now.getTime() - WEEK_MS).toISOString(); | |
| 29 | return db | |
| 30 | .query( | |
| 31 | `SELECT duty, | |
| 32 | COALESCE(SUM(CASE WHEN started >= ?1 THEN json_array_length(findings) END), 0) AS found, | |
| 33 | COALESCE(SUM(CASE WHEN started >= ?1 THEN json_array_length(actions) END), 0) AS acted, | |
| 34 | MAX(started) AS last | |
| 35 | FROM maintenance_run WHERE outcome NOT LIKE 'budget:%' GROUP BY duty`, | |
| 36 | ) | |
| 37 | .all(since) as WorkerTally[]; | |
| 38 | } | |
| 39 | ||
| 40 | /** Pure: a row per named worker, in the given order; a worker with no run is still a row. */ | |
| 41 | export function weekLine(workers: readonly string[], tally: readonly WorkerTally[]): WeekRow[] { | |
| 42 | const by = new Map(tally.map((t) => [t.duty, t])); | |
| 43 | return workers.map((name) => { | |
| 44 | const t = by.get(name); | |
| 45 | return { name, found: t?.found ?? 0, acted: t?.acted ?? 0, last: t?.last ?? null }; | |
| 46 | }); | |
| 47 | } | |
| 48 | ||
| 49 | /** The rows for the forge's own workers. */ | |
| 50 | export function weekRows(db: Database, workers: readonly string[], now = new Date()): WeekRow[] { | |
| 51 | return weekLine(workers, tallies(db, now)); | |
| 52 | } | |
| 53 | ||
| 54 | /** The one sentence on first view: how many workers found something this week. */ | |
| 55 | export function weekWords(rows: readonly WeekRow[]): string { | |
| 56 | const found = rows.filter((r) => r.found > 0).length; | |
| 57 | return `${String(found)} of ${String(rows.length)} workers found something this week`; | |
| 58 | } |
src/tui/screens/entries.ts +2
| @@ -64,6 +64,7 @@ import { entry as economics } from "./economics.ts"; | ||
| 64 | 64 | import { entry as money } from "./money.ts"; |
| 65 | 65 | import { entry as loopStalls } from "./loopstalls.ts"; |
| 66 | 66 | import { entry as footing } from "./footing.ts"; |
| 67 | import { entry as maintenanceWeek } from "./maintenanceweek.ts"; | |
| 67 | 68 | import { entry as offsite } from "./offsite.ts"; |
| 68 | 69 | import { entry as waiting } from "./waiting.ts"; |
| 69 | 70 | import { entry as slowPagesEntry } from "./slowpages.ts"; |
| @@ -133,6 +134,7 @@ export const ENTRIES: readonly PaletteEntry[] = [ | ||
| 133 | 134 | system, |
| 134 | 135 | loopStalls, |
| 135 | 136 | footing, |
| 137 | maintenanceWeek, | |
| 136 | 138 | offsite, |
| 137 | 139 | waiting, |
| 138 | 140 | slowPagesEntry, |
src/tui/screens/maintenanceweek.ts added +65
| @@ -0,0 +1,65 @@ | ||
| 1 | /** | |
| 2 | * The maintenance workers' week, in the terminal (#12436): the rows /system shows under | |
| 3 | * "Maintenance, last 7 days" and the MCP `system` tool answers for `kind: maintenance` — | |
| 4 | * one line per worker: what it found, what it did, when it last ran. The gate is theirs | |
| 5 | * (`telemetryReader`: a forge admin, or an agent granted `telemetry:read`). Read-only. | |
| 6 | */ | |
| 7 | ||
| 8 | import { telemetryReader } from "../../actions/telemetry.ts"; | |
| 9 | import { duties } from "../../maintain/registry.ts"; | |
| 10 | import { weekRows, weekWords } from "../../maintain/week_line.ts"; | |
| 11 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 12 | import { binding } from "../app/keys.ts"; | |
| 13 | import type { Session } from "../session.ts"; | |
| 14 | import { style } from "../term/style.ts"; | |
| 15 | import { pad } from "../term/width.ts"; | |
| 16 | import { Scroll, drawLines, hitScroll } from "./common.ts"; | |
| 17 | import type { PaletteEntry } from "./entries.ts"; | |
| 18 | ||
| 19 | const mayRead = (session: Session): boolean => telemetryReader(session.app, session.user) !== undefined; | |
| 20 | ||
| 21 | /** The screen's lines; empty for anyone the gate refuses. */ | |
| 22 | export function weekLines(session: Session, now = new Date()): string[] { | |
| 23 | if (!mayRead(session)) return []; | |
| 24 | const rows = weekRows(session.app.db, duties.map((d) => d.name), now); | |
| 25 | const width = Math.max(0, ...rows.map((r) => r.name.length)); | |
| 26 | return [ | |
| 27 | weekWords(rows), | |
| 28 | "", | |
| 29 | ...rows.map((r) => | |
| 30 | r.last === null | |
| 31 | ? `${pad(r.name, width)} not yet run` | |
| 32 | : `${pad(r.name, width)} found ${String(r.found)} · acted ${String(r.acted)} · last ${r.last.slice(0, 16).replace("T", " ")}Z`), | |
| 33 | ]; | |
| 34 | } | |
| 35 | ||
| 36 | export function weekScreen(session: Session, ctx: Ctx): Screen { | |
| 37 | const scroll = new Scroll(); | |
| 38 | return { | |
| 39 | title: "Maintenance, last 7 days", | |
| 40 | keys: [binding(["j", "k"], "scroll"), binding(["esc", "q"], "back")], | |
| 41 | render(area, s) { | |
| 42 | const c = ctx.theme.c; | |
| 43 | const lines = weekLines(session); | |
| 44 | drawLines(s, area, c, scroll, lines.map((text, i) => [{ text, style: style(i === 0 ? c.fg : c.mutedFg, c.bg) }])); | |
| 45 | hitScroll(ctx, area, scroll, lines.length); | |
| 46 | }, | |
| 47 | key(e) { | |
| 48 | if (scroll.key(e, weekLines(session).length)) return true; | |
| 49 | if (e.key === "esc" || e.key === "q") { | |
| 50 | ctx.pop(); | |
| 51 | return true; | |
| 52 | } | |
| 53 | return false; | |
| 54 | }, | |
| 55 | }; | |
| 56 | } | |
| 57 | ||
| 58 | export const entry: PaletteEntry = { | |
| 59 | id: "maintenanceweek", | |
| 60 | title: "Maintenance, last 7 days", | |
| 61 | hint: "what each maintenance worker found and did this week", | |
| 62 | after: ["footing", "stalls", "system"], | |
| 63 | offered: mayRead, | |
| 64 | run: (session, ctx) => ctx.push(weekScreen(session, ctx)), | |
| 65 | }; |
src/web/pages/system.ts +18
| @@ -61,6 +61,8 @@ import { shapeWords } from "../../engine/mode.ts"; | ||
| 61 | 61 | import { badge, chartBox, disclosure, meter, pill, row, time } from "../ui.ts"; |
| 62 | 62 | import { LARGEST_DIRS, largestDirs, type LargestDirs } from "../../system/largest_dirs.ts"; |
| 63 | 63 | import { DB_FILE_CAP, DB_GROWTH_MAX, TOP, dbSize, dbSizeNeed, type DbSize } from "../../system/db_size.ts"; |
| 64 | import { weekRows, weekWords, type WeekRow } from "../../maintain/week_line.ts"; | |
| 65 | import { duties } from "../../maintain/registry.ts"; | |
| 64 | 66 | import { childDirOf, listChildren } from "../../actions/spawn.ts"; |
| 65 | 67 | import { childrenUse, mibWords, realSelf, selfUse, shareOf, sizeWords, useWords, type ChildUseRow, type SelfUse } from "../../spawn/usage.ts"; |
| 66 | 68 | |
| @@ -141,6 +143,21 @@ export function dbSizeSection(size: DbSize): Html { | ||
| 141 | 143 | <p class="muted small">Measured ${time(w.at)}, at most once an hour.</p>`}`, { id: "sys-db-detail" })}</section>`; |
| 142 | 144 | } |
| 143 | 145 | |
outdated
Principle 1: say in one sentence what this section tells (e.g. 'N of M workers found something this week'). Also box 5: this adds 24 words / 6 blocks to first view and the budget file was raised; fold the rows behind a |
||
| 146 | /** One line per maintenance worker: what it found this week, what it did, when it last ran | |
| 147 | * (#12436). */ | |
| 148 | export function maintenanceSection(rows: readonly WeekRow[]): Html { | |
| 149 | // First sight: the heading and one sentence; the rows open behind one disclosure. | |
| 150 | return html`<section class="settings-block" id="sys-maintenance"><h2>Maintenance, last 7 days</h2> | |
| 151 | ${disclosure(weekWords(rows), html`<ul class="list" aria-label="Each maintenance worker: found, acted, last run">${rows.map((r) => | |
| 152 | row({ | |
| 153 | title: r.name, | |
| 154 | meta: html`${r.last === null ? null : html`found ${String(r.found)} · acted ${String(r.acted)}`}`, | |
| 155 | trail: r.last === null ? html`<span class="muted">not yet run</span>` : time(r.last), | |
| 156 | data: { worker: r.name, found: String(r.found), acted: String(r.acted) }, | |
| 157 | }), | |
| 158 | )}</ul>`)}</section>`; | |
| 159 | } | |
| 160 | ||
| 144 | 161 | /** This forge's own size and use when it is a child in a cell (#10853); nothing on any other forge. */ |
| 145 | 162 | export function selfSection(self: SelfUse | null): Html { |
| 146 | 163 | if (self === null) return html``; |
| @@ -632,6 +649,7 @@ export async function systemPage(ctx: Ctx): Promise<Response> { | ||
| 632 | 649 | <div class="js-only small muted">Sort by <button class="btn" data-size="sm" type="button" data-sort="cpu" aria-pressed="true"><kbd>c</kbd> CPU</button> |
| 633 | 650 | <button class="btn" data-size="sm" type="button" data-sort="mem" aria-pressed="false"><kbd>m</kbd> memory</button></div> |
| 634 | 651 | <div id="sys-procs" data-live-hold>${at("sys-procs")}</div></section> |
| 652 | ${maintenanceSection(timePhase(ctx.request, "maintenance", () => weekRows(ctx.app.db, duties.map((d) => d.name))))} | |
| 635 | 653 | ${footprintSection(lastFootprint() ?? lastProof(ctx.app.config.dataDir)?.footprint ?? null)} |
| 636 | 654 | ${footingSection(standsOn)} |
| 637 | 655 | ${offsiteSection(timePhase(ctx.request, "offsite", () => readOffsiteLane(ctx.app.config.dataDir, ctx.app.db)))} |
test/maintain-week-line.test.ts added +49
| @@ -0,0 +1,49 @@ | ||
| 1 | import { expect, test } from "bun:test"; | |
Add MCP-kind and terminal-screen tests, and a /system page test through the route; the only page test here calls maintenanceSection directly. |
||
| 2 | import { Database } from "bun:sqlite"; | |
| 3 | import { WEEK_MS, weekRows } from "../src/maintain/week_line.ts"; | |
| 4 | ||
| 5 | const now = new Date("2026-11-14T12:00:00.000Z"); | |
| 6 | function db(): Database { | |
| 7 | const d = new Database(":memory:"); | |
| 8 | d.run("CREATE TABLE maintenance_run (id INTEGER PRIMARY KEY AUTOINCREMENT, duty TEXT, started TEXT, finished TEXT, findings TEXT, actions TEXT, probes TEXT, outcome TEXT)"); | |
| 9 | return d; | |
| 10 | } | |
| 11 | const add = (d: Database, duty: string, at: number, f: number, a: number, outcome = "ok") => | |
| 12 | d.query("INSERT INTO maintenance_run (duty, started, finished, findings, actions, probes, outcome) VALUES (?1,?2,?2,?3,?4,'[]',?5)").run( | |
| 13 | duty, new Date(at).toISOString(), JSON.stringify(Array(f).fill("x")), JSON.stringify(Array(a).fill("y")), outcome); | |
| 14 | ||
| 15 | test("counts at the seven-day edge: exactly seven days is in, a millisecond older is out", () => { | |
| 16 | const d = db(); | |
| 17 | add(d, "a", now.getTime() - WEEK_MS, 2, 1); | |
| 18 | add(d, "a", now.getTime() - WEEK_MS - 1, 5, 5); | |
| 19 | const [r] = weekRows(d, ["a"], now); | |
| 20 | expect([r!.found, r!.acted]).toEqual([2, 1]); | |
| 21 | }); | |
| 22 | ||
| 23 | test("a worker with no run is a row, not hidden", () => { | |
| 24 | expect(weekRows(db(), ["idle"], now)).toEqual([{ name: "idle", found: 0, acted: 0, last: null }]); | |
| 25 | }); | |
| 26 | ||
| 27 | test("an idle week still shows the last run; two workers are told apart; budget stops do not count", () => { | |
| 28 | const d = db(); | |
| 29 | const old = now.getTime() - 20 * 86400_000; | |
| 30 | add(d, "a", old, 3, 3); | |
| 31 | add(d, "b", now.getTime() - 1000, 1, 0); | |
| 32 | add(d, "b", now.getTime(), 4, 4, "budget:runs"); | |
| 33 | const rows = weekRows(d, ["a", "b"], now); | |
| 34 | expect(rows[0]).toEqual({ name: "a", found: 0, acted: 0, last: new Date(old).toISOString() }); | |
| 35 | expect(rows[1]).toEqual({ name: "b", found: 1, acted: 0, last: new Date(now.getTime() - 1000).toISOString() }); | |
| 36 | }); | |
| 37 | ||
| 38 | test("/system draws a never-run worker as 'not yet run'", async () => { | |
| 39 | const { maintenanceSection } = await import("../src/web/pages/system.ts"); | |
| 40 | const out = maintenanceSection([{ name: "idle-one", found: 0, acted: 0, last: null }]).text; | |
| 41 | expect(out).toContain("idle-one"); | |
| 42 | expect(out).toContain("not yet run"); | |
| 43 | }); | |
| 44 | ||
| 45 | test("the one sentence counts the workers that found something", async () => { | |
| 46 | const { weekWords } = await import("../src/maintain/week_line.ts"); | |
| 47 | const row = (found: number) => ({ name: "w", found, acted: 0, last: null }); | |
| 48 | expect(weekWords([row(0), row(3), row(1)])).toBe("2 of 3 workers found something this week"); | |
| 49 | }); |
test/maintenance-week-doors.test.ts added +106
| @@ -0,0 +1,106 @@ | ||
| 1 | /** | |
| 2 | * The maintenance week's three doors (#12436): /system, the terminal screen and MCP `system` | |
| 3 | * `{kind:"maintenance"}`. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 6 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createApp, type App } from "../src/app.ts"; | |
| 10 | import { createAgent } from "../src/actions/crew.ts"; | |
| 11 | import { setTelemetryGrant } from "../src/actions/telemetry.ts"; | |
| 12 | import { createToken } from "../src/core/tokens.ts"; | |
| 13 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; | |
| 14 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 15 | import { duties } from "../src/maintain/registry.ts"; | |
| 16 | import { Session } from "../src/tui/session.ts"; | |
| 17 | import { weekLines } from "../src/tui/screens/maintenanceweek.ts"; | |
| 18 | import { quietLogs } from "./helpers/globals.ts"; | |
| 19 | ||
| 20 | quietLogs(); | |
| 21 | ||
| 22 | let dataDir = ""; | |
| 23 | let app: App; | |
| 24 | let servers: Servers; | |
| 25 | let admin = ""; | |
| 26 | let plain = ""; | |
| 27 | let alice: User; | |
| 28 | let bob: User; | |
| 29 | const first = duties[0]!.name; | |
| 30 | ||
| 31 | const identity = (user?: User) => ({ sshUsername: user?.username ?? "git", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user }); | |
| 32 | ||
| 33 | beforeAll(async () => { | |
| 34 | dataDir = await mkdtemp(join(tmpdir(), "forge-maint-week-")); | |
| 35 | app = createApp({ dataDir, port: 0 }); | |
| 36 | servers = await serve(app); | |
| 37 | const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "correct horse battery 9", isAdmin: true }); | |
| 38 | const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "correct horse battery 9" }); | |
| 39 | if (!a.ok || !b.ok) throw new Error("users"); | |
| 40 | alice = a.value; | |
| 41 | bob = b.value; | |
| 42 | admin = createToken(app.db, alice.id, "t", "admin").token; | |
| 43 | plain = createToken(app.db, bob.id, "t", "admin").token; | |
| 44 | const now = new Date().toISOString(); | |
| 45 | app.db | |
| 46 | .query("INSERT INTO maintenance_run (duty, started, finished, findings, actions, probes, outcome) VALUES (?1,?2,?2,'[\"a\",\"b\"]','[\"c\"]','[]','ok')") | |
| 47 | .run(first, now); | |
| 48 | }, 30_000); | |
| 49 | ||
| 50 | afterAll(async () => { | |
| 51 | servers.stop(); | |
| 52 | app.close(); | |
| 53 | await rm(dataDir, { recursive: true, force: true }); | |
| 54 | }); | |
| 55 | ||
| 56 | const call = async (token: string) => { | |
| 57 | const res = await fetch(`${servers.url}/mcp`, { | |
| 58 | method: "POST", | |
| 59 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` }, | |
| 60 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "system", arguments: { kind: "maintenance" } } }), | |
| 61 | }); | |
| 62 | return (await res.json()) as any; | |
| 63 | }; | |
| 64 | ||
| 65 | test("MCP maintenance answers a row per worker; a non-admin is forbidden; telemetry:read opens it to an agent", async () => { | |
| 66 | const out = await call(admin); | |
| 67 | expect(out.result.isError).not.toBe(true); | |
| 68 | const { workers } = JSON.parse(out.result.content[0].text); | |
| 69 | expect(workers.map((w: any) => w.name)).toEqual(duties.map((d) => d.name)); | |
| 70 | expect(workers[0]).toMatchObject({ name: first, found: 2, acted: 1 }); | |
| 71 | expect(workers[0].last).not.toBeNull(); | |
| 72 | expect(workers[1]).toMatchObject({ found: 0, acted: 0, last: null }); | |
| 73 | ||
| 74 | const refused = await call(plain); | |
| 75 | expect(refused.result.isError).toBe(true); | |
| 76 | expect(refused.result.content[0].text).toContain("forbidden"); | |
| 77 | ||
| 78 | const bot = await createAgent(app, getUserByName(app.db, "alice")!, { username: "maintbot" }); | |
| 79 | if (!bot.ok) throw new Error("bot"); | |
| 80 | const token = createToken(app.db, bot.value.user.id, "t", "ro").token; | |
| 81 | expect((await call(token)).result.isError).toBe(true); | |
| 82 | expect(setTelemetryGrant(app, alice, "maintbot", true).ok).toBe(true); | |
| 83 | expect((await call(token)).result.isError).not.toBe(true); | |
| 84 | }); | |
| 85 | ||
| 86 | test("the terminal screen says the sentence and lists every worker, for the same gate; others get nothing", () => { | |
| 87 | const lines = weekLines(new Session(app, identity(alice))); | |
| 88 | expect(lines[0]).toBe(`1 of ${String(duties.length)} workers found something this week`); | |
| 89 | expect(lines.length).toBe(duties.length + 2); | |
| 90 | expect(lines[2]).toContain("found 2 · acted 1"); | |
| 91 | expect(lines[3]).toContain("not yet run"); | |
| 92 | expect(weekLines(new Session(app, identity(bob)))).toEqual([]); | |
| 93 | expect(weekLines(new Session(app, identity(undefined)))).toEqual([]); | |
| 94 | }); | |
| 95 | ||
| 96 | test("/system through the route holds the section: the one sentence on first view, the rows behind a disclosure", async () => { | |
| 97 | const res = await fetch(`${servers.url}/system`, { headers: { authorization: `Bearer ${admin}` } }); | |
| 98 | expect(res.status).toBe(200); | |
| 99 | const body = await res.text(); | |
| 100 | const at = body.indexOf('id="sys-maintenance"'); | |
| 101 | expect(at).toBeGreaterThan(0); | |
| 102 | const section = body.slice(at, body.indexOf("</section>", at)); | |
| 103 | expect(section).toMatch(/<summary[^>]*>1 of \d+ workers found something this week<\/summary>/); | |
| 104 | expect(section).toContain(`data-worker="${first}"`); | |
| 105 | expect(section).toContain("not yet run"); | |
| 106 | }); |
test/palette-roster.test.ts +1
| @@ -123,6 +123,7 @@ test("a site-admin person is offered the whole roster", () => { | ||
| 123 | 123 | ["telemetry", "Telemetry", "which agents may read flow and system; enter flips the grant"], |
| 124 | 124 | ["stalls", "Main-thread stalls", "the last hour's stall ms by route"], |
| 125 | 125 | ["footing", "What the forge stands on", "each piece on another machine, in the order it would break the forge"], |
| 126 | ["maintenanceweek", "Maintenance, last 7 days", "what each maintenance worker found and did this week"], | |
| 126 | 127 | ["offsite", "Off-site backup", "where the sealed lane writes, when it last succeeded, and the last restore drill"], |
| 127 | 128 | ["capacity", "Capacity", "concurrency and guards, live; e changes a settable one"], |
| 128 | 129 | ["resilience", "Resilience", "where snapshots go and the mirror; each protection green, red or untested"], |
test/system-parts.test.ts +1
| @@ -54,6 +54,7 @@ test("one <h2> per part, each in a settings-block, and no card", async () => { | ||
| 54 | 54 | "Largest under the forge's data", |
| 55 | 55 | "Database size", |
| 56 | 56 | "Processes", |
| 57 | "Maintenance, last 7 days", | |
| 57 | 58 | "What the forge costs", |
| 58 | 59 | "What the forge stands on", |
| 59 | 60 | "Off-site backup", |
new above
offline
No test exercises this branch (rows, and forbidden for a non-admin without telemetry:read). Add one. The terminal door for these rows is also missing (src/tui/ screen plus docs/features/ how-to).