@selvajs/cli 4.8.0-beta.9 → 4.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,28 +8,23 @@ CLI for white-label Selva deployments.
8
8
  npx @selvajs/cli my-deployment
9
9
  ```
10
10
 
11
- Interactive scaffolder. Prompts for provider, tenancy, flags, brand name, admin email. Generates `SELVA_HMAC_KEY` + `SELVA_AT_REST_KEY`. Writes `.env`, `ecosystem.config.cjs`, `package.json`. Runs `npm install`.
11
+ Prompts for provider, tenancy, flags, brand name, admin email; generates `SELVA_HMAC_KEY` and `SELVA_AT_REST_KEY`; writes `.env`, `ecosystem.config.cjs`, `package.json`; runs `npm install`. Refuses to overwrite a non-empty directory unless you pass `--force`.
12
12
 
13
13
  ## Operate an existing deployment
14
14
 
15
- After install, the package exposes a `selva` bin:
15
+ Installing adds a `selva` bin, scoped to the deployment directory (needs `.env` or `ecosystem.config.cjs` in the cwd):
16
16
 
17
17
  ```bash
18
- selva init # reconfigure prompts; preserves existing secrets
19
- selva doctor # validate env + providers + paths
18
+ selva init # reconfigure prompts; keeps existing secrets
19
+ selva doctor [--fix] # validate env, providers, Node engine, boot persistence
20
+ selva migrate # bring package.json onto the current layout
20
21
  selva start | stop | restart | logs
21
- selva update # npm update @selvajs/selva + pm2 restart
22
+ selva update # update @selvajs/cli + @selvajs/selva, then restart
22
23
  selva keys rotate hmac # rotate SELVA_HMAC_KEY (logs everyone out)
23
24
  selva keys rotate at-rest # rotate SELVA_AT_REST_KEY (compute API key needs re-entry)
24
25
  ```
25
26
 
26
- All operator commands run inside the deployment directory (the one that contains `.env` and `ecosystem.config.cjs`).
27
-
28
- ## Re-running a command is safe
29
-
30
- - `npx @selvajs/cli` refuses to overwrite a non-empty directory without `--force`.
31
- - `selva init` reads the current `.env`, lets the user edit, and **never** regenerates `SELVA_HMAC_KEY` / `SELVA_AT_REST_KEY` if they're already set.
32
- - A `.selva-version` marker is written so a future CLI version knows which config layout it is looking at and can upgrade it cleanly.
27
+ `selva init` never regenerates `SELVA_HMAC_KEY` or `SELVA_AT_REST_KEY` once they're set — rotating those is `keys rotate`'s job, since it invalidates sessions or encrypted data. A `.selva-version` marker records which CLI version scaffolded the directory, so a later `selva migrate` knows what layout it's upgrading from.
33
28
 
34
29
  ## Relationship to `@selvajs/selva`
35
30
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@selvajs/cli",
3
- "version": "4.8.0-beta.9",
3
+ "version": "4.8.1",
4
4
  "description": "Scaffold and operate a Selva white-label deployment. `npx @selvajs/cli <dir>` to bootstrap, `selva <cmd>` to manage.",
5
5
  "license": "MIT",
6
6
  "author": "VektorNode",
@@ -34,12 +34,15 @@
34
34
  "!**/*.spec.*"
35
35
  ],
36
36
  "engines": {
37
- "node": ">=22.0.0"
37
+ "node": ">=24.0.0"
38
38
  },
39
39
  "dependencies": {
40
40
  "@clack/prompts": "^1.7.0",
41
41
  "picocolors": "^1.1.1"
42
42
  },
43
+ "devDependencies": {
44
+ "pm2": "7.0.3"
45
+ },
43
46
  "scripts": {
44
47
  "start": "node ./bin/cli.js",
45
48
  "selva": "node ./bin/selva.js",
@@ -12,7 +12,10 @@
12
12
 
13
13
  import { existsSync, readFileSync, accessSync, constants } from 'node:fs';
14
14
  import { spawnSync } from 'node:child_process';
15
- import { join, resolve, dirname, delimiter } from 'node:path';
15
+ // These checks only ever run on a Linux host (see the platform gate below), so
16
+ // every path here is POSIX. Using the platform-default `node:path` would build
17
+ // backslash paths and split PATH on `;` when the tests run on Windows.
18
+ import { posix as path } from 'node:path';
16
19
  import { homedir } from 'node:os';
17
20
  import { green, red, yellow, fixable } from './result.js';
18
21
 
@@ -22,10 +25,10 @@ export const systemEnv = {
22
25
  env: () => process.env,
23
26
  homedir,
24
27
  exists: existsSync,
25
- readFile: (path) => readFileSync(path, 'utf8'),
26
- isWritable: (path) => {
28
+ readFile: (target) => readFileSync(target, 'utf8'),
29
+ isWritable: (target) => {
27
30
  try {
28
- accessSync(path, constants.W_OK);
31
+ accessSync(target, constants.W_OK);
29
32
  return true;
30
33
  } catch {
31
34
  return false;
@@ -50,15 +53,15 @@ export function checkBootPersistence(dir, env = systemEnv) {
50
53
  // dump.pm2 is what `pm2 resurrect` replays. Without it the unit starts pm2 and
51
54
  // pm2 starts nothing.
52
55
  function checkSavedProcessList(dir, env) {
53
- const pm2Home = env.env().PM2_HOME ?? join(env.homedir(), '.pm2');
54
- if (env.exists(join(pm2Home, 'dump.pm2'))) {
56
+ const pm2Home = env.env().PM2_HOME ?? path.join(env.homedir(), '.pm2');
57
+ if (env.exists(path.join(pm2Home, 'dump.pm2'))) {
55
58
  return green('pm2 process list saved (dump.pm2 present)');
56
59
  }
57
60
  return yellow(
58
61
  'pm2 process list not saved — run `npx pm2 save` so a reboot can ' +
59
62
  'resurrect the app (nothing to restore without it)',
60
63
  fixable('run `pm2 save` to persist the current process list', () => {
61
- const bin = join(dir, 'node_modules', '.bin', 'pm2');
64
+ const bin = path.join(dir, 'node_modules', '.bin', 'pm2');
62
65
  if (!env.exists(bin)) return red('pm2 not installed in this deployment');
63
66
  const r = env.run(bin, ['save'], { cwd: dir });
64
67
  return (r.status ?? 1) === 0
@@ -89,7 +92,7 @@ function checkSystemdUnit(dir, env) {
89
92
  return [yellow(`pm2 systemd unit present but unreadable (${unitPath})`)];
90
93
  }
91
94
 
92
- const localPm2 = join(dir, 'node_modules', 'pm2', 'bin', 'pm2');
95
+ const localPm2 = path.join(dir, 'node_modules', 'pm2', 'bin', 'pm2');
93
96
  const execStart = /^ExecStart=(.+)$/m.exec(unit)?.[1] ?? '';
94
97
  if (execStart.includes(localPm2)) {
95
98
  return [green('pm2 systemd boot unit installed (uses deployment-local pm2)')];
@@ -102,7 +105,7 @@ function checkSystemdUnit(dir, env) {
102
105
  `expected: ${localPm2} resurrect\n ` +
103
106
  `Reboots will resurrect via the wrong pm2 (version skew). Re-run startup ` +
104
107
  `with the local binary:\n ` +
105
- `sudo env PATH=$PATH:${join(dir, 'node_modules', '.bin')} ${localPm2} ` +
108
+ `sudo env PATH=$PATH:${path.join(dir, 'node_modules', '.bin')} ${localPm2} ` +
106
109
  `startup systemd -u $USER --hp $HOME`
107
110
  )
108
111
  ];
@@ -116,14 +119,14 @@ function checkStrayGlobalPm2(dir, env) {
116
119
  // Only offer the removal when we could actually perform it. A global
117
120
  // install under /usr is root-owned; attempting it would half-fail and
118
121
  // leave the operator worse informed than a printed instruction.
119
- const writable = env.isWritable(dirname(globalPm2));
122
+ const writable = env.isWritable(path.dirname(globalPm2));
120
123
 
121
124
  return [
122
125
  yellow(
123
126
  `a pm2 outside this deployment is on PATH (${globalPm2}) — it can fork a ` +
124
127
  `mismatched daemon and trigger skew. Prefer \`npm run\` wrappers / \`npx pm2\` ` +
125
128
  `from this directory; consider \`npm uninstall -g pm2\`.` +
126
- (writable ? '' : `\n (${dirname(globalPm2)} is not writable — needs sudo)`),
129
+ (writable ? '' : `\n (${path.dirname(globalPm2)} is not writable — needs sudo)`),
127
130
  writable
128
131
  ? fixable(`uninstall the global pm2 at ${globalPm2}`, () => {
129
132
  const r = env.run('npm', ['uninstall', '-g', 'pm2'], {});
@@ -136,13 +139,12 @@ function checkStrayGlobalPm2(dir, env) {
136
139
  ];
137
140
  }
138
141
 
139
- // Scan PATH for a stray pm2 binary (read-only).
140
142
  export function findGlobalPm2(dir, env = systemEnv) {
141
- const localBin = resolve(dir, 'node_modules', '.bin');
142
- const dirs = (env.env().PATH ?? '').split(delimiter).filter(Boolean);
143
+ const localBin = path.resolve(dir, 'node_modules', '.bin');
144
+ const dirs = (env.env().PATH ?? '').split(path.delimiter).filter(Boolean);
143
145
  for (const d of dirs) {
144
- if (resolve(d) === localBin) continue;
145
- const candidate = join(d, 'pm2');
146
+ if (path.resolve(d) === localBin) continue;
147
+ const candidate = path.join(d, 'pm2');
146
148
  if (env.exists(candidate)) return candidate;
147
149
  }
148
150
  return null;
@@ -24,11 +24,7 @@ export function checkSecret(value, label) {
24
24
  return green(label);
25
25
  }
26
26
 
27
- /**
28
- * The three provider slots, lowercased and defaulted the same way the runtime
29
- * defaults them. Returned alongside the checks because the caller decides which
30
- * provider-specific checks to run from it.
31
- */
27
+ // Lowercased and defaulted the same way create-selva-providers.ts defaults them.
32
28
  export function resolveProviders(env) {
33
29
  return {
34
30
  auth: (env.SELVA_AUTH_PROVIDER ?? 'local').toLowerCase(),
@@ -69,13 +65,109 @@ export function checkOrigin(env) {
69
65
  return green(`ORIGIN=${env.ORIGIN}`);
70
66
  }
71
67
 
68
+ // Duplicated from HeaderAuthProvider.DEFAULT_HEADERS to avoid loading the runtime here.
69
+ // A test in providers/header-auth pins both sides, so drift surfaces in CI.
70
+ export const DEFAULT_HEADER_NAMES = {
71
+ upn: 'SELVA-UserPrincipalName',
72
+ email: 'SELVA-Email',
73
+ displayName: 'SELVA-DisplayName'
74
+ };
75
+
76
+ // oauth2-proxy's `set_xauthrequest` names. Two proxy styles are documented and
77
+ // both are correct, but they need opposite env config:
78
+ //
79
+ // rewrite — Caddy maps X-Auth-Request-* onto SELVA-* before proxying.
80
+ // Selva sees SELVA-*, so the overrides must be UNSET.
81
+ // copy-through — Caddy forwards X-Auth-Request-* unchanged.
82
+ // Selva sees those names, so all three must be overridden.
83
+ //
84
+ // Mixing them is the failure this check exists to catch: a name Selva reads but
85
+ // the proxy never sends yields `null` from identifyFromHeaders (for the UPN, a
86
+ // total login failure) with nothing in the logs pointing at the env var.
87
+ const OAUTH2_PROXY_HEADERS = new Set([
88
+ 'x-auth-request-user',
89
+ 'x-auth-request-email',
90
+ 'x-auth-request-preferred-username'
91
+ ]);
92
+
72
93
  /**
73
- * Report env vars that were renamed or replaced.
94
+ * Reports the header names the provider will actually read, and flags the
95
+ * combinations that can't match any documented proxy config.
74
96
  *
75
- * A rename is auto-fixable (`selva migrate` rewrites the key). A replacement
76
- * encodes a value in the new name, so migrate leaves it alone rather than
77
- * guessing — it is reported here and nowhere else.
97
+ * Deliberately not a "did you override all three" count: with the rewrite
98
+ * style, zero overrides is the correct answer, so counting alone would push
99
+ * operators toward breaking a working deployment.
78
100
  */
101
+ export function checkHeaderNames(env) {
102
+ const resolved = {
103
+ upn: env.HEADER_AUTH_UPN_HEADER || DEFAULT_HEADER_NAMES.upn,
104
+ email: env.HEADER_AUTH_EMAIL_HEADER || DEFAULT_HEADER_NAMES.email,
105
+ displayName: env.HEADER_AUTH_DISPLAY_NAME_HEADER || DEFAULT_HEADER_NAMES.displayName
106
+ };
107
+ const list = `UPN=${resolved.upn}, Email=${resolved.email}, DisplayName=${resolved.displayName}`;
108
+
109
+ const oauth2 = Object.values(resolved).filter((h) =>
110
+ OAUTH2_PROXY_HEADERS.has(h.toLowerCase())
111
+ ).length;
112
+ const defaults = Object.entries(resolved).filter(
113
+ ([slot, name]) => name === DEFAULT_HEADER_NAMES[slot]
114
+ ).length;
115
+
116
+ if (oauth2 === 0) {
117
+ return defaults === 3
118
+ ? green(`header names (bundled defaults): ${list}`)
119
+ : green(`header names (custom): ${list}`);
120
+ }
121
+
122
+ // Some X-Auth-Request-*, some SELVA-* defaults — neither proxy style emits
123
+ // that mix, so whichever slots are still on a default are being read from a
124
+ // header nothing sets.
125
+ if (defaults > 0) {
126
+ const stale = Object.entries(resolved)
127
+ .filter(([slot, name]) => name === DEFAULT_HEADER_NAMES[slot])
128
+ .map(([slot, name]) => `${slot}=${name}`)
129
+ .join(', ');
130
+ return yellow(
131
+ `header names mix oauth2-proxy and bundled-default names: ${list} — ` +
132
+ `${stale} will never arrive if your proxy forwards X-Auth-Request-* unchanged. ` +
133
+ `Either override all three with the X-Auth-Request-* names, or map them to SELVA-* ` +
134
+ `in the proxy and unset all three overrides.`
135
+ );
136
+ }
137
+
138
+ return green(`header names (oauth2-proxy pass-through): ${list}`);
139
+ }
140
+
141
+ // Below this, an annotated .env is just a slightly chatty config file; above it
142
+ // the operator is scrolling past screens of prose that no command can correct.
143
+ const COMMENT_LINE_BUDGET = 40;
144
+
145
+ /**
146
+ * Flags a `.env` still carrying the shipped documentation block.
147
+ *
148
+ * The block is a snapshot of the release the deployment was installed at.
149
+ * `migrate` rewrites keys but never prose, so those comments keep describing
150
+ * vars the code has since renamed or retired — confidently wrong instructions
151
+ * sitting in the file an operator reaches for first. Nothing breaks, which is
152
+ * why this is yellow, and why it needs saying at all.
153
+ */
154
+ export function checkEnvDocumentation(commentLines, fix) {
155
+ if (commentLines <= COMMENT_LINE_BUDGET) {
156
+ return green('.env is values-only');
157
+ }
158
+ return yellow(
159
+ `.env carries ~${commentLines} lines of shipped documentation. Comments are ` +
160
+ `never updated by \`selva migrate\`, so they still describe the release this ` +
161
+ `deployment was installed at — including variables the code no longer reads. ` +
162
+ `Strip them (values and your own inline notes are kept, .env.bak written):\n ` +
163
+ `npx selva doctor --fix`,
164
+ fix
165
+ );
166
+ }
167
+
168
+ // A rename is auto-fixable (`selva migrate` rewrites the key). A replacement
169
+ // encodes a value in the new name, so migrate leaves it alone rather than
170
+ // guessing — it's reported here and nowhere else.
79
171
  export function checkDeprecatedEnv(env) {
80
172
  const checks = [];
81
173
 
@@ -0,0 +1,372 @@
1
+ // What the host provides versus what the deployment brings itself.
2
+ //
3
+ // The split trips operators up: Node and npm come from the host (distro
4
+ // packages, nvm, whatever), pm2 comes from the deployment. Installing pm2 from
5
+ // apt or `npm i -g` looks like the tidy thing to do and produces a daemon that
6
+ // silently fights the local one. These checks name which side of the line each
7
+ // tool is on, so the answer is on screen instead of in a support thread.
8
+ //
9
+ // checkNodeEngine (doctor.js) already validates the running Node against
10
+ // engines.node. Nothing here repeats that — this covers what it can't see: npm,
11
+ // the pm2 install itself, and whether the Node running doctor is the same one
12
+ // pm2 launched the app under.
13
+
14
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
15
+ import { spawnSync } from 'node:child_process';
16
+ import { join } from 'node:path';
17
+ import { homedir } from 'node:os';
18
+ import { fixable, green, red, yellow } from './result.js';
19
+ import { PM2_VERSION } from '../deployment-package.js';
20
+
21
+ /** The real OS. Tests pass a stand-in with the same shape. */
22
+ export const runtimeEnv = {
23
+ platform: () => process.platform,
24
+ env: () => process.env,
25
+ homedir,
26
+ exists: existsSync,
27
+ readFile: (path) => readFileSync(path, 'utf8'),
28
+ realpath: (path) => {
29
+ try {
30
+ return realpathSync(path);
31
+ } catch {
32
+ return path;
33
+ }
34
+ },
35
+ execPath: () => process.execPath,
36
+ // Signal 0 probes liveness without touching the process. EPERM means it
37
+ // exists but belongs to another user — alive for our purposes.
38
+ processAlive: (pid) => {
39
+ try {
40
+ process.kill(pid, 0);
41
+ return true;
42
+ } catch (err) {
43
+ return err?.code === 'EPERM';
44
+ }
45
+ },
46
+ run: (cmd, args, opts) =>
47
+ spawnSync(cmd, args, {
48
+ ...opts,
49
+ encoding: 'utf8',
50
+ shell: process.platform === 'win32'
51
+ })
52
+ };
53
+
54
+ export function checkRuntimeEnvironment(dir, env = runtimeEnv) {
55
+ return [
56
+ checkNpm(env),
57
+ checkNodeProvenance(env),
58
+ ...checkPm2Install(dir, env),
59
+ ...checkPm2Daemon(dir, env),
60
+ ...checkPm2LogRotation(dir, env)
61
+ ];
62
+ }
63
+
64
+ // ── npm ─────────────────────────────────────────────────────────────────
65
+
66
+ // Debian's `nodejs` package doesn't always pull in `npm`, and some distro
67
+ // splits ship an npm several majors behind the Node beside it. Both only
68
+ // surface at `selva update`, which is the worst moment to discover it.
69
+ const MIN_NPM_MAJOR = 10;
70
+
71
+ function checkNpm(env) {
72
+ const probe = env.run('npm', ['--version'], {});
73
+ const version = String(probe.stdout ?? '')
74
+ .trim()
75
+ .split('\n')
76
+ .pop();
77
+
78
+ if ((probe.status ?? 1) !== 0 || !/^\d+\.\d+\.\d+/.test(version ?? '')) {
79
+ return red(
80
+ 'npm not found on PATH — `selva update` and `npm install` cannot run.\n ' +
81
+ 'On Debian/Ubuntu the `nodejs` package does not always include it. Install\n ' +
82
+ 'Node 24 from NodeSource, which bundles a matching npm:\n ' +
83
+ 'curl -fsSL https://deb.nodesource.com/setup_24.x | sudo -E bash - && sudo apt-get install -y nodejs'
84
+ );
85
+ }
86
+
87
+ const major = Number(/^(\d+)\./.exec(version)[1]);
88
+ if (major < MIN_NPM_MAJOR) {
89
+ return yellow(
90
+ `npm ${version} is older than the Node beside it usually ships (expected >= ${MIN_NPM_MAJOR}).\n ` +
91
+ 'A distro-split npm can resolve dependencies the runtime does not expect.\n ' +
92
+ 'Install Node from NodeSource so npm and Node come from one source.'
93
+ );
94
+ }
95
+ return green(`npm ${version} on PATH`);
96
+ }
97
+
98
+ // ── Node provenance ─────────────────────────────────────────────────────
99
+
100
+ // Which Node runs the app is decided by pm2's environment, not by the shell
101
+ // running doctor. When those differ — a distro Node on PATH for the login
102
+ // shell, an nvm Node for the daemon, or the reverse — doctor validates a
103
+ // version the app never uses, and engines.node passes while production runs
104
+ // something else entirely.
105
+ function checkNodeProvenance(env) {
106
+ const running = env.realpath(env.execPath());
107
+ const source = describeNodeSource(running);
108
+
109
+ const which = env.run(env.platform() === 'win32' ? 'where' : 'which', ['node'], {});
110
+ const onPath = String(which.stdout ?? '')
111
+ .trim()
112
+ .split('\n')[0]
113
+ ?.trim();
114
+
115
+ if (!onPath) {
116
+ return yellow(
117
+ `Node v${process.versions.node} at ${running} (${source}) — not resolvable on PATH`
118
+ );
119
+ }
120
+
121
+ if (env.realpath(onPath) === running) {
122
+ return green(`Node v${process.versions.node} — ${source} (${running})`);
123
+ }
124
+
125
+ return yellow(
126
+ `Two Node installations are in play: this shell resolves \`node\` to ${env.realpath(onPath)},\n ` +
127
+ `but doctor is running under ${running} (${source}). pm2 launches the app with the\n ` +
128
+ `Node it inherited when the daemon started, which may be neither. Confirm with:\n ` +
129
+ `npx pm2 describe selva-compute | grep -i "node.js version"`
130
+ );
131
+ }
132
+
133
+ // nvm/fnm-managed Nodes disappear for a systemd unit that starts before the
134
+ // user's shell profile runs — worth naming the manager rather than the path.
135
+ function describeNodeSource(path) {
136
+ const p = path.replace(/\\/g, '/');
137
+ if (/\/\.nvm\//.test(p)) return 'nvm-managed';
138
+ if (/\/\.fnm\/|\/fnm_multishells\//.test(p)) return 'fnm-managed';
139
+ if (/\/\.volta\//.test(p)) return 'volta-managed';
140
+ if (/^\/usr\/bin\/|^\/bin\//.test(p)) return 'distro package';
141
+ if (/^\/usr\/local\//.test(p)) return 'manual /usr/local install';
142
+ if (/\/snap\//.test(p)) return 'snap package';
143
+ return 'unknown source';
144
+ }
145
+
146
+ // ── pm2 install ─────────────────────────────────────────────────────────
147
+
148
+ // The deployment pins pm2 exactly (see deployment-package.js). This verifies
149
+ // the pin actually landed — a hand-edited package.json, a partial install, or
150
+ // an operator who ran `npm i -g pm2` and deleted the local one all end here.
151
+ function checkPm2Install(dir, env) {
152
+ const out = [];
153
+ const pkgPath = join(dir, 'node_modules', 'pm2', 'package.json');
154
+
155
+ if (!env.exists(pkgPath)) {
156
+ out.push(
157
+ red(
158
+ `pm2 is not installed in this deployment (expected ${join(dir, 'node_modules', 'pm2')}).\n ` +
159
+ 'Selva ships its own pinned pm2 on purpose — the `selva` commands refuse to fall\n ' +
160
+ 'back to a global one, because two pm2 versions sharing a daemon hang restarts.\n ' +
161
+ 'Fix: npm install'
162
+ )
163
+ );
164
+ return out;
165
+ }
166
+
167
+ let installed = null;
168
+ try {
169
+ installed = JSON.parse(env.readFile(pkgPath)).version ?? null;
170
+ } catch {
171
+ // Unreadable package.json — reported below as an unverifiable version.
172
+ }
173
+
174
+ if (!installed) {
175
+ out.push(yellow('pm2 installed but its version is unreadable — cannot verify the pin'));
176
+ } else if (installed === PM2_VERSION) {
177
+ out.push(green(`pm2 ${installed} installed locally (matches the pinned version)`));
178
+ } else {
179
+ out.push(
180
+ yellow(
181
+ `pm2 ${installed} is installed but this scaffold pins ${PM2_VERSION}.\n ` +
182
+ 'The pin is exact because pm2 CLI and daemon must match. Realign it:\n ' +
183
+ `npm install pm2@${PM2_VERSION} && npx pm2 update`
184
+ )
185
+ );
186
+ }
187
+
188
+ // A pm2 listed in dependencies with a range instead of the exact pin means
189
+ // package.json was hand-edited; the next `npm install` silently drifts again.
190
+ const declared = readDeclaredPm2(dir, env);
191
+ if (declared && declared !== PM2_VERSION) {
192
+ out.push(
193
+ yellow(
194
+ `package.json declares pm2 "${declared}" rather than the exact pin ${PM2_VERSION}.\n ` +
195
+ 'A range lets a later `npm install` adopt a version the running daemon is not.\n ' +
196
+ 'Run `selva migrate` to restore the canonical package.json.'
197
+ )
198
+ );
199
+ }
200
+
201
+ return out;
202
+ }
203
+
204
+ function readDeclaredPm2(dir, env) {
205
+ try {
206
+ const pkg = JSON.parse(env.readFile(join(dir, 'package.json')));
207
+ return pkg.dependencies?.pm2 ?? null;
208
+ } catch {
209
+ return null;
210
+ }
211
+ }
212
+
213
+ // ── pm2 daemon ──────────────────────────────────────────────────────────
214
+
215
+ // Reports three distinct states rather than pass/fail: no daemon (fine,
216
+ // nothing started yet), a matching daemon, or a daemon a foreign pm2 owns.
217
+ //
218
+ // `pm2 ping` SPAWNS a daemon when none is running, and doctor must stay
219
+ // read-only — so liveness is checked via pm2.pid + signal 0 first, and pm2
220
+ // itself is only invoked once a live daemon is confirmed.
221
+ //
222
+ // The daemon-is-newer direction is red and deliberately offers no fix: `pm2
223
+ // update` would downgrade the daemon and drop its process table, leaving
224
+ // selva-compute unregistered. Same reasoning as ensurePm2InSync in commands/pm2.js.
225
+ function checkPm2Daemon(dir, env) {
226
+ const bin = join(dir, 'node_modules', '.bin', env.platform() === 'win32' ? 'pm2.cmd' : 'pm2');
227
+ if (!env.exists(bin)) return [];
228
+
229
+ const pm2Home = env.env().PM2_HOME ?? join(env.homedir(), '.pm2');
230
+ const pidPath = join(pm2Home, 'pm2.pid');
231
+ if (!env.exists(pidPath)) {
232
+ return [yellow('pm2 daemon is not running — it starts on `selva start`')];
233
+ }
234
+ let pid = NaN;
235
+ try {
236
+ pid = Number(String(env.readFile(pidPath)).trim());
237
+ } catch {
238
+ // Unreadable pid file — fall through to the stale case.
239
+ }
240
+ if (!Number.isInteger(pid) || pid <= 0 || !env.processAlive(pid)) {
241
+ return [yellow('pm2 daemon is not running (stale pm2.pid) — it starts on `selva start`')];
242
+ }
243
+
244
+ const probe = env.run(bin, ['ping'], { cwd: dir });
245
+ const output = String(probe.stdout ?? '') + String(probe.stderr ?? '');
246
+
247
+ if (!/out-of-date/i.test(output)) {
248
+ if (/pong/i.test(output)) return [green('pm2 daemon responds and matches the local pm2')];
249
+ return [yellow('pm2 daemon did not answer `pm2 ping` — check `npx pm2 ping` by hand')];
250
+ }
251
+
252
+ const { daemon, local } = parseSkew(output);
253
+ if (daemon && local && compareVersions(daemon, local) > 0) {
254
+ return [
255
+ red(
256
+ `The running pm2 daemon (v${daemon}) is NEWER than this deployment's pm2 (v${local}),\n ` +
257
+ 'so a pm2 from outside the deployment owns it. `pm2 update` would downgrade the\n ' +
258
+ 'daemon and drop its process table, so `selva start` refuses outright.\n ' +
259
+ 'Resolve it (the app goes down briefly):\n ' +
260
+ `npx pm2 kill && sudo npm uninstall -g pm2 && npm install && npm start\n ` +
261
+ 'Then re-run: npx pm2 save && npx pm2 startup systemd -u $USER --hp $HOME'
262
+ )
263
+ ];
264
+ }
265
+
266
+ return [
267
+ yellow(
268
+ `pm2 daemon (v${daemon ?? 'unknown'}) differs from the local pm2 (v${local ?? PM2_VERSION}).\n ` +
269
+ 'Resync it — this briefly restarts managed processes: npx pm2 update'
270
+ )
271
+ ];
272
+ }
273
+
274
+ // ── pm2 log rotation ────────────────────────────────────────────────────
275
+
276
+ // pm2 appends to `$PM2_HOME/logs/*.log` forever. Nothing in a default install
277
+ // truncates them, and the app writes a line per solve — so the only bound is
278
+ // the disk. It fails late and all at once: the partition fills, and pm2 and the
279
+ // app go down together on a box that looked healthy the day before.
280
+ //
281
+ // Detected from the filesystem, never by running `pm2 ls`: an invocation with
282
+ // no live daemon spawns one as a side effect, which doctor must not do (see
283
+ // checkPm2Daemon).
284
+ //
285
+ // `$PM2_HOME/modules/<name>`, NOT `node_modules/` — pm2 keeps installed modules
286
+ // in their own tree. Checking the wrong path made this report "not installed"
287
+ // straight after a successful install, so `--fix` offered the same repair every
288
+ // run.
289
+ function checkPm2LogRotation(dir, env) {
290
+ const bin = join(dir, 'node_modules', '.bin', env.platform() === 'win32' ? 'pm2.cmd' : 'pm2');
291
+ if (!env.exists(bin)) return [];
292
+
293
+ const pm2Home = env.env().PM2_HOME ?? join(env.homedir(), '.pm2');
294
+ if (env.exists(join(pm2Home, 'modules', 'pm2-logrotate'))) {
295
+ return [green('pm2-logrotate installed — pm2 logs are rotated')];
296
+ }
297
+
298
+ return [
299
+ yellow(
300
+ 'pm2-logrotate is not installed — pm2 logs grow without bound and are only\n ' +
301
+ 'capped by free disk. Install it (takes effect immediately, no restart):\n ' +
302
+ 'npx pm2 install pm2-logrotate\n ' +
303
+ `npx pm2 set pm2-logrotate:rotateInterval "${LOGROTATE_SETTINGS.rotateInterval}"\n ` +
304
+ `npx pm2 set pm2-logrotate:retain ${LOGROTATE_SETTINGS.retain}\n ` +
305
+ `npx pm2 set pm2-logrotate:compress ${LOGROTATE_SETTINGS.compress}`,
306
+ fixable('install pm2-logrotate (weekly rotation, 8 kept, compressed)', () =>
307
+ installLogRotate(bin, dir, env)
308
+ )
309
+ )
310
+ ];
311
+ }
312
+
313
+ /**
314
+ * Weekly on Sunday 00:00, keeping 8 — about two months of history, compressed.
315
+ *
316
+ * Weekly rather than pm2's daily default: a Selva deployment writes a line per
317
+ * solve, so daily files are mostly idle days, and two months of them is a lot
318
+ * of near-empty archives to page through when tracing an incident.
319
+ */
320
+ const LOGROTATE_SETTINGS = {
321
+ rotateInterval: '0 0 * * 0',
322
+ retain: 8,
323
+ compress: true
324
+ };
325
+
326
+ // `pm2 install` needs no root and doesn't restart managed processes, which is
327
+ // what makes it eligible as a doctor fixer at all. The settings are applied
328
+ // after: failing to set one leaves rotation on at pm2's defaults, which still
329
+ // beats unbounded growth, so a failed `set` is reported, not fatal.
330
+ function installLogRotate(bin, dir, env) {
331
+ const install = env.run(bin, ['install', 'pm2-logrotate'], { cwd: dir });
332
+ if ((install.status ?? 1) !== 0) {
333
+ const detail = String(install.stderr ?? install.stdout ?? '')
334
+ .trim()
335
+ .split('\n')
336
+ .pop();
337
+ return red(`\`pm2 install pm2-logrotate\` failed${detail ? `: ${detail}` : ''}`);
338
+ }
339
+
340
+ const failed = [];
341
+ for (const [key, value] of Object.entries(LOGROTATE_SETTINGS)) {
342
+ const set = env.run(bin, ['set', `pm2-logrotate:${key}`, String(value)], { cwd: dir });
343
+ if ((set.status ?? 1) !== 0) failed.push(key);
344
+ }
345
+ if (failed.length > 0) {
346
+ return yellow(
347
+ `pm2-logrotate installed, but could not set: ${failed.join(', ')}. ` +
348
+ `Rotation is active at pm2's defaults; set them by hand with \`npx pm2 set\`.`
349
+ );
350
+ }
351
+ return green('pm2-logrotate installed — weekly rotation, 8 kept, compressed');
352
+ }
353
+
354
+ function parseSkew(output) {
355
+ // eslint-disable-next-line no-control-regex -- pm2 colourises via chalk on a TTY
356
+ const clean = output.replace(/\[[0-9;]*m/g, '');
357
+ return {
358
+ daemon: /In memory PM2 version:\s*v?(\d+\.\d+\.\d+)/i.exec(clean)?.[1] ?? null,
359
+ local: /Local PM2 version:\s*v?(\d+\.\d+\.\d+)/i.exec(clean)?.[1] ?? null
360
+ };
361
+ }
362
+
363
+ function compareVersions(a, b) {
364
+ const [x, y] = [a.split('.').map(Number), b.split('.').map(Number)];
365
+ for (let i = 0; i < 3; i++) {
366
+ if (x[i] > y[i]) return 1;
367
+ if (x[i] < y[i]) return -1;
368
+ }
369
+ return 0;
370
+ }
371
+
372
+ export { describeNodeSource, compareVersions, MIN_NPM_MAJOR };