|
| 1 | +"""Validate Claude release draft analysis before updating the draft release.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import argparse |
| 6 | +import json |
| 7 | +import os |
| 8 | +import re |
| 9 | +import sys |
| 10 | +from pathlib import Path |
| 11 | +from typing import Any |
| 12 | + |
| 13 | +REMOVAL_PATTERNS = [ |
| 14 | + re.compile(r"\b(?:removed|deleted|dropped)\b(?:(?!`).){0,80}`(?P<token>[^`\n]+)`", re.IGNORECASE), |
| 15 | + re.compile(r"`(?P<token>[^`\n]+)`(?:(?!`).){0,80}\b(?:removed|deleted|dropped)\b", re.IGNORECASE), |
| 16 | + re.compile( |
| 17 | + r"\bno longer\s+(?:supports?|accepts?|recognizes?|exports?|provides?|includes?|allows?|has)\b" |
| 18 | + r"(?:(?!`).){0,80}`(?P<token>[^`\n]+)`", |
| 19 | + re.IGNORECASE, |
| 20 | + ), |
| 21 | + re.compile( |
| 22 | + r"`(?P<token>[^`\n]+)`(?:(?!`).){0,80}\bno longer\s+" |
| 23 | + r"(?:available|exists|supported|accepted|recognized|exported|provided|included|allowed)\b", |
| 24 | + re.IGNORECASE, |
| 25 | + ), |
| 26 | +] |
| 27 | +UNREADABLE_DIFF_RE = re.compile( |
| 28 | + r"\b(?:unable|could not|can't|cannot)\b.{0,160}\b(?:read|access)\b.{0,160}" |
| 29 | + r"\b(?:prepared diff|analysis artifact|diff file|diff)\b", |
| 30 | + re.IGNORECASE | re.DOTALL, |
| 31 | +) |
| 32 | +TOKEN_BOUNDARY_CHARS = r"A-Za-z0-9_.:/-" |
| 33 | + |
| 34 | + |
| 35 | +def _parse_args() -> argparse.Namespace: |
| 36 | + """Parse validator CLI arguments.""" |
| 37 | + parser = argparse.ArgumentParser() |
| 38 | + parser.add_argument("--analysis-path", required=True, type=Path) |
| 39 | + parser.add_argument("--deleted-lines-path", required=True, type=Path) |
| 40 | + return parser.parse_args() |
| 41 | + |
| 42 | + |
| 43 | +def _parse_claude_output(raw_output: str) -> dict[str, Any]: |
| 44 | + """Parse Claude's structured output as a JSON object.""" |
| 45 | + if not raw_output: |
| 46 | + message = "Claude structured output is empty" |
| 47 | + raise SystemExit(message) |
| 48 | + try: |
| 49 | + parsed = json.loads(raw_output) |
| 50 | + except json.JSONDecodeError as exc: |
| 51 | + message = f"Invalid Claude structured output JSON: {exc}" |
| 52 | + raise SystemExit(message) from exc |
| 53 | + if isinstance(parsed, dict): |
| 54 | + return parsed |
| 55 | + message = "Claude structured output must be a JSON object" |
| 56 | + raise SystemExit(message) |
| 57 | + |
| 58 | + |
| 59 | +def _as_bool(value: Any) -> bool: |
| 60 | + """Normalize Claude's boolean-like field values.""" |
| 61 | + result = False |
| 62 | + match value: |
| 63 | + case bool(): |
| 64 | + result = value |
| 65 | + case str() if value.lower() == "true": |
| 66 | + result = True |
| 67 | + case _: |
| 68 | + result = False |
| 69 | + return result |
| 70 | + |
| 71 | + |
| 72 | +def _as_string(value: Any) -> str: |
| 73 | + """Normalize Claude's string-like field values.""" |
| 74 | + return value if isinstance(value, str) else "" |
| 75 | + |
| 76 | + |
| 77 | +def _normalize_token(token: str) -> str: |
| 78 | + """Normalize a claimed removed token for comparison.""" |
| 79 | + stripped = token.strip() |
| 80 | + normalized = stripped |
| 81 | + match stripped: |
| 82 | + case value if value.endswith("()"): |
| 83 | + normalized = value[:-2] |
| 84 | + case value: |
| 85 | + normalized = value |
| 86 | + return normalized |
| 87 | + |
| 88 | + |
| 89 | +def _iter_non_fenced_lines(text: str) -> list[str]: |
| 90 | + """Return lines outside Markdown code fences.""" |
| 91 | + lines: list[str] = [] |
| 92 | + in_fence = False |
| 93 | + for line in text.splitlines(): |
| 94 | + stripped = line.strip() |
| 95 | + if stripped.startswith(("```", "~~~")): |
| 96 | + in_fence = not in_fence |
| 97 | + continue |
| 98 | + if in_fence: |
| 99 | + continue |
| 100 | + lines.append(line) |
| 101 | + return lines |
| 102 | + |
| 103 | + |
| 104 | +def _claimed_removed_tokens(line: str) -> set[str]: |
| 105 | + """Extract explicit removed-token claims from one non-fenced line.""" |
| 106 | + tokens: set[str] = set() |
| 107 | + for pattern in REMOVAL_PATTERNS: |
| 108 | + for match in pattern.finditer(line): |
| 109 | + if normalized := _normalize_token(match.group("token")): |
| 110 | + tokens.add(normalized) |
| 111 | + return tokens |
| 112 | + |
| 113 | + |
| 114 | +def _token_present(token: str, deleted_lines: str) -> bool: |
| 115 | + """Return whether token appears with non-token boundaries in deleted lines.""" |
| 116 | + if not (normalized := _normalize_token(token)): |
| 117 | + return False |
| 118 | + pattern = re.compile(rf"(?<![{TOKEN_BOUNDARY_CHARS}]){re.escape(normalized)}(?![{TOKEN_BOUNDARY_CHARS}])") |
| 119 | + return bool(pattern.search(deleted_lines)) |
| 120 | + |
| 121 | + |
| 122 | +def _validate_removal_claims(breaking_changes_content: str, deleted_lines_path: Path) -> None: |
| 123 | + """Validate explicit removal claims against trusted deleted diff lines.""" |
| 124 | + claims = [ |
| 125 | + (line, token) |
| 126 | + for line in _iter_non_fenced_lines(breaking_changes_content) |
| 127 | + for token in _claimed_removed_tokens(line) |
| 128 | + ] |
| 129 | + if not claims: |
| 130 | + return |
| 131 | + |
| 132 | + deleted_lines = deleted_lines_path.read_text(encoding="utf-8") if deleted_lines_path.exists() else "" |
| 133 | + if not deleted_lines.strip(): |
| 134 | + print( |
| 135 | + "Release draft analysis claimed removals, but the exact PR diff has no deleted lines:", |
| 136 | + file=sys.stderr, |
| 137 | + ) |
| 138 | + print(breaking_changes_content, file=sys.stderr) |
| 139 | + raise SystemExit(1) |
| 140 | + |
| 141 | + invalid_claims = [ |
| 142 | + f"{line}\n Missing deleted token: {token}" |
| 143 | + for line, token in claims |
| 144 | + if not _token_present(token, deleted_lines) |
| 145 | + ] |
| 146 | + if not invalid_claims: |
| 147 | + return |
| 148 | + |
| 149 | + print("Release draft analysis claimed removals that are not present in the exact PR diff:", file=sys.stderr) |
| 150 | + print("\n".join(invalid_claims), file=sys.stderr) |
| 151 | + raise SystemExit(1) |
| 152 | + |
| 153 | + |
| 154 | +def _validate_diff_was_read(reasoning: str) -> None: |
| 155 | + """Fail if Claude says it could not read the prepared diff.""" |
| 156 | + if not (reasoning and UNREADABLE_DIFF_RE.search(reasoning)): |
| 157 | + return |
| 158 | + print("Release draft analysis could not read the prepared diff; refusing to update the draft.", file=sys.stderr) |
| 159 | + print(reasoning, file=sys.stderr) |
| 160 | + raise SystemExit(1) |
| 161 | + |
| 162 | + |
| 163 | +def main() -> int: |
| 164 | + """Validate Claude output and persist the normalized analysis JSON artifact.""" |
| 165 | + args = _parse_args() |
| 166 | + claude_output = _parse_claude_output(os.environ.get("CLAUDE_OUTPUT", "")) |
| 167 | + has_breaking_changes = _as_bool(claude_output.get("has_breaking_changes", False)) |
| 168 | + breaking_changes_content = _as_string(claude_output.get("breaking_changes_content", "")) |
| 169 | + reasoning = _as_string(claude_output.get("reasoning", "")) |
| 170 | + |
| 171 | + _validate_diff_was_read(reasoning) |
| 172 | + if has_breaking_changes: |
| 173 | + _validate_removal_claims(breaking_changes_content, args.deleted_lines_path) |
| 174 | + |
| 175 | + args.analysis_path.write_text( |
| 176 | + json.dumps( |
| 177 | + { |
| 178 | + "has_breaking_changes": has_breaking_changes, |
| 179 | + "breaking_changes_content": breaking_changes_content, |
| 180 | + "reasoning": reasoning, |
| 181 | + }, |
| 182 | + ensure_ascii=False, |
| 183 | + ) |
| 184 | + + "\n", |
| 185 | + encoding="utf-8", |
| 186 | + ) |
| 187 | + return 0 |
| 188 | + |
| 189 | + |
| 190 | +if __name__ == "__main__": |
| 191 | + raise SystemExit(main()) |
0 commit comments