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.
- second_source/__init__.py +3 -0
- second_source/action/__init__.py +4 -0
- second_source/action/commands.py +88 -0
- second_source/action/event.py +89 -0
- second_source/action/inputs.py +118 -0
- second_source/action/main.py +203 -0
- second_source/action/publish.py +184 -0
- second_source/action/setup.py +143 -0
- second_source/action/sweep.py +85 -0
- second_source/action/wait.py +49 -0
- second_source/benchmark/__init__.py +1 -0
- second_source/benchmark/aidev.py +248 -0
- second_source/benchmark/aidev_local.py +85 -0
- second_source/benchmark/golden.py +314 -0
- second_source/benchmark/redact.py +45 -0
- second_source/benchmark/rescore.py +388 -0
- second_source/benchmark/runner.py +159 -0
- second_source/benchmark/sample.py +243 -0
- second_source/benchmark/stats.py +363 -0
- second_source/cli/__init__.py +1 -0
- second_source/cli/bench.py +427 -0
- second_source/cli/main.py +182 -0
- second_source/core/__init__.py +4 -0
- second_source/core/aggregate.py +102 -0
- second_source/core/checks.py +470 -0
- second_source/core/engine.py +98 -0
- second_source/core/evidence.py +29 -0
- second_source/core/expr.py +206 -0
- second_source/core/hashing.py +41 -0
- second_source/core/model.py +112 -0
- second_source/core/pack.py +156 -0
- second_source/packs/__init__.py +1 -0
- second_source/packs/coding/__init__.py +16 -0
- second_source/packs/coding/checks/ci_config_caution.yaml +23 -0
- second_source/packs/coding/checks/ci_result.yaml +133 -0
- second_source/packs/coding/checks/ci_weakening_caution.yaml +27 -0
- second_source/packs/coding/checks/deployed.yaml +36 -0
- second_source/packs/coding/checks/docs_updated.yaml +22 -0
- second_source/packs/coding/checks/fixes_issue.yaml +58 -0
- second_source/packs/coding/checks/fixes_issue_durable.yaml +60 -0
- second_source/packs/coding/checks/integrity_guard.yaml +34 -0
- second_source/packs/coding/checks/integrity_inspection.yaml +21 -0
- second_source/packs/coding/checks/lint_caution.yaml +22 -0
- second_source/packs/coding/checks/matching_jobs_caution.yaml +22 -0
- second_source/packs/coding/checks/not_reverted.yaml +38 -0
- second_source/packs/coding/checks/tests_added.yaml +25 -0
- second_source/packs/coding/checks/tests_added_guard.yaml +26 -0
- second_source/packs/coding/checks/tests_removed_caution.yaml +23 -0
- second_source/packs/coding/detection.py +94 -0
- second_source/packs/coding/diff_facts.py +665 -0
- second_source/packs/coding/extract.py +911 -0
- second_source/packs/coding/functions.py +241 -0
- second_source/packs/coding/pack.yaml +33 -0
- second_source/packs/coding/trusted_rules.yaml +50 -0
- second_source/pipeline.py +112 -0
- second_source/report/__init__.py +1 -0
- second_source/report/render.py +503 -0
- second_source/sources/__init__.py +1 -0
- second_source/sources/github/__init__.py +4 -0
- second_source/sources/github/auth.py +48 -0
- second_source/sources/github/cache.py +67 -0
- second_source/sources/github/client.py +261 -0
- second_source/sources/github/mappers.py +454 -0
- second_source/sources/github/source.py +385 -0
- second_source/sources/github/urls.py +51 -0
- second_source-0.5.0.dist-info/METADATA +311 -0
- second_source-0.5.0.dist-info/RECORD +71 -0
- second_source-0.5.0.dist-info/WHEEL +4 -0
- second_source-0.5.0.dist-info/entry_points.txt +2 -0
- second_source-0.5.0.dist-info/licenses/LICENSE +202 -0
- second_source-0.5.0.dist-info/licenses/NOTICE +9 -0
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
"""``second-source bench``: reproduce the Agent Claim Truth benchmark (docs/benchmark.md).
|
|
2
|
+
|
|
3
|
+
second-source bench sample --per-agent 200 --seed 1 --max-per-repo 3 -o s.jsonl
|
|
4
|
+
second-source bench commits s.jsonl -o commits.jsonl [--per-pr 5]
|
|
5
|
+
second-source bench run s.jsonl -o results.jsonl [--limit 10] [--anonymous]
|
|
6
|
+
second-source bench facts results.jsonl -o facts.jsonl (diff counts for old records)
|
|
7
|
+
second-source bench rescore results.jsonl [--facts facts.jsonl] -o rescored.jsonl
|
|
8
|
+
second-source bench summarize results.jsonl -o summary/
|
|
9
|
+
second-source bench golden cases.jsonl [--split dev|test|all]
|
|
10
|
+
|
|
11
|
+
Each step reads the previous step's file, so a run can be stopped and resumed at any point.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import json
|
|
18
|
+
from collections.abc import Callable, Mapping
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import TextIO
|
|
22
|
+
|
|
23
|
+
import yaml
|
|
24
|
+
|
|
25
|
+
from second_source.benchmark import golden, stats
|
|
26
|
+
from second_source.benchmark.aidev import AidevClient, AidevError, repo_of
|
|
27
|
+
from second_source.benchmark.aidev_local import ParquetAidev
|
|
28
|
+
from second_source.benchmark.rescore import (
|
|
29
|
+
AlreadyRescored,
|
|
30
|
+
fetch_file_facts,
|
|
31
|
+
needs_file_facts,
|
|
32
|
+
rescore_all,
|
|
33
|
+
)
|
|
34
|
+
from second_source.benchmark.runner import read_results, run_benchmark
|
|
35
|
+
from second_source.benchmark.sample import (
|
|
36
|
+
DRAWS_PER_ROW,
|
|
37
|
+
FILTERS,
|
|
38
|
+
draw_sample,
|
|
39
|
+
read_sample,
|
|
40
|
+
write_sample,
|
|
41
|
+
)
|
|
42
|
+
from second_source.packs import coding
|
|
43
|
+
from second_source.packs.coding import diff_facts
|
|
44
|
+
from second_source.sources.github.auth import TokenResult
|
|
45
|
+
from second_source.sources.github.client import (
|
|
46
|
+
GitHubClient,
|
|
47
|
+
GitHubError,
|
|
48
|
+
NotFound,
|
|
49
|
+
RateLimited,
|
|
50
|
+
)
|
|
51
|
+
from second_source.sources.github.source import GitHubSource
|
|
52
|
+
|
|
53
|
+
EXIT_OK = 0
|
|
54
|
+
EXIT_ERROR = 2
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass(frozen=True)
|
|
58
|
+
class BenchContext:
|
|
59
|
+
"""Everything the bench commands touch outside the process, injectable for tests."""
|
|
60
|
+
|
|
61
|
+
client_factory: Callable[[str | None, bool], GitHubClient]
|
|
62
|
+
token_resolver: Callable[[Mapping[str, str] | None], TokenResult]
|
|
63
|
+
aidev_factory: Callable[[], AidevClient]
|
|
64
|
+
env: Mapping[str, str] | None
|
|
65
|
+
out: TextIO
|
|
66
|
+
err: TextIO
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def add_parser(commands: argparse._SubParsersAction) -> None:
|
|
70
|
+
bench = commands.add_parser("bench", help="run the Agent Claim Truth benchmark")
|
|
71
|
+
steps = bench.add_subparsers(dest="bench_command", required=True)
|
|
72
|
+
|
|
73
|
+
sample = steps.add_parser("sample", help="draw an agent-stratified sample from AIDev")
|
|
74
|
+
sample.add_argument("--per-agent", type=int, required=True)
|
|
75
|
+
sample.add_argument("--seed", type=int, required=True)
|
|
76
|
+
sample.add_argument("--filter", choices=sorted(FILTERS), default="merged_with_body")
|
|
77
|
+
sample.add_argument("--agents", help="comma-separated agent names (default: all)")
|
|
78
|
+
sample.add_argument(
|
|
79
|
+
"--exclude-from",
|
|
80
|
+
type=Path,
|
|
81
|
+
action="append",
|
|
82
|
+
default=[],
|
|
83
|
+
help="JSON Lines file whose records' url fields are skipped (repeatable)",
|
|
84
|
+
)
|
|
85
|
+
sample.add_argument(
|
|
86
|
+
"--exclude-repos-from",
|
|
87
|
+
type=Path,
|
|
88
|
+
action="append",
|
|
89
|
+
default=[],
|
|
90
|
+
help="JSON Lines file whose records' repositories are skipped entirely (repeatable)",
|
|
91
|
+
)
|
|
92
|
+
sample.add_argument(
|
|
93
|
+
"--max-per-repo",
|
|
94
|
+
type=int,
|
|
95
|
+
help="at most this many PRs per repository per agent (default: no cap)",
|
|
96
|
+
)
|
|
97
|
+
sample.add_argument(
|
|
98
|
+
"--draws-per-row",
|
|
99
|
+
type=int,
|
|
100
|
+
default=DRAWS_PER_ROW,
|
|
101
|
+
help="rows read per wanted row before an agent's quota gives up (default "
|
|
102
|
+
f"{DRAWS_PER_ROW}; raise it with --parquet, where reads are free)",
|
|
103
|
+
)
|
|
104
|
+
sample.add_argument(
|
|
105
|
+
"--parquet",
|
|
106
|
+
type=Path,
|
|
107
|
+
help="read AIDev from this downloaded pull_request Parquet file instead of the "
|
|
108
|
+
"dataset viewer API (same rows; needs `uv sync --extra local`)",
|
|
109
|
+
)
|
|
110
|
+
sample.add_argument("-o", "--output", type=Path, required=True)
|
|
111
|
+
|
|
112
|
+
commits = steps.add_parser(
|
|
113
|
+
"commits", help="add each sampled PR's commit messages from AIDev (for labelling)"
|
|
114
|
+
)
|
|
115
|
+
commits.add_argument("sample", type=Path)
|
|
116
|
+
commits.add_argument("--per-pr", type=int, default=5, help="first N commits of each PR")
|
|
117
|
+
commits.add_argument("-o", "--output", type=Path, required=True)
|
|
118
|
+
|
|
119
|
+
run = steps.add_parser("run", help="check every sampled PR (resumable)")
|
|
120
|
+
run.add_argument("sample", type=Path)
|
|
121
|
+
run.add_argument("-o", "--output", type=Path, required=True)
|
|
122
|
+
run.add_argument("--limit", type=int, help="check at most this many new PRs")
|
|
123
|
+
run.add_argument("--anonymous", action="store_true", help="never use a GitHub token")
|
|
124
|
+
run.add_argument("--no-cache", action="store_true", help="do not use the on-disk cache")
|
|
125
|
+
|
|
126
|
+
facts = steps.add_parser(
|
|
127
|
+
"facts", help="re-read diff counts for results whose counts came from other code"
|
|
128
|
+
)
|
|
129
|
+
facts.add_argument("results", type=Path)
|
|
130
|
+
facts.add_argument("-o", "--output", type=Path, required=True)
|
|
131
|
+
facts.add_argument("--no-cache", action="store_true", help="do not use the on-disk cache")
|
|
132
|
+
|
|
133
|
+
rescore = steps.add_parser("rescore", help="recompute verdicts offline with the current code")
|
|
134
|
+
rescore.add_argument("results", type=Path)
|
|
135
|
+
rescore.add_argument("--facts", type=Path, help="diff counts from `bench facts`")
|
|
136
|
+
rescore.add_argument("-o", "--output", type=Path, required=True)
|
|
137
|
+
|
|
138
|
+
summarize = steps.add_parser("summarize", help="write summary.json and summary.md")
|
|
139
|
+
summarize.add_argument("results", type=Path)
|
|
140
|
+
summarize.add_argument("-o", "--output", type=Path, required=True, help="output directory")
|
|
141
|
+
|
|
142
|
+
merge = steps.add_parser(
|
|
143
|
+
"merge-labels", help="merge two labellers' files into golden cases (with adjudications)"
|
|
144
|
+
)
|
|
145
|
+
merge.add_argument("sample", type=Path)
|
|
146
|
+
merge.add_argument("--a", type=Path, action="append", required=True, help="labeller A file")
|
|
147
|
+
merge.add_argument("--b", type=Path, action="append", required=True, help="labeller B file")
|
|
148
|
+
merge.add_argument("--adjudications", type=Path, help="JSON: {url: {expected, reason}}")
|
|
149
|
+
merge.add_argument("-o", "--output", type=Path, required=True)
|
|
150
|
+
|
|
151
|
+
rules = steps.add_parser("rules", help="precision of each extraction rule on a golden set")
|
|
152
|
+
rules.add_argument("cases", type=Path)
|
|
153
|
+
rules.add_argument("--split", choices=[golden.DEV, golden.TEST, "all"], default=golden.DEV)
|
|
154
|
+
rules.add_argument("--select", type=Path, help="write the trusted rules to this YAML file")
|
|
155
|
+
rules.add_argument("--min-hits", type=int, default=5)
|
|
156
|
+
rules.add_argument("--min-precision", type=float, default=0.95)
|
|
157
|
+
|
|
158
|
+
score = steps.add_parser("golden", help="score extraction against a labelled golden set")
|
|
159
|
+
score.add_argument("cases", type=Path)
|
|
160
|
+
score.add_argument("--split", choices=[golden.DEV, golden.TEST, "all"], default=golden.DEV)
|
|
161
|
+
score.add_argument(
|
|
162
|
+
"--high-confidence",
|
|
163
|
+
action="store_true",
|
|
164
|
+
help="count only claims found by trusted rules (what the benchmark publishes)",
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def run_command(args: argparse.Namespace, context: BenchContext) -> int:
|
|
169
|
+
handlers = {
|
|
170
|
+
"sample": _sample,
|
|
171
|
+
"commits": _commits,
|
|
172
|
+
"run": _run,
|
|
173
|
+
"facts": _facts,
|
|
174
|
+
"rescore": _rescore,
|
|
175
|
+
"summarize": _summarize,
|
|
176
|
+
"golden": _golden,
|
|
177
|
+
"merge-labels": _merge_labels,
|
|
178
|
+
"rules": _rules,
|
|
179
|
+
}
|
|
180
|
+
return handlers[args.bench_command](args, context)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _sample(args: argparse.Namespace, context: BenchContext) -> int:
|
|
184
|
+
agents = [a.strip() for a in args.agents.split(",")] if args.agents else None
|
|
185
|
+
exclude = {url for path in args.exclude_from for url in _urls_in(path)}
|
|
186
|
+
exclude_repos = {repo_of(url) for path in args.exclude_repos_from for url in _urls_in(path)}
|
|
187
|
+
try:
|
|
188
|
+
source = ParquetAidev(args.parquet) if args.parquet else context.aidev_factory()
|
|
189
|
+
with source as client:
|
|
190
|
+
sample = draw_sample(
|
|
191
|
+
client,
|
|
192
|
+
per_agent=args.per_agent,
|
|
193
|
+
seed=args.seed,
|
|
194
|
+
filter_name=args.filter,
|
|
195
|
+
agents=agents,
|
|
196
|
+
exclude=exclude,
|
|
197
|
+
exclude_repos=exclude_repos,
|
|
198
|
+
max_per_repo=args.max_per_repo,
|
|
199
|
+
draws_per_row=args.draws_per_row,
|
|
200
|
+
)
|
|
201
|
+
except (AidevError, ValueError) as error:
|
|
202
|
+
print(f"error: {error}", file=context.err)
|
|
203
|
+
return EXIT_ERROR
|
|
204
|
+
write_sample(sample, args.output)
|
|
205
|
+
print(f"wrote {len(sample.rows)} pull requests to {args.output}", file=context.out)
|
|
206
|
+
if sample.shortfall:
|
|
207
|
+
print(f"note: not enough matching rows for {sample.shortfall}", file=context.err)
|
|
208
|
+
return EXIT_OK
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _commits(args: argparse.Namespace, context: BenchContext) -> int:
|
|
212
|
+
"""One JSON line per sampled PR: url, agent and its first ``--per-pr`` commit messages."""
|
|
213
|
+
sample = read_sample(args.sample)
|
|
214
|
+
missing = [row.url for row in sample.rows if not row.id]
|
|
215
|
+
if missing:
|
|
216
|
+
print(f"error: {len(missing)} rows have no AIDev id; redraw the sample", file=context.err)
|
|
217
|
+
return EXIT_ERROR
|
|
218
|
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
|
219
|
+
try:
|
|
220
|
+
with context.aidev_factory() as client, args.output.open("w", encoding="utf-8") as out:
|
|
221
|
+
for row in sample.rows:
|
|
222
|
+
messages = client.commit_messages(row.id)[: args.per_pr]
|
|
223
|
+
record = {"url": row.url, "agent": row.agent, "commits": messages}
|
|
224
|
+
out.write(json.dumps(record, ensure_ascii=False) + "\n")
|
|
225
|
+
except (AidevError, ValueError) as error:
|
|
226
|
+
print(f"error: {error}", file=context.err)
|
|
227
|
+
return EXIT_ERROR
|
|
228
|
+
print(f"wrote commit messages for {len(sample.rows)} PRs to {args.output}", file=context.out)
|
|
229
|
+
return EXIT_OK
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _urls_in(path: Path) -> set[str]:
|
|
233
|
+
"""URLs of the records in a JSON Lines file (a sample's header record has none)."""
|
|
234
|
+
with path.open(encoding="utf-8") as handle:
|
|
235
|
+
records = (json.loads(line) for line in handle if line.strip())
|
|
236
|
+
return {record["url"] for record in records if "url" in record}
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _run(args: argparse.Namespace, context: BenchContext) -> int:
|
|
240
|
+
rows = read_sample(args.sample).rows
|
|
241
|
+
token = TokenResult(None, "none") if args.anonymous else context.token_resolver(context.env)
|
|
242
|
+
if token.token is None:
|
|
243
|
+
print(
|
|
244
|
+
"note: no GitHub token, so only about 10 PRs per hour can be checked", file=context.err
|
|
245
|
+
)
|
|
246
|
+
with context.client_factory(token.token, not args.no_cache) as client:
|
|
247
|
+
summary = run_benchmark(
|
|
248
|
+
rows,
|
|
249
|
+
args.output,
|
|
250
|
+
source=GitHubSource(client),
|
|
251
|
+
limit=args.limit,
|
|
252
|
+
progress=lambda message: print(message, file=context.err),
|
|
253
|
+
)
|
|
254
|
+
print(
|
|
255
|
+
f"checked {summary.checked}, errors {summary.errors}, "
|
|
256
|
+
f"already done {summary.skipped}"
|
|
257
|
+
+ (f"; stopped: {summary.stopped}" if summary.stopped else ""),
|
|
258
|
+
file=context.out,
|
|
259
|
+
)
|
|
260
|
+
return EXIT_OK
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _facts(args: argparse.Namespace, context: BenchContext) -> int:
|
|
264
|
+
"""Resumable like ``run``: PRs already in the output are skipped; a rate limit stops it."""
|
|
265
|
+
# Facts made by other code are as stale as the snapshot's own; fetch those again.
|
|
266
|
+
done = {
|
|
267
|
+
r["url"]
|
|
268
|
+
for r in (_records(args.output) if args.output.exists() else [])
|
|
269
|
+
if r.get("facts_version") == diff_facts.FACTS_VERSION or "error" in r
|
|
270
|
+
}
|
|
271
|
+
todo = [
|
|
272
|
+
r["url"] for r in read_results(args.results) if needs_file_facts(r) and r["url"] not in done
|
|
273
|
+
]
|
|
274
|
+
token = context.token_resolver(context.env)
|
|
275
|
+
if token.token is None:
|
|
276
|
+
print("note: no GitHub token, so only about 60 PRs per hour", file=context.err)
|
|
277
|
+
print(f"{len(todo)} PR(s) to re-read, {len(done)} already done", file=context.err)
|
|
278
|
+
fetched = stopped = 0
|
|
279
|
+
with (
|
|
280
|
+
context.client_factory(token.token, not args.no_cache) as client,
|
|
281
|
+
args.output.open("a", encoding="utf-8") as handle,
|
|
282
|
+
):
|
|
283
|
+
for url in todo:
|
|
284
|
+
try:
|
|
285
|
+
record = fetch_file_facts(client, url)
|
|
286
|
+
except RateLimited:
|
|
287
|
+
stopped = 1
|
|
288
|
+
break
|
|
289
|
+
except NotFound:
|
|
290
|
+
record = {"url": url, "error": "not_found"}
|
|
291
|
+
except GitHubError as error: # not recorded, so the next run retries it
|
|
292
|
+
print(f"error {url}: {error}", file=context.err)
|
|
293
|
+
continue
|
|
294
|
+
handle.write(json.dumps(record, sort_keys=True) + "\n")
|
|
295
|
+
handle.flush()
|
|
296
|
+
fetched += 1
|
|
297
|
+
# Progress on every PR, like `run`: a silent run of thousands of requests looks hung.
|
|
298
|
+
print(f"ok {fetched}/{len(todo)} {url}", file=context.err)
|
|
299
|
+
left = len(todo) - fetched # includes PRs that failed and will be retried
|
|
300
|
+
print(
|
|
301
|
+
f"fetched {fetched}, left {left}"
|
|
302
|
+
+ ("; stopped: GitHub rate limit reached, run again later" if stopped else ""),
|
|
303
|
+
file=context.out,
|
|
304
|
+
)
|
|
305
|
+
return EXIT_OK
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _rescore(args: argparse.Namespace, context: BenchContext) -> int:
|
|
309
|
+
facts: dict[str, dict] = {}
|
|
310
|
+
if args.facts:
|
|
311
|
+
facts = {
|
|
312
|
+
r["url"]: r
|
|
313
|
+
for r in _records(args.facts)
|
|
314
|
+
if r.get("facts_version") == diff_facts.FACTS_VERSION
|
|
315
|
+
}
|
|
316
|
+
records = read_results(args.results)
|
|
317
|
+
try:
|
|
318
|
+
rescored, mismatches = rescore_all(records, facts, pack_version=coding.load().version)
|
|
319
|
+
except AlreadyRescored as error:
|
|
320
|
+
print(f"error: {error}; re-score the original results file", file=context.err)
|
|
321
|
+
return EXIT_ERROR
|
|
322
|
+
with args.output.open("w", encoding="utf-8") as handle:
|
|
323
|
+
for record in rescored:
|
|
324
|
+
handle.write(json.dumps(record, sort_keys=True, ensure_ascii=False) + "\n")
|
|
325
|
+
missing = sum(needs_file_facts(r) and r["url"] not in facts for r in records)
|
|
326
|
+
errors = sum("rescore_error" in r for r in rescored)
|
|
327
|
+
print(
|
|
328
|
+
f"re-scored {len(rescored)} results; {len(facts)} with re-read diff counts, "
|
|
329
|
+
f"{missing} still without them (shown as not inspected); "
|
|
330
|
+
f"{mismatches} claim(s) could not be reproduced (now unverifiable), "
|
|
331
|
+
f"{errors} record(s) could not be rebuilt (RESCORE_ERROR)",
|
|
332
|
+
file=context.out,
|
|
333
|
+
)
|
|
334
|
+
return EXIT_OK
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _summarize(args: argparse.Namespace, context: BenchContext) -> int:
|
|
338
|
+
summary = stats.summarize(read_results(args.results))
|
|
339
|
+
args.output.mkdir(parents=True, exist_ok=True)
|
|
340
|
+
(args.output / "summary.json").write_text(
|
|
341
|
+
json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8"
|
|
342
|
+
)
|
|
343
|
+
(args.output / "summary.md").write_text(stats.to_markdown(summary), encoding="utf-8")
|
|
344
|
+
print(f"wrote summary.json and summary.md to {args.output}", file=context.out)
|
|
345
|
+
return EXIT_OK
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _golden(args: argparse.Namespace, context: BenchContext) -> int:
|
|
349
|
+
cases = golden.load_cases(args.cases)
|
|
350
|
+
if args.split != "all":
|
|
351
|
+
cases = golden.in_split(cases, args.split)
|
|
352
|
+
print(f"{len(cases)} cases ({args.split})", file=context.out)
|
|
353
|
+
print(golden.score(cases, high_only=args.high_confidence).report(), file=context.out)
|
|
354
|
+
return EXIT_OK
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _merge_labels(args: argparse.Namespace, context: BenchContext) -> int:
|
|
358
|
+
"""Merge labels; print agreement and every unresolved disagreement for adjudication."""
|
|
359
|
+
rows = [pull.to_dict() for pull in read_sample(args.sample).rows]
|
|
360
|
+
labels_a = {r["url"]: r for path in args.a for r in _records(path)}
|
|
361
|
+
labels_b = {r["url"]: r for path in args.b for r in _records(path)}
|
|
362
|
+
adjudications = (
|
|
363
|
+
json.loads(args.adjudications.read_text(encoding="utf-8")) if args.adjudications else {}
|
|
364
|
+
)
|
|
365
|
+
try:
|
|
366
|
+
result = golden.merge_labels(rows, labels_a, labels_b, adjudications)
|
|
367
|
+
except ValueError as error:
|
|
368
|
+
print(f"error: {error}", file=context.err)
|
|
369
|
+
return EXIT_ERROR
|
|
370
|
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
|
371
|
+
with args.output.open("w", encoding="utf-8") as handle:
|
|
372
|
+
for record in result.records:
|
|
373
|
+
handle.write(json.dumps(record, ensure_ascii=False, sort_keys=True) + "\n")
|
|
374
|
+
print(
|
|
375
|
+
f"exact agreement {result.exact_agreement}/{result.total}; "
|
|
376
|
+
f"wrote {len(result.records)} cases; unresolved {len(result.unresolved)}",
|
|
377
|
+
file=context.out,
|
|
378
|
+
)
|
|
379
|
+
kappas = ", ".join(
|
|
380
|
+
f"{kind} {value:.3f}" if value is not None else f"{kind} n/a"
|
|
381
|
+
for kind, value in result.kappa.items()
|
|
382
|
+
)
|
|
383
|
+
print(f"Cohen's kappa per type: {kappas}", file=context.out)
|
|
384
|
+
for record in result.unresolved:
|
|
385
|
+
summary = {k: record[k] for k in ("url", "labeller_a", "labeller_b", "notes_a", "notes_b")}
|
|
386
|
+
print(json.dumps(summary, ensure_ascii=False), file=context.out)
|
|
387
|
+
return EXIT_OK
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _records(path: Path) -> list[dict]:
|
|
391
|
+
with path.open(encoding="utf-8") as handle:
|
|
392
|
+
return [json.loads(line) for line in handle if line.strip()]
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _rules(args: argparse.Namespace, context: BenchContext) -> int:
|
|
396
|
+
cases = golden.load_cases(args.cases)
|
|
397
|
+
if args.split != "all":
|
|
398
|
+
cases = golden.in_split(cases, args.split)
|
|
399
|
+
print(f"{len(cases)} cases ({args.split})", file=context.out)
|
|
400
|
+
metrics = golden.score_rules(cases)
|
|
401
|
+
print(golden.rules_report(metrics), file=context.out)
|
|
402
|
+
if args.select:
|
|
403
|
+
trusted = golden.select_trusted(
|
|
404
|
+
metrics, min_hits=args.min_hits, min_precision=args.min_precision
|
|
405
|
+
)
|
|
406
|
+
document = {
|
|
407
|
+
"selected_on": {
|
|
408
|
+
"cases": args.cases.name,
|
|
409
|
+
"split": args.split,
|
|
410
|
+
"size": len(cases),
|
|
411
|
+
"min_hits": args.min_hits,
|
|
412
|
+
"min_precision": args.min_precision,
|
|
413
|
+
},
|
|
414
|
+
"trusted": trusted,
|
|
415
|
+
}
|
|
416
|
+
args.select.write_text(
|
|
417
|
+
TRUSTED_HEADER + yaml.safe_dump(document, sort_keys=False), encoding="utf-8"
|
|
418
|
+
)
|
|
419
|
+
print(f"wrote {len(trusted)} trusted rules to {args.select}", file=context.out)
|
|
420
|
+
return EXIT_OK
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
TRUSTED_HEADER = """\
|
|
424
|
+
# Extraction rules trusted for the benchmark: each fired at least min_hits times on the
|
|
425
|
+
# selection split with at least min_precision precision. Claims from other rules are kept but
|
|
426
|
+
# marked low confidence. Generated by `second-source bench rules --select`; do not edit by hand.
|
|
427
|
+
"""
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"""``second-source`` command line.
|
|
2
|
+
|
|
3
|
+
second-source check https://github.com/owner/repo/pull/123
|
|
4
|
+
second-source check owner/repo#123 --json
|
|
5
|
+
second-source bench ... (the benchmark; see cli/bench.py)
|
|
6
|
+
|
|
7
|
+
Zero setup: a token is picked up from GITHUB_TOKEN / GH_TOKEN or the GitHub CLI if present;
|
|
8
|
+
without one the public API is used (60 requests per hour, enough for a few PRs).
|
|
9
|
+
|
|
10
|
+
Exit codes (useful in scripts and CI):
|
|
11
|
+
0 checked; no claim was contradicted
|
|
12
|
+
1 checked; at least one claim was contradicted
|
|
13
|
+
2 could not check (bad reference, PR not found, network or API error)
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import sys
|
|
22
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import TextIO
|
|
25
|
+
|
|
26
|
+
from second_source import __version__
|
|
27
|
+
from second_source.benchmark.aidev import AidevClient
|
|
28
|
+
from second_source.cli import bench
|
|
29
|
+
from second_source.core.model import Result
|
|
30
|
+
from second_source.pipeline import check_pull_request
|
|
31
|
+
from second_source.report.render import to_json, to_text
|
|
32
|
+
from second_source.sources.github.auth import TokenResult, resolve_token
|
|
33
|
+
from second_source.sources.github.cache import DiskCache
|
|
34
|
+
from second_source.sources.github.client import GitHubClient, GitHubError
|
|
35
|
+
from second_source.sources.github.source import GitHubSource, PullRequestNotFound
|
|
36
|
+
from second_source.sources.github.urls import parse_pull_request
|
|
37
|
+
|
|
38
|
+
EXIT_OK = 0
|
|
39
|
+
EXIT_CONTRADICTED = 1
|
|
40
|
+
EXIT_ERROR = 2
|
|
41
|
+
|
|
42
|
+
ClientFactory = Callable[[str | None, bool], GitHubClient]
|
|
43
|
+
TokenResolver = Callable[[Mapping[str, str] | None], TokenResult]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def default_client_factory(token: str | None, use_cache: bool) -> GitHubClient:
|
|
47
|
+
return GitHubClient(token, cache=DiskCache() if use_cache else None)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
51
|
+
parser = argparse.ArgumentParser(
|
|
52
|
+
prog="second-source",
|
|
53
|
+
description="Check whether an AI agent's claims in a pull request are true.",
|
|
54
|
+
)
|
|
55
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
56
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
57
|
+
|
|
58
|
+
check = commands.add_parser("check", help="check the claims in one pull request")
|
|
59
|
+
check.add_argument("pull_request", help="PR URL or owner/repo#number")
|
|
60
|
+
check.add_argument("--json", action="store_true", help="print machine-readable JSON")
|
|
61
|
+
check.add_argument("--no-cache", action="store_true", help="do not use the on-disk cache")
|
|
62
|
+
check.add_argument("--no-color", action="store_true", help="disable coloured output")
|
|
63
|
+
check.add_argument(
|
|
64
|
+
"--anonymous",
|
|
65
|
+
action="store_true",
|
|
66
|
+
help="use the public API without any token, even if one is available",
|
|
67
|
+
)
|
|
68
|
+
bench.add_parser(commands)
|
|
69
|
+
commands.add_parser(
|
|
70
|
+
"action", help="run as the GitHub Action (reads its inputs from the environment)"
|
|
71
|
+
)
|
|
72
|
+
init = commands.add_parser("init", help="add the Second Source workflow to a repository")
|
|
73
|
+
init.add_argument("--path", type=Path, default=Path("."), help="repository root")
|
|
74
|
+
init.add_argument("--force", action="store_true", help="overwrite an existing workflow")
|
|
75
|
+
return parser
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def main(
|
|
79
|
+
argv: Sequence[str] | None = None,
|
|
80
|
+
*,
|
|
81
|
+
client_factory: ClientFactory = default_client_factory,
|
|
82
|
+
token_resolver: TokenResolver = resolve_token,
|
|
83
|
+
aidev_factory: Callable[[], AidevClient] = AidevClient,
|
|
84
|
+
env: Mapping[str, str] | None = None,
|
|
85
|
+
stdout: TextIO | None = None,
|
|
86
|
+
stderr: TextIO | None = None,
|
|
87
|
+
) -> int:
|
|
88
|
+
out = stdout or sys.stdout
|
|
89
|
+
err = stderr or sys.stderr
|
|
90
|
+
args = build_parser().parse_args(argv)
|
|
91
|
+
|
|
92
|
+
if args.command == "action":
|
|
93
|
+
from second_source.action.main import run_action # only needed inside Actions
|
|
94
|
+
|
|
95
|
+
return run_action(os.environ if env is None else env, out=out)
|
|
96
|
+
if args.command == "init":
|
|
97
|
+
return _init(args, out, err)
|
|
98
|
+
if args.command == "bench":
|
|
99
|
+
context = bench.BenchContext(
|
|
100
|
+
client_factory=client_factory,
|
|
101
|
+
token_resolver=token_resolver,
|
|
102
|
+
aidev_factory=aidev_factory,
|
|
103
|
+
env=env,
|
|
104
|
+
out=out,
|
|
105
|
+
err=err,
|
|
106
|
+
)
|
|
107
|
+
return bench.run_command(args, context)
|
|
108
|
+
return _check(args, client_factory, token_resolver, env, out, err)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _check(
|
|
112
|
+
args: argparse.Namespace,
|
|
113
|
+
client_factory: ClientFactory,
|
|
114
|
+
token_resolver: TokenResolver,
|
|
115
|
+
env: Mapping[str, str] | None,
|
|
116
|
+
out: TextIO,
|
|
117
|
+
err: TextIO,
|
|
118
|
+
) -> int:
|
|
119
|
+
try:
|
|
120
|
+
ref = parse_pull_request(args.pull_request)
|
|
121
|
+
except ValueError as error:
|
|
122
|
+
print(f"error: {error}", file=err)
|
|
123
|
+
return EXIT_ERROR
|
|
124
|
+
|
|
125
|
+
token = TokenResult(None, "none") if args.anonymous else token_resolver(env)
|
|
126
|
+
if token.token is None and not args.json:
|
|
127
|
+
print(
|
|
128
|
+
"note: no GitHub token found, using the public API (60 requests/hour). "
|
|
129
|
+
"Set GITHUB_TOKEN or run `gh auth login` for more.",
|
|
130
|
+
file=err,
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
with client_factory(token.token, not args.no_cache) as client:
|
|
134
|
+
try:
|
|
135
|
+
report = check_pull_request(ref, GitHubSource(client))
|
|
136
|
+
except PullRequestNotFound as error:
|
|
137
|
+
print(f"error: {error}", file=err)
|
|
138
|
+
return EXIT_ERROR
|
|
139
|
+
except GitHubError as error:
|
|
140
|
+
print(f"error: could not read the pull request from GitHub: {error}", file=err)
|
|
141
|
+
return EXIT_ERROR
|
|
142
|
+
|
|
143
|
+
if args.json:
|
|
144
|
+
print(json.dumps(to_json(report), indent=2), file=out)
|
|
145
|
+
else:
|
|
146
|
+
color = not args.no_color and _supports_color(out, env)
|
|
147
|
+
print(to_text(report, color=color), file=out)
|
|
148
|
+
|
|
149
|
+
contradicted = any(v.result is Result.CONTRADICTED for v in report.verdicts)
|
|
150
|
+
return EXIT_CONTRADICTED if contradicted else EXIT_OK
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _init(args: argparse.Namespace, out: TextIO, err: TextIO) -> int:
|
|
154
|
+
from second_source.action.setup import WorkflowExists, write_workflow
|
|
155
|
+
|
|
156
|
+
try:
|
|
157
|
+
path, names = write_workflow(args.path, force=args.force)
|
|
158
|
+
except WorkflowExists as existing:
|
|
159
|
+
print(f"error: {existing} already exists (use --force to overwrite)", file=err)
|
|
160
|
+
return EXIT_ERROR
|
|
161
|
+
print(f"wrote {path}", file=out)
|
|
162
|
+
if names:
|
|
163
|
+
print(f"re-checks after these CI workflows finish: {', '.join(names)}", file=out)
|
|
164
|
+
else:
|
|
165
|
+
print("no CI workflows found; the daily run will pick up CI results", file=out)
|
|
166
|
+
print("next: commit the file and open a pull request", file=out)
|
|
167
|
+
return EXIT_OK
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _supports_color(stream: TextIO, env: Mapping[str, str] | None) -> bool:
|
|
171
|
+
"""Colour only for real terminals, and never when NO_COLOR is set (no-color.org)."""
|
|
172
|
+
environment = os.environ if env is None else env
|
|
173
|
+
return stream.isatty() and "NO_COLOR" not in environment
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def run() -> None:
|
|
177
|
+
"""Console-script entry point."""
|
|
178
|
+
sys.exit(main())
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
if __name__ == "__main__":
|
|
182
|
+
run()
|