@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,776 @@
1
+ // AIDEV-NOTE (PMR-R8AG): telemetry wiring. Hard no-backend rules (part of
2
+ // the test gate): telemetry disabled or unconfigured = the session_start
3
+ // probe subscribes to NOTHING else and allocates nothing; endpoint
4
+ // unreachable = fire-and-forget export that fails silently after at most
5
+ // one journal note per process; tool calls and turns proceed identically
6
+ // whether export succeeds, fails, or no backend exists. Spans are
7
+ // metadata-only (attribute mapping in attributes.ts — no prompt or
8
+ // completion content ever enters a span).
9
+ import { createHash } from 'node:crypto'
10
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
11
+ import { agentRole } from '../flow/agent-role.ts'
12
+ import {
13
+ flowAttributes,
14
+ generationSpanAttributes,
15
+ parseTraceparent,
16
+ randomSpanId,
17
+ randomTraceId,
18
+ type SpanAttributes,
19
+ type TelemetryEnv,
20
+ type TelemetryRng,
21
+ toolSpanAttributes,
22
+ } from './attributes.ts'
23
+ import {
24
+ type ContentLevel,
25
+ DEFAULT_MAX_CONTENT_CHARS,
26
+ generationContentAttributes,
27
+ levelIncludes,
28
+ toolInputText,
29
+ toolOutputText,
30
+ } from './content.ts'
31
+ import {
32
+ exportSpans,
33
+ type TelemetryFetch,
34
+ type TelemetrySpan,
35
+ } from './exporter.ts'
36
+
37
+ /** Resolved telemetry settings; null = disabled (subscribe to nothing). */
38
+ export interface TelemetrySettings {
39
+ endpoint: string
40
+ headers: Record<string, string>
41
+ /** Content captured on spans; absent = 'off' (metadata only). */
42
+ captureContent?: ContentLevel
43
+ /** Jira issue base URL (…/browse/); work-mode spans get flow.url = base + ref. */
44
+ jiraBaseUrl?: string
45
+ /** Per-attribute cap for captured content; absent = DEFAULT_MAX_CONTENT_CHARS. */
46
+ maxContentChars?: number
47
+ }
48
+
49
+ export interface TelemetryDeps {
50
+ /** Load settings for the session cwd; null means OFF. */
51
+ loadSettings: (cwd: string) => Promise<TelemetrySettings | null>
52
+ env: TelemetryEnv
53
+ rng: TelemetryRng
54
+ fetchImpl: TelemetryFetch
55
+ now: () => number
56
+ /** Journal-note hook; called at most once per process, on first failure. */
57
+ onExportFailure: (error: string) => void
58
+ }
59
+
60
+ const FLUSH_THRESHOLD = 16
61
+ /**
62
+ * Deterministic phase span id: first 16 hex chars of sha256(traceId:phase).
63
+ * The main process exports the phase span; workers recompute the same id from
64
+ * their own PI_FLOW_TRACEPARENT + PI_FLOW_PHASE to nest under it, so no extra
65
+ * env var has to cross the package boundary.
66
+ */
67
+ export function phaseSpanId(traceId: string, phase: string): string {
68
+ return createHash('sha256')
69
+ .update(`${traceId}:${phase}`)
70
+ .digest('hex')
71
+ .slice(0, 16)
72
+ }
73
+
74
+ /**
75
+ * AIDEV-NOTE: PMR-ZV9Y 4.1 — deterministic step span id: first 16 hex chars
76
+ * of sha256(traceId:phase:step), the same construction and delimiter as
77
+ * phaseSpanId. A step span's id is therefore re-derivable from the trace plus
78
+ * the journal's (phase, step) pair, so nothing has to carry an id across the
79
+ * process boundary — at the price that a retried step inside the SAME trace
80
+ * cannot get a second span (see the step-span note in registerTelemetry).
81
+ */
82
+ export function stepSpanId(
83
+ traceId: string,
84
+ phase: string,
85
+ step: string,
86
+ ): string {
87
+ return createHash('sha256')
88
+ .update(`${traceId}:${phase}:${step}`)
89
+ .digest('hex')
90
+ .slice(0, 16)
91
+ }
92
+
93
+ /** Idempotency key of a step span within a trace (traceId:phase:step). */
94
+ function stepSpanKey(traceId: string, phase: string, step: string): string {
95
+ return `${traceId}:${phase}:${step}`
96
+ }
97
+
98
+ /**
99
+ * Session span name: "<flow ref> - <role>". The role comes from the agent
100
+ * type when known (scout, worker, reviewer...), else from the agent name up
101
+ * to its first colon (see flow/agent-role.ts); full name, type and phase stay
102
+ * as span attributes.
103
+ */
104
+ export function sessionSpanName(flow: SpanAttributes): string {
105
+ const role = agentRole(flow['agent.type'], flow['agent.name'])
106
+ const ref = flow['flow.ref']
107
+ if (ref === undefined) return role
108
+ return `${ref} - ${role}`
109
+ }
110
+
111
+ /**
112
+ * An open (or already-exported) step span. Kept in the state map after export
113
+ * on purpose: it is the record that makes a duplicate start a no-op, so a
114
+ * deterministic id is never sent twice (Tempo keeps both copies).
115
+ */
116
+ interface OpenStepSpan {
117
+ traceId: string
118
+ phase: string
119
+ step: string
120
+ name: string
121
+ spanId: string
122
+ startNano: string
123
+ attrs: SpanAttributes
124
+ parentId: string | undefined
125
+ /** already sent: never re-sent, only kept as a duplicate-start guard. */
126
+ exported: boolean
127
+ }
128
+
129
+ interface OpenToolSpan {
130
+ spanId: string
131
+ name: string
132
+ startUnixNano: string
133
+ parentSpanId: string | undefined
134
+ attributes: SpanAttributes
135
+ /** captured tool input (level tools+), empty otherwise */
136
+ input: string
137
+ }
138
+
139
+ function toUnixNano(ms: number): string {
140
+ return `${Math.floor(ms * 1_000_000)}`
141
+ }
142
+
143
+ /** Read usage numbers off an assistant message defensively (no any). */
144
+ function readUsage(
145
+ message: unknown,
146
+ ): { input: number; output: number; model: string } | null {
147
+ if (message == null || typeof message !== 'object') return null
148
+ const m = message as Record<string, unknown>
149
+ if (m.role !== 'assistant') return null
150
+ const usage = m.usage
151
+ if (usage == null || typeof usage !== 'object') return null
152
+ const u = usage as Record<string, unknown>
153
+ if (typeof u.input !== 'number' || typeof u.output !== 'number') return null
154
+ let model = 'unknown'
155
+ if (typeof m.model === 'string' && m.model.length > 0) model = m.model
156
+ return { input: u.input, output: u.output, model }
157
+ }
158
+
159
+ export interface TelemetryState {
160
+ enabled: boolean
161
+ settings: TelemetrySettings | null
162
+ traceId: string | null
163
+ rootParentId: string | null
164
+ /** traceId came from PI_FLOW_TRACEPARENT (so a later clear must reset it). */
165
+ fromFlow: boolean
166
+ /** flow trace ids whose root span this (main) process already emitted. */
167
+ rootsEmitted: Set<string>
168
+ /** worker session span (child of the flow root); null outside flow workers. */
169
+ session: { spanId: string } | null
170
+ /** main-process open phase span (exported when the phase closes). */
171
+ phase: {
172
+ traceId: string
173
+ name: string
174
+ spanId: string
175
+ startNano: string
176
+ attrs: SpanAttributes
177
+ /** root span id of ITS trace (rootParentId may already point at a newer trace when it closes). */
178
+ parentId: string | null
179
+ /** already sent: kept as parent for trailing spans, never re-sent. */
180
+ exported: boolean
181
+ } | null
182
+ /**
183
+ * PMR-ZV9Y 4.1 step spans, keyed by stepSpanKey. Entries are never removed —
184
+ * an exported entry is what makes a duplicate stepStart idempotent.
185
+ */
186
+ steps: Map<string, OpenStepSpan>
187
+ /** open ad-hoc (/brainstorm, /pr-quality) run: its own trace + reserved root span id. */
188
+ adhoc: {
189
+ traceId: string
190
+ spanId: string
191
+ startNano: string
192
+ attrs: SpanAttributes
193
+ } | null
194
+ /** root markers of open ad-hoc runs (by run id), kept until the run span closes them. */
195
+ adhocRoots: Map<
196
+ string,
197
+ { traceId: string; spanId: string; startNano: string }
198
+ >
199
+ flow: SpanAttributes
200
+ openTools: Map<string, OpenToolSpan>
201
+ buffer: TelemetrySpan[]
202
+ noted: boolean
203
+ unsubscribers: Array<() => void>
204
+ }
205
+
206
+ /**
207
+ * Register the telemetry extension surface on pi. The session_start probe
208
+ * decides once per session: settings null = zero telemetry subscriptions
209
+ * (the probe itself is the only overhead). session_shutdown unsubscribes
210
+ * and flushes whatever is left.
211
+ */
212
+ export interface TelemetryHandle {
213
+ /**
214
+ * Call after the flow loop stamps/re-stamps/clears the flow env (start,
215
+ * phase change, halt, pause, done, supersede). Closes + flushes a phase
216
+ * that just ended even though no further span ever fires, and flushes the
217
+ * flow root marker immediately. No-op while telemetry is off.
218
+ */
219
+ syncFlowEnv: () => void
220
+ /**
221
+ * Ad-hoc command runs (adhoc/tracker.ts). begin: spans made from now on
222
+ * join a fresh trace under a reserved root span. end: exports that root
223
+ * span ONCE (real start/end + the cost/token attributes) and returns the
224
+ * process to its per-session trace. A run with no matching begin (the
225
+ * /review worker, which ran in another process) exports a standalone span.
226
+ */
227
+ adhocBegin: (run: AdhocTraceInfo, nest: boolean) => void
228
+ adhocEnd: (run: AdhocTraceInfo, attributes: SpanAttributes) => void
229
+ /**
230
+ * PMR-ZV9Y 4.1 — Tempo step spans for the v2 step boundaries. The journal
231
+ * fan-out (telemetry/dispatch.ts, subtask 4.3) calls these from a
232
+ * 'step-start' / 'step-stop' event, which carries BOTH phase and step, so
233
+ * the signature takes them as a pair instead of reading the phase off
234
+ * process.env: the stamped phase can lag a step that closes across a phase
235
+ * transition, and the deterministic id must match the journal's own
236
+ * (phase, step) window. stepStart opens "<ref> - <step>" parented on the
237
+ * current phase span; stepStop closes it. Duplicate starts for the same
238
+ * (phase, step) are ignored, stops without a start are silent no-ops, and a
239
+ * closed span is never re-sent. Absent-safe no-ops while telemetry is off.
240
+ */
241
+ stepStart: (phase: string, step: string) => void
242
+ stepStop: (phase: string, step: string) => void
243
+ }
244
+
245
+ export interface AdhocTraceInfo {
246
+ id: string
247
+ kind: string
248
+ target: string
249
+ startMs: number
250
+ endMs: number
251
+ }
252
+
253
+ export function registerTelemetry(
254
+ pi: ExtensionAPI,
255
+ deps: TelemetryDeps,
256
+ ): TelemetryHandle {
257
+ const state: TelemetryState = {
258
+ enabled: false,
259
+ settings: null,
260
+ traceId: null,
261
+ rootParentId: null,
262
+ fromFlow: false,
263
+ rootsEmitted: new Set(),
264
+ session: null,
265
+ phase: null,
266
+ steps: new Map(),
267
+ adhoc: null,
268
+ adhocRoots: new Map(),
269
+ flow: {},
270
+ openTools: new Map(),
271
+ buffer: [],
272
+ noted: false,
273
+ unsubscribers: [],
274
+ }
275
+
276
+ const flush = (): void => {
277
+ if (state.buffer.length === 0) return
278
+ const spans = state.buffer.splice(0, state.buffer.length)
279
+ const settings = state.settings
280
+ if (settings === null) return
281
+ // fire-and-forget: failures surface at most one note, then drop
282
+ void exportSpans(
283
+ settings.endpoint,
284
+ settings.headers,
285
+ { 'service.name': 'pi-flow' },
286
+ spans,
287
+ deps.fetchImpl,
288
+ ).then((outcome) => {
289
+ if (outcome.ok) return
290
+ if (state.noted) return
291
+ state.noted = true
292
+ deps.onExportFailure(outcome.error ?? 'unknown export failure')
293
+ })
294
+ }
295
+
296
+ const contentLevel = (): ContentLevel =>
297
+ state.settings?.captureContent ?? 'off'
298
+ const toolContentAttributes = (
299
+ input: string,
300
+ result: unknown,
301
+ ): SpanAttributes => {
302
+ const attrs: SpanAttributes = {}
303
+ if (!levelIncludes(contentLevel(), 'tools')) return attrs
304
+ if (input.length > 0) attrs['tool.input'] = input
305
+ const output = toolOutputText(result, contentMax())
306
+ if (output.length > 0) attrs['tool.output'] = output
307
+ return attrs
308
+ }
309
+ const contentMax = (): number =>
310
+ state.settings?.maxContentChars ?? DEFAULT_MAX_CONTENT_CHARS
311
+
312
+ // AIDEV-NOTE: the flow loop reserves the root span id inside
313
+ // PI_FLOW_TRACEPARENT but nothing ever exported that span, so every trace
314
+ // showed "<root span not yet received>" in Grafana. The MAIN process
315
+ // (no PI_SUBAGENT_NAME — workers set it) exports the root once per flow
316
+ // trace, named "flow <ref>". shortcut: it is a zero-length marker emitted
317
+ // when the trace is first seen, not a span covering the whole run — upgrade
318
+ // if per-run duration on the root matters (Tempo derives trace duration
319
+ // from the child spans anyway).
320
+ const emitFlowRoot = (traceId: string, rootSpanId: string): void => {
321
+ if (state.rootsEmitted.has(traceId)) return
322
+ if (isWorker()) return
323
+ state.rootsEmitted.add(traceId)
324
+ const nowNano = toUnixNano(deps.now())
325
+ let name = 'flow'
326
+ const ref = state.flow['flow.ref']
327
+ if (ref !== undefined) name = `flow ${ref}`
328
+ state.buffer.push({
329
+ traceId,
330
+ spanId: rootSpanId,
331
+ name,
332
+ kind: 1,
333
+ startTimeUnixNano: nowNano,
334
+ endTimeUnixNano: nowNano,
335
+ attributes: { ...state.flow, 'flow.span': 'root' },
336
+ statusCode: 0,
337
+ })
338
+ }
339
+
340
+ const isWorker = (): boolean => {
341
+ const name = deps.env.PI_SUBAGENT_NAME
342
+ return name !== undefined && name.length > 0
343
+ }
344
+
345
+ // AIDEV-NOTE: workers get one session span ("<agent> · <phase>") between
346
+ // the flow root and their tool/gen spans, so a trace reads as a tree:
347
+ // flow <ref> -> worker session -> tool/gen. It is exported ONCE, as a
348
+ // zero-length marker, the first time the trace is seen — so a crashed
349
+ // worker's children never hang off a missing parent. shortcut: the span
350
+ // carries no real duration (trace duration comes from the child spans).
351
+ // Re-sending the same span id with a later end does NOT work: Tempo keeps
352
+ // both copies until compaction and which one wins is undefined (verified
353
+ // against the homelab Tempo 2.10), so never update a span in place.
354
+ const parentFor = (): string | undefined => {
355
+ if (state.session !== null) return state.session.spanId
356
+ if (state.phase !== null) return state.phase.spanId
357
+ return state.rootParentId ?? undefined
358
+ }
359
+
360
+ // AIDEV-NOTE: phase spans. The main process exports one span per flow
361
+ // phase ("<ref> - plan"), with its real start/end, and parents its own
362
+ // tool/gen spans on it; workers parent their session span on the same
363
+ // deterministic id (phaseSpanId). Clicking the phase in Grafana shows
364
+ // every call made in that phase. The span is exported when the phase
365
+ // CLOSES: flow_phase_complete finishing (the LAST phase has no successor,
366
+ // so without this its span stayed unsent and review/deviation sessions
367
+ // under it hung off a missing parent), next phase seen, flow cleared, or
368
+ // shutdown — never updated in place (Tempo keeps both copies of a re-sent span id). shortcut: a main
369
+ // process killed mid-phase never exports that phase span, so its children
370
+ // hang off a missing parent; the flow root still names the trace.
371
+ // AIDEV-NOTE: PMR-ZV9Y 4.1 — step spans copy the phase-span lifecycle: real
372
+ // start at stepStart, exported exactly ONCE at close, never updated in
373
+ // place. Close points: stepStop, the phase close (a step still open when its
374
+ // phase ends is that phase's trailing step), syncFlowEnv transitions, and
375
+ // session_shutdown — the last two reach here through ensureTrace/closePhase
376
+ // plus closeOpenSteps on shutdown. Workers NEVER export step spans, the same
377
+ // posture as phase spans: the id is per-trace and deterministic, so a worker
378
+ // copy of a step the main process also journals would be a Tempo duplicate;
379
+ // a worker's own spans already nest under its session span. A retried step
380
+ // inside one trace (e.g. the deviation gate rerun) collapses into the first
381
+ // span — accepted, because a second copy of the id is worse than a missing
382
+ // one. With no phase span open the step parents like every other span does
383
+ // through parentFor (session → phase → root marker), it is never dropped.
384
+ const closeStep = (open: OpenStepSpan): void => {
385
+ if (open.exported) return
386
+ open.exported = true
387
+ state.buffer.push({
388
+ traceId: open.traceId,
389
+ spanId: open.spanId,
390
+ parentSpanId: open.parentId,
391
+ name: open.name,
392
+ kind: 1,
393
+ startTimeUnixNano: open.startNano,
394
+ endTimeUnixNano: toUnixNano(deps.now()),
395
+ attributes: open.attrs,
396
+ statusCode: 0,
397
+ })
398
+ }
399
+
400
+ const closePhaseSteps = (traceId: string, phase: string): void => {
401
+ for (const stepSpan of state.steps.values()) {
402
+ if (stepSpan.exported) continue
403
+ if (stepSpan.traceId !== traceId) continue
404
+ if (stepSpan.phase !== phase) continue
405
+ closeStep(stepSpan)
406
+ }
407
+ }
408
+
409
+ const closeOpenSteps = (): void => {
410
+ for (const stepSpan of state.steps.values()) closeStep(stepSpan)
411
+ }
412
+
413
+ const closePhase = (): void => {
414
+ const open = state.phase
415
+ if (open === null || open.exported) return
416
+ closePhaseSteps(open.traceId, open.attrs.phase)
417
+ open.exported = true
418
+ state.buffer.push({
419
+ traceId: open.traceId,
420
+ spanId: open.spanId,
421
+ parentSpanId: open.parentId ?? undefined,
422
+ name: open.name,
423
+ kind: 1,
424
+ startTimeUnixNano: open.startNano,
425
+ endTimeUnixNano: toUnixNano(deps.now()),
426
+ attributes: open.attrs,
427
+ statusCode: 0,
428
+ })
429
+ }
430
+
431
+ const syncPhase = (traceId: string | null): void => {
432
+ if (isWorker()) return
433
+ const phase = state.flow.phase
434
+ const open = state.phase
435
+ if (open !== null) {
436
+ if (traceId === open.traceId && phase === open.attrs.phase) return
437
+ closePhase()
438
+ state.phase = null
439
+ }
440
+ if (traceId === null || phase === undefined) return
441
+ let name = phase
442
+ const ref = state.flow['flow.ref']
443
+ if (ref !== undefined) name = `${ref} - ${phase}`
444
+ state.phase = {
445
+ traceId,
446
+ name,
447
+ spanId: phaseSpanId(traceId, phase),
448
+ startNano: toUnixNano(deps.now()),
449
+ attrs: { ...state.flow, 'flow.span': 'phase' },
450
+ parentId: state.rootParentId,
451
+ exported: false,
452
+ }
453
+ }
454
+
455
+ // AIDEV-NOTE: the flow loop stamps PI_FLOW_REF / PHASE / TRACEPARENT into
456
+ // process.env at run START, which is after session_start in the main
457
+ // session. Re-read the env on every span so late stamps (and phase
458
+ // changes, and clears at terminal transitions) are honoured; a one-shot
459
+ // read at subscribe time left main-session spans without flow.ref.
460
+ const ensureTrace = (): void => {
461
+ state.flow = flowAttributes(deps.env)
462
+ const base = state.settings?.jiraBaseUrl
463
+ const trackRef = state.flow['flow.ref']
464
+ if (
465
+ base !== undefined &&
466
+ base.length > 0 &&
467
+ state.flow['flow.mode'] === 'work' &&
468
+ trackRef !== undefined
469
+ ) {
470
+ state.flow['flow.url'] = `${base}${trackRef}`
471
+ }
472
+ const ctx = parseTraceparent(deps.env.PI_FLOW_TRACEPARENT)
473
+ if (ctx !== null) {
474
+ state.traceId = ctx.traceId
475
+ state.rootParentId = ctx.parentId
476
+ state.fromFlow = true
477
+ emitFlowRoot(ctx.traceId, ctx.parentId)
478
+ syncPhase(ctx.traceId)
479
+ if (isWorker() && state.session === null) {
480
+ const spanId = randomSpanId(deps.rng)
481
+ const nowNano = toUnixNano(deps.now())
482
+ state.session = { spanId }
483
+ const name = sessionSpanName(state.flow)
484
+ let sessionParent = ctx.parentId
485
+ const workerPhase = state.flow.phase
486
+ if (workerPhase !== undefined) {
487
+ sessionParent = phaseSpanId(ctx.traceId, workerPhase)
488
+ }
489
+ state.buffer.push({
490
+ traceId: ctx.traceId,
491
+ spanId,
492
+ parentSpanId: sessionParent,
493
+ name,
494
+ kind: 1,
495
+ startTimeUnixNano: nowNano,
496
+ endTimeUnixNano: nowNano,
497
+ attributes: { ...state.flow, 'flow.span': 'session' },
498
+ statusCode: 0,
499
+ })
500
+ }
501
+ return
502
+ }
503
+ syncPhase(null)
504
+ if (state.adhoc !== null) {
505
+ Object.assign(state.flow, state.adhoc.attrs)
506
+ state.traceId = state.adhoc.traceId
507
+ state.rootParentId = state.adhoc.spanId
508
+ state.fromFlow = false
509
+ return
510
+ }
511
+ if (state.traceId !== null && !state.fromFlow) return
512
+ // no flow traceparent (never stamped, or cleared): own random trace
513
+ state.traceId = randomTraceId(deps.rng)
514
+ state.rootParentId = null
515
+ state.fromFlow = false
516
+ }
517
+
518
+ const subscribe = (settings: TelemetrySettings): void => {
519
+ state.enabled = true
520
+ state.settings = settings
521
+ ensureTrace()
522
+ state.unsubscribers.push(
523
+ pi.on('tool_execution_start', (event) => {
524
+ if (!state.enabled) return
525
+ ensureTrace()
526
+ let input = ''
527
+ if (levelIncludes(contentLevel(), 'tools')) {
528
+ input = toolInputText(event.args, contentMax())
529
+ }
530
+ state.openTools.set(event.toolCallId, {
531
+ spanId: randomSpanId(deps.rng),
532
+ name: `tool ${event.toolName}`,
533
+ startUnixNano: toUnixNano(deps.now()),
534
+ parentSpanId: parentFor(),
535
+ attributes: toolSpanAttributes(state.flow, {
536
+ toolName: event.toolName,
537
+ isError: false,
538
+ }),
539
+ input,
540
+ })
541
+ }),
542
+ )
543
+ state.unsubscribers.push(
544
+ pi.on('tool_execution_end', (event) => {
545
+ if (!state.enabled) return
546
+ const open = state.openTools.get(event.toolCallId)
547
+ if (open === undefined) return
548
+ ensureTrace()
549
+ state.openTools.delete(event.toolCallId)
550
+ let statusCode = 1
551
+ let statusMessage: string | undefined
552
+ if (event.isError) statusCode = 2
553
+ if (event.isError) statusMessage = `${event.toolName} failed`
554
+ const span: TelemetrySpan = {
555
+ traceId: state.traceId ?? randomTraceId(deps.rng),
556
+ spanId: open.spanId,
557
+ parentSpanId: open.parentSpanId,
558
+ name: open.name,
559
+ kind: 1,
560
+ startTimeUnixNano: open.startUnixNano,
561
+ endTimeUnixNano: toUnixNano(deps.now()),
562
+ attributes: {
563
+ ...toolSpanAttributes(state.flow, {
564
+ toolName: event.toolName,
565
+ isError: event.isError,
566
+ }),
567
+ ...toolContentAttributes(open.input, event.result),
568
+ },
569
+ statusCode,
570
+ ...(statusMessage !== undefined ? { statusMessage } : {}),
571
+ }
572
+ state.buffer.push(span)
573
+ if (event.toolName === 'flow_phase_complete' && !event.isError) {
574
+ // flush NOW: the main session may sit idle (or end) after the last
575
+ // phase, and the buffer only auto-flushes at FLUSH_THRESHOLD spans
576
+ closePhase()
577
+ flush()
578
+ }
579
+ if (state.buffer.length >= FLUSH_THRESHOLD) flush()
580
+ }),
581
+ )
582
+ state.unsubscribers.push(
583
+ pi.on('turn_end', (event) => {
584
+ if (!state.enabled) return
585
+ const usage = readUsage(event.message)
586
+ if (usage === null) return
587
+ ensureTrace()
588
+ const endMs = deps.now()
589
+ state.buffer.push({
590
+ traceId: state.traceId ?? randomTraceId(deps.rng),
591
+ spanId: randomSpanId(deps.rng),
592
+ parentSpanId: parentFor(),
593
+ name: `gen ${usage.model}`,
594
+ kind: 1,
595
+ startTimeUnixNano: toUnixNano(endMs),
596
+ endTimeUnixNano: toUnixNano(endMs),
597
+ attributes: {
598
+ ...generationSpanAttributes(state.flow, {
599
+ model: usage.model,
600
+ inputTokens: usage.input,
601
+ outputTokens: usage.output,
602
+ }),
603
+ ...generationContentAttributes(
604
+ contentLevel(),
605
+ contentMax(),
606
+ event.message,
607
+ ),
608
+ },
609
+ statusCode: 0,
610
+ })
611
+ if (state.buffer.length >= FLUSH_THRESHOLD) flush()
612
+ }),
613
+ )
614
+ state.unsubscribers.push(
615
+ pi.on('session_shutdown', () => {
616
+ if (!state.enabled) return
617
+ closePhase()
618
+ // steps opened while no phase span existed never get closed by it
619
+ closeOpenSteps()
620
+ flush()
621
+ for (const off of state.unsubscribers) off()
622
+ state.unsubscribers.length = 0
623
+ state.enabled = false
624
+ }),
625
+ )
626
+ }
627
+
628
+ pi.on('session_start', (_event, ctx) => {
629
+ if (state.enabled) return
630
+ void deps
631
+ .loadSettings(ctx.cwd)
632
+ .then((settings) => {
633
+ if (settings === null) return
634
+ subscribe(settings)
635
+ })
636
+ .catch(() => {
637
+ // config read failure = telemetry stays off, session proceeds
638
+ })
639
+ })
640
+
641
+ const adhocName = (run: AdhocTraceInfo): string => `${run.kind} ${run.target}`
642
+
643
+ return {
644
+ adhocBegin: (run, nest) => {
645
+ if (!state.enabled) return
646
+ ensureTrace()
647
+ if (state.fromFlow) return
648
+ // AIDEV-NOTE: the root span is a zero-length MARKER exported right away
649
+ // (same pattern as the flow root), so children made during the run
650
+ // never hang off a missing parent even if pi dies mid-run. The real
651
+ // duration/cost/tokens go on a separate "<kind> run" child span at
652
+ // close. Neither span is ever re-sent (Tempo keeps both copies).
653
+ const root = {
654
+ traceId: randomTraceId(deps.rng),
655
+ spanId: randomSpanId(deps.rng),
656
+ startNano: toUnixNano(run.startMs),
657
+ }
658
+ state.adhocRoots.set(run.id, root)
659
+ const attrs = {
660
+ 'adhoc.run': run.id,
661
+ 'adhoc.kind': run.kind,
662
+ 'adhoc.target': run.target,
663
+ }
664
+ state.buffer.push({
665
+ traceId: root.traceId,
666
+ spanId: root.spanId,
667
+ name: adhocName(run),
668
+ kind: 1,
669
+ startTimeUnixNano: root.startNano,
670
+ endTimeUnixNano: root.startNano,
671
+ attributes: { ...attrs, 'flow.span': 'adhoc' },
672
+ statusCode: 0,
673
+ })
674
+ flush()
675
+ if (!nest) return
676
+ state.adhoc = { ...root, attrs }
677
+ state.traceId = root.traceId
678
+ state.rootParentId = root.spanId
679
+ },
680
+ adhocEnd: (run, attributes) => {
681
+ if (!state.enabled) return
682
+ let root = state.adhocRoots.get(run.id)
683
+ state.adhocRoots.delete(run.id)
684
+ if (root === undefined) {
685
+ // begin never ran (telemetry enabled mid-run): emit the marker now
686
+ root = {
687
+ traceId: randomTraceId(deps.rng),
688
+ spanId: randomSpanId(deps.rng),
689
+ startNano: toUnixNano(run.startMs),
690
+ }
691
+ state.buffer.push({
692
+ traceId: root.traceId,
693
+ spanId: root.spanId,
694
+ name: adhocName(run),
695
+ kind: 1,
696
+ startTimeUnixNano: root.startNano,
697
+ endTimeUnixNano: root.startNano,
698
+ attributes: {
699
+ 'adhoc.run': run.id,
700
+ 'adhoc.kind': run.kind,
701
+ 'adhoc.target': run.target,
702
+ 'flow.span': 'adhoc',
703
+ },
704
+ statusCode: 0,
705
+ })
706
+ }
707
+ const open = state.adhoc
708
+ if (open !== null && open.attrs['adhoc.run'] === run.id) {
709
+ // back to a fresh per-session trace for whatever comes next
710
+ state.adhoc = null
711
+ state.traceId = null
712
+ state.rootParentId = null
713
+ }
714
+ state.buffer.push({
715
+ traceId: root.traceId,
716
+ spanId: randomSpanId(deps.rng),
717
+ parentSpanId: root.spanId,
718
+ name: `${run.kind} run`,
719
+ kind: 1,
720
+ startTimeUnixNano: root.startNano,
721
+ endTimeUnixNano: toUnixNano(run.endMs),
722
+ attributes: { ...attributes, 'flow.span': 'adhoc-run' },
723
+ statusCode: 0,
724
+ })
725
+ flush()
726
+ },
727
+ stepStart: (phase, step) => {
728
+ if (!state.enabled) return
729
+ // ensureTrace opens the phase span for the currently stamped phase, so
730
+ // the step can be parented on it right away.
731
+ ensureTrace()
732
+ if (isWorker()) return
733
+ const traceId = state.traceId
734
+ if (traceId === null) return
735
+ const key = stepSpanKey(traceId, phase, step)
736
+ // idempotent: an open OR already-exported step is never opened again
737
+ if (state.steps.has(key)) return
738
+ let name = step
739
+ const ref = state.flow['flow.ref']
740
+ if (ref !== undefined) name = `${ref} - ${step}`
741
+ state.steps.set(key, {
742
+ traceId,
743
+ phase,
744
+ step,
745
+ name,
746
+ spanId: stepSpanId(traceId, phase, step),
747
+ startNano: toUnixNano(deps.now()),
748
+ attrs: { ...state.flow, 'flow.span': 'step', phase, step },
749
+ parentId: parentFor(),
750
+ exported: false,
751
+ })
752
+ },
753
+ stepStop: (phase, step) => {
754
+ if (!state.enabled) return
755
+ if (isWorker()) return
756
+ // deliberately no ensureTrace here: the stop must close the step under
757
+ // the trace it was opened in, even if the flow env changed in between
758
+ // (a late syncFlowEnv then closes it via closePhaseSteps instead).
759
+ const traceId = state.traceId
760
+ if (traceId === null) return
761
+ const open = state.steps.get(stepSpanKey(traceId, phase, step))
762
+ if (open === undefined) return
763
+ if (open.exported) return
764
+ closeStep(open)
765
+ // flush NOW: a step boundary is the last thing before the session may go
766
+ // idle, and the buffer only auto-flushes at FLUSH_THRESHOLD spans
767
+ flush()
768
+ },
769
+ syncFlowEnv: () => {
770
+ if (!state.enabled) return
771
+ const before = state.buffer.length
772
+ ensureTrace()
773
+ if (state.buffer.length > before) flush()
774
+ },
775
+ }
776
+ }