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,88 @@
|
|
|
1
|
+
"""Commands people type in PR comments: ``/second-source recheck`` and ``/second-source dispute``.
|
|
2
|
+
|
|
3
|
+
Only the PR author and people with write access may run commands; anyone else's comment is
|
|
4
|
+
ignored silently, so a public repository cannot be made to spam labels or replies.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from enum import StrEnum
|
|
12
|
+
|
|
13
|
+
from second_source.sources.github.client import GitHubClient
|
|
14
|
+
from second_source.sources.github.urls import PullRequestRef
|
|
15
|
+
|
|
16
|
+
PREFIX = "/second-source"
|
|
17
|
+
# Author associations GitHub reports for people with write access to the repository.
|
|
18
|
+
TRUSTED_ASSOCIATIONS = frozenset({"OWNER", "MEMBER", "COLLABORATOR"})
|
|
19
|
+
# One line only ([ \t], not \s): the argument must never come from the next line, and the
|
|
20
|
+
# pattern stays linear on long comments (security review 1, M3 and H2).
|
|
21
|
+
_COMMAND_LINE = re.compile(rf"^[ \t]*{re.escape(PREFIX)}[ \t]+(\w+)(.*)$", re.MULTILINE)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class CommandName(StrEnum):
|
|
25
|
+
RECHECK = "recheck"
|
|
26
|
+
DISPUTE = "dispute"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class Command:
|
|
31
|
+
name: CommandName
|
|
32
|
+
argument: str # the dispute reason; empty for recheck
|
|
33
|
+
author: str
|
|
34
|
+
author_association: str
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def parse_command(body: str, author: str, author_association: str) -> Command | None:
|
|
38
|
+
"""The first ``/second-source <command>`` line in a comment, or None if there is none or
|
|
39
|
+
the command is unknown."""
|
|
40
|
+
found = _COMMAND_LINE.search(body or "")
|
|
41
|
+
if found is None:
|
|
42
|
+
return None
|
|
43
|
+
try:
|
|
44
|
+
name = CommandName(found.group(1).lower())
|
|
45
|
+
except ValueError:
|
|
46
|
+
return None
|
|
47
|
+
return Command(name, found.group(2).strip(), author, author_association)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def may_run(command: Command, pr_author: str) -> bool:
|
|
51
|
+
"""True if the commenter may run commands on this PR."""
|
|
52
|
+
return (
|
|
53
|
+
command.author_association in TRUSTED_ASSOCIATIONS
|
|
54
|
+
or command.author.lower() == pr_author.lower()
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# ---- disputes -------------------------------------------------------------------------------
|
|
59
|
+
|
|
60
|
+
PROJECT_URL = "https://github.com/Rarebuffalo/second-source"
|
|
61
|
+
DISPUTED_LABEL = "second-source: disputed"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
# The issue form, not prefilled: a prefilled link would copy a private repository's PR URL
|
|
65
|
+
# and the commenter's text into a public issue (security review 1, L5).
|
|
66
|
+
WRONG_VERDICT_FORM = f"{PROJECT_URL}/issues/new?template=wrong_verdict.yml"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def apply_dispute(client: GitHubClient, ref: PullRequestRef, command: Command) -> None:
|
|
70
|
+
"""Record a dispute: label the PR (the label is the only state) and, the first time only,
|
|
71
|
+
reply with where to report a wrong verdict.
|
|
72
|
+
|
|
73
|
+
The reply never repeats the commenter's text: it is posted as the bot, so echoing it would
|
|
74
|
+
let anyone who may comment publish mentions, links or images under the bot's name
|
|
75
|
+
(security review 1, M3). The reason stays in the comment that gave it.
|
|
76
|
+
"""
|
|
77
|
+
base = f"/repos/{ref.owner}/{ref.repo}/issues/{ref.number}"
|
|
78
|
+
labels = client.get_paginated(f"{base}/labels")
|
|
79
|
+
if any(label.get("name") == DISPUTED_LABEL for label in labels):
|
|
80
|
+
return # already disputed: one reply per PR, however many commands follow
|
|
81
|
+
client.post(f"{base}/labels", {"labels": [DISPUTED_LABEL]})
|
|
82
|
+
reply = (
|
|
83
|
+
"This PR is now marked **disputed**, and the Second Source check says so. The reason "
|
|
84
|
+
"is in the comment above.\n\nIf a verdict is wrong because Second Source misread a "
|
|
85
|
+
f"claim or the evidence, please [report it]({WRONG_VERDICT_FORM}) so the rules can be "
|
|
86
|
+
"fixed (for a private repository, describe it without the link)."
|
|
87
|
+
)
|
|
88
|
+
client.post(f"{base}/comments", {"body": reply})
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Turn the event that triggered a workflow run into a plan: what to check, and how.
|
|
2
|
+
|
|
3
|
+
| Event | Mode |
|
|
4
|
+
|------------------------------------------|---------|
|
|
5
|
+
| pull_request / pull_request_target | CHECK the PR |
|
|
6
|
+
| workflow_run (completed) | CHECK the PRs that run built |
|
|
7
|
+
| schedule / workflow_dispatch | SWEEP recent agent PRs |
|
|
8
|
+
| issue_comment with a /second-source line | COMMAND on that PR |
|
|
9
|
+
| anything else | SKIP, with a note saying why |
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from enum import StrEnum
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from second_source.action.commands import Command, parse_command
|
|
19
|
+
from second_source.sources.github.urls import PullRequestRef
|
|
20
|
+
|
|
21
|
+
PR_EVENTS = frozenset({"pull_request", "pull_request_target"})
|
|
22
|
+
# PR actions after which the claims or the evidence may have changed.
|
|
23
|
+
PR_ACTIONS = frozenset(
|
|
24
|
+
{"opened", "edited", "synchronize", "reopened", "ready_for_review", "closed"}
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Mode(StrEnum):
|
|
29
|
+
CHECK = "check"
|
|
30
|
+
SWEEP = "sweep"
|
|
31
|
+
COMMAND = "command"
|
|
32
|
+
SKIP = "skip"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class Plan:
|
|
37
|
+
mode: Mode
|
|
38
|
+
refs: tuple[PullRequestRef, ...] = ()
|
|
39
|
+
command: Command | None = None
|
|
40
|
+
pr_author: str = "" # for command permission checks
|
|
41
|
+
note: str = "" # why a run was skipped, shown in the log
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _ref(repository: str, number: int) -> PullRequestRef:
|
|
45
|
+
owner, name = repository.split("/", 1)
|
|
46
|
+
return PullRequestRef(owner, name, int(number))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def plan_for(event_name: str, event: dict[str, Any], repository: str) -> Plan:
|
|
50
|
+
if event_name in PR_EVENTS:
|
|
51
|
+
action = event.get("action", "")
|
|
52
|
+
if action not in PR_ACTIONS:
|
|
53
|
+
return Plan(Mode.SKIP, note=f"pull request action '{action}' changes nothing to check")
|
|
54
|
+
return Plan(Mode.CHECK, (_ref(repository, event["pull_request"]["number"]),))
|
|
55
|
+
|
|
56
|
+
if event_name == "workflow_run":
|
|
57
|
+
run = event.get("workflow_run", {})
|
|
58
|
+
if event.get("action") != "completed":
|
|
59
|
+
return Plan(Mode.SKIP, note="workflow run has not completed")
|
|
60
|
+
# GitHub lists the PRs whose head commit this run built. PRs from forks are not
|
|
61
|
+
# listed; the daily sweep covers them.
|
|
62
|
+
numbers = sorted({pr["number"] for pr in run.get("pull_requests", [])})
|
|
63
|
+
if not numbers:
|
|
64
|
+
return Plan(Mode.SKIP, note="the workflow run belongs to no pull request here")
|
|
65
|
+
return Plan(Mode.CHECK, tuple(_ref(repository, n) for n in numbers))
|
|
66
|
+
|
|
67
|
+
if event_name in ("schedule", "workflow_dispatch"):
|
|
68
|
+
return Plan(Mode.SWEEP)
|
|
69
|
+
|
|
70
|
+
if event_name == "issue_comment":
|
|
71
|
+
issue = event.get("issue", {})
|
|
72
|
+
comment = event.get("comment", {})
|
|
73
|
+
if event.get("action") != "created" or "pull_request" not in issue:
|
|
74
|
+
return Plan(Mode.SKIP, note="not a new comment on a pull request")
|
|
75
|
+
command = parse_command(
|
|
76
|
+
comment.get("body", ""),
|
|
77
|
+
(comment.get("user") or {}).get("login", ""),
|
|
78
|
+
comment.get("author_association", ""),
|
|
79
|
+
)
|
|
80
|
+
if command is None:
|
|
81
|
+
return Plan(Mode.SKIP, note="the comment has no /second-source command")
|
|
82
|
+
return Plan(
|
|
83
|
+
Mode.COMMAND,
|
|
84
|
+
(_ref(repository, issue["number"]),),
|
|
85
|
+
command=command,
|
|
86
|
+
pr_author=(issue.get("user") or {}).get("login", ""),
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
return Plan(Mode.SKIP, note=f"event '{event_name}' is not used by Second Source")
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Action inputs and run context, read from the environment GitHub Actions provides.
|
|
2
|
+
|
|
3
|
+
action.yml passes each input as an ``INPUT_<NAME>`` environment variable. Values are
|
|
4
|
+
validated here once, so the rest of the Action works with typed, trusted settings and a bad
|
|
5
|
+
input fails fast with a clear message instead of misbehaving later.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from collections.abc import Mapping
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class InputError(ValueError):
|
|
18
|
+
"""An input or required environment variable is missing or invalid."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class ActionInputs:
|
|
23
|
+
token: str = field(repr=False) # never shown in logs or reprs
|
|
24
|
+
wait_minutes: int = 10
|
|
25
|
+
only_agents: bool = True
|
|
26
|
+
fail_on_contradiction: bool = False
|
|
27
|
+
sweep_days: int = 30
|
|
28
|
+
ignore_claims: frozenset[str] = frozenset() # claim types neither checked nor shown
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class RunContext:
|
|
33
|
+
"""What GitHub tells every workflow run: the repository and the triggering event."""
|
|
34
|
+
|
|
35
|
+
repository: str # owner/name
|
|
36
|
+
event_name: str
|
|
37
|
+
event: dict[str, Any]
|
|
38
|
+
summary_path: Path | None # GITHUB_STEP_SUMMARY, absent outside Actions
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
_TRUE = {"true", "yes", "1", "on"}
|
|
42
|
+
_FALSE = {"false", "no", "0", "off", ""}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _flag(env: Mapping[str, str], name: str, default: bool) -> bool:
|
|
46
|
+
raw = env.get(f"INPUT_{name}")
|
|
47
|
+
if raw is None:
|
|
48
|
+
return default
|
|
49
|
+
value = raw.strip().lower()
|
|
50
|
+
if value in _TRUE:
|
|
51
|
+
return True
|
|
52
|
+
if value in _FALSE:
|
|
53
|
+
return default if value == "" else False
|
|
54
|
+
raise InputError(f"input {name.lower().replace('_', '-')} must be true or false, got {raw!r}")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _number(env: Mapping[str, str], name: str, default: int, low: int, high: int) -> int:
|
|
58
|
+
raw = env.get(f"INPUT_{name}", "").strip()
|
|
59
|
+
if not raw:
|
|
60
|
+
return default
|
|
61
|
+
try:
|
|
62
|
+
value = int(raw)
|
|
63
|
+
except ValueError:
|
|
64
|
+
raise InputError(f"input {name.lower().replace('_', '-')} must be a number") from None
|
|
65
|
+
if not low <= value <= high:
|
|
66
|
+
raise InputError(f"input {name.lower().replace('_', '-')} must be between {low} and {high}")
|
|
67
|
+
return value
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# Claim types a repository may switch off (MERGE_HOLDS is implicit in every merge and stays).
|
|
71
|
+
IGNORABLE_CLAIMS = frozenset(
|
|
72
|
+
{"TESTS_PASS", "BUILD_OK", "LINT_OK", "TESTS_ADDED", "DOCS_UPDATED", "FIXES_ISSUE", "DEPLOYED"}
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _claim_types(env: Mapping[str, str], name: str) -> frozenset[str]:
|
|
77
|
+
raw = env.get(f"INPUT_{name}", "")
|
|
78
|
+
names = frozenset(
|
|
79
|
+
part.strip().upper() for part in raw.replace("\n", ",").split(",") if part.strip()
|
|
80
|
+
)
|
|
81
|
+
unknown = names - IGNORABLE_CLAIMS
|
|
82
|
+
if unknown:
|
|
83
|
+
raise InputError(
|
|
84
|
+
f"input {name.lower().replace('_', '-')} has unknown claim types {sorted(unknown)}; "
|
|
85
|
+
f"use any of {sorted(IGNORABLE_CLAIMS)}"
|
|
86
|
+
)
|
|
87
|
+
return names
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def read_inputs(env: Mapping[str, str]) -> ActionInputs:
|
|
91
|
+
token = env.get("INPUT_GITHUB_TOKEN", "").strip()
|
|
92
|
+
if not token:
|
|
93
|
+
raise InputError("input github-token is empty; pass ${{ github.token }}")
|
|
94
|
+
return ActionInputs(
|
|
95
|
+
token=token,
|
|
96
|
+
wait_minutes=_number(env, "WAIT_MINUTES", 10, 0, 60),
|
|
97
|
+
only_agents=_flag(env, "ONLY_AGENTS", True),
|
|
98
|
+
fail_on_contradiction=_flag(env, "FAIL_ON_CONTRADICTION", False),
|
|
99
|
+
sweep_days=_number(env, "SWEEP_DAYS", 30, 1, 90),
|
|
100
|
+
ignore_claims=_claim_types(env, "IGNORE_CLAIMS"),
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def read_context(env: Mapping[str, str]) -> RunContext:
|
|
105
|
+
try:
|
|
106
|
+
repository = env["GITHUB_REPOSITORY"]
|
|
107
|
+
event_name = env["GITHUB_EVENT_NAME"]
|
|
108
|
+
event_path = Path(env["GITHUB_EVENT_PATH"])
|
|
109
|
+
except KeyError as missing:
|
|
110
|
+
raise InputError(
|
|
111
|
+
f"{missing.args[0]} is not set; is this running in GitHub Actions?"
|
|
112
|
+
) from None
|
|
113
|
+
try:
|
|
114
|
+
event = json.loads(event_path.read_text(encoding="utf-8"))
|
|
115
|
+
except (OSError, json.JSONDecodeError) as error:
|
|
116
|
+
raise InputError(f"cannot read the event payload: {error}") from error
|
|
117
|
+
summary = env.get("GITHUB_STEP_SUMMARY")
|
|
118
|
+
return RunContext(repository, event_name, event, Path(summary) if summary else None)
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"""``second-source action``: the GitHub Action's entrypoint (docs/action.md).
|
|
2
|
+
|
|
3
|
+
One run: read inputs and the triggering event, plan what to do, then for each target PR
|
|
4
|
+
check it, wait for CI if needed, and publish the check run and job summary.
|
|
5
|
+
|
|
6
|
+
Failures (a deleted PR, a GitHub error, the rate limit) are reported as workflow warnings and
|
|
7
|
+
never fail the workflow: Second Source is advice, and a broken advisor must not block anyone's
|
|
8
|
+
merge. Only bad inputs fail the run, so misconfiguration is noticed. At the rate limit the run
|
|
9
|
+
stops instead of failing every remaining PR, and the sweep stops early while requests remain
|
|
10
|
+
for PR events (action/sweep.py).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import sys
|
|
16
|
+
import time
|
|
17
|
+
from collections.abc import Callable, Mapping
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from datetime import UTC, datetime
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import TextIO
|
|
22
|
+
|
|
23
|
+
from second_source.action.commands import CommandName, apply_dispute, may_run
|
|
24
|
+
from second_source.action.event import Mode, Plan, plan_for
|
|
25
|
+
from second_source.action.inputs import ActionInputs, InputError, read_context, read_inputs
|
|
26
|
+
from second_source.action.publish import (
|
|
27
|
+
Outcome,
|
|
28
|
+
outcome_for,
|
|
29
|
+
publish_check_run,
|
|
30
|
+
write_job_summary,
|
|
31
|
+
)
|
|
32
|
+
from second_source.action.sweep import SWEEP_RESERVE, recent_pull_requests, rotated
|
|
33
|
+
from second_source.action.wait import wait_for_ci
|
|
34
|
+
from second_source.pipeline import PullRequestReport, check_pull_request
|
|
35
|
+
from second_source.sources.github.client import GitHubClient, GitHubError, RateLimited
|
|
36
|
+
from second_source.sources.github.source import GitHubSource, PullRequestNotFound
|
|
37
|
+
from second_source.sources.github.urls import PullRequestRef
|
|
38
|
+
|
|
39
|
+
# Fetched on every PR, claims or not, for the evidence summary in the check run (about four
|
|
40
|
+
# requests: the head commit's CI and the file list).
|
|
41
|
+
DIGEST_EVIDENCE = frozenset({"pr_state", "check_result", "changed_file", "changed_files_summary"})
|
|
42
|
+
|
|
43
|
+
EXIT_OK = 0
|
|
44
|
+
EXIT_BAD_INPUT = 2
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def run_action(
|
|
48
|
+
env: Mapping[str, str],
|
|
49
|
+
*,
|
|
50
|
+
client_factory: Callable[[str], GitHubClient] = lambda token: GitHubClient(token),
|
|
51
|
+
now: Callable[[], datetime] = lambda: datetime.now(UTC),
|
|
52
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
53
|
+
clock: Callable[[], float] = time.monotonic,
|
|
54
|
+
out: TextIO | None = None,
|
|
55
|
+
) -> int:
|
|
56
|
+
out = out or sys.stdout
|
|
57
|
+
try:
|
|
58
|
+
inputs = read_inputs(env)
|
|
59
|
+
context = read_context(env)
|
|
60
|
+
except InputError as error:
|
|
61
|
+
print(f"::error::{error}", file=out)
|
|
62
|
+
return EXIT_BAD_INPUT
|
|
63
|
+
|
|
64
|
+
plan = plan_for(context.event_name, context.event, context.repository)
|
|
65
|
+
if plan.mode is Mode.SKIP:
|
|
66
|
+
print(f"Nothing to do: {plan.note}.", file=out)
|
|
67
|
+
return EXIT_OK
|
|
68
|
+
|
|
69
|
+
with client_factory(inputs.token) as client:
|
|
70
|
+
run = ActionRun(client, inputs, plan, context.summary_path, now, sleep, clock, out)
|
|
71
|
+
run.own_workflow_path = own_workflow_path(env)
|
|
72
|
+
try:
|
|
73
|
+
refs, wait_seconds = run.targets(context.repository)
|
|
74
|
+
except GitHubError as error:
|
|
75
|
+
print(f"::warning::could not list what to check: {error}", file=out)
|
|
76
|
+
return EXIT_OK
|
|
77
|
+
# One wait budget for the whole run (a CI run can belong to several PRs), so the job
|
|
78
|
+
# never outlives its timeout.
|
|
79
|
+
wait_until = clock() + wait_seconds
|
|
80
|
+
for done, ref in enumerate(refs):
|
|
81
|
+
remaining = client.stats.rate_remaining
|
|
82
|
+
if plan.mode is Mode.SWEEP and remaining is not None and remaining < SWEEP_RESERVE:
|
|
83
|
+
print(
|
|
84
|
+
f"Sweep stopped after {done} of {len(refs)} PR(s): {remaining} API requests "
|
|
85
|
+
"left, kept for pull request events. Tomorrow's sweep starts elsewhere.",
|
|
86
|
+
file=out,
|
|
87
|
+
)
|
|
88
|
+
break
|
|
89
|
+
try:
|
|
90
|
+
run.process(ref, max(0.0, wait_until - clock()))
|
|
91
|
+
except PullRequestNotFound:
|
|
92
|
+
print(f"::warning::{ref} was not found or is not accessible.", file=out)
|
|
93
|
+
except RateLimited:
|
|
94
|
+
print(
|
|
95
|
+
f"::warning::GitHub's rate limit was reached at {ref}; stopped. "
|
|
96
|
+
"Remaining PRs are checked by their next event or the daily sweep.",
|
|
97
|
+
file=out,
|
|
98
|
+
)
|
|
99
|
+
break
|
|
100
|
+
except GitHubError as error:
|
|
101
|
+
print(f"::warning::could not check {ref}: {error}", file=out)
|
|
102
|
+
except Exception as error: # noqa: BLE001 - one bad PR must never fail the run
|
|
103
|
+
# Only the type is printed: the message may carry PR text, and PR text must
|
|
104
|
+
# never reach the runner's log as a workflow command.
|
|
105
|
+
print(f"::warning::could not check {ref}: {type(error).__name__}", file=out)
|
|
106
|
+
return EXIT_OK
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def own_workflow_path(env: Mapping[str, str]) -> str | None:
|
|
110
|
+
"""This workflow's file, from ``GITHUB_WORKFLOW_REF``
|
|
111
|
+
(``owner/repo/.github/workflows/second-source.yml@refs/heads/main``), so its own runs are
|
|
112
|
+
never mistaken for CI, whatever the workflow or its job is called."""
|
|
113
|
+
ref = env.get("GITHUB_WORKFLOW_REF", "")
|
|
114
|
+
path = ref.split("@", 1)[0]
|
|
115
|
+
parts = path.split("/", 2)
|
|
116
|
+
return parts[2] if len(parts) == 3 and parts[2] else None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@dataclass
|
|
120
|
+
class ActionRun:
|
|
121
|
+
"""Everything one Action run shares across the PRs it checks."""
|
|
122
|
+
|
|
123
|
+
client: GitHubClient
|
|
124
|
+
inputs: ActionInputs
|
|
125
|
+
plan: Plan
|
|
126
|
+
summary_path: Path | None
|
|
127
|
+
now: Callable[[], datetime]
|
|
128
|
+
sleep: Callable[[float], None]
|
|
129
|
+
clock: Callable[[], float]
|
|
130
|
+
out: TextIO
|
|
131
|
+
own_workflow_path: str | None = None
|
|
132
|
+
|
|
133
|
+
def targets(self, repository: str) -> tuple[list[PullRequestRef], float]:
|
|
134
|
+
"""Which PRs to check, and how long to wait for CI on each."""
|
|
135
|
+
plan, out = self.plan, self.out
|
|
136
|
+
if plan.mode is Mode.SWEEP:
|
|
137
|
+
refs = recent_pull_requests(
|
|
138
|
+
self.client,
|
|
139
|
+
repository,
|
|
140
|
+
now=self.now(),
|
|
141
|
+
days=self.inputs.sweep_days,
|
|
142
|
+
only_agents=self.inputs.only_agents,
|
|
143
|
+
)
|
|
144
|
+
refs = rotated(refs, self.now().toordinal())
|
|
145
|
+
print(f"Sweep: re-checking {len(refs)} recent agent pull request(s).", file=out)
|
|
146
|
+
return refs, 0.0 # the sweep never waits; the next event or sweep picks CI up
|
|
147
|
+
|
|
148
|
+
if plan.mode is Mode.COMMAND:
|
|
149
|
+
command = plan.command
|
|
150
|
+
assert command is not None
|
|
151
|
+
if not may_run(command, plan.pr_author):
|
|
152
|
+
print(f"Ignoring /second-source {command.name} from {command.author}.", file=out)
|
|
153
|
+
return [], 0.0
|
|
154
|
+
if command.name is CommandName.DISPUTE:
|
|
155
|
+
try:
|
|
156
|
+
apply_dispute(self.client, plan.refs[0], command)
|
|
157
|
+
except GitHubError as error:
|
|
158
|
+
# Say what failed (a missing permission shows up here), then still
|
|
159
|
+
# re-check the PR.
|
|
160
|
+
print(f"::warning::could not record the dispute: {error}", file=out)
|
|
161
|
+
return list(plan.refs), 0.0 # re-check now, so the check run shows the change
|
|
162
|
+
|
|
163
|
+
return list(plan.refs), self.inputs.wait_minutes * 60.0
|
|
164
|
+
|
|
165
|
+
def process(self, ref: PullRequestRef, wait_seconds: float) -> None:
|
|
166
|
+
"""Check one PR (waiting for CI within the budget) and publish the result."""
|
|
167
|
+
source = GitHubSource(self.client, clock=self.now, own_workflow_path=self.own_workflow_path)
|
|
168
|
+
|
|
169
|
+
def check() -> PullRequestReport:
|
|
170
|
+
report = check_pull_request(
|
|
171
|
+
ref,
|
|
172
|
+
source,
|
|
173
|
+
now=self.now(),
|
|
174
|
+
extra_evidence=DIGEST_EVIDENCE,
|
|
175
|
+
ignore_claims=self.inputs.ignore_claims,
|
|
176
|
+
)
|
|
177
|
+
if report.rate_limited:
|
|
178
|
+
# Evidence was cut short: publishing would show "unverifiable" over a real
|
|
179
|
+
# result, so stop instead (the caller ends the run with a warning).
|
|
180
|
+
raise RateLimited(403, str(ref), "(rate limit reached while reading evidence)")
|
|
181
|
+
return report
|
|
182
|
+
|
|
183
|
+
def outcome(report: PullRequestReport) -> Outcome:
|
|
184
|
+
return outcome_for(report, fail_on_contradiction=self.inputs.fail_on_contradiction)
|
|
185
|
+
|
|
186
|
+
report = check()
|
|
187
|
+
# Commands are explicit requests, so they run even on PRs with no detected agent.
|
|
188
|
+
if self.inputs.only_agents and report.agent is None and self.plan.mode is not Mode.COMMAND:
|
|
189
|
+
print(f"{ref}: no coding agent detected, skipped.", file=self.out)
|
|
190
|
+
return
|
|
191
|
+
|
|
192
|
+
report = wait_for_ci(
|
|
193
|
+
check,
|
|
194
|
+
budget_seconds=wait_seconds,
|
|
195
|
+
on_update=lambda current: publish_check_run(self.client, current, outcome(current)),
|
|
196
|
+
sleep=self.sleep,
|
|
197
|
+
clock=self.clock,
|
|
198
|
+
first=report,
|
|
199
|
+
)
|
|
200
|
+
final = outcome(report)
|
|
201
|
+
publish_check_run(self.client, report, final)
|
|
202
|
+
write_job_summary(self.summary_path, report, final)
|
|
203
|
+
print(f"{ref}: {final.title}", file=self.out)
|