spur-board 0.20.2 → 0.21.1

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/dist/cli.mjs CHANGED
@@ -1,19 +1,21 @@
1
- import { G as SLACK_BOT_SCOPES, P as ERRORS, U as configSchema, W as requiredSecretKeys, l as roleCanUseOperation, r as SYSTEMD_SERVICE_SETTINGS, u as OPERATIONS } from "./src-BQIJz8yP.mjs";
2
- import { a as errorExitCode, i as CliError, n as requestOperation, o as renderCliError, r as requestTokenEnrollment, s as escapeTerminalControls } from "./client-DfvJWQFq.mjs";
3
- import { a as memoryVerdictCache, c as loadEnrollmentConfig, i as fileVerdictCache, l as readConfiguredPort, n as cliPackageVersion, o as configFile, s as loadClientConfig, t as checkCatalog, u as resolveDaemonAddress } from "./config-BDEvO1UV.mjs";
1
+ import { G as SLACK_BOT_SCOPES, P as ERRORS, U as configSchema, W as requiredSecretKeys, l as roleCanUseOperation, r as SYSTEMD_SERVICE_SETTINGS, u as OPERATIONS } from "./src-C6fOCG5L.mjs";
2
+ import { a as errorExitCode, i as CliError, n as requestOperation, o as renderCliError, r as requestTokenEnrollment, s as escapeTerminalControls } from "./client-B4JXkdZu.mjs";
3
+ import { a as memoryVerdictCache, c as loadClientConfig, d as resolveDaemonAddress, i as fileVerdictCache, l as loadEnrollmentConfig, n as cliPackageVersion, o as configFile, s as dataDirectory, t as checkCatalog, u as readConfiguredPort } from "./config-CreYUbFe.mjs";
4
4
  import { createHash, randomBytes, randomUUID } from "node:crypto";
