@nice-code/commander 0.80.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.cjs CHANGED
@@ -4,16 +4,16 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
4
4
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
5
5
  //#endregion
6
6
  const require_types = require("./types-CIdWQGjF.cjs");
7
- let node_fs = require("node:fs");
7
+ let node_fs_promises = require("node:fs/promises");
8
8
  let node_path = require("node:path");
9
+ let _nice_code_process = require("@nice-code/process");
10
+ let node_fs = require("node:fs");
9
11
  let node_url = require("node:url");
10
12
  let jiti = require("jiti");
11
13
  let node_crypto = require("node:crypto");
12
14
  let module$1 = require("module");
13
15
  let ws = require("ws");
14
- let node_fs_promises = require("node:fs/promises");
15
16
  let node_os = require("node:os");
16
- let _nice_code_process = require("@nice-code/process");
17
17
  let node_child_process = require("node:child_process");
18
18
  let node_net = require("node:net");
19
19
  //#region src/cli/args.ts
@@ -124,6 +124,176 @@ function numericFlag(flags, name) {
124
124
  if (!Number.isInteger(parsed) || parsed < 1) return { error: `${name} needs a positive integer` };
125
125
  return parsed;
126
126
  }
127
+ /** Generous ceiling for every string field: real values are ids, hashes and one path. */
128
+ const MAX_FIELD_CHARS = 4096;
129
+ function boundedString(value) {
130
+ return typeof value === "string" && value.length <= MAX_FIELD_CHARS;
131
+ }
132
+ function boundedInt(value, min, max) {
133
+ return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
134
+ }
135
+ /** `startStamp` is compared against a freshly read one — a wrong shape must never compare equal. */
136
+ function validStartStamp(value) {
137
+ if (value == null) return true;
138
+ if (typeof value !== "object" || Array.isArray(value)) return false;
139
+ const stamp = value;
140
+ return boundedString(stamp["stamp"]) && (stamp["precision"] === "ticks" || stamp["precision"] === "seconds");
141
+ }
142
+ /**
143
+ * Bounded shape check. The record is read from a file this user's other processes write, so it is
144
+ * trusted-ish — but a truncated write, a stale schema, or a hand-edit must degrade to "no daemon"
145
+ * rather than feed a malformed value into the reuse path. Strings are length-capped so a corrupt
146
+ * record can't become a large allocation on every `readInstanceRecord`.
147
+ */
148
+ function isInstanceRecord(value) {
149
+ if (value == null || typeof value !== "object" || Array.isArray(value)) return false;
150
+ const record = value;
151
+ 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;
152
+ }
153
+ async function writeInstanceRecord(path, record) {
154
+ await (0, node_fs_promises.mkdir)((0, node_path.dirname)(path), {
155
+ recursive: true,
156
+ mode: 448
157
+ });
158
+ const temp = `${path}.${process.pid}.tmp`;
159
+ await (0, node_fs_promises.writeFile)(temp, `${JSON.stringify(record, null, 2)}\n`, {
160
+ encoding: "utf8",
161
+ mode: 384
162
+ });
163
+ await (0, node_fs_promises.rename)(temp, path);
164
+ }
165
+ async function readInstanceRecord(path) {
166
+ try {
167
+ const parsed = JSON.parse(await (0, node_fs_promises.readFile)(path, "utf8"));
168
+ return isInstanceRecord(parsed) ? parsed : null;
169
+ } catch {
170
+ return null;
171
+ }
172
+ }
173
+ async function removeInstanceRecord(path) {
174
+ await (0, node_fs_promises.unlink)(path).catch(() => {});
175
+ }
176
+ /**
177
+ * A record written by a daemon this build cannot talk to (edge 18): a DIFFERENT protocol
178
+ * version, or — the 0.80.0 lesson — the SAME protocol version but a different status-realm
179
+ * schema hash (a schema change whose bump was forgotten; the realm layer would refuse the
180
+ * attach anyway, but with a raw hash mismatch instead of a name and a remedy).
181
+ *
182
+ * `readInstanceRecord` rejects both, which is right — but "invalid" and "absent" then look
183
+ * identical, so a plain `up` would boot a second daemon straight into the first one's port and
184
+ * report `EADDRINUSE`. That is a true statement about the wrong problem. Reading it separately
185
+ * is what lets the CLI say which daemon is in the way, and how to replace it. Nothing here
186
+ * authorizes a kill by itself: `signalDaemonShutdown` still verifies identity first.
187
+ */
188
+ async function readSkewedInstanceRecord(path, expectedRealmSchemaHash) {
189
+ let parsed;
190
+ try {
191
+ parsed = JSON.parse(await (0, node_fs_promises.readFile)(path, "utf8"));
192
+ } catch {
193
+ return null;
194
+ }
195
+ if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
196
+ const record = parsed;
197
+ if (record["service"] !== "nice-commander") return null;
198
+ if (!boundedInt(record["protocolVersion"], 0, Number.MAX_SAFE_INTEGER)) return null;
199
+ if (!boundedInt(record["pid"], 1, Number.MAX_SAFE_INTEGER)) return null;
200
+ if (!boundedInt(record["port"], 1, 65535)) return null;
201
+ const sameProtocol = record["protocolVersion"] === 3;
202
+ const sameRealm = boundedString(record["realmSchemaHash"]) && record["realmSchemaHash"] === expectedRealmSchemaHash;
203
+ if (sameProtocol && sameRealm) return null;
204
+ return {
205
+ pid: record["pid"],
206
+ port: record["port"],
207
+ protocolVersion: record["protocolVersion"],
208
+ packageVersion: boundedString(record["packageVersion"]) ? record["packageVersion"] : "unknown",
209
+ startStamp: validStartStamp(record["startStamp"]) ? record["startStamp"] ?? null : null,
210
+ skew: sameProtocol ? "realm-schema" : "protocol"
211
+ };
212
+ }
213
+ /** Liveness only — enough to say "something is there", never enough to authorize a kill (C1). */
214
+ function pidAlive$1(pid) {
215
+ try {
216
+ process.kill(pid, 0);
217
+ return true;
218
+ } catch (error) {
219
+ return error.code === "EPERM";
220
+ }
221
+ }
222
+ /**
223
+ * Is this record's daemon still the process it claims to be? pid alive AND startStamp equal —
224
+ * an unreadable stamp answers false (a reused pid must never be trusted).
225
+ */
226
+ async function recordDaemonAlive(record) {
227
+ try {
228
+ process.kill(record.pid, 0);
229
+ } catch (error) {
230
+ if (error.code !== "EPERM") return false;
231
+ }
232
+ if (record.startStamp == null) return true;
233
+ const stamp = await (0, _nice_code_process.readProcessStartStamp)(record.pid);
234
+ return stamp != null && stamp.stamp === record.startStamp.stamp;
235
+ }
236
+ /**
237
+ * Protocol-independent shutdown: verify the record's pid is still the daemon it claims to be
238
+ * (pid + startStamp — the ledger's own identity rule), then SIGTERM it. The daemon's signal
239
+ * handler runs the exact shutdown ladder `shutdown` would have asked for over the wire, so this
240
+ * is the remedy of last resort for a daemon a CLI cannot TALK to — a build from before a
241
+ * protocol or realm-schema change — without asking anyone to hunt pids by hand. A second call
242
+ * while it is still stopping escalates, mirroring the daemon's own two-signal contract.
243
+ *
244
+ * ⚠ `identity-unverified` is a refusal, not an error to work around: a recorded stamp that no
245
+ * longer matches means pid reuse, and a record with no stamp cannot prove the pid is ours.
246
+ */
247
+ async function signalDaemonShutdown(target, waitMs = 15e3) {
248
+ const { pid, startStamp } = target;
249
+ if (!pidAlive$1(pid)) return {
250
+ outcome: "not-running",
251
+ pid
252
+ };
253
+ if (startStamp == null) return {
254
+ outcome: "identity-unverified",
255
+ pid
256
+ };
257
+ const stamp = await (0, _nice_code_process.readProcessStartStamp)(pid);
258
+ if (stamp == null || stamp.stamp !== startStamp.stamp) return {
259
+ outcome: "identity-unverified",
260
+ pid
261
+ };
262
+ try {
263
+ process.kill(pid, "SIGTERM");
264
+ } catch {
265
+ return {
266
+ outcome: "not-running",
267
+ pid
268
+ };
269
+ }
270
+ const deadline = Date.now() + waitMs;
271
+ while (Date.now() < deadline) {
272
+ if (!pidAlive$1(pid)) return {
273
+ outcome: "exited",
274
+ pid
275
+ };
276
+ await new Promise((resolve) => setTimeout(resolve, 150));
277
+ }
278
+ return {
279
+ outcome: pidAlive$1(pid) ? "still-stopping" : "exited",
280
+ pid
281
+ };
282
+ }
283
+ /** Authed liveness probe — the final word on "reuse this daemon" (bounded). */
284
+ async function pingDaemon(record, timeoutMs = 2e3) {
285
+ try {
286
+ const response = await fetch(`http://127.0.0.1:${record.port}/health`, {
287
+ headers: { authorization: `Bearer ${record.token}` },
288
+ signal: AbortSignal.timeout(timeoutMs)
289
+ });
290
+ if (!response.ok) return null;
291
+ const body = await response.json();
292
+ return body.ok === true && body.configKey === record.configKey ? body : null;
293
+ } catch {
294
+ return null;
295
+ }
296
+ }
127
297
  //#endregion
128
298
  //#region src/config/resolve.ts
129
299
  /** Topological order of the given id set over the dependsOn graph; config order breaks ties. */
@@ -22886,122 +23056,103 @@ async function ensureStateDir(paths) {
22886
23056
  mode: 448
22887
23057
  });
22888
23058
  }
22889
- /** Generous ceiling for every string field: real values are ids, hashes and one path. */
22890
- const MAX_FIELD_CHARS = 4096;
22891
- function boundedString(value) {
22892
- return typeof value === "string" && value.length <= MAX_FIELD_CHARS;
22893
- }
22894
- function boundedInt(value, min, max) {
22895
- return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max;
22896
- }
22897
- /** `startStamp` is compared against a freshly read one — a wrong shape must never compare equal. */
22898
- function validStartStamp(value) {
22899
- if (value == null) return true;
22900
- if (typeof value !== "object" || Array.isArray(value)) return false;
22901
- const stamp = value;
22902
- return boundedString(stamp["stamp"]) && (stamp["precision"] === "ticks" || stamp["precision"] === "seconds");
22903
- }
22904
- /**
22905
- * Bounded shape check. The record is read from a file this user's other processes write, so it is
22906
- * trusted-ish — but a truncated write, a stale schema, or a hand-edit must degrade to "no daemon"
22907
- * rather than feed a malformed value into the reuse path. Strings are length-capped so a corrupt
22908
- * record can't become a large allocation on every `readInstanceRecord`.
22909
- */
22910
- function isInstanceRecord(value) {
22911
- if (value == null || typeof value !== "object" || Array.isArray(value)) return false;
22912
- const record = value;
22913
- 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;
22914
- }
22915
- async function writeInstanceRecord(path, record) {
22916
- await (0, node_fs_promises.mkdir)((0, node_path.dirname)(path), {
22917
- recursive: true,
22918
- mode: 448
22919
- });
22920
- const temp = `${path}.${process.pid}.tmp`;
22921
- await (0, node_fs_promises.writeFile)(temp, `${JSON.stringify(record, null, 2)}\n`, {
22922
- encoding: "utf8",
22923
- mode: 384
22924
- });
22925
- await (0, node_fs_promises.rename)(temp, path);
22926
- }
22927
- async function readInstanceRecord(path) {
22928
- try {
22929
- const parsed = JSON.parse(await (0, node_fs_promises.readFile)(path, "utf8"));
22930
- return isInstanceRecord(parsed) ? parsed : null;
22931
- } catch {
22932
- return null;
22933
- }
22934
- }
22935
- async function removeInstanceRecord(path) {
22936
- await (0, node_fs_promises.unlink)(path).catch(() => {});
22937
- }
23059
+ //#endregion
23060
+ //#region src/daemon/packageVersion.ts
23061
+ let cached = null;
22938
23062
  /**
22939
- * A record written by a daemon speaking a DIFFERENT protocol version (edge 18).
22940
- *
22941
- * `readInstanceRecord` rejects it, which is right — we cannot talk to that daemon — but "invalid"
22942
- * and "absent" then look identical, so a plain `up` would boot a second daemon straight into the
22943
- * first one's port and report `EADDRINUSE`. That is a true statement about the wrong problem.
22944
- * Reading it separately is what lets the CLI say which daemon is in the way, and how to replace
22945
- * it. Nothing here authorizes a kill: an old daemon is a live execution lease like any other.
23063
+ * Resolved relative to the BUILT module, so the candidate list must cover every layout this
23064
+ * code ships in: `build/main-*.mjs` in the installed package (`../package.json` — the miss that
23065
+ * had every daemon reporting 0.0.0), and `src/daemon/*.ts` when run from sources (`../../`).
22946
23066
  */
