@oona/vlo 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,1540 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, realpathSync, statSync } from "node:fs";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
+ import { parseArgs } from "node:util";
5
+ import { glob, mkdir, stat, writeFile } from "node:fs/promises";
6
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
7
+ import { i as isEnvRef, t as DEFAULT_CONFIG } from "./define-DwM_Qhbw.js";
8
+ import { $ as loadKernel, et as openJournal, nt as openBlobStore, s as serve } from "./roles-D25bG980.js";
9
+ import { y as sha256Hex } from "./domain-Bs8TeDCv.js";
10
+ // src/config/load.ts
11
+ /**
12
+ * Loading `vlo.config.ts` and the modules it points at.
13
+ *
14
+ * The config is imported, not parsed: Node 24 strips TypeScript types natively, so a `.ts`
15
+ * config runs with no build step. The limitation that buys us — and it is the reason this
16
+ * is a load step and not a bundler — is that the config file itself may only use relative
17
+ * imports with explicit extensions. Path aliases and extensionless specifiers are not supported yet.
18
+ */
19
+ const CONFIG_NAMES = [
20
+ "vlo.config.ts",
21
+ "vlo.config.js",
22
+ "vlo.config.mjs"
23
+ ];
24
+ /**
25
+ * Finds and imports the config, picks a profile, resolves `env()` references and imports
26
+ * every module the globs match. Relative `sqlite://` and `file://` URLs in the profile are
27
+ * made absolute against the config directory, so they mean the same thing from any `cwd`.
28
+ */
29
+ async function loadConfig(cwd, profileName, configPath, opts = {}) {
30
+ const found = configPath !== void 0 ? resolve(cwd, configPath) : await findConfig(cwd);
31
+ const config = found === null ? DEFAULT_CONFIG : await importConfig(found);
32
+ const root = found === null ? cwd : dirOf(found);
33
+ const [name, profile] = selectProfile(config.profiles, profileName, opts.implicitProfile === true);
34
+ const modules = await importAll(root, [
35
+ ...patterns(config.workflows),
36
+ ...patterns(config.workers),
37
+ ...patterns(config.activities)
38
+ ]);
39
+ return {
40
+ ...found !== null ? { configPath: found } : {},
41
+ root,
42
+ profile: resolveProfile(name, profile, root),
43
+ workflows: collect(modules, "workflow"),
44
+ workers: collect(modules, "worker"),
45
+ activities: collect(modules, "activity"),
46
+ signals: collect(modules, "signal")
47
+ };
48
+ }
49
+ function selectProfile(profiles, name, implicit) {
50
+ const available = Object.keys(profiles);
51
+ if (name !== void 0) {
52
+ const profile = profiles[name];
53
+ if (profile === void 0) throw new Error(`no profile "${name}" in the config; available: ${available.join(", ")}`);
54
+ return [name, profile];
55
+ }
56
+ const local = profiles["local"];
57
+ if (implicit && local !== void 0) return ["local", local];
58
+ const [sole] = available;
59
+ if (implicit && sole !== void 0 && available.length === 1) return [sole, profiles[sole]];
60
+ throw new Error(`no profile selected; pass --profile; available: ${available.join(", ")}`);
61
+ }
62
+ /**
63
+ * `sqlite://<relative>` and `file://<relative>` become `sqlite://<root>/<relative>` and
64
+ * `file://<root>/<relative>`; `:memory:`, absolute paths (`sqlite:///abs`, `file:///abs`)
65
+ * and every other scheme (`postgres://`, `gcs://`) pass through untouched.
66
+ */
67
+ function absolutize(url, root) {
68
+ const match = /^(sqlite|file):\/\/(.*)$/.exec(url);
69
+ if (match === null) return url;
70
+ const scheme = match[1] ?? "";
71
+ const path = match[2] ?? "";
72
+ if (path.length === 0 || path === ":memory:" || isAbsolute(path)) return url;
73
+ return `${scheme}://${resolve(root, path)}`;
74
+ }
75
+ function resolveProfile(name, profile, root) {
76
+ const queues = {};
77
+ for (const [queue, spec] of Object.entries(profile.queues ?? {})) queues[queue] = {
78
+ ...optional("url", resolveRef(spec.url)),
79
+ ...optional("secret", resolveRef(spec.secret)),
80
+ ...spec.mode !== void 0 ? { mode: spec.mode } : {}
81
+ };
82
+ return {
83
+ name,
84
+ journal: absolutize(required(resolveRef(profile.journal), "journal"), root),
85
+ blob: absolutize(resolveRef(profile.blob) ?? "file://.vlo/blobs", root),
86
+ queues,
87
+ auth: {
88
+ ...optional("token", resolveRef(profile.auth?.token)),
89
+ ...optional("pushSecret", resolveRef(profile.auth?.pushSecret))
90
+ },
91
+ ...optional("publicUrl", resolveRef(profile.publicUrl ?? profile.host)),
92
+ ...profile.port !== void 0 ? { port: profile.port } : {},
93
+ ...profile.roles !== void 0 ? { roles: [...profile.roles] } : {},
94
+ ...profile.dispatcher !== void 0 ? { dispatcher: { ...profile.dispatcher } } : {},
95
+ ...profile.deploy !== void 0 ? { deploy: resolveDeploy(profile.deploy) } : {}
96
+ };
97
+ }
98
+ function resolveDeploy(deploy) {
99
+ return {
100
+ target: deploy.target,
101
+ ...optional("project", resolveRef(deploy.project)),
102
+ ...optional("region", resolveRef(deploy.region)),
103
+ ...optional("namePrefix", resolveRef(deploy.namePrefix)),
104
+ ...optional("service", resolveRef(deploy.service)),
105
+ ...optional("bucket", resolveRef(deploy.bucket)),
106
+ ...deploy.envs !== void 0 ? { envs: [...deploy.envs] } : {},
107
+ ...optional("secretName", resolveRef(deploy.secretName)),
108
+ ...optional("cron", resolveRef(deploy.cron))
109
+ };
110
+ }
111
+ function resolveRef(ref) {
112
+ if (ref === void 0) return void 0;
113
+ if (!isEnvRef(ref)) return ref;
114
+ const value = process.env[ref.__env];
115
+ if (value === void 0 || value.length === 0) {
116
+ if (ref.optional === true) return void 0;
117
+ throw new Error(`the environment variable ${ref.__env} is required by this profile but unset`);
118
+ }
119
+ return value;
120
+ }
121
+ function required(value, field) {
122
+ if (value === void 0) throw new Error(`the profile has no "${field}"`);
123
+ return value;
124
+ }
125
+ function optional(key, value) {
126
+ return value === void 0 ? {} : { [key]: value };
127
+ }
128
+ async function findConfig(cwd) {
129
+ for (const name of CONFIG_NAMES) {
130
+ const candidate = join(cwd, name);
131
+ if (await exists(candidate)) return candidate;
132
+ }
133
+ return null;
134
+ }
135
+ async function exists(path) {
136
+ try {
137
+ await stat(path);
138
+ return true;
139
+ } catch {
140
+ return false;
141
+ }
142
+ }
143
+ async function importConfig(path) {
144
+ const loaded = await import(pathToFileURL(path).href);
145
+ if (loaded.default === void 0) throw new Error(`${path} has no default export; use \`export default defineConfig({ … })\``);
146
+ return loaded.default;
147
+ }
148
+ function patterns(value) {
149
+ if (value === void 0) return [];
150
+ return typeof value === "string" ? [value] : [...value];
151
+ }
152
+ async function importAll(root, globs) {
153
+ const paths = /* @__PURE__ */ new Set();
154
+ for (const pattern of globs) for await (const match of glob(pattern, {
155
+ cwd: root,
156
+ exclude: ["**/node_modules/**"]
157
+ })) paths.add(isAbsolute(match) ? match : join(root, match));
158
+ return Promise.all([...paths].sort().map((path) => import(pathToFileURL(path).href)));
159
+ }
160
+ /**
161
+ * Anything a module exports that carries the right `kind` marker — default export or named,
162
+ * so re-exporting an activity from a workflow file registers it too. Deduped by `name` where
163
+ * there is one (workers have none) and by identity otherwise.
164
+ */
165
+ function collect(modules, kind) {
166
+ const byName = /* @__PURE__ */ new Map();
167
+ const anonymous = /* @__PURE__ */ new Set();
168
+ for (const exports of modules) for (const value of Object.values(exports)) {
169
+ if (!isKind(value, kind)) continue;
170
+ const name = value.name;
171
+ if (typeof name === "string") {
172
+ if (!byName.has(name)) byName.set(name, value);
173
+ } else anonymous.add(value);
174
+ }
175
+ return [...byName.values(), ...anonymous];
176
+ }
177
+ function isKind(value, kind) {
178
+ return typeof value === "object" && value !== null && value.kind === kind;
179
+ }
180
+ function dirOf(path) {
181
+ return resolve(path, "..");
182
+ }
183
+ // src/cli/bootstrap.ts
184
+ /**
185
+ * What `vlo dev` and `vlo serve` share: load the config, open and migrate the journal,
186
+ * bind the port, and print the same four ✓ lines. The two verbs differ only in their
187
+ * defaults — that is the point, so a laptop and Cloud Run run identical code.
188
+ */
189
+ async function start(options) {
190
+ const loaded = await loadConfig(options.cwd, options.profile, options.configPath, { implicitProfile: options.implicitProfile === true });
191
+ const journal = openJournal(loaded.profile.journal);
192
+ await journal.migrate();
193
+ line("journal", loaded.profile.journal);
194
+ const names = loaded.workflows.map((w) => w.name).sort();
195
+ line(`found ${names.length} workflow${names.length === 1 ? "" : "s"}`, names.join(" · "));
196
+ describeWorkers(loaded.workers.length, Object.keys(loaded.profile.queues));
197
+ const { roles, dispatcher, publicUrl } = loaded.profile;
198
+ const running = await serve({
199
+ journal,
200
+ blob: loaded.profile.blob,
201
+ workflows: loaded.workflows,
202
+ workers: loaded.workers,
203
+ activities: loaded.activities,
204
+ signals: loaded.signals,
205
+ queues: loaded.profile.queues,
206
+ auth: loaded.profile.auth,
207
+ ...roles !== void 0 ? { roles } : {},
208
+ ...dispatcher !== void 0 ? { dispatcher } : {},
209
+ ...publicUrl !== void 0 ? { publicUrl } : {},
210
+ port: options.port ?? loaded.profile.port ?? 4100
211
+ });
212
+ line("api", `http://localhost:${running.port}`);
213
+ running.host.events.on("warning", (w) => {
214
+ const detail = w.error instanceof Error ? `: ${w.error.message}` : "";
215
+ process.stderr.write(` ⚠ ${w.message}${detail}\n`);
216
+ });
217
+ const close = async () => {
218
+ await running.close();
219
+ await journal.close();
220
+ };
221
+ const shutdown = () => void close();
222
+ process.once("SIGINT", shutdown);
223
+ process.once("SIGTERM", shutdown);
224
+ return {
225
+ running,
226
+ loaded,
227
+ close
228
+ };
229
+ }
230
+ function describeWorkers(count, remoteQueues) {
231
+ if (count > 0) {
232
+ line(`found ${count} worker${count === 1 ? "" : "s"}`, "in-process");
233
+ return;
234
+ }
235
+ if (remoteQueues.length > 0) {
236
+ line("workers", `remote via queues ${remoteQueues.join(" · ")}`);
237
+ return;
238
+ }
239
+ process.stderr.write(" ⚠ no workers found: tasks will stay scheduled until a module exporting defineWorker() matches `workers` in vlo.config.ts, or a queue url is configured\n");
240
+ }
241
+ function line(label, value) {
242
+ const gap = label.length >= 9 ? " " : "";
243
+ process.stdout.write(` ✓ ${label.padEnd(9)}${gap}${value}\n`);
244
+ }
245
+ // src/cli/help.ts
246
+ /** `--help` detection, the `--profile` fallback and the package version, shared by every verb. */
247
+ /** From `src/cli/` (tsx) and from `dist/` (built), respectively. */
248
+ const PACKAGE_JSON_CANDIDATES = ["../../package.json", "../package.json"];
249
+ function wantsHelp(argv) {
250
+ return argv.includes("--help") || argv.includes("-h");
251
+ }
252
+ /** `--profile`, then `VLO_PROFILE`; an empty value counts as unset. */
253
+ function profileArg(values) {
254
+ const profile = values.profile ?? process.env["VLO_PROFILE"];
255
+ return profile === void 0 || profile.length === 0 ? void 0 : profile;
256
+ }
257
+ /** {@link profileArg}, but a missing profile is an error quoting the verb's usage. */
258
+ function requireProfile(values, usage) {
259
+ const profile = profileArg(values);
260
+ if (profile === void 0) throw new Error(`${usage}\n --profile is required (or set VLO_PROFILE)`);
261
+ return profile;
262
+ }
263
+ function version() {
264
+ for (const candidate of PACKAGE_JSON_CANDIDATES) try {
265
+ const pkg = JSON.parse(readFileSync(new URL(candidate, import.meta.url), "utf8"));
266
+ if (pkg.name === "@oona/vlo" && typeof pkg.version === "string") return pkg.version;
267
+ } catch {
268
+ continue;
269
+ }
270
+ throw new Error("vlo: could not find the SDK's package.json");
271
+ }
272
+ // src/cli/dev.ts
273
+ /**
274
+ * `vlo dev` — the whole engine on a laptop: SQLite, a file blob store, every role in one
275
+ * process. No hot reload and no console yet; the point is that `vlo dev` and a Cloud Run
276
+ * deployment run the same `serve()`.
277
+ *
278
+ * The profile is `--profile`, then `VLO_PROFILE`, then `local` if the config has one, then
279
+ * the config's only profile. A config with several profiles and no `local` needs the flag.
280
+ */
281
+ const USAGE$4 = "vlo dev [--config <path>] [--profile <name>] [--port <n>]";
282
+ async function dev(argv, cwd = process.cwd()) {
283
+ const { values } = parseArgs({
284
+ args: [...argv],
285
+ options: {
286
+ config: { type: "string" },
287
+ profile: { type: "string" },
288
+ port: { type: "string" }
289
+ }
290
+ });
291
+ const profile = profileArg(values);
292
+ return start({
293
+ cwd,
294
+ ...profile !== void 0 ? { profile } : {},
295
+ implicitProfile: true,
296
+ ...values.config !== void 0 ? { configPath: values.config } : {},
297
+ ...values.port !== void 0 ? { port: Number(values.port) } : {}
298
+ });
299
+ }
300
+ // src/deploy/cloud-run-tf.ts
301
+ /** Terraform identifiers cannot contain `-`. */
302
+ function varName(plan) {
303
+ return plan.service.replace(/[^A-Za-z0-9_]/g, "_");
304
+ }
305
+ function service(plan) {
306
+ const v = varName(plan);
307
+ return `// Vlo host on Cloud Run — generated by \`vlo deploy --profile ${plan.profile}\`.
308
+ //
309
+ // Drop into terraform/ beside cloud-run-video-renderer.tf; this file reuses that module's
310
+ // \`local.envs\` (pubsub.tf), \`local.env_buckets\` (storage.tf), \`var.project_id\` and the
311
+ // \`google_project_service\` enablements already declared there.
312
+
313
+ variable "${v}_image" {
314
+ description = "Initial container image. The real image is pushed by the Cloud Build trigger; Terraform ignores later image changes (lifecycle.ignore_changes)."
315
+ type = string
316
+ default = "us-docker.pkg.dev/cloudrun/container/hello"
317
+ }
318
+
319
+ variable "${v}_location" {
320
+ description = "Cloud Run region for the Vlo host."
321
+ type = string
322
+ default = "${plan.region}"
323
+ }
324
+
325
+ variable "${v}_envs" {
326
+ description = "Envs from local.envs the Vlo host is deployed to."
327
+ type = list(string)
328
+ default = ${hclList(plan.envs)}
329
+ }
330
+
331
+ locals {
332
+ ${v}_envs = { for name, env in local.envs : name => env if contains(var.${v}_envs, name) }
333
+ }
334
+
335
+ // ===========================================================================
336
+ // Secrets
337
+ // ===========================================================================
338
+ //
339
+ // First service in this project that needs a database, so the first that needs Secret
340
+ // Manager. Terraform declares the secret *containers* only — versions hold the values and
341
+ // would land in state, so they are added out of band, once per env:
342
+ //
343
+ // printf '%s' "$DATABASE_URL" | gcloud secrets versions add <secret-id> --data-file=-
344
+ //
345
+ // A service revision resolves "latest" at start-up, so rotating a secret is a new version
346
+ // plus a restart, with no Terraform run.
347
+
348
+ resource "google_secret_manager_secret" "${v}_database_url" {
349
+ for_each = local.${v}_envs
350
+
351
+ project = var.project_id
352
+ secret_id = "\${each.value.prefix}-${plan.secretName}-database-url"
353
+
354
+ replication {
355
+ auto {}
356
+ }
357
+ }
358
+
359
+ resource "google_secret_manager_secret" "${v}_token" {
360
+ for_each = local.${v}_envs
361
+
362
+ project = var.project_id
363
+ secret_id = "\${each.value.prefix}-${plan.secretName}-token"
364
+
365
+ replication {
366
+ auto {}
367
+ }
368
+ }
369
+
370
+ resource "google_secret_manager_secret" "${v}_push_secret" {
371
+ for_each = local.${v}_envs
372
+
373
+ project = var.project_id
374
+ secret_id = "\${each.value.prefix}-${plan.secretName}-push-secret"
375
+
376
+ replication {
377
+ auto {}
378
+ }
379
+ }
380
+
381
+ // ===========================================================================
382
+ // Per-env service account (least privilege)
383
+ // ===========================================================================
384
+
385
+ resource "google_service_account" "${v}" {
386
+ for_each = local.${v}_envs
387
+
388
+ account_id = "\${each.value.prefix}-${plan.service}"
389
+ display_name = "Vlo host (\${each.key})"
390
+ description = "Durable execution host for \${each.key}"
391
+ project = var.project_id
392
+ }
393
+
394
+ // Blob store: offloaded payloads and checkpoints, in the env's own bucket.
395
+ resource "google_storage_bucket_iam_member" "${v}_storage" {
396
+ for_each = local.${v}_envs
397
+
398
+ bucket = local.env_buckets[each.key]
399
+ role = "roles/storage.objectAdmin"
400
+ member = "serviceAccount:\${google_service_account.${v}[each.key].email}"
401
+ }
402
+
403
+ resource "google_secret_manager_secret_iam_member" "${v}_database_url" {
404
+ for_each = local.${v}_envs
405
+
406
+ project = var.project_id
407
+ secret_id = google_secret_manager_secret.${v}_database_url[each.key].secret_id
408
+ role = "roles/secretmanager.secretAccessor"
409
+ member = "serviceAccount:\${google_service_account.${v}[each.key].email}"
410
+ }
411
+
412
+ resource "google_secret_manager_secret_iam_member" "${v}_token" {
413
+ for_each = local.${v}_envs
414
+
415
+ project = var.project_id
416
+ secret_id = google_secret_manager_secret.${v}_token[each.key].secret_id
417
+ role = "roles/secretmanager.secretAccessor"
418
+ member = "serviceAccount:\${google_service_account.${v}[each.key].email}"
419
+ }
420
+
421
+ resource "google_secret_manager_secret_iam_member" "${v}_push_secret" {
422
+ for_each = local.${v}_envs
423
+
424
+ project = var.project_id
425
+ secret_id = google_secret_manager_secret.${v}_push_secret[each.key].secret_id
426
+ role = "roles/secretmanager.secretAccessor"
427
+ member = "serviceAccount:\${google_service_account.${v}[each.key].email}"
428
+ }
429
+
430
+ // Structured logs from the dispatcher and the router.
431
+ resource "google_project_iam_member" "${v}_log_writer" {
432
+ for_each = local.${v}_envs
433
+
434
+ project = var.project_id
435
+ role = "roles/logging.logWriter"
436
+ member = "serviceAccount:\${google_service_account.${v}[each.key].email}"
437
+ }
438
+
439
+ // ===========================================================================
440
+ // Cloud Run service
441
+ // ===========================================================================
442
+
443
+ resource "google_cloud_run_v2_service" "${v}" {
444
+ for_each = local.${v}_envs
445
+
446
+ name = "\${each.value.prefix}-${plan.service}"
447
+ location = var.${v}_location
448
+ project = var.project_id
449
+
450
+ template {
451
+ // Long-poll task claims and SSE streams hold a request open; 3600s is the ceiling.
452
+ timeout = "3600s"
453
+
454
+ // The host is I/O bound — it waits on Postgres and on worker pushes — so one instance
455
+ // serves many runs.
456
+ max_instance_request_concurrency = 80
457
+
458
+ scaling {
459
+ // The dispatcher is a background loop, not a request handler: scaling to zero would
460
+ // stop timers firing and tasks being pushed.
461
+ min_instance_count = 1
462
+ max_instance_count = 3
463
+ }
464
+
465
+ service_account = google_service_account.${v}[each.key].email
466
+
467
+ containers {
468
+ image = var.${v}_image
469
+
470
+ ports {
471
+ container_port = 8080
472
+ }
473
+
474
+ resources {
475
+ limits = {
476
+ cpu = "1"
477
+ memory = "1Gi"
478
+ }
479
+ // The dispatcher ticks between requests, so CPU must not be throttled when idle.
480
+ cpu_idle = false
481
+ startup_cpu_boost = true
482
+ }
483
+
484
+ env {
485
+ name = "VLO_PROFILE"
486
+ value = "${plan.profile}"
487
+ }
488
+ env {
489
+ name = "GCP_PROJECT_ID"
490
+ value = var.project_id
491
+ }
492
+ env {
493
+ name = "VLO_BUCKET"
494
+ value = local.env_buckets[each.key]
495
+ }
496
+
497
+ env {
498
+ name = "DATABASE_URL"
499
+ value_source {
500
+ secret_key_ref {
501
+ secret = google_secret_manager_secret.${v}_database_url[each.key].secret_id
502
+ version = "latest"
503
+ }
504
+ }
505
+ }
506
+ env {
507
+ name = "VLO_TOKEN"
508
+ value_source {
509
+ secret_key_ref {
510
+ secret = google_secret_manager_secret.${v}_token[each.key].secret_id
511
+ version = "latest"
512
+ }
513
+ }
514
+ }
515
+ env {
516
+ name = "VLO_PUSH_SECRET"
517
+ value_source {
518
+ secret_key_ref {
519
+ secret = google_secret_manager_secret.${v}_push_secret[each.key].secret_id
520
+ version = "latest"
521
+ }
522
+ }
523
+ }
524
+ }
525
+ }
526
+
527
+ ingress = "INGRESS_TRAFFIC_ALL"
528
+
529
+ // The image is deployed by the Cloud Build trigger; without this every apply would roll
530
+ // the running code back to the placeholder.
531
+ lifecycle {
532
+ ignore_changes = [
533
+ client,
534
+ client_version,
535
+ template[0].containers[0].image,
536
+ ]
537
+ }
538
+
539
+ depends_on = [
540
+ google_project_service.run,
541
+ ]
542
+ }
543
+
544
+ // Open at the network edge, closed at the app layer: every control-plane route requires the
545
+ // bearer token in VLO_TOKEN, and inbound task callbacks are HMAC-signed with VLO_PUSH_SECRET.
546
+ // IAM invoker checks cannot be used here because the callers are workers on other platforms
547
+ // (Vercel functions, pollers) that hold a Vlo token, not a Google identity.
548
+ resource "google_cloud_run_v2_service_iam_member" "${v}_invoker" {
549
+ for_each = local.${v}_envs
550
+
551
+ project = var.project_id
552
+ location = var.${v}_location
553
+ name = google_cloud_run_v2_service.${v}[each.key].name
554
+
555
+ role = "roles/run.invoker"
556
+ member = "allUsers"
557
+ }
558
+
559
+ output "${v}_urls" {
560
+ description = "Public URL of the Vlo host per env; this is VLO_PUBLIC_URL for its peers."
561
+ value = { for name, service in google_cloud_run_v2_service.${v} : name => service.uri }
562
+ }
563
+ `;
564
+ }
565
+ function trigger(plan) {
566
+ const v = varName(plan);
567
+ return `// Vlo deploy automation (Cloud Build triggers) — generated by
568
+ // \`vlo deploy --profile ${plan.profile}\`.
569
+ //
570
+ // Terraform ignores the service's container image (cloud-run-vlo.tf), so deploys happen
571
+ // here: per-env triggers watch main and run the generated cloudbuild.yaml
572
+ // (build → push → gcloud run deploy). Staging deploys automatically; prod waits for a
573
+ // manual approval in the Cloud Build console.
574
+ //
575
+ // ONE-TIME MANUAL PREREQUISITE: the GitHub repo must be connected to Cloud Build (install
576
+ // the Google Cloud Build GitHub App, then connect the repo under Cloud Build →
577
+ // Repositories, 1st gen). \`terraform apply\` fails with "repository mapping does not
578
+ // exist" until that is done. \`var.github_owner\` / \`var.github_repo\` are declared in
579
+ // cloudbuild-video-renderer.tf.
580
+
581
+ resource "google_artifact_registry_repository" "${v}" {
582
+ project = var.project_id
583
+ location = var.${v}_location
584
+ repository_id = "${plan.service}"
585
+ description = "Vlo host images (deployed via Cloud Build triggers)"
586
+ format = "DOCKER"
587
+
588
+ depends_on = [google_project_service.artifactregistry]
589
+ }
590
+
591
+ // Dedicated deploy SA, so the blast radius of the pipeline is explicit.
592
+ resource "google_service_account" "${v}_deployer" {
593
+ project = var.project_id
594
+ account_id = "${plan.service}-deployer"
595
+ display_name = "Vlo deployer (Cloud Build)"
596
+ description = "Builds and deploys the Vlo host Cloud Run services"
597
+ }
598
+
599
+ resource "google_artifact_registry_repository_iam_member" "${v}_deployer_ar_writer" {
600
+ project = var.project_id
601
+ location = google_artifact_registry_repository.${v}.location
602
+ repository = google_artifact_registry_repository.${v}.name
603
+ role = "roles/artifactregistry.writer"
604
+ member = "serviceAccount:\${google_service_account.${v}_deployer.email}"
605
+ }
606
+
607
+ resource "google_cloud_run_v2_service_iam_member" "${v}_deployer_run_developer" {
608
+ for_each = local.${v}_envs
609
+
610
+ project = var.project_id
611
+ location = var.${v}_location
612
+ name = google_cloud_run_v2_service.${v}[each.key].name
613
+ role = "roles/run.developer"
614
+ member = "serviceAccount:\${google_service_account.${v}_deployer.email}"
615
+ }
616
+
617
+ // Deploying a service that runs as the host SA requires actAs on it.
618
+ resource "google_service_account_iam_member" "${v}_deployer_act_as" {
619
+ for_each = local.${v}_envs
620
+
621
+ service_account_id = google_service_account.${v}[each.key].name
622
+ role = "roles/iam.serviceAccountUser"
623
+ member = "serviceAccount:\${google_service_account.${v}_deployer.email}"
624
+ }
625
+
626
+ // Custom-SA builds must write logs explicitly.
627
+ resource "google_project_iam_member" "${v}_deployer_log_writer" {
628
+ project = var.project_id
629
+ role = "roles/logging.logWriter"
630
+ member = "serviceAccount:\${google_service_account.${v}_deployer.email}"
631
+ }
632
+
633
+ resource "google_cloudbuild_trigger" "${v}_deploy" {
634
+ for_each = local.${v}_envs
635
+
636
+ project = var.project_id
637
+ name = "\${each.value.prefix}-${plan.service}-deploy"
638
+ description = "Build + deploy the Vlo host to \${each.key} on engine or workflow changes"
639
+ location = "global"
640
+
641
+ github {
642
+ owner = var.github_owner
643
+ name = var.github_repo
644
+ push {
645
+ branch = "^main$"
646
+ }
647
+ }
648
+
649
+ included_files = ["packages/vlo/**", "src/**/vlo/**", "vlo.config.ts"]
650
+ filename = "deploy/vlo/cloud-run/cloudbuild.yaml"
651
+
652
+ substitutions = {
653
+ _SERVICE = google_cloud_run_v2_service.${v}[each.key].name
654
+ _REGION = var.${v}_location
655
+ _REPO = google_artifact_registry_repository.${v}.repository_id
656
+ }
657
+
658
+ service_account = google_service_account.${v}_deployer.id
659
+
660
+ dynamic "approval_config" {
661
+ for_each = each.key == "prod" ? [1] : []
662
+ content {
663
+ approval_required = true
664
+ }
665
+ }
666
+
667
+ depends_on = [google_project_service.cloudbuild]
668
+ }
669
+ `;
670
+ }
671
+ function hclList(values) {
672
+ return `[${values.map((v) => `"${v}"`).join(", ")}]`;
673
+ }
674
+ // src/deploy/cloud-run.ts
675
+ /**
676
+ * Cloud Run templates.
677
+ *
678
+ * Shapes: a two-stage node:22-alpine image, a three-step cloudbuild, and per-env
679
+ * `for_each = local.envs` Terraform with the image under `lifecycle.ignore_changes`, so a
680
+ * generated stack reads like a hand-written one. Two things are new: the service needs a database, which means Secret Manager, and
681
+ * it is internet-reachable, which the control plane's bearer token — not IAM — protects.
682
+ */
683
+ function renderCloudRun(plan) {
684
+ return [
685
+ {
686
+ path: "cloud-run/Dockerfile",
687
+ contents: dockerfile(plan)
688
+ },
689
+ {
690
+ path: "cloud-run/cloudbuild.yaml",
691
+ contents: cloudbuild(plan)
692
+ },
693
+ {
694
+ path: "cloud-run/cloud-run-vlo.tf",
695
+ contents: service(plan)
696
+ },
697
+ {
698
+ path: "cloud-run/cloudbuild-vlo.tf",
699
+ contents: trigger(plan)
700
+ },
701
+ {
702
+ path: "cloud-run/README.md",
703
+ contents: readme(plan)
704
+ }
705
+ ];
706
+ }
707
+ function cloudRunCommands(plan) {
708
+ const project = plan.project ?? "<project-id>";
709
+ const first = plan.envs[0] ?? "staging";
710
+ return [
711
+ `# 1. copy the Terraform into the root module`,
712
+ `cp deploy/vlo/cloud-run/*.tf terraform/`,
713
+ ``,
714
+ `# 2. create the secret containers, then add a version per env (never in Terraform state)`,
715
+ `terraform -chdir=terraform apply -target=google_secret_manager_secret.${varName(plan)}_database_url`,
716
+ ...plan.envs.flatMap((env) => [
717
+ `printf '%s' "$DATABASE_URL" | gcloud secrets versions add ${plan.namePrefix}-${env}-${plan.secretName}-database-url --data-file=- --project ${project}`,
718
+ `printf '%s' "$VLO_TOKEN" | gcloud secrets versions add ${plan.namePrefix}-${env}-${plan.secretName}-token --data-file=- --project ${project}`,
719
+ `printf '%s' "$VLO_PUSH_SECRET" | gcloud secrets versions add ${plan.namePrefix}-${env}-${plan.secretName}-push-secret --data-file=- --project ${project}`
720
+ ]),
721
+ ``,
722
+ `# 3. the rest of the stack`,
723
+ `terraform -chdir=terraform apply`,
724
+ ``,
725
+ `# 4. first image (later ones ride the Cloud Build trigger on main)`,
726
+ `gcloud builds submit --config deploy/vlo/cloud-run/cloudbuild.yaml --project ${project} \\`,
727
+ ` --substitutions _SERVICE=${plan.namePrefix}-${first}-${plan.service},_REGION=${plan.region},_REPO=${plan.service}`
728
+ ];
729
+ }
730
+ function dockerfile(plan) {
731
+ return `# Vlo host image — generated by \`vlo deploy --profile ${plan.profile}\`.
732
+ # Build context is the repo root: the image needs the workspace, not just this directory.
733
+ #
734
+ # docker build -f deploy/vlo/cloud-run/Dockerfile -t vlo .
735
+
736
+ FROM node:22-alpine AS builder
737
+ WORKDIR /app
738
+ RUN corepack enable
739
+ COPY pnpm-lock.yaml pnpm-workspace.yaml package.json ./
740
+ COPY packages/vlo ./packages/vlo
741
+ RUN pnpm install --frozen-lockfile --filter @oona/vlo...
742
+ RUN pnpm --filter @oona/vlo build
743
+
744
+ FROM node:22-alpine AS runner
745
+ WORKDIR /app
746
+ ENV NODE_ENV=production
747
+ RUN corepack enable
748
+ COPY --from=builder /app/node_modules ./node_modules
749
+ COPY --from=builder /app/packages ./packages
750
+ # The profile decides which modules are loaded; the globs in vlo.config.ts resolve
751
+ # against this directory, so everything they can match has to be here.
752
+ COPY vlo.config.ts ./
753
+ COPY src ./src
754
+
755
+ ENV VLO_PROFILE=${plan.profile}
756
+ # Cloud Run injects PORT (default 8080) and \`vlo serve\` honours it.
757
+ EXPOSE 8080
758
+ CMD ["pnpm", "exec", "vlo", "serve", "--profile", "${plan.profile}"]
759
+ `;
760
+ }
761
+ function cloudbuild(plan) {
762
+ return `# Build + deploy the Vlo host to Cloud Run. Invoked by the per-env Cloud Build
763
+ # triggers in cloudbuild-vlo.tf (staging: auto on main; prod: same filter, gated on a
764
+ # manual approval). Substitutions:
765
+ # _SERVICE — Cloud Run service name (e.g. ${plan.namePrefix}-prod-${plan.service})
766
+ # _REGION — Cloud Run + Artifact Registry region
767
+ # _REPO — Artifact Registry docker repo name
768
+ steps:
769
+ - id: build
770
+ name: gcr.io/cloud-builders/docker
771
+ args:
772
+ - build
773
+ - -f
774
+ - deploy/vlo/cloud-run/Dockerfile
775
+ - -t
776
+ - \${_REGION}-docker.pkg.dev/\${PROJECT_ID}/\${_REPO}/${plan.service}:\${SHORT_SHA}
777
+ - -t
778
+ - \${_REGION}-docker.pkg.dev/\${PROJECT_ID}/\${_REPO}/${plan.service}:latest
779
+ - .
780
+
781
+ - id: push
782
+ name: gcr.io/cloud-builders/docker
783
+ args:
784
+ - push
785
+ - --all-tags
786
+ - \${_REGION}-docker.pkg.dev/\${PROJECT_ID}/\${_REPO}/${plan.service}
787
+
788
+ - id: deploy
789
+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
790
+ entrypoint: gcloud
791
+ args:
792
+ - run
793
+ - deploy
794
+ - \${_SERVICE}
795
+ - --image
796
+ - \${_REGION}-docker.pkg.dev/\${PROJECT_ID}/\${_REPO}/${plan.service}:\${SHORT_SHA}
797
+ - --region
798
+ - \${_REGION}
799
+ - --project
800
+ - \${PROJECT_ID}
801
+
802
+ images:
803
+ - \${_REGION}-docker.pkg.dev/\${PROJECT_ID}/\${_REPO}/${plan.service}:\${SHORT_SHA}
804
+ - \${_REGION}-docker.pkg.dev/\${PROJECT_ID}/\${_REPO}/${plan.service}:latest
805
+
806
+ # Required when the trigger runs as a custom service account.
807
+ options:
808
+ logging: CLOUD_LOGGING_ONLY
809
+ `;
810
+ }
811
+ function readme(plan) {
812
+ const project = plan.project ?? "<project-id>";
813
+ return `# Vlo on Cloud Run — \`${plan.profile}\`
814
+
815
+ Generated by \`vlo deploy --profile ${plan.profile}\`. Nothing here has been applied.
816
+
817
+ | File | Goes to | What it is |
818
+ | --- | --- | --- |
819
+ | \`Dockerfile\` | keep here | Two-stage image; \`CMD\` is \`vlo serve --profile ${plan.profile}\` |
820
+ | \`cloudbuild.yaml\` | keep here | build → push → \`gcloud run deploy\`, run by the triggers |
821
+ | \`cloud-run-vlo.tf\` | \`terraform/\` | Service, SA, IAM, Secret Manager containers |
822
+ | \`cloudbuild-vlo.tf\` | \`terraform/\` | Artifact Registry, deployer SA, per-env triggers |
823
+
824
+ Envs: ${plan.envs.join(", ")} · region \`${plan.region}\` · service \`\${prefix}-${plan.service}\`
825
+
826
+ ## One-time setup
827
+
828
+ 1. **Connect the repo to Cloud Build** — install the Google Cloud Build GitHub App and
829
+ connect the repo under Cloud Build → Repositories (1st gen). Terraform cannot do this,
830
+ and applies fail with "repository mapping does not exist" until it is done.
831
+ 2. **Copy the Terraform** into the root module: \`cp *.tf ../../../terraform/\`.
832
+ 3. **Create the secret containers**, then add a version per env. Versions are deliberately
833
+ not in Terraform — a value in state is a value in every plan output:
834
+
835
+ ${plan.envs.map((env) => ` \`\`\`bash
836
+ printf '%s' "$DATABASE_URL" | gcloud secrets versions add ${plan.namePrefix}-${env}-${plan.secretName}-database-url --data-file=- --project ${project}
837
+ printf '%s' "$VLO_TOKEN" | gcloud secrets versions add ${plan.namePrefix}-${env}-${plan.secretName}-token --data-file=- --project ${project}
838
+ printf '%s' "$VLO_PUSH_SECRET" | gcloud secrets versions add ${plan.namePrefix}-${env}-${plan.secretName}-push-secret --data-file=- --project ${project}
839
+ \`\`\``).join("\n")}
840
+ 4. \`terraform -chdir=terraform apply\`.
841
+ 5. Push to \`main\`. Staging builds and deploys; prod waits for approval in the Cloud Build
842
+ console.
843
+
844
+ ## Then
845
+
846
+ - \`vlo doctor --profile ${plan.profile}\` from a shell with the same env, before the first deploy.
847
+ - The service is reachable from the internet and protected by \`VLO_TOKEN\`; put a load
848
+ balancer or IAP in front of it if you need network-level restriction too.
849
+ - Rotating a secret is \`gcloud secrets versions add\` plus a revision restart — no apply.
850
+ `;
851
+ }
852
+ // src/deploy/vercel.ts
853
+ const TICK_PATH = "/api/vlo/v1/timers/tick";
854
+ function renderVercel(plan) {
855
+ const files = [{
856
+ path: "vercel/route.ts",
857
+ contents: route(plan)
858
+ }, {
859
+ path: "vercel/env.md",
860
+ contents: envChecklist(plan)
861
+ }];
862
+ if (plan.roles.includes("orchestrator")) files.splice(1, 0, {
863
+ path: "vercel/vercel-crons.json",
864
+ contents: crons(plan)
865
+ });
866
+ return files;
867
+ }
868
+ function vercelCommands(plan) {
869
+ return [
870
+ `# 1. drop the route in`,
871
+ `mkdir -p src/app/api/vlo/\\[\\[...path\\]\\]`,
872
+ `cp deploy/vlo/vercel/route.ts "src/app/api/vlo/[[...path]]/route.ts"`,
873
+ ``,
874
+ `# 2. environment (repeat for preview if you run one)`,
875
+ ...envNames(plan).map((name) => `vercel env add ${name} production`),
876
+ ``,
877
+ ...plan.roles.includes("orchestrator") ? [
878
+ `# 3. merge deploy/vlo/vercel/vercel-crons.json into the "crons" array in vercel.json`,
879
+ ``,
880
+ `# 4. ship`
881
+ ] : [`# 3. ship`],
882
+ `vercel deploy --prod`
883
+ ];
884
+ }
885
+ function route(plan) {
886
+ const queueLines = plan.queues.filter((q) => q.mode === "push").map((q) => ` ${key(q.name)}: { url: required("${envVar(q.name)}"), secret: required("VLO_PUSH_SECRET") },`);
887
+ return `/**
888
+ * Vlo control plane — generated by \`vlo deploy --profile ${plan.profile}\`.
889
+ * Drop in at \`app/api/vlo/[[...path]]/route.ts\`.
890
+ *
891
+ * Roles: ${plan.roles.join(", ")}. The dispatcher runs in \`manual\` mode because a
892
+ * serverless function has no process to tick in — the cron in vercel-crons.json calls
893
+ * POST /v1/timers/tick instead, and every tick does one full dispatcher pass.
894
+ */
895
+
896
+ import { handler } from "@oona/vlo/host";
897
+ // Globs cannot be bundled into a function, so the modules are imported explicitly.
898
+ // \`vlo deploy\` found ${plan.workflows.length === 0 ? "no workflows" : `these workflows: ${plan.workflows.join(", ")}`}; re-export them from these two barrels.
899
+ import { workflows } from "@/vlo/workflows";
900
+ import { workers } from "@/vlo/workers";
901
+
902
+ // A tick and a long task push both need more than the default 10s.
903
+ export const maxDuration = 300;
904
+
905
+ function required(name: string): string {
906
+ const value = process.env[name];
907
+ if (value === undefined || value === "") throw new Error(\`vlo: \${name} is not set\`);
908
+ return value;
909
+ }
910
+
911
+ export const { GET, POST } = handler({
912
+ journal: required("DATABASE_URL"),
913
+ blob: ${blobExpression(plan)},
914
+ workflows,
915
+ workers,
916
+ roles: [${plan.roles.map((r) => `"${r}"`).join(", ")}],
917
+ basePath: "/api/vlo",
918
+ dispatcher: { mode: "manual" },
919
+ queues: {
920
+ ${queueLines.length === 0 ? " // no push queues in this profile" : queueLines.join("\n")}
921
+ },
922
+ auth: { token: required("VLO_TOKEN"), pushSecret: required("VLO_PUSH_SECRET") },
923
+ publicUrl: required("VLO_PUBLIC_URL"),
924
+ });
925
+ `;
926
+ }
927
+ function crons(plan) {
928
+ return `${JSON.stringify({ crons: [{
929
+ path: TICK_PATH,
930
+ schedule: plan.cron
931
+ }] }, null, 2)}\n`;
932
+ }
933
+ function envChecklist(plan) {
934
+ const rows = [
935
+ ["`DATABASE_URL`", "Postgres journal. Pooled connection string — functions are short-lived."],
936
+ ["`VLO_TOKEN`", "Bearer token every control-plane route requires. The same value its clients hold."],
937
+ ["`VLO_PUSH_SECRET`", "HMAC secret shared with the workers this host pushes to and accepts callbacks from."],
938
+ ["`VLO_PUBLIC_URL`", "This deployment's own origin, e.g. `https://example.com`. Fills `complete_url` on a push."],
939
+ ...plan.queues.filter((q) => q.mode === "push").map((q) => [`\`${envVar(q.name)}\``, `Push endpoint for the \`${q.name}\` queue.`])
940
+ ];
941
+ if (plan.bucket !== void 0) rows.push(["`VLO_BUCKET`", "Bucket holding offloaded payloads and checkpoints."]);
942
+ if (plan.blobScheme === "gcs") rows.push(["`GCP_SERVICE_ACCOUNT_KEY_BASE64`", "Base64 service-account JSON for the blob bucket. Only needed off Google infrastructure — on Cloud Run, ADC covers it."]);
943
+ return `# Environment — \`${plan.profile}\` on Vercel
944
+
945
+ Set every variable below on the Vercel project before the first deploy. Vlo reads them at
946
+ request time, so a change needs a redeploy only if the value is baked into a build.
947
+
948
+ | Variable | What it is |
949
+ | --- | --- |
950
+ ${rows.map(([name, description]) => `| ${name} | ${description} |`).join("\n")}
951
+
952
+ ## Checks
953
+
954
+ - \`vlo doctor --profile ${plan.profile}\` with the same variables exported locally, before deploying.
955
+ ${plan.roles.includes("orchestrator") ? `- The cron in \`vercel-crons.json\` (\`${plan.cron}\`) is what advances timers, retries and task
956
+ pushes. Without it, runs start and then sit still.` : `- This deployment holds no \`orchestrator\` role, so something else must run the dispatcher.`}
957
+ - Blob store: \`${plan.blobScheme}\`${plan.bucket !== void 0 ? ` · bucket \`${plan.bucket}\`` : ""}.
958
+ `;
959
+ }
960
+ function envNames(plan) {
961
+ return [
962
+ "DATABASE_URL",
963
+ "VLO_TOKEN",
964
+ "VLO_PUSH_SECRET",
965
+ "VLO_PUBLIC_URL",
966
+ ...plan.queues.filter((q) => q.mode === "push").map((q) => envVar(q.name)),
967
+ ...plan.bucket !== void 0 ? ["VLO_BUCKET"] : [],
968
+ ...plan.blobScheme === "gcs" ? ["GCP_SERVICE_ACCOUNT_KEY_BASE64"] : []
969
+ ];
970
+ }
971
+ /** A function's filesystem is ephemeral, so anything but a bucket is a dev-only fallback. */
972
+ function blobExpression(plan) {
973
+ return plan.bucket !== void 0 ? "`gcs://${required(\"VLO_BUCKET\")}/vlo`" : "\"file:///tmp/vlo-blobs\"";
974
+ }
975
+ function key(queue) {
976
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(queue) ? queue : JSON.stringify(queue);
977
+ }
978
+ function envVar(queue) {
979
+ return `VLO_QUEUE_${queue.replace(/[^A-Za-z0-9]/g, "_").toUpperCase()}_URL`;
980
+ }
981
+ // src/deploy/render.ts
982
+ const DEFAULTS = {
983
+ region: "europe-west4",
984
+ namePrefix: "vlo",
985
+ service: "vlo",
986
+ secretName: "vlo",
987
+ cron: "* * * * *",
988
+ envs: ["staging", "prod"]
989
+ };
990
+ function planDeploy(loaded) {
991
+ const deploy = loaded.profile.deploy;
992
+ if (deploy === void 0) throw new Error(`profile "${loaded.profile.name}" has no \`deploy\` block; add deploy: { target: "cloud-run" | "vercel" } to vlo.config.ts`);
993
+ const queues = Object.entries(loaded.profile.queues).map(([name, config]) => ({
994
+ name,
995
+ mode: config.mode === "pull" ? "pull" : config.url !== void 0 ? "push" : "in-process"
996
+ }));
997
+ return {
998
+ profile: loaded.profile.name,
999
+ target: deploy.target,
1000
+ ...deploy.project !== void 0 ? { project: deploy.project } : {},
1001
+ region: deploy.region ?? DEFAULTS.region,
1002
+ namePrefix: deploy.namePrefix ?? DEFAULTS.namePrefix,
1003
+ service: deploy.service ?? DEFAULTS.service,
1004
+ ...bucketOf(deploy.bucket, loaded.profile.blob),
1005
+ envs: deploy.envs ?? [...DEFAULTS.envs],
1006
+ secretName: deploy.secretName ?? DEFAULTS.secretName,
1007
+ cron: deploy.cron ?? DEFAULTS.cron,
1008
+ roles: loaded.profile.roles ?? ["orchestrator", "api"],
1009
+ dispatcherMode: loaded.profile.dispatcher?.mode ?? "loop",
1010
+ queues,
1011
+ blobScheme: schemeOf(loaded.profile.blob),
1012
+ workflows: loaded.workflows.map((w) => w.name).sort()
1013
+ };
1014
+ }
1015
+ function render(plan) {
1016
+ return plan.target === "cloud-run" ? renderCloudRun(plan) : renderVercel(plan);
1017
+ }
1018
+ /** What `--apply` prints. Vlo never runs these: applying is the operator's call. */
1019
+ function commands(plan) {
1020
+ return plan.target === "cloud-run" ? cloudRunCommands(plan) : vercelCommands(plan);
1021
+ }
1022
+ function bucketOf(explicit, blobUrl) {
1023
+ if (explicit !== void 0) return { bucket: explicit };
1024
+ if (!blobUrl.startsWith("gcs://")) return {};
1025
+ const [bucket] = blobUrl.slice(6).split("/");
1026
+ return bucket !== void 0 && bucket.length > 0 ? { bucket } : {};
1027
+ }
1028
+ function schemeOf(url) {
1029
+ const end = url.indexOf("://");
1030
+ return end === -1 ? url : url.slice(0, end);
1031
+ }
1032
+ // src/cli/deploy.ts
1033
+ /**
1034
+ * `vlo deploy` — write the platform templates for a profile, and stop there.
1035
+ *
1036
+ * Generation is not application. The files land in `--out` for review and commit; `--apply`
1037
+ * prints the exact `gcloud` / `terraform` / `vercel` commands rather than running them, so
1038
+ * the thing that touches a cloud account is always a human with credentials.
1039
+ */
1040
+ const USAGE$3 = "vlo deploy --profile <name> [--config <path>] [--out deploy/vlo] [--apply]";
1041
+ /** Renders and writes; returns what was written, so tests can snapshot it. */
1042
+ async function deploy(options) {
1043
+ const plan = planDeploy(await loadConfig(options.cwd, options.profile, options.configPath));
1044
+ const files = render(plan);
1045
+ const out = resolve(options.cwd, options.out ?? "deploy/vlo");
1046
+ for (const file of files) {
1047
+ const target = resolve(out, file.path);
1048
+ await mkdir(dirname(target), { recursive: true });
1049
+ await writeFile(target, file.contents, "utf8");
1050
+ process.stdout.write(` ✓ ${relative(options.cwd, target)}\n`);
1051
+ }
1052
+ if (options.apply === true) {
1053
+ process.stdout.write(`\n ${plan.target} — run these yourself:\n\n`);
1054
+ for (const command of commands(plan)) process.stdout.write(command.length === 0 ? "\n" : ` ${command}\n`);
1055
+ process.stdout.write("\n");
1056
+ }
1057
+ return files;
1058
+ }
1059
+ async function deployCommand(argv, cwd = process.cwd()) {
1060
+ const { values } = parseArgs({
1061
+ args: [...argv],
1062
+ options: {
1063
+ config: { type: "string" },
1064
+ profile: { type: "string" },
1065
+ out: { type: "string" },
1066
+ apply: {
1067
+ type: "boolean",
1068
+ default: false
1069
+ }
1070
+ }
1071
+ });
1072
+ await deploy({
1073
+ cwd,
1074
+ profile: requireProfile(values, USAGE$3),
1075
+ ...values.config !== void 0 ? { configPath: values.config } : {},
1076
+ ...values.out !== void 0 ? { out: values.out } : {},
1077
+ apply: values.apply === true
1078
+ });
1079
+ }
1080
+ // src/cli/checks.ts
1081
+ /**
1082
+ * The checks behind `vlo doctor`.
1083
+ *
1084
+ * Every check is a real round trip, not a config read: the point is to fail here rather
1085
+ * than three minutes into a deploy. They use only the public journal, blob and kernel
1086
+ * surfaces, and they are cheap enough to run on every boot of a new environment — the blob
1087
+ * probe is content-addressed, so a re-run writes nothing.
1088
+ */
1089
+ const PROBE_BYTES = 1024;
1090
+ const MAX_WASM_BYTES = 1048576;
1091
+ const QUEUE_TIMEOUT_MS = 3e3;
1092
+ /** Same relative shape as `kernel/load.ts`: `wasm/` sits beside `src/` and beside `dist/`. */
1093
+ const WASM_CANDIDATES = ["../../wasm/vlo_kernel_bg.wasm", "../wasm/vlo_kernel_bg.wasm"];
1094
+ async function runChecks(loaded, options) {
1095
+ const checks = [];
1096
+ const journal = await checkJournal(checks, loaded, options);
1097
+ await checkBlob(checks, loaded);
1098
+ await checkKernel(checks);
1099
+ if (journal !== null) await checkSchemas(checks, loaded, journal);
1100
+ await checkQueues(checks, loaded, options.fetch ?? fetch);
1101
+ checkRoles(checks, loaded);
1102
+ if (journal !== null) await journal.close().catch(() => void 0);
1103
+ return checks;
1104
+ }
1105
+ /** Returns the open journal when it is usable, so later checks can reuse the connection. */
1106
+ async function checkJournal(checks, loaded, options) {
1107
+ const url = loaded.profile.journal;
1108
+ const dialect = url.startsWith("sqlite://") ? "sqlite" : "postgres";
1109
+ let journal;
1110
+ try {
1111
+ journal = openJournal(url);
1112
+ } catch (error) {
1113
+ checks.push({
1114
+ check: "journal",
1115
+ status: "fail",
1116
+ detail: message(error),
1117
+ hint: "journal must be a sqlite:// or postgres:// url"
1118
+ });
1119
+ return null;
1120
+ }
1121
+ let migrated;
1122
+ if (options.migrate) try {
1123
+ await journal.migrate();
1124
+ migrated = {
1125
+ check: "migrate",
1126
+ status: "ok",
1127
+ detail: "schema up to date"
1128
+ };
1129
+ } catch (error) {
1130
+ checks.push({
1131
+ check: "migrate",
1132
+ status: "fail",
1133
+ detail: message(error),
1134
+ hint: migrateHint(error)
1135
+ });
1136
+ await journal.close().catch(() => void 0);
1137
+ return null;
1138
+ }
1139
+ else migrated = {
1140
+ check: "migrate",
1141
+ status: "warn",
1142
+ detail: "skipped (--no-migrate)",
1143
+ hint: "re-run without --no-migrate to apply pending migrations"
1144
+ };
1145
+ const startedAt = Date.now();
1146
+ try {
1147
+ await journal.transaction((tx) => tx.lockRun("vlo-doctor"));
1148
+ } catch (error) {
1149
+ checks.push({
1150
+ check: "journal",
1151
+ status: "fail",
1152
+ detail: `${dialect} · ${message(error)}`,
1153
+ hint: options.migrate ? "check the journal url and that the database is reachable" : "the schema may be missing; re-run without --no-migrate"
1154
+ });
1155
+ checks.push(migrated);
1156
+ await journal.close().catch(() => void 0);
1157
+ return null;
1158
+ }
1159
+ checks.push({
1160
+ check: "journal",
1161
+ status: "ok",
1162
+ detail: `${dialect} · commit round trip ${Date.now() - startedAt} ms`
1163
+ }, migrated);
1164
+ return journal;
1165
+ }
1166
+ async function checkBlob(checks, loaded) {
1167
+ const url = loaded.profile.blob;
1168
+ try {
1169
+ const store = openBlobStore(url);
1170
+ const probe = new Uint8Array(PROBE_BYTES).fill(118);
1171
+ const digest = await store.put(probe);
1172
+ if (digest !== sha256Hex(probe)) {
1173
+ checks.push({
1174
+ check: "blob",
1175
+ status: "fail",
1176
+ detail: `${url} · put returned ${digest}, which is not the sha256 of the bytes`,
1177
+ hint: "the store is not content-addressed; payload refs would not resolve"
1178
+ });
1179
+ return;
1180
+ }
1181
+ const read = await store.get(digest);
1182
+ if (read.length !== probe.length) {
1183
+ checks.push({
1184
+ check: "blob",
1185
+ status: "fail",
1186
+ detail: `${url} · read back ${read.length} bytes, wrote ${probe.length}`,
1187
+ hint: "the store is truncating writes"
1188
+ });
1189
+ return;
1190
+ }
1191
+ checks.push({
1192
+ check: "blob",
1193
+ status: "ok",
1194
+ detail: `${url} · 1 KiB round trip`
1195
+ });
1196
+ } catch (error) {
1197
+ checks.push({
1198
+ check: "blob",
1199
+ status: "fail",
1200
+ detail: `${url} · ${message(error)}`,
1201
+ hint: "check the blob url and that the process may write there"
1202
+ });
1203
+ }
1204
+ }
1205
+ async function checkKernel(checks) {
1206
+ const bytes = wasmSize();
1207
+ if (bytes === null) {
1208
+ checks.push({
1209
+ check: "kernel",
1210
+ status: "fail",
1211
+ detail: "wasm not found",
1212
+ hint: "run scripts/build-kernel.sh from the vlo repo root, or set VLO_KERNEL_WASM"
1213
+ });
1214
+ return;
1215
+ }
1216
+ try {
1217
+ const kernel = await loadKernel();
1218
+ const kib = Math.round(bytes / 1024);
1219
+ const oversized = bytes > MAX_WASM_BYTES;
1220
+ checks.push({
1221
+ check: "kernel",
1222
+ status: oversized ? "warn" : "ok",
1223
+ detail: `protocol ${kernel.version().protocol} · ${kib} KiB`,
1224
+ ...oversized ? { hint: `over the ${MAX_WASM_BYTES / 1024} KiB budget; build with --release` } : {}
1225
+ });
1226
+ } catch (error) {
1227
+ checks.push({
1228
+ check: "kernel",
1229
+ status: "fail",
1230
+ detail: message(error),
1231
+ hint: `this SDK speaks protocol 1; rebuild the kernel`
1232
+ });
1233
+ }
1234
+ }
1235
+ function wasmSize() {
1236
+ const override = process.env["VLO_KERNEL_WASM"];
1237
+ const candidates = override !== void 0 && override !== "" ? [override] : WASM_CANDIDATES.map((c) => new URL(c, import.meta.url));
1238
+ for (const candidate of candidates) try {
1239
+ return statSync(candidate).size;
1240
+ } catch {
1241
+ continue;
1242
+ }
1243
+ return null;
1244
+ }
1245
+ /**
1246
+ * Registered activities and signals against the `schemas` table. A miss is not an error:
1247
+ * the host upserts every schema on boot. It is worth saying out loud, because a miss also
1248
+ * means no other process has booted this build yet.
1249
+ */
1250
+ async function checkSchemas(checks, loaded, journal) {
1251
+ const wanted = [...loaded.activities.map((a) => ({
1252
+ name: a.name,
1253
+ version: a.hash
1254
+ })), ...loaded.signals.map((s) => ({
1255
+ name: s.name,
1256
+ version: s.hash
1257
+ }))].filter((s) => s.version !== void 0);
1258
+ if (wanted.length === 0) {
1259
+ checks.push({
1260
+ check: "schemas",
1261
+ status: "ok",
1262
+ detail: "none declared"
1263
+ });
1264
+ return;
1265
+ }
1266
+ try {
1267
+ const missing = await journal.transaction(async (tx) => {
1268
+ const absent = [];
1269
+ for (const { name, version } of wanted) if (await tx.getSchema(name, version) === null) absent.push(name);
1270
+ return absent;
1271
+ });
1272
+ checks.push({
1273
+ check: "schemas",
1274
+ status: missing.length === 0 ? "ok" : "warn",
1275
+ detail: missing.length === 0 ? `${wanted.length} registered` : `${wanted.length - missing.length}/${wanted.length} registered · missing ${missing.join(" · ")}`,
1276
+ ...missing.length === 0 ? {} : { hint: "these register on the next host boot" }
1277
+ });
1278
+ } catch (error) {
1279
+ checks.push({
1280
+ check: "schemas",
1281
+ status: "fail",
1282
+ detail: message(error)
1283
+ });
1284
+ }
1285
+ }
1286
+ async function checkQueues(checks, loaded, doFetch) {
1287
+ const queues = Object.entries(loaded.profile.queues);
1288
+ if (queues.length === 0) {
1289
+ checks.push({
1290
+ check: "queues",
1291
+ status: "ok",
1292
+ detail: "none configured · in-process only"
1293
+ });
1294
+ return;
1295
+ }
1296
+ for (const [name, config] of queues) {
1297
+ const label = `queue:${name}`;
1298
+ if (config.mode === "pull") {
1299
+ checks.push({
1300
+ check: label,
1301
+ status: "ok",
1302
+ detail: "pull · served by pollers"
1303
+ });
1304
+ continue;
1305
+ }
1306
+ if (config.url === void 0) {
1307
+ const worker = loaded.workers.find((w) => w.queues.includes(name));
1308
+ checks.push(worker !== void 0 ? {
1309
+ check: label,
1310
+ status: "ok",
1311
+ detail: "in-process"
1312
+ } : {
1313
+ check: label,
1314
+ status: "fail",
1315
+ detail: "no url and no in-process worker",
1316
+ hint: `give the queue a url, or export defineWorker({ … }, { queues: ["${name}"] })`
1317
+ });
1318
+ continue;
1319
+ }
1320
+ checks.push(await probeQueue(label, config.url, config.secret, doFetch));
1321
+ }
1322
+ }
1323
+ async function probeQueue(label, url, secret, doFetch) {
1324
+ const unsigned = secret === void 0 || secret.length === 0;
1325
+ let health;
1326
+ try {
1327
+ health = new URL("/healthz", url);
1328
+ } catch {
1329
+ return {
1330
+ check: label,
1331
+ status: "fail",
1332
+ detail: `${url} is not a url`,
1333
+ hint: "queue url must be absolute"
1334
+ };
1335
+ }
1336
+ try {
1337
+ const response = await doFetch(health, { signal: AbortSignal.timeout(QUEUE_TIMEOUT_MS) });
1338
+ if (!response.ok) return {
1339
+ check: label,
1340
+ status: "fail",
1341
+ detail: `push · ${health.href} → ${response.status}`,
1342
+ hint: "the worker host is up but not healthy"
1343
+ };
1344
+ } catch (error) {
1345
+ return {
1346
+ check: label,
1347
+ status: "fail",
1348
+ detail: `push · ${health.href} unreachable: ${message(error)}`,
1349
+ hint: "start the worker host, or fix the queue url"
1350
+ };
1351
+ }
1352
+ return {
1353
+ check: label,
1354
+ status: unsigned ? "warn" : "ok",
1355
+ detail: `push · ${health.href} reachable${unsigned ? " · no secret" : ""}`,
1356
+ ...unsigned ? { hint: "set `secret` on the queue; unsigned pushes are rejected by the worker" } : {}
1357
+ };
1358
+ }
1359
+ function checkRoles(checks, loaded) {
1360
+ const { roles, dispatcher, deploy } = loaded.profile;
1361
+ const listed = roles ?? [
1362
+ "orchestrator",
1363
+ "api",
1364
+ "worker:*"
1365
+ ];
1366
+ const mode = dispatcher?.mode ?? "loop";
1367
+ const detail = `${listed.join(" · ")} · dispatcher ${mode}`;
1368
+ const stalled = listed.includes("orchestrator") && mode === "manual" && deploy?.cron === void 0;
1369
+ checks.push({
1370
+ check: "roles",
1371
+ status: stalled ? "warn" : "ok",
1372
+ detail,
1373
+ ...stalled ? { hint: "a manual dispatcher only advances on POST /v1/timers/tick; set `deploy.cron`" } : {}
1374
+ });
1375
+ }
1376
+ function message(error) {
1377
+ return error instanceof Error ? error.message : String(error);
1378
+ }
1379
+ /** A hint that matches the failure: reachability and auth are far more common than DDL rights. */
1380
+ function migrateHint(error) {
1381
+ const text = message(error);
1382
+ if (/ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|timeout/i.test(text)) return "the journal is unreachable: check the url, host and port, and that the database is running";
1383
+ if (/password|authentication|no pg_hba/i.test(text)) return "the journal rejected the credentials in the url";
1384
+ if (/does not exist/i.test(text)) return "the database named in the url does not exist";
1385
+ if (/permission denied for database/i.test(text)) return "the journal user cannot create the schema: GRANT CREATE ON DATABASE to it, or have a DBA run CREATE SCHEMA <name> AUTHORIZATION <user>";
1386
+ return "the journal user needs CREATE on its schema";
1387
+ }
1388
+ // src/cli/doctor.ts
1389
+ /**
1390
+ * `vlo doctor` — is this profile actually wired up?
1391
+ *
1392
+ * Every line is a real round trip (see `checks.ts`), rendered as one table with a fix hint
1393
+ * on anything that is not ✓. Any ✗ sets a non-zero exit code, so a deploy pipeline can gate
1394
+ * on it; `--json` prints the same array for a machine.
1395
+ */
1396
+ const USAGE$2 = "vlo doctor --profile <name> [--config <path>] [--json] [--no-migrate]";
1397
+ const ICONS = {
1398
+ ok: "✓",
1399
+ warn: "⚠",
1400
+ fail: "✗"
1401
+ };
1402
+ /** The whole verb minus argument parsing and printing, so tests can assert on the checks. */
1403
+ async function doctor(options) {
1404
+ return runChecks(await loadConfig(options.cwd, options.profile, options.configPath), {
1405
+ migrate: options.migrate ?? true,
1406
+ ...options.fetch !== void 0 ? { fetch: options.fetch } : {}
1407
+ });
1408
+ }
1409
+ async function doctorCommand(argv, cwd = process.cwd()) {
1410
+ const { values } = parseArgs({
1411
+ args: [...argv],
1412
+ allowNegative: true,
1413
+ options: {
1414
+ config: { type: "string" },
1415
+ profile: { type: "string" },
1416
+ json: {
1417
+ type: "boolean",
1418
+ default: false
1419
+ },
1420
+ migrate: {
1421
+ type: "boolean",
1422
+ default: true
1423
+ }
1424
+ }
1425
+ });
1426
+ const checks = await doctor({
1427
+ cwd,
1428
+ profile: requireProfile(values, USAGE$2),
1429
+ ...values.config !== void 0 ? { configPath: values.config } : {},
1430
+ migrate: values.migrate !== false
1431
+ });
1432
+ process.stdout.write(values.json === true ? `${JSON.stringify(checks, null, 2)}\n` : table(checks));
1433
+ if (checks.some((c) => c.status === "fail")) process.exitCode = 1;
1434
+ }
1435
+ function table(checks) {
1436
+ const width = Math.max(0, ...checks.map((c) => c.check.length));
1437
+ let out = "";
1438
+ for (const check of checks) {
1439
+ out += ` ${ICONS[check.status]} ${check.check.padEnd(width)} ${check.detail}\n`;
1440
+ if (check.hint !== void 0) out += ` ${" ".repeat(width + 3)} → ${check.hint}\n`;
1441
+ }
1442
+ return out;
1443
+ }
1444
+ // src/cli/serve.ts
1445
+ /**
1446
+ * `vlo serve` — the production twin of `vlo dev`.
1447
+ *
1448
+ * Same code path, no conveniences: the profile is required (there is no SQLite fallback to
1449
+ * silently land on), nothing is created on disk, and `PORT` is honoured because that is how
1450
+ * Cloud Run and every other container platform tells a process where to listen.
1451
+ */
1452
+ const USAGE$1 = "vlo serve --profile <name> [--config <path>] [--port <n>]";
1453
+ async function serveCommand(argv, cwd = process.cwd()) {
1454
+ const { values } = parseArgs({
1455
+ args: [...argv],
1456
+ options: {
1457
+ config: { type: "string" },
1458
+ profile: { type: "string" },
1459
+ port: { type: "string" }
1460
+ }
1461
+ });
1462
+ const profile = requireProfile(values, USAGE$1);
1463
+ const port = values.port ?? process.env["PORT"];
1464
+ return start({
1465
+ cwd,
1466
+ profile,
1467
+ ...values.config !== void 0 ? { configPath: values.config } : {},
1468
+ ...port !== void 0 && port.length > 0 ? { port: Number(port) } : {}
1469
+ });
1470
+ }
1471
+ // src/cli.ts
1472
+ /**
1473
+ * The `vlo` command: one verb per file under `cli/`.
1474
+ *
1475
+ * `dev` and `serve` are the same host with different defaults — that is deliberate, and it
1476
+ * is why `doctor` and `deploy` read the same profile: whatever runs on a laptop, what a
1477
+ * check reports and what a template deploys all come from one place in `vlo.config.ts`.
1478
+ */
1479
+ const VERB_USAGE = {
1480
+ dev: USAGE$4,
1481
+ serve: USAGE$1,
1482
+ doctor: USAGE$2,
1483
+ deploy: USAGE$3
1484
+ };
1485
+ const USAGE = [
1486
+ ...Object.values(VERB_USAGE),
1487
+ "vlo --help | -h | help",
1488
+ "vlo --version | -v"
1489
+ ].join("\n");
1490
+ async function main(argv = process.argv.slice(2), cwd = process.cwd()) {
1491
+ const [verb, ...rest] = argv;
1492
+ if (verb === void 0 || verb === "help" || wantsHelp([verb])) {
1493
+ process.stdout.write(`${USAGE}\n`);
1494
+ return;
1495
+ }
1496
+ if (verb === "--version" || verb === "-v") {
1497
+ process.stdout.write(`${version()}\n`);
1498
+ return;
1499
+ }
1500
+ const usage = VERB_USAGE[verb];
1501
+ if (usage !== void 0 && wantsHelp(rest)) {
1502
+ process.stdout.write(`${usage}\n`);
1503
+ return;
1504
+ }
1505
+ switch (verb) {
1506
+ case "dev":
1507
+ await dev(rest, cwd);
1508
+ return;
1509
+ case "serve":
1510
+ await serveCommand(rest, cwd);
1511
+ return;
1512
+ case "doctor":
1513
+ await doctorCommand(rest, cwd);
1514
+ return;
1515
+ case "deploy":
1516
+ await deployCommand(rest, cwd);
1517
+ return;
1518
+ default:
1519
+ process.stderr.write(`unknown command "${verb}"\n${USAGE}\n`);
1520
+ process.exitCode = 1;
1521
+ }
1522
+ }
1523
+ /**
1524
+ * True when this module is the process entry point. An installed `vlo` is launched through a
1525
+ * symlink in `node_modules/.bin`, so the launch path is resolved before it is compared.
1526
+ */
1527
+ function isEntryPoint() {
1528
+ const launched = process.argv[1];
1529
+ if (launched === void 0) return false;
1530
+ try {
1531
+ return realpathSync(launched) === realpathSync(fileURLToPath(import.meta.url));
1532
+ } catch {
1533
+ return false;
1534
+ }
1535
+ }
1536
+ if (isEntryPoint()) main().catch((error) => {
1537
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
1538
+ process.exitCode = 1;
1539
+ });
1540
+ export { main };