contribcheck 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.
@@ -0,0 +1,9 @@
1
+ """ContribCheck public package interface."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from contribcheck.analyzer import IssueAnalyzer
6
+ from contribcheck.github import GitHubClient
7
+ from contribcheck.models import InspectionReport, OverallStatus
8
+
9
+ __all__ = ["GitHubClient", "InspectionReport", "IssueAnalyzer", "OverallStatus"]
@@ -0,0 +1,585 @@
1
+ """Deterministic readiness analysis built from public GitHub evidence."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from collections.abc import Awaitable, Iterable
7
+ from dataclasses import dataclass
8
+ from datetime import UTC, datetime
9
+ from typing import Any, Generic, Protocol, TypeVar, cast
10
+
11
+ from pydantic import HttpUrl
12
+
13
+ from contribcheck.models import (
14
+ CheckResult,
15
+ Evidence,
16
+ InspectionReport,
17
+ IssueTarget,
18
+ JsonObject,
19
+ OverallStatus,
20
+ SignalStatus,
21
+ )
22
+ from contribcheck.parsing import comment_claims_work, extract_base_branch, parse_issue_reference
23
+
24
+ T = TypeVar("T")
25
+ MAINTAINER_ASSOCIATIONS = {"OWNER", "MEMBER", "COLLABORATOR"}
26
+ HARD_BLOCKER_KEYS = {"issue_state", "dependencies", "base_branch", "assignment", "repository"}
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class FetchResult(Generic[T]):
31
+ """Value-or-error wrapper used to keep optional checks independent."""
32
+
33
+ value: T | None = None
34
+ error: Exception | None = None
35
+
36
+
37
+ async def _capture(awaitable: Awaitable[T]) -> FetchResult[T]:
38
+ try:
39
+ return FetchResult(value=await awaitable)
40
+ except Exception as error: # Optional signals must not turn into false readiness.
41
+ return FetchResult(error=error)
42
+
43
+
44
+ class GitHubReader(Protocol):
45
+ """Read operations required by the analyzer."""
46
+
47
+ async def get_repository(self, target: IssueTarget) -> JsonObject: ...
48
+
49
+ async def get_issue(self, target: IssueTarget) -> JsonObject: ...
50
+
51
+ async def get_blocking_dependencies(self, target: IssueTarget) -> list[JsonObject]: ...
52
+
53
+ async def get_comments(self, target: IssueTarget) -> list[JsonObject]: ...
54
+
55
+ async def get_timeline(self, target: IssueTarget) -> list[JsonObject]: ...
56
+
57
+ async def search_open_pull_requests(self, target: IssueTarget) -> list[JsonObject]: ...
58
+
59
+ async def get_tree_paths(self, target: IssueTarget, ref: str) -> set[str]: ...
60
+
61
+ async def get_recent_workflow_runs(
62
+ self, target: IssueTarget, branch: str, *, limit: int = 10
63
+ ) -> list[JsonObject]: ...
64
+
65
+ async def branch_exists(self, target: IssueTarget, branch: str) -> bool: ...
66
+
67
+
68
+ class IssueAnalyzer:
69
+ """Inspect whether a public GitHub issue is ready for contribution."""
70
+
71
+ def __init__(self, client: GitHubReader) -> None:
72
+ self.client = client
73
+
74
+ async def inspect(self, reference: str, *, actor: str | None = None) -> InspectionReport:
75
+ """Build a report for one issue URL or shorthand reference."""
76
+
77
+ target = parse_issue_reference(reference)
78
+ repository, issue = await asyncio.gather(
79
+ self.client.get_repository(target), self.client.get_issue(target)
80
+ )
81
+ if "pull_request" in issue:
82
+ raise ValueError("ContribCheck currently inspects issues, not pull requests.")
83
+
84
+ default_branch = _string(repository.get("default_branch")) or "main"
85
+ base_branch = extract_base_branch(_string(issue.get("body")))
86
+
87
+ (
88
+ dependencies_result,
89
+ comments_result,
90
+ timeline_result,
91
+ search_result,
92
+ tree_result,
93
+ runs_result,
94
+ ) = await asyncio.gather(
95
+ _capture(self.client.get_blocking_dependencies(target)),
96
+ _capture(self.client.get_comments(target)),
97
+ _capture(self.client.get_timeline(target)),
98
+ _capture(self.client.search_open_pull_requests(target)),
99
+ _capture(self.client.get_tree_paths(target, default_branch)),
100
+ _capture(self.client.get_recent_workflow_runs(target, default_branch)),
101
+ )
102
+ branch_result = (
103
+ await _capture(self.client.branch_exists(target, base_branch))
104
+ if base_branch
105
+ else FetchResult[bool](value=None)
106
+ )
107
+
108
+ checks = [
109
+ self._issue_state_check(issue),
110
+ self._dependency_check(dependencies_result),
111
+ self._base_branch_check(base_branch, branch_result, target),
112
+ self._assignment_check(issue, actor),
113
+ self._claims_check(comments_result, actor),
114
+ self._competing_pr_check(timeline_result, search_result),
115
+ self._scope_check(issue),
116
+ self._contribution_docs_check(tree_result, target, default_branch),
117
+ self._repository_check(repository),
118
+ self._ci_check(runs_result),
119
+ self._maintainer_response_check(issue, comments_result),
120
+ ]
121
+ status = self._overall_status(checks)
122
+ return InspectionReport(
123
+ target=target,
124
+ title=_string(issue.get("title")) or f"Issue #{target.number}",
125
+ status=status,
126
+ checks=checks,
127
+ next_actions=self._next_actions(checks, status),
128
+ )
129
+
130
+ @staticmethod
131
+ def _issue_state_check(issue: JsonObject) -> CheckResult:
132
+ state = (_string(issue.get("state")) or "unknown").casefold()
133
+ if state == "open":
134
+ return _check("issue_state", "Issue state", SignalStatus.PASS, "The issue is open.")
135
+ return _check(
136
+ "issue_state",
137
+ "Issue state",
138
+ SignalStatus.FAILURE,
139
+ f"The issue is {state}; new implementation work should not begin.",
140
+ )
141
+
142
+ @staticmethod
143
+ def _dependency_check(result: FetchResult[list[JsonObject]]) -> CheckResult:
144
+ if result.error:
145
+ return _unknown("dependencies", "Dependencies", result.error)
146
+ dependencies = result.value or []
147
+ open_dependencies = [item for item in dependencies if item.get("state") == "open"]
148
+ if not open_dependencies:
149
+ return _check(
150
+ "dependencies", "Dependencies", SignalStatus.PASS, "No open blockers reported."
151
+ )
152
+ evidence = [
153
+ Evidence(
154
+ text=f"#{item.get('number')}: {item.get('title', 'Untitled issue')}",
155
+ url=_url(item.get("html_url")),
156
+ )
157
+ for item in open_dependencies
158
+ ]
159
+ return _check(
160
+ "dependencies",
161
+ "Dependencies",
162
+ SignalStatus.FAILURE,
163
+ f"Blocked by {len(open_dependencies)} open issue(s).",
164
+ evidence,
165
+ )
166
+
167
+ @staticmethod
168
+ def _base_branch_check(
169
+ branch: str | None, result: FetchResult[bool], target: IssueTarget
170
+ ) -> CheckResult:
171
+ if branch is None:
172
+ return _check(
173
+ "base_branch",
174
+ "Base branch",
175
+ SignalStatus.INFO,
176
+ "No non-default base branch is explicitly required in the issue body.",
177
+ )
178
+ if result.error:
179
+ return _unknown("base_branch", "Base branch", result.error)
180
+ if result.value:
181
+ return _check(
182
+ "base_branch",
183
+ "Base branch",
184
+ SignalStatus.PASS,
185
+ f"Required branch `{branch}` exists.",
186
+ [
187
+ Evidence(
188
+ text=branch,
189
+ url=_url(f"https://{target.host}/{target.full_name}/tree/{branch}"),
190
+ )
191
+ ],
192
+ )
193
+ return _check(
194
+ "base_branch",
195
+ "Base branch",
196
+ SignalStatus.FAILURE,
197
+ f"Required branch `{branch}` does not exist.",
198
+ )
199
+
200
+ @staticmethod
201
+ def _assignment_check(issue: JsonObject, actor: str | None) -> CheckResult:
202
+ assignees = _logins(issue.get("assignees"))
203
+ if not assignees:
204
+ return _check("assignment", "Assignment", SignalStatus.PASS, "The issue is unassigned.")
205
+ if actor and actor.casefold() in {login.casefold() for login in assignees}:
206
+ return _check(
207
+ "assignment",
208
+ "Assignment",
209
+ SignalStatus.PASS,
210
+ f"Assigned to the requested contributor, `{actor}`.",
211
+ )
212
+ return _check(
213
+ "assignment",
214
+ "Assignment",
215
+ SignalStatus.FAILURE,
216
+ "The issue is already assigned.",
217
+ [Evidence(text=login, url=_url(f"https://github.com/{login}")) for login in assignees],
218
+ )
219
+
220
+ @staticmethod
221
+ def _claims_check(result: FetchResult[list[JsonObject]], actor: str | None) -> CheckResult:
222
+ if result.error:
223
+ return _unknown("claims", "Comment claims", result.error)
224
+ claims: dict[str, JsonObject] = {}
225
+ for comment in result.value or []:
226
+ body = _string(comment.get("body")) or ""
227
+ login = _nested_string(comment, "user", "login")
228
+ if not login or login.endswith("[bot]") or not comment_claims_work(body):
229
+ continue
230
+ if actor and login.casefold() == actor.casefold():
231
+ continue
232
+ claims.setdefault(login, comment)
233
+ if not claims:
234
+ return _check(
235
+ "claims",
236
+ "Comment claims",
237
+ SignalStatus.PASS,
238
+ "No other contributor appears to have claimed the issue in comments.",
239
+ )
240
+ evidence = [
241
+ Evidence(text=login, url=_url(comment.get("html_url")))
242
+ for login, comment in claims.items()
243
+ ]
244
+ return _check(
245
+ "claims",
246
+ "Comment claims",
247
+ SignalStatus.WARNING,
248
+ "Another contributor may already be working on this issue.",
249
+ evidence,
250
+ )
251
+
252
+ @staticmethod
253
+ def _competing_pr_check(
254
+ timeline_result: FetchResult[list[JsonObject]],
255
+ search_result: FetchResult[list[JsonObject]],
256
+ ) -> CheckResult:
257
+ pull_requests: dict[str, str] = {}
258
+ for event in timeline_result.value or []:
259
+ if event.get("event") != "cross-referenced":
260
+ continue
261
+ source_issue = _nested_object(event, "source", "issue")
262
+ if not source_issue or "pull_request" not in source_issue:
263
+ continue
264
+ if source_issue.get("state") != "open":
265
+ continue
266
+ url = _string(source_issue.get("html_url"))
267
+ if url:
268
+ pull_requests[url] = _string(source_issue.get("title")) or url
269
+ for item in search_result.value or []:
270
+ url = _string(item.get("html_url"))
271
+ if url:
272
+ pull_requests[url] = _string(item.get("title")) or url
273
+
274
+ partial_error = timeline_result.error or search_result.error
275
+ if not pull_requests:
276
+ if partial_error:
277
+ return _unknown("competing_prs", "Competing pull requests", partial_error)
278
+ return _check(
279
+ "competing_prs",
280
+ "Competing pull requests",
281
+ SignalStatus.PASS,
282
+ "No open pull request referencing this issue was found.",
283
+ )
284
+ return _check(
285
+ "competing_prs",
286
+ "Competing pull requests",
287
+ SignalStatus.WARNING,
288
+ f"Found {len(pull_requests)} potentially competing open PR(s).",
289
+ [Evidence(text=title, url=_url(url)) for url, title in pull_requests.items()],
290
+ )
291
+
292
+ @staticmethod
293
+ def _scope_check(issue: JsonObject) -> CheckResult:
294
+ body = (_string(issue.get("body")) or "").strip()
295
+ normalized = body.casefold()
296
+ has_outcome = any(
297
+ marker in normalized
298
+ for marker in (
299
+ "definition of done",
300
+ "acceptance criteria",
301
+ "expected behavior",
302
+ "scope",
303
+ )
304
+ )
305
+ if len(body) >= 200 and has_outcome:
306
+ return _check(
307
+ "scope", "Issue scope", SignalStatus.PASS, "The issue describes scope or outcomes."
308
+ )
309
+ if len(body) >= 100:
310
+ return _check(
311
+ "scope",
312
+ "Issue scope",
313
+ SignalStatus.INFO,
314
+ "The issue has context, but acceptance criteria are not explicit.",
315
+ )
316
+ return _check(
317
+ "scope",
318
+ "Issue scope",
319
+ SignalStatus.WARNING,
320
+ "The issue description may be too brief to implement safely without clarification.",
321
+ )
322
+
323
+ @staticmethod
324
+ def _contribution_docs_check(
325
+ result: FetchResult[set[str]], target: IssueTarget, default_branch: str
326
+ ) -> CheckResult:
327
+ if result.error:
328
+ return _unknown("contribution_docs", "Contribution guide", result.error)
329
+ paths = result.value or set()
330
+ candidates = sorted(
331
+ path
332
+ for path in paths
333
+ if path.casefold() in {"contributing.md", "contributing.rst", ".github/contributing.md"}
334
+ )
335
+ if not candidates:
336
+ return _check(
337
+ "contribution_docs",
338
+ "Contribution guide",
339
+ SignalStatus.WARNING,
340
+ "No standard contribution guide was found.",
341
+ )
342
+ path = candidates[0]
343
+ return _check(
344
+ "contribution_docs",
345
+ "Contribution guide",
346
+ SignalStatus.PASS,
347
+ f"Found `{path}`.",
348
+ [
349
+ Evidence(
350
+ text=path,
351
+ url=_url(
352
+ f"https://{target.host}/{target.full_name}/blob/{default_branch}/{path}"
353
+ ),
354
+ )
355
+ ],
356
+ )
357
+
358
+ @staticmethod
359
+ def _repository_check(repository: JsonObject) -> CheckResult:
360
+ if repository.get("archived") is True or repository.get("disabled") is True:
361
+ return _check(
362
+ "repository",
363
+ "Repository health",
364
+ SignalStatus.FAILURE,
365
+ "The repository is archived or disabled.",
366
+ )
367
+ if repository.get("has_pull_requests") is False:
368
+ return _check(
369
+ "repository",
370
+ "Repository health",
371
+ SignalStatus.FAILURE,
372
+ "Pull requests are disabled for this repository.",
373
+ )
374
+ pushed_at = _datetime(repository.get("pushed_at"))
375
+ if pushed_at and (datetime.now(UTC) - pushed_at).days > 180:
376
+ age_days = (datetime.now(UTC) - pushed_at).days
377
+ return _check(
378
+ "repository",
379
+ "Repository health",
380
+ SignalStatus.WARNING,
381
+ f"The default repository activity is {age_days} days old.",
382
+ )
383
+ return _check(
384
+ "repository",
385
+ "Repository health",
386
+ SignalStatus.PASS,
387
+ "The repository is active and accepts pull requests.",
388
+ )
389
+
390
+ @staticmethod
391
+ def _ci_check(result: FetchResult[list[JsonObject]]) -> CheckResult:
392
+ if result.error:
393
+ return _unknown("default_branch_ci", "Default branch CI", result.error)
394
+ runs = result.value or []
395
+ if not runs:
396
+ return _check(
397
+ "default_branch_ci",
398
+ "Default branch CI",
399
+ SignalStatus.INFO,
400
+ "No completed GitHub Actions runs were found on the default branch.",
401
+ )
402
+
403
+ latest_by_workflow: dict[str, JsonObject] = {}
404
+ for run in runs:
405
+ name = _string(run.get("name")) or "Unnamed workflow"
406
+ latest_by_workflow.setdefault(name, run)
407
+ unhealthy = [
408
+ run
409
+ for run in latest_by_workflow.values()
410
+ if run.get("conclusion") not in {"success", "skipped", "neutral"}
411
+ ]
412
+ if unhealthy:
413
+ return _check(
414
+ "default_branch_ci",
415
+ "Default branch CI",
416
+ SignalStatus.WARNING,
417
+ "At least one latest default-branch workflow is not green.",
418
+ [
419
+ Evidence(
420
+ text=f"{run.get('name', 'Workflow')}: {run.get('conclusion', 'unknown')}",
421
+ url=_url(run.get("html_url")),
422
+ )
423
+ for run in unhealthy
424
+ ],
425
+ )
426
+ return _check(
427
+ "default_branch_ci",
428
+ "Default branch CI",
429
+ SignalStatus.PASS,
430
+ f"Latest runs for {len(latest_by_workflow)} workflow(s) are green.",
431
+ )
432
+
433
+ @staticmethod
434
+ def _maintainer_response_check(
435
+ issue: JsonObject, result: FetchResult[list[JsonObject]]
436
+ ) -> CheckResult:
437
+ if result.error:
438
+ return _unknown("maintainer_response", "Maintainer response", result.error)
439
+ created_at = _datetime(issue.get("created_at"))
440
+ maintainer_comments = [
441
+ comment
442
+ for comment in result.value or []
443
+ if comment.get("author_association") in MAINTAINER_ASSOCIATIONS
444
+ ]
445
+ if maintainer_comments:
446
+ first = min(
447
+ maintainer_comments,
448
+ key=lambda item: (
449
+ _datetime(item.get("created_at")) or datetime.max.replace(tzinfo=UTC)
450
+ ),
451
+ )
452
+ response_at = _datetime(first.get("created_at"))
453
+ response = "A maintainer has replied."
454
+ if created_at and response_at:
455
+ hours = max(0, int((response_at - created_at).total_seconds() // 3600))
456
+ response = f"A maintainer first replied after approximately {hours} hour(s)."
457
+ return _check(
458
+ "maintainer_response",
459
+ "Maintainer response",
460
+ SignalStatus.PASS,
461
+ response,
462
+ [Evidence(text="First maintainer reply", url=_url(first.get("html_url")))],
463
+ )
464
+ age_days = (datetime.now(UTC) - created_at).days if created_at else 0
465
+ status = SignalStatus.WARNING if age_days >= 7 else SignalStatus.INFO
466
+ return _check(
467
+ "maintainer_response",
468
+ "Maintainer response",
469
+ status,
470
+ "No maintainer response was found on this issue."
471
+ if age_days < 7
472
+ else f"No maintainer response was found after {age_days} days.",
473
+ )
474
+
475
+ @staticmethod
476
+ def _overall_status(checks: Iterable[CheckResult]) -> OverallStatus:
477
+ check_list = list(checks)
478
+ if any(
479
+ check.key in HARD_BLOCKER_KEYS and check.status == SignalStatus.FAILURE
480
+ for check in check_list
481
+ ):
482
+ return OverallStatus.BLOCKED
483
+ if any(
484
+ check.status in {SignalStatus.WARNING, SignalStatus.UNKNOWN, SignalStatus.FAILURE}
485
+ for check in check_list
486
+ ):
487
+ return OverallStatus.CAUTION
488
+ return OverallStatus.READY
489
+
490
+ @staticmethod
491
+ def _next_actions(checks: list[CheckResult], status: OverallStatus) -> list[str]:
492
+ by_key = {check.key: check for check in checks}
493
+ actions: list[str] = []
494
+ if by_key["dependencies"].status == SignalStatus.FAILURE:
495
+ actions.append("Wait for the listed dependency issues to close.")
496
+ if by_key["base_branch"].status == SignalStatus.FAILURE:
497
+ actions.append("Ask the maintainer to create or clarify the required base branch.")
498
+ if by_key["assignment"].status == SignalStatus.FAILURE:
499
+ actions.append("Coordinate with the current assignee before writing code.")
500
+ if by_key["claims"].status == SignalStatus.WARNING:
501
+ actions.append("Confirm the comment claim is inactive before starting.")
502
+ if by_key["competing_prs"].status == SignalStatus.WARNING:
503
+ actions.append("Review the linked pull request before proposing duplicate work.")
504
+ if by_key["default_branch_ci"].status == SignalStatus.WARNING:
505
+ actions.append("Separate pre-existing CI failures from failures caused by your change.")
506
+ if by_key["contribution_docs"].status == SignalStatus.PASS:
507
+ actions.append("Read the repository contribution guide before creating a branch.")
508
+ if status == OverallStatus.READY:
509
+ actions.append("Comment with a concise implementation plan before starting work.")
510
+ return actions or ["Review unknown checks manually before starting work."]
511
+
512
+
513
+ def _check(
514
+ key: str,
515
+ title: str,
516
+ status: SignalStatus,
517
+ summary: str,
518
+ evidence: list[Evidence] | None = None,
519
+ ) -> CheckResult:
520
+ return CheckResult(
521
+ key=key,
522
+ title=title,
523
+ status=status,
524
+ summary=summary,
525
+ evidence=evidence or [],
526
+ )
527
+
528
+
529
+ def _unknown(key: str, title: str, error: Exception | None) -> CheckResult:
530
+ detail = str(error) if error else "No diagnostic was returned."
531
+ return _check(
532
+ key,
533
+ title,
534
+ SignalStatus.UNKNOWN,
535
+ f"Could not verify this signal: {detail}",
536
+ )
537
+
538
+
539
+ def _string(value: Any) -> str | None:
540
+ return value if isinstance(value, str) else None
541
+
542
+
543
+ def _url(value: Any) -> HttpUrl | None:
544
+ candidate = _string(value)
545
+ if not candidate or not candidate.startswith(("https://", "http://")):
546
+ return None
547
+ return HttpUrl(candidate)
548
+
549
+
550
+ def _datetime(value: Any) -> datetime | None:
551
+ candidate = _string(value)
552
+ if not candidate:
553
+ return None
554
+ try:
555
+ return datetime.fromisoformat(candidate.replace("Z", "+00:00"))
556
+ except ValueError:
557
+ return None
558
+
559
+
560
+ def _logins(value: Any) -> list[str]:
561
+ if not isinstance(value, list):
562
+ return []
563
+ return [
564
+ login
565
+ for item in value
566
+ if isinstance(item, dict) and (login := _string(item.get("login"))) is not None
567
+ ]
568
+
569
+
570
+ def _nested_object(value: JsonObject, *keys: str) -> JsonObject | None:
571
+ current: Any = value
572
+ for key in keys:
573
+ if not isinstance(current, dict):
574
+ return None
575
+ current = current.get(key)
576
+ return cast(JsonObject, current) if isinstance(current, dict) else None
577
+
578
+
579
+ def _nested_string(value: JsonObject, *keys: str) -> str | None:
580
+ current: Any = value
581
+ for key in keys:
582
+ if not isinstance(current, dict):
583
+ return None
584
+ current = current.get(key)
585
+ return _string(current)