hazo_env 0.10.4 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGE_LOG.md +79 -0
  2. package/config/hazo_env_config.ini.sample +61 -0
  3. package/dist/cli.js +329 -0
  4. package/dist/deploy/build.d.ts +91 -0
  5. package/dist/deploy/build.d.ts.map +1 -0
  6. package/dist/deploy/build.js +389 -0
  7. package/dist/deploy/clean.d.ts +63 -0
  8. package/dist/deploy/clean.d.ts.map +1 -0
  9. package/dist/deploy/clean.js +135 -0
  10. package/dist/deploy/index.d.ts +13 -0
  11. package/dist/deploy/index.d.ts.map +1 -0
  12. package/dist/deploy/index.js +22 -0
  13. package/dist/deploy/init.d.ts +20 -0
  14. package/dist/deploy/init.d.ts.map +1 -0
  15. package/dist/deploy/init.js +131 -0
  16. package/dist/deploy/peer.d.ts +18 -0
  17. package/dist/deploy/peer.d.ts.map +1 -0
  18. package/dist/deploy/peer.js +48 -0
  19. package/dist/deploy/pm2-start.d.ts +100 -0
  20. package/dist/deploy/pm2-start.d.ts.map +1 -0
  21. package/dist/deploy/pm2-start.js +228 -0
  22. package/dist/deploy/rollback.d.ts +22 -0
  23. package/dist/deploy/rollback.d.ts.map +1 -0
  24. package/dist/deploy/rollback.js +196 -0
  25. package/dist/deploy/runner.d.ts +8 -0
  26. package/dist/deploy/runner.d.ts.map +1 -0
  27. package/dist/deploy/runner.js +35 -0
  28. package/dist/deploy/state.d.ts +19 -0
  29. package/dist/deploy/state.d.ts.map +1 -0
  30. package/dist/deploy/state.js +52 -0
  31. package/dist/deploy/status.d.ts +54 -0
  32. package/dist/deploy/status.d.ts.map +1 -0
  33. package/dist/deploy/status.js +182 -0
  34. package/dist/deploy/switch.d.ts +40 -0
  35. package/dist/deploy/switch.d.ts.map +1 -0
  36. package/dist/deploy/switch.js +183 -0
  37. package/dist/deploy/types.d.ts +96 -0
  38. package/dist/deploy/types.d.ts.map +1 -0
  39. package/dist/deploy/types.js +16 -0
  40. package/dist/deploy/verify.d.ts +41 -0
  41. package/dist/deploy/verify.d.ts.map +1 -0
  42. package/dist/deploy/verify.js +214 -0
  43. package/dist/index.d.ts +2 -0
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +3 -0
  46. package/dist/resolve/connect.d.ts.map +1 -1
  47. package/dist/resolve/connect.js +15 -1
  48. package/dist/resolve/deploy.d.ts +8 -0
  49. package/dist/resolve/deploy.d.ts.map +1 -0
  50. package/dist/resolve/deploy.js +140 -0
  51. package/dist/types/index.d.ts +10 -0
  52. package/dist/types/index.d.ts.map +1 -1
  53. package/package.json +12 -12
