@bakers-build/conductor 0.7.1-next.4 → 0.7.1-next.5

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.
@@ -1,5 +1,6 @@
1
1
  import { type BbCommandHost, type BbCommandPlugin, type ConductorLogger, type ProcProbe, type UpdateCheckOptions } from '@bakers-build/core';
2
2
  import { Command } from 'commander';
3
+ import { watchForRestart } from '../core/self-restart.js';
3
4
  import type { BbExecutor } from '../plugins/executor.js';
4
5
  import { type ResolvedAgent } from '../plugins/plugins.js';
5
6
  import type { BbRemote, ConductorStatus } from '../plugins/remote.js';
@@ -62,7 +63,14 @@ export interface BbCliDeps {
62
63
  askUpdate?: (question: string) => Promise<string>;
63
64
  /** Invoke `bakers` with an argv array (no binary name). */
64
65
  runBb?: (args: string[]) => Promise<void>;
66
+ /** The self-restart file watcher behind `start --foreground`. */
67
+ watchForRestart?: typeof watchForRestart;
68
+ /** Checks the changed config; resolves an error message, or undefined when it loads. */
69
+ checkConfig?: () => Promise<string | undefined>;
70
+ /** Replaces this process (`process.execve`). A test MUST inject a fake. */
71
+ execve?: Execve;
65
72
  }
73
+ type Execve = (file: string, args: string[], env: NodeJS.ProcessEnv) => void;
66
74
  /**
67
75
  * Start-time auth gate. Returns true if authenticated (session or session-less
68
76
  * provider); otherwise logs a single clear line and returns false.
@@ -1,16 +1,65 @@
1
- import { spawnSync } from 'node:child_process';
1
+ import { execFile, spawnSync } from 'node:child_process';
2
2
  import { basename, dirname, join, resolve } from 'node:path';
3
3
  import { createInterface } from 'node:readline';
4
+ import { promisify } from 'node:util';
4
5
  import { CommandRunner, checkForUpdate, configHomeOf, createBbConnectionClient, createLogger, declineUpdate, defaultProcProbe, deriveCheckoutRoot, deriveConductorLiveness, homeBbDir, loadReadyBbConnection, printVersionLine, readMachineContext, resolveConfigPath, setDefaultCommandRunner, signalVerifiedProcess, stemForConfigFile, updateNotice, verifyConductorProcess, } from '@bakers-build/core';
5
6
  import { Command } from 'commander';
6
7
  import { authStatus } from 'dropsh';
7
8
  import { resolveBbProjectContext } from '../bakers-project-context.js';
8
9
  import { composeConductorConfig, loadConductorConfig } from '../config.js';
9
10
  import { Conductor, registrationOf } from '../core/conductor.js';
11
+ import { watchForRestart } from '../core/self-restart.js';
10
12
  import { selectAgents, selectExecutor, selectRemote, selectWorkspace, } from '../plugins/plugins.js';
11
13
  import { sandboxFailures } from '../plugins/sandbox-preflight.js';
12
14
  import { spawnDetachedConductor, } from '../process/detached-spawn.js';
13
15
  import { ovenTools } from './oven-tools.js';
16
+ /**
17
+ * `oven start --dry-run` in a child with this process's own runtime and argv:
18
+ * the changed files are imported fresh there, never into this process.
19
+ */
20
+ async function defaultCheckConfig() {
21
+ const args = [
22
+ ...process.execArgv,
23
+ ...process.argv
24
+ .slice(1)
25
+ .map((a) => (a === '--foreground' ? '--dry-run' : a)),
26
+ ];
27
+ try {
28
+ await promisify(execFile)(process.execPath, args, {
29
+ cwd: process.cwd(),
30
+ env: process.env,
31
+ // A hung check would block every later restart; a timeout fails it.
32
+ timeout: 60_000,
33
+ });
34
+ return undefined;
35
+ }
36
+ catch (err) {
37
+ const { stderr, message } = err;
38
+ return stderr?.trim().split('\n').slice(-20).join('\n') || message;
39
+ }
40
+ }
41
+ /**
42
+ * `oven start --dry-run`: load what a start would load — config with project
43
+ * resolution, executor, workspace and agents — then stop before registering.
44
+ */
45
+ async function cmdDryRun(deps) {
46
+ try {
47
+ const config = await resolveConfig(deps, undefined, true);
48
+ const logger = loggerFor(await checkoutRootOf(config));
49
+ if (!deps.executor)
50
+ await selectExecutor(config, logger);
51
+ if (!deps.workspace)
52
+ await selectWorkspace(config, logger);
53
+ if (!deps.agents)
54
+ await selectAgents(config);
55
+ console.log(`config ok: ${config.config_path}`);
56
+ return 0;
57
+ }
58
+ catch (err) {
59
+ console.error(err instanceof Error ? err.message : String(err));
60
+ return 1;
61
+ }
62
+ }
14
63
  /** Default host bases for connection/plugin resolution when none is injected. */
