hazo_env 0.15.3 → 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.
Files changed (67) hide show
  1. package/CHANGE_LOG.md +120 -0
  2. package/README.md +333 -0
  3. package/dist/bin.d.ts +3 -0
  4. package/dist/bin.d.ts.map +1 -0
  5. package/dist/bin.js +17 -0
  6. package/dist/cli.js +178 -17
  7. package/dist/deploy/build.d.ts +1 -1
  8. package/dist/deploy/build.d.ts.map +1 -1
  9. package/dist/deploy/build.js +51 -14
  10. package/dist/deploy/clean.d.ts +2 -1
  11. package/dist/deploy/clean.d.ts.map +1 -1
  12. package/dist/deploy/clean.js +36 -6
  13. package/dist/deploy/generate-readme-cli.d.ts +3 -0
  14. package/dist/deploy/generate-readme-cli.d.ts.map +1 -0
  15. package/dist/deploy/generate-readme-cli.js +40 -0
  16. package/dist/deploy/help.d.ts +55 -0
  17. package/dist/deploy/help.d.ts.map +1 -0
  18. package/dist/deploy/help.js +545 -0
  19. package/dist/deploy/idle-slots.d.ts +42 -0
  20. package/dist/deploy/idle-slots.d.ts.map +1 -0
  21. package/dist/deploy/idle-slots.js +136 -0
  22. package/dist/deploy/index.d.ts +5 -0
  23. package/dist/deploy/index.d.ts.map +1 -1
  24. package/dist/deploy/index.js +5 -0
  25. package/dist/deploy/init.d.ts +14 -0
  26. package/dist/deploy/init.d.ts.map +1 -1
  27. package/dist/deploy/init.js +14 -1
  28. package/dist/deploy/preflight.d.ts +26 -0
  29. package/dist/deploy/preflight.d.ts.map +1 -0
  30. package/dist/deploy/preflight.js +91 -0
  31. package/dist/deploy/rollback.d.ts +10 -1
  32. package/dist/deploy/rollback.d.ts.map +1 -1
  33. package/dist/deploy/rollback.js +25 -1
  34. package/dist/deploy/share.d.ts +28 -0
  35. package/dist/deploy/share.d.ts.map +1 -0
  36. package/dist/deploy/share.js +53 -0
  37. package/dist/deploy/shared-dirs.d.ts +128 -0
  38. package/dist/deploy/shared-dirs.d.ts.map +1 -0
  39. package/dist/deploy/shared-dirs.js +486 -0
  40. package/dist/deploy/status.d.ts +8 -0
  41. package/dist/deploy/status.d.ts.map +1 -1
  42. package/dist/deploy/status.js +6 -0
  43. package/dist/deploy/switch.d.ts.map +1 -1
  44. package/dist/deploy/switch.js +25 -0
  45. package/dist/deploy/types.d.ts +18 -0
  46. package/dist/deploy/types.d.ts.map +1 -1
  47. package/dist/deploy/verify.d.ts.map +1 -1
  48. package/dist/deploy/verify.js +7 -1
  49. package/dist/envsync/engine.d.ts.map +1 -1
  50. package/dist/envsync/engine.js +21 -7
  51. package/dist/envsync/paths.d.ts +22 -0
  52. package/dist/envsync/paths.d.ts.map +1 -1
  53. package/dist/envsync/paths.js +55 -0
  54. package/dist/peer-hint.d.ts +8 -0
  55. package/dist/peer-hint.d.ts.map +1 -0
  56. package/dist/peer-hint.js +49 -0
  57. package/dist/resolve/config-hint.d.ts +2 -0
  58. package/dist/resolve/config-hint.d.ts.map +1 -0
  59. package/dist/resolve/config-hint.js +23 -0
  60. package/dist/resolve/connect.d.ts.map +1 -1
  61. package/dist/resolve/connect.js +2 -1
  62. package/dist/resolve/deploy.d.ts.map +1 -1
  63. package/dist/resolve/deploy.js +167 -1
  64. package/dist/resolve/envsync.d.ts +16 -0
  65. package/dist/resolve/envsync.d.ts.map +1 -1
  66. package/dist/resolve/envsync.js +19 -0
  67. package/package.json +4 -3