5
- import { chmodSync, closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, statSync, unlinkSync, writeFileSync } from "node:fs";
5
+ import { accessSync, chmodSync, closeSync, constants, cpSync, existsSync, ftruncateSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
6
6
  import { homedir, hostname, userInfo } from "node:os";
7
7
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
8
8
  import { Command, CommanderError } from "@commander-js/extra-typings";
9
9
  import { z } from "zod";
10
10
  import { get } from "node:http";
11
+ import { get as get$1 } from "node:https";
11
12
  import YAML from "yaml";
12
13
  import { spawn, spawnSync } from "node:child_process";
13
14
  import { parseEnv } from "node:util";
14
15
  import { createServer } from "node:net";
15
16
  import { access, cp, lstat, mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
16
17
  import { fileURLToPath } from "node:url";
18
+ import { createInterface } from "node:readline/promises";
17
19
  //#region src/manifest.ts
18
20
  function loadSlackManifestDefaults(env, home) {
19
21
  let contents;
@@ -185,7 +187,7 @@ function liveSessions() {
185
187
  }
186
188
  return sessions;
187
189
  }
188
- const defaultPorts = {
190
+ const defaultPorts$1 = {
189
191
  readText: (path) => readFileSync(path, "utf8"),
190
192
  secretFile: (path) => {
191
193
  const resolved = realpathSync(path);
@@ -401,7 +403,7 @@ async function runDoctor(options = {}) {
401
403
  const env = options.env ?? process.env;
402
404
  const home = options.home ?? homedir();
403
405
  const ports = {
404
- ...defaultPorts,
406
+ ...defaultPorts$1,
405
407
  ...options.ports
406
408
  };
407
409
  const checks = [];
@@ -565,21 +567,24 @@ function renderUserUnit(paths) {
565
567
  ""
566
568
  ].join("\n");
567
569
  }
568
- async function runCommand(command, args) {
570
+ /** Runs a command to completion. */
571
+ async function runCommand(command, args, options = {}) {
569
572
  return new Promise((resolveResult, reject) => {
570
- const child = spawn(command, [...args], { stdio: [
571
- "ignore",
572
- "pipe",
573
- "pipe"
574
- ] });
573
+ const child = spawn(command, [...args], {
574
+ stdio: [
575
+ "ignore",
576
+ "pipe",
577
+ "pipe",
578
+ options.lockFd ?? "ignore"
579
+ ],
580
+ ...options.env === void 0 ? {} : { env: options.env }
581
+ });
575
582
  let stdout = "";
576
583
  let stderr = "";
577
- child.stdout.setEncoding("utf8");
578
- child.stderr.setEncoding("utf8");
579
- child.stdout.on("data", (chunk) => {
584
+ child.stdout?.setEncoding("utf8").on("data", (chunk) => {
580
585
  stdout += chunk;
581
586
  });
582
- child.stderr.on("data", (chunk) => {
587
+ child.stderr?.setEncoding("utf8").on("data", (chunk) => {
583
588
  stderr += chunk;
584
589
  });
585
590
  child.on("error", reject);
@@ -664,7 +669,7 @@ async function installService(options = {}) {
664
669
  const paths = servicePaths(options);
665
670
  await preflight(paths);
666
671
  const runner = options.runner ?? runCommand;
667
- const fix = await checkHttpPort(readConfiguredPort(options.env ?? process.env, resolve(options.home ?? homedir())), {
672
+ const fix = await checkHttpPort(readConfiguredPort(options.env ?? process.env, resolve(options.home ?? homedir())) ?? 4777, {
668
673
  bind: options.bind ?? bindLoopback,
669
674
  run: runner
670
675
  });
@@ -715,6 +720,14 @@ async function restartService(options = {}) {
715
720
  serviceName
716
721
  ], { file: unitFile });
717
722
  }
723
+ /** Stops the service; a failed stop throws with systemctl's output. */
724
+ async function stopService(options = {}) {
725
+ await requireSuccess(options.runner ?? runCommand, "systemctl", [
726
+ "--user",
727
+ "stop",
728
+ serviceName
729
+ ]);
730
+ }
718
731
  async function statusService(options = {}) {
719
732
  const runner = options.runner ?? runCommand;
720
733
  const { active, enabled } = await unitState(runner);
@@ -755,7 +768,7 @@ const skills = [{
755
768
  name: "spur-board-setup"
756
769
  }];
757
770
  const agents = [".claude", ".codex"];
758
- async function packageVersion(packageRoot) {
771
+ async function packageVersion$1(packageRoot) {
759
772
  const manifest = JSON.parse(await readFile(join(packageRoot, "package.json"), "utf8"));
760
773
  if (typeof manifest.version !== "string" || !manifest.version) throw new Error("The spur-board package has no version.");
761
774
  return manifest.version;
@@ -1003,11 +1016,903 @@ async function installSkills(options = {}) {
1003
1016
  const packageRoot = resolve(options.packageRoot ?? fileURLToPath(new URL("../", import.meta.url)));
1004
1017
  const home = await realpath(resolve(options.home ?? homedir()));
1005
1018
  const env = options.env ?? process.env;
1006
- const version = await packageVersion(packageRoot);
1019
+ const version = await packageVersion$1(packageRoot);
1007
1020
  await Promise.all(skills.map((skill) => requireSource(join(packageRoot, "skills", skill.source))));
1008
1021
  return withInstallLock(home, env, () => installIntoHome(home, packageRoot, version, options, env));
1009
1022
  }
1010
1023
  //#endregion
1024
+ //#region src/update.ts
1025
+ const stateSchema = z.object({
1026
+ schema: z.literal(1),
1027
+ status: z.enum([
1028
+ "in-progress",
1029
+ "succeeded",
1030
+ "rolled-back",
1031
+ "rollback-failed"
1032
+ ]),
1033
+ from: z.string(),
1034
+ to: z.string(),
1035
+ startedAt: z.string(),
1036
+ finishedAt: z.string().nullable(),
1037
+ prefix: z.string(),
1038
+ packageRoot: z.string(),
1039
+ snapshot: z.string(),
1040
+ dbFile: z.string(),
1041
+ dbBackup: z.string().nullable(),
1042
+ reason: z.string().nullable(),
1043
+ /** Set once a rollback decided to restore the database, so a retry keeps that decision. */
1044
+ restoreDatabase: z.boolean().optional()
1045
+ });
1046
+ const doctorSchema = z.array(z.object({
1047
+ id: z.string(),
1048
+ status: z.string(),
1049
+ blocking: z.boolean(),
1050
+ fix: z.string().nullable()
1051
+ }));
1052
+ const VERSION = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
1053
+ const MCP_LINE = "Restart agent sessions that run `board mcp` so the MCP server loads the new catalog.";
1054
+ function defaultPorts() {
1055
+ return {
1056
+ runner: runCommand,
1057
+ confirm: async (question) => {
1058
+ const prompt = createInterface({
1059
+ input: process.stdin,
1060
+ output: process.stderr
1061
+ });
1062
+ try {
1063
+ return /^y(es)?$/i.test((await prompt.question(question)).trim());
1064
+ } finally {
1065
+ prompt.close();
1066
+ }
1067
+ },
1068
+ packageRoot: fileURLToPath(new URL("../", import.meta.url)),
1069
+ stdinIsTTY: process.stdin.isTTY,
1070
+ readyTimeoutMs: 12e4,
1071
+ firstPollTimeoutMs: 3e5,
1072
+ lockWaitMs: 2e4,
1073
+ doctorRecheckMs: 6e3,
1074
+ readEnviron: (pid) => readFileSync(`/proc/${String(pid)}/environ`, "utf8"),
1075
+ readCwd: (pid) => readlinkSync(`/proc/${String(pid)}/cwd`),
1076
+ readStatus: (pid) => readFileSync(`/proc/${String(pid)}/status`, "utf8"),
1077
+ sleep: (ms) => new Promise((resolve) => {
1078
+ setTimeout(resolve, ms);
1079
+ }),
1080
+ now: Date.now
1081
+ };
1082
+ }
1083
+ /** A step failure: the step name goes into the hint of the error the caller raises. */
1084
+ var StepError = class extends Error {
1085
+ step;
1086
+ constructor(step, detail) {
1087
+ super(detail);
1088
+ this.step = step;
1089
+ }
1090
+ };
1091
+ function detailOf(error) {
1092
+ return error instanceof Error ? error.message : String(error);
1093
+ }
1094
+ /** The child's JSON error as `code: hint`, else its trimmed output. */
1095
+ function childDetail(result) {
1096
+ const text = result.stderr.trim() || result.stdout.trim();
1097
+ try {
1098
+ const parsed = z.object({ error: z.object({
1099
+ code: z.string(),
1100
+ hint: z.string()
1101
+ }) }).safeParse(JSON.parse(text));
1102
+ if (parsed.success) return `${parsed.data.error.code}: ${parsed.data.error.hint}`;
1103
+ } catch {}
1104
+ return text.replace(/\s*\n\s*/g, " ") || `exit ${String(result.exitCode)}`;
1105
+ }
1106
+ function config(hint) {
1107
+ return new CliError("config", void 0, void 0, hint);
1108
+ }
1109
+ function migrationCount(packageRoot) {
1110
+ try {
1111
+ return readdirSync(join(packageRoot, "dist", "migrations")).filter((name) => name.endsWith(".sql")).length;
1112
+ } catch {
1113
+ return;
1114
+ }
1115
+ }
1116
+ /**
1117
+ * Whether the database is restored: the version being left has another migration count than
1118
+ * the snapshot, or either count cannot be read.
1119
+ */
1120
+ function schemaChanged(leaving, snapshot) {
1121
+ return leaving === void 0 || leaving !== migrationCount(snapshot);
1122
+ }
1123
+ function lockHolder(lockFile) {
1124
+ try {
1125
+ const pid = readFileSync(lockFile, "utf8").trim();
1126
+ return /^\d+$/.test(pid) ? pid : void 0;
1127
+ } catch {
1128
+ return;
1129
+ }
1130
+ }
1131
+ /**
1132
+ * Takes the update lock, so update and rollback never run at the same time: a `flock` on the open
1133
+ * file description of `file`, which is never removed. `flock -n 3` locks the description passed
1134
+ * to it as fd 3, and the lock lasts while any process still has that description open: this one,
1135
+ * or a child given it through `lockFd`. So an update killed during its npm install keeps a
1136
+ * rollback out until npm exits. Returns the fd; closing it releases this process's share.
1137
+ */
1138
+ async function takeUpdateLock(file, runner) {
1139
+ let fd;
1140
+ try {
1141
+ mkdirSync(dirname(file), {
1142
+ recursive: true,
1143
+ mode: 448
1144
+ });
1145
+ fd = openSync(file, "a", 384);
1146
+ } catch (error) {
1147
+ throw config(`Cannot open the update lock ${file}: ${detailOf(error)}`);
1148
+ }
1149
+ let result;
1150
+ try {
1151
+ result = await runner("flock", [
1152
+ "-n",
1153
+ "-E",
1154
+ "75",
1155
+ "3"
1156
+ ], { lockFd: fd });
1157
+ } catch (error) {
1158
+ closeSync(fd);
1159
+ throw config(`Cannot take the update lock ${file}: ${detailOf(error)}`);
1160
+ }
1161
+ if (result.exitCode === 0) {
1162
+ try {
1163
+ ftruncateSync(fd, 0);
1164
+ writeSync(fd, `${String(process.pid)}\n`);
1165
+ } catch {}
1166
+ return fd;
1167
+ }
1168
+ closeSync(fd);
1169
+ if (result.exitCode === 75) {
1170
+ const holder = lockHolder(file);
1171
+ throw config(`Another \`board update\` or \`board rollback\` holds the update lock ${file}${holder === void 0 ? "" : ` (taken by PID ${holder})`}; wait for it, and for the install steps it started, to finish.`);
1172
+ }
1173
+ throw config(`Cannot take the update lock ${file}: flock failed (exit ${String(result.exitCode)})${result.stderr.trim() ? `: ${result.stderr.trim()}` : ""}`);
1174
+ }
1175
+ /** Removes a leftover file or dir; a failure leaves it, which costs only disk space. */
1176
+ function removeQuietly(path) {
1177
+ try {
1178
+ rmSync(path, {
1179
+ recursive: true,
1180
+ force: true
1181
+ });
1182
+ } catch {}
1183
+ }
1184
+ function readState(file) {
1185
+ let text;
1186
+ try {
1187
+ text = readFileSync(file, "utf8");
1188
+ } catch {
1189
+ return;
1190
+ }
1191
+ try {
1192
+ const parsed = stateSchema.safeParse(JSON.parse(text));
1193
+ if (parsed.success) return parsed.data;
1194
+ } catch {}
1195
+ throw config(`Update state ${file} is not readable; remove it only after checking the install.`);
1196
+ }
1197
+ function writeState(file, state) {
1198
+ const temporary = `${file}.${randomUUID()}.tmp`;
1199
+ mkdirSync(dirname(file), {
1200
+ recursive: true,
1201
+ mode: 448
1202
+ });
1203
+ try {
1204
+ writeFileSync(temporary, `${JSON.stringify(state, null, 2)}\n`, { mode: 384 });
1205
+ renameSync(temporary, file);
1206
+ } catch (error) {
1207
+ rmSync(temporary, { force: true });
1208
+ throw error;
1209
+ }
1210
+ }
1211
+ function compareCore(left, right) {
1212
+ const parts = (version) => version.split(/[-+]/)[0]?.split(".").map(Number) ?? [];
1213
+ const [a, b] = [parts(left), parts(right)];
1214
+ for (let index = 0; index < 3; index += 1) {
1215
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
1216
+ if (difference !== 0) return difference;
1217
+ }
1218
+ return 0;
1219
+ }
1220
+ function unitLines(text) {
1221
+ const lines = text.split("\n");
1222
+ return {
1223
+ execStart: lines.find((line) => line.startsWith("ExecStart=")) ?? "(no ExecStart line)",
1224
+ environment: lines.filter((line) => line.startsWith("Environment=")).sort()
1225
+ };
1226
+ }
1227
+ /** `NAME=value` entries split at the first `=`, from `systemctl show` lines or an environ. */
1228
+ function entries(text, separator) {
1229
+ const result = /* @__PURE__ */ new Map();
1230
+ for (const entry of text.split(separator)) {
1231
+ const equals = entry.indexOf("=");
1232
+ if (equals > 0) result.set(entry.slice(0, equals), entry.slice(equals + 1));
1233
+ }
1234
+ return result;
1235
+ }
1236
+ /**
1237
+ * Checks the daemon the service runs, drop-ins, `EnvironmentFile` and `UnsetEnvironment`
1238
+ * included: the `argv[]` of the loaded `ExecStart`, the real and effective uids of its main process, then the
1239
+ * config file and data directory that process resolves from its own environment, home and
1240
+ * working directory, compared with this shell's.
1241
+ */
1242
+ async function checkRunningService(updater, argv) {
1243
+ const { ports } = updater;
1244
+ const show = await ports.runner("systemctl", [
1245
+ "--user",
1246
+ "show",
1247
+ serviceName,
1248
+ "--property=MainPID,ExecStart"
1249
+ ]);
1250
+ if (show.exitCode !== 0) throw config(`systemctl --user show ${serviceName} failed: ${childDetail(show)}`);
1251
+ const properties = entries(show.stdout, "\n");
1252
+ const execStart = properties.get("ExecStart") ?? "";
1253
+ const running = /argv\[\]=(.*?) ; /.exec(execStart)?.[1];
1254
+ const override = `a drop-in or environment setting overrides the unit file (\`systemctl --user cat ${serviceName}\` lists them). Remove the override and run \`board service install\`, or run \`board update\` from the environment the service runs with.`;
1255
+ if (running !== argv) throw config(`The running service has ExecStart ${running ?? `(${execStart || "not loaded"})`} but this shell gives ExecStart ${argv}; ${override}`);
1256
+ const mainPid = properties.get("MainPID") ?? "";
1257
+ const pid = /^\d+$/.test(mainPid) ? Number(mainPid) : 0;
1258
+ if (pid === 0) throw config(`The service has no main process (MainPID=${mainPid || "not shown"}); Board update needs a running service. Check \`board service status\`.`);
1259
+ const read = (what, value) => {
1260
+ try {
1261
+ return value();
1262
+ } catch (error) {
1263
+ throw config(`Cannot read the ${what} of the service's main process ${String(pid)}: ${detailOf(error)}. Board update reads it to check which database the daemon uses.`);
1264
+ }
1265
+ };
1266
+ const [uid, euid] = read("status", () => {
1267
+ const fields = /^Uid:\s+(\d+)\s+(\d+)/m.exec(ports.readStatus(pid));
1268
+ if (fields === null) throw new Error("it has no Uid line with a real and an effective uid");
1269
+ return [Number(fields[1]), Number(fields[2])];
1270
+ });
1271
+ const shellUid = process.getuid?.();
1272
+ const shellEuid = process.geteuid?.();
1273
+ if (uid !== shellUid || euid !== shellEuid) throw config(`The service's main process ${String(pid)} runs as uid ${String(uid)} with effective uid ${String(euid)} but this shell runs as uid ${String(shellUid)} with effective uid ${String(shellEuid)}; run \`board update\` as the user the daemon runs as.`);
1274
+ const environ = read("environment", () => ports.readEnviron(pid));
1275
+ const daemonEnv = Object.fromEntries(entries(environ, "\0"));
1276
+ const cwd = read("working directory", () => ports.readCwd(pid));
1277
+ const daemonHome = resolve(cwd, daemonEnv["HOME"] ?? read("passwd home directory", () => userInfo().homedir));
1278
+ const pairs = [[
1279
+ "data directory",
1280
+ dataDirectory(daemonEnv, daemonHome, cwd),
1281
+ updater.dataDir
1282
+ ], [
1283
+ "config file",
1284
+ configFile(daemonEnv, daemonHome, cwd),
1285
+ updater.configFile
1286
+ ]];
1287
+ for (const [what, daemon, shell] of pairs) if (daemon !== shell) throw config(`The running service (PID ${String(pid)}) uses the ${what} ${daemon} but this shell gives ${shell}; ${override}`);
1288
+ }
1289
+ function probe(address, path) {
1290
+ const url = new URL(path, address);
1291
+ const get$2 = url.protocol === "https:" ? get$1 : get;
1292
+ return new Promise((resolve) => {
1293
+ get$2(url, {
1294
+ agent: false,
1295
+ signal: AbortSignal.timeout(2e3)
1296
+ }, (response) => {
1297
+ let body = "";
1298
+ response.setEncoding("utf8");
1299
+ response.on("data", (chunk) => {
1300
+ body += chunk;
1301
+ });
1302
+ response.on("end", () => {
1303
+ const instance = response.headers["x-board-instance"];
1304
+ resolve({
1305
+ status: response.statusCode ?? 0,
1306
+ instance: typeof instance === "string" ? instance : void 0,
1307
+ body
1308
+ });
1309
+ });
1310
+ response.on("error", () => {
1311
+ resolve(void 0);
1312
+ });
1313
+ }).once("error", () => {
1314
+ resolve(void 0);
1315
+ });
1316
+ });
1317
+ }
1318
+ /** Runs one update or rollback; the ports and paths are fixed for its whole run. */
1319
+ var Updater = class {
1320
+ ports;
1321
+ env;
1322
+ home;
1323
+ progress;
1324
+ address;
1325
+ /** This shell's data directory and config file, absolute even for a relative HOME. */
1326
+ dataDir;
1327
+ configFile;
1328
+ /** The env of the package's own children: HOME and BOARD_HOME absolute, as this shell's. */
1329
+ childEnv;
1330
+ updateDir;
1331
+ stateFile;
1332
+ updateLock;
1333
+ dbFile;
1334
+ lockFile;
1335
+ /** The update lock's fd while `locked` runs. */
1336
+ lockFd;
1337
+ constructor(options, label) {
1338
+ this.ports = {
1339
+ ...defaultPorts(),
1340
+ ...options.ports
1341
+ };
1342
+ this.env = options.env;
1343
+ this.home = options.home;
1344
+ this.progress = (step) => {
1345
+ options.progress(`${label}: ${step}\n`);
1346
+ };
1347
+ this.address = resolveDaemonAddress(options.env, options.home);
1348
+ this.dataDir = resolve(dataDirectory(options.env, options.home));
1349
+ this.configFile = resolve(configFile(options.env, options.home));
1350
+ const boardHome = options.env["BOARD_HOME"];
1351
+ this.childEnv = {
1352
+ ...options.env,
1353
+ HOME: resolve(options.home),
1354
+ ...boardHome ? { BOARD_HOME: resolve(boardHome) } : {}
1355
+ };
1356
+ this.updateDir = join(this.dataDir, "update");
1357
+ this.stateFile = join(this.updateDir, "state.json");
1358
+ this.updateLock = join(this.updateDir, "update.lock");
1359
+ this.dbFile = join(this.dataDir, "board.sqlite");
1360
+ this.lockFile = join(this.dataDir, "board.lock");
1361
+ }
1362
+ /** Runs `body` under the update lock, taken before any state is read. */
1363
+ async locked(body) {
1364
+ const fd = await takeUpdateLock(this.updateLock, this.ports.runner);
1365
+ this.lockFd = fd;
1366
+ try {
1367
+ return await body();
1368
+ } finally {
1369
+ this.lockFd = void 0;
1370
+ closeSync(fd);
1371
+ }
1372
+ }
1373
+ /** Run options for a child that changes the install: it shares the update lock. */
1374
+ holding(env) {
1375
+ return {
1376
+ ...env === void 0 ? {} : { env },
1377
+ ...this.lockFd === void 0 ? {} : { lockFd: this.lockFd }
1378
+ };
1379
+ }
1380
+ bin(packageRoot) {
1381
+ return join(packageRoot, "dist", "bin.mjs");
1382
+ }
1383
+ npmEnv() {
1384
+ const path = this.env["PATH"];
1385
+ const node = dirname(process.execPath);
1386
+ return {
1387
+ ...this.env,
1388
+ PATH: path ? `${node}:${path}` : node
1389
+ };
1390
+ }
1391
+ async child(packageRoot, step, args) {
1392
+ const result = await this.ports.runner(process.execPath, [this.bin(packageRoot), ...args], this.holding(this.childEnv));
1393
+ if (result.exitCode !== 0) throw new StepError(step, childDetail(result));
1394
+ return result.stdout;
1395
+ }
1396
+ /** A doctor run: exit 0 or 1 with a parsable check list is a result; else a StepError. */
1397
+ async doctor(packageRoot) {
1398
+ const result = await this.ports.runner(process.execPath, [
1399
+ this.bin(packageRoot),
1400
+ "--json",
1401
+ "doctor"
1402
+ ], { env: this.childEnv });
1403
+ if (result.exitCode === 0 || result.exitCode === 1) try {
1404
+ const parsed = doctorSchema.safeParse(JSON.parse(result.stdout));
1405
+ if (parsed.success) return parsed.data;
1406
+ } catch {}
1407
+ throw new StepError("doctor", `the doctor child returned no check list: ${childDetail(result)}`);
1408
+ }
1409
+ async instance() {
1410
+ const answer = await probe(this.address, "/v1/schema");
1411
+ return answer?.status === 200 ? answer.instance : void 0;
1412
+ }
1413
+ /** Polls /v1/schema until it answers 200, from an instance other than `previous` when given. */
1414
+ async waitReady(previous) {
1415
+ const deadline = this.ports.now() + this.ports.readyTimeoutMs;
1416
+ for (;;) {
1417
+ const answer = await probe(this.address, "/v1/schema");
1418
+ if (answer?.status === 200 && (previous === void 0 || answer.instance !== previous)) return;
1419
+ if (this.ports.now() >= deadline) break;
1420
+ await this.ports.sleep(1e3);
1421
+ }
1422
+ throw new StepError("readiness", `the daemon was not ready at ${this.address.origin}/v1/schema within ${String(this.ports.readyTimeoutMs / 1e3)} s`);
1423
+ }
1424
+ /** Polls /v1/health until every required source finished a poll; a daemon without it skips. */
1425
+ async waitFirstPoll() {
1426
+ const deadline = this.ports.now() + this.ports.firstPollTimeoutMs;
1427
+ for (;;) {
1428
+ const answer = await probe(this.address, "/v1/health");
1429
+ if (answer?.status === 404) return "unsupported";
1430
+ if (answer?.status === 200) try {
1431
+ if (JSON.parse(answer.body).firstPollDone === true) return "done";
1432
+ } catch {}
1433
+ if (this.ports.now() >= deadline) break;
1434
+ await this.ports.sleep(2e3);
1435
+ }
1436
+ throw new StepError("first poll", `the sources did not finish their first complete poll within ${String(this.ports.firstPollTimeoutMs / 1e3)} s`);
1437
+ }
1438
+ async stop() {
1439
+ this.progress("stop");
1440
+ try {
1441
+ await stopService({
1442
+ env: this.env,
1443
+ home: this.home,
1444
+ runner: (command, args) => this.ports.runner(command, args, this.holding())
1445
+ });
1446
+ } catch (error) {
1447
+ throw new StepError("stop", detailOf(error));
1448
+ }
1449
+ }
1450
+ /** Stops the service and waits for the lock; a failed stop is fine when no process holds it. */
1451
+ async stopAndWaitLock() {
1452
+ try {
1453
+ await this.stop();
1454
+ } catch (error) {
1455
+ this.progress(`stop failed (${detailOf(error)}); checking the lock`);
1456
+ }
1457
+ await this.waitLock();
1458
+ }
1459
+ /** Waits until no process holds the board lock, so no daemon has the database open. */
1460
+ async waitLock() {
1461
+ this.progress("lock wait");
1462
+ const deadline = this.ports.now() + this.ports.lockWaitMs;
1463
+ for (;;) {
1464
+ const result = await this.ports.runner("flock", [
1465
+ "-n",
1466
+ "-E",
1467
+ "75",
1468
+ this.lockFile,
1469
+ "true"
1470
+ ]);
1471
+ if (result.exitCode === 0) return;
1472
+ if (result.exitCode !== 75) {
1473
+ const stderr = result.stderr.trim();
1474
+ throw new StepError("lock wait", `checking the database lock ${this.lockFile} with flock failed (exit ${String(result.exitCode)})${stderr ? `: ${stderr}` : ""}`);
1475
+ }
1476
+ if (this.ports.now() >= deadline) break;
1477
+ await this.ports.sleep(500);
1478
+ }
1479
+ const pid = lockHolder(this.lockFile);
1480
+ throw new StepError("lock wait", `the database lock ${this.lockFile} is still held${pid === void 0 ? "" : ` by PID ${pid}`}; stop that process`);
1481
+ }
1482
+ /** Brings the service back after a failure before any change; returns a failure note. */
1483
+ async restart(packageRoot) {
1484
+ this.progress("restart");
1485
+ try {
1486
+ await this.child(packageRoot, "service install", [
1487
+ "--json",
1488
+ "service",
1489
+ "install"
1490
+ ]);
1491
+ await this.waitReady(void 0);
1492
+ return "";
1493
+ } catch (error) {
1494
+ return ` The service did not start again: ${detailOf(error)}.`;
1495
+ }
1496
+ }
1497
+ finish(state, status, reason) {
1498
+ writeState(this.stateFile, {
1499
+ ...state,
1500
+ status,
1501
+ reason,
1502
+ finishedAt: new Date(this.ports.now()).toISOString()
1503
+ });
1504
+ }
1505
+ /**
1506
+ * Puts the snapshot package back and, when `restoreDatabase`, the backup database. `stopped`
1507
+ * holds the instance seen before the caller's own stop and lock wait; without it this stops.
1508
+ */
1509
+ async rollback(state, restoreDatabase, reason, stopped) {
1510
+ const current = {
1511
+ ...state,
1512
+ ...restoreDatabase ? { restoreDatabase } : {}
1513
+ };
1514
+ let step = "stop";
1515
+ try {
1516
+ writeState(this.stateFile, current);
1517
+ let previous = stopped?.previous;
1518
+ if (stopped === void 0) {
1519
+ previous = await this.instance();
1520
+ step = "lock wait";
1521
+ await this.stopAndWaitLock();
1522
+ }
1523
+ return await this.restore(current, restoreDatabase, reason, previous, (next) => {
1524
+ step = next;
1525
+ });
1526
+ } catch (error) {
1527
+ const failed = error instanceof StepError ? error.step : step;
1528
+ const detail = detailOf(error);
1529
+ try {
1530
+ this.finish(current, "rollback-failed", `${failed}: ${detail}`);
1531
+ } catch {}
1532
+ throw new CliError("rollback_failed", void 0, void 0, `Rolling back to ${state.from} failed at ${failed}: ${detail}. Fix it, then run \`board rollback --yes\`. The package snapshot is ${state.snapshot}${state.dbBackup === null ? "" : ` and the database backup is ${state.dbBackup}`}.`);
1533
+ }
1534
+ }
1535
+ async restore(state, restoreDatabase, reason, previous, at) {
1536
+ at("package restore");
1537
+ this.progress("package restore");
1538
+ restorePackage(state.snapshot, state.packageRoot);
1539
+ if (restoreDatabase && state.dbBackup !== null) {
1540
+ at("database restore");
1541
+ this.progress("database restore");
1542
+ await this.child(state.packageRoot, "database restore", [
1543
+ "copy-database",
1544
+ state.dbBackup,
1545
+ state.dbFile
1546
+ ]);
1547
+ }
1548
+ this.progress("service install");
1549
+ await this.child(state.packageRoot, "service install", [
1550
+ "--json",
1551
+ "service",
1552
+ "install"
1553
+ ]);
1554
+ this.progress("readiness");
1555
+ await this.waitReady(previous);
1556
+ this.progress("skills install");
1557
+ await this.child(state.packageRoot, "skills install", [
1558
+ "--json",
1559
+ "skills",
1560
+ "install"
1561
+ ]);
1562
+ this.finish(state, "rolled-back", reason);
1563
+ return restoreDatabase && state.dbBackup !== null ? "restored" : "kept";
1564
+ }
1565
+ };
1566
+ /**
1567
+ * Swaps the package dir for the snapshot. The snapshot is copied next to the package dir first,
1568
+ * so a failed copy leaves the package dir as it was; a package dir that npm already removed is
1569
+ * simply replaced.
1570
+ */
1571
+ function restorePackage(snapshot, packageRoot) {
1572
+ const id = randomUUID();
1573
+ const staged = `${packageRoot}.restore-${id}`;
1574
+ const aside = `${packageRoot}.rollback-${id}`;
1575
+ try {
1576
+ cpSync(snapshot, staged, {
1577
+ recursive: true,
1578
+ verbatimSymlinks: true
1579
+ });
1580
+ } catch (error) {
1581
+ rmSync(staged, {
1582
+ recursive: true,
1583
+ force: true
1584
+ });
1585
+ throw new StepError("package restore", `copying ${snapshot} failed: ${detailOf(error)}`);
1586
+ }
1587
+ let present = true;
1588
+ try {
1589
+ renameSync(packageRoot, aside);
1590
+ } catch (error) {
1591
+ if (error.code !== "ENOENT") {
1592
+ rmSync(staged, {
1593
+ recursive: true,
1594
+ force: true
1595
+ });
1596
+ throw new StepError("package restore", `moving ${packageRoot} aside failed: ${detailOf(error)}`);
1597
+ }
1598
+ present = false;
1599
+ }
1600
+ try {
1601
+ renameSync(staged, packageRoot);
1602
+ } catch (error) {
1603
+ if (present) renameSync(aside, packageRoot);
1604
+ rmSync(staged, {
1605
+ recursive: true,
1606
+ force: true
1607
+ });
1608
+ throw new StepError("package restore", `moving ${staged} into place failed: ${detailOf(error)}`);
1609
+ }
1610
+ if (present) rmSync(aside, {
1611
+ recursive: true,
1612
+ force: true
1613
+ });
1614
+ }
1615
+ function packageLayout(packageRoot) {
1616
+ let root;
1617
+ try {
1618
+ root = realpathSync(packageRoot);
1619
+ } catch {
1620
+ throw config(`The package directory ${packageRoot} cannot be read.`);
1621
+ }
1622
+ const modules = dirname(root);
1623
+ const lib = dirname(modules);
1624
+ if (basename(root) !== "spur-board" || basename(modules) !== "node_modules") throw config(`This package at ${root} is not a global npm install; update it the way it was installed.`);
1625
+ if (basename(lib) !== "lib") throw config(`The package at ${root} is not under <prefix>/lib/node_modules.`);
1626
+ try {
1627
+ accessSync(modules, constants.W_OK);
1628
+ } catch {
1629
+ throw config(`${modules} is not writable by this user; Board update needs a user npm prefix.`);
1630
+ }
1631
+ return {
1632
+ root,
1633
+ prefix: dirname(lib)
1634
+ };
1635
+ }
1636
+ function packageVersion(root) {
1637
+ try {
1638
+ const version = JSON.parse(readFileSync(join(root, "package.json"), "utf8")).version;
1639
+ if (typeof version === "string" && version) return version;
1640
+ } catch {}
1641
+ throw config(`The version of the package at ${root} cannot be read.`);
1642
+ }
1643
+ /** The `changed` field of a `service install` result, or null when it cannot be read. */
1644
+ function changedField(stdout) {
1645
+ try {
1646
+ const parsed = z.object({ changed: z.boolean() }).safeParse(JSON.parse(stdout));
1647
+ return parsed.success ? parsed.data.changed : null;
1648
+ } catch {
1649
+ return null;
1650
+ }
1651
+ }
1652
+ function blockingIds(report) {
1653
+ return new Set(report.filter((check) => check.blocking).map((check) => check.id));
1654
+ }
1655
+ /** `board update [version]`: preflight, snapshot, stop, backup, install, then health checks. */
1656
+ async function updatePackage(options, requested) {
1657
+ const updater = new Updater(options, "update");
1658
+ return updater.locked(() => update(updater, options, requested));
1659
+ }
1660
+ async function update(updater, options, requested) {
1661
+ const { ports } = updater;
1662
+ const { root, prefix } = packageLayout(ports.packageRoot);
1663
+ const from = packageVersion(root);
1664
+ const previous = readState(updater.stateFile);
1665
+ if (previous?.status === "in-progress" || previous?.status === "rollback-failed") throw config(`The update from ${previous.from} to ${previous.to} did not finish (state ${previous.status}); run \`board rollback --yes\` first.`);
1666
+ const unitPaths = servicePaths({
1667
+ env: options.env,
1668
+ home: options.home,
1669
+ nodePath: process.execPath,
1670
+ daemonEntry: join(root, "dist", "daemon.mjs")
1671
+ });
1672
+ let unitText;
1673
+ try {
1674
+ unitText = readFileSync(unitPaths.unitFile, "utf8");
1675
+ } catch {
1676
+ throw config(`Unit file ${unitPaths.unitFile} is not installed; run \`board service install\` first.`);
1677
+ }
1678
+ const unit = unitLines(unitText);
1679
+ const expected = unitLines(renderUserUnit(unitPaths));
1680
+ const mismatch = unit.execStart !== expected.execStart ? [unit.execStart, expected.execStart] : unit.environment.join("\n") !== expected.environment.join("\n") ? [unit.environment.join(" ") || "(no Environment line)", expected.environment.join(" ") || "(no Environment line)"] : void 0;
1681
+ if (mismatch) throw config(`The service unit has ${mismatch[0] ?? ""} but this shell gives ${mismatch[1] ?? ""}; run \`board update\` from the environment the service was installed from, or run \`board service install\` first.`);
1682
+ await checkRunningService(updater, `${unitPaths.nodePath} ${unitPaths.daemonEntry}`);
1683
+ const before = await probe(updater.address, "/v1/schema");
1684
+ if (before?.status !== 200) throw config(`The daemon is not ready at ${updater.address.origin} (${before === void 0 ? "no answer" : `HTTP ${String(before.status)}`}); Board update needs a running daemon. Check \`board service status\`.`);
1685
+ if (requested !== void 0 && !VERSION.test(requested)) throw new CliError("usage", void 0, void 0, `Version ${requested} is not a version like 1.2.3; omit it for the latest.`);
1686
+ const npmEnv = updater.npmEnv();
1687
+ const spec = `spur-board@${requested ?? "latest"}`;
1688
+ const view = await ports.runner("npm", [
1689
+ "view",
1690
+ spec,
1691
+ "version",
1692
+ "--json"
1693
+ ], { env: npmEnv });
1694
+ if (view.exitCode !== 0 && !/E404/.test(view.stderr)) throw config(`npm view ${spec} failed: ${childDetail(view)}`);
1695
+ let to;
1696
+ try {
1697
+ const parsed = view.exitCode === 0 ? JSON.parse(view.stdout || "null") : null;
1698
+ const value = Array.isArray(parsed) ? parsed.at(-1) : parsed;
1699
+ to = typeof value === "string" && value ? value : void 0;
1700
+ } catch {
1701
+ to = void 0;
1702
+ }
1703
+ if (to === void 0) throw new CliError("usage", void 0, void 0, `There is no published version ${spec}.`);
1704
+ if (to === from) return {
1705
+ from,
1706
+ to,
1707
+ changed: false
1708
+ };
1709
+ if (compareCore(to, from) < 0) throw new CliError("usage", void 0, void 0, `Version ${to} is older than the installed ${from}; to go back to the version before the last update, run \`board rollback\`.`);
1710
+ const target = `spur-board@${to}`;
1711
+ const npmArgs = [
1712
+ "--engine-strict",
1713
+ "--prefix",
1714
+ prefix,
1715
+ "--no-audit",
1716
+ "--no-fund",
1717
+ target
1718
+ ];
1719
+ const dryRun = await ports.runner("npm", [
1720
+ "install",
1721
+ "-g",
1722
+ "--dry-run",
1723
+ ...npmArgs
1724
+ ], { env: npmEnv });
1725
+ if (dryRun.exitCode !== 0) throw config(`${target} cannot be installed with this Node: ${childDetail(dryRun)}`);
1726
+ updater.progress("doctor");
1727
+ let baseline;
1728
+ try {
1729
+ baseline = await updater.doctor(root);
1730
+ } catch (error) {
1731
+ throw config(`Before the update, ${detailOf(error)}. Run \`board doctor\` to see why.`);
1732
+ }
1733
+ const blockedBefore = blockingIds(baseline);
1734
+ updater.progress("snapshot");
1735
+ const startedAt = new Date(ports.now()).toISOString();
1736
+ const snapshot = join(updater.updateDir, `package-${from}`);
1737
+ const partial = `${snapshot}.partial`;
1738
+ try {
1739
+ mkdirSync(updater.updateDir, {
1740
+ recursive: true,
1741
+ mode: 448
1742
+ });
1743
+ rmSync(partial, {
1744
+ recursive: true,
1745
+ force: true
1746
+ });
1747
+ cpSync(root, partial, {
1748
+ recursive: true,
1749
+ verbatimSymlinks: true
1750
+ });
1751
+ rmSync(snapshot, {
1752
+ recursive: true,
1753
+ force: true
1754
+ });
1755
+ renameSync(partial, snapshot);
1756
+ } catch (error) {
1757
+ rmSync(partial, {
1758
+ recursive: true,
1759
+ force: true
1760
+ });
1761
+ throw config(`Could not snapshot the package to ${snapshot}: ${detailOf(error)}`);
1762
+ }
1763
+ const backupDir = join(updater.updateDir, "db");
1764
+ const backup = join(backupDir, `board-${from}.sqlite`);
1765
+ const state = {
1766
+ schema: 1,
1767
+ status: "in-progress",
1768
+ from,
1769
+ to,
1770
+ startedAt,
1771
+ finishedAt: null,
1772
+ prefix,
1773
+ packageRoot: root,
1774
+ snapshot,
1775
+ dbFile: updater.dbFile,
1776
+ dbBackup: backup,
1777
+ reason: null
1778
+ };
1779
+ try {
1780
+ await updater.stop();
1781
+ await updater.waitLock();
1782
+ updater.progress("database backup");
1783
+ try {
1784
+ mkdirSync(backupDir, {
1785
+ recursive: true,
1786
+ mode: 448
1787
+ });
1788
+ chmodSync(backupDir, 448);
1789
+ } catch (error) {
1790
+ throw new StepError("database backup", detailOf(error));
1791
+ }
1792
+ await updater.child(root, "database backup", [
1793
+ "copy-database",
1794
+ updater.dbFile,
1795
+ backup
1796
+ ]);
1797
+ writeState(updater.stateFile, state);
1798
+ } catch (error) {
1799
+ const failure = error instanceof StepError ? error : new StepError("database backup", detailOf(error));
1800
+ if (snapshot !== previous?.snapshot) removeQuietly(snapshot);
1801
+ if (backup !== previous?.dbBackup) removeQuietly(backup);
1802
+ const restart = await updater.restart(root);
1803
+ throw new CliError("update_rolled_back", void 0, void 0, `Update to ${to} stopped at ${failure.step}: ${failure.message}. The package and database were not changed.${restart}`);
1804
+ }
1805
+ try {
1806
+ for (const name of readdirSync(updater.updateDir)) if (name.startsWith("package-") && join(updater.updateDir, name) !== snapshot) removeQuietly(join(updater.updateDir, name));
1807
+ for (const name of readdirSync(backupDir)) if (join(backupDir, name) !== backup) removeQuietly(join(backupDir, name));
1808
+ } catch (error) {
1809
+ updater.progress(`cleanup skipped (${detailOf(error)})`);
1810
+ }
1811
+ let leaving;
1812
+ let installed = false;
1813
+ try {
1814
+ updater.progress("npm install");
1815
+ const install = await ports.runner("npm", [
1816
+ "install",
1817
+ "-g",
1818
+ ...npmArgs
1819
+ ], updater.holding(npmEnv));
1820
+ leaving = migrationCount(root);
1821
+ installed = true;
1822
+ if (install.exitCode !== 0) throw new StepError("npm install", childDetail(install));
1823
+ updater.progress("service install");
1824
+ const unitChanged = changedField(await updater.child(root, "service install", [
1825
+ "--json",
1826
+ "service",
1827
+ "install"
1828
+ ]));
1829
+ updater.progress("readiness");
1830
+ await updater.waitReady(before.instance);
1831
+ updater.progress("skills install");
1832
+ await updater.child(root, "skills install", [
1833
+ "--json",
1834
+ "skills",
1835
+ "install"
1836
+ ]);
1837
+ updater.progress("first poll");
1838
+ const firstPoll = await updater.waitFirstPoll();
1839
+ updater.progress("doctor");
1840
+ let report = await updater.doctor(root);
1841
+ const newly = [...blockingIds(report)].filter((id) => !blockedBefore.has(id));
1842
+ if (newly.length > 0) {
1843
+ await ports.sleep(ports.doctorRecheckMs);
1844
+ report = await updater.doctor(root);
1845
+ const still = blockingIds(report);
1846
+ const persistent = newly.filter((id) => still.has(id));
1847
+ if (persistent.length > 0) throw new StepError("doctor", `newly blocking checks: ${persistent.join(", ")}`);
1848
+ }
1849
+ updater.finish(state, "succeeded", null);
1850
+ const stale = report.find((check) => check.id === "sessions.stale");
1851
+ const operator = [MCP_LINE, ...stale?.status === "warning" && stale.fix !== null ? [`Stop and wake these Spur sessions so they load the new skill: ${stale.fix}`] : []];
1852
+ return {
1853
+ from,
1854
+ to,
1855
+ changed: true,
1856
+ unitChanged,
1857
+ database: {
1858
+ backup: state.dbBackup,
1859
+ schemaChanged: schemaChanged(leaving, snapshot)
1860
+ },
1861
+ firstPoll,
1862
+ operator
1863
+ };
1864
+ } catch (error) {
1865
+ const failure = error instanceof StepError ? error : new StepError("update", detailOf(error));
1866
+ if (!installed) leaving = migrationCount(root);
1867
+ const restoreDatabase = schemaChanged(leaving, snapshot);
1868
+ const reason = `${failure.step}: ${failure.message}`;
1869
+ const database = await updater.rollback(state, restoreDatabase, reason);
1870
+ throw new CliError("update_rolled_back", void 0, void 0, `Update to ${to} failed at ${failure.step}: ${failure.message}. Version ${from} is back and its database was ${database === "restored" ? "restored from the backup taken before the update" : "kept"}.`);
1871
+ }
1872
+ }
1873
+ /** `board rollback`: go back to the version before the last update, after consent. */
1874
+ async function rollbackPackage(options, yes) {
1875
+ const updater = new Updater(options, "rollback");
1876
+ return updater.locked(() => rollback(updater, options, yes));
1877
+ }
1878
+ async function rollback(updater, options, yes) {
1879
+ const { ports } = updater;
1880
+ const state = readState(updater.stateFile);
1881
+ if (state === void 0 || ![
1882
+ "in-progress",
1883
+ "succeeded",
1884
+ "rollback-failed"
1885
+ ].includes(state.status)) throw config(`No update to roll back${state === void 0 ? "" : ` (the last one ended ${state.status})`}.`);
1886
+ const restoreDatabase = state.dbBackup !== null && (state.restoreDatabase === true || schemaChanged(migrationCount(state.packageRoot), state.snapshot));
1887
+ const lost = restoreDatabase ? `Board changes and journal events recorded after ${state.startedAt}.` : state.dbBackup === null ? "Nothing: no database backup was taken, so the current database was kept." : "Nothing: the schema did not change, so the current database was kept.";
1888
+ options.progress(`rollback: from ${state.to} to ${state.from}; the database is ${restoreDatabase ? "restored from the backup" : "kept"}. Lost: ${lost}\n`);
1889
+ if (!yes) {
1890
+ if (!(ports.stdinIsTTY && options.stdoutIsTTY)) throw new CliError("usage", void 0, void 0, "Read what is lost above, then rerun with --yes.");
1891
+ if (!await ports.confirm("Continue? [y/N] ")) return {
1892
+ from: state.to,
1893
+ to: state.from,
1894
+ rolledBack: false
1895
+ };
1896
+ }
1897
+ const previous = await updater.instance();
1898
+ try {
1899
+ await updater.stopAndWaitLock();
1900
+ } catch (error) {
1901
+ const failure = error instanceof StepError ? error : new StepError("stop", detailOf(error));
1902
+ const restart = await updater.restart(state.packageRoot);
1903
+ throw config(`Rollback stopped at ${failure.step}: ${failure.message}. Nothing was changed.${restart}`);
1904
+ }
1905
+ const reason = `rollback requested after ${state.status === "succeeded" ? "the update" : `state ${state.status}`}`;
1906
+ const database = await updater.rollback(state, restoreDatabase, reason, { previous });
1907
+ return {
1908
+ from: state.to,
1909
+ to: state.from,
1910
+ database,
1911
+ lost,
1912
+ operator: [MCP_LINE]
1913
+ };
1914
+ }
1915
+ //#endregion
1011
1916
  //#region src/cli.ts
1012
1917
  const processIo = {
1013
1918
  stdout: (text) => process.stdout.write(text),
@@ -1233,12 +2138,31 @@ function registerSetupCommands(program, options, io, env) {
1233
2138
  ...await runSetup(() => uninstallService(serviceOptions))
1234
2139
  });
1235
2140
  });
2141
+ const updateOptions = () => ({
2142
+ env,
2143
+ home: options.home ?? homedir(),
2144
+ stdoutIsTTY: io.isTTY,
2145
+ progress: io.stderr,
2146
+ ports: options.update
2147
+ });
2148
+ commandFor(program, "update").description("Update the package, service and skills, and roll back if the new version is unhealthy.").argument("[version]", "Version to install, such as 1.2.3; the latest when omitted.").action(async (...parts) => {
2149
+ const version = parts[0];
2150
+ if (version !== void 0 && typeof version !== "string") throw new CliError("usage");
2151
+ print(await runSetup(() => updatePackage(updateOptions(), version)));
2152
+ });
2153
+ const rollback = commandFor(program, "rollback");
2154
+ rollback.description("Return to the version before the last update.");
2155
+ rollback.option("--yes", "Roll back without asking; required when not at a terminal.");
2156
+ rollback.action(async () => {
2157
+ const yes = rollback.opts()["yes"] === true;
2158
+ print(await runSetup(() => rollbackPackage(updateOptions(), yes)));
2159
+ });
1236
2160
  commandFor(program, "mcp").summary("Start the MCP server for an agent on standard input and output.").description([
1237
2161
  "Start the MCP server for an agent on standard input and output. Stdout carries only JSON-RPC.",
1238
2162
  "",
1239
- "Each tool call finds the caller: `SPUR_SESSION` inside a Spur session, otherwise `BOARD_TOKEN`, otherwise the first `.spur-board/token` found walking upward from the directory the agent starts it in, stopping at home.",
2163
+ "Each tool call finds the caller: `SPUR_SESSION` inside a Spur session, otherwise `BOARD_TOKEN`, otherwise the first `.spur-board/token` found walking upward from the directory the agent starts it in, stopping at the root of its git worktree, or at home outside git; home itself is never searched.",
1240
2164
  "",
1241
- "It reaches the daemon at `BOARD_DAEMON_URL`, otherwise at `http.port` from `config.yaml`.",
2165
+ "It reaches the daemon at `BOARD_DAEMON_URL`, otherwise at `http.port` from `config.yaml`; with neither set nor a valid config, each call fails with `config` before any request.",
1242
2166
  "",
1243
2167
  "A `version_mismatch` answer means the server and the daemon have different catalogs: restart the agent session so `board mcp` loads the daemon's catalog; if it remains, run `board service restart`.",
1244
2168
  "",