15
64
  function defaultHost() {
16
65
  return { resolveBases: [import.meta.url, `${process.cwd()}/`] };
@@ -235,6 +284,9 @@ async function refuseIfAlreadyRunning(remote, id, thisHostKey, force, deps) {
235
284
  const existing = (await remote.listConductors('me')).find((c) => c.id === id);
236
285
  if (!existing)
237
286
  return false;
287
+ // A self-restart keeps the pid: the live record is this very process.
288
+ if (existing.lastPid === process.pid && existing.hostKey === thisHostKey)
289
+ return false;
238
290
  const probe = deps.procProbe ?? defaultProcProbe();
239
291
  const verified = verifyConductorProcess({
240
292
  pid: existing.lastPid,
@@ -314,29 +366,68 @@ async function cmdStartForeground(deps, log = {}, force = false, choice = {}) {
314
366
  // The endpoint file is how `bakers ports` and other CLI calls reach the tools.
315
367
  await conductor.startTools(join(homeBbDir(), 'conductors', `${conductor.id}.json`));
316
368
  const controller = new AbortController();
317
- const onSignal = () => controller.abort();
369
+ let restart = false;
370
+ // A stop wins over a restart already decided: `oven stop` must stay a stop.
371
+ const onSignal = () => {
372
+ restart = false;
373
+ controller.abort();
374
+ };
318
375
  process.once('SIGINT', onSignal);
319
376
  process.once('SIGTERM', onSignal);
377
+ const execve = deps.execve ?? process.execve?.bind(process);
378
+ let watcher;
379
+ if (config.restart_on_change !== false && config.watch_paths) {
380
+ if (!execve) {
381
+ logger.warn({ node: process.version }, 'restart_on_change needs process.execve (Node >= 22.15); the conductor does not restart itself on config changes');
382
+ }
383
+ else {
384
+ const check = deps.checkConfig ?? defaultCheckConfig;
385
+ watcher = (deps.watchForRestart ?? watchForRestart)(config.watch_paths, async (path) => {
386
+ if (controller.signal.aborted)
387
+ return;
388
+ logger.info({ path }, `restart_on_change: ${path} changed; checking config`);
389
+ const error = await check();
390
+ // A stop requested while the check ran stays a stop.
391
+ if (controller.signal.aborted)
392
+ return;
393
+ if (error !== undefined) {
394
+ logger.error({ path, err: error }, `config check failed; keeping the running conductor: ${error}`);
395
+ return;
396
+ }
397
+ logger.info({ path }, 'config check passed; restarting conductor');
398
+ restart = true;
399
+ watcher?.close();
400
+ controller.abort();
401
+ });
402
+ }
403
+ }
320
404
  try {
321
405
  await conductor.serve(controller.signal);
322
406
  }
323
407
  finally {
408
+ watcher?.close();
409
+ await conductor.stopTools();
324
410
  process.removeListener('SIGINT', onSignal);
325
411
  process.removeListener('SIGTERM', onSignal);
326
- await conductor.stopTools();
327
412
  // The exiting process writes its own `offline`. It has to be this process:
328
413
  // a heartbeat sets `online` unconditionally (ConductorRegistrar), so an
329
414
  // offline written by anyone else is erased by the next tick — the status
330
415
  // is only trustworthy when written after the heartbeats have stopped.
331
416
  // Best-effort: a conductor that cannot reach the control plane on the way
332
417
  // out must still exit, and the reaper flips it on lease expiry anyway.
333
- try {
334
- await remote.setConductorStatus(conductor.id, 'offline');
335
- }
336
- catch (err) {
337
- logger.warn({ conductorId: conductor.id, err: String(err) }, 'could not write offline status on shutdown; the lease reaper will');
418
+ // A self-restart skips it: the same conductor id comes straight back.
419
+ if (!restart) {
420
+ try {
421
+ await remote.setConductorStatus(conductor.id, 'offline');
422
+ }
423
+ catch (err) {
424
+ logger.warn({ conductorId: conductor.id, err: String(err) }, 'could not write offline status on shutdown; the lease reaper will');
425
+ }
338
426
  }
339
427
  }
428
+ // Same pid and log.
429
+ if (restart && execve)
430
+ execve(process.execPath, [process.execPath, ...process.execArgv, ...process.argv.slice(1)], process.env);
340
431
  }
341
432
  async function defaultAskUpdate(question) {
342
433
  const rl = createInterface({
@@ -881,7 +972,12 @@ Examples:
881
972
  'a second conductor if the running one cannot be verified or stopped.', false)
882
973
  .option('--adopt <uuid>', 'take over the conductor this machine, project and variant already have')
883
974
  .option('--new', 'register a new conductor instead of taking one over')
975
+ .option('--dry-run', 'load the config, executor, workspace and agents, then exit (0 when they load, 1 with the error)', false)
884
976
  .action(async function (opts) {
977
+ if (opts.dryRun) {
978
+ process.exitCode = await cmdDryRun(deps);
979
+ return;
980
+ }
885
981
  if (opts.adopt && opts.new) {
886
982
  console.error('Choose either --adopt <uuid> or --new, not both.');
887
983
  process.exitCode = 1;
@@ -1,5 +1,5 @@
1
1
  import { readdirSync } from 'node:fs';
2
- import { basename, resolve } from 'node:path';
2
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
3
3
  import { pathToFileURL } from 'node:url';
4
4
  import { assertSchemaVersion1, discoverAddons, discoverScoped, findDefaultExportObject, machineContextPath, matchDelimiter, readMachineContext, resolveConductorSlots, resolveModuleEslintStyle, scanTopLevelProperties, scopeAddons, stemForConfigFile, warnIgnoredMaxParallel, } from '@bakers-build/core';
5
5
  import { readBbProjectSelection } from './cli/project-context.js';
@@ -343,6 +343,9 @@ export async function loadConductorConfig(configFile) {
343
343
  ? config.states.map((state) => requireNonEmptyString(state, 'states'))
344
344
  : [];
345
345
  warnIgnoredMaxParallel(configPath, config);
346
+ const restartOnChange = config.restart_on_change ?? true;
347
+ if (typeof restartOnChange !== 'boolean')
348
+ throw new Error(`${configPath}: restart_on_change must be a boolean`);
346
349
  const machineCtx = await readMachineContext();
347
350
  warnIgnoredMaxParallel(machineContextPath(), machineCtx);
348
351
  const tunnel = machineCtx.tunnel === true;
@@ -575,6 +578,21 @@ export async function loadConductorConfig(configFile) {
575
578
  lease_seconds: optionalPositiveInteger(config.lease_seconds, 300, 'lease_seconds'),
576
579
  ...(config.hooks !== undefined ? { hooks: config.hooks } : {}),
577
580
  config_path: configPath,
581
+ restart_on_change: restartOnChange,
582
+ watch_paths: {
583
+ files: [
584
+ configPath,
585
+ configPath.replace(/\.js$/, '.local.js'),
586
+ join(dirname(configPath), 'connection.config.local.js'),
587
+ machineContextPath(),
588
+ ],
589
+ // A retired entry keeps its spec as key; only resolved modules have a dir.
590
+ dirs: [
591
+ ...new Set(effectiveAddons
592
+ .filter((a) => isAbsolute(a.key))
593
+ .map((a) => dirname(a.key))),
594
+ ],
595
+ },
578
596
  };
579
597
  }
580
598
  /**
@@ -0,0 +1,15 @@
1
+ /** What the running conductor loaded: single files and addon build dirs. */
2
+ export interface WatchPaths {
3
+ files: string[];
4
+ dirs: string[];
5
+ }
6
+ /**
7
+ * Call `trigger` with the last changed path after `debounceMs` without a
8
+ * further change. Files are watched through their parent directory, so an
9
+ * editor's rename-replace save and a newly created file both count; dirs are
10
+ * watched recursively. At most one trigger runs at a time; changes during one
11
+ * re-arm the debounce once it returns.
12
+ */
13
+ export declare function watchForRestart(paths: WatchPaths, trigger: (path: string) => Promise<void>, debounceMs?: number): {
14
+ close(): void;
15
+ };
@@ -0,0 +1,80 @@
1
+ // The foreground conductor restarts itself when a file it loaded changes:
2
+ // its config files, the machine config, or a configured addon's build. This
3
+ // module only watches, debounces and serializes; the caller decides whether a
4
+ // change becomes a restart (config check, drain, execve).
5
+ import { watch } from 'node:fs';
6
+ import { basename, dirname, join } from 'node:path';
7
+ /**
8
+ * Call `trigger` with the last changed path after `debounceMs` without a
9
+ * further change. Files are watched through their parent directory, so an
10
+ * editor's rename-replace save and a newly created file both count; dirs are
11
+ * watched recursively. At most one trigger runs at a time; changes during one
12
+ * re-arm the debounce once it returns.
13
+ */
14
+ export function watchForRestart(paths, trigger, debounceMs = 2000) {
15
+ const watchers = [];
16
+ let timer;
17
+ let last;
18
+ let running = false;
19
+ let pending = false;
20
+ let closed = false;
21
+ const fire = async () => {
22
+ timer = undefined;
23
+ running = true;
24
+ try {
25
+ await trigger(last);
26
+ }
27
+ finally {
28
+ running = false;
29
+ if (pending && !closed) {
30
+ pending = false;
31
+ arm();
32
+ }
33
+ }
34
+ };
35
+ const arm = () => {
36
+ clearTimeout(timer);
37
+ timer = setTimeout(() => void fire(), debounceMs);
38
+ };
39
+ const changed = (path) => {
40
+ if (closed)
41
+ return;
42
+ last = path;
43
+ if (running)
44
+ pending = true;
45
+ else
46
+ arm();
47
+ };
48
+ const tryWatch = (dir, recursive, on) => {
49
+ try {
50
+ watchers.push(watch(dir, { recursive, persistent: false }, (_e, f) => {
51
+ if (f)
52
+ on(f.toString());
53
+ }));
54
+ }
55
+ catch {
56
+ // A missing directory (no machine config yet, unbuilt addon) is not watched.
57
+ }
58
+ };
59
+ const byDir = new Map();
60
+ for (const file of paths.files) {
61
+ const names = byDir.get(dirname(file)) ?? new Set();
62
+ names.add(basename(file));
63
+ byDir.set(dirname(file), names);
64
+ }
65
+ for (const [dir, names] of byDir)
66
+ tryWatch(dir, false, (f) => {
67
+ if (names.has(f))
68
+ changed(join(dir, f));
69
+ });
70
+ for (const dir of new Set(paths.dirs))
71
+ tryWatch(dir, true, (f) => changed(join(dir, f)));
72
+ return {
73
+ close() {
74
+ closed = true;
75
+ clearTimeout(timer);
76
+ for (const w of watchers)
77
+ w.close();
78
+ },
79
+ };
80
+ }
@@ -75,6 +75,16 @@ export interface ConductorSettings {
75
75
  };
76
76
  /** Absolute path of the loaded config. */
77
77
  config_path: string;
78
+ /**
79
+ * `oven start --foreground` restarts itself when a file in `watch_paths`
80
+ * changes. Default true.
81
+ */
82
+ restart_on_change?: boolean;
83
+ /** The files and addon build dirs this config was loaded from. */
84
+ watch_paths?: {
85
+ files: string[];
86
+ dirs: string[];
87
+ };
78
88
  }
79
89
  /** Whole conductor.config.js (dropsh-superset): site + named plugin slots. */
80
90
  export interface ConductorFileConfig extends ConductorSettings {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bakers-build/conductor",
3
- "version": "0.7.1-next.4",
3
+ "version": "0.7.1-next.5",
4
4
  "description": "bakers.build conductor engine + CLI: registers, claims tickets via JSON:API, dispatches agents.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -32,14 +32,14 @@
32
32
  "dependencies": {
33
33
  "@dropsh/plugin-jsonapi-schema": "^0.8.2",
34
34
  "@dropsh/plugin-oauth2": "^0.8.2",
35
- "@bakers-build/core": "^0.7.1-next.4",
36
- "@bakers-build/message": "^0.7.1-next.4",
35
+ "@bakers-build/core": "^0.7.1-next.5",
36
+ "@bakers-build/message": "^0.7.1-next.5",
37
37
  "@modelcontextprotocol/sdk": "1.32.1",
38
38
  "commander": "^12.1.0",
39
39
  "dropsh": "^0.8.2"
40
40
  },
41
41
  "bakersBuild": {
42
- "commit": "0633e1e4d21ee420a1d0fc3eae2114750eb103bd",
42
+ "commit": "b34bd900ef0293024de7b5a956af08e67d407e29",
43
43
  "channel": "next"
44
44
  }
45
45
  }