@imdeadpool/guardex 8.4.0 → 8.4.2
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/CONTRIBUTING.md +13 -4
- package/README.md +223 -1
- package/THIRD-PARTY-NOTICES.md +29 -0
- package/bin/multiagent-safety.js +9 -12
- package/package.json +4 -2
- package/skills/gitguardex/SKILL.md +28 -0
- package/skills/pr-lens/SKILL.md +87 -0
- package/src/abide.js +534 -0
- package/src/agents/activity.js +23 -4
- package/src/agents/inspect.js +15 -6
- package/src/agents/launch.js +6 -1
- package/src/agents/process-lease.js +84 -0
- package/src/agents/sessions.js +96 -16
- package/src/agents/start.js +18 -9
- package/src/agents/status.js +35 -14
- package/src/agents/supervise.js +87 -0
- package/src/budget/index.js +6 -1
- package/src/cli/args.js +71 -77
- package/src/cli/commands/agents.js +38 -10
- package/src/cli/commands/branch.js +116 -103
- package/src/cli/commands/claude.js +604 -50
- package/src/cli/commands/codex.js +359 -0
- package/src/cli/commands/context.js +52 -0
- package/src/cli/commands/mcp.js +5 -1
- package/src/cli/commands/pr.js +138 -3
- package/src/cli/commands/review.js +3 -1
- package/src/cli/commands/setup.js +25 -0
- package/src/cli/commands/status.js +128 -60
- package/src/cli/commands/storage.js +24 -0
- package/src/cli/commands/usage.js +48 -0
- package/src/cli/commands/watch.js +157 -47
- package/src/cli/commands/worktree-copy-ignored.js +38 -0
- package/src/cli/commands/worktree-estimate.js +69 -0
- package/src/cli/commands/worktree-hooks.js +62 -0
- package/src/cli/commands/worktree-navigation.js +71 -0
- package/src/cli/commands/worktree-provision.js +92 -0
- package/src/cli/main.js +229 -110
- package/src/cli/shared/gate-flags.js +131 -0
- package/src/cli/shared/scaffolding.js +31 -3
- package/src/cli/shared-locks.js +3 -1
- package/src/cockpit/pane-actions.js +43 -7
- package/src/context.js +373 -17
- package/src/doctor/index.js +29 -35
- package/src/finish/events.js +254 -0
- package/src/finish/index.js +322 -62
- package/src/finish/post-branch-finish-cleanup.js +316 -22
- package/src/finish/preflight.js +44 -1
- package/src/finish/progress.js +36 -0
- package/src/finish/review-gate.js +317 -127
- package/src/finish/review-receipt.js +156 -0
- package/src/finish/with-claims-lock.py +29 -0
- package/src/git/index.js +179 -42
- package/src/hooks/index.js +68 -3
- package/src/mcp/collect.js +61 -5
- package/src/mcp/server.js +4 -0
- package/src/output/index.js +167 -1
- package/src/pr-lens-publish.js +93 -0
- package/src/pr-lens.js +184 -0
- package/src/pr-respond.js +860 -0
- package/src/pr-review.js +519 -159
- package/src/pr.js +73 -14
- package/src/provider-binary.js +21 -0
- package/src/review-diff-context.js +90 -0
- package/src/review-fix.js +23 -17
- package/src/scaffold/agent-worktree-prep.js +14 -12
- package/src/scaffold/dependency-store.js +234 -0
- package/src/scaffold/index.js +13 -1
- package/src/scaffold/provision-approvals.js +83 -0
- package/src/scaffold/provision-config.js +169 -40
- package/src/shared-git-state.js +11 -1
- package/src/speckit/index.js +12 -1
- package/src/storage/run-artifacts.js +185 -0
- package/src/toolchain/index.js +322 -2
- package/src/worktree-copy-ignored.js +200 -0
- package/src/worktree-hook-worker.js +29 -0
- package/src/worktree-hooks.js +333 -0
- package/src/worktree-navigation.js +248 -0
- package/src/worktree-picker.js +89 -0
- package/src/worktree-quota.js +100 -0
- package/src/worktree-start.js +100 -0
- package/templates/AGENTS.multiagent-safety.md +8 -0
- package/templates/AGENTS.multiagent-safety.min.md +3 -1
- package/templates/codex/skills/gitguardex/SKILL.md +28 -0
- package/templates/codex/skills/opensrc/SKILL.md +24 -0
- package/templates/githooks/post-merge +16 -2
- package/templates/scripts/agent-autofinish-watch.sh +17 -18
- package/templates/scripts/agent-branch-finish.sh +180 -19
- package/templates/scripts/agent-branch-merge.sh +7 -32
- package/templates/scripts/agent-branch-start.sh +202 -43
- package/templates/scripts/agent-claude-stop-finish.sh +4 -27
- package/templates/scripts/agent-file-locks.py +257 -29
- package/templates/scripts/agent-preflight.sh +3 -0
- package/templates/scripts/agent-worktree-prune.sh +975 -63
- package/templates/scripts/codex-agent.sh +55 -5
- package/templates/scripts/lib/guardex-base-branch.sh +207 -0
- package/templates/scripts/openspec/init-change-workspace.sh +10 -18
- package/templates/scripts/review-bot-watch.sh +171 -4
|
@@ -0,0 +1,860 @@
|
|
|
1
|
+
// Auto-fix blocking review threads on agent PRs.
|
|
2
|
+
//
|
|
3
|
+
// `gx pr respond --pr <n>` workflow:
|
|
4
|
+
// 1. Fetch PR metadata — refuse forks, get head branch.
|
|
5
|
+
// 2. Find the local agent/* worktree for that branch.
|
|
6
|
+
// 3. Verify the worktree is clean and on the right branch.
|
|
7
|
+
// 4. Fetch unresolved, non-outdated review threads with CRITICAL/HIGH gitguardex
|
|
8
|
+
// markers, or from a human reviewer who requested changes.
|
|
9
|
+
// 5. Convert threads to findings and run the existing review-fix path.
|
|
10
|
+
// 6. On success: push the fix commit, re-run gx pr-review (--post), then
|
|
11
|
+
// reply + resolve only the threads whose files changed.
|
|
12
|
+
//
|
|
13
|
+
// Refusals (exit 1 without touching the worktree):
|
|
14
|
+
// - fork PR (isCrossRepository)
|
|
15
|
+
// - branch is not agent/* (not an agent-managed branch)
|
|
16
|
+
// - no local worktree found for the branch
|
|
17
|
+
// - worktree has uncommitted tracked changes
|
|
18
|
+
// - --dry-run flag: print what would happen, then exit 0
|
|
19
|
+
|
|
20
|
+
'use strict';
|
|
21
|
+
|
|
22
|
+
const { GH_BIN } = require('./context');
|
|
23
|
+
const { run } = require('./core/runtime');
|
|
24
|
+
const { repoNameWithOwner } = require('./github-api');
|
|
25
|
+
const { worktreePathForBranch } = require('./agents/inspect');
|
|
26
|
+
const { gitRun, currentBranchName } = require('./git');
|
|
27
|
+
const { runReviewFix } = require('./review-fix');
|
|
28
|
+
const { runPrReview, MARKER } = require('./pr-review');
|
|
29
|
+
const { getPrHeadOid } = require('./pr');
|
|
30
|
+
|
|
31
|
+
const TOOL_PREFIX = '[gitguardex]';
|
|
32
|
+
|
|
33
|
+
// A fix hunk "addresses" a thread when it lands within this many lines of the
|
|
34
|
+
// thread's anchored range (pre-fix coordinates).
|
|
35
|
+
const THREAD_HUNK_MARGIN = 3;
|
|
36
|
+
|
|
37
|
+
// How long to wait for GitHub to expose the pushed fix commit as the PR head
|
|
38
|
+
// before re-reviewing. A re-review of the pre-fix diff must never drive resolution.
|
|
39
|
+
const PR_HEAD_WAIT_SECONDS = 60;
|
|
40
|
+
const PR_HEAD_POLL_SECONDS = 2;
|
|
41
|
+
|
|
42
|
+
// Only agent/* branches may be auto-fixed.
|
|
43
|
+
const AGENT_BRANCH_PREFIX = 'agent/';
|
|
44
|
+
|
|
45
|
+
// Severities that trigger an auto-fix from gitguardex review threads.
|
|
46
|
+
const BLOCKING_SEVERITIES = new Set(['high', 'critical']);
|
|
47
|
+
|
|
48
|
+
// Only these reviewer associations are trusted for human-thread auto-fix.
|
|
49
|
+
// GitHub's `authorAssociation` on a review reflects the submitter's repo role at
|
|
50
|
+
// submission time. NONE / CONTRIBUTOR / FIRST_TIME_CONTRIBUTOR are externals who
|
|
51
|
+
// can review public PRs — they must not be able to trigger the fix provider.
|
|
52
|
+
const TRUSTED_REVIEW_ASSOCIATIONS = new Set(['OWNER', 'MEMBER', 'COLLABORATOR']);
|
|
53
|
+
|
|
54
|
+
// Detect severity embedded in a gitguardex findingBody comment.
|
|
55
|
+
// findingBody writes e.g. `> 🔴 **CRITICAL** · category` or `> 🟠 **HIGH**`
|
|
56
|
+
const SEVERITY_IN_BODY_RE = /\*\*(CRITICAL|HIGH|MEDIUM|LOW)\*\*/i;
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Fetch PR metadata needed for the respond flow.
|
|
60
|
+
*
|
|
61
|
+
* Returns `{ headRefName, headRefOid, isCrossRepository }` on success, or throws.
|
|
62
|
+
* `headRefOid` is the current PR head commit SHA from GitHub — used to verify
|
|
63
|
+
* the local worktree is at the same commit before applying any fix.
|
|
64
|
+
*/
|
|
65
|
+
function fetchPrMeta(pr, repoRoot, runner = run) {
|
|
66
|
+
const result = runner(
|
|
67
|
+
GH_BIN,
|
|
68
|
+
['pr', 'view', String(pr), '--json', 'headRefName,isCrossRepository,headRefOid'],
|
|
69
|
+
{ cwd: repoRoot, timeout: 60_000, allowFailure: true }
|
|
70
|
+
);
|
|
71
|
+
if (result.status !== 0) {
|
|
72
|
+
throw new Error(`gh pr view ${pr} failed: ${(result.stderr || result.stdout || '').trim()}`);
|
|
73
|
+
}
|
|
74
|
+
let data;
|
|
75
|
+
try {
|
|
76
|
+
data = JSON.parse(String(result.stdout || '{}'));
|
|
77
|
+
} catch (error) {
|
|
78
|
+
throw new Error(`gh pr view JSON parse failed: ${error.message}`);
|
|
79
|
+
}
|
|
80
|
+
return {
|
|
81
|
+
headRefName: String(data.headRefName || ''),
|
|
82
|
+
headRefOid: String(data.headRefOid || ''),
|
|
83
|
+
isCrossRepository: Boolean(data.isCrossRepository)
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Extract the severity string from a gitguardex comment body, or '' if absent.
|
|
89
|
+
*/
|
|
90
|
+
function severityFromBody(body) {
|
|
91
|
+
const text = String(body || '');
|
|
92
|
+
const match = text.match(SEVERITY_IN_BODY_RE);
|
|
93
|
+
return match ? match[1].toLowerCase() : '';
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Extract the human-readable message from a gitguardex comment body.
|
|
98
|
+
* The lede is the first non-blockquote, non-empty paragraph after the header.
|
|
99
|
+
*/
|
|
100
|
+
function messageFromBody(body) {
|
|
101
|
+
const lines = String(body || '').split('\n');
|
|
102
|
+
const start = lines.findIndex((line) => !line.startsWith('>') && line.trim() !== '');
|
|
103
|
+
if (start === -1) return '';
|
|
104
|
+
const end = lines.findIndex((line, i) => i > start && line.trim() === '');
|
|
105
|
+
const slice = end === -1 ? lines.slice(start) : lines.slice(start, end);
|
|
106
|
+
return slice.join(' ').trim();
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Extract the fenced suggestion block from a gitguardex comment body.
|
|
111
|
+
* Returns '' when no suggestion is present.
|
|
112
|
+
*/
|
|
113
|
+
function suggestionFromBody(body) {
|
|
114
|
+
const text = String(body || '');
|
|
115
|
+
const open = text.indexOf('```suggestion\n');
|
|
116
|
+
if (open === -1) return '';
|
|
117
|
+
const close = text.indexOf('\n```', open + '```suggestion\n'.length);
|
|
118
|
+
if (close === -1) return '';
|
|
119
|
+
return text.slice(open + '```suggestion\n'.length, close);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Fetch unresolved, non-outdated review threads for `pr` that are candidates
|
|
124
|
+
* for auto-fix:
|
|
125
|
+
* - gitguardex threads with CRITICAL or HIGH severity
|
|
126
|
+
* - threads from a human reviewer who submitted a CHANGES_REQUESTED review
|
|
127
|
+
*
|
|
128
|
+
* Returns `{ threads, humanReviewers, trustedAuthor }` on success, or throws.
|
|
129
|
+
*/
|
|
130
|
+
function fetchBlockingThreads(pr, repoRoot, runner = run) {
|
|
131
|
+
const slug = repoNameWithOwner(repoRoot, runner);
|
|
132
|
+
if (!slug) {
|
|
133
|
+
throw new Error('repository slug unavailable (gh repo view failed)');
|
|
134
|
+
}
|
|
135
|
+
const [owner, name] = slug.split('/');
|
|
136
|
+
|
|
137
|
+
// One query: viewer login, all recent reviews (unfiltered), and review threads.
|
|
138
|
+
// We fetch all review states and compute the latest state per reviewer so that
|
|
139
|
+
// a reviewer who subsequently approved or dismissed their CHANGES_REQUESTED
|
|
140
|
+
// review is not treated as still blocking.
|
|
141
|
+
//
|
|
142
|
+
// `authorAssociation` on each review is checked to restrict auto-fix triggering
|
|
143
|
+
// to repository collaborators (OWNER/MEMBER/COLLABORATOR). External contributors
|
|
144
|
+
// (NONE, CONTRIBUTOR, FIRST_TIME_CONTRIBUTOR) are excluded so that anyone who can
|
|
145
|
+
// open a review on a public repo cannot trigger the fix provider.
|
|
146
|
+
//
|
|
147
|
+
// `latestComment` is a field alias for `comments(last:1)` — it gives the most
|
|
148
|
+
// recent comment in the thread, used to detect whether the bot already replied
|
|
149
|
+
// to a human reviewer thread (in which case we skip it until the reviewer acts).
|
|
150
|
+
const query = [
|
|
151
|
+
'query($owner:String!,$name:String!,$pr:Int!){',
|
|
152
|
+
'viewer{login}',
|
|
153
|
+
'repository(owner:$owner,name:$name){pullRequest(number:$pr){',
|
|
154
|
+
'reviews(last:50){nodes{author{login}state authorAssociation}pageInfo{hasPreviousPage}}',
|
|
155
|
+
'reviewThreads(first:100){nodes{',
|
|
156
|
+
'id isResolved isOutdated diffSide path line startLine',
|
|
157
|
+
'comments(first:3){nodes{id body author{login}}}',
|
|
158
|
+
'latestComment:comments(last:1){nodes{id body author{login}}}',
|
|
159
|
+
'}pageInfo{hasNextPage}}',
|
|
160
|
+
'}}}'
|
|
161
|
+
].join('');
|
|
162
|
+
|
|
163
|
+
const result = runner(
|
|
164
|
+
GH_BIN,
|
|
165
|
+
[
|
|
166
|
+
'api',
|
|
167
|
+
'graphql',
|
|
168
|
+
'-f',
|
|
169
|
+
`query=${query}`,
|
|
170
|
+
'-f',
|
|
171
|
+
`owner=${owner}`,
|
|
172
|
+
'-f',
|
|
173
|
+
`name=${name}`,
|
|
174
|
+
'-F',
|
|
175
|
+
`pr=${pr}`
|
|
176
|
+
],
|
|
177
|
+
{ cwd: repoRoot, timeout: 60_000, allowFailure: true }
|
|
178
|
+
);
|
|
179
|
+
if (result.status !== 0) {
|
|
180
|
+
throw new Error(
|
|
181
|
+
`GraphQL thread fetch failed: ${(result.stderr || result.stdout || '').trim()}`
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
let payload;
|
|
186
|
+
try {
|
|
187
|
+
payload = JSON.parse(String(result.stdout || '{}'));
|
|
188
|
+
} catch (error) {
|
|
189
|
+
throw new Error(`GraphQL response JSON parse failed: ${error.message}`);
|
|
190
|
+
}
|
|
191
|
+
if (Array.isArray(payload.errors) && payload.errors.length > 0) {
|
|
192
|
+
throw new Error(
|
|
193
|
+
payload.errors
|
|
194
|
+
.map((e) => e.message)
|
|
195
|
+
.filter(Boolean)
|
|
196
|
+
.join('; ')
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const trustedAuthor = String(payload?.data?.viewer?.login || '').toLowerCase();
|
|
201
|
+
if (!trustedAuthor) {
|
|
202
|
+
throw new Error('authenticated GitHub identity unavailable');
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// Build per-reviewer tracking from the review history.
|
|
206
|
+
// Reviews are returned oldest-first with `last:N`, so later entries overwrite
|
|
207
|
+
// earlier ones — the Map retains the most-recently-submitted state per author.
|
|
208
|
+
// We also track whether the reviewer has ever reviewed with a trusted association
|
|
209
|
+
// (OWNER/MEMBER/COLLABORATOR): `authorAssociation` reflects their repo role at
|
|
210
|
+
// submission time, so even a single trusted-association review is sufficient.
|
|
211
|
+
const latestStateByReviewer = new Map();
|
|
212
|
+
const trustedReviewerAssocs = new Set(); // reviewers with at least one trusted assoc
|
|
213
|
+
for (const review of payload?.data?.repository?.pullRequest?.reviews?.nodes || []) {
|
|
214
|
+
const login = String(review?.author?.login || '').toLowerCase();
|
|
215
|
+
const state = String(review?.state || '');
|
|
216
|
+
const assoc = String(review?.authorAssociation || '');
|
|
217
|
+
if (login && TRUSTED_REVIEW_ASSOCIATIONS.has(assoc)) {
|
|
218
|
+
trustedReviewerAssocs.add(login);
|
|
219
|
+
}
|
|
220
|
+
// COMMENTED and PENDING do not represent a review decision — skip them so a
|
|
221
|
+
// comment-only interaction cannot clear an active CHANGES_REQUESTED state.
|
|
222
|
+
if (login && state && state !== 'COMMENTED' && state !== 'PENDING') {
|
|
223
|
+
latestStateByReviewer.set(login, state);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
// Only treat a reviewer as "blocking" when BOTH hold:
|
|
227
|
+
// a) their most recent review decision is CHANGES_REQUESTED, AND
|
|
228
|
+
// b) they are a repository collaborator (OWNER/MEMBER/COLLABORATOR association).
|
|
229
|
+
// This prevents external contributors on public repos from triggering the fix
|
|
230
|
+
// provider via a CHANGES_REQUESTED review.
|
|
231
|
+
const humanReviewers = new Set(
|
|
232
|
+
[...latestStateByReviewer.entries()]
|
|
233
|
+
.filter(([login, state]) => state === 'CHANGES_REQUESTED' && trustedReviewerAssocs.has(login))
|
|
234
|
+
.map(([login]) => login)
|
|
235
|
+
);
|
|
236
|
+
|
|
237
|
+
// Guard against a truncated review list: if there are more than 50 reviews, the
|
|
238
|
+
// oldest ones fall off and an active CHANGES_REQUESTED reviewer could be silently
|
|
239
|
+
// excluded. Refuse rather than auto-fix with incomplete information.
|
|
240
|
+
const rawReviews = payload?.data?.repository?.pullRequest?.reviews;
|
|
241
|
+
// `last:50` fetches the most recent 50 reviews; hasPreviousPage=true means older
|
|
242
|
+
// reviews were dropped, so a CHANGES_REQUESTED reviewer could be missing.
|
|
243
|
+
if (rawReviews?.pageInfo?.hasPreviousPage) {
|
|
244
|
+
throw new Error(
|
|
245
|
+
'PR has more than 50 reviews; review history is truncated and auto-fix cannot ' +
|
|
246
|
+
'reliably determine the latest review state per reviewer. Refusing to auto-fix.'
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const rawThreads = payload?.data?.repository?.pullRequest?.reviewThreads;
|
|
251
|
+
if (!rawThreads || !Array.isArray(rawThreads.nodes)) {
|
|
252
|
+
throw new Error('review thread data unavailable');
|
|
253
|
+
}
|
|
254
|
+
if (rawThreads.pageInfo?.hasNextPage) {
|
|
255
|
+
throw new Error(
|
|
256
|
+
'PR has more than 100 review threads; refusing partial auto-fix (resolve some threads first)'
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const threads = rawThreads.nodes.filter((thread) => {
|
|
261
|
+
if (!thread || thread.isResolved || thread.isOutdated) return false;
|
|
262
|
+
if (!Array.isArray(thread.comments?.nodes) || thread.comments.nodes.length === 0) return false;
|
|
263
|
+
if (!thread.path || !thread.line) return false;
|
|
264
|
+
// LEFT-side threads reference deleted lines that no longer exist in the
|
|
265
|
+
// current file; applying a suggestion to LEFT coordinates would target
|
|
266
|
+
// unrelated surviving code. Skip them — the reviewer must re-thread.
|
|
267
|
+
if (thread.diffSide === 'LEFT') return false;
|
|
268
|
+
|
|
269
|
+
const firstComment = thread.comments.nodes[0];
|
|
270
|
+
const body = String(firstComment?.body || '');
|
|
271
|
+
const author = String(firstComment?.author?.login || '').toLowerCase();
|
|
272
|
+
|
|
273
|
+
// gitguardex-authored thread: must carry the MARKER and a blocking severity.
|
|
274
|
+
if (author === trustedAuthor && body.includes(MARKER)) {
|
|
275
|
+
const sev = severityFromBody(body);
|
|
276
|
+
return BLOCKING_SEVERITIES.has(sev);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// Human reviewer thread: the author must have an active CHANGES_REQUESTED review.
|
|
280
|
+
// Skip threads where the bot already replied and is waiting for the reviewer to
|
|
281
|
+
// act — detected by the most recent comment being from the trusted author with
|
|
282
|
+
// MARKER. This prevents re-queueing the same thread on every poll cycle.
|
|
283
|
+
if (humanReviewers.has(author)) {
|
|
284
|
+
const latestComment = thread.latestComment?.nodes?.[0];
|
|
285
|
+
const latestAuthor = String(latestComment?.author?.login || '').toLowerCase();
|
|
286
|
+
const latestBody = String(latestComment?.body || '');
|
|
287
|
+
if (latestAuthor === trustedAuthor && latestBody.includes(MARKER)) {
|
|
288
|
+
return false; // Bot already replied; skip until the reviewer responds.
|
|
289
|
+
}
|
|
290
|
+
return true;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
return false;
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
return { threads, humanReviewers, trustedAuthor };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Convert a review thread to a finding shape that `runReviewFix` understands.
|
|
301
|
+
*
|
|
302
|
+
* For gitguardex threads: extract severity, message, and suggestion from the body.
|
|
303
|
+
* For human threads: severity defaults to 'high'; message is the comment body (trimmed).
|
|
304
|
+
*/
|
|
305
|
+
function threadToFinding(thread, trustedAuthor) {
|
|
306
|
+
const firstComment = thread.comments.nodes[0];
|
|
307
|
+
const body = String(firstComment?.body || '');
|
|
308
|
+
const author = String(firstComment?.author?.login || '').toLowerCase();
|
|
309
|
+
const isBot = author === trustedAuthor && body.includes(MARKER);
|
|
310
|
+
|
|
311
|
+
const severity = isBot ? severityFromBody(body) || 'high' : 'high';
|
|
312
|
+
// For bot threads use the parsed message; for human threads prefix with an explicit
|
|
313
|
+
// data-label so the fix provider treats the reviewer's words as data, not instructions.
|
|
314
|
+
// This prevents prompt-injection via CHANGES_REQUESTED review comments.
|
|
315
|
+
// A human reviewer's latest follow-up in the same thread (e.g. "also handle the
|
|
316
|
+
// timeout case") is part of the request, so carry it alongside the first comment.
|
|
317
|
+
const latest = thread.latestComment?.nodes?.[0];
|
|
318
|
+
const latestBody = String(latest?.body || '');
|
|
319
|
+
const followUp =
|
|
320
|
+
!isBot &&
|
|
321
|
+
latest &&
|
|
322
|
+
latest.id !== firstComment?.id &&
|
|
323
|
+
String(latest.author?.login || '').toLowerCase() === author &&
|
|
324
|
+
latestBody.trim()
|
|
325
|
+
? ` | reviewer follow-up: ${latestBody.replace(/\s+/g, ' ').trim()}`
|
|
326
|
+
: '';
|
|
327
|
+
const rawMessage = isBot
|
|
328
|
+
? messageFromBody(body)
|
|
329
|
+
: `reviewer: ${body.replace(/\s+/g, ' ').trim()}${followUp}`;
|
|
330
|
+
// Cap so human-supplied content doesn't bloat the fix prompt.
|
|
331
|
+
const message = rawMessage.slice(0, 500) || `review thread on ${thread.path}:${thread.line}`;
|
|
332
|
+
const suggestion = isBot ? suggestionFromBody(body) : '';
|
|
333
|
+
|
|
334
|
+
return {
|
|
335
|
+
path: thread.path,
|
|
336
|
+
startLine: thread.startLine || 0,
|
|
337
|
+
line: thread.line,
|
|
338
|
+
severity,
|
|
339
|
+
category: '',
|
|
340
|
+
message,
|
|
341
|
+
suggestion
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Post a reply to a review thread via GraphQL mutation.
|
|
347
|
+
*
|
|
348
|
+
* Returns `{ ok, output }`.
|
|
349
|
+
*/
|
|
350
|
+
function replyToThread(threadId, body, repoRoot, runner = run) {
|
|
351
|
+
const mutation = [
|
|
352
|
+
'mutation($body:String!,$threadId:ID!){',
|
|
353
|
+
'addPullRequestReviewThreadReply(input:{body:$body,pullRequestReviewThreadId:$threadId}){',
|
|
354
|
+
'comment{id}}}'
|
|
355
|
+
].join('');
|
|
356
|
+
const result = runner(
|
|
357
|
+
GH_BIN,
|
|
358
|
+
[
|
|
359
|
+
'api',
|
|
360
|
+
'graphql',
|
|
361
|
+
'-f',
|
|
362
|
+
`query=${mutation}`,
|
|
363
|
+
'-f',
|
|
364
|
+
`body=${body}`,
|
|
365
|
+
'-f',
|
|
366
|
+
`threadId=${threadId}`
|
|
367
|
+
],
|
|
368
|
+
{ cwd: repoRoot, timeout: 60_000, allowFailure: true }
|
|
369
|
+
);
|
|
370
|
+
if (result.status !== 0) {
|
|
371
|
+
return { ok: false, output: (result.stderr || result.stdout || '').trim() };
|
|
372
|
+
}
|
|
373
|
+
let payload;
|
|
374
|
+
try {
|
|
375
|
+
payload = JSON.parse(String(result.stdout || '{}'));
|
|
376
|
+
} catch (error) {
|
|
377
|
+
return { ok: false, output: `JSON parse failed: ${error.message}` };
|
|
378
|
+
}
|
|
379
|
+
if (Array.isArray(payload.errors) && payload.errors.length > 0) {
|
|
380
|
+
return {
|
|
381
|
+
ok: false,
|
|
382
|
+
output: payload.errors
|
|
383
|
+
.map((e) => e.message)
|
|
384
|
+
.filter(Boolean)
|
|
385
|
+
.join('; ')
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
return { ok: true, output: '' };
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* Resolve a review thread via GraphQL mutation.
|
|
393
|
+
*
|
|
394
|
+
* Returns `{ ok, output }`.
|
|
395
|
+
*/
|
|
396
|
+
function resolveThread(threadId, repoRoot, runner = run) {
|
|
397
|
+
const mutation =
|
|
398
|
+
'mutation($thread:ID!){resolveReviewThread(input:{threadId:$thread}){thread{isResolved}}}';
|
|
399
|
+
const result = runner(
|
|
400
|
+
GH_BIN,
|
|
401
|
+
['api', 'graphql', '-f', `query=${mutation}`, '-f', `thread=${threadId}`],
|
|
402
|
+
{ cwd: repoRoot, timeout: 60_000, allowFailure: true }
|
|
403
|
+
);
|
|
404
|
+
if (result.status !== 0) {
|
|
405
|
+
return { ok: false, output: (result.stderr || result.stdout || '').trim() };
|
|
406
|
+
}
|
|
407
|
+
let payload;
|
|
408
|
+
try {
|
|
409
|
+
payload = JSON.parse(String(result.stdout || '{}'));
|
|
410
|
+
} catch (error) {
|
|
411
|
+
return { ok: false, output: `JSON parse failed: ${error.message}` };
|
|
412
|
+
}
|
|
413
|
+
if (Array.isArray(payload.errors) && payload.errors.length > 0) {
|
|
414
|
+
return {
|
|
415
|
+
ok: false,
|
|
416
|
+
output: payload.errors
|
|
417
|
+
.map((e) => e.message)
|
|
418
|
+
.filter(Boolean)
|
|
419
|
+
.join('; ')
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
if (payload?.data?.resolveReviewThread?.thread?.isResolved !== true) {
|
|
423
|
+
return { ok: false, output: 'thread was not marked resolved by GitHub' };
|
|
424
|
+
}
|
|
425
|
+
return { ok: true, output: '' };
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* Old-side (pre-fix) line ranges changed per file between `fromSha` and `toSha`.
|
|
430
|
+
*
|
|
431
|
+
* Returns `Map<path, Array<[start, end]>>`. A pure insertion (`-a,0`) is recorded
|
|
432
|
+
* as `[a, a]` — the line it was inserted after.
|
|
433
|
+
*/
|
|
434
|
+
function fixHunksByPath(worktreePath, fromSha, toSha, runner = run) {
|
|
435
|
+
const hunks = new Map();
|
|
436
|
+
if (!fromSha || !toSha) return hunks;
|
|
437
|
+
// Pin prefixes so diff.noprefix / diff.mnemonicPrefix in user config cannot
|
|
438
|
+
// change the header format this parser relies on.
|
|
439
|
+
const args = ['diff', '-U0', '--no-color', '--no-ext-diff', '--src-prefix=a/', '--dst-prefix=b/'];
|
|
440
|
+
const result = runner('git', [...args, fromSha, toSha], {
|
|
441
|
+
cwd: worktreePath,
|
|
442
|
+
allowFailure: true
|
|
443
|
+
});
|
|
444
|
+
if (result.status !== 0) return hunks;
|
|
445
|
+
let currentPath = '';
|
|
446
|
+
// `--- ` is a file header only between `diff --git` and the first hunk; inside a
|
|
447
|
+
// hunk it is a removed line whose content starts with `-- ` (SQL/Lua comments).
|
|
448
|
+
let inHeader = false;
|
|
449
|
+
for (const line of String(result.stdout || '').split('\n')) {
|
|
450
|
+
if (line.startsWith('diff --git ')) {
|
|
451
|
+
inHeader = true;
|
|
452
|
+
currentPath = '';
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
if (inHeader && line.startsWith('--- ')) {
|
|
456
|
+
// Old-side name; a newly-added file (/dev/null) has no pre-fix lines.
|
|
457
|
+
currentPath = line.startsWith('--- a/') ? line.slice(6) : '';
|
|
458
|
+
continue;
|
|
459
|
+
}
|
|
460
|
+
const match = /^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/.exec(line);
|
|
461
|
+
if (!match) continue;
|
|
462
|
+
inHeader = false;
|
|
463
|
+
if (!currentPath) continue;
|
|
464
|
+
const start = Number(match[1]);
|
|
465
|
+
const count = match[2] === undefined ? 1 : Number(match[2]);
|
|
466
|
+
const end = count === 0 ? start : start + count - 1;
|
|
467
|
+
if (!hunks.has(currentPath)) hunks.set(currentPath, []);
|
|
468
|
+
hunks.get(currentPath).push([start, end]);
|
|
469
|
+
}
|
|
470
|
+
return hunks;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/**
|
|
474
|
+
* True when a fix hunk overlaps the thread's anchored range (± margin).
|
|
475
|
+
* This is the per-thread evidence that the fix targeted THIS thread, not merely
|
|
476
|
+
* some other defect in the same file.
|
|
477
|
+
*/
|
|
478
|
+
function threadTouchedByFix(thread, hunks) {
|
|
479
|
+
const ranges = hunks.get(thread.path);
|
|
480
|
+
if (!ranges || ranges.length === 0) return false;
|
|
481
|
+
const line = Number(thread.line) || 0;
|
|
482
|
+
if (!line) return false;
|
|
483
|
+
const start = Number(thread.startLine) || line;
|
|
484
|
+
const lo = Math.min(start, line) - THREAD_HUNK_MARGIN;
|
|
485
|
+
const hi = Math.max(start, line) + THREAD_HUNK_MARGIN;
|
|
486
|
+
return ranges.some(([a, b]) => a <= hi && b >= lo);
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/** Poll until GitHub reports `expectedSha` as the PR head for `branch`. */
|
|
490
|
+
function waitForPrHead(repoRoot, branch, expectedSha, options = {}) {
|
|
491
|
+
const expected = String(expectedSha || '').trim();
|
|
492
|
+
if (!expected) return false;
|
|
493
|
+
const getHead = options.getHead || getPrHeadOid;
|
|
494
|
+
const sleep = options.sleep || ((seconds) => run('sleep', [String(seconds)], { cwd: repoRoot }));
|
|
495
|
+
const now = options.now || (() => Date.now());
|
|
496
|
+
const deadline = now() + (options.timeoutSeconds || PR_HEAD_WAIT_SECONDS) * 1000;
|
|
497
|
+
// eslint-disable-next-line no-constant-condition
|
|
498
|
+
while (true) {
|
|
499
|
+
const snapshot = getHead(repoRoot, branch);
|
|
500
|
+
if (snapshot && snapshot.headSha === expected) return true;
|
|
501
|
+
if (now() >= deadline) return false;
|
|
502
|
+
sleep(options.pollSeconds || PR_HEAD_POLL_SECONDS);
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* Push the current branch in `worktreePath` to origin.
|
|
508
|
+
*/
|
|
509
|
+
function pushBranch(worktreePath, runner = run) {
|
|
510
|
+
const branch = currentBranchName(worktreePath);
|
|
511
|
+
const result = runner('git', ['push', 'origin', branch], {
|
|
512
|
+
cwd: worktreePath,
|
|
513
|
+
timeout: 120_000,
|
|
514
|
+
allowFailure: true
|
|
515
|
+
});
|
|
516
|
+
if (result.status !== 0) {
|
|
517
|
+
throw new Error(
|
|
518
|
+
`git push origin ${branch} failed: ${(result.stderr || result.stdout || '').trim()}`
|
|
519
|
+
);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* Run the full respond flow for PR `options.pr`.
|
|
525
|
+
*
|
|
526
|
+
* Options:
|
|
527
|
+
* pr {string|number} PR number (required)
|
|
528
|
+
* target {string} Repo root (default: cwd)
|
|
529
|
+
* provider {string} 'codex'|'claude'
|
|
530
|
+
* model {string} Override model
|
|
531
|
+
* timeoutMs {number} Fix provider timeout
|
|
532
|
+
* dryRun {boolean} Print what would happen; no edits, no push
|
|
533
|
+
*
|
|
534
|
+
* Returns a result object; callers inspect `status` for their exit code:
|
|
535
|
+
* 'no-threads' Nothing actionable — exit 0.
|
|
536
|
+
* 'dry-run' Dry run — showed what would happen — exit 0.
|
|
537
|
+
* 'fixed' Fix committed and pushed, threads replied/resolved — exit 0.
|
|
538
|
+
* 'no-op' Fix ran but made no changes — exit 0.
|
|
539
|
+
* 'skipped' Pre-condition refused the run — exit 1 (reason set).
|
|
540
|
+
* 'fix-failed' Provider failed — exit 1.
|
|
541
|
+
* 'push-failed' Push or re-review failed — exit 1 (fixSha set).
|
|
542
|
+
*/
|
|
543
|
+
function prRespond(options = {}, deps = {}) {
|
|
544
|
+
const runner = deps.run || run;
|
|
545
|
+
const repoRoot = String(options.target || process.cwd());
|
|
546
|
+
const pr = String(options.pr || '');
|
|
547
|
+
if (!pr) {
|
|
548
|
+
return { status: 'skipped', reason: '--pr <number> is required' };
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
// 1. Fetch PR metadata.
|
|
552
|
+
const meta = fetchPrMeta(pr, repoRoot, runner);
|
|
553
|
+
if (meta.isCrossRepository) {
|
|
554
|
+
return {
|
|
555
|
+
status: 'skipped',
|
|
556
|
+
reason: `PR #${pr} is from a fork; auto-fix is only available on branches in this repository`
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
const branch = meta.headRefName;
|
|
560
|
+
if (!branch.startsWith(AGENT_BRANCH_PREFIX)) {
|
|
561
|
+
return {
|
|
562
|
+
status: 'skipped',
|
|
563
|
+
reason: `PR #${pr} head branch '${branch}' is not an agent/* branch; auto-fix only runs on agent-managed branches`
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
// 2. Resolve the local worktree for the branch.
|
|
568
|
+
const { worktreePath, worktreeFound } = worktreePathForBranch(repoRoot, branch);
|
|
569
|
+
if (!worktreeFound) {
|
|
570
|
+
return {
|
|
571
|
+
status: 'skipped',
|
|
572
|
+
reason: `no local worktree found for branch '${branch}' — run 'gx branch start' first`
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
// 3. Verify the worktree is on the expected branch and its HEAD matches the PR head.
|
|
577
|
+
const wtBranch = currentBranchName(worktreePath);
|
|
578
|
+
if (wtBranch !== branch) {
|
|
579
|
+
return {
|
|
580
|
+
status: 'skipped',
|
|
581
|
+
reason: `worktree at '${worktreePath}' is on '${wtBranch}', expected '${branch}'`
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
// Primary staleness check: compare local HEAD to the PR head SHA from GitHub.
|
|
586
|
+
// This is authoritative and does not require a network call.
|
|
587
|
+
if (meta.headRefOid) {
|
|
588
|
+
const localHead = String(
|
|
589
|
+
gitRun(worktreePath, ['rev-parse', 'HEAD'], { allowFailure: true }).stdout || ''
|
|
590
|
+
).trim();
|
|
591
|
+
if (localHead && localHead !== meta.headRefOid) {
|
|
592
|
+
return {
|
|
593
|
+
status: 'skipped',
|
|
594
|
+
reason:
|
|
595
|
+
`worktree HEAD (${localHead.slice(0, 8)}) does not match PR head ` +
|
|
596
|
+
`(${meta.headRefOid.slice(0, 8)}) — push the branch first`
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// Secondary staleness check: if origin is reachable, also verify via fetch.
|
|
602
|
+
// Step 1: check whether origin is configured. No remote → skip (local-only repo).
|
|
603
|
+
const remoteCheck = gitRun(worktreePath, ['remote', 'get-url', 'origin'], { allowFailure: true });
|
|
604
|
+
if (remoteCheck.status === 0) {
|
|
605
|
+
// Step 2: origin exists — fetch must succeed so we can compare.
|
|
606
|
+
const fetchResult = gitRun(worktreePath, ['fetch', 'origin', branch], { allowFailure: true });
|
|
607
|
+
if (fetchResult.status !== 0) {
|
|
608
|
+
return {
|
|
609
|
+
status: 'skipped',
|
|
610
|
+
reason: `git fetch origin ${branch} failed — cannot verify worktree HEAD against remote: ${(fetchResult.stderr || '').trim()}`
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
// Step 3: compare local HEAD to FETCH_HEAD — the SHA git wrote for the branch
|
|
614
|
+
// we just fetched. Using refs/remotes/origin/<branch> could be stale if the
|
|
615
|
+
// fetch refspec doesn't update that tracking ref.
|
|
616
|
+
const localHead = String(
|
|
617
|
+
gitRun(worktreePath, ['rev-parse', 'HEAD'], { allowFailure: true }).stdout || ''
|
|
618
|
+
).trim();
|
|
619
|
+
const remoteHead = String(
|
|
620
|
+
gitRun(worktreePath, ['rev-parse', 'FETCH_HEAD'], { allowFailure: true }).stdout || ''
|
|
621
|
+
).trim();
|
|
622
|
+
if (localHead && remoteHead && localHead !== remoteHead) {
|
|
623
|
+
return {
|
|
624
|
+
status: 'skipped',
|
|
625
|
+
reason:
|
|
626
|
+
`worktree HEAD (${localHead.slice(0, 8)}) does not match remote HEAD ` +
|
|
627
|
+
`(${remoteHead.slice(0, 8)}) — pull or push the branch first`
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
const statusResult = gitRun(worktreePath, ['status', '--porcelain', '-z'], {
|
|
633
|
+
allowFailure: true
|
|
634
|
+
});
|
|
635
|
+
const trackedDirty = String(statusResult.stdout || '')
|
|
636
|
+
.split('\0')
|
|
637
|
+
.filter((entry) => {
|
|
638
|
+
if (!entry || entry.length < 4) return false;
|
|
639
|
+
const s = entry.slice(0, 2);
|
|
640
|
+
return s !== '??' && s !== '!!';
|
|
641
|
+
});
|
|
642
|
+
if (trackedDirty.length > 0) {
|
|
643
|
+
return {
|
|
644
|
+
status: 'skipped',
|
|
645
|
+
reason: `worktree has ${trackedDirty.length} uncommitted change(s) — commit or stash first`
|
|
646
|
+
};
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
// 4. Fetch blocking threads.
|
|
650
|
+
let threads;
|
|
651
|
+
let trustedAuthor;
|
|
652
|
+
try {
|
|
653
|
+
({ threads, trustedAuthor } = fetchBlockingThreads(pr, repoRoot, runner));
|
|
654
|
+
} catch (error) {
|
|
655
|
+
return { status: 'skipped', reason: `thread fetch failed: ${error.message}` };
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
if (threads.length === 0) {
|
|
659
|
+
return { status: 'no-threads', threads: [] };
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
// Convert threads to findings.
|
|
663
|
+
const findings = threads.map((t) => threadToFinding(t, trustedAuthor));
|
|
664
|
+
|
|
665
|
+
if (options.dryRun) {
|
|
666
|
+
return {
|
|
667
|
+
status: 'dry-run',
|
|
668
|
+
threads,
|
|
669
|
+
findings,
|
|
670
|
+
worktreePath,
|
|
671
|
+
branch
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
// 5. Run the fix. Record the pre-fix HEAD so each thread can later be matched
|
|
676
|
+
// against the hunks the fix actually changed.
|
|
677
|
+
const preFixSha = String(
|
|
678
|
+
gitRun(worktreePath, ['rev-parse', 'HEAD'], { allowFailure: true }).stdout || ''
|
|
679
|
+
).trim();
|
|
680
|
+
const fixRunner = deps.runReviewFix || runReviewFix;
|
|
681
|
+
const reviewRunner = deps.runPrReview || runPrReview;
|
|
682
|
+
const pushRunner = deps.pushBranch || pushBranch;
|
|
683
|
+
const waitHead = deps.waitForPrHead || waitForPrHead;
|
|
684
|
+
let fixResult;
|
|
685
|
+
try {
|
|
686
|
+
fixResult = fixRunner(
|
|
687
|
+
{
|
|
688
|
+
repoRoot: worktreePath,
|
|
689
|
+
provider: options.provider || 'codex',
|
|
690
|
+
findings,
|
|
691
|
+
timeoutMs: options.timeoutMs,
|
|
692
|
+
expectBranch: branch,
|
|
693
|
+
model: options.model
|
|
694
|
+
},
|
|
695
|
+
deps
|
|
696
|
+
);
|
|
697
|
+
} catch (error) {
|
|
698
|
+
return { status: 'fix-failed', reason: error.message };
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
if (fixResult.status === 'skipped') {
|
|
702
|
+
return { status: 'skipped', reason: fixResult.reason };
|
|
703
|
+
}
|
|
704
|
+
if (fixResult.status === 'no-op') {
|
|
705
|
+
return { status: 'no-op', changedFiles: [], reason: fixResult.reason };
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
// fixResult.status === 'fixed'
|
|
709
|
+
const changedFiles = new Set(fixResult.changedFiles);
|
|
710
|
+
const fixSha = fixResult.sha;
|
|
711
|
+
|
|
712
|
+
// 6. Push the fix.
|
|
713
|
+
try {
|
|
714
|
+
pushRunner(worktreePath, runner);
|
|
715
|
+
} catch (error) {
|
|
716
|
+
return { status: 'push-failed', reason: error.message, fixSha };
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
// 7. Re-run pr-review with --post so the updated diff is reviewed again —
|
|
720
|
+
// but only once GitHub reports the fix commit as the PR head. Otherwise the
|
|
721
|
+
// re-review would fetch the pre-fix diff and a stale verdict would drive
|
|
722
|
+
// resolution. On timeout, skip the re-review: every thread stays open.
|
|
723
|
+
let reReviewResult = null;
|
|
724
|
+
const headCurrent = waitHead(repoRoot, branch, fixSha);
|
|
725
|
+
if (!headCurrent) {
|
|
726
|
+
process.stderr.write(
|
|
727
|
+
`${TOOL_PREFIX} PR head did not reach ${String(fixSha || '').slice(0, 8)}; ` +
|
|
728
|
+
'skipping re-review, threads left open (fix is pushed)\n'
|
|
729
|
+
);
|
|
730
|
+
}
|
|
731
|
+
try {
|
|
732
|
+
if (!headCurrent) throw new Error('stale PR head');
|
|
733
|
+
reReviewResult = reviewRunner(
|
|
734
|
+
{
|
|
735
|
+
pr,
|
|
736
|
+
target: worktreePath,
|
|
737
|
+
provider: options.provider || 'codex',
|
|
738
|
+
model: options.model,
|
|
739
|
+
post: true,
|
|
740
|
+
timeoutMs: options.timeoutMs
|
|
741
|
+
},
|
|
742
|
+
deps
|
|
743
|
+
);
|
|
744
|
+
} catch (error) {
|
|
745
|
+
// Non-fatal: fix is already pushed. Log but don't fail the whole respond.
|
|
746
|
+
if (headCurrent) {
|
|
747
|
+
process.stderr.write(`${TOOL_PREFIX} re-review failed (fix is pushed): ${error.message}\n`);
|
|
748
|
+
}
|
|
749
|
+
reReviewResult = null;
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
// 8. Reply + resolve threads the fix addressed.
|
|
753
|
+
// Resolve a thread only when ALL of these hold:
|
|
754
|
+
// a) re-review ran against the fix head, returned a findings array, AND was
|
|
755
|
+
// posted to the PR (published evidence; posted:false leaves threads open);
|
|
756
|
+
// b) a fix hunk overlaps THIS thread's anchored lines — touching some other
|
|
757
|
+
// part of the same file is not evidence that this thread's defect was fixed;
|
|
758
|
+
// c) the re-review reports no blocking finding left on that file.
|
|
759
|
+
const reReviewUsable = Boolean(
|
|
760
|
+
reReviewResult && Array.isArray(reReviewResult.findings) && reReviewResult.posted === true
|
|
761
|
+
);
|
|
762
|
+
const hunks = (deps.fixHunksByPath || fixHunksByPath)(worktreePath, preFixSha, fixSha, runner);
|
|
763
|
+
const reReviewRemainingPaths = new Set(
|
|
764
|
+
reReviewResult && Array.isArray(reReviewResult.findings)
|
|
765
|
+
? reReviewResult.findings
|
|
766
|
+
.filter((f) => BLOCKING_SEVERITIES.has(String(f && f.severity).toLowerCase()))
|
|
767
|
+
.map((f) => f.path)
|
|
768
|
+
: []
|
|
769
|
+
);
|
|
770
|
+
const resolved = [];
|
|
771
|
+
const skippedReply = [];
|
|
772
|
+
for (let index = 0; index < threads.length; index += 1) {
|
|
773
|
+
const thread = threads[index];
|
|
774
|
+
if (!changedFiles.has(thread.path)) {
|
|
775
|
+
skippedReply.push(thread.id);
|
|
776
|
+
continue;
|
|
777
|
+
}
|
|
778
|
+
if (!reReviewUsable) {
|
|
779
|
+
// Re-review failed, was stale, unposted, or returned no findings array:
|
|
780
|
+
// cannot confirm the fix; leave thread open.
|
|
781
|
+
skippedReply.push(thread.id);
|
|
782
|
+
continue;
|
|
783
|
+
}
|
|
784
|
+
if (!threadTouchedByFix(thread, hunks)) {
|
|
785
|
+
// The file changed, but not near this thread's lines.
|
|
786
|
+
skippedReply.push(thread.id);
|
|
787
|
+
continue;
|
|
788
|
+
}
|
|
789
|
+
if (reReviewRemainingPaths.has(thread.path)) {
|
|
790
|
+
// Re-review still reports a blocking finding on this file; leave thread open.
|
|
791
|
+
skippedReply.push(thread.id);
|
|
792
|
+
continue;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
// Determine whether this thread was authored by the bot.
|
|
796
|
+
const threadFirstComment = thread.comments && thread.comments.nodes && thread.comments.nodes[0];
|
|
797
|
+
const threadAuthor = String(
|
|
798
|
+
(threadFirstComment && threadFirstComment.author && threadFirstComment.author.login) || ''
|
|
799
|
+
).toLowerCase();
|
|
800
|
+
const isBotThread =
|
|
801
|
+
threadAuthor === trustedAuthor &&
|
|
802
|
+
String((threadFirstComment && threadFirstComment.body) || '').includes(MARKER);
|
|
803
|
+
|
|
804
|
+
const replyBody = [
|
|
805
|
+
`${MARKER}`,
|
|
806
|
+
`Applied fix in ${fixSha ? fixSha.slice(0, 8) : 'latest commit'}.`,
|
|
807
|
+
isBotThread
|
|
808
|
+
? 'Thread resolved automatically by gitguardex review-responder.'
|
|
809
|
+
: 'Please review the fix and resolve this thread when satisfied.'
|
|
810
|
+
].join('\n');
|
|
811
|
+
const replyResult = replyToThread(thread.id, replyBody, repoRoot, runner);
|
|
812
|
+
if (!replyResult.ok) {
|
|
813
|
+
process.stderr.write(
|
|
814
|
+
`${TOOL_PREFIX} failed to reply to thread ${thread.id}: ${replyResult.output}\n`
|
|
815
|
+
);
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
// Only auto-resolve gitguardex-bot threads: the fix provider explicitly targeted
|
|
819
|
+
// the structured finding. Human reviewer threads stay open for the reviewer to
|
|
820
|
+
// confirm their specific request was addressed.
|
|
821
|
+
if (!isBotThread) {
|
|
822
|
+
skippedReply.push(thread.id);
|
|
823
|
+
continue;
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
const resolveResult = resolveThread(thread.id, repoRoot, runner);
|
|
827
|
+
if (resolveResult.ok) {
|
|
828
|
+
resolved.push(thread.id);
|
|
829
|
+
} else {
|
|
830
|
+
process.stderr.write(
|
|
831
|
+
`${TOOL_PREFIX} failed to resolve thread ${thread.id}: ${resolveResult.output}\n`
|
|
832
|
+
);
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
return {
|
|
837
|
+
status: 'fixed',
|
|
838
|
+
fixSha,
|
|
839
|
+
changedFiles: fixResult.changedFiles,
|
|
840
|
+
threads,
|
|
841
|
+
resolved,
|
|
842
|
+
skippedReply,
|
|
843
|
+
reReviewPosted: reReviewResult ? Boolean(reReviewResult.posted) : false
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
module.exports = {
|
|
848
|
+
fetchBlockingThreads,
|
|
849
|
+
fetchPrMeta,
|
|
850
|
+
fixHunksByPath,
|
|
851
|
+
messageFromBody,
|
|
852
|
+
prRespond,
|
|
853
|
+
replyToThread,
|
|
854
|
+
resolveThread,
|
|
855
|
+
severityFromBody,
|
|
856
|
+
suggestionFromBody,
|
|
857
|
+
threadToFinding,
|
|
858
|
+
threadTouchedByFix,
|
|
859
|
+
waitForPrHead
|
|
860
|
+
};
|