Files
cal.diy/.github/workflows/devin-conflict-resolver.yml
T

447 lines
20 KiB
YAML

name: Devin PR Conflict Resolver
on:
# Run every 5 minutes instead of on push to main.
# This saves runner costs by avoiding the 20-second sleep that was needed
# to wait for GitHub to compute mergeable status after merges to main.
schedule:
- cron: '*/5 * * * *'
workflow_dispatch:
inputs:
pr_number:
description: 'PR number to resolve conflicts for (optional, bypasses maintainer access check for fork PRs)'
required: false
type: string
permissions:
contents: read
pull-requests: write
jobs:
check-conflicts:
name: Check Open PRs for Conflicts
runs-on: blacksmith-2vcpu-ubuntu-2404
steps:
- name: Get open PRs and check for conflicts
id: check-prs
uses: actions/github-script@v7
env:
INPUT_PR_NUMBER: ${{ inputs.pr_number }}
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const { owner, repo } = context.repo;
const manualPrNumber = process.env.INPUT_PR_NUMBER ? parseInt(process.env.INPUT_PR_NUMBER, 10) : null;
const query = `
query($owner: String!, $repo: String!, $cursor: String) {
repository(owner: $owner, name: $repo) {
pullRequests(states: OPEN, first: 100, after: $cursor) {
pageInfo {
hasNextPage
endCursor
}
nodes {
number
title
mergeable
isDraft
headRefName
baseRefName
url
headRepository {
owner {
login
}
name
}
maintainerCanModify
labels(first: 10) {
nodes {
name
}
}
}
}
}
}
`;
const allPRs = [];
let cursor = null;
do {
const result = await github.graphql(query, { owner, repo, cursor });
const { nodes, pageInfo } = result.repository.pullRequests;
allPRs.push(...nodes);
cursor = pageInfo.hasNextPage ? pageInfo.endCursor : null;
} while (cursor);
console.log(`Found ${allPRs.length} open PRs via GraphQL`);
if (manualPrNumber) {
console.log(`Manual PR number provided: ${manualPrNumber}`);
}
const conflictingPRs = [];
const unknownPRs = [];
function processPR(pr, mergeableStatus) {
const isTargetPR = manualPrNumber && pr.number === manualPrNumber;
const isFork = pr.headRepository?.owner?.login !== owner;
if (!isTargetPR && pr.isDraft) {
console.log(`PR #${pr.number} is a draft, skipping`);
return { skip: true };
}
if (!isTargetPR && isFork) {
console.log(`PR #${pr.number} is from a fork, skipping`);
return { skip: true };
}
if (!isTargetPR) {
const hasDevinLabel = pr.labels.nodes.some(label => label.name === 'devin-conflict-resolution');
if (hasDevinLabel) {
console.log(`PR #${pr.number} already has devin-conflict-resolution label, skipping`);
return { skip: true };
}
}
if (mergeableStatus === 'CONFLICTING' || (isTargetPR && mergeableStatus !== 'MERGEABLE')) {
const headRepoOwner = pr.headRepository?.owner?.login || owner;
const headRepoName = pr.headRepository?.name || repo;
if (isTargetPR) {
console.log(`PR #${pr.number} manually targeted for conflict resolution${isFork ? ' (from fork)' : ''}`);
} else {
console.log(`PR #${pr.number} has conflicts`);
}
return {
conflict: true,
data: {
number: pr.number,
title: pr.title,
head_ref: pr.headRefName,
base_ref: pr.baseRefName,
html_url: pr.url,
is_fork: isFork,
head_repo_owner: headRepoOwner,
head_repo_name: headRepoName,
is_manual: isTargetPR
},
isTargetPR
};
} else if (mergeableStatus === 'UNKNOWN') {
return { unknown: true, isTargetPR };
} else {
console.log(`PR #${pr.number} has no conflicts (mergeable: ${mergeableStatus})`);
return { skip: true };
}
}
for (const pr of allPRs) {
const result = processPR(pr, pr.mergeable);
if (result.conflict) {
conflictingPRs.push(result.data);
if (result.isTargetPR) break;
} else if (result.unknown) {
console.log(`PR #${pr.number} mergeable status is still being computed`);
unknownPRs.push(pr);
}
}
if (unknownPRs.length > 0) {
console.log(`\n${unknownPRs.length} PRs have UNKNOWN mergeable status, retrying via REST API...`);
for (const pr of unknownPRs) {
try {
const { data } = await github.rest.pulls.get({
owner,
repo,
pull_number: pr.number
});
let mergeableStatus;
if (data.mergeable === true) {
mergeableStatus = 'MERGEABLE';
} else if (data.mergeable === false) {
mergeableStatus = 'CONFLICTING';
} else {
mergeableStatus = 'UNKNOWN';
}
console.log(`PR #${pr.number} retry result: mergeable=${mergeableStatus}`);
const result = processPR(pr, mergeableStatus);
if (result.conflict) {
conflictingPRs.push(result.data);
if (result.isTargetPR) break;
} else if (result.unknown) {
console.log(`PR #${pr.number} still has UNKNOWN status, will be checked on next run`);
}
} catch (error) {
console.error(`Error retrying PR #${pr.number}: ${error.message}`);
}
}
}
if (manualPrNumber && conflictingPRs.length === 0) {
console.log(`Warning: PR #${manualPrNumber} not found or has no conflicts`);
}
const MAX_PRS = 15;
if (conflictingPRs.length > MAX_PRS) {
console.log(`Warning: Found ${conflictingPRs.length} PRs with conflicts, limiting to ${MAX_PRS} for safety`);
conflictingPRs.length = MAX_PRS;
}
console.log(`Found ${conflictingPRs.length} PRs with conflicts that need Devin sessions`);
const fs = require('fs');
fs.writeFileSync('/tmp/conflicting-prs.json', JSON.stringify(conflictingPRs));
core.setOutput('has-conflicts', conflictingPRs.length > 0 ? 'true' : 'false');
core.setOutput('conflict-count', conflictingPRs.length.toString());
- name: Handle Devin sessions for conflicting PRs
if: steps.check-prs.outputs.has-conflicts == 'true'
env:
DEVIN_API_KEY: ${{ secrets.DEVIN_API_KEY }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const fs = require('fs');
const conflictingPRs = JSON.parse(fs.readFileSync('/tmp/conflicting-prs.json', 'utf8'));
const { owner, repo } = context.repo;
async function checkSessionStatus(sessionId) {
const response = await fetch(`https://api.devin.ai/v1/sessions/${sessionId}`, {
headers: {
'Authorization': `Bearer ${process.env.DEVIN_API_KEY}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
console.log(`Failed to fetch session ${sessionId}: ${response.status}`);
return null;
}
return await response.json();
}
async function findExistingSession(prNumber, prBody) {
// First check if PR was created through Devin
const prSessionMatch = prBody?.match(/app\.devin\.ai\/sessions\/([a-f0-9-]+)/);
if (prSessionMatch) {
const sessionId = prSessionMatch[1];
console.log(`PR #${prNumber} was created by Devin session: ${sessionId}`);
const session = await checkSessionStatus(sessionId);
if (session) {
return { sessionId, sessionUrl: `https://app.devin.ai/sessions/${sessionId}`, isFromPrBody: true };
}
}
// Check PR comments for existing Devin session (conflict resolution or Cubic AI review)
const comments = await github.rest.issues.listComments({
owner,
repo,
issue_number: prNumber
});
const sessionPatterns = [
'Devin AI is resolving merge conflicts',
'Devin AI is addressing Cubic AI'
];
for (const comment of comments.data.reverse()) {
const hasDevinSession = sessionPatterns.some(pattern => comment.body?.includes(pattern));
if (hasDevinSession) {
const match = comment.body?.match(/app\.devin\.ai\/sessions\/([a-f0-9-]+)/);
if (match) {
const sessionId = match[1];
console.log(`Found existing session from comment: ${sessionId}`);
const session = await checkSessionStatus(sessionId);
if (session) {
const activeStatuses = ['working', 'blocked', 'resumed'];
if (activeStatuses.includes(session.status_enum)) {
console.log(`Session ${sessionId} is active (status: ${session.status_enum})`);
return { sessionId, sessionUrl: `https://app.devin.ai/sessions/${sessionId}`, isFromPrBody: false };
} else {
console.log(`Session ${sessionId} is not active (status: ${session.status_enum})`);
}
}
}
}
}
return null;
}
for (const pr of conflictingPRs) {
console.log(`Processing PR #${pr.number}: ${pr.title}${pr.is_fork ? ' (fork)' : ''}`);
const { data: prDetails } = await github.rest.pulls.get({
owner,
repo,
pull_number: pr.number
});
const existingSession = await findExistingSession(pr.number, prDetails.body);
const forkInstructions = pr.is_fork ? `
IMPORTANT: This PR is from a fork. The contributor has enabled "Allow edits from maintainers".
- Clone the FORK repository: ${pr.head_repo_owner}/${pr.head_repo_name}
- The branch to work on is: ${pr.head_ref}
- Add the upstream remote for ${owner}/${repo}
- Fetch and merge the upstream ${pr.base_ref} branch using standard git merge` : `
- Clone the repository: ${owner}/${repo}
- Check out the PR branch: ${pr.head_ref}
- Merge the base branch (${pr.base_ref}) using standard git merge`;
const conflictResolutionInstructions = `You are resolving merge conflicts on PR #${pr.number} in repository ${owner}/${repo}.
PR Title: ${pr.title}
PR URL: ${pr.html_url}
Head Branch: ${pr.head_ref}
Base Branch: ${pr.base_ref}
${pr.is_fork ? `Fork Repository: ${pr.head_repo_owner}/${pr.head_repo_name}` : ''}
Your tasks:
${forkInstructions}
Then:
1. Resolve all merge conflicts carefully:
- Review the conflicting changes from both branches
- Make intelligent decisions about how to combine the changes
- Preserve the intent of both the PR changes and the base branch updates
- If unsure about a conflict, prefer keeping both changes where possible
2. Test that the code still works after resolving conflicts (run lint/type checks).
3. Commit the merge resolution with a clear commit message.
4. CRITICAL VALIDATION BEFORE PUSHING: You MUST validate your merge commit before pushing:
- Run: git diff --stat HEAD^1...HEAD (shows changes relative to PR branch parent)
- Run: git diff --stat HEAD^2...HEAD (shows changes relative to base branch parent)
- The changes relative to the base branch parent (HEAD^2) should be SIMILAR to the original PR changes, NOT include all the new commits from ${pr.base_ref}
- If your merge commit shows hundreds of files changed or includes changes that were already in ${pr.base_ref}, STOP IMMEDIATELY
- A proper merge commit only contains conflict resolutions, not reproduced changes from the target branch
- If validation fails: DO NOT PUSH. Log the error, explain what went wrong, and abort the task.
5. Push the resolved changes to the PR branch only after validation passes.
6. After successfully pushing the resolved changes, remove the \`devin-conflict-resolution\` label from the PR using the GitHub API.
Rules and Guidelines:
1. Be careful when resolving conflicts - understand the context of both changes.
To help with this, try to find the recent PRs associated with the conflicting files to gain more context.
2. Follow the existing code style and conventions in the repository.
3. Run lint and type checks before pushing to ensure the code is valid.
4. If a conflict seems too complex or risky to resolve automatically, explain the situation in a PR comment instead.
5. Never ask for user confirmation. Never wait for user messages.
6. CRITICAL: If this is a fork PR and you encounter ANY error when pushing (permission denied, authentication failure, etc.), you MUST fail the task immediately. Do NOT attempt to push to a new branch in the main ${owner}/${repo} repository as a workaround. Simply report the error and stop.
7. CRITICAL: Never reproduce or recreate changes from the target branch. Your merge commit should ONLY contain conflict resolutions. If you find yourself manually copying file contents from ${pr.base_ref} or creating changes that mirror what's already in ${pr.base_ref}, you are doing it wrong. Use git's merge functionality properly - it handles bringing in changes automatically.`;
try {
let sessionUrl;
let isNewSession = false;
if (existingSession) {
console.log(`Sending message to existing session ${existingSession.sessionId} for PR #${pr.number}`);
const message = `PR #${pr.number} has new merge conflicts that need to be resolved.
${conflictResolutionInstructions}
Continue working on the same PR branch and push your fixes.`;
const response = await fetch(`https://api.devin.ai/v1/sessions/${existingSession.sessionId}/message`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.DEVIN_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ message })
});
if (!response.ok) {
console.error(`Failed to send message to session ${existingSession.sessionId}: ${response.status}`);
continue;
}
sessionUrl = existingSession.sessionUrl;
console.log(`Message sent to existing session for PR #${pr.number}`);
} else {
console.log(`Creating new Devin session for PR #${pr.number}`);
const response = await fetch('https://api.devin.ai/v1/sessions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.DEVIN_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
prompt: conflictResolutionInstructions,
title: `Resolve Conflicts: PR #${pr.number}`,
tags: ['conflict-resolution', `pr-${pr.number}`]
})
});
if (!response.ok) {
console.error(`Devin API error for PR #${pr.number}: ${response.status} ${response.statusText}`);
continue;
}
const data = await response.json();
sessionUrl = data.url || data.session_url;
isNewSession = true;
}
if (sessionUrl) {
if (isNewSession) {
console.log(`Devin session created for PR #${pr.number}: ${sessionUrl}`);
}
await github.rest.issues.addLabels({
owner,
repo,
issue_number: pr.number,
labels: ['devin-conflict-resolution']
});
const sessionStatusMessage = isNewSession
? 'A Devin session has been created to automatically resolve them.'
: 'The existing Devin session has been notified to resolve them.';
const commentBody = `### Devin AI is resolving merge conflicts
This PR has merge conflicts with the \`${pr.base_ref}\` branch. ${sessionStatusMessage}
[View Devin Session](${sessionUrl})
Devin will:
1. Merge the latest \`${pr.base_ref}\` into this branch
2. Resolve any conflicts intelligently
3. Run lint/type checks to ensure validity
4. Push the resolved changes
If you prefer to resolve conflicts manually, you can close the Devin session and handle it yourself.`;
await github.rest.issues.createComment({
owner,
repo,
issue_number: pr.number,
body: commentBody
});
} else {
console.log(`Failed to get session URL for PR #${pr.number}`);
}
} catch (error) {
console.error(`Error handling Devin session for PR #${pr.number}: ${error.message}`);
}
await new Promise(resolve => setTimeout(resolve, 1000));
}