issue_definitions.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758
  1. import json
  2. import os
  3. import re
  4. from abc import ABC, abstractmethod
  5. from typing import Any, ClassVar
  6. import jinja2
  7. import requests
  8. from openhands.core.config import LLMConfig
  9. from openhands.core.logger import openhands_logger as logger
  10. from openhands.events.event import Event
  11. from openhands.llm.llm import LLM
  12. from openhands.resolver.github_issue import GithubIssue, ReviewThread
  13. class IssueHandlerInterface(ABC):
  14. issue_type: ClassVar[str]
  15. llm: LLM
  16. @abstractmethod
  17. def get_converted_issues(
  18. self, issue_numbers: list[int] | None = None, comment_id: int | None = None
  19. ) -> list[GithubIssue]:
  20. """Download issues from GitHub."""
  21. pass
  22. @abstractmethod
  23. def get_instruction(
  24. self,
  25. issue: GithubIssue,
  26. prompt_template: str,
  27. repo_instruction: str | None = None,
  28. ) -> tuple[str, list[str]]:
  29. """Generate instruction and image urls for the agent."""
  30. pass
  31. @abstractmethod
  32. def guess_success(
  33. self, issue: GithubIssue, history: list[Event]
  34. ) -> tuple[bool, list[bool] | None, str]:
  35. """Guess if the issue has been resolved based on the agent's output."""
  36. pass
  37. class IssueHandler(IssueHandlerInterface):
  38. issue_type: ClassVar[str] = 'issue'
  39. def __init__(self, owner: str, repo: str, token: str, llm_config: LLMConfig):
  40. self.download_url = 'https://api.github.com/repos/{}/{}/issues'
  41. self.owner = owner
  42. self.repo = repo
  43. self.token = token
  44. self.llm = LLM(llm_config)
  45. def _download_issues_from_github(self) -> list[Any]:
  46. url = self.download_url.format(self.owner, self.repo)
  47. headers = {
  48. 'Authorization': f'token {self.token}',
  49. 'Accept': 'application/vnd.github.v3+json',
  50. }
  51. params: dict[str, int | str] = {'state': 'open', 'per_page': 100, 'page': 1}
  52. all_issues = []
  53. while True:
  54. response = requests.get(url, headers=headers, params=params)
  55. response.raise_for_status()
  56. issues = response.json()
  57. if not issues:
  58. break
  59. if not isinstance(issues, list) or any(
  60. [not isinstance(issue, dict) for issue in issues]
  61. ):
  62. raise ValueError('Expected list of dictionaries from Github API.')
  63. all_issues.extend(issues)
  64. assert isinstance(params['page'], int)
  65. params['page'] += 1
  66. return all_issues
  67. def _extract_image_urls(self, issue_body: str) -> list[str]:
  68. # Regular expression to match Markdown image syntax ![alt text](image_url)
  69. image_pattern = r'!\[.*?\]\((https?://[^\s)]+)\)'
  70. return re.findall(image_pattern, issue_body)
  71. def _extract_issue_references(self, body: str) -> list[int]:
  72. # First, remove code blocks as they may contain false positives
  73. body = re.sub(r'```.*?```', '', body, flags=re.DOTALL)
  74. # Remove inline code
  75. body = re.sub(r'`[^`]*`', '', body)
  76. # Remove URLs that contain hash symbols
  77. body = re.sub(r'https?://[^\s)]*#\d+[^\s)]*', '', body)
  78. # Now extract issue numbers, making sure they're not part of other text
  79. # The pattern matches #number that:
  80. # 1. Is at the start of text or after whitespace/punctuation
  81. # 2. Is followed by whitespace, punctuation, or end of text
  82. # 3. Is not part of a URL
  83. pattern = r'(?:^|[\s\[({]|[^\w#])#(\d+)(?=[\s,.\])}]|$)'
  84. return [int(match) for match in re.findall(pattern, body)]
  85. def _get_issue_comments(
  86. self, issue_number: int, comment_id: int | None = None
  87. ) -> list[str] | None:
  88. """Download comments for a specific issue from Github."""
  89. url = f'https://api.github.com/repos/{self.owner}/{self.repo}/issues/{issue_number}/comments'
  90. headers = {
  91. 'Authorization': f'token {self.token}',
  92. 'Accept': 'application/vnd.github.v3+json',
  93. }
  94. params = {'per_page': 100, 'page': 1}
  95. all_comments = []
  96. while True:
  97. response = requests.get(url, headers=headers, params=params)
  98. response.raise_for_status()
  99. comments = response.json()
  100. if not comments:
  101. break
  102. if comment_id:
  103. matching_comment = next(
  104. (
  105. comment['body']
  106. for comment in comments
  107. if comment['id'] == comment_id
  108. ),
  109. None,
  110. )
  111. if matching_comment:
  112. return [matching_comment]
  113. else:
  114. all_comments.extend([comment['body'] for comment in comments])
  115. params['page'] += 1
  116. return all_comments if all_comments else None
  117. def get_converted_issues(
  118. self, issue_numbers: list[int] | None = None, comment_id: int | None = None
  119. ) -> list[GithubIssue]:
  120. """Download issues from Github.
  121. Returns:
  122. List of Github issues.
  123. """
  124. if not issue_numbers:
  125. raise ValueError('Unspecified issue number')
  126. all_issues = self._download_issues_from_github()
  127. logger.info(f'Limiting resolving to issues {issue_numbers}.')
  128. all_issues = [
  129. issue
  130. for issue in all_issues
  131. if issue['number'] in issue_numbers and 'pull_request' not in issue
  132. ]
  133. if len(issue_numbers) == 1 and not all_issues:
  134. raise ValueError(f'Issue {issue_numbers[0]} not found')
  135. converted_issues = []
  136. for issue in all_issues:
  137. # Check for required fields (number and title)
  138. if any([issue.get(key) is None for key in ['number', 'title']]):
  139. logger.warning(
  140. f'Skipping issue {issue} as it is missing number or title.'
  141. )
  142. continue
  143. # Handle empty body by using empty string
  144. if issue.get('body') is None:
  145. issue['body'] = ''
  146. # Get issue thread comments
  147. thread_comments = self._get_issue_comments(
  148. issue['number'], comment_id=comment_id
  149. )
  150. # Convert empty lists to None for optional fields
  151. issue_details = GithubIssue(
  152. owner=self.owner,
  153. repo=self.repo,
  154. number=issue['number'],
  155. title=issue['title'],
  156. body=issue['body'],
  157. thread_comments=thread_comments,
  158. review_comments=None, # Initialize review comments as None for regular issues
  159. )
  160. converted_issues.append(issue_details)
  161. return converted_issues
  162. def get_instruction(
  163. self,
  164. issue: GithubIssue,
  165. prompt_template: str,
  166. repo_instruction: str | None = None,
  167. ) -> tuple[str, list[str]]:
  168. """Generate instruction for the agent."""
  169. # Format thread comments if they exist
  170. thread_context = ''
  171. if issue.thread_comments:
  172. thread_context = '\n\nIssue Thread Comments:\n' + '\n---\n'.join(
  173. issue.thread_comments
  174. )
  175. images = []
  176. images.extend(self._extract_image_urls(issue.body))
  177. images.extend(self._extract_image_urls(thread_context))
  178. template = jinja2.Template(prompt_template)
  179. return (
  180. template.render(
  181. body=issue.title + '\n\n' + issue.body + thread_context,
  182. repo_instruction=repo_instruction,
  183. ),
  184. images,
  185. )
  186. def guess_success(
  187. self, issue: GithubIssue, history: list[Event]
  188. ) -> tuple[bool, None | list[bool], str]:
  189. """Guess if the issue is fixed based on the history and the issue description."""
  190. last_message = history[-1].message
  191. # Include thread comments in the prompt if they exist
  192. issue_context = issue.body
  193. if issue.thread_comments:
  194. issue_context += '\n\nIssue Thread Comments:\n' + '\n---\n'.join(
  195. issue.thread_comments
  196. )
  197. with open(
  198. os.path.join(
  199. os.path.dirname(__file__),
  200. 'prompts/guess_success/issue-success-check.jinja',
  201. ),
  202. 'r',
  203. ) as f:
  204. template = jinja2.Template(f.read())
  205. prompt = template.render(issue_context=issue_context, last_message=last_message)
  206. response = self.llm.completion(messages=[{'role': 'user', 'content': prompt}])
  207. answer = response.choices[0].message.content.strip()
  208. pattern = r'--- success\n*(true|false)\n*--- explanation*\n((?:.|\n)*)'
  209. match = re.search(pattern, answer)
  210. if match:
  211. return match.group(1).lower() == 'true', None, match.group(2)
  212. return False, None, f'Failed to decode answer from LLM response: {answer}'
  213. class PRHandler(IssueHandler):
  214. issue_type: ClassVar[str] = 'pr'
  215. def __init__(self, owner: str, repo: str, token: str, llm_config: LLMConfig):
  216. super().__init__(owner, repo, token, llm_config)
  217. self.download_url = 'https://api.github.com/repos/{}/{}/pulls'
  218. def __download_pr_metadata(
  219. self, pull_number: int, comment_id: int | None = None
  220. ) -> tuple[list[str], list[int], list[str], list[ReviewThread], list[str]]:
  221. """Run a GraphQL query against the GitHub API for information.
  222. Retrieves information about:
  223. 1. unresolved review comments
  224. 2. referenced issues the pull request would close
  225. Args:
  226. pull_number: The number of the pull request to query.
  227. comment_id: Optional ID of a specific comment to focus on.
  228. query: The GraphQL query as a string.
  229. variables: A dictionary of variables for the query.
  230. token: Your GitHub personal access token.
  231. Returns:
  232. The JSON response from the GitHub API.
  233. """
  234. # Using graphql as REST API doesn't indicate resolved status for review comments
  235. # TODO: grabbing the first 10 issues, 100 review threads, and 100 coments; add pagination to retrieve all
  236. query = """
  237. query($owner: String!, $repo: String!, $pr: Int!) {
  238. repository(owner: $owner, name: $repo) {
  239. pullRequest(number: $pr) {
  240. closingIssuesReferences(first: 10) {
  241. edges {
  242. node {
  243. body
  244. number
  245. }
  246. }
  247. }
  248. url
  249. reviews(first: 100) {
  250. nodes {
  251. body
  252. state
  253. fullDatabaseId
  254. }
  255. }
  256. reviewThreads(first: 100) {
  257. edges{
  258. node{
  259. id
  260. isResolved
  261. comments(first: 100) {
  262. totalCount
  263. nodes {
  264. body
  265. path
  266. fullDatabaseId
  267. }
  268. }
  269. }
  270. }
  271. }
  272. }
  273. }
  274. }
  275. """
  276. variables = {'owner': self.owner, 'repo': self.repo, 'pr': pull_number}
  277. url = 'https://api.github.com/graphql'
  278. headers = {
  279. 'Authorization': f'Bearer {self.token}',
  280. 'Content-Type': 'application/json',
  281. }
  282. response = requests.post(
  283. url, json={'query': query, 'variables': variables}, headers=headers
  284. )
  285. response.raise_for_status()
  286. response_json = response.json()
  287. # Parse the response to get closing issue references and unresolved review comments
  288. pr_data = (
  289. response_json.get('data', {}).get('repository', {}).get('pullRequest', {})
  290. )
  291. # Get closing issues
  292. closing_issues = pr_data.get('closingIssuesReferences', {}).get('edges', [])
  293. closing_issues_bodies = [issue['node']['body'] for issue in closing_issues]
  294. closing_issue_numbers = [
  295. issue['node']['number'] for issue in closing_issues
  296. ] # Extract issue numbers
  297. # Get review comments
  298. reviews = pr_data.get('reviews', {}).get('nodes', [])
  299. if comment_id is not None:
  300. reviews = [
  301. review
  302. for review in reviews
  303. if int(review['fullDatabaseId']) == comment_id
  304. ]
  305. review_bodies = [review['body'] for review in reviews]
  306. # Get unresolved review threads
  307. review_threads = []
  308. thread_ids = [] # Store thread IDs; agent replies to the thread
  309. raw_review_threads = pr_data.get('reviewThreads', {}).get('edges', [])
  310. for thread in raw_review_threads:
  311. node = thread.get('node', {})
  312. if not node.get(
  313. 'isResolved', True
  314. ): # Check if the review thread is unresolved
  315. id = node.get('id')
  316. thread_contains_comment_id = False
  317. my_review_threads = node.get('comments', {}).get('nodes', [])
  318. message = ''
  319. files = []
  320. for i, review_thread in enumerate(my_review_threads):
  321. if (
  322. comment_id is not None
  323. and int(review_thread['fullDatabaseId']) == comment_id
  324. ):
  325. thread_contains_comment_id = True
  326. if (
  327. i == len(my_review_threads) - 1
  328. ): # Check if it's the last thread in the thread
  329. if len(my_review_threads) > 1:
  330. message += '---\n' # Add "---" before the last message if there's more than one thread
  331. message += 'latest feedback:\n' + review_thread['body'] + '\n'
  332. else:
  333. message += (
  334. review_thread['body'] + '\n'
  335. ) # Add each thread in a new line
  336. file = review_thread.get('path')
  337. if file and file not in files:
  338. files.append(file)
  339. if comment_id is None or thread_contains_comment_id:
  340. unresolved_thread = ReviewThread(comment=message, files=files)
  341. review_threads.append(unresolved_thread)
  342. thread_ids.append(id)
  343. return (
  344. closing_issues_bodies,
  345. closing_issue_numbers,
  346. review_bodies,
  347. review_threads,
  348. thread_ids,
  349. )
  350. # Override processing of downloaded issues
  351. def _get_pr_comments(
  352. self, pr_number: int, comment_id: int | None = None
  353. ) -> list[str] | None:
  354. """Download comments for a specific pull request from Github."""
  355. url = f'https://api.github.com/repos/{self.owner}/{self.repo}/issues/{pr_number}/comments'
  356. headers = {
  357. 'Authorization': f'token {self.token}',
  358. 'Accept': 'application/vnd.github.v3+json',
  359. }
  360. params = {'per_page': 100, 'page': 1}
  361. all_comments = []
  362. while True:
  363. response = requests.get(url, headers=headers, params=params)
  364. response.raise_for_status()
  365. comments = response.json()
  366. if not comments:
  367. break
  368. if comment_id is not None:
  369. matching_comment = next(
  370. (
  371. comment['body']
  372. for comment in comments
  373. if comment['id'] == comment_id
  374. ),
  375. None,
  376. )
  377. if matching_comment:
  378. return [matching_comment]
  379. else:
  380. all_comments.extend([comment['body'] for comment in comments])
  381. params['page'] += 1
  382. return all_comments if all_comments else None
  383. def __get_context_from_external_issues_references(
  384. self,
  385. closing_issues: list[str],
  386. closing_issue_numbers: list[int],
  387. issue_body: str,
  388. review_comments: list[str],
  389. review_threads: list[ReviewThread],
  390. thread_comments: list[str] | None,
  391. ):
  392. new_issue_references = []
  393. if issue_body:
  394. new_issue_references.extend(self._extract_issue_references(issue_body))
  395. if review_comments:
  396. for comment in review_comments:
  397. new_issue_references.extend(self._extract_issue_references(comment))
  398. if review_threads:
  399. for review_thread in review_threads:
  400. new_issue_references.extend(
  401. self._extract_issue_references(review_thread.comment)
  402. )
  403. if thread_comments:
  404. for thread_comment in thread_comments:
  405. new_issue_references.extend(
  406. self._extract_issue_references(thread_comment)
  407. )
  408. non_duplicate_references = set(new_issue_references)
  409. unique_issue_references = non_duplicate_references.difference(
  410. closing_issue_numbers
  411. )
  412. for issue_number in unique_issue_references:
  413. try:
  414. url = f'https://api.github.com/repos/{self.owner}/{self.repo}/issues/{issue_number}'
  415. headers = {
  416. 'Authorization': f'Bearer {self.token}',
  417. 'Accept': 'application/vnd.github.v3+json',
  418. }
  419. response = requests.get(url, headers=headers)
  420. response.raise_for_status()
  421. issue_data = response.json()
  422. issue_body = issue_data.get('body', '')
  423. if issue_body:
  424. closing_issues.append(issue_body)
  425. except requests.exceptions.RequestException as e:
  426. logger.warning(f'Failed to fetch issue {issue_number}: {str(e)}')
  427. return closing_issues
  428. def get_converted_issues(
  429. self, issue_numbers: list[int] | None = None, comment_id: int | None = None
  430. ) -> list[GithubIssue]:
  431. if not issue_numbers:
  432. raise ValueError('Unspecified issue numbers')
  433. all_issues = self._download_issues_from_github()
  434. logger.info(f'Limiting resolving to issues {issue_numbers}.')
  435. all_issues = [issue for issue in all_issues if issue['number'] in issue_numbers]
  436. converted_issues = []
  437. for issue in all_issues:
  438. # For PRs, body can be None
  439. if any([issue.get(key) is None for key in ['number', 'title']]):
  440. logger.warning(f'Skipping #{issue} as it is missing number or title.')
  441. continue
  442. # Handle None body for PRs
  443. body = issue.get('body') if issue.get('body') is not None else ''
  444. (
  445. closing_issues,
  446. closing_issues_numbers,
  447. review_comments,
  448. review_threads,
  449. thread_ids,
  450. ) = self.__download_pr_metadata(issue['number'], comment_id=comment_id)
  451. head_branch = issue['head']['ref']
  452. # Get PR thread comments
  453. thread_comments = self._get_pr_comments(
  454. issue['number'], comment_id=comment_id
  455. )
  456. closing_issues = self.__get_context_from_external_issues_references(
  457. closing_issues,
  458. closing_issues_numbers,
  459. body,
  460. review_comments,
  461. review_threads,
  462. thread_comments,
  463. )
  464. issue_details = GithubIssue(
  465. owner=self.owner,
  466. repo=self.repo,
  467. number=issue['number'],
  468. title=issue['title'],
  469. body=body,
  470. closing_issues=closing_issues,
  471. review_comments=review_comments,
  472. review_threads=review_threads,
  473. thread_ids=thread_ids,
  474. head_branch=head_branch,
  475. thread_comments=thread_comments,
  476. )
  477. converted_issues.append(issue_details)
  478. return converted_issues
  479. def get_instruction(
  480. self,
  481. issue: GithubIssue,
  482. prompt_template: str,
  483. repo_instruction: str | None = None,
  484. ) -> tuple[str, list[str]]:
  485. """Generate instruction for the agent."""
  486. template = jinja2.Template(prompt_template)
  487. images = []
  488. issues_str = None
  489. if issue.closing_issues:
  490. issues_str = json.dumps(issue.closing_issues, indent=4)
  491. images.extend(self._extract_image_urls(issues_str))
  492. # Handle PRs with review comments
  493. review_comments_str = None
  494. if issue.review_comments:
  495. review_comments_str = json.dumps(issue.review_comments, indent=4)
  496. images.extend(self._extract_image_urls(review_comments_str))
  497. # Handle PRs with file-specific review comments
  498. review_thread_str = None
  499. review_thread_file_str = None
  500. if issue.review_threads:
  501. review_threads = [
  502. review_thread.comment for review_thread in issue.review_threads
  503. ]
  504. review_thread_files = []
  505. for review_thread in issue.review_threads:
  506. review_thread_files.extend(review_thread.files)
  507. review_thread_str = json.dumps(review_threads, indent=4)
  508. review_thread_file_str = json.dumps(review_thread_files, indent=4)
  509. images.extend(self._extract_image_urls(review_thread_str))
  510. # Format thread comments if they exist
  511. thread_context = ''
  512. if issue.thread_comments:
  513. thread_context = '\n---\n'.join(issue.thread_comments)
  514. images.extend(self._extract_image_urls(thread_context))
  515. instruction = template.render(
  516. issues=issues_str,
  517. review_comments=review_comments_str,
  518. review_threads=review_thread_str,
  519. files=review_thread_file_str,
  520. thread_context=thread_context,
  521. repo_instruction=repo_instruction,
  522. )
  523. return instruction, images
  524. def _check_feedback_with_llm(self, prompt: str) -> tuple[bool, str]:
  525. """Helper function to check feedback with LLM and parse response."""
  526. response = self.llm.completion(messages=[{'role': 'user', 'content': prompt}])
  527. answer = response.choices[0].message.content.strip()
  528. pattern = r'--- success\n*(true|false)\n*--- explanation*\n((?:.|\n)*)'
  529. match = re.search(pattern, answer)
  530. if match:
  531. return match.group(1).lower() == 'true', match.group(2).strip()
  532. return False, f'Failed to decode answer from LLM response: {answer}'
  533. def _check_review_thread(
  534. self,
  535. review_thread: ReviewThread,
  536. issues_context: str,
  537. last_message: str,
  538. ) -> tuple[bool, str]:
  539. """Check if a review thread's feedback has been addressed."""
  540. files_context = json.dumps(review_thread.files, indent=4)
  541. with open(
  542. os.path.join(
  543. os.path.dirname(__file__),
  544. 'prompts/guess_success/pr-feedback-check.jinja',
  545. ),
  546. 'r',
  547. ) as f:
  548. template = jinja2.Template(f.read())
  549. prompt = template.render(
  550. issue_context=issues_context,
  551. feedback=review_thread.comment,
  552. files_context=files_context,
  553. last_message=last_message,
  554. )
  555. return self._check_feedback_with_llm(prompt)
  556. def _check_thread_comments(
  557. self,
  558. thread_comments: list[str],
  559. issues_context: str,
  560. last_message: str,
  561. ) -> tuple[bool, str]:
  562. """Check if thread comments feedback has been addressed."""
  563. thread_context = '\n---\n'.join(thread_comments)
  564. with open(
  565. os.path.join(
  566. os.path.dirname(__file__), 'prompts/guess_success/pr-thread-check.jinja'
  567. ),
  568. 'r',
  569. ) as f:
  570. template = jinja2.Template(f.read())
  571. prompt = template.render(
  572. issue_context=issues_context,
  573. thread_context=thread_context,
  574. last_message=last_message,
  575. )
  576. return self._check_feedback_with_llm(prompt)
  577. def _check_review_comments(
  578. self,
  579. review_comments: list[str],
  580. issues_context: str,
  581. last_message: str,
  582. ) -> tuple[bool, str]:
  583. """Check if review comments feedback has been addressed."""
  584. review_context = '\n---\n'.join(review_comments)
  585. with open(
  586. os.path.join(
  587. os.path.dirname(__file__), 'prompts/guess_success/pr-review-check.jinja'
  588. ),
  589. 'r',
  590. ) as f:
  591. template = jinja2.Template(f.read())
  592. prompt = template.render(
  593. issue_context=issues_context,
  594. review_context=review_context,
  595. last_message=last_message,
  596. )
  597. return self._check_feedback_with_llm(prompt)
  598. def guess_success(
  599. self, issue: GithubIssue, history: list[Event]
  600. ) -> tuple[bool, None | list[bool], str]:
  601. """Guess if the issue is fixed based on the history and the issue description."""
  602. last_message = history[-1].message
  603. issues_context = json.dumps(issue.closing_issues, indent=4)
  604. success_list = []
  605. explanation_list = []
  606. # Handle PRs with file-specific review comments
  607. if issue.review_threads:
  608. for review_thread in issue.review_threads:
  609. if issues_context and last_message:
  610. success, explanation = self._check_review_thread(
  611. review_thread, issues_context, last_message
  612. )
  613. else:
  614. success, explanation = False, 'Missing context or message'
  615. success_list.append(success)
  616. explanation_list.append(explanation)
  617. # Handle PRs with only thread comments (no file-specific review comments)
  618. elif issue.thread_comments:
  619. if issue.thread_comments and issues_context and last_message:
  620. success, explanation = self._check_thread_comments(
  621. issue.thread_comments, issues_context, last_message
  622. )
  623. else:
  624. success, explanation = (
  625. False,
  626. 'Missing thread comments, context or message',
  627. )
  628. success_list.append(success)
  629. explanation_list.append(explanation)
  630. elif issue.review_comments:
  631. # Handle PRs with only review comments (no file-specific review comments or thread comments)
  632. if issue.review_comments and issues_context and last_message:
  633. success, explanation = self._check_review_comments(
  634. issue.review_comments, issues_context, last_message
  635. )
  636. else:
  637. success, explanation = (
  638. False,
  639. 'Missing review comments, context or message',
  640. )
  641. success_list.append(success)
  642. explanation_list.append(explanation)
  643. else:
  644. # No review comments, thread comments, or file-level review comments found
  645. return False, None, 'No feedback was found to process'
  646. # Return overall success (all must be true) and explanations
  647. if not success_list:
  648. return False, None, 'No feedback was processed'
  649. return all(success_list), success_list, json.dumps(explanation_list)