Skip to content
Merged
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
89 changes: 62 additions & 27 deletions dev-tools/pr_review/sqlite_finding_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@ def _safe_finding_detail(value: Any) -> str:
r"^(?:(?:supported by static analysis|script executed|analysis results?|"
r"committable suggestion|script output|analysis chain|suggested fix|prompt for ai agents|ai (?:agent )?prompt)\s*:?|"
r"repository\s*:\s*`?[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+`?|"
r"length of output\s*:\s*[0-9]+)\s*$", re.IGNORECASE
r"length of output\s*:\s*[0-9]+)\s*$",
re.IGNORECASE,
)


Expand All @@ -80,6 +81,11 @@ def _is_evidence_label(value: str) -> bool:
return bool(_EVIDENCE_LABEL.fullmatch(candidate))


def _is_suggested_fix_label(value: str) -> bool:
candidate = _bold_line_content(value.strip()) or value.strip().strip("_*")
return bool(re.fullmatch(r"[^a-zA-Z0-9]*Suggested fix\s*:?\s*", candidate, flags=re.IGNORECASE))


def _headline_text(line: str) -> str:
# Inline code remains literal, including generic types and comparisons.
parts = re.split(r"(`+[^`]*`+)", line)
Expand All @@ -106,7 +112,7 @@ def _strip_badge_prefix(line: str, *, allow_two_field: bool = False) -> str:
):
match = re.match(pattern, line)
if match and _is_badge_line(match.group(), allow_two_field=allow_two_field):
return line[match.end():].strip()
return line[match.end() :].strip()
return line


