second-source 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. second_source/__init__.py +3 -0
  2. second_source/action/__init__.py +4 -0
  3. second_source/action/commands.py +88 -0
  4. second_source/action/event.py +89 -0
  5. second_source/action/inputs.py +118 -0
  6. second_source/action/main.py +203 -0
  7. second_source/action/publish.py +184 -0
  8. second_source/action/setup.py +143 -0
  9. second_source/action/sweep.py +85 -0
  10. second_source/action/wait.py +49 -0
  11. second_source/benchmark/__init__.py +1 -0
  12. second_source/benchmark/aidev.py +248 -0
  13. second_source/benchmark/aidev_local.py +85 -0
  14. second_source/benchmark/golden.py +314 -0
  15. second_source/benchmark/redact.py +45 -0
  16. second_source/benchmark/rescore.py +388 -0
  17. second_source/benchmark/runner.py +159 -0
  18. second_source/benchmark/sample.py +243 -0
  19. second_source/benchmark/stats.py +363 -0
  20. second_source/cli/__init__.py +1 -0
  21. second_source/cli/bench.py +427 -0
  22. second_source/cli/main.py +182 -0
  23. second_source/core/__init__.py +4 -0
  24. second_source/core/aggregate.py +102 -0
  25. second_source/core/checks.py +470 -0
  26. second_source/core/engine.py +98 -0
  27. second_source/core/evidence.py +29 -0
  28. second_source/core/expr.py +206 -0
  29. second_source/core/hashing.py +41 -0
  30. second_source/core/model.py +112 -0
  31. second_source/core/pack.py +156 -0
  32. second_source/packs/__init__.py +1 -0
  33. second_source/packs/coding/__init__.py +16 -0
  34. second_source/packs/coding/checks/ci_config_caution.yaml +23 -0
  35. second_source/packs/coding/checks/ci_result.yaml +133 -0
  36. second_source/packs/coding/checks/ci_weakening_caution.yaml +27 -0
  37. second_source/packs/coding/checks/deployed.yaml +36 -0
  38. second_source/packs/coding/checks/docs_updated.yaml +22 -0
  39. second_source/packs/coding/checks/fixes_issue.yaml +58 -0
  40. second_source/packs/coding/checks/fixes_issue_durable.yaml +60 -0
  41. second_source/packs/coding/checks/integrity_guard.yaml +34 -0
  42. second_source/packs/coding/checks/integrity_inspection.yaml +21 -0
  43. second_source/packs/coding/checks/lint_caution.yaml +22 -0
  44. second_source/packs/coding/checks/matching_jobs_caution.yaml +22 -0
  45. second_source/packs/coding/checks/not_reverted.yaml +38 -0
  46. second_source/packs/coding/checks/tests_added.yaml +25 -0
  47. second_source/packs/coding/checks/tests_added_guard.yaml +26 -0
  48. second_source/packs/coding/checks/tests_removed_caution.yaml +23 -0
  49. second_source/packs/coding/detection.py +94 -0
  50. second_source/packs/coding/diff_facts.py +665 -0
  51. second_source/packs/coding/extract.py +911 -0
  52. second_source/packs/coding/functions.py +241 -0
  53. second_source/packs/coding/pack.yaml +33 -0
  54. second_source/packs/coding/trusted_rules.yaml +50 -0
  55. second_source/pipeline.py +112 -0
  56. second_source/report/__init__.py +1 -0
  57. second_source/report/render.py +503 -0
  58. second_source/sources/__init__.py +1 -0
  59. second_source/sources/github/__init__.py +4 -0
  60. second_source/sources/github/auth.py +48 -0
  61. second_source/sources/github/cache.py +67 -0
  62. second_source/sources/github/client.py +261 -0
  63. second_source/sources/github/mappers.py +454 -0
  64. second_source/sources/github/source.py +385 -0
  65. second_source/sources/github/urls.py +51 -0
  66. second_source-0.5.0.dist-info/METADATA +311 -0
  67. second_source-0.5.0.dist-info/RECORD +71 -0
  68. second_source-0.5.0.dist-info/WHEEL +4 -0
  69. second_source-0.5.0.dist-info/entry_points.txt +2 -0
  70. second_source-0.5.0.dist-info/licenses/LICENSE +202 -0
  71. second_source-0.5.0.dist-info/licenses/NOTICE +9 -0
