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,184 @@
|
|
|
1
|
+
"""Publish a PR's verdicts as one "Second Source" check run, plus the job summary.
|
|
2
|
+
|
|
3
|
+
The check run is created once per head commit and then updated in place, so later runs (CI
|
|
4
|
+
finished, daily sweep, a recheck command) replace the table instead of piling up checks.
|
|
5
|
+
|
|
6
|
+
Conclusion rules (docs/action.md, section 4):
|
|
7
|
+
|
|
8
|
+
- CI still running for a claim -> the check stays ``in_progress``, so people see it is not done.
|
|
9
|
+
- a high-confidence claim is contradicted -> ``neutral`` by default (advice, never blocks a
|
|
10
|
+
merge) or ``failure`` when the repository opts in with ``fail-on-contradiction``.
|
|
11
|
+
- a high-confidence claim withdrawn by an integrity guard (CI passed, but the PR skipped tests
|
|
12
|
+
or weakened its CI) -> ``neutral``, never ``failure``: a guard is not proof of a false claim.
|
|
13
|
+
- a claim unverifiable because CI failed where its wording leaves room ("tests pass locally",
|
|
14
|
+
a partial run, a failure on only one of two commits) -> ``neutral`` with "(a CI job
|
|
15
|
+
failed)" in the title: not a contradiction, but not green either.
|
|
16
|
+
- otherwise -> ``success``, or ``neutral`` when there was nothing to check. Cautions never
|
|
17
|
+
change the conclusion.
|
|
18
|
+
|
|
19
|
+
Low-confidence claims are shown in the table but never change the conclusion.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
from collections import Counter
|
|
25
|
+
from dataclasses import dataclass
|
|
26
|
+
from datetime import UTC, datetime, timedelta
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from typing import Any
|
|
29
|
+
|
|
30
|
+
from second_source.action.commands import DISPUTED_LABEL
|
|
31
|
+
from second_source.core.model import Claim, Result
|
|
32
|
+
from second_source.pipeline import PullRequestReport
|
|
33
|
+
from second_source.report.render import WORDS, guard_text, to_markdown, withdrawn_reasons
|
|
34
|
+
from second_source.sources.github.client import GitHubClient
|
|
35
|
+
|
|
36
|
+
CHECK_NAME = "Second Source"
|
|
37
|
+
ACTIONS_APP = "github-actions" # the app that owns check runs created with GITHUB_TOKEN
|
|
38
|
+
CLOCK_SKEW = timedelta(minutes=5) # how far ahead another runner's clock may plausibly be
|
|
39
|
+
MAX_SUMMARY = 65_000 # GitHub limits check run output text to 65,535 characters
|
|
40
|
+
MAX_JOB_SUMMARY = 1_000_000 # bytes; GitHub's step summary limit is 1 MiB
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class Outcome:
|
|
45
|
+
status: str # "in_progress" or "completed"
|
|
46
|
+
conclusion: str | None # set only when completed
|
|
47
|
+
title: str
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _counts(claim: Claim) -> bool:
|
|
51
|
+
"""Claims that decide the conclusion: high confidence, or implicit (no extraction)."""
|
|
52
|
+
return claim.attributes.get("confidence", "high") == "high"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def awaiting_ci(report: PullRequestReport) -> bool:
|
|
56
|
+
"""True while a deciding claim is pending only because CI has not finished."""
|
|
57
|
+
return any(
|
|
58
|
+
verdict.result is Result.PENDING and "AWAITING_CI" in verdict.reasons
|
|
59
|
+
for verdict in (report.verdict_for(c) for c in report.claims if _counts(c))
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
# Unverifiable because CI failed where the claim's wording or commit leaves room (a local or
|
|
64
|
+
# partial run, or a failure only on one of two commits): not a contradiction, but not green.
|
|
65
|
+
CI_FAILED_REASONS = frozenset(
|
|
66
|
+
{"CI_FAILED_LOCAL_CLAIM", "CI_FAILED_SUBSET_CLAIM", "CLAIM_COMMIT_AMBIGUOUS"}
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def outcome_for(report: PullRequestReport, *, fail_on_contradiction: bool) -> Outcome:
|
|
71
|
+
deciding = [report.verdict_for(c) for c in report.claims if _counts(c)]
|
|
72
|
+
results = Counter(v.result for v in deciding)
|
|
73
|
+
|
|
74
|
+
if results[Result.CONTRADICTED]:
|
|
75
|
+
n = results[Result.CONTRADICTED]
|
|
76
|
+
conclusion = "failure" if fail_on_contradiction else "neutral"
|
|
77
|
+
return Outcome("completed", conclusion, f"{n} claim{'s' if n > 1 else ''} contradicted")
|
|
78
|
+
if awaiting_ci(report):
|
|
79
|
+
return Outcome("in_progress", None, "Waiting for CI")
|
|
80
|
+
withdrawn = [
|
|
81
|
+
reasons
|
|
82
|
+
for c in report.claims
|
|
83
|
+
if _counts(c) and (reasons := withdrawn_reasons(report.verdict_for(c)))
|
|
84
|
+
]
|
|
85
|
+
if withdrawn:
|
|
86
|
+
# CI passed but the PR changed what passing means: grey, never red. A guard is not proof
|
|
87
|
+
# that the claim is false, so this ignores fail-on-contradiction.
|
|
88
|
+
n = len(withdrawn)
|
|
89
|
+
title = f"{n} claim{'s' if n > 1 else ''} not verified: {guard_text(withdrawn[0][0])}"
|
|
90
|
+
return Outcome("completed", "neutral", title)
|
|
91
|
+
if not report.claims:
|
|
92
|
+
return Outcome("completed", "neutral", "No claims found")
|
|
93
|
+
|
|
94
|
+
order = [Result.VERIFIED, Result.PENDING, Result.UNVERIFIABLE]
|
|
95
|
+
parts = [f"{results[r]} {WORDS[r]}" for r in order if results[r]]
|
|
96
|
+
if not parts:
|
|
97
|
+
return Outcome("completed", "neutral", "Only low-confidence claims")
|
|
98
|
+
if any(CI_FAILED_REASONS & set(v.reasons) for v in deciding):
|
|
99
|
+
# Grey, not green: someone skimming the checks must not read "claims hold" while a
|
|
100
|
+
# CI job behind a claim failed.
|
|
101
|
+
return Outcome("completed", "neutral", ", ".join(parts) + " (a CI job failed)")
|
|
102
|
+
return Outcome("completed", "success", ", ".join(parts))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def summary_markdown(report: PullRequestReport) -> str:
|
|
106
|
+
text = to_markdown(report)
|
|
107
|
+
if DISPUTED_LABEL in report.labels:
|
|
108
|
+
text = (
|
|
109
|
+
"> **Disputed.** Someone on this PR believes a verdict is wrong; treat the results "
|
|
110
|
+
"below with care.\n\n" + text
|
|
111
|
+
)
|
|
112
|
+
if len(text) > MAX_SUMMARY:
|
|
113
|
+
text = text[:MAX_SUMMARY] + "\n\n_(truncated)_"
|
|
114
|
+
return text
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _checked_at(run: dict[str, Any]) -> datetime | None:
|
|
118
|
+
"""When the report shown in an existing check run was made (its ``external_id``)."""
|
|
119
|
+
try:
|
|
120
|
+
shown = datetime.fromisoformat(str(run.get("external_id") or ""))
|
|
121
|
+
except ValueError:
|
|
122
|
+
return None # written by an older version, or by hand: treat as older than anything
|
|
123
|
+
# A date without a zone (also written by hand) cannot be compared with ours: ignore it.
|
|
124
|
+
return shown if shown.tzinfo is not None else None
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def publish_check_run(
|
|
128
|
+
client: GitHubClient,
|
|
129
|
+
report: PullRequestReport,
|
|
130
|
+
outcome: Outcome,
|
|
131
|
+
*,
|
|
132
|
+
now: datetime | None = None,
|
|
133
|
+
) -> int:
|
|
134
|
+
"""Create or update the check run on the PR's head commit; return its id.
|
|
135
|
+
|
|
136
|
+
Several runs can work on one PR at once (a PR event still waiting for CI, the run that CI's
|
|
137
|
+
completion triggered, the daily sweep). Each check run records when its report was made, in
|
|
138
|
+
``external_id``, and a report older than the one already shown is not published, so a slow
|
|
139
|
+
run does not put an outdated "Waiting for CI" over a newer verdict. (Read-then-write is not
|
|
140
|
+
atomic, and runners' clocks can differ by seconds; the remaining window is that small.)
|
|
141
|
+
"""
|
|
142
|
+
base = f"/repos/{report.ref.owner}/{report.ref.repo}"
|
|
143
|
+
body: dict[str, object] = {
|
|
144
|
+
"name": CHECK_NAME,
|
|
145
|
+
"status": outcome.status,
|
|
146
|
+
"external_id": report.checked_at.isoformat(),
|
|
147
|
+
"output": {"title": outcome.title, "summary": summary_markdown(report)},
|
|
148
|
+
}
|
|
149
|
+
if outcome.conclusion is not None:
|
|
150
|
+
body["conclusion"] = outcome.conclusion
|
|
151
|
+
|
|
152
|
+
found = client.get_paginated(
|
|
153
|
+
f"{base}/commits/{report.head_sha}/check-runs", {"check_name": CHECK_NAME}, max_pages=1
|
|
154
|
+
)
|
|
155
|
+
# Only a run that GitHub Actions created can be ours: any other app (or a workflow the PR
|
|
156
|
+
# edited) can create a look-alike "Second Source" check (security review 1, M2).
|
|
157
|
+
existing = [run for run in found if (run.get("app") or {}).get("slug") == ACTIONS_APP]
|
|
158
|
+
if existing:
|
|
159
|
+
run_id = int(existing[0]["id"])
|
|
160
|
+
shown = _checked_at(existing[0])
|
|
161
|
+
# A time in the future cannot be a real report; it would freeze the check forever.
|
|
162
|
+
latest_possible = (now or datetime.now(UTC)) + CLOCK_SKEW
|
|
163
|
+
if shown is not None and report.checked_at < shown <= latest_possible:
|
|
164
|
+
return run_id # a newer report is already shown
|
|
165
|
+
client.patch(f"{base}/check-runs/{run_id}", body)
|
|
166
|
+
return run_id
|
|
167
|
+
created = client.post(f"{base}/check-runs", {**body, "head_sha": report.head_sha})
|
|
168
|
+
return int(created["id"])
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def write_job_summary(path: Path | None, report: PullRequestReport, outcome: Outcome) -> None:
|
|
172
|
+
"""Append this PR's table to the workflow run's summary page (no-op outside Actions)."""
|
|
173
|
+
if path is None:
|
|
174
|
+
return
|
|
175
|
+
section = f"## {report.ref}: {outcome.title}\n\n{summary_markdown(report)}\n\n"
|
|
176
|
+
used = path.stat().st_size if path.exists() else 0
|
|
177
|
+
if used + len(section.encode("utf-8")) > MAX_JOB_SUMMARY:
|
|
178
|
+
# GitHub rejects a step summary over 1 MiB; a long sweep lists the rest by name only
|
|
179
|
+
# (security review 1, L8). Each PR's check run still has its full table.
|
|
180
|
+
section = f"- {report.ref}: {outcome.title}\n"
|
|
181
|
+
if used + len(section.encode("utf-8")) > MAX_JOB_SUMMARY:
|
|
182
|
+
return
|
|
183
|
+
with path.open("a", encoding="utf-8") as handle:
|
|
184
|
+
handle.write(section)
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""``second-source init``: write the recommended workflow into a repository.
|
|
2
|
+
|
|
3
|
+
Setup should be one command and one commit. The generated workflow re-checks PRs when CI
|
|
4
|
+
finishes (``workflow_run``), which needs the names of the repository's CI workflows; they are
|
|
5
|
+
read from ``.github/workflows`` so nobody has to type them.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import yaml
|
|
14
|
+
|
|
15
|
+
from second_source import __version__
|
|
16
|
+
|
|
17
|
+
WORKFLOW_DIR = Path(".github/workflows")
|
|
18
|
+
WORKFLOW_FILE = WORKFLOW_DIR / "second-source.yml"
|
|
19
|
+
CI_TRIGGERS = frozenset({"push", "pull_request", "pull_request_target"})
|
|
20
|
+
# One run at a time per PR: PR events, the CI-finished re-check and /second-source recheck
|
|
21
|
+
# comments of the same PR share a group, and a newer queued run replaces an older one
|
|
22
|
+
# (harmless: it checks the same PR later), so a burst of recheck comments costs one run, not
|
|
23
|
+
# one each (security review 2, N7). A dispute gets a group of its own, because a dispute
|
|
24
|
+
# replaced in the queue would be lost. A CI run from a fork lists no PR and gets its own group.
|
|
25
|
+
# Overlap cannot reorder results either way: publish_check_run never replaces a newer report.
|
|
26
|
+
_CONCURRENCY_KEY = (
|
|
27
|
+
"${{ (github.event_name == 'issue_comment'"
|
|
28
|
+
" && contains(github.event.comment.body, '/second-source dispute') && github.run_id)"
|
|
29
|
+
" || github.event.issue.number || github.event.pull_request.number"
|
|
30
|
+
" || github.event.workflow_run.pull_requests[0].number || github.run_id }}"
|
|
31
|
+
)
|
|
32
|
+
# Longer than the longest CI wait (60 minutes) plus checking. A cancelled or timed-out run can
|
|
33
|
+
# leave the check run "in progress"; the next event or the daily sweep republishes it.
|
|
34
|
+
_JOB_TIMEOUT_MINUTES = 75
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _triggers(document: dict[Any, Any]) -> set[str]:
|
|
38
|
+
# YAML 1.1 reads a bare `on:` key as the boolean True, so look under both.
|
|
39
|
+
on = document.get("on", document.get(True))
|
|
40
|
+
if isinstance(on, str):
|
|
41
|
+
return {on}
|
|
42
|
+
if isinstance(on, list):
|
|
43
|
+
return {str(item) for item in on}
|
|
44
|
+
if isinstance(on, dict):
|
|
45
|
+
return {str(key) for key in on}
|
|
46
|
+
return set()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def ci_workflow_names(root: Path) -> list[str]:
|
|
50
|
+
"""Names of the workflows that run on pushes or PRs (the repository's CI), sorted.
|
|
51
|
+
|
|
52
|
+
A workflow without a ``name`` is known to GitHub by its file path, so that is used.
|
|
53
|
+
"""
|
|
54
|
+
names = []
|
|
55
|
+
directory = root / WORKFLOW_DIR
|
|
56
|
+
for path in sorted([*directory.glob("*.yml"), *directory.glob("*.yaml")]):
|
|
57
|
+
if path.name == WORKFLOW_FILE.name:
|
|
58
|
+
continue
|
|
59
|
+
try:
|
|
60
|
+
document = yaml.safe_load(path.read_text(encoding="utf-8"))
|
|
61
|
+
except (OSError, yaml.YAMLError):
|
|
62
|
+
continue # an unreadable workflow is skipped, not fatal
|
|
63
|
+
if isinstance(document, dict) and _triggers(document) & CI_TRIGGERS:
|
|
64
|
+
names.append(str(document.get("name") or path.relative_to(root).as_posix()))
|
|
65
|
+
return sorted(set(names))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def default_action_ref(version: str = __version__) -> str:
|
|
69
|
+
"""The Action's moving major tag for this release (``v0`` while 0.x), so a generated
|
|
70
|
+
workflow points at a tag that exists and picks up fixes within the major version."""
|
|
71
|
+
return f"Rarebuffalo/second-source@v{version.split('.')[0]}"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def workflow_text(ci_names: list[str], action_ref: str | None = None) -> str:
|
|
75
|
+
action_ref = action_ref or default_action_ref()
|
|
76
|
+
if ci_names:
|
|
77
|
+
quoted = ", ".join(f'"{name}"' for name in ci_names)
|
|
78
|
+
workflow_run = (
|
|
79
|
+
" # Re-check when CI finishes, so verdicts no longer wait on it.\n"
|
|
80
|
+
" workflow_run:\n"
|
|
81
|
+
f" workflows: [{quoted}]\n"
|
|
82
|
+
" types: [completed]\n"
|
|
83
|
+
)
|
|
84
|
+
else:
|
|
85
|
+
workflow_run = (
|
|
86
|
+
" # No CI workflows were found. Add `workflow_run` with your CI workflow names to\n"
|
|
87
|
+
" # re-check as soon as CI finishes; until then the daily run catches up.\n"
|
|
88
|
+
)
|
|
89
|
+
return f"""\
|
|
90
|
+
# Second Source: checks the claims coding agents make in their pull requests.
|
|
91
|
+
# Generated by `second-source init`. Docs: https://github.com/Rarebuffalo/second-source
|
|
92
|
+
#
|
|
93
|
+
# Safe with pull_request_target: Second Source reads the PR through the API only and never
|
|
94
|
+
# checks out or runs its code. Do not add an actions/checkout step to this workflow.
|
|
95
|
+
name: Second Source
|
|
96
|
+
|
|
97
|
+
on:
|
|
98
|
+
pull_request_target:
|
|
99
|
+
types: [opened, edited, synchronize, reopened, ready_for_review, closed]
|
|
100
|
+
{workflow_run} issue_comment:
|
|
101
|
+
types: [created]
|
|
102
|
+
schedule:
|
|
103
|
+
- cron: "17 6 * * *" # daily: durability (reverts, reopened issues) and pending claims
|
|
104
|
+
workflow_dispatch:
|
|
105
|
+
|
|
106
|
+
permissions:
|
|
107
|
+
checks: write
|
|
108
|
+
contents: read
|
|
109
|
+
pull-requests: write # to label a disputed PR (GitHub requires it for PR labels)
|
|
110
|
+
issues: write
|
|
111
|
+
actions: read
|
|
112
|
+
|
|
113
|
+
concurrency:
|
|
114
|
+
group: second-source-{_CONCURRENCY_KEY}
|
|
115
|
+
cancel-in-progress: false
|
|
116
|
+
|
|
117
|
+
jobs:
|
|
118
|
+
# The job id is its check-run name; checks ignore "second-source" as CI evidence.
|
|
119
|
+
second-source:
|
|
120
|
+
# Comments only matter when they hold a /second-source command on a pull request.
|
|
121
|
+
if: >-
|
|
122
|
+
github.event_name != 'issue_comment' ||
|
|
123
|
+
(github.event.issue.pull_request && contains(github.event.comment.body, '/second-source'))
|
|
124
|
+
runs-on: ubuntu-latest
|
|
125
|
+
timeout-minutes: {_JOB_TIMEOUT_MINUTES}
|
|
126
|
+
steps:
|
|
127
|
+
- uses: {action_ref}
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
class WorkflowExists(FileExistsError):
|
|
132
|
+
"""The workflow file is already there and overwriting was not asked for."""
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def write_workflow(root: Path, *, force: bool = False) -> tuple[Path, list[str]]:
|
|
136
|
+
"""Write the workflow; return its path and the CI workflow names it follows."""
|
|
137
|
+
path = root / WORKFLOW_FILE
|
|
138
|
+
if path.exists() and not force:
|
|
139
|
+
raise WorkflowExists(str(path))
|
|
140
|
+
names = ci_workflow_names(root)
|
|
141
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
142
|
+
path.write_text(workflow_text(names), encoding="utf-8")
|
|
143
|
+
return path, names
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""Daily sweep: find recent agent PRs to re-check (docs/action.md, section 2).
|
|
2
|
+
|
|
3
|
+
Durability claims ("the merge was not reverted", "the issue stayed closed") are judged over the
|
|
4
|
+
30 days after a merge, and pending claims need a later look. A scheduled run re-checks every
|
|
5
|
+
agent PR updated in the last ``sweep_days`` days.
|
|
6
|
+
|
|
7
|
+
Each re-check costs roughly 5-15 API requests: the response cache lives only for one run, so
|
|
8
|
+
nothing is free across runs. ``GITHUB_TOKEN`` allows about 1,000 requests an hour per
|
|
9
|
+
repository, so the run stops sweeping while ``SWEEP_RESERVE`` requests are still left for the
|
|
10
|
+
repository's PR events. Each day's sweep starts at a different place in the list
|
|
11
|
+
(``rotated``), so on a busy repository every PR is reached over successive days instead of
|
|
12
|
+
the same newest ones every time.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import math
|
|
18
|
+
from datetime import datetime, timedelta
|
|
19
|
+
|
|
20
|
+
from second_source.packs.coding.detection import detect_agent
|
|
21
|
+
from second_source.sources.github import mappers
|
|
22
|
+
from second_source.sources.github.client import GitHubClient, GitHubError, RateLimited
|
|
23
|
+
from second_source.sources.github.urls import PullRequestRef
|
|
24
|
+
|
|
25
|
+
MAX_PAGES = 5 # up to 500 recently updated PRs per run
|
|
26
|
+
SWEEP_RESERVE = 200 # requests left untouched for PR events while the sweep runs
|
|
27
|
+
# PRs whose own text shows no agent get their commits read (one request each), up to this
|
|
28
|
+
# many per sweep, to find agents known only from a commit trailer ("Co-Authored-By: Claude").
|
|
29
|
+
MAX_COMMIT_LOOKUPS = 30
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def rotated(refs: list[PullRequestRef], day: int) -> list[PullRequestRef]:
|
|
33
|
+
"""``refs`` starting at a position that moves with the day, wrapping around, so a sweep cut
|
|
34
|
+
short reaches different PRs each day. The stride is coprime with the list length, so over
|
|
35
|
+
``len(refs)`` days every PR comes first once."""
|
|
36
|
+
if not refs:
|
|
37
|
+
return refs
|
|
38
|
+
stride = next(s for s in (37, 41, 43) if math.gcd(s, len(refs)) == 1)
|
|
39
|
+
start = (day * stride) % len(refs)
|
|
40
|
+
return refs[start:] + refs[:start]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def recent_pull_requests(
|
|
44
|
+
client: GitHubClient,
|
|
45
|
+
repository: str,
|
|
46
|
+
*,
|
|
47
|
+
now: datetime,
|
|
48
|
+
days: int,
|
|
49
|
+
only_agents: bool = True,
|
|
50
|
+
) -> list[PullRequestRef]:
|
|
51
|
+
"""PRs updated within ``days``, newest first; only agent PRs unless told otherwise.
|
|
52
|
+
|
|
53
|
+
Agent detection uses the PR itself (author, branch, body) and, for up to
|
|
54
|
+
``MAX_COMMIT_LOOKUPS`` PRs that show nothing, its commit messages: an agent known only from
|
|
55
|
+
a commit trailer would otherwise never have its durability re-checked.
|
|
56
|
+
"""
|
|
57
|
+
owner, name = repository.split("/", 1)
|
|
58
|
+
cutoff = now - timedelta(days=days)
|
|
59
|
+
refs = []
|
|
60
|
+
lookups = 0
|
|
61
|
+
# Newest-updated first, so reading stops at the first PR older than the cutoff.
|
|
62
|
+
for page in range(1, MAX_PAGES + 1):
|
|
63
|
+
params = {"state": "all", "sort": "updated", "direction": "desc", "per_page": 100}
|
|
64
|
+
pulls = client.get(f"/repos/{owner}/{name}/pulls", {**params, "page": page})
|
|
65
|
+
for pull in pulls:
|
|
66
|
+
updated = mappers.parse_time(pull.get("updated_at"))
|
|
67
|
+
if updated is None or updated < cutoff:
|
|
68
|
+
return refs
|
|
69
|
+
if only_agents and detect_agent(mappers.signals_from_pull(pull, [])) is None:
|
|
70
|
+
if lookups >= MAX_COMMIT_LOOKUPS:
|
|
71
|
+
continue
|
|
72
|
+
lookups += 1
|
|
73
|
+
try:
|
|
74
|
+
commits = client.get(f"/repos/{owner}/{name}/pulls/{pull['number']}/commits")
|
|
75
|
+
except RateLimited:
|
|
76
|
+
lookups = MAX_COMMIT_LOOKUPS # no more lookups; keep sweeping what we found
|
|
77
|
+
continue
|
|
78
|
+
except GitHubError:
|
|
79
|
+
continue # one unreadable PR must not stop the whole sweep
|
|
80
|
+
if detect_agent(mappers.signals_from_pull(pull, commits)) is None:
|
|
81
|
+
continue
|
|
82
|
+
refs.append(PullRequestRef(owner, name, int(pull["number"])))
|
|
83
|
+
if len(pulls) < 100:
|
|
84
|
+
break
|
|
85
|
+
return refs
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Wait for CI to finish before giving a final verdict (docs/action.md, section 3).
|
|
2
|
+
|
|
3
|
+
"Tests pass" can only be judged once the PR's CI jobs complete. In check mode the Action
|
|
4
|
+
re-checks with growing pauses until no deciding claim is waiting on CI, or the time budget
|
|
5
|
+
(``wait-minutes``) runs out. After every attempt the caller publishes the current table, so the
|
|
6
|
+
check run shows progress. Whatever is still pending when the budget ends is picked up later by
|
|
7
|
+
the ``workflow_run`` event or the daily sweep.
|
|
8
|
+
|
|
9
|
+
Re-checking costs little: the GitHub client's ETag cache turns unchanged responses into
|
|
10
|
+
``304 Not Modified``, which do not count against the rate limit.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import time
|
|
16
|
+
from collections.abc import Callable
|
|
17
|
+
|
|
18
|
+
from second_source.action.publish import awaiting_ci
|
|
19
|
+
from second_source.pipeline import PullRequestReport
|
|
20
|
+
|
|
21
|
+
FIRST_PAUSE = 30.0 # seconds; doubles after each attempt
|
|
22
|
+
MAX_PAUSE = 120.0
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def wait_for_ci(
|
|
26
|
+
check: Callable[[], PullRequestReport],
|
|
27
|
+
*,
|
|
28
|
+
budget_seconds: float,
|
|
29
|
+
on_update: Callable[[PullRequestReport], None] = lambda _report: None,
|
|
30
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
31
|
+
clock: Callable[[], float] = time.monotonic,
|
|
32
|
+
first: PullRequestReport | None = None,
|
|
33
|
+
) -> PullRequestReport:
|
|
34
|
+
"""Run ``check`` until CI has settled or the budget is spent; return the last report.
|
|
35
|
+
|
|
36
|
+
``first`` is a report the caller already has, which saves one check.
|
|
37
|
+
"""
|
|
38
|
+
deadline = clock() + budget_seconds
|
|
39
|
+
pause = FIRST_PAUSE
|
|
40
|
+
report = first if first is not None else check()
|
|
41
|
+
while awaiting_ci(report):
|
|
42
|
+
remaining = deadline - clock()
|
|
43
|
+
if remaining <= 0:
|
|
44
|
+
break
|
|
45
|
+
on_update(report)
|
|
46
|
+
sleep(min(pause, remaining))
|
|
47
|
+
pause = min(pause * 2, MAX_PAUSE)
|
|
48
|
+
report = check()
|
|
49
|
+
return report
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""The "Agent Claim Truth" benchmark: sampling, batch runs and statistics (docs/benchmark.md)."""
|