@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.
@@ -7,9 +7,11 @@ import { sandboxFailures } from '../plugins/sandbox-preflight.js';
7
7
  import { loadTools } from '../plugins/tools.js';
8
8
  import { ActionQueue } from './action-queue.js';
9
9
  import { attemptFamily } from './attempt.js';
10
+ import { shellHookRunner } from './hook-runner.js';
10
11
  import { InboxRuntime, runInbox } from './inbox-runtime.js';
11
12
  import { measureMrChanges, mrChangesRows } from './mr-changes.js';
12
13
  import { startToolServer } from './tool-server.js';
14
+ import { signalUi } from './ui-signal.js';
13
15
  function sleep(ms, signal) {
14
16
  return new Promise((resolve) => {
15
17
  if (signal?.aborted) {
@@ -186,6 +188,7 @@ export class Conductor {
186
188
  logger;
187
189
  checkoutRoot;
188
190
  frozenStateFile;
191
+ runHook;
189
192
  uuid = null;
190
193
  /**
191
194
  * Frozen tickets seen on the last poll, by uuid, with the worktree their
@@ -200,11 +203,9 @@ export class Conductor {
200
203
  queue;
201
204
  /** The local MCP server for addon tools; only the serve process runs one. */
202
205
  toolServer;
203
- /** The live run token per run UUID, revoked when the run is finalised. */
204
- runTokens = new Map();
205
206
  /** Serializes git worktree add/remove: parallel ones fight over git locks. */
206
207
  gitLock = Promise.resolve();
207
- constructor(config, remote, executor, workspace, agents, logger, checkoutRoot = process.cwd(), frozenStateFile) {
208
+ constructor(config, remote, executor, workspace, agents, logger, checkoutRoot = process.cwd(), frozenStateFile, runHook = shellHookRunner(config.hooks, logger)) {
208
209
  this.config = config;
209
210
  this.remote = remote;
210
211
  this.executor = executor;
@@ -213,6 +214,7 @@ export class Conductor {
213
214
  this.logger = logger;
214
215
  this.checkoutRoot = checkoutRoot;
215
216
  this.frozenStateFile = frozenStateFile;
217
+ this.runHook = runHook;
216
218
  this.inboxAddons = new InboxRuntime(config.inboxAddons ?? [], remote, logger, (ticket) => this.runEnv(ticket, undefined, ticket.state), config.tools);
217
219
  this.queue = new ActionQueue(logger);
218
220
  }
@@ -277,37 +279,50 @@ export class Conductor {
277
279
  const { siteTools } = this.remote;
278
280
  if ((!this.config.tools && !siteTools) || this.toolServer)
279
281
  return;
282
+ // Runs closed while no server ran (`oven once`, a crash) lose their grant here.
283
+ const openRuns = await this.remote.fetchActiveRuns(this.id).then((runs) => runs.map((r) => r.runUuid), (err) => {
284
+ this.logger.warn({ err: String(err) }, 'active runs unreadable, keeping every persisted run grant');
285
+ return undefined;
286
+ });
280
287
  this.toolServer = await startToolServer({
281
288
  registry: this.config.tools ?? (await loadTools([])),
282
289
  workspaceRoot: this.checkoutRoot,
283
290
  logger: this.logger,
284
291
  ...(endpointFile ? { endpointFile } : {}),
292
+ ...(openRuns ? { openRuns } : {}),
285
293
  ...(siteTools ? { siteTools } : {}),
294
+ onSiteWrite: (b) => this.signalUi(b.worktreePath),
286
295
  });
287
296
  this.logger.info({ conductorId: this.config.conductor_id, url: this.toolServer.url }, 'tool server started');
288
297
  }
298
+ /** Tell an open `bakers ui` in the checkout (and the run's worktree) to reload. */
299
+ signalUi(worktree) {
300
+ signalUi(this.checkoutRoot);
301
+ if (worktree)
302
+ signalUi(worktree);
303
+ }
289
304
  async stopTools() {
290
305
  // Server first, so no new provision_up starts a run after the stop.
291
306
  await this.toolServer?.stop();
292
307
  await this.config.provisioning?.stop();
293
308
  await this.remote.siteTools?.close();
294
309
  this.toolServer = undefined;
295
- this.runTokens.clear();
296
310
  }
297
311
  /** A fresh token for this run's worktree; a re-dispatch replaces the old one. */
298
312
  issueRunTools(runUuid, binding) {
299
313
  if (!this.toolServer)
300
314
  return undefined;
301
- this.revokeRunTools(runUuid);
302
- const token = this.toolServer.issueRunToken(binding);
303
- this.runTokens.set(runUuid, token);
315
+ const token = this.toolServer.issueRunToken(runUuid, binding);
304
316
  return { url: this.toolServer.url, token };
305
317
  }
318
+ /** Never throws: a failed state write leaves the grant on disk, and the next start prunes it. */
306
319
  revokeRunTools(runUuid) {
307
- const token = this.runTokens.get(runUuid);
308
- if (token)
309
- this.toolServer?.revokeRunToken(token);
310
- this.runTokens.delete(runUuid);
320
+ try {
321
+ this.toolServer?.revokeRunToken(runUuid);
322
+ }
323
+ catch (err) {
324
+ this.logger.warn({ run: runUuid, err: String(err) }, 'run tool revoke failed');
325
+ }
311
326
  }
312
327
  async start() {
313
328
  this.uuid = await this.remote.registerConductor(this.registration());
@@ -404,6 +419,7 @@ export class Conductor {
404
419
  break;
405
420
  }
406
421
  this.logger.info({ conductorId: this.id, run: run.runUuid, ticket: run.ticketUuid }, 'claimed run');
422
+ this.signalUi();
407
423
  this.queue.enqueue({
408
424
  key: `dispatch:${run.runUuid}`,
409
425
  lane: run.ticketUuid,
@@ -454,7 +470,7 @@ export class Conductor {
454
470
  try {
455
471
  // Signal the agent to stop before capturing its log. Best-effort and
456
472
  // gated on the persistent capability (only hosted executors have a live
457
- // agent) — mirrors removeWorktree's gate. For herdr this is a no-op
473
+ // agent). For herdr this is a no-op
458
474
  // (the tab-close in closeRunTab kills the PTY); a stop failure must
459
475
  // never block finalisation.
460
476
  const branch = this.executor.capabilities().persistent
@@ -488,14 +504,17 @@ export class Conductor {
488
504
  await this.runFinalizeHook(r);
489
505
  if (!captured)
490
506
  throw captureError;
491
- // `?? true` is the default: an unset flag, and every config written
492
- // before this setting existed, keep uploading exactly as before.
493
- // `finalizeRun()` already spreads `...(log ? { log } : {})`, so an
494
- // empty string omits the attribute from the PATCH entirely — no
495
- // server change is needed and no empty log is written.
496
- const uploadedLog = (this.config.capture_logs ?? true) ? captured.log : '';
497
- await this.remote.finalizeRun(r.runUuid, uploadedLog, captured.metrics);
507
+ // The server's policy decides first (missing means no), and the local
508
+ // `capture_logs` opt-out can only narrow it. `finalizeRun()` spreads
509
+ // `...(log ? { log } : {})`, so an empty string omits the attribute
510
+ // from the PATCH entirely; the server re-checks its policy anyway.
511
+ const uploadedLog = r.runLogStorageAllowed === true && (this.config.capture_logs ?? true)
512
+ ? captured.log
513
+ : '';
514
+ // Revoke before the durable close: a crash between the two must not leave a closed run's grant.
498
515
  this.revokeRunTools(r.runUuid);
516
+ await this.remote.finalizeRun(r.runUuid, uploadedLog, captured.metrics);
517
+ this.signalUi(r.worktreePath);
499
518
  this.logger.info({ run: r.runUuid, state: r.state, footprint: captured.metrics }, 'run finalised');
500
519
  }
501
520
  catch (err) {
@@ -645,7 +664,7 @@ export class Conductor {
645
664
  }
646
665
  /**
647
666
  * Run one lifecycle slot (BB-599): every addon listener in accumulator
648
- * order, awaited, then the project shell hook through the executor. Never
667
+ * order, awaited, then the project shell hook through {@link runHook}. Never
649
668
  * throws. A failing listener is logged by slot, listener, ticket and run —
650
669
  * never with its message or the env — and reported in the returned result
651
670
  * the same way a failing shell command is, so the rest of the slot, the
@@ -682,7 +701,7 @@ export class Conductor {
682
701
  });
683
702
  }
684
703
  }
685
- const shell = await this.executor.runHook(name, cwd, { ticket: ticketRef }, shellEnv);
704
+ const shell = await this.runHook(name, cwd, { ticket: ticketRef }, shellEnv);
686
705
  if (failed.length === 0)
687
706
  return shell;
688
707
  const error = `hook listener failed: ${failed.join(', ')}`;
@@ -822,7 +841,7 @@ export class Conductor {
822
841
  * `BbTicket::preSave()` on any save of a terminal, unclosed ticket, so it
823
842
  * holds for every write path and cannot be withheld by a teardown hiccup —
824
843
  * the reap reasons about `cleaned_up` alone. `cleaned_up` is withheld unless
825
- * the teardown is ACCOUNTED FOR (BB-141 RC-2), which `removeWorktree`
844
+ * the teardown is ACCOUNTED FOR (BB-141 RC-2), which `workspace.remove`
826
845
  * reports as one of three outcomes (BB-293):
827
846
  * - `removed` — gone because this host tore it down → flag cleaned;
828
847
  * - `already_absent` — nothing was there to tear down. A FINISHED teardown,
@@ -881,14 +900,13 @@ export class Conductor {
881
900
  /** Reaps one ticket; isolated, so one failure never aborts the rest. */
882
901
  async reapOne(t) {
883
902
  try {
884
- // Infra teardown. The `after_done` hook runs in the worktree regardless
885
- // of executor kind (a non-persistent gitWorkspace still has an on-disk
886
- // worktree); only the workspace removal is gated on the persistent
887
- // capability (mirrors the executor-agnostic release path). Pass the
888
- // stable worktreePath so the executor resolves the worktree by path,
889
- // not by the mutable checked-out branch (the coding agent may rename
890
- // it). Teardown is idempotent: a worktree herdr no longer tracks is a
891
- // no-op / on-disk reclaim, not a failure.
903
+ // Infra teardown. The `after_done` hook runs in the worktree, then the
904
+ // workspace removes it — for every executor kind: a non-persistent
905
+ // executor still leaves an on-disk worktree behind. Pass the stable
906
+ // worktreePath so the workspace resolves the worktree by path, not by
907
+ // the mutable checked-out branch (the coding agent may rename it).
908
+ // Teardown is idempotent: a worktree no longer tracked is a no-op /
909
+ // on-disk reclaim, not a failure.
892
910
  //
893
911
  // The hook needs the DIRECTORY, not just a recorded path (BB-293): a
894
912
  // hook is a shell spawned with the worktree as its `cwd`, so against an
@@ -902,13 +920,12 @@ export class Conductor {
902
920
  // container runtime's project also drops its registration and database — and
903
921
  // that leftover is then an operator's to clear by hand.
904
922
  //
905
- // But the line states the CONDITION, not a decision about a hook: hook
906
- // commands are executor-owned config that the core cannot see, so it
907
- // does not know whether an `after_done` is configured at all. Saying a
908
- // hook was "skipped" would be false wherever none exists (the generated
909
- // playground config is exactly such a case). What the core does know is
910
- // that the directory is gone and that no `after_done` ran — both true in
911
- // either configuration.
923
+ // But the line states the CONDITION, not a decision about a hook: an
924
+ // `after_done` may be a listener, a shell command or nothing at all.
925
+ // Saying a hook was "skipped" would be false wherever none exists (the
926
+ // generated playground config is exactly such a case). What the core
927
+ // does know is that the directory is gone and that no `after_done` ran —
928
+ // both true in every configuration.
912
929
  //
913
930
  // `existsSync` here is a plain filesystem question, not worktree
914
931
  // knowledge: the core stays executor-agnostic and asks nothing about
@@ -944,83 +961,80 @@ export class Conductor {
944
961
  }, 'worktree directory absent — after_done not run');
945
962
  }
946
963
  }
947
- if (this.executor.capabilities().persistent) {
948
- let outcome;
949
- try {
950
- // removeWorktree reports what the teardown DID (BB-293):
951
- // `removed` = the worktree is gone because this host removed it;
952
- // `already_absent` = there was nothing to tear down; `unverified` =
953
- // it could NOT be resolved and may still be on disk (BB-141 RC-2
954
- // — e.g. worktree_path was never persisted and herdr lost track of
955
- // the branch). A THROW is a hard failure.
956
- outcome = await this.serialGit(() => this.executor.removeWorktree(t.branchName, t.worktreePath || undefined));
964
+ let outcome;
965
+ try {
966
+ // workspace.remove reports what the teardown DID (BB-293):
967
+ // `removed` = the worktree is gone because this host removed it;
968
+ // `already_absent` = there was nothing to tear down; `unverified` =
969
+ // it could NOT be resolved and may still be on disk (BB-141 RC-2
970
+ // — e.g. worktree_path was never persisted and herdr lost track of
971
+ // the branch). A THROW is a hard failure.
972
+ outcome = await this.serialGit(() => this.workspace.remove(t.branchName, t.worktreePath || undefined));
973
+ }
974
+ catch (err) {
975
+ this.logger.warn({
976
+ ticket: t.ticketUuid,
977
+ branch: t.branchName,
978
+ worktreePath: t.worktreePath,
979
+ err: String(err),
980
+ }, 'worktree teardown failed');
981
+ return; // leave cleaned_up=0 → the next reconciliation retries.
982
+ }
983
+ if (outcome === 'unverified') {
984
+ // BB-468 — an unverified teardown with NO run and NO recorded
985
+ // path has nothing left for a later reap to resolve: no run will
986
+ // appear on a terminal ticket, and no branch will appear for work
987
+ // that never started (`reap()` passes `t.worktreePath ||
988
+ // undefined`, so a never-ran ticket and a lost-path ticket reach
989
+ // the executor byte-identically — only the reaper, which alone
990
+ // knows `runUuid === ''`, can tell them apart). That retry is not
991
+ // deferred, it is unreachable, so it is logged ONCE at info and
992
+ // accounted for below rather than retried forever. BB-141 RC-2
993
+ // is unchanged for every ticket that DOES carry a run or a
994
+ // recorded path: those keep retrying below, unaffected.
995
+ if (!t.runUuid && !t.worktreePath) {
996
+ this.logger.info({ ticket: t.ticketUuid, branch: t.branchName }, 'no run and no recorded path — nothing to tear down');
957
997
  }
958
- catch (err) {
998
+ else {
999
+ // Unverified teardown (BB-141 RC-2): do NOT flag cleaned_up, or
1000
+ // the ticket drops off fetchUncleanedTickets (which filters
1001
+ // cleaned_up=0) and the orphan is never retried. Leave it on the
1002
+ // work list so a later reap — with a persisted path, or once the
1003
+ // executor resolves it via the parent-repo git worktree list —
1004
+ // can finish the job.
959
1005
  this.logger.warn({
960
1006
  ticket: t.ticketUuid,
961
1007
  branch: t.branchName,
962
1008
  worktreePath: t.worktreePath,
963
- err: String(err),
964
- }, 'worktree teardown failed');
1009
+ }, 'worktree teardown unverified — retrying next reap');
965
1010
  return; // leave cleaned_up=0 → the next reconciliation retries.
966
1011
  }
967
- if (outcome === 'unverified') {
968
- // BB-468 — an unverified teardown with NO run and NO recorded
969
- // path has nothing left for a later reap to resolve: no run will
970
- // appear on a terminal ticket, and no branch will appear for work
971
- // that never started (`reap()` passes `t.worktreePath ||
972
- // undefined`, so a never-ran ticket and a lost-path ticket reach
973
- // the executor byte-identically — only the reaper, which alone
974
- // knows `runUuid === ''`, can tell them apart). That retry is not
975
- // deferred, it is unreachable, so it is logged ONCE at info and
976
- // accounted for below rather than retried forever. BB-141 RC-2
977
- // is unchanged for every ticket that DOES carry a run or a
978
- // recorded path: those keep retrying below, unaffected.
979
- if (!t.runUuid && !t.worktreePath) {
980
- this.logger.info({ ticket: t.ticketUuid, branch: t.branchName }, 'no run and no recorded path — nothing to tear down');
981
- }
982
- else {
983
- // Unverified teardown (BB-141 RC-2): do NOT flag cleaned_up, or
984
- // the ticket drops off fetchUncleanedTickets (which filters
985
- // cleaned_up=0) and the orphan is never retried. Leave it on the
986
- // work list so a later reap — with a persisted path, or once the
987
- // executor resolves it via the parent-repo git worktree list —
988
- // can finish the job.
989
- this.logger.warn({
990
- ticket: t.ticketUuid,
991
- branch: t.branchName,
992
- worktreePath: t.worktreePath,
993
- }, 'worktree teardown unverified — retrying next reap');
994
- return; // leave cleaned_up=0 → the next reconciliation retries.
1012
+ }
1013
+ if (outcome === 'already_absent') {
1014
+ // BB-293: the worktree was gone before we got here. That is a
1015
+ // FINISHED teardown, so it is recorded rather than swallowed and
1016
+ // the ticket is flagged cleaned below — the next reap will not
1017
+ // retry it.
1018
+ this.logger.info({
1019
+ ticket: t.ticketUuid,
1020
+ branch: t.branchName,
1021
+ worktreePath: t.worktreePath,
1022
+ }, 'worktree already absent — teardown complete');
1023
+ // A ticket with no run has no record to write to — the conductor
1024
+ // log above is then the whole account.
1025
+ if (t.runUuid) {
1026
+ try {
1027
+ await this.remote.appendRunNote(t.runUuid, `worktree already absent at teardown: ${t.worktreePath || '(path unknown)'}`);
995
1028
  }
996
- }
997
- if (outcome === 'already_absent') {
998
- // BB-293: the worktree was gone before we got here. That is a
999
- // FINISHED teardown, so it is recorded rather than swallowed and
1000
- // the ticket is flagged cleaned below — the next reap will not
1001
- // retry it.
1002
- this.logger.info({
1003
- ticket: t.ticketUuid,
1004
- branch: t.branchName,
1005
- worktreePath: t.worktreePath,
1006
- }, 'worktree already absent — teardown complete');
1007
- // A ticket with no run has no record to write to — the conductor
1008
- // log above is then the whole account.
1009
- if (t.runUuid) {
1010
- try {
1011
- await this.remote.appendRunNote(t.runUuid, `worktree already absent at teardown: ${t.worktreePath || '(path unknown)'}`);
1012
- }
1013
- catch (err) {
1014
- // Best-effort: an unreachable control plane must not keep a
1015
- // finished teardown from being flagged.
1016
- this.logger.warn({ ticket: t.ticketUuid, run: t.runUuid, err: String(err) }, 'run note write failed');
1017
- }
1029
+ catch (err) {
1030
+ // Best-effort: an unreachable control plane must not keep a
1031
+ // finished teardown from being flagged.
1032
+ this.logger.warn({ ticket: t.ticketUuid, run: t.runUuid, err: String(err) }, 'run note write failed');
1018
1033
  }
1019
1034
  }
1020
1035
  }
1021
- // Teardown verified locally, the worktree was already absent, or there
1022
- // is nothing hosted to tear down: flag it cleaned so it drops off the
1023
- // work list.
1036
+ // Teardown verified locally or the worktree was already absent: flag it
1037
+ // cleaned so it drops off the work list.
1024
1038
  await this.remote.markTicketCleanedUp(t.ticketUuid);
1025
1039
  this.logger.info({ ticket: t.ticketUuid }, 'ticket cleaned up');
1026
1040
  }
@@ -1074,8 +1088,9 @@ export class Conductor {
1074
1088
  }
1075
1089
  /** Dispatches one claimed run; a failure terminalises it (BB-149). */
1076
1090
  async dispatchOrFail(run) {
1091
+ const at = {};
1077
1092
  try {
1078
- await this.dispatch(run);
1093
+ await this.dispatch(run, at);
1079
1094
  }
1080
1095
  catch (err) {
1081
1096
  // BB-149: terminalise the run to `failed` with the error captured,
@@ -1092,13 +1107,15 @@ export class Conductor {
1092
1107
  this.logger.error({ run: run.runUuid, err: String(err) }, 'dispatch failed');
1093
1108
  try {
1094
1109
  await this.remote.markFailed(run.runUuid, String(err));
1110
+ this.signalUi(at.worktree);
1095
1111
  }
1096
1112
  catch (markErr) {
1097
1113
  this.logger.warn({ run: run.runUuid, err: String(markErr) }, 'markFailed failed');
1098
1114
  }
1099
1115
  }
1100
1116
  }
1101
- async dispatch(run) {
1117
+ /** `at.worktree` is set once the workspace exists, so a failure can signal it. */
1118
+ async dispatch(run, at = {}) {
1102
1119
  const t = await this.remote.getTicket(run.ticketUuid);
1103
1120
  // Resolve the ticket alias and machine defaults, or the project selection hook.
1104
1121
  // Persist the package id below so finalize can choose its transcript parser.
@@ -1114,11 +1131,12 @@ export class Conductor {
1114
1131
  throw new Error(unavailable);
1115
1132
  const baseRef = t.baseBranch ? `origin/${t.baseBranch}` : undefined;
1116
1133
  // Resolve the run env once (per-ticket env_vars + core BB_* vars) and
1117
- // inject it into BOTH the executor-owned lifecycle hooks AND the agent run
1134
+ // inject it into BOTH the lifecycle hooks AND the agent run
1118
1135
  // env (BB-99). Reserved core keys always win; values may be sensitive so
1119
1136
  // only key names are ever logged.
1120
1137
  const env = await this.runEnv(t, run.runUuid, run.stateAtStart, chosen.agent);
1121
1138
  const ws = await this.serialGit(() => this.workspace.ensure(t.identifier, t.branchName, baseRef));
1139
+ at.worktree = ws.path;
1122
1140
  // The backend's own vars (Git config) join the run env; core keys still win.
1123
1141
  for (const [key, value] of Object.entries(ws.env ?? {})) {
1124
1142
  if (!isReservedEnvKey(key))
@@ -1156,7 +1174,7 @@ export class Conductor {
1156
1174
  */
1157
1175
  async launch(run, t, chosen, ws, ctx, launch) {
1158
1176
  const env = ctx.env;
1159
- // Lifecycle hooks are executor-owned + best-effort (BB-84): runHook never
1177
+ // Lifecycle hooks are conductor-owned + best-effort (BB-84): runHook never
1160
1178
  // throws, so neither call can abort dispatch or wedge a run in `claimed`.
1161
1179
  // `runSlot` runs the addon listeners first under the same rule (BB-599).
1162
1180
  // Both get the resolved run env so a setup/pre hook sees the same vars (e.g.
@@ -1200,7 +1218,7 @@ export class Conductor {
1200
1218
  err: provisioning.error,
1201
1219
  }, 'lifecycle hook failed');
1202
1220
  }
1203
- // BB-237: apply the workspace's open layout HERE — after `after_create`,
1221
+ // BB-237: open the fresh worktree in the executor HERE — after `after_create`,
1204
1222
  // before the run starts. The layout's startup command names the bakers CLI
1205
1223
  // that `after_create` builds; applied inside `workspace.ensure()` (where it
1206
1224
  // used to live) it necessarily fired first, so a self-hosting checkout had
@@ -1214,7 +1232,7 @@ export class Conductor {
1214
1232
  // Optional on the contract, so a workspace with no layout concept is a
1215
1233
  // no-op. Best-effort by contract: implementations swallow their own errors.
1216
1234
  if (ws.created) {
1217
- await this.workspace.applyOpenLayout?.(ws.path, {
1235
+ await this.executor.openWorkspace?.(ws.path, {
1218
1236
  identifier: t.identifier,
1219
1237
  branch: t.branchName,
1220
1238
  title: t.title,
@@ -1335,6 +1353,7 @@ export class Conductor {
1335
1353
  agent: chosen.id,
1336
1354
  startedAt: dispatchedAt,
1337
1355
  });
1356
+ this.signalUi(ws.path);
1338
1357
  }
1339
1358
  /**
1340
1359
  * Stop what a failed dispatch started (BB-599): the worker if it was
@@ -0,0 +1,23 @@
1
+ import { type ConductorLogger } from '@bakers-build/core';
2
+ import type { HookContext, HookName, HookResult } from '../plugins/executor.js';
3
+ import type { ConductorSettings } from '../types.js';
4
+ /** Runs a lifecycle-hook shell command in a cwd; rejects on non-zero exit. */
5
+ export type ShellRunner = (command: string, cwd: string, env?: Record<string, string>) => Promise<void>;
6
+ /**
7
+ * Runs the project shell hook of one lifecycle slot. The SINGLE catch point for
8
+ * all lifecycle hooks:
9
+ *
10
+ * - NEVER throws. No configured command → silent no-op. A failing command →
11
+ * `logger.error({hook,worktree,ticket,err}, 'lifecycle hook failed')`, so a
12
+ * hook failure never aborts dispatch or wedges a run in `claimed`.
13
+ * - Reports the outcome as a {@link HookResult} (BB-237): the caller decides
14
+ * what a failure means for the run it is dispatching.
15
+ *
16
+ * `env`, when given, is the run's resolved environment, merged over the hook
17
+ * process's inherited env. Values may be secret: only key names are ever logged.
18
+ */
19
+ export type HookRunner = (name: HookName, cwd: string, ctx: HookContext, env?: Record<string, string>) => Promise<HookResult>;
20
+ /** Default shell runner: `sh -c <command>` in the worktree — fails honestly. */
21
+ export declare const defaultShellRunner: ShellRunner;
22
+ /** The conductor's hook runner over the project's `hooks` commands. */
23
+ export declare function shellHookRunner(hooks: ConductorSettings['hooks'], logger: ConductorLogger, runShell?: ShellRunner): HookRunner;
@@ -0,0 +1,22 @@
1
+ import { exec } from '@bakers-build/core';
2
+ /** Default shell runner: `sh -c <command>` in the worktree — fails honestly. */
3
+ export const defaultShellRunner = async (command, cwd, env) => {
4
+ await exec('sh', ['-c', command], { cwd, ...(env ? { env } : {}) });
5
+ };
6
+ /** The conductor's hook runner over the project's `hooks` commands. */
7
+ export function shellHookRunner(hooks, logger, runShell = defaultShellRunner) {
8
+ return async (name, cwd, ctx, env) => {
9
+ const command = hooks?.[name];
10
+ if (!command) {
11
+ return { hook: name, ran: false, ok: true };
12
+ }
13
+ try {
14
+ await runShell(command, cwd, env);
15
+ return { hook: name, ran: true, ok: true };
16
+ }
17
+ catch (err) {
18
+ logger.error({ hook: name, worktree: cwd, ticket: ctx.ticket, err: String(err) }, 'lifecycle hook failed');
19
+ return { hook: name, ran: true, ok: false, error: String(err) };
20
+ }
21
+ };
22
+ }
@@ -3,6 +3,8 @@ import type { SiteToolClient } from '../plugins/remote.js';
3
3
  import type { ToolBinding } from '../plugins/tools.js';
4
4
  /** The site tools a run may call. */
5
5
  export declare const SITE_TOOLS: readonly string[];
6
+ /** The site tools that change a ticket; a successful call signals `bakers ui`. */
7
+ export declare const SITE_WRITE_TOOLS: readonly string[];
6
8
  export interface SiteTool {
7
9
  name: string;
8
10
  description?: string;
@@ -17,6 +17,14 @@ export const SITE_TOOLS = [
17
17
  'bakers_project_read',
18
18
  'bakers_user_read',
19
19
  ];
20
+ /** The site tools that change a ticket; a successful call signals `bakers ui`. */
21
+ export const SITE_WRITE_TOOLS = [
22
+ 'bakers_ticket_create',
23
+ 'bakers_ticket_update',
24
+ 'bakers_ticket_classify',
25
+ 'bakers_ticket_transition',
26
+ 'bakers_comment_publish',
27
+ ];
20
28
  const WIRE = 'tool_api__';
21
29
  export function siteToolProxy(client, logger) {
22
30
  return {
@@ -4,8 +4,9 @@ import type { ToolBinding, ToolRegistry } from '../plugins/tools.js';
4
4
  export interface ToolServer {
5
5
  /** The MCP endpoint. */
6
6
  url: string;
7
- issueRunToken(binding: ToolBinding): string;
8
- revokeRunToken(token: string): void;
7
+ /** A fresh token for the run; replaces the run's earlier grant. */
8
+ issueRunToken(runUuid: string, binding: ToolBinding): string;
9
+ revokeRunToken(runUuid: string): void;
9
10
  stop(): Promise<void>;
10
11
  }
11
12
  /** What the conductor publishes for the CLI in the endpoint file. */
@@ -24,5 +25,9 @@ export interface ToolServerOptions {
24
25
  logger?: ConductorLogger;
25
26
  /** The site's tools, served to run tokens only; absent: none. */
26
27
  siteTools?: SiteToolClient;
28
+ /** Called after a run's successful ticket write through a site tool. */
29
+ onSiteWrite?: (binding: ToolBinding) => void;
30
+ /** The runs still open; persisted grants of any other run are dropped. Absent: keep all. */
31
+ openRuns?: string[];
27
32
  }
28
33
  export declare function startToolServer(options: ToolServerOptions): Promise<ToolServer>;