@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,281 @@
1
+ // AIDEV-NOTE (PMR-2EGV 2.2): the guarded terminal purge. The homelab
2
+ // Pushgateway MERGES on write (PMR-WBC2 note in flow/push.ts), so the render
3
+ // guard that stops emitting `pi_flow_phase` on done/stale runs can never
4
+ // remove the series stored while the run was still active — an omitted line
5
+ // is never deleted. This module is the removal half of terminal publication:
6
+ // when a run's derived state retires the phase gauge (done/stale — see
7
+ // isPhaseRetiredState in flow/state-metrics.ts), the cost autopush reads the
8
+ // stored group back, decides with the PURE `planTerminalPurge`, DELETEs the
9
+ // group only when the fresh body provably contains every stored series except
10
+ // the purge targets, and then lets the normal POST recreate the group without
11
+ // the residue. The guard is the whole safety case: a fresh body that is
12
+ // missing a stored non-target series (e.g. a rotated session file lost a cost
13
+ // row) must SKIP the delete — losing the residue is recoverable, losing cost
14
+ // history is not.
15
+ //
16
+ // AIDEV-NOTE (PMR-3W5K): beyond the rotated-session cost row, two known
17
+ // stored-only series make the guard skip BY DESIGN (fail-closed), leaving the
18
+ // pi_flow_phase/pi_flow_step residue in place:
19
+ // 1. Old-title residual — pi_flow_run_title_info renders last-title-wins
20
+ // (flow/run-health.ts), but on the merge-on-write gateway (PMR-WBC2) a
21
+ // resumed run whose ticket was renamed stores the NEW title alongside
22
+ // the OLD one (a different title label is a different series; merge
23
+ // never deletes). The fresh body carries only the current title, so the
24
+ // stored old-title variant is a missing non-target series → skip.
25
+ // 2. Stored v1 residue — groups written before the PMR-ZV9Y 7.1 v1
26
+ // retirement still serve pi_flow_run_status / pi_flow_run_halt_reason /
27
+ // pi_flow_human_wait_seconds / pi_flow_gate_wait_seconds; no fresh body
28
+ // ever contains them → skip.
29
+ // Both are safe: the residue stays served, the cost/history series are
30
+ // untouched, and the caller's warning names the manual cleanup runbook —
31
+ // DELETE the pushgateway group, then /flow-cost <ref> --push (purgeWarning in
32
+ // flow/cost-autopush.ts). Do NOT weaken the guard to purge past these cases:
33
+ // an automatic delete that ignores a stored-only series is exactly the data
34
+ // loss the guard exists to prevent.
35
+ //
36
+ // Node-only like its push.ts dependencies: no pi runtime imports.
37
+
38
+ import type { GroupBodyResult, PushResult } from './push.ts'
39
+
40
+ /**
41
+ * The only metric families the terminal purge removes: the two gauges the
42
+ * render path suppresses on done/stale (pi_flow_phase by PMR-2EGV, the
43
+ * open-step pi_flow_step by PMR-ZV9Y P3a). Matched on the EXACT metric name —
44
+ * the cumulative siblings `pi_flow_phase_seconds` / `pi_flow_step_seconds`
45
+ * are durations, not in-flight evidence, and must survive.
46
+ */
47
+ const PURGE_TARGET_NAMES: ReadonlySet<string> = new Set([
48
+ 'pi_flow_phase',
49
+ 'pi_flow_step',
50
+ ])
51
+
52
+ /**
53
+ * Labels the gateway injects from the group URL (or itself) rather than from
54
+ * our body: `job`/`mode` come from the group path, `instance` is added by the
55
+ * Pushgateway on exposition. The stored body carries them, the fresh
56
+ * `buildPushBody` output does not — so series identity strips them from BOTH
57
+ * sides, or the superset guard would fail on every group.
58
+ */
59
+ const INJECTED_LABEL_KEYS: ReadonlySet<string> = new Set([
60
+ 'job',
61
+ 'mode',
62
+ 'instance',
63
+ ])
64
+
65
+ // AIDEV-NOTE (PMR-8NJZ): the two CURRENT-STATE families — the only series
66
+ // whose `state`/`reason` label values are normalized out of the superset
67
+ // identity. A terminal publication INTENTIONALLY replaces every prior
68
+ // current-state variant (running/waiting) with the fresh terminal one
69
+ // (done/stale), so the stored `pi_flow_state{state="running"}` pair can
70
+ // never appear in the fresh body verbatim — treating that difference as
71
+ // lost history made the guard skip every real terminal purge (verified live
72
+ // on PMR-V5AH). This normalization is scoped to EXACTLY these two family
73
+ // names and to EXACTLY the state/reason labels: every other identity label
74
+ // (ref, and any future non-state dimension) stays significant, and no other
75
+ // family (cost/title/durations/wait/step_seconds/…) is touched — a fresh
76
+ // body missing a stored series of any of those still SKIPs, so the
77
+ // cost/history protection is not weakened. A fresh body that lacks the
78
+ // current-state family entirely also still SKIPs (fail-closed): the stored
79
+ // identity is then absent from the fresh identity set like any other
80
+ // missing series.
81
+ const CURRENT_STATE_NAMES: ReadonlySet<string> = new Set([
82
+ 'pi_flow_state',
83
+ 'pi_flow_state_start_seconds',
84
+ ])
85
+
86
+ /** Label keys excluded from the identity of the current-state families. */
87
+ const CURRENT_STATE_VARIABLE_LABEL_KEYS: ReadonlySet<string> = new Set([
88
+ 'state',
89
+ 'reason',
90
+ ])
91
+
92
+ export type TerminalPurgeDecision =
93
+ | { action: 'purge' }
94
+ | { action: 'post' }
95
+ | { action: 'skip'; reason: string }
96
+
97
+ /** One parsed exposition line: the metric name plus its identity labels. */
98
+ interface SeriesLine {
99
+ name: string
100
+ /** Normalized identity: injected labels stripped, order normalized. */
101
+ identity: string
102
+ }
103
+
104
+ /** Extract `key="value"` pairs (Prometheus escaping: `\\`, `\"`, `\n`). */
105
+ function labelPairs(text: string): Array<{ key: string; value: string }> {
106
+ const pairs: Array<{ key: string; value: string }> = []
107
+ const pattern = /([A-Za-z_][A-Za-z0-9_]*)="((?:\\.|[^"\\])*)"/g
108
+ for (const match of text.matchAll(pattern)) {
109
+ const value = match[2]
110
+ .replace(/\\n/g, '\n')
111
+ .replace(/\\"/g, '"')
112
+ .replace(/\\\\/g, '\\')
113
+ pairs.push({ key: match[1], value })
114
+ }
115
+ return pairs
116
+ }
117
+
118
+ /** Parse one non-comment exposition line; null when there is no metric name. */
119
+ function parseSeriesLine(line: string): SeriesLine | null {
120
+ const trimmed = line.trim()
121
+ if (trimmed.length === 0) return null
122
+ if (trimmed.startsWith('#')) return null
123
+ const open = trimmed.indexOf('{')
124
+ let name: string
125
+ let identity = ''
126
+ if (open < 0) {
127
+ const space = trimmed.indexOf(' ')
128
+ if (space < 0) name = trimmed
129
+ else name = trimmed.slice(0, space)
130
+ } else {
131
+ name = trimmed.slice(0, open).trim()
132
+ const close = trimmed.lastIndexOf('}')
133
+ if (close > open) {
134
+ const pairs = labelPairs(trimmed.slice(open + 1, close))
135
+ // PMR-8NJZ: on the two current-state families the state/reason label
136
+ // values are per-publication, not identity — see CURRENT_STATE_NAMES.
137
+ const stateFamily = CURRENT_STATE_NAMES.has(name)
138
+ const kept = pairs.filter((pair) => {
139
+ if (INJECTED_LABEL_KEYS.has(pair.key)) return false
140
+ if (stateFamily && CURRENT_STATE_VARIABLE_LABEL_KEYS.has(pair.key)) {
141
+ return false
142
+ }
143
+ return true
144
+ })
145
+ kept.sort((a, b) => {
146
+ const left = `${a.key}=${a.value}`
147
+ const right = `${b.key}=${b.value}`
148
+ if (left < right) return -1
149
+ if (left > right) return 1
150
+ return 0
151
+ })
152
+ identity = kept.map((pair) => `${pair.key}="${pair.value}"`).join(',')
153
+ }
154
+ }
155
+ if (name.length === 0) return null
156
+ return { name, identity }
157
+ }
158
+
159
+ function seriesLines(bodyText: string): SeriesLine[] {
160
+ const out: SeriesLine[] = []
161
+ for (const line of bodyText.split('\n')) {
162
+ const parsed = parseSeriesLine(line)
163
+ if (parsed !== null) out.push(parsed)
164
+ }
165
+ return out
166
+ }
167
+
168
+ /** Human-readable series name for a skip reason: name + identity labels. */
169
+ function seriesDisplay(line: SeriesLine): string {
170
+ if (line.identity.length === 0) return line.name
171
+ return `${line.name}{${line.identity}}`
172
+ }
173
+
174
+ /**
175
+ * The pure purge decision. `storedBody` is the group read back from the
176
+ * gateway (fetchGroupBody output); `freshBody` is the terminal body about to
177
+ * be POSTed. Rules:
178
+ * - no stored pi_flow_phase/pi_flow_step series → 'post' (nothing to purge,
179
+ * the plain POST is enough);
180
+ * - residue present AND every stored NON-target series is also in the fresh
181
+ * body (same metric name + same label set after stripping the injected
182
+ * job/mode/instance labels; sample values ignored) → 'purge'. The two
183
+ * current-state families (pi_flow_state / pi_flow_state_start_seconds)
184
+ * additionally ignore their state/reason label values — a terminal
185
+ * publication intentionally replaces the prior current-state variant
186
+ * (PMR-8NJZ) — while a fresh body missing those families entirely still
187
+ * skips like any other missing series;
188
+ * - any stored non-target series missing from the fresh body → 'skip',
189
+ * naming the missing series (deleting would lose it — the merge-on-write
190
+ * gateway keeps it otherwise, and the pair-runbook cleans it later).
191
+ * Known intentional skip cases (PMR-3W5K, see the header note): a stored
192
+ * old pi_flow_run_title_info title variant (renamed ticket, merge-on-write
193
+ * keeps both) and stored retired v1 series (pi_flow_run_status et al).
194
+ * The safe manual cleanup for both is the runbook the caller's warning
195
+ * names: DELETE the pushgateway group, then /flow-cost <ref> --push.
196
+ */
197
+ export function planTerminalPurge(
198
+ storedBody: string,
199
+ freshBody: string,
200
+ ): TerminalPurgeDecision {
201
+ const stored = seriesLines(storedBody)
202
+ const targets = stored.filter((line) => PURGE_TARGET_NAMES.has(line.name))
203
+ if (targets.length === 0) return { action: 'post' }
204
+ const freshIdentities = new Set(
205
+ seriesLines(freshBody).map((line) => `${line.name}{${line.identity}}`),
206
+ )
207
+ const missing: string[] = []
208
+ for (const line of stored) {
209
+ if (PURGE_TARGET_NAMES.has(line.name)) continue
210
+ const identity = `${line.name}{${line.identity}}`
211
+ if (!freshIdentities.has(identity)) missing.push(seriesDisplay(line))
212
+ }
213
+ if (missing.length > 0) {
214
+ return {
215
+ action: 'skip',
216
+ reason: `stored series missing from the fresh body: ${missing.join('; ')}`,
217
+ }
218
+ }
219
+ return { action: 'purge' }
220
+ }
221
+
222
+ export interface TerminalPurgeDeps {
223
+ /** Read one stored group back (full-dump GET, filtered — push.ts). */
224
+ fetchGroupBody: (
225
+ ref: string,
226
+ mode: 'work' | 'personal',
227
+ ) => Promise<GroupBodyResult>
228
+ /** DELETE one stored group (push.ts). */
229
+ deleteGroup: (ref: string, mode: 'work' | 'personal') => Promise<PushResult>
230
+ }
231
+
232
+ /**
233
+ * What the caller turns into notify lines. 'purged' is info; 'skipped' and
234
+ * both failure kinds are warnings (the POST still happens — the purge is
235
+ * best-effort cleanup, never a blocker for the terminal push).
236
+ */
237
+ export type TerminalPurgeOutcome =
238
+ | { kind: 'purged' }
239
+ | { kind: 'no-residue' }
240
+ | { kind: 'skipped'; reason: string }
241
+ | { kind: 'read-failed'; error: string }
242
+ | { kind: 'delete-failed'; error: string }
243
+
244
+ /**
245
+ * Read back → decide → DELETE (only on 'purge'). Never throws: a transport
246
+ * failure on either seam becomes a typed outcome so the caller can warn and
247
+ * still do the plain POST. A failed DELETE must surface as 'delete-failed'
248
+ * (NOT silently proceed as if purged) — the caller's POST then recreates
249
+ * nothing, the residue simply stays stored.
250
+ */
251
+ export async function purgeTerminalResidue(
252
+ deps: TerminalPurgeDeps,
253
+ ref: string,
254
+ mode: 'work' | 'personal',
255
+ freshBody: string,
256
+ ): Promise<TerminalPurgeOutcome> {
257
+ let stored: GroupBodyResult
258
+ try {
259
+ stored = await deps.fetchGroupBody(ref, mode)
260
+ } catch (error) {
261
+ const message = error instanceof Error ? error.message : String(error)
262
+ return { kind: 'read-failed', error: message }
263
+ }
264
+ if (!stored.ok) return { kind: 'read-failed', error: stored.error }
265
+ const decision = planTerminalPurge(stored.body, freshBody)
266
+ if (decision.action === 'post') return { kind: 'no-residue' }
267
+ if (decision.action === 'skip') {
268
+ return { kind: 'skipped', reason: decision.reason }
269
+ }
270
+ let deleted: PushResult
271
+ try {
272
+ deleted = await deps.deleteGroup(ref, mode)
273
+ } catch (error) {
274
+ const message = error instanceof Error ? error.message : String(error)
275
+ return { kind: 'delete-failed', error: message }
276
+ }
277
+ if (!deleted.ok) {
278
+ return { kind: 'delete-failed', error: deleted.error ?? 'unknown error' }
279
+ }
280
+ return { kind: 'purged' }
281
+ }
@@ -0,0 +1,19 @@
1
+ // AIDEV-NOTE: PMR-2H3R — phase prompts can be injected while the prior
2
+ // phase's turn is still open. A settle from that generation (or an older one)
3
+ // carries no evidence about the new phase and must not be consumed. A missing
4
+ // counter preserves standalone harnesses without turn lifecycle wiring;
5
+ // production supplies a session-monotonic count of turn_start events.
6
+ export interface TurnGenerationSource {
7
+ getTurnGeneration?(): number
8
+ }
9
+
10
+ export function isPrePromptSettle(
11
+ promptGeneration: number | null,
12
+ source: TurnGenerationSource,
13
+ ): boolean {
14
+ const settledGeneration = source.getTurnGeneration?.()
15
+ if (promptGeneration === null || settledGeneration === undefined) {
16
+ return false
17
+ }
18
+ return settledGeneration <= promptGeneration
19
+ }