@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,518 @@
1
+ // AIDEV-NOTE: PMR-T8ZG — the code_review tool's seams (PMR-3ZY1): aven
2
+ // worktree-note parser, herdr list matchers, exec-injected worktree resolver
3
+ // and tuicr opener, ask-answer parsing, tuicr session slug picking, pass/fail
4
+ // routing, and the /code-review gate prompt. All exec goes through the
5
+ // injected ReviewDeps — tools/code-review.ts owns registration + wiring.
6
+
7
+ import { resolve } from 'node:path'
8
+ import { MODE_PROFILE } from '../mode-profile.ts'
9
+ import { type FlowRangeResult, resolveFlowRange } from '../shared/diff-base.ts'
10
+ import { readFlowBase } from '../shared/flow-base.ts'
11
+ import {
12
+ resolveStableRange,
13
+ stableRefusalText,
14
+ } from '../shared/stable-range.ts'
15
+ import type { WorkMode } from '../work-mode.ts'
16
+ import { type PersonalType, personalBranch } from '../worktree/branch.ts'
17
+ import type { HerdrWorktree } from '../worktree/herdr.ts'
18
+ import { extractResult, parseJson, pickString } from '../worktree/herdr.ts'
19
+
20
+ // AIDEV-NOTE: PMR-T8ZG — pure seams of the code_review tool (PMR-3ZY1):
21
+ // aven worktree-note parser, herdr list matchers, ask-answer parsing, tuicr
22
+ // session slug picking, pass/fail routing, and the /code-review gate prompt.
23
+ // No direct I/O here — exec goes through the injected ReviewDeps;
24
+ // tools/code-review.ts owns registration and production wiring.
25
+
26
+ export interface WorktreeNote {
27
+ path: string
28
+ branch: string | null
29
+ }
30
+
31
+ /**
32
+ * Parse `aven show <ref> --full` output for note bodies carrying a
33
+ * `worktree: <path>` line (same `note id=...` + `body<<EOF ... EOF` shape
34
+ * parseMetadataBlock trusts). Chat text mentioning "worktree:" is ignored —
35
+ * only heredoc bodies count.
36
+ */
37
+ export function parseWorktreeNotes(stdout: string): WorktreeNote[] {
38
+ const re = /^note id=\S+.*$\n^body<<EOF$\n([\s\S]*?)\n^EOF$/gm
39
+ const notes: WorktreeNote[] = []
40
+ let match = re.exec(stdout)
41
+ while (match !== null) {
42
+ const body = match[1] ?? ''
43
+ match = re.exec(stdout)
44
+ // AIDEV-NOTE: PMR-DE2P — accepts the skill's single-line form
45
+ // `worktree: <path> branch: <b>` and the two-line form.
46
+ const pathLine = /^worktree: (\S+)/m.exec(body)
47
+ if (pathLine === null) continue
48
+ const branchLine = /^(?:worktree: \S+ )?branch: (\S+)\s*$/m.exec(body)
49
+ notes.push({
50
+ path: pathLine[1] ?? '',
51
+ branch: branchLine === null ? null : (branchLine[1] ?? null),
52
+ })
53
+ }
54
+ return notes
55
+ }
56
+
57
+ /** Latest (last) worktree note, or null when none. */
58
+ export function latestWorktreeNote(stdout: string): WorktreeNote | null {
59
+ const notes = parseWorktreeNotes(stdout)
60
+ if (notes.length === 0) return null
61
+ return notes[notes.length - 1] ?? null
62
+ }
63
+
64
+ /** Exact-branch match against a `herdr worktree list` payload. */
65
+ export function matchHerdrWorktree(
66
+ worktrees: HerdrWorktree[],
67
+ branch: string,
68
+ ): HerdrWorktree | null {
69
+ return worktrees.find((w) => w.isLinked && w.branch === branch) ?? null
70
+ }
71
+
72
+ // AIDEV-NOTE: PMR-3ZY1 — mirrors worktree/branch.ts's PersonalType union;
73
+ // keep in sync when branch.ts changes.
74
+ const PERSONAL_BRANCH_TYPES: readonly PersonalType[] = [
75
+ 'feat',
76
+ 'fix',
77
+ 'chore',
78
+ 'docs',
79
+ 'refactor',
80
+ ]
81
+
82
+ /** Parse `title="..."` from the aven show --full metadata line. */
83
+ export function parseAvenTitle(stdout: string): string | null {
84
+ const match = /^[^\n]*\btitle="([^"]*)"/.exec(stdout)
85
+ const title = match === null ? null : (match[1] ?? null)
86
+ if (title === null || title.trim() === '') return null
87
+ return title
88
+ }
89
+
90
+ /** Expected personal branch for a ticket title: `feat(pi-flow): subject`
91
+ * -> `<type>/<slug of subject>` via worktree/branch.ts personalBranch.
92
+ * A recognizable conventional-commit type prefix sets the branch type;
93
+ * anything else falls back to 'feat'.
94
+ *
95
+ * AIDEV-NOTE: PMR-902B — while a personal flow is active the branch carries
96
+ * the flow's aven ref (`<type>/<REF>-<slug>`, e.g. feat/PMR-AB12-alpha-gate),
97
+ * because that is what createFlow names the worktree. Callers inside the
98
+ * review resolver pass the ref they are resolving for; pass null only when
99
+ * there is no flow ref, which keeps the bare legacy shape. */
100
+ export function titleBranch(title: string, ref: string | null): string {
101
+ let type: PersonalType = 'feat'
102
+ let name = title
103
+ const match = /^([a-z]+)(?:\([^)]*\))?:\s+(.+)$/.exec(title)
104
+ if (
105
+ match !== null &&
106
+ PERSONAL_BRANCH_TYPES.includes((match[1] ?? '') as PersonalType)
107
+ ) {
108
+ type = match[1] as PersonalType
109
+ name = match[2] ?? title
110
+ }
111
+ return personalBranch(name, type, ref)
112
+ }
113
+
114
+ /** Parse the ask_user_question answer text into pass/fail (null = unclear). */
115
+ export function parseAskAnswer(answerText: string): 'pass' | 'fail' | null {
116
+ const lowered = answerText.toLowerCase()
117
+ if (lowered.includes('pass')) return 'pass'
118
+ if (lowered.includes('fail')) return 'fail'
119
+ return null
120
+ }
121
+
122
+ /**
123
+ * Latest tuicr session slug from `tuicr review list` output.
124
+ * AIDEV-NOTE: PMR-G68P — tuicr v0.27.0 prints a JSON array of
125
+ * {slug, updated_at, ...} (verified against the installed binary), NOT
126
+ * `session: <slug>` lines — the previous regex never matched real output,
127
+ * so the fail path always fell to the free-text fallback. Array order is
128
+ * not a freshness guarantee, so the slug with the max updated_at wins.
129
+ */
130
+ export function pickLatestSessionSlug(listStdout: string): string | null {
131
+ const parsed: unknown = parseJson(listStdout)
132
+ if (!Array.isArray(parsed)) return null
133
+ let bestSlug: string | null = null
134
+ let bestUpdatedAt = ''
135
+ for (const entry of parsed) {
136
+ if (typeof entry !== 'object' || entry === null) continue
137
+ const record = entry as Record<string, unknown>
138
+ const slug = record.slug
139
+ if (typeof slug !== 'string' || slug === '') continue
140
+ const updatedAt = record.updated_at
141
+ let stamp = ''
142
+ if (typeof updatedAt === 'string') stamp = updatedAt
143
+ if (bestSlug === null || stamp > bestUpdatedAt) {
144
+ bestSlug = slug
145
+ bestUpdatedAt = stamp
146
+ }
147
+ }
148
+ return bestSlug
149
+ }
150
+
151
+ export interface ReviewRouting {
152
+ avenNote: string
153
+ message: string
154
+ }
155
+
156
+ // AIDEV-NOTE: PMR-5NZB 2.2 — the routing no longer carries a `marker` field.
157
+ // (Historical: the head-shaped in-session marker was deleted outright by
158
+ // PMR-V31Z 7.2 together with the durable receipt — a pass now records only
159
+ // the aven note.)
160
+ /** Pure pass routing: the dated aven note and the ad-hoc record message. */
161
+ export function routeReviewPass(ref: string, date: string): ReviewRouting {
162
+ const note = `human code review passed, ${date}`
163
+ return {
164
+ avenNote: note,
165
+ message:
166
+ `code_review: human PASS recorded for ${ref} (aven note: "${note}").\n` +
167
+ // PMR-V31Z 7.2 — ad-hoc record: the verdict is the aven note and
168
+ // nothing else; an active flow keeps delivering via its GitHub PR
169
+ // through its own prompts, so there is no next tool step to name.
170
+ `The verdict is recorded ad hoc — no further tool step is needed. If a flow is active for ${ref}, follow its own phase prompts.`,
171
+ }
172
+ }
173
+
174
+ export interface FailRouting {
175
+ avenNote: string
176
+ message: string
177
+ freeTextFallback: boolean
178
+ }
179
+
180
+ /** Pure fail routing: findings become the aven note, route back to /implement. */
181
+ export function routeReviewFail(ref: string, comments: string): FailRouting {
182
+ if (comments.trim().length === 0) {
183
+ return {
184
+ avenNote: '',
185
+ message: `code_review: human FAIL for ${ref}, but the tuicr session has no comments — ask the human to describe the findings (ask_user_question free text), then write them as an aven note on ${ref} and route back to /implement ${ref}.`,
186
+ freeTextFallback: true,
187
+ }
188
+ }
189
+ return {
190
+ avenNote: comments.trim(),
191
+ message: `code_review: human FAIL for ${ref} — findings recorded as an aven note. Route back to /implement ${ref} (retry budget applies). STOP.`,
192
+ freeTextFallback: false,
193
+ }
194
+ }
195
+
196
+ /** The /code-review command prompt: instructs the agent to call the tool. */
197
+ export function buildCodeReviewGatePrompt(ref: string): string {
198
+ return (
199
+ `Run an ad-hoc human code review for ${ref}:\n\n` +
200
+ `1. Call the code_review tool with ref="${ref}". It resolves the ref's worktree, opens tuicr for the human, and asks them pass/fail.\n` +
201
+ `2. Follow the tool's result: the verdict is recorded as an aven note on ${ref}; a fail routes back to /implement ${ref}.\n` +
202
+ `If the tool reports ask_user_question is unavailable, tell the human and re-call code_review once the ask surface is available.`
203
+ )
204
+ }
205
+
206
+ export interface ResolvedWorktree {
207
+ path: string
208
+ branch: string
209
+ source: 'binding' | 'note' | 'herdr'
210
+ }
211
+
212
+ export interface ExecResult {
213
+ code: number
214
+ stdout: string
215
+ stderr: string
216
+ }
217
+
218
+ /**
219
+ * I/O seams of the code_review tool. Production wiring is in
220
+ * registerCodeReviewTool; tests inject fakes and assert exec sequences.
221
+ */
222
+ export interface ReviewDeps {
223
+ getFlowWorktree: () => { ref: string; path: string; branch: string } | null
224
+ avenShowFull: (ref: string) => Promise<string>
225
+ herdrWorktreeList: () => Promise<HerdrWorktree[]>
226
+ exec: (
227
+ cmd: string,
228
+ args: string[],
229
+ opts?: { cwd?: string },
230
+ ) => Promise<ExecResult>
231
+ exists: (path: string) => boolean
232
+ /** Absolute root of the session repo (ctx.cwd) — candidates must share its common git dir. */
233
+ repoRoot: string
234
+ }
235
+
236
+ // AIDEV-NOTE: PMR-9XR0 — linked worktrees have different top-level paths;
237
+ // repository identity is the common git dir shared with the session repo.
238
+ /**
239
+ * Verify a candidate: path exists, its common git dir matches the session
240
+ * repo, and (when the candidate carries a branch) HEAD matches it. A stale
241
+ * note path fails verification and the resolver falls through to the next
242
+ * source — never open tuicr on the wrong tree.
243
+ */
244
+ async function verifyCandidate(
245
+ candidate: { path: string; branch: string | null },
246
+ deps: ReviewDeps,
247
+ ): Promise<{ ok: true; branch: string } | { ok: false; reason: string }> {
248
+ if (!deps.exists(candidate.path)) {
249
+ return { ok: false, reason: `path does not exist: ${candidate.path}` }
250
+ }
251
+ let candidateCommonDir = ''
252
+ let repoCommonDir = ''
253
+ try {
254
+ const candidateResult = await deps.exec(
255
+ 'git',
256
+ ['-C', candidate.path, 'rev-parse', '--git-common-dir'],
257
+ {},
258
+ )
259
+ const repoResult = await deps.exec(
260
+ 'git',
261
+ ['-C', deps.repoRoot, 'rev-parse', '--git-common-dir'],
262
+ {},
263
+ )
264
+ // AIDEV-NOTE: PMR-HXPQ — pi.exec returns non-zero codes without throwing;
265
+ // empty stdout would otherwise resolve to the base path and falsely match.
266
+ for (const [label, result] of [
267
+ ['candidate', candidateResult],
268
+ ['session', repoResult],
269
+ ] as const) {
270
+ if (result.code !== 0) {
271
+ const detail = (result.stderr || result.stdout).trim()
272
+ return {
273
+ ok: false,
274
+ reason: `git rev-parse --git-common-dir failed for ${label} (exit ${result.code}): ${detail}`,
275
+ }
276
+ }
277
+ }
278
+ candidateCommonDir = resolve(candidate.path, candidateResult.stdout.trim())
279
+ repoCommonDir = resolve(deps.repoRoot, repoResult.stdout.trim())
280
+ } catch (error) {
281
+ const msg = error instanceof Error ? error.message : String(error)
282
+ return { ok: false, reason: `git rev-parse failed: ${msg}` }
283
+ }
284
+ if (candidateCommonDir !== repoCommonDir) {
285
+ return {
286
+ ok: false,
287
+ reason: `${candidate.path} belongs to a different repository (common git dir ${candidateCommonDir}, expected ${repoCommonDir})`,
288
+ }
289
+ }
290
+ if (candidate.branch === null) {
291
+ return { ok: true, branch: '' }
292
+ }
293
+ const head = await deps.exec(
294
+ 'git',
295
+ ['-C', candidate.path, 'rev-parse', '--abbrev-ref', 'HEAD'],
296
+ {},
297
+ )
298
+ const actual = head.stdout.trim()
299
+ if (actual !== candidate.branch) {
300
+ return {
301
+ ok: false,
302
+ reason: `branch mismatch: expected ${candidate.branch}, HEAD is ${actual}`,
303
+ }
304
+ }
305
+ return { ok: true, branch: candidate.branch }
306
+ }
307
+
308
+ /**
309
+ * Resolve the ref's review worktree, source by source, verifying each hit.
310
+ * Throws (loud) when no source yields a verified worktree.
311
+ */
312
+ export async function resolveReviewWorktree(
313
+ ref: string,
314
+ deps: ReviewDeps,
315
+ ): Promise<ResolvedWorktree> {
316
+ const failures: string[] = []
317
+
318
+ const binding = deps.getFlowWorktree()
319
+ if (binding !== null && binding.ref === ref) {
320
+ const verified = await verifyCandidate(binding, deps)
321
+ if (verified.ok) {
322
+ return { path: binding.path, branch: verified.branch, source: 'binding' }
323
+ }
324
+ failures.push(`binding: ${verified.reason}`)
325
+ }
326
+
327
+ let noteStdout = ''
328
+ try {
329
+ noteStdout = await deps.avenShowFull(ref)
330
+ } catch (error) {
331
+ failures.push(
332
+ `note: aven show failed: ${error instanceof Error ? error.message : String(error)}`,
333
+ )
334
+ }
335
+ const note = latestWorktreeNote(noteStdout)
336
+ if (note !== null) {
337
+ const verified = await verifyCandidate(note, deps)
338
+ if (verified.ok) {
339
+ return {
340
+ path: note.path,
341
+ branch: verified.branch || note.branch || '',
342
+ source: 'note',
343
+ }
344
+ }
345
+ failures.push(`note: ${verified.reason}`)
346
+ }
347
+
348
+ let worktrees: HerdrWorktree[] = []
349
+ try {
350
+ worktrees = await deps.herdrWorktreeList()
351
+ } catch (error) {
352
+ failures.push(
353
+ `herdr list failed: ${error instanceof Error ? error.message : String(error)}`,
354
+ )
355
+ }
356
+ const title = parseAvenTitle(noteStdout)
357
+ let expected: string | null = null
358
+ if (title === null) {
359
+ failures.push('herdr: no title parsed from aven show output')
360
+ } else {
361
+ // AIDEV-NOTE: PMR-902B — ref-prefixed expectation: the resolver's ref is
362
+ // the flow ref, so a personal-mode worktree is found as
363
+ // `<type>/<REF>-<slug>` (lockstep with worktree/index.ts createFlow).
364
+ expected = titleBranch(title, ref)
365
+ }
366
+ let hit: HerdrWorktree | null = matchHerdrWorktree(worktrees, ref)
367
+ if (hit === null && expected !== null) {
368
+ hit = matchHerdrWorktree(worktrees, expected)
369
+ }
370
+ // AIDEV-NOTE: PMR-2YY4 — legacy bare-shape fallback: worktrees created
371
+ // BEFORE the ref-prefixed expectation (PMR-902B) live on <type>/<slug>
372
+ // with no ref segment, so `expected` can never match them. Try the bare
373
+ // shape once the ref-prefixed one missed; this only bites when the
374
+ // earlier sources (binding, notes, ref match) all missed too.
375
+ let legacy: string | null = null
376
+ if (hit === null && title !== null) {
377
+ legacy = titleBranch(title, null)
378
+ if (legacy !== expected) {
379
+ hit = matchHerdrWorktree(worktrees, legacy)
380
+ }
381
+ }
382
+ if (hit !== null) {
383
+ const verified = await verifyCandidate(hit, deps)
384
+ if (verified.ok) {
385
+ return { path: hit.path, branch: hit.branch, source: 'herdr' }
386
+ }
387
+ failures.push(`herdr: ${verified.reason}`)
388
+ } else if (expected !== null) {
389
+ let shapes = `expected branch ${expected}`
390
+ if (legacy !== null) {
391
+ shapes += ` or legacy branch ${legacy}`
392
+ }
393
+ failures.push(`herdr: no linked worktree matched ${ref} or ${shapes}`)
394
+ }
395
+
396
+ throw new Error(
397
+ `code_review: no worktree found for ${ref} (checked flow binding, aven note, herdr worktree list)` +
398
+ (failures.length > 0 ? `\n${failures.join('\n')}` : ''),
399
+ )
400
+ }
401
+
402
+ export type OpenTuicrResult =
403
+ | { ok: true; paneId: string; command: string }
404
+ | { ok: false; reason: string; command: string }
405
+
406
+ /**
407
+ * Open tuicr for the human: resolve the review range, open a focused herdr
408
+ * tab at the worktree (parse result.root_pane.pane_id), then
409
+ * `herdr pane run <pane> tuicr tui -r <range>` (text + Enter in one
410
+ * call — plain send-text does NOT submit). Fail-closed: any failure returns
411
+ * the manual command so the human can open it and the agent re-calls.
412
+ */
413
+ export async function openTuicrReview(
414
+ ref: string,
415
+ worktreePath: string,
416
+ mode: WorkMode,
417
+ deps: Pick<ReviewDeps, 'exec'>,
418
+ ): Promise<OpenTuicrResult> {
419
+ // AIDEV-NOTE: PMR-5NZB — the pane range IS the diff the human's pass/fail
420
+ // verdict is about: the verdict recorded by code_review applies to exactly
421
+ // this range (the pane itself is only the viewing surface). The
422
+ // range policy is mode-keyed data (MODE_PROFILE[mode].baseResolution,
423
+ // PMR-T22H) and every range comes from the shared resolvers — no
424
+ // hand-rolled merge-base remains:
425
+ // personal ('recorded-sha-integrity'): the ONE shared stable-range
426
+ // resolver (shared/stable-range.ts, PMR-R4AP) — the recorded
427
+ // creation-time flowbasesha, integrity-probed; diverged / no-sha /
428
+ // corrupt-sha refuse FAIL-CLOSED with the manual command (the pane
429
+ // must never show a moving-base range the flow's own resolvers
430
+ // consider unstable).
431
+ // work ('recorded-sha'): the recorded flowbasesha (legacy fallback: the
432
+ // recorded branch) via resolveFlowRange — byte-consistent with the
433
+ // work gates, NO integrity probe.
434
+ // unbound (no flowbase config): the legacy 'main' fallback — fail-open
435
+ // on purpose for non-flow contexts.
436
+ // AIDEV-NOTE: PMR-7N3D (REPLACED by PMR-5NZB — kept as history) — the
437
+ // pane used to range against merge-base(<recorded branch>, HEAD) computed
438
+ // here at open time, re-anchoring to a moving base after a mid-flow
439
+ // rebase. PMR-V31Z 7.2: the verdict recorded on this range is an ad-hoc
440
+ // aven note; it carries no run-journal authority.
441
+ const manual = `cd ${worktreePath} && tuicr tui`
442
+ let resolved: FlowRangeResult
443
+ if (MODE_PROFILE[mode].baseResolution === 'recorded-sha-integrity') {
444
+ const stable = await resolveStableRange(deps.exec, worktreePath)
445
+ if (stable.ok) {
446
+ resolved = stable
447
+ } else if (stable.kind === 'no-binding') {
448
+ resolved = await resolveFlowRange(deps.exec, worktreePath, 'main', 'main')
449
+ } else {
450
+ return {
451
+ ok: false,
452
+ reason: stableRefusalText(stable, 'code_review'),
453
+ command: manual,
454
+ }
455
+ }
456
+ } else {
457
+ const base = await readFlowBase(deps.exec, worktreePath)
458
+ if (base.ok) {
459
+ resolved = await resolveFlowRange(
460
+ deps.exec,
461
+ worktreePath,
462
+ base.value.branch,
463
+ base.value.sha ?? base.value.branch,
464
+ )
465
+ } else {
466
+ resolved = await resolveFlowRange(deps.exec, worktreePath, 'main', 'main')
467
+ }
468
+ }
469
+ if (!resolved.ok) {
470
+ return { ok: false, reason: resolved.reason, command: manual }
471
+ }
472
+ const range = resolved.value.range
473
+ const manualRange = `cd ${worktreePath} && tuicr tui -r ${range}`
474
+
475
+ const tabResult = await deps.exec(
476
+ 'herdr',
477
+ [
478
+ 'tab',
479
+ 'create',
480
+ '--cwd',
481
+ worktreePath,
482
+ '--label',
483
+ `review ${ref}`,
484
+ '--focus',
485
+ ],
486
+ {},
487
+ )
488
+ if (tabResult.code !== 0) {
489
+ return {
490
+ ok: false,
491
+ reason: `herdr tab create failed: ${tabResult.stderr || tabResult.stdout}`,
492
+ command: manualRange,
493
+ }
494
+ }
495
+ const root: unknown = extractResult(JSON.parse(tabResult.stdout) as unknown)
496
+ const paneId = pickString(root, ['root_pane.pane_id', 'pane_id'])
497
+ if (paneId === '') {
498
+ return {
499
+ ok: false,
500
+ reason: `herdr tab create returned no root_pane.pane_id: ${tabResult.stdout.slice(0, 200)}`,
501
+ command: manualRange,
502
+ }
503
+ }
504
+
505
+ const runResult = await deps.exec(
506
+ 'herdr',
507
+ ['pane', 'run', paneId, 'tuicr', 'tui', '-r', range],
508
+ {},
509
+ )
510
+ if (runResult.code !== 0) {
511
+ return {
512
+ ok: false,
513
+ reason: `herdr pane run tuicr failed: ${runResult.stderr || runResult.stdout}`,
514
+ command: manualRange,
515
+ }
516
+ }
517
+ return { ok: true, paneId, command: manualRange }
518
+ }