hazo_env 0.16.0 → 0.17.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/CHANGE_LOG.md CHANGED
@@ -1,5 +1,53 @@
1
1
  # hazo_env — Change Log
2
2
 
3
+ ## 0.17.0 — 2026-11-25
4
+
5
+ New: deploy pre-flight checks and `deploy clean --idle-slots`, from the first
6
+ GoTimer prod deploy on hazo_env (every item below was a real failure there).
7
+
8
+ - **`hazo-env` bin is now `dist/bin.js`**, a thin wrapper that dynamic-imports
9
+ `dist/cli.js`. `npx hazo_env ...` run outside the app (or in an app that
10
+ doesn't list hazo_env as a dependency) used to die with a raw
11
+ `ERR_MODULE_NOT_FOUND` stack for the `hazo_core` peer; it now prints the
12
+ fix (`cd` into the app, `npm i -D hazo_env`, `npx hazo_env <command>`). The
13
+ CLI's own top-level catch uses the same message (`src/peer-hint.ts`).
14
+ - **`deploy build` "cli-dependency" warning step** (also printed by `deploy
15
+ verify`/`deploy switch`) when `hazo_env` is missing from the app's
16
+ `package.json` — the build's own `npm ci` removes a hand-installed copy and
17
+ breaks the next run. Warning only. `BuildStepStatus` gains `'warn'`
18
+ (additive).
19
+ - **`deploy build` "config-untracked" pre-flight**: aborts before `git pull`
20
+ (so `last_build` is untouched) when `config/hazo_env_config.ini` is tracked
21
+ in git — it is per-slot (`dir_suffix` differs), so a tracked copy is
22
+ overwritten by the pull or blocks it. The message gives the `git rm
23
+ --cached` / `.gitignore` fix.
24
+ - **`deploy init`** adds `config/hazo_env_config.ini` to `.git/info/exclude`
25
+ in both slots (local to each clone; never dirties a tracked `.gitignore`).
26
+ New `RunInitResult.configExcludedFrom` (additive).
27
+ - **Missing-config hint**: `HAZO_ENV_CONFIG_FILE_MISSING` from a `-blue`/`-green`
28
+ slot now gives the exact `sed` command to copy the peer slot's INI with
29
+ `dir_suffix` swapped (`src/resolve/config-hint.ts`).
30
+ - **Restored the `git stash` step before `git pull`** (shipped in 0.15.3, lost
31
+ from the 0.16.0 source). It now compares the stash count before and after, so
32
+ older stash entries no longer produce a false "stashed local changes".
33
+ - **Failed build/install steps show the command's output**: the last 40 lines
34
+ of captured stdout+stderr are appended to the failing step (e.g. the real
35
+ `tsc` errors behind Next's bare "Failed to type check.", which go to
36
+ stdout). The CLI prints multi-line step details indented, and no longer
37
+ repeats the whole message in the "Build aborted" line.
38
+ - **`deploy verify` health hint**: a `curl_exit_7` (connection refused) failure
39
+ now says nothing is listening on `staging_port` — run `hazo-env deploy build`
40
+ first (it starts `<app>-staging`), or check `pm2 ls`.
41
+ - **New: `hazo-env deploy clean --idle-slots [--yes]`** (`src/deploy/idle-slots.ts`):
42
+ reclaims `node_modules` + `.next` from every app's idle standby slot listed in
43
+ `~/.hazo-deploy/*.json`. Runs from any directory (no `[deploy]` config
44
+ needed). Dry run unless `--yes`. Skips, with the reason printed, any slot
45
+ that is a `live_dir`, contains the cwd, has a PM2 process `pm_cwd` inside
46
+ it, or has `last_build` newer than `last_switch` (pending switch). Never
47
+ touches `data/`, config, `.env*` or shared dirs, and leaves symlinked
48
+ targets alone. Aborts without cleaning anything if `pm2 jlist` can't be
49
+ read. `deploy build`'s disk-check failure now suggests it.
50
+
3
51
  ## 0.16.0 — 2026-11-25
4
52
 
5
53
  New: shared dirs — upload folders (photos, blog images, composer exports, ...)
package/README.md CHANGED
@@ -232,6 +232,7 @@ If `shared_dirs` is configured, also creates the peer's shared-dir symlinks so t
232
232
  - standby slot: each found `env_files` entry, copied in (gitignored secrets never travel through `git clone`)
233
233
  - shared root + standby slot: shared-dir symlinks — `ensureLinks(standbyDir, { allowCreate: true })` creates `shared_root/<dir>` and the standby's `<dir>` symlink for every `shared_dirs` entry not already linked
234
234
  - state file: `~/.hazo-deploy/<app_name>.json` written fresh (`live_dir` = current dir, `standby_dir` = the new peer)
235
+ - live + standby slot: `.git/info/exclude` gains a `config/hazo_env_config.ini` entry (the INI is per-slot, so it must never be committed; the exclude file is local to each clone and never dirties a tracked `.gitignore`)
235
236
 
236
237
  **Config keys used:** `app_name`, `dir_suffix`, `env_files`, `shared_root`, `shared_dirs`
237
238
 
@@ -254,7 +255,9 @@ hazo-env deploy init
254
255
 
255
256
  Must be run FROM the standby directory — a "standby-dir-guard" step aborts immediately if the state file says `cwd` isn't the recorded `standby_dir`, because running the pipeline against the live dir would git-pull/rebuild the running production tree and, for a sqlite "copy" `db_strategy`, overwrite the live database with the standby's stale one.
256
257
 
257
- Steps run in order and any failure aborts immediately: standby-dir-guard → clean → disk-check → memory-check (→ stop-prod, only if `--stop-prod` and memory is still low) → db-resolve → shared-dirs → git-pull → install → pre-build → build → db-setup → migrate → clean-stale-staging → start-staging → health-check.
258
+ Steps run in order and any failure aborts immediately: standby-dir-guard → (cli-dependency warning) → clean → disk-check → memory-check (→ stop-prod, only if `--stop-prod` and memory is still low) → db-resolve → shared-dirs → config-untracked → (git-stash) → git-pull → install → pre-build → build → db-setup → migrate → clean-stale-staging → start-staging → health-check.
259
+
260
+ Run it via the app's own install (`npm i -D hazo_env`, then `npx hazo_env deploy build`): a "cli-dependency" warning step appears when `hazo_env` is missing from `package.json`, because the build's own `npm ci` would remove a hand-installed copy and break the next run. Uncommitted changes in the standby slot are stashed (never discarded) before `git pull`. A failing install/build step prints the last 40 lines of the command's output (e.g. the actual `tsc` errors behind Next's "Failed to type check.").
258
261
 
259
262
  The "shared-dirs" step runs BEFORE git-pull (the first destructive step) specifically so a shared-dir problem never marks `last_build` as attempted — see the failure modes below.
260
263
 
@@ -265,11 +268,12 @@ The "shared-dirs" step runs BEFORE git-pull (the first destructive step) specifi
265
268
  - standby slot: `resolveConnectConfig()` (or `--db`) to resolve `db_strategy: "auto"` to `copy`/`shared`
266
269
  - live slot: the sqlite db file (copy strategy only, to back up from)
267
270
  - standby slot: its own shared-dir link state (inspected internally by the `ensureLinks` call below)
271
+ - standby slot: `package.json` (is `hazo_env` a dependency?) and `git ls-files --error-unmatch config/hazo_env_config.ini` (is the per-slot INI tracked?)
268
272
 
269
273
  **Writes:**
270
274
  - standby slot: cache cleanup (same targets as `deploy clean`) then a disk-free check
271
275
  - live slot: `pm2 stop <app_name>` (only with `--stop-prod`, only if memory is still low after cleanup)
272
- - standby slot: `git pull` on `branch`, then `install_cmd`, `pre_build_cmd`, `build_cmd`
276
+ - standby slot: `git stash` of any uncommitted changes (recover with `git stash pop`), then `git pull` on `branch`, then `install_cmd`, `pre_build_cmd`, `build_cmd`
273
277
  - standby slot: sqlite backup copy from the live slot (copy strategy) — or nothing, for the "shared" strategy (same Postgres DB, no copy)
274
278
  - standby slot: `migrate_cmd`, only if non-empty
275
279
  - shared root + standby slot: shared-dir self-heal — `ensureLinks(standbyDir, { allowCreate: true, allowReplaceEmpty: true })`. This is the ONLY deploy command that auto-creates a missing link or auto-replaces an empty real directory; everywhere else that's left to `deploy share`.
@@ -281,6 +285,9 @@ The "shared-dirs" step runs BEFORE git-pull (the first destructive step) specifi
281
285
 
282
286
  **Failure modes:**
283
287
  - BuildAbortError (any step name above) — aborts on the first failing step; the error carries every step completed so far for reporting. If `--stop-prod` already stopped production before the abort, the message is prefixed "⚠ PRODUCTION IS DOWN" with the exact `pm2 start` command to bring it back up by hand.
