@nice-code/commander 0.111.0 → 0.113.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -278,33 +278,88 @@ var CommanderAuth = class {
278
278
  //#region src/daemon/configWatch.ts
279
279
  const DEBOUNCE_MS = 150;
280
280
  const RECONCILE_MS = 5e3;
281
+ /**
282
+ * `fs.watch` holds a descriptor per file on some platforms, and a config can import its way into
283
+ * a whole source tree. Files past this many are still caught by the stat-reconcile pass.
284
+ */
285
+ const MAX_FS_WATCHERS = 128;
281
286
  function watchCommanderConfig(options) {
282
287
  let closed = false;
283
288
  let timer = null;
284
289
  let inFlight = null;
285
290
  let queued = false;
286
291
  const mtimes = /* @__PURE__ */ new Map();
287
- const watchers = [];
292
+ const watchers = /* @__PURE__ */ new Map();
293
+ let files = new Set([options.configPath, ...options.watchFiles]);
288
294
  const rememberMtimes = async () => {
289
- for (const file of [options.configPath, ...options.watchFiles]) try {
295
+ for (const file of files) try {
290
296
  mtimes.set(file, (await (0, node_fs_promises.stat)(file)).mtimeMs);
291
297
  } catch {
292
298
  mtimes.delete(file);
293
299
  }
294
300
  };
301
+ /**
302
+ * Stamp the files no pass has stamped yet. One edited after the load that read it began stays
303
+ * unstamped, so the reconcile pass reloads it — that load may have read it before the edit.
304
+ */
305
+ const rememberDiscovered = async (loadStartedAt) => {
306
+ for (const file of files) {
307
+ if (mtimes.has(file)) continue;
308
+ try {
309
+ const { mtimeMs } = await (0, node_fs_promises.stat)(file);
310
+ if (mtimeMs < loadStartedAt) mtimes.set(file, mtimeMs);
311
+ } catch {}
312
+ }
313
+ };
314
+ /** Move the watchers onto `next`. Only the difference is touched: a kept file keeps its watcher. */
315
+ const watchFiles = (next) => {
316
+ files = next;
317
+ for (const [file, watcher] of watchers) {
318
+ if (files.has(file)) continue;
319
+ watcher.close();
320
+ watchers.delete(file);
321
+ mtimes.delete(file);
322
+ }
323
+ for (const file of files) {
324
+ if (watchers.has(file) || watchers.size >= MAX_FS_WATCHERS) continue;
325
+ try {
326
+ const watcher = (0, node_fs.watch)(file, { persistent: false }, trigger);
327
+ watcher.on("error", () => {});
328
+ watchers.set(file, watcher);
329
+ } catch {}
330
+ }
331
+ };
295
332
  const runAttempts = async () => {
296
333
  do {
297
334
  queued = false;
298
335
  await rememberMtimes();
336
+ const loadStartedAt = Date.now();
299
337
  try {
300
338
  const file = await require_cli.loadCommanderConfigFile(options.configPath);
301
339
  const { resolved, errors } = require_cli.validateCommanderConfig(file.raw, {
302
340
  configPath: file.configPath,
303
341
  configDir: file.configDir
304
342
  });
305
- if (resolved != null) options.onConfig(resolved);
306
- else options.onError(errors);
343
+ if (closed) return;
344
+ if (resolved != null) {
345
+ watchFiles(new Set([
346
+ options.configPath,
347
+ ...resolved.watchFiles,
348
+ ...file.loadedFiles
349
+ ]));
350
+ await rememberDiscovered(loadStartedAt);
351
+ options.onConfig(resolved);
352
+ } else {
353
+ watchFiles(new Set([...files, ...file.loadedFiles]));
354
+ await rememberDiscovered(loadStartedAt);
355
+ options.onError(errors);
356
+ }
307
357
  } catch (error) {
358
+ if (closed) return;
359
+ if (error instanceof require_cli.CommanderConfigLoadError) {
360
+ watchFiles(new Set([...files, ...error.loadedFiles]));
361
+ await rememberDiscovered(loadStartedAt);
362
+ }
308
363
  options.onError([error.message]);
309
364
  }
310
365
  } while (queued && !closed);
@@ -330,15 +385,11 @@ function watchCommanderConfig(options) {
330
385
  }, DEBOUNCE_MS);
331
386
  timer.unref();
332
387
  };
333
- for (const file of [options.configPath, ...options.watchFiles]) try {
334
- const watcher = (0, node_fs.watch)(file, { persistent: false }, trigger);
335
- watcher.on("error", () => {});
336
- watchers.push(watcher);
337
- } catch {}
338
- rememberMtimes();
388
+ watchFiles(files);
389
+ rememberDiscovered(options.loadedAt);
339
390
  const reconcile = setInterval(() => {
340
391
  (async () => {
341
- for (const file of [options.configPath, ...options.watchFiles]) {
392
+ for (const file of files) {
342
393
  let mtime = null;
343
394
  try {
344
395
  mtime = (await (0, node_fs_promises.stat)(file)).mtimeMs;
@@ -358,7 +409,7 @@ function watchCommanderConfig(options) {
358
409
  closed = true;
359
410
  if (timer != null) clearTimeout(timer);
360
411
  clearInterval(reconcile);
361
- for (const watcher of watchers) watcher.close();
412
+ for (const watcher of watchers.values()) watcher.close();
362
413
  },
363
414
  reloadNow: attempt
364
415
  };
@@ -662,12 +713,18 @@ function createControlPlane(options) {
662
713
  },
663
714
  stop: async ({ ids, withDependencies: alsoDependencies }) => {
664
715
  if (alsoDependencies !== true) return supervisor.stop(ids);
665
- const live = new Set(supervisor.status().filter((status) => LIVE_STATES.has(status.state)).map((status) => status.id));
666
- const { stop, kept } = require_cli.stopSetWithDependencies(supervisor.config.processes, ids, (id) => live.has(id));
716
+ const statuses = supervisor.status();
717
+ const nodes = statuses.map((status) => ({
718
+ id: status.id,
719
+ dependsOn: status.detail.dependsOn
720
+ }));
721
+ const live = new Set(statuses.filter((status) => LIVE_STATES.has(status.state)).map((status) => status.id));
722
+ const { stop, kept } = require_cli.stopSetWithDependencies(nodes, ids, (id) => live.has(id));
723
+ const neededBy = (id) => nodes.filter((node) => node.id !== id && live.has(node.id) && !stop.includes(node.id)).filter((node) => require_cli.withDependencies(nodes, [node.id]).has(id)).map((node) => node.id);
667
724
  const report = await supervisor.stop(stop);
668
- return kept.length === 0 ? report : {
725
+ return {
669
726
  ...report,
670
- warnings: [...report.warnings, `left running — still needed by other live processes: ${kept.join(", ")}`]
727
+ warnings: [...report.warnings, ...kept.map((id) => `"${id}" left running — still needed by ${neededBy(id).join(", ")}`)]
671
728
  };
672
729
  },
673
730
  restart: async ({ ids, wait, staggerMs, replaceSame, flags }) => {
@@ -1444,10 +1501,10 @@ var CommanderSupervisor = class {
1444
1501
  proc: null,
1445
1502
  envFingerprint: null,
1446
1503
  procFlags: null,
1504
+ procDefinitionHash: null,
1447
1505
  startedAt: null,
1448
1506
  lastStartedAt: this._lastStarts[definition.id] ?? null,
1449
1507
  flags: [],
1450
- stale: false,
1451
1508
  removed: false,
1452
1509
  blockedBy: null,
1453
1510
  blockedOn: null,
@@ -1471,10 +1528,11 @@ var CommanderSupervisor = class {
1471
1528
  _ensureProc(holder, flags = NO_FLAGS) {
1472
1529
  const definition = holder.definition;
1473
1530
  const fingerprint = require_cli.overrideFingerprint(definition, this._envOverrides);
1474
- if (holder.proc != null && (holder.envFingerprint !== fingerprint || !sameFlags(holder.procFlags ?? [], flags.flags)) && !ACTIVE_STATES.has(holder.proc.state)) holder.proc = null;
1531
+ if (holder.proc != null && (holder.procDefinitionHash !== definition.definitionHash || holder.envFingerprint !== fingerprint || !sameFlags(holder.procFlags ?? [], flags.flags)) && !ACTIVE_STATES.has(holder.proc.state)) holder.proc = null;
1475
1532
  if (holder.proc != null) return holder.proc;
1476
1533
  holder.envFingerprint = fingerprint;
1477
1534
  holder.procFlags = flags.flags;
1535
+ holder.procDefinitionHash = definition.definitionHash;
1478
1536
  const proc = (0, _nice_code_process.createNiceProcess)({
1479
1537
  id: definition.id,
1480
1538
  run: require_cli.runWithArgs(definition.run, flags.args),
@@ -1554,6 +1612,14 @@ var CommanderSupervisor = class {
1554
1612
  this._notify(holder.definition.id);
1555
1613
  }
1556
1614
  }
1615
+ /**
1616
+ * `required` is a start-time contract: nothing spawns until each such variable has a value —
1617
+ * an override, a declared default, or this daemon's own environment, which the child inherits.
1618
+ */
1619
+ _requiredRefusal(holder) {
1620
+ const missing = require_cli.missingRequired(holder.definition, this._envOverrides, process.env);
1621
+ return missing.length === 0 ? null : require_cli.requiredRefusal(holder.definition.id, missing, "daemon");
1622
+ }
1557
1623
  _protected() {
1558
1624
  this._protectedPids ??= require_cli.ancestors().then((pids) => new Set(pids));
1559
1625
  return this._protectedPids;
@@ -1754,6 +1820,16 @@ var CommanderSupervisor = class {
1754
1820
  outcome: "failed",
1755
1821
  reason: "supervisor is stopping"
1756
1822
  };
1823
+ const unmet = this._requiredRefusal(holder);
1824
+ if (unmet != null) {
1825
+ holder.startError = unmet;
1826
+ this._notify(id);
1827
+ return {
1828
+ id,
1829
+ outcome: "failed",
1830
+ reason: unmet
1831
+ };
1832
+ }
1757
1833
  const conflict = await this._exclusiveEndpointConflict(holder, replaceSame || holder.definition.replaceSame);
1758
1834
  if (conflict != null) {
1759
1835
  holder.startError = conflict;
@@ -1769,7 +1845,6 @@ var CommanderSupervisor = class {
1769
1845
  try {
1770
1846
  await proc.start();
1771
1847
  this._markStarted(holder);
1772
- holder.stale = false;
1773
1848
  holder.startError = null;
1774
1849
  this._recomputeDegraded();
1775
1850
  this._notify(id);
@@ -1843,6 +1918,16 @@ var CommanderSupervisor = class {
1843
1918
  outcome: "failed",
1844
1919
  reason: "supervisor is stopping"
1845
1920
  };
1921
+ const unmet = this._requiredRefusal(holder);
1922
+ if (unmet != null) {
1923
+ holder.startError = unmet;
1924
+ this._notify(id);
1925
+ return {
1926
+ id,
1927
+ outcome: "failed",
1928
+ reason: unmet
1929
+ };
1930
+ }
1846
1931
  const conflict = await this._exclusiveEndpointConflict(holder, replaceSame || holder.definition.replaceSame);
1847
1932
  if (conflict != null) {
1848
1933
  holder.startError = conflict;
@@ -1856,7 +1941,6 @@ var CommanderSupervisor = class {
1856
1941
  try {
1857
1942
  await proc.start();
1858
1943
  this._markStarted(holder);
1859
- holder.stale = false;
1860
1944
  holder.startError = null;
1861
1945
  this._notify(id);
1862
1946
  } catch (error) {
@@ -2052,9 +2136,13 @@ var CommanderSupervisor = class {
2052
2136
  };
2053
2137
  }
2054
2138
  /**
2055
- * Config reload (last-good already validated): changed definitions of RUNNING processes mark
2056
- * `stale` (never auto-restart); deleted definitions stay addressable as `removed`; idle
2057
- * processes just pick up the new definition on their next start.
2139
+ * Config reload (last-good already validated). Nothing restarts: a RUNNING process whose
2140
+ * definition changed reads `stale` until something restarts it, a deleted definition stays
2141
+ * addressable as `removed`, and an idle process is rebuilt on its next start (`_ensureProc`).
2142
+ *
2143
+ * ⚠ No handle is dropped here, running or idle. A start that is between building its handle
2144
+ * and spawning it would lose the process it is about to own — and a reload that changed nothing
2145
+ * would still wipe every finished run's state and log ring.
2058
2146
  */
2059
2147
  applyConfig(next) {
2060
2148
  this._config = next;
@@ -2067,14 +2155,6 @@ var CommanderSupervisor = class {
2067
2155
  continue;
2068
2156
  }
2069
2157
  holder.removed = false;
2070
- const active = holder.proc != null && ACTIVE_STATES.has(holder.proc.state);
2071
- if (active && holder.definition.definitionHash !== definition.definitionHash) holder.stale = true;
2072
- if (!active) {
2073
- holder.proc = null;
2074
- holder.envFingerprint = null;
2075
- holder.procFlags = null;
2076
- holder.stale = false;
2077
- }
2078
2158
  holder.definition = definition;
2079
2159
  this._notify(definition.id);
2080
2160
  }
@@ -2131,8 +2211,8 @@ var CommanderSupervisor = class {
2131
2211
  recentRuns: holder.recentRuns.map((run) => ({ ...run })),
2132
2212
  restarts: proc?.restarts ?? 0,
2133
2213
  lastExit: proc?.lastExit ?? null,
2134
- stale: holder.stale,
2135
2214
  removed: holder.removed,
2215
+ stale: active && holder.procDefinitionHash !== holder.definition.definitionHash,
2136
2216
  envDrift: active && holder.envFingerprint !== require_cli.overrideFingerprint(holder.definition, this._envOverrides),
2137
2217
  blockedBy: holder.blockedBy,
2138
2218
  startError: active ? null : holder.startError,
@@ -2301,6 +2381,7 @@ async function startCommanderDaemon(argv) {
2301
2381
  const configArg = argValue(argv, "--config");
2302
2382
  if (configArg == null) throw new Error("daemon requires --config <path>");
2303
2383
  const dataDir = argValue(argv, "--data-dir") ?? require_cli.resolveCommanderDataDir();
2384
+ const configLoadedAt = Date.now();
2304
2385
  const file = await require_cli.loadCommanderConfigFile(configArg);
2305
2386
  const { resolved, errors } = require_cli.validateCommanderConfig(file.raw, {
2306
2387
  configPath: file.configPath,
@@ -2549,7 +2630,8 @@ async function startCommanderDaemon(argv) {
2549
2630
  });
2550
2631
  watcher = watchCommanderConfig({
2551
2632
  configPath: resolved.configPath,
2552
- watchFiles: resolved.watchFiles,
2633
+ watchFiles: [...resolved.watchFiles, ...file.loadedFiles],
2634
+ loadedAt: configLoadedAt,
2553
2635
  onConfig: (next) => {
2554
2636
  supervisor.applyConfig(next);
2555
2637
  plane.syncConfig(next);
@@ -2631,4 +2713,4 @@ async function runCommanderDaemon(argv) {
2631
2713
  //#endregion
2632
2714
  exports.runCommanderDaemon = runCommanderDaemon;
2633
2715
 
2634
- //# sourceMappingURL=main-C3BG9bju.cjs.map
2716
+ //# sourceMappingURL=main-CcxTP9yh.cjs.map