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