@@ -0,0 +1,183 @@
1
+ // hazo_env/src/deploy/switch.ts — `deploy switch`: promote standby to live
2
+ //
3
+ // Makes the already-built, already-verified standby app live. This is the
4
+ // task that WRITES the new live/standby assignment — see build.ts's header
5
+ // for the bug (fixed there) that this file must not repeat: "live" is read
6
+ // from the state file (the authoritative source), never inferred from the
7
+ // blue/green directory-naming convention.
8
+ //
9
+ // Flow (see task-7 brief + the task-7 review fix-round for the full
10
+ // rationale):
11
+ // 1. Read state. No state file -> abort ("deploy init" hasn't run).
12
+ // 2. Read the git ref of the (about-to-be-promoted) standby dir FIRST,
13
+ // before anything is stopped/started — it's read-only, so there's no
14
+ // ordering reason to delay it, and reading it late (after the pm2 swap
15
+ // and hooks have already run) would leave state stale relative to
16
+ // reality if this read happened to fail.
17
+ // 3. Delete the current live PM2 process (`pm2 delete <app_name>` in the
18
+ // live dir) — see "pm2 delete, not stop" below for why `delete` (not
19
+ // `stop`) is required here. "process not found" (nothing registered —
20
+ // e.g. after a reboot without `pm2 save`, or a prior manual delete) is
21
+ // tolerated as non-fatal; any other failure aborts.
22
+ // 4. Delete the staging PM2 process (`pm2 delete <app_name>-staging`,
23
+ // matching build.ts's naming) if still registered — `pm2 stop` here
24
+ // would leave it registered with its `pm_cwd` pointing at THIS cycle's
25
+ // standby dir, so the NEXT `deploy build`'s `startNamedPm2Process` call
26
+ // for the same `-staging` name would restart that stale registration
27
+ // in place instead of creating a fresh one, silently health-checking
28
+ // the OLD build on the next cycle (same bug class as step 3, applied to
29
+ // the staging name). Non-fatal: the operator may have already deleted
30
+ // it, or `deploy build` may not have left it running.
31
+ // 5. Start the standby app on the PRODUCTION port under the PLAIN app name,
32
+ // via the shared `startNamedPm2Process` helper (see pm2-start.ts) — NOT
33
+ // a direct `pm2 start ecosystem.config.js --name ...`, which does not
34
+ // actually rename the process when starting from a config file (the
35
+ // same root-cause bug task 5/build.ts hit, fixed the same way here). On
36
+ // failure, attempts to restart the OLD live build (from the now-deleted
37
+ // live dir) so production isn't left down, and reports plainly whether
38
+ // that restoration succeeded.
39
+ // 6. Run post-switch hooks (`config.post_switch_cmds`), each independently
40
+ // non-fatal: a failing indexnow/cache-purge hook must never block the
41
+ // switch from completing or the state from updating.
42
+ // 7. Update state atomically: standby becomes live, (old) live becomes
43
+ // standby, `previous_live_dir` = the OLD live dir (for `deploy
44
+ // rollback`), `last_switch` + the git ref read in step 2 recorded.
45
+ //
46
+ // pm2 delete, not stop: `pm2 stop <app_name>` leaves the process
47
+ // REGISTERED (merely stopped) with its `pm_cwd` still pointing at the OLD
48
+ // live dir. Starting the standby app afterwards under that same
49
+ // `<app_name>` then doesn't create a fresh registration — pm2 sees the name
50
+ // is already registered and just restarts IT, from its existing (old,
51
+ // live-dir) `pm_cwd`, leaving production on the OLD build while the state
52
+ // file claims the standby dir is live. `pm2 delete` actually deregisters
53
+ // the old process, so `startNamedPm2Process`'s start (step 5) creates a
54
+ // genuinely fresh registration with the correct `pm_cwd`. There is only
55
+ // ever one `<app_name>` registration at a time, so there's no "preserve it
56
+ // for rollback" benefit to `stop` either — `deploy rollback` (task 8) will
57
+ // need to delete-then-fresh-start from `previous_live_dir` the same way, in
58
+ // the opposite direction.
59
+ import path from 'node:path';
60
+ import { readState, updateState } from './state.js';
61
+ import { promoteDirFresh, PromoteDirFreshError } from './pm2-start.js';
62
+ /** Thrown when there's nothing to switch (no state file yet) or a fatal step fails. */
63
+ export class SwitchAbortError extends Error {
64
+ constructor(message) {
65
+ super(message);
66
+ this.name = 'SwitchAbortError';
67
+ }
68
+ }
69
+ /**
70
+ * Promote the standby directory to live. See this file's header for the
71
+ * full step-by-step rationale.
72
+ */
73
+ export function runSwitch(config, runner, opts = {}) {
74
+ // Step 1: read state — the ONLY source of truth for which dir is live vs.
75
+ // standby. Never infer this from the blue/green naming convention here
76
+ // (see build.ts's header for why that was a critical bug there).
77
+ const state = readState(config.app_name);
78
+ if (!state) {
79
+ throw new SwitchAbortError(`No deploy state found for "${config.app_name}" — nothing to switch. Run "deploy init" first.`);
80
+ }
81
+ // Fix 2: refuse to promote standby unless it has had a SUCCESSFUL build
82
+ // since the last switch (or this is the first-ever switch, i.e.
83
+ // last_switch is unset). Without this, a standby dir that crashed
84
+ // mid-build, or was never rebuilt since a prior FAILED attempt, could get
85
+ // promoted to production while the CLI reports "Switch complete." —
86
+ // last_build_status/last_build already exist on the state file for
87
+ // exactly this reason (deploy build always writes them — see build.ts).
88
+ // --force bypasses this one check only (nothing else here is skippable).
89
+ if (!opts.force) {
90
+ const hasSuccessfulRecentBuild = state.last_build_status === 'success' &&
91
+ !!state.last_build &&
92
+ (!state.last_switch || state.last_build > state.last_switch);
93
+ if (!hasSuccessfulRecentBuild) {
94
+ throw new SwitchAbortError(`standby has not had a successful build since the last switch — run "deploy build" first, or pass ` +
95
+ `--force to override.`);
96
+ }
97
+ }
98
+ const oldLiveDir = path.resolve(state.live_dir);
99
+ const oldStandbyDir = path.resolve(state.standby_dir);
100
+ // Step 2: read the new live dir's git ref FIRST, before anything is
101
+ // stopped/started — read-only, so no ordering reason to delay it, and
102
+ // delaying it risks a late failure leaving state stale relative to a
103
+ // switch that already happened in reality (see header).
104
+ const gitRef = runner.exec('git rev-parse HEAD', { cwd: oldStandbyDir }).trim();
105
+ // Steps 3-5: delete (not stop — see header) the current live PM2
106
+ // registration, delete (same reason) the staging registration left by
107
+ // `deploy build`'s health check against the dir now being promoted (a
108
+ // stale one there would make the NEXT `deploy build`'s reuse of
109
+ // `<app>-staging` restart it in place instead of registering fresh — see
110
+ // promoteDirFresh's own header), then fresh-start the standby app on the
111
+ // production port via the shared helper (a direct `pm2 start
112
+ // ecosystem.config.js --name ...` does not actually rename the process —
113
+ // see header). On failure, promoteDirFresh itself attempts to bring the
114
+ // OLD live build back up so production isn't silently left down, and
115
+ // reports plainly whether that worked.
116
+ let stagingStopped;
117
+ let stagingDeleteWarning;
118
+ try {
119
+ const result = promoteDirFresh(runner, {
120
+ fromDir: oldLiveDir,
121
+ toDir: oldStandbyDir,
122
+ name: config.app_name,
123
+ port: config.prod_port,
124
+ stagingName: `${config.app_name}-staging`,
125
+ toLabel: 'standby app',
126
+ fromLabel: 'the previous live build',
127
+ });
128
+ stagingStopped = result.stagingDeleted;
129
+ stagingDeleteWarning = result.stagingDeleteWarning;
130
+ }
131
+ catch (e) {
132
+ if (e instanceof PromoteDirFreshError) {
133
+ throw new SwitchAbortError(e.message);
134
+ }
135
+ throw e;
136
+ }
137
+ // Step 6: post-switch hooks, each independently non-fatal.
138
+ const postSwitchHooks = [];
139
+ for (const cmd of config.post_switch_cmds) {
140
+ try {
141
+ const output = runner.exec(cmd, { cwd: oldStandbyDir });
142
+ postSwitchHooks.push({ cmd, status: 'pass', detail: output });
143
+ }
144
+ catch (e) {
145
+ postSwitchHooks.push({ cmd, status: 'fail', detail: e instanceof Error ? e.message : String(e) });
146
+ }
147
+ }
148
+ // Step 7: update state atomically. previous_live_dir = the OLD live dir
149
+ // (for "deploy rollback" — task 8), not the new one. git_ref was already
150
+ // resolved in step 2, before anything was touched.
151
+ const newState = updateState(config.app_name, {
152
+ live_dir: oldStandbyDir,
153
+ live_port: config.prod_port,
154
+ standby_dir: oldLiveDir,
155
+ staging_port: config.staging_port,
156
+ previous_live_dir: oldLiveDir,
157
+ last_switch: new Date().toISOString(),
158
+ git_ref: gitRef,
159
+ pm2_process: config.app_name,
160
+ });
161
+ // Fix 7: persist the pm2 process list after a successful promotion — see
162
+ // rollback.ts's identical comment for the full rationale. Non-fatal: the
163
+ // switch itself already succeeded, so a failed `pm2 save` is only
164
+ // surfaced as a warning.
165
+ const saveResult = runner.spawn('pm2 save');
166
+ const pm2SaveWarning = saveResult.code !== 0
167
+ ? `"pm2 save" failed after switch (exit ${saveResult.code}): ${saveResult.stderr || saveResult.stdout || 'no output'} — ` +
168
+ `a server reboot's "pm2 resurrect" may restore the OLD pm2 process list even though this switch ` +
169
+ `succeeded. Run "pm2 save" manually.`
170
+ : undefined;
171
+ return {
172
+ previousLiveDir: oldLiveDir,
173
+ newLiveDir: oldStandbyDir,
174
+ newStandbyDir: oldLiveDir,
175
+ prodPort: config.prod_port,
176
+ stagingPort: config.staging_port,
177
+ stagingStopped,
178
+ stagingDeleteWarning,
179
+ pm2SaveWarning,
180
+ postSwitchHooks,
181
+ state: newState,
182
+ };
183
+ }
@@ -0,0 +1,96 @@
1
+ /** Resolved `[deploy]` INI section, with defaults applied. */
2
+ export interface DeployConfig {
3
+ /** Logical app name — also the state file name (~/.hazo-deploy/<app_name>.json). Required, no default. */
4
+ app_name: string;
5
+ /** Suffix distinguishing live/standby sibling dirs (e.g. "green" for "gotimer-green"). Required, no default. */
6
+ dir_suffix: string;
7
+ /** Production PM2 port. Default: 3000 */
8
+ prod_port: number;
9
+ /** Staging port used during build/verify before switch. Default: 3001 */
10
+ staging_port: number;
11
+ /** Path (relative to app root) hit for health checks. Default: /api/health */
12
+ health_url: string;
13
+ /** Minimum free disk (MB) required before a build proceeds. Default: 1024 */
14
+ min_disk_mb: number;
15
+ /** Minimum free memory (MB) required before a build proceeds. Default: 512 */
16
+ min_memory_mb: number;
17
+ /** Git branch pulled by `deploy build` (overridable via --branch). Default: main */
18
+ branch: string;
19
+ /** How the standby DB is provisioned: "auto" infers from [db.*] driver. Default: auto */
20
+ db_strategy: 'auto' | 'copy' | 'shared';
21
+ /** Shell command that builds the app. Default: npm run build */
22
+ build_cmd: string;
23
+ /** Shell command that installs dependencies. Default: npm ci */
24
+ install_cmd: string;
25
+ /** Shell command run before the build (cache busting etc). Default: rm -rf .next */
26
+ pre_build_cmd: string;
27
+ /**
28
+ * Optional shell command run after DB setup during `deploy build` (Task 5).
29
+ * Migrations are project-specific — this package has no generic
30
+ * cross-project migration runner — so an empty string (the default) means
31
+ * "skip"; `deploy build` logs that it's assuming the consuming app's own
32
+ * schema bootstrap runs automatically at startup and moves on.
33
+ */
34
+ migrate_cmd?: string;
35
+ /** Shell commands run after a successful switch (indexnow, CDN purge, ...). May be empty. */
36
+ post_switch_cmds: string[];
37
+ }
38
+ /** Result of a single command execution. */
39
+ export interface CommandResult {
40
+ code: number;
41
+ stdout: string;
42
+ stderr: string;
43
+ }
44
+ /**
45
+ * All external command execution (git, npm, pm2, cp, system checks) flows
46
+ * through this interface. The production implementation (runner.ts) wraps
47
+ * child_process.execSync/spawnSync; tests inject a mock that records calls
48
+ * and returns configurable results. This is the single testing seam for the
49
+ * entire deploy module.
50
+ */
51
+ export interface CommandRunner {
52
+ /** Run `cmd` and return trimmed stdout. Throws on non-zero exit. */
53
+ exec(cmd: string, opts?: {
54
+ cwd?: string;
55
+ env?: Record<string, string>;
56
+ }): string;
57
+ /** Run `cmd` and return the full result (exit code, stdout, stderr) without throwing. */
58
+ spawn(cmd: string, opts?: {
59
+ cwd?: string;
60
+ env?: Record<string, string>;
61
+ }): CommandResult;
62
+ }
63
+ /**
64
+ * Persisted deploy state at ~/.hazo-deploy/<app_name>.json. Tracks which
65
+ * directory is currently live vs. standby, their ports, timestamps of the
66
+ * last build/switch, and enough history to support `deploy rollback`.
67
+ */
68
+ export interface DeployState {
69
+ app_name: string;
70
+ live_dir: string;
71
+ live_port: number;
72
+ standby_dir: string;
73
+ staging_port: number;
74
+ /** ISO timestamp of the last successful switch, if any. */
75
+ last_switch?: string;
76
+ /** ISO timestamp of the last build attempt, if any. */
77
+ last_build?: string;
78
+ last_build_status?: 'success' | 'failed';
79
+ /** Previous live_dir, retained for `deploy rollback`. */
80
+ previous_live_dir?: string;
81
+ /** Git ref (branch or sha) built into the current standby/live dir. */
82
+ git_ref?: string;
83
+ /** PM2 process name managing this app, read from ecosystem.config.js. */
84
+ pm2_process?: string;
85
+ }
86
+ /**
87
+ * Contract for any task that invokes `pm2 start` for this app (build,
88
+ * switch, ...): `deploy status` identifies which directory a PM2 process
89
+ * belongs to by matching `pm2_env.pm_cwd` against `live_dir`/`standby_dir`.
90
+ * PM2 only populates `pm_cwd` correctly when `cwd` is passed explicitly to
91
+ * `pm2 start` (e.g. `--cwd <dir>` or `cwd: <dir>` in ecosystem.config.js) —
92
+ * otherwise it defaults to wherever `pm2 start` itself was invoked from,
93
+ * which silently breaks status's directory matching with no error. Every
94
+ * `pm2 start` call for this app MUST pass `cwd` explicitly.
95
+ */
96
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/deploy/types.ts"],"names":[],"mappings":"AAMA,8DAA8D;AAC9D,MAAM,WAAW,YAAY;IAC3B,0GAA0G;IAC1G,QAAQ,EAAE,MAAM,CAAC;IACjB,gHAAgH;IAChH,UAAU,EAAE,MAAM,CAAC;IACnB,yCAAyC;IACzC,SAAS,EAAE,MAAM,CAAC;IAClB,yEAAyE;IACzE,YAAY,EAAE,MAAM,CAAC;IACrB,8EAA8E;IAC9E,UAAU,EAAE,MAAM,CAAC;IACnB,6EAA6E;IAC7E,WAAW,EAAE,MAAM,CAAC;IACpB,8EAA8E;IAC9E,aAAa,EAAE,MAAM,CAAC;IACtB,oFAAoF;IACpF,MAAM,EAAE,MAAM,CAAC;IACf,yFAAyF;IACzF,WAAW,EAAE,MAAM,GAAG,MAAM,GAAG,QAAQ,CAAC;IACxC,gEAAgE;IAChE,SAAS,EAAE,MAAM,CAAC;IAClB,gEAAgE;IAChE,WAAW,EAAE,MAAM,CAAC;IACpB,oFAAoF;IACpF,aAAa,EAAE,MAAM,CAAC;IACtB;;;;;;OAMG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,6FAA6F;IAC7F,gBAAgB,EAAE,MAAM,EAAE,CAAC;CAC5B;AAED,4CAA4C;AAC5C,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;;;;;GAMG;AACH,MAAM,WAAW,aAAa;IAC5B,oEAAoE;IACpE,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE;QAAE,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KAAE,GAAG,MAAM,CAAC;IACjF,yFAAyF;IACzF,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE;QAAE,GAAG,CAAC,EAAE,MAAM,CAAC;QAAC,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KAAE,GAAG,aAAa,CAAC;CAC1F;AAED;;;;GAIG;AACH,MAAM,WAAW,WAAW;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,2DAA2D;IAC3D,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,uDAAuD;IACvD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,iBAAiB,CAAC,EAAE,SAAS,GAAG,QAAQ,CAAC;IACzC,yDAAyD;IACzD,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,uEAAuE;IACvE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,yEAAyE;IACzE,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;;;;;;;;GASG"}
@@ -0,0 +1,16 @@
1
+ // hazo_env/src/deploy/types.ts — Types for the deploy module (blue-green orchestration)
2
+ //
3
+ // These shapes are load-bearing for every later deploy task (build/verify/
4
+ // switch/rollback/status/clean/init) — do not rename or restructure fields
5
+ // without updating the whole plan.
6
+ export {};
7
+ /**
8
+ * Contract for any task that invokes `pm2 start` for this app (build,
9
+ * switch, ...): `deploy status` identifies which directory a PM2 process
10
+ * belongs to by matching `pm2_env.pm_cwd` against `live_dir`/`standby_dir`.
11
+ * PM2 only populates `pm_cwd` correctly when `cwd` is passed explicitly to
12
+ * `pm2 start` (e.g. `--cwd <dir>` or `cwd: <dir>` in ecosystem.config.js) —
13
+ * otherwise it defaults to wherever `pm2 start` itself was invoked from,
14
+ * which silently breaks status's directory matching with no error. Every
15
+ * `pm2 start` call for this app MUST pass `cwd` explicitly.
16
+ */
@@ -0,0 +1,41 @@
1
+ import type { CommandRunner, DeployConfig } from './types.js';
2
+ export type VerifyCheckName = 'health' | 'typescript' | 'migration-parity';
3
+ export type VerifyCheckStatus = 'pass' | 'fail' | 'skipped';
4
+ export interface VerifyCheckResult {
5
+ name: VerifyCheckName;
6
+ status: VerifyCheckStatus;
7
+ detail: string;
8
+ }
9
+ export interface RunVerifyOptions {
10
+ /** Directory to run `tsc`/resolve the standby db path from. Defaults to process.cwd(). */
11
+ cwd?: string;
12
+ /**
13
+ * Health check retry count. Default: 2.
14
+ *
15
+ * `deploy build`'s health check defaults to 8 retries because it runs
16
+ * immediately after `pm2 start`, before the app has necessarily finished
17
+ * booting. `deploy verify` is re-run against an app that (per this
18
+ * command's own contract) should already be up and running — a long retry
19
+ * budget here would just mask "the app isn't actually running" behind a
20
+ * slow failure. A couple of quick retries still absorbs a brief blip
21
+ * without turning a single bad health check into a 12-second wait.
22
+ */
23
+ healthCheckAttempts?: number;
24
+ /** Delay between health check retries, in ms. Default: 500. */
25
+ healthCheckDelayMs?: number;
26
+ /** Shell command used for the TypeScript check. Default: "npx tsc --noEmit". */
27
+ tscCmd?: string;
28
+ }
29
+ export interface RunVerifyResult {
30
+ checks: VerifyCheckResult[];
31
+ /** True iff no check has status "fail" (a "skipped" check does not count against this). */
32
+ allPassed: boolean;
33
+ }
34
+ /**
35
+ * Run all three verify checks against `cwd` (the standby directory, which
36
+ * should already be running on `config.staging_port`). Every check runs
37
+ * regardless of whether an earlier one failed — see this file's header for
38
+ * why `verify` doesn't abort-on-first-failure the way `deploy build` does.
39
+ */
40
+ export declare function runVerify(config: DeployConfig, runner: CommandRunner, opts?: RunVerifyOptions): RunVerifyResult;
41
+ //# sourceMappingURL=verify.d.ts.map
@@ -0,0 +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,SAAS,CAAC;AAE5D,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,eAAe,CAAC;IACtB,MAAM,EAAE,iBAAiB,CAAC;IAC1B,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,gBAAgB;IAC/B,0FAA0F;IAC1F,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;;;;;;;;;;OAUG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,+DAA+D;IAC/D,kBAAkB,CAAC,EAAE,MAAM,CAAC;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;AAiID;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,IAAI,GAAE,gBAAqB,GAAG,eAAe,CA2DnH"}
@@ -0,0 +1,214 @@
1
+ // hazo_env/src/deploy/verify.ts — `deploy verify`: re-runnable checks against
2
+ // the already-running standby app
3
+ //
4
+ // Unlike `deploy build`, this does NOT rebuild or restart anything. It's the
5
+ // "operator fixes something, re-runs verify, iterates" loop: three
6
+ // independent checks against whatever is already on disk/running on the
7
+ // staging port in the current (standby) directory.
8
+ //
9
+ // 1. Health check — HTTP GET to the staging app's health endpoint.
10
+ // 2. TypeScript — `npx tsc --noEmit` in the standby dir (via CommandRunner).
11
+ // 3. Migration parity — compare the live dir's and the standby dir's sqlite
12
+ // `_migrations` table name-sets for the current DB env (skipped for a
13
+ // shared Postgres DB, where parity trivially holds).
14
+ //
15
+ // Each check is independent: one failing never prevents the others from
16
+ // running — the whole point of `verify` is to surface everything that's
17
+ // still broken in one pass, not to short-circuit at the first problem (that
18
+ // linear-abort behavior belongs to `deploy build`, not here).
19
+ import path from 'node:path';
20
+ import { createRequire } from 'node:module';
21
+ import { checkHealth, reroot, toAbsolute } from './build.js';
22
+ import { readState } from './state.js';
23
+ import { resolveConnectConfig } from '../resolve/connect.js';
24
+ // `doctor.ts`'s own _migrations-parity check (§7a) opens better-sqlite3 via a
25
+ // bare `require(...)`, which only works there because that file is loaded in
26
+ // a context where `require` happens to be in scope. This package builds to
27
+ // real ESM (`"type": "module"`), and under this package's own ESM/ts-jest
28
+ // test setup a bare `require` throws `ReferenceError: require is not
29
+ // defined` (verified directly while building this file). `createRequire`
30
+ // is the correct ESM-safe way to get a working `require` here, so this file
31
+ // uses it rather than copying doctor.ts's literal (and here, broken) form —
32
+ // see this task's report for the full note.
33
+ const require = createRequire(import.meta.url);
34
+ const DEFAULT_VERIFY_HEALTH_ATTEMPTS = 2;
35
+ const DEFAULT_VERIFY_HEALTH_DELAY_MS = 500;
36
+ const DEFAULT_TSC_CMD = 'npx tsc --noEmit';
37
+ /**
38
+ * Open `dbPath` read-only and return its `_migrations` table's name set.
39
+ * Mirrors doctor.ts's §7a shape (open via better-sqlite3, `SELECT name FROM
40
+ * _migrations`, treat a missing table as zero migrations applied) but
41
+ * returns a typed ok/error result instead of pushing directly into a
42
+ * DoctorCheck list, since this is a single live-vs-standby comparison rather
43
+ * than doctor's own N-env matrix.
44
+ *
45
+ * `fileMustExist: true` deliberately deviates from doctor.ts's plain
46
+ * `Database(path)` call: better-sqlite3 silently creates a new empty sqlite
47
+ * file at `path` if none exists, which would turn "the live db path doesn't
48
+ * actually exist" into a false "0 migrations, matches!" instead of a loud
49
+ * error.
50
+ */
51
+ function readMigrationNames(dbPath) {
52
+ let Database;
53
+ try {
54
+ Database = require('better-sqlite3');
55
+ }
56
+ catch (e) {
57
+ return { error: `better-sqlite3 is not available: ${e instanceof Error ? e.message : String(e)}` };
58
+ }
59
+ let db;
60
+ try {
61
+ db = Database(dbPath, { readonly: true, fileMustExist: true });
62
+ }
63
+ catch (e) {
64
+ return { error: `could not open ${dbPath}: ${e instanceof Error ? e.message : String(e)}` };
65
+ }
66
+ try {
67
+ const names = db.prepare('SELECT name FROM _migrations').all().map((r) => r.name);
68
+ return { names: new Set(names) };
69
+ }
70
+ catch {
71
+ // _migrations table doesn't exist yet — treat as zero migrations applied
72
+ // (same lenient behavior as doctor.ts's try/catch around the same query).
73
+ return { names: new Set() };
74
+ }
75
+ finally {
76
+ db.close();
77
+ }
78
+ }
79
+ /**
80
+ * Compare the live dir's and the standby (current) dir's sqlite
81
+ * `_migrations` name-sets for the resolved current-env DB config.
82
+ *
83
+ * Scoped deliberately narrower than doctor.ts's own §7a check: doctor
84
+ * compares N *named envs* against each other (e.g. dev ↔ staging) for
85
+ * `--all --probe`, whereas this compares the SAME env's db as seen from two
86
+ * different directories (live vs standby) in a blue/green pair — the
87
+ * question `deploy verify` needs answered is "did the standby's migrations
88
+ * actually get applied/match the one currently serving traffic", not
89
+ * "do dev and staging happen to agree".
90
+ */
91
+ function checkMigrationParity(cwd, liveDir) {
92
+ let dbConfig;
93
+ try {
94
+ dbConfig = resolveConnectConfig();
95
+ }
96
+ catch (e) {
97
+ return {
98
+ name: 'migration-parity',
99
+ status: 'fail',
100
+ detail: `could not resolve DB config: ${e instanceof Error ? e.message : String(e)}`,
101
+ };
102
+ }
103
+ if (dbConfig.type !== 'sqlite' || !dbConfig.sqlite) {
104
+ return {
105
+ name: 'migration-parity',
106
+ status: 'skipped',
107
+ detail: 'skipped (shared Postgres DB — parity trivially holds)',
108
+ };
109
+ }
110
+ const standbyDbPath = toAbsolute(cwd, dbConfig.sqlite.database_path);
111
+ const liveDbPath = reroot(cwd, liveDir, standbyDbPath);
112
+ if (liveDbPath === standbyDbPath) {
113
+ // Same reasoning as build.ts's db-setup step: the configured path isn't
114
+ // nested under the standby dir at all (e.g. an absolute [data] root
115
+ // shared by both live and standby), so live and standby are reading the
116
+ // exact same file — parity holds by construction.
117
+ return {
118
+ name: 'migration-parity',
119
+ status: 'pass',
120
+ detail: `sqlite db path is outside the live/standby split (shared) — parity holds by construction: ${standbyDbPath}`,
121
+ };
122
+ }
123
+ const liveResult = readMigrationNames(liveDbPath);
124
+ if ('error' in liveResult) {
125
+ return { name: 'migration-parity', status: 'fail', detail: `live db (${liveDbPath}): ${liveResult.error}` };
126
+ }
127
+ const standbyResult = readMigrationNames(standbyDbPath);
128
+ if ('error' in standbyResult) {
129
+ return { name: 'migration-parity', status: 'fail', detail: `standby db (${standbyDbPath}): ${standbyResult.error}` };
130
+ }
131
+ const onlyInLive = [...liveResult.names].filter((n) => !standbyResult.names.has(n));
132
+ const onlyInStandby = [...standbyResult.names].filter((n) => !liveResult.names.has(n));
133
+ if (onlyInLive.length === 0 && onlyInStandby.length === 0) {
134
+ return {
135
+ name: 'migration-parity',
136
+ status: 'pass',
137
+ detail: `${standbyResult.names.size} migration(s) match between live (${liveDbPath}) and standby (${standbyDbPath})`,
138
+ };
139
+ }
140
+ const detail = [
141
+ onlyInLive.length ? `only in live: ${onlyInLive.join(', ')}` : '',
142
+ onlyInStandby.length ? `only in standby: ${onlyInStandby.join(', ')}` : '',
143
+ ]
144
+ .filter(Boolean)
145
+ .join('; ');
146
+ return { name: 'migration-parity', status: 'fail', detail };
147
+ }
148
+ /**
149
+ * Run all three verify checks against `cwd` (the standby directory, which
150
+ * should already be running on `config.staging_port`). Every check runs
151
+ * regardless of whether an earlier one failed — see this file's header for
152
+ * why `verify` doesn't abort-on-first-failure the way `deploy build` does.
153
+ */
154
+ export function runVerify(config, runner, opts = {}) {
155
+ const cwd = path.resolve(opts.cwd ?? process.cwd());
156
+ const attempts = opts.healthCheckAttempts ?? DEFAULT_VERIFY_HEALTH_ATTEMPTS;
157
+ const delayMs = opts.healthCheckDelayMs ?? DEFAULT_VERIFY_HEALTH_DELAY_MS;
158
+ const tscCmd = opts.tscCmd ?? DEFAULT_TSC_CMD;
159
+ const checks = [];
160
+ // 1. Health check.
161
+ const healthUrl = `http://localhost:${config.staging_port}${config.health_url}`;
162
+ try {
163
+ const result = checkHealth(runner, healthUrl, attempts, delayMs);
164
+ if (result.ok) {
165
+ checks.push({
166
+ name: 'health',
167
+ status: 'pass',
168
+ detail: `${healthUrl} -> 200 (attempt ${result.attempts}/${attempts})`,
169
+ });
170
+ }
171
+ else {
172
+ checks.push({
173
+ name: 'health',
174
+ status: 'fail',
175
+ detail: `${healthUrl} returned "${result.lastCode}" (expected 200) after ${attempts} attempt(s).`,
176
+ });
177
+ }
178
+ }
179
+ catch (e) {
180
+ checks.push({ name: 'health', status: 'fail', detail: e instanceof Error ? e.message : String(e) });
181
+ }
182
+ // 2. TypeScript check.
183
+ try {
184
+ const result = runner.spawn(tscCmd, { cwd });
185
+ if (result.code === 0) {
186
+ checks.push({ name: 'typescript', status: 'pass', detail: `${tscCmd} — no errors` });
187
+ }
188
+ else {
189
+ const output = [result.stdout, result.stderr].filter((s) => s.trim().length > 0).join('\n').trim();
190
+ checks.push({
191
+ name: 'typescript',
192
+ status: 'fail',
193
+ detail: output || `${tscCmd} exited with code ${result.code}`,
194
+ });
195
+ }
196
+ }
197
+ catch (e) {
198
+ checks.push({ name: 'typescript', status: 'fail', detail: e instanceof Error ? e.message : String(e) });
199
+ }
200
+ // 3. Migration parity check.
201
+ const state = readState(config.app_name);
202
+ if (!state) {
203
+ checks.push({
204
+ name: 'migration-parity',
205
+ status: 'skipped',
206
+ detail: 'no deploy state found — run "deploy init" first',
207
+ });
208
+ }
209
+ else {
210
+ checks.push(checkMigrationParity(cwd, path.resolve(state.live_dir)));
211
+ }
212
+ const allPassed = checks.every((c) => c.status !== 'fail');
213
+ return { checks, allPassed };
214
+ }
package/dist/index.d.ts CHANGED
@@ -4,6 +4,8 @@ export * from './types/index.js';
4
4
  export * from './resolve/secrets.js';
5
5
  export * from './resolve/connect.js';
6
6
  export * from './resolve/files.js';
7
+ export * from './resolve/deploy.js';
8
+ export * from './deploy/index.js';
7
9
  export * from './doctor.js';
8
10
  export * from './lib/index.js';
9
11
  export { runSsh, assertSafeSshField } from './migrate/ssh-exec.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAE7E,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAEvG,cAAc,kBAAkB,CAAC;AAEjC,cAAc,sBAAsB,CAAC;AACrC,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC;AAEnC,cAAc,aAAa,CAAC;AAE5B,cAAc,gBAAgB,CAAC;AAE/B,OAAO,EAAE,MAAM,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAE7E,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAEvG,cAAc,kBAAkB,CAAC;AAEjC,cAAc,sBAAsB,CAAC;AACrC,cAAc,sBAAsB,CAAC;AACrC,cAAc,oBAAoB,CAAC;AACnC,cAAc,qBAAqB,CAAC;AAEpC,cAAc,mBAAmB,CAAC;AAElC,cAAc,aAAa,CAAC;AAE5B,cAAc,gBAAgB,CAAC;AAE/B,OAAO,EAAE,MAAM,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC"}
package/dist/index.js CHANGED
@@ -9,6 +9,9 @@ export * from './types/index.js';
9
9
  export * from './resolve/secrets.js';
10
10
  export * from './resolve/connect.js';
11
11
  export * from './resolve/files.js';
12
+ export * from './resolve/deploy.js';
13
+ // Deploy module (blue-green orchestration foundation: types, state, runner, peer)
14
+ export * from './deploy/index.js';
12
15
  // Doctor
13
16
  export * from './doctor.js';
14
17
  // Lib
@@ -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,CA4DlF"}
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,CA4ElF"}
@@ -68,7 +68,21 @@ export function resolveConnectConfig(opts = {}) {
68
68
  });
69
69
  }
70
70
  const database_path = substitutePlaceholders(rawPath, extraVars);
71
- return { type: 'sqlite', sqlite: { database_path } };
71
+ // Optional `driver = better-sqlite3` in [db.<env>] — passed straight through to
72
+ // hazo_connect's sqlite config. Validated here (not left for hazo_connect to reject)
73
+ // so a typo in the ini fails at config-resolve time with a hazo_env error that names
74
+ // the bad value, instead of surfacing later as hazo_connect's generic "Unsupported
75
+ // connection type" from deep inside the adapter factory.
76
+ const rawDriver = section['driver'];
77
+ if (rawDriver !== undefined && rawDriver !== 'sql.js' && rawDriver !== 'better-sqlite3') {
78
+ throw new HazoConfigError({
79
+ code: 'HAZO_ENV_CONFIG_UNKNOWN_SQLITE_DRIVER',
80
+ pkg: 'hazo_env',
81
+ message: `[db.${targetEnv}] has unknown driver "${rawDriver}". Expected "sql.js" or "better-sqlite3".`,
82
+ });
83
+ }
84
+ const driver = rawDriver;
85
+ return { type: 'sqlite', sqlite: driver ? { database_path, driver } : { database_path } };
72
86
  }
73
87
  if (type === 'postgrest') {
74
88
  const rawUrl = section['base_url'] ?? '';
@@ -0,0 +1,8 @@
1
+ import type { DeployConfig } from '../deploy/types.js';
2
+ /**
3
+ * Resolve the `[deploy]` section of hazo_env_config.ini into a typed
4
+ * DeployConfig. `app_name` and `dir_suffix` are the only fields without a
5
+ * default — every other field falls back to a sane value when omitted.
6
+ */
7
+ export declare function resolveDeployConfig(): DeployConfig;
8
+ //# sourceMappingURL=deploy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deploy.d.ts","sourceRoot":"","sources":["../../src/resolve/deploy.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAgFvD;;;;GAIG;AACH,wBAAgB,mBAAmB,IAAI,YAAY,CAuDlD"}