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,503 @@
|
|
|
1
|
+
"""Render a PullRequestReport for people (terminal, Markdown) and for programs (JSON).
|
|
2
|
+
|
|
3
|
+
All three renderers share ``rows()``, so the terminal, the GitHub check and the JSON output
|
|
4
|
+
always say the same thing about each claim.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from collections import Counter
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from second_source.core.model import Claim, Result, Verdict
|
|
15
|
+
from second_source.pipeline import PullRequestReport
|
|
16
|
+
|
|
17
|
+
JSON_SCHEMA_VERSION = "2" # 2: caveats, withdrawn, check roles, opened_at
|
|
18
|
+
|
|
19
|
+
SYMBOLS = {
|
|
20
|
+
Result.VERIFIED: "✔",
|
|
21
|
+
Result.CONTRADICTED: "✘",
|
|
22
|
+
Result.PENDING: "…",
|
|
23
|
+
Result.UNVERIFIABLE: "?",
|
|
24
|
+
}
|
|
25
|
+
WORDS = {
|
|
26
|
+
Result.VERIFIED: "verified",
|
|
27
|
+
Result.CONTRADICTED: "contradicted",
|
|
28
|
+
Result.PENDING: "pending",
|
|
29
|
+
Result.UNVERIFIABLE: "unverifiable",
|
|
30
|
+
}
|
|
31
|
+
_ANSI = {
|
|
32
|
+
Result.VERIFIED: "\033[32m", # green
|
|
33
|
+
Result.CONTRADICTED: "\033[31m", # red
|
|
34
|
+
Result.PENDING: "\033[33m", # yellow
|
|
35
|
+
Result.UNVERIFIABLE: "\033[90m", # grey
|
|
36
|
+
}
|
|
37
|
+
_RESET = "\033[0m"
|
|
38
|
+
|
|
39
|
+
# Reasons shown in words: what the integrity guards found (docs/packs/coding.md, "Integrity
|
|
40
|
+
# guards"), and absences that are not proof.
|
|
41
|
+
GUARD_TEXT = {
|
|
42
|
+
"PR_SKIPS_TESTS": "this PR skips tests",
|
|
43
|
+
"PR_WEAKENS_TEST_COMMAND": "this PR weakens how CI runs tests",
|
|
44
|
+
"PR_LOWERS_COVERAGE_GATE": "this PR lowers the coverage gate",
|
|
45
|
+
"ADDED_TESTS_ARE_SKIPPED": "the added tests are skipped",
|
|
46
|
+
"PR_CHANGES_CI_CONFIG": "this PR changed CI or test configuration",
|
|
47
|
+
"PR_REMOVES_TESTS": "this PR removes tests while the code stays",
|
|
48
|
+
"LINT_SUPPRESSIONS_ADDED": "this PR adds lint suppressions",
|
|
49
|
+
"LINT_CONFIG_CHANGED": "this PR changed lint configuration",
|
|
50
|
+
"MATCHING_JOB_SKIPPED": "some matching CI jobs were skipped",
|
|
51
|
+
"CI_TOLERATES_TEST_FAILURES": "this PR lets CI continue when tests fail",
|
|
52
|
+
"BUILD_SKIPS_TESTS": "this PR makes a build command skip tests",
|
|
53
|
+
"NOT_INSPECTED": "GitHub's API left out the diff of some files, so they were not inspected",
|
|
54
|
+
"GUARD_ERROR": "an integrity guard could not be evaluated",
|
|
55
|
+
# Absence that is not proof (never CONTRADICTED; see the check files for why).
|
|
56
|
+
"NO_TEST_FILES_FOUND": "no test file found in the changed files (tests inside code files"
|
|
57
|
+
" are not detected)",
|
|
58
|
+
"NO_DOC_FILES_FOUND": "no documentation file found in the changed files (docs inside code"
|
|
59
|
+
" are not detected)",
|
|
60
|
+
"REOPENED_THEN_CLOSED": "the issue was reopened after the merge, then closed again",
|
|
61
|
+
"REVERT_UNDONE": "the merge was reverted, then the revert was itself reverted",
|
|
62
|
+
}
|
|
63
|
+
# Every other reason in words, for people reading a check run; the JSON report keeps the
|
|
64
|
+
# codes. A reason missing here is shown as its code (tests keep this table complete).
|
|
65
|
+
REASON_TEXT = {
|
|
66
|
+
"ALL_MATCHING_CI_JOBS_PASSED": "every matching CI job passed",
|
|
67
|
+
"AWAITING_CI": "waiting for CI to finish",
|
|
68
|
+
"CI_JOB_FAILED": "a matching CI job failed",
|
|
69
|
+
"CI_FAILED_LOCAL_CLAIM": "CI failed, but the claim was about a local run",
|
|
70
|
+
"CI_FAILED_SUBSET_CLAIM": "CI failed, but the claim covered only part of the checks",
|
|
71
|
+
"CLAIM_COMMIT_AMBIGUOUS": "CI failed on only one of the commits the claim could mean",
|
|
72
|
+
"CI_TIMEOUT": "CI did not finish in time",
|
|
73
|
+
"NO_CI_RECORDS": "no CI ran on this commit (or its results were deleted)",
|
|
74
|
+
"NO_CI_RESULTS": "the matching CI jobs were skipped, cancelled or timed out",
|
|
75
|
+
"NO_MATCHING_CI_JOBS": "CI ran, but no job matched this claim",
|
|
76
|
+
"NO_COMMIT_REFERENCE": "no commit to check it against",
|
|
77
|
+
"SOURCE_STALE": "GitHub's data could not be read",
|
|
78
|
+
"TEST_FILES_CHANGED": "test files changed",
|
|
79
|
+
"DOC_FILES_CHANGED": "documentation files changed",
|
|
80
|
+
"NO_FILE_LIST": "the changed files could not be read",
|
|
81
|
+
"ISSUE_CLOSED_BY_MERGE": "the issue was closed when the PR merged",
|
|
82
|
+
"ISSUE_ALREADY_CLOSED": "the issue was already closed before the PR",
|
|
83
|
+
"ISSUE_STILL_OPEN": "the issue is still open after the merge",
|
|
84
|
+
"ISSUE_OPEN": "the issue is open",
|
|
85
|
+
"ISSUE_REOPENED": "the issue was reopened after the merge",
|
|
86
|
+
"ISSUE_STAYED_CLOSED": "the issue stayed closed",
|
|
87
|
+
"ISSUE_NOT_ACCESSIBLE": "the issue could not be read",
|
|
88
|
+
"NOT_AUTO_CLOSED": "GitHub does not close issues referenced this way",
|
|
89
|
+
"NOT_DEFAULT_BRANCH": "merged into a branch other than the default",
|
|
90
|
+
"NO_CLOSE_TIME": "GitHub gave no close time for the issue",
|
|
91
|
+
"NO_MERGE_TIME": "GitHub gave no merge time",
|
|
92
|
+
"NO_PR_STATE": "the PR's state could not be read",
|
|
93
|
+
"NOT_MERGED": "the PR was not merged",
|
|
94
|
+
"PR_NOT_MERGED": "the PR was closed without merging",
|
|
95
|
+
"NOT_MERGED_YET": "decided once the PR is merged",
|
|
96
|
+
"CLOSE_PENDING": "merged; waiting for GitHub to close the issue",
|
|
97
|
+
"IN_WINDOW": "still being watched",
|
|
98
|
+
"NOT_REVERTED": "not reverted",
|
|
99
|
+
"REVERTED": "the merge was reverted",
|
|
100
|
+
"DEPLOYMENT_SUCCEEDED": "a deployment of this commit succeeded",
|
|
101
|
+
"DEPLOYMENT_FAILED": "every deployment of this commit failed",
|
|
102
|
+
"DEPLOYMENT_FAILED_UNCLEAR": "a deployment failed, but GitHub may not list them all",
|
|
103
|
+
"DEPLOYMENT_UNCLEAR": "the deployments do not settle it",
|
|
104
|
+
"DEPLOYING": "a deployment is still running",
|
|
105
|
+
"NO_DEPLOYMENT_RECORDS": "no deployment of this commit was found",
|
|
106
|
+
}
|
|
107
|
+
WITHDRAWN_SYMBOL, WITHDRAWN_WORD = "⚠", "not verified"
|
|
108
|
+
|
|
109
|
+
# Pending reasons whose code alone misleads a reader: after the merge, "Fixes #3: pending
|
|
110
|
+
# (IN_WINDOW)" reads as if the issue were still open. Keyed by claim type and reason; the JSON
|
|
111
|
+
# report keeps the codes.
|
|
112
|
+
PENDING_TEXT = {
|
|
113
|
+
("FIXES_ISSUE", "IN_WINDOW"): "issue closed; watching for a reopen",
|
|
114
|
+
("MERGE_HOLDS", "IN_WINDOW"): "not reverted so far; watching for a revert",
|
|
115
|
+
("FIXES_ISSUE", "NOT_MERGED_YET"): "decided once the PR is merged",
|
|
116
|
+
("FIXES_ISSUE", "CLOSE_PENDING"): "merged; waiting for GitHub to close the issue",
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def guard_text(reason: str) -> str:
|
|
121
|
+
return GUARD_TEXT.get(reason) or REASON_TEXT.get(reason, reason)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def withdrawn_reasons(verdict: Verdict) -> tuple[str, ...]:
|
|
125
|
+
"""Reasons of guards that withdrew a verification: the deciding checks all said VERIFIED
|
|
126
|
+
and only guards made the claim UNVERIFIABLE. Empty for every other verdict, including a
|
|
127
|
+
claim that was already unverifiable for its own reasons (CI stale, no matching job)."""
|
|
128
|
+
if verdict.result is not Result.UNVERIFIABLE:
|
|
129
|
+
return ()
|
|
130
|
+
guard_reasons = {
|
|
131
|
+
run.reason
|
|
132
|
+
for run in verdict.check_runs
|
|
133
|
+
if run.role == "guard" and run.result is Result.UNVERIFIABLE
|
|
134
|
+
}
|
|
135
|
+
other_reasons = {
|
|
136
|
+
run.reason
|
|
137
|
+
for run in verdict.check_runs
|
|
138
|
+
if run.role != "guard" and run.result is not Result.VERIFIED
|
|
139
|
+
}
|
|
140
|
+
if not verdict.reasons or any(
|
|
141
|
+
reason not in guard_reasons or reason in other_reasons for reason in verdict.reasons
|
|
142
|
+
):
|
|
143
|
+
return ()
|
|
144
|
+
return verdict.reasons
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
# Display order: problems first.
|
|
148
|
+
_ORDER = [Result.CONTRADICTED, Result.UNVERIFIABLE, Result.PENDING, Result.VERIFIED]
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
@dataclass(frozen=True)
|
|
152
|
+
class Row:
|
|
153
|
+
"""One claim with its verdict, prepared for display."""
|
|
154
|
+
|
|
155
|
+
label: str
|
|
156
|
+
result: Result
|
|
157
|
+
reasons: tuple[str, ...]
|
|
158
|
+
details: tuple[str, ...] # one explanation per check run
|
|
159
|
+
origin: str
|
|
160
|
+
span: str | None
|
|
161
|
+
ref: str | None
|
|
162
|
+
withdrawn: tuple[str, ...] = () # guard reasons that withdrew a verification
|
|
163
|
+
cautions: tuple[str, ...] = () # optional guard reasons shown next to the result
|
|
164
|
+
claim_type: str = ""
|
|
165
|
+
|
|
166
|
+
@property
|
|
167
|
+
def symbol(self) -> str:
|
|
168
|
+
return WITHDRAWN_SYMBOL if self.withdrawn else SYMBOLS[self.result]
|
|
169
|
+
|
|
170
|
+
@property
|
|
171
|
+
def word(self) -> str:
|
|
172
|
+
return WITHDRAWN_WORD if self.withdrawn else WORDS[self.result]
|
|
173
|
+
|
|
174
|
+
@property
|
|
175
|
+
def why(self) -> str:
|
|
176
|
+
"""Reasons, with guard findings in words and cautions after them."""
|
|
177
|
+
parts = [self._reason_text(r) for r in self.reasons]
|
|
178
|
+
parts += [f"caution: {guard_text(c)}" for c in self.cautions]
|
|
179
|
+
return ", ".join(parts)
|
|
180
|
+
|
|
181
|
+
def _reason_text(self, reason: str) -> str:
|
|
182
|
+
if self.result is Result.PENDING and (self.claim_type, reason) in PENDING_TEXT:
|
|
183
|
+
return PENDING_TEXT[(self.claim_type, reason)]
|
|
184
|
+
return guard_text(reason)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def describe_claim(claim: Claim) -> str:
|
|
188
|
+
"""A short human description of a claim, e.g. "Fixes #12" or "Deployed to staging"."""
|
|
189
|
+
attributes = claim.attributes
|
|
190
|
+
match claim.type:
|
|
191
|
+
case "TESTS_PASS":
|
|
192
|
+
return "Tests pass"
|
|
193
|
+
case "BUILD_OK":
|
|
194
|
+
return "Build succeeds"
|
|
195
|
+
case "LINT_OK":
|
|
196
|
+
return "Lint passes"
|
|
197
|
+
case "TESTS_ADDED":
|
|
198
|
+
return "Tests added"
|
|
199
|
+
case "DOCS_UPDATED":
|
|
200
|
+
return "Docs updated"
|
|
201
|
+
case "FIXES_ISSUE":
|
|
202
|
+
repo = attributes.get("repo") or ""
|
|
203
|
+
return f"Fixes {repo}#{attributes.get('issue')}"
|
|
204
|
+
case "DEPLOYED":
|
|
205
|
+
return f"Deployed to {attributes.get('environment')}"
|
|
206
|
+
case "MERGE_HOLDS":
|
|
207
|
+
return "Merged change holds (not reverted)"
|
|
208
|
+
case _:
|
|
209
|
+
return claim.type
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def rows(report: PullRequestReport) -> list[Row]:
|
|
213
|
+
prepared = []
|
|
214
|
+
for claim in report.claims:
|
|
215
|
+
verdict: Verdict = report.verdict_for(claim)
|
|
216
|
+
label = describe_claim(claim)
|
|
217
|
+
if claim.attributes.get("confidence") == "low":
|
|
218
|
+
# Found by an extraction rule that has not proven its precision on the golden set:
|
|
219
|
+
# the agent may not have meant this as a claim.
|
|
220
|
+
label += " (low confidence)"
|
|
221
|
+
prepared.append(
|
|
222
|
+
Row(
|
|
223
|
+
label=label,
|
|
224
|
+
result=verdict.result,
|
|
225
|
+
reasons=verdict.reasons,
|
|
226
|
+
details=tuple(
|
|
227
|
+
f"{run.check_id}: {run.explanation or run.reason}"
|
|
228
|
+
for run in verdict.check_runs
|
|
229
|
+
# A guard that found nothing is noise in the details.
|
|
230
|
+
if not (run.role == "guard" and run.result is Result.VERIFIED)
|
|
231
|
+
),
|
|
232
|
+
origin=claim.origin,
|
|
233
|
+
span=claim.span,
|
|
234
|
+
ref=claim.attributes.get("ref"),
|
|
235
|
+
withdrawn=withdrawn_reasons(verdict),
|
|
236
|
+
cautions=verdict.caveats,
|
|
237
|
+
claim_type=claim.type,
|
|
238
|
+
)
|
|
239
|
+
)
|
|
240
|
+
return sorted(prepared, key=lambda row: _ORDER.index(row.result))
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def summary_counts(report: PullRequestReport) -> Counter[Result]:
|
|
244
|
+
return Counter(verdict.result for verdict in report.verdicts)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _agent_line(report: PullRequestReport) -> str:
|
|
248
|
+
if report.agent is None:
|
|
249
|
+
return "Agent: not detected (no known coding-agent signal)"
|
|
250
|
+
match = report.agent
|
|
251
|
+
return f"Agent: {match.agent} (detected by {match.signal.value}: {match.detail})"
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _summary_line(report: PullRequestReport) -> str:
|
|
255
|
+
counts = summary_counts(report)
|
|
256
|
+
parts = [f"{counts[result]} {WORDS[result]}" for result in _ORDER if counts[result]]
|
|
257
|
+
return ", ".join(parts) if parts else "no claims found"
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
# ---- terminal --------------------------------------------------------------------------------
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def to_text(report: PullRequestReport, *, color: bool = False) -> str:
|
|
264
|
+
def paint(result: Result, text: str) -> str:
|
|
265
|
+
return f"{_ANSI[result]}{text}{_RESET}" if color else text
|
|
266
|
+
|
|
267
|
+
lines = [
|
|
268
|
+
f"Second Source · {report.ref} · {report.ref.url}",
|
|
269
|
+
_agent_line(report),
|
|
270
|
+
f"Claims: {_summary_line(report)}",
|
|
271
|
+
"",
|
|
272
|
+
]
|
|
273
|
+
for row in rows(report):
|
|
274
|
+
lines.append(paint(row.result, f"{row.symbol} {row.word:<12} {row.label}"))
|
|
275
|
+
if row.span:
|
|
276
|
+
lines.append(f' said in {row.origin}: "{printable(row.span)}"')
|
|
277
|
+
lines.append(f" why: {row.why}")
|
|
278
|
+
lines.extend(f" - {detail}" for detail in row.details)
|
|
279
|
+
if report.stale:
|
|
280
|
+
lines += ["", f"Not fully checked (data unavailable): {', '.join(sorted(report.stale))}"]
|
|
281
|
+
lines += ["", f"GitHub API requests: {report.api_requests}"]
|
|
282
|
+
return "\n".join(lines)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
# ---- Markdown (GitHub check runs and job summaries) ------------------------------------------
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
# C0 and C1 control characters (except tab) and bidirectional overrides: in a terminal they can
|
|
289
|
+
# rewrite the screen or the clipboard; in Markdown they can hide or reorder text.
|
|
290
|
+
_UNSAFE = re.compile(r"[\x00-\x08\x0b-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]")
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def printable(text: str) -> str:
|
|
294
|
+
"""PR text with control and bidi-override characters replaced (security review 1, L2)."""
|
|
295
|
+
return _UNSAFE.sub("\ufffd", text)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
_CROSS_REPO_REF = re.compile(r"\S+/\S+#[0-9]+")
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def code_span(text: str) -> str:
|
|
302
|
+
"""PR text as an inline code span: GitHub renders it literally, so HTML, links, images and
|
|
303
|
+
@-mentions in it stay inert (security review 1, M1). The fence is longer than any run of
|
|
304
|
+
backticks inside, as CommonMark requires."""
|
|
305
|
+
text = printable(text).replace("\n", " ")
|
|
306
|
+
longest = max((len(run) for run in re.findall(r"`+", text)), default=0)
|
|
307
|
+
fence = "`" * (longest + 1)
|
|
308
|
+
return f"{fence} {text} {fence}"
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def escape_markdown_cell(text: str) -> str:
|
|
312
|
+
"""Escape text for a Markdown table cell."""
|
|
313
|
+
return text.replace("|", "\\|").replace("\n", " ")
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
_OWN_CHECKS = frozenset({"Second Source", "second-source"})
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def evidence_digest(report: PullRequestReport) -> list[str]:
|
|
320
|
+
"""What GitHub's own record says about this PR, whatever the agent claimed: CI on the head
|
|
321
|
+
commit, what the change touched, merge and revert state. Shown on every report, so the
|
|
322
|
+
check is useful on PRs that make no claims too (product review 1, F3).
|
|
323
|
+
|
|
324
|
+
Only evidence that was fetched is described; a line is left out rather than guessed.
|
|
325
|
+
"""
|
|
326
|
+
records = report.evidence
|
|
327
|
+
lines: list[str] = []
|
|
328
|
+
if "check_result" in report.fetched and "check_result" not in report.stale:
|
|
329
|
+
jobs = [
|
|
330
|
+
e.attributes
|
|
331
|
+
for e in records
|
|
332
|
+
if e.record_type == "check_result"
|
|
333
|
+
and e.attributes.get("ref") == report.head_sha
|
|
334
|
+
and e.attributes.get("name") not in _OWN_CHECKS
|
|
335
|
+
]
|
|
336
|
+
if not jobs:
|
|
337
|
+
lines.append("CI on the head commit: no CI results (yet)")
|
|
338
|
+
else:
|
|
339
|
+
running = sum(1 for j in jobs if j.get("status") != "completed")
|
|
340
|
+
failed = sorted(j["name"] for j in jobs if j.get("conclusion") == "failure")
|
|
341
|
+
passed = sum(1 for j in jobs if j.get("conclusion") == "success")
|
|
342
|
+
parts = [f"{passed} passed"]
|
|
343
|
+
if failed:
|
|
344
|
+
shown = ", ".join(failed[:5]) + (" …" if len(failed) > 5 else "")
|
|
345
|
+
parts.append(f"{len(failed)} failed ({shown})")
|
|
346
|
+
if running:
|
|
347
|
+
parts.append(f"{running} still running")
|
|
348
|
+
others = len(jobs) - passed - len(failed) - running
|
|
349
|
+
if others:
|
|
350
|
+
parts.append(f"{others} skipped, cancelled or neutral")
|
|
351
|
+
lines.append(f"CI on the head commit: {', '.join(parts)}")
|
|
352
|
+
summary = next(
|
|
353
|
+
(e.attributes for e in records if e.record_type == "changed_files_summary"), None
|
|
354
|
+
)
|
|
355
|
+
if summary is not None:
|
|
356
|
+
touched = [
|
|
357
|
+
f"{summary.get('files', 0)} file(s) changed",
|
|
358
|
+
"test files changed" if summary.get("test_source_changed") else "no test files changed",
|
|
359
|
+
]
|
|
360
|
+
if summary.get("ci_config_changed"):
|
|
361
|
+
touched.append("**CI configuration changed**")
|
|
362
|
+
if summary.get("removed_test_files"):
|
|
363
|
+
touched.append(f"{summary['removed_test_files']} test file(s) removed")
|
|
364
|
+
if summary.get("lint_suppressions_added"):
|
|
365
|
+
touched.append("lint suppressions added")
|
|
366
|
+
lines.append("Change: " + "; ".join(touched))
|
|
367
|
+
pr = next((e.attributes for e in records if e.record_type == "pr_state"), None)
|
|
368
|
+
if pr is not None:
|
|
369
|
+
if pr.get("merged"):
|
|
370
|
+
reverts = [
|
|
371
|
+
e for e in records if e.record_type == "revert" and not e.attributes.get("undone")
|
|
372
|
+
]
|
|
373
|
+
watch = "reverted" if reverts else "no revert found so far"
|
|
374
|
+
lines.append(f"Merged; {watch}")
|
|
375
|
+
else:
|
|
376
|
+
lines.append("Not merged" + (" (closed)" if pr.get("state") == "closed" else ""))
|
|
377
|
+
return [f"- {line}" for line in lines]
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def to_markdown(report: PullRequestReport) -> str:
|
|
381
|
+
lines = [
|
|
382
|
+
f"**Second Source** checked the claims in {report.ref}.",
|
|
383
|
+
"",
|
|
384
|
+
_agent_line(report),
|
|
385
|
+
"",
|
|
386
|
+
f"**Claims:** {_summary_line(report)}",
|
|
387
|
+
"",
|
|
388
|
+
]
|
|
389
|
+
table = rows(report)
|
|
390
|
+
if table:
|
|
391
|
+
lines += ["| | Claim | Result | Why | Said in |", "|---|---|---|---|---|"]
|
|
392
|
+
for row in table:
|
|
393
|
+
said = f"{row.origin}: {code_span(row.span)}" if row.span else row.origin
|
|
394
|
+
# A repository named in "Fixes owner/name#12" comes from PR text, and a name such
|
|
395
|
+
# as "a/_www.example.com" would render as a live link: show it as code
|
|
396
|
+
# (security review 2, N8).
|
|
397
|
+
label = escape_markdown_cell(_CROSS_REPO_REF.sub(lambda m: code_span(m[0]), row.label))
|
|
398
|
+
why = escape_markdown_cell(row.why)
|
|
399
|
+
lines.append(
|
|
400
|
+
f"| {row.symbol} | {label} | {row.word} | {why} | {escape_markdown_cell(said)} |"
|
|
401
|
+
)
|
|
402
|
+
digest = evidence_digest(report)
|
|
403
|
+
if digest:
|
|
404
|
+
while lines and lines[-1] == "":
|
|
405
|
+
lines.pop() # the claims line already ends a paragraph when there is no table
|
|
406
|
+
lines += ["", "**Evidence at a glance** (from GitHub, whatever was claimed):", "", *digest]
|
|
407
|
+
if report.stale:
|
|
408
|
+
lines += ["", f"_Not fully checked (data unavailable): {', '.join(sorted(report.stale))}_"]
|
|
409
|
+
lines += [
|
|
410
|
+
"",
|
|
411
|
+
"Missing or unavailable evidence is reported as *unverifiable*, never as contradicted.",
|
|
412
|
+
"*Low confidence* marks claims found by text patterns whose accuracy is not yet proven.",
|
|
413
|
+
"*Not verified* (⚠) means CI passed but the same PR changed what passing means (skipped",
|
|
414
|
+
"tests, a weakened test command); a *caution* is shown without changing the result.",
|
|
415
|
+
]
|
|
416
|
+
return "\n".join(lines)
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
# ---- JSON ------------------------------------------------------------------------------------
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def to_json(report: PullRequestReport) -> dict[str, Any]:
|
|
423
|
+
"""A stable, versioned structure for scripts. Times are ISO 8601 UTC."""
|
|
424
|
+
claims = []
|
|
425
|
+
for claim in report.claims:
|
|
426
|
+
verdict = report.verdict_for(claim)
|
|
427
|
+
claims.append(
|
|
428
|
+
{
|
|
429
|
+
"id": claim.id,
|
|
430
|
+
"type": claim.type,
|
|
431
|
+
"label": describe_claim(claim),
|
|
432
|
+
"origin": claim.origin,
|
|
433
|
+
"made_at": claim.made_at.isoformat(),
|
|
434
|
+
"span": claim.span,
|
|
435
|
+
"attributes": {k: _plain(v) for k, v in claim.attributes.items()},
|
|
436
|
+
"result": verdict.result.value,
|
|
437
|
+
"reasons": list(verdict.reasons),
|
|
438
|
+
"withdrawn": list(withdrawn_reasons(verdict)),
|
|
439
|
+
"caveats": list(verdict.caveats),
|
|
440
|
+
"checks": [
|
|
441
|
+
{
|
|
442
|
+
"id": run.check_id,
|
|
443
|
+
"version": run.check_version,
|
|
444
|
+
"level": run.level.value,
|
|
445
|
+
"role": run.role,
|
|
446
|
+
"result": run.result.value,
|
|
447
|
+
"reason": run.reason,
|
|
448
|
+
"explanation": run.explanation,
|
|
449
|
+
"inputs_hash": run.inputs_hash,
|
|
450
|
+
}
|
|
451
|
+
for run in verdict.check_runs
|
|
452
|
+
],
|
|
453
|
+
}
|
|
454
|
+
)
|
|
455
|
+
return {
|
|
456
|
+
"schema_version": JSON_SCHEMA_VERSION,
|
|
457
|
+
"pull_request": {
|
|
458
|
+
"ref": str(report.ref),
|
|
459
|
+
"url": report.ref.url,
|
|
460
|
+
"opened_at": report.episode.opened_at.isoformat(),
|
|
461
|
+
# The repository's current name (a renamed one still answers at its old URL).
|
|
462
|
+
"repo": report.episode.attributes.get("repo"),
|
|
463
|
+
},
|
|
464
|
+
"agent": (
|
|
465
|
+
None
|
|
466
|
+
if report.agent is None
|
|
467
|
+
else {"name": report.agent.agent, "signal": report.agent.signal.value}
|
|
468
|
+
),
|
|
469
|
+
"checked_at": report.checked_at.isoformat(),
|
|
470
|
+
"summary": {WORDS[result]: count for result, count in summary_counts(report).items()},
|
|
471
|
+
"claims": claims,
|
|
472
|
+
"stale": sorted(report.stale),
|
|
473
|
+
"errors": list(report.errors),
|
|
474
|
+
"api_requests": report.api_requests,
|
|
475
|
+
"fetched": sorted(report.fetched),
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def evidence_snapshot(report: PullRequestReport) -> list[dict[str, Any]]:
|
|
480
|
+
"""The evidence records behind the verdicts, JSON-safe and compact.
|
|
481
|
+
|
|
482
|
+
Stored with benchmark results so a verdict stays auditable after GitHub deletes the source
|
|
483
|
+
data (old workflow runs expire; repositories get deleted or renamed).
|
|
484
|
+
"""
|
|
485
|
+
snapshot = []
|
|
486
|
+
for record in report.evidence:
|
|
487
|
+
item: dict[str, Any] = {
|
|
488
|
+
"type": record.record_type,
|
|
489
|
+
"ref": record.external_ref,
|
|
490
|
+
"attributes": {key: _plain(value) for key, value in record.attributes.items()},
|
|
491
|
+
# Kept so a re-score de-duplicates as the original run did (newest version wins).
|
|
492
|
+
"observed_at": record.observed_at.isoformat(),
|
|
493
|
+
"version": record.version,
|
|
494
|
+
}
|
|
495
|
+
if record.occurred_at is not None:
|
|
496
|
+
item["occurred_at"] = record.occurred_at.isoformat()
|
|
497
|
+
snapshot.append(item)
|
|
498
|
+
return snapshot
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
def _plain(value: Any) -> Any:
|
|
502
|
+
"""Make attribute values JSON-safe (datetimes become ISO strings)."""
|
|
503
|
+
return value.isoformat() if hasattr(value, "isoformat") else value
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Sources: adapters that read episodes and evidence from external systems (GitHub first)."""
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Find a GitHub token without asking the user to configure anything.
|
|
2
|
+
|
|
3
|
+
Order (first one found wins):
|
|
4
|
+
|
|
5
|
+
1. ``GITHUB_TOKEN`` (set automatically inside GitHub Actions) or ``GH_TOKEN``;
|
|
6
|
+
2. ``gh auth token``, if the GitHub CLI is installed and logged in;
|
|
7
|
+
3. no token: the public API still works, limited to 60 requests per hour.
|
|
8
|
+
|
|
9
|
+
The token value is never logged or printed; only *where* it came from is reported.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
import subprocess
|
|
16
|
+
from collections.abc import Callable, Mapping
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
|
|
19
|
+
Runner = Callable[..., subprocess.CompletedProcess[str]]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class TokenResult:
|
|
24
|
+
token: str | None
|
|
25
|
+
origin: str # "GITHUB_TOKEN", "GH_TOKEN", "gh auth token" or "none"
|
|
26
|
+
|
|
27
|
+
def __repr__(self) -> str: # never reveal the token in logs or tracebacks
|
|
28
|
+
return f"TokenResult(origin={self.origin!r}, token={'***' if self.token else None})"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def resolve_token(
|
|
32
|
+
env: Mapping[str, str] | None = None, run: Runner = subprocess.run
|
|
33
|
+
) -> TokenResult:
|
|
34
|
+
environment = os.environ if env is None else env
|
|
35
|
+
for name in ("GITHUB_TOKEN", "GH_TOKEN"):
|
|
36
|
+
value = environment.get(name, "").strip()
|
|
37
|
+
if value:
|
|
38
|
+
return TokenResult(value, name)
|
|
39
|
+
|
|
40
|
+
try:
|
|
41
|
+
completed = run(
|
|
42
|
+
["gh", "auth", "token"], capture_output=True, text=True, timeout=5, check=False
|
|
43
|
+
)
|
|
44
|
+
except (OSError, subprocess.SubprocessError):
|
|
45
|
+
# gh is not installed or hung: fall through to unauthenticated access.
|
|
46
|
+
return TokenResult(None, "none")
|
|
47
|
+
token = completed.stdout.strip() if completed.returncode == 0 else ""
|
|
48
|
+
return TokenResult(token, "gh auth token") if token else TokenResult(None, "none")
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""On-disk ETag cache for the CLI and the benchmark.
|
|
2
|
+
|
|
3
|
+
Each cached response is one JSON file named after a hash of its URL, holding only the URL,
|
|
4
|
+
the ETag and the response body. Request headers (including any token) are never stored.
|
|
5
|
+
Unreadable or corrupt files are treated as cache misses: the cache can only save requests,
|
|
6
|
+
never break a run.
|
|
7
|
+
|
|
8
|
+
Nothing that holds code is stored: responses with diff patches (a PR's file list) are not
|
|
9
|
+
cached at all, and files and directories are readable by the owner only, because a cached PR
|
|
10
|
+
of a private repository is private data (security review 1, M5).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def default_cache_dir() -> Path:
|
|
23
|
+
"""``$XDG_CACHE_HOME/second-source/github``, or ``~/.cache/second-source/github``."""
|
|
24
|
+
base = os.environ.get("XDG_CACHE_HOME") or str(Path.home() / ".cache")
|
|
25
|
+
return Path(base) / "second-source" / "github"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class DiskCache:
|
|
29
|
+
def __init__(self, directory: str | Path | None = None) -> None:
|
|
30
|
+
self.directory = Path(directory) if directory else default_cache_dir()
|
|
31
|
+
|
|
32
|
+
def get(self, url: str) -> tuple[str, Any] | None:
|
|
33
|
+
path = self._path(url)
|
|
34
|
+
try:
|
|
35
|
+
entry = json.loads(path.read_text(encoding="utf-8"))
|
|
36
|
+
except (OSError, ValueError):
|
|
37
|
+
return None
|
|
38
|
+
# Guard against hash collisions or hand-edited files.
|
|
39
|
+
if entry.get("url") != url or "etag" not in entry:
|
|
40
|
+
return None
|
|
41
|
+
return entry["etag"], entry.get("body")
|
|
42
|
+
|
|
43
|
+
def put(self, url: str, etag: str, body: Any) -> None:
|
|
44
|
+
if _holds_code(body):
|
|
45
|
+
return
|
|
46
|
+
path = self._path(url)
|
|
47
|
+
try:
|
|
48
|
+
for directory in (self.directory, path.parent):
|
|
49
|
+
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
50
|
+
directory.chmod(0o700)
|
|
51
|
+
# Write to a temporary file and rename, so readers never see half-written files.
|
|
52
|
+
temporary = path.with_suffix(".tmp")
|
|
53
|
+
descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
54
|
+
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
|
|
55
|
+
handle.write(json.dumps({"url": url, "etag": etag, "body": body}))
|
|
56
|
+
temporary.replace(path)
|
|
57
|
+
except OSError:
|
|
58
|
+
return # a read-only or full disk must not fail the run
|
|
59
|
+
|
|
60
|
+
def _path(self, url: str) -> Path:
|
|
61
|
+
digest = hashlib.sha256(url.encode("utf-8")).hexdigest()
|
|
62
|
+
return self.directory / digest[:2] / f"{digest}.json"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _holds_code(body: Any) -> bool:
|
|
66
|
+
"""True for a response carrying diff patches (``GET /pulls/N/files``)."""
|
|
67
|
+
return isinstance(body, list) and any(isinstance(i, dict) and "patch" in i for i in body)
|