@h-rig/runtime 0.0.6-alpha.11 → 0.0.6-alpha.12

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.
@@ -1,4 +1,896 @@
1
1
  // @bun
2
+ // packages/runtime/src/control-plane/native/pr-review-gate.ts
3
+ import { mkdirSync, writeFileSync } from "fs";
4
+ import { resolve } from "path";
5
+ function parseJsonObject(value) {
6
+ if (!value?.trim())
7
+ return { value: {}, error: "empty JSON output" };
8
+ try {
9
+ const parsed = JSON.parse(value);
10
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? { value: parsed } : { value: {}, error: "JSON output was not an object" };
11
+ } catch (error) {
12
+ return { value: {}, error: error instanceof Error ? error.message : String(error) };
13
+ }
14
+ }
15
+ function flattenPaginatedArray(value) {
16
+ if (!Array.isArray(value))
17
+ return null;
18
+ if (value.every((entry) => Array.isArray(entry))) {
19
+ return value.flatMap((entry) => entry);
20
+ }
21
+ return value;
22
+ }
23
+ function parseJsonArray(value) {
24
+ if (!value?.trim())
25
+ return { value: [], error: "empty JSON output" };
26
+ try {
27
+ const parsed = JSON.parse(value);
28
+ const flattened = flattenPaginatedArray(parsed);
29
+ return flattened ? { value: flattened } : { value: [], error: "JSON output was not an array" };
30
+ } catch (error) {
31
+ return { value: [], error: error instanceof Error ? error.message : String(error) };
32
+ }
33
+ }
34
+ function parseGithubPrUrl(prUrl) {
35
+ const match = /^https?:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)\/?$/i.exec(prUrl.trim());
36
+ if (!match)
37
+ return null;
38
+ const prNumber = Number.parseInt(match[3], 10);
39
+ if (!Number.isFinite(prNumber))
40
+ return null;
41
+ return { owner: match[1], repo: match[2], repoName: `${match[1]}/${match[2]}`, prNumber };
42
+ }
43
+ function checkName(check) {
44
+ return String(check.name ?? check.context ?? "").trim();
45
+ }
46
+ function checkState(check) {
47
+ return String(check.conclusion ?? check.state ?? check.status ?? "").trim().toLowerCase();
48
+ }
49
+ function isGreptileLabel(value) {
50
+ return String(value ?? "").toLowerCase().includes("greptile");
51
+ }
52
+ function isGreptileGithubLogin(value) {
53
+ const login = String(value ?? "").toLowerCase().replace(/\[bot\]$/, "");
54
+ return login === "greptile" || login === "greptile-ai" || login === "greptileai" || login === "greptile-apps";
55
+ }
56
+ function isPassingCheck(check) {
57
+ const state = checkState(check);
58
+ return ["success", "successful", "passed", "neutral", "skipped", "completed"].includes(state);
59
+ }
60
+ function isPendingCheck(check) {
61
+ const state = checkState(check);
62
+ return ["pending", "queued", "in_progress", "waiting", "requested", "expected", "action_required"].includes(state);
63
+ }
64
+ function isFailingCheck(check) {
65
+ const state = checkState(check);
66
+ return ["failure", "failed", "timed_out", "action_required", "cancelled", "canceled", "error"].includes(state);
67
+ }
68
+ function wildcardToRegExp(pattern) {
69
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
70
+ return new RegExp(`^${escaped}$`, "i");
71
+ }
72
+ function isAllowedFailure(name, allowedFailures) {
73
+ return allowedFailures.some((pattern) => wildcardToRegExp(pattern).test(name));
74
+ }
75
+ function greptileScorePatterns() {
76
+ return [
77
+ /\b(?:confidence\s+score|confidence|rating|score)\s*:?\s*(\d+)\s*\/\s*(\d+)/gi,
78
+ /\b(\d+)\s*\/\s*(\d+)\s*(?:confidence|rating|score)/gi,
79
+ /\bgreptile[^\n]{0,80}?(\d+)\s*\/\s*(\d+)/gi
80
+ ];
81
+ }
82
+ function parseGreptileScores(input) {
83
+ const text = stripHtml(input);
84
+ const seen = new Set;
85
+ const scores = [];
86
+ for (const pattern of greptileScorePatterns()) {
87
+ for (const match of text.matchAll(pattern)) {
88
+ const value = Number.parseInt(match[1] || "", 10);
89
+ const scale = Number.parseInt(match[2] || "", 10);
90
+ if (!Number.isFinite(value) || !Number.isFinite(scale) || scale <= 0)
91
+ continue;
92
+ const raw = match[0] || `${value}/${scale}`;
93
+ const key = `${match.index ?? -1}:${value}/${scale}:${raw.toLowerCase()}`;
94
+ if (seen.has(key))
95
+ continue;
96
+ seen.add(key);
97
+ scores.push({ value, scale, raw });
98
+ }
99
+ }
100
+ return scores;
101
+ }
102
+ function stripHtml(input) {
103
+ return input.replace(/<[^>]+>/g, " ").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/\r/g, "").replace(/\n{3,}/g, `
104
+
105
+ `).trim();
106
+ }
107
+ function containsBlockerText(input) {
108
+ const text = stripHtml(input).replace(/\b(?:no|without|zero)\s+blockers?\b/gi, " ").replace(/\bno\s+changes\s+requested\b/gi, " ");
109
+ return /not safe(?: to merge)?|unsafe(?: to merge)?|do not merge|cannot merge|blockers?|must fix|changes requested|please fix|needs? fix|fix this|address this/i.test(text);
110
+ }
111
+ function containsGreptileNegativeVerdict(input) {
112
+ const text = stripHtml(input).replace(/\s+/g, " ").trim();
113
+ if (!text)
114
+ return false;
115
+ return /\b(?:status|verdict|review state|state|conclusion|result)\s*:?\s*(?:reject(?:ed|ion)?|skip(?:ped)?|fail(?:ed|ure)?|changes[_ ]requested|not approved)\b/i.test(text) || /\bgreptile\b.{0,160}\b(?:reject(?:ed|s|ion)?|skip(?:ped|s)?|fail(?:ed|s|ure)?|changes requested|did not approve|not approved)\b/i.test(text);
116
+ }
117
+ function isStrictFiveOfFive(score) {
118
+ return score.value === 5 && score.scale === 5;
119
+ }
120
+ function containsConflictingScoreText(input) {
121
+ return parseGreptileScores(input).some((score) => !isStrictFiveOfFive(score));
122
+ }
123
+ function firstString(record, keys) {
124
+ for (const key of keys) {
125
+ const value = record[key];
126
+ if (typeof value === "string")
127
+ return value;
128
+ }
129
+ return "";
130
+ }
131
+ function arrayField(record, key) {
132
+ const value = record[key];
133
+ return Array.isArray(value) ? value : [];
134
+ }
135
+ async function runJsonArray(command, args, cwd) {
136
+ const result = await command(args, { cwd });
137
+ const label = `gh ${args.join(" ")}`;
138
+ if (result.exitCode !== 0) {
139
+ return { value: [], error: `${label} failed (${result.exitCode}): ${result.stderr ?? result.stdout ?? ""}`.trim() };
140
+ }
141
+ const parsed = parseJsonArray(result.stdout);
142
+ return parsed.error ? { value: parsed.value, error: `${label} returned invalid JSON: ${parsed.error}` } : { value: parsed.value };
143
+ }
144
+ async function runJsonObject(command, args, cwd) {
145
+ const result = await command(args, { cwd });
146
+ const label = `gh ${args.join(" ")}`;
147
+ if (result.exitCode !== 0) {
148
+ return { value: {}, error: `${label} failed (${result.exitCode}): ${result.stderr ?? result.stdout ?? ""}`.trim() };
149
+ }
150
+ const parsed = parseJsonObject(result.stdout);
151
+ return parsed.error ? { value: parsed.value, error: `${label} returned invalid JSON: ${parsed.error}` } : { value: parsed.value };
152
+ }
153
+ function normalizeStatusCheck(entry) {
154
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
155
+ return null;
156
+ const record = entry;
157
+ const name = firstString(record, ["name", "context"]);
158
+ if (!name.trim())
159
+ return null;
160
+ const output = record.output && typeof record.output === "object" && !Array.isArray(record.output) ? record.output : null;
161
+ const app = record.app && typeof record.app === "object" && !Array.isArray(record.app) ? record.app : null;
162
+ return {
163
+ __typename: typeof record.__typename === "string" ? record.__typename : null,
164
+ name,
165
+ context: typeof record.context === "string" ? record.context : null,
166
+ status: typeof record.status === "string" ? record.status : null,
167
+ state: typeof record.state === "string" ? record.state : null,
168
+ conclusion: typeof record.conclusion === "string" ? record.conclusion : null,
169
+ detailsUrl: typeof record.detailsUrl === "string" ? record.detailsUrl : typeof record.details_url === "string" ? record.details_url : typeof record.html_url === "string" ? record.html_url : typeof record.link === "string" ? record.link : null,
170
+ link: typeof record.link === "string" ? record.link : typeof record.html_url === "string" ? record.html_url : null,
171
+ headSha: typeof record.headSha === "string" ? record.headSha : null,
172
+ head_sha: typeof record.head_sha === "string" ? record.head_sha : null,
173
+ output: output ? {
174
+ title: typeof output.title === "string" ? output.title : null,
175
+ summary: typeof output.summary === "string" ? output.summary : null,
176
+ text: typeof output.text === "string" ? output.text : null
177
+ } : null,
178
+ app: app ? {
179
+ slug: typeof app.slug === "string" ? app.slug : null,
180
+ name: typeof app.name === "string" ? app.name : null,
181
+ owner: app.owner && typeof app.owner === "object" ? app.owner : null
182
+ } : null
183
+ };
184
+ }
185
+ function normalizeReview(entry) {
186
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
187
+ return null;
188
+ const record = entry;
189
+ return {
190
+ id: typeof record.id === "string" ? record.id : typeof record.id === "number" ? String(record.id) : null,
191
+ state: typeof record.state === "string" ? record.state : null,
192
+ body: typeof record.body === "string" ? record.body : null,
193
+ commit_id: typeof record.commit_id === "string" ? record.commit_id : typeof record.commitId === "string" ? record.commitId : record.commit && typeof record.commit === "object" && typeof record.commit.oid === "string" ? record.commit.oid : null,
194
+ html_url: typeof record.html_url === "string" ? record.html_url : typeof record.url === "string" ? record.url : null,
195
+ author: record.author && typeof record.author === "object" ? record.author : record.user && typeof record.user === "object" ? record.user : null
196
+ };
197
+ }
198
+ function normalizeReviewComment(entry) {
199
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
200
+ return null;
201
+ const record = entry;
202
+ const body = typeof record.body === "string" ? record.body : null;
203
+ const path = typeof record.path === "string" ? record.path : null;
204
+ if (!body && !path)
205
+ return null;
206
+ return {
207
+ id: typeof record.id === "string" || typeof record.id === "number" ? record.id : null,
208
+ user: record.user && typeof record.user === "object" ? record.user : null,
209
+ author: record.author && typeof record.author === "object" ? record.author : null,
210
+ body,
211
+ path,
212
+ html_url: typeof record.html_url === "string" ? record.html_url : null,
213
+ url: typeof record.url === "string" ? record.url : null,
214
+ commit_id: typeof record.commit_id === "string" ? record.commit_id : null,
215
+ original_commit_id: typeof record.original_commit_id === "string" ? record.original_commit_id : null
216
+ };
217
+ }
218
+ function normalizeIssueComment(entry) {
219
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
220
+ return null;
221
+ const record = entry;
222
+ const body = typeof record.body === "string" ? record.body : null;
223
+ if (!body)
224
+ return null;
225
+ return {
226
+ id: typeof record.id === "string" || typeof record.id === "number" ? record.id : null,
227
+ user: record.user && typeof record.user === "object" ? record.user : null,
228
+ author: record.author && typeof record.author === "object" ? record.author : null,
229
+ body,
230
+ html_url: typeof record.html_url === "string" ? record.html_url : null,
231
+ url: typeof record.url === "string" ? record.url : null,
232
+ created_at: typeof record.created_at === "string" ? record.created_at : null
233
+ };
234
+ }
235
+ function normalizeReviewThread(entry) {
236
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
237
+ return null;
238
+ const record = entry;
239
+ return {
240
+ id: typeof record.id === "string" ? record.id : null,
241
+ isResolved: typeof record.isResolved === "boolean" ? record.isResolved : null,
242
+ isOutdated: typeof record.isOutdated === "boolean" ? record.isOutdated : null,
243
+ comments: record.comments && typeof record.comments === "object" ? record.comments : null
244
+ };
245
+ }
246
+ function relevantIssueComment(comment) {
247
+ const login = comment.user?.login ?? comment.author?.login ?? "";
248
+ const body = comment.body ?? "";
249
+ return isGreptileGithubLogin(login) || /greptile|blocker|unsafe|not safe|do not merge|must fix|please fix|changes requested|score|confidence|\b\d+\s*\/\s*5\b/i.test(body);
250
+ }
251
+ function latestThreadComment(thread) {
252
+ const nodes = thread.comments?.nodes ?? [];
253
+ return nodes.length > 0 ? nodes[nodes.length - 1] : null;
254
+ }
255
+ function unresolvedThreadSummaries(threads) {
256
+ return threads.flatMap((thread) => {
257
+ if (thread.isResolved === true || thread.isOutdated === true)
258
+ return [];
259
+ const latest = latestThreadComment(thread);
260
+ if (!latest)
261
+ return ["Unresolved review thread"];
262
+ const path = latest.path ? ` on ${latest.path}` : "";
263
+ return [`Unresolved review thread${path}: ${(latest.body ?? "").trim() || "(empty comment)"}`];
264
+ });
265
+ }
266
+ function collectBodies(evidence) {
267
+ return [
268
+ evidence.title ?? "",
269
+ evidence.body,
270
+ ...evidence.reviews.map((review) => review.body ?? ""),
271
+ ...evidence.changedFileReviewComments.map((comment) => comment.body ?? ""),
272
+ ...evidence.relevantIssueComments.map((comment) => comment.body ?? ""),
273
+ ...evidence.reviewThreads.flatMap((thread) => thread.comments?.nodes?.map((comment) => comment.body ?? "") ?? []),
274
+ ...(evidence.apiSignals ?? []).map((signal) => signal.body ?? "")
275
+ ].filter((body) => body.trim().length > 0);
276
+ }
277
+ function bodyExcerpt(body) {
278
+ const text = stripHtml(body).replace(/\s+/g, " ").trim();
279
+ return text.length > 240 ? `${text.slice(0, 237)}...` : text;
280
+ }
281
+ function makeGreptileSignal(input) {
282
+ const scores = parseGreptileScores(input.body);
283
+ const reviewedSha = input.reviewedSha?.trim() || null;
284
+ const current = reviewedSha ? reviewedSha === input.currentHeadSha : null;
285
+ const blocker = input.blocker ?? (containsBlockerText(input.body) || containsGreptileNegativeVerdict(input.body));
286
+ const explicitApproval = input.explicitApproval ?? false;
287
+ return {
288
+ source: input.source,
289
+ trusted: input.trusted,
290
+ authorLogin: input.authorLogin ?? null,
291
+ reviewedSha,
292
+ current,
293
+ stale: current === false,
294
+ score: scores[0] ?? null,
295
+ scores,
296
+ explicitApproval,
297
+ blocker,
298
+ actionable: input.actionable ?? blocker,
299
+ bodyExcerpt: bodyExcerpt(input.body),
300
+ body: input.body,
301
+ allScores: scores
302
+ };
303
+ }
304
+ function reviewAuthorLogin(review) {
305
+ return review.author?.login ?? null;
306
+ }
307
+ function commentAuthorLogin(comment) {
308
+ return comment.user?.login ?? comment.author?.login ?? null;
309
+ }
310
+ function collectGreptileSignals(evidence) {
311
+ const signals = [];
312
+ const contextSources = [
313
+ { source: "pr-title", body: evidence.title ?? "" },
314
+ { source: "pr-body", body: evidence.body }
315
+ ];
316
+ for (const context of contextSources) {
317
+ if (!context.body.trim())
318
+ continue;
319
+ if (!/greptile|score|confidence|\b\d+\s*\/\s*5\b|blocker|unsafe|not safe|do not merge|changes requested/i.test(context.body))
320
+ continue;
321
+ const contextBlocker = containsBlockerText(context.body);
322
+ signals.push(makeGreptileSignal({
323
+ source: context.source,
324
+ body: context.body,
325
+ currentHeadSha: evidence.currentHeadSha,
326
+ trusted: false,
327
+ blocker: contextBlocker,
328
+ actionable: contextBlocker
329
+ }));
330
+ }
331
+ for (const apiSignal of evidence.apiSignals ?? []) {
332
+ const body = [apiSignal.status ? `Status: ${apiSignal.status}` : "", apiSignal.body ?? ""].filter(Boolean).join(`
333
+
334
+ `);
335
+ if (!body.trim())
336
+ continue;
337
+ signals.push(makeGreptileSignal({
338
+ source: "api",
339
+ body,
340
+ currentHeadSha: evidence.currentHeadSha,
341
+ trusted: true,
342
+ reviewedSha: apiSignal.reviewedSha ?? null,
343
+ explicitApproval: false
344
+ }));
345
+ }
346
+ for (const review of evidence.reviews) {
347
+ const login = reviewAuthorLogin(review);
348
+ if (!isGreptileGithubLogin(login))
349
+ continue;
350
+ const state = String(review.state ?? "").toUpperCase();
351
+ const body = [state ? `Review state: ${state}` : "", review.body ?? ""].filter(Boolean).join(`
352
+
353
+ `);
354
+ if (!body.trim())
355
+ continue;
356
+ const dismissed = state === "DISMISSED";
357
+ signals.push(makeGreptileSignal({
358
+ source: "github-review",
359
+ body,
360
+ currentHeadSha: evidence.currentHeadSha,
361
+ trusted: !dismissed,
362
+ authorLogin: login,
363
+ reviewedSha: review.commit_id ?? null,
364
+ explicitApproval: undefined,
365
+ blocker: state === "CHANGES_REQUESTED" || undefined
366
+ }));
367
+ }
368
+ for (const comment of evidence.changedFileReviewComments) {
369
+ const login = commentAuthorLogin(comment);
370
+ const body = comment.body ?? "";
371
+ if (!body.trim() || !isGreptileGithubLogin(login))
372
+ continue;
373
+ signals.push(makeGreptileSignal({
374
+ source: "changed-file-comment",
375
+ body,
376
+ currentHeadSha: evidence.currentHeadSha,
377
+ trusted: true,
378
+ authorLogin: login,
379
+ reviewedSha: comment.commit_id ?? comment.original_commit_id ?? null
380
+ }));
381
+ }
382
+ for (const comment of evidence.relevantIssueComments) {
383
+ const login = commentAuthorLogin(comment);
384
+ const body = comment.body ?? "";
385
+ if (!body.trim() || !isGreptileGithubLogin(login))
386
+ continue;
387
+ signals.push(makeGreptileSignal({
388
+ source: "issue-comment",
389
+ body,
390
+ currentHeadSha: evidence.currentHeadSha,
391
+ trusted: true,
392
+ authorLogin: login
393
+ }));
394
+ }
395
+ for (const thread of evidence.reviewThreads) {
396
+ if (thread.isOutdated === true || thread.isResolved === true)
397
+ continue;
398
+ for (const comment of thread.comments?.nodes ?? []) {
399
+ const login = comment.author?.login ?? null;
400
+ const body = comment.body ?? "";
401
+ if (!body.trim() || !isGreptileGithubLogin(login))
402
+ continue;
403
+ signals.push(makeGreptileSignal({
404
+ source: "review-thread",
405
+ body,
406
+ currentHeadSha: evidence.currentHeadSha,
407
+ trusted: true,
408
+ authorLogin: login
409
+ }));
410
+ }
411
+ }
412
+ for (const check of evidence.checks) {
413
+ if (!isGreptileLabel(checkName(check)))
414
+ continue;
415
+ const reviewedSha = check.headSha ?? check.head_sha ?? null;
416
+ const label = `${checkName(check)} (${checkState(check) || "unknown"})`;
417
+ const body = [label, check.output?.title ?? "", check.output?.summary ?? "", check.output?.text ?? ""].filter((entry) => entry.trim().length > 0).join(`
418
+
419
+ `);
420
+ signals.push(makeGreptileSignal({
421
+ source: "github-check",
422
+ body,
423
+ currentHeadSha: evidence.currentHeadSha,
424
+ trusted: false,
425
+ reviewedSha,
426
+ explicitApproval: false,
427
+ blocker: isFailingCheck(check),
428
+ actionable: isFailingCheck(check)
429
+ }));
430
+ }
431
+ return signals;
432
+ }
433
+ function unresolvedGreptileThreadSummaries(threads) {
434
+ return threads.flatMap((thread) => {
435
+ if (thread.isResolved === true || thread.isOutdated === true)
436
+ return [];
437
+ const comments = thread.comments?.nodes ?? [];
438
+ if (!comments.some((comment) => isGreptileGithubLogin(comment.author?.login)))
439
+ return [];
440
+ const latest = latestThreadComment(thread);
441
+ if (!latest)
442
+ return ["Unresolved Greptile review thread"];
443
+ const path = latest.path ? ` on ${latest.path}` : "";
444
+ return [`Unresolved Greptile review thread${path}: ${(latest.body ?? "").trim() || "(empty comment)"}`];
445
+ });
446
+ }
447
+ function issueLevelBlockerSummaries(comments) {
448
+ return comments.flatMap((comment) => {
449
+ const body = comment.body?.trim() ?? "";
450
+ if (!body || !containsBlockerText(body) && !containsConflictingScoreText(body))
451
+ return [];
452
+ const login = commentAuthorLogin(comment) ?? "unknown";
453
+ const author = isGreptileGithubLogin(login) ? `Greptile issue comment by ${login}` : `Issue-level PR comment by ${login}`;
454
+ return [`${author}: ${body}`];
455
+ });
456
+ }
457
+ function reviewBodyBlockerSummaries(reviews) {
458
+ return reviews.flatMap((review) => {
459
+ const login = reviewAuthorLogin(review) ?? "unknown";
460
+ if (isGreptileGithubLogin(login))
461
+ return [];
462
+ const body = review.body?.trim() ?? "";
463
+ if (!body || !containsBlockerText(body) && !containsConflictingScoreText(body))
464
+ return [];
465
+ const state = review.state ? ` (${review.state})` : "";
466
+ return [`PR review summary by ${login}${state}: ${body}`];
467
+ });
468
+ }
469
+ function signalLabel(signal) {
470
+ const source = signal.source.replace(/-/g, " ");
471
+ const author = signal.authorLogin ? ` by ${signal.authorLogin}` : "";
472
+ const sha = signal.reviewedSha ? ` at ${signal.reviewedSha}` : "";
473
+ return `${source}${author}${sha}`;
474
+ }
475
+ function deriveGreptileEvidence(input) {
476
+ const rawBodies = collectBodies(input);
477
+ const signals = collectGreptileSignals(input);
478
+ const trustedSignals = signals.filter((signal) => signal.trusted);
479
+ const trustedScoreEntries = trustedSignals.flatMap((signal) => signal.allScores.map((score2) => ({ score: score2, signal })));
480
+ const contextScoreEntries = signals.filter((signal) => !signal.trusted).flatMap((signal) => signal.allScores.map((score2) => ({ score: score2, signal })));
481
+ const allScoreEntries = [...trustedScoreEntries, ...contextScoreEntries];
482
+ const staleSignals = signals.filter((signal) => !!signal.reviewedSha && signal.reviewedSha !== input.currentHeadSha && (signal.trusted || signal.source === "github-check"));
483
+ const isCurrentOrUntied = (signal) => !signal.reviewedSha || signal.reviewedSha === input.currentHeadSha;
484
+ const currentOrUntiedScoreEntries = allScoreEntries.filter((entry) => isCurrentOrUntied(entry.signal));
485
+ const lowScoreEntries = currentOrUntiedScoreEntries.filter((entry) => !isStrictFiveOfFive(entry.score));
486
+ const approvingScoreEntry = trustedScoreEntries.find((entry) => entry.signal.reviewedSha === input.currentHeadSha && entry.signal.source !== "github-check" && isStrictFiveOfFive(entry.score)) ?? null;
487
+ const approvedByScore = !!approvingScoreEntry;
488
+ const approvedByExplicitMapping = false;
489
+ const approvingSignal = approvingScoreEntry?.signal ?? null;
490
+ const lowestScore = lowScoreEntries.map((entry) => entry.score).sort((left, right) => left.value - right.value)[0] ?? null;
491
+ const score = lowestScore ?? approvingScoreEntry?.score ?? trustedScoreEntries[0]?.score ?? contextScoreEntries[0]?.score ?? null;
492
+ const failedGreptileChecks = input.checks.filter((check) => isGreptileLabel(checkName(check)) && isFailingCheck(check)).map((check) => `${checkName(check)} (${checkState(check) || "failed"})`);
493
+ const blockerSignals = signals.filter((signal) => signal.source !== "changed-file-comment" && (signal.blocker || signal.actionable) && (!signal.reviewedSha || signal.reviewedSha === input.currentHeadSha));
494
+ const staleBlockingSignals = [];
495
+ const blockers = [
496
+ ...blockerSignals.map((signal) => `${signalLabel(signal)}: ${signal.bodyExcerpt || "blocker text"}`),
497
+ ...reviewBodyBlockerSummaries(input.reviews),
498
+ ...issueLevelBlockerSummaries(input.relevantIssueComments),
499
+ ...lowScoreEntries.map((entry) => `Greptile score from ${signalLabel(entry.signal)} is ${entry.score.value}/${entry.score.scale}; strict merge requires trusted current-head 5/5.`),
500
+ ...staleBlockingSignals.map((signal) => `Greptile blocking signal from ${signalLabel(signal)} is stale; current PR head is ${input.currentHeadSha || "unknown"}.`),
501
+ ...failedGreptileChecks.map((entry) => `Greptile check failed: ${entry}`)
502
+ ];
503
+ const unresolvedComments = [
504
+ ...unresolvedGreptileThreadSummaries(input.reviewThreads)
505
+ ];
506
+ const greptileChecks = input.checks.filter((check) => isGreptileLabel(checkName(check)));
507
+ const greptileReviews = input.reviews.filter((review) => isGreptileGithubLogin(review.author?.login));
508
+ const completedGreptileCheck = greptileChecks.some((check) => {
509
+ const reviewedSha2 = check.headSha ?? check.head_sha ?? null;
510
+ return reviewedSha2 === input.currentHeadSha && (isPassingCheck(check) || isFailingCheck(check));
511
+ });
512
+ const completedGreptileReview = greptileReviews.some((review) => {
513
+ const state = String(review.state ?? "").toUpperCase();
514
+ const completedState = ["APPROVED", "COMMENTED", "CHANGES_REQUESTED"].includes(state) || !!review.body?.trim();
515
+ return completedState && review.commit_id === input.currentHeadSha;
516
+ });
517
+ const approvalReviewedSha = approvingSignal?.reviewedSha ?? null;
518
+ const reviewedSha = approvalReviewedSha ?? staleSignals[0]?.reviewedSha ?? trustedSignals.map((signal) => signal.reviewedSha ?? null).find(Boolean) ?? null;
519
+ const fresh = !!approvalReviewedSha && approvalReviewedSha === input.currentHeadSha;
520
+ const completed = completedGreptileCheck || completedGreptileReview || !!approvingSignal || trustedSignals.some((signal) => signal.source === "api" && signal.reviewedSha === input.currentHeadSha);
521
+ const hasGreptileEvidence = trustedSignals.length > 0 || signals.some((signal) => /greptile/i.test(signal.body));
522
+ const approved = fresh && completed && !blockers.length && !unresolvedComments.length && (approvedByScore || approvedByExplicitMapping);
523
+ const mapping = !hasGreptileEvidence ? "missing" : staleSignals.length > 0 && !approvingSignal ? "stale" : approvedByScore ? "score-5-of-5" : "unproven";
524
+ const source = approvingSignal?.source === "api" ? "api" : approvingSignal?.source === "github-review" ? "github-review" : approvingSignal?.source === "changed-file-comment" || approvingSignal?.source === "issue-comment" || approvingSignal?.source === "review-thread" ? "github-comment" : greptileReviews.length > 0 && greptileChecks.length > 0 ? "combined" : greptileReviews.length > 0 ? "github-review" : greptileChecks.length > 0 ? "github-check" : signals.some((signal) => signal.source === "pr-body" || signal.source === "pr-title") ? "pr-body" : "missing";
525
+ return {
526
+ source,
527
+ currentHeadSha: input.currentHeadSha,
528
+ reviewedSha,
529
+ fresh,
530
+ completed,
531
+ approved,
532
+ score,
533
+ explicitApproval: approvedByExplicitMapping,
534
+ blockers,
535
+ unresolvedComments,
536
+ rawBodies,
537
+ signals: signals.map(({ body: _body, allScores: _allScores, ...signal }) => signal),
538
+ mapping
539
+ };
540
+ }
541
+ function isGreptileCheckDetail(check) {
542
+ return isGreptileLabel(checkName(check)) || isGreptileGithubLogin(check.app?.slug) || isGreptileGithubLogin(check.app?.owner?.login) || isGreptileLabel(check.app?.name);
543
+ }
544
+ async function collectGreptileCheckDetails(input) {
545
+ const checkRunsRead = await runJsonArray(input.command, [
546
+ "api",
547
+ `repos/${input.repoName}/commits/${input.headSha}/check-runs`,
548
+ "--paginate",
549
+ "--slurp",
550
+ "--jq",
551
+ "map(.check_runs // []) | add // []"
552
+ ], input.projectRoot);
553
+ const checkRuns = checkRunsRead.value.map(normalizeStatusCheck).filter((entry) => !!entry).filter(isGreptileCheckDetail);
554
+ return checkRunsRead.error ? { value: checkRuns, error: checkRunsRead.error } : { value: checkRuns };
555
+ }
556
+ async function collectReviewThreads(input) {
557
+ const reviewThreads = [];
558
+ let afterCursor = null;
559
+ for (let page = 0;page < 100; page += 1) {
560
+ const afterLiteral = afterCursor ? JSON.stringify(afterCursor) : "null";
561
+ const threadsResponse = await runJsonObject(input.command, [
562
+ "api",
563
+ "graphql",
564
+ "-F",
565
+ `owner=${input.owner}`,
566
+ "-F",
567
+ `name=${input.name}`,
568
+ "-F",
569
+ `prNumber=${input.prNumber}`,
570
+ "-f",
571
+ `query=query($owner: String!, $name: String!, $prNumber: Int!) { repository(owner:$owner, name:$name) { pullRequest(number:$prNumber) { reviewThreads(first: 100, after: ${afterLiteral}) { nodes { id isResolved isOutdated comments(first: 100) { nodes { author { login } body path url createdAt } pageInfo { hasNextPage endCursor } } } pageInfo { hasNextPage endCursor } } } } }`
572
+ ], input.projectRoot);
573
+ if (threadsResponse.error) {
574
+ return { value: reviewThreads, error: threadsResponse.error };
575
+ }
576
+ const data = threadsResponse.value.data;
577
+ const repository = data?.repository;
578
+ const pullRequest = repository?.pullRequest;
579
+ const threads = pullRequest?.reviewThreads;
580
+ const nodes = threads?.nodes;
581
+ if (!Array.isArray(nodes)) {
582
+ return { value: reviewThreads, error: "GitHub reviewThreads response did not include a nodes array" };
583
+ }
584
+ const normalized = nodes.map(normalizeReviewThread).filter((entry) => !!entry);
585
+ reviewThreads.push(...normalized);
586
+ const truncatedCommentThread = normalized.find((thread) => thread.comments?.pageInfo?.hasNextPage === true);
587
+ if (truncatedCommentThread) {
588
+ return { value: reviewThreads, error: `GitHub review thread ${truncatedCommentThread.id ?? "unknown"} has more than 100 comments; nested pagination is incomplete` };
589
+ }
590
+ const pageInfo = threads?.pageInfo;
591
+ if (!pageInfo) {
592
+ if (nodes.length >= 100) {
593
+ return { value: reviewThreads, error: "GitHub reviewThreads pagination metadata missing after a full page" };
594
+ }
595
+ return { value: reviewThreads };
596
+ }
597
+ if (pageInfo.hasNextPage !== true) {
598
+ return { value: reviewThreads };
599
+ }
600
+ if (typeof pageInfo.endCursor !== "string" || !pageInfo.endCursor.trim()) {
601
+ return { value: reviewThreads, error: "GitHub reviewThreads pagination reported hasNextPage without endCursor" };
602
+ }
603
+ afterCursor = pageInfo.endCursor;
604
+ }
605
+ return { value: reviewThreads, error: "GitHub reviewThreads pagination exceeded 100 pages" };
606
+ }
607
+ async function collectPrReviewEvidence(input) {
608
+ const parsed = parseGithubPrUrl(input.prUrl);
609
+ if (!parsed) {
610
+ throw new Error(`Cannot parse GitHub PR URL: ${input.prUrl}`);
611
+ }
612
+ const readErrors = [];
613
+ const viewRead = await runJsonObject(input.command, [
614
+ "pr",
615
+ "view",
616
+ input.prUrl,
617
+ "--json",
618
+ "title,body,headRefOid,headRefName,baseRefName,state,isDraft,mergeable,mergeStateStatus,reviewDecision,reviews,statusCheckRollup"
619
+ ], input.projectRoot);
620
+ if (viewRead.error)
621
+ readErrors.push(viewRead.error);
622
+ const view = viewRead.value;
623
+ if (!Array.isArray(view.statusCheckRollup)) {
624
+ readErrors.push("gh pr view did not return required statusCheckRollup array");
625
+ }
626
+ if (!Array.isArray(view.reviews)) {
627
+ readErrors.push("gh pr view did not return required reviews array");
628
+ }
629
+ const headSha = firstString(view, ["headRefOid", "headSha", "head_sha"]);
630
+ const statusCheckRollup = arrayField(view, "statusCheckRollup").map(normalizeStatusCheck).filter((entry) => !!entry);
631
+ const reviews = arrayField(view, "reviews").map(normalizeReview).filter((entry) => !!entry);
632
+ const reviewCommentsRead = await runJsonArray(input.command, ["api", `repos/${parsed.repoName}/pulls/${parsed.prNumber}/comments`, "--paginate", "--slurp"], input.projectRoot);
633
+ if (reviewCommentsRead.error)
634
+ readErrors.push(reviewCommentsRead.error);
635
+ const reviewComments = reviewCommentsRead.value.map(normalizeReviewComment).filter((entry) => !!entry);
636
+ const issueCommentsRead = await runJsonArray(input.command, ["api", `repos/${parsed.repoName}/issues/${parsed.prNumber}/comments`, "--paginate", "--slurp"], input.projectRoot);
637
+ if (issueCommentsRead.error)
638
+ readErrors.push(issueCommentsRead.error);
639
+ const issueComments = issueCommentsRead.value.map(normalizeIssueComment).filter((entry) => !!entry).filter(relevantIssueComment);
640
+ const reviewThreadsRead = await collectReviewThreads({
641
+ command: input.command,
642
+ projectRoot: input.projectRoot,
643
+ owner: parsed.owner,
644
+ name: parsed.repo,
645
+ prNumber: parsed.prNumber
646
+ });
647
+ if (reviewThreadsRead.error)
648
+ readErrors.push(reviewThreadsRead.error);
649
+ const reviewThreads = reviewThreadsRead.value;
650
+ const greptileRollupChecks = statusCheckRollup.filter((check) => isGreptileLabel(checkName(check)));
651
+ let greptileCheckDetails = [];
652
+ if (headSha && greptileRollupChecks.length > 0) {
653
+ const checkDetailsRead = await collectGreptileCheckDetails({
654
+ command: input.command,
655
+ projectRoot: input.projectRoot,
656
+ repoName: parsed.repoName,
657
+ headSha
658
+ });
659
+ if (checkDetailsRead.error)
660
+ readErrors.push(checkDetailsRead.error);
661
+ greptileCheckDetails = checkDetailsRead.value;
662
+ if (!checkDetailsRead.error && greptileCheckDetails.length === 0) {
663
+ readErrors.push("Greptile check details could not be found for the current PR head");
664
+ }
665
+ }
666
+ const checksWithGreptileDetails = [...statusCheckRollup, ...greptileCheckDetails];
667
+ const checkFailures = statusCheckRollup.filter((check) => !isGreptileLabel(checkName(check)) && isFailingCheck(check) && !isAllowedFailure(checkName(check), input.allowedFailures ?? [])).map((check) => `Check failed: ${checkName(check)}${check.detailsUrl || check.link ? ` (${check.detailsUrl ?? check.link})` : ""}`);
668
+ const pendingChecks = statusCheckRollup.filter((check) => isPendingCheck(check) && (isGreptileLabel(checkName(check)) || !isAllowedFailure(checkName(check), input.allowedFailures ?? []))).map((check) => `Check pending: ${checkName(check)}`);
669
+ const evidenceBase = {
670
+ title: firstString(view, ["title"]),
671
+ body: firstString(view, ["body"]),
672
+ reviews,
673
+ changedFileReviewComments: reviewComments,
674
+ relevantIssueComments: issueComments,
675
+ reviewThreads,
676
+ checks: checksWithGreptileDetails,
677
+ currentHeadSha: headSha,
678
+ apiSignals: input.apiSignals ?? []
679
+ };
680
+ const greptile = deriveGreptileEvidence(evidenceBase);
681
+ return {
682
+ prUrl: input.prUrl,
683
+ prNumber: parsed.prNumber,
684
+ repoName: parsed.repoName,
685
+ title: evidenceBase.title,
686
+ body: evidenceBase.body,
687
+ headSha,
688
+ headRefName: firstString(view, ["headRefName"]),
689
+ baseRefName: firstString(view, ["baseRefName"]),
690
+ state: firstString(view, ["state"]),
691
+ isDraft: typeof view.isDraft === "boolean" ? view.isDraft : null,
692
+ mergeable: firstString(view, ["mergeable"]),
693
+ mergeStateStatus: firstString(view, ["mergeStateStatus"]),
694
+ reviewDecision: firstString(view, ["reviewDecision"]),
695
+ reviews,
696
+ reviewThreads,
697
+ changedFileReviewComments: reviewComments,
698
+ relevantIssueComments: issueComments,
699
+ statusCheckRollup: checksWithGreptileDetails,
700
+ checkFailures,
701
+ pendingChecks,
702
+ readErrors,
703
+ greptile
704
+ };
705
+ }
706
+ function evaluateEvidence(evidence) {
707
+ const reasons = [];
708
+ const warnings = [];
709
+ let pending = false;
710
+ if (evidence.readErrors.length > 0) {
711
+ reasons.push(...evidence.readErrors.map((error) => `Required PR evidence surface could not be read completely: ${error}`));
712
+ }
713
+ if (!evidence.headSha)
714
+ reasons.push("PR head SHA could not be read; current-head Greptile approval cannot be proven.");
715
+ if (evidence.checkFailures.length > 0)
716
+ reasons.push(...evidence.checkFailures);
717
+ if (evidence.pendingChecks.length > 0) {
718
+ pending = true;
719
+ reasons.push(...evidence.pendingChecks);
720
+ }
721
+ const reviewDecision = String(evidence.reviewDecision ?? "").toUpperCase();
722
+ if (reviewDecision === "CHANGES_REQUESTED" || reviewDecision === "REVIEW_REQUIRED") {
723
+ reasons.push(`Required review is unresolved (${evidence.reviewDecision}).`);
724
+ }
725
+ const unresolvedThreads = unresolvedThreadSummaries(evidence.reviewThreads);
726
+ if (unresolvedThreads.length > 0)
727
+ reasons.push(...unresolvedThreads);
728
+ const greptile = evidence.greptile;
729
+ if (greptile.mapping === "missing")
730
+ reasons.push("Missing Greptile check/review evidence for this PR.");
731
+ const staleSignal = greptile.signals.find((signal) => signal.reviewedSha && signal.reviewedSha !== evidence.headSha);
732
+ if (greptile.mapping === "stale" || greptile.reviewedSha && greptile.reviewedSha !== evidence.headSha || !greptile.approved && staleSignal) {
733
+ reasons.push(`Greptile evidence is stale (reviewed ${greptile.reviewedSha ?? staleSignal?.reviewedSha ?? "unknown"}, current ${evidence.headSha || "unknown"}).`);
734
+ }
735
+ if (!greptile.completed) {
736
+ pending = true;
737
+ reasons.push("Greptile check/review has not completed for the current PR head.");
738
+ }
739
+ if (!greptile.fresh)
740
+ reasons.push("Greptile approval is not tied to the current PR head SHA.");
741
+ if (greptile.score && !(greptile.score.scale === 5 && greptile.score.value === 5)) {
742
+ reasons.push(`Greptile score is ${greptile.score.value}/${greptile.score.scale}; strict merge requires trusted current-head 5/5.`);
743
+ }
744
+ if (!greptile.score && greptile.mapping !== "score-5-of-5") {
745
+ reasons.push("No parseable Greptile 5/5 score or explicit approved mapping was found from trusted current-head evidence; merge is blocked.");
746
+ }
747
+ if (greptile.mapping === "unproven") {
748
+ reasons.push("Greptile approval mapping is unproven; PR body/title or a green check alone cannot approve merge.");
749
+ }
750
+ if (greptile.blockers.length > 0) {
751
+ reasons.push(...greptile.blockers.map((entry) => `Greptile/blocker text: ${entry.trim().slice(0, 500)}`));
752
+ }
753
+ if (greptile.unresolvedComments.length > 0)
754
+ reasons.push(...greptile.unresolvedComments);
755
+ if (!greptile.approved)
756
+ warnings.push(`Greptile approval mapping is ${greptile.mapping}.`);
757
+ return { reasons: Array.from(new Set(reasons)), warnings, pending };
758
+ }
759
+ function evaluateStrictPrMergeGate(evidence) {
760
+ const evaluated = evaluateEvidence(evidence);
761
+ const approved = evaluated.reasons.length === 0 && evidence.greptile.approved;
762
+ return {
763
+ approved,
764
+ pending: evaluated.pending,
765
+ reasons: evaluated.reasons,
766
+ warnings: evaluated.warnings,
767
+ actionableFeedback: evaluated.reasons,
768
+ evidence
769
+ };
770
+ }
771
+ function promptExcerpt(value, maxChars = 4000) {
772
+ return value.length > maxChars ? `${value.slice(0, maxChars)}
773
+
774
+ [truncated for prompt; see full evidence artifact]` : value;
775
+ }
776
+ function promptJsonExcerpt(value, maxChars = 6000) {
777
+ return promptExcerpt(JSON.stringify(value, null, 2), maxChars);
778
+ }
779
+ function buildStrictPrGateSteeringPrompt(result) {
780
+ const evidence = result.evidence;
781
+ const unresolvedReviewThreads = evidence.reviewThreads.filter((thread) => thread.isResolved !== true && thread.isOutdated !== true);
782
+ const lines = [
783
+ `Strict PR merge gate blocked ${evidence.prUrl}.`,
784
+ `PR title: ${evidence.title || "(empty)"}`,
785
+ `Current PR head SHA: ${evidence.headSha || "unknown"}`,
786
+ `Greptile mapping: ${evidence.greptile.mapping}`,
787
+ evidence.greptile.score ? `Greptile score: ${evidence.greptile.score.value}/${evidence.greptile.score.scale}` : "Greptile score: not proven",
788
+ "",
789
+ "Gate reasons:",
790
+ ...result.reasons.length ? result.reasons.map((reason) => `- ${reason}`) : ["- No reasons recorded"],
791
+ "",
792
+ "Required evidence read status:",
793
+ evidence.readErrors.length ? JSON.stringify(evidence.readErrors, null, 2) : "All required PR evidence surfaces were read completely.",
794
+ "",
795
+ "Full PR title:",
796
+ evidence.title || "(empty)",
797
+ "",
798
+ "PR body excerpt:",
799
+ evidence.body ? promptExcerpt(evidence.body) : "(empty)",
800
+ "",
801
+ "All review comments on changed files:",
802
+ evidence.changedFileReviewComments.length ? promptJsonExcerpt(evidence.changedFileReviewComments) : "[]",
803
+ "",
804
+ "Unresolved review threads:",
805
+ unresolvedReviewThreads.length ? promptJsonExcerpt(unresolvedReviewThreads) : "[]",
806
+ "",
807
+ "Relevant issue-level PR comments:",
808
+ evidence.relevantIssueComments.length ? promptJsonExcerpt(evidence.relevantIssueComments) : "[]",
809
+ "",
810
+ "CI/check failures and pending checks:",
811
+ promptJsonExcerpt({ failures: evidence.checkFailures, pending: evidence.pendingChecks, rollup: evidence.statusCheckRollup }),
812
+ "",
813
+ "Greptile evidence:",
814
+ promptJsonExcerpt(evidence.greptile)
815
+ ];
816
+ if (result.artifacts) {
817
+ lines.push("", "Full evidence artifacts:", JSON.stringify(result.artifacts, null, 2));
818
+ }
819
+ return lines.join(`
820
+ `);
821
+ }
822
+ function persistPrReviewCycleArtifacts(input) {
823
+ const cycleName = input.final ? `${input.cycle}-final` : String(input.cycle);
824
+ const taskArtifactRoot = input.artifactRoot?.trim() ? input.artifactRoot : resolve(input.projectRoot, "artifacts", input.taskId);
825
+ const root = resolve(taskArtifactRoot, "pr-review-cycles", cycleName);
826
+ mkdirSync(root, { recursive: true });
827
+ const finalMergeGateResultPath = input.final ? resolve(taskArtifactRoot, "merge-gate-final.json") : undefined;
828
+ const paths = {
829
+ root,
830
+ prTitlePath: resolve(root, "pr-title.md"),
831
+ prBodyPath: resolve(root, "pr-body.md"),
832
+ prCommentsPath: resolve(root, "pr-comments.json"),
833
+ reviewThreadsPath: resolve(root, "review-threads.json"),
834
+ reviewCommentsPath: resolve(root, "review-comments.json"),
835
+ checkRollupPath: resolve(root, "check-rollup.json"),
836
+ greptileEvidencePath: resolve(root, "greptile-evidence.json"),
837
+ mergeGateResultPath: resolve(root, "merge-gate-result.json"),
838
+ steeringPromptPath: resolve(root, "agent-steering-prompt.md"),
839
+ ...finalMergeGateResultPath ? { finalMergeGateResultPath } : {}
840
+ };
841
+ writeFileSync(paths.prTitlePath, input.result.evidence.title || "", "utf8");
842
+ writeFileSync(paths.prBodyPath, input.result.evidence.body || "", "utf8");
843
+ writeFileSync(paths.prCommentsPath, `${JSON.stringify(input.result.evidence.relevantIssueComments, null, 2)}
844
+ `, "utf8");
845
+ writeFileSync(paths.reviewThreadsPath, `${JSON.stringify(input.result.evidence.reviewThreads, null, 2)}
846
+ `, "utf8");
847
+ writeFileSync(paths.reviewCommentsPath, `${JSON.stringify(input.result.evidence.changedFileReviewComments, null, 2)}
848
+ `, "utf8");
849
+ writeFileSync(paths.checkRollupPath, `${JSON.stringify(input.result.evidence.statusCheckRollup, null, 2)}
850
+ `, "utf8");
851
+ writeFileSync(paths.greptileEvidencePath, `${JSON.stringify(input.result.evidence.greptile, null, 2)}
852
+ `, "utf8");
853
+ const mergeGatePayload = {
854
+ approved: input.result.approved,
855
+ pending: input.result.pending,
856
+ reasons: input.result.reasons,
857
+ warnings: input.result.warnings,
858
+ actionableFeedback: input.result.actionableFeedback,
859
+ prUrl: input.result.evidence.prUrl,
860
+ title: input.result.evidence.title,
861
+ headSha: input.result.evidence.headSha,
862
+ readErrors: input.result.evidence.readErrors,
863
+ greptile: input.result.evidence.greptile,
864
+ evidence: input.result.evidence,
865
+ cycleArtifactRoot: root
866
+ };
867
+ writeFileSync(paths.mergeGateResultPath, `${JSON.stringify(mergeGatePayload, null, 2)}
868
+ `, "utf8");
869
+ if (paths.finalMergeGateResultPath) {
870
+ writeFileSync(paths.finalMergeGateResultPath, `${JSON.stringify(mergeGatePayload, null, 2)}
871
+ `, "utf8");
872
+ }
873
+ writeFileSync(paths.steeringPromptPath, input.steeringPrompt, "utf8");
874
+ return paths;
875
+ }
876
+ async function runStrictPrMergeGate(input) {
877
+ const evidence = await collectPrReviewEvidence(input);
878
+ const base = evaluateStrictPrMergeGate(evidence);
879
+ const preliminaryPrompt = buildStrictPrGateSteeringPrompt({ ...base, artifacts: undefined });
880
+ const artifacts = persistPrReviewCycleArtifacts({
881
+ projectRoot: input.projectRoot,
882
+ taskId: input.taskId,
883
+ cycle: input.cycle,
884
+ artifactRoot: input.artifactRoot,
885
+ result: base,
886
+ steeringPrompt: preliminaryPrompt,
887
+ final: input.final
888
+ });
889
+ const steeringPrompt = buildStrictPrGateSteeringPrompt({ ...base, artifacts });
890
+ writeFileSync(artifacts.steeringPromptPath, steeringPrompt, "utf8");
891
+ return { ...base, artifacts, steeringPrompt };
892
+ }
893
+
2
894
  // packages/runtime/src/control-plane/native/pr-automation.ts
