Spaces:
Running
Running
File size: 6,327 Bytes
4147729 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | from __future__ import annotations
import time
import logging
import os
from pathlib import Path
from backend.integrations.llm_factory import create_llm
from nodes.finding_quality import calibrate_findings
from nodes.review_runtime import changed_context, invoke_review, stage_result, reviewer_timeout
from pydantic import BaseModel, Field
from backend.state import Finding, OpenCodeReviewState
# This module contains a workflow node whose name starts with ``test_``.
# Prevent pytest from treating that production function as a test case.
__test__ = False
logger = logging.getLogger(__name__)
MAX_CONTEXT_CHARS = 6_000
MAX_FILE_CONTENT_CHARS = 4_000
# Prompt version β tied to the file on disk
PROMPT_VERSION = "v1"
PROMPT_FILE = Path(__file__).resolve().parent.parent / "prompts" / f"test_coverage_{PROMPT_VERSION}.txt"
# βββ Load prompt from file ββββββββββββββββββββββββββββββββββββββββββββββββββ
def _load_prompt() -> str:
"""Load the system prompt from the versioned prompt file."""
try:
return PROMPT_FILE.read_text(encoding="utf-8")
except FileNotFoundError:
logger.warning("Prompt file %s not found β using fallback", PROMPT_FILE)
return (
"You are a code reviewer focused on test coverage. "
"Analyse the PR diff and determine whether the changed logic "
"has adequate test coverage. Return a list of findings."
)
SYSTEM_PROMPT = _load_prompt()
# βββ Wrapper schema ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class TestCoverageReview(BaseModel):
"""Test-coverage gaps found during code review."""
findings: list[Finding] = Field(
default_factory=list,
description="Test-coverage issues found in the PR diff.",
)
# βββ Prompt builder βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _build_prompt(state: OpenCodeReviewState) -> str:
lines: list[str] = []
lines.append("## Diff\n```diff")
lines.append(state.diff or "")
lines.append("```\n")
if state.changed_files:
lines.append("## Changed files\n")
for cf in state.changed_files:
lines.append(f"### {cf.path} ({cf.status})")
content = changed_context(cf, state.review_mode)
if len(content) > MAX_FILE_CONTENT_CHARS:
content = content[:MAX_FILE_CONTENT_CHARS] + "\n⦠(truncated)"
lines.append(f"```\n{content}\n```\n")
if state.context_chunks:
lines.append("## Retrieved context\n")
ctx_chars = 0
for chunk in state.context_chunks:
snippet = chunk.content
if ctx_chars + len(snippet) > MAX_CONTEXT_CHARS:
remaining = MAX_CONTEXT_CHARS - ctx_chars
if remaining > 200:
lines.append(f"> {snippet[:remaining]}β¦ (truncated)")
break
prefix = "Past PR" if chunk.source == "past_pr" else chunk.file_path
lines.append(f"> [{prefix}]: {snippet}")
ctx_chars += len(snippet)
return "\n".join(lines)
# βββ Node ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def test_coverage_reviewer_node(state: OpenCodeReviewState) -> dict:
started = time.monotonic()
if not state.diff:
logger.info("No diff to review β skipping test-coverage review")
return {}
# Fast mode avoids a test specialist for documentation-only changes.
# Security and correctness still run; executable/config/unknown files
# always retain all reviewers, as does Thorough mode.
if state.review_mode == 'fast' and state.changed_files and all(
cf.path.lower().endswith(('.md', '.rst', '.txt')) for cf in state.changed_files
):
return {'review_stages': [{'reviewer': 'test_coverage', 'status': 'skipped',
'reason': 'Fast mode: documentation-only changes', 'duration_seconds': 0.0, 'model': ''}]}
try:
llm = create_llm(endpoint=state.endpoint or None, timeout=reviewer_timeout(state.review_mode), **({"max_tokens": 1200} if state.review_mode == "fast" else {}))
except ValueError as exc:
logger.warning("LLM unavailable β skipping test-coverage review: %s", exc)
return {"review_stages": [stage_result("test_coverage", started, error=exc, llm=locals().get("llm"))]}
user_prompt = _build_prompt(state)
logger.info(
"Invoking test-coverage reviewer (diff=%s, context=%d chunks, prompt_version=%s)",
_human_size(len(state.diff or "")),
len(state.context_chunks),
PROMPT_VERSION,
)
try:
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_prompt},
]
result: TestCoverageReview = invoke_review(llm, TestCoverageReview, messages, mode=state.review_mode) # type: ignore[assignment]
except Exception as exc:
logger.warning("Test-coverage review LLM call failed: %s", exc)
return {"review_stages": [stage_result("test_coverage", started, error=exc, llm=locals().get("llm"))]}
result.findings = calibrate_findings(result.findings, state)
if result.findings:
logger.info("Test-coverage review found %d issue(s)", len(result.findings))
for f in result.findings:
logger.debug(" [%.2f] %s:%dβ%d β %s", f.confidence, f.file_path, f.line_start, f.line_end, f.comment[:80])
else:
logger.info("Test-coverage review found no issues")
return {"findings": result.findings, "review_stages": [stage_result("test_coverage", started, llm=llm)]}
def _human_size(bytes_: int) -> str:
if bytes_ < 1024:
return f"{bytes_} B"
elif bytes_ < 1024 * 1024:
return f"{bytes_ / 1024:.1f} KiB"
else:
return f"{bytes_ / (1024 * 1024):.1f} MiB"
|