From 3c95320ad64782c84378451f39abdea437543965 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 10 Oct 2026 12:13:46 +1300 Subject: [PATCH] Recover authored review finding display from archived evidence --- dev-tools/pr_review/sqlite_finding_text.py | 89 +++-- dev-tools/pr_review/sqlite_review_records.py | 79 ++++- .../test_pr_review_sqlite_hosted_capture.py | 4 +- .../test_pr_review_sqlite_review_records.py | 334 ++++++++++++++++++ 4 files changed, 471 insertions(+), 35 deletions(-) diff --git a/dev-tools/pr_review/sqlite_finding_text.py b/dev-tools/pr_review/sqlite_finding_text.py index dd133f85d9..f3868a2c94 100644 --- a/dev-tools/pr_review/sqlite_finding_text.py +++ b/dev-tools/pr_review/sqlite_finding_text.py @@ -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, ) @@ -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) @@ -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 @@ -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. @@ -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" @@ -145,28 +155,39 @@ def _hosted_issue_markdown( value = re.sub(r"<(script|style)\b[^>]*>.*?", "", value, flags=re.DOTALL | re.IGNORECASE) value = re.sub( r"]*>\s*]*>(.*?)(.*?)", - 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) @@ -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 @@ -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) @@ -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) @@ -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) @@ -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": @@ -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) diff --git a/dev-tools/pr_review/sqlite_review_records.py b/dev-tools/pr_review/sqlite_review_records.py index 305706fcc3..5f77e60abe 100644 --- a/dev-tools/pr_review/sqlite_review_records.py +++ b/dev-tools/pr_review/sqlite_review_records.py @@ -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"[ \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()] + "" + return value + + def _archive_artifact(kind: str, content: str) -> tuple[str, str, int]: limits = { "cli_events": 8 * 1024 * 1024, @@ -4309,9 +4334,7 @@ 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"]) @@ -4319,7 +4342,10 @@ def _add_hosted_display_titles( 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"): @@ -4327,10 +4353,10 @@ def _add_hosted_display_titles( 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 @@ -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, @@ -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]]: @@ -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) @@ -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 diff --git a/dev-tools/validation/test_pr_review_sqlite_hosted_capture.py b/dev-tools/validation/test_pr_review_sqlite_hosted_capture.py index 7acaed1ffd..4c10c2e51a 100644 --- a/dev-tools/validation/test_pr_review_sqlite_hosted_capture.py +++ b/dev-tools/validation/test_pr_review_sqlite_hosted_capture.py @@ -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: diff --git a/dev-tools/validation/test_pr_review_sqlite_review_records.py b/dev-tools/validation/test_pr_review_sqlite_review_records.py index f2ba0556c5..52fc810f21 100644 --- a/dev-tools/validation/test_pr_review_sqlite_review_records.py +++ b/dev-tools/validation/test_pr_review_sqlite_review_records.py @@ -2609,6 +2609,340 @@ def test_stored_cli_severity_overrides_provider_projection(self) -> None: ) self.assertEqual(self.records.history(2828)["findings"][0]["display_severity"], "Trivial") + def cli_display_capture(self, events, *, imported=False): + self.bootstrap() + run_id = "run.cli-display" + observations = tuple( + FindingObservation( + source_finding_key=f"cli-run:{run_id}:finding:{index}", + title=sqlite_provider_imports._cli_finding_title( + event.get("codegenInstructions"), f"CodeRabbit CLI finding {index}" + ), + detail=_safe_finding_detail(sqlite_provider_imports._cli_detail(event.get("codegenInstructions"))), + ) + for index, event in enumerate(events, 1) + ) + stdout = ( + "\n".join( + json.dumps(event) + for event in [ + *events, + { + "type": "complete", + "status": "review_completed", + "findings": len(events), + "reviewedFiles": ["src/a.py"], + }, + ] + ) + + "\n" + ) + metadata = { + "repository": "owner/repo", + "run_id": run_id, + "kind": "cli", + "pull_request": 2828, + "candidate_sha": "a" * 40, + "child_head_sha": "a" * 40, + "parent_pr": None, + "parent_ref": "main", + "parent_sha": "b" * 40, + "merge_base": "b" * 40, + "patch_identity": "c" * 64, + "candidate_files": 1, + "capture_completion_marker": "capture-complete", + "duration_seconds": 9, + "exit_status": 0, + } + if imported: + self.records.record_run(run_id=run_id, source_pr=2828, channel="cli", findings=observations) + checkpoint = Checkpoint( + comment_id=999, + created_at="2026-10-01T00:00:00Z", + type="CLI", + raw_found=len(events), + accepted=0, + reviewed_sha="a" * 40, + file_count=1, + correction=False, + updated_at=None, + run_id=run_id, + hosted_review_id=None, + ) + fingerprint = sqlite_provider_imports._checkpoint_fingerprint(checkpoint) + metadata.update( + checkpoint_fields=dataclasses.asdict(checkpoint), + checkpoint_fingerprint=fingerprint, + checkpoint=checkpoint.as_json(), + ) + self.records.archive_imported_artifacts(run_id, {"cli_events": stdout, "metadata": json.dumps(metadata)}) + self.records.link_provider_origin( + repository="owner/repo", + source_pr=2828, + channel="cli", + provider_id=f"run:{run_id}", + checkpoint_id=999, + checkpoint_fingerprint=fingerprint, + run_id=run_id, + ) + else: + self.records.start_attempt( + attempt_id=run_id, + source_pr=2828, + channel="cli", + candidate_sha="a" * 40, + metadata=metadata, + started_at="2026-10-01T00:00:00Z", + ) + self.records.complete_attempt_run( + run_id, + finish={ + "state": "completed", + "finished_at": "2026-10-01T00:00:09Z", + "duration_seconds": 9, + "exit_status": 0, + "artifacts": {"cli_events": stdout, "metadata": json.dumps(metadata)}, + }, + run={ + "run_id": run_id, + "source_pr": 2828, + "channel": "cli", + "source_head": "a" * 40, + "reviewer": "CodeRabbit CLI", + "scope": "broad", + "findings": observations, + "started_at": "2026-10-01T00:00:00Z", + "finished_at": "2026-10-01T00:00:09Z", + }, + ) + return run_id + + def test_cli_display_uses_exact_archived_title_comment_and_preserves_history(self) -> None: + events = [ + { + "type": "finding", + "title": "Deny TRUNCATE on every immutable evidence table.", + "comment": "**Deny TRUNCATE on every immutable evidence table.**\n\n" + "Retain the receipt.\n\n
🐛 Suggested fix\n\n" + "```sql\n SELECT original_roles;\n\n```\n
", + "codegenInstructions": "", + "severity": "minor", + }, + { + "type": "finding", + "title": "Bind the original `globalRoles` from the receipt.", + "comment": "**Bind the original `globalRoles` from the receipt.**\n\n" + "A combined role change fails. Read [the contract](https://example.test/contract).", + "codegenInstructions": "Review comment at @src/a.py:1\nUpdate expected_before_state.", + "severity": "major", + }, + ] + run_id = self.cli_display_capture(events) + self.records.record_source_decision( + run_id, + f"cli-run:{run_id}:finding:1", + decision_id="routed-cli", + decision="routed", + target_pr=2879, + actor="reviewer", + reason="Owner fix", + ) + with sqlite3.connect(self.database) as connection: + before = list(connection.iterdump()) + with patch.object(self.records, "_write_connection", side_effect=AssertionError("read wrote")): + history = self.records.history(2828) + findings = {item["source_finding_key"]: item for item in history["findings"]} + first = findings[f"cli-run:{run_id}:finding:1"] + self.assertEqual(first["title"], "CodeRabbit CLI finding 1") + self.assertEqual(first["detail"], "") + self.assertEqual(first["display_title"], events[0]["title"]) + self.assertEqual(first["display_detail"], "Retain the receipt.\n\n```sql\n SELECT original_roles;\n\n```") + self.assertEqual(first["display_severity"], "Minor") + second = findings[f"cli-run:{run_id}:finding:2"] + self.assertEqual(second["title"], "Update expected_before_state.") + self.assertEqual(second["display_title"], events[1]["title"]) + self.assertIn("A combined role change fails.", second["display_detail"]) + self.assertEqual(second["display_severity"], "Major") + route = self.records.history(2879)["routes"][0] + self.assertEqual(route["display_title"], first["display_title"]) + self.assertEqual(route["display_detail"], first["display_detail"]) + self.assertEqual(self.records.history_batch((2828,))[2828], history) + with sqlite3.connect(self.database) as connection: + self.assertEqual(list(connection.iterdump()), before) + + def test_cli_display_import_is_exact_ordinal_and_fails_closed_on_wrong_origin(self) -> None: + event = { + "type": "finding", + "title": "Keep retained evidence.", + "comment": "Full explanation.", + "codegenInstructions": "Update the guard.", + "severity": "minor", + } + run_id = self.cli_display_capture([event], imported=True) + self.assertEqual(self.records.history(2828)["findings"][0]["display_title"], event["title"]) + with sqlite3.connect(self.database) as connection: + connection.execute("UPDATE provider_origins SET provider_id = 'run:other' WHERE run_id = ?", (run_id,)) + self.assertNotIn("display_title", self.records.history(2828)["findings"][0]) + + def test_cli_display_prose_fallback_bounds_and_redaction(self) -> None: + run_id = self.cli_display_capture( + [ + {"type": "finding", "codegenInstructions": "Review comment at @src/a.py:1\nLegacy issue."}, + { + "type": "finding", + "title": "Issue " + "x" * 400, + "comment": "Authorization: Bearer secret-display-token\n\n" + "body " * 2000, + "codegenInstructions": "", + "severity": "minor", + }, + ] + ) + findings = {item["source_finding_key"]: item for item in self.records.history(2828)["findings"]} + self.assertEqual(findings[f"cli-run:{run_id}:finding:1"]["display_detail"], "Legacy issue.") + bounded = findings[f"cli-run:{run_id}:finding:2"] + self.assertLessEqual(len(bounded["display_title"]), 300) + self.assertLessEqual(len(bounded["display_detail"]), 8000) + self.assertNotIn("secret-display-token", bounded["display_detail"]) + + def test_hosted_display_control_sentinel_is_only_removed_at_prose_headline(self) -> None: + raw_title = "<|im_start|>**Allow Account-local fences to differ from Account-scope generations.**" + self.hosted_display_run(title=raw_title) + archive = self.hosted_display_archive( + issue=( + "**🎯 Functional Correctness** | **🟠 Major** | **⚡ Quick win**\n\n" + + raw_title + + "\n\nA membership advance changes only its own generation.\n\n" + "```text\n<|im_start|>**Keep this literal code sample.**\n```" + ) + ) + self.records.archive_imported_artifacts("display-run", {"hosted_comments": archive}) + with sqlite3.connect(self.database) as connection: + before = list(connection.iterdump()) + finding = self.records.history(2839)["findings"][0] + self.assertEqual(finding["title"], raw_title) + self.assertEqual( + finding["display_title"], "Allow Account-local fences to differ from Account-scope generations." + ) + self.assertEqual(finding["display_severity"], "Major") + self.assertTrue(finding["display_detail"].startswith("A membership advance")) + self.assertIn("<|im_start|>**Keep this literal code sample.**", finding["display_detail"]) + with sqlite3.connect(self.database) as connection: + self.assertEqual(list(connection.iterdump()), before) + + def test_hosted_suggested_fix_keeps_jooq_terminator_diff_without_diagnostics(self) -> None: + title = "Use the configured jOOQ ignore terminator." + self.hosted_display_run(title=title) + diff = "```diff\n--- [jooq ignore end]\n+-- [jooq ignore stop]\n```" + archive = self.hosted_display_archive( + issue=( + f"**{title}**\n\nReplace it with:\n\n" + "
🐛 Suggested fix\n\n" + diff + "\n
\n\n" + "
🤖 Prompt for AI Agents\nRewrite everything.\n
" + ) + ) + self.records.archive_imported_artifacts("display-run", {"hosted_comments": archive}) + finding = self.records.history(2839)["findings"][0] + self.assertEqual(finding["display_detail"], "Replace it with:\n\n" + diff) + self.assertNotIn("Suggested fix", finding["display_detail"]) + self.assertNotIn("Script executed", finding["display_detail"]) + self.assertNotIn("echo diagnostic", finding["display_detail"]) + self.assertNotIn("Rewrite everything", finding["display_detail"]) + + def test_suggested_fix_label_variants_preserve_patches_but_not_diagnostics(self) -> None: + title = "Use the configured jOOQ ignore terminator." + diff = "```diff\n--- [jooq ignore end]\n+-- [jooq ignore stop]\n```" + for index, label in enumerate( + ( + "Suggested fix", + "**Suggested fix**", + "__Suggested fix__", + "Suggested fix:", + "**Suggested fix:**", + "🐛 Suggested fix:", + ) + ): + for details in (False, True): + with self.subTest(label=label, details=details): + fix = ( + f"
{label}\n\n{diff}\n
" + if details + else label + "\n\n" + diff + ) + archive = self.hosted_display_archive( + issue=( + f"**{title}**\n\nReplace it with:\n\n" + + fix + + "\n\n
🧰 ToolsTool noise.
\n\n" + "
🤖 Prompt for AI AgentsRewrite everything.
" + ) + ) + run_id = f"suggested-fix-{index}-{details}" + self.hosted_display_run(run_id=run_id, title=title, routed=False) + self.records.archive_imported_artifacts(run_id, {"hosted_comments": archive}) + finding = next(item for item in self.records.history(2839)["findings"] if item["run_id"] == run_id) + self.assertEqual(finding["display_detail"], "Replace it with:\n\n" + diff) + + def test_hosted_display_controls_preserve_tabs_newlines_and_immutable_archive(self) -> None: + title = "Keep reviewer explanation readable." + self.hosted_display_run(title=title) + archive = self.hosted_display_archive( + issue=( + f"**{title}**\n\nBody\x00\x08\x7f\x85text.\n\n" + "```sql\n\tSELECT tenant_id;\n\n\t-- retained indentation\n```" + ) + ) + self.records.archive_imported_artifacts("display-run", {"hosted_comments": archive}) + with sqlite3.connect(self.database) as connection: + before = list(connection.iterdump()) + finding = self.records.history(2839)["findings"][0] + self.assertEqual( + finding["display_detail"], "Body text.\n\n```sql\n\tSELECT tenant_id;\n\n\t-- retained indentation\n```" + ) + with sqlite3.connect(self.database) as connection: + self.assertEqual(list(connection.iterdump()), before) + + def test_hosted_footer_only_variants_recover_prose_but_substantive_conflicts_do_not(self) -> None: + title = "Keep generic Account updates readable by LOGIN source reads." + self.hosted_display_run(title=title) + archive = json.loads( + self.hosted_display_archive( + issue=( + "**🩺 Stability & Availability** | **🟠 Major** | **🏗️ Heavy lift**\n\n" + f"**{title}**\n\nGeneric Account events remain in retained history.\n\n" + "
🧰 Tools
PMDTool noise.
\n\n" + "\n\n" + "" + ) + ) + ) + native = json.loads(json.dumps(archive)) + native["comments"][0]["body"] = native["comments"][0]["body"].replace( + "auto-generated comment by", "auto-generated reply by" + ) + self.records.archive_imported_artifacts("display-run", {"hosted_comments": json.dumps(archive)}) + self.records.start_attempt(attempt_id="display-footer", source_pr=2839, channel="hosted") + self.records.finish_attempt( + "display-footer", state="completed", artifacts={"hosted_comments": json.dumps(native)} + ) + self.records.link_attempt_run("display-footer", "display-run") + with sqlite3.connect(self.database) as connection: + before = list(connection.iterdump()) + finding = self.records.history(2839)["findings"][0] + self.assertEqual(finding["title"], title) + self.assertEqual(finding["display_detail"], "Generic Account events remain in retained history.") + self.assertEqual(finding["display_severity"], "Major") + self.assertNotIn("Script executed", finding["display_detail"]) + self.assertNotIn("Tool noise", finding["display_detail"]) + with sqlite3.connect(self.database) as connection: + self.assertEqual(list(connection.iterdump()), before) + changed = json.dumps(native).replace("Generic Account events remain", "Different Account events remain") + connection.execute( + "UPDATE review_artifacts SET content = ? WHERE attempt_id = 'display-footer' " + "AND kind = 'hosted_comments'", + (changed,), + ) + self.assertNotIn("display_detail", self.records.history(2839)["findings"][0]) + def test_route_severity_uses_latest_observation_without_mixing_runs(self) -> None: self.bootstrap() key = "repeated-routed-finding"