@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,140 @@
1
+ // AIDEV-NOTE: opt-in content capture for telemetry spans. OFF by default —
2
+ // spans are metadata-only unless the user sets telemetry.captureContent.
3
+ // Levels are CUMULATIVE:
4
+ // off metadata only (default)
5
+ // text + assistant text on gen spans (gen_ai.completion)
6
+ // tools + tool calls the model made on gen spans (gen_ai.tool_calls),
7
+ // tool input/output on tool spans (tool.input / tool.output)
8
+ // all + the model's reasoning (gen_ai.reasoning)
9
+ // Captured content CAN contain secrets, code and personal data — it lands in
10
+ // the trace backend. Every value is truncated to maxContentChars (Tempo drops
11
+ // anything past max_attribute_bytes, default 2048, silently — see README).
12
+ // No redaction is attempted: the level is the control.
13
+ import type { SpanAttributes } from './attributes.ts'
14
+
15
+ export type ContentLevel = 'off' | 'text' | 'tools' | 'all'
16
+
17
+ export const CONTENT_LEVELS: readonly ContentLevel[] = [
18
+ 'off',
19
+ 'text',
20
+ 'tools',
21
+ 'all',
22
+ ]
23
+
24
+ /** Default per-attribute cap; stays under Tempo's default 2048-byte limit. */
25
+ export const DEFAULT_MAX_CONTENT_CHARS = 2000
26
+
27
+ const RANK: Record<ContentLevel, number> = {
28
+ off: 0,
29
+ text: 1,
30
+ tools: 2,
31
+ all: 3,
32
+ }
33
+
34
+ /** True when `level` captures at least `need`. */
35
+ export function levelIncludes(
36
+ level: ContentLevel,
37
+ need: ContentLevel,
38
+ ): boolean {
39
+ return RANK[level] >= RANK[need]
40
+ }
41
+
42
+ export function truncate(text: string, max: number): string {
43
+ if (text.length <= max) return text
44
+ const dropped = text.length - max
45
+ return `${text.slice(0, max)}…[truncated ${dropped} chars]`
46
+ }
47
+
48
+ function safeJson(value: unknown): string {
49
+ try {
50
+ const out = JSON.stringify(value)
51
+ if (out === undefined) return ''
52
+ return out
53
+ } catch {
54
+ return '[unserializable]'
55
+ }
56
+ }
57
+
58
+ export interface AssistantContent {
59
+ text: string
60
+ reasoning: string
61
+ toolCalls: Array<{ name: string; arguments: unknown }>
62
+ }
63
+
64
+ /** Pull text / thinking / tool calls out of an assistant message (defensive, no any). */
65
+ export function extractAssistantContent(message: unknown): AssistantContent {
66
+ const out: AssistantContent = { text: '', reasoning: '', toolCalls: [] }
67
+ if (message == null || typeof message !== 'object') return out
68
+ const content = (message as Record<string, unknown>).content
69
+ if (typeof content === 'string') {
70
+ out.text = content
71
+ return out
72
+ }
73
+ if (!Array.isArray(content)) return out
74
+ const texts: string[] = []
75
+ const thoughts: string[] = []
76
+ for (const part of content) {
77
+ if (part == null || typeof part !== 'object') continue
78
+ const p = part as Record<string, unknown>
79
+ if (p.type === 'text' && typeof p.text === 'string') texts.push(p.text)
80
+ if (
81
+ p.type === 'thinking' &&
82
+ typeof p.thinking === 'string' &&
83
+ p.redacted !== true
84
+ ) {
85
+ thoughts.push(p.thinking)
86
+ }
87
+ if (p.type === 'toolCall' && typeof p.name === 'string') {
88
+ out.toolCalls.push({ name: p.name, arguments: p.arguments })
89
+ }
90
+ }
91
+ out.text = texts.join('\n')
92
+ out.reasoning = thoughts.join('\n')
93
+ return out
94
+ }
95
+
96
+ /** Attributes to add to a gen span for the configured level. */
97
+ export function generationContentAttributes(
98
+ level: ContentLevel,
99
+ max: number,
100
+ message: unknown,
101
+ ): SpanAttributes {
102
+ const attrs: SpanAttributes = {}
103
+ if (level === 'off') return attrs
104
+ const content = extractAssistantContent(message)
105
+ if (content.text.length > 0) {
106
+ attrs['gen_ai.completion'] = truncate(content.text, max)
107
+ }
108
+ if (levelIncludes(level, 'tools') && content.toolCalls.length > 0) {
109
+ attrs['gen_ai.tool_calls'] = truncate(safeJson(content.toolCalls), max)
110
+ }
111
+ if (levelIncludes(level, 'all') && content.reasoning.length > 0) {
112
+ attrs['gen_ai.reasoning'] = truncate(content.reasoning, max)
113
+ }
114
+ return attrs
115
+ }
116
+
117
+ /** Tool input as text (level tools+); '' when empty. */
118
+ export function toolInputText(args: unknown, max: number): string {
119
+ if (args === undefined || args === null) return ''
120
+ return truncate(safeJson(args), max)
121
+ }
122
+
123
+ /** Tool result as text (level tools+): joined text parts, else JSON. */
124
+ export function toolOutputText(result: unknown, max: number): string {
125
+ if (result === undefined || result === null) return ''
126
+ if (typeof result === 'string') return truncate(result, max)
127
+ if (typeof result === 'object') {
128
+ const content = (result as Record<string, unknown>).content
129
+ if (Array.isArray(content)) {
130
+ const texts: string[] = []
131
+ for (const part of content) {
132
+ if (part == null || typeof part !== 'object') continue
133
+ const p = part as Record<string, unknown>
134
+ if (p.type === 'text' && typeof p.text === 'string') texts.push(p.text)
135
+ }
136
+ if (texts.length > 0) return truncate(texts.join('\n'), max)
137
+ }
138
+ }
139
+ return truncate(safeJson(result), max)
140
+ }
@@ -0,0 +1,521 @@
1
+ // AIDEV-NOTE: PMR-ZV9Y 4.3 — THE writer fan-out dispatcher (renderer #2's
2
+ // router of the plan's three-renderer architecture: Prometheus folds the
3
+ // journal in the push chain, THIS module re-renders each event live to Loki +
4
+ // the Tempo step spans, and since 5.2 pi-desktop-notify shares the same bag —
5
+ // see createNotifySink below).
6
+ //
7
+ // ══ SEAM MAP: where v2 events are journaled, and why ONE wrap point covers
8
+ // them all. Every v2 emission site routes through the mode-aware EventWriter
9
+ // (server/writer.ts) — nobody writes a journal line by hand except the two
10
+ // audited fallbacks below — so `createEventFanoutWriter` wraps THAT object at
11
+ // its single construction site (index.ts, session writer) and each event then
12
+ // passes exactly ONE dispatcher. No double Loki push, no missed seam:
13
+ //
14
+ // 1. flow/v2-emission.ts `emitV2` (state-change + step boundaries)
15
+ // -> deps.journal / deps.journalV2 -> index.ts journalSerial
16
+ // -> journal() -> writer.record [COVERED: wrapped]
17
+ // 2. tools/code-review.ts openReviewGate/closeReviewGate
18
+ // -> journalV2 -> writer.record [COVERED: wrapped]
19
+ // 3. tools/deviation.ts step pair + rerun state-change
20
+ // -> journalV2 -> journalGateEvent(event, writer)
21
+ // -> writer.record [COVERED: wrapped]
22
+ // 4. tools/run-attempt.ts escalation state-change
23
+ // -> deps.journalV2 -> index.ts writer.record [COVERED: wrapped]
24
+ // 5. tools/run-attempt.ts ATTEMPT LEDGER fallback (the scout §3 exception):
25
+ // createAttemptLedger(agentDir, {}) WITHOUT deps.record writes
26
+ // `attempt-record` straight through recordRunEvent, BYPASSING this
27
+ // wrapper. AUDITED 2026-11-25 and deliberately NOT routed: that kind is
28
+ // not a v2 event (nothing for Loki/Tempo to render), and index.ts
29
+ // always injects the record seam -> the writer. The v2 state-change of
30
+ // the same escalation rides seam 4, so nothing v2 is lost. Pinned by
31
+ // test/telemetry-dispatch.test.ts.
32
+ // 6. tools/flow-submit.ts direct recordRunEvent fallback (same shape):
33
+ // writes `step-output`, not a v2 kind, and index.ts always passes the
34
+ // writer. Not routed, same reason.
35
+ // 7. index.ts's own consumers of the same object — journalOnly (the /flow
36
+ // answer appendJournal, nested spawn-record), the receipt journals
37
+ // (code_review / phase_complete / spec_approve / land) and
38
+ // reviewExtension(pi, writer) — all hold the WRAPPED writer, so no
39
+ // second dispatcher is ever built for them.
40
+ // 8. server/daemon.ts (liveness/reconcile/tombstone writes): never wrapped.
41
+ // The daemon has no live event stream and pushes no Loki (see the
42
+ // telemetry.loki AIDEV-NOTE in config.ts) — wrapping it there is a bug,
43
+ // not a feature. Pinned by test/telemetry-dispatch.test.ts.
44
+ //
45
+ // ══ NEVER-THROW (ISC-A-5). `record` awaits the wrapped writer FIRST and
46
+ // forwards its outcome unchanged (best-effort false stays false, so
47
+ // flow_submit's journaled:false contract survives), then routes inside
48
+ // per-handler try/catch. Each sink is guarded separately: a throwing Loki
49
+ // settings getter never also costs the Tempo step span, and vice versa. Loki
50
+ // disabled / telemetry off = zero network calls, zero allocations beyond the
51
+ // identity map. Non-v2 kinds cost one kind check.
52
+ //
53
+ // ══ NO RE-VALIDATION. Whatever the writer recorded is routed; the closed
54
+ // label builder (telemetry/loki.ts buildLokiStream) is the label guard and the
55
+ // free text (note prose, deviation reasons, the step name) rides the JSON
56
+ // line only — never a label (ISC-A-1).
57
+ // PMR-ZV9Y 5.2: `recoveryCommand` is the single source of the `/flow <ref>`
58
+ // hint (flow/binding-heal.ts) — reusing it keeps the notify body and the
59
+ // session's recovery lines in lockstep. No cycle: binding-heal never imports
60
+ // telemetry/.
61
+ import { recoveryCommand } from '../flow/binding-heal.ts'
62
+ import {
63
+ expectedAction,
64
+ type FlowState,
65
+ NO_EXPECTED_ACTION,
66
+ reasonWaitKind,
67
+ } from '../flow/vocabulary.ts'
68
+ import type { FlowRunEvent } from '../run-state.ts'
69
+ import { runTracking } from '../run-state.ts'
70
+ import type { EventWriter } from '../server/writer.ts'
71
+ import {
72
+ type LokiFetch,
73
+ type LokiLabels,
74
+ type LokiNoteState,
75
+ type LokiSettings,
76
+ pushLokiEvent,
77
+ } from './loki.ts'
78
+
79
+ type StateChangeEvent = Extract<FlowRunEvent, { kind: 'state-change' }>
80
+ type StepStartEvent = Extract<FlowRunEvent, { kind: 'step-start' }>
81
+ type StepStopEvent = Extract<FlowRunEvent, { kind: 'step-stop' }>
82
+ /** The v2 step-boundary union (both kinds carry phase + step). */
83
+ export type StepBoundaryEvent = StepStartEvent | StepStopEvent
84
+
85
+ /**
86
+ * The fan-out sinks. All optional and individually guarded; `onEvent` runs
87
+ * first for EVERY journaled event (the identity tracker needs the run-start
88
+ * lines that never reach the v2 sinks).
89
+ */
90
+ export interface FanoutHandlers {
91
+ onEvent?: (event: FlowRunEvent) => void
92
+ onStateChange?: (event: StateChangeEvent) => void
93
+ onStepEvent?: (event: StepBoundaryEvent) => void
94
+ /**
95
+ * AIDEV-NOTE: PMR-ZV9Y fix round (P1 blocker) + fix-round-2 (P2a) — a
96
+ * SEPARATELY guarded observer that fires for EVERY journaled `state-change`
97
+ * event, regardless of which seam emitted it. index.ts wires it to the flow
98
+ * loop's `noteExternalV2State(ref, state, event.at)` so the loop's guarded v2
99
+ * emission is invalidated by TOOL-journaled waits (run-attempt escalate,
100
+ * deviation rerun) that the loop does not emit through its own seam. The full
101
+ * event is passed (not just ref/state) so the loop can keep the guard
102
+ * MONOTONIC on `event.at`: tool v2 writes bypass `journalSerial`, so a late
103
+ * loop `running` echo can route after a tool's `waiting_human`, and without a
104
+ * recency guard that echo would revert the guard to a stale state (the original
105
+ * P1 symptom in a narrow window). `onStateChange` is NOT
106
+ * reused for that: it is the telemetry/Loki+notify sink and a throwing notify
107
+ * would then also cost the loop bookkeeping (ISC-A-5). This observer runs in
108
+ * its OWN try/catch BEFORE onStateChange, so neither can cost the other and
109
+ * the loop learns the wait even when Loki/notify are off. The dispatcher is
110
+ * the single choke point (see the seam map above); hooking here needs zero
111
+ * journal re-reads and never re-validates the label (ISC-A-1 — the loop
112
+ * re-validates against FLOW_STATES itself). Pinned by
113
+ * test/loop-state-change.test.ts (the real-fan-out observer tests) and
114
+ * test/telemetry-dispatch.test.ts.
115
+ */
116
+ onV2StateChangeObserved?: (event: StateChangeEvent) => void
117
+ }
118
+
119
+ /** The Pushgateway identity pair a Loki stream is keyed by. */
120
+ export interface FanoutIdentity {
121
+ trackRef: string
122
+ mode: 'work' | 'personal'
123
+ }
124
+
125
+ /**
126
+ * Wrap the mode-aware writer so every recorded event keeps its original
127
+ * best-effort semantics AND routes to the v2 sinks (see the seam map above).
128
+ * Both writer methods dispatch: `record` (main process / daemon absent) and
129
+ * `recordJournalOnly` (nested worker + daemon-owned writes) — one dispatcher,
130
+ * whichever seam an event entered through.
131
+ */
132
+ export function createEventFanoutWriter(
133
+ writer: EventWriter,
134
+ handlers: FanoutHandlers,
135
+ ): EventWriter {
136
+ const route = (event: FlowRunEvent): void => {
137
+ // The observer is guarded separately from the kind sinks so a throwing
138
+ // identity capture can never also cost a Loki push.
139
+ if (handlers.onEvent !== undefined) {
140
+ try {
141
+ handlers.onEvent(event)
142
+ } catch {
143
+ // never-throw (ISC-A-5)
144
+ }
145
+ }
146
+ if (event.kind === 'state-change') {
147
+ // The loop-bookkeeping observer runs FIRST and in its OWN try/catch so a
148
+ // throwing telemetry sink never costs it (PMR-ZV9Y fix round, P1).
149
+ if (handlers.onV2StateChangeObserved !== undefined) {
150
+ try {
151
+ handlers.onV2StateChangeObserved(event)
152
+ } catch {
153
+ // never-throw (ISC-A-5)
154
+ }
155
+ }
156
+ if (handlers.onStateChange === undefined) return
157
+ try {
158
+ handlers.onStateChange(event)
159
+ } catch {
160
+ // never-throw (ISC-A-5)
161
+ }
162
+ return
163
+ }
164
+ if (event.kind === 'step-start' || event.kind === 'step-stop') {
165
+ if (handlers.onStepEvent === undefined) return
166
+ try {
167
+ handlers.onStepEvent(event)
168
+ } catch {
169
+ // never-throw (ISC-A-5)
170
+ }
171
+ }
172
+ }
173
+ return {
174
+ record: async (event) => {
175
+ // The writer first, and its outcome forwarded verbatim: the fan-out is
176
+ // a renderer, never a new durability contract.
177
+ const journaled = await writer.record(event)
178
+ route(event)
179
+ return journaled
180
+ },
181
+ recordJournalOnly: async (event) => {
182
+ // Forward durability just like record(): answer-time receipt stamping
183
+ // relies on false to warn instead of claiming a successful head-pin.
184
+ const journaled = await writer.recordJournalOnly(event)
185
+ route(event)
186
+ return journaled
187
+ },
188
+ }
189
+ }
190
+
191
+ /**
192
+ * Map the resolved `telemetry.loki` config block onto the pusher's settings:
193
+ * disabled or an empty endpoint is `null`, which `pushLokiEvent` treats as
194
+ * ZERO fetch calls (the same no-op posture as the OTLP path).
195
+ */
196
+ export function lokiPushSettings(settings: {
197
+ enabled: boolean
198
+ endpoint: string
199
+ headers?: Record<string, string>
200
+ }): LokiSettings | null {
201
+ if (!settings.enabled) return null
202
+ if (settings.endpoint.length === 0) return null
203
+ return { endpoint: settings.endpoint, headers: settings.headers ?? {} }
204
+ }
205
+
206
+ /**
207
+ * The closed Loki label set for one v2 event (telemetry/loki.ts owns the key
208
+ * list; this only fills it). `flow_ref`/`mode` come from the run identity,
209
+ * never from free text; `wait_kind` derives through reasonWaitKind so a drifted
210
+ * reason can never fabricate a "waiting on you" label. Step events carry
211
+ * `phase`; the step NAME is not a label (ISC-A-1) — it rides the JSON line.
212
+ */
213
+ export function buildEventLokiLabels(
214
+ event: StateChangeEvent | StepBoundaryEvent,
215
+ identity: FanoutIdentity,
216
+ ): LokiLabels {
217
+ const labels: LokiLabels = {
218
+ flow_ref: identity.trackRef,
219
+ mode: identity.mode,
220
+ kind: event.kind,
221
+ }
222
+ if (event.kind === 'state-change') {
223
+ labels.state = event.state
224
+ const reason = event.reason
225
+ if (reason !== undefined && reason !== '') {
226
+ labels.reason = reason
227
+ labels.wait_kind = reasonWaitKind(reason)
228
+ }
229
+ return labels
230
+ }
231
+ labels.phase = event.phase
232
+ return labels
233
+ }
234
+
235
+ /** The step-span slice of the telemetry handle (TelemetryHandle satisfies it). */
236
+ export interface StepSpanHandle {
237
+ stepStart: (phase: string, step: string) => void
238
+ stepStop: (phase: string, step: string) => void
239
+ }
240
+
241
+ export interface TelemetryHandlerDeps {
242
+ /** Resolved Loki push settings; null = disabled = zero network calls. */
243
+ loki: () => LokiSettings | null
244
+ /** Late-bound Tempo handle; null = telemetry off / not registered yet.
245
+ * NOT re-gated here: the 4.1 handle returns early while telemetry is
246
+ * disabled and its stepStart/stepStop carry the `isWorker()` guard, so a
247
+ * worker session journalling a step boundary still reaches Loki but never
248
+ * exports a duplicate step span (verified 2026-11-25). */
249
+ handle: () => StepSpanHandle | null
250
+ fetchImpl: LokiFetch
251
+ now: () => number
252
+ /** Failure note; at most one call per handler instance (shared guard). */
253
+ onNote: (ref: string, error: string) => void
254
+ /** Process env, read lazily for the resume case (PI_FLOW_TRACK_REF/MODE). */
255
+ env: Record<string, string | undefined>
256
+ timeoutMs?: number
257
+ /**
258
+ * AIDEV-NOTE: PMR-ZV9Y 5.2 — the desktop-notify sink, COMPOSED into
259
+ * `onStateChange` beside the Loki push. Absent = no notify path at all
260
+ * (the telemetry-only wiring stays silent). Each sink runs in its OWN
261
+ * try/catch: a throwing notify never costs the Loki push and vice versa
262
+ * (ISC-A-5), and the sinks are independent switches (D3) — `notify.desktop
263
+ * = false` still pushes Loki, `telemetry.loki = false` still pages.
264
+ */
265
+ notify?: NotifySinkDeps
266
+ }
267
+
268
+ /**
269
+ * Build the session's fan-out sinks: Loki for state-change + step boundaries,
270
+ * Tempo step spans for step boundaries. ONE instance per session, so its
271
+ * `LokiNoteState` once-guard and its run-identity map are exactly what the
272
+ * 4.2 pusher expects (process-level, never per event).
273
+ *
274
+ * IDENTITY: runTracking is the single source for a run's trackRef + mode
275
+ * (PMR-MSDJ 1.2), but the fan-out only ever sees ONE event at a time. So it
276
+ * watches the `run-start` lines passing the seam (the same source runTracking
277
+ * folds, last-wins) and falls back to the stamped attribution env for a run
278
+ * whose start happened in an earlier process, and finally to
279
+ * {aven ref, personal} — exactly runTracking's no-run-start semantics.
280
+ */
281
+ export function createTelemetryHandlers(
282
+ deps: TelemetryHandlerDeps,
283
+ ): FanoutHandlers {
284
+ const noteState: LokiNoteState = { noted: false }
285
+ const identities = new Map<string, FanoutIdentity>()
286
+ // PMR-ZV9Y 5.2: null = no notify channel wired (telemetry-only sessions).
287
+ let notifySink: NotifySink | null = null
288
+ if (deps.notify !== undefined) notifySink = createNotifySink(deps.notify)
289
+
290
+ const identityFor = (ref: string): FanoutIdentity => {
291
+ const observed = identities.get(ref)
292
+ if (observed !== undefined) return observed
293
+ const envMode = deps.env.PI_FLOW_MODE
294
+ const envTrack = deps.env.PI_FLOW_TRACK_REF
295
+ if (deps.env.PI_FLOW_REF === ref && envMode === 'work') {
296
+ let trackRef = ref
297
+ if (envTrack !== undefined && envTrack.length > 0) trackRef = envTrack
298
+ return { trackRef, mode: 'work' }
299
+ }
300
+ return runTracking([], ref)
301
+ }
302
+
303
+ const pushToLoki = (event: StateChangeEvent | StepBoundaryEvent): void => {
304
+ // The settings getter and the label/line build are the only throwing
305
+ // parts here — pushLokiEvent is no-throw by contract (4.2) and callers
306
+ // guard this function anyway.
307
+ const settings = deps.loki()
308
+ if (settings === null) return
309
+ const labels = buildEventLokiLabels(event, identityFor(event.ref))
310
+ pushLokiEvent(settings, labels, JSON.stringify(event), {
311
+ fetchImpl: deps.fetchImpl,
312
+ now: deps.now,
313
+ state: noteState,
314
+ onNote: (error) => {
315
+ deps.onNote(event.ref, error)
316
+ },
317
+ timeoutMs: deps.timeoutMs,
318
+ })
319
+ }
320
+
321
+ return {
322
+ onEvent: (event) => {
323
+ if (event.kind !== 'run-start') return
324
+ // Last run-start wins, the same rule runTracking pins (test/
325
+ // run-state-tracking.test.ts): a /flow rerun in work mode must not keep
326
+ // pushing personal-labelled Loki lines.
327
+ identities.set(event.ref, runTracking([event], event.ref))
328
+ },
329
+ onStateChange: (event) => {
330
+ // Two independently guarded sinks (4.3 Loki, 5.2 notify): a throwing
331
+ // notify never costs the Loki push and vice versa.
332
+ try {
333
+ pushToLoki(event)
334
+ } catch {
335
+ // never-throw (ISC-A-5)
336
+ }
337
+ if (notifySink === null) return
338
+ try {
339
+ notifySink(event)
340
+ } catch {
341
+ // never-throw (ISC-A-5): the sink is fire-and-forget by construction
342
+ // (createNotifySink catches inside its own async body), so this guard
343
+ // only covers a throwing gate.
344
+ }
345
+ },
346
+ onStepEvent: (event) => {
347
+ try {
348
+ pushToLoki(event)
349
+ } catch {
350
+ // never-throw (ISC-A-5)
351
+ }
352
+ const handle = deps.handle()
353
+ if (handle === null) return
354
+ try {
355
+ if (event.kind === 'step-start') {
356
+ handle.stepStart(event.phase, event.step)
357
+ return
358
+ }
359
+ handle.stepStop(event.phase, event.step)
360
+ } catch {
361
+ // never-throw (ISC-A-5)
362
+ }
363
+ },
364
+ }
365
+ }
366
+
367
+ // ══ DESKTOP NOTIFY SINK (PMR-ZV9Y 5.2) ═══════════════════════════════════
368
+ // AIDEV-NOTE: PMR-ZV9Y 5.2 — the second human-facing renderer of the v2 state
369
+ // machine: the live session's paging channel. It is a SIBLING of the Loki push
370
+ // inside `createTelemetryHandlers().onStateChange`, and each sink is guarded
371
+ // SEPARATELY — a throwing notify never costs the Loki line, and vice versa
372
+ // (ISC-A-5). @gtheys/rifle-batteries (the desktop-notify carrier since
373
+ // PMR-8YDK 5.2) is an OPTIONAL dependency: the ONLY reference to it in this
374
+ // file is `typeof import(...)` (type-only, erased at emit) plus the dynamic
375
+ // `import()` in loadNotifyModule below. NEVER add a static import of
376
+ // '@gtheys/rifle-batteries/notify' here — test/notify-hook.test.ts pins that,
377
+ // and a static edge would make an absent package a load-time crash instead of
378
+ // a degraded channel.
379
+ //
380
+ // FIRE RULE (exactly two states, `shouldNotifyState`): `waiting_human` (a
381
+ // human unblocks it) and `halted` (a human must). `waiting_machine` is Grafana/
382
+ // Loki material, never a page; `running`/`done`/`stale` silent. Gate ORDER is
383
+ // state → config → import, so a disabled or non-paging event never touches the
384
+ // module system.
385
+ //
386
+ // DEDUPE (decided, pinned by test/notify-hook.test.ts): ONE notification per
387
+ // state-change EVENT — no per-(ref, state, reason) once-guard. 2.1's guarded
388
+ // emission already suppresses same-state repeats inside a process, so a repeat
389
+ // only happens when a gate genuinely re-asks (waiting_human → running →
390
+ // waiting_human), which earns a second page. Cross-process re-asks (a resumed
391
+ // run, a second session) re-notify too: accepted, because the notification
392
+ // mirrors the journal and the journal is the audit record.
393
+ //
394
+ // MESSAGE FORMAT (pinned; keep it short + grep-able — a notification is an
395
+ // interruption, the journal is the detail):
396
+ // summary `pi-flow <ref>: <state>`
397
+ // body waiting_human → `<expectedAction> — reason: <reason>`
398
+ // e.g. `answer the code_review ask (pass/fail in this session) — reason: code_review_pending`
399
+ // halted → `reason: <reason> — recover with /flow <ref>`
400
+ // no registered action/reason → `recover with /flow <ref>`
401
+ // The action half comes from `expectedAction` (flow/vocabulary.ts is the single
402
+ // source; the Waiting-on-me board mirrors the same strings), so the command an
403
+ // operator types is exactly what the board already advertises. Free text (halt
404
+ // prose) never enters the body — the closed reason enum only (ISC-A-1).
405
+ //
406
+ // FAILURE POSTURE: at most ONE `onNote` per sink instance (the sink is built
407
+ // once per session, like the Loki note guard), then the channel is OFF for the
408
+ // rest of the session — never a retry storm, never a rejected promise into the
409
+ // host, never a throw into the flow loop.
410
+
411
+ /** The `@gtheys/rifle-batteries/notify` surface (PMR-ZV9Y 5.1, carried by the
412
+ * merged rifle-batteries package since PMR-8YDK 5.2), referenced TYPE-ONLY so
413
+ * an uninstalled optional dependency never breaks this module at RUNTIME (the
414
+ * type reference erases; only `loadNotifyModule` below touches the package,
415
+ * dynamically, inside a try/catch). Caveat: a consumer that runs `tsc` over
416
+ * pi-flow's SOURCES needs the optional package present to resolve the type —
417
+ * pi's loader does not typecheck, so an installed-without-batteries setup
418
+ * still runs, it just degrades the channel on the first paging event. */
419
+ export type DesktopNotifyModule =
420
+ typeof import('@gtheys/rifle-batteries/notify')
421
+
422
+ /** The production dynamic-import seam. Rejects when the package is absent or
423
+ * broken; `createNotifySink` turns that into one warn line + channel off. */
424
+ function loadNotifyModule(): Promise<DesktopNotifyModule> {
425
+ return import('@gtheys/rifle-batteries/notify')
426
+ }
427
+
428
+ export interface NotifySinkDeps {
429
+ /** Late-bound `notify.desktop.enabled` (default TRUE — an opt-out channel).
430
+ * Checked BEFORE the import, so a disabled channel loads nothing. */
431
+ desktop: () => boolean
432
+ /** Session cwd: the desktop-notify module (rifle-batteries) loads ITS OWN
433
+ * channel config (desktop /
434
+ * herdr / ntfy toggles) with it, so the user's per-repo notify settings win
435
+ * and pi-flow only decides whether a flow event pages at all. */
436
+ cwd: () => string
437
+ /** Dynamic-import seam (tests inject a fake; default = the 5.1 subpath). */
438
+ loadModule?: () => Promise<DesktopNotifyModule>
439
+ /** ONE call per sink instance on the first channel failure. */
440
+ onNote: (ref: string, error: string) => void
441
+ }
442
+
443
+ /** The v2 states that page a human (everything else stays board-only). */
444
+ export function shouldNotifyState(state: FlowState): boolean {
445
+ if (state === 'waiting_human') return true
446
+ return state === 'halted'
447
+ }
448
+
449
+ /** Notification title: ref + state, the shortest grep-able identity. */
450
+ export function notifySummary(event: StateChangeEvent): string {
451
+ return `pi-flow ${event.ref}: ${event.state}`
452
+ }
453
+
454
+ /** Notification body: the command that unblocks the run, then the closed
455
+ * reason. See the MESSAGE FORMAT note above. */
456
+ export function notifyBody(event: StateChangeEvent): string {
457
+ const reason = event.reason
458
+ const action = expectedAction(event.state, reason ?? '', event.ref)
459
+ const parts: string[] = []
460
+ if (action !== NO_EXPECTED_ACTION) parts.push(action)
461
+ if (reason !== undefined && reason !== '') parts.push(`reason: ${reason}`)
462
+ // A halt registers no unblock command, so the recovery hint carries it; a
463
+ // transition with neither still says what to type.
464
+ if (event.state === 'halted' || parts.length === 0) {
465
+ parts.push(`recover with ${recoveryCommand(event.ref)}`)
466
+ }
467
+ return parts.join(' — ')
468
+ }
469
+
470
+ /** The sink's own handle: call it with every v2 state-change event. */
471
+ export type NotifySink = (event: StateChangeEvent) => void
472
+
473
+ /**
474
+ * Build the session's desktop-notify sink. ONE instance per session (like the
475
+ * handler bag that composes it), so the once-guard and the cached module
476
+ * import are exactly process-scoped.
477
+ */
478
+ export function createNotifySink(deps: NotifySinkDeps): NotifySink {
479
+ const loadModule = deps.loadModule ?? loadNotifyModule
480
+ let loading: Promise<DesktopNotifyModule> | null = null
481
+ let noted = false
482
+ let off = false
483
+
484
+ const noteOnce = (ref: string, error: unknown): void => {
485
+ if (noted) return
486
+ noted = true
487
+ let text = 'unknown notify failure'
488
+ if (error instanceof Error) text = error.message
489
+ deps.onNote(ref, text)
490
+ }
491
+
492
+ return (event) => {
493
+ if (off) return
494
+ // Sync, allocation-free gate first (see the FIRE RULE note).
495
+ if (!shouldNotifyState(event.state)) return
496
+ // Fire-and-forget: the fan-out must never await a desktop notification.
497
+ void (async () => {
498
+ try {
499
+ if (!deps.desktop()) return
500
+ if (loading === null) loading = loadModule()
501
+ // Aliased so the await below keeps the narrowed type (a mutable
502
+ // closure variable loses its narrowing across an await).
503
+ const pending = loading
504
+ const notify = await pending
505
+ const config = await notify.loadConfig(deps.cwd())
506
+ await notify.dispatchNotification(
507
+ config,
508
+ notifySummary(event),
509
+ notifyBody(event),
510
+ )
511
+ } catch (error) {
512
+ // Absent/broken package, a malformed notify config, or a dead channel:
513
+ // ONE line, then the channel stays off for the session. The module
514
+ // import is not retried per event either (`loading` keeps the
515
+ // rejected promise, and `off` stops later calls from reaching it).
516
+ off = true
517
+ noteOnce(event.ref, error)
518
+ }
519
+ })()
520
+ }
521
+ }