benignswarm 0.12.133 → 0.12.135

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.
@@ -40,16 +40,21 @@ export async function install(p, out) {
40
40
  lines.push(`(was ${prev.bin}; run b9s doctor to find hooks and watchers still pointing there)`);
41
41
  const restarted = [];
42
42
  const elsewhere = [];
43
+ const failed = [];
43
44
  if (!bool(p.flags, "no-restart")) {
44
- const services = await restartInstallServices(rec.bin);
45
+ const services = await restartInstallServices(rec.bin, undefined, undefined, (message) => process.stderr.write(`b9s: ${message}\n`));
45
46
  restarted.push(...services.restarted);
46
47
  elsewhere.push(...services.not_restarted);
48
+ failed.push(...services.failed);
47
49
  }
48
50
  if (restarted.length)
49
51
  lines.push(`Restarted ${restarted.length} service${restarted.length === 1 ? "" : "s"} on it: ${restarted.map((l) => l.replace("org.benignswarm.watch.", "")).join(", ")}`);
50
52
  if (elsewhere.length)
51
53
  lines.push(`Not restarted:\n ${elsewhere.join("\n ")}`);
52
- out.print(lines.join("\n"), { install: rec, restarted, not_restarted: elsewhere });
54
+ if (failed.length)
55
+ lines.push(`Failed to restart:\n ${failed.join("\n ")}`);
56
+ out.print(lines.join("\n"), { install: rec, restarted, not_restarted: elsewhere, failed });
57
+ return failed.length ? 1 : 0;
53
58
  }
