@nice-code/commander 0.80.0 → 0.82.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,109 @@ 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
+ recentRuns: t.array(t.object({
23111
+ startedAt: t.number(),
23112
+ endedAt: t.optional(t.number()),
23113
+ outcome: t.optional(t.union(t.literal("succeeded"), t.literal("failed"), t.literal("stopped"), t.literal("crashed"), t.literal("timedOut")))
23114
+ })),
23115
+ restarts: t.number(),
23116
+ lastExit: t.optional(t.object({
23117
+ code: t.optional(t.number()),
23118
+ signal: t.optional(t.string()),
23119
+ expected: t.boolean()
23120
+ })),
23121
+ stale: t.boolean(),
23122
+ removed: t.boolean(),
23123
+ envDrift: t.boolean(),
23124
+ blockedBy: t.optional(t.string()),
23125
+ degradedBy: t.array(t.string()),
23126
+ unreadyReason: t.optional(t.string()),
23127
+ capability: t.optional(t.object({
23128
+ treeMechanism: t.string(),
23129
+ degraded: t.boolean(),
23130
+ notes: t.array(t.string())
23131
+ })),
23132
+ tags: t.record(t.id("tag"), t.string()),
23133
+ detail: t.object({
23134
+ command: t.string(),
23135
+ cwd: t.string(),
23136
+ dependsOn: t.array(t.string()),
23137
+ ready: t.optional(t.string()),
23138
+ timeoutMs: t.optional(t.number()),
23139
+ endpoints: t.array(t.object({
23140
+ name: t.string(),
23141
+ protocol: t.string(),
23142
+ host: t.string(),
23143
+ port: t.number(),
23144
+ ownership: t.string(),
23145
+ url: t.optional(t.string())
23146
+ })),
23147
+ envVars: t.array(t.object({
23148
+ name: t.string(),
23149
+ description: t.optional(t.string()),
23150
+ secret: t.boolean(),
23151
+ required: t.boolean(),
23152
+ values: t.optional(t.array(t.string())),
23153
+ source: t.string(),
23154
+ value: t.optional(t.string())
23155
+ }))
23156
+ })
23157
+ })),
23158
+ groups: t.record(t.id("groupName"), t.object({ members: t.array(t.string()) }))
23159
+ },
23160
+ rules: (r) => [r.path("**").view(r.everyone).alter(r.serverOnly)]
23161
+ });
23005
23162
  //#endregion
23006
23163
  //#region src/daemon/lockfile.ts
23007
23164
  const LOCK_RETRY_LIMIT = 250;
@@ -23124,22 +23281,55 @@ var CommanderDaemonBootError = class extends Error {
23124
23281
  this.name = "CommanderDaemonBootError";
23125
23282
  }
23126
23283
  };
