@bakers-build/conductor 0.6.1-next.6 → 0.6.1-next.7

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.
@@ -34,7 +34,9 @@ ${inputs.workspaceId ? ` workspace_id: ${JSON.stringify(inputs.workspaceId)},\n
34
34
  export function renderHostMachine(inputs) {
35
35
  return `// @bakers-schema-version 1
36
36
  // Local host identity. The run budget is set on the machine in the backend;
37
- // server credentials belong to bakers.config.js.
37
+ // server credentials belong to bakers.config.js. An \`executor\` slot here
38
+ // (e.g. \`{ plugin: '@bakers-build/addon-herdr-core' }\`) overrides every
39
+ // project's executor on this machine.
38
40
  export default {
39
41
  schema_version: 1,
40
42
  machine_id: ${JSON.stringify(inputs.machineId)},
@@ -58,12 +60,12 @@ export function renderCommittedConfig(inputs) {
58
60
  export default {
59
61
  bakers: { project: ${JSON.stringify(inputs.project)}${inputs.bakersWorkspace ? `, workspace: ${JSON.stringify(inputs.bakersWorkspace)}` : ''} },
60
62
  // The run budget (max_parallel) is set on the machine in the backend.
61
- // Set to false to keep this conductor's transcripts out of the log store
62
- // (e.g. large, uninteresting, or subject to a local policy). Default true;
63
- // metrics are unaffected either way.
63
+ // Transcripts upload only where the server's run-log storage allows it.
64
+ // Set to false to keep this conductor's transcripts local even then.
65
+ // Metrics are unaffected either way.
64
66
  capture_logs: true,
65
67
  ${inputs.hooks?.after_create || inputs.hooks?.after_done
66
- ? ` // Lifecycle hooks are executor-owned (BB-84): they live at the config top
68
+ ? ` // Lifecycle hooks are conductor-owned: they live at the config top
67
69
  // level — NOT on a plugin descriptor's \`with.hooks\`.
68
70
  hooks: { ${[
69
71
  inputs.hooks.after_create
@@ -12,6 +12,7 @@ export const CONDUCTOR_ADDON_SLOTS = {
12
12
  '@bakers-build/addon-remote-drupal': ['remote'],
13
13
  '@bakers-build/addon-herdr': ['executor', 'workspace'],
14
14
  '@bakers-build/addon-orca': ['executor', 'workspace'],
15
+ '@bakers-build/addon-herdr-core': ['executor'],
15
16
  '@bakers-build/addon-fake': ['remote', 'executor', 'workspace'],
16
17
  '@bakers-build/addon-workspace-git': ['workspace'],
17
18
  '@bakers-build/addon-claude': ['agent'],
@@ -2,11 +2,10 @@ import { type BbCommandHost, type BbCommandPlugin, type ConductorLogger, type Pr
2
2
  import { Command } from 'commander';
3
3
  import type { BbExecutor } from '../plugins/executor.js';
4
4
  import { type ResolvedAgent } from '../plugins/plugins.js';
5
- import type { HerdrHost } from '../plugins/process-host.js';
6
5
  import type { BbRemote, ConductorStatus } from '../plugins/remote.js';
7
6
  import type { BbWorkspace } from '../plugins/workspace.js';
7
+ import { type DetachedChild, type DetachedSpawnRequest } from '../process/detached-spawn.js';
8
8
  import type { ConductorFileConfig } from '../types.js';
9
- export type { HerdrHost };
10
9
  /** Test seam: inject any subset of dependencies. */
11
10
  export interface BbCliDeps {
12
11
  remote?: BbRemote;
@@ -21,11 +20,10 @@ export interface BbCliDeps {
21
20
  /** Host contract (resolveBases); default: this install + cwd. */
22
21
  host?: BbCommandHost;
23
22
  /**
24
- * The process host behind `start`. Defaults to the host contributed by a
25
- * conductor addon (`processHosts`, last wins). A test MUST inject a fake,
26
- * or the suite creates real workspaces + real conductor processes.
23
+ * The detached spawn behind `start`. Defaults to `spawnDetachedConductor`;
24
+ * a test MUST inject a fake, or the suite starts real conductor processes.
27
25
  */
28
- herdr?: HerdrHost;
26
+ spawnConductor?: (req: DetachedSpawnRequest) => Promise<DetachedChild>;
29
27
  /**
30
28
  * BB-232: the pid probe behind `stop`. Defaults to the real /proc reader —
31
29
  * a test MUST inject a fake, or the suite signals real processes.
@@ -1,7 +1,7 @@
1
1
  import { spawnSync } from 'node:child_process';
2
2
  import { basename, dirname, join, resolve } from 'node:path';
3
3
  import { createInterface } from 'node:readline';
4
- import { CommandRunner, checkForUpdate, createBbConnectionClient, createLogger, declineUpdate, defaultProcProbe, deriveCheckoutRoot, deriveConductorLiveness, homeBbDir, loadReadyBbConnection, printVersionLine, resolveConfigPath, setDefaultCommandRunner, signalVerifiedProcess, stemForConfigFile, updateNotice, verifyConductorProcess, } from '@bakers-build/core';
4
+ import { CommandRunner, checkForUpdate, configHomeOf, createBbConnectionClient, createLogger, declineUpdate, defaultProcProbe, deriveCheckoutRoot, deriveConductorLiveness, homeBbDir, loadReadyBbConnection, printVersionLine, resolveConfigPath, setDefaultCommandRunner, signalVerifiedProcess, stemForConfigFile, updateNotice, verifyConductorProcess, } from '@bakers-build/core';
5
5
  import { Command } from 'commander';
6
6
  import { authStatus } from 'dropsh';
7
7
  import { resolveBbProjectContext } from '../bakers-project-context.js';
@@ -9,6 +9,7 @@ import { composeConductorConfig, loadConductorConfig } from '../config.js';
9
9
  import { Conductor, registrationOf } from '../core/conductor.js';
10
10
  import { selectAgents, selectExecutor, selectRemote, selectWorkspace, } from '../plugins/plugins.js';
11
11
  import { sandboxFailures } from '../plugins/sandbox-preflight.js';
12
+ import { spawnDetachedConductor, } from '../process/detached-spawn.js';
12
13
  import { ovenTools } from './oven-tools.js';
13
14
  /** Default host bases for connection/plugin resolution when none is injected. */
14
15
  function defaultHost() {
@@ -96,13 +97,6 @@ function loggerFor(checkoutRoot, log = {}) {
96
97
  setDefaultCommandRunner(new CommandRunner(logger));
97
98
  return logger;
98
99
  }
99
- function herdrHostOf(deps, config) {
100
- const host = deps.herdr ?? config.processHost;
101
- if (!host) {
102
- throw new Error('no herdr process host — add @bakers-build/addon-herdr to conductor addons');
103
- }
104
- return host;
105
- }
106
100
  /**
107
101
  * The liveness words this CLI prints.
108
102
  *
@@ -386,7 +380,7 @@ function isInteractive(deps) {
386
380
  * A terminal asks whether to take it over (or which, when there are several);
387
381
  * any other answer than a choice or no cancels. Without one the start stops with
388
382
  * the control plane's own `--adopt`/`--new` hint. After this the id is known,
389
- * so no later start (nor the herdr child, which has no terminal) asks again.
383
+ * so no later start (nor the detached child, which has no terminal) asks again.
390
384
  * Returns false when the start must stop.
391
385
  */
392
386
  async function settleTakeover(deps, remote, registration, choice) {
@@ -579,11 +573,13 @@ function heartbeatAgeSeconds(row) {
579
573
  * heartbeat happened at some point before it, possibly by the process this
580
574
  * call just killed".
581
575
  */
582
- async function waitForFreshHeartbeat(remote, id, priorPid, priorLastSeen, deps) {
576
+ async function waitForFreshHeartbeat(remote, id, priorPid, priorLastSeen, deps, stopped = () => false) {
583
577
  const intervalMs = deps.startPollIntervalMs ?? START_POLL_INTERVAL_MS;
584
578
  const attempts = deps.startPollAttempts ?? START_POLL_MAX_ATTEMPTS;
585
579
  const sleep = deps.sleep ?? realSleep;
586
580
  for (let attempt = 0; attempt < attempts; attempt++) {
581
+ if (stopped())
582
+ return undefined;
587
583
  const row = (await remote.listConductors('me')).find((c) => c.id === id);
588
584
  if (row &&
589
585
  classify(row) === 'online' &&
@@ -711,41 +707,57 @@ async function cmdStartBody(deps, log, force = false, choice = {}) {
711
707
  }
712
708
  console.log(`stopped conductor ${id} for restart (--force)`);
713
709
  }
714
- // The herdr child has no terminal, so a takeover is settled here first.
710
+ // The detached child has no terminal, so a takeover is settled here first.
715
711
  if (!existing &&
716
712
  !(await settleTakeover(deps, remote, registrationOf(config, checkoutRoot), choice)))
717
713
  return;
718
- const handle = `bakers-conductor:${id}`;
719
- const fgFlags = [
720
- log.level ? `--log-level ${log.level}` : '',
721
- log.sink ? `--log-sink ${log.sink}` : '',
722
- ]
723
- .filter(Boolean)
724
- .join(' ');
725
- // BB-477: a herdr pane is a child of the herdr server, not of this
726
- // process, so it inherits the server's environment rather than the
727
- // BB_CONDUCTOR this process resolved. Carry the selector on the command
728
- // string itself, derived the same way the conductor reports its own
729
- // `conductor_name`, so the pane cannot re-resolve to a different config.
714
+ // BB-477: carry the selector on the child's own argv, derived the same way
715
+ // the conductor reports its `conductor_name`, so it cannot re-resolve to a
716
+ // different config.
730
717
  const stem = stemForConfigFile(basename(config.config_path));
731
- const selectorFlag = stem && stem !== 'conductor' ? `--conductor ${stem} ` : '';
732
- const fgCmd = `BB_CONDUCTOR_LOG=file bakers ${selectorFlag}oven ${fgFlags} start --foreground --no-update-check`.replace(/\s+/g, ' ');
718
+ const argv = [
719
+ process.execPath,
720
+ process.argv[1], // the running bakers entry script
721
+ ...(stem && stem !== 'conductor' ? ['--conductor', stem] : []),
722
+ 'oven',
723
+ ...(log.level ? ['--log-level', log.level] : []),
724
+ // No --log-sink: the child's stdout is the log file, pinned by BB_CONDUCTOR_LOG=file.
725
+ 'start',
726
+ '--foreground',
727
+ '--no-update-check',
728
+ ];
729
+ const logPath = join(configHomeOf(checkoutRoot), 'log.txt');
730
+ let child;
733
731
  try {
734
- await herdrHostOf(deps, config).spawn(handle, checkoutRoot, fgCmd);
735
- logger.info({ id, handle }, 'started conductor via herdr');
732
+ child = await (deps.spawnConductor ?? spawnDetachedConductor)({
733
+ argv,
734
+ cwd: checkoutRoot,
735
+ env: { ...process.env, BB_CONDUCTOR_LOG: 'file' },
736
+ logPath,
737
+ });
738
+ logger.info({ id, pid: child.pid }, 'started conductor detached');
736
739
  }
737
740
  catch (err) {
738
- logger.error({ id, err: err.message }, 'could not start via herdr');
739
- logger.warn({}, 'Hint: run `bakers oven start --foreground` under a service manager (systemd-user / docker) on hosts without herdr.');
740
- console.log(`failed to start conductor ${id}: could not launch via herdr — ${err.message}`);
741
+ console.log(`failed to start conductor ${id}: could not spawn — ${err.message} — see ${logPath}`);
742
+ process.exitCode = 1;
743
+ return;
744
+ }
745
+ let exited = false;
746
+ const outcome = await Promise.race([
747
+ child.exited.then((code) => {
748
+ exited = true; // ends the losing heartbeat poll, so the CLI exits now
749
+ return { code };
750
+ }),
751
+ waitForFreshHeartbeat(remote, id, priorPid, priorLastSeen, deps, () => exited).then((row) => ({ row })),
752
+ ]);
753
+ if ('code' in outcome) {
754
+ console.log(`failed to start conductor ${id}: exited with code ${outcome.code} before its first heartbeat — see ${logPath}`);
741
755
  process.exitCode = 1;
742
756
  return;
743
757
  }
744
- const started = await waitForFreshHeartbeat(remote, id, priorPid, priorLastSeen, deps);
758
+ const started = outcome.row;
745
759
  if (!started) {
746
- console.log(`failed to start conductor ${id}: spawned, but no fresh heartbeat arrived — ` +
747
- 'the herdr pane closes when the conductor exits, so a missing bakers on PATH or a crash before logging leaves no file; ' +
748
- 'check the conductor registered (a refused registration never heartbeats) and its own log');
760
+ console.log(`failed to start conductor ${id}: spawned, but no fresh heartbeat arrived — see ${logPath}`);
749
761
  process.exitCode = 1;
750
762
  return;
751
763
  }
@@ -861,7 +873,7 @@ Examples:
861
873
  BB_LOG_LEVEL=debug bakers oven once`);
862
874
  conductor
863
875
  .command('start')
864
- .description('start the conductor loop (herdr-hosted by default)')
876
+ .description('start the conductor loop (a detached background process by default)')
865
877
  .option('--foreground', 'run the loop in this process', false)
866
878
  .option('--no-update-check', 'skip the daily CLI update check')
867
879
  .option('--force', 'restart: verify-stop the already-running conductor (SIGTERM, a grace ' +
@@ -151,15 +151,6 @@ function validateHookListeners(value) {
151
151
  }
152
152
  return value;
153
153
  }
154
- function validateProcessHost(value) {
155
- if (!Array.isArray(value) || value.length === 0)
156
- return undefined;
157
- const host = value[value.length - 1];
158
- if (!isRecord(host) || typeof host.spawn !== 'function') {
159
- throw new Error('conductor addons[] processHosts must accumulate a host with spawn()');
160
- }
161
- return host;
162
- }
163
154
  function requirePlugin(value, kind) {
164
155
  if (!isRecord(value) || value.kind !== kind) {
165
156
  throw new Error(`conductor config requires a ${kind} plugin in the "${kind}" slot`);
@@ -420,41 +411,19 @@ export async function loadConductorConfig(configFile) {
420
411
  ];
421
412
  const tools = toolSets.length > 0 ? await loadTools(toolSets) : undefined;
422
413
  const inboxAddons = await loadInboxAddons(discovered.addonInbox, new Set(tools?.list().map((t) => t.name)));
423
- // Explicit executor/workspace descriptors still load those slots, but they
424
- // skip addons[] discovery — so a pre-BB-215 config never contributes a
425
- // process host unless we load that package's processHosts accumulator too.
426
- let processHost = validateProcessHost(discovered.processHosts);
427
- if (processHost === undefined) {
428
- const slotPlugins = [
429
- ...new Set([config.executor, config.workspace]
430
- .filter(isPluginDescriptor)
431
- .map((entry) => entry.plugin)),
432
- ];
433
- for (const spec of slotPlugins) {
434
- // A descriptor may be a plain factory file (`./fixture.js`), not an
435
- // addon preset. Slot resolution owns that error; skip a host we cannot
436
- // discover and keep looking at the other slot.
437
- try {
438
- const found = validateProcessHost(narrowConductorContributions(await discoverAddons([spec], 'conductor', addonBases, {
439
- only: ['processHosts'],
440
- })).processHosts);
441
- if (found !== undefined)
442
- processHost = found;
443
- }
444
- catch {
445
- // no process host from this descriptor
446
- }
447
- }
448
- }
449
414
  const remote = config.remote !== undefined
450
415
  ? await resolveSlot(config.remote, 'remote', configPath)
451
416
  : wired.remote;
452
417
  if (!remote) {
453
418
  throw new Error('conductor config resolves no remote — name a remote addon in addons[] or set the remote slot');
454
419
  }
455
- const executor = config.executor !== undefined
456
- ? await resolveSlot(config.executor, 'executor', configPath)
457
- : wired.executor;
420
+ // The machine may run its own installed tool: its explicit executor wins
421
+ // over the project's, which wins over the one discovered from addons[].
422
+ const executor = machineCtx.executor !== undefined
423
+ ? await resolveSlot(machineCtx.executor, 'executor', machineContextPath())
424
+ : config.executor !== undefined
425
+ ? await resolveSlot(config.executor, 'executor', configPath)
426
+ : wired.executor;
458
427
  if (!executor) {
459
428
  throw new Error('conductor config resolves no executor — name an executor addon in addons[] or set the executor slot');
460
429
  }
@@ -593,7 +562,6 @@ export async function loadConductorConfig(configFile) {
593
562
  ...(inboxAddons.length > 0 ? { inboxAddons } : {}),
594
563
  ...(tools !== undefined ? { tools } : {}),
595
564
  ...(config.hooks?.provision_up !== undefined ? { provisioning } : {}),
596
- ...(processHost !== undefined ? { processHost } : {}),
597
565
  bakers,
598
566
  ...identityOf(machineCtx, project, variant),
599
567
  variant,
@@ -1,13 +1,12 @@
1
1
  export { AmbiguousProjectNameError, type ResolvedBbProjectContext, resolveBbProjectContext, } from './bakers-project-context.js';
2
2
  export { type AgentFootprint, type AgentRunIdentity, type BbAgent, CONDUCTOR_TOKEN_ENV, CONDUCTOR_TOOLS_SERVER, CONDUCTOR_URL_ENV, DEFAULT_ENV_DENY, emptyAgentFootprint, matchesEnvDeny, type RunEnvPolicy, } from './plugins/agent.js';
3
3
  export { detectKnownOverrides, type KnownOptionSpec, type KnownOverrides, type KnownScalarKind, type ResolvedSecurity, resolveAgentCliOptions, resolveSecurityOptions, type SandboxOptions, SECURITY_MODES, type SecurityMode, type SecurityOptions, type SecurityReport, SHARED_SECURITY_KEY, type SharedListKey, type SharedSecurity, validateAgentArgs, validateOptionalBoolean, validateOptionalString, validateSharedSecurity, } from './plugins/agent-args.js';
4
- export type { BbExecutor, ExecutorCapabilities, HookContext, HookListener, HookListenerContext, HookListenerFn, HookName, HookResult, SpawnedSession, SpawnRunInput, WorktreeTeardown, } from './plugins/executor.js';
4
+ export type { BbExecutor, ExecutorCapabilities, HookContext, HookListener, HookListenerContext, HookListenerFn, HookName, HookResult, OpenWorkspaceContext, SpawnedSession, SpawnRunInput, WorktreeTeardown, } from './plugins/executor.js';
5
5
  export type { DiscoveredInbox, InboxBinding, InboxMessageHandler, InboxMessageRequest, InboxMessages, LoadedInbox, } from './plugins/message.js';
6
6
  export { loadInbox, validateRequestPayload, } from './plugins/message.js';
7
7
  export type { AgentCandidate, AgentPlugin, ExecutorDeps, ExecutorPlugin, RemotePlugin, ResolvedAgent, WorkspacePlugin, } from './plugins/plugins.js';
8
8
  export { resolveAgent, selectAgent, selectAgents, selectExecutor, selectRemote, selectWorkspace, } from './plugins/plugins.js';
9
9
  export { type ConductorAddonEntry, type ConductorContributions, narrowConductorContributions, type Preset, } from './plugins/preset.js';
10
- export type { HerdrHost } from './plugins/process-host.js';
11
10
  export type { ActiveRun, AddonDefinitionV2, AddonRegistration, BbRemote, ClaimedRun, ClaimOptions, ClaimWithheld, ConductorRegistration, ConductorStatus, FinalizableRun, FrozenTicket, InboxMessage, InboxSnapshot, RunMetrics, RunWriteAttributes, SiteToolClient, Ticket, TicketMetric, UncleanTicket, } from './plugins/remote.js';
12
11
  export { ConductorTakeoverRequired } from './plugins/remote.js';
13
12
  export { installCommand, lastLine, type SandboxHost, type SandboxPreflight, sandboxFailures, systemSandboxHost, } from './plugins/sandbox-preflight.js';
@@ -5,6 +5,7 @@ import { type ResolvedAgent } from '../plugins/plugins.js';
5
5
  import type { BbRemote, ConductorRegistration } from '../plugins/remote.js';
6
6
  import type { BbWorkspace } from '../plugins/workspace.js';
7
7
  import type { ConductorFileConfig } from '../types.js';
8
+ import { type HookRunner } from './hook-runner.js';
8
9
  /**
9
10
  * Resolve the environment a run executes in (BB-99): parse the ticket's
10
11
  * effective env_vars, drop any reserved key (loud warn — key NAME only, never
@@ -34,6 +35,7 @@ export declare class Conductor {
34
35
  private readonly logger;
35
36
  private readonly checkoutRoot;
36
37
  private readonly frozenStateFile?;
38
+ private readonly runHook;
37
39
  private uuid;
38
40
  /**
39
41
  * Frozen tickets seen on the last poll, by uuid, with the worktree their
@@ -48,11 +50,9 @@ export declare class Conductor {
48
50
  private readonly queue;
49
51
  /** The local MCP server for addon tools; only the serve process runs one. */
50
52
  private toolServer;
51
- /** The live run token per run UUID, revoked when the run is finalised. */
52
- private readonly runTokens;
53
53
  /** Serializes git worktree add/remove: parallel ones fight over git locks. */
54
54
  private gitLock;
55
- constructor(config: ConductorFileConfig, remote: BbRemote, executor: BbExecutor, workspace: BbWorkspace, agents: ResolvedAgent[], logger: ConductorLogger, checkoutRoot?: string, frozenStateFile?: string | undefined);
55
+ constructor(config: ConductorFileConfig, remote: BbRemote, executor: BbExecutor, workspace: BbWorkspace, agents: ResolvedAgent[], logger: ConductorLogger, checkoutRoot?: string, frozenStateFile?: string | undefined, runHook?: HookRunner);
56
56
  private serialGit;
57
57
  /**
58
58
  * `conductor_id` is derived by the loader from the machine UUID, project and
@@ -88,9 +88,12 @@ export declare class Conductor {
88
88
  * it to the CLI.
89
89
  */
90
90
  startTools(endpointFile?: string): Promise<void>;
91
+ /** Tell an open `bakers ui` in the checkout (and the run's worktree) to reload. */
92
+ private signalUi;
91
93
  stopTools(): Promise<void>;
92
94
  /** A fresh token for this run's worktree; a re-dispatch replaces the old one. */
93
95
  private issueRunTools;
96
+ /** Never throws: a failed state write leaves the grant on disk, and the next start prunes it. */
94
97
  private revokeRunTools;
95
98
  start(): Promise<void>;
96
99
  /** One tick that also waits for its actions: `bakers oven once`, tests. */
@@ -138,7 +141,7 @@ export declare class Conductor {
138
141
  private get listeners();
139
142
  /**
140
143
  * Run one lifecycle slot (BB-599): every addon listener in accumulator
141
- * order, awaited, then the project shell hook through the executor. Never
144
+ * order, awaited, then the project shell hook through {@link runHook}. Never
142
145
  * throws. A failing listener is logged by slot, listener, ticket and run —
143
146
  * never with its message or the env — and reported in the returned result
144
147
  * the same way a failing shell command is, so the rest of the slot, the
@@ -179,7 +182,7 @@ export declare class Conductor {
179
182
  * `BbTicket::preSave()` on any save of a terminal, unclosed ticket, so it
180
183
  * holds for every write path and cannot be withheld by a teardown hiccup —
181
184
  * the reap reasons about `cleaned_up` alone. `cleaned_up` is withheld unless
182
- * the teardown is ACCOUNTED FOR (BB-141 RC-2), which `removeWorktree`
185
+ * the teardown is ACCOUNTED FOR (BB-141 RC-2), which `workspace.remove`
183
186
  * reports as one of three outcomes (BB-293):
184
187
  * - `removed` — gone because this host tore it down → flag cleaned;
185
188
  * - `already_absent` — nothing was there to tear down. A FINISHED teardown,
@@ -220,6 +223,7 @@ export declare class Conductor {
220
223
  private runEnv;
221
224
  /** Dispatches one claimed run; a failure terminalises it (BB-149). */
222
225
  private dispatchOrFail;
226
+ /** `at.worktree` is set once the workspace exists, so a failure can signal it. */
223
227
  private dispatch;
224
228
  /**
225
229
  * The part of a dispatch that can leave a sidecar or a worker behind