package/CHANGE_LOG.md CHANGED
@@ -1,5 +1,125 @@
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
+
51
+ ## 0.16.0 — 2026-11-25
52
+
53
+ New: shared dirs — upload folders (photos, blog images, composer exports, ...)
54
+ now persist across blue-green `deploy switch`/`deploy init` instead of
55
+ silently splitting per slot (every file written while one slot was live was
56
+ previously invisible after the next switch).
57
+
58
+ - **`shared_root`** config field (`[deploy]` section): absolute directory,
59
+ outside both slot dirs, that holds the real files. Default
60
+ `~/<app_name>-shared` (`~` expanded). Validated at config-resolve time to
61
+ sit outside both the current and peer slot directories.
62
+ - **`shared_dirs`** config field (`[deploy]` section): comma list of
63
+ slot-relative folders (e.g. `var/uploads, data/blog-images`) to persist.
64
+ Default `[]` — feature off, zero behaviour change for existing apps.
65
+ Rejects absolute paths, `..` traversal, duplicates, nested entries, and
66
+ (when `db_strategy` resolves to `copy`) any entry containing the sqlite db
67
+ path — each via a typed `HazoConfigError`.
68
+ - **New core module** `src/deploy/shared-dirs.ts`: `inspectSharedDirs()`
69
+ reports each dir's per-slot state (`linked` / `missing` / `empty-dir` /
70
+ `real-dir` with a file count / `wrong-link`); `ensureLinks()`
71
+ creates/self-heals links (`allowCreate`, `allowReplaceEmpty`). Both throw
72
+ typed `SharedDirError`s (`HAZO_ENV_SHARED_DIR_MISSING` / `_EMPTY_DIR` /
73
+ `_REAL_DIR` / `_WRONG_LINK`). All deploy commands go through this module —
74
+ none touch shared-dir paths on the filesystem directly.
75
+ - **`deploy init`** creates the freshly-cloned peer's shared-dir symlinks
76
+ (`allowCreate: true`) so a new standby is correct from its first build.
77
+ - **`deploy build`** self-heals a missing link and replaces a leftover empty
78
+ real dir on the standby before the destructive `git-pull` step — the only
79
+ command that auto-creates or auto-replaces. A non-empty real dir or a link
80
+ to the wrong target aborts the build, pointing at `deploy share`.
81
+ - **`deploy switch`/`deploy rollback`** refuse to promote/restore a slot with
82
+ any shared-dir drift (any state other than `linked`), bypassable with the
83
+ existing `--force`.
84
+ - **`deploy status`** gains a per-dir, per-slot shared-dirs table.
85
+ - **`deploy clean`** never deletes through a shared-dir symlink — a clean
86
+ target that overlaps a configured `shared_dirs` entry is skipped with a
87
+ warning instead of being `rm -rf`'d.
88
+ - **New command `deploy share`** (`src/deploy/share.ts`, `--dry-run`):
89
+ one-time migration for an app that already has real, per-slot data in
90
+ what `shared_dirs` now names. Merges standby then live into `shared_root`
91
+ (live wins on content conflict; the losing copy is parked under
92
+ `shared_root/.conflicts/<slot>/<dir>/...`, never overwritten or deleted;
93
+ identical files are de-duped silently), swaps the standby's real dir for
94
+ a symlink first and the live slot's last so the running app sees the swap
95
+ as late and as briefly as possible, then re-scans the renamed
96
+ `<dir>.pre-share-<timestamp>` backups for files written during that
97
+ window and merges those too. Idempotent — an already-linked dir reports
98
+ "already linked", and a hand-made link to the expected target is adopted
99
+ rather than redone. Aborts untouched (atomic, all-or-nothing) if any dir
100
+ is already a symlink to the wrong target in either slot. Reports a new
101
+ `RunShareResult` (per-dir counts: from live, from standby, identical,
102
+ conflicts, final link target).
103
+ - **`envsync`**: the realpath containment check (`src/envsync/paths.ts`,
104
+ `src/envsync/engine.ts`) now treats files reached through a shared-dir
105
+ symlink as in-bounds when `[data] root`/`files_root` resolves through one,
106
+ so dumps/restores keep working once an app adopts shared dirs.
107
+ - **Help + docs**: every `deploy` subcommand and every `[deploy]` config key
108
+ now has structured help metadata (`src/deploy/help.ts`) driving
109
+ `hazo-env deploy --help`, `hazo-env deploy <cmd> --help`, and the new
110
+ documentation-only `hazo-env deploy config --help` — reads/writes per live
111
+ slot/standby slot/shared root/state file, config keys used, failure modes
112
+ with exact error codes, examples. `npm run docs:deploy`
113
+ (`src/deploy/generate-readme-cli.ts`) regenerates README.md's "Deploy"
114
+ section — including a first-time "Shared dirs" migration walkthrough —
115
+ from the same metadata, so the CLI and README cannot drift apart.
116
+ - Out of scope (unchanged by this release): object storage (S3/R2)
117
+ migration, sharing sqlite databases between slots, automatic deletion of
118
+ `.pre-share-*` backups, and per-app adoption config for Kinstripe/GoTimer
119
+ (tracked as separate specs).
120
+ - See `docs/adr/0001-shared-dirs-via-symlinks.md` for the symlink-vs-env-var-
121
+ vs-object-storage decision record.
122
+
3
123
  ## 0.15.3 — 2026-11-23