54
59
  export function embeddedHookCommands(value, marker) {
55
60
  const found = [];
@@ -19,6 +19,14 @@ export function commandLabel(command) {
19
19
  const line = command.join(" ").replace(/\s+/g, " ").trim();
20
20
  return line.length <= 200 ? line : `${line.slice(0, 197)}...`;
21
21
  }
22
+ function shellQuote(value) {
23
+ return `'${value.replace(/'/g, `'\\''`)}'`;
24
+ }
25
+ function unlockCommand(o) {
26
+ const project = o.projectSelection ? ` --project ${shellQuote(o.projectSelection)}` : "";
27
+ const scope = o.shared ? " --shared" : ` --machine ${shellQuote(o.machine)}`;
28
+ return `b9s --as ${shellQuote(o.identity)} unlock ${shellQuote(o.lock)} --job ${shellQuote(o.jobId)}${scope}${project}`;
29
+ }
22
30
  export async function runUnderLock(o, deps) {
23
31
  const now = deps.now ?? Date.now;
24
32
  const label = commandLabel(o.command);
@@ -26,12 +34,13 @@ export async function runUnderLock(o, deps) {
26
34
  const acquireBody = { unit: o.unit, note: o.note ?? label, shared: o.shared, machine: o.machine, job_token: o.token, lock_run: true };
27
35
  const release = async (completion) => {
28
36
  try {
29
- await deps.call("POST", `${base}/release`, { shared: o.shared, machine: o.shared ? undefined : o.machine, job_token: o.token, ...completion });
37
+ const result = await deps.call("POST", `${base}/release`, { shared: o.shared, machine: o.shared ? undefined : o.machine, job_token: o.token, ...completion });
38
+ forgetLockJob(o.jobsFile, o.jobsKey, o.token);
39
+ return result;
30
40
  }
31
41
  catch (error) {
32
- throw new CliError("lock_release_failed", `job ${o.jobId} could not release ${o.lock} (${error instanceof Error ? error.message : String(error)})`, `Release it: b9s unlock ${o.lock}${o.shared ? " --shared" : ""} --job ${o.jobId}`);
42
+ throw new CliError("lock_release_failed", `job ${o.jobId} could not release ${o.lock} (${error instanceof Error ? error.message : String(error)})`, `Release it: ${unlockCommand(o)}`);
33
43
  }
34
- forgetLockJob(o.jobsFile, o.jobsKey, o.token);
35
44
  };
36
45
  let r = await deps.call("POST", `${base}/acquire`, acquireBody);
37
46
  if (r.job_token !== o.token)
@@ -59,7 +68,11 @@ export async function runUnderLock(o, deps) {
59
68
  deps.log(`job ${o.jobId} holds ${o.lock}; running: ${label}`);
60
69
  const result = await deps.run(o.command);
61
70
  code = typeof result === "number" ? result : result.exit_code;
62
- await release(typeof result === "number" ? { exit_code: code } : { exit_code: code, ...(result.verified_baseline_sha ? { verified_baseline_sha: result.verified_baseline_sha } : {}), ...(result.tested_tree_sha ? { tested_tree_sha: result.tested_tree_sha } : {}) });
71
+ const released = await release(typeof result === "number" ? { exit_code: code } : { exit_code: code, ...(result.gate_output ? { gate_output: true } : {}), ...(result.verified_baseline_sha ? { verified_baseline_sha: result.verified_baseline_sha } : {}), ...(result.tested_tree_sha ? { tested_tree_sha: result.tested_tree_sha } : {}) });
72
+ if (released.gate_receipt?.recorded === false) {
73
+ const configured = released.gate_receipt.configured_command;
74
+ deps.log(`Gate receipt not recorded: ${released.gate_receipt.reason ?? "the reported gate result was refused"}.${configured ? ` Use the configured command: ${configured}` : " No complete gate command is configured."}`);
75
+ }
63
76
  }
64
77
  catch (error) {
65
78
  if (!error || !(error instanceof CliError) || error.code !== "lock_release_failed")
@@ -89,20 +102,47 @@ export function processDeps(call, log) {
89
102
  }),
90
103
  run: (command) => new Promise((resolve, reject) => {
91
104
  const child = spawn(command[0], command.slice(1), { stdio: ["inherit", "pipe", "inherit"] });
92
- let output = "";
105
+ let tail = "";
106
+ let gateOutput = false;
107
+ let baseline;
108
+ let testedTree;
109
+ const consumeLines = (text, final = false) => {
110
+ const lines = (tail + text).split(/\r?\n/);
111
+ const incomplete = lines.pop() ?? "";
112
+ if (final) {
113
+ tail = "";
114
+ if (incomplete)
115
+ lines.push(incomplete);
116
+ }
117
+ else {
118
+ tail = incomplete.slice(-2048);
119
+ }
120
+ for (const line of lines) {
121
+ if (/^gate:/i.test(line))
122
+ gateOutput = true;
123
+ const baselineMatch = line.match(/^gate: verified baseline ([0-9a-f]{40})\s*$/i);
124
+ // The gate's header is authoritative. Tests run later in the same process
125
+ // may print fixture marker lines; they must not replace the real SHAs.
126
+ if (baselineMatch && !baseline)
127
+ baseline = baselineMatch[1].toLowerCase();
128
+ const treeMatch = line.match(/^gate: tested tree ([0-9a-f]{40})\s*$/i);
129
+ if (treeMatch && !testedTree)
130
+ testedTree = treeMatch[1].toLowerCase();
131
+ }
132
+ };
93
133
  child.stdout?.on("data", (chunk) => {
94
134
  process.stdout.write(chunk);
95
- if (output.length < 8192)
96
- output += chunk.toString("utf8").slice(0, 8192 - output.length);
135
+ consumeLines(chunk.toString("utf8"));
97
136
  });
98
137
  forward = (signal) => { child.kill(signal); };
99
138
  child.once("error", (error) => { forward = undefined; reject(new CliError("command_not_started", `could not start ${command[0]}: ${error.message}`)); });
100
- child.once("exit", (code, signal) => {
139
+ // `close` follows stdout's `end`, so the final marker lines have been
140
+ // consumed before we construct the receipt sent with the lock release.
141
+ child.once("close", (code, signal) => {
101
142
  forward = undefined;
143
+ consumeLines("", true);
102
144
  const exit_code = code ?? 128 + (signal ? constants.signals[signal] ?? 0 : 0);
103
- const baseline = output.match(/^gate: verified baseline ([0-9a-f]{40})\s*$/im)?.[1]?.toLowerCase();
104
- const testedTree = output.match(/^gate: tested tree ([0-9a-f]{40})\s*$/im)?.[1]?.toLowerCase();
105
- resolve({ exit_code, ...(baseline ? { verified_baseline_sha: baseline } : {}), ...(testedTree ? { tested_tree_sha: testedTree } : {}) });
145
+ resolve({ exit_code, ...(gateOutput ? { gate_output: true } : {}), ...(baseline ? { verified_baseline_sha: baseline } : {}), ...(testedTree ? { tested_tree_sha: testedTree } : {}) });
106
146
  });
107
147
  }),
108
148
  dispose: () => { for (const signal of signals)
@@ -16,7 +16,7 @@ import { drainingUntil, writeMaintenance } from "../maintenance.js";
16
16
  import { TURN_HARNESSES, cachedClaudeLogin, claudeFacts, claudeHome, claudeSandbox, dshFacts, dshProcesses, probeFor, sessionProcesses } from "../harnesses.js";
17
17
  import { writeFileAtomic } from "../shared-file.js";
18
18
  import { readState, updateState } from "../state.js";
19
- import { installService, launchdFacts, launchdFactsLine, launchdGuidance, launchdSessionNow, lingerEnabled, MACHINE_LABEL, machineDaemonPath, readInstall, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
19
+ import { installService, launchdFacts, launchdFactsLine, launchdGuidance, launchdSessionNow, lingerEnabled, MACHINE_LABEL, machineDaemonPath, readInstall, removeService, requireInstall, restartServicesInBatches, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices, INSTALL_RESTART_BATCH_SIZE, INSTALL_RESTART_BATCH_PAUSE_MS } from "../install.js";
20
20
  import { CLI_VERSION } from "../version.js";
21
21
  import { probeCapabilities } from "../capabilities.js";
22
22
  import { diskSpaceNotice } from "../notices.js";
@@ -1135,7 +1135,62 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1135
1135
  ? (deps?.probeImdsContainer ? deps.probeImdsContainer({ runner }) : probeContainerImdsIsolation({ runner }))
1136
1136
  : null;
1137
1137
  const containerImdsOk = imdsContainerProbe ? imdsContainerProbe.ok : deps?.containerImdsBlocked;
1138
+ const recoveryFailures = new Map();
1139
+ const recoveryServices = [];
1140
+ const localWatcherServices = watcherServices();
1141
+ for (const session of desired) {
1142
+ if (session.desired !== "running")
1143
+ continue;
1144
+ const local = state.sessions[session.id];
1145
+ if (!local || local.container_name)
1146
+ continue;
1147
+ const project = projects.find((entry) => entry.id === session.project_id || entry.name === session.project);
1148
+ const poolImageOptIn = Boolean(session.pool) && !session.hardware_bound && Boolean(project?.image?.pool_sessions_enabled);
1149
+ const containerMode = isCloudHost || (poolImageOptIn && hostContainerProbe?.runtime !== null);
1150
+ if (containerMode)
1151
+ continue;
1152
+ const service = localWatcherServices.find((entry) => entry.label === watchLabelOf(session.agent));
1153
+ if (!service || serviceActive(service))
1154
+ continue;
1155
+ const sessionWritable = session.sandbox === "workspace-write"
1156
+ ? [...new Set([...defaultWorkspaceWritableRoots(), ...writable])]
1157
+ : writable;
1158
+ const fingerprint = sessionFingerprint({ ...session, thread: reconcileThread(session, local) }, session.sandbox === "workspace-write" ? sessionWritable : []);
1159
+ if (sessionConfigChanged(session, local, fingerprint))
1160
+ continue;
1161
+ recoveryServices.push(service);
1162
+ }
1163
+ if (recoveryServices.length) {
1164
+ const batchTotal = Math.ceil(recoveryServices.length / INSTALL_RESTART_BATCH_SIZE);
1165
+ const recovery = await restartServicesInBatches([], recoveryServices, {
1166
+ progress: (message) => log(`daemon watcher recovery: ${message}`),
1167
+ pause: deps?.wait,
1168
+ });
1169
+ for (const issue of recovery.not_started) {
1170
+ const entry = recoveryServices.find((service) => service.label === issue.label);
1171
+ if (entry)
1172
+ recoveryFailures.set(issue.label, issue.reason);
1173
+ }
1174
+ const count = recoveryServices.length;
1175
+ const returned = recovery.restarted.length;
1176
+ log(`daemon watcher recovery: attempted ${count} inactive session watcher${count === 1 ? "" : "s"} in ${batchTotal} batch${batchTotal === 1 ? "" : "es"}; ${returned} returned`);
1177
+ }
1138
1178
  const out = [];
1179
+ // Watcher recovery and session relaunch are one startup wave. Keep their counts together so
1180
+ // a short recovery tail cannot be followed immediately by a fresh full launch batch.
1181
+ let restartWorkScheduled = recoveryServices.length;
1182
+ const scheduleRestartWork = async (kind, agent) => {
1183
+ if (restartWorkScheduled > 0 && restartWorkScheduled % INSTALL_RESTART_BATCH_SIZE === 0) {
1184
+ log(`daemon restart wave: pausing ${INSTALL_RESTART_BATCH_PAUSE_MS / 1000}s after ${restartWorkScheduled} requests`);
1185
+ await (deps?.wait ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))))(INSTALL_RESTART_BATCH_PAUSE_MS);
1186
+ }
1187
+ const batch = Math.floor(restartWorkScheduled / INSTALL_RESTART_BATCH_SIZE) + 1;
1188
+ if (restartWorkScheduled % INSTALL_RESTART_BATCH_SIZE === 0) {
1189
+ log(`daemon restart wave batch ${batch}: starting up to ${INSTALL_RESTART_BATCH_SIZE} operations`);
1190
+ }
1191
+ restartWorkScheduled++;
1192
+ log(`daemon restart wave batch ${batch}: ${kind} for ${agent}`);
1193
+ };
1139
1194
  for (const s of desired) {
1140
1195
  const label = watchLabelOf(s.agent);
1141
1196
  const svc = () => watcherServices().find((w) => w.label === label);
@@ -1475,6 +1530,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1475
1530
  throw error;
1476
1531
  }
1477
1532
  try {
1533
+ await scheduleRestartWork("session start/relaunch", s.agent);
1478
1534
  pending.pid = (deps?.startTrackedSession ?? ((childBin, options, result) => startSessionChild(childBin, s.dir, options, result)))(bin, launchOptions, resultFile);
1479
1535
  }
1480
1536
  catch (error) {
@@ -1519,7 +1575,11 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
1519
1575
  };
1520
1576
  }
1521
1577
  else if (!containerMode && hostSvc) {
1578
+ const recoveryFailure = recoveryFailures.get(label);
1579
+ if (recoveryFailure)
1580
+ throw new Error(`its watcher ${label} could not be restarted during daemon recovery: ${recoveryFailure}`);
1522
1581
  if (!serviceActive(hostSvc)) {
1582
+ await scheduleRestartWork("watcher restart", s.agent);
1523
1583
  if (!restartWatcher(hostSvc))
1524
1584
  throw new Error(`its watcher ${label} is not loaded and could not be restarted`);
1525
1585
  log(`${s.agent}: watcher was not running; restarted`);
@@ -10,7 +10,7 @@ import { createHash } from "node:crypto";
10
10
  import { homedir, totalmem, userInfo } from "node:os";
11
11
  import { basename, dirname, join } from "node:path";
12
12
  import { bool, str } from "../args.js";
13
- import { configRoot, loadAgent, resolveAgentName } from "../config.js";
13
+ import { agentRef, configRoot, loadAgent, resolveAgentName } from "../config.js";
14
14
  import { Client } from "../client.js";
15
15
  import { heartbeatIfActive, reportWatcherHeartbeat, resolveActivitySource } from "../heartbeat.js";
16
16
  import { scanProject, unitWorktrees } from "./worktrees.js";
@@ -443,6 +443,27 @@ export async function resolveWatcherWorkUnitBinding(name) {
443
443
  return { binding: null, reason: "current work-unit assignment event is unavailable" };
444
444
  }
445
445
  }
446
+ /**
447
+ * Runs `work` with BSCHAT_AGENT naming this watcher's agent, then puts the environment back.
448
+ * The watcher is started with --as, so its own environment carries no identity; the git it runs
449
+ * to prepare a unit worktree calls the b9s credential helper as a child process, which can only
450
+ * learn who it is from the environment. Without this every fetch for a linked repository failed
451
+ * with no_identity and the watcher exited before any turn (0.12.133).
452
+ */
453
+ export function withAgentEnv(ref, work) {
454
+ const had = Object.prototype.hasOwnProperty.call(process.env, "BSCHAT_AGENT");
455
+ const before = process.env.BSCHAT_AGENT;
456
+ process.env.BSCHAT_AGENT = ref;
457
+ try {
458
+ return work();
459
+ }
460
+ finally {
461
+ if (had)
462
+ process.env.BSCHAT_AGENT = before;
463
+ else
464
+ delete process.env.BSCHAT_AGENT;
465
+ }
466
+ }
446
467
  /** Prepare an owned unit before launching its next turn, outside the harness sandbox. */
447
468
  async function prepareTurnWorktree(name, binding, allowSuperseded = false) {
448
469
  const creds = loadAgent(name);
@@ -473,7 +494,7 @@ async function prepareTurnWorktree(name, binding, allowSuperseded = false) {
473
494
  }
474
495
  const process = await client.call("GET", `/projects/${encodeURIComponent(project)}/process`);
475
496
  const { prepareWorktreeForWatcher } = await import("./wu.js");
476
- const prepared = prepareWorktreeForWatcher(binding.work_unit_number, unit, process.process?.definition, process.checkout?.exclude ?? []);
497
+ const prepared = withAgentEnv(agentRef(creds), () => prepareWorktreeForWatcher(binding.work_unit_number, unit, process.process?.definition, process.checkout?.exclude ?? []));
477
498
  return { number: binding.work_unit_number, path: prepared.path, status: unit.status };
478
499
  }
479
500
  catch (error) {
@@ -1702,7 +1702,8 @@ export async function lock(p, out) {
1702
1702
  const deps = processDeps((method, path, body) => client.call(method, path, body, { retries: lockRunRetries(path) }), (line) => process.stderr.write(`[b9s] ${line}\n`));
1703
1703
  try {
1704
1704
  process.exitCode = await runUnderLock({
1705
- project, lock: runName, shared, machine, unit: runUnit ? Number(runUnit) : null, note: str(p.flags, "note"), command: p.rest, token: runToken,
1705
+ project, identity: agentRef(creds), projectSelection: creds.project ? undefined : project,
1706
+ lock: runName, shared, machine, unit: runUnit ? Number(runUnit) : null, note: str(p.flags, "note"), command: p.rest, token: runToken,
1706
1707
  jobId: createHash("sha256").update(runToken).digest("hex").slice(0, 12),
1707
1708
  jobsFile: lockJobsFile(creds.project ? `${creds.project}.${creds.agent}` : `account.${creds.agent}`), jobsKey: lockJobKey(project, runName, shared ? null : machine),
1708
1709
  }, deps);
package/dist/help.js CHANGED
@@ -131,7 +131,7 @@ Agent commands
131
131
  acquisition queues through a machine maintenance drain/window and resumes after it
132
132
  machine identity is this host's hostname plus its registered label, shared by all agents here
133
133
  save the returned job token; reuse --token to check/retry the same job
134
- b9s lock run <name> [--unit n] [--note ..] [--shared] [--token <job-token>] -- <command> poll until granted, run the command, then release; exits with its code and records configured gate completion
134
+ b9s lock run <name> [--unit n] [--note ..] [--shared] [--token <job-token>] -- <command> poll until granted, run and release; gate receipt outcome is separate and does not change the command exit code
135
135
  polls every 15s; stale waiters are skipped after 60s with a process notice; later polls reap unreported holders idle 60s
136
136
  b9s locks shows waiter poll age; reported-command holders do not expire
137
137
  b9s unlock <name> [--job <id> | --token <job-token>] [--machine <label>|--shared] | b9s locks shows lock-run waiters' last-poll age; on this host the job token is kept for you
@@ -228,9 +228,9 @@ Machine placement enforces configured session slots and reports machine pressure
228
228
  fault with b9s-admin machine session resume.
229
229
  Codex: b9s watch --exec "codex queue --thread <id> --message {summary}" --service
230
230
  b9s update [--no-restart] the same as install --latest: upgrade this machine's b9s, repair PATH aliases,
231
- restart services on that install without waiting on one stop, and report failures
231
+ restart the machine daemon first, then watchers in batches of 5 with 5 s between batches
232
232
  b9s install [<version> | --latest] [--no-restart] make or upgrade this machine's one b9s (join does it once), repair PATH aliases,
233
- restart services resolving to it; other installs are left alone and named
233
+ restart its daemon first, then watchers in batches of 5 with 5 s between batches
234
234
  b9s sandbox probe [--checkout <dir>] [--api <host>] [--out <file>] [--nonce <id>]
235
235
  what the sandbox this runs in really allows: where commands run, which tools
236
236
  are there, what git can do, which hosts answer, what is writable; facts only
package/dist/install.js CHANGED
@@ -519,10 +519,11 @@ export function rewriteServiceInstall(s, installBin) {
519
519
  return original;
520
520
  }
521
521
  /** Rewrites matching service definitions, then restarts the services on the updated install. */
522
- export async function restartInstallServices(installBin, services = watcherServices(), driver) {
522
+ export async function restartInstallServices(installBin, services = watcherServices(), driver, progress = () => { }, pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms))) {
523
523
  const installReal = realpathSync(installBin);
524
524
  const restarted = [];
525
525
  const notRestarted = [];
526
+ const failed = [];
526
527
  const matching = [];
527
528
  for (const service of services) {
528
529
  const program = service.args?.[0];
@@ -548,8 +549,9 @@ export async function restartInstallServices(installBin, services = watcherServi
548
549
  ensureWatcherSliceMemoryLimits();
549
550
  }
550
551
  catch (error) {
551
- notRestarted.push(`Linux watcher memory limits were not applied; services were not restarted: ${error.message}`);
552
- return { restarted, not_restarted: notRestarted };
552
+ const reason = `Linux watcher memory limits were not applied; service was not restarted: ${error.message}`;
553
+ failed.push(...matching.map((service) => `${service.label}: ${reason}`));
554
+ return { restarted, not_restarted: notRestarted, failed };
553
555
  }
554
556
  }
555
557
  const rewritten = [];
@@ -558,7 +560,7 @@ export async function restartInstallServices(installBin, services = watcherServi
558
560
  rewritten.push({ service, original: rewriteServiceInstall(service, installBin) });
559
561
  }
560
562
  catch (error) {
561
- notRestarted.push(`${service.label} resolves to ${installReal}, but was not restarted: ${error.message}`);
563
+ failed.push(`${service.label} resolves to ${installReal}, but was not restarted: ${error.message}`);
562
564
  }
563
565
  }
564
566
  const systemd = rewritten.filter(({ service }) => service.kind === "systemd");
@@ -567,29 +569,23 @@ export async function restartInstallServices(installBin, services = watcherServi
567
569
  if (reload.status !== 0) {
568
570
  for (const { service, original } of systemd) {
569
571
  writeFileAtomic(service.path, original);
570
- notRestarted.push(`${service.label} resolves to ${installReal}, but its rewritten unit could not be loaded`);
572
+ failed.push(`${service.label} resolves to ${installReal}, but its rewritten unit could not be loaded`);
571
573
  }
572
574
  spawnSync("systemctl", ["--user", "daemon-reload"], { stdio: "ignore" });
573
575
  rewritten.splice(0, rewritten.length, ...rewritten.filter(({ service }) => service.kind !== "systemd"));
574
576
  }
575
577
  }
576
- const launchdServices = rewritten.filter(({ service }) => service.kind === "launchd");
577
- const systemdServices = rewritten.filter(({ service }) => service.kind === "systemd").map(({ service }) => service);
578
- for (const { service } of launchdServices) {
579
- try {
580
- reloadLaunchAgent(service.label, service.path);
581
- restarted.push(service.label);
582
- }
583
- catch (error) {
584
- notRestarted.push(`${service.label} resolves to ${installReal}, but could not be restarted: ${error.message}`);
585
- }
586
- }
587
- if (systemdServices.length) {
588
- const report = await restartWatcherServices(systemdServices, driver);
589
- restarted.push(...report.restarted);
590
- notRestarted.push(...report.not_started.map(({ label, reason }) => `${label} resolves to ${installReal}, but could not be restarted: ${reason}`));
591
- }
592
- return { restarted, not_restarted: notRestarted };
578
+ const restartable = rewritten.map(({ service }) => service);
579
+ const daemon = restartable.find((service) => service.label === MACHINE_LABEL);
580
+ const watchers = restartable.filter((service) => service.label.startsWith(WATCH_LABEL_PREFIX)).sort((a, b) => a.label.localeCompare(b.label));
581
+ const report = await restartServicesInBatches(daemon ? [daemon] : [], watchers, {
582
+ driver,
583
+ progress,
584
+ pause,
585
+ });
586
+ restarted.push(...report.restarted);
587
+ failed.push(...report.not_started.map(({ label, reason }) => `${label} resolves to ${installReal}, but could not be restarted: ${reason}`));
588
+ return { restarted, not_restarted: notRestarted, failed };
593
589
  }
594
590
  /**
595
591
  * A systemd user unit that keeps a watcher running. KillMode=process: a restart or upgrade stops the
@@ -722,6 +718,43 @@ export function requestWatcherRestart(s) {
722
718
  return restartLaunchAgent(s.label);
723
719
  return spawnSync("systemctl", ["--user", "--no-block", "restart", `${s.label}.service`], { stdio: "ignore" }).status === 0;
724
720
  }
721
+ export const INSTALL_RESTART_BATCH_SIZE = 5;
722
+ export const INSTALL_RESTART_BATCH_PAUSE_MS = 5_000;
723
+ /** Start the daemon first, then cap watcher startup bursts and let each wave settle before the next. */
724
+ export async function restartServicesInBatches(daemon, watchers, options = {}) {
725
+ const driver = options.driver ?? watcherRestartDriver;
726
+ const progress = options.progress ?? (() => { });
727
+ const pause = options.pause ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
728
+ const batchSize = options.batchSize ?? INSTALL_RESTART_BATCH_SIZE;
729
+ const pauseMs = options.pauseMs ?? INSTALL_RESTART_BATCH_PAUSE_MS;
730
+ if (!Number.isInteger(batchSize) || batchSize < 1)
731
+ throw new RangeError("restart batch size must be a positive integer");
732
+ if (!Number.isFinite(pauseMs) || pauseMs < 0)
733
+ throw new RangeError("restart batch pause must be non-negative");
734
+ const restarted = [];
735
+ const notStarted = [];
736
+ if (daemon.length) {
737
+ progress("Restarting machine daemon before watcher services");
738
+ const report = await restartWatcherServices(daemon, driver);
739
+ restarted.push(...report.restarted);
740
+ notStarted.push(...report.not_started);
741
+ }
742
+ const batchCount = Math.ceil(watchers.length / batchSize);
743
+ for (let offset = 0; offset < watchers.length; offset += batchSize) {
744
+ const batch = watchers.slice(offset, offset + batchSize);
745
+ const batchNumber = Math.floor(offset / batchSize) + 1;
746
+ progress(`Watcher batch ${batchNumber}/${batchCount}: restarting ${batch.length} services`);
747
+ const report = await restartWatcherServices(batch, driver);
748
+ restarted.push(...report.restarted);
749
+ notStarted.push(...report.not_started);
750
+ progress(`Watcher batch ${batchNumber}/${batchCount}: ${report.restarted.length}/${batch.length} services returned`);
751
+ if (batchNumber < batchCount) {
752
+ progress(`Pausing ${pauseMs / 1000}s before the next watcher batch`);
753
+ await pause(pauseMs);
754
+ }
755
+ }
756
+ return { restarted, not_started: notStarted };
757
+ }
725
758
  function watcherPid(service) {
726
759
  if (service.kind === "systemd") {
727
760
  const r = spawnSync("systemctl", ["--user", "show", "--property=MainPID", "--value", `${service.label}.service`], { encoding: "utf8" });
@@ -746,7 +779,14 @@ export async function restartWatcherServices(services, driver = watcherRestartDr
746
779
  const pending = new Map();
747
780
  const notStarted = [];
748
781
  for (const service of services) {
749
- const previousPid = driver.pid(service);
782
+ let previousPid;
783
+ try {
784
+ previousPid = driver.pid(service);
785
+ }
786
+ catch (error) {
787
+ notStarted.push({ label: service.label, reason: `could not read pre-restart process: ${error.message}` });
788
+ continue;
789
+ }
750
790
  let accepted = false;
751
791
  try {
752
792
  accepted = driver.request(service);
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.133";
1
+ export const CLI_VERSION = "0.12.135";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.133",
3
+ "version": "0.12.135",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {