@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,531 @@
1
+ // AIDEV-NOTE: PMR-H1GA — the /flow loop's settle-evaluation engine, split
2
+ // out of flow/loop.ts. Owns the mutable run state (FlowLoopState,
3
+ // pendingResume, specApprovalStepOpen) and decides what a settle means:
4
+ // onSettled / retryAfterBlockers / sendPhasePrompt / snapshot, plus the
5
+ // spec-approval pause branch and the restart-close of the plan.spec-approval
6
+ // step (closeSpecApprovalStepIfOpen). Run LIFECYCLE (start / halt /
7
+ // advanceAfter / the done path) stays in flow/loop.ts, which reaches the
8
+ // engine's decisions through the narrow SettleHost interface below.
9
+ // Imports are session-side by design (the daemon never reaches this module):
10
+ // implement/retry.ts and the prompt builders are session-side machinery.
11
+ import { MAX_ATTEMPTS } from '../implement/retry.ts'
12
+ import type { LoopRunStatus } from '../run-state.ts'
13
+ import { clearFlowEnv, type FlowEnv, stampFlowPhase } from './attribution.ts'
14
+ import {
15
+ checkCloseout,
16
+ closeoutHaltReason,
17
+ resolveCloseoutProofs,
18
+ } from './lifecycle-policy.ts'
19
+ import type { FlowLoopDeps, FlowLoopState } from './loop-deps.ts'
20
+ import { PHASE_LABEL, type Phase } from './orchestrate.ts'
21
+ import { buildPhasePrompt, fixRoundSuffix } from './phase-prompts.ts'
22
+ import { isPrePromptSettle } from './turn-generation.ts'
23
+ import type { V2EmissionGuard } from './v2-emission.ts'
24
+ import { v2StateForStatus } from './v2-resume.ts'
25
+ import type { FlowReason } from './vocabulary.ts'
26
+
27
+ export type { FlowLoopState } from './loop-deps.ts'
28
+
29
+ // AIDEV-NOTE: PMR-H1GA — the narrow host adapter. The §Architecture sketch
30
+ // had `FlowLoopImpl implements SettleHost`, but advanceAfter is PRIVATE on
31
+ // FlowLoopImpl (it is the loop's lifecycle machinery, not public API). A
32
+ // private method cannot satisfy a public interface member, and making it
33
+ // public would widen the internal class surface unnecessarily — rejected. Instead
34
+ // loop.ts passes an object literal with halt/advanceAfter closures (arrow
35
+ // functions capture the private methods), keeping advanceAfter private and
36
+ // the exported FlowLoop API unchanged.
37
+ export interface SettleHost {
38
+ halt(phase: Phase, reason: string, v2reason?: FlowReason): Promise<void>
39
+ advanceAfter(phase: Phase, labels: string[]): Promise<void>
40
+ }
41
+
42
+ export class FlowSettleEngine {
43
+ private runState: FlowLoopState | null = null
44
+ private promptTurnGeneration: number | null = null
45
+ // one-shot: the first sendPhasePrompt after a resumed start must not
46
+ // overwrite the seeded validateStartedAt (blockers-note cutoff)
47
+ private pendingResume = false
48
+ // AIDEV-NOTE: PMR-ZV9Y 2.1 — pairing guard for plan.spec-approval. The
49
+ // spec-approval pause journals step-start; the step-stop is emitted by
50
+ // closeSpecApprovalStepIfOpen on the loop restart (start()). This flag
51
+ // keeps them paired so an orphan stop never appears when a run never
52
+ // paused for approval. Seeded on a cross-process resume from the journal
53
+ // tail (resumePlanApprovalOpen). PMR-F79K: the restart close is the ONLY
54
+ // close — the advanceAfter pairing-guard stop was removed as unreachable.
55
+ private specApprovalStepOpen = false
56
+
57
+ private readonly deps: FlowLoopDeps
58
+ private readonly v2: V2EmissionGuard
59
+ private readonly env: FlowEnv
60
+ private readonly host: SettleHost
61
+
62
+ // AIDEV-NOTE: explicit field declarations + constructor assignment, NOT
63
+ // TypeScript parameter properties — node --test strip-only mode rejects
64
+ // them (ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX).
65
+ constructor(
66
+ deps: FlowLoopDeps,
67
+ v2: V2EmissionGuard,
68
+ env: FlowEnv,
69
+ host: SettleHost,
70
+ ) {
71
+ this.deps = deps
72
+ this.v2 = v2
73
+ this.env = env
74
+ this.host = host
75
+ }
76
+
77
+ // The run in flight, or null when idle (read by the loop's lifecycle
78
+ // methods and its public isActive/activeRef).
79
+ get state(): FlowLoopState | null {
80
+ return this.runState
81
+ }
82
+
83
+ // start() hands the freshly constructed run state over AFTER the yolo
84
+ // guard and the fail-closed stampFlowStart abort. specApprovalOpen is
85
+ // applied ONLY when supplied (a same-instance restart keeps the earlier
86
+ // pause's open step — see the field note above).
87
+ beginRun(
88
+ state: FlowLoopState,
89
+ opts: { pendingResume: boolean; specApprovalOpen?: boolean },
90
+ ): void {
91
+ if (opts.specApprovalOpen !== undefined) {
92
+ this.specApprovalStepOpen = opts.specApprovalOpen
93
+ }
94
+ this.pendingResume = opts.pendingResume
95
+ this.runState = state
96
+ }
97
+
98
+ // Terminal teardown entry point for the loop-owned lifecycle paths (halt,
99
+ // the done branch of advanceAfter): they snapshot BEFORE calling this.
100
+ clearRun(): void {
101
+ this.runState = null
102
+ }
103
+
104
+ // AIDEV-NOTE: PMR-ZV9Y 2.1 — spec-approval step-stop at the EARLIEST
105
+ // faithful restart site. Spec Behaviour 3 (plan.md:68) requires the journal
106
+ // ORDER `step-stop{plan.spec-approval}` THEN `state-change{running}`: the
107
+ // approval wait ends when the loop is RE-ENTERED after /flow answer, and
108
+ // `specApprovalStepOpen` (seeded from the journal tail on a cross-process
109
+ // resume, or kept set by this same instance's earlier pause) is exactly
110
+ // "the step is still open". Closing it HERE — before the running snapshot
111
+ // below — (a) orders the journal as the spec says, (b) bounds
112
+ // pi_flow_step_seconds / the Tempo span to the approval wait instead of
113
+ // stretching it to the plan phase-complete, and (c) guarantees a stop even
114
+ // when the restarted run HALTS before plan completes. It is
115
+ // PHASE-INDEPENDENT on purpose: /flow answer approve moves plan-state to
116
+ // approved so the restart can re-enter at implement, where the old
117
+ // advanceAfter-only close (gated on `phase === 'plan'`) would never fire
118
+ // and the step would leak. /flow answer reject routes the spec back to
119
+ // draft (more plan work, no label) — the wait STILL ENDED, so step-stop is
120
+ // correct there too; both answers restart the loop and neither keeps the
121
+ // approval step open. PMR-F79K: this is the ONLY close. The advanceAfter
122
+ // "idempotent fallback" stop that used to sit here as a second safety net
123
+ // was provably unreachable — the pause below sets the flag AND nulls
124
+ // the run state in the same block, onSettled bails on a null state, and
125
+ // this method clears the flag on every re-entry — so it was removed; the
126
+ // pin is 'PMR-F79K: the restart in start() is the ONLY plan.spec-approval
127
+ // close' in test/loop-state-change.test.ts. Consequence, stated plainly: a
128
+ // run that pauses for approval and is never re-entered keeps its step open,
129
+ // which is honest — the human still owes an answer.
130
+ closeSpecApprovalStepIfOpen(): void {
131
+ if (this.specApprovalStepOpen && this.runState !== null) {
132
+ this.v2.emitStep(
133
+ 'step-stop',
134
+ this.runState.ref,
135
+ 'plan',
136
+ 'plan.spec-approval',
137
+ )
138
+ this.specApprovalStepOpen = false
139
+ }
140
+ }
141
+
142
+ // AIDEV-NOTE: No abort flag needed — an aborted/escaped phase turn cannot
143
+ // have landed its label, so the label check below halts it. A post-label
144
+ // abort (Escape after completion) correctly still advances.
145
+ async onSettled(): Promise<void> {
146
+ if (this.runState === null || !this.runState.awaitingOutcome) return
147
+ if (isPrePromptSettle(this.promptTurnGeneration, this.deps)) return
148
+ this.runState.awaitingOutcome = false
149
+ const phase = this.runState.currentPhase
150
+ const labels = await this.deps.readLabels(this.runState.ref)
151
+ if (labels === null) {
152
+ await this.host.halt(
153
+ phase,
154
+ 'cannot read aven labels (fail-closed)',
155
+ 'aven_read_failed',
156
+ )
157
+ return
158
+ }
159
+ const label = PHASE_LABEL[phase]
160
+ // AIDEV-NOTE: PMR-5THZ — hoisted validate guards: the in-flight wait and
161
+ // the fresh-blocker route-back run BEFORE the label-present/missing
162
+ // split, so a stale 'review-passed' can no longer skip them (the
163
+ // reproduced PMR-PB3Z/PMR-5NZB race: the label landed before a refused
164
+ // landing + rebase, the post-rebase reviewer is still live, the branch
165
+ // is unmerged — the label-present branch used to advance straight into
166
+ // feedback). Both guards stay mode-agnostic, symmetric with the
167
+ // label-missing behavior they replace. The re-arm and the
168
+ // waiting_machine/waiting_human v2 emission are shared with the generic
169
+ // wait via armInFlightWait (identical by construction) — only the note
170
+ // wording differs: it must never claim the label is missing, because
171
+ // here it may well be present.
172
+ if (phase === 'validate') {
173
+ if (this.deps.hasInFlightSubagent()) {
174
+ this.armInFlightWait({
175
+ machine:
176
+ 'settled at validate while a subagent is still in flight — flow stays armed',
177
+ ask: 'settled at validate — a subagent is in flight and waiting on the human (ask_owner) — flow stays armed',
178
+ })
179
+ return
180
+ }
181
+ // AIDEV-NOTE: PMR-69V8 — route-back is extension sequencing, not a
182
+ // prompt instruction: validate settled and the agent left a fresh
183
+ // review-blockers note -> re-inject the implement prompt, bounded by
184
+ // the same 3-attempt budget as implement/retry.ts (2 retries).
185
+ // PMR-5THZ: hoisted above the label check, so the route-back also runs
186
+ // when a stale 'review-passed' is present — the two-label reset
187
+ // (retryAfterBlockers) consumes it instead of letting it advance.
188
+ if (this.deps.hasFreshBlockers !== undefined) {
189
+ const retried = await this.retryAfterBlockers(
190
+ await this.deps.hasFreshBlockers(
191
+ this.runState.ref,
192
+ this.runState.validateStartedAt,
193
+ ),
194
+ )
195
+ if (retried) return
196
+ }
197
+ }
198
+ if (!labels.includes(label)) {
199
+ // AIDEV-NOTE: PMR-5THZ — validate never reaches this generic wait: the
200
+ // hoisted guard above handles validate in-flight settles in both label
201
+ // states, so this branch now serves plan/implement/feedback only.
202
+ if (this.deps.hasInFlightSubagent()) {
203
+ this.armInFlightWait({
204
+ machine: `settled at ${phase} without the "${label}" label but a subagent is in flight — flow stays armed`,
205
+ ask: `settled at ${phase} without the "${label}" label — a subagent is in flight and waiting on the human (ask_owner) — flow stays armed`,
206
+ })
207
+ return
208
+ }
209
+ // AIDEV-NOTE: PMR-W60H — a plan settle without "planned" while the
210
+ // spec is at plan-state=review is the expected approval gate, not a
211
+ // failure: pause with clear wording (info, no "halted" note) so the
212
+ // failure-style halt stays reserved for real misses. aven failure or
213
+ // a missing field keeps the fail-closed halt. Resume: a later /flow
214
+ // re-enters plan; after spec approval the refreshed prompt completes
215
+ // the phase. PMR-DMHH: the note tells the human that recording the
216
+ // answer (/flow answer <ref> approve) resumes the run automatically,
217
+ // with the manual /flow <ref> rerun kept as the fallback.
218
+ if (phase === 'plan') {
219
+ const planState = await this.deps.readPlanState(this.runState.ref)
220
+ if (planState === 'review') {
221
+ const ref = this.runState.ref
222
+ const text = `flow paused at plan: awaiting spec approval (plan-state=review) — approve via /flow answer ${ref} approve (human-only; the run then resumes automatically — no rerun needed). If the auto-resume does not land, rerun /flow ${ref} manually (typing 'implement' as a plain message does NOT restart the flow — agent: tell the human to run /flow ${ref} before any implement/validate work)`
223
+ await this.deps.avenNote(ref, text)
224
+ this.deps.journal({ kind: 'note', at: now(), ref, text })
225
+ this.deps.notify(`/flow ${ref}: ${text}`, 'info')
226
+ // AIDEV-NOTE: PMR-ZV9Y 2.1 — spec-approval pause maps to v2
227
+ // waiting_human{spec_approval_pending} (paused) PLUS the
228
+ // plan.spec-approval step boundary. The matching step-stop is emitted
229
+ // at the EARLIEST restart site — start(), when the seeded
230
+ // specApprovalStepOpen flag says the step is still open (fix-round-3,
231
+ // deviation #1) — ordered BEFORE the running snapshot. PMR-F79K: that
232
+ // restart close is the ONLY close (the unreachable advanceAfter
233
+ // fallback is gone), and the run-state nulling two lines below is
234
+ // what makes it so: no settle can advance a paused instance, so a
235
+ // run that is never re-entered legitimately keeps the step open. The
236
+ // specApprovalStepOpen flag pairs start and stop so a run that never
237
+ // paused emits no orphan stop and at-most-one stop is journaled.
238
+ this.snapshot('paused', 'spec_approval_pending')
239
+ this.v2.emitStep('step-start', ref, 'plan', 'plan.spec-approval')
240
+ this.specApprovalStepOpen = true
241
+ this.runState = null
242
+ clearFlowEnv(this.env)
243
+ this.deps.onFlowEnvChange?.()
244
+ this.deps.setActiveRef?.(null)
245
+ this.deps.onRunEnd?.(ref)
246
+ return
247
+ }
248
+ }
249
+ await this.host.halt(
250
+ phase,
251
+ `phase completed without landing the "${label}" label`,
252
+ 'label_miss',
253
+ )
254
+ return
255
+ }
256
+ // AIDEV-NOTE: PMR-V31Z 2.1 — the personal merge-main landing gate that
257
+ // used to sit here (PMR-5THZ ancestry probe via the optional dep in
258
+ // flow/loop-deps.ts, its fail-closed halt, the landing-continuation
259
+ // re-send and its PMR-HG75 budget) is deleted: personal mode delivers
260
+ // via PR, so the local merge it proved never happens. The label mapping
261
+ // below is the whole decision — validate with "review-passed" advances
262
+ // into feedback by label order alone, exactly like every other phase.
263
+ // AIDEV-NOTE: PMR-VE27 — the feedback CLOSE-OUT gate at the settle (the
264
+ // matrix's "live feedback settle (label present)" row), re-based by
265
+ // PMR-V31Z: the ancestry evidence leg is superseded — personal delivers
266
+ // via PR and is unmerged BY DESIGN at close-out — so every mode verifies
267
+ // the journaled gh-pr-create effect instead; the PR is the close-out
268
+ // evidence. A settle whose feedback label ("done") is present
269
+ // re-verifies BEFORE advanceAfter — labels are claims, not proof, and
270
+ // external aven edits are uninterceptable, so this consumer reconciles.
271
+ // Refused → halt closeout_check_failed with no terminal teardown
272
+ // (advanceAfter's done branch is unreachable). PMR-2H3R composition:
273
+ // isPrePromptSettle above already consumed stale pre-prompt settles, so
274
+ // only a genuine post-prompt settle reaches this gate. The PMR-5NZB
275
+ // boundary holds: the evidence leg is PR-effect only — never review
276
+ // freshness.
277
+ if (phase === 'feedback') {
278
+ const state = this.runState
279
+ const closeout = checkCloseout({
280
+ mode: state.promptInput.mode,
281
+ yolo: state.promptInput.yolo === true,
282
+ proofs: await resolveCloseoutProofs(state.ref, {
283
+ prEffectFn: this.deps.prEffectFn,
284
+ }),
285
+ })
286
+ if (closeout.kind !== 'verified') {
287
+ await this.host.halt(
288
+ phase,
289
+ closeoutHaltReason(closeout, state.ref),
290
+ 'closeout_check_failed',
291
+ )
292
+ return
293
+ }
294
+ }
295
+ await this.host.advanceAfter(phase, labels)
296
+ }
297
+
298
+ // AIDEV-NOTE (worker-ask-wait fix): an in-flight child is NOT always a
299
+ // machine wait — if it parked on ask_owner, nothing moves until the
300
+ // OPERATOR answers, so the run belongs on the "Waiting on me — act
301
+ // now" board (state="waiting_human"), not in the machine-wait rows.
302
+ // The probe is optional and fail-closed: absent or false keeps the
303
+ // original waiting_machine{subagent_in_flight} label. Only the v2
304
+ // label and the note wording change — the v1 journal shape, the
305
+ // arming (awaitingOutcome=true) and the running return on the next
306
+ // settle are untouched.
307
+ // AIDEV-NOTE: PMR-5THZ — shared by the hoisted validate guard and the
308
+ // generic label-missing wait so the re-arm and the v2 emission stay
309
+ // identical across both call sites; only the note wording differs (the
310
+ // caller picks wording accurate for its label state).
311
+ private armInFlightWait(notes: { machine: string; ask: string }): void {
312
+ const state = this.runState
313
+ if (state === null) return
314
+ state.awaitingOutcome = true
315
+ const askPending = this.deps.hasPendingSubagentAsk?.() === true
316
+ let noteText = notes.machine
317
+ if (askPending) {
318
+ noteText = notes.ask
319
+ }
320
+ this.deps.journal({
321
+ kind: 'note',
322
+ at: now(),
323
+ ref: state.ref,
324
+ text: noteText,
325
+ })
326
+ // AIDEV-NOTE: PMR-ZV9Y 2.1 (ISC-7) — this branch has NO loop-state
327
+ // snapshot, so the waiting state would be invisible to v2 without an
328
+ // explicit emission (true for both labels here). The next settle that
329
+ // advances runs snapshot('running') (via sendPhasePrompt), which is a
330
+ // different state than either wait so it emits the return transition.
331
+ if (askPending) {
332
+ this.v2.emitStateChange(
333
+ state.ref,
334
+ 'waiting_human',
335
+ 'subagent_ask_pending',
336
+ )
337
+ } else {
338
+ this.v2.emitStateChange(
339
+ state.ref,
340
+ 'waiting_machine',
341
+ 'subagent_in_flight',
342
+ )
343
+ }
344
+ }
345
+
346
+ private async retryAfterBlockers(hasBlockers: boolean): Promise<boolean> {
347
+ const state = this.runState
348
+ if (state === null || !hasBlockers) return false
349
+ if (state.blockerRetries >= MAX_ATTEMPTS - 1) {
350
+ await this.host.halt(
351
+ 'validate',
352
+ `review blockers persist after ${state.blockerRetries} implement retries (budget exhausted)`,
353
+ 'blocker_budget_exhausted',
354
+ )
355
+ return true
356
+ }
357
+ // AIDEV-NOTE: PMR-B033 — reset the implement completion gate BEFORE
358
+ // re-injecting: the label-presence check in onSettled would otherwise
359
+ // treat the stale implement label from the previous round as a completed
360
+ // fix round and advance within seconds. Removal happens BEFORE the
361
+ // increment so a failed reset consumes no retry; fail-closed (dep
362
+ // absent / false / throw) halts with label_reset_failed instead of
363
+ // re-injecting implement. On restart the label is still present, so
364
+ // nextPhase re-derives validate and the route-back is retried naturally.
365
+ // AIDEV-NOTE: PMR-5THZ — the reset is widened to BOTH completion
366
+ // labels: a stale 'review-passed' must not survive the route-back
367
+ // either, because the next implement settle's nextPhase would then
368
+ // skip a fresh validation and jump straight to feedback on the old
369
+ // pass. removeAvenLabel is idempotent for absent labels
370
+ // (aven/client.ts), so both removals run unconditionally; EITHER one
371
+ // failing (dep absent / false / throw) halts fail-closed with
372
+ // label_reset_failed and consumes no retry.
373
+ const removeLabel = this.deps.removeAvenLabel
374
+ let reset = false
375
+ if (removeLabel !== undefined) {
376
+ try {
377
+ const removedImplement = await removeLabel(
378
+ state.ref,
379
+ PHASE_LABEL.implement,
380
+ )
381
+ const removedValidate = await removeLabel(
382
+ state.ref,
383
+ PHASE_LABEL.validate,
384
+ )
385
+ reset = removedImplement && removedValidate
386
+ } catch {
387
+ reset = false
388
+ }
389
+ }
390
+ if (!reset) {
391
+ await this.host.halt(
392
+ 'validate',
393
+ `could not reset the stale "${PHASE_LABEL.implement}" and "${PHASE_LABEL.validate}" labels on ${state.ref} — the implement fix round would auto-advance on them; check aven and rerun /flow ${state.ref}`,
394
+ 'label_reset_failed',
395
+ )
396
+ return true
397
+ }
398
+ state.blockerRetries += 1
399
+ this.deps.journal({
400
+ kind: 'note',
401
+ at: now(),
402
+ ref: state.ref,
403
+ text: `validate left review blockers — re-running implement (retry ${state.blockerRetries}/${MAX_ATTEMPTS - 1})`,
404
+ })
405
+ // AIDEV-NOTE: journal AFTER incrementing so a restart restores the
406
+ // incremented budget, not the pre-retry one.
407
+ this.snapshot('running')
408
+ this.deps.notify(
409
+ `/flow ${state.ref}: validate left review blockers — re-running implement (retry ${state.blockerRetries}/${MAX_ATTEMPTS - 1})`,
410
+ 'info',
411
+ )
412
+ // AIDEV-NOTE: the blockers live in the aven note, not in loop state — the
413
+ // suffix points the retried agent at it so the retry fixes something.
414
+ await this.sendPhasePrompt('implement', fixRoundSuffix(state.ref))
415
+ return true
416
+ }
417
+
418
+ async sendPhasePrompt(phase: Phase, suffix = ''): Promise<void> {
419
+ if (this.runState === null) return
420
+ // AIDEV-NOTE: PMR-V31Z 2.1 — the VE27 phase-ENTRY gate that stood here
421
+ // (checkPhaseEntry → reconcileStartPhase over the landing proof before
422
+ // every feedback prompt injection) is superseded: feedback entry is
423
+ // label-ordered for every mode (the PR, not a local merge, is the
424
+ // delivery), so there is no entry decision left to reconcile.
425
+ const labels = await this.deps.readLabels(this.runState.ref)
426
+ if (labels === null) {
427
+ await this.host.halt(
428
+ phase,
429
+ 'cannot read aven labels (fail-closed)',
430
+ 'aven_read_failed',
431
+ )
432
+ return
433
+ }
434
+ const result = await buildPhasePrompt(phase, {
435
+ ...this.runState.promptInput,
436
+ labels,
437
+ ...(phase === 'implement'
438
+ ? {
439
+ epicHasOpenChildren: await this.deps.epicHasOpenChildren(
440
+ this.runState.ref,
441
+ ),
442
+ }
443
+ : {}),
444
+ })
445
+ if (result.kind === 'block') {
446
+ await this.host.halt(phase, result.reason, 'prompt_send_failed')
447
+ return
448
+ }
449
+ this.deps.journal({
450
+ kind: 'phase-start',
451
+ at: now(),
452
+ ref: this.runState.ref,
453
+ phase,
454
+ })
455
+ const sessionFile = this.deps.getSessionFile?.() ?? null
456
+ if (sessionFile !== null && sessionFile.length > 0) {
457
+ this.deps.journal({
458
+ kind: 'main-session',
459
+ at: now(),
460
+ ref: this.runState.ref,
461
+ sessionFile,
462
+ })
463
+ }
464
+ // AIDEV-NOTE: PMR-T9ZQ 1.2 — owner identity refresh on every phase
465
+ // prompt. PROJECTED event (deps.journal routes to the projecting
466
+ // writer.record), unlike the journal-only 'main-session' above: the
467
+ // parked-run resume picker reads state.owner from the projection.
468
+ // Journaled even when the session file is unknown — pid is the liveness
469
+ // carrier. Best-effort: the journal dep contract is "never throws" and
470
+ // production wires it to writer.record, which swallows io errors.
471
+ this.deps.journal({
472
+ kind: 'owner-session',
473
+ at: now(),
474
+ ref: this.runState.ref,
475
+ sessionFile,
476
+ pid: process.pid,
477
+ })
478
+ this.runState.currentPhase = phase
479
+ // AIDEV-NOTE: PMR-HFK1 — phase transitions re-stamp the env so children
480
+ // spawned in later phases attribute to the phase doing the work.
481
+ stampFlowPhase(this.env, phase)
482
+ this.deps.onFlowEnvChange?.()
483
+ if (phase === 'validate' && !this.pendingResume) {
484
+ this.runState.validateStartedAt = now()
485
+ }
486
+ this.pendingResume = false
487
+ this.promptTurnGeneration = this.deps.getTurnGeneration?.() ?? null
488
+ this.deps.sendPrompt(result.prompt + suffix)
489
+ this.runState.awaitingOutcome = true
490
+ this.snapshot('running')
491
+ }
492
+
493
+ // AIDEV-NOTE: PMR-XTQQ — loop-state snapshot: journaled at start, every
494
+ // phase prompt (awaitingOutcome=true, running), the plan-approval pause
495
+ // (paused, awaitingOutcome=false — phase-3's pending protocol parks ONLY
496
+ // on awaitingOutcome=true + running), every retry increment, and on the
497
+ // terminal transitions (halted/done). Last-wins in the projection.
498
+ snapshot(status: LoopRunStatus, v2reason?: FlowReason): void {
499
+ if (this.runState === null) return
500
+ this.deps.journal({
501
+ kind: 'loop-state',
502
+ at: now(),
503
+ ref: this.runState.ref,
504
+ loop: {
505
+ phase: this.runState.currentPhase,
506
+ awaitingOutcome: this.runState.awaitingOutcome,
507
+ blockerRetries: this.runState.blockerRetries,
508
+ validateStartedAt: this.runState.validateStartedAt,
509
+ status,
510
+ },
511
+ })
512
+ // AIDEV-NOTE: PMR-ZV9Y 2.1 — snapshot is the v1 choke point AND the v2
513
+ // one: every status transition maps to exactly one state-change. `v2reason`
514
+ // is passed per-site because the choke point cannot always know it (all
515
+ // halts map to v2 `halted` but carry different reasons — aven_read_failed,
516
+ // blocker_budget_exhausted, prompt_send_failed, label_miss; paused maps to
517
+ // waiting_human but only the spec-approval pause has a reason). running/done
518
+ // carry none. The emission is guarded (see emitStateChange in
519
+ // flow/v2-emission.ts — PMR-H1GA moved the guard + master rationale
520
+ // there).
521
+ this.v2.emitStateChange(
522
+ this.runState.ref,
523
+ v2StateForStatus(status),
524
+ v2reason,
525
+ )
526
+ }
527
+ }
528
+
529
+ function now(): string {
530
+ return new Date().toISOString()
531
+ }