@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
package/index.ts ADDED
@@ -0,0 +1,3206 @@
1
+ // AIDEV-NOTE: PMR-T22H — index.ts is wiring only. Boundaries: aven/client.ts
2
+ // owns every aven shell-out; config.ts owns config + mode resolution;
3
+ // tools/* own the four agent tools; flow/phase-command.ts owns the 5 phase
4
+ // commands; spec-review/commands.ts owns the spec commands. What stays here:
5
+ // the extension entrypoint, the enforcement interceptors, the flow loop
6
+ // wiring, and /flow + /herdr-sync + /flow-view + /flow-view-replay.
7
+
8
+ import { spawn } from 'node:child_process'
9
+ import { randomBytes } from 'node:crypto'
10
+ import { existsSync, promises as fs, readFileSync } from 'node:fs'
11
+ import { readdir } from 'node:fs/promises'
12
+ import { join } from 'node:path'
13
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
14
+ import {
15
+ getAgentDir,
16
+ isToolCallEventType,
17
+ } from '@earendil-works/pi-coding-agent'
18
+ import type { AssignmentRecord } from '@gtheys/pi-interactive-subagents'
19
+ import {
20
+ hasLiveAssignmentForParent,
21
+ hasPendingAskForParent,
22
+ listAssignments,
23
+ onFlowSpawn,
24
+ } from '@gtheys/pi-interactive-subagents'
25
+ import {
26
+ adhocCloseMain,
27
+ adhocSettled,
28
+ configureAdhoc,
29
+ createAdhocTracker,
30
+ } from './adhoc/tracker.ts'
31
+ import {
32
+ applyAvenErrorLabel,
33
+ avenExec,
34
+ discoverAvenPrefixes,
35
+ ensureLabels,
36
+ epicHasOpenChildren,
37
+ lastAvenResolutionFailure,
38
+ listReadyTickets,
39
+ readAvenLabels,
40
+ readAvenSnapshot,
41
+ readFreshBlockers,
42
+ readJiraRef,
43
+ readPlanRevision,
44
+ readPlanState,
45
+ removeAvenLabel,
46
+ setAvenSessionCwd,
47
+ writeAvenNote,
48
+ writeGateAnswer,
49
+ } from './aven/client.ts'
50
+ import { listTicketStatuses } from './aven/status.ts'
51
+ import {
52
+ loadConfig,
53
+ resolveLokiSettings,
54
+ resolveMode,
55
+ resolveNotifySettings,
56
+ resolveRunServerEnabled,
57
+ saveViewerPlacement,
58
+ } from './config.ts'
59
+ import {
60
+ type AnswerDeps,
61
+ answerUsageText,
62
+ executeFlowAnswer,
63
+ parseFlowAnswerArgs,
64
+ } from './flow/answer.ts'
65
+ import { wakeOnGateAnswer } from './flow/answer-wake.ts'
66
+ import { FLOW_USAGE, type FlowArgs, parseFlowArgs } from './flow/args.ts'
67
+ import { createAskEmitter } from './flow/ask-emitter.ts'
68
+ import { spawnJournalTarget } from './flow/attribution.ts'
69
+ import {
70
+ consumeAwaitingSpecApproval,
71
+ isAwaitingSpecApproval,
72
+ } from './flow/awaiting-approval.ts'
73
+ import {
74
+ type HealResult,
75
+ healFlowBinding,
76
+ recoveryCommand,
77
+ } from './flow/binding-heal.ts'
78
+ import { pushToGateway } from './flow/cost.ts'
79
+ import { createCostAutoPush } from './flow/cost-autopush.ts'
80
+ import {
81
+ type FlowCostDeps,
82
+ registerFlowCostCommand,
83
+ } from './flow/cost-command.ts'
84
+ import {
85
+ type DurableRefDeps,
86
+ deriveFlowRefsDetailed,
87
+ deriveParkedCandidates,
88
+ type FlowRefDerivation,
89
+ type ParkedCandidate,
90
+ } from './flow/durable-refs.ts'
91
+ import { mergeIntercept, runsJournalWriteBlock } from './flow/effect-gate.ts'
92
+ import type { OpenGate } from './flow/gates.ts'
93
+ import { collectOpenGates, createGateDeps } from './flow/gates.ts'
94
+ import { resolveJiraEpic } from './flow/jira-ref.ts'
95
+ import {
96
+ lifecycleLabelMutation,
97
+ receiptMetadataMutation,
98
+ } from './flow/label-gate.ts'
99
+ import { landingIntercept } from './flow/land-gate.ts'
100
+ import {
101
+ type PrEffectProbe,
102
+ reconcileTerminalEntry,
103
+ resolveCloseoutProofs,
104
+ } from './flow/lifecycle-policy.ts'
105
+ import {
106
+ createFlowLoop,
107
+ type FlowLoop,
108
+ resumePlanApprovalOpenFromEvents,
109
+ resumeV2StateFromEvents,
110
+ } from './flow/loop.ts'
111
+ import { nextPhase } from './flow/orchestrate.ts'
112
+ import {
113
+ commandPhaseInput,
114
+ registerPhaseCommands,
115
+ } from './flow/phase-command.ts'
116
+ import {
117
+ isPickerInvocation,
118
+ planPickerOutcome,
119
+ planTicketPickerOutcome,
120
+ splitGateValue,
121
+ TICKET_ROW_VALUE,
122
+ } from './flow/picker.ts'
123
+ import { deleteGroup, fetchGroupBody } from './flow/push.ts'
124
+ import {
125
+ type ReconcileCommandDeps,
126
+ registerReconcileCommand,
127
+ } from './flow/reconcile-command.ts'
128
+ import { createReconcileDeps, listJournalRefs } from './flow/reconcile-deps.ts'
129
+ import {
130
+ parseRefKind,
131
+ registerAvenPrefixes,
132
+ trackingRef,
133
+ } from './flow/ref-kind.ts'
134
+ import {
135
+ mergeSeedInput,
136
+ resumeSeedFromEvents,
137
+ runInputRecord,
138
+ } from './flow/resume.ts'
139
+ import {
140
+ ownerPidAlive,
141
+ planResumePickerOutcome,
142
+ type ResumeSelection,
143
+ } from './flow/resume-picker.ts'
144
+ import { hasActiveFlowRun } from './flow/run-liveness.ts'
145
+ import {
146
+ type DashboardToggleOutcome,
147
+ initFlowWidget,
148
+ refreshAfterSettle,
149
+ refreshFlowWidget,
150
+ toggleFlowDashboardPin,
151
+ type WidgetAssignment,
152
+ } from './flow/widget.ts'
153
+ import {
154
+ type FlowBindingSnapshot,
155
+ type FlowWorktree,
156
+ getActiveFlowRef,
157
+ parseFlowBindingSnapshot,
158
+ reactivateFlowRef,
159
+ restoreFlowBinding,
160
+ setActiveFlowRef,
161
+ setBindingChangeListener,
162
+ } from './flow/worktree-context.ts'
163
+ import type { FlowDiagramDeps } from './flow-diagram/command.ts'
164
+ import {
165
+ diagramStamp,
166
+ registerFlowDiagramCommand,
167
+ } from './flow-diagram/command.ts'
168
+ import { loadHpRenderer } from './flow-diagram/vendor/harness-profiler/load.ts'
169
+ import {
170
+ preflightRepo,
171
+ resolveRepoRoot,
172
+ resolveSessionRepoRoot,
173
+ syncHerdrPlugin,
174
+ } from './herdr/sync.ts'
175
+ import {
176
+ decidePlacement,
177
+ FlowHerdrViewer,
178
+ isValidRef,
179
+ parseViewerPlacement,
180
+ pluginVersionStatus,
181
+ } from './herdr/viewer.ts'
182
+ import { MODE_PROFILE } from './mode-profile.ts'
183
+ import { registerJiraCreateBranch } from './plan-tools/jira-branch-tool.ts'
184
+ import { registerResolveFeaturePath } from './plan-tools/resolve-feature-path.ts'
185
+ import { registerResolveNotesPath } from './plan-tools/resolve-notes-path.ts'
186
+ import { registerResolveSpecPath } from './plan-tools/resolve-spec-path.ts'
187
+ import prQualityExtension from './pr-quality/index.ts'
188
+ import reviewExtension from './review/review.ts'
189
+ import {
190
+ createEffectJournal,
191
+ type FlowRunEvent,
192
+ isYoloRun,
193
+ isYoloRunCurrent,
194
+ projectRunState,
195
+ readRunEvents,
196
+ readRunMode,
197
+ readRunState,
198
+ runStatePath,
199
+ } from './run-state.ts'
200
+ import { resolveRunTitle } from './run-title.ts'
201
+ import { type ResumeConsumerDeps, resumeParkedRun } from './server/consumer.ts'
202
+ import { pendingDirPath } from './server/daemon.ts'
203
+ import {
204
+ ensureDaemon,
205
+ realPidAlive,
206
+ restartDaemon,
207
+ } from './server/lifecycle.ts'
208
+ import {
209
+ checkDaemonStaleness,
210
+ handleDaemonStaleness,
211
+ resolveHeadSha,
212
+ resolveMainCheckout,
213
+ sessionStalenessDeps,
214
+ } from './server/staleness.ts'
215
+ import {
216
+ createDaemonAliveProbe,
217
+ createEventWriter,
218
+ type EventWriter,
219
+ } from './server/writer.ts'
220
+ import sonarqubeExtension from './sonarqube/sonarqube.ts'
221
+ import { registerSpecCommands } from './spec-review/commands.ts'
222
+ import { registerOpenInPane } from './spec-review/open-in-pane.ts'
223
+ import {
224
+ createEventFanoutWriter,
225
+ createTelemetryHandlers,
226
+ type FanoutHandlers,
227
+ lokiPushSettings,
228
+ } from './telemetry/dispatch.ts'
229
+ import { registerTelemetry } from './telemetry/index.ts'
230
+ import type { LokiSettings } from './telemetry/loki.ts'
231
+ import { registerCodeReviewTool } from './tools/code-review.ts'
232
+ import { buildCodeReviewGatePrompt } from './tools/code-review-parse.ts'
233
+ import { registerDeviationReviewTool } from './tools/deviation.ts'
234
+ import { registerFlowSubmitTool } from './tools/flow-submit.ts'
235
+ import {
236
+ createLandingState,
237
+ defaultSuiteRunner,
238
+ registerLandTool,
239
+ } from './tools/land.ts'
240
+ import { registerPhaseCompleteTool } from './tools/phase-complete.ts'
241
+ import { productionReviewDeps } from './tools/review-deps.ts'
242
+ import {
243
+ createAttemptLedger,
244
+ registerRunAttemptTool,
245
+ } from './tools/run-attempt.ts'
246
+ import { registerSpecApproveTool } from './tools/spec-approve.ts'
247
+ import {
248
+ type CleanupFlowWorktreeSummary,
249
+ cleanupFlowWorktree,
250
+ default as worktreeExtension,
251
+ } from './worktree/index.ts'
252
+ import {
253
+ refsFromRunsDir,
254
+ resolveDoneWorktree,
255
+ sweepMergedFlowWorktrees,
256
+ } from './worktree/sweep.ts'
257
+
258
+ // AIDEV-NOTE: test-facing export surface (PMR-T22H) — tests import these
259
+ // from index.ts; the implementations now live in the boundary modules.
260
+ export {
261
+ readAvenLabels,
262
+ readGateAnswer,
263
+ setAvenSessionCwd,
264
+ specApprove,
265
+ writeGateAnswer,
266
+ } from './aven/client.ts'
267
+ export {
268
+ loadConfig,
269
+ readConfigFile,
270
+ resolveLokiSettings,
271
+ resolveMode,
272
+ resolveNotifySettings,
273
+ resolveRunServerEnabled,
274
+ saveViewerPlacement,
275
+ } from './config.ts'
276
+
277
+ // AIDEV-NOTE: PMR-XTQQ — best-effort journal write seam. Writers route
278
+ // through the mode-aware writer: journal-only while the durable run server
279
+ // owns the projection (per-write liveness probe), today's full writer path
280
+ // when absent. Journal failures must never break a flow phase; aven labels
281
+ // remain the gate source of truth.
282
+
283
+ // AIDEV-NOTE: production wiring for the /flow answer dispatch lives INSIDE
284
+ // the extension closure below (makeAnswerDeps) so the answer path's journal
285
+ // appends route through the mode-aware writer seam.
286
+
287
+ // Shared by /flow dashboard and the alt+shift+d shortcut — one notify surface so the
288
+ // keyboard path and the command path always stay in parity.
289
+ type DashboardNotifyLevel = 'info' | 'warning' | 'error'
290
+ type DashboardNotifyCtx = {
291
+ ui: { notify: (message: string, level?: DashboardNotifyLevel) => void }
292
+ }
293
+
294
+ function notifyDashboardOutcome(
295
+ ctx: DashboardNotifyCtx,
296
+ outcome: DashboardToggleOutcome,
297
+ ): void {
298
+ if (outcome === 'no-content') {
299
+ ctx.ui.notify(
300
+ 'No flow content to show — the dashboard appears when a flow is active.',
301
+ 'info',
302
+ )
303
+ } else if (outcome === 'pinned') {
304
+ ctx.ui.notify(
305
+ 'Flow dashboard pinned — /flow dashboard or alt+shift+d to hide.',
306
+ 'info',
307
+ )
308
+ } else {
309
+ ctx.ui.notify('Flow dashboard hidden.', 'info')
310
+ }
311
+ }
312
+
313
+ // AIDEV-NOTE: PMR-XQZM — pure subagent-child check, OR-pair convention
314
+ // (pi-interactive-subagents index.ts:1155-1157): !!PI_SUBAGENT_SESSION ||
315
+ // !!PI_SUBAGENT_ID, stamped exec-time on fresh spawns AND subagent_resume.
316
+ // Gate on the OR-pair ONLY — resumed children lack PI_SUBAGENT_AGENT /
317
+ // PI_DENY_TOOLS / PI_SUBAGENT_WORKTREE, and unstamped panes (manual open /
318
+ // intercom handover) keep today's behavior. Set-but-empty counts as absent
319
+ // (matches the !! semantics). Replicated per package on purpose: AGENTS.md
320
+ // forbids cross-package runtime deps.
321
+ export function isSubagentSession(
322
+ env: Record<string, string | undefined>,
323
+ ): boolean {
324
+ const session = env.PI_SUBAGENT_SESSION
325
+ if (typeof session === 'string' && session !== '') {
326
+ return true
327
+ }
328
+ const id = env.PI_SUBAGENT_ID
329
+ return typeof id === 'string' && id !== ''
330
+ }
331
+
332
+ // AIDEV-NOTE: PMR-T9ZQ 3.1 — the seam now derives rich PARKED CANDIDATES
333
+ // (not bare refs): the cross-session resume paths must know the candidate's
334
+ // phase/status/owner/worktree history before they render the consent menu.
335
+ // Production defaults resolve the session gitRoot and scan the pending-run
336
+ // records; tests inject fakes via the optional second parameter.
337
+ export interface DurableRebindDeps {
338
+ deriveCandidates: () => Promise<ParkedCandidate[]>
339
+ heal: (ref: string, cwd: string) => Promise<HealResult>
340
+ // AIDEV-NOTE: PMR-1KXH — wall clock (ms) for the settle-scan cooldown,
341
+ // injectable so tests advance the window without sleeps. Defaults to
342
+ // Date.now.
343
+ now?: () => number
344
+ // AIDEV-NOTE: PMR-YG18 — stderr sink for the headless resume-picker
345
+ // fallback lines. In print/json modes ctx.hasUI is false and pi binds the
346
+ // no-op uiContext, so ctx.ui.notify drops the recovery lines entirely;
347
+ // stderr is the only channel those modes surface. Injectable so tests
348
+ // observe the channel without monkeypatching process.stderr. Defaults to
349
+ // process.stderr.write.
350
+ writeStderr?: (line: string) => void
351
+ // AIDEV-NOTE: PMR-XQZM — child-session env for the subagent consent gate.
352
+ // Optional like now/writeStderr; production wires process.env (durableRebind
353
+ // construction below), tests inject explicit objects so the gate is
354
+ // decidable without touching the real process env.
355
+ env?: Record<string, string | undefined>
356
+ }
357
+
358
+ // AIDEV-NOTE: PMR-T9ZQ — one-line decline notice for the resume picker: the
359
+ // session stays clean, the recovery commands are the whole message. Pure so
360
+ // the wiring test can pin the exact shape.
361
+ function resumeDeclineMessage(refs: string[]): string {
362
+ let commands = ''
363
+ for (let i = 0; i < refs.length; i++) {
364
+ if (i > 0) {
365
+ commands += ' / '
366
+ }
367
+ commands += recoveryCommand(refs[i])
368
+ }
369
+ return `pi-flow: resume declined — this session stays clean. Recover with ${commands}.`
370
+ }
371
+
372
+ // The consent prompt for a parked cross-session run. Select rows are
373
+ // rendered from flow/resume-picker.ts labels, so the title stays generic.
374
+ const RESUME_SELECT_TITLE = 'Parked flow runs in this repo — resume one?'
375
+
376
+ // AIDEV-NOTE: PMR-T9ZQ — the ctx surface askResumeThenArm needs. Structurally
377
+ // narrowed (same shape as pickReadyTicketRef) so command, session_start and
378
+ // agent_settled contexts all fit without importing Pi internals.
379
+ type ResumeAskCtx = {
380
+ cwd: string
381
+ hasUI: boolean
382
+ ui: {
383
+ notify(message: string, level?: 'info' | 'warning' | 'error'): void
384
+ select(title: string, options: string[]): Promise<string | undefined>
385
+ }
386
+ }
387
+
388
+ // AIDEV-NOTE: PMR-T9ZQ — module-level ask latch, per PROCESS (so a settle
389
+ // firing while a startup select is open can never stack a second prompt).
390
+ // askResumeThenArm flips it to 'asking' SYNCHRONOUSLY before awaiting
391
+ // ctx.ui.select and to 'done' after any completed ask (pick, cancel, or a
392
+ // fail-closed throw). The startup path calls askResumeThenArm unconditionally
393
+ // (every new session asks at most once anyway); the agent_settled belt-and-
394
+ // braces path (subtask 3.2) must gate on 'idle'.
395
+ type ResumeAskState = 'idle' | 'asking' | 'done'
396
+ let resumeAskState: ResumeAskState = 'idle'
397
+
398
+ // AIDEV-NOTE: PMR-1KXH — cooldown for the agent_settled belt-and-braces
399
+ // candidate scan. The ask-once latch is only spent when candidates are
400
+ // FOUND, so every clean-session settle used to re-run deriveCandidates (an
401
+ // uncached `git rev-parse` plus a read+parse+projection of EVERY pending
402
+ // record) just to find nothing. An EMPTY settle scan now arms this window:
403
+ // further settles inside it skip the scan entirely. Deliberately NOT
404
+ // touched: session_start (always scans), the ask-once latch (an empty scan
405
+ // still leaves it 'idle'), and non-empty scans (the latch pins those). Worst
406
+ // case a run parked mid-window is discovered one cooldown later — bounded,
407
+ // and the prompt-once contract is unchanged. 60s because settles fire once
408
+ // per turn: quick tool-heavy turns are where the wasted scans stack up,
409
+ // while a minute of deferred discovery is invisible next to a parked run's
410
+ // lifetime.
411
+ export const EMPTY_SETTLE_SCAN_COOLDOWN_MS = 60_000
412
+
413
+ // AIDEV-NOTE: PMR-DRKH — injectable IO seam for the session_start durable
414
+ // rebind (plan 3.1). Production defaults resolve the session gitRoot and
415
+ // scan the pending-run records (same construction as the worktreeExtension
416
+ // deriveFlowRefs wiring); tests inject fakes via the optional second
417
+ // parameter on the extension factory.
418
+ export default function (
419
+ pi: ExtensionAPI,
420
+ durableRebindDeps?: DurableRebindDeps,
421
+ ) {
422
+ // AIDEV-NOTE: PMR-XTQQ — runServer.enabled kill switch (default true).
423
+ // Synced from config at session_start (deviation JKD6RFC0MYY3N29C: the
424
+ // switch must be live from extension init, not only from the first /flow,
425
+ // so a disabled session gets exactly today's full-writer/no-injection
426
+ // behavior before any /flow ran) and re-synced at every /flow start.
427
+ // false = the probe always reports absent (full-writer path permanently),
428
+ // ensureDaemon never spawns, and the pending consumer is a no-op.
429
+ let runServerEnabled = true
430
+ // AIDEV-NOTE: PMR-XTQQ subtask 3.3 — in-process per-ref latch for the
431
+ // pending-record consumer. Added on a successful consumption attempt
432
+ // (before the /flow injection), cleared when the /flow start path runs so
433
+ // a real rerun re-arms the consumer. agent_settled fires often; the latch
434
+ // plus the rename-first ENOENT contract makes repeated settles no-ops.
435
+ const resumeLatch = new Set<string>()
436
+ // AIDEV-NOTE: PMR-DMHH subtask 2.1 — per-ref latch for the gate-answer
437
+ // wake (decision logic in flow/answer-wake.ts). Two kinds: 'rearm' (a
438
+ // `/flow <ref>` resume injection is in flight — survives until the /flow
439
+ // start path clears it, mirroring resumeLatch's lifecycle, so a queued
440
+ // but not-yet-executed /flow blocks a second injection) and 'plain' (a
441
+ // standalone plain wake — superseded by each new human answer for that
442
+ // ref, so reject → revise → approve wakes again). A send throw clears its
443
+ // own entry inside wakeOnGateAnswer, so a failed injection stays
444
+ // retryable.
445
+ const gateWakeLatch = new Map<string, 'rearm' | 'plain'>()
446
+ // AIDEV-NOTE: the ref of the restored session binding (PMR-PJM0), when
447
+ // one exists — the only ref the agent_settled consumer checks. session_start
448
+ // fires before any settle, so this is always populated before use.
449
+ // PMR-T9ZQ 3.2: a NULL boundRef no longer means "the settle path does
450
+ // nothing" — it means this session owns no restored run, so the settle path
451
+ // may run the consent picker for a late parked candidate (never a silent
452
+ // rebind).
453
+ let boundRef: string | null = null
454
+
455
+ // AIDEV-NOTE: PMR-XTQQ subtask 3.3 — shared consumer deps. Pure-ish:
456
+ // sender + io live behind these closures so tests never need a live pi.
457
+ function resumeConsumerDeps(ref: string): ResumeConsumerDeps {
458
+ return {
459
+ ref,
460
+ agentDir: getAgentDir(),
461
+ pendingDir: pendingDirPath(getAgentDir()),
462
+ enabled: () => runServerEnabled,
463
+ loopActive: () => loop.isActive(),
464
+ latch: resumeLatch,
465
+ notify: (message, level) => {
466
+ if (notifyUser !== null) notifyUser(message, level)
467
+ },
468
+ send: (message) => {
469
+ pi.sendUserMessage(message, { expandPromptTemplates: true })
470
+ },
471
+ }
472
+ }
473
+ // AIDEV-NOTE: PMR-86NN + PMR-T9ZQ — single construction site for the
474
+ // production durable-run scanner deps, shared by the two derive modes:
475
+ // deriveFlowRefs (plain refs — the worktree bind self-heal seam) and
476
+ // deriveParkedCandidates (rich records — the resume picker). One site so
477
+ // the two can never drift. Resolves the session gitRoot at call time
478
+ // (same `git rev-parse --show-toplevel` semantics as the sweep's journal
479
+ // filter) and reuses the pendingDir construction from the resume
480
+ // consumer; gitRoot resolution failure fails closed (null => empty list).
481
+ const durableScanDeps = async (): Promise<DurableRefDeps | null> => {
482
+ const gitRoot = await resolveSessionRepoRoot(pi)
483
+ if (gitRoot === null) {
484
+ return null
485
+ }
486
+ return {
487
+ agentDir: getAgentDir(),
488
+ pendingDir: pendingDirPath(getAgentDir()),
489
+ io: {
490
+ readdir: (dir) => readdir(dir),
491
+ readFile: (p) => fs.readFile(p, 'utf8'),
492
+ },
493
+ readRunEvents: (agentDir, ref, io) => readRunEvents(agentDir, ref, io),
494
+ gitRoot,
495
+ }
496
+ }
497
+ const makeDeriveRefsDetailed = (): (() => Promise<FlowRefDerivation>) => {
498
+ return async () => {
499
+ const deps = await durableScanDeps()
500
+ if (deps === null) {
501
+ return { refs: [], foreignSkipped: [] }
502
+ }
503
+ // AIDEV-NOTE: PMR-RRW9 — ONLY the bind-adoption seam gets the
504
+ // owner-scoped filter inputs: the calling session's main session
505
+ // file (late-bound; refreshed on session_start) and the reused
506
+ // ownerPidAlive probe from flow/resume-picker.ts. deriveParkedCandidates
507
+ // (the resume picker) keeps the wide scan — the human arbitrates
508
+ // there via the owner-liveness hint.
509
+ // AIDEV-NOTE: PMR-3N9N — callerPid is injected HERE (the only place
510
+ // process.pid is read) so a live self-owned headless run (null
511
+ // sessionFile, same pid after a reload) stays adoptable.
512
+ return deriveFlowRefsDetailed({
513
+ ...deps,
514
+ callerSessionFile: mainSessionFile,
515
+ callerPid: process.pid,
516
+ pidAlive: ownerPidAlive,
517
+ })
518
+ }
519
+ }
520
+ const makeDeriveRefs = (): (() => Promise<string[]>) => {
521
+ // AIDEV-NOTE: PMR-YN61 — the plain string[] seam is a projection of the
522
+ // detailed one so the two owner-scoped wirings can never drift (same
523
+ // single-construction rule as durableScanDeps above).
524
+ const detailed = makeDeriveRefsDetailed()
525
+ return async () => {
526
+ const derivation = await detailed()
527
+ return derivation.refs
528
+ }
529
+ }
530
+ // AIDEV-NOTE: PMR-T9ZQ 3.1 — production rich-candidate scanner for the
531
+ // resume picker (same scan/filters as makeDeriveRefs, per the durable-refs
532
+ // header note).
533
+ const makeDeriveCandidates = (): (() => Promise<ParkedCandidate[]>) => {
534
+ return async () => {
535
+ const deps = await durableScanDeps()
536
+ if (deps === null) {
537
+ return []
538
+ }
539
+ return deriveParkedCandidates(deps)
540
+ }
541
+ }
542
+ // AIDEV-NOTE: PMR-DRKH — production derive/heal IO for the session_start
543
+ // durable rebind. Heal goes through the shared productionReviewDeps so the
544
+ // resolver's verification chain (binding → aven note → herdr) is identical
545
+ // to /code-review. Overridable via the extension factory's second param.
546
+ // PMR-T9ZQ: the candidate list is rich now and NOTHING here runs before a
547
+ // human picks Resume (see the session_start resume-picker gate below).
548
+ const durableRebind: DurableRebindDeps = durableRebindDeps ?? {
549
+ deriveCandidates: makeDeriveCandidates(),
550
+ heal: (ref, cwd) => healFlowBinding(ref, productionReviewDeps(pi, cwd)),
551
+ env: process.env,
552
+ }
553
+ // AIDEV-NOTE: PMR-1KXH — cooldown state + clock for the settle-scan
554
+ // throttle. Closure-scoped, so each extension instance (one per process in
555
+ // production) owns its window; tests inject `now` to advance it without
556
+ // sleeps.
557
+ const settleScanNow = durableRebind.now ?? (() => Date.now())
558
+ // AIDEV-NOTE: PMR-YG18 — late-bound like `now` so a partially injected
559
+ // test seam still gets the production stderr default.
560
+ const resumeFallbackStderr =
561
+ durableRebind.writeStderr ??
562
+ ((line: string) => {
563
+ process.stderr.write(`${line}\n`)
564
+ })
565
+ let lastEmptySettleScanAt: number | null = null
566
+ // AIDEV-NOTE: PMR-ZV9Y 4.3 — THE v2 fan-out wrap point. `telemetry/dispatch.ts`
567
+ // carries the seam map; the short version is that every v2 emitter in the
568
+ // session (loop journal/journalV2 via journalSerial -> journal, the
569
+ // code-review and deviation gates, the run-attempt ledger + escalation seam,
570
+ // flow_submit, the receipt journals) holds THIS object, so wrapping it here
571
+ // routes every journaled v2 event exactly once — no double Loki push, no
572
+ // missed path. The daemon (server/daemon.ts) builds no writer and never
573
+ // gets this wrapper: session-side only, per the telemetry.loki AIDEV note
574
+ // in config.ts. Both sinks are late-bound on purpose:
575
+ // - `loki` stays null until the session's config read resolves
576
+ // telemetry.loki (disabled by default = ZERO fetch calls);
577
+ // - `telemetryHandle` is assigned right after registerTelemetry below,
578
+ // so telemetry-off sessions keep the absent-safe no-op path.
579
+ let lokiSettings: LokiSettings | null = null
580
+ // AIDEV-NOTE: PMR-ZV9Y 5.2 — the DESKTOP-notify sink shares the same handler
581
+ // bag above (createTelemetryHandlers guards the Loki push and the notify
582
+ // sink SEPARATELY, so neither can cost the other). Both inputs are
583
+ // late-bound like `lokiSettings`:
584
+ // - `notifyDesktop` is the `notify.desktop.enabled` gate — default TRUE,
585
+ // an opt-OUT channel (the opposite of telemetry.loki's opt-in default),
586
+ // so a fresh install pages on a waiting_human/halted transition;
587
+ // - `sessionCwd` is the session cwd, which the desktop-notify module
588
+ // (rifle-batteries) needs to load ITS OWN channel config (desktop /
589
+ // herdr / ntfy toggles stay the user's; pi-flow only decides whether a
590
+ // flow event pages at all — D3).
591
+ // Grafana alerting is the independent second channel: neither switch here
592
+ // affects it, and it is paused/muted in Grafana, never from here.
593
+ let notifyDesktop = true
594
+ let sessionCwd = process.cwd()
595
+ // late-bound: the telemetry handle only exists after registerTelemetry far
596
+ // below; it is declared HERE because the v2 fan-out reads it per event (the
597
+ // ad-hoc tracker uses the same holder).
598
+ let telemetryHandle: ReturnType<typeof registerTelemetry> | null = null
599
+ // AIDEV-NOTE: PMR-ZV9Y fix round (P1 blocker) — late-bound flow loop so the
600
+ // fan-out dispatcher's single-choke-point `route` can invalidate the loop's
601
+ // guarded v2 emission on a TOOL-journaled wait (run-attempt escalate,
602
+ // deviation rerun). Assigned right after `createFlowLoop` below; null until
603
+ // then (a pre-loop event simply skips the observer, same posture as
604
+ // telemetryHandle). See the onV2StateChangeObserved doc in dispatch.ts.
605
+ let flowLoopForV2: FlowLoop | null = null
606
+ const telemetryHandlers: FanoutHandlers = createTelemetryHandlers({
607
+ loki: () => lokiSettings,
608
+ handle: () => telemetryHandle,
609
+ fetchImpl: async (url, init) => {
610
+ const response = await fetch(url, init)
611
+ return { status: response.status }
612
+ },
613
+ now: () => Date.now(),
614
+ // At most ONE note per session (the shared once-guard inside the
615
+ // handler bag), mirroring the OTLP exporter-failure posture below.
616
+ onNote: (ref, error) => {
617
+ void journal({
618
+ kind: 'note',
619
+ at: new Date().toISOString(),
620
+ ref,
621
+ text: `loki push failed: ${error} (further failures silent)`,
622
+ })
623
+ },
624
+ env: process.env,
625
+ // PMR-ZV9Y 5.2 — fire-and-forget desktop page on waiting_human/halted.
626
+ // The sink never blocks the fan-out (it never awaits into `record`) and
627
+ // NEVER throws: an absent/broken @gtheys/rifle-batteries (the
628
+ // desktop-notify carrier, an OPTIONAL dependency) journals ONE note, then
629
+ // the channel stays off.
630
+ notify: {
631
+ desktop: () => notifyDesktop,
632
+ cwd: () => sessionCwd,
633
+ onNote: (ref, error) => {
634
+ void journal({
635
+ kind: 'note',
636
+ at: new Date().toISOString(),
637
+ ref,
638
+ text: `desktop notify unavailable: ${error} (channel off, further failures silent)`,
639
+ })
640
+ },
641
+ },
642
+ })
643
+ // AIDEV-NOTE: PMR-ZV9Y fix round (P1 blocker) + fix-round-2 (P2a) — compose
644
+ // the loop-guard invalidator onto the single choke point (the fan-out
645
+ // dispatcher's `route`). Every journaled v2 state-change reaches it, loop- OR
646
+ // tool-emitted, so a run-attempt escalate / deviation rerun wait re-seeds the
647
+ // loop's `lastEmittedV2` and the loop's next differing-state emission is NOT
648
+ // suppressed. Late-bound on `flowLoopForV2` (a pre-loop event skips it).
649
+ // Idempotent for the loop's OWN emissions (it re-writes the value it just
650
+ // emitted), so running->running stays suppressed and no transition is
651
+ // fabricated. The dispatcher guards this observer separately from the Loki +
652
+ // notify sinks (ISC-A-5), so telemetry-off sessions still get the fix. The
653
+ // event `at` is threaded through so noteExternalV2State stays monotonic on
654
+ // recency: a tool write bypasses journalSerial and can route after the loop's
655
+ // queued running echo, so without the timestamp the guard could revert to a
656
+ // stale state (the original P1 symptom in a narrow window). PMR-422Q (PMR-0NRH
657
+ // review blocker 2) threads `event.reason` too: the loop's live-wait hold may
658
+ // only be armed by a waiting_human whose OWNING SEAM journals its own running
659
+ // close (SELF_CLOSING_HUMAN_WAITS in flow/vocabulary.ts), because a hold armed
660
+ // on a wait that never closes — run_attempt escalate, deviation rerun — latches
661
+ // and silently drops every later loop-emitted wait for the rest of the
662
+ // process's run. Without the reason the loop cannot tell those apart, so it can
663
+ // only hold the waits it knows will be released.
664
+ telemetryHandlers.onV2StateChangeObserved = (event) => {
665
+ if (flowLoopForV2 === null) return
666
+ const { ref, state, at, reason } = event
667
+ flowLoopForV2.noteExternalV2State(ref, state, at, reason)
668
+ }
669
+ const writer: EventWriter = createEventFanoutWriter(
670
+ createEventWriter(
671
+ getAgentDir(),
672
+ createDaemonAliveProbe(getAgentDir(), () => runServerEnabled),
673
+ ),
674
+ telemetryHandlers,
675
+ )
676
+
677
+ /** Resolve `notify.desktop.enabled` + the session cwd into the fan-out's
678
+ * notify sink. Called from the same config reads as syncLokiSettings
679
+ * (best-effort: an unreadable config keeps the enabled-by-default channel
680
+ * and the previous cwd, never throws). The cwd is what the desktop-notify
681
+ * module (rifle-batteries) loads ITS OWN channel config with, so a project
682
+ * override of the notify channels works exactly like the extension's own
683
+ * hooks do. */
684
+ function syncNotifySettings(
685
+ config: Parameters<typeof resolveNotifySettings>[0],
686
+ cwd: string,
687
+ ): void {
688
+ notifyDesktop = resolveNotifySettings(config).desktop.enabled
689
+ sessionCwd = cwd
690
+ }
691
+
692
+ /** Resolve `telemetry.loki` into the fan-out's live settings. Called from
693
+ * the session_start probe and every /flow config read (best-effort: an
694
+ * unreadable config leaves Loki disabled, never throws). */
695
+ function syncLokiSettings(
696
+ config: Parameters<typeof resolveLokiSettings>[0],
697
+ ): void {
698
+ lokiSettings = lokiPushSettings(resolveLokiSettings(config))
699
+ }
700
+
701
+ async function journal(
702
+ event: Parameters<typeof writer.record>[0],
703
+ ): Promise<void> {
704
+ await writer.record(event)
705
+ }
706
+
707
+ async function journalOnly(
708
+ event: Parameters<typeof writer.recordJournalOnly>[0],
709
+ ): Promise<boolean> {
710
+ return writer.recordJournalOnly(event)
711
+ }
712
+
713
+ // AIDEV-NOTE: PMR-T9ZQ 3.1 — arm a CONSENTED cross-session resume: exactly
714
+ // today's PMR-DRKH sequence, in order, but only ever reached behind the
715
+ // picker gate. heal is conditional on candidate.hasWorktree — a run that
716
+ // never journaled a worktree-create effect gets the plain restore info
717
+ // and NEVER a heal-failed warning (kills the plan-phase noise). The config
718
+ // sync stays BEFORE the consumer (JKD6RFC0MYY3N29C), and the whole gate
719
+ // runs strictly before consumePending renames a pending record.
720
+ async function armResumedRun(
721
+ ctx: ResumeAskCtx,
722
+ candidate: ParkedCandidate,
723
+ ): Promise<void> {
724
+ const ref = candidate.ref
725
+ // AIDEV-NOTE: PMR-C1XT — re-check the live binding AFTER the (unbounded,
726
+ // and in RPC mode NON-MODAL) picker wait resolved, BEFORE restoreFlowBinding
727
+ // touches anything. The settle-path live-binding guard runs before the async
728
+ // scan, so a flow that went live in THIS session while the human
729
+ // deliberated is only visible now. Restore is an unconditional
730
+ // ({ref, worktree: null}) clobber: without this re-check it overwrites that
731
+ // live ref and drops its worktree binding to null, and when the candidate
732
+ // never declared a worktree no heal rebinds it — reproducing the PMR-2424
733
+ // "review diffs the main checkout" failure class. Same rule as
734
+ // flow/binding-heal.ts mayMutate: the live flow owns the binding, so a
735
+ // resume of a DIFFERENT ref is refused (clean session, recovery hint).
736
+ const live = getActiveFlowRef()
737
+ if (live !== null && live !== ref) {
738
+ ctx.ui.notify(
739
+ `pi-flow: resume skipped — flow ${live} is live in this session, so its binding stays authoritative. Recover with ${recoveryCommand(ref)} if needed.`,
740
+ 'info',
741
+ )
742
+ return
743
+ }
744
+ restoreFlowBinding({ ref, worktree: null })
745
+ boundRef = ref
746
+ if (candidate.hasWorktree) {
747
+ try {
748
+ const healed = await durableRebind.heal(ref, ctx.cwd)
749
+ if (healed.ok) {
750
+ ctx.ui.notify(
751
+ `pi-flow: restored flow binding for ${ref} from the pending-run record. The /flow loop itself is not resumed — recover with ${recoveryCommand(ref)} if needed.`,
752
+ 'info',
753
+ )
754
+ } else {
755
+ ctx.ui.notify(
756
+ `pi-flow: restored flow binding for ${ref}, but the worktree heal failed (${healed.reason}). Recover with ${recoveryCommand(ref)}.`,
757
+ 'warning',
758
+ )
759
+ }
760
+ } catch {
761
+ ctx.ui.notify(
762
+ `pi-flow: restored flow binding for ${ref}. Recover with ${recoveryCommand(ref)}.`,
763
+ 'info',
764
+ )
765
+ }
766
+ } else {
767
+ ctx.ui.notify(
768
+ `pi-flow: restored flow binding for ${ref} (this run never bound a worktree). Recover with ${recoveryCommand(ref)} if needed.`,
769
+ 'info',
770
+ )
771
+ }
772
+ try {
773
+ const config = await loadConfig(ctx.cwd)
774
+ runServerEnabled = resolveRunServerEnabled(config)
775
+ } catch {
776
+ // best-effort init; /flow re-syncs per start
777
+ }
778
+ await resumeParkedRun(resumeConsumerDeps(ref))
779
+ }
780
+
781
+ // The notify degradation shared by the headless plan and every fail-closed
782
+ // path: one info line per candidate, nothing else.
783
+ // AIDEV-NOTE: PMR-YG18 — when ctx.hasUI is false, notify is pi's no-op
784
+ // uiContext (print/json modes), so the same lines are ALSO written to
785
+ // stderr — the only channel a headless operator can see. Interactive
786
+ // sessions (including the select-throw fail-closed path, where the real
787
+ // ctx.hasUI is true) stay notify-only: no duplicate output next to a
788
+ // working UI. Notify is kept in the headless branch too so the seam's
789
+ // notify-based pins stay valid; a no-op notify shows nothing twice.
790
+ function notifyResumeFallback(ctx: ResumeAskCtx, lines: string[]): void {
791
+ for (const line of lines) {
792
+ ctx.ui.notify(line, 'info')
793
+ if (!ctx.hasUI) {
794
+ resumeFallbackStderr(line)
795
+ }
796
+ }
797
+ }
798
+
799
+ // AIDEV-NOTE: PMR-T9ZQ 3.1 — the shared ask-then-arm gate for BOTH
800
+ // cross-session resume paths (session_start's durable rebind here; the
801
+ // agent_settled belt-and-braces path in subtask 3.2 reuses it verbatim).
802
+ // The order is the contract: derive -> planResumePickerOutcome -> (UI
803
+ // sessions only) ctx.ui.select -> armResumedRun on a resume pick. Nothing
804
+ // binds, heals, consumes or injects before the human answers, and every
805
+ // non-resume outcome fails CLOSED to a fully clean session: a decline/Esc
806
+ // gets one info line listing the recovery commands, a headless context or
807
+ // a throwing select gets the notify-only fallback lines. The module-level
808
+ // ask latch is flipped synchronously around the await so overlapping
809
+ // asks never stack two prompts in one process.
810
+ async function askResumeThenArm(
811
+ ctx: ResumeAskCtx,
812
+ candidates: ParkedCandidate[],
813
+ ): Promise<void> {
814
+ let plan = planResumePickerOutcome(ctx.hasUI, candidates)
815
+ if (plan.kind === 'menu') {
816
+ if (resumeAskState === 'asking') {
817
+ return
818
+ }
819
+ const labelToValue = new Map(plan.options.map((o) => [o.label, o.value]))
820
+ resumeAskState = 'asking'
821
+ let selection: ResumeSelection
822
+ try {
823
+ const picked = await ctx.ui.select(
824
+ RESUME_SELECT_TITLE,
825
+ plan.options.map((o) => o.label),
826
+ )
827
+ if (picked === undefined) {
828
+ selection = { stage: 'resume-cancelled' }
829
+ } else {
830
+ selection = {
831
+ stage: 'resume-picked',
832
+ value: labelToValue.get(picked) ?? '',
833
+ }
834
+ }
835
+ } catch {
836
+ // select unavailable (a mode without a dialog implementation) or it
837
+ // threw: fail closed — no consent was obtained, so surface the
838
+ // plain-text recovery lines and leave the session clean. Re-planning
839
+ // with hasUI=false is what turns this path into the same notify-only
840
+ // shape the headless startup shows.
841
+ resumeAskState = 'done'
842
+ const closed = planResumePickerOutcome(false, candidates)
843
+ if (closed.kind === 'fallback') {
844
+ notifyResumeFallback(ctx, closed.lines)
845
+ }
846
+ return
847
+ }
848
+ resumeAskState = 'done'
849
+ plan = planResumePickerOutcome(ctx.hasUI, candidates, selection)
850
+ }
851
+ if (plan.kind === 'fallback') {
852
+ notifyResumeFallback(ctx, plan.lines)
853
+ return
854
+ }
855
+ if (plan.kind === 'declined') {
856
+ ctx.ui.notify(resumeDeclineMessage(plan.refs), 'info')
857
+ return
858
+ }
859
+ if (plan.kind === 'resume') {
860
+ await armResumedRun(ctx, plan.candidate)
861
+ }
862
+ }
863
+
864
+ // AIDEV-NOTE: PMR-BCP7 — shared runner for BOTH ask sites (session_start's
865
+ // durable-rebind gate and the agent_settled belt-and-braces gate), so the two
866
+ // cannot drift again. A zero-candidate scan is 'silent' and deliberately
867
+ // leaves the latch 'idle' so a later settle can still ask. Every REAL ask —
868
+ // menu, decline, or the headless notify-only fallback — counts as the
869
+ // once-per-process ask, so the latch is pinned here. The startup site used to
870
+ // skip this pinning: a headless fallback returned with the latch still 'idle'
871
+ // and the first agent_settled re-ran the gate, re-printing the same recovery
872
+ // lines (invisible back then only because headless notify is a no-op; since
873
+ // PMR-YG18 the fallback also reaches stderr, so an unpinned latch would
874
+ // re-print on an operator-visible channel).
875
+ async function runResumeGateOnce(
876
+ ctx: ResumeAskCtx,
877
+ candidates: ParkedCandidate[],
878
+ ): Promise<void> {
879
+ if (candidates.length === 0) {
880
+ return
881
+ }
882
+ await askResumeThenArm(ctx, candidates)
883
+ if (resumeAskState === 'idle') {
884
+ resumeAskState = 'done'
885
+ }
886
+ }
887
+
888
+ // AIDEV-NOTE: production wiring for the /flow answer dispatch (PMR-R5VB) —
889
+ // the only place where human answers reach aven. `ctx` is the command
890
+ // handler's context, structurally narrowed. Lives inside the extension
891
+ // closure so appendJournal routes through the mode-aware writer seam
892
+ // (journal-only while the durable run server owns the projection).
893
+ // AIDEV-NOTE (yolo plan 1.2): shared ready-ticket picker IO for both the
894
+ // zero-arg /flow picker ('tickets' plan) and the '/flow --yolo' shortcut.
895
+ // Same planner (planTicketPickerOutcome), same select, same notify
896
+ // outcomes; the callers differ only in the yolo bit they put on the
897
+ // reassigned parsed ref. Returns the picked ref, or undefined when every
898
+ // non-run outcome (fallback / none / failed / silent) already notified or
899
+ // stayed silent and the handler must return.
900
+ async function pickReadyTicketRef(
901
+ ctx: {
902
+ hasUI: boolean
903
+ ui: {
904
+ notify(message: string, level: 'info' | 'warning' | 'error'): void
905
+ select(title: string, options: string[]): Promise<string | undefined>
906
+ }
907
+ },
908
+ hadGates: boolean,
909
+ ): Promise<string | undefined> {
910
+ const tickets = await listReadyTickets()
911
+ let ticketPlan = planTicketPickerOutcome(ctx.hasUI, hadGates, tickets)
912
+ if (ticketPlan.kind === 'menu') {
913
+ const labelToValue = new Map(
914
+ ticketPlan.options.map((o) => [o.label, o.value]),
915
+ )
916
+ const picked = await ctx.ui.select(
917
+ 'Ready ticket — start a flow:',
918
+ ticketPlan.options.map((o) => o.label),
919
+ )
920
+ if (picked === undefined) {
921
+ ticketPlan = planTicketPickerOutcome(ctx.hasUI, hadGates, tickets, {
922
+ stage: 'ticket-cancelled',
923
+ })
924
+ } else {
925
+ ticketPlan = planTicketPickerOutcome(ctx.hasUI, hadGates, tickets, {
926
+ stage: 'ticket-picked',
927
+ ref: labelToValue.get(picked) ?? '',
928
+ })
929
+ }
930
+ }
931
+ if (ticketPlan.kind === 'fallback') {
932
+ for (const line of ticketPlan.lines) {
933
+ ctx.ui.notify(line, 'info')
934
+ }
935
+ return undefined
936
+ }
937
+ if (ticketPlan.kind === 'none') {
938
+ ctx.ui.notify(ticketPlan.line, 'info')
939
+ return undefined
940
+ }
941
+ if (ticketPlan.kind === 'failed') {
942
+ const detail = lastAvenResolutionFailure() ?? 'aven unavailable'
943
+ ctx.ui.notify(
944
+ `pi-flow: could not list ready tickets (${detail}) — run \`aven list --ready\` to inspect, then /flow <ref> manually`,
945
+ 'warning',
946
+ )
947
+ return undefined
948
+ }
949
+ if (ticketPlan.kind === 'run') {
950
+ return ticketPlan.ref
951
+ }
952
+ // 'silent' (cancel / lookup miss): notify nothing.
953
+ return undefined
954
+ }
955
+
956
+ // AIDEV-NOTE (yolo plan 1.2): gate collection with the fail-closed warn
957
+ // shared by the zero-arg picker and the /flow --yolo shortcut. Returns
958
+ // null after warning when the runs dir / aven list read failed.
959
+ async function collectGatesOrWarn(ctx: {
960
+ ui: { notify(message: string, level: 'info' | 'warning' | 'error'): void }
961
+ }): Promise<OpenGate[] | null> {
962
+ let gates: OpenGate[] = []
963
+ let failed = false
964
+ try {
965
+ gates = await collectOpenGates(createGateDeps(getAgentDir()))
966
+ } catch {
967
+ failed = true
968
+ }
969
+ if (failed) {
970
+ ctx.ui.notify(
971
+ 'pi-flow: could not read open gates (runs dir / aven list failed) — run /flow answer <ref> <choice> manually',
972
+ 'warning',
973
+ )
974
+ return null
975
+ }
976
+ return gates
977
+ }
978
+
979
+ function makeAnswerDeps(ctx: {
980
+ cwd: string
981
+ ui: {
982
+ notify(message: string, level: 'info' | 'warning' | 'error'): void
983
+ }
984
+ }): AnswerDeps {
985
+ return {
986
+ notify: (message, level) => ctx.ui.notify(message, level),
987
+ writeGateAnswer: (ref, gate, choice) =>
988
+ writeGateAnswer(ref, gate, choice),
989
+ writeAvenNote: (ref, text) => writeAvenNote(ref, text),
990
+ // AIDEV-NOTE: PMR-N0D5 — bind a spec approve answer to the CURRENT
991
+ // plan revision (sha256 of the plan file content at the ticket's
992
+ // plan-path). Journaled WITH the gate-answer event; spec_approve and
993
+ // the plan receipt gate refuse a stale answer when the plan later
994
+ // changed. readPlanRevision is fail-soft (null on aven failure,
995
+ // absent plan-path metadata, unreadable plan file) and the answer
996
+ // path treats null/throw as fail-soft too (unbound answer + warning;
997
+ // the gates then refuse fail-closed until a bound re-answer).
998
+ bindPlanRevision: (ref) => readPlanRevision(ref),
999
+ appendJournal: async (event) => {
1000
+ // AIDEV-NOTE: PMR-V31Z 7.1 — void-context: the aven metadata is the
1001
+ // authoritative receipt; the journal append is a best-effort
1002
+ // projection (flow/answer.ts swallows failures). The former
1003
+ // journalOnly-outcome consumer (the stampReviewPass head-stamp) was
1004
+ // deleted with the review gate.
1005
+ await journalOnly(event)
1006
+ },
1007
+ now: () => new Date().toISOString(),
1008
+ // AIDEV-NOTE: PMR-DMHH subtask 2.1 — post-record wake hook, fired by
1009
+ // executeFlowAnswer only after a successful receipt write. The typed
1010
+ // answer branch AND the zero-arg picker share makeAnswerDeps, so both
1011
+ // wake identically (picker parity by construction, ISC-5) and both
1012
+ // pass through the paused-waiter ownership guard (ISC-13): the local
1013
+ // identity is process.pid + the session_start-refreshed
1014
+ // mainSessionFile — the same value the loop stamps into its
1015
+ // owner-session events via getSessionFile(), so the same-session
1016
+ // comparison is exact. The send wrapper mirrors resumeConsumerDeps:
1017
+ // expandPromptTemplates lets the injected `/flow <ref>` expand exactly
1018
+ // like a human-typed command.
1019
+ onGateAnswered: (ref, gate, choice) =>
1020
+ wakeOnGateAnswer(ref, gate, choice, {
1021
+ loopActive: () => loop.isActive(),
1022
+ readRunState: (r) => readRunState(getAgentDir(), r),
1023
+ localIdentity: () => ({
1024
+ pid: process.pid,
1025
+ sessionFile: mainSessionFile,
1026
+ }),
1027
+ hasStandaloneAwait: (r) => isAwaitingSpecApproval(r),
1028
+ consumeStandaloneAwait: (r) => {
1029
+ consumeAwaitingSpecApproval(r)
1030
+ },
1031
+ latch: gateWakeLatch,
1032
+ notify: (message, level) => ctx.ui.notify(message, level),
1033
+ send: (message) => {
1034
+ pi.sendUserMessage(message, { expandPromptTemplates: true })
1035
+ },
1036
+ }),
1037
+ }
1038
+ }
1039
+ // AIDEV-NOTE: ui.notify holder — command and event handlers each get their
1040
+ // own ctx; the loop needs one stable notify. session_start fires before any
1041
+ // command or agent_settled event, so the holder is always populated by then.
1042
+ let notifyUser:
1043
+ | ((message: string, level: 'info' | 'warning' | 'error') => void)
1044
+ | null = null
1045
+
1046
+ // main pi session file, refreshed on session_start; journaled per phase so
1047
+ // /flow-cost can attribute main-session cost (see flow/cost.ts)
1048
+ let mainSessionFile: string | null = null
1049
+ // late-bound: automatic cost push, built after the cost deps below
1050
+ let autoPushCost: ((ref: string) => Promise<void>) | null = null
1051
+ // late-bound: the telemetry handle only exists after registerTelemetry below
1052
+ let syncTelemetryFlowEnv: (() => void) | null = null
1053
+ // AIDEV-NOTE: PMR-81SX 5.2 — late-bound worktree cleanup at flow done. The
1054
+ // wrapper is wired into the loop before the worktree extension has resolved
1055
+ // its effects journal; the impl is assigned right after registration so the
1056
+ // cleanup's effect declarations land in the SAME journal the worktree tool
1057
+ // itself uses.
1058
+ let onFlowDoneImpl:
1059
+ | ((
1060
+ ref: string,
1061
+ mode: 'work' | 'personal',
1062
+ worktree: FlowWorktree | undefined,
1063
+ // PMR-YG2N fix round — session repo root (undefined = process cwd).
1064
+ cwd: string | undefined,
1065
+ ) => Promise<CleanupFlowWorktreeSummary>)
1066
+ | null = null
1067
+ // AIDEV-NOTE: PMR-ZV9Y 2.1 — serialized journal sink for the loop. Every
1068
+ // loop transition can now emit TWO projected writes back-to-back (the v1
1069
+ // loop-state snapshot AND the v2 state-change) with no await between them;
1070
+ // `void journal(event)` would let both `recordRunEvent` read-modify-write
1071
+ // cycles observe the same pre-append projection and interleave their
1072
+ // writeFile, corrupting the run-state JSON. Chaining each write onto the
1073
+ // previous one keeps the fire-and-forget (never-throw) contract while
1074
+ // strictly ordering appends and projection rewrites. journal + journalV2
1075
+ // share the chain so the durable journal's event order matches emission
1076
+ // order.
1077
+ let journalChain: Promise<void> = Promise.resolve()
1078
+ const journalSerial = (event: Parameters<typeof journal>[0]): void => {
1079
+ journalChain = journalChain
1080
+ .then(() => journal(event))
1081
+ .catch(() => undefined)
1082
+ }
1083
+ // AIDEV-NOTE: PMR-VE27 — production PR-effect probe for the feedback
1084
+ // close-out gate (work + personal yolo legs), the plan's prLandingEffect
1085
+ // closure shape: a readRunEvents pre-check distinguishes an unreadable
1086
+ // journal ({kind:'unreadable'}) from a readable journal without the
1087
+ // declaration ({kind:'missing'}), and found is the journaled
1088
+ // gh-pr-create effect `flow_land <ref>` declares before authorizing
1089
+ // (PMR-VDVJ). Tri-state probe for lifecycle-policy.ts's PrEffectProbe;
1090
+ // fail-closed — no readable journal, no evidence. The same closure shape
1091
+ // serves the /flow all-labels terminal re-entry in the epic's phase 4.
1092
+ const prLandingEffect = async (ref: string): Promise<PrEffectProbe> => {
1093
+ const events = await readRunEvents(getAgentDir(), ref)
1094
+ if (events === null) {
1095
+ return {
1096
+ kind: 'unreadable',
1097
+ reason: `the run journal for ${ref} is missing or unreadable`,
1098
+ }
1099
+ }
1100
+ const effects = createEffectJournal(getAgentDir())
1101
+ const found = await effects.find({ ref, effect: 'gh-pr-create' })
1102
+ if (found === null) return { kind: 'missing' }
1103
+ return { kind: 'found' }
1104
+ }
1105
+ // AIDEV-NOTE: PMR-2H3R — unlike Pi's per-agent-run turnIndex, this counter
1106
+ // never resets. It lets the loop distinguish a stale open-turn settle from
1107
+ // the outcome of a turn started after a phase prompt was injected.
1108
+ let turnGeneration = 0
1109
+ const loop = createFlowLoop({
1110
+ getTurnGeneration: () => turnGeneration,
1111
+ getSessionFile: () => mainSessionFile,
1112
+ onRunEnd: (ref) => {
1113
+ if (autoPushCost !== null) void autoPushCost(ref)
1114
+ },
1115
+ onFlowEnvChange: () => {
1116
+ if (syncTelemetryFlowEnv !== null) syncTelemetryFlowEnv()
1117
+ },
1118
+ notify: (message, level) => {
1119
+ if (notifyUser !== null) {
1120
+ notifyUser(message, level)
1121
+ } else {
1122
+ console.log(`[pi-flow] ${level}: ${message}`)
1123
+ }
1124
+ },
1125
+ journal: (event) => {
1126
+ journalSerial(event)
1127
+ },
1128
+ // AIDEV-NOTE: PMR-ZV9Y 2.1 — the v2 emission seam routes to the SAME
1129
+ // best-effort writer as `journal`, so state-change/step events land in the
1130
+ // durable run journal and reach the phase-4 telemetry fan-out; a separate
1131
+ // dep name only (never a second writer). The loop wraps the call, so a
1132
+ // throwing seam cannot halt a phase (ISC-A-5).
1133
+ journalV2: (event) => {
1134
+ journalSerial(event)
1135
+ },
1136
+ readLabels: (ref) => readAvenLabels(ref),
1137
+ // AIDEV-NOTE: PMR-B033 — the blocker route-back resets the implement
1138
+ // completion gate through this dep (load-bearing: the loop halts
1139
+ // label_reset_failed when it is absent or fails).
1140
+ removeAvenLabel: (ref, label) => removeAvenLabel(ref, label),
1141
+ // AIDEV-NOTE: PMR-VE27 — the feedback settle's close-out gate needs the
1142
+ // journaled gh-pr-create tri-state (work + personal-yolo evidence leg).
1143
+ // The SAME prLandingEffect closure the phase-complete tool uses (defined
1144
+ // above createFlowLoop); absent would be fail-closed, halting every
1145
+ // work/yolo flow at done — so it is wired explicitly here.
1146
+ prEffectFn: prLandingEffect,
1147
+ readPlanState: (ref) => readPlanState(ref),
1148
+ hasFreshBlockers: (ref, since) => readFreshBlockers(ref, since),
1149
+ avenNote: (ref, text) => writeAvenNote(ref, text),
1150
+ // yolo 5.1 — best-effort `error` label on halted yolo runs (never
1151
+ // rejects; the loop additionally catches, belt and braces).
1152
+ avenLabel: (ref) => applyAvenErrorLabel(ref),
1153
+ // PMR-81SX 5.2 — wrapper never rejects (impl never throws either); the
1154
+ // loop additionally catches, belt and braces.
1155
+ onFlowDone: async (ref, mode, worktree) => {
1156
+ if (onFlowDoneImpl !== null) {
1157
+ try {
1158
+ // AIDEV-NOTE: PMR-YG2N fix round — the loop has no ctx, so the
1159
+ // done-path cwd falls back to the session repo root resolved from
1160
+ // the process cwd (no cwd arg), matching commandPhaseInput's
1161
+ // journal gitRoot semantics.
1162
+ const loopRoot = await resolveSessionRepoRoot(pi)
1163
+ let loopCwd: string | undefined
1164
+ if (loopRoot === null) {
1165
+ loopCwd = undefined
1166
+ } else {
1167
+ loopCwd = loopRoot
1168
+ }
1169
+ await onFlowDoneImpl(ref, mode, worktree, loopCwd)
1170
+ } catch {
1171
+ // never break the run end
1172
+ }
1173
+ }
1174
+ },
1175
+ epicHasOpenChildren: (ref) => epicHasOpenChildren(ref),
1176
+ hasInFlightSubagent: () => hasLiveAssignmentForParent(process.pid),
1177
+ // AIDEV-NOTE (worker-ask-wait fix): same record scan as the in-flight guard
1178
+ // above, but additionally requires an open ask_owner record — it reclassifies
1179
+ // the loop's in-flight wait as waiting_human{subagent_ask_pending} so the run
1180
+ // shows up on the "Waiting on me — act now" board while a child waits on the
1181
+ // operator (flow/loop-settle.ts onSettled).
1182
+ hasPendingSubagentAsk: () => hasPendingAskForParent(process.pid),
1183
+ setActiveRef: (ref) => {
1184
+ if (ref === null) {
1185
+ setActiveFlowRef(null)
1186
+ } else {
1187
+ reactivateFlowRef(ref)
1188
+ }
1189
+ },
1190
+ resetLandingState: () => {
1191
+ landingState.authorized = null
1192
+ },
1193
+ sendPrompt: (prompt) => {
1194
+ pi.sendUserMessage(prompt)
1195
+ },
1196
+ })
1197
+ // AIDEV-NOTE: PMR-ZV9Y fix round (P1 blocker) — late-bind the loop into the
1198
+ // fan-out's single-choke-point state-change observer so tool-journaled waits
1199
+ // (run-attempt escalate, deviation rerun) invalidate the loop's guarded v2
1200
+ // emission. See the onV2StateChangeObserved wiring above.
1201
+ flowLoopForV2 = loop
1202
+ pi.on('turn_start', () => {
1203
+ turnGeneration += 1
1204
+ })
1205
+
1206
+ // AIDEV-NOTE: PMR-HFK1 — spawn attribution journaling (PMR-C998). The
1207
+ // subagents extension emits spawn/resume/reattach events; while a flow run
1208
+ // is active we journal them as structured `spawn-record` events (no more
1209
+ // note text — note-text emission is retired by PMR-C998) so the later
1210
+ // flow-cost rollup can reconstruct child->subtask attribution even if env
1211
+ // stamps are lost (reassignments/takeovers included — cost follows whoever
1212
+ // actually did the work). No active run = nothing to attribute, ignore.
1213
+ // Best-effort: journal failures are already swallowed by the journal()
1214
+ // wrapper.
1215
+ onFlowSpawn((info) => {
1216
+ // AIDEV-NOTE: nested spawns — in a flow WORKER (scouts spawned by a plan
1217
+ // agent, ...) the loop is not running, but the worker inherited
1218
+ // PI_FLOW_REF, so its spawns still belong to that flow. Those records go
1219
+ // to the journal only (recordJournalOnly); the main process routes through
1220
+ // the mode-aware writer (journal-only while the daemon owns the
1221
+ // projection, full writer otherwise).
1222
+ const target = spawnJournalTarget(loop.activeRef(), process.env)
1223
+ if (target === null) return
1224
+ const { ref, nested } = target
1225
+ // AIDEV-NOTE: PMR-C998 — structured spawn-record instead of note text.
1226
+ // subtask / sessionFile are carried only when present (never empty
1227
+ // strings) so the reader can distinguish "unknown" from "known empty".
1228
+ const event: Extract<FlowRunEvent, { kind: 'spawn-record' }> = {
1229
+ kind: 'spawn-record',
1230
+ at: new Date().toISOString(),
1231
+ ref,
1232
+ childId: info.childId,
1233
+ name: info.name,
1234
+ spawnKind: info.kind,
1235
+ }
1236
+ if (info.subtask !== undefined && info.subtask !== '') {
1237
+ event.subtask = info.subtask
1238
+ }
1239
+ // AIDEV-NOTE (PMR-EA8X): sessionFile lets /flow-cost resolve child
1240
+ // sessions from the journal alone (PMR-C998: now a structured field on
1241
+ // the spawn-record instead of a note-text suffix; older notes without it
1242
+ // still fall back to the durable assignment records).
1243
+ if (info.sessionFile !== undefined && info.sessionFile !== '') {
1244
+ event.sessionFile = info.sessionFile
1245
+ }
1246
+ if (nested) {
1247
+ void journalOnly(event)
1248
+ return
1249
+ }
1250
+ void journal(event)
1251
+ // AIDEV-NOTE (PMR-ZGPY 3.2): widget refresh on subagent lifecycle change.
1252
+ void refreshFlowWidget()
1253
+ })
1254
+
1255
+ // AIDEV-NOTE (PMR-ZGPY 3.2): flow-status widget wiring ONLY — lifecycle
1256
+ // and data collection live in flow/widget.ts. refreshFlowWidget() is
1257
+ // pulled from agent_settled + the onFlowSpawn hook; assignment filtering
1258
+ // to THIS process's children happens inside the widget via parentPid.
1259
+ initFlowWidget(pi, {
1260
+ readState: async () => {
1261
+ const ref = loop.activeRef()
1262
+ if (ref === null) return null
1263
+ const events = await readRunEvents(getAgentDir(), ref)
1264
+ if (events === null) return null
1265
+ return projectRunState(events)
1266
+ },
1267
+ listAssignments: () => {
1268
+ const assignments: WidgetAssignment[] = []
1269
+ for (const view of listAssignments()) {
1270
+ if (view.state === 'unknown') continue
1271
+ assignments.push({
1272
+ name: view.record.name,
1273
+ status: view.record.status,
1274
+ parentPid: view.record.claim.pid,
1275
+ })
1276
+ }
1277
+ return assignments
1278
+ },
1279
+ collectOpenGates: () => collectOpenGates(createGateDeps(getAgentDir())),
1280
+ parentPid: process.pid,
1281
+ })
1282
+
1283
+ pi.on('session_start', (_event, ctx) => {
1284
+ notifyUser = (message, level) => ctx.ui.notify(message, level)
1285
+ mainSessionFile = ctx.sessionManager.getSessionFile() ?? null
1286
+ setAvenSessionCwd(ctx.cwd)
1287
+ // AIDEV-NOTE: PMR-ZV9Y 5.2 — the notify sink's cwd is stamped HERE too,
1288
+ // not only in syncNotifySettings: if the session_start telemetry probe's
1289
+ // config read throws, the desktop-notify module (rifle-batteries) still
1290
+ // resolves its project override against the real session cwd instead of
1291
+ // process.cwd().
1292
+ sessionCwd = ctx.cwd
1293
+ void ensureLabels(notifyUser)
1294
+ // AIDEV-NOTE: PMR-7B8M rev 1 — best-effort daemon staleness probe at
1295
+ // session start: the daemon records the spawner checkout's SHA in the
1296
+ // pidfile; an actionable verdict fires when it differs from the
1297
+ // MAIN-checkout HEAD (resolved from this session's worktree) or the
1298
+ // pidfile predates tracking. A worktree's own commits never move main
1299
+ // HEAD, so they never trigger this.
1300
+ // AIDEV-NOTE: PMR-5563 — the actionable verdict AUTO-RESTARTS the daemon
1301
+ // through handleDaemonStaleness when the idle gate passes (no active flow
1302
+ // loop AND no busy run on disk — flow/run-liveness.ts); a busy daemon or
1303
+ // a failed restart keeps today's manual-kill warning. The restart
1304
+ // closure resolves provenance LAZILY — only when a restart actually
1305
+ // fires — so the common fresh path gains zero extra git calls. All seams
1306
+ // are injectable (isIdle/restart on HandleStalenessDeps).
1307
+ // Fire-and-forget + never-throws, like the telemetry probe above.
1308
+ // ctx.cwd is passed explicitly because sessions may run outside the process
1309
+ // cwd.
1310
+ // AIDEV-NOTE: PMR-7B8M rev 1 gated this on nothing ("a disabled daemon is
1311
+ // simply not alive → unchecked → silent"). PMR-2FJ1 replaces that with an
1312
+ // explicit runServer.enabled gate: the kill switch only stops THIS repo
1313
+ // from spawning/using the daemon, so a daemon left alive by another repo
1314
+ // or an earlier build still warned "restart the daemon" every session in a
1315
+ // repo that never touches it. A config read failure keeps the enabled
1316
+ // default (same posture as the resume-consumer sync below).
1317
+ void (async () => {
1318
+ let enabled = true
1319
+ try {
1320
+ const config = await loadConfig(ctx.cwd)
1321
+ enabled = resolveRunServerEnabled(config)
1322
+ } catch {
1323
+ // best-effort: an unreadable config must not silence the warning
1324
+ }
1325
+ if (!enabled) {
1326
+ return
1327
+ }
1328
+ // AIDEV-NOTE: PMR-7B8M — same exec seam shape as the /flow start site
1329
+ // (a bare method reference loses `this`); named once so the lazy
1330
+ // restart closure below reuses the exact same seam.
1331
+ const execStaleness = (
1332
+ command: string,
1333
+ args: string[],
1334
+ options?: { cwd?: string },
1335
+ ) => pi.exec(command, args, options)
1336
+ await handleDaemonStaleness(
1337
+ {
1338
+ ...sessionStalenessDeps(execStaleness, getAgentDir(), ctx.cwd),
1339
+ isIdle: async () => {
1340
+ if (loop.isActive()) return false
1341
+ return !(await hasActiveFlowRun(getAgentDir(), realPidAlive))
1342
+ },
1343
+ restart: async (pid: number) => {
1344
+ // Provenance resolved lazily — only when a restart actually fires.
1345
+ const headSha = await resolveHeadSha(execStaleness, ctx.cwd)
1346
+ const mainCheckout = await resolveMainCheckout(
1347
+ execStaleness,
1348
+ ctx.cwd,
1349
+ )
1350
+ let gitRoot: string | null = null
1351
+ if (mainCheckout !== null) {
1352
+ gitRoot = mainCheckout.path
1353
+ }
1354
+ return restartDaemon(getAgentDir(), pid, {
1355
+ gitSha: headSha,
1356
+ gitRoot,
1357
+ })
1358
+ },
1359
+ },
1360
+ (message: string, level: 'info' | 'warning') =>
1361
+ ctx.ui.notify(message, level),
1362
+ )
1363
+ })()
1364
+ // AIDEV-NOTE: PMR-F8HB — register this workspace's aven project
1365
+ // prefixes so bare Jira-shaped aven refs (PMR-2424) classify as aven
1366
+ // instead of colliding with JIRA_RE. Best-effort: aven unavailable or
1367
+ // no projects keeps the historical Jira-first heuristic.
1368
+ void discoverAvenPrefixes().then((prefixes) => {
1369
+ if (prefixes.length > 0) {
1370
+ registerAvenPrefixes(prefixes)
1371
+ }
1372
+ })
1373
+ // AIDEV-NOTE: PMR-PJM0 — rebuild the flow ref/worktree binding after
1374
+ // reload/restart from the last persisted session entry.
1375
+ let saved: FlowBindingSnapshot | null = null
1376
+ // AIDEV-NOTE: PMR-P2MK — getBranch() walks the current leaf path only, so
1377
+ // an abandoned fork's binding cannot win; entry data is shape-validated.
1378
+ for (const entry of ctx.sessionManager.getBranch()) {
1379
+ if (entry.type === 'custom' && entry.customType === 'pi-flow-binding') {
1380
+ const parsed = parseFlowBindingSnapshot(entry.data)
1381
+ if (parsed !== null) saved = parsed
1382
+ }
1383
+ }
1384
+ const savedRef = saved?.ref
1385
+ if (saved !== null && savedRef != null) {
1386
+ const restored = saved
1387
+ if (restored.worktree && !existsSync(restored.worktree.path)) {
1388
+ saved = { ref: savedRef, worktree: null }
1389
+ }
1390
+ restoreFlowBinding(restored)
1391
+ // AIDEV-NOTE: PMR-PJM0 + PMR-XTQQ subtask 3.3 — the /flow loop itself
1392
+ // is not resumed on reload, BUT when a parked run record exists for
1393
+ // this ref (durable run server parked it mid-loop), the consumer below
1394
+ // re-presents `/flow <ref>` automatically. Manual rerun stays the
1395
+ // fallback for the no-record / dropped-record path.
1396
+ notifyUser(
1397
+ `pi-flow: restored flow binding for ${savedRef}. The /flow loop itself is not resumed — if a parked run record exists it is re-presented automatically; otherwise rerun /flow ${savedRef} to continue phases.`,
1398
+ 'info',
1399
+ )
1400
+ boundRef = savedRef
1401
+ // AIDEV-NOTE: PMR-XTQQ — sync the kill switch from config BEFORE the
1402
+ // consumer runs (deviation JKD6RFC0MYY3N29C): with runServer.enabled
1403
+ // false, resumeParkedRun must no-op (today's behavior) even though no
1404
+ // /flow has run in this session yet. Config read failure keeps the
1405
+ // enabled default — best-effort; /flow re-syncs per start and surfaces
1406
+ // config errors loudly there.
1407
+ void (async () => {
1408
+ try {
1409
+ const config = await loadConfig(ctx.cwd)
1410
+ runServerEnabled = resolveRunServerEnabled(config)
1411
+ } catch {
1412
+ // best-effort init; /flow re-syncs per start
1413
+ }
1414
+ await resumeParkedRun(resumeConsumerDeps(savedRef))
1415
+ })()
1416
+ } else {
1417
+ // AIDEV-NOTE: PMR-DRKH — durable resume PICKER gate when the PMR-PJM0
1418
+ // branch walk restored nothing (no pi-flow-binding entry on the leaf
1419
+ // path). PMR-T9ZQ rewrote the old automatic takeover: candidates are
1420
+ // derived as rich ParkedCandidates and handed to the shared
1421
+ // askResumeThenArm gate, which renders the consent menu (ctx.ui.select)
1422
+ // and binds / heals / consumes ONLY after a human picked Resume.
1423
+ // Zero candidates → silent (today's behavior); no UI, a declined pick,
1424
+ // Esc or a throwing select → fully clean session plus notify-only
1425
+ // recovery lines. A resumed pick runs the same heal + config-sync +
1426
+ // resumeParkedRun sequence as the PMR-PJM0 block above (config read
1427
+ // BEFORE the consumer, JKD6RFC0MYY3N29C), with the heal skipped
1428
+ // entirely for runs that never declared a worktree. The gate always
1429
+ // precedes consumePending, so a declined session never renames a
1430
+ // pending record. A new session re-arms the ask-once latch (the plan's
1431
+ // accepted per-process restart case).
1432
+ resumeAskState = 'idle'
1433
+ void (async () => {
1434
+ // AIDEV-NOTE: PMR-XQZM — subagent children never render the
1435
+ // parked-run consent menu: a child answering "Resume" could steal a
1436
+ // run owned by the main session. Cheapest-first (mirrors the PMR-1KXH
1437
+ // cooldown philosophy): return BEFORE the deriveCandidates scan, so a
1438
+ // child pays one env check and prints nothing (no menu, no notify
1439
+ // fallback, no stderr line). The latch stays 'idle' — the skip never
1440
+ // spends it.
1441
+ if (isSubagentSession(durableRebind.env ?? process.env)) {
1442
+ return
1443
+ }
1444
+ let candidates: ParkedCandidate[]
1445
+ try {
1446
+ candidates = await durableRebind.deriveCandidates()
1447
+ } catch {
1448
+ return
1449
+ }
1450
+ await runResumeGateOnce(ctx, candidates)
1451
+ })()
1452
+ }
1453
+ setBindingChangeListener((snapshot) => {
1454
+ pi.appendEntry('pi-flow-binding', snapshot)
1455
+ })
1456
+ // AIDEV-NOTE: PMR-YG2N 4.1 — fire-and-forget sweep AFTER the restore
1457
+ // block + binding listener: a restored done binding is itself sweepable.
1458
+ runBackgroundSweep({ cwd: ctx.cwd })
1459
+ })
1460
+
1461
+ // AIDEV-NOTE: PMR-EZHA — enforcement boundary for lifecycle run state.
1462
+ // Aven lifecycle labels (LIFECYCLE_LABELS) are written ONLY through the
1463
+ // flow_phase_complete tool (tools/phase-complete.ts), which re-checks the
1464
+ // pure gates (flow/label-gate.ts over gates.ts / orchestrate.ts) before
1465
+ // exec'ing aven. Direct agent-side mutation is blocked at the bash
1466
+ // tool_call event — the ExtensionAPI does offer real interception (handler
1467
+ // returns {block, reason}), so no guard-wrapper fallback script is needed.
1468
+ // The boundary is the agent's bash TOOL: a human running aven by hand is
1469
+ // out of scope (humans own the run). Type labels (bug, oneshot, plan) stay
1470
+ // agent-writable. PMR-R5VB (review blocker fix): the same tool_call
1471
+ // interceptor also blocks forged human receipts via bash metadata writes —
1472
+ // see receiptMetadataMutation below.
1473
+ // AIDEV-NOTE: PMR-06RH — landing interceptor. `git push` / `gh pr create`
1474
+ // are blocked ONLY while the flow loop has an active ref, and only until
1475
+ // flow_land authorizes that ref's landing (landingState). No flow active →
1476
+ // undefined → normal git use outside pi-flow is never touched. A human
1477
+ // running git by hand is out of scope (humans own the run).
1478
+ // AIDEV-NOTE: PMR-06RH — landing interceptor. `git push` / `gh pr create`
1479
+ // are blocked ONLY while the flow loop has an active ref, and only until
1480
+ // flow_land authorizes that ref's landing (landingState). PMR-VZEV: the
1481
+ // authorization is cleared after use — one flow_land ok authorizes ONE
1482
+ // landing command; the next push re-blocks. No flow active → normal git
1483
+ // use outside pi-flow is never touched. A human running git by hand is
1484
+ // out of scope (humans own the run).
1485
+ // AIDEV-NOTE: PMR-VDVJ phase 4 — merge interceptor (mergeIntercept):
1486
+ // every git-merge form is blocked while a flow ref is active — the
1487
+ // flow's delivery is its GitHub PR (PMR-V31Z 4.1 deleted the merge-main
1488
+ // landing and its one-shot mergeAuthorized pin), so there is no
1489
+ // authorization that can clear this block. The same handler carries the
1490
+ // R4 runs-journal forge blocker (runsJournalWriteBlock): bash
1491
+ // writes/appends/redirects onto pi-flow/runs are blocked while a flow is
1492
+ // active — guardrail hardening for the receipt surface, NOT a security
1493
+ // boundary (aliases/`sh -c` and unmatched writers remain known limits, see
1494
+ // flow/effect-gate.ts). PMR-V31Z 6.1 removed the rebase start-form
1495
+ // interceptor (rebaseBashIntercept) that shared this handler — the
1496
+ // sanctioned integration rebase it guarded is gone; rebases are no longer
1497
+ // intercepted during flows.
1498
+ const landingState = createLandingState()
1499
+ pi.on('tool_call', (event) => {
1500
+ if (!isToolCallEventType('bash', event)) return undefined
1501
+ const label = lifecycleLabelMutation(event.input.command)
1502
+ if (label !== null) {
1503
+ return {
1504
+ block: true,
1505
+ reason: `lifecycle label "${label}" is extension-governed — call the flow_phase_complete tool instead of writing aven labels directly`,
1506
+ }
1507
+ }
1508
+ // AIDEV-NOTE: PMR-R5VB — receipt forge blocker. Writing aven metadata
1509
+ // spec-answer (any value) or plan-state=approved directly from the
1510
+ // model's bash would forge a human receipt, reaching spec_approve
1511
+ // without a human /flow answer (the flow_land consumer of such receipts
1512
+ // died with the merge-main leg — PMR-V31Z 4.1 — but the spec_approve
1513
+ // gate still stands). The review-answer key left the blocked set when
1514
+ // PMR-V31Z 7.1 deleted the review gate — with no reader it forges
1515
+ // nothing.
1516
+ // receiptMetadataMutation (flow/label-gate.ts) gates those at this same
1517
+ // boundary; the extension's own aven writes (flow/answer.ts) bypass it
1518
+ // because they are not model tool calls.
1519
+ const metadata = receiptMetadataMutation(event.input.command)
1520
+ if (metadata !== null) {
1521
+ if (metadata === 'plan-state=approved') {
1522
+ return {
1523
+ block: true,
1524
+ reason:
1525
+ 'plan-state=approved is extension-governed — approval transitions go through the receipt-gated spec_approve tool, which requires a human /flow answer first',
1526
+ }
1527
+ }
1528
+ return {
1529
+ block: true,
1530
+ reason: `aven metadata "${metadata}" is human-gated — the human records receipts with /flow answer <ref> <choice>; model-written receipts are not proof of anything`,
1531
+ }
1532
+ }
1533
+ const decision = landingIntercept(
1534
+ event.input.command,
1535
+ loop.activeRef(),
1536
+ landingState.authorized,
1537
+ )
1538
+ if (decision.action === 'block') {
1539
+ return { block: true, reason: decision.reason }
1540
+ }
1541
+ if (decision.clear) {
1542
+ landingState.authorized = null
1543
+ }
1544
+ const mergeDecision = mergeIntercept(event.input.command, loop.activeRef())
1545
+ if (mergeDecision.action === 'block') {
1546
+ return { block: true, reason: mergeDecision.reason }
1547
+ }
1548
+ const journalReason = runsJournalWriteBlock(
1549
+ event.input.command,
1550
+ loop.activeRef(),
1551
+ )
1552
+ if (journalReason !== null) {
1553
+ return { block: true, reason: journalReason }
1554
+ }
1555
+ return undefined
1556
+ })
1557
+
1558
+ // AIDEV-NOTE: PMR-0NRH 2.2 — generic mid-turn ask visibility wired onto the
1559
+ // tool_call / tool_result(+tool_execution_end) hook pair (flow/ask-emitter.ts).
1560
+ // THE SEAM: Pi AWAITS the `tool_call` handlers before it executes the tool
1561
+ // (agent-session `_beforeToolCall` -> `emitToolCall`), so the journal line
1562
+ // lands BEFORE the ask blocks. That is what makes a mid-turn
1563
+ // ask_user_question visible at all: the turn never settles while the ask
1564
+ // blocks, so the settle-based v2 emission in flow/v2-emission.ts cannot cover it.
1565
+ // The close rides `tool_result` (same turn) and `tool_execution_end`
1566
+ // (REQUIRED: a blocked/aborted call skips tool_result but still emits
1567
+ // tool_execution_end, so without the third registration an orphan
1568
+ // waiting_human would sit on the board forever); first-wins via the
1569
+ // emitter's remembered toolCallId.
1570
+ // SINGLE-WRITER RULE: this must ride THE wrapped fan-out writer (the
1571
+ // `writer` constructed above via createEventFanoutWriter — the same object
1572
+ // registerCodeReviewTool receives), never a raw createEventWriter, because
1573
+ // the fan-out's `onV2StateChangeObserved` handler is what calls
1574
+ // loop.noteExternalV2State to keep the loop's emission guard in sync with
1575
+ // tool-journaled waits (see the PMR-ZV9Y note at the fan-out construction).
1576
+ // PMR-422Q 2.2 — the `renewLease` dep below is an IN-PROCESS PING, never a
1577
+ // journal write: this emitter is the ask-liveness oracle (its heartbeatAsks
1578
+ // map tracks nested asks too), so it may renew the loop's live-wait lease
1579
+ // directly via loop.renewLiveWaitLease. That keeps the SINGLE-WRITER RULE
1580
+ // intact — a beat touches neither `writer` nor the journal, so the journal
1581
+ // can never grow from heartbeats (ISC-A-2) — and it is why the renewal is
1582
+ // NOT routed through the onV2StateChangeObserved observer above.
1583
+ // NESTED-CALL CONTRACT (two-tier dedupe, doc-cited): a tool-owned ask made
1584
+ // via ctx.executeTool DOES re-fire these hooks — docs/extensions.md
1585
+ // "Calling Other Tools" (line 2794) states nested calls go through the
1586
+ // `tool_call` and `tool_result` handlers like model-issued calls, carry
1587
+ // `parentToolCallId`, and get `toolCallId` assigned by Pi as
1588
+ // `<parent id>/<n>`. PRIMARY tier: the emitter skips any open whose
1589
+ // `parentToolCallId` is set, because a nested ask is owned by a tool that
1590
+ // journals its own wait (tools/code-review.ts does exactly this). SECONDARY
1591
+ // tier: for a non-nested open, the journal-tail `waiting_human` scan (the
1592
+ // emitter's module-local `lastV2StateRecord` — the SAME derivation the close
1593
+ // uses, so the close never demands more of the journal than the open did)
1594
+ // skips a double-open when a loop-owned wait is already journaled.
1595
+ // DEFENCE IN DEPTH: correctness would survive even
1596
+ // without the primary check, because the emitter's close is Map-gated on
1597
+ // toolCallId and can never fire for a call this emitter did not track — the
1598
+ // Map key is set on tracking, before the dedupe read and before any open
1599
+ // record is journaled, so a close may still fire for a call whose open was
1600
+ // never journaled. The primary check remains the load-bearing mechanism,
1601
+ // not a fallback.
1602
+ // This registration is a SEPARATE handler from the bash/landing interceptor
1603
+ // above; it never blocks and never reorders that gate. Handlers registered
1604
+ // here intentionally do not unsubscribe (session lifetime, like the
1605
+ // interceptors above).
1606
+ const askEmitter = createAskEmitter({
1607
+ getActiveRef: () => loop.activeRef(),
1608
+ writer,
1609
+ readEvents: (ref) => readRunEvents(getAgentDir(), ref),
1610
+ now: () => new Date().toISOString(),
1611
+ renewLease: (ref) => loop.renewLiveWaitLease(ref),
1612
+ })
1613
+ pi.on('tool_call', askEmitter.onToolCall)
1614
+ pi.on('tool_result', askEmitter.onToolFinalized)
1615
+ pi.on('tool_execution_end', askEmitter.onToolFinalized)
1616
+
1617
+ // AIDEV-NOTE: PMR-VE27 — the phase-complete tool gets the production
1618
+ // close-out deps: journaled mode (readRunMode), the journaled yolo bit
1619
+ // (isYoloRun), and the prLandingEffect journal probe above. RE-BASED by
1620
+ // PMR-V31Z (rebase supersede): the PMR-5THZ landing closure
1621
+ // (isFlowBranchLanded) is DELETED with the local-merge landing it proved —
1622
+ // prEffect is the only close-out evidence left. An absent probe dep maps
1623
+ // to a null proof inside the tool and refuses fail-closed, so the probe
1624
+ // closure is passed explicitly here.
1625
+ registerPhaseCompleteTool(
1626
+ pi,
1627
+ undefined,
1628
+ writer,
1629
+ isYoloRun,
1630
+ readRunMode,
1631
+ prLandingEffect,
1632
+ // AIDEV-NOTE: PMR-N0D5 — the plan receipt exemption gets the
1633
+ // EPOCH-AWARE yolo reader (bit after the latest run-start, non-terminal
1634
+ // loop, else no exemption). The close-out dispatch above keeps isYoloRun
1635
+ // (terminal-run close-out semantics are pinned, ISC-A-4).
1636
+ isYoloRunCurrent,
1637
+ )
1638
+ // AIDEV-NOTE: the durable answer-side landing routes are both gone: the
1639
+ // head-unpinned route (PMR-R5VB readReviewAnswer) was removed earlier, and
1640
+ // PMR-V31Z 7.1 deleted the review-gate answer and its dispatcher head-stamp
1641
+ // (the former stampReviewPass wiring here). /flow answer now serves only
1642
+ // the spec gate; the lineage-route and 3.4 integration seams (raw-journal
1643
+ // reader, ancestry probe, narrow exec, strict receipt writer) were deleted
1644
+ // with the sanctioned-rebase subsystem (PMR-V31Z 4.2/5.1).
1645
+ registerLandTool(pi, {
1646
+ state: landingState,
1647
+ activeRef: () => loop.activeRef(),
1648
+ runSuite: defaultSuiteRunner,
1649
+ writer,
1650
+ // AIDEV-NOTE: PMR-VDVJ — strict effect journal for the pr landing's
1651
+ // declare-before-authorize gate; journal-only O_APPEND writes are
1652
+ // daemon-safe by design (the projection folds in on the next full write).
1653
+ effects: createEffectJournal(getAgentDir()),
1654
+ })
1655
+ // AIDEV-NOTE: PMR-T8ZG — the ad-hoc human code-review tool (PMR-3ZY1;
1656
+ // PMR-V31Z 7.2 made it standalone): it shares no state with the flow
1657
+ // tools anymore — a verdict recorded here is an aven note on the ref, and
1658
+ // the v2 wait emissions ride the wrapped writer.
1659
+ registerCodeReviewTool(pi, writer)
1660
+ // AIDEV-NOTE: PMR-R9EN — the deviation gate is a registered tool so the
1661
+ // validate prompt can instruct the agent to CALL something (D3/D4) instead
1662
+ // of naming TS functions it cannot invoke.
1663
+ registerDeviationReviewTool(pi, writer)
1664
+ // AIDEV-NOTE: PMR-XTQQ 4.2 — the flow_run_attempt budget is durable: the
1665
+ // tool journals attempt-record snapshots through the mode-aware writer
1666
+ // (journal-only while the daemon owns the projection) and seeds from the
1667
+ // journal on first call per ref. Ledger io failures degrade to in-memory.
1668
+ registerRunAttemptTool(
1669
+ pi,
1670
+ createAttemptLedger(getAgentDir(), {
1671
+ record: async (event) => {
1672
+ // Outcome boolean intentionally discarded: the ledger is best-effort.
1673
+ await writer.record(event)
1674
+ },
1675
+ }),
1676
+ // AIDEV-NOTE: PMR-ZV9Y 2.2 — the escalation wait's v2 state-change rides
1677
+ // the SAME mode-aware writer as the attempt-record snapshots above (one
1678
+ // writer, so the durable journal and the phase-4 telemetry fan-out see
1679
+ // both). The tool wraps the call, so a throwing seam can never change the
1680
+ // escalation outcome (ISC-A-5).
1681
+ {
1682
+ journalV2: async (event) => {
1683
+ await writer.record(event)
1684
+ },
1685
+ },
1686
+ )
1687
+ // AIDEV-NOTE: PMR-CD46 — mode-aware writer so spec_approve receipt
1688
+ // writes route journal-only while the daemon owns the projection
1689
+ // (mirrors registerPhaseCompleteTool above).
1690
+ registerSpecApproveTool(pi, undefined, writer)
1691
+ // AIDEV-NOTE: PMR-C998 — advisory step-output journaling via flow_submit;
1692
+ // shares the mode-aware writer so journal writes stay daemon-safe.
1693
+ registerFlowSubmitTool(pi, { writer })
1694
+ // AIDEV-NOTE: PMR-XCA9 — plan-tools absorbed from the retired pi-planning
1695
+ // package (resolve_spec_path, resolve_feature_path, open_in_pane,
1696
+ // jira_create_branch; /review-spec lives in spec-review/commands.ts).
1697
+ registerResolveSpecPath(pi)
1698
+ registerResolveFeaturePath(pi)
1699
+ registerResolveNotesPath(pi)
1700
+ registerOpenInPane(pi)
1701
+ registerJiraCreateBranch(pi)
1702
+
1703
+ // AIDEV-NOTE: PMR-W8SG — review/sonarqube/pr-quality absorbed from the
1704
+ // retired pi-review package. Each is a self-registering extension
1705
+ // entrypoint (own commands + agent tool); pi-review is deleted, so these
1706
+ // register exactly once, here.
1707
+ reviewExtension(pi, writer)
1708
+ sonarqubeExtension(pi)
1709
+ prQualityExtension(pi)
1710
+
1711
+ // AIDEV-NOTE: PMR-K0ZV — worktree/ absorbed from the retired pi-worktree
1712
+ // package. Self-registering extension entrypoint (the `worktree` agent
1713
+ // tool); pi-worktree is deleted, so it registers exactly once, here. The
1714
+ // journal is created here so the flow-done cleanup (PMR-81SX 5.2) can
1715
+ // share the exact same instance.
1716
+ const worktreeEffects = createEffectJournal(getAgentDir())
1717
+ // AIDEV-NOTE: PMR-DRKH — worktree bind self-heal seam; the scanner is
1718
+ // the shared makeDeriveRefs() above (PMR-86NN).
1719
+ // AIDEV-NOTE: PMR-YN61 — the detailed seam is wired alongside so the bind
1720
+ // refusal can name foreign-live filtered refs and their `/flow <ref>`
1721
+ // recovery commands; both seams share makeDeriveRefsDetailed's
1722
+ // owner-scoped construction (callerSessionFile/callerPid/pidAlive).
1723
+ worktreeExtension(pi, {
1724
+ effects: worktreeEffects,
1725
+ deriveFlowRefs: makeDeriveRefs(),
1726
+ deriveFlowRefsDetailed: makeDeriveRefsDetailed(),
1727
+ })
1728
+
1729
+ // AIDEV-NOTE: PMR-YG2N 4.1 — background worktree sweep, latched fire-and-
1730
+ // forget. Latched because session_start and the /flow run path can both
1731
+ // trigger it within one session; the sweep itself is idempotent but the
1732
+ // aven execs it performs are not free, so a concurrent invocation is
1733
+ // dropped, not queued. Wiring only (PMR-T22H): all sweep logic lives in
1734
+ // worktree/sweep.ts.
1735
+ let sweepInFlight = false
1736
+ const runBackgroundSweep = (ctx: { cwd: string }): void => {
1737
+ if (sweepInFlight) {
1738
+ return
1739
+ }
1740
+ sweepInFlight = true
1741
+ const deps = {
1742
+ listRefs: async () => {
1743
+ try {
1744
+ const names = await readdir(join(getAgentDir(), 'pi-flow', 'runs'))
1745
+ return refsFromRunsDir(names)
1746
+ } catch {
1747
+ return []
1748
+ }
1749
+ },
1750
+ readEvents: async (ref: string) => {
1751
+ const events = await readRunEvents(getAgentDir(), ref)
1752
+ if (events === null) {
1753
+ return []
1754
+ }
1755
+ return events
1756
+ },
1757
+ appendEvent: (event: FlowRunEvent) => journal(event),
1758
+ readLabels: (ref: string) => readAvenLabels(ref),
1759
+ // AIDEV-NOTE: PMR-TE7Q — preserve writeAvenNote's delivery result;
1760
+ // awaiting and discarding it made failed notes look dedupe-able.
1761
+ annotate: (ref: string, body: string) => writeAvenNote(ref, body),
1762
+ // AIDEV-NOTE: PMR-YG2N fix round — the sweep's gitRoot filter must
1763
+ // match the journal's gitRoot semantics (commandPhaseInput:
1764
+ // `git rev-parse --show-toplevel` from the session cwd), NOT
1765
+ // resolveRepoRoot()'s install-root value; a foreign-root journal ref
1766
+ // under the old wiring was silently noop'd with a terminal marker.
1767
+ // resolveSessionRepoRoot never throws; null (or a throw) makes the
1768
+ // sweep return quietly (fail-closed).
1769
+ sessionGitRoot: async () => resolveSessionRepoRoot(pi, ctx.cwd),
1770
+ notify: (message: string, level: 'info' | 'warning') => {
1771
+ if (notifyUser !== null) {
1772
+ notifyUser(message, level)
1773
+ }
1774
+ },
1775
+ }
1776
+ void sweepMergedFlowWorktrees(pi, worktreeEffects, ctx.cwd, deps)
1777
+ .catch(() => {})
1778
+ .finally(() => {
1779
+ sweepInFlight = false
1780
+ })
1781
+ }
1782
+ onFlowDoneImpl = async (ref, mode, worktree, cwd) => {
1783
+ // Loop contract is Promise<void>: the CleanupFlowWorktreeSummary is
1784
+ // intentionally discarded here (observability lives in the annotate
1785
+ // path inside cleanupFlowWorktree itself, PMR-W6C4).
1786
+ const summary = await cleanupFlowWorktree(pi, worktreeEffects, {
1787
+ ref,
1788
+ mode,
1789
+ worktree,
1790
+ // AIDEV-NOTE: PMR-YG2N fix round — the done-path cwd is the session
1791
+ // repo root supplied by the caller (/flow done branch passes ctx.cwd;
1792
+ // the loop wrapper passes resolveSessionRepoRoot(pi), process-cwd
1793
+ // semantics), replacing the PMR-82K0 resolveRepoRoot() install-root
1794
+ // value that mis-scoped cleanup in foreign repos.
1795
+ cwd,
1796
+ annotate: (noteRef, body) => writeAvenNote(noteRef, body),
1797
+ })
1798
+ // AIDEV-NOTE: PMR-YG2N 3.1 — best-effort worktree-sweep marker with the
1799
+ // flow-done source so later sweeps can skip terminal outcomes; routed
1800
+ // through the mode-aware writer seam (journal closure above).
1801
+ try {
1802
+ const event: Extract<FlowRunEvent, { kind: 'worktree-sweep' }> = {
1803
+ kind: 'worktree-sweep',
1804
+ at: new Date().toISOString(),
1805
+ ref,
1806
+ source: 'flow-done',
1807
+ outcome: summary.action,
1808
+ detail: summary.reason,
1809
+ }
1810
+ if (summary.annotated !== undefined) {
1811
+ event.annotated = summary.annotated
1812
+ }
1813
+ await journal(event)
1814
+ } catch {
1815
+ // a failed marker changes nothing else
1816
+ }
1817
+ return summary
1818
+ }
1819
+
1820
+ // AIDEV-NOTE: The /flow advancement hook. agent_settled fires after a run
1821
+ // fully settles (blocking ask_user_question gates keep the run in flight,
1822
+ // so gates are never raced). Fire-and-forget subagents DO settle the run
1823
+ // mid-phase — their result arrives later as a steer — so the loop's
1824
+ // hasInFlightSubagent guard keeps those settles from halting the flow.
1825
+ // The loop re-reads aven labels and either injects the next phase prompt
1826
+ // or halts — advancement is code, not model.
1827
+ pi.on('agent_settled', (_event, ctx) => {
1828
+ // AIDEV-NOTE: PMR-2KH5 — the refresh must run AFTER the loop's settle
1829
+ // work: phase-complete/phase-start are journaled only inside onSettled
1830
+ // (after an aven readLabels shell-out) and the widget projects
1831
+ // currentPhase solely from journal events, so the old concurrent refresh
1832
+ // read the pre-transition journal and re-set the stale phase (footer a
1833
+ // turn behind; done/halt never refreshed). refreshAfterSettle chains the
1834
+ // refresh onto the settle promise. Still fire-and-forget: the extension
1835
+ // runner awaits handlers, so awaiting the shell-out here would stall
1836
+ // pi's idle resolution; the onSettled rejection stays unhandled, as
1837
+ // before (fail-noisy).
1838
+ void refreshAfterSettle(() => loop.onSettled())
1839
+ // AIDEV-NOTE (PMR-ZGPY 3.2): pull-based widget refresh — no fs.watch in
1840
+ // the flow process (ISC-A-3); the widget updates on settle signals.
1841
+ // AIDEV-NOTE: PMR-XTQQ subtask 3.3 — belt-and-braces consumer path. A
1842
+ // parked record for the restored binding is consumed + re-presented here
1843
+ // when session_start's check found nothing (e.g. the daemon parked the
1844
+ // run moments later). No-ops unless a binding exists; the consumer
1845
+ // itself guards loop-active / disabled / latch / nothing-pending.
1846
+ // PMR-2KH5 decision: resumeParkedRun stays CONCURRENT with the settle
1847
+ // refresh — it re-presents a parked prompt and never journals phase
1848
+ // events, so it cannot race the widget's journal read.
1849
+ const resumeRef = boundRef
1850
+ if (resumeRef !== null) {
1851
+ void resumeParkedRun(resumeConsumerDeps(resumeRef))
1852
+ return
1853
+ }
1854
+ // AIDEV-NOTE: PMR-T9ZQ 3.2 — belt-and-braces CONSENT gate for a LATE
1855
+ // parked candidate (the daemon parked the run after session_start's scan
1856
+ // found nothing, and a session with no binding used to let it stall
1857
+ // silently). boundRef === null now runs the SAME askResumeThenArm gate as
1858
+ // startup, once per process. Three guards carry the contract: the sync
1859
+ // door check (a settle landing while the startup picker is open never
1860
+ // stacks a second menu); the post-scan re-check (askResumeThenArm guards
1861
+ // 'asking' but never 'done', so an ask that completed during our scan
1862
+ // must not be spent again); and the live-binding check — a session that
1863
+ // started /flow HERE owns a run without boundRef being set (that var
1864
+ // only tracks the session_start restore), and adopting its own parked run
1865
+ // would drop a real worktree binding back to null. A headless fallback
1866
+ // never reaches a menu, so the latch is pinned here too — otherwise every
1867
+ // settle would re-print those recovery lines. Net effect: this path
1868
+ // reaches resumeParkedRun for NO ref that did not pass the gate.
1869
+ if (getActiveFlowRef() !== null || resumeAskState !== 'idle') {
1870
+ return
1871
+ }
1872
+ // AIDEV-NOTE: PMR-XQZM — subagent child gate, same OR-pair as the
1873
+ // session_start wrapper above: skip silently before the cooldown check
1874
+ // and the deriveCandidates scan. Parked runs stay parked for the owner
1875
+ // session; the latch stays 'idle' (the skip never spends it).
1876
+ if (isSubagentSession(durableRebind.env ?? process.env)) {
1877
+ return
1878
+ }
1879
+ void (async () => {
1880
+ // AIDEV-NOTE: PMR-1KXH — while the last EMPTY settle scan's cooldown
1881
+ // runs, a settle costs one comparison instead of a git subprocess plus
1882
+ // a full pending-dir projection. Only empty scans arm the window, so
1883
+ // this never delays a candidate that was already visible.
1884
+ if (
1885
+ lastEmptySettleScanAt !== null &&
1886
+ settleScanNow() - lastEmptySettleScanAt < EMPTY_SETTLE_SCAN_COOLDOWN_MS
1887
+ ) {
1888
+ return
1889
+ }
1890
+ let candidates: ParkedCandidate[]
1891
+ try {
1892
+ candidates = await durableRebind.deriveCandidates()
1893
+ } catch {
1894
+ return
1895
+ }
1896
+ if (candidates.length === 0) {
1897
+ // nothing parked (yet): leave the latch armed for a later settle,
1898
+ // and arm the cooldown so back-to-back settles stop paying for the
1899
+ // scan (PMR-1KXH)
1900
+ lastEmptySettleScanAt = settleScanNow()
1901
+ return
1902
+ }
1903
+ // the scan is async — a startup ask may have opened (or finished)
1904
+ // while it ran, so the latch is re-checked before spending the ask
1905
+ if (resumeAskState !== 'idle') {
1906
+ return
1907
+ }
1908
+ // PMR-BCP7: the shared runner owns the post-ask latch pinning, so this
1909
+ // site and the startup site cannot drift apart again.
1910
+ await runResumeGateOnce(ctx, candidates)
1911
+ })()
1912
+ })
1913
+
1914
+ registerPhaseCommands(pi)
1915
+ registerSpecCommands(pi)
1916
+
1917
+ // AIDEV-NOTE (PMR-EA8X): /flow-cost — offline per-ticket cost rollup from
1918
+ // the run journal + session files (the authority). --push forwards
1919
+ // aggregates to the Pushgateway when PI_FLOW_PUSHGATEWAY_URL is set
1920
+ // (endpoint override + bearer secret = the two env-var exceptions the
1921
+ // config rules allow); push failures warn, never fail.
1922
+ const costDeps: FlowCostDeps = {
1923
+ readRunEvents: (ref) => readRunEvents(getAgentDir(), ref),
1924
+ listAssignmentRecords: () => {
1925
+ const records: AssignmentRecord[] = []
1926
+ for (const view of listAssignments()) {
1927
+ if (view.state === 'unknown') continue
1928
+ records.push(view.record)
1929
+ }
1930
+ return records
1931
+ },
1932
+ readSessionFile: (file) => {
1933
+ try {
1934
+ return readFileSync(file, 'utf8')
1935
+ } catch {
1936
+ return null
1937
+ }
1938
+ },
1939
+ push: (ref, body, mode) => {
1940
+ const url = process.env.PI_FLOW_PUSHGATEWAY_URL
1941
+ if (url === undefined || url.length === 0) {
1942
+ return Promise.resolve({
1943
+ ok: false,
1944
+ error: 'PI_FLOW_PUSHGATEWAY_URL is not set',
1945
+ })
1946
+ }
1947
+ const token = process.env.PI_FLOW_PUSHGATEWAY_TOKEN
1948
+ return pushToGateway(
1949
+ url,
1950
+ ref,
1951
+ body,
1952
+ async (u, init) => {
1953
+ const response = await fetch(u, init)
1954
+ // PMR-WBC2 fix round: pass text() through so pushToGateway can put
1955
+ // a bounded snippet of the gateway's reason body into the error —
1956
+ // this wrapper backs the most user-visible failure surface (the
1957
+ // /flow-cost --push and terminal-autopush notifications).
1958
+ return {
1959
+ status: response.status,
1960
+ statusText: response.statusText,
1961
+ text: () => response.text(),
1962
+ }
1963
+ },
1964
+ token,
1965
+ mode,
1966
+ )
1967
+ },
1968
+ }
1969
+ registerFlowCostCommand(pi, costDeps)
1970
+
1971
+ // AIDEV-NOTE (PMR-MSDJ 2.3): /flow-reconcile-push — the manual face of the
1972
+ // tombstone reconcile. Every seam is the DAEMON'S OWN wiring
1973
+ // (`flow/reconcile-deps.ts`): one env gate, one journal rule,
1974
+ // one aven call, so the two surfaces cannot disagree about what is stale.
1975
+ // The only session-side difference is the channel — `warn` lands in
1976
+ // `ctx.ui.notify` here instead of `server.log`, and `agentDir` is
1977
+ // `getAgentDir()` (Pi's own resolution) rather than the daemon's
1978
+ // PI_FLOW_AGENT_DIR. See flow/reconcile-command.ts for the mode/URL
1979
+ // semantics table (`--dry-run` answers WITHOUT a gateway, a real run does not).
1980
+ const reconcileDeps: ReconcileCommandDeps = {
1981
+ createEngineDeps: (warn) =>
1982
+ createReconcileDeps({ agentDir: getAgentDir(), warn }),
1983
+ listJournalRefs: () => listJournalRefs(getAgentDir()),
1984
+ readRunEvents: (ref) => readRunEvents(getAgentDir(), ref),
1985
+ listTicketStatuses: () => listTicketStatuses(),
1986
+ // AIDEV-NOTE: PMR-7B8M — session-side daemon staleness probe for the
1987
+ // /flow-reconcile-push report. `pi.exec` is wrapped in an arrow closure
1988
+ // (a bare method reference loses `this`).
1989
+ // AIDEV-NOTE: PMR-7B8M rev 2 (review P2) — the session cwd MUST be read
1990
+ // inside this arrow, per call: without an explicit cwd, pi.exec falls back
1991
+ // to the extension loader's load-time cwd (fixed when pi starts), which is
1992
+ // a different repo than the session may be in by the time the command runs
1993
+ // — `sessionCwd` is refreshed on every session_start, so it is read live
1994
+ // here like the notify sink's `cwd: () => sessionCwd`.
1995
+ checkDaemonStaleness: () =>
1996
+ checkDaemonStaleness(
1997
+ sessionStalenessDeps(
1998
+ (command: string, args: string[], options?: { cwd?: string }) =>
1999
+ pi.exec(command, args, options),
2000
+ getAgentDir(),
2001
+ sessionCwd,
2002
+ ),
2003
+ ),
2004
+ }
2005
+ registerReconcileCommand(pi, reconcileDeps)
2006
+
2007
+ // AIDEV-NOTE (PMR-PVT5 4.2): /flow-diagram wiring — mirrors the costDeps
2008
+ // shapes (readRunEvents + filtered listAssignments + try/catch session
2009
+ // reads) and owns only the side effects: diagram write under
2010
+ // `<agentDir>/pi-flow/diagrams` with an injected-clock filename stamp, and
2011
+ // a best-effort xdg-open/open fallback that resolves false on anything
2012
+ // abnormal. Filename/patch logic lives in flow-diagram/command.ts; this
2013
+ // file stays wiring-only.
2014
+ const nowMs = (): number => Date.now()
2015
+ const flowDiagramDeps: FlowDiagramDeps = {
2016
+ readRunEvents: (ref) => readRunEvents(getAgentDir(), ref),
2017
+ listAssignmentRecords: () => {
2018
+ const records: AssignmentRecord[] = []
2019
+ for (const view of listAssignments()) {
2020
+ if (view.state === 'unknown') continue
2021
+ records.push(view.record)
2022
+ }
2023
+ return records
2024
+ },
2025
+ readSessionFile: (file) => {
2026
+ try {
2027
+ return readFileSync(file, 'utf8')
2028
+ } catch {
2029
+ return null
2030
+ }
2031
+ },
2032
+ loadRenderer: () => loadHpRenderer(),
2033
+ writeDiagram: async (ref, runIndex, html) => {
2034
+ const dir = join(getAgentDir(), 'pi-flow', 'diagrams')
2035
+ await fs.mkdir(dir, { recursive: true })
2036
+ const path = join(
2037
+ dir,
2038
+ `${ref}.run${runIndex}.${diagramStamp(nowMs())}.html`,
2039
+ )
2040
+ await fs.writeFile(path, html, 'utf8')
2041
+ return path
2042
+ },
2043
+ openDiagram: (path) => {
2044
+ // AIDEV-NOTE: try each opener in order; detached + stdio ignore, unref
2045
+ // the child, resolve false on spawn error or non-zero exit.
2046
+ const openers = ['xdg-open', 'open']
2047
+ const attempt = (index: number): Promise<boolean> => {
2048
+ if (index >= openers.length) return Promise.resolve(false)
2049
+ return new Promise((resolve) => {
2050
+ const child = spawn(openers[index] as string, [path], {
2051
+ detached: true,
2052
+ stdio: 'ignore',
2053
+ })
2054
+ child.on('error', () => {
2055
+ void attempt(index + 1).then(resolve)
2056
+ })
2057
+ child.on('spawn', () => {
2058
+ child.unref()
2059
+ })
2060
+ child.on('exit', (code) => {
2061
+ if (code === 0) {
2062
+ resolve(true)
2063
+ } else {
2064
+ void attempt(index + 1).then(resolve)
2065
+ }
2066
+ })
2067
+ })
2068
+ }
2069
+ return attempt(0)
2070
+ },
2071
+ }
2072
+ registerFlowDiagramCommand(pi, flowDiagramDeps)
2073
+ // AIDEV-NOTE: cost metrics are pushed automatically when a run ends (done,
2074
+ // halt, pause) — same env gate as `/flow-cost --push`; see flow/cost-autopush.ts.
2075
+ autoPushCost = createCostAutoPush({
2076
+ ...costDeps,
2077
+ enabled: () => (process.env.PI_FLOW_PUSHGATEWAY_URL ?? '').length > 0,
2078
+ // AIDEV-NOTE (PMR-2EGV 2.2): the terminal purge's two gateway seams,
2079
+ // pre-bound to the same env URL/token as the push wrapper above. The
2080
+ // enabled() gate runs first, so these are never called without a URL —
2081
+ // the in-wrapper guard only keeps the never-throw posture if that ever
2082
+ // changes. The manual /flow-cost --push stays a plain POST (it gets
2083
+ // costDeps only, never these).
2084
+ fetchGroupBody: (ref, mode) => {
2085
+ const url = process.env.PI_FLOW_PUSHGATEWAY_URL
2086
+ if (url === undefined || url.length === 0) {
2087
+ return Promise.resolve({
2088
+ ok: false,
2089
+ error: 'PI_FLOW_PUSHGATEWAY_URL is not set',
2090
+ })
2091
+ }
2092
+ return fetchGroupBody(
2093
+ url,
2094
+ ref,
2095
+ mode,
2096
+ process.env.PI_FLOW_PUSHGATEWAY_TOKEN,
2097
+ (u, init) => fetch(u, init),
2098
+ )
2099
+ },
2100
+ deleteGroup: (ref, mode) => {
2101
+ const url = process.env.PI_FLOW_PUSHGATEWAY_URL
2102
+ if (url === undefined || url.length === 0) {
2103
+ return Promise.resolve({
2104
+ ok: false,
2105
+ error: 'PI_FLOW_PUSHGATEWAY_URL is not set',
2106
+ })
2107
+ }
2108
+ return deleteGroup(
2109
+ url,
2110
+ ref,
2111
+ (u, init) => fetch(u, init),
2112
+ process.env.PI_FLOW_PUSHGATEWAY_TOKEN,
2113
+ mode,
2114
+ )
2115
+ },
2116
+ notify: (message, level) => {
2117
+ if (notifyUser !== null) notifyUser(`flow-cost ${message}`, level)
2118
+ },
2119
+ })
2120
+
2121
+ // AIDEV-NOTE: ad-hoc (/brainstorm, /pr-quality, /review) time + cost; see
2122
+ // adhoc/tracker.ts. Same env gate as the cost push: no URL = push fails
2123
+ // silently inside the tracker.
2124
+ configureAdhoc(
2125
+ createAdhocTracker({
2126
+ now: () => Date.now(),
2127
+ getSessionFile: () => mainSessionFile,
2128
+ readSession: costDeps.readSessionFile,
2129
+ flowActive: () => (process.env.PI_FLOW_REF ?? '').length > 0,
2130
+ trace: {
2131
+ begin: (run, nest) => telemetryHandle?.adhocBegin(run, nest),
2132
+ end: (run, attributes) => telemetryHandle?.adhocEnd(run, attributes),
2133
+ },
2134
+ push: async (runId, body) => {
2135
+ const url = process.env.PI_FLOW_PUSHGATEWAY_URL
2136
+ if (url === undefined || url.length === 0) return
2137
+ const headers: Record<string, string> = { 'content-type': 'text/plain' }
2138
+ const token = process.env.PI_FLOW_PUSHGATEWAY_TOKEN
2139
+ if (token !== undefined && token.length > 0) {
2140
+ headers.authorization = `Bearer ${token}`
2141
+ }
2142
+ await fetch(
2143
+ `${url.replace(/\/+$/, '')}/metrics/job/pi-flow-adhoc/run/${encodeURIComponent(runId)}`,
2144
+ { method: 'POST', headers, body },
2145
+ )
2146
+ },
2147
+ }),
2148
+ )
2149
+ pi.on('agent_settled', () => {
2150
+ void adhocSettled()
2151
+ })
2152
+ pi.on('session_shutdown', () => {
2153
+ void adhocCloseMain()
2154
+ })
2155
+
2156
+ // AIDEV-NOTE (PMR-R8AG): OTLP telemetry, disabled by default. The
2157
+ // session_start probe resolves telemetry config (global + project merge,
2158
+ // same loader as everything else); null = zero subscriptions, zero
2159
+ // allocations. PI_FLOW_OTLP_TOKEN (env, never config) adds the bearer
2160
+ // header. Export failures journal at most ONE note per process — flow
2161
+ // runs must proceed identically with no backend at all.
2162
+ const telemetry = registerTelemetry(pi, {
2163
+ loadSettings: async (cwd) => {
2164
+ const config = await loadConfig(cwd)
2165
+ // AIDEV-NOTE: PMR-ZV9Y 4.3 — the OTLP session_start probe doubles as the
2166
+ // ONE config read the Loki fan-out needs (README: telemetry.loki is read
2167
+ // once per session). Synced BEFORE the enabled check below because
2168
+ // `telemetry.enabled: false` + `telemetry.loki.enabled: true` is a valid
2169
+ // combination: Loki pushes without any OTLP subscription.
2170
+ syncLokiSettings(config)
2171
+ // PMR-ZV9Y 5.2: the notify channel is likewise independent of the OTLP
2172
+ // master switch, so it syncs from this same session_start read.
2173
+ syncNotifySettings(config, cwd)
2174
+ const telemetry = config.telemetry
2175
+ if (telemetry === undefined || !telemetry.enabled) return null
2176
+ const endpoint = telemetry.otlpEndpoint
2177
+ // AIDEV-NOTE: PMR-VSST — unreachable in practice: readConfigFile
2178
+ // rejects telemetry.enabled=true without otlpEndpoint at the config
2179
+ // boundary, and loadConfig above runs that same check. The guard only
2180
+ // narrows the now-optional type for TelemetrySettings — no cast.
2181
+ if (endpoint === undefined) return null
2182
+ const headers: Record<string, string> = { ...(telemetry.headers ?? {}) }
2183
+ const token = process.env.PI_FLOW_OTLP_TOKEN
2184
+ if (token !== undefined && token.length > 0) {
2185
+ headers.authorization = `Bearer ${token}`
2186
+ }
2187
+ return {
2188
+ endpoint,
2189
+ headers,
2190
+ captureContent: telemetry.captureContent,
2191
+ jiraBaseUrl: telemetry.jiraBaseUrl,
2192
+ maxContentChars: telemetry.maxContentChars,
2193
+ }
2194
+ },
2195
+ env: process.env,
2196
+ rng: { bytes: (n) => randomBytes(n) },
2197
+ fetchImpl: async (url, init) => {
2198
+ const response = await fetch(url, init)
2199
+ return { status: response.status }
2200
+ },
2201
+ now: () => Date.now(),
2202
+ onExportFailure: (error) => {
2203
+ const ref = loop.activeRef()
2204
+ if (ref === null) return
2205
+ void journal({
2206
+ kind: 'note',
2207
+ at: new Date().toISOString(),
2208
+ ref,
2209
+ text: `telemetry export failed: ${error} (further failures silent)`,
2210
+ })
2211
+ },
2212
+ })
2213
+ syncTelemetryFlowEnv = telemetry.syncFlowEnv
2214
+ telemetryHandle = telemetry
2215
+
2216
+ // AIDEV-NOTE: PMR-T8ZG — human entry point of the ad-hoc code review
2217
+ // (PMR-V31Z 7.2: standalone utility, no flow gate behind it). The
2218
+ // command resolves the ref and sends the ad-hoc prompt via
2219
+ // sendUserMessage (phase-command pattern); the code_review tool owns
2220
+ // everything else. Agents cannot invoke slash commands, which is exactly
2221
+ // why the tool exists.
2222
+ pi.registerCommand('code-review', {
2223
+ description:
2224
+ 'Run an ad-hoc human code review for a ref. Usage: /code-review <jira-id | aven-ref>',
2225
+ handler: async (args, ctx) => {
2226
+ const raw = args.trim()
2227
+ if (raw === '') {
2228
+ ctx.ui.notify('Usage: /code-review <jira-id | aven-ref>', 'info')
2229
+ return
2230
+ }
2231
+ const kinded = parseRefKind(raw)
2232
+ let ref: string
2233
+ if (kinded.kind === 'jira') {
2234
+ ref = kinded.jiraId
2235
+ } else {
2236
+ ref = kinded.ref
2237
+ }
2238
+ pi.sendUserMessage(buildCodeReviewGatePrompt(ref))
2239
+ },
2240
+ })
2241
+
2242
+ // AIDEV-NOTE: alt+shift+d is the keyboard twin of `/flow dashboard` — both
2243
+ // delegate to toggleFlowDashboardPin. Precedent: pi-prompt-snippets pairs
2244
+ // alt+s with /snippets. alt+d was rejected: it is a Pi built-in
2245
+ // (tui.editor.deleteWordForward), so the old registration shadowed it — the
2246
+ // earlier no-collision check only covered in-repo extensions, not built-ins.
2247
+ pi.registerShortcut('alt+shift+d', {
2248
+ description: 'Toggle the flow dashboard widget',
2249
+ handler: async (ctx) => {
2250
+ notifyDashboardOutcome(ctx, await toggleFlowDashboardPin(ctx))
2251
+ },
2252
+ })
2253
+
2254
+ pi.registerCommand('flow', {
2255
+ description:
2256
+ 'PIV run-all (plan -> implement -> validate -> feedback; personal feedback = wrap-up: outcome summary, done, auto worktree cleanup) or record a protected human decision. Usage: /flow <ref> [--yolo] | /flow --yolo (receipt gates skipped, personal mode only) | /flow answer <ref> <approve|reject|pass|fail> | /flow dashboard. Brainstorm topics go through /brainstorm. Completed-flow worktrees are cleaned up automatically (loop done, /flow rerun, or session/flow-start sweep) and are never deleted while dirty, in flight, or unproven.',
2257
+ // AIDEV-NOTE: Aven IS the run state — labels fetched fail-closed (aven
2258
+ // failure aborts, never starts mid-phase by accident). nextPhase()
2259
+ // resolves the first phase whose completion label is missing, then the
2260
+ // extension-owned loop (flow/loop.ts) takes over: it injects ONE phase
2261
+ // prompt at a time (same builder the phase commands use) and advances on
2262
+ // agent_settled when the phase label lands. No driver agent — the model
2263
+ // never sequences phases.
2264
+ handler: async (args, ctx) => {
2265
+ const answerParsed = parseFlowAnswerArgs(args)
2266
+ if (answerParsed.kind === 'answer-help') {
2267
+ ctx.ui.notify(answerUsageText, 'info')
2268
+ return
2269
+ }
2270
+ if (answerParsed.kind === 'answer') {
2271
+ // AIDEV-NOTE: PMR-R5VB + PMR-DMHH 2.2 — /flow answer is the
2272
+ // HUMAN-ONLY decision recorder, and the answer is RECEIPT-FIRST:
2273
+ // executeFlowAnswer fail-closed-writes the metadata receipt before
2274
+ // anything else can act on the choice (a failed write means no
2275
+ // wake, no note, no journal — early return inside
2276
+ // executeFlowAnswer). AFTER a successful record the dispatcher's
2277
+ // optional onGateAnswered hook MAY inject a wake — `/flow <ref>`
2278
+ // for approve-on-paused, a plain message for reject/standalone —
2279
+ // reusing the resumeParkedRun injection pattern
2280
+ // (pi.sendUserMessage with expandPromptTemplates). The wake is
2281
+ // human-initiated by construction: slash commands run before the
2282
+ // agent loop (extensions.md) and cannot be invoked by the agent,
2283
+ // so a model turn is only ever triggered by a human keystroke.
2284
+ // The never-forge property (PMR-R5VB) is preserved because the
2285
+ // wake carries no authority: spec_approve re-reads the receipt
2286
+ // fail-closed, so an injected wake without a receipt still
2287
+ // refuses. Same ref charset guard as the run path — the journal
2288
+ // filename derives from the ref.
2289
+ if (!isValidRef(answerParsed.ref)) {
2290
+ ctx.ui.notify(
2291
+ `/flow answer ${answerParsed.ref}: invalid ref (must match [A-Za-z0-9][A-Za-z0-9._-]{0,99}) — aborting.`,
2292
+ 'warning',
2293
+ )
2294
+ return
2295
+ }
2296
+ await executeFlowAnswer(
2297
+ { ref: answerParsed.ref, choice: answerParsed.choice },
2298
+ makeAnswerDeps(ctx),
2299
+ )
2300
+ return
2301
+ }
2302
+ // AIDEV-NOTE (PMR-C3B6): '/flow dashboard' is a literal token reserved at the
2303
+ // HANDLER level, before parseFlowArgs — 'dashboard' matches the ref charset
2304
+ // ([A-Za-z0-9][A-Za-z0-9._-]{0,99}) so without this branch it would start a
2305
+ // run for a ticket named 'dashboard'. Exact single token, case-insensitive
2306
+ // (same reservation semantics as the 'help' literal in flow/args.ts,
2307
+ // PMR-N0W6). Toggle-only: never sendUserMessage, never spawns.
2308
+ if (args.trim().toLowerCase() === 'dashboard') {
2309
+ notifyDashboardOutcome(ctx, await toggleFlowDashboardPin(ctx))
2310
+ return
2311
+ }
2312
+ let parsed: FlowArgs = parseFlowArgs(args)
2313
+ if (isPickerInvocation(args)) {
2314
+ // AIDEV-NOTE (PMR-ZGPY 4.2, PMR-XQA1; fix round 2): ONLY zero-arg
2315
+ // /flow opens the two-step picker (gate select → choice select). Every
2316
+ // other arg shape keeps the parseFlowArgs usage notify below —
2317
+ // /flow X Y is a typo, not a picker. The picker ANSWERS gates via
2318
+ // executeFlowAnswer with the SAME deps the /flow answer subcommand
2319
+ // uses (makeAnswerDeps). PMR-DMHH 2.2 renegotiates the old
2320
+ // PMR-W60H/ISC-A-1 never-sendUserMessage claim for the ANSWER
2321
+ // branch by explicit decision: a picked answer shares the
2322
+ // onGateAnswered wake hook, so it wakes exactly like a typed one
2323
+ // (parity by construction, ISC-5) and passes the same
2324
+ // paused-waiter ownership guard (ISC-13). The picker itself still
2325
+ // never STARTS a run: it never spawns, and the only fall-through
2326
+ // is the ready-ticket 'run' plan handled below. It is fully
2327
+ // independent of T6 (D10). All decision logic is pure
2328
+ // (planPickerOutcome); this handler only performs ctx.ui.select IO
2329
+ // and acts on the plan. Menu option values are the composite
2330
+ // ref|kind (splitGateValue) so same-ref rows resolve their own
2331
+ // vocabulary (fix round 2). collectOpenGates failure is fail-closed:
2332
+ // warn once, never throw (ISC-13). ctx.ui.select returns the option
2333
+ // STRING or undefined on cancel (Pi types.d.ts) — labels map back to
2334
+ // values through the option lists.
2335
+ // AIDEV-NOTE (PMR-3E1Z 3.1): the ONLY fall-through outcome is the
2336
+ // ready-ticket 'run' plan: a picked ref is reassigned into `parsed`
2337
+ // as { kind: 'aven', ref } and the block falls through into the
2338
+ // standard run path — the exact same start a typed /flow <ref> gets.
2339
+ // Every other picker outcome returns inside this block. No
2340
+ // sendUserMessage / spawn / resume on the fall-through path itself
2341
+ // (PMR-W60H / ISC-A-1): falling through IS the flow start. (The
2342
+ // ANSWER branch's wake now goes through the shared makeAnswerDeps
2343
+ // hook — see the PMR-DMHH 2.2 anchor above — not through any send
2344
+ // on this run fall-through path.)
2345
+ let gates: OpenGate[] = []
2346
+ const collected = await collectGatesOrWarn(ctx)
2347
+ if (collected === null) {
2348
+ return
2349
+ }
2350
+ gates = collected
2351
+ let plan = planPickerOutcome(ctx.hasUI, gates)
2352
+ if (plan.kind === 'menu') {
2353
+ const labelToValue = new Map(
2354
+ plan.options.map((o) => [o.label, o.value]),
2355
+ )
2356
+ const picked = await ctx.ui.select(
2357
+ 'Open gate — pick one:',
2358
+ plan.options.map((o) => o.label),
2359
+ )
2360
+ if (picked === undefined) {
2361
+ plan = planPickerOutcome(ctx.hasUI, gates, {
2362
+ stage: 'gate-cancelled',
2363
+ })
2364
+ } else {
2365
+ const value = labelToValue.get(picked) ?? ''
2366
+ // Sentinel row first (PMR-3E1Z): the ready-ticket row must never
2367
+ // reach splitGateValue — it is not a composite ref|kind value.
2368
+ if (value === TICKET_ROW_VALUE) {
2369
+ plan = planPickerOutcome(ctx.hasUI, gates, {
2370
+ stage: 'ticket-row-picked',
2371
+ })
2372
+ } else {
2373
+ // Composite value → ref+kind (fix round 2): ref-only lookup could
2374
+ // first-match another row sharing the ref.
2375
+ const split = splitGateValue(value)
2376
+ plan = planPickerOutcome(ctx.hasUI, gates, {
2377
+ stage: 'gate-picked',
2378
+ gateRef: split.ref,
2379
+ gateKind: split.kind,
2380
+ })
2381
+ }
2382
+ }
2383
+ }
2384
+ if (plan.kind === 'choice-menu') {
2385
+ const labelToValue = new Map(
2386
+ plan.options.map((o) => [o.label, o.value]),
2387
+ )
2388
+ const chosen = await ctx.ui.select(
2389
+ `${plan.gateRef} — answer with:`,
2390
+ plan.options.map((o) => o.label),
2391
+ )
2392
+ if (chosen === undefined) {
2393
+ plan = planPickerOutcome(ctx.hasUI, gates, {
2394
+ stage: 'choice-cancelled',
2395
+ gateRef: plan.gateRef,
2396
+ gateKind: plan.gateKind,
2397
+ })
2398
+ } else {
2399
+ plan = planPickerOutcome(ctx.hasUI, gates, {
2400
+ stage: 'answered',
2401
+ gateRef: plan.gateRef,
2402
+ gateKind: plan.gateKind,
2403
+ choice: labelToValue.get(chosen) ?? '',
2404
+ })
2405
+ }
2406
+ }
2407
+ if (plan.kind === 'tickets') {
2408
+ // PMR-3E1Z 3.1 / yolo plan 1.2: ready-ticket picker step, shared
2409
+ // with the /flow --yolo shortcut via pickReadyTicketRef. Only
2410
+ // 'run' falls through (parsed reassigned below); everything else
2411
+ // notifies or stays silent and returns.
2412
+ const ticketRef = await pickReadyTicketRef(ctx, gates.length > 0)
2413
+ if (ticketRef === undefined) {
2414
+ return
2415
+ }
2416
+ // AIDEV-NOTE (PMR-3E1Z): picked refs join the run path exactly
2417
+ // like a typed /flow <aven-ref> — parsed reassigned, block falls
2418
+ // through. 'aven' never matches the 'jira' branch below, so
2419
+ // picked refs skip Jira resolution like typed aven refs.
2420
+ parsed = { kind: 'aven', ref: ticketRef, yolo: false }
2421
+ } else if (plan.kind === 'fallback') {
2422
+ for (const line of plan.lines) {
2423
+ ctx.ui.notify(line, 'info')
2424
+ }
2425
+ return
2426
+ } else if (plan.kind === 'empty') {
2427
+ // 'empty' is purely silent now (PMR-3E1Z): zero-gate invocations
2428
+ // return 'tickets' before this branch, so it only covers user
2429
+ // cancel / lookup miss — notify nothing.
2430
+ return
2431
+ } else if (plan.kind === 'print-command') {
2432
+ ctx.ui.notify(
2433
+ `/flow answer ${plan.ref} ${plan.choices.join('|')}`,
2434
+ 'info',
2435
+ )
2436
+ return
2437
+ } else if (plan.kind === 'answer') {
2438
+ await executeFlowAnswer(
2439
+ { ref: plan.ref, choice: plan.choice },
2440
+ makeAnswerDeps(ctx),
2441
+ )
2442
+ return
2443
+ } else {
2444
+ // AIDEV-NOTE: PMR-P3MB — catch-all safety net. Every current
2445
+ // PickerPlan kind is handled above (a hypothetical miss would land
2446
+ // on the benign parsed {kind:'help'} path), but a FUTURE variant
2447
+ // must never slide into the flow-start path below.
2448
+ return
2449
+ }
2450
+ }
2451
+ if (parsed.kind === 'picker') {
2452
+ // AIDEV-NOTE (yolo plan 1.2): bare '/flow --yolo' skips the
2453
+ // gate-answering select — a yolo run never waits on gates — and
2454
+ // lands directly on the ready-ticket picker. The picked ref is
2455
+ // reassigned with yolo: true and falls through into the standard
2456
+ // run path below, exactly like the zero-arg picker's 'run'
2457
+ // outcome. Gate collection stays because the ticket picker
2458
+ // suppresses its no-gates message while gates are open; a gate
2459
+ // read failure warns fail-closed and returns, never starts a run.
2460
+ const collected = await collectGatesOrWarn(ctx)
2461
+ if (collected === null) {
2462
+ return
2463
+ }
2464
+ const yoloRef = await pickReadyTicketRef(ctx, collected.length > 0)
2465
+ if (yoloRef === undefined) {
2466
+ return
2467
+ }
2468
+ parsed = { kind: 'aven', ref: yoloRef, yolo: true }
2469
+ }
2470
+ if (parsed.kind === 'help') {
2471
+ // Fix round 2: non-zero-arg /flow keeps the pre-picker usage notify —
2472
+ // the picker is exclusively the zero-arg invocation (isPickerInvocation).
2473
+ ctx.ui.notify(FLOW_USAGE, 'info')
2474
+ return
2475
+ }
2476
+ const mode = await resolveMode(pi, ctx.cwd)
2477
+ let ref: string
2478
+ if (parsed.kind === 'jira') {
2479
+ if (!MODE_PROFILE[mode].acceptsJiraRefs) {
2480
+ ctx.ui.notify(
2481
+ `/flow ${parsed.jiraId}: Jira IDs are work-mode only (this repo is personal) — use an aven ref`,
2482
+ 'warning',
2483
+ )
2484
+ return
2485
+ }
2486
+ const resolved = await resolveJiraEpic(parsed.jiraId, avenExec)
2487
+ if (resolved.kind === 'abort') {
2488
+ ctx.ui.notify(`/flow ${parsed.jiraId}: ${resolved.reason}`, 'warning')
2489
+ return
2490
+ }
2491
+ ref = resolved.ref
2492
+ if (resolved.created) {
2493
+ ctx.ui.notify(
2494
+ `/flow ${parsed.jiraId}: pulled in local epic ${resolved.ref}`,
2495
+ 'info',
2496
+ )
2497
+ }
2498
+ } else {
2499
+ ref = parsed.ref
2500
+ }
2501
+ // AIDEV-NOTE: PMR-HFK1 — charset guard BEFORE run-start: the journal
2502
+ // filename and the attribution env both derive from the ref (the loop
2503
+ // re-checks at start; this keeps the run-start event out of a journal
2504
+ // whose projection would be unusable).
2505
+ if (!isValidRef(ref)) {
2506
+ ctx.ui.notify(
2507
+ `/flow ${ref}: invalid ref (must match [A-Za-z0-9][A-Za-z0-9._-]{0,99}) — aborting.`,
2508
+ 'warning',
2509
+ )
2510
+ return
2511
+ }
2512
+ // AIDEV-NOTE: PMR-XTQQ — ensure the durable run server at run start,
2513
+ // BEFORE the loop starts: a live daemon takes over projection ownership
2514
+ // so every subsequent journal write routes journal-only. Spawn failure
2515
+ // or disabled switch → notify once and continue (never block the flow;
2516
+ // the full-writer fallback is today's exact behavior).
2517
+ const config = await loadConfig(ctx.cwd)
2518
+ runServerEnabled = resolveRunServerEnabled(config)
2519
+ // AIDEV-NOTE: PMR-ZV9Y 4.3 — re-sync the Loki fan-out per run start, so
2520
+ // a config edit lands on the NEXT /flow without waiting for a session
2521
+ // restart (the session_start probe above covers the no-/flow path).
2522
+ syncLokiSettings(config)
2523
+ // PMR-ZV9Y 5.2: same re-sync for the desktop channel (+ the /flow cwd).
2524
+ syncNotifySettings(config, ctx.cwd)
2525
+ // AIDEV-NOTE: PMR-7B8M — resolve the checkout HEAD BEFORE ensureDaemon:
2526
+ // a fresh spawn records it in the pidfile (PI_FLOW_DAEMON_GIT_SHA env);
2527
+ // an already-running daemon is probed for staleness instead. 'spawned' is
2528
+ // fresh by construction (its pidfile carries this session's HEAD).
2529
+ const execStaleness = (
2530
+ command: string,
2531
+ args: string[],
2532
+ options?: { cwd?: string },
2533
+ ) => pi.exec(command, args, options)
2534
+ const headSha = await resolveHeadSha(execStaleness, ctx.cwd)
2535
+ if (runServerEnabled) {
2536
+ // AIDEV-NOTE: PMR-7B8M rev 2 — the daemon is ONE GLOBAL process serving
2537
+ // every repo, so the SHA alone cannot tell a later session whether it
2538
+ // describes THEIR repo (review P1: cross-repo false positives). Record
2539
+ // the repo's MAIN-worktree path next to the SHA; the staleness verdict
2540
+ // goes silent when a session's main checkout differs. The recorded SHA
2541
+ // stays the SPAWNING checkout's HEAD (a worktree spawn records the
2542
+ // worktree HEAD — that is the provenance of the code it loaded).
2543
+ const mainCheckout = await resolveMainCheckout(execStaleness, ctx.cwd)
2544
+ let gitRoot: string | null = null
2545
+ if (mainCheckout !== null) {
2546
+ gitRoot = mainCheckout.path
2547
+ }
2548
+ const ensured = await ensureDaemon(getAgentDir(), undefined, {
2549
+ gitSha: headSha,
2550
+ gitRoot,
2551
+ })
2552
+ if (
2553
+ ensured.status === 'spawn-timeout' ||
2554
+ ensured.status === 'spawn-failed'
2555
+ ) {
2556
+ let detail = ''
2557
+ if (ensured.status === 'spawn-failed') {
2558
+ detail = ` (${ensured.reason})`
2559
+ }
2560
+ ctx.ui.notify(
2561
+ `pi-flow: run server not started${detail} — continuing in-session; runs won't survive a session exit`,
2562
+ 'warning',
2563
+ )
2564
+ }
2565
+ // AIDEV-NOTE: PMR-7B8M — only an already-running daemon can be stale;
2566
+ // 'spawned' is fresh by construction and spawn-timeout/spawn-failed keep
2567
+ // their existing warnings above. Awaited (never-throws, bounded) so the
2568
+ // notification lands before the run continues; a stale pidfile never
2569
+ // blocks the flow. PMR-5563: the actionable verdict auto-restarts when
2570
+ // the idle gate passes — the same handleDaemonStaleness seams as
2571
+ // session_start, but headSha/gitRoot are REUSED from the ensureDaemon
2572
+ // call above instead of re-resolving provenance. A busy daemon or a
2573
+ // failed restart keeps the manual-kill warning.
2574
+ if (ensured.status === 'already-running') {
2575
+ await handleDaemonStaleness(
2576
+ {
2577
+ ...sessionStalenessDeps(execStaleness, getAgentDir(), ctx.cwd),
2578
+ isIdle: async () => {
2579
+ if (loop.isActive()) return false
2580
+ return !(await hasActiveFlowRun(getAgentDir(), realPidAlive))
2581
+ },
2582
+ restart: (pid: number) =>
2583
+ restartDaemon(getAgentDir(), pid, {
2584
+ gitSha: headSha,
2585
+ gitRoot,
2586
+ }),
2587
+ },
2588
+ (message: string, level: 'info' | 'warning') =>
2589
+ ctx.ui.notify(message, level),
2590
+ )
2591
+ }
2592
+ }
2593
+ // AIDEV-NOTE: PMR-9DZ0 — single shared aven call feeds BOTH the
2594
+ // fail-closed labels read and the best-effort title: readAvenSnapshot
2595
+ // replaces readAvenLabels here and returns the full snapshot, so the
2596
+ // title is free (zero extra aven shell-outs in personal mode). The
2597
+ // fail-closed abort below is byte-identical in message and behavior —
2598
+ // `!snapshot.ok` (fuzzy-match / bad-json / exec throw, all recorded via
2599
+ // lastAvenResolutionFailure) aborts exactly as a null labels read did.
2600
+ // The title itself is sanitized at the journal write seam (run-title.ts)
2601
+ // and is best-effort: a title lookup never blocks the run.
2602
+ const snapshot = await readAvenSnapshot(ref)
2603
+ if (snapshot === null || !snapshot.ok) {
2604
+ const detail =
2605
+ lastAvenResolutionFailure() ??
2606
+ 'Check that the ref exists and aven is available.'
2607
+ ctx.ui.notify(
2608
+ `/flow ${ref}: cannot read aven labels — aborting (fail-closed). ${detail}`,
2609
+ 'warning',
2610
+ )
2611
+ return
2612
+ }
2613
+ const labels = snapshot.labels
2614
+ const next = nextPhase(labels, mode)
2615
+ // AIDEV-NOTE: PMR-VE27 — the start path's label mapping. PMR-V31Z: the
2616
+ // done branch's landing-continuation leg is superseded (personal
2617
+ // delivers via PR and is unmerged BY DESIGN at close-out), so the
2618
+ // mapping IS the label mapping again — no re-mapping, no suffix.
2619
+ if (next.kind === 'done') {
2620
+ // AIDEV-NOTE: PMR-VE27 (plan decision 5) — the all-labels re-entry
2621
+ // consults the shared lifecycle policy BEFORE the terminal treatment,
2622
+ // re-based by PMR-V31Z: the close-out evidence is the journaled
2623
+ // gh-pr-create effect for EVERY mode (the ancestry leg guarded the
2624
+ // deleted local merge; personal journals the PR effect in feedback
2625
+ // now). VERIFIED → the existing terminal treatment unchanged.
2626
+ // REFUSED → warning + return: nothing destroyed, no cleanup, no run.
2627
+ const yolo = await isYoloRun(ref)
2628
+ const proofs = await resolveCloseoutProofs(ref, {
2629
+ prEffectFn: prLandingEffect,
2630
+ })
2631
+ const terminal = reconcileTerminalEntry({
2632
+ next,
2633
+ mode,
2634
+ yolo,
2635
+ proofs,
2636
+ })
2637
+ if (terminal.kind === 'abort') {
2638
+ ctx.ui.notify(`/flow ${ref}: ${terminal.reason}`, 'warning')
2639
+ return
2640
+ }
2641
+ // AIDEV-NOTE: PMR-V31Z 2.1 — the terminal leg returns UNCONDITIONALLY
2642
+ // (after the abort check above `terminal` is the verified terminal
2643
+ // decision): the done-branch must never fall through implicitly, or
2644
+ // TS's control-flow analysis cannot narrow `next` to the phase
2645
+ // variant for the startInput below (exhaustion through a second
2646
+ // nested discriminant if is invisible to that narrowing).
2647
+ const resolved = await resolveDoneWorktree(pi, ctx.cwd, ref)
2648
+ let summary: CleanupFlowWorktreeSummary
2649
+ if (onFlowDoneImpl === null) {
2650
+ summary = { action: 'deferred', reason: 'cleanup not ready' }
2651
+ } else {
2652
+ try {
2653
+ summary = await onFlowDoneImpl(ref, mode, resolved, ctx.cwd)
2654
+ } catch {
2655
+ summary = { action: 'deferred', reason: 'cleanup error' }
2656
+ }
2657
+ }
2658
+ let cleanupLine: string
2659
+ if (summary.action === 'removed') {
2660
+ cleanupLine = `Worktree cleanup: removed ${resolved?.path ?? ''}.`
2661
+ } else if (summary.action === 'noop') {
2662
+ cleanupLine = 'Worktree cleanup: no flow worktree bound.'
2663
+ } else {
2664
+ cleanupLine = `Worktree cleanup: deferred (${summary.reason}).`
2665
+ }
2666
+ if (summary.action === 'removed' && getActiveFlowRef() === ref) {
2667
+ setActiveFlowRef(null)
2668
+ }
2669
+ ctx.ui.notify(
2670
+ `/flow ${ref}: all phase labels present (done) — nothing to run. ${cleanupLine}`,
2671
+ 'info',
2672
+ )
2673
+ return
2674
+ }
2675
+ // AIDEV-NOTE: PMR-XTQQ phase 2 — resume seeding. The journal tail's
2676
+ // latest loop-state restores the blocker-retry budget and the validate
2677
+ // blockers-note cutoff exactly; the journaled run-input scalars win
2678
+ // over a fresh rebuild ONLY while their gitRoot still exists (else the
2679
+ // fresh commandPhaseInput result is used). Phase position is never
2680
+ // seeded — aven labels re-derive it via nextPhase above.
2681
+ // PMR-ZV9Y 2.1: the SAME tail seeds the guarded v2 emission state and
2682
+ // the plan.spec-approval pairing flag, so a restart does not re-emit the
2683
+ // last state-change the prior process journaled (no running→running
2684
+ // spam across /flow re-entry) and a paused-for-approval restart still
2685
+ // closes the step it opened.
2686
+ // PMR-5THZ: this whole block (seed read + prompt-input/yolo resolution)
2687
+ // is HOISTED from below the run-start journal so the landing
2688
+ // reconciliation right after it knows yolo BEFORE anything is
2689
+ // journaled — behavior-neutral (a pure journal read plus the same
2690
+ // commandPhaseInput/mergeSeedInput pipeline); the run-input journal
2691
+ // and the startInput seed usages below consume the hoisted values
2692
+ // unchanged.
2693
+ const seedEvents = await readRunEvents(getAgentDir(), ref)
2694
+ const seed = resumeSeedFromEvents(seedEvents, (p) => existsSync(p))
2695
+ const seedV2State = resumeV2StateFromEvents(seedEvents)
2696
+ const seedPlanApprovalOpen = resumePlanApprovalOpenFromEvents(seedEvents)
2697
+ // AIDEV-NOTE (yolo plan 2.1/2.2, 6.1): thread --yolo BEFORE
2698
+ // mergeSeedInput — the journaled seed wins for yolo (flag-less resume of
2699
+ // a yolo run stays yolo; --yolo cannot upgrade a running non-yolo seed).
2700
+ // Config yolo only fills a FRESH start: absent flag (false) || config.
2701
+ // PMR-V31Z 2.1: this resolution still runs before the run-input journal
2702
+ // below; the landing reconciliation that motivated the original hoist
2703
+ // (PMR-5THZ) is deleted — personal feedback entry is label-ordered.
2704
+ let promptInput = {
2705
+ ...(await commandPhaseInput(pi, {
2706
+ mode,
2707
+ ref,
2708
+ cwd: ctx.cwd,
2709
+ })),
2710
+ yolo: parsed.yolo || config.yolo,
2711
+ }
2712
+ promptInput = mergeSeedInput(promptInput, seed)
2713
+ const yolo = promptInput.yolo === true
2714
+ promptInput = { ...promptInput, yolo }
2715
+ // AIDEV-NOTE: work/personal separation — the run is TRACKED by its Jira
2716
+ // key in work mode (typed Jira ID, else the epic's jira-ref metadata),
2717
+ // by the aven ref in personal mode. `ref` (aven) still drives the
2718
+ // journal and every aven operation.
2719
+ let epicJiraRef: string | null = null
2720
+ if (mode === 'work' && parsed.kind !== 'jira') {
2721
+ epicJiraRef = await readJiraRef(ref)
2722
+ }
2723
+ const trackRef = trackingRef({
2724
+ mode,
2725
+ avenRef: ref,
2726
+ jiraId: parsed.kind === 'jira' ? parsed.jiraId : undefined,
2727
+ epicJiraRef,
2728
+ })
2729
+ // AIDEV-NOTE: PMR-9DZ0 — best-effort run title, journaled on run-start
2730
+ // so the dashboards can show "REF — title". WHY single shared aven call:
2731
+ // personal mode reads the title off the `snapshot` above (zero extra
2732
+ // shell-outs); work mode resolves it from the Jira key (typed ref, else
2733
+ // the epic's jira-ref metadata) via the shared acli helper. The title is
2734
+ // sanitized at the journal write seam (run-title.ts). resolveRunTitle
2735
+ // never throws, but its warning must NOT abort the run: notify at
2736
+ // 'warning' and keep journaling run-start without a title.
2737
+ let jiraKey: string | null = null
2738
+ if (mode === 'work') {
2739
+ if (parsed.kind === 'jira') {
2740
+ jiraKey = parsed.jiraId
2741
+ } else {
2742
+ jiraKey = epicJiraRef
2743
+ }
2744
+ }
2745
+ // AIDEV-NOTE: PMR-RMWX — the run-start timestamp is captured BEFORE the
2746
+ // title lookup, not at the event literal. resolveRunTitle shells out to
2747
+ // acli with a 15 s timeout (plan-tools/jira-issue.ts), so stamping `at`
2748
+ // after that await pushed pi_flow_run_start_seconds (the "Started" column
2749
+ // on piflow-runs) up to 15 s late on a slow or unreachable Jira. Personal
2750
+ // mode never shell-outs, so only work mode was affected.
2751
+ const startedAt = new Date().toISOString()
2752
+ const titleResult = await resolveRunTitle(pi, {
2753
+ mode,
2754
+ avenTitle: snapshot.title,
2755
+ jiraKey,
2756
+ })
2757
+ if (titleResult.warning !== null) {
2758
+ ctx.ui.notify(`pi-flow: ${titleResult.warning}`, 'warning')
2759
+ }
2760
+ const runStartEvent: FlowRunEvent = {
2761
+ kind: 'run-start',
2762
+ at: startedAt,
2763
+ ref,
2764
+ mode,
2765
+ trackRef,
2766
+ }
2767
+ // Omit the title key entirely when unresolved (never write undefined)
2768
+ // so old journals and title-less runs stay byte-identical.
2769
+ if (titleResult.title !== undefined) {
2770
+ runStartEvent.title = titleResult.title
2771
+ }
2772
+ // AIDEV-NOTE: PMR-N0D5 — snapshot the ticket's oneshot-ness AT
2773
+ // run-start (the labels read above is the same read that derived the
2774
+ // start phase — no extra aven call). Journal-first oneshot provenance:
2775
+ // the plan receipt gates consult this snapshot (readOneshotSnapshot),
2776
+ // so a label added mid-run cannot mint the exemption. The key is
2777
+ // OMITTED when false so non-oneshot run-start lines stay
2778
+ // byte-identical to the pre-N0D5 shape.
2779
+ if (labels.includes('oneshot')) {
2780
+ runStartEvent.oneshot = true
2781
+ }
2782
+ await journal(runStartEvent)
2783
+ // AIDEV-NOTE: PMR-T9ZQ 1.2 — owner identity stamp. PROJECTED event (not
2784
+ // journal-only): the parked-run resume picker reads state.owner through
2785
+ // readRunEvents + projectRunState, so this must go through the
2786
+ // projecting `journal` seam. sessionFile is the closure's main session
2787
+ // file (null until a session_start supplied one — the loop refreshes it
2788
+ // per phase prompt); pid is the liveness carrier the picker probes.
2789
+ // Best-effort like every other journal write: writer.record never
2790
+ // rejects, so a failed stamp cannot halt the run.
2791
+ await journal({
2792
+ kind: 'owner-session',
2793
+ at: new Date().toISOString(),
2794
+ ref,
2795
+ sessionFile: mainSessionFile,
2796
+ pid: process.pid,
2797
+ })
2798
+ // AIDEV-NOTE: PMR-5THZ — the resume seeding + prompt-input/yolo
2799
+ // resolution that used to live here is HOISTED above the (since
2800
+ // PMR-V31Z 2.1, deleted) landing reconciliation and the run-start
2801
+ // journal; the run-input journal below and the startInput seed usages
2802
+ // keep consuming the hoisted seed/promptInput/yolo unchanged.
2803
+ // AIDEV-NOTE: serializable prompt-input subset; closures
2804
+ // (findTicketRef, ...) are rebuilt per invocation, never journaled.
2805
+ // mergeSeedInput (override rule) and runInputRecord (journaled shape)
2806
+ // live in flow/resume.ts — flow.test.ts covers both.
2807
+ await journal({
2808
+ kind: 'run-input',
2809
+ at: new Date().toISOString(),
2810
+ ref,
2811
+ input: runInputRecord(promptInput),
2812
+ })
2813
+ await adhocCloseMain()
2814
+ const startInput: Parameters<typeof loop.start>[0] = {
2815
+ ref,
2816
+ trackRef,
2817
+ // AIDEV-NOTE: PMR-V31Z 2.1 — the label mapping IS the start phase:
2818
+ // the landing reconciliation that could re-enter validate on an
2819
+ // unmerged branch is deleted (personal delivers via PR).
2820
+ phase: next.phase,
2821
+ promptInput,
2822
+ yolo,
2823
+ }
2824
+ if (seed.resume !== undefined) {
2825
+ startInput.resume = seed.resume
2826
+ }
2827
+ // AIDEV-NOTE: PMR-ZV9Y 2.1 — v2 emission seed (guarded, derived above).
2828
+ // resumeState absent on a genuinely fresh run → the loop seeds null and
2829
+ // start()'s snapshot('running') emits running; on a restart it equals the
2830
+ // last journaled state-change so the same state is NOT re-emitted.
2831
+ if (seedV2State !== undefined) {
2832
+ startInput.resumeState = seedV2State
2833
+ }
2834
+ startInput.resumePlanApprovalOpen = seedPlanApprovalOpen
2835
+ // AIDEV-NOTE: PMR-YG2N 4.1 — fire-and-forget sweep immediately before
2836
+ // loop.start: a restarting flow is never done, so the labels-done gate
2837
+ // keeps its own worktree safe without a skip-list.
2838
+ runBackgroundSweep({ cwd: ctx.cwd })
2839
+ await loop.start(startInput)
2840
+ // AIDEV-NOTE: PMR-XTQQ subtask 3.3 — a real rerun re-arms the pending
2841
+ // consumer for this ref.
2842
+ resumeLatch.delete(ref)
2843
+ // AIDEV-NOTE: PMR-DMHH subtask 2.1 — a real rerun re-arms the
2844
+ // gate-answer wake for this ref (the fresh owner-session stamp above
2845
+ // re-identifies this process as the restarted run's owner) and retires
2846
+ // the standalone awaiting-approval marker: the flow owns the ref now,
2847
+ // so the standalone plain-wake path is dead.
2848
+ gateWakeLatch.delete(ref)
2849
+ consumeAwaitingSpecApproval(ref)
2850
+ },
2851
+ })
2852
+
2853
+ pi.registerCommand('herdr-sync', {
2854
+ description:
2855
+ 'Link this repo as a Herdr plugin (idempotent). Usage: /herdr-sync',
2856
+ // AIDEV-NOTE: Explicit-only plugin registration — never during
2857
+ // session_start. Preflight validates herdr-plugin.toml against the
2858
+ // package version; herdr absent = graceful skip. Port of pi-workflows'
2859
+ // `pi-workflows herdr sync` discipline.
2860
+ handler: async (_args, ctx) => {
2861
+ const repoRoot = resolveRepoRoot()
2862
+ let result: Awaited<ReturnType<typeof syncHerdrPlugin>>
2863
+ try {
2864
+ result = await syncHerdrPlugin(repoRoot)
2865
+ } catch (error) {
2866
+ const msg = error instanceof Error ? error.message : String(error)
2867
+ ctx.ui.notify(`/herdr-sync failed: ${msg}`, 'warning')
2868
+ return
2869
+ }
2870
+ const level = result.status === 'unavailable' ? 'info' : 'info'
2871
+ ctx.ui.notify(
2872
+ `${result.message}${result.runningPiProcessesNeedReload ? ' Running Pi processes need a reload to pick up plugin panes.' : ''}`,
2873
+ level,
2874
+ )
2875
+ },
2876
+ })
2877
+
2878
+ pi.registerCommand('flow-view', {
2879
+ description:
2880
+ 'Open the flow run-state viewer in a Herdr pane. Usage: /flow-view <jira-id | aven-ref | aven:<ref> | jira:<key>> [right|below|left|above|tab]',
2881
+ // AIDEV-NOTE: Herdr-gated viewer opener. Requires an existing run-state
2882
+ // file (i.e. /flow must have started at least once for the ref). Dedupes
2883
+ // by pane label ("flow · <ref>") via herdr api snapshot — survives Pi
2884
+ // reloads without any state of our own.
2885
+ handler: async (args, ctx) => {
2886
+ const parts = args.trim().split(/\s+/).filter(Boolean)
2887
+ const rawRef = parts[0]
2888
+ const placementArg = parts[1]
2889
+ // AIDEV-NOTE: same kind-prefix escape hatch as the phase parsers
2890
+ // (PMR-PCVK) — strip aven:/jira: before the run-state filename check.
2891
+ let ref: string | undefined
2892
+ if (rawRef === undefined) {
2893
+ ref = undefined
2894
+ } else {
2895
+ const kinded = parseRefKind(rawRef)
2896
+ if (kinded.kind === 'jira') {
2897
+ ref = kinded.jiraId
2898
+ } else {
2899
+ ref = kinded.ref
2900
+ }
2901
+ }
2902
+ if (ref === undefined || !isValidRef(ref)) {
2903
+ ctx.ui.notify(
2904
+ 'Usage: /flow-view <jira-id | aven-ref | aven:<ref> | jira:<key>> [right|below|left|above|tab]',
2905
+ 'info',
2906
+ )
2907
+ return
2908
+ }
2909
+ // AIDEV-NOTE: Placement resolution chain (PMR-9Q2S 3.2): explicit arg
2910
+ // (validated below) > configured viewerPlacement > interactive prompt
2911
+ // (only when ctx.hasUI; no UI -> 'right' silently). loadConfig throws
2912
+ // on malformed config — same failure mode as the rest of pi-flow.
2913
+ // AIDEV-NOTE: PMR-JP37 (3.3) — a freshly picked placement is persisted
2914
+ // best-effort to the global config so the next /flow-view without an
2915
+ // arg skips the prompt. Persistence failure warns but never blocks the
2916
+ // open; arg/config paths below never rewrite config.
2917
+ let parsedArg: ReturnType<typeof parseViewerPlacement>
2918
+ if (placementArg === undefined) {
2919
+ parsedArg = undefined
2920
+ } else {
2921
+ parsedArg = parseViewerPlacement(placementArg)
2922
+ }
2923
+ if (placementArg !== undefined && parsedArg === undefined) {
2924
+ ctx.ui.notify(
2925
+ `Unknown placement "${placementArg}". Use right|below|left|above|tab.`,
2926
+ 'warning',
2927
+ )
2928
+ return
2929
+ }
2930
+ let configured: ReturnType<typeof parseViewerPlacement>
2931
+ try {
2932
+ const config = await loadConfig(ctx.cwd)
2933
+ configured = config.viewerPlacement
2934
+ } catch (error) {
2935
+ const msg = error instanceof Error ? error.message : String(error)
2936
+ ctx.ui.notify(`/flow-view: failed to load config: ${msg}`, 'warning')
2937
+ return
2938
+ }
2939
+ const decision = decidePlacement(parsedArg, configured)
2940
+ let placement: NonNullable<ReturnType<typeof parseViewerPlacement>>
2941
+ if (decision.kind === 'placement') {
2942
+ placement = decision.placement
2943
+ } else if (ctx.hasUI) {
2944
+ const choice = await ctx.ui.select('Viewer placement:', [
2945
+ 'right',
2946
+ 'below',
2947
+ 'left',
2948
+ 'above',
2949
+ 'tab',
2950
+ ])
2951
+ if (choice === undefined) {
2952
+ placement = 'right'
2953
+ } else {
2954
+ const picked = parseViewerPlacement(choice)
2955
+ if (picked === undefined) {
2956
+ placement = 'right'
2957
+ } else {
2958
+ placement = picked
2959
+ try {
2960
+ const savedPath = await saveViewerPlacement(getAgentDir(), picked)
2961
+ ctx.ui.notify(`Saved viewer placement to ${savedPath}.`, 'info')
2962
+ } catch (error) {
2963
+ const msg = error instanceof Error ? error.message : String(error)
2964
+ ctx.ui.notify(
2965
+ `/flow-view: could not save viewer placement: ${msg}`,
2966
+ 'warning',
2967
+ )
2968
+ }
2969
+ }
2970
+ }
2971
+ } else {
2972
+ placement = 'right'
2973
+ }
2974
+ const viewer = new FlowHerdrViewer(pi.exec)
2975
+ const capability = await viewer.probe()
2976
+ if (!capability.available) {
2977
+ ctx.ui.notify(`/flow-view: ${capability.reason}`, 'warning')
2978
+ return
2979
+ }
2980
+ // AIDEV-NOTE: Installed-plugin version gate (PMR-9Q2S 2.2). This is a
2981
+ // diagnostic refusal, not a repair — the fix is /herdr-sync, never an
2982
+ // inline relink. Preflight failure also refuses instead of crashing.
2983
+ let expected: string
2984
+ try {
2985
+ expected = (await preflightRepo(resolveRepoRoot())).version
2986
+ } catch (error) {
2987
+ const msg = error instanceof Error ? error.message : String(error)
2988
+ ctx.ui.notify(
2989
+ `/flow-view: repo preflight failed: ${msg} — run /herdr-sync`,
2990
+ 'warning',
2991
+ )
2992
+ return
2993
+ }
2994
+ const installed = await viewer.installedPlugin()
2995
+ const versionStatus = pluginVersionStatus(installed, expected)
2996
+ if (versionStatus.status === 'not-installed') {
2997
+ ctx.ui.notify(
2998
+ '/flow-view: herdr plugin not installed — run /herdr-sync to relink the plugin.',
2999
+ 'warning',
3000
+ )
3001
+ return
3002
+ }
3003
+ if (versionStatus.status === 'disabled') {
3004
+ ctx.ui.notify(
3005
+ '/flow-view: herdr plugin is disabled — run /herdr-sync to relink the plugin.',
3006
+ 'warning',
3007
+ )
3008
+ return
3009
+ }
3010
+ if (versionStatus.status === 'drift') {
3011
+ ctx.ui.notify(
3012
+ `/flow-view: herdr plugin version ${versionStatus.installed} != expected ${versionStatus.expected} — run /herdr-sync to relink the plugin.`,
3013
+ 'warning',
3014
+ )
3015
+ return
3016
+ }
3017
+ const runFile = runStatePath(getAgentDir(), ref)
3018
+ if (runFile === null) {
3019
+ ctx.ui.notify(`/flow-view: invalid ref "${ref}".`, 'warning')
3020
+ return
3021
+ }
3022
+ try {
3023
+ await fs.access(runFile)
3024
+ } catch {
3025
+ ctx.ui.notify(
3026
+ `/flow-view ${ref}: no run state yet — run /flow ${ref} first.`,
3027
+ 'warning',
3028
+ )
3029
+ return
3030
+ }
3031
+ try {
3032
+ const opened = await viewer.open(ref, placement)
3033
+ let message: string
3034
+ if (opened.reused) {
3035
+ message = `Focused existing flow viewer for ${ref}.`
3036
+ } else {
3037
+ message = `Opened flow viewer for ${ref} (${placement}).`
3038
+ }
3039
+ ctx.ui.notify(message, 'info')
3040
+ } catch (error) {
3041
+ const msg = error instanceof Error ? error.message : String(error)
3042
+ ctx.ui.notify(`/flow-view ${ref}: ${msg}`, 'warning')
3043
+ }
3044
+ },
3045
+ })
3046
+
3047
+ pi.registerCommand('flow-view-replay', {
3048
+ description:
3049
+ 'Open the flow journal replay viewer in a Herdr pane. Usage: /flow-view-replay <jira-id | aven-ref | aven:<ref> | jira:<key>> [right|below|left|above|tab]',
3050
+ // AIDEV-NOTE: PMR-ZGPY 5.4 wiring — byte-for-byte mirror of the
3051
+ // /flow-view handler above with one difference: viewer.open is called
3052
+ // with 'replay' mode (typecheck-enforced union in FlowHerdrViewer.open).
3053
+ // The handler body is intentionally duplicated rather than extracted
3054
+ // (wiring-only subtask); if a third mode ever lands, extract then.
3055
+ handler: async (args, ctx) => {
3056
+ const parts = args.trim().split(/\s+/).filter(Boolean)
3057
+ const rawRef = parts[0]
3058
+ const placementArg = parts[1]
3059
+ let ref: string | undefined
3060
+ if (rawRef === undefined) {
3061
+ ref = undefined
3062
+ } else {
3063
+ const kinded = parseRefKind(rawRef)
3064
+ if (kinded.kind === 'jira') {
3065
+ ref = kinded.jiraId
3066
+ } else {
3067
+ ref = kinded.ref
3068
+ }
3069
+ }
3070
+ if (ref === undefined || !isValidRef(ref)) {
3071
+ ctx.ui.notify(
3072
+ 'Usage: /flow-view-replay <jira-id | aven-ref | aven:<ref> | jira:<key>> [right|below|left|above|tab]',
3073
+ 'info',
3074
+ )
3075
+ return
3076
+ }
3077
+ let parsedArg: ReturnType<typeof parseViewerPlacement>
3078
+ if (placementArg === undefined) {
3079
+ parsedArg = undefined
3080
+ } else {
3081
+ parsedArg = parseViewerPlacement(placementArg)
3082
+ }
3083
+ if (placementArg !== undefined && parsedArg === undefined) {
3084
+ ctx.ui.notify(
3085
+ `Unknown placement "${placementArg}". Use right|below|left|above|tab.`,
3086
+ 'warning',
3087
+ )
3088
+ return
3089
+ }
3090
+ let configured: ReturnType<typeof parseViewerPlacement>
3091
+ try {
3092
+ const config = await loadConfig(ctx.cwd)
3093
+ configured = config.viewerPlacement
3094
+ } catch (error) {
3095
+ const msg = error instanceof Error ? error.message : String(error)
3096
+ ctx.ui.notify(
3097
+ `/flow-view-replay: failed to load config: ${msg}`,
3098
+ 'warning',
3099
+ )
3100
+ return
3101
+ }
3102
+ const decision = decidePlacement(parsedArg, configured)
3103
+ let placement: NonNullable<ReturnType<typeof parseViewerPlacement>>
3104
+ if (decision.kind === 'placement') {
3105
+ placement = decision.placement
3106
+ } else if (ctx.hasUI) {
3107
+ const choice = await ctx.ui.select('Viewer placement:', [
3108
+ 'right',
3109
+ 'below',
3110
+ 'left',
3111
+ 'above',
3112
+ 'tab',
3113
+ ])
3114
+ if (choice === undefined) {
3115
+ placement = 'right'
3116
+ } else {
3117
+ const picked = parseViewerPlacement(choice)
3118
+ if (picked === undefined) {
3119
+ placement = 'right'
3120
+ } else {
3121
+ placement = picked
3122
+ try {
3123
+ const savedPath = await saveViewerPlacement(getAgentDir(), picked)
3124
+ ctx.ui.notify(`Saved viewer placement to ${savedPath}.`, 'info')
3125
+ } catch (error) {
3126
+ const msg = error instanceof Error ? error.message : String(error)
3127
+ ctx.ui.notify(
3128
+ `/flow-view-replay: could not save viewer placement: ${msg}`,
3129
+ 'warning',
3130
+ )
3131
+ }
3132
+ }
3133
+ }
3134
+ } else {
3135
+ placement = 'right'
3136
+ }
3137
+ const viewer = new FlowHerdrViewer(pi.exec)
3138
+ const capability = await viewer.probe()
3139
+ if (!capability.available) {
3140
+ ctx.ui.notify(`/flow-view-replay: ${capability.reason}`, 'warning')
3141
+ return
3142
+ }
3143
+ let expected: string
3144
+ try {
3145
+ expected = (await preflightRepo(resolveRepoRoot())).version
3146
+ } catch (error) {
3147
+ const msg = error instanceof Error ? error.message : String(error)
3148
+ ctx.ui.notify(
3149
+ `/flow-view-replay: repo preflight failed: ${msg} — run /herdr-sync`,
3150
+ 'warning',
3151
+ )
3152
+ return
3153
+ }
3154
+ const installed = await viewer.installedPlugin()
3155
+ const versionStatus = pluginVersionStatus(installed, expected)
3156
+ if (versionStatus.status === 'not-installed') {
3157
+ ctx.ui.notify(
3158
+ '/flow-view-replay: herdr plugin not installed — run /herdr-sync to relink the plugin.',
3159
+ 'warning',
3160
+ )
3161
+ return
3162
+ }
3163
+ if (versionStatus.status === 'disabled') {
3164
+ ctx.ui.notify(
3165
+ '/flow-view-replay: herdr plugin is disabled — run /herdr-sync to relink the plugin.',
3166
+ 'warning',
3167
+ )
3168
+ return
3169
+ }
3170
+ if (versionStatus.status === 'drift') {
3171
+ ctx.ui.notify(
3172
+ `/flow-view-replay: herdr plugin version ${versionStatus.installed} != expected ${versionStatus.expected} — run /herdr-sync to relink the plugin.`,
3173
+ 'warning',
3174
+ )
3175
+ return
3176
+ }
3177
+ const runFile = runStatePath(getAgentDir(), ref)
3178
+ if (runFile === null) {
3179
+ ctx.ui.notify(`/flow-view-replay: invalid ref "${ref}".`, 'warning')
3180
+ return
3181
+ }
3182
+ try {
3183
+ await fs.access(runFile)
3184
+ } catch {
3185
+ ctx.ui.notify(
3186
+ `/flow-view-replay ${ref}: no run state yet — run /flow ${ref} first.`,
3187
+ 'warning',
3188
+ )
3189
+ return
3190
+ }
3191
+ try {
3192
+ const opened = await viewer.open(ref, placement, 'replay')
3193
+ let message: string
3194
+ if (opened.reused) {
3195
+ message = `Focused existing flow replay viewer for ${ref}.`
3196
+ } else {
3197
+ message = `Opened flow replay viewer for ${ref} (${placement}).`
3198
+ }
3199
+ ctx.ui.notify(message, 'info')
3200
+ } catch (error) {
3201
+ const msg = error instanceof Error ? error.message : String(error)
3202
+ ctx.ui.notify(`/flow-view-replay ${ref}: ${msg}`, 'warning')
3203
+ }
3204
+ },
3205
+ })
3206
+ }