Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 37 additions & 19 deletions pr_agent/servers/github_action_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,29 +57,46 @@ def _inject_artifact_context():
artifact_text = load_artifact()
if not artifact_text:
return
target_tools = get_settings().get(
"ARTIFACTS.TARGET_TOOLS",
["pr_reviewer", "pr_description", "pr_code_suggestions"]
)
if isinstance(target_tools, str):
target_tools = [t.strip() for t in target_tools.split(",") if t.strip()]
target_tools = {str(t).lower() for t in target_tools}
separator = "\n======\n\n"
for key in get_settings():
setting = get_settings().get(key)
if str(type(setting)) == "<class 'dynaconf.utils.boxing.DynaBox'>":
if key.lower() in target_tools and hasattr(setting, 'extra_instructions'):
extra_instructions = str(setting.extra_instructions or "")
if artifact_text not in extra_instructions:
setting.extra_instructions = (
extra_instructions + separator + artifact_text
if extra_instructions else artifact_text
)
get_logger().info(f"Injected artifact context into tools: {target_tools}")
_append_tool_context(artifact_text)
get_logger().info("Injected artifact context into tools")
except (OSError, ValueError, TypeError) as e:
get_logger().warning(f"github action: failed to process artifacts: {e}", exc_info=True)


def _append_tool_context(text: str) -> None:
"""Append a labelled block to the extra_instructions of each artifact target tool."""
target_tools = get_settings().get(
"ARTIFACTS.TARGET_TOOLS",
["pr_reviewer", "pr_description", "pr_code_suggestions"],
)
if isinstance(target_tools, str):
target_tools = [t.strip() for t in target_tools.split(",") if t.strip()]
target_tools = {str(t).lower() for t in target_tools}
for key in get_settings():
setting = get_settings().get(key)
if str(type(setting)) == "<class 'dynaconf.utils.boxing.DynaBox'>":
if key.lower() in target_tools and hasattr(setting, "extra_instructions"):
existing = str(setting.extra_instructions or "")
if text not in existing:
setting.extra_instructions = (
existing + "\n======\n\n" + text if existing else text
)


def _inject_ci_conclusion(conclusion: str) -> None:
"""Tell the model how the workflow that triggered this run finished."""
if not conclusion:
return
_append_tool_context(
"CI status\n"
"=====\n"
f"The workflow run that triggered this review concluded: {conclusion}.\n"
"=====\n"
"If the conclusion is not 'success', the change has not passed CI. "
"Say so in your output rather than implying the change is clean."
)


async def run_action():
# Get environment variables
GITHUB_EVENT_NAME = os.environ.get('GITHUB_EVENT_NAME')
Expand Down Expand Up @@ -316,6 +333,7 @@ async def run_action():

# Inject artifact context after repo settings are applied for workflow_run
_inject_artifact_context()
_inject_ci_conclusion(workflow_run.get("conclusion"))

auto_review = get_setting_or_env("GITHUB_ACTION.AUTO_REVIEW", None)
if auto_review is None:
Expand Down
84 changes: 77 additions & 7 deletions tests/unittest/test_github_action_runner_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,18 +364,20 @@ async def test_issue_comment_from_user_is_processed(monkeypatch, tmp_path, resto
assert handled == [("https://api.github.com/repos/org/repo/pulls/1", "/review")]


def _write_workflow_run_event(tmp_path, originating_event="pull_request", pull_requests=None):
def _write_workflow_run_event(tmp_path, originating_event="pull_request", pull_requests=None, conclusion="success"):
if pull_requests is None:
pull_requests = [{"url": "https://api.github.com/repos/org/repo/pulls/42", "number": 42}]
workflow_run = {
"id": 9999,
"event": originating_event,
"pull_requests": pull_requests,
}
if conclusion is not None:
workflow_run["conclusion"] = conclusion
event_path = tmp_path / "event.json"
event_path.write_text(json.dumps({
"action": "completed",
"workflow_run": {
"id": 9999,
"event": originating_event,
"conclusion": "success",
"pull_requests": pull_requests,
},
"workflow_run": workflow_run,
}))
return event_path

Expand Down Expand Up @@ -433,6 +435,74 @@ def fake_get_setting_or_env(key, default=None):
]


@pytest.mark.asyncio
async def test_workflow_run_injects_ci_conclusion(monkeypatch, tmp_path, restore_github_settings):
"""The workflow_run handler must pass the triggering workflow's conclusion to the tools."""
runs = []
_patch_workflow_run_deps(monkeypatch, runs)
monkeypatch.setenv("GITHUB_EVENT_NAME", "workflow_run")
monkeypatch.setenv(
"GITHUB_EVENT_PATH", str(_write_workflow_run_event(tmp_path, conclusion="failure"))
)
monkeypatch.setenv("GITHUB_TOKEN", "token")

def fake_get_setting_or_env(key, default=None):
values = {
"GITHUB_ACTION.AUTO_DESCRIBE": False,
"GITHUB_ACTION.AUTO_REVIEW": True,
"GITHUB_ACTION.AUTO_IMPROVE": False,
"GITHUB_ACTION_CONFIG.ENABLE_OUTPUT": True,
}
return values.get(key, default)

monkeypatch.setattr(github_action_runner, "get_setting_or_env", fake_get_setting_or_env)

await github_action_runner.run_action()

assert "concluded: failure" in str(get_settings().pr_reviewer.extra_instructions)


@pytest.mark.asyncio
async def test_workflow_run_without_conclusion_injects_nothing(monkeypatch, tmp_path, restore_github_settings):
"""A payload without a conclusion key must not append any CI context."""
settings = get_settings()
saved = {}
try:
for key in ("pr_reviewer", "pr_description", "pr_code_suggestions"):
setting = settings.get(key)
if setting is not None and hasattr(setting, "extra_instructions"):
saved[key] = setting.extra_instructions
setting.extra_instructions = None

runs = []
_patch_workflow_run_deps(monkeypatch, runs)
monkeypatch.setenv("GITHUB_EVENT_NAME", "workflow_run")
monkeypatch.setenv(
"GITHUB_EVENT_PATH", str(_write_workflow_run_event(tmp_path, conclusion=None))
)
monkeypatch.setenv("GITHUB_TOKEN", "token")

def fake_get_setting_or_env(key, default=None):
values = {
"GITHUB_ACTION.AUTO_DESCRIBE": False,
"GITHUB_ACTION.AUTO_REVIEW": True,
"GITHUB_ACTION.AUTO_IMPROVE": False,
"GITHUB_ACTION_CONFIG.ENABLE_OUTPUT": True,
}
return values.get(key, default)

monkeypatch.setattr(github_action_runner, "get_setting_or_env", fake_get_setting_or_env)

await github_action_runner.run_action()

assert "CI status" not in str(get_settings().pr_reviewer.extra_instructions)
finally:
for key, value in saved.items():
setting = settings.get(key)
if setting is not None and hasattr(setting, "extra_instructions"):
setting.extra_instructions = value


@pytest.mark.asyncio
async def test_workflow_run_skips_non_pull_request_origin(monkeypatch, tmp_path, restore_github_settings):
runs = []
Expand Down
Loading