@nice-code/commander 0.79.0 → 0.81.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,16 +1,16 @@
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 { closeSync, existsSync, openSync, readFileSync, realpathSync, statSync } from "node:fs";
4
+ import { mkdir, open, readFile, rename, unlink, writeFile } from "node:fs/promises";
5
5
  import { dirname, isAbsolute, join, resolve } from "node:path";
6
+ import { createNiceProcess, detectCapability, openProcessLedger, readProcessStartStamp, signalProcessGroup, taskkillTree } from "@nice-code/process";
7
+ import { closeSync, existsSync, openSync, readFileSync, realpathSync, statSync } from "node:fs";
6
8
  import { pathToFileURL } from "node:url";
7
9
  import { createJiti } from "jiti";
8
10
  import { createHash, randomUUID, webcrypto } from "node:crypto";
9
11
  import { createRequire as createRequire$1 } from "module";
10
12
  import { WebSocket as WebSocket$1 } from "ws";
11
- import { mkdir, open, readFile, rename, unlink, writeFile } from "node:fs/promises";
12
13
  import { homedir } from "node:os";
13
- import { createNiceProcess, detectCapability, openProcessLedger, readProcessStartStamp, signalProcessGroup, taskkillTree } from "@nice-code/process";
14
14
  import { spawn } from "node:child_process";
15
15
  import { connect } from "node:net";
16
16
  //#region \0rolldown/runtime.js
@@ -125,6 +125,176 @@ function numericFlag(flags, name) {
125
125
  if (!Number.isInteger(parsed) || parsed < 1) return { error: `${name} needs a positive integer` };
126
126
  return parsed;
127
127
  }
128
+ /** Generous ceiling for every string field: real values are ids, hashes and one path. */
129
+ const MAX_FIELD_CHARS = 4096;
130
+ function boundedString(value) {
131
+ return typeof value === "string" && value.length <= MAX_FIELD_CHARS;
132
+ }
133
+ function boundedInt(value, min, max) {
134
+ return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
135
+ }
136
+ /** `startStamp` is compared against a freshly read one — a wrong shape must never compare equal. */
137
+ function validStartStamp(value) {
138
+ if (value == null) return true;
139
+ if (typeof value !== "object" || Array.isArray(value)) return false;
140
+ const stamp = value;
141
+ return boundedString(stamp["stamp"]) && (stamp["precision"] === "ticks" || stamp["precision"] === "seconds");
142
+ }
143
+ /**
144
+ * Bounded shape check. The record is read from a file this user's other processes write, so it is
145
+ * trusted-ish — but a truncated write, a stale schema, or a hand-edit must degrade to "no daemon"
146
+ * rather than feed a malformed value into the reuse path. Strings are length-capped so a corrupt
147
+ * record can't become a large allocation on every `readInstanceRecord`.
148
+ */
149
+ function isInstanceRecord(value) {
150
+ if (value == null || typeof value !== "object" || Array.isArray(value)) return false;
151
+ const record = value;
152
+ 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 === 3;
153
+ }
154
+ async function writeInstanceRecord(path, record) {
155
+ await mkdir(dirname(path), {
156
+ recursive: true,
157
+ mode: 448
158
+ });
159
+ const temp = `${path}.${process.pid}.tmp`;
160
+ await writeFile(temp, `${JSON.stringify(record, null, 2)}\n`, {
161
+ encoding: "utf8",
162
+ mode: 384
163
+ });
164
+ await rename(temp, path);
165
+ }
166
+ async function readInstanceRecord(path) {
167
+ try {
168
+ const parsed = JSON.parse(await readFile(path, "utf8"));
169
+ return isInstanceRecord(parsed) ? parsed : null;
170
+ } catch {
171
+ return null;
172
+ }
173
+ }
174
+ async function removeInstanceRecord(path) {
175
+ await unlink(path).catch(() => {});
176
+ }
177
+ /**
178
+ * A record written by a daemon this build cannot talk to (edge 18): a DIFFERENT protocol
179
+ * version, or — the 0.80.0 lesson — the SAME protocol version but a different status-realm
180
+ * schema hash (a schema change whose bump was forgotten; the realm layer would refuse the
181
+ * attach anyway, but with a raw hash mismatch instead of a name and a remedy).
182
+ *
183
+ * `readInstanceRecord` rejects both, which is right — but "invalid" and "absent" then look
184
+ * identical, so a plain `up` would boot a second daemon straight into the first one's port and
185
+ * report `EADDRINUSE`. That is a true statement about the wrong problem. Reading it separately
186
+ * is what lets the CLI say which daemon is in the way, and how to replace it. Nothing here
187
+ * authorizes a kill by itself: `signalDaemonShutdown` still verifies identity first.
188
+ */
189
+ async function readSkewedInstanceRecord(path, expectedRealmSchemaHash) {
190
+ let parsed;
191
+ try {
192
+ parsed = JSON.parse(await readFile(path, "utf8"));
193
+ } catch {
194
+ return null;
195
+ }
196
+ if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
197
+ const record = parsed;
198
+ if (record["service"] !== "nice-commander") return null;
199
+ if (!boundedInt(record["protocolVersion"], 0, Number.MAX_SAFE_INTEGER)) return null;
200
+ if (!boundedInt(record["pid"], 1, Number.MAX_SAFE_INTEGER)) return null;
201
+ if (!boundedInt(record["port"], 1, 65535)) return null;
202
+ const sameProtocol = record["protocolVersion"] === 3;
203
+ const sameRealm = boundedString(record["realmSchemaHash"]) && record["realmSchemaHash"] === expectedRealmSchemaHash;
204
+ if (sameProtocol && sameRealm) return null;
205
+ return {
206
+ pid: record["pid"],
207
+ port: record["port"],
208
+ protocolVersion: record["protocolVersion"],
209
+ packageVersion: boundedString(record["packageVersion"]) ? record["packageVersion"] : "unknown",
210
+ startStamp: validStartStamp(record["startStamp"]) ? record["startStamp"] ?? null : null,
211
+ skew: sameProtocol ? "realm-schema" : "protocol"
212
+ };
213
+ }
214
+ /** Liveness only — enough to say "something is there", never enough to authorize a kill (C1). */
215
+ function pidAlive$1(pid) {
216
+ try {
217
+ process.kill(pid, 0);
218
+ return true;
219
+ } catch (error) {
220
+ return error.code === "EPERM";
221
+ }
222
+ }
223
+ /**
224
+ * Is this record's daemon still the process it claims to be? pid alive AND startStamp equal —
225
+ * an unreadable stamp answers false (a reused pid must never be trusted).
226
+ */
227
+ async function recordDaemonAlive(record) {
228
+ try {
229
+ process.kill(record.pid, 0);
230
+ } catch (error) {
231
+ if (error.code !== "EPERM") return false;
232
+ }
233
+ if (record.startStamp == null) return true;
234
+ const stamp = await readProcessStartStamp(record.pid);
235
+ return stamp != null && stamp.stamp === record.startStamp.stamp;
236
+ }
237
+ /**
238
+ * Protocol-independent shutdown: verify the record's pid is still the daemon it claims to be
239
+ * (pid + startStamp — the ledger's own identity rule), then SIGTERM it. The daemon's signal
240
+ * handler runs the exact shutdown ladder `shutdown` would have asked for over the wire, so this
241
+ * is the remedy of last resort for a daemon a CLI cannot TALK to — a build from before a
242
+ * protocol or realm-schema change — without asking anyone to hunt pids by hand. A second call
243
+ * while it is still stopping escalates, mirroring the daemon's own two-signal contract.
244
+ *
245
+ * ⚠ `identity-unverified` is a refusal, not an error to work around: a recorded stamp that no
246
+ * longer matches means pid reuse, and a record with no stamp cannot prove the pid is ours.
247
+ */
248
+ async function signalDaemonShutdown(target, waitMs = 15e3) {
249
+ const { pid, startStamp } = target;
250
+ if (!pidAlive$1(pid)) return {
251
+ outcome: "not-running",
252
+ pid
253
+ };
254
+ if (startStamp == null) return {
255
+ outcome: "identity-unverified",
256
+ pid
257
+ };
258
+ const stamp = await readProcessStartStamp(pid);
259
+ if (stamp == null || stamp.stamp !== startStamp.stamp) return {
260
+ outcome: "identity-unverified",
261
+ pid
262
+ };
263
+ try {
264
+ process.kill(pid, "SIGTERM");
265
+ } catch {
266
+ return {
267
+ outcome: "not-running",
268
+ pid
269
+ };
270
+ }
271
+ const deadline = Date.now() + waitMs;
272
+ while (Date.now() < deadline) {
273
+ if (!pidAlive$1(pid)) return {
274
+ outcome: "exited",
275
+ pid
276
+ };
277
+ await new Promise((resolve) => setTimeout(resolve, 150));
278
+ }
279
+ return {
280
+ outcome: pidAlive$1(pid) ? "still-stopping" : "exited",
281
+ pid
282
+ };
283
+ }
284
+ /** Authed liveness probe — the final word on "reuse this daemon" (bounded). */
285
+ async function pingDaemon(record, timeoutMs = 2e3) {
286
+ try {
287
+ const response = await fetch(`http://127.0.0.1:${record.port}/health`, {
288
+ headers: { authorization: `Bearer ${record.token}` },
289
+ signal: AbortSignal.timeout(timeoutMs)
290
+ });
291
+ if (!response.ok) return null;
292
+ const body = await response.json();
293
+ return body.ok === true && body.configKey === record.configKey ? body : null;
294
+ } catch {
295
+ return null;
296
+ }
297
+ }
128
298
  //#endregion