22947
- async function readForeignInstanceRecord(path) {
22948
- let parsed;
22949
- try {
22950
- parsed = JSON.parse(await (0, node_fs_promises.readFile)(path, "utf8"));
22951
- } catch {
22952
- return null;
22953
- }
22954
- if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
22955
- const record = parsed;
22956
- if (record["service"] !== "nice-commander") return null;
22957
- if (!boundedInt(record["protocolVersion"], 0, Number.MAX_SAFE_INTEGER)) return null;
22958
- if (record["protocolVersion"] === 2) return null;
22959
- if (!boundedInt(record["pid"], 1, Number.MAX_SAFE_INTEGER)) return null;
22960
- if (!boundedInt(record["port"], 1, 65535)) return null;
22961
- return {
22962
- pid: record["pid"],
22963
- port: record["port"],
22964
- protocolVersion: record["protocolVersion"],
22965
- packageVersion: boundedString(record["packageVersion"]) ? record["packageVersion"] : "unknown"
22966
- };
22967
- }
22968
- /** Liveness only — enough to say "something is there", never enough to authorize a kill (C1). */
22969
- function pidAlive$1(pid) {
22970
- try {
22971
- process.kill(pid, 0);
22972
- return true;
22973
- } catch (error) {
22974
- return error.code === "EPERM";
22975
- }
23067
+ async function commanderPackageVersion() {
23068
+ if (cached != null) return cached;
23069
+ for (const candidate of [
23070
+ new URL("../package.json", require("url").pathToFileURL(__filename).href),
23071
+ new URL("../../package.json", require("url").pathToFileURL(__filename).href),
23072
+ new URL("../../../package.json", require("url").pathToFileURL(__filename).href)
23073
+ ]) try {
23074
+ const parsed = JSON.parse(await (0, node_fs_promises.readFile)(candidate, "utf8"));
23075
+ if (typeof parsed.version === "string" && parsed.name === "@nice-code/commander") {
23076
+ cached = parsed.version;
23077
+ return cached;
23078
+ }
23079
+ } catch {}
23080
+ cached = "0.0.0";
23081
+ return cached;
22976
23082
  }
23083
+ //#endregion
23084
+ //#region src/protocol/statusRealm.ts
22977
23085
  /**
22978
- * Is this record's daemon still the process it claims to be? pid alive AND startStamp equal —
22979
- * an unreadable stamp answers false (a reused pid must never be trusted).
23086
+ * Read-only viewer for every authenticated identity — control authority lives in the ticket
23087
+ * gate at the upgrade, the realm floor (`authenticated`) just guarantees a real wire identity
23088
+ * behind every attach. No intents: clients never write.
22980
23089
  */
22981
- async function recordDaemonAlive(record) {
22982
- try {
22983
- process.kill(record.pid, 0);
22984
- } catch (error) {
22985
- if (error.code !== "EPERM") return false;
22986
- }
22987
- if (record.startStamp == null) return true;
22988
- const stamp = await (0, _nice_code_process.readProcessStartStamp)(record.pid);
22989
- return stamp != null && stamp.stamp === record.startStamp.stamp;
22990
- }
22991
- /** Authed liveness probe — the final word on "reuse this daemon" (bounded). */
22992
- async function pingDaemon(record, timeoutMs = 2e3) {
22993
- try {
22994
- const response = await fetch(`http://127.0.0.1:${record.port}/health`, {
22995
- headers: { authorization: `Bearer ${record.token}` },
22996
- signal: AbortSignal.timeout(timeoutMs)
22997
- });
22998
- if (!response.ok) return null;
22999
- const body = await response.json();
23000
- return body.ok === true && body.configKey === record.configKey ? body : null;
23001
- } catch {
23002
- return null;
23003
- }
23004
- }
23090
+ const commanderStatusRealm = defineRealm({
23091
+ id: "commander_status",
23092
+ avatars: { viewer: { persistentId: t.string() } },
23093
+ state: {
23094
+ generation: t.number(),
23095
+ configRevisionHash: t.string(),
23096
+ configError: t.array(t.string()),
23097
+ processes: t.record(t.id("processId"), t.object({
23098
+ kind: t.string(),
23099
+ state: t.string(),
23100
+ pid: t.optional(t.number()),
23101
+ startedAt: t.optional(t.number()),
23102
+ sawOutputAt: t.optional(t.number()),
23103
+ lastTask: t.optional(t.object({
23104
+ outcome: t.string(),
23105
+ reason: t.optional(t.string()),
23106
+ timedOut: t.boolean(),
23107
+ endedAt: t.number(),
23108
+ durationMs: t.optional(t.number())
23109
+ })),
23110
+ restarts: t.number(),
23111
+ lastExit: t.optional(t.object({
23112
+ code: t.optional(t.number()),
23113
+ signal: t.optional(t.string()),
23114
+ expected: t.boolean()
23115
+ })),
23116
+ stale: t.boolean(),
23117
+ removed: t.boolean(),
23118
+ envDrift: t.boolean(),
23119
+ blockedBy: t.optional(t.string()),
23120
+ degradedBy: t.array(t.string()),
23121
+ unreadyReason: t.optional(t.string()),
23122
+ capability: t.optional(t.object({
23123
+ treeMechanism: t.string(),
23124
+ degraded: t.boolean(),
23125
+ notes: t.array(t.string())
23126
+ })),
23127
+ tags: t.record(t.id("tag"), t.string()),
23128
+ detail: t.object({
23129
+ command: t.string(),
23130
+ cwd: t.string(),
23131
+ dependsOn: t.array(t.string()),
23132
+ ready: t.optional(t.string()),
23133
+ endpoints: t.array(t.object({
23134
+ name: t.string(),
23135
+ protocol: t.string(),
23136
+ host: t.string(),
23137
+ port: t.number(),
23138
+ ownership: t.string(),
23139
+ url: t.optional(t.string())
23140
+ })),
23141
+ envVars: t.array(t.object({
23142
+ name: t.string(),
23143
+ description: t.optional(t.string()),
23144
+ secret: t.boolean(),
23145
+ required: t.boolean(),
23146
+ values: t.optional(t.array(t.string())),
23147
+ source: t.string(),
23148
+ value: t.optional(t.string())
23149
+ }))
23150
+ })
23151
+ })),
23152
+ groups: t.record(t.id("groupName"), t.object({ members: t.array(t.string()) }))
23153
+ },
23154
+ rules: (r) => [r.path("**").view(r.everyone).alter(r.serverOnly)]
23155
+ });
23005
23156
  //#endregion
23006
23157
  //#region src/daemon/lockfile.ts
23007
23158
  const LOCK_RETRY_LIMIT = 250;
@@ -23124,22 +23275,55 @@ var CommanderDaemonBootError = class extends Error {
23124
23275
  this.name = "CommanderDaemonBootError";
23125
23276
  }
23126
23277
  };
