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

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.
@@ -0,0 +1,905 @@
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 parseGreptileScore(input) {
103
+ return parseGreptileScores(input)[0] ?? null;
104
+ }
105
+ function stripHtml(input) {
106
+ return input.replace(/<[^>]+>/g, " ").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/\r/g, "").replace(/\n{3,}/g, `
107
+
108
+ `).trim();
109
+ }
110
+ function containsBlockerText(input) {
111
+ const text = stripHtml(input).replace(/\b(?:no|without|zero)\s+blockers?\b/gi, " ").replace(/\bno\s+changes\s+requested\b/gi, " ");
112
+ 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);
113
+ }
114
+ function isStrictFiveOfFive(score) {
115
+ return score.value === 5 && score.scale === 5;
116
+ }
117
+ function containsConflictingScoreText(input) {
118
+ return parseGreptileScores(input).some((score) => !isStrictFiveOfFive(score));
119
+ }
120
+ function firstString(record, keys) {
121
+ for (const key of keys) {
122
+ const value = record[key];
123
+ if (typeof value === "string")
124
+ return value;
125
+ }
126
+ return "";
127
+ }
128
+ function arrayField(record, key) {
129
+ const value = record[key];
130
+ return Array.isArray(value) ? value : [];
131
+ }
132
+ async function runJsonArray(command, args, cwd) {
133
+ const result = await command(args, { cwd });
134
+ const label = `gh ${args.join(" ")}`;
135
+ if (result.exitCode !== 0) {
136
+ return { value: [], error: `${label} failed (${result.exitCode}): ${result.stderr ?? result.stdout ?? ""}`.trim() };
137
+ }
138
+ const parsed = parseJsonArray(result.stdout);
139
+ return parsed.error ? { value: parsed.value, error: `${label} returned invalid JSON: ${parsed.error}` } : { value: parsed.value };
140
+ }
141
+ async function runJsonObject(command, args, cwd) {
142
+ const result = await command(args, { cwd });
143
+ const label = `gh ${args.join(" ")}`;
144
+ if (result.exitCode !== 0) {
145
+ return { value: {}, error: `${label} failed (${result.exitCode}): ${result.stderr ?? result.stdout ?? ""}`.trim() };
146
+ }
147
+ const parsed = parseJsonObject(result.stdout);
148
+ return parsed.error ? { value: parsed.value, error: `${label} returned invalid JSON: ${parsed.error}` } : { value: parsed.value };
149
+ }
150
+ function normalizeStatusCheck(entry) {
151
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
152
+ return null;
153
+ const record = entry;
154
+ const name = firstString(record, ["name", "context"]);
155
+ if (!name.trim())
156
+ return null;
157
+ const output = record.output && typeof record.output === "object" && !Array.isArray(record.output) ? record.output : null;
158
+ const app = record.app && typeof record.app === "object" && !Array.isArray(record.app) ? record.app : null;
159
+ return {
160
+ __typename: typeof record.__typename === "string" ? record.__typename : null,
161
+ name,
162
+ context: typeof record.context === "string" ? record.context : null,
163
+ status: typeof record.status === "string" ? record.status : null,
164
+ state: typeof record.state === "string" ? record.state : null,
165
+ conclusion: typeof record.conclusion === "string" ? record.conclusion : null,
166
+ 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,
167
+ link: typeof record.link === "string" ? record.link : typeof record.html_url === "string" ? record.html_url : null,
168
+ headSha: typeof record.headSha === "string" ? record.headSha : null,
169
+ head_sha: typeof record.head_sha === "string" ? record.head_sha : null,
170
+ output: output ? {
171
+ title: typeof output.title === "string" ? output.title : null,
172
+ summary: typeof output.summary === "string" ? output.summary : null,
173
+ text: typeof output.text === "string" ? output.text : null
174
+ } : null,
175
+ app: app ? {
176
+ slug: typeof app.slug === "string" ? app.slug : null,
177
+ name: typeof app.name === "string" ? app.name : null,
178
+ owner: app.owner && typeof app.owner === "object" ? app.owner : null
179
+ } : null
180
+ };
181
+ }
182
+ function normalizeReview(entry) {
183
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
184
+ return null;
185
+ const record = entry;
186
+ return {
187
+ id: typeof record.id === "string" ? record.id : typeof record.id === "number" ? String(record.id) : null,
188
+ state: typeof record.state === "string" ? record.state : null,
189
+ body: typeof record.body === "string" ? record.body : null,
190
+ 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,
191
+ html_url: typeof record.html_url === "string" ? record.html_url : typeof record.url === "string" ? record.url : null,
192
+ author: record.author && typeof record.author === "object" ? record.author : record.user && typeof record.user === "object" ? record.user : null
193
+ };
194
+ }
195
+ function normalizeReviewComment(entry) {
196
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
197
+ return null;
198
+ const record = entry;
199
+ const body = typeof record.body === "string" ? record.body : null;
200
+ const path = typeof record.path === "string" ? record.path : null;
201
+ if (!body && !path)
202
+ return null;
203
+ return {
204
+ id: typeof record.id === "string" || typeof record.id === "number" ? record.id : null,
205
+ user: record.user && typeof record.user === "object" ? record.user : null,
206
+ author: record.author && typeof record.author === "object" ? record.author : null,
207
+ body,
208
+ path,
209
+ html_url: typeof record.html_url === "string" ? record.html_url : null,
210
+ url: typeof record.url === "string" ? record.url : null,
211
+ commit_id: typeof record.commit_id === "string" ? record.commit_id : null,
212
+ original_commit_id: typeof record.original_commit_id === "string" ? record.original_commit_id : null
213
+ };
214
+ }
215
+ function normalizeIssueComment(entry) {
216
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
217
+ return null;
218
+ const record = entry;
219
+ const body = typeof record.body === "string" ? record.body : null;
220
+ if (!body)
221
+ return null;
222
+ return {
223
+ id: typeof record.id === "string" || typeof record.id === "number" ? record.id : null,
224
+ user: record.user && typeof record.user === "object" ? record.user : null,
225
+ author: record.author && typeof record.author === "object" ? record.author : null,
226
+ body,
227
+ html_url: typeof record.html_url === "string" ? record.html_url : null,
228
+ url: typeof record.url === "string" ? record.url : null,
229
+ created_at: typeof record.created_at === "string" ? record.created_at : null
230
+ };
231
+ }
232
+ function normalizeReviewThread(entry) {
233
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
234
+ return null;
235
+ const record = entry;
236
+ return {
237
+ id: typeof record.id === "string" ? record.id : null,
238
+ isResolved: typeof record.isResolved === "boolean" ? record.isResolved : null,
239
+ isOutdated: typeof record.isOutdated === "boolean" ? record.isOutdated : null,
240
+ comments: record.comments && typeof record.comments === "object" ? record.comments : null
241
+ };
242
+ }
243
+ function relevantIssueComment(comment) {
244
+ const login = comment.user?.login ?? comment.author?.login ?? "";
245
+ const body = comment.body ?? "";
246
+ 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);
247
+ }
248
+ function latestThreadComment(thread) {
249
+ const nodes = thread.comments?.nodes ?? [];
250
+ return nodes.length > 0 ? nodes[nodes.length - 1] : null;
251
+ }
252
+ function unresolvedThreadSummaries(threads) {
253
+ return threads.flatMap((thread) => {
254
+ if (thread.isResolved === true || thread.isOutdated === true)
255
+ return [];
256
+ const latest = latestThreadComment(thread);
257
+ if (!latest)
258
+ return ["Unresolved review thread"];
259
+ const path = latest.path ? ` on ${latest.path}` : "";
260
+ return [`Unresolved review thread${path}: ${(latest.body ?? "").trim() || "(empty comment)"}`];
261
+ });
262
+ }
263
+ function collectBodies(evidence) {
264
+ return [
265
+ evidence.title ?? "",
266
+ evidence.body,
267
+ ...evidence.reviews.map((review) => review.body ?? ""),
268
+ ...evidence.changedFileReviewComments.map((comment) => comment.body ?? ""),
269
+ ...evidence.relevantIssueComments.map((comment) => comment.body ?? ""),
270
+ ...evidence.reviewThreads.flatMap((thread) => thread.comments?.nodes?.map((comment) => comment.body ?? "") ?? []),
271
+ ...(evidence.apiSignals ?? []).map((signal) => signal.body ?? "")
272
+ ].filter((body) => body.trim().length > 0);
273
+ }
274
+ function bodyExcerpt(body) {
275
+ const text = stripHtml(body).replace(/\s+/g, " ").trim();
276
+ return text.length > 240 ? `${text.slice(0, 237)}...` : text;
277
+ }
278
+ function makeGreptileSignal(input) {
279
+ const scores = parseGreptileScores(input.body);
280
+ const reviewedSha = input.reviewedSha?.trim() || null;
281
+ const current = reviewedSha ? reviewedSha === input.currentHeadSha : null;
282
+ const blocker = input.blocker ?? containsBlockerText(input.body);
283
+ const explicitApproval = input.explicitApproval ?? false;
284
+ return {
285
+ source: input.source,
286
+ trusted: input.trusted,
287
+ authorLogin: input.authorLogin ?? null,
288
+ reviewedSha,
289
+ current,
290
+ stale: current === false,
291
+ score: scores[0] ?? null,
292
+ scores,
293
+ explicitApproval,
294
+ blocker,
295
+ actionable: input.actionable ?? blocker,
296
+ bodyExcerpt: bodyExcerpt(input.body),
297
+ body: input.body,
298
+ allScores: scores
299
+ };
300
+ }
301
+ function reviewAuthorLogin(review) {
302
+ return review.author?.login ?? null;
303
+ }
304
+ function commentAuthorLogin(comment) {
305
+ return comment.user?.login ?? comment.author?.login ?? null;
306
+ }
307
+ function collectGreptileSignals(evidence) {
308
+ const signals = [];
309
+ const contextSources = [
310
+ { source: "pr-title", body: evidence.title ?? "" },
311
+ { source: "pr-body", body: evidence.body }
312
+ ];
313
+ for (const context of contextSources) {
314
+ if (!context.body.trim())
315
+ continue;
316
+ if (!/greptile|score|confidence|\b\d+\s*\/\s*5\b|blocker|unsafe|not safe|do not merge|changes requested/i.test(context.body))
317
+ continue;
318
+ const contextBlocker = containsBlockerText(context.body);
319
+ signals.push(makeGreptileSignal({
320
+ source: context.source,
321
+ body: context.body,
322
+ currentHeadSha: evidence.currentHeadSha,
323
+ trusted: false,
324
+ blocker: contextBlocker,
325
+ actionable: contextBlocker
326
+ }));
327
+ }
328
+ for (const apiSignal of evidence.apiSignals ?? []) {
329
+ const body = [apiSignal.status ? `Status: ${apiSignal.status}` : "", apiSignal.body ?? ""].filter(Boolean).join(`
330
+
331
+ `);
332
+ if (!body.trim())
333
+ continue;
334
+ signals.push(makeGreptileSignal({
335
+ source: "api",
336
+ body,
337
+ currentHeadSha: evidence.currentHeadSha,
338
+ trusted: true,
339
+ reviewedSha: apiSignal.reviewedSha ?? null,
340
+ explicitApproval: false
341
+ }));
342
+ }
343
+ for (const review of evidence.reviews) {
344
+ const login = reviewAuthorLogin(review);
345
+ if (!isGreptileGithubLogin(login))
346
+ continue;
347
+ const state = String(review.state ?? "").toUpperCase();
348
+ const body = [state ? `Review state: ${state}` : "", review.body ?? ""].filter(Boolean).join(`
349
+
350
+ `);
351
+ if (!body.trim())
352
+ continue;
353
+ const dismissed = state === "DISMISSED";
354
+ signals.push(makeGreptileSignal({
355
+ source: "github-review",
356
+ body,
357
+ currentHeadSha: evidence.currentHeadSha,
358
+ trusted: !dismissed,
359
+ authorLogin: login,
360
+ reviewedSha: review.commit_id ?? null,
361
+ explicitApproval: undefined,
362
+ blocker: state === "CHANGES_REQUESTED" || undefined
363
+ }));
364
+ }
365
+ for (const comment of evidence.changedFileReviewComments) {
366
+ const login = commentAuthorLogin(comment);
367
+ const body = comment.body ?? "";
368
+ if (!body.trim() || !isGreptileGithubLogin(login))
369
+ continue;
370
+ signals.push(makeGreptileSignal({
371
+ source: "changed-file-comment",
372
+ body,
373
+ currentHeadSha: evidence.currentHeadSha,
374
+ trusted: true,
375
+ authorLogin: login,
376
+ reviewedSha: comment.commit_id ?? comment.original_commit_id ?? null
377
+ }));
378
+ }
379
+ for (const comment of evidence.relevantIssueComments) {
380
+ const login = commentAuthorLogin(comment);
381
+ const body = comment.body ?? "";
382
+ if (!body.trim() || !isGreptileGithubLogin(login))
383
+ continue;
384
+ signals.push(makeGreptileSignal({
385
+ source: "issue-comment",
386
+ body,
387
+ currentHeadSha: evidence.currentHeadSha,
388
+ trusted: true,
389
+ authorLogin: login
390
+ }));
391
+ }
392
+ for (const thread of evidence.reviewThreads) {
393
+ if (thread.isOutdated === true || thread.isResolved === true)
394
+ continue;
395
+ for (const comment of thread.comments?.nodes ?? []) {
396
+ const login = comment.author?.login ?? null;
397
+ const body = comment.body ?? "";
398
+ if (!body.trim() || !isGreptileGithubLogin(login))
399
+ continue;
400
+ signals.push(makeGreptileSignal({
401
+ source: "review-thread",
402
+ body,
403
+ currentHeadSha: evidence.currentHeadSha,
404
+ trusted: true,
405
+ authorLogin: login
406
+ }));
407
+ }
408
+ }
409
+ for (const check of evidence.checks) {
410
+ if (!isGreptileLabel(checkName(check)))
411
+ continue;
412
+ const reviewedSha = check.headSha ?? check.head_sha ?? null;
413
+ const label = `${checkName(check)} (${checkState(check) || "unknown"})`;
414
+ const body = [label, check.output?.title ?? "", check.output?.summary ?? "", check.output?.text ?? ""].filter((entry) => entry.trim().length > 0).join(`
415
+
416
+ `);
417
+ signals.push(makeGreptileSignal({
418
+ source: "github-check",
419
+ body,
420
+ currentHeadSha: evidence.currentHeadSha,
421
+ trusted: false,
422
+ reviewedSha,
423
+ explicitApproval: false,
424
+ blocker: isFailingCheck(check),
425
+ actionable: isFailingCheck(check)
426
+ }));
427
+ }
428
+ return signals;
429
+ }
430
+ function unresolvedGreptileThreadSummaries(threads) {
431
+ return threads.flatMap((thread) => {
432
+ if (thread.isResolved === true || thread.isOutdated === true)
433
+ return [];
434
+ const comments = thread.comments?.nodes ?? [];
435
+ if (!comments.some((comment) => isGreptileGithubLogin(comment.author?.login)))
436
+ return [];
437
+ const latest = latestThreadComment(thread);
438
+ if (!latest)
439
+ return ["Unresolved Greptile review thread"];
440
+ const path = latest.path ? ` on ${latest.path}` : "";
441
+ return [`Unresolved Greptile review thread${path}: ${(latest.body ?? "").trim() || "(empty comment)"}`];
442
+ });
443
+ }
444
+ function actionableChangedFileCommentSummaries(_comments) {
445
+ return [];
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.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
+ ...actionableChangedFileCommentSummaries(input.changedFileReviewComments)
506
+ ];
507
+ const greptileChecks = input.checks.filter((check) => isGreptileLabel(checkName(check)));
508
+ const greptileReviews = input.reviews.filter((review) => isGreptileGithubLogin(review.author?.login));
509
+ const completedGreptileCheck = greptileChecks.some((check) => {
510
+ const reviewedSha2 = check.headSha ?? check.head_sha ?? null;
511
+ return reviewedSha2 === input.currentHeadSha && (isPassingCheck(check) || isFailingCheck(check));
512
+ });
513
+ const completedGreptileReview = greptileReviews.some((review) => {
514
+ const state = String(review.state ?? "").toUpperCase();
515
+ const completedState = ["APPROVED", "COMMENTED", "CHANGES_REQUESTED"].includes(state) || !!review.body?.trim();
516
+ return completedState && review.commit_id === input.currentHeadSha;
517
+ });
518
+ const approvalReviewedSha = approvingSignal?.reviewedSha ?? null;
519
+ const reviewedSha = approvalReviewedSha ?? staleSignals[0]?.reviewedSha ?? trustedSignals.map((signal) => signal.reviewedSha ?? null).find(Boolean) ?? null;
520
+ const fresh = !!approvalReviewedSha && approvalReviewedSha === input.currentHeadSha;
521
+ const completed = completedGreptileCheck || completedGreptileReview || !!approvingSignal || trustedSignals.some((signal) => signal.source === "api" && signal.reviewedSha === input.currentHeadSha);
522
+ const hasGreptileEvidence = trustedSignals.length > 0 || signals.some((signal) => /greptile/i.test(signal.body));
523
+ const approved = fresh && completed && !blockers.length && !unresolvedComments.length && (approvedByScore || approvedByExplicitMapping);
524
+ const mapping = !hasGreptileEvidence ? "missing" : staleSignals.length > 0 && !approvingSignal ? "stale" : approvedByScore ? "score-5-of-5" : "unproven";
525
+ 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";
526
+ return {
527
+ source,
528
+ currentHeadSha: input.currentHeadSha,
529
+ reviewedSha,
530
+ fresh,
531
+ completed,
532
+ approved,
533
+ score,
534
+ explicitApproval: approvedByExplicitMapping,
535
+ blockers,
536
+ unresolvedComments,
537
+ rawBodies,
538
+ signals: signals.map(({ body: _body, allScores: _allScores, ...signal }) => signal),
539
+ mapping
540
+ };
541
+ }
542
+ function isGreptileCheckDetail(check) {
543
+ return isGreptileLabel(checkName(check)) || isGreptileGithubLogin(check.app?.slug) || isGreptileGithubLogin(check.app?.owner?.login) || isGreptileLabel(check.app?.name);
544
+ }
545
+ async function collectGreptileCheckDetails(input) {
546
+ const checkRunsRead = await runJsonArray(input.command, [
547
+ "api",
548
+ `repos/${input.repoName}/commits/${input.headSha}/check-runs`,
549
+ "--paginate",
550
+ "--slurp",
551
+ "--jq",
552
+ "map(.check_runs // []) | add // []"
553
+ ], input.projectRoot);
554
+ const checkRuns = checkRunsRead.value.map(normalizeStatusCheck).filter((entry) => !!entry).filter(isGreptileCheckDetail);
555
+ return checkRunsRead.error ? { value: checkRuns, error: checkRunsRead.error } : { value: checkRuns };
556
+ }
557
+ async function collectReviewThreads(input) {
558
+ const reviewThreads = [];
559
+ let afterCursor = null;
560
+ for (let page = 0;page < 100; page += 1) {
561
+ const afterLiteral = afterCursor ? JSON.stringify(afterCursor) : "null";
562
+ const threadsResponse = await runJsonObject(input.command, [
563
+ "api",
564
+ "graphql",
565
+ "-F",
566
+ `owner=${input.owner}`,
567
+ "-F",
568
+ `name=${input.name}`,
569
+ "-F",
570
+ `prNumber=${input.prNumber}`,
571
+ "-f",
572
+ `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 } } } } }`
573
+ ], input.projectRoot);
574
+ if (threadsResponse.error) {
575
+ return { value: reviewThreads, error: threadsResponse.error };
576
+ }
577
+ const data = threadsResponse.value.data;
578
+ const repository = data?.repository;
579
+ const pullRequest = repository?.pullRequest;
580
+ const threads = pullRequest?.reviewThreads;
581
+ const nodes = threads?.nodes;
582
+ if (!Array.isArray(nodes)) {
583
+ return { value: reviewThreads, error: "GitHub reviewThreads response did not include a nodes array" };
584
+ }
585
+ const normalized = nodes.map(normalizeReviewThread).filter((entry) => !!entry);
586
+ reviewThreads.push(...normalized);
587
+ const truncatedCommentThread = normalized.find((thread) => thread.comments?.pageInfo?.hasNextPage === true);
588
+ if (truncatedCommentThread) {
589
+ return { value: reviewThreads, error: `GitHub review thread ${truncatedCommentThread.id ?? "unknown"} has more than 100 comments; nested pagination is incomplete` };
590
+ }
591
+ const pageInfo = threads?.pageInfo;
592
+ if (!pageInfo) {
593
+ if (nodes.length >= 100) {
594
+ return { value: reviewThreads, error: "GitHub reviewThreads pagination metadata missing after a full page" };
595
+ }
596
+ return { value: reviewThreads };
597
+ }
598
+ if (pageInfo.hasNextPage !== true) {
599
+ return { value: reviewThreads };
600
+ }
601
+ if (typeof pageInfo.endCursor !== "string" || !pageInfo.endCursor.trim()) {
602
+ return { value: reviewThreads, error: "GitHub reviewThreads pagination reported hasNextPage without endCursor" };
603
+ }
604
+ afterCursor = pageInfo.endCursor;
605
+ }
606
+ return { value: reviewThreads, error: "GitHub reviewThreads pagination exceeded 100 pages" };
607
+ }
608
+ async function collectPrReviewEvidence(input) {
609
+ const parsed = parseGithubPrUrl(input.prUrl);
610
+ if (!parsed) {
611
+ throw new Error(`Cannot parse GitHub PR URL: ${input.prUrl}`);
612
+ }
613
+ const readErrors = [];
614
+ const viewRead = await runJsonObject(input.command, [
615
+ "pr",
616
+ "view",
617
+ input.prUrl,
618
+ "--json",
619
+ "title,body,headRefOid,headRefName,baseRefName,state,isDraft,mergeable,mergeStateStatus,reviewDecision,reviews,statusCheckRollup"
620
+ ], input.projectRoot);
621
+ if (viewRead.error)
622
+ readErrors.push(viewRead.error);
623
+ const view = viewRead.value;
624
+ if (!Array.isArray(view.statusCheckRollup)) {
625
+ readErrors.push("gh pr view did not return required statusCheckRollup array");
626
+ }
627
+ if (!Array.isArray(view.reviews)) {
628
+ readErrors.push("gh pr view did not return required reviews array");
629
+ }
630
+ const headSha = firstString(view, ["headRefOid", "headSha", "head_sha"]);
631
+ const statusCheckRollup = arrayField(view, "statusCheckRollup").map(normalizeStatusCheck).filter((entry) => !!entry);
632
+ const reviews = arrayField(view, "reviews").map(normalizeReview).filter((entry) => !!entry);
633
+ const reviewCommentsRead = await runJsonArray(input.command, ["api", `repos/${parsed.repoName}/pulls/${parsed.prNumber}/comments`, "--paginate", "--slurp"], input.projectRoot);
634
+ if (reviewCommentsRead.error)
635
+ readErrors.push(reviewCommentsRead.error);
636
+ const reviewComments = reviewCommentsRead.value.map(normalizeReviewComment).filter((entry) => !!entry);
637
+ const issueCommentsRead = await runJsonArray(input.command, ["api", `repos/${parsed.repoName}/issues/${parsed.prNumber}/comments`, "--paginate", "--slurp"], input.projectRoot);
638
+ if (issueCommentsRead.error)
639
+ readErrors.push(issueCommentsRead.error);
640
+ const issueComments = issueCommentsRead.value.map(normalizeIssueComment).filter((entry) => !!entry).filter(relevantIssueComment);
641
+ const reviewThreadsRead = await collectReviewThreads({
642
+ command: input.command,
643
+ projectRoot: input.projectRoot,
644
+ owner: parsed.owner,
645
+ name: parsed.repo,
646
+ prNumber: parsed.prNumber
647
+ });
648
+ if (reviewThreadsRead.error)
649
+ readErrors.push(reviewThreadsRead.error);
650
+ const reviewThreads = reviewThreadsRead.value;
651
+ const greptileRollupChecks = statusCheckRollup.filter((check) => isGreptileLabel(checkName(check)));
652
+ let greptileCheckDetails = [];
653
+ if (headSha && greptileRollupChecks.length > 0) {
654
+ const checkDetailsRead = await collectGreptileCheckDetails({
655
+ command: input.command,
656
+ projectRoot: input.projectRoot,
657
+ repoName: parsed.repoName,
658
+ headSha
659
+ });
660
+ if (checkDetailsRead.error)
661
+ readErrors.push(checkDetailsRead.error);
662
+ greptileCheckDetails = checkDetailsRead.value;
663
+ if (!checkDetailsRead.error && greptileCheckDetails.length === 0) {
664
+ readErrors.push("Greptile check details could not be found for the current PR head");
665
+ }
666
+ }
667
+ const checksWithGreptileDetails = [...statusCheckRollup, ...greptileCheckDetails];
668
+ 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})` : ""}`);
669
+ const pendingChecks = statusCheckRollup.filter((check) => isPendingCheck(check) && !isAllowedFailure(checkName(check), input.allowedFailures ?? [])).map((check) => `Check pending: ${checkName(check)}`);
670
+ const evidenceBase = {
671
+ title: firstString(view, ["title"]),
672
+ body: firstString(view, ["body"]),
673
+ reviews,
674
+ changedFileReviewComments: reviewComments,
675
+ relevantIssueComments: issueComments,
676
+ reviewThreads,
677
+ checks: checksWithGreptileDetails,
678
+ currentHeadSha: headSha,
679
+ apiSignals: input.apiSignals ?? []
680
+ };
681
+ const greptile = deriveGreptileEvidence(evidenceBase);
682
+ return {
683
+ prUrl: input.prUrl,
684
+ prNumber: parsed.prNumber,
685
+ repoName: parsed.repoName,
686
+ title: evidenceBase.title,
687
+ body: evidenceBase.body,
688
+ headSha,
689
+ headRefName: firstString(view, ["headRefName"]),
690
+ baseRefName: firstString(view, ["baseRefName"]),
691
+ state: firstString(view, ["state"]),
692
+ isDraft: typeof view.isDraft === "boolean" ? view.isDraft : null,
693
+ mergeable: firstString(view, ["mergeable"]),
694
+ mergeStateStatus: firstString(view, ["mergeStateStatus"]),
695
+ reviewDecision: firstString(view, ["reviewDecision"]),
696
+ reviews,
697
+ reviewThreads,
698
+ changedFileReviewComments: reviewComments,
699
+ relevantIssueComments: issueComments,
700
+ statusCheckRollup: checksWithGreptileDetails,
701
+ checkFailures,
702
+ pendingChecks,
703
+ readErrors,
704
+ greptile
705
+ };
706
+ }
707
+ function evaluateEvidence(evidence) {
708
+ const reasons = [];
709
+ const warnings = [];
710
+ let pending = false;
711
+ if (evidence.readErrors.length > 0) {
712
+ reasons.push(...evidence.readErrors.map((error) => `Required PR evidence surface could not be read completely: ${error}`));
713
+ }
714
+ if (!evidence.headSha)
715
+ reasons.push("PR head SHA could not be read; current-head Greptile approval cannot be proven.");
716
+ if (evidence.checkFailures.length > 0)
717
+ reasons.push(...evidence.checkFailures);
718
+ if (evidence.pendingChecks.length > 0) {
719
+ pending = true;
720
+ reasons.push(...evidence.pendingChecks);
721
+ }
722
+ const reviewDecision = String(evidence.reviewDecision ?? "").toUpperCase();
723
+ if (reviewDecision === "CHANGES_REQUESTED" || reviewDecision === "REVIEW_REQUIRED") {
724
+ reasons.push(`Required review is unresolved (${evidence.reviewDecision}).`);
725
+ }
726
+ const unresolvedThreads = unresolvedThreadSummaries(evidence.reviewThreads);
727
+ if (unresolvedThreads.length > 0)
728
+ reasons.push(...unresolvedThreads);
729
+ const greptile = evidence.greptile;
730
+ if (greptile.mapping === "missing")
731
+ reasons.push("Missing Greptile check/review evidence for this PR.");
732
+ const staleSignal = greptile.signals.find((signal) => signal.reviewedSha && signal.reviewedSha !== evidence.headSha);
733
+ if (greptile.mapping === "stale" || greptile.reviewedSha && greptile.reviewedSha !== evidence.headSha || !greptile.approved && staleSignal) {
734
+ reasons.push(`Greptile evidence is stale (reviewed ${greptile.reviewedSha ?? staleSignal?.reviewedSha ?? "unknown"}, current ${evidence.headSha || "unknown"}).`);
735
+ }
736
+ if (!greptile.completed) {
737
+ pending = true;
738
+ reasons.push("Greptile check/review has not completed for the current PR head.");
739
+ }
740
+ if (!greptile.fresh)
741
+ reasons.push("Greptile approval is not tied to the current PR head SHA.");
742
+ if (greptile.score && !(greptile.score.scale === 5 && greptile.score.value === 5)) {
743
+ reasons.push(`Greptile score is ${greptile.score.value}/${greptile.score.scale}; strict merge requires trusted current-head 5/5.`);
744
+ }
745
+ if (!greptile.score && greptile.mapping !== "score-5-of-5") {
746
+ reasons.push("No parseable Greptile 5/5 score or explicit approved mapping was found from trusted current-head evidence; merge is blocked.");
747
+ }
748
+ if (greptile.mapping === "unproven") {
749
+ reasons.push("Greptile approval mapping is unproven; PR body/title or a green check alone cannot approve merge.");
750
+ }
751
+ if (greptile.blockers.length > 0) {
752
+ reasons.push(...greptile.blockers.map((entry) => `Greptile/blocker text: ${entry.trim().slice(0, 500)}`));
753
+ }
754
+ if (greptile.unresolvedComments.length > 0)
755
+ reasons.push(...greptile.unresolvedComments);
756
+ if (!greptile.approved)
757
+ warnings.push(`Greptile approval mapping is ${greptile.mapping}.`);
758
+ return { reasons: Array.from(new Set(reasons)), warnings, pending };
759
+ }
760
+ function evaluateStrictPrMergeGate(evidence) {
761
+ const evaluated = evaluateEvidence(evidence);
762
+ const approved = evaluated.reasons.length === 0 && evidence.greptile.approved;
763
+ return {
764
+ approved,
765
+ pending: evaluated.pending,
766
+ reasons: evaluated.reasons,
767
+ warnings: evaluated.warnings,
768
+ actionableFeedback: evaluated.reasons,
769
+ evidence
770
+ };
771
+ }
772
+ function promptExcerpt(value, maxChars = 4000) {
773
+ return value.length > maxChars ? `${value.slice(0, maxChars)}
774
+
775
+ [truncated for prompt; see full evidence artifact]` : value;
776
+ }
777
+ function promptJsonExcerpt(value, maxChars = 6000) {
778
+ return promptExcerpt(JSON.stringify(value, null, 2), maxChars);
779
+ }
780
+ function buildStrictPrGateSteeringPrompt(result) {
781
+ const evidence = result.evidence;
782
+ const unresolvedReviewThreads = evidence.reviewThreads.filter((thread) => thread.isResolved !== true && thread.isOutdated !== true);
783
+ const lines = [
784
+ `Strict PR merge gate blocked ${evidence.prUrl}.`,
785
+ `PR title: ${evidence.title || "(empty)"}`,
786
+ `Current PR head SHA: ${evidence.headSha || "unknown"}`,
787
+ `Greptile mapping: ${evidence.greptile.mapping}`,
788
+ evidence.greptile.score ? `Greptile score: ${evidence.greptile.score.value}/${evidence.greptile.score.scale}` : "Greptile score: not proven",
789
+ "",
790
+ "Gate reasons:",
791
+ ...result.reasons.length ? result.reasons.map((reason) => `- ${reason}`) : ["- No reasons recorded"],
792
+ "",
793
+ "Required evidence read status:",
794
+ evidence.readErrors.length ? JSON.stringify(evidence.readErrors, null, 2) : "All required PR evidence surfaces were read completely.",
795
+ "",
796
+ "Full PR title:",
797
+ evidence.title || "(empty)",
798
+ "",
799
+ "PR body excerpt:",
800
+ evidence.body ? promptExcerpt(evidence.body) : "(empty)",
801
+ "",
802
+ "All review comments on changed files:",
803
+ evidence.changedFileReviewComments.length ? promptJsonExcerpt(evidence.changedFileReviewComments) : "[]",
804
+ "",
805
+ "Unresolved review threads:",
806
+ unresolvedReviewThreads.length ? promptJsonExcerpt(unresolvedReviewThreads) : "[]",
807
+ "",
808
+ "Relevant issue-level PR comments:",
809
+ evidence.relevantIssueComments.length ? promptJsonExcerpt(evidence.relevantIssueComments) : "[]",
810
+ "",
811
+ "CI/check failures and pending checks:",
812
+ promptJsonExcerpt({ failures: evidence.checkFailures, pending: evidence.pendingChecks, rollup: evidence.statusCheckRollup }),
813
+ "",
814
+ "Greptile evidence:",
815
+ promptJsonExcerpt(evidence.greptile)
816
+ ];
817
+ if (result.artifacts) {
818
+ lines.push("", "Full evidence artifacts:", JSON.stringify(result.artifacts, null, 2));
819
+ }
820
+ return lines.join(`
821
+ `);
822
+ }
823
+ function persistPrReviewCycleArtifacts(input) {
824
+ const cycleName = input.final ? `${input.cycle}-final` : String(input.cycle);
825
+ const taskArtifactRoot = input.artifactRoot?.trim() ? input.artifactRoot : resolve(input.projectRoot, "artifacts", input.taskId);
826
+ const root = resolve(taskArtifactRoot, "pr-review-cycles", cycleName);
827
+ mkdirSync(root, { recursive: true });
828
+ const finalMergeGateResultPath = input.final ? resolve(taskArtifactRoot, "merge-gate-final.json") : undefined;
829
+ const paths = {
830
+ root,
831
+ prTitlePath: resolve(root, "pr-title.md"),
832
+ prBodyPath: resolve(root, "pr-body.md"),
833
+ prCommentsPath: resolve(root, "pr-comments.json"),
834
+ reviewThreadsPath: resolve(root, "review-threads.json"),
835
+ reviewCommentsPath: resolve(root, "review-comments.json"),
836
+ checkRollupPath: resolve(root, "check-rollup.json"),
837
+ greptileEvidencePath: resolve(root, "greptile-evidence.json"),
838
+ mergeGateResultPath: resolve(root, "merge-gate-result.json"),
839
+ steeringPromptPath: resolve(root, "agent-steering-prompt.md"),
840
+ ...finalMergeGateResultPath ? { finalMergeGateResultPath } : {}
841
+ };
842
+ writeFileSync(paths.prTitlePath, input.result.evidence.title || "", "utf8");
843
+ writeFileSync(paths.prBodyPath, input.result.evidence.body || "", "utf8");
844
+ writeFileSync(paths.prCommentsPath, `${JSON.stringify(input.result.evidence.relevantIssueComments, null, 2)}
845
+ `, "utf8");
846
+ writeFileSync(paths.reviewThreadsPath, `${JSON.stringify(input.result.evidence.reviewThreads, null, 2)}
847
+ `, "utf8");
848
+ writeFileSync(paths.reviewCommentsPath, `${JSON.stringify(input.result.evidence.changedFileReviewComments, null, 2)}
849
+ `, "utf8");
850
+ writeFileSync(paths.checkRollupPath, `${JSON.stringify(input.result.evidence.statusCheckRollup, null, 2)}
851
+ `, "utf8");
852
+ writeFileSync(paths.greptileEvidencePath, `${JSON.stringify(input.result.evidence.greptile, null, 2)}
853
+ `, "utf8");
854
+ const mergeGatePayload = {
855
+ approved: input.result.approved,
856
+ pending: input.result.pending,
857
+ reasons: input.result.reasons,
858
+ warnings: input.result.warnings,
859
+ actionableFeedback: input.result.actionableFeedback,
860
+ prUrl: input.result.evidence.prUrl,
861
+ title: input.result.evidence.title,
862
+ headSha: input.result.evidence.headSha,
863
+ readErrors: input.result.evidence.readErrors,
864
+ greptile: input.result.evidence.greptile,
865
+ evidence: input.result.evidence,
866
+ cycleArtifactRoot: root
867
+ };
868
+ writeFileSync(paths.mergeGateResultPath, `${JSON.stringify(mergeGatePayload, null, 2)}
869
+ `, "utf8");
870
+ if (paths.finalMergeGateResultPath) {
871
+ writeFileSync(paths.finalMergeGateResultPath, `${JSON.stringify(mergeGatePayload, null, 2)}
872
+ `, "utf8");
873
+ }
874
+ writeFileSync(paths.steeringPromptPath, input.steeringPrompt, "utf8");
875
+ return paths;
876
+ }
877
+ async function runStrictPrMergeGate(input) {
878
+ const evidence = await collectPrReviewEvidence(input);
879
+ const base = evaluateStrictPrMergeGate(evidence);
880
+ const preliminaryPrompt = buildStrictPrGateSteeringPrompt({ ...base, artifacts: undefined });
881
+ const artifacts = persistPrReviewCycleArtifacts({
882
+ projectRoot: input.projectRoot,
883
+ taskId: input.taskId,
884
+ cycle: input.cycle,
885
+ artifactRoot: input.artifactRoot,
886
+ result: base,
887
+ steeringPrompt: preliminaryPrompt,
888
+ final: input.final
889
+ });
890
+ const steeringPrompt = buildStrictPrGateSteeringPrompt({ ...base, artifacts });
891
+ writeFileSync(artifacts.steeringPromptPath, steeringPrompt, "utf8");
892
+ return { ...base, artifacts, steeringPrompt };
893
+ }
894
+ export {
895
+ stripHtml,
896
+ runStrictPrMergeGate,
897
+ persistPrReviewCycleArtifacts,
898
+ parseGreptileScore,
899
+ parseGithubPrUrl,
900
+ isGreptileGithubLogin,
901
+ evaluateStrictPrMergeGate,
902
+ deriveGreptileEvidence,
903
+ collectPrReviewEvidence,
904
+ buildStrictPrGateSteeringPrompt
905
+ };