@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,526 @@
1
+ // AIDEV-NOTE: PMR-YG2N — durable sweep over run-journal refs; labels-done
2
+ // gate; fail-closed. Pure helpers live here; the sweep engine itself lands in
3
+ // a later slice (sweepMergedFlowWorktrees).
4
+
5
+ import { existsSync } from 'node:fs'
6
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
7
+ import { avenShowFull } from '../aven/client.ts'
8
+ import { nextPhase } from '../flow/orchestrate.ts'
9
+ import { resumeSeedFromEvents } from '../flow/resume.ts'
10
+ import { type FlowWorktree, getFlowWorktree } from '../flow/worktree-context.ts'
11
+ import { isValidRef } from '../herdr/viewer.ts'
12
+ import type { EffectJournal, FlowRunEvent } from '../run-state.ts'
13
+ import {
14
+ latestWorktreeNote,
15
+ matchHerdrWorktree,
16
+ } from '../tools/code-review-parse.ts'
17
+ import { type HerdrWorktree, worktreeList } from './herdr.ts'
18
+ import {
19
+ type CleanupAnnotate,
20
+ type CleanupFlowWorktreeSummary,
21
+ cleanupFlowWorktree,
22
+ } from './index.ts'
23
+ import { cleanupOrphanedWorktree } from './orphan.ts'
24
+
25
+ export type SweepOutcome = 'removed' | 'noop' | 'deferred'
26
+
27
+ // AIDEV-NOTE: PMR-PB3Z 2.4 — the exact detail string written by pre-orphan
28
+ // sweeps for a gone-noop. Keyed on byte-equality by the terminal-skip
29
+ // exception below; the 2.3 verified-absent detail must never equal it.
30
+ const LEGACY_GONE_NOOP_DETAIL = 'recorded worktree gone or absent from herdr'
31
+
32
+ /** Terminal sweep outcomes let a later sweep skip the ref entirely. */
33
+ export function isTerminalSweepOutcome(outcome: SweepOutcome): boolean {
34
+ if (outcome === 'removed') return true
35
+ if (outcome === 'noop') return true
36
+ return false
37
+ }
38
+
39
+ export interface SweepOutcomePick {
40
+ outcome: SweepOutcome
41
+ source: 'flow-done' | 'sweep'
42
+ }
43
+
44
+ export interface SweepDiagnosisPick {
45
+ outcome: SweepOutcome
46
+ source: 'flow-done' | 'sweep'
47
+ detail?: string
48
+ annotated?: boolean
49
+ }
50
+
51
+ function latestSweepEvent(
52
+ events: FlowRunEvent[],
53
+ ): Extract<FlowRunEvent, { kind: 'worktree-sweep' }> | null {
54
+ let latest: Extract<FlowRunEvent, { kind: 'worktree-sweep' }> | null = null
55
+ for (const event of events) {
56
+ if (event.kind === 'worktree-sweep') {
57
+ latest = event
58
+ }
59
+ }
60
+ return latest
61
+ }
62
+
63
+ /** Latest worktree-sweep event's outcome+source, or null when none exist. */
64
+ export function lastSweepOutcome(
65
+ events: FlowRunEvent[],
66
+ ): SweepOutcomePick | null {
67
+ const event = latestSweepEvent(events)
68
+ if (event === null) {
69
+ return null
70
+ }
71
+ return { outcome: event.outcome, source: event.source }
72
+ }
73
+
74
+ /**
75
+ * AIDEV-NOTE: PMR-PB3Z 2.4 / PMR-TE7Q — full latest worktree-sweep diagnosis
76
+ * (outcome+source+detail+optional delivery evidence), or null when none exist.
77
+ * The sweep engine keys
78
+ * the bounded legacy-noop reconciliation on `detail`, and 3.1's annotation
79
+ * dedupe passes this as the prior outcome into the cleanup engines.
80
+ */
81
+ export function lastSweepDiagnosis(
82
+ events: FlowRunEvent[],
83
+ ): SweepDiagnosisPick | null {
84
+ const event = latestSweepEvent(events)
85
+ if (event === null) {
86
+ return null
87
+ }
88
+ const diagnosis: SweepDiagnosisPick = {
89
+ outcome: event.outcome,
90
+ source: event.source,
91
+ }
92
+ // AIDEV-NOTE: if/else assignment instead of a spread-ternary (PMR-B8MQ);
93
+ // repo-wide rule forbids ternaries (PMR-YG2N constraint 4).
94
+ if (event.detail !== undefined) {
95
+ diagnosis.detail = event.detail
96
+ }
97
+ if (event.annotated !== undefined) {
98
+ diagnosis.annotated = event.annotated
99
+ }
100
+ return diagnosis
101
+ }
102
+
103
+ /**
104
+ * Refs present in a pi-flow runs dir listing: journal/projection suffixes
105
+ * stripped, invalid charsets dropped, deduped, sorted.
106
+ */
107
+ export function refsFromRunsDir(names: string[]): string[] {
108
+ const refs = new Set<string>()
109
+ for (const name of names) {
110
+ let candidate: string | null = null
111
+ if (name.endsWith('.journal.jsonl')) {
112
+ candidate = name.slice(0, -'.journal.jsonl'.length)
113
+ } else if (name.endsWith('.json')) {
114
+ candidate = name.slice(0, -'.json'.length)
115
+ }
116
+ if (candidate !== null && isValidRef(candidate)) {
117
+ refs.add(candidate)
118
+ }
119
+ }
120
+ return [...refs].sort()
121
+ }
122
+
123
+ /**
124
+ * AIDEV-NOTE: PMR-YG2N 3.1 — resolve the worktree a finished flow's done
125
+ * branch should clean up: the live /flow binding first (getFlowWorktree),
126
+ * the aven note second (resolveNoteWorktree). undefined = nothing bound.
127
+ * Never throws — the done branch must not block on resolution failure.
128
+ */
129
+ export async function resolveDoneWorktree(
130
+ pi: ExtensionAPI,
131
+ cwd: string,
132
+ ref: string,
133
+ ): Promise<FlowWorktree | undefined> {
134
+ const attached = getFlowWorktree()
135
+ if (attached !== null && attached.ref === ref) {
136
+ return attached
137
+ }
138
+ try {
139
+ const binding = await resolveNoteWorktree(pi, cwd, ref)
140
+ if (binding.kind === 'bound') {
141
+ return binding.worktree
142
+ }
143
+ } catch {
144
+ // never throw from resolution — the caller treats this as unbound
145
+ }
146
+ return undefined
147
+ }
148
+
149
+ export type NoteBinding =
150
+ | { kind: 'bound'; worktree: FlowWorktree }
151
+ | { kind: 'orphan'; path: string; branch: string | null }
152
+ | { kind: 'gone' }
153
+ | { kind: 'none' }
154
+ | { kind: 'unverifiable'; reason: string }
155
+
156
+ function unverifiableBinding(error: unknown): NoteBinding {
157
+ let reason: string
158
+ if (error instanceof Error) {
159
+ reason = error.message
160
+ } else {
161
+ reason = String(error)
162
+ }
163
+ return { kind: 'unverifiable', reason }
164
+ }
165
+
166
+ /**
167
+ * AIDEV-NOTE: PMR-8SFJ — resolve the worktree an aven note recorded for a
168
+ * ref against live herdr state. Never throws: every fallible step (aven
169
+ * show, herdr list) degrades to 'unverifiable'. The bound result's ref is
170
+ * the ticket-read ref and its branch is the herdr-authoritative one, so
171
+ * cleanupFlowWorktree's ref-invariant (worktree.ref === ref) holds by
172
+ * construction.
173
+ */
174
+ export async function resolveNoteWorktree(
175
+ pi: ExtensionAPI,
176
+ cwd: string,
177
+ ref: string,
178
+ worktrees?: HerdrWorktree[],
179
+ ): Promise<NoteBinding> {
180
+ let stdout: string | null = null
181
+ try {
182
+ stdout = await avenShowFull(ref)
183
+ } catch (error: unknown) {
184
+ return unverifiableBinding(error)
185
+ }
186
+ if (stdout === null) {
187
+ return { kind: 'unverifiable', reason: 'aven show failed' }
188
+ }
189
+ const note = latestWorktreeNote(stdout)
190
+ if (note === null) {
191
+ return { kind: 'none' }
192
+ }
193
+ if (!existsSync(note.path)) {
194
+ return { kind: 'gone' }
195
+ }
196
+ let list: HerdrWorktree[]
197
+ if (worktrees !== undefined) {
198
+ list = worktrees
199
+ } else {
200
+ try {
201
+ list = await worktreeList(pi, cwd)
202
+ } catch (error: unknown) {
203
+ return unverifiableBinding(error)
204
+ }
205
+ }
206
+ let found: HerdrWorktree | null = null
207
+ if (note.branch !== null) {
208
+ found = matchHerdrWorktree(list, note.branch)
209
+ } else {
210
+ for (const w of list) {
211
+ if (w.isLinked && w.path === note.path) {
212
+ found = w
213
+ break
214
+ }
215
+ }
216
+ }
217
+ if (found === null) {
218
+ // AIDEV-NOTE: PMR-PB3Z 2.1 — the note path exists on disk but herdr no
219
+ // longer tracks a worktree for it: an orphaned on-disk worktree, not a
220
+ // gone one. Carries the note's path+branch for the guarded orphan
221
+ // cleanup engine (routed in by sweepMergedFlowWorktrees, subtask 2.3).
222
+ return { kind: 'orphan', path: note.path, branch: note.branch }
223
+ }
224
+ return {
225
+ kind: 'bound',
226
+ worktree: { ref, path: found.path, branch: found.branch },
227
+ }
228
+ }
229
+
230
+ export interface SweepCandidateInput {
231
+ mode: 'work' | 'personal'
232
+ gitRoot: string
233
+ }
234
+
235
+ /**
236
+ * Latest run-input's { mode, gitRoot } from the journal, or null when the
237
+ * journal has none. Reuses resumeSeedFromEvents with an always-true
238
+ * gitRootExists so the pick is identical to the resume path.
239
+ */
240
+ export function sweepCandidateInput(
241
+ events: FlowRunEvent[] | null,
242
+ ): SweepCandidateInput | null {
243
+ const seed = resumeSeedFromEvents(events, () => true)
244
+ if (seed.input === undefined) return null
245
+ return { mode: seed.input.mode, gitRoot: seed.input.gitRoot }
246
+ }
247
+
248
+ export interface SweepDeps {
249
+ listRefs: () => Promise<string[]>
250
+ readEvents: (ref: string) => Promise<FlowRunEvent[]>
251
+ appendEvent: (event: FlowRunEvent) => Promise<void>
252
+ readLabels: (ref: string) => Promise<string[] | null>
253
+ // AIDEV-NOTE: PMR-TE7Q — the production seam returns writeAvenNote's
254
+ // boolean; CleanupAnnotate retains legacy Promise<void> injections.
255
+ annotate: CleanupAnnotate
256
+ sessionGitRoot: () => Promise<string | null>
257
+ notify?: (message: string, level: 'info' | 'warning') => void
258
+ }
259
+
260
+ /**
261
+ * AIDEV-NOTE: PMR-PB3Z 2.3 — shared post-cleanup journaling + notify for
262
+ * the bound and orphan paths. Both engines return the same
263
+ * CleanupFlowWorktreeSummary vocabulary, so the worktree-sweep marker is
264
+ * identical either way; only the outcome notify wording differs ('orphaned'
265
+ * when herdr no longer tracks the worktree). Delivery failures additionally
266
+ * warn on both paths. Identical non-terminal outcome notifies stay quiet;
267
+ * marker/notify failures change nothing else.
268
+ */
269
+ async function journalSweepOutcome(
270
+ deps: SweepDeps,
271
+ ref: string,
272
+ summary: CleanupFlowWorktreeSummary,
273
+ orphaned: boolean,
274
+ prior: SweepDiagnosisPick | null,
275
+ ): Promise<void> {
276
+ try {
277
+ const event: Extract<FlowRunEvent, { kind: 'worktree-sweep' }> = {
278
+ kind: 'worktree-sweep',
279
+ at: new Date().toISOString(),
280
+ ref,
281
+ source: 'sweep',
282
+ outcome: summary.action,
283
+ detail: summary.reason,
284
+ }
285
+ if (summary.annotated !== undefined) {
286
+ event.annotated = summary.annotated
287
+ }
288
+ await deps.appendEvent(event)
289
+ } catch {
290
+ // A failed marker changes nothing else.
291
+ }
292
+ if (summary.annotated === false && deps.notify !== undefined) {
293
+ try {
294
+ deps.notify(
295
+ `Sweep: cleanup annotation delivery failed for ${ref}; the next identical sweep retries the note (${summary.reason})`,
296
+ 'warning',
297
+ )
298
+ } catch {
299
+ // A failed notify changes nothing else.
300
+ }
301
+ }
302
+ // AIDEV-NOTE: PMR-7RJA — identical non-terminal retries keep journaling
303
+ // and retrying quietly; changed states and terminal outcomes still notify.
304
+ // The independent annotated=false delivery warning above always fires.
305
+ // PMR-V31Z 3.2: 'removed' is the only outcome that notifies — the only
306
+ // non-terminal outcome left is 'deferred', which stays quiet.
307
+ const identicalNonTerminal =
308
+ prior !== null &&
309
+ !isTerminalSweepOutcome(summary.action) &&
310
+ prior.outcome === summary.action &&
311
+ prior.detail === summary.reason
312
+ if (!identicalNonTerminal && summary.action === 'removed') {
313
+ if (deps.notify !== undefined) {
314
+ let message: string
315
+ if (orphaned) {
316
+ message = `Sweep: removed orphaned flow worktree for ${ref}`
317
+ } else {
318
+ message = `Sweep: removed flow worktree for ${ref}`
319
+ }
320
+ try {
321
+ deps.notify(message, 'info')
322
+ } catch {
323
+ // A failed notify changes nothing else.
324
+ }
325
+ }
326
+ }
327
+ }
328
+
329
+ /**
330
+ * AIDEV-NOTE: PMR-YG2N — background sweep engine over run-journal refs.
331
+ * Never-throw by construction: only truly global steps (sessionGitRoot,
332
+ * worktreeList) short-circuit the whole sweep by return — fail-closed; every
333
+ * per-ref fallible step is locally try/caught so one bad ref never rejects
334
+ * the sweep nor poisons the others. Local-only filters (terminal marker,
335
+ * gitRoot match) run before any per-ref aven exec. The labels-done gate
336
+ * below is what makes this sweep safe for in-flight flows: an active loop
337
+ * always carries un-set phase labels, so `nextPhase(labels, mode)` can never
338
+ * return 'done' for a flow that is still running — no active-loop skip-list
339
+ * is needed, and refs failing the gate get no marker so they are retried by
340
+ * a later sweep once they finish.
341
+ * AIDEV-NOTE: PMR-PB3Z 2.4 — the terminal skip has exactly ONE exception:
342
+ * a terminal `noop` whose latest detail is the exact legacy string
343
+ * `recorded worktree gone or absent from herdr` (written before the orphan
344
+ * path existed) falls through once so the ref is re-resolved — an on-disk
345
+ * orphan reaches the guarded engine, a truly absent path re-marks terminal
346
+ * with the new verified-absent detail. After a successful marker rewrite,
347
+ * the new detail never matches the legacy string and later sweeps skip
348
+ * before aven. Journal-write failures retain ordinary retry semantics.
349
+ */
350
+ export async function sweepMergedFlowWorktrees(
351
+ pi: ExtensionAPI,
352
+ effects: EffectJournal,
353
+ cwd: string,
354
+ deps: SweepDeps,
355
+ ): Promise<void> {
356
+ let sessionRoot: string | null
357
+ try {
358
+ sessionRoot = await deps.sessionGitRoot()
359
+ } catch {
360
+ return
361
+ }
362
+ if (sessionRoot === null) {
363
+ return
364
+ }
365
+
366
+ let sharedWorktrees: HerdrWorktree[]
367
+ try {
368
+ // AIDEV-NOTE: fetched once and shared across all refs — no re-list per ref.
369
+ sharedWorktrees = await worktreeList(pi, cwd)
370
+ } catch {
371
+ return
372
+ }
373
+ // AIDEV-NOTE: PMR-PB3Z 2.3 — an empty Herdr list is not proof that no
374
+ // on-disk orphans exist. Continue to the journal-backed refs so the last
375
+ // remaining orphan still reaches the guarded cleanup engine.
376
+
377
+ let refs: string[]
378
+ try {
379
+ refs = await deps.listRefs()
380
+ } catch {
381
+ return
382
+ }
383
+
384
+ for (const ref of refs) {
385
+ let events: FlowRunEvent[]
386
+ try {
387
+ events = await deps.readEvents(ref)
388
+ } catch {
389
+ continue
390
+ }
391
+ const prior = lastSweepDiagnosis(events)
392
+ // AIDEV-NOTE: PMR-TE7Q — only a marker with annotated=true is proof of
393
+ // delivery and becomes priorOutcome. False or legacy/absent delivery
394
+ // evidence retries the note; markers still preserve each diagnosis.
395
+ let priorOutcome:
396
+ | { action: CleanupFlowWorktreeSummary['action']; reason: string }
397
+ | undefined
398
+ if (prior !== null && prior.annotated === true) {
399
+ let priorReason = ''
400
+ if (prior.detail !== undefined) {
401
+ priorReason = prior.detail
402
+ }
403
+ priorOutcome = { action: prior.outcome, reason: priorReason }
404
+ }
405
+ if (prior !== null && isTerminalSweepOutcome(prior.outcome)) {
406
+ // AIDEV-NOTE: PMR-PB3Z 2.4 — the single terminal-skip exception: a
407
+ // legacy gone-noop (exact old detail, written before the orphan
408
+ // binding existed) falls through ONCE so 2.1/2.3 re-resolve it — an
409
+ // on-disk orphan reaches the guarded engine, a truly absent path
410
+ // re-marks terminal with the new verified-absent detail. Once that
411
+ // marker is persisted, its detail no longer matches the exception.
412
+ // Failed marker writes leave the legacy state intact for a retry.
413
+ if (
414
+ prior.outcome === 'noop' &&
415
+ prior.detail === LEGACY_GONE_NOOP_DETAIL
416
+ ) {
417
+ // fall through to re-resolution
418
+ } else {
419
+ continue
420
+ }
421
+ }
422
+ const candidate = sweepCandidateInput(events)
423
+ if (candidate === null) {
424
+ continue
425
+ }
426
+ if (candidate.gitRoot !== sessionRoot) {
427
+ continue
428
+ }
429
+
430
+ let labels: string[] | null
431
+ try {
432
+ labels = await deps.readLabels(ref)
433
+ } catch {
434
+ continue
435
+ }
436
+ if (labels === null) {
437
+ // No marker: label-read failure is retried by a later sweep.
438
+ continue
439
+ }
440
+ // AIDEV-NOTE: PMR-YG2N — the labels-done gate. Runs before
441
+ // resolveNoteWorktree and before anything destructive (see note above).
442
+ const phase = nextPhase(labels, candidate.mode)
443
+ if (phase.kind !== 'done') {
444
+ // No marker: not-done refs are retried later.
445
+ continue
446
+ }
447
+
448
+ let binding: NoteBinding
449
+ try {
450
+ binding = await resolveNoteWorktree(pi, cwd, ref, sharedWorktrees)
451
+ } catch {
452
+ // No marker: unverifiable refs are retried by a later sweep.
453
+ continue
454
+ }
455
+ if (binding.kind === 'unverifiable') {
456
+ continue
457
+ }
458
+ if (binding.kind === 'orphan') {
459
+ // AIDEV-NOTE: PMR-PB3Z 2.3 — orphan bindings (note path on disk, no
460
+ // herdr record) route to the guarded orphan engine, which removes via
461
+ // a DECLARED git worktree remove (herdr cannot serve: no record).
462
+ // Same never-throw guard as the bound path: an engine throw leaves NO
463
+ // marker, so a later sweep retries the ref.
464
+ let orphanSummary: CleanupFlowWorktreeSummary
465
+ try {
466
+ orphanSummary = await cleanupOrphanedWorktree(pi, effects, {
467
+ ref,
468
+ mode: candidate.mode,
469
+ path: binding.path,
470
+ branch: binding.branch,
471
+ cwd,
472
+ annotate: deps.annotate,
473
+ priorOutcome,
474
+ })
475
+ } catch {
476
+ continue
477
+ }
478
+ await journalSweepOutcome(deps, ref, orphanSummary, true, prior)
479
+ continue
480
+ }
481
+ if (binding.kind === 'none' || binding.kind === 'gone') {
482
+ let detail: string
483
+ if (binding.kind === 'none') {
484
+ detail = 'no recorded worktree note'
485
+ } else {
486
+ // AIDEV-NOTE: PMR-YG2N fix round — 'gone' means the note EXISTS but
487
+ // its recorded worktree path is absent from disk; the old wording
488
+ // ('no existing worktree note') was misleading. PMR-PB3Z 2.3 — the
489
+ // detail now says exactly that, and deliberately differs from the
490
+ // legacy string ('recorded worktree gone or absent from herdr'):
491
+ // subtask 2.4's bounded legacy-noop reconciliation keys on the old
492
+ // wording, so terminal markers written from here on must never
493
+ // match it.
494
+ detail = 'recorded worktree gone: path verified absent from disk'
495
+ }
496
+ try {
497
+ await deps.appendEvent({
498
+ kind: 'worktree-sweep',
499
+ at: new Date().toISOString(),
500
+ ref,
501
+ source: 'sweep',
502
+ outcome: 'noop',
503
+ detail,
504
+ })
505
+ } catch {
506
+ // A failed marker changes nothing else.
507
+ }
508
+ continue
509
+ }
510
+
511
+ let summary: CleanupFlowWorktreeSummary
512
+ try {
513
+ summary = await cleanupFlowWorktree(pi, effects, {
514
+ ref,
515
+ mode: candidate.mode,
516
+ worktree: binding.worktree,
517
+ cwd,
518
+ annotate: deps.annotate,
519
+ priorOutcome,
520
+ })
521
+ } catch {
522
+ continue
523
+ }
524
+ await journalSweepOutcome(deps, ref, summary, false, prior)
525
+ }
526
+ }