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