3
895
  var UPLOADED_SNAPSHOT_PR_MARKER = "<!-- rig:uploaded-snapshot -->";
4
896
  function positiveInt(value, fallback) {
@@ -6,7 +898,7 @@ function positiveInt(value, fallback) {
6
898
  }
7
899
  function resolvePrAutomationLimits(config) {
8
900
  return {
9
- maxPrFixIterations: positiveInt(config?.automation?.maxPrFixIterations, 30)
901
+ maxPrFixIterations: positiveInt(config?.automation?.maxPrFixIterations, 100500)
10
902
  };
11
903
  }
12
904
  function buildPrAutomationBody(input) {
@@ -24,24 +916,24 @@ function buildPrAutomationBody(input) {
24
916
  return lines.join(`
25
917
  `);
26
918
  }
27
- function wildcardToRegExp(pattern) {
919
+ function wildcardToRegExp2(pattern) {
28
920
  const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
29
921
  return new RegExp(`^${escaped}$`, "i");
30
922
  }
31
- function isAllowedFailure(name, allowedFailures) {
32
- return allowedFailures.some((pattern) => wildcardToRegExp(pattern).test(name));
923
+ function isAllowedFailure2(name, allowedFailures) {
924
+ return allowedFailures.some((pattern) => wildcardToRegExp2(pattern).test(name));
33
925
  }
34
- function isPendingCheck(check) {
926
+ function isPendingCheck2(check) {
35
927
  const conclusion = String(check.conclusion ?? "").toLowerCase();
36
928
  const state = String(check.state ?? check.status ?? "").toLowerCase();
37
929
  return ["pending", "queued", "in_progress", "waiting", "requested", "expected", "action_required"].includes(conclusion) || ["pending", "queued", "in_progress", "waiting", "requested", "expected"].includes(state);
38
930
  }
39
- function isPassingCheck(check) {
931
+ function isPassingCheck2(check) {
40
932
  const conclusion = String(check.conclusion ?? "").toLowerCase();
41
933
  const state = String(check.state ?? check.status ?? "").toLowerCase();
42
934
  return ["success", "successful", "passed", "neutral", "skipped"].includes(conclusion) || ["success", "successful", "passed", "completed"].includes(state);
43
935
  }
44
- function isFailingCheck(check) {
936
+ function isFailingCheck2(check) {
45
937
  const conclusion = String(check.conclusion ?? "").toLowerCase();
46
938
  const state = String(check.state ?? check.status ?? "").toLowerCase();
47
939
  return ["failure", "failed", "timed_out", "action_required", "cancelled", "error"].includes(conclusion) || ["failure", "failed", "timed_out", "action_required", "cancelled", "error"].includes(state);
@@ -51,9 +943,9 @@ function collectPendingPrChecks(input) {
51
943
  const pending = [];
52
944
  for (const check of input.checks ?? []) {
53
945
  const name = check.name.trim();
54
- if (!name || isAllowedFailure(name, allowedFailures))
946
+ if (!name || isAllowedFailure2(name, allowedFailures))
55
947
  continue;
56
- if (isPendingCheck(check) && !isPassingCheck(check))
948
+ if (isPendingCheck2(check) && !isPassingCheck2(check))
57
949
  pending.push(name);
58
950
  }
59
951
  return pending;
@@ -63,7 +955,7 @@ function collectActionablePrFeedback(input) {
63
955
  const feedback = [];
64
956
  for (const check of input.checks ?? []) {
65
957
  const name = check.name.trim();
66
- if (!name || !isFailingCheck(check) || isAllowedFailure(name, allowedFailures))
958
+ if (!name || !isFailingCheck2(check) || isAllowedFailure2(name, allowedFailures))
67
959
  continue;
68
960
  feedback.push(`Check failed: ${name}${check.detailsUrl ? ` (${check.detailsUrl})` : ""}`);
69
961
  }
@@ -77,7 +969,7 @@ function collectActionablePrFeedback(input) {
77
969
  }
78
970
  return feedback;
79
971
  }
80
- function parseJsonArray(value) {
972
+ function parseJsonArray2(value) {
81
973
  if (!value?.trim())
82
974
  return [];
83
975
  try {
@@ -88,7 +980,7 @@ function parseJsonArray(value) {
88
980
  }
89
981
  }
90
982
  function parsePrChecks(value) {
91
- return parseJsonArray(value).flatMap((entry) => {
983
+ return parseJsonArray2(value).flatMap((entry) => {
92
984
  if (!entry || typeof entry !== "object")
93
985
  return [];
94
986
  const record = entry;
@@ -335,6 +1227,10 @@ async function runRepoDefaultMerge(input) {
335
1227
  const merge = input.config?.merge ?? {};
336
1228
  if (merge.mode === "off")
337
1229
  return;
1230
+ const matchHeadSha = input.matchHeadSha?.trim();
1231
+ if (!matchHeadSha) {
1232
+ throw new Error(`Refusing to merge ${input.prUrl}: strict merge gate did not provide a current head SHA.`);
1233
+ }
338
1234
  const method = merge.method ?? "repo-default";
339
1235
  const args = ["pr", "merge", input.prUrl];
340
1236
  if (method === "repo-default") {
@@ -342,6 +1238,7 @@ async function runRepoDefaultMerge(input) {
342
1238
  } else {
343
1239
  args.push(`--${method}`);
344
1240
  }
1241
+ args.push("--match-head-commit", matchHeadSha);
345
1242
  if (merge.deleteBranch === true) {
346
1243
  args.push("--delete-branch");
347
1244
  }
@@ -350,6 +1247,23 @@ async function runRepoDefaultMerge(input) {
350
1247
  }
351
1248
  await runChecked(input.command, args, input.cwd);
352
1249
  }
1250
+ function shouldAttemptRigMerge(config) {
1251
+ const mode = config?.merge?.mode;
1252
+ return mode !== "off" && mode !== "pr-ready";
1253
+ }
1254
+ function isPendingOnlyGate(result) {
1255
+ if (!result.pending)
1256
+ return false;
1257
+ const evidence = result.evidence;
1258
+ if (evidence.readErrors.length > 0 || evidence.checkFailures.length > 0)
1259
+ return false;
1260
+ if (evidence.greptile.blockers.length > 0 || evidence.greptile.unresolvedComments.length > 0)
1261
+ return false;
1262
+ const conflictingScore = evidence.greptile.signals.some((signal) => (!signal.reviewedSha || signal.reviewedSha === evidence.headSha) && signal.score && !(signal.score.scale === 5 && signal.score.value === 5));
1263
+ if (conflictingScore)
1264
+ return false;
1265
+ return evidence.pendingChecks.length > 0 || !evidence.greptile.completed || evidence.greptile.mapping === "missing" || evidence.greptile.mapping === "stale" || evidence.greptile.mapping === "unproven";
1266
+ }
353
1267
  async function runPrAutomation(input) {
354
1268
  const prConfig = input.config?.pr ?? {};
355
1269
  if (prConfig.mode === "off" || prConfig.mode === "ask") {
@@ -388,45 +1302,103 @@ ${createResult.stdout ?? ""}`) : null;
388
1302
  await input.lifecycle?.onPrOpened?.({ prUrl });
389
1303
  const { maxPrFixIterations } = resolvePrAutomationLimits(input.config);
390
1304
  let latestFeedback = [];
1305
+ let pendingElapsedMs = 0;
1306
+ const shouldMerge = shouldAttemptRigMerge(input.config);
391
1307
  for (let iteration = 1;iteration <= maxPrFixIterations; iteration += 1) {
392
1308
  await input.lifecycle?.onReviewCiStarted?.({ prUrl, iteration });
393
- const checks = prConfig.watchChecks === false ? [] : await readPrChecks({ prUrl, command: input.command, cwd: input.projectRoot });
394
- const reviewThreads = prConfig.autoFixReview === false ? [] : parsePrViewReviewThreads((await runChecked(input.command, ["pr", "view", prUrl, "--json", "reviewDecision,reviews"], input.projectRoot)).stdout);
395
- latestFeedback = collectActionablePrFeedback({
396
- checks,
397
- reviewThreads,
1309
+ if (!shouldMerge) {
1310
+ const checks = prConfig.watchChecks === false ? [] : await readPrChecks({ prUrl, command: input.command, cwd: input.projectRoot });
1311
+ const reviewThreads = prConfig.autoFixReview === false ? [] : parsePrViewReviewThreads((await runChecked(input.command, ["pr", "view", prUrl, "--json", "reviewDecision,reviews"], input.projectRoot)).stdout);
1312
+ latestFeedback = collectActionablePrFeedback({
1313
+ checks,
1314
+ reviewThreads,
1315
+ allowedFailures: input.config?.merge?.allowedFailures ?? []
1316
+ });
1317
+ const pendingChecks = collectPendingPrChecks({ checks, allowedFailures: input.config?.merge?.allowedFailures ?? [] });
1318
+ if (latestFeedback.length === 0 && pendingChecks.length > 0) {
1319
+ const timeoutMs = positiveInt(prConfig.pendingTimeoutMs, 600000);
1320
+ const pollMs = positiveInt(prConfig.pendingPollMs, 15000);
1321
+ if (iteration >= maxPrFixIterations || timeoutMs <= 0 || pendingElapsedMs >= timeoutMs) {
1322
+ return { status: "needs_attention", prUrl, iterations: iteration, actionableFeedback: pendingChecks.map((name) => `Check still pending: ${name}`), merged: false };
1323
+ }
1324
+ const sleepMs = Math.min(pollMs, timeoutMs - pendingElapsedMs);
1325
+ await (input.sleep ?? Bun.sleep)(sleepMs);
1326
+ pendingElapsedMs += sleepMs;
1327
+ continue;
1328
+ }
1329
+ if (latestFeedback.length === 0) {
1330
+ pendingElapsedMs = 0;
1331
+ return { status: "opened", prUrl, iterations: iteration, actionableFeedback: [], merged: false };
1332
+ }
1333
+ pendingElapsedMs = 0;
1334
+ if (iteration >= maxPrFixIterations || prConfig.autoFixChecks === false && prConfig.autoFixReview === false) {
1335
+ return { status: "needs_attention", prUrl, iterations: iteration, actionableFeedback: latestFeedback, merged: false };
1336
+ }
1337
+ await input.lifecycle?.onFeedback?.({ prUrl, iteration, feedback: latestFeedback });
1338
+ await input.steerPi([
1339
+ `PR automation found actionable feedback on ${prUrl}.`,
1340
+ `Fix iteration ${iteration + 1}/${maxPrFixIterations}.`,
1341
+ "",
1342
+ ...latestFeedback.map((entry) => `- ${entry}`)
1343
+ ].join(`
1344
+ `));
1345
+ continue;
1346
+ }
1347
+ const gate = await runStrictPrMergeGate({
1348
+ projectRoot: input.projectRoot,
1349
+ prUrl,
1350
+ taskId: input.taskId,
1351
+ runId: input.runId,
1352
+ cycle: iteration,
1353
+ command: input.command,
1354
+ artifactRoot: input.artifactRoot,
398
1355
  allowedFailures: input.config?.merge?.allowedFailures ?? []
399
1356
  });
400
- const pendingChecks = collectPendingPrChecks({ checks, allowedFailures: input.config?.merge?.allowedFailures ?? [] });
401
- if (latestFeedback.length === 0 && pendingChecks.length > 0) {
402
- const timeoutMs = positiveInt(prConfig.pendingTimeoutMs, 600000);
403
- const pollMs = positiveInt(prConfig.pendingPollMs, 15000);
404
- if (iteration >= maxPrFixIterations || timeoutMs <= 0) {
405
- return { status: "needs_attention", prUrl, iterations: iteration, actionableFeedback: pendingChecks.map((name) => `Check still pending: ${name}`), merged: false };
1357
+ latestFeedback = [...gate.actionableFeedback];
1358
+ if (gate.approved) {
1359
+ pendingElapsedMs = 0;
1360
+ const finalGate = await runStrictPrMergeGate({
1361
+ projectRoot: input.projectRoot,
1362
+ prUrl,
1363
+ taskId: input.taskId,
1364
+ runId: input.runId,
1365
+ cycle: iteration,
1366
+ command: input.command,
1367
+ artifactRoot: input.artifactRoot,
1368
+ allowedFailures: input.config?.merge?.allowedFailures ?? [],
1369
+ final: true
1370
+ });
1371
+ if (finalGate.approved) {
1372
+ await input.lifecycle?.onMergeStarted?.({ prUrl });
1373
+ await runRepoDefaultMerge({ prUrl, config: input.config, command: input.command, cwd: input.projectRoot, matchHeadSha: finalGate.evidence.headSha });
1374
+ await input.lifecycle?.onMerged?.({ prUrl });
1375
+ return { status: "merged", prUrl, iterations: iteration, actionableFeedback: [], merged: true };
406
1376
  }
407
- await (input.sleep ?? Bun.sleep)(Math.min(pollMs, timeoutMs));
1377
+ latestFeedback = [...finalGate.actionableFeedback];
1378
+ if (iteration >= maxPrFixIterations || prConfig.autoFixChecks === false && prConfig.autoFixReview === false) {
1379
+ return { status: "needs_attention", prUrl, iterations: iteration, actionableFeedback: latestFeedback, merged: false };
1380
+ }
1381
+ await input.lifecycle?.onFeedback?.({ prUrl, iteration, feedback: latestFeedback });
1382
+ await input.steerPi(finalGate.steeringPrompt);
408
1383
  continue;
409
1384
  }
410
- if (latestFeedback.length === 0) {
411
- if (input.config?.merge?.mode === "off" || input.config?.merge?.mode === "pr-ready") {
412
- return { status: "opened", prUrl, iterations: iteration, actionableFeedback: [], merged: false };
1385
+ if (isPendingOnlyGate(gate)) {
1386
+ const timeoutMs = positiveInt(prConfig.pendingTimeoutMs, 600000);
1387
+ const pollMs = positiveInt(prConfig.pendingPollMs, 15000);
1388
+ if (iteration >= maxPrFixIterations || timeoutMs <= 0 || pendingElapsedMs >= timeoutMs) {
1389
+ return { status: "needs_attention", prUrl, iterations: iteration, actionableFeedback: latestFeedback, merged: false };
413
1390
  }
414
- await input.lifecycle?.onMergeStarted?.({ prUrl });
415
- await runRepoDefaultMerge({ prUrl, config: input.config, command: input.command, cwd: input.projectRoot });
416
- await input.lifecycle?.onMerged?.({ prUrl });
417
- return { status: "merged", prUrl, iterations: iteration, actionableFeedback: [], merged: true };
1391
+ const sleepMs = Math.min(pollMs, timeoutMs - pendingElapsedMs);
1392
+ await (input.sleep ?? Bun.sleep)(sleepMs);
1393
+ pendingElapsedMs += sleepMs;
1394
+ continue;
418
1395
  }
1396
+ pendingElapsedMs = 0;
419
1397
  if (iteration >= maxPrFixIterations || prConfig.autoFixChecks === false && prConfig.autoFixReview === false) {
420
1398
  return { status: "needs_attention", prUrl, iterations: iteration, actionableFeedback: latestFeedback, merged: false };
421
1399
  }
422
1400
  await input.lifecycle?.onFeedback?.({ prUrl, iteration, feedback: latestFeedback });
423
- await input.steerPi([
424
- `PR automation found actionable feedback on ${prUrl}.`,
425
- `Fix iteration ${iteration + 1}/${maxPrFixIterations}.`,
426
- "",
427
- ...latestFeedback.map((entry) => `- ${entry}`)
428
- ].join(`
429
- `));
1401
+ await input.steerPi(gate.steeringPrompt);
430
1402
  }
431
1403
  return { status: "needs_attention", prUrl, iterations: maxPrFixIterations, actionableFeedback: latestFeedback, merged: false };
432
1404
  }