129
299
  //#region src/config/resolve.ts
130
300
  /** Topological order of the given id set over the dependsOn graph; config order breaks ties. */
@@ -22887,122 +23057,103 @@ async function ensureStateDir(paths) {
22887
23057
  mode: 448
22888
23058
  });
22889
23059
  }
22890
- /** Generous ceiling for every string field: real values are ids, hashes and one path. */
22891
- const MAX_FIELD_CHARS = 4096;
22892
- function boundedString(value) {
22893
- return typeof value === "string" && value.length <= MAX_FIELD_CHARS;
22894
- }
22895
- function boundedInt(value, min, max) {
22896
- return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
22897
- }
22898
- /** `startStamp` is compared against a freshly read one — a wrong shape must never compare equal. */
22899
- function validStartStamp(value) {
22900
- if (value == null) return true;
22901
- if (typeof value !== "object" || Array.isArray(value)) return false;
22902
- const stamp = value;
22903
- return boundedString(stamp["stamp"]) && (stamp["precision"] === "ticks" || stamp["precision"] === "seconds");
22904
- }
22905
- /**
22906
- * Bounded shape check. The record is read from a file this user's other processes write, so it is
22907
- * trusted-ish — but a truncated write, a stale schema, or a hand-edit must degrade to "no daemon"
22908
- * rather than feed a malformed value into the reuse path. Strings are length-capped so a corrupt
22909
- * record can't become a large allocation on every `readInstanceRecord`.
22910
- */
22911
- function isInstanceRecord(value) {
22912
- if (value == null || typeof value !== "object" || Array.isArray(value)) return false;
22913
- const record = value;
22914
- 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) && validStartStamp(record.startStamp) && record.protocolVersion === 2;
22915
- }
22916
- async function writeInstanceRecord(path, record) {
22917
- await mkdir(dirname(path), {
22918
- recursive: true,
22919
- mode: 448
22920
- });
22921
- const temp = `${path}.${process.pid}.tmp`;
22922
- await writeFile(temp, `${JSON.stringify(record, null, 2)}\n`, {
22923
- encoding: "utf8",
22924
- mode: 384
22925
- });
22926
- await rename(temp, path);
22927
- }
22928
- async function readInstanceRecord(path) {
22929
- try {
22930
- const parsed = JSON.parse(await readFile(path, "utf8"));
22931
- return isInstanceRecord(parsed) ? parsed : null;
22932
- } catch {
22933
- return null;
22934
- }
22935
- }
22936
- async function removeInstanceRecord(path) {
22937
- await unlink(path).catch(() => {});
22938
- }
23060
+ //#endregion
23061
+ //#region src/daemon/packageVersion.ts
23062
+ let cached = null;
22939
23063
  /**
22940
- * A record written by a daemon speaking a DIFFERENT protocol version (edge 18).
22941
- *
22942
- * `readInstanceRecord` rejects it, which is right — we cannot talk to that daemon — but "invalid"
22943
- * and "absent" then look identical, so a plain `up` would boot a second daemon straight into the
22944
- * first one's port and report `EADDRINUSE`. That is a true statement about the wrong problem.
22945
- * Reading it separately is what lets the CLI say which daemon is in the way, and how to replace
22946
- * it. Nothing here authorizes a kill: an old daemon is a live execution lease like any other.
23064
+ * Resolved relative to the BUILT module, so the candidate list must cover every layout this
23065
+ * code ships in: `build/main-*.mjs` in the installed package (`../package.json` — the miss that
23066
+ * had every daemon reporting 0.0.0), and `src/daemon/*.ts` when run from sources (`../../`).
22947
23067
  */
22948
- async function readForeignInstanceRecord(path) {
22949
- let parsed;
22950
- try {
22951
- parsed = JSON.parse(await readFile(path, "utf8"));
22952
- } catch {
22953
- return null;
22954
- }
22955
- if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
22956
- const record = parsed;
22957
- if (record["service"] !== "nice-commander") return null;
22958
- if (!boundedInt(record["protocolVersion"], 0, Number.MAX_SAFE_INTEGER)) return null;
22959
- if (record["protocolVersion"] === 2) return null;
22960
- if (!boundedInt(record["pid"], 1, Number.MAX_SAFE_INTEGER)) return null;
22961
- if (!boundedInt(record["port"], 1, 65535)) return null;
22962
- return {
22963
- pid: record["pid"],
22964
- port: record["port"],
22965
- protocolVersion: record["protocolVersion"],
22966
- packageVersion: boundedString(record["packageVersion"]) ? record["packageVersion"] : "unknown"
22967
- };
22968
- }
22969
- /** Liveness only — enough to say "something is there", never enough to authorize a kill (C1). */
22970
- function pidAlive$1(pid) {
22971
- try {
22972
- process.kill(pid, 0);
22973
- return true;
22974
- } catch (error) {
22975
- return error.code === "EPERM";
22976
- }
23068
+ async function commanderPackageVersion() {
23069
+ if (cached != null) return cached;
23070
+ for (const candidate of [
23071
+ new URL("../package.json", import.meta.url),
23072
+ new URL("../../package.json", import.meta.url),
23073
+ new URL("../../../package.json", import.meta.url)
23074
+ ]) try {
23075
+ const parsed = JSON.parse(await readFile(candidate, "utf8"));
23076
+ if (typeof parsed.version === "string" && parsed.name === "@nice-code/commander") {
23077
+ cached = parsed.version;
23078
+ return cached;
23079
+ }
23080
+ } catch {}
23081
+ cached = "0.0.0";
23082
+ return cached;
22977
23083
  }
23084
+ //#endregion
23085
+ //#region src/protocol/statusRealm.ts
22978
23086
  /**
22979
- * Is this record's daemon still the process it claims to be? pid alive AND startStamp equal —
22980
- * an unreadable stamp answers false (a reused pid must never be trusted).
23087
+ * Read-only viewer for every authenticated identity — control authority lives in the ticket
23088
+ * gate at the upgrade, the realm floor (`authenticated`) just guarantees a real wire identity
23089
+ * behind every attach. No intents: clients never write.
22981
23090
  */
22982
- async function recordDaemonAlive(record) {
22983
- try {
22984
- process.kill(record.pid, 0);
22985
- } catch (error) {
22986
- if (error.code !== "EPERM") return false;
22987
- }
22988
- if (record.startStamp == null) return true;
22989
- const stamp = await readProcessStartStamp(record.pid);
22990
- return stamp != null && stamp.stamp === record.startStamp.stamp;
22991
- }
22992
- /** Authed liveness probe — the final word on "reuse this daemon" (bounded). */
22993
- async function pingDaemon(record, timeoutMs = 2e3) {
22994
- try {
22995
- const response = await fetch(`http://127.0.0.1:${record.port}/health`, {
22996
- headers: { authorization: `Bearer ${record.token}` },
22997
- signal: AbortSignal.timeout(timeoutMs)
22998
- });
22999
- if (!response.ok) return null;
23000
- const body = await response.json();
23001
- return body.ok === true && body.configKey === record.configKey ? body : null;
23002
- } catch {
23003
- return null;
23004
- }
23005
- }
23091
+ const commanderStatusRealm = defineRealm({
23092
+ id: "commander_status",
23093
+ avatars: { viewer: { persistentId: t.string() } },
23094
+ state: {
23095
+ generation: t.number(),
23096
+ configRevisionHash: t.string(),
23097
+ configError: t.array(t.string()),
23098
+ processes: t.record(t.id("processId"), t.object({
23099
+ kind: t.string(),
23100
+ state: t.string(),
23101
+ pid: t.optional(t.number()),
23102
+ startedAt: t.optional(t.number()),
23103
+ sawOutputAt: t.optional(t.number()),
23104
+ lastTask: t.optional(t.object({
23105
+ outcome: t.string(),
23106
+ reason: t.optional(t.string()),
23107
+ timedOut: t.boolean(),
23108
+ endedAt: t.number(),
23109
+ durationMs: t.optional(t.number())
23110
+ })),
23111
+ restarts: t.number(),
23112
+ lastExit: t.optional(t.object({
23113
+ code: t.optional(t.number()),
23114
+ signal: t.optional(t.string()),
23115
+ expected: t.boolean()
23116
+ })),
23117
+ stale: t.boolean(),
23118
+ removed: t.boolean(),
23119
+ envDrift: t.boolean(),
23120
+ blockedBy: t.optional(t.string()),
23121
+ degradedBy: t.array(t.string()),
23122
+ unreadyReason: t.optional(t.string()),
23123
+ capability: t.optional(t.object({
23124
+ treeMechanism: t.string(),
23125
+ degraded: t.boolean(),
23126
+ notes: t.array(t.string())
23127
+ })),
23128
+ tags: t.record(t.id("tag"), t.string()),
23129
+ detail: t.object({
23130
+ command: t.string(),
23131
+ cwd: t.string(),
23132
+ dependsOn: t.array(t.string()),
23133
+ ready: t.optional(t.string()),
23134
+ endpoints: t.array(t.object({
23135
+ name: t.string(),
23136
+ protocol: t.string(),
23137
+ host: t.string(),
23138
+ port: t.number(),
23139
+ ownership: t.string(),
23140
+ url: t.optional(t.string())
23141
+ })),
23142
+ envVars: t.array(t.object({
23143
+ name: t.string(),
23144
+ description: t.optional(t.string()),
23145
+ secret: t.boolean(),
23146
+ required: t.boolean(),
23147
+ values: t.optional(t.array(t.string())),
23148
+ source: t.string(),
23149
+ value: t.optional(t.string())
23150
+ }))
23151
+ })
23152
+ })),
23153
+ groups: t.record(t.id("groupName"), t.object({ members: t.array(t.string()) }))
23154
+ },
23155
+ rules: (r) => [r.path("**").view(r.everyone).alter(r.serverOnly)]
23156
+ });
23006
23157
  //#endregion
23007
23158
  //#region src/daemon/lockfile.ts
23008
23159
  const LOCK_RETRY_LIMIT = 250;
@@ -23125,22 +23276,55 @@ var CommanderDaemonBootError = class extends Error {
23125
23276
  this.name = "CommanderDaemonBootError";
23126
23277
  }
23127
23278
  };