23284
+ /**
23285
+ * Stop a skewed daemon so the boot below can proceed — ONLY when nothing of it is running.
23286
+ * "Running" is answered by the ledger, the one surface both builds share regardless of wire
23287
+ * protocol: any record whose pid is alive (a supervised child, or a foreground `run` lease) is
23288
+ * a live dev environment, and an upgrade must never be the thing that kills one.
23289
+ */
23290
+ async function replaceSkewedDaemon(paths, skewed) {
23291
+ 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" : ""})`;
23292
+ let liveIds = [];
23293
+ try {
23294
+ liveIds = (await (0, _nice_code_process.openProcessLedger)({
23295
+ dir: paths.stateDir,
23296
+ namespace: paths.ledgerNamespace
23297
+ }).list()).filter((record) => pidAlive$1(record.pid)).map((record) => record.id);
23298
+ } catch {
23299
+ 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.`);
23300
+ }
23301
+ 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.`);
23302
+ switch ((await signalDaemonShutdown({
23303
+ pid: skewed.pid,
23304
+ startStamp: skewed.startStamp
23305
+ })).outcome) {
23306
+ case "exited": return {
23307
+ pid: skewed.pid,
23308
+ packageVersion: skewed.packageVersion
23309
+ };
23310
+ case "not-running": return;
23311
+ 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).`);
23312
+ 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}.`);
23313
+ }
23314
+ }
23127
23315
  async function ensureDaemon(options) {
23128
23316
  const dataDir = options.dataDir != null ? (0, node_path.resolve)(options.dataDir) : resolveCommanderDataDir();
23129
23317
  const paths = commanderStatePaths(dataDir, options.config.configKey);
23130
23318
  const timeoutMs = options.handshakeTimeoutMs ?? HANDSHAKE_TIMEOUT_MS;
23131
23319
  return withCommanderLock(paths.upLockPath, async () => {
23132
23320
  const existing = await readInstanceRecord(paths.instanceRecordPath);
23133
- if (existing != null && await recordDaemonAlive(existing)) {
23321
+ const compatible = existing != null && existing.realmSchemaHash === commanderStatusRealm.schemaHash;
23322
+ if (compatible && await recordDaemonAlive(existing)) {
23134
23323
  if (await pingDaemon(existing) != null) return {
23135
23324
  record: existing,
23136
23325
  reused: true,
23137
23326
  paths
23138
23327
  };
23139
23328
  }
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}.`);
23329
+ let replaced;
23330
+ if (!compatible) {
23331
+ const skewed = await readSkewedInstanceRecord(paths.instanceRecordPath, commanderStatusRealm.schemaHash);
23332
+ if (skewed != null && pidAlive$1(skewed.pid)) replaced = await replaceSkewedDaemon(paths, skewed);
23143
23333
  }
23144
23334
  await ensureStateDir(paths);
23145
23335
  const bootFd = (0, node_fs.openSync)(paths.bootLogPath, "w", 384);
@@ -23174,7 +23364,8 @@ async function ensureDaemon(options) {
23174
23364
  if (await pingDaemon(record) != null) return {
23175
23365
  record,
23176
23366
  reused: false,
23177
- paths
23367
+ paths,
23368
+ ...replaced != null ? { replaced } : {}
23178
23369
  };
23179
23370
  }
23180
23371
  if (exited != null) {
@@ -23396,79 +23587,6 @@ const commanderChannel = defineChannel({
23396
23587
  toConnector: []
23397
23588
  });
23398
23589
  //#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
23590
  //#region src/cli/daemonClient.ts
23473
23591
  /** The running daemon for this config, or null (dead record, failed ping, nothing on disk). */
23474
23592
  async function findDaemon(config) {
@@ -23481,12 +23599,28 @@ async function findDaemon(config) {
23481
23599
  spawned: false
23482
23600
  } : null;
23483
23601
  }
23602
+ /**
23603
+ * A daemon this build cannot talk to is IN THE WAY, not absent — the same distinction `up`
23604
+ * makes (edge 18). Reporting "not running" while one plainly IS sends you to `up`, which then
23605
+ * fails on something else entirely. The remedy is always the same and always THIS build's:
23606
+ * `shutdown` falls back to a verified signal when it cannot speak to the daemon.
23607
+ */
23608
+ async function findSkewedDaemon(config) {
23609
+ const skewed = await readSkewedInstanceRecord(commanderStatePaths(resolveCommanderDataDir(), config.configKey).instanceRecordPath, commanderStatusRealm.schemaHash);
23610
+ if (skewed == null || !pidAlive$1(skewed.pid)) return null;
23611
+ const difference = skewed.skew === "protocol" ? `speaks protocol v${skewed.protocolVersion}; this build speaks v3` : "was started before an upgrade changed the status schema";
23612
+ return {
23613
+ 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.`,
23614
+ pid: skewed.pid,
23615
+ startStamp: skewed.startStamp
23616
+ };
23617
+ }
23484
23618
  /** Read-only commands' daemon-or-report: never starts anything, exit 3 when not running. */
23485
23619
  async function requireDaemon(config) {
23486
23620
  const handle = await findDaemon(config);
23487
23621
  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.`);
23622
+ const skewed = await findSkewedDaemon(config);
23623
+ if (skewed != null) throw new CliExit(EXIT.notRunning, skewed.message);
23490
23624
  throw new CliExit(EXIT.notRunning, `daemon not running for "${config.name}" (start one with \`up\`)`);
23491
23625
  }
23492
23626
  /** `up`/`ui`'s spawn-or-reuse; the daemon child reruns THIS bin (`daemon` subcommand). */
@@ -23498,7 +23632,8 @@ async function ensureDaemonRunning(config) {
23498
23632
  return {
23499
23633
  record: result.record,
23500
23634
  paths: result.paths,
23501
- spawned: !result.reused
23635
+ spawned: !result.reused,
23636
+ ...result.replaced != null ? { replaced: result.replaced } : {}
23502
23637
  };
23503
23638
  }
23504
23639
  async function mintTicket(record) {
@@ -23519,6 +23654,7 @@ async function mintTicket(record) {
23519
23654
  }
23520
23655
  async function connectDaemon(handle) {
23521
23656
  const { record } = handle;
23657
+ 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
23658
  const ticket = await mintTicket(record);
23523
23659
  const runtime = new ActionRuntime(RuntimeCoordinate.env("commander_cli").withPersistentId(`cli-${(0, node_crypto.randomUUID)().slice(0, 8)}`));
23524
23660
  const connector = connectChannel(runtime, commanderChannel, {
@@ -23556,7 +23692,8 @@ async function connectDaemon(handle) {
23556
23692
  } catch {
23557
23693
  connector.dispose();
23558
23694
  const reason = realm.attachError != null ? String(realm.attachError) : "timeout";
23559
- throw new CliExit(EXIT.failure, `could not attach the status realm (${reason})`);
23695
+ 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.` : "";
23696
+ throw new CliExit(EXIT.failure, `could not attach the status realm (${reason}).${hint}`);
23560
23697
  }
23561
23698
  return {
23562
23699
  record,
@@ -23567,7 +23704,7 @@ async function connectDaemon(handle) {
23567
23704
  const payload = await (await runtime.handleActionPayload(request)).waitForResultPayload();
23568
23705
  if (!payload.result.ok) throw new CliExit(EXIT.failure, `action "${action}" rejected by the daemon`);
23569
23706
  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`);
23707
+ 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
23708
  return report;
23572
23709
  },
23573
23710
  setEnv: async (input) => {
@@ -23672,6 +23809,7 @@ async function cmdUp(ctx) {
23672
23809
  }
23673
23810
  const handle = await ensureDaemonRunning(ctx.config);
23674
23811
  ctx.spawnedDaemon = handle.spawned;
23812
+ 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
23813
  const client = await connectDaemon(handle);
23676
23814
  try {
23677
23815
  const wait = !ctx.args.flags.has("--no-wait");
@@ -23714,17 +23852,71 @@ async function cmdDown(ctx) {
23714
23852
  async function cmdRestart(ctx) {
23715
23853
  return controlVerb(ctx, "restart");
23716
23854
  }
23855
+ /**
23856
+ * `shutdown` must be the command that ALWAYS works — it is the remedy every skew message names.
23857
+ * The wire is tried first (the graceful ask); when the daemon cannot be talked to — another
23858
+ * build's protocol, a changed realm schema, a wedged socket — it falls back to a verified
23859
+ * SIGTERM, which runs the daemon's own shutdown ladder. Without this fallback, the one command
23860
+ * that fixes "the CLI cannot talk to the daemon" was itself behind that same wall.
23861
+ */
23717
23862
  async function cmdShutdown(ctx) {
23718
23863
  const bad = unknownFlags(ctx.args.flags, []);
23719
23864
  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();
23865
+ const { out } = ctx;
23866
+ const handle = await findDaemon(ctx.config);
23867
+ if (handle != null) try {
23868
+ const client = await connectDaemon(handle);
23869
+ try {
23870
+ await client.shutdown();
23871
+ if (out.json) out.printJson({
23872
+ ok: true,
23873
+ via: "wire"
23874
+ });
23875
+ else out.print(`daemon for "${ctx.config.name}" is shutting down`);
23876
+ return EXIT.ok;
23877
+ } finally {
23878
+ client.dispose();
23879
+ }
23880
+ } catch (error) {
23881
+ if (!(error instanceof CliExit)) throw error;
23882
+ return reportSignalShutdown(ctx, await signalDaemonShutdown({
23883
+ pid: handle.record.pid,
23884
+ startStamp: handle.record.startStamp
23885
+ }));
23886
+ }
23887
+ const skewed = await findSkewedDaemon(ctx.config);
23888
+ if (skewed != null) {
23889
+ if (!out.json) out.print(out.paint("gray", skewed.message));
23890
+ return reportSignalShutdown(ctx, await signalDaemonShutdown({
23891
+ pid: skewed.pid,
23892
+ startStamp: skewed.startStamp
23893
+ }));
23894
+ }
23895
+ throw new CliExit(EXIT.notRunning, `daemon not running for "${ctx.config.name}"`);
23896
+ }
23897
+ function reportSignalShutdown(ctx, result) {
23898
+ const { out } = ctx;
23899
+ if (out.json) {
23900
+ out.printJson({
23901
+ ok: result.outcome === "exited",
23902
+ via: "signal",
23903
+ ...result
23904
+ });
23905
+ return result.outcome === "exited" ? EXIT.ok : EXIT.failure;
23906
+ }
23907
+ switch (result.outcome) {
23908
+ case "exited":
23909
+ 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)`);
23910
+ return EXIT.ok;
23911
+ case "still-stopping":
23912
+ out.print(out.paint("yellow", `⚠ daemon (pid ${result.pid}) was signalled and is still stopping — run \`shutdown\` again to escalate if it stays stuck`));
23913
+ return EXIT.failure;
23914
+ case "identity-unverified":
23915
+ 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.`));
23916
+ return EXIT.failure;
23917
+ case "not-running":
23918
+ out.print(`daemon not running for "${ctx.config.name}" (stale record)`);
23919
+ return EXIT.ok;
23728
23920
  }
23729
23921
  }
23730
23922
  //#endregion
@@ -23864,6 +24056,10 @@ async function diagnose(ctx, handle) {
23864
24056
  };
23865
24057
  const paths = commanderStatePaths(resolveCommanderDataDir(), config.configKey);
23866
24058
  report.info.push(handle != null ? `daemon: running (pid ${handle.record.pid}, port ${handle.record.port}, generation ${handle.record.generation})` : `daemon: not running`);
24059
+ if (handle == null) {
24060
+ const skewed = await findSkewedDaemon(config);
24061
+ if (skewed != null) report.warnings.push(skewed.message);
24062
+ }
23867
24063
  if (handle != null) {
23868
24064
  const ping = await pingDaemon(handle.record).catch(() => null);
23869
24065
  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 +25273,7 @@ async function withTimeout(ctx, run) {
25077
25273
  async function main() {
25078
25274
  const argv = process.argv.slice(2);
25079
25275
  if (argv[0] === "daemon") {
25080
- const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-d60iXc8C.cjs"));
25276
+ const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-D1Qv8v0t.cjs"));
25081
25277
  return runCommanderDaemon(argv.slice(1));
25082
25278
  }
25083
25279
  const parsed = parseCliArgs(argv);
@@ -25132,6 +25328,7 @@ exports.RuntimeCoordinate = RuntimeCoordinate;
25132
25328
  exports.applyEnvMutation = applyEnvMutation;
25133
25329
  exports.commanderChannel = commanderChannel;
25134
25330
  exports.commanderControlDomain = commanderControlDomain;
25331
+ exports.commanderPackageVersion = commanderPackageVersion;
25135
25332
  exports.commanderStatePaths = commanderStatePaths;
25136
25333
  exports.commanderStatusRealm = commanderStatusRealm;
25137
25334
  exports.countOverrides = countOverrides;