@h-rig/runtime 0.0.6-alpha.3 → 0.0.6-alpha.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/bin/rig-agent-dispatch.js +1165 -785
  2. package/dist/bin/rig-agent.js +458 -389
  3. package/dist/src/control-plane/agent-wrapper.js +1191 -504
  4. package/dist/src/control-plane/authority-files.js +12 -6
  5. package/dist/src/control-plane/harness-main.js +2186 -1786
  6. package/dist/src/control-plane/hooks/completion-verification.js +2084 -1019
  7. package/dist/src/control-plane/hooks/inject-context.js +193 -139
  8. package/dist/src/control-plane/hooks/submodule-branch.js +603 -545
  9. package/dist/src/control-plane/hooks/task-runtime-start.js +603 -545
  10. package/dist/src/control-plane/materialize-task-config.js +64 -8
  11. package/dist/src/control-plane/native/git-ops.js +90 -64
  12. package/dist/src/control-plane/native/harness-cli.js +1989 -682
  13. package/dist/src/control-plane/native/pr-automation.js +1657 -54
  14. package/dist/src/control-plane/native/pr-review-gate.js +1455 -0
  15. package/dist/src/control-plane/native/repo-ops.js +3 -0
  16. package/dist/src/control-plane/native/run-ops.js +39 -13
  17. package/dist/src/control-plane/native/task-ops.js +1819 -527
  18. package/dist/src/control-plane/native/validator.js +163 -109
  19. package/dist/src/control-plane/native/verifier.js +1616 -323
  20. package/dist/src/control-plane/native/workspace-ops.js +12 -6
  21. package/dist/src/control-plane/pi-sessiond/bin.js +793 -0
  22. package/dist/src/control-plane/pi-sessiond/client.js +41 -0
  23. package/dist/src/control-plane/pi-sessiond/event-hub.js +59 -0
  24. package/dist/src/control-plane/pi-sessiond/extension-ui-context.js +198 -0
  25. package/dist/src/control-plane/pi-sessiond/launcher.js +173 -0
  26. package/dist/src/control-plane/pi-sessiond/server.js +802 -0
  27. package/dist/src/control-plane/pi-sessiond/session-service.js +540 -0
  28. package/dist/src/control-plane/pi-sessiond/types.js +1 -0
  29. package/dist/src/control-plane/plugin-host-context.js +54 -0
  30. package/dist/src/control-plane/runtime/image/fingerprint-sidecar.js +3 -0
  31. package/dist/src/control-plane/runtime/image/index.js +3 -0
  32. package/dist/src/control-plane/runtime/image-fingerprint-sidecar.js +3 -0
  33. package/dist/src/control-plane/runtime/image.js +3 -0
  34. package/dist/src/control-plane/runtime/index.js +517 -722
  35. package/dist/src/control-plane/runtime/isolation/home.js +28 -6
  36. package/dist/src/control-plane/runtime/isolation/index.js +541 -461
  37. package/dist/src/control-plane/runtime/isolation/runner.js +28 -6
  38. package/dist/src/control-plane/runtime/isolation/shared.js +9 -6
  39. package/dist/src/control-plane/runtime/isolation.js +541 -461
  40. package/dist/src/control-plane/runtime/plugin-mode.js +3 -27
  41. package/dist/src/control-plane/runtime/queue.js +458 -385
  42. package/dist/src/control-plane/runtime/snapshot/task-run.js +3 -0
  43. package/dist/src/control-plane/runtime/task-run-snapshot.js +3 -0
  44. package/dist/src/control-plane/skill-materializer.js +46 -0
  45. package/dist/src/control-plane/tasks/source-aware-task-config-source.js +14 -2
  46. package/dist/src/control-plane/tasks/source-lifecycle.js +86 -32
  47. package/dist/src/index.js +27 -298
  48. package/dist/src/layout.js +12 -7
  49. package/dist/src/local-server.js +20 -14
  50. package/native/darwin-arm64/rig-git +0 -0
  51. package/native/darwin-arm64/rig-git.build-manifest.json +1 -1
  52. package/native/darwin-arm64/rig-shell +0 -0
  53. package/native/darwin-arm64/rig-shell.build-manifest.json +1 -1
  54. package/native/darwin-arm64/rig-tools +0 -0
  55. package/native/darwin-arm64/rig-tools.build-manifest.json +1 -1
  56. package/native/darwin-arm64/runtime-native.dylib +0 -0
  57. package/package.json +8 -6
  58. package/dist/src/control-plane/runtime/plugins.js +0 -1131
  59. package/dist/src/plugins.js +0 -329
