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