hazo_env 0.11.0 → 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.
package/CHANGE_LOG.md CHANGED
@@ -1,5 +1,15 @@
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
+
3
13
  ## 0.12.0 — 2026-10-24
4
14
 
5
15
  New: `hazo-env deploy` — a full blue-green deployment CLI for single-VM sites
package/dist/cli.js CHANGED
@@ -212,6 +212,7 @@ Usage:
212
212
  --stop-prod --branch=<b> --db=<env> --peer-dir=<path>
213
213
  hazo-env deploy verify Re-run health/typecheck/migration checks on standby
214
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
215
216
  hazo-env deploy rollback Reverse the last switch
216
217
  hazo-env deploy status Show live/standby dirs, ports, PM2 state, disk/memory
217
218
  hazo-env deploy clean Reclaim disk space from old builds and caches
@@ -413,14 +414,21 @@ async function runDeploySwitch() {
413
414
  const { resolveDeployConfig } = await import('./resolve/deploy.js');
414
415
  const { runSwitch, SwitchAbortError } = await import('./deploy/switch.js');
415
416
  const { nodeCommandRunner } = await import('./deploy/runner.js');
417
+ const force = args.includes('--force');
416
418
  const config = resolveDeployConfig();
417
419
  console.log(`\n${pc.bold('hazo-env deploy switch')} ${pc.dim(config.app_name)}\n`);
418
420
  try {
419
- const result = runSwitch(config, nodeCommandRunner);
421
+ const result = runSwitch(config, nodeCommandRunner, { force });
420
422
  console.log(` ${pc.green('✓')} deleted live PM2 registration "${config.app_name}" in ${result.previousLiveDir}`);
421
423
  console.log(` ${result.stagingStopped ? pc.green('✓') : pc.dim('·')} staging process "${config.app_name}-staging"` +
422
424
  `${result.stagingStopped ? ' stopped' : ' was not running (skipped)'}`);
425
+ if (result.stagingDeleteWarning) {
426
+ console.log(` ${pc.yellow('⚠')} ${result.stagingDeleteWarning}`);
427
+ }
423
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
+ }
424
432
  console.log('');
425
433
  if (result.postSwitchHooks.length) {
426
434
  console.log(` post-switch hooks:`);
@@ -454,6 +462,12 @@ async function runDeployRollback() {
454
462
  try {
455
463
  const result = runRollback(config, nodeCommandRunner);
456
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
+ }
457
471
  console.log('');
458
472
  console.log(` ${pc.green('rolled back')} to ${pc.bold(result.restoredLiveDir)}, running on port ${result.prodPort}.`);
459
473
  console.log(` standby: ${result.newStandbyDir}`);
@@ -82,9 +82,10 @@ export declare function checkHealth(runner: CommandRunner, url: string, attempts
82
82
  * run in the order documented in the task-5 brief (with db-strategy
83
83
  * resolution/validation moved earlier, before git pull, so a bad `--db`
84
84
  * fails fast); any failure throws `BuildAbortError` immediately. The state
85
- * file's `last_build`/`last_build_status` is updated regardless of outcome
86
- * (success path included), via a `finally` so a thrown error is never
87
- * swallowed.
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.
88
89
  */
89
90
  export declare function runBuild(config: DeployConfig, runner: CommandRunner, opts?: RunBuildOptions): RunBuildResult;
90
91
  //# sourceMappingURL=build.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../../src/deploy/build.ts"],"names":[],"mappings":"AAuBA,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;;;;;;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
13
  // whatever partial work happened on disk as-is — re-running `deploy build`
14
14
  // is the recovery path, not an automatic rollback. The state file's
15
- // last_build/last_build_status is always updated, win or lose.
15
+ // last_build/last_build_status is updated once the pipeline reaches its
16
+ // first DESTRUCTIVE step (git pull) — never before (an early abort, e.g.
17
+ // the standby-dir guard or a disk/memory/db-resolve failure, leaves
18
+ // last_build untouched, since nothing destructive happened) — and is
19
+ // overwritten again with the final outcome if the pipeline completes
20
+ // normally (success or a later failure). See the "Fix 3" comments inline
21
+ // around the git-pull step and the closing `finally` block for the full
22
+ // rationale (this two-write scheme fixes both a false "stale build" block
23
+ // on deploy rollback from an early abort, and a missed one from a Ctrl+C
24
+ // after `pre_build_cmd` has already run).
16
25
  import path from 'node:path';
17
26
  import { autoClean } from './clean.js';
18
27
  import { resolvePeerDir } from './peer.js';
19
28
  import { queryDiskFreeMb, queryMemoryFreeMb } from './status.js';
20
29
  import { readState, updateState } from './state.js';
21
30
  import { SWAP_INCREASE_SUGGESTIONS } from './clean.js';
22
- import { startNamedPm2Process } from './pm2-start.js';
31
+ import { startNamedPm2Process, isPm2ProcessNotFound } from './pm2-start.js';
23
32
  import { resolveConnectConfig } from '../resolve/connect.js';
24
33
  /** Thrown when any pipeline step fails. Carries the steps completed so far for reporting. */
25
34
  export class BuildAbortError extends Error {
@@ -94,7 +103,8 @@ function sleepSync(ms) {
94
103
  export function checkHealth(runner, url, attempts, delayMs) {
95
104
  let lastCode = '';
96
105
  for (let attempt = 1; attempt <= attempts; attempt++) {
97
- lastCode = runner.exec(`curl -s -o /dev/null -w '%{http_code}' ${JSON.stringify(url)}`).trim();
106
+ const result = runner.spawn(`curl -s -o /dev/null -w '%{http_code}' ${JSON.stringify(url)}`);
107
+ lastCode = result.code === 0 ? result.stdout.trim() : `curl_exit_${result.code}`;
98
108
  if (lastCode === '200')
99
109
  return { ok: true, lastCode, attempts: attempt };
100
110
  if (attempt < attempts)
@@ -107,9 +117,10 @@ export function checkHealth(runner, url, attempts, delayMs) {
107
117
  * run in the order documented in the task-5 brief (with db-strategy
108
118
  * resolution/validation moved earlier, before git pull, so a bad `--db`
109
119
  * fails fast); any failure throws `BuildAbortError` immediately. The state
110
- * file's `last_build`/`last_build_status` is updated regardless of outcome
111
- * (success path included), via a `finally` so a thrown error is never
112
- * swallowed.
120
+ * file's `last_build`/`last_build_status` is written once the pipeline
121
+ * reaches its first destructive step (git pull), and again with the final
122
+ * outcome if the pipeline completes (success or failure) — see this file's
123
+ * header (Fix 3) for the full rationale; an early abort never touches it.
113
124
  */
114
125
  export function runBuild(config, runner, opts = {}) {
115
126
  const cwd = path.resolve(opts.cwd ?? process.cwd());
@@ -118,12 +129,33 @@ export function runBuild(config, runner, opts = {}) {
118
129
  const healthCheckDelayMs = opts.healthCheckDelayMs ?? DEFAULT_HEALTH_CHECK_DELAY_MS;
119
130
  const warnings = [];
120
131
  const steps = [];
132
+ // Fix 3: whether the pipeline has reached its first DESTRUCTIVE step (git
133
+ // pull — see the `finally` block at the bottom of this function for the
134
+ // full rationale). Early aborts (standby-dir guard, disk/memory checks,
135
+ // db-resolve validation) never flip this, so they never touch
136
+ // last_build/last_build_status at all — nothing destructive happened, so
137
+ // there's nothing stale to warn rollback.ts about.
138
+ let destructiveStepReached = false;
139
+ // Fix 6: true once `--stop-prod` has actually stopped the live PM2
140
+ // process. If the build subsequently aborts for ANY reason, `abort()`
141
+ // below makes sure that fact — production is currently DOWN — is
142
+ // unmissable in the thrown error, rather than buried behind an unrelated
143
+ // "build failed" message.
144
+ let productionStopped = false;
145
+ let liveDirForAbortMessage = '';
121
146
  function pass(name, detail) {
122
147
  steps.push({ name, status: 'pass', detail });
123
148
  }
124
149
  function abort(name, message) {
125
- steps.push({ name, status: 'fail', detail: message });
126
- throw new BuildAbortError(message, steps);
150
+ const finalMessage = productionStopped
151
+ ? `${message}\n\n` +
152
+ `⚠ PRODUCTION IS DOWN: --stop-prod stopped "${config.app_name}" in ${liveDirForAbortMessage} to free ` +
153
+ `memory, and the build subsequently aborted — production was never restarted. Bring it back up with:\n` +
154
+ ` cd ${liveDirForAbortMessage} && pm2 start ecosystem.config.js --env production\n` +
155
+ `or run "deploy rollback" / investigate manually.`
156
+ : message;
157
+ steps.push({ name, status: 'fail', detail: finalMessage });
158
+ throw new BuildAbortError(finalMessage, steps);
127
159
  }
128
160
  /**
129
161
  * Run a risky operation (anything touching CommandRunner or an external
@@ -181,6 +213,8 @@ export function runBuild(config, runner, opts = {}) {
181
213
  if (opts.stopProd) {
182
214
  runStep('stop-prod', () => runner.exec(`pm2 stop ${config.app_name}`, { cwd: liveDir }));
183
215
  pass('stop-prod', `stopped "${config.app_name}" in ${liveDir}`);
216
+ productionStopped = true;
217
+ liveDirForAbortMessage = liveDir;
184
218
  memoryFreeMb = queryMemoryFreeMb(runner, warnings);
185
219
  memoryLow = memoryFreeMb !== undefined && memoryFreeMb < config.min_memory_mb;
186
220
  }
@@ -203,6 +237,27 @@ export function runBuild(config, runner, opts = {}) {
203
237
  abort('db-resolve', `db_strategy resolved to "copy" but the resolved db config is type "${dbConfig.type}", not sqlite.`);
204
238
  }
205
239
  pass('db-resolve', `strategy=${dbStrategyResolved}${opts.db ? ` db=${opts.db}` : ''}`);
240
+ // Fix 3: write a provisional/pessimistic `last_build` marker right
241
+ // before the first DESTRUCTIVE step (git pull) — everything above this
242
+ // point (guard, disk/memory checks, db-resolve) is read-only, so an
243
+ // abort before here must NEVER touch last_build at all (an early abort
244
+ // leaves the previous live build fully intact; rollback.ts's
245
+ // stale-build guard must stay unblocked). From here on, the standby
246
+ // dir's on-disk state is no longer guaranteed clean: if the operator
247
+ // Ctrl+C's the process after `pre_build_cmd` (typically `rm -rf .next`)
248
+ // has already run, the `finally` block below never executes (process
249
+ // killed) — this provisional write is what's left behind for
250
+ // rollback.ts to see, correctly blocking it (the standby dir may now be
251
+ // a half-destroyed mess that is no longer safe to promote). A normal
252
+ // completion (success or a later, cleaner failure) overwrites this via
253
+ // the `finally` block's own write.
254
+ destructiveStepReached = true;
255
+ try {
256
+ updateState(config.app_name, { last_build: new Date().toISOString(), last_build_status: 'failed' });
257
+ }
258
+ catch {
259
+ // No state file yet — best-effort, same as the finally block below.
260
+ }
206
261
  // Step 4: git pull
207
262
  runStep('git-pull', () => runner.exec(`git pull origin ${branch}`, { cwd }));
208
263
  pass('git-pull', `origin ${branch}`);
@@ -272,6 +327,32 @@ export function runBuild(config, runner, opts = {}) {
272
327
  // in and starting pm2 from THAT clone instead — see pm2-start.ts's
273
328
  // header for the full why.
274
329
  const stagingProcessName = `${config.app_name}-staging`;
330
+ // Fix 4a: tolerant-delete any stale "<app>-staging" registration before
331
+ // starting it fresh — defense in depth. `start-staging` normally finds
332
+ // nothing here because a prior `deploy switch`/`deploy rollback` already
333
+ // deleted it (via `promoteDirFresh`'s own staging-delete step). If that
334
+ // delete ever silently failed, the NEXT `deploy build` would otherwise
335
+ // hit the stale registration and `startNamedPm2Process` would restart
336
+ // IT IN PLACE (pm2 only recomputes cwd for a name it's never registered
337
+ // before — see pm2-start.ts's header) — meaning the health check below
338
+ // would test the OLD directory's code, not this build's, and a
339
+ // subsequent `deploy switch` would silently promote untested code. Never
340
+ // fatal: "process not found" is the expected common case, and any other
341
+ // failure here is only a warning — the fresh start below is what
342
+ // actually matters.
343
+ const stagingCleanupResult = runner.spawn(`pm2 delete ${stagingProcessName}`, { cwd });
344
+ if (stagingCleanupResult.code === 0) {
345
+ pass('clean-stale-staging', `deleted a stale "${stagingProcessName}" PM2 registration before starting fresh`);
346
+ }
347
+ else if (isPm2ProcessNotFound(stagingCleanupResult)) {
348
+ pass('clean-stale-staging', `no stale "${stagingProcessName}" registration found`);
349
+ }
350
+ else {
351
+ const detail = `failed to delete a stale "${stagingProcessName}" registration (continuing anyway): ` +
352
+ (stagingCleanupResult.stderr || stagingCleanupResult.stdout || `exit code ${stagingCleanupResult.code}`);
353
+ warnings.push(detail);
354
+ pass('clean-stale-staging', detail);
355
+ }
275
356
  runStep('start-staging', () => startNamedPm2Process(runner, { dir: cwd, name: stagingProcessName, port: config.staging_port }));
276
357
  pass('start-staging', `name=${stagingProcessName} PORT=${config.staging_port}, cwd=${cwd}`);
277
358
  // Step 10: health check, retried — pm2 start returns before the app has
@@ -287,13 +368,22 @@ export function runBuild(config, runner, opts = {}) {
287
368
  return { steps, stagingPort: config.staging_port, stagingUrl, dbStrategyResolved, warnings };
288
369
  }
289
370
  finally {
290
- try {
291
- updateState(config.app_name, { last_build: new Date().toISOString(), last_build_status: buildStatus });
292
- }
293
- catch {
294
- // No state file yet (deploy init was never run) — build still ran;
295
- // state bookkeeping is best-effort and must never mask the real
296
- // pipeline error (or success) above.
371
+ // Fix 3: only overwrite last_build/last_build_status here if the
372
+ // pipeline actually reached the first destructive step (the provisional
373
+ // marker written just before git pull, above). An early abort (guard/
374
+ // disk/memory/db-resolve) never set that flag, so this block correctly
375
+ // no-ops for it — nothing destructive happened, so last_build should be
376
+ // left exactly as it was (possibly undefined) rather than stamped
377
+ // "failed" and falsely blocking deploy rollback's stale-build guard.
378
+ if (destructiveStepReached) {
379
+ try {
380
+ updateState(config.app_name, { last_build: new Date().toISOString(), last_build_status: buildStatus });
381
+ }
382
+ catch {
383
+ // No state file yet (deploy init was never run) — build still ran;
384
+ // state bookkeeping is best-effort and must never mask the real
385
+ // pipeline error (or success) above.
386
+ }
297
387
  }
298
388
  }
299
389
  }
@@ -3,4 +3,11 @@ export * from './state.js';
3
3
  export * from './runner.js';
4
4
  export * from './peer.js';
5
5
  export * from './pm2-start.js';
6
+ export * from './clean.js';
7
+ export * from './status.js';
8
+ export * from './init.js';
9
+ export * from './build.js';
10
+ export * from './verify.js';
11
+ export * from './switch.js';
12
+ export * from './rollback.js';
6
13
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/deploy/index.ts"],"names":[],"mappings":"AACA,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC;AAC1B,cAAc,gBAAgB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/deploy/index.ts"],"names":[],"mappings":"AAUA,cAAc,YAAY,CAAC;AAC3B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC;AAC1B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,WAAW,CAAC;AAC1B,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC;AAC5B,cAAc,eAAe,CAAC"}
@@ -1,6 +1,22 @@
1
1
  // hazo_env/src/deploy/index.ts — Deploy module barrel export
2
+ //
3
+ // Fix 5 (final review wave): the command functions (runInit/runBuild/
4
+ // runVerify/runSwitch/runRollback/runStatus/runClean) and their abort error
5
+ // classes were missing from this barrel — only the supporting
6
+ // types/state/runner/peer/pm2-start modules were exported, so programmatic
7
+ // callers of `hazo_env` (per the spec's "Package export" section) couldn't
8
+ // actually import the deploy commands themselves. `src/index.ts`'s own
9
+ // `export * from './deploy/index.js'` picks up everything added here
10
+ // automatically — no change needed there.
2
11
  export * from './types.js';
3
12
  export * from './state.js';
4
13
  export * from './runner.js';
5
14
  export * from './peer.js';
6
15
  export * from './pm2-start.js';
16
+ export * from './clean.js';
17
+ export * from './status.js';
18
+ export * from './init.js';
19
+ export * from './build.js';
20
+ export * from './verify.js';
21
+ export * from './switch.js';
22
+ export * from './rollback.js';
@@ -1 +1 @@
1
- {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../src/deploy/init.ts"],"names":[],"mappings":"AAmBA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAe,MAAM,YAAY,CAAC;AAsC3E,MAAM,WAAW,cAAc;IAC7B,iFAAiF;IACjF,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,oEAAoE;IACpE,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,aAAa;IAC5B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,GAAE,cAAmB,GAAG,aAAa,CA8B7G"}
1
+ {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../src/deploy/init.ts"],"names":[],"mappings":"AAqBA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAe,MAAM,YAAY,CAAC;AAgD3E,MAAM,WAAW,cAAc;IAC7B,iFAAiF;IACjF,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,oEAAoE;IACpE,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,aAAa;IAC5B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;CACnB;AA0CD;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,GAAE,cAAmB,GAAG,aAAa,CAgC7G"}
@@ -14,9 +14,20 @@
14
14
  // not hazo_env's own file I/O.
15
15
  import fs from 'node:fs';
16
16
  import path from 'node:path';
17
+ import { HazoConfig } from 'hazo_config/server';
17
18
  import { resolvePeerDir } from './peer.js';
18
19
  import { writeState } from './state.js';
20
+ import { getEnv } from '../index.client.js';
19
21
  const CONFIG_RELATIVE_PATH = path.join('config', 'hazo_env_config.ini');
22
+ // Matches resolve/files.ts's DEFAULT_DATA_ROOT — kept as a local literal
23
+ // rather than importing that module, since resolveFilesConfig()/
24
+ // resolveFilesRoot() are both hard-coded to resolve against
25
+ // `process.cwd()`, which during `deploy init` is the CURRENT (live) dir,
26
+ // not the freshly-cloned peer dir this function needs to resolve the data
27
+ // root *for*. Re-reading the peer's own just-copied INI directly (see
28
+ // `ensurePeerDataDir` below) keeps this correct regardless of what
29
+ // directory `deploy init` itself happens to be run from.
30
+ const DEFAULT_DATA_ROOT = 'app_data';
20
31
  /**
21
32
  * Blue<->green swap applied to the `dir_suffix = <value>` VALUE in the INI
22
33
  * (as opposed to peer.ts's swapColorSuffix, which swaps a "-blue"/"-green"
@@ -48,6 +59,45 @@ function swapDirSuffixInIni(iniContent) {
48
59
  const swapped = swapDirSuffixValue(match[2]);
49
60
  return iniContent.replace(pattern, `$1${swapped}$3`);
50
61
  }
62
+ /**
63
+ * Fix 9: `deploy build`'s FIRST run on a fresh peer dir aborts at the
64
+ * sqlite db-copy step with "destination directory does not exist" because
65
+ * the `[data] root` dir (typically gitignored, so a fresh `git clone`
66
+ * doesn't bring it along) was never created. Mirrors build.ts's own
67
+ * db_strategy detection (auto -> infer sqlite-ness from `[db.<env>]` type;
68
+ * copy -> always sqlite; shared -> never sqlite) so this only fires for
69
+ * sites that are actually sqlite-backed — a no-op for Postgres/"shared"
70
+ * sites, which have no per-dir data file to provision.
71
+ *
72
+ * Reads the PEER's own just-copied INI (not `resolveFilesConfig()`/
73
+ * `resolveConnectConfig()`, both of which resolve against `process.cwd()`
74
+ * — the CURRENT/live dir here, not the peer) so the `[data] root` and
75
+ * `[db.<env>] type` values reflect the peer's own config exactly.
76
+ */
77
+ function ensurePeerDataDir(config, peerIniPath, peerDir) {
78
+ if (config.db_strategy === 'shared')
79
+ return; // never sqlite-backed by definition — nothing to provision.
80
+ let peerConfig;
81
+ try {
82
+ peerConfig = new HazoConfig({ filePath: peerIniPath });
83
+ }
84
+ catch {
85
+ // Can't read the INI we just wrote — nothing safe to infer or create.
86
+ return;
87
+ }
88
+ let sqliteBacked = config.db_strategy === 'copy';
89
+ if (config.db_strategy === 'auto') {
90
+ const env = getEnv();
91
+ const dbSection = peerConfig.getSection(`db.${env}`);
92
+ sqliteBacked = dbSection?.['type'] === 'sqlite';
93
+ }
94
+ if (!sqliteBacked)
95
+ return;
96
+ const dataSection = peerConfig.getSection('data');
97
+ const root = dataSection?.['root'] ?? DEFAULT_DATA_ROOT;
98
+ const dataRoot = path.isAbsolute(root) ? root : path.join(peerDir, root);
99
+ fs.mkdirSync(dataRoot, { recursive: true });
100
+ }
51
101
  /**
52
102
  * Create the peer (standby) directory: resolve its path, abort if it
53
103
  * already exists, clone the repo into it, copy the INI config across with
@@ -68,6 +118,7 @@ export function runInit(config, runner, opts = {}) {
68
118
  const swappedIni = swapDirSuffixInIni(iniContent);
69
119
  fs.mkdirSync(path.dirname(peerIniPath), { recursive: true });
70
120
  fs.writeFileSync(peerIniPath, swappedIni, 'utf-8');
121
+ ensurePeerDataDir(config, peerIniPath, peerDir);
71
122
  const state = {
72
123
  app_name: config.app_name,
73
124
  live_dir: currentDir,
@@ -57,6 +57,18 @@ export interface PromoteDirFreshOptions {
57
57
  export interface PromoteDirFreshResult {
58
58
  /** True iff a staging PM2 process was found and deleted (false if stagingName was omitted, or was already stopped/absent). */
59
59
  stagingDeleted: boolean;
60
+ /**
61
+ * Set when the staging-delete step failed for a reason OTHER than
62
+ * "process not found" (a real failure, not simply "nothing to delete").
63
+ * Previously such a failure was silently swallowed into `stagingDeleted:
64
+ * false`, indistinguishable from the common "already stopped/absent"
65
+ * case — leaving a stale `<name>-staging` registration in place for the
66
+ * NEXT `deploy build` to collide with (see build.ts's own tolerant
67
+ * staging-delete, added as defense in depth for this exact bug class).
68
+ * Callers (switch.ts/rollback.ts) should surface this, not just the
69
+ * plain boolean.
70
+ */
71
+ stagingDeleteWarning?: string;
60
72
  }
61
73
  /** Thrown when any step of promoteDirFresh fails fatally. Message already includes the restore-attempt outcome when the primary start fails. */
62
74
  export declare class PromoteDirFreshError extends Error {
@@ -1 +1 @@
1
- {"version":3,"file":"pm2-start.d.ts","sourceRoot":"","sources":["../../src/deploy/pm2-start.ts"],"names":[],"mappings":"AAiCA,OAAO,KAAK,EAAE,aAAa,EAAE,aAAa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AyE;IACzE,GAAG,EAAE,MAAM,CAAC;IACZ,gGAAgG;IAChG,IAAI,EAAE,MAAM,CAAC;IACb,uEAAuE;IACvE,IAAI,EAAE,MAAM,CAAC;CACd;AAeD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,aAAa,EAAE,IAAI,EAAE,2BAA2B,GAAG,IAAI,CAkEnG;AAeD,mHAAmH;AACnH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,aAAa,GAAG,OAAO,CAEnE;AAED,MAAM,WAAW,sBAAsB;IACrC,uEAAuE;IACvE,OAAO,EAAE,MAAM,CAAC;IAChB,uDAAuD;IACvD,KAAK,EAAE,MAAM,CAAC;IACd,8GAA8G;IAC9G,IAAI,EAAE,MAAM,CAAC;IACb,2CAA2C;IAC3C,IAAI,EAAE,MAAM,CAAC;IACb;;;;;;OAMG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,mGAAmG;IACnG,OAAO,EAAE,MAAM,CAAC;IAChB,qJAAqJ;IACrJ,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,qBAAqB;IACpC,8HAA8H;IAC9H,cAAc,EAAE,OAAO,CAAC;IACxB;;;;;;;;;;OAUG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC/B;AAED,gJAAgJ;AAChJ,qBAAa,oBAAqB,SAAQ,KAAK;gBACjC,OAAO,EAAE,MAAM;CAI5B;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,aAAa,EAAE,IAAI,EAAE,sBAAsB,GAAG,qBAAqB,CA4D1G"}
@@ -94,14 +94,37 @@ export function startNamedPm2Process(runner, opts) {
94
94
  // separate verify run) from clobbering each other.
95
95
  const uniqueSuffix = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
96
96
  const tempFile = path.join(os.tmpdir(), `hazo-env-pm2-${opts.name}-${uniqueSuffix}.config.cjs`);
97
- fs.writeFileSync(tempFile, `module.exports = ${JSON.stringify({ apps: [namedApp] }, null, 2)};\n`, 'utf-8');
98
- // Deliberately NOT cleaned up here: pm2 start may read the file
99
- // asynchronously (forking its own daemon process against it), and
100
- // deleting it immediately after `runner.exec` returns risks a race with
101
- // that read. It's an ephemeral, uniquely-named file in os.tmpdir() — the
102
- // OS reclaims tmpdir over time, and the cost of leaving a few small JSON
103
- // files behind is far lower than the cost of a flaky deploy.
104
- runner.exec(`pm2 start ${JSON.stringify(tempFile)} --env production`);
97
+ // mode: 0o600 (owner read/write only) — this file is a clone of the real
98
+ // app's ecosystem config, including its `env`/`env_production` block,
99
+ // which is routinely populated from `.env.local` i.e. real production
100
+ // secrets (DB credentials, API keys, ...). Written to world-readable
101
+ // os.tmpdir() by default would leak those secrets to any other local
102
+ // user; 0o600 keeps it readable only by the user running this process.
103
+ fs.writeFileSync(tempFile, `module.exports = ${JSON.stringify({ apps: [namedApp] }, null, 2)};\n`, {
104
+ encoding: 'utf-8',
105
+ mode: 0o600,
106
+ });
107
+ // Deleted in `finally`, right after `pm2 start` returns — not left behind
108
+ // "forever" as this helper used to document. `pm2 start <file>` parses the
109
+ // config file SYNCHRONOUSLY inside its own short-lived CLI process (before
110
+ // handing the already-parsed app definition off to the pm2 daemon), so by
111
+ // the time `runner.exec` returns the file has already been fully read;
112
+ // deleting it here is safe and closes the secret-leak window instead of
113
+ // leaving a world-readable (well, now 0o600, but still unnecessary) copy
114
+ // of production secrets sitting in /tmp indefinitely. The deletion itself
115
+ // is best-effort: a failure to unlink must never mask the real pm2 result
116
+ // (success or failure) from the `try` block above it.
117
+ try {
118
+ runner.exec(`pm2 start ${JSON.stringify(tempFile)} --env production`);
119
+ }
120
+ finally {
121
+ try {
122
+ fs.unlinkSync(tempFile);
123
+ }
124
+ catch {
125
+ // best-effort cleanup — ignore (e.g. already removed, permissions).
126
+ }
127
+ }
105
128
  }
106
129
  // ─── promoteDirFresh ─────────────────────────────────────────────────────
107
130
  //
@@ -154,13 +177,22 @@ export function promoteDirFresh(runner, opts) {
154
177
  (deleteResult.stderr || deleteResult.stdout || `exit code ${deleteResult.code}`));
155
178
  }
156
179
  let stagingDeleted = false;
180
+ let stagingDeleteWarning;
157
181
  if (opts.stagingName) {
158
182
  try {
159
183
  const result = runner.spawn(`pm2 delete ${opts.stagingName}`, { cwd: opts.toDir });
160
184
  stagingDeleted = result.code === 0;
185
+ if (!stagingDeleted && !isPm2ProcessNotFound(result)) {
186
+ stagingDeleteWarning =
187
+ `Failed to delete stale PM2 registration "${opts.stagingName}" in ${opts.toDir}: ` +
188
+ (result.stderr || result.stdout || `exit code ${result.code}`);
189
+ }
161
190
  }
162
- catch {
191
+ catch (e) {
163
192
  stagingDeleted = false;
193
+ stagingDeleteWarning =
194
+ `Failed to delete stale PM2 registration "${opts.stagingName}" in ${opts.toDir}: ` +
195
+ (e instanceof Error ? e.message : String(e));
164
196
  }
165
197
  }
166
198
  try {
@@ -192,5 +224,5 @@ export function promoteDirFresh(runner, opts) {
192
224
  }
193
225
  throw new PromoteDirFreshError(`Failed to start the ${opts.toLabel} (${opts.toDir}) on the production port: ${startMsg}\n${restoreMsg}`);
194
226
  }
195
- return { stagingDeleted };
227
+ return { stagingDeleted, stagingDeleteWarning };
196
228
  }
@@ -4,6 +4,10 @@ export interface RunRollbackResult {
4
4
  newStandbyDir: string;
5
5
  prodPort: number;
6
6
  state: DeployState;
7
+ /** Set when the defense-in-depth staging cleanup (see header) failed for a reason other than "not found". */
8
+ stagingDeleteWarning?: string;
9
+ /** Set when `pm2 save` failed after a successful rollback (non-fatal — the rollback itself already succeeded). */
10
+ pm2SaveWarning?: string;
7
11
  }
8
12
  /** Thrown when there's nothing to roll back, or a fatal step fails. */
9
13
  export declare class RollbackAbortError extends Error {
@@ -1 +1 @@
1
- {"version":3,"file":"rollback.d.ts","sourceRoot":"","sources":["../../src/deploy/rollback.ts"],"names":[],"mappings":"AAkFA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE3E,MAAM,WAAW,iBAAiB;IAChC,eAAe,EAAE,MAAM,CAAC;IACxB,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,WAAW,CAAC;CACpB;AAED,uEAAuE;AACvE,qBAAa,kBAAmB,SAAQ,KAAK;gBAC/B,OAAO,EAAE,MAAM;CAI5B;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,GAAG,iBAAiB,CAqF1F"}
1
+ {"version":3,"file":"rollback.d.ts","sourceRoot":"","sources":["../../src/deploy/rollback.ts"],"names":[],"mappings":"AAkFA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE3E,MAAM,WAAW,iBAAiB;IAChC,eAAe,EAAE,MAAM,CAAC;IACxB,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,WAAW,CAAC;IACnB,6GAA6G;IAC7G,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,kHAAkH;IAClH,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,uEAAuE;AACvE,qBAAa,kBAAmB,SAAQ,KAAK;gBAC/B,OAAO,EAAE,MAAM;CAI5B;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,GAAG,iBAAiB,CAoH1F"}
@@ -108,9 +108,19 @@ export function runRollback(config, runner) {
108
108
  // stale-build guard" in the header). A missing last_build means no build
109
109
  // has ever run; that's trivially "no build since the switch".
110
110
  if (state.last_build && state.last_switch && state.last_build > state.last_switch) {
111
- throw new RollbackAbortError(`Standby has been rebuilt since the last switch (last_build ${state.last_build} is newer than ` +
112
- `last_switch ${state.last_switch}) — the previous live build no longer exists (it was rebuilt in ` +
113
- `place by "deploy build"). Cannot safely roll back.`);
111
+ // Wording note (fix round): `last_build` here does not necessarily mean
112
+ // a build actually SUCCEEDED since the last switch — since build.ts
113
+ // (Fix 3) now writes a provisional `last_build` the moment the pipeline
114
+ // reaches its first destructive step (git pull), this guard also trips
115
+ // for a build attempt that was interrupted (e.g. Ctrl+C after `rm -rf
116
+ // .next` already ran) or that failed partway through. Either way the
117
+ // standby dir may no longer hold the artifact that was actually live
118
+ // before the switch, so the wording below covers both "it succeeded and
119
+ // got promoted" and "an attempt merely ran" without claiming more than
120
+ // is known.
121
+ throw new RollbackAbortError(`A build has run on standby since the last switch (last_build ${state.last_build} is newer than ` +
122
+ `last_switch ${state.last_switch}) — the previous live build may no longer be intact (it may have been ` +
123
+ `rebuilt, or partially rebuilt, in place by "deploy build"). Cannot safely roll back.`);
114
124
  }
115
125
  const currentLiveDir = path.resolve(state.live_dir);
116
126
  const restoreDir = path.resolve(state.previous_live_dir);
@@ -124,11 +134,15 @@ export function runRollback(config, runner) {
124
134
  // promoteDirFresh itself attempts to bring the build rollback was trying
125
135
  // to replace back up so production isn't silently left down, and
126
136
  // reports plainly whether that worked.
137
+ let stagingDeleteWarning;
127
138
  try {
128
- // stagingDeleted isn't currently surfaced in RunRollbackResult — this is
129
- // defense in depth (see header), not the normal path — so the return
130
- // value is intentionally unused here.
131
- promoteDirFresh(runner, {
139
+ // stagingDeleted (a plain boolean) isn't currently surfaced in
140
+ // RunRollbackResult — this is defense in depth (see header), not the
141
+ // normal path. stagingDeleteWarning IS surfaced (Fix 4b): a REAL
142
+ // deletion failure (not just "nothing to delete") would otherwise be
143
+ // silently swallowed, leaving a stale registration for the next
144
+ // `deploy build` to collide with.
145
+ const promoteResult = promoteDirFresh(runner, {
132
146
  fromDir: currentLiveDir,
133
147
  toDir: restoreDir,
134
148
  name: config.app_name,
@@ -137,6 +151,7 @@ export function runRollback(config, runner) {
137
151
  toLabel: 'previous live app',
138
152
  fromLabel: 'the build that was live before this rollback attempt',
139
153
  });
154
+ stagingDeleteWarning = promoteResult.stagingDeleteWarning;
140
155
  }
141
156
  catch (e) {
142
157
  if (e instanceof PromoteDirFreshError) {
@@ -158,10 +173,24 @@ export function runRollback(config, runner) {
158
173
  git_ref: gitRef,
159
174
  pm2_process: config.app_name,
160
175
  });
176
+ // Fix 7: persist the pm2 process list after a successful promotion. Without
177
+ // this, a server reboot's `pm2 resurrect` (if configured to run on boot)
178
+ // could bring back the OLD pm2 registration while the state file already
179
+ // claims the restored dir is live — a silent divergence. Non-fatal: the
180
+ // rollback itself already succeeded, so a failed `pm2 save` is only a
181
+ // warning, never a reason to report the rollback as failed.
182
+ const saveResult = runner.spawn('pm2 save');
183
+ const pm2SaveWarning = saveResult.code !== 0
184
+ ? `"pm2 save" failed after rollback (exit ${saveResult.code}): ${saveResult.stderr || saveResult.stdout || 'no output'} — ` +
185
+ `a server reboot's "pm2 resurrect" may restore the OLD pm2 process list even though this rollback ` +
186
+ `succeeded. Run "pm2 save" manually.`
187
+ : undefined;
161
188
  return {
162
189
  restoredLiveDir: restoreDir,
163
190
  newStandbyDir: currentLiveDir,
164
191
  prodPort: config.prod_port,
165
192
  state: newState,
193
+ stagingDeleteWarning,
194
+ pm2SaveWarning,
166
195
  };
167
196
  }
@@ -12,6 +12,10 @@ export interface RunSwitchResult {
12
12
  stagingPort: number;
13
13
  /** True iff a staging PM2 process was found and stopped (false if it was already stopped/absent). */
14
14
  stagingStopped: boolean;
15
+ /** Set when the staging-delete step (above) failed for a reason other than "not found". */
16
+ stagingDeleteWarning?: string;
17
+ /** Set when `pm2 save` failed after a successful switch (non-fatal — the switch itself already succeeded). */
18
+ pm2SaveWarning?: string;
15
19
  postSwitchHooks: PostSwitchHookResult[];
16
20
  state: DeployState;
17
21
  }
@@ -19,9 +23,18 @@ export interface RunSwitchResult {
19
23
  export declare class SwitchAbortError extends Error {
20
24
  constructor(message: string);
21
25
  }
26
+ export interface RunSwitchOptions {
27
+ /**
28
+ * Fix 2: bypass the "standby must have a successful, post-last-switch
29
+ * build" check below. Use only when the operator has independently
30
+ * verified the standby dir is safe to promote (e.g. it was built/verified
31
+ * through some means outside this state file's tracking).
32
+ */
33
+ force?: boolean;
34
+ }
22
35
  /**
23
36
  * Promote the standby directory to live. See this file's header for the
24
37
  * full step-by-step rationale.
25
38
  */
26
- export declare function runSwitch(config: DeployConfig, runner: CommandRunner): RunSwitchResult;
39
+ export declare function runSwitch(config: DeployConfig, runner: CommandRunner, opts?: RunSwitchOptions): RunSwitchResult;
27
40
  //# sourceMappingURL=switch.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"switch.d.ts","sourceRoot":"","sources":["../../src/deploy/switch.ts"],"names":[],"mappings":"AA8DA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE3E,MAAM,WAAW,oBAAoB;IACnC,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC;IACxB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,eAAe;IAC9B,eAAe,EAAE,MAAM,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,qGAAqG;IACrG,cAAc,EAAE,OAAO,CAAC;IACxB,eAAe,EAAE,oBAAoB,EAAE,CAAC;IACxC,KAAK,EAAE,WAAW,CAAC;CACpB;AAED,uFAAuF;AACvF,qBAAa,gBAAiB,SAAQ,KAAK;gBAC7B,OAAO,EAAE,MAAM;CAI5B;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,GAAG,eAAe,CAqFtF"}
1
+ {"version":3,"file":"switch.d.ts","sourceRoot":"","sources":["../../src/deploy/switch.ts"],"names":[],"mappings":"AA8DA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE3E,MAAM,WAAW,oBAAoB;IACnC,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC;IACxB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,eAAe;IAC9B,eAAe,EAAE,MAAM,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,qGAAqG;IACrG,cAAc,EAAE,OAAO,CAAC;IACxB,2FAA2F;IAC3F,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,8GAA8G;IAC9G,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,eAAe,EAAE,oBAAoB,EAAE,CAAC;IACxC,KAAK,EAAE,WAAW,CAAC;CACpB;AAED,uFAAuF;AACvF,qBAAa,gBAAiB,SAAQ,KAAK;gBAC7B,OAAO,EAAE,MAAM;CAI5B;AAED,MAAM,WAAW,gBAAgB;IAC/B;;;;;OAKG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,GAAE,gBAAqB,GAAG,eAAe,CA0HnH"}
@@ -70,7 +70,7 @@ export class SwitchAbortError extends Error {
70
70
  * Promote the standby directory to live. See this file's header for the
71
71
  * full step-by-step rationale.
72
72
  */
73
- export function runSwitch(config, runner) {
73
+ export function runSwitch(config, runner, opts = {}) {
74
74
  // Step 1: read state — the ONLY source of truth for which dir is live vs.
75
75
  // standby. Never infer this from the blue/green naming convention here
76
76
  // (see build.ts's header for why that was a critical bug there).
@@ -78,6 +78,23 @@ export function runSwitch(config, runner) {
78
78
  if (!state) {
79
79
  throw new SwitchAbortError(`No deploy state found for "${config.app_name}" — nothing to switch. Run "deploy init" first.`);
80
80
  }
81
+ // Fix 2: refuse to promote standby unless it has had a SUCCESSFUL build
82
+ // since the last switch (or this is the first-ever switch, i.e.
83
+ // last_switch is unset). Without this, a standby dir that crashed
84
+ // mid-build, or was never rebuilt since a prior FAILED attempt, could get
85
+ // promoted to production while the CLI reports "Switch complete." —
86
+ // last_build_status/last_build already exist on the state file for
87
+ // exactly this reason (deploy build always writes them — see build.ts).
88
+ // --force bypasses this one check only (nothing else here is skippable).
89
+ if (!opts.force) {
90
+ const hasSuccessfulRecentBuild = state.last_build_status === 'success' &&
91
+ !!state.last_build &&
92
+ (!state.last_switch || state.last_build > state.last_switch);
93
+ if (!hasSuccessfulRecentBuild) {
94
+ throw new SwitchAbortError(`standby has not had a successful build since the last switch — run "deploy build" first, or pass ` +
95
+ `--force to override.`);
96
+ }
97
+ }
81
98
  const oldLiveDir = path.resolve(state.live_dir);
82
99
  const oldStandbyDir = path.resolve(state.standby_dir);
83
100
  // Step 2: read the new live dir's git ref FIRST, before anything is
@@ -97,6 +114,7 @@ export function runSwitch(config, runner) {
97
114
  // OLD live build back up so production isn't silently left down, and
98
115
  // reports plainly whether that worked.
99
116
  let stagingStopped;
117
+ let stagingDeleteWarning;
100
118
  try {
101
119
  const result = promoteDirFresh(runner, {
102
120
  fromDir: oldLiveDir,
@@ -108,6 +126,7 @@ export function runSwitch(config, runner) {
108
126
  fromLabel: 'the previous live build',
109
127
  });
110
128
  stagingStopped = result.stagingDeleted;
129
+ stagingDeleteWarning = result.stagingDeleteWarning;
111
130
  }
112
131
  catch (e) {
113
132
  if (e instanceof PromoteDirFreshError) {
@@ -139,6 +158,16 @@ export function runSwitch(config, runner) {
139
158
  git_ref: gitRef,
140
159
  pm2_process: config.app_name,
141
160
  });
161
+ // Fix 7: persist the pm2 process list after a successful promotion — see
162
+ // rollback.ts's identical comment for the full rationale. Non-fatal: the
163
+ // switch itself already succeeded, so a failed `pm2 save` is only
164
+ // surfaced as a warning.
165
+ const saveResult = runner.spawn('pm2 save');
166
+ const pm2SaveWarning = saveResult.code !== 0
167
+ ? `"pm2 save" failed after switch (exit ${saveResult.code}): ${saveResult.stderr || saveResult.stdout || 'no output'} — ` +
168
+ `a server reboot's "pm2 resurrect" may restore the OLD pm2 process list even though this switch ` +
169
+ `succeeded. Run "pm2 save" manually.`
170
+ : undefined;
142
171
  return {
143
172
  previousLiveDir: oldLiveDir,
144
173
  newLiveDir: oldStandbyDir,
@@ -146,6 +175,8 @@ export function runSwitch(config, runner) {
146
175
  prodPort: config.prod_port,
147
176
  stagingPort: config.staging_port,
148
177
  stagingStopped,
178
+ stagingDeleteWarning,
179
+ pm2SaveWarning,
149
180
  postSwitchHooks,
150
181
  state: newState,
151
182
  };
@@ -1 +1 @@
1
- {"version":3,"file":"deploy.d.ts","sourceRoot":"","sources":["../../src/resolve/deploy.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AA6DvD;;;;GAIG;AACH,wBAAgB,mBAAmB,IAAI,YAAY,CAuDlD"}
1
+ {"version":3,"file":"deploy.d.ts","sourceRoot":"","sources":["../../src/resolve/deploy.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAgFvD;;;;GAIG;AACH,wBAAgB,mBAAmB,IAAI,YAAY,CAuDlD"}
@@ -36,11 +36,30 @@ function loadConfig() {
36
36
  });
37
37
  }
38
38
  }
39
- function parseIntOr(value, fallback) {
39
+ /**
40
+ * Parse an INI integer field, applying `fallback` only when the field is
41
+ * ABSENT. A field that IS present but not a valid integer (e.g. `prod_port
42
+ * = abc`) throws a clear `HazoConfigError` instead of silently falling back
43
+ * to the default — matching `db_strategy`'s existing validation below
44
+ * rather than masking a typo as "3000, no error" (Fix 8).
45
+ *
46
+ * Uses `Number(...)` rather than `parseInt`, which deliberately rejects
47
+ * trailing garbage (`parseInt('3000abc', 10)` === 3000; `Number('3000abc')`
48
+ * is NaN) so a value that's only partially numeric is still caught.
49
+ */
50
+ function parseIntField(key, value, fallback) {
40
51
  if (value === undefined)
41
52
  return fallback;
42
- const parsed = parseInt(value, 10);
43
- return Number.isFinite(parsed) ? parsed : fallback;
53
+ const trimmed = value.trim();
54
+ const parsed = Number(trimmed);
55
+ if (trimmed === '' || !Number.isInteger(parsed)) {
56
+ throw new HazoConfigError({
57
+ code: 'HAZO_ENV_CONFIG_INVALID_DEPLOY_INT_FIELD',
58
+ pkg: 'hazo_env',
59
+ message: `[deploy] ${key} "${value}" is invalid. Expected an integer.`,
60
+ });
61
+ }
62
+ return parsed;
44
63
  }
45
64
  /**
46
65
  * Collects `post_switch_cmd`, `post_switch_cmd_2`, `post_switch_cmd_3`, ...
@@ -105,11 +124,11 @@ export function resolveDeployConfig() {
105
124
  return {
106
125
  app_name,
107
126
  dir_suffix,
108
- prod_port: parseIntOr(section['prod_port'], DEFAULTS.prod_port),
109
- staging_port: parseIntOr(section['staging_port'], DEFAULTS.staging_port),
127
+ prod_port: parseIntField('prod_port', section['prod_port'], DEFAULTS.prod_port),
128
+ staging_port: parseIntField('staging_port', section['staging_port'], DEFAULTS.staging_port),
110
129
  health_url: section['health_url'] ?? DEFAULTS.health_url,
111
- min_disk_mb: parseIntOr(section['min_disk_mb'], DEFAULTS.min_disk_mb),
112
- min_memory_mb: parseIntOr(section['min_memory_mb'], DEFAULTS.min_memory_mb),
130
+ min_disk_mb: parseIntField('min_disk_mb', section['min_disk_mb'], DEFAULTS.min_disk_mb),
131
+ min_memory_mb: parseIntField('min_memory_mb', section['min_memory_mb'], DEFAULTS.min_memory_mb),
113
132
  branch: section['branch'] ?? DEFAULTS.branch,
114
133
  db_strategy: db_strategy_raw,
115
134
  build_cmd: section['build_cmd'] ?? DEFAULTS.build_cmd,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hazo_env",
3
- "version": "0.11.0",
3
+ "version": "0.12.1",
4
4
  "description": "Canonical environment resolver — typed env names, per-env DB/file/secret config, doctor and CLI for hazo apps",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -40,14 +40,14 @@
40
40
  "picocolors": "^1.1.1"
41
41
  },
42
42
  "peerDependencies": {
43
- "hazo_core": "^2.4.1",
44
- "hazo_config": "^2.6.0",
45
- "hazo_connect": "^4.3.3",
46
- "hazo_files": "^3.4.0",
47
- "hazo_secure": "^1.8.1",
43
+ "hazo_core": "^2.5.0",
44
+ "hazo_config": "^2.7.2",
45
+ "hazo_connect": "^4.3.5",
46
+ "hazo_files": "^3.7.0",
47
+ "hazo_secure": "^1.9.1",
48
48
  "hazo_audit": "^2.3.0",
49
- "hazo_pdf": "^2.4.0",
50
- "hazo_i18n": "^0.9.0",
49
+ "hazo_pdf": "^2.5.0",
50
+ "hazo_i18n": "^0.17.0",
51
51
  "react": "^18.0.0 || ^19.0.0",
52
52
  "react-dom": "^18.0.0 || ^19.0.0",
53
53
  "next": "^14.0.0 || ^16.0.0"
@@ -91,9 +91,9 @@
91
91
  "@types/react": "^19.0.0",
92
92
  "@types/react-dom": "^19.0.0",
93
93
  "hazo_core": "^2.5.0",
94
- "hazo_config": "^2.6.0",
94
+ "hazo_config": "^2.7.2",
95
95
  "hazo_connect": "^4.3.5",
96
- "hazo_files": "^3.4.0",
96
+ "hazo_files": "^3.7.0",
97
97
  "next": "^16.0.10",
98
98
  "react": "^19.0.0",
99
99
  "react-dom": "^19.0.0",