hazo_env 0.10.4 → 0.12.1

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.
Files changed (53) hide show
  1. package/CHANGE_LOG.md +79 -0
  2. package/config/hazo_env_config.ini.sample +61 -0
  3. package/dist/cli.js +329 -0
  4. package/dist/deploy/build.d.ts +91 -0
  5. package/dist/deploy/build.d.ts.map +1 -0
  6. package/dist/deploy/build.js +389 -0
  7. package/dist/deploy/clean.d.ts +63 -0
  8. package/dist/deploy/clean.d.ts.map +1 -0
  9. package/dist/deploy/clean.js +135 -0
  10. package/dist/deploy/index.d.ts +13 -0
  11. package/dist/deploy/index.d.ts.map +1 -0
  12. package/dist/deploy/index.js +22 -0
  13. package/dist/deploy/init.d.ts +20 -0
  14. package/dist/deploy/init.d.ts.map +1 -0
  15. package/dist/deploy/init.js +131 -0
  16. package/dist/deploy/peer.d.ts +18 -0
  17. package/dist/deploy/peer.d.ts.map +1 -0
  18. package/dist/deploy/peer.js +48 -0
  19. package/dist/deploy/pm2-start.d.ts +100 -0
  20. package/dist/deploy/pm2-start.d.ts.map +1 -0
  21. package/dist/deploy/pm2-start.js +228 -0
  22. package/dist/deploy/rollback.d.ts +22 -0
  23. package/dist/deploy/rollback.d.ts.map +1 -0
  24. package/dist/deploy/rollback.js +196 -0
  25. package/dist/deploy/runner.d.ts +8 -0
  26. package/dist/deploy/runner.d.ts.map +1 -0
  27. package/dist/deploy/runner.js +35 -0
  28. package/dist/deploy/state.d.ts +19 -0
  29. package/dist/deploy/state.d.ts.map +1 -0
  30. package/dist/deploy/state.js +52 -0
  31. package/dist/deploy/status.d.ts +54 -0
  32. package/dist/deploy/status.d.ts.map +1 -0
  33. package/dist/deploy/status.js +182 -0
  34. package/dist/deploy/switch.d.ts +40 -0
  35. package/dist/deploy/switch.d.ts.map +1 -0
  36. package/dist/deploy/switch.js +183 -0
  37. package/dist/deploy/types.d.ts +96 -0
  38. package/dist/deploy/types.d.ts.map +1 -0
  39. package/dist/deploy/types.js +16 -0
  40. package/dist/deploy/verify.d.ts +41 -0
  41. package/dist/deploy/verify.d.ts.map +1 -0
  42. package/dist/deploy/verify.js +214 -0
  43. package/dist/index.d.ts +2 -0
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +3 -0
  46. package/dist/resolve/connect.d.ts.map +1 -1
  47. package/dist/resolve/connect.js +15 -1
  48. package/dist/resolve/deploy.d.ts +8 -0
  49. package/dist/resolve/deploy.d.ts.map +1 -0
  50. package/dist/resolve/deploy.js +140 -0
  51. package/dist/types/index.d.ts +10 -0
  52. package/dist/types/index.d.ts.map +1 -1
  53. package/package.json +12 -12
package/CHANGE_LOG.md CHANGED
@@ -1,5 +1,84 @@
1
1
  # hazo_env — Change Log
2
2
 