23279
+ /**
23280
+ * Stop a skewed daemon so the boot below can proceed — ONLY when nothing of it is running.
23281
+ * "Running" is answered by the ledger, the one surface both builds share regardless of wire
23282
+ * protocol: any record whose pid is alive (a supervised child, or a foreground `run` lease) is
23283
+ * a live dev environment, and an upgrade must never be the thing that kills one.
23284
+ */
23285
+ async function replaceSkewedDaemon(paths, skewed) {
23286
+ const daemonLabel = `the daemon for this config (pid ${skewed.pid}, build ${skewed.packageVersion}, protocol v${skewed.protocolVersion}) predates this CLI (protocol v3${skewed.skew === "realm-schema" ? ", different status schema" : ""})`;
23287
+ let liveIds = [];
23288
+ try {
23289
+ liveIds = (await openProcessLedger({
23290
+ dir: paths.stateDir,
23291
+ namespace: paths.ledgerNamespace
23292
+ }).list()).filter((record) => pidAlive$1(record.pid)).map((record) => record.id);
23293
+ } catch {
23294
+ throw new Error(`${daemonLabel}, and its ledger could not be read to prove nothing is running. Run \`nice-commander shutdown\` (it stops the daemon and everything it runs), then retry.`);
23295
+ }
23296
+ if (liveIds.length > 0) throw new Error(`${daemonLabel} and is still running: ${liveIds.join(", ")}. Replacing it would stop them. Run \`nice-commander shutdown\` when you are ready (it stops the daemon and everything it runs), then \`up\` again.`);
23297
+ switch ((await signalDaemonShutdown({
23298
+ pid: skewed.pid,
23299
+ startStamp: skewed.startStamp
23300
+ })).outcome) {
23301
+ case "exited": return {
23302
+ pid: skewed.pid,
23303
+ packageVersion: skewed.packageVersion
23304
+ };
23305
+ case "not-running": return;
23306
+ case "still-stopping": throw new Error(`${daemonLabel}; nothing of it is running, so it was asked to shut down — but it is still stopping. Retry in a moment (a second attempt escalates).`);
23307
+ case "identity-unverified": throw new Error(`${daemonLabel}, but pid ${skewed.pid} could not be verified as that daemon (start stamp missing or changed — possibly pid reuse). Nothing was killed. Verify the pid yourself, and if the daemon is really gone remove ${paths.instanceRecordPath}.`);
23308
+ }
23309
+ }
23128
23310
  async function ensureDaemon(options) {
23129
23311
  const dataDir = options.dataDir != null ? resolve(options.dataDir) : resolveCommanderDataDir();
23130
23312
  const paths = commanderStatePaths(dataDir, options.config.configKey);
23131
23313
  const timeoutMs = options.handshakeTimeoutMs ?? HANDSHAKE_TIMEOUT_MS;
23132
23314
  return withCommanderLock(paths.upLockPath, async () => {
23133
23315
  const existing = await readInstanceRecord(paths.instanceRecordPath);
23134
- if (existing != null && await recordDaemonAlive(existing)) {
23316
+ const compatible = existing != null && existing.realmSchemaHash === commanderStatusRealm.schemaHash;
23317
+ if (compatible && await recordDaemonAlive(existing)) {
23135
23318
  if (await pingDaemon(existing) != null) return {
23136
23319
  record: existing,
23137
23320
  reused: true,
23138
23321
  paths
23139
23322
  };
23140
23323
  }
23141
- if (existing == null) {
23142
- const foreign = await readForeignInstanceRecord(paths.instanceRecordPath);
23143
- if (foreign != null && pidAlive$1(foreign.pid)) throw new Error(`a nice-commander daemon speaking protocol v${foreign.protocolVersion} (package ${foreign.packageVersion}) is already running for this config — pid ${foreign.pid}, port ${foreign.port}. This build speaks v2 and cannot talk to it. Stop it with that version's \`nice-commander shutdown\`, or end pid ${foreign.pid} yourself; if it is already gone, remove ${paths.instanceRecordPath}.`);
23324
+ let replaced;
23325
+ if (!compatible) {
23326
+ const skewed = await readSkewedInstanceRecord(paths.instanceRecordPath, commanderStatusRealm.schemaHash);
23327
+ if (skewed != null && pidAlive$1(skewed.pid)) replaced = await replaceSkewedDaemon(paths, skewed);
23144
23328
  }
23145
23329
  await ensureStateDir(paths);
23146
23330
  const bootFd = openSync(paths.bootLogPath, "w", 384);
@@ -23175,7 +23359,8 @@ async function ensureDaemon(options) {
23175
23359
  if (await pingDaemon(record) != null) return {
23176
23360
  record,
23177
23361
  reused: false,
23178
- paths
23362
+ paths,
23363
+ ...replaced != null ? { replaced } : {}
23179
23364
  };
23180
23365
  }
23181
23366
  if (exited != null) {
@@ -23397,71 +23582,6 @@ const commanderChannel = defineChannel({
23397
23582
  toConnector: []
23398
23583
  });
23399
23584
  //#endregion
23400
- //#region src/protocol/statusRealm.ts
23401
- /**
23402
- * Read-only viewer for every authenticated identity — control authority lives in the ticket
23403
- * gate at the upgrade, the realm floor (`authenticated`) just guarantees a real wire identity
23404
- * behind every attach. No intents: clients never write.
23405
- */
23406
- const commanderStatusRealm = defineRealm({
23407
- id: "commander_status",
23408
- avatars: { viewer: { persistentId: t.string() } },
23409
- state: {
23410
- generation: t.number(),
23411
- configRevisionHash: t.string(),
23412
- configError: t.array(t.string()),
23413
- processes: t.record(t.id("processId"), t.object({
23414
- kind: t.string(),
23415
- state: t.string(),
23416
- pid: t.optional(t.number()),
23417
- startedAt: t.optional(t.number()),
23418
- restarts: t.number(),
23419
- lastExit: t.optional(t.object({
23420
- code: t.optional(t.number()),
23421
- signal: t.optional(t.string()),
23422
- expected: t.boolean()
23423
- })),
23424
- stale: t.boolean(),
23425
- removed: t.boolean(),
23426
- envDrift: t.boolean(),
23427
- blockedBy: t.optional(t.string()),
23428
- degradedBy: t.array(t.string()),
23429
- unreadyReason: t.optional(t.string()),
23430
- capability: t.optional(t.object({
23431
- treeMechanism: t.string(),
23432
- degraded: t.boolean(),
23433
- notes: t.array(t.string())
23434
- })),
23435
- tags: t.record(t.id("tag"), t.string()),
23436
- detail: t.object({
23437
- command: t.string(),
23438
- cwd: t.string(),
23439
- dependsOn: t.array(t.string()),
23440
- ready: t.optional(t.string()),
23441
- endpoints: t.array(t.object({
23442
- name: t.string(),
23443
- protocol: t.string(),
23444
- host: t.string(),
23445
- port: t.number(),
23446
- ownership: t.string(),
23447
- url: t.optional(t.string())
23448
- })),
23449
- envVars: t.array(t.object({
23450
- name: t.string(),
23451
- description: t.optional(t.string()),
23452
- secret: t.boolean(),
23453
- required: t.boolean(),
23454
- values: t.optional(t.array(t.string())),
23455
- source: t.string(),
23456
- value: t.optional(t.string())
23457
- }))
23458
- })
23459
- })),
23460
- groups: t.record(t.id("groupName"), t.object({ members: t.array(t.string()) }))
23461
- },
23462
- rules: (r) => [r.path("**").view(r.everyone).alter(r.serverOnly)]
23463
- });
23464
- //#endregion
23465
23585
  //#region src/cli/daemonClient.ts
23466
23586
  /** The running daemon for this config, or null (dead record, failed ping, nothing on disk). */
23467
23587
  async function findDaemon(config) {
@@ -23474,12 +23594,28 @@ async function findDaemon(config) {
23474
23594
  spawned: false
23475
23595
  } : null;
23476
23596
  }
23597
+ /**
23598
+ * A daemon this build cannot talk to is IN THE WAY, not absent — the same distinction `up`
23599
+ * makes (edge 18). Reporting "not running" while one plainly IS sends you to `up`, which then
23600
+ * fails on something else entirely. The remedy is always the same and always THIS build's:
23601
+ * `shutdown` falls back to a verified signal when it cannot speak to the daemon.
23602
+ */
23603
+ async function findSkewedDaemon(config) {
23604
+ const skewed = await readSkewedInstanceRecord(commanderStatePaths(resolveCommanderDataDir(), config.configKey).instanceRecordPath, commanderStatusRealm.schemaHash);
23605
+ if (skewed == null || !pidAlive$1(skewed.pid)) return null;
23606
+ const difference = skewed.skew === "protocol" ? `speaks protocol v${skewed.protocolVersion}; this build speaks v3` : "was started before an upgrade changed the status schema";
23607
+ return {
23608
+ 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.`,
23609
+ pid: skewed.pid,
23610
+ startStamp: skewed.startStamp
23611
+ };
23612
+ }
23477
23613
  /** Read-only commands' daemon-or-report: never starts anything, exit 3 when not running. */
23478
23614
  async function requireDaemon(config) {
23479
23615
  const handle = await findDaemon(config);
23480
23616
  if (handle != null) return handle;
23481
- const foreign = await readForeignInstanceRecord(commanderStatePaths(resolveCommanderDataDir(), config.configKey).instanceRecordPath);
23482
- if (foreign != null && pidAlive$1(foreign.pid)) throw new CliExit(EXIT.notRunning, `a nice-commander daemon speaking protocol v${foreign.protocolVersion} (package ${foreign.packageVersion}) is running for this config — pid ${foreign.pid}, port ${foreign.port}. This build speaks v2 and cannot read its state. Stop it with that version's \`nice-commander shutdown\`, then \`up\` again.`);
23617
+ const skewed = await findSkewedDaemon(config);
23618
+ if (skewed != null) throw new CliExit(EXIT.notRunning, skewed.message);
23483
23619
  throw new CliExit(EXIT.notRunning, `daemon not running for "${config.name}" (start one with \`up\`)`);
23484
23620
  }
23485
23621
  /** `up`/`ui`'s spawn-or-reuse; the daemon child reruns THIS bin (`daemon` subcommand). */
@@ -23491,7 +23627,8 @@ async function ensureDaemonRunning(config) {
23491
23627
  return {
23492
23628
  record: result.record,
23493
23629
  paths: result.paths,
23494
- spawned: !result.reused
23630
+ spawned: !result.reused,
23631
+ ...result.replaced != null ? { replaced: result.replaced } : {}
23495
23632
  };
23496
23633
  }
23497
23634
  async function mintTicket(record) {
@@ -23512,6 +23649,7 @@ async function mintTicket(record) {
23512
23649
  }
23513
23650
  async function connectDaemon(handle) {
23514
23651
  const { record } = handle;
23652
+ if (record.realmSchemaHash !== commanderStatusRealm.schemaHash) throw new CliExit(EXIT.failure, `the daemon for this config (pid ${record.pid}, build ${record.packageVersion}) was started before an upgrade changed the status schema — this CLI (build ${await commanderPackageVersion()}) cannot read its state. Run \`nice-commander shutdown\` (it stops a daemon from any build), then retry.`);
23515
23653
  const ticket = await mintTicket(record);
23516
23654
  const runtime = new ActionRuntime(RuntimeCoordinate.env("commander_cli").withPersistentId(`cli-${randomUUID().slice(0, 8)}`));
23517
23655
  const connector = connectChannel(runtime, commanderChannel, {
@@ -23549,7 +23687,8 @@ async function connectDaemon(handle) {
23549
23687
  } catch {
23550
23688
  connector.dispose();
23551
23689
  const reason = realm.attachError != null ? String(realm.attachError) : "timeout";
23552
- throw new CliExit(EXIT.failure, `could not attach the status realm (${reason})`);
23690
+ const hint = reason.includes("schema_mismatch") ? ` The daemon (pid ${record.pid}, build ${record.packageVersion}) and this CLI were built from different realm definitions — run \`nice-commander shutdown\` (it stops a daemon from any build), then retry.` : "";
23691
+ throw new CliExit(EXIT.failure, `could not attach the status realm (${reason}).${hint}`);
23553
23692
  }
23554
23693
  return {
23555
23694
  record,
@@ -23560,7 +23699,7 @@ async function connectDaemon(handle) {
23560
23699
  const payload = await (await runtime.handleActionPayload(request)).waitForResultPayload();
23561
23700
  if (!payload.result.ok) throw new CliExit(EXIT.failure, `action "${action}" rejected by the daemon`);
23562
23701
  const report = parseActionReport(payload.result.output);
23563
- if (report == null) throw new CliExit(EXIT.failure, `the daemon answered "${action}" with something this CLI does not recognise — protocol ${record.protocolVersion} vs 2`);
23702
+ if (report == null) throw new CliExit(EXIT.failure, `the daemon answered "${action}" with something this CLI does not recognise — protocol ${record.protocolVersion} vs 3`);
23564
23703
  return report;
23565
23704
  },
23566
23705
  setEnv: async (input) => {
@@ -23665,6 +23804,7 @@ async function cmdUp(ctx) {
23665
23804
  }
23666
23805
  const handle = await ensureDaemonRunning(ctx.config);
23667
23806
  ctx.spawnedDaemon = handle.spawned;
23807
+ if (handle.replaced != null && !ctx.out.json) ctx.out.print(ctx.out.paint("gray", `· replaced the previous daemon (pid ${handle.replaced.pid}, build ${handle.replaced.packageVersion}) — it predated this CLI and nothing was running`));
23668
23808
  const client = await connectDaemon(handle);
23669
23809
  try {
23670
23810
  const wait = !ctx.args.flags.has("--no-wait");
@@ -23707,17 +23847,71 @@ async function cmdDown(ctx) {
23707
23847
  async function cmdRestart(ctx) {
23708
23848
  return controlVerb(ctx, "restart");
23709
23849
  }
23850
+ /**
23851
+ * `shutdown` must be the command that ALWAYS works — it is the remedy every skew message names.
23852
+ * The wire is tried first (the graceful ask); when the daemon cannot be talked to — another
23853
+ * build's protocol, a changed realm schema, a wedged socket — it falls back to a verified
23854
+ * SIGTERM, which runs the daemon's own shutdown ladder. Without this fallback, the one command
23855
+ * that fixes "the CLI cannot talk to the daemon" was itself behind that same wall.
23856
+ */
23710
23857
  async function cmdShutdown(ctx) {
23711
23858
  const bad = unknownFlags(ctx.args.flags, []);
23712
23859
  if (bad != null) throw new CliExit(EXIT.usage, bad);
23713
- const client = await connectDaemon(await requireDaemon(ctx.config));
23714
- try {
23715
- await client.shutdown();
23716
- if (ctx.out.json) ctx.out.printJson({ ok: true });
23717
- else ctx.out.print(`daemon for "${ctx.config.name}" is shutting down`);
23718
- return EXIT.ok;
23719
- } finally {
23720
- client.dispose();
23860
+ const { out } = ctx;
23861
+ const handle = await findDaemon(ctx.config);
23862
+ if (handle != null) try {
23863
+ const client = await connectDaemon(handle);
23864
+ try {
23865
+ await client.shutdown();
23866
+ if (out.json) out.printJson({
23867
+ ok: true,
23868
+ via: "wire"
23869
+ });
23870
+ else out.print(`daemon for "${ctx.config.name}" is shutting down`);
23871
+ return EXIT.ok;
23872
+ } finally {
23873
+ client.dispose();
23874
+ }
23875
+ } catch (error) {
23876
+ if (!(error instanceof CliExit)) throw error;
23877
+ return reportSignalShutdown(ctx, await signalDaemonShutdown({
23878
+ pid: handle.record.pid,
23879
+ startStamp: handle.record.startStamp
23880
+ }));
23881
+ }
23882
+ const skewed = await findSkewedDaemon(ctx.config);
23883
+ if (skewed != null) {
23884
+ if (!out.json) out.print(out.paint("gray", skewed.message));
23885
+ return reportSignalShutdown(ctx, await signalDaemonShutdown({
23886
+ pid: skewed.pid,
23887
+ startStamp: skewed.startStamp
23888
+ }));
23889
+ }
23890
+ throw new CliExit(EXIT.notRunning, `daemon not running for "${ctx.config.name}"`);
23891
+ }
23892
+ function reportSignalShutdown(ctx, result) {
23893
+ const { out } = ctx;
23894
+ if (out.json) {
23895
+ out.printJson({
23896
+ ok: result.outcome === "exited",
23897
+ via: "signal",
23898
+ ...result
23899
+ });
23900
+ return result.outcome === "exited" ? EXIT.ok : EXIT.failure;
23901
+ }
23902
+ switch (result.outcome) {
23903
+ case "exited":
23904
+ out.print(`daemon for "${ctx.config.name}" (pid ${result.pid}) could not be reached over the wire — stopped via signal (its own shutdown ladder ran)`);
23905
+ return EXIT.ok;
23906
+ case "still-stopping":
23907
+ out.print(out.paint("yellow", `⚠ daemon (pid ${result.pid}) was signalled and is still stopping — run \`shutdown\` again to escalate if it stays stuck`));
23908
+ return EXIT.failure;
23909
+ case "identity-unverified":
23910
+ out.print(out.paint("yellow", `⚠ pid ${result.pid} could not be verified as the recorded daemon (start stamp missing or changed — possibly pid reuse). Nothing was killed; verify the pid yourself, and remove the instance record if the daemon is really gone.`));
23911
+ return EXIT.failure;
23912
+ case "not-running":
23913
+ out.print(`daemon not running for "${ctx.config.name}" (stale record)`);
23914
+ return EXIT.ok;
23721
23915
  }
23722
23916
  }
23723
23917
  //#endregion
@@ -23857,6 +24051,10 @@ async function diagnose(ctx, handle) {
23857
24051
  };
23858
24052
  const paths = commanderStatePaths(resolveCommanderDataDir(), config.configKey);
23859
24053
  report.info.push(handle != null ? `daemon: running (pid ${handle.record.pid}, port ${handle.record.port}, generation ${handle.record.generation})` : `daemon: not running`);
24054
+ if (handle == null) {
24055
+ const skewed = await findSkewedDaemon(config);
24056
+ if (skewed != null) report.warnings.push(skewed.message);
24057
+ }
23860
24058
  if (handle != null) {
23861
24059
  const ping = await pingDaemon(handle.record).catch(() => null);
23862
24060
  if (ping != null) report.info.push(`daemon env snapshot: ${formatAge(ping.uptimeMs)} old — children inherit the environment the daemon booted with; restart it (\`nice-commander shutdown\` then \`up\`) to pick up a changed PATH, toolchain or global env`);
@@ -24422,7 +24620,7 @@ async function cmdLogs(ctx) {
24422
24620
  }
24423
24621
  //#endregion
24424
24622
  //#region src/cli/commands/run.ts
24425
- const ACTIVE_STATES = new Set([
24623
+ const ACTIVE_STATES$1 = new Set([
24426
24624
  "starting",
24427
24625
  "running",
24428
24626
  "ready",
@@ -24510,7 +24708,7 @@ async function cmdRun(ctx) {
24510
24708
  if (handle != null) {
24511
24709
  const client = await connectDaemon(handle);
24512
24710
  try {
24513
- const owned = defs.filter((def) => ACTIVE_STATES.has(client.state().processes[def.id]?.state ?? ""));
24711
+ const owned = defs.filter((def) => ACTIVE_STATES$1.has(client.state().processes[def.id]?.state ?? ""));
24514
24712
  if (owned.length > 0) throw new CliExit(EXIT.failure, `"${owned.map((def) => def.id).join("\", \"")}" is owned by the running daemon — \`down\` it there first (silent double-start is never allowed).`);
24515
24713
  } finally {
24516
24714
  client.dispose();
@@ -24729,7 +24927,7 @@ async function cmdRun(ctx) {
24729
24927
  }
24730
24928
  for (const depId of def.dependsOn) {
24731
24929
  const dep = procs.find((candidate) => candidate.id === depId);
24732
- if (dep != null && byId.get(depId)?.kind === "service" && ACTIVE_STATES.has(dep.state)) await dep.whenReady().catch(() => {
24930
+ if (dep != null && byId.get(depId)?.kind === "service" && ACTIVE_STATES$1.has(dep.state)) await dep.whenReady().catch(() => {
24733
24931
  out.warn(out.paint("yellow", `⚠ dependency "${depId}" did not become ready — starting anyway`));
24734
24932
  });
24735
24933
  }
@@ -24812,28 +25010,54 @@ function formatUptime(sinceMs, now = Date.now()) {
24812
25010
  }
24813
25011
  //#endregion
24814
25012
  //#region src/cli/commands/status.ts
24815
- function notesFor(proc) {
25013
+ const ACTIVE_STATES = new Set([
25014
+ "starting",
25015
+ "running",
25016
+ "ready",
25017
+ "unready",
25018
+ "backoff",
25019
+ "stopping"
25020
+ ]);
25021
+ /** Beyond this, a run that has printed nothing reads as wedged, not quiet — say so. */
25022
+ const SILENT_START_NOTE_MS = 15e3;
25023
+ function notesFor(proc, now) {
24816
25024
  const notes = [];
24817
25025
  if (proc.blockedBy != null) notes.push(`blocked: ${proc.blockedBy}`);
24818
25026
  if (proc.degradedBy.length > 0) notes.push(`degraded by ${proc.degradedBy.join(", ")}`);
24819
25027
  if (proc.unreadyReason != null) notes.push(`unready: ${proc.unreadyReason}`);
25028
+ 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)})`);
25029
+ const lastTask = proc.lastTask;
25030
+ if (!ACTIVE_STATES.has(proc.state) && lastTask?.outcome === "failed" && lastTask.reason != null) notes.push(`last run failed: ${lastTask.reason} (${formatUptime(lastTask.endedAt, now)} ago)`);
24820
25031
  if (proc.stale) notes.push("stale (config changed — restart to apply)");
24821
25032
  const sticky = proc.detail.envVars.filter((declared) => declared.source === "override").length;
24822
25033
  if (sticky > 0) notes.push(`${sticky} sticky env override${sticky === 1 ? "" : "s"} (see \`env\`)`);
24823
25034
  if (proc.envDrift) notes.push("env override changed — restart to apply");
24824
25035
  if (proc.removed) notes.push("removed from config");
24825
- if (proc.capability?.degraded === true) notes.push(proc.capability.treeMechanism);
24826
25036
  return notes.join("; ");
24827
25037
  }
25038
+ /**
25039
+ * Degraded tree ownership is a host-wide fact (every process shares one mechanism), so it prints
25040
+ * once under the table instead of drowning every row's NOTES — on WSL that would be every row.
25041
+ */
25042
+ function capabilityFooter(state) {
25043
+ const seen = /* @__PURE__ */ new Set();
25044
+ for (const proc of Object.values(state.processes)) {
25045
+ if (proc.capability?.degraded !== true) continue;
25046
+ const notes = proc.capability.notes.length > 0 ? `: ${proc.capability.notes.join(" ")}` : "";
25047
+ seen.add(`⚠ tree ownership degraded (${proc.capability.treeMechanism})${notes}`);
25048
+ }
25049
+ return [...seen].map((line) => `\n${line}`).join("");
25050
+ }
24828
25051
  function renderTable(out, state) {
25052
+ const now = Date.now();
24829
25053
  const rows = Object.entries(state.processes).map(([id, proc]) => [
24830
25054
  id,
24831
25055
  proc.kind,
24832
25056
  proc.state,
24833
25057
  proc.pid != null ? String(proc.pid) : "-",
24834
- proc.startedAt != null ? formatUptime(proc.startedAt) : "-",
25058
+ ACTIVE_STATES.has(proc.state) && proc.startedAt != null ? formatUptime(proc.startedAt, now) : "-",
24835
25059
  String(proc.restarts),
24836
- notesFor(proc)
25060
+ notesFor(proc, now)
24837
25061
  ]);
24838
25062
  const head = `generation ${state.generation} · revision ${state.configRevisionHash}`;
24839
25063
  const configError = state.configError.length > 0 ? `\nconfig error (last-good kept): ${state.configError[0]}` : "";
@@ -24845,7 +25069,7 @@ function renderTable(out, state) {
24845
25069
  "UPTIME",
24846
25070
  "R",
24847
25071
  "NOTES"
24848
- ], rows)}${configError}`;
25072
+ ], rows)}${capabilityFooter(state)}${configError}`;
24849
25073
  }
24850
25074
  async function cmdStatus(ctx) {
24851
25075
  const bad = unknownFlags(ctx.args.flags, ["--watch"]);
@@ -25044,7 +25268,7 @@ async function withTimeout(ctx, run) {
25044
25268
  async function main() {
25045
25269
  const argv = process.argv.slice(2);
25046
25270
  if (argv[0] === "daemon") {
25047
- const { runCommanderDaemon } = await import("./main-B5pT7VaY.mjs");
25271
+ const { runCommanderDaemon } = await import("./main-DyR1LyM-.mjs");
25048
25272
  return runCommanderDaemon(argv.slice(1));
25049
25273
  }
25050
25274
  const parsed = parseCliArgs(argv);
@@ -25088,6 +25312,6 @@ main().then((code) => {
25088
25312
  process.exitCode = EXIT.failure;
25089
25313
  });
25090
25314
  //#endregion
25091
- export { validateCommanderConfig as A, httpAcceptorCarrier as C, ActionRuntime as D, createDefaultServeLogger as E, orderByDependency as F, withDependencies as I, envVarViews as M, overrideFingerprint as N, RuntimeCoordinate as O, loadCommanderConfigFile as P, createRealmServerEngine as S, serveChannel as T, writeInstanceRecord as _, commanderStatusRealm as a, resolveCommanderDataDir as b, COMMANDER_BOOTSTRAP_PATH as c, COMMANDER_TICKET_PATH as d, COMMANDER_TICKET_PROTOCOL_PREFIX as f, removeInstanceRecord as g, recordDaemonAlive as h, readEnvOverrides as i, effectiveEnv as j, createMemoryStorageAdapter_json as k, COMMANDER_HEALTH_PATH as l, readInstanceRecord as m, applyEnvMutation as n, commanderChannel as o, COMMANDER_WS_PATH as p, countOverrides as r, commanderControlDomain as s, parseLogsClientMessage as t, COMMANDER_LOGS_PATH as u, commanderStatePaths as v, wsAcceptorCarrier as w, createRealmAcceptor as x, ensureStateDir as y };
25315
+ export { overrideFingerprint as A, createDefaultServeLogger as C, validateCommanderConfig as D, createMemoryStorageAdapter_json as E, recordDaemonAlive as F, removeInstanceRecord as I, writeInstanceRecord as L, orderByDependency as M, withDependencies as N, effectiveEnv as O, readInstanceRecord as P, serveChannel as S, RuntimeCoordinate as T, resolveCommanderDataDir as _, commanderChannel as a, httpAcceptorCarrier as b, COMMANDER_HEALTH_PATH as c, COMMANDER_TICKET_PROTOCOL_PREFIX as d, COMMANDER_WS_PATH as f, ensureStateDir as g, commanderStatePaths as h, readEnvOverrides as i, loadCommanderConfigFile as j, envVarViews as k, COMMANDER_LOGS_PATH as l, commanderPackageVersion as m, applyEnvMutation as n, commanderControlDomain as o, commanderStatusRealm as p, countOverrides as r, COMMANDER_BOOTSTRAP_PATH as s, parseLogsClientMessage as t, COMMANDER_TICKET_PATH as u, createRealmAcceptor as v, ActionRuntime as w, wsAcceptorCarrier as x, createRealmServerEngine as y };
25092
25316
 
25093
25317
  //# sourceMappingURL=cli.mjs.map