Expand All @@ -124,7 +130,7 @@ def _hosted_issue_markdown(
continue
summary = _headline_text(match.group(1))
if re.search(r"prompt for ai agents|ai (?:agent )?prompt", summary, re.IGNORECASE):
value = value[:match.start()]
value = value[: match.start()]
break
# Protect ordinary samples before any HTML/metadata cleanup. Diagnostic
# details still discard their entire block, including protected samples.
Expand All @@ -134,7 +140,11 @@ def _hosted_issue_markdown(
marker += ":"
for index, (start, end) in reversed(list(enumerate(_markdown_fenced_ranges(value)))):
preceding = value[:start].rstrip().splitlines()
if preceding and _is_evidence_label(_headline_text(preceding[-1])):
if (
preceding
and _is_evidence_label(_headline_text(preceding[-1]))
and not _is_suggested_fix_label(_headline_text(preceding[-1]))
):
replacement = "\n"
else:
token = f"{marker}{index}\x00"
Expand All @@ -145,28 +155,39 @@ def _hosted_issue_markdown(
value = re.sub(r"<(script|style)\b[^>]*>.*?</\1>", "", value, flags=re.DOTALL | re.IGNORECASE)
value = re.sub(
r"<details\b[^>]*>\s*<summary\b[^>]*>(.*?)</summary>(.*?)</details>",
lambda match: "" if (_is_evidence_label(_headline_text(match.group(1)))
or re.fullmatch(r"[^a-zA-Z0-9]*Tools\s*", _headline_text(match.group(1))))
else match.group(1) + "\n" + match.group(2),
lambda match: (
""
if (
(
_is_evidence_label(_headline_text(match.group(1)))
and not _is_suggested_fix_label(_headline_text(match.group(1)))
)
or re.fullmatch(r"[^a-zA-Z0-9]*Tools\s*", _headline_text(match.group(1)))
)
else match.group(1) + "\n" + match.group(2)
),
value,
flags=re.DOTALL | re.IGNORECASE,
)
# Security taxonomy is metadata only when the provider header and an
# adjacent exploitability/CWE block prove that a later authored remediation exists.
value = "\n".join(
line for line in value.splitlines()
if not _is_evidence_label(_headline_text(html.unescape(line)))
and line.strip() not in {"---", "***", "___"}
line
for line in value.splitlines()
if not _is_evidence_label(_headline_text(html.unescape(line))) and line.strip() not in {"---", "***", "___"}
)
pattern = re.compile(
r"^([^\n]+)\n[ \t\n]*\*\*([^\n*]+)\*\*[ \t]*\n[ \t\n]*"
r"((?:\*\*(?:Reachability|Exploitability|CWE):\*\*[^\n]*\n[ \t\n]*)+)"
r"(?=\*\*[^\n*]+\*\*(?:[ \t]|$))", re.MULTILINE
r"(?=\*\*[^\n*]+\*\*(?:[ \t]|$))",
re.MULTILINE,
)

def strip_classification(match: re.Match[str]) -> str:
header, classification, metadata = match.groups()
if (
not _is_badge_line(header) or len(header.split("|")) not in {3, 4}
not _is_badge_line(header)
or len(header.split("|")) not in {3, 4}
or _badge_label_text(header.split("|")[0]).casefold() != "security & privacy"
or "**Exploitability:**" not in metadata
or not re.search(r"\*\*CWE:\*\*.*CWE-[0-9]+", metadata)
Expand All @@ -175,6 +196,7 @@ def strip_classification(match: re.Match[str]) -> str:
if classification_titles is not None:
classification_titles.add(classification)
return header + "\n"

value = pattern.sub(strip_classification, value)
lines = []
header_position = True
Expand All @@ -187,8 +209,9 @@ def strip_classification(match: re.Match[str]) -> str:
header_position = False
if not keep_badges:
line = _strip_badge_prefix(line, allow_two_field=allow_two_field)
if line and ((_is_badge_line(line, allow_two_field=allow_two_field) and not keep_badges)
or _is_evidence_label(line)):
if line and (
(_is_badge_line(line, allow_two_field=allow_two_field) and not keep_badges) or _is_evidence_label(line)
):
continue
if line or not lines or lines[-1]:
lines.append(line)
Expand Down Expand Up @@ -255,7 +278,7 @@ def _hosted_display_detail(value: str, title: str) -> str:
break
match = re.match(r"^(?:\*\*(.+?)\*\*|__(.+?)__)(?:\s|$)", candidate)
if match and (match.group(1) or match.group(2)) == title:
lines[index] = candidate[match.end():].lstrip()
lines[index] = candidate[match.end() :].lstrip()
break
value = "\n".join(lines).strip()
value, _ = _redact_archive_text(value)
Expand All @@ -277,8 +300,10 @@ def _badge_label_text(value: str) -> str:


def _explicit_severity_label(value: str, *, priority_badge: bool = False) -> str | None:
labels = {label.casefold(): label for label in
("Critical", "Major", "Minor", "Trivial", "High", "Medium", "Low", "P0", "P1", "P2", "P3")}
labels = {
label.casefold(): label
for label in ("Critical", "Major", "Minor", "Trivial", "High", "Medium", "Low", "P0", "P1", "P2", "P3")
}
candidate = _badge_label_text(value)
candidate = re.sub(r"^severity\s*:\s*", "", candidate, flags=re.IGNORECASE)
priority = re.fullmatch(r"(P[0-3])\]?(?:\s+(?:Bug|Issue|Nit|Suggestion))?", candidate, re.IGNORECASE)
Expand All @@ -293,14 +318,23 @@ def _is_badge_line(line: str, *, allow_two_field: bool = False) -> bool:
candidate = re.sub(r"^#{1,6}\s*", "", line).strip()
sections = [section.strip() for section in candidate.split("|")]
wrapped_fields = all(
any(section.startswith(delimiter) and section.endswith(delimiter)
for delimiter in ("_", "**", "__")) for section in sections
any(section.startswith(delimiter) and section.endswith(delimiter) for delimiter in ("_", "**", "__"))
for section in sections
)
if len(sections) == 2 and wrapped_fields:
known_categories = {"bug", "data integrity & integration", "functional correctness", "maintainability & code quality",
"security & privacy", "stability & availability"}
return (allow_two_field and _badge_label_text(sections[0]).casefold() in known_categories
and _explicit_severity_label(sections[1]) is not None)
known_categories = {
"bug",
"data integrity & integration",
"functional correctness",
"maintainability & code quality",
"security & privacy",
"stability & availability",
}
return (
allow_two_field
and _badge_label_text(sections[0]).casefold() in known_categories
and _explicit_severity_label(sections[1]) is not None
)
if len(sections) in {3, 4} and wrapped_fields:
category = _badge_label_text(sections[0]).casefold()
if category.startswith("security") and category != "security & privacy":
Expand Down Expand Up @@ -340,11 +374,12 @@ def _hosted_display_severity(value: str) -> str | None:
match = re.match(
r"^(?:_[^\n]*?_(?:\s*\|\s*_[^\n]*?_){1,3}|"
r"\*\*[^\n]*?\*\*(?:\s*\|\s*\*\*[^\n]*?\*\*){1,3}|"
r"__[^\n]*?__(?:\s*\|\s*__[^\n]*?__){1,3})", line
r"__[^\n]*?__(?:\s*\|\s*__[^\n]*?__){1,3})",
line,
)
fields = (
match.group().split("|") if match and _is_badge_line(match.group(), allow_two_field=allow_two_field) else []
)
fields = match.group().split("|") if match and _is_badge_line(
match.group(), allow_two_field=allow_two_field
) else []
badge = fields[-1] if len(fields) == 2 else fields[-2] if fields else None
if badge is None:
match = re.match(r"^(?:\*\*([^\n]*?)\*\*|__([^\n]*?)__)", line)
Expand Down
79 changes: 72 additions & 7 deletions dev-tools/pr_review/sqlite_review_records.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,31 @@ def redact(match: re.Match[str]) -> str:
return value, redactions


def _display_provider_prose(value: str) -> str:
"""Normalize display controls and remove prose-headline sentinels outside samples."""

from .sqlite_hosted_capture import _markdown_fenced_ranges

value = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]", " ", value)
fences = _markdown_fenced_ranges(value)
pattern = re.compile(r"(?m)^([ \t]*(?:>[ \t]*)*)<\|im_start\|>(?=\*\*|__|#{1,6}[ \t])")
return pattern.sub(
lambda match: match.group() if any(start <= match.start() < end for start, end in fences) else match.group(1),
value,
)


def _display_hosted_body_identity(value: str) -> str:
"""Treat only the terminal generated comment/reply footer as equivalent."""

from .sqlite_hosted_capture import _markdown_fenced_ranges

match = re.search(r"<!-- This is an auto-generated (?:comment|reply) by CodeRabbit -->[ \t\r\n]*\Z", value)
if match and not any(start <= match.start() < end for start, end in _markdown_fenced_ranges(value)):
return value[: match.start()] + "<!-- This is an auto-generated comment by CodeRabbit -->"
return value


def _archive_artifact(kind: str, content: str) -> tuple[str, str, int]:
limits = {
"cli_events": 8 * 1024 * 1024,
Expand Down Expand Up @@ -4309,28 +4334,29 @@ def _add_hosted_display_titles(
cache_key = (run_id, record["source_pr"])
if cache_key not in cache:
reader = (
self._hosted_display_titles
if record["source_channel"] == "hosted"
else self._cli_display_severities
self._hosted_display_titles if record["source_channel"] == "hosted" else self._cli_display_findings
)
cache[cache_key] = reader(connection, run_id, record["source_pr"])
presentation = cache[cache_key].get(record["source_finding_key"])
if presentation:
if "display_severity" not in record:
record["display_severity"] = presentation["display_severity"]
if (
_unusable_hosted_title(title) or title in presentation.get("classification_titles", ())
record["source_channel"] == "cli"
or _display_provider_prose(title) != title
or _unusable_hosted_title(title)
or title in presentation.get("classification_titles", ())
) and presentation.get("display_title"):
record["display_title"] = presentation["display_title"]
if presentation.get("display_title_is_excerpt") and title == presentation.get("display_title"):
record["display_title_is_excerpt"] = True
if presentation.get("display_detail"):
record["display_detail"] = presentation["display_detail"]

def _cli_display_severities(
def _cli_display_findings(
self, connection: sqlite3.Connection, run_id: str, source_pr: int
) -> dict[str, dict[str, Any]]:
"""Associate retained provider severity with exact validated CLI finding ordinals."""
"""Project retained provider prose at exact validated CLI finding ordinals."""

from . import evidence

Expand Down Expand Up @@ -4395,6 +4421,7 @@ def _cli_display_severities(
}
return {
f"cli-run:{capture_id}:finding:{index}": {
**self._cli_display_prose(finding),
"display_severity": labels.get(finding["severity"].strip().casefold())
if isinstance(finding.get("severity"), str)
else None,
Expand All @@ -4404,6 +4431,43 @@ def _cli_display_severities(
except (evidence.EvidenceError, ReviewRecordsError, KeyError, TypeError, ValueError, AttributeError):
return {}

@staticmethod
def _cli_display_prose(finding: dict[str, Any]) -> dict[str, str]:
"""Prefer reviewer title/comment; keep legacy stored projections immutable."""

from .sqlite_finding_text import _hosted_display_detail
from .sqlite_provider_imports import _cli_detail, _cli_finding_title, _normalize_cli_title_text

raw_title = finding.get("title")
title = _display_provider_prose(raw_title).strip() if isinstance(raw_title, str) else ""
title = re.sub(r"^(?:\*\*(.*?)\*\*|__(.*?)__)$", lambda match: match.group(1) or match.group(2), title)
comment = finding.get("comment")
detail = _display_provider_prose(comment).strip() if isinstance(comment, str) else ""
headline = re.match(r"^(?:\*\*([^\n]+?)\*\*|__([^\n]+?)__)(?:[ \t]*\n|[ \t]+|$)", detail)
if headline:
authored_title = headline.group(1) or headline.group(2)
if not title or title == authored_title or title.startswith(authored_title + " "):
title = authored_title
detail = detail[headline.end() :].lstrip()
if not title:
title = _cli_finding_title(finding.get("codegenInstructions"), "")
if detail:
detail = _hosted_display_detail(detail, title)
if not detail:
detail = _cli_detail(finding.get("codegenInstructions"))
title = " ".join(_normalize_cli_title_text(title).split())
title, _ = _redact_archive_text(title)
detail = _display_provider_prose(detail)
detail, _ = _redact_archive_text(detail)
return {
key: value
for key, value in {
"display_title": title[:300].rstrip(),
"display_detail": detail[:8000].rstrip(),
}.items()
if value
}

def _hosted_display_titles(
self, connection: sqlite3.Connection, run_id: str, source_pr: int
) -> dict[str, dict[str, Any]]:
Expand Down Expand Up @@ -4462,6 +4526,7 @@ def _hosted_display_titles(
body = comment.get("body")
if comment_id is None or not isinstance(body, str) or comment_id in ambiguous_ids:
continue
body = _display_hosted_body_identity(body)
if comment_id in bodies and bodies[comment_id] != body:
# Conflicting exact identity never picks a variant, including later repeats.
ambiguous_ids.add(comment_id)
Expand All @@ -4471,7 +4536,7 @@ def _hosted_display_titles(
titles = {}
for comment_id, body in bodies.items():
try:
findings = _hosted_comment_finding_segments(comment_id, body)
findings = _hosted_comment_finding_segments(comment_id, _display_provider_prose(body))
except HostedCaptureError:
# Invalid individual comments cannot invalidate independent exact-key siblings.
continue
Expand Down
4 changes: 3 additions & 1 deletion dev-tools/validation/test_pr_review_sqlite_hosted_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -784,7 +784,9 @@ def test_actual_analysis_before_headline_and_inline_duplicate(self) -> None:
)
finding = sqlite_hosted_capture._hosted_comment_finding_segments(4152944302, body)[0]
self.assertEqual(finding["title"], title)
self.assertEqual(finding["display_detail"], "Lines 20–25 must preserve `tenantId`.")
self.assertEqual(
finding["display_detail"], "Lines 20–25 must preserve `tenantId`.\n\n```diff\n+noise\n```"
)
self.assertEqual(finding["display_severity"], "Major")

def test_hosted_severity_reads_explicit_badges_only(self) -> None:
Expand Down
Loading
Loading