3
+ ## 0.12.1 — 2026-11-07
4
+
5
+ Fix: `deploy build` health check now retries on connection-refused. `checkHealth`
6
+ used `runner.exec` (throws on non-zero curl exit) instead of `runner.spawn`
7
+ (returns the result), so the very first attempt — which almost always hits
8
+ connection-refused because PM2 returns before the app finishes booting — aborted
9
+ the entire health check with zero retries. Switched to `runner.spawn` and
10
+ encoded curl's own exit code as `curl_exit_<N>` in the `lastCode` field so the
11
+ retry loop and error message both work correctly.
12
+
13
+ ## 0.12.0 — 2026-10-24
14
+
15
+ New: `hazo-env deploy` — a full blue-green deployment CLI for single-VM sites
16
+ that maintain two sibling directories differing only by a blue/green suffix
17
+ (e.g. `gotimer-blue/`, `gotimer-green/`), orchestrated entirely through a new
18
+ `[deploy]` ini section and a state file at `~/.hazo-deploy/<app_name>.json`:
19
+
20
+ - `deploy init` — creates the peer directory, clones the repo into it, and
21
+ writes the initial state file.
22
+ - `deploy build` — runs the full standby build pipeline (pre-build/install/
23
+ build, DB provisioning via `db_strategy`, an optional `migrate_cmd`) and
24
+ starts the result as `<app_name>-staging` on `staging_port` for
25
+ health-checking before switch.
26
+ - `deploy verify` — re-runs health/typecheck/migration checks against the
27
+ standby build without switching.
28
+ - `deploy switch` — promotes standby to live and demotes live to standby.
29
+ - `deploy rollback` — reverses the last `deploy switch` in one command, using
30
+ `previous_live_dir` recorded by switch; aborts with a clear message if
31
+ there's no switch left to reverse (either none has run, or a prior
32
+ rollback already consumed it). `previous_live_dir` is deliberately
33
+ cleared (not repopulated) by rollback itself, so a rollback is a one-shot
34
+ recovery action rather than a live/standby toggle — see `src/deploy/
35
+ rollback.ts`'s header for the full reasoning.
36
+ - `deploy status` — reports live/standby dirs, ports, PM2 process state, and
37
+ disk/memory headroom.
38
+ - `deploy clean` — reclaims disk space from old builds/caches, with
39
+ `--aggressive` system-level cleanup suggestions.
40
+
41
+ Both `deploy build`'s staging start and `deploy switch`/`deploy rollback`'s
42
+ live-promotion start share one hardened primitive, `startNamedPm2Process`
43
+ (`src/deploy/pm2-start.ts`): `pm2 start ecosystem.config.js --name X` does
44
+ NOT rename the process when starting from a config file — pm2 reads the
45
+ name baked into the file itself and ignores the CLI override — so a direct
46
+ call silently restarts (or no-ops against) whatever was already registered
47
+ under the ecosystem file's real name instead of creating a distinct
48
+ process. The shared helper clones the target dir's ecosystem.config.js with
49
+ name/cwd/port overridden into a per-call temp file and starts from THAT
50
+ file instead. Every step that replaces a PM2 registration uses `pm2
51
+ delete`, never `stop` — `stop` leaves the old registration's `pm_cwd`
52
+ pointing at the old directory, so the next start under the same name would
53
+ just restart it in place rather than registering fresh against the new
54
+ directory.
55
+
56
+ ## 0.11.0 — 2026-10-21
57
+
58
+ New: `[db.<env>]`'s `type = sqlite` section now accepts an optional `driver` key
59
+ (`sql.js` or `better-sqlite3`), passed straight through to hazo_connect as
60
+ `sqlite.driver`. `resolveConnectConfig()` previously only ever forwarded
61
+ `database_path`, so hazo_connect's own `better-sqlite3` driver — the one built for
62
+ safe multi-connection access to one file — was unreachable from the ini; every
63
+ `resolveConnectConfig()`-driven app was silently stuck on the `sql.js` default
64
+ regardless of what it configured.
65
+
66
+ Found while root-causing a Quizaboo dev bug: Next.js dev compiles `middleware.ts`
67
+ separately from route handlers, so a `db` singleton built from
68
+ `resolveConnectConfig()` and imported in both ends up as two independent processes'
69
+ worth of `sql.js` adapter, each holding its own in-memory copy of the same
70
+ `.sqlite` file and overwriting the whole file on every write — a torn read during
71
+ that overwrite loaded a corrupted buffer in one of them, producing an intermittent
72
+ `database disk image is malformed` on every request in that bundle until restart.
73
+ hazo_connect's `better-sqlite3` driver (real OS-level WAL locking, safe for
74
+ concurrent connections) already exists for exactly this; this fix just makes it
75
+ reachable via the ini an app actually configures. An unrecognized `driver` value
76
+ throws `HAZO_ENV_CONFIG_UNKNOWN_SQLITE_DRIVER` at config-resolve time rather than
77
+ surfacing later as hazo_connect's generic "Unsupported connection type".
78
+
79
+ Backward compatible: omitting `driver` keeps the existing `sql.js` default
80
+ behavior unchanged.
81
+
3
82
  ## 0.10.4 — 2026-10-11
4
83
 
5
84
  Bug fix: `hazo-env doctor --probe`'s SQLite DB-probe check crashed with
@@ -35,6 +35,17 @@ root = app_data
35
35
  ; SQLite database for local development
36
36
  type = sqlite
37
37
  database_path = ${DATA_ROOT}/dev.sqlite
38
+ ; Optional: which SQLite engine hazo_connect opens the file with.
39
+ ; sql.js (default) — zero native deps, but keeps one in-memory copy per
40
+ ; process and overwrites the whole file on every write. Safe only when
41
+ ; exactly one process ever touches database_path. A Next.js dev server
42
+ ; already breaks that assumption on its own (middleware.ts compiles as a
43
+ ; separate bundle from route handlers, each importing its own copy), and
44
+ ; it WILL corrupt the file under concurrent access.
45
+ ; better-sqlite3 — opens the file natively with real OS-level WAL locking;
46
+ ; safe for multiple connections/processes against the same file. Needs
47
+ ; the optional `better-sqlite3` package installed.
48
+ ; driver = better-sqlite3
38
49
 
