plotroom 0.1.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.
- plotroom/__init__.py +0 -0
- plotroom/__main__.py +8 -0
- plotroom/_secret_file.py +8 -0
- plotroom/adapters/__init__.py +0 -0
- plotroom/adapters/claude_desktop.py +219 -0
- plotroom/adapters/embedding_http.py +175 -0
- plotroom/adapters/github/__init__.py +337 -0
- plotroom/adapters/github/app_credential.py +209 -0
- plotroom/adapters/github/ci.py +738 -0
- plotroom/adapters/github/commit_statuses.py +63 -0
- plotroom/adapters/github/deployments.py +213 -0
- plotroom/adapters/github/details.py +867 -0
- plotroom/adapters/github/issue_details.py +368 -0
- plotroom/adapters/github/junit.py +210 -0
- plotroom/adapters/github/junit_xml.py +162 -0
- plotroom/adapters/github/kodus_review.py +347 -0
- plotroom/adapters/github/pr_details.py +192 -0
- plotroom/adapters/github/pull_comparison.py +108 -0
- plotroom/adapters/github/read.py +530 -0
- plotroom/adapters/github/ticket_tree.py +336 -0
- plotroom/adapters/mcp/__init__.py +5 -0
- plotroom/adapters/mcp/proxy.py +722 -0
- plotroom/adapters/mcp/server.py +931 -0
- plotroom/adapters/openrouter.py +151 -0
- plotroom/adapters/store_sqlite/__init__.py +6 -0
- plotroom/adapters/store_sqlite/actions_sql.py +148 -0
- plotroom/adapters/store_sqlite/asks_sql.py +153 -0
- plotroom/adapters/store_sqlite/backfill_sql.py +138 -0
- plotroom/adapters/store_sqlite/budgets_sql.py +102 -0
- plotroom/adapters/store_sqlite/checklists_sql.py +77 -0
- plotroom/adapters/store_sqlite/claims_sql.py +54 -0
- plotroom/adapters/store_sqlite/embedding_sql.py +275 -0
- plotroom/adapters/store_sqlite/github_sql.py +331 -0
- plotroom/adapters/store_sqlite/goals_sql.py +57 -0
- plotroom/adapters/store_sqlite/human_queue_sql.py +60 -0
- plotroom/adapters/store_sqlite/items_sql.py +129 -0
- plotroom/adapters/store_sqlite/lanes_sql.py +85 -0
- plotroom/adapters/store_sqlite/ledger_sql.py +506 -0
- plotroom/adapters/store_sqlite/migrate.py +194 -0
- plotroom/adapters/store_sqlite/migrations/env.py +36 -0
- plotroom/adapters/store_sqlite/migrations/script.py.mako +19 -0
- plotroom/adapters/store_sqlite/migrations/versions/0001_project_meta.py +23 -0
- plotroom/adapters/store_sqlite/migrations/versions/0002_event_log.py +40 -0
- plotroom/adapters/store_sqlite/migrations/versions/0003_next_items.py +49 -0
- plotroom/adapters/store_sqlite/migrations/versions/0004_actions.py +28 -0
- plotroom/adapters/store_sqlite/migrations/versions/0005_lanes.py +36 -0
- plotroom/adapters/store_sqlite/migrations/versions/0006_work_items.py +22 -0
- plotroom/adapters/store_sqlite/migrations/versions/0007_item_changes.py +33 -0
- plotroom/adapters/store_sqlite/migrations/versions/0008_claude_turn_aliases.py +30 -0
- plotroom/adapters/store_sqlite/migrations/versions/0009_github_projection.py +38 -0
- plotroom/adapters/store_sqlite/migrations/versions/0010_github_pull_freshness.py +37 -0
- plotroom/adapters/store_sqlite/migrations/versions/0011_github_resources.py +27 -0
- plotroom/adapters/store_sqlite/migrations/versions/0012_local_triggers_outbox.py +80 -0
- plotroom/adapters/store_sqlite/migrations/versions/0013_lane_claims.py +22 -0
- plotroom/adapters/store_sqlite/migrations/versions/0015_recurring_triggers.py +45 -0
- plotroom/adapters/store_sqlite/migrations/versions/0016_merge_controller.py +28 -0
- plotroom/adapters/store_sqlite/migrations/versions/0017_lane_checklists.py +36 -0
- plotroom/adapters/store_sqlite/migrations/versions/0018_guardrails.py +33 -0
- plotroom/adapters/store_sqlite/migrations/versions/0019_clerk_import_metadata.py +16 -0
- plotroom/adapters/store_sqlite/migrations/versions/0020_search.py +30 -0
- plotroom/adapters/store_sqlite/migrations/versions/0021_human_queue.py +46 -0
- plotroom/adapters/store_sqlite/migrations/versions/0022_search_records.py +77 -0
- plotroom/adapters/store_sqlite/migrations/versions/0023_operator_goals.py +25 -0
- plotroom/adapters/store_sqlite/migrations/versions/0024_embedding_rejections.py +36 -0
- plotroom/adapters/store_sqlite/outbox_sql.py +78 -0
- plotroom/adapters/store_sqlite/routes_sql.py +26 -0
- plotroom/adapters/store_sqlite/search_sql.py +116 -0
- plotroom/adapters/store_sqlite/store.py +623 -0
- plotroom/adapters/store_sqlite/triggers_sql.py +111 -0
- plotroom/adapters/store_sqlite/work_items_sql.py +36 -0
- plotroom/adapters/switchboard.py +152 -0
- plotroom/adapters/usage_fixture.py +11 -0
- plotroom/adapters/work_items_bmad.py +256 -0
- plotroom/adapters/work_items_github_issues.py +323 -0
- plotroom/app/__init__.py +0 -0
- plotroom/app/bridge.py +162 -0
- plotroom/app/clerk_import.py +349 -0
- plotroom/app/cli.py +290 -0
- plotroom/app/clock.py +12 -0
- plotroom/app/config.py +984 -0
- plotroom/app/daemon_start.py +453 -0
- plotroom/app/lock.py +77 -0
- plotroom/app/logging.py +93 -0
- plotroom/app/portfile.py +218 -0
- plotroom/app/runtime.py +518 -0
- plotroom/app/serve.py +671 -0
- plotroom/app/session_intake.py +51 -0
- plotroom/app/sqlite_floor.py +35 -0
- plotroom/app/tokens.py +265 -0
- plotroom/core/__init__.py +0 -0
- plotroom/core/actions.py +67 -0
- plotroom/core/ask_checks.py +124 -0
- plotroom/core/asks.py +123 -0
- plotroom/core/branch_updates.py +207 -0
- plotroom/core/bridge.py +112 -0
- plotroom/core/briefs.py +83 -0
- plotroom/core/budgets.py +182 -0
- plotroom/core/catalog.py +464 -0
- plotroom/core/checklists.py +151 -0
- plotroom/core/claims.py +296 -0
- plotroom/core/clerk_import.py +379 -0
- plotroom/core/commands.py +85 -0
- plotroom/core/deploy_window.py +21 -0
- plotroom/core/envelope.py +20 -0
- plotroom/core/events.py +227 -0
- plotroom/core/github.py +306 -0
- plotroom/core/github_projection.py +310 -0
- plotroom/core/goal_language.py +374 -0
- plotroom/core/goal_projection.py +146 -0
- plotroom/core/human_queue.py +119 -0
- plotroom/core/intake.py +106 -0
- plotroom/core/kodus_review.py +53 -0
- plotroom/core/lanes.py +281 -0
- plotroom/core/ledger.py +808 -0
- plotroom/core/merge_controller.py +344 -0
- plotroom/core/merge_flakes.py +422 -0
- plotroom/core/merge_gate.py +724 -0
- plotroom/core/merge_lane.py +70 -0
- plotroom/core/merge_overlap.py +76 -0
- plotroom/core/next_items.py +60 -0
- plotroom/core/operator_goals.py +103 -0
- plotroom/core/outbox.py +70 -0
- plotroom/core/pull_overlaps.py +152 -0
- plotroom/core/reports.py +62 -0
- plotroom/core/roles.py +100 -0
- plotroom/core/routing.py +55 -0
- plotroom/core/run_reports.py +53 -0
- plotroom/core/search.py +266 -0
- plotroom/core/search_sources.py +94 -0
- plotroom/core/snapshot.py +204 -0
- plotroom/core/trigger_actions.py +89 -0
- plotroom/core/triggers.py +550 -0
- plotroom/core/unit_of_work.py +541 -0
- plotroom/core/watchers.py +35 -0
- plotroom/core/work_items.py +23 -0
- plotroom/core/writer.py +164 -0
- plotroom/ports/__init__.py +6 -0
- plotroom/ports/clock.py +12 -0
- plotroom/ports/github_write.py +72 -0
- plotroom/ports/search.py +197 -0
- plotroom/ports/session_reader.py +23 -0
- plotroom/ports/store.py +323 -0
- plotroom/ports/usage_meter.py +35 -0
- plotroom/ports/work_items.py +22 -0
- plotroom/py.typed +0 -0
- plotroom-0.1.0.dist-info/METADATA +230 -0
- plotroom-0.1.0.dist-info/RECORD +150 -0
- plotroom-0.1.0.dist-info/WHEEL +4 -0
- plotroom-0.1.0.dist-info/entry_points.txt +2 -0
- plotroom-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""Decode the bounded JUnit report dialect used for flake evidence."""
|
|
2
|
+
|
|
3
|
+
import io
|
|
4
|
+
import stat
|
|
5
|
+
import zipfile
|
|
6
|
+
import zlib
|
|
7
|
+
from collections import Counter
|
|
8
|
+
from xml.etree import ElementTree as ET
|
|
9
|
+
|
|
10
|
+
from plotroom.adapters.github.read import Row
|
|
11
|
+
|
|
12
|
+
MAX_XML = 4 * 1024 * 1024
|
|
13
|
+
MAX_TESTS = 5_000
|
|
14
|
+
MAX_FAILED_TESTS = 300
|
|
15
|
+
MAX_NODES = 20_000
|
|
16
|
+
MAX_DEPTH = 32
|
|
17
|
+
MAX_FIELD = 500
|
|
18
|
+
MAX_EXCERPT = 500
|
|
19
|
+
SUITE_METADATA = {"properties", "system-out", "system-err"}
|
|
20
|
+
RESULTS = {"failure": "failures", "error": "errors", "skipped": "skipped"}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class _BoundedTree(ET.TreeBuilder):
|
|
24
|
+
def __init__(self) -> None:
|
|
25
|
+
super().__init__()
|
|
26
|
+
self.nodes = 0
|
|
27
|
+
self.depth = 0
|
|
28
|
+
|
|
29
|
+
def start(self, tag: str, attrs: dict[str, str]) -> ET.Element:
|
|
30
|
+
self.nodes += 1
|
|
31
|
+
self.depth += 1
|
|
32
|
+
if self.nodes > MAX_NODES or self.depth > MAX_DEPTH:
|
|
33
|
+
raise ValueError("JUnit XML exceeded its structural limits")
|
|
34
|
+
return super().start(tag, attrs)
|
|
35
|
+
|
|
36
|
+
def end(self, tag: str) -> ET.Element:
|
|
37
|
+
self.depth -= 1
|
|
38
|
+
return super().end(tag)
|
|
39
|
+
|
|
40
|
+
def doctype(self, name: str, pubid: str | None, system: str | None) -> None:
|
|
41
|
+
raise ValueError("JUnit DTDs are not supported")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _report(archive: bytes) -> ET.Element:
|
|
45
|
+
try:
|
|
46
|
+
with zipfile.ZipFile(io.BytesIO(archive)) as zipped:
|
|
47
|
+
files = zipped.infolist()
|
|
48
|
+
if len(files) != 1:
|
|
49
|
+
raise ValueError("JUnit archive must have exactly one member")
|
|
50
|
+
member = files[0]
|
|
51
|
+
if (
|
|
52
|
+
member.orig_filename != "junit.xml"
|
|
53
|
+
or stat.S_IFMT(member.external_attr >> 16) not in {0, stat.S_IFREG}
|
|
54
|
+
or member.flag_bits & 1
|
|
55
|
+
or member.compress_type not in {zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED}
|
|
56
|
+
or not 0 < member.file_size <= MAX_XML
|
|
57
|
+
):
|
|
58
|
+
raise ValueError("JUnit archive member is unsafe")
|
|
59
|
+
with zipped.open(member) as source:
|
|
60
|
+
document = source.read(MAX_XML + 1)
|
|
61
|
+
if len(document) != member.file_size:
|
|
62
|
+
raise ValueError("JUnit archive member is incomplete")
|
|
63
|
+
# The target rejects DTDs before entity resolution and limits tree growth.
|
|
64
|
+
parser = ET.XMLParser(target=_BoundedTree()) # noqa: S314
|
|
65
|
+
return ET.fromstring(document.decode("utf-8", errors="strict"), parser=parser) # noqa: S314
|
|
66
|
+
except (
|
|
67
|
+
ET.ParseError,
|
|
68
|
+
OSError,
|
|
69
|
+
EOFError,
|
|
70
|
+
RuntimeError,
|
|
71
|
+
zipfile.BadZipFile,
|
|
72
|
+
zlib.error,
|
|
73
|
+
):
|
|
74
|
+
raise ValueError("JUnit archive or XML is invalid") from None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _field(value: str) -> bool:
|
|
78
|
+
return (
|
|
79
|
+
bool(value)
|
|
80
|
+
and len(value) <= MAX_FIELD
|
|
81
|
+
and value.strip() == value
|
|
82
|
+
and all(character.isprintable() for character in value)
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _case(element: ET.Element) -> tuple[tuple[str, str], ET.Element | None]:
|
|
87
|
+
path = element.get("file", "")
|
|
88
|
+
classname, name = element.get("classname", ""), element.get("name", "")
|
|
89
|
+
test_id = f"{classname}::{name}"
|
|
90
|
+
if (
|
|
91
|
+
not _field(path)
|
|
92
|
+
or "\\" in path
|
|
93
|
+
or ":" in path
|
|
94
|
+
or any(part in {"", ".", ".."} for part in path.split("/"))
|
|
95
|
+
or not _field(classname)
|
|
96
|
+
or "::" in classname
|
|
97
|
+
or not _field(name)
|
|
98
|
+
or len(test_id) > MAX_FIELD
|
|
99
|
+
):
|
|
100
|
+
raise ValueError("JUnit testcase has no safe, stable identity")
|
|
101
|
+
outcomes = [child for child in element if child.tag in RESULTS]
|
|
102
|
+
if len(outcomes) > 1 or any(
|
|
103
|
+
child.tag not in RESULTS and child.tag not in SUITE_METADATA for child in element
|
|
104
|
+
):
|
|
105
|
+
raise ValueError("JUnit testcase has an unknown or ambiguous outcome")
|
|
106
|
+
outcome = outcomes[0] if outcomes else None
|
|
107
|
+
skipped = outcome is not None and outcome.tag == "skipped"
|
|
108
|
+
statuses = (None, "run", "notrun") if skipped else (None, "run")
|
|
109
|
+
results = (None, "completed", "suppressed") if skipped else (None, "completed")
|
|
110
|
+
if element.get("status") not in statuses or element.get("result") not in results:
|
|
111
|
+
raise ValueError("JUnit testcase does not establish a completed result")
|
|
112
|
+
return (path, test_id), outcome
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _certify_counts(suite: ET.Element, counts: Counter[str]) -> None:
|
|
116
|
+
for key in ("tests", "failures", "errors", "skipped"):
|
|
117
|
+
if key in suite.attrib and suite.attrib[key] != str(counts[key]):
|
|
118
|
+
raise ValueError("JUnit suite counters do not match the testcases")
|
|
119
|
+
if suite.get("disabled", "0") != "0":
|
|
120
|
+
raise ValueError("JUnit suite has tests without completed results")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _collect(
|
|
124
|
+
suite: ET.Element,
|
|
125
|
+
cases: dict[tuple[str, str], ET.Element | None],
|
|
126
|
+
) -> Counter[str]:
|
|
127
|
+
if suite.tag not in {"testsuite", "testsuites"}:
|
|
128
|
+
raise ValueError("JUnit report has an unknown suite")
|
|
129
|
+
counts: Counter[str] = Counter()
|
|
130
|
+
for child in suite:
|
|
131
|
+
if child.tag == "testsuite":
|
|
132
|
+
counts.update(_collect(child, cases))
|
|
133
|
+
elif child.tag == "testcase" and suite.tag == "testsuite":
|
|
134
|
+
identity, outcome = _case(child)
|
|
135
|
+
if identity in cases or len(cases) >= MAX_TESTS:
|
|
136
|
+
raise ValueError("JUnit report has duplicate or too many testcases")
|
|
137
|
+
cases[identity] = outcome
|
|
138
|
+
counts["tests"] += 1
|
|
139
|
+
if outcome is not None:
|
|
140
|
+
counts[RESULTS[outcome.tag]] += 1
|
|
141
|
+
elif child.tag not in SUITE_METADATA:
|
|
142
|
+
raise ValueError("JUnit suite has unexpected data")
|
|
143
|
+
_certify_counts(suite, counts)
|
|
144
|
+
return counts
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def junit_evidence(archive: bytes, *, passed: bool) -> list[Row]:
|
|
148
|
+
cases: dict[tuple[str, str], ET.Element | None] = {}
|
|
149
|
+
counts = _collect(_report(archive), cases)
|
|
150
|
+
failed = counts["failures"] + counts["errors"]
|
|
151
|
+
if bool(failed) == passed:
|
|
152
|
+
raise ValueError("JUnit report does not confirm its job result")
|
|
153
|
+
if failed > MAX_FAILED_TESTS:
|
|
154
|
+
raise ValueError("JUnit report has too many failed testcases")
|
|
155
|
+
evidence: list[Row] = []
|
|
156
|
+
for (path, test_id), outcome in cases.items():
|
|
157
|
+
if passed and outcome is None:
|
|
158
|
+
evidence.append({"path": path, "test_id": test_id})
|
|
159
|
+
elif not passed and outcome is not None and outcome.tag != "skipped":
|
|
160
|
+
excerpt = (outcome.get("message") or outcome.text or "")[:MAX_EXCERPT]
|
|
161
|
+
evidence.append({"path": path, "test_id": test_id, "excerpt": excerpt})
|
|
162
|
+
return evidence
|
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
"""Read exact-head Kodus check evidence for one open pull request."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from typing import Literal
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
from plotroom.adapters.github import GitHubUnavailable
|
|
12
|
+
from plotroom.adapters.github.read import (
|
|
13
|
+
GitHubReadClient,
|
|
14
|
+
ReviewThreadPull,
|
|
15
|
+
Row,
|
|
16
|
+
number,
|
|
17
|
+
obj,
|
|
18
|
+
rows,
|
|
19
|
+
string,
|
|
20
|
+
)
|
|
21
|
+
from plotroom.core.events import format_time
|
|
22
|
+
from plotroom.core.github import PullRequest, valid_git_sha
|
|
23
|
+
from plotroom.core.github_projection import GitHubResource
|
|
24
|
+
from plotroom.core.kodus_review import KodusReviewPolicy
|
|
25
|
+
|
|
26
|
+
_REVIEWED = "Review finished successfully. Suggestions (if any) were posted as PR/file comments."
|
|
27
|
+
_CADENCE_SKIP = "Manual mode requires @kody start-review."
|
|
28
|
+
_MAINTAINER_ASSOCIATIONS = frozenset({"OWNER", "MEMBER", "COLLABORATOR"})
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class PullIdentity:
|
|
33
|
+
pull_id: int
|
|
34
|
+
base_repository_id: int
|
|
35
|
+
head_repository_id: int
|
|
36
|
+
created_at: datetime
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class ReviewCheck:
|
|
41
|
+
id: int
|
|
42
|
+
mode: Literal["reviewed", "cadence-skip"]
|
|
43
|
+
fingerprint: str
|
|
44
|
+
head_sha: str
|
|
45
|
+
started_at: datetime
|
|
46
|
+
completed_at: datetime
|
|
47
|
+
association: tuple[int, int, int, int, str] | None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _nonempty(value: object) -> str:
|
|
51
|
+
result = string(value)
|
|
52
|
+
if not result.strip():
|
|
53
|
+
raise ValueError("GitHub returned an empty identity")
|
|
54
|
+
return result
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _time(value: object) -> datetime:
|
|
58
|
+
timestamp = datetime.fromisoformat(string(value))
|
|
59
|
+
if timestamp.utcoffset() is None:
|
|
60
|
+
raise ValueError("GitHub returned a timestamp without an offset")
|
|
61
|
+
return timestamp
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _pull_identity(row: Row, pull: PullRequest) -> PullIdentity:
|
|
65
|
+
base, head = obj(row["base"]), obj(row["head"])
|
|
66
|
+
base_repo, head_repo = obj(base["repo"]), obj(head["repo"])
|
|
67
|
+
if (
|
|
68
|
+
number(row["number"]) != pull.number
|
|
69
|
+
or row["state"] != "open"
|
|
70
|
+
or string(base_repo["full_name"]).lower() != pull.repository
|
|
71
|
+
or string(head_repo["full_name"]).lower() != pull.head_repository
|
|
72
|
+
or head["ref"] != pull.branch
|
|
73
|
+
or head["sha"] != pull.head_sha
|
|
74
|
+
or _time(row["updated_at"]) != _time(pull.updated_at)
|
|
75
|
+
):
|
|
76
|
+
raise GitHubUnavailable("GitHub returned a different pull request revision")
|
|
77
|
+
return PullIdentity(
|
|
78
|
+
number(row["id"]),
|
|
79
|
+
number(base_repo["id"]),
|
|
80
|
+
number(head_repo["id"]),
|
|
81
|
+
_time(row["created_at"]),
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _is_kodus_check(row: Row, policy: KodusReviewPolicy) -> bool:
|
|
86
|
+
raw_app = row.get("app")
|
|
87
|
+
if row.get("name") != policy.check_name or not isinstance(raw_app, dict):
|
|
88
|
+
return False
|
|
89
|
+
app = obj(raw_app)
|
|
90
|
+
return (
|
|
91
|
+
type(app.get("id")) is int
|
|
92
|
+
and app["id"] == policy.app_id
|
|
93
|
+
and app.get("slug") == policy.app_slug
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _pull_association(row: Row) -> tuple[int, int, int, int, str]:
|
|
98
|
+
base, head = obj(row["base"]), obj(row["head"])
|
|
99
|
+
return (
|
|
100
|
+
number(row["number"]),
|
|
101
|
+
number(row["id"]),
|
|
102
|
+
number(obj(base["repo"])["id"]),
|
|
103
|
+
number(obj(head["repo"])["id"]),
|
|
104
|
+
string(head["sha"]),
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def parse_review_check(row: Row, policy: KodusReviewPolicy) -> ReviewCheck | None:
|
|
109
|
+
"""Recognize the App's exact result and fingerprint the check inputs used by the gate."""
|
|
110
|
+
if not _is_kodus_check(row, policy) or row.get("status") != "completed":
|
|
111
|
+
return None
|
|
112
|
+
try:
|
|
113
|
+
signature = (row["conclusion"], obj(row["output"])["summary"])
|
|
114
|
+
if signature == ("success", _REVIEWED):
|
|
115
|
+
mode = "reviewed"
|
|
116
|
+
elif signature == ("skipped", _CADENCE_SKIP):
|
|
117
|
+
mode = "cadence-skip"
|
|
118
|
+
else:
|
|
119
|
+
return None
|
|
120
|
+
run_id, head_sha = number(row["id"]), string(row["head_sha"])
|
|
121
|
+
if not valid_git_sha(head_sha):
|
|
122
|
+
return None
|
|
123
|
+
started_at, completed_at = _time(row["started_at"]), _time(row["completed_at"])
|
|
124
|
+
associations = rows(row["pull_requests"])
|
|
125
|
+
if len(associations) > 1:
|
|
126
|
+
return None
|
|
127
|
+
association = _pull_association(associations[0]) if associations else None
|
|
128
|
+
canonical = (
|
|
129
|
+
mode,
|
|
130
|
+
run_id,
|
|
131
|
+
head_sha,
|
|
132
|
+
policy.app_id,
|
|
133
|
+
policy.app_slug,
|
|
134
|
+
policy.check_name,
|
|
135
|
+
format_time(started_at),
|
|
136
|
+
format_time(completed_at),
|
|
137
|
+
association,
|
|
138
|
+
)
|
|
139
|
+
fingerprint = hashlib.sha256(json.dumps(canonical).encode()).hexdigest()
|
|
140
|
+
except KeyError, TypeError, ValueError, OverflowError:
|
|
141
|
+
return None
|
|
142
|
+
return ReviewCheck(run_id, mode, fingerprint, head_sha, started_at, completed_at, association)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
async def _review_form_binds_pull(
|
|
146
|
+
api: GitHubReadClient,
|
|
147
|
+
client: httpx.AsyncClient,
|
|
148
|
+
token: str,
|
|
149
|
+
pull: PullRequest,
|
|
150
|
+
policy: KodusReviewPolicy,
|
|
151
|
+
sha: str,
|
|
152
|
+
started_at: datetime,
|
|
153
|
+
completed_at: datetime,
|
|
154
|
+
) -> bool:
|
|
155
|
+
"""Corroborate an unassociated success with a submitted exact-commit review."""
|
|
156
|
+
path = f"/pulls/{pull.number}"
|
|
157
|
+
bot_login = f"{policy.app_slug}[bot]"
|
|
158
|
+
url_prefix = f"{api.api_url}/repos/"
|
|
159
|
+
identifiers: set[int] = set()
|
|
160
|
+
matches = 0
|
|
161
|
+
async for review in api.pages(
|
|
162
|
+
client,
|
|
163
|
+
token,
|
|
164
|
+
f"{path}/reviews",
|
|
165
|
+
verify_terminal=True,
|
|
166
|
+
verify_boundaries=True,
|
|
167
|
+
):
|
|
168
|
+
review_id = number(review["id"])
|
|
169
|
+
url = string(review["pull_request_url"])
|
|
170
|
+
if (
|
|
171
|
+
review_id in identifiers
|
|
172
|
+
or not url.startswith(url_prefix)
|
|
173
|
+
or not url.endswith(path)
|
|
174
|
+
or url.removeprefix(url_prefix).removesuffix(path).lower() != api.repository.lower()
|
|
175
|
+
):
|
|
176
|
+
return False
|
|
177
|
+
identifiers.add(review_id)
|
|
178
|
+
user = obj(review["user"])
|
|
179
|
+
if _nonempty(user["login"]).lower() != bot_login:
|
|
180
|
+
continue
|
|
181
|
+
if user["type"] != "Bot":
|
|
182
|
+
return False
|
|
183
|
+
submitted_at = _time(review["submitted_at"])
|
|
184
|
+
if not started_at <= submitted_at <= completed_at:
|
|
185
|
+
continue
|
|
186
|
+
explicit_app = review.get("performed_via_github_app")
|
|
187
|
+
if explicit_app is not None:
|
|
188
|
+
app = obj(explicit_app)
|
|
189
|
+
if number(app["id"]) != policy.app_id or string(app["slug"]) != policy.app_slug:
|
|
190
|
+
return False
|
|
191
|
+
if review["commit_id"] != sha or review["state"] != "COMMENTED":
|
|
192
|
+
return False
|
|
193
|
+
matches += 1
|
|
194
|
+
return matches == 1
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
async def _check(
|
|
198
|
+
api: GitHubReadClient,
|
|
199
|
+
client: httpx.AsyncClient,
|
|
200
|
+
token: str,
|
|
201
|
+
pull: PullRequest,
|
|
202
|
+
identity: PullIdentity,
|
|
203
|
+
policy: KodusReviewPolicy,
|
|
204
|
+
sha: str,
|
|
205
|
+
) -> ReviewCheck:
|
|
206
|
+
if not valid_git_sha(sha):
|
|
207
|
+
raise ValueError("invalid Kodus check head")
|
|
208
|
+
trusted: list[Row] = []
|
|
209
|
+
identifiers: set[int] = set()
|
|
210
|
+
async for row in api.pages(
|
|
211
|
+
client,
|
|
212
|
+
token,
|
|
213
|
+
f"/commits/{sha}/check-runs",
|
|
214
|
+
key="check_runs",
|
|
215
|
+
params={"check_name": policy.check_name, "filter": "latest"},
|
|
216
|
+
verify_total=True,
|
|
217
|
+
verify_boundaries=True,
|
|
218
|
+
):
|
|
219
|
+
run_id = number(row["id"])
|
|
220
|
+
if run_id in identifiers:
|
|
221
|
+
raise GitHubUnavailable("GitHub returned duplicate check IDs")
|
|
222
|
+
identifiers.add(run_id)
|
|
223
|
+
if _is_kodus_check(row, policy):
|
|
224
|
+
trusted.append(row)
|
|
225
|
+
if len(trusted) != 1:
|
|
226
|
+
raise GitHubUnavailable("GitHub did not return one trusted Kodus check")
|
|
227
|
+
check = parse_review_check(trusted[0], policy)
|
|
228
|
+
if (
|
|
229
|
+
check is None
|
|
230
|
+
or check.head_sha != sha
|
|
231
|
+
or not identity.created_at <= check.started_at <= check.completed_at
|
|
232
|
+
):
|
|
233
|
+
raise GitHubUnavailable("Kodus check does not prove an exact completed-head outcome")
|
|
234
|
+
# The association may contain GitHub's current PR snapshot. The run's own head is pinned above.
|
|
235
|
+
association = check.association
|
|
236
|
+
if (
|
|
237
|
+
association is not None
|
|
238
|
+
and association[:4]
|
|
239
|
+
== (pull.number, identity.pull_id, identity.base_repository_id, identity.head_repository_id)
|
|
240
|
+
and association[4] in (sha, pull.head_sha)
|
|
241
|
+
):
|
|
242
|
+
return check
|
|
243
|
+
if (
|
|
244
|
+
check.association is None
|
|
245
|
+
and check.mode == "reviewed"
|
|
246
|
+
and await _review_form_binds_pull(
|
|
247
|
+
api, client, token, pull, policy, sha, check.started_at, check.completed_at
|
|
248
|
+
)
|
|
249
|
+
):
|
|
250
|
+
return check
|
|
251
|
+
raise GitHubUnavailable("Kodus check lacks a verified review or cadence skip for this pull")
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _answered(thread: Row, pr_author: str) -> bool:
|
|
255
|
+
if thread["isResolved"] is not True:
|
|
256
|
+
return False
|
|
257
|
+
connection = obj(thread["comments"])
|
|
258
|
+
comments = rows(connection["nodes"])
|
|
259
|
+
count = number(connection["totalCount"])
|
|
260
|
+
if not count == len(comments) <= 100 or obj(connection["pageInfo"])["hasNextPage"] is not False:
|
|
261
|
+
return False
|
|
262
|
+
identifiers = {_nonempty(comment["id"]) for comment in comments}
|
|
263
|
+
roots = [comment for comment in comments if comment["replyTo"] is None]
|
|
264
|
+
if len(identifiers) != count or len(roots) != 1:
|
|
265
|
+
return False
|
|
266
|
+
root = roots[0]
|
|
267
|
+
reviewer = _nonempty(obj(root["author"])["login"]).lower()
|
|
268
|
+
answered = False
|
|
269
|
+
for comment in comments:
|
|
270
|
+
actor = obj(comment["author"])
|
|
271
|
+
login = _nonempty(actor["login"]).lower()
|
|
272
|
+
kind = _nonempty(actor["__typename"])
|
|
273
|
+
association = _nonempty(comment["authorAssociation"])
|
|
274
|
+
if comment is root:
|
|
275
|
+
continue
|
|
276
|
+
if obj(comment["replyTo"])["id"] != root["id"]:
|
|
277
|
+
return False
|
|
278
|
+
if (
|
|
279
|
+
kind == "User"
|
|
280
|
+
and login != reviewer
|
|
281
|
+
and (login == pr_author or association in _MAINTAINER_ASSOCIATIONS)
|
|
282
|
+
):
|
|
283
|
+
answered = True
|
|
284
|
+
return answered
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
async def fetch_kodus_review(
|
|
288
|
+
api: GitHubReadClient,
|
|
289
|
+
client: httpx.AsyncClient,
|
|
290
|
+
token: str,
|
|
291
|
+
pull: PullRequest,
|
|
292
|
+
policy: KodusReviewPolicy,
|
|
293
|
+
) -> GitHubResource:
|
|
294
|
+
if pull.repository != api.repository.lower():
|
|
295
|
+
raise ValueError("Kodus evidence requested from a different repository")
|
|
296
|
+
path = f"/pulls/{number(pull.number)}"
|
|
297
|
+
detail = obj(await api.get(client, token, path))
|
|
298
|
+
identity = _pull_identity(detail, pull)
|
|
299
|
+
check = await _check(api, client, token, pull, identity, policy, pull.head_sha)
|
|
300
|
+
evidence: Row = {
|
|
301
|
+
"repository": pull.repository,
|
|
302
|
+
"pull_number": pull.number,
|
|
303
|
+
"pull_id": identity.pull_id,
|
|
304
|
+
"created_at": format_time(identity.created_at),
|
|
305
|
+
"head_sha": pull.head_sha,
|
|
306
|
+
"pull_version": pull.version,
|
|
307
|
+
"pull_updated_at": pull.updated_at,
|
|
308
|
+
"app_id": policy.app_id,
|
|
309
|
+
"app_slug": policy.app_slug,
|
|
310
|
+
"check_name": policy.check_name,
|
|
311
|
+
"check_id": check.id,
|
|
312
|
+
"check_fingerprint": check.fingerprint,
|
|
313
|
+
"mode": check.mode,
|
|
314
|
+
}
|
|
315
|
+
if check.mode == "cadence-skip":
|
|
316
|
+
opening = policy.opening_head(pull.repository, pull.number)
|
|
317
|
+
if (
|
|
318
|
+
opening is None
|
|
319
|
+
or opening.head_sha == pull.head_sha
|
|
320
|
+
or opening.pull_id != identity.pull_id
|
|
321
|
+
or opening.created_at != evidence["created_at"]
|
|
322
|
+
):
|
|
323
|
+
raise GitHubUnavailable("No trusted opening head attestation for this pull request")
|
|
324
|
+
opening_check = await _check(api, client, token, pull, identity, policy, opening.head_sha)
|
|
325
|
+
if opening_check.mode != "reviewed" or opening_check.id == check.id:
|
|
326
|
+
raise GitHubUnavailable("Opening head lacks a completed Kodus review")
|
|
327
|
+
if opening_check.completed_at > check.started_at:
|
|
328
|
+
raise GitHubUnavailable(
|
|
329
|
+
"The current cadence skip started before opening review completed"
|
|
330
|
+
)
|
|
331
|
+
author = _nonempty(obj(detail["user"])["login"]).lower()
|
|
332
|
+
thread_pull = ReviewThreadPull(_nonempty(detail["node_id"]), author)
|
|
333
|
+
answered_threads: list[str] = []
|
|
334
|
+
async for thread in api.review_threads(
|
|
335
|
+
client, token, pull.number, pull.head_sha, cadence=thread_pull
|
|
336
|
+
):
|
|
337
|
+
if not _answered(thread, author):
|
|
338
|
+
raise GitHubUnavailable("A cadence review thread is unresolved or unanswered")
|
|
339
|
+
answered_threads.append(string(thread["id"]))
|
|
340
|
+
evidence.update(
|
|
341
|
+
opening_sha=opening.head_sha,
|
|
342
|
+
opening_check_id=opening_check.id,
|
|
343
|
+
answered_threads=sorted(answered_threads),
|
|
344
|
+
)
|
|
345
|
+
if _pull_identity(obj(await api.get(client, token, path)), pull) != identity:
|
|
346
|
+
raise GitHubUnavailable("Pull identity changed during the Kodus review read")
|
|
347
|
+
return GitHubResource((), attributes=evidence)
|