@nice-code/commander 0.102.0 → 0.104.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,
@@ -22163,6 +22166,20 @@ var RealmRuleTrie = class {
22163
22166
  params
22164
22167
  };
22165
22168
  }
22169
+ /**
22170
+ * Whether some rule's pattern can match a path strictly BENEATH `path` (a `**` at or above it
22171
+ * counts). Ignores `view` conditions — the answer is about schema reachability, not access.
22172
+ */
22173
+ reachesBeneath(path) {
22174
+ return this._reachesBeneath(this._root, path, 0);
22175
+ }
22176
+ _reachesBeneath(node, path, depth) {
22177
+ if (node.deep != null) return true;
22178
+ if (depth === path.length) return (node.lit?.size ?? 0) > 0 || node.var != null || node.star != null;
22179
+ const litChild = node.lit?.get(path[depth]);
22180
+ if (litChild != null && this._reachesBeneath(litChild, path, depth + 1)) return true;
22181
+ return node.var != null && this._reachesBeneath(node.var.node, path, depth + 1);
22182
+ }
22166
22183
  _match(node, path, depth) {
22167
22184
  if (depth === path.length) return node.exact;
22168
22185
  const seg = path[depth];
@@ -22722,14 +22739,22 @@ const OMIT = {
22722
22739
  value: void 0,
22723
22740
  anyVisible: false
22724
22741
  };
22725
- function pruneNode(ctx, node, value, path) {
22742
+ /** Does `path` pass through a record entry? Its containers are then data, not structure. */
22743
+ function underRecordEntry(schemaRoot, path) {
22744
+ for (let depth = 1; depth < path.length; depth++) {
22745
+ const parent = schemaNodeAtPath(schemaRoot, path.slice(0, depth));
22746
+ if (parent != null && unwrapOptional(parent).kind === "record") return true;
22747
+ }
22748
+ return false;
22749
+ }
22750
+ function pruneNode(ctx, node, value, path, inEntry = underRecordEntry(ctx.schemaRoot, path)) {
22726
22751
  if (value === void 0) return OMIT;
22727
22752
  const inner = unwrapOptional(node);
22728
22753
  if (inner.kind === "object") {
22729
22754
  const out = {};
22730
22755
  let anyVisible = false;
22731
22756
  for (const [key, child] of Object.entries(inner.entries)) {
22732
- const pruned = pruneNode(ctx, child, value[key], [...path, key]);
22757
+ const pruned = pruneNode(ctx, child, value[key], [...path, key], inEntry);
22733
22758
  if (pruned.anyVisible) {
22734
22759
  out[key] = pruned.value;
22735
22760
  anyVisible = true;
@@ -22744,15 +22769,16 @@ function pruneNode(ctx, node, value, path) {
22744
22769
  const out = {};
22745
22770
  let anyVisible = false;
22746
22771
  if (value != null && typeof value === "object") for (const [key, entry] of Object.entries(value)) {
22747
- const pruned = pruneNode(ctx, inner.value, entry, [...path, key]);
22772
+ const pruned = pruneNode(ctx, inner.value, entry, [...path, key], true);
22748
22773
  if (pruned.anyVisible) {
22749
22774
  out[key] = pruned.value;
22750
22775
  anyVisible = true;
22751
22776
  }
22752
22777
  }
22778
+ const structural = !inEntry && ctx.trie.reachesBeneath(path);
22753
22779
  return {
22754
22780
  value: out,
22755
- anyVisible: anyVisible || leafVisible(ctx, path)
22781
+ anyVisible: anyVisible || structural || leafVisible(ctx, path)
22756
22782
  };
22757
22783
  }
22758
22784
  return leafVisible(ctx, path) ? {
@@ -24165,6 +24191,7 @@ const commanderStatusRealm = defineRealm({
24165
24191
  removed: t.boolean(),
24166
24192
  envDrift: t.boolean(),
24167
24193
  blockedBy: t.optional(t.string()),
24194
+ startError: t.optional(t.string()),
24168
24195
  degradedBy: t.array(t.string()),
24169
24196
  unreadyReason: t.optional(t.string()),
24170
24197
  capability: t.optional(t.object({
@@ -24178,6 +24205,7 @@ const commanderStatusRealm = defineRealm({
24178
24205
  command: t.string(),
24179
24206
  cwd: t.string(),
24180
24207
  dependsOn: t.array(t.string()),
24208
+ url: t.optional(t.string()),
24181
24209
  ready: t.optional(t.string()),
24182
24210
  timeoutMs: t.optional(t.number()),
24183
24211
  endpoints: t.array(t.object({
@@ -24355,7 +24383,7 @@ var CommanderDaemonBootError = class extends Error {
24355
24383
  * a live dev environment, and an upgrade must never be the thing that kills one.
24356
24384
  */
24357
24385
  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" : ""})`;
24386
+ 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
24387
  let liveIds;
24360
24388
  try {
24361
24389
  liveIds = (await (0, _nice_code_process.openProcessLedger)({
@@ -24497,7 +24525,7 @@ function checkPortsReport(value) {
24497
24525
  r.endpoint,
24498
24526
  r.host,
24499
24527
  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") || ![
24528
+ ].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
24529
  r.startStamp,
24502
24530
  r.token,
24503
24531
  r.refusal
@@ -24561,9 +24589,12 @@ function checkStart(value) {
24561
24589
  if (wait != null && typeof wait !== "boolean") return "wait: expected a boolean";
24562
24590
  const staggerMs = record["staggerMs"];
24563
24591
  if (staggerMs != null && (typeof staggerMs !== "number" || staggerMs < 0)) return "staggerMs: expected a non-negative number";
24592
+ const replaceSame = record["replaceSame"];
24593
+ if (replaceSame != null && typeof replaceSame !== "boolean") return "replaceSame: expected a boolean";
24564
24594
  const input = { ids };
24565
24595
  if (wait != null) input.wait = wait;
24566
24596
  if (staggerMs != null) input.staggerMs = staggerMs;
24597
+ if (replaceSame != null) input.replaceSame = replaceSame;
24567
24598
  return input;
24568
24599
  }
24569
24600
  function checkSetEnv(value) {
@@ -24802,7 +24833,7 @@ async function findDaemon(config) {
24802
24833
  async function findSkewedDaemon(config) {
24803
24834
  const skewed = await readSkewedInstanceRecord(commanderStatePaths(resolveCommanderDataDir(), config.configKey).instanceRecordPath, commanderStatusRealm.schemaHash);
24804
24835
  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";
24836
+ const difference = skewed.skew === "protocol" ? `speaks protocol v${skewed.protocolVersion}; this build speaks v7` : "was started before an upgrade changed the status schema";
24806
24837
  return {
24807
24838
  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
24839
  pid: skewed.pid,
@@ -24900,7 +24931,7 @@ async function connectDaemon(handle) {
24900
24931
  const payload = await (await runtime.handleActionPayload(request)).waitForResultPayload();
24901
24932
  if (!payload.result.ok) throw new CliExit(EXIT.failure, `action "${action}" rejected by the daemon`);
24902
24933
  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`);
24934
+ 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
24935
  return report;
24905
24936
  },
24906
24937
  setEnv: async (input) => {
@@ -24940,6 +24971,18 @@ function stateSymbol(out, state) {
24940
24971
  default: return out.paint("cyan", "▸");
24941
24972
  }
24942
24973
  }
24974
+ /** Where a ready process can be reached: its http endpoints' URLs, else its declared `url`. */
24975
+ function urlsOf(node) {
24976
+ if (node == null) return [];
24977
+ const urls = node.detail.endpoints.flatMap((endpoint) => endpoint.url != null ? [endpoint.url] : []);
24978
+ if (urls.length === 0 && node.detail.url != null) urls.push(node.detail.url);
24979
+ return urls;
24980
+ }
24981
+ /** `✓ web ready → http://localhost:3050` — the address is declared, so the line can carry it. */
24982
+ function reachLine(out, node) {
24983
+ const urls = urlsOf(node);
24984
+ return urls.length === 0 ? "" : ` → ${urls.map((url) => out.paint("cyan", url)).join(" ")}`;
24985
+ }
24943
24986
  /** Stream the transition narrative for the touched ids while an action runs. */
24944
24987
  async function withProgress(client, out, ids, run) {
24945
24988
  if (out.json || ids.size === 0) return run();
@@ -24952,7 +24995,8 @@ async function withProgress(client, out, ids, run) {
24952
24995
  const current = `${proc.state}${proc.blockedBy != null ? ` — ${proc.blockedBy}` : ""}`;
24953
24996
  if (last.get(id) === current) continue;
24954
24997
  last.set(id, current);
24955
- out.print(`${stateSymbol(out, proc.state)} ${out.accent(id, id)} ${current}`);
24998
+ const reach = proc.state === "ready" ? reachLine(out, proc) : "";
24999
+ out.print(`${stateSymbol(out, proc.state)} ${out.accent(id, id)} ${current}${reach}`);
24956
25000
  }
24957
25001
  };
24958
25002
  const off = client.realm.listenToPatches(() => note());
@@ -24971,13 +25015,36 @@ const NARRATED = new Set([
24971
25015
  "succeeded",
24972
25016
  "blocked"
24973
25017
  ]);
24974
- function printReport(out, report) {
24975
- if (out.json) out.printJson(report);
25018
+ /**
25019
+ * `--json` carries the generation's verdict as data: the action outcome per id, plus the state,
25020
+ * pid and endpoints the realm holds for it once the action has settled — so a script can decide
25021
+ * from one object what `status --json` would otherwise have to be asked for next.
25022
+ */
25023
+ function enrichReport(report, state) {
25024
+ return {
25025
+ results: report.results.map((result) => {
25026
+ const node = state.processes[result.id];
25027
+ return {
25028
+ ...result,
25029
+ state: node?.state ?? "unknown",
25030
+ ...node?.pid != null ? { pid: node.pid } : {},
25031
+ ...node?.blockedBy != null ? { blockedBy: node.blockedBy } : {},
25032
+ ...node?.startError != null ? { startError: node.startError } : {},
25033
+ endpoints: node?.detail.endpoints ?? [],
25034
+ urls: urlsOf(node)
25035
+ };
25036
+ }),
25037
+ warnings: report.warnings
25038
+ };
25039
+ }
25040
+ function printReport(out, report, state) {
25041
+ if (out.json) out.printJson(enrichReport(report, state));
24976
25042
  else {
24977
25043
  for (const result of report.results) {
24978
25044
  if (NARRATED.has(result.outcome)) continue;
24979
25045
  const note = result.reason != null ? ` — ${result.reason}` : "";
24980
- out.print(`${stateSymbol(out, result.outcome)} ${out.accent(result.id, result.id)} ${result.outcome}${note}`);
25046
+ const reach = result.outcome === "already-running" ? reachLine(out, state.processes[result.id]) : "";
25047
+ out.print(`${stateSymbol(out, result.outcome)} ${out.accent(result.id, result.id)} ${result.outcome}${note}${reach}`);
24981
25048
  }
24982
25049
  for (const warning of report.warnings) out.warn(`${out.paint("yellow", "⚠")} ${warning}`);
24983
25050
  }
@@ -24987,6 +25054,7 @@ async function cmdUp(ctx) {
24987
25054
  const bad = unknownFlags(ctx.args.flags, [
24988
25055
  "--no-wait",
24989
25056
  "--dry-run",
25057
+ "--replace-same",
24990
25058
  "--all",
24991
25059
  "--any"
24992
25060
  ]);
@@ -25011,12 +25079,14 @@ async function cmdUp(ctx) {
25011
25079
  try {
25012
25080
  const wait = !ctx.args.flags.has("--no-wait");
25013
25081
  const staggerMs = staggerFor(ctx.config, ctx.args.positionals);
25082
+ const replaceSame = ctx.args.flags.has("--replace-same");
25014
25083
  const report = await withProgress(client, ctx.out, new Set(selection.ordered), () => client.control("start", {
25015
25084
  ids: selection.ordered,
25016
25085
  wait,
25017
- ...staggerMs > 0 ? { staggerMs } : {}
25086
+ ...staggerMs > 0 ? { staggerMs } : {},
25087
+ ...replaceSame ? { replaceSame } : {}
25018
25088
  }));
25019
- return printReport(ctx.out, report);
25089
+ return printReport(ctx.out, report, client.state());
25020
25090
  } finally {
25021
25091
  client.dispose();
25022
25092
  }
@@ -25024,6 +25094,7 @@ async function cmdUp(ctx) {
25024
25094
  async function controlVerb(ctx, verb) {
25025
25095
  const known = verb === "restart" ? [
25026
25096
  "--no-wait",
25097
+ "--replace-same",
25027
25098
  "--all",
25028
25099
  "--any"
25029
25100
  ] : ["--all", "--any"];
@@ -25037,12 +25108,14 @@ async function controlVerb(ctx, verb) {
25037
25108
  bare: "required",
25038
25109
  extraIds: Object.keys(client.state().processes ?? {}).filter((id) => !declared.has(id))
25039
25110
  });
25111
+ const replaceSame = ctx.args.flags.has("--replace-same");
25040
25112
  const report = await withProgress(client, ctx.out, new Set(selection.ordered), () => verb === "stop" ? client.control("stop", { ids: selection.ordered }) : client.control("restart", {
25041
25113
  ids: selection.ordered,
25042
25114
  wait: !ctx.args.flags.has("--no-wait"),
25043
- staggerMs: staggerFor(ctx.config, ctx.args.positionals)
25115
+ staggerMs: staggerFor(ctx.config, ctx.args.positionals),
25116
+ ...replaceSame ? { replaceSame } : {}
25044
25117
  }));
25045
- return printReport(ctx.out, report);
25118
+ return printReport(ctx.out, report, client.state());
25046
25119
  } finally {
25047
25120
  client.dispose();
25048
25121
  }
@@ -25200,6 +25273,117 @@ function countOverrides(overrides) {
25200
25273
  return Object.values(overrides).reduce((total, values) => total + Object.keys(values).length, 0);
25201
25274
  }
25202
25275
  //#endregion
25276
+ //#region src/ports/definitionMatch.ts
25277
+ const exec$1 = (0, node_util.promisify)(node_child_process.execFile);
25278
+ /** How many parents above the listener are examined. Deeper than any dev-server wrapper stack. */
25279
+ const MAX_ANCESTRY = 8;
25280
+ const SHELLS = new Set([
25281
+ "sh",
25282
+ "bash",
25283
+ "zsh",
25284
+ "dash",
25285
+ "fish",
25286
+ "ksh"
25287
+ ]);
25288
+ /** argv as a single comparable string: argv[0] reduced to its basename, whitespace collapsed. */
25289
+ function canonicalCommand(args) {
25290
+ const tokens = args.trim().split(/\s+/).filter((token) => token !== "");
25291
+ if (tokens.length === 0) return "";
25292
+ tokens[0] = (0, node_path.basename)(tokens[0] ?? "");
25293
+ if (tokens.length >= 3 && SHELLS.has(tokens[0] ?? "") && tokens[1] === "-c") return tokens.slice(2).join(" ");
25294
+ return tokens.join(" ");
25295
+ }
25296
+ /** The definition's command in the same canonical form a live process's argv reduces to. */
25297
+ function definitionCommand(definition) {
25298
+ return canonicalCommand(typeof definition.run === "string" ? definition.run : definition.run.join(" "));
25299
+ }
25300
+ async function readIdentity(pid) {
25301
+ const match = (await exec$1("ps", [
25302
+ "-p",
25303
+ String(pid),
25304
+ "-o",
25305
+ "ppid=",
25306
+ "-o",
25307
+ "args="
25308
+ ], { timeout: 5e3 }).catch(() => null))?.stdout.trim().match(/^(\d+)\s+(.*)$/s);
25309
+ if (match == null) return null;
25310
+ const ppid = Number(match[1]);
25311
+ return {
25312
+ ppid: Number.isInteger(ppid) ? ppid : null,
25313
+ args: match[2] ?? ""
25314
+ };
25315
+ }
25316
+ async function readCwd(pid) {
25317
+ const line = (await exec$1("lsof", [
25318
+ "-a",
25319
+ "-p",
25320
+ String(pid),
25321
+ "-d",
25322
+ "cwd",
25323
+ "-Fn"
25324
+ ], { timeout: 5e3 }).catch(() => null))?.stdout.split("\n").find((entry) => entry.startsWith("n"));
25325
+ return line == null ? null : line.slice(1);
25326
+ }
25327
+ async function samePath(a, b) {
25328
+ if (a === b) return true;
25329
+ const [ra, rb] = await Promise.all([(0, node_fs_promises.realpath)(a).catch(() => a), (0, node_fs_promises.realpath)(b).catch(() => b)]);
25330
+ return ra === rb;
25331
+ }
25332
+ /**
25333
+ * Walk up from `listenerPid` looking for the definition's argv+cwd. Null when nothing in the
25334
+ * bounded ancestry matches, when the platform cannot answer (no `ps`/`lsof`), or when the walk
25335
+ * reaches a protected pid — commander itself and its ancestors are never part of a stray.
25336
+ */
25337
+ async function findStray(listenerPid, definition, protectedPids) {
25338
+ if (process.platform === "win32") return null;
25339
+ const wanted = definitionCommand(definition);
25340
+ if (wanted === "") return null;
25341
+ const chain = [];
25342
+ let pid = listenerPid;
25343
+ for (let depth = 0; depth <= MAX_ANCESTRY; depth += 1) {
25344
+ if (pid <= 1 || protectedPids.has(pid)) return null;
25345
+ const identity = await readIdentity(pid);
25346
+ if (identity == null) return null;
25347
+ const stamp = await (0, _nice_code_process.readProcessStartStamp)(pid);
25348
+ const member = {
25349
+ pid,
25350
+ startStamp: stamp?.stamp ?? null
25351
+ };
25352
+ chain.push(member);
25353
+ if (canonicalCommand(identity.args) === wanted) {
25354
+ const cwd = await readCwd(pid);
25355
+ if (cwd != null && await samePath(cwd, definition.cwd)) return {
25356
+ root: member,
25357
+ chain
25358
+ };
25359
+ }
25360
+ if (identity.ppid == null) return null;
25361
+ pid = identity.ppid;
25362
+ }
25363
+ return null;
25364
+ }
25365
+ /** Still the process we saw? A reused pid fails this and is left alone. */
25366
+ async function stillSame(member) {
25367
+ if (member.startStamp == null) return false;
25368
+ return (await (0, _nice_code_process.readProcessStartStamp)(member.pid))?.stamp === member.startStamp;
25369
+ }
25370
+ /**
25371
+ * Signal every verified member of the stray tree, root first (a wrapper such as `bun run`
25372
+ * forwards the signal and exits; signalling the leaf alone lets a watcher respawn it). Members
25373
+ * whose identity no longer checks out are skipped, never guessed at.
25374
+ */
25375
+ async function signalStray(stray, signal) {
25376
+ let signalled = 0;
25377
+ for (const member of [...stray.chain].reverse()) {
25378
+ if (!await stillSame(member)) continue;
25379
+ try {
25380
+ process.kill(member.pid, signal);
25381
+ signalled += 1;
25382
+ } catch {}
25383
+ }
25384
+ return signalled;
25385
+ }
25386
+ //#endregion
25203
25387
  //#region src/ports/listeners.ts
25204
25388
  const exec = (0, node_util.promisify)(node_child_process.execFile);
25205
25389
  const ACTIVE = new Set([
@@ -25289,6 +25473,7 @@ async function processDetails(pid) {
25289
25473
  cwd: cwd?.stdout.split("\n").find((l) => l.startsWith("n"))?.slice(1) ?? null
25290
25474
  };
25291
25475
  }
25476
+ /** Commander itself and everything above it — never a kill target, never part of a stray. */
25292
25477
  async function ancestors() {
25293
25478
  const result = [
25294
25479
  1,
@@ -25310,6 +25495,23 @@ async function ancestors() {
25310
25495
  }
25311
25496
  return result;
25312
25497
  }
25498
+ /**
25499
+ * The first visible listener on one exclusive endpoint, identified. Null when nothing local is
25500
+ * visible on it; throws where the platform cannot answer (no `lsof`, Windows) — the caller
25501
+ * falls back to "in use by something" rather than guessing.
25502
+ */
25503
+ async function identifyEndpointOwner(definition, endpoint, protectedPids) {
25504
+ const hosts = await localAddresses(endpoint.host);
25505
+ const owner = (await listeners(endpoint.port)).find((candidate) => addressMatches(candidate.address, endpoint.port, hosts) && !protectedPids.has(candidate.pid));
25506
+ if (owner == null) return null;
25507
+ const details = await processDetails(owner.pid);
25508
+ return {
25509
+ pid: owner.pid,
25510
+ command: details.command ?? owner.command,
25511
+ cwd: details.cwd,
25512
+ stray: await findStray(owner.pid, definition, protectedPids)
25513
+ };
25514
+ }
25313
25515
  /** Inspection and mutation share this service in the CLI and authenticated daemon control plane. */
25314
25516
  function createPortInspector(options) {
25315
25517
  const snapshots = /* @__PURE__ */ new Map();
@@ -25344,6 +25546,7 @@ function createPortInspector(options) {
25344
25546
  seen.add(owner.pid);
25345
25547
  const stamp = await (0, _nice_code_process.readProcessStartStamp)(owner.pid);
25346
25548
  const details = await processDetails(owner.pid);
25549
+ const stray = await findStray(owner.pid, proc, protectedPids);
25347
25550
  const managed = config.processes.some((p) => ACTIVE.has(states.get(p.id) ?? "") && p.endpoints.some((e) => e.port === endpoint.port));
25348
25551
  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
25552
  const listener = {
@@ -25356,6 +25559,8 @@ function createPortInspector(options) {
25356
25559
  ppid: details.ppid,
25357
25560
  cwd: details.cwd,
25358
25561
  startStamp: stamp?.stamp ?? null,
25562
+ stray: stray != null,
25563
+ strayRoot: stray?.root.pid ?? null,
25359
25564
  refusal,
25360
25565
  token: refusal == null ? (0, node_crypto.randomUUID)() : null
25361
25566
  };
@@ -25363,6 +25568,7 @@ function createPortInspector(options) {
25363
25568
  if (snapshots.size >= 1e3) snapshots.delete(snapshots.keys().next().value);
25364
25569
  snapshots.set(listener.token, {
25365
25570
  listener,
25571
+ stray,
25366
25572
  expires: Date.now() + 3e5
25367
25573
  });
25368
25574
  }
@@ -25385,7 +25591,7 @@ function createPortInspector(options) {
25385
25591
  };
25386
25592
  const target = snapshot.listener;
25387
25593
  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);
25594
+ 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
25595
  if (!current || current.refusal) return {
25390
25596
  listeners: fresh.listeners,
25391
25597
  warnings: [...fresh.warnings, current?.refusal ?? "Listener changed or exited; nothing was killed. Inspect ports again."]
@@ -25412,8 +25618,14 @@ function createPortInspector(options) {
25412
25618
  listeners: [],
25413
25619
  warnings: ["Process identity changed; nothing was killed."]
25414
25620
  };
25415
- try {
25416
- process.kill(target.pid, input.force ? "SIGKILL" : "SIGTERM");
25621
+ const signal = input.force ? "SIGKILL" : "SIGTERM";
25622
+ if (snapshot.stray != null) {
25623
+ if (await signalStray(snapshot.stray, signal) === 0) return {
25624
+ listeners: [],
25625
+ warnings: ["Stray tree already gone; nothing was killed."]
25626
+ };
25627
+ } else try {
25628
+ process.kill(target.pid, signal);
25417
25629
  } catch (error) {
25418
25630
  return {
25419
25631
  listeners: fresh.listeners,
@@ -25433,6 +25645,149 @@ function createPortInspector(options) {
25433
25645
  return { run };
25434
25646
  }
25435
25647
  //#endregion
25648
+ //#region src/cli/commands/ports.ts
25649
+ async function portProcessStates(ctx) {
25650
+ const handle = await findDaemon(ctx.config);
25651
+ if (!handle) return /* @__PURE__ */ new Map();
25652
+ const client = await connectDaemon(handle);
25653
+ try {
25654
+ return new Map(Object.entries(client.state().processes).map(([id, p]) => [id, p.state]));
25655
+ } finally {
25656
+ client.dispose();
25657
+ }
25658
+ }
25659
+ /** One row per listener; the STRAY column is the verdict that decides what a stop will end. */
25660
+ function renderListeners(ctx, result) {
25661
+ return ctx.out.table([
25662
+ "PROCESS",
25663
+ "ENDPOINT",
25664
+ "PID",
25665
+ "PARENT",
25666
+ "COMMAND",
25667
+ "CWD",
25668
+ "STRAY",
25669
+ "IDENTITY",
25670
+ "STOP"
25671
+ ], result.listeners.map((l) => [
25672
+ l.id,
25673
+ `${l.host}:${l.port}`,
25674
+ String(l.pid),
25675
+ String(l.ppid ?? "unknown"),
25676
+ l.command,
25677
+ l.cwd ?? "unavailable",
25678
+ strayCell(l),
25679
+ l.startStamp ?? "unknown",
25680
+ l.refusal ?? "available"
25681
+ ]));
25682
+ }
25683
+ function strayCell(listener) {
25684
+ if (!listener.stray) return "no";
25685
+ return listener.strayRoot != null && listener.strayRoot !== listener.pid ? `yes (root ${listener.strayRoot})` : "yes";
25686
+ }
25687
+ /** `[y/N]` on a TTY; scripts pass `--yes` or get a usage error, never a silent kill. */
25688
+ async function confirmKill(ctx, question, reportForRefusal) {
25689
+ if (ctx.args.flags.has("--yes")) return true;
25690
+ reportForRefusal();
25691
+ if (!process.stdin.isTTY || ctx.out.json) throw new CliExit(EXIT.usage, "Stopping requires interactive confirmation, or --yes for scripts");
25692
+ const rl = (0, node_readline_promises.createInterface)({
25693
+ input: process.stdin,
25694
+ output: process.stdout
25695
+ });
25696
+ try {
25697
+ const answer = await rl.question(`${question} [y/N] `);
25698
+ return /^y(es)?$/i.test(answer.trim());
25699
+ } finally {
25700
+ rl.close();
25701
+ }
25702
+ }
25703
+ async function cmdPorts(ctx) {
25704
+ const bad = unknownFlags(ctx.args.flags, [
25705
+ "--all",
25706
+ "--kill",
25707
+ "--kill-owner",
25708
+ "--yes",
25709
+ "--force"
25710
+ ]);
25711
+ if (bad) throw new CliExit(EXIT.usage, bad);
25712
+ const pid = numericFlag(ctx.args.flags, "--kill");
25713
+ if (pid != null && typeof pid !== "number") throw new CliExit(EXIT.usage, pid.error);
25714
+ for (const flag of [
25715
+ "--yes",
25716
+ "--force",
25717
+ "--all",
25718
+ "--kill-owner"
25719
+ ]) if (ctx.args.flags.has(flag) && ctx.args.flags.get(flag) !== true) throw new CliExit(EXIT.usage, `${flag} takes no value`);
25720
+ const killOwner = ctx.args.flags.has("--kill-owner");
25721
+ if (pid != null && killOwner) throw new CliExit(EXIT.usage, "--kill PID and --kill-owner are alternatives; pass one");
25722
+ 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");
25723
+ 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");
25724
+ const ids = ctx.args.positionals.length || ctx.args.flags.has("--all") ? selectOrExit(ctx, { bare: "required" }).direct : ctx.config.processes.map((p) => p.id);
25725
+ const inspector = createPortInspector({
25726
+ config: () => ctx.config,
25727
+ states: () => portProcessStates(ctx),
25728
+ protectedPids: async () => {
25729
+ const daemon = await findDaemon(ctx.config);
25730
+ return daemon ? [daemon.record.pid] : [];
25731
+ }
25732
+ });
25733
+ const report = await inspector.run({ ids });
25734
+ const print = (result) => {
25735
+ if (ctx.out.json) {
25736
+ ctx.out.printJson(result);
25737
+ return;
25738
+ }
25739
+ ctx.out.print(renderListeners(ctx, result));
25740
+ if (!result.listeners.length) ctx.out.print("No visible listeners on the selected exclusive TCP endpoints.");
25741
+ for (const warning of result.warnings) ctx.out.warn(warning);
25742
+ };
25743
+ const force = ctx.args.flags.has("--force");
25744
+ const verb = force ? "Force kill" : "Stop";
25745
+ 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}` : "");
25746
+ if (killOwner) {
25747
+ let current = report;
25748
+ const attempted = /* @__PURE__ */ new Set();
25749
+ const warnings = [];
25750
+ let stopped = 0;
25751
+ for (;;) {
25752
+ const target = current.listeners.find((l) => l.token != null && !attempted.has(l.pid));
25753
+ if (target?.token == null) break;
25754
+ attempted.add(target.pid);
25755
+ if (!await confirmKill(ctx, `${verb} ${describe(target)}?`, () => print(current))) continue;
25756
+ current = await inspector.run({
25757
+ ids,
25758
+ token: target.token,
25759
+ force
25760
+ });
25761
+ warnings.push(...current.warnings);
25762
+ if (!current.listeners.some((l) => l.pid === target.pid)) stopped += 1;
25763
+ }
25764
+ const refused = current.listeners.filter((l) => l.refusal != null);
25765
+ print({
25766
+ listeners: current.listeners,
25767
+ warnings: [...new Set(warnings)]
25768
+ });
25769
+ 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" : ""));
25770
+ return warnings.length > 0 || current.listeners.some((l) => l.token != null) ? EXIT.failure : EXIT.ok;
25771
+ }
25772
+ if (!pid) {
25773
+ print(report);
25774
+ return report.warnings.length ? EXIT.failure : EXIT.ok;
25775
+ }
25776
+ const target = report.listeners.find((l) => l.pid === pid);
25777
+ if (!target?.token) {
25778
+ print(report);
25779
+ throw new CliExit(EXIT.failure, target?.refusal ?? `PID ${pid} is not a verified listener on the selected endpoints`);
25780
+ }
25781
+ if (!await confirmKill(ctx, `${verb} ${describe(target)}?`, () => print(report))) return EXIT.ok;
25782
+ const result = await inspector.run({
25783
+ ids,
25784
+ token: target.token,
25785
+ force
25786
+ });
25787
+ print(result);
25788
+ return result.warnings.length ? EXIT.failure : EXIT.ok;
25789
+ }
25790
+ //#endregion
25436
25791
  //#region src/cli/commands/doctor.ts
25437
25792
  function formatAge(ms) {
25438
25793
  if (ms < 6e4) return `${Math.round(ms / 1e3)}s`;
@@ -25572,9 +25927,62 @@ async function diagnose(ctx, handle) {
25572
25927
  token: null
25573
25928
  }));
25574
25929
  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}\``}`);
25930
+ for (const owner of occupied.listeners) {
25931
+ 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`;
25932
+ 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}\``}`);
25933
+ }
25576
25934
  return report;
25577
25935
  }
25936
+ /**
25937
+ * `--reap-strays`: stop every stray on a configured exclusive port. Strangers are printed with
25938
+ * the same table and left where they are — the stray verdict (argv + cwd, identity re-checked
25939
+ * before every signal) is the only thing that authorizes a kill here.
25940
+ */
25941
+ async function reapStrays(ctx, handle) {
25942
+ const { out, config } = ctx;
25943
+ const stateById = handle != null ? await fetchProcessStates(handle) : /* @__PURE__ */ new Map();
25944
+ const ids = config.processes.filter((proc) => !ACTIVE_LIKE.has(stateById.get(proc.id) ?? "")).map((proc) => proc.id);
25945
+ const inspector = createPortInspector({
25946
+ config: () => config,
25947
+ states: async () => stateById,
25948
+ protectedPids: async () => handle ? [handle.record.pid] : []
25949
+ });
25950
+ const force = ctx.args.flags.has("--force");
25951
+ let current = await inspector.run({ ids });
25952
+ const attempted = /* @__PURE__ */ new Set();
25953
+ const warnings = [...current.warnings];
25954
+ let stopped = 0;
25955
+ for (;;) {
25956
+ const target = current.listeners.find((l) => l.stray && l.token != null && !attempted.has(l.pid));
25957
+ if (target?.token == null) break;
25958
+ attempted.add(target.pid);
25959
+ 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})` : ""}?`, () => {
25960
+ if (!out.json) out.print(renderListeners(ctx, current));
25961
+ })) continue;
25962
+ current = await inspector.run({
25963
+ ids,
25964
+ token: target.token,
25965
+ force
25966
+ });
25967
+ warnings.push(...current.warnings);
25968
+ if (!current.listeners.some((l) => l.pid === target.pid)) stopped += 1;
25969
+ }
25970
+ const strangers = current.listeners.filter((l) => !l.stray);
25971
+ if (out.json) out.printJson({
25972
+ stopped,
25973
+ listeners: current.listeners.map((l) => ({
25974
+ ...l,
25975
+ token: null
25976
+ })),
25977
+ warnings: [...new Set(warnings)]
25978
+ });
25979
+ else {
25980
+ out.print(`reap-strays: ${stopped} stray listener(s) stopped` + (strangers.length > 0 ? `, ${strangers.length} left alone (not this config's commands — see STRAY)` : ""));
25981
+ if (current.listeners.length > 0) out.print(renderListeners(ctx, current));
25982
+ for (const warning of new Set(warnings)) out.print(`${out.paint("yellow", "⚠")} ${warning}`);
25983
+ }
25984
+ return warnings.length > 0 || current.listeners.some((l) => l.stray && l.token != null) ? EXIT.failure : EXIT.ok;
25985
+ }
25578
25986
  const ACTIVE_LIKE = new Set([
25579
25987
  "starting",
25580
25988
  "running",
@@ -25591,9 +25999,22 @@ async function fetchProcessStates(handle) {
25591
25999
  }
25592
26000
  }
25593
26001
  async function cmdDoctor(ctx) {
25594
- const bad = unknownFlags(ctx.args.flags, ["--reap"]);
26002
+ const bad = unknownFlags(ctx.args.flags, [
26003
+ "--reap",
26004
+ "--reap-strays",
26005
+ "--yes",
26006
+ "--force"
26007
+ ]);
25595
26008
  if (bad != null) throw new CliExit(EXIT.usage, bad);
26009
+ for (const flag of [
26010
+ "--reap",
26011
+ "--reap-strays",
26012
+ "--yes",
26013
+ "--force"
26014
+ ]) if (ctx.args.flags.has(flag) && ctx.args.flags.get(flag) !== true) throw new CliExit(EXIT.usage, `${flag} takes no value`);
26015
+ 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
26016
  const handle = await findDaemon(ctx.config);
26017
+ if (ctx.args.flags.has("--reap-strays")) return reapStrays(ctx, handle);
25597
26018
  if (ctx.args.flags.has("--reap")) {
25598
26019
  const { out } = ctx;
25599
26020
  if (handle != null) {
@@ -25807,7 +26228,11 @@ async function cmdList(ctx) {
25807
26228
  return EXIT.ok;
25808
26229
  }
25809
26230
  async function cmdExplain(ctx) {
25810
- const bad = unknownFlags(ctx.args.flags, ["--all", "--any"]);
26231
+ const bad = unknownFlags(ctx.args.flags, [
26232
+ "--all",
26233
+ "--any",
26234
+ "--env"
26235
+ ]);
25811
26236
  if (bad != null) throw new CliExit(EXIT.usage, bad);
25812
26237
  const selection = selectOrExit(ctx, { bare: "default" });
25813
26238
  const { out } = ctx;
@@ -25824,6 +26249,10 @@ async function cmdExplain(ctx) {
25824
26249
  selection.ordered.forEach((id, index) => {
25825
26250
  out.print(` ${index + 1}. ${id}`);
25826
26251
  });
26252
+ if (!ctx.args.flags.has("--env")) {
26253
+ out.print(out.paint("gray", "env: `explain <sel> --env` shows each id's spawn environment"));
26254
+ return EXIT.ok;
26255
+ }
25827
26256
  const overrides = await readEnvOverrides(commanderStatePaths(resolveCommanderDataDir(), ctx.config.configKey).envOverridesPath);
25828
26257
  out.print("env:");
25829
26258
  out.print(" note: `run` children inherit THIS shell's environment; daemon-owned starts (`up`) inherit");
@@ -26072,102 +26501,6 @@ async function cmdLogs(ctx) {
26072
26501
  }
26073
26502
  }
26074
26503
  //#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
26504
  //#region src/run/scheduler.ts
26172
26505
  async function runTaskPool(options) {
26173
26506
  const { failFast } = options;
@@ -26602,6 +26935,7 @@ const SILENT_START_NOTE_MS = 15e3;
26602
26935
  function notesFor(proc, now) {
26603
26936
  const notes = [];
26604
26937
  if (proc.blockedBy != null) notes.push(`blocked: ${proc.blockedBy}`);
26938
+ if (proc.startError != null) notes.push(`start failed: ${proc.startError}`);
26605
26939
  if (proc.degradedBy.length > 0) notes.push(`degraded by ${proc.degradedBy.join(", ")}`);
26606
26940
  if (proc.unreadyReason != null) notes.push(`unready: ${proc.unreadyReason}`);
26607
26941
  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 +27172,42 @@ function mutateSavedFilters(current, change) {
26838
27172
  }
26839
27173
  //#endregion
26840
27174
  //#region src/cli.ts
26841
- const HELP = `nice-commander — one typed config, one control surface, for dev environments.
27175
+ const USAGE = `nice-commander — one typed config, one control surface, for dev environments.
26842
27176
 
26843
27177
  usage: nice-commander [--config <path>] [--json] [--no-color] [--timeout <ms>] [command] [selection] [flags]
26844
27178
 
26845
- With NO command, "ui" runs: the daemon is ensured and the browser opened. --help prints this text.
27179
+ With NO command, "ui" runs: the daemon is ensured and the browser opened. --help prints this text;
27180
+ <command> --help prints that command's section.
26846
27181
 
26847
27182
  selection: process ids, suite names, @pin names, tag=val, or --all. Several tag=val terms AND
26848
27183
  together; --any ORs them instead. A tag selection and --all never start an optIn process.
26849
27184
  Bare up/explain use the config's defaultSelection (or print the suites and exit);
26850
27185
  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
27186
+ `;
27187
+ /**
27188
+ * One entry per command, so `up --help` can answer with `up` alone. The full text is the usage
27189
+ * block followed by every entry, in this order.
27190
+ */
27191
+ const COMMAND_HELP = [
27192
+ ["up", ` up [sel] [--no-wait] [--dry-run] [--replace-same]
27193
+ start: deps auto-included, DAG order, live progress;
27194
+ a ready service prints its URL. --replace-same lets a
27195
+ start take an exclusive port from a STRAY — this same
27196
+ command in the same cwd, started outside the daemon
27197
+ (a stranger on the port still refuses). --json reports
27198
+ every id's outcome, state, pid and endpoints as data.`],
27199
+ ["down", " down <sel> stop (reverse-DAG order)"],
27200
+ ["restart", ` restart <sel> [--no-wait] [--replace-same]
27201
+ stop + start`],
27202
+ ["status", " status [--watch] table from the live status realm"],
27203
+ ["logs", " logs <sel> [-f] merged interleaved tail with colored id prefixes"],
27204
+ ["list", " list config introspection (processes, suites, warnings)"],
27205
+ ["explain", ` explain [sel] [--env] expanded ids, auto-included deps, DAG order, suite
27206
+ policy; --env adds each id's spawn environment`],
27207
+ ["env", ` env [sel] [--set N=V] [--unset N] declared env vars and their values; --clear drops
26861
27208
  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
27209
+ later start until cleared, and never restarts anything.`],
27210
+ ["run", ` run <sel> [--parallel N] [--fail-fast] foreground, no daemon; tasks = local CI shape
26864
27211
  (a suite supplies its own parallel/fail-fast),
26865
27212
  a single id gets raw inherited stdio (interactive).
26866
27213
  --fail-fast = stop at the FIRST failure and stop the
@@ -26868,20 +27215,40 @@ commands:
26868
27215
  failure is reported, and the exit code is still
26869
27216
  non-zero. Children inherit THIS shell's environment;
26870
27217
  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.
27218
+ boot-time snapshot instead — see doctor.`],
27219
+ ["ui", " ui ensure the daemon and open the browser (prints URL)"],
27220
+ ["doctor", ` doctor [--reap] [--reap-strays [--yes] [--force]]
27221
+ diagnostics: ledger, capability, endpoints (each port
27222
+ owner marked STRAY or not), env.
26874
27223
  --reap collects a crashed daemon's orphans NOW
26875
27224
  (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
-
27225
+ daemon is live). --reap-strays stops every stray —
27226
+ a listener that is this config's own command outside
27227
+ the daemon — after confirmation (--yes for scripts);
27228
+ strangers are listed and left alone.`],
27229
+ ["ports", ` ports [sel] [--kill PID | --kill-owner] [--yes] [--force]
27230
+ inspect exclusive TCP port owners (STRAY = this
27231
+ definition's own command outside the daemon).
27232
+ --kill PID stops that listener; --kill-owner stops
27233
+ whatever holds the selection's exclusive endpoints,
27234
+ no PID needed. Both prompt (--yes for scripts); a
27235
+ stray is stopped as its tree, a stranger only as the
27236
+ listener. --force sends SIGKILL instead of SIGTERM.`],
27237
+ ["shutdown", " shutdown stop the daemon (graceful ladder)"]
27238
+ ];
27239
+ const FOOTER = `
26882
27240
  status/down/logs/doctor/shutdown never start a missing daemon — they report "not running".
26883
27241
  exit codes: 0 ok · 1 failure · 2 usage · 3 daemon not running · 4 timeout
26884
27242
  `;
27243
+ const HELP = `${USAGE}
27244
+ commands:
27245
+ ${COMMAND_HELP.map(([, text]) => text).join("\n")}
27246
+ ${FOOTER}`;
27247
+ function helpFor(command) {
27248
+ const entry = command == null ? void 0 : COMMAND_HELP.find(([name]) => name === command);
27249
+ if (entry == null) return HELP;
27250
+ return `usage: nice-commander [--config <path>] [--json] [--no-color] [--timeout <ms>] ${entry[0]} …\n\n${entry[1]}\n${FOOTER}`;
27251
+ }
26885
27252
  const COMMANDS = {
26886
27253
  up: cmdUp,
26887
27254
  down: cmdDown,
@@ -26929,7 +27296,7 @@ async function withTimeout(ctx, run) {
26929
27296
  async function main() {
26930
27297
  const argv = process.argv.slice(2);
26931
27298
  if (argv[0] === "daemon") {
26932
- const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-D-StoxUH.cjs"));
27299
+ const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-DkrkRGT6.cjs"));
26933
27300
  return runCommanderDaemon(argv.slice(1));
26934
27301
  }
26935
27302
  const parsed = parseCliArgs(argv);
@@ -26938,7 +27305,7 @@ async function main() {
26938
27305
  return EXIT.usage;
26939
27306
  }
26940
27307
  if (parsed.help || parsed.command === "help") {
26941
- process.stdout.write(HELP);
27308
+ process.stdout.write(helpFor(parsed.command === "help" ? null : parsed.command));
26942
27309
  return EXIT.ok;
26943
27310
  }
26944
27311
  const requested = parsed.command ?? "ui";
@@ -26981,6 +27348,7 @@ exports.COMMANDER_TICKET_PATH = COMMANDER_TICKET_PATH;
26981
27348
  exports.COMMANDER_TICKET_PROTOCOL_PREFIX = COMMANDER_TICKET_PROTOCOL_PREFIX;
26982
27349
  exports.COMMANDER_WS_PATH = COMMANDER_WS_PATH;
26983
27350
  exports.RuntimeCoordinate = RuntimeCoordinate;
27351
+ exports.ancestors = ancestors;
26984
27352
  exports.applyEnvMutation = applyEnvMutation;
26985
27353
  exports.commanderChannel = commanderChannel;
26986
27354
  exports.commanderControlDomain = commanderControlDomain;
@@ -26999,6 +27367,7 @@ exports.ensureStateDir = ensureStateDir;
26999
27367
  exports.envVarViews = envVarViews;
27000
27368
  exports.hashCanonical = hashCanonical;
27001
27369
  exports.httpAcceptorCarrier = httpAcceptorCarrier;
27370
+ exports.identifyEndpointOwner = identifyEndpointOwner;
27002
27371
  exports.loadCommanderConfigFile = loadCommanderConfigFile;
27003
27372
  exports.mutateSavedFilters = mutateSavedFilters;
27004
27373
  exports.orderByDependency = orderByDependency;
@@ -27013,6 +27382,7 @@ exports.resolveCommanderDataDir = resolveCommanderDataDir;
27013
27382
  exports.runTaskPool = runTaskPool;
27014
27383
  exports.savedFilterId = savedFilterId;
27015
27384
  exports.serveChannel = serveChannel;
27385
+ exports.signalStray = signalStray;
27016
27386
  exports.stopSetWithDependencies = stopSetWithDependencies;
27017
27387
  exports.validateCommanderConfig = validateCommanderConfig;
27018
27388
  exports.withDependencies = withDependencies;