@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,122 @@
1
+ // AIDEV-NOTE (PMR-EA8X): /flow-cost command registration. All data access
2
+ // is injected so tests exercise the command purely; the offline ground-truth
3
+ // rollup lives in flow/cost-rows.ts (moved out of this module in PMR-8MQH 1.3
4
+ // so the daemon can reach it — this file re-exports it, see below). `--push`
5
+ // forwards aggregates to the Pushgateway (optional backend): push failures
6
+ // surface as warnings and never fail the report — the session files stay the
7
+ // authority.
8
+
9
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
10
+ import { isValidRef } from '../herdr/viewer.ts'
11
+ import { buildPushBody, formatCostReport, type PushResult } from './cost.ts'
12
+ import {
13
+ type CostRollup,
14
+ type CostRollupDeps,
15
+ computeCostRollup,
16
+ } from './cost-rows.ts'
17
+
18
+ // AIDEV-NOTE (PMR-8MQH 1.3): computeCostRollup + CostRollup/CostRollupDeps
19
+ // live in flow/cost-rows.ts (node-only, daemon-reachable). Re-exported here so
20
+ // every existing importer (flow/cost-autopush.ts, index.ts, test/*) keeps its
21
+ // './cost-command.ts' import unchanged.
22
+ export { type CostRollup, type CostRollupDeps, computeCostRollup }
23
+
24
+ export interface FlowCostDeps extends CostRollupDeps {
25
+ /** Push exposition body to the gateway; ok=false is a warning, not fatal. */
26
+ push: (
27
+ ref: string,
28
+ body: string,
29
+ mode?: 'work' | 'personal',
30
+ ) => Promise<PushResult>
31
+ }
32
+
33
+ type ParsedCostArgs =
34
+ | { kind: 'ok'; ref: string; push: boolean }
35
+ | { kind: 'help' }
36
+
37
+ export function parseCostArgs(args: string): ParsedCostArgs {
38
+ const tokens = args
39
+ .trim()
40
+ .split(/\s+/)
41
+ .filter((t) => t.length > 0)
42
+ let ref: string | null = null
43
+ let push = false
44
+ for (const token of tokens) {
45
+ if (token === '--push') {
46
+ push = true
47
+ continue
48
+ }
49
+ if (ref === null) {
50
+ ref = token
51
+ continue
52
+ }
53
+ return { kind: 'help' }
54
+ }
55
+ if (ref === null) return { kind: 'help' }
56
+ return { kind: 'ok', ref, push }
57
+ }
58
+
59
+ export function registerFlowCostCommand(
60
+ pi: ExtensionAPI,
61
+ deps: FlowCostDeps,
62
+ ): void {
63
+ pi.registerCommand('flow-cost', {
64
+ description:
65
+ 'Per-ticket cost rollup from session files (offline ground truth). Usage: /flow-cost <ref> [--push]',
66
+ handler: async (args, ctx) => {
67
+ const parsed = parseCostArgs(args)
68
+ if (parsed.kind === 'help') {
69
+ ctx.ui.notify(
70
+ 'Usage: /flow-cost <ref> [--push] — cost per worker/subtask/phase from the run journal + session files.',
71
+ 'info',
72
+ )
73
+ return
74
+ }
75
+ if (!isValidRef(parsed.ref)) {
76
+ ctx.ui.notify(
77
+ `/flow-cost ${parsed.ref}: invalid ref (must match [A-Za-z0-9][A-Za-z0-9._-]{0,99}) — aborting.`,
78
+ 'warning',
79
+ )
80
+ return
81
+ }
82
+ const rollup = await computeCostRollup(parsed.ref, deps)
83
+ if (rollup.kind === 'no-journal') {
84
+ ctx.ui.notify(
85
+ `/flow-cost ${parsed.ref}: no run journal found — nothing to roll up.`,
86
+ 'warning',
87
+ )
88
+ return
89
+ }
90
+ if (rollup.kind === 'empty') {
91
+ ctx.ui.notify(
92
+ `/flow-cost ${parsed.ref}: journal has no subagent spawn notes (pre-attribution run?) — nothing to roll up.`,
93
+ 'info',
94
+ )
95
+ return
96
+ }
97
+ const { rows, durations, trackRef, mode, steps, events } = rollup
98
+ ctx.ui.notify(
99
+ formatCostReport(parsed.ref, rows, durations, steps ?? []),
100
+ 'info',
101
+ )
102
+ if (parsed.push) {
103
+ const result = await deps.push(
104
+ trackRef,
105
+ buildPushBody(trackRef, rows, durations, events),
106
+ mode,
107
+ )
108
+ if (result.ok) {
109
+ ctx.ui.notify(
110
+ `/flow-cost ${parsed.ref}: pushed aggregates to the pushgateway.`,
111
+ 'info',
112
+ )
113
+ } else {
114
+ ctx.ui.notify(
115
+ `/flow-cost ${parsed.ref}: pushgateway push FAILED (${result.error ?? 'unknown error'}) — report above is still the ground truth.`,
116
+ 'warning',
117
+ )
118
+ }
119
+ }
120
+ },
121
+ })
122
+ }
@@ -0,0 +1,296 @@
1
+ // AIDEV-NOTE (PMR-FQMW 1.1): journal/session projection family — the pure
2
+ // readers of the run journal and session jsonl bodies, split out of
3
+ // flow/cost-rows.ts so each cost-rows module stays small. This module is part
4
+ // of the cost-rows family and is held to the same rules; the load-bearing
5
+ // MODULE CONTRACT (node-only, daemon-reachable, byte-stable) lives in
6
+ // flow/cost-rows.ts and is not restated here.
7
+
8
+ import type { FlowPhase, FlowRunEvent } from '../run-state.ts'
9
+
10
+ /** One parsed attribution note from the run journal. */
11
+ export interface SpawnNote {
12
+ childId: string
13
+ name: string
14
+ kind: 'spawn' | 'resume' | 'reattach'
15
+ subtask: string | null
16
+ sessionFile: string | null
17
+ at: string
18
+ /** Phase active when the spawn happened (null = between phases). */
19
+ phase: FlowPhase | null
20
+ }
21
+
22
+ export interface ToolCallCount {
23
+ tool: string
24
+ status: 'ok' | 'error'
25
+ count: number
26
+ }
27
+
28
+ export interface PhaseDuration {
29
+ phase: FlowPhase
30
+ /** Seconds from phase-start to phase-complete (or the last journal event). */
31
+ seconds: number
32
+ }
33
+
34
+ // AIDEV-NOTE: legacy reader only — writer retired note emission in PMR-C998;
35
+ // do not re-add. Kept so old note-only journals still parse.
36
+ const SPAWN_NOTE_RE =
37
+ /^subagent (\S+) \("([^"]*)"\) (spawn|resume|reattach)(?: for subtask (\S+))? — attribution env stamped(?:, session="([^"]*)")?$/
38
+
39
+ /** Parse one journal note text into a SpawnNote (null when not a spawn note). */
40
+ export function parseSpawnNote(
41
+ text: string,
42
+ phase: FlowPhase | null,
43
+ ): SpawnNote | null {
44
+ const match = SPAWN_NOTE_RE.exec(text)
45
+ if (match === null) return null
46
+ let subtask: string | null = null
47
+ if (match[4] !== undefined) subtask = match[4]
48
+ let sessionFile: string | null = null
49
+ if (match[5] !== undefined) sessionFile = match[5]
50
+ return {
51
+ childId: match[1],
52
+ name: match[2],
53
+ kind: match[3] as SpawnNote['kind'],
54
+ subtask,
55
+ sessionFile,
56
+ at: '',
57
+ phase,
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Extract spawn notes from ordered journal events, annotating each with the
63
+ * phase that was active at that point in the event stream. Notes written
64
+ * before the first phase-start (or between phases) get null.
65
+ */
66
+ export function collectSpawnNotes(
67
+ events: readonly FlowRunEvent[],
68
+ ): SpawnNote[] {
69
+ const notes: SpawnNote[] = []
70
+ let phase: FlowPhase | null = null
71
+ for (const event of events) {
72
+ if (event.kind === 'run-start') {
73
+ phase = null
74
+ continue
75
+ }
76
+ if (event.kind === 'phase-start') {
77
+ phase = event.phase
78
+ continue
79
+ }
80
+ if (event.kind === 'phase-complete') {
81
+ phase = null
82
+ continue
83
+ }
84
+ if (event.kind === 'spawn-record') {
85
+ let subtask: string | null = null
86
+ if (event.subtask !== undefined) subtask = event.subtask
87
+ let sessionFile: string | null = null
88
+ if (event.sessionFile !== undefined) sessionFile = event.sessionFile
89
+ notes.push({
90
+ childId: event.childId,
91
+ name: event.name,
92
+ kind: event.spawnKind,
93
+ subtask,
94
+ sessionFile,
95
+ at: event.at,
96
+ phase,
97
+ })
98
+ continue
99
+ }
100
+ if (event.kind === 'note') {
101
+ const note = parseSpawnNote(event.text, phase)
102
+ if (note !== null) {
103
+ note.at = event.at
104
+ notes.push(note)
105
+ }
106
+ }
107
+ }
108
+ return notes
109
+ }
110
+
111
+ /** Parse a session jsonl file body into entries (torn tail lines skipped). */
112
+ export function parseSessionEntries(text: string): unknown[] {
113
+ const entries: unknown[] = []
114
+ for (const line of text.split('\n')) {
115
+ const trimmed = line.trim()
116
+ if (trimmed.length === 0) continue
117
+ try {
118
+ entries.push(JSON.parse(trimmed))
119
+ } catch {
120
+ // torn tail line — skip
121
+ }
122
+ }
123
+ return entries
124
+ }
125
+
126
+ /** Count toolResult entries per tool/status (session-jsonl shape). Pure. */
127
+ export function countToolCalls(entries: readonly unknown[]): ToolCallCount[] {
128
+ const counts = new Map<string, number>()
129
+ for (const entry of entries) {
130
+ if (entry == null || typeof entry !== 'object') continue
131
+ const e = entry as Record<string, unknown>
132
+ if (e.type !== 'message') continue
133
+ const message = e.message
134
+ if (message == null || typeof message !== 'object') continue
135
+ const m = message as Record<string, unknown>
136
+ if (m.role !== 'toolResult') continue
137
+ let tool = 'unknown'
138
+ if (typeof m.toolName === 'string' && m.toolName.length > 0) {
139
+ tool = m.toolName
140
+ }
141
+ const status: 'ok' | 'error' = m.isError === true ? 'error' : 'ok'
142
+ const key = `${status}\u0000${tool}`
143
+ counts.set(key, (counts.get(key) ?? 0) + 1)
144
+ }
145
+ const out: ToolCallCount[] = []
146
+ for (const [key, count] of counts) {
147
+ const separator = key.indexOf('\u0000')
148
+ out.push({
149
+ status: key.slice(0, separator) as 'ok' | 'error',
150
+ tool: key.slice(separator + 1),
151
+ count,
152
+ })
153
+ }
154
+ out.sort((a, b) => {
155
+ if (a.tool !== b.tool) return a.tool.localeCompare(b.tool)
156
+ if (a.status !== b.status) return a.status.localeCompare(b.status)
157
+ return 0
158
+ })
159
+ return out
160
+ }
161
+
162
+ /** Distinct main-session files journaled for a run, in first-seen order. */
163
+ export function collectMainSessionFiles(
164
+ events: readonly FlowRunEvent[],
165
+ ): string[] {
166
+ const files: string[] = []
167
+ for (const event of events) {
168
+ if (event.kind !== 'main-session') continue
169
+ if (!files.includes(event.sessionFile)) files.push(event.sessionFile)
170
+ }
171
+ return files
172
+ }
173
+
174
+ export interface PhaseWindow {
175
+ phase: FlowPhase
176
+ startMs: number
177
+ /** exclusive */
178
+ endMs: number
179
+ }
180
+
181
+ /**
182
+ * Phase time windows from the journal. A phase runs from its phase-start
183
+ * until the NEXT phase-start (so the model's reply right after
184
+ * flow_phase_complete still counts for the phase it finished); the last
185
+ * phase ends at its phase-complete, else at the last journal event.
186
+ * Repeated phase-starts for one phase (route-back) yield several windows.
187
+ */
188
+ export function phaseWindows(events: readonly FlowRunEvent[]): PhaseWindow[] {
189
+ const starts: Array<{ phase: FlowPhase; ms: number }> = []
190
+ for (const event of events) {
191
+ if (event.kind !== 'phase-start') continue
192
+ const ms = Date.parse(event.at)
193
+ if (Number.isFinite(ms)) starts.push({ phase: event.phase, ms })
194
+ }
195
+ if (starts.length === 0) return []
196
+ let lastMs = starts[starts.length - 1].ms
197
+ const last = starts[starts.length - 1]
198
+ for (const event of events) {
199
+ const ms = Date.parse(event.at)
200
+ if (!Number.isFinite(ms) || ms < last.ms) continue
201
+ if (event.kind === 'phase-complete' && event.phase === last.phase) {
202
+ lastMs = ms
203
+ break
204
+ }
205
+ if (ms > lastMs) lastMs = ms
206
+ }
207
+ const windows: PhaseWindow[] = []
208
+ for (let i = 0; i < starts.length; i += 1) {
209
+ let endMs = lastMs
210
+ if (i + 1 < starts.length) endMs = starts[i + 1].ms
211
+ windows.push({ phase: starts[i].phase, startMs: starts[i].ms, endMs })
212
+ }
213
+ return windows
214
+ }
215
+
216
+ /** Per-phase wall-clock durations from journal events. Pure. */
217
+ export function phaseDurations(
218
+ events: readonly FlowRunEvent[],
219
+ ): PhaseDuration[] {
220
+ const lastAt = events.length > 0 ? events[events.length - 1].at : null
221
+ const out = new Map<FlowPhase, number>()
222
+ const startAt = new Map<FlowPhase, string>()
223
+ for (const event of events) {
224
+ if (event.kind === 'phase-start') {
225
+ startAt.set(event.phase, event.at)
226
+ } else if (event.kind === 'phase-complete') {
227
+ const started = startAt.get(event.phase)
228
+ if (started !== undefined) {
229
+ const seconds = (Date.parse(event.at) - Date.parse(started)) / 1000
230
+ if (Number.isFinite(seconds) && seconds >= 0) {
231
+ out.set(event.phase, (out.get(event.phase) ?? 0) + seconds)
232
+ }
233
+ startAt.delete(event.phase)
234
+ }
235
+ }
236
+ }
237
+ // still-open phases run to the last journal event we have
238
+ if (lastAt !== null) {
239
+ for (const [phase, started] of startAt) {
240
+ const seconds = (Date.parse(lastAt) - Date.parse(started)) / 1000
241
+ if (Number.isFinite(seconds) && seconds >= 0) {
242
+ out.set(phase, (out.get(phase) ?? 0) + seconds)
243
+ }
244
+ }
245
+ }
246
+ const durations: PhaseDuration[] = []
247
+ for (const [phase, seconds] of out) {
248
+ durations.push({ phase, seconds })
249
+ }
250
+ durations.sort((a, b) => a.phase.localeCompare(b.phase))
251
+ return durations
252
+ }
253
+
254
+ /** Per-phase step-output submission counts (advisory evidence only). */
255
+ export interface PhaseStepSummary {
256
+ phase: FlowPhase
257
+ /** All step-output events for the phase (submissions are never deduped). */
258
+ total: number
259
+ /** Submissions with ok === true. */
260
+ ok: number
261
+ /** Submissions with ok === false. */
262
+ failed: number
263
+ }
264
+
265
+ // AIDEV-NOTE (PMR-C998): sums journal 'step-output' submissions per phase.
266
+ // Counting is order-insensitive per PMR-5HTN (single pass, unknown kinds are
267
+ // ignored by the event union itself). Advisory evidence only — a failed step
268
+ // never blocks anything and submissions without `ok` count only in `total`.
269
+ export function summarizeStepOutputs(
270
+ events: readonly FlowRunEvent[],
271
+ ): PhaseStepSummary[] {
272
+ const totals = new Map<FlowPhase, PhaseStepSummary>()
273
+ for (const event of events) {
274
+ if (event.kind !== 'step-output') continue
275
+ const summary = totals.get(event.phase) ?? {
276
+ phase: event.phase,
277
+ total: 0,
278
+ ok: 0,
279
+ failed: 0,
280
+ }
281
+ summary.total += 1
282
+ if (event.ok === true) summary.ok += 1
283
+ if (event.ok === false) summary.failed += 1
284
+ totals.set(event.phase, summary)
285
+ }
286
+ const out: PhaseStepSummary[] = []
287
+ for (const summary of totals.values()) {
288
+ out.push(summary)
289
+ }
290
+ // AIDEV-NOTE (PMR-C998): canonical FlowPhase order (plan, implement,
291
+ // validate, feedback) — NOT alphabetical, so the report reads like the
292
+ // run actually progressed.
293
+ const phaseOrder: FlowPhase[] = ['plan', 'implement', 'validate', 'feedback']
294
+ out.sort((a, b) => phaseOrder.indexOf(a.phase) - phaseOrder.indexOf(b.phase))
295
+ return out
296
+ }
@@ -0,0 +1,112 @@
1
+ // AIDEV-NOTE (PMR-45VS 3.1): Prometheus exposition — the label helpers and
2
+ // the byte-stable Pushgateway body builder — split out of flow/cost-rows.ts
3
+ // so each cost-rows module stays small. This module is part of the cost-rows
4
+ // family and is held to the same rules; the load-bearing MODULE CONTRACT
5
+ // (node-only, daemon-reachable, byte-stable) lives in flow/cost-rows.ts and
6
+ // is not restated here.
7
+
8
+ import type { FlowRunEvent } from '../run-state.ts'
9
+ import { agentRole } from './agent-role.ts'
10
+ import type { PhaseDuration } from './cost-rows-journal.ts'
11
+ import type { WorkerRow } from './cost-rows-rows.ts'
12
+ import { renderRunHealthLines } from './run-health.ts'
13
+
14
+ // AIDEV-NOTE: exported so flow/run-health.ts reuses the exact escaping
15
+ // instead of duplicating it (Prometheus text exposition rules).
16
+ export function escapeLabelValue(value: string): string {
17
+ return value.replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/"/g, '\\"')
18
+ }
19
+
20
+ export function labelString(labels: Record<string, string>): string {
21
+ const parts: string[] = []
22
+ for (const key of Object.keys(labels)) {
23
+ parts.push(`${key}="${escapeLabelValue(labels[key])}"`)
24
+ }
25
+ return parts.join(',')
26
+ }
27
+
28
+ /**
29
+ * Render the Prometheus text exposition for the Pushgateway (PMR-EA8X
30
+ * `--push`). Only sessions that actually reported usage contribute — a
31
+ * coverage gap contributes nothing rather than an invented zero.
32
+ *
33
+ * AIDEV-NOTE: the optional 4th `events` parameter appends the journal-derived
34
+ * run-health lines (flow/run-health.ts) after the cost/duration lines. When
35
+ * omitted the body is byte-identical to the historical output — existing
36
+ * push consumers rely on that.
37
+ */
38
+ export function buildPushBody(
39
+ ref: string,
40
+ rows: readonly WorkerRow[],
41
+ durations: readonly PhaseDuration[],
42
+ events?: readonly FlowRunEvent[],
43
+ ): string {
44
+ const lines: string[] = []
45
+ const roleSeen = new Set<string>()
46
+ const modelSeen = new Set<string>()
47
+ for (const row of rows) {
48
+ if (!row.summary.sawUsage) continue
49
+ // AIDEV-NOTE: role rides on its own info series (one per ref+session) so
50
+ // the existing metric label sets stay untouched; dashboards join it with
51
+ // `* on (ref, session) group_left (role) pi_flow_run_role_info`.
52
+ if (!roleSeen.has(row.childId)) {
53
+ roleSeen.add(row.childId)
54
+ lines.push(
55
+ `pi_flow_run_role_info{${labelString({ ref, session: row.childId, role: row.role ?? agentRole(null, row.name) })}} 1`,
56
+ )
57
+ }
58
+ // AIDEV-NOTE (PMR-NRH8): model metadata is an additive info family, never
59
+ // new labels on existing metrics. Empty model sets emit no bytes, keeping
60
+ // model-less bodies byte-identical; dedupe also covers per-phase main rows.
61
+ for (const model of row.models) {
62
+ const key = JSON.stringify([row.childId, model])
63
+ if (modelSeen.has(key)) continue
64
+ modelSeen.add(key)
65
+ lines.push(
66
+ `pi_flow_run_model_info{${labelString({ ref, session: row.childId, model })}} 1`,
67
+ )
68
+ }
69
+ let phase = ''
70
+ if (row.phase !== null) phase = row.phase
71
+ let subtask = ''
72
+ if (row.subtask !== null) subtask = row.subtask
73
+ lines.push(
74
+ `pi_flow_run_cost_usd{${labelString({ ref, phase, agent: row.name, subtask, session: row.childId })}} ${row.summary.totals.cost}`,
75
+ )
76
+ lines.push(
77
+ `pi_flow_tokens_total{${labelString({ ref, phase, agent: row.name, kind: 'input', session: row.childId })}} ${row.summary.totals.input}`,
78
+ )
79
+ lines.push(
80
+ `pi_flow_tokens_total{${labelString({ ref, phase, agent: row.name, kind: 'output', session: row.childId })}} ${row.summary.totals.output}`,
81
+ )
82
+ lines.push(
83
+ `pi_flow_tokens_total{${labelString({ ref, phase, agent: row.name, kind: 'cacheRead', session: row.childId })}} ${row.summary.totals.cacheRead}`,
84
+ )
85
+ lines.push(
86
+ `pi_flow_tokens_total{${labelString({ ref, phase, agent: row.name, kind: 'cacheWrite', session: row.childId })}} ${row.summary.totals.cacheWrite}`,
87
+ )
88
+ for (const call of row.toolCalls) {
89
+ lines.push(
90
+ `pi_flow_tool_calls_total{${labelString({
91
+ ref,
92
+ phase,
93
+ agent: row.name,
94
+ tool: call.tool,
95
+ status: call.status,
96
+ session: row.childId,
97
+ })}} ${call.count}`,
98
+ )
99
+ }
100
+ }
101
+ for (const duration of durations) {
102
+ lines.push(
103
+ `pi_flow_run_duration_seconds{${labelString({ ref, phase: duration.phase })}} ${duration.seconds}`,
104
+ )
105
+ }
106
+ if (events !== undefined) {
107
+ for (const line of renderRunHealthLines(ref, events)) {
108
+ lines.push(line)
109
+ }
110
+ }
111
+ return `${lines.join('\n')}\n`
112
+ }