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,911 @@
1
+ """Rule-based claim extraction for coding agents.
2
+
3
+ Turns PR text (title, body, commit messages, agent comments) into ``Claim`` objects such as
4
+ "TESTS_PASS at commit abc123". No AI model is used: deterministic patterns keep results
5
+ cheap, reproducible and resistant to prompt injection.
6
+
7
+ Guiding rule: **precision over recall.** If a sentence might be a plan, a question, a hedge
8
+ or a negation, it is skipped. A missed claim is far less harmful than a claim the agent never
9
+ made, because that claim could then be "contradicted" unfairly.
10
+
11
+ Pipeline per text source:
12
+
13
+ clean -> split into clauses -> drop non-assertions -> match patterns -> Claims
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import re
19
+ from collections.abc import Iterator, Sequence
20
+ from dataclasses import dataclass, replace
21
+ from datetime import datetime
22
+ from functools import lru_cache
23
+ from pathlib import Path
24
+ from typing import Any
25
+
26
+ import yaml
27
+
28
+ from second_source.core.hashing import sha256_hex
29
+ from second_source.core.model import Claim
30
+ from second_source.packs.coding.functions import (
31
+ is_build_check,
32
+ is_doc_path,
33
+ is_lint_check,
34
+ is_test_check,
35
+ is_test_path,
36
+ )
37
+
38
+ # Claim type names (kept as constants so typos fail loudly in tests and code).
39
+ TESTS_PASS = "TESTS_PASS"
40
+ BUILD_OK = "BUILD_OK"
41
+ LINT_OK = "LINT_OK"
42
+ TESTS_ADDED = "TESTS_ADDED"
43
+ FIXES_ISSUE = "FIXES_ISSUE"
44
+ DOCS_UPDATED = "DOCS_UPDATED"
45
+ DEPLOYED = "DEPLOYED"
46
+ MERGE_HOLDS = "MERGE_HOLDS"
47
+
48
+ MAX_SPAN = 200 # characters of supporting text kept on each claim
49
+ # Text read per source. PR bodies are at most 65,536 characters on GitHub, but commit messages
50
+ # and comments are not bounded; claims sit near the top of what agents write. Every pattern
51
+ # below is linear or near-linear in its input, and this cap bounds the rest (security review 1,
52
+ # H2: PR text is attacker-controlled).
53
+ MAX_TEXT = 20_000
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class TextSource:
58
+ """One piece of PR text, with when it was written and which commit it refers to."""
59
+
60
+ origin: str # "title" | "body" | "commit" | "comment"
61
+ text: str
62
+ written_at: datetime
63
+ ref: str | None = None # PR head commit when written (for a commit message: that commit)
64
+ # For editable texts (title, body): the PR head when the text was read, if it differs from
65
+ # ``ref``. The text may have been edited up to then, so either commit could be meant.
66
+ final_ref: str | None = None
67
+ final_at: datetime | None = None # when ``final_ref`` was committed (CI starts from then)
68
+
69
+
70
+ # --------------------------------------------------------------------------------------------
71
+ # Step 1: cleaning. Remove text that is not the agent's own statement.
72
+ # --------------------------------------------------------------------------------------------
73
+
74
+ _INLINE_CODE = re.compile(r"`[^`\n]*`")
75
+ # [ \t], not \s: a quote marker must not let the pattern run across blank lines.
76
+ _QUOTED_LINE = re.compile(r"^[ \t]*>.*$", re.MULTILINE)
77
+
78
+ # Review bots (CodeRabbit, Cursor Bugbot) append summaries to the PR body between marker
79
+ # comments. Those are the bot's words about the change, not the agent's claims. (start, end);
80
+ # the span runs on past ``end`` to the next "-->".
81
+ _BOT_MARKERS = (
82
+ (r"<!--\s*this is an auto-generated comment", r"<!--\s*end of auto-generated comment"),
83
+ (r"<!--\s*cursor_summary", r"<!--\s*/cursor_summary"),
84
+ )
85
+ _HORIZONTAL_RUN = re.compile(r"[ \t\f\v\u00a0]{2,}")
86
+ _BLANK_LINES = re.compile(r"\n(?:[ \t]*\n){2,}")
87
+
88
+
89
+ def squeeze(text: str) -> str:
90
+ """Collapse runs of spaces and tabs to one space, and of blank lines to one blank line.
91
+
92
+ Whitespace runs carry no meaning in a claim, but a pattern that starts with whitespace is
93
+ retried at every position of a run, so long runs made matching quadratic or worse
94
+ (security review 2, N1 and N5). Squeezing first bounds every pattern by the text's words.
95
+ """
96
+ return _BLANK_LINES.sub("\n\n", _HORIZONTAL_RUN.sub(" ", text.replace("\r\n", "\n")))
97
+
98
+
99
+ def _remove_between(text: str, start: str, end: str, *, end_until: str = "") -> str:
100
+ """Remove every span from regex ``start`` to regex ``end`` (case-insensitive), in one
101
+ left-to-right pass; with ``end_until`` the span runs on past ``end`` to that literal.
102
+
103
+ Linear time, unlike a lazy ``.*?`` regex, which rescans to the end of the text for every
104
+ start marker that is never closed. An unclosed span, or one whose ``end_until`` never
105
+ comes, is kept, as the regexes kept it. Searching the text itself (not a lower-cased copy,
106
+ whose length can differ: "İ") keeps the positions right.
107
+ """
108
+ starts, ends = re.compile(start, re.IGNORECASE), re.compile(end, re.IGNORECASE)
109
+ out, position = [], 0
110
+ while (begin := starts.search(text, position)) is not None:
111
+ close = ends.search(text, begin.end())
112
+ if close is None:
113
+ break
114
+ stop = close.end()
115
+ if end_until:
116
+ found = text.find(end_until, stop)
117
+ if found == -1:
118
+ break
119
+ stop = found + len(end_until)
120
+ out += [text[position : begin.start()], " "]
121
+ position = stop
122
+ out.append(text[position:])
123
+ return "".join(out)
124
+
125
+
126
+ def without_blocks(text: str) -> str:
127
+ """Drop bot sections, code blocks, HTML comments and quoted lines; keep inline code."""
128
+ for start, end in _BOT_MARKERS:
129
+ text = _remove_between(text, start, end, end_until="-->")
130
+ for fence in ("```", "~~~"):
131
+ text = _remove_between(text, re.escape(fence), re.escape(fence))
132
+ text = _remove_between(text, "<!--", "-->")
133
+ return _QUOTED_LINE.sub(" ", text)
134
+
135
+
136
+ def prepared(text: str) -> str:
137
+ """The part of a text that extraction reads: whitespace squeezed, blocks removed, then at
138
+ most ``MAX_TEXT`` characters. Cutting after removing blocks means a long body can never
139
+ leave a bot section open and have the bot's words credited to the agent."""
140
+ return without_blocks(squeeze(text))[:MAX_TEXT]
141
+
142
+
143
+ def clean(text: str) -> str:
144
+ """Drop everything that is not the agent's own prose: bot sections, code, HTML comments
145
+ and quoted lines (quotes are someone else's words)."""
146
+ return _INLINE_CODE.sub(" ", without_blocks(squeeze(text)))
147
+
148
+
149
+ # --------------------------------------------------------------------------------------------
150
+ # Step 2: clauses. Each line, sentence and checklist item is judged on its own.
151
+ # --------------------------------------------------------------------------------------------
152
+
153
+ _CHECKBOX = re.compile(r"^\s*+(?:[-*+]|\d+[.)])?\s*+\[( |x|X)\]\s*(.*)$")
154
+ _BULLET = re.compile(r"^\s*(?:[-*+]|\d+[.)])\s+")
155
+ _SENTENCE_END = re.compile(r"(?<=[.!;])\s+")
156
+ # Where one statement ends and an independent one starts inside a sentence, so a negation in
157
+ # the second part cannot cancel the first: "tests pass but integration tests had issues",
158
+ # "verified that tests pass and no other usages exist". Plain "and" is not split, because
159
+ # "tests and lint pass" is one statement about both.
160
+ # A relative clause after a comma describes something else ("fixes bug #12, where the plugin
161
+ # would misapply filters"), so it is judged on its own too.
162
+ _CLAUSE_BREAK = re.compile(
163
+ r",?\s++but\s+|\s++and\s++(?=(?:no|not|none|nothing|never)\b)|,\s++(?=(?:where|which|when)\b)"
164
+ )
165
+
166
+
167
+ # A Markdown heading ("## Local testing") or a line that is only bold text, possibly as a list
168
+ # item ("**Testing:**", "1. **New Files**:").
169
+ # Matched on a right-stripped line, so no trailing-whitespace backtracking is possible.
170
+ _HEADING = re.compile(
171
+ r"^\s*+(?:#{1,6}\s++(?P<hash>\S.*)|(?:(?:[-*+]|\d+[.)])\s++)?\*\*(?P<bold>[^*]+)\*\*:?)$"
172
+ )
173
+
174
+
175
+ def heading_of(line: str) -> str | None:
176
+ """The heading text if ``line`` is a heading, else None."""
177
+ found = _HEADING.match(line.rstrip())
178
+ return None if found is None else (found.group("hash") or found.group("bold")).strip()
179
+
180
+
181
+ def clauses(text: str) -> Iterator[str]:
182
+ """Yield candidate clauses (see ``clauses_in_sections``)."""
183
+ for clause, _heading in clauses_in_sections(text):
184
+ yield clause
185
+
186
+
187
+ def clauses_in_sections(text: str) -> Iterator[tuple[str, str]]:
188
+ """Yield (clause, heading of the section it is in). Unchecked checklist items are dropped
189
+ here: ``- [ ] Tests pass`` is a to-do, not a claim."""
190
+ heading = ""
191
+ for line in text.splitlines():
192
+ heading = heading_of(line) or heading
193
+ box = _CHECKBOX.match(line)
194
+ if box:
195
+ if box.group(1) == " ":
196
+ continue
197
+ line = box.group(2)
198
+ line = _BULLET.sub("", line).strip()
199
+ for sentence in _SENTENCE_END.split(line):
200
+ for part in _CLAUSE_BREAK.split(sentence):
201
+ part = part.strip(" \t-*#:|")
202
+ if part:
203
+ yield part, heading
204
+
205
+
206
+ # --------------------------------------------------------------------------------------------
207
+ # Step 3: drop clauses that are not plain assertions.
208
+ # --------------------------------------------------------------------------------------------
209
+
210
+ # Plans, hedges, quantifiers, conditions and negations. Any of these disqualifies the clause.
211
+ _NOT_AN_ASSERTION = re.compile(
212
+ # plans and conditions
213
+ r"\b(will|would|should|could|might|may|need to|needs to|todo|to do|not yet|once|unless|"
214
+ r"until|hopefully|probably|expected to|supposed to|wip|pending|"
215
+ # negations
216
+ r"not|no|none|nothing|without|never|no longer|cannot|can't|"
217
+ # failure words
218
+ r"fail|fails|failing|failed|failure|broken|flaky|"
219
+ # partial or quantified statements ("most tests pass" is not "tests pass")
220
+ r"partially|partial|related|most|mostly|some|several|few|majority|except|excluding|"
221
+ r"apart from|"
222
+ r"where applicable)\b"
223
+ r"|n't\b"
224
+ )
225
+ # A partial count ("19/22 tests passing") is a hedge, however positive the wording.
226
+ _COUNT = re.compile(r"\b([0-9]{1,9})\s*+/\s*+([0-9]{1,9})\b")
227
+
228
+ # "No lint errors" or "compiles with no warnings" are positive claims even though they contain
229
+ # "no"; these exact phrases are removed before the negation test so claim patterns can still
230
+ # match them.
231
+ _POSITIVE_NO = re.compile(
232
+ r"\bno\s+((lint|linting|linter|eslint|type)\s+)?(errors|warnings|issues)\b"
233
+ r"|\bwithout\s+(any\s+)?(failures?|errors?|warnings?|issues)\b"
234
+ # "211 pass, 0 fail", "zero warnings"
235
+ r"|\b(0|zero)\s+(fail|fails|failed|failures?|errors?|warnings?|issues)\b"
236
+ )
237
+ # Quoted text names something ("the 'not re-exported' note"); its words are not the agent's
238
+ # own negation or hedge.
239
+ _QUOTED_TEXT = re.compile(r'"[^"\n]*"|“[^”\n]*”')
240
+
241
+
242
+ # "... to ensure / to verify X" says why something was done; X itself is not asserted.
243
+ _PURPOSE = re.compile(
244
+ r"\bto\s+(?:ensure|guarantee|verify|confirm|make sure|check|validate)\b"
245
+ # "... (PR #70996) which added schema tests": a relative clause describing another change.
246
+ r"|\b(?:which|that)\s+(?:had\s+|has\s+)?(?:added|adds|introduced|introduces|created|creates)\b"
247
+ )
248
+
249
+
250
+ def asserted_part(clause: str) -> str:
251
+ """The part of a clause before any purpose phrase or relative clause ("ran tests to ensure
252
+ X" → "ran tests"; "follows #12 which added tests" → "follows #12")."""
253
+ found = _PURPOSE.search(clause.lower())
254
+ return clause if found is None else clause[: found.start()]
255
+
256
+
257
+ # A clause split off at ", which" describes the noun before it, often another PR or commit
258
+ # ("follows #12, which added schema tests"), not this change.
259
+ _RELATIVE_CLAUSE = re.compile(r"^\s*which\b", re.IGNORECASE)
260
+
261
+
262
+ # Conditions: "included tests if applicable", and template lines such as "If this pull request
263
+ # adds new functionality, it includes unit tests" (a rule, not a statement). Issue references
264
+ # are exempt (see is_assertion): "Fixes #42: the app crashes if the token expires" names the
265
+ # issue's subject, and the closing keyword itself is unconditional.
266
+ _CONDITION = re.compile(r"\b(if|whether)\b")
267
+
268
+
269
+ def is_assertion(clause: str, *, conditions_allowed: bool = False) -> bool:
270
+ if clause.rstrip().endswith("?") or _RELATIVE_CLAUSE.match(clause):
271
+ return False
272
+ lowered = _POSITIVE_NO.sub(" ", _QUOTED_TEXT.sub(" ", clause.lower()))
273
+ if any(int(done) < int(total) for done, total in _COUNT.findall(lowered)):
274
+ return False
275
+ if not conditions_allowed and _CONDITION.search(lowered):
276
+ return False
277
+ return not _NOT_AN_ASSERTION.search(lowered)
278
+
279
+
280
+ # --------------------------------------------------------------------------------------------
281
+ # Step 4: patterns per claim type (matched on the lower-cased clause).
282
+ # --------------------------------------------------------------------------------------------
283
+
284
+ _PASS_WORDS = r"(pass|passes|passed|passing|green|succeed|succeeds|succeeded|successful)"
285
+
286
+ # Every rule has a stable name. Claims record the rule that produced them, so precision can be
287
+ # measured per rule on the golden set (``second-source bench rules``) and only rules that hold
288
+ # the precision target are trusted (see TRUSTED_RULES below).
289
+ Rule = tuple[str, re.Pattern[str]]
290
+
291
+
292
+ def _rule(name: str, pattern: str) -> Rule:
293
+ return name, re.compile(pattern)
294
+
295
+
296
+ _PATTERNS: dict[str, tuple[Rule, ...]] = {
297
+ TESTS_PASS: (
298
+ # "(?<!-)" keeps "self-test passed" (a script checking itself) out.
299
+ _rule(
300
+ "tests_pass.plain",
301
+ r"\b(all\s+)?(the\s+)?(existing\s+|new\s+)?(unit\s+|integration\s+|e2e\s+)?"
302
+ r"(?<!-)tests?\s+"
303
+ rf"(are\s+|is\s+|now\s+|still\s+|all\s+)*{_PASS_WORDS}\b",
304
+ ),
305
+ # Quantified subjects with words in between: "All new and existing unit tests for the
306
+ # filters plugin passed", "All 28 existing RWS tests continue passing".
307
+ _rule(
308
+ "tests_pass.quantified",
309
+ r"\b(all|new|existing)\b[^.]{0,40}?(?<!-)\btests?\b[^.]{0,40}?"
310
+ r"\b(passed|pass|passing|continue\s+(to\s+)?pass(ing)?)\b",
311
+ ),
312
+ # "7 tests added (all passing)", "27 tests, all passing".
313
+ _rule(
314
+ "tests_pass.all_passing",
315
+ r"(?<!-)\btests?\b[^.]{0,40}\ball\s+(pass|passing|passed|green)\b",
316
+ ),
317
+ # "Verified compilation and tests", "verified with existing unit tests".
318
+ _rule("tests_pass.verified", r"\bverified\b[^.]{0,40}?\b(tests?|test suite)\b"),
319
+ _rule(
320
+ "tests_pass.suite",
321
+ rf"\b(test suite|test run|tests? run)\s+(is\s+)?(now\s+)?{_PASS_WORDS}\b",
322
+ ),
323
+ # CI as a whole. Bare "checks pass" is too vague ("repo checks pass" may be lint).
324
+ _rule(
325
+ "tests_pass.ci",
326
+ r"\b(ci|all checks|all ci checks|ci checks)\s+(is\s+|are\s+)?(now\s+)?"
327
+ r"(green|passing|pass|passed)\b",
328
+ ),
329
+ _rule(
330
+ "tests_pass.runner_prose",
331
+ r"\b(pytest|jest|vitest|npm test|yarn test|go test|cargo test|mocha|rspec)\b"
332
+ r"[^.]{0,40}\b(pass|passes|passed|passing|green)\b",
333
+ ),
334
+ _rule(
335
+ "tests_pass.tests_and_pass",
336
+ r"\btests?\b[^.]{0,30}\band\s+(they\s+|these\s+|both\s+)?(are\s+|all\s+)*"
337
+ r"(pass|passing|passed)\b",
338
+ ),
339
+ # "✅ Tests" or "✅ Tests pass" as a whole clause; not "✅ Tests added for X".
340
+ _rule(
341
+ "tests_pass.check_mark",
342
+ r"✅\s*(all\s+)?tests?(\s+(pass|passes|passed|passing|green))?\s*[.!]?$",
343
+ ),
344
+ ),
345
+ BUILD_OK: (
346
+ _rule(
347
+ "build_ok.plain",
348
+ r"\b(the\s+)?build\s+(is\s+|now\s+)*"
349
+ r"(passes|passed|passing|succeeds|succeeded|successful|green|ok|works)\b",
350
+ ),
351
+ _rule("build_ok.builds", r"\bbuilds\s+(successfully|cleanly|fine|without errors)\b"),
352
+ _rule(
353
+ "build_ok.compiles",
354
+ r"\b(compiles|compiled)\s+(successfully|cleanly|fine|without (errors|warnings))\b",
355
+ ),
356
+ _rule(
357
+ "build_ok.compilation", rf"\b(compilation|cargo check)\s+(is\s+|now\s+)*{_PASS_WORDS}\b"
358
+ ),
359
+ _rule(
360
+ "build_ok.clean_or_verified",
361
+ r"\b(clean|successful)\s+build\b|\bverified\b[^.]{0,30}?\bcompilation\b",
362
+ ),
363
+ ),
364
+ LINT_OK: (
365
+ _rule(
366
+ "lint_ok.plain",
367
+ r"\b(lint|linting|linter|linters|eslint|ruff|flake8|pylint|clippy)\s+"
368
+ r"(checks?\s+)?(is\s+|are\s+|now\s+)*(passes|passed|passing|clean|green|happy|ok)\b",
369
+ ),
370
+ _rule(
371
+ "lint_ok.no_errors",
372
+ r"\bno\s+(lint|linting|linter|eslint|type)\s+(errors|warnings|issues)\b",
373
+ ),
374
+ # "Docs formatting, markdown lint, link audit, and repo checks pass".
375
+ _rule(
376
+ "lint_ok.lint_list",
377
+ r"\b(lint|linting|linters?|formatting|format checks?)\b[^.]{0,50}?"
378
+ r"\b(pass|passes|passed|passing|clean)\b",
379
+ ),
380
+ _rule(
381
+ "lint_ok.verified", r"\bverified\s+(with|by|using)\s+(the\s+)?(lint|linting|linters?)\b"
382
+ ),
383
+ _rule(
384
+ "lint_ok.type_check_tool", r"\b(type ?check(ing)?|mypy|tsc)\s+(passes|passed|clean)\b"
385
+ ),
386
+ _rule(
387
+ "lint_ok.type_checks",
388
+ rf"\b(typescript|type)\s+checks?\s+(are\s+|now\s+)*{_PASS_WORDS}\b",
389
+ ),
390
+ _rule(
391
+ "lint_ok.zero_errors",
392
+ r"\b(zero|0)\s+(lint|linter|linting)\s+(errors|warnings|issues)\b",
393
+ ),
394
+ ),
395
+ TESTS_ADDED: (
396
+ # "Added 3 new unit tests", "Added comprehensive unit tests", "Added a new E2E test".
397
+ # Up to three describing words may sit between the verb and "tests", but not a
398
+ # preposition: "added support for tests" is not adding tests.
399
+ _rule(
400
+ "tests_added.verb",
401
+ r"\b(added|adds|add|wrote|writes|created|creates|includes|included|introduced|"
402
+ r"introduces)\s+(?:(?!(?:for|to|of|in|with|on|from)\b)[\w-]+\s+){0,3}?"
403
+ r"(tests?|test cases?|test coverage|specs?|assertions|regression coverage)\b"
404
+ # "test metadata", "test scripts", "test data" are not new automated tests, and nor
405
+ # are features or infrastructure named after testing: "added save and test
406
+ # connection functionality", "created test PR #12", "add integration test workflow".
407
+ r"(?!\s+(metadata|data|fixtures?|utilities|utils|helpers?|scripts?|ids?|names?|plans?|"
408
+ r"connections?|prs?|pull requests?|workflows?|apps?|accounts?|users?|environments?|"
409
+ r"servers?|mode|pages?|buttons?|endpoints?|commands?|targets?|jobs?|runners?)\b)",
410
+ ),
411
+ _rule(
412
+ "tests_added.new_for",
413
+ r"\bnew\s+(unit\s+|integration\s+|regression\s+)?tests?\s+(for|covering|to cover)\b",
414
+ ),
415
+ _rule(
416
+ "tests_added.new_count", r"\bnew\W{1,6}\d+\s+(new\s+)?(unit\s+)?tests?\b"
417
+ ), # "**New**: 4 tests"
418
+ _rule(
419
+ "tests_added.coverage",
420
+ r"\b(improved|increased|expanded|extended)\s+(\w+\s+)?test\s+coverage\b",
421
+ ),
422
+ _rule(
423
+ "tests_added.extended_passive",
424
+ r"\btests?\s+(were\s+|have been\s+)?(extended|expanded)\b",
425
+ ),
426
+ _rule("tests_added.added_passive", r"\btests?\s+(were\s+|have been\s+)?added\b"),
427
+ # "11 tests covering all include patterns", "7 proxy integration tests added".
428
+ _rule(
429
+ "tests_added.count",
430
+ r"\b\d+\s+(?:[\w-]+\s+){0,3}?(tests?|test cases)\s+(added|covering|to cover)\b",
431
+ ),
432
+ _rule(
433
+ "tests_added.extended",
434
+ r"\b(extended|expanded)\s+(the\s+)?(tests?|test suite|test coverage)\b",
435
+ ),
436
+ # Changed assertions check new behaviour; plain "updated tests" may be a refactor.
437
+ _rule("tests_added.assertions", r"\bupdated\s+(the\s+)?test\s+assertions\b"),
438
+ ),
439
+ DOCS_UPDATED: (
440
+ # "Updates the source-clickhouse user documentation", "Improves the Entity Cache
441
+ # documentation": up to three describing words before the documentation noun.
442
+ # "Updates the source-clickhouse user documentation", "update progress in TypeScript
443
+ # README", "add a baseline doc": a change verb, then within five words a documentation
444
+ # noun that is not docs tooling ("added logging to the documentation builder").
445
+ _rule(
446
+ "docs_updated.verb",
447
+ r"\b(updated|updates|update|added|adds|add|wrote|write|improved|improves|improve|"
448
+ r"corrected|corrects|correct|rewrote|rewrites|rewrite|expanded|expands|expand|"
449
+ r"refreshed|refreshes|refresh|created|creates|create)\s+(?:[\w-]+\s+){0,5}?"
450
+ r"(docs|documentation|readme|changelog|doc)\b"
451
+ # Docs tooling, inline code docs ("XML doc comments" live in source files and are
452
+ # not documentation files) and other nouns: "doc info", "docs extras".
453
+ r"(?!\s+(builder|build|builds|generator|generation|site|tooling|pipeline|workflow|"
454
+ r"comments?|strings?|blocks?|info|extras?|dependencies|deps|group)\b)",
455
+ ),
456
+ _rule("docs_updated.new", r"\bnew\s+(readme|docs|documentation|design doc|guide)\b"),
457
+ # Documentation files named in plain text: "Update the instructions in AGENTS.md".
458
+ _rule(
459
+ "docs_updated.file",
460
+ r"\b(updated|updates|update|added|adds|created|creates|edited|edits|rewrote|"
461
+ r"rewrites|corrected|corrects|expanded|expands)\b[^.]{0,60}?"
462
+ r"(?<![\w/.-])[\w/.-]+\.(md|mdx|rst|adoc)\b",
463
+ ),
464
+ # "README.md updated", "API docs updated", "documentation and examples updated".
465
+ _rule(
466
+ "docs_updated.passive",
467
+ r"\b(docs|documentation|readme(\.md)?|changelog(\.md)?|news)\b[^.]{0,30}?"
468
+ r"\b(are\s+|is\s+|was\s+|were\s+|have been\s+|has been\s+)?"
469
+ r"(updated|added|improved|refreshed|expanded)\b",
470
+ ),
471
+ ),
472
+ }
473
+
474
+ # Matched separately because they capture values.
475
+ _ISSUE_REF = re.compile(
476
+ r"\b(?:close|closes|closed|fix|fixes|fixed|resolve|resolves|resolved)(?:\s*+:)?\s++"
477
+ r"(?:(?:the\s+)?(?:issue|bug)\s+)?" # "fixes issue #12", "fixes bug #12"
478
+ # GitHub owner and repository names; anything else ("../..") is not a reference.
479
+ r"(?P<repo>[a-z0-9][a-z0-9-]{0,38}/[a-z0-9._-]{1,100})?#(?P<number>[0-9]{1,9})\b",
480
+ re.ASCII,
481
+ )
482
+ _DEPLOY = re.compile(
483
+ r"\b(?:deployed|deploys|shipped)\s+(?:to|on)\s+(?:the\s+)?"
484
+ r"(?P<env>staging|production|prod|preview|dev|development|qa|test)\b"
485
+ )
486
+ _ENVIRONMENT_ALIASES = {"prod": "production", "dev": "development"}
487
+
488
+
489
+ # Phrases saying a check ran on the agent's own machine or sandbox rather than in CI.
490
+ # Matched on the clause and on the heading of its section ("## Local verification").
491
+ _LOCAL_SCOPE = re.compile(
492
+ r"\blocally\b"
493
+ r"|\blocal\s+(run|runs|testing|tests?|verification|validation|checks?|build|environment|"
494
+ r"machine|setup)\b"
495
+ r"|\b(on|in)\s+(my|the|a)\s+(local\s+)?(machine|sandbox|container|dev environment)\b"
496
+ r"|\bsandbox\b"
497
+ )
498
+
499
+ # Claim types that can say where they ran, or that only part of the checks ran.
500
+ _SCOPED_TYPES = frozenset({TESTS_PASS, BUILD_OK, LINT_OK})
501
+
502
+ # A claim about part of the checks: "targeted tests pass", "unit tests for the importer pass",
503
+ # "the 12 new tests pass". CI can corroborate it, but an unrelated failing job (an E2E suite, a
504
+ # different package in a monorepo) does not make it false, so it gets ``scope=subset``.
505
+ # "Unit"/"integration"/"e2e" stay subsets even with "all": CI job names cannot be told apart
506
+ # reliably (a failing "test" job may be the E2E suite). A count or "new" is a subset unless the
507
+ # text says "all" ("All 120 tests pass") or "new and existing".
508
+ _SUBSET_SCOPE = re.compile(
509
+ r"\b(targeted|relevant|affected|specific|selected|focused|unit|integration|e2e|"
510
+ r"end-to-end|smoke)\s+(?:[\w-]+\s+){0,2}?tests?\b"
511
+ r"|(?<!\ball\s)(?<!\band\s)(?<![\d,])\b(new|\d[\d,]*)\s+(?!and\s+existing\b)(?:[\w-]+\s+){0,2}?tests?\b"
512
+ r"|\btests?\s+(for|of|under|covering)\b"
513
+ )
514
+ # Command arguments that select part of a suite: paths, test ids, filters, packages. Arguments
515
+ # that mean "everything" ("go test ./...", "--workspace", "--all") are not selectors.
516
+ _SELECTOR_ARGUMENT = re.compile(
517
+ r"/|::|\.(py|[cm]?[jt]sx?|go|rs|rb|java|kt|cs)\b|^-(k|t|p)$|^--(filter|package|testnamepattern|"
518
+ r"grep|project|scope)\b|^-[a-z]*k$"
519
+ )
520
+ _WHOLE_SUITE_ARGUMENT = re.compile(r"^(\./\.\.\.|\.\.\.|\.|\./|--workspace|--all|-r|--recursive)$")
521
+ # Script runners run the project's own lint script ("npm run lint"); a tool named directly
522
+ # ("biome lint", "ruff check .") is one linter among possibly several CI lint jobs.
523
+ _SCRIPT_RUNNERS = frozenset({"npm", "pnpm", "yarn", "bun", "make", "just", "task", "npx"})
524
+
525
+
526
+ def scope_of(clause: str, heading: str) -> str | None:
527
+ """``local`` for checks run on the agent's machine, ``subset`` for part of the checks."""
528
+ if is_local(clause, heading):
529
+ return "local"
530
+ if _SUBSET_SCOPE.search(clause.lower()):
531
+ return "subset"
532
+ return None
533
+
534
+
535
+ def command_scope(command: str) -> str | None:
536
+ """``subset`` for a command that selects part of a suite or names one lint tool.
537
+
538
+ "pytest tests/test_parser.py" checks one file; "biome lint" checks one linter. Either can
539
+ pass while another CI job of the same kind fails.
540
+ """
541
+ words = command.lower().split()
542
+ if not words:
543
+ return None
544
+ if is_lint_check(command) and words[0] not in _SCRIPT_RUNNERS:
545
+ return "subset"
546
+ arguments = [word for word in words[1:] if not _WHOLE_SUITE_ARGUMENT.match(word)]
547
+ return "subset" if any(_SELECTOR_ARGUMENT.search(word) for word in arguments) else None
548
+
549
+
550
+ def is_local(*texts: str) -> bool:
551
+ """True if any of the texts says the check ran locally (see ``_LOCAL_SCOPE``)."""
552
+ return any(_LOCAL_SCOPE.search(text.lower()) for text in texts)
553
+
554
+
555
+ # Rules whose precision held the target on the golden set's selection split
556
+ # (trusted_rules.yaml, written by `second-source bench rules --select`). Claims they find are
557
+ # marked confidence "high"; all other claims "low". The benchmark headline counts only "high".
558
+ TRUSTED_RULES_FILE = Path(__file__).parent / "trusted_rules.yaml"
559
+ HIGH, LOW = "high", "low"
560
+
561
+
562
+ @lru_cache(maxsize=1)
563
+ def trusted_rules() -> frozenset[tuple[str, str]]:
564
+ """The trusted (claim type, rule) pairs."""
565
+ document = yaml.safe_load(TRUSTED_RULES_FILE.read_text(encoding="utf-8")) or {}
566
+ return frozenset((entry["type"], entry["rule"]) for entry in document.get("trusted", []))
567
+
568
+
569
+ # Rule precision was measured on PR bodies only. Titles, commit messages and comments are a
570
+ # different genre ("test: add test app", "fix: add test"), so a rule's trust does not carry
571
+ # over: claims from those texts stay low confidence until they are labelled and measured.
572
+ MEASURED_ORIGINS = frozenset({"body"})
573
+
574
+
575
+ def confidence_of(claim_type: str, rule: str, origin: str = "body") -> str:
576
+ trusted = origin in MEASURED_ORIGINS and (claim_type, rule) in trusted_rules()
577
+ return HIGH if trusted else LOW
578
+
579
+
580
+ ISSUE_RULE = "fixes_issue.closing_ref"
581
+ DEPLOY_RULE = "deployed.phrase"
582
+ CODE_SENTENCE_RULES = (
583
+ "command.marked",
584
+ "command.prose",
585
+ "changed_file.test",
586
+ "changed_file.doc",
587
+ )
588
+
589
+
590
+ def rule_names() -> list[str]:
591
+ """Every extraction rule name, in definition order."""
592
+ clause_rules = [name for rules in _PATTERNS.values() for name, _pattern in rules]
593
+ return [*clause_rules, ISSUE_RULE, DEPLOY_RULE, *CODE_SENTENCE_RULES]
594
+
595
+
596
+ def _match_clause(
597
+ clause: str, scope: str | None, *, all_rules: bool = False
598
+ ) -> Iterator[tuple[str, dict[str, Any]]]:
599
+ """Yield (claim type, attributes) for every claim found in one clause.
600
+
601
+ Normally one claim per type, from the first rule that matches. With ``all_rules`` every
602
+ matching rule yields, which is what per-rule scoring needs.
603
+ """
604
+ lowered = clause.lower()
605
+
606
+ for claim_type, rules in _PATTERNS.items():
607
+ matched = [name for name, pattern in rules if pattern.search(lowered)]
608
+ # Prefer a trusted rule when several match, so the claim gets the confidence it earned.
609
+ matched.sort(key=lambda name: confidence_of(claim_type, name) != HIGH)
610
+ for name in matched if all_rules else matched[:1]:
611
+ attributes: dict[str, Any] = {"rule": name}
612
+ if scope and claim_type in _SCOPED_TYPES:
613
+ attributes["scope"] = scope
614
+ yield claim_type, attributes
615
+
616
+ for found in _ISSUE_REF.finditer(lowered):
617
+ if found.group("repo") and found.group("repo").split("/")[1] in (".", ".."):
618
+ continue
619
+ issue = int(found.group("number"))
620
+ yield FIXES_ISSUE, {"issue": issue, "repo": found.group("repo") or "", "rule": ISSUE_RULE}
621
+
622
+ for found in _DEPLOY.finditer(lowered):
623
+ env = found.group("env")
624
+ yield DEPLOYED, {"environment": _ENVIRONMENT_ALIASES.get(env, env), "rule": DEPLOY_RULE}
625
+
626
+
627
+ # --------------------------------------------------------------------------------------------
628
+ # Step 4b: sentences that name commands or files in inline code.
629
+ #
630
+ # `clean` removes inline code, so the clause patterns never see it. Real agents put the most
631
+ # checkable statements there, so these sentences are read separately:
632
+ #
633
+ # - **Command results.** "- ✅ `pytest -q`", "`pytest tests/`: 201 passed", "Ran `pnpm tsc`
634
+ # and it completed successfully". A command claims success only when a ✅/✔ sits right
635
+ # next to it, or the sentence's own prose says it passed. A ✅ used as a section emoji
636
+ # ("**✅ Verification:** ran `npm test`") is not next to the command and does not count.
637
+ # Sentences with ❌, ⚠️ or ✗ never claim success, and nor do purpose clauses ("ran
638
+ # `npm test` to ensure it passes" says why it ran, not what happened).
639
+ # - **Changed files.** "Created `tests/test_parser.py`", "Updated `docs/setup.md`". A test
640
+ # file that was added or extended is TESTS_ADDED; any edited documentation file is
641
+ # DOCS_UPDATED. Paths listed under a "New files" or "Added" heading count as added.
642
+ # --------------------------------------------------------------------------------------------
643
+
644
+ _SUCCESS_MARK = re.compile(r"✅|✔")
645
+ _FAILURE_MARK = re.compile(r"❌|⚠|✗|✖|🚫")
646
+ _INLINE_COMMAND = re.compile(r"`([^`\n]+)`")
647
+ # A success mark directly before or after inline code (bold markers and separators allowed).
648
+ _MARKED_CODE = re.compile(
649
+ r"(?:✅|✔)\s*+(?:\*\*)?\s*+`[^`\n]++`|`[^`\n]++`\s*+(?:\*\*)?\s*+[:\-–—]?\s*+(?:✅|✔)"
650
+ )
651
+ # Prose saying a command succeeded ("201 passed" included).
652
+ _SUCCESS_PROSE = re.compile(
653
+ r"\b(passed|passes|passing|succeeded|succeeds|successful|successfully|clean|green|"
654
+ r"all pass|ok)\b|\b\d+\s*(/\s*\d+\s*)?(tests?\s+)?(passed|pass)\b"
655
+ r"|\b(0|zero)\s+(errors|warnings|issues|failures)\b"
656
+ )
657
+
658
+ # Programs that run tests, builds or linters. Inline code only counts as a command if it
659
+ # starts with one of these; otherwise "✅ Created `tests/test_x.py`" would look like a test run.
660
+ _KNOWN_RUNNERS = frozenset(
661
+ {
662
+ "pytest", "py.test", "python", "python3", "uv", "poetry", "pipenv", "tox", "nox",
663
+ "hatch", "npm", "npx", "yarn", "pnpm", "bun", "deno", "node", "jest", "vitest", "mocha",
664
+ "go", "cargo", "make", "just", "mvn", "gradle", "./gradlew", "gradlew", "dotnet",
665
+ "bundle", "rake", "rspec", "mix", "ruff", "eslint", "flake8", "pylint", "mypy", "black",
666
+ "prettier", "tsc", "golangci-lint", "pre-commit", "bazel", "swift", "xcodebuild",
667
+ "composer", "phpunit", "biome", "oxlint", "pyright", "rubocop", "stylelint",
668
+ }
669
+ ) # fmt: skip
670
+
671
+ # Verbs that say a file was changed. Test files only count when added or extended (a test
672
+ # file "fixed" or "renamed" is not new testing); documentation counts for any edit.
673
+ _ADD_VERB = re.compile(
674
+ r"\b(add|adds|added|create|creates|created|new|introduce|introduces|introduced|"
675
+ r"extend|extends|extended|expand|expands|expanded|wrote|write|writes)\b"
676
+ )
677
+ _EDIT_VERB = re.compile(
678
+ r"\b(add|adds|added|create|creates|created|new|update|updates|updated|modify|modifies|"
679
+ r"modified|change|changes|changed|edit|edits|edited|fix|fixes|fixed|correct|corrects|"
680
+ r"corrected|rewrite|rewrites|rewrote|document|documents|documented|expand|expands|"
681
+ r"expanded|extend|extends|extended|improve|improves|improved|wrote|write|writes)\b"
682
+ )
683
+ # Paths named only as a reference ("as described in `README.md`") are not changes.
684
+ _REFERENCE_BEFORE = re.compile(
685
+ r"\b(per|see|from|according to|described in|referenced in|following|like)\s*$"
686
+ )
687
+ _ADDED_SECTION = re.compile(r"\b(new|added|created)\b")
688
+
689
+
690
+ def _looks_like_command(code: str) -> bool:
691
+ """True if inline code is a command line (``pytest -q``), not a file path or identifier."""
692
+ tokens = code.strip().removeprefix("$").split()
693
+ return bool(tokens) and tokens[0].lower() in _KNOWN_RUNNERS
694
+
695
+
696
+ def _looks_like_path(code: str) -> bool:
697
+ """True if inline code is a file path (``docs/setup.md``, ``README.md``)."""
698
+ code = code.strip()
699
+ if " " in code:
700
+ return False
701
+ # File extensions are lower case in practice; "ButtonIconSize.Md" is a code identifier.
702
+ return "/" in code or bool(re.search(r"\.[a-z0-9]{1,6}$", code))
703
+
704
+
705
+ def _command_type(command: str) -> str | None:
706
+ # Lint and build are tested first: "npm run test:lint" should count as lint, not tests.
707
+ if is_lint_check(command):
708
+ return LINT_OK
709
+ if is_build_check(command):
710
+ return BUILD_OK
711
+ if is_test_check(command):
712
+ return TESTS_PASS
713
+ return None
714
+
715
+
716
+ def _changed_file_claims(sentence: str, prose: str, heading: str) -> Iterator[str]:
717
+ """Claim types for files the sentence says were changed (rules ``changed_file.*``)."""
718
+ in_added_section = bool(_ADDED_SECTION.search(heading.lower()))
719
+ added = in_added_section or bool(_ADD_VERB.search(prose))
720
+ edited = in_added_section or bool(_EDIT_VERB.search(prose))
721
+ for found in _INLINE_COMMAND.finditer(sentence):
722
+ path = found.group(1)
723
+ if not _looks_like_path(path) or _REFERENCE_BEFORE.search(
724
+ sentence[: found.start()].lower()
725
+ ):
726
+ continue
727
+ if added and is_test_path(path):
728
+ yield TESTS_ADDED
729
+ elif edited and is_doc_path(path):
730
+ yield DOCS_UPDATED
731
+
732
+
733
+ def _code_sentence_claims(text: str) -> Iterator[tuple[str, dict[str, Any], str]]:
734
+ """Yield (claim type, attributes, span) from sentences that contain inline code."""
735
+ heading = ""
736
+ for line in text.splitlines(): # already prepared: see _candidates
737
+ heading = heading_of(line) or heading
738
+ box = _CHECKBOX.match(line)
739
+ if box and box.group(1) == " ":
740
+ continue # unchecked to-do item
741
+ for sentence in _SENTENCE_END.split(line):
742
+ if "`" not in sentence or _FAILURE_MARK.search(sentence):
743
+ continue
744
+ prose = _INLINE_COMMAND.sub(" ", sentence).lower()
745
+ if not is_assertion(prose):
746
+ continue
747
+ span = sentence.strip()
748
+ local = is_local(sentence, heading)
749
+
750
+ if _MARKED_CODE.search(sentence):
751
+ rule = "command.marked" # ✅ right next to the command
752
+ elif _SUCCESS_PROSE.search(asserted_part(prose)):
753
+ rule = "command.prose" # "`pytest`: 201 passed"
754
+ else:
755
+ rule = None
756
+ if rule:
757
+ for command in filter(_looks_like_command, _INLINE_COMMAND.findall(sentence)):
758
+ claim_type = _command_type(command)
759
+ if claim_type:
760
+ scope = "local" if local else command_scope(command)
761
+ attributes = {"scope": scope} if scope else {}
762
+ yield claim_type, {**attributes, "rule": rule}, span
763
+
764
+ for claim_type in _changed_file_claims(sentence, prose, heading):
765
+ name = "changed_file.test" if claim_type == TESTS_ADDED else "changed_file.doc"
766
+ yield claim_type, {"rule": name}, span
767
+
768
+
769
+ # --------------------------------------------------------------------------------------------
770
+ # Step 5: build Claim objects.
771
+ # --------------------------------------------------------------------------------------------
772
+
773
+ # Claim types whose verification depends on the commit the claim refers to.
774
+ _REF_TYPES = frozenset({TESTS_PASS, BUILD_OK, LINT_OK, DEPLOYED})
775
+
776
+
777
+ def _candidates(
778
+ source: TextSource, *, all_rules: bool = False
779
+ ) -> Iterator[tuple[str, dict[str, Any], str]]:
780
+ """Every (claim type, attributes, span) found in one text source, in reading order."""
781
+ text = prepared(source.text)
782
+ for clause, heading in clauses_in_sections(_INLINE_CODE.sub(" ", text)):
783
+ if is_assertion(clause):
784
+ scope = scope_of(clause, heading)
785
+ matches = _match_clause(asserted_part(clause), scope, all_rules=all_rules)
786
+ for claim_type, attributes in matches:
787
+ yield claim_type, attributes, clause
788
+ elif is_assertion(clause, conditions_allowed=True):
789
+ # Only a condition word disqualified the clause: issue references still count.
790
+ for claim_type, attributes in _match_clause(asserted_part(clause), None):
791
+ if claim_type == FIXES_ISSUE:
792
+ yield claim_type, attributes, clause
793
+ yield from _code_sentence_claims(text)
794
+
795
+
796
+ def rule_hits(text: str, origin: str = "body") -> set[tuple[str, str]]:
797
+ """Every (claim type, rule name) that fires anywhere in ``text``.
798
+
799
+ Unlike ``extract_claims`` this keeps all matching rules, not just the first per clause, so
800
+ each rule can be scored on its own against a golden set.
801
+ """
802
+ source = TextSource(origin=origin, text=text, written_at=datetime.min)
803
+ return {
804
+ (kind, attributes["rule"]) for kind, attributes, _ in _candidates(source, all_rules=True)
805
+ }
806
+
807
+
808
+ # Attributes that describe *how* something was said, not *what* was claimed. They are kept on
809
+ # the claim but ignored when deciding whether two claims are the same.
810
+ # "Tests pass" and "tests pass locally" are one claim; the first statement made is kept.
811
+ # "rule" records which extraction rule found the claim; it is not part of what was claimed.
812
+ _DESCRIPTIVE_ATTRIBUTES = frozenset({"scope", "rule", "confidence", "final_at", "stated_in_body"})
813
+
814
+
815
+ def extract_claims(
816
+ episode_id: str, sources: Sequence[TextSource], *, repo: str | None = None
817
+ ) -> list[Claim]:
818
+ """Extract claims from all text sources of one episode, in source order.
819
+
820
+ Identical claims (same type, same substance, same commit) are kept once, using the
821
+ earliest text that made them. ``repo`` is the PR's own repository (``owner/name``); issue
822
+ references that name it explicitly are treated like plain ``#123`` references, so
823
+ "Fixes #12" and "Fixes owner/name#12" are one claim.
824
+ """
825
+ claims: list[Claim] = []
826
+ seen: dict[str, int] = {} # claim key -> index in claims
827
+ for source in sorted(sources, key=lambda s: s.written_at):
828
+ for claim_type, attributes, span in _candidates(source):
829
+ if claim_type in _REF_TYPES:
830
+ attributes["ref"] = source.ref
831
+ if claim_type in _SCOPED_TYPES and source.final_ref:
832
+ attributes["final_ref"] = source.final_ref
833
+ if source.final_at:
834
+ attributes["final_at"] = source.final_at
835
+ if claim_type == FIXES_ISSUE and repo and attributes["repo"] == repo.lower():
836
+ attributes["repo"] = ""
837
+ attributes["confidence"] = confidence_of(claim_type, attributes["rule"], source.origin)
838
+ substance = {k: v for k, v in attributes.items() if k not in _DESCRIPTIVE_ATTRIBUTES}
839
+ key = sha256_hex([episode_id, claim_type, substance])
840
+ if key in seen:
841
+ claims[seen[key]] = _merge_statement(claims[seen[key]], attributes, source, span)
842
+ continue
843
+ seen[key] = len(claims)
844
+ claims.append(
845
+ Claim(
846
+ id=f"clm_{key[:16]}",
847
+ episode_id=episode_id,
848
+ type=claim_type,
849
+ made_at=source.written_at,
850
+ attributes=attributes,
851
+ origin=source.origin,
852
+ span=span[:MAX_SPAN],
853
+ )
854
+ )
855
+ return claims
856
+
857
+
858
+ # Narrower scopes protect a claim from contradiction; when statements disagree, the most
859
+ # protective one wins ("local" > "subset" > none).
860
+ _SCOPE_RANK = {"local": 2, "subset": 1}
861
+
862
+
863
+ def _merge_statement(
864
+ kept: Claim, attributes: dict[str, Any], source: TextSource, span: str
865
+ ) -> Claim:
866
+ """Fold a repeated statement of the same claim into the claim already kept.
867
+
868
+ - **Scope:** the most protective scope of all statements is kept. "Targeted tests pass" in
869
+ the body must not lose its ``subset`` scope because a commit said "tests pass" first,
870
+ and a ✅ `pnpm lint` command keeps its scope when prose in the same sentence also matched.
871
+ - **Trust:** if this statement was found by a trusted rule and the kept one was not, the
872
+ claim becomes high confidence, and the trusted statement (its span, origin and time)
873
+ replaces the kept one, so a report quotes the text that earned the trust.
874
+ """
875
+ merged = dict(kept.attributes)
876
+ if source.origin in ("body", "title"):
877
+ # The claim was also made in the PR's own description, whatever said it first: the
878
+ # source fetches its evidence with the body's priority (sources/github/source.py).
879
+ merged["stated_in_body"] = True
880
+ scopes = [kept.attributes.get("scope"), attributes.get("scope")]
881
+ scope = max(scopes, key=lambda value: _SCOPE_RANK.get(value or "", 0))
882
+ if scope:
883
+ merged["scope"] = scope
884
+ if attributes["confidence"] == HIGH and kept.attributes["confidence"] == LOW:
885
+ merged.update(rule=attributes["rule"], confidence=HIGH)
886
+ return replace(
887
+ kept,
888
+ attributes=merged,
889
+ origin=source.origin,
890
+ made_at=source.written_at,
891
+ span=span[:MAX_SPAN],
892
+ )
893
+ return replace(kept, attributes=merged)
894
+
895
+
896
+ def merge_claim(episode_id: str, merged_at: datetime, merge_sha: str) -> Claim:
897
+ """The implicit claim every merged PR makes: "this change is good and will stay".
898
+
899
+ Durability checks (reverts, reopened issues) verify this claim over time.
900
+ """
901
+ attributes = {"merge_sha": merge_sha}
902
+ key = sha256_hex([episode_id, MERGE_HOLDS, attributes])
903
+ return Claim(
904
+ id=f"clm_{key[:16]}",
905
+ episode_id=episode_id,
906
+ type=MERGE_HOLDS,
907
+ made_at=merged_at,
908
+ attributes=attributes,
909
+ origin="merge",
910
+ span=None,
911
+ )