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

Games: a day after a mod set is installed, the games page says whether it helped, with take-back one tap away #18201

opened this

Merged 3h 37m ago, live in production

scout/forge:scout/18192-games-a-day-after-a-mod-set-is-installed → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/18192-games-a-day-after-a-mod-set-is-installed was merged into main as 2243020.

Review

Sign in to review this change.
9 files changed +488 −37
docs/features/game-mods.md +1
@@ -33,5 +33,6 @@ The image does not check a pack's file hashes (its Modrinth project path does; i
3333 - **Web:** `/games/<box>/<service>`, the Mods (or Plugins) block: updates, what is installed, Search, Preview, Install and restart; on a mod server, the Modpack block: the pack, its locked files, Search packs, Preview, Install pack and restart.
3434 - **Terminal:** a service's screen, `m`: `/` search, `a` install by a result's number or a slug, `s` the survival performance set, `q` the quality-of-life set, `r` the admin set, `u` update all, `d` remove, `p` a modpack by slug; `y` commits the preview shown, `n` drops it (`src/tui/screens/game_mods.ts`).
3535 - **MCP:** `games` with `mods`, `mods_search`, `mods_pack_search`, `mods_install`, `mods_update`, `mods_remove`, `mods_pack`; a change is planned until `dryRun: false`.
36 - **Did the set help**: a day after a set lands, the server's page and its row in the box's list say *helped*, *no change*, *hurt* or *not enough numbers*, with both tick times (24 h after against 24 h before, from the box's check-in minutes; `src/games/set_verdict.ts`; the first ten minutes after a start are left out). The terminal's server screen and MCP `games` `list` (`modSets`) say the same. On *hurt*, *Preview taking it back* shows one commit (`set:<name>` to `mods_remove`, or `d` in the terminal's Mods); nothing is taken back unless a person commits it.
3637
3738 All three read and write through `src/games/mods.ts`, over the client in `src/games/modrinth.ts`.
outdated

This bullet lands after the closing line 'All three read and write through src/games/mods.ts', so it reads as a fourth door of that list. Put it above that line, and shorten it: it is one very long paragraph.

src/core/event_audience.ts +4
@@ -266,6 +266,10 @@ export function classifiedAudience(kind: string): EventAudience | undefined {
266266 kind.startsWith("runner.") ||
267267 // A shell on a game box and everything it said: its owner's, the forge admin's (`games/shell.ts`).
268268 kind.startsWith("game.shell.") ||
269 // A mod set installed on or taken back from a server: the admins' record
270 // (`games/set_verdict.ts`).
271 kind === "game.mods.set_installed" ||
272 kind === "game.mods.set_taken_back" ||
269273 // A command taken back keeps its text, which may be a shell one (`games/take_back.ts`).
270274 kind === "game.command.taken_back" ||
271275 // Which forges this one lends runners to is its admin's too (`actions/lending.ts`).
src/games/mods.ts +51 −8
@@ -27,6 +27,7 @@ import { SPARK_CFG, SPARK_VAR, sparkConfig, sparkConfigFile } from "./spark.ts";
2727 import { publicOrigin } from "../core/public_origin.ts";
2828 import { AUTOSTOPPER } from "./sleep.ts";
2929 import { servicesOf, type GameBox } from "./store.ts";
30 import { noteSet } from "./set_verdict.ts";
3031
3132 /** What a service has, as its repository says at the compose file's commit. */
3233 export interface Mods {
@@ -59,6 +60,11 @@ export interface Plan {
5960 readonly done: string;
6061 /** The modpack the lock holds after it (undefined: as it was). */
6162 readonly pack?: LockedPack;
63 /**
64 * A set this plan installs or takes back, kept as an event so the forge can say a day later
65 * whether it helped (`set_verdict.ts`).
66 */
67 readonly set?: { readonly name: string; readonly op: "installed" | "taken_back" };
6268 /** A config file written in the same commit (spark's: where its profiles go). */
6369 readonly configs?: readonly { readonly file: string; readonly content: string }[];
6470 }
@@ -313,6 +319,7 @@ async function planSet(app: App, m: Mods, service: string, set: ModSet): Promise
313319 lock: got.value,
314320 env: envFor(m, got.value, kept),
315321 message: `games: ${service} mods: add ${what}${withDeps}`,
322 set: { name: set.name, op: "installed" },
316323 sha: m.sha,
317324 done: `${what[0]!.toUpperCase()}${what.slice(1)} is installed${withDeps === "" ? "" : ` with ${withDeps.slice(5)}`}`,
318325 },
@@ -352,8 +359,49 @@ export async function planUpdate(app: App, m: Mods, service: string, ref: string
352359 };
353360 }
354361
355 /** Remove `ref`, and what it alone required. A dependency something else requires stays. */
362 /** The lock without the dependencies nothing requires any more, until nothing else drops out. */
363 function withoutOrphans(lock: readonly Locked[]): Locked[] {
364 let next = [...lock];
365 for (;;) {
366 const orphan = next.find((l) => !l.top && !next.some((o) => o.requires.includes(l.project)));
367 if (orphan === undefined) return next;
368 next = next.filter((l) => l !== orphan);
369 }
370 }
371
372 /**
373 * Take a set back: its members, and what only they required. A member something outside the set
374 * requires stays.
375 */
376 function planRemoveSet(m: Mods, service: string, set: ModSet): Result<Plan> {
377 const mine = m.lock.filter((l) => l.top && set.slugs.includes(l.slug));
378 if (mine.length === 0) return { ok: false, error: `The ${set.title.toLowerCase()} set is not installed here.` };
379 let next = m.lock.filter((l) => !mine.includes(l));
380 // A member another install requires goes back in, and what it requires with it.
381 for (const l of mine) if (next.some((o) => o.requires.includes(l.project))) next = m.lock.filter((o) => next.includes(o) || o === l);
382 next = withoutOrphans(next);
383 const gone = mine.filter((l) => !next.includes(l)).map((l) => l.title);
384 return {
385 ok: true,
386 value: {
387 lines: diffLines(m, next, new Set()),
388 lock: next,
389 env: envFor(m, next, m.loose),
390 message: `games: ${service} mods: remove the ${set.title.toLowerCase()} set`,
391 set: { name: set.name, op: "taken_back" },
392 sha: m.sha,
393 done: `The ${set.title.toLowerCase()} set is taken back (${gone.join(", ")})`,
394 },
395 };
396 }
397
398 /**
399 * Remove `ref` (a project, or `set:<name>` for a whole set), and what it alone required. A
400 * dependency something else requires stays.
401 */
356402 export async function planRemove(m: Mods, service: string, ref: string): Promise<Result<Plan>> {
403 const set = setNamed(ref);
404 if (set !== undefined) return planRemoveSet(m, service, set);
357405 const gone = find(m.lock, ref.trim());
358406 if (gone === undefined) return { ok: false, error: `${ref} is not installed here.` };
359407 const needs = m.lock.filter((o) => o.project !== gone.project && o.requires.includes(gone.project)).map((o) => o.title);
@@ -362,13 +410,7 @@ export async function planRemove(m: Mods, service: string, ref: string): Promise
362410 ok: false,
363411 error: `${gone.title} is there because ${needs.join(" and ")} ${needs.length === 1 ? "requires" : "require"} it; remove that first.`,
364412 };
365 let next = m.lock.filter((l) => l.project !== gone.project);
366 // Then whatever only it required, until nothing else drops out.
367 for (;;) {
368 const orphan = next.find((l) => !l.top && !next.some((o) => o.requires.includes(l.project)));
369 if (orphan === undefined) break;
370 next = next.filter((l) => l !== orphan);
371 }
413 const next = withoutOrphans(m.lock.filter((l) => l.project !== gone.project));
372414 return {
373415 ok: true,
374416 value: {
@@ -394,6 +436,7 @@ export async function commitPlan(app: App, user: User, box: GameBox, service: st
394436 extra: [{ path: lockPath(box, service), content: lockText(m.target, plan.lock, plan.pack ?? m.pack) }],
395437 expectTip: plan.sha,
396438 });
439 if (done.ok && plan.set !== undefined) noteSet(app, user.id, box, service, plan.set.name, plan.set.op, done.sha);
397440 return done.ok ? { ok: true, value: done.sha } : done;
398441 }
399442
src/games/set_verdict.ts added +169
@@ -0,0 +1,169 @@
1 /**
2 * Did a mod set help (#18192, the last step of #18059): the forge keeps when a set landed on a
3 * server (`game.mods.set_installed` in the event log, no table of its own) and, a day after,
4 * compares the 24 h of tick time and TPS after it with the 24 h before, from the minutes the box
5 * already reports at check-in (`game_metric`). Nothing is taken back on its own: a "hurt" verdict
6 * names the take-back (`set:<name>` to the mods remove) and the person decides.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import type { App } from "../app.ts";
11 import { SETS, SET_PREFIX, type ModSet } from "./mod_sets.ts";
12 import type { GameBox } from "./store.ts";
13
14 const DAY_MINUTES = 1440;
15 /** Fewest minutes with a reading either side must hold for a verdict. */
16 const MIN_SAMPLES = 12;
17 /** How much a tick time must move to count. */
18 const MOVE = 0.1;
19 /**
20 * Minutes after a server starts that do not count: a cold JVM's ticks are slow whatever is
21 * installed.
22 */
23 const WARM_MINUTES = 10;
24 /** A set's verdict is shown for this long after the install; the minutes are kept 30 days. */
25 const SHOWN_DAYS = 28;
26
27 export type Word = "helped" | "no change" | "hurt" | "not enough numbers";
28
29 /** What one window of a server was like. */
30 export interface Reading {
31 /** Minutes that carried both a TPS and a tick time. */
32 readonly samples: number;
33 readonly tps: number | null;
34 readonly mspt: number | null;
35 /** Players on, averaged over the minutes that said, and the most at once. */
36 readonly players: number;
37 readonly peak: number;
38 }
39
40 export interface Verdict {
41 readonly set: string;
42 readonly title: string;
43 readonly service: string;
44 readonly installedAt: string;
45 /** Null until the day after is over. */
46 readonly word: Word | null;
47 readonly before: Reading;
48 readonly after: Reading;
49 /** The `project` that takes the set back, only when it hurt. */
50 readonly takeBack: string | null;
51 /** The word and both tick times, short enough for a server's row in a list. */
52 readonly short: string;
53 /** The numbers behind the word: both windows' TPS and players. Empty while measuring. */
54 readonly detail: string;
55 /** The same sentence on the page, in the terminal and over MCP. */
56 readonly says: string;
57 }
58
59 const tenth = (n: number): number => Math.round(n * 10) / 10;
60
61 /** The verdict of two windows: plain numbers in, one of four words out. */
62 export function judge(before: Reading, after: Reading): Word {
63 if (before.samples < MIN_SAMPLES || after.samples < MIN_SAMPLES || before.mspt === null || after.mspt === null || before.tps === null || after.tps === null) return "not enough numbers";
64 const change = before.mspt === 0 ? 0 : (after.mspt - before.mspt) / before.mspt;
65 // TPS is compared at the tenth the page shows: 19.98 against 20 is not a drop.
66 const tpsDown = tenth(after.tps) < tenth(before.tps);
67 if (change >= MOVE || tpsDown) return "hurt";
68 return change <= -MOVE ? "helped" : "no change";
69 }
70
71 interface MinuteRow {
72 minute: number;
73 players_max: number;
74 players_last: number;
75 players_n: number;
76 tps_sum: number;
77 tps_n: number;
78 mspt_sum: number;
79 mspt_n: number;
80 }
81
82 /** The minutes of [from, to) of one server, without the ones just after it started. */
83 function readWindow(db: Database, boxId: string, service: string, from: number, to: number, starts: readonly number[]): Reading {
84 const rows = db
85 .query<MinuteRow, [string, string, number, number]>(
86 "SELECT minute, players_max, players_last, players_n, tps_sum, tps_n, mspt_sum, mspt_n FROM game_metric WHERE box_id = ?1 AND service = ?2 AND minute >= ?3 AND minute < ?4",
87 )
88 .all(boxId, service, from, to)
89 .filter((r) => !starts.some((s) => r.minute >= s && r.minute < s + WARM_MINUTES));
90 const read = rows.filter((r) => r.tps_n > 0 && r.mspt_n > 0);
91 const sum = (f: (r: MinuteRow) => number): number => read.reduce((a, r) => a + f(r), 0);
92 const tpsN = sum((r) => r.tps_n);
93 const msptN = sum((r) => r.mspt_n);
94 const seen = rows.filter((r) => r.players_n > 0);
95 return {
96 samples: read.length,
97 tps: tpsN === 0 ? null : Math.round((sum((r) => r.tps_sum) / tpsN) * 100) / 100,
98 mspt: msptN === 0 ? null : Math.round((sum((r) => r.mspt_sum) / msptN) * 100) / 100,
99 players: seen.length === 0 ? 0 : tenth(seen.reduce((a, r) => a + r.players_last, 0) / seen.length),
100 peak: rows.reduce((m, r) => Math.max(m, r.players_max), 0),
101 };
102 }
103
104 /** A set landed on, or left, a server: the event the verdict starts from. */
105 export function noteSet(app: App, actorId: string, box: Pick<GameBox, "id" | "name">, service: string, set: string, op: "installed" | "taken_back", sha: string): void {
106 app.bus.append({ kind: op === "installed" ? "game.mods.set_installed" : "game.mods.set_taken_back", actorId, payload: { boxId: box.id, box: box.name, service, set, sha } });
107 }
108
109 const ms = (r: Reading): string => (r.mspt === null ? "no tick time" : `${r.mspt} ms`);
110 const tpsOf = (r: Reading): string => (r.tps === null ? "no TPS" : `${r.tps} TPS`);
111
112 /** TPS and players either side of the install: what a verdict rests on beside the tick times. */
113 function detailOf(word: Word | null, before: Reading, after: Reading): string {
114 if (word === null) return "";
115 const on = (r: Reading): string => `${r.players} on average, ${r.peak} at most`;
116 return `${tpsOf(before)} → ${tpsOf(after)}; players ${on(before)} before, ${on(after)} after.`;
117 }
118
119 /** The sentence every surface shows: the word and both numbers it rests on. */
120 function says(title: string, word: Word | null, before: Reading, after: Reading, hoursLeft: number): string {
121 if (word === null) return `${title} set: measuring, the verdict comes in ${hoursLeft} h.`;
122 const head = word === "not enough numbers" ? `${title} set: not enough numbers to say (needs ${MIN_SAMPLES} minutes of tick readings each side; ${before.samples} before, ${after.samples} after).` : `${title} set: ${word}.`;
123 return `${head} Tick time ${ms(before)} → ${ms(after)}, ${detailOf(word, before, after)}`;
124 }
125
126 /** The word and the two tick times: what a row in a list of servers carries. */
127 function shortOf(word: Word | null, before: Reading, after: Reading, hoursLeft: number): string {
128 if (word === null) return `measuring, ${hoursLeft} h to go`;
129 return word === "not enough numbers" ? word : `${word}, tick time ${ms(before)} → ${ms(after)}`;
130 }
131
132 /**
133 * Each set last installed on the box (one service, or all) and not taken back since, newest first:
134 * the day after it, compared with the day before. The minutes just after a start are left out of
135 * both sides, and the day after begins at the restart the install caused.
136 */
137 export function verdictsOf(db: Database, box: Pick<GameBox, "id">, service?: string, now = new Date()): Verdict[] {
138 const events = db
139 .query<{ kind: string; payload: string; created_at: string }, [string]>(
140 "SELECT kind, payload, created_at FROM event WHERE kind IN ('game.mods.set_installed', 'game.mods.set_taken_back') AND json_extract(payload, '$.boxId') = ?1 ORDER BY created_at DESC, id DESC",
141 )
142 .all(box.id);
143 const latest = new Map<string, { kind: string; at: string; service: string; set: ModSet | undefined }>();
144 for (const e of events) {
145 const p = JSON.parse(e.payload) as { service?: unknown; set?: unknown };
146 if (typeof p.service !== "string" || typeof p.set !== "string" || (service !== undefined && p.service !== service)) continue;
147 if (!latest.has(`${p.service}/${p.set}`)) latest.set(`${p.service}/${p.set}`, { kind: e.kind, at: e.created_at, service: p.service, set: SETS.find((x) => x.name === p.set) });
148 }
149 const nowMin = Math.floor(now.getTime() / 60_000);
150 const out: Verdict[] = [];
151 for (const e of latest.values()) {
152 const { set, service: svc } = e;
153 const t = Math.floor(Date.parse(e.at) / 60_000);
154 if (set === undefined || e.kind !== "game.mods.set_installed" || !Number.isFinite(t) || nowMin - t > SHOWN_DAYS * DAY_MINUTES) continue;
155 const starts = db
156 .query<{ at: string }, [string, string]>("SELECT at FROM game_player_event WHERE box_id = ?1 AND service = ?2 AND kind = 'start'")
157 .all(box.id, svc)
158 .map((r) => Math.floor(Date.parse(r.at) / 60_000))
159 .filter(Number.isFinite);
160 const restart = starts.filter((s) => s >= t && s < t + DAY_MINUTES).sort((a, b) => a - b)[0] ?? t;
161 const before = readWindow(db, box.id, svc, t - DAY_MINUTES, t, starts);
162 const done = nowMin >= t + DAY_MINUTES;
163 const after = readWindow(db, box.id, svc, restart, Math.min(nowMin + 1, restart + DAY_MINUTES), starts);
164 const word = done ? judge(before, after) : null;
165 const hoursLeft = Math.max(1, Math.ceil((t + DAY_MINUTES - nowMin) / 60));
166 out.push({ set: set.name, title: set.title, service: svc, installedAt: e.at, word, before, after, takeBack: word === "hurt" ? `${SET_PREFIX}${set.name}` : null, short: shortOf(word, before, after, hoursLeft), detail: detailOf(word, before, after), says: says(set.title, word, before, after, hoursLeft) });
167 }
168 return out.sort((a, b) => b.installedAt.localeCompare(a.installedAt));
169 }
src/http/mcp/tools/games.ts +8 −2

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

View file
src/tui/screens/games.ts +2
@@ -20,6 +20,7 @@ import { ageWords, type LogPage } from "../../logs/page.ts";
2020 import { LogPane } from "../ui/log_pane.ts";
2121 import { commitPolicy, policyOf, proxyPort, STILL_BILLED } from "../../games/sleep.ts";
2222 import { queueShell } from "../../games/shell.ts";
23 import { verdictsOf } from "../../games/set_verdict.ts";
2324 import { takeBack } from "../../games/take_back.ts";
2425 import { AUDIT_SAYS, blockSays, mayTakeBack, serviceBlocks, shellBlocks, shellSays, type Block } from "../../terminal/blocks.ts";
2526 import { watchBox } from "../../games/notify.ts";
@@ -363,6 +364,7 @@ export function gameServiceScreen(f: Session, ctx: Ctx, box: GameBox, service: s
363364 ...held(),
364365 nowWords(servicesOf(f.app.db, box.id).find((x) => x.name === service), powerNow(f.app.db, box.id, service)),
365366 figuresOf(f.app.db, f.user, boxNamed(f.app.db, box.name) ?? box, service),
367 ...verdictsOf(f.app.db, box, service).map((v) => (v.takeBack === null ? v.says : `${v.says} In Mods, d then ${v.takeBack} previews it; nothing is taken back alone.`)),
366368 ...findingsOf(f.app.db, box.id, service).flatMap((x) => [x.says, ...x.fix.map((l) => `Fix: ${l}`)]),
367369 online.length === 0 ? `Nobody is on ${service} right now.` : `Online: ${online.map((p) => tag(p.name)).join(", ")}`,
368370 `${lists.whitelistOn ? "Only listed players may join" : "Anyone may join"} · ${lists.whitelist.length} listed · ${lists.ops.length} operators · ${lists.bans.length} banned`,
src/web/pages/games.ts +27
@@ -9,6 +9,7 @@
99
1010 import { cancelHeld, heldOf, holdUntilQuiet, QUIET_MINUTES } from "../../games/when_quiet.ts";
1111 import { addPluginUrl, commitServiceEnv, composeServices, readCompose, serviceEnv } from "../../games/compose.ts";
12 import { verdictsOf } from "../../games/set_verdict.ts";
1213 import { offered, SETS, SET_PREFIX } from "../../games/mod_sets.ts";
1314 import { commitPlan, modsOf, packUpdateOf, planInstall, planPack, planPackUpdate, planRemove, planUpdate, updatesOf, type Mods, type Plan } from "../../games/mods.ts";
1415 import { search, searchPacks, type Hit, type Result } from "../../games/modrinth.ts";
@@ -337,9 +338,11 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> {
337338 const day = metricsSeries(ctx.app.db, box, n, "24h");
338339 const tps = lastOf(day, (p) => p.tps);
339340 const players = day.length === 0 ? null : day.at(-1)!.players;
341 const sets = verdictsOf(ctx.app.db, box, n);
340342 return row({
341343 href: `/games/${box.name}/${n}`,
342344 title: n,
345 ...(sets.length === 0 ? {} : { facts: sets.map((v) => ({ label: `${v.title} set`, value: v.short })) }),
343346 meta: html`${nowWords(s, powerNow(ctx.app.db, box.id, n))}${players === null ? "" : ` · ${players} online`}${tps === null ? "" : ` · ${tps.toFixed(1)} TPS`}${brief.get(n) ? ` · ${brief.get(n)!}` : ""}
344347 ${day.length === 0 ? "" : html`<span class="bar muted">${sparkOf(day, (p) => p.players, `${n}: players over 24 hours`)}${sparkOf(day, (p) => p.tps, `${n}: TPS over 24 hours`)}${sparkOf(day, (p) => p.memMiB, `${n}: memory over 24 hours`)}</span>`}`,
345348 ...(act
@@ -613,6 +616,7 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> {
613616 const settings = compose === undefined ? [] : settingsOf(compose.text, service, env);
614617 const wanted = settingsWanted(ctx.url.searchParams);
615618 const preview = compose !== undefined && act && Object.keys(wanted).length > 0 ? planSettings(compose.text, service, env, wanted) : undefined;
619 const verdicts = await setVerdictsBlock(ctx, box, service, base, act, mods?.ok ? mods.value : undefined, ctx.url.searchParams.get("undo") ?? "");
616620 return timePhase(ctx.request, "render", () => page({
617621 ctx,
618622 title: `${service} · ${box.name}`,
@@ -623,6 +627,7 @@ export async function gameServicePage(ctx: Ctx): Promise<Response> {
623627 <p class="game-now" id="game-now" aria-live="polite">${nowWords(seen, powerNow(ctx.app.db, box.id, service))}</p>
624628 <p class="muted small" id="game-figures">${figuresOf(ctx.app.db, ctx.auth.user, box, service)}</p>
625629 ${held}
630 ${verdicts}
626631 ${findingsBlock(findings)}
627632 ${joinTrouble(ctx, box, service)}
628633 ${peopleBlock(ctx, box, service, act)}
@@ -744,6 +749,28 @@ function numbersBlock(ctx: Ctx, box: GameBox, service: string): Html {
744749 </section>`);
745750 }
746751
752 /**
753 * What each set installed on this server did a day later, with both numbers. A hurt one offers its
754 * take-back as one action, previewed (`?undo=set:<name>`) and committed only by the person's press.
755 */
756 async function setVerdictsBlock(ctx: Ctx, box: GameBox, service: string, base: string, act: boolean, mods: Mods | undefined, undo: string): Promise<Html | null> {
757 const all = verdictsOf(ctx.app.db, box, service);
758 if (all.length === 0) return null;
759 const wanted = all.find((v) => act && v.takeBack !== null && v.takeBack === undo && mods !== undefined);
760 const plan = wanted === undefined || mods === undefined ? undefined : await planRemove(mods, service, undo);
outdated

Principle 1 and 8: this is a long dense sentence (arrows, TPS, players both sides, then 'Taking it back is one action.') right above a button that says the same. Say the word and the two tick times; drop the sentence that explains the button. Principle 6/7: the hurt case is a boxed notice; a plain row with the verdict word as its value would match the dl-row pattern.

761 return html`<div class="set-verdicts">${rowList(
762 all.map((v) =>
763 row({
764 title: `${v.title} set`,
765 facts: [{ label: "Verdict", value: v.short }],
766 ...(v.detail === "" ? {} : { meta: html`${v.detail}` }),
767 ...(act && v.takeBack !== null && v !== wanted ? { after: btn("Preview taking it back", { size: "sm", variant: "secondary", href: `${base}?undo=${v.takeBack}`, label: `Preview taking the ${v.title} set back` }) } : {}),
768 }),
769 ),
770 )}
771 ${plan === undefined ? null : plan.ok ? previewBlock(plan.value, `${base}/mods/remove`, { project: undo }, "Take it back and restart", base) : html`<p class="notice danger" role="alert">${plan.error}</p>`}</div>`;
772 }
773
747774 /** What a change does, line by line, with the one button that commits it on the commit shown. */
748775 const previewBlock = (plan: { lines: readonly string[]; sha: string }, action: string, sent: Readonly<Record<string, string>>, label: string, cancel: string): Html =>
749776 html`<h3>What this does</h3>
test/game-mods.test.ts +84 −27
@@ -17,6 +17,7 @@ import { readCompose, readRepoFile, serviceEnv } from "../src/games/compose.ts";
1717 import { configMounts } from "../src/games/plugin_config.ts";
1818 import { boxOfSparkSecret } from "../src/games/spark.ts";
1919 import { search, searchPacks, targetOf } from "../src/games/modrinth.ts";
20 import { noteSet } from "../src/games/set_verdict.ts";
2021 import { commitPlan, lockPath, modsOf, packUpdateOf, planInstall, planPack, planPackUpdate, planRemove, planUpdate, updatesOf } from "../src/games/mods.ts";
2122 import { boxNamed, createGameBox, envFiles, recordSync, type GameBox } from "../src/games/store.ts";
2223 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
@@ -25,6 +26,7 @@ import { askPower } from "../src/games/power.ts";
2526 import { AUTOSTOPPER, commitPolicy } from "../src/games/sleep.ts";
2627 import { createForgeApp } from "../src/tui/forge.ts";
2728 import { QUALITY, SETS } from "../src/games/mod_sets.ts";
29 import { gameServiceScreen } from "../src/tui/screens/games.ts";
2830 import { gameModsScreen } from "../src/tui/screens/game_mods.ts";
2931 import { headlessTerminal } from "../src/tui/term/terminal.ts";
3032 import { quietLogs } from "./helpers/globals.ts";
@@ -769,22 +771,7 @@ describe("the page and the MCP tool", () => {
769771 });
770772
771773 test("the MCP tool plans first and commits with dryRun false", async () => {
772 const call = async (args: Record<string, unknown>) => {
773 const res = await http.handle(
774 new Request(`${ORIGIN}/mcp`, {
775 method: "POST",
776 headers: { authorization: `Bearer ${tok}`, "content-type": "application/json", accept: "application/json, text/event-stream" },
777 body: JSON.stringify({
778 jsonrpc: "2.0",
779 id: 1,
780 method: "tools/call",
781 params: { name: "games", arguments: { box: "net", service: "hub", ...args } },
782 }),
783 }),
784 );
785 const body = (await res.json()) as { result: { isError?: boolean; content: { text: string }[] } };
786 return { error: body.result.isError === true, value: JSON.parse(body.result.content[0]!.text) as Record<string, unknown> };
787 };
774 const call = (args: Record<string, unknown>) => mcp({ service: "hub", ...args });
788775 const planned = await call({ action: "mods_install", project: "chunky" });
789776 expect(planned.value).toMatchObject({ planned: true, lines: expect.arrayContaining(["Adds ChunkyLib 1.0.2 (required by Chunky)"]) });
790777 expect(serviceEnv((await readCompose(app, box))!.text, "hub")["MODRINTH_PROJECTS"]).not.toContain("chunky");
@@ -795,19 +782,20 @@ describe("the page and the MCP tool", () => {
795782 });
796783 });
797784
785 const mcp = async (args: Record<string, unknown>) => {
786 const res = await http.handle(
787 new Request(`${ORIGIN}/mcp`, {
788 method: "POST",
789 headers: { authorization: `Bearer ${tok}`, "content-type": "application/json", accept: "application/json, text/event-stream" },
790 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "games", arguments: { box: "net", service: "smp", ...args } } }),
791 }),
792 );
793 const body = (await res.json()) as { result: { isError?: boolean; content: { text: string }[] } };
794 return { error: body.result.isError === true, value: JSON.parse(body.result.content[0]!.text) as Record<string, unknown> };
795 };
796
798797 describe("the survival performance set", () => {
799798 const SLUGS = ["chunky", "fabric-api", "lithium", "noisium", "scalablelux"];
800 const mcp = async (args: Record<string, unknown>) => {
801 const res = await http.handle(
802 new Request(`${ORIGIN}/mcp`, {
803 method: "POST",
804 headers: { authorization: `Bearer ${tok}`, "content-type": "application/json", accept: "application/json, text/event-stream" },
805 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "games", arguments: { box: "net", service: "smp", ...args } } }),
806 }),
807 );
808 const body = (await res.json()) as { result: { isError?: boolean; content: { text: string }[] } };
809 return { error: body.result.isError === true, value: JSON.parse(body.result.content[0]!.text) as Record<string, unknown> };
810 };
811799
812800 test("a plan names the four mods and Fabric API, and writes nothing", async () => {
813801 const m = await mods("smp");
@@ -1114,6 +1102,75 @@ describe("the admin set", () => {
11141102 });
11151103 });
11161104
1105 describe("did the set help (#18192)", () => {
1106 const events = () => app.db.query<{ kind: string; payload: string }, []>("SELECT kind, payload FROM event WHERE kind LIKE 'game.mods.set_%' ORDER BY id").all();
1107 const slugs = async () => (await mods("smp")).lock.map((l) => l.slug);
1108
1109 test("taking a set back and installing it again are each noted, and the take-back is one commit", async () => {
1110 expect(await slugs()).toContain("ledger");
1111 const r = await asAlice("/games/net/smp/mods/remove", { project: "set:admin", sha: (await mods("smp")).sha });
1112 expect(r.status).toBe(303);
1113 expect(await slugs()).not.toContain("luckperms");
1114 expect(await slugs()).not.toContain("fabric-language-kotlin");
1115 expect(events().at(-1)).toMatchObject({ kind: "game.mods.set_taken_back" });
1116 const back = await asAlice("/games/net/smp/mods/install", { project: "set:admin", sha: (await mods("smp")).sha });
1117 expect(back.status).toBe(303);
1118 expect(events().at(-1)).toMatchObject({ kind: "game.mods.set_installed" });
1119 expect(JSON.parse(events().at(-1)!.payload)).toMatchObject({ box: "net", service: "smp", set: "admin" });
1120 // A single project's remove is not a set's: no event.
1121 const before = events().length;
1122 const one = await planRemove(await mods("smp"), "smp", "ledger");
1123 if (!one.ok) throw new Error(one.error);
1124 expect(one.value.set).toBeUndefined();
1125 expect(events().length).toBe(before);
1126 });
1127
1128 test("a day later the page, the terminal's words and MCP all say hurt, and the take-back is previewed then committed by a person", async () => {
1129 const at = Date.now() - 25 * 3_600_000;
1130 app.db.query("UPDATE event SET created_at = ?1 WHERE kind = 'game.mods.set_installed' AND json_extract(payload, '$.set') = 'admin'").run(new Date(at).toISOString());
1131 app.db.query("UPDATE event SET created_at = ?1 WHERE kind = 'game.mods.set_taken_back'").run(new Date(at - 3_600_000).toISOString());
1132 const nowMin = Math.floor(Date.now() / 60_000);
1133 const put = app.db.query("INSERT OR REPLACE INTO game_metric (box_id, service, minute, n, players_max, players_last, players_n, tps_sum, tps_n, mspt_sum, mspt_n) VALUES (?1, 'smp', ?2, 1, 2, 2, 1, 20, 1, ?3, 1)");
1134 for (let m = nowMin - 49 * 60; m <= nowMin; m++) put.run(box.id, m, m < Math.floor(at / 60_000) ? 30 : 45);
1135 const page = await (await asAlice("/games/net/smp")).text();
1136 expect(page).toContain("hurt, tick time 30 ms → 45 ms");
1137 expect(page).toContain("20 TPS → 20 TPS; players 2 on average, 2 at most before, 2 on average, 2 at most after.");
1138 expect(page).not.toContain("Taking it back is one action");
1139 // The box's list of servers carries the word and both tick times on the server's row.
1140 const boxPage = await (await asAlice("/games/net")).text();
1141 expect(boxPage).toContain("Admin set");
1142 expect(boxPage).toContain("hurt, tick time 30 ms → 45 ms");
1143 expect(page).toContain("Preview taking it back");
1144 // MCP lists the services the box has registered: hub, with the same verdict.
1145 noteSet(app, alice.id, box, "hub", "survival", "installed", "abc");
1146 app.db.query("UPDATE event SET created_at = ?1 WHERE json_extract(payload, '$.service') = 'hub'").run(new Date(at).toISOString());
1147 app.db.query("INSERT INTO game_metric (box_id, service, minute, n, players_max, players_last, players_n, tps_sum, tps_n, mspt_sum, mspt_n) SELECT box_id, 'hub', minute, n, players_max, players_last, players_n, tps_sum, tps_n, mspt_sum, mspt_n FROM game_metric WHERE service = 'smp'").run();
1148 const asked = await mcp({ action: "list" });
1149 const items = (asked.value as { items: { services: { name: string; modSets?: string[] }[] }[] }).items;
1150 expect(items.flatMap((i) => i.services).find((s) => s.name === "hub")?.modSets?.[0]).toBe("Survival performance set: hurt. Tick time 30 ms → 45 ms, 20 TPS → 20 TPS; players 2 on average, 2 at most before, 2 on average, 2 at most after.");
1151 // Previewed: nothing is changed by looking.
1152 const shown = await (await asAlice("/games/net/smp?undo=set:admin")).text();
1153 expect(shown).toContain("Take it back and restart");
1154 expect(await slugs()).toContain("ledger");
1155 const done = await asAlice("/games/net/smp/mods/remove", { project: "set:admin", sha: (await mods("smp")).sha });
1156 expect(done.status).toBe(303);
1157 expect(await slugs()).not.toContain("ledger");
1158 expect(await (await asAlice("/games/net/smp")).text()).not.toContain("Admin set: hurt");
1159 });
1160
1161 test("the terminal's server screen says the same, and where the take-back is", async () => {
1162 const terminal = headlessTerminal(300, 30);
1163 const { app: tui, session } = createForgeApp(app, { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice }, { terminal, exitHooks: false });
1164 tui.start();
1165 tui.ctx.push(gameServiceScreen(session, tui.ctx, box, "hub"));
1166 await settleUntil(tui, "[console]");
1167 terminal.feed("\t\t");
1168 await settleUntil(tui, "Survival performance set: hurt. Tick time 30 ms → 45 ms");
1169 expect(tui.screen.toText()).toContain("d then set:survival previews it");
1170 tui.stop?.();
1171 });
1172 });
1173
11171174 describe("a slug the lock holds is not followed to another project (#18196)", () => {
11181175 const REFUSED = "essential-commands is now project ECid0002 by mallory; the lock holds ECid0001 by patbox — nothing installed. If it moved on purpose, remove Essential Commands and add essential-commands again.";
11191176 const IMPOSTOR = { id: "ECid0002", slug: "essential-commands", title: "Essential Commands" };
test/set-verdict.test.ts added +142
@@ -0,0 +1,142 @@
1 /**
2 * Did a mod set help (#18192): the four words from plain numbers, and the verdict read from the
3 * event the install leaves and the minutes the box reported, with a restart and a short record
4 * kept out of the way.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { createUser } from "../src/core/users.ts";
12 import { createGameBox, boxNamed } from "../src/games/store.ts";
13 import { judge, noteSet, verdictsOf, type Reading } from "../src/games/set_verdict.ts";
14 import { quietLogs } from "./helpers/globals.ts";
15
16 quietLogs();
17
18 const reading = (o: Partial<Reading> = {}): Reading => ({ samples: 100, tps: 20, mspt: 40, players: 3, peak: 5, ...o });
19
20 describe("judge: four words", () => {
21 test("helped: tick time down 10% or more, TPS not lower", () => {
22 expect(judge(reading(), reading({ mspt: 36 }))).toBe("helped");
23 expect(judge(reading({ tps: 19.5 }), reading({ mspt: 20, tps: 19.5 }))).toBe("helped");
24 });
25 test("no change: tick time within 10% and TPS the same", () => {
26 expect(judge(reading(), reading({ mspt: 38 }))).toBe("no change");
27 expect(judge(reading(), reading({ mspt: 43, tps: 19.98 }))).toBe("no change");
28 });
29 test("hurt: tick time up 10% or more, or TPS down, even with a faster tick", () => {
30 expect(judge(reading(), reading({ mspt: 44 }))).toBe("hurt");
31 expect(judge(reading(), reading({ mspt: 20, tps: 19.2 }))).toBe("hurt");
32 });
33 test("not enough numbers: fewer than 12 samples on either side, or none of a measure", () => {
34 expect(judge(reading({ samples: 11 }), reading())).toBe("not enough numbers");
35 expect(judge(reading(), reading({ samples: 11 }))).toBe("not enough numbers");
36 expect(judge(reading(), reading({ mspt: null }))).toBe("not enough numbers");
37 expect(judge(reading({ samples: 12 }), reading({ samples: 12, mspt: 30 }))).toBe("helped");
38 });
39 });
40
41 describe("verdictsOf: from the event and the minutes", () => {
42 let dir: string;
43 let app: App;
44 const T = Date.parse("2026-12-01T12:00:00.000Z");
45 const tMin = T / 60_000;
46 let n = 0;
47 let actor = "";
48 const newBox = () => {
49 const name = `net${++n}`;
50 createGameBox(app.db, { name });
51 return boxNamed(app.db, name)!;
52 };
53 const minutes = (boxId: string, from: number, count: number, mspt: number, tps = 20, players = 2) => {
54 const q = app.db.query("INSERT OR REPLACE INTO game_metric (box_id, service, minute, n, players_max, players_last, players_n, tps_sum, tps_n, mspt_sum, mspt_n) VALUES (?1, 'smp', ?2, 1, ?3, ?3, 1, ?4, 1, ?5, 1)");
55 for (let i = 0; i < count; i++) q.run(boxId, from + i, players + (i % 2), tps, mspt);
56 };
57 const installed = (box: { id: string; name: string }, op: "installed" | "taken_back" = "installed") => {
58 noteSet(app, actor, box, "smp", "survival", op, "abc");
59 app.db.query("UPDATE event SET created_at = ?1 WHERE id = (SELECT id FROM event ORDER BY id DESC LIMIT 1)").run(new Date(T).toISOString());
60 };
61 const now = new Date(T + 25 * 3_600_000);
62
63 beforeAll(async () => {
64 dir = await mkdtemp(join(tmpdir(), "forge-set-verdict-"));
65 app = createApp({ dataDir: dir, port: 0 });
66 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "correct horse battery" });
67 if (!made.ok) throw new Error("no user");
68 actor = made.value.id;
69 }, 30_000);
70 afterAll(async () => {
71 app.close();
72 await rm(dir, { recursive: true, force: true });
73 });
74
75 test("helped, with both numbers and the players on in each window, in one sentence", () => {
76 const box = newBox();
77 installed(box);
78 minutes(box.id, tMin - 1440, 1440, 50);
79 minutes(box.id, tMin, 1440, 30, 20, 4);
80 const [v] = verdictsOf(app.db, box, "smp", now);
81 expect(v).toMatchObject({ set: "survival", word: "helped", takeBack: null, before: { mspt: 50, tps: 20, samples: 1440 }, after: { mspt: 30, players: 4.5, peak: 5 } });
82 expect(v!.says).toBe("Survival performance set: helped. Tick time 50 ms → 30 ms, 20 TPS → 20 TPS; players 2.5 on average, 3 at most before, 4.5 on average, 5 at most after.");
83 });
84
85 test("hurt names the take-back, and nothing in verdictsOf takes anything back", () => {
86 const box = newBox();
87 installed(box);
88 minutes(box.id, tMin - 1440, 1440, 30);
89 minutes(box.id, tMin, 1440, 45);
90 const [v] = verdictsOf(app.db, box, undefined, now);
91 expect(v).toMatchObject({ word: "hurt", takeBack: "set:survival" });
92 expect(v!.short).toBe("hurt, tick time 30 ms → 45 ms");
93 });
94
95 test("no change, and not enough numbers when the box reported little", () => {
96 const a = newBox();
97 installed(a);
98 minutes(a.id, tMin - 1440, 1440, 40);
99 minutes(a.id, tMin, 1440, 41);
100 expect(verdictsOf(app.db, a, "smp", now)[0]!.word).toBe("no change");
101 const b = newBox();
102 installed(b);
103 minutes(b.id, tMin - 1440, 1440, 40);
104 minutes(b.id, tMin, 5, 20);
105 const [v] = verdictsOf(app.db, b, "smp", now);
106 expect(v!.word).toBe("not enough numbers");
107 expect(v!.says).toContain("not enough numbers");
108 });
109
110 test("before the day is over it only says it is measuring", () => {
111 const box = newBox();
112 installed(box);
113 minutes(box.id, tMin - 1440, 1440, 40);
114 const [v] = verdictsOf(app.db, box, "smp", new Date(T + 20 * 3_600_000));
115 expect(v).toMatchObject({ word: null, takeBack: null });
116 expect(v!.says).toBe("Survival performance set: measuring, the verdict comes in 4 h.");
117 });
118
119 test("a restart inside the window is not a hurt: the minutes after a start are left out", () => {
120 const box = newBox();
121 installed(box);
122 minutes(box.id, tMin - 1440, 1440, 40);
123 minutes(box.id, tMin, 1440, 30);
124 // Slow ticks as a cold server warms up, twice: at the install and on the second night.
125 for (const at of [tMin + 2, tMin + 600]) {
126 minutes(box.id, at, 10, 400);
127 app.db.query("INSERT INTO game_player_event (box_id, service, player, kind, at) VALUES (?1, 'smp', '', 'start', ?2)").run(box.id, new Date(at * 60_000).toISOString());
128 }
129 expect(verdictsOf(app.db, box, "smp", now)[0]).toMatchObject({ word: "helped", after: { mspt: 30 } });
130 });
131
132 test("a set taken back is no longer judged, and another server's install is not shown", () => {
133 const box = newBox();
134 installed(box);
135 minutes(box.id, tMin - 1440, 1440, 30);
136 minutes(box.id, tMin, 1440, 45);
137 expect(verdictsOf(app.db, box, "smp", now)).toHaveLength(1);
138 expect(verdictsOf(app.db, box, "other", now)).toHaveLength(0);
139 noteSet(app, actor, box, "smp", "survival", "taken_back", "def");
140 expect(verdictsOf(app.db, box, "smp", now)).toHaveLength(0);
141 });
142 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs