@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,287 @@
1
+ // AIDEV-NOTE: PMR-T22H — phase-command factory. The 5 phase commands
2
+ // (/brainstorm, /plan, /implement, /validate, /feedback) share ONE skeleton
3
+ // (parse → resolveMode → resolve ref → commandPhaseInput → buildPhasePrompt
4
+ // → sendOrNotify) so notify wording and gate wiring cannot drift between
5
+ // phases; per-command variance is declared via the hooks below. The /flow
6
+ // loop command does NOT use the factory (it resolves/creates the epic and
7
+ // journals) but shares commandPhaseInput.
8
+
9
+ import type {
10
+ ExtensionAPI,
11
+ ExtensionCommandContext,
12
+ } from '@earendil-works/pi-coding-agent'
13
+ import { adhocBeginMain } from '../adhoc/tracker.ts'
14
+ import {
15
+ avenExec,
16
+ epicHasOpenChildren,
17
+ readAvenLabels,
18
+ } from '../aven/client.ts'
19
+ import { type BrainstormArgs, parseBrainstormArgs } from '../brainstorm/args.ts'
20
+ import { loadConfig, resolveMode } from '../config.ts'
21
+ import { parseFeedbackArgs } from '../feedback/args.ts'
22
+ import { parseImplementArgs } from '../implement/args.ts'
23
+ import { parsePlanArgs } from '../plan/args.ts'
24
+ import { getRepoName } from '../plan-tools/helpers.ts'
25
+ import { parseValidateArgs } from '../validate/args.ts'
26
+ import type { WorkMode } from '../work-mode.ts'
27
+ import { markAwaitingSpecApproval } from './awaiting-approval.ts'
28
+ import { findJiraEpic, findTicketBrainstormTarget } from './jira-ref.ts'
29
+ import {
30
+ type BrainstormOverride,
31
+ buildPhasePrompt,
32
+ type CommandPhase,
33
+ type PhasePrompt,
34
+ type PhasePromptInput,
35
+ } from './phase-prompts.ts'
36
+
37
+ type ParsedRef =
38
+ | { kind: 'jira'; jiraId: string }
39
+ | { kind: 'aven'; ref: string }
40
+
41
+ // AIDEV-NOTE: Option B — phase-command Jira resolution is read-only: an
42
+ // existing pulled-in epic (jira-ref metadata) replaces the Jira ID so label
43
+ // gates read the epic; a miss passes the Jira ID through unchanged (the
44
+ // feature-plan-aven skill handles the cold pull-in itself). Only /flow
45
+ // creates the epic (it needs a real ref before any phase can run).
46
+ export async function resolvePhaseRef(
47
+ parsed: ParsedRef,
48
+ mode: WorkMode,
49
+ ): Promise<string> {
50
+ if (parsed.kind === 'aven' || mode !== 'work') return refOf(parsed)
51
+ const found = await findJiraEpic(parsed.jiraId, avenExec)
52
+ return found.kind === 'found' ? found.ref : parsed.jiraId
53
+ }
54
+
55
+ function refOf(parsed: ParsedRef): string {
56
+ return parsed.kind === 'jira' ? parsed.jiraId : parsed.ref
57
+ }
58
+
59
+ // AIDEV-NOTE: Shared per-invocation inputs for buildPhasePrompt — the phase
60
+ // commands and (via /flow) the loop build identical inputs from the same env,
61
+ // so a human-invoked phase and a flow-driven phase can never drift.
62
+ export async function commandPhaseInput(
63
+ pi: ExtensionAPI,
64
+ input: {
65
+ mode: WorkMode
66
+ ref: string
67
+ cwd?: string
68
+ labels?: readonly string[]
69
+ onBrainstormFallback?: (jiraId: string) => void
70
+ },
71
+ ): Promise<PhasePromptInput> {
72
+ const { stdout } = await pi.exec('git', ['rev-parse', '--show-toplevel'], {})
73
+ const config = await loadConfig(input.cwd ?? process.cwd())
74
+ return {
75
+ mode: input.mode,
76
+ ref: input.ref,
77
+ gitRoot: stdout.trim(),
78
+ // AIDEV-NOTE: PMR-YC8V — origin-remote-first repo name (worktree-safe),
79
+ // the same source the plan-tool resolvers use, so /brainstorm writes to
80
+ // $LLM_NOTES_ROOT/<origin-name>/… instead of a per-worktree junk dir.
81
+ repoName: await getRepoName(pi),
82
+ workRoots: config.workRoots,
83
+ labels: input.labels ?? [],
84
+ // AIDEV-NOTE: read-only ticket lookup for ticket brainstorming — jira-ref epic
85
+ // first (labels land there, /flow resumes clean), then the jira-key synced
86
+ // ticket (no acli needed). Neither → acli branch, announced via
87
+ // onBrainstormFallback so an acli-first run never looks like aven was
88
+ // skipped.
89
+ findTicketRef: async (jiraId) => {
90
+ const found = await findTicketBrainstormTarget(jiraId, avenExec)
91
+ if (found.kind === 'none') input.onBrainstormFallback?.(jiraId)
92
+ if (found.kind === 'epic' || found.kind === 'synced') {
93
+ return { kind: found.kind, ref: found.ref }
94
+ }
95
+ return null
96
+ },
97
+ }
98
+ }
99
+
100
+ // AIDEV-NOTE: shared handler tail — one block/send path for every phase
101
+ // command, so notify wording cannot drift between phases.
102
+ function sendOrNotify(
103
+ pi: ExtensionAPI,
104
+ ctx: ExtensionCommandContext,
105
+ name: string,
106
+ ref: string,
107
+ result: PhasePrompt,
108
+ ): void {
109
+ if (result.kind === 'block') {
110
+ ctx.ui.notify(`/${name} ${ref}: ${result.reason}`, 'warning')
111
+ return
112
+ }
113
+ pi.sendUserMessage(result.prompt)
114
+ }
115
+
116
+ interface PhaseCommandOptions<Parsed extends { kind: string }> {
117
+ name: CommandPhase
118
+ description: string
119
+ /** Shown as `Usage: <usage>` when the parser returns kind 'help'. */
120
+ usage: string
121
+ parse: (raw: string) => Parsed | { kind: 'help' }
122
+ /** Resolve the phase ref from parsed args; default is the shared
123
+ * resolvePhaseRef (aven-first Jira resolution). */
124
+ resolveRef?: (parsed: Parsed, mode: WorkMode) => Promise<string>
125
+ /** Extra PhasePromptInput fields (labels, brainstorm override, epic guard). */
126
+ extraInput?: (input: {
127
+ parsed: Parsed
128
+ mode: WorkMode
129
+ ref: string
130
+ ctx: ExtensionCommandContext
131
+ }) => Promise<Partial<PhasePromptInput>>
132
+ /** Called when ticket brainstorming finds no aven epic or synced ticket and
133
+ * falls back to acli. */
134
+ onBrainstormFallback?: (jiraId: string, ctx: ExtensionCommandContext) => void
135
+ // AIDEV-NOTE: PMR-DMHH — optional post-send hook, invoked by the shared
136
+ // handler tail ONLY when the prompt was actually sent (result.kind !==
137
+ // 'block'). Used by /plan to arm the standalone awaiting-approval marker
138
+ // so a later `/flow answer <ref> approve` can plain-wake this session.
139
+ /** Called after the phase prompt was sent (never for block results). */
140
+ onPromptSent?: (ref: string) => void
141
+ }
142
+
143
+ function registerPhaseCommand<Parsed extends { kind: string }>(
144
+ pi: ExtensionAPI,
145
+ options: PhaseCommandOptions<Parsed>,
146
+ ): void {
147
+ pi.registerCommand(options.name, {
148
+ description: options.description,
149
+ handler: async (args, ctx) => {
150
+ const parsed = options.parse(args)
151
+ if ((parsed as { kind: string }).kind === 'help') {
152
+ ctx.ui.notify(`Usage: ${options.usage}`, 'info')
153
+ return
154
+ }
155
+ const run = parsed as Parsed
156
+ const mode = await resolveMode(pi, ctx.cwd)
157
+ let ref: string
158
+ if (options.resolveRef !== undefined) {
159
+ ref = await options.resolveRef(run, mode)
160
+ } else {
161
+ ref = await resolvePhaseRef(run as Parsed & ParsedRef, mode)
162
+ }
163
+ const base = await commandPhaseInput(pi, {
164
+ mode,
165
+ ref,
166
+ cwd: ctx.cwd,
167
+ onBrainstormFallback:
168
+ options.onBrainstormFallback === undefined
169
+ ? undefined
170
+ : (jiraId) => options.onBrainstormFallback?.(jiraId, ctx),
171
+ })
172
+ const extra =
173
+ options.extraInput === undefined
174
+ ? {}
175
+ : await options.extraInput({ parsed: run, mode, ref, ctx })
176
+ const result = await buildPhasePrompt(options.name, { ...base, ...extra })
177
+ if (options.name === 'brainstorm')
178
+ adhocBeginMain('brainstorm', ref, false)
179
+ sendOrNotify(pi, ctx, options.name, ref, result)
180
+ // AIDEV-NOTE: PMR-DMHH — arm only when the prompt actually went out;
181
+ // a block result means nothing was sent, so nothing may be awaited.
182
+ if (result.kind !== 'block' && options.onPromptSent !== undefined) {
183
+ options.onPromptSent(ref)
184
+ }
185
+ },
186
+ })
187
+ }
188
+
189
+ function brainstormOverrideOf(
190
+ parsed: Exclude<BrainstormArgs, { kind: 'help' }>,
191
+ ): BrainstormOverride {
192
+ if (parsed.kind === 'debug') {
193
+ return { kind: 'debug', text: parsed.symptom }
194
+ }
195
+ if (parsed.forceRef === true) {
196
+ return { kind: 'feature', text: parsed.topic, refHint: 'force' }
197
+ }
198
+ return { kind: 'feature', text: parsed.topic, refHint: 'explicit' }
199
+ }
200
+
201
+ export function registerPhaseCommands(pi: ExtensionAPI): void {
202
+ // AIDEV-NOTE: Prompt prep lives in flow/phase-prompts.ts (shared with the
203
+ // /flow loop). The ticket-creation gate lives in the agent prompt (GATE_
204
+ // INSTRUCTIONS in brainstorm/prompt.ts) — the command itself never creates
205
+ // tickets, and the prompt-driven gate replaced buildTicketPlan (PMR-3EQ8).
206
+ // Ticket refs (ID=<jira-id>, or bare jira-shaped in work mode) resolve
207
+ // aven-first via findEpicRef and skip the creation gate — see
208
+ // brainstorm/refs.ts.
209
+ registerPhaseCommand(pi, {
210
+ name: 'brainstorm',
211
+ description:
212
+ 'Brainstorm phase (standalone, not a lifecycle phase). Usage: /brainstorm <topic> | /brainstorm ID=<jira-id> | /brainstorm --debug <symptom>',
213
+ usage:
214
+ '/brainstorm <topic> | /brainstorm ID=<jira-id> | /brainstorm --debug <symptom>',
215
+ parse: parseBrainstormArgs,
216
+ resolveRef: async (parsed) => {
217
+ if (parsed.kind === 'debug') return parsed.symptom
218
+ return parsed.topic
219
+ },
220
+ extraInput: async ({ parsed }) => ({
221
+ brainstorm: brainstormOverrideOf(parsed),
222
+ }),
223
+ onBrainstormFallback: (jiraId, ctx) => {
224
+ ctx.ui.notify(
225
+ `/brainstorm ${jiraId}: no aven epic or synced ticket found — brainstorming falls back to the Jira ticket via acli`,
226
+ 'info',
227
+ )
228
+ },
229
+ })
230
+
231
+ // AIDEV-NOTE: Both modes route to the user's feature-plan-aven skill by
232
+ // name; personal mode keeps only the size check + oneshot escape inline
233
+ // and delegates the plan verdict to the skill (PMR-T6KF).
234
+ registerPhaseCommand(pi, {
235
+ name: 'plan',
236
+ description:
237
+ 'PIV plan phase. Usage: /plan <jira-id | aven-ref | aven:<ref> | jira:<key>>',
238
+ usage: '/plan <jira-id | aven-ref | aven:<ref> | jira:<key>>',
239
+ parse: parsePlanArgs,
240
+ // AIDEV-NOTE: PMR-DMHH — standalone /plan arms the awaiting-approval
241
+ // marker so a later `/flow answer <ref> approve` can plain-wake this
242
+ // session. implement/validate/feedback/brainstorm never arm it.
243
+ onPromptSent: (ref) => markAwaitingSpecApproval(ref),
244
+ })
245
+
246
+ // AIDEV-NOTE: Gate wiring lives in implement/routing.ts via
247
+ // buildPhasePrompt('implement'). Labels fetched fail-closed (aven failure
248
+ // -> empty labels -> routing refuses).
249
+ registerPhaseCommand(pi, {
250
+ name: 'implement',
251
+ description:
252
+ 'PIV implement phase. Usage: /implement <jira-id | aven-ref | aven:<ref> | jira:<key>>',
253
+ usage: '/implement <jira-id | aven-ref | aven:<ref> | jira:<key>>',
254
+ parse: parseImplementArgs,
255
+ extraInput: async ({ ref }) => ({
256
+ labels: (await readAvenLabels(ref)) ?? [],
257
+ epicHasOpenChildren: await epicHasOpenChildren(ref),
258
+ }),
259
+ })
260
+
261
+ // AIDEV-NOTE: Work mode resolves the sh-devctl scripts dir from the first
262
+ // configured workRoot (validate/paths.ts) inside buildPhasePrompt; missing
263
+ // workRoots blocks loudly. Personal mode (PMR-8449) never hits the work gate.
264
+ registerPhaseCommand(pi, {
265
+ name: 'validate',
266
+ description:
267
+ 'PIV validate phase. Usage: /validate <jira-id | aven-ref | aven:<ref> | jira:<key>>',
268
+ usage: '/validate <jira-id | aven-ref | aven:<ref> | jira:<key>>',
269
+ parse: parseValidateArgs,
270
+ })
271
+
272
+ // AIDEV-NOTE: Work mode runs the /sonarqube + /pr-quality gate via the
273
+ // prompt; personal mode runs the wrap-up (outcome summary, review-feedback
274
+ // tickets, done) after validate's merge (PMR-81SX).
275
+ // Triage rules live in the pure feedback/triage.ts and the prompt text;
276
+ // the close-out evidence gates on the done write live in
277
+ // flow/lifecycle-policy.ts consulted by the flow_phase_complete tool and
278
+ // the loop sinks (PMR-VE27) — the standalone command stays a documented
279
+ // human-attested escape hatch outside those machine guards.
280
+ registerPhaseCommand(pi, {
281
+ name: 'feedback',
282
+ description:
283
+ 'PIV feedback phase. Usage: /feedback <jira-id | aven-ref | aven:<ref> | jira:<key>>',
284
+ usage: '/feedback <jira-id | aven-ref | aven:<ref> | jira:<key>>',
285
+ parse: parseFeedbackArgs,
286
+ })
287
+ }
@@ -0,0 +1,13 @@
1
+ // AIDEV-NOTE: single phase-emoji map for BOTH widget surfaces — the frame
2
+ // accent prefix (flow/frame.ts stylePhaseRow, PMR-X7BH) and the footer text
3
+ // (flow/status.ts renderFooterStatus, PMR-C3B6). This module reconciles the
4
+ // two identical copies that existed while PMR-X7BH and PMR-C3B6 landed in
5
+ // parallel; add new phases here once. Hardcoded per the no-config decision;
6
+ // keyed loosely (Record<string, string>) so neither call site has to import
7
+ // run-state types into this leaf module.
8
+ export const PHASE_EMOJI: Readonly<Record<string, string>> = {
9
+ plan: '📝',
10
+ implement: '🔨',
11
+ validate: '🔍',
12
+ feedback: '🎁',
13
+ }
@@ -0,0 +1,251 @@
1
+ // AIDEV-NOTE: Single source of truth for phase handoff prompts, shared by
2
+ // the phase commands (/brainstorm, /plan, ...) in index.ts and the /flow loop
3
+ // (prompt injection lives in flow/loop-settle.ts). Both entrypoints MUST
4
+ // produce identical prompts so gates and phase logic can never drift between
5
+ // a human invocation and a flow-driven one. The loop never "reimplements" a
6
+ // phase — it calls these same builders the commands call.
7
+ import {
8
+ brainstormArtifactPath,
9
+ resolveBrainstormDir,
10
+ } from '../brainstorm/paths.ts'
11
+ import {
12
+ buildBrainstormPrompt,
13
+ buildTicketBrainstormPrompt,
14
+ } from '../brainstorm/prompt.ts'
15
+ import { classifyBrainstormTarget } from '../brainstorm/refs.ts'
16
+ import { buildFeedbackPrompt } from '../feedback/prompt.ts'
17
+ import { buildImplementPrompt } from '../implement/prompt.ts'
18
+ import { routeFor } from '../implement/routing.ts'
19
+ import { buildPlanPrompt } from '../plan/prompt.ts'
20
+ import { resolveDevctlScriptsDir } from '../validate/paths.ts'
21
+ import { buildValidatePrompt } from '../validate/prompt.ts'
22
+ import type { WorkMode } from '../work-mode.ts'
23
+ import type { Phase } from './orchestrate.ts'
24
+
25
+ // AIDEV-NOTE: PMR-Z2K7 — research left the lifecycle Phase union; it stays
26
+ // here as a command-only phase so /brainstorm (and only /brainstorm) can
27
+ // reach brainstormPrompt through the shared builder (PMR-H7RW renamed the
28
+ // member from 'research' to 'brainstorm'). The /flow loop only ever passes
29
+ // lifecycle Phases.
30
+ export type CommandPhase = Phase | 'brainstorm'
31
+
32
+ export type PhasePrompt =
33
+ | { kind: 'send'; prompt: string }
34
+ | { kind: 'block'; reason: string }
35
+
36
+ export interface BrainstormOverride {
37
+ kind: 'feature' | 'debug'
38
+ text: string
39
+ /** Provenance of text — decides ticket-ref resolution
40
+ * (brainstorm/refs.ts classifyBrainstormTarget): 'force' = known Jira ID
41
+ * (/flow jira kind or ID= prefix), 'explicit' = bare /brainstorm topic
42
+ * (ticket path only when jira-shaped AND work mode). Undefined = default
43
+ * ref-as-topic; never the ticket path (an aven ref must not hit acli). */
44
+ refHint?: 'force' | 'explicit'
45
+ }
46
+
47
+ export interface PhasePromptInput {
48
+ mode: WorkMode
49
+ ref: string
50
+ /** Git toplevel of the session cwd; brainstorm/plan derive repoName from it. */
51
+ gitRoot: string
52
+ /** Repo name from getRepoName (origin remote name preferred, worktree-safe).
53
+ * PMR-YC8V: brainstorm must NOT derive it from the gitRoot basename — in a
54
+ * herdr worktree that is the worktree dir, scattering notes into per-
55
+ * worktree junk dirs. Falls back to the gitRoot basename when absent. */
56
+ repoName?: string
57
+ /** Resolved pi-flow config workRoots; work-mode validate needs them. */
58
+ workRoots: readonly string[]
59
+ /** Current aven labels on the ref; implement routing gates on them. */
60
+ labels: readonly string[]
61
+ /** True when the ref is an epic with open children — forces the plan route
62
+ * (an oneshot route over an open tree is always a misroute: the whole
63
+ * tree gets executed as one batch without per-task workers). */
64
+ epicHasOpenChildren?: boolean
65
+ /** True when the run started with /flow --yolo (gates skipped). */
66
+ yolo?: boolean
67
+ /** /brainstorm override: explicit kind + topic/symptom (flow defaults to feature+ref). */
68
+ brainstorm?: BrainstormOverride
69
+ /** Aven ticket lookup for ticket brainstorming (jira-ref epic, then jira-key
70
+ * synced ticket). Null = neither exists — the prompt falls back to acli. */
71
+ findTicketRef?: (jiraId: string) => Promise<{
72
+ kind: 'epic' | 'synced'
73
+ ref: string
74
+ } | null>
75
+ }
76
+
77
+ export async function buildPhasePrompt(
78
+ phase: CommandPhase,
79
+ input: PhasePromptInput,
80
+ ): Promise<PhasePrompt> {
81
+ switch (phase) {
82
+ case 'brainstorm':
83
+ return brainstormPrompt(input)
84
+ case 'plan':
85
+ return planPrompt(input)
86
+ case 'implement':
87
+ return implementPrompt(input)
88
+ case 'validate':
89
+ return validatePrompt(input)
90
+ case 'feedback':
91
+ return feedbackPrompt(input)
92
+ }
93
+ }
94
+
95
+ // AIDEV-NOTE: async so ticket brainstorming can resolve the local epic via
96
+ // findEpicRef before the prompt is built — /flow and /brainstorm share this
97
+ // one path. Debug symptoms never take the ticket branch.
98
+ async function brainstormPrompt(input: PhasePromptInput): Promise<PhasePrompt> {
99
+ const brainstorm = input.brainstorm ?? {
100
+ kind: 'feature' as const,
101
+ text: input.ref,
102
+ }
103
+ // AIDEV-NOTE: PMR-YC8V — caller-supplied repoName (getRepoName: origin
104
+ // remote name preferred) keeps /brainstorm in a herdr worktree writing
105
+ // $LLM_NOTES_ROOT/<origin-name>/notes/brainstorm/ like the resolver tools,
106
+ // not $LLM_NOTES_ROOT/<worktree-dir>/… junk dirs.
107
+ const repoName = input.repoName ?? input.gitRoot.split('/').pop() ?? 'unknown'
108
+ const dir = resolveBrainstormDir(
109
+ input.mode,
110
+ process.env.LLM_NOTES_ROOT,
111
+ process.env.PERSONAL_FEATURES,
112
+ repoName,
113
+ input.gitRoot,
114
+ )
115
+ const today = new Date().toISOString().slice(0, 10)
116
+ const target = classifyBrainstormTarget(brainstorm.text, {
117
+ force: brainstorm.refHint === 'force',
118
+ explicit: brainstorm.refHint === 'explicit',
119
+ mode: input.mode,
120
+ })
121
+ if (brainstorm.kind === 'feature' && target.kind === 'ticket') {
122
+ let resolved: { kind: 'epic' | 'synced'; ref: string } | null = null
123
+ if (input.findTicketRef !== undefined) {
124
+ resolved = await input.findTicketRef(target.jiraId)
125
+ }
126
+ return {
127
+ kind: 'send',
128
+ prompt: buildTicketBrainstormPrompt({
129
+ jiraId: target.jiraId,
130
+ target: resolved,
131
+ artifactPath: brainstormArtifactPath(dir, target.jiraId, today),
132
+ mode: input.mode,
133
+ }),
134
+ }
135
+ }
136
+ const artifactPath = brainstormArtifactPath(dir, brainstorm.text, today)
137
+ return {
138
+ kind: 'send',
139
+ prompt: buildBrainstormPrompt({
140
+ kind: brainstorm.kind,
141
+ input: brainstorm.text,
142
+ artifactPath,
143
+ mode: input.mode,
144
+ }),
145
+ }
146
+ }
147
+
148
+ function planPrompt(input: PhasePromptInput): PhasePrompt {
149
+ return {
150
+ kind: 'send',
151
+ prompt: buildPlanPrompt({
152
+ mode: input.mode,
153
+ ref: input.ref,
154
+ yolo: input.yolo,
155
+ }),
156
+ }
157
+ }
158
+
159
+ function implementPrompt(input: PhasePromptInput): PhasePrompt {
160
+ const routed = routeFor('aven', input.labels)
161
+ if (routed.kind === 'refuse') {
162
+ return { kind: 'block', reason: routed.reason }
163
+ }
164
+ // AIDEV-NOTE: structural routing guard (widened by PMR-7GQ3) — labels are
165
+ // the routing contract, but a tree with open children is plan-route work no
166
+ // matter what the type labels say (legacy approvals, manual label edits).
167
+ // When epicHasOpenChildren is true, both non-plan routes are overridden to
168
+ // plan: an oneshot prompt batches the whole tree into one cycle with no
169
+ // workers, and a bug prompt (bug wins over plan in routeFor) would inject
170
+ // a single-cycle bug flow over an open epic tree. Precedence: this
171
+ // tree-aware layer wins over labels; routeFor itself is untouched — its
172
+ // labels-only contract stays pinned by implement.test.ts.
173
+ let route = routed.route
174
+ const overridesToPlan =
175
+ input.epicHasOpenChildren === true &&
176
+ (routed.route === 'oneshot' || routed.route === 'bug')
177
+ if (overridesToPlan) {
178
+ route = 'plan'
179
+ }
180
+ return {
181
+ kind: 'send',
182
+ prompt: buildImplementPrompt({
183
+ mode: input.mode,
184
+ ref: input.ref,
185
+ route,
186
+ }),
187
+ }
188
+ }
189
+
190
+ function validatePrompt(input: PhasePromptInput): PhasePrompt {
191
+ if (input.mode === 'work') {
192
+ const scriptsDir = resolveDevctlScriptsDir(input.workRoots)
193
+ if (scriptsDir === null) {
194
+ return {
195
+ kind: 'block',
196
+ reason:
197
+ 'no workRoots configured — cannot resolve the sh-devctl scripts dir',
198
+ }
199
+ }
200
+ return {
201
+ kind: 'send',
202
+ prompt: buildValidatePrompt({
203
+ mode: input.mode,
204
+ ref: input.ref,
205
+ scriptsDir,
206
+ }),
207
+ }
208
+ }
209
+ // AIDEV-NOTE: personal oneshot tickets have no plan.md, so the deviation
210
+ // gate must name the ticket description as the spec source, not plan-path.
211
+ // Yolo rides along (yolo 4.2); work mode keeps its prompt unchanged even
212
+ // when yolo is set (yolo is personal-only).
213
+ return {
214
+ kind: 'send',
215
+ prompt: buildValidatePrompt({
216
+ mode: input.mode,
217
+ ref: input.ref,
218
+ scriptsDir: null,
219
+ oneshot: input.labels.includes('oneshot'),
220
+ yolo: input.yolo,
221
+ }),
222
+ }
223
+ }
224
+
225
+ function feedbackPrompt(input: PhasePromptInput): PhasePrompt {
226
+ // AIDEV-NOTE: PMR-81SX — personal feedback is a real phase now; since
227
+ // PMR-V31Z 1.3 it OWNS the PR delivery (validate completes without
228
+ // landing), one personalPrDeliverySection for yolo and non-yolo. Both
229
+ // entrypoints keep producing identical prompts via this single builder.
230
+ // Yolo rides along (yolo 4.3); work mode keeps its prompt unchanged even
231
+ // when yolo is set (yolo is personal-only).
232
+ return {
233
+ kind: 'send',
234
+ prompt: buildFeedbackPrompt({
235
+ mode: input.mode,
236
+ ref: input.ref,
237
+ yolo: input.yolo,
238
+ }),
239
+ }
240
+ }
241
+
242
+ // AIDEV-NOTE: PMR-H1GA — prompt text belongs with prompt building, so this
243
+ // moved from flow/loop.ts to here (PMR-H1GA split). Its only caller is the
244
+ // settle engine's retryAfterBlockers (flow/loop-settle.ts): the suffix
245
+ // points the retried agent at the blockers note the validate round left on
246
+ // the ref.
247
+ export function fixRoundSuffix(ref: string): string {
248
+ return `
249
+
250
+ FIX ROUND (automatic retry after validate): read the MOST RECENT aven note on ${ref} containing "reviewed-at:" (aven show ${ref} --full). It lists the review blockers or deviation report. Fix EVERY item in it first, then run tests and commit. The fix round RESETS the phase-completion gate (the stale completion label was removed) — after fixing, testing, and committing, call the flow_phase_complete tool with ref=${ref} and phase="implement" again; this round does not complete without a fresh call.`
251
+ }