39
50
  [db.test]
40
51
  ; SQLite database for automated tests
@@ -122,3 +133,53 @@ path = /home/pubs/kinstripe/var/uploads
122
133
  ; strict and pinned — no trust-on-first-use. When omitted, the first connection
123
134
  ; is accepted (accept-new) and persisted to config/hazo_env_known_hosts.
124
135
  ; host_key = ${SSH_HOST_KEY_PROD}
136
+
137
+ ; ─── deploy: blue-green deployment orchestration ─────────────────────────────
138
+ ; Drives `hazo-env deploy ...` (init/build/verify/switch/rollback/status/clean).
139
+ ; Sites maintain two sibling directories differing only by a blue/green
140
+ ; suffix (e.g. gotimer-blue/, gotimer-green/). Only app_name and dir_suffix
141
+ ; are required — every other field has a sane default.
142
+
143
+ [deploy]
144
+ ; Logical app name. Also names the state file: ~/.hazo-deploy/<app_name>.json
145
+ app_name = myapp
146
+ ; Which color suffix THIS directory is (the peer is resolved by swapping
147
+ ; blue<->green on the current directory's basename). Required, no default.
148
+ dir_suffix = green
149
+
150
+ ; Production PM2 port. Default: 3000
151
+ prod_port = 3000
152
+ ; Staging port used by `deploy build`/`deploy verify` before switching. Default: 3001
153
+ staging_port = 3001
154
+ ; Path hit for health checks during build/verify/status. Default: /api/health
155
+ health_url = /api/health
156
+
157
+ ; Minimum free disk (MB) required before a build proceeds. Default: 1024
158
+ min_disk_mb = 1024
159
+ ; Minimum free memory (MB) required before a build proceeds. Default: 512
160
+ min_memory_mb = 512
161
+
162
+ ; Git branch pulled by `deploy build` (overridable with --branch). Default: main
163
+ branch = main
164
+ ; How the standby DB is provisioned: auto (infer from [db.*] driver), copy
165
+ ; (sqlite file copy from peer), or shared (point at the same Postgres DB).
166
+ ; Default: auto
167
+ db_strategy = auto
168
+
169
+ ; Shell commands for the build pipeline. Defaults shown.
170
+ pre_build_cmd = rm -rf .next
171
+ install_cmd = npm ci
172
+ build_cmd = npm run build
173
+
174
+ ; Optional shell command run after DB setup during `deploy build`. Migrations
175
+ ; are project-specific (no generic cross-project migration runner lives in
176
+ ; this package), so the default is empty — "deploy build" then logs that it's
177
+ ; assuming the consuming app's own schema bootstrap runs automatically at
178
+ ; startup and moves on. Set this when the app needs an explicit migration step.
179
+ ; migrate_cmd = npm run db:migrate
180
+
181
+ ; Optional shell commands run after a successful `deploy switch` (indexnow
182
+ ; submission, CDN cache purge, ...). Numbered suffixes (_2, _3, ...) run in
183
+ ; order after the unsuffixed post_switch_cmd. Omit entirely to run none.
184
+ ; post_switch_cmd = npm run indexnow
185
+ ; post_switch_cmd_2 = bash scripts/cf-purge.sh
package/dist/cli.js CHANGED
@@ -201,6 +201,330 @@ async function runServe() {
201
201
  process.exit(1);
202
202
  }
203
203
  }
204
+ const DEPLOY_SUBCOMMANDS = ['init', 'build', 'verify', 'switch', 'rollback', 'status', 'clean'];
205
+ function printDeployHelp() {
206
+ console.log(`
207
+ ${pc.bold('hazo-env deploy')} — blue-green deployment orchestration
208
+
209
+ Usage:
210
+ hazo-env deploy init Create peer dir, clone repo, generate config, write state
211
+ hazo-env deploy build Run the full build pipeline on the standby dir
212
+ --stop-prod --branch=<b> --db=<env> --peer-dir=<path>
213
+ hazo-env deploy verify Re-run health/typecheck/migration checks on standby
214
+ hazo-env deploy switch Stop prod, start standby on the prod port, run post-switch hooks
215
+ --force Bypass the "standby must have a successful recent build" check
216
+ hazo-env deploy rollback Reverse the last switch
217
+ hazo-env deploy status Show live/standby dirs, ports, PM2 state, disk/memory
218
+ hazo-env deploy clean Reclaim disk space from old builds and caches
219
+ --aggressive Also suggest system-level cleanup commands
220
+ `);
221
+ }
222
+ function formatDirStatus(info) {
223
+ const indicator = info.running ? pc.green(`✓ running (pid ${info.pid})`) : pc.dim('✗ not running');
224
+ return ` ${pc.bold(info.role.padEnd(8))} ${info.dir} ${pc.dim(`port ${info.port}`)} ${indicator}`;
225
+ }
226
+ async function runDeployStatus() {
227
+ const { resolveDeployConfig } = await import('./resolve/deploy.js');
228
+ const { runStatus } = await import('./deploy/status.js');
229
+ const { nodeCommandRunner } = await import('./deploy/runner.js');
230
+ const config = resolveDeployConfig();
231
+ const result = runStatus(config, nodeCommandRunner);
232
+ console.log(`\n${pc.bold(`hazo-env deploy status`)} ${pc.dim(result.appName)}\n`);
233
+ if (!result.stateFound) {
234
+ console.log(` ${pc.yellow('⚠')} No deploy state found yet — run "hazo-env deploy init" first.\n`);
235
+ }
236
+ else {
237
+ if (result.live)
238
+ console.log(formatDirStatus(result.live));
239
+ if (result.standby)
240
+ console.log(formatDirStatus(result.standby));
241
+ console.log('');
242
+ console.log(` last switch: ${result.lastSwitch ?? pc.dim('(none)')}`);
243
+ console.log(` last build: ${result.lastBuild ?? pc.dim('(none)')}${result.lastBuildStatus ? ` ${result.lastBuildStatus === 'success' ? pc.green(result.lastBuildStatus) : pc.red(result.lastBuildStatus)}` : ''}`);
244
+ console.log('');
245
+ }
246
+ const diskLine = result.diskFreeMb !== undefined ? `${result.diskFreeMb} MB free` : pc.dim('(unknown)');
247
+ console.log(` disk: ${diskLine}`);
248
+ const memValue = result.memoryFreeMb !== undefined ? `${result.memoryFreeMb} MB free` : pc.dim('(unknown)');
249
+ const memLine = result.memoryLow ? `${pc.yellow(memValue)} ${pc.yellow(`⚠ below min_memory_mb (${result.minMemoryMb})`)}` : memValue;
250
+ console.log(` memory: ${memLine}`);
251
+ if (result.warnings.length) {
252
+ console.log('');
253
+ for (const warning of result.warnings) {
254
+ console.log(` ${pc.yellow('⚠')} ${warning}`);
255
+ }
256
+ }
257
+ console.log('');
258
+ }
259
+ async function runDeployInit() {
260
+ const { resolveDeployConfig } = await import('./resolve/deploy.js');
261
+ const { runInit } = await import('./deploy/init.js');
262
+ const { nodeCommandRunner } = await import('./deploy/runner.js');
263
+ const config = resolveDeployConfig();
264
+ console.log(`\n${pc.bold('hazo-env deploy init')} ${pc.dim(config.app_name)}\n`);
265
+ try {
266
+ const result = runInit(config, nodeCommandRunner);
267
+ console.log(` ${pc.green('✓')} Peer directory created: ${result.peerDir}`);
268
+ console.log(` ${pc.dim(`cloned from ${result.originUrl}`)}`);
269
+ console.log('');
270
+ console.log(` Next steps:`);
271
+ console.log(` cd ${result.peerDir}`);
272
+ console.log(` hazo-env deploy build`);
273
+ console.log('');
274
+ }
275
+ catch (e) {
276
+ const msg = e instanceof Error ? e.message : String(e);
277
+ console.error(`\n ${pc.red('✗')} ${msg}\n`);
278
+ process.exit(1);
279
+ }
280
+ }
281
+ function formatBytes(bytes) {
282
+ if (bytes >= 1024 * 1024 * 1024)
283
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
284
+ if (bytes >= 1024 * 1024)
285
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
286
+ if (bytes >= 1024)
287
+ return `${(bytes / 1024).toFixed(1)} KB`;
288
+ return `${bytes} B`;
289
+ }
290
+ async function runDeployClean() {
291
+ const { resolveDeployConfig } = await import('./resolve/deploy.js');
292
+ const { runClean } = await import('./deploy/clean.js');
293
+ const { nodeCommandRunner } = await import('./deploy/runner.js');
294
+ const aggressive = args.includes('--aggressive');
295
+ const config = resolveDeployConfig();
296
+ console.log(`\n${pc.bold('hazo-env deploy clean')} ${pc.dim(config.app_name)}\n`);
297
+ const result = runClean(config, nodeCommandRunner, { aggressive });
298
+ for (const target of result.targets) {
299
+ if (target.skipped) {
300
+ console.log(` ${pc.dim('·')} ${target.target.padEnd(20)} ${pc.dim('(not present)')}`);
301
+ }
302
+ else if (target.error) {
303
+ console.log(` ${pc.red('✗')} ${target.target.padEnd(20)} ${pc.red(target.error)}`);
304
+ }
305
+ else {
306
+ console.log(` ${pc.green('✓')} ${target.target.padEnd(20)} ${pc.dim(`reclaimed ${formatBytes(target.bytesReclaimed)}`)}`);
307
+ }
308
+ }
309
+ console.log('');
310
+ console.log(` ${pc.bold('total reclaimed:')} ${formatBytes(result.totalBytesReclaimed)}`);
311
+ console.log('');
312
+ if (result.warnings.length) {
313
+ for (const warning of result.warnings) {
314
+ console.log(` ${pc.yellow('⚠')} ${warning}`);
315
+ }
316
+ console.log('');
317
+ }
318
+ if (result.swapSuggestions.length) {
319
+ const memValue = result.memoryFreeMb !== undefined ? `${result.memoryFreeMb} MB free` : '(unknown)';
320
+ console.log(` ${pc.yellow('⚠')} Free memory (${memValue}) is below min_memory_mb (${result.minMemoryMb}).`);
321
+ console.log(` ${pc.dim('Consider increasing swap (not executed — requires sudo):')}`);
322
+ for (const cmd of result.swapSuggestions) {
323
+ console.log(` ${pc.dim('$')} ${cmd}`);
324
+ }
325
+ console.log('');
326
+ }
327
+ if (aggressive) {
328
+ console.log(` ${pc.dim('--aggressive: suggested system-level cleanup (not executed — requires sudo):')}`);
329
+ for (const cmd of result.systemSuggestions) {
330
+ console.log(` ${pc.dim('$')} ${cmd}`);
331
+ }
332
+ console.log('');
333
+ }
334
+ }
335
+ function flagValue(flagArgs, name) {
336
+ const idx = flagArgs.findIndex((a) => a === `--${name}`);
337
+ if (idx >= 0)
338
+ return flagArgs[idx + 1];
339
+ const inline = flagArgs.find((a) => a.startsWith(`--${name}=`));
340
+ return inline?.split('=').slice(1).join('=');
341
+ }
342
+ async function runDeployBuild() {
343
+ const { resolveDeployConfig } = await import('./resolve/deploy.js');
344
+ const { runBuild, BuildAbortError } = await import('./deploy/build.js');
345
+ const { nodeCommandRunner } = await import('./deploy/runner.js');
346
+ const stopProd = args.includes('--stop-prod');
347
+ const branch = flagValue(args, 'branch');
348
+ const db = flagValue(args, 'db');
349
+ const peerDir = flagValue(args, 'peer-dir');
350
+ const config = resolveDeployConfig();
351
+ console.log(`\n${pc.bold('hazo-env deploy build')} ${pc.dim(config.app_name)}\n`);
352
+ function printSteps(steps) {
353
+ for (const step of steps) {
354
+ const icon = step.status === 'pass' ? pc.green('✓') : pc.red('✗');
355
+ const detail = step.detail ? ` ${pc.dim(step.detail)}` : '';
356
+ console.log(` ${icon} ${step.name.padEnd(16)}${detail}`);
357
+ }
358
+ }
359
+ try {
360
+ const result = runBuild(config, nodeCommandRunner, { stopProd, branch, db, peerDir });
361
+ console.log('');
362
+ printSteps(result.steps);
363
+ console.log('');
364
+ console.log(` ${pc.green('Build succeeded.')} staging: ${pc.bold(result.stagingUrl)} (db strategy: ${result.dbStrategyResolved})`);
365
+ console.log('');
366
+ console.log(` Next steps:`);
367
+ console.log(` hazo-env deploy verify`);
368
+ console.log(` hazo-env deploy switch`);
369
+ console.log('');
370
+ }
371
+ catch (e) {
372
+ if (e instanceof BuildAbortError) {
373
+ console.log('');
374
+ printSteps(e.steps);
375
+ console.log('');
376
+ console.error(` ${pc.red('✗ Build aborted:')} ${e.message}\n`);
377
+ process.exit(1);
378
+ return;
379
+ }
380
+ const msg = e instanceof Error ? e.message : String(e);
381
+ console.error(`\n ${pc.red('✗')} ${msg}\n`);
382
+ process.exit(1);
383
+ }
384
+ }
385
+ function verifyStatusIcon(status) {
386
+ if (status === 'pass')
387
+ return pc.green('✓');
388
+ if (status === 'skipped')
389
+ return pc.yellow('–');
390
+ return pc.red('✗');
391
+ }
392
+ async function runDeployVerify() {
393
+ const { resolveDeployConfig } = await import('./resolve/deploy.js');
394
+ const { runVerify } = await import('./deploy/verify.js');
395
+ const { nodeCommandRunner } = await import('./deploy/runner.js');
396
+ const config = resolveDeployConfig();
397
+ console.log(`\n${pc.bold('hazo-env deploy verify')} ${pc.dim(config.app_name)}\n`);
398
+ const result = runVerify(config, nodeCommandRunner);
399
+ const nameWidth = Math.max(...result.checks.map((c) => c.name.length)) + 2;
400
+ for (const check of result.checks) {
401
+ const icon = verifyStatusIcon(check.status);
402
+ console.log(` ${icon} ${check.name.padEnd(nameWidth)}${pc.dim(check.detail)}`);
403
+ }
404
+ console.log('');
405
+ if (result.allPassed) {
406
+ console.log(` ${pc.green('All checks passed.')} Next: ${pc.bold('hazo-env deploy switch')}\n`);
407
+ }
408
+ else {
409
+ console.log(` ${pc.red('Some checks failed.')} Fix the issue(s) above, then re-run ${pc.bold('hazo-env deploy verify')}.\n`);
410
+ process.exit(1);
411
+ }
412
+ }
413
+ async function runDeploySwitch() {
414
+ const { resolveDeployConfig } = await import('./resolve/deploy.js');
415
+ const { runSwitch, SwitchAbortError } = await import('./deploy/switch.js');
416
+ const { nodeCommandRunner } = await import('./deploy/runner.js');
417
+ const force = args.includes('--force');
418
+ const config = resolveDeployConfig();
419
+ console.log(`\n${pc.bold('hazo-env deploy switch')} ${pc.dim(config.app_name)}\n`);
420
+ try {
421
+ const result = runSwitch(config, nodeCommandRunner, { force });
422
+ console.log(` ${pc.green('✓')} deleted live PM2 registration "${config.app_name}" in ${result.previousLiveDir}`);
423
+ console.log(` ${result.stagingStopped ? pc.green('✓') : pc.dim('·')} staging process "${config.app_name}-staging"` +
424
+ `${result.stagingStopped ? ' stopped' : ' was not running (skipped)'}`);
425
+ if (result.stagingDeleteWarning) {
426
+ console.log(` ${pc.yellow('⚠')} ${result.stagingDeleteWarning}`);
427
+ }
428
+ console.log(` ${pc.green('✓')} started "${config.app_name}" on port ${result.prodPort} in ${result.newLiveDir}`);
429
+ if (result.pm2SaveWarning) {
430
+ console.log(` ${pc.yellow('⚠')} ${result.pm2SaveWarning}`);
431
+ }
432
+ console.log('');
433
+ if (result.postSwitchHooks.length) {
434
+ console.log(` post-switch hooks:`);
435
+ for (const hook of result.postSwitchHooks) {
436
+ const icon = hook.status === 'pass' ? pc.green('✓') : pc.red('✗');
437
+ console.log(` ${icon} ${hook.cmd}${hook.detail ? ` ${pc.dim(hook.detail)}` : ''}`);
438
+ }
439
+ console.log('');
440
+ }
441
+ console.log(` ${pc.green('Switch complete.')} live: ${pc.bold(result.newLiveDir)} (port ${result.prodPort})`);
442
+ console.log(` standby: ${result.newStandbyDir}`);
443
+ console.log('');
444
+ }
445
+ catch (e) {
446
+ if (e instanceof SwitchAbortError) {
447
+ console.error(`\n ${pc.red('✗')} ${e.message}\n`);
448
+ process.exit(1);
449
+ return;
450
+ }
451
+ const msg = e instanceof Error ? e.message : String(e);
452
+ console.error(`\n ${pc.red('✗')} ${msg}\n`);
453
+ process.exit(1);
454
+ }
455
+ }
456
+ async function runDeployRollback() {
457
+ const { resolveDeployConfig } = await import('./resolve/deploy.js');
458
+ const { runRollback, RollbackAbortError } = await import('./deploy/rollback.js');
459
+ const { nodeCommandRunner } = await import('./deploy/runner.js');
460
+ const config = resolveDeployConfig();
461
+ console.log(`\n${pc.bold('hazo-env deploy rollback')} ${pc.dim(config.app_name)}\n`);
462
+ try {
463
+ const result = runRollback(config, nodeCommandRunner);
464
+ console.log(` ${pc.green('✓')} started "${config.app_name}" on port ${result.prodPort} in ${result.restoredLiveDir}`);
465
+ if (result.stagingDeleteWarning) {
466
+ console.log(` ${pc.yellow('⚠')} ${result.stagingDeleteWarning}`);
467
+ }
468
+ if (result.pm2SaveWarning) {
469
+ console.log(` ${pc.yellow('⚠')} ${result.pm2SaveWarning}`);
470
+ }
471
+ console.log('');
472
+ console.log(` ${pc.green('rolled back')} to ${pc.bold(result.restoredLiveDir)}, running on port ${result.prodPort}.`);
473
+ console.log(` standby: ${result.newStandbyDir}`);
474
+ console.log('');
475
+ }
476
+ catch (e) {
477
+ if (e instanceof RollbackAbortError) {
478
+ console.error(`\n ${pc.red('✗')} ${e.message}\n`);
479
+ process.exit(1);
480
+ return;
481
+ }
482
+ const msg = e instanceof Error ? e.message : String(e);
483
+ console.error(`\n ${pc.red('✗')} ${msg}\n`);
484
+ process.exit(1);
485
+ }
486
+ }
487
+ async function runDeploy() {
488
+ const subCmd = args[0];
489
+ if (!subCmd || subCmd === '--help' || subCmd === '-h') {
490
+ printDeployHelp();
491
+ return;
492
+ }
493
+ if (!DEPLOY_SUBCOMMANDS.includes(subCmd)) {
494
+ console.error(pc.red(`Error: unknown deploy subcommand "${subCmd}"`));
495
+ printDeployHelp();
496
+ process.exit(1);
497
+ return;
498
+ }
499
+ if (subCmd === 'init') {
500
+ await runDeployInit();
501
+ return;
502
+ }
503
+ if (subCmd === 'status') {
504
+ await runDeployStatus();
505
+ return;
506
+ }
507
+ if (subCmd === 'clean') {
508
+ await runDeployClean();
509
+ return;
510
+ }
511
+ if (subCmd === 'build') {
512
+ await runDeployBuild();
513
+ return;
514
+ }
515
+ if (subCmd === 'verify') {
516
+ await runDeployVerify();
517
+ return;
518
+ }
519
+ if (subCmd === 'switch') {
520
+ await runDeploySwitch();
521
+ return;
522
+ }
523
+ if (subCmd === 'rollback') {
524
+ await runDeployRollback();
525
+ return;
526
+ }
527
+ }
204
528
  function printHelp() {
205
529
  console.log(`
206
530
  ${pc.bold('hazo-env')} — environment resolver CLI
@@ -222,6 +546,8 @@ Usage:
222
546
  --show-values Print env values in the diff (hidden by default)
223
547
  hazo-env serve Start the envsync HTTP service (HAZO_ENVSYNC_TOKEN required)
224
548
  --port <n> --bind <host> Override HAZO_ENVSYNC_PORT / HAZO_ENVSYNC_BIND
549
+ hazo-env deploy [subcommand] Blue-green deployment orchestration (see "deploy --help")
550
+ init | build | verify | switch | rollback | status | clean
225
551
  `);
226
552
  }
