@bakers-build/conductor 0.8.0 → 0.8.1-next.2

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.
@@ -39,6 +39,8 @@ export declare class Conductor {
39
39
  /** Re-reads machine.config.js per run; absent, `config.tunnel` stays. */
40
40
  private readonly readMachine?;
41
41
  private uuid;
42
+ /** Runs running at this process's first lost-run check whose pane lookup has not answered yet: resumed, not failed. */
43
+ private recovering?;
42
44
  /**
43
45
  * Frozen tickets seen on the last poll, by uuid, with the worktree their
44
46
  * hook ran in. Mirrored to `frozenStateFile` when one is given, so an
@@ -46,6 +48,10 @@ export declare class Conductor {
46
48
  * restart does not repeat `on_freeze`; loaded on the first observation.
47
49
  */
48
50
  private frozenSeen;
51
+ /** Transcript mtime each active run was last checked for denials at. */
52
+ private readonly stallChecked;
53
+ /** Active runs already reported as blocked; never reported twice. */
54
+ private readonly stallReported;
49
55
  /** The addons with contract-2 inbox messages this conductor runs. */
50
56
  private readonly inboxAddons;
51
57
  /** The per-item work each tick enqueues. */
@@ -80,7 +86,7 @@ export declare class Conductor {
80
86
  *
81
87
  * Only `cmdStartForeground` calls this. `cmdPoll` and `cmdReap` also build a
82
88
  * Conductor and call start() + tick(), then exit; if they reported a pid,
83
- * every `bakers oven once` would overwrite the running conductor's pid
89
+ * every `bakers conductor once` would overwrite the running conductor's pid
84
90
  * with its own short-lived one and the next stop would signal a dead — or
85
91
  * recycled — process. Making the report opt-in means those two commands
86
92
  * cannot do so even by accident.
@@ -102,7 +108,7 @@ export declare class Conductor {
102
108
  /** Never throws: a failed state write leaves the grant on disk, and the next start prunes it. */
103
109
  private revokeRunTools;
104
110
  start(): Promise<void>;
105
- /** One tick that also waits for its actions: `bakers oven once`, tests. */
111
+ /** One tick that also waits for its actions: `bakers conductor once`, tests. */
106
112
  tick(): Promise<void>;
107
113
  /** A failing list query must not stop the other steps or the claims. */
108
114
  private step;
@@ -112,6 +118,25 @@ export declare class Conductor {
112
118
  * the heartbeat or the claims.
113
119
  */
114
120
  produce(): Promise<void>;
121
+ /**
122
+ * Fails every running run whose terminal is gone: nobody executes it, and
123
+ * the server never expires a `running` run. Keyed off the durable active-run
124
+ * query, so a restarted conductor checks adopted runs on its first tick.
125
+ */
126
+ private enqueueLostRuns;
127
+ /**
128
+ * Fails and reports one run when its terminal is gone; a failed lookup
129
+ * changes nothing. On a run's first answering lookup after a restart it
130
+ * resumes the run instead, when its agent and session allow.
131
+ */
132
+ private lostOne;
133
+ private stillRunning;
134
+ private lostComment;
135
+ /**
136
+ * Relaunches a lost run in its worktree with its agent's session resume.
137
+ * Returns undefined when resumed, else why it was not: the caller fails it.
138
+ */
139
+ private resumeLost;
115
140
  /**
116
141
  * One-shot finalisation: for each of this conductor's runs that is state in
117
142
  * (done, cancelled) but not yet closed, read the agent transcript from its
@@ -120,8 +145,26 @@ export declare class Conductor {
120
145
  * conductor still finalises any unclosed run on its next tick.
121
146
  */
122
147
  private enqueueFinalize;
148
+ /**
149
+ * A run a permission rule denied cannot ask anyone on an unattended box,
150
+ * so it stops. Once its transcript has been quiet for {@link STALL_QUIET_MS}
151
+ * and holds a denial, report it once. One stat per running run per tick;
152
+ * the transcript is read once per modification.
153
+ */
154
+ private observeStalls;
155
+ /**
156
+ * The technical-problem note, then the error: the PM bot relays the newest
157
+ * comment of a frozen, labelled ticket. Cancelling lets finalisation stop
158
+ * the agent and keep its transcript.
159
+ */
160
+ private reportBlocked;
123
161
  /** Finalises one run; a failure is logged and retried next tick. */
124
162
  private finalizeOne;
163
+ /**
164
+ * The agent that actually ran: the persisted run.agent id, falling back to
165
+ * the first candidate for a run written before the field existed (empty id).
166
+ */
167
+ private agentFor;
125
168
  /** Read the run's transcript and parse its footprint for the close write. */
126
169
  private captureRun;
127
170
  /**
@@ -175,7 +218,7 @@ export declare class Conductor {
175
218
  * whose workspace still lingers (BB-89). Driven by the durable `cleaned_up`
176
219
  * flag via {@link BbRemote.fetchUncleanedTickets}: every ticket the server
177
220
  * has already closed but not yet cleaned. The SAME reconciliation runs on
178
- * every tick AND standalone as `bakers oven clean`, and the query is
221
+ * every tick AND standalone as `bakers conductor clean`, and the query is
179
222
  * scoped to THIS conductor (BB-121) — so it catches the orphans a
180
223
  * live-tick-only path structurally cannot (the conductor was down when the
181
224
  * ticket closed, or crashed mid-cleanup) for its OWN tickets. A foreign
@@ -240,13 +283,18 @@ export declare class Conductor {
240
283
  * one `plugins` entry. A failed install throws, failing the run start.
241
284
  */
242
285
  private installPlugins;
243
- /** `at.worktree` is set once the workspace exists, so a failure can signal it. */
286
+ /**
287
+ * `at.worktree` is set once the workspace exists, so a failure can signal it.
288
+ * `resume`: continue the run's newest agent session instead of prompting afresh.
289
+ */
244
290
  private dispatch;
245
291
  /**
246
292
  * The part of a dispatch that can leave a sidecar or a worker behind
247
293
  * (BB-599): its caller unwinds it through `after_run` on any failure.
248
294
  */
249
295
  private launch;
296
+ /** The run's newest agent session, or why it cannot be resumed. */
297
+ private resumableSession;
250
298
  /**
251
299
  * Stop what a failed dispatch started (BB-599): the worker if it was
252
300
  * launched, then the `after_run` listeners and shell hook. Best-effort — it
@@ -33,14 +33,20 @@ function sleep(ms, signal) {
33
33
  }
34
34
  /**
35
35
  * A run-env key is reserved when it names a conductor-provided core variable:
36
- * any `BB_*`, `WORKSPACE_ROOT`, or `TICKET_URL`. User `env_vars` may not
37
- * clobber these — the core vars always win (BB-99).
36
+ * any `BAKERS_*`, `WORKSPACE_ROOT`, or `TICKET_URL`. User `env_vars` may not
37
+ * clobber these — the core vars always win (BB-99). `BB_*` stays reserved: a
38
+ * retired name in the run env would make the agent's `bakers` refuse to start.
38
39
  */
39
40
  function isReservedEnvKey(key) {
40
- return (key.startsWith('BB_') || key === 'WORKSPACE_ROOT' || key === 'TICKET_URL');
41
+ return (key.startsWith('BAKERS_') ||
42
+ key.startsWith('BB_') ||
43
+ key === 'WORKSPACE_ROOT' ||
44
+ key === 'TICKET_URL');
41
45
  }
42
46
  /** A portable environment variable name. */
43
47
  const ENV_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
48
+ /** How long a run's transcript stays unchanged before its permission denials are reported. */
49
+ const STALL_QUIET_MS = 5 * 60_000;
44
50
  /**
45
51
  * What a failed listener is logged as: the error's class name, never its
46
52
  * message — listener text may carry an env value (BB-599).
@@ -153,12 +159,36 @@ function recordAfterCreateOutcome(file, worktreePath, ok) {
153
159
  // best-effort: a later dispatch simply re-runs after_create.
154
160
  }
155
161
  }
162
+ /**
163
+ * Run UUIDs this conductor resumed after a restart, beside its config file so
164
+ * a second restart fails a run instead of resuming it again.
165
+ * shortcut: entries are never pruned (a UUID per resumed run); prune on finalize if it ever grows.
166
+ */
167
+ function resumedStateFileOf(config) {
168
+ const file = config.config_path;
169
+ return join(dirname(file), `${basename(file, '.js')}.resumed.json`);
170
+ }
171
+ function loadResumed(file) {
172
+ try {
173
+ const v = JSON.parse(readFileSync(file, 'utf8'));
174
+ return Array.isArray(v) ? v : [];
175
+ }
176
+ catch {
177
+ return [];
178
+ }
179
+ }
180
+ /** A lost run the restart recovery fails instead of resuming; the message is the reason. */
181
+ class ResumeRefused extends Error {
182
+ }
183
+ /** A resume met a run that is no longer `running`: nothing to launch or fail. */
184
+ class RunClosed extends Error {
185
+ }
156
186
  function renderPrompt(template, values) {
157
187
  return template
158
188
  .replaceAll('{identifier}', values.identifier)
159
189
  .replaceAll('{state}', values.state)
160
- .replaceAll('{runUuid}', values.runUuid)
161
- .replaceAll('{ticketUuid}', values.ticketUuid);
190
+ .replaceAll('{run_uuid}', values.runUuid)
191
+ .replaceAll('{ticket_uuid}', values.ticketUuid);
162
192
  }
163
193
  /**
164
194
  * A conductor's registration payload, built from its config: what the engine
@@ -193,6 +223,8 @@ export class Conductor {
193
223
  runHook;
194
224
  readMachine;
195
225
  uuid = null;
226
+ /** Runs running at this process's first lost-run check whose pane lookup has not answered yet: resumed, not failed. */
227
+ recovering;
196
228
  /**
197
229
  * Frozen tickets seen on the last poll, by uuid, with the worktree their
198
230
  * hook ran in. Mirrored to `frozenStateFile` when one is given, so an
@@ -200,6 +232,10 @@ export class Conductor {
200
232
  * restart does not repeat `on_freeze`; loaded on the first observation.
201
233
  */
202
234
  frozenSeen = null;
235
+ /** Transcript mtime each active run was last checked for denials at. */
236
+ stallChecked = new Map();
237
+ /** Active runs already reported as blocked; never reported twice. */
238
+ stallReported = new Set();
203
239
  /** The addons with contract-2 inbox messages this conductor runs. */
204
240
  inboxAddons;
205
241
  /** The per-item work each tick enqueues. */
@@ -260,7 +296,7 @@ export class Conductor {
260
296
  *
261
297
  * Only `cmdStartForeground` calls this. `cmdPoll` and `cmdReap` also build a
262
298
  * Conductor and call start() + tick(), then exit; if they reported a pid,
263
- * every `bakers oven once` would overwrite the running conductor's pid
299
+ * every `bakers conductor once` would overwrite the running conductor's pid
264
300
  * with its own short-lived one and the next stop would signal a dead — or
265
301
  * recycled — process. Making the report opt-in means those two commands
266
302
  * cannot do so even by accident.
@@ -349,7 +385,7 @@ export class Conductor {
349
385
  this.logger.error({ conductorId: this.id }, line);
350
386
  }
351
387
  }
352
- /** One tick that also waits for its actions: `bakers oven once`, tests. */
388
+ /** One tick that also waits for its actions: `bakers conductor once`, tests. */
353
389
  async tick() {
354
390
  await this.produce();
355
391
  await this.queue.drain();
@@ -403,9 +439,11 @@ export class Conductor {
403
439
  }
404
440
  // A hung action blocks only its ticket's lane; make it visible.
405
441
  this.queue.warnOverdue(this.config.lease_seconds * 1000);
442
+ await this.step('lost', () => this.enqueueLostRuns());
406
443
  await this.step('finalize', () => this.enqueueFinalize());
407
444
  await this.step('reap', () => this.enqueueReap());
408
445
  await this.step('freeze', () => this.observeFreezes());
446
+ await this.step('stalls', () => this.observeStalls());
409
447
  await runInbox(this.remote, this.inboxAddons, this.id, this.logger, this.queue);
410
448
  // A run that cannot start its sandbox would only fail and count against
411
449
  // the retry cap; claim nothing until every enabled agent can start.
@@ -457,6 +495,122 @@ export class Conductor {
457
495
  : 'idle, nothing to claim');
458
496
  }
459
497
  }
498
+ /**
499
+ * Fails every running run whose terminal is gone: nobody executes it, and
500
+ * the server never expires a `running` run. Keyed off the durable active-run
501
+ * query, so a restarted conductor checks adopted runs on its first tick.
502
+ */
503
+ async enqueueLostRuns() {
504
+ if (!this.executor.runAlive)
505
+ return;
506
+ const runs = (await this.remote.fetchActiveRuns(this.id)).filter((r) => r.state === 'running');
507
+ this.recovering ??= new Set(runs.map((r) => r.runUuid));
508
+ for (const r of runs) {
509
+ this.queue.enqueue({
510
+ key: `lost:${r.runUuid}`,
511
+ lane: r.ticketUuid || r.runUuid,
512
+ run: () => this.lostOne(r),
513
+ });
514
+ }
515
+ }
516
+ /**
517
+ * Fails and reports one run when its terminal is gone; a failed lookup
518
+ * changes nothing. On a run's first answering lookup after a restart it
519
+ * resumes the run instead, when its agent and session allow.
520
+ */
521
+ async lostOne(r) {
522
+ let alive;
523
+ try {
524
+ alive = (await this.executor.runAlive?.(r.branchName, r.runId)) ?? true;
525
+ }
526
+ catch (err) {
527
+ this.logger.warn({ run: r.runUuid, err: String(err) }, 'pane lookup failed; run left active');
528
+ return;
529
+ }
530
+ const recovery = this.recovering?.delete(r.runUuid) ?? false;
531
+ if (alive)
532
+ return;
533
+ let refused;
534
+ try {
535
+ // The run may have ended normally since the snapshot.
536
+ if (!(await this.stillRunning(r.runUuid)))
537
+ return;
538
+ if (recovery) {
539
+ refused = await this.resumeLost(r);
540
+ if (refused === undefined)
541
+ return;
542
+ }
543
+ const gone = `herdr pane gone: ${this.executor.id} found no live terminal for run #${r.runId} (branch ${r.branchName})`;
544
+ const cause = refused ? `conductor restart: ${refused}; ${gone}` : gone;
545
+ // herdr may have restored the tab and restarted an agent in it; a fresh run would share the worktree.
546
+ await this.executor
547
+ .cleanupRun(r.branchName, r.runId)
548
+ .catch((err) => {
549
+ this.logger.warn({ run: r.runUuid, err: String(err) }, 'lost run tab not closed');
550
+ });
551
+ await this.remote.markFailed(r.runUuid, cause);
552
+ this.revokeRunTools(r.runUuid);
553
+ this.signalUi(r.worktreePath);
554
+ this.logger.warn({ run: r.runUuid }, cause);
555
+ }
556
+ catch (err) {
557
+ // A transient remote error must not cost the retry its resume or its restart reason.
558
+ if (recovery)
559
+ this.recovering?.add(r.runUuid);
560
+ this.logger.warn({ run: r.runUuid, err: String(err) }, 'lost run not marked failed; retried next tick');
561
+ return;
562
+ }
563
+ // Not retried: the run is no longer active, so a retry could only duplicate.
564
+ await this.lostComment(r, `was marked \`failed\`: its terminal pane is gone (\`${this.executor.id}\` found no live terminal on branch \`${r.branchName}\`), so nobody was executing it any more.${refused ? ` It could not be resumed after the conductor restart: ${refused}. The ticket gets a fresh run.` : ''}`);
565
+ }
566
+ async stillRunning(runUuid) {
567
+ return (await this.remote.fetchActiveRuns(this.id)).some((a) => a.runUuid === runUuid && a.state === 'running');
568
+ }
569
+ async lostComment(r, what) {
570
+ await this.remote
571
+ .publishTicketComment(r.ticketUuid, `Run #${r.runId} (\`${r.runUuid}\`) in state \`${r.stateAtStart}\` ${what}\n`)
572
+ .catch((err) => {
573
+ this.logger.warn({ run: r.runUuid, err: String(err) }, 'lost run comment failed');
574
+ });
575
+ }
576
+ /**
577
+ * Relaunches a lost run in its worktree with its agent's session resume.
578
+ * Returns undefined when resumed, else why it was not: the caller fails it.
579
+ */
580
+ async resumeLost(r) {
581
+ const file = resumedStateFileOf(this.config);
582
+ const resumed = loadResumed(file);
583
+ if (resumed.includes(r.runUuid))
584
+ return 'the run was already resumed once';
585
+ if (!r.worktreePath || !existsSync(r.worktreePath))
586
+ return `its worktree ${r.worktreePath || '(unrecorded)'} is gone`;
587
+ try {
588
+ // Recorded first: a resume that dies half-way must not be tried again.
589
+ mkdirSync(dirname(file), { recursive: true });
590
+ writeFileSync(file, `${JSON.stringify([...resumed, r.runUuid])}\n`);
591
+ await this.dispatch({
592
+ runUuid: r.runUuid,
593
+ runId: r.runId,
594
+ ticketUuid: r.ticketUuid,
595
+ stateAtStart: r.stateAtStart,
596
+ handler: r.stateAtStart,
597
+ }, {}, true);
598
+ }
599
+ catch (err) {
600
+ // A cancel during the launch makes the server reject it; that run is closed, not failed.
601
+ if (err instanceof RunClosed ||
602
+ !(await this.stillRunning(r.runUuid).catch(() => true))) {
603
+ this.logger.info({ run: r.runUuid }, 'lost run closed during its resume');
604
+ return undefined;
605
+ }
606
+ return err instanceof ResumeRefused
607
+ ? err.message
608
+ : `the resume launch failed: ${err instanceof Error ? err.message : String(err)}`;
609
+ }
610
+ this.logger.info({ run: r.runUuid }, 'lost run resumed after restart');
611
+ await this.lostComment(r, `was resumed after a conductor restart: its terminal pane was gone, so the agent continues its session in \`${r.worktreePath}\`.`);
612
+ return undefined;
613
+ }
460
614
  /**
461
615
  * One-shot finalisation: for each of this conductor's runs that is state in
462
616
  * (done, cancelled) but not yet closed, read the agent transcript from its
@@ -474,6 +628,107 @@ export class Conductor {
474
628
  });
475
629
  }
476
630
  }
631
+ /**
632
+ * A run a permission rule denied cannot ask anyone on an unattended box,
633
+ * so it stops. Once its transcript has been quiet for {@link STALL_QUIET_MS}
634
+ * and holds a denial, report it once. One stat per running run per tick;
635
+ * the transcript is read once per modification.
636
+ */
637
+ async observeStalls() {
638
+ const runs = await this.remote.fetchActiveRuns(this.id);
639
+ const live = new Set(runs.map((r) => r.runUuid));
640
+ for (const seen of [this.stallChecked, this.stallReported])
641
+ for (const id of seen.keys())
642
+ if (!live.has(id))
643
+ seen.delete(id);
644
+ for (const r of runs) {
645
+ if (r.state !== 'running' || !r.worktreePath)
646
+ continue;
647
+ if (this.stallReported.has(r.runUuid))
648
+ continue;
649
+ const agent = this.agentFor(r)?.agent;
650
+ if (!agent?.permissionDenials || !agent.runLogModified)
651
+ continue;
652
+ const identity = {
653
+ sessionId: r.runUuid,
654
+ attemptFamily: attemptFamily(r.runUuid),
655
+ };
656
+ let denied;
657
+ try {
658
+ const modified = await agent.runLogModified(r.worktreePath, identity);
659
+ if (modified === undefined ||
660
+ Date.now() - modified < STALL_QUIET_MS ||
661
+ this.stallChecked.get(r.runUuid) === modified)
662
+ continue;
663
+ denied = agent.permissionDenials(await agent.getRunLog(r.worktreePath, identity));
664
+ // Only a successful read counts: a stuck transcript never changes again.
665
+ this.stallChecked.set(r.runUuid, modified);
666
+ }
667
+ catch (err) {
668
+ this.logger.warn({ conductorId: this.id, run: r.runUuid, err }, 'could not read the run transcript for permission denials');
669
+ continue;
670
+ }
671
+ if (denied.length === 0)
672
+ continue;
673
+ this.stallReported.add(r.runUuid);
674
+ this.queue.enqueue({
675
+ key: `stall:${r.runUuid}`,
676
+ lane: r.ticketUuid || r.runUuid,
677
+ run: () => this.reportBlocked(r, denied),
678
+ });
679
+ }
680
+ }
681
+ /**
682
+ * The technical-problem note, then the error: the PM bot relays the newest
683
+ * comment of a frozen, labelled ticket. Cancelling lets finalisation stop
684
+ * the agent and keep its transcript.
685
+ */
686
+ async reportBlocked(r, denied) {
687
+ const site = this.remote.siteTools;
688
+ // Without site tools nothing reaches the ticket; a silent cancel would hide the run.
689
+ // Unmarked, the next tick with site tools reports it.
690
+ if (!site) {
691
+ this.stallReported.delete(r.runUuid);
692
+ this.stallChecked.delete(r.runUuid);
693
+ throw new Error('no site tools to report the blocked run');
694
+ }
695
+ this.logger.warn({ conductorId: this.id, run: r.runUuid, denied }, 'run blocked on a permission denial; reporting and cancelling it');
696
+ const call = async (name, args) => {
697
+ const result = await site.call(`tool_api__${name}`, args);
698
+ if (result?.isError)
699
+ throw new Error(`${name}: ${JSON.stringify(result?.content)}`);
700
+ };
701
+ const comment = (body) => call('bakers_comment_publish', {
702
+ ticket: r.ticketUuid,
703
+ type: 'comment',
704
+ body,
705
+ });
706
+ try {
707
+ await comment('# Technical problem\n\nPlease contact the developers.\n');
708
+ await comment([
709
+ '# Error',
710
+ '',
711
+ `The sandboxed run stopped: a permission rule denied an action it needed, and its transcript has not changed for ${STALL_QUIET_MS / 60_000} minutes. An allow rule for the action is missing from the agent's \`permissions\` settings. Add it, then unfreeze the ticket.`,
712
+ '',
713
+ 'Denied actions:',
714
+ '',
715
+ ...denied.map((action) => `- \`${action}\``),
716
+ '',
717
+ ].join('\n'));
718
+ await call('bakers_ticket_update', {
719
+ ticket: r.ticketUuid,
720
+ labels_add: ['technical problem'],
721
+ frozen: true,
722
+ });
723
+ }
724
+ finally {
725
+ // A stuck run is cancelled even when the report fails; the warning names the actions.
726
+ // shortcut: the reported mark lives in memory, so if this cancel fails a restarted
727
+ // conductor reports the run again; persist the mark if duplicates show up.
728
+ await this.remote.cancelRun(r.runUuid);
729
+ }
730
+ this.signalUi();
731
+ }
477
732
  /** Finalises one run; a failure is logged and retried next tick. */
478
733
  async finalizeOne(r) {
479
734
  try {
@@ -530,12 +785,16 @@ export class Conductor {
530
785
  this.logger.warn({ run: r.runUuid, err: String(err) }, 'run finalise failed');
531
786
  }
532
787
  }
788
+ /**
789
+ * The agent that actually ran: the persisted run.agent id, falling back to
790
+ * the first candidate for a run written before the field existed (empty id).
791
+ */
792
+ agentFor(r) {
793
+ return this.agents.find((a) => a.id === r.agent) ?? this.agents[0];
794
+ }
533
795
  /** Read the run's transcript and parse its footprint for the close write. */
534
796
  async captureRun(r) {
535
- // Route to the agent that actually ran (BB-144): the persisted
536
- // run.agent id, falling back to the first candidate for a run written
537
- // before the field existed (empty id).
538
- const resolved = this.agents.find((a) => a.id === r.agent) ?? this.agents[0];
797
+ const resolved = this.agentFor(r);
539
798
  if (!resolved) {
540
799
  throw new Error('no agent candidates configured for finalize');
541
800
  }
@@ -837,7 +1096,7 @@ export class Conductor {
837
1096
  * whose workspace still lingers (BB-89). Driven by the durable `cleaned_up`
838
1097
  * flag via {@link BbRemote.fetchUncleanedTickets}: every ticket the server
839
1098
  * has already closed but not yet cleaned. The SAME reconciliation runs on
840
- * every tick AND standalone as `bakers oven clean`, and the query is
1099
+ * every tick AND standalone as `bakers conductor clean`, and the query is
841
1100
  * scoped to THIS conductor (BB-121) — so it catches the orphans a
842
1101
  * live-tick-only path structurally cannot (the conductor was down when the
843
1102
  * ticket closed, or crashed mid-cleanup) for its OWN tickets. A foreign
@@ -1071,24 +1330,24 @@ export class Conductor {
1071
1330
  workspaceIds = ids.join(',');
1072
1331
  }
1073
1332
  catch (err) {
1074
- this.logger.warn({ ticket: t.identifier, err: String(err) }, 'could not resolve reachable workspaces for BB_WORKSPACE_IDS');
1333
+ this.logger.warn({ ticket: t.identifier, err: String(err) }, 'could not resolve reachable workspaces for BAKERS_WORKSPACE_IDS');
1075
1334
  }
1076
1335
  const core = {
1077
- BB_URL: this.config.site.base_url,
1078
- BB_ID: t.uuid,
1336
+ BAKERS_URL: this.config.site.base_url,
1337
+ BAKERS_ID: t.uuid,
1079
1338
  // BB-569: lets a launch wrapper key off the ticket and the run's
1080
1339
  // start state without parsing the prompt (addon-claude `measure`).
1081
- ...(t.identifier ? { BB_TICKET_IDENTIFIER: t.identifier } : {}),
1082
- ...(state ? { BB_STATE: state } : {}),
1083
- ...(runUuid ? { BB_RUN_UUID: runUuid } : {}),
1084
- BB_TUNNEL: (await this.currentTunnel()) ? '1' : '0',
1340
+ ...(t.identifier ? { BAKERS_TICKET_IDENTIFIER: t.identifier } : {}),
1341
+ ...(state ? { BAKERS_STATE: state } : {}),
1342
+ ...(runUuid ? { BAKERS_RUN_UUID: runUuid } : {}),
1343
+ BAKERS_TUNNEL: (await this.currentTunnel()) ? '1' : '0',
1085
1344
  WORKSPACE_ROOT: this.checkoutRoot,
1086
1345
  ...(t.issueUrl ? { TICKET_URL: t.issueUrl } : {}),
1087
- ...(t.projectName ? { BB_PROJECT: t.projectName } : {}),
1088
- ...(t.projectId ? { BB_PROJECT_ID: t.projectId } : {}),
1089
- ...(t.workspaceName ? { BB_WORKSPACE: t.workspaceName } : {}),
1090
- ...(t.workspaceId ? { BB_WORKSPACE_ID: t.workspaceId } : {}),
1091
- ...(workspaceIds ? { BB_WORKSPACE_IDS: workspaceIds } : {}),
1346
+ ...(t.projectName ? { BAKERS_PROJECT: t.projectName } : {}),
1347
+ ...(t.projectId ? { BAKERS_PROJECT_ID: t.projectId } : {}),
1348
+ ...(t.workspaceName ? { BAKERS_WORKSPACE: t.workspaceName } : {}),
1349
+ ...(t.workspaceId ? { BAKERS_WORKSPACE_ID: t.workspaceId } : {}),
1350
+ ...(workspaceIds ? { BAKERS_WORKSPACE_IDS: workspaceIds } : {}),
1092
1351
  };
1093
1352
  return resolveRunEnv(t.effectiveEnvVars, core, this.logger, {
1094
1353
  ticket: t.identifier,
@@ -1200,8 +1459,11 @@ export class Conductor {
1200
1459
  log();
1201
1460
  return { env: launch.env, args: launch.args };
1202
1461
  }
1203
- /** `at.worktree` is set once the workspace exists, so a failure can signal it. */
1204
- async dispatch(run, at = {}) {
1462
+ /**
1463
+ * `at.worktree` is set once the workspace exists, so a failure can signal it.
1464
+ * `resume`: continue the run's newest agent session instead of prompting afresh.
1465
+ */
1466
+ async dispatch(run, at = {}, resume = false) {
1205
1467
  const t = await this.remote.getTicket(run.ticketUuid);
1206
1468
  // Resolve the ticket alias and machine defaults, or the project selection hook.
1207
1469
  // Persist the package id below so finalize can choose its transcript parser.
@@ -1216,7 +1478,7 @@ export class Conductor {
1216
1478
  if (unavailable)
1217
1479
  throw new Error(unavailable);
1218
1480
  const baseRef = t.baseBranch ? `origin/${t.baseBranch}` : undefined;
1219
- // Resolve the run env once (per-ticket env_vars + core BB_* vars) and
1481
+ // Resolve the run env once (per-ticket env_vars + core BAKERS_* vars) and
1220
1482
  // inject it into BOTH the lifecycle hooks AND the agent run
1221
1483
  // env (BB-99). Reserved core keys always win; values may be sensitive so
1222
1484
  // only key names are ever logged.
@@ -1247,7 +1509,7 @@ export class Conductor {
1247
1509
  };
1248
1510
  const launch = { started: false };
1249
1511
  try {
1250
- await this.launch(run, t, chosen, ws, ctx, launch);
1512
+ await this.launch(run, t, chosen, ws, ctx, launch, resume);
1251
1513
  }
1252
1514
  catch (err) {
1253
1515
  await this.unwindDispatch(ctx, launch.started);
@@ -1258,8 +1520,11 @@ export class Conductor {
1258
1520
  * The part of a dispatch that can leave a sidecar or a worker behind
1259
1521
  * (BB-599): its caller unwinds it through `after_run` on any failure.
1260
1522
  */
1261
- async launch(run, t, chosen, ws, ctx, launch) {
1523
+ async launch(run, t, chosen, ws, ctx, launch, resume = false) {
1262
1524
  const env = ctx.env;
1525
+ const resumeSession = resume
1526
+ ? await this.resumableSession(chosen, ws.path, run.runUuid)
1527
+ : undefined;
1263
1528
  // Lifecycle hooks are conductor-owned + best-effort (BB-84): runHook never
1264
1529
  // throws, so neither call can abort dispatch or wedge a run in `claimed`.
1265
1530
  // `runSlot` runs the addon listeners first under the same rule (BB-599).
@@ -1378,12 +1643,19 @@ export class Conductor {
1378
1643
  // field's accepted formats and the PATCH would be rejected (review round
1379
1644
  // 4, Critical 1).
1380
1645
  const dispatchedAt = Math.floor(Date.now() / 1000);
1646
+ // A resumed run already is `running`; one closed meanwhile (cancelled) is not relaunched.
1647
+ if (resume && !(await this.stillRunning(run.runUuid)))
1648
+ throw new RunClosed();
1381
1649
  const tools = chosen.agent.withoutConductorTools
1382
1650
  ? undefined
1383
1651
  : this.issueRunTools(run.runUuid, { worktreePath: ws.path, ticket: t });
1384
1652
  const plugins = await this.installPlugins(chosen, t, run, ws.path);
1385
1653
  Object.assign(env, plugins.env);
1386
- const command = chosen.agent.launchCommand(prompt, identity, ws.path, tools ? { url: tools.url } : undefined, env, plugins.args);
1654
+ const command = resumeSession === undefined
1655
+ ? chosen.agent.launchCommand(prompt, identity, ws.path, tools ? { url: tools.url } : undefined, env, plugins.args)
1656
+ : chosen.agent.resumeCommand?.(resumeSession, ws.path, tools ? { url: tools.url } : undefined, env, plugins.args);
1657
+ if (command === undefined)
1658
+ throw new ResumeRefused(`agent ${chosen.id} cannot resume a session in this configuration`);
1387
1659
  // Read after launchCommand: a warning may depend on what this launch got.
1388
1660
  const warnings = chosen.agent.launchWarnings;
1389
1661
  if (warnings?.length) {
@@ -1443,6 +1715,20 @@ export class Conductor {
1443
1715
  });
1444
1716
  this.signalUi(ws.path);
1445
1717
  }
1718
+ /** The run's newest agent session, or why it cannot be resumed. */
1719
+ async resumableSession(chosen, worktree, runUuid) {
1720
+ if (!chosen.agent.resumeCommand || !chosen.agent.sessionExists)
1721
+ throw new ResumeRefused(`agent ${chosen.id} has no session resume`);
1722
+ let newest;
1723
+ for (const id of attemptFamily(runUuid)) {
1724
+ if (!(await chosen.agent.sessionExists(worktree, id)))
1725
+ break;
1726
+ newest = id;
1727
+ }
1728
+ if (newest === undefined)
1729
+ throw new ResumeRefused(`no agent session of the run in ${worktree}`);
1730
+ return newest;
1731
+ }
1446
1732
  /**
1447
1733
  * Stop what a failed dispatch started (BB-599): the worker if it was
1448
1734
  * launched, then the `after_run` listeners and shell hook. Best-effort — it
@@ -1504,7 +1790,7 @@ export class Conductor {
1504
1790
  }
1505
1791
  await this.queue.drain();
1506
1792
  // NB: the poll loop never writes status=offline itself. A graceful stop
1507
- // (`bakers oven stop`) writes offline directly server-side; a crash or
1793
+ // (`bakers conductor stop`) writes offline directly server-side; a crash or
1508
1794
  // hard-kill leaves a stale lease that the Drupal cron reaper flips to
1509
1795
  // offline (bb_core cron → ConductorReaper). Liveness is thus always
1510
1796
  // derived from status + last_seen/lease_expires_at, never from the loop.
@@ -18,7 +18,7 @@ export interface ToolServerEndpoint {
18
18
  }
19
19
  export interface ToolServerOptions {
20
20
  registry: ToolRegistry;
21
- /** `<BB_HOME>/conductors/<conductor_id>.json`; absent: no operator access. */
21
+ /** `<BAKERS_HOME>/conductors/<conductor_id>.json`; absent: no operator access. */
22
22
  endpointFile?: string;
23
23
  /** The operator may only name worktrees below this directory. */
24
24
  workspaceRoot?: string;