@nice-code/commander 0.100.0 → 0.103.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.
package/build/cli.cjs CHANGED
@@ -151,7 +151,7 @@ function validStartStamp(value) {
151
151
  function isInstanceRecord(value) {
152
152
  if (value == null || typeof value !== "object" || Array.isArray(value)) return false;
153
153
  const record = value;
154
- return record.service === "nice-commander" && boundedString(record.instanceId) && boundedInt(record.generation, 0, Number.MAX_SAFE_INTEGER) && boundedInt(record.pid, 1, Number.MAX_SAFE_INTEGER) && boundedInt(record.port, 1, 65535) && boundedString(record.token) && boundedString(record.configKey) && boundedString(record.configRevisionHash) && boundedString(record.configPath) && boundedString(record.packageVersion) && boundedString(record.realmSchemaHash) && validStartStamp(record.startStamp) && record.protocolVersion === 6;
154
+ return record.service === "nice-commander" && boundedString(record.instanceId) && boundedInt(record.generation, 0, Number.MAX_SAFE_INTEGER) && boundedInt(record.pid, 1, Number.MAX_SAFE_INTEGER) && boundedInt(record.port, 1, 65535) && boundedString(record.token) && boundedString(record.configKey) && boundedString(record.configRevisionHash) && boundedString(record.configPath) && boundedString(record.packageVersion) && boundedString(record.realmSchemaHash) && validStartStamp(record.startStamp) && record.protocolVersion === 7;
155
155
  }
156
156
  async function writeInstanceRecord(path, record) {
157
157
  await (0, node_fs_promises.mkdir)((0, node_path.dirname)(path), {
@@ -201,7 +201,7 @@ async function readSkewedInstanceRecord(path, expectedRealmSchemaHash) {
201
201
  if (!boundedInt(record["protocolVersion"], 0, Number.MAX_SAFE_INTEGER)) return null;
202
202
  if (!boundedInt(record["pid"], 1, Number.MAX_SAFE_INTEGER)) return null;
203
203
  if (!boundedInt(record["port"], 1, 65535)) return null;
204
- const sameProtocol = record["protocolVersion"] === 6;
204
+ const sameProtocol = record["protocolVersion"] === 7;
205
205
  const sameRealm = boundedString(record["realmSchemaHash"]) && record["realmSchemaHash"] === expectedRealmSchemaHash;
206
206
  if (sameProtocol && sameRealm) return null;
207
207
  return {
@@ -1029,6 +1029,8 @@ function validateCommanderConfig(raw, anchor) {
1029
1029
  tags[key] = clean;
1030
1030
  }
1031
1031
  if (proc.optIn != null && typeof proc.optIn !== "boolean") errors.push(`${at}.optIn: expected a boolean`);
1032
+ if (proc.replaceSame != null && typeof proc.replaceSame !== "boolean") errors.push(`${at}.replaceSame: expected a boolean`);
1033
+ const replaceSame = proc.replaceSame ?? config.defaults?.replaceSame ?? false;
1032
1034
  const endpoints = [];
1033
1035
  const endpointNames = /* @__PURE__ */ new Set();
1034
1036
  for (const [endpointIndex, endpoint] of (proc.endpoints ?? []).entries()) {
@@ -1116,6 +1118,7 @@ function validateCommanderConfig(raw, anchor) {
1116
1118
  optIn: proc.optIn === true,
1117
1119
  dependsOn,
1118
1120
  endpoints,
1121
+ replaceSame: replaceSame === true,
1119
1122
  ...proc.url != null ? { url: proc.url } : {},
1120
1123
  ...ready != null ? { ready } : {},
1121
1124
  stop,
@@ -24165,6 +24168,7 @@ const commanderStatusRealm = defineRealm({
24165
24168
  removed: t.boolean(),
24166
24169
  envDrift: t.boolean(),
24167
24170
  blockedBy: t.optional(t.string()),
24171
+ startError: t.optional(t.string()),
24168
24172
  degradedBy: t.array(t.string()),
24169
24173
  unreadyReason: t.optional(t.string()),
24170
24174
  capability: t.optional(t.object({
@@ -24178,6 +24182,7 @@ const commanderStatusRealm = defineRealm({
24178
24182
  command: t.string(),
24179
24183
  cwd: t.string(),
24180
24184
  dependsOn: t.array(t.string()),
24185
+ url: t.optional(t.string()),
24181
24186
  ready: t.optional(t.string()),
24182
24187
  timeoutMs: t.optional(t.number()),
24183
24188
  endpoints: t.array(t.object({
@@ -24355,7 +24360,7 @@ var CommanderDaemonBootError = class extends Error {
24355
24360
  * a live dev environment, and an upgrade must never be the thing that kills one.
24356
24361
  */
24357
24362
  async function replaceSkewedDaemon(paths, skewed) {
24358
- const daemonLabel = `the daemon for this config (pid ${skewed.pid}, build ${skewed.packageVersion}, protocol v${skewed.protocolVersion}) predates this CLI (protocol v6${skewed.skew === "realm-schema" ? ", different status schema" : ""})`;
24363
+ const daemonLabel = `the daemon for this config (pid ${skewed.pid}, build ${skewed.packageVersion}, protocol v${skewed.protocolVersion}) predates this CLI (protocol v7${skewed.skew === "realm-schema" ? ", different status schema" : ""})`;
24359
24364
  let liveIds;
24360
24365
  try {
24361
24366
  liveIds = (await (0, _nice_code_process.openProcessLedger)({
@@ -24497,7 +24502,7 @@ function checkPortsReport(value) {
24497
24502
  r.endpoint,
24498
24503
  r.host,
24499
24504
  r.command
24500
- ].every((s) => typeof s === "string") || !Number.isInteger(r.pid) || Number(r.pid) < 1 || !Number.isInteger(r.port) || Number(r.port) < 1 || Number(r.port) > 65535 || !(r.ppid === null || Number.isInteger(r.ppid) && Number(r.ppid) >= 0) || !(r.cwd === null || typeof r.cwd === "string") || ![
24505
+ ].every((s) => typeof s === "string") || !Number.isInteger(r.pid) || Number(r.pid) < 1 || !Number.isInteger(r.port) || Number(r.port) < 1 || Number(r.port) > 65535 || !(r.ppid === null || Number.isInteger(r.ppid) && Number(r.ppid) >= 0) || !(r.cwd === null || typeof r.cwd === "string") || typeof r.stray !== "boolean" || !(r.strayRoot === null || Number.isInteger(r.strayRoot) && Number(r.strayRoot) >= 1) || ![
24501
24506
  r.startStamp,
24502
24507
  r.token,
24503
24508
  r.refusal
@@ -24561,9 +24566,12 @@ function checkStart(value) {
24561
24566
  if (wait != null && typeof wait !== "boolean") return "wait: expected a boolean";
24562
24567
  const staggerMs = record["staggerMs"];
24563
24568
  if (staggerMs != null && (typeof staggerMs !== "number" || staggerMs < 0)) return "staggerMs: expected a non-negative number";
24569
+ const replaceSame = record["replaceSame"];
24570
+ if (replaceSame != null && typeof replaceSame !== "boolean") return "replaceSame: expected a boolean";
24564
24571
  const input = { ids };
24565
24572
  if (wait != null) input.wait = wait;
24566
24573
  if (staggerMs != null) input.staggerMs = staggerMs;
24574
+ if (replaceSame != null) input.replaceSame = replaceSame;
24567
24575
  return input;
24568
24576
  }
24569
24577
  function checkSetEnv(value) {
@@ -24802,7 +24810,7 @@ async function findDaemon(config) {
24802
24810
  async function findSkewedDaemon(config) {
24803
24811
  const skewed = await readSkewedInstanceRecord(commanderStatePaths(resolveCommanderDataDir(), config.configKey).instanceRecordPath, commanderStatusRealm.schemaHash);
24804
24812
  if (skewed == null || !pidAlive$1(skewed.pid)) return null;
24805
- const difference = skewed.skew === "protocol" ? `speaks protocol v${skewed.protocolVersion}; this build speaks v6` : "was started before an upgrade changed the status schema";
24813
+ const difference = skewed.skew === "protocol" ? `speaks protocol v${skewed.protocolVersion}; this build speaks v7` : "was started before an upgrade changed the status schema";
24806
24814
  return {
24807
24815
  message: `the daemon for this config (pid ${skewed.pid}, port ${skewed.port}, build ${skewed.packageVersion}) ${difference} — this CLI (build ${await commanderPackageVersion()}) cannot talk to it. Run \`nice-commander shutdown\` (it stops a daemon from any build), then retry.`,
24808
24816
  pid: skewed.pid,
@@ -24900,7 +24908,7 @@ async function connectDaemon(handle) {
24900
24908
  const payload = await (await runtime.handleActionPayload(request)).waitForResultPayload();
24901
24909
  if (!payload.result.ok) throw new CliExit(EXIT.failure, `action "${action}" rejected by the daemon`);
24902
24910
  const report = parseActionReport(payload.result.output);
24903
- if (report == null) throw new CliExit(EXIT.failure, `the daemon answered "${action}" with something this CLI does not recognise — protocol ${record.protocolVersion} vs 6`);
24911
+ if (report == null) throw new CliExit(EXIT.failure, `the daemon answered "${action}" with something this CLI does not recognise — protocol ${record.protocolVersion} vs 7`);
24904
24912
  return report;
24905
24913
  },
24906
24914
  setEnv: async (input) => {
@@ -24940,6 +24948,18 @@ function stateSymbol(out, state) {
24940
24948
  default: return out.paint("cyan", "▸");
24941
24949
  }
24942
24950
  }
24951
+ /** Where a ready process can be reached: its http endpoints' URLs, else its declared `url`. */
24952
+ function urlsOf(node) {
24953
+ if (node == null) return [];
24954
+ const urls = node.detail.endpoints.flatMap((endpoint) => endpoint.url != null ? [endpoint.url] : []);
24955
+ if (urls.length === 0 && node.detail.url != null) urls.push(node.detail.url);
24956
+ return urls;
24957
+ }
24958
+ /** `✓ web ready → http://localhost:3050` — the address is declared, so the line can carry it. */
24959
+ function reachLine(out, node) {
24960
+ const urls = urlsOf(node);
24961
+ return urls.length === 0 ? "" : ` → ${urls.map((url) => out.paint("cyan", url)).join(" ")}`;
24962
+ }
24943
24963
  /** Stream the transition narrative for the touched ids while an action runs. */
24944
24964
  async function withProgress(client, out, ids, run) {
24945
24965
  if (out.json || ids.size === 0) return run();
@@ -24952,7 +24972,8 @@ async function withProgress(client, out, ids, run) {
24952
24972
  const current = `${proc.state}${proc.blockedBy != null ? ` — ${proc.blockedBy}` : ""}`;
24953
24973
  if (last.get(id) === current) continue;
24954
24974
  last.set(id, current);
24955
- out.print(`${stateSymbol(out, proc.state)} ${out.accent(id, id)} ${current}`);
24975
+ const reach = proc.state === "ready" ? reachLine(out, proc) : "";
24976
+ out.print(`${stateSymbol(out, proc.state)} ${out.accent(id, id)} ${current}${reach}`);
24956
24977
  }
24957
24978
  };
24958
24979
  const off = client.realm.listenToPatches(() => note());
@@ -24971,13 +24992,36 @@ const NARRATED = new Set([
24971
24992
  "succeeded",
24972
24993
  "blocked"
24973
24994
  ]);
24974
- function printReport(out, report) {
24975
- if (out.json) out.printJson(report);
24995
+ /**
24996
+ * `--json` carries the generation's verdict as data: the action outcome per id, plus the state,
24997
+ * pid and endpoints the realm holds for it once the action has settled — so a script can decide
24998
+ * from one object what `status --json` would otherwise have to be asked for next.
24999
+ */
25000
+ function enrichReport(report, state) {
25001
+ return {
25002
+ results: report.results.map((result) => {
25003
+ const node = state.processes[result.id];
25004
+ return {
25005
+ ...result,
25006
+ state: node?.state ?? "unknown",
25007
+ ...node?.pid != null ? { pid: node.pid } : {},
25008
+ ...node?.blockedBy != null ? { blockedBy: node.blockedBy } : {},
25009
+ ...node?.startError != null ? { startError: node.startError } : {},
25010
+ endpoints: node?.detail.endpoints ?? [],
25011
+ urls: urlsOf(node)
25012
+ };
25013
+ }),
25014
+ warnings: report.warnings
25015
+ };
25016
+ }
25017
+ function printReport(out, report, state) {
25018
+ if (out.json) out.printJson(enrichReport(report, state));
24976
25019
  else {
24977
25020
  for (const result of report.results) {
24978
25021
  if (NARRATED.has(result.outcome)) continue;
24979
25022
  const note = result.reason != null ? ` — ${result.reason}` : "";
24980
- out.print(`${stateSymbol(out, result.outcome)} ${out.accent(result.id, result.id)} ${result.outcome}${note}`);
25023
+ const reach = result.outcome === "already-running" ? reachLine(out, state.processes[result.id]) : "";
25024
+ out.print(`${stateSymbol(out, result.outcome)} ${out.accent(result.id, result.id)} ${result.outcome}${note}${reach}`);
24981
25025
  }
24982
25026
  for (const warning of report.warnings) out.warn(`${out.paint("yellow", "⚠")} ${warning}`);
24983
25027
  }
@@ -24987,6 +25031,7 @@ async function cmdUp(ctx) {
24987
25031
  const bad = unknownFlags(ctx.args.flags, [
24988
25032
  "--no-wait",
24989
25033
  "--dry-run",
25034
+ "--replace-same",
24990
25035
  "--all",
24991
25036
  "--any"
24992
25037
  ]);
@@ -25011,12 +25056,14 @@ async function cmdUp(ctx) {
25011
25056
  try {
25012
25057
  const wait = !ctx.args.flags.has("--no-wait");
25013
25058
  const staggerMs = staggerFor(ctx.config, ctx.args.positionals);
25059
+ const replaceSame = ctx.args.flags.has("--replace-same");
25014
25060
  const report = await withProgress(client, ctx.out, new Set(selection.ordered), () => client.control("start", {
25015
25061
  ids: selection.ordered,
25016
25062
  wait,
25017
- ...staggerMs > 0 ? { staggerMs } : {}
25063
+ ...staggerMs > 0 ? { staggerMs } : {},
25064
+ ...replaceSame ? { replaceSame } : {}
25018
25065
  }));
25019
- return printReport(ctx.out, report);
25066
+ return printReport(ctx.out, report, client.state());
25020
25067
  } finally {
25021
25068
  client.dispose();
25022
25069
  }
@@ -25024,6 +25071,7 @@ async function cmdUp(ctx) {
25024
25071
  async function controlVerb(ctx, verb) {
25025
25072
  const known = verb === "restart" ? [
25026
25073
  "--no-wait",
25074
+ "--replace-same",
25027
25075
  "--all",
25028
25076
  "--any"
25029
25077
  ] : ["--all", "--any"];
@@ -25037,12 +25085,14 @@ async function controlVerb(ctx, verb) {
25037
25085
  bare: "required",
25038
25086
  extraIds: Object.keys(client.state().processes ?? {}).filter((id) => !declared.has(id))
25039
25087
  });
25088
+ const replaceSame = ctx.args.flags.has("--replace-same");
25040
25089
  const report = await withProgress(client, ctx.out, new Set(selection.ordered), () => verb === "stop" ? client.control("stop", { ids: selection.ordered }) : client.control("restart", {
25041
25090
  ids: selection.ordered,
25042
25091
  wait: !ctx.args.flags.has("--no-wait"),
25043
- staggerMs: staggerFor(ctx.config, ctx.args.positionals)
25092
+ staggerMs: staggerFor(ctx.config, ctx.args.positionals),
25093
+ ...replaceSame ? { replaceSame } : {}
25044
25094
  }));
25045
- return printReport(ctx.out, report);
25095
+ return printReport(ctx.out, report, client.state());
25046
25096
  } finally {
25047
25097
  client.dispose();
25048
25098
  }
@@ -25200,6 +25250,117 @@ function countOverrides(overrides) {
25200
25250
  return Object.values(overrides).reduce((total, values) => total + Object.keys(values).length, 0);
25201
25251
  }
25202
25252
  //#endregion
25253
+ //#region src/ports/definitionMatch.ts
25254
+ const exec$1 = (0, node_util.promisify)(node_child_process.execFile);
25255
+ /** How many parents above the listener are examined. Deeper than any dev-server wrapper stack. */
25256
+ const MAX_ANCESTRY = 8;
25257
+ const SHELLS = new Set([
25258
+ "sh",
25259
+ "bash",
25260
+ "zsh",
25261
+ "dash",
25262
+ "fish",
25263
+ "ksh"
25264
+ ]);
25265
+ /** argv as a single comparable string: argv[0] reduced to its basename, whitespace collapsed. */
25266
+ function canonicalCommand(args) {
25267
+ const tokens = args.trim().split(/\s+/).filter((token) => token !== "");
25268
+ if (tokens.length === 0) return "";
25269
+ tokens[0] = (0, node_path.basename)(tokens[0] ?? "");
25270
+ if (tokens.length >= 3 && SHELLS.has(tokens[0] ?? "") && tokens[1] === "-c") return tokens.slice(2).join(" ");
25271
+ return tokens.join(" ");
25272
+ }
25273
+ /** The definition's command in the same canonical form a live process's argv reduces to. */
25274
+ function definitionCommand(definition) {
25275
+ return canonicalCommand(typeof definition.run === "string" ? definition.run : definition.run.join(" "));
25276
+ }
25277
+ async function readIdentity(pid) {
25278
+ const match = (await exec$1("ps", [
25279
+ "-p",
25280
+ String(pid),
25281
+ "-o",
25282
+ "ppid=",
25283
+ "-o",
25284
+ "args="
25285
+ ], { timeout: 5e3 }).catch(() => null))?.stdout.trim().match(/^(\d+)\s+(.*)$/s);
25286
+ if (match == null) return null;
25287
+ const ppid = Number(match[1]);
25288
+ return {
25289
+ ppid: Number.isInteger(ppid) ? ppid : null,
25290
+ args: match[2] ?? ""
25291
+ };
25292
+ }
25293
+ async function readCwd(pid) {
25294
+ const line = (await exec$1("lsof", [
25295
+ "-a",
25296
+ "-p",
25297
+ String(pid),
25298
+ "-d",
25299
+ "cwd",
25300
+ "-Fn"
25301
+ ], { timeout: 5e3 }).catch(() => null))?.stdout.split("\n").find((entry) => entry.startsWith("n"));
25302
+ return line == null ? null : line.slice(1);
25303
+ }
25304
+ async function samePath(a, b) {
25305
+ if (a === b) return true;
25306
+ const [ra, rb] = await Promise.all([(0, node_fs_promises.realpath)(a).catch(() => a), (0, node_fs_promises.realpath)(b).catch(() => b)]);
25307
+ return ra === rb;
25308
+ }
25309
+ /**
25310
+ * Walk up from `listenerPid` looking for the definition's argv+cwd. Null when nothing in the
25311
+ * bounded ancestry matches, when the platform cannot answer (no `ps`/`lsof`), or when the walk
25312
+ * reaches a protected pid — commander itself and its ancestors are never part of a stray.
25313
+ */
25314
+ async function findStray(listenerPid, definition, protectedPids) {
25315
+ if (process.platform === "win32") return null;
25316
+ const wanted = definitionCommand(definition);
25317
+ if (wanted === "") return null;
25318
+ const chain = [];
25319
+ let pid = listenerPid;
25320
+ for (let depth = 0; depth <= MAX_ANCESTRY; depth += 1) {
25321
+ if (pid <= 1 || protectedPids.has(pid)) return null;
25322
+ const identity = await readIdentity(pid);
25323
+ if (identity == null) return null;
25324
+ const stamp = await (0, _nice_code_process.readProcessStartStamp)(pid);
25325
+ const member = {
25326
+ pid,
25327
+ startStamp: stamp?.stamp ?? null
25328
+ };
25329
+ chain.push(member);
25330
+ if (canonicalCommand(identity.args) === wanted) {
25331
+ const cwd = await readCwd(pid);
25332
+ if (cwd != null && await samePath(cwd, definition.cwd)) return {
25333
+ root: member,
25334
+ chain
25335
+ };
25336
+ }
25337
+ if (identity.ppid == null) return null;
25338
+ pid = identity.ppid;
25339
+ }
25340
+ return null;
25341
+ }
25342
+ /** Still the process we saw? A reused pid fails this and is left alone. */
25343
+ async function stillSame(member) {
25344
+ if (member.startStamp == null) return false;
25345
+ return (await (0, _nice_code_process.readProcessStartStamp)(member.pid))?.stamp === member.startStamp;
25346
+ }
25347
+ /**
25348
+ * Signal every verified member of the stray tree, root first (a wrapper such as `bun run`
25349
+ * forwards the signal and exits; signalling the leaf alone lets a watcher respawn it). Members
25350
+ * whose identity no longer checks out are skipped, never guessed at.
25351
+ */
25352
+ async function signalStray(stray, signal) {
25353
+ let signalled = 0;
25354
+ for (const member of [...stray.chain].reverse()) {
25355
+ if (!await stillSame(member)) continue;
25356
+ try {
25357
+ process.kill(member.pid, signal);
25358
+ signalled += 1;
25359
+ } catch {}
25360
+ }
25361
+ return signalled;
25362
+ }
25363
+ //#endregion
25203
25364
  //#region src/ports/listeners.ts
25204
25365
  const exec = (0, node_util.promisify)(node_child_process.execFile);
25205
25366
  const ACTIVE = new Set([
@@ -25289,6 +25450,7 @@ async function processDetails(pid) {
25289
25450
  cwd: cwd?.stdout.split("\n").find((l) => l.startsWith("n"))?.slice(1) ?? null
25290
25451
  };
25291
25452
  }
25453
+ /** Commander itself and everything above it — never a kill target, never part of a stray. */
25292
25454
  async function ancestors() {
25293
25455
  const result = [
25294
25456
  1,
@@ -25310,6 +25472,23 @@ async function ancestors() {
25310
25472
  }
25311
25473
  return result;
25312
25474
  }
25475
+ /**
25476
+ * The first visible listener on one exclusive endpoint, identified. Null when nothing local is
25477
+ * visible on it; throws where the platform cannot answer (no `lsof`, Windows) — the caller
25478
+ * falls back to "in use by something" rather than guessing.
25479
+ */
25480
+ async function identifyEndpointOwner(definition, endpoint, protectedPids) {
25481
+ const hosts = await localAddresses(endpoint.host);
25482
+ const owner = (await listeners(endpoint.port)).find((candidate) => addressMatches(candidate.address, endpoint.port, hosts) && !protectedPids.has(candidate.pid));
25483
+ if (owner == null) return null;
25484
+ const details = await processDetails(owner.pid);
25485
+ return {
25486
+ pid: owner.pid,
25487
+ command: details.command ?? owner.command,
25488
+ cwd: details.cwd,
25489
+ stray: await findStray(owner.pid, definition, protectedPids)
25490
+ };
25491
+ }
25313
25492
  /** Inspection and mutation share this service in the CLI and authenticated daemon control plane. */
25314
25493
  function createPortInspector(options) {
25315
25494
  const snapshots = /* @__PURE__ */ new Map();
@@ -25344,6 +25523,7 @@ function createPortInspector(options) {
25344
25523
  seen.add(owner.pid);
25345
25524
  const stamp = await (0, _nice_code_process.readProcessStartStamp)(owner.pid);
25346
25525
  const details = await processDetails(owner.pid);
25526
+ const stray = await findStray(owner.pid, proc, protectedPids);
25347
25527
  const managed = config.processes.some((p) => ACTIVE.has(states.get(p.id) ?? "") && p.endpoints.some((e) => e.port === endpoint.port));
25348
25528
  const refusal = protectedPids.has(owner.pid) ? "Commander or its parent cannot be terminated here" : managed ? "A configured process using this port is active; use its stop control first" : stamp == null ? "Process identity is unavailable" : null;
25349
25529
  const listener = {
@@ -25356,6 +25536,8 @@ function createPortInspector(options) {
25356
25536
  ppid: details.ppid,
25357
25537
  cwd: details.cwd,
25358
25538
  startStamp: stamp?.stamp ?? null,
25539
+ stray: stray != null,
25540
+ strayRoot: stray?.root.pid ?? null,
25359
25541
  refusal,
25360
25542
  token: refusal == null ? (0, node_crypto.randomUUID)() : null
25361
25543
  };
@@ -25363,6 +25545,7 @@ function createPortInspector(options) {
25363
25545
  if (snapshots.size >= 1e3) snapshots.delete(snapshots.keys().next().value);
25364
25546
  snapshots.set(listener.token, {
25365
25547
  listener,
25548
+ stray,
25366
25549
  expires: Date.now() + 3e5
25367
25550
  });
25368
25551
  }
@@ -25385,7 +25568,7 @@ function createPortInspector(options) {
25385
25568
  };
25386
25569
  const target = snapshot.listener;
25387
25570
  const fresh = await inspect([target.id]);
25388
- const current = fresh.listeners.find((l) => l.pid === target.pid && l.endpoint === target.endpoint && l.host === target.host && l.port === target.port && l.startStamp === target.startStamp && l.command === target.command);
25571
+ const current = fresh.listeners.find((l) => l.pid === target.pid && l.endpoint === target.endpoint && l.host === target.host && l.port === target.port && l.startStamp === target.startStamp && l.command === target.command && l.strayRoot === target.strayRoot);
25389
25572
  if (!current || current.refusal) return {
25390
25573
  listeners: fresh.listeners,
25391
25574
  warnings: [...fresh.warnings, current?.refusal ?? "Listener changed or exited; nothing was killed. Inspect ports again."]
@@ -25412,8 +25595,14 @@ function createPortInspector(options) {
25412
25595
  listeners: [],
25413
25596
  warnings: ["Process identity changed; nothing was killed."]
25414
25597
  };
25415
- try {
25416
- process.kill(target.pid, input.force ? "SIGKILL" : "SIGTERM");
25598
+ const signal = input.force ? "SIGKILL" : "SIGTERM";
25599
+ if (snapshot.stray != null) {
25600
+ if (await signalStray(snapshot.stray, signal) === 0) return {
25601
+ listeners: [],
25602
+ warnings: ["Stray tree already gone; nothing was killed."]
25603
+ };
25604
+ } else try {
25605
+ process.kill(target.pid, signal);
25417
25606
  } catch (error) {
25418
25607
  return {
25419
25608
  listeners: fresh.listeners,
@@ -25433,6 +25622,149 @@ function createPortInspector(options) {
25433
25622
  return { run };
25434
25623
  }
25435
25624
  //#endregion
25625
+ //#region src/cli/commands/ports.ts
25626
+ async function portProcessStates(ctx) {
25627
+ const handle = await findDaemon(ctx.config);
25628
+ if (!handle) return /* @__PURE__ */ new Map();
25629
+ const client = await connectDaemon(handle);
25630
+ try {
25631
+ return new Map(Object.entries(client.state().processes).map(([id, p]) => [id, p.state]));
25632
+ } finally {
25633
+ client.dispose();
25634
+ }
25635
+ }
25636
+ /** One row per listener; the STRAY column is the verdict that decides what a stop will end. */
25637
+ function renderListeners(ctx, result) {
25638
+ return ctx.out.table([
25639
+ "PROCESS",
25640
+ "ENDPOINT",
25641
+ "PID",
25642
+ "PARENT",
25643
+ "COMMAND",
25644
+ "CWD",
25645
+ "STRAY",
25646
+ "IDENTITY",
25647
+ "STOP"
25648
+ ], result.listeners.map((l) => [
25649
+ l.id,
25650
+ `${l.host}:${l.port}`,
25651
+ String(l.pid),
25652
+ String(l.ppid ?? "unknown"),
25653
+ l.command,
25654
+ l.cwd ?? "unavailable",
25655
+ strayCell(l),
25656
+ l.startStamp ?? "unknown",
25657
+ l.refusal ?? "available"
25658
+ ]));
25659
+ }
25660
+ function strayCell(listener) {
25661
+ if (!listener.stray) return "no";
25662
+ return listener.strayRoot != null && listener.strayRoot !== listener.pid ? `yes (root ${listener.strayRoot})` : "yes";
25663
+ }
25664
+ /** `[y/N]` on a TTY; scripts pass `--yes` or get a usage error, never a silent kill. */
25665
+ async function confirmKill(ctx, question, reportForRefusal) {
25666
+ if (ctx.args.flags.has("--yes")) return true;
25667
+ reportForRefusal();
25668
+ if (!process.stdin.isTTY || ctx.out.json) throw new CliExit(EXIT.usage, "Stopping requires interactive confirmation, or --yes for scripts");
25669
+ const rl = (0, node_readline_promises.createInterface)({
25670
+ input: process.stdin,
25671
+ output: process.stdout
25672
+ });
25673
+ try {
25674
+ const answer = await rl.question(`${question} [y/N] `);
25675
+ return /^y(es)?$/i.test(answer.trim());
25676
+ } finally {
25677
+ rl.close();
25678
+ }
25679
+ }
25680
+ async function cmdPorts(ctx) {
25681
+ const bad = unknownFlags(ctx.args.flags, [
25682
+ "--all",
25683
+ "--kill",
25684
+ "--kill-owner",
25685
+ "--yes",
25686
+ "--force"
25687
+ ]);
25688
+ if (bad) throw new CliExit(EXIT.usage, bad);
25689
+ const pid = numericFlag(ctx.args.flags, "--kill");
25690
+ if (pid != null && typeof pid !== "number") throw new CliExit(EXIT.usage, pid.error);
25691
+ for (const flag of [
25692
+ "--yes",
25693
+ "--force",
25694
+ "--all",
25695
+ "--kill-owner"
25696
+ ]) if (ctx.args.flags.has(flag) && ctx.args.flags.get(flag) !== true) throw new CliExit(EXIT.usage, `${flag} takes no value`);
25697
+ const killOwner = ctx.args.flags.has("--kill-owner");
25698
+ if (pid != null && killOwner) throw new CliExit(EXIT.usage, "--kill PID and --kill-owner are alternatives; pass one");
25699
+ if (!pid && !killOwner && (ctx.args.flags.has("--force") || ctx.args.flags.has("--yes"))) throw new CliExit(EXIT.usage, "--force/--yes require --kill PID or --kill-owner");
25700
+ if (killOwner && ctx.args.positionals.length === 0 && !ctx.args.flags.has("--all")) throw new CliExit(EXIT.usage, "--kill-owner needs a selection (ids, suite, tag=val) or --all");
25701
+ const ids = ctx.args.positionals.length || ctx.args.flags.has("--all") ? selectOrExit(ctx, { bare: "required" }).direct : ctx.config.processes.map((p) => p.id);
25702
+ const inspector = createPortInspector({
25703
+ config: () => ctx.config,
25704
+ states: () => portProcessStates(ctx),
25705
+ protectedPids: async () => {
25706
+ const daemon = await findDaemon(ctx.config);
25707
+ return daemon ? [daemon.record.pid] : [];
25708
+ }
25709
+ });
25710
+ const report = await inspector.run({ ids });
25711
+ const print = (result) => {
25712
+ if (ctx.out.json) {
25713
+ ctx.out.printJson(result);
25714
+ return;
25715
+ }
25716
+ ctx.out.print(renderListeners(ctx, result));
25717
+ if (!result.listeners.length) ctx.out.print("No visible listeners on the selected exclusive TCP endpoints.");
25718
+ for (const warning of result.warnings) ctx.out.warn(warning);
25719
+ };
25720
+ const force = ctx.args.flags.has("--force");
25721
+ const verb = force ? "Force kill" : "Stop";
25722
+ const describe = (target) => `${target.stray ? "stray " : ""}PID ${target.pid} (${target.command}) on ${target.host}:${target.port}` + (target.stray && target.strayRoot != null && target.strayRoot !== target.pid ? ` and its root PID ${target.strayRoot}` : "");
25723
+ if (killOwner) {
25724
+ let current = report;
25725
+ const attempted = /* @__PURE__ */ new Set();
25726
+ const warnings = [];
25727
+ let stopped = 0;
25728
+ for (;;) {
25729
+ const target = current.listeners.find((l) => l.token != null && !attempted.has(l.pid));
25730
+ if (target?.token == null) break;
25731
+ attempted.add(target.pid);
25732
+ if (!await confirmKill(ctx, `${verb} ${describe(target)}?`, () => print(current))) continue;
25733
+ current = await inspector.run({
25734
+ ids,
25735
+ token: target.token,
25736
+ force
25737
+ });
25738
+ warnings.push(...current.warnings);
25739
+ if (!current.listeners.some((l) => l.pid === target.pid)) stopped += 1;
25740
+ }
25741
+ const refused = current.listeners.filter((l) => l.refusal != null);
25742
+ print({
25743
+ listeners: current.listeners,
25744
+ warnings: [...new Set(warnings)]
25745
+ });
25746
+ if (!ctx.out.json) ctx.out.print(`kill-owner: ${stopped} stopped` + (refused.length > 0 ? `, ${refused.length} refused (see STOP)` : "") + (current.listeners.length === 0 ? " — selected endpoints are free" : ""));
25747
+ return warnings.length > 0 || current.listeners.some((l) => l.token != null) ? EXIT.failure : EXIT.ok;
25748
+ }
25749
+ if (!pid) {
25750
+ print(report);
25751
+ return report.warnings.length ? EXIT.failure : EXIT.ok;
25752
+ }
25753
+ const target = report.listeners.find((l) => l.pid === pid);
25754
+ if (!target?.token) {
25755
+ print(report);
25756
+ throw new CliExit(EXIT.failure, target?.refusal ?? `PID ${pid} is not a verified listener on the selected endpoints`);
25757
+ }
25758
+ if (!await confirmKill(ctx, `${verb} ${describe(target)}?`, () => print(report))) return EXIT.ok;
25759
+ const result = await inspector.run({
25760
+ ids,
25761
+ token: target.token,
25762
+ force
25763
+ });
25764
+ print(result);
25765
+ return result.warnings.length ? EXIT.failure : EXIT.ok;
25766
+ }
25767
+ //#endregion
25436
25768
  //#region src/cli/commands/doctor.ts
25437
25769
  function formatAge(ms) {
25438
25770
  if (ms < 6e4) return `${Math.round(ms / 1e3)}s`;
@@ -25572,9 +25904,62 @@ async function diagnose(ctx, handle) {
25572
25904
  token: null
25573
25905
  }));
25574
25906
  report.warnings.push(...occupied.warnings);
25575
- for (const owner of occupied.listeners) report.info.push(`port owner ${owner.id}.${owner.endpoint} (${owner.host}:${owner.port}): PID ${owner.pid}, ${owner.command}, identity ${owner.startStamp ?? "unknown"} — ${owner.refusal ?? `inspect/stop with \`nice-commander ports ${owner.id} --kill ${owner.pid}\``}`);
25907
+ for (const owner of occupied.listeners) {
25908
+ const verdict = owner.stray ? `STRAY — "${owner.id}"'s own command outside the daemon` + (owner.strayRoot != null && owner.strayRoot !== owner.pid ? ` (root PID ${owner.strayRoot})` : "") + "; `doctor --reap-strays` stops it, `up --replace-same` replaces it" : `not "${owner.id}"'s command — never stopped automatically`;
25909
+ report.info.push(`port owner ${owner.id}.${owner.endpoint} (${owner.host}:${owner.port}): PID ${owner.pid}, ${owner.command}, identity ${owner.startStamp ?? "unknown"} — ${verdict} — ${owner.refusal ?? `inspect/stop with \`nice-commander ports ${owner.id} --kill ${owner.pid}\``}`);
25910
+ }
25576
25911
  return report;
25577
25912
  }
25913
+ /**
25914
+ * `--reap-strays`: stop every stray on a configured exclusive port. Strangers are printed with
25915
+ * the same table and left where they are — the stray verdict (argv + cwd, identity re-checked
25916
+ * before every signal) is the only thing that authorizes a kill here.
25917
+ */
25918
+ async function reapStrays(ctx, handle) {
25919
+ const { out, config } = ctx;
25920
+ const stateById = handle != null ? await fetchProcessStates(handle) : /* @__PURE__ */ new Map();
25921
+ const ids = config.processes.filter((proc) => !ACTIVE_LIKE.has(stateById.get(proc.id) ?? "")).map((proc) => proc.id);
25922
+ const inspector = createPortInspector({
25923
+ config: () => config,
25924
+ states: async () => stateById,
25925
+ protectedPids: async () => handle ? [handle.record.pid] : []
25926
+ });
25927
+ const force = ctx.args.flags.has("--force");
25928
+ let current = await inspector.run({ ids });
25929
+ const attempted = /* @__PURE__ */ new Set();
25930
+ const warnings = [...current.warnings];
25931
+ let stopped = 0;
25932
+ for (;;) {
25933
+ const target = current.listeners.find((l) => l.stray && l.token != null && !attempted.has(l.pid));
25934
+ if (target?.token == null) break;
25935
+ attempted.add(target.pid);
25936
+ if (!await confirmKill(ctx, `${force ? "Force kill" : "Stop"} stray PID ${target.pid} (${target.command}) on ${target.host}:${target.port}, "${target.id}"'s own command${target.strayRoot != null && target.strayRoot !== target.pid ? ` (tree root PID ${target.strayRoot})` : ""}?`, () => {
25937
+ if (!out.json) out.print(renderListeners(ctx, current));
25938
+ })) continue;
25939
+ current = await inspector.run({
25940
+ ids,
25941
+ token: target.token,
25942
+ force
25943
+ });
25944
+ warnings.push(...current.warnings);
25945
+ if (!current.listeners.some((l) => l.pid === target.pid)) stopped += 1;
25946
+ }
25947
+ const strangers = current.listeners.filter((l) => !l.stray);
25948
+ if (out.json) out.printJson({
25949
+ stopped,
25950
+ listeners: current.listeners.map((l) => ({
25951
+ ...l,
25952
+ token: null
25953
+ })),
25954
+ warnings: [...new Set(warnings)]
25955
+ });
25956
+ else {
25957
+ out.print(`reap-strays: ${stopped} stray listener(s) stopped` + (strangers.length > 0 ? `, ${strangers.length} left alone (not this config's commands — see STRAY)` : ""));
25958
+ if (current.listeners.length > 0) out.print(renderListeners(ctx, current));
25959
+ for (const warning of new Set(warnings)) out.print(`${out.paint("yellow", "⚠")} ${warning}`);
25960
+ }
25961
+ return warnings.length > 0 || current.listeners.some((l) => l.stray && l.token != null) ? EXIT.failure : EXIT.ok;
25962
+ }
25578
25963
  const ACTIVE_LIKE = new Set([
25579
25964
  "starting",
25580
25965
  "running",
@@ -25591,9 +25976,22 @@ async function fetchProcessStates(handle) {
25591
25976
  }
25592
25977
  }
25593
25978
  async function cmdDoctor(ctx) {
25594
- const bad = unknownFlags(ctx.args.flags, ["--reap"]);
25979
+ const bad = unknownFlags(ctx.args.flags, [
25980
+ "--reap",
25981
+ "--reap-strays",
25982
+ "--yes",
25983
+ "--force"
25984
+ ]);
25595
25985
  if (bad != null) throw new CliExit(EXIT.usage, bad);
25986
+ for (const flag of [
25987
+ "--reap",
25988
+ "--reap-strays",
25989
+ "--yes",
25990
+ "--force"
25991
+ ]) if (ctx.args.flags.has(flag) && ctx.args.flags.get(flag) !== true) throw new CliExit(EXIT.usage, `${flag} takes no value`);
25992
+ if (!ctx.args.flags.has("--reap-strays") && (ctx.args.flags.has("--yes") || ctx.args.flags.has("--force"))) throw new CliExit(EXIT.usage, "--yes/--force belong to --reap-strays");
25596
25993
  const handle = await findDaemon(ctx.config);
25994
+ if (ctx.args.flags.has("--reap-strays")) return reapStrays(ctx, handle);
25597
25995
  if (ctx.args.flags.has("--reap")) {
25598
25996
  const { out } = ctx;
25599
25997
  if (handle != null) {
@@ -25807,7 +26205,11 @@ async function cmdList(ctx) {
25807
26205
  return EXIT.ok;
25808
26206
  }
25809
26207
  async function cmdExplain(ctx) {
25810
- const bad = unknownFlags(ctx.args.flags, ["--all", "--any"]);
26208
+ const bad = unknownFlags(ctx.args.flags, [
26209
+ "--all",
26210
+ "--any",
26211
+ "--env"
26212
+ ]);
25811
26213
  if (bad != null) throw new CliExit(EXIT.usage, bad);
25812
26214
  const selection = selectOrExit(ctx, { bare: "default" });
25813
26215
  const { out } = ctx;
@@ -25824,6 +26226,10 @@ async function cmdExplain(ctx) {
25824
26226
  selection.ordered.forEach((id, index) => {
25825
26227
  out.print(` ${index + 1}. ${id}`);
25826
26228
  });
26229
+ if (!ctx.args.flags.has("--env")) {
26230
+ out.print(out.paint("gray", "env: `explain <sel> --env` shows each id's spawn environment"));
26231
+ return EXIT.ok;
26232
+ }
25827
26233
  const overrides = await readEnvOverrides(commanderStatePaths(resolveCommanderDataDir(), ctx.config.configKey).envOverridesPath);
25828
26234
  out.print("env:");
25829
26235
  out.print(" note: `run` children inherit THIS shell's environment; daemon-owned starts (`up`) inherit");
@@ -26072,102 +26478,6 @@ async function cmdLogs(ctx) {
26072
26478
  }
26073
26479
  }
26074
26480
  //#endregion
26075
- //#region src/cli/commands/ports.ts
26076
- async function portProcessStates(ctx) {
26077
- const handle = await findDaemon(ctx.config);
26078
- if (!handle) return /* @__PURE__ */ new Map();
26079
- const client = await connectDaemon(handle);
26080
- try {
26081
- return new Map(Object.entries(client.state().processes).map(([id, p]) => [id, p.state]));
26082
- } finally {
26083
- client.dispose();
26084
- }
26085
- }
26086
- async function cmdPorts(ctx) {
26087
- const bad = unknownFlags(ctx.args.flags, [
26088
- "--all",
26089
- "--kill",
26090
- "--yes",
26091
- "--force"
26092
- ]);
26093
- if (bad) throw new CliExit(EXIT.usage, bad);
26094
- const pid = numericFlag(ctx.args.flags, "--kill");
26095
- if (pid != null && typeof pid !== "number") throw new CliExit(EXIT.usage, pid.error);
26096
- for (const flag of [
26097
- "--yes",
26098
- "--force",
26099
- "--all"
26100
- ]) if (ctx.args.flags.has(flag) && ctx.args.flags.get(flag) !== true) throw new CliExit(EXIT.usage, `${flag} takes no value`);
26101
- if (!pid && (ctx.args.flags.has("--force") || ctx.args.flags.has("--yes"))) throw new CliExit(EXIT.usage, "--force/--yes require --kill PID");
26102
- const ids = ctx.args.positionals.length || ctx.args.flags.has("--all") ? selectOrExit(ctx, { bare: "required" }).direct : ctx.config.processes.map((p) => p.id);
26103
- const inspector = createPortInspector({
26104
- config: () => ctx.config,
26105
- states: () => portProcessStates(ctx),
26106
- protectedPids: async () => {
26107
- const daemon = await findDaemon(ctx.config);
26108
- return daemon ? [daemon.record.pid] : [];
26109
- }
26110
- });
26111
- const report = await inspector.run({ ids });
26112
- const print = (result) => {
26113
- if (ctx.out.json) {
26114
- ctx.out.printJson(result);
26115
- return;
26116
- }
26117
- ctx.out.print(ctx.out.table([
26118
- "PROCESS",
26119
- "ENDPOINT",
26120
- "PID",
26121
- "PARENT",
26122
- "COMMAND",
26123
- "CWD",
26124
- "IDENTITY",
26125
- "STOP"
26126
- ], result.listeners.map((l) => [
26127
- l.id,
26128
- `${l.host}:${l.port}`,
26129
- String(l.pid),
26130
- String(l.ppid ?? "unknown"),
26131
- l.command,
26132
- l.cwd ?? "unavailable",
26133
- l.startStamp ?? "unknown",
26134
- l.refusal ?? "available"
26135
- ])));
26136
- if (!result.listeners.length) ctx.out.print("No visible listeners on the selected exclusive TCP endpoints.");
26137
- for (const warning of result.warnings) ctx.out.warn(warning);
26138
- };
26139
- if (!pid) {
26140
- print(report);
26141
- return report.warnings.length ? EXIT.failure : EXIT.ok;
26142
- }
26143
- const target = report.listeners.find((l) => l.pid === pid);
26144
- if (!target?.token) {
26145
- print(report);
26146
- throw new CliExit(EXIT.failure, target?.refusal ?? `PID ${pid} is not a verified listener on the selected endpoints`);
26147
- }
26148
- if (!ctx.args.flags.has("--yes")) {
26149
- print(report);
26150
- if (!process.stdin.isTTY || ctx.out.json) throw new CliExit(EXIT.usage, "Stopping requires interactive confirmation, or --yes with --kill PID");
26151
- const rl = (0, node_readline_promises.createInterface)({
26152
- input: process.stdin,
26153
- output: process.stdout
26154
- });
26155
- try {
26156
- const answer = await rl.question(`${ctx.args.flags.has("--force") ? "Force kill" : "Stop"} PID ${pid} (${target.command}) on ${target.host}:${target.port}? [y/N] `);
26157
- if (!/^y(es)?$/i.test(answer.trim())) return EXIT.ok;
26158
- } finally {
26159
- rl.close();
26160
- }
26161
- }
26162
- const result = await inspector.run({
26163
- ids,
26164
- token: target.token,
26165
- force: ctx.args.flags.has("--force")
26166
- });
26167
- print(result);
26168
- return result.warnings.length ? EXIT.failure : EXIT.ok;
26169
- }
26170
- //#endregion
26171
26481
  //#region src/run/scheduler.ts
26172
26482
  async function runTaskPool(options) {
26173
26483
  const { failFast } = options;
@@ -26602,6 +26912,7 @@ const SILENT_START_NOTE_MS = 15e3;
26602
26912
  function notesFor(proc, now) {
26603
26913
  const notes = [];
26604
26914
  if (proc.blockedBy != null) notes.push(`blocked: ${proc.blockedBy}`);
26915
+ if (proc.startError != null) notes.push(`start failed: ${proc.startError}`);
26605
26916
  if (proc.degradedBy.length > 0) notes.push(`degraded by ${proc.degradedBy.join(", ")}`);
26606
26917
  if (proc.unreadyReason != null) notes.push(`unready: ${proc.unreadyReason}`);
26607
26918
  if (ACTIVE_STATES.has(proc.state) && proc.sawOutputAt == null && proc.startedAt != null && now - proc.startedAt > SILENT_START_NOTE_MS) notes.push(`no output since start (${formatUptime(proc.startedAt, now)})`);
@@ -26838,29 +27149,42 @@ function mutateSavedFilters(current, change) {
26838
27149
  }
26839
27150
  //#endregion
26840
27151
  //#region src/cli.ts
26841
- const HELP = `nice-commander — one typed config, one control surface, for dev environments.
27152
+ const USAGE = `nice-commander — one typed config, one control surface, for dev environments.
26842
27153
 
26843
27154
  usage: nice-commander [--config <path>] [--json] [--no-color] [--timeout <ms>] [command] [selection] [flags]
26844
27155
 
26845
- With NO command, "ui" runs: the daemon is ensured and the browser opened. --help prints this text.
27156
+ With NO command, "ui" runs: the daemon is ensured and the browser opened. --help prints this text;
27157
+ <command> --help prints that command's section.
26846
27158
 
26847
27159
  selection: process ids, suite names, @pin names, tag=val, or --all. Several tag=val terms AND
26848
27160
  together; --any ORs them instead. A tag selection and --all never start an optIn process.
26849
27161
  Bare up/explain use the config's defaultSelection (or print the suites and exit);
26850
27162
  bare down/restart/logs/run always require a selection — omission never means --all.
26851
-
26852
- commands:
26853
- up [sel] [--no-wait] [--dry-run] start: deps auto-included, DAG order, live progress
26854
- down <sel> stop (reverse-DAG order)
26855
- restart <sel> [--no-wait] stop + start
26856
- status [--watch] table from the live status realm
26857
- logs <sel> [-f] merged interleaved tail with colored id prefixes
26858
- list config introspection (processes, suites, warnings)
26859
- explain [sel] expanded ids, auto-included deps, DAG order, suite policy
26860
- env [sel] [--set N=V] [--unset N] declared env vars and their values; --clear drops
27163
+ `;
27164
+ /**
27165
+ * One entry per command, so `up --help` can answer with `up` alone. The full text is the usage
27166
+ * block followed by every entry, in this order.
27167
+ */
27168
+ const COMMAND_HELP = [
27169
+ ["up", ` up [sel] [--no-wait] [--dry-run] [--replace-same]
27170
+ start: deps auto-included, DAG order, live progress;
27171
+ a ready service prints its URL. --replace-same lets a
27172
+ start take an exclusive port from a STRAY — this same
27173
+ command in the same cwd, started outside the daemon
27174
+ (a stranger on the port still refuses). --json reports
27175
+ every id's outcome, state, pid and endpoints as data.`],
27176
+ ["down", " down <sel> stop (reverse-DAG order)"],
27177
+ ["restart", ` restart <sel> [--no-wait] [--replace-same]
27178
+ stop + start`],
27179
+ ["status", " status [--watch] table from the live status realm"],
27180
+ ["logs", " logs <sel> [-f] merged interleaved tail with colored id prefixes"],
27181
+ ["list", " list config introspection (processes, suites, warnings)"],
27182
+ ["explain", ` explain [sel] [--env] expanded ids, auto-included deps, DAG order, suite
27183
+ policy; --env adds each id's spawn environment`],
27184
+ ["env", ` env [sel] [--set N=V] [--unset N] declared env vars and their values; --clear drops
26861
27185
  overrides. A set value is STICKY: it applies to every
26862
- later start until cleared, and never restarts anything.
26863
- run <sel> [--parallel N] [--fail-fast] foreground, no daemon; tasks = local CI shape
27186
+ later start until cleared, and never restarts anything.`],
27187
+ ["run", ` run <sel> [--parallel N] [--fail-fast] foreground, no daemon; tasks = local CI shape
26864
27188
  (a suite supplies its own parallel/fail-fast),
26865
27189
  a single id gets raw inherited stdio (interactive).
26866
27190
  --fail-fast = stop at the FIRST failure and stop the
@@ -26868,20 +27192,40 @@ commands:
26868
27192
  failure is reported, and the exit code is still
26869
27193
  non-zero. Children inherit THIS shell's environment;
26870
27194
  daemon-owned processes (up) inherit the daemon's
26871
- boot-time snapshot instead — see doctor.
26872
- ui ensure the daemon and open the browser (prints URL)
26873
- doctor [--reap] diagnostics: ledger, capability, endpoints, env.
27195
+ boot-time snapshot instead — see doctor.`],
27196
+ ["ui", " ui ensure the daemon and open the browser (prints URL)"],
27197
+ ["doctor", ` doctor [--reap] [--reap-strays [--yes] [--force]]
27198
+ diagnostics: ledger, capability, endpoints (each port
27199
+ owner marked STRAY or not), env.
26874
27200
  --reap collects a crashed daemon's orphans NOW
26875
27201
  (same reap the next boot runs; refused while a
26876
- daemon is live)
26877
- ports [sel] [--kill PID] [--force] inspect exclusive TCP port owners; selected PID stop
26878
- prompts for confirmation (--yes for scripts).
26879
- --force sends SIGKILL instead of SIGTERM.
26880
- shutdown stop the daemon (graceful ladder)
26881
-
27202
+ daemon is live). --reap-strays stops every stray —
27203
+ a listener that is this config's own command outside
27204
+ the daemon — after confirmation (--yes for scripts);
27205
+ strangers are listed and left alone.`],
27206
+ ["ports", ` ports [sel] [--kill PID | --kill-owner] [--yes] [--force]
27207
+ inspect exclusive TCP port owners (STRAY = this
27208
+ definition's own command outside the daemon).
27209
+ --kill PID stops that listener; --kill-owner stops
27210
+ whatever holds the selection's exclusive endpoints,
27211
+ no PID needed. Both prompt (--yes for scripts); a
27212
+ stray is stopped as its tree, a stranger only as the
27213
+ listener. --force sends SIGKILL instead of SIGTERM.`],
27214
+ ["shutdown", " shutdown stop the daemon (graceful ladder)"]
27215
+ ];
27216
+ const FOOTER = `
26882
27217
  status/down/logs/doctor/shutdown never start a missing daemon — they report "not running".
26883
27218
  exit codes: 0 ok · 1 failure · 2 usage · 3 daemon not running · 4 timeout
26884
27219
  `;
27220
+ const HELP = `${USAGE}
27221
+ commands:
27222
+ ${COMMAND_HELP.map(([, text]) => text).join("\n")}
27223
+ ${FOOTER}`;
27224
+ function helpFor(command) {
27225
+ const entry = command == null ? void 0 : COMMAND_HELP.find(([name]) => name === command);
27226
+ if (entry == null) return HELP;
27227
+ return `usage: nice-commander [--config <path>] [--json] [--no-color] [--timeout <ms>] ${entry[0]} …\n\n${entry[1]}\n${FOOTER}`;
27228
+ }
26885
27229
  const COMMANDS = {
26886
27230
  up: cmdUp,
26887
27231
  down: cmdDown,
@@ -26929,7 +27273,7 @@ async function withTimeout(ctx, run) {
26929
27273
  async function main() {
26930
27274
  const argv = process.argv.slice(2);
26931
27275
  if (argv[0] === "daemon") {
26932
- const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-D-StoxUH.cjs"));
27276
+ const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-DkrkRGT6.cjs"));
26933
27277
  return runCommanderDaemon(argv.slice(1));
26934
27278
  }
26935
27279
  const parsed = parseCliArgs(argv);
@@ -26938,7 +27282,7 @@ async function main() {
26938
27282
  return EXIT.usage;
26939
27283
  }
26940
27284
  if (parsed.help || parsed.command === "help") {
26941
- process.stdout.write(HELP);
27285
+ process.stdout.write(helpFor(parsed.command === "help" ? null : parsed.command));
26942
27286
  return EXIT.ok;
26943
27287
  }
26944
27288
  const requested = parsed.command ?? "ui";
@@ -26981,6 +27325,7 @@ exports.COMMANDER_TICKET_PATH = COMMANDER_TICKET_PATH;
26981
27325
  exports.COMMANDER_TICKET_PROTOCOL_PREFIX = COMMANDER_TICKET_PROTOCOL_PREFIX;
26982
27326
  exports.COMMANDER_WS_PATH = COMMANDER_WS_PATH;
26983
27327
  exports.RuntimeCoordinate = RuntimeCoordinate;
27328
+ exports.ancestors = ancestors;
26984
27329
  exports.applyEnvMutation = applyEnvMutation;
26985
27330
  exports.commanderChannel = commanderChannel;
26986
27331
  exports.commanderControlDomain = commanderControlDomain;
@@ -26999,6 +27344,7 @@ exports.ensureStateDir = ensureStateDir;
26999
27344
  exports.envVarViews = envVarViews;
27000
27345
  exports.hashCanonical = hashCanonical;
27001
27346
  exports.httpAcceptorCarrier = httpAcceptorCarrier;
27347
+ exports.identifyEndpointOwner = identifyEndpointOwner;
27002
27348
  exports.loadCommanderConfigFile = loadCommanderConfigFile;
27003
27349
  exports.mutateSavedFilters = mutateSavedFilters;
27004
27350
  exports.orderByDependency = orderByDependency;
@@ -27013,6 +27359,7 @@ exports.resolveCommanderDataDir = resolveCommanderDataDir;
27013
27359
  exports.runTaskPool = runTaskPool;
27014
27360
  exports.savedFilterId = savedFilterId;
27015
27361
  exports.serveChannel = serveChannel;
27362
+ exports.signalStray = signalStray;
27016
27363
  exports.stopSetWithDependencies = stopSetWithDependencies;
27017
27364
  exports.validateCommanderConfig = validateCommanderConfig;
27018
27365
  exports.withDependencies = withDependencies;