@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,432 @@
1
+ // AIDEV-NOTE: Herdr adapter for the flow run-state viewer (ported from
2
+ // pi-workflows' herdr-viewer design). Uses ONLY public herdr CLI verbs
3
+ // through pi.exec with bounded timeouts and bounded JSON parsing. No polling,
4
+ // no state file — and no daemon of its own (deliberate stance, updated for
5
+ // PMR-XTQQ: pi-flow now owns exactly one daemon, the durable run server in
6
+ // server/daemon.ts; this viewer stays daemon-free and only reads files).
7
+ // Dedupe keys off the pane LABEL ("flow · <ref>"), which survives Pi
8
+ // reloads because it lives in herdr's own snapshot.
9
+
10
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
11
+ import { getAgentDir } from '@earendil-works/pi-coding-agent'
12
+ import { journalPathFor, runStatePath } from '../run-state.ts'
13
+ import { parseInstalledPlugin } from './sync.ts'
14
+
15
+ export const HERDR_PLUGIN_ID = 'gtheys.pi-my-rifle-ext'
16
+ export const HERDR_PLUGIN_ENTRYPOINT = 'flow'
17
+ export const VIEWER_LABEL_PREFIX = 'flow · '
18
+
19
+ const COMMAND_TIMEOUT_MS = 5_000
20
+ const MAX_JSON_CHARS = 1_000_000
21
+
22
+ export const VIEWER_PLACEMENTS = [
23
+ 'right',
24
+ 'below',
25
+ 'left',
26
+ 'above',
27
+ 'tab',
28
+ ] as const
29
+
30
+ export type ViewerPlacement = (typeof VIEWER_PLACEMENTS)[number]
31
+
32
+ export type HerdrCapability =
33
+ | { available: true }
34
+ | { available: false; reason: string }
35
+
36
+ export type ViewerOpenResult = { paneId: string; reused: boolean }
37
+
38
+ type Exec = ExtensionAPI['exec']
39
+
40
+ type HerdrPane = {
41
+ paneId: string
42
+ tabId: string
43
+ workspaceId: string
44
+ label?: string
45
+ }
46
+
47
+ export function parseViewerPlacement(
48
+ value: string,
49
+ ): ViewerPlacement | undefined {
50
+ return VIEWER_PLACEMENTS.find((placement) => placement === value)
51
+ }
52
+
53
+ // AIDEV-NOTE: Pure placement-resolution chain (PMR-9Q2S 3.2). Takes an
54
+ // ALREADY-PARSED arg — the /flow-view handler keeps its own raw-string
55
+ // validation/warning path. Order: explicit arg > configured value > prompt.
56
+ export type PlacementDecision =
57
+ | { kind: 'placement'; placement: ViewerPlacement }
58
+ | { kind: 'prompt' }
59
+
60
+ export function decidePlacement(
61
+ arg: ViewerPlacement | undefined,
62
+ configured: ViewerPlacement | undefined,
63
+ ): PlacementDecision {
64
+ if (arg !== undefined) {
65
+ return { kind: 'placement', placement: arg }
66
+ }
67
+ if (configured !== undefined) {
68
+ return { kind: 'placement', placement: configured }
69
+ }
70
+ return { kind: 'prompt' }
71
+ }
72
+
73
+ // AIDEV-NOTE (PMR-ZGPY 5.3): pane labels double as herdr dedupe keys, so live
74
+ // (`flow · <ref>`) and replay (`flow · <ref> · replay`) labels MUST stay
75
+ // distinct — hence the load-bearing ` · replay` suffix. Keep these two strings
76
+ // in sync with composePaneLabel in plugins/herdr/flow-viewer.mjs (cannot be
77
+ // imported from TS here; byte-equality is pinned in test/herdr-viewer.test.ts
78
+ // by importing the .mjs from the test side). Live label is byte-identical to
79
+ // pre-replay output (ISC-8/ISC-10).
80
+ export function viewerPaneLabel(ref: string): string {
81
+ return `${VIEWER_LABEL_PREFIX}${ref}`
82
+ }
83
+
84
+ export const REPLAY_LABEL_SUFFIX = ' · replay'
85
+
86
+ export function replayPaneLabel(ref: string): string {
87
+ return `${viewerPaneLabel(ref)}${REPLAY_LABEL_SUFFIX}`
88
+ }
89
+
90
+ export type FlowViewerMode = 'live' | 'replay'
91
+
92
+ // AIDEV-NOTE: mirrors composePaneLabel in plugins/herdr/flow-viewer.mjs.
93
+ function paneLabelFor(ref: string, mode: FlowViewerMode): string {
94
+ if (mode === 'replay') {
95
+ return replayPaneLabel(ref)
96
+ }
97
+ return viewerPaneLabel(ref)
98
+ }
99
+
100
+ /**
101
+ * Pure env-arg builder for the herdr plugin pane open (PMR-WF74). Passes
102
+ * PI_FLOW_REF, PI_FLOW_RUN_FILE and PI_FLOW_JOURNAL_FILE so the pane prefers
103
+ * the journal path from env and only falls back to deriving it from runFile.
104
+ */
105
+ export function buildViewerOpenEnv(
106
+ ref: string,
107
+ runFile: string,
108
+ mode: FlowViewerMode = 'live',
109
+ ): string[] {
110
+ const args = [
111
+ '--env',
112
+ `PI_FLOW_REF=${ref}`,
113
+ '--env',
114
+ `PI_FLOW_RUN_FILE=${runFile}`,
115
+ '--env',
116
+ `PI_FLOW_JOURNAL_FILE=${journalPathFor(runFile)}`,
117
+ ]
118
+ if (mode === 'replay') {
119
+ args.push('--env', 'PI_FLOW_VIEWER_MODE=replay')
120
+ }
121
+ return args
122
+ }
123
+
124
+ /** Strict ref charset — the same rule as runFileName, enforced at the boundary. */
125
+ export function isValidRef(ref: string): boolean {
126
+ return /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(ref)
127
+ }
128
+
129
+ // AIDEV-NOTE: Pure version-status decision for the /flow-view gate
130
+ // (PMR-9Q2S 2.2). Disabled wins over drift — a disabled plugin cannot render
131
+ // the pane even when versions match, so the message must say "disabled".
132
+ export type PluginVersionStatus =
133
+ | { status: 'ok' }
134
+ | { status: 'not-installed' }
135
+ | { status: 'disabled'; installed: string }
136
+ | { status: 'drift'; installed: string; expected: string }
137
+
138
+ export function pluginVersionStatus(
139
+ installed: { version: string; enabled: boolean } | undefined,
140
+ expected: string,
141
+ ): PluginVersionStatus {
142
+ if (installed === undefined) {
143
+ return { status: 'not-installed' }
144
+ }
145
+ if (!installed.enabled) {
146
+ return { status: 'disabled', installed: installed.version }
147
+ }
148
+ if (installed.version !== expected) {
149
+ return { status: 'drift', installed: installed.version, expected }
150
+ }
151
+ return { status: 'ok' }
152
+ }
153
+
154
+ export class FlowHerdrViewer {
155
+ private readonly knownPanes = new Map<string, string>()
156
+ private readonly opening = new Map<string, Promise<ViewerOpenResult>>()
157
+ private readonly exec: Exec
158
+ private readonly env: NodeJS.ProcessEnv
159
+
160
+ // AIDEV-NOTE: no constructor parameter properties — Node's strip-only TS
161
+ // mode (the repo test runner) rejects them.
162
+ constructor(exec: Exec, env: NodeJS.ProcessEnv = process.env) {
163
+ this.exec = exec
164
+ this.env = env
165
+ }
166
+
167
+ async probe(): Promise<HerdrCapability> {
168
+ if (this.env.HERDR_ENV !== '1') {
169
+ return { available: false, reason: 'Pi is not running in Herdr.' }
170
+ }
171
+ try {
172
+ await this.currentPane()
173
+ } catch (error) {
174
+ return { available: false, reason: errorMessage(error) }
175
+ }
176
+ return { available: true }
177
+ }
178
+
179
+ async open(
180
+ ref: string,
181
+ placement: ViewerPlacement,
182
+ mode: FlowViewerMode = 'live',
183
+ ): Promise<ViewerOpenResult> {
184
+ // AIDEV-NOTE (PMR-ZGPY 5.3): dedupe key is the pane LABEL string, so live
185
+ // and replay panes for the same ref never collide. Live path byte-identical.
186
+ const key = paneLabelFor(ref, mode)
187
+ const pending = this.opening.get(key)
188
+ if (pending !== undefined) return await pending
189
+
190
+ const opening = this.openOnce(ref, placement, mode).finally(() => {
191
+ if (this.opening.get(key) === opening) this.opening.delete(key)
192
+ })
193
+ this.opening.set(key, opening)
194
+ return await opening
195
+ }
196
+
197
+ private async openOnce(
198
+ ref: string,
199
+ placement: ViewerPlacement,
200
+ mode: FlowViewerMode,
201
+ ): Promise<ViewerOpenResult> {
202
+ const label = paneLabelFor(ref, mode)
203
+ const existing = await this.findAndFocus(label)
204
+ if (existing !== undefined) {
205
+ return { paneId: existing, reused: true }
206
+ }
207
+ const caller = await this.currentPane()
208
+ const runFile = runStatePath(getAgentDir(), ref)
209
+ if (runFile === null) {
210
+ throw new Error(`Invalid flow ref: ${ref}`)
211
+ }
212
+ const args = [
213
+ 'plugin',
214
+ 'pane',
215
+ 'open',
216
+ '--plugin',
217
+ HERDR_PLUGIN_ID,
218
+ '--entrypoint',
219
+ HERDR_PLUGIN_ENTRYPOINT,
220
+ ...buildViewerOpenEnv(ref, runFile, mode),
221
+ '--focus',
222
+ ]
223
+ if (placement === 'tab') {
224
+ args.push('--placement', 'tab', '--workspace', caller.workspaceId)
225
+ } else {
226
+ args.push(
227
+ '--placement',
228
+ 'split',
229
+ '--target-pane',
230
+ caller.paneId,
231
+ '--direction',
232
+ placement === 'below' || placement === 'above' ? 'down' : 'right',
233
+ )
234
+ }
235
+ const opened = parseOpenedPane(await this.runJson('herdr', args))
236
+ if (placement === 'left' || placement === 'above') {
237
+ try {
238
+ await this.run('herdr', [
239
+ 'pane',
240
+ 'swap',
241
+ '--source-pane',
242
+ opened.paneId,
243
+ '--target-pane',
244
+ caller.paneId,
245
+ ])
246
+ } catch (error) {
247
+ await this.run('herdr', [
248
+ 'plugin',
249
+ 'pane',
250
+ 'close',
251
+ opened.paneId,
252
+ ]).catch(() => undefined)
253
+ throw error
254
+ }
255
+ }
256
+ this.knownPanes.set(label, opened.paneId)
257
+ return { paneId: opened.paneId, reused: false }
258
+ }
259
+
260
+ private async findAndFocus(label: string): Promise<string | undefined> {
261
+ const knownPaneId = this.knownPanes.get(label)
262
+ if (knownPaneId !== undefined) {
263
+ try {
264
+ await this.run('herdr', ['plugin', 'pane', 'focus', knownPaneId])
265
+ return knownPaneId
266
+ } catch {
267
+ this.knownPanes.delete(label)
268
+ }
269
+ }
270
+ const existing = await this.findByLabel(label)
271
+ if (existing === undefined) return undefined
272
+ try {
273
+ await this.run('herdr', ['plugin', 'pane', 'focus', existing.paneId])
274
+ this.knownPanes.set(label, existing.paneId)
275
+ return existing.paneId
276
+ } catch {
277
+ // The pane can close between the snapshot and the focus request.
278
+ return undefined
279
+ }
280
+ }
281
+
282
+ // AIDEV-NOTE (PMR-ZGPY 5.3): matches the EXACT label for the requested mode
283
+ // — a live open must never focus a replay pane for the same ref and vice
284
+ // versa (ISC-10 label-dedupe protection).
285
+ async find(
286
+ ref: string,
287
+ mode: FlowViewerMode = 'live',
288
+ ): Promise<HerdrPane | undefined> {
289
+ return this.findByLabel(paneLabelFor(ref, mode))
290
+ }
291
+
292
+ private async findByLabel(label: string): Promise<HerdrPane | undefined> {
293
+ const snapshot = await this.runJson('herdr', ['api', 'snapshot'])
294
+ return snapshotPanes(snapshot).find((pane) => pane.label === label)
295
+ }
296
+
297
+ async installedPlugin(): Promise<ReturnType<typeof parseInstalledPlugin>> {
298
+ // AIDEV-NOTE: Fail-soft like inspectHerdr's ENOENT path in sync.ts —
299
+ // any herdr failure is treated as not-installed by the /flow-view gate.
300
+ try {
301
+ const stdout = await this.run('herdr', [
302
+ 'plugin',
303
+ 'list',
304
+ '--plugin',
305
+ HERDR_PLUGIN_ID,
306
+ '--json',
307
+ ])
308
+ return parseInstalledPlugin(stdout)
309
+ } catch {
310
+ return undefined
311
+ }
312
+ }
313
+
314
+ private async currentPane(): Promise<HerdrPane> {
315
+ return parseCurrentPane(
316
+ await this.runJson('herdr', ['pane', 'current', '--current']),
317
+ )
318
+ }
319
+
320
+ private async run(command: string, args: string[]): Promise<string> {
321
+ const result = await this.exec(command, args, {
322
+ timeout: COMMAND_TIMEOUT_MS,
323
+ })
324
+ if (result.code !== 0) {
325
+ const message =
326
+ result.stderr.trim() || result.stdout.trim() || `exit ${result.code}`
327
+ throw new Error(`${command} failed: ${boundedText(message)}`)
328
+ }
329
+ return result.stdout
330
+ }
331
+
332
+ private async runJson(command: string, args: string[]): Promise<unknown> {
333
+ const stdout = await this.run(command, args)
334
+ if (stdout.length > MAX_JSON_CHARS) {
335
+ throw new Error(`${command} returned too much data.`)
336
+ }
337
+ try {
338
+ return JSON.parse(stdout) as unknown
339
+ } catch {
340
+ throw new Error(`${command} returned invalid JSON.`)
341
+ }
342
+ }
343
+ }
344
+
345
+ // ── pure parsers, exported for tests ──
346
+
347
+ export function parseCurrentPane(value: unknown): HerdrPane {
348
+ const result = requiredRecord(value, 'result', 'Herdr pane response')
349
+ return paneFromValue(requiredRecord(result, 'pane', 'Herdr pane response'))
350
+ }
351
+
352
+ export function parseOpenedPane(value: unknown): { paneId: string } {
353
+ const result = requiredRecord(value, 'result', 'Herdr plugin pane response')
354
+ const pluginPane = requiredRecord(
355
+ result,
356
+ 'plugin_pane',
357
+ 'Herdr plugin pane response',
358
+ )
359
+ const pane = paneFromValue(
360
+ requiredRecord(pluginPane, 'pane', 'Herdr plugin pane response'),
361
+ )
362
+ return { paneId: pane.paneId }
363
+ }
364
+
365
+ export function snapshotPanes(value: unknown): HerdrPane[] {
366
+ const result = requiredRecord(value, 'result', 'Herdr snapshot')
367
+ const snapshot = requiredRecord(result, 'snapshot', 'Herdr snapshot')
368
+ const panes = arrayValue(snapshot, 'panes')
369
+ if (panes === undefined) throw new Error('Herdr snapshot has no panes.')
370
+ return panes.flatMap((pane) => {
371
+ try {
372
+ return [paneFromValue(pane)]
373
+ } catch {
374
+ return []
375
+ }
376
+ })
377
+ }
378
+
379
+ function paneFromValue(value: unknown): HerdrPane {
380
+ if (!isRecord(value)) throw new Error('Herdr returned an invalid pane.')
381
+ const label = value.label
382
+ return {
383
+ paneId: requiredString(value, 'pane_id', 'Herdr pane'),
384
+ tabId: requiredString(value, 'tab_id', 'Herdr pane'),
385
+ workspaceId: requiredString(value, 'workspace_id', 'Herdr pane'),
386
+ ...(typeof label === 'string' ? { label } : {}),
387
+ }
388
+ }
389
+
390
+ function requiredRecord(
391
+ value: unknown,
392
+ key: string,
393
+ label: string,
394
+ ): Record<string, unknown> {
395
+ if (!isRecord(value)) throw new Error(`${label} is invalid.`)
396
+ const nested = value[key]
397
+ if (!isRecord(nested)) throw new Error(`${label} has no ${key}.`)
398
+ return nested
399
+ }
400
+
401
+ function requiredString(
402
+ value: Record<string, unknown>,
403
+ key: string,
404
+ label: string,
405
+ ): string {
406
+ const nested = value[key]
407
+ if (typeof nested !== 'string' || nested.length === 0) {
408
+ throw new Error(`${label} has no ${key}.`)
409
+ }
410
+ return nested
411
+ }
412
+
413
+ function arrayValue(value: unknown, key: string): unknown[] | undefined {
414
+ const nested = isRecord(value) ? value[key] : undefined
415
+ return Array.isArray(nested) ? nested : undefined
416
+ }
417
+
418
+ function isRecord(value: unknown): value is Record<string, unknown> {
419
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
420
+ }
421
+
422
+ function boundedText(value: string): string {
423
+ const compact = value
424
+ .replace(/[\r\n\t]+/gu, ' ')
425
+ .replace(/ +/gu, ' ')
426
+ .trim()
427
+ return compact.length <= 300 ? compact : `${compact.slice(0, 299)}…`
428
+ }
429
+
430
+ function errorMessage(error: unknown): string {
431
+ return error instanceof Error ? error.message : String(error)
432
+ }
@@ -0,0 +1,21 @@
1
+ // AIDEV-NOTE: Pure /implement arg parsing — same shape as plan/args.ts.
2
+ // Jira-style ref (PROJECT-123) routes to work-mode tooling (jira_create_branch);
3
+ // anything else is a personal aven ref. (PMR-Z2K7: --skip-research removed
4
+ // with the research phase.)
5
+
6
+ import { parseRefKind } from '../flow/ref-kind.ts'
7
+
8
+ export type ImplementArgs =
9
+ | { kind: 'jira'; jiraId: string }
10
+ | { kind: 'aven'; ref: string }
11
+ | { kind: 'help' }
12
+
13
+ export function parseImplementArgs(raw: string): ImplementArgs {
14
+ const parts = raw.trim().split(/\s+/)
15
+ if (parts.length !== 1 || parts[0] === '') return { kind: 'help' }
16
+ const parsed = parseRefKind(parts[0] ?? '')
17
+ if (parsed.kind === 'jira') {
18
+ return { kind: 'jira', jiraId: parsed.jiraId }
19
+ }
20
+ return { kind: 'aven', ref: parsed.ref }
21
+ }
@@ -0,0 +1,98 @@
1
+ // AIDEV-NOTE: Handoff prompts per route, sent via sendUserMessage from the
2
+ // /implement command (same pattern as plan/prompt.ts). Plan routing hands off
3
+ // to the implement-plan-aven skill BY NAME — never reimplemented here. Oneshot
4
+ // and bug routing are pi-flow's own playbooks: worktree isolation (PMR-NJYY),
5
+ // branch derivation (jira_create_branch for work refs; ref-injected
6
+ // conventional branch for personal — feat/<REF>-<slug> during an active flow,
7
+ // bare feat/<slug> outside one, see BRANCH_RULES / PMR-902B), per-task
8
+ // test+commit cycle, retry budget, escalation.
9
+
10
+ export interface ImplementPromptInput {
11
+ mode: 'work' | 'personal'
12
+ ref: string
13
+ route: 'oneshot' | 'plan' | 'bug'
14
+ }
15
+
16
+ function commonRules(ref: string): string {
17
+ return `
18
+ Hard rules for every task in this phase:
19
+ - Implement ONLY inside an isolated git worktree (PMR-NJYY rule). The main checkout is read-only.
20
+ - Retry budget: the flow_run_attempt tool owns it. Run each test attempt and
21
+ report the outcome via flow_run_attempt (ref=${ref}, result with ok,
22
+ lastError, commands, hypothesis). The tool permits 3 total attempts (2
23
+ retries); its escalation result (a tool error naming the commands, last
24
+ error, and hypothesis, also recorded as an aven note) means STOP and
25
+ escalate to the human — never silently continue past a red test or past an
26
+ escalation.
27
+ - Report step evidence via the flow_submit tool after each meaningful
28
+ boundary (plan written, test run, gate-relevant check) — advisory
29
+ journaling only, never a substitute for the phase-completion label.
30
+ - Each task = implement -> run tests -> commit. A task is done only when its test run is green AND the commit landed in the worktree.
31
+ - Follow the repo's commit discipline; use conventional commit subjects.
32
+ - Empty verification commits (evidence markers with no diff): use \`chore:\` — or \`docs:\` only if documentation actually changed — never \`test:\` merely because a test command ran (PMR-DF9B).
33
+ - PHASE COMPLETION LABEL: when ALL work for this phase is green and committed, call the flow_phase_complete tool with ref=${ref} and phase="implement" — it applies the "active" label after re-checking the gates, and its result confirms the label landed. NEVER set the ticket status to "done" in this phase; later phases own that. Direct aven label edits on lifecycle labels are blocked.
34
+ `
35
+ }
36
+
37
+ // AIDEV-NOTE: PMR-902B — personal-flow branch/commit conventions, stated for
38
+ // all three implement routes (this block is interpolated into the plan, bug
39
+ // and oneshot prompts). Branch shape is `<type>/<REF>-<slug>` — never
40
+ // bracketed, git refnames reject `[` — and the worktree tool injects the
41
+ // active flow ref automatically, so the agent must not compose it by hand.
42
+ // Commit subjects keep the ref AFTER the scope (user-decided, mirrors
43
+ // prompts/git.md's Jira rule). The plan route's `Subtask: <subtask-ref>`
44
+ // trailer mandate stays byte-identical: this rule sits beside it, and the
45
+ // review gates still derive per-subtask diff ranges from those trailers.
46
+ const BRANCH_RULES = `
47
+ Branch derivation:
48
+ - Work mode: create the branch via the jira_create_branch tool for the ticket ref.
49
+ - Personal mode: create a conventional branch from the ticket slug via the
50
+ worktree tool — during an active flow the ref is injected automatically
51
+ (feat/<REF>-<slug>, e.g. feat/PMR-AB12-add-save-button); outside a flow,
52
+ bare feat/<slug>.
53
+ Commit subjects (personal mode): embed the flow ref after the scope —
54
+ type(scope): [REF] subject (e.g. feat(pi-flow): [PMR-AB12] add retry budget).
55
+ The Subtask: <subtask-ref> trailer rule is unchanged and still required.`
56
+
57
+ export function buildImplementPrompt(input: ImplementPromptInput): string {
58
+ const header = `Implement phase (PIV flow). Mode: ${input.mode}. Ref: ${input.ref}. Route: ${input.route}.`
59
+
60
+ // AIDEV-NOTE: PMR-JVJN — the plan route used to forbid starting a
61
+ // dep-blocked subtask while feature-plan-aven's contract dep-linked every
62
+ // subtask on its own phase: the first subtask of every phase could never
63
+ // legally start. One rule now: subtasks carry no deps (the N./N.M prefix
64
+ // sort is the execution order); phases chain via deps.
65
+ // aven-tree-contract.test.ts pins this across prompt + skills + docs.
66
+ if (input.route === 'plan') {
67
+ return `${header}
68
+ Invoke the user's implement-plan-aven skill (engineering:implement-plan-aven)
69
+ for ${input.ref} and follow its workflow exactly.
70
+ ${BRANCH_RULES}${commonRules(input.ref)}
71
+ - Walk the epic's subtasks IN ORDER (aven epic list) — subtasks carry no
72
+ dependencies (PMR-JVJN); execution order is the N./N.M title prefix
73
+ sort, and only phases chain via aven deps.
74
+ - EACH subtask gets its own test run + commit; mark it done only then.
75
+ - When spawning a subagent to implement a subtask, pass the subtask's ref as the spawn's \`subtask\` parameter (subagent tool) so cost attribution follows the work (PI_FLOW_SUBTASK env stamp + journal note). Omit it for scouts and general-purpose workers.
76
+ - EVERY commit message ends with a \`Subtask: <subtask-ref>\` trailer naming
77
+ the subtask it implements (e.g. "Subtask: PMR-AB12"). The review gates
78
+ derive per-subtask diff ranges from these trailers; a commit without the
79
+ trailer is unattributed and will be surfaced as such.
80
+ - Keep working until ALL subtasks are done (each marked done only after its own test run + commit); then set the "active" label on ${input.ref} — never mark the epic status done in this phase.`
81
+ }
82
+
83
+ if (input.route === 'bug') {
84
+ return `${header}
85
+ Reproduce-first bug flow for ${input.ref}:
86
+ 1. Read the research artifact's evidence and REPRODUCE the bug first — write a failing test that demonstrates it.
87
+ 2. Fix the bug; the test must turn green and prove the fix.
88
+ 3. Run the full test suite, then commit.
89
+ ${BRANCH_RULES}${commonRules(input.ref)}`
90
+ }
91
+
92
+ return `${header}
93
+ Oneshot flow for ${input.ref}:
94
+ 1. Implement the change in a single implement -> test -> commit cycle.
95
+ 2. Run the test suite; it must be green before the commit lands.
96
+ 3. Once tests are green AND the commit landed, apply the PHASE COMPLETION LABEL rule above (flow_phase_complete with phase="implement").
97
+ ${BRANCH_RULES}${commonRules(input.ref)}`
98
+ }
@@ -0,0 +1,57 @@
1
+ // AIDEV-NOTE: Pure retry-budget state machine (3 TOTAL attempts, so 2 retries
2
+ // before escalate). nextAttempt is the ONLY transition; a failed test never
3
+ // silently passes through — after the 3rd failed attempt the machine returns
4
+ // an escalation record instead of a retry (PMR-2N3C).
5
+ // The "3 attempts total then escalates" acceptance criterion is tested against
6
+ // this module directly with an always-failing attempt (test/implement.test.ts).
7
+ // Invariant: callers must STOP and surface the escalation to the human; the
8
+ // machine itself has no side effects so the caller owns aven notes / status.
9
+
10
+ export interface AttemptResult {
11
+ ok: boolean
12
+ lastError?: string
13
+ commands?: readonly string[]
14
+ hypothesis?: string
15
+ }
16
+
17
+ export interface RetryState {
18
+ attempts: number
19
+ }
20
+
21
+ export type RetryTransition =
22
+ | { status: 'passed' }
23
+ | { status: 'retry'; state: RetryState }
24
+ | {
25
+ status: 'escalate'
26
+ escalation: {
27
+ commands: readonly string[]
28
+ lastError: string
29
+ hypothesis: string
30
+ }
31
+ }
32
+
33
+ // Total failing attempts permitted before escalate (retries = MAX_ATTEMPTS - 1).
34
+ export const MAX_ATTEMPTS = 3
35
+
36
+ export function startRetry(): RetryState {
37
+ return { attempts: 0 }
38
+ }
39
+
40
+ export function nextAttempt(
41
+ state: RetryState,
42
+ result: AttemptResult,
43
+ ): RetryTransition {
44
+ if (result.ok) return { status: 'passed' }
45
+ const attempts = state.attempts + 1
46
+ if (attempts < MAX_ATTEMPTS) {
47
+ return { status: 'retry', state: { attempts } }
48
+ }
49
+ return {
50
+ status: 'escalate',
51
+ escalation: {
52
+ commands: result.commands ?? [],
53
+ lastError: result.lastError ?? 'unknown error',
54
+ hypothesis: result.hypothesis ?? 'no hypothesis recorded',
55
+ },
56
+ }
57
+ }
@@ -0,0 +1,31 @@
1
+ // AIDEV-NOTE: Pure routing for /implement. The gate wiring lives HERE, not in
2
+ // the command handler: canImplement refuses tickets without 'planned' (W76D).
3
+ // (PMR-Z2K7: the research skip gate ('skip-required') was removed with the
4
+ // research phase.)
5
+
6
+ import { canImplement } from '../gates.ts'
7
+
8
+ export type Route = 'oneshot' | 'plan' | 'bug'
9
+ export type RefKind = 'jira' | 'aven'
10
+
11
+ export type RouteResult =
12
+ | { kind: 'ok'; route: Route }
13
+ | { kind: 'refuse'; reason: string }
14
+
15
+ export function routeFor(
16
+ refKind: RefKind,
17
+ labels: readonly string[],
18
+ ): RouteResult {
19
+ void refKind
20
+ const gate = canImplement(labels)
21
+ if (!gate.ok) {
22
+ return { kind: 'refuse', reason: gate.reason ?? 'cannot implement' }
23
+ }
24
+ if (labels.includes('bug')) {
25
+ return { kind: 'ok', route: 'bug' }
26
+ }
27
+ if (labels.includes('plan')) {
28
+ return { kind: 'ok', route: 'plan' }
29
+ }
30
+ return { kind: 'ok', route: 'oneshot' }
31
+ }