23278
+ /**
23279
+ * Stop a skewed daemon so the boot below can proceed — ONLY when nothing of it is running.
23280
+ * "Running" is answered by the ledger, the one surface both builds share regardless of wire
23281
+ * protocol: any record whose pid is alive (a supervised child, or a foreground `run` lease) is
23282
+ * a live dev environment, and an upgrade must never be the thing that kills one.
23283
+ */
23284
+ async function replaceSkewedDaemon(paths, skewed) {
23285
+ 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" : ""})`;
23286
+ let liveIds = [];
23287
+ try {
23288
+ liveIds = (await (0, _nice_code_process.openProcessLedger)({
23289
+ dir: paths.stateDir,
23290
+ namespace: paths.ledgerNamespace
23291
+ }).list()).filter((record) => pidAlive$1(record.pid)).map((record) => record.id);
23292
+ } catch {
23293
+ 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.`);
23294
+ }
23295
+ 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.`);
23296
+ switch ((await signalDaemonShutdown({
23297
+ pid: skewed.pid,
23298
+ startStamp: skewed.startStamp
23299
+ })).outcome) {
23300
+ case "exited": return {
23301
+ pid: skewed.pid,
23302
+ packageVersion: skewed.packageVersion
23303
+ };
23304
+ case "not-running": return;
23305
+ 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).`);
23306
+ 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}.`);
23307
+ }
23308
+ }
23127
23309
  async function ensureDaemon(options) {
23128
23310
  const dataDir = options.dataDir != null ? (0, node_path.resolve)(options.dataDir) : resolveCommanderDataDir();
23129
23311
  const paths = commanderStatePaths(dataDir, options.config.configKey);
23130
23312
  const timeoutMs = options.handshakeTimeoutMs ?? HANDSHAKE_TIMEOUT_MS;
23131
23313
  return withCommanderLock(paths.upLockPath, async () => {
23132
23314
  const existing = await readInstanceRecord(paths.instanceRecordPath);
23133
- if (existing != null && await recordDaemonAlive(existing)) {
23315
+ const compatible = existing != null && existing.realmSchemaHash === commanderStatusRealm.schemaHash;
23316
+ if (compatible && await recordDaemonAlive(existing)) {
23134
23317
  if (await pingDaemon(existing) != null) return {
23135
23318
  record: existing,
23136
23319
  reused: true,
23137
23320
  paths
23138
23321
  };
23139
23322
  }
23140
- if (existing == null) {
23141
- const foreign = await readForeignInstanceRecord(paths.instanceRecordPath);
23142
- 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}.`);
23323
+ let replaced;
23324
+ if (!compatible) {
23325
+ const skewed = await readSkewedInstanceRecord(paths.instanceRecordPath, commanderStatusRealm.schemaHash);
23326
+ if (skewed != null && pidAlive$1(skewed.pid)) replaced = await replaceSkewedDaemon(paths, skewed);
23143
23327
  }
23144
23328
  await ensureStateDir(paths);
23145
23329
  const bootFd = (0, node_fs.openSync)(paths.bootLogPath, "w", 384);
@@ -23174,7 +23358,8 @@ async function ensureDaemon(options) {
23174
23358
  if (await pingDaemon(record) != null) return {
23175
23359
  record,
23176
23360
  reused: false,
23177
- paths
23361
+ paths,
23362
+ ...replaced != null ? { replaced } : {}
23178
23363
  };
23179
23364
  }
23180
23365
  if (exited != null) {
@@ -23396,79 +23581,6 @@ const commanderChannel = defineChannel({
23396
23581
  toConnector: []
23397
23582
  });
23398
23583
  //#endregion
23399
- //#region src/protocol/statusRealm.ts
23400
- /**
23401
- * Read-only viewer for every authenticated identity — control authority lives in the ticket
23402
- * gate at the upgrade, the realm floor (`authenticated`) just guarantees a real wire identity
23403
- * behind every attach. No intents: clients never write.
23404
- */
23405
- const commanderStatusRealm = defineRealm({
23406
- id: "commander_status",
23407
- avatars: { viewer: { persistentId: t.string() } },
23408
- state: {
23409
- generation: t.number(),
23410
- configRevisionHash: t.string(),
23411
- configError: t.array(t.string()),
23412
- processes: t.record(t.id("processId"), t.object({
23413
- kind: t.string(),
23414
- state: t.string(),
23415
- pid: t.optional(t.number()),
23416
- startedAt: t.optional(t.number()),
23417
- sawOutputAt: t.optional(t.number()),
23418
- lastTask: t.optional(t.object({
23419
- outcome: t.string(),
23420
- reason: t.optional(t.string()),
23421
- timedOut: t.boolean(),
23422
- endedAt: t.number(),
23423
- durationMs: t.optional(t.number())
23424
- })),
23425
- restarts: t.number(),
23426
- lastExit: t.optional(t.object({
23427
- code: t.optional(t.number()),
23428
- signal: t.optional(t.string()),
23429
- expected: t.boolean()
23430
- })),
23431
- stale: t.boolean(),
23432
- removed: t.boolean(),
23433
- envDrift: t.boolean(),
23434
- blockedBy: t.optional(t.string()),
23435
- degradedBy: t.array(t.string()),
23436
- unreadyReason: t.optional(t.string()),
23437
- capability: t.optional(t.object({
23438
- treeMechanism: t.string(),
23439
- degraded: t.boolean(),
23440
- notes: t.array(t.string())
23441
- })),
23442
- tags: t.record(t.id("tag"), t.string()),
23443
- detail: t.object({
23444
- command: t.string(),
23445
- cwd: t.string(),
23446
- dependsOn: t.array(t.string()),
23447
- ready: t.optional(t.string()),
23448
- endpoints: t.array(t.object({
23449
- name: t.string(),
23450
- protocol: t.string(),
23451
- host: t.string(),
23452
- port: t.number(),
23453
- ownership: t.string(),
23454
- url: t.optional(t.string())
23455
- })),
23456
- envVars: t.array(t.object({
23457
- name: t.string(),
23458
- description: t.optional(t.string()),
23459
- secret: t.boolean(),
23460
- required: t.boolean(),
23461
- values: t.optional(t.array(t.string())),
23462
- source: t.string(),
23463
- value: t.optional(t.string())
23464
- }))
23465
- })
23466
- })),
23467
- groups: t.record(t.id("groupName"), t.object({ members: t.array(t.string()) }))
23468
- },
23469
- rules: (r) => [r.path("**").view(r.everyone).alter(r.serverOnly)]
23470
- });
23471
- //#endregion
23472
23584
  //#region src/cli/daemonClient.ts
23473
23585
  /** The running daemon for this config, or null (dead record, failed ping, nothing on disk). */
23474
23586
  async function findDaemon(config) {
@@ -23481,12 +23593,28 @@ async function findDaemon(config) {
23481
23593
  spawned: false
23482
23594
  } : null;
23483
23595
  }
23596
+ /**
23597
+ * A daemon this build cannot talk to is IN THE WAY, not absent — the same distinction `up`
23598
+ * makes (edge 18). Reporting "not running" while one plainly IS sends you to `up`, which then
23599
+ * fails on something else entirely. The remedy is always the same and always THIS build's:
23600
+ * `shutdown` falls back to a verified signal when it cannot speak to the daemon.
23601
+ */
23602
+ async function findSkewedDaemon(config) {
23603
+ const skewed = await readSkewedInstanceRecord(commanderStatePaths(resolveCommanderDataDir(), config.configKey).instanceRecordPath, commanderStatusRealm.schemaHash);
23604
+ if (skewed == null || !pidAlive$1(skewed.pid)) return null;
23605
+ const difference = skewed.skew === "protocol" ? `speaks protocol v${skewed.protocolVersion}; this build speaks v3` : "was started before an upgrade changed the status schema";
23606
+ return {
23607
+ 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.`,
23608
+ pid: skewed.pid,
23609
+ startStamp: skewed.startStamp
23610
+ };
23611
+ }
23484
23612
  /** Read-only commands' daemon-or-report: never starts anything, exit 3 when not running. */
23485
23613
  async function requireDaemon(config) {
23486
23614
  const handle = await findDaemon(config);
23487
23615
  if (handle != null) return handle;
23488
- const foreign = await readForeignInstanceRecord(commanderStatePaths(resolveCommanderDataDir(), config.configKey).instanceRecordPath);
23489
- 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.`);
23616
+ const skewed = await findSkewedDaemon(config);
23617
+ if (skewed != null) throw new CliExit(EXIT.notRunning, skewed.message);
23490
23618
  throw new CliExit(EXIT.notRunning, `daemon not running for "${config.name}" (start one with \`up\`)`);
23491
23619
  }
23492
23620
  /** `up`/`ui`'s spawn-or-reuse; the daemon child reruns THIS bin (`daemon` subcommand). */
@@ -23498,7 +23626,8 @@ async function ensureDaemonRunning(config) {
23498
23626
  return {
23499
23627
  record: result.record,
23500
23628
  paths: result.paths,
23501
- spawned: !result.reused
23629
+ spawned: !result.reused,
23630
+ ...result.replaced != null ? { replaced: result.replaced } : {}
23502
23631
  };
23503
23632
  }
23504
23633
  async function mintTicket(record) {
@@ -23519,6 +23648,7 @@ async function mintTicket(record) {
23519
23648
  }
23520
23649
  async function connectDaemon(handle) {
23521
23650
  const { record } = handle;
23651
+ 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.`);
23522
23652
  const ticket = await mintTicket(record);
23523
23653
  const runtime = new ActionRuntime(RuntimeCoordinate.env("commander_cli").withPersistentId(`cli-${(0, node_crypto.randomUUID)().slice(0, 8)}`));
23524
23654
  const connector = connectChannel(runtime, commanderChannel, {
@@ -23556,7 +23686,8 @@ async function connectDaemon(handle) {
23556
23686
  } catch {
23557
23687
  connector.dispose();
23558
23688
  const reason = realm.attachError != null ? String(realm.attachError) : "timeout";
23559
- throw new CliExit(EXIT.failure, `could not attach the status realm (${reason})`);
23689
+ 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.` : "";
23690
+ throw new CliExit(EXIT.failure, `could not attach the status realm (${reason}).${hint}`);
23560
23691
  }
23561
23692
  return {
23562
23693
  record,
@@ -23567,7 +23698,7 @@ async function connectDaemon(handle) {
23567
23698
  const payload = await (await runtime.handleActionPayload(request)).waitForResultPayload();
23568
23699
  if (!payload.result.ok) throw new CliExit(EXIT.failure, `action "${action}" rejected by the daemon`);
23569
23700
  const report = parseActionReport(payload.result.output);
23570
- if (report == null) throw new CliExit(EXIT.failure, `the daemon answered "${action}" with something this CLI does not recognise — protocol ${record.protocolVersion} vs 2`);
23701
+ if (report == null) throw new CliExit(EXIT.failure, `the daemon answered "${action}" with something this CLI does not recognise — protocol ${record.protocolVersion} vs 3`);
23571
23702
  return report;
23572
23703
  },
23573
23704
  setEnv: async (input) => {
@@ -23672,6 +23803,7 @@ async function cmdUp(ctx) {
23672
23803
  }
23673
23804
  const handle = await ensureDaemonRunning(ctx.config);
23674
23805
  ctx.spawnedDaemon = handle.spawned;
23806
+ 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`));
23675
23807
  const client = await connectDaemon(handle);
23676
23808
  try {
23677
23809
  const wait = !ctx.args.flags.has("--no-wait");
@@ -23714,17 +23846,71 @@ async function cmdDown(ctx) {
23714
23846
  async function cmdRestart(ctx) {
23715
23847
  return controlVerb(ctx, "restart");
23716
23848
  }
23849
+ /**
23850
+ * `shutdown` must be the command that ALWAYS works — it is the remedy every skew message names.
23851
+ * The wire is tried first (the graceful ask); when the daemon cannot be talked to — another
23852
+ * build's protocol, a changed realm schema, a wedged socket — it falls back to a verified
23853
+ * SIGTERM, which runs the daemon's own shutdown ladder. Without this fallback, the one command
23854
+ * that fixes "the CLI cannot talk to the daemon" was itself behind that same wall.
23855
+ */
23717
23856
  async function cmdShutdown(ctx) {
23718
23857
  const bad = unknownFlags(ctx.args.flags, []);
23719
23858
  if (bad != null) throw new CliExit(EXIT.usage, bad);
23720
- const client = await connectDaemon(await requireDaemon(ctx.config));
23721
- try {
23722
- await client.shutdown();
23723
- if (ctx.out.json) ctx.out.printJson({ ok: true });
23724
- else ctx.out.print(`daemon for "${ctx.config.name}" is shutting down`);
23725
- return EXIT.ok;
23726
- } finally {
23727
- client.dispose();
23859
+ const { out } = ctx;
23860
+ const handle = await findDaemon(ctx.config);
23861
+ if (handle != null) try {
23862
+ const client = await connectDaemon(handle);
23863
+ try {
23864
+ await client.shutdown();
23865
+ if (out.json) out.printJson({
23866
+ ok: true,
23867
+ via: "wire"
23868
+ });
23869
+ else out.print(`daemon for "${ctx.config.name}" is shutting down`);
23870
+ return EXIT.ok;
23871
+ } finally {
23872
+ client.dispose();
23873
+ }
23874
+ } catch (error) {
23875
+ if (!(error instanceof CliExit)) throw error;
23876
+ return reportSignalShutdown(ctx, await signalDaemonShutdown({
23877
+ pid: handle.record.pid,
23878
+ startStamp: handle.record.startStamp
23879
+ }));
23880
+ }
23881
+ const skewed = await findSkewedDaemon(ctx.config);
23882
+ if (skewed != null) {
23883
+ if (!out.json) out.print(out.paint("gray", skewed.message));
23884
+ return reportSignalShutdown(ctx, await signalDaemonShutdown({
23885
+ pid: skewed.pid,
23886
+ startStamp: skewed.startStamp
23887
+ }));
23888
+ }
23889
+ throw new CliExit(EXIT.notRunning, `daemon not running for "${ctx.config.name}"`);
23890
+ }
23891
+ function reportSignalShutdown(ctx, result) {
23892
+ const { out } = ctx;
23893
+ if (out.json) {
23894
+ out.printJson({
23895
+ ok: result.outcome === "exited",
23896
+ via: "signal",
23897
+ ...result
23898
+ });
23899
+ return result.outcome === "exited" ? EXIT.ok : EXIT.failure;
23900
+ }
23901
+ switch (result.outcome) {
23902
+ case "exited":
23903
+ 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)`);
23904
+ return EXIT.ok;
23905
+ case "still-stopping":
23906
+ out.print(out.paint("yellow", `⚠ daemon (pid ${result.pid}) was signalled and is still stopping — run \`shutdown\` again to escalate if it stays stuck`));
23907
+ return EXIT.failure;
23908
+ case "identity-unverified":
23909
+ 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.`));
23910
+ return EXIT.failure;
23911
+ case "not-running":
23912
+ out.print(`daemon not running for "${ctx.config.name}" (stale record)`);
23913
+ return EXIT.ok;
23728
23914
  }
23729
23915
  }
23730
23916
  //#endregion
@@ -23864,6 +24050,10 @@ async function diagnose(ctx, handle) {
23864
24050
  };
23865
24051
  const paths = commanderStatePaths(resolveCommanderDataDir(), config.configKey);
23866
24052
  report.info.push(handle != null ? `daemon: running (pid ${handle.record.pid}, port ${handle.record.port}, generation ${handle.record.generation})` : `daemon: not running`);
24053
+ if (handle == null) {
24054
+ const skewed = await findSkewedDaemon(config);
24055
+ if (skewed != null) report.warnings.push(skewed.message);
24056
+ }
23867
24057
  if (handle != null) {
23868
24058
  const ping = await pingDaemon(handle.record).catch(() => null);
23869
24059
  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`);
@@ -25077,7 +25267,7 @@ async function withTimeout(ctx, run) {
25077
25267
  async function main() {
25078
25268
  const argv = process.argv.slice(2);
25079
25269
  if (argv[0] === "daemon") {
25080
- const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-d60iXc8C.cjs"));
25270
+ const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-CecRz_2L.cjs"));
25081
25271
  return runCommanderDaemon(argv.slice(1));
25082
25272
  }
25083
25273
  const parsed = parseCliArgs(argv);
@@ -25132,6 +25322,7 @@ exports.RuntimeCoordinate = RuntimeCoordinate;
25132
25322
  exports.applyEnvMutation = applyEnvMutation;
25133
25323
  exports.commanderChannel = commanderChannel;
25134
25324
  exports.commanderControlDomain = commanderControlDomain;
25325
+ exports.commanderPackageVersion = commanderPackageVersion;
25135
25326
  exports.commanderStatePaths = commanderStatePaths;
25136
25327
  exports.commanderStatusRealm = commanderStatusRealm;
25137
25328
  exports.countOverrides = countOverrides;