@@ -0,0 +1,1455 @@
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
+
6
+ // packages/runtime/src/control-plane/runtime/baked-secrets.ts
7
+ var BAKED_RUNTIME_SECRETS = {
8
+ ANTHROPIC_API_KEY: typeof RIG_BAKED_ANTHROPIC_API_KEY !== "undefined" ? RIG_BAKED_ANTHROPIC_API_KEY : "",
9
+ OPENAI_API_KEY: typeof RIG_BAKED_OPENAI_API_KEY !== "undefined" ? RIG_BAKED_OPENAI_API_KEY : "",
10
+ OPENROUTER_API_KEY: typeof RIG_BAKED_OPENROUTER_API_KEY !== "undefined" ? RIG_BAKED_OPENROUTER_API_KEY : "",
11
+ AI_REVIEW_MODE: typeof RIG_BAKED_AI_REVIEW_MODE !== "undefined" ? RIG_BAKED_AI_REVIEW_MODE : "",
12
+ AI_REVIEW_PROVIDER: typeof RIG_BAKED_AI_REVIEW_PROVIDER !== "undefined" ? RIG_BAKED_AI_REVIEW_PROVIDER : "",
13
+ GREPTILE_API_BASE: typeof RIG_BAKED_GREPTILE_API_BASE !== "undefined" ? RIG_BAKED_GREPTILE_API_BASE : "",
14
+ GREPTILE_REMOTE: typeof RIG_BAKED_GREPTILE_REMOTE !== "undefined" ? RIG_BAKED_GREPTILE_REMOTE : "",
15
+ GREPTILE_REPOSITORY: typeof RIG_BAKED_GREPTILE_REPOSITORY !== "undefined" ? RIG_BAKED_GREPTILE_REPOSITORY : "",
16
+ GREPTILE_CONTEXT_BRANCH: typeof RIG_BAKED_GREPTILE_CONTEXT_BRANCH !== "undefined" ? RIG_BAKED_GREPTILE_CONTEXT_BRANCH : "",
17
+ GREPTILE_DEFAULT_BRANCH: typeof RIG_BAKED_GREPTILE_DEFAULT_BRANCH !== "undefined" ? RIG_BAKED_GREPTILE_DEFAULT_BRANCH : "",
18
+ GREPTILE_API_KEY: typeof RIG_BAKED_GREPTILE_API_KEY !== "undefined" ? RIG_BAKED_GREPTILE_API_KEY : "",
19
+ GREPTILE_GITHUB_TOKEN: typeof RIG_BAKED_GREPTILE_GITHUB_TOKEN !== "undefined" ? RIG_BAKED_GREPTILE_GITHUB_TOKEN : "",
20
+ GREPTILE_POLL_ATTEMPTS: typeof RIG_BAKED_GREPTILE_POLL_ATTEMPTS !== "undefined" ? RIG_BAKED_GREPTILE_POLL_ATTEMPTS : "",
21
+ GREPTILE_POLL_INTERVAL_MS: typeof RIG_BAKED_GREPTILE_POLL_INTERVAL_MS !== "undefined" ? RIG_BAKED_GREPTILE_POLL_INTERVAL_MS : "",
22
+ GH_TOKEN: typeof RIG_BAKED_GITHUB_TOKEN !== "undefined" ? RIG_BAKED_GITHUB_TOKEN : "",
23
+ GITHUB_TOKEN: typeof RIG_BAKED_GITHUB_TOKEN !== "undefined" ? RIG_BAKED_GITHUB_TOKEN : "",
24
+ GITHUB_SSH_KEY: typeof RIG_BAKED_GITHUB_SSH_KEY !== "undefined" ? RIG_BAKED_GITHUB_SSH_KEY : "",
25
+ AWS_ACCESS_KEY_ID: typeof RIG_BAKED_AWS_ACCESS_KEY_ID !== "undefined" ? RIG_BAKED_AWS_ACCESS_KEY_ID : "",
26
+ AWS_SECRET_ACCESS_KEY: typeof RIG_BAKED_AWS_SECRET_ACCESS_KEY !== "undefined" ? RIG_BAKED_AWS_SECRET_ACCESS_KEY : "",
27
+ AWS_REGION: typeof RIG_BAKED_AWS_REGION !== "undefined" ? RIG_BAKED_AWS_REGION : "",
28
+ LINEAR_API_KEY: typeof RIG_BAKED_LINEAR_API_KEY !== "undefined" ? RIG_BAKED_LINEAR_API_KEY : "",
29
+ LINEAR_WEBHOOK_SECRET: typeof RIG_BAKED_LINEAR_WEBHOOK_SECRET !== "undefined" ? RIG_BAKED_LINEAR_WEBHOOK_SECRET : ""
30
+ };
31
+ function resolveRuntimeSecrets(env, baked = BAKED_RUNTIME_SECRETS) {
32
+ const resolved = {};
33
+ const keys = new Set([
34
+ ...Object.keys(BAKED_RUNTIME_SECRETS),
35
+ ...Object.keys(baked)
36
+ ]);
37
+ for (const key of keys) {
38
+ const envValue = env[key]?.trim();
39
+ const bakedValue = baked[key]?.trim();
40
+ if (envValue) {
41
+ resolved[key] = envValue;
42
+ } else if (bakedValue) {
43
+ resolved[key] = bakedValue;
44
+ }
45
+ }
46
+ return resolved;
47
+ }
48
+
49
+ // packages/runtime/src/control-plane/native/pr-review-gate.ts
50
+ function parseJsonObject(value) {
51
+ if (!value?.trim())
52
+ return { value: {}, error: "empty JSON output" };
53
+ try {
54
+ const parsed = JSON.parse(value);
55
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? { value: parsed } : { value: {}, error: "JSON output was not an object" };
56
+ } catch (error) {
57
+ return { value: {}, error: error instanceof Error ? error.message : String(error) };
58
+ }
59
+ }
60
+ function flattenPaginatedArray(value) {
61
+ if (!Array.isArray(value))
62
+ return null;
63
+ if (value.every((entry) => Array.isArray(entry))) {
64
+ return value.flatMap((entry) => entry);
65
+ }
66
+ return value;
67
+ }
68
+ function parseConcatenatedJsonValues(value) {
69
+ const text = value.trim();
70
+ const docs = [];
71
+ let start = null;
72
+ let depth = 0;
73
+ let inString = false;
74
+ let escape = false;
75
+ for (let index = 0;index < text.length; index += 1) {
76
+ const char = text[index];
77
+ if (start === null) {
78
+ if (/\s/.test(char))
79
+ continue;
80
+ start = index;
81
+ }
82
+ if (inString) {
83
+ if (escape) {
84
+ escape = false;
85
+ } else if (char === "\\") {
86
+ escape = true;
87
+ } else if (char === '"') {
88
+ inString = false;
89
+ }
90
+ continue;
91
+ }
92
+ if (char === '"') {
93
+ inString = true;
94
+ continue;
95
+ }
96
+ if (char === "{" || char === "[") {
97
+ depth += 1;
98
+ continue;
99
+ }
100
+ if (char === "}" || char === "]") {
101
+ depth -= 1;
102
+ if (depth < 0)
103
+ return { value: docs, error: "unexpected JSON close delimiter" };
104
+ if (depth === 0 && start !== null) {
105
+ const segment = text.slice(start, index + 1);
106
+ try {
107
+ docs.push(JSON.parse(segment));
108
+ } catch (error) {
109
+ return { value: docs, error: error instanceof Error ? error.message : String(error) };
110
+ }
111
+ start = null;
112
+ }
113
+ }
114
+ }
115
+ if (inString || depth !== 0 || start !== null)
116
+ return { value: docs, error: "incomplete JSON stream" };
117
+ return { value: docs };
118
+ }
119
+ function parseJsonArray(value) {
120
+ if (!value?.trim())
121
+ return { value: [], error: "empty JSON output" };
122
+ try {
123
+ const parsed = JSON.parse(value);
124
+ const flattened = flattenPaginatedArray(parsed);
125
+ return flattened ? { value: flattened } : { value: [], error: "JSON output was not an array" };
126
+ } catch (error) {
127
+ const streamed = parseConcatenatedJsonValues(value);
128
+ if (streamed.error)
129
+ return { value: [], error: error instanceof Error ? error.message : String(error) };
130
+ const flattened = streamed.value.flatMap((entry) => flattenPaginatedArray(entry) ?? []);
131
+ return flattened.length > 0 || streamed.value.length === 0 ? { value: flattened } : { value: [], error: "JSON output was not an array" };
132
+ }
133
+ }
134
+ function parseGithubPrUrl(prUrl) {
135
+ const match = /^https?:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)\/?$/i.exec(prUrl.trim());
136
+ if (!match)
137
+ return null;
138
+ const prNumber = Number.parseInt(match[3], 10);
139
+ if (!Number.isFinite(prNumber))
140
+ return null;
141
+ return { owner: match[1], repo: match[2], repoName: `${match[1]}/${match[2]}`, prNumber };
142
+ }
143
+ function checkName(check) {
144
+ return String(check.name ?? check.context ?? "").trim();
145
+ }
146
+ function checkState(check) {
147
+ return String(check.conclusion ?? check.state ?? check.status ?? "").trim().toLowerCase();
148
+ }
149
+ function isGreptileLabel(value) {
150
+ return String(value ?? "").toLowerCase().includes("greptile");
151
+ }
152
+ function isGreptileGithubLogin(value) {
153
+ const login = String(value ?? "").toLowerCase().replace(/\[bot\]$/, "");
154
+ return login === "greptile" || login === "greptile-ai" || login === "greptileai" || login === "greptile-apps";
155
+ }
156
+ function isPassingCheck(check) {
157
+ const state = checkState(check);
158
+ return ["success", "successful", "passed", "neutral", "skipped", "completed"].includes(state);
159
+ }
160
+ function isPendingCheck(check) {
161
+ const state = checkState(check);
162
+ return ["pending", "queued", "in_progress", "waiting", "requested", "expected", "action_required"].includes(state);
163
+ }
164
+ function isFailingCheck(check) {
165
+ const state = checkState(check);
166
+ return ["failure", "failed", "timed_out", "action_required", "cancelled", "canceled", "error"].includes(state);
167
+ }
168
+ function wildcardToRegExp(pattern) {
169
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
170
+ return new RegExp(`^${escaped}$`, "i");
171
+ }
172
+ function isAllowedFailure(name, allowedFailures) {
173
+ return allowedFailures.some((pattern) => wildcardToRegExp(pattern).test(name));
174
+ }
175
+ function greptileScorePatterns() {
176
+ return [
177
+ /\b(?:confidence\s+score|confidence|rating|score)\s*:?\s*(\d+)\s*\/\s*(\d+)/gi,
178
+ /\b(\d+)\s*\/\s*(\d+)\s*(?:confidence|rating|score)/gi,
179
+ /\bgreptile[^\n]{0,80}?(\d+)\s*\/\s*(\d+)/gi
180
+ ];
181
+ }
182
+ function parseGreptileScores(input) {
183
+ const text = stripHtml(input);
184
+ const seen = new Set;
185
+ const scores = [];
186
+ for (const pattern of greptileScorePatterns()) {
187
+ for (const match of text.matchAll(pattern)) {
188
+ const value = Number.parseInt(match[1] || "", 10);
189
+ const scale = Number.parseInt(match[2] || "", 10);
190
+ if (!Number.isFinite(value) || !Number.isFinite(scale) || scale <= 0)
191
+ continue;
192
+ const raw = match[0] || `${value}/${scale}`;
193
+ const key = `${match.index ?? -1}:${value}/${scale}:${raw.toLowerCase()}`;
194
+ if (seen.has(key))
195
+ continue;
196
+ seen.add(key);
197
+ scores.push({ value, scale, raw });
198
+ }
199
+ }
200
+ return scores;
201
+ }
202
+ function parseGreptileScore(input) {
203
+ return parseGreptileScores(input)[0] ?? null;
204
+ }
205
+ function stripHtml(input) {
206
+ return input.replace(/<[^>]+>/g, " ").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/\r/g, "").replace(/\n{3,}/g, `
207
+
208
+ `).trim();
209
+ }
210
+ function containsBlockerText(input) {
211
+ const text = stripHtml(input).replace(/\b(?:no|without|zero)\s+blockers?\b/gi, " ").replace(/\bno\s+changes\s+requested\b/gi, " ");
212
+ 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|\breject(?:ed|ion)?\b|\bskip(?:ped)?\b|status\s*:\s*(?:reject(?:ed)?|skip(?:ped)?|failed)/i.test(text);
213
+ }
214
+ function isStrictFiveOfFive(score) {
215
+ return score.value === 5 && score.scale === 5;
216
+ }
217
+ function containsConflictingScoreText(input) {
218
+ return parseGreptileScores(input).some((score) => !isStrictFiveOfFive(score));
219
+ }
220
+ function extractGreptileCommentBlock(input) {
221
+ const match = input.match(/<!--\s*greptile_comment\s*-->([\s\S]*?)<!--\s*\/greptile_comment\s*-->/i);
222
+ return match?.[1]?.trim() ?? null;
223
+ }
224
+ function extractGreptileBodyReviewedSha(input) {
225
+ const block = extractGreptileCommentBlock(input);
226
+ if (!block)
227
+ return null;
228
+ const commitLink = block.match(/\/commit\/([0-9a-f]{40})(?:\b|[^0-9a-f])/i);
229
+ return commitLink?.[1]?.toLowerCase() ?? null;
230
+ }
231
+ function isoAtOrAfter(value, floor) {
232
+ if (!value || !floor)
233
+ return false;
234
+ const valueMs = Date.parse(value);
235
+ const floorMs = Date.parse(floor);
236
+ return Number.isFinite(valueMs) && Number.isFinite(floorMs) && valueMs >= floorMs;
237
+ }
238
+ function greptileStatusVerdict(status) {
239
+ const normalized = String(status ?? "").trim().toUpperCase().replace(/[\s-]+/g, "_");
240
+ if (!normalized)
241
+ return null;
242
+ if (["APPROVE", "APPROVED"].includes(normalized))
243
+ return "approved";
244
+ if (["REJECT", "REJECTED", "CHANGES_REQUESTED", "CHANGE_REQUESTED"].includes(normalized))
245
+ return "rejected";
246
+ if (["SKIP", "SKIPPED"].includes(normalized))
247
+ return "skipped";
248
+ if (["FAIL", "FAILED", "FAILURE", "ERROR"].includes(normalized))
249
+ return "failed";
250
+ if (["PENDING", "QUEUED", "IN_PROGRESS", "RUNNING", "STARTED", "REQUESTED", "REVIEWING_FILES", "GENERATING_SUMMARY"].includes(normalized))
251
+ return "pending";
252
+ if (["COMPLETE", "COMPLETED"].includes(normalized))
253
+ return "completed";
254
+ return null;
255
+ }
256
+ function isBlockingGreptileVerdict(verdict) {
257
+ return verdict === "rejected" || verdict === "skipped" || verdict === "failed";
258
+ }
259
+ function greptileRequestTimeoutMs(env) {
260
+ const fallback = 30000;
261
+ const parsed = Number.parseInt(env.GREPTILE_REQUEST_TIMEOUT_MS || `${fallback}`, 10);
262
+ return Number.isFinite(parsed) && parsed >= 1000 ? parsed : fallback;
263
+ }
264
+ function normalizeGreptileMcpCodeReview(entry, fallbackId) {
265
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
266
+ return null;
267
+ const record = entry;
268
+ const id = typeof record.id === "string" ? record.id.trim() : fallbackId?.trim() ?? "";
269
+ if (!id)
270
+ return null;
271
+ const metadataRecord = record.metadata && typeof record.metadata === "object" && !Array.isArray(record.metadata) ? record.metadata : null;
272
+ return {
273
+ id,
274
+ status: typeof record.status === "string" ? record.status : null,
275
+ createdAt: typeof record.createdAt === "string" ? record.createdAt : null,
276
+ body: typeof record.body === "string" ? record.body : null,
277
+ metadata: metadataRecord ? { checkHeadSha: typeof metadataRecord.checkHeadSha === "string" ? metadataRecord.checkHeadSha : null } : null
278
+ };
279
+ }
280
+ function uniqueGreptileCodeReviews(reviews) {
281
+ const seen = new Set;
282
+ const unique = [];
283
+ for (const review of reviews) {
284
+ if (seen.has(review.id))
285
+ continue;
286
+ seen.add(review.id);
287
+ unique.push(review);
288
+ }
289
+ return unique;
290
+ }
291
+ function selectGreptileApiReviewsForGate(reviews, headSha) {
292
+ const sorted = [...reviews].sort((left, right) => Date.parse(right.createdAt ?? "") - Date.parse(left.createdAt ?? ""));
293
+ const current = headSha ? sorted.filter((review) => review.metadata?.checkHeadSha === headSha) : [];
294
+ const untied = sorted.filter((review) => !review.metadata?.checkHeadSha);
295
+ const latest = sorted.slice(0, 1);
296
+ return uniqueGreptileCodeReviews([...current, ...untied, ...latest]);
297
+ }
298
+ function greptileApiSignalFromCodeReview(review, details) {
299
+ const selected = details ?? review;
300
+ return {
301
+ id: selected.id || review.id,
302
+ body: selected.body ?? review.body ?? null,
303
+ reviewedSha: selected.metadata?.checkHeadSha ?? review.metadata?.checkHeadSha ?? null,
304
+ status: selected.status ?? review.status ?? null
305
+ };
306
+ }
307
+ async function callGreptileMcpToolForGate(input) {
308
+ const controller = new AbortController;
309
+ const timeoutId = setTimeout(() => {
310
+ controller.abort(new Error(`Greptile MCP tool ${input.name} timed out after ${input.timeoutMs}ms.`));
311
+ }, input.timeoutMs);
312
+ let response;
313
+ try {
314
+ response = await input.fetchFn(input.apiBase, {
315
+ method: "POST",
316
+ headers: {
317
+ Authorization: `Bearer ${input.apiKey}`,
318
+ "Content-Type": "application/json"
319
+ },
320
+ body: JSON.stringify({
321
+ jsonrpc: "2.0",
322
+ id: `rig-strict-gate-${input.name}-${Date.now()}`,
323
+ method: "tools/call",
324
+ params: { name: input.name, arguments: input.args }
325
+ }),
326
+ signal: controller.signal
327
+ });
328
+ } catch (error) {
329
+ if (controller.signal.aborted) {
330
+ throw controller.signal.reason instanceof Error ? controller.signal.reason : new Error(`Greptile MCP tool ${input.name} timed out after ${input.timeoutMs}ms.`);
331
+ }
332
+ throw error;
333
+ } finally {
334
+ clearTimeout(timeoutId);
335
+ }
336
+ const raw = await response.text();
337
+ if (!response.ok) {
338
+ throw new Error(`HTTP ${response.status}: ${raw}`);
339
+ }
340
+ let envelope;
341
+ try {
342
+ envelope = JSON.parse(raw);
343
+ } catch {
344
+ throw new Error(`Malformed MCP response: ${raw}`);
345
+ }
346
+ if (envelope.error?.message) {
347
+ throw new Error(envelope.error.message);
348
+ }
349
+ const text = (envelope.result?.content ?? []).filter((item) => item.type === "text" && typeof item.text === "string").map((item) => item.text ?? "").join(`
350
+ `).trim();
351
+ if (!text) {
352
+ throw new Error(`MCP tool ${input.name} returned no text payload.`);
353
+ }
354
+ return text;
355
+ }
356
+ async function callGreptileMcpToolJsonForGate(input) {
357
+ const text = await callGreptileMcpToolForGate(input);
358
+ try {
359
+ return JSON.parse(text);
360
+ } catch {
361
+ throw new Error(`MCP tool ${input.name} returned malformed JSON: ${text}`);
362
+ }
363
+ }
364
+ async function collectConfiguredGreptileApiSignals(input) {
365
+ if (!input.enabled || input.options?.enabled === false) {
366
+ return { signals: [], errors: [] };
367
+ }
368
+ const env = input.options?.env ?? process.env;
369
+ const secrets = resolveRuntimeSecrets(env);
370
+ const apiKey = secrets.GREPTILE_API_KEY?.trim() ?? "";
371
+ if (!apiKey) {
372
+ return { signals: [], errors: [] };
373
+ }
374
+ const fetchFn = input.options?.fetch ?? globalThis.fetch;
375
+ if (typeof fetchFn !== "function") {
376
+ return { signals: [], errors: ["Greptile API/MCP evidence read failed: fetch is not available."] };
377
+ }
378
+ const apiBase = secrets.GREPTILE_API_BASE?.trim() || "https://api.greptile.com/mcp";
379
+ const remote = secrets.GREPTILE_REMOTE?.trim() || "github";
380
+ const repository = secrets.GREPTILE_REPOSITORY?.trim() || input.repoName;
381
+ const defaultBranch = secrets.GREPTILE_DEFAULT_BRANCH?.trim() || input.baseRefName?.trim() || "main";
382
+ const timeoutMs = greptileRequestTimeoutMs(env);
383
+ try {
384
+ const listPayload = await callGreptileMcpToolJsonForGate({
385
+ apiBase,
386
+ apiKey,
387
+ name: "list_code_reviews",
388
+ args: {
389
+ name: repository,
390
+ remote,
391
+ defaultBranch,
392
+ prNumber: input.prNumber,
393
+ limit: 20
394
+ },
395
+ timeoutMs,
396
+ fetchFn
397
+ });
398
+ const reviews = (listPayload.codeReviews ?? []).map((entry) => normalizeGreptileMcpCodeReview(entry)).filter((review) => !!review);
399
+ const selectedReviews = selectGreptileApiReviewsForGate(reviews, input.headSha);
400
+ const signals = [];
401
+ for (const review of selectedReviews) {
402
+ const detailsPayload = await callGreptileMcpToolJsonForGate({
403
+ apiBase,
404
+ apiKey,
405
+ name: "get_code_review",
406
+ args: { codeReviewId: review.id },
407
+ timeoutMs,
408
+ fetchFn
409
+ });
410
+ const details = normalizeGreptileMcpCodeReview(detailsPayload.codeReview, review.id) ?? review;
411
+ signals.push(greptileApiSignalFromCodeReview(review, details));
412
+ }
413
+ return { signals, errors: [] };
414
+ } catch (error) {
415
+ return {
416
+ signals: [],
417
+ errors: [`Greptile API/MCP evidence read failed: ${error instanceof Error ? error.message : String(error)}`]
418
+ };
419
+ }
420
+ }
421
+ function firstString(record, keys) {
422
+ for (const key of keys) {
423
+ const value = record[key];
424
+ if (typeof value === "string")
425
+ return value;
426
+ }
427
+ return "";
428
+ }
429
+ function arrayField(record, key) {
430
+ const value = record[key];
431
+ return Array.isArray(value) ? value : [];
432
+ }
433
+ async function runJsonArray(command, args, cwd) {
434
+ const result = await command(args, { cwd });
435
+ const label = `gh ${args.join(" ")}`;
436
+ if (result.exitCode !== 0) {
437
+ return { value: [], error: `${label} failed (${result.exitCode}): ${result.stderr ?? result.stdout ?? ""}`.trim() };
438
+ }
439
+ const parsed = parseJsonArray(result.stdout);
440
+ return parsed.error ? { value: parsed.value, error: `${label} returned invalid JSON: ${parsed.error}` } : { value: parsed.value };
441
+ }
442
+ async function runJsonObject(command, args, cwd) {
443
+ const result = await command(args, { cwd });
444
+ const label = `gh ${args.join(" ")}`;
445
+ if (result.exitCode !== 0) {
446
+ return { value: {}, error: `${label} failed (${result.exitCode}): ${result.stderr ?? result.stdout ?? ""}`.trim() };
447
+ }
448
+ const parsed = parseJsonObject(result.stdout);
449
+ return parsed.error ? { value: parsed.value, error: `${label} returned invalid JSON: ${parsed.error}` } : { value: parsed.value };
450
+ }
451
+ function normalizeStatusCheck(entry) {
452
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
453
+ return null;
454
+ const record = entry;
455
+ const name = firstString(record, ["name", "context"]);
456
+ if (!name.trim())
457
+ return null;
458
+ const output = record.output && typeof record.output === "object" && !Array.isArray(record.output) ? record.output : null;
459
+ const app = record.app && typeof record.app === "object" && !Array.isArray(record.app) ? record.app : null;
460
+ return {
461
+ __typename: typeof record.__typename === "string" ? record.__typename : null,
462
+ name,
463
+ context: typeof record.context === "string" ? record.context : null,
464
+ status: typeof record.status === "string" ? record.status : null,
465
+ state: typeof record.state === "string" ? record.state : null,
466
+ conclusion: typeof record.conclusion === "string" ? record.conclusion : null,
467
+ 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,
468
+ link: typeof record.link === "string" ? record.link : typeof record.html_url === "string" ? record.html_url : null,
469
+ headSha: typeof record.headSha === "string" ? record.headSha : null,
470
+ head_sha: typeof record.head_sha === "string" ? record.head_sha : null,
471
+ output: output ? {
472
+ title: typeof output.title === "string" ? output.title : null,
473
+ summary: typeof output.summary === "string" ? output.summary : null,
474
+ text: typeof output.text === "string" ? output.text : null
475
+ } : null,
476
+ app: app ? {
477
+ slug: typeof app.slug === "string" ? app.slug : null,
478
+ name: typeof app.name === "string" ? app.name : null,
479
+ owner: app.owner && typeof app.owner === "object" ? app.owner : null
480
+ } : null
481
+ };
482
+ }
483
+ function normalizeReview(entry) {
484
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
485
+ return null;
486
+ const record = entry;
487
+ return {
488
+ id: typeof record.id === "string" ? record.id : typeof record.id === "number" ? String(record.id) : null,
489
+ state: typeof record.state === "string" ? record.state : null,
490
+ body: typeof record.body === "string" ? record.body : null,
491
+ 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,
492
+ html_url: typeof record.html_url === "string" ? record.html_url : typeof record.url === "string" ? record.url : null,
493
+ author: record.author && typeof record.author === "object" ? record.author : record.user && typeof record.user === "object" ? record.user : null
494
+ };
495
+ }
496
+ function normalizeReviewComment(entry) {
497
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
498
+ return null;
499
+ const record = entry;
500
+ const body = typeof record.body === "string" ? record.body : null;
501
+ const path = typeof record.path === "string" ? record.path : null;
502
+ if (!body && !path)
503
+ return null;
504
+ return {
505
+ id: typeof record.id === "string" || typeof record.id === "number" ? record.id : null,
506
+ user: record.user && typeof record.user === "object" ? record.user : null,
507
+ author: record.author && typeof record.author === "object" ? record.author : null,
508
+ body,
509
+ path,
510
+ html_url: typeof record.html_url === "string" ? record.html_url : null,
511
+ url: typeof record.url === "string" ? record.url : null,
512
+ commit_id: typeof record.commit_id === "string" ? record.commit_id : null,
513
+ original_commit_id: typeof record.original_commit_id === "string" ? record.original_commit_id : null
514
+ };
515
+ }
516
+ function normalizeIssueComment(entry) {
517
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
518
+ return null;
519
+ const record = entry;
520
+ const body = typeof record.body === "string" ? record.body : null;
521
+ if (!body)
522
+ return null;
523
+ return {
524
+ id: typeof record.id === "string" || typeof record.id === "number" ? record.id : null,
525
+ user: record.user && typeof record.user === "object" ? record.user : null,
526
+ author: record.author && typeof record.author === "object" ? record.author : null,
527
+ body,
528
+ html_url: typeof record.html_url === "string" ? record.html_url : null,
529
+ url: typeof record.url === "string" ? record.url : null,
530
+ created_at: typeof record.created_at === "string" ? record.created_at : null
531
+ };
532
+ }
533
+ function normalizeReviewThread(entry) {
534
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
535
+ return null;
536
+ const record = entry;
537
+ return {
538
+ id: typeof record.id === "string" ? record.id : null,
539
+ isResolved: typeof record.isResolved === "boolean" ? record.isResolved : null,
540
+ isOutdated: typeof record.isOutdated === "boolean" ? record.isOutdated : null,
541
+ comments: record.comments && typeof record.comments === "object" ? record.comments : null
542
+ };
543
+ }
544
+ function relevantIssueComment(comment) {
545
+ const login = comment.user?.login ?? comment.author?.login ?? "";
546
+ const body = comment.body ?? "";
547
+ return isGreptileGithubLogin(login) || containsBlockerText(body) || /greptile|score|confidence|\b\d+\s*\/\s*5\b/i.test(body);
548
+ }
549
+ function latestThreadComment(thread) {
550
+ const nodes = thread.comments?.nodes ?? [];
551
+ return nodes.length > 0 ? nodes[nodes.length - 1] : null;
552
+ }
553
+ function unresolvedThreadSummaries(threads) {
554
+ return threads.flatMap((thread) => {
555
+ if (thread.isResolved === true || thread.isOutdated === true)
556
+ return [];
557
+ const latest = latestThreadComment(thread);
558
+ if (!latest)
559
+ return ["Unresolved review thread"];
560
+ const path = latest.path ? ` on ${latest.path}` : "";
561
+ return [`Unresolved review thread${path}: ${(latest.body ?? "").trim() || "(empty comment)"}`];
562
+ });
563
+ }
564
+ function collectBodies(evidence) {
565
+ return [
566
+ evidence.title ?? "",
567
+ evidence.body,
568
+ ...evidence.reviews.map((review) => review.body ?? ""),
569
+ ...evidence.changedFileReviewComments.map((comment) => comment.body ?? ""),
570
+ ...evidence.relevantIssueComments.map((comment) => comment.body ?? ""),
571
+ ...evidence.reviewThreads.flatMap((thread) => thread.comments?.nodes?.map((comment) => comment.body ?? "") ?? []),
572
+ ...(evidence.apiSignals ?? []).map((signal) => signal.body ?? "")
573
+ ].filter((body) => body.trim().length > 0);
574
+ }
575
+ function bodyExcerpt(body) {
576
+ const text = stripHtml(body).replace(/\s+/g, " ").trim();
577
+ return text.length > 240 ? `${text.slice(0, 237)}...` : text;
578
+ }
579
+ function makeGreptileSignal(input) {
580
+ const scores = parseGreptileScores(input.body);
581
+ const reviewedSha = input.reviewedSha?.trim() || null;
582
+ const current = reviewedSha ? reviewedSha === input.currentHeadSha : null;
583
+ const verdict = input.verdict ?? null;
584
+ const blocker = input.blocker ?? (isBlockingGreptileVerdict(verdict) || containsBlockerText(input.body));
585
+ const explicitApproval = input.explicitApproval ?? false;
586
+ return {
587
+ source: input.source,
588
+ trusted: input.trusted,
589
+ authorLogin: input.authorLogin ?? null,
590
+ reviewedSha,
591
+ current,
592
+ stale: current === false,
593
+ score: scores[0] ?? null,
594
+ scores,
595
+ explicitApproval,
596
+ verdict,
597
+ blocker,
598
+ actionable: input.actionable ?? blocker,
599
+ bodyExcerpt: bodyExcerpt(input.body),
600
+ body: input.body,
601
+ allScores: scores
602
+ };
603
+ }
604
+ function reviewAuthorLogin(review) {
605
+ return review.author?.login ?? null;
606
+ }
607
+ function commentAuthorLogin(comment) {
608
+ return comment.user?.login ?? comment.author?.login ?? null;
609
+ }
610
+ function collectGreptileSignals(evidence) {
611
+ const signals = [];
612
+ const greptileBodyReviewedSha = extractGreptileBodyReviewedSha(evidence.body);
613
+ const trustedGreptileBody = Boolean(greptileBodyReviewedSha && isGreptileGithubLogin(evidence.bodyEditorLogin) && isoAtOrAfter(evidence.bodyLastEditedAt, evidence.headCommittedDate));
614
+ const contextSources = [
615
+ { source: "pr-title", body: evidence.title ?? "" },
616
+ {
617
+ source: "pr-body",
618
+ body: evidence.body,
619
+ trusted: trustedGreptileBody,
620
+ authorLogin: trustedGreptileBody ? evidence.bodyEditorLogin ?? null : null,
621
+ reviewedSha: greptileBodyReviewedSha,
622
+ verdict: trustedGreptileBody ? "completed" : null
623
+ }
624
+ ];
625
+ for (const context of contextSources) {
626
+ if (!context.body.trim())
627
+ continue;
628
+ const contextBlocker = containsBlockerText(context.body);
629
+ if (!contextBlocker && !/greptile|score|confidence|\b\d+\s*\/\s*5\b/i.test(context.body))
630
+ continue;
631
+ signals.push(makeGreptileSignal({
632
+ source: context.source,
633
+ body: context.body,
634
+ currentHeadSha: evidence.currentHeadSha,
635
+ trusted: context.trusted === true,
636
+ authorLogin: context.authorLogin,
637
+ reviewedSha: context.reviewedSha,
638
+ verdict: context.verdict,
639
+ blocker: contextBlocker,
640
+ actionable: contextBlocker
641
+ }));
642
+ }
643
+ for (const apiSignal of evidence.apiSignals ?? []) {
644
+ const body = [apiSignal.status ? `Status: ${apiSignal.status}` : "", apiSignal.body ?? ""].filter(Boolean).join(`
645
+
646
+ `) || "Status: UNKNOWN";
647
+ const verdict = greptileStatusVerdict(apiSignal.status);
648
+ signals.push(makeGreptileSignal({
649
+ source: "api",
650
+ body,
651
+ currentHeadSha: evidence.currentHeadSha,
652
+ trusted: true,
653
+ reviewedSha: apiSignal.reviewedSha ?? null,
654
+ explicitApproval: verdict === "approved",
655
+ verdict
656
+ }));
657
+ }
658
+ for (const review of evidence.reviews) {
659
+ const login = reviewAuthorLogin(review);
660
+ if (!isGreptileGithubLogin(login))
661
+ continue;
662
+ const state = String(review.state ?? "").toUpperCase();
663
+ const body = [state ? `Review state: ${state}` : "", review.body ?? ""].filter(Boolean).join(`
664
+
665
+ `);
666
+ if (!body.trim())
667
+ continue;
668
+ const dismissed = state === "DISMISSED";
669
+ signals.push(makeGreptileSignal({
670
+ source: "github-review",
671
+ body,
672
+ currentHeadSha: evidence.currentHeadSha,
673
+ trusted: !dismissed,
674
+ authorLogin: login,
675
+ reviewedSha: review.commit_id ?? null,
676
+ explicitApproval: undefined,
677
+ blocker: state === "CHANGES_REQUESTED" || undefined
678
+ }));
679
+ }
680
+ for (const comment of evidence.relevantIssueComments) {
681
+ const login = commentAuthorLogin(comment);
682
+ const body = comment.body ?? "";
683
+ if (!body.trim() || !isGreptileGithubLogin(login))
684
+ continue;
685
+ signals.push(makeGreptileSignal({
686
+ source: "issue-comment",
687
+ body,
688
+ currentHeadSha: evidence.currentHeadSha,
689
+ trusted: true,
690
+ authorLogin: login
691
+ }));
692
+ }
693
+ for (const thread of evidence.reviewThreads) {
694
+ if (thread.isOutdated === true || thread.isResolved === true)
695
+ continue;
696
+ for (const comment of thread.comments?.nodes ?? []) {
697
+ const login = comment.author?.login ?? null;
698
+ const body = comment.body ?? "";
699
+ if (!body.trim() || !isGreptileGithubLogin(login))
700
+ continue;
701
+ signals.push(makeGreptileSignal({
702
+ source: "review-thread",
703
+ body,
704
+ currentHeadSha: evidence.currentHeadSha,
705
+ trusted: true,
706
+ authorLogin: login
707
+ }));
708
+ }
709
+ }
710
+ for (const check of evidence.checks) {
711
+ if (!isGreptileLabel(checkName(check)))
712
+ continue;
713
+ const reviewedSha = check.headSha ?? check.head_sha ?? null;
714
+ const label = `${checkName(check)} (${checkState(check) || "unknown"})`;
715
+ const body = [label, check.output?.title ?? "", check.output?.summary ?? "", check.output?.text ?? ""].filter((entry) => entry.trim().length > 0).join(`
716
+
717
+ `);
718
+ signals.push(makeGreptileSignal({
719
+ source: "github-check",
720
+ body,
721
+ currentHeadSha: evidence.currentHeadSha,
722
+ trusted: false,
723
+ reviewedSha,
724
+ explicitApproval: false,
725
+ blocker: isFailingCheck(check),
726
+ actionable: isFailingCheck(check)
727
+ }));
728
+ }
729
+ return signals;
730
+ }
731
+ function unresolvedGreptileThreadSummaries(threads) {
732
+ return threads.flatMap((thread) => {
733
+ if (thread.isResolved === true || thread.isOutdated === true)
734
+ return [];
735
+ const comments = thread.comments?.nodes ?? [];
736
+ if (!comments.some((comment) => isGreptileGithubLogin(comment.author?.login)))
737
+ return [];
738
+ const latest = latestThreadComment(thread);
739
+ if (!latest)
740
+ return ["Unresolved Greptile review thread"];
741
+ const path = latest.path ? ` on ${latest.path}` : "";
742
+ return [`Unresolved Greptile review thread${path}: ${(latest.body ?? "").trim() || "(empty comment)"}`];
743
+ });
744
+ }
745
+ function actionableChangedFileCommentSummaries(_comments) {
746
+ return [];
747
+ }
748
+ function issueLevelBlockerSummaries(comments) {
749
+ return comments.flatMap((comment) => {
750
+ const body = comment.body?.trim() ?? "";
751
+ if (!body || !containsBlockerText(body) && !containsConflictingScoreText(body))
752
+ return [];
753
+ const login = commentAuthorLogin(comment) ?? "unknown";
754
+ const author = isGreptileGithubLogin(login) ? `Greptile issue comment by ${login}` : `Issue-level PR comment by ${login}`;
755
+ return [`${author}: ${body}`];
756
+ });
757
+ }
758
+ function reviewBodyBlockerSummaries(reviews) {
759
+ return reviews.flatMap((review) => {
760
+ const login = reviewAuthorLogin(review) ?? "unknown";
761
+ if (isGreptileGithubLogin(login))
762
+ return [];
763
+ const body = review.body?.trim() ?? "";
764
+ if (!body || !containsBlockerText(body) && !containsConflictingScoreText(body))
765
+ return [];
766
+ const state = review.state ? ` (${review.state})` : "";
767
+ return [`PR review summary by ${login}${state}: ${body}`];
768
+ });
769
+ }
770
+ function signalLabel(signal) {
771
+ const source = signal.source.replace(/-/g, " ");
772
+ const author = signal.authorLogin ? ` by ${signal.authorLogin}` : "";
773
+ const sha = signal.reviewedSha ? ` at ${signal.reviewedSha}` : "";
774
+ return `${source}${author}${sha}`;
775
+ }
776
+ function deriveGreptileEvidence(input) {
777
+ const rawBodies = collectBodies(input);
778
+ const signals = collectGreptileSignals(input);
779
+ const trustedSignals = signals.filter((signal) => signal.trusted);
780
+ const trustedScoreEntries = trustedSignals.flatMap((signal) => signal.allScores.map((score2) => ({ score: score2, signal })));
781
+ const contextScoreEntries = signals.filter((signal) => !signal.trusted).flatMap((signal) => signal.allScores.map((score2) => ({ score: score2, signal })));
782
+ const allScoreEntries = [...trustedScoreEntries, ...contextScoreEntries];
783
+ const staleSignals = signals.filter((signal) => !!signal.reviewedSha && signal.reviewedSha !== input.currentHeadSha && (signal.trusted || signal.source === "github-check"));
784
+ const isCurrentOrUntied = (signal) => !signal.reviewedSha || signal.reviewedSha === input.currentHeadSha;
785
+ const currentOrUntiedScoreEntries = allScoreEntries.filter((entry) => isCurrentOrUntied(entry.signal));
786
+ const lowScoreEntries = currentOrUntiedScoreEntries.filter((entry) => !isStrictFiveOfFive(entry.score));
787
+ const currentPendingApiSignals = trustedSignals.filter((signal) => signal.source === "api" && signal.verdict === "pending" && isCurrentOrUntied(signal));
788
+ const signalCanApproveByScore = (signal) => {
789
+ if (signal.source === "api")
790
+ return signal.verdict === "approved" || signal.verdict === "completed";
791
+ return signal.verdict !== "pending" && !isBlockingGreptileVerdict(signal.verdict);
792
+ };
793
+ const approvingScoreEntry = trustedScoreEntries.find((entry) => entry.signal.reviewedSha === input.currentHeadSha && entry.signal.source !== "github-check" && signalCanApproveByScore(entry.signal) && isStrictFiveOfFive(entry.score)) ?? null;
794
+ const approvingExplicitSignal = trustedSignals.find((signal) => signal.source === "api" && signal.reviewedSha === input.currentHeadSha && signal.explicitApproval === true && !signal.blocker) ?? null;
795
+ const approvedByScore = !!approvingScoreEntry;
796
+ const approvedByExplicitMapping = !!approvingExplicitSignal;
797
+ const approvingSignal = approvingScoreEntry?.signal ?? approvingExplicitSignal;
798
+ const lowestScore = lowScoreEntries.map((entry) => entry.score).sort((left, right) => left.value - right.value)[0] ?? null;
799
+ const score = lowestScore ?? approvingScoreEntry?.score ?? trustedScoreEntries[0]?.score ?? contextScoreEntries[0]?.score ?? null;
800
+ const failedGreptileChecks = input.checks.filter((check) => isGreptileLabel(checkName(check)) && isFailingCheck(check)).map((check) => `${checkName(check)} (${checkState(check) || "failed"})`);
801
+ const blockerSignals = signals.filter((signal) => (signal.blocker || signal.actionable) && (!signal.reviewedSha || signal.reviewedSha === input.currentHeadSha));
802
+ const staleBlockingSignals = [];
803
+ const blockers = [
804
+ ...blockerSignals.map((signal) => `${signalLabel(signal)}: ${signal.bodyExcerpt || "blocker text"}`),
805
+ ...reviewBodyBlockerSummaries(input.reviews),
806
+ ...issueLevelBlockerSummaries(input.relevantIssueComments),
807
+ ...lowScoreEntries.map((entry) => `Greptile score from ${signalLabel(entry.signal)} is ${entry.score.value}/${entry.score.scale}; strict merge requires trusted current-head 5/5.`),
808
+ ...staleBlockingSignals.map((signal) => `Greptile blocking signal from ${signalLabel(signal)} is stale; current PR head is ${input.currentHeadSha || "unknown"}.`),
809
+ ...failedGreptileChecks.map((entry) => `Greptile check failed: ${entry}`)
810
+ ];
811
+ const unresolvedComments = [
812
+ ...unresolvedGreptileThreadSummaries(input.reviewThreads),
813
+ ...actionableChangedFileCommentSummaries(input.changedFileReviewComments)
814
+ ];
815
+ const greptileChecks = input.checks.filter((check) => isGreptileLabel(checkName(check)));
816
+ const greptileReviews = input.reviews.filter((review) => isGreptileGithubLogin(review.author?.login));
817
+ const completedGreptileCheck = greptileChecks.some((check) => {
818
+ const reviewedSha2 = check.headSha ?? check.head_sha ?? null;
819
+ return reviewedSha2 === input.currentHeadSha && (isPassingCheck(check) || isFailingCheck(check));
820
+ });
821
+ const completedGreptileReview = greptileReviews.some((review) => {
822
+ const state = String(review.state ?? "").toUpperCase();
823
+ const completedState = ["APPROVED", "COMMENTED", "CHANGES_REQUESTED"].includes(state) || !!review.body?.trim();
824
+ return completedState && review.commit_id === input.currentHeadSha;
825
+ });
826
+ const completedGreptileApi = trustedSignals.some((signal) => signal.source === "api" && signal.reviewedSha === input.currentHeadSha && (signal.verdict === "approved" || signal.verdict === "rejected" || signal.verdict === "skipped" || signal.verdict === "failed" || signal.verdict === "completed"));
827
+ const approvalReviewedSha = approvingSignal?.reviewedSha ?? null;
828
+ const reviewedSha = approvalReviewedSha ?? staleSignals[0]?.reviewedSha ?? trustedSignals.map((signal) => signal.reviewedSha ?? null).find(Boolean) ?? null;
829
+ const fresh = !!approvalReviewedSha && approvalReviewedSha === input.currentHeadSha;
830
+ const completed = completedGreptileCheck || completedGreptileReview || completedGreptileApi || !!approvingSignal;
831
+ const hasGreptileEvidence = trustedSignals.length > 0 || signals.some((signal) => /greptile/i.test(signal.body));
832
+ const approved = fresh && completed && !blockers.length && !unresolvedComments.length && currentPendingApiSignals.length === 0 && (approvedByScore || approvedByExplicitMapping);
833
+ const mapping = !hasGreptileEvidence ? "missing" : staleSignals.length > 0 && !approvingSignal ? "stale" : approvedByScore ? "score-5-of-5" : approvedByExplicitMapping ? "explicit-approved" : "unproven";
834
+ const source = approvingSignal?.source === "api" ? "api" : approvingSignal?.source === "github-review" ? "github-review" : approvingSignal?.source === "pr-body" || approvingSignal?.source === "pr-title" ? "pr-body" : 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";
835
+ return {
836
+ source,
837
+ currentHeadSha: input.currentHeadSha,
838
+ reviewedSha,
839
+ fresh,
840
+ completed,
841
+ approved,
842
+ score,
843
+ explicitApproval: approvedByExplicitMapping,
844
+ blockers,
845
+ unresolvedComments,
846
+ rawBodies,
847
+ signals: signals.map(({ body: _body, allScores: _allScores, ...signal }) => signal),
848
+ mapping
849
+ };
850
+ }
851
+ function isGreptileCheckDetail(check) {
852
+ return isGreptileLabel(checkName(check)) || isGreptileGithubLogin(check.app?.slug) || isGreptileGithubLogin(check.app?.owner?.login) || isGreptileLabel(check.app?.name);
853
+ }
854
+ async function collectGreptileCheckDetails(input) {
855
+ const checkRunsRead = await runJsonObject(input.command, [
856
+ "api",
857
+ `repos/${input.repoName}/commits/${input.headSha}/check-runs`,
858
+ "-F",
859
+ "per_page=100"
860
+ ], input.projectRoot);
861
+ const checkRuns = arrayField(checkRunsRead.value, "check_runs").map(normalizeStatusCheck).filter((entry) => !!entry).filter(isGreptileCheckDetail);
862
+ return checkRunsRead.error ? { value: checkRuns, error: checkRunsRead.error } : { value: checkRuns };
863
+ }
864
+ async function collectPullRequestProvenance(input) {
865
+ const response = await runJsonObject(input.command, [
866
+ "api",
867
+ "graphql",
868
+ "-F",
869
+ `owner=${input.owner}`,
870
+ "-F",
871
+ `name=${input.name}`,
872
+ "-F",
873
+ `prNumber=${input.prNumber}`,
874
+ "-f",
875
+ "query=query($owner: String!, $name: String!, $prNumber: Int!) { repository(owner:$owner, name:$name) { pullRequest(number:$prNumber) { lastEditedAt editor { login } commits(last: 1) { nodes { commit { oid committedDate } } } } } }"
876
+ ], input.projectRoot);
877
+ if (response.error)
878
+ return { value: {}, error: response.error };
879
+ const data = response.value.data;
880
+ const repository = data?.repository;
881
+ const pullRequest = repository?.pullRequest;
882
+ if (!pullRequest)
883
+ return { value: {}, error: "GitHub pullRequest provenance response did not include a pullRequest object" };
884
+ const editor = pullRequest.editor;
885
+ const commits = pullRequest.commits;
886
+ const nodes = Array.isArray(commits?.nodes) ? commits.nodes : [];
887
+ const latestCommitNode = nodes[nodes.length - 1];
888
+ const latestCommit = latestCommitNode?.commit;
889
+ return {
890
+ value: {
891
+ bodyEditorLogin: typeof editor?.login === "string" ? editor.login : null,
892
+ bodyLastEditedAt: typeof pullRequest.lastEditedAt === "string" ? pullRequest.lastEditedAt : null,
893
+ headCommittedDate: typeof latestCommit?.committedDate === "string" ? latestCommit.committedDate : null
894
+ }
895
+ };
896
+ }
897
+ async function collectReviewThreads(input) {
898
+ const reviewThreads = [];
899
+ let afterCursor = null;
900
+ for (let page = 0;page < 100; page += 1) {
901
+ const afterLiteral = afterCursor ? JSON.stringify(afterCursor) : "null";
902
+ const threadsResponse = await runJsonObject(input.command, [
903
+ "api",
904
+ "graphql",
905
+ "-F",
906
+ `owner=${input.owner}`,
907
+ "-F",
908
+ `name=${input.name}`,
909
+ "-F",
910
+ `prNumber=${input.prNumber}`,
911
+ "-f",
912
+ `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 } } } } }`
913
+ ], input.projectRoot);
914
+ if (threadsResponse.error) {
915
+ return { value: reviewThreads, error: threadsResponse.error };
916
+ }
917
+ const data = threadsResponse.value.data;
918
+ const repository = data?.repository;
919
+ const pullRequest = repository?.pullRequest;
920
+ const threads = pullRequest?.reviewThreads;
921
+ const nodes = threads?.nodes;
922
+ if (!Array.isArray(nodes)) {
923
+ return { value: reviewThreads, error: "GitHub reviewThreads response did not include a nodes array" };
924
+ }
925
+ const normalized = nodes.map(normalizeReviewThread).filter((entry) => !!entry);
926
+ reviewThreads.push(...normalized);
927
+ const truncatedCommentThread = normalized.find((thread) => thread.comments?.pageInfo?.hasNextPage === true);
928
+ if (truncatedCommentThread) {
929
+ return { value: reviewThreads, error: `GitHub review thread ${truncatedCommentThread.id ?? "unknown"} has more than 100 comments; nested pagination is incomplete` };
930
+ }
931
+ const pageInfo = threads?.pageInfo;
932
+ if (!pageInfo) {
933
+ if (nodes.length >= 100) {
934
+ return { value: reviewThreads, error: "GitHub reviewThreads pagination metadata missing after a full page" };
935
+ }
936
+ return { value: reviewThreads };
937
+ }
938
+ if (pageInfo.hasNextPage !== true) {
939
+ return { value: reviewThreads };
940
+ }
941
+ if (typeof pageInfo.endCursor !== "string" || !pageInfo.endCursor.trim()) {
942
+ return { value: reviewThreads, error: "GitHub reviewThreads pagination reported hasNextPage without endCursor" };
943
+ }
944
+ afterCursor = pageInfo.endCursor;
945
+ }
946
+ return { value: reviewThreads, error: "GitHub reviewThreads pagination exceeded 100 pages" };
947
+ }
948
+ async function collectPrReviewEvidence(input) {
949
+ const parsed = parseGithubPrUrl(input.prUrl);
950
+ if (!parsed) {
951
+ throw new Error(`Cannot parse GitHub PR URL: ${input.prUrl}`);
952
+ }
953
+ const readErrors = [];
954
+ const viewRead = await runJsonObject(input.command, [
955
+ "pr",
956
+ "view",
957
+ input.prUrl,
958
+ "--json",
959
+ "title,body,headRefOid,headRefName,baseRefName,state,isDraft,mergeable,mergeStateStatus,reviewDecision,reviews,statusCheckRollup"
960
+ ], input.projectRoot);
961
+ if (viewRead.error)
962
+ readErrors.push(viewRead.error);
963
+ const view = viewRead.value;
964
+ if (!Array.isArray(view.statusCheckRollup)) {
965
+ readErrors.push("gh pr view did not return required statusCheckRollup array");
966
+ }
967
+ if (!Array.isArray(view.reviews)) {
968
+ readErrors.push("gh pr view did not return required reviews array");
969
+ }
970
+ const headSha = firstString(view, ["headRefOid", "headSha", "head_sha"]);
971
+ const baseRefName = firstString(view, ["baseRefName"]);
972
+ const statusCheckRollup = arrayField(view, "statusCheckRollup").map(normalizeStatusCheck).filter((entry) => !!entry);
973
+ const reviews = arrayField(view, "reviews").map(normalizeReview).filter((entry) => !!entry);
974
+ const provenanceRead = await collectPullRequestProvenance({
975
+ command: input.command,
976
+ projectRoot: input.projectRoot,
977
+ owner: parsed.owner,
978
+ name: parsed.repo,
979
+ prNumber: parsed.prNumber
980
+ });
981
+ const provenance = provenanceRead.value;
982
+ const reviewCommentsRead = await runJsonArray(input.command, ["api", `repos/${parsed.repoName}/pulls/${parsed.prNumber}/comments`, "--paginate"], input.projectRoot);
983
+ if (reviewCommentsRead.error)
984
+ readErrors.push(reviewCommentsRead.error);
985
+ const reviewComments = reviewCommentsRead.value.map(normalizeReviewComment).filter((entry) => !!entry);
986
+ const issueCommentsRead = await runJsonArray(input.command, ["api", `repos/${parsed.repoName}/issues/${parsed.prNumber}/comments`, "--paginate"], input.projectRoot);
987
+ if (issueCommentsRead.error)
988
+ readErrors.push(issueCommentsRead.error);
989
+ const issueComments = issueCommentsRead.value.map(normalizeIssueComment).filter((entry) => !!entry).filter(relevantIssueComment);
990
+ const reviewThreadsRead = await collectReviewThreads({
991
+ command: input.command,
992
+ projectRoot: input.projectRoot,
993
+ owner: parsed.owner,
994
+ name: parsed.repo,
995
+ prNumber: parsed.prNumber
996
+ });
997
+ if (reviewThreadsRead.error)
998
+ readErrors.push(reviewThreadsRead.error);
999
+ const reviewThreads = reviewThreadsRead.value;
1000
+ const greptileRollupChecks = statusCheckRollup.filter((check) => isGreptileLabel(checkName(check)));
1001
+ let greptileCheckDetails = [];
1002
+ if (headSha && greptileRollupChecks.length > 0) {
1003
+ const checkDetailsRead = await collectGreptileCheckDetails({
1004
+ command: input.command,
1005
+ projectRoot: input.projectRoot,
1006
+ repoName: parsed.repoName,
1007
+ headSha
1008
+ });
1009
+ greptileCheckDetails = checkDetailsRead.value;
1010
+ }
1011
+ const checksWithGreptileDetails = [...statusCheckRollup, ...greptileCheckDetails];
1012
+ const shouldCollectConfiguredGreptileApi = input.greptileApi?.enabled !== false;
1013
+ const configuredGreptileApiRead = await collectConfiguredGreptileApiSignals({
1014
+ enabled: shouldCollectConfiguredGreptileApi,
1015
+ options: input.greptileApi,
1016
+ repoName: parsed.repoName,
1017
+ prNumber: parsed.prNumber,
1018
+ headSha,
1019
+ baseRefName
1020
+ });
1021
+ readErrors.push(...configuredGreptileApiRead.errors);
1022
+ const apiSignals = [...input.apiSignals ?? [], ...configuredGreptileApiRead.signals];
1023
+ 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})` : ""}`);
1024
+ const pendingChecks = statusCheckRollup.filter((check) => isPendingCheck(check) && (isGreptileLabel(checkName(check)) || !isAllowedFailure(checkName(check), input.allowedFailures ?? []))).map((check) => `Check pending: ${checkName(check)}`);
1025
+ const evidenceBase = {
1026
+ title: firstString(view, ["title"]),
1027
+ body: firstString(view, ["body"]),
1028
+ bodyEditorLogin: provenance.bodyEditorLogin ?? null,
1029
+ bodyLastEditedAt: provenance.bodyLastEditedAt ?? null,
1030
+ headCommittedDate: provenance.headCommittedDate ?? null,
1031
+ reviews,
1032
+ changedFileReviewComments: reviewComments,
1033
+ relevantIssueComments: issueComments,
1034
+ reviewThreads,
1035
+ checks: checksWithGreptileDetails,
1036
+ currentHeadSha: headSha,
1037
+ apiSignals
1038
+ };
1039
+ const greptile = deriveGreptileEvidence(evidenceBase);
1040
+ return {
1041
+ prUrl: input.prUrl,
1042
+ prNumber: parsed.prNumber,
1043
+ repoName: parsed.repoName,
1044
+ title: evidenceBase.title,
1045
+ body: evidenceBase.body,
1046
+ bodyEditorLogin: evidenceBase.bodyEditorLogin,
1047
+ bodyLastEditedAt: evidenceBase.bodyLastEditedAt,
1048
+ headCommittedDate: evidenceBase.headCommittedDate,
1049
+ headSha,
1050
+ headRefName: firstString(view, ["headRefName"]),
1051
+ baseRefName,
1052
+ state: firstString(view, ["state"]),
1053
+ isDraft: typeof view.isDraft === "boolean" ? view.isDraft : null,
1054
+ mergeable: firstString(view, ["mergeable"]),
1055
+ mergeStateStatus: firstString(view, ["mergeStateStatus"]),
1056
+ reviewDecision: firstString(view, ["reviewDecision"]),
1057
+ reviews,
1058
+ reviewThreads,
1059
+ changedFileReviewComments: reviewComments,
1060
+ relevantIssueComments: issueComments,
1061
+ statusCheckRollup: checksWithGreptileDetails,
1062
+ checkFailures,
1063
+ pendingChecks,
1064
+ readErrors,
1065
+ greptile
1066
+ };
1067
+ }
1068
+ function capGateMessage(value, maxChars = 1200) {
1069
+ const normalized = value.trim();
1070
+ return normalized.length > maxChars ? `${normalized.slice(0, maxChars)}
1071
+ [truncated for gate summary; see full evidence artifact]` : normalized;
1072
+ }
1073
+ function evaluateEvidence(evidence) {
1074
+ const reasonDetails = [];
1075
+ const warnings = [];
1076
+ const seen = new Set;
1077
+ const addReason = (reason) => {
1078
+ const capped = { ...reason, message: capGateMessage(reason.message) };
1079
+ const key = `${capped.code}:${capped.message}`;
1080
+ if (seen.has(key))
1081
+ return;
1082
+ seen.add(key);
1083
+ reasonDetails.push(capped);
1084
+ };
1085
+ const greptile = evidence.greptile;
1086
+ const staleSignal = greptile.signals.find((signal) => signal.reviewedSha && signal.reviewedSha !== evidence.headSha);
1087
+ const hasPendingGreptileCheck = evidence.pendingChecks.some((check) => /greptile/i.test(check));
1088
+ const pendingGreptileApiSignals = greptile.signals.filter((signal) => signal.source === "api" && signal.verdict === "pending" && (!signal.reviewedSha || signal.reviewedSha === evidence.headSha));
1089
+ const unknownGreptileApiSignals = greptile.signals.filter((signal) => signal.source === "api" && !signal.verdict && (!signal.reviewedSha || signal.reviewedSha === evidence.headSha));
1090
+ const awaitingFreshGreptileProof = hasPendingGreptileCheck || pendingGreptileApiSignals.length > 0 || !greptile.completed || greptile.mapping === "missing" || greptile.mapping === "stale";
1091
+ for (const error of evidence.readErrors) {
1092
+ addReason({
1093
+ code: "read_error",
1094
+ reasonClass: "reject",
1095
+ surface: error.startsWith("Greptile API/MCP") ? "greptile" : "github",
1096
+ suggestedAction: "needs_attention",
1097
+ message: `Required PR evidence surface could not be read completely: ${error}`,
1098
+ headSha: evidence.headSha || null
1099
+ });
1100
+ }
1101
+ if (!evidence.headSha) {
1102
+ addReason({
1103
+ code: "missing_head_sha",
1104
+ reasonClass: "reject",
1105
+ surface: "github",
1106
+ suggestedAction: "needs_attention",
1107
+ message: "PR head SHA could not be read; current-head Greptile approval cannot be proven.",
1108
+ headSha: null
1109
+ });
1110
+ }
1111
+ for (const failure of evidence.checkFailures) {
1112
+ addReason({
1113
+ code: "ci_failed",
1114
+ reasonClass: "reject",
1115
+ surface: "ci",
1116
+ suggestedAction: "fix",
1117
+ message: failure,
1118
+ headSha: evidence.headSha || null
1119
+ });
1120
+ }
1121
+ for (const pendingCheck of evidence.pendingChecks) {
1122
+ addReason({
1123
+ code: "check_pending",
1124
+ reasonClass: "pending",
1125
+ surface: "ci",
1126
+ suggestedAction: "wait",
1127
+ message: pendingCheck,
1128
+ headSha: evidence.headSha || null
1129
+ });
1130
+ }
1131
+ const reviewDecision = String(evidence.reviewDecision ?? "").toUpperCase();
1132
+ if (reviewDecision === "CHANGES_REQUESTED" || reviewDecision === "REVIEW_REQUIRED") {
1133
+ addReason({
1134
+ code: "review_decision_blocking",
1135
+ reasonClass: "reject",
1136
+ surface: "review",
1137
+ suggestedAction: "fix",
1138
+ message: `Required review is unresolved (${evidence.reviewDecision}).`,
1139
+ headSha: evidence.headSha || null
1140
+ });
1141
+ }
1142
+ for (const thread of unresolvedThreadSummaries(evidence.reviewThreads)) {
1143
+ addReason({
1144
+ code: "review_thread_unresolved",
1145
+ reasonClass: "reject",
1146
+ surface: "review",
1147
+ suggestedAction: "fix",
1148
+ message: thread,
1149
+ headSha: evidence.headSha || null
1150
+ });
1151
+ }
1152
+ if (greptile.mapping === "missing") {
1153
+ addReason({
1154
+ code: "greptile_missing",
1155
+ reasonClass: "pending",
1156
+ surface: "greptile",
1157
+ suggestedAction: "wait",
1158
+ message: "Missing Greptile check/review evidence for this PR.",
1159
+ headSha: evidence.headSha || null
1160
+ });
1161
+ }
1162
+ if (greptile.mapping === "stale" || greptile.reviewedSha && greptile.reviewedSha !== evidence.headSha || !greptile.approved && staleSignal) {
1163
+ addReason({
1164
+ code: "greptile_stale",
1165
+ reasonClass: "pending",
1166
+ surface: "greptile",
1167
+ suggestedAction: "wait",
1168
+ message: `Greptile evidence is stale (reviewed ${greptile.reviewedSha ?? staleSignal?.reviewedSha ?? "unknown"}, current ${evidence.headSha || "unknown"}).`,
1169
+ headSha: evidence.headSha || null,
1170
+ reviewedSha: greptile.reviewedSha ?? staleSignal?.reviewedSha ?? null
1171
+ });
1172
+ }
1173
+ for (const signal of pendingGreptileApiSignals) {
1174
+ addReason({
1175
+ code: "greptile_pending",
1176
+ reasonClass: "pending",
1177
+ surface: "greptile",
1178
+ suggestedAction: "wait",
1179
+ message: `Greptile API/MCP review is pending for the current PR head${signal.bodyExcerpt ? `: ${signal.bodyExcerpt}` : "."}`,
1180
+ headSha: evidence.headSha || null,
1181
+ reviewedSha: signal.reviewedSha ?? null
1182
+ });
1183
+ }
1184
+ for (const signal of unknownGreptileApiSignals) {
1185
+ addReason({
1186
+ code: "greptile_api_status_unknown",
1187
+ reasonClass: "reject",
1188
+ surface: "greptile",
1189
+ suggestedAction: "needs_attention",
1190
+ message: `Greptile API/MCP review status is unknown; merge requires a known terminal APPROVED/COMPLETED 5/5 result or a known conservative status${signal.bodyExcerpt ? `: ${signal.bodyExcerpt}` : "."}`,
1191
+ headSha: evidence.headSha || null,
1192
+ reviewedSha: signal.reviewedSha ?? null
1193
+ });
1194
+ }
1195
+ if (!greptile.completed) {
1196
+ addReason({
1197
+ code: "greptile_pending",
1198
+ reasonClass: "pending",
1199
+ surface: "greptile",
1200
+ suggestedAction: "wait",
1201
+ message: "Greptile check/review has not completed for the current PR head.",
1202
+ headSha: evidence.headSha || null,
1203
+ reviewedSha: greptile.reviewedSha ?? null
1204
+ });
1205
+ }
1206
+ if (!greptile.fresh) {
1207
+ addReason({
1208
+ code: "greptile_not_current_head",
1209
+ reasonClass: awaitingFreshGreptileProof ? "pending" : "reject",
1210
+ surface: "greptile",
1211
+ suggestedAction: awaitingFreshGreptileProof ? "wait" : "ask_greptile",
1212
+ message: "Greptile approval is not tied to the current PR head SHA.",
1213
+ headSha: evidence.headSha || null,
1214
+ reviewedSha: greptile.reviewedSha ?? null
1215
+ });
1216
+ }
1217
+ if (greptile.score && !(greptile.score.scale === 5 && greptile.score.value === 5)) {
1218
+ addReason({
1219
+ code: "greptile_score_not_5",
1220
+ reasonClass: "reject",
1221
+ surface: "greptile",
1222
+ suggestedAction: "fix",
1223
+ message: `Greptile score is ${greptile.score.value}/${greptile.score.scale}; strict merge requires trusted current-head 5/5.`,
1224
+ headSha: evidence.headSha || null,
1225
+ reviewedSha: greptile.reviewedSha ?? null
1226
+ });
1227
+ }
1228
+ const hasApprovedMapping = greptile.mapping === "score-5-of-5" || greptile.mapping === "explicit-approved";
1229
+ if (!greptile.score && !hasApprovedMapping) {
1230
+ addReason({
1231
+ code: "greptile_score_missing",
1232
+ reasonClass: awaitingFreshGreptileProof ? "pending" : "reject",
1233
+ surface: "greptile",
1234
+ suggestedAction: awaitingFreshGreptileProof ? "wait" : "ask_greptile",
1235
+ message: "No parseable Greptile 5/5 score or direct current-head Greptile API APPROVED mapping was found from trusted evidence; merge is blocked.",
1236
+ headSha: evidence.headSha || null,
1237
+ reviewedSha: greptile.reviewedSha ?? null
1238
+ });
1239
+ }
1240
+ if (greptile.mapping === "unproven") {
1241
+ addReason({
1242
+ code: "greptile_mapping_unproven",
1243
+ reasonClass: awaitingFreshGreptileProof ? "pending" : "reject",
1244
+ surface: "greptile",
1245
+ suggestedAction: awaitingFreshGreptileProof ? "wait" : "ask_greptile",
1246
+ message: "Greptile approval mapping is unproven; PR body/title or a green check alone cannot approve merge.",
1247
+ headSha: evidence.headSha || null,
1248
+ reviewedSha: greptile.reviewedSha ?? null
1249
+ });
1250
+ }
1251
+ for (const blocker of greptile.blockers) {
1252
+ addReason({
1253
+ code: "greptile_blocker_text",
1254
+ reasonClass: "reject",
1255
+ surface: "greptile",
1256
+ suggestedAction: "fix",
1257
+ message: `Greptile/blocker text: ${blocker}`,
1258
+ headSha: evidence.headSha || null,
1259
+ reviewedSha: greptile.reviewedSha ?? null
1260
+ });
1261
+ }
1262
+ for (const comment of greptile.unresolvedComments) {
1263
+ addReason({
1264
+ code: "greptile_unresolved_comment",
1265
+ reasonClass: "reject",
1266
+ surface: "greptile",
1267
+ suggestedAction: "fix",
1268
+ message: comment,
1269
+ headSha: evidence.headSha || null,
1270
+ reviewedSha: greptile.reviewedSha ?? null
1271
+ });
1272
+ }
1273
+ if (!greptile.approved)
1274
+ warnings.push(`Greptile approval mapping is ${greptile.mapping}.`);
1275
+ const pending = reasonDetails.length > 0 && reasonDetails.every((reason) => reason.reasonClass === "pending");
1276
+ return { reasons: reasonDetails.map((reason) => reason.message), reasonDetails, warnings, pending };
1277
+ }
1278
+ function evaluateStrictPrMergeGate(evidence) {
1279
+ const evaluated = evaluateEvidence(evidence);
1280
+ const approved = evaluated.reasonDetails.length === 0 && evidence.greptile.approved;
1281
+ return {
1282
+ approved,
1283
+ pending: evaluated.pending,
1284
+ reasons: evaluated.reasons,
1285
+ reasonDetails: evaluated.reasonDetails,
1286
+ warnings: evaluated.warnings,
1287
+ actionableFeedback: evaluated.reasons,
1288
+ evidence
1289
+ };
1290
+ }
1291
+ function strictMergeHeadShaFromGate(result, prUrl) {
1292
+ if (!result.approved) {
1293
+ throw new Error(`Refusing to merge ${prUrl}: strict merge gate is not approved.`);
1294
+ }
1295
+ if (result.evidence.prUrl !== prUrl) {
1296
+ throw new Error(`Refusing to merge ${prUrl}: strict merge gate evidence belongs to ${result.evidence.prUrl}.`);
1297
+ }
1298
+ const headSha = result.evidence.headSha?.trim();
1299
+ if (!headSha) {
1300
+ throw new Error(`Refusing to merge ${prUrl}: strict merge gate did not provide a current head SHA.`);
1301
+ }
1302
+ if (!/^[0-9a-f]{40}$/i.test(headSha)) {
1303
+ throw new Error(`Refusing to merge ${prUrl}: strict merge gate head is not a raw 40-character commit SHA.`);
1304
+ }
1305
+ if (!result.evidence.greptile.fresh || result.evidence.greptile.currentHeadSha !== headSha) {
1306
+ throw new Error(`Refusing to merge ${prUrl}: strict merge gate approval is not tied to head ${headSha}.`);
1307
+ }
1308
+ if (result.evidence.greptile.mapping !== "score-5-of-5" && result.evidence.greptile.mapping !== "explicit-approved") {
1309
+ throw new Error(`Refusing to merge ${prUrl}: strict merge gate mapping is ${result.evidence.greptile.mapping}.`);
1310
+ }
1311
+ return headSha;
1312
+ }
1313
+ function promptExcerpt(value, maxChars = 4000) {
1314
+ return value.length > maxChars ? `${value.slice(0, maxChars)}
1315
+
1316
+ [truncated for prompt; see full evidence artifact]` : value;
1317
+ }
1318
+ function promptJsonExcerpt(value, maxChars = 6000) {
1319
+ return promptExcerpt(JSON.stringify(value, null, 2), maxChars);
1320
+ }
1321
+ function buildStrictPrGateSteeringPrompt(result) {
1322
+ const evidence = result.evidence;
1323
+ const unresolvedReviewThreads = evidence.reviewThreads.filter((thread) => thread.isResolved !== true && thread.isOutdated !== true);
1324
+ const displayedReasons = result.reasons.slice(0, 20).map((reason) => `- ${promptExcerpt(reason, 1200)}`);
1325
+ if (result.reasons.length > displayedReasons.length) {
1326
+ displayedReasons.push(`- ${result.reasons.length - displayedReasons.length} additional gate reasons omitted from prompt; see merge-gate-result.json.`);
1327
+ }
1328
+ const lines = [
1329
+ `Strict PR merge gate blocked ${evidence.prUrl}.`,
1330
+ `PR title: ${evidence.title || "(empty)"}`,
1331
+ `Current PR head SHA: ${evidence.headSha || "unknown"}`,
1332
+ `Greptile mapping: ${evidence.greptile.mapping}`,
1333
+ evidence.greptile.score ? `Greptile score: ${evidence.greptile.score.value}/${evidence.greptile.score.scale}` : "Greptile score: not proven",
1334
+ "",
1335
+ "Gate reasons:",
1336
+ ...displayedReasons.length ? displayedReasons : ["- No reasons recorded"],
1337
+ "",
1338
+ "Structured gate reason details:",
1339
+ result.reasonDetails.length ? promptJsonExcerpt(result.reasonDetails, 4000) : "[]",
1340
+ "",
1341
+ "Required evidence read status:",
1342
+ evidence.readErrors.length ? promptJsonExcerpt(evidence.readErrors, 2000) : "All required PR evidence surfaces were read completely.",
1343
+ "",
1344
+ "Full PR title:",
1345
+ evidence.title || "(empty)",
1346
+ "",
1347
+ "PR body excerpt:",
1348
+ evidence.body ? promptExcerpt(evidence.body) : "(empty)",
1349
+ "",
1350
+ "All review comments on changed files:",
1351
+ evidence.changedFileReviewComments.length ? promptJsonExcerpt(evidence.changedFileReviewComments) : "[]",
1352
+ "",
1353
+ "Unresolved review threads:",
1354
+ unresolvedReviewThreads.length ? promptJsonExcerpt(unresolvedReviewThreads) : "[]",
1355
+ "",
1356
+ "Relevant issue-level PR comments:",
1357
+ evidence.relevantIssueComments.length ? promptJsonExcerpt(evidence.relevantIssueComments) : "[]",
1358
+ "",
1359
+ "CI/check failures and pending checks:",
1360
+ promptJsonExcerpt({ failures: evidence.checkFailures, pending: evidence.pendingChecks, rollup: evidence.statusCheckRollup }),
1361
+ "",
1362
+ "Greptile evidence:",
1363
+ promptJsonExcerpt(evidence.greptile)
1364
+ ];
1365
+ if (result.artifacts) {
1366
+ lines.push("", "Full evidence artifacts:", JSON.stringify(result.artifacts, null, 2));
1367
+ }
1368
+ return lines.join(`
1369
+ `);
1370
+ }
1371
+ function persistPrReviewCycleArtifacts(input) {
1372
+ const cycleName = input.final ? `${input.cycle}-final` : String(input.cycle);
1373
+ const taskArtifactRoot = input.artifactRoot?.trim() ? input.artifactRoot : resolve(input.projectRoot, "artifacts", input.taskId);
1374
+ const root = resolve(taskArtifactRoot, "pr-review-cycles", cycleName);
1375
+ mkdirSync(root, { recursive: true });
1376
+ const finalMergeGateResultPath = input.final ? resolve(taskArtifactRoot, "merge-gate-final.json") : undefined;
1377
+ const paths = {
1378
+ root,
1379
+ prTitlePath: resolve(root, "pr-title.md"),
1380
+ prBodyPath: resolve(root, "pr-body.md"),
1381
+ prCommentsPath: resolve(root, "pr-comments.json"),
1382
+ reviewThreadsPath: resolve(root, "review-threads.json"),
1383
+ reviewCommentsPath: resolve(root, "review-comments.json"),
1384
+ checkRollupPath: resolve(root, "check-rollup.json"),
1385
+ greptileEvidencePath: resolve(root, "greptile-evidence.json"),
1386
+ mergeGateResultPath: resolve(root, "merge-gate-result.json"),
1387
+ steeringPromptPath: resolve(root, "agent-steering-prompt.md"),
1388
+ ...finalMergeGateResultPath ? { finalMergeGateResultPath } : {}
1389
+ };
1390
+ writeFileSync(paths.prTitlePath, input.result.evidence.title || "", "utf8");
1391
+ writeFileSync(paths.prBodyPath, input.result.evidence.body || "", "utf8");
1392
+ writeFileSync(paths.prCommentsPath, `${JSON.stringify(input.result.evidence.relevantIssueComments, null, 2)}
1393
+ `, "utf8");
1394
+ writeFileSync(paths.reviewThreadsPath, `${JSON.stringify(input.result.evidence.reviewThreads, null, 2)}
1395
+ `, "utf8");
1396
+ writeFileSync(paths.reviewCommentsPath, `${JSON.stringify(input.result.evidence.changedFileReviewComments, null, 2)}
1397
+ `, "utf8");
1398
+ writeFileSync(paths.checkRollupPath, `${JSON.stringify(input.result.evidence.statusCheckRollup, null, 2)}
1399
+ `, "utf8");
1400
+ writeFileSync(paths.greptileEvidencePath, `${JSON.stringify(input.result.evidence.greptile, null, 2)}
1401
+ `, "utf8");
1402
+ const mergeGatePayload = {
1403
+ approved: input.result.approved,
1404
+ pending: input.result.pending,
1405
+ reasons: input.result.reasons,
1406
+ reasonDetails: input.result.reasonDetails,
1407
+ warnings: input.result.warnings,
1408
+ actionableFeedback: input.result.actionableFeedback,
1409
+ prUrl: input.result.evidence.prUrl,
1410
+ title: input.result.evidence.title,
1411
+ headSha: input.result.evidence.headSha,
1412
+ readErrors: input.result.evidence.readErrors,
1413
+ greptile: input.result.evidence.greptile,
1414
+ evidence: input.result.evidence,
1415
+ cycleArtifactRoot: root
1416
+ };
1417
+ writeFileSync(paths.mergeGateResultPath, `${JSON.stringify(mergeGatePayload, null, 2)}
1418
+ `, "utf8");
1419
+ if (paths.finalMergeGateResultPath) {
1420
+ writeFileSync(paths.finalMergeGateResultPath, `${JSON.stringify(mergeGatePayload, null, 2)}
1421
+ `, "utf8");
1422
+ }
1423
+ writeFileSync(paths.steeringPromptPath, input.steeringPrompt, "utf8");
1424
+ return paths;
1425
+ }
1426
+ async function runStrictPrMergeGate(input) {
1427
+ const evidence = await collectPrReviewEvidence(input);
1428
+ const base = evaluateStrictPrMergeGate(evidence);
1429
+ const preliminaryPrompt = buildStrictPrGateSteeringPrompt({ ...base, artifacts: undefined });
1430
+ const artifacts = persistPrReviewCycleArtifacts({
1431
+ projectRoot: input.projectRoot,
1432
+ taskId: input.taskId,
1433
+ cycle: input.cycle,
1434
+ artifactRoot: input.artifactRoot,
1435
+ result: base,
1436
+ steeringPrompt: preliminaryPrompt,
1437
+ final: input.final
1438
+ });
1439
+ const steeringPrompt = buildStrictPrGateSteeringPrompt({ ...base, artifacts });
1440
+ writeFileSync(artifacts.steeringPromptPath, steeringPrompt, "utf8");
1441
+ return { ...base, artifacts, steeringPrompt };
1442
+ }
1443
+ export {
1444
+ stripHtml,
1445
+ strictMergeHeadShaFromGate,
1446
+ runStrictPrMergeGate,
1447
+ persistPrReviewCycleArtifacts,
1448
+ parseGreptileScore,
1449
+ parseGithubPrUrl,
1450
+ isGreptileGithubLogin,
1451
+ evaluateStrictPrMergeGate,
1452
+ deriveGreptileEvidence,
1453
+ collectPrReviewEvidence,
1454
+ buildStrictPrGateSteeringPrompt
1455
+ };