288
+ - BuildAbortError at "config-untracked" — `config/hazo_env_config.ini` is tracked in git. It is per-slot (`dir_suffix` differs), so a pull would overwrite or conflict with the slot's copy; `git rm --cached` it, add it to `.gitignore`, commit, and keep each slot's local copy. Checked before `git-pull`, so `last_build` is untouched.
289
+ - BuildAbortError at "disk-check" — free disk still below `min_disk_mb` after cleanup; the message suggests `hazo-env deploy clean --idle-slots` to reclaim other apps' idle standby `node_modules`/`.next`.
290
+ - HazoConfigError "HAZO_ENV_CONFIG_FILE_MISSING" — no `config/hazo_env_config.ini` in the slot; when the cwd is a `-blue`/`-green` dir and the peer has one, the message gives the exact `sed` command to copy it with `dir_suffix` swapped.
284
291
  - SharedDirError "HAZO_ENV_SHARED_DIR_REAL_DIR" / "HAZO_ENV_SHARED_DIR_WRONG_LINK" (surfaces as the "shared-dirs" build step's failure) — a non-empty real directory, or a symlink to the wrong target, is sitting where a shared-dir link belongs; build refuses and its message points at "hazo-env deploy share". ("HAZO_ENV_SHARED_DIR_MISSING" / "_EMPTY_DIR" never surface here — build always passes `allowCreate` and `allowReplaceEmpty`.)
285
292
 
286
293
  **Examples:**
@@ -308,6 +315,7 @@ Never throws on a failed check: each of the three checks (`health`, `typescript`
308
315
 
309
316
  **Failure modes:**
310
317
  - (no thrown error) — failures are reported per-check in `checks[]`; the process exits 1 if `allPassed` is false.
318
+ - `health` fail with "curl_exit_7" (connection refused) — nothing is listening on `staging_port`; the detail tells you to run `hazo-env deploy build` first (it starts `<app_name>-staging`) or check `pm2 ls`.
311
319
 
312
320
  **Examples:**
313
321
  ```
@@ -406,28 +414,37 @@ hazo-env deploy status
406
414
  #### `deploy clean`
407
415
 
408
416
  - `--aggressive` — Also PRINT (never run) system-level cleanup suggestions (apt/journalctl/docker) that need sudo.
417
+ - `--idle-slots` — Instead: reclaim `node_modules` + `.next` from EVERY app's idle standby slot listed in `~/.hazo-deploy/*.json`. Runs from any directory (no `[deploy]` config needed). Dry run unless `--yes`.
418
+ - `--yes` — With `--idle-slots`: actually delete (default is a dry run that only lists slots and sizes).
409
419
 
410
420
  Deletes `.next.rollback`, `.next.staging`, and `node_modules/.cache`, and runs `npm cache clean --force`. Also called automatically as the first step of `deploy build`.
411
421
 
412
422
  Never deletes through a shared-dir symlink: any clean target that equals, contains, or is contained by a configured `shared_dirs` entry is skipped with a warning instead of being touched.
413
423
 
424
+ `--idle-slots` mode: for every state file in `~/.hazo-deploy`, takes its `standby_dir` and removes only `node_modules` and `.next` (never `data/`, config, `.env*`, or shared dirs; a target that is a symlink is left alone). A slot is skipped, with the reason printed, if it is any app's `live_dir`, is the current directory, has a PM2 process whose `pm_cwd` is inside it, or has `last_build` newer than `last_switch` (built but not yet switched — clearing it would force a rebuild before `deploy switch`). The next `deploy build` on a cleaned slot reinstalls and rebuilds as usual.
425
+
414
426
  **Reads:**
415
427
  - current slot: `du -sk` on each clean target
416
428
  - external: `npm config get cache`, free memory
429
+ - state file (`--idle-slots`): every `~/.hazo-deploy/*.json`; external: `pm2 jlist` for each process's `pm_cwd`; each eligible slot: `test -L` and `du -sk` on `node_modules`/`.next`
417
430
 
418
431
  **Writes:**
419
432
  - current slot: `rm -rf` on the three targets above (each skipped individually if it overlaps a shared dir)
420
433
  - external: `npm cache clean --force`
434
+ - each eligible idle standby slot (`--idle-slots --yes` only): `rm -rf` on `node_modules` and `.next`
421
435
 
422
436
  **Config keys used:** `shared_dirs`, `min_memory_mb`
423
437
 
424
438
  **Failure modes:**
425
439
  - (no thrown error) — a target that fails to clean records `targets[].error` and a warning; "overlaps a configured shared dir" is also a warning, never an abort.
440
+ - IdleSlotsAbortError (`--idle-slots`) — `pm2 jlist` failed or returned unparsable output; nothing is cleaned, since no slot can be proven idle.
426
441
 
427
442
  **Examples:**
428
443
  ```
429
444
  hazo-env deploy clean
430
445
  hazo-env deploy clean --aggressive
446
+ hazo-env deploy clean --idle-slots
447
+ hazo-env deploy clean --idle-slots --yes
431
448
  ```
432
449
 
433
450
  #### `deploy share`
package/dist/bin.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=bin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bin.d.ts","sourceRoot":"","sources":["../src/bin.ts"],"names":[],"mappings":""}
package/dist/bin.js ADDED
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ // hazo_env/src/bin.ts — `hazo-env` bin entry.
3
+ //
4
+ // Thin wrapper: dynamic-imports the real CLI so a peer dependency that can't
5
+ // be resolved at module-link time (cli.ts statically imports modules that
6
+ // import hazo_core) surfaces as a readable fix instead of a raw stack trace.
7
+ import { missingPeerMessage } from './peer-hint.js';
8
+ try {
9
+ await import('./cli.js');
10
+ }
11
+ catch (e) {
12
+ const message = missingPeerMessage(e);
13
+ if (!message)
14
+ throw e;
15
+ console.error(`\n${message}\n`);
16
+ process.exit(1);
17
+ }
package/dist/cli.js CHANGED
@@ -5,6 +5,7 @@ import { getEnv } from './index.client.js';
5
5
  import { describeEnv, getEnvRole, getPattern } from './env.server.js';
6
6
  import { doctor } from './doctor.js';
7
7
  import { DEPLOY_SUBCOMMAND_NAMES, renderDeploySummaryList, renderDeploySubcommandHelpText, renderDeployConfigHelpText, } from './deploy/help.js';
8
+ import { missingPeerMessage } from './peer-hint.js';
8
9
  const [, , command, ...args] = process.argv;
9
10
  function statusIcon(status) {
10
11
  if (status === 'ok')
@@ -304,6 +305,9 @@ async function runDeployInit() {
304
305
  if (result.envFilesMissing.length) {
305
306
  console.log(` ${pc.yellow('⚠')} Env files not found (copy manually): ${result.envFilesMissing.join(', ')}`);
306
307
  }
308
+ if (result.configExcludedFrom.length) {
309
+ console.log(` ${pc.green('✓')} config/hazo_env_config.ini excluded from git in: ${result.configExcludedFrom.join(', ')}`);
310
+ }
307
311
  console.log('');
308
312
  console.log(` Next steps:`);
309
313
  console.log(` cd ${result.peerDir}`);
@@ -325,7 +329,57 @@ function formatBytes(bytes) {
325
329
  return `${(bytes / 1024).toFixed(1)} KB`;
326
330
  return `${bytes} B`;
327
331
  }
332
+ async function runDeployCleanIdleSlots() {
333
+ const { runCleanIdleSlots, IdleSlotsAbortError } = await import('./deploy/idle-slots.js');
334
+ const { nodeCommandRunner } = await import('./deploy/runner.js');
335
+ const yes = args.includes('--yes');
336
+ console.log(`\n${pc.bold('hazo-env deploy clean --idle-slots')}${yes ? '' : pc.dim(' (dry run — re-run with --yes to delete)')}\n`);
337
+ let result;
338
+ try {
339
+ result = runCleanIdleSlots(nodeCommandRunner, { yes });
340
+ }
341
+ catch (e) {
342
+ if (e instanceof IdleSlotsAbortError) {
343
+ console.error(` ${pc.red('✗')} ${e.message}\n`);
344
+ process.exit(1);
345
+ return;
346
+ }
347
+ throw e;
348
+ }
349
+ if (result.slots.length === 0) {
350
+ console.log(` ${pc.dim('No deploy state files found in ~/.hazo-deploy — nothing to clean.')}\n`);
351
+ }
352
+ for (const slot of result.slots) {
353
+ if (!slot.eligible) {
354
+ console.log(` ${pc.dim('·')} ${slot.app_name.padEnd(16)} ${slot.slot_dir} ${pc.yellow(`skipped: ${slot.skipReason}`)}`);
355
+ continue;
356
+ }
357
+ console.log(` ${pc.green('✓')} ${slot.app_name.padEnd(16)} ${slot.slot_dir} ${pc.bold(formatBytes(slot.bytes))}`);
358
+ for (const t of slot.targets) {
359
+ const status = t.error
360
+ ? pc.red(t.error)
361
+ : t.skipped
362
+ ? pc.dim(t.skipReason ?? 'skipped')
363
+ : t.removed
364
+ ? `reclaimed ${formatBytes(t.bytes)}`
365
+ : `${formatBytes(t.bytes)} (would delete)`;
366
+ console.log(` ${t.name.padEnd(14)} ${status}`);
367
+ }
368
+ }
369
+ console.log('');
370
+ console.log(` ${pc.bold(result.dryRun ? 'total reclaimable:' : 'total reclaimed:')} ${formatBytes(result.totalBytes)}`);
371
+ if (result.dryRun && result.totalBytes > 0) {
372
+ console.log(` ${pc.dim('Nothing was deleted. Re-run with --yes to delete node_modules/.next from the slots above.')}`);
373
+ }
374
+ for (const warning of result.warnings)
375
+ console.log(` ${pc.yellow('⚠')} ${warning}`);
376
+ console.log('');
377
+ }
328
378
  async function runDeployClean() {
379
+ if (args.includes('--idle-slots')) {
380
+ await runDeployCleanIdleSlots();
381
+ return;
382
+ }
329
383
  const { resolveDeployConfig } = await import('./resolve/deploy.js');
330
384
  const { runClean } = await import('./deploy/clean.js');
331
385
  const { nodeCommandRunner } = await import('./deploy/runner.js');
@@ -389,9 +443,12 @@ async function runDeployBuild() {
389
443
  console.log(`\n${pc.bold('hazo-env deploy build')} ${pc.dim(config.app_name)}\n`);
390
444
  function printSteps(steps) {
391
445
  for (const step of steps) {
392
- const icon = step.status === 'pass' ? pc.green('✓') : pc.red('✗');
393
- const detail = step.detail ? ` ${pc.dim(step.detail)}` : '';
446
+ const icon = step.status === 'pass' ? pc.green('✓') : step.status === 'warn' ? pc.yellow('⚠') : pc.red('✗');
447
+ const [first = '', ...rest] = (step.detail ?? '').split('\n');
448
+ const detail = first ? ` ${step.status === 'pass' ? pc.dim(first) : first}` : '';
394
449
  console.log(` ${icon} ${step.name.padEnd(16)}${detail}`);
450
+ for (const line of rest)
451
+ console.log(` ${line}`);
395
452
  }
396
453
  }
397
454
  try {
@@ -411,7 +468,10 @@ async function runDeployBuild() {
411
468
  console.log('');
412
469
  printSteps(e.steps);
413
470
  console.log('');
414
- console.error(` ${pc.red('✗ Build aborted:')} ${e.message}\n`);
471
+ const failedStep = e.steps.find((s) => s.status === 'fail');
472
+ console.error(failedStep
473
+ ? ` ${pc.red('✗ Build aborted')} at step "${failedStep.name}" — see its output above.\n`
474
+ : ` ${pc.red('✗ Build aborted:')} ${e.message}\n`);
415
475
  process.exit(1);
416
476
  return;
417
477
  }
@@ -427,12 +487,19 @@ function verifyStatusIcon(status) {
427
487
  return pc.yellow('–');
428
488
  return pc.red('✗');
429
489
  }
490
+ async function printCliDependencyWarning() {
491
+ const { cliDependencyWarning } = await import('./deploy/preflight.js');
492
+ const warning = cliDependencyWarning(process.cwd());
493
+ if (warning)
494
+ console.log(` ${pc.yellow('⚠')} ${warning}\n`);
495
+ }
430
496
  async function runDeployVerify() {
431
497
  const { resolveDeployConfig } = await import('./resolve/deploy.js');
432
498
  const { runVerify } = await import('./deploy/verify.js');
433
499
  const { nodeCommandRunner } = await import('./deploy/runner.js');
434
500
  const config = resolveDeployConfig();
435
501
  console.log(`\n${pc.bold('hazo-env deploy verify')} ${pc.dim(config.app_name)}\n`);
502
+ await printCliDependencyWarning();
436
503
  const result = runVerify(config, nodeCommandRunner, { tscCmd: config.verify_tsc_cmd });
437
504
  const nameWidth = Math.max(...result.checks.map((c) => c.name.length)) + 2;
438
505
  for (const check of result.checks) {
@@ -455,6 +522,7 @@ async function runDeploySwitch() {
455
522
  const force = args.includes('--force');
456
523
  const config = resolveDeployConfig();
457
524
  console.log(`\n${pc.bold('hazo-env deploy switch')} ${pc.dim(config.app_name)}\n`);
525
+ await printCliDependencyWarning();
458
526
  try {
459
527
  const result = runSwitch(config, nodeCommandRunner, { force });
460
528
  console.log(` ${pc.green('✓')} deleted live PM2 registration "${config.app_name}" in ${result.previousLiveDir}`);
@@ -695,6 +763,11 @@ Usage:
695
763
  }
696
764
  }
697
765
  catch (e) {
766
+ const peerMessage = missingPeerMessage(e);
767
+ if (peerMessage) {
768
+ console.error(`\n${peerMessage}\n`);
769
+ process.exit(1);
770
+ }
698
771
  const msg = e instanceof Error ? e.message : String(e);
699
772
  console.error(`\n${pc.red('Error:')} ${msg}\n`);
700
773
  process.exit(1);
@@ -15,7 +15,7 @@ export interface RunBuildOptions {
15
15
  /** Delay between health check retries, in ms. Default: 1500. */
16
16
  healthCheckDelayMs?: number;
17
17
  }
18
- export type BuildStepStatus = 'pass' | 'fail';
18
+ export type BuildStepStatus = 'pass' | 'warn' | 'fail';
19
19
  export interface BuildStepResult {
20
20
  name: string;
21
21
  status: BuildStepStatus;
@@ -1 +1 @@
1
- {"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../../src/deploy/build.ts"],"names":[],"mappings":"AAiCA,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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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,CAuWhH"}
@@ -30,6 +30,7 @@ import { readState, updateState } from './state.js';
30
30
  import { SWAP_INCREASE_SUGGESTIONS } from './clean.js';
31
31
  import { startNamedPm2Process, isPm2ProcessNotFound } from './pm2-start.js';
32
32
  import { ensureLinks } from './shared-dirs.js';
33
+ import { cliDependencyWarning, commandFailureDetail, isDeployConfigGitTracked, TRACKED_DEPLOY_CONFIG_MESSAGE, } from './preflight.js';
33
34
  import { resolveConnectConfig } from '../resolve/connect.js';
34
35
  /** Thrown when any pipeline step fails. Carries the steps completed so far for reporting. */
35
36
  export class BuildAbortError extends Error {
@@ -147,6 +148,10 @@ export function runBuild(config, runner, opts = {}) {
147
148
  function pass(name, detail) {
148
149
  steps.push({ name, status: 'pass', detail });
149
150
  }
151
+ function warn(name, detail) {
152
+ steps.push({ name, status: 'warn', detail });
153
+ warnings.push(detail);
154
+ }
150
155
  function abort(name, message) {
151
156
  const finalMessage = productionStopped
152
157
  ? `${message}\n\n` +
@@ -174,8 +179,10 @@ export function runBuild(config, runner, opts = {}) {
174
179
  catch (e) {
175
180
  if (e instanceof BuildAbortError)
176
181
  throw e;
177
- const msg = e instanceof Error ? e.message : String(e);
178
- return abort(name, msg);
182
+ // commandFailureDetail appends the tail of the command's captured
183
+ // stdout+stderr — `next build` prints its tsc errors to stdout, which
184
+ // execSync keeps on the error object, not in its message.
185
+ return abort(name, commandFailureDetail(e));
179
186
  }
180
187
  }
181
188
  let buildStatus = 'failed';
@@ -198,13 +205,20 @@ export function runBuild(config, runner, opts = {}) {
198
205
  : state
199
206
  ? path.resolve(state.live_dir)
200
207
  : resolvePeerDir(cwd, undefined, config.dir_suffix);
208
+ // Warning only: hazo_env missing from package.json means this run's own
209
+ // `npm ci` (install step) removes it, breaking the NEXT `npx hazo_env`.
210
+ const dependencyWarning = cliDependencyWarning(cwd);
211
+ if (dependencyWarning)
212
+ warn('cli-dependency', dependencyWarning);
201
213
  // Step 1: auto-clean, then check disk free against min_disk_mb.
202
214
  const cleanResult = autoClean(config, runner);
203
215
  pass('clean', `reclaimed ${cleanResult.totalBytesReclaimed} bytes across ${cleanResult.targets.length} targets`);
204
216
  warnings.push(...cleanResult.warnings);
205
217
  const diskFreeMb = queryDiskFreeMb(runner, cwd, warnings);
206
218
  if (diskFreeMb !== undefined && diskFreeMb < config.min_disk_mb) {
207
- abort('disk-check', `Disk free (${diskFreeMb} MB) is still below min_disk_mb (${config.min_disk_mb}) after cleanup.`);
219
+ abort('disk-check', `Disk free (${diskFreeMb} MB) is still below min_disk_mb (${config.min_disk_mb}) after cleanup. ` +
220
+ `Run "hazo-env deploy clean --idle-slots" to reclaim space from other apps' idle standby slots ` +
221
+ `(dry run first; add --yes to delete).`);
208
222
  }
209
223
  pass('disk-check', diskFreeMb !== undefined ? `${diskFreeMb} MB free` : 'unknown — skipping check');
210
224
  // Step 2/3: memory check, optionally freed by stopping the live PM2 process.
@@ -256,6 +270,12 @@ export function runBuild(config, runner, opts = {}) {
256
270
  else {
257
271
  pass('shared-dirs', 'no shared_dirs configured — skipping');
258
272
  }
273
+ // Pre-flight (read-only, so before the destructive marker below): the
274
+ // per-slot INI must not be git-tracked — see preflight.ts's header.
275
+ if (runStep('config-untracked', () => isDeployConfigGitTracked(runner, cwd))) {
276
+ abort('config-untracked', TRACKED_DEPLOY_CONFIG_MESSAGE);
277
+ }
278
+ pass('config-untracked', 'config/hazo_env_config.ini is not tracked by git');
259
279
  // Fix 3: write a provisional/pessimistic `last_build` marker right
260
280
  // before the first DESTRUCTIVE step (git pull) — everything above this
261
281
  // point (guard, disk/memory checks, db-resolve) is read-only, so an
@@ -277,7 +297,18 @@ export function runBuild(config, runner, opts = {}) {
277
297
  catch {
278
298
  // No state file yet — best-effort, same as the finally block below.
279
299
  }
280
- // Step 4: git pull
300
+ // Step 4a: stash any local changes so git pull doesn't fail. The standby
301
+ // dir is a disposable clone; uncommitted edits there are leftover
302
+ // artifacts (npm-install-time package.json rewrites, hand patches), never
303
+ // intentional work. Best-effort: a failed stash just lets the pull
304
+ // report the real conflict. (Shipped in 0.15.3, lost in 0.16.0.)
305
+ const countStashes = () => (runner.spawn('git stash list', { cwd }).stdout ?? '').split('\n').filter((l) => l.trim().length > 0).length;
306
+ const stashesBefore = countStashes();
307
+ const stashResult = runner.spawn('git stash --quiet', { cwd });
308
+ if (stashResult.code === 0 && countStashes() > stashesBefore) {
309
+ pass('git-stash', 'stashed local changes (recover with "git stash list" / "git stash pop")');
310
+ }
311
+ // Step 4b: git pull
281
312
  runStep('git-pull', () => runner.exec(`git pull origin ${branch}`, { cwd }));
282
313
  pass('git-pull', `origin ${branch}`);
283
314
  // Step 5: install
@@ -1 +1 @@
1
- {"version":3,"file":"help.d.ts","sourceRoot":"","sources":["../../src/deploy/help.ts"],"names":[],"mappings":"AA0BA,gGAAgG;AAChG,eAAO,MAAM,uBAAuB,wFAS1B,CAAC;AAEX,MAAM,MAAM,oBAAoB,GAAG,CAAC,OAAO,uBAAuB,CAAC,CAAC,MAAM,CAAC,CAAC;AAE5E,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,oBAAoB;IACnC,IAAI,EAAE,oBAAoB,CAAC;IAC3B,2FAA2F;IAC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AM,CAwClD"}
@@ -55,6 +55,7 @@ export const DEPLOY_SUBCOMMAND_HELP = {
55
55
  'standby slot: each found `env_files` entry, copied in (gitignored secrets never travel through `git clone`)',
56
56
  'shared root + standby slot: shared-dir symlinks — `ensureLinks(standbyDir, { allowCreate: true })` creates `shared_root/<dir>` and the standby\'s `<dir>` symlink for every `shared_dirs` entry not already linked',
57
57
  'state file: `~/.hazo-deploy/<app_name>.json` written fresh (`live_dir` = current dir, `standby_dir` = the new peer)',
58
+ 'live + standby slot: `.git/info/exclude` gains a `config/hazo_env_config.ini` entry (the INI is per-slot, so it must never be committed; the exclude file is local to each clone and never dirties a tracked `.gitignore`)',
58
59
  ],
59
60
  configKeys: ['app_name', 'dir_suffix', 'env_files', 'shared_root', 'shared_dirs'],
60
61
  failureModes: [
@@ -75,7 +76,8 @@ export const DEPLOY_SUBCOMMAND_HELP = {
75
76
  ],
76
77
  description: [
77
78
  'Must be run FROM the standby directory — a "standby-dir-guard" step aborts immediately if the state file says `cwd` isn\'t the recorded `standby_dir`, because running the pipeline against the live dir would git-pull/rebuild the running production tree and, for a sqlite "copy" `db_strategy`, overwrite the live database with the standby\'s stale one.',
78
- 'Steps run in order and any failure aborts immediately: standby-dir-guard → clean → disk-check → memory-check (→ stop-prod, only if `--stop-prod` and memory is still low) → db-resolve → shared-dirs → git-pull → install → pre-build → build → db-setup → migrate → clean-stale-staging → start-staging → health-check.',
79
+ 'Steps run in order and any failure aborts immediately: standby-dir-guard → (cli-dependency warning) → clean → disk-check → memory-check (→ stop-prod, only if `--stop-prod` and memory is still low) → db-resolve → shared-dirs → config-untracked → (git-stash) → git-pull → install → pre-build → build → db-setup → migrate → clean-stale-staging → start-staging → health-check.',
80
+ 'Run it via the app\'s own install (`npm i -D hazo_env`, then `npx hazo_env deploy build`): a "cli-dependency" warning step appears when `hazo_env` is missing from `package.json`, because the build\'s own `npm ci` would remove a hand-installed copy and break the next run. Uncommitted changes in the standby slot are stashed (never discarded) before `git pull`. A failing install/build step prints the last 40 lines of the command\'s output (e.g. the actual `tsc` errors behind Next\'s "Failed to type check.").',
79
81
  'The "shared-dirs" step runs BEFORE git-pull (the first destructive step) specifically so a shared-dir problem never marks `last_build` as attempted — see the failure modes below.',
80
82
  ],
81
83
  reads: [
@@ -85,11 +87,12 @@ export const DEPLOY_SUBCOMMAND_HELP = {
85
87
  'standby slot: `resolveConnectConfig()` (or `--db`) to resolve `db_strategy: "auto"` to `copy`/`shared`',
86
88
  'live slot: the sqlite db file (copy strategy only, to back up from)',
87
89
  'standby slot: its own shared-dir link state (inspected internally by the `ensureLinks` call below)',
90
+ 'standby slot: `package.json` (is `hazo_env` a dependency?) and `git ls-files --error-unmatch config/hazo_env_config.ini` (is the per-slot INI tracked?)',
88
91
  ],
89
92
  writes: [
90
93
  'standby slot: cache cleanup (same targets as `deploy clean`) then a disk-free check',
91
94
  'live slot: `pm2 stop <app_name>` (only with `--stop-prod`, only if memory is still low after cleanup)',
92
- 'standby slot: `git pull` on `branch`, then `install_cmd`, `pre_build_cmd`, `build_cmd`',
95
+ 'standby slot: `git stash` of any uncommitted changes (recover with `git stash pop`), then `git pull` on `branch`, then `install_cmd`, `pre_build_cmd`, `build_cmd`',
93
96
  'standby slot: sqlite backup copy from the live slot (copy strategy) — or nothing, for the "shared" strategy (same Postgres DB, no copy)',
94
97
  'standby slot: `migrate_cmd`, only if non-empty',
95
98
  'shared root + standby slot: shared-dir self-heal — `ensureLinks(standbyDir, { allowCreate: true, allowReplaceEmpty: true })`. This is the ONLY deploy command that auto-creates a missing link or auto-replaces an empty real directory; everywhere else that\'s left to `deploy share`.',
@@ -103,6 +106,9 @@ export const DEPLOY_SUBCOMMAND_HELP = {
103
106
  ],
104
107
  failureModes: [
105
108
  'BuildAbortError (any step name above) — aborts on the first failing step; the error carries every step completed so far for reporting. If `--stop-prod` already stopped production before the abort, the message is prefixed "⚠ PRODUCTION IS DOWN" with the exact `pm2 start` command to bring it back up by hand.',
109
+ 'BuildAbortError at "config-untracked" — `config/hazo_env_config.ini` is tracked in git. It is per-slot (`dir_suffix` differs), so a pull would overwrite or conflict with the slot\'s copy; `git rm --cached` it, add it to `.gitignore`, commit, and keep each slot\'s local copy. Checked before `git-pull`, so `last_build` is untouched.',
110
+ 'BuildAbortError at "disk-check" — free disk still below `min_disk_mb` after cleanup; the message suggests `hazo-env deploy clean --idle-slots` to reclaim other apps\' idle standby `node_modules`/`.next`.',
111
+ 'HazoConfigError "HAZO_ENV_CONFIG_FILE_MISSING" — no `config/hazo_env_config.ini` in the slot; when the cwd is a `-blue`/`-green` dir and the peer has one, the message gives the exact `sed` command to copy it with `dir_suffix` swapped.',
106
112
  'SharedDirError "HAZO_ENV_SHARED_DIR_REAL_DIR" / "HAZO_ENV_SHARED_DIR_WRONG_LINK" (surfaces as the "shared-dirs" build step\'s failure) — a non-empty real directory, or a symlink to the wrong target, is sitting where a shared-dir link belongs; build refuses and its message points at "hazo-env deploy share". ("HAZO_ENV_SHARED_DIR_MISSING" / "_EMPTY_DIR" never surface here — build always passes `allowCreate` and `allowReplaceEmpty`.)',
107
113
  ],
108
114
  examples: ['hazo-env deploy build', 'hazo-env deploy build --stop-prod --branch=release'],
@@ -125,6 +131,7 @@ export const DEPLOY_SUBCOMMAND_HELP = {
125
131
  configKeys: ['staging_port', 'health_url', 'verify_tsc_cmd', 'db_strategy'],
126
132
  failureModes: [
127
133
  '(no thrown error) — failures are reported per-check in `checks[]`; the process exits 1 if `allPassed` is false.',
134
+ '`health` fail with "curl_exit_7" (connection refused) — nothing is listening on `staging_port`; the detail tells you to run `hazo-env deploy build` first (it starts `<app_name>-staging`) or check `pm2 ls`.',
128
135
  ],
129
136
  examples: ['hazo-env deploy verify'],
130
137
  },
@@ -213,18 +220,30 @@ export const DEPLOY_SUBCOMMAND_HELP = {
213
220
  summary: 'Reclaim disk space from old builds and caches',
214
221
  flags: [
215
222
  { flag: '--aggressive', description: 'Also PRINT (never run) system-level cleanup suggestions (apt/journalctl/docker) that need sudo.' },
223
+ { flag: '--idle-slots', description: 'Instead: reclaim `node_modules` + `.next` from EVERY app\'s idle standby slot listed in `~/.hazo-deploy/*.json`. Runs from any directory (no `[deploy]` config needed). Dry run unless `--yes`.' },
224
+ { flag: '--yes', description: 'With `--idle-slots`: actually delete (default is a dry run that only lists slots and sizes).' },
216
225
  ],
217
226
  description: [
218
227
  'Deletes `.next.rollback`, `.next.staging`, and `node_modules/.cache`, and runs `npm cache clean --force`. Also called automatically as the first step of `deploy build`.',
219
228
  'Never deletes through a shared-dir symlink: any clean target that equals, contains, or is contained by a configured `shared_dirs` entry is skipped with a warning instead of being touched.',
229
+ '`--idle-slots` mode: for every state file in `~/.hazo-deploy`, takes its `standby_dir` and removes only `node_modules` and `.next` (never `data/`, config, `.env*`, or shared dirs; a target that is a symlink is left alone). A slot is skipped, with the reason printed, if it is any app\'s `live_dir`, is the current directory, has a PM2 process whose `pm_cwd` is inside it, or has `last_build` newer than `last_switch` (built but not yet switched — clearing it would force a rebuild before `deploy switch`). The next `deploy build` on a cleaned slot reinstalls and rebuilds as usual.',
230
+ ],
231
+ reads: [
232
+ 'current slot: `du -sk` on each clean target',
233
+ 'external: `npm config get cache`, free memory',
234
+ 'state file (`--idle-slots`): every `~/.hazo-deploy/*.json`; external: `pm2 jlist` for each process\'s `pm_cwd`; each eligible slot: `test -L` and `du -sk` on `node_modules`/`.next`',
235
+ ],
236
+ writes: [
237
+ 'current slot: `rm -rf` on the three targets above (each skipped individually if it overlaps a shared dir)',
238
+ 'external: `npm cache clean --force`',
239
+ 'each eligible idle standby slot (`--idle-slots --yes` only): `rm -rf` on `node_modules` and `.next`',
220
240
  ],
221
- reads: ['current slot: `du -sk` on each clean target', 'external: `npm config get cache`, free memory'],
222
- writes: ['current slot: `rm -rf` on the three targets above (each skipped individually if it overlaps a shared dir)', 'external: `npm cache clean --force`'],
223
241
  configKeys: ['shared_dirs', 'min_memory_mb'],
224
242
  failureModes: [
225
243
  '(no thrown error) — a target that fails to clean records `targets[].error` and a warning; "overlaps a configured shared dir" is also a warning, never an abort.',
244
+ 'IdleSlotsAbortError (`--idle-slots`) — `pm2 jlist` failed or returned unparsable output; nothing is cleaned, since no slot can be proven idle.',
226
245
  ],
227
- examples: ['hazo-env deploy clean', 'hazo-env deploy clean --aggressive'],
246
+ examples: ['hazo-env deploy clean', 'hazo-env deploy clean --aggressive', 'hazo-env deploy clean --idle-slots', 'hazo-env deploy clean --idle-slots --yes'],
228
247
  },
229
248
  share: {
230
249
  name: 'share',
@@ -0,0 +1,42 @@
1
+ import type { CommandRunner } from './types.js';
2
+ export declare const IDLE_SLOT_TARGETS: readonly ["node_modules", ".next"];
3
+ export interface IdleSlotTargetResult {
4
+ name: (typeof IDLE_SLOT_TARGETS)[number];
5
+ path: string;
6
+ /** Measured size in bytes (0 when absent). */
7
+ bytes: number;
8
+ /** True when the target was absent, or left alone because it is a symlink. */
9
+ skipped: boolean;
10
+ skipReason?: string;
11
+ /** True once actually removed (only with `yes`). */
12
+ removed: boolean;
13
+ error?: string;
14
+ }
15
+ export interface IdleSlotResult {
16
+ app_name: string;
17
+ slot_dir: string;
18
+ eligible: boolean;
19
+ /** Why the slot was skipped (only when !eligible). */
20
+ skipReason?: string;
21
+ targets: IdleSlotTargetResult[];
22
+ /** Measured bytes (dry run) or bytes actually reclaimed (`yes`). */
23
+ bytes: number;
24
+ }
25
+ export interface RunCleanIdleSlotsOptions {
26
+ /** Actually delete. Default false (dry run: measure and report only). */
27
+ yes?: boolean;
28
+ /** Directory treated as "current" for the cwd safety check. Defaults to process.cwd(). */
29
+ cwd?: string;
30
+ }
31
+ export interface RunCleanIdleSlotsResult {
32
+ dryRun: boolean;
33
+ slots: IdleSlotResult[];
34
+ totalBytes: number;
35
+ warnings: string[];
36
+ }
37
+ export declare class IdleSlotsAbortError extends Error {
38
+ constructor(message: string);
39
+ }
40
+ /** See this file's header. Throws IdleSlotsAbortError only when PM2 state can't be read. */
41
+ export declare function runCleanIdleSlots(runner: CommandRunner, opts?: RunCleanIdleSlotsOptions): RunCleanIdleSlotsResult;
42
+ //# sourceMappingURL=idle-slots.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"idle-slots.d.ts","sourceRoot":"","sources":["../../src/deploy/idle-slots.ts"],"names":[],"mappings":"AAwBA,OAAO,KAAK,EAAE,aAAa,EAAe,MAAM,YAAY,CAAC;AAE7D,eAAO,MAAM,iBAAiB,oCAAqC,CAAC;AAEpE,MAAM,WAAW,oBAAoB;IACnC,IAAI,EAAE,CAAC,OAAO,iBAAiB,CAAC,CAAC,MAAM,CAAC,CAAC;IACzC,IAAI,EAAE,MAAM,CAAC;IACb,8CAA8C;IAC9C,KAAK,EAAE,MAAM,CAAC;IACd,8EAA8E;IAC9E,OAAO,EAAE,OAAO,CAAC;IACjB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,oDAAoD;IACpD,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,cAAc;IAC7B,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,OAAO,CAAC;IAClB,sDAAsD;IACtD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,oBAAoB,EAAE,CAAC;IAChC,oEAAoE;IACpE,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,wBAAwB;IACvC,yEAAyE;IACzE,GAAG,CAAC,EAAE,OAAO,CAAC;IACd,0FAA0F;IAC1F,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,uBAAuB;IACtC,MAAM,EAAE,OAAO,CAAC;IAChB,KAAK,EAAE,cAAc,EAAE,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,EAAE,CAAC;CACpB;AAED,qBAAa,mBAAoB,SAAQ,KAAK;gBAChC,OAAO,EAAE,MAAM;CAI5B;AAuGD,4FAA4F;AAC5F,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,aAAa,EAAE,IAAI,GAAE,wBAA6B,GAAG,uBAAuB,CAoBrH"}
@@ -0,0 +1,136 @@
1
+ // hazo_env/src/deploy/idle-slots.ts — `deploy clean --idle-slots`
2
+ //
3
+ // A host running several blue-green apps keeps a full standby checkout per
4
+ // app, each with its own `node_modules` + `.next` — easily 1 GB+ apiece of
5
+ // disk that nothing is using between deploys. This reclaims exactly those
6
+ // two folders from every app's IDLE standby slot, across every state file
7
+ // in ~/.hazo-deploy (not just the current app's), so it runs from anywhere
8
+ // and needs no [deploy] config in cwd.
9
+ //
10
+ // Safety, per slot (any one skips it, with the reason reported):
11
+ // - it is any app's live_dir;
12
+ // - it is (or contains) the current working directory;
13
+ // - a PM2 process's pm2_env.pm_cwd is (or is inside) it;
14
+ // - its last_build is newer than last_switch (built but not yet switched —
15
+ // clearing it would force a rebuild before `deploy switch`).
16
+ // If `pm2 jlist` can't be read, the whole run aborts: without it nothing
17
+ // proves a slot is idle. Only `node_modules` and `.next` are ever removed —
18
+ // never data/, config, .env*, or shared dirs; a target that is a symlink is
19
+ // left alone (it may point into shared storage). Dry-run by default; pass
20
+ // `yes` to delete. All measurement/removal goes through CommandRunner.
21
+ import fs from 'node:fs';
22
+ import path from 'node:path';
23
+ import { getStateDir } from './state.js';
24
+ export const IDLE_SLOT_TARGETS = ['node_modules', '.next'];
25
+ export class IdleSlotsAbortError extends Error {
26
+ constructor(message) {
27
+ super(message);
28
+ this.name = 'IdleSlotsAbortError';
29
+ }
30
+ }
31
+ function isSameOrInside(child, parent) {
32
+ const rel = path.relative(parent, child);
33
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
34
+ }
35
+ function readAllStates(warnings) {
36
+ const dir = getStateDir();
37
+ if (!fs.existsSync(dir))
38
+ return [];
39
+ const states = [];
40
+ for (const file of fs.readdirSync(dir).filter((f) => f.endsWith('.json')).sort()) {
41
+ try {
42
+ const state = JSON.parse(fs.readFileSync(path.join(dir, file), 'utf-8'));
43
+ if (state && typeof state.standby_dir === 'string' && typeof state.live_dir === 'string') {
44
+ states.push(state);
45
+ }
46
+ else {
47
+ warnings.push(`skipping state file ${file}: missing live_dir/standby_dir`);
48
+ }
49
+ }
50
+ catch {
51
+ warnings.push(`skipping state file ${file}: not valid JSON`);
52
+ }
53
+ }
54
+ return states;
55
+ }
56
+ function queryPm2Cwds(runner) {
57
+ const result = runner.spawn('pm2 jlist');
58
+ if (result.code !== 0) {
59
+ throw new IdleSlotsAbortError(`pm2 jlist failed (exit ${result.code}): ${result.stderr.trim() || 'no stderr'} — cannot prove any slot is idle, nothing cleaned.`);
60
+ }
61
+ let parsed;
62
+ try {
63
+ parsed = JSON.parse(result.stdout);
64
+ }
65
+ catch {
66
+ throw new IdleSlotsAbortError('pm2 jlist returned unparsable JSON — cannot prove any slot is idle, nothing cleaned.');
67
+ }
68
+ if (!Array.isArray(parsed)) {
69
+ throw new IdleSlotsAbortError('pm2 jlist did not return a list — cannot prove any slot is idle, nothing cleaned.');
70
+ }
71
+ return parsed
72
+ .filter((p) => typeof p.pm2_env?.pm_cwd === 'string')
73
+ .map((p) => ({ name: p.name ?? '(unnamed)', cwd: path.resolve(p.pm2_env.pm_cwd) }));
74
+ }
75
+ function skipReasonFor(state, slot, cwd, liveDirs, pm2Cwds) {
76
+ if (!fs.existsSync(slot))
77
+ return 'slot directory does not exist';
78
+ if (liveDirs.includes(slot))
79
+ return 'it is a live_dir';
80
+ if (isSameOrInside(cwd, slot))
81
+ return 'it is the current working directory';
82
+ const proc = pm2Cwds.find((p) => isSameOrInside(p.cwd, slot));
83
+ if (proc)
84
+ return `PM2 process "${proc.name}" is running from it`;
85
+ if (state.last_build && (!state.last_switch || Date.parse(state.last_build) > Date.parse(state.last_switch))) {
86
+ return `pending build (last_build ${state.last_build} is newer than last_switch ${state.last_switch ?? '(never)'}) — clearing it would force a rebuild before switch`;
87
+ }
88
+ return undefined;
89
+ }
90
+ function measureKb(runner, absPath) {
91
+ const result = runner.spawn(`du -sk ${JSON.stringify(absPath)}`);
92
+ if (result.code !== 0)
93
+ return undefined;
94
+ const kb = Number(result.stdout.trim().split(/\s+/)[0]);
95
+ return Number.isFinite(kb) ? kb : undefined;
96
+ }
97
+ function processTarget(runner, slot, name, yes, warnings) {
98
+ const absPath = path.join(slot, name);
99
+ if (runner.spawn(`test -L ${JSON.stringify(absPath)}`).code === 0) {
100
+ return { name, path: absPath, bytes: 0, skipped: true, skipReason: 'symlink — left alone (may point at shared storage)', removed: false };
101
+ }
102
+ const kb = measureKb(runner, absPath);
103
+ if (kb === undefined) {
104
+ return { name, path: absPath, bytes: 0, skipped: true, skipReason: 'not present', removed: false };
105
+ }
106
+ const bytes = kb * 1024;
107
+ if (!yes)
108
+ return { name, path: absPath, bytes, skipped: false, removed: false };
109
+ const rm = runner.spawn(`rm -rf ${JSON.stringify(absPath)}`);
110
+ if (rm.code !== 0) {
111
+ const error = rm.stderr.trim() || `exit ${rm.code}`;
112
+ warnings.push(`failed to remove ${absPath}: ${error}`);
113
+ return { name, path: absPath, bytes: 0, skipped: false, removed: false, error };
114
+ }
115
+ return { name, path: absPath, bytes, skipped: false, removed: true };
116
+ }
117
+ /** See this file's header. Throws IdleSlotsAbortError only when PM2 state can't be read. */
118
+ export function runCleanIdleSlots(runner, opts = {}) {
119
+ const yes = opts.yes === true;
120
+ const cwd = path.resolve(opts.cwd ?? process.cwd());
121
+ const warnings = [];
122
+ const states = readAllStates(warnings);
123
+ const pm2Cwds = states.length > 0 ? queryPm2Cwds(runner) : [];
124
+ const liveDirs = states.map((s) => path.resolve(s.live_dir));
125
+ const slots = states.map((state) => {
126
+ const slot = path.resolve(state.standby_dir);
127
+ const skipReason = skipReasonFor(state, slot, cwd, liveDirs, pm2Cwds);
128
+ if (skipReason) {
129
+ return { app_name: state.app_name, slot_dir: slot, eligible: false, skipReason, targets: [], bytes: 0 };
130
+ }
131
+ const targets = IDLE_SLOT_TARGETS.map((name) => processTarget(runner, slot, name, yes, warnings));
132
+ const bytes = targets.reduce((sum, t) => sum + t.bytes, 0);
133
+ return { app_name: state.app_name, slot_dir: slot, eligible: true, targets, bytes };
134
+ });
135
+ return { dryRun: !yes, slots, totalBytes: slots.reduce((sum, s) => sum + s.bytes, 0), warnings };
136
+ }
@@ -14,4 +14,6 @@ export * from './switch.js';
14
14
  export * from './rollback.js';
15
15
  export * from './share.js';
16
16
  export * from './help.js';
17
+ export * from './preflight.js';
18
+ export * from './idle-slots.js';
17
19
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
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,cAAc,CAAC;AAC7B,cAAc,kBAAkB,CAAC;AACjC,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;AAC9B,cAAc,YAAY,CAAC;AAC3B,cAAc,WAAW,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,cAAc,CAAC;AAC7B,cAAc,kBAAkB,CAAC;AACjC,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;AAC9B,cAAc,YAAY,CAAC;AAC3B,cAAc,WAAW,CAAC;AAC1B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC"}
@@ -24,3 +24,5 @@ export * from './switch.js';
24
24
  export * from './rollback.js';
25
25
  export * from './share.js';
26
26
  export * from './help.js';
27
+ export * from './preflight.js';
28
+ export * from './idle-slots.js';
@@ -19,6 +19,12 @@ export interface RunInitResult {
19
19
  * every existing caller of `runInit` is unaffected).
20
20
  */
21
21
  sharedDirsLinked: EnsureLinkResult[];
22
+ /**
23
+ * Slot dirs whose `.git/info/exclude` gained a `config/hazo_env_config.ini`
24
+ * entry (the INI is per-slot, so it must never be committed). Local to each
25
+ * clone, so it never dirties a tracked .gitignore.
26
+ */
27
+ configExcludedFrom: string[];
22
28
  }
23
29
  /**
24
30
  * Create the peer (standby) directory: resolve its path, abort if it
@@ -1 +1 @@
1
- {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../src/deploy/init.ts"],"names":[],"mappings":"AAsBA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAe,MAAM,YAAY,CAAC;AAC3E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAgDzD,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;IAClB,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,eAAe,EAAE,MAAM,EAAE,CAAC;IAC1B;;;;;OAKG;IACH,gBAAgB,EAAE,gBAAgB,EAAE,CAAC;CACtC;AA0CD;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,GAAE,cAAmB,GAAG,aAAa,CA0D7G"}
1
+ {"version":3,"file":"init.d.ts","sourceRoot":"","sources":["../../src/deploy/init.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAe,MAAM,YAAY,CAAC;AAC3E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAgDzD,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;IAClB,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,eAAe,EAAE,MAAM,EAAE,CAAC;IAC1B;;;;;OAKG;IACH,gBAAgB,EAAE,gBAAgB,EAAE,CAAC;IACrC;;;;OAIG;IACH,kBAAkB,EAAE,MAAM,EAAE,CAAC;CAC9B;AA0CD;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,GAAE,cAAmB,GAAG,aAAa,CA4D7G"}
@@ -19,6 +19,7 @@ import { resolvePeerDir } from './peer.js';
19
19
  import { writeState } from './state.js';
20
20
  import { getEnv } from '../index.client.js';
21
21
  import { ensureLinks } from './shared-dirs.js';
22
+ import { excludeDeployConfigFromGit } from './preflight.js';
22
23
  const CONFIG_RELATIVE_PATH = path.join('config', 'hazo_env_config.ini');
23
24
  // Matches resolve/files.ts's DEFAULT_DATA_ROOT — kept as a local literal
24
25
  // rather than importing that module, since resolveFilesConfig()/
@@ -144,6 +145,7 @@ export function runInit(config, runner, opts = {}) {
144
145
  envFilesMissing.push(envFile);
145
146
  }
146
147
  }
148
+ const configExcludedFrom = [currentDir, peerDir].filter((dir) => excludeDeployConfigFromGit(dir));
147
149
  const state = {
148
150
  app_name: config.app_name,
149
151
  live_dir: currentDir,
@@ -152,5 +154,5 @@ export function runInit(config, runner, opts = {}) {
152
154
  staging_port: config.staging_port,
153
155
  };
154
156
  writeState(state);
155
- return { currentDir, peerDir, originUrl, envFilesCopied, envFilesMissing, sharedDirsLinked };
157
+ return { currentDir, peerDir, originUrl, envFilesCopied, envFilesMissing, sharedDirsLinked, configExcludedFrom };
156
158
  }
@@ -0,0 +1,26 @@
1
+ import type { CommandRunner } from './types.js';
2
+ export declare const DEPLOY_CONFIG_RELATIVE_PATH: string;
3
+ /** Default number of trailing output lines shown for a failed command. */
4
+ export declare const FAILURE_OUTPUT_TAIL_LINES = 40;
5
+ /**
6
+ * Warning text when `cwd/package.json` exists but lists hazo_env in neither
7
+ * dependencies nor devDependencies; undefined otherwise (including when
8
+ * there is no package.json at all).
9
+ */
10
+ export declare function cliDependencyWarning(cwd: string): string | undefined;
11
+ /** True when config/hazo_env_config.ini is tracked by git in `cwd`. */
12
+ export declare function isDeployConfigGitTracked(runner: CommandRunner, cwd: string): boolean;
13
+ export declare const TRACKED_DEPLOY_CONFIG_MESSAGE: string;
14
+ /**
15
+ * Add the per-slot config path to `<dir>/.git/info/exclude` (local to that
16
+ * clone, so it never dirties a tracked .gitignore). Returns true if an entry
17
+ * was added; false if `dir` isn't a git checkout or the entry already exists.
18
+ */
19
+ export declare function excludeDeployConfigFromGit(dir: string): boolean;
20
+ /**
21
+ * Describe a failed CommandRunner.exec: the error's first line plus the tail
22
+ * of the command's captured stdout+stderr (execSync errors carry both as
23
+ * properties). Falls back to the plain message when no output was captured.
24
+ */
25
+ export declare function commandFailureDetail(e: unknown, tailLines?: number): string;
26
+ //# sourceMappingURL=preflight.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"preflight.d.ts","sourceRoot":"","sources":["../../src/deploy/preflight.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD,eAAO,MAAM,2BAA2B,QAA6C,CAAC;AAEtF,0EAA0E;AAC1E,eAAO,MAAM,yBAAyB,KAAK,CAAC;AAE5C;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAcpE;AAED,uEAAuE;AACvE,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAGpF;AAED,eAAO,MAAM,6BAA6B,QAOmE,CAAC;AAE9G;;;;GAIG;AACH,wBAAgB,0BAA0B,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAW/D;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,CAAC,EAAE,OAAO,EAAE,SAAS,SAA4B,GAAG,MAAM,CAc9F"}
@@ -0,0 +1,91 @@
1
+ // hazo_env/src/deploy/preflight.ts — Operator-mistake checks shared by deploy commands
2
+ //
3
+ // Each helper encodes a failure mode hit on a real deploy (GoTimer, 2026-11):
4
+ // - hazo_env not listed in the app's package.json: works once via a manual
5
+ // install, then `deploy build`'s own `npm ci` removes it and the next
6
+ // `npx hazo_env` fetches a standalone copy that can't resolve its peers.
7
+ // - config/hazo_env_config.ini tracked in git: `dir_suffix` differs per
8
+ // slot, so a tracked copy is either overwritten by `git pull` (wrong
9
+ // suffix) or blocks the pull against the slot's untracked copy.
10
+ // - a failed install/build reporting only Next's last line ("Failed to type
11
+ // check.") because the actual tsc errors went to stdout, which execSync
12
+ // keeps on the error object rather than in its message.
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ export const DEPLOY_CONFIG_RELATIVE_PATH = path.join('config', 'hazo_env_config.ini');
16
+ /** Default number of trailing output lines shown for a failed command. */
17
+ export const FAILURE_OUTPUT_TAIL_LINES = 40;
18
+ /**
19
+ * Warning text when `cwd/package.json` exists but lists hazo_env in neither
20
+ * dependencies nor devDependencies; undefined otherwise (including when
21
+ * there is no package.json at all).
22
+ */
23
+ export function cliDependencyWarning(cwd) {
24
+ const pkgPath = path.join(cwd, 'package.json');
25
+ if (!fs.existsSync(pkgPath))
26
+ return undefined;
27
+ let pkg;
28
+ try {
29
+ pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
34
+ if (pkg.dependencies?.hazo_env || pkg.devDependencies?.hazo_env)
35
+ return undefined;
36
+ return ('hazo_env is not in this app\'s package.json — the build\'s own `npm ci` will remove it, so the next ' +
37
+ '`npx hazo_env` will fetch a standalone copy that cannot load its peers. Add it: npm i -D hazo_env');
38
+ }
39
+ /** True when config/hazo_env_config.ini is tracked by git in `cwd`. */
40
+ export function isDeployConfigGitTracked(runner, cwd) {
41
+ const result = runner.spawn(`git ls-files --error-unmatch ${DEPLOY_CONFIG_RELATIVE_PATH}`, { cwd });
42
+ return result.code === 0;
43
+ }
44
+ export const TRACKED_DEPLOY_CONFIG_MESSAGE = `${DEPLOY_CONFIG_RELATIVE_PATH} is tracked in git, but it is per-slot (dir_suffix differs between blue ` +
45
+ `and green) — a pull would overwrite this slot's copy or conflict with it. Untrack it from the repo and ` +
46
+ `ignore it, then re-run:\n` +
47
+ ` git rm --cached ${DEPLOY_CONFIG_RELATIVE_PATH}\n` +
48
+ ` echo "${DEPLOY_CONFIG_RELATIVE_PATH}" >> .gitignore\n` +
49
+ ` git commit -m "untrack per-slot hazo_env config" && git push\n` +
50
+ `Keep each slot's local copy (restore it from the peer slot with dir_suffix swapped if a pull deleted it).`;
51
+ /**
52
+ * Add the per-slot config path to `<dir>/.git/info/exclude` (local to that
53
+ * clone, so it never dirties a tracked .gitignore). Returns true if an entry
54
+ * was added; false if `dir` isn't a git checkout or the entry already exists.
55
+ */
56
+ export function excludeDeployConfigFromGit(dir) {
57
+ const gitDir = path.join(dir, '.git');
58
+ if (!fs.existsSync(gitDir) || !fs.statSync(gitDir).isDirectory())
59
+ return false;
60
+ const entry = DEPLOY_CONFIG_RELATIVE_PATH.split(path.sep).join('/');
61
+ const excludePath = path.join(gitDir, 'info', 'exclude');
62
+ const existing = fs.existsSync(excludePath) ? fs.readFileSync(excludePath, 'utf-8') : '';
63
+ if (existing.split('\n').some((line) => line.trim() === entry || line.trim() === `/${entry}`))
64
+ return false;
65
+ fs.mkdirSync(path.dirname(excludePath), { recursive: true });
66
+ const prefix = existing.length > 0 && !existing.endsWith('\n') ? '\n' : '';
67
+ fs.appendFileSync(excludePath, `${prefix}# per-slot blue/green deploy config (hazo_env)\n${entry}\n`, 'utf-8');
68
+ return true;
69
+ }
70
+ /**
71
+ * Describe a failed CommandRunner.exec: the error's first line plus the tail
72
+ * of the command's captured stdout+stderr (execSync errors carry both as
73
+ * properties). Falls back to the plain message when no output was captured.
74
+ */
75
+ export function commandFailureDetail(e, tailLines = FAILURE_OUTPUT_TAIL_LINES) {
76
+ const message = e instanceof Error ? e.message : String(e);
77
+ if (!e || typeof e !== 'object')
78
+ return message;
79
+ const { stdout, stderr } = e;
80
+ const output = [stdout, stderr]
81
+ .map((s) => (typeof s === 'string' ? s : Buffer.isBuffer(s) ? s.toString('utf-8') : ''))
82
+ .filter((s) => s.trim().length > 0)
83
+ .join('\n')
84
+ .trimEnd();
85
+ if (!output)
86
+ return message;
87
+ const lines = output.split('\n');
88
+ const tail = lines.slice(-tailLines);
89
+ const header = lines.length > tailLines ? `last ${tailLines} of ${lines.length} output lines` : 'command output';
90
+ return `${message.split('\n')[0]}\n--- ${header} ---\n${tail.join('\n')}`;
91
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"verify.d.ts","sourceRoot":"","sources":["../../src/deploy/verify.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAe9D,MAAM,MAAM,eAAe,GAAG,QAAQ,GAAG,YAAY,GAAG,kBAAkB,CAAC;AAC3E,MAAM,MAAM,iBAAiB,GAAG,MAAM,GAAG,MAAM,GAAG,SAA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AAC;IAC5B,gFAAgF;IAChF,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,iBAAiB,EAAE,CAAC;IAC5B,2FAA2F;IAC3F,SAAS,EAAE,OAAO,CAAC;CACpB;AAoID;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,GAAE,gBAAqB,GAAG,eAAe,CAgEnH"}
@@ -145,6 +145,8 @@ function checkMigrationParity(cwd, liveDir) {
145
145
  .join('; ');
146
146
  return { name: 'migration-parity', status: 'fail', detail };
147
147
  }
148
+ /** curl's exit code for "connection refused", as reported by checkHealth. */
149
+ const CURL_CONNECTION_REFUSED = 'curl_exit_7';
148
150
  /**
149
151
  * Run all three verify checks against `cwd` (the standby directory, which
150
152
  * should already be running on `config.staging_port`). Every check runs
@@ -172,7 +174,11 @@ export function runVerify(config, runner, opts = {}) {
172
174
  checks.push({
173
175
  name: 'health',
174
176
  status: 'fail',
175
- detail: `${healthUrl} returned "${result.lastCode}" (expected 200) after ${attempts} attempt(s).`,
177
+ detail: `${healthUrl} returned "${result.lastCode}" (expected 200) after ${attempts} attempt(s).` +
178
+ (result.lastCode === CURL_CONNECTION_REFUSED
179
+ ? ` Nothing is listening on staging port ${config.staging_port} — run "hazo-env deploy build" first ` +
180
+ `(it starts the standby app as "${config.app_name}-staging"), or check "pm2 ls".`
181
+ : ''),
176
182
  });
177
183
  }
178
184
  }
@@ -0,0 +1,8 @@
1
+ /** Peer dependency names declared in this package's own package.json. */
2
+ export declare function readPeerNames(): string[];
3
+ /**
4
+ * If `err` is an ERR_MODULE_NOT_FOUND for one of `peerNames`, return a
5
+ * user-facing explanation and fix; otherwise undefined (caller rethrows).
6
+ */
7
+ export declare function missingPeerMessage(err: unknown, peerNames?: string[]): string | undefined;
8
+ //# sourceMappingURL=peer-hint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"peer-hint.d.ts","sourceRoot":"","sources":["../src/peer-hint.ts"],"names":[],"mappings":"AAYA,yEAAyE;AACzE,wBAAgB,aAAa,IAAI,MAAM,EAAE,CAQxC;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,OAAO,EAAE,SAAS,GAAE,MAAM,EAAoB,GAAG,MAAM,GAAG,SAAS,CAmB1G"}
@@ -0,0 +1,49 @@
1
+ // hazo_env/src/peer-hint.ts — Friendly message for a missing peer dependency
2
+ //
3
+ // hazo_env's peers (hazo_core, hazo_config, ...) are only resolvable when the
4
+ // CLI runs from inside an app that installs them. `npx hazo_env ...` outside
5
+ // such an app (or in an app where hazo_env isn't a dependency, so npx fetches
6
+ // a lone copy into ~/.npm/_npx) dies at module load with a raw
7
+ // ERR_MODULE_NOT_FOUND stack. This turns that into an actionable message.
8
+ // Deliberately import-free (beyond node builtins) so it can run before any
9
+ // peer has been loaded.
10
+ import fs from 'node:fs';
11
+ /** Peer dependency names declared in this package's own package.json. */
12
+ export function readPeerNames() {
13
+ try {
14
+ const pkgUrl = new URL('../package.json', import.meta.url);
15
+ const pkg = JSON.parse(fs.readFileSync(pkgUrl, 'utf-8'));
16
+ return Object.keys(pkg.peerDependencies ?? {});
17
+ }
18
+ catch {
19
+ return [];
20
+ }
21
+ }
22
+ /**
23
+ * If `err` is an ERR_MODULE_NOT_FOUND for one of `peerNames`, return a
24
+ * user-facing explanation and fix; otherwise undefined (caller rethrows).
25
+ */
26
+ export function missingPeerMessage(err, peerNames = readPeerNames()) {
27
+ if (!err || typeof err !== 'object')
28
+ return undefined;
29
+ const e = err;
30
+ if (e.code !== 'ERR_MODULE_NOT_FOUND' || typeof e.message !== 'string')
31
+ return undefined;
32
+ const match = e.message.match(/Cannot find package '([^']+)'/);
33
+ if (!match)
34
+ return undefined;
35
+ const pkg = match[1];
36
+ if (!peerNames.includes(pkg))
37
+ return undefined;
38
+ return [
39
+ `hazo-env: cannot load its peer dependency "${pkg}".`,
40
+ '',
41
+ 'hazo_env must run from inside your app, where its peers are installed. Running it via',
42
+ 'npx outside the app (or in an app that does not list hazo_env as a dependency) fetches a',
43
+ 'standalone copy that cannot see them.',
44
+ '',
45
+ 'Fix: cd into the app directory and install it as a devDependency, then re-run:',
46
+ ' npm i -D hazo_env',
47
+ ' npx hazo_env <command>',
48
+ ].join('\n');
49
+ }
@@ -0,0 +1,2 @@
1
+ export declare function missingConfigMessage(filePath: string, cwd?: string): string;
2
+ //# sourceMappingURL=config-hint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config-hint.d.ts","sourceRoot":"","sources":["../../src/resolve/config-hint.ts"],"names":[],"mappings":"AAUA,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,GAAE,MAAsB,GAAG,MAAM,CAe1F"}
@@ -0,0 +1,23 @@
1
+ // hazo_env/src/resolve/config-hint.ts — Error text for a missing hazo_env_config.ini
2
+ //
3
+ // The INI is per-slot in a blue/green deploy (dir_suffix differs) and must
4
+ // stay untracked, so a slot can legitimately lose it (e.g. a pull that
5
+ // removes a previously-tracked copy). When the cwd looks like a slot dir,
6
+ // point at the peer slot's copy with the exact command to restore it.
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ export function missingConfigMessage(filePath, cwd = process.cwd()) {
10
+ const base = `Config file not found: ${filePath}. Create config/hazo_env_config.ini.`;
11
+ const match = path.basename(cwd).match(/^(.*)-(blue|green)$/);
12
+ if (!match)
13
+ return base;
14
+ const [, stem, suffix] = match;
15
+ const peerSuffix = suffix === 'blue' ? 'green' : 'blue';
16
+ const peerConfig = path.join(path.dirname(cwd), `${stem}-${peerSuffix}`, 'config', 'hazo_env_config.ini');
17
+ if (!fs.existsSync(peerConfig)) {
18
+ return `${base} In a blue/green slot, copy the peer slot's file and set dir_suffix = ${suffix} (keep it out of git).`;
19
+ }
20
+ return (`${base} This looks like the "${suffix}" slot — restore it from the peer slot with dir_suffix swapped ` +
21
+ `(the file is per-slot; keep it out of git):\n` +
22
+ ` sed 's/^\\(dir_suffix *= *\\)${peerSuffix}/\\1${suffix}/' ${JSON.stringify(peerConfig)} > config/hazo_env_config.ini`);
23
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../../src/resolve/connect.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,WAAW,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAmB5E;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,GAAE,qBAA0B,GAAG,WAAW,CA+GlF"}
1
+ {"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../../src/resolve/connect.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,WAAW,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAoB5E;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,GAAE,qBAA0B,GAAG,WAAW,CA+GlF"}
@@ -5,6 +5,7 @@ import { HazoConfigError } from 'hazo_core';
5
5
  import { getEnv } from '../index.client.js';
6
6
  import { substitutePlaceholders } from './secrets.js';
7
7
  import { resolveFilesConfig } from './files.js';
8
+ import { missingConfigMessage } from './config-hint.js';
8
9
  function findConfigFile(pkg) {
9
10
  return path.resolve(process.cwd(), 'config', `${pkg}_config.ini`);
10
11
  }
@@ -17,7 +18,7 @@ function loadConfig() {
17
18
  throw new HazoConfigError({
18
19
  code: 'HAZO_ENV_CONFIG_FILE_MISSING',
19
20
  pkg: 'hazo_env',
20
- message: `Config file not found: ${filePath}. Create config/hazo_env_config.ini.`,
21
+ message: missingConfigMessage(filePath),
21
22
  });
22
23
  }
23
24
  }
@@ -1 +1 @@
1
- {"version":3,"file":"deploy.d.ts","sourceRoot":"","sources":["../../src/resolve/deploy.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAyRvD;;;;GAIG;AACH,wBAAgB,mBAAmB,IAAI,YAAY,CA+DlD"}
1
+ {"version":3,"file":"deploy.d.ts","sourceRoot":"","sources":["../../src/resolve/deploy.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AA0RvD;;;;GAIG;AACH,wBAAgB,mBAAmB,IAAI,YAAY,CA+DlD"}
@@ -10,6 +10,7 @@ import { HazoConfig } from 'hazo_config/server';
10
10
  import { HazoConfigError } from 'hazo_core';
11
11
  import { resolvePeerDir } from '../deploy/peer.js';
12
12
  import { resolveConnectConfig } from './connect.js';
13
+ import { missingConfigMessage } from './config-hint.js';
13
14
  const DEFAULTS = {
14
15
  prod_port: 3000,
15
16
  staging_port: 3001,
@@ -35,7 +36,7 @@ function loadConfig() {
35
36
  throw new HazoConfigError({
36
37
  code: 'HAZO_ENV_CONFIG_FILE_MISSING',
37
38
  pkg: 'hazo_env',
38
- message: `Config file not found: ${filePath}. Create config/hazo_env_config.ini.`,
39
+ message: missingConfigMessage(filePath),
39
40
  });
40
41
  }
41
42
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hazo_env",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
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",
@@ -19,7 +19,7 @@
19
19
  "./package.json": "./package.json"
20
20
  },
21
21
  "bin": {
22
- "hazo-env": "./dist/cli.js"
22
+ "hazo-env": "./dist/bin.js"
23
23
  },
24
24
  "files": [
25
25
  "dist",