@bakers-build/addon-herdr 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.
package/dist/src/index.js CHANGED
@@ -1,91 +1,28 @@
1
- import { existsSync, rmSync } from 'node:fs';
1
+ import { rmSync } from 'node:fs';
2
2
  import { exec, shellQuote, slugify } from '@bakers-build/core';
3
3
  import { renderTemplate, resolveStateConfig, } from './config.js';
4
- import { forceRemoveDir, restoreWritable } from './fs.js';
5
4
  import { watchLaunch, writeLaunchScript, } from './launch-script.js';
5
+ import { applyOpenLayout, DEFAULT_OPEN_LAYOUT, isEmptyLayout, parseFirstPane, parseRootPane, } from './open-layout.js';
6
6
  import { applyPaneLayout, isRecord, parseJson, } from './pane-layout.js';
7
7
  import { AGENT_SHELL_ENV, envArgs } from './panes.js';
8
8
  import { deriveHerdrRoot } from './root-anchor.js';
9
- import { parseWorkspaceList } from './workspace-list.js';
9
+ import { listWorktrees, resolveWorktreeEntry, } from './worktrees.js';
10
+ export { DEFAULT_OPEN_LAYOUT } from './open-layout.js';
10
11
  export { envArgs } from './panes.js';
11
12
  // BB-139: the herdr workspace lives in the same package now (the separate
12
13
  // @bakers-build/addon-herdr-workspace was merged in). The package DEFAULT export
13
14
  // stays the executor (below); herdrWorkspace + HerdrWorkspace are named exports.
14
- export { herdrProcessHost } from './process-host.js';
15
15
  export { HerdrWorkspace, herdrWorkspace, } from './workspace.js';
16
16
  export { parseWorkspaceList, } from './workspace-list.js';
17
17
  async function defaultExec(args, opts) {
18
18
  return exec('herdr', args, opts);
19
19
  }
20
- /** Default git runner: real `git` in the given cwd (the parent repo root). */
21
- const defaultGitRunner = (args, cwd) => exec('git', args, { cwd });
22
- /**
23
- * Parse `git worktree list --porcelain`. Records are blank-line separated; each
24
- * has a `worktree <path>` line and, for an attached HEAD, a `branch
25
- * refs/heads/<branch>` line (a detached HEAD has none). `prunable <reason>`
26
- * entries (a `.git/worktrees/<name>` admin entry whose dir has vanished) still
27
- * carry their `worktree <path>` line, so they parse too — the caller decides
28
- * what to do with a path no longer on disk.
29
- */
30
- function parseGitWorktreePorcelain(output) {
31
- const entries = [];
32
- let path = null;
33
- let branch = null;
34
- const flush = () => {
35
- if (path) {
36
- entries.push({ path, branch });
37
- }
38
- path = null;
39
- branch = null;
40
- };
41
- for (const line of output.split('\n')) {
42
- if (line.startsWith('worktree ')) {
43
- flush(); // a new record begins — commit the previous one
44
- path = line.slice('worktree '.length).trim();
45
- }
46
- else if (line.startsWith('branch ')) {
47
- branch = line
48
- .slice('branch '.length)
49
- .trim()
50
- .replace(/^refs\/heads\//, '');
51
- }
52
- }
53
- flush();
54
- return entries;
55
- }
56
- /** Default hook runner: `sh -c <command>` in the worktree — fails honestly. */
57
- const defaultShellRunner = async (command, cwd, env) => {
58
- await exec('sh', ['-c', command], { cwd, ...(env ? { env } : {}) });
59
- };
60
20
  const noopLogger = {
61
21
  debug() { },
62
22
  info() { },
63
23
  warn() { },
64
24
  error() { },
65
25
  };
66
- function parseWorktreeList(output) {
67
- const parsed = parseJson(output, 'worktree list');
68
- const worktrees = isRecord(parsed)
69
- ? parsed.result?.worktrees
70
- : undefined;
71
- if (!Array.isArray(worktrees)) {
72
- return [];
73
- }
74
- // Key on `path` only — herdr reports `branch: null` for a detached HEAD, and
75
- // the branch is mutable anyway (see resolveWorktreeEntry). Dropping such
76
- // entries is exactly the BB-114 defect: the worktree becomes invisible to
77
- // a path lookup.
78
- return worktrees
79
- .filter(isRecord)
80
- .filter((w) => typeof w.path === 'string')
81
- .map((w) => ({
82
- branch: typeof w.branch === 'string' ? w.branch : null,
83
- path: w.path,
84
- ...(typeof w.open_workspace_id === 'string' && w.open_workspace_id
85
- ? { open_workspace_id: w.open_workspace_id }
86
- : {}),
87
- }));
88
- }
89
26
  /**
90
27
  * Extract the open workspace id from `herdr worktree open`'s own JSON. herdr
91
28
  * returns it in the result envelope under any of these keys (herdr 0.7.x):
@@ -150,104 +87,22 @@ function parseTabCreate(output) {
150
87
  }
151
88
  return { paneId, tabId };
152
89
  }
153
- /** Normalise a worktree path for comparison (strip trailing slashes). */
154
- function normPath(path) {
155
- return path.replace(/\/+$/, '');
156
- }
157
- /**
158
- * Resolve a worktree entry, preferring the stable `worktreePath` over `branch`.
159
- * The checked-out branch is mutable (the coding agent may rename/switch it), so
160
- * the path — deterministic and identifier-derived — is the reliable key. Fall
161
- * back to a branch match so a missing/renamed path still resolves. Returns null
162
- * only when neither key matches any listed worktree.
163
- */
164
- function resolveWorktreeEntry(entries, branch, worktreePath) {
165
- if (worktreePath) {
166
- const want = normPath(worktreePath);
167
- const byPath = entries.find((e) => normPath(e.path) === want);
168
- if (byPath) {
169
- return byPath;
170
- }
171
- }
172
- return entries.find((e) => e.branch === branch) ?? null;
173
- }
174
90
  export class HerdrExecutor {
175
91
  options;
176
92
  execHerdr;
177
93
  logger;
178
- runShell;
179
- runGit;
180
94
  id = 'herdr';
181
- constructor(options, execHerdr = defaultExec, logger = noopLogger, runShell = defaultShellRunner, runGit = defaultGitRunner) {
95
+ constructor(options, execHerdr = defaultExec, logger = noopLogger) {
182
96
  this.options = options;
183
97
  this.execHerdr = execHerdr;
184
98
  this.logger = logger;
185
- this.runShell = runShell;
186
- this.runGit = runGit;
187
99
  }
188
100
  capabilities() {
189
101
  return { persistent: true };
190
102
  }
191
- /**
192
- * Run the lifecycle hook `name` best-effort — the single catch point for all
193
- * lifecycle hooks (see {@link BbExecutor.runHook}). No configured command →
194
- * silent no-op. A failing command → log loudly (hook + worktree + ticket +
195
- * err) and return. NEVER throws, so a hook failure can't abort dispatch or
196
- * wedge a run.
197
- *
198
- * BB-237: it also RETURNS what happened ({@link HookResult}). Not throwing
199
- * kept a hook from wedging a run, but swallowing the outcome entirely left the
200
- * caller unable to tell a provisioned worktree from a broken one — so an agent
201
- * was dispatched into a worktree whose bootstrap had aborted, with nothing but
202
- * a log line (which, on a TTY, went nowhere) to say so.
203
- */
204
- async runHook(name, cwd, ctx, env) {
205
- const command = this.options.hooks?.[name];
206
- if (!command) {
207
- return { hook: name, ran: false, ok: true };
208
- }
209
- try {
210
- await this.runShell(command, cwd, env);
211
- return { hook: name, ran: true, ok: true };
212
- }
213
- catch (err) {
214
- this.logger.error({ hook: name, worktree: cwd, ticket: ctx.ticket, err: String(err) }, 'lifecycle hook failed');
215
- return { hook: name, ran: true, ok: false, error: String(err) };
216
- }
217
- }
218
- /**
219
- * List worktrees, ALWAYS anchored to the configured parent repo root
220
- * (BB-211). `herdr worktree list` is machine-global, but run WITHOUT
221
- * `--cwd` it resolves herdr's own ambient (previously selected / persisted /
222
- * process / shell / daemon) repository context. When a preceding
223
- * `bakers-cleanup-*` integration test selected then deleted a
224
- * `/tmp/bakers-cleanup-*` repo, that stale context survives and the unanchored
225
- * list exits (`cannot change to '/tmp/bakers-cleanup-…'`), aborting dispatch.
226
- * Anchoring every list with `--cwd this.options.root` makes listing
227
- * independent of that ambient context. This is the SINGLE choke point for
228
- * all executor `worktree list` call paths — the sibling
229
- * {@link HerdrWorkspace.ensure} anchors identically. The `--cwd` is only
230
- * omitted when no root is configured (rootless test callers).
231
- *
232
- * On a herdr failure it throws an error naming the explicit configured root
233
- * and the operation (AC-9) instead of surfacing herdr's raw stale-context
234
- * message, so a future context failure is diagnosable.
235
- */
236
- async listWorktrees() {
237
- const args = [
238
- 'worktree',
239
- 'list',
240
- ...(this.options.root ? ['--cwd', this.options.root] : []),
241
- '--json',
242
- ];
243
- let output;
244
- try {
245
- output = await this.execHerdr(args);
246
- }
247
- catch (err) {
248
- throw new Error(`herdr worktree list failed for configured root ${this.options.root ?? '<unset>'}: ${String(err)}`);
249
- }
250
- return parseWorktreeList(output);
103
+ /** List worktrees anchored to the parent repo root (see {@link listWorktrees}). */
104
+ listWorktrees() {
105
+ return listWorktrees(this.execHerdr, this.options.root);
251
106
  }
252
107
  /**
253
108
  * Find the worktree entry (path + open_workspace_id) for a branch via
@@ -277,336 +132,52 @@ export class HerdrExecutor {
277
132
  return (resolveWorktreeEntry(entries, branch, worktreePath)?.open_workspace_id ??
278
133
  null);
279
134
  }
280
- /** Parent repo root for git worktree admin ops (falls back to `fallback`). */
281
- gitRoot(fallback) {
282
- return this.options.root ?? fallback;
283
- }
284
135
  /**
285
- * Sweep orphaned `.git/worktrees/<name>` admin entries at the parent repo
286
- * root — the ones whose on-disk dir has vanished (BB-141: they show up as
287
- * `prunable` in `git worktree list`). Best-effort: a prune failure must never
288
- * fail teardown.
136
+ * Lay out a freshly created worktree's herdr workspace with the `open`
137
+ * layout (BB-139/BB-234) — after `after_create`, which builds what the layout
138
+ * command may name (BB-237). The worktree may come from any workspace: its
139
+ * herdr workspace is found by path (falling back to `branch`), or opened from
140
+ * the parent repo root when none is open yet. Best-effort: nothing resolvable
141
+ * is a silent no-op, a failure is logged and swallowed.
289
142
  */
290
- async pruneWorktrees(root) {
291
- try {
292
- await this.runGit(['worktree', 'prune'], root);
293
- }
294
- catch {
295
- // best-effort — pruning is a sweep, never the teardown's success gate
296
- }
297
- }
298
- /**
299
- * Remove an on-disk worktree GIT-AWARELY (BB-141 RC-1). The old fallback
300
- * raw-`rm`'d the directory and left the parent repo's `.git/worktrees/<name>`
301
- * admin entry behind → a `prunable` orphan. This:
302
- * 1. restores owner-write (Drupal hardens web/sites/default 0555 +
303
- * settings.php 0444 — chmod-restorable by the owning user, no sudo);
304
- * 2. `git worktree remove --force <path>` from the PARENT repo root, which
305
- * unlinks the directory AND drops the `.git/worktrees/<name>` entry —
306
- * but ONLY when the path really is a registered worktree (BB-293):
307
- * against an unregistered path git exits 128 and the shared exec helper
308
- * logs `ERROR: exec failed` for a condition this code expects and
309
- * handles. The guard lives here rather than at the caller because this
310
- * method has a second call site (the path resolved via
311
- * {@link findGitWorktree});
312
- * 3. guarantees the directory is gone (a raw force-remove) in case git
313
- * refused or was skipped — a no-op if git already removed it;
314
- * 4. prunes the repo so any now-stale admin entry is swept.
315
- *
316
- * Returns whether the directory is gone afterwards. A reclaim that cannot
317
- * remove it REPORTS instead of throwing (BB-293, spec D5): the raw EACCES
318
- * used to propagate all the way out of {@link removeWorktree} and reach the
319
- * reaper as an opaque exception.
320
- */
321
- async gitAwareRemove(path, registered) {
322
- restoreWritable(path);
323
- const root = this.gitRoot(path);
324
- if (registered) {
325
- try {
326
- await this.runGit(['worktree', 'remove', '--force', path], root);
327
- }
328
- catch (err) {
329
- // Registered yet refused — genuinely unexpected. Say so, then reclaim
330
- // the directory directly below.
331
- this.logger.warn({ path, err: String(err) }, 'git worktree remove failed on a registered worktree');
332
- }
333
- }
334
- if (existsSync(path)) {
335
- try {
336
- forceRemoveDir(path);
337
- }
338
- catch (err) {
339
- // BB-293 (spec D5): a leftover we cannot unlink — most likely
340
- // foreign-owned (a container wrote it under another uid), which chmod
341
- // cannot repair. Name the failing step; the reaper retries.
342
- this.logger.warn({ path, err: String(err) }, 'worktree directory reclaim failed');
343
- return false;
344
- }
143
+ async openWorkspace(path, ctx) {
144
+ // `??`, not `||`: an explicit `open: {}` must survive as the opt-out.
145
+ const open = this.options.open ?? DEFAULT_OPEN_LAYOUT;
146
+ if (isEmptyLayout(open)) {
147
+ return;
345
148
  }
346
- await this.pruneWorktrees(root);
347
- return true;
348
- }
349
- /**
350
- * When herdr has lost track of a worktree and its `worktreePath` was never
351
- * persisted, the PARENT repo's `git worktree list` still knows it (BB-141
352
- * RC-2 — the ~28 never-touched leftovers). Resolve the lost worktree's on-disk
353
- * path there, preferring an exact `worktreePath` match, then a branch match;
354
- * never the main worktree. Returns null when nothing matches. Best-effort: a
355
- * git failure resolves to null.
356
- *
357
- * `cwd` is only where git is RUN. The main worktree is excluded by git's own
358
- * porcelain ordering (it is always the first record) rather than by comparing
359
- * against `cwd`, because the two coincide only when a parent root is
360
- * configured. Without one the probe falls back to running git inside the
361
- * worktree itself, and a `path !== cwd` filter then dropped the very entry
362
- * being asked about — so `registered: true` was unreachable for a rootless
363
- * executor (BB-293 review, finding 1). The configured root is excluded too,
364
- * belt and braces, so a caller that anchors elsewhere still never resolves the
365
- * main checkout as a ticket worktree.
366
- */
367
- async findGitWorktree(cwd, branch, worktreePath) {
368
- let output;
149
+ let root = null;
369
150
  try {
370
- output = await this.runGit(['worktree', 'list', '--porcelain'], cwd);
371
- }
372
- catch {
373
- return null;
374
- }
375
- const mainRoot = this.options.root;
376
- const candidates = parseGitWorktreePorcelain(output).filter((e, i) => i > 0 && (!mainRoot || normPath(e.path) !== normPath(mainRoot)));
377
- if (worktreePath) {
378
- const want = normPath(worktreePath);
379
- const byPath = candidates.find((e) => normPath(e.path) === want);
380
- if (byPath) {
381
- return byPath.path;
151
+ const entry = resolveWorktreeEntry(await this.listWorktrees(), ctx.branch, path);
152
+ if (entry?.open_workspace_id) {
153
+ root = parseFirstPane(await this.execHerdr([
154
+ 'pane',
155
+ 'list',
156
+ '--workspace',
157
+ entry.open_workspace_id,
158
+ ]));
382
159
  }
383
- }
384
- return candidates.find((e) => e.branch === branch)?.path ?? null;
385
- }
386
- /**
387
- * Ask — passively — whether this worktree still exists, in BOTH dimensions
388
- * that can come apart (BB-293): git's registration, and the directory on
389
- * disk. The reported failure was exactly a case where they disagreed — the
390
- * directory was there, the registration was not — so a single-dimension
391
- * check cannot decide what to do.
392
- *
393
- * Passive by construction: it writes nothing, calls no herdr, and NEVER
394
- * throws. A git failure yields `registered: false`, degrading the verdict to
395
- * the on-disk answer rather than failing the teardown.
396
- *
397
- * The persisted `worktreePath` is the stable key and wins when given;
398
- * `registered` then describes THAT path, never a branch match pointing
399
- * somewhere else (the checked-out branch is mutable — BB-114).
400
- *
401
- * git is run at the configured parent root when there is one, else inside the
402
- * worktree itself — `git worktree list` enumerates the whole repo from any of
403
- * its worktrees, so the rootless answer is the same list.
404
- */
405
- async probeWorktree(branch, worktreePath) {
406
- const cwd = this.options.root ?? worktreePath ?? null;
407
- const gitPath = cwd
408
- ? await this.findGitWorktree(cwd, branch, worktreePath)
409
- : null;
410
- const path = worktreePath ?? gitPath;
411
- const registered = gitPath !== null && path !== null && normPath(gitPath) === normPath(path);
412
- return { registered, onDisk: path !== null && existsSync(path), path };
413
- }
414
- /**
415
- * BB-166 focus guard. herdr's `worktree remove` deletes the ticket
416
- * worktree's on-disk directory; if that workspace is the CURRENTLY FOCUSED
417
- * one, the interactive client is left in a now-deleted `cwd` and herdr spawns
418
- * a stray empty workspace for the dead path. So before the remove, if the
419
- * target workspace is focused, switch focus to the main-checkout (non-linked)
420
- * workspace of the SAME repo. A background reap of a non-focused worktree
421
- * (or one herdr no longer lists) focuses nothing.
422
- *
423
- * Returns whether it is SAFE to proceed with the remove: `false` when a
424
- * required focus switch cannot be resolved or verified — the caller then
425
- * aborts (returns `false` → `cleaned_up=0`) so the reaper retries later,
426
- * rather than deleting the focused path out from under the user.
427
- */
428
- async ensureFocusSafeToRemove(workspaceId) {
429
- const workspaces = parseWorkspaceList(await this.execHerdr(['workspace', 'list']));
430
- const target = workspaces.find((w) => w.workspaceId === workspaceId);
431
- // Not focused (or not listed) → removing it strands no client.
432
- if (!target?.focused) {
433
- return true;
434
- }
435
- // Focused: resolve the main-checkout workspace for the SAME repo — the
436
- // non-linked workspace whose repo_root matches the target's (falling back
437
- // to the configured parent root when herdr reports no repo_root).
438
- const anchor = target.repoRoot ?? this.options.root ?? null;
439
- const parent = anchor === null
440
- ? undefined
441
- : workspaces.find((w) => w.workspaceId !== workspaceId &&
442
- !w.isLinkedWorktree &&
443
- w.repoRoot !== null &&
444
- normPath(w.repoRoot) === normPath(anchor));
445
- // No safe target → do NOT delete the focused path; retry later.
446
- if (!parent) {
447
- return false;
448
- }
449
- try {
450
- await this.execHerdr(['workspace', 'focus', parent.workspaceId]);
451
- }
452
- catch {
453
- return false;
454
- }
455
- // Verify the switch actually took before deleting the (was-focused) dir.
456
- const after = parseWorkspaceList(await this.execHerdr(['workspace', 'list']));
457
- const parentNow = after.find((w) => w.workspaceId === parent.workspaceId);
458
- const targetNow = after.find((w) => w.workspaceId === workspaceId);
459
- return parentNow?.focused === true && targetNow?.focused !== true;
460
- }
461
- /**
462
- * Tear down a ticket's entire worktree (git worktree + hosted workspace).
463
- * `herdr worktree remove` is keyed by an open workspace id, so resolve the
464
- * worktree first — by its stable `worktreePath`, falling back to `branch`
465
- * (see {@link resolveWorktreeEntry}): if its workspace is already open use
466
- * that id; otherwise open the on-disk worktree to obtain one (mirrors
467
- * startRun's open-if-needed).
468
- *
469
- * `herdr worktree list` is machine-global — it enumerates every repo's
470
- * worktrees on the host, most of which are not ours. So a no-match does NOT
471
- * mean "error"; it means herdr no longer tracks this ticket's worktree. When
472
- * herdr has lost track, teardown is resolved off git itself (never a foreign
473
- * worktree), git-awarely so no `.git/worktrees/<name>` metadata is orphaned
474
- * (BB-141 RC-1). Since BB-293 that resolution starts by ASKING — a passive
475
- * {@link probeWorktree} reads both dimensions of existence and the four cases
476
- * branch explicitly:
477
- * - neither registered nor on disk → nothing to do at all;
478
- * - registered but gone from disk → sweep the prunable admin entry;
479
- * - on disk but not registered → reclaim the directory, WITHOUT asking git
480
- * to remove a worktree it does not know (the bogus `ERROR: exec failed`);
481
- * - both → reclaim it git-awarely, `git worktree remove` included.
482
- * A path that resolves in NEITHER dimension is not "absent" — it is
483
- * unresolved, and still reported `unverified` (BB-141 RC-2).
484
- *
485
- * Reports what the teardown DID (BB-293): `removed` when the worktree is
486
- * gone because this host removed it (or reclaimed an on-disk orphan, or swept
487
- * the prunable admin entry it left behind), `already_absent` when a RESOLVED
488
- * worktree existed in neither dimension, and `unverified` ONLY when nothing
489
- * was resolvable or the directory could not be reclaimed — the reaper then
490
- * leaves the ticket on its work list for a later retry instead of falsely
491
- * flagging it cleaned (BB-141 RC-2).
492
- */
493
- async removeWorktree(branch, worktreePath) {
494
- // BB-468 / BB-228 (superseded MR !258, trigger folded in here): a
495
- // ticket whose recorded `worktreePath` IS the configured parent-repo root
496
- // must be refused rather than acted on. BB-293 already excludes the main
497
- // checkout on the git side (`findGitWorktree` drops porcelain record 0 and
498
- // the configured root), but neither `resolveWorktreeEntry` (herdr-tracked
499
- // path) nor the probe fallback below carried the same filter, leaving two
500
- // live branches: herdr tracks the workspace → `herdr worktree remove
501
- // --force` throws `not_linked_worktree`, caught by the reaper and retried
502
- // forever; herdr does NOT track it → the probe resolves `worktreePath`
503
- // itself (unfiltered), `registered: false`, `onDisk: true`, and
504
- // `gitAwareRemove` calls `forceRemoveDir` on the MAIN CHECKOUT. Refusing
505
- // here, before either branch is reached, closes both without touching the
506
- // git-side exclusion or the executor's `unverified`/`already_absent`
507
- // contract for every other path.
508
- if (this.options.root && worktreePath) {
509
- const root = normPath(this.options.root);
510
- if (normPath(worktreePath) === root) {
511
- this.logger.warn({ branch, worktreePath, root: this.options.root }, 'refusing to tear down the main checkout');
512
- return 'unverified';
160
+ else {
161
+ root = parseRootPane(await this.execHerdr([
162
+ 'worktree',
163
+ 'open',
164
+ '--cwd',
165
+ this.options.root ?? path,
166
+ '--branch',
167
+ ctx.branch,
168
+ '--no-focus',
169
+ '--json',
170
+ ]), 'worktree open');
513
171
  }
514
172
  }
515
- const entries = await this.listWorktrees();
516
- const entry = resolveWorktreeEntry(entries, branch, worktreePath);
517
- if (!entry) {
518
- // herdr no longer tracks it. BB-293: ask before acting. An
519
- // already-absent worktree is a FINISHED teardown, not a failure to retry
520
- // — and running `git worktree remove` against an unregistered path is
521
- // what produced the bogus `ERROR: exec failed` (git exits 128 on an
522
- // expected, handled condition). herdr still tracking the worktree is
523
- // itself evidence that something is there to release, which is why the
524
- // probe governs only this lost-track path and the tracked path below
525
- // keeps its behaviour unchanged.
526
- const probe = await this.probeWorktree(branch, worktreePath);
527
- if (probe.path) {
528
- if (!probe.onDisk) {
529
- if (!probe.registered) {
530
- this.logger.info({ branch, worktreePath: probe.path }, 'worktree already absent — nothing to tear down');
531
- return 'already_absent';
532
- }
533
- // A prunable admin entry whose directory has vanished: the metadata
534
- // sweep IS the teardown here (BB-141).
535
- await this.pruneWorktrees(this.gitRoot(probe.path));
536
- return 'removed';
537
- }
538
- return (await this.gitAwareRemove(probe.path, probe.registered))
539
- ? 'removed'
540
- : 'unverified';
541
- }
542
- // Nothing resolvable in either dimension — the path was never persisted
543
- // and git does not know the branch either. Sweep pre-existing orphans,
544
- // then report the teardown UNVERIFIED so the reaper retries rather than
545
- // falsely cleaning (BB-141 RC-2). NOT `already_absent`: absence can
546
- // only be claimed about a worktree that was actually located.
547
- if (this.options.root) {
548
- await this.pruneWorktrees(this.options.root);
549
- }
550
- return 'unverified';
551
- }
552
- let workspaceId = entry.open_workspace_id ?? null;
553
- if (!workspaceId) {
554
- // Reattach from the PARENT repo root, never the linked worktree itself:
555
- // herdr rejects an open whose --cwd is a linked worktree with
556
- // `linked_worktree_source` ("New and open actions start from the repo
557
- // parent workspace"), which then yields no workspace id and the remove
558
- // never runs. Fall back to the linked path only when no root is
559
- // configured (keeps the old behaviour for rootless test callers).
560
- await this.execHerdr([
561
- 'worktree',
562
- 'open',
563
- '--cwd',
564
- this.options.root ?? entry.path,
565
- '--branch',
566
- // entry.branch is null for a detached HEAD; fall back to the ticket
567
- // branch so `open` still gets a branch arg.
568
- entry.branch ?? branch,
569
- '--no-focus',
570
- '--json',
571
- ]);
572
- // Re-resolve by the same keys — open flips the entry's workspace id.
573
- const reopened = resolveWorktreeEntry(await this.listWorktrees(), branch, worktreePath);
574
- workspaceId = reopened?.open_workspace_id ?? null;
575
- if (!workspaceId) {
576
- throw new Error(`herdr worktree open did not yield a workspace id for path ${entry.path} (branch ${entry.branch})`);
577
- }
578
- }
579
- // BB-166: before deleting the worktree's directory, if its workspace is
580
- // the focused one, move focus to the main checkout — else the client is
581
- // stranded in a deleted cwd. If a needed focus switch can't be made safely,
582
- // abort UNVERIFIED so the reaper retries rather than stranding the user.
583
- if (!(await this.ensureFocusSafeToRemove(workspaceId))) {
584
- return 'unverified';
585
- }
586
- // Drupal hardens web/sites/default (0555) and settings.php/.htaccess (0444);
587
- // herdr's remove performs the actual unlink and would hit EACCES on those
588
- // read-only dirs. Restore owner-write on the on-disk worktree first.
589
- restoreWritable(entry.path);
590
- await this.execHerdr([
591
- 'worktree',
592
- 'remove',
593
- '--workspace',
594
- workspaceId,
595
- '--force',
596
- '--json',
597
- ]);
598
- // BB-166: verify the directory is actually gone on disk. If it survived,
599
- // report the teardown UNVERIFIED (false) so the reaper retries instead of
600
- // falsely flagging the ticket cleaned.
601
- if (existsSync(entry.path)) {
602
- return 'unverified';
173
+ catch (err) {
174
+ this.logger.warn({ branch: ctx.branch, worktree: path, err: String(err) }, 'herdr open-layout failed (best-effort, ignored)');
175
+ return;
603
176
  }
604
- // Sweep any orphaned `.git/worktrees/<name>` admin entries at the parent
605
- // root (this teardown's and any pre-existing prunable ones — BB-141).
606
- if (this.options.root) {
607
- await this.pruneWorktrees(this.options.root);
177
+ if (!root) {
178
+ return;
608
179
  }
609
- return 'removed';
180
+ await applyOpenLayout(this.execHerdr, this.logger, open, root, path, ctx);
610
181
  }
611
182
  async startRun(input) {
612
183
  const branchName = input.ticket.branchName;
@@ -623,7 +194,7 @@ export class HerdrExecutor {
623
194
  // open actions start from the repo parent workspace"), so passing
624
195
  // input.workspacePath (the linked path) makes every first dispatch of a
625
196
  // closed-on-disk worktree fail — the run is released and re-claimed in a
626
- // loop. Mirrors removeWorktree's reattach. Fall back to the linked path
197
+ // loop. Mirrors the teardown's reattach. Fall back to the linked path
627
198
  // only when no root is configured (rootless test callers).
628
199
  if (!workspaceId) {
629
200
  const openOutput = await this.execHerdr([
@@ -739,8 +310,7 @@ export class HerdrExecutor {
739
310
  * tab and any non-run tab in the same workspace are left untouched, and a
740
311
  * missing match is a quiet no-op. Best-effort: a failing close is swallowed.
741
312
  * No `/exit`/C-c and no `(done)` rename — the matched tab simply goes away.
742
- * The branch worktree is untouched (that is the reap/{@link removeWorktree}
743
- * lifecycle).
313
+ * The branch worktree is untouched (that is `HerdrWorkspace.remove`).
744
314
  */
745
315
  async cleanupRun(branch, runId) {
746
316
  const workspaceId = await this.findWorkspaceByBranch(branch);
@@ -780,20 +350,22 @@ export function herdrExecutor(options = {}) {
780
350
  id: 'herdr',
781
351
  requiredModules: [],
782
352
  async createExecutor(config, deps) {
353
+ // Hooks used to ride on this addon's options; now only the conductor runs
354
+ // them, so a leftover would drop silently. Fail loudly instead.
355
+ if (options.hooks !== undefined) {
356
+ throw new Error("@bakers-build/addon-herdr no longer takes `with.hooks`: move them to the conductor config's top-level `hooks`");
357
+ }
783
358
  // Derive the parent repo root via the single shared anchor (BB-177) so
784
- // removeWorktree / worktree open reattach from the main clone, not the
785
- // linked worktree — identical derivation to the sibling herdrWorkspace.
359
+ // worktree open reattaches from the main clone, not the linked worktree
360
+ // — identical derivation to the sibling herdrWorkspace.
786
361
  const root = await deriveHerdrRoot(config.config_path, {
787
362
  ...(options.root !== undefined ? { override: options.root } : {}),
788
363
  ...(options.execGit ? { execGit: options.execGit } : {}),
789
364
  });
790
- // Lifecycle hooks are top-level config (BB-84); the executor runs them
791
- // best-effort through its injected logger.
792
365
  return new HerdrExecutor({
793
366
  command: options.command ?? 'claude',
794
367
  root,
795
- ...(options.hooks ? { hooks: options.hooks } : {}),
796
- ...(config.hooks ? { hooks: config.hooks } : {}),
368
+ ...(options.open ? { open: options.open } : {}),
797
369
  ...(options.default ? { default: options.default } : {}),
798
370
  ...(options.states ? { states: options.states } : {}),
799
371
  ...(options.launchWatch ? { launchWatch: options.launchWatch } : {}),