@camunda8/cli 4.7.0-alpha.4 → 4.7.0-alpha.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/CONTEXT.md +12 -0
  2. package/PLUGIN-HELP.md +1 -1
  3. package/README.md +8 -1
  4. package/dist/commands/deploy.d.ts.map +1 -1
  5. package/dist/commands/deploy.js +2 -2
  6. package/dist/commands/deploy.js.map +1 -1
  7. package/dist/commands/helpers/deploy-helpers.d.ts +14 -1
  8. package/dist/commands/helpers/deploy-helpers.d.ts.map +1 -1
  9. package/dist/commands/helpers/deploy-helpers.js +69 -13
  10. package/dist/commands/helpers/deploy-helpers.js.map +1 -1
  11. package/dist/commands/mcp-proxy.d.ts.map +1 -1
  12. package/dist/commands/mcp-proxy.js +13 -8
  13. package/dist/commands/mcp-proxy.js.map +1 -1
  14. package/dist/commands/profiles.d.ts.map +1 -1
  15. package/dist/commands/profiles.js +13 -7
  16. package/dist/commands/profiles.js.map +1 -1
  17. package/dist/commands/run.d.ts.map +1 -1
  18. package/dist/commands/run.js +1 -8
  19. package/dist/commands/run.js.map +1 -1
  20. package/dist/commands/watch.d.ts.map +1 -1
  21. package/dist/commands/watch.js +10 -2
  22. package/dist/commands/watch.js.map +1 -1
  23. package/dist/core/client.d.ts +13 -0
  24. package/dist/core/client.d.ts.map +1 -1
  25. package/dist/core/client.js +48 -21
  26. package/dist/core/client.js.map +1 -1
  27. package/dist/core/config.d.ts +34 -3
  28. package/dist/core/config.d.ts.map +1 -1
  29. package/dist/core/config.js +91 -9
  30. package/dist/core/config.js.map +1 -1
  31. package/dist/core/env-address.d.ts +22 -0
  32. package/dist/core/env-address.d.ts.map +1 -0
  33. package/dist/core/env-address.js +30 -0
  34. package/dist/core/env-address.js.map +1 -0
  35. package/dist/core/errors.d.ts +17 -0
  36. package/dist/core/errors.d.ts.map +1 -1
  37. package/dist/core/errors.js +32 -0
  38. package/dist/core/errors.js.map +1 -1
  39. package/dist/core/index.d.ts +2 -0
  40. package/dist/core/index.d.ts.map +1 -1
  41. package/dist/core/index.js +2 -0
  42. package/dist/core/index.js.map +1 -1
  43. package/dist/core/logger.d.ts.map +1 -1
  44. package/dist/core/logger.js +2 -1
  45. package/dist/core/logger.js.map +1 -1
  46. package/dist/core/node-version.d.ts +18 -0
  47. package/dist/core/node-version.d.ts.map +1 -0
  48. package/dist/core/node-version.js +38 -0
  49. package/dist/core/node-version.js.map +1 -0
  50. package/dist/default-plugins/cluster/README.md +16 -1
  51. package/dist/default-plugins/cluster/c8ctl-plugin.js +745 -115
  52. package/dist/default-plugins/element-template/c8ctl-plugin.js +248 -7
  53. package/dist/default-plugins/mcp/README.md +37 -0
  54. package/dist/default-plugins/mcp/c8ctl-plugin.js +4973 -0
  55. package/dist/default-plugins/mcp/package.json +8 -0
  56. package/dist/default-plugins/modeler/README.md +23 -0
  57. package/dist/default-plugins/modeler/c8ctl-plugin.js +4314 -0
  58. package/dist/default-plugins/modeler/package.json +8 -0
  59. package/dist/default-plugins/setup/README.md +42 -0
  60. package/dist/default-plugins/setup/c8ctl-plugin.js +6845 -0
  61. package/dist/default-plugins/setup/package.json +8 -0
  62. package/dist/default-plugins/skills/README.md +35 -0
  63. package/dist/default-plugins/skills/c8ctl-plugin.js +3369 -0
  64. package/dist/default-plugins/skills/package.json +8 -0
  65. package/dist/framework/argv-parser.d.ts +14 -0
  66. package/dist/framework/argv-parser.d.ts.map +1 -1
  67. package/dist/framework/argv-parser.js +25 -0
  68. package/dist/framework/argv-parser.js.map +1 -1
  69. package/dist/framework/command-registry.d.ts +28 -2
  70. package/dist/framework/command-registry.d.ts.map +1 -1
  71. package/dist/framework/command-registry.js +47 -2
  72. package/dist/framework/command-registry.js.map +1 -1
  73. package/dist/framework/plugins/plugin-loader.d.ts +20 -2
  74. package/dist/framework/plugins/plugin-loader.d.ts.map +1 -1
  75. package/dist/framework/plugins/plugin-loader.js.map +1 -1
  76. package/dist/framework/ui/help.d.ts.map +1 -1
  77. package/dist/framework/ui/help.js +57 -14
  78. package/dist/framework/ui/help.js.map +1 -1
  79. package/dist/framework/ui/prompt.d.ts +88 -0
  80. package/dist/framework/ui/prompt.d.ts.map +1 -1
  81. package/dist/framework/ui/prompt.js +558 -20
  82. package/dist/framework/ui/prompt.js.map +1 -1
  83. package/dist/index.d.ts.map +1 -1
  84. package/dist/index.js +68 -12
  85. package/dist/index.js.map +1 -1
  86. package/dist/utils/command-local/mcp-install-helpers.d.ts +68 -0
  87. package/dist/utils/command-local/mcp-install-helpers.d.ts.map +1 -0
  88. package/dist/utils/command-local/mcp-install-helpers.js +485 -0
  89. package/dist/utils/command-local/mcp-install-helpers.js.map +1 -0
  90. package/dist/utils/command-local/process-instance-helpers.d.ts +6 -0
  91. package/dist/utils/command-local/process-instance-helpers.d.ts.map +1 -1
  92. package/dist/utils/command-local/process-instance-helpers.js +9 -0
  93. package/dist/utils/command-local/process-instance-helpers.js.map +1 -1
  94. package/dist/utils/command-local/skills-install-helpers.d.ts +49 -0
  95. package/dist/utils/command-local/skills-install-helpers.d.ts.map +1 -0
  96. package/dist/utils/command-local/skills-install-helpers.js +436 -0
  97. package/dist/utils/command-local/skills-install-helpers.js.map +1 -0
  98. package/dist/utils/index.d.ts +2 -2
  99. package/dist/utils/index.d.ts.map +1 -1
  100. package/dist/utils/index.js +2 -2
  101. package/dist/utils/index.js.map +1 -1
  102. package/dist/utils/shared/camunda-json.d.ts +16 -3
  103. package/dist/utils/shared/camunda-json.d.ts.map +1 -1
  104. package/dist/utils/shared/camunda-json.js +20 -5
  105. package/dist/utils/shared/camunda-json.js.map +1 -1
  106. package/dist/utils/shared/deploy-resource-selection.d.ts +7 -15
  107. package/dist/utils/shared/deploy-resource-selection.d.ts.map +1 -1
  108. package/dist/utils/shared/deploy-resource-selection.js +9 -19
  109. package/dist/utils/shared/deploy-resource-selection.js.map +1 -1
  110. package/dist/utils/shared/ignore.d.ts +6 -0
  111. package/dist/utils/shared/ignore.d.ts.map +1 -1
  112. package/dist/utils/shared/ignore.js +9 -1
  113. package/dist/utils/shared/ignore.js.map +1 -1
  114. package/package.json +3 -2
  115. package/dist/utils/command-local/setup-detectors.d.ts +0 -51
  116. package/dist/utils/command-local/setup-detectors.d.ts.map +0 -1
  117. package/dist/utils/command-local/setup-detectors.js +0 -115
  118. package/dist/utils/command-local/setup-detectors.js.map +0 -1
  119. package/dist/utils/command-local/setup-prerequisites.d.ts +0 -67
  120. package/dist/utils/command-local/setup-prerequisites.d.ts.map +0 -1
  121. package/dist/utils/command-local/setup-prerequisites.js +0 -238
  122. package/dist/utils/command-local/setup-prerequisites.js.map +0 -1
@@ -10,21 +10,26 @@
10
10
 
11
11
  import { spawn, execFileSync } from 'node:child_process';
12
12
  import {
13
+ closeSync,
13
14
  createWriteStream,
14
15
  existsSync,
16
+ fstatSync,
15
17
  mkdirSync,
18
+ openSync,
16
19
  writeFileSync,
17
20
  renameSync,
18
21
  rmSync,
19
22
  readdirSync,
20
23
  readFileSync,
24
+ readSync,
21
25
  statSync,
22
26
  } from 'node:fs';
23
27
  import { once } from 'node:events';
24
28
  import { chmod } from 'node:fs/promises';
