@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,384 @@
1
+ /**
2
+ * AIDEV-NOTE: PMR-PB3Z (subtask 2.2) — guarded cleanup engine for ORPHANED
3
+ * flow worktrees: the directory (and usually its merged branch) still exists
4
+ * on disk, but herdr no longer tracks the worktree. Policy record:
5
+ *
6
+ * - Why herdr-based removal cannot serve: removeWorktreeCore removes via
7
+ * `herdr worktree remove --workspace <id>`, which needs a herdr workspace
8
+ * record — an orphan has none. The only correct removal is a DECLARED
9
+ * `git worktree remove <path>` (git's own porcelain: refuses dirty or
10
+ * locked worktrees without force, updates .git/worktrees metadata).
11
+ * - Why cwd containment is the join key for the agent guard: with no herdr
12
+ * workspace record there is no workspace_id to join on; a live agent whose
13
+ * cwd sits inside the orphan path is the only remaining liveness signal.
14
+ * Same unknown-means-live policy as cleanupFlowWorktree (ANY matched agent
15
+ * defers regardless of agent_status), same PMR-F5HB self-pane exclusion
16
+ * via ownPaneIdFromEnv().
17
+ * - Why recovery text is mandatory: an orphan deferral is the LAST automated
18
+ * line — no herdr record exists to inspect, so every deferred
19
+ * reason must name the exact blocker AND a manual recovery action.
20
+ *
21
+ * Guard order mirrors cleanupFlowWorktree: branch capture → read-only residue
22
+ * classification (1.1/1.2, including the wt≠main invariant) → agent guard →
23
+ * residue unlink + re-status → PR-state branch decision (ghPrState +
24
+ * decideAutoBranchDelete, unified for both modes by PMR-V31Z 3.2) →
25
+ * declared removal → branch decision, best-effort prune + clearFlowBase →
26
+ * annotation. The engine
27
+ * NEVER throws, NEVER passes --force, and has no rm -rf / git clean
28
+ * fallback. Failures before removal keep the worktree; residue removal is
29
+ * always followed by a fail-closed status check before removal can proceed.
30
+ */
31
+
32
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
33
+ import type { EffectJournal } from '../run-state.ts'
34
+ import { clearFlowBase } from '../shared/flow-base.ts'
35
+ import {
36
+ agentList,
37
+ type HerdrAgent,
38
+ isPathWithin,
39
+ ownPaneIdFromEnv,
40
+ } from './herdr.ts'
41
+ import {
42
+ type CleanupAnnotate,
43
+ type CleanupFlowWorktreeSummary,
44
+ declareWorktreeEffect,
45
+ ghPrState,
46
+ mainCheckout,
47
+ } from './index.ts'
48
+ import {
49
+ decideAutoBranchDelete,
50
+ describePruneFailure,
51
+ } from './remove-guards.ts'
52
+ import { classifyResidue, removeGeneratedResidue } from './residue.ts'
53
+
54
+ export type OrphanCleanupInput = {
55
+ ref: string
56
+ mode: 'work' | 'personal'
57
+ /** Verified to exist on disk by the orphan binding (sweep 2.1). */
58
+ path: string
59
+ /** Note branch; re-derived from the checkout when null (see Step 1). */
60
+ branch: string | null
61
+ cwd: string | undefined
62
+ // AIDEV-NOTE: PMR-TE7Q — false means delivery failed; the legacy void
63
+ // signature is treated as success. The summary carries the delivery result.
64
+ annotate?: CleanupAnnotate
65
+ // AIDEV-NOTE: PMR-PB3Z (subtask 3.1) — same dedupe seam as
66
+ // CleanupFlowWorktreeInput: the sweep passes the last journaled diagnosis
67
+ // so an identical repeated orphan state writes no duplicate aven note.
68
+ priorOutcome?: {
69
+ action: 'noop' | 'deferred' | 'removed'
70
+ reason: string
71
+ }
72
+ }
73
+
74
+ export async function cleanupOrphanedWorktree(
75
+ pi: ExtensionAPI,
76
+ effects: EffectJournal,
77
+ input: OrphanCleanupInput,
78
+ ): Promise<CleanupFlowWorktreeSummary> {
79
+ const wtPath = input.path
80
+ // AIDEV-NOTE (PMR-W6C4, mirrored from cleanupFlowWorktree): every
81
+ // non-removed outcome is made human-visible via a best-effort annotation
82
+ // naming the path and reason — an orphan deferral must never be silent.
83
+ // PMR-PB3Z (3.1) dedupe exception (mirrored too): an outcome
84
+ // byte-identical to input.priorOutcome (action AND reason) was confirmed
85
+ // delivered by an earlier sweep, so the quiet retry skips the note while
86
+ // action/reason stay unchanged and annotated=true carries the proof forward.
87
+ // Every non-removed outcome goes through this one annotateOutcome seam.
88
+ const isDuplicatePrior = (
89
+ action: CleanupFlowWorktreeSummary['action'],
90
+ reason: string,
91
+ ): boolean => {
92
+ const prior = input.priorOutcome
93
+ if (prior === undefined) {
94
+ return false
95
+ }
96
+ return prior.action === action && prior.reason === reason
97
+ }
98
+ const annotateOutcome = async (
99
+ action: CleanupFlowWorktreeSummary['action'],
100
+ reason: string,
101
+ ): Promise<CleanupFlowWorktreeSummary> => {
102
+ const summary: CleanupFlowWorktreeSummary = { action, reason }
103
+ if (!input.annotate) {
104
+ return summary
105
+ }
106
+ if (isDuplicatePrior(action, reason)) {
107
+ // The sweep only supplies priorOutcome after confirmed delivery.
108
+ summary.annotated = true
109
+ return summary
110
+ }
111
+ try {
112
+ const delivered = await input.annotate(
113
+ input.ref,
114
+ `worktree cleanup ${action} (${wtPath}): ${reason}`,
115
+ )
116
+ summary.annotated = delivered !== false
117
+ } catch {
118
+ summary.annotated = false
119
+ }
120
+ return summary
121
+ }
122
+ try {
123
+ // Capture the branch before removal. The worktree's actual HEAD is
124
+ // ALWAYS probed (read-only, before any status/agent/removal side
125
+ // effect): a missing note branch is derived from it, and a SUPPLIED
126
+ // note branch is verified against it.
127
+ // AIDEV-NOTE: PMR-1X4A — branch/status probe failures can mean broken
128
+ // worktree metadata or a plain directory. Their recovery text diagnoses
129
+ // metadata and guards manual deletion instead of recommending the same
130
+ // `git worktree remove` that cannot work for those failure modes.
131
+ const headProbe = await pi.exec(
132
+ 'git',
133
+ ['rev-parse', '--abbrev-ref', 'HEAD'],
134
+ { cwd: wtPath },
135
+ )
136
+ let branch: string
137
+ let actualBranch: string
138
+ if (input.branch !== null) {
139
+ branch = input.branch
140
+ if (headProbe.code !== 0) {
141
+ return annotateOutcome(
142
+ 'deferred',
143
+ `orphan worktree branch verification failed: ${headProbe.stderr || headProbe.stdout} — inspect the worktree manually; restore its git metadata or remove it manually (git worktree remove ${wtPath})`,
144
+ )
145
+ }
146
+ actualBranch = headProbe.stdout.trim()
147
+ } else {
148
+ if (headProbe.code !== 0) {
149
+ return annotateOutcome(
150
+ 'deferred',
151
+ `orphan branch resolution failed: ${headProbe.stderr || headProbe.stdout} — diagnose with git worktree list and inspect .git/worktrees/<id>; for broken metadata, run git worktree prune, then delete ${wtPath} manually only after genuine user work has been ruled out or preserved; for a plain non-worktree directory, delete ${wtPath} manually under the same guard`,
152
+ )
153
+ }
154
+ branch = headProbe.stdout.trim()
155
+ actualBranch = branch
156
+ }
157
+ // AIDEV-NOTE: PMR-PB3Z (fix-round blocker) — a detached-HEAD worktree
158
+ // yields the literal branch name 'HEAD' (supplied or derived). The
159
+ // PR-state probe would then run `gh pr view HEAD` — no PR is ever
160
+ // queryable under that name, and even a "keep" verdict could not say
161
+ // WHICH commits it keeps, so an unmerged detached commit could be
162
+ // stranded or lost. Defer BEFORE
163
+ // any status/agent/removal side effect and name a recovery action.
164
+ if (actualBranch === 'HEAD') {
165
+ return annotateOutcome(
166
+ 'deferred',
167
+ `orphan worktree ${wtPath} has a detached HEAD — merged proof is impossible without a branch name; check out or identify the actual branch in the worktree before retrying, or remove manually only after preserving/verifying the work (git worktree remove ${wtPath})`,
168
+ )
169
+ }
170
+ // AIDEV-NOTE: PMR-PB3Z (fix-round blocker 2) — a supplied note branch
171
+ // can be valid AND merged while the worktree is checked out somewhere
172
+ // else entirely: the PR-state probe against the NOTE branch would
173
+ // green-light the removal while the worktree's actual (possibly
174
+ // unmerged) HEAD is deleted. The actual checkout must match the note
175
+ // branch before any side effect; a mismatch defers naming both branches
176
+ // and a recovery action.
177
+ if (actualBranch !== branch) {
178
+ return annotateOutcome(
179
+ 'deferred',
180
+ `orphan worktree ${wtPath} is checked out on branch ${actualBranch} but the note names ${branch} — align the worktree with the note (git -C ${wtPath} checkout ${branch}) or correct the note before retrying, or remove manually only after verifying the work (git worktree remove ${wtPath})`,
181
+ )
182
+ }
183
+
184
+ // Only untracked `.pi/plans/` content is removable (PMR-YBQ6: plans are
185
+ // LLM-authored, never user work — no twin/byte-identity check).
186
+ // All other dirt defers before the agent probe; equal worktree/main
187
+ // paths also fail closed in classifyResidue.
188
+ const status = await pi.exec('git', ['status', '--porcelain', '-uall'], {
189
+ cwd: wtPath,
190
+ })
191
+ if (status.code !== 0) {
192
+ return annotateOutcome(
193
+ 'deferred',
194
+ `orphan worktree ${wtPath} is dirty-check-unverifiable: git status failed: ${status.stderr || status.stdout} — diagnose with git worktree list and inspect .git/worktrees/<id>; for broken metadata, run git worktree prune, then delete ${wtPath} manually only after genuine user work has been ruled out or preserved; for a plain non-worktree directory, delete ${wtPath} manually under the same guard`,
195
+ )
196
+ }
197
+ // Resolve main only for dirty worktrees and reuse it for the PR probe.
198
+ let resolvedMain: string | undefined
199
+ let residueFiles: string[] = []
200
+ if (status.stdout.trim() !== '') {
201
+ try {
202
+ resolvedMain = await mainCheckout(pi, input.cwd)
203
+ } catch (error) {
204
+ return annotateOutcome(
205
+ 'deferred',
206
+ `orphan worktree ${wtPath} is dirty and the main checkout is unresolvable: ${(error as Error).message} — resolve the repository state manually; the next sweep retries automatically`,
207
+ )
208
+ }
209
+ const classification = classifyResidue({
210
+ statusOutput: status.stdout,
211
+ wtPath,
212
+ mainPath: resolvedMain,
213
+ })
214
+ if (classification.kind === 'user-work') {
215
+ return annotateOutcome(
216
+ 'deferred',
217
+ `orphan worktree ${wtPath} is dirty (${classification.detail}) — commit, stash, or clean the worktree manually; the next sweep retries automatically`,
218
+ )
219
+ }
220
+ if (classification.kind === 'generated-residue') {
221
+ residueFiles = classification.files
222
+ }
223
+ }
224
+
225
+ // Any non-self agent inside the orphan means live, including unknown
226
+ // states; list failure also defers. Self-pane exclusion prevents the
227
+ // flow session from pinning its own worktree (PMR-F5HB).
228
+ let agents: HerdrAgent[]
229
+ try {
230
+ agents = await agentList(pi, input.cwd)
231
+ } catch {
232
+ return annotateOutcome(
233
+ 'deferred',
234
+ `herdr agent list unavailable — cannot prove no agent is in-flight in ${wtPath}; the next sweep retries automatically`,
235
+ )
236
+ }
237
+ const ownPaneId = ownPaneIdFromEnv()
238
+ let liveAgent: HerdrAgent | undefined
239
+ for (const agent of agents) {
240
+ if (ownPaneId !== '' && agent.pane === ownPaneId) {
241
+ continue
242
+ }
243
+ if (agent.cwd !== undefined && isPathWithin(agent.cwd, wtPath)) {
244
+ liveAgent = agent
245
+ break
246
+ }
247
+ }
248
+ if (liveAgent !== undefined) {
249
+ let agentState = liveAgent.state
250
+ if (agentState === '') {
251
+ agentState = 'unknown'
252
+ }
253
+ return annotateOutcome(
254
+ 'deferred',
255
+ `agent '${liveAgent.name}' (state: ${agentState}) may still be in-flight in ${wtPath} — wait for it to finish or close its pane; the next sweep retries automatically`,
256
+ )
257
+ }
258
+
259
+ // AIDEV-NOTE: PMR-D1AV — classification above is early and read-only;
260
+ // destructive unlink + its fail-closed re-status happen ONLY after the
261
+ // agent guard passes, so live/unknown agents keep every plan file.
262
+ if (residueFiles.length > 0) {
263
+ removeGeneratedResidue(residueFiles, wtPath)
264
+ const recheck = await pi.exec('git', ['status', '--porcelain', '-uall'], {
265
+ cwd: wtPath,
266
+ })
267
+ if (recheck.code !== 0 || recheck.stdout.trim() !== '') {
268
+ return annotateOutcome(
269
+ 'deferred',
270
+ `orphan worktree ${wtPath} is dirty (residue removal incomplete) — remove the remaining files under .pi/plans manually; the next sweep retries automatically`,
271
+ )
272
+ }
273
+ }
274
+
275
+ // AIDEV-NOTE: PMR-V31Z 3.2 — both modes decide on GitHub PR state
276
+ // (ghPrState); the personal local merge-base probe (PMR-81SX's
277
+ // merged-proof) is gone. Only a MERGED PR (or force) deletes the branch;
278
+ // every unproven state keeps the branch while the worktree is removed
279
+ // (see decideAutoBranchDelete in worktree/remove-guards.ts).
280
+ let main: string
281
+ try {
282
+ if (resolvedMain !== undefined) {
283
+ main = resolvedMain
284
+ } else {
285
+ main = await mainCheckout(pi, input.cwd)
286
+ }
287
+ } catch (error) {
288
+ return annotateOutcome(
289
+ 'deferred',
290
+ `cannot resolve main checkout: ${(error as Error).message} — resolve the repository state manually; the next sweep retries automatically`,
291
+ )
292
+ }
293
+ const prState = await ghPrState(pi, main, branch)
294
+ const decision = decideAutoBranchDelete({ prState })
295
+
296
+ // Declare the exact command before acting (PMR-VDVJ). Plain
297
+ // `git worktree remove` refuses dirty or locked worktrees; there is no
298
+ // force or recursive-delete fallback.
299
+ const command = `git worktree remove ${wtPath}`
300
+ const declared = await declareWorktreeEffect(
301
+ effects,
302
+ input.ref,
303
+ 'worktree-remove',
304
+ command,
305
+ )
306
+ if (!declared.ok) {
307
+ return annotateOutcome(
308
+ 'deferred',
309
+ `worktree remove refused: effect declaration failed (${declared.reason}) — the orphan was left intact; restore the effect journal and retry the sweep, or remove it manually with git worktree remove ${wtPath}`,
310
+ )
311
+ }
312
+ const removal = await pi.exec('git', ['worktree', 'remove', wtPath], {
313
+ cwd: main,
314
+ })
315
+ if (removal.code !== 0) {
316
+ return annotateOutcome(
317
+ 'deferred',
318
+ `git worktree remove failed for ${wtPath}: ${removal.stderr || removal.stdout} — remove manually (git worktree remove ${wtPath}; if the git metadata is stale, git worktree prune then delete the directory)`,
319
+ )
320
+ }
321
+
322
+ // Step 6 — branch decision (same vocabulary as removeWorktreeCore):
323
+ // -D, not -d, because squash merges look unmerged to git's ancestry
324
+ // check; the delete/keep verdict was already made in Step 4.
325
+ let branchDeleted = false
326
+ let branchNote = `branch ${branch} kept`
327
+ if (decision.action === 'delete') {
328
+ const del = await pi.exec('git', ['branch', '-D', branch], {
329
+ cwd: main,
330
+ })
331
+ if (del.code === 0) {
332
+ branchDeleted = true
333
+ branchNote = `branch ${branch} deleted`
334
+ } else {
335
+ branchNote = `branch ${branch} delete failed: ${del.stderr || del.stdout}`
336
+ }
337
+ } else if (decision.action === 'keep-branch') {
338
+ branchNote = `branch ${branch} kept (${decision.reason})`
339
+ }
340
+
341
+ // Best-effort prune — never fails the removal.
342
+ let pruneNote = 'prune ok'
343
+ const prune = await pi.exec('git', ['fetch', '--prune'], { cwd: main })
344
+ if (prune.code !== 0) {
345
+ pruneNote = describePruneFailure(prune.stderr || prune.stdout)
346
+ }
347
+
348
+ const execFn = (c: string, a: string[], o?: { cwd?: string }) =>
349
+ pi.exec(c, a, o)
350
+ try {
351
+ await clearFlowBase(execFn, main, branch)
352
+ } catch {
353
+ // best-effort: stale config keys are harmless
354
+ }
355
+
356
+ let branchWord = 'kept'
357
+ if (branchDeleted) {
358
+ branchWord = 'deleted'
359
+ }
360
+ const summary: CleanupFlowWorktreeSummary = {
361
+ action: 'removed',
362
+ reason: `removed ${wtPath}; ${branchNote}; ${pruneNote}`,
363
+ }
364
+ if (input.annotate) {
365
+ try {
366
+ const delivered = await input.annotate(
367
+ input.ref,
368
+ `worktree removed (orphan) (${wtPath}), branch ${branchWord}: ${branch}`,
369
+ )
370
+ summary.annotated = delivered !== false
371
+ } catch {
372
+ summary.annotated = false
373
+ }
374
+ }
375
+
376
+ return summary
377
+ } catch (error) {
378
+ // Never throw — the sweep's own catch is belt-and-braces.
379
+ return annotateOutcome(
380
+ 'deferred',
381
+ `orphan cleanup error (non-fatal): ${(error as Error).message} — inspect ${wtPath} manually; the next sweep retries automatically`,
382
+ )
383
+ }
384
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Pure branch-delete decisions for worktree remove.
3
+ * Merge state is checked on GitHub because squash merges leave the local
4
+ * branch looking unmerged (see plan 2026-09-07, remove step 4).
5
+ */
6
+
7
+ export type PrState = 'MERGED' | 'OPEN' | 'CLOSED' | 'NO_PR' | 'GH_MISSING'
8
+
9
+ export type BranchDeleteDecision =
10
+ | { action: 'delete' }
11
+ | { action: 'refuse'; reason: string }
12
+ | { action: 'skip'; reason: string }
13
+
14
+ export function decideBranchDelete(input: {
15
+ deleteBranchRequested: boolean
16
+ prState: PrState
17
+ force: boolean
18
+ }): BranchDeleteDecision {
19
+ if (!input.deleteBranchRequested) {
20
+ return { action: 'skip', reason: 'delete_branch not requested' }
21
+ }
22
+ if (input.prState === 'MERGED' || input.force) {
23
+ return { action: 'delete' }
24
+ }
25
+ if (input.prState === 'GH_MISSING') {
26
+ return {
27
+ action: 'refuse',
28
+ reason: 'gh CLI unavailable — cannot verify merge state',
29
+ }
30
+ }
31
+ if (input.prState === 'NO_PR') {
32
+ return {
33
+ action: 'refuse',
34
+ reason: 'no PR found for branch — refusing to delete an unmerged branch',
35
+ }
36
+ }
37
+ return {
38
+ action: 'refuse',
39
+ reason: `PR for branch is ${input.prState} — refusing to delete an unmerged branch`,
40
+ }
41
+ }
42
+
43
+ // AIDEV-NOTE: PMR-81SX — auto-cleanup (flow done) decision for branch
44
+ // removal, unified on PR state by PMR-V31Z 3.1: personal flows now deliver
45
+ // via GitHub PR, so both modes share this one dispatch. The branch outlives
46
+ // the flow worktree until the human merges on GitHub: only a MERGED PR (or an
47
+ // explicit force) deletes it; every unproven state keeps the branch while the
48
+ // worktree is removed. keep-all is gone — a completed flow never keeps its
49
+ // worktree. decideBranchDelete above (manual path) must stay untouched: its
50
+ // refusal semantics are pinned by tests and user-facing.
51
+ export type AutoBranchDeleteDecision =
52
+ | { action: 'delete' }
53
+ | { action: 'keep-branch'; reason: string }
54
+
55
+ export function decideAutoBranchDelete(input: {
56
+ prState: PrState
57
+ force?: boolean
58
+ }): AutoBranchDeleteDecision {
59
+ if (input.force) {
60
+ return { action: 'delete' }
61
+ }
62
+ if (input.prState === 'MERGED') {
63
+ return { action: 'delete' }
64
+ }
65
+ if (input.prState === 'OPEN') {
66
+ return {
67
+ action: 'keep-branch',
68
+ reason:
69
+ 'PR still open — removing worktree, keeping branch until the human merges',
70
+ }
71
+ }
72
+ if (input.prState === 'CLOSED') {
73
+ return {
74
+ action: 'keep-branch',
75
+ reason: 'PR closed without merge — cannot prove merge, keeping branch',
76
+ }
77
+ }
78
+ if (input.prState === 'GH_MISSING') {
79
+ return {
80
+ action: 'keep-branch',
81
+ reason: 'gh CLI unavailable — cannot verify merge state, keeping branch',
82
+ }
83
+ }
84
+ return {
85
+ action: 'keep-branch',
86
+ reason: 'no PR found for branch — cannot prove merge, keeping branch',
87
+ }
88
+ }
89
+
90
+ // AIDEV-NOTE: herdr panes may lack SSH_AUTH_SOCK, so the post-remove
91
+ // `git fetch --prune` can fail with publickey even when the user's keys are
92
+ // fine (PMR-8JQ8). Classify auth failures as a skip instead of a scary
93
+ // failure line; the fetch stays best-effort either way.
94
+ export function describePruneFailure(output: string): string {
95
+ if (/Permission denied \(publickey\)/.test(output)) {
96
+ return 'prune skipped: git fetch --prune could not authenticate (ssh publickey) in this environment; remote refs may be stale'
97
+ }
98
+ return `git fetch --prune failed (non-fatal): ${output}`
99
+ }
@@ -0,0 +1,216 @@
1
+ /**
2
+ * AIDEV-NOTE: PMR-PB3Z — generated-residue classification for landed flow
3
+ * worktrees (subtask 1.1; wired into cleanupFlowWorktree in 1.2).
4
+ *
5
+ * AIDEV-NOTE: PMR-YBQ6 — verified mechanism (2026-11-29): `.pi/plans/` is
6
+ * tracked in git in this repo (published by docs commits); `herdr worktree
7
+ * create` performs a plain `git worktree add`, and git materializes tracked
8
+ * files at checkout with creation-time mtimes — that is why fresh worktrees
9
+ * contain `.pi/plans/` with fresh mtimes. No copying layer exists: pi-flow's
10
+ * bootstrap copies only .env* files. The dirty entry that used to defer
11
+ * landed-worktree cleanup forever is the worktree's OWN plan dir
12
+ * (`.pi/plans/<ref>/`, written in-place during the flow session, with no
13
+ * twin in the main checkout).
14
+ *
15
+ * Policy (PMR-YBQ6, user decision 2026-11-29): a dirty worktree is
16
+ * auto-removable "generated residue" when EVERY dirty entry is an untracked
17
+ * (`??`) file under `.pi/plans/`. Plans are LLM-authored during flows —
18
+ * never precious human work — so they are discardable unconditionally: one
19
+ * blunt rule, no ref matching, no byte-identity/twin check. The worktree's
20
+ * own in-place-written plan dir is therefore residue too and no longer
21
+ * defers cleanup. Untracked files OUTSIDE `.pi/plans/` and any tracked
22
+ * change still classify as user-work and defer.
23
+ *
24
+ * Why not `.gitignore` instead: ignoring `.pi/plans/` in the main repo would
25
+ * hide plan artifacts from the human's `git status` and would silently
26
+ * swallow ANY `.pi/plans` content at removal time. Explicit classification
27
+ * keeps the discard decision visible in cleanup reasons (see plan.md "Key
28
+ * Decisions").
29
+ *
30
+ * Fail-closed everywhere: quoted/unparsable porcelain paths, `wtPath ===
31
+ * mainPath`, `..`/backslash/absolute path segments, and any fs error during
32
+ * removal all classify or return as user-work / not-ok — never as removable.
33
+ *
34
+ * This module is pure + `node:fs` only: callers supply the
35
+ * `git status --porcelain -uall` output as a string; no herdr/git exec here.
36
+ */
37
+
38
+ import { rmdirSync, unlinkSync } from 'node:fs'
39
+ import path from 'node:path'
40
+
41
+ export type ResidueClassification =
42
+ | { kind: 'clean' }
43
+ | { kind: 'generated-residue'; files: string[] } // absolute wt paths under .pi/plans/
44
+ | { kind: 'user-work'; detail: string }
45
+
46
+ const RESIDUE_PREFIX = '.pi/plans/'
47
+
48
+ function errMessage(err: unknown): string {
49
+ if (err instanceof Error) return err.message
50
+ return String(err)
51
+ }
52
+
53
+ function errnoCode(err: unknown): string | null {
54
+ if (err instanceof Error && 'code' in err && typeof err.code === 'string') {
55
+ return err.code
56
+ }
57
+ return null
58
+ }
59
+
60
+ /**
61
+ * Parse `git status --porcelain -uall` output into {xy, path} entries.
62
+ * Returns null on quoted (C-quoted) or malformed lines — fail-closed: the
63
+ * caller must treat null as user work, never as removable residue.
64
+ */
65
+ export function parsePorcelain(
66
+ output: string,
67
+ ): Array<{ xy: string; path: string }> | null {
68
+ const entries: Array<{ xy: string; path: string }> = []
69
+ for (const line of output.split('\n')) {
70
+ if (line === '') continue
71
+ if (line.length < 4) return null
72
+ if (line[2] !== ' ') return null
73
+ const p = line.slice(3)
74
+ if (p === '') return null
75
+ // AIDEV-NOTE: PMR-PB3Z — git C-quotes paths with special characters
76
+ // ("...\t..."). Unquoting is error-prone; fail closed instead.
77
+ if (p.startsWith('"')) return null
78
+ entries.push({ xy: line.slice(0, 2), path: p })
79
+ }
80
+ return entries
81
+ }
82
+
83
+ /** True when a porcelain relpath could escape its root or is not a plain file path. */
84
+ function hasUnsafeSegments(p: string): boolean {
85
+ if (p.includes('\\')) return true
86
+ if (p.startsWith('/')) return true
87
+ for (const segment of p.split('/')) {
88
+ if (segment === '' || segment === '..') return true
89
+ }
90
+ return false
91
+ }
92
+
93
+ /**
94
+ * Classify a dirty worktree's status output. `generated-residue` is returned
95
+ * when EVERY entry is an untracked `.pi/plans/` file — PMR-YBQ6 policy:
96
+ * plans are LLM-authored, never user work, so no twin/byte-identity check
97
+ * applies. Every other combination is `user-work` with a specific detail.
98
+ * `wtPath === mainPath` is user-work (fail-closed — residue must never be
99
+ * "removed" from the main checkout).
100
+ */
101
+ export function classifyResidue(input: {
102
+ statusOutput: string // git status --porcelain -uall
103
+ wtPath: string
104
+ mainPath: string
105
+ }): ResidueClassification {
106
+ const entries = parsePorcelain(input.statusOutput)
107
+ if (entries === null) {
108
+ return {
109
+ kind: 'user-work',
110
+ detail: 'unparsable porcelain output (quoted or malformed path)',
111
+ }
112
+ }
113
+ if (entries.length === 0) return { kind: 'clean' }
114
+
115
+ const wtPath = path.resolve(input.wtPath)
116
+ const mainPath = path.resolve(input.mainPath)
117
+ if (wtPath === mainPath) {
118
+ return {
119
+ kind: 'user-work',
120
+ detail: `worktree path equals main checkout: ${wtPath}`,
121
+ }
122
+ }
123
+
124
+ let tracked = 0
125
+ for (const entry of entries) {
126
+ if (entry.xy !== '??') tracked += 1
127
+ }
128
+ if (tracked > 0) {
129
+ return { kind: 'user-work', detail: `${tracked} tracked change(s)` }
130
+ }
131
+
132
+ for (const entry of entries) {
133
+ if (hasUnsafeSegments(entry.path)) {
134
+ return {
135
+ kind: 'user-work',
136
+ detail: `unsafe untracked path: ${entry.path}`,
137
+ }
138
+ }
139
+ }
140
+
141
+ let outside = 0
142
+ for (const entry of entries) {
143
+ if (!entry.path.startsWith(RESIDUE_PREFIX)) outside += 1
144
+ }
145
+ if (outside > 0) {
146
+ return {
147
+ kind: 'user-work',
148
+ detail: `${outside} untracked file(s) outside .pi/plans`,
149
+ }
150
+ }
151
+
152
+ const files: string[] = []
153
+ for (const entry of entries) {
154
+ files.push(path.join(wtPath, entry.path))
155
+ }
156
+ return { kind: 'generated-residue', files }
157
+ }
158
+
159
+ /**
160
+ * Delete exactly the proven residue files (absolute paths under
161
+ * `<wtPath>/.pi/plans/`) plus the parent directories the deletion emptied,
162
+ * bounded strictly under `<wtPath>/.pi/plans/`. Fails closed: any file
163
+ * outside that subtree is refused before anything is deleted, and any fs
164
+ * error returns not-ok (the caller re-statuses to decide the actual state).
165
+ * The main checkout is unreachable through this API — the subtree guard is
166
+ * anchored on the passed wtPath only.
167
+ */
168
+ export function removeGeneratedResidue(
169
+ files: string[],
170
+ wtPath: string,
171
+ ): { ok: true } | { ok: false; reason: string } {
172
+ const root = path.resolve(wtPath, '.pi', 'plans')
173
+ const resolved: string[] = []
174
+ for (const file of files) {
175
+ const abs = path.resolve(file)
176
+ if (!abs.startsWith(root + path.sep)) {
177
+ return {
178
+ ok: false,
179
+ reason: `refusing to delete outside ${root}: ${file}`,
180
+ }
181
+ }
182
+ resolved.push(abs)
183
+ }
184
+ for (const abs of resolved) {
185
+ try {
186
+ unlinkSync(abs)
187
+ } catch (err) {
188
+ return {
189
+ ok: false,
190
+ reason: `failed to delete ${abs}: ${errMessage(err)}`,
191
+ }
192
+ }
193
+ }
194
+ // Prune directories the deletion emptied. rmdirSync only removes empty
195
+ // dirs, so a non-empty dir (ENOTEMPTY/EEXIST) just stops the upward walk;
196
+ // the loop condition keeps every removal strictly under root.
197
+ for (const abs of resolved) {
198
+ let dir = path.dirname(abs)
199
+ while (dir.startsWith(root + path.sep)) {
200
+ try {
201
+ rmdirSync(dir)
202
+ } catch (err) {
203
+ const code = errnoCode(err)
204
+ if (code === 'ENOTEMPTY' || code === 'EEXIST' || code === 'ENOENT') {
205
+ break
206
+ }
207
+ return {
208
+ ok: false,
209
+ reason: `failed to remove emptied dir ${dir}: ${errMessage(err)}`,
210
+ }
211
+ }
212
+ dir = path.dirname(dir)
213
+ }
214
+ }
215
+ return { ok: true }
216
+ }