@bakers-build/addon-herdr 0.6.1-next.6 → 0.6.1-next.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,42 +1,13 @@
1
1
  import { resolve } from 'node:path';
2
2
  import { loadInstructions, runBranchGit, } from '@bakers-build/addon-workspace-git';
3
3
  import { exec } from '@bakers-build/core';
4
- import { renderTemplate } from './config.js';
5
- import { applyPaneLayout, isRecord, parseJson } from './pane-layout.js';
4
+ import { isRecord, parseJson } from './pane-layout.js';
6
5
  import { deriveHerdrRoot } from './root-anchor.js';
7
6
  import { resolveBaseRef } from './shared.js';
8
- /** Max `{title}` length substituted into the overview **tab** label (BB-374). */
9
- export const OPEN_TAB_TITLE_MAX = 30;
10
- /** Cap overview-tab `{title}` and append `...` when truncated. */
11
- export function truncateOpenTabTitle(title) {
12
- if (title.length <= OPEN_TAB_TITLE_MAX) {
13
- return title;
14
- }
15
- return `${title.slice(0, OPEN_TAB_TITLE_MAX)}...`;
16
- }
17
- /** Default overview tab chrome (BB-374) — always-visible tab bar identity. */
18
- export const DEFAULT_OPEN_TAB_LABEL = '{identifier} · {title}';
19
- /** Default overview pane/panel label template (BB-374). */
20
- export const DEFAULT_OPEN_PANEL_LABEL = '{identifier} · {title}';
21
- /**
22
- * The shipped default open layout (BB-234): a fresh worktree's initial pane
23
- * renders the ticket it belongs to instead of an anonymous shell prompt.
24
- *
25
- * It lives in **code, not config**, because a default each repo has to opt into
26
- * would leave the defect in place for every other consumer of this addon; the
27
- * addon already ships opinionated defaults of this kind (`BUILTIN_DEFAULTS` in
28
- * `./config.js`), and `bakers ui` is a command of the very host that ships it.
29
- *
30
- * `open: {}` is the documented opt-out back to the pre-BB-234 bare tab, so
31
- * the default is not a one-way door.
32
- */
33
- export const DEFAULT_OPEN_LAYOUT = {
34
- command: 'bakers ui --ticket {identifier}',
35
- tabLabel: DEFAULT_OPEN_TAB_LABEL,
36
- panelLabel: DEFAULT_OPEN_PANEL_LABEL,
37
- };
7
+ import { removeHerdrWorktree } from './worktrees.js';
38
8
  const defaultExec = (args) => exec('herdr', args);
39
9
  const defaultGitExec = (args) => exec('git', args);
10
+ const defaultRunGit = (args, cwd) => exec('git', args, { cwd });
40
11
  const noopLogger = {
41
12
  debug() { },
42
13
  info() { },
@@ -75,24 +46,6 @@ function parseWorktreePath(output, command) {
75
46
  }
76
47
  return path;
77
48
  }
78
- /**
79
- * Parse `worktree create` → root pane id (+ optional tab id for BB-374
80
- * overview tab rename). Sibling of {@link parseWorktreePath}. Returns null when
81
- * the create JSON carries no pane id, so the open-layout caller can skip
82
- * silently rather than throw (best-effort).
83
- */
84
- function parseWorktreeRootPane(output) {
85
- const parsed = parseJson(output, 'worktree create');
86
- if (!isRecord(parsed) || !isRecord(parsed.result))
87
- return null;
88
- const result = parsed.result;
89
- const paneId = result.root_pane?.pane_id;
90
- if (typeof paneId !== 'string' || !paneId)
91
- return null;
92
- const tabIdRaw = result.root_pane?.tab_id ?? result.tab?.tab_id;
93
- const tabId = typeof tabIdRaw === 'string' && tabIdRaw ? tabIdRaw : undefined;
94
- return tabId !== undefined ? { paneId, tabId } : { paneId };
95
- }
96
49
  /** Git-safe branch validation: safe ref chars only, no leading dot, no `..`. */
97
50
  export function validateBranch(branch) {
98
51
  if (!/^[A-Za-z0-9._/-]+$/.test(branch) ||
@@ -107,30 +60,23 @@ export class HerdrWorkspace {
107
60
  execGit;
108
61
  root;
109
62
  worktreeDir;
110
- open;
111
63
  logger;
112
- /**
113
- * Root panes captured by a FRESH `ensure` create, keyed by worktree path,
114
- * awaiting {@link applyOpenLayout} (BB-237). One-shot: consumed on apply.
115
- * Optional `tabId` powers the BB-374 overview tab rename.
116
- */
117
- pendingRootPanes = new Map();
64
+ runGit;
118
65
  constructor(options) {
119
66
  this.options = options;
120
67
  this.execHerdr = options.execHerdr ?? defaultExec;
121
68
  this.execGit = options.execGit ?? defaultGitExec;
122
69
  this.root = resolve(options.root);
123
70
  this.worktreeDir = options.worktreeDir ?? '.bakers-worktrees';
124
- // `??`, not `||`: an explicit `open: {}` must survive as the opt-out.
125
- this.open = options.open ?? DEFAULT_OPEN_LAYOUT;
71
+ this.runGit = options.runGit ?? defaultRunGit;
126
72
  this.logger = options.logger ?? noopLogger;
127
73
  }
128
74
  /**
129
75
  * Ensure the branch's worktree + herdr workspace exist.
130
76
  *
131
- * `_identifier` is unused HERE: the worktree is located by branch, and since
132
- * BB-237 the open layout — the one thing that consumed the identifier, to
133
- * render `{identifier}` (BB-234) — is applied by {@link applyOpenLayout},
77
+ * `_identifier` is unused HERE: the worktree is located by branch, and the
78
+ * open layout — the one thing that consumed the identifier, to render
79
+ * `{identifier}` (BB-234) — is applied by `HerdrExecutor.openWorkspace`,
134
80
  * which takes it on its own `ctx`. The parameter stays because it is the
135
81
  * `BbWorkspace.ensure` contract position (the git workspace does use it).
136
82
  * It is still taken as-passed rather than parsed back out of `branch`, which
@@ -204,19 +150,9 @@ export class HerdrWorkspace {
204
150
  '--json',
205
151
  ]);
206
152
  const path = parseWorktreePath(createOutput, 'worktree create');
207
- // BB-237: CAPTURE the fresh root pane here, but do NOT lay it out yet.
208
- // The layout's startup command names the bakers CLI, which the `after_create`
209
- // hook builds — and that hook runs after `ensure()` returns. Applying the
210
- // layout here fired the command before its binary existed, which is why the
211
- // pane command needed a sentinel wait loop. The conductor now calls
212
- // `applyOpenLayout` after the hook; a create with no root pane in its output
213
- // stores nothing, so the layout is a no-op exactly as before.
214
- const pending = parseWorktreeRootPane(createOutput);
215
- if (pending) {
216
- this.pendingRootPanes.set(path, pending);
217
- }
218
- // The `after_create` hook is run by the executor (BB-84), not here — the
219
- // workspace only reports that it created a fresh worktree.
153
+ // The `after_create` hook and the open layout run after `ensure()` returns
154
+ // (conductor, then `HerdrExecutor.openWorkspace`) — the workspace only
155
+ // reports that it created a fresh worktree.
220
156
  return {
221
157
  path,
222
158
  instructions: loadInstructions(path),
@@ -225,109 +161,17 @@ export class HerdrWorkspace {
225
161
  };
226
162
  }
227
163
  /**
228
- * Apply the open layout to the root pane captured by the most recent
229
- * {@link ensure} create for `path` — by default (BB-234) the ticket's
230
- * `bakers ui` deep link, so the tab shows the ticket instead of a bare shell.
231
- * The pane's cwd is the worktree checkout, passed explicitly on the splits
232
- * (the root pane's cwd is already the checkout).
233
- *
234
- * BB-374 then renames the overview tab (`{identifier} · {title}` with title
235
- * capped at {@link OPEN_TAB_TITLE_MAX}) and root pane (full
236
- * `{identifier} · {title}`) — fresh-create only, same gate as the layout.
237
- *
238
- * NO stored pane ⇒ silent no-op. That is the reused-worktree case: `ensure`
239
- * took the reuse branch, there is no fresh root pane, and re-applying would
240
- * start a duplicate editor process on reattach (BB-139). The capture is
241
- * one-shot — consumed here — so a repeat call cannot double-apply and the map
242
- * cannot grow without bound.
243
- *
244
- * Best-effort — mirrors the `fetchBaseRef` pattern: a broken layout is logged
245
- * and swallowed so a startup-command failure can NEVER wedge dispatch.
164
+ * Tear down the branch's worktree and its herdr workspace
165
+ * (`herdr worktree remove --force`); a worktree herdr no longer tracks is
166
+ * torn down with git alone. See {@link removeHerdrWorktree}.
246
167
  */
247
- async applyOpenLayout(path, ctx) {
248
- const pending = this.pendingRootPanes.get(path);
249
- if (!pending) {
250
- return;
251
- }
252
- this.pendingRootPanes.delete(path);
253
- const { paneId: rootPaneId } = pending;
254
- try {
255
- // Render the ROOT command here (spec D2). `applyPaneLayout` types its
256
- // root command verbatim for the executor's brace-bearing env-prefixed
257
- // agent command, so templating it there would corrupt that; the split
258
- // commands it already renders from the same `vars`.
259
- const vars = {
260
- identifier: ctx.identifier,
261
- branch: ctx.branch,
262
- title: ctx.title,
263
- worktreePath: path,
264
- };
265
- const layout = {
266
- ...this.open,
267
- ...(this.open.command !== undefined
268
- ? { command: renderTemplate(this.open.command, vars) }
269
- : {}),
270
- };
271
- await applyPaneLayout(this.execHerdr, rootPaneId, layout, path, vars);
272
- await this.applyOverviewLabels(rootPaneId, pending.tabId, vars);
273
- }
274
- catch (err) {
275
- this.logger.warn({ branch: ctx.branch, worktree: path, err: String(err) }, 'herdr open-layout failed (best-effort, ignored)');
276
- }
277
- }
278
- /**
279
- * Best-effort overview tab + pane renames (BB-374). Skipped for the
280
- * `open: {}` opt-out. A missing create-time tab id falls back to `pane get`.
281
- */
282
- async applyOverviewLabels(rootPaneId, createTabId, vars) {
283
- const emptyOptOut = this.open.command === undefined &&
284
- !this.open.panes?.length &&
285
- this.open.tabLabel === undefined &&
286
- this.open.panelLabel === undefined;
287
- if (emptyOptOut) {
288
- return;
289
- }
290
- // Tab bar is always visible; cap title length and mark truncation with
291
- // `...`. Pane/panel label keeps the full title for pane borders.
292
- const tabVars = {
293
- ...vars,
294
- title: truncateOpenTabTitle(vars.title ?? ''),
295
- };
296
- const tabLabel = renderTemplate(this.open.tabLabel ?? DEFAULT_OPEN_TAB_LABEL, tabVars);
297
- const panelLabel = renderTemplate(this.open.panelLabel ?? DEFAULT_OPEN_PANEL_LABEL, vars);
298
- let tabId = createTabId;
299
- if (!tabId) {
300
- try {
301
- tabId = (await this.resolveTabIdForPane(rootPaneId)) ?? undefined;
302
- }
303
- catch (err) {
304
- this.logger.warn({ paneId: rootPaneId, err: String(err) }, 'herdr overview tab id lookup failed (best-effort, ignored)');
305
- }
306
- }
307
- if (tabId) {
308
- try {
309
- await this.execHerdr(['tab', 'rename', tabId, tabLabel]);
310
- }
311
- catch (err) {
312
- this.logger.warn({ tabId, err: String(err) }, 'herdr overview tab rename failed (best-effort, ignored)');
313
- }
314
- }
315
- try {
316
- await this.execHerdr(['pane', 'rename', rootPaneId, panelLabel]);
317
- }
318
- catch (err) {
319
- this.logger.warn({ paneId: rootPaneId, err: String(err) }, 'herdr overview pane rename failed (best-effort, ignored)');
320
- }
321
- }
322
- /** `pane get <id>` → `result.pane.tab_id` when present. */
323
- async resolveTabIdForPane(paneId) {
324
- const output = await this.execHerdr(['pane', 'get', paneId, '--json']);
325
- const parsed = parseJson(output, 'pane get');
326
- const tabId = isRecord(parsed)
327
- ? parsed.result?.pane
328
- ?.tab_id
329
- : undefined;
330
- return typeof tabId === 'string' && tabId ? tabId : null;
168
+ remove(branch, worktreePath) {
169
+ return removeHerdrWorktree({
170
+ root: this.root,
171
+ execHerdr: this.execHerdr,
172
+ runGit: this.runGit,
173
+ logger: this.logger,
174
+ }, branch, worktreePath);
331
175
  }
332
176
  }
333
177
  export function herdrWorkspace(opts = {}) {
@@ -335,9 +179,8 @@ export function herdrWorkspace(opts = {}) {
335
179
  kind: 'workspace',
336
180
  id: 'herdr',
337
181
  requiredModules: [],
338
- // BB-234: `deps` carries the conductor logger, so the best-effort
339
- // open-layout failure is actually logged instead of vanishing into the noop
340
- // logger. Optional per the contract — absent, the noop default stays.
182
+ // `deps` carries the conductor logger, so teardown warnings are actually
183
+ // logged. Optional per the contract — absent, the noop default stays.
341
184
  async createWorkspace(config, deps) {
342
185
  const root = await deriveHerdrRoot(config.config_path, {
343
186
  ...(opts.root !== undefined ? { override: opts.root } : {}),
@@ -347,7 +190,6 @@ export function herdrWorkspace(opts = {}) {
347
190
  root,
348
191
  ...(opts.worktreeDir ? { worktreeDir: opts.worktreeDir } : {}),
349
192
  ...(opts.baseBranch ? { baseBranch: opts.baseBranch } : {}),
350
- ...(opts.open ? { open: opts.open } : {}),
351
193
  ...(opts.execHerdr ? { execHerdr: opts.execHerdr } : {}),
352
194
  ...(opts.autoSetupMerge ? { autoSetupMerge: true } : {}),
353
195
  ...(deps?.logger ? { logger: deps.logger } : {}),
@@ -0,0 +1,67 @@
1
+ import { type WorktreeGitExec } from '@bakers-build/addon-workspace-git';
2
+ import type { WorktreeTeardown } from '@bakers-build/conductor/contract';
3
+ import type { ConductorLogger } from '@bakers-build/core';
4
+ import { type HerdrExec } from './pane-layout.js';
5
+ export interface WorktreeEntry {
6
+ /** herdr's reported git branch — null when the worktree HEAD is detached. */
7
+ branch: string | null;
8
+ path: string;
9
+ open_workspace_id?: string;
10
+ }
11
+ export declare function parseWorktreeList(output: string): WorktreeEntry[];
12
+ /** Normalise a worktree path for comparison (strip trailing slashes). */
13
+ export declare function normPath(path: string): string;
14
+ /**
15
+ * Resolve a worktree entry, preferring the stable `worktreePath` over `branch`.
16
+ * The checked-out branch is mutable (the coding agent may rename/switch it), so
17
+ * the path — deterministic and identifier-derived — is the reliable key. Fall
18
+ * back to a branch match so a missing/renamed path still resolves. Returns null
19
+ * only when neither key matches any listed worktree.
20
+ */
21
+ export declare function resolveWorktreeEntry(entries: WorktreeEntry[], branch: string, worktreePath?: string): WorktreeEntry | null;
22
+ /**
23
+ * List worktrees, ALWAYS anchored to the configured parent repo root
24
+ * (BB-211). `herdr worktree list` is machine-global, but run WITHOUT
25
+ * `--cwd` it resolves herdr's own ambient (previously selected / persisted /
26
+ * process / shell / daemon) repository context. When a preceding
27
+ * `bakers-cleanup-*` integration test selected then deleted a
28
+ * `/tmp/bakers-cleanup-*` repo, that stale context survives and the unanchored
29
+ * list exits (`cannot change to '/tmp/bakers-cleanup-…'`), aborting dispatch.
30
+ * Anchoring every list with `--cwd root` makes listing independent of that
31
+ * ambient context. This is the SINGLE choke point for all executor and
32
+ * teardown `worktree list` call paths — {@link HerdrWorkspace.ensure} anchors
33
+ * identically. The `--cwd` is only omitted when no root is configured
34
+ * (rootless test callers).
35
+ *
36
+ * On a herdr failure it throws an error naming the explicit configured root
37
+ * and the operation (AC-9) instead of surfacing herdr's raw stale-context
38
+ * message, so a future context failure is diagnosable.
39
+ */
40
+ export declare function listWorktrees(execHerdr: HerdrExec, root: string | undefined): Promise<WorktreeEntry[]>;
41
+ /** What the herdr worktree teardown needs. */
42
+ export interface HerdrTeardownDeps {
43
+ /** The parent repo root; absent only for rootless test callers. */
44
+ root?: string;
45
+ execHerdr: HerdrExec;
46
+ runGit: WorktreeGitExec;
47
+ logger: ConductorLogger;
48
+ }
49
+ /**
50
+ * Tear down a ticket's entire worktree (git worktree + hosted workspace).
51
+ * `herdr worktree remove` is keyed by an open workspace id, so resolve the
52
+ * worktree first — by its stable `worktreePath`, falling back to `branch`
53
+ * (see {@link resolveWorktreeEntry}): if its workspace is already open use
54
+ * that id; otherwise open the on-disk worktree to obtain one.
55
+ *
56
+ * `herdr worktree list` is machine-global — it enumerates every repo's
57
+ * worktrees on the host, most of which are not ours. So a no-match does NOT
58
+ * mean "error"; it means herdr no longer tracks this ticket's worktree. Then
59
+ * the teardown is git's alone: {@link removeGitWorktree} asks before acting
60
+ * (BB-293) and removes git-awarely, so no `.git/worktrees/<name>` metadata is
61
+ * orphaned (BB-141 RC-1).
62
+ *
63
+ * Reports what the teardown DID (BB-293): `removed`, `already_absent`, or
64
+ * `unverified` when nothing was resolvable, the directory survived, or a
65
+ * focus switch could not be made safely — the reaper then retries.
66
+ */
67
+ export declare function removeHerdrWorktree(deps: HerdrTeardownDeps, branch: string, worktreePath?: string): Promise<WorktreeTeardown>;
@@ -0,0 +1,223 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { removeGitWorktree, restoreWritable, } from '@bakers-build/addon-workspace-git';
3
+ import { isRecord, parseJson } from './pane-layout.js';
4
+ import { parseWorkspaceList } from './workspace-list.js';
5
+ export function parseWorktreeList(output) {
6
+ const parsed = parseJson(output, 'worktree list');
7
+ const worktrees = isRecord(parsed)
8
+ ? parsed.result?.worktrees
9
+ : undefined;
10
+ if (!Array.isArray(worktrees)) {
11
+ return [];
12
+ }
13
+ // Key on `path` only — herdr reports `branch: null` for a detached HEAD, and
14
+ // the branch is mutable anyway (see resolveWorktreeEntry). Dropping such
15
+ // entries is exactly the BB-114 defect: the worktree becomes invisible to
16
+ // a path lookup.
17
+ return worktrees
18
+ .filter(isRecord)
19
+ .filter((w) => typeof w.path === 'string')
20
+ .map((w) => ({
21
+ branch: typeof w.branch === 'string' ? w.branch : null,
22
+ path: w.path,
23
+ ...(typeof w.open_workspace_id === 'string' && w.open_workspace_id
24
+ ? { open_workspace_id: w.open_workspace_id }
25
+ : {}),
26
+ }));
27
+ }
28
+ /** Normalise a worktree path for comparison (strip trailing slashes). */
29
+ export function normPath(path) {
30
+ return path.replace(/\/+$/, '');
31
+ }
32
+ /**
33
+ * Resolve a worktree entry, preferring the stable `worktreePath` over `branch`.
34
+ * The checked-out branch is mutable (the coding agent may rename/switch it), so
35
+ * the path — deterministic and identifier-derived — is the reliable key. Fall
36
+ * back to a branch match so a missing/renamed path still resolves. Returns null
37
+ * only when neither key matches any listed worktree.
38
+ */
39
+ export function resolveWorktreeEntry(entries, branch, worktreePath) {
40
+ if (worktreePath) {
41
+ const want = normPath(worktreePath);
42
+ const byPath = entries.find((e) => normPath(e.path) === want);
43
+ if (byPath) {
44
+ return byPath;
45
+ }
46
+ }
47
+ return entries.find((e) => e.branch === branch) ?? null;
48
+ }
49
+ /**
50
+ * List worktrees, ALWAYS anchored to the configured parent repo root
51
+ * (BB-211). `herdr worktree list` is machine-global, but run WITHOUT
52
+ * `--cwd` it resolves herdr's own ambient (previously selected / persisted /
53
+ * process / shell / daemon) repository context. When a preceding
54
+ * `bakers-cleanup-*` integration test selected then deleted a
55
+ * `/tmp/bakers-cleanup-*` repo, that stale context survives and the unanchored
56
+ * list exits (`cannot change to '/tmp/bakers-cleanup-…'`), aborting dispatch.
57
+ * Anchoring every list with `--cwd root` makes listing independent of that
58
+ * ambient context. This is the SINGLE choke point for all executor and
59
+ * teardown `worktree list` call paths — {@link HerdrWorkspace.ensure} anchors
60
+ * identically. The `--cwd` is only omitted when no root is configured
61
+ * (rootless test callers).
62
+ *
63
+ * On a herdr failure it throws an error naming the explicit configured root
64
+ * and the operation (AC-9) instead of surfacing herdr's raw stale-context
65
+ * message, so a future context failure is diagnosable.
66
+ */
67
+ export async function listWorktrees(execHerdr, root) {
68
+ const args = ['worktree', 'list', ...(root ? ['--cwd', root] : []), '--json'];
69
+ let output;
70
+ try {
71
+ output = await execHerdr(args);
72
+ }
73
+ catch (err) {
74
+ throw new Error(`herdr worktree list failed for configured root ${root ?? '<unset>'}: ${String(err)}`);
75
+ }
76
+ return parseWorktreeList(output);
77
+ }
78
+ /**
79
+ * BB-166 focus guard. herdr's `worktree remove` deletes the ticket
80
+ * worktree's on-disk directory; if that workspace is the CURRENTLY FOCUSED
81
+ * one, the interactive client is left in a now-deleted `cwd` and herdr spawns
82
+ * a stray empty workspace for the dead path. So before the remove, if the
83
+ * target workspace is focused, switch focus to the main-checkout (non-linked)
84
+ * workspace of the SAME repo. A background reap of a non-focused worktree
85
+ * (or one herdr no longer lists) focuses nothing.
86
+ *
87
+ * Returns whether it is SAFE to proceed with the remove: `false` when a
88
+ * required focus switch cannot be resolved or verified — the caller then
89
+ * aborts (returns `unverified`) so the reaper retries later, rather than
90
+ * deleting the focused path out from under the user.
91
+ */
92
+ async function ensureFocusSafeToRemove(deps, workspaceId) {
93
+ const workspaces = parseWorkspaceList(await deps.execHerdr(['workspace', 'list']));
94
+ const target = workspaces.find((w) => w.workspaceId === workspaceId);
95
+ // Not focused (or not listed) → removing it strands no client.
96
+ if (!target?.focused) {
97
+ return true;
98
+ }
99
+ // Focused: resolve the main-checkout workspace for the SAME repo — the
100
+ // non-linked workspace whose repo_root matches the target's (falling back
101
+ // to the configured parent root when herdr reports no repo_root).
102
+ const anchor = target.repoRoot ?? deps.root ?? null;
103
+ const parent = anchor === null
104
+ ? undefined
105
+ : workspaces.find((w) => w.workspaceId !== workspaceId &&
106
+ !w.isLinkedWorktree &&
107
+ w.repoRoot !== null &&
108
+ normPath(w.repoRoot) === normPath(anchor));
109
+ // No safe target → do NOT delete the focused path; retry later.
110
+ if (!parent) {
111
+ return false;
112
+ }
113
+ try {
114
+ await deps.execHerdr(['workspace', 'focus', parent.workspaceId]);
115
+ }
116
+ catch {
117
+ return false;
118
+ }
119
+ // Verify the switch actually took before deleting the (was-focused) dir.
120
+ const after = parseWorkspaceList(await deps.execHerdr(['workspace', 'list']));
121
+ const parentNow = after.find((w) => w.workspaceId === parent.workspaceId);
122
+ const targetNow = after.find((w) => w.workspaceId === workspaceId);
123
+ return parentNow?.focused === true && targetNow?.focused !== true;
124
+ }
125
+ /**
126
+ * Tear down a ticket's entire worktree (git worktree + hosted workspace).
127
+ * `herdr worktree remove` is keyed by an open workspace id, so resolve the
128
+ * worktree first — by its stable `worktreePath`, falling back to `branch`
129
+ * (see {@link resolveWorktreeEntry}): if its workspace is already open use
130
+ * that id; otherwise open the on-disk worktree to obtain one.
131
+ *
132
+ * `herdr worktree list` is machine-global — it enumerates every repo's
133
+ * worktrees on the host, most of which are not ours. So a no-match does NOT
134
+ * mean "error"; it means herdr no longer tracks this ticket's worktree. Then
135
+ * the teardown is git's alone: {@link removeGitWorktree} asks before acting
136
+ * (BB-293) and removes git-awarely, so no `.git/worktrees/<name>` metadata is
137
+ * orphaned (BB-141 RC-1).
138
+ *
139
+ * Reports what the teardown DID (BB-293): `removed`, `already_absent`, or
140
+ * `unverified` when nothing was resolvable, the directory survived, or a
141
+ * focus switch could not be made safely — the reaper then retries.
142
+ */
143
+ export async function removeHerdrWorktree(deps, branch, worktreePath) {
144
+ const { root, execHerdr, logger } = deps;
145
+ // BB-468 / BB-228: a ticket whose recorded `worktreePath` IS the configured
146
+ // parent-repo root is refused before either branch below is reached — the
147
+ // herdr-tracked path would retry `not_linked_worktree` forever, and the git
148
+ // path would reclaim the MAIN CHECKOUT.
149
+ if (root && worktreePath && normPath(worktreePath) === normPath(root)) {
150
+ logger.warn({ branch, worktreePath, root }, 'refusing to tear down the main checkout');
151
+ return 'unverified';
152
+ }
153
+ const entry = resolveWorktreeEntry(await listWorktrees(execHerdr, root), branch, worktreePath);
154
+ if (!entry) {
155
+ // herdr no longer tracks it. herdr still tracking the worktree is itself
156
+ // evidence that something is there to release, which is why the git probe
157
+ // governs only this lost-track path.
158
+ return removeGitWorktree(root, branch, worktreePath, deps.runGit, logger);
159
+ }
160
+ let workspaceId = entry.open_workspace_id ?? null;
161
+ if (!workspaceId) {
162
+ // Reattach from the PARENT repo root, never the linked worktree itself:
163
+ // herdr rejects an open whose --cwd is a linked worktree with
164
+ // `linked_worktree_source` ("New and open actions start from the repo
165
+ // parent workspace"), which then yields no workspace id and the remove
166
+ // never runs. Fall back to the linked path only when no root is
167
+ // configured (keeps the old behaviour for rootless test callers).
168
+ await execHerdr([
169
+ 'worktree',
170
+ 'open',
171
+ '--cwd',
172
+ root ?? entry.path,
173
+ '--branch',
174
+ // entry.branch is null for a detached HEAD; fall back to the ticket
175
+ // branch so `open` still gets a branch arg.
176
+ entry.branch ?? branch,
177
+ '--no-focus',
178
+ '--json',
179
+ ]);
180
+ // Re-resolve by the same keys — open flips the entry's workspace id.
181
+ const reopened = resolveWorktreeEntry(await listWorktrees(execHerdr, root), branch, worktreePath);
182
+ workspaceId = reopened?.open_workspace_id ?? null;
183
+ if (!workspaceId) {
184
+ throw new Error(`herdr worktree open did not yield a workspace id for path ${entry.path} (branch ${entry.branch})`);
185
+ }
186
+ }
187
+ // BB-166: before deleting the worktree's directory, if its workspace is
188
+ // the focused one, move focus to the main checkout — else the client is
189
+ // stranded in a deleted cwd. If a needed focus switch can't be made safely,
190
+ // abort UNVERIFIED so the reaper retries rather than stranding the user.
191
+ if (!(await ensureFocusSafeToRemove(deps, workspaceId))) {
192
+ return 'unverified';
193
+ }
194
+ // Drupal hardens web/sites/default (0555) and settings.php/.htaccess (0444);
195
+ // herdr's remove performs the actual unlink and would hit EACCES on those
196
+ // read-only dirs. Restore owner-write on the on-disk worktree first.
197
+ restoreWritable(entry.path);
198
+ await execHerdr([
199
+ 'worktree',
200
+ 'remove',
201
+ '--workspace',
202
+ workspaceId,
203
+ '--force',
204
+ '--json',
205
+ ]);
206
+ // BB-166: verify the directory is actually gone on disk. If it survived,
207
+ // report the teardown UNVERIFIED so the reaper retries instead of falsely
208
+ // flagging the ticket cleaned.
209
+ if (existsSync(entry.path)) {
210
+ return 'unverified';
211
+ }
212
+ // Sweep any orphaned `.git/worktrees/<name>` admin entries at the parent
213
+ // root (this teardown's and any pre-existing prunable ones — BB-141).
214
+ if (root) {
215
+ try {
216
+ await deps.runGit(['worktree', 'prune'], root);
217
+ }
218
+ catch {
219
+ // best-effort — pruning is a sweep, never the teardown's success gate
220
+ }
221
+ }
222
+ return 'removed';
223
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bakers-build/addon-herdr",
3
- "version": "0.6.1-next.6",
3
+ "version": "0.6.1-next.8",
4
4
  "description": "bakers.build herdr integration: spawn executor + per-ticket worktree workspace.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -21,14 +21,14 @@
21
21
  "directory": "bakers-cli/addons/herdr"
22
22
  },
23
23
  "dependencies": {
24
- "@bakers-build/addon-workspace-git": "^0.6.1-next.6"
24
+ "@bakers-build/addon-workspace-git": "^0.6.1-next.8"
25
25
  },
26
26
  "peerDependencies": {
27
- "@bakers-build/conductor": "^0.6.1-next.6",
28
- "@bakers-build/core": "^0.6.1-next.6"
27
+ "@bakers-build/conductor": "^0.6.1-next.8",
28
+ "@bakers-build/core": "^0.6.1-next.8"
29
29
  },
30
30
  "bakersBuild": {
31
- "commit": "12b97ff4aa2422d69dab286141f3234609f32351",
31
+ "commit": "a39a1b099521005460e4f9d9534aa7935ed88e91",
32
32
  "channel": "next"
33
33
  }
34
34
  }
@@ -1,6 +0,0 @@
1
- import type { HerdrHost } from '@bakers-build/conductor/contract';
2
- /**
3
- * Close every herdr workspace whose label equals the conductor handle, then
4
- * create one and `exec env` the pane command so herdr auto-closes on exit.
5
- */
6
- export declare const herdrProcessHost: HerdrHost;
@@ -1,46 +0,0 @@
1
- import { exec } from '@bakers-build/core';
2
- import { isRecord, parseJson } from './pane-layout.js';
3
- import { parseWorkspaceList } from './workspace-list.js';
4
- function parseWorkspaceCreate(output) {
5
- const parsed = parseJson(output, 'workspace create');
6
- const paneId = isRecord(parsed)
7
- ? parsed.result
8
- ?.root_pane?.pane_id
9
- : undefined;
10
- if (typeof paneId !== 'string' || paneId === '') {
11
- throw new Error('herdr workspace create returned no pane id');
12
- }
13
- return paneId;
14
- }
15
- /**
16
- * Close every herdr workspace whose label equals the conductor handle, then
17
- * create one and `exec env` the pane command so herdr auto-closes on exit.
18
- */
19
- export const herdrProcessHost = {
20
- async spawn(label, cwd, cmd) {
21
- const listed = parseWorkspaceList(await exec('herdr', ['workspace', 'list']));
22
- for (const ws of listed) {
23
- if (ws.label === label) {
24
- try {
25
- await exec('herdr', ['workspace', 'close', ws.workspaceId]);
26
- }
27
- catch {
28
- // herdr may already have auto-closed it after a previous stop
29
- }
30
- }
31
- }
32
- const paneId = parseWorkspaceCreate(await exec('herdr', [
33
- 'workspace',
34
- 'create',
35
- '--cwd',
36
- cwd,
37
- '--label',
38
- label,
39
- '--no-focus',
40
- ]));
41
- // `exec env` replaces the pane's login shell (fish-safe VAR=value form)
42
- // so herdr closes the workspace when the conductor exits by any path.
43
- // `env` needs a real `bakers` executable on PATH.
44
- await exec('herdr', ['pane', 'run', paneId, `exec env ${cmd}`]);
45
- },
46
- };