@@ -0,0 +1,665 @@
1
+ """Integrity facts from a file's unified diff: counts, never code.
2
+
3
+ GitHub's `/pulls/N/files` returns each file's `patch`. Second Source never stores code, so the
4
+ GitHub mapper passes the patch through ``facts`` and keeps only the numbers it returns. The
5
+ integrity guards (checks/*_guard.yaml) read those numbers to spot a PR that shaped its own
6
+ evidence: skipped or removed tests, a weakened test command, a lowered coverage gate.
7
+
8
+ Every pattern is deliberately narrow (design: private/research/integrity-design-comparison.md):
9
+
10
+ - **Skips** count only *unconditional, declaration-level* markers (``@pytest.mark.skip``,
11
+ ``it.skip("…"``, ``#[ignore]``, ``@Disabled``). Runtime skips (``pytest.skip(``,
12
+ ``t.Skip(``) are excluded: in a sample of agent PRs most of them were legitimate environment
13
+ guards ("no GPU"). ``.only`` / ``fit`` count, because they silently skip every other test.
14
+ - **Weakened test commands** (``continue-on-error: true``, ``|| true``, ``--deselect``,
15
+ ``-k "not …"``) count only within a few lines of a test command in the same hunk.
16
+ - **Coverage gates** count only when one hunk removes and adds the same key, in the config file
17
+ that owns it, with a weaker number (lower, or higher for Codecov's allowed drop).
18
+
19
+ Lines are matched on ``+`` / ``-`` lines inside hunks.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import hashlib
25
+ import re
26
+ from pathlib import Path
27
+ from typing import Any
28
+
29
+ from second_source.packs.coding.functions import (
30
+ is_ci_path,
31
+ is_lint_config_path,
32
+ is_test_config_path,
33
+ is_test_path,
34
+ )
35
+
36
+ # Which code produced a record's diff counts: a fingerprint of this module and the path rules
37
+ # it uses. Counts are made once, when the patch is read, and the patch is never stored, so a
38
+ # re-score can trust stored counts only when the fingerprint matches (benchmark/rescore.py).
39
+ FACTS_VERSION = hashlib.sha256(
40
+ b"".join(
41
+ (Path(__file__).parent / name).read_bytes() for name in ("diff_facts.py", "functions.py")
42
+ )
43
+ ).hexdigest()[:12]
44
+
45
+ MAX_MARKER_LINES = 5 # new-file line numbers kept for links into the diff
46
+
47
+ # ---- languages ------------------------------------------------------------------------------
48
+
49
+ _LANGUAGES = {
50
+ "py": "python",
51
+ "js": "js", "jsx": "js", "ts": "js", "tsx": "js", "mjs": "js", "cjs": "js",
52
+ "mts": "js", "cts": "js",
53
+ "go": "go",
54
+ "rs": "rust",
55
+ "java": "jvm", "kt": "jvm", "kts": "jvm", "scala": "jvm",
56
+ "cs": "csharp",
57
+ "rb": "ruby",
58
+ "php": "php",
59
+ } # fmt: skip
60
+
61
+
62
+ def language_of(path: str) -> str | None:
63
+ extension = path.rsplit(".", 1)[-1].lower() if "." in path else ""
64
+ return _LANGUAGES.get(extension)
65
+
66
+
67
+ # ---- patterns per language (applied to the text after the leading "+" or "-") ---------------
68
+
69
+ _Q = r"""['"`]""" # a string literal starts here: "it.skip('name'" but not "it.skip()"
70
+
71
+ # Declaration-level markers, anchored at the start of the line (after an optional "await"), so
72
+ # a marker inside a comment or a string ("code: \"describe.skip('x')\"") does not count. A
73
+ # Python decorator must end the line, may carry a trailing comment, or may open a multi-line
74
+ # argument list ("@pytest.mark.skip(" then "reason=…"); prose such as "@pytest.mark.skip is used
75
+ # for…" in a docstring is none of these.
76
+ _PY_DECORATOR_END = r"\s*(\(.*)?\s*(#.*)?$"
77
+ _SKIP = {
78
+ "python": re.compile(
79
+ rf"^\s*@(pytest\.)?mark\.(skip|xfail)\b(?!if){_PY_DECORATOR_END}"
80
+ rf"|^\s*@unittest\.(skip\b(?!If|Unless)|expectedFailure)\b{_PY_DECORATOR_END}"
81
+ r"|^\s*pytestmark\s*=.*\bpytest\.mark\.(skip|xfail)\b(?!if)"
82
+ ),
83
+ "js": re.compile(
84
+ rf"^\s*(await\s+)?(test\.)?(it|test|describe|context|suite|specify)\.(skip|only|fixme)"
85
+ rf"(\.each\b.*)?\s*\(\s*{_Q}"
86
+ rf"|^\s*(await\s+)?test\.fixme\s*\(\s*{_Q}"
87
+ rf"|^\s*(await\s+)?(xit|xdescribe|xtest|xcontext|fit|fdescribe)\s*\(\s*{_Q}"
88
+ ),
89
+ "rust": re.compile(r"^\s*#\[ignore\b"),
90
+ "jvm": re.compile(r"^\s*@(Disabled|Ignore)\b"),
91
+ "csharp": re.compile(r"^\s*\[\s*(Ignore|Skip)\b|\b(Fact|Theory)\s*\(\s*Skip\s*="),
92
+ "ruby": re.compile(r"^\s*(xit|xdescribe|xcontext)\b"),
93
+ }
94
+ # Skip markers that also declare the test on the same line ("it.skip('x', …)", "xit('x'",
95
+ # "[Fact(Skip = …)]"). In Python, Java, Rust and C# attributes the marker is a separate line from
96
+ # the declaration, so only these forms count as a test case themselves.
97
+ _JS_SUITE_SKIP = re.compile(
98
+ r"^\s*(await\s+)?(test\.)?(describe|context|suite)\.skip\b|^\s*(await\s+)?(xdescribe|xcontext)\s*\("
99
+ )
100
+ _PYTESTMARK = re.compile(r"^\s*pytestmark\s*=")
101
+ # Lines that belong to a group's header, at the group's own indentation: decorators and
102
+ # annotations stacked above it, the class line, and the opening describe line.
103
+ _GROUP_HEADER = re.compile(
104
+ r"^\s*(@|(public\s+|final\s+|abstract\s+)*class\s|(await\s+)?(test\.)?(describe|context|suite)\b"
105
+ r"|(xdescribe|xcontext)\b)"
106
+ )
107
+ _PY_SELF_TEST = re.compile(r"\b(pytester|testdir)\.(makepyfile|makefile|inline_run|runpytest)\b")
108
+ _DECLARING_SKIP = {
109
+ # Suites (describe/context/suite) are not test cases.
110
+ "js": re.compile(
111
+ rf"^\s*(await\s+)?(test\.)?(it|test|specify)\.(skip|only|fixme)(\.each\b.*)?\s*\(\s*{_Q}"
112
+ rf"|^\s*(await\s+)?test\.fixme\s*\(\s*{_Q}"
113
+ rf"|^\s*(await\s+)?(xit|xtest|fit)\s*\(\s*{_Q}"
114
+ ),
115
+ "csharp": re.compile(r"\b(Fact|Theory)\s*\(\s*Skip\s*="),
116
+ "ruby": re.compile(r"^\s*xit\b"),
117
+ }
118
+ # Tests of a test framework write skip markers inside strings on purpose. Python: markers inside
119
+ # a triple-quoted string are ignored (tracked per hunk). JS: files using ESLint's RuleTester.
120
+ _JS_SELF_TEST = re.compile(r"\bRuleTester\b")
121
+ _TRIPLE_QUOTE = re.compile(r"\"\"\"|\'\'\'")
122
+ _COMMENT_LINE = re.compile(r"^\s*(//|/\*|\*|#(?!\[))") # Rust attributes start with "#["
123
+
124
+ _TEST_CASE = {
125
+ "python": re.compile(r"^\s*(async\s+)?def\s+test\w*\s*\("),
126
+ "js": re.compile(rf"(^|[^.\w])(it|test)\s*\(\s*{_Q}"),
127
+ "go": re.compile(r"^func\s+(Test|Fuzz)\w*\s*\("),
128
+ "rust": re.compile(r"#\[(\w+::)?test\b"),
129
+ "jvm": re.compile(r"@(Test|ParameterizedTest|RepeatedTest)\b"),
130
+ "csharp": re.compile(r"\[(Fact|Theory|Test|TestMethod|TestCase)\b"),
131
+ "ruby": re.compile(r"""^\s*(it|specify|test)\s*(\(|['"])"""),
132
+ "php": re.compile(r"function\s+test\w*\s*\(|@test\b"),
133
+ }
134
+
135
+ _ASSERT = re.compile(
136
+ r"\bassert\w*\b|\bexpect\s*\(|\.should\b|\bt\.(Error|Errorf|Fatal|Fatalf|Fail)\b"
137
+ r"|\brequire\.\w+\(|\bassert(_eq|_ne)?!\(|\.to(Be|Equal|Have|Throw|Match|Contain)\w*\("
138
+ r"|\bAssert\.\w+\(|\$this->assert\w+\("
139
+ )
140
+
141
+ # Ways to make CI tolerate failing or missing tests. They count only on the same logical
142
+ # command as a test runner (the same line, or a line continued with a backslash), except
143
+ # continue-on-error, which counts in the same workflow step, or for the whole job when it sits at
144
+ # job level.
145
+ _SAME_COMMAND_WEAKENING = re.compile(
146
+ r"\|\|\s*(true|exit 0|:)\s*(#.*)?$|--passWithNoTests|--collect-only|--deselect\b"
147
+ r"|\s-k\s+['\"]?not\b|\s-m\s+['\"]?not\b|--ignore[= ]|\s--\s+--skip\b|\s-skip\s"
148
+ )
149
+ # Build-tool flags that skip tests. Routine on build-only steps (package an artifact, test
150
+ # elsewhere), so they count only when the PR added them to a command that ran without them
151
+ # (a removed line in the same hunk with the same tool and without the flag).
152
+ _BUILD_SKIP_FLAG = re.compile(r"\s-DskipTests\b|\s-Dmaven\.test\.skip=true|(?<=\S)\s+-x\s+test\b")
153
+ _BUILD_TOOL = re.compile(r"\b(mvnw?|gradlew?)\b")
154
+ _TEST_GOAL = re.compile(r"\b(test|verify|check)\b")
155
+ _CONTINUE_ON_ERROR = re.compile(r"^(\s*)continue-on-error:\s*(true|\$\{\{\s*true\s*\}\})\s*(#.*)?$")
156
+ _YAML_KEY = re.compile(r"^[\w.-]+:\s*(#.*)?$") # a mapping key on its own line (job header)
157
+ _JOB_KEY = re.compile(
158
+ r"^(\s*)(runs-on|steps|needs|strategy):"
159
+ ) # timeout-minutes is also a step key
160
+ _STEP_START = re.compile(r"^(\s*)-\s") # a list item; steps are those at the steps' indentation
161
+ _STEP_KEYS = re.compile(r"^\s*-\s+(name|run|uses):")
162
+ _TEST_COMMAND = re.compile(
163
+ r"\b(pytest|tox|nox|npm (run )?test|yarn test|pnpm (run )?test|jest|vitest|mocha|go test"
164
+ r"|cargo (test|nextest)|mvnw?\b.*\b(test|verify)|gradlew?\b.*\b(test|check)"
165
+ r"|rspec|phpunit|dotnet test|ctest|make (test|check))\b"
166
+ )
167
+ # Installing a test runner is not running it ("pip install pytest").
168
+ _INSTALL = re.compile(
169
+ r"\b(pip3? install|uv (pip install|add|sync)|npm (i|install|ci)\b|yarn add|pnpm (add|install)"
170
+ r"|poetry (add|install)|apt(-get)? install|brew install|cargo install|go install)\b"
171
+ )
172
+ MAX_LINE = 2000 # longer lines (minified or generated) are not read
173
+
174
+ # Files where a test command or a coverage gate can be configured.
175
+ _COMMAND_FILES = re.compile(
176
+ r"(^|/)(\.github/workflows/[^/]+\.ya?ml|\.github/actions/.+\.ya?ml|\.gitlab-ci\.yml|\.circleci/[^/]+|tox\.ini|noxfile\.py"
177
+ r"|pytest\.ini|setup\.cfg|pyproject\.toml|package\.json|makefile|justfile|\.travis\.yml"
178
+ r"|azure-pipelines[^/]*\.ya?ml|codecov\.ya?ml|\.codecov\.ya?ml|\.coveragerc"
179
+ r"|jest\.config\.[cm]?[jt]s|vitest\.config\.[cm]?[jt]s|\.nycrc[^/]*)$",
180
+ re.IGNORECASE,
181
+ )
182
+
183
+ # Coverage gates. A key counts only in the config files that own it, with the number right
184
+ # after it ("fail_under = 90", '"lines": 80', "target: 85%"), so unrelated keys such as a build
185
+ # matrix "target: x86_64-…" never match. Codecov's "threshold" is the allowed *drop*, so for it a
186
+ # higher number is a weaker gate.
187
+ # Possessive whitespace runs: adjacent \s* groups would backtrack quadratically on long
188
+ # blank runs in attacker-written config lines (security review 1, H2).
189
+ _NUMBER = r"""\s*+["']?\s*+[:=]\s*+["']?([0-9]{1,9}(?:\.[0-9]{1,9})?)%?["']?\s*+(?:,|#|$)"""
190
+ _COVERAGE_PY_FILES = re.compile(r"(^|/)(pyproject\.toml|setup\.cfg|\.coveragerc|tox\.ini)$", re.I)
191
+ _JS_COVERAGE_FILES = re.compile(
192
+ r"(^|/)(jest\.config\.[\w.]+|vitest\.config\.[\w.]+|\.nycrc[\w.]*|nyc\.config\.[\w.]+"
193
+ r"|package\.json)$",
194
+ re.I,
195
+ )
196
+ _CODECOV_FILES = re.compile(r"(^|/)\.?codecov\.ya?ml$", re.I)
197
+ # (key name, pattern with the number as group 1, files it applies to, higher number = stricter)
198
+ _GATES = (
199
+ ("fail_under", re.compile(r"^\s*fail[_-]under" + _NUMBER), _COVERAGE_PY_FILES, True),
200
+ (
201
+ "js_threshold",
202
+ re.compile(r"""^\s*["']?(?:branches|lines|functions|statements)["']?""" + _NUMBER),
203
+ _JS_COVERAGE_FILES,
204
+ True,
205
+ ),
206
+ ("codecov_target", re.compile(r"^\s*target" + _NUMBER), _CODECOV_FILES, True),
207
+ ("codecov_threshold", re.compile(r"^\s*threshold" + _NUMBER), _CODECOV_FILES, False),
208
+ )
209
+ # A fail-under flag on a test command, in any file that runs tests.
210
+ _FAIL_UNDER_FLAG = re.compile(r"--(?:cov-)?fail-under[= ](\d+(?:\.\d+)?)")
211
+ # Switching a Codecov status check off (only counts when an existing config is edited).
212
+ _CODECOV_AUTO = re.compile(r"^\s*target:\s*auto\b")
213
+ _COVERAGE_OFF = re.compile(r"^\s*(informational:\s*true|(project|patch):\s*off)\b")
214
+
215
+
216
+ def _gate(path: str, text: str) -> tuple[str, float, bool] | None:
217
+ """(key, number, higher-is-stricter) if the line sets a coverage gate in this file."""
218
+ flag = _FAIL_UNDER_FLAG.search(text)
219
+ if flag:
220
+ return "fail_under", float(flag.group(1)), True # same gate as fail_under in config
221
+ for name, pattern, files, stricter in _GATES:
222
+ if files.search(path):
223
+ found = pattern.search(text)
224
+ if found:
225
+ key = name
226
+ if name == "js_threshold": # one gate per metric
227
+ key += ":" + re.search(r"branches|lines|functions|statements", text).group(0)
228
+ return key, float(found.group(1)), stricter
229
+ return None
230
+
231
+
232
+ # Lint suppressions added in non-test code (a caution for "lint passes").
233
+ _LINT_SUPPRESSION = re.compile(
234
+ r"#\s*noqa\b|#\s*type:\s*ignore|//\s*@ts-(ignore|expect-error|nocheck)|eslint-disable"
235
+ r"|#!?\[allow\(|//\s*nolint\b|#\s*pylint:\s*disable|@SuppressWarnings|//\s*biome-ignore"
236
+ )
237
+
238
+ _HUNK = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@")
239
+
240
+
241
+ def facts(path: str, status: str, patch: str | None) -> dict[str, Any]:
242
+ """Integrity counts for one changed file. Absent counts mean zero."""
243
+ if patch is None:
244
+ return {"patch_available": False}
245
+ language = language_of(path)
246
+ test_file = is_test_path(path)
247
+ command_file = bool(_COMMAND_FILES.search(path))
248
+ gate_file = command_file or bool(_CODECOV_FILES.search(path) or _JS_COVERAGE_FILES.search(path))
249
+ counts: dict[str, Any] = {"patch_available": True}
250
+ markers: list[int] = []
251
+ js_self_test = language == "js" and bool(_JS_SELF_TEST.search(patch))
252
+ file_wide_suite_skip = False
253
+ # Gate families removed and added in this file. Whether a gate was deleted outright is
254
+ # decided per PR in summarize(): moving fail_under from setup.cfg to pyproject.toml, or from
255
+ # a --cov-fail-under flag into config, is not a deletion.
256
+ file_removed_gates: dict[str, float] = {} # family -> strictest number removed
257
+ file_added_gates: dict[str, float] = {} # family -> weakest number added
258
+
259
+ def bump(key: str, line_number: int | None = None) -> None:
260
+ counts[key] = counts.get(key, 0) + 1
261
+ if line_number is not None and len(markers) < MAX_MARKER_LINES:
262
+ markers.append(line_number)
263
+
264
+ for hunk in _hunks(patch):
265
+ removed_gates: dict[str, tuple[float, bool]] = {}
266
+ added_gates: dict[str, tuple[float, bool]] = {}
267
+ removed_lines = [text for sign, text, _n in hunk if sign == "-"]
268
+ commands = _command_rows(hunk) if command_file else []
269
+ step_of = _step_numbers(hunk) if command_file else []
270
+ steps_with_tests = {step_of[i] for i, is_command in enumerate(commands) if is_command}
271
+ # Inside a Python triple-quoted string? Tracked separately for the old file (context and
272
+ # removed lines) and the new file (context and added lines), so interleaved edits do not
273
+ # confuse the two. A hunk that starts inside a string is not detected (accepted risk);
274
+ # pytester-style hunks are recognised by their calls as a second signal.
275
+ old_in_string = new_in_string = False
276
+ framework_hunk = language == "python" and any(
277
+ _PY_SELF_TEST.search(text) for _s, text, _n in hunk
278
+ )
279
+ # A skipped group (describe.skip, a skipped class) covers the new cases indented under
280
+ # it, until the indentation returns to the group's level.
281
+ group_indent: int | None = None
282
+ group_body = False # seen a line inside the group: a later header starts another group
283
+ for index, (sign, text, new_line) in enumerate(hunk):
284
+ if group_indent is not None and sign != "-" and text.strip():
285
+ if _indent(text) > group_indent:
286
+ group_body = True
287
+ elif group_body or not _GROUP_HEADER.match(text):
288
+ group_indent = None
289
+ starts_in_string = old_in_string if sign == "-" else new_in_string
290
+ if language == "python" and len(_TRIPLE_QUOTE.findall(text)) % 2:
291
+ if sign != "+":
292
+ old_in_string = not old_in_string
293
+ if sign != "-":
294
+ new_in_string = not new_in_string
295
+ if sign == " " or len(text) > MAX_LINE:
296
+ continue
297
+ text = _squeezed(text)
298
+ if test_file and language and not _COMMENT_LINE.match(text) and not starts_in_string:
299
+ skip = (
300
+ not js_self_test
301
+ and not framework_hunk
302
+ and language in _SKIP
303
+ and bool(_SKIP[language].search(text))
304
+ )
305
+ if skip:
306
+ bump("test_skips_added" if sign == "+" else "test_skips_removed", new_line)
307
+ if sign == "+" and _is_suite_skip(language, text, hunk, index):
308
+ bump("suite_skips_added")
309
+ if language == "python" and _PYTESTMARK.search(text):
310
+ file_wide_suite_skip = True
311
+ else:
312
+ group_indent, group_body = _indent(text), False
313
+ # A test case is a declaration; a skip marker counts as one only when it declares
314
+ # the test on the same line ("it.skip('x', …)"), not as a separate decorator.
315
+ declares_skip = (
316
+ skip
317
+ and language in _DECLARING_SKIP
318
+ and bool(_DECLARING_SKIP[language].search(text))
319
+ )
320
+ if declares_skip or (language in _TEST_CASE and _TEST_CASE[language].search(text)):
321
+ bump("test_cases_added" if sign == "+" else "test_cases_removed")
322
+ if sign == "+" and group_indent is not None and _indent(text) > group_indent:
323
+ bump("suite_skipped_cases")
324
+ if _ASSERT.search(text):
325
+ bump("asserts_added" if sign == "+" else "asserts_removed")
326
+ if sign == "+" and not test_file and language and _LINT_SUPPRESSION.search(text):
327
+ bump("lint_suppressions_added")
328
+ if command_file and sign == "+":
329
+ # The test command itself weakened: withdraws "tests pass".
330
+ if commands[index] and _SAME_COMMAND_WEAKENING.search(text):
331
+ bump("test_cmd_weakened", new_line)
332
+ # continue-on-error on the test step itself, and a test-skipping flag added to a
333
+ # test/verify/check command, are as narrow as the line-level signals: they
334
+ # withdraw. Job-level tolerance and flags on build/package/deploy commands are
335
+ # cautions until benchmark run 2 measures them.
336
+ tolerated = _tolerates_failures(
337
+ text, index, hunk, commands, step_of, steps_with_tests
338
+ )
339
+ if tolerated == "step":
340
+ bump("test_cmd_weakened", new_line)
341
+ elif tolerated == "job":
342
+ bump("ci_failures_tolerated", new_line)
343
+ build_skip = _skips_tests_in_build(text, removed_lines)
344
+ if build_skip == "test_goal":
345
+ bump("test_cmd_weakened", new_line)
346
+ elif build_skip == "other_goal":
347
+ bump("build_tests_skipped", new_line)
348
+ if gate_file:
349
+ gate = _gate(path, text)
350
+ if gate:
351
+ key, number, stricter = gate
352
+ (removed_gates if sign == "-" else added_gates)[key] = (number, stricter)
353
+ _keep(
354
+ file_removed_gates if sign == "-" else file_added_gates,
355
+ key,
356
+ number,
357
+ strictest=sign == "-",
358
+ stricter=stricter,
359
+ )
360
+ off = sign == "+" and _CODECOV_FILES.search(path) and _COVERAGE_OFF.search(text)
361
+ # A first Codecov config lowers nothing; switching a status off in an existing
362
+ # one does, as does replacing a target number with "auto".
363
+ auto = (
364
+ sign == "+" and _CODECOV_AUTO.search(text) and "codecov_target" in removed_gates
365
+ )
366
+ if (off and status != "added") or auto:
367
+ counts["coverage_gate_lowered"] = True
368
+ if sign == "+" and text.strip():
369
+ counts["nonblank_added"] = counts.get("nonblank_added", 0) + 1
370
+ for key, (number, stricter) in added_gates.items():
371
+ if key in removed_gates:
372
+ before = removed_gates[key][0]
373
+ if (number < before) if stricter else (number > before):
374
+ counts["coverage_gate_lowered"] = True
375
+ if file_wide_suite_skip:
376
+ # A module-level pytestmark skip covers every new case of the file.
377
+ counts["suite_skipped_cases"] = counts.get("test_cases_added", 0)
378
+ # Gate families and their numbers (configuration values, not code). A deleted file's gates
379
+ # are left out: removing a whole package or config file is not lowering a gate elsewhere.
380
+ if file_removed_gates and status != "removed":
381
+ counts["gates_removed"] = dict(sorted(file_removed_gates.items()))
382
+ if file_added_gates:
383
+ counts["gates_added"] = dict(sorted(file_added_gates.items()))
384
+ if markers:
385
+ counts["marker_lines"] = markers
386
+ return counts
387
+
388
+
389
+ # Codecov's threshold is the allowed drop: a higher number is a weaker gate.
390
+ _HIGHER_IS_WEAKER = frozenset({"codecov_threshold"})
391
+
392
+
393
+ def _keep(
394
+ gates: dict[str, float], key: str, number: float, *, strictest: bool, stricter: bool
395
+ ) -> None:
396
+ """Keep, per family, the strictest removed number or the weakest added number."""
397
+ if key not in gates:
398
+ gates[key] = number
399
+ return
400
+ higher_is_stricter = stricter
401
+ pick_higher = higher_is_stricter if strictest else not higher_is_stricter
402
+ gates[key] = max(gates[key], number) if pick_higher else min(gates[key], number)
403
+
404
+
405
+ def _gate_weakened(family: str, removed: float | None, added: float | None) -> bool:
406
+ """Across the whole PR: did this gate family get weaker?"""
407
+ if removed is None:
408
+ return False
409
+ if added is None:
410
+ # Deleted and added nowhere. Removing Codecov's allowed drop makes the gate stricter.
411
+ return family not in _HIGHER_IS_WEAKER
412
+ return added > removed if family in _HIGHER_IS_WEAKER else added < removed
413
+
414
+
415
+ _INNER_RUN = re.compile(r"[ \t]{2,}")
416
+
417
+
418
+ def _squeezed(line: str) -> str:
419
+ """The line with runs of spaces after its indentation collapsed. Patterns that start with
420
+ whitespace were retried at every position of a long run (security review 2, N5); the
421
+ indentation itself is kept, because test groups are found by it."""
422
+ body = line.lstrip(" \t")
423
+ return line[: len(line) - len(body)] + _INNER_RUN.sub(" ", body)
424
+
425
+
426
+ def _indent(text: str) -> int:
427
+ return len(text) - len(text.lstrip())
428
+
429
+
430
+ def _is_suite_skip(
431
+ language: str, text: str, hunk: list[tuple[str, str, int | None]], index: int
432
+ ) -> bool:
433
+ """A skip marker that covers a group of tests rather than one test."""
434
+ if language == "js":
435
+ return bool(_JS_SUITE_SKIP.search(text))
436
+ if language == "ruby":
437
+ return bool(re.match(r"^\s*(xdescribe|xcontext)\b", text))
438
+ if language == "python" and _PYTESTMARK.search(text):
439
+ return True
440
+ if language in ("python", "jvm"):
441
+ # The next added, non-blank, non-decorator line declares a class.
442
+ for sign, following, _n in hunk[index + 1 :]:
443
+ if sign == "-" or not following.strip() or following.lstrip().startswith("@"):
444
+ continue
445
+ return bool(re.match(r"^\s*(public\s+|final\s+|abstract\s+)*class\s", following))
446
+ return False
447
+
448
+
449
+ def _tolerates_failures(
450
+ text: str,
451
+ index: int,
452
+ hunk: list[tuple[str, str, int | None]],
453
+ commands: list[bool],
454
+ step_of: list[int],
455
+ steps_with_tests: set[int],
456
+ ) -> str | None:
457
+ """ "step" for an added continue-on-error in the same workflow step as a test command,
458
+ "job" for one at job level in a job (within the hunk) that runs tests, else None."""
459
+ flag = _CONTINUE_ON_ERROR.match(text)
460
+ if not flag:
461
+ return None
462
+ indent = len(flag.group(1))
463
+ job_level = any(len(m.group(1)) == indent for _s, t, _n in hunk if (m := _JOB_KEY.match(t)))
464
+ if not job_level:
465
+ return "step" if step_of[index] in steps_with_tests else None
466
+
467
+ # Job level: look for a test command in the same job only, scanning both ways until a key at
468
+ # a shallower indentation than the job's own keys (the job header, or the next job).
469
+ def job_rows(rows: range) -> list[int]:
470
+ found = []
471
+ for row in rows:
472
+ line = hunk[row][1]
473
+ stripped = line.lstrip()
474
+ if stripped and len(line) - len(stripped) < indent and _YAML_KEY.match(stripped):
475
+ break
476
+ found.append(row)
477
+ return found
478
+
479
+ same_job = job_rows(range(index + 1, len(hunk))) + job_rows(range(index - 1, -1, -1))
480
+ return "job" if any(commands[row] for row in same_job) else None
481
+
482
+
483
+ def _skips_tests_in_build(text: str, removed_lines: list[str]) -> str | None:
484
+ """-DskipTests / -x test added to a command that ran before without it (the same command,
485
+ flag removed, on a removed line of the hunk): "test_goal" when that command tests
486
+ (test/verify/check), "other_goal" for build/package/deploy commands, else None."""
487
+ if not (_BUILD_TOOL.search(text) and _BUILD_SKIP_FLAG.search(text)):
488
+ return None
489
+ stripped = _normalise(_BUILD_SKIP_FLAG.sub(" ", text))
490
+ if not any(_normalise(removed) == stripped for removed in removed_lines):
491
+ return None
492
+ return "test_goal" if _TEST_GOAL.search(stripped) else "other_goal"
493
+
494
+
495
+ def _normalise(command: str) -> str:
496
+ return " ".join(command.split())
497
+
498
+
499
+ def _command_rows(hunk: list[tuple[str, str, int | None]]) -> list[bool]:
500
+ """Per row: is it (part of) a test command? A line continued with a backslash belongs to
501
+ the command it continues, so "pytest \\" then " --deselect x" is one command."""
502
+ rows: list[bool] = []
503
+ continuing = False
504
+ for _sign, text, _line in hunk:
505
+ own = bool(_TEST_COMMAND.search(text)) and not _INSTALL.search(text)
506
+ rows.append(own or continuing)
507
+ continuing = (own or continuing) and text.rstrip().endswith("\\")
508
+ return rows
509
+
510
+
511
+ def _step_numbers(hunk: list[tuple[str, str, int | None]]) -> list[int]:
512
+ """Per row: the workflow step it belongs to. Steps start at list items at the indentation
513
+ of the first item after a "steps:" line (so a matrix "include: - name:" or a "- --fix"
514
+ inside a step's with: does not start a step). Without a "steps:" line in the hunk, the
515
+ first item with name:/run:/uses: sets the indentation."""
516
+ indent = None
517
+ after_steps = False
518
+ for _sign, text, _line in hunk:
519
+ if re.match(r"^\s*steps:\s*$", text):
520
+ after_steps = True
521
+ continue
522
+ item = _STEP_START.match(text)
523
+ if item and after_steps:
524
+ indent = len(item.group(1))
525
+ break
526
+ if indent is None:
527
+ indent = next(
528
+ (
529
+ len(m.group(1))
530
+ for _s, text, _n in hunk
531
+ if (m := _STEP_START.match(text)) and _STEP_KEYS.search(text)
532
+ ),
533
+ None,
534
+ )
535
+ numbers: list[int] = []
536
+ step = 0
537
+ for _sign, text, _line in hunk:
538
+ item = _STEP_START.match(text)
539
+ if item and (indent is None or len(item.group(1)) == indent):
540
+ step += 1
541
+ numbers.append(step)
542
+ return numbers
543
+
544
+
545
+ def _hunks(patch: str) -> list[list[tuple[str, str, int | None]]]:
546
+ """Split a unified diff into hunks of (sign, text, new-file line number or None)."""
547
+ hunks: list[list[tuple[str, str, int | None]]] = []
548
+ new_line = 0
549
+ # split("\n"), not splitlines(): a form feed or a Unicode line separator inside a line is
550
+ # content, and must not create a fabricated diff line.
551
+ for raw in (line.removesuffix("\r") for line in patch.split("\n")):
552
+ header = _HUNK.match(raw)
553
+ if header:
554
+ hunks.append([])
555
+ new_line = int(header.group(1))
556
+ continue
557
+ # GitHub's patch starts at the first hunk (no file headers), so a removed SQL comment
558
+ # ("--- x") is content, not a header. "" is metadata.
559
+ if not hunks or raw.startswith("\\"):
560
+ continue
561
+ sign, text = raw[:1], raw[1:]
562
+ if sign == "+":
563
+ hunks[-1].append(("+", text, new_line))
564
+ new_line += 1
565
+ elif sign == "-":
566
+ hunks[-1].append(("-", text, None))
567
+ else:
568
+ hunks[-1].append((" ", text, new_line))
569
+ new_line += 1
570
+ return hunks
571
+
572
+
573
+ # ---- one PR-level summary -------------------------------------------------------------------
574
+ # CEL has no sum(), so the guards read one record with the PR's totals instead of adding up
575
+ # per-file counts in YAML.
576
+
577
+
578
+ def summarize(files: list[dict[str, Any]]) -> dict[str, Any]:
579
+ """PR-level totals over per-file records (path, status, additions, deletions + facts)."""
580
+ total: dict[str, Any] = {
581
+ "files": len(files),
582
+ "test_skips_net": 0,
583
+ "test_cases_added": 0,
584
+ "test_cases_removed": 0,
585
+ "asserts_added": 0,
586
+ "test_cmd_weakened": 0,
587
+ "ci_failures_tolerated": 0, # continue-on-error on a test step or test job
588
+ "build_tests_skipped": 0, # -DskipTests / -x test added to an existing command
589
+ "suite_skipped_cases": 0, # new test cases in files that skip a whole group
590
+ "lint_suppressions_added": 0,
591
+ "removed_test_files": 0,
592
+ "test_source_changed": 0, # test files in a known language with added lines
593
+ "code_net": 0, # added minus deleted lines in non-test source files
594
+ "code_removed": False, # a non-test source file was deleted
595
+ "coverage_gate_lowered": False,
596
+ "ci_config_changed": False,
597
+ "lint_config_changed": False,
598
+ "uninspected": 0, # test, CI or test-config files GitHub sent no patch for
599
+ }
600
+ changed_ci: list[str] = []
601
+ gates_removed: dict[str, float] = {}
602
+ gates_added: dict[str, float] = {}
603
+ for file in files:
604
+ for family, number in dict(file.get("gates_removed") or {}).items():
605
+ _keep(
606
+ gates_removed,
607
+ family,
608
+ number,
609
+ strictest=True,
610
+ stricter=family not in _HIGHER_IS_WEAKER,
611
+ )
612
+ for family, number in dict(file.get("gates_added") or {}).items():
613
+ _keep(
614
+ gates_added,
615
+ family,
616
+ number,
617
+ strictest=False,
618
+ stricter=family not in _HIGHER_IS_WEAKER,
619
+ )
620
+ path, status = file["path"], file.get("status", "modified")
621
+ test_file = is_test_path(path)
622
+ config = is_ci_path(path) or is_test_config_path(path)
623
+ if config:
624
+ total["ci_config_changed"] = True
625
+ changed_ci.append(path)
626
+ if is_lint_config_path(path):
627
+ total["lint_config_changed"] = True
628
+ # A record without facts (an old snapshot) was not inspected: never read it as clean.
629
+ if (test_file or config) and not file.get("patch_available", False):
630
+ total["uninspected"] += 1
631
+ if test_file:
632
+ if status == "removed":
633
+ total["removed_test_files"] += 1
634
+ elif language_of(path) and file.get("additions", 0) > 0:
635
+ total["test_source_changed"] += 1
636
+ elif language_of(path):
637
+ total["code_net"] += file.get("additions", 0) - file.get("deletions", 0)
638
+ if status == "removed":
639
+ total["code_removed"] = True
640
+ total["test_skips_net"] += file.get("test_skips_added", 0) - file.get(
641
+ "test_skips_removed", 0
642
+ )
643
+ for key in (
644
+ "test_cases_added",
645
+ "test_cases_removed",
646
+ "asserts_added",
647
+ "test_cmd_weakened",
648
+ "ci_failures_tolerated",
649
+ "build_tests_skipped",
650
+ "suite_skipped_cases",
651
+ "lint_suppressions_added",
652
+ ):
653
+ total[key] += file.get(key, 0)
654
+ if file.get("coverage_gate_lowered"):
655
+ total["coverage_gate_lowered"] = True
656
+ # A gate moved between files keeps its family; it is weakened only if it was deleted
657
+ # outright or re-added with a weaker number (setup.cfg 90 -> pyproject.toml 50).
658
+ if any(
659
+ _gate_weakened(family, number, gates_added.get(family))
660
+ for family, number in gates_removed.items()
661
+ ):
662
+ total["coverage_gate_lowered"] = True
663
+ if changed_ci:
664
+ total["ci_config_files"] = sorted(changed_ci)[:5]
665
+ return total