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

One page that says where the bottleneck is right now: line, CPU, checks, model, disk, with the levers beside each #13723

Merged opened this in answer to

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

Merged

scout/forge:scout/13712-one-page-that-says-where-the-bottleneck → main 11 commits fork 3 threads · 3 unresolved

  • Merged. scout/13712-one-page-that-says-where-the-bottleneck was merged into main as 5a4f606.

Review

Sign in to review this change.
10 files changed +390 −3
docs/MCP.md +1 −1
@@ -226,7 +226,7 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
226226 | `subscription_wake` | — | Admin: wake a resting subscription | 168 |
227227 | `subscriptions` | — | Claude accounts: scopes, budgets | 158 |
228228 | `sync` | — | Sync a mirror now; `originId` reconnects it | 197 |
229 | `system` | `pause`, `resume`, `csp`, `routes`, `footing`, `offsite`, `size`, `maintenance`, `growth` | The forge machine now: CPU, memory, disk, network | 462 |
229 | `system` | `pause`, `resume`, `csp`, `routes`, `bottleneck`, `footing`, `offsite`, `size`, `maintenance`, `growth` | The forge machine now: CPU, memory, disk, network | 475 |
230230 | `take_back` | — | Open the pull that undoes a shipped pull | 219 |
231231 | `take_updates` | — | Take the parent forge's updates into a fork | 268 |
232232 | `teams` | — | Crew teams for person admins: charter, dial (0–100) and member agents | 338 |
docs/design/audit.md +1
@@ -114,6 +114,7 @@ Machine routes are not pages and have no entry: `/audit.csv`,
114114 ### Machine and operation (admin)
115115
116116 - `/system` — `pages/system.ts` · the machine as it is now: cores, load, memory, processes · `/flow`, `/` · none seen; updates in place over `/system/stream`, no reload script.
117 - `/system/bottleneck` — `pages/bottleneck.ts` · what limits the forge now: one sentence and a row each with its lever; the owner's only · `/system` · none seen; reuses the list and muted text.
117118 - `/resilience` — `pages/resilience.ts` · each protection in `docs/THREATS.md` against the last gate's tests · `/settings/resilience` (similar name, different content) · none seen.
118119 - `/maintenance` — `pages/maintenance.ts` · prepare the forge for a power-off and end it · `/resilience`, `/settings/backups` · none seen.
119120 - `/admin/limits` — `pages/admin-limits.ts` · every limit with value, default and reason · `/settings/capacity` (also a numbers-you-can-change page) · none seen.
docs/features/README.md +1
@@ -481,6 +481,7 @@ Read with the guide page [Every setting, by topic](../guide-settings.md).
481481 Read with the guide page [When something is wrong](../guide-when-wrong.md).
482482
483483 - [The machine's real size on /system and in health](system.md)
484 - [Where the bottleneck is: the line, CPU, checks, crew, memory and disk, each beside its lever](bottleneck.md)
484485 - [A child forge the host stopped](child-stopped.md)
485486 - [A failed adapter pull speaks once in the writers' feed](sync-failed-feed.md)
486487 - [A failing webhook is said once](webhook-failing.md)
docs/features/bottleneck.md added +20
@@ -0,0 +1,20 @@
1 # Where the bottleneck is
2
3 A forge admin sees in one sentence what limits the forge now, then one row each for the internet
4 connection, CPU, checks, crew, memory and disk: the reading, its ceiling, and the setting that moves
5 it. Two doors, one reading (`readBottleneck`):
outdated

Claims 'its last hour as a small line'; the pull has no history. Remove the claim or build it. Also no terminal how-to (both doors).

6
7 - **Page:** `/system/bottleneck`, linked from `/system`.
8 - **MCP:** the `system` tool with `kind: bottleneck`; a non-admin gets `forbidden`.
9
10 - **The sentence** names the row at 90% or more of its ceiling, the nearest first; else "Nothing is
11 at its limit."
12 - **The connection's ceiling** is the megabits a second it carries out: start the forge with
13 `FORGE_LINE_MBIT`. Unset, the row says so and never takes the sentence. Loopback is not counted.
14 Nothing in the forge moves this row, so it has no setting beside it.
15 - **CPU** is the machine's busy share times its cores, against the forge's own core limit when it has one.
16 - **Not measured here**, and listed on the page rather than guessed: round trips to outside hosts, a
17 page through the public address against loopback, bytes split by sender, and the host's traffic
18 shaping.
19
20 Code: `src/system/bottleneck.ts`, `src/web/pages/bottleneck.ts`.
src/http/mcp/tools/system.ts +8 −2

Diff not shown — a line 2,792 characters wide (limit 2,000). +8 −2

View file
src/http/server.ts +2
@@ -38,6 +38,7 @@ import { queueScanPush } from "../checks/scan.ts";
3838 import { parentCallback, parentStart } from "./rp.ts";
3939 import { prerenderComments } from "../web/prerender.ts";
4040 import { systemPage, systemStream } from "../web/pages/system.ts";
41 import { bottleneckPage } from "../web/pages/bottleneck.ts";
4142 import { contributePage } from "../web/pages/contribute.ts";
4243 import { pipelinePage } from "../web/pages/pipeline.ts";
4344 import { adminDataPage, appDataCsv, appDataPage, dataPage } from "../web/pages/data.ts";
@@ -1117,6 +1118,7 @@ export function buildRouter(): Router<Handler> {
11171118 router.add("POST", "/flow/suggestion", suggestionTake);
11181119 router.add("GET", "/system", systemPage);
11191120 router.add("GET", "/system/stream", systemStream);
1121 router.add("GET", "/system/bottleneck", bottleneckPage);
11201122 router.add("GET", "/contribute", contributePage);
11211123 // The one path a change follows, in four words (#7703); literal, above /:owner.
11221124 router.add("GET", "/pipeline", pipelinePage);
src/system/bottleneck.ts added +164
@@ -0,0 +1,164 @@
1 /**
2 * Where the forge is limited right now (#13712): the line, the CPU, the checks, the crew, memory
3 * and disk, each as now / ceiling / the lever beside it, and one sentence naming the row nearest
4 * its ceiling. `judge` is plain data in, plain data out; `readBottleneck` feeds it from the live
5 * machine reading and the run table. What is not measured from here is listed in `unseen`, never
6 * guessed: the round trips to outside hosts, the split of bytes by sender, and the host's shaper.
7 * The uplink's ceiling is the admin's `FORGE_LINE_MBIT` (megabits a second, out); without it the
8 * line row says no ceiling is set and never takes the sentence.
9 */
10 import type { Database } from "bun:sqlite";
11 import { capacityValue } from "../core/capacity.ts";
12 import { runningAgentRuns } from "../crew/running.ts";
13 import type { SystemView } from "./view.ts";
14
15 export type RowId = "line" | "cpu" | "checks" | "crew" | "memory" | "disk";
16
17 export type Row = {
18 id: RowId;
19 label: string;
20 /** The reading in words, with its unit. */
21 now: string;
22 /** The ceiling in words; null when none is known. */
23 ceiling: string | null;
24 /** now over ceiling, 0 to 1 and over; null without a ceiling. */
25 fraction: number | null;
26 /** Anything beside the figure: the split, the queue. */
27 detail: string;
28 /** The control that moves it; null when nothing in the forge does. */
29 lever: { label: string; href: string } | null;
30 };
31
32 export type Bottleneck = { at: string; says: string; limited: RowId | null; rows: Row[]; unseen: string[] };
33
34 export type Input = {
35 view: SystemView;
36 /** Megabits a second the internet connection carries, out; null when not set. */
37 lineMbit: number | null;
38 checks: { running: number; slots: number; queued: number };
39 crew: { running: number; slots: number; queued: number };
40 };
41
42 /** A row at or past this share of its ceiling is what limits the forge. */
43 export const LIMIT = 0.9;
44
45 export const UNSEEN: readonly string[] = [
46 "Round trips to outside hosts and a page through the public address against loopback are not measured here.",
47 "Bytes out and in are the machine's, not split by what sent them (pages, model requests, backups).",
48 "The host's traffic shaping (queue delay per class, drops) is the host's: not visible from here.",
49 ];
50
51 const mbit = (bytesPerSecond: number): number => Math.round(((bytesPerSecond * 8) / 1e6) * 10) / 10;
52 const gib = (b: number): string => `${Math.round((b / 2 ** 30) * 10) / 10} GiB`;
53
54 /** The configured ceiling: a positive number of megabits, else null. */
55 export function lineCeiling(env: string | undefined): number | null {
56 const n = Number(env?.trim());
57 return env !== undefined && env.trim() !== "" && Number.isFinite(n) && n > 0 && n <= 1_000_000 ? n : null;
58 }
59
60 export function judge(input: Input, at = new Date()): Bottleneck {
61 const { view, lineMbit, checks, crew } = input;
62 const rows: Row[] = [];
63
64 const out = view.net.filter((n) => n.name !== "lo");
65 const known = out.some((n) => n.txBytesPerSecond !== null);
66 const tx = mbit(out.reduce((s, n) => s + (n.txBytesPerSecond ?? 0), 0));
67 const rx = mbit(out.reduce((s, n) => s + (n.rxBytesPerSecond ?? 0), 0));
68 rows.push({
69 id: "line",
70 label: "Connection",
71 now: known ? `${tx} Mbit/s out, ${rx} in` : "not read yet",
72 ceiling: lineMbit === null ? null : `${lineMbit} Mbit/s out`,
73 fraction: !known || lineMbit === null ? null : tx / lineMbit,
74 detail: lineMbit === null ? "No ceiling is set: start the forge with FORGE_LINE_MBIT set to the megabits your internet connection carries out." : "Nothing in the forge moves this; it is the connection's.",
75 lever: null,
76 });
77
78 // busyPct is the mean over every core the machine has, so it is scaled by that count; the ceiling
79 // is the forge's own limit when it has one.
80 const cores = view.cpu.limitCores ?? view.cpu.cores.length;
81 const busy = view.cpu.busyPct;
82 const busyCores = busy === null ? null : Math.round((busy / 100) * view.cpu.cores.length * 10) / 10;
83 const byKind = new Map<string, number>();
84 for (const g of view.groups) byKind.set(g.kind, (byKind.get(g.kind) ?? 0) + (g.cpuCores ?? 0));
85 const split = [...byKind].filter(([, c]) => c >= 0.05).sort((a, b) => b[1] - a[1]).map(([k, c]) => `${k} ${Math.round(c * 10) / 10}`);
86 rows.push({
87 id: "cpu",
88 label: "CPU",
89 now: busyCores === null ? "not read yet" : `${busyCores} of ${cores} cores`,
90 ceiling: `${cores} cores`,
91 fraction: busyCores === null || cores <= 0 ? null : busyCores / cores,
92 detail: split.length === 0 ? "" : `Held by: ${split.join(", ")}.`,
93 lever: { label: "Set how many checks and crew runs go at once", href: "/settings/capacity" },
94 });
95
96 rows.push({
97 id: "checks",
98 label: "Checks",
99 now: `${checks.running} of ${checks.slots} slots`,
100 ceiling: `${checks.slots} at once`,
101 fraction: checks.slots > 0 ? checks.running / checks.slots : null,
102 detail: checks.queued > 0 ? `${checks.queued} wait for a slot.` : "",
103 lever: { label: "Set how many checks go at once", href: "/settings/capacity" },
104 });
105 rows.push({
106 id: "crew",
107 label: "Crew",
108 now: `${crew.running} of ${crew.slots} runs`,
109 ceiling: `${crew.slots} at once`,
110 fraction: crew.slots > 0 ? crew.running / crew.slots : null,
111 detail: crew.queued > 0 ? `${crew.queued} wait for a slot.` : "",
112 lever: { label: "Set how many crew runs go at once", href: "/settings/capacity" },
113 });
114
115 const m = view.memory;
116 rows.push({
117 id: "memory",
118 label: "Memory",
119 now: m === null ? "not read yet" : gib(m.usedBytes),
120 ceiling: m === null ? null : gib(m.totalBytes),
121 fraction: m === null || m.totalBytes <= 0 ? null : m.usedBytes / m.totalBytes,
122 detail: "",
123 lever: { label: "Set how many checks and crew runs go at once", href: "/settings/capacity" },
124 });
125
126 const fullest = view.disks.filter((d) => d.totalBytes > 0).sort((a, b) => b.usedBytes / b.totalBytes - a.usedBytes / a.totalBytes)[0];
127 rows.push({
128 id: "disk",
129 label: "Disk",
130 now: fullest === undefined ? "not read yet" : `${gib(fullest.usedBytes)} on ${fullest.mount}`,
131 ceiling: fullest === undefined ? null : gib(fullest.totalBytes),
132 fraction: fullest === undefined ? null : fullest.usedBytes / fullest.totalBytes,
133 detail: "",
134 lever: { label: "Open the backup settings", href: "/settings/backups" },
135 });
136
137 let worst: Row | null = null;
138 for (const r of rows) if (r.fraction !== null && r.fraction >= LIMIT && (worst === null || r.fraction > (worst.fraction ?? 0))) worst = r;
139 return { at: at.toISOString(), says: worst === null ? "Nothing is at its limit." : sentence(worst, input, tx), limited: worst?.id ?? null, rows, unseen: [...UNSEEN] };
140 }
141
142 function sentence(r: Row, input: Input, tx: number): string {
143 const { checks, crew, lineMbit } = input;
144 if (r.id === "line") return `The internet connection is full: ${tx} of ${lineMbit} Mbit/s.`;
145 if (r.id === "checks") return `Checks hold ${checks.running} of ${checks.slots} slots; ${checks.queued} wait.`;
146 if (r.id === "crew") return `The crew holds ${crew.running} of ${crew.slots} runs; ${crew.queued} wait.`;
147 if (r.id === "cpu") return `The CPU is full: ${r.now}.`;
148 if (r.id === "memory") return `Memory is nearly full: ${r.now} of ${r.ceiling}.`;
149 return `The disk is nearly full: ${r.now} of ${r.ceiling}.`;
150 }
151
152 function count(db: Database, kind: string, state: string): number {
153 return db.query<{ n: number }, [string, string]>("SELECT COUNT(*) AS n FROM run WHERE kind = ?1 AND state = ?2").get(kind, state)?.n ?? 0;
154 }
155
156 /** The reading now, from the machine view and the run table. */
157 export function readBottleneck(db: Database, view: SystemView, env: string | undefined = process.env["FORGE_LINE_MBIT"]): Bottleneck {
158 return judge({
159 view,
160 lineMbit: lineCeiling(env),
161 checks: { running: count(db, "check", "running"), slots: Number(capacityValue(db, "checks.concurrency")), queued: count(db, "check", "queued") },
162 crew: { running: runningAgentRuns(), slots: Number(capacityValue(db, "crew.concurrency")), queued: count(db, "agent", "queued") },
163 });
164 }
src/web/pages/bottleneck.ts added +39
@@ -0,0 +1,39 @@
1 /**
2 * /system/bottleneck, for the owner (#13712): one sentence on what limits the forge now, then a
3 * row each for the line, CPU, checks, crew, memory and disk, with the control
4 * beside it. Numbers are `system/bottleneck.ts`'s, the same the MCP `system` tool
5 * (`kind: bottleneck`) reads. First paint is server-rendered; nothing polls.
6 */
7 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
8 import { telemetryReader } from "../../actions/telemetry.ts";
9 import type { Ctx } from "../../http/context.ts";
10 import { readBottleneck, type Row } from "../../system/bottleneck.ts";
11 import { live } from "../../system/live.ts";
12 import { notFoundPage, pageHead, signInFirst } from "../chrome.ts";
13 import { html, type Html } from "../html.ts";
14 import { page } from "../layout.ts";
15 import { statusRow } from "./security.ts";
16
17 function rowHtml(r: Row, limited: boolean): Html {
18 const percent = r.fraction === null ? "" : ` (${Math.min(999, Math.round(r.fraction * 100))}%)`;
outdated

Principle 7: a reading with its ceiling and lever is a dl row, not a hand-built li with bold label, percent in brackets and a 'Lever:' line. Principle 8: say 'Change it:' or just link the action in plain words.

19 const reading = html`${r.now}${r.ceiling === null ? html`` : html` of ${r.ceiling}`}${percent}`;
20 const state = html`${limited ? html`<span class="badge" data-variant="danger">At its limit</span> ` : html``}${reading}${r.detail === "" ? html`` : html`<div class="small muted">${r.detail}</div>`}`;
21 return statusRow(r.label, state, r.lever === null ? null : html`<a href="${r.lever.href}">${r.lever.label}</a>`, `bn-${r.id}`);
22 }
23
24 export async function bottleneckPage(ctx: Ctx): Promise<Response> {
25 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
26 if (!ctx.auth.user) return signInFirst(ctx);
27 const reader = telemetryReader(ctx.app, ctx.auth.user);
28 if (reader?.kind !== "owner") return notFoundPage(ctx);
29 const rendering = performance.now();
30 const b = readBottleneck(ctx.app.db, live().read());

Principle 1: the sub sentence and the bold bn-says line below it say the same thing; drop the sub. No terminal screen exists for this page (both doors).

31 const body = html`${pageHead("Bottleneck", { actions: html`<a href="/system">System</a>` })}
32 <p id="bn-says"><strong>${b.says}</strong></p>
33 <dl class="status-rows" id="bn-rows">${b.rows.map((r) => rowHtml(r, r.id === b.limited))}</dl>
34 <section class="settings-block"><h2>Not measured here</h2>
35 <ul>${b.unseen.map((u) => html`<li class="small">${u}</li>`)}</ul></section>`;
36 const response = page({ ctx, title: "Bottleneck", body });
37 notePhase(ctx.request, "render", performance.now() - rendering);
38 return response;
39 }
src/web/pages/system.ts +1
@@ -658,6 +658,7 @@ export async function systemPage(ctx: Ctx): Promise<Response> {
658658 const at = (id: string): Html => raw(r[id]!);
659659 const help = disclosure("? How to read this", html`<div class="prose break" id="sys-help">
660660 <p>The machine now, updated in place about every 2 s over one event stream. Its history is on <a href="/boards">Boards</a> (the machine source).</p>
661 <p id="bottleneck-link"><a href="/system/bottleneck">Where the bottleneck is</a>: one page, in plain words.</p>
661662 ${caps}${processCaps}${floor}${selfHelp(self)}
662663 <p>Stalls are main-thread pauses past 200 ms, as of this page's load; <code>/metrics</code> has the series.</p>
663664 <p>Cache counts are since this process started. What each cache holds:</p>
test/bottleneck.test.ts added +153
@@ -0,0 +1,153 @@
1 /** Where the bottleneck is (#13712): the sentence follows the row nearest its ceiling. */
2 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { createToken } from "../src/core/tokens.ts";
8 import { createUser, getUserByName } from "../src/core/users.ts";
9 import { serve, type Servers } from "../src/http/server.ts";
10 import { judge, lineCeiling, type Input } from "../src/system/bottleneck.ts";
11 import type { SystemView } from "../src/system/view.ts";
12 import { quietLogs } from "./helpers/globals.ts";
13
14 quietLogs();
15
16 const view = (over: Partial<SystemView> = {}): SystemView => ({
17 at: "2026-11-15T00:00:00Z",
18 seconds: 2,
19 cpu: { busyPct: 20, cores: [20, 20], limitCores: 2, history: [] },
20 temps: [],
21 hottestC: null,
22 load: null,
23 memory: { totalBytes: 8 * 2 ** 30, usedBytes: 2 * 2 ** 30, swapUsedBytes: 0, swapTotalBytes: 0 },
24 disks: [{ mount: "/data", fs: "ext4", totalBytes: 100, usedBytes: 40 }],
25 net: [
26 { name: "lo", rxBytesPerSecond: 9e9, txBytesPerSecond: 9e9 },
27 { name: "eth0", rxBytesPerSecond: 100_000, txBytesPerSecond: 437_500 },
28 ],
29 io: [],
30 processes: 1,
31 groups: [{ label: "check:1", kind: "check", procs: 1, cpuCores: 0.8, rssBytes: 0, capBytes: null, capBy: null, oldestSeconds: 0, top: [], tests: [] }],
32 duplicates: [],
33 ...over,
34 });
35 const input = (over: Partial<Input> = {}): Input => ({
36 view: view(),
37 lineMbit: 3.5,
38 checks: { running: 1, slots: 4, queued: 0 },
39 crew: { running: 0, slots: 2, queued: 0 },
40 ...over,
41 });
42
43 describe("judge", () => {
44 test("a full uplink is the first sentence, and loopback is not counted", () => {
45 const b = judge(input());
46 expect(b.says).toBe("The internet connection is full: 3.5 of 3.5 Mbit/s.");
47 expect(b.limited).toBe("line");
48 });
49 test("nothing near a ceiling says so; no ceiling never takes the sentence", () => {
50 expect(judge(input({ lineMbit: null })).says).toBe("Nothing is at its limit.");
51 expect(judge(input({ lineMbit: 100 })).says).toBe("Nothing is at its limit.");
52 expect(judge(input({ lineMbit: null })).rows[0]!.detail).toContain("FORGE_LINE_MBIT");
53 });
54 test("checks hold every slot", () => {
55 const b = judge(input({ lineMbit: 100, checks: { running: 4, slots: 4, queued: 17 } }));
56 expect(b.says).toBe("Checks hold 4 of 4 slots; 17 wait.");
57 });
58 test("the row nearest its ceiling wins", () => {
59 const b = judge(input({ lineMbit: 100, checks: { running: 4, slots: 4, queued: 1 }, view: view({ cpu: { busyPct: 100, cores: [100, 100], limitCores: 2, history: [] } }) }));
60 expect(b.says).toBe("The CPU is full: 2 of 2 cores.");
61 expect(b.limited).toBe("cpu");
62 });
63 test("every row names a lever, and what is not seen is listed", () => {
64 const b = judge(input());
65 expect(b.rows.map((r) => r.id)).toEqual(["line", "cpu", "checks", "crew", "memory", "disk"]);
66 for (const r of b.rows) expect(r.lever === null || r.lever.href.startsWith("/")).toBe(true);
67 expect(b.unseen.join(" ")).toContain("not visible from here");
68 });
69 test("memory, disk and crew each take the sentence at their ceiling", () => {
70 const base = { lineMbit: null } as const;
71 expect(judge(input({ ...base, view: view({ memory: { totalBytes: 2 ** 30, usedBytes: 0.92 * 2 ** 30, swapUsedBytes: 0, swapTotalBytes: 0 } }) })).says).toBe("Memory is nearly full: 0.9 GiB of 1 GiB.");
72 expect(judge(input({ ...base, view: view({ disks: [{ mount: "/data", fs: "ext4", totalBytes: 2 ** 30, usedBytes: 2 ** 30 }] }) })).says).toBe("The disk is nearly full: 1 GiB on /data of 1 GiB.");
73 expect(judge(input({ ...base, crew: { running: 2, slots: 2, queued: 3 } })).says).toBe("The crew holds 2 of 2 runs; 3 wait.");
74 });
75 test("a missing reading says not read yet and never takes the sentence", () => {
76 const b = judge(input({ lineMbit: 1, view: view({ cpu: { busyPct: null, cores: [], history: [] }, memory: null, disks: [], net: [] }) }));
77 expect(b.says).toBe("Nothing is at its limit.");
78 for (const id of ["line", "cpu", "memory", "disk"]) expect(b.rows.find((r) => r.id === id)!.now).toBe("not read yet");
79 });
80 test("CPU busy share is over the machine's cores, against the forge's own limit", () => {
81 const b = judge(input({ lineMbit: null, view: view({ cpu: { busyPct: 50, cores: [50, 50, 50, 50], limitCores: 2, history: [] } }) }));
82 const cpu = b.rows.find((r) => r.id === "cpu")!;
83 expect(cpu.now).toBe("2 of 2 cores");
84 expect(b.limited).toBe("cpu");
85 });
86 test("the connection row has no control; the others link one", () => {
87 const b = judge(input());
88 expect(b.rows[0]!.lever).toBeNull();
89 expect(b.rows.slice(1).every((r) => r.lever !== null)).toBe(true);
90 });
91 test("the ceiling is a positive number or nothing", () => {
92 expect(lineCeiling("3.5")).toBe(3.5);
93 for (const bad of [undefined, "", "0", "-1", "x", "1e12"]) expect(lineCeiling(bad)).toBeNull();
94 });
95 });
96
97 describe("the page", () => {
98 let dir: string;
99 let app: App;
100 let servers: Servers;
101 let cookie: string;
102 beforeAll(async () => {
103 dir = await mkdtemp(join(tmpdir(), "forge-bottleneck-"));
104 app = createApp({ dataDir: dir, port: 0 });
105 servers = await serve(app);
106 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
107 if (!made.ok) throw new Error(made.error);
108 const signin = await fetch(`${servers.url}/signin`, { method: "POST", body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }), redirect: "manual" });
109 cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
110 }, 30_000);
111 afterAll(async () => {
112 servers.stop();
113 app.close();
114 await rm(dir, { recursive: true, force: true });
115 });
116 test("the owner reads the sentence and the levers; a stranger is told nothing", async () => {
117 const res = await fetch(`${servers.url}/system/bottleneck`, { headers: { cookie } });
118 expect(res.status).toBe(200);
119 const text = await res.text();
120 expect(text).toContain('id="bn-says"');
121 expect(text).toContain('href="/settings/capacity"');
122 const out = await fetch(`${servers.url}/system/bottleneck`, { redirect: "manual" });
123 expect(await out.text()).not.toContain("bn-says");
124 });
125 test("a signed-in non-admin is refused", async () => {
126 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
127 if (!made.ok) throw new Error(made.error);
128 const signin = await fetch(`${servers.url}/signin`, { method: "POST", body: new URLSearchParams({ username: "bob", password: "a-good-passphrase" }), redirect: "manual" });
129 const bob = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
130 const res = await fetch(`${servers.url}/system/bottleneck`, { headers: { cookie: bob } });
131 expect(res.status).toBe(403);
132 expect(await res.text()).not.toContain("bn-says");
133 });
134 test("the MCP tool refuses a non-admin and gives an admin the rows", async () => {
135 const alice = getUserByName(app.db, "alice")!;
136 const bob = getUserByName(app.db, "bob")!;
137 const call = async (userId: string) => {
138 const token = createToken(app.db, userId, "t", "admin").token;
139 const res = await fetch(`${servers.url}/mcp`, {
140 method: "POST",
141 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
142 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "system", arguments: { kind: "bottleneck" } } }),
143 });
144 return ((await res.json()) as any).result;
145 };
146 const refused = await call(bob.id);
147 expect(refused.isError).toBe(true);
148 expect(refused.content[0].text).toContain("forbidden");
149 const ok = await call(alice.id);
150 expect(ok.isError).not.toBe(true);
151 expect(JSON.parse(ok.content[0].text).rows.map((r: any) => r.id)).toEqual(["line", "cpu", "checks", "crew", "memory", "disk"]);
152 });
153 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs