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

Recovery, part 1: a one-page notecard whose commands the drill runs, and a Backups line that says whether the forge is recoverable now #2098

Parked opened this
Closed without merging

scout/forge:scout/1986-recovery-part-1-a-one-page-notecard-whos → main 8 commits fork 3 threads · 3 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
17 files changed +467 −38
docs/RESTORE.md +23 −11
@@ -15,21 +15,33 @@ Print this. Keep it somewhere that is not the forge.
1515
1616 ## The lines
1717
18 Replace `<store-dir>`, `<data-dir>` and `<passphrase>`. A line ending
19 `# network` needs the network and `# boot` starts the forge and does not
18 Replace `<store-dir>`, `<data-dir>` and `<passphrase>`. Lines ending
19 `# network` need the network and `# boot` starts the forge and does not
2020 return; `test/restore-card.test.ts` runs every other line against a test
21 snapshot, so this card cannot drift from the command.
21 snapshot, and its line 3 is the CLI whose `latest` goes through `restoreLatest`, the
22 same function `src/snapshot/drill.ts` restores with every week.
2223
23 1. `git clone https://forge.open-platform.sh/trevato/forge.git forge && cd forge # network`
24 2. `bun install # network`
25 3. `export FORGE_SNAPSHOT_DIR=<store-dir>`
26 4. `export FORGE_SNAPSHOT_PASSPHRASE=<passphrase>`
27 5. `bun run src/snapshot/restore.ts latest <data-dir>`
28 6. `test -s <data-dir>/forge.db`
29 7. `FORGE_DATA=<data-dir> bun run src/main.ts # boot`
24 1. `command -v git >/dev/null || apt-get install -y git; command -v bun >/dev/null || curl -fsSL https://bun.sh/install | bash; git clone https://forge.open-platform.sh/trevato/forge.git forge && cd forge && bun install # network`
25 2. `export FORGE_SNAPSHOT_DIR=<store-dir> FORGE_SNAPSHOT_PASSPHRASE=<passphrase>`
26 3. `bun run src/snapshot/restore.ts latest <data-dir> && test -s <data-dir>/forge.db`
27 4. `FORGE_DATA=<data-dir> bun run src/main.ts # boot`
28
29 Line 1 installs git (Debian-family `apt-get`; use your own package manager
30 elsewhere) and bun first if they are missing. It pipes bun's installer to a
31 shell: read <https://bun.sh/install> before you run it.
32 Then the last step is by hand and is not a command: at your DNS provider,
33 point the forge's name (A/AAAA) at this machine.
34
35 ## Where the secrets live
36
37 - **Passphrase**: in the owner's password manager and on a paper copy in the
38 safe, never in the bucket and never in the repository.
39 - **Bucket credentials** (`S3_ACCESS_KEY`, `S3_SECRET_KEY`): in the same
40 place. For a bucket, export `S3_ENDPOINT`, `S3_BUCKET`, `S3_ACCESS_KEY`,
41 `S3_SECRET_KEY` and `S3_REGION` in place of `FORGE_SNAPSHOT_DIR` in line 2.
3042
3143 The restore prints what it brought back. A wrong passphrase refuses before
3244 writing anything; a missing one restores without the key and lists the
3345 sealed values to set again. To pick an older snapshot, put its name
34 (`2026-09-22T08-00-00Z`) where line 5 says `latest`. Details:
46 (`2026-09-22T08-00-00Z`) where line 3 says `latest`. Details:
3547 [SNAPSHOT.md](SNAPSHOT.md).
src/core/migrations/20261016000000-drill-counts.ts added +9
@@ -0,0 +1,9 @@
1 // The drill counts what a restore brought back (#1986): users, pulls and
2 // apps beside repositories and issues, and whether a sealed value opened.
3 // No default: a row from before has NULL, which means "not recorded", never zero.
4 export default `
5 ALTER TABLE drill ADD COLUMN users INTEGER;
6 ALTER TABLE drill ADD COLUMN pulls INTEGER;
7 ALTER TABLE drill ADD COLUMN apps INTEGER;
8 ALTER TABLE drill ADD COLUMN sealed_opens INTEGER;
9 `;
src/snapshot/drill.ts +27 −7
@@ -14,12 +14,20 @@ import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
1414 import { join } from "node:path";
1515 import { bootRestored } from "./boot.ts";
1616 import { forgetKey, open } from "../kernel/secret.ts";
17 import { restoreSnapshot } from "./restore.ts";
17 import { restoreLatest } from "./restore.ts";
1818 import { listSnapshots } from "./snapshot.ts";
1919 import type { Store } from "./store.ts";
2020
2121 export const DRILL_TIMEOUT_MS = 10 * 60_000;
2222
23 export interface DrillCounts {
24 readonly repositories: number;
25 readonly users: number;
26 readonly issues: number;
27 readonly pulls: number;
28 readonly apps: number;
29 }
30
2331 export type DrillStep = "fetch" | "restore" | "open" | "count" | "unseal" | "health";
2432
2533 export interface DrillDeps {
@@ -30,7 +38,7 @@ export interface DrillDeps {
3038 readonly timeoutMs?: number | undefined;
3139 readonly now?: (() => Date) | undefined;
3240 /** Test seam: the restore itself. */
33 readonly restore?: typeof restoreSnapshot | undefined;
41 readonly restore?: typeof restoreLatest | undefined;
3442 /** Test seam: boot a data directory on a side port and say whether it is healthy. */
3543 readonly boot?: typeof bootRestored | undefined;
3644 }
@@ -39,7 +47,11 @@ export interface DrillResult {
3947 readonly at: string;
4048 readonly snapshotId: string | null;
4149 readonly ms: number;
42 readonly counts: { readonly repositories: number; readonly issues: number };
50 readonly counts: DrillCounts;
51 /** Set by `lastDrill` for a row kept before users, pulls, apps and the seal were counted. */
52 readonly predatesCounts?: boolean;
53 /** Whether one sealed value opened with the restored key; null when nothing is sealed. */
54 readonly sealedOpens: boolean | null;
4355 /** The side-booted forge's word; "unreached" when an earlier step failed. */
4456 readonly health: "ok" | "failed" | "unreached";
4557 readonly verdict: "green" | "red";
@@ -63,8 +75,9 @@ export async function runDrill(deps: DrillDeps): Promise<DrillResult> {
6375 const started = performance.now();
6476 const at = clock().toISOString();
6577 const timeoutMs = deps.timeoutMs ?? DRILL_TIMEOUT_MS;
66 const restore = deps.restore ?? restoreSnapshot;
67 const counts = { repositories: 0, issues: 0 };
78 const restore = deps.restore ?? restoreLatest;
79 const counts = { repositories: 0, users: 0, issues: 0, pulls: 0, apps: 0 };
80 let sealedOpens: boolean | null = null;
6881 let snapshotId: string | null = null;
6982 let step: DrillStep = "fetch";
7083 let scratch: string | undefined;
@@ -83,10 +96,12 @@ export async function runDrill(deps: DrillDeps): Promise<DrillResult> {
8396 mkdirSync(parent, { recursive: true });
8497 scratch = mkdtempSync(join(parent, "restore-"));
8598 const target = join(scratch, "data");
86 await within(
87 restore(deps.store, newest.name, target, { passphrase: deps.passphrase }),
99 const restored = await within(
100 restore(deps.store, target, { passphrase: deps.passphrase }),
88101 left(),
89102 );
103 // What was restored, not what the listing saw: a snapshot may have landed between.
104 snapshotId = restored.manifest.name;
90105
91106 step = "open";
92107 const { Database } = await import("bun:sqlite");
@@ -98,7 +113,10 @@ export async function runDrill(deps: DrillDeps): Promise<DrillResult> {
98113 const n = (sql: string): number =>
99114 db.query<{ n: number }, []>(sql).get()?.n ?? 0;
100115 counts.repositories = n("SELECT count(*) AS n FROM repo");
116 counts.users = n("SELECT count(*) AS n FROM user");
101117 counts.issues = n("SELECT count(*) AS n FROM issue");
118 counts.pulls = n("SELECT count(*) AS n FROM pull");
119 counts.apps = n("SELECT count(*) AS n FROM app");
102120
103121 step = "unseal";
104122 const secret = db
@@ -121,6 +139,7 @@ export async function runDrill(deps: DrillDeps): Promise<DrillResult> {
121139 : undefined;
122140 if (sealed !== undefined) {
123141 const opened = open(target, sealed.value, sealed.aad);
142 sealedOpens = opened.ok;
124143 if (!opened.ok)
125144 throw new Error(
126145 "a sealed value does not open with the restored key",
@@ -159,6 +178,7 @@ export async function runDrill(deps: DrillDeps): Promise<DrillResult> {
159178 snapshotId,
160179 ms: Math.round(performance.now() - started),
161180 counts,
181 sealedOpens,
162182 health,
163183 verdict: failedStep === null ? "green" : "red",
164184 failedStep,
src/snapshot/drills.ts +20 −3
@@ -13,6 +13,10 @@ interface Row {
1313 ms: number;
1414 repositories: number;
1515 issues: number;
16 users: number | null;
17 pulls: number | null;
18 apps: number | null;
19 sealed_opens: number | null;
1620 verdict: "green" | "red";
1721 failed_step: DrillStep | null;
1822 reason: string | null;
@@ -20,14 +24,18 @@ interface Row {
2024
2125 export function recordDrill(db: Database, result: DrillResult): void {
2226 db.query(
23 `INSERT INTO drill (at, snapshot_id, ms, repositories, issues, verdict, failed_step, reason)
24 VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
27 `INSERT INTO drill (at, snapshot_id, ms, repositories, issues, users, pulls, apps, sealed_opens, verdict, failed_step, reason)
28 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2529 ).run(
2630 result.at,
2731 result.snapshotId,
2832 result.ms,
2933 result.counts.repositories,
3034 result.counts.issues,
35 result.counts.users,
36 result.counts.pulls,
37 result.counts.apps,
38 result.sealedOpens === null ? null : result.sealedOpens ? 1 : 0,
3139 result.verdict,
3240 result.failedStep,
3341 result.reason,
@@ -45,7 +53,16 @@ export function lastDrill(db: Database): DrillResult | undefined {
4553 at: row.at,
4654 snapshotId: row.snapshot_id,
4755 ms: row.ms,
48 counts: { repositories: row.repositories, issues: row.issues },
56 counts: {
57 repositories: row.repositories,
58 users: row.users ?? 0,
59 issues: row.issues,
60 pulls: row.pulls ?? 0,
61 apps: row.apps ?? 0,
62 },
63 // Rows kept before the migration never counted these; say so, do not say zero.
64 ...(row.users === null ? { predatesCounts: true } : {}),
65 sealedOpens: row.sealed_opens === null ? null : row.sealed_opens === 1,
4966 // Not stored: green means health read ok; a red one failed at it or never got there.
5067 health:
5168 row.verdict === "green" ? "ok" : row.failed_step === "health" ? "failed" : "unreached",
src/snapshot/recoverable.ts added +82
@@ -0,0 +1,82 @@
1 /**
2 * Whether the forge is recoverable now, as plain data for both doors (the
3 * Backups page and the terminal): the store answers, the newest snapshot,
4 * whether the key travels in it, the last drill. Any part that fails makes
5 * the whole not ok.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { lastDrill } from "./drills.ts";
10 import { keyOf, type Manifest } from "./snapshot.ts";
11
12 /** One clause; `at` is an ISO time the surface formats in its own way. */
13 export interface Clause {
14 readonly text: string;
15 readonly at?: string;
16 }
17
18 export interface Recoverable {
19 readonly ok: boolean;
20 readonly clauses: readonly Clause[];
21 }
22
23 export function recoverable(
24 db: Database,
25 snapshots: readonly Manifest[],
26 listingError: string | undefined,
27 ): Recoverable {
28 const d = lastDrill(db);
29 const newest = snapshots[0];
30 const carried = newest === undefined ? undefined : keyOf(newest);
31 const clauses: Clause[] = [
32 { text: listingError === undefined ? "store reachable" : "store not reachable" },
33 newest === undefined
34 ? { text: "no snapshot yet" }
35 : { text: "newest snapshot", at: newest.finishedAt },
36 { text: carried === "wrapped" ? "key carried" : "key not carried" },
37 d === undefined
38 ? { text: "no drill yet" }
39 : { text: `last drill ${d.verdict}`, at: d.at },
40 ];
41 const ok =
42 listingError === undefined &&
43 newest !== undefined &&
44 carried === "wrapped" &&
45 d?.verdict === "green";
46 return { ok, clauses };
47 }
48
49 /**
50 * What the last drill counted, in a clause: "3 repositories, 2 users, …".
51 * A row from before the new counts says only what it did record.
52 */
53 export function countsSay(d: {
54 readonly counts: {
55 readonly repositories: number;
56 readonly users: number;
57 readonly issues: number;
58 readonly pulls: number;
59 readonly apps: number;
60 };
61 readonly sealedOpens: boolean | null;
62 readonly predatesCounts?: boolean | undefined;
63 }): string {
64 const c = d.counts;
65 const n = (k: number, one: string, many: string): string =>
66 `${k} ${k === 1 ? one : many}`;
67 if (d.predatesCounts === true) {
68 return `${n(c.repositories, "repository", "repositories")}, ${n(c.issues, "issue", "issues")}; users, pulls, apps and the seal were not counted then`;
outdated

A NULL sealed_opens from a pre-migration row is rendered as "nothing sealed to open", which is false. Distinguish unknown from nothing sealed, and do not print zero counts for rows that predate the columns.

69 }
70 return [
71 n(c.repositories, "repository", "repositories"),
72 n(c.users, "user", "users"),
73 n(c.issues, "issue", "issues"),
74 n(c.pulls, "pull", "pulls"),
75 n(c.apps, "app", "apps"),
76 ].join(", ") +
77 (d.sealedOpens === null
78 ? "; nothing sealed to open"
79 : d.sealedOpens
80 ? "; a sealed value opens"
81 : "; a sealed value does not open");
82 }
src/snapshot/restore.ts +33 −6
@@ -174,6 +174,29 @@ export async function restoreSnapshot(
174174 return { manifest, files, repos, key: have, sealedMissing };
175175 }
176176
177 /** Thrown by `restoreLatest` when the store holds no snapshot. */
178 export class NoSnapshotError extends Error {
179 constructor(where: string) {
180 super(`no snapshot in ${where}`);
181 this.name = "NoSnapshotError";
182 }
outdated

RESTORE_LINE is never executed or used by the CLI or the drill; only tests read it. Either drive the usage text and the card test from it for real, or remove it and the drift claim.

183 }
184
185 /**
186 * Restore the newest snapshot in the store; throws NoSnapshotError when it
187 * holds none. The card's line 3 (`restore.ts latest`) and the drill both come
188 * through here.
189 */
190 export async function restoreLatest(
191 store: Store,
192 dataDir: string,
193 opts: { passphrase?: string | undefined } = {},
194 ): Promise<Restored> {
195 const newest = (await listSnapshots(store))[0];
196 if (newest === undefined) throw new NoSnapshotError(store.where);
197 return restoreSnapshot(store, newest.name, dataDir, opts);
198 }
199
177200 if (import.meta.main) {
178201 const [name, dataDir] = process.argv.slice(2);
179202 if (!name || !dataDir) {
@@ -193,15 +216,19 @@ if (import.meta.main) {
193216 );
194217 process.exit(2);
195218 }
196 const newest = name === "latest" ? (await listSnapshots(store))[0] : undefined;
197 if (name === "latest" && newest === undefined) {
219 const passphrase = process.env["FORGE_SNAPSHOT_PASSPHRASE"] || undefined;
220 let done: Restored;
221 try {
outdated

Matching an error by its message text is fragile; throw a small typed error from restoreLatest and test with instanceof.

222 done =
223 name === "latest"
224 ? await restoreLatest(store, dataDir, { passphrase })
225 : await restoreSnapshot(store, name, dataDir, { passphrase });
226 } catch (error) {
227 if (!(error instanceof NoSnapshotError)) throw error;
198228 // CLI message on stderr for the person at the terminal.
199 console.error(`no snapshot in ${store.where}`);
229 console.error(error.message);
200230 process.exit(1);
201231 }
202 const done = await restoreSnapshot(store, newest?.name ?? name, dataDir, {
203 passphrase: process.env["FORGE_SNAPSHOT_PASSPHRASE"] || undefined,
204 });
205232 console.log(
206233 `restored ${done.manifest.name} (forge ${done.manifest.version}): ${done.files} files, ${done.repos} repositories into ${dataDir}`,
207234 );
src/tui/forge.ts +12
@@ -38,6 +38,7 @@ import { pullScreen } from "./screens/pull.ts";
3838 import { blobScreen } from "./screens/repo.ts";
3939 import { dashboardScreen } from "./screens/dashboard.ts";
4040 import { accessScreen } from "./screens/access.ts";
41 import { backupLines, backupsScreen } from "./screens/backups.ts";
4142 import { resilienceLines, resilienceScreen } from "./screens/resilience.ts";
4243 import { flowLines, flowScreen } from "./screens/flow.ts";
4344 import { stalledScreen } from "./screens/stalled.ts";
@@ -257,6 +258,17 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
257258 hint: "what outside agents tried",
258259 run: () => ctx.push(accessScreen(session, ctx)),
259260 });
261 // Whether the forge is recoverable now, as Settings → Backups says it: a site admin's.
262 if (session.user?.isAdmin === true && session.user.kind !== "agent")
263 commands.push({
264 id: "backups",
265 title: "Backups",
266 hint: "whether the forge is recoverable now",
267 run: () =>
268 runAsync(ctx, async () =>
269 ctx.push(backupsScreen(ctx, await backupLines(session))),
270 ),
271 });
260272 commands.push({
261273 id: "family",
262274 title: "Family",
src/tui/screens/backups.ts added +64
@@ -0,0 +1,64 @@
1 /**
2 * The Backups command's dialog, a forge admin's: Settings → Backups' one
3 * line ("is the forge recoverable now?") and the last drill's counts, from
4 * `snapshot/recoverable.ts`, the same the page reads. Read-only; Enter, Esc
5 * or q closes it.
6 */
7
8 import { countsSay, recoverable } from "../../snapshot/recoverable.ts";
9 import { lastDrill } from "../../snapshot/drills.ts";
10 import { snapshotsOf } from "../../snapshot/service.ts";
11 import type { Manifest } from "../../snapshot/snapshot.ts";
12 import type { Ctx, Screen } from "../app/app.ts";
13 import { binding } from "../app/keys.ts";
14 import type { Session } from "../session.ts";
15 import { wrap } from "../term/width.ts";
16 import { dialog } from "../ui/widgets.ts";
17 import { ago } from "./common.ts";
18
19 const WIDTH = 64;
20
21 export async function backupLines(f: Session): Promise<string[]> {
22 const svc = snapshotsOf(f.app);
23 if (svc === undefined || svc.store === undefined)
24 return wrap("No snapshots are taken: this forge was given nowhere to put them.", WIDTH - 6);
25 let snapshots: Manifest[] = [];
26 let listing: string | undefined;
27 try {
28 snapshots = await svc.list();
29 } catch (error) {
30 listing = String(error);
31 }
32 const r = recoverable(f.db, snapshots, listing);
33 const d = lastDrill(f.db);
34 const said = r.clauses
35 .map((c) => (c.at === undefined ? c.text : `${c.text} ${ago(c.at)}`))
36 .join(" · ");
37 return [
38 ...wrap(`${r.ok ? "Recoverable" : "Not proven recoverable"}: ${said}`, WIDTH - 6),
39 ...(d === undefined || d.verdict !== "green"
40 ? []
41 : ["", ...wrap(`Drill restored ${countsSay(d)}.`, WIDTH - 6)]),
42 ];
43 }
44
45 export function backupsScreen(ctx: Ctx, lines: readonly string[]): Screen {
46 return {
47 title: "Backups",
48 keys: [binding(["enter", "esc", "q"], "close")],
49 render(area, s) {
50 const buttons = dialog(s, area, ctx.theme.c, {
51 title: "Backups",
52 body: lines,
53 actions: [{ label: "Close" }],
54 selected: 0,
55 width: WIDTH,
56 });
57 buttons.forEach((rect) => ctx.hit(rect, () => ctx.pop()));
58 },
59 key(e) {
60 if (e.key === "enter" || e.key === "esc" || e.key === "q") ctx.pop();
61 return true;
62 },
63 };
64 }
src/web/pages/backups.ts +20 −2
@@ -17,7 +17,8 @@ import {
1717 import { forgetMirror, saveMirror } from "../../actions/mirror.ts";
1818 import { mirrorSealedSet, mirrorNeed, MIRROR_SEALED } from "../../snapshot/mirror.ts";
1919 import { resolveDestination, sealedSet } from "../../snapshot/destination.ts";
20 import { keyOf } from "../../snapshot/snapshot.ts";
20 import { keyOf, type Manifest } from "../../snapshot/snapshot.ts";
21 import { countsSay, recoverable } from "../../snapshot/recoverable.ts";
2122 import { lastDrill } from "../../snapshot/drills.ts";
2223 import { snapshotsOf } from "../../snapshot/service.ts";
2324 import type { Ctx } from "../../http/context.ts";
@@ -98,7 +99,7 @@ function drillLine(ctx: Ctx): Html {
9899 ? html`<p class="backups-drill">
99100 ${icon("check")} Last drill ${time(d.at)}: snapshot
100101 <code>${d.snapshotId ?? ""}</code> restored green in ${d.ms} ms —
101 ${d.counts.repositories} repositories, ${d.counts.issues} issues.
102 ${countsSay(d)}.
102103 </p>`
103104 : html`<p class="backups-error backups-drill">
104105 ${icon("alert")} Last drill ${time(d.at)}: snapshot
@@ -113,6 +114,22 @@ function drillLine(ctx: Ctx): Html {
113114 </form>`;
114115 }
115116
117 /** Whether the forge is recoverable now, in one line; any failing part makes it an alert. */
118 function recoverableLine(
119 ctx: Ctx,
120 snapshots: readonly Manifest[],
121 listing: string | undefined,
122 ): Html {
123 const r = recoverable(ctx.app.db, snapshots, listing);
124 return html`<p class="backups-recoverable${r.ok ? "" : " backups-error"}">
125 ${icon(r.ok ? "check" : "alert")}
126 ${r.clauses.map(
127 (c, i) =>
128 html`${i ? " · " : ""}${c.text}${c.at === undefined ? "" : html` ${time(c.at)}`}`,
129 )}
130 </p>`;
131 }
132
116133 export async function backupsPage(ctx: Ctx): Promise<Response> {
117134 const denied = requireAdmin(ctx);
118135 if (denied) return denied;
@@ -150,6 +167,7 @@ bun run src/snapshot/restore.ts ${snapshots[0].name} /path/to/empty/data</pre>`
150167 crew's logs — to <code>${svc.store.where}</code>, and keeps the newest
151168 fourteen.
152169 </p>
170 ${recoverableLine(ctx, snapshots, listing)}
153171 ${keyNote(svc.wraps, snapshots[0])}
154172 ${when(
155173 svc.progress(),
test/domains.test.ts +1 −1
@@ -62,7 +62,7 @@ test("a nearly full disk says the state's words", () => {
6262
6363 test("a red restore drill says the snapshot store's words", () => {
6464 recordVerdict(dataDir, {
65 at: new Date().toISOString(), snapshotId: null, ms: 1, counts: { repositories: 0, issues: 0 },
65 at: new Date().toISOString(), snapshotId: null, ms: 1, counts: { repositories: 0, users: 0, issues: 0, pulls: 0, apps: 0 }, sealedOpens: null,
6666 health: "unreached", verdict: "red", failedStep: "fetch", reason: "no bucket",
6767 });
6868 for (const s of said("snapshots")) expect(read()).toContain(s);
test/drill-board-line.test.ts +1 −1
@@ -23,7 +23,7 @@ const drill = (at: number, red: boolean): DrillResult => ({
2323 at: new Date(at).toISOString(),
2424 snapshotId: "snap-1",
2525 ms: 5,
26 counts: { repositories: 1, issues: 1 },
26 counts: { repositories: 1, users: 0, issues: 1, pulls: 0, apps: 0 }, sealedOpens: null,
2727 health: red ? "failed" : "ok",
2828 verdict: red ? "red" : "green",
2929 failedStep: red ? "unseal" : null,
test/drill-legacy-row.test.ts added +42
@@ -0,0 +1,42 @@
1 /** A drill row kept before the counts existed says so; it never claims zeros or "nothing sealed". */
2 import { expect, test } from "bun:test";
3 import { createApp } from "../src/app.ts";
4 import { mkdtempSync, rmSync } from "node:fs";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { lastDrill } from "../src/snapshot/drills.ts";
8 import { countsSay } from "../src/snapshot/recoverable.ts";
9 import { NoSnapshotError, restoreLatest } from "../src/snapshot/restore.ts";
10 import { dirStore } from "../src/snapshot/store.ts";
11
12 test("a pre-migration row is not counted as zeros and a missing seal", () => {
13 const root = mkdtempSync(join(tmpdir(), "forge-drill-legacy-"));
14 const app = createApp({ dataDir: root, port: 0 });
15 try {
16 app.db
17 .query(
18 `INSERT INTO drill (at, snapshot_id, ms, repositories, issues, verdict) VALUES (?, 's', 5, 4, 9, 'green')`,
19 )
20 .run(new Date().toISOString());
21 const d = lastDrill(app.db)!;
22 expect(d.predatesCounts).toBe(true);
23 const say = countsSay(d);
24 expect(say).toContain("4 repositories, 9 issues");
25 expect(say).toContain("not counted then");
26 expect(say).not.toContain("0 users");
27 expect(say).not.toContain("nothing sealed");
28 } finally {
29 app.close();
30 rmSync(root, { recursive: true, force: true });
31 }
32 });
33
34 test("an empty store throws a NoSnapshotError", async () => {
35 const root = mkdtempSync(join(tmpdir(), "forge-drill-empty-"));
36 try {
37 const err = await restoreLatest(dirStore(join(root, "store")), join(root, "d")).catch((e) => e);
38 expect(err).toBeInstanceOf(NoSnapshotError);
39 } finally {
40 rmSync(root, { recursive: true, force: true });
41 }
42 });
test/drill-verdict.test.ts +2 −2
@@ -134,7 +134,7 @@ describe("the drill's verdict", () => {
134134 at: "2026-09-22T09:00:00Z",
135135 snapshotId: null,
136136 ms: 5,
137 counts: { repositories: 0, issues: 0 },
137 counts: { repositories: 0, users: 0, issues: 0, pulls: 0, apps: 0 }, sealedOpens: null,
138138 health: "unreached",
139139 verdict: "red",
140140 failedStep: "fetch",
@@ -221,7 +221,7 @@ describe("telling the recovery issue", () => {
221221 at: "2026-10-18T09:00:00Z",
222222 snapshotId: "s",
223223 ms: 1,
224 counts: { repositories: 0, issues: 0 },
224 counts: { repositories: 0, users: 0, issues: 0, pulls: 0, apps: 0 }, sealedOpens: null,
225225 health: "ok",
226226 verdict: "green",
227227 failedStep: null,
test/restore-card.test.ts +10 −2
@@ -73,11 +73,19 @@ test("only network and boot lines are skipped, and they are the known ones", ()
7373 const skipped = lines.filter((l) => /# (network|boot)$/.test(l.text));
7474 expect(skipped.map((l) => l.text.replace(/ # (network|boot)$/, "")).sort()).toEqual([
7575 "FORGE_DATA=<data-dir> bun run src/main.ts",
76 "bun install",
77 "git clone https://forge.open-platform.sh/trevato/forge.git forge && cd forge",
76 'command -v git >/dev/null || apt-get install -y git; command -v bun >/dev/null || curl -fsSL https://bun.sh/install | bash; git clone https://forge.open-platform.sh/trevato/forge.git forge && cd forge && bun install',
7877 ]);
7978 });
8079
80 test("the card's restore line is the one the drill runs", () => {
81 const restores = lines.filter((l) => l.text.includes("restore.ts"));
82 expect(restores).toHaveLength(1);
83 expect(restores[0]!.n).toBe(3);
84 expect(restores[0]!.text).toStartWith("bun run src/snapshot/restore.ts latest <data-dir>");
85 // The run below executes that line; test/snapshot-drill.test.ts checks the
86 // drill restores through the same restoreLatest.
87 });
88
8189 test("the card's own lines restore the snapshot into an empty directory", async () => {
8290 const store = join(root, "store");
8391 const data = join(root, "restored");
test/snapshot-drill-page.test.ts +8 −2
@@ -62,7 +62,7 @@ describe("the drill on the Backups page", () => {
6262 at: new Date().toISOString(),
6363 snapshotId: "snap-stub-1",
6464 ms: 1234,
65 counts: { repositories: 7, issues: 42 },
65 counts: { repositories: 7, users: 3, issues: 42, pulls: 5, apps: 2 }, sealedOpens: true,
6666 health: verdict === "green" ? "ok" : "unreached",
6767 verdict,
6868 failedStep: verdict === "green" ? null : "unseal",
@@ -93,12 +93,18 @@ describe("the drill on the Backups page", () => {
9393 const before = await page(cookie);
9494 expect(before).toContain("No restore drill has run yet");
9595 expect(before).toContain("Run a drill");
96 // The one line: store, newest snapshot, key, last drill.
97 expect(before).toContain("store reachable");
98 expect(before).toContain("no snapshot yet");
99 expect(before).toContain("key not carried");
100 expect(before).toContain("no drill yet");
96101 expect((await post(cookie)).status).toBe(303);
97102 expect(ran).toBe(1);
98103 const html = await page(cookie);
99104 expect(html).toContain("snap-stub-1");
100 expect(html).toContain("7 repositories, 42 issues");
105 expect(html).toContain("7 repositories, 3 users, 42 issues, 5 pulls, 2 apps; a sealed value opens");
101106 expect(html).toContain("1234 ms");
107 expect(html).toContain("last drill green");
102108 expect(app.db.query("SELECT count(*) AS n FROM drill").get()).toEqual({ n: 1 });
103109 });
104110
test/snapshot-drill.test.ts +29 −1
@@ -14,6 +14,7 @@ import { createApp, type App } from "../src/app.ts";
1414 import { createIssue } from "../src/core/issues.ts";
1515 import { createUser } from "../src/core/users.ts";
1616 import { runDrill } from "../src/snapshot/drill.ts";
17 import { restoreLatest } from "../src/snapshot/restore.ts";
1718 import { takeSnapshot } from "../src/snapshot/snapshot.ts";
1819 import { dirStore } from "../src/snapshot/store.ts";
1920
@@ -98,11 +99,38 @@ describe("the restore drill", () => {
9899 expect(r.verdict).toBe("green");
99100 expect(r.failedStep).toBeNull();
100101 expect(r.snapshotId).toBe("2026-09-22T08-00-00Z");
101 expect(r.counts).toEqual({ repositories: 1, issues: 2 });
102 expect(r.counts).toEqual({ repositories: 1, users: 1, issues: 2, pulls: 0, apps: 1 });
103 expect(r.sealedOpens).toBe(true);
102104 expect(r.ms).toBeGreaterThanOrEqual(0);
103105 expect(scratchLeft()).toEqual([]);
104106 });
105107
108 test("the drill restores through restoreLatest, the card's entry point", async () => {
109 const seen: string[] = [];
110 const r = await runDrill(
111 deps({
112 restore: (st: unknown, target: string, opts: unknown) => {
113 seen.push(target);
114 return restoreLatest(st as never, target, opts as never);
115 },
116 }),
117 );
118 expect(r.verdict).toBe("green");
119 expect(seen).toHaveLength(1);
120 });
121
122 test("the recorded snapshot id is the one restored, not the one listed", async () => {
123 const r = await runDrill(
124 deps({
125 restore: async (st: unknown, target: string, opts: unknown) => {
126 const done = await restoreLatest(st as never, target, opts as never);
127 return { ...done, manifest: { ...done.manifest, name: "landed-between" } };
128 },
129 }),
130 );
131 expect(r.snapshotId).toBe("landed-between");
132 });
133
106134 test("a sealed value that cannot open (no passphrase, so no key) is red at unseal", async () => {
107135 const r = await runDrill(deps({ passphrase: undefined }));
108136 expect(r.verdict).toBe("red");
test/tui-backups.test.ts added +84
@@ -0,0 +1,84 @@
1 /**
2 * The terminal answers "is the forge recoverable now?" as the Backups page
3 * does, from the same module, and shows what the last drill counted. Only a
4 * site admin is offered the command.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtempSync, rmSync } from "node:fs";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { createUser, type User } from "../src/core/users.ts";
12 import { recordDrill } from "../src/snapshot/drills.ts";
13 import { startSnapshots, type SnapshotsHandle } from "../src/snapshot/service.ts";
14 import { dirStore } from "../src/snapshot/store.ts";
15 import { forgeCommands, Session } from "../src/tui/forge.ts";
16 import { backupLines } from "../src/tui/screens/backups.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18
19 quietLogs();
20
21 let root = "";
22 let app: App;
23 let svc: SnapshotsHandle;
24 let admin: User;
25 let member: User;
26
27 const identity = (user?: User) => ({
28 sshUsername: "x",
29 remoteAddress: "127.0.0.1",
30 ...(user ? { user } : {}),
31 });
32
33 beforeAll(async () => {
34 root = mkdtempSync(join(tmpdir(), "forge-tuibackups-"));
35 app = createApp({ dataDir: root, port: 0 });
36 const make = async (username: string, adminIfFirst: boolean) => {
37 const u = await createUser(app.db, {
38 trusted: true,
39 username,
40 email: `${username}@forge.local`,
41 password: "a-good-passphrase",
42 adminIfFirst,
43 });
44 if (!u.ok) throw new Error(u.error);
45 return u.value;
46 };
47 admin = await make("alice", true);
48 member = await make("bob", false);
49 svc = startSnapshots(app, dirStore(join(root, "store")), { version: "t", nightly: false });
50 });
51
52 afterAll(async () => {
53 await svc.stop();
54 app.close();
55 rmSync(root, { recursive: true, force: true });
56 });
57
58 test("the terminal says the forge is not proven recoverable, then what the drill counted", async () => {
59 const session = new Session(app, identity(admin));
60 const before = (await backupLines(session)).join(" ");
61 expect(before).toContain("Not proven recoverable");
62 expect(before).toContain("no snapshot yet");
63 expect(before).toContain("no drill yet");
64 recordDrill(app.db, {
65 at: new Date().toISOString(),
66 snapshotId: "s1",
67 ms: 5,
68 counts: { repositories: 7, users: 3, issues: 42, pulls: 5, apps: 2 },
69 sealedOpens: true,
70 health: "ok",
71 verdict: "green",
72 failedStep: null,
73 reason: null,
74 });
75 const after = (await backupLines(session)).join(" ").replace(/\s+/g, " ");
76 expect(after).toContain("last drill green");
77 expect(after).toContain("7 repositories, 3 users, 42 issues, 5 pulls, 2 apps; a sealed value opens");
78 });
79
80 test("only a site admin is offered the command", () => {
81 const ids = (u: User) => forgeCommands(new Session(app, identity(u)))({} as never).map((c) => c.id);
82 expect(ids(admin)).toContain("backups");
83 expect(ids(member)).not.toContain("backups");
84 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs