@camunda8/cli 4.1.1-alpha.1 → 4.2.0-alpha.2

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
@@ -67,6 +67,9 @@ npm install @camunda8/cli -g
67
67
  # Start a local Camunda 8 cluster (no Docker required)
68
68
  c8ctl cluster start
69
69
 
70
+ # Store a secret for local development (values are never shown or stored by c8ctl)
71
+ c8ctl cluster secrets set OPENAI_API_KEY
72
+
70
73
  # Deploy a process and start an instance
71
74
  c8ctl deploy ./my-process.bpmn
72
75
  c8ctl run my-process
@@ -67,13 +67,29 @@ patch releases.
67
67
  If the download server is unreachable, the aliases fall back to the values
68
68
  shipped in the plugin's `package.json`.
69
69
 
70
+ ### Resilient running-state tracking
71
+
72
+ A running cluster is tracked both by c8run's own `.process` pidfiles (which live
73
+ inside the version's install directory) **and** by a durable PID record kept at
74
+ the cache root (`cluster.pids`). Because that record survives the version's
75
+ install directory being replaced, upgraded, or removed while the cluster is
76
+ still running, `cluster status` and `cluster stop` continue to see the live
77
+ process — where they previously reported the cluster as *stopped* and left the
78
+ process orphaned on its ports. To prevent orphaning in the first place, `delete`
79
+ and a rolling `install` refuse to **remove the install directory** of a version
80
+ whose instance is still running, and `purge` refuses to **delete the runtime
81
+ data** of a running version — note that `purge` only clears runtime/history data
82
+ and always leaves the install directory itself in place. Stop the cluster first.
83
+ If a process does end up orphaned (e.g. the directory was removed outside
84
+ c8ctl), `cluster stop` terminates it directly using the recorded PID.
85
+
70
86
  ## How it works
71
87
 
72
88
  1. **Download**: Automatically downloads the correct c8run binary for your platform from the Camunda Download Center
73
89
  2. **Cache**: Stores downloaded binaries in a platform-specific cache directory
74
90
  3. **Start**: Launches c8run in the background and waits for the cluster to become healthy
75
91
  4. **Stop**: Gracefully shuts down the running cluster
76
- 5. **Status**: Reports whether a cluster is running by checking the active marker file and the live health endpoint
92
+ 5. **Status**: Reports whether a cluster is running by checking the active marker file, the durable PID record (`cluster.pids`), and the live health endpoint — so it still detects a cluster whose install directory was replaced or removed while running
77
93
  6. **Logs**: Streams log output (camunda.log, connectors.log) from the running cluster using `tail -f`
78
94
  7. **List**: Shows all locally cached versions and the current resolved values of available version aliases
79
95
  8. **List-remote**: Queries the Camunda Download Center and displays all available versions
@@ -8,19 +8,20 @@
8
8
  * c8ctl cluster stop [<version>]
9
9
  */
10
10
 
11
- import { spawn } from 'node:child_process';
11
+ import { spawn, execFileSync } from 'node:child_process';
12
12
  import {
13
13
  createWriteStream,
14
14
  existsSync,
15
15
  mkdirSync,
16
16
  writeFileSync,
17
+ renameSync,
17
18
  rmSync,
18
19
  readdirSync,
19
20
  readFileSync,
20
21
  } from 'node:fs';
21
22
  import { chmod } from 'node:fs/promises';
22
23
  import { homedir, platform as osPlatform, arch as osArch } from 'node:os';
23
- import { join, dirname } from 'node:path';
24
+ import { join, dirname, isAbsolute, resolve } from 'node:path';
24
25
  import { fileURLToPath } from 'node:url';
25
26
 
26
27
  // ---------------------------------------------------------------------------
@@ -299,6 +300,8 @@ function fireAndForget(promise) {
299
300
  return promise.catch(() => {});
300
301
  }
301
302
 
303
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
304
+
302
305
  // ---------------------------------------------------------------------------
303
306
  // Plugin metadata
304
307
  // ---------------------------------------------------------------------------
@@ -321,6 +324,7 @@ export const metadata = {
321
324
  { name: 'log', description: 'Stream cluster logs' },
322
325
  { name: 'logs', description: 'Stream cluster logs' },
323
326
  { name: 'purge', description: 'Delete runtime data (keeps binary) so the next start is fresh' },
327
+ { name: 'secrets', description: 'Manage local development secrets (passed through to c8run)' },
324
328
  ],
325
329
  examples: [
326
330
  { command: 'c8ctl cluster start', description: 'Start a local Camunda 8 cluster (latest stable)' },
@@ -335,6 +339,10 @@ export const metadata = {
335
339
  { command: 'c8ctl cluster delete 8.8', description: 'Remove a locally cached version' },
336
340
  { command: 'c8ctl cluster purge 8.8', description: 'Delete runtime data for a version (binary stays intact)' },
337
341
  { command: 'c8ctl cluster stop --purge', description: 'Stop the running cluster and delete its runtime data' },
342
+ { command: 'c8ctl cluster secrets set OPENAI_API_KEY', description: 'Store a secret (prompts, no-echo)' },
343
+ { command: 'c8ctl cluster secrets list', description: 'List secret names (values are never shown)' },
344
+ { command: 'c8ctl cluster secrets import .env.secrets', description: 'Import secrets from a dotenv file' },
345
+ { command: 'c8ctl cluster secrets delete OPENAI_API_KEY --yes', description: 'Delete a secret without prompting' },
338
346
  ],
339
347
  },
340
348
  },
