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

One model for every cloud: provider ▸ account ▸ project ▸ resources, read every 5 minutes #17226

opened this

Merged 40h 20m ago, live in production

sold/cloud-projects → main 0 commits 4 threads · 4 unresolved

  • Merged. sold/cloud-projects was merged into main as 8eddcc7.

Review

Sign in to review this change.
17 files changed +883 −8
docs/features/infra.md +5
@@ -65,3 +65,8 @@ Deleting a database, and the data in it, is not here yet: do it at DigitalOcean,
6565 Phase 3's first kind, DigitalOcean Spaces (`src/cloud/bucket.ts`; a new provider is one more row of `BUCKETS`). In Talk or MCP, `infra` `price` with `bucket: {region, name, stored_gib?, out_gib?}` says what a bucket costs a month and where it would answer: the provider's list price ($5 with 250 GiB stored and 1 TiB out in it, 2¢ and 1¢ a GiB over), held as numbers because Spaces has no price endpoint. `bind` with `repo` sets that app's secret `BUCKET_URL` to the bucket's address (`src/actions/bucket.ts`), which restarts the app as any secret change does. Not done yet: making the bucket from a plan (it needs Spaces keys, which the forge does not hold), Hetzner and B2, and the page and terminal doors; make the bucket at the provider and keep its keys as the app's secrets.
6666
6767 Terminal: the **Buckets** palette entry (`src/tui/screens/buckets.ts`): `p` reads a price for anyone signed in, `b` binds a bucket's address to an app as `BUCKET_URL`, a forge admin's only.
68
69 ## Projects: one model for every cloud (#17151)
70
71 Every DigitalOcean and Hetzner account is read into provider ▸ account ▸ project ▸ resource every five minutes (the `cloud-projects` duty), and on demand (Read now under Projects on /infra, `P` in the terminal's Infra). GETs only, through the audited fetch (`gatedFetch`), with the account's sealed key. DigitalOcean: `GET /v2/projects`, then each project's `/v2/projects/{id}/resources` (URNs `do:droplet:…`, `do:volume:…`), joined with `/v2/droplets` and `/v2/volumes`; a droplet or volume in no project's list is filed under the default. Hetzner: one token is one project, named by the account's project label (else its name); servers, volumes, firewalls and primary IPs, each with its `forge` label. Kept in `cloud_project` and `cloud_resource`, columns named for the OpenTelemetry `cloud.*`/`host.*` attributes (`cloud_provider`, `cloud_account_id`, `cloud_region`, `cloud_resource_id`, `host_type`). Whether a thing is the forge's is the cloud watch's judgement; the rest is "found", named and never touched. /infra's Projects section lists each project with its resources, its monthly cost at list price (a thing the catalog cannot price is counted, not guessed), and made by the forge against found; the terminal's Infra lists the same; `infra` `list` carries `projects` (ten at most, five strays named each) with a `says` line.
72
src/actions/infra.ts +26 −1
@@ -14,6 +14,9 @@
1414 */
1515
1616 import type { App } from "../app.ts";
17 import { projectsOf, refreshProjects, type ProjectView } from "../cloud/projects.ts";
18 import { gatedFetch } from "../cloud/gate.ts";
19 import { resolveSecrets } from "../core/secret_store.ts";
1720 import { billingSentence, billsOf, existsAtProvider, type Bills } from "../cloud/billing.ts";
1821 import { specWordsOf } from "../cloud/dns_record.ts";
1922 import { experiments, type Experiments } from "../cloud/experiments.ts";
@@ -37,7 +40,7 @@ import { repoDir } from "../git/repos.ts";
3740 import { err, ok, type Result } from "../kernel/result.ts";
3841 import { listBoxes } from "../games/store.ts";
3942 import { getBaseDomain } from "../settings/pinned_domain.ts";
40 import { LIFETIME_DAYS, dayWords, endsWords } from "./pinned.ts";
43 import { LIFETIME_DAYS, dayWords, endsWords, net } from "./pinned.ts";
4144 import { placeWords } from "../cloud/places.ts";
4245 import { countSnapshots, listSnapshots } from "../core/snapshots.ts";
4346 import { snapshotOffer, snapshotView, type SnapshotView } from "./infra_snapshot.ts";
@@ -814,3 +817,25 @@ export function rebuild(app: App, actor: User | undefined, planId: string): Resu
814817
815818 /** The domain machines are named under, for a door that shows where a new one will answer. */
816819 export const domainOf = (app: App): string => getBaseDomain(app.db);
820
821 /** Every cloud project and what is in it, as the last read kept it (`cloud/projects.ts`). An admin's. */
822 export function projectsView(app: App, actor: User | undefined): Result<ProjectView[], string> {
823 const who = admin(actor);
824 return who.ok ? ok(projectsOf(app.db)) : who;
825 }
826
827 /**
828 * Read every DigitalOcean and Hetzner account into its projects now, as the five-minute duty does:
829 * GETs only, through the audited fetch, with the sealed keys opened for this admin.
830 */
831 export async function readProjectsNow(app: App, actor: User | undefined): Promise<Result<{ read: string[]; failed: string[] }, string>> {
832 const who = admin(actor);
833 if (!who.ok) return who;
834 return ok(
835 await refreshProjects(
836 app.db,
837 (secret) => resolveSecrets(app.db, app.config.dataDir, app.bus, [secret], { actor: who.value.id, run: "infra:projects" })[secret],
838 (provider, account) => gatedFetch(app.db, { provider, account }, "infra:projects", net.fetch),
839 ),
840 );
841 }
src/cloud/projects.ts added +351
@@ -0,0 +1,351 @@
1 /**
2 * Every cloud as one model (#17151, V3): provider ▸ account ▸ project ▸ resource, read from the
3 * provider with GETs alone and kept in `cloud_project` and `cloud_resource`, columns named for the
4 * OpenTelemetry `cloud.*`/`host.*` attributes.
5 *
6 * - DigitalOcean: `GET /v2/projects`, then each project's `/v2/projects/{id}/resources` (URNs
7 * `do:droplet:<id>`, `do:volume:<id>`), joined with `/v2/droplets` and `/v2/volumes` for their
8 * names, regions and sizes. A droplet or volume in no project's list is filed under the default.
9 * - Hetzner: one token is one project, named by the label the forge keeps for the account (its
10 * project setting, else its name). Servers, volumes, firewalls and primary IPs, each with its
11 * `forge` label, which groups what the forge made by the forge it was made for.
12 *
13 * Whether a thing is the forge's is the watch's own judgement (`judge`: on a live row, or named as
14 * the forge names things and young or of a live row); the rest is `found`. A stray is named, never
15 * touched. Prices are list prices from the Places catalog; the provider's bill is the truth.
16 */
17
18 import type { Database } from "bun:sqlite";
19 import { getCloudAccount, listCloudAccounts, secretNameOf } from "../core/cloud_account.ts";
20 import { priced } from "./ceiling.ts";
21 import { VOLUME_GIB } from "./places.ts";
22 import { dollars } from "./prices.ts";
23 import type { Fetch } from "./providers.ts";
24 import { judge, pages, text } from "./watch.ts";
25 import type { Seen } from "./watch_read.ts";
26
27 /** The clouds read into projects. */
28 export const PROJECT_CLOUDS = ["digitalocean", "hetzner"] as const;
29
30 export type ResourceKind = "machine" | "volume" | "firewall" | "address";
31
32 export interface CloudProject {
33 readonly provider: string;
34 readonly account: string;
35 readonly id: string;
36 readonly name: string;
37 readonly isDefault: boolean;
38 }
39
40 export interface CloudResource {
41 readonly provider: string;
42 readonly account: string;
43 readonly project: string;
44 /** `<kind>:<the provider's id>`: ids of different kinds may meet at one provider. */
45 readonly id: string;
46 readonly kind: ResourceKind;
47 readonly name: string;
48 readonly region: string;
49 readonly size: string;
50 /** The `forge` label (Hetzner) or tag (DigitalOcean): the forge it was made for; empty when none. */
51 readonly label: string;
52 readonly madeBy: "forge" | "found";
53 /** List price a month, cents; null when the catalog has none. */
54 readonly cents: number | null;
55 readonly createdAt: string;
56 }
57
58 /** One thing as read: the watch's fields, any kind (an address too), its project and its label. */
59 type Thing = Omit<Seen, "kind"> & { readonly kind: ResourceKind; readonly project: string; readonly label: string };
60
61 /** What was read of an account before it is judged: its projects and each thing, with its project. */
62 interface Read {
63 readonly projects: { id: string; name: string; isDefault: boolean }[];
64 readonly things: Thing[];
65 }
66
67 const DO = "https://api.digitalocean.com/v2";
68 const HZ = "https://api.hetzner.cloud/v1";
69
70 /** The forge tag of a DigitalOcean thing (`forge:<name>`), or empty. */
71 const doLabel = (tags: unknown): string =>
72 Array.isArray(tags)
73 ? (tags
74 .map(String)
75 .find((t) => t.startsWith("forge:"))
76 ?.slice(6) ?? "")
77 : "";
78
79 async function readDigitalOcean(f: Fetch, token: string): Promise<Read> {
80 const projects = (await pages(f, token, `${DO}/projects`, "projects", 200)).map((p) => ({
81 id: text(p.id, 64),
82 name: text(p.name),
83 isDefault: p.is_default === true,
84 }));
85 const owner = new Map<string, string>();
86 for (const p of projects)
87 for (const r of await pages(f, token, `${DO}/projects/${encodeURIComponent(p.id)}/resources`, "resources", 200))
88 owner.set(String(r.urn), p.id);
89 const fallback = projects.find((p) => p.isDefault)?.id ?? projects[0]?.id ?? "default";
90 const [droplets, volumes] = [
91 await pages(f, token, `${DO}/droplets`, "droplets", 200),
92 await pages(f, token, `${DO}/volumes`, "volumes", 200),
93 ];
94 return {
95 projects: projects.length > 0 ? projects : [{ id: "default", name: "default", isDefault: true }],
96 things: [
97 ...droplets.map((x) => ({
98 kind: "machine" as const,
99 id: text(x.id),
100 name: text(x.name),
101 createdAt: text(x.created_at),
102 datacenter: text(x.region?.slug),
103 size: text(x.size_slug),
104 gib: 0,
105 project: owner.get(`do:droplet:${String(x.id)}`) ?? fallback,
106 label: doLabel(x.tags),
107 })),
108 ...volumes.map((x) => ({
109 kind: "volume" as const,
110 id: text(x.id),
111 name: text(x.name),
112 createdAt: text(x.created_at),
113 datacenter: text(x.region?.slug),
114 size: "",
115 gib: Number(x.size_gigabytes) || VOLUME_GIB,
116 project: owner.get(`do:volume:${String(x.id)}`) ?? fallback,
117 label: doLabel(x.tags),
118 })),
119 ].filter((t) => t.id !== ""),
120 };
121 }
122
123 async function readHetzner(f: Fetch, token: string, project: string): Promise<Read> {
124 const [servers, volumes, walls, ips] = [
125 await pages(f, token, `${HZ}/servers`, "servers", 50),
126 await pages(f, token, `${HZ}/volumes`, "volumes", 50),
127 await pages(f, token, `${HZ}/firewalls`, "firewalls", 50),
128 await pages(f, token, `${HZ}/primary_ips`, "primary_ips", 50),
129 ];
130 const label = (x: any): string => text(x?.labels?.forge, 40);
131 const base = (x: any) => ({ id: text(x.id), name: text(x.name), createdAt: text(x.created), project, label: label(x) });
132 return {
133 projects: [{ id: project, name: project, isDefault: true }],
134 things: [
135 ...servers.map((x) => ({
136 ...base(x),
137 kind: "machine" as const,
138 datacenter: text(x.datacenter?.location?.name),
139 size: text(x.server_type?.name),
140 gib: 0,
141 })),
142 ...volumes.map((x) => ({
143 ...base(x),
144 kind: "volume" as const,
145 datacenter: text(x.location?.name),
146 size: "",
147 gib: Number(x.size) || VOLUME_GIB,
148 })),
149 ...walls.map((x) => ({ ...base(x), kind: "firewall" as const, datacenter: "", size: "", gib: 0 })),
150 ...ips.map((x) => ({
151 ...base(x),
152 kind: "address" as const,
153 datacenter: text(x.datacenter?.location?.name),
154 size: text(x.type),
155 gib: 0,
156 })),
157 ].filter((t) => t.id !== ""),
158 };
159 }
160
161 /** The label a Hetzner account's one project goes by: the project the forge files it in, else its name. */
162 export const hetznerProject = (db: Database, account: string): string => getCloudAccount(db, "hetzner", account)?.project || account;
163
164 /**
165 * Read an account's projects and everything in them, judge each thing as the watch does, and keep
166 * it all in place of the last read. GETs only, through `f` (the caller's `gatedFetch`, so each is
167 * audited). Throws when a read fails: nothing is half-kept.
168 */
169 export async function readProjects(
170 db: Database,
171 provider: string,
172 account: string,
173 f: Fetch,
174 token: string,
175 now = new Date(),
176 ): Promise<{ projects: number; resources: number }> {
177 const read =
178 provider === "digitalocean"
179 ? await readDigitalOcean(f, token)
180 : provider === "hetzner"
181 ? await readHetzner(f, token, hetznerProject(db, account))
182 : undefined;
183 if (read === undefined) throw new Error(`${provider} is not read into projects`);
184 const prices = priced(db);
185 // Machines, volumes and firewalls are judged as the watch judges them; an address is the forge's
186 // when its labelled for a forge, and has no catalog price.
187 const judged = judge(
188 db,
189 provider,
190 account,
191 read.things.flatMap((t): Seen[] => (t.kind === "address" ? [] : [{ ...t, kind: t.kind }])),
192 prices,
193 now.getTime(),
194 );
195 const verdict = new Map(judged.map((j) => [`${j.kind}:${j.id}`, j]));
196 const at = now.toISOString();
197 db.transaction(() => {
198 db.query("DELETE FROM cloud_project WHERE cloud_provider = ?1 AND cloud_account_id = ?2").run(provider, account);
199 db.query("DELETE FROM cloud_resource WHERE cloud_provider = ?1 AND cloud_account_id = ?2").run(provider, account);
200 const project = db.query(
201 "INSERT INTO cloud_project (cloud_provider, cloud_account_id, cloud_project_id, name, is_default, read_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
202 );
203 for (const p of read.projects) project.run(provider, account, p.id, p.name, p.isDefault ? 1 : 0, at);
204 const thing = db.query(
205 `INSERT OR REPLACE INTO cloud_resource (cloud_provider, cloud_account_id, cloud_resource_id, cloud_project_id, kind, name, cloud_region, host_type, label, made_by, cents, created_at, read_at)
206 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)`,
207 );
208 for (const t of read.things) {
209 const j = verdict.get(`${t.kind}:${t.id}`);
210 const mine = j === undefined ? t.label !== "" : j.verdict === "forge";
211 thing.run(
212 provider,
213 account,
214 `${t.kind}:${t.id}`,
215 t.project,
216 t.kind,
217 t.name,
218 t.datacenter,
219 t.size,
220 t.label,
221 mine ? "forge" : "found",
222 j?.cents ?? -1,
223 t.createdAt,
224 at,
225 );
226 }
227 })();
228 return { projects: read.projects.length, resources: read.things.length };
229 }
230
231 export interface ProjectView extends CloudProject {
232 readonly resources: readonly CloudResource[];
233 /** What it all costs a month, cents, from the priced things. */
234 readonly monthlyCents: number;
235 /** Things the catalog cannot price. */
236 readonly unpriced: number;
237 readonly readAt: string;
238 }
239
240 /** Every project kept, each account's in name order, its resources the forge's first ("forge" sorts before "found"). */
241 export function projectsOf(db: Database): ProjectView[] {
242 const projects = db
243 .query<
244 { cloud_provider: string; cloud_account_id: string; cloud_project_id: string; name: string; is_default: number; read_at: string },
245 []
246 >("SELECT * FROM cloud_project ORDER BY cloud_provider, cloud_account_id, is_default DESC, name")
247 .all();
248 const resources = db
249 .query<
250 {
251 cloud_provider: string;
252 cloud_account_id: string;
253 cloud_resource_id: string;
254 cloud_project_id: string;
255 kind: ResourceKind;
256 name: string;
257 cloud_region: string;
258 host_type: string;
259 label: string;
260 made_by: "forge" | "found";
261 cents: number;
262 created_at: string;
263 },
264 []
265 >("SELECT * FROM cloud_resource ORDER BY made_by, kind, name")
266 .all();
267 return projects.map((p) => {
268 const own = resources
269 .filter(
270 (r) =>
271 r.cloud_provider === p.cloud_provider && r.cloud_account_id === p.cloud_account_id && r.cloud_project_id === p.cloud_project_id,
272 )
273 .map(
274 (r): CloudResource => ({
275 provider: r.cloud_provider,
276 account: r.cloud_account_id,
277 project: r.cloud_project_id,
278 id: r.cloud_resource_id,
279 kind: r.kind,
280 name: r.name,
281 region: r.cloud_region,
282 size: r.host_type,
283 label: r.label,
284 madeBy: r.made_by,
285 cents: r.cents < 0 ? null : r.cents,
286 createdAt: r.created_at,
287 }),
288 );
289 return {
290 provider: p.cloud_provider,
291 account: p.cloud_account_id,
292 id: p.cloud_project_id,
293 name: p.name,
294 isDefault: p.is_default === 1,
295 resources: own,
296 monthlyCents: own.reduce((n, r) => n + (r.cents ?? 0), 0),
297 unpriced: own.filter((r) => r.cents === null).length,
298 readAt: p.read_at,
299 };
300 });
301 }
302
303 /** A project in a line: "digitalocean/main ▸ forges: 3 made by the forge, 1 found (do-test), $26.00 a month". */
304 export function projectLine(p: ProjectView, most = 3): string {
305 const found = p.resources.filter((r) => r.madeBy === "found");
306 const named = found.slice(0, most).map((r) => r.name || r.id);
307 const strays =
308 found.length === 0
309 ? "nothing found it did not make"
310 : `${found.length} found${named.length > 0 ? ` (${named.join(", ")}${found.length > most ? `, and ${found.length - most} more` : ""})` : ""}`;
311 const made = p.resources.length - found.length;
312 return `${p.provider}/${p.account} ▸ ${p.name}: ${made} made by the forge, ${strays}, ${dollars(p.monthlyCents)} a month${p.unpriced > 0 ? ` (${p.unpriced} unpriced)` : ""}`;
313 }
314
315 /** Every project in one paragraph, at most `most` named: what the MCP list says first. */
316 export function projectsSays(all: readonly ProjectView[], most = 10): string {
317 if (all.length === 0) return "No cloud project read yet: they are read every 5 minutes from each account that may write.";
318 const shown = all.slice(0, most).map((p) => projectLine(p));
319 return `${shown.join(". ")}${all.length > most ? `. And ${all.length - most} more projects` : ""}.`;
320 }
321
322 /**
323 * Read every account of a project cloud into its projects, each with its sealed key through
324 * `gatedFetch` (every GET audited under `purpose`). An account whose key cannot be opened, or
325 * whose read fails, keeps its last read and is named in the answer.
326 */
327 export async function refreshProjects(
328 db: Database,
329 open: (secret: string) => string | undefined,
330 fetchFor: (provider: string, account: string) => Fetch,
331 now = new Date(),
332 ): Promise<{ read: string[]; failed: string[] }> {
333 const read: string[] = [];
334 const failed: string[] = [];
335 for (const a of listCloudAccounts(db)) {
336 if (!(PROJECT_CLOUDS as readonly string[]).includes(a.provider)) continue;
337 const who = `${a.provider}/${a.name}`;
338 const token = open(secretNameOf(a.provider, a.name));
339 if (token === undefined) {
340 failed.push(`${who}: its key could not be opened`);
341 continue;
342 }
343 try {
344 await readProjects(db, a.provider, a.name, fetchFor(a.provider, a.name), token, now);
345 read.push(who);
346 } catch (e) {
347 failed.push(`${who}: ${e instanceof Error ? e.message.slice(0, 200) : "the read failed"}`);
348 }
349 }
350 return { read, failed };
351 }
src/cloud/watch.ts +3 −2
@@ -37,9 +37,10 @@ export const GRACE_MS = 2 * 3_600_000;
3737 * body (markdown) and a notification, so only plain characters stay and the rest becomes `?`.
3838 */
3939 export const plain = (s: string, max = 120): string => s.slice(0, max).replace(/[^A-Za-z0-9 ._:/()+-]/g, "?");
40 const text = (v: unknown, max = 120): string => (typeof v === "string" || typeof v === "number" ? plain(String(v), max) : "");
40 export const text = (v: unknown, max = 120): string => (typeof v === "string" || typeof v === "number" ? plain(String(v), max) : "");
4141
42 async function pages(f: Fetch, token: string, base: string, key: string, per: number): Promise<any[]> {
42 /** Every page of a provider's list, `per` a page, at most `MAX_PAGES`; throws on any failed read. */
43 export async function pages(f: Fetch, token: string, base: string, key: string, per: number): Promise<any[]> {
4344 const out: any[] = [];
4445 for (let page = 1; page <= MAX_PAGES; page++) {
4546 const res = await f(`${base}${base.includes("?") ? "&" : "?"}per_page=${per}&page=${page}`, { headers: { authorization: `Bearer ${token}` } });
src/core/account_purge.ts +1
@@ -56,6 +56,7 @@ export const COVERED: Readonly<Record<string, Coverage>> = {
5656 "allocation_entry.actor_id": FORMER,
5757 "allocation_weekly.set_by": FORMER,
5858 "cloud_watch_ack.by": FORMER,
59 "cloud_resource.made_by": { do: "none", why: "who made a thing at a cloud provider: \"forge\" or \"found\", never an account" },
5960 "config_change.by": FORMER,
6061 "crew_device.added_by": FORMER,
6162 "crew_device.granted_by": FORMER,
src/core/empty_words.ts +1
@@ -99,6 +99,7 @@ const TABLE = {
9999 gameBoxes: { sentence: "Nothing runs here yet.", reason: "A game box is a machine on your cloud running a compose project; an admin makes one from Infra." },
100100 gameServices: { sentence: "Nothing has reported yet.", reason: "The box shows its services once its agent first syncs." },
101101 gamePlugins: { sentence: "Nothing is installed.", reason: "Add a URL, a Modrinth project or a jar below." },
102 cloudProjects: { sentence: "Nothing read yet.", reason: "Each DigitalOcean and Hetzner account is read into its projects every 5 minutes; Read now reads them at once." },
102103 } as const satisfies Readonly<Record<string, EmptyWords>>;
103104
104105 export type EmptyKind = keyof typeof TABLE;
src/core/migration-pins/20261201200000-cloud-projects.pin added +1
@@ -0,0 +1,1 @@
1 c2a97c62624166b9c09999d68544fc0969eb28c3a843edacb6e413313eb50665
src/core/migrations/20261201200000-cloud-projects.ts added +34
@@ -0,0 +1,34 @@
1 // Every cloud as one model (#17151, V3): provider ▸ account ▸ project ▸ resource, columns named for
2 // the OpenTelemetry `cloud.*` and `host.*` attributes (cloud.provider, cloud.account.id,
3 // cloud.region, cloud.resource_id, host.type). A DigitalOcean account has many projects; a Hetzner
4 // token is one project, named by the label the forge keeps. `made_by` is `forge` for what the
5 // forge's rows made and `found` for the rest; `cents` the list price a month, -1 when there is none.
6 // Replaced whole for an account at each read (every 5 minutes, and on demand). Additive: two tables.
7 export default `
8 CREATE TABLE cloud_project (
9 cloud_provider TEXT NOT NULL,
10 cloud_account_id TEXT NOT NULL,
11 cloud_project_id TEXT NOT NULL,
12 name TEXT NOT NULL,
13 is_default INTEGER NOT NULL DEFAULT 0,
14 read_at TEXT NOT NULL,
15 PRIMARY KEY (cloud_provider, cloud_account_id, cloud_project_id)
16 ) WITHOUT ROWID;
17 CREATE TABLE cloud_resource (
18 cloud_provider TEXT NOT NULL,
19 cloud_account_id TEXT NOT NULL,
20 cloud_resource_id TEXT NOT NULL,
21 cloud_project_id TEXT NOT NULL,
22 kind TEXT NOT NULL,
23 name TEXT NOT NULL,
24 cloud_region TEXT NOT NULL DEFAULT '',
25 host_type TEXT NOT NULL DEFAULT '',
26 label TEXT NOT NULL DEFAULT '',
27 made_by TEXT NOT NULL,
28 cents INTEGER NOT NULL DEFAULT -1,
29 created_at TEXT NOT NULL DEFAULT '',
30 read_at TEXT NOT NULL,
31 PRIMARY KEY (cloud_provider, cloud_account_id, cloud_resource_id)
32 ) WITHOUT ROWID;
33 CREATE INDEX cloud_resource_project ON cloud_resource (cloud_provider, cloud_account_id, cloud_project_id);
34 `;
src/generated/duties.ts +1
@@ -10,6 +10,7 @@ export const DUTY_MODULES: readonly (readonly [string, () => { duty?: unknown }]
1010 ["backup_age.ts", () => require("../maintain/duties/backup_age.ts")],
1111 ["backup_growth.ts", () => require("../maintain/duties/backup_growth.ts")],
1212 ["chapter_stall.ts", () => require("../maintain/duties/chapter_stall.ts")],
13 ["cloud_projects.ts", () => require("../maintain/duties/cloud_projects.ts")],
1314 ["cloud_watch.ts", () => require("../maintain/duties/cloud_watch.ts")],
1415 ["daily_proof.ts", () => require("../maintain/duties/daily_proof.ts")],
1516 ["dead_doc_paths.ts", () => require("../maintain/duties/dead_doc_paths.ts")],
src/generated/migrations.ts +2
@@ -457,6 +457,7 @@ import m452 from "../core/migrations/20261201170000-managed-database.ts";
457457 import m453 from "../core/migrations/20261201180000-game-box-diag.ts";
458458 import m454 from "../core/migrations/20261201190000-working-edit.ts";
459459 import m455 from "../core/migrations/20261201190500-runner-machine.ts";
460 import m456 from "../core/migrations/20261201200000-cloud-projects.ts";
460461
461462 /** Each migration file's name and its default export, in name order. */
462463 export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
@@ -916,4 +917,5 @@ export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
916917 ["20261201180000-game-box-diag.ts", m453],
917918 ["20261201190000-working-edit.ts", m454],
918919 ["20261201190500-runner-machine.ts", m455],
920 ["20261201200000-cloud-projects.ts", m456],
919921 ];
src/http/infra_routes.ts +21 −2
@@ -5,7 +5,7 @@
55 */
66
77 import { infraCode } from "../cloud/infra_read.ts";
8 import { buildOf, machineOf, type ComposeChoices, composeChoices, domainOf, infraOf, nameFor, planCompose, planRecord, rebuild, recordAccounts, startBuild } from "../actions/infra.ts";
8 import { buildOf, machineOf, projectsView, readProjectsNow, type ComposeChoices, composeChoices, domainOf, infraOf, nameFor, planCompose, planRecord, rebuild, recordAccounts, startBuild } from "../actions/infra.ts";
99 import { dropRecord } from "../actions/dns_record.ts";
1010 import { deleteSnapshot, endWithSnapshot, restoreSnapshot } from "../actions/infra_snapshot.ts";
1111 import { clearPinned, endsWords, keepPinned, retirePinned, retireWords } from "../actions/pinned.ts";
@@ -68,7 +68,8 @@ async function render(
6868 compose = composeForm(choices, state, planTray(planned.value), domainOf(ctx.app));
6969 }
7070 const code = await infraCode(ctx.app, user);
71 const body = infraPage(view.value, compose, build, { composing: o.composing, code: code.ok ? code.value : [], records: recordForm(recordAccounts(ctx.app)) });
71 const projects = timePhase(ctx.request, "projects", () => projectsView(ctx.app, user));
72 const body = infraPage(view.value, compose, build, { composing: o.composing, code: code.ok ? code.value : [], records: recordForm(recordAccounts(ctx.app)), projects: projects.ok ? projects.value : [] });
7273 return page({ ctx, title: "Infrastructure", scriptJs: SCRIPT, styleCss: INFRA_CSS, body, ...(o.flash ? { flash: o.flash } : {}) }, status);
7374 }
7475
@@ -176,6 +177,23 @@ async function infraRebuild(ctx: Ctx): Promise<Response> {
176177 : flashTo(ctx, "/infra", { tone: "danger", message: again.error });
177178 }
178179
180 // POST /infra/projects: read every account into its projects now (GETs only), then back to them.
181 async function infraProjects(ctx: Ctx): Promise<Response> {
182 const denied = guard(ctx);
183 if (denied) return denied;
184 const form = await readForm(ctx, "admin");
185 if (form instanceof Response) return form;
186 const done = await readProjectsNow(ctx.app, ctx.auth.user);
187 if (!done.ok) return notFoundPage(ctx);
188 return flashTo(
189 ctx,
190 "/infra#projects",
191 done.value.failed.length === 0
192 ? { message: done.value.read.length === 0 ? "No DigitalOcean or Hetzner account to read." : `Read ${done.value.read.join(", ")}.` }
193 : { tone: "danger", message: `Not read: ${done.value.failed.join("; ")}` },
194 );
195 }
196
179197 // POST /infra/:name/keep and /infra/:name/end (End now arrives from the confirm page).
180198 async function infraMachine(ctx: Ctx): Promise<Response> {
181199 const denied = guard(ctx);
@@ -254,6 +272,7 @@ export function infraRoutes(router: Router<Handler>): void {
254272 router.add("POST", "/infra/apply", infraApply);
255273 router.add("POST", "/infra/record", infraRecord);
256274 router.add("POST", "/infra/rebuild", infraRebuild);
275 router.add("POST", "/infra/projects", infraProjects);
257276 router.add("GET", "/infra/:name/ending", infraEnding);
258277 router.add("POST", "/infra/snapshot/:id/:act", infraSnapshot);
259278 router.add("POST", "/infra/:name/:act", infraMachine);
src/http/lazy_lists.ts +1
@@ -593,6 +593,7 @@ export const OPERATIONS_ROUTES = [
593593 ["POST", "/infra/apply"],
594594 ["POST", "/infra/record"],
595595 ["POST", "/infra/rebuild"],
596 ["POST", "/infra/projects"],
596597 ["GET", "/infra/:name/ending"],
597598 ["POST", "/infra/snapshot/:id/:act"],
598599 ["POST", "/infra/:name/:act"],
src/http/mcp/tools/infra.ts +19 −1
@@ -1,4 +1,5 @@
11 import { infraCode } from "../../../cloud/infra_read.ts";
2 import { projectsOf, projectsSays } from "../../../cloud/projects.ts";
23 import { buildOf, firewallWant, gameWant, planDatabase, goneWords, infraOf, infraSays, machineOf, nameFor, planById, planCompose, planWants, startBuild } from "../../../actions/infra.ts";
34 import { bindBucket, readBucket } from "../../../actions/bucket.ts";
45 import { endsWords, keepPinned } from "../../../actions/pinned.ts";
@@ -47,7 +48,24 @@ export const tool: Tool = {
4748 if (!v.ok) return bad("not_found", "no such tool here");
4849 const { experiments, ...rest } = v.value;
4950 // One paragraph that names every machine first, so a reader of the groups alone misses nothing.
50 return good({ says: infraSays(v.value), ...experiments, ...rest });
51 // Account ▸ project, bounded: ten projects, five strays named each, and one line for them all.
52 const all = projectsOf(ctx.app.db);
53 const projects = {
54 says: projectsSays(all),
55 items: all.slice(0, 10).map((p) => {
56 const found = p.resources.filter((r) => r.madeBy === "found");
57 return {
58 account: `${p.provider}/${p.account}`,
59 project: p.name,
60 monthlyCents: p.monthlyCents,
61 madeByForge: p.resources.length - found.length,
62 found: found.length,
63 strays: found.slice(0, 5).map((r) => `${r.kind} ${r.name || r.id}`),
64 readAt: p.readAt,
65 };
66 }),
67 };
68 return good({ says: infraSays(v.value), ...experiments, ...rest, projects });
5169 }
5270 if (action === "check") {
5371 // Compare the DNS records the forge made with Cloudflare now, as the hourly watch does.
src/maintain/duties/cloud_projects.ts added +31
@@ -0,0 +1,31 @@
1 /**
2 * Cloud projects (#17151, V3): every five minutes, read each DigitalOcean and Hetzner account into
3 * its projects and resources (`cloud/projects.ts`), with GETs alone through the audited fetch and
4 * the sealed keys, so /infra, the terminal and the `infra` tool group what runs by account ▸
5 * project and name what the forge did not make. An account that cannot be read is a finding.
6 */
7
8 import { net } from "../../actions/pinned.ts";
9 import { gatedFetch } from "../../cloud/gate.ts";
10 import { refreshProjects } from "../../cloud/projects.ts";
11 import { resolveSecrets } from "../../core/secret_store.ts";
12 import type { Duty } from "../duty.ts";
13
14 export const duty: Duty = {
15 name: "cloud-projects",
16 intervalMs: 5 * 60_000,
17 budget: { runsPerDay: 300, dollarsPerDay: 1, reason: "every 5 minutes is 288 a day; it makes only read calls that cost no money" },
18 async run({ db, bus, now, app }) {
19 if (app === undefined) return { findings: [], actions: [] };
20 const done = await refreshProjects(
21 db,
22 (secret) => resolveSecrets(db, app.config.dataDir, bus, [secret], { run: "maintain:cloud-projects" })[secret],
23 (provider, account) => gatedFetch(db, { provider, account }, "maintain:cloud-projects", net.fetch),
24 now,
25 );
26 return {
27 findings: done.failed.map((summary) => ({ summary, probe: { kind: "measurement" as const, what: "cloud accounts not read into projects", number: done.failed.length, at: now.toISOString() } })),
28 actions: done.read.length === 0 ? [] : [`read ${done.read.join(", ")} into projects`],
29 };
30 },
31 };
src/tui/screens/infra.ts +20 −1
@@ -14,7 +14,7 @@
1414
1515 import { dropRecord, lookAtRecords, lookWords } from "../../actions/dns_record.ts";
1616 import { infraCode, type CodeFile } from "../../cloud/infra_read.ts";
17 import { buildOf, composeChoices, databaseChoices, infraOf, nameFor, planCompose, planDatabase, planRecord, recordAccounts, startBuild, type Compose, type Planned, type Running } from "../../actions/infra.ts";
17 import { buildOf, composeChoices, databaseChoices, infraOf, projectsView, readProjectsNow, nameFor, planCompose, planDatabase, planRecord, recordAccounts, startBuild, type Compose, type Planned, type Running } from "../../actions/infra.ts";
1818 import { deleteSnapshot, endWithSnapshot, restoredName, restoreSnapshot } from "../../actions/infra_snapshot.ts";
1919 import { LIFETIME_DAYS, clearPinned, endsWords, keepPinned, retirePinned, retireWords } from "../../actions/pinned.ts";
2020 import type { SnapshotView } from "../../actions/infra_snapshot.ts";
@@ -282,6 +282,7 @@ export function infraScreen(f: Session, ctx: Ctx): Screen {
282282 binding(["u"], "remove the selected DNS record"),
283283 binding(["r"], "restore a snapshot"),
284284 binding(["d"], "delete a snapshot"),
285 binding(["P"], "read cloud projects now"),
285286 ],
286287 async load(signal) {
287288 live(
@@ -365,6 +366,17 @@ export function infraScreen(f: Session, ctx: Ctx): Screen {
365366 ];
366367 rows.push(...v.value.snapshots.map((x) => ({ title: `snapshot: ${x.name} · ${x.state === "ready" && x.cents > 0 ? month(x.cents) : x.state}`, secondary: x.says, meta: `${x.target}/${x.account}` })));
367368 if (v.value.snapshotsHidden > 0) rows.push({ title: `${v.value.snapshotsHidden} older snapshots are not listed: only the newest 200 are shown`, meta: "" });
369 // Account ▸ project (#17151): each project, what it costs, and what the forge did not make, by name.
370 const projects = projectsView(f.app, f.user);
371 for (const p of projects.ok ? projects.value : []) {
372 const found = p.resources.filter((r) => r.madeBy === "found");
373 rows.push({
374 title: `${p.provider}/${p.account} ▸ ${p.name} · ${month(p.monthlyCents)}`,
375 secondary: `${p.resources.length - found.length} made by the forge · ${found.length === 0 ? "nothing found it did not make" : `found: ${found.map((r) => `${r.kind} ${r.name || r.id}`).join(", ")}`}`,
376 ...(found.length > 0 ? { tone: "attn" as const } : {}),
377 meta: "project",
378 });
379 }
368380 if (rows.length === 0 && progress.length === 0)
369381 rows.push({ title: "Nothing runs on your own cloud yet. Press n to build something, b for a database.", meta: "" });
370382 drawList(s, list!, c, state, [...progress, ...rows]);
@@ -407,6 +419,13 @@ export function infraScreen(f: Session, ctx: Ctx): Screen {
407419 );
408420 return true;
409421 }
422 if (e.key === "P") {
423 say("Reading every DigitalOcean and Hetzner account into its projects…");
424 void readProjectsNow(f.app, f.user).then((done) =>
425 say(!done.ok ? "Infrastructure is a forge admin's." : done.value.failed.length > 0 ? `Not read: ${done.value.failed.join("; ")}` : `Read ${done.value.read.join(", ") || "no account"}.`),
426 );
427 return true;
428 }
410429 // A snapshot row: restore it as a new forge, or delete it.
411430 const snap = tail.snapshots[state.index - progress - drift - all.length - tail.ended - records];
412431 if (e.key === "r" || e.key === "d") {
src/web/pages/infra.ts +57 −1
@@ -12,10 +12,12 @@
1212 */
1313
1414 import { LIFETIME_DAYS } from "../../actions/pinned.ts";
15 import { emptyLine } from "../empty_words.ts";
1516 import type { CodeFile } from "../../cloud/infra_read.ts";
1617 import { restoredName, type SnapshotView } from "../../actions/infra_snapshot.ts";
1718 import { ENDED_DAYS, type RecordFields, type Build, type ComposeChoices, type InfraView, type Planned, type Running } from "../../actions/infra.ts";
1819 import { dollars } from "../../cloud/prices.ts";
20 import { type CloudResource, type ProjectView } from "../../cloud/projects.ts";
1921 import { pageHead } from "../chrome.ts";
2022 import { html, raw, type Html } from "../html.ts";
2123 import { icon } from "../icons.ts";
@@ -515,12 +517,66 @@ export function recordForm(accounts: readonly string[], s: Partial<RecordFields>
515517 </form>`;
516518 }
517519
520 /** The resources a project's row shows beneath it; the rest are counted in one row. */
outdated

Earlier ask, still open: this is infraPage's doc comment, stacked above projectsRegion's. Move it back onto infraPage.

521 export const PROJECT_RESOURCE_ROWS = 10;
522
523 /**
524 * Every cloud project, account ▸ project (#17151): its resources, what they cost a month, and what
525 * the forge made against what it found. A stray is named here and never touched.
526 */
527 export function projectsRegion(projects: readonly ProjectView[]): Html {
528 const thing = (r: CloudResource): Html =>
529 row({
530 title: r.name || r.id,
531 meta: html`${r.kind}${r.region ? ` · ${r.region}` : ""}${r.size ? ` · ${r.size}` : ""} · ${r.cents === null ? "no list price" : `${dollars(r.cents)} a month`} ·
532 ${r.madeBy === "forge" ? `made by the forge${r.label ? ` for ${r.label}` : ""}` : "found: not made by the forge"}`,
533 });
534 return html`<section class="settings-block" id="projects">
535 <h2>Projects</h2>
536 ${projects.length === 0
537 ? emptyLine("cloudProjects")
538 : rowList(
539 projects.map((p) => {
540 const found = p.resources.filter((r) => r.madeBy === "found");
outdated

Earlier ask, still open (principles 1 and 7): this parses the sentence projectLine built, so a name containing ': ' breaks the row, and it is one dense line rather than a dl row. Read the fields from ProjectView, and cap the resource rows beneath.

541 const named = found.slice(0, 3).map((r) => r.name || r.id);
542 const over = p.resources.length - PROJECT_RESOURCE_ROWS;
543 return row({
544 title: `${p.provider}/${p.account} ▸ ${p.name}`,
545 facts: [
546 { label: "Made by the forge", value: String(p.resources.length - found.length) },
547 {
548 label: "Found",
549 value:
550 found.length === 0
551 ? "nothing it did not make"
552 : `${String(found.length)}: ${named.join(", ")}${found.length > named.length ? `, and ${String(found.length - named.length)} more` : ""}`,
553 },
554 { label: "A month", value: `${dollars(p.monthlyCents)}${p.unpriced > 0 ? `, ${String(p.unpriced)} unpriced` : ""}` },
555 { label: "Read", value: `${p.readAt.slice(11, 16)} UTC` },
556 ],
557 children: [
558 ...p.resources.slice(0, PROJECT_RESOURCE_ROWS).map(thing),
559 ...(over > 0 ? [row({ title: `and ${String(over)} more` })] : []),
560 ],
561 });
562 }),
563 )}
564 <form method="post" action="/infra/projects">${btn("Read now", { variant: "ghost", type: "submit" })}</form>
565 </section>`;
566 }
567
518568 /** The whole page: the head sentence, what runs, then compose (closed once something runs) or a build. */
519 export function infraPage(v: InfraView, compose: Html, build: Build | undefined, s: { composing: boolean; records?: Html; code?: readonly CodeFile[] }): Html {
569 export function infraPage(
570 v: InfraView,
571 compose: Html,
572 build: Build | undefined,
573 s: { composing: boolean; records?: Html; code?: readonly CodeFile[]; projects?: readonly ProjectView[] },
574 ): Html {
520575 const open = s.composing || v.groups.length === 0;
521576 return html`${pageHead("Infrastructure", { sub: "What runs on your own cloud, what it's for, what it costs, and when it ends." })}
522577 <div data-infra>
523578 ${runningRegion(v)}
579 ${projectsRegion(s.projects ?? [])}
524580 ${codeRegion(s.code ?? [])}
525581 ${build !== undefined
526582 ? buildTray(build)
test/cloud-projects.test.ts added +309
@@ -0,0 +1,309 @@
1 /**
2 * Every cloud as one model (#17151, V3): DigitalOcean's projects and their resources (URNs joined
3 * with droplets and volumes), and a Hetzner token's one project, read with GETs alone from recorded
4 * answers into provider ▸ account ▸ project ▸ resource; what the forge made against what it found;
5 * a stray named and never touched; and the doors: /infra's Projects, the terminal's Infra and the
6 * `infra list` tool's `projects` with its `says`.
7 */
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtempSync } from "node:fs";
10 import { rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { createApp, type App } from "../src/app.ts";
14 import { projectLine, projectsOf, projectsSays, readProjects, refreshProjects } from "../src/cloud/projects.ts";
15 import { secretNameOf } from "../src/core/cloud_account.ts";
16 import { insertPinned, setRemote } from "../src/core/pinned.ts";
17 import { createSession } from "../src/core/sessions.ts";
18 import { createToken } from "../src/core/tokens.ts";
19 import { createUser, type User } from "../src/core/users.ts";
20 import { serve, type Servers } from "../src/http/server.ts";
21 import { createForgeApp } from "../src/tui/forge.ts";
22 import { infraScreen } from "../src/tui/screens/infra.ts";
23 import { PROJECT_RESOURCE_ROWS, projectsRegion } from "../src/web/pages/infra.ts";
24 import { headlessTerminal } from "../src/tui/term/terminal.ts";
25 import { mcpTool } from "./helpers/mcp.ts";
26 import { seedPlaces } from "./helpers/places-fixture.ts";
27 import { settleApp } from "./helpers/tui.ts";
28
29 /** What DigitalOcean answered: two projects, a droplet and a volume the forge made, a website droplet, and one in no project's list. */
30 const DO: Record<string, unknown> = {
31 "/v2/projects": {
32 projects: [
33 { id: "p-forges", name: "forges", is_default: true },
34 { id: "p-site", name: "website", is_default: false },
35 ],
36 },
37 "/v2/projects/p-forges/resources": { resources: [{ urn: "do:droplet:111" }, { urn: "do:volume:vol-a" }] },
38 "/v2/projects/p-site/resources": { resources: [{ urn: "do:droplet:222" }] },
39 "/v2/droplets": {
40 droplets: [
41 {
42 id: 111,
43 name: "forge-mc",
44 created_at: "2026-11-30T06:00:00Z",
45 region: { slug: "nyc3" },
46 size_slug: "s-1vcpu-2gb",
47 tags: ["forge-pinned", "forge:mc"],
48 },
49 { id: 222, name: "web-1", created_at: "2025-01-01T00:00:00Z", region: { slug: "nyc3" }, size_slug: "s-1vcpu-2gb", tags: [] },
50 { id: 333, name: "old-test", created_at: "2025-01-01T00:00:00Z", region: { slug: "ams3" }, size_slug: "s-1vcpu-2gb", tags: [] },
51 ],
52 },
53 "/v2/volumes": {
54 volumes: [
55 {
56 id: "vol-a",
57 name: "forge-mc-data",
58 created_at: "2026-11-30T06:00:00Z",
59 region: { slug: "nyc3" },
60 size_gigabytes: 10,
61 tags: ["forge:mc"],
62 },
63 ],
64 },
65 };
66 /** What Hetzner answered: a server, its volume and a primary IP labelled for a forge, a firewall made by hand. */
67 const HZ: Record<string, unknown> = {
68 "/v1/servers": {
69 servers: [
70 {
71 id: 9,
72 name: "forge-box",
73 created: "2026-11-30T06:00:00Z",
74 datacenter: { location: { name: "nbg1" } },
75 server_type: { name: "cx23" },
76 labels: { forge: "box", "forge-pinned": "true" },
77 },
78 ],
79 },
80 "/v1/volumes": {
81 volumes: [
82 { id: 9, name: "forge-box-data", created: "2026-11-30T06:00:00Z", location: { name: "nbg1" }, size: 10, labels: { forge: "box" } },
83 ],
84 },
85 "/v1/firewalls": { firewalls: [{ id: 4, name: "office", created: "2025-01-01T00:00:00Z", labels: {} }] },
86 "/v1/primary_ips": {
87 primary_ips: [
88 {
89 id: 5,
90 name: "primary_ip-5",
91 created: "2026-11-30T06:00:00Z",
92 type: "ipv4",
93 datacenter: { location: { name: "nbg1" } },
94 labels: { forge: "box" },
95 },
96 ],
97 },
98 };
99
100 /** A fetch that answers from a recording, and keeps every call's method and path. */
101 function recorded(answers: Record<string, unknown>, calls: string[]) {
102 return async (url: string | URL | Request, init?: RequestInit): Promise<Response> => {
103 const u = new URL(String(url));
104 calls.push(`${init?.method ?? "GET"} ${u.pathname}`);
105 const body = answers[u.pathname];
106 // One page each: the reader stops when a page is shorter than asked.
107 return body === undefined ? new Response("{}", { status: 404 }) : Response.json(body);
108 };
109 }
110
111 let dir = "";
112 let app: App;
113 let servers: Servers;
114 let alice: User;
115 const calls: string[] = [];
116
117 beforeAll(async () => {
118 dir = mkdtempSync(join(tmpdir(), "forge-cloud-projects-"));
119 app = createApp({ dataDir: dir, port: 0 });
120 servers = await serve(app);
121 const made = await createUser(app.db, {
122 origin: "seed",
123 trusted: true,
124 username: "alice",
125 email: "[email protected]",
126 password: "a-good-passphrase",
127 adminIfFirst: true,
128 });
129 if (!made.ok) throw new Error(made.error);
130 alice = made.value;
131 await seedPlaces(app.db);
132 app.db.run("INSERT INTO cloud_account (provider, name, summary, write_allowed) VALUES ('digitalocean', 'main', '', 1)");
133 app.db.run("INSERT INTO cloud_account (provider, name, summary, write_allowed, project) VALUES ('hetzner', 'eu', '', 1, 'games')");
134 for (const [name, target, account, remote, volume, datacenter, size] of [
135 ["mc", "digitalocean", "main", "111", "vol-a", "nyc3", "s-1vcpu-2gb"],
136 ["box", "hetzner", "eu", "9", "9", "nbg1", "cx23"],
137 ] as const) {
138 insertPinned(
139 app.db,
140 {
141 name,
142 target,
143 account,
144 app: "",
145 source: "",
146 version: "v1",
147 config: {},
148 host: "",
149 claimHash: "",
150 claimExpires: "",
151 datacenter,
152 size,
153 },
154 alice.id,
155 );
156 setRemote(app.db, name, { remote, volume, state: "running" });
157 }
158 await readProjects(app.db, "digitalocean", "main", recorded(DO, calls), "t", new Date("2026-12-01T12:00:00Z"));
159 await readProjects(app.db, "hetzner", "eu", recorded(HZ, calls), "t", new Date("2026-12-01T12:00:00Z"));
160 });
161
162 afterAll(async () => {
163 servers.stop();
164 app.close();
165 await rm(dir, { recursive: true, force: true });
166 });
167
168 describe("reading", () => {
169 test("GETs only", () => {
170 expect(calls.length).toBeGreaterThan(0);
171 expect(calls.every((c) => c.startsWith("GET "))).toBe(true);
172 expect(calls).toContain("GET /v2/projects/p-forges/resources");
173 expect(calls).toContain("GET /v1/primary_ips");
174 });
175
176 test("DigitalOcean: each project with its resources; one in no project's list is the default's; the forge's against what it found", () => {
177 const all = projectsOf(app.db);
178 const forges = all.find((p) => p.provider === "digitalocean" && p.name === "forges")!;
179 const site = all.find((p) => p.name === "website")!;
180 expect(forges.isDefault).toBe(true);
181 expect(forges.resources.map((r) => [r.id, r.madeBy, r.label])).toEqual([
182 ["machine:111", "forge", "mc"],
183 ["volume:vol-a", "forge", "mc"],
184 ["machine:333", "found", ""],
185 ]);
186 expect(site.resources.map((r) => [r.name, r.madeBy, r.region])).toEqual([["web-1", "found", "nyc3"]]);
187 // Priced from the catalog: the droplet less its volume, the volume, each a month.
188 expect(forges.monthlyCents).toBeGreaterThan(0);
189 expect(projectLine(site)).toBe(
190 `digitalocean/main ▸ website: 0 made by the forge, 1 found (web-1), $${(site.monthlyCents / 100).toFixed(2)} a month`,
191 );
192 });
193
194 test("Hetzner: one token is one project, named by the forge's label; grouped by the forge label; a hand-made firewall is found", () => {
195 const games = projectsOf(app.db).find((p) => p.provider === "hetzner")!;
196 expect(games).toMatchObject({ account: "eu", id: "games", name: "games", isDefault: true });
197 expect(games.resources.map((r) => [r.kind, r.name, r.madeBy, r.label])).toEqual([
198 ["address", "primary_ip-5", "forge", "box"],
199 ["machine", "forge-box", "forge", "box"],
200 ["volume", "forge-box-data", "forge", "box"],
201 ["firewall", "office", "found", ""],
202 ]);
203 // A primary IP has no catalog price: counted, never guessed.
204 expect(games.unpriced).toBe(1);
205 });
206
207 test("a read that fails keeps the last one and is named; an unopened key is named too", async () => {
208 const done = await refreshProjects(
209 app.db,
210 (secret) => (secret === secretNameOf("hetzner", "eu") ? undefined : "t"),
211 () => async () => new Response("no", { status: 401 }),
212 );
213 expect(done.read).toEqual([]);
214 expect(done.failed).toEqual([
215 "digitalocean/main: api.digitalocean.com answered 401 to projects",
216 "hetzner/eu: its key could not be opened",
217 ]);
218 expect(projectsOf(app.db).filter((p) => p.provider === "digitalocean")).toHaveLength(2);
219 });
220
221 test("the paragraph names every project, ten at most", () => {
222 const all = projectsOf(app.db);
223 expect(projectsSays(all)).toContain("digitalocean/main ▸ forges: 2 made by the forge, 1 found (old-test)");
224 expect(projectsSays([...all, ...all, ...all, ...all])).toEndWith("And 2 more projects.");
225 expect(projectsSays([])).toStartWith("No cloud project read yet");
226 });
227 });
228
229 describe("the doors", () => {
230 test("/infra groups by account ▸ project, with each project's resources and strays named", async () => {
231 const page = await (
232 await fetch(`${servers.url}/infra`, { headers: { cookie: `forge_session=${createSession(app.db, alice.id).token}` } })
233 ).text();
234 expect(page).toContain('id="projects"');
235 expect(page).toContain("digitalocean/main ▸ website");
236 expect(page).toContain("hetzner/eu ▸ games");
237 expect(page).toContain("found: not made by the forge");
238 expect(page).toContain('action="/infra/projects"');
239 });
240
241 test("a project's row reads its fields, not a sentence: a name with ': ' keeps its facts, and its resources are capped", () => {
242 const thing = (i: number, madeBy: "forge" | "found") => ({
243 provider: "digitalocean",
244 account: "main",
245 project: "p1",
246 id: `machine:${String(i)}`,
247 kind: "machine" as const,
248 name: `box-${String(i)}`,
249 region: "nyc1",
250 size: "s-1vcpu-1gb",
251 label: "",
252 madeBy,
253 cents: 600,
254 createdAt: "2026-12-01T00:00:00Z",
255 });
256 const resources = Array.from({ length: PROJECT_RESOURCE_ROWS + 2 }, (_, i) => thing(i, i < 2 ? "found" : "forge"));
257 const html = String(
258 projectsRegion([
259 {
260 provider: "digitalocean",
261 account: "main",
262 id: "p1",
263 name: "a: b",
264 isDefault: false,
265 resources,
266 monthlyCents: 600 * resources.length,
267 unpriced: 0,
268 readAt: "2026-12-01T17:42:00Z",
269 },
270 ]),
271 );
272 expect(html).toContain("digitalocean/main ▸ a: b");
273 expect(html).toContain("<dt>Made by the forge</dt><dd>10</dd>");
274 expect(html).toContain("<dt>Found</dt><dd>2: box-0, box-1</dd>");
275 expect(html).toContain("<dt>A month</dt><dd>$72.00</dd>");
276 expect(html).toContain("<dt>Read</dt><dd>17:42 UTC</dd>");
277 expect(html).toContain(`box-${String(PROJECT_RESOURCE_ROWS - 1)}`);
278 expect(html).not.toContain(`box-${String(PROJECT_RESOURCE_ROWS)}<`);
279 expect(html).toContain("and 2 more");
280 });
281
282 test("infra list carries projects, bounded, with a says line", async () => {
283 const token = createToken(app.db, alice.id, "admin", "admin").token;
284 const listed = await mcpTool(servers.url, token, "infra", { action: "list" });
285 expect(listed.value.projects.says).toContain("hetzner/eu ▸ games: 3 made by the forge, 1 found (office)");
286 expect(listed.value.projects.items.find((p: { project: string }) => p.project === "website")).toMatchObject({
287 account: "digitalocean/main",
288 madeByForge: 0,
289 found: 1,
290 strays: ["machine web-1"],
291 });
292 });
293
294 test("the terminal's Infra lists each project with what it did not make", async () => {
295 const terminal = headlessTerminal(160, 40);
296 const { app: tui, session } = createForgeApp(
297 app,
298 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice },
299 { terminal, exitHooks: false },
300 );
301 tui.start();
302 tui.ctx.push(infraScreen(session, tui.ctx));
303 await settleApp(tui);
304 const text = tui.screen.toText();
305 tui.stop?.();
306 expect(text).toContain("digitalocean/main ▸ website");
307 expect(text).toContain("found: machine web-1");
308 });
309 });

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

Keyboard shortcuts

Docs