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

Hard to bring down, not an Achilles heel: one place to manage, many places to fail; the forge's failure domains named and each one tested #1202

Closed opened this in answer to
Closed without merging

mason/forge:mason/1148-hard-to-bring-down-not-an-achilles-heel → main 9 commits fork 3 threads · 3 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
42 files changed +997 −30
.bash_profile added
No content changes.
.bashrc added
No content changes.
.claude/agents added
No content changes.
.claude/commands added
No content changes.
.claude/hooks added
No content changes.
.claude/launch.json added
No content changes.
.claude/loop.md added
No content changes.
.claude/output-styles added
No content changes.
.claude/routines added
No content changes.
.claude/scheduled_tasks.json added
No content changes.
.claude/settings.json added
No content changes.
.claude/settings.local.json added
No content changes.
.claude/skills added
No content changes.
.claude/workflows added
No content changes.
.gitconfig added
No content changes.
.gitmodules added
No content changes.
.idea added
No content changes.
.mcp.json added
No content changes.
.profile added
No content changes.
.ripgreprc added
No content changes.
.vscode added
No content changes.
.zprofile added
No content changes.
.zshrc added
No content changes.
README.md +10
@@ -361,6 +361,16 @@ it answers by default: `.well-known`, feeds, cards, the manifest.
361361 `docs/SNAPSHOT.md` is a forge back from a copy: what a nightly snapshot
362362 holds, where it goes, and the one command that restores it.
363363
364 `docs/DOMAINS.md` is where the forge can fail on its own: compute, state,
365 the snapshot store, the edge, identity, the model credential and the runner,
366 each with what breaks, how the forge says so and what the owner does. An
367 admin reads the same map, with what needs them now and where snapshots go, at
368 **Settings → Resilience** (`/settings/resilience`). The needs it shows, such
369 as a snapshot store on the forge's own volume, are also on the board (each
370 linked to where it is fixed) and in `GET /api/v1/health`. In the terminal an
371 admin presses `R` on the dashboard, or picks Resilience from the palette, for
outdated

The review bar asks for both doors in the same pull. Add the TUI Resilience screen (#1236) here and remove this sentence.

372 the same page in the same words.
373
364374 `docs/EXTRACT.md` is the forge on a machine of its own, and the platform it
365375 grew up in switched off: what a host owes it, the moves in order, and what is
366376 given up.
docs/DOMAINS.md added +123
@@ -0,0 +1,123 @@
1 # Failure domains — one place to manage, many places to fail
2
3 A forge is managed in one place, but it should not be able to fail in one
4 place. This is the map of where it can fail on its own. For each domain it
5 says what breaks, how the forge says so, how long until it is back, and what
6 the owner does. Settings → Resilience shows the same map, with what is true
7 of this forge right now. The sentinel (#1131) reads it. The same rows live
8 in `src/kernel/domains.ts`, and `test/domains.test.ts` checks that this page
9 and that file name the same domains.
10
11 Today one machine runs the forge, its database, its runner and its edge
12 tunnel. The map says which of those already fail apart, and names the issue
13 that owns each place where they do not yet.
14
15 ## Compute
16
17 The pod.
18
19 - **Breaks:** every page, the API, git over HTTP and SSH, the crew, and
20 every app's process.
21 - **Says so:** the platform's probe of `/healthz` fails and the platform
22 restarts the pod. While the body is gone, the edge Worker
23 (`infra/forge-cloudflare/worker.js`) answers `/healthz` with 503 and every
24 other request with a plain 502.
25 - **Back:** a restart takes under two minutes. On boot, every app comes
26 back from its default branch and its open pulls.
27 - **Owner:** nothing, for a restart. If the pod does not come back, read
28 its log and redeploy the last release.
29 - **Not yet:** the edge serving a static "the forge is restarting" page,
30 and the last Resilience page, by itself (#1194).
31
32 ## State
33
34 The volume under `FORGE_DATA`: the database, `secret.key`, the SSH host
35 key, every repository, and every app's data.
36
37 - **Breaks:** everything, if the volume is lost. If it is only full, every
38 write fails.
39 - **Says so:** vitals names a disk that is nearly full (`/api/v1/health`,
40 the board). A lost volume is a forge that does not boot.
41 - **Back:** a full disk is back as soon as space is freed. A lost volume
42 takes one restore from the newest snapshot (`docs/SNAPSHOT.md`).
43 - **Owner:** free space, or restore the newest snapshot into an empty
44 directory, with the passphrase at hand.
45
46 ## Snapshot store
47
48 Where the nightly snapshot goes: the bucket, or `FORGE_SNAPSHOT_DIR`.
49
50 - **Breaks:** nothing that serves. The nightly snapshot fails, so the way
51 back from a lost volume is only as new as the last snapshot taken.
52 - **Says so:** Settings → Backups says the last snapshot failed and why, or
53 that the store could not be listed. Vitals says so when the store is a
54 directory on the forge's own volume, because then the snapshot store and
55 the state share one point of failure.
56 - **Back:** the next nightly snapshot after the store answers again, or
57 straight away with *Snapshot now*.
58 - **Owner:** keep the store off the machine (a bucket), read Backups after
59 a failure, and take a snapshot by hand once the store answers.
60 - **Not yet:** a weekly restore drill that proves a snapshot opens (#1182).
61
62 ## Edge
63
64 The tunnel and DNS that carry requests to the pod.
65
66 - **Breaks:** the forge keeps running, but nobody outside can reach it. SSH
67 on its own port may still answer.
68 - **Says so:** nothing from inside. The forge is up and cannot see that it
69 is unreachable. The platform's uptime probe is what notices.
70 - **Back:** within minutes, once the tunnel reconnects or the DNS record is
71 corrected.
72 - **Owner:** check the tunnel and the DNS record on the platform. The forge
73 itself needs nothing.
74 - **Not yet:** a drill that cuts the tunnel and records what was said
75 (#1195).
76
77 ## Identity
78
79 Signing in: the forge's own accounts, and the origins' OAuth tokens that
80 mirrors use.
81
82 - **Breaks:** signing in to the forge is local (a password checked against
83 its own database), so an origin being down does not lock the owner out.
84 An origin that is down stops its mirrors syncing and pushing through.
85 - **Says so:** a mirror's sync or push-through fails with the origin's
86 reason, on the page that asked for it.
87 - **Back:** when the origin is back, or once a new token is linked.
88 - **Owner:** sign in with the password. When the origin is back and its
89 token no longer works, link it again in Settings → Origins.
90 - **Not yet:** passkeys, kept by the forge rather than by an origin (#667).
91
92 ## Model credential
93
94 The subscription token the crew runs on.
95
96 - **Breaks:** the crew. No agent run starts or finishes. Every page, git,
97 and every app keep working.
98 - **Says so:** the run fails on its issue with the provider's reason, and
99 Settings → Subscriptions shows the subscription's standing.
100 - **Back:** as soon as a working token is set. The queue picks up where it
101 stopped.
102 - **Owner:** set a new token in Settings → Subscriptions.
103
104 ## Runner
105
106 What runs checks and the crew's work: the cell on the same machine.
107
108 - **Breaks:** checks, so a pull waits for its verdict. Nothing that serves
109 stops.
110 - **Says so:** vitals names a check queue that has waited more than thirty
111 minutes, and any runs that are stuck.
112 - **Back:** when the runner has room again. A run whose lease lapsed is
113 marked failed and can be run again.
114 - **Owner:** cancel what is stuck. A person can still land a fix.
115 - **Not yet:** a guarantee that losing the runner never blocks the release
116 of a fix (#1196).
117
118 ## Drills
119
120 Each domain gets a drill, run on a schedule the way the restore drill is
121 run. The drill records the forge's own words while the domain is down, and
122 compares them with this map (#1195). Until then, the restore drill (#1182)
123 is the only one.
scripts/gate.ts +3
@@ -143,6 +143,7 @@ export const GATE: readonly string[] = [
143143 "test/highlight.test.ts",
144144 "test/diff-edge-cases.test.ts",
145145 "test/diff.test.ts",
146 "test/domains.test.ts",
146147 "test/edge-auth.test.ts",
147148 "test/edit-words.test.ts",
148149 "test/edits-security.test.ts",
@@ -198,6 +199,8 @@ export const GATE: readonly string[] = [
198199 "test/data-home.test.ts",
199200 "test/tree.test.ts",
200201 "test/reports.test.ts",
202 "test/resilience.test.ts",
203 "test/tui-resilience.test.ts",
201204 "test/report-discovery.test.ts",
202205 "test/apps-report.test.ts",
203206 "test/private-app.test.ts",
src/actions/health.ts +20 −5
@@ -14,6 +14,25 @@ import { listApps } from "../core/apps.ts";
1414 import type { User } from "../core/users.ts";
1515 import { forgeHealth, type ForgeHealth } from "../kernel/guard.ts";
1616 import { vitals, type Vitals } from "../kernel/vitals.ts";
17 import { snapshotsOf } from "../snapshot/service.ts";
18
19 /**
20 * This forge's vitals, as every surface reads them: the board's strip,
21 * the asks, and the health answer. One place gathers what they measure.
22 */
23 export function forgeVitals(app: App): Vitals {
24 const runtime = appsRuntime(app);
25 const envs = runtime
26 ? listApps(app.db).flatMap((record) => runtime.status(record))
27 : [];
28 const snapshotDir = snapshotsOf(app)?.store?.dir;
29 return vitals({
30 db: app.db,
31 dataDir: app.config.dataDir,
32 envs,
33 ...(snapshotDir === undefined ? {} : { snapshotDir }),
34 });
35 }
1736
1837 export function readHealth(
1938 app: App,
@@ -21,10 +40,6 @@ export function readHealth(
2140 ): ForgeHealth | (Vitals & ForgeHealth) {
2241 const forge = forgeHealth();
2342 if (!actor?.isAdmin) return forge;
24 const runtime = appsRuntime(app);
25 const envs = runtime
26 ? listApps(app.db).flatMap((record) => runtime.status(record))
27 : [];
28 const v = vitals({ db: app.db, dataDir: app.config.dataDir, envs });
43 const v = forgeVitals(app);
2944 return { ...v, ...forge, ok: forge.ok && v.ok };
3045 }
src/actions/resilience.ts added +66
@@ -0,0 +1,66 @@
1 /**
2 * Resilience, as both doors read it: what needs the owner now (vitals),
3 * where snapshots go and how the last one went, and the map of failure
4 * domains (`kernel/domains.ts`). Settings → Resilience and the terminal's
5 * Resilience screen render this and nothing else, so the two say the same
6 * thing in the same words.
7 *
8 * For a site admin only: anyone else gets `undefined`. Nothing here is slow:
9 * the store is not listed (Backups does that), and vitals is a fixed handful
10 * of queries.
11 */
12
13 import type { App } from "../app.ts";
14 import type { User } from "../core/users.ts";
15 import { DOMAINS, type Domain } from "../kernel/domains.ts";
16 import { snapshotsOf } from "../snapshot/service.ts";
17 import { forgeVitals } from "./health.ts";
18
19 /** Said when nothing needs the owner. */
20 export const ALL_FINE = "All fine: nothing needs you now.";
21 /** Said when the forge was given nowhere to put snapshots. */
22 export const NO_STORE =
23 "No snapshots are taken: this forge was given nowhere to put them. A lost volume would be lost for good.";
24 /** When snapshots are taken, as a sentence ends it. */
25 export const SCHEDULE = "every night at 08:00 UTC";
26
27 /** The last snapshot this process took: finished, or failed and why. */
28 export type LastSnapshot =
29 | { readonly ok: true; readonly name: string; readonly at: string }
30 | { readonly ok: false; readonly error: string; readonly at: string };
31
32 export interface Resilience {
33 readonly ok: boolean;
34 readonly needs: readonly string[];
35 /** Where snapshots are written; undefined when there is nowhere. */
36 readonly store: string | undefined;
37 readonly last: LastSnapshot | undefined;
38 readonly domains: readonly Domain[];
39 }
40
41 export function readResilience(
42 app: App,
43 actor: User | undefined,
44 ): Resilience | undefined {
45 if (!actor?.isAdmin) return undefined;
46 const v = forgeVitals(app);
47 const svc = snapshotsOf(app);
48 const taken = svc?.last();
49 const last: LastSnapshot | undefined =
50 taken?.error !== undefined
51 ? { ok: false, error: taken.error, at: taken.at ?? "" }
52 : taken?.manifest !== undefined
53 ? {
54 ok: true,
55 name: taken.manifest.name,
56 at: taken.manifest.finishedAt,
57 }
58 : undefined;
59 return {
60 ok: v.ok,
61 needs: v.needs,
62 store: svc?.store?.where,
63 last,
64 domains: DOMAINS,
65 };
66 }
src/http/server.ts +2
@@ -91,6 +91,7 @@ import {
9191 backupsPage,
9292 backupsTest,
9393 } from "../web/pages/backups.ts";
94 import { resiliencePage } from "../web/pages/resilience.ts";
9495 import {
9596 cloudAdd,
9697 cloudAudit,
@@ -653,6 +654,7 @@ export function buildRouter(): Router<Handler> {
653654 router.add("POST", "/settings/backups/destination", backupsDestination);
654655 router.add("POST", "/settings/backups/test", backupsTest);
655656 router.add("POST", "/settings/backups/clear", backupsClear);
657 router.add("GET", "/settings/resilience", resiliencePage);
656658 router.add("GET", "/settings/accounts", accountsPage);
657659 router.add("GET", "/settings/accounts/:username", personSignInsPage);
658660 router.add(
src/kernel/domains.ts added +146
@@ -0,0 +1,146 @@
1 /**
2 * The forge's failure domains: each place it can fail on its own, what
3 * breaks when it does, how the forge says so, how long until it is back,
4 * and what the owner does. `docs/DOMAINS.md` is the same map in prose, and
5 * a test keeps the two naming the same domains. Settings → Resilience
6 * renders this; the sentinel (#1131) reads it.
7 *
8 * Plain data, and one check that two of them do not share a single point
9 * by accident: a snapshot directory on the volume it is a copy of.
10 */
11
12 import { statSync } from "node:fs";
13 import { dirname, relative, resolve, isAbsolute } from "node:path";
14
15 export interface Domain {
16 readonly id: string;
17 readonly name: string;
18 /** What stops working when this one fails. */
19 readonly breaks: string;
20 /** Where and in what words the forge says so. */
21 readonly says: string;
22 /** How long until it is back, on its own or with the owner's hand. */
23 readonly back: string;
24 /** What the owner does. */
25 readonly owner: string;
26 /** What is not yet true of it, and the issue that owns that. */
27 readonly gap?: string;
28 }
29
30 /** Each field a domain is read by, and the word every surface labels it with. */
31 export const DOMAIN_FIELDS = [
32 ["breaks", "Breaks"],
33 ["says", "Says so"],
34 ["back", "Back"],
35 ["owner", "You"],
36 ["gap", "Not yet"],
37 ] as const satisfies readonly (readonly [keyof Domain, string])[];
38
39 export const DOMAINS: readonly Domain[] = [
40 {
41 id: "compute",
42 name: "Compute",
43 breaks:
44 "The pod: every page, the API, git over HTTP and SSH, the crew and every app's process.",
45 says: "The platform's probe of /healthz fails and it restarts the pod; the edge answers /healthz with 503 and other requests with a plain 502.",
46 back: "A restart: under two minutes. The app processes come back from the default branch and the open pulls on boot.",
47 owner: "Nothing for a restart. If it does not come back, read the pod's log and redeploy the last release.",
48 gap: "The edge serves a static \"the forge is restarting\" page (#1194).",
49 },
50 {
51 id: "state",
52 name: "State",
53 breaks:
54 "The volume under FORGE_DATA: the database, the secret key, the SSH host key, every repository and every app's data.",
55 says: "Vitals names a nearly full disk; a lost volume is a forge that does not boot.",
56 back: "A full disk: as soon as space is freed. A lost volume: one restore from the newest snapshot (docs/SNAPSHOT.md).",
57 owner: "Free space, or restore the newest snapshot into an empty directory with the passphrase.",
58 },
59 {
60 id: "snapshots",
61 name: "Snapshot store",
62 breaks:
63 "Nothing that serves; the nightly snapshot fails, and the way back from a lost volume is only as new as the last one taken.",
64 says: "Settings → Backups says the last snapshot failed and why, or that the store could not be listed. Vitals names a store kept on the state volume.",
65 back: "The next nightly snapshot after the store answers, or now with Snapshot now.",
66 owner: "Keep the store off the machine (a bucket), check Backups after a failure, and take one now once it answers.",
67 gap: "A weekly restore drill proves a snapshot opens (#1182).",
68 },
69 {
70 id: "edge",
71 name: "Edge",
72 breaks:
73 "The tunnel and DNS: the forge runs but nobody outside reaches it; SSH on its own port may still answer.",
74 says: "Nothing from inside: the forge is up and cannot see it is unreachable. The platform's uptime probe is what notices.",
75 back: "Minutes, once the tunnel reconnects or DNS is corrected.",
76 owner: "Check the tunnel and the DNS record on the platform; the forge itself needs nothing.",
77 gap: "A drill cuts the tunnel and records what was said (#1195).",
78 },
79 {
80 id: "identity",
81 name: "Identity",
82 breaks:
83 "Signing in. The forge's own sign-in is local (a password checked in its database), so an origin being down does not lock the owner out. It stops mirrors syncing and pushing through to the origin.",
84 says: "A mirror's sync or push-through fails with the origin's reason, on the page that asked for it.",
85 back: "When the origin is back, or when a new token is linked.",
86 owner: "Sign in with the password; when the origin is back and the token no longer works, link it again in Settings → Origins.",
87 gap: "Passkeys, kept by the forge and not an origin (#667).",
88 },
89 {
90 id: "model",
91 name: "Model credential",
92 breaks:
93 "The crew: no agent run starts or finishes. Every page, git and every app keep working.",
94 says: "The run fails with the provider's reason on the issue, and Settings → Subscriptions shows the subscription's standing.",
95 back: "As soon as a working token is set; the queue picks up where it stopped.",
96 owner: "Set a new token in Settings → Subscriptions.",
97 },
98 {
99 id: "runner",
100 name: "Runner",
101 breaks:
102 "Checks: a pull waits for its verdict. Nothing that serves stops.",
103 says: "Vitals names a check queue that has waited over thirty minutes and runs that are stuck.",
104 back: "When the runner has room again; a run whose lease lapsed is failed and can be run again.",
105 owner: "Cancel what is stuck; a person can still land a fix.",
106 gap: "Losing the runner never blocks a release of a fix (#1196).",
107 },
108 ];
109
110 /**
111 * The nearest path that exists at or above `path`, so a directory not yet
112 * made is measured by the volume it would be made on.
113 */
114 function existing(path: string): string {
115 let at = resolve(path);
116 for (;;) {
117 try {
118 statSync(at);
119 return at;
120 } catch {
121 const up = dirname(at);
122 if (up === at) return at;
123 at = up;
124 }
125 }
126 }
127
128 const deviceOf = (path: string): number => statSync(existing(path)).dev;
129
130 /**
131 * Whether `copy` lives on the same volume as `source`: inside it, or on
132 * the same device. A copy that shares the volume is lost with it.
133 */
134 export function sharesVolume(
135 source: string,
136 copy: string,
137 devOf: (path: string) => number = deviceOf,
138 ): boolean {
139 const rel = relative(resolve(source), resolve(copy));
140 if (rel === "" || (!rel.startsWith("..") && !isAbsolute(rel))) return true;
141 try {
142 return devOf(source) === devOf(copy);
143 } catch {
144 return false;
145 }
146 }
src/kernel/vitals.ts +12
@@ -11,6 +11,7 @@
1111 import type { Database } from "bun:sqlite";
1212 import { statfsSync } from "node:fs";
1313 import { freemem, totalmem } from "node:os";
14 import { sharesVolume } from "./domains.ts";
1415 import { recentErrors, type ErrorLine } from "./log.ts";
1516 import { leaseLapsed, listRunning, queueDepth } from "../core/runs.ts";
1617 import { STALE_AFTER_MS } from "../runs/lease.ts";
@@ -23,6 +24,9 @@ export const ERROR_BURST = 20;
2324 export const NO_PROGRESS_MS = 6 * 3_600_000;
2425 /** A run that has waited this long to start is a queue that is not moving. */
2526 export const QUEUE_WAIT_MAX_MS = 30 * 60_000;
27 /** The need said when snapshots share the volume they are a copy of. */
28 export const SNAPSHOTS_ON_STATE_VOLUME =
29 "Snapshots are kept on the forge's own volume: losing it loses them too. Point them at a bucket or another disk.";
2630
2731 export interface EnvCount {
2832 readonly env: string;
@@ -56,6 +60,8 @@ export interface VitalsInput {
5660 readonly dataDir: string;
5761 /** Every environment the runtime holds, when one is up. */
5862 readonly envs?: readonly EnvCount[];
63 /** The directory snapshots are written to, when the store is one. */
64 readonly snapshotDir?: string;
5965 readonly now?: number;
6066 }
6167
@@ -73,6 +79,12 @@ export function vitals(input: VitalsInput): Vitals {
7379 `Disk is nearly full: ${Math.round((disk.freeBytes / disk.totalBytes) * 100)}% free.`,
7480 );
7581
82 if (
83 input.snapshotDir !== undefined &&
84 sharesVolume(input.dataDir, input.snapshotDir)
outdated

This need reaches the board strip, but needHref (board.ts) gives it no link. Map it to /settings/backups so the warning leads to its fix, and test the href.

85 )
86 needs.push(SNAPSHOTS_ON_STATE_VOLUME);
87
7688 const queue: Record<string, number> = {};
7789 for (const row of queueDepth(input.db, now)) {
7890 queue[row.kind] = row.queued;
src/snapshot/store.ts +3
@@ -12,6 +12,8 @@ import { dirname, join, relative } from "node:path";
1212 export interface Store {
1313 /** What this store is, for a page and a log; never a secret. */
1414 readonly where: string;
15 /** The directory it writes under, when it is one; a bucket has none. */
16 readonly dir?: string;
1517 put(key: string, body: Uint8Array | string): Promise<void>;
1618 get(key: string): Promise<Uint8Array | undefined>;
1719 /** Every key under `prefix`, in no particular order. */
@@ -125,6 +127,7 @@ export function dirStore(root: string): Store {
125127 };
126128 return {
127129 where: root,
130 dir: root,
128131 async put(key, body) {
129132 const path = at(key);
130133 mkdirSync(dirname(path), { recursive: true });
src/tui/forge.ts +8
@@ -34,6 +34,7 @@ import { issuesScreen, newIssueScreen } from "./screens/issues.ts";
3434 import { newPullScreen } from "./screens/newpull.ts";
3535 import { newRepoScreen } from "./screens/newrepo.ts";
3636 import { repoScreen } from "./screens/repo.ts";
37 import { resilienceScreen } from "./screens/resilience.ts";
3738 import { signInScreen } from "./screens/signin.ts";
3839 import { local } from "./screens/where.ts";
3940
@@ -161,6 +162,13 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
161162 run: () => openOnWeb(session, ctx, "/settings", "Account settings"),
162163 },
163164 );
165 if (session.user?.isAdmin === true)
166 commands.push({
167 id: "resilience",
168 title: "Resilience",
169 hint: "where the forge can fail",
170 run: () => ctx.push(resilienceScreen(session, ctx)),
171 });
164172 commands.push({
165173 id: "quit",
166174 title: "Quit",
src/tui/screens/dashboard.ts +8
@@ -57,6 +57,7 @@ import { issueScreen } from "./issue.ts";
5757 import { newRepoScreen } from "./newrepo.ts";
5858 import { pullScreen } from "./pull.ts";
5959 import { repoScreen } from "./repo.ts";
60 import { resilienceScreen } from "./resilience.ts";
6061 import { local } from "./where.ts";
6162 import { signInScreen } from "./signin.ts";
6263
@@ -248,6 +249,9 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
248249 }),
249250 binding(["n"], "new repo", { disabled: !f.signedIn }),
250251 binding(["A"], "account", { disabled: !f.signedIn }),
252 ...(f.user?.isAdmin === true
253 ? [binding(["R"], "resilience")]
254 : []),
251255 binding(["s"], "sign in", { disabled: f.signedIn }),
252256 binding(["r"], "refresh"),
253257 ];
@@ -333,6 +337,10 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
333337 openOnWeb(f, ctx, "/settings", "Account settings");
334338 return true;
335339 }
340 if (e.key === "R" && f.user?.isAdmin === true) {
341 ctx.push(resilienceScreen(f, ctx));
342 return true;
343 }
336344 if (e.key === "s" && !f.signedIn) {
337345 ctx.push(signInScreen(f, ctx, reload));
338346 return true;
src/tui/screens/resilience.ts added +131
@@ -0,0 +1,131 @@
1 /**
2 * `R` on the dashboard, for a site admin: Settings → Resilience in the
3 * terminal. What needs the owner now, where snapshots go and how the last
4 * one went, and every failure domain with what breaks, how the forge says
5 * so, how long until it is back and what to do.
6 *
7 * It reads `readResilience`, the same answer the web page renders, in the
8 * same words; nothing here is a second copy. Anyone else gets an empty
9 * screen: `readResilience` answers them nothing.
10 */
11
12 import {
13 ALL_FINE,
14 NO_STORE,
15 readResilience,
16 SCHEDULE,
17 type Resilience,
18 } from "../../actions/resilience.ts";
19 import { DOMAIN_FIELDS } from "../../kernel/domains.ts";
20 import type { Ctx, Screen } from "../app/app.ts";
21 import { binding } from "../app/keys.ts";
22 import { BOLD, style, type Style } from "../term/style.ts";
23 import { wrap } from "../term/width.ts";
24 import type { Tokens } from "../ui/theme.ts";
25 import { emptyState } from "../ui/widgets.ts";
26 import type { Session } from "../session.ts";
27 import { Scroll, ago, drawLines, hitScroll, openOnWeb } from "./common.ts";
28
29 type Line = { text: string; style: Style }[];
30
31 export function resilienceScreen(f: Session, ctx: Ctx): Screen {
32 let r = readResilience(f.app, f.user);
33 const scroll = new Scroll();
34 let width = -1;
35 let lines: Line[] = [];
36 const reload = (): void => {
37 r = readResilience(f.app, f.user);
38 width = -1;
39 };
40
41 return {
42 title: "Resilience",
43 get keys() {
44 return [
45 binding(["j", "k"], "scroll"),
46 binding(["b"], "backups on the web", { disabled: r === undefined }),
47 binding(["r"], "refresh"),
48 binding(["esc", "q"], "back"),
49 ];
50 },
51 render(area, s) {
52 const c = ctx.theme.c;
53 if (r === undefined) {
54 emptyState(s, area, c, { title: "Nothing here" });
55 return;
56 }
57 if (width !== area.w) {
58 width = area.w;
59 lines = resilienceLines(r, Math.max(20, area.w - 2), c);
60 }
61 drawLines(s, area, c, scroll, lines);
62 hitScroll(ctx, area, scroll, lines.length);
63 },
64 key(e) {
65 if (e.key === "esc" || e.key === "q") {
66 ctx.pop();
67 return true;
68 }
69 if (r === undefined) return false;
70 if (e.key === "b") {
71 openOnWeb(f, ctx, "/settings/backups", "Backups");
72 return true;
73 }
74 if (e.key === "r") {
75 reload();
76 return true;
77 }
78 return scroll.key(e, lines.length);
79 },
80 };
81 }
82
83 /** The page's three cards as wrapped, styled lines: Now, Snapshots, the map. */
84 export function resilienceLines(
85 r: Resilience,
86 width: number,
87 c: Tokens,
88 ): Line[] {
89 const out: Line[] = [];
90 const head = (text: string): void => {
91 if (out.length > 0) out.push([]);
92 out.push([{ text, style: style(c.fg, c.bg, BOLD) }]);
93 };
94 const para = (text: string, st: Style, indent = ""): void => {
95 for (const line of wrap(text, Math.max(1, width - indent.length)))
96 out.push([{ text: indent + line, style: st }]);
97 };
98 const plain = style(c.fg, c.bg);
99 const muted = style(c.mutedFg, c.bg);
100 const danger = style(c.danger, c.bg);
101
102 head("Now");
103 if (r.ok) para(ALL_FINE, style(c.success, c.bg));
104 else for (const need of r.needs) para(`! ${need}`, danger);
105
106 head("Snapshots");
107 if (r.store === undefined) para(`! ${NO_STORE}`, danger);
108 else para(`Snapshots go to ${r.store} ${SCHEDULE}.`, plain);
109 if (r.last?.ok === true)
110 para(
111 `The last one this process took, ${r.last.name}, finished ${ago(r.last.at)}.`,
112 plain,
113 );
114 if (r.last?.ok === false)
115 para(
116 `! The last snapshot failed ${ago(r.last.at)}: ${r.last.error}`,
117 danger,
118 );
119 para("Every snapshot, and how to restore one: b", muted);
120
121 head("Where it can fail");
122 for (const d of r.domains) {
123 out.push([]);
124 out.push([{ text: d.name, style: style(c.fg, c.bg, BOLD) }]);
125 for (const [key, label] of DOMAIN_FIELDS) {
126 const value = d[key];
127 if (value !== undefined) para(`${label}: ${value}`, muted, " ");
128 }
129 }
130 return out;
131 }
src/web/pages/board.ts +11 −13
@@ -24,7 +24,6 @@ import {
2424 type Decision,
2525 type DecisionKind,
2626 } from "../../core/decisions.ts";
27 import { appsRuntime } from "../../apps/runtime.ts";
2827 import { efficiencyForRepos } from "../../core/efficiency.ts";
2928 import { reviewStats, type ReviewStats } from "../../core/review-stats.ts";
3029 import { standings, WINDOW_MS } from "../../core/standing.ts";
@@ -36,9 +35,12 @@ import {
3635 } from "../../core/subscriptions.ts";
3736 import { readSpend } from "../../actions/spend.ts";
3837 import { spendView } from "./spend.ts";
39 import { listApps } from "../../core/apps.ts";
4038 import { forgeHealth, rolloutLine } from "../../kernel/guard.ts";
41 import { vitals, type Vitals } from "../../kernel/vitals.ts";
39 import {
40 SNAPSHOTS_ON_STATE_VOLUME,
41 type Vitals,
42 } from "../../kernel/vitals.ts";
43 import { forgeVitals } from "../../actions/health.ts";
4244 import { getIssue, getIssuesByIds, type Issue } from "../../core/issues.ts";
4345 import { looksForApps } from "../../core/looks.ts";
4446 import {
@@ -303,10 +305,14 @@ export function bigRedirect(ctx: Ctx): Response {
303305
304306 // ---- the forge ----
305307
306 /** Where a need can be acted on, when it can: a stuck run's page. */
308 /**
309 * Where a need can be acted on, when it can: a stuck run's page, or Backups
310 * for a snapshot store on the state volume, where its destination is set.
311 */
307312 function needHref(need: string, v: Vitals): string | undefined {
308313 if (/ stuck\.$/.test(need) && v.stuck[0] !== undefined)
309314 return `/${v.stuck[0].repo}/runs/${v.stuck[0].runId}`;
315 if (need === SNAPSHOTS_ON_STATE_VOLUME) return "/settings/backups";
310316 return undefined;
311317 }
312318
@@ -317,15 +323,7 @@ function needHref(need: string, v: Vitals): string | undefined {
317323 */
318324 function forgeStrip(ctx: Ctx): Html | null {
319325 if (!ctx.auth.user?.isAdmin) return null;
320 const app = ctx.app;
321 const runtime = appsRuntime(app);
322 const v = vitals({
323 db: app.db,
324 dataDir: app.config.dataDir,
325 envs: runtime
326 ? listApps(app.db).flatMap((record) => runtime.status(record))
327 : [],
328 });
326 const v = forgeVitals(ctx.app);
329327 const fh = forgeHealth();
330328 const rollout = rolloutLine(fh);
331329 const others = fh.incidents.filter(
src/web/pages/origins.ts +7
@@ -78,6 +78,7 @@ export type AccountSection =
7878 | "accounts"
7979 | "subscriptions"
8080 | "backups"
81 | "resilience"
8182 | "secrets"
8283 | "capacity"
8384 | "cloud";
@@ -137,6 +138,12 @@ export function accountSections(
137138 icon: "download" as const,
138139 current: current === "backups",
139140 },
141 {
142 label: "Resilience",
143 href: "/settings/resilience",
144 icon: "shield" as const,
145 current: current === "resilience",
146 },
140147 ]
141148 : []),
142149 {
src/web/pages/resilience.ts added +103
@@ -0,0 +1,103 @@
1 /**
2 * Resilience, for an admin: the one page the owner reads to know where the
3 * forge can fail and what is true of it now. What needs them (vitals),
4 * where snapshots go and how the last one went, and the map of failure
5 * domains (`kernel/domains.ts`, `docs/DOMAINS.md`), each with what breaks,
6 * how the forge says so, how long until it is back and what to do. The
7 * terminal's Resilience screen reads the same `readResilience`.
8 */
9
10 import {
11 ALL_FINE,
12 NO_STORE,
13 readResilience,
14 SCHEDULE,
15 } from "../../actions/resilience.ts";
16 import type { Ctx } from "../../http/context.ts";
17 import { DOMAIN_FIELDS } from "../../kernel/domains.ts";
18 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
19 import { html, when } from "../html.ts";
20 import { page } from "../layout.ts";
21 import { card, icon, listCard, row, time } from "../ui.ts";
22 import { accountSections } from "./origins.ts";
23
24 // GET /settings/resilience
25 export function resiliencePage(ctx: Ctx): Response {
26 if (!ctx.auth.user) return signInFirst(ctx);
27 const r = readResilience(ctx.app, ctx.auth.user);
28 if (r === undefined) return notFoundPage(ctx);
29 const last = r.last;
30
31 const standing = card(
32 r.ok
33 ? html`<p>${icon("check")} ${ALL_FINE}</p>`
34 : html`<ul>
35 ${r.needs.map(
36 (need) =>
37 html`<li class="backups-error">${icon("alert")} ${need}</li>`,
38 )}
39 </ul>`,
40 {
41 head: html`${icon("activity")}
42 <h2>Now</h2>`,
43 },
44 );
45
46 const snapshots = card(
47 html`${r.store === undefined
48 ? html`<p class="backups-error">${icon("alert")} ${NO_STORE}</p>`
49 : html`<p>
50 Snapshots go to <code>${r.store}</code> ${SCHEDULE}.
51 </p>`}
52 ${when(
53 last?.ok === true ? last : undefined,
54 (m) =>
55 html`<p>
56 ${icon("check")} The last one this process took,
57 <span class="mono">${m.name}</span>, finished ${time(m.at)}.
58 </p>`,
59 )}
60 ${when(
61 last?.ok === false ? last : undefined,
62 (failed) =>
63 html`<p class="backups-error">
64 ${icon("alert")} The last snapshot failed ${time(failed.at)}:
65 ${failed.error}
66 </p>`,
67 )}
68 <p><a href="/settings/backups">Every snapshot, and how to restore one</a></p>`,
69 {
70 head: html`${icon("download")}
71 <h2>Snapshots</h2>`,
72 },
73 );
74
75 const map = listCard(
76 r.domains.map((d) =>
77 row({
78 lead: icon("shield"),
79 title: d.name,
80 meta: html`${DOMAIN_FIELDS.filter(([key]) => d[key] !== undefined).map(
81 ([key, label], i) =>
82 html`${i > 0 ? html`<br />` : ""}<strong>${label}:</strong>
83 ${d[key]}`,
84 )}`,
85 }),
86 ),
87 {
88 head: html`${icon("map")}
89 <h2>Where it can fail</h2>`,
90 },
91 );
92
93 return page({
94 ctx,
95 title: "Resilience",
96 body: html`<div class="page-head"><h1>Resilience</h1></div>
97 ${settingsLayout(
98 accountSections("resilience", { admin: true }),
99 html`${standing}${snapshots}${map}`,
100 "Account settings",
101 )}`,
102 });
103 }
src/web/studio/asks.ts +3 −12
@@ -10,8 +10,7 @@
1010 import type { Database } from "bun:sqlite";
1111 import { previewEnv } from "../../apps/data.ts";
1212 import { crewForRepos } from "../../core/agents.ts";
13 import { appsRuntime } from "../../apps/runtime.ts";
14 import { appsForRepos, getAppByRepo, listApps } from "../../core/apps.ts";
13 import { appsForRepos, getAppByRepo } from "../../core/apps.ts";
1514 import { latestDecision, stopStands } from "../../core/decisions.ts";
1615 import { getHold, holdsFor } from "../../core/holds.ts";
1716 import { askDismissals } from "../../core/interactions.ts";
@@ -49,7 +48,7 @@ import { CHECK_FAILED_LIMIT } from "../../crew/dispatch.ts";
4948 import { isStalePull, mergesAgainSince } from "../../crew/stale_asks.ts";
5049 import { waitsForPerson, type ReviewWait } from "../../crew/review.ts";
5150 import type { Ctx } from "../../http/context.ts";
52 import { vitals } from "../../kernel/vitals.ts";
51 import { forgeVitals } from "../../actions/health.ts";
5352 import { repoBase } from "../chrome.ts";
5453 import { html, when, type Html } from "../html.ts";
5554 import { btn, card, icon, row } from "../ui.ts";
@@ -939,15 +938,7 @@ export function decisionActions(ctx: Ctx, d: Decision): Html {
939938 */
940939 export function forgeNeedsFor(ctx: Ctx, user: User | undefined): string[] {
941940 if (!user?.isAdmin) return [];
942 const runtime = appsRuntime(ctx.app);
943 const envs = runtime
944 ? listApps(ctx.app.db).flatMap((record) => runtime.status(record))
945 : [];
946 return vitals({
947 db: ctx.app.db,
948 dataDir: ctx.app.config.dataDir,
949 envs,
950 }).needs;
941 return forgeVitals(ctx.app).needs;
951942 }
952943
953944 /**
test/domains.test.ts added +69
@@ -0,0 +1,69 @@
1 /** The failure domains: the map agrees with its page, and a snapshot store on the state volume is named. */
2
3 import { afterAll, beforeAll, expect, test } from "bun:test";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { Database } from "bun:sqlite";
8 import { DOMAINS, sharesVolume } from "../src/kernel/domains.ts";
9 import { vitals } from "../src/kernel/vitals.ts";
10 import { migrate } from "../src/kernel/migrate.ts";
11 import { migrations } from "../src/core/schema.ts";
12
13 let dataDir: string;
14 let db: Database;
15
16 beforeAll(async () => {
17 dataDir = await mkdtemp(join(tmpdir(), "forge-domains-"));
18 db = new Database(":memory:");
19 migrate(db, migrations);
20 });
21 afterAll(async () => {
22 db.close();
23 await rm(dataDir, { recursive: true, force: true });
24 });
25
26 test("docs/DOMAINS.md and the module name the same domains, in the same order", async () => {
27 const doc = await Bun.file(join(import.meta.dir, "../docs/DOMAINS.md")).text();
28 const headings = [...doc.matchAll(/^## (.+)$/gm)]
29 .map((m) => m[1])
30 .filter((h) => h !== "Drills");
31 expect(headings).toEqual(DOMAINS.map((d) => d.name));
32 });
33
34 test("every domain says what breaks, how it is said, when it is back, and what the owner does", () => {
35 for (const d of DOMAINS)
36 for (const field of [d.breaks, d.says, d.back, d.owner])
37 expect(field.length).toBeGreaterThan(10);
38 expect(new Set(DOMAINS.map((d) => d.id)).size).toBe(DOMAINS.length);
39 });
40
41 test("a copy inside the source shares its volume, whatever the devices say", () => {
42 const devOf = () => {
43 throw new Error("not asked");
44 };
45 expect(sharesVolume("/data", "/data/snapshots", devOf)).toBe(true);
46 expect(sharesVolume("/data", "/data", devOf)).toBe(true);
47 expect(sharesVolume("/data", "/data/../data/x", devOf)).toBe(true);
48 });
49
50 test("a copy elsewhere shares the volume only when it is the same device", () => {
51 const devs: Record<string, number> = { "/data": 1, "/backup": 2, "/other": 1 };
52 const devOf = (p: string) => devs[p] ?? 0;
53 expect(sharesVolume("/data", "/backup", devOf)).toBe(false);
54 expect(sharesVolume("/data", "/other", devOf)).toBe(true);
55 expect(sharesVolume("/data", "/database", devOf)).toBe(false);
56 });
57
58 test("vitals names a snapshot directory kept on the forge's own volume", () => {
59 const shared = vitals({
60 db,
61 dataDir,
62 snapshotDir: join(dataDir, "snapshots-not-yet-made"),
63 });
64 expect(shared.ok).toBe(false);
65 expect(shared.needs.some((n) => n.startsWith("Snapshots are kept on the forge's own volume"))).toBe(true);
66
67 const none = vitals({ db, dataDir });
68 expect(none.needs.some((n) => n.startsWith("Snapshots"))).toBe(false);
69 });
test/resilience.test.ts added +129
@@ -0,0 +1,129 @@
1 /** Settings → Resilience: the map, the snapshots and what needs the owner, on one page, for an admin only. */
2
3 import { afterAll, beforeAll, expect, test } from "bun:test";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp, type App } from "../src/app.ts";
8 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
9 import { DOMAINS } from "../src/kernel/domains.ts";
10 import { startSnapshots } from "../src/snapshot/service.ts";
11 import { dirStore, type Store } from "../src/snapshot/store.ts";
12
13 let dataDir: string;
14 let app: App;
15 let http: ForgeHttp;
16
17 const BASE = "http://forge.test";
18 const get = (path: string, init: RequestInit = {}) =>
19 http.handle(new Request(BASE + path, init));
20
21 const signIn = async (username: string): Promise<string> => {
22 const res = await get("/signin", {
23 method: "POST",
24 headers: { origin: BASE },
25 body: new URLSearchParams({ username, password: "a-good-passphrase" }),
26 redirect: "manual",
27 });
28 return (res.headers.get("set-cookie") ?? "").split(";")[0]!;
29 };
30
31 beforeAll(async () => {
32 dataDir = await mkdtemp(join(tmpdir(), "forge-resilience-"));
33 app = createApp({ dataDir, port: 0 });
34 http = forgeHttp(app);
35 for (const username of ["alice", "bob"])
36 await get("/api/v1/users", {
37 method: "POST",
38 headers: { "content-type": "application/json" },
39 body: JSON.stringify({
40 username,
41 email: `${username}@forge.local`,
42 password: "a-good-passphrase",
43 }),
44 });
45 }, 30_000);
46 afterAll(async () => {
47 http.close();
48 await rm(dataDir, { recursive: true, force: true });
49 });
50
51 test("an admin reads every domain, and a forge with no store says so", async () => {
52 const cookie = await signIn("alice");
53 const res = await get("/settings/resilience", {
54 headers: { cookie },
55 });
56 expect(res.status).toBe(200);
57 const body = (await res.text()).replace(/\s+/g, " ");
58 for (const d of DOMAINS) expect(body).toContain(d.name);
59 expect(body).toContain("No snapshots are taken");
60 expect(body).toContain('href="/settings/resilience"');
61 });
62
63 test("a snapshot store on the forge's own volume is a need on the page and a link on the board", async () => {
64 const cookie = await signIn("alice");
65 const svc = startSnapshots(app, dirStore(join(dataDir, "snapshots")), {
66 version: "t",
67 nightly: false,
68 });
69 try {
70 const body = (
71 await (
72 await get("/settings/resilience", {
73 headers: { cookie },
74 })
75 ).text()
76 ).replace(/\s+/g, " ");
77 expect(body).toContain("Snapshots are kept on the forge&#39;s own volume");
78 expect(body).toContain(join(dataDir, "snapshots"));
79 // The board names the same need, and taps through to where it is fixed.
80 const board = await (await get("/board", { headers: { cookie } })).text();
81 expect(board.replace(/\s+/g, " ")).toContain(
82 'href="/settings/backups">Snapshots are kept on the forge&#39;s own volume',
83 );
84 } finally {
85 await svc.stop();
86 }
87 });
88
89 test("a failed snapshot is on the page with its reason, escaped", async () => {
90 const cookie = await signIn("alice");
91 const refusing: Store = {
92 where: "bucket <b>refusing</b>",
93 put: () => Promise.reject(new Error("the bucket said <no>")),
94 get: async () => undefined,
95 list: async () => [],
96 names: async () => [],
97 delete: async () => {},
98 };
99 const svc = startSnapshots(app, refusing, { version: "t", nightly: false });
100 try {
101 await expect(svc.now()).rejects.toThrow("the bucket said <no>");
102 const body = (
103 await (
104 await get("/settings/resilience", {
105 headers: { cookie },
106 })
107 ).text()
108 ).replace(/\s+/g, " ");
109 expect(body).toContain("The last snapshot failed");
110 expect(body).toContain("the bucket said &lt;no&gt;");
111 expect(body).toContain("bucket &lt;b&gt;refusing&lt;/b&gt;");
112 expect(body).not.toContain("<no>");
113 } finally {
114 await svc.stop();
115 }
116 });
117
118 test("a plain user is told nothing is here, and a stranger is sent to sign in", async () => {
119 const cookie = await signIn("bob");
120 const plain = await get("/settings/resilience", {
121 headers: { cookie },
122 });
123 expect(plain.status).toBe(404);
124 expect(await plain.text()).not.toContain("Where it can fail");
125 const stranger = await get("/settings/resilience", {
126 redirect: "manual",
127 });
128 expect(stranger.status).toBe(303);
129 });
test/tui-resilience.test.ts added +143
@@ -0,0 +1,143 @@
1 /**
2 * Resilience in the terminal (#1236): `R` on the dashboard opens, for an
3 * admin, the same needs, snapshot store and failure-domain map the web page
4 * shows. A plain user and a guest have no `R` and reach nothing.
5 */
6
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { signUp } from "../src/actions/users.ts";
12 import { createApp, type App as Forge } from "../src/app.ts";
13 import type { User } from "../src/core/users.ts";
14 import { DOMAINS } from "../src/kernel/domains.ts";
15 import { startSnapshots } from "../src/snapshot/service.ts";
16 import { dirStore } from "../src/snapshot/store.ts";
17 import { createForgeApp } from "../src/tui/forge.ts";
18 import { resilienceScreen } from "../src/tui/screens/resilience.ts";
19 import type { TuiIdentity } from "../src/tui/session.ts";
20 import { Session } from "../src/tui/session.ts";
21 import { headlessTerminal } from "../src/tui/term/terminal.ts";
22 import { quietLogs } from "./helpers/globals.ts";
23 import { settleApp } from "./helpers/tui.ts";
24
25 quietLogs();
26
27 let dataDir: string;
28 let forge: Forge;
29 let alice: User;
30 let bob: User;
31
32 beforeAll(async () => {
33 dataDir = await mkdtemp(join(tmpdir(), "forge-tui-resilience-"));
34 forge = createApp({ dataDir, port: 0 });
35 const a = await signUp(forge, {
36 username: "alice",
37 email: "[email protected]",
38 password: "a-long-passphrase",
39 });
40 const b = await signUp(forge, {
41 username: "bob",
42 email: "[email protected]",
43 password: "another-long-passphrase",
44 });
45 if (!a.ok || !b.ok) throw new Error("signup failed");
46 alice = a.value;
47 bob = b.value;
48 expect(alice.isAdmin).toBe(true);
49 expect(bob.isAdmin).toBe(false);
50 }, 30_000);
51 afterAll(async () => {
52 forge.close();
53 await rm(dataDir, { recursive: true, force: true });
54 });
55
56 const identity = (user?: User): TuiIdentity => ({
57 sshUsername: user?.username ?? "git",
58 remoteAddress: "127.0.0.1",
59 fingerprint: "SHA256:test",
60 ...(user === undefined ? {} : { user }),
61 });
62
63 /** A session at the dashboard, `R` pressed; the screen as text. */
64 async function pressR(user?: User, rows = 120): Promise<string> {
65 const terminal = headlessTerminal(120, rows);
66 const { app } = createForgeApp(forge, identity(user), {
67 terminal,
68 exitHooks: false,
69 });
70 app.start();
71 try {
72 await settleApp(app);
73 app.dispatch({ type: "key", key: "R", ctrl: false, alt: false, shift: true });
74 await settleApp(app);
75 return app.screen.toText().replace(/\s+/g, " ");
76 } finally {
77 app.stop();
78 }
79 }
80
81 test("an admin presses R and reads every domain, and that no store is set", async () => {
82 const text = await pressR(alice);
83 expect(text).toContain("Where it can fail");
84 for (const d of DOMAINS) expect(text).toContain(d.name);
85 expect(text).toContain("No snapshots are taken");
86 expect(text).toContain("Not yet:");
87 });
88
89 test("a store on the forge's own volume is a need, and where it goes is said", async () => {
90 const where = join(dataDir, "snapshots");
91 const svc = startSnapshots(forge, dirStore(where), {
92 version: "t",
93 nightly: false,
94 });
95 try {
96 const text = await pressR(alice);
97 expect(text).toContain("Snapshots are kept on the forge's own volume");
98 expect(text).toContain("every night at 08:00 UTC");
99 } finally {
100 await svc.stop();
101 }
102 });
103
104 test("the palette offers Resilience to an admin only", () => {
105 const ids = (who?: User): string[] =>
106 createForgeApp(forge, identity(who), {
107 terminal: headlessTerminal(80, 24),
108 exitHooks: false,
109 }).app.commands.map((command) => command.id);
110 expect(ids(alice)).toContain("resilience");
111 expect(ids(bob)).not.toContain("resilience");
112 expect(ids()).not.toContain("resilience");
113 });
114
115 test("a plain user and a guest have no R and reach nothing", async () => {
116 for (const who of [bob, undefined]) {
117 const text = await pressR(who);
118 expect(text).not.toContain("Where it can fail");
119 expect(text).not.toContain("resilience");
120 }
121 });
122
123 test("the screen itself shows a non-admin nothing, even reached directly", async () => {
124 for (const who of [bob, undefined]) {
125 const terminal = headlessTerminal(100, 40);
126 const { app } = createForgeApp(forge, identity(who), {
127 terminal,
128 exitHooks: false,
129 });
130 const session = new Session(forge, identity(who));
131 let shown = "";
132 app.start();
133 try {
134 app.ctx.push(resilienceScreen(session, app.ctx));
135 await settleApp(app);
136 shown = app.screen.toText();
137 } finally {
138 app.stop();
139 }
140 expect(shown).not.toContain("Where it can fail");
141 for (const d of DOMAINS) expect(shown).not.toContain(d.breaks.slice(0, 30));
142 }
143 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs