@gtheys/pi-flow 0.0.0-stage → 0.2.0

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.
Files changed (164) hide show
  1. package/README.md +833 -2
  2. package/adhoc/tracker.ts +360 -0
  3. package/aven/client.ts +996 -0
  4. package/aven/status.ts +395 -0
  5. package/brainstorm/args.ts +24 -0
  6. package/brainstorm/artifact.ts +67 -0
  7. package/brainstorm/paths.ts +43 -0
  8. package/brainstorm/prompt.ts +172 -0
  9. package/brainstorm/refs.ts +41 -0
  10. package/config.schema.json +161 -0
  11. package/config.ts +577 -0
  12. package/feedback/args.ts +21 -0
  13. package/feedback/prompt.ts +177 -0
  14. package/feedback/triage.ts +88 -0
  15. package/flow/agent-role.ts +46 -0
  16. package/flow/answer-wake.ts +212 -0
  17. package/flow/answer.ts +183 -0
  18. package/flow/args.ts +48 -0
  19. package/flow/ask-emitter.ts +331 -0
  20. package/flow/attribution.ts +145 -0
  21. package/flow/aven-resolve-exec.ts +95 -0
  22. package/flow/aven-resolve.ts +80 -0
  23. package/flow/awaiting-approval.ts +32 -0
  24. package/flow/binding-heal.ts +68 -0
  25. package/flow/cost-autopush.ts +162 -0
  26. package/flow/cost-command.ts +122 -0
  27. package/flow/cost-rows-journal.ts +296 -0
  28. package/flow/cost-rows-push.ts +112 -0
  29. package/flow/cost-rows-rows.ts +209 -0
  30. package/flow/cost-rows.ts +228 -0
  31. package/flow/cost.ts +173 -0
  32. package/flow/durable-refs.ts +287 -0
  33. package/flow/effect-gate.ts +137 -0
  34. package/flow/ensure-labels.ts +44 -0
  35. package/flow/frame.ts +172 -0
  36. package/flow/gates.ts +211 -0
  37. package/flow/jira-ref.ts +212 -0
  38. package/flow/label-gate.ts +149 -0
  39. package/flow/land-gate.ts +98 -0
  40. package/flow/lifecycle-policy.ts +162 -0
  41. package/flow/live-wait.ts +52 -0
  42. package/flow/liveness.ts +408 -0
  43. package/flow/loop-deps.ts +210 -0
  44. package/flow/loop-settle.ts +531 -0
  45. package/flow/loop.ts +437 -0
  46. package/flow/orchestrate.ts +45 -0
  47. package/flow/phase-command.ts +287 -0
  48. package/flow/phase-emoji.ts +13 -0
  49. package/flow/phase-prompts.ts +251 -0
  50. package/flow/picker.ts +307 -0
  51. package/flow/push.ts +475 -0
  52. package/flow/reconcile-command.ts +253 -0
  53. package/flow/reconcile-deps.ts +329 -0
  54. package/flow/reconcile.ts +738 -0
  55. package/flow/ref-kind.ts +80 -0
  56. package/flow/resume-picker.ts +222 -0
  57. package/flow/resume.ts +116 -0
  58. package/flow/run-health.ts +252 -0
  59. package/flow/run-liveness.ts +33 -0
  60. package/flow/state-metrics.ts +559 -0
  61. package/flow/status.ts +105 -0
  62. package/flow/step-output.ts +416 -0
  63. package/flow/steps.ts +73 -0
  64. package/flow/terminal-purge.ts +281 -0
  65. package/flow/turn-generation.ts +19 -0
  66. package/flow/v2-emission.ts +381 -0
  67. package/flow/v2-resume.ts +100 -0
  68. package/flow/vocabulary.ts +261 -0
  69. package/flow/widget.ts +448 -0
  70. package/flow/worktree-context.ts +136 -0
  71. package/flow-diagram/assemble.ts +27 -0
  72. package/flow-diagram/command.ts +252 -0
  73. package/flow-diagram/translate.ts +862 -0
  74. package/flow-diagram/vendor/harness-profiler/LICENSE +21 -0
  75. package/flow-diagram/vendor/harness-profiler/PIN.md +64 -0
  76. package/flow-diagram/vendor/harness-profiler/hp.js +960 -0
  77. package/flow-diagram/vendor/harness-profiler/load.ts +66 -0
  78. package/flow-diagram/vendor/harness-profiler/view.html +436 -0
  79. package/gates.ts +20 -0
  80. package/herdr/sync.ts +355 -0
  81. package/herdr/viewer.ts +432 -0
  82. package/implement/args.ts +21 -0
  83. package/implement/prompt.ts +98 -0
  84. package/implement/retry.ts +57 -0
  85. package/implement/routing.ts +31 -0
  86. package/index.ts +3206 -0
  87. package/mode-profile.ts +56 -0
  88. package/package.json +205 -4
  89. package/phase-state.ts +18 -0
  90. package/plan/args.ts +20 -0
  91. package/plan/prompt.ts +251 -0
  92. package/plan/size-check.ts +46 -0
  93. package/plan-tools/helpers.ts +177 -0
  94. package/plan-tools/jira-branch-tool.ts +54 -0
  95. package/plan-tools/jira-branch.ts +109 -0
  96. package/plan-tools/jira-issue.ts +85 -0
  97. package/plan-tools/resolve-feature-path.ts +30 -0
  98. package/plan-tools/resolve-notes-path.ts +37 -0
  99. package/plan-tools/resolve-spec-path.ts +31 -0
  100. package/pr-quality/index.ts +908 -0
  101. package/review/LICENSE +19 -0
  102. package/review/deviation.ts +252 -0
  103. package/review/review.ts +3053 -0
  104. package/review/sem-guidance.d.mts +8 -0
  105. package/review/sem-guidance.mjs +89 -0
  106. package/review/verdict.ts +13 -0
  107. package/run-state.ts +2046 -0
  108. package/run-title.ts +91 -0
  109. package/server/consumer.ts +146 -0
  110. package/server/daemon.ts +1094 -0
  111. package/server/lifecycle.ts +679 -0
  112. package/server/pending.ts +267 -0
  113. package/server/staleness.ts +320 -0
  114. package/server/writer.ts +86 -0
  115. package/shared/diff-base.ts +138 -0
  116. package/shared/flow-base.ts +210 -0
  117. package/shared/sonarqube-utils.ts +415 -0
  118. package/shared/stable-range.ts +102 -0
  119. package/slugify.ts +13 -0
  120. package/sonarqube/sonarqube.ts +821 -0
  121. package/spec-review/approve.ts +91 -0
  122. package/spec-review/args.ts +21 -0
  123. package/spec-review/aven-spec.ts +142 -0
  124. package/spec-review/commands.ts +336 -0
  125. package/spec-review/escape-regexp.ts +7 -0
  126. package/spec-review/open-in-pane.ts +166 -0
  127. package/spec-review/picker.ts +74 -0
  128. package/spec-review/prompt.ts +72 -0
  129. package/spec-review/publish-args.ts +33 -0
  130. package/spec-review/publish.ts +210 -0
  131. package/telemetry/attributes.ts +118 -0
  132. package/telemetry/content.ts +140 -0
  133. package/telemetry/dispatch.ts +521 -0
  134. package/telemetry/exporter.ts +124 -0
  135. package/telemetry/index.ts +776 -0
  136. package/telemetry/loki.ts +224 -0
  137. package/tools/code-review-parse.ts +518 -0
  138. package/tools/code-review.ts +312 -0
  139. package/tools/deviation.ts +737 -0
  140. package/tools/flow-submit.ts +302 -0
  141. package/tools/land.ts +608 -0
  142. package/tools/phase-complete.ts +476 -0
  143. package/tools/result.ts +18 -0
  144. package/tools/review-deps.ts +44 -0
  145. package/tools/run-attempt.ts +312 -0
  146. package/tools/spec-approve.ts +265 -0
  147. package/validate/args.ts +22 -0
  148. package/validate/deviation-gate.ts +229 -0
  149. package/validate/gate-target.ts +371 -0
  150. package/validate/gate.ts +79 -0
  151. package/validate/paths.ts +20 -0
  152. package/validate/personal.ts +104 -0
  153. package/validate/prompt.ts +525 -0
  154. package/validate/review-gate.ts +134 -0
  155. package/validate/subtask-range.ts +113 -0
  156. package/work-mode.ts +19 -0
  157. package/worktree/bootstrap.ts +243 -0
  158. package/worktree/branch.ts +168 -0
  159. package/worktree/herdr.ts +447 -0
  160. package/worktree/index.ts +1447 -0
  161. package/worktree/orphan.ts +384 -0
  162. package/worktree/remove-guards.ts +99 -0
  163. package/worktree/residue.ts +216 -0
  164. package/worktree/sweep.ts +526 -0
@@ -0,0 +1,1447 @@
1
+ /**
2
+ * Worktree module — `worktree` tool wrapping Herdr worktree workspaces.
3
+ * Actions: create / list / bind / remove. See plan 2026-09-07-pi-worktree-extension.
4
+ * AIDEV-NOTE: PMR-K0ZV — absorbed from the retired pi-worktree package into
5
+ * pi-flow; registered exactly once from pi-flow/index.ts.
6
+ */
7
+
8
+ import { promises as fs } from 'node:fs'
9
+ import path from 'node:path'
10
+ import type {
11
+ ExtensionAPI,
12
+ ExtensionContext,
13
+ } from '@earendil-works/pi-coding-agent'
14
+ import { getAgentDir } from '@earendil-works/pi-coding-agent'
15
+ import { Type } from 'typebox'
16
+ import { recoveryCommand } from '../flow/binding-heal.ts'
17
+ import type { FlowRefDerivation } from '../flow/durable-refs.ts'
18
+ import { DEFAULT_RECIPES } from '../flow/effect-gate.ts'
19
+ import {
20
+ type FlowWorktree,
21
+ getActiveFlowRef,
22
+ getFlowWorktree,
23
+ NO_ACTIVE_FLOW_WARNING,
24
+ setActiveFlowRef,
25
+ setFlowWorktree,
26
+ } from '../flow/worktree-context.ts'
27
+ import { createEffectJournal, type EffectJournal } from '../run-state.ts'
28
+ import {
29
+ clearFlowBase,
30
+ currentBranch,
31
+ recordFlowBase,
32
+ resolveBaseSha,
33
+ } from '../shared/flow-base.ts'
34
+ import { copyEnvFiles, runBootstrap } from './bootstrap.ts'
35
+ import { deriveBranch, parseBranchInput, slugify } from './branch.ts'
36
+ import {
37
+ agentList,
38
+ filterLinked,
39
+ type HerdrAgent,
40
+ type HerdrWorkspace,
41
+ type HerdrWorktree,
42
+ herdrAvailable,
43
+ isPathWithin,
44
+ ownPaneIdFromEnv,
45
+ parseJson,
46
+ pickString,
47
+ workspaceClose,
48
+ workspaceList,
49
+ worktreeCreate,
50
+ worktreeList,
51
+ worktreeRemove,
52
+ } from './herdr.ts'
53
+ import {
54
+ type BranchDeleteDecision,
55
+ decideAutoBranchDelete,
56
+ decideBranchDelete,
57
+ describePruneFailure,
58
+ type PrState,
59
+ } from './remove-guards.ts'
60
+ import { classifyResidue, removeGeneratedResidue } from './residue.ts'
61
+
62
+ type ToolResult = {
63
+ content: Array<{ type: 'text'; text: string }>
64
+ details: Record<string, unknown> | undefined
65
+ }
66
+
67
+ function textResult(
68
+ text: string,
69
+ details?: Record<string, unknown>,
70
+ ): ToolResult {
71
+ const result: ToolResult = { content: [{ type: 'text', text }], details }
72
+ return result
73
+ }
74
+
75
+ /** Update callback shape pi hands to execute: partial AgentToolResult. */
76
+ type OnUpdate =
77
+ | ((update: {
78
+ content: Array<{ type: 'text'; text: string }>
79
+ details: Record<string, unknown> | undefined
80
+ }) => void)
81
+ | undefined
82
+
83
+ function errorResult(text: string): ToolResult {
84
+ return textResult(text)
85
+ }
86
+
87
+ // AIDEV-NOTE: PMR-VDVJ phase 5 — declare-before-act for worktree
88
+ // create/remove. The journal is resolved LAZILY: list/bind (and tests that
89
+ // don't opt in) never construct it, so no filesystem access happens on those
90
+ // paths. Fail-closed: a failed declaration refuses the action — for create
91
+ // the pre-recorded flow base is cleared (the existing create-failure revert),
92
+ // for remove the worktree is simply left intact (nothing to revert).
93
+ function resolveEffects(deps?: WorktreeDeps): EffectJournal {
94
+ if (deps?.effects) {
95
+ return deps.effects
96
+ }
97
+ return createEffectJournal(getAgentDir())
98
+ }
99
+
100
+ // AIDEV-NOTE: PMR-PB3Z (2.2) — exported for the orphan cleanup engine
101
+ // (worktree/orphan.ts), which declares its `git worktree remove` effect
102
+ // through the same fail-closed seam.
103
+ export async function declareWorktreeEffect(
104
+ effects: EffectJournal,
105
+ ref: string,
106
+ effect: 'worktree-create' | 'worktree-remove' | 'workspace-close',
107
+ command: string,
108
+ ): Promise<{ ok: true } | { ok: false; reason: string }> {
109
+ const declared = await effects.declare({
110
+ ref,
111
+ effect,
112
+ command,
113
+ recipe: DEFAULT_RECIPES[effect],
114
+ })
115
+ if (!declared.ok) {
116
+ return { ok: false, reason: declared.reason }
117
+ }
118
+ return { ok: true }
119
+ }
120
+
121
+ /** First `worktree <path>` entry of `git worktree list --porcelain`. */
122
+ // AIDEV-NOTE: PMR-PB3Z (2.2) — exported for the orphan cleanup engine.
123
+ export async function mainCheckout(
124
+ pi: ExtensionAPI,
125
+ // PMR-YG2N fix round — undefined = process cwd (loop done path).
126
+ cwd: string | undefined,
127
+ ): Promise<string> {
128
+ const result = await pi.exec('git', ['worktree', 'list', '--porcelain'], {
129
+ cwd,
130
+ })
131
+ if (result.code !== 0) {
132
+ throw new Error(
133
+ `git worktree list failed: ${result.stderr || result.stdout}`,
134
+ )
135
+ }
136
+ for (const line of result.stdout.split('\n')) {
137
+ if (line.startsWith('worktree ')) {
138
+ return line.slice('worktree '.length)
139
+ }
140
+ }
141
+ throw new Error('git worktree list returned no worktree entries')
142
+ }
143
+
144
+ async function createFlow(
145
+ pi: ExtensionAPI,
146
+ effects: EffectJournal,
147
+ cwd: string,
148
+ params: {
149
+ jira_id?: string
150
+ name?: string
151
+ type?: string
152
+ branch?: string
153
+ label?: string
154
+ },
155
+ signal: AbortSignal | undefined,
156
+ onUpdate: OnUpdate,
157
+ ): Promise<ToolResult> {
158
+ const report = (text: string) => {
159
+ if (onUpdate) {
160
+ onUpdate({ content: [{ type: 'text', text }], details: undefined })
161
+ }
162
+ }
163
+
164
+ let input: ReturnType<typeof parseBranchInput>
165
+ try {
166
+ input = parseBranchInput({
167
+ jira_id: params.jira_id,
168
+ name: params.name,
169
+ type: params.type,
170
+ branch: params.branch,
171
+ })
172
+ } catch (error) {
173
+ return errorResult((error as Error).message)
174
+ }
175
+
176
+ // AIDEV-NOTE: PMR-902B — during an active flow the aven ref is injected
177
+ // into personal branches (<type>/<REF>-<slug>, e.g. feat/PMR-AB12-add-save).
178
+ // Never a tool parameter: read from the flow's module-global context. Only
179
+ // the personal kind carries it — deriveBranch ignores it for literal and
180
+ // jira inputs, so those paths stay byte-for-byte as before.
181
+ const flowRef = getActiveFlowRef()
182
+ if (input.kind === 'personal' && flowRef !== null) {
183
+ input = { ...input, flowRef }
184
+ }
185
+
186
+ let derived: Awaited<ReturnType<typeof deriveBranch>>
187
+ try {
188
+ derived = await deriveBranch(pi, input)
189
+ } catch (error) {
190
+ return errorResult(
191
+ `Branch derivation failed for input ${JSON.stringify({
192
+ jira_id: params.jira_id,
193
+ name: params.name,
194
+ branch: params.branch,
195
+ })}: ${(error as Error).message}`,
196
+ )
197
+ }
198
+
199
+ const preflight = await herdrAvailable(pi, cwd)
200
+ if (!preflight.ok) {
201
+ return errorResult(
202
+ `${preflight.error}\nThe worktree tool must run inside a Herdr session with herdr on PATH.`,
203
+ )
204
+ }
205
+
206
+ let label: string
207
+ if (params.label) {
208
+ label = params.label
209
+ } else {
210
+ label = slugify(derived.branch)
211
+ }
212
+
213
+ // AIDEV-NOTE: PMR-R4AP — capture the main checkout's branch as the flow's
214
+ // diff base BEFORE creating the worktree; refuse on detached HEAD.
215
+ const execFn = (c: string, a: string[], o?: { cwd?: string }) =>
216
+ pi.exec(c, a, o)
217
+ let mainPath: string
218
+ try {
219
+ mainPath = await mainCheckout(pi, cwd)
220
+ } catch (error) {
221
+ return errorResult((error as Error).message)
222
+ }
223
+ const base = await currentBranch(execFn, mainPath)
224
+ if (!base.ok) {
225
+ return errorResult(`Cannot record flow base: ${base.reason}`)
226
+ }
227
+
228
+ const baseShaResult = await resolveBaseSha(execFn, mainPath, base.branch)
229
+ if (!baseShaResult.ok) {
230
+ return errorResult(`Cannot record flow base: ${baseShaResult.reason}`)
231
+ }
232
+ const baseSha = baseShaResult.branch
233
+
234
+ // Record BEFORE creating: no half-created worktree if recording fails
235
+ // (git config is repo-shared and works for a not-yet-existing branch).
236
+ const preRecorded = await recordFlowBase(
237
+ execFn,
238
+ mainPath,
239
+ derived.branch,
240
+ base.branch,
241
+ baseSha,
242
+ )
243
+ if (!preRecorded.ok) {
244
+ return errorResult(`Cannot record flow base: ${preRecorded.reason}`)
245
+ }
246
+
247
+ // AIDEV-NOTE: PMR-VDVJ — declare the exact herdr argv BEFORE creating the
248
+ // worktree (fail-closed): on declare failure the pre-recorded flow base is
249
+ // cleared via the same revert the create-failure path uses, and no herdr
250
+ // create call is made.
251
+ const command = `herdr worktree create --cwd ${cwd} --branch ${derived.branch} --label ${label} --base ${baseSha}`
252
+ const declared = await declareWorktreeEffect(
253
+ effects,
254
+ getActiveFlowRef() ?? 'worktree-ops',
255
+ 'worktree-create',
256
+ command,
257
+ )
258
+ if (!declared.ok) {
259
+ await clearFlowBase(execFn, mainPath, derived.branch)
260
+ return errorResult(
261
+ `worktree create refused: effect declaration failed (${declared.reason}) — fail-closed: the worktree was NOT created and the pre-recorded flow base was cleared`,
262
+ )
263
+ }
264
+
265
+ report(
266
+ `Creating worktree ${derived.branch} from ${base.branch}@${baseSha.slice(0, 9)}...`,
267
+ )
268
+ let created: { path: string; workspaceId: string }
269
+ try {
270
+ created = await worktreeCreate(pi, cwd, derived.branch, label, baseSha)
271
+ } catch (error) {
272
+ await clearFlowBase(execFn, mainPath, derived.branch)
273
+ return errorResult((error as Error).message)
274
+ }
275
+ if (created.path === '') {
276
+ return errorResult(
277
+ `herdr worktree create succeeded but returned no worktree path. Raw output tail: ${JSON.stringify(created)}`,
278
+ )
279
+ }
280
+ const { path, workspaceId } = created
281
+
282
+ // Verify herdr really branched from the recorded SHA.
283
+ const head = await execFn('git', ['rev-parse', 'HEAD'], { cwd: path })
284
+ if (head.code !== 0 || head.stdout.trim() !== baseSha) {
285
+ return errorResult(
286
+ `Worktree created at ${path} but its HEAD (${head.stdout.trim()}) is not the recorded base ${base.branch}@${baseSha} — herdr did not honour --base. Remove the worktree and report this.`,
287
+ )
288
+ }
289
+
290
+ // AIDEV-NOTE: PMR-1CCT — bind the created worktree to the active flow (if
291
+ // any) so the review tool resolves its diff here instead of the session
292
+ // checkout. Skipped (with a loud warning in the result) outside a flow run.
293
+ const flowBound = setFlowWorktree(path, derived.branch)
294
+
295
+ report(`Bootstrapping dependencies in ${path}...`)
296
+ const bootstrap = await runBootstrap(pi, path, signal, report)
297
+
298
+ const main = mainPath
299
+
300
+ report('Copying env files...')
301
+ const envCopied = await copyEnvFiles(pi, main, path)
302
+
303
+ const bootstrapLines = bootstrap
304
+ .map((step) => {
305
+ let line = `FAIL ${step.label} — ${step.output}`
306
+ if (step.ok) {
307
+ line = `ok ${step.label}`
308
+ }
309
+ return line
310
+ })
311
+ .join('\n')
312
+ let envLine = 'none (all present or none found)'
313
+ if (envCopied.length > 0) {
314
+ envLine = envCopied.join(', ')
315
+ }
316
+
317
+ // AIDEV-NOTE: raw Aven CLI commands resolve project paths from the main
318
+ // checkout, while all implementation remains in the created worktree.
319
+ const lines = [
320
+ `Worktree ready: ${derived.branch}`,
321
+ `Path: ${path}`,
322
+ `Flow base: ${base.branch} @ ${baseSha}`,
323
+ `Workspace: ${workspaceId || '(unknown)'}`,
324
+ `Bootstrap:\n${bootstrapLines}`,
325
+ `Env files copied: ${envLine}`,
326
+ `Next: cd ${path} && pi -c (or spawn a subagent with cwd ${path})`,
327
+ `Aven: run raw commands from the main checkout (cd ${mainPath} && aven ...); keep implementation in the worktree`,
328
+ ]
329
+ if (!flowBound) {
330
+ lines.push(NO_ACTIVE_FLOW_WARNING)
331
+ }
332
+ const text = lines.join('\n')
333
+
334
+ return textResult(text, {
335
+ branch: derived.branch,
336
+ path,
337
+ workspaceId,
338
+ bootstrap,
339
+ envCopied,
340
+ flowBound,
341
+ })
342
+ }
343
+
344
+ // AIDEV-NOTE: join-key logic — workspace id when the agent entry carries
345
+ // one, else segment-aware worktree-path containment against agent cwd.
346
+ // Minimal join; dashboard polish (main-checkout filter, branch sort) landed in 3.1.
347
+ function joinAgents(
348
+ worktrees: HerdrWorktree[],
349
+ agents: HerdrAgent[],
350
+ ): Map<HerdrWorktree, HerdrAgent | undefined> {
351
+ const joined = new Map<HerdrWorktree, HerdrAgent | undefined>()
352
+ for (const wt of worktrees) {
353
+ let match: HerdrAgent | undefined
354
+ if (wt.workspaceId !== '') {
355
+ match = agents.find((a) => a.workspaceId === wt.workspaceId)
356
+ }
357
+ if (!match) {
358
+ match = agents.find(
359
+ (a) => a.cwd !== undefined && isPathWithin(a.cwd, wt.path),
360
+ )
361
+ }
362
+ joined.set(wt, match)
363
+ }
364
+ return joined
365
+ }
366
+
367
+ // AIDEV-NOTE: PMR-8JVY — rebind resumed worktrees so review diffs never
368
+ // resolve against the session checkout and produce an empty range.
369
+ // AIDEV-NOTE: PMR-MQT2 — path is resolved against the session cwd (not the
370
+ // extension host's process.cwd()) and validated against herdr state, like
371
+ // removeFlow's "No Herdr worktree found" guard.
372
+ async function bindFlow(
373
+ pi: ExtensionAPI,
374
+ cwd: string,
375
+ params: {
376
+ path?: string
377
+ branch?: string
378
+ },
379
+ deps?: WorktreeDeps,
380
+ ): Promise<ToolResult> {
381
+ if (!params.path || !params.branch) {
382
+ return errorResult("bind requires 'path' and 'branch'")
383
+ }
384
+ const wtPath = path.resolve(cwd, params.path)
385
+ const stat = await fs.stat(wtPath).catch(() => null)
386
+ if (!stat?.isDirectory()) {
387
+ return errorResult(`No directory at ${wtPath}`)
388
+ }
389
+ let ref = getActiveFlowRef()
390
+ let adopted = false
391
+ if (ref === null) {
392
+ // AIDEV-NOTE: PMR-DRKH — binding self-heal: with no active flow ref
393
+ // (module state lost on pi reload), derive candidate refs from durable
394
+ // pending records via the injected seam. Adoption only on exactly one
395
+ // survivor (SINGLE-CANDIDATE-ONLY rule in flow/durable-refs.ts);
396
+ // zero/absent seam keeps the original refusal byte-for-byte (worktree
397
+ // tests assert it), multiple lists a per-ref recovery command.
398
+ let candidates: string[] = []
399
+ // AIDEV-NOTE: PMR-YN61 — the detailed seam additionally reports the
400
+ // refs the owner filter dropped as foreign-live, so the zero-survivor
401
+ // refusal can name them and their `/flow <ref>` recovery commands
402
+ // instead of hiding that a live foreign run exists. Foreign-skipped
403
+ // refs are NEVER adopted — they never enter `candidates`.
404
+ let foreignSkipped: string[] = []
405
+ if (deps?.deriveFlowRefsDetailed) {
406
+ const derivation = await deps.deriveFlowRefsDetailed()
407
+ candidates = derivation.refs
408
+ foreignSkipped = derivation.foreignSkipped
409
+ } else if (deps?.deriveFlowRefs) {
410
+ candidates = await deps.deriveFlowRefs()
411
+ }
412
+ if (candidates.length === 0) {
413
+ if (foreignSkipped.length > 0) {
414
+ const lines = foreignSkipped.map((skipped) => {
415
+ return ` ${recoveryCommand(skipped)} — ${skipped}`
416
+ })
417
+ return errorResult(
418
+ `No active flow ref — nothing to bind to. ${NO_ACTIVE_FLOW_WARNING}\nSkipped foreign live flow(s) owned by another running session (NOT adopted):\n${lines.join('\n')}\nRecover one explicitly with the matching command above, then bind again.`,
419
+ )
420
+ }
421
+ return errorResult(
422
+ `No active flow ref — nothing to bind to. ${NO_ACTIVE_FLOW_WARNING}`,
423
+ )
424
+ }
425
+ if (candidates.length > 1) {
426
+ const lines = candidates.map((candidate) => {
427
+ return ` ${recoveryCommand(candidate)} — ${candidate}`
428
+ })
429
+ return errorResult(
430
+ `No active flow ref — multiple candidate flows found:\n${lines.join('\n')}\nRecover exactly one explicitly before binding.`,
431
+ )
432
+ }
433
+ const candidate = candidates[0]
434
+ if (candidate === undefined) {
435
+ return errorResult(
436
+ `No active flow ref — nothing to bind to. ${NO_ACTIVE_FLOW_WARNING}`,
437
+ )
438
+ }
439
+ ref = candidate
440
+ adopted = true
441
+ // AIDEV-NOTE: PMR-NN5A — adoption is applied (setActiveFlowRef) only
442
+ // AFTER target and branch verification below, just before
443
+ // setFlowWorktree. Setting it here would leak an orphaned active ref
444
+ // when the bind is refused.
445
+ }
446
+ let worktrees: HerdrWorktree[]
447
+ try {
448
+ worktrees = await worktreeList(pi, cwd)
449
+ } catch (error) {
450
+ return errorResult((error as Error).message)
451
+ }
452
+ const target = worktrees.find((wt) => wt.path === wtPath)
453
+ if (!target) {
454
+ return errorResult(`No Herdr worktree found at path ${wtPath}`)
455
+ }
456
+ if (target.branch !== params.branch) {
457
+ return errorResult(
458
+ `Herdr worktree at ${wtPath} is on branch ${target.branch}, not ${params.branch}`,
459
+ )
460
+ }
461
+ const previous = getFlowWorktree()
462
+ if (adopted && ref !== null) {
463
+ setActiveFlowRef(ref)
464
+ }
465
+ setFlowWorktree(wtPath, params.branch)
466
+ let replaced = ''
467
+ if (previous) {
468
+ replaced = ` (replacing previous binding ${previous.path})`
469
+ }
470
+ let adoptedNote = ''
471
+ if (adopted) {
472
+ adoptedNote = ' (ref adopted from pending flow state)'
473
+ }
474
+ return textResult(
475
+ `Bound worktree ${wtPath} (${params.branch}) to flow ${ref}${replaced}${adoptedNote}`,
476
+ )
477
+ }
478
+
479
+ async function listFlow(pi: ExtensionAPI, cwd: string): Promise<ToolResult> {
480
+ const preflight = await herdrAvailable(pi, cwd)
481
+ if (!preflight.ok) {
482
+ return errorResult(
483
+ `${preflight.error}\nThe worktree tool must run inside a Herdr session with herdr on PATH.`,
484
+ )
485
+ }
486
+
487
+ let worktrees: HerdrWorktree[]
488
+ try {
489
+ worktrees = await worktreeList(pi, cwd)
490
+ } catch (error) {
491
+ return errorResult((error as Error).message)
492
+ }
493
+
494
+ // AIDEV-NOTE: dashboard = parallel workspaces only; herdr also returns
495
+ // the main checkout row (isLinked === false) which is filtered out.
496
+ const linked = filterLinked(worktrees)
497
+ if (linked.length === 0) {
498
+ return textResult('No worktrees (only the main checkout exists)', {
499
+ worktrees,
500
+ agentsDegraded: false,
501
+ })
502
+ }
503
+ const sorted = [...linked].sort((a, b) => a.branch.localeCompare(b.branch))
504
+
505
+ let agents: HerdrAgent[] = []
506
+ let degraded = false
507
+ try {
508
+ agents = await agentList(pi, cwd)
509
+ } catch {
510
+ degraded = true
511
+ }
512
+
513
+ const joined = joinAgents(sorted, agents)
514
+ const rows = sorted.map((wt) => {
515
+ const agent = joined.get(wt)
516
+ let state = '—'
517
+ let pane = '—'
518
+ if (agent) {
519
+ state = agent.state
520
+ pane = agent.pane
521
+ }
522
+ return { branch: wt.branch, state, pane, path: wt.path }
523
+ })
524
+
525
+ const width = (key: 'branch' | 'state' | 'pane') =>
526
+ Math.max(key.length, ...rows.map((r) => r[key].length))
527
+ const wBranch = width('branch')
528
+ const wState = width('state')
529
+ const wPane = width('pane')
530
+ const lines = [
531
+ `${'branch'.padEnd(wBranch)} ${'state'.padEnd(wState)} ${'pane'.padEnd(wPane)} path`,
532
+ `${'-'.repeat(wBranch)} ${'-'.repeat(wState)} ${'-'.repeat(wPane)} ${'-'.repeat(4)}`,
533
+ ...rows.map(
534
+ (r) =>
535
+ `${r.branch.padEnd(wBranch)} ${r.state.padEnd(wState)} ${r.pane.padEnd(wPane)} ${r.path}`,
536
+ ),
537
+ ]
538
+ if (degraded) {
539
+ lines.push('(agent list unavailable — agent state shown as —)')
540
+ }
541
+ return textResult(lines.join('\n'), { worktrees, agentsDegraded: degraded })
542
+ }
543
+
544
+ // AIDEV-NOTE: remove guards order per spec (now in removeWorktreeCore) —
545
+ // branch captured BEFORE removal (branch ref only exists while the worktree
546
+ // checkout does); PR merge state via gh checked BEFORE herdr removal so a
547
+ // refused branch delete leaves the worktree untouched. `git branch -D`
548
+ // (not -d) because squash merges look unmerged to git's ancestry check.
549
+ // AIDEV-NOTE: PMR-PB3Z (2.2) — exported for the orphan cleanup engine.
550
+ export async function ghPrState(
551
+ pi: ExtensionAPI,
552
+ main: string,
553
+ branch: string,
554
+ ): Promise<PrState> {
555
+ const result = await pi.exec(
556
+ 'gh',
557
+ ['pr', 'view', branch, '--json', 'state'],
558
+ { cwd: main },
559
+ )
560
+ if (result.code !== 0) {
561
+ const err = `${result.stderr}${result.stdout}`
562
+ if (/command not found/.test(err)) {
563
+ return 'GH_MISSING'
564
+ }
565
+ return 'NO_PR'
566
+ }
567
+ const payload = parseJson(result.stdout)
568
+ const state = pickString(payload, ['state'])
569
+ if (state === 'MERGED' || state === 'OPEN' || state === 'CLOSED') {
570
+ return state
571
+ }
572
+ return 'NO_PR'
573
+ }
574
+
575
+ // AIDEV-NOTE: PMR-K0ZV/PMR-VDVJ phase 5 — the removal core takes an EXPLICIT
576
+ // ref for the effect declaration: the auto path clears the active flow ref
577
+ // before cleanup runs, so the caller passes the captured ref; the manual
578
+ // wrapper passes getActiveFlowRef() ?? 'worktree-ops'.
579
+ // Decision injection (PMR-81SX fix round): opts.branchDecision, when
580
+ // present, replaces the ghPrState + decideBranchDelete re-derivation —
581
+ // manual removeFlow passes no decision (re-derive as always); the auto
582
+ // cleanup path injects ONLY a 'delete' verdict (its keep-branch verdict
583
+ // never reaches the core — deleteBranch stays false so the default skip
584
+ // note reproduces byte-identically). AutoBranchDeleteDecision has no
585
+ // 'refuse' variant, so the manual path's refuse handling stays where the
586
+ // refuse decisions actually originate: the re-derivation branch.
587
+ export type RemoveWorktreeOpts = {
588
+ path: string
589
+ force: boolean
590
+ deleteBranch: boolean
591
+ ref: string
592
+ // AIDEV-NOTE: PMR-81SX fix round — pre-made branch-delete decision for the
593
+ // AUTO path. Only the 'delete' verdict is injectable: keep verdicts never
594
+ // reach the core (cleanupFlowWorktree skips injection for keep-branch),
595
+ // and AutoBranchDeleteDecision has no 'refuse' variant, so a
596
+ // refuse can only arise on the manual re-derivation path below.
597
+ branchDecision?: { action: 'delete' }
598
+ }
599
+
600
+ export type RemoveWorktreeResult = {
601
+ removed: string
602
+ branch: string
603
+ branchDeleted: boolean
604
+ branchNote: string
605
+ pruneNote: string
606
+ prState: PrState | undefined
607
+ force: boolean
608
+ }
609
+
610
+ export async function removeWorktreeCore(
611
+ pi: ExtensionAPI,
612
+ effects: EffectJournal,
613
+ // PMR-YG2N fix round — undefined = process cwd (loop done path).
614
+ cwd: string | undefined,
615
+ opts: RemoveWorktreeOpts,
616
+ ): Promise<RemoveWorktreeResult | { error: string }> {
617
+ const path = opts.path
618
+ // Branch must be captured before removal — after `herdr worktree remove`
619
+ // the checkout (and its HEAD) is gone, but the branch ref remains.
620
+ const branchResult = await pi.exec(
621
+ 'git',
622
+ ['rev-parse', '--abbrev-ref', 'HEAD'],
623
+ { cwd: path },
624
+ )
625
+ if (branchResult.code !== 0) {
626
+ return {
627
+ error: `git rev-parse failed in ${path}: ${branchResult.stderr || branchResult.stdout}`,
628
+ }
629
+ }
630
+ const branch = branchResult.stdout.trim()
631
+
632
+ const force = opts.force
633
+ const status = await pi.exec('git', ['status', '--porcelain'], {
634
+ cwd: path,
635
+ })
636
+ if (status.code !== 0) {
637
+ return {
638
+ error: `git status failed in ${path}: ${status.stderr || status.stdout}`,
639
+ }
640
+ }
641
+ const dirtyCount = status.stdout
642
+ .split('\n')
643
+ .filter((line) => line.trim() !== '').length
644
+ if (dirtyCount > 0 && !force) {
645
+ return {
646
+ error: `${path} is dirty (${dirtyCount} changed files) — pass force: true to remove anyway`,
647
+ }
648
+ }
649
+
650
+ const preflight = await herdrAvailable(pi, cwd)
651
+ if (!preflight.ok) {
652
+ return {
653
+ error: `${preflight.error}\nThe worktree tool must run inside a Herdr session with herdr on PATH.`,
654
+ }
655
+ }
656
+
657
+ let worktrees: HerdrWorktree[]
658
+ try {
659
+ worktrees = await worktreeList(pi, cwd)
660
+ } catch (error) {
661
+ return { error: (error as Error).message }
662
+ }
663
+ const target = worktrees.find((wt) => wt.path === path)
664
+ if (!target) {
665
+ return { error: `No Herdr worktree found at path ${path}` }
666
+ }
667
+
668
+ const main = await mainCheckout(pi, cwd)
669
+
670
+ // PR state resolved BEFORE removal so a refused branch delete aborts
671
+ // with the worktree intact.
672
+ let decision: BranchDeleteDecision = {
673
+ action: 'skip',
674
+ reason: 'delete_branch not requested',
675
+ }
676
+ let prState: PrState | undefined
677
+ if (opts.branchDecision !== undefined) {
678
+ // Auto path: caller already decided — never re-derive via gh/decideBranchDelete.
679
+ // Only a 'delete' verdict is injectable (AutoBranchDeleteDecision has no
680
+ // 'refuse' variant and keep verdicts never reach the core), so there is
681
+ // no refuse handling here: a manual-tool 'Pass force: true' suggestion
682
+ // would be wrong vocabulary on the auto path anyway.
683
+ decision = opts.branchDecision
684
+ } else if (opts.deleteBranch) {
685
+ // Manual path: re-derive PR state and consult the manual guard.
686
+ prState = await ghPrState(pi, main, branch)
687
+ decision = decideBranchDelete({
688
+ deleteBranchRequested: true,
689
+ prState,
690
+ force,
691
+ })
692
+ if (decision.action === 'refuse') {
693
+ return {
694
+ error: `Refusing to remove: branch ${branch} not deletable — ${decision.reason}.\nPass force: true to remove anyway.`,
695
+ }
696
+ }
697
+ }
698
+
699
+ // AIDEV-NOTE: PMR-VDVJ — declare the exact herdr argv BEFORE removing
700
+ // (fail-closed): on declare failure the worktree is left intact — nothing
701
+ // to revert, the PR-state guard already ran before this point.
702
+ let removeCommand = `herdr worktree remove --workspace ${target.workspaceId}`
703
+ if (force) {
704
+ removeCommand = `${removeCommand} --force`
705
+ }
706
+ const declared = await declareWorktreeEffect(
707
+ effects,
708
+ opts.ref,
709
+ 'worktree-remove',
710
+ removeCommand,
711
+ )
712
+ if (!declared.ok) {
713
+ return {
714
+ error: `worktree remove refused: effect declaration failed (${declared.reason}) — fail-closed: the worktree was left intact`,
715
+ }
716
+ }
717
+
718
+ try {
719
+ await worktreeRemove(pi, cwd, target.workspaceId, force)
720
+ } catch (error) {
721
+ return { error: (error as Error).message }
722
+ }
723
+
724
+ let branchDeleted = false
725
+ let branchNote = `branch ${branch} kept`
726
+ if (decision.action === 'delete') {
727
+ const del = await pi.exec('git', ['branch', '-D', branch], {
728
+ cwd: main,
729
+ })
730
+ if (del.code === 0) {
731
+ branchDeleted = true
732
+ branchNote = `branch ${branch} deleted`
733
+ } else {
734
+ branchNote = `branch ${branch} delete failed: ${del.stderr || del.stdout}`
735
+ }
736
+ } else if (decision.action === 'skip') {
737
+ branchNote = `branch ${branch} kept (${decision.reason})`
738
+ }
739
+
740
+ // Best-effort prune — never fails the remove.
741
+ let pruneNote = 'prune ok'
742
+ const prune = await pi.exec('git', ['fetch', '--prune'], { cwd: main })
743
+ if (prune.code !== 0) {
744
+ pruneNote = describePruneFailure(prune.stderr || prune.stdout)
745
+ }
746
+
747
+ return {
748
+ removed: path,
749
+ branch,
750
+ branchDeleted,
751
+ branchNote,
752
+ pruneNote,
753
+ prState,
754
+ force,
755
+ }
756
+ }
757
+
758
+ export type CleanupAnnotate =
759
+ | ((ref: string, body: string) => Promise<boolean>)
760
+ | ((ref: string, body: string) => Promise<void>)
761
+
762
+ // AIDEV-NOTE: PMR-81SX — auto-cleanup at flow done (phase 5 of PMR-81SX).
763
+ // Contract: NEVER throws (each fallible step is locally caught; callers also
764
+ // catch as belt-and-braces). Fail-closed defer semantics: USER-WORK dirt
765
+ // (PMR-PB3Z — dirt is classified in Step 2; untracked `.pi/plans/` residue
766
+ // is auto-removed instead of deferring — PMR-YBQ6: plans are LLM-authored,
767
+ // never user work, so no twin check), any matched
768
+ // in-flight agent (including unknown agent_status — herdr's state
769
+ // strings are not enumerated in code, so ANY matched agent defers), or an
770
+ // agentList failure all keep the worktree untouched. Halt/pause never reach
771
+ // this code — only the done path calls it. Branch removal is decided from
772
+ // GitHub PR state here (ghPrState + decideAutoBranchDelete, PMR-V31Z 3.2):
773
+ // the loop's merge authorization proves permission, not that the PR was
774
+ // actually merged, so the cleanup re-checks PR state in the done path.
775
+ export type CleanupFlowWorktreeInput = {
776
+ ref: string
777
+ mode: 'work' | 'personal'
778
+ worktree: FlowWorktree | undefined
779
+ // PMR-YG2N fix round — session cwd when invoked from the /flow done
780
+ // branch; undefined (process cwd) on the loop done path.
781
+ cwd: string | undefined
782
+ // AIDEV-NOTE: PMR-TE7Q — false means delivery failed; the Promise<void>
783
+ // signature retains legacy injected annotators and is treated as success.
784
+ // The summary carries the result so failed writes never become dedupe keys.
785
+ annotate?: CleanupAnnotate
786
+ // AIDEV-NOTE: PMR-PB3Z (subtask 3.1) — the sweep passes the last journaled
787
+ // diagnosis (lastSweepDiagnosis, worktree/sweep.ts) as priorOutcome so an
788
+ // identical repeated state writes no duplicate aven note; the /flow done
789
+ // inline path passes no prior and always annotates its first diagnosis.
790
+ priorOutcome?: {
791
+ action: 'noop' | 'deferred' | 'removed'
792
+ reason: string
793
+ }
794
+ }
795
+
796
+ export type CleanupFlowWorktreeSummary = {
797
+ action: 'noop' | 'deferred' | 'removed'
798
+ reason: string
799
+ // AIDEV-NOTE: PMR-TE7Q — true means delivered (or deduped against confirmed
800
+ // delivery); false means failed and retriable. Absent means no note was due.
801
+ annotated?: boolean
802
+ }
803
+
804
+ export async function cleanupFlowWorktree(
805
+ pi: ExtensionAPI,
806
+ effects: EffectJournal,
807
+ input: CleanupFlowWorktreeInput,
808
+ ): Promise<CleanupFlowWorktreeSummary> {
809
+ // AIDEV-NOTE (PMR-W6C4): every non-removed outcome is made human-visible
810
+ // via a best-effort annotation naming the path and reason — otherwise a
811
+ // superseded stale worktree is kept with no trace at all, undermining the
812
+ // no-lingering-worktrees goal. Two exceptions: (1) the trivial 'no flow
813
+ // worktree bound' noop — nothing exists, and annotating every
814
+ // worktree-less flow done would spam the ticket; (2) PMR-PB3Z (3.1)
815
+ // dedupe — an outcome byte-identical to input.priorOutcome (action AND
816
+ // reason) was confirmed delivered by an earlier sweep, so the quiet retry
817
+ // skips the note while action/reason stay unchanged and annotated=true
818
+ // carries the delivery proof forward (a changed reason/action re-annotates).
819
+ const isDuplicatePrior = (
820
+ action: CleanupFlowWorktreeSummary['action'],
821
+ reason: string,
822
+ ): boolean => {
823
+ const prior = input.priorOutcome
824
+ if (prior === undefined) {
825
+ return false
826
+ }
827
+ return prior.action === action && prior.reason === reason
828
+ }
829
+ const annotateOutcome = async (
830
+ action: CleanupFlowWorktreeSummary['action'],
831
+ reason: string,
832
+ pathForNote: string | undefined,
833
+ ): Promise<CleanupFlowWorktreeSummary> => {
834
+ const summary: CleanupFlowWorktreeSummary = { action, reason }
835
+ if (!input.annotate) {
836
+ return summary
837
+ }
838
+ if (isDuplicatePrior(action, reason)) {
839
+ // The sweep only supplies priorOutcome after confirmed delivery.
840
+ summary.annotated = true
841
+ return summary
842
+ }
843
+ const pathText = pathForNote ?? 'unknown path'
844
+ const body = `worktree cleanup ${action} (${pathText}): ${reason}`
845
+ try {
846
+ const delivered = await input.annotate(input.ref, body)
847
+ summary.annotated = delivered !== false
848
+ } catch {
849
+ summary.annotated = false
850
+ }
851
+ return summary
852
+ }
853
+ try {
854
+ if (input.worktree === undefined) {
855
+ return { action: 'noop', reason: 'no flow worktree bound' }
856
+ }
857
+ // Fail-closed binding invariant (PMR-81SX fix round): after a /flow
858
+ // supersede, a stale binding from the prior flow can still be attached —
859
+ // never remove another flow's worktree or branch -D its branch under
860
+ // this flow's effect-journal ref / annotation.
861
+ if (input.worktree.ref !== input.ref) {
862
+ return annotateOutcome(
863
+ 'noop',
864
+ `worktree binding belongs to flow ${input.worktree.ref}, not ${input.ref} — not cleaning up`,
865
+ input.worktree.path,
866
+ )
867
+ }
868
+ const wtPath = input.worktree.path
869
+ const wtBranch = input.worktree.branch
870
+
871
+ // AIDEV-NOTE: PMR-PB3Z — Step 2 CLASSIFIES dirt instead of blanket-
872
+ // deferring (the removal core keeps its own guard; this skip happens
873
+ // even earlier). Preserved invariant: genuine user work still short-
874
+ // circuits BEFORE the in-flight agent probe. Auto-removable residue is
875
+ // untracked `.pi/plans/` content (worktree/residue.ts) — PMR-YBQ6:
876
+ // plans are LLM-authored, never user work, so no twin/byte-identity
877
+ // check; every status/classification/removal failure defers fail-closed
878
+ // with a recovery action.
879
+ const status = await pi.exec('git', ['status', '--porcelain', '-uall'], {
880
+ cwd: wtPath,
881
+ })
882
+ if (status.code !== 0) {
883
+ return annotateOutcome(
884
+ 'deferred',
885
+ `worktree ${wtPath} is dirty-check-unverifiable: git status failed: ${status.stderr || status.stdout} — inspect the worktree manually; the next sweep retries automatically`,
886
+ wtPath,
887
+ )
888
+ }
889
+ // Resolved lazily when the worktree is dirty; reused by Step 4 so a
890
+ // residue-classifying cleanup never resolves the main checkout twice.
891
+ let resolvedMain: string | undefined
892
+ let residueFiles: string[] = []
893
+ if (status.stdout.trim() !== '') {
894
+ try {
895
+ resolvedMain = await mainCheckout(pi, input.cwd)
896
+ } catch (error) {
897
+ return annotateOutcome(
898
+ 'deferred',
899
+ `worktree ${wtPath} is dirty and the main checkout is unresolvable: ${(error as Error).message} — resolve the repository state manually; the next sweep retries automatically`,
900
+ wtPath,
901
+ )
902
+ }
903
+ const classification = classifyResidue({
904
+ statusOutput: status.stdout,
905
+ wtPath,
906
+ mainPath: resolvedMain,
907
+ })
908
+ if (classification.kind === 'user-work') {
909
+ return annotateOutcome(
910
+ 'deferred',
911
+ `worktree ${wtPath} is dirty (${classification.detail}) — commit, stash, or clean the worktree manually; the next sweep retries automatically`,
912
+ wtPath,
913
+ )
914
+ }
915
+ if (classification.kind === 'generated-residue') {
916
+ residueFiles = classification.files
917
+ }
918
+ }
919
+
920
+ // AIDEV-NOTE: PMR-PB3Z (subtask 3.2) — reason-audit contract: EVERY
921
+ // non-removable outcome reason below names the exact blocker AND a
922
+ // recovery action (mirrors the orphan engine's policy in
923
+ // worktree/orphan.ts). Guard tokens (`dirty`, `in-flight`, `kept`) stay
924
+ // byte-stable so existing assertions and the 3.1 dedupe keep matching.
925
+ let agents: HerdrAgent[]
926
+ try {
927
+ agents = await agentList(pi, input.cwd)
928
+ } catch {
929
+ return annotateOutcome(
930
+ 'deferred',
931
+ 'herdr agent list unavailable — cannot prove no agent is in-flight; the next sweep retries automatically',
932
+ wtPath,
933
+ )
934
+ }
935
+ let worktrees: HerdrWorktree[]
936
+ try {
937
+ worktrees = await worktreeList(pi, input.cwd)
938
+ } catch (error) {
939
+ return annotateOutcome(
940
+ 'deferred',
941
+ `herdr worktree list failed: ${(error as Error).message} — cannot verify the worktree binding; the next sweep retries automatically`,
942
+ wtPath,
943
+ )
944
+ }
945
+ const target = worktrees.find((wt) => wt.path === wtPath)
946
+ if (!target) {
947
+ return annotateOutcome(
948
+ 'deferred',
949
+ `no Herdr worktree found at ${wtPath} — the herdr record may be gone while the directory remains; a later sweep re-resolves it automatically, or inspect the worktree manually`,
950
+ wtPath,
951
+ )
952
+ }
953
+ const joined = joinAgents([target], agents)
954
+ let agent = joined.get(target)
955
+ // AIDEV-NOTE (PMR-F5HB): the flow session's OWN herdr agent must not
956
+ // self-match the in-flight guard — when the session runs INSIDE the flow
957
+ // worktree, its own agent row carries the worktree cwd/workspace and
958
+ // would defer cleanup forever. Self is identified by pane id via the
959
+ // shared ownPaneIdFromEnv() (worktree/herdr.ts; PMR-PB3Z 2.2 extraction).
960
+ // Subagent children live on their own panes and still match (and defer)
961
+ // as before.
962
+ const ownPaneId = ownPaneIdFromEnv()
963
+ if (agent !== undefined && ownPaneId !== '' && agent.pane === ownPaneId) {
964
+ agent = undefined
965
+ }
966
+ if (agent) {
967
+ let agentState = agent.state
968
+ if (agentState === '') {
969
+ agentState = 'unknown'
970
+ }
971
+ return annotateOutcome(
972
+ 'deferred',
973
+ `agent '${agent.name}' (state: ${agentState}) may still be in-flight in ${wtPath} — wait for it to finish or close its pane; the next sweep retries automatically`,
974
+ wtPath,
975
+ )
976
+ }
977
+
978
+ // AIDEV-NOTE: PMR-D1AV — classification above is early and read-only;
979
+ // destructive unlink + its fail-closed re-status happen ONLY after the
980
+ // agent guard passes, so live/unknown agents keep every plan file.
981
+ if (residueFiles.length > 0) {
982
+ removeGeneratedResidue(residueFiles, wtPath)
983
+ const recheck = await pi.exec('git', ['status', '--porcelain', '-uall'], {
984
+ cwd: wtPath,
985
+ })
986
+ if (recheck.code !== 0 || recheck.stdout.trim() !== '') {
987
+ return annotateOutcome(
988
+ 'deferred',
989
+ `worktree ${wtPath} is dirty (residue removal incomplete) — remove the remaining files under .pi/plans manually; the next sweep retries automatically`,
990
+ wtPath,
991
+ )
992
+ }
993
+ }
994
+
995
+ let main: string
996
+ try {
997
+ if (resolvedMain !== undefined) {
998
+ main = resolvedMain
999
+ } else {
1000
+ main = await mainCheckout(pi, input.cwd)
1001
+ }
1002
+ } catch (error) {
1003
+ return annotateOutcome(
1004
+ 'deferred',
1005
+ `cannot resolve main checkout: ${(error as Error).message} — resolve the repository state manually; the next sweep retries automatically`,
1006
+ wtPath,
1007
+ )
1008
+ }
1009
+ // AIDEV-NOTE: PMR-V31Z 3.2 — both modes decide on GitHub PR state
1010
+ // (ghPrState); the personal local merge-base probe (PMR-81SX's
1011
+ // merged-proof) is gone. Only a MERGED PR (or force) deletes the branch;
1012
+ // every unproven state keeps the branch while the worktree is removed
1013
+ // (see decideAutoBranchDelete in worktree/remove-guards.ts).
1014
+ const prState = await ghPrState(pi, main, wtBranch)
1015
+ const decision = decideAutoBranchDelete({ prState })
1016
+
1017
+ // AIDEV-NOTE: decision injection — the AUTO decision computed here is
1018
+ // passed verbatim (branchDecision) so the core's manual NO_PR/
1019
+ // GH_MISSING re-derivation never vetoes an auto delete. For
1020
+ // 'keep-branch' no decision is injected: deleteBranch is false, so the
1021
+ // core's default skip ('delete_branch not requested') reproduces the
1022
+ // previous note byte-identically.
1023
+ let branchDecision: { action: 'delete' } | undefined
1024
+ if (decision.action === 'delete') {
1025
+ branchDecision = { action: 'delete' }
1026
+ }
1027
+ const removed = await removeWorktreeCore(pi, effects, input.cwd, {
1028
+ path: wtPath,
1029
+ force: false,
1030
+ deleteBranch: decision.action === 'delete',
1031
+ ref: input.ref,
1032
+ branchDecision,
1033
+ })
1034
+ if ('error' in removed) {
1035
+ return annotateOutcome(
1036
+ 'deferred',
1037
+ `worktree removal failed: ${removed.error} — inspect the worktree manually; the next sweep retries automatically`,
1038
+ wtPath,
1039
+ )
1040
+ }
1041
+
1042
+ const execFn = (c: string, a: string[], o?: { cwd?: string }) =>
1043
+ pi.exec(c, a, o)
1044
+ try {
1045
+ await clearFlowBase(execFn, main, wtBranch)
1046
+ } catch {
1047
+ // best-effort: stale config keys are harmless
1048
+ }
1049
+ let branchWord = 'kept'
1050
+ if (removed.branchDeleted) {
1051
+ branchWord = 'deleted'
1052
+ }
1053
+ let outcomeReason = 'work mode'
1054
+ if (input.mode === 'personal') {
1055
+ outcomeReason = 'personal mode'
1056
+ }
1057
+ if (decision.action === 'keep-branch') {
1058
+ outcomeReason = decision.reason
1059
+ }
1060
+ const summary: CleanupFlowWorktreeSummary = {
1061
+ action: 'removed',
1062
+ reason: `removed ${wtPath}; ${removed.branchNote}; ${removed.pruneNote}`,
1063
+ }
1064
+ if (input.annotate) {
1065
+ try {
1066
+ const delivered = await input.annotate(
1067
+ input.ref,
1068
+ `worktree removed (${wtPath}), branch ${branchWord}: ${wtBranch} (${outcomeReason})`,
1069
+ )
1070
+ summary.annotated = delivered !== false
1071
+ } catch {
1072
+ summary.annotated = false
1073
+ }
1074
+ }
1075
+
1076
+ return summary
1077
+ } catch (error) {
1078
+ // Never throw — the loop's own catch is belt-and-braces.
1079
+ return annotateOutcome(
1080
+ 'deferred',
1081
+ `cleanup error (non-fatal): ${(error as Error).message} — inspect the worktree manually; the next sweep retries automatically`,
1082
+ input.worktree?.path,
1083
+ )
1084
+ }
1085
+ }
1086
+
1087
+ async function removeFlow(
1088
+ pi: ExtensionAPI,
1089
+ effects: EffectJournal,
1090
+ cwd: string,
1091
+ params: {
1092
+ cwd?: string
1093
+ force?: boolean
1094
+ delete_branch?: boolean
1095
+ },
1096
+ ): Promise<ToolResult> {
1097
+ if (!params.cwd) {
1098
+ return errorResult("remove requires 'cwd' — the worktree path to remove")
1099
+ }
1100
+ const result = await removeWorktreeCore(pi, effects, cwd, {
1101
+ path: params.cwd,
1102
+ force: params.force === true,
1103
+ deleteBranch: params.delete_branch === true,
1104
+ ref: getActiveFlowRef() ?? 'worktree-ops',
1105
+ })
1106
+ if ('error' in result) {
1107
+ return errorResult(result.error)
1108
+ }
1109
+ const text = [
1110
+ `Removed worktree at ${result.removed}.`,
1111
+ result.branchNote,
1112
+ result.pruneNote,
1113
+ ].join('\n')
1114
+ return textResult(text, {
1115
+ removed: result.removed,
1116
+ branch: result.branch,
1117
+ branchDeleted: result.branchDeleted,
1118
+ prState: result.prState,
1119
+ force: result.force,
1120
+ })
1121
+ }
1122
+
1123
+ // AIDEV-NOTE: PMR-DMZR — one entry per workspace in the prune result:
1124
+ // 'closed' workspaces were proven dangling and closed; every 'skipped'
1125
+ // entry carries the failing check verbatim (fail-closed visibility —
1126
+ // anything not closed must say why).
1127
+ export type PruneEntry = {
1128
+ workspaceId: string
1129
+ label: string
1130
+ checkoutPath: string
1131
+ outcome: 'closed' | 'skipped'
1132
+ reason: string
1133
+ }
1134
+
1135
+ // AIDEV-NOTE: PMR-DMZR — prune closes only PROVEN-dangling herdr workspaces
1136
+ // (herdr's workspace registry never learns that pi-flow's sweep removed the
1137
+ // git worktree underneath it). A workspace is closed ONLY when ALL hold:
1138
+ // (a) worktree provenance with a checkout_path, (b) checkout_path missing on
1139
+ // disk, (c) path absent from `herdr worktree list`, (d) no agent attached —
1140
+ // same fail-closed unknown-means-live policy as cleanupFlowWorktree's
1141
+ // in-flight guard, including the PMR-F5HB self-pane exclusion
1142
+ // (HERDR_PANE_ID). ANY failure to list workspaces/agents/worktrees aborts
1143
+ // the whole run before a single close (fail-closed). Declare-before-act
1144
+ // (PMR-VDVJ): the exact `herdr workspace close <id>` argv is journaled
1145
+ // under the 'workspace-close' effect kind before each close.
1146
+ async function pruneFlow(
1147
+ pi: ExtensionAPI,
1148
+ effects: EffectJournal,
1149
+ // PMR-YG2N fix round — undefined = process cwd (loop done path).
1150
+ cwd: string | undefined,
1151
+ ): Promise<ToolResult> {
1152
+ const preflight = await herdrAvailable(pi, cwd)
1153
+ if (!preflight.ok) {
1154
+ return errorResult(
1155
+ `${preflight.error}\nThe worktree tool must run inside a Herdr session with herdr on PATH.`,
1156
+ )
1157
+ }
1158
+
1159
+ // Fail-closed: every list must succeed or NOTHING is closed.
1160
+ let workspaces: HerdrWorkspace[]
1161
+ try {
1162
+ workspaces = await workspaceList(pi, cwd)
1163
+ } catch (error) {
1164
+ return errorResult(`prune aborted: ${(error as Error).message}`)
1165
+ }
1166
+ let worktrees: HerdrWorktree[]
1167
+ try {
1168
+ worktrees = await worktreeList(pi, cwd)
1169
+ } catch (error) {
1170
+ return errorResult(`prune aborted: ${(error as Error).message}`)
1171
+ }
1172
+ let agents: HerdrAgent[]
1173
+ try {
1174
+ agents = await agentList(pi, cwd)
1175
+ } catch (error) {
1176
+ return errorResult(`prune aborted: ${(error as Error).message}`)
1177
+ }
1178
+
1179
+ // AIDEV-NOTE (PMR-F5HB): same self-pane identification as
1180
+ // cleanupFlowWorktree via the shared ownPaneIdFromEnv()
1181
+ // (worktree/herdr.ts; PMR-PB3Z 2.2 extraction) — the session's own agent
1182
+ // row must not pin its workspace via the attach check.
1183
+ const ownPaneId = ownPaneIdFromEnv()
1184
+
1185
+ const wtPaths = new Set(worktrees.map((wt) => wt.path))
1186
+ const ref = getActiveFlowRef() ?? 'worktree-ops'
1187
+ const entries: PruneEntry[] = []
1188
+
1189
+ for (const ws of workspaces) {
1190
+ const entry: PruneEntry = {
1191
+ workspaceId: ws.workspaceId,
1192
+ label: ws.label,
1193
+ checkoutPath: ws.checkoutPath,
1194
+ outcome: 'skipped',
1195
+ reason: '',
1196
+ }
1197
+ // (a) provenance: only worktree-backed records are candidates.
1198
+ if (ws.checkoutPath === '') {
1199
+ entry.reason = 'no worktree provenance (not worktree-backed)'
1200
+ entries.push(entry)
1201
+ continue
1202
+ }
1203
+ // herdr workspace close needs a target id; a provenance record without
1204
+ // one cannot be closed (defensive-parse '' degrades to a skip).
1205
+ if (ws.workspaceId === '') {
1206
+ entry.reason = 'workspace id missing — cannot close'
1207
+ entries.push(entry)
1208
+ continue
1209
+ }
1210
+ // (b) the checkout must be gone from disk. AIDEV-NOTE: PMR-SK1W —
1211
+ // only ENOENT proves the checkout is missing; EACCES/ELOOP/transient
1212
+ // stat errors mean it MAY still exist, so skip with the error named
1213
+ // (fail-closed: unknown-means-live, never close an unstatable path).
1214
+ let checkoutMissing = false
1215
+ try {
1216
+ await fs.stat(ws.checkoutPath)
1217
+ } catch (error) {
1218
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
1219
+ checkoutMissing = true
1220
+ } else {
1221
+ entry.reason = `cannot stat checkout path (${(error as Error).message}) — treating as live`
1222
+ entries.push(entry)
1223
+ continue
1224
+ }
1225
+ }
1226
+ if (!checkoutMissing) {
1227
+ entry.reason = 'checkout path exists on disk'
1228
+ entries.push(entry)
1229
+ continue
1230
+ }
1231
+ // (c) herdr must not still track the worktree for this path.
1232
+ if (wtPaths.has(ws.checkoutPath)) {
1233
+ entry.reason = 'checkout path still present in herdr worktree list'
1234
+ entries.push(entry)
1235
+ continue
1236
+ }
1237
+ // (d) no agent attached (self-pane rows excluded first; ANY matched
1238
+ // agent defers regardless of its agent_status — unknown-means-live).
1239
+ let attached: HerdrAgent | undefined
1240
+ for (const agent of agents) {
1241
+ if (ownPaneId !== '' && agent.pane === ownPaneId) {
1242
+ continue
1243
+ }
1244
+ if (agent.workspaceId !== '' && agent.workspaceId === ws.workspaceId) {
1245
+ attached = agent
1246
+ break
1247
+ }
1248
+ if (agent.cwd !== undefined && isPathWithin(agent.cwd, ws.checkoutPath)) {
1249
+ attached = agent
1250
+ break
1251
+ }
1252
+ }
1253
+ if (attached !== undefined) {
1254
+ let agentState = attached.state
1255
+ if (agentState === '') {
1256
+ agentState = 'unknown'
1257
+ }
1258
+ entry.reason = `agent '${attached.name}' (state: ${agentState}) may still be in-flight`
1259
+ entries.push(entry)
1260
+ continue
1261
+ }
1262
+ // Declare the exact argv BEFORE acting (fail-closed per workspace).
1263
+ const command = `herdr workspace close ${ws.workspaceId}`
1264
+ const declared = await declareWorktreeEffect(
1265
+ effects,
1266
+ ref,
1267
+ 'workspace-close',
1268
+ command,
1269
+ )
1270
+ if (!declared.ok) {
1271
+ entry.reason = `effect declaration failed (${declared.reason}) — workspace left untouched`
1272
+ entries.push(entry)
1273
+ continue
1274
+ }
1275
+ try {
1276
+ await workspaceClose(pi, cwd, ws.workspaceId)
1277
+ } catch (error) {
1278
+ entry.reason = (error as Error).message
1279
+ entries.push(entry)
1280
+ continue
1281
+ }
1282
+ entry.outcome = 'closed'
1283
+ entry.reason = `closed dangling workspace (checkout ${ws.checkoutPath} missing on disk, absent from herdr worktree list, no agents attached)`
1284
+ entries.push(entry)
1285
+ }
1286
+
1287
+ const closed = entries.filter((e) => e.outcome === 'closed')
1288
+ const skipped = entries.filter((e) => e.outcome === 'skipped')
1289
+ const lines = [
1290
+ `Prune complete: ${closed.length} closed, ${skipped.length} skipped.`,
1291
+ ]
1292
+ if (closed.length > 0) {
1293
+ lines.push('', 'closed:')
1294
+ for (const e of closed) {
1295
+ lines.push(` ${e.workspaceId} ${e.label} — ${e.reason}`)
1296
+ }
1297
+ }
1298
+ if (skipped.length > 0) {
1299
+ lines.push('', 'skipped:')
1300
+ for (const e of skipped) {
1301
+ lines.push(` ${e.workspaceId} ${e.label} — ${e.reason}`)
1302
+ }
1303
+ }
1304
+ return textResult(lines.join('\n'), {
1305
+ entries,
1306
+ closed: closed.length,
1307
+ skipped: skipped.length,
1308
+ })
1309
+ }
1310
+
1311
+ // AIDEV-NOTE: PMR-DRKH — optional deriveFlowRefs seam for bind-time
1312
+ // self-heal; inject a scanner here from pi-flow/index.ts (real) or tests
1313
+ // (fake). Absent seam = zero candidates = original refusal.
1314
+ // AIDEV-NOTE: PMR-YN61 — optional detailed variant: when present it takes
1315
+ // precedence over deriveFlowRefs and additionally carries the foreign-live
1316
+ // refs the owner filter skipped, so the zero-survivor refusal can name
1317
+ // them (and their `/flow <ref>` recovery commands) without adopting them.
1318
+ export interface WorktreeDeps {
1319
+ effects?: EffectJournal
1320
+ deriveFlowRefs?: () => Promise<string[]>
1321
+ deriveFlowRefsDetailed?: () => Promise<FlowRefDerivation>
1322
+ }
1323
+
1324
+ export default function (pi: ExtensionAPI, deps?: WorktreeDeps) {
1325
+ pi.registerTool({
1326
+ name: 'worktree',
1327
+ label: 'Worktree',
1328
+ description:
1329
+ 'Create, list, bind, or remove git worktrees managed as Herdr workspaces. Create derives a branch (from a Jira issue, a conventional name+type, or a literal), creates the Herdr worktree, bootstraps dependencies from the detected lockfile, copies missing .env* files from the main checkout. List shows a worktree/agent dashboard. Bind re-attaches an existing worktree to the active flow (resume path) so the review tool diffs it; remove guards against dirty worktrees. Prune closes herdr workspaces proven dangling (checkout removed outside herdr); each close is declared in the effect journal before acting.',
1330
+ promptSnippet:
1331
+ 'Create/list/bind/remove/prune git worktrees as Herdr workspaces for parallel work',
1332
+ promptGuidelines: [
1333
+ 'Use worktree when implementing multiple features of the same repo in parallel — create a worktree before spawning a subagent with cwd set to the new worktree path.',
1334
+ 'Use worktree list as a dashboard of worktrees and their running pi agent states.',
1335
+ 'Create supports exactly one of jira_id, name (+type), or branch.',
1336
+ 'Use bind when resuming a flow with an existing worktree (from the ticket worktree: note) — create binds automatically, resume must bind explicitly.',
1337
+ 'Use prune at the end of a flow to close herdr workspaces whose checkout directories were already removed — only proven-dangling workspaces are closed, everything else is skipped with a reason.',
1338
+ ],
1339
+ parameters: Type.Object({
1340
+ action: Type.Union(
1341
+ [
1342
+ Type.Literal('create'),
1343
+ Type.Literal('list'),
1344
+ Type.Literal('bind'),
1345
+ Type.Literal('remove'),
1346
+ Type.Literal('prune'),
1347
+ ],
1348
+ { description: 'Action to perform' },
1349
+ ),
1350
+ jira_id: Type.Optional(
1351
+ Type.String({
1352
+ description: 'Create mode 1: Jira ticket ID, e.g. DP-121 (uses acli)',
1353
+ }),
1354
+ ),
1355
+ name: Type.Optional(
1356
+ Type.String({
1357
+ description:
1358
+ 'Create mode 2: feature name, slugified into <type>/<slug>; during an active flow the ref is injected (<type>/<REF>-<slug>)',
1359
+ }),
1360
+ ),
1361
+ type: Type.Optional(
1362
+ Type.Union(
1363
+ [
1364
+ Type.Literal('feat'),
1365
+ Type.Literal('fix'),
1366
+ Type.Literal('chore'),
1367
+ Type.Literal('docs'),
1368
+ Type.Literal('refactor'),
1369
+ ],
1370
+ { description: 'Branch type for name mode (default: feat)' },
1371
+ ),
1372
+ ),
1373
+ branch: Type.Optional(
1374
+ Type.String({
1375
+ description:
1376
+ 'Create mode 3: literal branch name; bind: branch the worktree is on (required)',
1377
+ }),
1378
+ ),
1379
+ label: Type.Optional(
1380
+ Type.String({
1381
+ description: 'Herdr workspace label (default: branch slug)',
1382
+ }),
1383
+ ),
1384
+ cwd: Type.Optional(
1385
+ Type.String({
1386
+ description: 'remove: worktree path to remove (required for remove)',
1387
+ }),
1388
+ ),
1389
+ path: Type.Optional(
1390
+ Type.String({
1391
+ description: 'bind: worktree path to bind to the active flow',
1392
+ }),
1393
+ ),
1394
+ force: Type.Optional(
1395
+ Type.Boolean({
1396
+ description: 'remove: skip dirty guard / unmerged-branch guard',
1397
+ }),
1398
+ ),
1399
+ delete_branch: Type.Optional(
1400
+ Type.Boolean({
1401
+ description: 'remove: delete branch after removal (merge-checked)',
1402
+ }),
1403
+ ),
1404
+ }),
1405
+ async execute(
1406
+ _toolCallId: string,
1407
+ params: {
1408
+ action: 'create' | 'list' | 'bind' | 'remove' | 'prune'
1409
+ jira_id?: string
1410
+ name?: string
1411
+ type?: 'feat' | 'fix' | 'chore' | 'docs' | 'refactor'
1412
+ branch?: string
1413
+ label?: string
1414
+ cwd?: string
1415
+ path?: string
1416
+ force?: boolean
1417
+ delete_branch?: boolean
1418
+ },
1419
+ signal: AbortSignal | undefined,
1420
+ onUpdate: OnUpdate,
1421
+ ctx: ExtensionContext,
1422
+ ): Promise<ToolResult> {
1423
+ const cwd = ctx?.cwd ?? process.cwd()
1424
+ void _toolCallId
1425
+ if (params.action === 'create') {
1426
+ return createFlow(
1427
+ pi,
1428
+ resolveEffects(deps),
1429
+ cwd,
1430
+ params,
1431
+ signal,
1432
+ onUpdate,
1433
+ )
1434
+ }
1435
+ if (params.action === 'list') {
1436
+ return listFlow(pi, cwd)
1437
+ }
1438
+ if (params.action === 'bind') {
1439
+ return bindFlow(pi, cwd, params, deps)
1440
+ }
1441
+ if (params.action === 'prune') {
1442
+ return pruneFlow(pi, resolveEffects(deps), cwd)
1443
+ }
1444
+ return removeFlow(pi, resolveEffects(deps), cwd, params)
1445
+ },
1446
+ })
1447
+ }