227
553
  (async () => {
@@ -238,6 +564,9 @@ Usage:
238
564
  else if (command === 'serve') {
239
565
  await runServe();
240
566
  }
567
+ else if (command === 'deploy') {
568
+ await runDeploy();
569
+ }
241
570
  else {
242
571
  printHelp();
243
572
  }
@@ -0,0 +1,91 @@
1
+ import type { CommandRunner, DeployConfig } from './types.js';
2
+ export interface RunBuildOptions {
3
+ /** Directory to treat as "current" (the standby dir being built). Defaults to process.cwd(). */
4
+ cwd?: string;
5
+ /** Stop the live PM2 process to free memory if the memory check fails. */
6
+ stopProd?: boolean;
7
+ /** Git branch to pull. Defaults to config.branch. */
8
+ branch?: string;
9
+ /** Postgres env name to resolve against [db.<env>] (shared db_strategy only). */
10
+ db?: string;
11
+ /** Explicit peer dir override. Takes precedence over the state file's live_dir. */
12
+ peerDir?: string;
13
+ /** Health check retry count. Default: 8. */
14
+ healthCheckAttempts?: number;
15
+ /** Delay between health check retries, in ms. Default: 1500. */
16
+ healthCheckDelayMs?: number;
17
+ }
18
+ export type BuildStepStatus = 'pass' | 'fail';
19
+ export interface BuildStepResult {
20
+ name: string;
21
+ status: BuildStepStatus;
22
+ detail?: string;
23
+ }
24
+ export interface RunBuildResult {
25
+ steps: BuildStepResult[];
26
+ stagingPort: number;
27
+ stagingUrl: string;
28
+ dbStrategyResolved: 'copy' | 'shared';
29
+ warnings: string[];
30
+ }
31
+ /** Thrown when any pipeline step fails. Carries the steps completed so far for reporting. */
32
+ export declare class BuildAbortError extends Error {
33
+ readonly steps: BuildStepResult[];
34
+ constructor(message: string, steps: BuildStepResult[]);
35
+ }
36
+ /**
37
+ * Re-root `targetPath` (known to live under `fromDir`) onto `toDir`: compute
38
+ * `targetPath`'s path relative to `fromDir` and rejoin it onto `toDir`.
39
+ *
40
+ * Falls back to `targetPath` unchanged when it isn't actually inside
41
+ * `fromDir` — e.g. an absolute `[data] root` (or an absolute db path)
42
+ * configured identically for both live and standby legitimately points at
43
+ * one shared location rather than a per-directory one, and in that case
44
+ * there's nothing to re-root; callers treat an unchanged result as "shared,
45
+ * skip the copy" rather than attempting a same-path no-op command.
46
+ *
47
+ * Exported so `deploy verify` (src/deploy/verify.ts) can re-root the standby
48
+ * sqlite db path onto the live dir for its migration-parity check, using the
49
+ * exact same live/standby path mapping this file's own db-setup step relies
50
+ * on, instead of duplicating it.
51
+ */
52
+ export declare function reroot(fromDir: string, toDir: string, targetPath: string): string;
53
+ /**
54
+ * Resolve a possibly-relative path against `baseDir` without touching an
55
+ * already-absolute one. Exported for the same reason as `reroot` above.
56
+ */
57
+ export declare function toAbsolute(baseDir: string, maybePath: string): string;
58
+ export interface HealthCheckResult {
59
+ ok: boolean;
60
+ lastCode: string;
61
+ attempts: number;
62
+ }
63
+ /**
64
+ * Poll `url` with curl up to `attempts` times, `delayMs` apart, succeeding on
65
+ * the first 200. `pm2 start` returns before the app has actually finished
66
+ * booting, so a single immediate check would almost always see
67
+ * connection-refused on a real deploy. Deliberately omits curl's `-f` (which
68
+ * makes curl itself exit non-zero — and `exec` throw — on a non-2xx
69
+ * response): `-w '%{http_code}'` needs the real status code in stdout so
70
+ * this function can judge pass/fail itself rather than only ever seeing
71
+ * "did curl's own exit code say ok".
72
+ *
73
+ * Exported so `deploy verify` (src/deploy/verify.ts) can reuse the exact same
74
+ * poll/retry logic for its own health check against the already-running
75
+ * staging app, instead of reimplementing it with a second curl-parsing
76
+ * helper. `deploy verify` passes a smaller `attempts`/`delayMs` budget by
77
+ * default — see verify.ts's doc comment for why.
78
+ */
79
+ export declare function checkHealth(runner: CommandRunner, url: string, attempts: number, delayMs: number): HealthCheckResult;
80
+ /**
81
+ * Run the full build pipeline against `cwd` (the standby directory). Steps
82
+ * run in the order documented in the task-5 brief (with db-strategy
83
+ * resolution/validation moved earlier, before git pull, so a bad `--db`
84
+ * fails fast); any failure throws `BuildAbortError` immediately. The state
85
+ * file's `last_build`/`last_build_status` is written once the pipeline
86
+ * reaches its first destructive step (git pull), and again with the final
87
+ * outcome if the pipeline completes (success or failure) — see this file's
88
+ * header (Fix 3) for the full rationale; an early abort never touches it.
89
+ */
90
+ export declare function runBuild(config: DeployConfig, runner: CommandRunner, opts?: RunBuildOptions): RunBuildResult;
91
+ //# sourceMappingURL=build.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../../src/deploy/build.ts"],"names":[],"mappings":"AAgCA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAI9D,MAAM,WAAW,eAAe;IAC9B,gGAAgG;IAChG,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,0EAA0E;IAC1E,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,qDAAqD;IACrD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,iFAAiF;IACjF,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,mFAAmF;IACnF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,4CAA4C;IAC5C,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,gEAAgE;IAChE,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED,MAAM,MAAM,eAAe,GAAG,MAAM,GAAG,MAAM,CAAC;AAE9C,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,eAAe,CAAC;IACxB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,cAAc;IAC7B,KAAK,EAAE,eAAe,EAAE,CAAC;IACzB,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,kBAAkB,EAAE,MAAM,GAAG,QAAQ,CAAC;IACtC,QAAQ,EAAE,MAAM,EAAE,CAAC;CACpB;AAED,6FAA6F;AAC7F,qBAAa,eAAgB,SAAQ,KAAK;IACxC,QAAQ,CAAC,KAAK,EAAE,eAAe,EAAE,CAAC;gBAEtB,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,eAAe,EAAE;CAKtD;AAKD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAMjF;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAErE;AAiBD,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE,OAAO,CAAC;IACZ,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,iBAAiB,CASpH;AAED;;;;;;;;;GASG;AACH,wBAAgB,QAAQ,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,GAAE,eAAoB,GAAG,cAAc,CAiThH"}