@h-rig/runtime 0.0.6-alpha.2 → 0.0.6-alpha.21

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