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,243 @@
1
+ """Deterministic, agent-stratified samples of AIDev pull requests (docs/benchmark.md, section 2).
2
+
3
+ The curated AIDev table stores each agent's rows as one contiguous block. So we:
4
+
5
+ 1. **Locate blocks:** find where each agent's rows start and end with a binary search on single
6
+ rows, then check the blocks really are contiguous (an agent seen in two blocks is an error,
7
+ because the binary search would then be meaningless).
8
+ 2. **Draw rows:** for each agent, pick random row offsets inside its block (without
9
+ replacement) and keep rows that pass the filters, until the agent's quota is full or the
10
+ draw budget is spent.
11
+ 3. **Cap repositories:** at most ``max_per_repo`` PRs per repository per agent. Without a cap
12
+ one busy repository dominated an agent (49 of 200 Codex PRs in run 1), so per-agent rates
13
+ described a handful of projects. Whole repositories can also be excluded, which keeps a new
14
+ golden set or holdout disjoint from everything seen before.
15
+
16
+ Each agent has its own random stream, seeded from ``(seed, agent)``. The same seed and dataset
17
+ revision therefore always give the same sample, and changing one agent's quota does not change
18
+ the rows drawn for any other agent.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import random
25
+ from collections import Counter
26
+ from collections.abc import Callable, Iterable, Iterator
27
+ from dataclasses import dataclass, field
28
+ from pathlib import Path
29
+ from typing import Any, Protocol
30
+
31
+ from second_source import __version__
32
+ from second_source.benchmark.aidev import CONFIG, DATASET, AidevError, AidevPullRequest, Page
33
+
34
+ Filter = Callable[[AidevPullRequest], bool]
35
+
36
+
37
+ class RowSource(Protocol):
38
+ """Where rows come from: the dataset viewer API (AidevClient) or a downloaded Parquet file
39
+ (aidev_local.ParquetAidev). Both serve the same rows at the same offsets."""
40
+
41
+ def page(self, offset: int, length: int = ...) -> Page: ...
42
+
43
+ def revision(self) -> str: ...
44
+
45
+
46
+ # How many rows we may read per wanted row before giving up on an agent's quota.
47
+ DRAWS_PER_ROW = 5 # default; raise it for a local Parquet source, where reads are free
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class Block:
52
+ """Rows ``start .. end-1`` of the table all belong to ``agent``."""
53
+
54
+ agent: str
55
+ start: int
56
+ end: int
57
+
58
+ @property
59
+ def size(self) -> int:
60
+ return self.end - self.start
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class Sample:
65
+ """A drawn sample plus everything needed to reproduce it."""
66
+
67
+ header: dict[str, Any]
68
+ rows: tuple[AidevPullRequest, ...]
69
+ shortfall: dict[str, int] = field(default_factory=dict) # agent -> rows still missing
70
+
71
+
72
+ def has_body(pull: AidevPullRequest) -> bool:
73
+ """Golden-set filter: a PR without a body cannot contain claims."""
74
+ return bool(pull.body.strip())
75
+
76
+
77
+ def merged_with_body(pull: AidevPullRequest) -> bool:
78
+ """Benchmark filter: merged PRs only (durability and most evidence need a merge)."""
79
+ return pull.merged and has_body(pull)
80
+
81
+
82
+ FILTERS: dict[str, Filter] = {"has_body": has_body, "merged_with_body": merged_with_body}
83
+
84
+
85
+ def locate_blocks(client: RowSource) -> tuple[Block, ...]:
86
+ """Find each agent's contiguous block of rows. Costs about 20 requests per agent."""
87
+ total = client.page(0, 1).total
88
+ cache: dict[int, str] = {}
89
+
90
+ def agent_at(offset: int) -> str:
91
+ if offset not in cache:
92
+ cache[offset] = client.page(offset, 1).rows[0].agent
93
+ return cache[offset]
94
+
95
+ blocks: list[Block] = []
96
+ start = 0
97
+ while start < total:
98
+ agent = agent_at(start)
99
+ # Binary search for the first row after ``start`` with a different agent.
100
+ # Invariant: agent_at(low) == agent; high is past the end of the block.
101
+ low, high = start, total
102
+ while high - low > 1:
103
+ middle = (low + high) // 2
104
+ if agent_at(middle) == agent:
105
+ low = middle
106
+ else:
107
+ high = middle
108
+ blocks.append(Block(agent, start, high))
109
+ start = high
110
+
111
+ agents = [block.agent for block in blocks]
112
+ repeated = sorted({agent for agent in agents if agents.count(agent) > 1})
113
+ if repeated:
114
+ raise AidevError(f"table is not grouped by agent (split blocks for {repeated})")
115
+ return tuple(blocks)
116
+
117
+
118
+ def sample_block(
119
+ client: RowSource,
120
+ block: Block,
121
+ *,
122
+ count: int,
123
+ seed: int,
124
+ accept: Filter,
125
+ exclude: frozenset[str] = frozenset(),
126
+ exclude_repos: frozenset[str] = frozenset(),
127
+ max_per_repo: int | None = None,
128
+ draws_per_row: int = DRAWS_PER_ROW,
129
+ ) -> list[AidevPullRequest]:
130
+ """Up to ``count`` random rows from one block that pass ``accept``.
131
+
132
+ Rows whose URL is in ``exclude`` (for example PRs already in a golden set) or whose
133
+ repository is in ``exclude_repos`` are skipped and do not count towards ``count``, so a set
134
+ can grow without duplicates. ``max_per_repo`` caps PRs per repository.
135
+ """
136
+ rng = random.Random(f"{seed}:{block.agent}")
137
+ budget = min(block.size, count * draws_per_row)
138
+ chosen: list[AidevPullRequest] = []
139
+ per_repo: Counter[str] = Counter()
140
+ for offset in rng.sample(range(block.start, block.end), budget):
141
+ if len(chosen) == count:
142
+ break
143
+ pull = client.page(offset, 1).rows[0]
144
+ if pull.url in exclude or pull.repo in exclude_repos or not accept(pull):
145
+ continue
146
+ if max_per_repo is not None and per_repo[pull.repo] >= max_per_repo:
147
+ continue
148
+ per_repo[pull.repo] += 1
149
+ chosen.append(pull)
150
+ return chosen
151
+
152
+
153
+ def draw_sample(
154
+ client: RowSource,
155
+ *,
156
+ per_agent: int,
157
+ seed: int,
158
+ filter_name: str = "has_body",
159
+ agents: Iterable[str] | None = None,
160
+ exclude: Iterable[str] = (),
161
+ exclude_repos: Iterable[str] = (),
162
+ max_per_repo: int | None = None,
163
+ draws_per_row: int = DRAWS_PER_ROW,
164
+ ) -> Sample:
165
+ """Draw ``per_agent`` PRs for each agent (all agents in the table unless given), skipping
166
+ any PR whose URL is in ``exclude`` or whose repository is in ``exclude_repos``, with at most
167
+ ``max_per_repo`` PRs per repository per agent."""
168
+ excluded = frozenset(exclude)
169
+ excluded_repos = frozenset(repo.lower() for repo in exclude_repos)
170
+ accept = FILTERS[filter_name]
171
+ blocks = locate_blocks(client)
172
+ wanted = set(agents) if agents is not None else {block.agent for block in blocks}
173
+ missing = wanted - {block.agent for block in blocks}
174
+ if missing:
175
+ raise ValueError(f"agents not in the dataset: {sorted(missing)}")
176
+
177
+ rows: list[AidevPullRequest] = []
178
+ shortfall: dict[str, int] = {}
179
+ for block in blocks:
180
+ if block.agent not in wanted:
181
+ continue
182
+ chosen = sample_block(
183
+ client,
184
+ block,
185
+ count=per_agent,
186
+ seed=seed,
187
+ accept=accept,
188
+ exclude=excluded,
189
+ exclude_repos=excluded_repos,
190
+ max_per_repo=max_per_repo,
191
+ draws_per_row=draws_per_row,
192
+ )
193
+ rows.extend(chosen)
194
+ if len(chosen) < per_agent:
195
+ shortfall[block.agent] = per_agent - len(chosen)
196
+
197
+ header = {
198
+ "dataset": DATASET,
199
+ "config": CONFIG,
200
+ "revision": client.revision(),
201
+ "seed": seed,
202
+ "per_agent": per_agent,
203
+ "filter": filter_name,
204
+ "blocks": [[block.agent, block.start, block.end] for block in blocks],
205
+ "shortfall": shortfall,
206
+ "excluded": len(excluded),
207
+ "excluded_repos": len(excluded_repos),
208
+ "max_per_repo": max_per_repo,
209
+ "draws_per_row": draws_per_row,
210
+ "tool_version": __version__,
211
+ }
212
+ return Sample(header=header, rows=tuple(rows), shortfall=shortfall)
213
+
214
+
215
+ # ---- JSON Lines files: one header record, then one record per pull request -----------------
216
+
217
+
218
+ def write_sample(sample: Sample, path: Path) -> None:
219
+ path.parent.mkdir(parents=True, exist_ok=True)
220
+ with path.open("w", encoding="utf-8") as handle:
221
+ handle.write(json.dumps({"header": sample.header}, sort_keys=True) + "\n")
222
+ for pull in sample.rows:
223
+ handle.write(json.dumps(pull.to_dict(), sort_keys=True, ensure_ascii=False) + "\n")
224
+
225
+
226
+ def read_sample(path: Path) -> Sample:
227
+ header: dict[str, Any] = {}
228
+ rows: list[AidevPullRequest] = []
229
+ for number, record in enumerate(_records(path), start=1):
230
+ if "header" in record:
231
+ if number != 1:
232
+ raise ValueError(f"{path}:{number}: header must be the first record")
233
+ header = record["header"]
234
+ else:
235
+ rows.append(AidevPullRequest(**record)) # records were written by to_dict()
236
+ return Sample(header=header, rows=tuple(rows), shortfall=dict(header.get("shortfall", {})))
237
+
238
+
239
+ def _records(path: Path) -> Iterator[dict[str, Any]]:
240
+ with path.open(encoding="utf-8") as handle:
241
+ for line in handle:
242
+ if line.strip():
243
+ yield json.loads(line)
@@ -0,0 +1,363 @@
1
+ """Benchmark statistics: per-agent, per-claim-type truth rates with Wilson intervals (section 6).
2
+
3
+ Definitions (claims are counted from the batch runner's result records):
4
+
5
+ - **Counted per PR, not per claim.** A PR's claims of one type become one outcome (any
6
+ contradicted → contradicted; else any verified → verified; else scoped CI failure; else
7
+ pending; else unverifiable). One PR with 25 similar commit-message claims would otherwise
8
+ outweigh 24 other PRs, and claims of one PR are not independent trials.
9
+ - **all** = a PR's stated claims together. The implicit MERGE_HOLDS claim (made by every merged
10
+ PR, not written by the agent) is reported on its own and left out of **all**, so it cannot
11
+ dilute the rate of claims agents actually wrote.
12
+ - Every cell reports how many **repositories** its checkable PRs come from: PRs of one
13
+ repository are not independent either, so a rate resting on few repositories is weak.
14
+ - **checkable** PRs are those with a definite answer: VERIFIED or CONTRADICTED.
15
+ - **false rate** = contradicted / checkable, the share of checkable PRs whose claim was false.
16
+ - **coverage** = checkable / all PRs with the claim, so a low false rate cannot hide behind
17
+ "almost nothing could be checked".
18
+ - **Only high-confidence claims count.** Claims found by extraction rules that have not proven
19
+ their precision on the golden set (``confidence: low``) are counted separately, per agent, and
20
+ never enter the rates. The implicit MERGE_HOLDS claim needs no extraction and always counts.
21
+ - **CI failed after a scoped claim** (reasons ``CI_FAILED_LOCAL_CLAIM`` and
22
+ ``CI_FAILED_SUBSET_CLAIM``) is counted on its own and never folded into the false rate: the
23
+ agent said a check passed *locally*, or that *part* of the checks passed, and a CI job
24
+ failed. That is a signal, not proof (see docs/benchmark.md, section 4).
25
+
26
+ Intervals are 95% Wilson score intervals. Unlike the usual "p ± 1.96·SE", they stay inside
27
+ [0, 1] and remain sensible for small samples and for rates near 0 or 1.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import math
33
+ from collections import Counter, defaultdict
34
+ from collections.abc import Iterable, Mapping
35
+ from dataclasses import dataclass, field
36
+ from typing import Any
37
+
38
+ from second_source.benchmark.aidev import repo_of
39
+
40
+ Z_95 = 1.959963984540054 # two-sided 95% normal quantile
41
+ SCOPED_CI_FAILED = frozenset({"CI_FAILED_LOCAL_CLAIM", "CI_FAILED_SUBSET_CLAIM"})
42
+ ALL = "all" # pseudo claim type: every claim an agent wrote (not MERGE_HOLDS)
43
+ IMPLICIT_TYPES = frozenset({"MERGE_HOLDS"}) # claims no agent wrote; never part of ALL
44
+
45
+ # How a PR's several claims of one type combine into one outcome, strongest first.
46
+ _OUTCOME_ORDER = (
47
+ "CONTRADICTED",
48
+ "VERIFIED",
49
+ "WITHDRAWN",
50
+ "SCOPED_CI_FAILED",
51
+ "PENDING",
52
+ "UNVERIFIABLE",
53
+ )
54
+
55
+
56
+ def wilson_interval(successes: int, trials: int, z: float = Z_95) -> tuple[float, float]:
57
+ """Wilson score interval for a binomial proportion. (0, 1) when there are no trials."""
58
+ if trials < 0 or not 0 <= successes <= trials:
59
+ raise ValueError(f"invalid counts: {successes} of {trials}")
60
+ if trials == 0:
61
+ return 0.0, 1.0
62
+ p = successes / trials
63
+ denominator = 1 + z * z / trials
64
+ centre = (p + z * z / (2 * trials)) / denominator
65
+ margin = z * math.sqrt(p * (1 - p) / trials + z * z / (4 * trials * trials)) / denominator
66
+ # At p = 0 or p = 1 the matching bound is exactly 0 or 1; set it directly so floating-point
67
+ # rounding cannot report 0.9999... for "every claim was false".
68
+ low = 0.0 if successes == 0 else max(0.0, centre - margin)
69
+ high = 1.0 if successes == trials else min(1.0, centre + margin)
70
+ return low, high
71
+
72
+
73
+ def outcome_of(result: str, reasons: Iterable[str], withdrawn: bool = False) -> str:
74
+ """One claim's verdict as a counting outcome. Scoped CI failures and verifications withdrawn
75
+ by an integrity guard are kept apart, so neither silently moves the false rate."""
76
+ if result == "UNVERIFIABLE" and withdrawn:
77
+ return "WITHDRAWN"
78
+ if result == "UNVERIFIABLE" and SCOPED_CI_FAILED.intersection(reasons):
79
+ return "SCOPED_CI_FAILED"
80
+ return result if result in _OUTCOME_ORDER else "UNVERIFIABLE"
81
+
82
+
83
+ def combine(outcomes: Iterable[str]) -> str:
84
+ """One outcome for several claims of the same type on one PR."""
85
+ return min(outcomes, key=_OUTCOME_ORDER.index)
86
+
87
+
88
+ @dataclass
89
+ class Cell:
90
+ """Counts of PRs for one agent and one claim type."""
91
+
92
+ verified: int = 0
93
+ contradicted: int = 0
94
+ scoped_ci_failed: int = 0
95
+ withdrawn: int = 0 # CI passed, but the PR shaped its own evidence (integrity guards)
96
+ pending: int = 0
97
+ unverifiable: int = 0 # excluding scoped_ci_failed
98
+ repos: set[str] = field(default_factory=set) # repositories of the checkable PRs
99
+
100
+ def add(self, outcome: str, repo: str = "") -> None:
101
+ if outcome == "VERIFIED":
102
+ self.verified += 1
103
+ elif outcome == "CONTRADICTED":
104
+ self.contradicted += 1
105
+ elif outcome == "PENDING":
106
+ self.pending += 1
107
+ elif outcome == "WITHDRAWN":
108
+ self.withdrawn += 1
109
+ elif outcome == "SCOPED_CI_FAILED":
110
+ self.scoped_ci_failed += 1
111
+ else:
112
+ self.unverifiable += 1
113
+ if outcome in ("VERIFIED", "CONTRADICTED") and repo:
114
+ self.repos.add(repo)
115
+
116
+ @property
117
+ def total(self) -> int:
118
+ return (
119
+ self.verified
120
+ + self.contradicted
121
+ + self.scoped_ci_failed
122
+ + self.withdrawn
123
+ + self.pending
124
+ + self.unverifiable
125
+ )
126
+
127
+ @property
128
+ def checkable(self) -> int:
129
+ return self.verified + self.contradicted
130
+
131
+ @property
132
+ def false_rate(self) -> float | None:
133
+ return self.contradicted / self.checkable if self.checkable else None
134
+
135
+ @property
136
+ def coverage(self) -> float | None:
137
+ return self.checkable / self.total if self.total else None
138
+
139
+ def to_dict(self) -> dict[str, Any]:
140
+ low, high = wilson_interval(self.contradicted, self.checkable)
141
+ return {
142
+ "prs": self.total,
143
+ "repos": len(self.repos),
144
+ "verified": self.verified,
145
+ "contradicted": self.contradicted,
146
+ "ci_failed_after_scoped_claim": self.scoped_ci_failed,
147
+ "withdrawn_by_integrity_guard": self.withdrawn,
148
+ "pending": self.pending,
149
+ "unverifiable": self.unverifiable,
150
+ "checkable": self.checkable,
151
+ "coverage": self.coverage,
152
+ "false_rate": self.false_rate,
153
+ "false_rate_ci95": [low, high] if self.checkable else None,
154
+ # Comparable with runs made before the integrity guards existed: withdrawn claims
155
+ # counted as verified, as they would have been then.
156
+ "false_rate_without_guards": (
157
+ self.contradicted / (self.checkable + self.withdrawn)
158
+ if self.checkable + self.withdrawn
159
+ else None
160
+ ),
161
+ "false_rate_without_guards_ci95": (
162
+ list(wilson_interval(self.contradicted, self.checkable + self.withdrawn))
163
+ if self.checkable + self.withdrawn
164
+ else None
165
+ ),
166
+ }
167
+
168
+
169
+ @dataclass
170
+ class AgentStats:
171
+ prs: int = 0
172
+ errors: int = 0
173
+ detected_as_dataset_agent: int = 0
174
+ low_confidence_claims: int = 0 # found by unproven rules; not in the rates
175
+ claims: dict[str, Cell] = field(default_factory=lambda: defaultdict(Cell))
176
+
177
+
178
+ def _testreceipt_cells(records: Iterable[Mapping[str, Any]]) -> dict[str, Any]:
179
+ """A cell comparable to testreceipt's study (github.com/amos689/testreceipt, docs/study.md):
180
+ PRs whose description claims the tests pass, with CI results at the claim's commit, and the
181
+ share where CI failed. Counted per year the PR was opened, over all agents.
182
+
183
+ Our version: high-confidence, unscoped TESTS_PASS claims from the PR body, decided
184
+ (VERIFIED or CONTRADICTED). Differences remain (their parser, their labels, their CI
185
+ matching), so agreement is corroboration and disagreement is a finding to explain.
186
+ """
187
+ years: dict[str, Cell] = defaultdict(Cell)
188
+ for record in records:
189
+ report = record.get("report")
190
+ if not report:
191
+ continue
192
+ opened = (report.get("pull_request") or {}).get("opened_at", "")
193
+ year = opened[:4] or "unknown"
194
+ outcomes = [
195
+ outcome_of(claim["result"], claim["reasons"])
196
+ for claim in report["claims"]
197
+ if claim["type"] == "TESTS_PASS"
198
+ and claim.get("origin") == "body"
199
+ and claim.get("attributes", {}).get("confidence") == "high"
200
+ and "scope" not in claim.get("attributes", {})
201
+ ]
202
+ decided = [o for o in outcomes if o in ("VERIFIED", "CONTRADICTED")]
203
+ if decided:
204
+ years[year].add(combine(decided), repo_of(record["url"]))
205
+ return {year: years[year].to_dict() for year in sorted(years)}
206
+
207
+
208
+ def summarize(records: Iterable[Mapping[str, Any]]) -> dict[str, Any]:
209
+ """Aggregate runner result records into the published summary structure."""
210
+ agents: dict[str, AgentStats] = defaultdict(AgentStats)
211
+ for record in records:
212
+ stats = agents[record["dataset_agent"]]
213
+ if "error" in record:
214
+ stats.errors += 1
215
+ continue
216
+ report = record["report"]
217
+ stats.prs += 1
218
+ detected = (report.get("agent") or {}).get("name")
219
+ if detected == record["dataset_agent"]:
220
+ stats.detected_as_dataset_agent += 1
221
+ repo = repo_of(record["url"])
222
+ by_type: dict[str, list[str]] = defaultdict(list)
223
+ for claim in report["claims"]:
224
+ if claim.get("attributes", {}).get("confidence", "high") != "high":
225
+ stats.low_confidence_claims += 1
226
+ continue
227
+ by_type[claim["type"]].append(
228
+ outcome_of(claim["result"], claim["reasons"], bool(claim.get("withdrawn")))
229
+ )
230
+ for kind, outcomes in by_type.items():
231
+ stats.claims[kind].add(combine(outcomes), repo)
232
+ written = [
233
+ o for kind, outcomes in by_type.items() if kind not in IMPLICIT_TYPES for o in outcomes
234
+ ]
235
+ if written:
236
+ stats.claims[ALL].add(combine(written), repo)
237
+
238
+ versions = Counter(
239
+ f"{record.get('tool_version', 'unknown')}/pack {record.get('pack_version', 'unknown')}"
240
+ for record in records
241
+ if "report" in record
242
+ )
243
+ return {
244
+ # More than one entry means the run mixes code versions (resumed after an upgrade);
245
+ # re-score the stored evidence with one version before publishing.
246
+ "code_versions": dict(sorted(versions.items())),
247
+ # Claims a re-score could not reproduce (benchmark/rescore.py); they are counted as
248
+ # unverifiable, and a published summary must say how many there are.
249
+ "rescore_mismatches": sum(
250
+ "rescore_mismatch" in claim
251
+ for record in records
252
+ if "report" in record
253
+ for claim in record["report"]["claims"]
254
+ ),
255
+ "testreceipt_comparable": _testreceipt_cells(records),
256
+ "agents": {
257
+ agent: {
258
+ "prs": stats.prs,
259
+ "errors": stats.errors,
260
+ "detection_agreement": (
261
+ stats.detected_as_dataset_agent / stats.prs if stats.prs else None
262
+ ),
263
+ "low_confidence_claims": stats.low_confidence_claims,
264
+ "claims": {kind: cell.to_dict() for kind, cell in sorted(stats.claims.items())},
265
+ }
266
+ for agent, stats in sorted(agents.items())
267
+ },
268
+ }
269
+
270
+
271
+ # ---- Markdown -----------------------------------------------------------------------------
272
+
273
+
274
+ def _percent(value: float | None) -> str:
275
+ return "–" if value is None else f"{100 * value:.0f}%"
276
+
277
+
278
+ def to_markdown(summary: Mapping[str, Any], *, title: str = "Agent Claim Truth") -> str:
279
+ lines = [
280
+ f"# {title}",
281
+ "",
282
+ "Counted per PR: a PR's claims of one type give one outcome. False rate = contradicted",
283
+ "÷ checkable PRs (95% Wilson interval; PRs of one repository are not independent, so",
284
+ "check the *Repos* column). Coverage = checkable ÷ all PRs with the claim. *Scoped, CI",
285
+ "failed* = the agent said a check passed locally, or that part of the checks passed, and",
286
+ "a CI job failed; shown separately and never counted as false. *Withdrawn* = CI passed but",
287
+ "the PR weakened its own tests or CI (integrity guards); *Without guards* counts those as",
288
+ "verified, as runs before the guards did, for comparison. *all* = PRs by their",
289
+ "written claims together: a PR counts as contradicted if any of them was, so it is not",
290
+ "comparable to the per-type rates (MERGE_HOLDS, implicit in every merge, is left out).",
291
+ "Only high-confidence claims (found by extraction rules with proven precision) are",
292
+ "counted.",
293
+ "",
294
+ ]
295
+ versions = summary.get("code_versions") or {}
296
+ if len(versions) > 1:
297
+ mixed = ", ".join(f"{name} ({count} PRs)" for name, count in versions.items())
298
+ lines += [f"> **Mixed code versions:** {mixed}. Re-score before publishing.", ""]
299
+ if summary.get("rescore_mismatches"):
300
+ lines += [
301
+ f"> **Re-scored:** {summary['rescore_mismatches']} claim(s) could not be reproduced "
302
+ "from their saved evidence and are counted as unverifiable.",
303
+ "",
304
+ ]
305
+ cells = summary.get("testreceipt_comparable") or {}
306
+ if cells:
307
+ lines += [
308
+ "## Comparable to testreceipt",
309
+ "",
310
+ "PRs whose body claims the tests pass (high confidence, unscoped) and whose CI at",
311
+ "the claim's commit decided it; share where CI failed, by year opened. Compare with",
312
+ "testreceipt's study (github.com/amos689/testreceipt): same question, independent",
313
+ "parser and labels.",
314
+ "",
315
+ "| Year | PRs | Repos | CI failed | Rate (95% CI) |",
316
+ "|---|---:|---:|---:|---|",
317
+ ]
318
+ for year, cell in cells.items():
319
+ interval = cell["false_rate_ci95"]
320
+ rate = (
321
+ f"{_percent(cell['false_rate'])} ({_percent(interval[0])}–{_percent(interval[1])})"
322
+ )
323
+ lines.append(
324
+ f"| {year} | {cell['checkable']} | {cell['repos']} | "
325
+ f"{cell['contradicted']} | {rate} |"
326
+ )
327
+ lines.append("")
328
+ for agent, data in summary["agents"].items():
329
+ agreement = _percent(data["detection_agreement"])
330
+ lines += [
331
+ f"## {agent}",
332
+ "",
333
+ f"{data['prs']} PRs checked, {data['errors']} errors, "
334
+ f"agent detection agreed with the dataset label on {agreement}; "
335
+ f"{data['low_confidence_claims']} low-confidence claims not counted.",
336
+ "",
337
+ "| Claim | PRs | Repos | Verified | Contradicted | Scoped, CI failed | Withdrawn | "
338
+ "Coverage | False rate (95% CI) | Without guards (95% CI) |",
339
+ "|---|---:|---:|---:|---:|---:|---:|---:|---|---|",
340
+ ]
341
+ for kind, cell in data["claims"].items():
342
+ interval = cell["false_rate_ci95"]
343
+ rate = (
344
+ "–"
345
+ if interval is None
346
+ else f"{_percent(cell['false_rate'])} "
347
+ f"({_percent(interval[0])}–{_percent(interval[1])})"
348
+ )
349
+ unguarded = cell["false_rate_without_guards_ci95"]
350
+ rate_without = (
351
+ "–"
352
+ if unguarded is None
353
+ else f"{_percent(cell['false_rate_without_guards'])} "
354
+ f"({_percent(unguarded[0])}–{_percent(unguarded[1])})"
355
+ )
356
+ lines.append(
357
+ f"| {kind} | {cell['prs']} | {cell['repos']} | {cell['verified']} | "
358
+ f"{cell['contradicted']} | {cell['ci_failed_after_scoped_claim']} | "
359
+ f"{cell['withdrawn_by_integrity_guard']} | {_percent(cell['coverage'])} | "
360
+ f"{rate} | {rate_without} |"
361
+ )
362
+ lines.append("")
363
+ return "\n".join(lines)
@@ -0,0 +1 @@
1
+ """Command-line interface: ``second-source check <pull request>``."""