@@ -363,6 +371,12 @@ function getLogger() {
363
371
 
364
372
  const ACTIVE_MARKER_FILE = 'cluster.active';
365
373
  const VERSION_MARKER_FILE = 'cluster.version';
374
+ // Durable running-cluster PID record, written at start time. Unlike c8run's
375
+ // own `.process` pidfiles — which live INSIDE a version's install dir and
376
+ // vanish when that dir is replaced or removed — this record lives at the
377
+ // cache root, so a running instance stays trackable (status/stop) even after
378
+ // its install directory is deleted or upgraded out from under it (#560).
379
+ const PID_RECORD_FILE = 'cluster.pids';
366
380
  const CLUSTER_STARTUP_TIMEOUT_MS = 120000;
367
381
  const HEALTH_CHECK_TIMEOUT_MS = 3_000;
368
382
  const ALIAS_COLUMN_WIDTH = 22;
@@ -658,6 +672,20 @@ export function getC8RunBinaryPath(config) {
658
672
 
659
673
  export function purgeInstalledVersion(config, { reason } = {}) {
660
674
  const logger = getLogger();
675
+
676
+ // Never remove a version's install dir while an instance started from it is
677
+ // still running — doing so orphans the process (it keeps holding its ports)
678
+ // and destroys the .process pidfiles c8ctl relied on to find it, so
679
+ // status/stop go blind (#560). This backstops every caller: the delete/purge
680
+ // subcommands guard earlier with a friendlier message, and the rolling-update
681
+ // path relies on this to refuse an in-place upgrade of a running version.
682
+ if (isVersionInstanceRunning(config.cacheDir, config.version)) {
683
+ throw new Error(
684
+ `Refusing to remove c8run ${config.version}: an instance started from this version is still running. ` +
685
+ 'Stop it first with "c8ctl cluster stop".',
686
+ );
687
+ }
688
+
661
689
  const installDir = join(config.cacheDir, `c8run-${config.version}`);
662
690
  const platformInfo = getPlatformIdentifier();
663
691
  const archiveFile = join(
@@ -747,6 +775,16 @@ export async function ensureC8RunInstalled(config) {
747
775
  logger.info(`c8run ${config.version} is already installed and up to date.`);
748
776
  return;
749
777
  }
778
+ // Refuse to replace a running version's install dir out from under it.
779
+ // purgeInstalledVersion throws if an instance is still running; surface
780
+ // an update-specific hint so the user knows to stop the cluster first.
781
+ if (isVersionInstanceRunning(config.cacheDir, config.version)) {
782
+ throw new Error(
783
+ `A newer c8run ${config.version} is available, but an instance started from the current ` +
784
+ 'install is still running. Updating now would orphan it and free none of its ports. ' +
785
+ 'Stop it first with "c8ctl cluster stop", then re-run the install.',
786
+ );
787
+ }
750
788
  purgeInstalledVersion(config);
751
789
  } else {
752
790
  // Use local installation as-is (start subcommand, or pinned version)
@@ -771,6 +809,22 @@ export async function ensureC8RunInstalled(config) {
771
809
  }
772
810
  }
773
811
 
812
+ // Reached the download/extract fallback. Either nothing is installed, or the
813
+ // install dir exists but its binary is missing/corrupt (isC8RunInstalled is
814
+ // false, so the guarded rolling-update branch above was skipped entirely).
815
+ // extractArchive writes into c8run-${version}; if an instance started from
816
+ // this version is still live — a partial/corrupt install whose processes are
817
+ // running — extracting would overwrite files under the live cluster and could
818
+ // corrupt it. Refuse here too, mirroring the rolling-update guard above, so a
819
+ // (re)install can never mutate a running install (#560).
820
+ if (isVersionInstanceRunning(config.cacheDir, config.version)) {
821
+ throw new Error(
822
+ `Refusing to (re)install c8run ${config.version}: an instance started from it is still running, ` +
823
+ 'and extracting now would overwrite files under the live cluster. ' +
824
+ 'Stop it first with "c8ctl cluster stop", then re-run the install.',
825
+ );
826
+ }
827
+
774
828
  logger.info('No local installation found. Setting up...');
775
829
 
776
830
  const { archivePath, etag } = await downloadC8Run(config);
@@ -891,6 +945,23 @@ async function startC8Run(config, debug = false) {
891
945
  logger.warn('Found stale cluster marker (no running processes detected). Cleaning up.');
892
946
  if (existsSync(markerFile)) rmSync(markerFile);
893
947
  if (existsSync(versionFile)) rmSync(versionFile);
948
+ } else if (hasRunningClusterPidfiles(config.cacheDir)) {
949
+ // No active marker, but a live process is still tracked — typically an
950
+ // orphan recorded only in the durable cache-root PID record after its
951
+ // install dir was replaced/removed (#560). Refuse rather than launch a
952
+ // second instance: a successful start would overwrite the record with a
953
+ // fresh snapshot (losing the orphan's PID), and on the default ports it
954
+ // would collide with the still-running process. Preserve the record so
955
+ // "c8ctl cluster stop" can still find and reap the orphan.
956
+ logger.warn(
957
+ 'A cluster process appears to be running already (no active marker, but a live tracked process was found).',
958
+ );
959
+ const record = readRunningClusterRecord(config.cacheDir);
960
+ if (record?.version) {
961
+ logger.info(`Detected running version from the durable PID record: ${record.version}`);
962
+ }
963
+ logger.info('Stop it first with "c8ctl cluster stop".');
964
+ return;
894
965
  }
895
966
 
896
967
  logger.info('Starting Camunda 8 local cluster...');
@@ -955,6 +1026,28 @@ async function startC8Run(config, debug = false) {
955
1026
  const isReady = await waitForClusterReady();
956
1027
 
957
1028
  if (isReady) {
1029
+ // Publish the durable PID record BEFORE the active marker. If c8ctl is
1030
+ // interrupted between these writes, a record-without-marker is recoverable
1031
+ // (status/stop still see the live process via the record), whereas a
1032
+ // marker-without-record would let the stale-marker cleanup path drop the
1033
+ // markers and leave the process orphaned with no handle to reap it (#560).
1034
+ //
1035
+ // The record write is nevertheless best-effort: if it throws (e.g. the
1036
+ // cache root is unwritable / disk full), we must NOT abort here and leave a
1037
+ // just-started, healthy cluster with NEITHER a record NOR markers — that
1038
+ // strands it for both `status` and `stop`. The install dir still exists at
1039
+ // this point, so the markers + c8run's own `.process` pidfiles keep the
1040
+ // cluster fully trackable and stoppable; only the extra orphan-recovery
1041
+ // handle (needed later, if the dir is removed) is missing, which we warn on.
1042
+ try {
1043
+ recordRunningClusterPids(config);
1044
+ } catch (error) {
1045
+ logger.warn(
1046
+ `Could not persist the durable cluster PID record (${
1047
+ error instanceof Error ? error.message : String(error)
1048
+ }); the cluster is still tracked via its markers and pidfiles.`,
1049
+ );
1050
+ }
958
1051
  writeFileSync(markerFile, 'running');
959
1052
  writeFileSync(versionFile, config.version);
960
1053
  printSummary(startupOutput, config.version);
@@ -968,21 +1061,161 @@ async function startC8Run(config, debug = false) {
968
1061
  }
969
1062
  }
970
1063
 
971
- export function hasRunningClusterPidfiles(cacheDir) {
972
- if (!existsSync(cacheDir)) {
1064
+ /** True when a PID refers to a live process. EPERM (owned by another user) counts as alive. */
1065
+ export function isPidAlive(pid) {
1066
+ if (!Number.isInteger(pid) || pid <= 0) {
973
1067
  return false;
974
1068
  }
1069
+ try {
1070
+ process.kill(pid, 0);
1071
+ return true;
1072
+ } catch (error) {
1073
+ return Boolean(error && error.code === 'EPERM');
1074
+ }
1075
+ }
975
1076
 
976
- const versionDirs = readdirSync(cacheDir, { withFileTypes: true })
977
- .filter(
978
- (entry) =>
979
- entry.isDirectory() && entry.name.startsWith('c8run-'),
980
- )
981
- .map((entry) => join(cacheDir, entry.name));
1077
+ /**
1078
+ * A best-effort, platform-native "start signature" for a PID — enough to tell
1079
+ * the ORIGINAL process apart from an unrelated one that reused the same numeric
1080
+ * PID after the original exited. Returns a stable string, or null when the
1081
+ * platform/environment gives us nothing to fingerprint with (in which case
1082
+ * callers fall back to a liveness-only check). Never throws.
1083
+ */
1084
+ /**
1085
+ * True on platforms where `processStartSignature()` can produce a real
1086
+ * fingerprint (Linux, macOS/BSD, Windows). On any other platform no PID can be
1087
+ * fingerprinted, so callers must degrade to a liveness-only reuse guard rather
1088
+ * than dropping otherwise-trackable PIDs (#560).
1089
+ */
1090
+ export function platformSupportsProcessSignature() {
1091
+ const platform = osPlatform();
1092
+ return (
1093
+ platform === 'linux' ||
1094
+ platform === 'darwin' ||
1095
+ platform.endsWith('bsd') ||
1096
+ platform === 'win32'
1097
+ );
1098
+ }
1099
+
1100
+ export function processStartSignature(pid) {
1101
+ if (!Number.isInteger(pid) || pid <= 0) {
1102
+ return null;
1103
+ }
1104
+ const platform = osPlatform();
1105
+ try {
1106
+ if (platform === 'linux') {
1107
+ // /proc/<pid>/stat field 22 is the process start time (clock ticks since
1108
+ // boot) — fixed for the life of the process and re-assigned with the PID,
1109
+ // so it distinguishes a reused PID. `comm` (field 2) can contain spaces
1110
+ // and parentheses, so parse the numeric fields from the LAST ')'.
1111
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf-8');
1112
+ const rparen = stat.lastIndexOf(')');
1113
+ if (rparen === -1) return null;
1114
+ const fields = stat.slice(rparen + 1).trim().split(/\s+/);
1115
+ // After ')' the fields are state(3), ppid(4), …; starttime is field 22,
1116
+ // i.e. index 19 of this remainder (22 - 3).
1117
+ const starttime = fields[19];
1118
+ return starttime ? `linux:${starttime}` : null;
1119
+ }
1120
+ if (platform === 'darwin' || platform.endsWith('bsd')) {
1121
+ // `ps -o lstart=` prints the process start timestamp, but only at
1122
+ // ONE-SECOND resolution — a PID reused within that same second would
1123
+ // reproduce it, and macOS `ps` exposes no higher-resolution creation
1124
+ // time. Pair it with the executable path (`comm=`), which is fixed for
1125
+ // the life of the process and an unrelated process that reused the PID
1126
+ // will not share. The combined fingerprint means `recordedPidIsLive()`
1127
+ // rejects such a replacement instead of signalling an unrelated process.
1128
+ const out = execFileSync('ps', ['-o', 'lstart=,comm=', '-p', String(pid)], {
1129
+ encoding: 'utf-8',
1130
+ timeout: 3000,
1131
+ // `lstart` is rendered in the process locale, so a start under one
1132
+ // LC_TIME and a stop under another would produce different strings for
1133
+ // the SAME live process — `recordedPidIsLive()` would then reject the
1134
+ // orphan as gone and never reap it. Pin a fixed C/POSIX locale so the
1135
+ // signature is locale-independent and stable across invocations (#560).
1136
+ env: { ...process.env, LC_ALL: 'C', LC_TIME: 'C', LANG: 'C' },
1137
+ }).trim();
1138
+ return out ? `ps:${out}` : null;
1139
+ }
1140
+ if (platform === 'win32') {
1141
+ // Windows is a supported platform (#560): fingerprint with the process
1142
+ // creation time from CIM/WMI. Paired with the PID it distinguishes the
1143
+ // original process from an unrelated one that reused the numeric PID.
1144
+ // Guard the null case so a missing PID yields empty output (→ null) rather
1145
+ // than a property access on $null throwing.
1146
+ const out = execFileSync(
1147
+ 'powershell',
1148
+ [
1149
+ '-NoProfile',
1150
+ '-NonInteractive',
1151
+ '-Command',
1152
+ `$p = Get-CimInstance Win32_Process -Filter "ProcessId=${pid}"; ` +
1153
+ `if ($p) { $p.CreationDate.ToString('o') }`,
1154
+ ],
1155
+ { encoding: 'utf-8', timeout: 5000 },
1156
+ ).trim();
1157
+ return out ? `win:${out}` : null;
1158
+ }
1159
+ } catch {
1160
+ // No signature available — the caller falls back to a liveness-only check.
1161
+ }
1162
+ return null;
1163
+ }
1164
+
1165
+ /**
1166
+ * True when `pid` is alive AND, where we captured a start signature for it, that
1167
+ * signature still matches — i.e. it is the ORIGINAL recorded process, not an
1168
+ * unrelated one that reused the PID after the original exited. A recorded entry
1169
+ * with NO signature is trusted (liveness only) ONLY on platforms that cannot
1170
+ * fingerprint at all; on a fingerprinting platform our writer never persists a
1171
+ * signature-less PID (#568), so a signature-less entry there can only be a
1172
+ * stale/legacy/hand-edited `cluster.pids` and is rejected rather than risk
1173
+ * signalling a reused, unrelated process. When a signature WAS recorded but the
1174
+ * platform cannot reproduce one now (transient `ps` failure), the guard still
1175
+ * degrades to liveness only, never inventing a false negative that would strand
1176
+ * a real orphan.
1177
+ */
1178
+ export function recordedPidIsLive(pid, signature) {
1179
+ if (!isPidAlive(pid)) {
1180
+ return false;
1181
+ }
1182
+ if (!signature) {
1183
+ // No signature recorded. On a fingerprinting platform this can only be a
1184
+ // stale/legacy/hand-edited record (our writer always signs live PIDs there
1185
+ // now), whose bare numeric liveness could match a reused unrelated process
1186
+ // — refuse it. Only non-fingerprinting platforms keep the liveness-only
1187
+ // degrade, since there no recorded PID can ever carry a signature and
1188
+ // rejecting would strand every real orphan (#560/#568).
1189
+ return !platformSupportsProcessSignature();
1190
+ }
1191
+ const current = processStartSignature(pid);
1192
+ return current === null || current === signature;
1193
+ }
1194
+
1195
+ /**
1196
+ * Collect the PIDs recorded in c8run `.process` pidfiles under `cacheDir`.
1197
+ * When `version` is given only that version's install dir is scanned;
1198
+ * otherwise every `c8run-*` install dir is scanned. Each install dir and its
1199
+ * immediate subdirectories are scanned (max depth 1) rather than a full
1200
+ * recursive DFS — c8run installs can contain large extracted trees, logs, and
1201
+ * data that would make a deep walk slow. Returns parsed positive integers
1202
+ * (alive or not); the caller decides liveness.
1203
+ */
1204
+ export function collectPidfilePids(cacheDir, { version } = {}) {
1205
+ const pids = [];
1206
+ if (!existsSync(cacheDir)) {
1207
+ return pids;
1208
+ }
1209
+
1210
+ let versionDirs;
1211
+ if (version) {
1212
+ versionDirs = [join(cacheDir, `c8run-${version}`)];
1213
+ } else {
1214
+ versionDirs = readdirSync(cacheDir, { withFileTypes: true })
1215
+ .filter((entry) => entry.isDirectory() && entry.name.startsWith('c8run-'))
1216
+ .map((entry) => join(cacheDir, entry.name));
1217
+ }
982
1218
 
983
- // Scan each version dir and its immediate subdirectories (max depth 1)
984
- // rather than a full recursive DFS — c8run installs can contain large
985
- // extracted trees, logs, and data that would make a deep walk slow.
986
1219
  for (const versionDir of versionDirs) {
987
1220
  let entries;
988
1221
  try {
@@ -1011,34 +1244,299 @@ export function hasRunningClusterPidfiles(cacheDir) {
1011
1244
  if (!entry.isFile() || !entry.name.endsWith('.process')) {
1012
1245
  continue;
1013
1246
  }
1014
-
1015
- const entryPath = join(dir, entry.name);
1016
-
1017
1247
  let pid;
1018
1248
  try {
1019
- pid = Number.parseInt(readFileSync(entryPath, 'utf-8').trim(), 10);
1249
+ pid = Number.parseInt(readFileSync(join(dir, entry.name), 'utf-8').trim(), 10);
1020
1250
  } catch {
1021
1251
  // Pidfile may have been removed between listing and reading.
1022
1252
  continue;
1023
1253
  }
1024
-
1025
- if (!Number.isInteger(pid) || pid <= 0) {
1026
- continue;
1254
+ if (Number.isInteger(pid) && pid > 0) {
1255
+ pids.push(pid);
1027
1256
  }
1257
+ }
1258
+ }
1259
+ }
1028
1260
 
1029
- try {
1030
- process.kill(pid, 0);
1031
- return true;
1032
- } catch (error) {
1033
- if (error && error.code === 'EPERM') {
1034
- return true;
1035
- }
1036
- }
1261
+ return pids;
1262
+ }
1263
+
1264
+ function getPidRecordPath(cacheDir) {
1265
+ return join(cacheDir, PID_RECORD_FILE);
1266
+ }
1267
+
1268
+ /**
1269
+ * Read the durable running-cluster PID record (see PID_RECORD_FILE). Returns
1270
+ * `{ version, pids }` or null when absent/unparseable. This record lives at
1271
+ * the cache root, so it survives a running version's install dir being
1272
+ * replaced or deleted — the case that otherwise orphans the process (#560).
1273
+ */
1274
+ export function readRunningClusterRecord(cacheDir) {
1275
+ const filePath = getPidRecordPath(cacheDir);
1276
+ if (!existsSync(filePath)) {
1277
+ return null;
1278
+ }
1279
+ let parsed;
1280
+ try {
1281
+ parsed = JSON.parse(readFileSync(filePath, 'utf-8'));
1282
+ } catch {
1283
+ return null;
1284
+ }
1285
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
1286
+ return null;
1287
+ }
1288
+ const version = typeof parsed.version === 'string' && parsed.version ? parsed.version : null;
1289
+ const pids = Array.isArray(parsed.pids)
1290
+ ? parsed.pids.filter((pid) => Number.isInteger(pid) && pid > 0)
1291
+ : [];
1292
+ const signatures =
1293
+ parsed.signatures && typeof parsed.signatures === 'object' && !Array.isArray(parsed.signatures)
1294
+ ? Object.fromEntries(
1295
+ Object.entries(parsed.signatures).filter(
1296
+ ([pid, sig]) => Number.isInteger(Number(pid)) && typeof sig === 'string' && sig,
1297
+ ),
1298
+ )
1299
+ : {};
1300
+ // Reject any record that lacks a non-empty version attribution. A record
1301
+ // with no version but stray PIDs (e.g. a malformed/hand-edited cluster.pids)
1302
+ // would otherwise let liveRecordedPids()/reapClusterProcesses() treat those
1303
+ // PIDs as cluster-owned and signal them with no version to attribute them to
1304
+ // — a path to killing an unrelated live process during `cluster stop` (#560).
1305
+ if (!version) {
1306
+ return null;
1307
+ }
1308
+ // Reject a record whose version fails the same path-traversal guard applied
1309
+ // to CLI-supplied versions. `version` is later interpolated into join() paths
1310
+ // by getC8RunBinaryPath during `cluster stop`, so a malformed record such as
1311
+ // `foo/../../tmp` could otherwise bypass validateVersionSpec and make stop
1312
+ // inspect/execute a binary outside the cache root (#560). Treat an invalid
1313
+ // record as unusable rather than trusting on-disk state.
1314
+ try {
1315
+ validateVersionSpec(version);
1316
+ } catch {
1317
+ return null;
1318
+ }
1319
+ return { version, pids, signatures };
1320
+ }
1321
+
1322
+ /** Persist the durable running-cluster PID record. */
1323
+ export function writeRunningClusterRecord(cacheDir, { version, pids, signatures }) {
1324
+ mkdirSync(cacheDir, { recursive: true });
1325
+ const cleanPids = Array.isArray(pids)
1326
+ ? [...new Set(pids.filter((pid) => Number.isInteger(pid) && pid > 0))]
1327
+ : [];
1328
+ const cleanSignatures = {};
1329
+ if (signatures && typeof signatures === 'object' && !Array.isArray(signatures)) {
1330
+ for (const pid of cleanPids) {
1331
+ const sig = signatures[pid];
1332
+ if (typeof sig === 'string' && sig) {
1333
+ cleanSignatures[pid] = sig;
1037
1334
  }
1038
1335
  }
1039
1336
  }
1337
+ // `cluster.pids` is the ONLY recovery handle once an install dir disappears,
1338
+ // so the write must be crash-safe: serialise to a sibling temp file and
1339
+ // atomically rename it into place. An interruption then leaves either the
1340
+ // previous valid record or the new one — never a truncated/unparseable file
1341
+ // that would make status/stop lose the orphan PID (#560).
1342
+ const finalPath = getPidRecordPath(cacheDir);
1343
+ const tmpPath = `${finalPath}.${process.pid}.${Date.now()}.tmp`;
1344
+ const payload = JSON.stringify({
1345
+ version: version ?? null,
1346
+ pids: cleanPids,
1347
+ signatures: cleanSignatures,
1348
+ });
1349
+ try {
1350
+ writeFileSync(tmpPath, payload);
1351
+ renameSync(tmpPath, finalPath);
1352
+ } catch (error) {
1353
+ try {
1354
+ if (existsSync(tmpPath)) rmSync(tmpPath);
1355
+ } catch {
1356
+ // best effort — nothing more we can do about a leftover temp file
1357
+ }
1358
+ throw error;
1359
+ }
1360
+ }
1040
1361
 
1041
- return false;
1362
+ /** Remove the durable running-cluster PID record if present. */
1363
+ export function clearRunningClusterRecord(cacheDir) {
1364
+ const filePath = getPidRecordPath(cacheDir);
1365
+ if (existsSync(filePath)) {
1366
+ rmSync(filePath);
1367
+ }
1368
+ }
1369
+
1370
+ /**
1371
+ * Retire the durable record when it no longer tracks any LIVE process. A stale
1372
+ * record left by a crash, a forced kill, or an already-stopped cluster keeps
1373
+ * dead PIDs in `cluster.pids`; on a platform where signature capture is
1374
+ * unavailable the liveness-only fallback would later mistake a reused PID for
1375
+ * this cluster — blocking a start and risking an unrelated process during stop
1376
+ * (#560). Safe to call from any cleanup / no-running path: a no-op when the
1377
+ * record is absent or still has at least one live recorded PID.
1378
+ */
1379
+ export function clearStaleRunningClusterRecord(cacheDir) {
1380
+ if (readRunningClusterRecord(cacheDir) && liveRecordedPids(cacheDir).length === 0) {
1381
+ clearRunningClusterRecord(cacheDir);
1382
+ }
1383
+ }
1384
+
1385
+ /** The still-live PIDs from the durable running-cluster record. */
1386
+ export function liveRecordedPids(cacheDir) {
1387
+ const record = readRunningClusterRecord(cacheDir);
1388
+ if (!record) {
1389
+ return [];
1390
+ }
1391
+ return record.pids.filter((pid) => recordedPidIsLive(pid, record.signatures?.[pid]));
1392
+ }
1393
+
1394
+ /**
1395
+ * Snapshot the live c8run PIDs for the just-started version into the durable
1396
+ * cache-root record, so the cluster stays trackable (status/stop) even if its
1397
+ * install dir is later replaced or removed (#560). Each PID is fingerprinted
1398
+ * with a start signature so a later stop/status can tell the recorded process
1399
+ * apart from an unrelated one that reused its PID.
1400
+ */
1401
+ export function recordRunningClusterPids(config, { signatureOf = processStartSignature } = {}) {
1402
+ const canFingerprint = platformSupportsProcessSignature();
1403
+ const pids = [];
1404
+ const signatures = {};
1405
+ for (const pid of collectPidfilePids(config.cacheDir, { version: config.version })) {
1406
+ if (canFingerprint) {
1407
+ // Capture identity with a SINGLE combined liveness+fingerprint operation.
1408
+ // processStartSignature runs one `ps`/PowerShell query that already
1409
+ // returns null for a dead PID, so — unlike a separate isPidAlive()
1410
+ // pre-check followed by a later signature capture — there is no window in
1411
+ // which the liveness probe and the fingerprint could observe two
1412
+ // different processes and record a reused PID's identity as c8run's
1413
+ // (#560). A null result means the PID is not a live, fingerprintable
1414
+ // process, so it is omitted: persisting it without a signature would let
1415
+ // a later reuse of the number fall back to numeric liveness and let the
1416
+ // reap path signal an unrelated process.
1417
+ const sig = signatureOf(pid);
1418
+ if (sig) {
1419
+ signatures[pid] = sig;
1420
+ pids.push(pid);
1421
+ }
1422
+ } else if (isPidAlive(pid)) {
1423
+ // This platform can't fingerprint any process, so no recorded PID can
1424
+ // carry a signature; keep the live PID so the cluster stays trackable
1425
+ // (the reuse guard degrades to a liveness-only check everywhere).
1426
+ pids.push(pid);
1427
+ }
1428
+ }
1429
+ writeRunningClusterRecord(config.cacheDir, { version: config.version, pids, signatures });
1430
+ }
1431
+
1432
+ /**
1433
+ * True when an instance started from the given version is still running,
1434
+ * either via a live `.process` pidfile in its install dir or via the durable
1435
+ * PID record attributing a live process to that version.
1436
+ */
1437
+ export function isVersionInstanceRunning(cacheDir, version) {
1438
+ if (collectPidfilePids(cacheDir, { version }).some((pid) => isPidAlive(pid))) {
1439
+ return true;
1440
+ }
1441
+ const record = readRunningClusterRecord(cacheDir);
1442
+ return Boolean(
1443
+ record &&
1444
+ record.version === version &&
1445
+ record.pids.some((pid) => recordedPidIsLive(pid, record.signatures?.[pid])),
1446
+ );
1447
+ }
1448
+
1449
+ /**
1450
+ * Send SIGTERM to a PID, wait up to `graceMs` for it to exit, then SIGKILL.
1451
+ * Returns true once the process is confirmed gone.
1452
+ */
1453
+ async function terminatePid(pid, { signature, graceMs = 5000, pollMs = 200 } = {}) {
1454
+ // Revalidate the recorded identity before EVERY signal, not just numeric
1455
+ // liveness. If the original process exits and its PID is reused (e.g. during
1456
+ // the SIGTERM grace window), the captured start signature no longer matches
1457
+ // and we must NOT escalate to an unrelated process (#560). recordedPidIsLive
1458
+ // degrades to a liveness-only check when no signature was captured.
1459
+ if (!recordedPidIsLive(pid, signature)) {
1460
+ return false;
1461
+ }
1462
+ try {
1463
+ process.kill(pid, 'SIGTERM');
1464
+ } catch {
1465
+ // Already exited or not permitted — fall through to the liveness check.
1466
+ }
1467
+ const deadline = Date.now() + graceMs;
1468
+ // Poll for exit with a CHEAP liveness probe (signal 0 — no subprocess). A
1469
+ // process' start signature is immutable while it lives, so re-running the
1470
+ // external `ps`/PowerShell signature query on every 200 ms poll would spawn
1471
+ // dozens of subprocesses (each with a multi-second timeout) and make stop
1472
+ // block far beyond graceMs on a slow host. We still revalidate the recorded
1473
+ // IDENTITY (signature) immediately before the SIGKILL escalation below, so a
1474
+ // PID reused during the grace window can never be signalled as if it were the
1475
+ // tracked process (#560).
1476
+ while (isPidAlive(pid) && Date.now() < deadline) {
1477
+ await sleep(pollMs);
1478
+ }
1479
+ if (recordedPidIsLive(pid, signature)) {
1480
+ try {
1481
+ process.kill(pid, 'SIGKILL');
1482
+ } catch {
1483
+ // Best effort — nothing more we can do.
1484
+ }
1485
+ await sleep(pollMs);
1486
+ }
1487
+ // Confirmed gone once the ORIGINAL recorded process is no longer live — a
1488
+ // signature mismatch (PID reuse) counts as gone: the process we tracked ended.
1489
+ return !recordedPidIsLive(pid, signature);
1490
+ }
1491
+
1492
+ /**
1493
+ * Terminate any cluster processes still alive under `cacheDir` — those named
1494
+ * by the durable PID record, each of which is validated against its recorded
1495
+ * start signature before we signal it. This is the stop backstop for the
1496
+ * orphan case (#560), where `c8run stop` cannot reach a process whose install
1497
+ * dir / pidfiles were removed. We deliberately do NOT scan raw `.process`
1498
+ * pidfiles here: they carry no start-signature, span every cached version, and
1499
+ * a stale pidfile whose numeric PID was reused would make us SIGTERM/SIGKILL an
1500
+ * unrelated process. Raw pidfiles remain c8run's own responsibility. Never
1501
+ * targets this process (or its parent). Returns the count actually terminated.
1502
+ */
1503
+ export async function reapClusterProcesses(cacheDir) {
1504
+ const record = readRunningClusterRecord(cacheDir);
1505
+ const signatures = record?.signatures ?? {};
1506
+ const targets = new Set(liveRecordedPids(cacheDir));
1507
+ // Guard against ever signalling the c8ctl process itself (or its parent) —
1508
+ // a cluster's Java process is never c8ctl, and tests stand in with own PIDs.
1509
+ targets.delete(process.pid);
1510
+ if (typeof process.ppid === 'number') {
1511
+ targets.delete(process.ppid);
1512
+ }
1513
+
1514
+ let reaped = 0;
1515
+ for (const pid of targets) {
1516
+ // Carry the recorded start signature into termination so each signal is
1517
+ // gated on the ORIGINAL identity, not bare numeric liveness (#560).
1518
+ if (await terminatePid(pid, { signature: signatures[pid] })) {
1519
+ reaped += 1;
1520
+ }
1521
+ }
1522
+ return reaped;
1523
+ }
1524
+
1525
+ export function hasRunningClusterPidfiles(cacheDir) {
1526
+ if (!existsSync(cacheDir)) {
1527
+ return false;
1528
+ }
1529
+
1530
+ // Primary signal: c8run's own .process pidfiles inside the install dirs.
1531
+ if (collectPidfilePids(cacheDir).some((pid) => isPidAlive(pid))) {
1532
+ return true;
1533
+ }
1534
+
1535
+ // Fallback: the durable cache-root PID record. This still resolves after a
1536
+ // running version's install dir (and with it the .process pidfiles) has been
1537
+ // replaced or deleted, which would otherwise make c8ctl report the live
1538
+ // cluster as stopped and leave its process orphaned (#560).
1539
+ return liveRecordedPids(cacheDir).length > 0;
1042
1540
  }
1043
1541
 
1044
1542
  export async function stopC8Run(config, debug = false) {
@@ -1050,6 +1548,9 @@ export async function stopC8Run(config, debug = false) {
1050
1548
  const clusterAppearsRunning = hasRunningClusterPidfiles(config.cacheDir);
1051
1549
 
1052
1550
  if (!markerExists && !clusterAppearsRunning) {
1551
+ // Nothing live to stop. Retire any stale record left by a crash/kill so its
1552
+ // dead PIDs cannot later be mistaken for this cluster (#560).
1553
+ clearStaleRunningClusterRecord(config.cacheDir);
1053
1554
  logger.warn(
1054
1555
  'No cluster is currently running.',
1055
1556
  );
@@ -1071,6 +1572,7 @@ export async function stopC8Run(config, debug = false) {
1071
1572
  if (existsSync(markerFile)) {
1072
1573
  rmSync(markerFile);
1073
1574
  }
1575
+ clearRunningClusterRecord(config.cacheDir);
1074
1576
  return staleVersion;
1075
1577
  }
1076
1578
 
@@ -1101,6 +1603,16 @@ export async function stopC8Run(config, debug = false) {
1101
1603
  }
1102
1604
  }
1103
1605
 
1606
+ // Fall back to the durable PID record's version when the marker is gone —
1607
+ // this is the version whose install dir may have been removed (#560).
1608
+ if (versionsToTry.length === 0) {
1609
+ const record = readRunningClusterRecord(config.cacheDir);
1610
+ if (record?.version) {
1611
+ stoppedVersion = record.version;
1612
+ versionsToTry.push(record.version);
1613
+ }
1614
+ }
1615
+
1104
1616
  if (versionsToTry.length === 0) {
1105
1617
  if (installedVersions.length === 0) {
1106
1618
  versionsToTry.push(config.version);
@@ -1190,29 +1702,366 @@ export async function stopC8Run(config, debug = false) {
1190
1702
  }
1191
1703
  }
1192
1704
 
1193
- // Always clean up markers, even if stop failed — a stale marker
1194
- // would permanently block future starts.
1705
+ // Reap any cluster processes still alive after the c8run stop attempt(s).
1706
+ // In the orphan case (#560) the version's install dir — and with it the
1707
+ // .process pidfiles c8run's own stop relies on — was replaced or removed
1708
+ // while the process kept running, so `c8run stop` cannot see it. The durable
1709
+ // cache-root PID record lets us find and terminate the process directly.
1710
+ const reaped = await reapClusterProcesses(config.cacheDir);
1711
+ if (reaped > 0) {
1712
+ hadSuccessfulStop = true;
1713
+ logger.warn(
1714
+ `Terminated ${reaped} orphaned cluster process${reaped === 1 ? '' : 'es'} that c8run no longer tracked.`,
1715
+ );
1716
+ }
1717
+
1718
+ // Markers are always cleared (a stale marker or version file would block
1719
+ // future starts), but the durable PID record is the ONLY handle to an orphan.
1720
+ // If reaping could not confirm every recorded process dead — e.g. signalling
1721
+ // returned EPERM, or the kill did not land — keep the record so a later
1722
+ // "c8ctl cluster stop" can retry. Only clear it once every recorded PID is
1723
+ // confirmed gone (#560).
1195
1724
  if (existsSync(markerFile)) {
1196
1725
  rmSync(markerFile);
1197
1726
  }
1198
1727
  if (existsSync(versionFile)) {
1199
1728
  rmSync(versionFile);
1200
1729
  }
1201
-
1202
- if (attempted === 0) {
1203
- throw new Error(
1204
- 'Could not find an installed c8run binary to execute stop.',
1730
+ const remainingPids = liveRecordedPids(config.cacheDir);
1731
+ if (remainingPids.length === 0) {
1732
+ clearRunningClusterRecord(config.cacheDir);
1733
+ } else {
1734
+ logger.warn(
1735
+ 'Some recorded cluster processes could not be confirmed stopped; keeping the durable ' +
1736
+ 'PID record so "c8ctl cluster stop" can retry.',
1205
1737
  );
1206
1738
  }
1207
1739
 
1208
- if (!hadSuccessfulStop && lastError) {
1740
+ if (attempted === 0 && !hadSuccessfulStop) {
1741
+ // ...but only when there is nothing left to reap. If a recorded process is
1742
+ // still alive (e.g. reaping hit EPERM), the incomplete-stop diagnostic
1743
+ // below carries the actionable PID/retry guidance and must win over this
1744
+ // generic "no binary" message even though the install dir is gone (#560).
1745
+ if (remainingPids.length === 0) {
1746
+ throw new Error(
1747
+ 'Could not find an installed c8run binary to execute stop.',
1748
+ );
1749
+ }
1750
+ } else if (!hadSuccessfulStop && lastError && remainingPids.length === 0) {
1209
1751
  throw lastError;
1210
1752
  }
1211
1753
 
1754
+ // A partial stop is still a FAILED stop: if any recorded PID is confirmed
1755
+ // alive after reaping, the cluster may still hold its ports, so a fresh start
1756
+ // would collide. Surface it as an error (the record was retained above) so
1757
+ // the CLI exits non-zero and the user retries, rather than reporting success
1758
+ // while an orphan lingers (#560).
1759
+ if (remainingPids.length > 0) {
1760
+ throw new Error(
1761
+ `Stop incomplete: ${remainingPids.length} recorded cluster process${
1762
+ remainingPids.length === 1 ? '' : 'es'
1763
+ } could not be confirmed stopped (PID${remainingPids.length === 1 ? '' : 's'}: ${remainingPids.join(', ')}). ` +
1764
+ 'The durable PID record was kept — retry with "c8ctl cluster stop".',
1765
+ );
1766
+ }
1767
+
1212
1768
  logger.info('Cluster stopped.');
1213
1769
  return stoppedVersion;
1214
1770
  }
1215
1771
 
1772
+ // ---------------------------------------------------------------------------
1773
+ // Secrets passthrough (#314)
1774
+ //
1775
+ // c8run itself owns secret storage, validation, and locking (`c8run secrets
1776
+ // set|list|path|delete|import`). c8ctl adds no store and sees no values —
1777
+ // it only locates the right c8run binary and forwards the call to it.
1778
+ // ---------------------------------------------------------------------------
1779
+
1780
+ // Global c8ctl flags, mirrored from src/framework/command-registry.ts's
1781
+ // GLOBAL_FLAGS (a plugin cannot import src/ — see the layering rules in
1782
+ // AGENTS.md). Needed to correctly identify the "cluster secrets" token pair
1783
+ // in raw argv: c8ctl accepts these flags anywhere on the command line, not
1784
+ // just before the verb, so one can legitimately sit between "cluster" and
1785
+ // "secrets" (e.g. `c8ctl cluster --profile prod secrets set KEY --stdin`).
1786
+ const GLOBAL_BOOLEAN_FLAGS = new Set(['--help', '-h', '--dry-run', '--verbose', '--json', '--yes', '-y']);
1787
+ const GLOBAL_STRING_FLAGS = new Set(['--profile', '--fields', '--version', '-v']);
1788
+
1789
+ /** True for a recognized global boolean flag token (never consumes a following token). */
1790
+ function isGlobalBooleanFlagToken(token) {
1791
+ return GLOBAL_BOOLEAN_FLAGS.has(token);
1792
+ }
1793
+
1794
+ /**
1795
+ * True for a recognized global string flag token, in either "--flag value"
1796
+ * or "--flag=value" form. The caller still needs to know which form it was
1797
+ * to decide whether to also skip the next token — see `stringFlagTokenWidth`.
1798
+ */
1799
+ function isGlobalStringFlagToken(token) {
1800
+ const name = token.includes('=') ? token.slice(0, token.indexOf('=')) : token;
1801
+ return GLOBAL_STRING_FLAGS.has(name);
1802
+ }
1803
+
1804
+ /** How many argv slots a global string flag token occupies: 1 for "--flag=value", 2 for "--flag value". */
1805
+ function stringFlagTokenWidth(token) {
1806
+ return token.includes('=') ? 1 : 2;
1807
+ }
1808
+
1809
+ /**
1810
+ * Recover the raw argv tail that follows "cluster secrets", reading
1811
+ * `argv` (normally `process.argv.slice(2)`) directly instead of the array
1812
+ * the c8ctl host passes to a plugin command. The host's top-level parser
1813
+ * treats an unrecognized flag as a boolean and strips it from the
1814
+ * positionals a plugin receives (see #364 in src/index.ts), which would
1815
+ * silently drop flags like --stdin, --all, and --yes before they ever
1816
+ * reached this plugin.
1817
+ *
1818
+ * Walks argv from the start, skipping recognized global flags (in both
1819
+ * "--flag value" and "--flag=value" form) wherever they appear — including
1820
+ * between "cluster" and "secrets" — until it finds that pair, then returns
1821
+ * everything after it. Falls back to `hostArgs.slice(1)` — the args array a
1822
+ * plugin host actually delivers — only when no such pair is found at all,
1823
+ * e.g. a direct/programmatic call, or "cluster" is followed by some other
1824
+ * verb.
1825
+ */
1826
+ export function sliceSecretsArgv(argv, hostArgs) {
1827
+ let i = 0;
1828
+ let foundCluster = false;
1829
+
1830
+ while (i < argv.length) {
1831
+ const token = argv[i];
1832
+
1833
+ if (!foundCluster && token === 'cluster') {
1834
+ foundCluster = true;
1835
+ i += 1;
1836
+ continue;
1837
+ }
1838
+
1839
+ if (foundCluster && token === 'secrets') {
1840
+ return argv.slice(i + 1);
1841
+ }
1842
+
1843
+ if (isGlobalBooleanFlagToken(token)) {
1844
+ i += 1;
1845
+ continue;
1846
+ }
1847
+ if (isGlobalStringFlagToken(token)) {
1848
+ i += stringFlagTokenWidth(token);
1849
+ continue;
1850
+ }
1851
+
1852
+ // After "cluster", anything that isn't a recognized global flag and
1853
+ // isn't "secrets" means this isn't the invocation we're looking for
1854
+ // (e.g. "cluster start") — give up and fall back.
1855
+ if (foundCluster) break;
1856
+
1857
+ i += 1;
1858
+ }
1859
+
1860
+ return hostArgs.slice(1);
1861
+ }
1862
+
1863
+ /**
1864
+ * Split a `cluster secrets` argv tail into an optional pinned c8run version
1865
+ * and the passthrough arguments that go to `c8run secrets` unchanged.
1866
+ *
1867
+ * Only strips --c8-version (in either "--c8-version value" or
1868
+ * "--c8-version=value" form, matching how the rest of c8ctl accepts string
1869
+ * flags) when it is the very first token, so any later occurrence reaches
1870
+ * c8run untouched. There is deliberately no verb allowlist here — c8ctl
1871
+ * does not validate or enumerate c8run's own verbs, so an older, newer, or
1872
+ * unreleased c8run's verb set (including one c8ctl has never heard of) is
1873
+ * still forwarded and its own error surfaces as-is.
1874
+ */
1875
+ export function parseSecretsArgs(tail) {
1876
+ let version = null;
1877
+ let passthrough = tail;
1878
+
1879
+ const first = passthrough[0];
1880
+ const isC8VersionFlag = first === '--c8-version' || (typeof first === 'string' && first.startsWith('--c8-version='));
1881
+ if (isC8VersionFlag) {
1882
+ if (first.startsWith('--c8-version=')) {
1883
+ version = first.slice('--c8-version='.length);
1884
+ passthrough = passthrough.slice(1);
1885
+ } else {
1886
+ version = passthrough[1];
1887
+ passthrough = passthrough.slice(2);
1888
+ }
1889
+ if (!version || version.startsWith('-')) {
1890
+ throw new Error(
1891
+ 'Missing value for --c8-version. Example: c8ctl cluster secrets --c8-version 8.10 list',
1892
+ );
1893
+ }
1894
+ }
1895
+
1896
+ if (passthrough.length === 0) {
1897
+ throw new Error(
1898
+ 'usage: c8ctl cluster secrets [--c8-version <version>] <set|list|path|delete|import|...>',
1899
+ );
1900
+ }
1901
+
1902
+ return { version, passthrough };
1903
+ }
1904
+
1905
+ /**
1906
+ * Resolve paths in a secrets passthrough call against the caller's cwd, not
1907
+ * c8run's. c8run always runs with its cwd set to its own binary directory
1908
+ * (see startC8Run below), so a relative `import <file>` or
1909
+ * C8RUN_SECRETS_DIR would otherwise resolve against the wrong directory and
1910
+ * silently miss the file the user meant.
1911
+ *
1912
+ * Only touches an `import` positional and C8RUN_SECRETS_DIR; every other
1913
+ * verb and flag passes through untouched. "-" (stdin) and already-absolute
1914
+ * paths are left alone. Never mutates the passthrough array or env object
1915
+ * it receives.
1916
+ */
1917
+ export function resolveSecretsPaths(passthrough, { cwd = process.cwd(), env = process.env } = {}) {
1918
+ let resolvedPassthrough = passthrough;
1919
+ if (
1920
+ passthrough[0] === 'import' &&
1921
+ passthrough[1] &&
1922
+ passthrough[1] !== '-' &&
1923
+ !isAbsolute(passthrough[1])
1924
+ ) {
1925
+ resolvedPassthrough = [...passthrough];
1926
+ resolvedPassthrough[1] = resolve(cwd, passthrough[1]);
1927
+ }
1928
+
1929
+ let resolvedEnv = env;
1930
+ const secretsDir = env.C8RUN_SECRETS_DIR;
1931
+ if (secretsDir && !isAbsolute(secretsDir)) {
1932
+ resolvedEnv = { ...env, C8RUN_SECRETS_DIR: resolve(cwd, secretsDir) };
1933
+ }
1934
+
1935
+ return { passthrough: resolvedPassthrough, env: resolvedEnv };
1936
+ }
1937
+
1938
+ /**
1939
+ * True when a cluster is currently running, returning its version. Requires
1940
+ * both marker files plus a live pidfile — a stale marker with no live
1941
+ * process must not misdirect a secrets call at a version that is not
1942
+ * actually running.
1943
+ */
1944
+ function runningMarkerVersion(cacheDir) {
1945
+ const markerFile = join(cacheDir, ACTIVE_MARKER_FILE);
1946
+ const versionFile = join(cacheDir, VERSION_MARKER_FILE);
1947
+ if (!existsSync(markerFile) || !existsSync(versionFile)) return null;
1948
+ if (!hasRunningClusterPidfiles(cacheDir)) return null;
1949
+ const version = readFileSync(versionFile, 'utf-8').trim();
1950
+ return version || null;
1951
+ }
1952
+
1953
+ /**
1954
+ * Pick which installed c8run binary should handle a `secrets` passthrough
1955
+ * call. Order: an explicit --c8-version always wins; otherwise prefer the
1956
+ * version currently running (its store is the one actually in effect),
1957
+ * otherwise fall back to the highest locally installed version.
1958
+ *
1959
+ * Never triggers a download — fetching a multi-hundred-MB c8run archive to
1960
+ * run `secrets list` would be a surprising side effect. Returns null when
1961
+ * nothing is installed so the caller can point the user at `cluster install`.
1962
+ */
1963
+ export async function selectSecretsVersion(cacheDir, { explicit } = {}) {
1964
+ if (explicit) {
1965
+ validateVersionSpec(explicit);
1966
+ return resolveVersion(explicit, { preferLocal: true, cacheDir });
1967
+ }
1968
+
1969
+ const running = runningMarkerVersion(cacheDir);
1970
+ if (running) return running;
1971
+
1972
+ const installed = getInstalledVersionsList(cacheDir)
1973
+ .sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
1974
+ return installed.length > 0 ? installed[installed.length - 1] : null;
1975
+ }
1976
+
1977
+ /**
1978
+ * Translate c8run's "unsupported operation" failure into an actionable hint
1979
+ * naming the resolved version, instead of leaving the user to guess why a
1980
+ * documented subcommand didn't work. Any other failure — a validation
1981
+ * error, a permission error, and so on — is c8run's own message, already
1982
+ * streamed to stderr as it was produced; this returns null so the caller
1983
+ * does not print anything extra.
1984
+ */
1985
+ export function mapSecretsFailure(exitCode, stderrTail, version) {
1986
+ if (exitCode === 0) return null;
1987
+ if (!/unsupported operation:\s*secrets/i.test(stderrTail)) return null;
1988
+
1989
+ return (
1990
+ `c8run ${version} does not support "secrets" yet.\n` +
1991
+ `Install a c8run build that includes it, e.g.: c8ctl cluster install ${version}\n` +
1992
+ 'Until then, pass secrets as environment variables when starting instead:\n' +
1993
+ ' SECRET_MY_KEY=value c8ctl cluster start\n'
1994
+ );
1995
+ }
1996
+
1997
+ /**
1998
+ * Forward a `cluster secrets` call to the resolved c8run binary's own
1999
+ * `secrets` subcommand, unchanged. stdin/stdout/stderr are inherited so the
2000
+ * no-echo prompt, --stdin, and `import -` all behave exactly as they would
2001
+ * calling c8run directly — c8ctl adds no validation and never sees a value.
2002
+ *
2003
+ * `spawnFn`, `cwd`, and `env` are injectable for testing; production calls
2004
+ * rely on their defaults (the real `spawn`, the current process's cwd and
2005
+ * environment).
2006
+ */
2007
+ export async function runClusterSecrets(
2008
+ cacheDir,
2009
+ tail,
2010
+ { explicitVersion, spawnFn = spawn, cwd = process.cwd(), env = process.env } = {},
2011
+ ) {
2012
+ const logger = getLogger();
2013
+
2014
+ const version = await selectSecretsVersion(cacheDir, { explicit: explicitVersion });
2015
+ if (!version) {
2016
+ logger.error(
2017
+ 'No c8run installed locally. Install one first: c8ctl cluster install alpha',
2018
+ );
2019
+ process.exit(1);
2020
+ return;
2021
+ }
2022
+
2023
+ let binaryPath;
2024
+ try {
2025
+ binaryPath = getC8RunBinaryPath({ cacheDir, version });
2026
+ } catch (error) {
2027
+ logger.error(`Failed to run secrets command: ${error.message}`);
2028
+ process.exit(1);
2029
+ return;
2030
+ }
2031
+
2032
+ const { passthrough, env: resolvedEnv } = resolveSecretsPaths(tail, { cwd, env });
2033
+
2034
+ const exitCode = await new Promise((resolvePromise, reject) => {
2035
+ const proc = spawnFn(binaryPath, ['secrets', ...passthrough], {
2036
+ stdio: ['inherit', 'inherit', 'pipe'],
2037
+ cwd: dirname(binaryPath),
2038
+ env: resolvedEnv,
2039
+ });
2040
+
2041
+ let stderrTail = '';
2042
+ proc.stderr?.on('data', (chunk) => {
2043
+ const text = typeof chunk === 'string' ? chunk : chunk.toString('utf-8');
2044
+ process.stderr.write(text);
2045
+ stderrTail = (stderrTail + text).slice(-4096);
2046
+ });
2047
+
2048
+ proc.on('error', (err) => {
2049
+ reject(new Error(`Failed to spawn c8run: ${err.message}`));
2050
+ });
2051
+ proc.on('close', (code) => {
2052
+ const hint = mapSecretsFailure(code ?? 1, stderrTail, version);
2053
+ if (hint) {
2054
+ logger.error(hint);
2055
+ }
2056
+ resolvePromise(code ?? 1);
2057
+ });
2058
+ });
2059
+
2060
+ if (exitCode !== 0) {
2061
+ process.exit(exitCode);
2062
+ }
2063
+ }
2064
+
1216
2065
  // ---------------------------------------------------------------------------
1217
2066
  // Status
1218
2067
  // ---------------------------------------------------------------------------
@@ -1231,9 +2080,15 @@ export async function clusterStatus(cacheDir) {
1231
2080
  const versionFile = join(cacheDir, VERSION_MARKER_FILE);
1232
2081
 
1233
2082
  const markerExists = existsSync(markerFile);
1234
- const version = markerExists && existsSync(versionFile)
2083
+ const record = readRunningClusterRecord(cacheDir);
2084
+ // A live process may exist without (or despite) a marker — e.g. after its
2085
+ // install dir was replaced/removed, orphaning it (#560). Detect it so status
2086
+ // never reports "stopped" while a tracked cluster process is still alive.
2087
+ const processesRunning = hasRunningClusterPidfiles(cacheDir);
2088
+ const markerVersion = markerExists && existsSync(versionFile)
1235
2089
  ? readFileSync(versionFile, 'utf-8').trim() || null
1236
2090
  : null;
2091
+ const version = markerVersion ?? record?.version ?? null;
1237
2092
 
1238
2093
  // Check live health endpoint regardless of marker
1239
2094
  let isHealthy = false;
@@ -1253,8 +2108,18 @@ export async function clusterStatus(cacheDir) {
1253
2108
  // Health endpoint not reachable
1254
2109
  }
1255
2110
 
2111
+ // A cluster process is alive but not tracked by a marker — typically an
2112
+ // orphan left after its install dir was replaced/removed (#560).
2113
+ const untracked = !markerExists && processesRunning;
2114
+
2115
+ // `untracked` takes precedence over a healthy probe: an orphaned process can
2116
+ // still serve the health endpoint while holding its ports, and the operator
2117
+ // must be told it is no longer tracked (and how to recover) rather than shown
2118
+ // a plain "running". Healthy connection URLs are still surfaced below.
1256
2119
  let status;
1257
- if (isHealthy) {
2120
+ if (untracked) {
2121
+ status = 'running (untracked)';
2122
+ } else if (isHealthy) {
1258
2123
  status = 'running';
1259
2124
  } else if (markerExists) {
1260
2125
  status = 'starting or unresponsive';
@@ -1263,11 +2128,21 @@ export async function clusterStatus(cacheDir) {
1263
2128
  }
1264
2129
 
1265
2130
  if (globalThis.c8ctl?.getLogger().mode === 'json') {
1266
- logger.json({ status, version, urls: isHealthy ? CLUSTER_URLS : undefined });
2131
+ // Machine-readable status must carry the SAME recovery guidance the text
2132
+ // renderer prints below for an orphan, otherwise a `--json` consumer sees
2133
+ // `running (untracked)` with no actionable instruction (#560).
2134
+ logger.json({
2135
+ status,
2136
+ version,
2137
+ urls: isHealthy ? CLUSTER_URLS : undefined,
2138
+ recovery: untracked
2139
+ ? 'A cluster process is still running but is no longer tracked by c8ctl (its install directory was likely replaced or removed while running). Stop it with: c8ctl cluster stop'
2140
+ : undefined,
2141
+ });
1267
2142
  return;
1268
2143
  }
1269
2144
 
1270
- if (!markerExists && !isHealthy) {
2145
+ if (!markerExists && !isHealthy && !processesRunning) {
1271
2146
  console.log('Cluster status: stopped');
1272
2147
  console.log('');
1273
2148
  console.log(' Start with: c8ctl cluster start');
@@ -1288,7 +2163,15 @@ export async function clusterStatus(cacheDir) {
1288
2163
  console.log(' - Health: ' + CLUSTER_URLS.health);
1289
2164
  console.log('');
1290
2165
  console.log(' Default credentials: demo / demo');
1291
- } else {
2166
+ }
2167
+
2168
+ if (untracked) {
2169
+ // Shown even when the orphan is healthy: it is still not tracked by c8ctl.
2170
+ console.log('');
2171
+ console.log(' A cluster process is still running but is no longer tracked by c8ctl');
2172
+ console.log(' (its install directory was likely replaced or removed while running).');
2173
+ console.log(' Stop it with: c8ctl cluster stop');
2174
+ } else if (!isHealthy) {
1292
2175
  console.log('');
1293
2176
  console.log(' The cluster appears to have been started but is not yet responding.');
1294
2177
  console.log(' Run "c8ctl cluster status" again in a moment, or check the logs.');
@@ -1469,6 +2352,9 @@ export async function deleteVersion(cacheDir, versionSpec) {
1469
2352
  }
1470
2353
 
1471
2354
  purgeInstalledVersion(config, { reason: 'as requested' });
2355
+ // Retire a stale durable record with no live PIDs so its dead (possibly
2356
+ // reused) PIDs are not later mistaken for this cluster (#560).
2357
+ clearStaleRunningClusterRecord(cacheDir);
1472
2358
  logger.info(`Version ${versionSpec} has been deleted.`);
1473
2359
  }
1474
2360
 
@@ -1505,31 +2391,45 @@ export async function purgeClusterData(cacheDir, versionSpec) {
1505
2391
  }
1506
2392
 
1507
2393
  const config = { cacheDir, version: resolvedVersion };
1508
- if (!isC8RunInstalled(config)) {
2394
+ const installDir = join(cacheDir, `c8run-${resolvedVersion}`);
2395
+ if (!existsSync(installDir)) {
1509
2396
  logger.error(`Version ${resolvedVersion} is not installed locally.`);
1510
2397
  process.exit(1);
1511
2398
  }
1512
2399
 
1513
- const binaryPath = getC8RunBinaryPath(config);
1514
- const binaryDir = dirname(binaryPath);
2400
+ // Runtime data normally sits next to the c8run binary. If the binary itself
2401
+ // is missing but the install dir survives — a partial/corrupt install, or the
2402
+ // orphan case where the binary was removed out from under a running cluster
2403
+ // (#560) — fall back to scanning the install dir and its immediate subdirs so
2404
+ // leftover data is still purged instead of being silently left behind.
2405
+ const binaryPath = findC8RunBinaryPath(config);
2406
+ const dataRoots = binaryPath
2407
+ ? [dirname(binaryPath)]
2408
+ : [
2409
+ installDir,
2410
+ ...readdirSync(installDir, { withFileTypes: true })
2411
+ .filter((entry) => entry.isDirectory())
2412
+ .map((entry) => join(installDir, entry.name)),
2413
+ ];
1515
2414
 
1516
2415
  const deleted = [];
2416
+ for (const dataRoot of dataRoots) {
2417
+ // Delete camunda-data (history data + application state)
2418
+ const camundaDataDir = join(dataRoot, 'camunda-data');
2419
+ if (existsSync(camundaDataDir)) {
2420
+ rmSync(camundaDataDir, { recursive: true });
2421
+ deleted.push('camunda-data');
2422
+ }
1517
2423
 
1518
- // Delete camunda-data (history data + application state)
1519
- const camundaDataDir = join(binaryDir, 'camunda-data');
1520
- if (existsSync(camundaDataDir)) {
1521
- rmSync(camundaDataDir, { recursive: true });
1522
- deleted.push('camunda-data');
1523
- }
1524
-
1525
- // Delete Zeebe journal data inside camunda-zeebe-* subdirectory
1526
- if (existsSync(binaryDir)) {
1527
- for (const entry of readdirSync(binaryDir, { withFileTypes: true })) {
1528
- if (!entry.isDirectory() || !entry.name.startsWith('camunda-zeebe-')) continue;
1529
- const dataDir = join(binaryDir, entry.name, 'data');
1530
- if (existsSync(dataDir)) {
1531
- rmSync(dataDir, { recursive: true });
1532
- deleted.push(join(entry.name, 'data'));
2424
+ // Delete Zeebe journal data inside camunda-zeebe-* subdirectory
2425
+ if (existsSync(dataRoot)) {
2426
+ for (const entry of readdirSync(dataRoot, { withFileTypes: true })) {
2427
+ if (!entry.isDirectory() || !entry.name.startsWith('camunda-zeebe-')) continue;
2428
+ const dataDir = join(dataRoot, entry.name, 'data');
2429
+ if (existsSync(dataDir)) {
2430
+ rmSync(dataDir, { recursive: true });
2431
+ deleted.push(join(entry.name, 'data'));
2432
+ }
1533
2433
  }
1534
2434
  }
1535
2435
  }
@@ -1542,6 +2442,9 @@ export async function purgeClusterData(cacheDir, versionSpec) {
1542
2442
  } else {
1543
2443
  logger.info(`No runtime data found for ${resolvedVersion} — nothing to delete.`);
1544
2444
  }
2445
+ // Retire a stale durable record with no live PIDs so its dead (possibly
2446
+ // reused) PIDs are not later mistaken for this cluster (#560).
2447
+ clearStaleRunningClusterRecord(cacheDir);
1545
2448
  logger.info(`Binary and installed files preserved. Start fresh with: c8ctl cluster start ${resolvedVersion}`);
1546
2449
  }
1547
2450
 
@@ -1686,6 +2589,25 @@ const VALID_SUBCOMMANDS = ['start', 'stop', 'status', 'list', 'list-remote', 'in
1686
2589
  export const commands = {
1687
2590
  'cluster': async (args) => {
1688
2591
  const logger = getLogger();
2592
+
2593
+ // Secrets passthrough (#314) is intercepted before parsePluginArgs:
2594
+ // its arguments (verbs, flags, positionals) belong to c8run, not to
2595
+ // c8ctl's own version/--debug/--purge parsing.
2596
+ if (args[0] === 'secrets') {
2597
+ let parsedSecrets;
2598
+ try {
2599
+ parsedSecrets = parseSecretsArgs(sliceSecretsArgv(process.argv.slice(2), args));
2600
+ } catch (error) {
2601
+ logger.error(error.message);
2602
+ process.exit(1);
2603
+ return;
2604
+ }
2605
+ await runClusterSecrets(getCacheDir(), parsedSecrets.passthrough, {
2606
+ explicitVersion: parsedSecrets.version,
2607
+ });
2608
+ return;
2609
+ }
2610
+
1689
2611
  const parsed = parsePluginArgs(args);
1690
2612
 
1691
2613
  if (!parsed.subcommand || !VALID_SUBCOMMANDS.includes(parsed.subcommand)) {
@@ -1699,6 +2621,7 @@ export const commands = {
1699
2621
  console.log(' c8ctl cluster install <version>');
1700
2622
  console.log(' c8ctl cluster delete <version>');
1701
2623
  console.log(' c8ctl cluster purge <version>');
2624
+ console.log(' c8ctl cluster secrets [--c8-version <version>] <set|list|path|delete|import|...>');
1702
2625
  console.log('');
1703
2626
  console.log('Subcommands:');
1704
2627
  console.log(' start Download (if needed) and start a local Camunda 8 cluster');
@@ -1710,6 +2633,7 @@ export const commands = {
1710
2633
  console.log(' install Download a version without starting it');
1711
2634
  console.log(' delete Remove a locally cached version to reclaim disk space');
1712
2635
  console.log(' purge Delete runtime data for a version (binary stays intact, next start is fresh)');
2636
+ console.log(' secrets Manage local development secrets (forwarded verbatim to c8run)');
1713
2637
  console.log('');
1714
2638
  console.log('Options:');
1715
2639
  console.log(' <version> Camunda version, alias, or major.minor (default: stable)');
@@ -1744,6 +2668,14 @@ export const commands = {
1744
2668
  console.log(' c8ctl cluster delete 8.8');
1745
2669
  console.log(' c8ctl cluster purge 8.8 # Delete runtime data, keep binary');
1746
2670
  console.log(' c8ctl cluster stop --purge # Stop cluster and delete its runtime data');
2671
+ console.log(' c8ctl cluster secrets set OPENAI_API_KEY # Prompts, no-echo; use --stdin for automation');
2672
+ console.log(' c8ctl cluster secrets list');
2673
+ console.log(' c8ctl cluster secrets import .env.secrets');
2674
+ console.log(' c8ctl cluster secrets delete OPENAI_API_KEY --yes');
2675
+ console.log('');
2676
+ console.log('secrets forwards everything after it to c8run\'s own "secrets" command —');
2677
+ console.log('c8ctl never sees or stores a secret value. Run "c8ctl cluster secrets help"');
2678
+ console.log('for c8run\'s own secrets help (--help here belongs to c8ctl).');
1747
2679
  return;
1748
2680
  }
1749
2681
 
@@ -1876,6 +2808,17 @@ export const commands = {
1876
2808
  if (!stoppedVersion) {
1877
2809
  logger.warn('Cannot determine which version to purge (version marker is missing). ' +
1878
2810
  'To purge manually, run: c8ctl cluster purge <version>');
2811
+ } else if (!existsSync(join(theCacheDir, `c8run-${stoppedVersion}`))) {
2812
+ // The install dir itself is already gone — e.g. the orphan case
2813
+ // where it was removed out from under a running cluster (#560).
2814
+ // There is genuinely no runtime data left to purge, so treat it as
2815
+ // already purged rather than letting purgeClusterData exit "not
2816
+ // installed" and fail the combined command. If the install dir
2817
+ // still exists (even with its binary missing), fall through to
2818
+ // purgeClusterData so any leftover data is not silently retained.
2819
+ logger.info(
2820
+ `Version ${stoppedVersion} is no longer installed; its runtime data is already gone. Nothing to purge.`,
2821
+ );
1879
2822
  } else {
1880
2823
  await purgeClusterData(theCacheDir, stoppedVersion);
1881
2824
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camunda8/cli",
3
- "version": "4.1.1-alpha.1",
3
+ "version": "4.2.0-alpha.2",
4
4
  "description": "Camunda 8 CLI - minimal-dependency CLI for Camunda 8 operations",
5
5
  "type": "module",
6
6
  "engines": {