@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.
- package/README.md +833 -2
- package/adhoc/tracker.ts +360 -0
- package/aven/client.ts +996 -0
- package/aven/status.ts +395 -0
- package/brainstorm/args.ts +24 -0
- package/brainstorm/artifact.ts +67 -0
- package/brainstorm/paths.ts +43 -0
- package/brainstorm/prompt.ts +172 -0
- package/brainstorm/refs.ts +41 -0
- package/config.schema.json +161 -0
- package/config.ts +577 -0
- package/feedback/args.ts +21 -0
- package/feedback/prompt.ts +177 -0
- package/feedback/triage.ts +88 -0
- package/flow/agent-role.ts +46 -0
- package/flow/answer-wake.ts +212 -0
- package/flow/answer.ts +183 -0
- package/flow/args.ts +48 -0
- package/flow/ask-emitter.ts +331 -0
- package/flow/attribution.ts +145 -0
- package/flow/aven-resolve-exec.ts +95 -0
- package/flow/aven-resolve.ts +80 -0
- package/flow/awaiting-approval.ts +32 -0
- package/flow/binding-heal.ts +68 -0
- package/flow/cost-autopush.ts +162 -0
- package/flow/cost-command.ts +122 -0
- package/flow/cost-rows-journal.ts +296 -0
- package/flow/cost-rows-push.ts +112 -0
- package/flow/cost-rows-rows.ts +209 -0
- package/flow/cost-rows.ts +228 -0
- package/flow/cost.ts +173 -0
- package/flow/durable-refs.ts +287 -0
- package/flow/effect-gate.ts +137 -0
- package/flow/ensure-labels.ts +44 -0
- package/flow/frame.ts +172 -0
- package/flow/gates.ts +211 -0
- package/flow/jira-ref.ts +212 -0
- package/flow/label-gate.ts +149 -0
- package/flow/land-gate.ts +98 -0
- package/flow/lifecycle-policy.ts +162 -0
- package/flow/live-wait.ts +52 -0
- package/flow/liveness.ts +408 -0
- package/flow/loop-deps.ts +210 -0
- package/flow/loop-settle.ts +531 -0
- package/flow/loop.ts +437 -0
- package/flow/orchestrate.ts +45 -0
- package/flow/phase-command.ts +287 -0
- package/flow/phase-emoji.ts +13 -0
- package/flow/phase-prompts.ts +251 -0
- package/flow/picker.ts +307 -0
- package/flow/push.ts +475 -0
- package/flow/reconcile-command.ts +253 -0
- package/flow/reconcile-deps.ts +329 -0
- package/flow/reconcile.ts +738 -0
- package/flow/ref-kind.ts +80 -0
- package/flow/resume-picker.ts +222 -0
- package/flow/resume.ts +116 -0
- package/flow/run-health.ts +252 -0
- package/flow/run-liveness.ts +33 -0
- package/flow/state-metrics.ts +559 -0
- package/flow/status.ts +105 -0
- package/flow/step-output.ts +416 -0
- package/flow/steps.ts +73 -0
- package/flow/terminal-purge.ts +281 -0
- package/flow/turn-generation.ts +19 -0
- package/flow/v2-emission.ts +381 -0
- package/flow/v2-resume.ts +100 -0
- package/flow/vocabulary.ts +261 -0
- package/flow/widget.ts +448 -0
- package/flow/worktree-context.ts +136 -0
- package/flow-diagram/assemble.ts +27 -0
- package/flow-diagram/command.ts +252 -0
- package/flow-diagram/translate.ts +862 -0
- package/flow-diagram/vendor/harness-profiler/LICENSE +21 -0
- package/flow-diagram/vendor/harness-profiler/PIN.md +64 -0
- package/flow-diagram/vendor/harness-profiler/hp.js +960 -0
- package/flow-diagram/vendor/harness-profiler/load.ts +66 -0
- package/flow-diagram/vendor/harness-profiler/view.html +436 -0
- package/gates.ts +20 -0
- package/herdr/sync.ts +355 -0
- package/herdr/viewer.ts +432 -0
- package/implement/args.ts +21 -0
- package/implement/prompt.ts +98 -0
- package/implement/retry.ts +57 -0
- package/implement/routing.ts +31 -0
- package/index.ts +3206 -0
- package/mode-profile.ts +56 -0
- package/package.json +205 -4
- package/phase-state.ts +18 -0
- package/plan/args.ts +20 -0
- package/plan/prompt.ts +251 -0
- package/plan/size-check.ts +46 -0
- package/plan-tools/helpers.ts +177 -0
- package/plan-tools/jira-branch-tool.ts +54 -0
- package/plan-tools/jira-branch.ts +109 -0
- package/plan-tools/jira-issue.ts +85 -0
- package/plan-tools/resolve-feature-path.ts +30 -0
- package/plan-tools/resolve-notes-path.ts +37 -0
- package/plan-tools/resolve-spec-path.ts +31 -0
- package/pr-quality/index.ts +908 -0
- package/review/LICENSE +19 -0
- package/review/deviation.ts +252 -0
- package/review/review.ts +3053 -0
- package/review/sem-guidance.d.mts +8 -0
- package/review/sem-guidance.mjs +89 -0
- package/review/verdict.ts +13 -0
- package/run-state.ts +2046 -0
- package/run-title.ts +91 -0
- package/server/consumer.ts +146 -0
- package/server/daemon.ts +1094 -0
- package/server/lifecycle.ts +679 -0
- package/server/pending.ts +267 -0
- package/server/staleness.ts +320 -0
- package/server/writer.ts +86 -0
- package/shared/diff-base.ts +138 -0
- package/shared/flow-base.ts +210 -0
- package/shared/sonarqube-utils.ts +415 -0
- package/shared/stable-range.ts +102 -0
- package/slugify.ts +13 -0
- package/sonarqube/sonarqube.ts +821 -0
- package/spec-review/approve.ts +91 -0
- package/spec-review/args.ts +21 -0
- package/spec-review/aven-spec.ts +142 -0
- package/spec-review/commands.ts +336 -0
- package/spec-review/escape-regexp.ts +7 -0
- package/spec-review/open-in-pane.ts +166 -0
- package/spec-review/picker.ts +74 -0
- package/spec-review/prompt.ts +72 -0
- package/spec-review/publish-args.ts +33 -0
- package/spec-review/publish.ts +210 -0
- package/telemetry/attributes.ts +118 -0
- package/telemetry/content.ts +140 -0
- package/telemetry/dispatch.ts +521 -0
- package/telemetry/exporter.ts +124 -0
- package/telemetry/index.ts +776 -0
- package/telemetry/loki.ts +224 -0
- package/tools/code-review-parse.ts +518 -0
- package/tools/code-review.ts +312 -0
- package/tools/deviation.ts +737 -0
- package/tools/flow-submit.ts +302 -0
- package/tools/land.ts +608 -0
- package/tools/phase-complete.ts +476 -0
- package/tools/result.ts +18 -0
- package/tools/review-deps.ts +44 -0
- package/tools/run-attempt.ts +312 -0
- package/tools/spec-approve.ts +265 -0
- package/validate/args.ts +22 -0
- package/validate/deviation-gate.ts +229 -0
- package/validate/gate-target.ts +371 -0
- package/validate/gate.ts +79 -0
- package/validate/paths.ts +20 -0
- package/validate/personal.ts +104 -0
- package/validate/prompt.ts +525 -0
- package/validate/review-gate.ts +134 -0
- package/validate/subtask-range.ts +113 -0
- package/work-mode.ts +19 -0
- package/worktree/bootstrap.ts +243 -0
- package/worktree/branch.ts +168 -0
- package/worktree/herdr.ts +447 -0
- package/worktree/index.ts +1447 -0
- package/worktree/orphan.ts +384 -0
- package/worktree/remove-guards.ts +99 -0
- package/worktree/residue.ts +216 -0
- package/worktree/sweep.ts +526 -0
package/review/review.ts
ADDED
|
@@ -0,0 +1,3053 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Code Review Extension (inspired by Codex's review feature)
|
|
3
|
+
*
|
|
4
|
+
* Provides a `/review` command that prompts the agent to review code changes.
|
|
5
|
+
* Supports multiple review modes:
|
|
6
|
+
* - Review a GitHub pull request (checks out the PR locally)
|
|
7
|
+
* - Review against a base branch (PR style)
|
|
8
|
+
* - Review uncommitted changes
|
|
9
|
+
* - Review a specific commit
|
|
10
|
+
* - Custom review instructions
|
|
11
|
+
*
|
|
12
|
+
* Usage:
|
|
13
|
+
* - `/review` - show interactive selector
|
|
14
|
+
* - `/review pr 123` - review PR #123 (checks out locally)
|
|
15
|
+
* - `/review pr https://github.com/owner/repo/pull/123` - review PR from URL
|
|
16
|
+
* - `/review uncommitted` - review uncommitted changes directly
|
|
17
|
+
* - `/review branch main` - review against main branch
|
|
18
|
+
* - `/review commit abc123` - review specific commit
|
|
19
|
+
* - `/review folder src docs` - review specific folders/files (snapshot, not diff)
|
|
20
|
+
* - `/review custom "check for security issues"` - custom instructions
|
|
21
|
+
*
|
|
22
|
+
* Project-specific review guidelines:
|
|
23
|
+
* - If a REVIEW_GUIDELINES.md file exists in the same directory as .pi,
|
|
24
|
+
* its contents are appended to the review prompt.
|
|
25
|
+
*
|
|
26
|
+
* Note: PR review requires a clean working tree (no uncommitted changes to tracked files).
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
import { promises as fs } from 'node:fs'
|
|
30
|
+
import path from 'node:path'
|
|
31
|
+
import type {
|
|
32
|
+
AgentToolResult,
|
|
33
|
+
ExtensionAPI,
|
|
34
|
+
ExtensionCommandContext,
|
|
35
|
+
ExtensionContext,
|
|
36
|
+
ExtensionToolContext,
|
|
37
|
+
} from '@earendil-works/pi-coding-agent'
|
|
38
|
+
import {
|
|
39
|
+
BorderedLoader,
|
|
40
|
+
CONFIG_DIR_NAME,
|
|
41
|
+
DynamicBorder,
|
|
42
|
+
getAgentDir,
|
|
43
|
+
} from '@earendil-works/pi-coding-agent'
|
|
44
|
+
import {
|
|
45
|
+
Container,
|
|
46
|
+
type SelectItem,
|
|
47
|
+
SelectList,
|
|
48
|
+
Text,
|
|
49
|
+
} from '@earendil-works/pi-tui'
|
|
50
|
+
import {
|
|
51
|
+
isMuxAvailable,
|
|
52
|
+
launchSubagent,
|
|
53
|
+
type SubagentResult,
|
|
54
|
+
watchSubagent,
|
|
55
|
+
} from '@gtheys/pi-interactive-subagents'
|
|
56
|
+
import { Type } from 'typebox'
|
|
57
|
+
import {
|
|
58
|
+
adhocAddWorker,
|
|
59
|
+
adhocBeginWorker,
|
|
60
|
+
adhocFinish,
|
|
61
|
+
} from '../adhoc/tracker.ts'
|
|
62
|
+
import { resolveMode } from '../config.ts'
|
|
63
|
+
import { getActiveFlowRef, getFlowWorktree } from '../flow/worktree-context.ts'
|
|
64
|
+
import { MODE_PROFILE } from '../mode-profile.ts'
|
|
65
|
+
import {
|
|
66
|
+
createDaemonAliveProbe,
|
|
67
|
+
createEventWriter,
|
|
68
|
+
type EventWriter,
|
|
69
|
+
} from '../server/writer.ts'
|
|
70
|
+
import { type Exec, getMergeBase } from '../shared/diff-base.ts'
|
|
71
|
+
import { readFlowBase } from '../shared/flow-base.ts'
|
|
72
|
+
import {
|
|
73
|
+
resolveStableRange,
|
|
74
|
+
stableRefusalText,
|
|
75
|
+
} from '../shared/stable-range.ts'
|
|
76
|
+
import {
|
|
77
|
+
type ResolvedWorktree,
|
|
78
|
+
resolveReviewWorktree,
|
|
79
|
+
} from '../tools/code-review-parse.ts'
|
|
80
|
+
import { productionReviewDeps } from '../tools/review-deps.ts'
|
|
81
|
+
import {
|
|
82
|
+
buildGateTarget,
|
|
83
|
+
deriveSubtaskAttribution,
|
|
84
|
+
type GateTarget,
|
|
85
|
+
gateTargetId,
|
|
86
|
+
reviewedCommitsLine,
|
|
87
|
+
reviewedRangeLine,
|
|
88
|
+
verifyGateWithExec,
|
|
89
|
+
} from '../validate/gate-target.ts'
|
|
90
|
+
import type { WorkMode } from '../work-mode.ts'
|
|
91
|
+
import {
|
|
92
|
+
filterLinked,
|
|
93
|
+
type HerdrWorktree,
|
|
94
|
+
herdrAvailable,
|
|
95
|
+
worktreeCreate,
|
|
96
|
+
worktreeList,
|
|
97
|
+
worktreeRemove,
|
|
98
|
+
} from '../worktree/herdr.ts'
|
|
99
|
+
import {
|
|
100
|
+
buildSemReviewGuidance,
|
|
101
|
+
getSemToolAvailability,
|
|
102
|
+
} from './sem-guidance.mjs'
|
|
103
|
+
import { REVIEW_VERDICT_INSTRUCTIONS } from './verdict.ts'
|
|
104
|
+
|
|
105
|
+
// State to track fresh session review (where we branched from).
|
|
106
|
+
// Module-level state means only one review can be active at a time.
|
|
107
|
+
// This is intentional - the UI and /end-review command assume a single active review.
|
|
108
|
+
let reviewOriginId: string | undefined
|
|
109
|
+
let endReviewInProgress = false
|
|
110
|
+
|
|
111
|
+
// AIDEV-NOTE: PMR-C6AK — pure gate for the ocr scout skip in
|
|
112
|
+
// spawnReviewJobs. During an active personal-mode flow the GitHub PR is
|
|
113
|
+
// the review surface (PMR-V31Z), so the scout would only add noise; the
|
|
114
|
+
// user kept this skip after the code_review human gate was removed
|
|
115
|
+
// (PMR-V31Z 7.2). A work-mode flow and a manual /review (no active flow)
|
|
116
|
+
// keep ocr.
|
|
117
|
+
export function skipOcrScout(
|
|
118
|
+
activeFlowRef: string | null,
|
|
119
|
+
mode: 'work' | 'personal',
|
|
120
|
+
): boolean {
|
|
121
|
+
return activeFlowRef !== null && mode === 'personal'
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// AIDEV-NOTE: PMR-P1ZA — single precondition for every review spawn path
|
|
125
|
+
// (command and tool). launchSubagent needs the session to run INSIDE herdr
|
|
126
|
+
// (HERDR_WORKSPACE_ID / HERDR_PANE_ID), not just a reachable herdr binary;
|
|
127
|
+
// gating on isMuxAvailable() alone let PR targets do checkout/worktree work
|
|
128
|
+
// that the spawn then could not complete.
|
|
129
|
+
export function canSpawnReviewSubagent(
|
|
130
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
131
|
+
muxAvailable: () => boolean = isMuxAvailable,
|
|
132
|
+
): boolean {
|
|
133
|
+
const ws = env.HERDR_WORKSPACE_ID?.trim()
|
|
134
|
+
const pane = env.HERDR_PANE_ID?.trim()
|
|
135
|
+
const insideHerdr = Boolean(ws) || Boolean(pane?.includes(':'))
|
|
136
|
+
return insideHerdr && muxAvailable()
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const REVIEW_STATE_TYPE = 'review-session'
|
|
140
|
+
|
|
141
|
+
type ReviewSessionState = {
|
|
142
|
+
active: boolean
|
|
143
|
+
originId?: string
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function setReviewWidget(ctx: ExtensionContext, active: boolean) {
|
|
147
|
+
if (!ctx.hasUI) return
|
|
148
|
+
if (!active) {
|
|
149
|
+
ctx.ui.setWidget('review', undefined)
|
|
150
|
+
return
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
ctx.ui.setWidget('review', (_tui, theme) => {
|
|
154
|
+
const text = new Text(
|
|
155
|
+
theme.fg('warning', 'Review session active, return with /end-review'),
|
|
156
|
+
0,
|
|
157
|
+
0,
|
|
158
|
+
)
|
|
159
|
+
return {
|
|
160
|
+
render(width: number) {
|
|
161
|
+
return text.render(width)
|
|
162
|
+
},
|
|
163
|
+
invalidate() {
|
|
164
|
+
text.invalidate()
|
|
165
|
+
},
|
|
166
|
+
}
|
|
167
|
+
})
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function getReviewState(ctx: ExtensionContext): ReviewSessionState | undefined {
|
|
171
|
+
let state: ReviewSessionState | undefined
|
|
172
|
+
for (const entry of ctx.sessionManager.getBranch()) {
|
|
173
|
+
if (entry.type === 'custom' && entry.customType === REVIEW_STATE_TYPE) {
|
|
174
|
+
state = entry.data as ReviewSessionState | undefined
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
return state
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function applyReviewState(ctx: ExtensionContext) {
|
|
182
|
+
const state = getReviewState(ctx)
|
|
183
|
+
|
|
184
|
+
if (state?.active && state.originId) {
|
|
185
|
+
reviewOriginId = state.originId
|
|
186
|
+
setReviewWidget(ctx, true)
|
|
187
|
+
return
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
reviewOriginId = undefined
|
|
191
|
+
setReviewWidget(ctx, false)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// Review target types (matching Codex's approach)
|
|
195
|
+
type ReviewTarget =
|
|
196
|
+
| { type: 'uncommitted' }
|
|
197
|
+
| { type: 'baseBranch'; branch: string }
|
|
198
|
+
| { type: 'ocrDelegate'; branch: string }
|
|
199
|
+
| { type: 'commit'; sha: string; title?: string }
|
|
200
|
+
| { type: 'custom'; instructions: string }
|
|
201
|
+
| {
|
|
202
|
+
type: 'pullRequest'
|
|
203
|
+
prNumber: number
|
|
204
|
+
baseBranch: string
|
|
205
|
+
title: string
|
|
206
|
+
tuicrInstructions?: string
|
|
207
|
+
worktree?: PrWorktreeInfo
|
|
208
|
+
}
|
|
209
|
+
| { type: 'folder'; paths: string[] }
|
|
210
|
+
|
|
211
|
+
// AIDEV-NOTE: PR reviews under Herdr run in a dedicated worktree (branch
|
|
212
|
+
// review/pr-<n> fetched from pull/<n>/head) instead of hijacking the main
|
|
213
|
+
// checkout — no clean-tree requirement, current branch untouched. Fresh
|
|
214
|
+
// worktrees get `yarn install` up front (see installWorktreeDeps) so the
|
|
215
|
+
// reviewer subagent can run tests. The worktree is auto-removed (with its
|
|
216
|
+
// branch) when the review finishes.
|
|
217
|
+
export interface PrWorktreeInfo {
|
|
218
|
+
path: string
|
|
219
|
+
workspaceId: string
|
|
220
|
+
branch: string
|
|
221
|
+
/** Outstanding async jobs (reviewer, ocr scout); worktree removed at 0. */
|
|
222
|
+
pending: number
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const prWorktrees = new Map<number, PrWorktreeInfo>()
|
|
226
|
+
|
|
227
|
+
// AIDEV-NOTE: PMR-2DS4 — pure refcount helpers so the reserve/release
|
|
228
|
+
// matrix (reviewer spawned|aborted x ocr on|off) is testable without a mux.
|
|
229
|
+
/** Reserve both jobs (reviewer + ocr scout) before either spawns. */
|
|
230
|
+
export function reservePrJobs(info: Pick<PrWorktreeInfo, 'pending'>): void {
|
|
231
|
+
info.pending = 2
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Release one job; returns true when this was the last one (remove worktree). */
|
|
235
|
+
export function releasePrJob(info: Pick<PrWorktreeInfo, 'pending'>): boolean {
|
|
236
|
+
info.pending -= 1
|
|
237
|
+
return info.pending <= 0
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Compose the full review prompt: rubric + target-specific prompt + sem
|
|
242
|
+
* guidance + project REVIEW_GUIDELINES.md. Shared by the /review command and
|
|
243
|
+
* the agent-callable `review` tool — one implementation.
|
|
244
|
+
*
|
|
245
|
+
* AIDEV-NOTE: extraction boundary (was inline in executeReview). Keep both
|
|
246
|
+
* surfaces calling this so prompt composition never diverges.
|
|
247
|
+
*/
|
|
248
|
+
export async function buildFullReviewPrompt(
|
|
249
|
+
pi: ExtensionAPI,
|
|
250
|
+
target: ReviewTarget,
|
|
251
|
+
cwd: string,
|
|
252
|
+
): Promise<string> {
|
|
253
|
+
const prompt = await buildReviewPrompt(pi, target, cwd)
|
|
254
|
+
const semReviewInstructions = await buildSemReviewInstructions(pi, target)
|
|
255
|
+
const projectGuidelines = await loadProjectReviewGuidelines(cwd)
|
|
256
|
+
|
|
257
|
+
// Combine the review rubric with the specific prompt
|
|
258
|
+
let fullPrompt = `${REVIEW_RUBRIC}\n\n---\n\nPlease perform a code review with the following focus:\n\n${prompt}`
|
|
259
|
+
|
|
260
|
+
if (semReviewInstructions) {
|
|
261
|
+
fullPrompt += `\n\n${semReviewInstructions}`
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
if (projectGuidelines) {
|
|
265
|
+
fullPrompt += `\n\nThis project has additional instructions for code reviews:\n\n${projectGuidelines}`
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
if (target.type === 'pullRequest' && target.tuicrInstructions) {
|
|
269
|
+
fullPrompt += target.tuicrInstructions
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
return fullPrompt
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// AIDEV-NOTE: PMR-6EEW gate integrity — pin the /review target at spawn.
|
|
276
|
+
// The /review prompts historically told the reviewer to run `git merge-base`
|
|
277
|
+
// ITSELF (BASE_BRANCH_PROMPT_FALLBACK), so the range reviewed was whatever
|
|
278
|
+
// the reviewer computed at review time — the last unpinned range in the
|
|
279
|
+
// system (PMR-R4AP: review gate pinned itself to main while the base
|
|
280
|
+
// question was open). buildReviewGatePin resolves the range in the harness
|
|
281
|
+
// and returns null for unpinnable targets (uncommitted / folder / custom /
|
|
282
|
+
// unresolvable base) — those keep the legacy behavior instead of failing
|
|
283
|
+
// the whole review. PURE seam: exec injected, tests never touch a repo.
|
|
284
|
+
export async function buildReviewGatePin(
|
|
285
|
+
exec: Exec,
|
|
286
|
+
target: ReviewTarget,
|
|
287
|
+
cwd?: string,
|
|
288
|
+
): Promise<GateTarget | null> {
|
|
289
|
+
let baseRef: string | null = null
|
|
290
|
+
let headRef = 'HEAD'
|
|
291
|
+
let refLabel = ''
|
|
292
|
+
if (target.type === 'baseBranch') {
|
|
293
|
+
baseRef = await getMergeBase(exec, target.branch, cwd)
|
|
294
|
+
refLabel = `review-branch-${target.branch.replace(/[^a-zA-Z0-9-]/g, '-')}`
|
|
295
|
+
} else if (target.type === 'ocrDelegate') {
|
|
296
|
+
baseRef = await getMergeBase(exec, target.branch, cwd)
|
|
297
|
+
refLabel = `review-ocr-${target.branch.replace(/[^a-zA-Z0-9-]/g, '-')}`
|
|
298
|
+
} else if (target.type === 'pullRequest') {
|
|
299
|
+
baseRef = await getMergeBase(exec, target.baseBranch, target.worktree?.path)
|
|
300
|
+
refLabel = `review-pr-${target.prNumber}`
|
|
301
|
+
} else if (target.type === 'commit') {
|
|
302
|
+
baseRef = `${target.sha}^`
|
|
303
|
+
headRef = target.sha
|
|
304
|
+
refLabel = `review-commit-${target.sha.slice(0, 9)}`
|
|
305
|
+
} else {
|
|
306
|
+
return null
|
|
307
|
+
}
|
|
308
|
+
if (baseRef === null) return null
|
|
309
|
+
|
|
310
|
+
const base = await exec('git', ['rev-parse', baseRef], { cwd })
|
|
311
|
+
const head = await exec('git', ['rev-parse', headRef], { cwd })
|
|
312
|
+
if (base.code !== 0 || head.code !== 0) return null
|
|
313
|
+
const baseSha = base.stdout.trim()
|
|
314
|
+
const headSha = head.stdout.trim()
|
|
315
|
+
if (baseSha === '' || headSha === '') return null
|
|
316
|
+
|
|
317
|
+
const diff = await exec('git', ['diff', `${baseSha}..${headSha}`], { cwd })
|
|
318
|
+
if (diff.code !== 0) return null
|
|
319
|
+
|
|
320
|
+
const built = buildGateTarget({
|
|
321
|
+
gate: 'review',
|
|
322
|
+
ref: refLabel,
|
|
323
|
+
baseSha,
|
|
324
|
+
headSha,
|
|
325
|
+
diff: diff.stdout,
|
|
326
|
+
})
|
|
327
|
+
if (!('diffSha256' in built)) return null
|
|
328
|
+
return built
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// AIDEV-NOTE: PMR-R4AP/PMR-5NZB — mode-keyed flow review base, extracted
|
|
332
|
+
// as an exported seam so real-git tests drive both modes without Pi config.
|
|
333
|
+
// In a flow worktree the review base is NOT whatever branch name the agent
|
|
334
|
+
// typed or origin/<branch>: work mode keeps the SHA recorded at worktree
|
|
335
|
+
// create (same value deviation_review uses); personal mode resolves the
|
|
336
|
+
// STABLE range through the ONE shared resolver (shared/stable-range.ts) —
|
|
337
|
+
// the recorded creation-time flowbasesha, integrity-probed by
|
|
338
|
+
// merge-base(HEAD, <local flowbase branch>) === flowbasesha — so the
|
|
339
|
+
// review and deviation gates agree by construction (PMR-R4AP).
|
|
340
|
+
// Returns a typed result, never a bare string:
|
|
341
|
+
// - 'resolved' carries a SHA (never a branch NAME): downstream consumers
|
|
342
|
+
// (buildReviewGatePin, buildReviewPrompt, buildSemReviewInstructions —
|
|
343
|
+
// which omits cwd, isEmptyBranchRange, the ocr args) each call
|
|
344
|
+
// getMergeBase(exec, target.branch, …); a raw SHA has no
|
|
345
|
+
// `<sha>@{upstream}`, so they all land on local `merge-base HEAD <sha>`
|
|
346
|
+
// == the resolved SHA — no per-consumer plumbing needed. Substituting
|
|
347
|
+
// the branch NAME instead would re-resolve through the base's upstream
|
|
348
|
+
// ref — the PMR-MH1Y/DQ7Z regression, forbidden in personal mode (it
|
|
349
|
+
// never pushes, upstream lags local main and sweeps unrelated commits
|
|
350
|
+
// in).
|
|
351
|
+
// - 'legacy' carries the requested branch for unbound (non-flow) reviews
|
|
352
|
+
// and for legacy work-mode worktrees without a recorded sha — unchanged
|
|
353
|
+
// behavior; the isEmptyBranchRange refusal in the tool execute still
|
|
354
|
+
// produces the friendly empty-range error for those.
|
|
355
|
+
// - 'refuse' is the personal fail-closed outcome (diverged / no-sha /
|
|
356
|
+
// corrupt-sha / range-error) and becomes the tool's isError result
|
|
357
|
+
// BEFORE the empty-range check — a bound personal worktree never
|
|
358
|
+
// silently falls back to a moving base.
|
|
359
|
+
// AIDEV-NOTE: PMR-7N3D (REPLACED by PMR-5NZB — kept as history) — personal
|
|
360
|
+
// mode used to resolve the gate-time base as the rebase-aware
|
|
361
|
+
// merge-base(HEAD, <local flowbase branch>) and fell back to the recorded
|
|
362
|
+
// sha / requested branch on resolution failure. The stable-range contract
|
|
363
|
+
// inverted that policy: the recorded sha is the pin and a moved merge-base
|
|
364
|
+
// is an integrity failure that refuses, not a new base.
|
|
365
|
+
export type BranchReviewRef =
|
|
366
|
+
| { kind: 'resolved'; sha: string }
|
|
367
|
+
| { kind: 'legacy'; ref: string }
|
|
368
|
+
| { kind: 'refuse'; reason: string }
|
|
369
|
+
|
|
370
|
+
export async function resolveBranchRefForReview(
|
|
371
|
+
pi: ExtensionAPI,
|
|
372
|
+
requestedBranch: string,
|
|
373
|
+
cwd: string,
|
|
374
|
+
mode: WorkMode | (() => Promise<WorkMode>),
|
|
375
|
+
): Promise<BranchReviewRef> {
|
|
376
|
+
const recorded = await readFlowBase(execOf(pi), cwd)
|
|
377
|
+
if (!recorded.ok) return { kind: 'legacy', ref: requestedBranch }
|
|
378
|
+
// AIDEV-NOTE: PMR-1W7N — the mode is resolved LAZILY, only once a flow
|
|
379
|
+
// base is actually recorded: a non-flow branch review (or a hermetic mock
|
|
380
|
+
// test) never touches pi-flow config, so a malformed config file cannot
|
|
381
|
+
// turn the friendly empty-range refusal into a raw tool exception.
|
|
382
|
+
let resolvedMode: WorkMode
|
|
383
|
+
if (typeof mode === 'function') {
|
|
384
|
+
resolvedMode = await mode()
|
|
385
|
+
} else {
|
|
386
|
+
resolvedMode = mode
|
|
387
|
+
}
|
|
388
|
+
if (MODE_PROFILE[resolvedMode].baseResolution === 'recorded-sha-integrity') {
|
|
389
|
+
// AIDEV-NOTE: PMR-5NZB — personal resolves through the ONE shared
|
|
390
|
+
// stable-range resolver; its typed refusal becomes the gate's
|
|
391
|
+
// fail-closed 'refuse' with the recovery text intact. A no-binding
|
|
392
|
+
// race (the base vanished between the read above and the probe) keeps
|
|
393
|
+
// the legacy non-flow behavior rather than refusing.
|
|
394
|
+
const stable = await resolveStableRange(execOf(pi), cwd)
|
|
395
|
+
if (!stable.ok) {
|
|
396
|
+
if (stable.kind === 'no-binding') {
|
|
397
|
+
return { kind: 'legacy', ref: requestedBranch }
|
|
398
|
+
}
|
|
399
|
+
return { kind: 'refuse', reason: stableRefusalText(stable, 'review') }
|
|
400
|
+
}
|
|
401
|
+
return { kind: 'resolved', sha: stable.value.baseSha }
|
|
402
|
+
}
|
|
403
|
+
// AIDEV-NOTE: PMR-5NZB — work mode byte-for-byte unchanged: the recorded
|
|
404
|
+
// flowbasesha anchors the review; a legacy worktree without one keeps
|
|
405
|
+
// the requested branch. No integrity probe, no stable-range resolver.
|
|
406
|
+
if (recorded.value.sha !== null) {
|
|
407
|
+
return { kind: 'resolved', sha: recorded.value.sha }
|
|
408
|
+
}
|
|
409
|
+
return { kind: 'legacy', ref: requestedBranch }
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** Echo-contract section appended to the reviewer prompt when pinned. */
|
|
413
|
+
export function reviewEchoSection(target: GateTarget): string {
|
|
414
|
+
let subtaskSection = ''
|
|
415
|
+
if (target.subtask !== undefined) {
|
|
416
|
+
subtaskSection = `\n\nThis review is scoped to subtask ${target.subtask.ref}. Also end with a SECOND final line:\n ${reviewedCommitsLine(target)}\ncopied EXACTLY (reviewed_commits: <sha>,<sha>,...). Both lines are compared against the pin; any difference invalidates your review.`
|
|
417
|
+
}
|
|
418
|
+
return `
|
|
419
|
+
|
|
420
|
+
---
|
|
421
|
+
|
|
422
|
+
## Pinned review target (gate integrity)
|
|
423
|
+
|
|
424
|
+
The harness pinned the exact range you must review:
|
|
425
|
+
${reviewedRangeLine(target)}${subtaskSection}
|
|
426
|
+
|
|
427
|
+
End your review with that line copied EXACTLY (reviewed_range: <base>..<head>), as the final line of your output. It is compared character by character against the pin; any difference invalidates your review. Do not recompute the merge-base — review the pinned range only.`
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// Prompts (adapted from Codex)
|
|
431
|
+
const UNCOMMITTED_PROMPT =
|
|
432
|
+
'Review the current code changes (staged, unstaged, and untracked files) and provide prioritized findings.'
|
|
433
|
+
|
|
434
|
+
const BASE_BRANCH_PROMPT_WITH_MERGE_BASE =
|
|
435
|
+
"Review the code changes against the base branch '{baseBranch}'. The merge base commit for this comparison is {mergeBaseSha}. Run `git diff {mergeBaseSha}` to inspect the changes relative to {baseBranch}. Provide prioritized, actionable findings."
|
|
436
|
+
|
|
437
|
+
const BASE_BRANCH_PROMPT_FALLBACK =
|
|
438
|
+
'Review the code changes against the base branch \'{branch}\'. Start by finding the merge diff between the current branch and {branch}\'s upstream e.g. (`git merge-base HEAD "$(git rev-parse --abbrev-ref "{branch}@{upstream}")"`), then run `git diff` against that SHA to see what changes we would merge into the {branch} branch. Provide prioritized, actionable findings.'
|
|
439
|
+
|
|
440
|
+
// AIDEV-NOTE: ocr delegate mode — the reviewing agent IS the LLM. ocr only
|
|
441
|
+
// emits the reviewable-file spec (delegate preview) and resolved rules
|
|
442
|
+
// (delegate rule); no ocr LLM config required.
|
|
443
|
+
const OCR_DELEGATE_PROMPT = [
|
|
444
|
+
"Perform a delegated OpenCodeReview (host-agent mode) of the current branch's changes against '{baseBranch}'. The diff base ref is {fromRef}.",
|
|
445
|
+
"You are the reviewing LLM — do NOT run `ocr review` or `ocr scan` (they call the binary's own LLM).",
|
|
446
|
+
'Steps:',
|
|
447
|
+
'1. Run `ocr delegate preview --from {fromRef} --to HEAD --format json` to list the reviewable files.',
|
|
448
|
+
'2. Run `ocr delegate rule <file...> --from {fromRef} --to HEAD --format json` on those files to resolve the review rules.',
|
|
449
|
+
'3. Run `git diff {fromRef}` to inspect the changes.',
|
|
450
|
+
'4. Apply the resolved rules to the changes and provide prioritized, actionable findings. For each finding cite file and line, the rule it maps to, and a suggested fix.',
|
|
451
|
+
].join('\n')
|
|
452
|
+
|
|
453
|
+
const COMMIT_PROMPT_WITH_TITLE =
|
|
454
|
+
'Review the code changes introduced by commit {sha} ("{title}"). Provide prioritized, actionable findings.'
|
|
455
|
+
|
|
456
|
+
const COMMIT_PROMPT =
|
|
457
|
+
'Review the code changes introduced by commit {sha}. Provide prioritized, actionable findings.'
|
|
458
|
+
|
|
459
|
+
const PULL_REQUEST_PROMPT =
|
|
460
|
+
'Review pull request #{prNumber} ("{title}") against the base branch \'{baseBranch}\'. The merge base commit for this comparison is {mergeBaseSha}. Run `git diff {mergeBaseSha}` to inspect the changes that would be merged. Provide prioritized, actionable findings.'
|
|
461
|
+
|
|
462
|
+
const PULL_REQUEST_PROMPT_FALLBACK =
|
|
463
|
+
'Review pull request #{prNumber} ("{title}") against the base branch \'{baseBranch}\'. Start by finding the merge base between the current branch and {baseBranch} (e.g., `git merge-base HEAD {baseBranch}`), then run `git diff` against that SHA to see the changes that would be merged. Provide prioritized, actionable findings.'
|
|
464
|
+
|
|
465
|
+
const FOLDER_REVIEW_PROMPT =
|
|
466
|
+
'Review the code in the following paths: {paths}. This is a snapshot review (not a diff). Read the files directly in these paths and provide prioritized, actionable findings.'
|
|
467
|
+
|
|
468
|
+
// The detailed review rubric (adapted from Codex's review_prompt.md)
|
|
469
|
+
const REVIEW_RUBRIC = `# Review Guidelines
|
|
470
|
+
|
|
471
|
+
You are acting as a code reviewer for a proposed code change made by another engineer.
|
|
472
|
+
|
|
473
|
+
Below are default guidelines for determining what to flag. These are not the final word — if you encounter more specific guidelines elsewhere (in a developer message, user message, file, or project review guidelines appended below), those override these general instructions.
|
|
474
|
+
|
|
475
|
+
## Determining what to flag
|
|
476
|
+
|
|
477
|
+
Flag issues that:
|
|
478
|
+
1. Meaningfully impact the accuracy, performance, security, or maintainability of the code.
|
|
479
|
+
2. Are discrete and actionable (not general issues or multiple combined issues).
|
|
480
|
+
3. Don't demand rigor inconsistent with the rest of the codebase.
|
|
481
|
+
4. Were introduced in the changes being reviewed (not pre-existing bugs).
|
|
482
|
+
5. The author would likely fix if aware of them.
|
|
483
|
+
6. Don't rely on unstated assumptions about the codebase or author's intent.
|
|
484
|
+
7. Have provable impact on other parts of the code — it is not enough to speculate that a change may disrupt another part, you must identify the parts that are provably affected.
|
|
485
|
+
8. Are clearly not intentional changes by the author.
|
|
486
|
+
9. Be particularly careful with untrusted user input and follow the specific guidelines to review.
|
|
487
|
+
|
|
488
|
+
## Untrusted User Input
|
|
489
|
+
|
|
490
|
+
1. Be careful with open redirects, they must always be checked to only go to trusted domains (?next_page=...)
|
|
491
|
+
2. Always flag SQL that is not parametrized
|
|
492
|
+
3. In systems with user supplied URL input, http fetches always need to be protected against access to local resources (intercept DNS resolver!)
|
|
493
|
+
4. Escape, don't sanitize if you have the option (eg: HTML escaping)
|
|
494
|
+
|
|
495
|
+
## Comment guidelines
|
|
496
|
+
|
|
497
|
+
1. Be clear about why the issue is a problem.
|
|
498
|
+
2. Communicate severity appropriately - don't exaggerate.
|
|
499
|
+
3. Be brief - at most 1 paragraph.
|
|
500
|
+
4. Keep code snippets under 3 lines, wrapped in inline code or code blocks.
|
|
501
|
+
5. Use \`\`\`suggestion blocks ONLY for concrete replacement code (minimal lines; no commentary inside the block). Preserve the exact leading whitespace of the replaced lines.
|
|
502
|
+
6. Explicitly state scenarios/environments where the issue arises.
|
|
503
|
+
7. Use a matter-of-fact tone - helpful AI assistant, not accusatory.
|
|
504
|
+
8. Write for quick comprehension without close reading.
|
|
505
|
+
9. Avoid excessive flattery or unhelpful phrases like "Great job...".
|
|
506
|
+
|
|
507
|
+
## Review priorities
|
|
508
|
+
|
|
509
|
+
1. Call out newly added dependencies explicitly and explain why they're needed.
|
|
510
|
+
2. Prefer simple, direct solutions over wrappers or abstractions without clear value.
|
|
511
|
+
3. Favor fail-fast behavior; avoid logging-and-continue patterns that hide errors.
|
|
512
|
+
4. Prefer predictable production behavior; crashing is better than silent degradation.
|
|
513
|
+
5. Treat back pressure handling as critical to system stability.
|
|
514
|
+
6. Apply system-level thinking; flag changes that increase operational risk or on-call wakeups.
|
|
515
|
+
7. Ensure that errors are always checked against codes or stable identifiers, never error messages.
|
|
516
|
+
|
|
517
|
+
## Priority levels
|
|
518
|
+
|
|
519
|
+
Tag each finding with a priority level in the title:
|
|
520
|
+
- [P0] - Drop everything to fix. Blocking release/operations. Only for universal issues that do not depend on assumptions about inputs.
|
|
521
|
+
- [P1] - Urgent. Should be addressed in the next cycle.
|
|
522
|
+
- [P2] - Normal. To be fixed eventually.
|
|
523
|
+
- [P3] - Low. Nice to have.
|
|
524
|
+
|
|
525
|
+
## Output format
|
|
526
|
+
|
|
527
|
+
Provide your findings in a clear, structured format:
|
|
528
|
+
1. List each finding with its priority tag, file location, and explanation.
|
|
529
|
+
2. Findings must reference locations that overlap with the actual diff — don't flag pre-existing code.
|
|
530
|
+
3. Keep line references as short as possible (avoid ranges over 5-10 lines; pick the most suitable subrange).
|
|
531
|
+
4. At the end, provide an overall verdict: "correct" (no blocking issues) or "needs attention" (has blocking issues).
|
|
532
|
+
5. Ignore trivial style issues unless they obscure meaning or violate documented standards.
|
|
533
|
+
6. Do not generate a full PR fix — only flag issues and optionally provide short suggestion blocks.
|
|
534
|
+
${REVIEW_VERDICT_INSTRUCTIONS}
|
|
535
|
+
|
|
536
|
+
Output all findings the author would fix if they knew about them. If there are no qualifying findings, explicitly state the code looks good. Don't stop at the first finding - list every qualifying issue.`
|
|
537
|
+
|
|
538
|
+
async function loadProjectReviewGuidelines(
|
|
539
|
+
cwd: string,
|
|
540
|
+
): Promise<string | null> {
|
|
541
|
+
let currentDir = path.resolve(cwd)
|
|
542
|
+
|
|
543
|
+
while (true) {
|
|
544
|
+
const piDir = path.join(currentDir, CONFIG_DIR_NAME)
|
|
545
|
+
const guidelinesPath = path.join(currentDir, 'REVIEW_GUIDELINES.md')
|
|
546
|
+
|
|
547
|
+
const piStats = await fs.stat(piDir).catch(() => null)
|
|
548
|
+
if (piStats?.isDirectory()) {
|
|
549
|
+
const guidelineStats = await fs.stat(guidelinesPath).catch(() => null)
|
|
550
|
+
if (guidelineStats?.isFile()) {
|
|
551
|
+
try {
|
|
552
|
+
const content = await fs.readFile(guidelinesPath, 'utf8')
|
|
553
|
+
const trimmed = content.trim()
|
|
554
|
+
if (trimmed) {
|
|
555
|
+
return trimmed
|
|
556
|
+
}
|
|
557
|
+
return null
|
|
558
|
+
} catch {
|
|
559
|
+
return null
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
return null
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
const parentDir = path.dirname(currentDir)
|
|
566
|
+
if (parentDir === currentDir) {
|
|
567
|
+
return null
|
|
568
|
+
}
|
|
569
|
+
currentDir = parentDir
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
/**
|
|
574
|
+
* AIDEV-NOTE: PMR-1CCT — prefer the active flow's worktree as the review cwd
|
|
575
|
+
* so branch/uncommitted reviews diff the tree carrying the change, not the
|
|
576
|
+
* session checkout.
|
|
577
|
+
* AIDEV-NOTE: PMR-0KMQ — upgraded to the VERIFIED resolver (binding → aven
|
|
578
|
+
* note → herdr list; each candidate verified: path exists, common git dir
|
|
579
|
+
* matches the session repo per PMR-9XR0, HEAD branch matches). Stale/foreign
|
|
580
|
+
* bindings are no longer trusted by path alone and no longer cleared here —
|
|
581
|
+
* they fall through to the other sources, and only a total resolution
|
|
582
|
+
* failure silently falls back to the session checkout (branch/uncommitted
|
|
583
|
+
* semantics preserved; their wrong-tree guard is isEmptyBranchRange).
|
|
584
|
+
*/
|
|
585
|
+
async function resolveFlowReviewCwd(
|
|
586
|
+
pi: ExtensionAPI,
|
|
587
|
+
fallback: string,
|
|
588
|
+
): Promise<string> {
|
|
589
|
+
const activeRef = getActiveFlowRef()
|
|
590
|
+
if (activeRef === null) return fallback
|
|
591
|
+
try {
|
|
592
|
+
const wt = await resolveReviewWorktree(
|
|
593
|
+
activeRef,
|
|
594
|
+
productionReviewDeps(pi, fallback),
|
|
595
|
+
)
|
|
596
|
+
return wt.path
|
|
597
|
+
} catch {
|
|
598
|
+
return fallback
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
export type CommitReviewCwd =
|
|
603
|
+
| { ok: true; cwd: string; source: 'worktree' | 'session' }
|
|
604
|
+
| { ok: false; reason: string }
|
|
605
|
+
|
|
606
|
+
// AIDEV-NOTE: PMR-0KMQ — commit reviews of flow work must pin, diff, spawn
|
|
607
|
+
// and re-check HEAD in the VERIFIED bound worktree (PMR-9XR0 identity check);
|
|
608
|
+
// from the session checkout the staleness recheck compares against main's
|
|
609
|
+
// HEAD and reports a bogus 'stale' verdict. Shas NOT on the flow branch keep
|
|
610
|
+
// the session checkout so unrelated commit reviews are unaffected.
|
|
611
|
+
export async function resolveCommitReviewCwd(
|
|
612
|
+
pi: ExtensionAPI,
|
|
613
|
+
sessionCwd: string,
|
|
614
|
+
sha: string,
|
|
615
|
+
): Promise<CommitReviewCwd> {
|
|
616
|
+
const activeRef = getActiveFlowRef()
|
|
617
|
+
if (activeRef === null) {
|
|
618
|
+
return { ok: true, cwd: sessionCwd, source: 'session' }
|
|
619
|
+
}
|
|
620
|
+
let wt: ResolvedWorktree
|
|
621
|
+
try {
|
|
622
|
+
wt = await resolveReviewWorktree(
|
|
623
|
+
activeRef,
|
|
624
|
+
productionReviewDeps(pi, sessionCwd),
|
|
625
|
+
)
|
|
626
|
+
} catch (error) {
|
|
627
|
+
let msg: string
|
|
628
|
+
if (error instanceof Error) {
|
|
629
|
+
msg = error.message
|
|
630
|
+
} else {
|
|
631
|
+
msg = String(error)
|
|
632
|
+
}
|
|
633
|
+
return { ok: false, reason: msg }
|
|
634
|
+
}
|
|
635
|
+
// AIDEV-NOTE: PMR-HXPQ — pi.exec returns non-zero codes without throwing.
|
|
636
|
+
const ancestor = await pi.exec(
|
|
637
|
+
'git',
|
|
638
|
+
['-C', wt.path, 'merge-base', '--is-ancestor', sha, 'HEAD'],
|
|
639
|
+
{},
|
|
640
|
+
)
|
|
641
|
+
if (ancestor.code !== 0) {
|
|
642
|
+
return { ok: true, cwd: sessionCwd, source: 'session' }
|
|
643
|
+
}
|
|
644
|
+
return { ok: true, cwd: wt.path, source: 'worktree' }
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
// The review tool's discriminated target shape (mirrors the inline union on
|
|
648
|
+
// registerTool(...).execute) so the exported cwd seam below stays type-safe.
|
|
649
|
+
export type ReviewToolTarget =
|
|
650
|
+
| { type: 'uncommitted' }
|
|
651
|
+
| { type: 'branch'; branch: string }
|
|
652
|
+
| { type: 'commit'; sha: string; title?: string }
|
|
653
|
+
| { type: 'pr'; ref: string }
|
|
654
|
+
| { type: 'folder'; paths: string[] }
|
|
655
|
+
| { type: 'custom'; instructions: string }
|
|
656
|
+
|
|
657
|
+
export type ReviewTargetCwd =
|
|
658
|
+
| { ok: true; cwd: string }
|
|
659
|
+
| { ok: false; reason: string; sha: string }
|
|
660
|
+
|
|
661
|
+
// AIDEV-NOTE: PMR-TDJC — the review tool's per-target cwd dispatch, extracted
|
|
662
|
+
// into an EXPORTED mux-free seam (same testing rationale as
|
|
663
|
+
// resolveCommitReviewCwd / resolveDeviationCwd): the tool consumes `reviewCwd`
|
|
664
|
+
// only AFTER canSpawnReviewSubagent() gates the spawn path, so a deterministic
|
|
665
|
+
// unit test cannot observe the resolved cwd through execute() in a no-mux
|
|
666
|
+
// environment. Routing lives entirely here: branch/uncommitted/custom/folder
|
|
667
|
+
// resolve through the bound flow worktree (resolveFlowReviewCwd already returns
|
|
668
|
+
// the session fallback when no flow is live, so this stays correct outside a
|
|
669
|
+
// flow); commit resolves the VERIFIED bound worktree (PMR-0KMQ) or refuses.
|
|
670
|
+
export async function resolveReviewCwdForTarget(
|
|
671
|
+
pi: ExtensionAPI,
|
|
672
|
+
sessionCwd: string,
|
|
673
|
+
p: ReviewToolTarget,
|
|
674
|
+
): Promise<ReviewTargetCwd> {
|
|
675
|
+
if (
|
|
676
|
+
p.type === 'branch' ||
|
|
677
|
+
p.type === 'uncommitted' ||
|
|
678
|
+
p.type === 'custom' ||
|
|
679
|
+
p.type === 'folder'
|
|
680
|
+
) {
|
|
681
|
+
return { ok: true, cwd: await resolveFlowReviewCwd(pi, sessionCwd) }
|
|
682
|
+
}
|
|
683
|
+
if (p.type === 'commit' && getActiveFlowRef() !== null) {
|
|
684
|
+
const commitCwd = await resolveCommitReviewCwd(pi, sessionCwd, p.sha)
|
|
685
|
+
if (!commitCwd.ok) {
|
|
686
|
+
return { ok: false, reason: commitCwd.reason, sha: p.sha }
|
|
687
|
+
}
|
|
688
|
+
return { ok: true, cwd: commitCwd.cwd }
|
|
689
|
+
}
|
|
690
|
+
// pr, and commit with no active flow: session checkout. (folder/custom are
|
|
691
|
+
// handled above via resolveFlowReviewCwd — PMR-TDJC.)
|
|
692
|
+
return { ok: true, cwd: sessionCwd }
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
/**
|
|
696
|
+
* AIDEV-NOTE: PMR-1CCT — empty-range guard. A baseBranch review whose merge
|
|
697
|
+
* base equals HEAD diffs nothing; flow work lives in an isolated worktree, so
|
|
698
|
+
* from the main checkout the range is main..main and OCR would return a
|
|
699
|
+
* skipped/clean-looking artifact — a silent gate pass. Callers must fail
|
|
700
|
+
* loudly instead. Unresolvable refs stay unguarded (existing prompt-fallback
|
|
701
|
+
* behavior).
|
|
702
|
+
*/
|
|
703
|
+
export async function isEmptyBranchRange(
|
|
704
|
+
pi: ExtensionAPI,
|
|
705
|
+
branch: string,
|
|
706
|
+
cwd: string,
|
|
707
|
+
): Promise<boolean> {
|
|
708
|
+
const mergeBase = await getMergeBase(execOf(pi), branch, cwd)
|
|
709
|
+
if (mergeBase === null) return false
|
|
710
|
+
try {
|
|
711
|
+
const { stdout, code } = await pi.exec('git', ['rev-parse', 'HEAD'], {
|
|
712
|
+
cwd,
|
|
713
|
+
})
|
|
714
|
+
if (code !== 0) return false
|
|
715
|
+
return stdout.trim() === mergeBase
|
|
716
|
+
} catch {
|
|
717
|
+
return false
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
// AIDEV-NOTE: lazy wrapper — mock pis without exec must fail inside the
|
|
722
|
+
// resolver's try/catch (null), not at call-site bind time.
|
|
723
|
+
function execOf(pi: ExtensionAPI): Exec {
|
|
724
|
+
return (cmd, args, options) => pi.exec(cmd, args, options)
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
// AIDEV-NOTE: PMR-7TPN — linked flow worktrees other than the review cwd.
|
|
728
|
+
// Pure: fixture-tested against `herdr worktree list` payloads.
|
|
729
|
+
export function unboundFlowWorktrees(
|
|
730
|
+
worktrees: HerdrWorktree[],
|
|
731
|
+
cwd: string,
|
|
732
|
+
): HerdrWorktree[] {
|
|
733
|
+
return filterLinked(worktrees).filter((w) => w.path !== cwd)
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/**
|
|
737
|
+
* AIDEV-NOTE: PMR-7TPN — warning for a review launched with NO active flow
|
|
738
|
+
* and NO worktree binding while linked flow worktrees exist elsewhere: the
|
|
739
|
+
* real change likely lives in one of them, and a review from this checkout
|
|
740
|
+
* would read the wrong diff (the PMR-PKSS failure mode). Null = no warning.
|
|
741
|
+
*/
|
|
742
|
+
export function unboundWorktreeWarning(
|
|
743
|
+
worktrees: HerdrWorktree[],
|
|
744
|
+
cwd: string,
|
|
745
|
+
): string | null {
|
|
746
|
+
const others = unboundFlowWorktrees(worktrees, cwd)
|
|
747
|
+
if (others.length === 0) return null
|
|
748
|
+
const names = others.map((w) => `${w.branch} (${w.path})`).join(', ')
|
|
749
|
+
return `WARNING: no flow is active in this session, but linked flow worktree(s) exist: ${names}. If this review belongs to a flow ticket, the change likely lives in that worktree, not this checkout — run the review from there or restart the flow (/flow <ref>) so the worktree binding is known. This review runs against ${cwd}; check the Reviewed-range line in the result before trusting the verdict.`
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/** Async wrapper: herdr unavailable or failing list = no warning (best-effort). */
|
|
753
|
+
async function unboundWorktreeWarningFor(
|
|
754
|
+
pi: ExtensionAPI,
|
|
755
|
+
cwd: string,
|
|
756
|
+
): Promise<string | null> {
|
|
757
|
+
try {
|
|
758
|
+
return unboundWorktreeWarning(await worktreeList(pi, cwd), cwd)
|
|
759
|
+
} catch {
|
|
760
|
+
return null
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
// AIDEV-NOTE: PMR-7TPN — pure header builders for delivered review results;
|
|
765
|
+
// every result states the reviewed range (when pinned) and the cwd.
|
|
766
|
+
export function pinnedRangeHeader(pin: GateTarget, cwd: string): string {
|
|
767
|
+
return `Reviewed range: ${pin.baseSha}..${pin.headSha} in ${cwd} (verified against the pinned target)`
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
export function legacyRangeHeader(cwd: string | undefined): string {
|
|
771
|
+
return `Reviewed in: ${cwd ?? 'the session checkout'} (no pin — legacy mode; range unverified)`
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
/**
|
|
775
|
+
* Get list of local branches
|
|
776
|
+
*/
|
|
777
|
+
async function getLocalBranches(pi: ExtensionAPI): Promise<string[]> {
|
|
778
|
+
const { stdout, code } = await pi.exec('git', [
|
|
779
|
+
'branch',
|
|
780
|
+
'--format=%(refname:short)',
|
|
781
|
+
])
|
|
782
|
+
if (code !== 0) return []
|
|
783
|
+
return stdout
|
|
784
|
+
.trim()
|
|
785
|
+
.split('\n')
|
|
786
|
+
.filter((b) => b.trim())
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
/**
|
|
790
|
+
* Get list of recent commits
|
|
791
|
+
*/
|
|
792
|
+
async function getRecentCommits(
|
|
793
|
+
pi: ExtensionAPI,
|
|
794
|
+
limit: number = 10,
|
|
795
|
+
): Promise<Array<{ sha: string; title: string }>> {
|
|
796
|
+
const { stdout, code } = await pi.exec('git', [
|
|
797
|
+
'log',
|
|
798
|
+
`--oneline`,
|
|
799
|
+
`-n`,
|
|
800
|
+
`${limit}`,
|
|
801
|
+
])
|
|
802
|
+
if (code !== 0) return []
|
|
803
|
+
|
|
804
|
+
return stdout
|
|
805
|
+
.trim()
|
|
806
|
+
.split('\n')
|
|
807
|
+
.filter((line) => line.trim())
|
|
808
|
+
.map((line) => {
|
|
809
|
+
const [sha, ...rest] = line.trim().split(' ')
|
|
810
|
+
return { sha, title: rest.join(' ') }
|
|
811
|
+
})
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
/**
|
|
815
|
+
* Check if there are uncommitted changes (staged, unstaged, or untracked)
|
|
816
|
+
*/
|
|
817
|
+
async function hasUncommittedChanges(pi: ExtensionAPI): Promise<boolean> {
|
|
818
|
+
const { stdout, code } = await pi.exec('git', ['status', '--porcelain'])
|
|
819
|
+
return code === 0 && stdout.trim().length > 0
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
/**
|
|
823
|
+
* Check if there are changes that would prevent switching branches
|
|
824
|
+
* (staged or unstaged changes to tracked files - untracked files are fine)
|
|
825
|
+
*/
|
|
826
|
+
async function hasPendingChanges(pi: ExtensionAPI): Promise<boolean> {
|
|
827
|
+
// Check for staged or unstaged changes to tracked files
|
|
828
|
+
const { stdout, code } = await pi.exec('git', ['status', '--porcelain'])
|
|
829
|
+
if (code !== 0) return false
|
|
830
|
+
|
|
831
|
+
// Filter out untracked files (lines starting with ??)
|
|
832
|
+
const lines = stdout
|
|
833
|
+
.trim()
|
|
834
|
+
.split('\n')
|
|
835
|
+
.filter((line) => line.trim())
|
|
836
|
+
const trackedChanges = lines.filter((line) => !line.startsWith('??'))
|
|
837
|
+
return trackedChanges.length > 0
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
/**
|
|
841
|
+
* Parse a PR reference (URL or number) and return the PR number
|
|
842
|
+
*/
|
|
843
|
+
function parsePrReference(ref: string): number | null {
|
|
844
|
+
const trimmed = ref.trim()
|
|
845
|
+
|
|
846
|
+
// Try as a number first
|
|
847
|
+
const num = parseInt(trimmed, 10)
|
|
848
|
+
if (!Number.isNaN(num) && num > 0) {
|
|
849
|
+
return num
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
// Try to extract from GitHub URL
|
|
853
|
+
// Formats: https://github.com/owner/repo/pull/123
|
|
854
|
+
// github.com/owner/repo/pull/123
|
|
855
|
+
const urlMatch = trimmed.match(/github\.com\/[^/]+\/[^/]+\/pull\/(\d+)/)
|
|
856
|
+
if (urlMatch) {
|
|
857
|
+
return parseInt(urlMatch[1], 10)
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
return null
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
/**
|
|
864
|
+
* Get PR information from GitHub CLI
|
|
865
|
+
*/
|
|
866
|
+
async function getPrInfo(
|
|
867
|
+
pi: ExtensionAPI,
|
|
868
|
+
prNumber: number,
|
|
869
|
+
): Promise<{ baseBranch: string; title: string; headBranch: string } | null> {
|
|
870
|
+
const { stdout, code } = await pi.exec('gh', [
|
|
871
|
+
'pr',
|
|
872
|
+
'view',
|
|
873
|
+
String(prNumber),
|
|
874
|
+
'--json',
|
|
875
|
+
'baseRefName,title,headRefName',
|
|
876
|
+
])
|
|
877
|
+
|
|
878
|
+
if (code !== 0) return null
|
|
879
|
+
|
|
880
|
+
try {
|
|
881
|
+
const data = JSON.parse(stdout)
|
|
882
|
+
return {
|
|
883
|
+
baseBranch: data.baseRefName,
|
|
884
|
+
title: data.title,
|
|
885
|
+
headBranch: data.headRefName,
|
|
886
|
+
}
|
|
887
|
+
} catch {
|
|
888
|
+
return null
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
/**
|
|
893
|
+
* Checkout a PR using GitHub CLI
|
|
894
|
+
*/
|
|
895
|
+
async function checkoutPr(
|
|
896
|
+
pi: ExtensionAPI,
|
|
897
|
+
prNumber: number,
|
|
898
|
+
): Promise<{ success: boolean; error?: string }> {
|
|
899
|
+
const { stdout, stderr, code } = await pi.exec('gh', [
|
|
900
|
+
'pr',
|
|
901
|
+
'checkout',
|
|
902
|
+
String(prNumber),
|
|
903
|
+
])
|
|
904
|
+
|
|
905
|
+
if (code !== 0) {
|
|
906
|
+
return {
|
|
907
|
+
success: false,
|
|
908
|
+
error: stderr || stdout || 'Failed to checkout PR',
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
return { success: true }
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
// AIDEV-NOTE: worktree-backed PR review. Branch review/pr-<n> is fetched
|
|
916
|
+
// from pull/<n>/head so the PR code lands in a dedicated Herdr worktree —
|
|
917
|
+
// the main checkout (and its dirty state) is never touched. Only used when
|
|
918
|
+
// a mux is available (the reviewer subagent must run with cwd in the
|
|
919
|
+
// worktree; the legacy in-session path cannot).
|
|
920
|
+
function prWorktreeBranch(prNumber: number): string {
|
|
921
|
+
return `review/pr-${prNumber}`
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
/** First worktree checkout path holding `branch`, via git porcelain. */
|
|
925
|
+
async function findWorktreeForBranch(
|
|
926
|
+
pi: ExtensionAPI,
|
|
927
|
+
cwd: string,
|
|
928
|
+
branch: string,
|
|
929
|
+
): Promise<string | null> {
|
|
930
|
+
const { stdout, code } = await pi.exec(
|
|
931
|
+
'git',
|
|
932
|
+
['worktree', 'list', '--porcelain'],
|
|
933
|
+
{ cwd },
|
|
934
|
+
)
|
|
935
|
+
if (code !== 0) return null
|
|
936
|
+
|
|
937
|
+
let currentPath = ''
|
|
938
|
+
for (const line of stdout.split('\n')) {
|
|
939
|
+
if (line.startsWith('worktree ')) {
|
|
940
|
+
currentPath = line.slice('worktree '.length)
|
|
941
|
+
}
|
|
942
|
+
if (line === `branch refs/heads/${branch}`) {
|
|
943
|
+
return currentPath
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
return null
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
async function removePrWorktree(
|
|
950
|
+
pi: ExtensionAPI,
|
|
951
|
+
ctx: ExtensionContext,
|
|
952
|
+
prNumber: number,
|
|
953
|
+
info: PrWorktreeInfo,
|
|
954
|
+
): Promise<void> {
|
|
955
|
+
const errors: string[] = []
|
|
956
|
+
if (info.workspaceId) {
|
|
957
|
+
try {
|
|
958
|
+
await worktreeRemove(pi, ctx.cwd, info.workspaceId, true)
|
|
959
|
+
} catch (error) {
|
|
960
|
+
errors.push((error as Error).message)
|
|
961
|
+
}
|
|
962
|
+
} else {
|
|
963
|
+
const result = await pi.exec(
|
|
964
|
+
'git',
|
|
965
|
+
['worktree', 'remove', '--force', info.path],
|
|
966
|
+
{ cwd: ctx.cwd },
|
|
967
|
+
)
|
|
968
|
+
if (result.code !== 0) {
|
|
969
|
+
errors.push(result.stderr || result.stdout)
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
// Branch is a fetched copy of the PR head — force delete is safe.
|
|
974
|
+
const branch = await pi.exec('git', ['branch', '-D', info.branch], {
|
|
975
|
+
cwd: ctx.cwd,
|
|
976
|
+
})
|
|
977
|
+
if (branch.code !== 0) {
|
|
978
|
+
errors.push(branch.stderr || branch.stdout)
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
if (errors.length === 0) {
|
|
982
|
+
prWorktrees.delete(prNumber)
|
|
983
|
+
ctx.ui.notify(`Removed review worktree for PR #${prNumber}`, 'info')
|
|
984
|
+
return
|
|
985
|
+
}
|
|
986
|
+
ctx.ui.notify(
|
|
987
|
+
`Worktree cleanup for PR #${prNumber} failed: ${errors.join('; ')} — remove manually when done.`,
|
|
988
|
+
'warning',
|
|
989
|
+
)
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
// AIDEV-NOTE: fresh review worktrees get deps installed up front so the
|
|
993
|
+
// reviewer subagent can run tests immediately. GH_TOKEN from `gh auth
|
|
994
|
+
// token` authenticates private GitHub Packages registries (SalaryHero
|
|
995
|
+
// repos); pi.exec has no env option, so the token is injected via bash -c.
|
|
996
|
+
// Gated on yarn.lock — non-yarn repos (e.g. bun monorepos) are skipped.
|
|
997
|
+
// Install failure only warns: the code-reading part of the review still
|
|
998
|
+
// works without node_modules.
|
|
999
|
+
async function installWorktreeDeps(
|
|
1000
|
+
pi: ExtensionAPI,
|
|
1001
|
+
ctx: ExtensionContext,
|
|
1002
|
+
worktreePath: string,
|
|
1003
|
+
): Promise<void> {
|
|
1004
|
+
try {
|
|
1005
|
+
await fs.access(path.join(worktreePath, 'yarn.lock'))
|
|
1006
|
+
} catch {
|
|
1007
|
+
return
|
|
1008
|
+
}
|
|
1009
|
+
ctx.ui.notify(
|
|
1010
|
+
'Installing dependencies in review worktree (yarn install)...',
|
|
1011
|
+
'info',
|
|
1012
|
+
)
|
|
1013
|
+
const result = await pi.exec(
|
|
1014
|
+
'bash',
|
|
1015
|
+
['-c', 'GH_TOKEN=$(gh auth token) yarn install'],
|
|
1016
|
+
{ cwd: worktreePath, timeout: 10 * 60 * 1000 },
|
|
1017
|
+
)
|
|
1018
|
+
if (result.code !== 0) {
|
|
1019
|
+
ctx.ui.notify(
|
|
1020
|
+
`yarn install in review worktree failed — tests may not run: ${(result.stderr || result.stdout).slice(-300)}`,
|
|
1021
|
+
'warning',
|
|
1022
|
+
)
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
async function preparePrWorktree(
|
|
1027
|
+
pi: ExtensionAPI,
|
|
1028
|
+
ctx: ExtensionContext,
|
|
1029
|
+
prNumber: number,
|
|
1030
|
+
): Promise<PrWorktreeInfo | null> {
|
|
1031
|
+
const preflight = await herdrAvailable(pi, ctx.cwd)
|
|
1032
|
+
if (!preflight.ok) return null
|
|
1033
|
+
|
|
1034
|
+
const branch = prWorktreeBranch(prNumber)
|
|
1035
|
+
|
|
1036
|
+
const existing = prWorktrees.get(prNumber)
|
|
1037
|
+
if (existing) {
|
|
1038
|
+
ctx.ui.notify(`Reusing review worktree for PR #${prNumber}`, 'info')
|
|
1039
|
+
return existing
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
// AIDEV-NOTE: stale detection uses `git worktree list --porcelain`, NOT
|
|
1043
|
+
// `herdr worktree list` — the herdr listing is focus-scoped and may show
|
|
1044
|
+
// another repo's worktrees. A stale worktree from a dead session is
|
|
1045
|
+
// force-removed (with its branch) before recreating.
|
|
1046
|
+
const stale = await findWorktreeForBranch(pi, ctx.cwd, branch)
|
|
1047
|
+
if (stale) {
|
|
1048
|
+
ctx.ui.notify(
|
|
1049
|
+
`Removing stale review worktree for PR #${prNumber}...`,
|
|
1050
|
+
'info',
|
|
1051
|
+
)
|
|
1052
|
+
await pi.exec('git', ['worktree', 'remove', '--force', stale], {
|
|
1053
|
+
cwd: ctx.cwd,
|
|
1054
|
+
})
|
|
1055
|
+
await pi.exec('git', ['branch', '-D', branch], { cwd: ctx.cwd })
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
const fetch = await pi.exec(
|
|
1059
|
+
'git',
|
|
1060
|
+
['fetch', '--force', 'origin', `pull/${prNumber}/head:${branch}`],
|
|
1061
|
+
{ cwd: ctx.cwd },
|
|
1062
|
+
)
|
|
1063
|
+
if (fetch.code !== 0) {
|
|
1064
|
+
ctx.ui.notify(
|
|
1065
|
+
`Failed to fetch PR ref: ${fetch.stderr || fetch.stdout}`,
|
|
1066
|
+
'error',
|
|
1067
|
+
)
|
|
1068
|
+
return null
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
const created = await worktreeCreate(
|
|
1072
|
+
pi,
|
|
1073
|
+
ctx.cwd,
|
|
1074
|
+
branch,
|
|
1075
|
+
`review-pr-${prNumber}`,
|
|
1076
|
+
).catch(() => null)
|
|
1077
|
+
if (!created || created.path === '') {
|
|
1078
|
+
ctx.ui.notify(
|
|
1079
|
+
`Failed to create review worktree${created ? ` (no path in output: ${JSON.stringify(created)})` : ''}`,
|
|
1080
|
+
'error',
|
|
1081
|
+
)
|
|
1082
|
+
return null
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
await installWorktreeDeps(pi, ctx, created.path)
|
|
1086
|
+
|
|
1087
|
+
const info: PrWorktreeInfo = {
|
|
1088
|
+
path: created.path,
|
|
1089
|
+
workspaceId: created.workspaceId,
|
|
1090
|
+
branch,
|
|
1091
|
+
pending: 0,
|
|
1092
|
+
}
|
|
1093
|
+
prWorktrees.set(prNumber, info)
|
|
1094
|
+
return info
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
/**
|
|
1098
|
+
* Check whether a binary is available on PATH.
|
|
1099
|
+
*/
|
|
1100
|
+
async function commandExists(pi: ExtensionAPI, bin: string): Promise<boolean> {
|
|
1101
|
+
const { code } = await pi.exec('which', [bin])
|
|
1102
|
+
return code === 0
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1105
|
+
/**
|
|
1106
|
+
* Get "owner/repo" for the current repo from GitHub CLI.
|
|
1107
|
+
*/
|
|
1108
|
+
async function getRepoSlug(pi: ExtensionAPI): Promise<string | null> {
|
|
1109
|
+
const { stdout, code } = await pi.exec('gh', [
|
|
1110
|
+
'repo',
|
|
1111
|
+
'view',
|
|
1112
|
+
'--json',
|
|
1113
|
+
'nameWithOwner',
|
|
1114
|
+
])
|
|
1115
|
+
if (code !== 0) return null
|
|
1116
|
+
try {
|
|
1117
|
+
return JSON.parse(stdout).nameWithOwner ?? null
|
|
1118
|
+
} catch {
|
|
1119
|
+
return null
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
// AIDEV-NOTE: Fire-and-forget Herdr pane launch for PR review. Never blocks or
|
|
1124
|
+
// throws into the review flow - any missing piece (Herdr, tuicr, gh slug,
|
|
1125
|
+
// pane split) just skips the pane and the normal chat-based review proceeds.
|
|
1126
|
+
/**
|
|
1127
|
+
* If tuicr + Herdr are available, open a tuicr review TUI for the PR in a
|
|
1128
|
+
* Herdr pane on the right and return tuicr-skill instructions for the agent
|
|
1129
|
+
* to work with that session.
|
|
1130
|
+
*/
|
|
1131
|
+
async function maybeOpenTuicrForPr(
|
|
1132
|
+
pi: ExtensionAPI,
|
|
1133
|
+
ctx: ExtensionContext,
|
|
1134
|
+
prNumber: number,
|
|
1135
|
+
reviewCwd?: string,
|
|
1136
|
+
): Promise<string | undefined> {
|
|
1137
|
+
if (process.env.HERDR_ENV !== '1') return undefined
|
|
1138
|
+
if (!(await commandExists(pi, 'tuicr'))) return undefined
|
|
1139
|
+
if (!(await commandExists(pi, 'herdr'))) return undefined
|
|
1140
|
+
|
|
1141
|
+
const repoSlug = await getRepoSlug(pi)
|
|
1142
|
+
if (!repoSlug) return undefined
|
|
1143
|
+
|
|
1144
|
+
const split = await pi.exec('herdr', [
|
|
1145
|
+
'pane',
|
|
1146
|
+
'split',
|
|
1147
|
+
'--current',
|
|
1148
|
+
'--direction',
|
|
1149
|
+
'right',
|
|
1150
|
+
'--cwd',
|
|
1151
|
+
reviewCwd ?? ctx.cwd,
|
|
1152
|
+
'--focus',
|
|
1153
|
+
])
|
|
1154
|
+
if (split.code !== 0) return undefined
|
|
1155
|
+
|
|
1156
|
+
let paneId: string | undefined
|
|
1157
|
+
try {
|
|
1158
|
+
paneId = JSON.parse(split.stdout)?.result?.pane?.pane_id
|
|
1159
|
+
} catch {
|
|
1160
|
+
paneId = undefined
|
|
1161
|
+
}
|
|
1162
|
+
if (!paneId) return undefined
|
|
1163
|
+
|
|
1164
|
+
await pi.exec('herdr', ['pane', 'run', paneId, `tuicr pr ${prNumber}`])
|
|
1165
|
+
ctx.ui.notify(`Opened tuicr for PR #${prNumber} in a Herdr pane`, 'info')
|
|
1166
|
+
|
|
1167
|
+
const sessionSlug = `gh:${repoSlug}/pr/${prNumber}`
|
|
1168
|
+
return `\n\nA tuicr review TUI is open in a Herdr pane for this PR (repo \`${repoSlug}\`, session \`${sessionSlug}\`). Follow the tuicr skill to work with that session, adding each finding with \`tuicr review add\`.
|
|
1169
|
+
|
|
1170
|
+
Before choosing \`--type\`, read the \`comment_types\` list from the tuicr config (\`~/.config/tuicr/config.toml\`, or \`$XDG_CONFIG_HOME/tuicr/config.toml\` if set) and match each finding to the \`id\` whose \`definition\` fits best - do not default to \`issue\` for everything. Typical mapping: must-fix-before-merge -> \`blocker\`, security/data-integrity -> \`security\`, should-fix-but-not-blocking -> \`issue\`, low-priority/optional tweak -> \`nit\` or \`suggestion\`, needs an answer before you can judge it -> \`question\`, missing/weak tests -> \`test\`, missing/wrong types -> \`types\`, missing/wrong error handling -> \`errors\`, unrequested change or leftover debug code -> \`scope\`, something worth calling out positively -> \`praise\`, and explicit delete/move/extract/simplify asks -> the matching id. Fall back to \`--type issue\` only if the config has no \`comment_types\` or none fit. Example: \`tuicr review add --repo ${repoSlug} --session ${sessionSlug} --target-file <path> --line <n> --side new --type <matched-type> --username "pi-review" "<finding>"\`.`
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
/**
|
|
1174
|
+
* Get the current branch name
|
|
1175
|
+
*/
|
|
1176
|
+
async function getCurrentBranch(pi: ExtensionAPI): Promise<string | null> {
|
|
1177
|
+
const { stdout, code } = await pi.exec('git', ['branch', '--show-current'])
|
|
1178
|
+
if (code === 0 && stdout.trim()) {
|
|
1179
|
+
return stdout.trim()
|
|
1180
|
+
}
|
|
1181
|
+
return null
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
/**
|
|
1185
|
+
* Get the default branch (main or master)
|
|
1186
|
+
*/
|
|
1187
|
+
async function getDefaultBranch(pi: ExtensionAPI): Promise<string> {
|
|
1188
|
+
// Try to get from remote HEAD
|
|
1189
|
+
const { stdout, code } = await pi.exec('git', [
|
|
1190
|
+
'symbolic-ref',
|
|
1191
|
+
'refs/remotes/origin/HEAD',
|
|
1192
|
+
'--short',
|
|
1193
|
+
])
|
|
1194
|
+
if (code === 0 && stdout.trim()) {
|
|
1195
|
+
return stdout.trim().replace('origin/', '')
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
// Fall back to checking if main or master exists
|
|
1199
|
+
const branches = await getLocalBranches(pi)
|
|
1200
|
+
if (branches.includes('main')) return 'main'
|
|
1201
|
+
if (branches.includes('master')) return 'master'
|
|
1202
|
+
|
|
1203
|
+
return 'main' // Default fallback
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
/**
|
|
1207
|
+
* Build the review prompt based on target
|
|
1208
|
+
*/
|
|
1209
|
+
async function buildReviewPrompt(
|
|
1210
|
+
pi: ExtensionAPI,
|
|
1211
|
+
target: ReviewTarget,
|
|
1212
|
+
cwd?: string,
|
|
1213
|
+
): Promise<string> {
|
|
1214
|
+
switch (target.type) {
|
|
1215
|
+
case 'uncommitted':
|
|
1216
|
+
return UNCOMMITTED_PROMPT
|
|
1217
|
+
|
|
1218
|
+
case 'baseBranch': {
|
|
1219
|
+
const mergeBase = await getMergeBase(execOf(pi), target.branch, cwd)
|
|
1220
|
+
if (mergeBase) {
|
|
1221
|
+
return BASE_BRANCH_PROMPT_WITH_MERGE_BASE.replace(
|
|
1222
|
+
/{baseBranch}/g,
|
|
1223
|
+
target.branch,
|
|
1224
|
+
).replace(/{mergeBaseSha}/g, mergeBase)
|
|
1225
|
+
}
|
|
1226
|
+
return BASE_BRANCH_PROMPT_FALLBACK.replace(/{branch}/g, target.branch)
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
case 'ocrDelegate': {
|
|
1230
|
+
const mergeBase = await getMergeBase(execOf(pi), target.branch, cwd)
|
|
1231
|
+
const fromRef = mergeBase ?? target.branch
|
|
1232
|
+
return OCR_DELEGATE_PROMPT.replace(
|
|
1233
|
+
/{baseBranch}/g,
|
|
1234
|
+
target.branch,
|
|
1235
|
+
).replace(/{fromRef}/g, fromRef)
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
case 'commit':
|
|
1239
|
+
if (target.title) {
|
|
1240
|
+
return COMMIT_PROMPT_WITH_TITLE.replace('{sha}', target.sha).replace(
|
|
1241
|
+
'{title}',
|
|
1242
|
+
target.title,
|
|
1243
|
+
)
|
|
1244
|
+
}
|
|
1245
|
+
return COMMIT_PROMPT.replace('{sha}', target.sha)
|
|
1246
|
+
|
|
1247
|
+
case 'custom':
|
|
1248
|
+
return target.instructions
|
|
1249
|
+
|
|
1250
|
+
case 'pullRequest': {
|
|
1251
|
+
const mergeBase = await getMergeBase(
|
|
1252
|
+
execOf(pi),
|
|
1253
|
+
target.baseBranch,
|
|
1254
|
+
target.worktree?.path,
|
|
1255
|
+
)
|
|
1256
|
+
if (mergeBase) {
|
|
1257
|
+
return PULL_REQUEST_PROMPT.replace(
|
|
1258
|
+
/{prNumber}/g,
|
|
1259
|
+
String(target.prNumber),
|
|
1260
|
+
)
|
|
1261
|
+
.replace(/{title}/g, target.title)
|
|
1262
|
+
.replace(/{baseBranch}/g, target.baseBranch)
|
|
1263
|
+
.replace(/{mergeBaseSha}/g, mergeBase)
|
|
1264
|
+
}
|
|
1265
|
+
return PULL_REQUEST_PROMPT_FALLBACK.replace(
|
|
1266
|
+
/{prNumber}/g,
|
|
1267
|
+
String(target.prNumber),
|
|
1268
|
+
)
|
|
1269
|
+
.replace(/{title}/g, target.title)
|
|
1270
|
+
.replace(/{baseBranch}/g, target.baseBranch)
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
case 'folder':
|
|
1274
|
+
return FOLDER_REVIEW_PROMPT.replace('{paths}', target.paths.join(', '))
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
/**
|
|
1279
|
+
* Get user-facing hint for the review target
|
|
1280
|
+
*/
|
|
1281
|
+
function getUserFacingHint(target: ReviewTarget): string {
|
|
1282
|
+
switch (target.type) {
|
|
1283
|
+
case 'uncommitted':
|
|
1284
|
+
return 'current changes'
|
|
1285
|
+
case 'baseBranch':
|
|
1286
|
+
return `changes against '${target.branch}'`
|
|
1287
|
+
case 'ocrDelegate':
|
|
1288
|
+
return `ocr delegate review against '${target.branch}'`
|
|
1289
|
+
case 'commit': {
|
|
1290
|
+
const shortSha = target.sha.slice(0, 7)
|
|
1291
|
+
if (target.title) {
|
|
1292
|
+
return `commit ${shortSha}: ${target.title}`
|
|
1293
|
+
}
|
|
1294
|
+
return `commit ${shortSha}`
|
|
1295
|
+
}
|
|
1296
|
+
case 'custom': {
|
|
1297
|
+
if (target.instructions.length > 40) {
|
|
1298
|
+
return `${target.instructions.slice(0, 37)}...`
|
|
1299
|
+
}
|
|
1300
|
+
return target.instructions
|
|
1301
|
+
}
|
|
1302
|
+
case 'pullRequest': {
|
|
1303
|
+
let shortTitle: string
|
|
1304
|
+
if (target.title.length > 30) {
|
|
1305
|
+
shortTitle = `${target.title.slice(0, 27)}...`
|
|
1306
|
+
} else {
|
|
1307
|
+
shortTitle = target.title
|
|
1308
|
+
}
|
|
1309
|
+
return `PR #${target.prNumber}: ${shortTitle}`
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
case 'folder': {
|
|
1313
|
+
const joined = target.paths.join(', ')
|
|
1314
|
+
if (joined.length > 40) {
|
|
1315
|
+
return `folders: ${joined.slice(0, 37)}...`
|
|
1316
|
+
}
|
|
1317
|
+
return `folders: ${joined}`
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
|
|
1322
|
+
// Review preset options for the selector (keep this order stable)
|
|
1323
|
+
const REVIEW_PRESETS = [
|
|
1324
|
+
{
|
|
1325
|
+
value: 'uncommitted',
|
|
1326
|
+
label: 'Review uncommitted changes',
|
|
1327
|
+
description: '',
|
|
1328
|
+
},
|
|
1329
|
+
{
|
|
1330
|
+
value: 'baseBranch',
|
|
1331
|
+
label: 'Review against a base branch',
|
|
1332
|
+
description: '(local)',
|
|
1333
|
+
},
|
|
1334
|
+
{ value: 'commit', label: 'Review a commit', description: '' },
|
|
1335
|
+
{
|
|
1336
|
+
value: 'pullRequest',
|
|
1337
|
+
label: 'Review a pull request',
|
|
1338
|
+
description: '(GitHub PR)',
|
|
1339
|
+
},
|
|
1340
|
+
{
|
|
1341
|
+
value: 'folder',
|
|
1342
|
+
label: 'Review a folder (or more)',
|
|
1343
|
+
description: '(snapshot, not diff)',
|
|
1344
|
+
},
|
|
1345
|
+
{ value: 'custom', label: 'Custom review instructions', description: '' },
|
|
1346
|
+
{
|
|
1347
|
+
value: 'ocrDelegate',
|
|
1348
|
+
label: 'Review with ocr delegate rules',
|
|
1349
|
+
description: '(agent applies ocr rules; no ocr LLM)',
|
|
1350
|
+
},
|
|
1351
|
+
] as const
|
|
1352
|
+
|
|
1353
|
+
/**
|
|
1354
|
+
* Sem (semantic code tools) review guidance for a target, or null when sem
|
|
1355
|
+
* tools are unavailable. Module scope so buildFullReviewPrompt can use it.
|
|
1356
|
+
*/
|
|
1357
|
+
async function buildSemReviewInstructions(
|
|
1358
|
+
pi: ExtensionAPI,
|
|
1359
|
+
target: ReviewTarget,
|
|
1360
|
+
): Promise<string | null> {
|
|
1361
|
+
const tools = getSemToolAvailability(pi.getActiveTools())
|
|
1362
|
+
if (!tools.any) return null
|
|
1363
|
+
|
|
1364
|
+
switch (target.type) {
|
|
1365
|
+
case 'baseBranch': {
|
|
1366
|
+
const mergeBase = await getMergeBase(execOf(pi), target.branch)
|
|
1367
|
+
return buildSemReviewGuidance(
|
|
1368
|
+
{ type: 'baseBranch', branch: target.branch, mergeBase },
|
|
1369
|
+
tools,
|
|
1370
|
+
)
|
|
1371
|
+
}
|
|
1372
|
+
case 'pullRequest': {
|
|
1373
|
+
const mergeBase = await getMergeBase(
|
|
1374
|
+
execOf(pi),
|
|
1375
|
+
target.baseBranch,
|
|
1376
|
+
target.worktree?.path,
|
|
1377
|
+
)
|
|
1378
|
+
return buildSemReviewGuidance(
|
|
1379
|
+
{
|
|
1380
|
+
type: 'pullRequest',
|
|
1381
|
+
prNumber: target.prNumber,
|
|
1382
|
+
baseBranch: target.baseBranch,
|
|
1383
|
+
title: target.title,
|
|
1384
|
+
mergeBase,
|
|
1385
|
+
},
|
|
1386
|
+
tools,
|
|
1387
|
+
)
|
|
1388
|
+
}
|
|
1389
|
+
default:
|
|
1390
|
+
return buildSemReviewGuidance(target, tools)
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
// AIDEV-NOTE: PMR-XTQQ — default writer probes per write; index.ts passes
|
|
1395
|
+
// the shared runServer-configured writer so the kill switch applies here too.
|
|
1396
|
+
export default function reviewExtension(
|
|
1397
|
+
pi: ExtensionAPI,
|
|
1398
|
+
writer: EventWriter = createEventWriter(
|
|
1399
|
+
getAgentDir(),
|
|
1400
|
+
createDaemonAliveProbe(getAgentDir()),
|
|
1401
|
+
),
|
|
1402
|
+
) {
|
|
1403
|
+
pi.on('session_start', (_event, ctx) => {
|
|
1404
|
+
applyReviewState(ctx)
|
|
1405
|
+
})
|
|
1406
|
+
|
|
1407
|
+
// AIDEV-NOTE: was 'session_switch' (no such event in current SDK); session_info_changed
|
|
1408
|
+
// is the closest post-switch signal and re-applies review state after a switch.
|
|
1409
|
+
pi.on('session_info_changed', (_event, ctx) => {
|
|
1410
|
+
applyReviewState(ctx)
|
|
1411
|
+
})
|
|
1412
|
+
|
|
1413
|
+
pi.on('session_tree', (_event, ctx) => {
|
|
1414
|
+
applyReviewState(ctx)
|
|
1415
|
+
})
|
|
1416
|
+
|
|
1417
|
+
/**
|
|
1418
|
+
* Determine the smart default review type based on git state
|
|
1419
|
+
*/
|
|
1420
|
+
async function getSmartDefault(): Promise<
|
|
1421
|
+
'uncommitted' | 'baseBranch' | 'commit'
|
|
1422
|
+
> {
|
|
1423
|
+
// Priority 1: If there are uncommitted changes, default to reviewing them
|
|
1424
|
+
if (await hasUncommittedChanges(pi)) {
|
|
1425
|
+
return 'uncommitted'
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
// Priority 2: If on a feature branch (not the default branch), default to PR-style review
|
|
1429
|
+
const currentBranch = await getCurrentBranch(pi)
|
|
1430
|
+
const defaultBranch = await getDefaultBranch(pi)
|
|
1431
|
+
if (currentBranch && currentBranch !== defaultBranch) {
|
|
1432
|
+
return 'baseBranch'
|
|
1433
|
+
}
|
|
1434
|
+
|
|
1435
|
+
// Priority 3: Default to reviewing a specific commit
|
|
1436
|
+
return 'commit'
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
/**
|
|
1440
|
+
* Show the review preset selector
|
|
1441
|
+
*/
|
|
1442
|
+
async function showReviewSelector(
|
|
1443
|
+
ctx: ExtensionContext,
|
|
1444
|
+
): Promise<ReviewTarget | null> {
|
|
1445
|
+
// Determine smart default (but keep the list order stable)
|
|
1446
|
+
const smartDefault = await getSmartDefault()
|
|
1447
|
+
const items: SelectItem[] = REVIEW_PRESETS.map((preset) => ({
|
|
1448
|
+
value: preset.value,
|
|
1449
|
+
label: preset.label,
|
|
1450
|
+
description: preset.description,
|
|
1451
|
+
}))
|
|
1452
|
+
const smartDefaultIndex = items.findIndex(
|
|
1453
|
+
(item) => item.value === smartDefault,
|
|
1454
|
+
)
|
|
1455
|
+
|
|
1456
|
+
while (true) {
|
|
1457
|
+
const result = await ctx.ui.custom<string | null>(
|
|
1458
|
+
(tui, theme, _kb, done) => {
|
|
1459
|
+
const container = new Container()
|
|
1460
|
+
container.addChild(
|
|
1461
|
+
new DynamicBorder((str) => theme.fg('accent', str)),
|
|
1462
|
+
)
|
|
1463
|
+
container.addChild(
|
|
1464
|
+
new Text(theme.fg('accent', theme.bold('Select a review preset'))),
|
|
1465
|
+
)
|
|
1466
|
+
|
|
1467
|
+
const selectList = new SelectList(items, Math.min(items.length, 10), {
|
|
1468
|
+
selectedPrefix: (text) => theme.fg('accent', text),
|
|
1469
|
+
selectedText: (text) => theme.fg('accent', text),
|
|
1470
|
+
description: (text) => theme.fg('muted', text),
|
|
1471
|
+
scrollInfo: (text) => theme.fg('dim', text),
|
|
1472
|
+
noMatch: (text) => theme.fg('warning', text),
|
|
1473
|
+
})
|
|
1474
|
+
|
|
1475
|
+
// Preselect the smart default without reordering the list
|
|
1476
|
+
if (smartDefaultIndex >= 0) {
|
|
1477
|
+
selectList.setSelectedIndex(smartDefaultIndex)
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1480
|
+
selectList.onSelect = (item) => done(item.value)
|
|
1481
|
+
selectList.onCancel = () => done(null)
|
|
1482
|
+
|
|
1483
|
+
container.addChild(selectList)
|
|
1484
|
+
container.addChild(
|
|
1485
|
+
new Text(
|
|
1486
|
+
theme.fg('dim', 'Press enter to confirm or esc to go back'),
|
|
1487
|
+
),
|
|
1488
|
+
)
|
|
1489
|
+
container.addChild(
|
|
1490
|
+
new DynamicBorder((str) => theme.fg('accent', str)),
|
|
1491
|
+
)
|
|
1492
|
+
|
|
1493
|
+
return {
|
|
1494
|
+
render(width: number) {
|
|
1495
|
+
return container.render(width)
|
|
1496
|
+
},
|
|
1497
|
+
invalidate() {
|
|
1498
|
+
container.invalidate()
|
|
1499
|
+
},
|
|
1500
|
+
handleInput(data: string) {
|
|
1501
|
+
selectList.handleInput(data)
|
|
1502
|
+
tui.requestRender()
|
|
1503
|
+
},
|
|
1504
|
+
}
|
|
1505
|
+
},
|
|
1506
|
+
)
|
|
1507
|
+
|
|
1508
|
+
if (!result) return null
|
|
1509
|
+
|
|
1510
|
+
// Handle each preset type
|
|
1511
|
+
switch (result) {
|
|
1512
|
+
case 'uncommitted':
|
|
1513
|
+
return { type: 'uncommitted' }
|
|
1514
|
+
|
|
1515
|
+
case 'baseBranch': {
|
|
1516
|
+
const target = await showBranchSelector(ctx)
|
|
1517
|
+
if (target) return target
|
|
1518
|
+
break
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
case 'commit': {
|
|
1522
|
+
const target = await showCommitSelector(ctx)
|
|
1523
|
+
if (target) return target
|
|
1524
|
+
break
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
case 'custom': {
|
|
1528
|
+
const target = await showCustomInput(ctx)
|
|
1529
|
+
if (target) return target
|
|
1530
|
+
break
|
|
1531
|
+
}
|
|
1532
|
+
|
|
1533
|
+
case 'ocrDelegate': {
|
|
1534
|
+
if (!(await commandExists(pi, 'ocr'))) {
|
|
1535
|
+
ctx.ui.notify(
|
|
1536
|
+
'ocr is not on PATH — delegate review unavailable.',
|
|
1537
|
+
'warning',
|
|
1538
|
+
)
|
|
1539
|
+
break
|
|
1540
|
+
}
|
|
1541
|
+
const base = await showBranchSelector(ctx)
|
|
1542
|
+
if (base && base.type === 'baseBranch') {
|
|
1543
|
+
return { type: 'ocrDelegate', branch: base.branch }
|
|
1544
|
+
}
|
|
1545
|
+
break
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
case 'folder': {
|
|
1549
|
+
const target = await showFolderInput(ctx)
|
|
1550
|
+
if (target) return target
|
|
1551
|
+
break
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
case 'pullRequest': {
|
|
1555
|
+
const target = await showPrInput(ctx)
|
|
1556
|
+
if (target) return target
|
|
1557
|
+
break
|
|
1558
|
+
}
|
|
1559
|
+
|
|
1560
|
+
default:
|
|
1561
|
+
return null
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
/**
|
|
1567
|
+
* Show branch selector for base branch review
|
|
1568
|
+
*/
|
|
1569
|
+
async function showBranchSelector(
|
|
1570
|
+
ctx: ExtensionContext,
|
|
1571
|
+
): Promise<ReviewTarget | null> {
|
|
1572
|
+
const branches = await getLocalBranches(pi)
|
|
1573
|
+
const currentBranch = await getCurrentBranch(pi)
|
|
1574
|
+
const defaultBranch = await getDefaultBranch(pi)
|
|
1575
|
+
|
|
1576
|
+
// Never offer the current branch as a base branch (reviewing against itself is meaningless).
|
|
1577
|
+
let candidateBranches: string[]
|
|
1578
|
+
if (currentBranch) {
|
|
1579
|
+
candidateBranches = branches.filter((b) => b !== currentBranch)
|
|
1580
|
+
} else {
|
|
1581
|
+
candidateBranches = branches
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
if (candidateBranches.length === 0) {
|
|
1585
|
+
let noBranchMsg: string
|
|
1586
|
+
if (currentBranch) {
|
|
1587
|
+
noBranchMsg = `No other branches found (current branch: ${currentBranch})`
|
|
1588
|
+
} else {
|
|
1589
|
+
noBranchMsg = 'No branches found'
|
|
1590
|
+
}
|
|
1591
|
+
ctx.ui.notify(noBranchMsg, 'error')
|
|
1592
|
+
return null
|
|
1593
|
+
}
|
|
1594
|
+
|
|
1595
|
+
// Sort branches with default branch first
|
|
1596
|
+
const sortedBranches = candidateBranches.sort((a, b) => {
|
|
1597
|
+
if (a === defaultBranch) return -1
|
|
1598
|
+
if (b === defaultBranch) return 1
|
|
1599
|
+
return a.localeCompare(b)
|
|
1600
|
+
})
|
|
1601
|
+
|
|
1602
|
+
const items: SelectItem[] = sortedBranches.map((branch) => {
|
|
1603
|
+
let description: string
|
|
1604
|
+
if (branch === defaultBranch) {
|
|
1605
|
+
description = '(default)'
|
|
1606
|
+
} else {
|
|
1607
|
+
description = ''
|
|
1608
|
+
}
|
|
1609
|
+
return { value: branch, label: branch, description }
|
|
1610
|
+
})
|
|
1611
|
+
|
|
1612
|
+
const result = await ctx.ui.custom<string | null>(
|
|
1613
|
+
(tui, theme, _kb, done) => {
|
|
1614
|
+
const container = new Container()
|
|
1615
|
+
container.addChild(new DynamicBorder((str) => theme.fg('accent', str)))
|
|
1616
|
+
container.addChild(
|
|
1617
|
+
new Text(theme.fg('accent', theme.bold('Select base branch'))),
|
|
1618
|
+
)
|
|
1619
|
+
|
|
1620
|
+
const selectList = new SelectList(items, Math.min(items.length, 10), {
|
|
1621
|
+
selectedPrefix: (text) => theme.fg('accent', text),
|
|
1622
|
+
selectedText: (text) => theme.fg('accent', text),
|
|
1623
|
+
description: (text) => theme.fg('muted', text),
|
|
1624
|
+
scrollInfo: (text) => theme.fg('dim', text),
|
|
1625
|
+
noMatch: (text) => theme.fg('warning', text),
|
|
1626
|
+
})
|
|
1627
|
+
|
|
1628
|
+
let searchQuery = ''
|
|
1629
|
+
selectList.onSelect = (item) => done(item.value)
|
|
1630
|
+
selectList.onCancel = () => done(null)
|
|
1631
|
+
|
|
1632
|
+
container.addChild(selectList)
|
|
1633
|
+
container.addChild(
|
|
1634
|
+
new Text(
|
|
1635
|
+
theme.fg('dim', 'Type to filter • enter to select • esc to cancel'),
|
|
1636
|
+
),
|
|
1637
|
+
)
|
|
1638
|
+
container.addChild(new DynamicBorder((str) => theme.fg('accent', str)))
|
|
1639
|
+
|
|
1640
|
+
return {
|
|
1641
|
+
render(width: number) {
|
|
1642
|
+
return container.render(width)
|
|
1643
|
+
},
|
|
1644
|
+
invalidate() {
|
|
1645
|
+
container.invalidate()
|
|
1646
|
+
},
|
|
1647
|
+
handleInput(data: string) {
|
|
1648
|
+
// Handle search filtering
|
|
1649
|
+
if (data.length === 1 && data >= ' ') {
|
|
1650
|
+
searchQuery += data
|
|
1651
|
+
selectList.setFilter(searchQuery)
|
|
1652
|
+
} else if (data === '\x7f' || data === '\b') {
|
|
1653
|
+
searchQuery = searchQuery.slice(0, -1)
|
|
1654
|
+
selectList.setFilter(searchQuery)
|
|
1655
|
+
} else {
|
|
1656
|
+
selectList.handleInput(data)
|
|
1657
|
+
}
|
|
1658
|
+
tui.requestRender()
|
|
1659
|
+
},
|
|
1660
|
+
}
|
|
1661
|
+
},
|
|
1662
|
+
)
|
|
1663
|
+
|
|
1664
|
+
if (!result) return null
|
|
1665
|
+
return { type: 'baseBranch', branch: result }
|
|
1666
|
+
}
|
|
1667
|
+
|
|
1668
|
+
/**
|
|
1669
|
+
* Show commit selector
|
|
1670
|
+
*/
|
|
1671
|
+
async function showCommitSelector(
|
|
1672
|
+
ctx: ExtensionContext,
|
|
1673
|
+
): Promise<ReviewTarget | null> {
|
|
1674
|
+
const commits = await getRecentCommits(pi, 20)
|
|
1675
|
+
|
|
1676
|
+
if (commits.length === 0) {
|
|
1677
|
+
ctx.ui.notify('No commits found', 'error')
|
|
1678
|
+
return null
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
const items: SelectItem[] = commits.map((commit) => ({
|
|
1682
|
+
value: commit.sha,
|
|
1683
|
+
label: `${commit.sha.slice(0, 7)} ${commit.title}`,
|
|
1684
|
+
description: '',
|
|
1685
|
+
}))
|
|
1686
|
+
|
|
1687
|
+
const result = await ctx.ui.custom<{ sha: string; title: string } | null>(
|
|
1688
|
+
(tui, theme, _kb, done) => {
|
|
1689
|
+
const container = new Container()
|
|
1690
|
+
container.addChild(new DynamicBorder((str) => theme.fg('accent', str)))
|
|
1691
|
+
container.addChild(
|
|
1692
|
+
new Text(theme.fg('accent', theme.bold('Select commit to review'))),
|
|
1693
|
+
)
|
|
1694
|
+
|
|
1695
|
+
const selectList = new SelectList(items, Math.min(items.length, 10), {
|
|
1696
|
+
selectedPrefix: (text) => theme.fg('accent', text),
|
|
1697
|
+
selectedText: (text) => theme.fg('accent', text),
|
|
1698
|
+
description: (text) => theme.fg('muted', text),
|
|
1699
|
+
scrollInfo: (text) => theme.fg('dim', text),
|
|
1700
|
+
noMatch: (text) => theme.fg('warning', text),
|
|
1701
|
+
})
|
|
1702
|
+
|
|
1703
|
+
let searchQuery = ''
|
|
1704
|
+
selectList.onSelect = (item) => {
|
|
1705
|
+
const commit = commits.find((c) => c.sha === item.value)
|
|
1706
|
+
if (commit) {
|
|
1707
|
+
done(commit)
|
|
1708
|
+
} else {
|
|
1709
|
+
done(null)
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
1712
|
+
selectList.onCancel = () => done(null)
|
|
1713
|
+
|
|
1714
|
+
container.addChild(selectList)
|
|
1715
|
+
container.addChild(
|
|
1716
|
+
new Text(
|
|
1717
|
+
theme.fg('dim', 'Type to filter • enter to select • esc to cancel'),
|
|
1718
|
+
),
|
|
1719
|
+
)
|
|
1720
|
+
container.addChild(new DynamicBorder((str) => theme.fg('accent', str)))
|
|
1721
|
+
|
|
1722
|
+
return {
|
|
1723
|
+
render(width: number) {
|
|
1724
|
+
return container.render(width)
|
|
1725
|
+
},
|
|
1726
|
+
invalidate() {
|
|
1727
|
+
container.invalidate()
|
|
1728
|
+
},
|
|
1729
|
+
handleInput(data: string) {
|
|
1730
|
+
// Handle search filtering
|
|
1731
|
+
if (data.length === 1 && data >= ' ') {
|
|
1732
|
+
searchQuery += data
|
|
1733
|
+
selectList.setFilter(searchQuery)
|
|
1734
|
+
} else if (data === '\x7f' || data === '\b') {
|
|
1735
|
+
searchQuery = searchQuery.slice(0, -1)
|
|
1736
|
+
selectList.setFilter(searchQuery)
|
|
1737
|
+
} else {
|
|
1738
|
+
selectList.handleInput(data)
|
|
1739
|
+
}
|
|
1740
|
+
tui.requestRender()
|
|
1741
|
+
},
|
|
1742
|
+
}
|
|
1743
|
+
},
|
|
1744
|
+
)
|
|
1745
|
+
|
|
1746
|
+
if (!result) return null
|
|
1747
|
+
return { type: 'commit', sha: result.sha, title: result.title }
|
|
1748
|
+
}
|
|
1749
|
+
|
|
1750
|
+
/**
|
|
1751
|
+
* Show custom instructions input
|
|
1752
|
+
*/
|
|
1753
|
+
async function showCustomInput(
|
|
1754
|
+
ctx: ExtensionContext,
|
|
1755
|
+
): Promise<ReviewTarget | null> {
|
|
1756
|
+
const result = await ctx.ui.editor(
|
|
1757
|
+
'Enter review instructions:',
|
|
1758
|
+
'Review the code for security vulnerabilities and potential bugs...',
|
|
1759
|
+
)
|
|
1760
|
+
|
|
1761
|
+
if (!result?.trim()) return null
|
|
1762
|
+
return { type: 'custom', instructions: result.trim() }
|
|
1763
|
+
}
|
|
1764
|
+
|
|
1765
|
+
function parseReviewPaths(value: string): string[] {
|
|
1766
|
+
return value
|
|
1767
|
+
.split(/\s+/)
|
|
1768
|
+
.map((item) => item.trim())
|
|
1769
|
+
.filter((item) => item.length > 0)
|
|
1770
|
+
}
|
|
1771
|
+
|
|
1772
|
+
/**
|
|
1773
|
+
* Show folder input
|
|
1774
|
+
*/
|
|
1775
|
+
async function showFolderInput(
|
|
1776
|
+
ctx: ExtensionContext,
|
|
1777
|
+
): Promise<ReviewTarget | null> {
|
|
1778
|
+
const result = await ctx.ui.editor(
|
|
1779
|
+
'Enter folders/files to review (space-separated or one per line):',
|
|
1780
|
+
'.',
|
|
1781
|
+
)
|
|
1782
|
+
|
|
1783
|
+
if (!result?.trim()) return null
|
|
1784
|
+
const paths = parseReviewPaths(result)
|
|
1785
|
+
if (paths.length === 0) return null
|
|
1786
|
+
|
|
1787
|
+
return { type: 'folder', paths }
|
|
1788
|
+
}
|
|
1789
|
+
|
|
1790
|
+
/**
|
|
1791
|
+
* Show PR input and handle checkout (delegates to handlePrCheckout)
|
|
1792
|
+
*/
|
|
1793
|
+
async function showPrInput(
|
|
1794
|
+
ctx: ExtensionContext,
|
|
1795
|
+
): Promise<ReviewTarget | null> {
|
|
1796
|
+
// Get PR reference from user
|
|
1797
|
+
const prRef = await ctx.ui.editor(
|
|
1798
|
+
'Enter PR number or URL (e.g. 123 or https://github.com/owner/repo/pull/123):',
|
|
1799
|
+
'',
|
|
1800
|
+
)
|
|
1801
|
+
|
|
1802
|
+
if (!prRef?.trim()) return null
|
|
1803
|
+
|
|
1804
|
+
return handlePrCheckout(ctx, prRef)
|
|
1805
|
+
}
|
|
1806
|
+
|
|
1807
|
+
// AIDEV-NOTE: subagent review path (pi-interactive-subagents). Preferred
|
|
1808
|
+
// whenever a supported mux is available: spawns the bundled 'reviewer' agent
|
|
1809
|
+
// (Opus, read+bash, auto-exit) in a mux pane — non-blocking, main session
|
|
1810
|
+
// untouched, findings steer back as a review_result message. The legacy
|
|
1811
|
+
// in-session/branch flow below only runs without a mux or on spawn failure.
|
|
1812
|
+
function deliverSubagentReviewResult(
|
|
1813
|
+
hint: string,
|
|
1814
|
+
result: SubagentResult,
|
|
1815
|
+
// AIDEV-NOTE: PMR-6EEW — when a pin is present the findings are only
|
|
1816
|
+
// surfaced as trustworthy after the echo contract + staleness check
|
|
1817
|
+
// against the pinned range. A mismatch/missing-echo/stale verdict is
|
|
1818
|
+
// delivered as failed: findings stay visible but flagged unverified.
|
|
1819
|
+
pin?: GateTarget | null,
|
|
1820
|
+
reviewCwd?: string,
|
|
1821
|
+
) {
|
|
1822
|
+
const failed = result.exitCode !== 0 || !!result.errorMessage
|
|
1823
|
+
void (async () => {
|
|
1824
|
+
let content: string
|
|
1825
|
+
let verificationFailed = false
|
|
1826
|
+
// AIDEV-NOTE: PMR-7TPN — every delivered review result states the
|
|
1827
|
+
// reviewed range and cwd so a wrong-range verdict is visible at a
|
|
1828
|
+
// glance. Pinned reviews state the exact verified base..head; legacy
|
|
1829
|
+
// (unpinned) reviews state the cwd and say the range is unverified.
|
|
1830
|
+
let rangeHeader: string
|
|
1831
|
+
if (failed) {
|
|
1832
|
+
rangeHeader = `Reviewed in: ${reviewCwd ?? 'the session checkout'}. The review did not complete; no range was reviewed.`
|
|
1833
|
+
content = `Code review failed (${hint}): ${result.errorMessage ?? `exit code ${result.exitCode}`}\n\n${rangeHeader}`
|
|
1834
|
+
} else if (pin !== null && pin !== undefined && reviewCwd !== undefined) {
|
|
1835
|
+
const verification = await verifyGateWithExec(
|
|
1836
|
+
execOf(pi),
|
|
1837
|
+
reviewCwd,
|
|
1838
|
+
pin,
|
|
1839
|
+
result.summary,
|
|
1840
|
+
)
|
|
1841
|
+
verificationFailed = !verification.ok
|
|
1842
|
+
if (verification.ok) {
|
|
1843
|
+
rangeHeader = pinnedRangeHeader(pin, reviewCwd)
|
|
1844
|
+
content = `Code review finished (${hint}). ${rangeHeader}\n\nReviewer findings:\n\n${result.summary}\n\nSession: ${result.sessionFile}`
|
|
1845
|
+
} else {
|
|
1846
|
+
rangeHeader = `Reviewed in: ${reviewCwd}. Range verification FAILED (${verification.status}): ${verification.reason}`
|
|
1847
|
+
content = `Code review finished (${hint}) but GATE INTEGRITY FAILED (${verification.status}) — ${verification.reason}.\n\n${rangeHeader}\n\nThe findings below were NOT verified against the pinned range; treat them as unverified and re-run /review.\n\n${result.summary}\n\nSession: ${result.sessionFile}`
|
|
1848
|
+
}
|
|
1849
|
+
} else {
|
|
1850
|
+
rangeHeader = legacyRangeHeader(reviewCwd)
|
|
1851
|
+
content = `Code review finished (${hint}). ${rangeHeader}\n\nReviewer findings:\n\n${result.summary}\n\nSession: ${result.sessionFile}`
|
|
1852
|
+
}
|
|
1853
|
+
pi.sendMessage(
|
|
1854
|
+
{
|
|
1855
|
+
customType: 'review_result',
|
|
1856
|
+
content,
|
|
1857
|
+
display: true,
|
|
1858
|
+
details: {
|
|
1859
|
+
hint,
|
|
1860
|
+
failed: failed || verificationFailed,
|
|
1861
|
+
sessionFile: result.sessionFile,
|
|
1862
|
+
},
|
|
1863
|
+
},
|
|
1864
|
+
{ triggerTurn: true, deliverAs: 'steer' },
|
|
1865
|
+
)
|
|
1866
|
+
})()
|
|
1867
|
+
}
|
|
1868
|
+
|
|
1869
|
+
// AIDEV-NOTE: worktree removal is refcounted. A PR review worktree may
|
|
1870
|
+
// host two async jobs (reviewer subagent + ocr scout); each calls
|
|
1871
|
+
// prWorktreeJobDone on completion and the last one out removes the
|
|
1872
|
+
// worktree + branch. Job count is set BEFORE spawning to close the
|
|
1873
|
+
// fast-finisher race.
|
|
1874
|
+
function prWorktreeJobDone(ctx: ExtensionContext, prNumber: number): void {
|
|
1875
|
+
const info = prWorktrees.get(prNumber)
|
|
1876
|
+
if (!info) return
|
|
1877
|
+
if (releasePrJob(info)) {
|
|
1878
|
+
void removePrWorktree(pi, ctx, prNumber, info)
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
// AIDEV-NOTE: ocr (OpenCodeReview) second opinion. When the `ocr` binary
|
|
1883
|
+
// exists, a scout subagent runs `ocr <args> --format json --output <tmpfile>`
|
|
1884
|
+
// in the review cwd (PR worktree for pullRequest, ctx.cwd otherwise) and
|
|
1885
|
+
// the JSON steers back as an ocr_result message. Pure runner — the scout
|
|
1886
|
+
// must not analyze, just return path + file contents.
|
|
1887
|
+
// Delegate mode is a separate picker preset (ocrDelegate target): the
|
|
1888
|
+
// reviewer subagent itself applies ocr's delegate preview/rule spec —
|
|
1889
|
+
// no ocr LLM config required.
|
|
1890
|
+
function deliverOcrResult(scope: string, result: SubagentResult) {
|
|
1891
|
+
const failed = result.exitCode !== 0 || !!result.errorMessage
|
|
1892
|
+
const content = failed
|
|
1893
|
+
? `ocr review failed (${scope}): ${result.errorMessage ?? `exit code ${result.exitCode}`}`
|
|
1894
|
+
: `ocr review finished (${scope}). Output:
|
|
1895
|
+
|
|
1896
|
+
${result.summary}`
|
|
1897
|
+
|
|
1898
|
+
pi.sendMessage(
|
|
1899
|
+
{
|
|
1900
|
+
customType: 'ocr_result',
|
|
1901
|
+
content,
|
|
1902
|
+
display: true,
|
|
1903
|
+
details: { scope, failed, sessionFile: result.sessionFile },
|
|
1904
|
+
},
|
|
1905
|
+
{ triggerTurn: true, deliverAs: 'steer' },
|
|
1906
|
+
)
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
async function startOcrReview(
|
|
1910
|
+
ctx: ExtensionContext,
|
|
1911
|
+
scope: string,
|
|
1912
|
+
ocrArgs: string[],
|
|
1913
|
+
reviewCwd: string,
|
|
1914
|
+
jobDone?: () => void,
|
|
1915
|
+
): Promise<boolean> {
|
|
1916
|
+
const task = [
|
|
1917
|
+
'Run an OpenCodeReview pass and return its JSON output. You are a pure command runner.',
|
|
1918
|
+
'Run exactly:',
|
|
1919
|
+
'f="$(mktemp -t ocr-review-XXXXXX.json)"',
|
|
1920
|
+
`ocr ${ocrArgs.join(' ')} --format json --output "$f"`,
|
|
1921
|
+
'cat "$f"',
|
|
1922
|
+
'If ocr fails, still return its full error output.',
|
|
1923
|
+
'Do NOT analyze, summarize, review, or fix anything. Do NOT explore the codebase.',
|
|
1924
|
+
'Your final message: the output file path on its first line, then the file contents verbatim.',
|
|
1925
|
+
].join('\n')
|
|
1926
|
+
|
|
1927
|
+
try {
|
|
1928
|
+
const running = await launchSubagent(
|
|
1929
|
+
{
|
|
1930
|
+
agent: 'scout',
|
|
1931
|
+
name: `ocr: ${scope}`,
|
|
1932
|
+
task,
|
|
1933
|
+
cwd: reviewCwd,
|
|
1934
|
+
},
|
|
1935
|
+
ctx,
|
|
1936
|
+
)
|
|
1937
|
+
|
|
1938
|
+
ctx.ui.notify(
|
|
1939
|
+
`ocr review (${scope}) running in a scout pane — output arrives here when done.`,
|
|
1940
|
+
'info',
|
|
1941
|
+
)
|
|
1942
|
+
|
|
1943
|
+
watchSubagent(running, new AbortController().signal)
|
|
1944
|
+
.then((result) => {
|
|
1945
|
+
deliverOcrResult(scope, result)
|
|
1946
|
+
if (jobDone) jobDone()
|
|
1947
|
+
})
|
|
1948
|
+
.catch((err) => {
|
|
1949
|
+
const message = err instanceof Error ? err.message : String(err)
|
|
1950
|
+
deliverOcrResult(scope, {
|
|
1951
|
+
name: `ocr: ${scope}`,
|
|
1952
|
+
task,
|
|
1953
|
+
summary: `Watcher error: ${message}`,
|
|
1954
|
+
sessionFile: undefined,
|
|
1955
|
+
exitCode: 1,
|
|
1956
|
+
elapsed: 0,
|
|
1957
|
+
errorMessage: message,
|
|
1958
|
+
})
|
|
1959
|
+
if (jobDone) jobDone()
|
|
1960
|
+
})
|
|
1961
|
+
return true
|
|
1962
|
+
} catch (err) {
|
|
1963
|
+
const message = err instanceof Error ? err.message : String(err)
|
|
1964
|
+
ctx.ui.notify(
|
|
1965
|
+
`ocr scout spawn failed (${message}). Continuing without ocr.`,
|
|
1966
|
+
'warning',
|
|
1967
|
+
)
|
|
1968
|
+
return false
|
|
1969
|
+
}
|
|
1970
|
+
}
|
|
1971
|
+
|
|
1972
|
+
/**
|
|
1973
|
+
* AIDEV-NOTE: spawn status distinguishes 'aborted' (PR worktree spawn
|
|
1974
|
+
* failure — worktree job already released inside) from 'failed' (no
|
|
1975
|
+
* worktree; the command falls back to in-session review, the tool reports
|
|
1976
|
+
* an error).
|
|
1977
|
+
*/
|
|
1978
|
+
async function startSubagentReview(
|
|
1979
|
+
ctx: ExtensionContext,
|
|
1980
|
+
fullPrompt: string,
|
|
1981
|
+
hint: string,
|
|
1982
|
+
reviewCwd?: string,
|
|
1983
|
+
worktree?: { prNumber: number; info: PrWorktreeInfo },
|
|
1984
|
+
pin?: GateTarget | null,
|
|
1985
|
+
): Promise<'spawned' | 'aborted' | 'failed'> {
|
|
1986
|
+
try {
|
|
1987
|
+
const running = await launchSubagent(
|
|
1988
|
+
{
|
|
1989
|
+
agent: 'reviewer',
|
|
1990
|
+
name: `Review: ${hint}`,
|
|
1991
|
+
task: fullPrompt,
|
|
1992
|
+
cwd: reviewCwd ?? ctx.cwd,
|
|
1993
|
+
},
|
|
1994
|
+
ctx,
|
|
1995
|
+
)
|
|
1996
|
+
|
|
1997
|
+
ctx.ui.notify(
|
|
1998
|
+
`Review "${hint}" running in a subagent pane — findings arrive here when done.`,
|
|
1999
|
+
'info',
|
|
2000
|
+
)
|
|
2001
|
+
|
|
2002
|
+
const adhocRun = adhocBeginWorker('review', hint)
|
|
2003
|
+
watchSubagent(running, new AbortController().signal)
|
|
2004
|
+
.then((result) => {
|
|
2005
|
+
adhocAddWorker(adhocRun, {
|
|
2006
|
+
sessionFile: result.sessionFile ?? '',
|
|
2007
|
+
role: 'review',
|
|
2008
|
+
})
|
|
2009
|
+
void adhocFinish(adhocRun)
|
|
2010
|
+
deliverSubagentReviewResult(hint, result, pin, reviewCwd ?? ctx.cwd)
|
|
2011
|
+
if (worktree) prWorktreeJobDone(ctx, worktree.prNumber)
|
|
2012
|
+
})
|
|
2013
|
+
.catch((err) => {
|
|
2014
|
+
void adhocFinish(adhocRun)
|
|
2015
|
+
const message = err instanceof Error ? err.message : String(err)
|
|
2016
|
+
deliverSubagentReviewResult(hint, {
|
|
2017
|
+
name: `Review: ${hint}`,
|
|
2018
|
+
task: fullPrompt,
|
|
2019
|
+
summary: `Watcher error: ${message}`,
|
|
2020
|
+
sessionFile: undefined,
|
|
2021
|
+
exitCode: 1,
|
|
2022
|
+
elapsed: 0,
|
|
2023
|
+
errorMessage: message,
|
|
2024
|
+
})
|
|
2025
|
+
if (worktree) prWorktreeJobDone(ctx, worktree.prNumber)
|
|
2026
|
+
})
|
|
2027
|
+
return 'spawned'
|
|
2028
|
+
} catch (err) {
|
|
2029
|
+
const message = err instanceof Error ? err.message : String(err)
|
|
2030
|
+
// With a PR worktree the legacy in-session fallback would review the
|
|
2031
|
+
// wrong tree (main checkout, not the PR) — count the failed job, which
|
|
2032
|
+
// also removes the worktree if no other job holds it, and abort.
|
|
2033
|
+
if (worktree) {
|
|
2034
|
+
// Reviewer spawn failed and aborted the PR review. The worktree job
|
|
2035
|
+
// is released by the caller (spawnReviewJobs) so the ocr reservation
|
|
2036
|
+
// is cleaned up in one place.
|
|
2037
|
+
ctx.ui.notify(
|
|
2038
|
+
`Subagent spawn failed (${message}). PR review aborted — the worktree is removed when remaining jobs finish; retry with /review pr.`,
|
|
2039
|
+
'error',
|
|
2040
|
+
)
|
|
2041
|
+
return 'aborted'
|
|
2042
|
+
}
|
|
2043
|
+
ctx.ui.notify(
|
|
2044
|
+
`Subagent review unavailable (${message}). Falling back to in-session review.`,
|
|
2045
|
+
'warning',
|
|
2046
|
+
)
|
|
2047
|
+
return 'failed'
|
|
2048
|
+
}
|
|
2049
|
+
}
|
|
2050
|
+
|
|
2051
|
+
/**
|
|
2052
|
+
* Spawn the reviewer subagent (and the ocr scout when the binary exists)
|
|
2053
|
+
* for a review target. Shared by the /review command and the agent-callable
|
|
2054
|
+
* `review` tool — one implementation.
|
|
2055
|
+
*
|
|
2056
|
+
* AIDEV-NOTE: fire-and-steer — spawns and returns; findings keep arriving
|
|
2057
|
+
* later as review_result / ocr_result steer messages via pi.sendMessage.
|
|
2058
|
+
* The PR worktree refcount is reserved (pending = 2) BEFORE either job
|
|
2059
|
+
* spawns so a fast reviewer can't tear the worktree out from under ocr.
|
|
2060
|
+
*/
|
|
2061
|
+
async function spawnReviewJobs(
|
|
2062
|
+
ctx: ExtensionContext,
|
|
2063
|
+
target: ReviewTarget,
|
|
2064
|
+
fullPrompt: string,
|
|
2065
|
+
// AIDEV-NOTE: PMR-1CCT — review cwd override (flow worktree). All diff
|
|
2066
|
+
// resolution (merge-base, ocr range, subagent cwd) must happen in the
|
|
2067
|
+
// tree that carries the change, not the session checkout.
|
|
2068
|
+
cwdOverride?: string,
|
|
2069
|
+
): Promise<{
|
|
2070
|
+
status: 'spawned' | 'aborted' | 'failed'
|
|
2071
|
+
ocrStarted: boolean
|
|
2072
|
+
}> {
|
|
2073
|
+
// AIDEV-NOTE: no-mux gate — main's executeReview only entered the spawn
|
|
2074
|
+
// path behind canSpawnReviewSubagent(). launchSubagent writes a durable 'starting'
|
|
2075
|
+
// assignment record BEFORE it throws outside herdr, and its throw path
|
|
2076
|
+
// does not clean that record — so calling it without a mux leaks durable
|
|
2077
|
+
// state per invocation. Fail soft to the legacy in-session path instead.
|
|
2078
|
+
if (!canSpawnReviewSubagent()) {
|
|
2079
|
+
return { status: 'failed', ocrStarted: false }
|
|
2080
|
+
}
|
|
2081
|
+
const prWorktree =
|
|
2082
|
+
target.type === 'pullRequest' && target.worktree
|
|
2083
|
+
? { prNumber: target.prNumber, info: target.worktree }
|
|
2084
|
+
: undefined
|
|
2085
|
+
let reviewCwd: string | undefined
|
|
2086
|
+
if (target.type === 'pullRequest') {
|
|
2087
|
+
reviewCwd = target.worktree?.path
|
|
2088
|
+
} else {
|
|
2089
|
+
reviewCwd = cwdOverride
|
|
2090
|
+
}
|
|
2091
|
+
// Reserve both worktree jobs up front (reviewer + ocr scout) so a
|
|
2092
|
+
// fast-finishing reviewer can't tear the worktree out from under ocr.
|
|
2093
|
+
if (prWorktree) reservePrJobs(prWorktree.info)
|
|
2094
|
+
|
|
2095
|
+
// AIDEV-NOTE: PMR-6EEW — pin at spawn. The reviewer prompt gets the
|
|
2096
|
+
// pinned range + echo contract; the delivery path verifies the echo and
|
|
2097
|
+
// re-resolves HEAD before the findings are surfaced as trustworthy.
|
|
2098
|
+
const pin = await buildReviewGatePin(
|
|
2099
|
+
execOf(pi),
|
|
2100
|
+
target,
|
|
2101
|
+
reviewCwd ?? ctx.cwd,
|
|
2102
|
+
)
|
|
2103
|
+
const pinnedPrompt =
|
|
2104
|
+
pin !== null ? `${fullPrompt}${reviewEchoSection(pin)}` : fullPrompt
|
|
2105
|
+
|
|
2106
|
+
// AIDEV-NOTE: PMR-6EEW per-subtask ranges + /review journaling — when a
|
|
2107
|
+
// flow is active, journal the pinned range and its subtask → commits
|
|
2108
|
+
// attribution (Subtask: trailers). Best-effort: journal failures never
|
|
2109
|
+
// break the review. No active flow (e.g. manual `/review PR N`) = no
|
|
2110
|
+
// journaling; that path is untouched.
|
|
2111
|
+
const activeRef = getActiveFlowRef()
|
|
2112
|
+
if (pin !== null && activeRef !== null) {
|
|
2113
|
+
try {
|
|
2114
|
+
await writer.record({
|
|
2115
|
+
kind: 'gate-target',
|
|
2116
|
+
at: new Date().toISOString(),
|
|
2117
|
+
ref: activeRef,
|
|
2118
|
+
gate: 'review',
|
|
2119
|
+
targetId: gateTargetId(pin),
|
|
2120
|
+
baseSha: pin.baseSha,
|
|
2121
|
+
headSha: pin.headSha,
|
|
2122
|
+
diffSha256: pin.diffSha256,
|
|
2123
|
+
})
|
|
2124
|
+
const attribution = await deriveSubtaskAttribution(
|
|
2125
|
+
execOf(pi),
|
|
2126
|
+
reviewCwd ?? ctx.cwd,
|
|
2127
|
+
pin.baseSha,
|
|
2128
|
+
pin.headSha,
|
|
2129
|
+
)
|
|
2130
|
+
if (attribution.ok) {
|
|
2131
|
+
await writer.record({
|
|
2132
|
+
kind: 'subtask-ranges',
|
|
2133
|
+
at: new Date().toISOString(),
|
|
2134
|
+
ref: activeRef,
|
|
2135
|
+
gate: 'review',
|
|
2136
|
+
baseSha: pin.baseSha,
|
|
2137
|
+
headSha: pin.headSha,
|
|
2138
|
+
bySubtask: attribution.attribution.bySubtask,
|
|
2139
|
+
unattributed: attribution.attribution.unattributed,
|
|
2140
|
+
})
|
|
2141
|
+
}
|
|
2142
|
+
} catch {
|
|
2143
|
+
// best-effort — the review itself is unaffected
|
|
2144
|
+
}
|
|
2145
|
+
}
|
|
2146
|
+
|
|
2147
|
+
const status = await startSubagentReview(
|
|
2148
|
+
ctx,
|
|
2149
|
+
pinnedPrompt,
|
|
2150
|
+
getUserFacingHint(target),
|
|
2151
|
+
reviewCwd,
|
|
2152
|
+
prWorktree,
|
|
2153
|
+
pin,
|
|
2154
|
+
)
|
|
2155
|
+
|
|
2156
|
+
// AIDEV-NOTE: on 'aborted' the reviewer slot is released here (the
|
|
2157
|
+
// release stayed out of startSubagentReview so it happens in exactly one
|
|
2158
|
+
// place), then the ocr attempt below still runs — same as the original
|
|
2159
|
+
// executeReview flow, where a failed reviewer spawn did not cancel ocr.
|
|
2160
|
+
// Both slots are released either by ocr's jobDone or by the !ocrSpawned
|
|
2161
|
+
// release at the end, so pending reaches 0 and the worktree cleans up.
|
|
2162
|
+
if (status === 'aborted' && prWorktree) {
|
|
2163
|
+
prWorktreeJobDone(ctx, prWorktree.prNumber)
|
|
2164
|
+
}
|
|
2165
|
+
if (status === 'failed') {
|
|
2166
|
+
return { status, ocrStarted: false }
|
|
2167
|
+
}
|
|
2168
|
+
|
|
2169
|
+
// AIDEV-NOTE: ocr second opinion — scout runs ocr in the review cwd
|
|
2170
|
+
// when the binary exists; skips silently otherwise. Target mapping:
|
|
2171
|
+
// pullRequest → review --from <base> --to <worktree branch> (worktree),
|
|
2172
|
+
// baseBranch → review --from <merge-base> --to HEAD,
|
|
2173
|
+
// uncommitted → review (workspace mode),
|
|
2174
|
+
// commit → review --commit <sha>,
|
|
2175
|
+
// folder → scan --path <paths> (no diff).
|
|
2176
|
+
// ocrDelegate is excluded — the reviewer itself applies the ocr rules.
|
|
2177
|
+
// custom is excluded — no diff equivalent.
|
|
2178
|
+
let ocrSpawned = false
|
|
2179
|
+
// AIDEV-NOTE: PMR-C6AK — skip the scout during a personal-mode flow:
|
|
2180
|
+
// the code_review human gate is the second opinion there. Manual /review
|
|
2181
|
+
// without an active flow, and work-mode flows, keep ocr.
|
|
2182
|
+
let skipScout = false
|
|
2183
|
+
if (getActiveFlowRef() !== null) {
|
|
2184
|
+
const mode = await resolveMode(pi, ctx.cwd)
|
|
2185
|
+
skipScout = skipOcrScout(getActiveFlowRef(), mode)
|
|
2186
|
+
}
|
|
2187
|
+
if (!skipScout && (await commandExists(pi, 'ocr'))) {
|
|
2188
|
+
let scope: string | null = null
|
|
2189
|
+
let ocrArgs: string[] = []
|
|
2190
|
+
if (target.type === 'pullRequest') {
|
|
2191
|
+
const toRef = prWorktree ? prWorktree.info.branch : 'HEAD'
|
|
2192
|
+
scope = `PR #${target.prNumber}`
|
|
2193
|
+
ocrArgs = ['review', '--from', target.baseBranch, '--to', toRef]
|
|
2194
|
+
} else if (target.type === 'baseBranch') {
|
|
2195
|
+
const mergeBase = await getMergeBase(
|
|
2196
|
+
execOf(pi),
|
|
2197
|
+
target.branch,
|
|
2198
|
+
reviewCwd ?? ctx.cwd,
|
|
2199
|
+
)
|
|
2200
|
+
if (mergeBase) {
|
|
2201
|
+
scope = `${target.branch}...HEAD`
|
|
2202
|
+
ocrArgs = ['review', '--from', mergeBase, '--to', 'HEAD']
|
|
2203
|
+
}
|
|
2204
|
+
} else if (target.type === 'uncommitted') {
|
|
2205
|
+
scope = 'uncommitted'
|
|
2206
|
+
ocrArgs = ['review']
|
|
2207
|
+
} else if (target.type === 'commit') {
|
|
2208
|
+
scope = `commit ${target.sha.slice(0, 7)}`
|
|
2209
|
+
ocrArgs = ['review', '--commit', target.sha]
|
|
2210
|
+
} else if (target.type === 'folder') {
|
|
2211
|
+
scope = `scan: ${target.paths.join(', ')}`
|
|
2212
|
+
ocrArgs = ['scan', '--path', target.paths.join(',')]
|
|
2213
|
+
}
|
|
2214
|
+
if (scope && ocrArgs.length > 0) {
|
|
2215
|
+
let jobDone: (() => void) | undefined
|
|
2216
|
+
if (target.type === 'pullRequest') {
|
|
2217
|
+
const prNumber = target.prNumber
|
|
2218
|
+
jobDone = () => prWorktreeJobDone(ctx, prNumber)
|
|
2219
|
+
}
|
|
2220
|
+
ocrSpawned = await startOcrReview(
|
|
2221
|
+
ctx,
|
|
2222
|
+
scope,
|
|
2223
|
+
ocrArgs,
|
|
2224
|
+
reviewCwd ?? ctx.cwd,
|
|
2225
|
+
jobDone,
|
|
2226
|
+
)
|
|
2227
|
+
}
|
|
2228
|
+
}
|
|
2229
|
+
if (prWorktree && !ocrSpawned) {
|
|
2230
|
+
prWorktreeJobDone(ctx, prWorktree.prNumber)
|
|
2231
|
+
}
|
|
2232
|
+
return { status, ocrStarted: ocrSpawned }
|
|
2233
|
+
}
|
|
2234
|
+
|
|
2235
|
+
/**
|
|
2236
|
+
* Execute the review
|
|
2237
|
+
*/
|
|
2238
|
+
async function executeReview(
|
|
2239
|
+
ctx: ExtensionCommandContext,
|
|
2240
|
+
target: ReviewTarget,
|
|
2241
|
+
useFreshSession: boolean,
|
|
2242
|
+
): Promise<void> {
|
|
2243
|
+
// AIDEV-NOTE: PMR-1CCT — same empty-range guard as the review tool: an
|
|
2244
|
+
// interactive branch review against HEAD's own merge base diffs nothing.
|
|
2245
|
+
if (
|
|
2246
|
+
target.type === 'baseBranch' &&
|
|
2247
|
+
(await isEmptyBranchRange(pi, target.branch, ctx.cwd))
|
|
2248
|
+
) {
|
|
2249
|
+
ctx.ui.notify(
|
|
2250
|
+
`Empty review range: HEAD == merge-base with '${target.branch}' in ${ctx.cwd} — nothing to review here. Run /review from the checkout carrying the change.`,
|
|
2251
|
+
'error',
|
|
2252
|
+
)
|
|
2253
|
+
return
|
|
2254
|
+
}
|
|
2255
|
+
// AIDEV-NOTE: PMR-3P3T — the human /review commit path resolves the
|
|
2256
|
+
// same VERIFIED flow-worktree seam as the review tool (PMR-0KMQ).
|
|
2257
|
+
// Without it, a commit review started from a main-checkout-rooted
|
|
2258
|
+
// session pinned and re-checked HEAD against main and reported the
|
|
2259
|
+
// misleading 'stale' verdict PMR-0KMQ eliminated for the tool path.
|
|
2260
|
+
// Fail closed with the tool path's wording on a checkout mismatch;
|
|
2261
|
+
// shas off the flow branch keep the session checkout.
|
|
2262
|
+
let cwdOverride: string | undefined
|
|
2263
|
+
if (target.type === 'commit' && getActiveFlowRef() !== null) {
|
|
2264
|
+
const commitCwd = await resolveCommitReviewCwd(pi, ctx.cwd, target.sha)
|
|
2265
|
+
if (!commitCwd.ok) {
|
|
2266
|
+
ctx.ui.notify(
|
|
2267
|
+
`Review refused: checkout mismatch — ${commitCwd.reason}. Pinning commit ${target.sha} from ${ctx.cwd} would re-check HEAD against the wrong checkout and report a misleading 'stale' verdict. Fix or re-bind the flow worktree (run /flow <ref> to resume so the flow loop session holds the worktree context), then re-run the review.`,
|
|
2268
|
+
'error',
|
|
2269
|
+
)
|
|
2270
|
+
return
|
|
2271
|
+
}
|
|
2272
|
+
cwdOverride = commitCwd.cwd
|
|
2273
|
+
}
|
|
2274
|
+
// AIDEV-NOTE: PMR-7TPN — warn when the review runs from a checkout with
|
|
2275
|
+
// no active flow while linked flow worktrees exist elsewhere.
|
|
2276
|
+
if (
|
|
2277
|
+
(target.type === 'baseBranch' || target.type === 'uncommitted') &&
|
|
2278
|
+
getActiveFlowRef() === null &&
|
|
2279
|
+
getFlowWorktree() === null
|
|
2280
|
+
) {
|
|
2281
|
+
const warn = await unboundWorktreeWarningFor(pi, ctx.cwd)
|
|
2282
|
+
if (warn !== null) ctx.ui.notify(warn, 'info')
|
|
2283
|
+
}
|
|
2284
|
+
const fullPrompt = await buildFullReviewPrompt(
|
|
2285
|
+
pi,
|
|
2286
|
+
target,
|
|
2287
|
+
cwdOverride ?? ctx.cwd,
|
|
2288
|
+
)
|
|
2289
|
+
const hint = getUserFacingHint(target)
|
|
2290
|
+
|
|
2291
|
+
// Subagent path — preferred whenever a mux is available. Runs before the
|
|
2292
|
+
// branch machinery so a mux present means no session-tree branch is created.
|
|
2293
|
+
const spawned = await spawnReviewJobs(ctx, target, fullPrompt, cwdOverride)
|
|
2294
|
+
if (spawned.status !== 'failed') {
|
|
2295
|
+
return
|
|
2296
|
+
}
|
|
2297
|
+
|
|
2298
|
+
// Legacy in-session path (no mux, or subagent spawn failed)
|
|
2299
|
+
if (reviewOriginId) {
|
|
2300
|
+
ctx.ui.notify(
|
|
2301
|
+
'Already in a review. Use /end-review to finish first.',
|
|
2302
|
+
'warning',
|
|
2303
|
+
)
|
|
2304
|
+
return
|
|
2305
|
+
}
|
|
2306
|
+
|
|
2307
|
+
if (useFreshSession) {
|
|
2308
|
+
// Store current position (where we'll return to)
|
|
2309
|
+
const originId = ctx.sessionManager.getLeafId() ?? undefined
|
|
2310
|
+
if (!originId) {
|
|
2311
|
+
ctx.ui.notify(
|
|
2312
|
+
'Failed to determine review origin. Try again from a session with messages.',
|
|
2313
|
+
'error',
|
|
2314
|
+
)
|
|
2315
|
+
return
|
|
2316
|
+
}
|
|
2317
|
+
reviewOriginId = originId
|
|
2318
|
+
|
|
2319
|
+
// Keep a local copy so session_tree events during navigation don't wipe it
|
|
2320
|
+
const lockedOriginId = originId
|
|
2321
|
+
|
|
2322
|
+
// Find the first user message in the session
|
|
2323
|
+
const entries = ctx.sessionManager.getEntries()
|
|
2324
|
+
const firstUserMessage = entries.find(
|
|
2325
|
+
(e) => e.type === 'message' && e.message.role === 'user',
|
|
2326
|
+
)
|
|
2327
|
+
|
|
2328
|
+
if (!firstUserMessage) {
|
|
2329
|
+
ctx.ui.notify('No user message found in session', 'error')
|
|
2330
|
+
reviewOriginId = undefined
|
|
2331
|
+
return
|
|
2332
|
+
}
|
|
2333
|
+
|
|
2334
|
+
// Navigate to first user message to create a new branch from that point
|
|
2335
|
+
// Label it as "code-review" so it's visible in the tree
|
|
2336
|
+
try {
|
|
2337
|
+
const result = await ctx.navigateTree(firstUserMessage.id, {
|
|
2338
|
+
summarize: false,
|
|
2339
|
+
label: 'code-review',
|
|
2340
|
+
})
|
|
2341
|
+
if (result.cancelled) {
|
|
2342
|
+
reviewOriginId = undefined
|
|
2343
|
+
return
|
|
2344
|
+
}
|
|
2345
|
+
} catch (error) {
|
|
2346
|
+
// Clean up state if navigation fails
|
|
2347
|
+
reviewOriginId = undefined
|
|
2348
|
+
let errMsg: string
|
|
2349
|
+
if (error instanceof Error) {
|
|
2350
|
+
errMsg = error.message
|
|
2351
|
+
} else {
|
|
2352
|
+
errMsg = String(error)
|
|
2353
|
+
}
|
|
2354
|
+
ctx.ui.notify(`Failed to start review: ${errMsg}`, 'error')
|
|
2355
|
+
return
|
|
2356
|
+
}
|
|
2357
|
+
|
|
2358
|
+
// Restore origin after navigation events (session_tree can reset it)
|
|
2359
|
+
reviewOriginId = lockedOriginId
|
|
2360
|
+
|
|
2361
|
+
// Clear the editor (navigating to user message fills it with the message text)
|
|
2362
|
+
ctx.ui.setEditorText('')
|
|
2363
|
+
|
|
2364
|
+
// Show widget indicating review is active
|
|
2365
|
+
setReviewWidget(ctx, true)
|
|
2366
|
+
|
|
2367
|
+
// Persist review state so tree navigation can restore/reset it
|
|
2368
|
+
pi.appendEntry(REVIEW_STATE_TYPE, {
|
|
2369
|
+
active: true,
|
|
2370
|
+
originId: lockedOriginId,
|
|
2371
|
+
})
|
|
2372
|
+
}
|
|
2373
|
+
|
|
2374
|
+
let modeHint: string
|
|
2375
|
+
if (useFreshSession) {
|
|
2376
|
+
modeHint = ' (fresh session)'
|
|
2377
|
+
} else {
|
|
2378
|
+
modeHint = ''
|
|
2379
|
+
}
|
|
2380
|
+
ctx.ui.notify(`Starting review: ${hint}${modeHint}`, 'info')
|
|
2381
|
+
|
|
2382
|
+
// Send as a user message that triggers a turn
|
|
2383
|
+
pi.sendUserMessage(fullPrompt)
|
|
2384
|
+
}
|
|
2385
|
+
|
|
2386
|
+
/**
|
|
2387
|
+
* Parse command arguments for direct invocation
|
|
2388
|
+
* Returns the target or a special marker for PR that needs async handling
|
|
2389
|
+
*/
|
|
2390
|
+
function parseArgs(
|
|
2391
|
+
args: string | undefined,
|
|
2392
|
+
): ReviewTarget | { type: 'pr'; ref: string } | null {
|
|
2393
|
+
if (!args?.trim()) return null
|
|
2394
|
+
|
|
2395
|
+
const parts = args.trim().split(/\s+/)
|
|
2396
|
+
const subcommand = parts[0]?.toLowerCase()
|
|
2397
|
+
|
|
2398
|
+
switch (subcommand) {
|
|
2399
|
+
case 'uncommitted':
|
|
2400
|
+
return { type: 'uncommitted' }
|
|
2401
|
+
|
|
2402
|
+
case 'branch': {
|
|
2403
|
+
const branch = parts[1]
|
|
2404
|
+
if (!branch) return null
|
|
2405
|
+
return { type: 'baseBranch', branch }
|
|
2406
|
+
}
|
|
2407
|
+
|
|
2408
|
+
case 'commit': {
|
|
2409
|
+
const sha = parts[1]
|
|
2410
|
+
if (!sha) return null
|
|
2411
|
+
const title = parts.slice(2).join(' ') || undefined
|
|
2412
|
+
return { type: 'commit', sha, title }
|
|
2413
|
+
}
|
|
2414
|
+
|
|
2415
|
+
case 'custom': {
|
|
2416
|
+
const instructions = parts.slice(1).join(' ')
|
|
2417
|
+
if (!instructions) return null
|
|
2418
|
+
return { type: 'custom', instructions }
|
|
2419
|
+
}
|
|
2420
|
+
|
|
2421
|
+
case 'folder': {
|
|
2422
|
+
const paths = parseReviewPaths(parts.slice(1).join(' '))
|
|
2423
|
+
if (paths.length === 0) return null
|
|
2424
|
+
return { type: 'folder', paths }
|
|
2425
|
+
}
|
|
2426
|
+
|
|
2427
|
+
case 'pr': {
|
|
2428
|
+
const ref = parts[1]
|
|
2429
|
+
if (!ref) return null
|
|
2430
|
+
return { type: 'pr', ref }
|
|
2431
|
+
}
|
|
2432
|
+
|
|
2433
|
+
default:
|
|
2434
|
+
return null
|
|
2435
|
+
}
|
|
2436
|
+
}
|
|
2437
|
+
|
|
2438
|
+
/**
|
|
2439
|
+
* Handle PR checkout and return a ReviewTarget (or null on failure).
|
|
2440
|
+
*
|
|
2441
|
+
* AIDEV-NOTE: worktree-first when Herdr + mux are available — the PR is
|
|
2442
|
+
* fetched into a dedicated review/pr-<n> worktree and the reviewer runs
|
|
2443
|
+
* there; the main checkout stays untouched (no clean-tree requirement).
|
|
2444
|
+
* Fallback (no mux / no Herdr / worktree failure) is the legacy in-place
|
|
2445
|
+
* `gh pr checkout`, which needs a clean tree.
|
|
2446
|
+
*/
|
|
2447
|
+
async function handlePrCheckout(
|
|
2448
|
+
ctx: ExtensionContext,
|
|
2449
|
+
ref: string,
|
|
2450
|
+
): Promise<ReviewTarget | null> {
|
|
2451
|
+
const prNumber = parsePrReference(ref)
|
|
2452
|
+
if (!prNumber) {
|
|
2453
|
+
ctx.ui.notify(
|
|
2454
|
+
'Invalid PR reference. Enter a number or GitHub PR URL.',
|
|
2455
|
+
'error',
|
|
2456
|
+
)
|
|
2457
|
+
return null
|
|
2458
|
+
}
|
|
2459
|
+
|
|
2460
|
+
// Get PR info
|
|
2461
|
+
ctx.ui.notify(`Fetching PR #${prNumber} info...`, 'info')
|
|
2462
|
+
const prInfo = await getPrInfo(pi, prNumber)
|
|
2463
|
+
|
|
2464
|
+
if (!prInfo) {
|
|
2465
|
+
ctx.ui.notify(
|
|
2466
|
+
`Could not find PR #${prNumber}. Make sure gh is authenticated and the PR exists.`,
|
|
2467
|
+
'error',
|
|
2468
|
+
)
|
|
2469
|
+
return null
|
|
2470
|
+
}
|
|
2471
|
+
|
|
2472
|
+
let worktree: PrWorktreeInfo | undefined
|
|
2473
|
+
if (canSpawnReviewSubagent()) {
|
|
2474
|
+
ctx.ui.notify(`Preparing review worktree for PR #${prNumber}...`, 'info')
|
|
2475
|
+
worktree = (await preparePrWorktree(pi, ctx, prNumber)) ?? undefined
|
|
2476
|
+
}
|
|
2477
|
+
|
|
2478
|
+
if (!worktree) {
|
|
2479
|
+
// Legacy in-place checkout — needs a clean tree
|
|
2480
|
+
if (await hasPendingChanges(pi)) {
|
|
2481
|
+
ctx.ui.notify(
|
|
2482
|
+
'Cannot checkout PR: you have uncommitted changes. Please commit or stash them first.',
|
|
2483
|
+
'error',
|
|
2484
|
+
)
|
|
2485
|
+
return null
|
|
2486
|
+
}
|
|
2487
|
+
|
|
2488
|
+
ctx.ui.notify(`Checking out PR #${prNumber}...`, 'info')
|
|
2489
|
+
const checkoutResult = await checkoutPr(pi, prNumber)
|
|
2490
|
+
|
|
2491
|
+
if (!checkoutResult.success) {
|
|
2492
|
+
ctx.ui.notify(`Failed to checkout PR: ${checkoutResult.error}`, 'error')
|
|
2493
|
+
return null
|
|
2494
|
+
}
|
|
2495
|
+
|
|
2496
|
+
ctx.ui.notify(
|
|
2497
|
+
`Checked out PR #${prNumber} (${prInfo.headBranch})`,
|
|
2498
|
+
'info',
|
|
2499
|
+
)
|
|
2500
|
+
}
|
|
2501
|
+
|
|
2502
|
+
const tuicrInstructions = await maybeOpenTuicrForPr(
|
|
2503
|
+
pi,
|
|
2504
|
+
ctx,
|
|
2505
|
+
prNumber,
|
|
2506
|
+
worktree?.path,
|
|
2507
|
+
)
|
|
2508
|
+
|
|
2509
|
+
return {
|
|
2510
|
+
type: 'pullRequest',
|
|
2511
|
+
prNumber,
|
|
2512
|
+
baseBranch: prInfo.baseBranch,
|
|
2513
|
+
title: prInfo.title,
|
|
2514
|
+
tuicrInstructions,
|
|
2515
|
+
worktree,
|
|
2516
|
+
}
|
|
2517
|
+
}
|
|
2518
|
+
|
|
2519
|
+
// Register the /review command
|
|
2520
|
+
pi.registerCommand('review', {
|
|
2521
|
+
description:
|
|
2522
|
+
'Review code changes (PR, uncommitted, branch, commit, folder, or custom)',
|
|
2523
|
+
handler: async (args, ctx) => {
|
|
2524
|
+
if (!ctx.hasUI) {
|
|
2525
|
+
ctx.ui.notify('Review requires interactive mode', 'error')
|
|
2526
|
+
return
|
|
2527
|
+
}
|
|
2528
|
+
|
|
2529
|
+
// Check if we're in a git repository
|
|
2530
|
+
// AIDEV-NOTE: PMR-NPWY — pass ctx.cwd explicitly: under the makeRealPi
|
|
2531
|
+
// sandbox seam a cwd-less exec REJECTS instead of returning {code: 1}.
|
|
2532
|
+
const { code } = await pi.exec('git', ['rev-parse', '--git-dir'], {
|
|
2533
|
+
cwd: ctx.cwd,
|
|
2534
|
+
})
|
|
2535
|
+
if (code !== 0) {
|
|
2536
|
+
ctx.ui.notify('Not a git repository', 'error')
|
|
2537
|
+
return
|
|
2538
|
+
}
|
|
2539
|
+
|
|
2540
|
+
// Try to parse direct arguments
|
|
2541
|
+
let target: ReviewTarget | null = null
|
|
2542
|
+
let fromSelector = false
|
|
2543
|
+
const parsed = parseArgs(args)
|
|
2544
|
+
|
|
2545
|
+
if (parsed) {
|
|
2546
|
+
if (parsed.type === 'pr') {
|
|
2547
|
+
// Handle PR checkout (async operation)
|
|
2548
|
+
target = await handlePrCheckout(ctx, parsed.ref)
|
|
2549
|
+
if (!target) {
|
|
2550
|
+
ctx.ui.notify(
|
|
2551
|
+
'PR review failed. Returning to review menu.',
|
|
2552
|
+
'warning',
|
|
2553
|
+
)
|
|
2554
|
+
}
|
|
2555
|
+
} else {
|
|
2556
|
+
target = parsed
|
|
2557
|
+
}
|
|
2558
|
+
}
|
|
2559
|
+
|
|
2560
|
+
// If no args or invalid args, show selector
|
|
2561
|
+
if (!target) {
|
|
2562
|
+
fromSelector = true
|
|
2563
|
+
}
|
|
2564
|
+
|
|
2565
|
+
while (true) {
|
|
2566
|
+
if (!target && fromSelector) {
|
|
2567
|
+
target = await showReviewSelector(ctx)
|
|
2568
|
+
}
|
|
2569
|
+
|
|
2570
|
+
if (!target) {
|
|
2571
|
+
ctx.ui.notify('Review cancelled', 'info')
|
|
2572
|
+
return
|
|
2573
|
+
}
|
|
2574
|
+
|
|
2575
|
+
// Determine if we should use fresh session mode
|
|
2576
|
+
// Check if this is a new session (no messages yet)
|
|
2577
|
+
const entries = ctx.sessionManager.getEntries()
|
|
2578
|
+
const messageCount = entries.filter((e) => e.type === 'message').length
|
|
2579
|
+
|
|
2580
|
+
let useFreshSession = false
|
|
2581
|
+
|
|
2582
|
+
// With a mux available, /review always spawns a subagent — no mode
|
|
2583
|
+
// question needed. The selector below is the legacy no-mux flow only.
|
|
2584
|
+
if (messageCount > 0 && !canSpawnReviewSubagent()) {
|
|
2585
|
+
const choice = await ctx.ui.select('Start review in:', [
|
|
2586
|
+
'Empty branch',
|
|
2587
|
+
'Current session',
|
|
2588
|
+
])
|
|
2589
|
+
|
|
2590
|
+
if (choice === undefined) {
|
|
2591
|
+
if (fromSelector) {
|
|
2592
|
+
target = null
|
|
2593
|
+
continue
|
|
2594
|
+
}
|
|
2595
|
+
ctx.ui.notify('Review cancelled', 'info')
|
|
2596
|
+
return
|
|
2597
|
+
}
|
|
2598
|
+
|
|
2599
|
+
useFreshSession = choice === 'Empty branch'
|
|
2600
|
+
}
|
|
2601
|
+
// If messageCount === 0, useFreshSession stays false (current session mode)
|
|
2602
|
+
|
|
2603
|
+
await executeReview(ctx, target, useFreshSession)
|
|
2604
|
+
return
|
|
2605
|
+
}
|
|
2606
|
+
},
|
|
2607
|
+
})
|
|
2608
|
+
|
|
2609
|
+
// AIDEV-NOTE: Agent-callable surface — fire-and-steer. Spawns the reviewer
|
|
2610
|
+
// (and ocr scout) subagents and returns immediately; findings arrive later
|
|
2611
|
+
// as review_result / ocr_result steer messages. Shares buildFullReviewPrompt
|
|
2612
|
+
// and spawnReviewJobs with the /review command — one implementation.
|
|
2613
|
+
pi.registerTool({
|
|
2614
|
+
name: 'review',
|
|
2615
|
+
label: 'code review',
|
|
2616
|
+
description:
|
|
2617
|
+
'Start a code review of uncommitted changes, a branch, a commit, a PR, folders, or custom instructions. Spawns a reviewer subagent (requires the herdr mux) and returns immediately; findings arrive later as steer messages.',
|
|
2618
|
+
promptSnippet:
|
|
2619
|
+
'Spawn a background code review subagent for a target (uncommitted, branch, commit, pr, folder, custom).',
|
|
2620
|
+
promptGuidelines: [
|
|
2621
|
+
'The review runs in the background — findings arrive as later messages. Do not call this when the user needs review findings in this turn.',
|
|
2622
|
+
],
|
|
2623
|
+
parameters: Type.Object({
|
|
2624
|
+
target: Type.Union([
|
|
2625
|
+
Type.Object({ type: Type.Literal('uncommitted') }),
|
|
2626
|
+
Type.Object({
|
|
2627
|
+
type: Type.Literal('branch'),
|
|
2628
|
+
branch: Type.String({ description: 'Base branch to diff against' }),
|
|
2629
|
+
}),
|
|
2630
|
+
Type.Object({
|
|
2631
|
+
type: Type.Literal('commit'),
|
|
2632
|
+
sha: Type.String({ description: 'Commit SHA to review' }),
|
|
2633
|
+
title: Type.Optional(Type.String()),
|
|
2634
|
+
}),
|
|
2635
|
+
Type.Object({
|
|
2636
|
+
type: Type.Literal('pr'),
|
|
2637
|
+
ref: Type.String({
|
|
2638
|
+
description: 'PR number or GitHub PR URL',
|
|
2639
|
+
}),
|
|
2640
|
+
}),
|
|
2641
|
+
Type.Object({
|
|
2642
|
+
type: Type.Literal('folder'),
|
|
2643
|
+
paths: Type.Array(Type.String(), {
|
|
2644
|
+
description: 'Paths to review (snapshot, not a diff)',
|
|
2645
|
+
}),
|
|
2646
|
+
}),
|
|
2647
|
+
Type.Object({
|
|
2648
|
+
type: Type.Literal('custom'),
|
|
2649
|
+
instructions: Type.String({
|
|
2650
|
+
description: 'Custom review instructions',
|
|
2651
|
+
}),
|
|
2652
|
+
}),
|
|
2653
|
+
]),
|
|
2654
|
+
}),
|
|
2655
|
+
async execute(
|
|
2656
|
+
_toolCallId: string,
|
|
2657
|
+
params: {
|
|
2658
|
+
target:
|
|
2659
|
+
| { type: 'uncommitted' }
|
|
2660
|
+
| { type: 'branch'; branch: string }
|
|
2661
|
+
| { type: 'commit'; sha: string; title?: string }
|
|
2662
|
+
| { type: 'pr'; ref: string }
|
|
2663
|
+
| { type: 'folder'; paths: string[] }
|
|
2664
|
+
| { type: 'custom'; instructions: string }
|
|
2665
|
+
},
|
|
2666
|
+
_signal: AbortSignal,
|
|
2667
|
+
_onUpdate: unknown,
|
|
2668
|
+
ctx: ExtensionToolContext,
|
|
2669
|
+
): Promise<AgentToolResult<{ hint: string; ocr: boolean } | undefined>> {
|
|
2670
|
+
const p = params.target
|
|
2671
|
+
// AIDEV-NOTE: PMR-1CCT — resolve the review cwd and the empty-range
|
|
2672
|
+
// guard BEFORE the mux check: a branch review whose merge base equals
|
|
2673
|
+
// HEAD diffs nothing (flow work lives in a worktree, the session
|
|
2674
|
+
// checkout sits on main), and must fail loudly instead of returning a
|
|
2675
|
+
// skipped/clean-looking artifact. The routing itself lives in the
|
|
2676
|
+
// exported resolveReviewCwdForTarget seam (PMR-TDJC) so it is testable
|
|
2677
|
+
// without a mux; the commit checkout-mismatch refusal text stays here.
|
|
2678
|
+
const cwdResult = await resolveReviewCwdForTarget(pi, ctx.cwd, p)
|
|
2679
|
+
if (!cwdResult.ok) {
|
|
2680
|
+
return {
|
|
2681
|
+
content: [
|
|
2682
|
+
{
|
|
2683
|
+
type: 'text',
|
|
2684
|
+
text: `Review refused: checkout mismatch — ${cwdResult.reason}. Pinning commit ${cwdResult.sha} from ${ctx.cwd} would re-check HEAD against the wrong checkout and report a misleading 'stale' verdict. Fix or re-bind the flow worktree (run /flow <ref> to resume so the flow loop session holds the worktree context), then re-run the review.`,
|
|
2685
|
+
},
|
|
2686
|
+
],
|
|
2687
|
+
// AIDEV-NOTE: isError results omit details — a fabricated
|
|
2688
|
+
// empty hint would mislead consumers. See pr-quality/index.ts.
|
|
2689
|
+
details: undefined,
|
|
2690
|
+
isError: true,
|
|
2691
|
+
}
|
|
2692
|
+
}
|
|
2693
|
+
const reviewCwd = cwdResult.cwd
|
|
2694
|
+
// AIDEV-NOTE: PMR-R4AP (amended by PMR-5NZB) — in a flow worktree the
|
|
2695
|
+
// review base is resolved by resolveBranchRefForReview (see its note:
|
|
2696
|
+
// work → recorded sha, personal → stable-range integrity resolver,
|
|
2697
|
+
// ONE resolved SHA plumbed to all consumers), not whatever branch
|
|
2698
|
+
// name the agent typed or origin/<branch>. A 'refuse' result is the
|
|
2699
|
+
// personal fail-closed integrity outcome: it returns isError with
|
|
2700
|
+
// the stable-range recovery text BEFORE the empty-range check below
|
|
2701
|
+
// — never a moving-base review.
|
|
2702
|
+
let branchRef = ''
|
|
2703
|
+
if (p.type === 'branch') {
|
|
2704
|
+
// AIDEV-NOTE: PMR-1W7N — thunk, not a value: resolveMode loads
|
|
2705
|
+
// pi-flow config (and throws on a malformed file), which must only
|
|
2706
|
+
// happen once resolveBranchRefForReview confirms a recorded flow
|
|
2707
|
+
// base. Plain non-flow `/review branch main` stays config-free.
|
|
2708
|
+
const baseResolution = await resolveBranchRefForReview(
|
|
2709
|
+
pi,
|
|
2710
|
+
p.branch,
|
|
2711
|
+
reviewCwd,
|
|
2712
|
+
() => resolveMode(pi, reviewCwd),
|
|
2713
|
+
)
|
|
2714
|
+
if (baseResolution.kind === 'refuse') {
|
|
2715
|
+
return {
|
|
2716
|
+
content: [{ type: 'text', text: baseResolution.reason }],
|
|
2717
|
+
// AIDEV-NOTE: isError results omit details — a fabricated
|
|
2718
|
+
// empty hint would mislead consumers. See pr-quality/index.ts.
|
|
2719
|
+
details: undefined,
|
|
2720
|
+
isError: true,
|
|
2721
|
+
}
|
|
2722
|
+
}
|
|
2723
|
+
if (baseResolution.kind === 'resolved') {
|
|
2724
|
+
branchRef = baseResolution.sha
|
|
2725
|
+
} else {
|
|
2726
|
+
branchRef = baseResolution.ref
|
|
2727
|
+
}
|
|
2728
|
+
}
|
|
2729
|
+
if (
|
|
2730
|
+
p.type === 'branch' &&
|
|
2731
|
+
(await isEmptyBranchRange(pi, branchRef, reviewCwd))
|
|
2732
|
+
) {
|
|
2733
|
+
return {
|
|
2734
|
+
content: [
|
|
2735
|
+
{
|
|
2736
|
+
type: 'text',
|
|
2737
|
+
text: `Empty review range: HEAD == merge-base with '${branchRef}' in ${reviewCwd} — the change is not on this checkout/branch, so the diff would be empty. Run the review from the worktree carrying the change (or start the flow loop so its worktree binding is known). Refusing to spawn a review that would silently pass.`,
|
|
2738
|
+
},
|
|
2739
|
+
],
|
|
2740
|
+
// AIDEV-NOTE: isError results omit details — a fabricated
|
|
2741
|
+
// empty hint would mislead consumers. See pr-quality/index.ts.
|
|
2742
|
+
details: undefined,
|
|
2743
|
+
isError: true,
|
|
2744
|
+
}
|
|
2745
|
+
}
|
|
2746
|
+
|
|
2747
|
+
if (!canSpawnReviewSubagent()) {
|
|
2748
|
+
return {
|
|
2749
|
+
content: [
|
|
2750
|
+
{
|
|
2751
|
+
type: 'text',
|
|
2752
|
+
text: 'Review requires a subagent mux (herdr). Ask the user to run the /review command instead.',
|
|
2753
|
+
},
|
|
2754
|
+
],
|
|
2755
|
+
// AIDEV-NOTE: isError results omit details — a fabricated
|
|
2756
|
+
// empty hint would mislead consumers. See pr-quality/index.ts.
|
|
2757
|
+
details: undefined,
|
|
2758
|
+
isError: true,
|
|
2759
|
+
}
|
|
2760
|
+
}
|
|
2761
|
+
|
|
2762
|
+
let target: ReviewTarget
|
|
2763
|
+
if (p.type === 'uncommitted') {
|
|
2764
|
+
target = { type: 'uncommitted' }
|
|
2765
|
+
} else if (p.type === 'branch') {
|
|
2766
|
+
target = { type: 'baseBranch', branch: branchRef }
|
|
2767
|
+
} else if (p.type === 'commit') {
|
|
2768
|
+
target = { type: 'commit', sha: p.sha, title: p.title }
|
|
2769
|
+
} else if (p.type === 'folder') {
|
|
2770
|
+
target = { type: 'folder', paths: p.paths }
|
|
2771
|
+
} else if (p.type === 'custom') {
|
|
2772
|
+
target = { type: 'custom', instructions: p.instructions }
|
|
2773
|
+
} else {
|
|
2774
|
+
const prTarget = await handlePrCheckout(ctx, p.ref)
|
|
2775
|
+
if (!prTarget) {
|
|
2776
|
+
return {
|
|
2777
|
+
content: [
|
|
2778
|
+
{
|
|
2779
|
+
type: 'text',
|
|
2780
|
+
text: `PR checkout failed for ${p.ref}. See the notification for details.`,
|
|
2781
|
+
},
|
|
2782
|
+
],
|
|
2783
|
+
details: undefined,
|
|
2784
|
+
isError: true,
|
|
2785
|
+
}
|
|
2786
|
+
}
|
|
2787
|
+
target = prTarget
|
|
2788
|
+
}
|
|
2789
|
+
|
|
2790
|
+
const fullPrompt = await buildFullReviewPrompt(pi, target, reviewCwd)
|
|
2791
|
+
const { status, ocrStarted } = await spawnReviewJobs(
|
|
2792
|
+
ctx,
|
|
2793
|
+
target,
|
|
2794
|
+
fullPrompt,
|
|
2795
|
+
reviewCwd,
|
|
2796
|
+
)
|
|
2797
|
+
const hint = getUserFacingHint(target)
|
|
2798
|
+
|
|
2799
|
+
if (status === 'spawned') {
|
|
2800
|
+
let text = `Review spawned: ${hint}. Findings will arrive here as messages when the reviewer finishes.`
|
|
2801
|
+
if (ocrStarted) {
|
|
2802
|
+
text += ' An ocr second-opinion scout was also started.'
|
|
2803
|
+
}
|
|
2804
|
+
// AIDEV-NOTE: PMR-7TPN — surface the unbound-flow-worktree risk on
|
|
2805
|
+
// the spawn response too, not only in the delivered result.
|
|
2806
|
+
if (
|
|
2807
|
+
(target.type === 'baseBranch' || target.type === 'uncommitted') &&
|
|
2808
|
+
getActiveFlowRef() === null &&
|
|
2809
|
+
getFlowWorktree() === null
|
|
2810
|
+
) {
|
|
2811
|
+
const warn = await unboundWorktreeWarningFor(pi, reviewCwd)
|
|
2812
|
+
if (warn !== null) text += `\n\n${warn}`
|
|
2813
|
+
}
|
|
2814
|
+
return {
|
|
2815
|
+
content: [{ type: 'text', text }],
|
|
2816
|
+
details: { hint, ocr: ocrStarted },
|
|
2817
|
+
}
|
|
2818
|
+
}
|
|
2819
|
+
|
|
2820
|
+
let text: string
|
|
2821
|
+
if (status === 'aborted') {
|
|
2822
|
+
text = `Review aborted: subagent spawn failed for ${hint}. The PR review worktree is being cleaned up; retry with /review pr.`
|
|
2823
|
+
} else {
|
|
2824
|
+
text = `Review spawn failed: ${hint}. The review tool has no in-session fallback — ask the user to run /review.`
|
|
2825
|
+
}
|
|
2826
|
+
return {
|
|
2827
|
+
content: [{ type: 'text', text }],
|
|
2828
|
+
isError: true,
|
|
2829
|
+
details: { hint, ocr: ocrStarted },
|
|
2830
|
+
}
|
|
2831
|
+
},
|
|
2832
|
+
})
|
|
2833
|
+
|
|
2834
|
+
// Custom prompt for review summaries - focuses on preserving actionable findings
|
|
2835
|
+
const REVIEW_SUMMARY_PROMPT = `We are leaving a code-review branch and returning to the main coding branch.
|
|
2836
|
+
Create a structured handoff that can be used immediately to implement fixes.
|
|
2837
|
+
|
|
2838
|
+
You MUST summarize the review that happened in this branch so findings can be acted on.
|
|
2839
|
+
Do not omit findings: include every actionable issue that was identified.
|
|
2840
|
+
|
|
2841
|
+
Required sections (in order):
|
|
2842
|
+
|
|
2843
|
+
## Review Scope
|
|
2844
|
+
- What was reviewed (files/paths, changes, and scope)
|
|
2845
|
+
|
|
2846
|
+
## Verdict
|
|
2847
|
+
- "correct" or "needs attention"
|
|
2848
|
+
|
|
2849
|
+
## Findings
|
|
2850
|
+
For EACH finding, include:
|
|
2851
|
+
- Priority tag ([P0]..[P3]) and short title
|
|
2852
|
+
- File location (\`path/to/file.ext:line\`)
|
|
2853
|
+
- Why it matters (brief)
|
|
2854
|
+
- What should change (brief, actionable)
|
|
2855
|
+
|
|
2856
|
+
## Fix Queue
|
|
2857
|
+
1. Ordered implementation checklist (highest priority first)
|
|
2858
|
+
|
|
2859
|
+
## Constraints & Preferences
|
|
2860
|
+
- Any constraints or preferences mentioned during review
|
|
2861
|
+
- Or "(none)"
|
|
2862
|
+
|
|
2863
|
+
Preserve exact file paths, function names, and error messages where available.`
|
|
2864
|
+
|
|
2865
|
+
const REVIEW_FIX_FINDINGS_PROMPT = `Use the latest review summary in this session and implement the review findings now.
|
|
2866
|
+
|
|
2867
|
+
Instructions:
|
|
2868
|
+
1. Treat the summary's Findings/Fix Queue as a checklist.
|
|
2869
|
+
2. Fix in priority order: P0, P1, then P2 (include P3 if quick and safe).
|
|
2870
|
+
3. If a finding is invalid/already fixed/not possible right now, briefly explain why and continue.
|
|
2871
|
+
4. Run relevant tests/checks for touched code where practical.
|
|
2872
|
+
5. End with: fixed items, deferred/skipped items (with reasons), and verification results.`
|
|
2873
|
+
|
|
2874
|
+
type EndReviewAction = 'returnOnly' | 'returnAndFix' | 'returnAndSummarize'
|
|
2875
|
+
|
|
2876
|
+
function getActiveReviewOrigin(ctx: ExtensionContext): string | undefined {
|
|
2877
|
+
if (reviewOriginId) {
|
|
2878
|
+
return reviewOriginId
|
|
2879
|
+
}
|
|
2880
|
+
|
|
2881
|
+
const state = getReviewState(ctx)
|
|
2882
|
+
if (state?.active && state.originId) {
|
|
2883
|
+
reviewOriginId = state.originId
|
|
2884
|
+
return reviewOriginId
|
|
2885
|
+
}
|
|
2886
|
+
|
|
2887
|
+
if (state?.active) {
|
|
2888
|
+
setReviewWidget(ctx, false)
|
|
2889
|
+
pi.appendEntry(REVIEW_STATE_TYPE, { active: false })
|
|
2890
|
+
ctx.ui.notify(
|
|
2891
|
+
'Review state was missing origin info; cleared review status.',
|
|
2892
|
+
'warning',
|
|
2893
|
+
)
|
|
2894
|
+
}
|
|
2895
|
+
|
|
2896
|
+
return undefined
|
|
2897
|
+
}
|
|
2898
|
+
|
|
2899
|
+
function clearReviewState(ctx: ExtensionContext) {
|
|
2900
|
+
setReviewWidget(ctx, false)
|
|
2901
|
+
reviewOriginId = undefined
|
|
2902
|
+
pi.appendEntry(REVIEW_STATE_TYPE, { active: false })
|
|
2903
|
+
}
|
|
2904
|
+
|
|
2905
|
+
async function runEndReview(ctx: ExtensionCommandContext): Promise<void> {
|
|
2906
|
+
if (!ctx.hasUI) {
|
|
2907
|
+
ctx.ui.notify('End-review requires interactive mode', 'error')
|
|
2908
|
+
return
|
|
2909
|
+
}
|
|
2910
|
+
|
|
2911
|
+
if (endReviewInProgress) {
|
|
2912
|
+
ctx.ui.notify('/end-review is already running', 'info')
|
|
2913
|
+
return
|
|
2914
|
+
}
|
|
2915
|
+
|
|
2916
|
+
const originId = getActiveReviewOrigin(ctx)
|
|
2917
|
+
if (!originId) {
|
|
2918
|
+
if (!getReviewState(ctx)?.active) {
|
|
2919
|
+
ctx.ui.notify(
|
|
2920
|
+
'Not in a review branch (use /review first, or review was started in current session mode)',
|
|
2921
|
+
'info',
|
|
2922
|
+
)
|
|
2923
|
+
}
|
|
2924
|
+
return
|
|
2925
|
+
}
|
|
2926
|
+
|
|
2927
|
+
endReviewInProgress = true
|
|
2928
|
+
try {
|
|
2929
|
+
const choice = await ctx.ui.select('Finish review:', [
|
|
2930
|
+
'Return only',
|
|
2931
|
+
'Return and fix findings',
|
|
2932
|
+
'Return and summarize',
|
|
2933
|
+
])
|
|
2934
|
+
|
|
2935
|
+
if (choice === undefined) {
|
|
2936
|
+
ctx.ui.notify('Cancelled. Use /end-review to try again.', 'info')
|
|
2937
|
+
return
|
|
2938
|
+
}
|
|
2939
|
+
|
|
2940
|
+
let action: EndReviewAction
|
|
2941
|
+
if (choice === 'Return and fix findings') {
|
|
2942
|
+
action = 'returnAndFix'
|
|
2943
|
+
} else if (choice === 'Return and summarize') {
|
|
2944
|
+
action = 'returnAndSummarize'
|
|
2945
|
+
} else {
|
|
2946
|
+
action = 'returnOnly'
|
|
2947
|
+
}
|
|
2948
|
+
if (action === 'returnOnly') {
|
|
2949
|
+
try {
|
|
2950
|
+
const result = await ctx.navigateTree(originId, { summarize: false })
|
|
2951
|
+
if (result.cancelled) {
|
|
2952
|
+
ctx.ui.notify(
|
|
2953
|
+
'Navigation cancelled. Use /end-review to try again.',
|
|
2954
|
+
'info',
|
|
2955
|
+
)
|
|
2956
|
+
return
|
|
2957
|
+
}
|
|
2958
|
+
} catch (error) {
|
|
2959
|
+
let errMsg2: string
|
|
2960
|
+
if (error instanceof Error) {
|
|
2961
|
+
errMsg2 = error.message
|
|
2962
|
+
} else {
|
|
2963
|
+
errMsg2 = String(error)
|
|
2964
|
+
}
|
|
2965
|
+
ctx.ui.notify(`Failed to return: ${errMsg2}`, 'error')
|
|
2966
|
+
return
|
|
2967
|
+
}
|
|
2968
|
+
|
|
2969
|
+
clearReviewState(ctx)
|
|
2970
|
+
ctx.ui.notify('Review complete! Returned to original position.', 'info')
|
|
2971
|
+
return
|
|
2972
|
+
}
|
|
2973
|
+
|
|
2974
|
+
const summaryResult = await ctx.ui.custom<{
|
|
2975
|
+
cancelled: boolean
|
|
2976
|
+
error?: string
|
|
2977
|
+
} | null>((tui, theme, _kb, done) => {
|
|
2978
|
+
const loader = new BorderedLoader(
|
|
2979
|
+
tui,
|
|
2980
|
+
theme,
|
|
2981
|
+
'Returning and summarizing review branch...',
|
|
2982
|
+
)
|
|
2983
|
+
loader.onAbort = () => done(null)
|
|
2984
|
+
|
|
2985
|
+
ctx
|
|
2986
|
+
.navigateTree(originId, {
|
|
2987
|
+
summarize: true,
|
|
2988
|
+
customInstructions: REVIEW_SUMMARY_PROMPT,
|
|
2989
|
+
replaceInstructions: true,
|
|
2990
|
+
})
|
|
2991
|
+
.then(done)
|
|
2992
|
+
.catch((err) => {
|
|
2993
|
+
let errStr: string
|
|
2994
|
+
if (err instanceof Error) {
|
|
2995
|
+
errStr = err.message
|
|
2996
|
+
} else {
|
|
2997
|
+
errStr = String(err)
|
|
2998
|
+
}
|
|
2999
|
+
done({ cancelled: false, error: errStr })
|
|
3000
|
+
})
|
|
3001
|
+
|
|
3002
|
+
return loader
|
|
3003
|
+
})
|
|
3004
|
+
|
|
3005
|
+
if (summaryResult === null) {
|
|
3006
|
+
ctx.ui.notify(
|
|
3007
|
+
'Summarization cancelled. Use /end-review to try again.',
|
|
3008
|
+
'info',
|
|
3009
|
+
)
|
|
3010
|
+
return
|
|
3011
|
+
}
|
|
3012
|
+
|
|
3013
|
+
if (summaryResult.error) {
|
|
3014
|
+
ctx.ui.notify(`Summarization failed: ${summaryResult.error}`, 'error')
|
|
3015
|
+
return
|
|
3016
|
+
}
|
|
3017
|
+
|
|
3018
|
+
if (summaryResult.cancelled) {
|
|
3019
|
+
ctx.ui.notify(
|
|
3020
|
+
'Navigation cancelled. Use /end-review to try again.',
|
|
3021
|
+
'info',
|
|
3022
|
+
)
|
|
3023
|
+
return
|
|
3024
|
+
}
|
|
3025
|
+
|
|
3026
|
+
clearReviewState(ctx)
|
|
3027
|
+
|
|
3028
|
+
if (action === 'returnAndSummarize') {
|
|
3029
|
+
if (!ctx.ui.getEditorText().trim()) {
|
|
3030
|
+
ctx.ui.setEditorText('Act on the review findings')
|
|
3031
|
+
}
|
|
3032
|
+
ctx.ui.notify('Review complete! Returned and summarized.', 'info')
|
|
3033
|
+
return
|
|
3034
|
+
}
|
|
3035
|
+
|
|
3036
|
+
pi.sendUserMessage(REVIEW_FIX_FINDINGS_PROMPT, { deliverAs: 'followUp' })
|
|
3037
|
+
ctx.ui.notify(
|
|
3038
|
+
'Review complete! Returned and queued a follow-up to fix findings.',
|
|
3039
|
+
'info',
|
|
3040
|
+
)
|
|
3041
|
+
} finally {
|
|
3042
|
+
endReviewInProgress = false
|
|
3043
|
+
}
|
|
3044
|
+
}
|
|
3045
|
+
|
|
3046
|
+
// Register the /end-review command
|
|
3047
|
+
pi.registerCommand('end-review', {
|
|
3048
|
+
description: 'Complete review and return to original position',
|
|
3049
|
+
handler: async (_args, ctx) => {
|
|
3050
|
+
await runEndReview(ctx)
|
|
3051
|
+
},
|
|
3052
|
+
})
|
|
3053
|
+
}
|