@gtheys/pi-flow 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/README.md +833 -2
  2. package/adhoc/tracker.ts +360 -0
  3. package/aven/client.ts +996 -0
  4. package/aven/status.ts +395 -0
  5. package/brainstorm/args.ts +24 -0
  6. package/brainstorm/artifact.ts +67 -0
  7. package/brainstorm/paths.ts +43 -0
  8. package/brainstorm/prompt.ts +172 -0
  9. package/brainstorm/refs.ts +41 -0
  10. package/config.schema.json +161 -0
  11. package/config.ts +577 -0
  12. package/feedback/args.ts +21 -0
  13. package/feedback/prompt.ts +177 -0
  14. package/feedback/triage.ts +88 -0
  15. package/flow/agent-role.ts +46 -0
  16. package/flow/answer-wake.ts +212 -0
  17. package/flow/answer.ts +183 -0
  18. package/flow/args.ts +48 -0
  19. package/flow/ask-emitter.ts +331 -0
  20. package/flow/attribution.ts +145 -0
  21. package/flow/aven-resolve-exec.ts +95 -0
  22. package/flow/aven-resolve.ts +80 -0
  23. package/flow/awaiting-approval.ts +32 -0
  24. package/flow/binding-heal.ts +68 -0
  25. package/flow/cost-autopush.ts +162 -0
  26. package/flow/cost-command.ts +122 -0
  27. package/flow/cost-rows-journal.ts +296 -0
  28. package/flow/cost-rows-push.ts +112 -0
  29. package/flow/cost-rows-rows.ts +209 -0
  30. package/flow/cost-rows.ts +228 -0
  31. package/flow/cost.ts +173 -0
  32. package/flow/durable-refs.ts +287 -0
  33. package/flow/effect-gate.ts +137 -0
  34. package/flow/ensure-labels.ts +44 -0
  35. package/flow/frame.ts +172 -0
  36. package/flow/gates.ts +211 -0
  37. package/flow/jira-ref.ts +212 -0
  38. package/flow/label-gate.ts +149 -0
  39. package/flow/land-gate.ts +98 -0
  40. package/flow/lifecycle-policy.ts +162 -0
  41. package/flow/live-wait.ts +52 -0
  42. package/flow/liveness.ts +408 -0
  43. package/flow/loop-deps.ts +210 -0
  44. package/flow/loop-settle.ts +531 -0
  45. package/flow/loop.ts +437 -0
  46. package/flow/orchestrate.ts +45 -0
  47. package/flow/phase-command.ts +287 -0
  48. package/flow/phase-emoji.ts +13 -0
  49. package/flow/phase-prompts.ts +251 -0
  50. package/flow/picker.ts +307 -0
  51. package/flow/push.ts +475 -0
  52. package/flow/reconcile-command.ts +253 -0
  53. package/flow/reconcile-deps.ts +329 -0
  54. package/flow/reconcile.ts +738 -0
  55. package/flow/ref-kind.ts +80 -0
  56. package/flow/resume-picker.ts +222 -0
  57. package/flow/resume.ts +116 -0
  58. package/flow/run-health.ts +252 -0
  59. package/flow/run-liveness.ts +33 -0
  60. package/flow/state-metrics.ts +559 -0
  61. package/flow/status.ts +105 -0
  62. package/flow/step-output.ts +416 -0
  63. package/flow/steps.ts +73 -0
  64. package/flow/terminal-purge.ts +281 -0
  65. package/flow/turn-generation.ts +19 -0
  66. package/flow/v2-emission.ts +381 -0
  67. package/flow/v2-resume.ts +100 -0
  68. package/flow/vocabulary.ts +261 -0
  69. package/flow/widget.ts +448 -0
  70. package/flow/worktree-context.ts +136 -0
  71. package/flow-diagram/assemble.ts +27 -0
  72. package/flow-diagram/command.ts +252 -0
  73. package/flow-diagram/translate.ts +862 -0
  74. package/flow-diagram/vendor/harness-profiler/LICENSE +21 -0
  75. package/flow-diagram/vendor/harness-profiler/PIN.md +64 -0
  76. package/flow-diagram/vendor/harness-profiler/hp.js +960 -0
  77. package/flow-diagram/vendor/harness-profiler/load.ts +66 -0
  78. package/flow-diagram/vendor/harness-profiler/view.html +436 -0
  79. package/gates.ts +20 -0
  80. package/herdr/sync.ts +355 -0
  81. package/herdr/viewer.ts +432 -0
  82. package/implement/args.ts +21 -0
  83. package/implement/prompt.ts +98 -0
  84. package/implement/retry.ts +57 -0
  85. package/implement/routing.ts +31 -0
  86. package/index.ts +3206 -0
  87. package/mode-profile.ts +56 -0
  88. package/package.json +205 -4
  89. package/phase-state.ts +18 -0
  90. package/plan/args.ts +20 -0
  91. package/plan/prompt.ts +251 -0
  92. package/plan/size-check.ts +46 -0
  93. package/plan-tools/helpers.ts +177 -0
  94. package/plan-tools/jira-branch-tool.ts +54 -0
  95. package/plan-tools/jira-branch.ts +109 -0
  96. package/plan-tools/jira-issue.ts +85 -0
  97. package/plan-tools/resolve-feature-path.ts +30 -0
  98. package/plan-tools/resolve-notes-path.ts +37 -0
  99. package/plan-tools/resolve-spec-path.ts +31 -0
  100. package/pr-quality/index.ts +908 -0
  101. package/review/LICENSE +19 -0
  102. package/review/deviation.ts +252 -0
  103. package/review/review.ts +3053 -0
  104. package/review/sem-guidance.d.mts +8 -0
  105. package/review/sem-guidance.mjs +89 -0
  106. package/review/verdict.ts +13 -0
  107. package/run-state.ts +2046 -0
  108. package/run-title.ts +91 -0
  109. package/server/consumer.ts +146 -0
  110. package/server/daemon.ts +1094 -0
  111. package/server/lifecycle.ts +679 -0
  112. package/server/pending.ts +267 -0
  113. package/server/staleness.ts +320 -0
  114. package/server/writer.ts +86 -0
  115. package/shared/diff-base.ts +138 -0
  116. package/shared/flow-base.ts +210 -0
  117. package/shared/sonarqube-utils.ts +415 -0
  118. package/shared/stable-range.ts +102 -0
  119. package/slugify.ts +13 -0
  120. package/sonarqube/sonarqube.ts +821 -0
  121. package/spec-review/approve.ts +91 -0
  122. package/spec-review/args.ts +21 -0
  123. package/spec-review/aven-spec.ts +142 -0
  124. package/spec-review/commands.ts +336 -0
  125. package/spec-review/escape-regexp.ts +7 -0
  126. package/spec-review/open-in-pane.ts +166 -0
  127. package/spec-review/picker.ts +74 -0
  128. package/spec-review/prompt.ts +72 -0
  129. package/spec-review/publish-args.ts +33 -0
  130. package/spec-review/publish.ts +210 -0
  131. package/telemetry/attributes.ts +118 -0
  132. package/telemetry/content.ts +140 -0
  133. package/telemetry/dispatch.ts +521 -0
  134. package/telemetry/exporter.ts +124 -0
  135. package/telemetry/index.ts +776 -0
  136. package/telemetry/loki.ts +224 -0
  137. package/tools/code-review-parse.ts +518 -0
  138. package/tools/code-review.ts +312 -0
  139. package/tools/deviation.ts +737 -0
  140. package/tools/flow-submit.ts +302 -0
  141. package/tools/land.ts +608 -0
  142. package/tools/phase-complete.ts +476 -0
  143. package/tools/result.ts +18 -0
  144. package/tools/review-deps.ts +44 -0
  145. package/tools/run-attempt.ts +312 -0
  146. package/tools/spec-approve.ts +265 -0
  147. package/validate/args.ts +22 -0
  148. package/validate/deviation-gate.ts +229 -0
  149. package/validate/gate-target.ts +371 -0
  150. package/validate/gate.ts +79 -0
  151. package/validate/paths.ts +20 -0
  152. package/validate/personal.ts +104 -0
  153. package/validate/prompt.ts +525 -0
  154. package/validate/review-gate.ts +134 -0
  155. package/validate/subtask-range.ts +113 -0
  156. package/work-mode.ts +19 -0
  157. package/worktree/bootstrap.ts +243 -0
  158. package/worktree/branch.ts +168 -0
  159. package/worktree/herdr.ts +447 -0
  160. package/worktree/index.ts +1447 -0
  161. package/worktree/orphan.ts +384 -0
  162. package/worktree/remove-guards.ts +99 -0
  163. package/worktree/residue.ts +216 -0
  164. package/worktree/sweep.ts +526 -0