4
124
 
5
125
  Fix: `deploy build` auto-stashes local changes before `git pull`.
package/README.md CHANGED
@@ -194,6 +194,339 @@ hazo-env sync download-files | upload-files --archive <p> [--confirm] [--allow-p
194
194
  hazo-env serve [--port <n>] [--bind <host>] # requires HAZO_ENVSYNC_TOKEN
195
195
  ```
196
196
 
197
+ <!-- BEGIN GENERATED: deploy section (see src/deploy/help.ts) -->
198
+
199
+ ## Deploy (blue-green orchestration)
200
+
201
+ Drives `hazo-env deploy <subcommand>`. Two sibling directories differing only by a blue/green `dir_suffix` (e.g. `gotimer-blue/`, `gotimer-green/`) — one live, one standby — swap roles on `deploy switch`. State lives at `~/.hazo-deploy/<app_name>.json`, never inferred from the directory name alone. All subcommand and config docs below are generated from `src/deploy/help.ts` — see `hazo-env deploy --help` / `hazo-env deploy <cmd> --help` / `hazo-env deploy config --help` for the same content at the terminal.
202
+
203
+ ### Subcommands
204
+
205
+ | Command | Purpose |
206
+ |---|---|
207
+ | `deploy init` | Create peer dir, clone repo, generate config, write state |
208
+ | `deploy build` | Run the full build pipeline on the standby dir |
209
+ | `deploy verify` | Re-run health/typecheck/migration checks on standby |
210
+ | `deploy switch` | Stop prod, start standby on the prod port, run post-switch hooks |
211
+ | `deploy rollback` | Reverse the last switch |
212
+ | `deploy status` | Show live/standby dirs, ports, PM2 state, disk/memory, shared dirs |
213
+ | `deploy clean` | Reclaim disk space from old builds and caches |
214
+ | `deploy share` | One-time migration: merge shared_dirs into shared_root + symlink |
215
+ | `deploy config` | Show every `[deploy]` config key (default, meaning, example) |
216
+
217
+ #### `deploy init`
218
+
219
+ Creates the sibling "standby" directory for a brand-new blue-green app: clones the current directory's git origin into `<app>-<opposite dir_suffix>`, rewrites the clone's own `dir_suffix`, copies gitignored env files across, and records both directories in the state file. Run once, from what becomes the "live" directory.
220
+
221
+ If `shared_dirs` is configured, also creates the peer's shared-dir symlinks so the freshly-cloned standby is correct before its first `deploy build` ever runs — see "Shared dirs" below.
222
+
223
+ **Reads:**
224
+ - live slot: `config/hazo_env_config.ini` (the resolved `[deploy]` section)
225
+ - live slot: `git remote get-url origin`
226
+ - live slot: each `env_files` entry present on disk (best-effort — missing ones are reported, not fatal)
227
+
228
+ **Writes:**
229
+ - external: a new sibling directory — `git clone <origin>` into `<app>-<opposite dir_suffix>`
230
+ - standby slot: `config/hazo_env_config.ini`, with `dir_suffix` swapped blue↔green
231
+ - standby slot: the `[data] root` directory, when the app is sqlite-backed (`db_strategy` resolves to `copy`)
232
+ - standby slot: each found `env_files` entry, copied in (gitignored secrets never travel through `git clone`)
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
+ - 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`)
236
+
237
+ **Config keys used:** `app_name`, `dir_suffix`, `env_files`, `shared_root`, `shared_dirs`
238
+
239
+ **Failure modes:**
240
+ - (plain Error) "Peer directory already exists" — refuses to overwrite an existing peer; remove the stale directory by hand before retrying.
241
+ - (plain Error) "Cannot swap dir_suffix ... expected \"blue\" or \"green\"" / "Could not find a \"dir_suffix = ...\" line" — `dir_suffix` must be exactly "blue" or "green" for the INI rewrite to find and flip it.
242
+ - SharedDirError "HAZO_ENV_SHARED_DIR_REAL_DIR" / "HAZO_ENV_SHARED_DIR_WRONG_LINK" — the freshly-cloned peer already has a real or wrongly-linked `shared_dirs` path (stale debris from a prior partial `init`); run "hazo-env deploy share" to migrate it instead of re-running `init`.
243
+
244
+ **Examples:**
245
+ ```
246
+ hazo-env deploy init
247
+ ```
248
+
249
+ #### `deploy build`
250
+
251
+ - `--stop-prod` — If the memory check fails, stop the live PM2 process first to free memory, then re-check.
252
+ - `--branch=<b>` — Override `config.branch` for the git pull step.
253
+ - `--db=<env>` — Resolve `[db.<env>]` instead of the current `HAZO_ENV` when validating a "shared" db strategy.
254
+ - `--peer-dir=<path>` — Override which directory is treated as "live" for the `--stop-prod` target and the sqlite-copy source (the state file's `live_dir` is still used otherwise).
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.
257
+
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.").
261
+
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.
263
+
264
+ **Reads:**
265
+ - state file: `standby_dir` must equal `cwd` (the guard above)
266
+ - standby slot: free disk (`df`) compared against `min_disk_mb`
267
+ - external: free memory compared against `min_memory_mb`
268
+ - standby slot: `resolveConnectConfig()` (or `--db`) to resolve `db_strategy: "auto"` to `copy`/`shared`
269
+ - live slot: the sqlite db file (copy strategy only, to back up from)
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?)
272
+
273
+ **Writes:**
274
+ - standby slot: cache cleanup (same targets as `deploy clean`) then a disk-free check
275
+ - live slot: `pm2 stop <app_name>` (only with `--stop-prod`, only if memory is still low after cleanup)
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`
277
+ - standby slot: sqlite backup copy from the live slot (copy strategy) — or nothing, for the "shared" strategy (same Postgres DB, no copy)
278
+ - standby slot: `migrate_cmd`, only if non-empty
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`.
280
+ - standby slot: stale `<app_name>-staging` pm2 process deleted, then a fresh one started on `staging_port`
281
+ - external: health check against `health_url` on `staging_port` (retried)
282
+ - state file: `last_build` / `last_build_status` — written once the pipeline reaches `git-pull` (so an early abort above that point never marks a build as attempted), and again with the final outcome when the pipeline finishes
283
+
284
+ **Config keys used:** `app_name`, `dir_suffix`, `branch`, `db_strategy`, `install_cmd`, `pre_build_cmd`, `build_cmd`, `migrate_cmd`, `min_disk_mb`, `min_memory_mb`, `staging_port`, `health_url`, `shared_root`, `shared_dirs`
285
+
286
+ **Failure modes:**
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.
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`.)
292
+
293
+ **Examples:**
294
+ ```
295
+ hazo-env deploy build
296
+ hazo-env deploy build --stop-prod --branch=release
297
+ ```
298
+
299
+ #### `deploy verify`
300
+
301
+ Re-checks the already-running staging process without rebuilding anything — the gate to run again after fixing something `deploy build` already succeeded past, right before `deploy switch`.
302
+
303
+ Never throws on a failed check: each of the three checks (`health`, `typescript`, `migration-parity`) reports `pass` / `fail` / `skipped` in the returned `checks[]` array; the CLI exits with status 1 if any check failed.
304
+
305
+ **Reads:**
306
+ - state file: to find the standby dir and `staging_port`
307
+ - external: `curl` against `health_url` on `staging_port` (2 attempts, 500ms apart — a smaller retry budget than `build`'s, since the app should already be up)
308
+ - standby slot: `verify_tsc_cmd`, run with `cwd` set to the standby dir
309
+ - live + standby slot: each one's `_migrations` table (read-only), compared for parity — only when `db_strategy` resolves to "copy" (sqlite); `skipped` otherwise
310
+
311
+ **Writes:**
312
+ - (none — verify never mutates the filesystem, pm2, or the state file)
313
+
314
+ **Config keys used:** `staging_port`, `health_url`, `verify_tsc_cmd`, `db_strategy`
315
+
316
+ **Failure modes:**
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`.
319
+
320
+ **Examples:**
321
+ ```
322
+ hazo-env deploy verify
323
+ ```
324
+
325
+ #### `deploy switch`
326
+
327
+ - `--force` — Bypass BOTH the build-recency check (standby must have a successful build since the last switch) AND the shared-dirs drift check below.
328
+
329
+ Promotes the standby directory to live: deletes (not stops — a fresh `pm2 start` follows) the current live PM2 process, starts the standby fresh on `prod_port`, runs `post_switch_cmd(s)`, and swaps `live_dir`/`standby_dir` in the state file.
330
+
331
+ Refuses to promote a standby that has not had a successful `deploy build` since the last switch, and refuses to promote onto a slot with shared-dir drift — both only unless `--force` is passed.
332
+
333
+ **Reads:**
334
+ - state file: `live_dir`/`standby_dir`, and `last_build`/`last_build_status`/`last_switch` for the build-recency check
335
+ - standby slot: `git rev-parse HEAD` (recorded as `git_ref` in the new state)
336
+ - live + standby slot: `inspectSharedDirs` (read-only) — skipped entirely when `shared_dirs` is empty or `--force` is passed
337
+
338
+ **Writes:**
339
+ - live slot (old): `pm2 delete <app_name>`
340
+ - standby slot (old): `pm2 delete <app_name>-staging`, then a fresh `pm2 start` on `prod_port` (this directory becomes the new live slot)
341
+ - standby slot (old, now live): each `post_switch_cmd` / `post_switch_cmd_N`, run in order — a failing hook is reported, never fatal
342
+ - state file: `live_dir`/`standby_dir` swapped, `previous_live_dir` set to the old live dir, `last_switch`, `git_ref`, `pm2_process`
343
+ - external: `pm2 save` (failure is a warning, not fatal)
344
+ - external: `sidecar_apps` reloaded/recreated to follow the new live dir (never throws — see sidecar.ts)
345
+
346
+ **Config keys used:** `app_name`, `prod_port`, `post_switch_cmd`, `sidecar_apps`, `shared_dirs`
347
+
348
+ **Failure modes:**
349
+ - (plain Error — SwitchAbortError) "No deploy state found for \"<app>\" — nothing to switch. Run \"deploy init\" first."
350
+ - SwitchAbortError "standby has not had a successful build since the last switch — run \"deploy build\" first, or pass --force to override." (bypassed by `--force`)
351
+ - SwitchAbortError "Shared dir(s) not fully linked in both slots: ... Run \"hazo-env deploy share\" to fix, or pass --force to override." (bypassed by `--force`; never fires when `shared_dirs` is empty)
352
+
353
+ **Examples:**
354
+ ```
355
+ hazo-env deploy switch
356
+ hazo-env deploy switch --force
357
+ ```
358
+
359
+ #### `deploy rollback`
360
+
361
+ - `--force` — Bypass the shared-dirs drift check only — the stale-build guard below has NO bypass.
362
+
363
+ Reverses the most recent `deploy switch`: puts `previous_live_dir` back on `prod_port`. Only reverses a switch that hasn't already been rolled back — there is no history beyond one step.
364
+
365
+ Refuses unconditionally (no `--force`) if `deploy build` has run on the standby since the last switch, because the previous live build may no longer be intact on disk.
366
+
367
+ **Reads:**
368
+ - state file: `previous_live_dir`, `last_build`, `last_switch`
369
+ - live + standby slot: `inspectSharedDirs` (read-only), unless `--force`
370
+ - the directory being restored: `git rev-parse HEAD`
371
+
372
+ **Writes:**
373
+ - current live slot: `pm2 delete <app_name>`
374
+ - restored slot: `pm2 delete <app_name>-staging` if present, then a fresh `pm2 start` on `prod_port`
375
+ - state file: `live_dir`/`standby_dir` swapped back, `previous_live_dir` cleared (rollback is not itself reversible)
376
+ - external: `pm2 save` (warning-only on failure), `sidecar_apps` reload/recreate (never throws)
377
+
378
+ **Config keys used:** `app_name`, `prod_port`, `sidecar_apps`, `shared_dirs`
379
+
380
+ **Failure modes:**
381
+ - RollbackAbortError "No deploy state found for \"<app>\" — nothing to roll back. Run \"deploy init\" first."
382
+ - RollbackAbortError "No previous switch recorded for \"<app>\" — nothing to roll back. ..." — `deploy rollback` only reverses a switch that hasn't already been rolled back.
383
+ - RollbackAbortError "A build has run on standby since the last switch (...) — ... Cannot safely roll back." — NO `--force` bypass exists for this one.
384
+ - RollbackAbortError "Shared dir(s) not fully linked in both slots: ... Run \"hazo-env deploy share\" to fix, or pass --force to override." (bypassed by `--force`)
385
+
386
+ **Examples:**
387
+ ```
388
+ hazo-env deploy rollback
389
+ hazo-env deploy rollback --force
390
+ ```
391
+
392
+ #### `deploy status`
393
+
394
+ Read-only snapshot: which directory is live/standby, whether their PM2 processes are actually running, sidecar freshness, disk/memory headroom, and — when `shared_dirs` is configured — a per-dir, per-slot shared-dirs table (linked / missing / empty-dir / real-dir(N files) / wrong-link).
395
+
396
+ **Reads:**
397
+ - state file: `live_dir`/`standby_dir`/ports/`last_build`/`last_switch`
398
+ - external: `pm2 jlist`, `df -k <cwd>`, `vm_stat` (darwin) or `/proc/meminfo` (linux)
399
+ - live + standby slot: `inspectSharedDirs`, only when the state file exists and `shared_dirs` is non-empty
400
+
401
+ **Writes:**
402
+ - (none)
403
+
404
+ **Config keys used:** `min_memory_mb`, `sidecar_apps`, `shared_root`, `shared_dirs`
405
+
406
+ **Failure modes:**
407
+ - (no thrown error) — a missing state file, or an unreachable `pm2`/`df`/`vm_stat`, each degrade to a `warnings[]` entry and an "(unknown)" field rather than aborting.
408
+
409
+ **Examples:**
410
+ ```
411
+ hazo-env deploy status
412
+ ```
413
+
414
+ #### `deploy clean`
415
+
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).
419
+
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`.
421
+
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.
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
+
426
+ **Reads:**
427
+ - current slot: `du -sk` on each clean target
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`
430
+
431
+ **Writes:**
432
+ - current slot: `rm -rf` on the three targets above (each skipped individually if it overlaps a shared dir)
433
+ - external: `npm cache clean --force`
434
+ - each eligible idle standby slot (`--idle-slots --yes` only): `rm -rf` on `node_modules` and `.next`
435
+
436
+ **Config keys used:** `shared_dirs`, `min_memory_mb`
437
+
438
+ **Failure modes:**
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.
441
+
442
+ **Examples:**
443
+ ```
444
+ hazo-env deploy clean
445
+ hazo-env deploy clean --aggressive
446
+ hazo-env deploy clean --idle-slots
447
+ hazo-env deploy clean --idle-slots --yes
448
+ ```
449
+
450
+ #### `deploy share`
451
+
452
+ - `--dry-run` — Produce the full report without writing, renaming, or linking anything.
453
+
454
+ The one-time migration onto shared dirs for an app that already has real (per-slot) data sitting in what `shared_dirs` now names. Runnable from either slot — live/standby roles always come from the state file's own labels (whichever side wins a content conflict), never from `cwd`.
455
+
456
+ No-op (prints a message and exits) when `shared_dirs` is empty. Safe to re-run: already-linked dirs are reported as such and left untouched (idempotent).
457
+
458
+ Order: merge standby then live into `shared_root` (live wins on content conflict; standby's losing copy is parked, never overwritten or deleted) → swap the STANDBY slot's real dir for the symlink first → swap the LIVE slot's real dir for the symlink last (so the running app sees its folder replaced as late and as briefly as possible) → re-scan both renamed backup dirs for files written during that swap window and merge those too.
459
+
460
+ **Reads:**
461
+ - state file: `live_dir`/`standby_dir` labels (never inferred from `cwd`'s blue/green naming); the standby is used only if it still exists on disk — a missing peer, or no state file at all (pre-`deploy init`), means only the live/current dir is migrated
462
+ - live + standby slot: every file under each configured `shared_dirs` entry (to merge, hash-compare, and copy)
463
+
464
+ **Writes:**
465
+ - shared root: `shared_root/<dir>` created; files copied in preserving mtime and mode; conflicting incoming copies parked under `shared_root/.conflicts/<slot-basename>/<dir>/<relPath>` (never overwrites, never deletes a source file)
466
+ - live + standby slot: each real/empty `<dir>` renamed aside to `<dir>.pre-share-<ISO timestamp>` (never deleted — left for the operator to verify and remove by hand), then replaced with a symlink to `shared_root/<dir>`
467
+ - live + standby slot: the renamed `.pre-share-*` dirs are re-scanned once for files written during the rename race window, and those are merged too
468
+ - state file: NOT written — `deploy share` never updates deploy state.
469
+
470
+ **Config keys used:** `shared_root`, `shared_dirs`
471
+
472
+ **Failure modes:**
473
+ - SharedDirError "HAZO_ENV_SHARED_DIR_WRONG_LINK" — a pre-flight check, before anything is written: if ANY configured dir is already a symlink to somewhere other than the expected target in EITHER slot, the ENTIRE run aborts untouched (atomic all-or-nothing, never partially migrates). Remove the stray link by hand first, or confirm it should point elsewhere.
474
+ - (unwrapped) raw filesystem errors (permission denied, disk full, ...) propagate as-is.
475
+
476
+ **Examples:**
477
+ ```
478
+ hazo-env deploy share --dry-run
479
+ hazo-env deploy share
480
+ ```
481
+
482
+ ### Config reference (`[deploy]`)
483
+
484
+ | Key | Default | Meaning |
485
+ |---|---|---|
486
+ | `app_name` | (none — required) | Logical app name. Also names the state file: ~/.hazo-deploy/<app_name>.json. |
487
+ | `dir_suffix` | (none — required) | Which color suffix THIS directory is (must be exactly "blue" or "green"). The peer is resolved by swapping it on the current directory's basename. |
488
+ | `prod_port` | 3000 | Production PM2 port. |
489
+ | `staging_port` | 3001 | Staging port used by `deploy build`/`deploy verify` before switching. |
490
+ | `health_url` | /api/health | Path hit for health checks during build/verify/status. |
491
+ | `min_disk_mb` | 1024 | Minimum free disk (MB) required before a build proceeds. |
492
+ | `min_memory_mb` | 512 | Minimum free memory (MB) required before a build proceeds (and the threshold `deploy clean`/`deploy status` compare against for swap/memory warnings). |
493
+ | `branch` | main | Git branch pulled by `deploy build` (overridable with `--branch`). |
494
+ | `db_strategy` | auto | How the standby DB is provisioned: auto (infer from [db.*] driver), copy (sqlite file copy from the peer), or shared (both slots point at the same Postgres DB). An invalid value throws at config-resolve time. |
495
+ | `build_cmd` | npm run build | Shell command that builds the app. |
496
+ | `install_cmd` | npm ci | Shell command that installs dependencies. |
497
+ | `pre_build_cmd` | rm -rf .next | Shell command run before the build (cache busting, etc). |
498
+ | `migrate_cmd` | (empty — skipped) | Optional shell command run after DB setup during `deploy build`. Empty (the default) means `deploy build` logs that it's assuming the app's own schema bootstrap runs automatically at startup and moves on. |
499
+ | `post_switch_cmd` | [] (none) | Shell commands run after a successful `deploy switch` (indexnow submission, CDN purge, ...). Numbered suffixes run in order after the unsuffixed key; collection stops at the first missing/blank numbered key, so a gap silently truncates the list. |
500
+ | `sidecar_apps` | [] (none) | Other pm2 app names in the SAME ecosystem file that move with the live dir but are never blue-green-swapped themselves (a cron/scheduler/jobs worker, websocket server, PDF-render pool, ...). |
501
+ | `env_files` | .env.local | Gitignored files (relative to app root) copied from the live dir to the peer during `deploy init`. |
502
+ | `verify_tsc_cmd` | npx tsc --noEmit | Shell command used for the TypeScript check in `deploy verify`. Override to exclude test files, e.g. with a dedicated tsconfig. |
503
+ | `shared_root` | ~/<app_name>-shared | Directory, outside BOTH slot dirs, that `shared_dirs` entries are symlinked from into each slot. Must resolve to an absolute path outside both the current and peer slot directories (validated at config-resolve time). |
504
+ | `shared_dirs` | [] (feature off) | Folders (e.g. var/uploads) that must persist across blue-green slots instead of being duplicated per clone — see "Shared dirs" below. Validated: no absolute paths, no ".." traversal, no duplicates, no entry nested inside another, and (when the resolved db strategy is "copy") no entry containing the sqlite db path. |
505
+
506
+ ### Shared dirs — first-time migration walkthrough
507
+
508
+ An app running blue-green loses every upload a user makes on each `deploy switch` unless the folder it's written to is declared as a shared dir. Migrating an EXISTING app (one that already has real, per-slot data in that folder) is a one-time, interactive step:
509
+
510
+ 1. **Declare the folders.** Add `shared_dirs` (and, optionally, `shared_root`) to `[deploy]` in `hazo_env_config.ini` — in BOTH slots (the live one you edit now, and the standby, which `deploy init`/`deploy build` will keep in sync going forward). Example:
511
+ ```ini
512
+ [deploy]
513
+ shared_root = ~/gotimer-shared
514
+ shared_dirs = var/uploads, data/blog-images
515
+ ```
516
+ 2. **Run the migration once**, from either slot:
517
+ ```
518
+ hazo-env deploy share --dry-run # preview: what would merge, what would conflict, what would link
519
+ hazo-env deploy share # apply it
520
+ ```
521
+ This merges whatever is already on disk in BOTH slots into `shared_root` (the live slot wins any same-path content conflict; the losing copy is parked under `.conflicts/`, never deleted), then replaces each slot's real folder with a symlink into `shared_root` — standby first, live last, so the running app sees the swap as late and as briefly as possible.
522
+ 3. **Read the report.** Each shared dir prints how many files came from live, from standby, how many were identical (deduped), and how many conflicted. A non-zero conflict count means two slots had the SAME path with DIFFERENT content — go look at the parked copies under `<shared_root>/.conflicts/<slot>/<dir>/...` before deleting anything.
523
+ 4. **Verify, then clean up.** `deploy share` never deletes your original data — it renames each slot's old real directory aside to `<dir>.pre-share-<timestamp>`. Once `hazo-env deploy status` shows every shared dir as `linked` in both slots and the app looks right, delete the `.pre-share-*` backup directories by hand.
524
+ 5. **From then on it's automatic.** `deploy init` links a new peer's shared dirs on creation; `deploy build` self-heals a missing link or an empty leftover directory on the standby before it builds; `deploy switch`/`deploy rollback` refuse to promote a slot that isn't fully linked (bypass with `--force` only if you've verified it by hand); `deploy status` shows per-slot drift at a glance; `deploy clean` never deletes through a shared-dir symlink.
525
+
526
+ A BRAND NEW app that has never had real per-slot data in these folders doesn't need this walkthrough at all — just set `shared_dirs` before the first `deploy init`, and every slot starts out correctly linked.
527
+
528
+ <!-- END GENERATED: deploy section -->
529
+
197
530
  ## Config reference (`hazo_env_config.ini`)
198
531
 
199
532
  See `config/hazo_env_config.ini.sample` for the full annotated template.
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
+ }