File size: 12,703 Bytes
914f53d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
import { loadConfig } from './config.js';
import { isBugbotReviewable, resolveActivePair, substituteBugbotSlot } from './rotate.js';
import { applyResolvedIds, openBlocking, parseResolveIds } from './findings.js';
import {
  createOctokit,
  listAllIssueComments,
  loadOrCreateState,
  prHasLabel,
  removeLabel,
  saveState,
} from './state.js';
import {
  fetchWorkflowStatuses,
  getChangedFiles,
  getPrHeadSha,
  isCiFailed,
  requiredWorkflowsForPaths,
} from './ci-gates.js';
import type { PlanOutput, PrAgentState } from './types.js';

export async function runPlan(repoRoot: string): Promise<PlanOutput> {
  const config = loadConfig(repoRoot);
  const owner = process.env.GITHUB_REPOSITORY_OWNER!;
  const repo = process.env.GITHUB_REPOSITORY?.split('/')[1]!;
  const prNumber = Number(process.env.PR_NUMBER);
  const author = process.env.PR_AUTHOR ?? '';
  const isFork = process.env.PR_IS_FORK === 'true';
  const forceRotation = process.env.FORCE_ROTATION === 'true';

  const octokit = createOctokit();

  if (await prHasLabel(octokit, owner, repo, prNumber, 'agent-stop')) {
    return {
      runBugbot: false,
      runStandards: false,
      runDepth: false,
      activePair: [],
      state: (await loadOrCreateState(octokit, owner, repo, prNumber)).state,
      shouldSkip: true,
      skipReason: 'agent-stop label',
    };
  }

  if (await prHasLabel(octokit, owner, repo, prNumber, 'ready-for-human-review')) {
    const hasResume = await prHasLabel(octokit, owner, repo, prNumber, 'agent-resume');
    if (!hasResume) {
      const { state } = await loadOrCreateState(octokit, owner, repo, prNumber);
      return {
        runBugbot: false,
        runStandards: false,
        runDepth: false,
        activePair: [],
        state,
        shouldSkip: true,
        skipReason: 'awaiting human handoff',
      };
    }
  }

  const labels = await octokit.issues.get({ owner, repo, issue_number: prNumber });
  const labelNames = (labels.data.labels ?? []).map((l) =>
    typeof l === 'string' ? l : l.name!,
  );

  if (config.authors.mode === 'allowlist' && !config.authors.allowlist.includes(author)) {
    return skipPlan(octokit, owner, repo, prNumber, 'author not in allowlist');
  }
  if (config.authors.mode === 'label_only' && !labelNames.includes('agent-review')) {
    return skipPlan(octokit, owner, repo, prNumber, 'missing agent-review label');
  }

  const { state: loadedState, commentId } = await loadOrCreateState(
    octokit,
    owner,
    repo,
    prNumber,
  );
  let state = loadedState;

  // saveState bumps the *remote* revision but cannot update this local copy,
  // so a second write in the same run gets refused as a lost update — and the
  // agent-resume path writes twice, silently dropping everything after it
  // (agent-resolve handling, the selfDispatches reset). Adopt the written
  // revision so later writes in this run still land.
  const persist = async (next: PrAgentState): Promise<PrAgentState> => {
    const { revision } = await saveState(octokit, owner, repo, prNumber, next, commentId);
    return { ...next, revision };
  };

  if (labelNames.includes('agent-resume')) {
    // Grant a fresh budget window. Without resetting cycle/fixRound, a PR
    // that already crossed maxOrchestratorCycles or maxFixRounds would
    // immediately re-trigger budget_exhausted on its very next cycle, making
    // agent-resume a near no-op for any long-lived PR. The finding ledger
    // (openFindings/resolvedFindings/mutedFingerprints) is preserved as-is.
    state = {
      ...state,
      status: 'in_progress',
      consecutiveNoNewReviews: 0,
      cycle: 0,
      fixRound: 0,
      stagnationFixRounds: 0,
    };
    await removeLabel(octokit, owner, repo, prNumber, 'agent-resume');
    await removeLabel(octokit, owner, repo, prNumber, 'ready-for-human-review');
    await removeLabel(octokit, owner, repo, prNumber, 'agent-needs-human');
    await removeLabel(octokit, owner, repo, prNumber, 'agent-ci-failing');
    state = await persist(state);
  }

  // A fresh `pull_request` event means the human moved the PR forward, so the
  // self-dispatch budget for a stalled loop starts over.
  if (process.env.GITHUB_EVENT_NAME === 'pull_request' && state.selfDispatches > 0) {
    state = { ...state, selfDispatches: 0 };
  }

  const resolveIds = parseResolveIds(
    (await listAllIssueComments(octokit, owner, repo, prNumber)).map((c) => c.body),
  );
  if (resolveIds.length > 0) {
    const applied = applyResolvedIds(state, resolveIds, state.cycle);
    if (applied.changed) {
      state = {
        ...state,
        openFindings: applied.openFindings,
        resolvedFindings: applied.resolvedFindings,
        mutedFingerprints: applied.mutedFingerprints,
      };
      state = await persist(state);
      console.log(`Resolved findings via agent-resolve: ${resolveIds.join(', ')}`);
    }
  }

  if (process.env.CI_RECHECK_ONLY === 'true') {
    if (state.status !== 'in_progress') {
      return {
        runBugbot: false,
        runStandards: false,
        runDepth: false,
        activePair: [],
        state,
        shouldSkip: true,
        skipReason: `ci recheck skipped: status ${state.status}`,
      };
    }
    return {
      runBugbot: false,
      runStandards: false,
      runDepth: false,
      activePair: [],
      state,
      shouldSkip: false,
      recheckOnly: true,
    };
  }

  if (state.status !== 'in_progress') {
    return {
      runBugbot: false,
      runStandards: false,
      runDepth: false,
      activePair: [],
      state,
      shouldSkip: true,
      skipReason: `status ${state.status}`,
    };
  }

  // Reviews already converged: no open blocking findings and enough clean
  // cycles for handoff. The only thing left to wait for is CI, so re-running
  // model reviews of an unchanged diff just burns credits (#3648 spent 8 full
  // review cycles — ~16 model runs — reaching a handoff that needed 2). Route
  // straight to the wait-ci -> recheck-handoff path instead.
  if (
    openBlocking(state.openFindings).length === 0 &&
    state.consecutiveNoNewReviews >= config.limits.consecutiveNoNewReviewsForHandoff
  ) {
    // Mirror the cycle-cap block: recheck-handoff no-ops on red CI, so routing a
    // failed-CI workflow_run event to recheckOnly here strands the PR in_progress
    // forever (fixer never runs, no handoff posted). When CI is failing and the
    // fixer still has rounds left, skip model reviews but return the deferral
    // shape (shouldSkip=false, no recheckOnly) so aggregate sets shouldFix and the
    // fixer reacts to the CI failure.
    let ciFailed = process.env.CI_TRIGGER_FAILED === 'true';
    if (!ciFailed && state.fixRound < config.limits.maxFixRounds) {
      try {
        const ref = await getPrHeadSha(octokit, owner, repo, prNumber);
        const changedFiles = await getChangedFiles(octokit, owner, repo, prNumber);
        const required = requiredWorkflowsForPaths(changedFiles, repoRoot);
        const ciChecks = await fetchWorkflowStatuses(octokit, owner, repo, ref, required);
        ciFailed = isCiFailed(ciChecks);
      } catch (err) {
        console.warn('plan: failed to fetch CI status for reviews-clean deferral', err);
      }
    }

    if (ciFailed && state.fixRound < config.limits.maxFixRounds) {
      console.log(
        `Reviews clean but CI failed with fixRound=${state.fixRound}; skipping model reviews, deferring to fixer`,
      );
      state = await persist(state);
      return {
        runBugbot: false,
        runStandards: false,
        runDepth: false,
        activePair: [],
        state,
        shouldSkip: false,
        skipReason: 'reviews clean; CI fix deferred',
      };
    }

    console.log(
      `Reviews clean (consecutiveNoNewReviews=${state.consecutiveNoNewReviews}); skipping model reviews, CI recheck only`,
    );
    state = await persist(state);
    return {
      runBugbot: false,
      runStandards: false,
      runDepth: false,
      activePair: [],
      state,
      shouldSkip: false,
      recheckOnly: true,
      skipReason: 'reviews clean; awaiting CI',
    };
  }

  if (state.cycle >= config.limits.maxOrchestratorCycles) {
    // Mirror aggregate: when CI is red and the fixer still has rounds left,
    // do not force budget_exhausted — continue with reviews skipped so
    // aggregate can set shouldFix and the fixer can react to the CI failure.
    let ciFailed = process.env.CI_TRIGGER_FAILED === 'true';
    if (!ciFailed && state.fixRound < config.limits.maxFixRounds) {
      try {
        const ref = await getPrHeadSha(octokit, owner, repo, prNumber);
        const changedFiles = await getChangedFiles(octokit, owner, repo, prNumber);
        const required = requiredWorkflowsForPaths(changedFiles, repoRoot);
        const ciChecks = await fetchWorkflowStatuses(octokit, owner, repo, ref, required);
        ciFailed = isCiFailed(ciChecks);
      } catch (err) {
        console.warn('plan: failed to fetch CI status for cycle-cap deferral', err);
      }
    }

    if (ciFailed && state.fixRound < config.limits.maxFixRounds) {
      console.log(
        `Cycle cap reached (${state.cycle}) but CI failed with fixRound=${state.fixRound}; deferring handoff for fixer`,
      );
      state = await persist(state);
      return {
        runBugbot: false,
        runStandards: false,
        runDepth: false,
        activePair: [],
        state,
        shouldSkip: false,
        skipReason: 'max cycles deferred for CI fix',
      };
    }

    const exhausted = await persist({ ...state, status: 'budget_exhausted' as const });
    return {
      runBugbot: false,
      runStandards: false,
      runDepth: false,
      activePair: [],
      state: exhausted,
      shouldSkip: true,
      skipReason: 'max cycles',
      shouldHandoff: true,
      handoffReason: 'budget_exhausted',
    };
  }

  let activePair = resolveActivePair(state, forceRotation);

  // Bugbot opens no check run on prose-only diffs, so scheduling it there
  // wastes a poll window and leaves the cycle one opinion short (#3851). Swap
  // in a model slot that actually reviews the change.
  if (activePair.includes('bugbot')) {
    try {
      const changedFiles = await getChangedFiles(octokit, owner, repo, prNumber);
      if (!isBugbotReviewable(changedFiles)) {
        const substituted = substituteBugbotSlot(activePair);
        console.log(
          `Prose-only diff: replacing bugbot slot with ${substituted.join(', ')}`,
        );
        activePair = substituted;
      }
    } catch (err) {
      console.warn('plan: failed to classify diff for bugbot slot; keeping bugbot', err);
    }
  }

  const output: PlanOutput = {
    runBugbot: activePair.includes('bugbot'),
    runStandards: activePair.includes('standards'),
    runDepth: activePair.includes('depth'),
    activePair,
    state,
    shouldSkip: false,
  };

  if (isFork) {
    console.log('Fork PR: reviews only, fixer will be skipped');
  }

  state = await persist(state);
  return output;
}

