@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/flow/widget.ts ADDED
@@ -0,0 +1,448 @@
1
+ // AIDEV-NOTE (PMR-ZGPY 3.2): flow-status widget lifecycle — modeled on the
2
+ // pi-interactive-subagents widget (latestCtx module holder, updateWidget →
3
+ // updateWidgetUnsafe guarded try/catch, factory component with a 2s
4
+ // presentation-only tick). ISC-A-2: every ctx.ui.setWidget call happens
5
+ // inside updateWidgetUnsafe, which only ever runs under updateWidget's
6
+ // try/catch — a stale ctx after session reload can never crash the host.
7
+ // ISC-A-3: no fs.watch anywhere — refresh is pull-based (refreshFlowWidget
8
+ // from index.ts's agent_settled / onFlowSpawn paths) plus the presentation
9
+ // tick that ONLY calls tui.requestRender() (no data IO in the tick).
10
+ // Fail-closed data collection (collectWidgetData): one broken source keeps
11
+ // its own empty/null slice; a throw inside the pipeline keeps the last
12
+ // cached content — we unregister ONLY on genuinely-empty content, never on
13
+ // an error. The re-register guard mirrors subagents :1115: when already
14
+ // registered we update the cache and ask for a redraw (widgetTui
15
+ // .requestRender()) instead of re-registering, which would reset the tick.
16
+ // Fix round 2: dispose() resets the registration flag, so a NEW session_start
17
+ // ctx re-registers a fresh component (setWidget runs again).
18
+ // PMR-C3B6 (D1 rewrite): visibility is a 3-state machine — 'hidden'
19
+ // (default), 'flashing' (phase transition reveals the widget for FLASH_MS
20
+ // via a one-shot timer), 'pinned' (explicit toggleFlowDashboardPin). Content
21
+ // alone NEVER registers; the footer status (Phase 2) is NEVER gated on
22
+ // visibility. session_start re-syncs: it resets visibility to hidden and
23
+ // suppresses the flash so the first refresh adopts the current phase
24
+ // silently. registerWidget/unregisterWidget are shared module helpers used
25
+ // by refresh, the toggle, and the flash expiry callback.
26
+
27
+ import type {
28
+ ExtensionAPI,
29
+ ExtensionContext,
30
+ Theme,
31
+ } from '@earendil-works/pi-coding-agent'
32
+ import type { FlowRunState } from '../run-state.ts'
33
+ import { frameFlowStatusLines } from './frame.ts'
34
+ import type { OpenGate } from './gates.ts'
35
+ import {
36
+ type AssignmentSummary,
37
+ renderFlowStatusLines,
38
+ renderFooterStatus,
39
+ shouldShowWidget,
40
+ } from './status.ts'
41
+
42
+ /** Per-assignment slice the widget consumes; parentPid lets the module filter
43
+ * to THIS process's children (spec: filter lives here, not in the caller). */
44
+ export interface WidgetAssignment extends AssignmentSummary {
45
+ parentPid: number
46
+ }
47
+
48
+ /** Injectable data + timing seams (tests inject recording fakes). */
49
+ export interface FlowWidgetDeps {
50
+ readState(): Promise<FlowRunState | null>
51
+ listAssignments(): WidgetAssignment[]
52
+ collectOpenGates(): Promise<OpenGate[]>
53
+ parentPid: number
54
+ timing?: {
55
+ setInterval: (fn: () => void, ms: number) => unknown
56
+ clearInterval: (handle: unknown) => void
57
+ setTimeout?: (fn: () => void, ms: number) => unknown
58
+ clearTimeout?: (handle: unknown) => void
59
+ }
60
+ }
61
+
62
+ const WIDGET_NAME = 'flow-status'
63
+ const TICK_MS = 2000
64
+
65
+ // Module holders — same shape as subagents index.ts :817.
66
+ let latestCtx: ExtensionContext | null = null
67
+ let deps: FlowWidgetDeps | null = null
68
+ let widgetTui: { requestRender: () => void } | null = null
69
+ let widgetRegistered = false
70
+ let cachedLines: string[] = []
71
+ // AIDEV-NOTE (PMR-MGWP): minimal phase slice cached alongside cachedLines so
72
+ // render() picks the frame accent without re-reading state (render stays IO-free).
73
+ let cachedPhase: string | null = null
74
+ // Captured at setWidget-factory time; render() falls back to the plain clamp
75
+ // when absent (test harnesses invoke the factory with tui only).
76
+ let widgetTheme: Theme | null = null
77
+ // AIDEV-NOTE (PMR-C3B6): visibility state machine — default hidden (D1
78
+ // rewrite): content alone never registers; the ONLY reveal paths are a
79
+ // phase-transition flash and an explicit pin (toggleFlowDashboardPin). The
80
+ // footer status (Phase 2) is NEVER gated on visibility.
81
+ type WidgetVisibility = 'hidden' | 'flashing' | 'pinned'
82
+ let visibility: WidgetVisibility = 'hidden'
83
+ let flashHandle: unknown = null
84
+ let suppressFlashOnce = false
85
+ const FLASH_MS = 4000
86
+
87
+ interface WidgetData {
88
+ state: FlowRunState | null
89
+ subtasks: WidgetAssignment[]
90
+ gates: OpenGate[]
91
+ }
92
+
93
+ /** Fail-closed fan-out: a rejected source becomes its empty slice. Returns
94
+ * null when ANY source rejected — callers keep the last cached content
95
+ * (an error must never be confused with genuinely-empty data). */
96
+ async function collectWidgetData(): Promise<WidgetData | null> {
97
+ const localDeps = deps
98
+ if (localDeps === null) {
99
+ return { state: null, subtasks: [], gates: [] }
100
+ }
101
+ const [stateRes, assignmentsRes, gatesRes] = await Promise.allSettled([
102
+ localDeps.readState(),
103
+ Promise.resolve(localDeps.listAssignments()),
104
+ localDeps.collectOpenGates(),
105
+ ])
106
+ if (
107
+ stateRes.status === 'rejected' ||
108
+ assignmentsRes.status === 'rejected' ||
109
+ gatesRes.status === 'rejected'
110
+ ) {
111
+ return null
112
+ }
113
+ const subtasks = assignmentsRes.value.filter(
114
+ (a) => a.parentPid === localDeps.parentPid,
115
+ )
116
+ return { state: stateRes.value, subtasks, gates: gatesRes.value }
117
+ }
118
+
119
+ async function updateWidget(): Promise<void> {
120
+ if (!latestCtx?.hasUI) return
121
+ // AIDEV-NOTE: latestCtx goes stale after session replacement/reload — pi
122
+ // throws on stale ctx; a dead widget render must never crash the host
123
+ // (subagents :1115 pattern). Covers every setWidget call (ISC-A-2).
124
+ try {
125
+ await updateWidgetUnsafe()
126
+ } catch {}
127
+ }
128
+
129
+ /** PMR-C3B6: one-shot timer pair — injected timing when it provides
130
+ * setTimeout/clearTimeout, globals otherwise (same discipline as the tick). */
131
+ function resolveOneShotTiming(): {
132
+ setTimeout: (fn: () => void, ms: number) => unknown
133
+ clearTimeout: (handle: unknown) => void
134
+ } {
135
+ const t = deps?.timing
136
+ if (t?.setTimeout !== undefined && t?.clearTimeout !== undefined) {
137
+ return { setTimeout: t.setTimeout, clearTimeout: t.clearTimeout }
138
+ }
139
+ return {
140
+ setTimeout: (fn: () => void, ms: number) => setTimeout(fn, ms),
141
+ clearTimeout: (handle: unknown) => {
142
+ clearTimeout(handle as ReturnType<typeof setTimeout>)
143
+ },
144
+ }
145
+ }
146
+
147
+ /** PMR-C3B6: arm (or re-arm) the flash one-shot — on expiry the widget goes
148
+ * back to hidden and unregisters. The callback runs OUTSIDE updateWidget's
149
+ * try/catch, so its unregister is identity-guarded (PMR-AD0H pattern). */
150
+ function armFlash(ctx: ExtensionContext): void {
151
+ clearFlash()
152
+ const timing = resolveOneShotTiming()
153
+ flashHandle = timing.setTimeout(() => {
154
+ flashHandle = null
155
+ visibility = 'hidden'
156
+ if (widgetTui === null && !widgetRegistered) return
157
+ unregisterWidget(ctx)
158
+ }, FLASH_MS)
159
+ }
160
+
161
+ /** PMR-C3B6: cancel a pending flash timer, if any. */
162
+ function clearFlash(): void {
163
+ if (flashHandle === null) return
164
+ const timing = resolveOneShotTiming()
165
+ timing.clearTimeout(flashHandle)
166
+ flashHandle = null
167
+ }
168
+
169
+ /** PMR-C3B6: shared unregister — flag reset + guarded setWidget(undefined).
170
+ * Used by refresh (empty/hidden paths), the toggle, and the flash expiry. */
171
+ function unregisterWidget(ctx: ExtensionContext): void {
172
+ if (!widgetRegistered) return
173
+ widgetRegistered = false
174
+ widgetTui = null
175
+ try {
176
+ ctx.ui.setWidget(WIDGET_NAME, undefined)
177
+ } catch {}
178
+ }
179
+
180
+ /** PMR-C3B6: shared register — idempotent (already registered → cheap
181
+ * redraw). The factory reads timing from deps?.timing at registration time;
182
+ * callers run under updateWidget's try/catch (the toggle wraps its own). */
183
+ function registerWidget(ctx: ExtensionContext): void {
184
+ if (widgetRegistered) {
185
+ // Cheap path (subagents :1115): don't re-register — that would reset the
186
+ // 2s tick. Refresh the cache and ask for a redraw.
187
+ try {
188
+ widgetTui?.requestRender()
189
+ } catch {}
190
+ return
191
+ }
192
+ widgetRegistered = true
193
+ const timing = deps?.timing
194
+ try {
195
+ ctx.ui.setWidget(
196
+ WIDGET_NAME,
197
+ (tui: { requestRender: () => void }, theme?: Theme) => {
198
+ widgetTui = tui
199
+ // AIDEV-NOTE (PMR-MGWP): theme is captured once per registration;
200
+ // render must never reach back into ctx (it can go stale mid-session).
201
+ if (theme !== undefined) {
202
+ widgetTheme = theme
203
+ }
204
+ // Presentation tick ONLY — no data IO here (ISC-A-3 complement). The
205
+ // stop action is captured per-branch so dispose() needs no casts.
206
+ let stopTick: () => void
207
+ if (timing === undefined) {
208
+ const t = setInterval(() => {
209
+ try {
210
+ tui.requestRender()
211
+ } catch {}
212
+ }, TICK_MS)
213
+ stopTick = () => {
214
+ clearInterval(t)
215
+ }
216
+ } else {
217
+ const t = timing.setInterval(() => {
218
+ try {
219
+ tui.requestRender()
220
+ } catch {}
221
+ }, TICK_MS)
222
+ stopTick = () => {
223
+ timing.clearInterval(t)
224
+ }
225
+ }
226
+ return {
227
+ invalidate() {},
228
+ dispose() {
229
+ stopTick()
230
+ // PMR-ZGPY fix round 2 (mirrors subagents index.ts dispose): the
231
+ // registration flag MUST reset, or after a session reload tears
232
+ // the component down every refresh takes the cheap requestRender
233
+ // no-op path and the widget never returns. Guarded by the same
234
+ // identity check the precedent uses, BEFORE nulling.
235
+ if (widgetTui === tui) {
236
+ widgetTui = null
237
+ widgetRegistered = false
238
+ }
239
+ },
240
+ render(width: number): string[] {
241
+ // AIDEV-NOTE (PMR-MGWP): ANSI-aware framing replaces the old
242
+ // String.slice clamp; without a theme (harness) we keep the plain clamp.
243
+ // Styling (PMR-X7BH) lives inside frameFlowStatusLines; cachedLines
244
+ // must stay plain ASCII — the no-theme clamp below would split
245
+ // surrogate pairs / cut SGR sequences mid-escape otherwise.
246
+ const localTheme = widgetTheme
247
+ if (localTheme === null) {
248
+ return cachedLines.map((line) =>
249
+ line.slice(0, Math.max(0, width)),
250
+ )
251
+ }
252
+ return frameFlowStatusLines(
253
+ cachedLines,
254
+ width,
255
+ localTheme,
256
+ cachedPhase,
257
+ )
258
+ },
259
+ }
260
+ },
261
+ )
262
+ } catch (error) {
263
+ // PMR-C3B6: never leave the flag set when pi rejected the registration —
264
+ // the host may rethrow on a stale ctx outside updateWidget's guard.
265
+ widgetRegistered = false
266
+ throw error
267
+ }
268
+ }
269
+
270
+ async function updateWidgetUnsafe(): Promise<void> {
271
+ const localDeps = deps
272
+ if (localDeps === null) return
273
+ const ctx = latestCtx
274
+ if (ctx === null) return
275
+ const collected = await collectWidgetData()
276
+ if (collected === null) {
277
+ // AIDEV-NOTE (PMR-ZGPY 3.2): a source ERROR (not genuinely-empty data) —
278
+ // keep the last cached content and just redraw; never unregister on a
279
+ // data error, that would blink the widget away on a transient failure.
280
+ try {
281
+ widgetTui?.requestRender()
282
+ } catch {}
283
+ return
284
+ }
285
+ const input = {
286
+ state: collected.state,
287
+ subtasks: collected.subtasks.map((a) => ({
288
+ name: a.name,
289
+ status: a.status,
290
+ })),
291
+ gates: collected.gates,
292
+ }
293
+ if (!shouldShowWidget(input)) {
294
+ // Unregister only on genuinely-empty content, never on a data error.
295
+ // PMR-C3B6: the pin does not outlive the flow — clear flash + pin state.
296
+ clearFlash()
297
+ visibility = 'hidden'
298
+ cachedLines = []
299
+ cachedPhase = null
300
+ try {
301
+ ctx.ui.setStatus('flow', undefined)
302
+ } catch {}
303
+ unregisterWidget(ctx)
304
+ return
305
+ }
306
+ // AIDEV-NOTE (PMR-C3B6): detect the phase transition BEFORE updating
307
+ // cachedPhase. suppressFlashOnce marks a session_start re-sync — the first
308
+ // refresh after a session start adopts the current phase without flashing.
309
+ const newPhase = collected.state?.currentPhase ?? null
310
+ const transitioned =
311
+ newPhase !== null && newPhase !== cachedPhase && !suppressFlashOnce
312
+ suppressFlashOnce = false
313
+ cachedLines = renderFlowStatusLines(input)
314
+ cachedPhase = newPhase
315
+ // AIDEV-NOTE (PMR-C3B6): footer status is set on every content refresh —
316
+ // unconditional (Phase 2 invariant), never gated on visibility. Covers the
317
+ // three refresh entries: index.ts onFlowSpawn, index.ts agent_settled,
318
+ // session_start (via initFlowWidget → refreshFlowWidget).
319
+ try {
320
+ ctx.ui.setStatus('flow', renderFooterStatus(collected.state))
321
+ } catch {}
322
+ // AIDEV-NOTE (PMR-C3B6): visibility branch — only registration is gated.
323
+ if (visibility === 'pinned') {
324
+ // Pinned: ensure registered, NO flash — transitions are a no-op.
325
+ registerWidget(ctx)
326
+ return
327
+ }
328
+ if (transitioned) {
329
+ // Phase transition: reveal for FLASH_MS, (re-)arm the one-shot timer.
330
+ visibility = 'flashing'
331
+ registerWidget(ctx)
332
+ armFlash(ctx)
333
+ return
334
+ }
335
+ if (visibility === 'flashing') {
336
+ // Still flashing, no new transition: timer keeps running.
337
+ registerWidget(ctx)
338
+ return
339
+ }
340
+ // Hidden: defensive unregister (PMR-AD0H) — pi may hold an orphan
341
+ // registration from a pre-reset lifecycle.
342
+ unregisterWidget(ctx)
343
+ }
344
+
345
+ /** Pull-based refresh — index.ts calls this from the onFlowSpawn hook and
346
+ * (via refreshAfterSettle) from agent_settled. Never throws (ISC-A-2). */
347
+ export async function refreshFlowWidget(): Promise<void> {
348
+ await updateWidget()
349
+ }
350
+
351
+ /** PMR-2KH5: settle-ordered refresh for the agent_settled handler. Phase
352
+ * truth (phase-complete / phase-start) is journaled only inside the loop's
353
+ * onSettled — after an aven readLabels shell-out — while the widget projects
354
+ * currentPhase solely from journal events. Firing the refresh concurrently
355
+ * with onSettled read the pre-transition journal, re-set the stale footer
356
+ * phase, and left nothing to correct it until the next settle (footer a turn
357
+ * behind; done/halt never refreshed). Chaining the refresh on the settle
358
+ * promise fixes the ordering; finally() guarantees the refresh still runs
359
+ * when onSettled rejects. The rejection itself propagates to the caller
360
+ * (fail-noisy, unchanged from the old bare `void loop.onSettled()`). */
361
+ export function refreshAfterSettle(
362
+ onSettled: () => Promise<void>,
363
+ ): Promise<void> {
364
+ return onSettled().finally(() => refreshFlowWidget())
365
+ }
366
+
367
+ export type DashboardToggleOutcome = 'pinned' | 'hidden' | 'no-content'
368
+
369
+ /** Toggle-pin the dashboard widget (PMR-C3B6). Uses the passed ctx (command /
370
+ * shortcut handlers receive fresh ones), else the module latestCtx holder.
371
+ * pinned → hidden: clear pin, unregister. hidden|flashing → pinned:
372
+ * re-collect data; without renderable content return 'no-content' changing
373
+ * nothing; otherwise pin, refresh the caches, and register. */
374
+ export async function toggleFlowDashboardPin(
375
+ ctx?: ExtensionContext,
376
+ ): Promise<DashboardToggleOutcome> {
377
+ const target = ctx ?? latestCtx
378
+ if (visibility === 'pinned') {
379
+ visibility = 'hidden'
380
+ if (target !== null) {
381
+ try {
382
+ unregisterWidget(target)
383
+ } catch {}
384
+ }
385
+ return 'hidden'
386
+ }
387
+ if (target === null || !target.hasUI) return 'no-content'
388
+ const collected = await collectWidgetData()
389
+ if (collected === null) return 'no-content'
390
+ const input = {
391
+ state: collected.state,
392
+ subtasks: collected.subtasks.map((a) => ({
393
+ name: a.name,
394
+ status: a.status,
395
+ })),
396
+ gates: collected.gates,
397
+ }
398
+ if (!shouldShowWidget(input)) return 'no-content'
399
+ clearFlash()
400
+ visibility = 'pinned'
401
+ cachedLines = renderFlowStatusLines(input)
402
+ cachedPhase = collected.state?.currentPhase ?? null
403
+ try {
404
+ target.ui.setStatus('flow', renderFooterStatus(collected.state))
405
+ } catch {}
406
+ try {
407
+ registerWidget(target)
408
+ } catch {
409
+ // AIDEV-NOTE: a throw here (e.g. a stale ctx whose setWidget fails) must
410
+ // not leave the machine claiming 'pinned' for an unregistered widget —
411
+ // reset to 'hidden' so the next toggle re-pins instead of unpinning; the
412
+ // footer status set above still reflects the attempted pin and the next
413
+ // session_start re-syncs regardless.
414
+ visibility = 'hidden'
415
+ }
416
+ return 'pinned'
417
+ }
418
+
419
+ /** Register the widget lifecycle: session_start listener capturing latestCtx
420
+ * plus an initial refresh. Wiring-only call from index.ts. AIDEV-NOTE
421
+ * (PMR-ZGPY 3.2): init is the ONLY path that resets lifecycle state
422
+ * (registered flag, cached lines, tick handle) — mid-run refreshes must never
423
+ * re-register, or the 2s presentation tick would reset every time.
424
+ * PMR-C3B6: init also resets the visibility machine; session_start re-syncs
425
+ * (hidden + flash suppressed) instead of counting as a transition. */
426
+ export function initFlowWidget(
427
+ pi: ExtensionAPI,
428
+ widgetDeps: FlowWidgetDeps,
429
+ ): void {
430
+ deps = widgetDeps
431
+ widgetRegistered = false
432
+ widgetTui = null
433
+ cachedLines = []
434
+ cachedPhase = null
435
+ widgetTheme = null
436
+ visibility = 'hidden'
437
+ clearFlash()
438
+ suppressFlashOnce = false
439
+ pi.on('session_start', (_event, ctx) => {
440
+ latestCtx = ctx
441
+ // PMR-C3B6: a session start is a re-sync, not a transition — adopt the
442
+ // current phase silently on the next refresh.
443
+ visibility = 'hidden'
444
+ clearFlash()
445
+ suppressFlashOnce = true
446
+ void refreshFlowWidget()
447
+ })
448
+ }
@@ -0,0 +1,136 @@
1
+ import { existsSync } from 'node:fs'
2
+
3
+ // AIDEV-NOTE: PMR-1CCT — flow worktree context. The review tool resolves its
4
+ // diff in ctx.cwd (the session checkout), but flow work lands in an isolated
5
+ // Herdr worktree — so a review from the main checkout diffs main..main (empty
6
+ // range, silent pass). This module is the bridge: the flow loop owns the
7
+ // active ref, the worktree tool binds the created path/branch to it, and the
8
+ // review tool prefers this cwd for branch/uncommitted targets.
9
+ // Process-global, last-writer-wins across concurrent sessions — same known
10
+ // limit as avenSessionCwd (tracked separately, PMR-7ZEE).
11
+
12
+ export interface FlowWorktree {
13
+ ref: string
14
+ path: string
15
+ branch: string
16
+ }
17
+
18
+ let activeRef: string | null = null
19
+ let worktree: FlowWorktree | null = null
20
+ let lastWorktree: FlowWorktree | null = null
21
+
22
+ // AIDEV-NOTE: PMR-PJM0 — module state dies on pi reload/restart. index.ts
23
+ // persists every change as a session entry (appendEntry) and replays the last
24
+ // one on session_start via restoreFlowBinding. PMR-DRKH: when the replay
25
+ // finds no entry (cross-session resume, fork, new session), session_start
26
+ // re-derives the binding from durable pending-run records and the gate tools
27
+ // self-heal on demand via flow/binding-heal.ts.
28
+ export interface FlowBindingSnapshot {
29
+ ref: string | null
30
+ worktree: FlowWorktree | null
31
+ }
32
+ let changeListener: ((snapshot: FlowBindingSnapshot) => void) | null = null
33
+
34
+ export function setBindingChangeListener(
35
+ fn: ((snapshot: FlowBindingSnapshot) => void) | null,
36
+ ): void {
37
+ changeListener = fn
38
+ }
39
+
40
+ function notifyChange(): void {
41
+ changeListener?.({ ref: activeRef, worktree })
42
+ }
43
+
44
+ // AIDEV-NOTE: PMR-P2MK — session entry data is untrusted (old/hand-edited
45
+ // sessions). Validate before restoring; a bad shape yields null, never a throw.
46
+ export function parseFlowBindingSnapshot(
47
+ value: unknown,
48
+ ): FlowBindingSnapshot | null {
49
+ if (typeof value !== 'object' || value === null) return null
50
+ const v = value as Record<string, unknown>
51
+ if (v.ref !== null && typeof v.ref !== 'string') return null
52
+ const wt = v.worktree
53
+ if (wt === null || wt === undefined) {
54
+ return { ref: v.ref, worktree: null }
55
+ }
56
+ if (typeof wt !== 'object') return null
57
+ const w = wt as Record<string, unknown>
58
+ if (
59
+ typeof w.ref !== 'string' ||
60
+ typeof w.path !== 'string' ||
61
+ typeof w.branch !== 'string'
62
+ ) {
63
+ return null
64
+ }
65
+ return {
66
+ ref: v.ref,
67
+ worktree: { ref: w.ref, path: w.path, branch: w.branch },
68
+ }
69
+ }
70
+
71
+ /** Restore a persisted snapshot. Does not fire the change listener. */
72
+ export function restoreFlowBinding(snapshot: FlowBindingSnapshot): void {
73
+ activeRef = snapshot.ref
74
+ worktree = null
75
+ if (snapshot.ref !== null && snapshot.worktree?.ref === snapshot.ref) {
76
+ worktree = snapshot.worktree
77
+ }
78
+ }
79
+
80
+ /** Set (or clear, null) the active flow ref. Clearing the ref clears the binding. */
81
+ export function setActiveFlowRef(ref: string | null): void {
82
+ // AIDEV-NOTE: the loop clears the ref on every halt/pause; remember the
83
+ // cleared binding so a rerun can restore it via reactivateFlowRef (PMR-182S).
84
+ if (ref === null && worktree !== null) {
85
+ lastWorktree = worktree
86
+ }
87
+ activeRef = ref
88
+ if (ref === null) {
89
+ worktree = null
90
+ }
91
+ notifyChange()
92
+ }
93
+
94
+ /**
95
+ * Loop entry point for /flow: activate the ref and, when the SAME ref's
96
+ * worktree was dropped by a halt/pause and its path still exists, restore it.
97
+ * Kept separate from setActiveFlowRef so plain activation stays a clean slate.
98
+ */
99
+ export function reactivateFlowRef(ref: string): void {
100
+ const remembered = lastWorktree
101
+ setActiveFlowRef(ref)
102
+ if (remembered?.ref === ref && existsSync(remembered.path)) {
103
+ worktree = remembered
104
+ notifyChange()
105
+ }
106
+ }
107
+
108
+ export function getActiveFlowRef(): string | null {
109
+ return activeRef
110
+ }
111
+
112
+ // AIDEV-NOTE: PMR-2424 — a skipped bind used to be silent, so the review tool
113
+ // diffed the main checkout and returned a bogus pass. Callers surface this.
114
+ export const NO_ACTIVE_FLOW_WARNING =
115
+ 'WARNING: no active flow — the worktree was NOT bound to a flow, so review/land gates will not apply to it. Tell the human to run `/flow aven:<ref>` (or `/flow <ref>`) before continuing with implement/validate.'
116
+
117
+ /**
118
+ * Bind a created worktree to the active flow ref. Returns false (and binds
119
+ * nothing) when no flow runs, so callers can warn instead of failing silently.
120
+ */
121
+ export function setFlowWorktree(path: string, branch: string): boolean {
122
+ if (activeRef === null) return false
123
+ worktree = { ref: activeRef, path, branch }
124
+ notifyChange()
125
+ return true
126
+ }
127
+
128
+ export function getFlowWorktree(): FlowWorktree | null {
129
+ return worktree
130
+ }
131
+
132
+ /** Drop the worktree binding (e.g. the path no longer exists). Keeps the ref. */
133
+ export function clearFlowWorktree(): void {
134
+ worktree = null
135
+ notifyChange()
136
+ }
@@ -0,0 +1,27 @@
1
+ import type { DiagramHeader, DiagramRecord } from './translate.ts'
2
+ import type { HpRenderer } from './vendor/harness-profiler/load.ts'
3
+
4
+ // AIDEV-NOTE: the fork's view.html carries a second data slot next to hp.js's
5
+ // /*DATA*/null (see PIN.md). hp.js's renderHtml already fills /*DATA*/null
6
+ // before returning, so this module owns ONLY the FLOW_HEADER slot. String.replace
7
+ // with a bare string replacement arg interprets `$&`-style patterns in the
8
+ // replacement — a replacer callback makes the JSON insert literal, matching
9
+ // hp.js's own `template.replace(DATA_SLOT, () => json)` technique.
10
+ const FLOW_HEADER_SLOT = '/*FLOW_HEADER*/null'
11
+
12
+ /**
13
+ * Pure assembler: renders the diagram via the given renderer and splices the
14
+ * ticket header JSON into the FLOW_HEADER slot. No fs, no Pi runtime imports.
15
+ */
16
+ export function renderDiagramHtml(
17
+ renderer: HpRenderer,
18
+ header: DiagramHeader,
19
+ records: readonly DiagramRecord[],
20
+ runId: string,
21
+ ): string {
22
+ const template = renderer.renderHtml({ id: runId, records })
23
+ // `<` is escaped so user data (e.g. a crafted PR url) cannot close the
24
+ // surrounding <script> tag — same technique as hp.js's DATA slot.
25
+ const json = JSON.stringify(header).replace(/</g, () => '\\u003c')
26
+ return template.replace(FLOW_HEADER_SLOT, () => json)
27
+ }