@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,33 @@
1
+ import type { FlowRunState } from '../run-state.ts'
2
+ import { realPidAlive } from '../server/lifecycle.ts'
3
+ import { readRunsFromDisk } from './gates.ts'
4
+
5
+ export type PidAlive = (pid: number) => boolean
6
+
7
+ // AIDEV-NOTE: PMR-5563 — daemon idle gate. The scan in hasActiveFlowRun is
8
+ // repo-agnostic BY DESIGN: the flow daemon is ONE global process serving
9
+ // every repo's runs under runsDir(agentDir), so ANY live run on disk makes
10
+ // it busy. A run is busy only when its loop is 'running' AND its owner pid
11
+ // is still alive; no-owner and dead-owner runs are idle — restarts must
12
+ // never be blocked by crashed sessions or ancient journals (parked runs
13
+ // count as busy: awaitingOutcome + status 'running', see isParkedLoop in
14
+ // server/pending.ts). realPidAlive is shared with server/lifecycle.ts so
15
+ // there is exactly one liveness probe implementation (flow→server import
16
+ // precedent: flow/durable-refs.ts).
17
+ export function runIsBusy(run: FlowRunState, pidAlive: PidAlive): boolean {
18
+ if (run.loop === undefined) return false
19
+ if (run.loop.status !== 'running') return false
20
+ if (run.owner === undefined) return false
21
+ return pidAlive(run.owner.pid)
22
+ }
23
+
24
+ export async function hasActiveFlowRun(
25
+ agentDir: string,
26
+ pidAlive: PidAlive = realPidAlive,
27
+ ): Promise<boolean> {
28
+ const runs = await readRunsFromDisk(agentDir)
29
+ for (const run of runs) {
30
+ if (runIsBusy(run, pidAlive)) return true
31
+ }
32
+ return false
33
+ }
@@ -0,0 +1,559 @@
1
+ // AIDEV-NOTE: PMR-ZV9Y 3.1 — the pure v2 journal→Prometheus derivation behind
2
+ // the six gauge families of the plan's vocabulary table: pi_flow_state,
3
+ // pi_flow_state_start_seconds, pi_flow_phase, pi_flow_wait_seconds,
4
+ // pi_flow_step, pi_flow_step_seconds.
5
+ //
6
+ // AIDEV-NOTE: PMR-2EGV — pi_flow_phase is RETIRED on done/stale runs:
7
+ // renderStateMetricLines suppresses the phase line when the derived state is
8
+ // 'done' or 'stale' (isPhaseRetiredState), because a finished run has no
9
+ // current phase. Halted is the deliberate exception — a halted run is still IN
10
+ // its phase and may resume, so the phase line is kept there (unlike the P3a
11
+ // open-step suppression, which treats halted as terminal). See the P3a
12
+ // AIDEV-NOTE block below for the shared render-guard rationale.
13
+ //
14
+ // NODE-ONLY, DAEMON-REACHABLE, PURE. Closure is deliberately narrower than
15
+ // cost-rows.ts's allowlist: '../run-state.ts' (types + `projectRunState`),
16
+ // './vocabulary.ts', './cost-rows.ts' (`labelString`) — nothing else, no node
17
+ // builtin needed. Subtask 3.2 adds this file to the textual guard in
18
+ // test/cost-rows-node-only.test.ts. No I/O and no `Date.now()`: identical
19
+ // events render byte-identical lines, which is what the Pushgateway group body
20
+ // depends on (flow/push.ts). The cycle this creates once 3.2 wires it in
21
+ // (cost-rows → run-health → state-metrics → cost-rows) is ESM-safe for the
22
+ // same reason the cost-rows ↔ run-health seam is: since the PMR-45VS split
23
+ // `labelString` is DECLARED in './cost-rows-push.ts' and re-exported through
24
+ // the './cost-rows.ts' facade, and every side of the seam exports hoisted
25
+ // function declarations consumed at CALL time — never call
26
+ // `labelString` from a module initializer here.
27
+ //
28
+ // THE DERIVATION CONTRACT (pinned by test/state-metrics.test.ts):
29
+ // 1. Current state: the projected `FlowRunState.currentState` wins. It IS the
30
+ // last valid 'state-change' (applyEvent enforces the closed enums), so a
31
+ // drifted enum can never become a label value — ISC-A-1 holds by
32
+ // construction, not by re-checking here.
33
+ // 2. Legacy fallback (ISC-6): with no 'state-change' events, v2 state comes
34
+ // from the projected v1 loop status — paused→waiting_human, halted→halted,
35
+ // running→running, done→done — always with reason '' ("old runs render,
36
+ // just without reason granularity"). `LoopRunStatus` is untouched
37
+ // (ISC-A-2). The state's start is the last 'loop-state' event's `at`,
38
+ // because LoopStateRecord carries no timestamp of its own.
39
+ // 3. No projection (no run-start) and no loop snapshot → null → NO lines,
40
+ // mirroring renderRunHealthLines for the same journal: both blocks in one
41
+ // push body must describe the same run.
42
+ // 4. Wait windows walk the RAW events (a dropped projection write must never
43
+ // lose window math). A window opens at a transition whose (state, reason)
44
+ // pair differs from the open window's and closes at the next transition;
45
+ // identical repeats do NOT restart the clock, a reason change DOES
46
+ // re-open (the seconds then land in the new reason's bucket, which is the
47
+ // point of the per-reason gauge). Open windows contribute nothing,
48
+ // re-opened waits sum, arithmetic stays unfloored — the same posture as the
49
+ // retired v1 scanPausedWindows in run-health.ts. Only waiting_human /
50
+ // waiting_machine accumulate; running / halted / done / stale never count
51
+ // as a wait.
52
+ // 5. A journal with no 'state-change' events falls back to the paused-window
53
+ // scan re-implemented here (wait_kind 'human', reason '') rather than
54
+ // importing run-health.ts: that import is not on this subtask's allowlist
55
+ // and would deepen the cycle above. The arithmetic mirrored run-health.ts's
56
+ // scanPausedWindows exactly, so ISC-6 values agreed with the frozen
57
+ // pi_flow_human_wait_seconds aggregate. AIDEV-NOTE (PMR-ZV9Y 7.1): that
58
+ // aggregate and its scan are RETIRED, which makes this mirror the sole
59
+ // implementation of the paused-window arithmetic — the values it produces
60
+ // are unchanged, they simply no longer have a v1 twin to match. A v2 journal
61
+ // never runs the legacy scan — the two would double-count the same pause.
62
+ //
63
+ // AIDEV-NOTE: THE TYPE-LINE RULE — never add `# TYPE` / `# HELP` lines here,
64
+ // even though that looks like the "correct" exposition format. No source in
65
+ // this package emits them; the gateway auto-detects and stores every family
66
+ // here as UNTYPED (the `# TYPE pi_flow_run_status untyped` strings in the
67
+ // test/push.ts and test/reconcile.ts fixtures are copied from a LIVE dump). So
68
+ // bare lines ARE the repo convention, not an omission. Emitting
69
+ // `# TYPE pi_flow_state gauge` would flip that family to gauge on the first
70
+ // push while `filterGroupLines` (flow/push.ts) strips every `#` line from the
71
+ // body `tombstoneBody` re-POSTs (flow/reconcile.ts) — typed first push plus
72
+ // untyped re-POST is the whole-group 400 documented in the push.ts header
73
+ // (PMR-WBC2: "… is not a GAUGE", which once made every tombstone re-POST
74
+ // fail). It would break reconcile for every ref carrying v2 lines, starting
75
+ // with the pi_flow_state series the cutover alert reads.
76
+ //
77
+ // AIDEV-NOTE: CARDINALITY POSTURE (ISC-A-1). state / reason / wait_kind are
78
+ // closed-enum by construction (projection-validated; wait_kind through
79
+ // reasonWaitKind). phase comes from the projection or the PHASE_VALUES guard
80
+ // below. `step` is the only label read straight off a journal event, and it is
81
+ // CHARSET-GUARDED (STEP_NAME_RE) rather than registry-checked. That is a
82
+ // DELIBERATE allowlist choice, not a reachability limit: flow/steps.ts is in
83
+ // fact daemon-safe (its only import is `import type { Phase }`, erased at
84
+ // runtime, so the transitive closure walk in test/cost-rows-node-only.test.ts
85
+ // would accept it), but a VALUE import of it would trip the per-root DIRECT
86
+ // textual allowlist `ROOT_ALLOWLISTS['flow/state-metrics.ts']` in that same
87
+ // guard, which locked for 3.1/3.2 lists only run-state / cost-rows /
88
+ // vocabulary. We keep the closure narrower than strictly necessary because
89
+ // registry membership is ALREADY enforced at the emit boundary (subtask 1.2
90
+ // binds the prompt letters to STEP_REGISTRY and flow_submit warns on
91
+ // unregistered names); the charset guard here exists only to keep free text —
92
+ // a halt note pasted by a future writer — out of a label value (ISC-A-1).
93
+ // AIDEV-NOTE (PMR-ZV9Y fix round, P3b): an earlier revision of this note
94
+ // claimed importing steps.ts "would violate the node-only allowlist" as if it
95
+ // were unreachable. That was imprecise — it is reachable; it is simply not on
96
+ // the deliberately narrow direct allowlist, and adding it would force an edit
97
+ // to the frozen closure guard for a check the emit boundary already performs.
98
+ // AIDEV-NOTE (PMR-ZV9Y fix-round-3, deviation #3): that P3b posture is now
99
+ // SUPERSEDED — the closure guard is widened and state-metrics.ts DOES
100
+ // value-import isRegisteredStep from './steps.ts' (the widening is safe exactly
101
+ // as P3b described it: steps.ts is pure data, its lone './orchestrate.ts' edge
102
+ // is type-only and erased at runtime, so the transitive closure walk never
103
+ // loads orchestrate.ts; flow/steps.ts is registered as its own guard root).
104
+ // The `step` label is therefore now REGISTRY-CLOSED at the render boundary
105
+ // (scanStepWindows rejects any step isRegisteredStep(phase, step) is false for,
106
+ // for BOTH pi_flow_step and pi_flow_step_seconds), which is the spec's
107
+ // "Registered names only" rule (plan.md:37) and the real bounded-cardinality
108
+ // guarantee ISC-A-1 wanted. STEP_NAME_RE is kept as a cheap pre-filter that
109
+ // rejects structurally-broken values (spaces, over-length) before the registry
110
+ // lookup — NOT as the cardinality control any more. The journal + Loki line
111
+ // still carry unregistered / free-form step names (implement + feedback
112
+ // registries are empty by design); only the Prometheus LABEL surface is
113
+ // registry-closed. The paragraph above (charset-only rationale) is retained as
114
+ // history per G-1 — it is no longer the implemented contract.
115
+
116
+ import type { FlowPhase, FlowRunEvent } from '../run-state.ts'
117
+ import { projectRunState } from '../run-state.ts'
118
+ import { labelString } from './cost-rows.ts'
119
+ import { isRegisteredStep } from './steps.ts'
120
+ import type { FlowReason, FlowState, WaitKind } from './vocabulary.ts'
121
+ import { FLOW_REASONS, FLOW_STATES, reasonWaitKind } from './vocabulary.ts'
122
+
123
+ /** A v2 state with the journal timestamp it began at. */
124
+ export interface V2State {
125
+ state: FlowState
126
+ reason: FlowReason | ''
127
+ at: string
128
+ }
129
+
130
+ /** One in-flight (phase, step) pair. */
131
+ export interface OpenStep {
132
+ phase: FlowPhase
133
+ step: string
134
+ }
135
+
136
+ export interface StateWindowScan {
137
+ /**
138
+ * Cumulative wait seconds per (wait_kind, reason), keyed
139
+ * `"<wait_kind>\u0000<reason>"` (the run-health composite-key convention,
140
+ * so no separator can collide with an enum value). Insertion order is
141
+ * first-contribution order, which is what the render path needs for a
142
+ * byte-stable body. Buckets with no measurable seconds never appear.
143
+ */
144
+ seconds: Map<string, number>
145
+ }
146
+
147
+ export interface StepWindowScan {
148
+ /**
149
+ * Cumulative COMPLETED seconds per (phase, step), keyed
150
+ * `"<phase>\u0000<step>"`, first-contribution order.
151
+ */
152
+ seconds: Map<string, number>
153
+ /** Steps with an unmatched step-start, in first-start order. */
154
+ open: OpenStep[]
155
+ }
156
+
157
+ /**
158
+ * The phase vocabulary, mirrored from `FlowPhase` in run-state.ts (that
159
+ * module keeps its own `PHASES` list private, and importing a constant from
160
+ * flow/orchestrate.ts would drag the session-side graph into this daemon
161
+ * closure). test/state-metrics.test.ts pins the guard by rejecting a journal
162
+ * whose step event carries an out-of-vocabulary phase.
163
+ */
164
+ const PHASE_VALUES: readonly FlowPhase[] = [
165
+ 'plan',
166
+ 'implement',
167
+ 'validate',
168
+ 'feedback',
169
+ ]
170
+
171
+ /**
172
+ * Structural pre-filter for a journaled step name. This is NO LONGER the
173
+ * cardinality control on its own — the registry IS (see below). It rejects
174
+ * structurally-broken values (spaces, over-length) cheaply BEFORE the
175
+ * `isRegisteredStep` lookup in scanStepWindows, so a pasted free-text halt note
176
+ * never even reaches a registry call. The registry gate is the authority now
177
+ * (PMR-ZV9Y fix-round-3, deviation #3): this module value-imports
178
+ * `isRegisteredStep` from './steps.ts' and scanStepWindows drops any
179
+ * (phase, step) the registry does not list, for BOTH pi_flow_step and
180
+ * pi_flow_step_seconds. The earlier "enforced at the emit boundary only, so
181
+ * this module does not consult the registry" posture is RETIRED — the charset
182
+ * alone let a well-formed-but-unregistered name (validate.bogus) become a label
183
+ * value, which is exactly the unbounded-cardinality leak ISC-A-1 forbids.
184
+ * './steps.ts' is now on the per-root direct allowlist
185
+ * `ROOT_ALLOWLISTS['flow/state-metrics.ts']` in test/cost-rows-node-only.test.ts
186
+ * and flow/steps.ts is registered as its own guard root; the widening is safe
187
+ * because steps.ts is pure data (a const map + a predicate, no I/O, no pi
188
+ * runtime) whose lone './orchestrate.ts' edge is type-only and erased at
189
+ * runtime. The charset mirrors flow_submit's own validation (FLOW_VALUE_RE:
190
+ * alphanumeric plus `. _ -`, ≤64 chars) and the registry's `<phase>.<name>`
191
+ * naming, so a free-text value can never become a label value — ISC-A-1.
192
+ * AIDEV-NOTE (PMR-ZV9Y fix round, P3b): corrected from the earlier "would
193
+ * violate the node-only allowlist" wording, which overstated a reachability
194
+ * limit that is really a narrow, deliberate allowlist choice. (Superseded by
195
+ * fix-round-3: the choice is gone — the allowlist is widened deliberately.)
196
+ */
197
+ const STEP_NAME_RE = /^[a-z]+\.[A-Za-z0-9._-]{1,63}$/
198
+
199
+ /** Mirror of run-health.ts's epochSeconds: unparseable or absent → undefined. */
200
+ function epochSeconds(at: string): number | undefined {
201
+ if (typeof at !== 'string') return undefined
202
+ const seconds = Math.floor(Date.parse(at) / 1000)
203
+ if (!Number.isFinite(seconds)) return undefined
204
+ return seconds
205
+ }
206
+
207
+ /**
208
+ * Positive finite span between two journal timestamps, in seconds. `undefined`
209
+ * covers every unusable case (non-string, unparseable, zero, negative — the
210
+ * last two mean the journal is out of order, which must never fabricate a
211
+ * negative gauge). Same unfloored millisecond math as the retired v1
212
+ * scanPausedWindows.
213
+ */
214
+ function spanSeconds(fromAt: string, toAt: string): number | undefined {
215
+ if (typeof fromAt !== 'string' || typeof toAt !== 'string') return undefined
216
+ const seconds = (Date.parse(toAt) - Date.parse(fromAt)) / 1000
217
+ if (!Number.isFinite(seconds) || seconds <= 0) return undefined
218
+ return seconds
219
+ }
220
+
221
+ /** The valid 'state-change' events, in journal order. */
222
+ function stateTransitions(
223
+ events: readonly FlowRunEvent[],
224
+ ): Array<{ state: FlowState; reason: FlowReason | ''; at: string }> {
225
+ const out: Array<{ state: FlowState; reason: FlowReason | ''; at: string }> =
226
+ []
227
+ for (const event of events) {
228
+ if (event.kind !== 'state-change') continue
229
+ // Same vocabulary rules as applyEvent (run-state.ts): out-of-vocabulary
230
+ // transitions are evidence in the journal but never a label value.
231
+ if (!FLOW_STATES.includes(event.state)) continue
232
+ const reason = event.reason === undefined ? '' : event.reason
233
+ if (typeof reason !== 'string') continue
234
+ if (reason !== '' && !FLOW_REASONS.includes(reason as FlowReason)) continue
235
+ if (typeof event.at !== 'string') continue
236
+ out.push({
237
+ state: event.state,
238
+ reason: reason as FlowReason | '',
239
+ at: event.at,
240
+ })
241
+ }
242
+ return out
243
+ }
244
+
245
+ /**
246
+ * The current v2 state: the projection when the journal has v2 events, else
247
+ * the legacy loop-status mapping (ISC-6). Pure.
248
+ */
249
+ export function deriveV2State(events: readonly FlowRunEvent[]): V2State | null {
250
+ const projected = projectRunState(events)
251
+ if (projected === null) return null
252
+ const current = projected.currentState
253
+ if (current !== undefined) {
254
+ return { state: current.state, reason: current.reason, at: current.at }
255
+ }
256
+ const loop = projected.loop
257
+ if (loop === undefined) return null
258
+ // LoopStateRecord has no timestamp, so the state's start comes from the
259
+ // raw event that produced the projected record (the last loop-state).
260
+ let at = ''
261
+ for (const event of events) {
262
+ if (event.kind !== 'loop-state') continue
263
+ if (typeof event.at !== 'string') continue
264
+ at = event.at
265
+ }
266
+ let state: FlowState = 'done'
267
+ if (loop.status === 'paused') state = 'waiting_human'
268
+ else if (loop.status === 'halted') state = 'halted'
269
+ else if (loop.status === 'running') state = 'running'
270
+ return { state, reason: '', at }
271
+ }
272
+
273
+ /** The wait kind for a window: the reason's kind, else the state's. */
274
+ function waitKind(state: FlowState, reason: FlowReason | ''): WaitKind {
275
+ if (reason !== '') return reasonWaitKind(reason)
276
+ if (state === 'waiting_human') return 'human'
277
+ return 'machine'
278
+ }
279
+
280
+ function addWait(
281
+ seconds: Map<string, number>,
282
+ window: { state: FlowState; reason: FlowReason | ''; at: string },
283
+ span: number | undefined,
284
+ ): void {
285
+ if (span === undefined) return
286
+ if (window.state !== 'waiting_human' && window.state !== 'waiting_machine') {
287
+ return
288
+ }
289
+ const kind = waitKind(window.state, window.reason)
290
+ const key = `${kind}\u0000${window.reason}`
291
+ seconds.set(key, (seconds.get(key) ?? 0) + span)
292
+ }
293
+
294
+ /**
295
+ * Legacy paused-window scan, mirroring run-health.ts's RETIRED
296
+ * scanPausedWindows (PMR-ZV9Y 7.1 — this is now the only implementation of
297
+ * that arithmetic):
298
+ * a window opens at the first paused loop-state snapshot and closes at the
299
+ * next event that is NOT a paused loop-state (consecutive paused snapshots do
300
+ * not restart the clock); an unclosed window contributes nothing. Returns the
301
+ * v2 bucket so the render path stays a single code path.
302
+ */
303
+ function legacyWaitSeconds(
304
+ events: readonly FlowRunEvent[],
305
+ ): Map<string, number> {
306
+ const seconds = new Map<string, number>()
307
+ let openAt: string | null = null
308
+ let total = 0
309
+ for (const event of events) {
310
+ let isPausedSnapshot = false
311
+ if (event.kind === 'loop-state' && event.loop.status === 'paused') {
312
+ isPausedSnapshot = true
313
+ }
314
+ if (openAt === null) {
315
+ if (isPausedSnapshot) openAt = event.at
316
+ continue
317
+ }
318
+ if (isPausedSnapshot) continue
319
+ const span = spanSeconds(openAt, event.at)
320
+ if (span !== undefined) total += span
321
+ openAt = null
322
+ }
323
+ if (total > 0) seconds.set('human\u0000', total)
324
+ return seconds
325
+ }
326
+
327
+ /**
328
+ * Cumulative v2 wait seconds per (wait_kind, reason) — the arithmetic behind
329
+ * `pi_flow_wait_seconds`. Reads the RAW event list, so a re-opened wait opens
330
+ * a new window (plan PMR-ZV9Y, "Duplicate state-change events"). A journal
331
+ * with no v2 'state-change' events falls back to the paused-window scan.
332
+ * Pure; open windows contribute nothing.
333
+ */
334
+ export function scanStateWindows(
335
+ events: readonly FlowRunEvent[],
336
+ ): StateWindowScan {
337
+ const transitions = stateTransitions(events)
338
+ if (transitions.length === 0) {
339
+ return { seconds: legacyWaitSeconds(events) }
340
+ }
341
+ const seconds = new Map<string, number>()
342
+ let open: { state: FlowState; reason: FlowReason | ''; at: string } | null =
343
+ null
344
+ for (const transition of transitions) {
345
+ if (open === null) {
346
+ open = transition
347
+ continue
348
+ }
349
+ if (transition.state === open.state && transition.reason === open.reason) {
350
+ continue
351
+ }
352
+ addWait(seconds, open, spanSeconds(open.at, transition.at))
353
+ open = transition
354
+ }
355
+ // `open` is deliberately left unclosed at the end of the journal: the run
356
+ // is still in that state, and pi_flow_state_start_seconds carries its age.
357
+ return { seconds }
358
+ }
359
+
360
+ /**
361
+ * v2 step windows: cumulative completed seconds per (phase, step) plus the
362
+ * in-flight steps behind `pi_flow_step` / `pi_flow_step_seconds`.
363
+ *
364
+ * AIDEV-NOTE: pairing is per (phase, step) with LAST-START-WINS. A duplicate
365
+ * step-start with no stop in between is the process-restart / re-ask path
366
+ * (the loop re-journals 'step-start' when it re-enters the gate), and the
367
+ * journaled stop is evidence of the work that JUST finished — measuring from
368
+ * the first start would inflate the step duration with the dead time of the
369
+ * abandoned attempt. A step-stop with no open start is ignored (a journal
370
+ * whose head was truncated, or a stop recorded after a restart). An unclosed
371
+ * step contributes no seconds but stays in `open`.
372
+ */
373
+ export function scanStepWindows(
374
+ events: readonly FlowRunEvent[],
375
+ ): StepWindowScan {
376
+ const seconds = new Map<string, number>()
377
+ const startedAt = new Map<string, string>()
378
+ const order: string[] = []
379
+ const labels = new Map<string, OpenStep>()
380
+ for (const event of events) {
381
+ if (event.kind !== 'step-start' && event.kind !== 'step-stop') continue
382
+ if (!PHASE_VALUES.includes(event.phase)) continue
383
+ if (typeof event.step !== 'string') continue
384
+ if (!STEP_NAME_RE.test(event.step)) continue
385
+ // AIDEV-NOTE: PMR-ZV9Y fix-round-3 (deviation #3) — the registry is now
386
+ // the label-surface authority (plan.md:37 "Registered names only"). A
387
+ // charset-valid but UNREGISTERED name is ignored for BOTH gauges, which
388
+ // also empties implement/feedback (free-form flow_submit names by design).
389
+ // The journal + Loki line still carry them — only the Prometheus label
390
+ // surface is registry-closed (bounded cardinality, ISC-A-1). Keeping
391
+ // STEP_NAME_RE above is still load-bearing: it rejects structurally-broken
392
+ // values (spaces, >64 chars) cheaply before the registry lookup, and
393
+ // isRegisteredStep would otherwise index a free-text halt note.
394
+ if (!isRegisteredStep(event.phase, event.step)) continue
395
+ if (typeof event.at !== 'string') continue
396
+ const key = `${event.phase}\u0000${event.step}`
397
+ if (event.kind === 'step-start') {
398
+ startedAt.set(key, event.at)
399
+ labels.set(key, { phase: event.phase, step: event.step })
400
+ if (!order.includes(key)) order.push(key)
401
+ continue
402
+ }
403
+ const start = startedAt.get(key)
404
+ if (start === undefined) continue
405
+ startedAt.delete(key)
406
+ const span = spanSeconds(start, event.at)
407
+ if (span === undefined) continue
408
+ seconds.set(key, (seconds.get(key) ?? 0) + span)
409
+ }
410
+ const open: OpenStep[] = []
411
+ for (const key of order) {
412
+ if (!startedAt.has(key)) continue
413
+ const label = labels.get(key)
414
+ if (label === undefined) continue
415
+ open.push(label)
416
+ }
417
+ return { seconds, open }
418
+ }
419
+
420
+ /**
421
+ * AIDEV-NOTE: PMR-ZV9Y fix round (P3a) — the terminal derived states that carry
422
+ * NO live in-flight step: halted / done / stale. When `deriveV2State` yields
423
+ * one of these, `renderStateMetricLines` suppresses the open-step `pi_flow_step`
424
+ * lines (an unclosed step-start on a finished run is a phantom, see the render
425
+ * path). `running`, `waiting_human` and `waiting_machine` are NOT terminal: a
426
+ * genuinely open step there is real live state. A `null` derived state (no
427
+ * projection) is treated as non-terminal here because the whole render already
428
+ * returns no state lines in that case (contract 3), and the open-step loop
429
+ * simply has nothing else to gate against.
430
+ */
431
+ function isTerminalState(current: V2State | null): boolean {
432
+ if (current === null) return false
433
+ if (current.state === 'halted') return true
434
+ if (current.state === 'done') return true
435
+ return current.state === 'stale'
436
+ }
437
+
438
+ /**
439
+ * AIDEV-NOTE: PMR-2EGV — states that retire the phase gauge. `done`/`stale`
440
+ * only: a halted run is still IN its phase and may resume (human decision),
441
+ * unlike isTerminalState, which also retires the open-step gauge on halted.
442
+ * A `null` derived state is non-terminal for the same reason as
443
+ * isTerminalState: the whole render already returns no state lines then
444
+ * (contract 3), and there is no phase decision left to gate.
445
+ */
446
+ export function isPhaseRetiredState(current: V2State | null): boolean {
447
+ if (current === null) return false
448
+ if (current.state === 'done') return true
449
+ return current.state === 'stale'
450
+ }
451
+
452
+ /** The current phase: the loop snapshot wins, else the projected current phase. */
453
+ function currentPhaseLabel(events: readonly FlowRunEvent[]): FlowPhase | null {
454
+ const projected = projectRunState(events)
455
+ if (projected === null) return null
456
+ if (projected.loop !== undefined) return projected.loop.phase
457
+ if (projected.currentPhase !== undefined) return projected.currentPhase
458
+ return null
459
+ }
460
+
461
+ /**
462
+ * Render the six v2 gauge families for one ref (plan PMR-ZV9Y's vocabulary
463
+ * table, in that order): pi_flow_state, pi_flow_state_start_seconds,
464
+ * pi_flow_phase, pi_flow_wait_seconds, pi_flow_step, pi_flow_step_seconds.
465
+ *
466
+ * AIDEV-NOTE: bare sample lines only — no `# TYPE` / `# HELP`, for the
467
+ * tombstone round-trip reason recorded in the module header above (and the
468
+ * same posture as the frozen run-health.ts block).
469
+ *
470
+ * No `mode` label: the Pushgateway group URL carries it (v1 convention).
471
+ * Every value on this Prometheus label surface comes from a closed enum or,
472
+ * for the step label of pi_flow_step / pi_flow_step_seconds, the registry gate
473
+ * (isRegisteredStep), so a free-text halt note can never reach a Prometheus
474
+ * label (ISC-A-1). This closure is scoped to the metric LABELS only — the
475
+ * journal events and the Tempo step spans / Loki lines built from them still
476
+ * carry the raw step name by design (see the module header and flow/steps.ts).
477
+ * First-seen order everywhere; a bucket with nothing measured emits no line
478
+ * (never an invented zero — the cost body takes the same posture for coverage
479
+ * gaps).
480
+ */
481
+ export function renderStateMetricLines(
482
+ ref: string,
483
+ events: readonly FlowRunEvent[],
484
+ ): string[] {
485
+ const lines: string[] = []
486
+ const current = deriveV2State(events)
487
+ if (current !== null) {
488
+ const labels = labelString({
489
+ ref,
490
+ state: current.state,
491
+ reason: current.reason,
492
+ })
493
+ lines.push(`pi_flow_state{${labels}} 1`)
494
+ const start = epochSeconds(current.at)
495
+ if (start !== undefined) {
496
+ lines.push(`pi_flow_state_start_seconds{${labels}} ${start}`)
497
+ }
498
+ }
499
+ const phase = currentPhaseLabel(events)
500
+ // AIDEV-NOTE: PMR-2EGV — the phase gauge is retired on done/stale (a
501
+ // finished run has no current phase); halted keeps it (still IN the phase,
502
+ // may resume). Same guard shape as the P3a step suppression below.
503
+ if (phase !== null && !isPhaseRetiredState(current)) {
504
+ lines.push(`pi_flow_phase{${labelString({ ref, phase })}} 1`)
505
+ }
506
+ for (const [key, value] of scanStateWindows(events).seconds) {
507
+ const separator = key.indexOf('\u0000')
508
+ lines.push(
509
+ `pi_flow_wait_seconds{${labelString({
510
+ ref,
511
+ wait_kind: key.slice(0, separator),
512
+ reason: key.slice(separator + 1),
513
+ })}} ${value}`,
514
+ )
515
+ }
516
+ const steps = scanStepWindows(events)
517
+ // AIDEV-NOTE: PMR-ZV9Y fix round (P3a) — an open step is LIVE in-flight
518
+ // evidence. Once the derived state is halted / done / stale the run has no
519
+ // work in flight, so an unmatched step-start (a code-review ask aborted by
520
+ // Escape, a deviation verdict that kept re-running until the halt, a
521
+ // spec-approval pause on a since-closed ticket) would otherwise render
522
+ // `pi_flow_step{…} 1` forever — the gateway merges on write (push.ts), so the
523
+ // line persists in the stored body and surfaces on the piflow-runs
524
+ // "Live state" row for a dead run. Suppress the open-step lines whenever the
525
+ // derived state is halted/done/stale; running and both waiting states keep
526
+ // them, because there a genuinely open step is real. The COMPLETED
527
+ // `pi_flow_step_seconds` buckets stay — they are cumulative durations, not
528
+ // in-flight evidence. This is the render-side half; the tombstone-side
529
+ // decision is recorded in flow/reconcile.ts `tombstoneBody`.
530
+ //
531
+ // AIDEV-NOTE: PMR-2EGV — the same retired-run logic now gates the
532
+ // pi_flow_phase line above: a done/stale run has no current phase, so the
533
+ // phase gauge is suppressed there (isPhaseRetiredState). The halted
534
+ // exception differs from the step rule: halted KEEPS the phase line because
535
+ // a halted run is still IN its phase and may resume, whereas the open-step
536
+ // line is retired on halted (a halted run has no live in-flight step).
537
+ if (!isTerminalState(current)) {
538
+ for (const openStep of steps.open) {
539
+ lines.push(
540
+ `pi_flow_step{${labelString({
541
+ ref,
542
+ phase: openStep.phase,
543
+ step: openStep.step,
544
+ })}} 1`,
545
+ )
546
+ }
547
+ }
548
+ for (const [key, value] of steps.seconds) {
549
+ const separator = key.indexOf('\u0000')
550
+ lines.push(
551
+ `pi_flow_step_seconds{${labelString({
552
+ ref,
553
+ phase: key.slice(0, separator),
554
+ step: key.slice(separator + 1),
555
+ })}} ${value}`,
556
+ )
557
+ }
558
+ return lines
559
+ }