async function skipPlan(

  octokit: ReturnType<typeof createOctokit>,

  owner: string,

  repo: string,

  prNumber: number,

  reason: string,

): Promise<PlanOutput> {
  const { state } = await loadOrCreateState(octokit, owner, repo, prNumber);
  return {
    runBugbot: false,
    runStandards: false,
    runDepth: false,
    activePair: [],
    state,
    shouldSkip: true,
    skipReason: reason,
  };
}

export async function writePlanOutputs(repoRoot: string, plan: PlanOutput): Promise<void> {
  const { appendFileSync } = await import('node:fs');
  const out = process.env.GITHUB_OUTPUT;
  if (!out) return;

  const set = (k: string, v: string) => appendFileSync(out, `${k}=${v}\n`);

  set('should_skip', String(plan.shouldSkip));
  set('skip_reason', plan.skipReason ?? '');
  set('run_bugbot', String(plan.runBugbot));
  set('run_standards', String(plan.runStandards));
  set('run_depth', String(plan.runDepth));
  set('run_codex', String(plan.activePair.includes('codex')));
  set('active_pair', plan.activePair.join(','));
  set('is_dry_run', String(loadConfig(repoRoot).dryRun));
  set('should_handoff', String(plan.shouldHandoff ?? false));
  set('handoff_reason', plan.handoffReason ?? '');
  set('recheck_only', String(plan.recheckOnly ?? false));
}

export { getChangedFiles };