@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,862 @@
1
+ // AIDEV-NOTE (PMR-V3FN 2.1): pure translator core for /flow-diagram.
2
+ // Segments the run journal on 'run-start' events and extracts header facts
3
+ // for the selected run. Record synthesis (schema-v2 records) lands in 2.2/2.3
4
+ // via the synthesizeRecords seam — this module deliberately has NO fs and NO
5
+ // Pi runtime imports so it stays unit-testable in isolation.
6
+
7
+ import type { AssignmentRecord } from '@gtheys/pi-interactive-subagents'
8
+ import {
9
+ collectMainSessionFiles,
10
+ collectSpawnNotes,
11
+ type PhaseDuration,
12
+ type PhaseWindow,
13
+ phaseDurations,
14
+ phaseWindows,
15
+ } from '../flow/cost.ts'
16
+ import type { FlowRunEvent } from '../run-state.ts'
17
+
18
+ export interface DiagramHeader {
19
+ /** Ref from the segment's run-start event. */
20
+ ref: string
21
+ /** 1-based index of the selected run within the journal. */
22
+ runIndex: number
23
+ /** Total number of run-start events in the journal. */
24
+ runCount: number
25
+ mode: 'work' | 'personal'
26
+ /** Ref the run is tracked by (Jira key in work mode); absent when same as ref. */
27
+ trackRef?: string
28
+ /** Per-phase wall-clock durations (seconds) for the selected segment. */
29
+ phases: PhaseDuration[]
30
+ /** Subtask → commit shas from the segment's subtask-ranges event. */
31
+ commitsBySubtask: Array<{ subtask: string; commits: string[] }>
32
+ unattributed: string[]
33
+ /** PR url from the last step-output in the segment that carries one. */
34
+ prUrl?: string
35
+ }
36
+
37
+ /**
38
+ * AIDEV-NOTE (PMR-V392): token spend in harness-profiler schema-v2 shape.
39
+ * Mapping from pi session `usage` blocks (camelCase): new = input + cacheWrite,
40
+ * cached = cacheRead, out = output; calls = distinct assistant message ids
41
+ * (dedup by entry id). 2.3 reuses this mapping for standalone spend records.
42
+ */
43
+ export interface Spend {
44
+ new: number
45
+ cached: number
46
+ out: number
47
+ calls: number
48
+ }
49
+
50
+ /**
51
+ * A synthetic `tool: 'Agent'` call record for one journaled spawn. This is
52
+ * what makes `hp.js` `contextsOf()` (PARENT_TOOLS = ['Skill','Agent']) create
53
+ * the child lane + spawn arrow.
54
+ *
55
+ * AIDEV-NOTE (PMR-V392) synthetic-id scheme: contexts are keyed by the
56
+ * journaled childId (stable across the run); the main context is 'main'
57
+ * (hp.js MAIN). tool_use_id = 'spawn-<childId>' is dedup-safe — repeated
58
+ * spawn/resume/reattach records for one child collapse onto one lane.
59
+ */
60
+ export interface SpawnCallRecord {
61
+ v: 2
62
+ harness: 'pi'
63
+ /** End of the child's work — the record's position on the timeline. */
64
+ at: string
65
+ /** '<ref> run <k>' — shared by all records of the selected run. */
66
+ session: string
67
+ agent_id: string
68
+ tool: 'Agent'
69
+ tool_use_id: string
70
+ name: string
71
+ child_agent_id: string
72
+ child_agent_type?: string
73
+ /**
74
+ * AIDEV-NOTE (deviation fix): omitted for lost children (no session end,
75
+ * no assignment updatedAt) — the spec's two-step end chain yields no end,
76
+ * so the lane carries no length claim ("lanes without ends"). hp.js reads
77
+ * `duration_ms || 0` for layout, so absence is safe.
78
+ */
79
+ duration_ms?: number
80
+ child_spend?: Spend
81
+ }
82
+
83
+ /**
84
+ * One paired toolCall/toolResult from any context's session (main or child).
85
+ * Per Appendix A: never uses PARENT_TOOLS names, so it renders inside the
86
+ * lane it belongs to.
87
+ */
88
+ export interface ToolCallRecord {
89
+ v: 2
90
+ harness: 'pi'
91
+ session: string
92
+ agent_id: string
93
+ tool_use_id: string
94
+ tool: string
95
+ /** Command head (bash) or tool name, clipped. */
96
+ name: string
97
+ /** Clipped one-line command, bash calls only. */
98
+ args?: string
99
+ /** First line of the toolResult text, clipped. */
100
+ result?: string
101
+ duration_ms: number
102
+ ok?: boolean
103
+ context_tokens?: number
104
+ /** Unpaired toolCall (no result yet) stays on the timeline as running. */
105
+ running?: boolean
106
+ at: string
107
+ }
108
+
109
+ /** Per-context token totals; `contextSpend()` in hp.js reads these. */
110
+ export interface SpendRecord {
111
+ v: 2
112
+ harness: 'pi'
113
+ session: string
114
+ agent_id: string
115
+ event: 'SubagentStop'
116
+ spend: Spend
117
+ at: string
118
+ }
119
+
120
+ /** Vertical labeled phase marker (one per segmented phase-start). */
121
+ export interface PhaseMarkerRecord {
122
+ v: 2
123
+ harness: 'pi'
124
+ session: string
125
+ agent_id: 'main'
126
+ event: 'PreCompact'
127
+ trigger: string
128
+ at: string
129
+ }
130
+
131
+ /** Inline diamond milestone (gate decision / receipt / commit). */
132
+ export interface MilestoneMarkerRecord {
133
+ v: 2
134
+ harness: 'pi'
135
+ session: string
136
+ agent_id: 'main'
137
+ tool: 'Skill'
138
+ tool_use_id: string
139
+ name: string
140
+ ok: true
141
+ at: string
142
+ }
143
+
144
+ /**
145
+ * AIDEV-NOTE (PMR-V392): 2.2 emits spawn records; 2.3 adds tool-call,
146
+ * spend (SubagentStop) and marker records to this union.
147
+ */
148
+ export type DiagramRecord =
149
+ | SpawnCallRecord
150
+ | ToolCallRecord
151
+ | SpendRecord
152
+ | PhaseMarkerRecord
153
+ | MilestoneMarkerRecord
154
+
155
+ export type DiagramResult =
156
+ | {
157
+ kind: 'ok'
158
+ header: DiagramHeader
159
+ records: DiagramRecord[]
160
+ /** AIDEV-NOTE (PMR-9CHQ): degradation warnings (skipped records). */
161
+ warnings: readonly string[]
162
+ }
163
+ /** No run-start events at all — nothing segmentable in the journal. */
164
+ | { kind: 'no-records' }
165
+ /**
166
+ * AIDEV-NOTE (PMR-V3FN): runIndex beyond runCount; runCount travels so
167
+ * the caller can say "journal has N runs".
168
+ */
169
+ | { kind: 'out-of-range'; runCount: number }
170
+
171
+ export interface DiagramContext {
172
+ assignments: readonly AssignmentRecord[]
173
+ /** Parsed session entries keyed by session file path. */
174
+ sessionEntriesByFile: ReadonlyMap<string, readonly unknown[]>
175
+ /**
176
+ * AIDEV-NOTE (PMR-9CHQ): degradation warnings collected during synthesis
177
+ * (one per skipped record, capped) — surfaced by the caller, never thrown.
178
+ */
179
+ warnings: string[]
180
+ }
181
+
182
+ /**
183
+ * AIDEV-NOTE: run-start events delimit runs; the segment INCLUDES its
184
+ * run-start event and events before the first run-start belong to run 1.
185
+ * runIndex is 1-based; null/undefined selects the latest run.
186
+ */
187
+ export function segmentRuns(events: readonly FlowRunEvent[]): FlowRunEvent[][] {
188
+ const segments: FlowRunEvent[][] = []
189
+ // pre-run-start events are buffered until the first run-start opens run 1
190
+ let current: FlowRunEvent[] = []
191
+ let open = false
192
+ for (const event of events) {
193
+ if (event.kind === 'run-start') {
194
+ if (open) {
195
+ segments.push(current)
196
+ current = [event]
197
+ } else {
198
+ // events before the first run-start belong to run 1
199
+ current = [event, ...current]
200
+ open = true
201
+ }
202
+ } else {
203
+ current.push(event)
204
+ }
205
+ }
206
+ if (open) segments.push(current)
207
+ return segments
208
+ }
209
+
210
+ /**
211
+ * AIDEV-NOTE (PMR-GPQJ): segment selection is exported so callers
212
+ * (command.ts) can scope session-file reads to the SELECTED run instead of
213
+ * reading every run's sessions journal-wide. buildDiagram consumes the same
214
+ * selection, so both paths agree on the index/runCount math.
215
+ */
216
+ export type SegmentSelection =
217
+ | { kind: 'ok'; segment: FlowRunEvent[]; index: number; runCount: number }
218
+ /** No run-start events at all — nothing segmentable in the journal. */
219
+ | { kind: 'no-records' }
220
+ | { kind: 'out-of-range'; runCount: number }
221
+
222
+ export function selectSegment(
223
+ events: readonly FlowRunEvent[],
224
+ runIndex: number | null | undefined,
225
+ ): SegmentSelection {
226
+ const segments = segmentRuns(events)
227
+ const runCount = segments.length
228
+ let index: number
229
+ if (runIndex === null || runIndex === undefined) {
230
+ index = runCount
231
+ } else {
232
+ index = runIndex
233
+ }
234
+ if (runCount === 0) return { kind: 'no-records' }
235
+ if (index < 1 || index > runCount) return { kind: 'out-of-range', runCount }
236
+ return { kind: 'ok', segment: segments[index - 1], index, runCount }
237
+ }
238
+
239
+ const NAME_LIMIT = 60
240
+
241
+ function clip(text: string): string {
242
+ if (text.length <= NAME_LIMIT) return text
243
+ return text.slice(0, NAME_LIMIT)
244
+ }
245
+
246
+ function entryTimeMs(entry: unknown): number | null {
247
+ if (entry == null || typeof entry !== 'object') return null
248
+ const raw = (entry as Record<string, unknown>).timestamp
249
+ if (typeof raw !== 'string') return null
250
+ const ms = Date.parse(raw)
251
+ if (!Number.isFinite(ms)) return null
252
+ return ms
253
+ }
254
+
255
+ /** Last parsed entry timestamp (ms), null when no timestamped entries. */
256
+ function lastEntryMs(entries: readonly unknown[]): number | null {
257
+ let last: number | null = null
258
+ for (const entry of entries) {
259
+ const ms = entryTimeMs(entry)
260
+ if (ms === null) continue
261
+ if (last === null || ms > last) last = ms
262
+ }
263
+ return last
264
+ }
265
+
266
+ /** AIDEV-NOTE (PMR-V392): see Spend — dedup by entry id, camelCase usage. */
267
+ function computeSpend(entries: readonly unknown[]): Spend | undefined {
268
+ const seen = new Set<string>()
269
+ const spend: Spend = { new: 0, cached: 0, out: 0, calls: 0 }
270
+ for (const entry of entries) {
271
+ if (entry == null || typeof entry !== 'object') continue
272
+ const e = entry as Record<string, unknown>
273
+ if (e.type !== 'message') continue
274
+ const message = e.message
275
+ if (message == null || typeof message !== 'object') continue
276
+ const m = message as Record<string, unknown>
277
+ if (m.role !== 'assistant') continue
278
+ let id = ''
279
+ if (typeof e.id === 'string') {
280
+ id = e.id
281
+ }
282
+ if (id.length > 0) {
283
+ if (seen.has(id)) continue
284
+ seen.add(id)
285
+ }
286
+ const usage = m.usage
287
+ if (usage == null || typeof usage !== 'object') continue
288
+ const u = usage as Record<string, unknown>
289
+ const num = (value: unknown): number => {
290
+ if (typeof value === 'number' && Number.isFinite(value)) return value
291
+ return 0
292
+ }
293
+ spend.new += num(u.input) + num(u.cacheWrite)
294
+ spend.cached += num(u.cacheRead)
295
+ spend.out += num(u.output)
296
+ spend.calls += 1
297
+ }
298
+ if (spend.calls === 0) return undefined
299
+ return spend
300
+ }
301
+
302
+ /**
303
+ * AIDEV-NOTE (PMR-V392): the orchestrator's main session contains raw
304
+ * subagent-spawn tool calls (tool name `subagent`, verified in a real pi
305
+ * session file and docs/extensions.md). They duplicate the journal-derived
306
+ * spawn arrows from synthesizeSpawns, so they are skipped here. Phase 5
307
+ * smoke re-verifies against real data.
308
+ */
309
+ export const SPAWN_TOOL_SKIP: readonly string[] = ['subagent']
310
+
311
+ /** One session lane we walk for tool calls and spend. */
312
+ interface Lane {
313
+ agentId: string
314
+ entries: readonly unknown[]
315
+ /** Fallback end (assignment.updatedAt / spawn at) when entries lack timestamps. */
316
+ fallbackEndMs: number | null
317
+ }
318
+
319
+ interface ResolvedChild {
320
+ childId: string
321
+ sessionFile: string | null
322
+ fallbackEndMs: number | null
323
+ }
324
+
325
+ /** Mirrors synthesizeSpawns' sessionFile/end fallback for spend records. */
326
+ function resolveChildren(
327
+ segment: readonly FlowRunEvent[],
328
+ ctx: DiagramContext,
329
+ ): ResolvedChild[] {
330
+ const byChild = new Map<string, AssignmentRecord>()
331
+ for (const record of ctx.assignments) {
332
+ byChild.set(record.childId, record)
333
+ }
334
+ const children: ResolvedChild[] = []
335
+ for (const note of collectSpawnNotes(segment)) {
336
+ let sessionFile: string | null = note.sessionFile
337
+ const assignmentRecord = byChild.get(note.childId)
338
+ if (
339
+ (sessionFile === null || sessionFile.length === 0) &&
340
+ assignmentRecord !== undefined
341
+ ) {
342
+ sessionFile = assignmentRecord.sessionFile
343
+ }
344
+ let fallbackEndMs: number | null = null
345
+ if (assignmentRecord !== undefined) {
346
+ const parsed = Date.parse(assignmentRecord.updatedAt)
347
+ if (Number.isFinite(parsed)) fallbackEndMs = parsed
348
+ }
349
+ if (fallbackEndMs === null) {
350
+ const parsed = Date.parse(note.at)
351
+ if (Number.isFinite(parsed)) fallbackEndMs = parsed
352
+ }
353
+ children.push({ childId: note.childId, sessionFile, fallbackEndMs })
354
+ }
355
+ return children
356
+ }
357
+
358
+ function laneEntries(
359
+ ctx: DiagramContext,
360
+ sessionFile: string | null,
361
+ ): readonly unknown[] {
362
+ if (sessionFile === null || sessionFile.length === 0) return []
363
+ const entries = ctx.sessionEntriesByFile.get(sessionFile)
364
+ if (entries === undefined) return []
365
+ return entries
366
+ }
367
+
368
+ /**
369
+ * AIDEV-NOTE (review blocker B2): main pi sessions RESUME across runs, so a
370
+ * lane must only carry entries inside the selected segment's phase windows —
371
+ * same rule as buildMainRows in flow/cost.ts. Entries outside every window
372
+ * are pre/post-flow chat; entries without a parseable timestamp are dropped
373
+ * (they cannot be placed on the timeline). Empty windows clip everything —
374
+ * a run with no phase-starts has no attributable main-lane activity.
375
+ */
376
+ function clipToWindows(
377
+ entries: readonly unknown[],
378
+ windows: readonly PhaseWindow[],
379
+ ): readonly unknown[] {
380
+ const clipped: unknown[] = []
381
+ for (const entry of entries) {
382
+ const ms = entryTimeMs(entry)
383
+ if (ms === null) continue
384
+ const window = windows.find((w) => ms >= w.startMs && ms < w.endMs)
385
+ if (window === undefined) continue
386
+ clipped.push(entry)
387
+ }
388
+ return clipped
389
+ }
390
+
391
+ function buildLanes(
392
+ segment: readonly FlowRunEvent[],
393
+ ctx: DiagramContext,
394
+ ): Lane[] {
395
+ const windows = phaseWindows(segment)
396
+ const lanes: Lane[] = []
397
+ for (const sessionFile of collectMainSessionFiles(segment)) {
398
+ lanes.push({
399
+ agentId: 'main',
400
+ entries: clipToWindows(laneEntries(ctx, sessionFile), windows),
401
+ fallbackEndMs: null,
402
+ })
403
+ }
404
+ for (const child of resolveChildren(segment, ctx)) {
405
+ lanes.push({
406
+ agentId: child.childId,
407
+ entries: laneEntries(ctx, child.sessionFile),
408
+ fallbackEndMs: child.fallbackEndMs,
409
+ })
410
+ }
411
+ return lanes
412
+ }
413
+
414
+ /** AIDEV-NOTE (PMR-V392): duration = toolResult ms-epoch − assistant ISO, clamped ≥ 0. */
415
+ function callDurationMs(resultMs: number, entryMs: number | null): number {
416
+ if (entryMs === null) return 0
417
+ const duration = resultMs - entryMs
418
+ if (duration < 0) return 0
419
+ return duration
420
+ }
421
+
422
+ interface ToolCallBlock {
423
+ id: string
424
+ name: string
425
+ command: string | null
426
+ }
427
+
428
+ interface ToolResultInfo {
429
+ ms: number
430
+ isError: boolean
431
+ text: string | null
432
+ }
433
+
434
+ function extractToolCallBlock(block: unknown): ToolCallBlock | null {
435
+ if (block == null || typeof block !== 'object') return null
436
+ const b = block as Record<string, unknown>
437
+ if (b.type !== 'toolCall') return null
438
+ if (typeof b.id !== 'string' || typeof b.name !== 'string') return null
439
+ let command: string | null = null
440
+ const args = b.arguments
441
+ if (b.name === 'bash' && args != null && typeof args === 'object') {
442
+ const cmd = (args as Record<string, unknown>).command
443
+ if (typeof cmd === 'string' && cmd.length > 0) {
444
+ command = cmd.split('\n')[0]
445
+ }
446
+ }
447
+ return { id: b.id, name: b.name, command }
448
+ }
449
+
450
+ function extractToolResult(entry: unknown): ToolResultInfo | null {
451
+ if (entry == null || typeof entry !== 'object') return null
452
+ const e = entry as Record<string, unknown>
453
+ if (e.type !== 'message') return null
454
+ const message = e.message
455
+ if (message == null || typeof message !== 'object') return null
456
+ const m = message as Record<string, unknown>
457
+ if (m.role !== 'toolResult') return null
458
+ if (typeof m.toolCallId !== 'string') return null
459
+ if (typeof m.timestamp !== 'number' || !Number.isFinite(m.timestamp)) {
460
+ return null
461
+ }
462
+ let isError = false
463
+ if (m.isError === true) isError = true
464
+ let text: string | null = null
465
+ const content = m.content
466
+ if (Array.isArray(content)) {
467
+ for (const block of content) {
468
+ if (block == null || typeof block !== 'object') continue
469
+ const b = block as Record<string, unknown>
470
+ if (b.type !== 'text' || typeof b.text !== 'string') continue
471
+ text = b.text.split('\n')[0]
472
+ break
473
+ }
474
+ }
475
+ return { ms: m.timestamp, isError, text }
476
+ }
477
+
478
+ function callName(call: ToolCallBlock): string {
479
+ if (call.command !== null) {
480
+ const head = call.command.trim().split(/\s+/)[0]
481
+ if (head.length > 0) return head
482
+ }
483
+ return call.name
484
+ }
485
+
486
+ function synthesizeToolCalls(
487
+ segment: readonly FlowRunEvent[],
488
+ ctx: DiagramContext,
489
+ runId: string,
490
+ ): ToolCallRecord[] {
491
+ const records: ToolCallRecord[] = []
492
+ for (const lane of buildLanes(segment, ctx)) {
493
+ const resultsById = new Map<string, ToolResultInfo>()
494
+ for (const entry of lane.entries) {
495
+ const result = extractToolResult(entry)
496
+ if (result === null) continue
497
+ const key = resultKeyOf(entry)
498
+ if (resultsById.has(key)) continue
499
+ resultsById.set(key, result)
500
+ }
501
+ for (const entry of lane.entries) {
502
+ if (entry == null || typeof entry !== 'object') continue
503
+ const e = entry as Record<string, unknown>
504
+ if (e.type !== 'message') continue
505
+ const message = e.message
506
+ if (message == null || typeof message !== 'object') continue
507
+ const m = message as Record<string, unknown>
508
+ if (m.role !== 'assistant') continue
509
+ const entryMs = entryTimeMs(entry)
510
+ let contextTokens: number | undefined
511
+ const usage = m.usage
512
+ if (usage != null && typeof usage === 'object') {
513
+ const total = (usage as Record<string, unknown>).totalTokens
514
+ if (typeof total === 'number' && Number.isFinite(total)) {
515
+ contextTokens = total
516
+ }
517
+ }
518
+ const content = m.content
519
+ if (!Array.isArray(content)) continue
520
+ for (const block of content) {
521
+ const call = extractToolCallBlock(block)
522
+ if (call === null) continue
523
+ if (SPAWN_TOOL_SKIP.includes(call.name)) continue
524
+ const result = resultsById.get(call.id)
525
+ let at: string
526
+ if (result === undefined) {
527
+ if (entryMs !== null) at = new Date(entryMs).toISOString()
528
+ else at = ''
529
+ } else {
530
+ at = new Date(result.ms).toISOString()
531
+ }
532
+ const record: ToolCallRecord = {
533
+ v: 2,
534
+ harness: 'pi',
535
+ session: runId,
536
+ agent_id: lane.agentId,
537
+ tool_use_id: call.id,
538
+ tool: call.name,
539
+ name: clip(callName(call)),
540
+ duration_ms: 0,
541
+ at,
542
+ }
543
+ if (call.command !== null) record.args = clip(call.command)
544
+ if (contextTokens !== undefined) record.context_tokens = contextTokens
545
+ if (result === undefined) {
546
+ record.running = true
547
+ } else {
548
+ record.duration_ms = callDurationMs(result.ms, entryMs)
549
+ record.ok = !result.isError
550
+ if (result.text !== null) record.result = clip(result.text)
551
+ }
552
+ records.push(record)
553
+ }
554
+ }
555
+ }
556
+ return records
557
+ }
558
+
559
+ function resultKeyOf(entry: unknown): string {
560
+ if (entry == null || typeof entry !== 'object') return ''
561
+ const e = entry as Record<string, unknown>
562
+ if (e.type !== 'message') return ''
563
+ const message = e.message
564
+ if (message == null || typeof message !== 'object') return ''
565
+ const toolCallId = (message as Record<string, unknown>).toolCallId
566
+ if (typeof toolCallId === 'string') return toolCallId
567
+ return ''
568
+ }
569
+
570
+ function synthesizeSpendRecords(
571
+ segment: readonly FlowRunEvent[],
572
+ ctx: DiagramContext,
573
+ runId: string,
574
+ ): SpendRecord[] {
575
+ const records: SpendRecord[] = []
576
+ for (const lane of buildLanes(segment, ctx)) {
577
+ const spend = computeSpend(lane.entries)
578
+ if (spend === undefined) continue
579
+ let endMs = lastEntryMs(lane.entries)
580
+ if (endMs === null) endMs = lane.fallbackEndMs
581
+ if (endMs === null) continue
582
+ records.push({
583
+ v: 2,
584
+ harness: 'pi',
585
+ session: runId,
586
+ agent_id: lane.agentId,
587
+ event: 'SubagentStop',
588
+ spend,
589
+ at: new Date(endMs).toISOString(),
590
+ })
591
+ }
592
+ return records
593
+ }
594
+
595
+ function synthesizePhaseMarkers(
596
+ segment: readonly FlowRunEvent[],
597
+ runId: string,
598
+ ): PhaseMarkerRecord[] {
599
+ const records: PhaseMarkerRecord[] = []
600
+ for (const event of segment) {
601
+ if (event.kind !== 'phase-start') continue
602
+ records.push({
603
+ v: 2,
604
+ harness: 'pi',
605
+ session: runId,
606
+ agent_id: 'main',
607
+ event: 'PreCompact',
608
+ trigger: `phase ${event.phase}`,
609
+ at: event.at,
610
+ })
611
+ }
612
+ return records
613
+ }
614
+
615
+ function synthesizeMilestoneMarkers(
616
+ segment: readonly FlowRunEvent[],
617
+ runId: string,
618
+ ): MilestoneMarkerRecord[] {
619
+ const records: MilestoneMarkerRecord[] = []
620
+ let mark = 0
621
+ const push = (name: string, at: string): void => {
622
+ mark += 1
623
+ records.push({
624
+ v: 2,
625
+ harness: 'pi',
626
+ session: runId,
627
+ agent_id: 'main',
628
+ tool: 'Skill',
629
+ tool_use_id: `mark-${mark}`,
630
+ name: clip(name),
631
+ ok: true,
632
+ at,
633
+ })
634
+ }
635
+ // latest gate-decision per gate
636
+ const latestByGate = new Map<
637
+ string,
638
+ Extract<FlowRunEvent, { kind: 'gate-decision' }>
639
+ >()
640
+ for (const event of segment) {
641
+ if (event.kind === 'gate-decision') latestByGate.set(event.gate, event)
642
+ }
643
+ for (const event of latestByGate.values()) {
644
+ push(`gate ${event.gate}: ${event.status}`, event.at)
645
+ }
646
+ for (const event of segment) {
647
+ if (event.kind === 'command-receipt') {
648
+ push(`receipt: ${event.command}`, event.at)
649
+ } else if (event.kind === 'subtask-ranges') {
650
+ for (const range of event.bySubtask) {
651
+ for (const sha of range.commits) {
652
+ push(`commit ${sha.slice(0, 7)} → ${range.subtask}`, event.at)
653
+ }
654
+ }
655
+ }
656
+ }
657
+ return records
658
+ }
659
+
660
+ function synthesizeSpawns(
661
+ segment: readonly FlowRunEvent[],
662
+ ctx: DiagramContext,
663
+ runId: string,
664
+ ): SpawnCallRecord[] {
665
+ const notes = collectSpawnNotes(segment)
666
+ const byChild = new Map<string, AssignmentRecord>()
667
+ for (const record of ctx.assignments) {
668
+ byChild.set(record.childId, record)
669
+ }
670
+ const records: SpawnCallRecord[] = []
671
+ for (const note of notes) {
672
+ // Mirrors computeCostRollup's byChild fallback (flow/cost-rows.ts):
673
+ // when the spawn note lacks a sessionFile, the assignment record supplies
674
+ // sessionFile / agent type / subtask / end timestamp.
675
+ let sessionFile: string | null = note.sessionFile
676
+ const assignmentRecord = byChild.get(note.childId)
677
+ if (
678
+ (sessionFile === null || sessionFile.length === 0) &&
679
+ assignmentRecord !== undefined
680
+ ) {
681
+ sessionFile = assignmentRecord.sessionFile
682
+ }
683
+ let entries: readonly unknown[] | undefined
684
+ if (sessionFile !== null && sessionFile.length > 0) {
685
+ entries = ctx.sessionEntriesByFile.get(sessionFile)
686
+ }
687
+ const spawnMs = Date.parse(note.at)
688
+ let endMs = lastEntryMs(entries ?? [])
689
+ if (endMs === null && assignmentRecord !== undefined) {
690
+ const parsed = Date.parse(assignmentRecord.updatedAt)
691
+ if (Number.isFinite(parsed)) endMs = parsed
692
+ }
693
+ // AIDEV-NOTE (deviation fix): the end chain is two-step per spec §2.2 —
694
+ // last parsed session entry, else assignment updatedAt. A lost child
695
+ // (neither present) gets NO end: the record is positioned at the spawn
696
+ // event's own timestamp (a position, not an end claim) and omits
697
+ // duration_ms ("lanes without ends"); no spawn-time fallback exists.
698
+ let at: string
699
+ let duration: number | undefined
700
+ if (endMs !== null) {
701
+ at = new Date(endMs).toISOString()
702
+ if (Number.isFinite(spawnMs)) {
703
+ duration = Math.max(0, endMs - spawnMs)
704
+ }
705
+ } else {
706
+ at = note.at
707
+ }
708
+ let display = note.name
709
+ if (display.length === 0 && assignmentRecord !== undefined) {
710
+ display = assignmentRecord.name
711
+ }
712
+ if (display.length === 0) display = note.childId
713
+ if (assignmentRecord?.agent !== undefined) display = assignmentRecord.agent
714
+ let name = display
715
+ const subtask = note.subtask ?? assignmentRecord?.subtask
716
+ if (subtask !== null && subtask !== undefined)
717
+ name = `${display} · ${subtask}`
718
+ const record: SpawnCallRecord = {
719
+ v: 2,
720
+ harness: 'pi',
721
+ at,
722
+ session: runId,
723
+ agent_id: 'main',
724
+ tool: 'Agent',
725
+ tool_use_id: `spawn-${note.childId}`,
726
+ name: clip(name),
727
+ child_agent_id: note.childId,
728
+ }
729
+ if (duration !== undefined) record.duration_ms = duration
730
+ if (assignmentRecord?.agent !== undefined) {
731
+ record.child_agent_type = assignmentRecord.agent
732
+ }
733
+ const spend = computeSpend(entries ?? [])
734
+ if (spend !== undefined) record.child_spend = spend
735
+ records.push(record)
736
+ }
737
+ return records
738
+ }
739
+
740
+ /**
741
+ * AIDEV-NOTE (PMR-V392): 2.2 adds spawns; 2.3 layers toolCalls, spend
742
+ * (SubagentStop) and marker records, then sorts the whole set by `at`.
743
+ */
744
+ /**
745
+ * AIDEV-NOTE (PMR-9CHQ): final backstop — any record whose `at` is missing
746
+ * or unparseable (timestamp-less toolCall fallback, corrupted spawn note or
747
+ * journal event) is SKIPPED with a warning instead of reaching the vendored
748
+ * renderer, where NaN timestamps throw inside clock() and blank the page.
749
+ */
750
+ const SKIPPED_WARNING_CAP = 20
751
+
752
+ function recordLabel(record: DiagramRecord): string {
753
+ if ('name' in record) return record.name
754
+ if ('trigger' in record) return record.trigger
755
+ return record.event
756
+ }
757
+
758
+ function dropUnplaceableRecords(
759
+ records: readonly DiagramRecord[],
760
+ warnings: string[],
761
+ ): DiagramRecord[] {
762
+ const kept: DiagramRecord[] = []
763
+ let skipped = 0
764
+ for (const record of records) {
765
+ if (
766
+ typeof record.at === 'string' &&
767
+ Number.isFinite(Date.parse(record.at))
768
+ ) {
769
+ kept.push(record)
770
+ continue
771
+ }
772
+ skipped += 1
773
+ if (warnings.length < SKIPPED_WARNING_CAP) {
774
+ warnings.push(
775
+ `skipped record "${recordLabel(record)}" (agent ${record.agent_id}) — unparseable or missing timestamp`,
776
+ )
777
+ }
778
+ }
779
+ if (skipped > SKIPPED_WARNING_CAP) {
780
+ warnings.push(
781
+ `…and ${skipped - SKIPPED_WARNING_CAP} more skipped record(s)`,
782
+ )
783
+ }
784
+ return kept
785
+ }
786
+
787
+ function synthesizeRecords(
788
+ segment: readonly FlowRunEvent[],
789
+ ctx: DiagramContext,
790
+ runId: string,
791
+ ): DiagramRecord[] {
792
+ const records: DiagramRecord[] = [
793
+ ...synthesizeSpawns(segment, ctx, runId),
794
+ ...synthesizeToolCalls(segment, ctx, runId),
795
+ ...synthesizeSpendRecords(segment, ctx, runId),
796
+ ...synthesizePhaseMarkers(segment, runId),
797
+ ...synthesizeMilestoneMarkers(segment, runId),
798
+ ]
799
+ records.sort((a, b) => {
800
+ if (a.at < b.at) return -1
801
+ if (a.at > b.at) return 1
802
+ return 0
803
+ })
804
+ return dropUnplaceableRecords(records, ctx.warnings)
805
+ }
806
+
807
+ export function buildDiagram(
808
+ _ref: string,
809
+ runIndex: number | null | undefined,
810
+ events: readonly FlowRunEvent[],
811
+ assignments: readonly AssignmentRecord[],
812
+ sessionEntriesByFile: ReadonlyMap<string, readonly unknown[]>,
813
+ ): DiagramResult {
814
+ const selection = selectSegment(events, runIndex)
815
+ if (selection.kind === 'no-records') return { kind: 'no-records' }
816
+ if (selection.kind === 'out-of-range') {
817
+ return { kind: 'out-of-range', runCount: selection.runCount }
818
+ }
819
+ const { segment, index, runCount } = selection
820
+ const runStart = segment.find((event) => event.kind === 'run-start')
821
+ if (runStart === undefined || runStart.kind !== 'run-start') {
822
+ return { kind: 'no-records' }
823
+ }
824
+
825
+ const header: DiagramHeader = {
826
+ ref: runStart.ref,
827
+ runIndex: index,
828
+ runCount,
829
+ mode: runStart.mode,
830
+ phases: phaseDurations(segment),
831
+ commitsBySubtask: [],
832
+ unattributed: [],
833
+ }
834
+ if (runStart.trackRef !== undefined) {
835
+ header.trackRef = runStart.trackRef
836
+ }
837
+
838
+ for (const event of segment) {
839
+ if (event.kind === 'subtask-ranges') {
840
+ header.commitsBySubtask = [...event.bySubtask]
841
+ header.unattributed = [...event.unattributed]
842
+ } else if (event.kind === 'step-output' && event.prUrl !== undefined) {
843
+ header.prUrl = event.prUrl
844
+ }
845
+ }
846
+
847
+ const runId = `${runStart.ref} run ${index}`
848
+ const warnings: string[] = []
849
+ const records = synthesizeRecords(
850
+ segment,
851
+ {
852
+ assignments,
853
+ sessionEntriesByFile,
854
+ warnings,
855
+ },
856
+ runId,
857
+ )
858
+ if (records.length === 0) return { kind: 'no-records' }
859
+ return { kind: 'ok', header, records, warnings }
860
+ }
861
+
862
+ export type { PhaseDuration, PhaseWindow } from '../flow/cost.ts'