25
- import { homedir, platform as osPlatform, arch as osArch } from 'node:os';
26
- import { join, dirname, isAbsolute, resolve } from 'node:path';
29
+ import { homedir, platform as osPlatform, arch as osArch, constants as osConstants } from 'node:os';
30
+ import { join, dirname, basename, isAbsolute, relative, resolve } from 'node:path';
27
31
  import { finished } from 'node:stream/promises';
32
+ import { StringDecoder } from 'node:string_decoder';
28
33
  import { fileURLToPath } from 'node:url';
29
34
 
30
35
  // ---------------------------------------------------------------------------
@@ -210,37 +215,145 @@ function readLocalAliasMapping(cacheDir, alias) {
210
215
  const filePath = getAliasMappingPath(cacheDir, alias);
211
216
  if (!existsSync(filePath)) return null;
212
217
  try {
213
- const value = readFileSync(filePath, 'utf-8').trim();
214
218
  // Only use the cached mapping if the version is actually installed
215
- const config = { cacheDir, version: value };
216
- if (isC8RunInstalled(config)) return value;
217
-
218
- // For rolling versions (minor version patterns like "8.9"), check if any
219
- // installed version matches the minor version prefix (e.g. "8.9" matches
220
- // "8.9.5"). This prevents re-downloading a rolling alias when a compatible
221
- // pinned version is already installed locally (#431).
222
- if (isMinorVersionPattern(value)) {
223
- const installedVersions = getInstalledVersionsList(cacheDir)
224
- .sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
225
- const match = installedVersions
226
- .filter((v) => v.startsWith(value + '.'))
227
- .reverse()
228
- .find((v) => isC8RunInstalled({ cacheDir, version: v }));
229
- if (match) return match;
219
+ return findInstalledAliasTarget(cacheDir, readFileSync(filePath, 'utf-8').trim(), alias);
220
+ } catch {
221
+ return null;
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Return the installed version that satisfies an alias target, or null.
227
+ * An exact install wins; for a rolling minor pattern ("8.9") the highest
228
+ * installed pin in that minor line ("8.9.5") also counts, so a compatible
229
+ * pinned install is not re-downloaded (#431). For `stable`, an install whose
230
+ * build is a prerelease never counts — whether pinned ("c8run-8.10.0-alpha1")
231
+ * or a rolling dir that still holds an alpha build ("c8run-8.10/c8run-8.10.0-alpha1").
232
+ */
233
+ function findInstalledAliasTarget(cacheDir, value, alias) {
234
+ const accepts = (version) => {
235
+ const build = installedBuildName(cacheDir, version);
236
+ if (!build) return false;
237
+ return alias !== 'stable' || !isPrereleaseBuild(build);
238
+ };
239
+
240
+ if (accepts(value)) return value;
241
+
242
+ if (isMinorVersionPattern(value)) {
243
+ const installedVersions = getInstalledVersionsList(cacheDir)
244
+ .sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
245
+ const match = installedVersions
246
+ .filter((v) => v.startsWith(value + '.'))
247
+ .reverse()
248
+ .find(accepts);
249
+ if (match) return match;
250
+ }
251
+
252
+ return null;
253
+ }
254
+
255
+ /** True for a build dir like "c8run-8.10.0-alpha1" (anything with a semver prerelease suffix). */
256
+ function isPrereleaseBuild(buildDirName) {
257
+ return /^c8run-\d+\.\d+(\.\d+)?-/.test(buildDirName);
258
+ }
259
+
260
+ /**
261
+ * Every cluster data dir in an install: `camunda-data` and the `data` dir
262
+ * inside each `camunda-zeebe-` dir, beside any launcher in the install dir
263
+ * or one of its immediate subdirs (older builds of a rolling install, or an
264
+ * install that lost its launcher). `cluster purge` deletes exactly these, and
265
+ * `stable` refuses to replace an install that still has any.
266
+ */
267
+ function findClusterDataDirs(installDir) {
268
+ const listDirs = (dir) => {
269
+ try {
270
+ return readdirSync(dir, { withFileTypes: true }).filter((entry) => entry.isDirectory());
271
+ } catch {
272
+ return [];
273
+ }
274
+ };
275
+ const roots = [installDir, ...listDirs(installDir).map((entry) => join(installDir, entry.name))];
276
+ const found = [];
277
+ for (const root of roots) {
278
+ const camundaData = join(root, 'camunda-data');
279
+ if (existsSync(camundaData)) found.push(camundaData);
280
+ for (const entry of listDirs(root)) {
281
+ const journal = join(root, entry.name, 'data');
282
+ if (entry.name.startsWith('camunda-zeebe-') && existsSync(journal)) found.push(journal);
230
283
  }
284
+ }
285
+ return found;
286
+ }
231
287
 
232
- return null;
288
+ /**
289
+ * Refuse to replace a `stable` install whose cluster data would be deleted:
290
+ * a prerelease build, or an install that lost its launcher. Data may sit
291
+ * beside the launcher or, without one, in the install dir or a subdir of it.
292
+ * A GA build is replaced like any rolling update.
293
+ */
294
+ function refuseIfClusterDataAtRisk(config) {
295
+ const version = config.version;
296
+ const installDir = join(config.cacheDir, `c8run-${version}`);
297
+ if (!existsSync(installDir)) return;
298
+ const build = installedBuildName(config.cacheDir, version);
299
+ if (build && !isPrereleaseBuild(build)) return;
300
+
301
+ if (findClusterDataDirs(installDir).length === 0) return;
302
+
303
+ const state = build
304
+ ? `holds a prerelease build (${build.slice('c8run-'.length)}) with cluster data`
305
+ : 'has cluster data but no c8run launcher';
306
+ const options = build
307
+ ? `Keep using it with "c8ctl cluster start ${version}", or delete its data with`
308
+ : 'Delete its data with';
309
+ throw new Error(
310
+ `c8run ${version} ${state}. "stable" needs a GA build, and replacing this install would delete that data. ` +
311
+ `${options} "c8ctl cluster purge ${version}" and run this command again.`,
312
+ );
313
+ }
314
+
315
+ /** Name of the build dir whose c8run would launch for `version` (e.g. "c8run-8.10.0-alpha1"), or null. */
316
+ function installedBuildName(cacheDir, version) {
317
+ const binaryPath = findC8RunBinaryPath({ cacheDir, version });
318
+ return binaryPath ? basename(dirname(binaryPath)) : null;
319
+ }
320
+
321
+ /** The prerelease build installed for `version`, or null when none is installed or it is GA. */
322
+ function installedPrereleaseBuild(cacheDir, version) {
323
+ const build = installedBuildName(cacheDir, version);
324
+ return build && isPrereleaseBuild(build) ? build : null;
325
+ }
326
+
327
+ /**
328
+ * Explain why `stable` has no usable local install when the version it would
329
+ * resolve to only holds a prerelease build — either `version` itself or the
330
+ * cached `stable` mapping (which resolution skips for that reason). Null otherwise.
331
+ */
332
+ function describePrereleaseOnlyStable(cacheDir, version) {
333
+ let cached = null;
334
+ try {
335
+ cached = readFileSync(getAliasMappingPath(cacheDir, 'stable'), 'utf-8').trim();
233
336
  } catch {
234
- return null;
337
+ // No cached mapping
235
338
  }
339
+ for (const candidate of [version, cached]) {
340
+ const build = candidate && installedPrereleaseBuild(cacheDir, candidate);
341
+ if (build) {
342
+ return `Only a prerelease build of ${candidate} is installed (${build.slice('c8run-'.length)}); "stable" needs a GA build.`;
343
+ }
344
+ }
345
+ return null;
236
346
  }
237
347
 
348
+ /** Persist an alias mapping. Returns false if it could not be written. */
238
349
  export function storeLocalAliasMapping(cacheDir, alias, resolved) {
239
350
  try {
240
351
  mkdirSync(cacheDir, { recursive: true });
241
352
  writeFileSync(getAliasMappingPath(cacheDir, alias), resolved);
353
+ return true;
242
354
  } catch {
243
355
  // Best-effort — don't break the command if we can't persist
356
+ return false;
244
357
  }
245
358
  }
246
359
 
@@ -265,16 +378,21 @@ export function _resetDynamicAliasCache() {
265
378
  }
266
379
 
267
380
  /**
268
- * Non-blocking background check: query the remote download server and print
269
- * a hint if the remote alias resolves to a different (newer) version.
381
+ * Non-blocking background check: query the remote download server and act
382
+ * if the remote alias resolves to a newer minor than the one being started.
383
+ *
384
+ * - Newer version already installed (e.g. via `cluster install 8.10`): the
385
+ * persisted alias mapping is advanced to it, so the *next* `start` uses it.
386
+ * Nothing is downloaded — the user already chose to install that version.
387
+ * - Newer version not installed: only a hint is printed; the mapping is left
388
+ * alone so `start` never silently switches to a version it would have to
389
+ * download.
270
390
  *
271
- * Important: does NOT update the persisted alias mapping. The mapping is only
272
- * updated when the user explicitly runs `cluster install`, keeping `start`
273
- * deterministic across runs.
391
+ * The current run is never affected: it has already resolved its version.
274
392
  *
275
393
  * Returns the fire-and-forget promise (for testing).
276
394
  */
277
- export function checkBackgroundAliasFreshness(versionSpec, resolvedVersion) {
395
+ export function checkBackgroundAliasFreshness(versionSpec, resolvedVersion, cacheDir) {
278
396
  const logger = getLogger();
279
397
  const controller = new AbortController();
280
398
  const timeoutId = setTimeout(() => controller.abort(), 5000);
@@ -285,7 +403,22 @@ export function checkBackgroundAliasFreshness(versionSpec, resolvedVersion) {
285
403
  if (html) {
286
404
  const remote = parseVersionsFromHtml(html);
287
405
  const remoteVersion = remote?.[versionSpec];
288
- if (remoteVersion && isRemoteMinorNewer(remoteVersion, resolvedVersion)) {
406
+ if (!remoteVersion || !isRemoteMinorNewer(remoteVersion, resolvedVersion)) return;
407
+ const installed = cacheDir && findInstalledAliasTarget(cacheDir, remoteVersion, versionSpec);
408
+ if (installed) {
409
+ if (storeLocalAliasMapping(cacheDir, versionSpec, remoteVersion)) {
410
+ logger.info(
411
+ `"${versionSpec}" now resolves to ${remoteVersion}, which is already installed. ` +
412
+ `The next "c8ctl cluster start ${versionSpec}" will use it.`,
413
+ );
414
+ } else {
415
+ // Name the exact install: a plain "8.10" would look for c8run-8.10 and download it.
416
+ logger.info(
417
+ `"${versionSpec}" now resolves to ${remoteVersion}, which is already installed, ` +
418
+ `but the cached alias could not be updated. Start it with: c8ctl cluster start ${installed}`,
419
+ );
420
+ }
421
+ } else {
289
422
  logger.info(
290
423
  `A newer "${versionSpec}" release is available (${remoteVersion}). ` +
291
424
  `Install it with: c8ctl cluster install ${versionSpec}`,
@@ -310,6 +443,25 @@ function fireAndForget(promise) {
310
443
  return promise.catch(() => {});
311
444
  }
312
445
 
446
+ /**
447
+ * Give the background `start` hints (alias freshness, rolling update) a short,
448
+ * bounded chance to print before a failed start calls process.exit(), which
449
+ * would otherwise drop them mid-flight. A failed start is when a newer version
450
+ * is most worth knowing about.
451
+ */
452
+ export async function flushStartHints(config, timeoutMs = 1000) {
453
+ const pending = [config?._aliasHintPromise, config?._hintPromise].filter(Boolean);
454
+ if (pending.length === 0) return;
455
+ let timer;
456
+ await Promise.race([
457
+ Promise.all(pending),
458
+ new Promise((resolve) => {
459
+ timer = setTimeout(resolve, timeoutMs);
460
+ }),
461
+ ]);
462
+ clearTimeout(timer);
463
+ }
464
+
313
465
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
314
466
 
315
467
  // ---------------------------------------------------------------------------
@@ -334,12 +486,13 @@ export const metadata = {
334
486
  // so the subcommand flags are documented via `flagsHint` instead.
335
487
  passthrough: true,
336
488
  passthroughHint:
337
- '--purge, --debug, --physical-tenants and --c8-version are read by the plugin. For local management, physical-tenants and --physical-tenant are forwarded unchanged to a compatible c8run release.',
489
+ '--purge, --debug, --port, --physical-tenants and --c8-version are read by the plugin. For local management, physical-tenants and --physical-tenant are forwarded unchanged to a compatible c8run release.',
338
490
  flagsHint: [
339
491
  '--c8-version <version> Camunda version, alias or major.minor (alternative to the positional <version>)',
340
492
  '--debug (start, stop) Stream raw c8run output',
341
493
  '--purge (stop only) Also delete runtime data after stopping',
342
494
  '--physical-tenants <ids> (start only) Comma-separated physical tenants for this run (repeatable; Camunda 8.10+)',
495
+ '--port <number> (start only) Main Camunda HTTP port (default 8080; gRPC 26500 and health 9600 stay fixed)',
343
496
  '--physical-tenant <id> (secrets only) Scope secrets to one physical tenant (also --physical-tenant=<id>)',
344
497
  ],
345
498
  subcommands: [
@@ -360,6 +513,7 @@ export const metadata = {
360
513
  { command: 'c8ctl cluster start', description: 'Start a local Camunda 8 cluster (latest stable)' },
361
514
  { command: 'c8ctl cluster start 8.8', description: 'Start the latest cached 8.8.x release' },
362
515
  { command: 'c8ctl cluster start 8.9.0-alpha5', description: 'Start a specific version' },
516
+ { command: 'c8ctl cluster start --port 9091', description: 'Start a local cluster serving HTTP on port 9091' },
363
517
  { command: 'c8ctl cluster stop', description: 'Stop the running cluster' },
364
518
  { command: 'c8ctl cluster status', description: 'Show whether a cluster is running and how to connect' },
365
519
  { command: 'c8ctl cluster logs', description: 'Stream log output from the running cluster' },
@@ -404,6 +558,8 @@ function getLogger() {
404
558
 
405
559
  const ACTIVE_MARKER_FILE = 'cluster.active';
406
560
  const VERSION_MARKER_FILE = 'cluster.version';
561
+ const PORT_MARKER_FILE = 'cluster.port';
562
+ const DEFAULT_HTTP_PORT = 8080;
407
563
  // Durable running-cluster PID record, written at start time. Unlike c8run's
408
564
  // own `.process` pidfiles — which live INSIDE a version's install dir and
409
565
  // vanish when that dir is replaced or removed — this record lives at the
@@ -1276,7 +1432,11 @@ async function downloadC8Run(config) {
1276
1432
  return { archivePath: targetFile, etag: result.etag };
1277
1433
  }
1278
1434
 
1279
- async function extractArchive(archivePath, targetDir) {
1435
+ // How long an aborted extractor gets to exit before it is killed outright.
1436
+ const EXTRACTOR_KILL_GRACE_MS = 3000;
1437
+
1438
+ /** Aborting `abortSignal` terminates the extractor; the promise settles once it has exited. */
1439
+ async function extractArchive(archivePath, targetDir, { abortSignal } = {}) {
1280
1440
  const logger = getLogger();
1281
1441
  logger.info(`Extracting to ${targetDir}...`);
1282
1442
 
@@ -1290,6 +1450,17 @@ async function extractArchive(archivePath, targetDir) {
1290
1450
 
1291
1451
  return new Promise((resolve, reject) => {
1292
1452
  const proc = spawn(command, args, { stdio: 'inherit' });
1453
+ let killTimer;
1454
+ const terminate = () => {
1455
+ proc.kill('SIGTERM');
1456
+ killTimer = setTimeout(() => proc.kill('SIGKILL'), EXTRACTOR_KILL_GRACE_MS);
1457
+ };
1458
+ if (abortSignal?.aborted) terminate();
1459
+ else abortSignal?.addEventListener('abort', terminate, { once: true });
1460
+ proc.on('close', () => {
1461
+ clearTimeout(killTimer);
1462
+ abortSignal?.removeEventListener('abort', terminate);
1463
+ });
1293
1464
  proc.on('exit', (code, signal) => {
1294
1465
  if (code === 0) {
1295
1466
  logger.info('Extraction complete.');
@@ -1491,7 +1662,18 @@ export async function hasNewerVersionAvailable(config) {
1491
1662
  export async function ensureC8RunInstalled(config) {
1492
1663
  const logger = getLogger();
1493
1664
 
1494
- if (isC8RunInstalled(config)) {
1665
+ // `stable` must never launch a prerelease, e.g. a rolling dir still holding
1666
+ // the alpha build installed through `alpha` before that minor went GA.
1667
+ const prereleaseBuild = config.requireGA ? installedPrereleaseBuild(config.cacheDir, config.version) : null;
1668
+ // Checked before downloading anything, and again right before the swap.
1669
+ if (config.requireGA) refuseIfClusterDataAtRisk(config);
1670
+
1671
+ if (prereleaseBuild) {
1672
+ logger.info(
1673
+ `c8run ${config.version} holds a prerelease build (${prereleaseBuild.slice('c8run-'.length)}); ` +
1674
+ '"stable" needs a GA build, so it will be replaced.',
1675
+ );
1676
+ } else if (isC8RunInstalled(config)) {
1495
1677
  if (config.checkForUpdates) {
1496
1678
  // Explicitly asked to check for updates (e.g. install subcommand with a rolling version)
1497
1679
  const hasUpdate = await hasNewerVersionAvailable(config);
@@ -1509,7 +1691,9 @@ export async function ensureC8RunInstalled(config) {
1509
1691
  'Stop it first with "c8ctl cluster stop", then re-run the install.',
1510
1692
  );
1511
1693
  }
1512
- purgeInstalledVersion(config);
1694
+ // stable is replaced via a staged swap after the new build is validated,
1695
+ // so a rejected archive never leaves it without a usable install.
1696
+ if (!config.requireGA) purgeInstalledVersion(config);
1513
1697
  } else {
1514
1698
  // Use local installation as-is (start subcommand, or pinned version)
1515
1699
  logger.info(`c8run ${config.version} is already installed.`);
@@ -1549,20 +1733,34 @@ export async function ensureC8RunInstalled(config) {
1549
1733
  );
1550
1734
  }
1551
1735
 
1552
- logger.info('No local installation found. Setting up...');
1736
+ if (!isC8RunInstalled(config)) logger.info('No local installation found. Setting up...');
1553
1737
 
1554
- const { archivePath, etag } = await downloadC8Run(config);
1738
+ let download;
1739
+ try {
1740
+ download = await downloadC8Run(config);
1741
+ } catch (error) {
1742
+ const note = config.requireGA && describePrereleaseOnlyStable(config.cacheDir, config.version);
1743
+ if (note) throw new Error(`${note} ${error?.message ?? error}`, { cause: error?.cause });
1744
+ throw error;
1745
+ }
1746
+ const { archivePath, etag } = download;
1555
1747
 
1556
1748
  const installDir = join(config.cacheDir, `c8run-${config.version}`);
1557
- await extractArchive(archivePath, installDir);
1749
+
1750
+ if (config.requireGA) {
1751
+ await installGABuild(config, archivePath, installDir);
1752
+ } else {
1753
+ await extractArchive(archivePath, installDir);
1754
+ }
1558
1755
 
1559
1756
  // Clean up the downloaded archive to save disk space
1560
1757
  if (existsSync(archivePath)) {
1561
1758
  rmSync(archivePath);
1562
1759
  }
1563
1760
 
1564
- const binaryPath = getC8RunBinaryPath(config);
1565
- await chmod(binaryPath, 0o755);
1761
+ if (!config.requireGA) {
1762
+ await chmod(getC8RunBinaryPath(config), 0o755);
1763
+ }
1566
1764
 
1567
1765
  // Store the ETag for rolling versions so future checks can detect new releases
1568
1766
  if (config.isRolling && etag) {
@@ -1572,18 +1770,161 @@ export async function ensureC8RunInstalled(config) {
1572
1770
  logger.info(`c8run ${config.version} installed successfully.`);
1573
1771
  }
1574
1772
 
1773
+ /**
1774
+ * Install the archive for `stable` without ever leaving a prerelease or
1775
+ * nothing in place: extract into a staging dir, require a GA launcher there,
1776
+ * then swap it in. Any failure before the swap leaves the existing install
1777
+ * (e.g. a usable alpha build) untouched.
1778
+ */
1779
+ async function installGABuild(config, archivePath, installDir) {
1780
+ const logger = getLogger();
1781
+ const stagingRoot = join(config.cacheDir, `.staging-c8run-${config.version}-${process.pid}`);
1782
+ const stagedDir = join(stagingRoot, `c8run-${config.version}`);
1783
+ // Dot-prefixed so neither dir is ever listed as an installed version ("c8run-*").
1784
+ const backupDir = join(config.cacheDir, `.replaced-c8run-${config.version}-${process.pid}`);
1785
+ // Leftovers of runs that were killed outright (SIGKILL, power loss) cannot clean up after themselves.
1786
+ sweepStaleInstallDirs(config.cacheDir);
1787
+ rmSync(stagingRoot, { recursive: true, force: true });
1788
+
1789
+ // `finally` does not run when a signal ends the process, so clean up here.
1790
+ // The swap below is synchronous, so a signal can only land while extracting.
1791
+ const extraction = new AbortController();
1792
+ let extracting = Promise.resolve();
1793
+ let interrupted = false;
1794
+ const signalHandlers = INTERRUPT_SIGNALS.map((signal) => {
1795
+ const handler = async () => {
1796
+ interrupted = true;
1797
+ extraction.abort();
1798
+ // The extractor must be gone first, or it can recreate files after the cleanup.
1799
+ await extracting.catch(() => {});
1800
+ removeStagingRoot(stagingRoot);
1801
+ process.exit(128 + osConstants.signals[signal]);
1802
+ };
1803
+ process.on(signal, handler);
1804
+ return [signal, handler];
1805
+ });
1806
+
1807
+ try {
1808
+ extracting = extractArchive(archivePath, stagedDir, { abortSignal: extraction.signal });
1809
+ // On an interrupt the handler owns the shutdown; do not let the abort error unwind into the caller first.
1810
+ await extracting.catch((error) => {
1811
+ if (interrupted) return new Promise(() => {});
1812
+ throw error;
1813
+ });
1814
+ const stagedBinary = findC8RunBinaryPath({ cacheDir: stagingRoot, version: config.version });
1815
+ if (!stagedBinary) {
1816
+ throw new Error(`The downloaded c8run ${config.version} archive does not contain a c8run launcher.`);
1817
+ }
1818
+ const stagedBuild = basename(dirname(stagedBinary));
1819
+ if (isPrereleaseBuild(stagedBuild)) {
1820
+ throw new Error(
1821
+ `The downloaded c8run ${config.version} is a prerelease build (${stagedBuild.slice('c8run-'.length)}); ` +
1822
+ '"stable" needs a GA build. Try again once the GA build is published, or start an explicit GA version.',
1823
+ );
1824
+ }
1825
+ await chmod(stagedBinary, 0o755);
1826
+
1827
+ // Rechecked here: another c8ctl may have started this version during the download.
1828
+ if (isVersionInstanceRunning(config.cacheDir, config.version)) {
1829
+ throw new Error(
1830
+ `Refusing to replace c8run ${config.version}: an instance started from it is still running. ` +
1831
+ 'Stop it first with "c8ctl cluster stop".',
1832
+ );
1833
+ }
1834
+
1835
+ // Rechecked here too: data may have been created during the download.
1836
+ refuseIfClusterDataAtRisk(config);
1837
+
1838
+ const replacing = existsSync(installDir);
1839
+ if (replacing) {
1840
+ logger.info(`Replacing the existing c8run ${config.version} build...`);
1841
+ rmSync(backupDir, { recursive: true, force: true });
1842
+ renameSync(installDir, backupDir);
1843
+ }
1844
+ try {
1845
+ renameSync(stagedDir, installDir);
1846
+ } catch (error) {
1847
+ if (replacing) renameSync(backupDir, installDir);
1848
+ throw error;
1849
+ }
1850
+ if (replacing) rmSync(backupDir, { recursive: true, force: true });
1851
+ } finally {
1852
+ for (const [signal, handler] of signalHandlers) process.off(signal, handler);
1853
+ rmSync(stagingRoot, { recursive: true, force: true });
1854
+ }
1855
+ }
1856
+
1857
+ const INTERRUPT_SIGNALS = ['SIGINT', 'SIGTERM'];
1858
+
1859
+ function removeStagingRoot(stagingRoot) {
1860
+ try {
1861
+ rmSync(stagingRoot, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 });
1862
+ } catch {
1863
+ // Best effort: the next install or delete/purge sweeps what is left.
1864
+ }
1865
+ }
1866
+
1867
+ const STALE_INSTALL_DIR = /^\.(staging|replaced)-(c8run-.+)-(\d+)$/;
1868
+
1869
+ /**
1870
+ * Clean up after `.staging-c8run-*` and `.replaced-c8run-*` dirs whose owning
1871
+ * c8ctl (the trailing pid) is gone. They are dot-prefixed, so `cluster list`
1872
+ * and `cluster delete` never see them. Dirs of a live pid belong to a
1873
+ * concurrent install and are left alone.
1874
+ *
1875
+ * A staging dir is only ever a partial extraction, so it is deleted. A
1876
+ * `.replaced` dir is the previous install, set aside just before the swap; if
1877
+ * its owner died between the two renames it is the only copy left, so it is
1878
+ * moved back when the install dir is missing and deleted only when redundant.
1879
+ */
1880
+ export function sweepStaleInstallDirs(cacheDir) {
1881
+ if (!existsSync(cacheDir)) return;
1882
+ for (const entry of readdirSync(cacheDir, { withFileTypes: true })) {
1883
+ const match = entry.isDirectory() && STALE_INSTALL_DIR.exec(entry.name);
1884
+ if (!match || isPidAlive(Number(match[3]))) continue;
1885
+ const dir = join(cacheDir, entry.name);
1886
+ try {
1887
+ const installDir = join(cacheDir, match[2]);
1888
+ if (match[1] === 'replaced' && !existsSync(installDir)) {
1889
+ renameSync(dir, installDir);
1890
+ } else {
1891
+ rmSync(dir, { recursive: true, force: true });
1892
+ }
1893
+ } catch {
1894
+ // Best effort: housekeeping must not fail the command that triggered it.
1895
+ }
1896
+ }
1897
+ }
1898
+
1575
1899
  // ---------------------------------------------------------------------------
1576
1900
  // Process management
1577
1901
  // ---------------------------------------------------------------------------
1578
1902
 
1579
1903
  const STARTUP_SUMMARY_MARKER = '- Operate:';
1904
+ const ANSI_SGR = /\u001b\[[0-9;]*m/g;
1905
+
1906
+ /**
1907
+ * c8run's zerolog console lines (`9:57AM INF …`). The summary is printed
1908
+ * as soon as Camunda is healthy, but the captured output continues with
1909
+ * these log lines while the Connectors runtime still starts. Cut there —
1910
+ * printing them after the summary looks like the cluster started twice.
1911
+ */
1912
+ const C8RUN_LOG_LINE =
1913
+ /^\d{1,2}:\d{2}(?::\d{2})?(?:AM|PM)?\s+(?:DBG|INF|WRN|ERR|FTL|PNC|TRC)\s/;
1580
1914
 
1581
- function extractStartupSummary(rawOutput) {
1582
- const startIndex = rawOutput.indexOf(STARTUP_SUMMARY_MARKER);
1915
+ export function extractStartupSummary(rawOutput) {
1916
+ const output = rawOutput.replace(ANSI_SGR, '');
1917
+ const startIndex = output.indexOf(STARTUP_SUMMARY_MARKER);
1583
1918
  if (startIndex === -1) {
1584
1919
  return null;
1585
1920
  }
1586
- return rawOutput.slice(startIndex).trim();
1921
+ const lines = output.slice(startIndex).split('\n');
1922
+ const summaryLines = [];
1923
+ for (const line of lines) {
1924
+ if (C8RUN_LOG_LINE.test(line.trimStart())) break;
1925
+ summaryLines.push(line);
1926
+ }
1927
+ return summaryLines.join('\n').trim();
1587
1928
  }
1588
1929
 
1589
1930
  async function waitForClusterReady(maxWaitMs = CLUSTER_STARTUP_TIMEOUT_MS) {
@@ -1614,29 +1955,39 @@ async function waitForClusterReady(maxWaitMs = CLUSTER_STARTUP_TIMEOUT_MS) {
1614
1955
  return false;
1615
1956
  }
1616
1957
 
1617
- function printSummary(rawOutput, version) {
1958
+ function printSummary(rawOutput, version, port = DEFAULT_HTTP_PORT) {
1618
1959
  const summary = extractStartupSummary(rawOutput);
1619
1960
 
1620
1961
  if (summary) {
1621
1962
  console.log(`\n${summary}\n`);
1622
- return;
1963
+ } else {
1964
+ // c8run daemonizes so captured output is often empty — print known defaults
1965
+ const urls = clusterUrls(port);
1966
+ console.log('');
1967
+ console.log(`Camunda 8 (${version}) is running:`);
1968
+ console.log('');
1969
+ console.log(` - Operate: ${urls.operate}`);
1970
+ console.log(` - Tasklist: ${urls.tasklist}`);
1971
+ console.log(` - Zeebe GRPC: ${urls.zeebeGrpc}`);
1972
+ console.log(` - Zeebe REST: ${urls.zeebeRest}`);
1973
+ console.log(` - Health: ${urls.health}`);
1974
+ console.log('');
1975
+ console.log(' Default credentials: demo / demo');
1976
+ console.log('');
1623
1977
  }
1624
1978
 
1625
- // c8run daemonizes so captured output is often empty — print known defaults
1626
- console.log('');
1627
- console.log(`Camunda 8 (${version}) is running:`);
1628
- console.log('');
1629
- console.log(' - Operate: http://localhost:8080/operate');
1630
- console.log(' - Tasklist: http://localhost:8080/tasklist');
1631
- console.log(' - Zeebe GRPC: localhost:26500');
1632
- console.log(' - Zeebe REST: http://localhost:8080/v2/');
1633
- console.log(' - Health: http://localhost:9600/actuator/health');
1634
- console.log('');
1635
- console.log(' Default credentials: demo / demo');
1636
- console.log('');
1979
+ if (port !== DEFAULT_HTTP_PORT) {
1980
+ // The built-in 'local' profile targets the default port; tell the user how
1981
+ // to point c8ctl at this cluster rather than rewriting their profile.
1982
+ console.log(` c8ctl's 'local' profile targets port ${DEFAULT_HTTP_PORT}. To use this cluster, either:`);
1983
+ console.log(` c8ctl add profile local-${port} --baseUrl=http://localhost:${port}/v2 --username=demo --password=demo`);
1984
+ console.log(` c8ctl use profile local-${port}`);
1985
+ console.log(` or, with no active profile, set CAMUNDA_BASE_URL=http://localhost:${port}/v2`);
1986
+ console.log('');
1987
+ }
1637
1988
  }
1638
1989
 
1639
- async function startC8Run(config, debug = false, startArgs = []) {
1990
+ async function startC8Run(config, debug = false, startArgs = [], port = DEFAULT_HTTP_PORT) {
1640
1991
  const logger = getLogger();
1641
1992
  const binaryPath = getC8RunBinaryPath(config);
1642
1993
  const logDir = join(dirname(binaryPath), 'log');
@@ -1647,6 +1998,7 @@ async function startC8Run(config, debug = false, startArgs = []) {
1647
1998
 
1648
1999
  const markerFile = join(config.cacheDir, ACTIVE_MARKER_FILE);
1649
2000
  const versionFile = join(config.cacheDir, VERSION_MARKER_FILE);
2001
+ const portFile = join(config.cacheDir, PORT_MARKER_FILE);
1650
2002
 
1651
2003
  if (existsSync(markerFile)) {
1652
2004
  // Check whether actual cluster processes are still alive.
@@ -1669,6 +2021,7 @@ async function startC8Run(config, debug = false, startArgs = []) {
1669
2021
  logger.warn('Found stale cluster marker (no running processes detected). Cleaning up.');
1670
2022
  if (existsSync(markerFile)) rmSync(markerFile);
1671
2023
  if (existsSync(versionFile)) rmSync(versionFile);
2024
+ rmSync(portFile, { force: true });
1672
2025
  } else if (hasRunningClusterPidfiles(config.cacheDir)) {
1673
2026
  // No active marker, but a live process is still tracked — typically an
1674
2027
  // orphan recorded only in the durable cache-root PID record after its
@@ -1689,16 +2042,37 @@ async function startC8Run(config, debug = false, startArgs = []) {
1689
2042
 
1690
2043
  logger.info('Starting Camunda 8 local cluster...');
1691
2044
 
2045
+ // Persist the chosen port BEFORE spawning c8run. If c8ctl is interrupted
2046
+ // while the launcher is still running (SIGINT/SIGTERM, crash), c8run's
2047
+ // `.process` pidfiles can remain live without the success/failure writes
2048
+ // below ever running — and `cluster status` reads the recorded port whenever
2049
+ // tracked processes survive. Without this early write, recovery status would
2050
+ // advertise the default port for a cluster actually serving on the custom
2051
+ // one.
2052
+ writeFileSync(portFile, String(port));
2053
+
2054
+ // c8run passes its environment to every Java process it launches. An
2055
+ // inherited SERVER_PORT would therefore move the bundled Connectors runtime
2056
+ // onto the Camunda port as well (port clash) — use --port instead. On Windows
2057
+ // the variable name is case-insensitive, so the exclusion must be too.
2058
+ const launchEnv = buildC8RunLaunchEnv(resolveLocalStoreEnv(process.env, process.cwd()));
1692
2059
  const proc = spawn(binaryPath, ['start', ...startArgs], {
1693
2060
  stdio: ['ignore', 'pipe', 'pipe'],
1694
2061
  cwd: dirname(binaryPath),
1695
- env: { ...resolveLocalStoreEnv(process.env, process.cwd()), C8RUN_CLI_NAME },
2062
+ env: { ...launchEnv, C8RUN_CLI_NAME },
1696
2063
  });
1697
2064
 
1698
2065
  if (typeof proc.pid !== 'number') {
2066
+ // spawn() reports this failure via an async 'error' event; without a
2067
+ // listener it would crash the process while the hints are flushed below.
2068
+ proc.on('error', (err) => logger.error(`Failed to spawn c8run: ${err.message}`));
2069
+ if (!hasRunningClusterPidfiles(config.cacheDir)) {
2070
+ rmSync(portFile, { force: true });
2071
+ }
1699
2072
  logger.error('Failed to start cluster process: no PID received from c8run.');
1700
2073
  logger.error(`Check logs in: ${logDir}`);
1701
2074
  logger.info(`Print logs with: cat "${logDir}"/*.log`, { essential: true });
2075
+ await flushStartHints(config);
1702
2076
  process.exit(1);
1703
2077
  }
1704
2078
 
@@ -1724,34 +2098,53 @@ async function startC8Run(config, debug = false, startArgs = []) {
1724
2098
  let exitCode = null;
1725
2099
  let exitSignal = null;
1726
2100
 
1727
- await new Promise((resolve, reject) => {
1728
- proc.on('error', (err) => {
1729
- reject(new Error(`Failed to spawn c8run: ${err.message}`));
1730
- });
1731
- proc.on('close', (code, signal) => {
1732
- exitCode = code;
1733
- exitSignal = signal;
1734
- resolve();
2101
+ try {
2102
+ await new Promise((resolve, reject) => {
2103
+ proc.on('error', (err) => {
2104
+ reject(new Error(`Failed to spawn c8run: ${err.message}`));
2105
+ });
2106
+ proc.on('close', (code, signal) => {
2107
+ exitCode = code;
2108
+ exitSignal = signal;
2109
+ resolve();
2110
+ });
1735
2111
  });
1736
- });
2112
+ } catch (error) {
2113
+ if (!hasRunningClusterPidfiles(config.cacheDir)) {
2114
+ rmSync(portFile, { force: true });
2115
+ }
2116
+ throw error;
2117
+ }
1737
2118
 
1738
2119
  if (exitCode !== 0) {
1739
2120
  // A failed tenant probe leaves healthy engines alive; preserve their identity
1740
2121
  // for stop/status even if the installation directory is subsequently replaced.
1741
2122
  try {
1742
2123
  recordRunningClusterPids(config, { skipEmpty: true, startupFailed: true });
2124
+ // Persist the port for the survivors too: the success-only marker write
2125
+ // below never runs on this path, so without it a failed custom-port
2126
+ // start would leave status reporting the default port for processes
2127
+ // that actually serve on the custom one.
2128
+ writeFileSync(portFile, String(port));
1743
2129
  } catch (error) {
1744
2130
  logger.warn(`Could not record surviving cluster processes: ${formatErrorWithCause(error)}. Use "c8ctl cluster stop" while the installation is still present.`);
1745
2131
  }
2132
+ if (!hasRunningClusterPidfiles(config.cacheDir)) {
2133
+ rmSync(portFile, { force: true });
2134
+ }
1746
2135
  if (startupOutput.trim()) {
1747
2136
  logger.error(`c8run output:\n${startupOutput.trim()}`);
1748
2137
  }
1749
2138
  if (startArgs.length > 0 && /flag provided but not defined: -physical-tenants/.test(startupOutput)) {
1750
2139
  logger.error('This cached c8run build lacks --physical-tenants. Install a Camunda 8.10+ build containing physical-tenant CLI support with "c8ctl cluster install 8.10".');
1751
2140
  }
2141
+ if (/flag provided but not defined: -port\b/.test(startupOutput)) {
2142
+ logger.error('This cached c8run build does not support --port. Install a newer Camunda 8 Run build (for example "c8ctl cluster install 8.10") or start without --port.');
2143
+ }
1752
2144
  logger.error(
1753
2145
  `c8run start exited with code ${exitCode ?? 'unknown'}${exitSignal ? ` (signal: ${exitSignal})` : ''}. Cluster will not be marked as running.`,
1754
2146
  );
2147
+ await flushStartHints(config);
1755
2148
  process.exit(typeof exitCode === 'number' && exitCode > 0 ? exitCode : 1);
1756
2149
  }
1757
2150
 
@@ -1784,15 +2177,23 @@ async function startC8Run(config, debug = false, startArgs = []) {
1784
2177
  }
1785
2178
  writeFileSync(markerFile, 'running');
1786
2179
  writeFileSync(versionFile, config.version);
1787
- printSummary(startupOutput, config.version);
2180
+ writeFileSync(portFile, String(port));
2181
+ printSummary(startupOutput, config.version, port);
1788
2182
  } else {
1789
2183
  // Readiness can fail even after c8run exits successfully. Retain the same
1790
2184
  // recovery handle as a nonzero launcher exit before reporting failure.
1791
2185
  try {
1792
2186
  recordRunningClusterPids(config, { skipEmpty: true, startupFailed: true });
2187
+ // Persist the port for the survivors too (same reason as the nonzero
2188
+ // launcher exit path above): without it, status would report the
2189
+ // default port for processes serving on the custom one.
2190
+ writeFileSync(portFile, String(port));
1793
2191
  } catch (error) {
1794
2192
  logger.warn(`Could not record surviving cluster processes: ${formatErrorWithCause(error)}. Use "c8ctl cluster stop" while the installation is still present.`);
1795
2193
  }
2194
+ if (!hasRunningClusterPidfiles(config.cacheDir)) {
2195
+ rmSync(portFile, { force: true });
2196
+ }
1796
2197
  logger.error(
1797
2198
  'Cluster failed to start within timeout.',
1798
2199
  );
@@ -2363,8 +2764,11 @@ export async function stopC8Run(config, debug = false) {
2363
2764
 
2364
2765
  if (!markerExists && !clusterAppearsRunning) {
2365
2766
  // Nothing live to stop. Retire any stale record left by a crash/kill so its
2366
- // dead PIDs cannot later be mistaken for this cluster (#560).
2767
+ // dead PIDs cannot later be mistaken for this cluster (#560). No process is
2768
+ // serving, so the port record is stale too — drop it, otherwise a later
2769
+ // status would keep advertising the old custom port for a stopped cluster.
2367
2770
  clearStaleRunningClusterRecord(config.cacheDir);
2771
+ rmSync(join(config.cacheDir, PORT_MARKER_FILE), { force: true });
2368
2772
  logger.warn(
2369
2773
  'No cluster is currently running.',
2370
2774
  );
@@ -2386,6 +2790,7 @@ export async function stopC8Run(config, debug = false) {
2386
2790
  if (existsSync(markerFile)) {
2387
2791
  rmSync(markerFile);
2388
2792
  }
2793
+ rmSync(join(config.cacheDir, PORT_MARKER_FILE), { force: true });
2389
2794
  clearRunningClusterRecord(config.cacheDir);
2390
2795
  return staleVersion;
2391
2796
  }
@@ -2551,6 +2956,17 @@ export async function stopC8Run(config, debug = false) {
2551
2956
  );
2552
2957
  }
2553
2958
 
2959
+ // The port record describes the cluster that was just stopped. Only drop it
2960
+ // once NOTHING still tracks a live process — neither the durable PID record
2961
+ // nor c8run's own `.process` pidfiles. `remainingPids` alone misses a process
2962
+ // tracked only by a pidfile (e.g. one the durable record never captured, or
2963
+ // whose record was already cleared), so gating on it would delete the port
2964
+ // while that survivor still serves — and a later `cluster status` would
2965
+ // advertise the default port for a custom-port cluster.
2966
+ if (!hasRunningClusterPidfiles(config.cacheDir)) {
2967
+ rmSync(join(config.cacheDir, PORT_MARKER_FILE), { force: true });
2968
+ }
2969
+
2554
2970
  if (attempted === 0 && !hadSuccessfulStop) {
2555
2971
  // ...but only when there is nothing left to reap. If a recorded process is
2556
2972
  // still alive (e.g. reaping hit EPERM), the incomplete-stop diagnostic
@@ -2714,6 +3130,32 @@ function resolveLocalStoreEnv(env, cwd) {
2714
3130
  return resolvedEnv;
2715
3131
  }
2716
3132
 
3133
+ /**
3134
+ * Build the environment handed to the c8run child process. c8run forwards its
3135
+ * environment to every Java process it launches, so an inherited SERVER_PORT
3136
+ * would also move the bundled Connectors runtime onto the Camunda port (a port
3137
+ * clash) — strip it and pass the port via --port instead.
3138
+ *
3139
+ * On Windows environment-variable names are case-insensitive, so the exclusion
3140
+ * must match case-insensitively there: an inherited `Server_Port` or
3141
+ * `server_port` is the same variable as `SERVER_PORT` and must be removed too.
3142
+ * Elsewhere names are case-sensitive, so only the exact `SERVER_PORT` is dropped
3143
+ * (a distinct lowercase `server_port` is a different variable and is left alone).
3144
+ *
3145
+ * @param {Record<string, string | undefined>} env
3146
+ * @param {string} [platform]
3147
+ * @returns {Record<string, string | undefined>}
3148
+ */
3149
+ export function buildC8RunLaunchEnv(env, platform = osPlatform()) {
3150
+ if (platform === 'win32') {
3151
+ return Object.fromEntries(
3152
+ Object.entries(env).filter(([name]) => name.toUpperCase() !== 'SERVER_PORT'),
3153
+ );
3154
+ }
3155
+ const { SERVER_PORT: _ignoredServerPort, ...launchEnv } = env;
3156
+ return launchEnv;
3157
+ }
3158
+
2717
3159
  /**
2718
3160
  * True when a cluster is currently running, returning its version. Requires
2719
3161
  * both marker files plus a live pidfile — a stale marker with no live
@@ -2860,13 +3302,28 @@ async function runClusterLocalCommand(
2860
3302
  // Status
2861
3303
  // ---------------------------------------------------------------------------
2862
3304
 
2863
- const CLUSTER_URLS = {
2864
- operate: 'http://localhost:8080/operate',
2865
- tasklist: 'http://localhost:8080/tasklist',
2866
- zeebeGrpc: 'localhost:26500',
2867
- zeebeRest: 'http://localhost:8080/v2/',
2868
- health: 'http://localhost:9600/actuator/health',
2869
- };
3305
+ /**
3306
+ * Endpoints of the local cluster. `--port` moves only c8run's main HTTP port;
3307
+ * gRPC (26500) and the management/health port (9600) stay fixed.
3308
+ */
3309
+ export function clusterUrls(port = DEFAULT_HTTP_PORT) {
3310
+ return {
3311
+ operate: `http://localhost:${port}/operate`,
3312
+ tasklist: `http://localhost:${port}/tasklist`,
3313
+ zeebeGrpc: 'localhost:26500',
3314
+ zeebeRest: `http://localhost:${port}/v2/`,
3315
+ health: 'http://localhost:9600/actuator/health',
3316
+ };
3317
+ }
3318
+
3319
+ /** HTTP port recorded by the latest start attempt, or the c8run default. */
3320
+ export function readClusterPort(cacheDir) {
3321
+ const portFile = join(cacheDir, PORT_MARKER_FILE);
3322
+ if (!existsSync(portFile)) return DEFAULT_HTTP_PORT;
3323
+ const raw = readFileSync(portFile, 'utf-8').trim();
3324
+ const port = /^\d+$/.test(raw) ? Number(raw) : NaN;
3325
+ return port >= 1 && port <= 65535 ? port : DEFAULT_HTTP_PORT;
3326
+ }
2870
3327
 
2871
3328
  export async function clusterStatus(cacheDir) {
2872
3329
  const logger = getLogger();
@@ -2879,6 +3336,10 @@ export async function clusterStatus(cacheDir) {
2879
3336
  // install dir was replaced/removed, orphaning it (#560). Detect it so status
2880
3337
  // never reports "stopped" while a tracked cluster process is still alive.
2881
3338
  const processesRunning = hasRunningClusterPidfiles(cacheDir);
3339
+ // The port is persisted before c8run starts and may be the only surviving
3340
+ // endpoint record after an interrupted launch. Trust it whenever present;
3341
+ // readClusterPort falls back to the c8run default when it is absent or invalid.
3342
+ const CLUSTER_URLS = clusterUrls(readClusterPort(cacheDir));
2882
3343
  const markerVersion = markerExists && existsSync(versionFile)
2883
3344
  ? readFileSync(versionFile, 'utf-8').trim() || null
2884
3345
  : null;
@@ -3142,7 +3603,10 @@ export async function deleteVersion(cacheDir, versionSpec) {
3142
3603
 
3143
3604
  const config = { cacheDir, version: resolvedVersion };
3144
3605
 
3145
- if (!isC8RunInstalled(config)) {
3606
+ // Guard on the install dir, not on the binary: the dir can survive
3607
+ // without its launcher (partial/corrupt install), and delete should
3608
+ // still remove what is left rather than report the version unremovable.
3609
+ if (!existsSync(join(cacheDir, `c8run-${resolvedVersion}`))) {
3146
3610
  logger.warn(`Version ${versionSpec} is not installed locally.`);
3147
3611
  return;
3148
3612
  }
@@ -3186,48 +3650,19 @@ export async function purgeClusterData(cacheDir, versionSpec) {
3186
3650
  process.exit(1);
3187
3651
  }
3188
3652
 
3189
- const config = { cacheDir, version: resolvedVersion };
3190
3653
  const installDir = join(cacheDir, `c8run-${resolvedVersion}`);
3191
3654
  if (!existsSync(installDir)) {
3192
3655
  logger.error(`Version ${resolvedVersion} is not installed locally.`);
3193
3656
  process.exit(1);
3194
3657
  }
3195
3658
 
3196
- // Runtime data normally sits next to the c8run binary. If the binary itself
3197
- // is missing but the install dir survives — a partial/corrupt install, or the
3198
- // orphan case where the binary was removed out from under a running cluster
3199
- // (#560) — fall back to scanning the install dir and its immediate subdirs so
3200
- // leftover data is still purged instead of being silently left behind.
3201
- const binaryPath = findC8RunBinaryPath(config);
3202
- const dataRoots = binaryPath
3203
- ? [dirname(binaryPath)]
3204
- : [
3205
- installDir,
3206
- ...readdirSync(installDir, { withFileTypes: true })
3207
- .filter((entry) => entry.isDirectory())
3208
- .map((entry) => join(installDir, entry.name)),
3209
- ];
3210
-
3659
+ // Not only beside the launcher that would run: an older build of a rolling
3660
+ // install, or an install that lost its launcher, can hold data too, and
3661
+ // `stable` refuses to replace an install while any of it is left.
3211
3662
  const deleted = [];
3212
- for (const dataRoot of dataRoots) {
3213
- // Delete camunda-data (history data + application state)
3214
- const camundaDataDir = join(dataRoot, 'camunda-data');
3215
- if (existsSync(camundaDataDir)) {
3216
- rmSync(camundaDataDir, { recursive: true });
3217
- deleted.push('camunda-data');
3218
- }
3219
-
3220
- // Delete Zeebe journal data inside camunda-zeebe-* subdirectory
3221
- if (existsSync(dataRoot)) {
3222
- for (const entry of readdirSync(dataRoot, { withFileTypes: true })) {
3223
- if (!entry.isDirectory() || !entry.name.startsWith('camunda-zeebe-')) continue;
3224
- const dataDir = join(dataRoot, entry.name, 'data');
3225
- if (existsSync(dataDir)) {
3226
- rmSync(dataDir, { recursive: true });
3227
- deleted.push(join(entry.name, 'data'));
3228
- }
3229
- }
3230
- }
3663
+ for (const dataDir of findClusterDataDirs(installDir)) {
3664
+ rmSync(dataDir, { recursive: true });
3665
+ deleted.push(relative(installDir, dataDir));
3231
3666
  }
3232
3667
 
3233
3668
  if (deleted.length > 0) {
@@ -3250,6 +3685,164 @@ export async function purgeClusterData(cacheDir, versionSpec) {
3250
3685
 
3251
3686
  const LOG_FILES = ['camunda.log', 'connectors.log'];
3252
3687
 
3688
+ // Like `tail -f`: show the last lines of each file, then follow appends.
3689
+ const FOLLOW_INITIAL_LINES = 10;
3690
+ // Logs can be large, so the initial lines are found by scanning back in blocks.
3691
+ const TAIL_BLOCK_BYTES = 64 * 1024;
3692
+ const NEWLINE = 0x0a;
3693
+
3694
+ function readRange(file, start, end) {
3695
+ const fd = openSync(file, 'r');
3696
+ try {
3697
+ const buffer = Buffer.alloc(end - start);
3698
+ const bytesRead = readSync(fd, buffer, 0, buffer.length, start);
3699
+ return buffer.subarray(0, bytesRead);
3700
+ } finally {
3701
+ closeSync(fd);
3702
+ }
3703
+ }
3704
+
3705
+ /**
3706
+ * Byte offset at which the last `count` lines of `file` start. Scans back
3707
+ * from the end until enough newlines are found, so a single entry longer
3708
+ * than any fixed window is still shown in full. The offset is always at a
3709
+ * line start, so decoding from it never splits a UTF-8 character. Also
3710
+ * returns the identity of the scanned file, to detect a later replacement.
3711
+ */
3712
+ function tailStart(file, count) {
3713
+ const fd = openSync(file, 'r');
3714
+ try {
3715
+ const stats = fstatSync(fd, { bigint: true });
3716
+ const id = fileIdentity(stats);
3717
+ const size = Number(stats.size);
3718
+ const buffer = Buffer.alloc(TAIL_BLOCK_BYTES);
3719
+ let newlines = 0;
3720
+ for (let end = size; end > 0;) {
3721
+ const start = Math.max(0, end - buffer.length);
3722
+ const bytesRead = readSync(fd, buffer, 0, end - start, start);
3723
+ for (let i = bytesRead - 1; i >= 0; i--) {
3724
+ // A trailing newline ends the last line rather than starting a new one.
3725
+ if (buffer[i] !== NEWLINE || start + i === size - 1) continue;
3726
+ if (++newlines === count) return { offset: start + i + 1, id };
3727
+ }
3728
+ end = start;
3729
+ }
3730
+ return { offset: 0, id };
3731
+ } finally {
3732
+ closeSync(fd);
3733
+ }
3734
+ }
3735
+
3736
+ const isMissingFile = error => error?.code === 'ENOENT';
3737
+
3738
+ const fileIdentity = stats => `${stats.dev}:${stats.ino}`;
3739
+
3740
+ /**
3741
+ * Follow log files without `tail`, which Windows does not ship. Prints the
3742
+ * last lines of each file (with `==> file <==` headers when there are several,
3743
+ * as `tail` does), then polls for appended bytes until `signal` aborts.
3744
+ * A file that shrinks or is replaced (truncated or rotated) is re-read from the start.
3745
+ */
3746
+ export async function followLogFiles(files, {
3747
+ signal,
3748
+ write = chunk => process.stdout.write(chunk),
3749
+ intervalMs = 500,
3750
+ } = {}) {
3751
+ const multiple = files.length > 1;
3752
+ let current = null;
3753
+ const emit = (file, text) => {
3754
+ if (multiple && current !== file) {
3755
+ write(`${current === null ? '' : '\n'}==> ${file} <==\n`);
3756
+ current = file;
3757
+ }
3758
+ if (text) write(text);
3759
+ };
3760
+
3761
+ // Reads whatever was appended since the last read. A file can vanish at
3762
+ // any point while it is rotated, so a missing file just yields nothing
3763
+ // and is picked up again on a later poll.
3764
+ const readAppended = (file, entry) => {
3765
+ try {
3766
+ const stats = statSync(file, { bigint: true });
3767
+ const size = Number(stats.size);
3768
+ const id = fileIdentity(stats);
3769
+ // A replaced file can be as large as the one it rotated out.
3770
+ const replaced = entry.id !== undefined && entry.id !== id;
3771
+ entry.id = id;
3772
+ if (replaced || size < entry.offset) {
3773
+ entry.offset = 0;
3774
+ entry.decoder = new StringDecoder('utf8');
3775
+ }
3776
+ if (size === entry.offset) return '';
3777
+ const chunk = readRange(file, entry.offset, size);
3778
+ entry.offset += chunk.length;
3779
+ return entry.decoder.write(chunk);
3780
+ } catch (error) {
3781
+ if (isMissingFile(error)) return '';
3782
+ throw error;
3783
+ }
3784
+ };
3785
+
3786
+ const state = new Map();
3787
+ for (const file of files) {
3788
+ let start = { offset: 0, id: undefined };
3789
+ try {
3790
+ start = tailStart(file, FOLLOW_INITIAL_LINES);
3791
+ } catch (error) {
3792
+ if (!isMissingFile(error)) throw error;
3793
+ }
3794
+ const entry = { ...start, decoder: new StringDecoder('utf8') };
3795
+ state.set(file, entry);
3796
+ // Emitted even when empty, so every file gets its header up front.
3797
+ emit(file, readAppended(file, entry));
3798
+ }
3799
+
3800
+ const poll = () => {
3801
+ for (const file of files) {
3802
+ const text = readAppended(file, state.get(file));
3803
+ if (text) emit(file, text);
3804
+ }
3805
+ };
3806
+
3807
+ await new Promise((resolve, reject) => {
3808
+ let timer;
3809
+ const settle = error => {
3810
+ clearInterval(timer);
3811
+ signal?.removeEventListener('abort', stop);
3812
+ if (error) reject(error);
3813
+ else resolve();
3814
+ };
3815
+ // An unexpected read error ends following instead of escaping the timer.
3816
+ const tick = () => {
3817
+ try {
3818
+ poll();
3819
+ return true;
3820
+ } catch (error) {
3821
+ settle(error);
3822
+ return false;
3823
+ }
3824
+ };
3825
+ function stop() {
3826
+ if (tick()) settle();
3827
+ }
3828
+ timer = setInterval(tick, intervalMs);
3829
+ if (signal?.aborted) stop();
3830
+ else signal?.addEventListener('abort', stop, { once: true });
3831
+ });
3832
+ }
3833
+
3834
+ /** Follows log files until Ctrl+C, which ends the command cleanly. */
3835
+ export async function followLogsUntilInterrupted(files, options = {}) {
3836
+ const controller = new AbortController();
3837
+ const sigintHandler = () => controller.abort();
3838
+ process.on('SIGINT', sigintHandler);
3839
+ try {
3840
+ await followLogFiles(files, { ...options, signal: controller.signal });
3841
+ } finally {
3842
+ process.removeListener('SIGINT', sigintHandler);
3843
+ }
3844
+ }
3845
+
3253
3846
  export async function streamLogs(cacheDir) {
3254
3847
  const logger = getLogger();
3255
3848
  const markerFile = join(cacheDir, ACTIVE_MARKER_FILE);
@@ -3295,6 +3888,12 @@ export async function streamLogs(cacheDir) {
3295
3888
  logger.info(`Streaming logs from ${logDir} (Ctrl+C to stop)...`);
3296
3889
  logger.info('');
3297
3890
 
3891
+ if (osPlatform() === 'win32') {
3892
+ // Windows has no `tail`, so follow the files in-process.
3893
+ await followLogsUntilInterrupted(existingLogs);
3894
+ return;
3895
+ }
3896
+
3298
3897
  // Use tail -f to follow all log files
3299
3898
  const tailArgs = ['-f', ...existingLogs];
3300
3899
  const tail = spawn('tail', tailArgs, { stdio: 'inherit' });
@@ -3343,6 +3942,15 @@ export function parsePluginArgs(args) {
3343
3942
  continue;
3344
3943
  }
3345
3944
 
3945
+ if (arg === '--port' || arg.startsWith('--port=')) {
3946
+ const value = arg === '--port' ? args[i + 1] : arg.slice('--port='.length);
3947
+ result.port = parsePort(value);
3948
+ result.startArgs ??= [];
3949
+ result.startArgs.push('--port', String(result.port));
3950
+ i += arg === '--port' ? 2 : 1;
3951
+ continue;
3952
+ }
3953
+
3346
3954
  if (arg === '--c8-version') {
3347
3955
  const next = args[i + 1];
3348
3956
  if (!next || next.startsWith('-')) {
@@ -3395,12 +4003,26 @@ export function parsePluginArgs(args) {
3395
4003
  i += 1;
3396
4004
  }
3397
4005
 
4006
+ if (result.port !== undefined && result.subcommand !== 'start') {
4007
+ throw new Error('--port can only be used with the start subcommand');
4008
+ }
3398
4009
  if (result.startArgs && result.subcommand !== 'start') {
3399
4010
  throw new Error('--physical-tenants can only be used with the start subcommand');
3400
4011
  }
3401
4012
  return result;
3402
4013
  }
3403
4014
 
4015
+ function parsePort(value) {
4016
+ if (!value || value.startsWith('-')) {
4017
+ throw new Error('Missing value for --port. Provide the HTTP port, for example: c8ctl cluster start --port 9091');
4018
+ }
4019
+ const port = /^\d+$/.test(value) ? Number(value) : NaN;
4020
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
4021
+ throw new Error(`Invalid value for --port: "${value}". Use an integer between 1 and 65535.`);
4022
+ }
4023
+ return port;
4024
+ }
4025
+
3404
4026
  // ---------------------------------------------------------------------------
3405
4027
  // Plugin commands export
3406
4028
  // ---------------------------------------------------------------------------
@@ -3588,6 +4210,10 @@ export const commands = {
3588
4210
  process.exit(1);
3589
4211
  }
3590
4212
 
4213
+ if (parsed.subcommand === 'delete' || parsed.subcommand === 'purge') {
4214
+ sweepStaleInstallDirs(getCacheDir());
4215
+ }
4216
+
3591
4217
  if (parsed.subcommand === 'delete') {
3592
4218
  try {
3593
4219
  await deleteVersion(getCacheDir(), parsed.version);
@@ -3637,11 +4263,6 @@ export const commands = {
3637
4263
  logger.info(`Resolved alias "${versionSpec}" → ${version}`);
3638
4264
  }
3639
4265
 
3640
- // For start with a named alias, check in the background whether the
3641
- // remote resolves to a different (newer) version and hint if so.
3642
- if (isStart && isVersionAlias(versionSpec)) {
3643
- checkBackgroundAliasFreshness(versionSpec, version);
3644
- }
3645
4266
  const rolling = isRollingVersion(versionSpec);
3646
4267
  const config = {
3647
4268
  cacheDir: theCacheDir,
@@ -3653,14 +4274,23 @@ export const commands = {
3653
4274
  checkForUpdateHint: parsed.subcommand === 'start' && rolling,
3654
4275
  // --verbose: detailed HTTP diagnostics for the c8run download
3655
4276
  verbose: ctx?.verbose === true,
4277
+ // stable: reject (and replace) an install whose build is a prerelease
4278
+ requireGA: versionSpec === 'stable',
3656
4279
  };
3657
4280
 
4281
+ // For start with a named alias, check in the background whether the
4282
+ // remote resolves to a different (newer) version and hint if so.
4283
+ if (isStart && isVersionAlias(versionSpec)) {
4284
+ config._aliasHintPromise = checkBackgroundAliasFreshness(versionSpec, version, theCacheDir);
4285
+ }
4286
+
3658
4287
  if (parsed.subcommand === 'start') {
3659
4288
  try {
3660
4289
  await ensureC8RunInstalled(config);
3661
- await startC8Run(config, parsed.debug, parsed.startArgs);
4290
+ await startC8Run(config, parsed.debug, parsed.startArgs, parsed.port);
3662
4291
  } catch (error) {
3663
4292
  logger.error(`Failed to start cluster: ${formatErrorWithCause(error)}`);
4293
+ await flushStartHints(config);
3664
4294
  process.exit(1);
3665
4295
  }
3666
4296
  } else if (parsed.subcommand === 'stop') {