Compare commits
21 Commits
master
...
3c94c3cfac
| Author | SHA1 | Date | |
|---|---|---|---|
| 3c94c3cfac | |||
| 2ab87d507f | |||
| 9b63fbbcfc | |||
| 26d69707c6 | |||
| a14e2bdd50 | |||
| 24ca1c2898 | |||
| 925fa550b1 | |||
| a6e6963c33 | |||
| f08c7b64c1 | |||
| c5dd178fd6 | |||
| b47a3b3146 | |||
| e54b5f1848 | |||
| 9e40e7fed8 | |||
| 88d9ac2105 | |||
| 479223ceb2 | |||
| e81f03c5aa | |||
| b99730f9a4 | |||
| 64db2efa38 | |||
| cf1e33474e | |||
| a341a67727 | |||
| dfae518f0c |
@@ -86,5 +86,5 @@ uv run start-agent
|
||||
|
||||
- **The agent MUST ONLY operate on repos within the `meeks` organization.**
|
||||
- `gitea/client.py:48` enforces this with a hardcoded filter: `if r.get("owner", {}).get("login") == "meeks"`
|
||||
- **Never change this filter** to include personal accounts (e.g., `meeks-ai`) or other organizations.
|
||||
- **Never change this filter** to include personal accounts (e.g., `unknown-ai`) or other organizations.
|
||||
- This filter is the single source of truth for repo scope — do not bypass it.
|
||||
|
||||
+7
-5
@@ -2,7 +2,6 @@ import asyncio
|
||||
import logging
|
||||
import lmstudio as lms
|
||||
from typing import Any, Callable
|
||||
from core.interfaces import Agent
|
||||
from .prompt import CAVEMAN_PROMPT
|
||||
|
||||
logger: logging.Logger = logging.getLogger("agent-base")
|
||||
@@ -54,7 +53,7 @@ class _ActResponseCapture:
|
||||
return '\n'.join(self.responses) if self.responses else "No response captured."
|
||||
|
||||
|
||||
class BaseAgent(Agent):
|
||||
class BaseAgent:
|
||||
"""Base AI agent implementing common LMStudio interaction patterns."""
|
||||
|
||||
def __init__(self, model_name: str) -> None:
|
||||
@@ -71,7 +70,8 @@ class BaseAgent(Agent):
|
||||
"""Run a single interaction with the agent."""
|
||||
if self.model is None:
|
||||
await self.initialize()
|
||||
assert self.model is not None
|
||||
if self.model is None:
|
||||
raise RuntimeError("Model initialization failed: model is None")
|
||||
|
||||
messages: list[dict[str, str]] = [
|
||||
{"role": "system", "content": self.system_prompt},
|
||||
@@ -91,7 +91,8 @@ class BaseAgent(Agent):
|
||||
"""Run the agent with tool calling capability."""
|
||||
if self.model is None:
|
||||
await self.initialize()
|
||||
assert self.model is not None
|
||||
if self.model is None:
|
||||
raise RuntimeError("Model initialization failed: model is None")
|
||||
|
||||
try:
|
||||
capture = _ActResponseCapture()
|
||||
@@ -113,4 +114,5 @@ class CavemanAgent(BaseAgent):
|
||||
|
||||
def __init__(self, model_name: str) -> None:
|
||||
super().__init__(model_name)
|
||||
self.system_prompt = CAVEMAN_PROMPT
|
||||
self.system_prompt: str = CAVEMAN_PROMPT
|
||||
|
||||
|
||||
@@ -10,4 +10,5 @@ class CodingAgent(BaseAgent):
|
||||
|
||||
def __init__(self, model_name: str) -> None:
|
||||
super().__init__(model_name)
|
||||
self.system_prompt = CODING_AGENT_SYSTEM_PROMPT
|
||||
self.system_prompt: str = CODING_AGENT_SYSTEM_PROMPT
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ You are an autonomous AI Software Engineer working on the `meeks` organization's
|
||||
|
||||
### 🎯 SCOPE & BOUNDARIES
|
||||
- **Organization**: You ONLY work on repositories under the `meeks` organization (e.g., `meeks/ai-electronbun-todo-app`).
|
||||
- **DO NOT work on**: `meeks-ai`, `michael`, or any other organization/personal repos.
|
||||
- **DO NOT work on**: any other organization/personal repos.
|
||||
- **DO NOT create new repositories**. The repo already exists. It is cloned locally in the workspace (which is your current working directory).
|
||||
- **DO NOT edit `.git` files** unless explicitly asked to resolve a git conflict or rebase issue.
|
||||
|
||||
@@ -119,7 +119,7 @@ Before writing any code or making any changes, you MUST:
|
||||
- Could multiple approaches work and you're unsure which to pick?
|
||||
|
||||
3. **If ANY uncertainty exists** — STOP and ask before implementing:
|
||||
- Post a comment on the issue or PR (using `add_comment_to_issue` or `add_comment` tool) with your specific question(s).
|
||||
- Post a comment on the issue or PR (using `add_comment_to_issue` tool) with your specific question(s).
|
||||
- List the approaches you are considering and ask which is preferred.
|
||||
- **Your comment MUST include the following marker on its own line at the very end:**
|
||||
```
|
||||
|
||||
@@ -17,7 +17,8 @@ class CoordinatorAgent(BaseAgent):
|
||||
|
||||
def __init__(self, model_name: str) -> None:
|
||||
super().__init__(model_name)
|
||||
self.system_prompt = COORDINATOR_SYSTEM_PROMPT
|
||||
self.system_prompt: str = COORDINATOR_SYSTEM_PROMPT
|
||||
|
||||
|
||||
async def decide_action(
|
||||
self,
|
||||
|
||||
+485
-229
File diff suppressed because it is too large
Load Diff
@@ -1,94 +0,0 @@
|
||||
import logging
|
||||
from gitea.client import GiteaClient
|
||||
from core.interfaces import (
|
||||
IssuesClient,
|
||||
PullRequestsClient,
|
||||
FilesClient,
|
||||
RefsClient,
|
||||
ReposClient,
|
||||
)
|
||||
from core.coding_agent import CodingAgent
|
||||
from core.agent import CavemanAgent
|
||||
from core.coordinator_agent import CoordinatorAgent
|
||||
from core.planning_agent import PlanningAgent
|
||||
from core.notification_agent import NotificationReaderAgent
|
||||
from gitea.workspace import WorkspaceManager
|
||||
|
||||
logger: logging.Logger = logging.getLogger("core-factory")
|
||||
|
||||
|
||||
class GiteaClientFactory:
|
||||
"""Factory for creating Gitea client components with dependency injection support."""
|
||||
|
||||
@staticmethod
|
||||
def create_full_client() -> GiteaClient:
|
||||
return GiteaClient()
|
||||
|
||||
@staticmethod
|
||||
def create_issues_client(client: GiteaClient | None = None) -> IssuesClient:
|
||||
if client is None:
|
||||
client = GiteaClient()
|
||||
return client
|
||||
|
||||
@staticmethod
|
||||
def create_prs_client(client: GiteaClient | None = None) -> PullRequestsClient:
|
||||
if client is None:
|
||||
client = GiteaClient()
|
||||
return client
|
||||
|
||||
@staticmethod
|
||||
def create_files_client(client: GiteaClient | None = None) -> FilesClient:
|
||||
if client is None:
|
||||
client = GiteaClient()
|
||||
return client
|
||||
|
||||
@staticmethod
|
||||
def create_refs_client(client: GiteaClient | None = None) -> RefsClient:
|
||||
if client is None:
|
||||
client = GiteaClient()
|
||||
return client
|
||||
|
||||
@staticmethod
|
||||
def create_repos_client(client: GiteaClient | None = None) -> ReposClient:
|
||||
if client is None:
|
||||
client = GiteaClient()
|
||||
return client
|
||||
|
||||
|
||||
class AgentFactory:
|
||||
"""Factory for creating AI agent instances."""
|
||||
|
||||
@staticmethod
|
||||
def create_coding_agent(model_name: str) -> CodingAgent:
|
||||
logger.info(f"Factory creating CodingAgent with model: {model_name}")
|
||||
return CodingAgent(model_name)
|
||||
|
||||
@staticmethod
|
||||
def create_caveman_agent(model_name: str) -> CavemanAgent:
|
||||
logger.info(f"Factory creating CavemanAgent with model: {model_name}")
|
||||
return CavemanAgent(model_name)
|
||||
|
||||
@staticmethod
|
||||
def create_coordinator_agent(model_name: str) -> CoordinatorAgent:
|
||||
logger.info(f"Factory creating CoordinatorAgent with model: {model_name}")
|
||||
return CoordinatorAgent(model_name)
|
||||
|
||||
@staticmethod
|
||||
def create_planning_agent(model_name: str) -> PlanningAgent:
|
||||
logger.info(f"Factory creating PlanningAgent with model: {model_name}")
|
||||
return PlanningAgent(model_name)
|
||||
|
||||
@staticmethod
|
||||
def create_notification_reader_agent(model_name: str) -> NotificationReaderAgent:
|
||||
logger.info(f"Factory creating NotificationReaderAgent with model: {model_name}")
|
||||
return NotificationReaderAgent(model_name)
|
||||
|
||||
|
||||
|
||||
class WorkspaceFactory:
|
||||
"""Factory for creating workspace manager instances."""
|
||||
|
||||
@staticmethod
|
||||
def create_workspace() -> WorkspaceManager:
|
||||
logger.info("Factory creating WorkspaceManager")
|
||||
return WorkspaceManager()
|
||||
@@ -1,182 +0,0 @@
|
||||
"""Interfaces for Gitea operations."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any
|
||||
from gitea.models import (
|
||||
IssueModel,
|
||||
PullRequestModel,
|
||||
CommentModel,
|
||||
LabelModel,
|
||||
UserModel,
|
||||
RepositoryModel,
|
||||
PullRequestFileModel,
|
||||
)
|
||||
|
||||
|
||||
class IssuesClient(ABC):
|
||||
"""Interface for Gitea issue operations."""
|
||||
|
||||
@abstractmethod
|
||||
def list_repo_issues(self, owner: str, repo: str, state: str = "open") -> list[IssueModel]: ...
|
||||
|
||||
@abstractmethod
|
||||
def get_issue(self, owner: str, repo: str, issue_number: int) -> IssueModel: ...
|
||||
|
||||
@abstractmethod
|
||||
def close_issue(self, owner: str, repo: str, issue_number: int) -> IssueModel: ...
|
||||
|
||||
@abstractmethod
|
||||
def get_issue_comments(self, owner: str, repo: str, issue_number: int) -> list[CommentModel]: ...
|
||||
|
||||
@abstractmethod
|
||||
def list_assigned_issues(self, owner: str, repo: str) -> list[IssueModel]: ...
|
||||
|
||||
@abstractmethod
|
||||
def create_issue(
|
||||
self,
|
||||
owner: str,
|
||||
repo: str,
|
||||
title: str,
|
||||
body: str,
|
||||
labels: list[str] | None = None,
|
||||
assignees: list[str] | None = None,
|
||||
) -> IssueModel: ...
|
||||
|
||||
@abstractmethod
|
||||
def add_comment(self, owner: str, repo: str, issue_number: int, body: str) -> CommentModel: ...
|
||||
|
||||
@abstractmethod
|
||||
def add_label(self, owner: str, repo: str, issue_number: int, label: str) -> LabelModel: ...
|
||||
|
||||
|
||||
class PullRequestsClient(ABC):
|
||||
"""Interface for Gitea pull request operations."""
|
||||
|
||||
@abstractmethod
|
||||
def list_repo_pull_requests(self, owner: str, repo: str, state: str = "open") -> list[PullRequestModel]: ...
|
||||
|
||||
@abstractmethod
|
||||
def get_pull_request(self, owner: str, repo: str, pull_number: int) -> PullRequestModel: ...
|
||||
|
||||
@abstractmethod
|
||||
def close_pull_request(self, owner: str, repo: str, pull_number: int) -> PullRequestModel: ...
|
||||
|
||||
@abstractmethod
|
||||
def get_pull_request_comments(self, owner: str, repo: str, pull_number: int) -> list[CommentModel]: ...
|
||||
|
||||
@abstractmethod
|
||||
def get_pr_reviews(self, owner: str, repo: str, pr_number: int) -> list[dict[str, Any]]: ...
|
||||
|
||||
@abstractmethod
|
||||
def get_pull_request_diff(self, owner: str, repo: str, pull_number: int) -> str: ...
|
||||
|
||||
@abstractmethod
|
||||
def get_pull_request_patch(self, owner: str, repo: str, pull_number: int) -> str: ...
|
||||
|
||||
@abstractmethod
|
||||
def get_pull_request_files(self, owner: str, repo: str, pull_number: int) -> list[PullRequestFileModel]: ...
|
||||
|
||||
@abstractmethod
|
||||
def list_assigned_pull_requests(self, owner: str, repo: str) -> list[PullRequestModel]: ...
|
||||
|
||||
@abstractmethod
|
||||
def create_pull_request(
|
||||
self, owner: str, repo: str, head: str, base: str, title: str, description: str = ""
|
||||
) -> PullRequestModel: ...
|
||||
|
||||
@abstractmethod
|
||||
def update_pull_request(
|
||||
self,
|
||||
owner: str,
|
||||
repo: str,
|
||||
pull_number: int,
|
||||
title: str | None = None,
|
||||
body: str | None = None,
|
||||
state: str | None = None,
|
||||
) -> PullRequestModel: ...
|
||||
|
||||
@abstractmethod
|
||||
def approve_pr(self, owner: str, repo: str, pr_number: int, comment: str) -> dict[str, Any]: ...
|
||||
|
||||
@abstractmethod
|
||||
def request_changes_pr(self, owner: str, repo: str, pr_number: int, comment: str) -> dict[str, Any]: ...
|
||||
|
||||
@abstractmethod
|
||||
def dismiss_review_pr(
|
||||
self, owner: str, repo: str, pr_number: int, review_id: int, message: str
|
||||
) -> dict[str, Any]: ...
|
||||
|
||||
@abstractmethod
|
||||
def assign_issue(self, owner: str, repo: str, issue_number: int, username: str) -> IssueModel: ...
|
||||
|
||||
|
||||
class FilesClient(ABC):
|
||||
"""Interface for Gitea file/content operations."""
|
||||
|
||||
@abstractmethod
|
||||
def get_file_content(self, owner: str, repo: str, path: str, ref: str = "master") -> str | list[str]: ...
|
||||
|
||||
@abstractmethod
|
||||
def update_file(
|
||||
self, owner: str, repo: str, path: str, message: str, content: str, branch: str
|
||||
) -> dict[str, Any]: ...
|
||||
|
||||
|
||||
class RefsClient(ABC):
|
||||
"""Interface for Gitea git ref operations."""
|
||||
|
||||
@abstractmethod
|
||||
def update_ref(self, owner: str, repo: str, ref: str, sha: str) -> dict[str, Any]: ...
|
||||
|
||||
@abstractmethod
|
||||
def create_ref(self, owner: str, repo: str, ref: str, sha: str) -> dict[str, Any]: ...
|
||||
|
||||
|
||||
class ReposClient(ABC):
|
||||
"""Interface for Gitea repository operations."""
|
||||
|
||||
@abstractmethod
|
||||
def list_all_user_repos(self) -> list[RepositoryModel]: ...
|
||||
|
||||
|
||||
class Agent(ABC):
|
||||
"""Interface for AI agent operations."""
|
||||
|
||||
@abstractmethod
|
||||
async def initialize(self) -> None: ...
|
||||
|
||||
@abstractmethod
|
||||
async def run(self, user_input: str) -> str: ...
|
||||
|
||||
@abstractmethod
|
||||
async def run_with_tools(self, user_input: str, tools: list[Any]) -> str: ...
|
||||
|
||||
|
||||
class Workspace(ABC):
|
||||
"""Interface for workspace management."""
|
||||
|
||||
@abstractmethod
|
||||
def get_repo_path(self, repo_full_name: str) -> Any: ...
|
||||
|
||||
@abstractmethod
|
||||
def sanitize_repo(self, repo_path: Any) -> None: ...
|
||||
|
||||
@abstractmethod
|
||||
def clone_repo(self, repo_full_name: str, clone_url: str) -> Any: ...
|
||||
|
||||
|
||||
class MissionBuilder(ABC):
|
||||
"""Interface for mission string construction."""
|
||||
|
||||
@abstractmethod
|
||||
def build_issue_mission(self, issue_info: dict[str, Any], branch_name: str) -> str: ...
|
||||
|
||||
@abstractmethod
|
||||
def build_pr_mission(self, pr_info: dict[str, Any]) -> str: ...
|
||||
|
||||
|
||||
class BranchStrategy(ABC):
|
||||
"""Interface for branch creation strategy."""
|
||||
|
||||
@abstractmethod
|
||||
async def create_or_reuse_branch(self, repo_path: Any, branch_name: str, base_branch: str | None = None) -> str: ...
|
||||
@@ -17,7 +17,8 @@ class NotificationReaderAgent(BaseAgent):
|
||||
|
||||
def __init__(self, model_name: str) -> None:
|
||||
super().__init__(model_name)
|
||||
self.system_prompt = NOTIFICATION_READER_SYSTEM_PROMPT
|
||||
self.system_prompt: str = NOTIFICATION_READER_SYSTEM_PROMPT
|
||||
|
||||
|
||||
async def decide_notification(
|
||||
self,
|
||||
|
||||
+69
-30
@@ -11,12 +11,17 @@ from core.queue import WorkQueue, WorkItem
|
||||
from core.dispatcher import AgentDispatcher
|
||||
from gitea.client import GiteaClient
|
||||
from gitea.models import IssueModel, PullRequestModel, RepositoryModel
|
||||
from gitea.tools.gitea_tools import GiteaTools
|
||||
from gitea.tools.issue_tools import IssueTools
|
||||
from gitea.tools.pr_tools import PRTools
|
||||
from gitea.tools.file_tools import FileTools
|
||||
from gitea.tools.git_tools import GitTools
|
||||
from gitea.config import AGENT_MODEL_ID, AGENT_MAX_RETRIES
|
||||
from gitea.workspace import WorkspaceManager
|
||||
from core.factory import AgentFactory
|
||||
from core.notification_agent import (
|
||||
NotificationReaderAgent,
|
||||
NotificationNoToolCalledError,
|
||||
)
|
||||
from core.notification_tools import NotificationTools
|
||||
from core.notification_agent import NotificationNoToolCalledError
|
||||
|
||||
logger: logging.Logger = logging.getLogger("agent-orchestrator")
|
||||
|
||||
@@ -27,19 +32,32 @@ class AgentOrchestrator:
|
||||
def __init__(
|
||||
self,
|
||||
client: GiteaClient,
|
||||
tools: GiteaTools,
|
||||
issue_tools: IssueTools,
|
||||
pr_tools: PRTools,
|
||||
file_tools: FileTools,
|
||||
git_tools: GitTools,
|
||||
model_name: str = AGENT_MODEL_ID,
|
||||
max_retries: int = AGENT_MAX_RETRIES,
|
||||
) -> None:
|
||||
self._client = client
|
||||
self._tools = tools
|
||||
self._issue_tools = issue_tools
|
||||
self._pr_tools = pr_tools
|
||||
self._file_tools = file_tools
|
||||
self._git_tools = git_tools
|
||||
self._model_name = model_name
|
||||
self._work_queue = WorkQueue()
|
||||
self._dispatcher = AgentDispatcher(client, tools, model_name, max_retries)
|
||||
self._notification_reader = AgentFactory.create_notification_reader_agent(model_name)
|
||||
self._dispatcher = AgentDispatcher(
|
||||
client,
|
||||
issue_tools,
|
||||
pr_tools,
|
||||
file_tools,
|
||||
git_tools,
|
||||
model_name,
|
||||
max_retries,
|
||||
)
|
||||
self._notification_reader = NotificationReaderAgent(model_name)
|
||||
self._max_retries = max_retries
|
||||
|
||||
|
||||
def _get_state_file_path(self) -> Path:
|
||||
"""Get the path to the persistent state file."""
|
||||
return Path(__file__).parent.parent / "agent_state.json"
|
||||
@@ -68,7 +86,9 @@ class AgentOrchestrator:
|
||||
async def poll_and_dispatch(self) -> None:
|
||||
"""Poll Gitea unread notifications, enqueue them, and dispatch to agent."""
|
||||
last_checked = self._read_last_checked()
|
||||
logger.info(f"Polling unread notifications since: {last_checked or 'beginning'}")
|
||||
logger.info(
|
||||
f"Polling unread notifications since: {last_checked or 'beginning'}"
|
||||
)
|
||||
|
||||
notifications = self._client.list_unread_notifications(since=last_checked)
|
||||
|
||||
@@ -81,10 +101,10 @@ class AgentOrchestrator:
|
||||
# Filter and enqueue tasks from notifications
|
||||
latest_timestamp = last_checked
|
||||
inspection_tools = [
|
||||
self._tools.get_issue,
|
||||
self._tools.get_pull_request,
|
||||
self._tools.get_issue_comments,
|
||||
self._tools.get_pull_request_comments,
|
||||
self._issue_tools.get_issue,
|
||||
self._pr_tools.get_pull_request,
|
||||
self._issue_tools.get_issue_comments,
|
||||
self._pr_tools.get_pull_request_comments,
|
||||
]
|
||||
|
||||
for n in notifications:
|
||||
@@ -107,7 +127,9 @@ class AgentOrchestrator:
|
||||
try:
|
||||
task_number = int(subj_url.rstrip("/").split("/")[-1])
|
||||
except (ValueError, IndexError):
|
||||
logger.warning(f"Could not parse task number from subject URL: {subj_url}")
|
||||
logger.warning(
|
||||
f"Could not parse task number from subject URL: {subj_url}"
|
||||
)
|
||||
continue
|
||||
|
||||
# Run NotificationReaderAgent to pre-screen the notification
|
||||
@@ -126,21 +148,27 @@ class AgentOrchestrator:
|
||||
attempt += 1
|
||||
try:
|
||||
await self._notification_reader.decide_notification(
|
||||
mission,
|
||||
inspection_tools,
|
||||
notification_tools
|
||||
mission, inspection_tools, notification_tools
|
||||
)
|
||||
success = True
|
||||
break
|
||||
except NotificationNoToolCalledError as e:
|
||||
logger.error(f"Notification reader error on notification {notification_id} (attempt {attempt}/{attempt_limit}): {e}")
|
||||
logger.error(
|
||||
f"Notification reader error on notification {notification_id} (attempt {attempt}/{attempt_limit}): {e}"
|
||||
)
|
||||
|
||||
if not success or notification_tools.action == "SKIP":
|
||||
reason = notification_tools.arguments.get("reason", "Failed to call routing tool / default skip")
|
||||
logger.info(f"Skipping notification {notification_id} for {repo_full_name}#{task_number}. Reason: {reason}")
|
||||
reason = notification_tools.arguments.get(
|
||||
"reason", "Failed to call routing tool / default skip"
|
||||
)
|
||||
logger.info(
|
||||
f"Skipping notification {notification_id} for {repo_full_name}#{task_number}. Reason: {reason}"
|
||||
)
|
||||
if notification_id is not None:
|
||||
self._client.mark_notification_as_read(notification_id)
|
||||
logger.info(f"Marked skipped Gitea notification thread {notification_id} as read.")
|
||||
logger.info(
|
||||
f"Marked skipped Gitea notification thread {notification_id} as read."
|
||||
)
|
||||
continue
|
||||
|
||||
# Route based on decided action
|
||||
@@ -148,7 +176,9 @@ class AgentOrchestrator:
|
||||
try:
|
||||
issue = self._client.get_issue(owner, repo_name, task_number)
|
||||
if issue.repository is None:
|
||||
issue = issue.model_copy(update={"repository": RepositoryModel(**repo_info)})
|
||||
issue = issue.model_copy(
|
||||
update={"repository": RepositoryModel(**repo_info)}
|
||||
)
|
||||
|
||||
item = WorkItem(
|
||||
repo_full_name=repo_full_name,
|
||||
@@ -156,16 +186,20 @@ class AgentOrchestrator:
|
||||
task_number=task_number,
|
||||
task_info=issue,
|
||||
notification_id=notification_id,
|
||||
priority=0
|
||||
priority=0,
|
||||
)
|
||||
self._work_queue.enqueue(item)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to fetch issue #{task_number} for notification: {e}")
|
||||
logger.error(
|
||||
f"Failed to fetch issue #{task_number} for notification: {e}"
|
||||
)
|
||||
elif notification_tools.action == "PROCESS_PR":
|
||||
try:
|
||||
pr = self._client.get_pull_request(owner, repo_name, task_number)
|
||||
if pr.repository is None:
|
||||
pr = pr.model_copy(update={"repository": RepositoryModel(**repo_info)})
|
||||
pr = pr.model_copy(
|
||||
update={"repository": RepositoryModel(**repo_info)}
|
||||
)
|
||||
|
||||
item = WorkItem(
|
||||
repo_full_name=repo_full_name,
|
||||
@@ -173,12 +207,13 @@ class AgentOrchestrator:
|
||||
task_number=task_number,
|
||||
task_info=pr,
|
||||
notification_id=notification_id,
|
||||
priority=0
|
||||
priority=0,
|
||||
)
|
||||
self._work_queue.enqueue(item)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to fetch PR #{task_number} for notification: {e}")
|
||||
|
||||
logger.error(
|
||||
f"Failed to fetch PR #{task_number} for notification: {e}"
|
||||
)
|
||||
|
||||
# Process enqueued work
|
||||
if not self._work_queue.is_empty:
|
||||
@@ -213,7 +248,11 @@ class AgentOrchestrator:
|
||||
|
||||
for i, result in enumerate(results):
|
||||
item = work_items[i]
|
||||
logger.info(f"Completed {item.task_type} #{item.task_number}: {result[:200]}")
|
||||
logger.info(
|
||||
f"Completed {item.task_type} #{item.task_number}: {result[:200]}"
|
||||
)
|
||||
if item.notification_id is not None:
|
||||
self._client.mark_notification_as_read(item.notification_id)
|
||||
logger.info(f"Marked Gitea notification thread {item.notification_id} as read.")
|
||||
logger.info(
|
||||
f"Marked Gitea notification thread {item.notification_id} as read."
|
||||
)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import logging
|
||||
from core.agent import BaseAgent
|
||||
from .coding_prompt import CODING_AGENT_SYSTEM_PROMPT
|
||||
from core.prompts import PLANNING_AGENT_SYSTEM_PROMPT
|
||||
|
||||
logger: logging.Logger = logging.getLogger("agent-planning")
|
||||
|
||||
@@ -10,4 +10,5 @@ class PlanningAgent(BaseAgent):
|
||||
|
||||
def __init__(self, model_name: str) -> None:
|
||||
super().__init__(model_name)
|
||||
self.system_prompt = CODING_AGENT_SYSTEM_PROMPT
|
||||
self.system_prompt: str = PLANNING_AGENT_SYSTEM_PROMPT
|
||||
|
||||
|
||||
@@ -49,3 +49,16 @@ CRITICAL INSTRUCTIONS:
|
||||
- You can use the provided inspection tools (like get_issue, get_pull_request, get_issue_comments, get_pull_request_comments) to gather more details if the basic notification metadata is insufficient to make a decision.
|
||||
"""
|
||||
|
||||
|
||||
PLANNING_AGENT_SYSTEM_PROMPT: str = """
|
||||
You are an AI Planning Agent. Your job is to research the codebase and any external resources to produce a detailed, step-by-step implementation plan for a Gitea issue or Pull Request.
|
||||
|
||||
CRITICAL RULES:
|
||||
1. You are ONLY generating an implementation plan. DO NOT write files, DO NOT edit files, DO NOT commit, DO NOT push, and DO NOT create branches or PRs.
|
||||
2. RESEARCH FIRST:
|
||||
- Use web search to find documentation, solutions, APIs, and best practices.
|
||||
- Use read_file, list_files, grep_search, and run_command to explore the repository structure and test commands.
|
||||
3. Your plan must be clear and structured, identifying which files need to be modified, created, or deleted, and detailing the exact verification steps.
|
||||
"""
|
||||
|
||||
|
||||
|
||||
+31
-20
@@ -1,4 +1,5 @@
|
||||
import logging
|
||||
import threading
|
||||
from pydantic import BaseModel
|
||||
from typing import Any, Optional
|
||||
from gitea.models import IssueModel, PullRequestModel
|
||||
@@ -19,43 +20,53 @@ class WorkQueue:
|
||||
"""Thread-safe work queue grouped by repo."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock: threading.Lock = threading.Lock()
|
||||
self._queue: list[WorkItem] = []
|
||||
self._enqueued_repos: set[str] = set()
|
||||
|
||||
def enqueue(self, item: WorkItem) -> None:
|
||||
self._queue.append(item)
|
||||
self._enqueued_repos.add(item.repo_full_name)
|
||||
logger.info(f"Enqueued work item: {item.task_type} #{item.task_number} for {item.repo_full_name}")
|
||||
with self._lock:
|
||||
self._queue.append(item)
|
||||
self._enqueued_repos.add(item.repo_full_name)
|
||||
logger.info(f"Enqueued work item: {item.task_type} #{item.task_number} for {item.repo_full_name}")
|
||||
|
||||
def enqueue_batch(self, items: list[WorkItem]) -> None:
|
||||
for item in items:
|
||||
self.enqueue(item)
|
||||
with self._lock:
|
||||
for item in items:
|
||||
self._queue.append(item)
|
||||
self._enqueued_repos.add(item.repo_full_name)
|
||||
logger.info(f"Enqueued work item: {item.task_type} #{item.task_number} for {item.repo_full_name}")
|
||||
|
||||
def get_repo_work(self, repo: str) -> list[WorkItem]:
|
||||
"""Get all work items for a specific repo."""
|
||||
items: list[WorkItem] = [
|
||||
item for item in self._queue if item.repo_full_name == repo
|
||||
]
|
||||
logger.info(f"Retrieved {len(items)} work items for repository: {repo}")
|
||||
return items
|
||||
with self._lock:
|
||||
items: list[WorkItem] = [
|
||||
item for item in self._queue if item.repo_full_name == repo
|
||||
]
|
||||
logger.info(f"Retrieved {len(items)} work items for repository: {repo}")
|
||||
return items
|
||||
|
||||
def remove_repo_work(self, repo: str) -> None:
|
||||
"""Remove all work items for a specific repo."""
|
||||
self._queue = [
|
||||
item for item in self._queue if item.repo_full_name != repo
|
||||
]
|
||||
self._enqueued_repos.discard(repo)
|
||||
logger.info(f"Removed all work items for repository: {repo}")
|
||||
with self._lock:
|
||||
self._queue = [
|
||||
item for item in self._queue if item.repo_full_name != repo
|
||||
]
|
||||
self._enqueued_repos.discard(repo)
|
||||
logger.info(f"Removed all work items for repository: {repo}")
|
||||
|
||||
def get_next_repo(self) -> str | None:
|
||||
"""Get the next repo with work, or None if empty."""
|
||||
if not self._enqueued_repos:
|
||||
return None
|
||||
return next(iter(self._enqueued_repos))
|
||||
with self._lock:
|
||||
if not self._enqueued_repos:
|
||||
return None
|
||||
return next(iter(self._enqueued_repos))
|
||||
|
||||
@property
|
||||
def is_empty(self) -> bool:
|
||||
return len(self._queue) == 0
|
||||
with self._lock:
|
||||
return len(self._queue) == 0
|
||||
|
||||
def __len__(self) -> int:
|
||||
return len(self._queue)
|
||||
with self._lock:
|
||||
return len(self._queue)
|
||||
|
||||
+330
-279
@@ -1,8 +1,12 @@
|
||||
import httpx
|
||||
import json
|
||||
import base64
|
||||
import logging
|
||||
from typing import Any, Optional
|
||||
from .config import GITEA_URL, GITEA_TOKEN
|
||||
|
||||
logger: logging.Logger = logging.getLogger("gitea.client")
|
||||
|
||||
from .config import GITEA_URL, GITEA_TOKEN, GITEA_ORG_FILTER
|
||||
from .models import (
|
||||
UserModel,
|
||||
LabelModel,
|
||||
@@ -12,16 +16,9 @@ from .models import (
|
||||
CommentModel,
|
||||
PullRequestFileModel,
|
||||
)
|
||||
from core.interfaces import (
|
||||
IssuesClient,
|
||||
PullRequestsClient,
|
||||
FilesClient,
|
||||
RefsClient,
|
||||
ReposClient,
|
||||
)
|
||||
|
||||
|
||||
class GiteaClient(IssuesClient, PullRequestsClient, FilesClient, RefsClient, ReposClient):
|
||||
class GiteaClient:
|
||||
"""HTTP client for Gitea API v1."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
@@ -30,117 +27,141 @@ class GiteaClient(IssuesClient, PullRequestsClient, FilesClient, RefsClient, Rep
|
||||
"Authorization": f"token {GITEA_TOKEN}",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
self.client: httpx.Client = httpx.Client(headers=self.headers)
|
||||
|
||||
def get_authenticated_user(self) -> UserModel | None:
|
||||
def close(self) -> None:
|
||||
"""Close the underlying HTTP client."""
|
||||
self.client.close()
|
||||
|
||||
def __enter__(self) -> "GiteaClient":
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
|
||||
self.close()
|
||||
|
||||
def __del__(self) -> None:
|
||||
try:
|
||||
with httpx.Client() as client:
|
||||
response = client.get(f"{self.base_url}/api/v1/user", headers=self.headers)
|
||||
response.raise_for_status()
|
||||
return UserModel(**response.json())
|
||||
self.client.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def get_authenticated_user(self) -> UserModel:
|
||||
try:
|
||||
response = self.client.get(f"{self.base_url}/api/v1/user")
|
||||
response.raise_for_status()
|
||||
return UserModel(**response.json())
|
||||
except Exception as e:
|
||||
print(f"Error getting authenticated user: {e}")
|
||||
return None
|
||||
logger.error(f"Error getting authenticated user: {e}", exc_info=True)
|
||||
raise RuntimeError(f"Could not get authenticated user: {e}") from e
|
||||
|
||||
def list_all_user_repos(self) -> list[RepositoryModel]:
|
||||
try:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/user/repos"
|
||||
response = client.get(url, headers=self.headers)
|
||||
response.raise_for_status()
|
||||
repos: list[dict[str, Any]] = response.json()
|
||||
# Filter to ONLY meeks organization repos, include mirrors
|
||||
seen: set[str] = set()
|
||||
result: list[RepositoryModel] = []
|
||||
for r in repos:
|
||||
full_name = r.get("full_name", "")
|
||||
if full_name and full_name not in seen and (r.get("owner") or {}).get("login") == "meeks":
|
||||
seen.add(full_name)
|
||||
result.append(RepositoryModel(**r))
|
||||
return result
|
||||
url = f"{self.base_url}/api/v1/user/repos"
|
||||
response = self.client.get(url)
|
||||
response.raise_for_status()
|
||||
repos: list[dict[str, Any]] = response.json()
|
||||
# Filter to ONLY configured organization repos, include mirrors
|
||||
seen: set[str] = set()
|
||||
result: list[RepositoryModel] = []
|
||||
for r in repos:
|
||||
full_name = r.get("full_name", "")
|
||||
if (
|
||||
full_name
|
||||
and full_name not in seen
|
||||
and (r.get("owner") or {}).get("login") == GITEA_ORG_FILTER
|
||||
):
|
||||
seen.add(full_name)
|
||||
result.append(RepositoryModel(**r))
|
||||
return result
|
||||
except Exception as e:
|
||||
print(f"Error listing user repos: {e}")
|
||||
logger.error(f"Error listing user repos: {e}", exc_info=True)
|
||||
return []
|
||||
|
||||
def list_repo_issues(self, owner: str, repo: str, state: str = "open") -> list[IssueModel]:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/issues?type=issues&state={state}"
|
||||
response = client.get(url, headers=self.headers)
|
||||
response.raise_for_status()
|
||||
return [IssueModel(**item) for item in response.json()]
|
||||
def list_repo_issues(
|
||||
self, owner: str, repo: str, state: str = "open"
|
||||
) -> list[IssueModel]:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/issues?type=issues&state={state}"
|
||||
response = self.client.get(url)
|
||||
response.raise_for_status()
|
||||
return [IssueModel(**item) for item in response.json()]
|
||||
|
||||
def list_repo_pull_requests(self, owner: str, repo: str, state: str = "open") -> list[PullRequestModel]:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls?state={state}"
|
||||
response = client.get(url, headers=self.headers)
|
||||
if response.status_code == 404:
|
||||
return []
|
||||
response.raise_for_status()
|
||||
return [PullRequestModel(**item) for item in response.json()]
|
||||
def list_repo_pull_requests(
|
||||
self, owner: str, repo: str, state: str = "open"
|
||||
) -> list[PullRequestModel]:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls?state={state}"
|
||||
response = self.client.get(url)
|
||||
if response.status_code == 404:
|
||||
return []
|
||||
response.raise_for_status()
|
||||
return [PullRequestModel(**item) for item in response.json()]
|
||||
|
||||
def get_pull_request(self, owner: str, repo: str, pull_number: int) -> PullRequestModel:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls/{pull_number}"
|
||||
response = client.get(url, headers=self.headers)
|
||||
response.raise_for_status()
|
||||
return PullRequestModel(**response.json())
|
||||
def get_pull_request(
|
||||
self, owner: str, repo: str, pull_number: int
|
||||
) -> PullRequestModel:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls/{pull_number}"
|
||||
response = self.client.get(url)
|
||||
response.raise_for_status()
|
||||
return PullRequestModel(**response.json())
|
||||
|
||||
def get_issue(self, owner: str, repo: str, issue_number: int) -> IssueModel:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/issues/{issue_number}"
|
||||
response = client.get(url, headers=self.headers)
|
||||
response.raise_for_status()
|
||||
return IssueModel(**response.json())
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/issues/{issue_number}"
|
||||
response = self.client.get(url)
|
||||
response.raise_for_status()
|
||||
return IssueModel(**response.json())
|
||||
|
||||
def close_issue(self, owner: str, repo: str, issue_number: int) -> IssueModel:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/issues/{issue_number}"
|
||||
data: dict[str, str] = {"state": "closed"}
|
||||
response = client.patch(url, headers=self.headers, json=data)
|
||||
response.raise_for_status()
|
||||
return IssueModel(**response.json())
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/issues/{issue_number}"
|
||||
data: dict[str, str] = {"state": "closed"}
|
||||
response = self.client.patch(url, json=data)
|
||||
response.raise_for_status()
|
||||
return IssueModel(**response.json())
|
||||
|
||||
def close_pull_request(self, owner: str, repo: str, pull_number: int) -> PullRequestModel:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls/{pull_number}"
|
||||
data: dict[str, str] = {"state": "closed"}
|
||||
response = client.patch(url, headers=self.headers, json=data)
|
||||
response.raise_for_status()
|
||||
return PullRequestModel(**response.json())
|
||||
def close_pull_request(
|
||||
self, owner: str, repo: str, pull_number: int
|
||||
) -> PullRequestModel:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls/{pull_number}"
|
||||
data: dict[str, str] = {"state": "closed"}
|
||||
response = self.client.patch(url, json=data)
|
||||
response.raise_for_status()
|
||||
return PullRequestModel(**response.json())
|
||||
|
||||
def get_issue_comments(self, owner: str, repo: str, issue_number: int) -> list[CommentModel]:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/issues/{issue_number}/comments"
|
||||
response = client.get(url, headers=self.headers)
|
||||
response.raise_for_status()
|
||||
return [CommentModel(**item) for item in response.json()]
|
||||
def get_issue_comments(
|
||||
self, owner: str, repo: str, issue_number: int
|
||||
) -> list[CommentModel]:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/issues/{issue_number}/comments"
|
||||
response = self.client.get(url)
|
||||
response.raise_for_status()
|
||||
return [CommentModel(**item) for item in response.json()]
|
||||
|
||||
def get_pull_request_comments(self, owner: str, repo: str, pull_number: int) -> list[CommentModel]:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/issues/{pull_number}/comments"
|
||||
response = client.get(url, headers=self.headers)
|
||||
response.raise_for_status()
|
||||
return [CommentModel(**item) for item in response.json()]
|
||||
def get_pull_request_comments(
|
||||
self, owner: str, repo: str, pull_number: int
|
||||
) -> list[CommentModel]:
|
||||
url = (
|
||||
f"{self.base_url}/api/v1/repos/{owner}/{repo}/issues/{pull_number}/comments"
|
||||
)
|
||||
response = self.client.get(url)
|
||||
response.raise_for_status()
|
||||
return [CommentModel(**item) for item in response.json()]
|
||||
|
||||
def get_pull_request_diff(self, owner: str, repo: str, pull_number: int) -> str:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls/{pull_number}/diff"
|
||||
response = client.get(url, headers=self.headers)
|
||||
response.raise_for_status()
|
||||
return response.text
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls/{pull_number}/diff"
|
||||
response = self.client.get(url)
|
||||
response.raise_for_status()
|
||||
return response.text
|
||||
|
||||
def get_pull_request_patch(self, owner: str, repo: str, pull_number: int) -> str:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls/{pull_number}/patch"
|
||||
response = client.get(url, headers=self.headers)
|
||||
response.raise_for_status()
|
||||
return response.text
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls/{pull_number}/patch"
|
||||
response = self.client.get(url)
|
||||
response.raise_for_status()
|
||||
return response.text
|
||||
|
||||
def get_pull_request_files(self, owner: str, repo: str, pull_number: int) -> list[PullRequestFileModel]:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls/{pull_number}/files"
|
||||
response = client.get(url, headers=self.headers)
|
||||
response.raise_for_status()
|
||||
return [PullRequestFileModel(**item) for item in response.json()]
|
||||
def get_pull_request_files(
|
||||
self, owner: str, repo: str, pull_number: int
|
||||
) -> list[PullRequestFileModel]:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls/{pull_number}/files"
|
||||
response = self.client.get(url)
|
||||
response.raise_for_status()
|
||||
return [PullRequestFileModel(**item) for item in response.json()]
|
||||
|
||||
def list_assigned_issues(self, owner: str = "", repo: str = "") -> list[IssueModel]:
|
||||
try:
|
||||
@@ -149,20 +170,18 @@ class GiteaClient(IssuesClient, PullRequestsClient, FilesClient, RefsClient, Rep
|
||||
return []
|
||||
username: str = user.login
|
||||
if owner and repo:
|
||||
response = httpx.get(
|
||||
response = self.client.get(
|
||||
f"{self.base_url}/api/v1/repos/{owner}/{repo}/issues?assignee={username}&state=open&type=issues",
|
||||
headers=self.headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return [IssueModel(**item) for item in response.json()]
|
||||
all_issues: list[IssueModel] = []
|
||||
repos = self.list_all_user_repos()
|
||||
for r in repos:
|
||||
repo_owner = r.owner if hasattr(r, 'owner') else (r.get("owner") or {}).get("login", "")
|
||||
repo_name = r.name if hasattr(r, 'name') else r.get("name", "")
|
||||
resp = httpx.get(
|
||||
repo_owner = r.owner
|
||||
repo_name = r.name
|
||||
resp = self.client.get(
|
||||
f"{self.base_url}/api/v1/repos/{repo_owner}/{repo_name}/issues?assignee={username}&state=open&type=issues",
|
||||
headers=self.headers,
|
||||
)
|
||||
if resp.status_code == 200:
|
||||
for item in resp.json():
|
||||
@@ -173,10 +192,12 @@ class GiteaClient(IssuesClient, PullRequestsClient, FilesClient, RefsClient, Rep
|
||||
all_issues.append(issue)
|
||||
return all_issues
|
||||
except Exception as e:
|
||||
print(f"DEBUG: list_assigned_issues error: {e}")
|
||||
logger.error(f"Error listing assigned issues: {e}", exc_info=True)
|
||||
return []
|
||||
|
||||
def list_assigned_pull_requests(self, owner: str = "", repo: str = "") -> list[PullRequestModel]:
|
||||
def list_assigned_pull_requests(
|
||||
self, owner: str = "", repo: str = ""
|
||||
) -> list[PullRequestModel]:
|
||||
"""List all pull requests assigned to or authored by the authenticated user."""
|
||||
try:
|
||||
user = self.get_authenticated_user()
|
||||
@@ -184,57 +205,66 @@ class GiteaClient(IssuesClient, PullRequestsClient, FilesClient, RefsClient, Rep
|
||||
return []
|
||||
username: str = user.login
|
||||
if owner and repo:
|
||||
response = httpx.get(
|
||||
response = self.client.get(
|
||||
f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls?state=open",
|
||||
headers=self.headers,
|
||||
)
|
||||
if response.status_code == 404:
|
||||
return []
|
||||
response.raise_for_status()
|
||||
all_prs: list[PullRequestModel] = [PullRequestModel(**pr) for pr in response.json()]
|
||||
all_prs: list[PullRequestModel] = [
|
||||
PullRequestModel(**pr) for pr in response.json()
|
||||
]
|
||||
return [
|
||||
pr for pr in all_prs
|
||||
if (pr.assignee and pr.assignee.login == username) or (pr.user and pr.user.login == username)
|
||||
pr
|
||||
for pr in all_prs
|
||||
if (pr.assignee and pr.assignee.login == username)
|
||||
or (pr.user and pr.user.login == username)
|
||||
]
|
||||
all_prs: list[PullRequestModel] = []
|
||||
repos = self.list_all_user_repos()
|
||||
for r in repos:
|
||||
repo_owner = r.owner if hasattr(r, 'owner') else (r.get("owner") or {}).get("login", "")
|
||||
repo_name = r.name if hasattr(r, 'name') else r.get("name", "")
|
||||
resp = httpx.get(
|
||||
repo_owner = r.owner
|
||||
repo_name = r.name
|
||||
resp = self.client.get(
|
||||
f"{self.base_url}/api/v1/repos/{repo_owner}/{repo_name}/pulls?state=open",
|
||||
headers=self.headers,
|
||||
)
|
||||
if resp.status_code == 200:
|
||||
for pr_data in resp.json():
|
||||
pr = PullRequestModel(**pr_data)
|
||||
if (pr.assignee and pr.assignee.login == username) or (pr.user and pr.user.login == username):
|
||||
if (pr.assignee and pr.assignee.login == username) or (
|
||||
pr.user and pr.user.login == username
|
||||
):
|
||||
# Backfill repository if Gitea omitted it
|
||||
if pr.repository is None:
|
||||
pr = pr.model_copy(update={"repository": r})
|
||||
all_prs.append(pr)
|
||||
return all_prs
|
||||
except Exception as e:
|
||||
print(f"DEBUG: list_assigned_pull_requests error: {e}")
|
||||
logger.error(f"Error listing assigned pull requests: {e}", exc_info=True)
|
||||
return []
|
||||
|
||||
def create_pull_request(
|
||||
self, owner: str, repo: str, head: str, base: str, title: str, description: str = ""
|
||||
self,
|
||||
owner: str,
|
||||
repo: str,
|
||||
head: str,
|
||||
base: str,
|
||||
title: str,
|
||||
description: str = "",
|
||||
) -> PullRequestModel:
|
||||
try:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls"
|
||||
data: dict[str, str] = {
|
||||
"title": title,
|
||||
"body": description,
|
||||
"head": head,
|
||||
"base": base,
|
||||
}
|
||||
response = client.post(url, headers=self.headers, json=data)
|
||||
response.raise_for_status()
|
||||
return PullRequestModel(**response.json())
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls"
|
||||
data: dict[str, str] = {
|
||||
"title": title,
|
||||
"body": description,
|
||||
"head": head,
|
||||
"base": base,
|
||||
}
|
||||
response = self.client.post(url, json=data)
|
||||
response.raise_for_status()
|
||||
return PullRequestModel(**response.json())
|
||||
except Exception as e:
|
||||
print(f"Error creating pull request: {e}")
|
||||
logger.error(f"Error creating pull request: {e}", exc_info=True)
|
||||
raise
|
||||
|
||||
def update_pull_request(
|
||||
@@ -247,20 +277,19 @@ class GiteaClient(IssuesClient, PullRequestsClient, FilesClient, RefsClient, Rep
|
||||
state: str | None = None,
|
||||
) -> PullRequestModel:
|
||||
try:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls/{pull_number}"
|
||||
data: dict[str, Any] = {}
|
||||
if title is not None:
|
||||
data["title"] = title
|
||||
if body is not None:
|
||||
data["body"] = body
|
||||
if state is not None:
|
||||
data["state"] = state
|
||||
response = client.patch(url, headers=self.headers, json=data)
|
||||
response.raise_for_status()
|
||||
return PullRequestModel(**response.json())
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls/{pull_number}"
|
||||
data: dict[str, Any] = {}
|
||||
if title is not None:
|
||||
data["title"] = title
|
||||
if body is not None:
|
||||
data["body"] = body
|
||||
if state is not None:
|
||||
data["state"] = state
|
||||
response = self.client.patch(url, json=data)
|
||||
response.raise_for_status()
|
||||
return PullRequestModel(**response.json())
|
||||
except Exception as e:
|
||||
print(f"Error updating pull request: {e}")
|
||||
logger.error(f"Error updating pull request: {e}", exc_info=True)
|
||||
raise
|
||||
|
||||
def create_pr_via_tea(
|
||||
@@ -268,48 +297,51 @@ class GiteaClient(IssuesClient, PullRequestsClient, FilesClient, RefsClient, Rep
|
||||
) -> PullRequestModel:
|
||||
return self.create_pull_request(owner, repo, head, base, title, description)
|
||||
|
||||
def approve_pr(self, owner: str, repo: str, pr_number: int, comment: str) -> dict[str, Any]:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls/{pr_number}/reviews"
|
||||
data: dict[str, Any] = {"event": "APPROVED", "body": comment}
|
||||
response = client.post(url, headers=self.headers, json=data)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
def approve_pr(
|
||||
self, owner: str, repo: str, pr_number: int, comment: str
|
||||
) -> dict[str, Any]:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls/{pr_number}/reviews"
|
||||
data: dict[str, Any] = {"event": "APPROVED", "body": comment}
|
||||
response = self.client.post(url, json=data)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def request_changes_pr(self, owner: str, repo: str, pr_number: int, comment: str) -> dict[str, Any]:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls/{pr_number}/reviews"
|
||||
data: dict[str, Any] = {"event": "REQUEST_CHANGES", "body": comment}
|
||||
response = client.post(url, headers=self.headers, json=data)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
def request_changes_pr(
|
||||
self, owner: str, repo: str, pr_number: int, comment: str
|
||||
) -> dict[str, Any]:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls/{pr_number}/reviews"
|
||||
data: dict[str, Any] = {"event": "REQUEST_CHANGES", "body": comment}
|
||||
response = self.client.post(url, json=data)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def get_pr_reviews(self, owner: str, repo: str, pr_number: int) -> list[dict[str, Any]]:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls/{pr_number}/reviews"
|
||||
response = client.get(url, headers=self.headers)
|
||||
if response.status_code == 404:
|
||||
return []
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
def get_pr_reviews(
|
||||
self, owner: str, repo: str, pr_number: int
|
||||
) -> list[dict[str, Any]]:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls/{pr_number}/reviews"
|
||||
response = self.client.get(url)
|
||||
if response.status_code == 404:
|
||||
return []
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def dismiss_review_pr(
|
||||
self, owner: str, repo: str, pr_number: int, review_id: int, message: str
|
||||
) -> dict[str, Any]:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls/{pr_number}/reviews/{review_id}/dismissals"
|
||||
data: dict[str, str] = {"message": message}
|
||||
response = client.post(url, headers=self.headers, json=data)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls/{pr_number}/reviews/{review_id}/dismissals"
|
||||
data: dict[str, str] = {"message": message}
|
||||
response = self.client.post(url, json=data)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def assign_issue(self, owner: str, repo: str, issue_number: int, username: str) -> IssueModel:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/issues/{issue_number}"
|
||||
data: dict[str, list[str]] = {"assignees": [username]}
|
||||
response = client.patch(url, headers=self.headers, json=data)
|
||||
response.raise_for_status()
|
||||
return IssueModel(**response.json())
|
||||
def assign_issue(
|
||||
self, owner: str, repo: str, issue_number: int, username: str
|
||||
) -> IssueModel:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/issues/{issue_number}"
|
||||
data: dict[str, list[str]] = {"assignees": [username]}
|
||||
response = self.client.patch(url, json=data)
|
||||
response.raise_for_status()
|
||||
return IssueModel(**response.json())
|
||||
|
||||
def create_issue(
|
||||
self,
|
||||
@@ -320,132 +352,151 @@ class GiteaClient(IssuesClient, PullRequestsClient, FilesClient, RefsClient, Rep
|
||||
labels: list[str] | None = None,
|
||||
assignees: list[str] | None = None,
|
||||
) -> IssueModel:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/issues"
|
||||
data: dict[str, Any] = {"title": title, "body": body}
|
||||
if labels:
|
||||
data["labels"] = labels
|
||||
if assignees:
|
||||
data["assignees"] = assignees
|
||||
response = client.post(url, headers=self.headers, json=data)
|
||||
response.raise_for_status()
|
||||
return IssueModel(**response.json())
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/issues"
|
||||
data: dict[str, Any] = {"title": title, "body": body}
|
||||
if labels:
|
||||
data["labels"] = labels
|
||||
if assignees:
|
||||
data["assignees"] = assignees
|
||||
response = self.client.post(url, json=data)
|
||||
response.raise_for_status()
|
||||
return IssueModel(**response.json())
|
||||
|
||||
def add_comment(self, owner: str, repo: str, issue_number: int, body: str) -> CommentModel:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/issues/{issue_number}/comments"
|
||||
data: dict[str, str] = {"body": body}
|
||||
response = client.post(url, headers=self.headers, json=data)
|
||||
response.raise_for_status()
|
||||
return CommentModel(**response.json())
|
||||
def add_comment(
|
||||
self, owner: str, repo: str, issue_number: int, body: str
|
||||
) -> CommentModel:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/issues/{issue_number}/comments"
|
||||
data: dict[str, str] = {"body": body}
|
||||
response = self.client.post(url, json=data)
|
||||
response.raise_for_status()
|
||||
return CommentModel(**response.json())
|
||||
|
||||
def add_label(self, owner: str, repo: str, issue_number: int, label: str) -> LabelModel:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/issues/{issue_number}/labels"
|
||||
data: list[str] = [label]
|
||||
response = client.post(url, headers=self.headers, json=data)
|
||||
response.raise_for_status()
|
||||
return LabelModel(**response.json())
|
||||
def add_label(
|
||||
self, owner: str, repo: str, issue_number: int, label: str
|
||||
) -> LabelModel:
|
||||
url = (
|
||||
f"{self.base_url}/api/v1/repos/{owner}/{repo}/issues/{issue_number}/labels"
|
||||
)
|
||||
data: list[str] = [label]
|
||||
response = self.client.post(url, json=data)
|
||||
response.raise_for_status()
|
||||
return LabelModel(**response.json())
|
||||
|
||||
def add_label_pr(self, owner: str, repo: str, pr_number: int, label: str) -> LabelModel:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/issues/{pr_number}/labels"
|
||||
data: list[str] = [label]
|
||||
response = client.post(url, headers=self.headers, json=data)
|
||||
response.raise_for_status()
|
||||
return LabelModel(**response.json())
|
||||
def add_label_pr(
|
||||
self, owner: str, repo: str, pr_number: int, label: str
|
||||
) -> LabelModel:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/issues/{pr_number}/labels"
|
||||
data: list[str] = [label]
|
||||
response = self.client.post(url, json=data)
|
||||
response.raise_for_status()
|
||||
return LabelModel(**response.json())
|
||||
|
||||
def update_ref(self, owner: str, repo: str, ref: str, sha: str) -> dict[str, Any]:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/git/ref/{ref}"
|
||||
data: dict[str, str] = {"sha": sha}
|
||||
response = client.post(url, headers=self.headers, json=data)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/git/ref/{ref}"
|
||||
data: dict[str, str] = {"sha": sha}
|
||||
response = self.client.post(url, json=data)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def create_ref(self, owner: str, repo: str, ref: str, sha: str) -> dict[str, Any]:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/git/refs"
|
||||
data: dict[str, str] = {"ref": ref, "sha": sha}
|
||||
response = client.post(url, headers=self.headers, json=data)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/git/refs"
|
||||
data: dict[str, str] = {"ref": ref, "sha": sha}
|
||||
response = self.client.post(url, json=data)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def update_file(
|
||||
self, owner: str, repo: str, path: str, message: str, content: str, branch: str
|
||||
) -> dict[str, Any]:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/contents/{path}"
|
||||
data: dict[str, str] = {
|
||||
"message": message,
|
||||
"content": base64.b64encode(content.encode()).decode(),
|
||||
"branch": branch,
|
||||
"new_branch": f"{branch}-update-{path}",
|
||||
}
|
||||
response = client.put(url, headers=self.headers, json=data)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/contents/{path}"
|
||||
data: dict[str, str] = {
|
||||
"message": message,
|
||||
"content": base64.b64encode(content.encode()).decode(),
|
||||
"branch": branch,
|
||||
"new_branch": f"{branch}-update-{path}",
|
||||
}
|
||||
response = self.client.put(url, json=data)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
def get_file_content(self, owner: str, repo: str, path: str, ref: str = "master") -> str | list[str]:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/contents/{path}"
|
||||
params: dict[str, str] = {"ref": ref}
|
||||
response = client.get(url, headers=self.headers, params=params)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
if isinstance(data, list):
|
||||
return [item.get("content", "") for item in data if item.get("type") == "file"]
|
||||
return base64.b64decode(data.get("content", "")).decode() if data.get("content") else ""
|
||||
def get_file_content(
|
||||
self, owner: str, repo: str, path: str, ref: str = "master"
|
||||
) -> str | list[str]:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/contents/{path}"
|
||||
params: dict[str, str] = {"ref": ref}
|
||||
response = self.client.get(url, params=params)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
if isinstance(data, list):
|
||||
return [
|
||||
item.get("content", "") for item in data if item.get("type") == "file"
|
||||
]
|
||||
return (
|
||||
base64.b64decode(data.get("content", "")).decode()
|
||||
if data.get("content")
|
||||
else ""
|
||||
)
|
||||
|
||||
def list_unread_notifications(self, since: Optional[str] = None) -> list[dict[str, Any]]:
|
||||
def list_unread_notifications(
|
||||
self, since: Optional[str] = None
|
||||
) -> list[dict[str, Any]]:
|
||||
try:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/notifications"
|
||||
params: dict[str, str] = {"all": "false"}
|
||||
if since:
|
||||
params["since"] = since
|
||||
response = client.get(url, headers=self.headers, params=params)
|
||||
response.raise_for_status()
|
||||
notifications: list[dict[str, Any]] = response.json()
|
||||
|
||||
result: list[dict[str, Any]] = []
|
||||
for n in notifications:
|
||||
repo_info = n.get("repository") or {}
|
||||
owner_info = repo_info.get("owner") or {}
|
||||
owner_login = owner_info.get("login", "")
|
||||
if owner_login == "meeks":
|
||||
result.append(n)
|
||||
return result
|
||||
url = f"{self.base_url}/api/v1/notifications"
|
||||
params: dict[str, str] = {"all": "false"}
|
||||
if since:
|
||||
params["since"] = since
|
||||
response = self.client.get(url, params=params)
|
||||
response.raise_for_status()
|
||||
notifications: list[dict[str, Any]] = response.json()
|
||||
|
||||
result: list[dict[str, Any]] = []
|
||||
for n in notifications:
|
||||
repo_info = n.get("repository") or {}
|
||||
owner_info = repo_info.get("owner") or {}
|
||||
owner_login = owner_info.get("login", "")
|
||||
if owner_login == GITEA_ORG_FILTER:
|
||||
result.append(n)
|
||||
return result
|
||||
except Exception as e:
|
||||
print(f"Error listing unread notifications: {e}")
|
||||
logger.error(f"Error listing unread notifications: {e}", exc_info=True)
|
||||
return []
|
||||
|
||||
def mark_notification_as_read(self, thread_id: int) -> bool:
|
||||
try:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/notifications/threads/{thread_id}"
|
||||
response = client.patch(url, headers=self.headers)
|
||||
response.raise_for_status()
|
||||
return True
|
||||
url = f"{self.base_url}/api/v1/notifications/threads/{thread_id}"
|
||||
response = self.client.patch(url)
|
||||
response.raise_for_status()
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"Error marking notification thread {thread_id} as read: {e}")
|
||||
logger.error(
|
||||
f"Error marking notification thread {thread_id} as read: {e}",
|
||||
exc_info=True,
|
||||
)
|
||||
return False
|
||||
|
||||
def merge_pull_request(
|
||||
self, owner: str, repo: str, pull_number: int, style: str = "squash", title: str = "", message: str = ""
|
||||
self,
|
||||
owner: str,
|
||||
repo: str,
|
||||
pull_number: int,
|
||||
style: str = "squash",
|
||||
title: str = "",
|
||||
message: str = "",
|
||||
) -> bool:
|
||||
try:
|
||||
with httpx.Client() as client:
|
||||
url = f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls/{pull_number}/merge"
|
||||
data: dict[str, Any] = {
|
||||
"Do": style,
|
||||
"MergeTitleField": title,
|
||||
"MergeMessageField": message,
|
||||
}
|
||||
response = client.post(url, headers=self.headers, json=data)
|
||||
response.raise_for_status()
|
||||
return True
|
||||
url = (
|
||||
f"{self.base_url}/api/v1/repos/{owner}/{repo}/pulls/{pull_number}/merge"
|
||||
)
|
||||
data: dict[str, Any] = {
|
||||
"Do": style,
|
||||
"MergeTitleField": title,
|
||||
"MergeMessageField": message,
|
||||
}
|
||||
response = self.client.post(url, json=data)
|
||||
response.raise_for_status()
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"Error merging pull request {pull_number}: {e}")
|
||||
logger.error(
|
||||
f"Error merging pull request {pull_number}: {e}", exc_info=True
|
||||
)
|
||||
raise
|
||||
|
||||
|
||||
+4
-9
@@ -13,6 +13,8 @@ class AgentSettings(BaseSettings):
|
||||
gitea_repos_root: str = ""
|
||||
agent_model_id: str = "qwen/qwen3.6-35b-a3b"
|
||||
agent_max_retries: int = 2
|
||||
agent_usernames: list[str] = ["agent-bot"]
|
||||
gitea_org_filter: str = "meeks"
|
||||
searxng_url: str = ""
|
||||
searxng_username: str = ""
|
||||
searxng_password: str = ""
|
||||
@@ -31,15 +33,8 @@ GITEA_TOKEN: str = _agent_settings.gitea_token
|
||||
GITEA_REPOS_ROOT: str = _agent_settings.gitea_repos_root
|
||||
AGENT_MODEL_ID: str = _agent_settings.agent_model_id
|
||||
AGENT_MAX_RETRIES: int = _agent_settings.agent_max_retries
|
||||
AGENT_USERNAMES: list[str] = _agent_settings.agent_usernames
|
||||
GITEA_ORG_FILTER: str = _agent_settings.gitea_org_filter
|
||||
SEARXNG_URL: str = _agent_settings.searxng_url
|
||||
SEARXNG_USERNAME: str = _agent_settings.searxng_username
|
||||
SEARXNG_PASSWORD: str = _agent_settings.searxng_password
|
||||
|
||||
import os
|
||||
os.environ["GITEA_SERVER_URL"] = GITEA_URL
|
||||
os.environ["GITEA_SERVER_TOKEN"] = GITEA_TOKEN
|
||||
os.environ["SEARXNG_URL"] = SEARXNG_URL
|
||||
os.environ["SEARXNG_USERNAME"] = SEARXNG_USERNAME
|
||||
os.environ["SEARXNG_PASSWORD"] = SEARXNG_PASSWORD
|
||||
|
||||
|
||||
|
||||
@@ -132,6 +132,15 @@ class CodingTools:
|
||||
|
||||
return commands
|
||||
|
||||
def _get_subprocess_env(self) -> dict[str, str]:
|
||||
from gitea.config import GITEA_URL, GITEA_TOKEN
|
||||
env = os.environ.copy()
|
||||
if GITEA_URL:
|
||||
env["GITEA_SERVER_URL"] = GITEA_URL
|
||||
if GITEA_TOKEN:
|
||||
env["GITEA_SERVER_TOKEN"] = GITEA_TOKEN
|
||||
return env
|
||||
|
||||
def run_verification(self) -> tuple[bool, str]:
|
||||
commands = self._parse_verification_commands()
|
||||
if not commands:
|
||||
@@ -143,7 +152,8 @@ class CodingTools:
|
||||
try:
|
||||
res = subprocess.run(
|
||||
cmd, shell=True, cwd=self.repo_path,
|
||||
capture_output=True, text=True, timeout=120
|
||||
capture_output=True, text=True, timeout=120,
|
||||
env=self._get_subprocess_env()
|
||||
)
|
||||
if res.returncode != 0:
|
||||
log_output.append(
|
||||
@@ -213,6 +223,7 @@ class CodingTools:
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
cwd=self.repo_path,
|
||||
env=self._get_subprocess_env(),
|
||||
)
|
||||
stdout: str
|
||||
stderr: str
|
||||
@@ -263,10 +274,10 @@ class CodingTools:
|
||||
"""
|
||||
resolved: str = self._resolve_path(path)
|
||||
try:
|
||||
command: str = f"grep -ri '{pattern}' {resolved}"
|
||||
command: list[str] = ["grep", "-ri", pattern, resolved]
|
||||
process: subprocess.Popen[str] = subprocess.Popen(
|
||||
command,
|
||||
shell=True,
|
||||
shell=False,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
|
||||
@@ -1,177 +0,0 @@
|
||||
from gitea.tools.issue_tools import IssueTools
|
||||
from gitea.tools.pr_tools import PRTools
|
||||
from gitea.tools.file_tools import FileTools
|
||||
from gitea.tools.git_tools import GitTools
|
||||
from gitea.client import GiteaClient
|
||||
|
||||
|
||||
class GiteaTools:
|
||||
"""Facade for Gitea tool operations - delegates to focused tool classes."""
|
||||
|
||||
def __init__(self, client: GiteaClient) -> None:
|
||||
self._client = client
|
||||
self.issue_tools = IssueTools(client)
|
||||
self.pr_tools = PRTools(client)
|
||||
self.file_tools = FileTools(client)
|
||||
self.git_tools = GitTools(client)
|
||||
|
||||
# ---- Issue operations (delegated) ----
|
||||
|
||||
def get_issue(self, owner: str, repo: str, issue_number: int) -> str:
|
||||
"""Get the details of a specific issue. Args: owner (repo owner), repo (repo name), issue_number (issue ID)."""
|
||||
return self.issue_tools.get_issue(owner, repo, issue_number)
|
||||
|
||||
def get_pull_request(self, owner: str, repo: str, pull_number: int) -> str:
|
||||
"""Get the details of a specific pull request. Args: owner (repo owner), repo (repo name), pull_number (PR ID)."""
|
||||
return self.pr_tools.get_pull_request(owner, repo, pull_number)
|
||||
|
||||
def close_issue(self, owner: str, repo: str, issue_number: int) -> str:
|
||||
"""Close an issue. Args: owner (repo owner), repo (repo name), issue_number (issue ID)."""
|
||||
return self.issue_tools.close_issue(owner, repo, issue_number)
|
||||
|
||||
def close_pull_request(self, owner: str, repo: str, pull_number: int) -> str:
|
||||
"""Close a pull request. Args: owner (repo owner), repo (repo name), pull_number (PR ID)."""
|
||||
return self.pr_tools.close_pull_request(owner, repo, pull_number)
|
||||
|
||||
def get_issue_comments(
|
||||
self,
|
||||
owner: str,
|
||||
repo: str,
|
||||
issue_number: int,
|
||||
limit: int = 20,
|
||||
offset: int = 0,
|
||||
) -> str:
|
||||
"""Get all comments on an issue. Args: owner, repo, issue_number, limit (default 20), offset (default 0)."""
|
||||
return self.issue_tools.get_issue_comments(owner, repo, issue_number, limit=limit, offset=offset)
|
||||
|
||||
def get_pull_request_comments(
|
||||
self,
|
||||
owner: str,
|
||||
repo: str,
|
||||
pull_number: int,
|
||||
limit: int = 20,
|
||||
offset: int = 0,
|
||||
) -> str:
|
||||
"""Get all comments on a pull request. Args: owner, repo, pull_number, limit (default 20), offset (default 0)."""
|
||||
return self.pr_tools.get_pull_request_comments(owner, repo, pull_number, limit=limit, offset=offset)
|
||||
|
||||
def list_assigned_issues(self) -> list[dict]:
|
||||
"""List all issues assigned to the authenticated user across all repos."""
|
||||
return self.issue_tools.list_assigned_issues()
|
||||
|
||||
def list_assigned_pull_requests(self) -> list[dict]:
|
||||
"""List all pull requests assigned to the authenticated user across all repos."""
|
||||
return self.pr_tools.list_assigned_pull_requests()
|
||||
|
||||
def list_issues(self, owner: str, repo: str, state: str = "open") -> str:
|
||||
"""List issues in a repository. Args: owner (repo owner), repo (repo name), state (open, closed, or all)."""
|
||||
return self.issue_tools.list_issues(owner, repo, state)
|
||||
|
||||
def list_pull_requests(self, owner: str, repo: str, state: str = "open") -> str:
|
||||
"""List pull requests in a repository. Args: owner (repo owner), repo (repo name), state (open, closed, or all)."""
|
||||
return self.pr_tools.list_pull_requests(owner, repo, state)
|
||||
|
||||
def get_file_content(
|
||||
self,
|
||||
owner: str,
|
||||
repo: str,
|
||||
path: str,
|
||||
offset: int = 1,
|
||||
limit: int = 250,
|
||||
) -> str:
|
||||
"""Get the content of a file from a repository. Args: owner, repo, path, offset (line, default 1), limit (default 250)."""
|
||||
return self.file_tools.get_file_content(owner, repo, path, offset=offset, limit=limit)
|
||||
|
||||
def create_pull_request(self, owner: str, repo: str, head: str, base: str, title: str, description: str = "") -> str:
|
||||
"""Create a new pull request. Args: owner, repo, head (source branch), base (target branch), title, description."""
|
||||
return self.pr_tools.create_pull_request(owner, repo, head, base, title, description)
|
||||
|
||||
def update_pull_request(
|
||||
self,
|
||||
owner: str,
|
||||
repo: str,
|
||||
pull_number: int,
|
||||
title: str | None = None,
|
||||
body: str | None = None,
|
||||
state: str | None = None,
|
||||
) -> str:
|
||||
"""Update an existing pull request. Args: owner, repo, pull_number, title (optional), body (optional), state (optional)."""
|
||||
return self.pr_tools.update_pull_request(owner, repo, pull_number, title, body, state)
|
||||
|
||||
def create_issue(self, owner: str, repo: str, title: str, body: str, labels: list[str] | None = None, assignees: list[str] | None = None) -> str:
|
||||
"""Create a new issue. Args: owner, repo, title, body, labels (optional), assignees (optional)."""
|
||||
return self.issue_tools.create_issue(owner, repo, title, body, labels, assignees)
|
||||
|
||||
def create_branch(self, owner: str, repo: str, ref: str, sha: str) -> str:
|
||||
"""Create a new branch in a repository. Args: owner, repo, ref (branch name), sha (commit SHA)."""
|
||||
return self.git_tools.create_branch(owner, repo, ref, sha)
|
||||
|
||||
def commit_file(self, owner: str, repo: str, path: str, message: str, content: str, branch: str) -> str:
|
||||
"""Commit a file to a repository. Args: owner, repo, path, message, content, branch."""
|
||||
return self.file_tools.commit_file(owner, repo, path, message, content, branch)
|
||||
|
||||
def add_label_to_issue(self, owner: str, repo: str, issue_number: int, label: str) -> str:
|
||||
"""Add a label to an issue. Args: owner, repo, issue_number, label."""
|
||||
return self.issue_tools.add_label_to_issue(owner, repo, issue_number, label)
|
||||
|
||||
def add_label_to_pr(self, owner: str, repo: str, pr_number: int, label: str) -> str:
|
||||
"""Add a label to a pull request. Args: owner, repo, pr_number, label."""
|
||||
return self.pr_tools.add_label_to_pr(owner, repo, pr_number, label)
|
||||
|
||||
def add_comment_to_issue(self, owner: str, repo: str, issue_number: int, body: str) -> str:
|
||||
"""Add a comment to an issue. Args: owner, repo, issue_number, body."""
|
||||
return self.issue_tools.add_comment_to_issue(owner, repo, issue_number, body)
|
||||
|
||||
def get_pull_request_diff(
|
||||
self,
|
||||
owner: str,
|
||||
repo: str,
|
||||
pull_number: int,
|
||||
max_chars: int = 15000,
|
||||
char_offset: int = 0,
|
||||
) -> str:
|
||||
"""Get the diff of a pull request. Args: owner, repo, pull_number, max_chars (default 15000), char_offset (default 0)."""
|
||||
return self.pr_tools.get_pull_request_diff(owner, repo, pull_number, max_chars=max_chars, char_offset=char_offset)
|
||||
|
||||
def get_pull_request_patch(
|
||||
self,
|
||||
owner: str,
|
||||
repo: str,
|
||||
pull_number: int,
|
||||
max_chars: int = 15000,
|
||||
char_offset: int = 0,
|
||||
) -> str:
|
||||
"""Get the patch of a pull request. Args: owner, repo, pull_number, max_chars (default 15000), char_offset (default 0)."""
|
||||
return self.pr_tools.get_pull_request_patch(owner, repo, pull_number, max_chars=max_chars, char_offset=char_offset)
|
||||
|
||||
def approve_pull_request(self, owner: str, repo: str, pull_number: int, comment: str) -> str:
|
||||
"""Approve a pull request. Args: owner, repo, pull_number, comment."""
|
||||
return self.pr_tools.approve_pull_request(owner, repo, pull_number, comment)
|
||||
|
||||
def request_changes(self, owner: str, repo: str, pull_number: int, comment: str) -> str:
|
||||
"""Request changes on a pull request. Args: owner, repo, pull_number, comment."""
|
||||
return self.pr_tools.request_changes(owner, repo, pull_number, comment)
|
||||
|
||||
def add_comment(self, owner: str, repo: str, issue_number: int, body: str) -> str:
|
||||
"""Add a comment to an issue. Args: owner, repo, issue_number, body."""
|
||||
return self.issue_tools.add_comment(owner, repo, issue_number, body)
|
||||
|
||||
def add_label(self, owner: str, repo: str, issue_number: int, label: str) -> str:
|
||||
"""Add a label to an issue. Args: owner, repo, issue_number, label."""
|
||||
return self.issue_tools.add_label(owner, repo, issue_number, label)
|
||||
|
||||
def get_file_content_with_ref(
|
||||
self,
|
||||
owner: str,
|
||||
repo: str,
|
||||
path: str,
|
||||
ref: str = "master",
|
||||
offset: int = 1,
|
||||
limit: int = 250,
|
||||
) -> str:
|
||||
"""Get file content with a specific git ref. Args: owner, repo, path, ref (branch/tag), offset (line, default 1), limit (default 250)."""
|
||||
return self.file_tools.get_file_content_with_ref(owner, repo, path, ref=ref, offset=offset, limit=limit)
|
||||
|
||||
def update_file(self, owner: str, repo: str, path: str, message: str, content: str, branch: str) -> str:
|
||||
"""Update a file in a repository. Args: owner, repo, path, message, content, branch."""
|
||||
return self.file_tools.update_file(owner, repo, path, message, content, branch)
|
||||
+30
-20
@@ -1,10 +1,13 @@
|
||||
"""Tools for Gitea issue operations."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
from gitea.client import GiteaClient
|
||||
from gitea.models import IssueModel, CommentModel, LabelModel
|
||||
|
||||
logger: logging.Logger = logging.getLogger("gitea.tools.issue_tools")
|
||||
|
||||
|
||||
class IssueTools:
|
||||
"""Tools for Gitea issue operations."""
|
||||
@@ -66,10 +69,17 @@ class IssueTools:
|
||||
repo_name = repo.name
|
||||
issues = self._client.list_assigned_issues(owner, repo_name)
|
||||
if issues:
|
||||
all_issues.extend([issue.model_dump() if hasattr(issue, 'model_dump') else issue for issue in issues])
|
||||
all_issues.extend(
|
||||
[
|
||||
issue.model_dump()
|
||||
if hasattr(issue, "model_dump")
|
||||
else issue
|
||||
for issue in issues
|
||||
]
|
||||
)
|
||||
return all_issues
|
||||
except Exception as e:
|
||||
print(f"DEBUG: list_assigned_issues error: {e}")
|
||||
logger.error(f"Error listing assigned issues: {e}", exc_info=True)
|
||||
return []
|
||||
|
||||
def list_issues(self, owner: str, repo: str, state: str = "open") -> str:
|
||||
@@ -82,37 +92,37 @@ class IssueTools:
|
||||
except Exception as e:
|
||||
return f"Error listing issues: {str(e)}"
|
||||
|
||||
def create_issue(self, owner: str, repo: str, title: str, body: str, labels: list[str] | None = None, assignees: list[str] | None = None) -> str:
|
||||
def create_issue(
|
||||
self,
|
||||
owner: str,
|
||||
repo: str,
|
||||
title: str,
|
||||
body: str,
|
||||
labels: list[str] | None = None,
|
||||
assignees: list[str] | None = None,
|
||||
) -> str:
|
||||
try:
|
||||
issue = self._client.create_issue(owner, repo, title, body, labels, assignees)
|
||||
issue = self._client.create_issue(
|
||||
owner, repo, title, body, labels, assignees
|
||||
)
|
||||
return f"Issue #{issue.number} created successfully in {owner}/{repo}."
|
||||
except Exception as e:
|
||||
return f"Error creating issue: {str(e)}"
|
||||
|
||||
def add_label_to_issue(self, owner: str, repo: str, issue_number: int, label: str) -> str:
|
||||
def add_label_to_issue(
|
||||
self, owner: str, repo: str, issue_number: int, label: str
|
||||
) -> str:
|
||||
try:
|
||||
self._client.add_label(owner, repo, issue_number, label)
|
||||
return f"Label '{label}' added to issue #{issue_number}."
|
||||
except Exception as e:
|
||||
return f"Error adding label to issue #{issue_number}: {e}"
|
||||
|
||||
def add_comment_to_issue(self, owner: str, repo: str, issue_number: int, body: str) -> str:
|
||||
def add_comment_to_issue(
|
||||
self, owner: str, repo: str, issue_number: int, body: str
|
||||
) -> str:
|
||||
try:
|
||||
self._client.add_comment(owner, repo, issue_number, body)
|
||||
return f"Comment added to issue #{issue_number}."
|
||||
except Exception as e:
|
||||
return f"Error adding comment to issue #{issue_number}: {e}"
|
||||
|
||||
def add_comment(self, owner: str, repo: str, issue_number: int, body: str) -> str:
|
||||
try:
|
||||
comment = self._client.add_comment(owner, repo, issue_number, body)
|
||||
return f"Comment added to #{issue_number}."
|
||||
except Exception as e:
|
||||
return f"Error adding comment: {str(e)}"
|
||||
|
||||
def add_label(self, owner: str, repo: str, issue_number: int, label: str) -> str:
|
||||
try:
|
||||
self._client.add_label(owner, repo, issue_number, label)
|
||||
return f"Label '{label}' added to #{issue_number}."
|
||||
except Exception as e:
|
||||
return f"Error adding label: {str(e)}"
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
"""Tools for Gitea pull request operations."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
from gitea.client import GiteaClient
|
||||
from gitea.models import PullRequestModel, CommentModel
|
||||
|
||||
logger: logging.Logger = logging.getLogger("gitea.tools.pr_tools")
|
||||
|
||||
|
||||
_MAX_DIFF_CHARS: int = 15_000
|
||||
|
||||
|
||||
@@ -93,7 +97,7 @@ class PRTools:
|
||||
all_prs.extend([pr.model_dump() if hasattr(pr, 'model_dump') else pr for pr in prs])
|
||||
return all_prs
|
||||
except Exception as e:
|
||||
print(f"DEBUG: list_assigned_pull_requests error: {e}")
|
||||
logger.error(f"Error listing assigned pull requests: {e}", exc_info=True)
|
||||
return []
|
||||
|
||||
def list_pull_requests(self, owner: str, repo: str, state: str = "open") -> str:
|
||||
|
||||
+57
-50
@@ -1,9 +1,12 @@
|
||||
import os
|
||||
import logging
|
||||
import subprocess
|
||||
import base64
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
from .config import GITEA_REPOS_ROOT, GITEA_URL, GITEA_TOKEN
|
||||
from gitea.client import GiteaClient
|
||||
|
||||
logger: logging.Logger = logging.getLogger("gitea-workspace")
|
||||
|
||||
@@ -14,60 +17,38 @@ class WorkspaceManager:
|
||||
def __init__(self) -> None:
|
||||
self.root_dir: Path = Path(GITEA_REPOS_ROOT).expanduser().resolve()
|
||||
self.root_dir.mkdir(parents=True, exist_ok=True)
|
||||
self._configure_git_credentials()
|
||||
|
||||
def _configure_git_credentials(self) -> None:
|
||||
try:
|
||||
# Unset any global configs we might have set previously
|
||||
subprocess.run(
|
||||
["git", "config", "--global", "--unset", "credential.helper"],
|
||||
capture_output=True
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "config", "--global", "--unset", "user.name"],
|
||||
capture_output=True
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "config", "--global", "--unset", "user.email"],
|
||||
capture_output=True
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Error unsetting global configs: {e}")
|
||||
|
||||
def _configure_repo_user(self, repo_path: Path) -> None:
|
||||
try:
|
||||
# Configure credential helper locally for the repo
|
||||
subprocess.run(
|
||||
["git", "-C", str(repo_path), "config", "credential.helper", "store"],
|
||||
check=True, capture_output=True
|
||||
)
|
||||
# Write to ~/.git-credentials
|
||||
parsed = urlparse(GITEA_URL.rstrip("/"))
|
||||
cred_line = f"{parsed.scheme}://meeks-ai:{GITEA_TOKEN}@{parsed.netloc}\n"
|
||||
cred_file = Path("~/.git-credentials").expanduser()
|
||||
if cred_file.exists():
|
||||
content = cred_file.read_text()
|
||||
if cred_line.strip() not in content:
|
||||
cred_file.write_text(content + cred_line)
|
||||
else:
|
||||
cred_file.write_text(cred_line)
|
||||
|
||||
from gitea.client import GiteaClient
|
||||
client = GiteaClient()
|
||||
user = client.get_authenticated_user()
|
||||
if user:
|
||||
name = user.full_name or user.login or "meeks-ai"
|
||||
email = user.email or "micke_ingvarsson+ai@hotmail.com"
|
||||
subprocess.run(
|
||||
["git", "-C", str(repo_path), "config", "user.name", name],
|
||||
check=True, capture_output=True
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(repo_path), "config", "user.email", email],
|
||||
check=True, capture_output=True
|
||||
)
|
||||
if not user or not user.login:
|
||||
raise RuntimeError("No authenticated user found.")
|
||||
username: str = user.login
|
||||
|
||||
auth_str: str = f"{username}:{GITEA_TOKEN}"
|
||||
auth_bytes: bytes = auth_str.encode("utf-8")
|
||||
auth_b64: str = base64.b64encode(auth_bytes).decode("utf-8")
|
||||
|
||||
# Configure extraHeader locally for the repo
|
||||
subprocess.run(
|
||||
["git", "-C", str(repo_path), "config", "http.extraHeader", f"Authorization: Basic {auth_b64}"],
|
||||
check=True, capture_output=True
|
||||
)
|
||||
|
||||
name: str = user.full_name or user.login
|
||||
email: str = user.email or f"{user.login}@noreply.gitea"
|
||||
subprocess.run(
|
||||
["git", "-C", str(repo_path), "config", "user.name", name],
|
||||
check=True, capture_output=True
|
||||
)
|
||||
subprocess.run(
|
||||
["git", "-C", str(repo_path), "config", "user.email", email],
|
||||
check=True, capture_output=True
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Error configuring local git user: {e}")
|
||||
raise
|
||||
|
||||
def get_repo_path(self, repo_full_name: str) -> Path:
|
||||
parts: list[str] = repo_full_name.split("/")
|
||||
@@ -86,6 +67,19 @@ class WorkspaceManager:
|
||||
check=True, capture_output=True,
|
||||
)
|
||||
self._configure_repo_user(repo_path)
|
||||
|
||||
# Check for any uncommitted changes or untracked files
|
||||
status_res = subprocess.run(
|
||||
["git", "-C", str(repo_path), "status", "--porcelain"],
|
||||
check=True, capture_output=True, text=True
|
||||
)
|
||||
if status_res.stdout.strip():
|
||||
logger.info(f"Uncommitted changes detected in {repo_path}. Stashing before sanitization.")
|
||||
subprocess.run(
|
||||
["git", "-C", str(repo_path), "stash", "push", "-u", "-m", "Auto-backup before agent sanitization"],
|
||||
check=True, capture_output=True
|
||||
)
|
||||
|
||||
subprocess.run(
|
||||
["git", "-C", str(repo_path), "reset", "--hard", "HEAD"],
|
||||
check=True, capture_output=True,
|
||||
@@ -115,7 +109,8 @@ class WorkspaceManager:
|
||||
check=True, capture_output=True,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Error during sanitization: {e}")
|
||||
logger.error(f"Error during sanitization: {e}", exc_info=True)
|
||||
raise RuntimeError(f"Failed to sanitize repository {repo_full_name} at {repo_path}: {e}") from e
|
||||
|
||||
def clone_repo(self, repo_full_name: str, clone_url: str | None = None) -> Path:
|
||||
repo_path: Path = self.get_repo_path(repo_full_name)
|
||||
@@ -123,13 +118,25 @@ class WorkspaceManager:
|
||||
if not (repo_path / ".git").exists():
|
||||
new_path: Path = repo_path.parent / f"{repo_full_name.replace('/', '_')}_old"
|
||||
if new_path.exists():
|
||||
import shutil
|
||||
shutil.rmtree(new_path)
|
||||
repo_path.rename(new_path)
|
||||
return repo_path
|
||||
|
||||
logger.info(f"Cloning repository {repo_full_name} to {repo_path}...")
|
||||
auth_url = self._get_authenticated_url(repo_full_name)
|
||||
subprocess.run(["git", "clone", auth_url, str(repo_path)], check=True, capture_output=True)
|
||||
|
||||
client = GiteaClient()
|
||||
user = client.get_authenticated_user()
|
||||
if not user or not user.login:
|
||||
raise RuntimeError("No authenticated user found.")
|
||||
username: str = user.login
|
||||
|
||||
auth_str: str = f"{username}:{GITEA_TOKEN}"
|
||||
auth_bytes: bytes = auth_str.encode("utf-8")
|
||||
auth_b64: str = base64.b64encode(auth_bytes).decode("utf-8")
|
||||
subprocess.run(
|
||||
["git", "clone", "-c", f"http.extraHeader=Authorization: Basic {auth_b64}", auth_url, str(repo_path)],
|
||||
check=True, capture_output=True
|
||||
)
|
||||
self._configure_repo_user(repo_path)
|
||||
return repo_path
|
||||
|
||||
@@ -7,7 +7,10 @@ from pathlib import Path
|
||||
from dotenv import load_dotenv
|
||||
|
||||
from gitea.client import GiteaClient
|
||||
from gitea.tools.gitea_tools import GiteaTools
|
||||
from gitea.tools.issue_tools import IssueTools
|
||||
from gitea.tools.pr_tools import PRTools
|
||||
from gitea.tools.file_tools import FileTools
|
||||
from gitea.tools.git_tools import GitTools
|
||||
from gitea.config import AGENT_MODEL_ID, AGENT_MAX_RETRIES
|
||||
from core.orchestrator import AgentOrchestrator
|
||||
|
||||
@@ -38,12 +41,11 @@ file_handler = RotatingFileHandler(LOG_FILE, maxBytes=5 * 1024 * 1024, backupCou
|
||||
file_handler.setFormatter(JSONFormatter())
|
||||
|
||||
stream_handler = logging.StreamHandler()
|
||||
stream_handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(message)s"))
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
handlers=[file_handler, stream_handler]
|
||||
stream_handler.setFormatter(
|
||||
logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
|
||||
)
|
||||
|
||||
logging.basicConfig(level=logging.INFO, handlers=[file_handler, stream_handler])
|
||||
logger: logging.Logger = logging.getLogger("coding-agent")
|
||||
|
||||
|
||||
@@ -58,11 +60,33 @@ async def main() -> None:
|
||||
|
||||
# Initialize Gitea components
|
||||
client: GiteaClient = GiteaClient()
|
||||
tools: GiteaTools = GiteaTools(client)
|
||||
try:
|
||||
user = client.get_authenticated_user()
|
||||
if not user or not user.login:
|
||||
raise RuntimeError("No authenticated user found.")
|
||||
logger.info(f"Authenticated as user: {user.login}")
|
||||
except Exception as e:
|
||||
logger.critical(
|
||||
f"Critical initialization error: No authenticated user found. {e}"
|
||||
)
|
||||
raise SystemExit(1)
|
||||
|
||||
issue_tools: IssueTools = IssueTools(client)
|
||||
pr_tools: PRTools = PRTools(client)
|
||||
file_tools: FileTools = FileTools(client)
|
||||
git_tools: GitTools = GitTools(client)
|
||||
model_name: str = AGENT_MODEL_ID
|
||||
|
||||
# Initialize orchestrator
|
||||
orchestrator: AgentOrchestrator = AgentOrchestrator(client, tools, model_name, AGENT_MAX_RETRIES)
|
||||
orchestrator: AgentOrchestrator = AgentOrchestrator(
|
||||
client,
|
||||
issue_tools,
|
||||
pr_tools,
|
||||
file_tools,
|
||||
git_tools,
|
||||
model_name,
|
||||
AGENT_MAX_RETRIES,
|
||||
)
|
||||
|
||||
logger.info("--- Autonomous Coding Agent Active ---")
|
||||
logger.info(f"Model: {model_name}")
|
||||
@@ -91,11 +115,15 @@ async def main() -> None:
|
||||
break
|
||||
except Exception as e:
|
||||
consecutive_errors += 1
|
||||
logger.error(f"Error in main loop (attempt {consecutive_errors}/{max_consecutive_errors}): {e}")
|
||||
logger.error(
|
||||
f"Error in main loop (attempt {consecutive_errors}/{max_consecutive_errors}): {e}"
|
||||
)
|
||||
|
||||
# If too many consecutive errors, wait longer
|
||||
if consecutive_errors >= max_consecutive_errors:
|
||||
logger.error(f"Too many consecutive errors ({max_consecutive_errors}). Waiting 5 minutes before retry.")
|
||||
logger.error(
|
||||
f"Too many consecutive errors ({max_consecutive_errors}). Waiting 5 minutes before retry."
|
||||
)
|
||||
await asyncio.sleep(300)
|
||||
consecutive_errors = 0
|
||||
else:
|
||||
|
||||
@@ -104,13 +104,13 @@ async def test_dispatch_planning_and_coding_phases(mock_planning_class: MagicMoc
|
||||
mock_client.get_issue_comments.return_value = []
|
||||
|
||||
from gitea.models import UserModel
|
||||
mock_client.get_authenticated_user.return_value = UserModel(login="meeks-ai")
|
||||
mock_client.get_authenticated_user.return_value = UserModel(login="unknown-ai")
|
||||
|
||||
mock_pr = PullRequestModel(
|
||||
number=42,
|
||||
title="fix bug",
|
||||
body="bug details",
|
||||
user=UserModel(login="meeks-ai")
|
||||
user=UserModel(login="unknown-ai")
|
||||
)
|
||||
mock_client.get_pull_request.return_value = mock_pr
|
||||
mock_client.get_pull_request_diff.return_value = "diff"
|
||||
@@ -137,9 +137,7 @@ async def test_dispatch_planning_and_coding_phases(mock_planning_class: MagicMoc
|
||||
priority=0
|
||||
)
|
||||
|
||||
# We mock os.path.isdir to return True so os.chdir won't fail or crash in test
|
||||
with patch("os.path.isdir", return_value=True), patch("os.chdir"):
|
||||
results = await dispatcher.dispatch("meeks/repo1", [work_item])
|
||||
results = await dispatcher.dispatch("meeks/repo1", [work_item])
|
||||
|
||||
assert len(results) == 1
|
||||
assert results[0] == "PR #1 Created"
|
||||
|
||||
+13
-2
@@ -56,7 +56,7 @@ def test_gitea_client_list_assigned_issues() -> None:
|
||||
user_mock.login = "testuser"
|
||||
|
||||
with patch.object(client, "get_authenticated_user", return_value=user_mock), \
|
||||
patch("httpx.get") as mock_get:
|
||||
patch("httpx.Client.get") as mock_get:
|
||||
mock_response: MagicMock = MagicMock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = []
|
||||
@@ -75,7 +75,7 @@ def test_gitea_client_list_assigned_pull_requests() -> None:
|
||||
user_mock.login = "testuser"
|
||||
|
||||
with patch.object(client, "get_authenticated_user", return_value=user_mock), \
|
||||
patch("httpx.get") as mock_get:
|
||||
patch("httpx.Client.get") as mock_get:
|
||||
mock_response: MagicMock = MagicMock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = [
|
||||
@@ -122,3 +122,14 @@ def test_gitea_client_list_unread_notifications() -> None:
|
||||
assert kwargs.get("params") == {"all": "false", "since": "2026-06-30T21:41:16+02:00"}
|
||||
|
||||
|
||||
import pytest
|
||||
|
||||
def test_gitea_client_get_authenticated_user_failure() -> None:
|
||||
client: GiteaClient = GiteaClient()
|
||||
with patch("httpx.Client.get") as mock_get:
|
||||
mock_get.side_effect = Exception("Connection error")
|
||||
with pytest.raises(RuntimeError, match="Could not get authenticated user"):
|
||||
client.get_authenticated_user()
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -126,8 +126,17 @@ def test_grep_search_success(mock_popen: MagicMock) -> None:
|
||||
mock_process.returncode = 0
|
||||
mock_popen.return_value = mock_process
|
||||
|
||||
res: str = CodingTools().grep_search("pattern", "/path")
|
||||
tools = CodingTools()
|
||||
res: str = tools.grep_search("pattern", "/path")
|
||||
assert res == "match_line"
|
||||
mock_popen.assert_called_once_with(
|
||||
["grep", "-ri", "pattern", tools._resolve_path("/path")],
|
||||
shell=False,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
cwd=tools.repo_path,
|
||||
)
|
||||
|
||||
|
||||
@patch("subprocess.Popen")
|
||||
@@ -137,8 +146,17 @@ def test_grep_search_no_matches(mock_popen: MagicMock) -> None:
|
||||
mock_process.returncode = 1
|
||||
mock_popen.return_value = mock_process
|
||||
|
||||
res: str = CodingTools().grep_search("pattern", "/path")
|
||||
tools = CodingTools()
|
||||
res: str = tools.grep_search("pattern", "/path")
|
||||
assert "No matches found" in res
|
||||
mock_popen.assert_called_once_with(
|
||||
["grep", "-ri", "pattern", tools._resolve_path("/path")],
|
||||
shell=False,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
cwd=tools.repo_path,
|
||||
)
|
||||
|
||||
|
||||
def test_grep_search_error() -> None:
|
||||
|
||||
+93
-21
@@ -107,6 +107,7 @@ async def test_build_pr_mission_injects_issue_context(mock_agent_class: MagicMoc
|
||||
mock_agent_instance.run_with_tools = AsyncMock(return_value="PR Reviewed.")
|
||||
mock_agent_class.return_value = mock_agent_instance
|
||||
|
||||
mock_client.get_authenticated_user.return_value = UserModel(login="unknown-ai")
|
||||
dispatcher = AgentDispatcher(client=mock_client, tools=mock_tools)
|
||||
|
||||
work_item = WorkItem(
|
||||
@@ -186,12 +187,12 @@ async def test_dispatch_skips_already_reviewed_pr() -> None:
|
||||
mock_tools: MagicMock = MagicMock(spec=GiteaTools)
|
||||
|
||||
from gitea.models import UserModel
|
||||
mock_client.get_authenticated_user.return_value = UserModel(login="meeks-ai")
|
||||
mock_client.get_authenticated_user.return_value = UserModel(login="unknown-ai")
|
||||
pr = PullRequestModel(
|
||||
number=104,
|
||||
title="already reviewed PR",
|
||||
body="closes #42",
|
||||
user=UserModel(login="meeks-ai")
|
||||
user=UserModel(login="unknown-ai")
|
||||
)
|
||||
mock_client.get_pull_request.return_value = pr
|
||||
mock_client.get_pull_request_diff.return_value = "diff"
|
||||
@@ -222,29 +223,35 @@ def _make_comment(login: str, body: str) -> CommentModel:
|
||||
return CommentModel(id=1, body=body, user=user)
|
||||
|
||||
|
||||
def _make_dispatcher_for_reply_tests() -> AgentDispatcher:
|
||||
mock_client = MagicMock()
|
||||
mock_client.get_authenticated_user.return_value = UserModel(login="unknown-ai")
|
||||
return AgentDispatcher(client=mock_client, tools=MagicMock())
|
||||
|
||||
|
||||
def test_is_awaiting_reply_no_comments() -> None:
|
||||
dispatcher = AgentDispatcher(client=MagicMock(), tools=MagicMock())
|
||||
dispatcher = _make_dispatcher_for_reply_tests()
|
||||
assert dispatcher._is_awaiting_reply([]) is False
|
||||
|
||||
|
||||
def test_is_awaiting_reply_no_question() -> None:
|
||||
dispatcher = AgentDispatcher(client=MagicMock(), tools=MagicMock())
|
||||
comments = [_make_comment("meeks-ai", "I will fix this now.")]
|
||||
dispatcher = _make_dispatcher_for_reply_tests()
|
||||
comments = [_make_comment("unknown-ai", "I will fix this now.")]
|
||||
assert dispatcher._is_awaiting_reply(comments) is False
|
||||
|
||||
|
||||
def test_is_awaiting_reply_agent_question_no_human_reply() -> None:
|
||||
dispatcher = AgentDispatcher(client=MagicMock(), tools=MagicMock())
|
||||
dispatcher = _make_dispatcher_for_reply_tests()
|
||||
body = "Should I use approach A or B?\n<!-- agent:awaiting-reply -->"
|
||||
comments = [_make_comment("meeks-ai", body)]
|
||||
comments = [_make_comment("unknown-ai", body)]
|
||||
assert dispatcher._is_awaiting_reply(comments) is True
|
||||
|
||||
|
||||
def test_is_awaiting_reply_agent_question_human_replied() -> None:
|
||||
dispatcher = AgentDispatcher(client=MagicMock(), tools=MagicMock())
|
||||
dispatcher = _make_dispatcher_for_reply_tests()
|
||||
body = "Should I use approach A or B?\n<!-- agent:awaiting-reply -->"
|
||||
comments = [
|
||||
_make_comment("meeks-ai", body),
|
||||
_make_comment("unknown-ai", body),
|
||||
_make_comment("michael", "Use approach A please."),
|
||||
]
|
||||
assert dispatcher._is_awaiting_reply(comments) is False
|
||||
@@ -252,8 +259,8 @@ def test_is_awaiting_reply_agent_question_human_replied() -> None:
|
||||
|
||||
def test_is_awaiting_reply_no_marker_not_detected() -> None:
|
||||
"""Agent asked a question but forgot the marker — should NOT be skipped."""
|
||||
dispatcher = AgentDispatcher(client=MagicMock(), tools=MagicMock())
|
||||
comments = [_make_comment("meeks-ai", "Should I use approach A or B?")]
|
||||
dispatcher = _make_dispatcher_for_reply_tests()
|
||||
comments = [_make_comment("unknown-ai", "Should I use approach A or B?")]
|
||||
assert dispatcher._is_awaiting_reply(comments) is False
|
||||
|
||||
|
||||
@@ -264,7 +271,7 @@ async def test_dispatch_proposes_plan(mock_coord_class: MagicMock) -> None:
|
||||
|
||||
mock_client.list_repo_pull_requests.return_value = []
|
||||
mock_client.get_issue_comments.return_value = []
|
||||
mock_client.get_authenticated_user.return_value = UserModel(login="meeks-ai")
|
||||
mock_client.get_authenticated_user.return_value = UserModel(login="unknown-ai")
|
||||
|
||||
async def mock_decide(mission: str, planning_tools: list, coord_tools) -> str:
|
||||
coord_tools.propose_plan(plan="- Add endpoint\n<!-- agent:plan-proposal -->\n<!-- agent:awaiting-reply -->", issue_number=42)
|
||||
@@ -295,7 +302,7 @@ async def test_dispatch_answers_question(mock_coord_class: MagicMock) -> None:
|
||||
|
||||
mock_client.list_repo_pull_requests.return_value = []
|
||||
mock_client.get_issue_comments.return_value = []
|
||||
mock_client.get_authenticated_user.return_value = UserModel(login="meeks-ai")
|
||||
mock_client.get_authenticated_user.return_value = UserModel(login="unknown-ai")
|
||||
|
||||
async def mock_decide(mission: str, planning_tools: list, coord_tools) -> str:
|
||||
coord_tools.answer_question(answer="X works by doing Y.\n<!-- agent:question-response -->\n<!-- agent:awaiting-reply -->", issue_number=42)
|
||||
@@ -325,11 +332,11 @@ async def test_dispatch_closes_issue_on_satisfaction(mock_coord_class: MagicMock
|
||||
mock_tools: MagicMock = MagicMock(spec=GiteaTools)
|
||||
|
||||
mock_client.list_repo_pull_requests.return_value = []
|
||||
mock_client.get_authenticated_user.return_value = UserModel(login="meeks-ai")
|
||||
mock_client.get_authenticated_user.return_value = UserModel(login="unknown-ai")
|
||||
|
||||
# Human comments indicating satisfaction after our answer
|
||||
mock_client.get_issue_comments.return_value = [
|
||||
_make_comment("meeks-ai", "Here is the answer.\n<!-- agent:question-response -->\n<!-- agent:awaiting-reply -->"),
|
||||
_make_comment("unknown-ai", "Here is the answer.\n<!-- agent:question-response -->\n<!-- agent:awaiting-reply -->"),
|
||||
_make_comment("michael", "Yes, thanks! That makes sense.")
|
||||
]
|
||||
|
||||
@@ -364,9 +371,9 @@ async def test_dispatch_executes_approved_plan_and_creates_wip_pr(mock_coord_cla
|
||||
mock_tools: MagicMock = MagicMock(spec=GiteaTools)
|
||||
|
||||
mock_client.list_repo_pull_requests.return_value = []
|
||||
mock_client.get_authenticated_user.return_value = UserModel(login="meeks-ai")
|
||||
mock_client.get_authenticated_user.return_value = UserModel(login="unknown-ai")
|
||||
mock_client.get_issue_comments.return_value = [
|
||||
_make_comment("meeks-ai", "### Proposed Plan\n<!-- agent:plan-proposal -->\n<!-- agent:awaiting-reply -->"),
|
||||
_make_comment("unknown-ai", "### Proposed Plan\n<!-- agent:plan-proposal -->\n<!-- agent:awaiting-reply -->"),
|
||||
_make_comment("michael", "looks good, go ahead")
|
||||
]
|
||||
|
||||
@@ -414,7 +421,7 @@ async def test_dispatch_resumes_wip_pr(mock_coord_class: MagicMock, mock_coding_
|
||||
mock_client: MagicMock = MagicMock(spec=GiteaClient)
|
||||
mock_tools: MagicMock = MagicMock(spec=GiteaTools)
|
||||
|
||||
mock_client.get_authenticated_user.return_value = UserModel(login="meeks-ai")
|
||||
mock_client.get_authenticated_user.return_value = UserModel(login="unknown-ai")
|
||||
|
||||
# Existing WIP PR addressing issue #42
|
||||
wip_pr = PullRequestModel(
|
||||
@@ -427,7 +434,7 @@ async def test_dispatch_resumes_wip_pr(mock_coord_class: MagicMock, mock_coding_
|
||||
mock_client.get_pr_reviews.return_value = []
|
||||
|
||||
mock_client.get_issue_comments.return_value = [
|
||||
_make_comment("meeks-ai", "### Proposed Plan\n<!-- agent:plan-proposal -->\n<!-- agent:awaiting-reply -->"),
|
||||
_make_comment("unknown-ai", "### Proposed Plan\n<!-- agent:plan-proposal -->\n<!-- agent:awaiting-reply -->"),
|
||||
_make_comment("michael", "looks good, go ahead")
|
||||
]
|
||||
mock_client.get_pull_request_comments.return_value = []
|
||||
@@ -462,7 +469,7 @@ async def test_dispatch_skips_pr_if_not_requested_reviewer() -> None:
|
||||
mock_client: MagicMock = MagicMock(spec=GiteaClient)
|
||||
mock_tools: MagicMock = MagicMock(spec=GiteaTools)
|
||||
|
||||
mock_client.get_authenticated_user.return_value = UserModel(login="meeks-ai")
|
||||
mock_client.get_authenticated_user.return_value = UserModel(login="unknown-ai")
|
||||
|
||||
# PR authored by michael, requested reviewers is empty (agent not requested)
|
||||
pr_detail = PullRequestModel(
|
||||
@@ -511,7 +518,7 @@ async def test_dispatch_uses_coordinator_tool_calling(mock_coord_class: MagicMoc
|
||||
|
||||
mock_client.list_repo_pull_requests.return_value = []
|
||||
mock_client.get_issue_comments.return_value = []
|
||||
mock_client.get_authenticated_user.return_value = UserModel(login="meeks-ai")
|
||||
mock_client.get_authenticated_user.return_value = UserModel(login="unknown-ai")
|
||||
|
||||
# Mock agent invoking propose_plan tool
|
||||
async def mock_decide(mission: str, planning_tools: list, coord_tools) -> str:
|
||||
@@ -542,3 +549,68 @@ async def test_dispatch_uses_coordinator_tool_calling(mock_coord_class: MagicMoc
|
||||
)
|
||||
|
||||
|
||||
async def test_dispatcher_raises_type_error_for_invalid_task_info() -> None:
|
||||
mock_client: MagicMock = MagicMock(spec=GiteaClient)
|
||||
mock_tools: MagicMock = MagicMock(spec=GiteaTools)
|
||||
|
||||
# Mock return values for methods called prior to the isinstance check
|
||||
mock_client.list_repo_pull_requests.return_value = []
|
||||
mock_client.get_issue_comments.return_value = []
|
||||
mock_client.get_authenticated_user.return_value = UserModel(login="unknown-ai")
|
||||
|
||||
dispatcher = AgentDispatcher(client=mock_client, tools=mock_tools)
|
||||
|
||||
# 1. Test dispatch raises TypeError if task_info is not IssueModel for an issue task
|
||||
work_item_invalid_issue = WorkItem(
|
||||
repo_full_name="meeks/repo1",
|
||||
task_type="issue",
|
||||
task_number=42,
|
||||
task_info=PullRequestModel(number=42), # Invalid model type
|
||||
priority=0
|
||||
)
|
||||
with pytest.raises(TypeError, match="Expected task_info to be an IssueModel"):
|
||||
await dispatcher.dispatch("meeks/repo1", [work_item_invalid_issue])
|
||||
|
||||
# 2. Test _build_pr_mission raises TypeError if task_info is not PullRequestModel
|
||||
work_item_invalid_pr = WorkItem(
|
||||
repo_full_name="meeks/repo1",
|
||||
task_type="pr",
|
||||
task_number=42,
|
||||
task_info=IssueModel(number=42), # Invalid model type
|
||||
priority=0
|
||||
)
|
||||
with pytest.raises(TypeError, match="Expected task_info to be a PullRequestModel"):
|
||||
dispatcher._build_pr_mission(work_item_invalid_pr)
|
||||
|
||||
# 3. Test _build_issue_mission raises TypeError if task_info is not IssueModel
|
||||
with pytest.raises(TypeError, match="Expected task_info to be an IssueModel"):
|
||||
dispatcher._build_issue_mission(work_item_invalid_issue)
|
||||
|
||||
|
||||
async def test_dispatch_fails_if_no_authenticated_user() -> None:
|
||||
mock_client: MagicMock = MagicMock(spec=GiteaClient)
|
||||
mock_tools: MagicMock = MagicMock(spec=GiteaTools)
|
||||
|
||||
# Simulate get_authenticated_user returning None
|
||||
mock_client.get_authenticated_user.return_value = None
|
||||
|
||||
dispatcher = AgentDispatcher(client=mock_client, tools=mock_tools)
|
||||
work_item = WorkItem(
|
||||
repo_full_name="meeks/repo1",
|
||||
task_type="issue",
|
||||
task_number=42,
|
||||
task_info=IssueModel(number=42, title="add X", body=""),
|
||||
priority=0
|
||||
)
|
||||
|
||||
with pytest.raises(RuntimeError, match="No authenticated user found."):
|
||||
await dispatcher.dispatch("meeks/repo1", [work_item])
|
||||
|
||||
# Simulate get_authenticated_user raising an Exception
|
||||
mock_client.get_authenticated_user.side_effect = Exception("API error")
|
||||
with pytest.raises(RuntimeError, match="No authenticated user found."):
|
||||
await dispatcher.dispatch("meeks/repo1", [work_item])
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
from unittest.mock import MagicMock
|
||||
from gitea.client import GiteaClient
|
||||
from gitea.tools.gitea_tools import GiteaTools
|
||||
|
||||
|
||||
def test_gitea_tools_delegation() -> None:
|
||||
mock_client: MagicMock = MagicMock(spec=GiteaClient)
|
||||
gitea_tools: GiteaTools = GiteaTools(mock_client)
|
||||
|
||||
# 1. get_issue
|
||||
gitea_tools.get_issue("owner", "repo", 1)
|
||||
mock_client.get_issue.assert_called_once_with("owner", "repo", 1)
|
||||
|
||||
# 2. get_pull_request
|
||||
gitea_tools.get_pull_request("owner", "repo", 2)
|
||||
mock_client.get_pull_request.assert_called_once_with("owner", "repo", 2)
|
||||
|
||||
# 3. close_issue
|
||||
gitea_tools.close_issue("owner", "repo", 3)
|
||||
mock_client.close_issue.assert_called_once_with("owner", "repo", 3)
|
||||
|
||||
# 4. close_pull_request
|
||||
gitea_tools.close_pull_request("owner", "repo", 4)
|
||||
mock_client.close_pull_request.assert_called_once_with("owner", "repo", 4)
|
||||
|
||||
# 5. get_issue_comments
|
||||
gitea_tools.get_issue_comments("owner", "repo", 5)
|
||||
mock_client.get_issue_comments.assert_called_once_with("owner", "repo", 5)
|
||||
|
||||
# 6. get_pull_request_comments
|
||||
gitea_tools.get_pull_request_comments("owner", "repo", 6)
|
||||
mock_client.get_pull_request_comments.assert_called_once_with("owner", "repo", 6)
|
||||
|
||||
# 7. list_assigned_issues
|
||||
mock_client.list_all_user_repos.return_value = []
|
||||
gitea_tools.list_assigned_issues()
|
||||
mock_client.list_all_user_repos.assert_called()
|
||||
|
||||
# 8. list_assigned_pull_requests
|
||||
gitea_tools.list_assigned_pull_requests()
|
||||
mock_client.list_all_user_repos.assert_called()
|
||||
|
||||
# 9. list_issues
|
||||
gitea_tools.list_issues("owner", "repo")
|
||||
mock_client.list_repo_issues.assert_called_once_with("owner", "repo", "open")
|
||||
|
||||
# 10. list_pull_requests
|
||||
gitea_tools.list_pull_requests("owner", "repo")
|
||||
mock_client.list_repo_pull_requests.assert_called_once_with("owner", "repo", "open")
|
||||
|
||||
# 11. get_file_content
|
||||
gitea_tools.get_file_content("owner", "repo", "path")
|
||||
mock_client.get_file_content.assert_called_with("owner", "repo", "path")
|
||||
|
||||
# 12. create_pull_request
|
||||
gitea_tools.create_pull_request("owner", "repo", "head", "base", "title", "desc")
|
||||
mock_client.create_pr_via_tea.assert_called_once_with("owner", "repo", "title", "desc", "head", "base")
|
||||
|
||||
# 13. create_issue
|
||||
gitea_tools.create_issue("owner", "repo", "title", "body")
|
||||
mock_client.create_issue.assert_called_once_with("owner", "repo", "title", "body", None, None)
|
||||
|
||||
# 14. create_branch
|
||||
gitea_tools.create_branch("owner", "repo", "branch", "sha")
|
||||
mock_client.create_ref.assert_called_once_with("owner", "repo", "branch", "sha")
|
||||
|
||||
# 15. commit_file
|
||||
gitea_tools.commit_file("owner", "repo", "path", "msg", "content", "branch")
|
||||
mock_client.update_file.assert_called_with("owner", "repo", "path", "msg", "content", "branch")
|
||||
|
||||
# 16. add_label_to_issue
|
||||
gitea_tools.add_label_to_issue("owner", "repo", 1, "bug")
|
||||
mock_client.add_label.assert_called_with("owner", "repo", 1, "bug")
|
||||
|
||||
# 17. add_label_to_pr
|
||||
gitea_tools.add_label_to_pr("owner", "repo", 1, "bug")
|
||||
mock_client.add_label_pr.assert_called_once_with("owner", "repo", 1, "bug")
|
||||
|
||||
# 18. add_comment_to_issue
|
||||
gitea_tools.add_comment_to_issue("owner", "repo", 1, "body")
|
||||
mock_client.add_comment.assert_called_with("owner", "repo", 1, "body")
|
||||
|
||||
# 19. get_pull_request_diff
|
||||
gitea_tools.get_pull_request_diff("owner", "repo", 1)
|
||||
mock_client.get_pull_request_diff.assert_called_once_with("owner", "repo", 1)
|
||||
|
||||
# 20. get_pull_request_patch
|
||||
gitea_tools.get_pull_request_patch("owner", "repo", 1)
|
||||
mock_client.get_pull_request_patch.assert_called_once_with("owner", "repo", 1)
|
||||
|
||||
# 21. approve_pull_request
|
||||
gitea_tools.approve_pull_request("owner", "repo", 1, "good")
|
||||
mock_client.approve_pr.assert_called_once_with("owner", "repo", 1, "good")
|
||||
|
||||
# 22. request_changes
|
||||
gitea_tools.request_changes("owner", "repo", 1, "bad")
|
||||
mock_client.request_changes_pr.assert_called_once_with("owner", "repo", 1, "bad")
|
||||
|
||||
# 23. add_comment
|
||||
gitea_tools.add_comment("owner", "repo", 1, "body")
|
||||
mock_client.add_comment.assert_called_with("owner", "repo", 1, "body")
|
||||
|
||||
# 24. add_label
|
||||
gitea_tools.add_label("owner", "repo", 1, "bug")
|
||||
mock_client.add_label.assert_called_with("owner", "repo", 1, "bug")
|
||||
|
||||
# 25. get_file_content_with_ref
|
||||
gitea_tools.get_file_content_with_ref("owner", "repo", "path", "ref")
|
||||
mock_client.get_file_content.assert_called_with("owner", "repo", "path", "ref")
|
||||
|
||||
# 26. update_file
|
||||
gitea_tools.update_file("owner", "repo", "path", "msg", "content", "branch")
|
||||
mock_client.update_file.assert_called_with("owner", "repo", "path", "msg", "content", "branch")
|
||||
@@ -127,9 +127,13 @@ def test_create_issue_success() -> None:
|
||||
mock_client.create_issue.return_value = issue
|
||||
|
||||
issue_tools: IssueTools = IssueTools(mock_client)
|
||||
res: str = issue_tools.create_issue("owner", "repo", "Title", "Body", ["label1"], ["assignee1"])
|
||||
res: str = issue_tools.create_issue(
|
||||
"owner", "repo", "Title", "Body", ["label1"], ["assignee1"]
|
||||
)
|
||||
assert res == "Issue #2 created successfully in owner/repo."
|
||||
mock_client.create_issue.assert_called_once_with("owner", "repo", "Title", "Body", ["label1"], ["assignee1"])
|
||||
mock_client.create_issue.assert_called_once_with(
|
||||
"owner", "repo", "Title", "Body", ["label1"], ["assignee1"]
|
||||
)
|
||||
|
||||
|
||||
def test_create_issue_failure() -> None:
|
||||
@@ -175,39 +179,3 @@ def test_add_comment_to_issue_failure() -> None:
|
||||
issue_tools: IssueTools = IssueTools(mock_client)
|
||||
res: str = issue_tools.add_comment_to_issue("owner", "repo", 1, "body")
|
||||
assert "Error adding comment to issue #1: API Error" in res
|
||||
|
||||
|
||||
def test_add_comment_success() -> None:
|
||||
mock_client: MagicMock = MagicMock(spec=GiteaClient)
|
||||
mock_client.add_comment.return_value = CommentModel(id=1)
|
||||
|
||||
issue_tools: IssueTools = IssueTools(mock_client)
|
||||
res: str = issue_tools.add_comment("owner", "repo", 1, "body")
|
||||
assert res == "Comment added to #1."
|
||||
|
||||
|
||||
def test_add_comment_failure() -> None:
|
||||
mock_client: MagicMock = MagicMock(spec=GiteaClient)
|
||||
mock_client.add_comment.side_effect = Exception("API Error")
|
||||
|
||||
issue_tools: IssueTools = IssueTools(mock_client)
|
||||
res: str = issue_tools.add_comment("owner", "repo", 1, "body")
|
||||
assert "Error adding comment: API Error" in res
|
||||
|
||||
|
||||
def test_add_label_success() -> None:
|
||||
mock_client: MagicMock = MagicMock(spec=GiteaClient)
|
||||
mock_client.add_label.return_value = LabelModel(name="bug")
|
||||
|
||||
issue_tools: IssueTools = IssueTools(mock_client)
|
||||
res: str = issue_tools.add_label("owner", "repo", 1, "bug")
|
||||
assert res == "Label 'bug' added to #1."
|
||||
|
||||
|
||||
def test_add_label_failure() -> None:
|
||||
mock_client: MagicMock = MagicMock(spec=GiteaClient)
|
||||
mock_client.add_label.side_effect = Exception("API Error")
|
||||
|
||||
issue_tools: IssueTools = IssueTools(mock_client)
|
||||
res: str = issue_tools.add_label("owner", "repo", 1, "bug")
|
||||
assert "Error adding label: API Error" in res
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
from unittest.mock import MagicMock, AsyncMock, patch
|
||||
import pytest
|
||||
from main import main
|
||||
|
||||
pytestmark = pytest.mark.anyio
|
||||
|
||||
|
||||
@patch("main.load_dotenv")
|
||||
@patch("main.os.chdir")
|
||||
@patch("main.GiteaClient")
|
||||
@patch("main.GiteaTools")
|
||||
@patch("main.AgentOrchestrator")
|
||||
async def test_main_startup_success(
|
||||
mock_orchestrator_class: MagicMock,
|
||||
mock_tools_class: MagicMock,
|
||||
mock_client_class: MagicMock,
|
||||
mock_chdir: MagicMock,
|
||||
mock_load_dotenv: MagicMock
|
||||
) -> None:
|
||||
mock_client = MagicMock()
|
||||
mock_client_class.return_value = mock_client
|
||||
mock_user = MagicMock()
|
||||
mock_user.login = "agent-test"
|
||||
mock_client.get_authenticated_user.return_value = mock_user
|
||||
|
||||
mock_orchestrator = MagicMock()
|
||||
mock_orchestrator.poll_and_dispatch = AsyncMock(side_effect=KeyboardInterrupt())
|
||||
mock_orchestrator_class.return_value = mock_orchestrator
|
||||
|
||||
# Run main; it should exit gracefully on KeyboardInterrupt
|
||||
await main()
|
||||
|
||||
mock_client.get_authenticated_user.assert_called_once()
|
||||
mock_orchestrator.poll_and_dispatch.assert_called_once()
|
||||
|
||||
|
||||
@patch("main.load_dotenv")
|
||||
@patch("main.os.chdir")
|
||||
@patch("main.GiteaClient")
|
||||
@patch("main.GiteaTools")
|
||||
@patch("main.AgentOrchestrator")
|
||||
async def test_main_startup_fails_no_authenticated_user(
|
||||
mock_orchestrator_class: MagicMock,
|
||||
mock_tools_class: MagicMock,
|
||||
mock_client_class: MagicMock,
|
||||
mock_chdir: MagicMock,
|
||||
mock_load_dotenv: MagicMock
|
||||
) -> None:
|
||||
mock_client = MagicMock()
|
||||
mock_client_class.return_value = mock_client
|
||||
# Simulate no user returned
|
||||
mock_client.get_authenticated_user.return_value = None
|
||||
|
||||
with pytest.raises(SystemExit) as exc_info:
|
||||
await main()
|
||||
|
||||
assert exc_info.value.code == 1
|
||||
mock_orchestrator_class.assert_not_called()
|
||||
@@ -21,9 +21,9 @@ def temp_state_file(tmp_path: Path) -> Path:
|
||||
@patch("core.orchestrator.AgentOrchestrator._get_state_file_path")
|
||||
@patch("core.orchestrator.AgentDispatcher")
|
||||
@patch("core.orchestrator.WorkspaceManager")
|
||||
@patch("core.orchestrator.AgentFactory")
|
||||
@patch("core.orchestrator.NotificationReaderAgent")
|
||||
async def test_poll_and_dispatch_no_notifications(
|
||||
mock_factory: MagicMock,
|
||||
mock_notification_reader_class: MagicMock,
|
||||
mock_workspace_class: MagicMock,
|
||||
mock_dispatcher_class: MagicMock,
|
||||
mock_get_path: MagicMock,
|
||||
@@ -46,9 +46,9 @@ async def test_poll_and_dispatch_no_notifications(
|
||||
@patch("core.orchestrator.AgentOrchestrator._get_state_file_path")
|
||||
@patch("core.orchestrator.AgentDispatcher")
|
||||
@patch("core.orchestrator.WorkspaceManager")
|
||||
@patch("core.orchestrator.AgentFactory")
|
||||
@patch("core.orchestrator.NotificationReaderAgent")
|
||||
async def test_poll_and_dispatch_with_notifications(
|
||||
mock_factory: MagicMock,
|
||||
mock_notification_reader_class: MagicMock,
|
||||
mock_workspace_class: MagicMock,
|
||||
mock_dispatcher_class: MagicMock,
|
||||
mock_get_path: MagicMock,
|
||||
@@ -66,7 +66,7 @@ async def test_poll_and_dispatch_with_notifications(
|
||||
notification_tools.skip_notification("Unrelated")
|
||||
return "Decided"
|
||||
mock_reader.decide_notification = AsyncMock(side_effect=mock_decide_notification)
|
||||
mock_factory.create_notification_reader_agent.return_value = mock_reader
|
||||
mock_notification_reader_class.return_value = mock_reader
|
||||
mock_client = MagicMock(spec=GiteaClient)
|
||||
mock_tools = MagicMock(spec=GiteaTools)
|
||||
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import threading
|
||||
from core.queue import WorkQueue, WorkItem
|
||||
from gitea.models import IssueModel
|
||||
|
||||
|
||||
def test_work_queue_basic_operations() -> None:
|
||||
queue: WorkQueue = WorkQueue()
|
||||
assert queue.is_empty
|
||||
assert len(queue) == 0
|
||||
assert queue.get_next_repo() is None
|
||||
|
||||
item1 = WorkItem(
|
||||
repo_full_name="meeks/repo1",
|
||||
task_type="issue",
|
||||
task_number=1,
|
||||
task_info=IssueModel(number=1),
|
||||
)
|
||||
item2 = WorkItem(
|
||||
repo_full_name="meeks/repo1",
|
||||
task_type="issue",
|
||||
task_number=2,
|
||||
task_info=IssueModel(number=2),
|
||||
)
|
||||
item3 = WorkItem(
|
||||
repo_full_name="meeks/repo2",
|
||||
task_type="issue",
|
||||
task_number=3,
|
||||
task_info=IssueModel(number=3),
|
||||
)
|
||||
|
||||
queue.enqueue(item1)
|
||||
assert not queue.is_empty
|
||||
assert len(queue) == 1
|
||||
assert queue.get_next_repo() == "meeks/repo1"
|
||||
|
||||
queue.enqueue_batch([item2, item3])
|
||||
assert len(queue) == 3
|
||||
|
||||
# get_repo_work
|
||||
repo1_work = queue.get_repo_work("meeks/repo1")
|
||||
assert len(repo1_work) == 2
|
||||
assert repo1_work[0].task_number == 1
|
||||
assert repo1_work[1].task_number == 2
|
||||
|
||||
# remove_repo_work
|
||||
queue.remove_repo_work("meeks/repo1")
|
||||
assert len(queue) == 1
|
||||
assert queue.get_next_repo() == "meeks/repo2"
|
||||
|
||||
queue.remove_repo_work("meeks/repo2")
|
||||
assert queue.is_empty
|
||||
assert len(queue) == 0
|
||||
assert queue.get_next_repo() is None
|
||||
|
||||
|
||||
def test_work_queue_thread_safety() -> None:
|
||||
queue: WorkQueue = WorkQueue()
|
||||
num_threads: int = 10
|
||||
items_per_thread: int = 100
|
||||
barrier = threading.Barrier(num_threads)
|
||||
|
||||
def worker(thread_idx: int) -> None:
|
||||
barrier.wait() # synchronize start
|
||||
for i in range(items_per_thread):
|
||||
item = WorkItem(
|
||||
repo_full_name=f"meeks/repo_{thread_idx}",
|
||||
task_type="issue",
|
||||
task_number=i,
|
||||
task_info=IssueModel(number=i),
|
||||
)
|
||||
queue.enqueue(item)
|
||||
|
||||
threads: list[threading.Thread] = []
|
||||
for idx in range(num_threads):
|
||||
t = threading.Thread(target=worker, args=(idx,))
|
||||
threads.append(t)
|
||||
t.start()
|
||||
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
# Verify that all items are enqueued
|
||||
assert len(queue) == num_threads * items_per_thread
|
||||
|
||||
# Concurrently remove repo work
|
||||
barrier_remove = threading.Barrier(num_threads)
|
||||
|
||||
def remover(thread_idx: int) -> None:
|
||||
barrier_remove.wait()
|
||||
queue.remove_repo_work(f"meeks/repo_{thread_idx}")
|
||||
|
||||
remove_threads: list[threading.Thread] = []
|
||||
for idx in range(num_threads):
|
||||
t = threading.Thread(target=remover, args=(idx,))
|
||||
remove_threads.append(t)
|
||||
t.start()
|
||||
|
||||
for t in remove_threads:
|
||||
t.join()
|
||||
|
||||
assert queue.is_empty
|
||||
assert len(queue) == 0
|
||||
@@ -140,6 +140,12 @@ class TestFormatResults:
|
||||
|
||||
|
||||
class TestSearchSearxng:
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_searxng_url(self) -> "Generator[None, None, None]":
|
||||
from typing import Generator
|
||||
with patch("gitea.tools.research_tools._SEARXNG_URL", "http://localhost"):
|
||||
yield
|
||||
|
||||
def _make_searxng_response(self, results: list[dict]) -> MagicMock:
|
||||
mock_resp = MagicMock()
|
||||
mock_resp.json.return_value = {"results": results}
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock, patch
|
||||
import pytest
|
||||
|
||||
from gitea.workspace import WorkspaceManager
|
||||
|
||||
|
||||
@patch("gitea.workspace.subprocess.run")
|
||||
@patch("gitea.workspace.GiteaClient")
|
||||
def test_workspace_manager_configure_repo_user(
|
||||
mock_client_class: MagicMock,
|
||||
mock_run: MagicMock
|
||||
) -> None:
|
||||
mock_client = MagicMock()
|
||||
mock_client_class.return_value = mock_client
|
||||
mock_user = MagicMock()
|
||||
mock_user.full_name = "Agent Tester"
|
||||
mock_user.login = "agent-test"
|
||||
mock_user.email = "agent-test@example.com"
|
||||
mock_client.get_authenticated_user.return_value = mock_user
|
||||
|
||||
workspace = WorkspaceManager()
|
||||
repo_path = Path("/tmp/mock-repo")
|
||||
|
||||
workspace._configure_repo_user(repo_path)
|
||||
|
||||
assert mock_run.call_count >= 3
|
||||
calls = [c[0][0] for c in mock_run.call_args_list]
|
||||
|
||||
assert any("http.extraHeader" in call for call in calls)
|
||||
assert any("user.name" in call for call in calls)
|
||||
assert any("user.email" in call for call in calls)
|
||||
|
||||
|
||||
@patch("gitea.workspace.subprocess.run")
|
||||
@patch("gitea.workspace.GiteaClient")
|
||||
def test_workspace_manager_clone_repo(
|
||||
mock_client_class: MagicMock,
|
||||
mock_run: MagicMock
|
||||
) -> None:
|
||||
mock_client = MagicMock()
|
||||
mock_client_class.return_value = mock_client
|
||||
mock_user = MagicMock()
|
||||
mock_user.full_name = "Agent Tester"
|
||||
mock_user.login = "agent-test"
|
||||
mock_user.email = "agent-test@example.com"
|
||||
mock_client.get_authenticated_user.return_value = mock_user
|
||||
|
||||
workspace = WorkspaceManager()
|
||||
|
||||
with patch.object(workspace, "_configure_repo_user") as mock_configure:
|
||||
with patch.object(workspace, "get_repo_path") as mock_get_path:
|
||||
mock_repo_path = MagicMock(spec=Path)
|
||||
mock_repo_path.exists.return_value = False
|
||||
mock_get_path.return_value = mock_repo_path
|
||||
|
||||
workspace.clone_repo("meeks/repo1")
|
||||
|
||||
mock_run.assert_called_once()
|
||||
args = mock_run.call_args[0][0]
|
||||
assert "clone" in args
|
||||
assert any("http.extraHeader=Authorization: Basic" in arg for arg in args)
|
||||
mock_configure.assert_called_once_with(mock_repo_path)
|
||||
|
||||
|
||||
@patch("gitea.workspace.GiteaClient")
|
||||
def test_workspace_manager_fails_if_no_authenticated_user(
|
||||
mock_client_class: MagicMock
|
||||
) -> None:
|
||||
mock_client = MagicMock()
|
||||
mock_client_class.return_value = mock_client
|
||||
mock_client.get_authenticated_user.return_value = None
|
||||
|
||||
workspace = WorkspaceManager()
|
||||
with pytest.raises(RuntimeError, match="No authenticated user found."):
|
||||
workspace.clone_repo("meeks/repo1")
|
||||
|
||||
with pytest.raises(RuntimeError, match="No authenticated user found."):
|
||||
workspace._configure_repo_user(Path("/tmp/mock-repo"))
|
||||
|
||||
|
||||
@patch("gitea.workspace.GiteaClient")
|
||||
def test_workspace_manager_fails_if_authenticated_user_has_no_login(
|
||||
mock_client_class: MagicMock
|
||||
) -> None:
|
||||
mock_client = MagicMock()
|
||||
mock_client_class.return_value = mock_client
|
||||
mock_user = MagicMock()
|
||||
mock_user.login = ""
|
||||
mock_client.get_authenticated_user.return_value = mock_user
|
||||
|
||||
workspace = WorkspaceManager()
|
||||
with pytest.raises(RuntimeError, match="No authenticated user found."):
|
||||
workspace.clone_repo("meeks/repo1")
|
||||
|
||||
with pytest.raises(RuntimeError, match="No authenticated user found."):
|
||||
workspace._configure_repo_user(Path("/tmp/mock-repo"))
|
||||
|
||||
|
||||
@patch("gitea.workspace.subprocess.run")
|
||||
@patch("gitea.workspace.GiteaClient")
|
||||
def test_workspace_manager_sanitize_repo_no_changes(
|
||||
mock_client_class: MagicMock,
|
||||
mock_run: MagicMock
|
||||
) -> None:
|
||||
# Setup Gitea client mock
|
||||
mock_client = MagicMock()
|
||||
mock_client_class.return_value = mock_client
|
||||
mock_user = MagicMock()
|
||||
mock_user.full_name = "Agent Tester"
|
||||
mock_user.login = "agent-test"
|
||||
mock_user.email = "agent-test@example.com"
|
||||
mock_client.get_authenticated_user.return_value = mock_user
|
||||
|
||||
# Mock subprocess.run for status check and others
|
||||
def mock_run_side_effect(args: list[str], **kwargs: Any) -> MagicMock:
|
||||
result = MagicMock()
|
||||
result.returncode = 0
|
||||
if "status" in args:
|
||||
result.stdout = ""
|
||||
else:
|
||||
result.stdout = "some output"
|
||||
return result
|
||||
|
||||
mock_run.side_effect = mock_run_side_effect
|
||||
|
||||
workspace = WorkspaceManager()
|
||||
repo_path = Path("/tmp/mock-repo")
|
||||
|
||||
workspace.sanitize_repo("meeks/repo1", repo_path)
|
||||
|
||||
# Verify that stash was not called
|
||||
stash_calls = [call for call in mock_run.call_args_list if "stash" in call[0][0]]
|
||||
assert len(stash_calls) == 0
|
||||
|
||||
# Verify other expected git calls
|
||||
reset_calls = [call for call in mock_run.call_args_list if "reset" in call[0][0]]
|
||||
clean_calls = [call for call in mock_run.call_args_list if "clean" in call[0][0]]
|
||||
assert len(reset_calls) > 0
|
||||
assert len(clean_calls) > 0
|
||||
|
||||
|
||||
@patch("gitea.workspace.subprocess.run")
|
||||
@patch("gitea.workspace.GiteaClient")
|
||||
def test_workspace_manager_sanitize_repo_with_changes(
|
||||
mock_client_class: MagicMock,
|
||||
mock_run: MagicMock
|
||||
) -> None:
|
||||
# Setup Gitea client mock
|
||||
mock_client = MagicMock()
|
||||
mock_client_class.return_value = mock_client
|
||||
mock_user = MagicMock()
|
||||
mock_user.full_name = "Agent Tester"
|
||||
mock_user.login = "agent-test"
|
||||
mock_user.email = "agent-test@example.com"
|
||||
mock_client.get_authenticated_user.return_value = mock_user
|
||||
|
||||
# Mock subprocess.run to show modified files
|
||||
def mock_run_side_effect(args: list[str], **kwargs: Any) -> MagicMock:
|
||||
result = MagicMock()
|
||||
result.returncode = 0
|
||||
if "status" in args:
|
||||
result.stdout = " M file.py\n?? untracked.py\n"
|
||||
else:
|
||||
result.stdout = ""
|
||||
return result
|
||||
|
||||
mock_run.side_effect = mock_run_side_effect
|
||||
|
||||
workspace = WorkspaceManager()
|
||||
repo_path = Path("/tmp/mock-repo")
|
||||
|
||||
workspace.sanitize_repo("meeks/repo1", repo_path)
|
||||
|
||||
# Verify stash push was called
|
||||
stash_calls = [call for call in mock_run.call_args_list if "stash" in call[0][0]]
|
||||
assert len(stash_calls) == 1
|
||||
assert "push" in stash_calls[0][0][0]
|
||||
assert "-u" in stash_calls[0][0][0]
|
||||
|
||||
|
||||
@patch("gitea.workspace.subprocess.run")
|
||||
@patch("gitea.workspace.GiteaClient")
|
||||
def test_workspace_manager_sanitize_repo_fails(
|
||||
mock_client_class: MagicMock,
|
||||
mock_run: MagicMock
|
||||
) -> None:
|
||||
# Setup Gitea client mock
|
||||
mock_client = MagicMock()
|
||||
mock_client_class.return_value = mock_client
|
||||
mock_user = MagicMock()
|
||||
mock_user.full_name = "Agent Tester"
|
||||
mock_user.login = "agent-test"
|
||||
mock_user.email = "agent-test@example.com"
|
||||
mock_client.get_authenticated_user.return_value = mock_user
|
||||
|
||||
# Mock remote set-url to fail
|
||||
import subprocess
|
||||
mock_run.side_effect = subprocess.CalledProcessError(1, "git remote set-url")
|
||||
|
||||
workspace = WorkspaceManager()
|
||||
repo_path = Path("/tmp/mock-repo")
|
||||
|
||||
with pytest.raises(RuntimeError, match="Failed to sanitize repository"):
|
||||
workspace.sanitize_repo("meeks/repo1", repo_path)
|
||||
Reference in New Issue
Block a user