@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,737 @@
1
+ // AIDEV-NOTE: PMR-R9EN fix round 2 — agent-callable deviation gate. The
2
+ // validate prompt (D3/D4) used to name TS functions (startDeviationReview /
3
+ // parseDeviationArtifact) an LLM agent cannot invoke; this tool wraps the
4
+ // whole step: compose the reviewer prompt (review/deviation.ts), spawn+await
5
+ // the fresh-context reviewer subagent, and parse the artifact strictly with
6
+ // the deviation-gate contract. Fail-closed: a spawn failure or a malformed
7
+ // artifact is an isError tool result — the agent re-runs, never treats it as
8
+ // 0 deviations. Pure seams (prompt composition + result mapping) are exported
9
+ // for tests; execute only wires them to the subagent path.
10
+
11
+ import { rmSync } from 'node:fs'
12
+ import { mkdtemp, writeFile } from 'node:fs/promises'
13
+ import { tmpdir } from 'node:os'
14
+ import { join } from 'node:path'
15
+ import type {
16
+ AgentToolResult,
17
+ ExtensionAPI,
18
+ ExtensionToolContext,
19
+ } from '@earendil-works/pi-coding-agent'
20
+ import { getAgentDir } from '@earendil-works/pi-coding-agent'
21
+ import type { SubagentResult } from '@gtheys/pi-interactive-subagents'
22
+ import { Type } from 'typebox'
23
+ import { loadConfig } from '../config.ts'
24
+ import { healFlowBinding } from '../flow/binding-heal.ts'
25
+ import { MODE_PROFILE } from '../mode-profile.ts'
26
+ import {
27
+ buildDeviationReviewPrompt,
28
+ checkDiffLinesRead,
29
+ DEVIATION_INLINE_DIFF_MAX,
30
+ type DeviationReviewInput,
31
+ startDeviationReview,
32
+ } from '../review/deviation.ts'
33
+ import type { FlowRunEvent } from '../run-state.ts'
34
+ import {
35
+ createDaemonAliveProbe,
36
+ createEventWriter,
37
+ type EventWriter,
38
+ } from '../server/writer.ts'
39
+ import {
40
+ commitMessagesForRange,
41
+ diffForRange,
42
+ type Exec,
43
+ type FlowRange,
44
+ resolveFlowRange,
45
+ } from '../shared/diff-base.ts'
46
+ import { readFlowBase } from '../shared/flow-base.ts'
47
+ import {
48
+ resolveStableRange,
49
+ stableRefusalText,
50
+ } from '../shared/stable-range.ts'
51
+ import {
52
+ type DeviationArtifact,
53
+ parseDeviationArtifact,
54
+ } from '../validate/deviation-gate.ts'
55
+ import {
56
+ buildGateTarget,
57
+ deriveSubtaskAttribution,
58
+ type GateTarget,
59
+ type GateVerification,
60
+ gateTargetId,
61
+ verifyGateWithExec,
62
+ } from '../validate/gate-target.ts'
63
+ import { modeForToplevel, type WorkMode } from '../work-mode.ts'
64
+ import type { ReviewDeps } from './code-review-parse.ts'
65
+ import { toolResult } from './result.ts'
66
+ import { productionReviewDeps } from './review-deps.ts'
67
+
68
+ export interface DeviationReviewToolParams {
69
+ mode: 'work' | 'personal'
70
+ ref: string
71
+ spec: string
72
+ avenNotes: string
73
+ }
74
+
75
+ /** Diff + commit messages the tool resolved itself (PMR-R4AP). */
76
+ export interface ResolvedRange {
77
+ diff: string
78
+ commitMessages: string
79
+ flowRange: FlowRange
80
+ }
81
+
82
+ export type ResolvedRangeResult =
83
+ | { ok: true; value: ResolvedRange }
84
+ | { ok: false; reason: string }
85
+
86
+ export type DeviationCwdResolution =
87
+ | { ok: true; cwd: string }
88
+ | { ok: false; reason: string }
89
+
90
+ // AIDEV-NOTE: PMR-0KMQ — deviation gate cwd must be the VERIFIED bound flow
91
+ // worktree, never the raw binding path (PMR-7ZEE) or a silent ctx.cwd fallback:
92
+ // readFlowBase keys branch.<feature>.flowbase and only resolves from the
93
+ // feature-branch checkout. Reuses the code_review resolver (binding → aven
94
+ // note → herdr list; each candidate verified: path exists, common git dir
95
+ // matches the session repo per PMR-9XR0, HEAD branch matches). When no source
96
+ // verifies we fail CLOSED with the mismatch reason — a silent fallback to the
97
+ // session checkout is exactly the "flow worktree is not bound" refusal this
98
+ // ticket removes from the happy path.
99
+ export async function resolveDeviationCwd(
100
+ ref: string,
101
+ deps: ReviewDeps,
102
+ ): Promise<DeviationCwdResolution> {
103
+ try {
104
+ // AIDEV-NOTE: PMR-DRKH — heal-first: resolving doubles as re-arming the
105
+ // module binding after a pi reload; the fail-closed shape is unchanged.
106
+ const heal = await healFlowBinding(ref, deps)
107
+ if (heal.ok) {
108
+ return { ok: true, cwd: heal.worktree.path }
109
+ }
110
+ return { ok: false, reason: heal.reason }
111
+ } catch (error) {
112
+ let msg: string
113
+ if (error instanceof Error) {
114
+ msg = error.message
115
+ } else {
116
+ msg = String(error)
117
+ }
118
+ return { ok: false, reason: msg }
119
+ }
120
+ }
121
+
122
+ // AIDEV-NOTE: PMR-R4AP — the tool, not the agent, owns the diff range: base
123
+ // branch recorded at worktree create (shared/flow-base.ts) -> shared
124
+ // resolver (shared/diff-base.ts, same one pi-review uses) -> diff + commit
125
+ // messages. Missing base, unresolvable base or empty range is an error —
126
+ // the gate never runs on an empty diff.
127
+ // AIDEV-NOTE: PMR-5NZB — the baseRef handed to the shared resolver is
128
+ // mode-keyed data (MODE_PROFILE[mode].baseResolution), so BOTH gates resolve
129
+ // personal mode through the ONE shared stable-range resolver
130
+ // (shared/stable-range.ts) and can never disagree (PMR-R4AP). PMR-K74M: the
131
+ // mode itself is DERIVED inside execute (deriveGateMode) — a wrong
132
+ // LLM-supplied params.mode can no longer flip the base, which makes the
133
+ // never-disagree claim literally true. personal: the recorded creation-time
134
+ // flowbasesha, integrity-probed — merge-base(HEAD, <local flowbase branch>)
135
+ // must EQUAL the recorded sha; a mid-flow rebase or base-merge refuses
136
+ // fail-closed ('diverged') instead of re-anchoring to a moving base. NEVER
137
+ // the base's upstream ref (PMR-MH1Y/DQ7Z). work: the flowbasesha recorded
138
+ // at worktree create (legacy fallback: the branch) — byte-for-byte the
139
+ // previous behavior.
140
+ // AIDEV-NOTE: PMR-7N3D (REPLACED by PMR-5NZB — kept as history) — personal
141
+ // mode used to resolve the gate-time base as merge-base(HEAD, <local
142
+ // flowbase branch>): rebase-aware, because a mid-flow rebase (PMR-1KAE)
143
+ // moved the merge-base while the recorded flowbasesha could not self-heal
144
+ // and swept every commit other flows landed on main since worktree create.
145
+ // The stable-range contract inverted that policy: the recorded sha is now
146
+ // the pin and a moved merge-base is an integrity failure, not a new base.
147
+ // AIDEV-NOTE: PMR-K74M — same derivation review.ts gets from resolveMode
148
+ // (config.ts), but pinned to the flow worktree: resolveMode runs its
149
+ // rev-parse in the session cwd, while this gate must classify the WORKTREE
150
+ // toplevel (a work-repo worktree can sit outside the session checkout).
151
+ // A derivation failure (e.g. malformed pi-flow config) is a fail-closed
152
+ // error result in execute, never a silent params.mode fallback.
153
+ // AIDEV-NOTE: PMR-5NZB — exported for the code_review tuicr opener
154
+ // (tools/code-review.ts): the opener's range policy is mode-keyed too, so
155
+ // it derives the mode from the RESOLVED review worktree through this same
156
+ // seam — one derivation, never the session cwd, never LLM input.
157
+ export async function deriveGateMode(
158
+ exec: Exec,
159
+ cwd: string,
160
+ ): Promise<WorkMode> {
161
+ const { stdout } = await exec('git', ['rev-parse', '--show-toplevel'], {
162
+ cwd,
163
+ })
164
+ const config = await loadConfig(cwd)
165
+ return modeForToplevel(stdout.trim(), config.workRoots)
166
+ }
167
+
168
+ // AIDEV-NOTE: PMR-8HST/PMR-S4W0 — best-effort temp-dir removal shared by the
169
+ // write-failure catch and the finally in execute: a throwing rmSync
170
+ // (busy/shared TMPDIR) must never replace the tool result with an unhandled
171
+ // exception. Mirrors sweepTmpDirs in test/tmpdir.ts.
172
+ export function tryRemove(dir: string): void {
173
+ try {
174
+ rmSync(dir, { recursive: true, force: true })
175
+ } catch {
176
+ // swallow: cleanup is best-effort and must not mask the tool result
177
+ }
178
+ }
179
+
180
+ export async function resolveDeviationRange(
181
+ exec: Exec,
182
+ cwd: string,
183
+ mode: WorkMode,
184
+ ): Promise<ResolvedRangeResult> {
185
+ let range: FlowRange
186
+ if (MODE_PROFILE[mode].baseResolution === 'recorded-sha-integrity') {
187
+ // AIDEV-NOTE: PMR-5NZB — personal resolves through the ONE shared
188
+ // stable-range resolver; its typed refusal becomes the gate's
189
+ // fail-closed {ok:false} with the recovery text intact.
190
+ const stable = await resolveStableRange(exec, cwd)
191
+ if (!stable.ok) {
192
+ return { ok: false, reason: stableRefusalText(stable, 'deviation') }
193
+ }
194
+ range = stable.value
195
+ } else {
196
+ // AIDEV-NOTE: PMR-5NZB — work mode byte-for-byte unchanged: the
197
+ // recorded flowbasesha (legacy fallback: the recorded branch) anchors
198
+ // the range; no integrity probe, no stable-range resolver.
199
+ const base = await readFlowBase(exec, cwd)
200
+ if (!base.ok) return base
201
+ const baseRef = base.value.sha ?? base.value.branch
202
+ const resolved = await resolveFlowRange(
203
+ exec,
204
+ cwd,
205
+ base.value.branch,
206
+ baseRef,
207
+ )
208
+ if (!resolved.ok) return resolved
209
+ range = resolved.value
210
+ }
211
+ try {
212
+ const diff = await diffForRange(exec, cwd, range.range)
213
+ if (diff.trim() === '') {
214
+ return { ok: false, reason: `empty diff for ${range.range}` }
215
+ }
216
+ const commitMessages = await commitMessagesForRange(exec, cwd, range.range)
217
+ return { ok: true, value: { diff, commitMessages, flowRange: range } }
218
+ } catch (error) {
219
+ return {
220
+ ok: false,
221
+ reason: error instanceof Error ? error.message : String(error),
222
+ }
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Compose the reviewer prompt from the tool params + the resolved range.
228
+ * When a gate target is supplied the pinned range rides along so the
229
+ * reviewer can echo it back (PMR-6EEW echo contract).
230
+ */
231
+ export function deviationReviewPromptFrom(
232
+ params: DeviationReviewToolParams,
233
+ resolved: Pick<ResolvedRange, 'diff' | 'commitMessages'>,
234
+ target: GateTarget | null = null,
235
+ diffPath?: string,
236
+ ): string {
237
+ const input: DeviationReviewInput = {
238
+ mode: params.mode,
239
+ spec: params.spec,
240
+ diff: resolved.diff,
241
+ commitMessages: resolved.commitMessages,
242
+ avenNotes: params.avenNotes,
243
+ }
244
+ if (target !== null) {
245
+ input.pinnedRange = { baseSha: target.baseSha, headSha: target.headSha }
246
+ }
247
+ if (diffPath !== undefined) input.diffPath = diffPath
248
+ return buildDeviationReviewPrompt(input)
249
+ }
250
+
251
+ /**
252
+ * AIDEV-NOTE: PMR-6EEW gate integrity — verify the verifier. Delegates to
253
+ * the shared exec-backed check in validate/gate-target.ts. Kept as a named
254
+ * seam for the deviation tool tests.
255
+ */
256
+ export async function verifyDeviationGateResult(
257
+ exec: Exec,
258
+ cwd: string,
259
+ target: GateTarget,
260
+ artifact: string,
261
+ ): Promise<GateVerification> {
262
+ return verifyGateWithExec(exec, cwd, target, artifact)
263
+ }
264
+
265
+ /** Best-effort journal write — never breaks the gate (house rule). Routed
266
+ * through the mode-aware writer (PMR-XTQQ): journal-only while the daemon
267
+ * owns the projection, full writer when absent. */
268
+ async function journalGateEvent(
269
+ event: FlowRunEvent,
270
+ writer: EventWriter,
271
+ ): Promise<void> {
272
+ await writer.record(event)
273
+ }
274
+
275
+ /** One-line description of the range, shown to agent and human. */
276
+ export function describeRange(r: FlowRange): string {
277
+ return `base ${r.baseBranch} @ ${r.baseSha}, range ${r.range} (${r.commitCount} commit(s), HEAD ${r.headSha})`
278
+ }
279
+
280
+ export type DeviationReviewDetails = DeviationArtifact
281
+
282
+ // AIDEV-NOTE: PMR-MH1Y — bound the excerpt so a pathological artifact cannot
283
+ // blow up the tool result; tail-biased because the verdict section is emitted
284
+ // at the end of the reviewer reply. PMR-H17H: keep a bounded HEAD slice too —
285
+ // the numbered prose findings (the exact diagnosis the excerpt exists for)
286
+ // are enumerated BEFORE the verdict section and a pure tail can cut them off.
287
+ const RAW_ARTIFACT_EXCERPT_MAX = 4000
288
+ const RAW_ARTIFACT_EXCERPT_HEAD = 800
289
+
290
+ function rawArtifactExcerpt(artifact: string): string {
291
+ if (artifact.length <= RAW_ARTIFACT_EXCERPT_MAX) {
292
+ return artifact
293
+ }
294
+ const head = artifact.slice(0, RAW_ARTIFACT_EXCERPT_HEAD)
295
+ const tail = artifact.slice(
296
+ -(RAW_ARTIFACT_EXCERPT_MAX - RAW_ARTIFACT_EXCERPT_HEAD),
297
+ )
298
+ return `${head}\n…\n${tail}`
299
+ }
300
+
301
+ /**
302
+ * Map a raw reviewer artifact to the tool result. A malformed artifact is an
303
+ * isError result carrying the parse reason — never a silent 0.
304
+ * AIDEV-NOTE: PMR-MH1Y — a parse failure also carries the raw reviewer
305
+ * artifact (bounded) so the caller can SEE what the reviewer emitted and
306
+ * diagnose the mismatch. PMR-C0YV failed 3 identical blind re-runs because
307
+ * the error named only the count parity, never the artifact.
308
+ */
309
+ export function deviationResultToToolResult(
310
+ rawArtifact: string,
311
+ ): AgentToolResult<DeviationReviewDetails> {
312
+ const parsed = parseDeviationArtifact(rawArtifact)
313
+ if (!parsed.ok) {
314
+ return toolResult(
315
+ `deviation_review: artifact parse failed — ${parsed.reason}\nRe-run the deviation_review tool with the same inputs. NEVER treat this as 0 deviations.\n--- raw reviewer artifact (for diagnosis) ---\n${rawArtifactExcerpt(rawArtifact)}\n--- end raw reviewer artifact ---`,
316
+ parsed,
317
+ { isError: true },
318
+ )
319
+ }
320
+ const listed = parsed.deviations
321
+ .map((d) => `- ${d.what} (${d.file}:${d.line})`)
322
+ .join('\n')
323
+ // AIDEV-NOTE (PMR-6YC7): a recovered parse (well-formed lines were scoped
324
+ // out of the verdict section) is flagged so the caller knows the artifact
325
+ // shape was off-contract even though the count matched exactly.
326
+ let recoveredNote = ''
327
+ if (parsed.recovered === true) {
328
+ recoveredNote =
329
+ ' (recovered: the verdict-section scoping excluded the well-formed lines — e.g. a restated heading or subheading — but the artifact-wide lines exactly match the declared count)'
330
+ }
331
+ let summary: string
332
+ if (parsed.deviationsCount === 0) {
333
+ summary =
334
+ 'deviation_review: 0 deviations from spec — continue to D5 (record the "no deviation from spec" aven note, then flow_phase_complete).'
335
+ } else {
336
+ summary = `deviation_review: ${parsed.deviationsCount} deviation(s) from spec${recoveredNote}:\n${listed}\nContinue to D5 — a HUMAN decides via ask_user_question (accept / fix).`
337
+ }
338
+ return toolResult(summary, parsed)
339
+ }
340
+
341
+ /** A watcher/spawn failure rendered as the SubagentResult shape it reports. */
342
+ function failedResult(result: SubagentResult): string {
343
+ const detail = result.errorMessage ?? `exit code ${result.exitCode}`
344
+ return `deviation_review: reviewer subagent failed — ${detail}. Re-run the deviation_review tool. NEVER treat this as 0 deviations.`
345
+ }
346
+
347
+ export function registerDeviationReviewTool(
348
+ pi: ExtensionAPI,
349
+ // AIDEV-NOTE: PMR-XTQQ — mode-aware writer seam; default probes per write
350
+ // (daemon enabled). index.ts passes the shared runServer-configured writer.
351
+ // PMR-ZV9Y 2.2 doubles as the v2 emission seam (step-start/step-stop/
352
+ // state-change ride `journalGateEvent` → `writer.record`), so no second
353
+ // writer is introduced and every gate event lands in the one journal.
354
+ writer: EventWriter = createEventWriter(
355
+ getAgentDir(),
356
+ createDaemonAliveProbe(getAgentDir()),
357
+ ),
358
+ // AIDEV-NOTE: PMR-ZV9Y 2.2 — injectable seams, production defaults (the
359
+ // registerRunAttemptTool deps pattern). `review` wraps the reviewer spawn:
360
+ // the v2 verdict/rerun emissions sit AFTER the reviewer returns, and a test
361
+ // process has no subagent mux, so without this seam the step-stop /
362
+ // deviation_gate_rerun rows of the phase-2 mapping table would be
363
+ // unreachable from execute. Default = the real startDeviationReview.
364
+ deps: {
365
+ review?: typeof startDeviationReview
366
+ } = {},
367
+ ): void {
368
+ const review = deps.review ?? startDeviationReview
369
+ // AIDEV-NOTE: PMR-ZV9Y 2.2 — the deviation gate's v2 emissions (plan
370
+ // phase-2 mapping row "deviation"). Pairing per ref, journal-only kinds:
371
+ // pin → step-start{validate, validate.deviation}
372
+ // verdict → step-stop{validate, validate.deviation}
373
+ // re-run → state-change{waiting_machine, deviation_gate_rerun}
374
+ // The step stays OPEN across a re-run (the rerun state-change records
375
+ // the wait), so the whole attempt sequence journals exactly one
376
+ // step-start/step-stop window — the deviation idiom of 2.1's
377
+ // specApprovalStepOpen guard. Every write goes through journalGateEvent
378
+ // (the tool's existing mode-aware writer) inside try/catch: a v2 journal
379
+ // failure can NEVER replace the gate verdict (ISC-A-5). Writers are
380
+ // optional-shaped here (the param has a production default), so the
381
+ // pre-2.2 harnesses that pass no writer keep the journal writes they
382
+ // already had and never reach these sites in tests (ISC-A-2).
383
+ const openDeviationSteps = new Set<string>()
384
+ const journalV2 = async (event: FlowRunEvent): Promise<void> => {
385
+ try {
386
+ await journalGateEvent(event, writer)
387
+ } catch {
388
+ // best-effort — the gate verdict stands on its own
389
+ }
390
+ }
391
+ const openDeviationStep = async (ref: string): Promise<void> => {
392
+ if (openDeviationSteps.has(ref)) return
393
+ openDeviationSteps.add(ref)
394
+ await journalV2({
395
+ kind: 'step-start',
396
+ at: new Date().toISOString(),
397
+ ref,
398
+ phase: 'validate',
399
+ step: 'validate.deviation',
400
+ })
401
+ }
402
+ const closeDeviationStep = async (ref: string): Promise<void> => {
403
+ if (!openDeviationSteps.has(ref)) return
404
+ openDeviationSteps.delete(ref)
405
+ await journalV2({
406
+ kind: 'step-stop',
407
+ at: new Date().toISOString(),
408
+ ref,
409
+ phase: 'validate',
410
+ step: 'validate.deviation',
411
+ })
412
+ }
413
+ const journalGateRerun = async (ref: string): Promise<void> => {
414
+ if (!openDeviationSteps.has(ref)) return
415
+ await journalV2({
416
+ kind: 'state-change',
417
+ at: new Date().toISOString(),
418
+ ref,
419
+ state: 'waiting_machine',
420
+ reason: 'deviation_gate_rerun',
421
+ })
422
+ }
423
+ pi.registerTool({
424
+ name: 'deviation_review',
425
+ label: 'deviation review',
426
+ description:
427
+ 'Run the spec-deviation gate: spawns a fresh-context reviewer subagent that compares the resolved spec text against the git diff, then parses its deviation artifact strictly. Returns the parsed verdict (deviations_count + deviations) or an error — a parse error means re-run, never 0 deviations.',
428
+ promptSnippet:
429
+ 'Spec-deviation gate for the validate phase — call after the review gate returned 0 blockers.',
430
+ promptGuidelines: [
431
+ 'Call deviation_review with mode, ref, the resolved spec text and the mined aven notes (validate prompt steps D1/D2). Do NOT pass a diff or commit messages: the tool resolves base, diff and commits itself in the flow worktree and reports the base SHA and range in its result.',
432
+ 'A "cannot resolve the flow worktree" refusal names a checkout mismatch: the bound flow worktree could not be verified (missing, foreign repo, branch moved). STOP and tell the human — fix or re-bind the worktree (/flow <ref> to resume so the flow loop session holds the worktree context); never retry from the session checkout.',
433
+ 'If the result says the flow base is missing or the range is empty, STOP and tell the human — never retry with a hand-written diff.',
434
+ 'An error result means re-run deviation_review — NEVER treat an error or malformed artifact as 0 deviations. A parse failure carries the raw reviewer artifact: read it first to see what the reviewer emitted before re-running.',
435
+ 'The gate pins its review target at spawn and verifies the reviewer echoed the pinned range (PMR-6EEW). A target_mismatch or stale result invalidates the verdict — re-run the tool; do not hand-wave a verdict around it.',
436
+ ],
437
+ parameters: Type.Object({
438
+ mode: Type.Union([Type.Literal('work'), Type.Literal('personal')], {
439
+ description:
440
+ 'The flow mode — advisory only: the tool derives the authoritative mode from the flow worktree (PMR-K74M) and uses the derived value when they disagree',
441
+ }),
442
+ ref: Type.String({ description: 'Aven ticket ref, e.g. PMR-ABC1' }),
443
+ spec: Type.String({
444
+ description:
445
+ 'The resolved spec text (D1) — authoritative comparison base',
446
+ }),
447
+ avenNotes: Type.String({
448
+ description: 'Recent aven notes mined per D2 (empty string when none)',
449
+ }),
450
+ }),
451
+ async execute(
452
+ _toolCallId: string,
453
+ params: DeviationReviewToolParams,
454
+ _signal: AbortSignal,
455
+ _onUpdate: unknown,
456
+ ctx: ExtensionToolContext,
457
+ ): Promise<AgentToolResult<DeviationReviewDetails>> {
458
+ // AIDEV-NOTE: PMR-0KMQ — the cwd is the VERIFIED bound flow worktree;
459
+ // an unresolvable worktree is a fail-closed mismatch refusal (no
460
+ // reviewer, no doomed "not bound" run from the session checkout).
461
+ const resolution = await resolveDeviationCwd(
462
+ params.ref,
463
+ productionReviewDeps(pi, ctx.cwd),
464
+ )
465
+ if (!resolution.ok) {
466
+ return toolResult(
467
+ `deviation_review: cannot resolve the flow worktree for ${params.ref} — checkout mismatch: ${resolution.reason}. The flow base is recorded on the feature branch (branch.<feature>.flowbase), so the diff range cannot be resolved from the session checkout (${ctx.cwd}). Fix or re-bind the flow worktree, then re-run. No reviewer was spawned. NEVER treat this as 0 deviations.\nRecovery: run /flow ${params.ref} to re-arm the flow binding, then re-call.`,
468
+ { ok: false as const, reason: resolution.reason },
469
+ { isError: true },
470
+ )
471
+ }
472
+ const cwd = resolution.cwd
473
+ const exec: Exec = (cmd, args, options) => pi.exec(cmd, args, options)
474
+ // AIDEV-NOTE: PMR-K74M — the gate's mode (and therefore its diff base)
475
+ // is DERIVED from the flow worktree toplevel + pi-flow config, the same
476
+ // inputs review.ts feeds resolveMode: an LLM-supplied params.mode can
477
+ // no longer flip the base between the recorded sha and the local
478
+ // merge-base (they diverge exactly after a mid-flow rebase). A
479
+ // derivation failure is fail-closed — never a silent params.mode
480
+ // fallback.
481
+ let mode: WorkMode
482
+ try {
483
+ mode = await deriveGateMode(exec, cwd)
484
+ } catch (error) {
485
+ const reason = error instanceof Error ? error.message : String(error)
486
+ return toolResult(
487
+ `deviation_review: cannot derive the flow mode — ${reason}. No reviewer was spawned. Fix the pi-flow config and re-run. NEVER treat this as 0 deviations.`,
488
+ { ok: false as const, reason: 'mode derivation failed' },
489
+ { isError: true },
490
+ )
491
+ }
492
+ const resolved = await resolveDeviationRange(exec, cwd, mode)
493
+ if (!resolved.ok) {
494
+ return toolResult(
495
+ `deviation_review: cannot resolve the diff range — ${resolved.reason}. No reviewer was spawned. Tell the human; NEVER treat this as 0 deviations.`,
496
+ { ok: false as const, reason: resolved.reason },
497
+ { isError: true },
498
+ )
499
+ }
500
+ // AIDEV-NOTE: PMR-6EEW — pin at spawn. The reviewer prompt is built
501
+ // from this pinned target, and its verdict is only accepted if it
502
+ // echoes the pin and HEAD has not moved since.
503
+ const built = buildGateTarget({
504
+ gate: 'deviation',
505
+ ref: params.ref,
506
+ baseSha: resolved.value.flowRange.baseSha,
507
+ headSha: resolved.value.flowRange.headSha,
508
+ diff: resolved.value.diff,
509
+ })
510
+ let target: GateTarget | null = null
511
+ if ('diffSha256' in built) {
512
+ target = built
513
+ await journalGateEvent(
514
+ {
515
+ kind: 'gate-target',
516
+ at: new Date().toISOString(),
517
+ ref: params.ref,
518
+ gate: 'deviation',
519
+ targetId: gateTargetId(target),
520
+ baseSha: target.baseSha,
521
+ headSha: target.headSha,
522
+ diffSha256: target.diffSha256,
523
+ },
524
+ writer,
525
+ )
526
+ // AIDEV-NOTE: PMR-ZV9Y 2.2 — the pinned target is the moment the gate
527
+ // starts judging bytes, so the validate.deviation step opens here
528
+ // (idempotent per ref: a re-run re-pins but does NOT re-open).
529
+ await openDeviationStep(params.ref)
530
+ // AIDEV-NOTE: PMR-6EEW per-subtask ranges — journal the subtask →
531
+ // commits attribution of the pinned range (Subtask: trailers).
532
+ // Best-effort by design; unattributed commits are surfaced in the
533
+ // event, never guessed at.
534
+ try {
535
+ const attribution = await deriveSubtaskAttribution(
536
+ exec,
537
+ cwd,
538
+ target.baseSha,
539
+ target.headSha,
540
+ )
541
+ if (attribution.ok) {
542
+ await journalGateEvent(
543
+ {
544
+ kind: 'subtask-ranges',
545
+ at: new Date().toISOString(),
546
+ ref: params.ref,
547
+ gate: 'deviation',
548
+ baseSha: target.baseSha,
549
+ headSha: target.headSha,
550
+ bySubtask: attribution.attribution.bySubtask,
551
+ unattributed: attribution.attribution.unattributed,
552
+ },
553
+ writer,
554
+ )
555
+ }
556
+ } catch {
557
+ // best-effort — the gate itself is unaffected
558
+ }
559
+ }
560
+ // AIDEV-NOTE: large diffs go to a temp file, not the prompt (see
561
+ // DeviationReviewInput.diffPath). Falls back to inline on write failure.
562
+ // AIDEV-NOTE: PMR-MVSX — the deviation-diff- mkdtemp dir must not leak:
563
+ // it is removed in the finally below once startDeviationReview has
564
+ // settled, covering the success path AND every error return (spawn
565
+ // failure, nonzero exit, gate-verification failure, diff_lines_read
566
+ // mismatch, parse error). A write failure after a successful mkdtemp
567
+ // removes the orphaned dir immediately.
568
+ let diffPath: string | undefined
569
+ let diffDir: string | undefined
570
+ if (resolved.value.diff.length > DEVIATION_INLINE_DIFF_MAX) {
571
+ try {
572
+ diffDir = await mkdtemp(join(tmpdir(), 'deviation-diff-'))
573
+ diffPath = join(diffDir, 'pinned.diff')
574
+ await writeFile(diffPath, resolved.value.diff)
575
+ } catch {
576
+ if (diffDir !== undefined) {
577
+ // AIDEV-NOTE: PMR-8HST — guarded via tryRemove: a throwing rmSync
578
+ // here would escape as an unhandled tool exception and replace
579
+ // the inline-fallback tool result.
580
+ tryRemove(diffDir)
581
+ diffDir = undefined
582
+ }
583
+ diffPath = undefined
584
+ }
585
+ }
586
+ try {
587
+ const prompt = deviationReviewPromptFrom(
588
+ { ...params, mode },
589
+ resolved.value,
590
+ target,
591
+ diffPath,
592
+ )
593
+ const rangeLine = describeRange(resolved.value.flowRange)
594
+ let result: SubagentResult
595
+ try {
596
+ result = await review({ ...ctx, cwd }, prompt, params.ref)
597
+ } catch (error) {
598
+ const message = error instanceof Error ? error.message : String(error)
599
+ // AIDEV-NOTE: PMR-ZV9Y 2.2 — spawn failure mandates the same gate
600
+ // re-run as a rejected verdict ("Re-run the deviation_review tool"),
601
+ // so it journals the machine wait too.
602
+ await journalGateRerun(params.ref)
603
+ return toolResult(
604
+ `deviation_review: reviewer spawn failed — ${message}. Re-run the deviation_review tool when the subagent mux is available. NEVER treat this as 0 deviations.`,
605
+ { ok: false as const, reason: message },
606
+ { isError: true },
607
+ )
608
+ }
609
+ if (result.exitCode !== 0 || result.errorMessage !== undefined) {
610
+ // AIDEV-NOTE: PMR-ZV9Y 2.2 — failedResult's text mandates a gate
611
+ // re-run → the machine wait (see the spawn-failure branch above).
612
+ await journalGateRerun(params.ref)
613
+ return toolResult(
614
+ failedResult(result),
615
+ {
616
+ ok: false as const,
617
+ reason: result.errorMessage ?? `exit code ${result.exitCode}`,
618
+ },
619
+ { isError: true },
620
+ )
621
+ }
622
+ // AIDEV-NOTE: PMR-6EEW — verify the verifier BEFORE parsing findings:
623
+ // echo contract first, staleness second. A mismatch or stale verdict
624
+ // is a hard error; the gate re-runs on the (possibly new) range.
625
+ if (target !== null) {
626
+ const verification = await verifyDeviationGateResult(
627
+ exec,
628
+ cwd,
629
+ target,
630
+ result.summary,
631
+ )
632
+ if (!verification.ok) {
633
+ await journalGateEvent(
634
+ {
635
+ kind: 'gate-decision',
636
+ at: new Date().toISOString(),
637
+ ref: params.ref,
638
+ gate: 'deviation',
639
+ targetId: gateTargetId(target),
640
+ status: verification.status,
641
+ },
642
+ writer,
643
+ )
644
+ // AIDEV-NOTE: PMR-ZV9Y 2.2 — target-mismatch / stale / fail: the
645
+ // verdict was judged against the wrong bytes and is rejected, so
646
+ // journal the machine wait (mapping row "rerun →
647
+ // state-change{waiting_machine, deviation_gate_rerun}").
648
+ await journalGateRerun(params.ref)
649
+ return toolResult(
650
+ `deviation_review: gate integrity check FAILED (${verification.status}) — ${verification.reason}. The verdict was NOT accepted. Re-run the deviation_review tool; NEVER treat this as 0 deviations.`,
651
+ { ok: false as const, reason: verification.reason },
652
+ { isError: true },
653
+ )
654
+ }
655
+ // AIDEV-NOTE: PMR-SPND — integrity acceptance alone journals NO
656
+ // gate-decision: pass/fail is the VERDICT (0 vs >0 deviations) and
657
+ // is emitted only after the artifact parses strictly (below). The
658
+ // old premature 'pass' here made every run with deviations read as
659
+ // a clean pass in the journal.
660
+ }
661
+ if (diffPath !== undefined) {
662
+ const check = checkDiffLinesRead(resolved.value.diff, result.summary)
663
+ if (!check.ok) {
664
+ // AIDEV-NOTE: PMR-ZV9Y 2.2 — same class as the integrity
665
+ // rejection above: the verdict was NOT accepted, a re-run is
666
+ // mandated → machine wait.
667
+ await journalGateRerun(params.ref)
668
+ return toolResult(
669
+ `deviation_review: reviewer did not prove it read the whole diff file (diff_lines_read: expected ${check.expected}, got ${check.got ?? 'none'}). The verdict was NOT accepted. Re-run the deviation_review tool; NEVER treat this as 0 deviations.`,
670
+ { ok: false as const, reason: 'diff_lines_read mismatch' },
671
+ { isError: true },
672
+ )
673
+ }
674
+ }
675
+ const mapped = deviationResultToToolResult(result.summary)
676
+ // AIDEV-NOTE: PMR-ZV9Y 2.2 — the gate's terminal fork: a parsed
677
+ // verdict CLOSES the validate.deviation step (step-stop), a parse
678
+ // failure is an isError result mandating a re-run (machine wait, step
679
+ // stays open for the next attempt). deviationResultToToolResult sets
680
+ // isError on parse failure only, so this one check splits the two.
681
+ if (mapped.isError === true) {
682
+ await journalGateRerun(params.ref)
683
+ } else {
684
+ // AIDEV-NOTE: PMR-SPND — gate-decision verdict semantics (human-
685
+ // chosen, closed pass/fail vocabulary, ISC-A-1 — no new status):
686
+ // pass = the gate ran, the artifact parsed strictly, 0 deviations
687
+ // fail = the gate ran, the artifact parsed strictly, >0 deviations
688
+ // The event's PRESENCE on this path records successful execution +
689
+ // parsing; a parse failure journals NO gate-decision (only the
690
+ // rerun wait), so a parse error can never read as pass. Integrity
691
+ // rejections above keep their own closed statuses (echo-missing /
692
+ // target-mismatch / stale, or fail-closed 'fail' when HEAD cannot
693
+ // be re-resolved) — never pass. Consumers reading events alone can
694
+ // therefore tell "ran clean" from "found deviations" without a new
695
+ // field.
696
+ if (target !== null) {
697
+ let status: 'pass' | 'fail' = 'fail'
698
+ if (mapped.details.ok && mapped.details.deviationsCount === 0) {
699
+ status = 'pass'
700
+ }
701
+ await journalGateEvent(
702
+ {
703
+ kind: 'gate-decision',
704
+ at: new Date().toISOString(),
705
+ ref: params.ref,
706
+ gate: 'deviation',
707
+ targetId: gateTargetId(target),
708
+ status,
709
+ },
710
+ writer,
711
+ )
712
+ }
713
+ await closeDeviationStep(params.ref)
714
+ }
715
+ const first = mapped.content[0]
716
+ if (first !== undefined && first.type === 'text') {
717
+ // AIDEV-NOTE: PMR-K74M — surface a params.mode correction instead
718
+ // of silently overriding it, so a confused caller sees which mode
719
+ // the gate actually used.
720
+ let modeNote = ''
721
+ if (params.mode !== mode) {
722
+ modeNote = ` (note: params.mode said "${params.mode}" but the gate derived "${mode}" from the flow worktree — the derived mode was used)`
723
+ }
724
+ first.text = `Resolved ${rangeLine}${modeNote}\n${first.text}`
725
+ }
726
+ return mapped
727
+ } finally {
728
+ if (diffDir !== undefined) {
729
+ // AIDEV-NOTE: cleanup must never mask the computed verdict — a
730
+ // throwing rmSync (busy/shared TMPDIR) would replace `return
731
+ // mapped` with an exception. PMR-8HST/PMR-S4W0: shared tryRemove.
732
+ tryRemove(diffDir)
733
+ }
734
+ }
735
+ },
736
+ })
737
+ }