@bakers-build/addon-herdr 0.6.1-next.5 → 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.
@@ -1,43 +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 { herdrAgentHost } from './agents.js';
5
- import { renderTemplate } from './config.js';
6
- import { applyPaneLayout, isRecord, parseJson } from './pane-layout.js';
4
+ import { isRecord, parseJson } from './pane-layout.js';
7
5
  import { deriveHerdrRoot } from './root-anchor.js';
8
6
  import { resolveBaseRef } from './shared.js';
9
- /** Max `{title}` length substituted into the overview **tab** label (BB-374). */
10
- export const OPEN_TAB_TITLE_MAX = 30;
11
- /** Cap overview-tab `{title}` and append `...` when truncated. */
12
- export function truncateOpenTabTitle(title) {
13
- if (title.length <= OPEN_TAB_TITLE_MAX) {
14
- return title;
15
- }
16
- return `${title.slice(0, OPEN_TAB_TITLE_MAX)}...`;
17
- }
18
- /** Default overview tab chrome (BB-374) — always-visible tab bar identity. */
19
- export const DEFAULT_OPEN_TAB_LABEL = '{identifier} · {title}';
20
- /** Default overview pane/panel label template (BB-374). */
21
- export const DEFAULT_OPEN_PANEL_LABEL = '{identifier} · {title}';
22
- /**
23
- * The shipped default open layout (BB-234): a fresh worktree's initial pane
24
- * renders the ticket it belongs to instead of an anonymous shell prompt.
25
- *
26
- * It lives in **code, not config**, because a default each repo has to opt into
27
- * would leave the defect in place for every other consumer of this addon; the
28
- * addon already ships opinionated defaults of this kind (`BUILTIN_DEFAULTS` in
29
- * `./config.js`), and `bakers ui` is a command of the very host that ships it.
30
- *
31
- * `open: {}` is the documented opt-out back to the pre-BB-234 bare tab, so
32
- * the default is not a one-way door.
33
- */
34
- export const DEFAULT_OPEN_LAYOUT = {
35
- command: 'bakers ui --ticket {identifier}',
36
- tabLabel: DEFAULT_OPEN_TAB_LABEL,
37
- panelLabel: DEFAULT_OPEN_PANEL_LABEL,
38
- };
7
+ import { removeHerdrWorktree } from './worktrees.js';
39
8
  const defaultExec = (args) => exec('herdr', args);
40
9
  const defaultGitExec = (args) => exec('git', args);
10
+ const defaultRunGit = (args, cwd) => exec('git', args, { cwd });
41
11
  const noopLogger = {
42
12
  debug() { },
43
13
  info() { },
@@ -76,24 +46,6 @@ function parseWorktreePath(output, command) {
76
46
  }
77
47
  return path;
78
48
  }
79
- /**
80
- * Parse `worktree create` → root pane id (+ optional tab id for BB-374
81
- * overview tab rename). Sibling of {@link parseWorktreePath}. Returns null when
82
- * the create JSON carries no pane id, so the open-layout caller can skip
83
- * silently rather than throw (best-effort).
84
- */
85
- function parseWorktreeRootPane(output) {
86
- const parsed = parseJson(output, 'worktree create');
87
- if (!isRecord(parsed) || !isRecord(parsed.result))
88
- return null;
89
- const result = parsed.result;
90
- const paneId = result.root_pane?.pane_id;
91
- if (typeof paneId !== 'string' || !paneId)
92
- return null;
93
- const tabIdRaw = result.root_pane?.tab_id ?? result.tab?.tab_id;
94
- const tabId = typeof tabIdRaw === 'string' && tabIdRaw ? tabIdRaw : undefined;
95
- return tabId !== undefined ? { paneId, tabId } : { paneId };
96
- }
97
49
  /** Git-safe branch validation: safe ref chars only, no leading dot, no `..`. */
98
50
  export function validateBranch(branch) {
99
51
  if (!/^[A-Za-z0-9._/-]+$/.test(branch) ||
@@ -108,33 +60,23 @@ export class HerdrWorkspace {
108
60
  execGit;
109
61
  root;
110
62
  worktreeDir;
111
- open;
112
63
  logger;
113
- /**
114
- * Root panes captured by a FRESH `ensure` create, keyed by worktree path,
115
- * awaiting {@link applyOpenLayout} (BB-237). One-shot: consumed on apply.
116
- * Optional `tabId` powers the BB-374 overview tab rename.
117
- */
118
- pendingRootPanes = new Map();
119
- /** Herdr-backed intent-level agent host for `bakers ui` (BB-190). */
120
- agentHost;
64
+ runGit;
121
65
  constructor(options) {
122
66
  this.options = options;
123
67
  this.execHerdr = options.execHerdr ?? defaultExec;
124
68
  this.execGit = options.execGit ?? defaultGitExec;
125
69
  this.root = resolve(options.root);
126
70
  this.worktreeDir = options.worktreeDir ?? '.bakers-worktrees';
127
- // `??`, not `||`: an explicit `open: {}` must survive as the opt-out.
128
- this.open = options.open ?? DEFAULT_OPEN_LAYOUT;
71
+ this.runGit = options.runGit ?? defaultRunGit;
129
72
  this.logger = options.logger ?? noopLogger;
130
- this.agentHost = herdrAgentHost(this.execHerdr);
131
73
  }
132
74
  /**
133
75
  * Ensure the branch's worktree + herdr workspace exist.
134
76
  *
135
- * `_identifier` is unused HERE: the worktree is located by branch, and since
136
- * BB-237 the open layout — the one thing that consumed the identifier, to
137
- * 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`,
138
80
  * which takes it on its own `ctx`. The parameter stays because it is the
139
81
  * `BbWorkspace.ensure` contract position (the git workspace does use it).
140
82
  * It is still taken as-passed rather than parsed back out of `branch`, which
@@ -208,19 +150,9 @@ export class HerdrWorkspace {
208
150
  '--json',
209
151
  ]);
210
152
  const path = parseWorktreePath(createOutput, 'worktree create');
211
- // BB-237: CAPTURE the fresh root pane here, but do NOT lay it out yet.
212
- // The layout's startup command names the bakers CLI, which the `after_create`
213
- // hook builds — and that hook runs after `ensure()` returns. Applying the
214
- // layout here fired the command before its binary existed, which is why the
215
- // pane command needed a sentinel wait loop. The conductor now calls
216
- // `applyOpenLayout` after the hook; a create with no root pane in its output
217
- // stores nothing, so the layout is a no-op exactly as before.
218
- const pending = parseWorktreeRootPane(createOutput);
219
- if (pending) {
220
- this.pendingRootPanes.set(path, pending);
221
- }
222
- // The `after_create` hook is run by the executor (BB-84), not here — the
223
- // 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.
224
156
  return {
225
157
  path,
226
158
  instructions: loadInstructions(path),
@@ -229,109 +161,17 @@ export class HerdrWorkspace {
229
161
  };
230
162
  }
231
163
  /**
232
- * Apply the open layout to the root pane captured by the most recent
233
- * {@link ensure} create for `path` — by default (BB-234) the ticket's
234
- * `bakers ui` deep link, so the tab shows the ticket instead of a bare shell.
235
- * The pane's cwd is the worktree checkout, passed explicitly on the splits
236
- * (the root pane's cwd is already the checkout).
237
- *
238
- * BB-374 then renames the overview tab (`{identifier} · {title}` with title
239
- * capped at {@link OPEN_TAB_TITLE_MAX}) and root pane (full
240
- * `{identifier} · {title}`) — fresh-create only, same gate as the layout.
241
- *
242
- * NO stored pane ⇒ silent no-op. That is the reused-worktree case: `ensure`
243
- * took the reuse branch, there is no fresh root pane, and re-applying would
244
- * start a duplicate editor process on reattach (BB-139). The capture is
245
- * one-shot — consumed here — so a repeat call cannot double-apply and the map
246
- * cannot grow without bound.
247
- *
248
- * Best-effort — mirrors the `fetchBaseRef` pattern: a broken layout is logged
249
- * 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}.
250
167
  */
251
- async applyOpenLayout(path, ctx) {
252
- const pending = this.pendingRootPanes.get(path);
253
- if (!pending) {
254
- return;
255
- }
256
- this.pendingRootPanes.delete(path);
257
- const { paneId: rootPaneId } = pending;
258
- try {
259
- // Render the ROOT command here (spec D2). `applyPaneLayout` types its
260
- // root command verbatim for the executor's brace-bearing env-prefixed
261
- // agent command, so templating it there would corrupt that; the split
262
- // commands it already renders from the same `vars`.
263
- const vars = {
264
- identifier: ctx.identifier,
265
- branch: ctx.branch,
266
- title: ctx.title,
267
- worktreePath: path,
268
- };
269
- const layout = {
270
- ...this.open,
271
- ...(this.open.command !== undefined
272
- ? { command: renderTemplate(this.open.command, vars) }
273
- : {}),
274
- };
275
- await applyPaneLayout(this.execHerdr, rootPaneId, layout, path, vars);
276
- await this.applyOverviewLabels(rootPaneId, pending.tabId, vars);
277
- }
278
- catch (err) {
279
- this.logger.warn({ branch: ctx.branch, worktree: path, err: String(err) }, 'herdr open-layout failed (best-effort, ignored)');
280
- }
281
- }
282
- /**
283
- * Best-effort overview tab + pane renames (BB-374). Skipped for the
284
- * `open: {}` opt-out. A missing create-time tab id falls back to `pane get`.
285
- */
286
- async applyOverviewLabels(rootPaneId, createTabId, vars) {
287
- const emptyOptOut = this.open.command === undefined &&
288
- !this.open.panes?.length &&
289
- this.open.tabLabel === undefined &&
290
- this.open.panelLabel === undefined;
291
- if (emptyOptOut) {
292
- return;
293
- }
294
- // Tab bar is always visible; cap title length and mark truncation with
295
- // `...`. Pane/panel label keeps the full title for pane borders.
296
- const tabVars = {
297
- ...vars,
298
- title: truncateOpenTabTitle(vars.title ?? ''),
299
- };
300
- const tabLabel = renderTemplate(this.open.tabLabel ?? DEFAULT_OPEN_TAB_LABEL, tabVars);
301
- const panelLabel = renderTemplate(this.open.panelLabel ?? DEFAULT_OPEN_PANEL_LABEL, vars);
302
- let tabId = createTabId;
303
- if (!tabId) {
304
- try {
305
- tabId = (await this.resolveTabIdForPane(rootPaneId)) ?? undefined;
306
- }
307
- catch (err) {
308
- this.logger.warn({ paneId: rootPaneId, err: String(err) }, 'herdr overview tab id lookup failed (best-effort, ignored)');
309
- }
310
- }
311
- if (tabId) {
312
- try {
313
- await this.execHerdr(['tab', 'rename', tabId, tabLabel]);
314
- }
315
- catch (err) {
316
- this.logger.warn({ tabId, err: String(err) }, 'herdr overview tab rename failed (best-effort, ignored)');
317
- }
318
- }
319
- try {
320
- await this.execHerdr(['pane', 'rename', rootPaneId, panelLabel]);
321
- }
322
- catch (err) {
323
- this.logger.warn({ paneId: rootPaneId, err: String(err) }, 'herdr overview pane rename failed (best-effort, ignored)');
324
- }
325
- }
326
- /** `pane get <id>` → `result.pane.tab_id` when present. */
327
- async resolveTabIdForPane(paneId) {
328
- const output = await this.execHerdr(['pane', 'get', paneId, '--json']);
329
- const parsed = parseJson(output, 'pane get');
330
- const tabId = isRecord(parsed)
331
- ? parsed.result?.pane
332
- ?.tab_id
333
- : undefined;
334
- 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);
335
175
  }
336
176
  }
337
177
  export function herdrWorkspace(opts = {}) {
@@ -339,9 +179,8 @@ export function herdrWorkspace(opts = {}) {
339
179
  kind: 'workspace',
340
180
  id: 'herdr',
341
181
  requiredModules: [],
342
- // BB-234: `deps` carries the conductor logger, so the best-effort
343
- // open-layout failure is actually logged instead of vanishing into the noop
344
- // 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.
345
184
  async createWorkspace(config, deps) {
346
185
  const root = await deriveHerdrRoot(config.config_path, {
347
186
  ...(opts.root !== undefined ? { override: opts.root } : {}),
@@ -351,7 +190,6 @@ export function herdrWorkspace(opts = {}) {
351
190
  root,
352
191
  ...(opts.worktreeDir ? { worktreeDir: opts.worktreeDir } : {}),
353
192
  ...(opts.baseBranch ? { baseBranch: opts.baseBranch } : {}),
354
- ...(opts.open ? { open: opts.open } : {}),
355
193
  ...(opts.execHerdr ? { execHerdr: opts.execHerdr } : {}),
356
194
  ...(opts.autoSetupMerge ? { autoSetupMerge: true } : {}),
357
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.5",
3
+ "version": "0.6.1-next.7",
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.5"
24
+ "@bakers-build/addon-workspace-git": "^0.6.1-next.7"
25
25
  },
26
26
  "peerDependencies": {
27
- "@bakers-build/conductor": "^0.6.1-next.5",
28
- "@bakers-build/core": "^0.6.1-next.5"
27
+ "@bakers-build/conductor": "^0.6.1-next.7",
28
+ "@bakers-build/core": "^0.6.1-next.7"
29
29
  },
30
30
  "bakersBuild": {
31
- "commit": "314f28982940df736bea55293a81435d37864b31",
31
+ "commit": "b89398b187bf51f4f9ca5bfc1150469f73a879e6",
32
32
  "channel": "next"
33
33
  }
34
34
  }
@@ -1,45 +0,0 @@
1
- /** A hosted agent as reported by the host. `id` is the host-owned stable handle
2
- * (survives a TUI restart); `group` is the opaque grouping key it was launched
3
- * under; `label` is a human tag for the list. */
4
- export interface HostedAgent {
5
- id: string;
6
- group: string;
7
- label: string;
8
- }
9
- /**
10
- * The INTENT-level agent host herdr provides. The caller says "launch an agent
11
- * in this group", "show that agent", "list this group" — it never names panes,
12
- * tabs, splits or zoom. The host (herdr) owns the whole layout policy. `group`
13
- * is OPAQUE (bakers passes the project slug). `command` is the resolved shell
14
- * command the agent runs (the renderer's prompt is turned into a command by the
15
- * `bakers ui` entry before it reaches here — herdr stays agent-binary-agnostic).
16
- */
17
- export interface AgentLaunchHost {
18
- /**
19
- * Start an agent and return its stable handle. The host decides where the
20
- * session is placed and shows it; the caller only supplies intent + a group.
21
- */
22
- launch(opts: {
23
- group: string;
24
- cwd: string;
25
- command: string;
26
- env?: Record<string, string | undefined> | undefined;
27
- label?: string | undefined;
28
- }): Promise<HostedAgent>;
29
- /** The live agents of a group — the source of truth for the list, rebuilt
30
- * from the host on demand so sessions survive a TUI restart. */
31
- list(group: string): Promise<HostedAgent[]>;
32
- /** Bring one agent to the foreground (the host zooms/switches as it sees fit). */
33
- focus(id: string): Promise<void>;
34
- /** Stop showing a group's agents and return focus to the caller. Durable —
35
- * the agents keep running; this never terminates them. */
36
- hide(group: string): Promise<void>;
37
- /** Terminate one agent for good. */
38
- kill(id: string): Promise<void>;
39
- /** Send literal text to an agent's input. */
40
- sendText(id: string, text: string): Promise<void>;
41
- }
42
- /** A workspace (or other plugin) that can host agents at the intent level. */
43
- export interface AgentLaunchHostProvider {
44
- agentHost: AgentLaunchHost;
45
- }
@@ -1,9 +0,0 @@
1
- // Herdr's own agent-host contract (BB-194 AC-3). It used to live in
2
- // `@bakers-build/core` as `AgentLaunchHost`/`HostedAgent`, but the agent-host seam is
3
- // a TUI/renderer concern, not a conductor-engine one — so core dropped it and
4
- // herdr types its impl LOCALLY. This interface imports nothing removed and
5
- // nothing from `@bakers-build/addon-bakers-ui`: the renderer owns its own
6
- // prompt-level `TuiAgentService`, and the conductor `bakers ui` entry adapts this
7
- // mechanism-level (`command`-based) host to it. Structurally compatible, no
8
- // cross-package type coupling.
9
- export {};
@@ -1,3 +0,0 @@
1
- import type { AgentLaunchHost } from './agent-host.js';
2
- import type { HerdrExec } from './pane-layout.js';
3
- export declare function herdrAgentHost(execHerdr: HerdrExec): AgentLaunchHost;