@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,476 @@
1
+ // AIDEV-NOTE: PMR-EZHA — the ONLY sanctioned write path for lifecycle
2
+ // labels. Reads labels, consults the pure gate (checkPhaseCompletion), and
3
+ // on refusal returns the gate reason as a tool error; on success execs the
4
+ // same writeAvenLabel path the flow loop uses. Idempotent: an
5
+ // already-complete phase returns ok without re-writing.
6
+ // AIDEV-NOTE: PMR-3MTZ — the plan phase's fresh write is additionally
7
+ // receipt-gated: readGateAnswer(ref, 'spec') must return 'approve' (the
8
+ // human's /flow answer receipt) before 'planned' is written; refusal is
9
+ // fail-closed like spec_approve (PMR-R5VB). PMR-J6TW: tickets carrying the
10
+ // `oneshot` label are EXEMPT — the oneshot route (PMR-3HMZ) never produces
11
+ // a receipt by design, so the gate is skipped for them at both check sites
12
+ // (here and spec_approve). The fast path stays receipt-free and
13
+ // implement/validate/feedback stay label-order-only.
14
+ // AIDEV-NOTE: PMR-VE27 — the feedback phase is close-out gated on BOTH the
15
+ // fresh-write and the already-recorded path (the deliberate ISC-2 change:
16
+ // close-out is the one phase whose idempotent fast path re-verifies). The
17
+ // shared policy (flow/lifecycle-policy.ts checkCloseout) is consulted AFTER
18
+ // the pure label-order gate and BEFORE any PMR-4S6V receipt, with mode from
19
+ // the run journal (readModeFn → readRunMode, fail-closed null), yolo from
20
+ // the existing isYoloRunFn, and the proof from the injected probe (prEffect
21
+ // = the journaled gh-pr-create tri-state). RE-BASED by PMR-V31Z (rebase
22
+ // resolution, human-approved supersede policy): the landed = PMR-5THZ
23
+ // ancestry closure proof leg is SUPERSEDED — it guarded the deleted local
24
+ // merge-main landing, and personal now delivers via PR, so every mode
25
+ // verifies the journaled gh-pr-create effect (the PR is the close-out
26
+ // evidence). A refusal is an isError result with recovery text and journals
27
+ // NO receipt (ISC-A-6). plan/implement/validate skip the block entirely —
28
+ // their fast paths stay byte-identical (ISC-A-1). The full decision
29
+ // contract is docs/piv-flow-lifecycle-matrix.md.
30
+ import type {
31
+ AgentToolResult,
32
+ ExtensionAPI,
33
+ } from '@earendil-works/pi-coding-agent'
34
+ import { getAgentDir } from '@earendil-works/pi-coding-agent'
35
+ import { Type } from 'typebox'
36
+ import {
37
+ readAvenLabels,
38
+ readGateAnswer,
39
+ readPlanRevision,
40
+ writeAvenLabel,
41
+ } from '../aven/client.ts'
42
+ import { checkPhaseCompletion } from '../flow/label-gate.ts'
43
+ import {
44
+ type CloseoutDecision,
45
+ checkCloseout,
46
+ type PrEffectProbe,
47
+ } from '../flow/lifecycle-policy.ts'
48
+ import { PHASE_LABEL, type Phase } from '../flow/orchestrate.ts'
49
+ import {
50
+ createReceiptJournal,
51
+ isYoloRun,
52
+ type ReceiptJournal,
53
+ readOneshotSnapshot,
54
+ readRouteConfirmedCurrent,
55
+ readRunMode,
56
+ readSpecAnswerBinding,
57
+ specAnswerBindingRefusal,
58
+ } from '../run-state.ts'
59
+ import type { EventWriter } from '../server/writer.ts'
60
+ import type { WorkMode } from '../work-mode.ts'
61
+ import { toolResult } from './result.ts'
62
+
63
+ export interface PhaseCompleteDetails {
64
+ ok: boolean
65
+ refused: boolean
66
+ already: boolean
67
+ reason: string
68
+ label: string
69
+ }
70
+
71
+ // AIDEV-NOTE: PMR-4S6V — best-effort receipt write shared by the fresh and
72
+ // already-complete paths; a journal failure never fails the tool result.
73
+ async function recordPhaseReceipt(
74
+ receipts: ReceiptJournal,
75
+ ref: string,
76
+ phase: Phase,
77
+ ): Promise<void> {
78
+ await receipts
79
+ .record({ ref, command: 'flow_phase_complete', target: phase })
80
+ .catch(() => {
81
+ // best-effort — journal failures never fail the tool result
82
+ })
83
+ }
84
+
85
+ // AIDEV-NOTE: PMR-VE27 — recovery text for a close-out refusal, re-based by
86
+ // PMR-V31Z (rebase supersede): every mode verifies the SAME journaled
87
+ // gh-pr-create effect now (the ancestry/merge-main recovery legs are
88
+ // superseded with the deleted local-merge landing), so the recovery is
89
+ // uniform — declare the effect via flow_land (personal feedback journals
90
+ // the prUrl there too; PMR-VDVJ). The checkCloseout reason stays
91
+ // in the text so the fail-closed leg is identifiable. PMR-YZ4D: flow_land
92
+ // takes ref + an optional review artifact only (tools/land.ts) — the old
93
+ // `route=pr` flag is dead vocabulary from the deleted merge-main landing,
94
+ // so the recovery names the live invocation.
95
+ function closeoutRefusalText(
96
+ decision: Exclude<CloseoutDecision, { kind: 'verified' }>,
97
+ ref: string,
98
+ ): string {
99
+ return `flow_phase_complete refused: ${decision.reason}. Recovery: run flow_land ${ref} so the gh-pr-create effect is declared in the run journal (PMR-VDVJ), then rerun flow_phase_complete for feedback.`
100
+ }
101
+
102
+ // AIDEV-NOTE: PMR-VE27 — shared isError shaping for the two new close-out
103
+ // refusal legs (mode-unreadable and the checkCloseout decision mapping);
104
+ // refused=true marks it a policy refusal in the details.
105
+ function closeoutRefusalResult(
106
+ text: string,
107
+ ): AgentToolResult<PhaseCompleteDetails> {
108
+ return toolResult(
109
+ text,
110
+ { ok: false, refused: true, already: false, reason: text, label: '' },
111
+ { isError: true },
112
+ )
113
+ }
114
+
115
+ // AIDEV-NOTE: PMR-YZ4D — the error-shaping helper the flow modules keep
116
+ // locally (flow/lifecycle-policy.ts, flow/ensure-labels.ts,
117
+ // flow/liveness.ts): a thrown probe's message becomes the refusal reason.
118
+ function errorText(error: unknown): string {
119
+ if (error instanceof Error) return error.message
120
+ return String(error)
121
+ }
122
+
123
+ // AIDEV-NOTE: PMR-N0D5 — isError shaping shared by the plan receipt gate's
124
+ // refusal legs (missing receipt, stale plan-revision binding); same
125
+ // refused=true policy-refusal details as closeoutRefusalResult.
126
+ function planGateRefusalResult(
127
+ text: string,
128
+ ): AgentToolResult<PhaseCompleteDetails> {
129
+ return toolResult(
130
+ text,
131
+ { ok: false, refused: true, already: false, reason: text, label: '' },
132
+ { isError: true },
133
+ )
134
+ }
135
+
136
+ // AIDEV-NOTE: PMR-4S6V — receipts defaults to the real run-journal-backed
137
+ // journal so index.ts stays untouched. record is best-effort: a journal
138
+ // failure must never turn a successful gate transition into a tool error
139
+ // (ISC-8). Receipts are journaled on BOTH the fresh-write success path and
140
+ // the already-complete fast path (ISC-5 divergence window), never on the
141
+ // refusal/failure paths.
142
+ export function registerPhaseCompleteTool(
143
+ pi: ExtensionAPI,
144
+ receipts: ReceiptJournal = createReceiptJournal(getAgentDir()),
145
+ // AIDEV-NOTE: PMR-XTQQ — mode-aware writer (server/writer.ts). Present =
146
+ // receipt writes route through it (journal-only while the daemon owns the
147
+ // projection); absent = today's exact full-writer behavior.
148
+ writer?: EventWriter,
149
+ // AIDEV-NOTE: yolo plan 3.1 — injectable for tests; production default
150
+ // reads the real run projection (fail-closed).
151
+ isYoloRunFn: (ref: string) => Promise<boolean> = isYoloRun,
152
+ // AIDEV-NOTE: PMR-VE27 — close-out provenance + proofs, injectable with
153
+ // production defaults (mirrors isYoloRunFn). readModeFn defaults to the
154
+ // run-journal reader (readRunMode — last run-start wins, fail-closed
155
+ // null). The prEffect probe has NO module default (it needs the
156
+ // index.ts pi.exec effect-journal closure): index.ts passes the
157
+ // production closure, and an ABSENT probe maps to a null proof, which
158
+ // checkCloseout refuses fail-closed ("dep not wired"). (PMR-YZ4D: the
159
+ // old "two proof probes" wording named the since-deleted
160
+ // isFlowBranchLanded ancestry probe.)
161
+ readModeFn: (ref: string) => Promise<WorkMode | null> = readRunMode,
162
+ // AIDEV-NOTE: PMR-V31Z (rebase supersede) — the isFlowBranchLandedFn
163
+ // ancestry param PMR-VE27 added here is DELETED with the local-merge
164
+ // landing it proved; prEffectFn is the only proof probe left.
165
+ prEffectFn?: (ref: string) => Promise<PrEffectProbe>,
166
+ // AIDEV-NOTE: PMR-N0D5 — epoch-aware yolo read for the PLAN receipt
167
+ // exemption ONLY. No module default: absent falls back to isYoloRunFn
168
+ // (the pre-N0D5 projection reader) so every existing injection and the
169
+ // feedback close-out dispatch keep their exact semantics (ISC-A-4); the
170
+ // PRODUCTION wiring passes isYoloRunCurrent at the index.ts registration
171
+ // seam, giving the exemption journal currency (bit after the latest
172
+ // run-start, non-terminal loop, else no exemption). The close-out yolo
173
+ // read below stays on isYoloRunFn — a terminal run's close-out dispatch
174
+ // is pinned behavior, not an exemption.
175
+ planYoloFn?: (ref: string) => Promise<boolean>,
176
+ ): void {
177
+ let effectiveReceipts = receipts
178
+ if (writer !== undefined) {
179
+ effectiveReceipts = createReceiptJournal(
180
+ getAgentDir(),
181
+ undefined,
182
+ writer.record,
183
+ )
184
+ }
185
+ pi.registerTool({
186
+ name: 'flow_phase_complete',
187
+ label: 'flow phase complete',
188
+ description:
189
+ 'Record completion of a PIV flow phase by applying its lifecycle label (plan=planned, implement=active, validate=review-passed, feedback=done). The gate re-checks phase order and refuses out-of-order completion with the reason; the plan phase additionally refuses until the human ran /flow answer <ref> approve — except for oneshot tickets, which complete plan receipt-free when the run-start journaled the oneshot snapshot OR the run carries a current plan.route-confirmed step-output together with the live oneshot label (PMR-AYMZ); a mid-run oneshot label alone refuses, and its recovery is re-running /flow <ref>, never the approve answer. The feedback phase additionally requires close-out evidence before done — every run needs a gh-pr-create effect journaled by flow_land (personal delivers via PR, PMR-V31Z) — and re-verifies that evidence even when done is already recorded. This is the ONLY way to write lifecycle labels — direct aven label edits on the ticket are blocked.',
190
+ promptSnippet:
191
+ 'Gated lifecycle-label completion for PIV flow phases (plan/implement/validate/feedback).',
192
+ promptGuidelines: [
193
+ 'Call flow_phase_complete to close a flow phase — never run `aven edit <ref> --label <lifecycle>` yourself; that mutation is blocked.',
194
+ 'A refusal carries the gate reason (missing prior phase); run the missing phase, do not retry the call.',
195
+ 'The plan phase additionally requires a human approval receipt: flow_phase_complete(plan) refuses until the human ran `/flow answer <ref> approve`. On that refusal, tell the human to run `/flow answer <ref> approve`, then re-call flow_phase_complete once the receipt exists — never fake or bypass it with raw aven commands. The receipt is also FRESHNESS-checked (PMR-N0D5): a refusal naming a stale plan-revision binding or a missing binding means the plan changed after the approval was recorded — the human re-runs `/flow answer <ref> approve` once the plan is final, then the gate re-checks. Tickets carrying the `oneshot` label skip this receipt gate entirely (the oneshot route never produces a receipt): the exemption fires from the run-start oneshot snapshot, or mid-run when a current `plan.route-confirmed` step-output is journaled AND the live `oneshot` label is present (PMR-AYMZ). A refusal naming the oneshot route as not exempt means neither leg holds — the recovery is the human re-running `/flow <ref>` (the fresh run-start snapshots the label), NEVER `/flow answer <ref> approve`: a oneshot has no plan file, so the approve receipt cannot bind.',
196
+ 'flow_phase_complete(feedback) is close-out gated: every mode needs the gh-pr-create effect declared via `flow_land <ref>` first (personal delivers via PR, PMR-V31Z), then re-call. The gate re-verifies even when done is already recorded — never bypass it with raw aven commands.',
197
+ ],
198
+ parameters: Type.Object({
199
+ ref: Type.String({ description: 'Aven ticket ref, e.g. PMR-ABC1' }),
200
+ phase: Type.Union(
201
+ [
202
+ Type.Literal('plan'),
203
+ Type.Literal('implement'),
204
+ Type.Literal('validate'),
205
+ Type.Literal('feedback'),
206
+ ],
207
+ {
208
+ description: 'The flow phase being marked complete',
209
+ },
210
+ ),
211
+ }),
212
+ async execute(
213
+ _toolCallId: string,
214
+ params: { ref: string; phase: Phase },
215
+ ): Promise<AgentToolResult<PhaseCompleteDetails>> {
216
+ const labels = await readAvenLabels(params.ref)
217
+ if (labels === null) {
218
+ return toolResult(
219
+ `flow_phase_complete: cannot read aven labels for ${params.ref} (fail-closed)`,
220
+ { ok: false, refused: false, already: false, reason: '', label: '' },
221
+ { isError: true },
222
+ )
223
+ }
224
+ const gate = checkPhaseCompletion(params.phase, labels)
225
+ if (!gate.ok) {
226
+ return toolResult(
227
+ `flow_phase_complete refused phase "${params.phase}" on ${params.ref}: ${gate.reason}`,
228
+ {
229
+ ok: false,
230
+ refused: true,
231
+ already: false,
232
+ reason: gate.reason ?? '',
233
+ label: '',
234
+ },
235
+ { isError: true },
236
+ )
237
+ }
238
+ // AIDEV-NOTE: PMR-VE27 — the feedback close-out gate (ISC-2/ISC-3),
239
+ // covering BOTH the fresh-write and the already-recorded path: the
240
+ // consult sits before the label-presence fast path below, so an
241
+ // already-complete feedback phase re-verifies its evidence instead of
242
+ // trusting the label (labels are claims, not proof). The pure order
243
+ // gate above ran first, so out-of-order completions keep their order
244
+ // refusal and the probes are not spent on them. Every fail-closed leg
245
+ // below (mode null, absent probe dep, failed probe, missing journal
246
+ // evidence) refuses with recovery text and journals NO receipt.
247
+ if (params.phase === 'feedback') {
248
+ // AIDEV-NOTE: PMR-YZ4D — the three probe reads below are raw
249
+ // injected calls; a throw maps fail-closed onto that probe's
250
+ // failure leg instead of escaping as a generic tool exception (the
251
+ // same throw-to-failure-leg mapping the loop-sink plumbing applies
252
+ // via probePrEffect/resolveCloseoutProofs in
253
+ // flow/lifecycle-policy.ts): mode → null (the existing
254
+ // unreadable-mode refusal below), yolo → false (production
255
+ // isYoloRun's own read-failure semantic), prEffect → the unreadable
256
+ // tri-state whose reason checkCloseout embeds in the refusal text.
257
+ // No probe throw can reach the label write or the receipt journal.
258
+ let mode: WorkMode | null
259
+ try {
260
+ mode = await readModeFn(params.ref)
261
+ } catch {
262
+ mode = null
263
+ }
264
+ if (mode === null) {
265
+ const text = `flow_phase_complete refused: cannot determine the run mode for close-out verification on ${params.ref} — the run journal has no readable run-start event. Start the flow with /flow ${params.ref} so the mode is journaled, then rerun flow_phase_complete for feedback.`
266
+ return closeoutRefusalResult(text)
267
+ }
268
+ let yolo: boolean
269
+ try {
270
+ yolo = await isYoloRunFn(params.ref)
271
+ } catch {
272
+ yolo = false
273
+ }
274
+ let prEffect: PrEffectProbe | null = null
275
+ if (prEffectFn !== undefined) {
276
+ try {
277
+ prEffect = await prEffectFn(params.ref)
278
+ } catch (error) {
279
+ prEffect = { kind: 'unreadable', reason: errorText(error) }
280
+ }
281
+ }
282
+ const closeout = checkCloseout({
283
+ mode,
284
+ yolo,
285
+ proofs: { prEffect },
286
+ })
287
+ if (closeout.kind !== 'verified') {
288
+ const text = closeoutRefusalText(closeout, params.ref)
289
+ return closeoutRefusalResult(text)
290
+ }
291
+ }
292
+ const label = PHASE_LABEL[params.phase]
293
+ if (labels.includes(label)) {
294
+ await recordPhaseReceipt(effectiveReceipts, params.ref, params.phase)
295
+ return toolResult(
296
+ `flow_phase_complete: "${label}" already recorded on ${params.ref} — phase ${params.phase} was already complete`,
297
+ { ok: true, refused: false, already: true, reason: '', label },
298
+ )
299
+ }
300
+ // AIDEV-NOTE: PMR-3MTZ / PMR-J6TW — plan-phase receipt gate (fail-closed,
301
+ // the spec_approve PMR-R5VB pattern): the fresh write of 'planned' must
302
+ // be preceded by a human approval receipt (readGateAnswer(ref, 'spec')
303
+ // === 'approve') — EXCEPT when an exemption leg fires (amended by
304
+ // PMR-N0D5 + PMR-AYMZ; each leg's provenance rules live in the
305
+ // dedicated anchors below): (1) the run-start oneshot snapshot when a
306
+ // journal exists (the live `oneshot` label only for truly standalone
307
+ // calls), (2) the confirmed-route leg — an epoch-current
308
+ // plan.route-confirmed step-output journaled together with the live
309
+ // `oneshot` label — or (3) journaled yolo. The oneshot route
310
+ // (PMR-3HMZ) never produces a receipt by design, so an exempted write
311
+ // proceeds right after the human size/route confirmation. A live
312
+ // label ALONE mid-run cannot mint an exemption: that refusal carries
313
+ // the re-run /flow <ref> recovery, never the approve answer. The
314
+ // labels read stays fail-closed: a read failure refuses before this
315
+ // block for every route. null covers both an absent spec-answer
316
+ // metadata block and an aven read failure; 'reject' or any other
317
+ // choice refuses too. The already-complete fast path below stays
318
+ // receipt-free (PMR-4S6V idempotency), and implement/validate/feedback
319
+ // remain label-order-only.
320
+ // AIDEV-NOTE: PMR-ZWX8 — the oneshot exemption is a PROMPT-LEVEL
321
+ // checkpoint by accepted design: the `oneshot` label is agent-writable
322
+ // (type labels are deliberately outside lifecycleLabelMutation), and
323
+ // the human's explicit oneshot route invocation IS the size
324
+ // confirmation — adding the label by hand is that same decision.
325
+ // Interception of `--label oneshot` bash edits was considered and
326
+ // REJECTED: a ref-scoped matcher duplicates fragile CLI parsing (the
327
+ // PMR-5RFR/PMR-SB3H matcher-evasion treadmill) and cannot cover
328
+ // `aven add --label oneshot`, the legitimate human-directed oneshot
329
+ // setup path, without blocking unrelated filings whenever any flow is
330
+ // active. Residual risk is accepted at the prompt level (PMR-ZM8J):
331
+ // the gate performs NO mode check — "personal mode" is the inherited
332
+ // prompt-level bound (the human drives the session in the sanctioned
333
+ // flow), not an enforcement claim; a work-mode run whose agent sets
334
+ // the label would mint the exemption too. Aven's ticket
335
+ // history makes a rogue self-label auditable after the fact. Revisit
336
+ // this seam if the trust model ever needs enforced label provenance.
337
+ // PMR-AYMZ: the confirmed-route leg extends this same trust shape —
338
+ // the journaled plan.route-confirmed step-output is agent-written
339
+ // evidence OF the human's ask_user_question answer (the route gate
340
+ // journals it only after the human confirms the route), so it rides
341
+ // the same prompt-level-checkpoint trust as the label and stays
342
+ // auditable after the fact via the append-only journal.
343
+ // AIDEV-NOTE: yolo plan 3.1 — third exemption path beside the oneshot
344
+ // label (PMR-ZWX8): input.yolo === true is journaled by the run server
345
+ // from the human's CLI invocation (--yolo), not from any agent-writable
346
+ // label or metadata, so a yolo ref cannot be self-granted by the agent
347
+ // and may complete the plan write without the approval receipt. The
348
+ // isYoloRun read is fail-closed (absent projection / read failure =
349
+ // not yolo → full gate). The receiptMetadataMutation bash interceptor
350
+ // in index.ts stays untouched: the exemption is this explicit branch
351
+ // in the gate check, never a forged receipt.
352
+ // AIDEV-NOTE: PMR-N0D5 — provenance/currency tightening of BOTH
353
+ // exemption paths (the exemption SHAPE was unchanged at N0D5;
354
+ // PMR-AYMZ later added the confirmed-route leg — see the oneshot
355
+ // bullet):
356
+ // • Oneshot is JOURNAL-FIRST: a journaled run-start for the ref
357
+ // switches the exemption to the run-start oneshot snapshot (the
358
+ // ticket's label state at start time), so a mid-run label add
359
+ // cannot mint it; null snapshot (no journaled run-start) keeps the
360
+ // live-label fallback for truly standalone calls (sanctioned
361
+ // policy decision, aven note H4NADAF97Y6HD1QF). PMR-AYMZ adds the
362
+ // confirmed-route leg for runs whose snapshot is absent/false: an
363
+ // epoch-current ok=true plan.route-confirmed step-output journaled
364
+ // in this run AND the live `oneshot` label together mint the
365
+ // exemption; the label alone mid-run still cannot and refuses
366
+ // with the re-run-/flow recovery (never the approve answer — a
367
+ // oneshot has no plan file to bind). Trust note (conscious
368
+ // policy, not a silent widening): BOTH signals of the new leg are
369
+ // agent-writable (the journal event and the type label), so the
370
+ // residual self-minting risk is accepted as an extension of the
371
+ // PMR-ZWX8 policy shape — the bound is prompt-level/inherited,
372
+ // NOT enforced: the gate performs no mode check, so "personal
373
+ // mode" describes where the sanctioned flow runs, not a guard
374
+ // (PMR-ZM8J). Auditable
375
+ // after the fact via the append-only journal and aven ticket
376
+ // history.
377
+ // • Yolo rides planYoloFn (production: isYoloRunCurrent — bit
378
+ // journaled after the latest run-start, non-terminal loop, else
379
+ // no exemption).
380
+ // • The approve answer is BOUND to the plan revision: a plan edit
381
+ // after the answer, an unbound journaled answer, or an
382
+ // unresolvable plan revision refuse with the re-answer recovery
383
+ // (specAnswerBindingRefusal). No journal → standalone
384
+ // metadata-only gate, unchanged (PMR-FA3D).
385
+ const oneshotSnapshot = await readOneshotSnapshot(params.ref)
386
+ let planOneshot: boolean
387
+ if (oneshotSnapshot !== null) {
388
+ planOneshot = oneshotSnapshot
389
+ } else {
390
+ planOneshot = labels.includes('oneshot')
391
+ }
392
+ // AIDEV-NOTE: PMR-AYMZ — the confirmed-route leg: an epoch-current
393
+ // ok=true plan.route-confirmed step-output journaled in this run AND
394
+ // the live `oneshot` label TOGETHER mint the plan-gate exemption.
395
+ // The AND is load-bearing: planned tickets journal
396
+ // plan.route-confirmed too, so the journaled event alone must never
397
+ // exempt — the live label is the oneshot-ness signal. See the
398
+ // PMR-N0D5 anchor below for the trust model (prompt-level/inherited:
399
+ // no mode check enforces the personal-mode bound, PMR-ZM8J).
400
+ const routeConfirmed = await readRouteConfirmedCurrent(params.ref)
401
+ let routeExempt: boolean
402
+ if (routeConfirmed && labels.includes('oneshot')) {
403
+ routeExempt = true
404
+ } else {
405
+ routeExempt = false
406
+ }
407
+ let planYolo: boolean
408
+ if (planYoloFn !== undefined) {
409
+ planYolo = await planYoloFn(params.ref)
410
+ } else {
411
+ planYolo = await isYoloRunFn(params.ref)
412
+ }
413
+ if (
414
+ params.phase === 'plan' &&
415
+ !planOneshot &&
416
+ !routeExempt &&
417
+ !planYolo
418
+ ) {
419
+ // AIDEV-NOTE: PMR-AYMZ — oneshot-shaped refusal, keyed on the LIVE
420
+ // label only and placed BEFORE readGateAnswer: when the label is
421
+ // present but neither exemption leg holds, the approve receipt can
422
+ // never bind (a oneshot has no plan file), so skip the receipt read
423
+ // entirely and refuse with the re-run-/flow recovery. When the
424
+ // label is absent, the standard approve refusal below stays
425
+ // byte-identical (planned tickets keep their correct recovery
426
+ // text).
427
+ if (labels.includes('oneshot')) {
428
+ return planGateRefusalResult(
429
+ `flow_phase_complete refused: the oneshot route is not exempt on ${params.ref} — the run-start oneshot snapshot is absent/false and no current plan.route-confirmed step-output is journaled for this run. The live oneshot label alone cannot mint the exemption mid-run (PMR-N0D5 journal-first provenance; PMR-AYMZ adds the confirmed-route leg). A plan.route-confirmed row journaled without ok=true (or stale, before the latest run-start) does not count: the in-run recovery (PMR-4ANM) is re-journaling it via flow_submit with step="plan.route-confirmed", output.phase="plan", ok=true in this run; otherwise Recovery: the human re-runs /flow ${params.ref} — the fresh run-start snapshots the now-present oneshot label and the exemption fires in the new epoch. Do NOT run /flow answer ${params.ref} approve: an oneshot has no plan file, so the approve receipt cannot bind.`,
430
+ )
431
+ }
432
+ const answer = await readGateAnswer(params.ref, 'spec')
433
+ if (answer !== 'approve') {
434
+ let found: string
435
+ if (answer === null) {
436
+ found = 'none/unreadable'
437
+ } else {
438
+ found = answer
439
+ }
440
+ return planGateRefusalResult(
441
+ `flow_phase_complete refused: no human approval receipt for plan on ${params.ref} — the human must run /flow answer ${params.ref} approve (human-only slash command; the receipt is the exact-ref-guarded aven spec-answer metadata). Found: ${found}. After the human answers, re-call flow_phase_complete.`,
442
+ )
443
+ }
444
+ const binding = await readSpecAnswerBinding(params.ref)
445
+ if (binding.hasJournal) {
446
+ const currentRevision = await readPlanRevision(params.ref)
447
+ const bindingRefusal = specAnswerBindingRefusal(
448
+ binding,
449
+ currentRevision,
450
+ params.ref,
451
+ )
452
+ if (bindingRefusal !== null) {
453
+ return planGateRefusalResult(
454
+ `flow_phase_complete refused: ${bindingRefusal}`,
455
+ )
456
+ }
457
+ }
458
+ }
459
+ const written = await writeAvenLabel(params.ref, label)
460
+ if (!written) {
461
+ return toolResult(
462
+ `flow_phase_complete: aven write failed for "${label}" on ${params.ref}`,
463
+ { ok: false, refused: false, already: false, reason: '', label: '' },
464
+ { isError: true },
465
+ )
466
+ }
467
+ // AIDEV-NOTE: PMR-4S6V — journal the receipt only after the label write succeeded;
468
+ // best-effort, never fails the ok result.
469
+ await recordPhaseReceipt(effectiveReceipts, params.ref, params.phase)
470
+ return toolResult(
471
+ `flow_phase_complete: "${label}" landed on ${params.ref} — phase ${params.phase} recorded, the label is verified by this result`,
472
+ { ok: true, refused: false, already: false, reason: '', label },
473
+ )
474
+ },
475
+ })
476
+ }
@@ -0,0 +1,18 @@
1
+ // AIDEV-NOTE: PMR-T22H — shared AgentToolResult shaping for pi-flow tools:
2
+ // one text content block, typed details, isError only when set.
3
+ import type { AgentToolResult } from '@earendil-works/pi-coding-agent'
4
+
5
+ export function toolResult<Details>(
6
+ text: string,
7
+ details: Details,
8
+ opts: { isError?: boolean } = {},
9
+ ): AgentToolResult<Details> {
10
+ const result: AgentToolResult<Details> = {
11
+ content: [{ type: 'text', text }],
12
+ details,
13
+ }
14
+ if (opts.isError === true) {
15
+ result.isError = true
16
+ }
17
+ return result
18
+ }
@@ -0,0 +1,44 @@
1
+ // AIDEV-NOTE: PMR-Y6YP — extracted from tools/code-review.ts to break the
2
+ // land.ts <-> code-review.ts module cycle (code-review.ts used to import
3
+ // defaultResolveHead from land.ts; land.ts needs productionReviewDeps;
4
+ // PMR-V31Z 7.2 removed the code_review -> land import, the extraction
5
+ // stays for the shared wiring). This module is a LEAF: it must never
6
+ // import from land.ts or code-review.ts.
7
+ import { existsSync } from 'node:fs'
8
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
9
+ import { getFlowWorktree } from '../flow/worktree-context.ts'
10
+ import { worktreeList } from '../worktree/herdr.ts'
11
+ import type { ReviewDeps } from './code-review-parse.ts'
12
+
13
+ // AIDEV-NOTE: PMR-0KMQ — shared factory: the fresh-context review gate
14
+ // (review/review.ts, commit mode) and the deviation gate (tools/deviation.ts)
15
+ // reuse this exact wiring so all three gates resolve the same VERIFIED bound
16
+ // flow worktree (resolveReviewWorktree: binding → aven note → herdr, each
17
+ // candidate verified via common-git-dir + branch). Takes a bare repoRoot
18
+ // instead of the tool context so non-code-review callers can pass ctx.cwd.
19
+ export function productionReviewDeps(
20
+ pi: ExtensionAPI,
21
+ repoRoot: string,
22
+ ): ReviewDeps {
23
+ return {
24
+ getFlowWorktree,
25
+ avenShowFull: async (ref: string) => {
26
+ const result = await pi.exec('aven', ['show', ref, '--full'], {
27
+ cwd: repoRoot,
28
+ })
29
+ if (result.code !== 0) {
30
+ throw new Error(result.stderr || `aven show ${ref} failed`)
31
+ }
32
+ return result.stdout
33
+ },
34
+ herdrWorktreeList: () => worktreeList(pi, repoRoot),
35
+ exec: async (cmd: string, args: string[], opts?: { cwd?: string }) => {
36
+ const result = await pi.exec(cmd, args, {
37
+ cwd: opts?.cwd ?? repoRoot,
38
+ })
39
+ return { code: result.code, stdout: result.stdout, stderr: result.stderr }
40
+ },
41
+ exists: (p: string) => existsSync(p),
42
+ repoRoot,
43
+ }
44
+ }