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

Build the duty roster on first ask, so a duty imported first is never read ha… #17241

opened this in answer to

Merged 42h 26m ago, live in production

mason/forge:mason/17207-build-the-duty-roster-on-first-ask-so-a → main 0 commits fork 2 threads · 2 unresolved

  • Merged. mason/17207-build-the-duty-roster-on-first-ask-so-a was merged into main as dd5bb60.

Review

Sign in to review this change.
42 files changed +112 −93
src/http/mcp/tools/system.ts +1 −1
@@ -107,7 +107,7 @@ export const tool: Tool = {
107107 const reader = telemetryReader(ctx.app, user);
108108 if (!reader) return badBlocked("forbidden", noTelemetryBlocked(ctx.app, user, "Reading this forge's maintenance workers takes the telemetry:read grant."));
109109 noteRead(ctx.app, user, reader, "system");
110 return good({ workers: weekRows(ctx.app.db, duties.map((d) => d.name)).map((w) => ({ ...w, says: resultWords(w) })) });
110 return good({ workers: weekRows(ctx.app.db, duties().map((d) => d.name)).map((w) => ({ ...w, says: resultWords(w) })) });
111111 }
112112 if (args["kind"] === "adopted") {
113113 if (!user.isAdmin) return bad("forbidden", "only an admin of this forge reads its child forges across a restart");
src/maintain/lanes.ts +2 −2
@@ -61,10 +61,10 @@ export function readLanes(db: Database, now: Date): Lane[] {
6161 )
6262 .all(names, from, to, week) as Row[];
6363 const by = new Map(rows.map((r) => [r.duty, r]));
64 const budgets = budgetsOf(db, duties);
64 const budgets = budgetsOf(db, duties());
6565 return LANES.map((l) => {
6666 const r = by.get(l.duty);
67 const switchable = duties.some((d) => d.name === l.duty);
67 const switchable = duties().some((d) => d.name === l.duty);
6868 const paused = switchable && isPaused(db, l.duty);
6969 const result = paused ? "paused" : r?.outcome == null ? null : r.outcome === "ok" ? "ok" : "failed";
7070 return {
src/maintain/pause.ts +2 −2
@@ -116,7 +116,7 @@ function stateWords(name: string, s: Row | null, last: string | undefined, f: {
116116 * after a duty's newest `ok` (and after its last resume), the only ones `failing` can count.
117117 */
118118 export function dutyStates(db: Database, now = Date.now()): DutyState[] {
119 const names = JSON.stringify(registered.map((d) => d.name));
119 const names = JSON.stringify(registered().map((d) => d.name));
120120 const heads = db
121121 .query(
122122 `SELECT d.value AS name, s.paused, s.reason, s.by, s.since, s.from_run,
@@ -146,7 +146,7 @@ export function dutyStates(db: Database, now = Date.now()): DutyState[] {
146146 });
147147 }
148148
149 export const knownDuty = (name: string): boolean => registered.some((d) => d.name === name);
149 export const knownDuty = (name: string): boolean => registered().some((d) => d.name === name);
150150
151151 /** One switch for page, API and MCP: the same words. */
152152 export function switchDuty(db: Database, name: unknown, paused: unknown, by: string): { ok: true; says: string } | { ok: false; code: "invalid" | "not_found"; says: string } {
src/maintain/registry.ts +12 −6
@@ -23,10 +23,16 @@ export function rosterOf(modules: readonly (readonly [string, () => { duty?: unk
2323 });
2424 }
2525
26 /**
27 * The roster as `src/generated/duties.ts` lists it (a pull that adds a duty file regenerates it).
28 */
29 const others: readonly Duty[] = rosterOf(DUTY_MODULES);
26 let built: readonly Duty[] | undefined;
3027
31 /** The duties plus the one that watches them for silence. */
32 export const duties: readonly Duty[] = [...others, dutyIdle(others)];
28 /**
29 * The roster, built on first ask and never at import: a duty whose own graph reaches the registry
30 * cannot see its `duty` uninitialised (#17155).
31 */
32 export function duties(): readonly Duty[] {
33 if (built === undefined) {
34 const others = rosterOf(DUTY_MODULES);
35 built = [...others, dutyIdle(others)];
36 }
37 return built;
38 }
src/maintain/runner.ts +1 −1
@@ -32,7 +32,7 @@ export interface Maintain {
3232 }
3333
3434 export function startMaintain(app: App, options: { duties?: readonly Duty[]; everyMs?: number; timeoutMs?: number; keep?: number } = {}): Maintain {
35 const list = options.duties ?? registered;
35 const list = options.duties ?? registered();
3636 const seen = new Set<string>();
3737 for (const d of list) {
3838 if (!validName(d.name)) throw new Error(`maintenance duty name "${d.name}" is not lowercase words and dashes`);
src/maintain/schedule.ts +1 −1
@@ -55,7 +55,7 @@ export function scheduleOf(o: { lastStarted: number | undefined; intervalMs: num
5555 export function dutySchedules(db: Database, states: readonly { name: string; paused: boolean }[], now: number): Map<string, Schedule> {
5656 const results = lastResultAll(db);
5757 const paused = new Map(states.map((d) => [d.name, d.paused]));
58 return new Map(registered.map((d) => [d.name, scheduleOf({ lastStarted: results.get(d.name)?.started, intervalMs: d.intervalMs, paused: paused.get(d.name) === true, now, last: results.get(d.name) })]));
58 return new Map(registered().map((d) => [d.name, scheduleOf({ lastStarted: results.get(d.name)?.started, intervalMs: d.intervalMs, paused: paused.get(d.name) === true, now, last: results.get(d.name) })]));
5959 }
6060
6161 /**
src/tui/screens/dutybudgets.ts +3 −3
@@ -19,7 +19,7 @@ const mayAct = (session: Session): boolean => session.user?.isAdmin === true &&
1919 /** One duty a line, the chosen one marked; empty for anyone the gate refuses. */
2020 export function budgetLines(session: Session, chosen: number): string[] {
2121 if (!mayAct(session)) return [];
22 return duties.map((d, i) => {
22 return duties().map((d, i) => {
2323 const b = budgetOf(session.db, d);
2424 const u = usedToday(session.db, d.name, new Date());
2525 return `${i === chosen ? ">" : " "} ${d.name}: ${u.runs} of ${b.runsPerDay} runs, $${u.dollars.toFixed(2)} of $${b.dollarsPerDay.toFixed(2)} today (${d.budget.reason})`;
@@ -29,7 +29,7 @@ export function budgetLines(session: Session, chosen: number): string[] {
2929 /** Move the chosen duty's budget by `delta` (or back to its own with `reset`); what it says, or nothing for anyone the gate refuses. */
3030 export function moveBudget(session: Session, chosen: number, kind: BudgetKind, delta: number, reset = false): string {
3131 if (!mayAct(session)) return "";
32 const d = duties[chosen];
32 const d = duties()[chosen];
3333 if (d === undefined) return "";
3434 const actor = session.user!.id;
3535 if (reset) {
@@ -58,7 +58,7 @@ export function dutyBudgetScreen(session: Session, ctx: Ctx): Screen {
5858 key(e) {
5959 if (e.ctrl || e.alt) return true;
6060 if (e.key === "esc" || e.key === "q") ctx.pop();
61 else if (e.key === "j" || e.key === "down") chosen = Math.min(chosen + 1, duties.length - 1);
61 else if (e.key === "j" || e.key === "down") chosen = Math.min(chosen + 1, duties().length - 1);
6262 else if (e.key === "k" || e.key === "up") chosen = Math.max(chosen - 1, 0);
6363 else if (e.key === "+") note = moveBudget(session, chosen, "runs", 1);
6464 else if (e.key === "-") note = moveBudget(session, chosen, "runs", -1);
src/tui/screens/maintenanceweek.ts +1 −1
@@ -21,7 +21,7 @@ const mayRead = (session: Session): boolean => telemetryReader(session.app, sess
2121 /** The screen's lines; empty for anyone the gate refuses. */
2222 export function weekLines(session: Session, now = new Date()): string[] {
2323 if (!mayRead(session)) return [];
24 const rows = weekRows(session.app.db, duties.map((d) => d.name), now);
24 const rows = weekRows(session.app.db, duties().map((d) => d.name), now);
2525 const width = Math.max(0, ...rows.map((r) => r.name.length));
2626 return [
2727 weekWords(rows),
src/web/pages/maintenance_budgets.ts +3 −3
@@ -16,10 +16,10 @@ import { btn, field as formControl } from "../ui.ts";
1616
1717 /** Every duty's budget row, in `names` order: two reads for all of them, not three a duty. */
1818 export function budgetRows(app: App, names: readonly string[], now = new Date()): Html[] {
19 const budgets = budgetsOf(app.db, duties);
19 const budgets = budgetsOf(app.db, duties());
2020 const used = usedTodayAll(app.db, now);
2121 return names.map((name) => {
22 const d = duties.find((x) => x.name === name);
22 const d = duties().find((x) => x.name === name);
2323 const b = budgets.get(name);
2424 return d === undefined || b === undefined ? html`` : budgetOfRow(d, b, used.get(name) ?? { runs: 0, dollars: 0 });
2525 });
@@ -44,7 +44,7 @@ export async function maintenanceBudget(ctx: Ctx): Promise<Response> {
4444 if (user === undefined || !user.isAdmin || user.kind === "agent") return flashTo(ctx, "/maintenance", { tone: "danger", message: "Only a forge admin who is a person sets a budget." });
4545 const form = await readForm(ctx, "admin");
4646 if (form instanceof Response) return form;
47 const duty = duties.find((d) => d.name === formField(form, "duty"));
47 const duty = duties().find((d) => d.name === formField(form, "duty"));
4848 if (duty === undefined) return flashTo(ctx, "/maintenance", { tone: "danger", message: "No such duty." });
4949 const picked: [("runs" | "dollars"), number | null][] = [];
5050 for (const kind of ["runs", "dollars"] as const) {
src/web/pages/system.ts +1 −1
@@ -836,7 +836,7 @@ export async function systemPage(ctx: Ctx, patterns: () => readonly string[]): P
836836 ${routeUseSection(timePhase(ctx.request, "routes", () => {
837837 return leastUsed(routeUsage(ctx.app.db, patterns(), new Date()));
838838 }))}
839 ${maintenanceSection(timePhase(ctx.request, "maintenance", () => weekRows(ctx.app.db, duties.map((d) => d.name))), timePhase(ctx.request, "starts", () => startStats(ctx.app.db, new Date(Date.now() - 7 * 86_400_000).toISOString())))}
839 ${maintenanceSection(timePhase(ctx.request, "maintenance", () => weekRows(ctx.app.db, duties().map((d) => d.name))), timePhase(ctx.request, "starts", () => startStats(ctx.app.db, new Date(Date.now() - 7 * 86_400_000).toISOString())))}
840840 ${footprintSection(lastFootprint() ?? lastProof(ctx.app.config.dataDir)?.footprint ?? null)}
841841 ${footingSection(standsOn)}
842842 ${restoreSection(timePhase(ctx.request, "restore", () => restoreLine(lastPass(ctx.app.db), lastDrill(ctx.app.db), Date.now())))}
test/account-purge.test.ts +1 −1
@@ -45,7 +45,7 @@ afterAll(() => rmSync(root, { recursive: true, force: true }));
4545 describe("the purge", () => {
4646 test("is a duty on the roster, hourly", async () => {
4747 const { duties } = await import("../src/maintain/registry.ts");
48 expect(duties.some((d) => d.name === "account-purge")).toBe(true);
48 expect(duties().some((d) => d.name === "account-purge")).toBe(true);
4949 expect(duty.intervalMs).toBe(3_600_000);
5050 });
5151
test/cloud-watch.test.ts +1 −1
@@ -82,7 +82,7 @@ describe("cloud watch", () => {
8282 });
8383
8484 test("the duty is on the roster", () => {
85 expect(duties.map((d) => d.name)).toContain("cloud-watch");
85 expect(duties().map((d) => d.name)).toContain("cloud-watch");
8686 });
8787
8888 test("the forge's own machine and volume are quiet, and the page says when it looked", async () => {
test/duty-idle.test.ts +1 −1
@@ -20,7 +20,7 @@ const run = (at: number) => watcher.run({ db: w.app.db, bus: w.app.bus, now: new
2020 const defects = () => w.titles().filter((t) => t === titleOf("quiet-one"));
2121
2222 test("registered, and a duty that never ran or ran recently files nothing", async () => {
23 expect(duties.map((d) => d.name)).toContain(NAME);
23 expect(duties().map((d) => d.name)).toContain(NAME);
2424 expect((await run(T0)).actions).toEqual([]);
2525 ran(T0);
2626 expect((await run(T0 + 20 * MIN)).actions).toEqual([]); // exactly twice: not over
test/duty-roster-order.test.ts added +13
@@ -0,0 +1,13 @@
1 import { expect, test } from "bun:test";
2
3 test("a duty imported before the registry still joins the roster (#17155)", async () => {
4 const p = Bun.spawn([process.execPath, "-e", `
5 await import("./src/maintain/duties/flow_keeper.ts");
6 const { duties } = await import("./src/maintain/registry.ts");
7 const { DUTY_MODULES } = await import("./src/generated/duties.ts");
8 if (duties().length !== DUTY_MODULES.length + 1) process.exit(2);
9 `], { cwd: `${import.meta.dir}/..`, stdout: "pipe", stderr: "pipe" });
10 const err = await new Response(p.stderr).text();
11 expect(err).not.toContain("before initialization");
12 expect(await p.exited).toBe(0);
13 });
test/duty-roster.test.ts +3 −3
@@ -12,9 +12,9 @@ import { validName } from "../src/maintain/duty.ts";
1212 test("every duty file is on the roster, once, and the idle watcher is last", () => {
1313 const files = readdirSync("src/maintain/duties").filter((f) => f.endsWith(".ts") && f !== "duty_idle.ts");
1414 expect(dutyFiles(new URL("../src/maintain/duties/", import.meta.url))).toEqual(files.sort());
15 expect(duties.length).toBe(files.length + 1);
16 expect(duties.at(-1)?.name).toBe(NAME);
17 const names = duties.map((d) => d.name);
15 expect(duties().length).toBe(files.length + 1);
16 expect(duties().at(-1)?.name).toBe(NAME);
17 const names = duties().map((d) => d.name);
1818 expect(new Set(names).size).toBe(names.length);
1919 for (const n of names) expect(validName(n)).toBe(true);
2020 });
test/efficiency-runner.test.ts +1 −1
@@ -38,7 +38,7 @@ function falling(now: number): void {
3838 }
3939
4040 test("run by the runner with the app, the duty finds the fall; the admin screen lists it", async () => {
41 expect(duties.map((d) => d.name)).toContain("efficiency-watcher");
41 expect(duties().map((d) => d.name)).toContain("efficiency-watcher");
4242 const now = Date.now();
4343 falling(now);
4444 const m = startMaintain(app, { duties: [duty], everyMs: 1e9 });
test/maint-stale-branches.test.ts +1 −1
@@ -56,7 +56,7 @@ test("lists stale branches without an open pull, never the default or a pulled o
5656 });
5757
5858 test("the duty files one finding with a count, is registered, and deletes nothing", async () => {
59 expect(duties).toContain(duty);
59 expect(duties()).toContain(duty);
6060 const r = await duty.run({ db: app.db, bus: app.bus, now: NOW, app });
6161 expect(r.findings).toHaveLength(1);
6262 expect(r.findings[0]!.probe?.number).toBe(2);
test/maint-untested.test.ts +1 −1
@@ -57,5 +57,5 @@ test("an empty list files nothing", async () => {
5757 });
5858
5959 test("it is registered", () => {
60 expect(duties.map((d) => d.name)).toContain("untested-sources");
60 expect(duties().map((d) => d.name)).toContain("untested-sources");
6161 });
test/maintain-backup-age.test.ts +2 −2
@@ -36,7 +36,7 @@ const run = (hours: number) => duty.run(at(hours));
3636 const filed = () => w.titles().filter((t) => t === TITLE);
3737
3838 test("the duty is registered", () => {
39 expect(duties.map((d) => d.name)).toContain("backup-age");
39 expect(duties().map((d) => d.name)).toContain("backup-age");
4040 });
4141
4242 test("a backup under 36 hours old files nothing", async () => {
@@ -80,7 +80,7 @@ test("no backup directory set, or an empty one, is quiet", async () => {
8080 });
8181
8282 test("the maintenance board lists backup-age as a row", () => {
83 const rows = weekRows(w.app.db, duties.map((d) => d.name));
83 const rows = weekRows(w.app.db, duties().map((d) => d.name));
8484 expect(rows.map((r) => r.name)).toContain("backup-age");
8585 });
8686
test/maintain-dead-doc-paths.test.ts +1 −1
@@ -40,7 +40,7 @@ test("the duty makes one finding with a probe, and none when nothing is dead", a
4040 });
4141
4242 test("the duty is registered", () => {
43 expect(duties).toContain(duty);
43 expect(duties()).toContain(duty);
4444 });
4545
4646 test("one finding per doc, every dead path listed, and the terminal's run board counts them", async () => {
test/maintain-disk-free.test.ts +1 −1
@@ -116,5 +116,5 @@ test("dataSizes sums every top-level directory and the loose files, largest firs
116116 });
117117
118118 test("the duty is in the registry", () => {
119 expect(duties.map((d) => d.name)).toContain("disk-free");
119 expect(duties().map((d) => d.name)).toContain("disk-free");
120120 });
test/maintain-duty-states.test.ts +3 −3
@@ -30,8 +30,8 @@ const run = (duty: string, outcome: string) => {
3030 };
3131
3232 test("every duty's state, batched, is the state read one duty at a time", async () => {
33 expect(duties.length).toBeGreaterThan(7);
34 const [byPerson, byRunner, failingOn, erroredOnce, resumed, budgeted, okAfterErrors] = duties.map((d) => d.name);
33 expect(duties().length).toBeGreaterThan(7);
34 const [byPerson, byRunner, failingOn, erroredOnce, resumed, budgeted, okAfterErrors] = duties().map((d) => d.name);
3535 setPaused(app.db, byPerson!, true, "alice", new Date(t));
3636 for (const o of ["ok", "failed: one", "failed: two", "failed: three\nmore"]) run(byRunner!, o);
3737 pauseOnErrors(app.db, byRunner!, new Date(t));
@@ -46,7 +46,7 @@ test("every duty's state, batched, is the state read one duty at a time", async
4646
4747 const now = t + 3_600_000;
4848 const batched = dutyStates(app.db, now);
49 expect(batched).toEqual(duties.map((d) => dutyState(app.db, d.name, now)));
49 expect(batched).toEqual(duties().map((d) => dutyState(app.db, d.name, now)));
5050 const said = new Map(batched.map((s) => [s.name, s.detail]));
5151 expect(said.get(failingOn!)).toStartWith("on; failing since ");
5252 expect(said.get(budgeted!)).toStartWith("on; failing since ");
test/maintain-edge-kept.test.ts +1 −1
@@ -65,7 +65,7 @@ async function run(read: Get, url: string | undefined = "https://forge.example",
6565 const shareable = (edge: Record<string, string>): Get => async () => h({ "cache-control": "public, max-age=0, s-maxage=60", ...edge });
6666
6767 test("the duty is on the roster, hourly, and reads only the configured URL", async () => {
68 expect(duties.find((d) => d.name === "edge-kept")?.intervalMs).toBe(3_600_000);
68 expect(duties().find((d) => d.name === "edge-kept")?.intervalMs).toBe(3_600_000);
6969 const seen: string[] = [];
7070 const { once } = await run(async (u) => (seen.push(u), h({ "cache-control": "public, s-maxage=60", "cf-cache-status": "HIT" })));
7171 const r = await once();
test/maintain-edge-resilience.test.ts +1 −1
@@ -34,7 +34,7 @@ test("it pushes on boot, again only when the map changes, and says when the edge
3434
3535 test("the duty is on the roster, silent without an edge, and pushes the page with one", async () => {
3636 forgetPushed();
37 expect(duties.find((d) => d.name === "edge-resilience")?.intervalMs).toBe(60_000);
37 expect(duties().find((d) => d.name === "edge-resilience")?.intervalMs).toBe(60_000);
3838 const app = createApp({ dataDir: mkdtempSync(join(tmpdir(), "edge-res-")), port: 0 });
3939 const bodies: string[] = [];
4040 const put: Put = async (_u, init) => (bodies.push(init.body), { ok: true, status: 200 });
test/maintain-failing.test.ts +1 −1
@@ -25,7 +25,7 @@ let app: App;
2525 let servers: Servers;
2626 let admin = "";
2727 let adminId = "";
28 const name = duties[0]!.name;
28 const name = duties()[0]!.name;
2929 beforeAll(async () => {
3030 root = mkdtempSync(join(tmpdir(), "forge-failing-"));
3131 app = createApp({ dataDir: root, port: 0 });
test/maintain-flaky-tests.test.ts +1 −1
@@ -39,5 +39,5 @@ test("files that flaked in the week are named with counts", async () => {
3939 });
4040
4141 test("it is registered", () => {
42 expect(duties.map((d) => d.name)).toContain("flaky-tests");
42 expect(duties().map((d) => d.name)).toContain("flaky-tests");
4343 });
test/maintain-merged-branches.test.ts +1 −1
@@ -70,7 +70,7 @@ test("never lists main, even when a pull merged from it", async () => {
7070 });
7171
7272 test("the duty posts one finding with a number, and is registered", async () => {
73 expect(duties).toContain(duty);
73 expect(duties()).toContain(duty);
7474 const r = await duty.run({ db: app.db, bus: app.bus, now: NOW, app });
7575 expect(r.findings).toHaveLength(1);
7676 expect(r.findings[0]!.probe?.number).toBe(1);
test/maintain-nothing.test.ts +1 −1
@@ -57,7 +57,7 @@ test("a run with a finding says so and is not 'nothing'", async () => {
5757
5858 test("the schedule read from the runs table says 'checked' for a clean row and 'found' for a finding", async () => {
5959 const { duties } = await import("../src/maintain/registry.ts");
60 const { clean, found } = { clean: duties[0]!, found: duties[1]! };
60 const { clean, found } = { clean: duties()[0]!, found: duties()[1]! };
6161 app.db.exec("DELETE FROM maintenance_run");
6262 const at = new Date(Date.now() - 3 * H).toISOString();
6363 const ins = app.db.query("INSERT INTO maintenance_run (duty, started, finished, findings, outcome) VALUES (?1, ?2, ?2, ?3, 'ok')");
test/maintain-pause.test.ts +1 −1
@@ -21,7 +21,7 @@ let app: App;
2121 let servers: Servers;
2222 let admin = "";
2323 let ro = "";
24 const name = duties[0]!.name;
24 const name = duties()[0]!.name;
2525
2626 beforeAll(async () => {
2727 root = mkdtempSync(join(tmpdir(), "forge-pause-"));
test/maintain-previews-duty.test.ts +1 −1
@@ -50,7 +50,7 @@ afterAll(async () => {
5050 });
5151
5252 test("the duty is registered, and with nothing old it finds nothing", async () => {
53 expect(duties.some((d) => d.name === "preview-dirs")).toBe(true);
53 expect(duties().some((d) => d.name === "preview-dirs")).toBe(true);
5454 expect(await duty.run(ctx())).toEqual({ findings: [], actions: [] });
5555 });
5656
test/maintain-red-apps.test.ts +1 −1
@@ -52,5 +52,5 @@ test("recovered: a green latest check files nothing, even after the old issue is
5252 });
5353
5454 test("the duty is in the registry", () => {
55 expect(duties.map((d) => d.name)).toContain("red-apps");
55 expect(duties().map((d) => d.name)).toContain("red-apps");
5656 });
test/maintain-slow-tests.test.ts +1 −1
@@ -62,7 +62,7 @@ test("a stored log without timings is said, not guessed", async () => {
6262 });
6363
6464 test("it is registered", () => {
65 expect(duties.map((d) => d.name)).toContain("slow-tests");
65 expect(duties().map((d) => d.name)).toContain("slow-tests");
6666 });
6767
6868 test("the slow-tests duty is one of the rows /maintenance lists, on, from the same registry", () => {
test/maintain-stale-issues.test.ts +1 −1
@@ -62,5 +62,5 @@ test("at most 20 names, the rest counted; a closed report lets the next night fi
6262 });
6363
6464 test("the duty is in the registry", () => {
65 expect(duties.map((d) => d.name)).toContain("stale-issues");
65 expect(duties().map((d) => d.name)).toContain("stale-issues");
6666 });
test/maintain-v1-proven.test.ts +1 −1
@@ -120,7 +120,7 @@ test("no public origin: nothing is called", async () => {
120120 });
121121
122122 test("the duty is registered, weekly", () => {
123 expect(duties.find((d) => d.name === "v1-proven")?.intervalMs).toBe(7 * 86_400_000);
123 expect(duties().find((d) => d.name === "v1-proven")?.intervalMs).toBe(7 * 86_400_000);
124124 });
125125
126126 test("a passing probe notes it once on its open defect and leaves it open; the defect is found by its body key, not its title", async () => {
test/maintain-wait-split.test.ts +1 −1
@@ -118,7 +118,7 @@ test("the run's bound sits under the runner's deadline", () => {
118118 });
119119
120120 test("the forge runs it", () => {
121 expect(duties.map((d) => d.name)).toContain("wait-split");
121 expect(duties().map((d) => d.name)).toContain("wait-split");
122122 });
123123
124124 test("in a cell the duty never asks its own public host: loopback alone, and the line says so (#14664)", async () => {
test/maintain.test.ts +32 −32
@@ -102,8 +102,8 @@ test("a duty that throws is recorded as failed and the next still runs", async (
102102
103103 test("the pulls duty is registered and a run with no quiet pull leaves an ok row with no findings", async () => {
104104 clear();
105 expect(duties.map((d) => d.name)).toContain("stale-pulls");
106 const m = startMaintain(app, { duties: duties.filter((d) => d.name === "stale-pulls"), everyMs: 1e9 });
105 expect(duties().map((d) => d.name)).toContain("stale-pulls");
106 const m = startMaintain(app, { duties: duties().filter((d) => d.name === "stale-pulls"), everyMs: 1e9 });
107107 m.stop();
108108 await m.tick(new Date("2026-11-11T12:00:00Z"));
109109 const [row] = latest(app.db, 1);
@@ -239,7 +239,7 @@ test("a stored budget replaces the declared one, and a blank takes it back; the
239239 expect(parseBudget("runs", "0")).toBeUndefined();
240240 expect(parseBudget("runs", "1e3")).toBeUndefined();
241241 expect(parseBudget("dollars", "0.5")).toBe(0.5);
242 for (const d of duties) expect(d.budget.reason.length).toBeGreaterThan(10);
242 for (const d of duties()) expect(d.budget.reason.length).toBeGreaterThan(10);
243243 });
244244
245245 test("POST /maintenance/budget moves a budget for an admin, refuses a bad number, and the page shows the reason", async () => {
@@ -249,42 +249,42 @@ test("POST /maintenance/budget moves a budget for an admin, refuses a bad number
249249 const cookie = `forge_session=${createSession(app.db, adminId).token}`;
250250 const post = (body: Record<string, string>) =>
251251 fetch(`${servers.url}/maintenance/budget`, { method: "POST", redirect: "manual", headers: { cookie, origin: servers.url, "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(body) });
252 const name = duties[0]!.name;
252 const name = duties()[0]!.name;
253253 expect((await post({ duty: name, runs: "7", dollars: "2.5" })).status).toBe(303);
254254 const { budgetOf } = await import("../src/maintain/budget.ts");
255 expect(budgetOf(app.db, duties[0]!)).toEqual({ runsPerDay: 7, dollarsPerDay: 2.5 });
255 expect(budgetOf(app.db, duties()[0]!)).toEqual({ runsPerDay: 7, dollarsPerDay: 2.5 });
256256 await post({ duty: name, runs: "0", dollars: "2.5" });
257 expect(budgetOf(app.db, duties[0]!).runsPerDay).toBe(7);
257 expect(budgetOf(app.db, duties()[0]!).runsPerDay).toBe(7);
258258 await post({ duty: name, runs: "", dollars: "" });
259 expect(budgetOf(app.db, duties[0]!).runsPerDay).toBe(duties[0]!.budget.runsPerDay);
259 expect(budgetOf(app.db, duties()[0]!).runsPerDay).toBe(duties()[0]!.budget.runsPerDay);
260260 const page = await (await fetch(`${servers.url}/maintenance`, { headers: { cookie } })).text();
261 expect(page).toContain(duties[0]!.budget.reason);
261 expect(page).toContain(duties()[0]!.budget.reason);
262262 });
263263
264264 test("only an admin moves a budget: a non-admin, a guest and a cross-origin post are refused and nothing changes", async () => {
265265 const { createSession } = await import("../src/core/sessions.ts");
266266 const { budgetOf } = await import("../src/maintain/budget.ts");
267267 const id = (n: string) => (app.db.query("SELECT id FROM user WHERE username = ?1").get(n) as { id: string }).id;
268 const own = { ...budgetOf(app.db, duties[0]!) };
268 const own = { ...budgetOf(app.db, duties()[0]!) };
269269 const post = (cookie: string, origin: string) =>
270270 fetch(`${servers.url}/maintenance/budget`, {
271271 method: "POST", redirect: "manual",
272272 headers: { ...(cookie ? { cookie } : {}), origin, "content-type": "application/x-www-form-urlencoded" },
273 body: new URLSearchParams({ duty: duties[0]!.name, runs: "3", dollars: "3" }),
273 body: new URLSearchParams({ duty: duties()[0]!.name, runs: "3", dollars: "3" }),
274274 });
275275 const bobCookie = `forge_session=${createSession(app.db, id("bob")).token}`;
276276 const aliceCookie = `forge_session=${createSession(app.db, id("alice")).token}`;
277277 await post(bobCookie, servers.url);
278 expect(budgetOf(app.db, duties[0]!)).toEqual(own);
278 expect(budgetOf(app.db, duties()[0]!)).toEqual(own);
279279 await post("", servers.url);
280 expect(budgetOf(app.db, duties[0]!)).toEqual(own);
280 expect(budgetOf(app.db, duties()[0]!)).toEqual(own);
281281 app.db.query("UPDATE user SET is_agent = 1, is_admin = 1 WHERE username = 'bob'").run();
282282 await post(bobCookie, servers.url);
283 expect(budgetOf(app.db, duties[0]!)).toEqual(own);
283 expect(budgetOf(app.db, duties()[0]!)).toEqual(own);
284284 app.db.query("UPDATE user SET is_agent = 0, is_admin = 0 WHERE username = 'bob'").run();
285285 const cross = await post(aliceCookie, "https://evil.example");
286286 expect(cross.status).toBeGreaterThanOrEqual(400);
287 expect(budgetOf(app.db, duties[0]!)).toEqual(own);
287 expect(budgetOf(app.db, duties()[0]!)).toEqual(own);
288288 });
289289
290290 test("a stored dollars budget is enforced, and a value equal to the declared one is not stored", async () => {
@@ -311,17 +311,17 @@ test("the budget screen moves a budget for an admin who is a person and shows no
311311 const id = (app.db.query("SELECT id FROM user WHERE username = 'alice'").get() as { id: string }).id;
312312 const as = (user: unknown) => ({ user, db: app.db }) as never;
313313 const adminS = as({ isAdmin: true, kind: "person", id, username: "alice" });
314 const before = budgetOf(app.db, duties[0]!).runsPerDay;
315 expect(budgetLines(adminS, 0).some((l) => l.startsWith("> " + duties[0]!.name))).toBe(true);
314 const before = budgetOf(app.db, duties()[0]!).runsPerDay;
315 expect(budgetLines(adminS, 0).some((l) => l.startsWith("> " + duties()[0]!.name))).toBe(true);
316316 moveBudget(adminS, 0, "runs", 1);
317 expect(budgetOf(app.db, duties[0]!).runsPerDay).toBe(before + 1);
317 expect(budgetOf(app.db, duties()[0]!).runsPerDay).toBe(before + 1);
318318 moveBudget(adminS, 0, "runs", 0, true);
319 expect(budgetOf(app.db, duties[0]!).runsPerDay).toBe(duties[0]!.budget.runsPerDay);
319 expect(budgetOf(app.db, duties()[0]!).runsPerDay).toBe(duties()[0]!.budget.runsPerDay);
320320 for (const who of [as({ isAdmin: false, kind: "person", id }), as({ isAdmin: true, kind: "agent", id }), as(undefined)]) {
321321 expect(budgetLines(who, 0)).toEqual([]);
322322 expect(moveBudget(who, 0, "runs", 1)).toBe("");
323323 }
324 expect(budgetOf(app.db, duties[0]!).runsPerDay).toBe(duties[0]!.budget.runsPerDay);
324 expect(budgetOf(app.db, duties()[0]!).runsPerDay).toBe(duties()[0]!.budget.runsPerDay);
325325 });
326326
327327 test("the budget screen's keys move the chosen duty's budget, and a refused session's keys do nothing", async () => {
@@ -331,7 +331,7 @@ test("the budget screen's keys move the chosen duty's budget, and a refused sess
331331 let popped = 0;
332332 const ctx = { invalidate: () => {}, pop: () => popped++, theme: {} } as never;
333333 const press = (screen: { key?: (e: never) => boolean }, key: string) => screen.key!({ key, ctrl: false, alt: false } as never);
334 const d = duties[0]!;
334 const d = duties()[0]!;
335335 const own = { ...budgetOf(app.db, d) };
336336 const screen = dutyBudgetScreen({ user: { isAdmin: true, kind: "person", id }, db: app.db } as never, ctx);
337337 press(screen, "+");
@@ -357,21 +357,21 @@ test("every duty's budget and today's use, read in two statements, are what the
357357 const { budgetOf, budgetsOf, setBudget, usedToday, usedTodayAll } = await import("../src/maintain/budget.ts");
358358 const now = new Date("2026-11-11T12:00:00Z");
359359 const ins = app.db.query("INSERT INTO maintenance_run (duty, started, finished, findings, actions, probes, outcome, dollars) VALUES (?1, ?2, ?2, '[]', '[]', '[]', ?3, ?4)");
360 ins.run(duties[0]!.name, "2026-11-11T01:00:00.000Z", "ok", 0.25);
361 ins.run(duties[0]!.name, "2026-11-11T02:00:00.000Z", "ok", 0.5);
362 ins.run(duties[0]!.name, "2026-11-11T03:00:00.000Z", "budget: runs per day, 2 of 2 used", 0);
363 ins.run(duties[1]!.name, "2026-11-10T23:00:00.000Z", "ok", 1);
364 setBudget(app.db, duties[1]!, "runs", 9, "u");
365 app.db.query("INSERT INTO forge_setting (key, value, updated_by, updated_at) VALUES (?1, 'nonsense', 'u', '')").run(`maintain.${duties[2]!.name}.dollars`);
366 const budgets = budgetsOf(app.db, duties);
360 ins.run(duties()[0]!.name, "2026-11-11T01:00:00.000Z", "ok", 0.25);
361 ins.run(duties()[0]!.name, "2026-11-11T02:00:00.000Z", "ok", 0.5);
362 ins.run(duties()[0]!.name, "2026-11-11T03:00:00.000Z", "budget: runs per day, 2 of 2 used", 0);
363 ins.run(duties()[1]!.name, "2026-11-10T23:00:00.000Z", "ok", 1);
364 setBudget(app.db, duties()[1]!, "runs", 9, "u");
365 app.db.query("INSERT INTO forge_setting (key, value, updated_by, updated_at) VALUES (?1, 'nonsense', 'u', '')").run(`maintain.${duties()[2]!.name}.dollars`);
366 const budgets = budgetsOf(app.db, duties());
367367 const used = usedTodayAll(app.db, now);
368 for (const d of duties) {
368 for (const d of duties()) {
369369 expect(budgets.get(d.name)).toEqual(budgetOf(app.db, d));
370370 expect(used.get(d.name) ?? { runs: 0, dollars: 0 }).toEqual(usedToday(app.db, d.name, now));
371371 }
372 expect(budgets.get(duties[1]!.name)!.runsPerDay).toBe(9);
373 expect(used.get(duties[0]!.name)).toEqual({ runs: 2, dollars: 0.75 });
374 setBudget(app.db, duties[1]!, "runs", null, "u");
375 app.db.query("DELETE FROM forge_setting WHERE key = ?1").run(`maintain.${duties[2]!.name}.dollars`);
372 expect(budgets.get(duties()[1]!.name)!.runsPerDay).toBe(9);
373 expect(used.get(duties()[0]!.name)).toEqual({ runs: 2, dollars: 0.75 });
374 setBudget(app.db, duties()[1]!, "runs", null, "u");
375 app.db.query("DELETE FROM forge_setting WHERE key = ?1").run(`maintain.${duties()[2]!.name}.dollars`);
376376 clear();
377377 });
test/maintenance-chapter-stall.test.ts +1 −1
@@ -81,5 +81,5 @@ test("a closed issue is not stalled", () => {
8181 });
8282
8383 test("the duty is in the registry", () => {
84 expect(duties.map((d) => d.name)).toContain("chapter-stall");
84 expect(duties().map((d) => d.name)).toContain("chapter-stall");
8585 });
test/maintenance-last-run.test.ts +3 −3
@@ -66,10 +66,10 @@ afterAll(async () => {
6666 * one standing alone.
6767 */
6868 function seed(): { a: string; b: string; c: string; ran: string } {
69 const [a, b, c] = duties;
69 const [a, b, c] = duties();
7070 setSystemTime(new Date(NOW));
7171 app.db.run("DELETE FROM maintenance_run");
72 for (const d of duties) setPaused(app.db, d.name, false, "boss");
72 for (const d of duties()) setPaused(app.db, d.name, false, "boss");
7373 const ins = app.db.query("INSERT INTO maintenance_run (duty, started, finished, outcome) VALUES (?1, ?2, ?2, 'ok')");
7474 ins.run(a!.name, new Date(NOW - a!.intervalMs / 2).toISOString());
7575 ins.run(b!.name, new Date(NOW - 4 * b!.intervalMs).toISOString());
@@ -98,7 +98,7 @@ test("the page shows ran/next, late in the attn tone, and says paused once", asy
9898 test("every registered duty has a schedule; a paused one's words are only when it ran", () => {
9999 seed();
100100 const all = dutySchedules(app.db, dutyStates(app.db), Date.now());
101 expect([...all.keys()]).toEqual(duties.map((d) => d.name));
101 expect([...all.keys()]).toEqual(duties().map((d) => d.name));
102102 expect(scheduleWords({ ran: "ran 2h ago", next: "next in 4h", late: true })).toBe("ran 2h ago; next in 4h");
103103 expect(scheduleWords({ ran: "ran 4d ago", next: "paused", late: false })).toBe("ran 4d ago");
104104 });
test/maintenance-page.test.ts +1 −1
@@ -38,7 +38,7 @@ beforeAll(async () => {
3838 // 200 stored rows, a third of them errored, spread over the registered duties.
3939 const ins = app.db.query("INSERT INTO maintenance_run (duty, started, finished, outcome) VALUES (?1, ?2, ?2, ?3)");
4040 app.db.transaction(() => {
41 for (let i = 0; i < 200; i++) ins.run(duties[i % duties.length]!.name, new Date(Date.now() - (200 - i) * 60_000).toISOString(), i % 3 === 0 ? "failed: boom" : "ok");
41 for (let i = 0; i < 200; i++) ins.run(duties()[i % duties().length]!.name, new Date(Date.now() - (200 - i) * 60_000).toISOString(), i % 3 === 0 ? "failed: boom" : "ok");
4242 })();
4343 });
4444 afterAll(async () => {
test/maintenance-pause-who.test.ts +1 −1
@@ -19,7 +19,7 @@ let root = "";
1919 let app: App;
2020 let servers: Servers;
2121 let admin = "";
22 const name = duties[0]!.name;
22 const name = duties()[0]!.name;
2323 const page = async (): Promise<string> => (await fetch(`${servers.url}/maintenance`, { headers: { authorization: `Bearer ${admin}` } })).text();
2424
2525 beforeAll(async () => {
test/maintenance-week-doors.test.ts +4 −4
@@ -26,7 +26,7 @@ let admin = "";
2626 let plain = "";
2727 let alice: User;
2828 let bob: User;
29 const first = duties[0]!.name;
29 const first = duties()[0]!.name;
3030
3131 const identity = (user?: User) => ({ sshUsername: user?.username ?? "git", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user });
3232
@@ -66,7 +66,7 @@ test("MCP maintenance answers a row per worker; a non-admin is forbidden; teleme
6666 const out = await call(admin);
6767 expect(out.result.isError).not.toBe(true);
6868 const { workers } = JSON.parse(out.result.content[0].text);
69 expect(workers.map((w: any) => w.name)).toEqual(duties.map((d) => d.name));
69 expect(workers.map((w: any) => w.name)).toEqual(duties().map((d) => d.name));
7070 expect(workers[0]).toMatchObject({ name: first, found: 2, acted: 1, result: "ok", says: "ok in 0 ms" });
7171 expect(workers[0].last).not.toBeNull();
7272 expect(workers[1]).toMatchObject({ found: 0, acted: 0, last: null });
@@ -85,8 +85,8 @@ test("MCP maintenance answers a row per worker; a non-admin is forbidden; teleme
8585
8686 test("the terminal screen says the sentence and lists every worker, for the same gate; others get nothing", () => {
8787 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);
88 expect(lines[0]).toBe(`1 of ${String(duties().length)} workers found something this week`);
89 expect(lines.length).toBe(duties().length + 2);
9090 expect(lines[2]).toContain("found 2 · acted 1");
9191 expect(lines[2]).toContain("ok in 0 ms");
9292 expect(lines[3]).toContain("not yet run");
test/tui-maintenance-pause-who.test.ts +1 −1
@@ -29,7 +29,7 @@ afterAll(async () => {
2929 });
3030
3131 test("a paused duty reads 'paused by <handle> 3 h ago' in the terminal", async () => {
32 setPaused(app.db, duties[0]!.name, true, "boss", new Date(Date.now() - 3 * 3_600_000 - 1000));
32 setPaused(app.db, duties()[0]!.name, true, "boss", new Date(Date.now() - 3 * 3_600_000 - 1000));
3333 const terminal = headlessTerminal(160, 40);
3434 const { app: tui, session } = createForgeApp(app, { sshUsername: "boss", remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user: admin }, { terminal, exitHooks: false });
3535 tui.start();

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

Keyboard shortcuts

Docs