@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,360 @@
1
+ // AIDEV-NOTE: time + cost tracking for the standalone commands that run
2
+ // OUTSIDE a /flow run (/brainstorm, /pr-quality, /review). Flow runs are
3
+ // tracked through the run journal; these have no journal, so a tiny in-memory
4
+ // tracker records a window per run and pushes `pi_flow_adhoc_*` metrics
5
+ // (Pushgateway job `pi-flow-adhoc`, group `run=<id>`) on every update. The
6
+ // metric names differ from the flow ones ON PURPOSE so the flow dashboards
7
+ // (which select pi_flow_run_* without a job filter) never pick them up.
8
+ //
9
+ // Cost model:
10
+ // - main-session commands (brainstorm, pr-quality): the main session's
11
+ // usage between the command and the LAST agent_settled while the run is
12
+ // open. pr-quality closes after its first settle (one triage turn);
13
+ // brainstorm stays open (it is a conversation) until another ad-hoc
14
+ // command, a flow run or session shutdown. Chat after a brainstorm that
15
+ // is not part of it is therefore counted — known limit.
16
+ // - worker commands (review): the reviewer subagent's whole session file.
17
+ //
18
+ // Disabled while a flow is active (PI_FLOW_REF set): the flow journal already
19
+ // accounts for everything in that run. Never throws.
20
+ import { summarizeEntriesUsage } from '@gtheys/pi-interactive-subagents'
21
+ import { parseSessionEntries } from '../flow/cost.ts'
22
+
23
+ export type AdhocKind = 'brainstorm' | 'pr-quality' | 'review'
24
+
25
+ export interface AdhocWorker {
26
+ sessionFile: string
27
+ role: string
28
+ }
29
+
30
+ export interface AdhocRun {
31
+ id: string
32
+ kind: AdhocKind
33
+ target: string
34
+ startMs: number
35
+ endMs: number
36
+ mainSessionFile: string | null
37
+ workers: AdhocWorker[]
38
+ }
39
+
40
+ function esc(value: string): string {
41
+ return value.replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/"/g, '\\"')
42
+ }
43
+
44
+ function labels(values: Record<string, string>): string {
45
+ const parts: string[] = []
46
+ for (const key of Object.keys(values)) {
47
+ parts.push(`${key}="${esc(values[key])}"`)
48
+ }
49
+ return parts.join(',')
50
+ }
51
+
52
+ function entryMs(entry: unknown): number | null {
53
+ if (entry === null || typeof entry !== 'object') return null
54
+ const raw = (entry as Record<string, unknown>).timestamp
55
+ if (typeof raw !== 'string') return null
56
+ const ms = Date.parse(raw)
57
+ if (!Number.isFinite(ms)) return null
58
+ return ms
59
+ }
60
+
61
+ export function adhocRunId(
62
+ kind: AdhocKind,
63
+ target: string,
64
+ startMs: number,
65
+ ): string {
66
+ const slug = target
67
+ .toLowerCase()
68
+ .replace(/[^a-z0-9]+/g, '-')
69
+ .replace(/^-+|-+$/g, '')
70
+ .slice(0, 40)
71
+ const stamp = new Date(startMs)
72
+ .toISOString()
73
+ .slice(0, 16)
74
+ .replace(/[-:]/g, '')
75
+ if (slug.length === 0) return `${kind}-${stamp}`
76
+ return `${kind}-${slug}-${stamp}`
77
+ }
78
+
79
+ export interface AdhocSessionRow {
80
+ role: string
81
+ session: string
82
+ input: number
83
+ output: number
84
+ cacheRead: number
85
+ cacheWrite: number
86
+ cost: number
87
+ }
88
+
89
+ /** Usage rows for one run. Unreadable sessions / no usage add no row. */
90
+ export function summarizeAdhoc(
91
+ run: AdhocRun,
92
+ readSession: (file: string) => string | null,
93
+ ): AdhocSessionRow[] {
94
+ const rows: AdhocSessionRow[] = []
95
+ const add = (role: string, session: string, entries: readonly unknown[]) => {
96
+ const summary = summarizeEntriesUsage(entries)
97
+ if (!summary.sawUsage) return
98
+ const t = summary.totals
99
+ rows.push({
100
+ role,
101
+ session,
102
+ input: t.input,
103
+ output: t.output,
104
+ cacheRead: t.cacheRead,
105
+ cacheWrite: t.cacheWrite,
106
+ cost: t.cost,
107
+ })
108
+ }
109
+ if (run.mainSessionFile !== null) {
110
+ const raw = readSession(run.mainSessionFile)
111
+ if (raw !== null) {
112
+ const inWindow = parseSessionEntries(raw).filter((entry) => {
113
+ const ms = entryMs(entry)
114
+ return ms !== null && ms >= run.startMs && ms <= run.endMs
115
+ })
116
+ add('main', 'main', inWindow)
117
+ }
118
+ }
119
+ run.workers.forEach((worker, index) => {
120
+ const raw = readSession(worker.sessionFile)
121
+ if (raw === null) return
122
+ add(worker.role, `${worker.role}-${index + 1}`, parseSessionEntries(raw))
123
+ })
124
+ return rows
125
+ }
126
+
127
+ /** Span attributes for the run's trace span (strings only, like every span). */
128
+ export function adhocSpanAttributes(
129
+ run: AdhocRun,
130
+ rows: readonly AdhocSessionRow[],
131
+ ): Record<string, string> {
132
+ let cost = 0
133
+ let input = 0
134
+ let output = 0
135
+ let cacheRead = 0
136
+ let cacheWrite = 0
137
+ for (const row of rows) {
138
+ cost += row.cost
139
+ input += row.input
140
+ output += row.output
141
+ cacheRead += row.cacheRead
142
+ cacheWrite += row.cacheWrite
143
+ }
144
+ const attrs: Record<string, string> = {
145
+ 'adhoc.run': run.id,
146
+ 'adhoc.kind': run.kind,
147
+ 'adhoc.target': run.target,
148
+ 'adhoc.duration_s': String(Math.max(0, (run.endMs - run.startMs) / 1000)),
149
+ 'adhoc.cost_usd': String(cost),
150
+ 'adhoc.tokens.input': String(input),
151
+ 'adhoc.tokens.output': String(output),
152
+ 'adhoc.tokens.cache_read': String(cacheRead),
153
+ 'adhoc.tokens.cache_write': String(cacheWrite),
154
+ }
155
+ const reviewer = run.workers[0]
156
+ if (reviewer !== undefined) attrs['adhoc.session_file'] = reviewer.sessionFile
157
+ return attrs
158
+ }
159
+
160
+ /** Prometheus exposition for one run. Pure; unreadable sessions add nothing. */
161
+ export function buildAdhocBody(
162
+ run: AdhocRun,
163
+ readSession: (file: string) => string | null,
164
+ ): string {
165
+ const base = { run: run.id, kind: run.kind, target: run.target }
166
+ const lines: string[] = []
167
+ lines.push(
168
+ `pi_flow_adhoc_start_seconds{${labels(base)}} ${run.startMs / 1000}`,
169
+ )
170
+ const seconds = Math.max(0, (run.endMs - run.startMs) / 1000)
171
+ lines.push(`pi_flow_adhoc_duration_seconds{${labels(base)}} ${seconds}`)
172
+ for (const row of summarizeAdhoc(run, readSession)) {
173
+ const rowLabels = { ...base, role: row.role, session: row.session }
174
+ lines.push(`pi_flow_adhoc_cost_usd{${labels(rowLabels)}} ${row.cost}`)
175
+ const kinds: Array<[string, number]> = [
176
+ ['input', row.input],
177
+ ['output', row.output],
178
+ ['cacheRead', row.cacheRead],
179
+ ['cacheWrite', row.cacheWrite],
180
+ ]
181
+ for (const [type, value] of kinds) {
182
+ lines.push(
183
+ `pi_flow_adhoc_tokens_total{${labels({ ...rowLabels, type })}} ${value}`,
184
+ )
185
+ }
186
+ }
187
+ return `${lines.join('\n')}\n`
188
+ }
189
+
190
+ export interface AdhocDeps {
191
+ now: () => number
192
+ getSessionFile: () => string | null
193
+ readSession: (file: string) => string | null
194
+ /** Replace the Pushgateway group for the run. Failures are swallowed. */
195
+ push: (runId: string, body: string) => Promise<unknown>
196
+ /** True while a /flow run is active: tracking is skipped. */
197
+ flowActive: () => boolean
198
+ /**
199
+ * Trace hooks (telemetry). begin: export the zero-length root marker now;
200
+ * nest=true (main-session run) also nests spans made from now on under it,
201
+ * nest=false (worker run: its work happens in another process) does not.
202
+ * end: export the "<kind> run" span ONCE with the real duration, cost and
203
+ * tokens (never update in place; Tempo keeps both copies of a re-sent id).
204
+ */
205
+ trace?: {
206
+ begin: (run: AdhocRun, nest: boolean) => void
207
+ end: (run: AdhocRun, attributes: Record<string, string>) => void
208
+ }
209
+ }
210
+
211
+ export interface AdhocTracker {
212
+ beginMain: (
213
+ kind: AdhocKind,
214
+ target: string,
215
+ singleTurn: boolean,
216
+ ) => AdhocRun | null
217
+ beginWorker: (kind: AdhocKind, target: string) => AdhocRun | null
218
+ addWorker: (run: AdhocRun | null, worker: AdhocWorker) => void
219
+ finish: (run: AdhocRun | null) => Promise<void>
220
+ /** agent_settled: extend the open main-session run and push. */
221
+ settled: () => Promise<void>
222
+ /** Close the open main-session run (flow start / session shutdown). */
223
+ closeMain: () => Promise<void>
224
+ }
225
+
226
+ export function createAdhocTracker(deps: AdhocDeps): AdhocTracker {
227
+ let mainRun: AdhocRun | null = null
228
+ let mainSingleTurn = false
229
+
230
+ function endTrace(run: AdhocRun): void {
231
+ if (deps.trace === undefined) return
232
+ try {
233
+ deps.trace.end(
234
+ run,
235
+ adhocSpanAttributes(run, summarizeAdhoc(run, deps.readSession)),
236
+ )
237
+ } catch {
238
+ // best-effort by design
239
+ }
240
+ }
241
+
242
+ async function pushRun(run: AdhocRun): Promise<void> {
243
+ try {
244
+ await deps.push(run.id, buildAdhocBody(run, deps.readSession))
245
+ } catch {
246
+ // best-effort by design
247
+ }
248
+ }
249
+
250
+ function newRun(kind: AdhocKind, target: string, main: boolean): AdhocRun {
251
+ const startMs = deps.now()
252
+ let mainSessionFile: string | null = null
253
+ if (main) mainSessionFile = deps.getSessionFile()
254
+ return {
255
+ id: adhocRunId(kind, target, startMs),
256
+ kind,
257
+ target,
258
+ startMs,
259
+ endMs: startMs,
260
+ mainSessionFile,
261
+ workers: [],
262
+ }
263
+ }
264
+
265
+ async function closeMain(): Promise<void> {
266
+ const run = mainRun
267
+ mainRun = null
268
+ if (run !== null) {
269
+ run.endMs = deps.now()
270
+ endTrace(run)
271
+ await pushRun(run)
272
+ }
273
+ }
274
+
275
+ return {
276
+ beginMain(kind, target, singleTurn) {
277
+ if (deps.flowActive()) return null
278
+ void closeMain()
279
+ mainRun = newRun(kind, target, true)
280
+ mainSingleTurn = singleTurn
281
+ deps.trace?.begin(mainRun, true)
282
+ void pushRun(mainRun)
283
+ return mainRun
284
+ },
285
+ beginWorker(kind, target) {
286
+ if (deps.flowActive()) return null
287
+ const run = newRun(kind, target, false)
288
+ deps.trace?.begin(run, false)
289
+ return run
290
+ },
291
+ addWorker(run, worker) {
292
+ if (run === null || worker.sessionFile.length === 0) return
293
+ run.workers.push(worker)
294
+ },
295
+ async finish(run) {
296
+ if (run === null) return
297
+ run.endMs = deps.now()
298
+ endTrace(run)
299
+ await pushRun(run)
300
+ },
301
+ async settled() {
302
+ if (mainRun === null) return
303
+ mainRun.endMs = deps.now()
304
+ await pushRun(mainRun)
305
+ if (mainSingleTurn) {
306
+ endTrace(mainRun)
307
+ mainRun = null
308
+ }
309
+ },
310
+ closeMain,
311
+ }
312
+ }
313
+
314
+ // AIDEV-NOTE: module-level handle so the command modules (phase-command,
315
+ // pr-quality, review) can report without threading a dependency through
316
+ // every registration. index.ts configures it once; unconfigured = no-ops.
317
+ let current: AdhocTracker | null = null
318
+
319
+ export function configureAdhoc(tracker: AdhocTracker | null): void {
320
+ current = tracker
321
+ }
322
+
323
+ export function adhocBeginMain(
324
+ kind: AdhocKind,
325
+ target: string,
326
+ singleTurn: boolean,
327
+ ): AdhocRun | null {
328
+ if (current === null) return null
329
+ return current.beginMain(kind, target, singleTurn)
330
+ }
331
+
332
+ export function adhocBeginWorker(
333
+ kind: AdhocKind,
334
+ target: string,
335
+ ): AdhocRun | null {
336
+ if (current === null) return null
337
+ return current.beginWorker(kind, target)
338
+ }
339
+
340
+ export function adhocAddWorker(
341
+ run: AdhocRun | null,
342
+ worker: AdhocWorker,
343
+ ): void {
344
+ current?.addWorker(run, worker)
345
+ }
346
+
347
+ export function adhocFinish(run: AdhocRun | null): Promise<void> {
348
+ if (current === null) return Promise.resolve()
349
+ return current.finish(run)
350
+ }
351
+
352
+ export function adhocSettled(): Promise<void> {
353
+ if (current === null) return Promise.resolve()
354
+ return current.settled()
355
+ }
356
+
357
+ export function adhocCloseMain(): Promise<void> {
358
+ if (current === null) return Promise.resolve()
359
+ return current.closeMain()
360
+ }