@@ -0,0 +1,80 @@
1
+ // AIDEV-NOTE: Shared ref-kind classification (PMR-PCVK). `aven:<ref>` /
2
+ // `jira:<key>` prefix forces the kind and is stripped before validation;
3
+ // bare refs keep the historical letter-suffix heuristic, where a bare
4
+ // `<ALPHA>-<digits>` ref is Jira and anything else is aven. Pure — no pi
5
+ // imports — so every phase arg parser and /flow-view can share it.
6
+ // AIDEV-NOTE: PMR-F8HB — the bare heuristic misclassifies all-digit aven
7
+ // refs (PMR-2424) as Jira because they are shape-identical to Jira keys.
8
+ // aven project prefixes registered from `aven project list` (see
9
+ // aven/client.ts discoverAvenPrefixes + index.ts init) override the
10
+ // heuristic: a bare ref whose alpha prefix is a known aven project prefix
11
+ // is aven, never Jira. Unregistered prefixes keep the old heuristic.
12
+
13
+ export type RefKind =
14
+ | { kind: 'jira'; jiraId: string }
15
+ | { kind: 'aven'; ref: string }
16
+
17
+ const JIRA_RE = /^([a-zA-Z][a-zA-Z0-9]+)-(\d+)$/
18
+
19
+ const avenProjectPrefixes = new Set<string>()
20
+
21
+ /** Register aven project prefixes (e.g. 'PMR') for the bare-ref disambiguation above. */
22
+ export function registerAvenPrefixes(prefixes: readonly string[]): void {
23
+ for (const raw of prefixes) {
24
+ const prefix = raw.trim().toUpperCase()
25
+ if (prefix !== '') avenProjectPrefixes.add(prefix)
26
+ }
27
+ }
28
+
29
+ /** Test seam: clear the registry between cases. */
30
+ export function clearAvenPrefixes(): void {
31
+ avenProjectPrefixes.clear()
32
+ }
33
+
34
+ export function knownAvenPrefixes(): readonly string[] {
35
+ return [...avenProjectPrefixes]
36
+ }
37
+
38
+ export function parseRefKind(raw: string): RefKind {
39
+ if (raw.startsWith('aven:')) {
40
+ return { kind: 'aven', ref: raw.slice('aven:'.length) }
41
+ }
42
+ if (raw.startsWith('jira:')) {
43
+ const key = raw.slice('jira:'.length)
44
+ const match = JIRA_RE.exec(key)
45
+ if (match) {
46
+ return { kind: 'jira', jiraId: `${match[1].toUpperCase()}-${match[2]}` }
47
+ }
48
+ return { kind: 'jira', jiraId: key.toUpperCase() }
49
+ }
50
+ const match = JIRA_RE.exec(raw)
51
+ if (match) {
52
+ // PMR-F8HB: a Jira-shaped ref whose alpha prefix belongs to a known
53
+ // aven project is an aven ref with an all-digit suffix (PMR-2424).
54
+ if (avenProjectPrefixes.has(match[1].toUpperCase())) {
55
+ return { kind: 'aven', ref: raw }
56
+ }
57
+ return { kind: 'jira', jiraId: `${match[1].toUpperCase()}-${match[2]}` }
58
+ }
59
+ return { kind: 'aven', ref: raw }
60
+ }
61
+
62
+ /**
63
+ * The ref a flow run is TRACKED by in telemetry, metrics and dashboards.
64
+ * Personal mode: the aven ref. Work mode: the Jira key — taken from the Jira
65
+ * ID the user typed (`/flow DP-236`), else from the epic's `jira-ref` metadata
66
+ * (when the user passed the local aven epic), else the aven ref. The aven ref
67
+ * itself is unchanged everywhere else (journal filename, aven operations).
68
+ */
69
+ export function trackingRef(input: {
70
+ mode: 'work' | 'personal'
71
+ avenRef: string
72
+ jiraId?: string
73
+ epicJiraRef?: string | null
74
+ }): string {
75
+ if (input.mode !== 'work') return input.avenRef
76
+ if (input.jiraId !== undefined && input.jiraId.length > 0) return input.jiraId
77
+ const epic = input.epicJiraRef
78
+ if (epic !== undefined && epic !== null && epic.length > 0) return epic
79
+ return input.avenRef
80
+ }
@@ -0,0 +1,222 @@
1
+ // AIDEV-NOTE: PMR-T9ZQ 2.2 — pure building blocks for the parked-run RESUME
2
+ // picker: the decision table (planResumePickerOutcome), the menu/fallback
3
+ // label builders, the age formatter, and the best-effort owner-liveness
4
+ // hint. This is the sibling of flow/picker.ts's planTicketPickerOutcome:
5
+ // NO ui calls, NO ctx, NO async, NO side effects here — index.ts (phase 3)
6
+ // renders `ctx.ui.select` with the options returned below and re-calls the
7
+ // planner with the picked option's value as `selection`. Declining must
8
+ // therefore be expressible with zero session state change, which it is:
9
+ // every plan kind is data.
10
+ //
11
+ // AIDEV-NOTE: PMR-T9ZQ — ownerPidAlive is a COPIED pattern from
12
+ // pi-interactive-subagents assignments.ts:206-214. Cross-package runtime
13
+ // imports are forbidden, so it is duplicated here on purpose; keep both
14
+ // copies' semantics (ESRCH=dead, EPERM=alive, other=dead) in sync.
15
+ // Pid REUSE IS AN ACCEPTED RISK (mirrors assignments.ts:64): a dead owner's
16
+ // pid may be recycled by an unrelated process. In this picker the answer is
17
+ // display-only and never blocks, pre-selects, or auto-resumes. PMR-RRW9 also
18
+ // uses the probe for bind adoption: there, a reused live pid plus a session
19
+ // mismatch fails closed and leaves explicit /flow recovery to the human.
20
+
21
+ import type { OwnerRecord } from '../run-state.ts'
22
+ import type { ParkedCandidate } from './durable-refs.ts'
23
+
24
+ /** One select row. `value` is the stable id the caller maps back to a
25
+ * candidate (refs for run rows, RESUME_NONE_VALUE for the clean-session
26
+ * row); `label` is the display string handed to ctx.ui.select. */
27
+ export interface ResumePickerOption {
28
+ label: string
29
+ value: string
30
+ }
31
+
32
+ /** Sentinel value for the "None — leave this session clean" row: picking it
33
+ * declines, exactly like cancelling the dialog. */
34
+ export const RESUME_NONE_VALUE = '__resume-none__'
35
+
36
+ /** What the caller's select returned. `resume-cancelled` is Esc/abort;
37
+ * `value` is the picked option's value (never a label prefix match). A
38
+ * value that resolves to no candidate is a lookup miss (the list changed
39
+ * between render and pick) and is handled fail-closed. */
40
+ export type ResumeSelection =
41
+ | { stage: 'resume-cancelled' }
42
+ | { stage: 'resume-picked'; value: string }
43
+
44
+ /**
45
+ * What the caller does next. Pure data, one kind per branch:
46
+ * - 'silent': zero candidates — nothing to say, nothing to ask.
47
+ * - 'fallback': headless (or fail-closed after a select throw) — lines the
48
+ * caller surfaces as info; the session stays clean.
49
+ * - 'menu': render ctx.ui.select with these options.
50
+ * - 'declined': the human said no (or the pick went stale) — no binding,
51
+ * no heal, no injection; `refs` feeds one info line listing the
52
+ * recovery command(s).
53
+ * - 'resume': the human consented to this exact candidate — the caller may
54
+ * now bind/heal/consume.
55
+ */
56
+ export type ResumePickerPlan =
57
+ | { kind: 'silent' }
58
+ | { kind: 'fallback'; lines: string[] }
59
+ | { kind: 'menu'; options: ResumePickerOption[] }
60
+ | { kind: 'declined'; refs: string[] }
61
+ | { kind: 'resume'; candidate: ParkedCandidate }
62
+
63
+ const MINUTE_MS = 60_000
64
+ const HOUR_MS = 60 * MINUTE_MS
65
+ const DAY_MS = 24 * HOUR_MS
66
+
67
+ /**
68
+ * Human age of `atIso` relative to `nowIso`: 'just now' (< 1m), 'Xm ago'
69
+ * (< 1h), 'Xh ago' (< 1d), 'Xd ago' beyond that. A future or unparsable
70
+ * timestamp is never a negative/NaN age: future → 'just now', malformed →
71
+ * 'unknown'.
72
+ */
73
+ export function formatAge(nowIso: string, atIso: string): string {
74
+ const nowMs = Date.parse(nowIso)
75
+ const atMs = Date.parse(atIso)
76
+ if (Number.isNaN(nowMs) || Number.isNaN(atMs)) return 'unknown'
77
+ const deltaMs = nowMs - atMs
78
+ if (deltaMs < MINUTE_MS) return 'just now'
79
+ if (deltaMs < HOUR_MS) return `${Math.floor(deltaMs / MINUTE_MS)}m ago`
80
+ if (deltaMs < DAY_MS) return `${Math.floor(deltaMs / HOUR_MS)}h ago`
81
+ return `${Math.floor(deltaMs / DAY_MS)}d ago`
82
+ }
83
+
84
+ function errorCode(err: unknown): string {
85
+ if (typeof err !== 'object' || err === null) return ''
86
+ const code: unknown = Reflect.get(err, 'code')
87
+ if (typeof code === 'string') return code
88
+ return ''
89
+ }
90
+
91
+ /**
92
+ * Copied liveness probe (see the header AIDEV-NOTE): `process.kill(pid, 0)`
93
+ * performs permission/existence checks without signalling. ESRCH → dead;
94
+ * EPERM → alive (another user's process); success → alive; any other throw
95
+ * (incl. a non-positive pid, which would otherwise mean "signal my own
96
+ * process group") → dead. The picker displays the answer; deriveFlowRefs
97
+ * additionally uses it for fail-closed bind adoption (PMR-RRW9).
98
+ */
99
+ export function ownerPidAlive(pid: number): boolean {
100
+ if (!Number.isInteger(pid) || pid <= 0) return false
101
+ try {
102
+ process.kill(pid, 0)
103
+ return true
104
+ } catch (err) {
105
+ return errorCode(err) === 'EPERM'
106
+ }
107
+ }
108
+
109
+ /** Liveness hint for one owner record: '' when there is no owner at all
110
+ * (pre-owner journals), else the alive/exited wording shown in the menu. */
111
+ export function ownerHint(owner: OwnerRecord | undefined): string {
112
+ if (owner === undefined) return ''
113
+ if (ownerPidAlive(owner.pid)) return 'owner session appears alive'
114
+ return 'owner session exited'
115
+ }
116
+
117
+ /** Age reference for a candidate: the owner refresh stamp when present (the
118
+ * run-activity stamp is otherwise the freshest signal the picker has). */
119
+ function candidateAgeIso(candidate: ParkedCandidate): string {
120
+ if (candidate.owner === undefined) return candidate.updatedAt
121
+ return candidate.owner.at
122
+ }
123
+
124
+ /** `PMR-X — implement, running, updated 5m ago[, owner session …]` — the
125
+ * shared one-line description behind both the menu label and the fallback
126
+ * line. Pure strings only, so tests can pin the exact text. */
127
+ function describeCandidate(candidate: ParkedCandidate, nowIso: string): string {
128
+ // A run before its first phase-start has no phase; the menu still needs
129
+ // a readable row, so null renders as 'none'.
130
+ let phaseText = 'none'
131
+ if (candidate.phase !== null) phaseText = candidate.phase
132
+ const age = formatAge(nowIso, candidateAgeIso(candidate))
133
+ const base = `${candidate.ref} — ${phaseText}, ${candidate.status}, updated ${age}`
134
+ const hint = ownerHint(candidate.owner)
135
+ if (hint === '') return base
136
+ return `${base}, ${hint}`
137
+ }
138
+
139
+ /** One menu row per candidate plus the clean-session row, always last. */
140
+ export function buildResumeMenuOptions(
141
+ candidates: readonly ParkedCandidate[],
142
+ nowIso: string,
143
+ ): ResumePickerOption[] {
144
+ const options: ResumePickerOption[] = []
145
+ for (const candidate of candidates) {
146
+ options.push({
147
+ label: `Resume ${describeCandidate(candidate, nowIso)}`,
148
+ value: candidate.ref,
149
+ })
150
+ }
151
+ options.push({
152
+ label: 'None — leave this session clean',
153
+ value: RESUME_NONE_VALUE,
154
+ })
155
+ return options
156
+ }
157
+
158
+ /** Headless / fail-closed plain-text listing: one line per candidate naming
159
+ * the exact recovery command. The caller surfaces these and binds nothing. */
160
+ export function buildResumeFallbackLines(
161
+ candidates: readonly ParkedCandidate[],
162
+ nowIso: string,
163
+ ): string[] {
164
+ const lines: string[] = []
165
+ for (const candidate of candidates) {
166
+ lines.push(
167
+ `${describeCandidate(candidate, nowIso)} — recover with /flow ${candidate.ref}`,
168
+ )
169
+ }
170
+ return lines
171
+ }
172
+
173
+ function candidateRefs(candidates: readonly ParkedCandidate[]): string[] {
174
+ const refs: string[] = []
175
+ for (const candidate of candidates) {
176
+ refs.push(candidate.ref)
177
+ }
178
+ return refs
179
+ }
180
+
181
+ /**
182
+ * Pure decision table for the parked-run resume picker. Ordering matters
183
+ * and mirrors the incident this guards: no candidates means there is
184
+ * nothing to ask (silent) whatever the UI or selection state; a session
185
+ * without UI never sees a menu (fallback); only a UI session with no
186
+ * selection yet gets the menu; then the selection is classified —
187
+ * cancel/Esc, the clean-session row, and a stale/unknown value all land on
188
+ * 'declined' (fail-closed: nothing is bound, healed, or injected), and
189
+ * only an exact ref match yields 'resume'.
190
+ */
191
+ export function planResumePickerOutcome(
192
+ hasUI: boolean,
193
+ candidates: readonly ParkedCandidate[],
194
+ selection?: ResumeSelection,
195
+ nowIso: string = new Date().toISOString(),
196
+ ): ResumePickerPlan {
197
+ if (candidates.length === 0) {
198
+ return { kind: 'silent' }
199
+ }
200
+ if (!hasUI) {
201
+ return {
202
+ kind: 'fallback',
203
+ lines: buildResumeFallbackLines(candidates, nowIso),
204
+ }
205
+ }
206
+ if (selection === undefined) {
207
+ return { kind: 'menu', options: buildResumeMenuOptions(candidates, nowIso) }
208
+ }
209
+ if (selection.stage === 'resume-cancelled') {
210
+ return { kind: 'declined', refs: candidateRefs(candidates) }
211
+ }
212
+ if (selection.value === RESUME_NONE_VALUE) {
213
+ return { kind: 'declined', refs: candidateRefs(candidates) }
214
+ }
215
+ const picked = candidates.find((c) => c.ref === selection.value)
216
+ if (picked === undefined) {
217
+ // Lookup miss: the menu was rendered from a list this candidate no
218
+ // longer belongs to. Stay clean rather than guessing across refs.
219
+ return { kind: 'declined', refs: candidateRefs(candidates) }
220
+ }
221
+ return { kind: 'resume', candidate: picked }
222
+ }
package/flow/resume.ts ADDED
@@ -0,0 +1,116 @@
1
+ // AIDEV-NOTE: PMR-XTQQ phase 2 — resume seeding from the durable journal.
2
+ // Pure tail-reader over readRunEvents output: picks the latest run-input and
3
+ // loop-state events for a ref. The seed restores the loop's retry budget and
4
+ // the validate blockers-note cutoff EXACTLY (a fresh Date.now() would
5
+ // re-narrow the freshness window). Phase position is NEVER seeded here —
6
+ // aven labels remain the run state; the loop re-derives it via nextPhase().
7
+ // The journaled prompt-input scalars are used only when their gitRoot still
8
+ // exists on disk (otherwise the handler rebuilds fresh via commandPhaseInput).
9
+ import type {
10
+ FlowRunEvent,
11
+ LoopRunStatus,
12
+ LoopStateRecord,
13
+ RunInputRecord,
14
+ } from '../run-state.ts'
15
+
16
+ export interface FlowResumeSeed {
17
+ /**
18
+ * Restored budget/cutoff; present when the last snapshot was non-terminal.
19
+ */
20
+ resume?: {
21
+ blockerRetries: number
22
+ validateStartedAt: string
23
+ }
24
+ /** Journaled prompt-input scalars; present only when gitRoot still exists. */
25
+ input?: RunInputRecord
26
+ }
27
+
28
+ const NON_TERMINAL: readonly LoopRunStatus[] = ['running', 'paused']
29
+
30
+ export function resumeSeedFromEvents(
31
+ events: FlowRunEvent[] | null,
32
+ gitRootExists: (p: string) => boolean,
33
+ ): FlowResumeSeed {
34
+ const seed: FlowResumeSeed = {}
35
+ let loop: LoopStateRecord | null = null
36
+ let input: RunInputRecord | null = null
37
+ if (events !== null) {
38
+ for (const event of events) {
39
+ if (event.kind === 'loop-state') loop = event.loop
40
+ if (event.kind === 'run-input') input = event.input
41
+ }
42
+ }
43
+ // AIDEV-NOTE: only non-terminal snapshots seed — a halted/done run must
44
+ // not leak a stale blockers cutoff into a fresh rerun.
45
+ if (loop !== null && NON_TERMINAL.includes(loop.status)) {
46
+ seed.resume = {
47
+ blockerRetries: loop.blockerRetries,
48
+ validateStartedAt: loop.validateStartedAt,
49
+ }
50
+ }
51
+ if (input !== null && gitRootExists(input.gitRoot)) {
52
+ seed.input = input
53
+ }
54
+ return seed
55
+ }
56
+
57
+ export interface JournalablePromptInput {
58
+ mode: 'work' | 'personal'
59
+ gitRoot: string
60
+ workRoots: readonly string[]
61
+ yolo?: boolean
62
+ }
63
+
64
+ /**
65
+ * AIDEV-NOTE: PMR-XTQQ 2.2 — the /flow handler's seed override: journaled
66
+ * scalars win over the freshly rebuilt commandPhaseInput result (the gitRoot
67
+ * existence gate already ran in resumeSeedFromEvents, so an override here is
68
+ * safe). Extracted pure so flow.test.ts exercises exactly what the handler
69
+ * merges before it journals run-input.
70
+ */
71
+ export function mergeSeedInput<T extends JournalablePromptInput>(
72
+ promptInput: T,
73
+ seed: FlowResumeSeed,
74
+ ): T {
75
+ if (seed.input === undefined) {
76
+ return promptInput
77
+ }
78
+ // AIDEV-NOTE: yolo plan 2.2 + review fix (P1) — the JOURNALED seed wins
79
+ // for yolo ONLY while the journaled run is non-terminal: seed.resume is
80
+ // present exactly when the last loop snapshot was running/paused
81
+ // (resumeSeedFromEvents), so a flag-less re-invocation of a live yolo run
82
+ // stays yolo and --yolo cannot upgrade a live non-yolo seed. A halted/done
83
+ // run is a FRESH start: the explicit flag/config applies and history never
84
+ // silently vetoes it. The handler must therefore stamp parsed.yolo onto
85
+ // promptInput BEFORE calling this, not after.
86
+ const seedYolo = seed.input.yolo === true
87
+ return {
88
+ ...promptInput,
89
+ mode: seed.input.mode,
90
+ gitRoot: seed.input.gitRoot,
91
+ workRoots: seed.input.workRoots,
92
+ // terminal journal (no resume block): keep the fresh flag/config value
93
+ ...(seed.resume !== undefined ? { yolo: seedYolo } : {}),
94
+ }
95
+ }
96
+
97
+ /**
98
+ * AIDEV-NOTE: PMR-XTQQ 2.2 — the serializable prompt-input subset the /flow
99
+ * handler journals as a run-input event. Closures and labels (findTicketRef,
100
+ * epicHasOpenChildren, ...) are rebuilt per invocation and never journaled.
101
+ */
102
+ export function runInputRecord(
103
+ promptInput: JournalablePromptInput,
104
+ ): RunInputRecord {
105
+ const record: RunInputRecord = {
106
+ mode: promptInput.mode,
107
+ gitRoot: promptInput.gitRoot,
108
+ workRoots: [...promptInput.workRoots],
109
+ }
110
+ // yolo plan 2.2 — journal the flag only when on, so non-yolo records keep
111
+ // the pre-yolo shape (mergeSeedInput treats a missing field as non-yolo).
112
+ if (promptInput.yolo === true) {
113
+ record.yolo = true
114
+ }
115
+ return record
116
+ }
@@ -0,0 +1,252 @@
1
+ // AIDEV-NOTE: run-lifecycle health metrics for the Pushgateway push body.
2
+ // These series are JOURNAL-PROJECTION-ONLY: every value is derived from the
3
+ // run journal events (projectRunState + raw event scans), never from session
4
+ // jsonl files — so they appear even when session coverage gaps exist, and
5
+ // they keep working if cost attribution changes shape. Dashboards
6
+ // `piflow-health/runs` consume these exact metric names/labels (frozen —
7
+ // renaming a metric or label is a dashboard-breaking change).
8
+ // AIDEV-NOTE (PMR-ZV9Y 7.1): the FROZEN SET below is now — after the v1
9
+ // state-vocabulary retirement — {gate decisions, retry attempts, blocker
10
+ // retries, worktree sweep, run start}, followed by the v2 state-machine
11
+ // gauges. The four v1 state-vocabulary lines `pi_flow_run_status`,
12
+ // `pi_flow_run_halt_reason`, `pi_flow_human_wait_seconds` and
13
+ // `pi_flow_gate_wait_seconds` were retired here (their blocks and the
14
+ // scanPausedWindows path that fed them are gone) because phases 6.2–6.5 cut
15
+ // every dashboard and alert rule over to the v2 state vocabulary
16
+ // (`pi_flow_state` …, rendered by flow/state-metrics.ts). The halt reason is
17
+ // now ONLY the closed v2 reason enum on `pi_flow_state`/`pi_flow_wait_seconds`
18
+ // — the free-text halt-note derivation that block 2 used to scrape onto a
19
+ // label value is deleted (plan gotcha 8). Nothing outside the frozen set may
20
+ // move, rename or reorder; the v2 blocks are appended after the frozen block
21
+ // in the plan's table order (see the append site below).
22
+ // AIDEV-NOTE (PMR-8MQH 4.2): WHO PUSHES these lines changed, WHAT they say
23
+ // did not. `pi_flow_run_status` used to reach the gateway only from the
24
+ // session-side terminal autopush; since PMR-8MQH the daemon's periodic
25
+ // liveness pass (flow/liveness.ts) also pushes this same render for refs
26
+ // whose journal projects `running`, so a `running` value now refreshes while
27
+ // a run is in flight. No metric name, label key, label value or line ORDER
28
+ // changed — the frozen rule above still holds, and both producers render
29
+ // through the identical buildPushBody path.
30
+ // AIDEV-NOTE (PMR-8MQH 1.2): labelString is imported from './cost-rows.ts',
31
+ // NOT './cost.ts' — cost.ts value-imports the pi-interactive-subagents root
32
+ // (heavy extension graph), so an edge there would silently drag the session-
33
+ // side runtime into this daemon-reachable module's closure. The OLD
34
+ // cost.ts <-> run-health.ts cycle is gone; the cycle here is now the family
35
+ // seam cost-rows.ts -> cost-rows-push.ts -> run-health.ts -> cost-rows.ts
36
+ // (PMR-45VS): labelString is DECLARED in './cost-rows-push.ts' and re-exported
37
+ // through the './cost-rows.ts' facade, so this import site never moved. The
38
+ // cycle stays deliberate and ESM-safe: every side exports only hoisted
39
+ // function declarations consumed at call time, never at module init. The
40
+ // closure guard in test/cost-rows-node-only.test.ts keeps cost.ts out of it.
41
+ // AIDEV-NOTE (PMR-ZV9Y 3.2): the frozen block below is FROZEN-UNTIL-CUTOVER,
42
+ // not frozen-forever. Subtask 3.2 appended the v2 state-machine gauges as
43
+ // blocks 10+ (see renderStateMetricLines below), so this module now renders
44
+ // BOTH vocabularies at once — deliberately, because the live alert rules and
45
+ // the `piflow-*` boards still read the v1 series and the cutover is one
46
+ // deliberate move in 6.5. The retirement of the v1 state-vocabulary lines
47
+ // (run status, halt reason, human wait, gate waits) belongs to phase 7 ONLY,
48
+ // and nothing before 6.5 may move, rename or drop an existing line. The
49
+ // additive rule and the reason the v1 lines cannot be dropped early are both
50
+ // recorded at the append site below and in flow/state-metrics.ts.
51
+ // AIDEV-NOTE (PMR-ZV9Y 7.1): this cutover has now LANDED — the four v1
52
+ // state-vocabulary blocks are removed and the v2 gauges above are the only
53
+ // state vocabulary this module renders. See the header 7.1 note for the new
54
+ // frozen set; the FROZEN-UNTIL-CUTOVER framing above is kept as history.
55
+ // AIDEV-NOTE (PMR-9DZ0 2.1; title retention amended by PMR-2EGV): the
56
+ // run-title block below is an ADDITIVE AMENDMENT to that frozen shape, not a
57
+ // change to it: `pi_flow_run_title_info` is a new family appended AFTER the
58
+ // frozen set and AFTER the v2 state families (block 7), so nothing existing
59
+ // moved, renamed or reordered and the frozen-prefix pins stay byte-for-byte.
60
+ // It is journal-derived only (the LAST run-start carrying a title wins),
61
+ // renders through the existing labelString/escapeLabelValue seam above, and
62
+ // adds NO import — the node-only closure guarded by
63
+ // test/cost-rows-node-only.test.ts is untouched. Dashboards join it as `* on
64
+ // (ref) group_left (title)`. flow/push.ts now KEEPS this family in fetched
65
+ // group bodies (superseding the PMR-9DZ0 2.2 / PMR-2CPZ prune): terminal
66
+ // publication DELETEs the group and re-POSTs the body, so dropping the title
67
+ // would erase run-title history. Keeping it cannot resurrect an old title IN
68
+ // THE RENDER — every fresh push re-renders the current journal title — but
69
+ // AIDEV-NOTE (PMR-3W5K): on the merge-on-write gateway (PMR-WBC2) an
70
+ // unchanged title is the only case a fresh push overwrites in place. A
71
+ // resumed run whose ticket was RENAMED stores the new title ALONGSIDE the
72
+ // old-title series (a different title label is a different series; merge
73
+ // never deletes), and the terminal re-post carries forward whatever the last
74
+ // fresh push stored — so a renamed run's stored group can hold multiple title
75
+ // variants. The old variant is also a stored non-target series the fresh body
76
+ // never contains, so the terminal-purge guard SKIPs fail-closed on it
77
+ // (flow/terminal-purge.ts, PMR-3W5K note); the safe cleanup is the manual
78
+ // runbook — DELETE the pushgateway group, then /flow-cost <ref> --push.
79
+ import type { FlowRunEvent } from '../run-state.ts'
80
+ import { projectRunState } from '../run-state.ts'
81
+ import { labelString } from './cost-rows.ts'
82
+ import { renderStateMetricLines } from './state-metrics.ts'
83
+
84
+ // `at` is a raw journal string (readRunEvents casts JSON.parse output), so an
85
+ // unparseable timestamp is possible in practice: treat it as "absent" instead
86
+ // of letting NaN reach the exposition body. (The retired v1 wait windows kept
87
+ // their own unfloored millisecond math — flooring there would have changed
88
+ // existing values; the surviving v2 window math lives in
89
+ // flow/state-metrics.ts.)
90
+ function epochSeconds(at: string): number | undefined {
91
+ const seconds = Math.floor(Date.parse(at) / 1000)
92
+ if (!Number.isFinite(seconds)) return undefined
93
+ return seconds
94
+ }
95
+
96
+ // AIDEV-NOTE: pi_flow_run_start_seconds is ADDITIVE — it joined the frozen
97
+ // series without renaming or reordering any existing line.
98
+ // AIDEV-NOTE (PMR-ZV9Y 7.1): this note said "it is no longer literally the last
99
+ // line" because the additive pi_flow_gate_wait_seconds series followed it; that
100
+ // series is retired, so run start is the last line of the frozen set again and
101
+ // only the v2 state gauges come after it.
102
+ // Consumers: the homelab `piflow-runs` dashboard ("Started"
103
+ // column and the run timeline panel), which needs an absolute epoch timestamp
104
+ // per ref; gauge values alone only say "this ref exists", not when it began.
105
+ // Derived from the journal: the FIRST 'run-start' event wins (a restart
106
+ // re-records run-start, but the run's start stays the original one), falling
107
+ // back to the earliest event timestamp when no run-start carries a parseable
108
+ // `at`. No usable timestamp means no line at all.
109
+ function runStartSeconds(events: readonly FlowRunEvent[]): number | undefined {
110
+ for (const event of events) {
111
+ if (event.kind !== 'run-start') continue
112
+ const seconds = epochSeconds(event.at)
113
+ if (seconds !== undefined) return seconds
114
+ }
115
+ let earliest: number | undefined
116
+ for (const event of events) {
117
+ const seconds = epochSeconds(event.at)
118
+ if (seconds === undefined) continue
119
+ if (earliest === undefined || seconds < earliest) earliest = seconds
120
+ }
121
+ return earliest
122
+ }
123
+
124
+ // AIDEV-NOTE (PMR-9DZ0 2.1): pi_flow_run_title_info is derived from the LAST
125
+ // run-start carrying a title — deliberately the OPPOSITE of runStartSeconds'
126
+ // first-wins rule. A resume re-journals run-start with a fresh ticket title,
127
+ // and the newest title is the one the dashboard should show; a resume whose
128
+ // lookup failed journals no `title` key at all, so title-less run-start events
129
+ // are skipped rather than clearing an earlier title. Sanitized at journal-write
130
+ // time by run-title.ts (single line, capped, control chars stripped), so the
131
+ // render only needs the exposition escaping that labelString already applies.
132
+ // An empty title never reaches the render: the writer omits the key, and an
133
+ // empty-title series would fan out the dashboard group_left(title) join.
134
+ function runTitle(events: readonly FlowRunEvent[]): string | undefined {
135
+ let title: string | undefined
136
+ for (const event of events) {
137
+ if (event.kind !== 'run-start') continue
138
+ if (event.title === undefined || event.title === '') continue
139
+ title = event.title
140
+ }
141
+ return title
142
+ }
143
+
144
+ /**
145
+ * Render the Prometheus exposition lines for run health (gate decision counts,
146
+ * retry/blocker counters, worktree-sweep counts, run start epoch seconds,
147
+ * then the v2 state-machine gauges, then the additive run-title tail block).
148
+ * Pure: same journal events in, same lines out. Metric order is fixed; within a
149
+ * grouped metric lines follow first-seen event order so pushes stay byte-stable
150
+ * for the Pushgateway group. The FROZEN block (gate decisions … run start)
151
+ * never moves; the v2 state gauges are appended after it (see the append site
152
+ * below), and the title block after those (see the header PMR-9DZ0 note).
153
+ *
154
+ * AIDEV-NOTE (PMR-ZV9Y 7.1): the v1 state-vocabulary lines this used to render
155
+ * (`pi_flow_run_status`, `pi_flow_run_halt_reason`, `pi_flow_human_wait_seconds`,
156
+ * `pi_flow_gate_wait_seconds`) are retired — the v2 `pi_flow_state` /
157
+ * `pi_flow_state_start_seconds` / `pi_flow_wait_seconds` families in
158
+ * flow/state-metrics.ts supersede them, and every dashboard/alert consumer was
159
+ * cut over in 6.2–6.5. The paused-window scan that fed the two wait lines is
160
+ * gone with them (flow/state-metrics.ts keeps its own mirror for the ISC-6
161
+ * legacy fallback).
162
+ */
163
+ export function renderRunHealthLines(
164
+ ref: string,
165
+ events: readonly FlowRunEvent[],
166
+ ): string[] {
167
+ const state = projectRunState(events)
168
+ if (state === null) return []
169
+ const lines: string[] = []
170
+ // 1 — gate decisions: RAW gate-answer events grouped by (gate, choice).
171
+ // The projection deliberately keeps only the latest answer per gate, so
172
+ // counting it would erase the reject→approve retry churn this measures.
173
+ const gateCounts = new Map<string, number>()
174
+ for (const event of events) {
175
+ if (event.kind !== 'gate-answer') continue
176
+ const key = `${event.gate}\u0000${event.choice}`
177
+ gateCounts.set(key, (gateCounts.get(key) ?? 0) + 1)
178
+ }
179
+ for (const [key, count] of gateCounts) {
180
+ const separator = key.indexOf('\u0000')
181
+ lines.push(
182
+ `pi_flow_gate_decisions_total{${labelString({
183
+ ref,
184
+ gate: key.slice(0, separator),
185
+ choice: key.slice(separator + 1),
186
+ })}} ${count}`,
187
+ )
188
+ }
189
+ // 2 — retry attempts (flow_run_attempt budget; 'passed' resets to 0).
190
+ let attempts = 0
191
+ if (state.attempts !== undefined) attempts = state.attempts
192
+ lines.push(`pi_flow_retry_attempts{${labelString({ ref })}} ${attempts}`)
193
+ // 3 — blocker retries from the loop record.
194
+ let blockerRetries = 0
195
+ if (state.loop !== undefined) blockerRetries = state.loop.blockerRetries
196
+ lines.push(
197
+ `pi_flow_blocker_retries{${labelString({ ref })}} ${blockerRetries}`,
198
+ )
199
+ // 4 — worktree sweep outcomes (evidence-only in the projection, so the
200
+ // RAW events carry the counts).
201
+ const sweepCounts = new Map<string, number>()
202
+ for (const event of events) {
203
+ if (event.kind !== 'worktree-sweep') continue
204
+ sweepCounts.set(event.outcome, (sweepCounts.get(event.outcome) ?? 0) + 1)
205
+ }
206
+ for (const [outcome, count] of sweepCounts) {
207
+ lines.push(
208
+ `pi_flow_worktree_sweep_total{${labelString({ ref, outcome })}} ${count}`,
209
+ )
210
+ }
211
+ // 5 — run start epoch seconds (see the AIDEV-NOTE above runStartSeconds).
212
+ // AIDEV-NOTE (PMR-ZV9Y 7.1): this was additive block 8; the retirement of
213
+ // blocks 1+2, 4 and 9 moved it to the tail of the frozen set, which is now
214
+ // {gate decisions, retry attempts, blocker retries, worktree sweep, run
215
+ // start}. Its position relative to every kept line is unchanged.
216
+ const startSeconds = runStartSeconds(events)
217
+ if (startSeconds !== undefined) {
218
+ lines.push(
219
+ `pi_flow_run_start_seconds{${labelString({ ref })}} ${startSeconds}`,
220
+ )
221
+ }
222
+ // 6+ — the v2 state-machine gauges (flow/state-metrics.ts), the successor of
223
+ // the v1 state vocabulary retired above.
224
+ // AIDEV-NOTE (PMR-ZV9Y 3.2): the v2 blocks were ADDITIVE when they landed —
225
+ // every family was appended AFTER every pre-existing line, in the plan's
226
+ // table order (state, state start, phase, wait, step, step seconds), so
227
+ // nothing existing moved, renamed or reordered while the live alert rules and
228
+ // the `piflow-*` boards still read the v1 series.
229
+ // AIDEV-NOTE (PMR-ZV9Y 7.1): with the v1 state-vocabulary lines now retired,
230
+ // that table order IS the state-vocabulary order; the families after the
231
+ // frozen set are frozen too (see the header 7.1 note).
232
+ // The render is the single shared seam for BOTH push paths — the terminal
233
+ // autopush and the daemon liveness pass call the same buildPushBody →
234
+ // renderRunHealthLines chain (the PMR-8MQH invariant) — which is why the v2
235
+ // math lives in a pure module reached from here rather than session-side.
236
+ // `renderStateMetricLines` returns no lines when nothing derives (no
237
+ // projection, or a projection with neither a v1 loop record nor a v2
238
+ // 'state-change'), so for those journals it contributes nothing.
239
+ for (const line of renderStateMetricLines(ref, events)) {
240
+ lines.push(line)
241
+ }
242
+ // 7 — run title info (PMR-9DZ0). ADDITIVE TAIL BLOCK appended AFTER the v2
243
+ // state families; the frozen set and the v2 families are untouched — see the
244
+ // header amendment note. Journal-derived only: LAST run-start with a title wins.
245
+ // One series per ref; dashboards join `* on (ref) group_left (title)` with an
246
+ // `or … unless on (ref)` fallback so title-less runs stay visible.
247
+ const title = runTitle(events)
248
+ if (title !== undefined) {
249
+ lines.push(`pi_flow_run_title_info{${labelString({ ref, title })}} 1`)
250
+ }
251
+ return lines
252
+ }