| 1 | """GitHub Issues/PRs search via the public GitHub Search API. |
| 2 | |
| 3 | Uses api.github.com/search/issues for issue/PR discovery and per-item comment |
| 4 | enrichment. Search and repository metadata can use GITHUB_TOKEN or |
| 5 | `gh auth token` for higher limits. Comments, READMEs, and releases use the |
| 6 | anonymous REST tier because those responses do not certify repository visibility. |
| 7 | """ |
| 8 | |
| 9 | import json |
| 10 | import math |
| 11 | import os |
| 12 | import re |
| 13 | import subprocess |
| 14 | import sys |
| 15 | import time |
| 16 | import urllib.error |
| 17 | import urllib.parse |
| 18 | import urllib.request |
| 19 | from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, as_completed, wait as futures_wait |
| 20 | from datetime import datetime, timezone |
| 21 | from http.client import HTTPException |
| 22 | from typing import Any, Callable, Dict, List, Optional |
| 23 | |
| 24 | from . import dates, env, http, log, schema |
| 25 | from .query import extract_core_subject |
| 26 | from .relevance import token_overlap_relevance |
| 27 | |
| 28 | SEARCH_URL = "https://api.github.com/search/issues" |
| 29 | _REPO_SLUG = re.compile(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+") |
| 30 | |
| 31 | DEPTH_LIMITS = { |
| 32 | "quick": 15, |
| 33 | "default": 30, |
| 34 | "deep": 60, |
| 35 | } |
| 36 | |
| 37 | ENRICH_LIMITS = { |
| 38 | "quick": 3, |
| 39 | "default": 5, |
| 40 | "deep": 8, |
| 41 | } |
| 42 | |
| 43 | # Unauthenticated GitHub search allows ~10 requests/min, so cap result volume |
| 44 | # conservatively when running without a token to stay within the anon tier. |
| 45 | UNAUTH_COUNT_CAP = 10 |
| 46 | |
| 47 | USER_AGENT = "last30days/3.0 (research tool)" |
| 48 | |
| 49 | |
| 50 | def _log(msg: str): |
| 51 | log.source_log("GitHub", msg, tty_only=False) |
| 52 | |
| 53 | |
| 54 | def _resolve_token(token: Optional[str] = None) -> Optional[str]: |
| 55 | """Resolve GitHub auth token from argument, env, or gh CLI.""" |
| 56 | if token: |
| 57 | return token |
| 58 | env_token = env.read_secret_env("GITHUB_TOKEN") |
| 59 | if env_token: |
| 60 | return env_token |
| 61 | # Fallback: try gh CLI |
| 62 | try: |
| 63 | result = subprocess.run( |
| 64 | ["gh", "auth", "token"], |
| 65 | capture_output=True, text=True, timeout=5, |
| 66 | ) |
| 67 | if result.returncode == 0 and result.stdout.strip(): |
| 68 | return result.stdout.strip() |
| 69 | except (FileNotFoundError, subprocess.TimeoutExpired, OSError): |
| 70 | pass |
| 71 | return None |
| 72 | |
| 73 | |
| 74 | def resolve_token(token: Optional[str] = None) -> Optional[str]: |
| 75 | """Public alias for ``_resolve_token``. |
| 76 | |
| 77 | The pipeline uses this to select the authenticated search tier. |
| 78 | """ |
| 79 | return _resolve_token(token) |
| 80 | |
| 81 | |
| 82 | def _fetch_json( |
| 83 | url: str, |
| 84 | token: Optional[str] = None, |
| 85 | timeout: float = 15, |
| 86 | failure_out: Optional[List[str]] = None, |
| 87 | ) -> Optional[Dict[str, Any]]: |
| 88 | """Fetch JSON from GitHub API. Returns None on failure. |
| 89 | |
| 90 | When ``failure_out`` is provided, a short human-readable reason is |
| 91 | appended for every failure branch so callers can distinguish transport |
| 92 | failures from genuinely empty results (issue #384). |
| 93 | """ |
| 94 | |
| 95 | def _note(msg: str) -> None: |
| 96 | if failure_out is not None: |
| 97 | failure_out.append(msg) |
| 98 | headers = { |
| 99 | "User-Agent": USER_AGENT, |
| 100 | "Accept": "application/vnd.github+json", |
| 101 | } |
| 102 | if token: |
| 103 | headers["Authorization"] = f"Bearer {token}" |
| 104 | |
| 105 | req = urllib.request.Request(url, headers=headers) |
| 106 | try: |
| 107 | with http.open_request(req, timeout) as resp: |
| 108 | body = resp.read().decode("utf-8") |
| 109 | return json.loads(body) |
| 110 | except urllib.error.HTTPError as e: |
| 111 | if e.code == 403: |
| 112 | _log(f"403 rate limited or forbidden: {url}") |
| 113 | _note("HTTP 403: rate limited or forbidden") |
| 114 | return None |
| 115 | if e.code == 422: |
| 116 | _log(f"422 unprocessable: {url}") |
| 117 | _note("HTTP 422: unprocessable query") |
| 118 | return None |
| 119 | _log(f"HTTP {e.code}: {e.reason}") |
| 120 | _note(f"HTTP {e.code}: {e.reason}") |
| 121 | return None |
| 122 | except (urllib.error.URLError, OSError, TimeoutError, HTTPException) as e: |
| 123 | _log(f"Network error: {e}") |
| 124 | _note(f"network error: {e}") |
| 125 | return None |
| 126 | except (json.JSONDecodeError, UnicodeDecodeError) as e: |
| 127 | _log(f"JSON decode error: {e}") |
| 128 | _note(f"invalid JSON: {e}") |
| 129 | return None |
| 130 | |
| 131 | |
| 132 | def _parse_repo_from_url(html_url: str) -> str: |
| 133 | """Extract 'owner/repo' from a GitHub issue/PR URL.""" |
| 134 | parts = html_url.replace("https://github.com/", "").split("/") |
| 135 | if len(parts) >= 2: |
| 136 | return f"{parts[0]}/{parts[1]}" |
| 137 | return "" |
| 138 | |
| 139 | |
| 140 | def _parse_date(iso_str: Optional[str]) -> Optional[str]: |
| 141 | """Parse a GitHub ISO 8601 datetime string and return YYYY-MM-DD. |
| 142 | |
| 143 | Returns None for non-date input. GitHub's API always emits ISO 8601 |
| 144 | (e.g. "2026-02-26T16:00:00Z"), but we defer to dates.parse_date() so |
| 145 | garbage input gets rejected instead of silently sliced. |
| 146 | """ |
| 147 | dt = dates.parse_date(iso_str) |
| 148 | return dt.strftime("%Y-%m-%d") if dt else None |
| 149 | |
| 150 | |
| 151 | def _compute_relevance( |
| 152 | query: str, |
| 153 | title: str, |
| 154 | rank_index: int, |
| 155 | reactions: int, |
| 156 | comments: int, |
| 157 | ) -> float: |
| 158 | """Blend text relevance with engagement signals.""" |
| 159 | rank_score = max(0.3, 1.0 - (rank_index * 0.02)) |
| 160 | engagement_boost = min(0.2, math.log1p(reactions + comments) / 20) |
| 161 | |
| 162 | if query: |
| 163 | content_score = token_overlap_relevance(query, title) |
| 164 | relevance = min(1.0, 0.6 * rank_score + 0.4 * content_score + engagement_boost) |
| 165 | else: |
| 166 | relevance = min(1.0, rank_score * 0.7 + engagement_boost + 0.1) |
| 167 | |
| 168 | return round(relevance, 2) |
| 169 | |
| 170 | |
| 171 | # Issue search matches body text, so an off-topic query still returns a full |
| 172 | # page: keyword-stuffed spam issues and passing mentions in unrelated repos. |
| 173 | # Their search rank is as good as a real hit's, so the blended score above |
| 174 | # cannot separate them. A keyword result is kept only when its title names the |
| 175 | # topic or its repo is named for it. 0.25 sits just above the 0.24 cap that |
| 176 | # token_overlap_relevance gives a match on generic words alone. |
| 177 | TOPICAL_FLOOR = 0.25 |
| 178 | |
| 179 | |
| 180 | def _clears_topical_floor(topic: str, title: str, repo: str) -> bool: |
| 181 | """True when a keyword-search result is about ``topic``. |
| 182 | |
| 183 | Rank and engagement play no part. Person and project modes never call this. |
| 184 | """ |
| 185 | repo_words = re.sub(r"[/_.\-]+", " ", repo) |
| 186 | return max( |
| 187 | token_overlap_relevance(topic, title), |
| 188 | token_overlap_relevance(topic, repo_words), |
| 189 | ) >= TOPICAL_FLOOR |
| 190 | |
| 191 | |
| 192 | # GitHub search qualifiers the planner sometimes writes straight into the topic |
| 193 | # string (e.g. "open source AI stars:>1000 created:>2025-03-20"). They must not |
| 194 | # reach the query builder in `search_github`: it appends its own |
| 195 | # `created:{from_date}..{to_date}`, and when two `created:` qualifiers collide GitHub |
| 196 | # honours the FIRST and silently ignores ours. The API then returns |
| 197 | # out-of-window items that `parse_github_response`'s date filter drops |
| 198 | # wholesale — a source that fetches results and reports zero (issue #949). |
| 199 | # Qualifiers may also arrive fully wrapped in one pair of parens/brackets/ |
| 200 | # quotes ("(created:>2025-03-20)", '"stars:>1000"'), which an LLM planner |
| 201 | # plausibly emits; _WRAPPED_QUALIFIER_RE consumes the whole wrapper pair with |
| 202 | # the qualifier so no stray `()`/`""` residue reaches the query (issue #952). |
| 203 | # The plain regex's boundary also accepts wrapper openers so a qualifier with |
| 204 | # a missing closer ("(created:>2025-03-20") is still stripped rather than |
| 205 | # leaking into the query; qualifier-only wrapper residue is discarded below. |
| 206 | QUALIFIER_KEYS = frozenset({ |
| 207 | "answered", "archived", "assignee", "author", "base", "category", "closed", |
| 208 | "comments", "commenter", "created", "draft", "fork", "forks", "head", "in", |
| 209 | "interactions", "involves", "is", "label", "language", "license", "linked", |
| 210 | "mentions", "merged", "milestone", "no", "org", "owner", "parent-issue", |
| 211 | "project", "pushed", "reactions", "reason", "repo", "review", |
| 212 | "review-requested", "reviewed-by", "sha", "size", "sort", "stars", "state", |
| 213 | "status", "sub-issue", "team", "topic", "topics", "type", "updated", "user", |
| 214 | "visibility", |
| 215 | }) |
| 216 | |
| 217 | _QUALIFIER_KEYS_ALT = "|".join(sorted(QUALIFIER_KEYS, key=lambda k: (-len(k), k))) |
| 218 | |
| 219 | _QUALIFIER_RE = re.compile( |
| 220 | r"(?:(?<=[\s,;(\)\[\]\"'])|^)[-+]*?(?:" |
| 221 | + _QUALIFIER_KEYS_ALT |
| 222 | + r"):(?:[<>]=?)?(?:\([^)]*\)|\"[^\"]*\"|\([^\s,;()\[\]]+|[^\s,;()\[\]]+)[,;]?", |
| 223 | re.IGNORECASE, |
| 224 | ) |
| 225 | |
| 226 | # A qualifier fully wrapped in a single pair of parens/brackets/quotes. The |
| 227 | # wrapper pair is consumed with the qualifier, so stripping leaves no residue. |
| 228 | # Optional leading +/- negation before the wrapper (e.g. `-(is:public)`, |
| 229 | # `-"is:public"`) is consumed when bounded by whitespace/punctuation. |
| 230 | # An unbalanced quote (e.g. `label:"bug`) is not a wrapper shape and is left |
| 231 | # to _QUALIFIER_RE, which strips the qualifier as before. |
| 232 | _WRAPPED_QUALIFIER_RE = re.compile( |
| 233 | r"(?:(?:(?<=[\s,;(\)\[\]\"'])|^)[-+]+)?[\(\[\"'][-+]*(?:" |
| 234 | + _QUALIFIER_KEYS_ALT |
| 235 | + r"):(?:[<>]=?)?(?:\([^)]*\)|\"[^\"]*\"|[^\s,;()\[\]\"']+)[\)\]\"']", |
| 236 | re.IGNORECASE, |
| 237 | ) |
| 238 | |
| 239 | _ESCAPED_QUOTE_RE = re.compile(r'(?<!\\)\\+(?=")') |
| 240 | _BRACKET_OPEN_FOR_CLOSE = {")": "(", "]": "["} |
| 241 | |
| 242 | |
| 243 | def _collapse_empty_wrappers(text: str) -> str: |
| 244 | """Collapse nested empty (), [], "", '' pairs (ignoring inner whitespace) in O(N).""" |
| 245 | out: list[str] = [] |
| 246 | non_ws_indices: list[int] = [] |
| 247 | in_dquote = False |
| 248 | in_squote = False |
| 249 | for ch in text: |
| 250 | bracket_opener = _BRACKET_OPEN_FOR_CLOSE.get(ch) |
| 251 | if bracket_opener is not None: |
| 252 | if non_ws_indices and out[non_ws_indices[-1]] == bracket_opener: |
| 253 | open_idx = non_ws_indices.pop() |
| 254 | del out[open_idx:] |
| 255 | continue |
| 256 | elif ch == '"': |
| 257 | if in_dquote: |
| 258 | in_dquote = False |
| 259 | if non_ws_indices and out[non_ws_indices[-1]] == '"': |
| 260 | open_idx = non_ws_indices.pop() |
| 261 | del out[open_idx:] |
| 262 | continue |
| 263 | else: |
| 264 | in_dquote = True |
| 265 | elif ch == "'": |
| 266 | if in_squote: |
| 267 | in_squote = False |
| 268 | if non_ws_indices and out[non_ws_indices[-1]] == "'": |
| 269 | open_idx = non_ws_indices.pop() |
| 270 | del out[open_idx:] |
| 271 | continue |
| 272 | else: |
| 273 | in_squote = True |
| 274 | if not ch.isspace(): |
| 275 | non_ws_indices.append(len(out)) |
| 276 | out.append(ch) |
| 277 | return "".join(out) |
| 278 | |
| 279 | |
| 280 | def strip_search_qualifiers(text: str) -> str: |
| 281 | """Strip GitHub search qualifiers from a topic, leaving plain-language text. |
| 282 | |
| 283 | Whitespace is collapsed. Returns an empty string when the topic was nothing |
| 284 | but qualifiers; callers must handle that rather than searching on an empty |
| 285 | term, which would match the entire site. |
| 286 | """ |
| 287 | stripped = _ESCAPED_QUOTE_RE.sub("", text) |
| 288 | had_qualifier = False |
| 289 | |
| 290 | def _strip_to_fixpoint(value: str) -> tuple[str, bool]: |
| 291 | changed_qualifier = False |
| 292 | cur = _collapse_empty_wrappers(value) |
| 293 | while True: |
| 294 | after_wrap = _WRAPPED_QUALIFIER_RE.sub(" ", cur) |
| 295 | after_plain = _QUALIFIER_RE.sub(" ", after_wrap) |
| 296 | if after_plain != cur: |
| 297 | changed_qualifier = True |
| 298 | cleaned = _collapse_empty_wrappers(after_plain) |
| 299 | if cleaned == cur: |
| 300 | return cur, changed_qualifier |
| 301 | cur = cleaned |
| 302 | |
| 303 | stripped, found = _strip_to_fixpoint(stripped) |
| 304 | had_qualifier = had_qualifier or found |
| 305 | |
| 306 | # Drop an unmatched trailing double quote so an unclosed phrase in `core` |
| 307 | # cannot swallow engine-added qualifiers (`created:...`, `is:issue`). |
| 308 | if stripped.count('"') % 2 == 1: |
| 309 | idx = stripped.rfind('"') |
| 310 | stripped = stripped[:idx] + stripped[idx + 1:] |
| 311 | stripped, found = _strip_to_fixpoint(stripped) |
| 312 | had_qualifier = had_qualifier or found |
| 313 | |
| 314 | # Malformed/nested wrappers can leave only punctuation after a qualifier |
| 315 | # is removed (#969). There is no subject to search in that case. Keep |
| 316 | # wrappers around actual topic text, including unbalanced ones like "ai (foo". |
| 317 | if had_qualifier and re.fullmatch(r"[\s()\[\]\"'-]*", stripped): |
| 318 | return "" |
| 319 | return " ".join(stripped.split()) |
| 320 | |
| 321 | |
| 322 | # Bound topic fragments in logs/error envelopes so fanout cannot blow them up (#954). |
| 323 | _DIAGNOSTIC_TOPIC_LIMIT = 120 |
| 324 | |
| 325 | |
| 326 | def _truncate_diagnostic(text: str, limit: int = _DIAGNOSTIC_TOPIC_LIMIT) -> str: |
| 327 | """Cap a topic fragment used in logs or error envelopes.""" |
| 328 | if len(text) <= limit: |
| 329 | return text |
| 330 | return f"{text[:limit]}..." |
| 331 | |
| 332 | |
| 333 | def search_github( |
| 334 | topic: str, |
| 335 | from_date: str, |
| 336 | to_date: str, |
| 337 | depth: str = "default", |
| 338 | token: Optional[str] = None, |
| 339 | *, |
| 340 | title_only: bool = True, |
| 341 | deadline: Optional[float] = None, |
| 342 | stopped: Optional[Callable[[], bool]] = None, |
| 343 | ) -> Dict[str, Any]: |
| 344 | """Search GitHub Issues and PRs (HTTP fetch only). |
| 345 | |
| 346 | Returns a raw envelope shaped like every other adapter's ``search_X``: |
| 347 | ``{"items": [raw GitHub API items], "context": {core, from_date, |
| 348 | to_date, count}}``. Normalization, date filtering, and sorting move |
| 349 | to ``parse_github_response``; comment enrichment moves to |
| 350 | ``enrich_with_comments``. |
| 351 | |
| 352 | Args: |
| 353 | topic: Search topic |
| 354 | from_date: Start date (YYYY-MM-DD) |
| 355 | to_date: End date (YYYY-MM-DD) |
| 356 | depth: 'quick', 'default', or 'deep' |
| 357 | token: Optional GitHub token (falls back to env/gh CLI) |
| 358 | |
| 359 | Returns: |
| 360 | Dict envelope. Empty ``items`` list on any failure. |
| 361 | """ |
| 362 | count = DEPTH_LIMITS.get(depth, DEPTH_LIMITS["default"]) |
| 363 | core = extract_core_subject(topic) |
| 364 | plain_core = strip_search_qualifiers(core) |
| 365 | if not plain_core: |
| 366 | # A qualifier-only (or empty) topic leaves nothing to search on. |
| 367 | # Skip the network rather than querying an empty term, which would |
| 368 | # match the whole site (#949). Return a clean empty envelope, not an |
| 369 | # error, so the pipeline records NO_RESULTS instead of ERROR (#953) |
| 370 | # and GitHub is not marked as a failed attempt. Mixed-topic strip |
| 371 | # logs below stay bounded by _truncate_diagnostic (#954). |
| 372 | _log("Topic contained only search qualifiers or was empty; nothing to search") |
| 373 | return { |
| 374 | "items": [], |
| 375 | "context": {"core": core, "from_date": from_date, |
| 376 | "to_date": to_date, "count": count}, |
| 377 | } |
| 378 | if plain_core != core: |
| 379 | _log( |
| 380 | "Stripped search qualifiers: " |
| 381 | f"'{_truncate_diagnostic(core)}' -> '{_truncate_diagnostic(plain_core)}'" |
| 382 | ) |
| 383 | core = plain_core |
| 384 | resolved_token = _resolve_token(token) |
| 385 | authed = bool(resolved_token) |
| 386 | if not authed: |
| 387 | # Fall back to the unauthenticated REST tier instead of returning nothing. |
| 388 | # It is rate-limited, so cap the request volume. |
| 389 | count = min(count, UNAUTH_COUNT_CAP) |
| 390 | _log("No GitHub token; using the unauthenticated REST tier (low rate limit)") |
| 391 | _log(f"Searching for '{core}' (raw: '{topic}', since {from_date}, count={count})") |
| 392 | |
| 393 | # Only results whose title names the topic survive the topical floor, so |
| 394 | # search titles first: a body search fills the page with popular issues that |
| 395 | # merely mention the topic, and the floor then drops all of them. Callers |
| 396 | # pass title_only=False as a fallback when planner-expanded queries yield |
| 397 | # no title matches. |
| 398 | base_q = f"is:public {core} created:{from_date}..{to_date}" |
| 399 | if title_only: |
| 400 | base_q += " in:title" |
| 401 | |
| 402 | def _search(qualifier: Optional[str]) -> Optional[Dict[str, Any]]: |
| 403 | if stopped is not None and stopped(): |
| 404 | fetch_failures.append("cancelled") |
| 405 | return None |
| 406 | req_timeout: float = 30.0 |
| 407 | if deadline is not None: |
| 408 | remaining = deadline - time.monotonic() |
| 409 | if remaining <= 0: |
| 410 | fetch_failures.append("deadline exceeded") |
| 411 | return None |
| 412 | req_timeout = min(req_timeout, remaining) |
| 413 | q = f"{base_q} {qualifier}" if qualifier else base_q |
| 414 | params = { |
| 415 | "q": q, |
| 416 | "sort": "reactions", |
| 417 | "order": "desc", |
| 418 | "per_page": str(min(count, 100)), |
| 419 | } |
| 420 | url = f"{SEARCH_URL}?{urllib.parse.urlencode(params)}" |
| 421 | return _fetch_json(url, token=resolved_token, timeout=req_timeout, |
| 422 | failure_out=fetch_failures) |
| 423 | |
| 424 | fetch_failures: List[str] = [] |
| 425 | partition_failure: Optional[str] = None |
| 426 | if authed: |
| 427 | # GitHub rejects AUTHENTICATED /search/issues queries that carry |
| 428 | # neither `is:issue` nor `is:pull-request` (HTTP 422). Anonymous |
| 429 | # queries are still grandfathered, which is why this only bites once |
| 430 | # a token is present -- including via the `gh auth token` fallback. |
| 431 | # |
| 432 | # Appending a single qualifier would silently halve the corpus: for |
| 433 | # "rust async created:>2026-08-02" GitHub reports 1,072 issues and |
| 434 | # 7,044 pull requests against 8,115 combined, so `is:issue` alone |
| 435 | # drops ~87% of matches. Query both and merge instead, which keeps |
| 436 | # coverage AND the authenticated rate limit. |
| 437 | merged: List[Dict[str, Any]] = [] |
| 438 | seen_ids = set() |
| 439 | failed_qualifiers: List[str] = [] |
| 440 | for qualifier in ("is:issue", "is:pull-request"): |
| 441 | if stopped is not None and stopped(): |
| 442 | fetch_failures.append("cancelled") |
| 443 | failed_qualifiers.append(qualifier) |
| 444 | break |
| 445 | if deadline is not None and time.monotonic() >= deadline: |
| 446 | fetch_failures.append("deadline exceeded") |
| 447 | failed_qualifiers.append(qualifier) |
| 448 | break |
| 449 | part = _search(qualifier) |
| 450 | if part is None: |
| 451 | failed_qualifiers.append(qualifier) |
| 452 | continue |
| 453 | for item in part.get("items", []): |
| 454 | item_id = item.get("id") |
| 455 | if item_id in seen_ids: |
| 456 | continue |
| 457 | seen_ids.add(item_id) |
| 458 | merged.append(item) |
| 459 | # Both sub-queries are reaction-sorted; the merge is not, so re-sort |
| 460 | # before truncating or the second query's tail would outrank the |
| 461 | # first query's head. |
| 462 | merged.sort(key=lambda i: (i.get("reactions") or {}).get("total_count", 0), |
| 463 | reverse=True) |
| 464 | data = {"items": merged[:count]} if merged else None |
| 465 | if failed_qualifiers: |
| 466 | partition_failure = ( |
| 467 | f"GitHub partition(s) failed: {', '.join(failed_qualifiers)}" |
| 468 | + (f" ({fetch_failures[-1]})" if fetch_failures else "") |
| 469 | ) |
| 470 | else: |
| 471 | data = _search(None) |
| 472 | stop_reason = ( |
| 473 | fetch_failures[-1] |
| 474 | if fetch_failures and fetch_failures[-1] in {"cancelled", "deadline exceeded"} |
| 475 | else None |
| 476 | ) |
| 477 | if not data: |
| 478 | envelope = {"items": [], "context": {"core": core, "from_date": from_date, |
| 479 | "to_date": to_date, "count": count}} |
| 480 | if stop_reason is not None: |
| 481 | envelope["stopped_reason"] = stop_reason |
| 482 | envelope["error"] = f"GitHub search timed out ({stop_reason})" |
| 483 | elif authed and partition_failure: |
| 484 | envelope["error"] = partition_failure |
| 485 | elif authed and fetch_failures: |
| 486 | # Authenticated transport failures must not be laundered into a |
| 487 | # clean no-results outcome (issue #384). |
| 488 | envelope["error"] = f"GitHub API request failed: {fetch_failures[-1]}" |
| 489 | elif not authed: |
| 490 | # Could be the anon rate limit (403) or an unprocessable query (422) |
| 491 | # -- _fetch_json maps both to None. Don't over-claim which; suggest a |
| 492 | # token since that fixes the common (rate-limit) case. |
| 493 | envelope["error"] = ( |
| 494 | "GitHub unauthenticated request returned no data (anon rate limit " |
| 495 | "or unprocessable query; set GITHUB_TOKEN or run gh auth login)" |
| 496 | ) |
| 497 | return envelope |
| 498 | |
| 499 | raw_items = data.get("items", []) |
| 500 | _log(f"Found {len(raw_items)} issues/PRs") |
| 501 | |
| 502 | envelope: Dict[str, Any] = { |
| 503 | "items": raw_items, |
| 504 | "context": { |
| 505 | "core": core, |
| 506 | "from_date": from_date, |
| 507 | "to_date": to_date, |
| 508 | "count": count, |
| 509 | }, |
| 510 | } |
| 511 | if stop_reason is not None: |
| 512 | envelope["stopped_reason"] = stop_reason |
| 513 | if partition_failure: |
| 514 | envelope["error"] = partition_failure |
| 515 | return envelope |
| 516 | |
| 517 | |
| 518 | def parse_github_response( |
| 519 | response: Dict[str, Any], |
| 520 | topic: Optional[str] = None, |
| 521 | ) -> List[Dict[str, Any]]: |
| 522 | """Normalize a ``search_github`` envelope into the skill's item shape. |
| 523 | |
| 524 | Pure function: no I/O, no token, no enrichment. Drops results that are |
| 525 | not about the topic, applies the date filter using the search context and |
| 526 | sorts by relevance. |
| 527 | |
| 528 | ``topic`` is the research topic the results are judged against. It |
| 529 | defaults to the subject the search ran on. |
| 530 | """ |
| 531 | if not isinstance(response, dict): |
| 532 | return [] |
| 533 | raw_items = response.get("items") or [] |
| 534 | if not isinstance(raw_items, list): |
| 535 | return [] |
| 536 | context = response.get("context") or {} |
| 537 | core = context.get("core") or "" |
| 538 | from_date = context.get("from_date") or "" |
| 539 | to_date = context.get("to_date") or "" |
| 540 | count = context.get("count") or DEPTH_LIMITS["default"] |
| 541 | floor_topic = strip_search_qualifiers(extract_core_subject(topic or "")) or core |
| 542 | |
| 543 | items: List[Dict[str, Any]] = [] |
| 544 | off_topic = 0 |
| 545 | for i, item in enumerate(raw_items[:count]): |
| 546 | html_url = item.get("html_url", "") |
| 547 | repo = _parse_repo_from_url(html_url) |
| 548 | title = item.get("title", "") |
| 549 | if not _clears_topical_floor(floor_topic, title, repo): |
| 550 | off_topic += 1 |
| 551 | continue |
| 552 | body_text = item.get("body") or "" |
| 553 | reactions_total = item.get("reactions", {}).get("total_count", 0) if isinstance(item.get("reactions"), dict) else 0 |
| 554 | comment_count = item.get("comments") or 0 |
| 555 | labels = [ |
| 556 | lbl.get("name", "") for lbl in (item.get("labels") or []) |
| 557 | if isinstance(lbl, dict) |
| 558 | ] |
| 559 | state = item.get("state", "") |
| 560 | is_pr = "pull_request" in item |
| 561 | author = item.get("user", {}).get("login", "") if isinstance(item.get("user"), dict) else "" |
| 562 | |
| 563 | relevance = _compute_relevance(core, title, i, reactions_total, comment_count) |
| 564 | |
| 565 | items.append({ |
| 566 | "id": f"GH{i + 1}", |
| 567 | "title": title, |
| 568 | "url": html_url, |
| 569 | "date": _parse_date(item.get("created_at")), |
| 570 | "author": author, |
| 571 | "source": "github", |
| 572 | "score": reactions_total, |
| 573 | "container": repo, |
| 574 | "snippet": body_text[:300] if body_text else "", |
| 575 | "relevance": relevance, |
| 576 | "why_relevant": f"GitHub {'PR' if is_pr else 'issue'}: {title[:60]}", |
| 577 | "engagement": { |
| 578 | "reactions": reactions_total, |
| 579 | "comments": comment_count, |
| 580 | }, |
| 581 | "metadata": { |
| 582 | "labels": labels, |
| 583 | "state": state, |
| 584 | "comment_count": comment_count, |
| 585 | "reactions": reactions_total, |
| 586 | "is_pr": is_pr, |
| 587 | }, |
| 588 | }) |
| 589 | |
| 590 | if off_topic: |
| 591 | _log( |
| 592 | f"Dropped {off_topic} of {off_topic + len(items)} results not about " |
| 593 | f"'{_truncate_diagnostic(floor_topic)}'" |
| 594 | ) |
| 595 | |
| 596 | # Date filter |
| 597 | if from_date and to_date: |
| 598 | items = [ |
| 599 | item for item in items |
| 600 | if item.get("date") is None or (from_date <= item["date"] <= to_date) |
| 601 | ] |
| 602 | |
| 603 | items.sort(key=lambda x: x.get("relevance", 0), reverse=True) |
| 604 | return items |
| 605 | |
| 606 | |
| 607 | def enrich_with_comments( |
| 608 | items: List[Dict[str, Any]], |
| 609 | depth: str = "default", |
| 610 | *, |
| 611 | deadline: Optional[float] = None, |
| 612 | stopped: Optional[Callable[[], bool]] = None, |
| 613 | to_date: Optional[str] = None, |
| 614 | ) -> List[Dict[str, Any]]: |
| 615 | """Fetch public comments for top items by reactions and attach to metadata.""" |
| 616 | if not items: |
| 617 | return items |
| 618 | if stopped is not None and stopped(): |
| 619 | return items |
| 620 | req_timeout = 15.0 |
| 621 | if deadline is not None: |
| 622 | remaining = deadline - time.monotonic() |
| 623 | if remaining <= 0: |
| 624 | return items |
| 625 | req_timeout = min(req_timeout, remaining) |
| 626 | |
| 627 | limit = ENRICH_LIMITS.get(depth, ENRICH_LIMITS["default"]) |
| 628 | |
| 629 | by_reactions = sorted( |
| 630 | range(len(items)), |
| 631 | key=lambda i: items[i].get("score", 0), |
| 632 | reverse=True, |
| 633 | ) |
| 634 | to_enrich = by_reactions[:limit] |
| 635 | as_of = _historical_cutoff(to_date) if to_date else None |
| 636 | |
| 637 | _log(f"Enriching top {len(to_enrich)} items with comments") |
| 638 | |
| 639 | executor = ThreadPoolExecutor(max_workers=5) |
| 640 | try: |
| 641 | futures = { |
| 642 | executor.submit( |
| 643 | _fetch_item_comments, |
| 644 | items[idx]["url"], |
| 645 | timeout=req_timeout, |
| 646 | as_of=as_of, |
| 647 | ): idx |
| 648 | for idx in to_enrich |
| 649 | } |
| 650 | |
| 651 | if deadline is None and stopped is None: |
| 652 | for future in as_completed(futures): |
| 653 | idx = futures[future] |
| 654 | try: |
| 655 | comments = future.result(timeout=15) |
| 656 | items[idx]["metadata"]["top_comments"] = comments |
| 657 | except (KeyError, TypeError, OSError) as exc: |
| 658 | _log(f"Comment enrichment failed for {items[idx].get('url', '?')}: {type(exc).__name__}: {exc}") |
| 659 | items[idx]["metadata"]["top_comments"] = [] |
| 660 | else: |
| 661 | pending = set(futures) |
| 662 | while pending: |
| 663 | if stopped is not None and stopped(): |
| 664 | break |
| 665 | if deadline is not None: |
| 666 | left = deadline - time.monotonic() |
| 667 | if left <= 0: |
| 668 | break |
| 669 | step = min(0.1, left) |
| 670 | else: |
| 671 | step = 0.1 |
| 672 | done, pending = futures_wait(pending, timeout=step, return_when=FIRST_COMPLETED) |
| 673 | for future in done: |
| 674 | idx = futures[future] |
| 675 | try: |
| 676 | comments = future.result(timeout=0) |
| 677 | items[idx]["metadata"]["top_comments"] = comments |
| 678 | except (KeyError, TypeError, OSError) as exc: |
| 679 | _log(f"Comment enrichment failed for {items[idx].get('url', '?')}: {type(exc).__name__}: {exc}") |
| 680 | items[idx]["metadata"]["top_comments"] = [] |
| 681 | for future in pending: |
| 682 | future.cancel() |
| 683 | finally: |
| 684 | executor.shutdown(wait=(deadline is None and stopped is None), cancel_futures=True) |
| 685 | |
| 686 | return items |
| 687 | |
| 688 | |
| 689 | def _fetch_item_comments( |
| 690 | issue_url: str, |
| 691 | max_comments: int = 5, |
| 692 | timeout: float = 15, |
| 693 | *, |
| 694 | as_of: Optional[str] = None, |
| 695 | ) -> List[Dict[str, Any]]: |
| 696 | """Fetch comments for a GitHub issue/PR. |
| 697 | |
| 698 | Args: |
| 699 | issue_url: HTML URL like https://github.com/owner/repo/issues/123 |
| 700 | max_comments: Max comments to return |
| 701 | timeout: Request timeout in seconds |
| 702 | |
| 703 | Returns: |
| 704 | List of comment dicts with score, excerpt, author. |
| 705 | """ |
| 706 | if max_comments <= 0: |
| 707 | return [] |
| 708 | |
| 709 | path = issue_url.replace("https://github.com/", "") |
| 710 | path = path.replace("/pull/", "/issues/") |
| 711 | # GitHub's per-issue comments endpoint orders by ascending ID and does not |
| 712 | # support reaction sorting, so fetch its largest page and rank locally. |
| 713 | api_url = f"https://api.github.com/repos/{path}/comments?per_page=100" |
| 714 | |
| 715 | data = _fetch_json(api_url, timeout=timeout) |
| 716 | if not data or not isinstance(data, list): |
| 717 | return [] |
| 718 | |
| 719 | comments = [] |
| 720 | for c in data: |
| 721 | if not isinstance(c, dict): |
| 722 | continue |
| 723 | user = c.get("user") |
| 724 | if _is_bot_user(user): |
| 725 | continue |
| 726 | created = _parse_date(c.get("created_at")) |
| 727 | if as_of: |
| 728 | if not created or created > as_of: |
| 729 | continue |
| 730 | # The REST endpoint returns only the current revision of a comment. |
| 731 | if c.get("updated_at"): |
| 732 | updated = _parse_date(c["updated_at"]) |
| 733 | if not updated or updated > as_of: |
| 734 | continue |
| 735 | body = c.get("body") or "" |
| 736 | excerpt = body[:300] + "..." if len(body) > 300 else body |
| 737 | reactions = c.get("reactions", {}) |
| 738 | reaction_count = reactions.get("total_count", 0) if isinstance(reactions, dict) else 0 |
| 739 | author = user.get("login", "") if isinstance(user, dict) else "" |
| 740 | |
| 741 | comment = { |
| 742 | "score": reaction_count, |
| 743 | "excerpt": excerpt, |
| 744 | "author": author, |
| 745 | } |
| 746 | if created: |
| 747 | comment["date"] = created |
| 748 | if c.get("html_url"): |
| 749 | comment["url"] = c["html_url"] |
| 750 | comments.append(comment) |
| 751 | |
| 752 | # Python's sort is stable, preserving API order for reaction-count ties. |
| 753 | comments.sort(key=lambda comment: comment["score"], reverse=True) |
| 754 | return comments[:max_comments] |
| 755 | |
| 756 | |
| 757 | def _is_bot_user(user: Any) -> bool: |
| 758 | """Return whether a GitHub comment author is recognizably automated. |
| 759 | |
| 760 | GitHub's REST payload marks bot accounts with ``user.type == "Bot"``. |
| 761 | Some compatible or partial payloads omit that field but retain the |
| 762 | conventional ``[bot]`` suffix on the login or display name. Missing user |
| 763 | metadata represents an unknown/deleted author, not evidence of automation. |
| 764 | """ |
| 765 | if not isinstance(user, dict): |
| 766 | return False |
| 767 | if str(user.get("type") or "").casefold() == "bot": |
| 768 | return True |
| 769 | return any( |
| 770 | isinstance(user.get(field), str) |
| 771 | and user[field].strip().casefold().endswith("[bot]") |
| 772 | for field in ("login", "name") |
| 773 | ) |
| 774 | |
| 775 | |
| 776 | # --------------------------------------------------------------------------- |
| 777 | # Person-mode search: author-scoped queries, star enrichment, release notes |
| 778 | # --------------------------------------------------------------------------- |
| 779 | |
| 780 | PERSON_DEPTH_LIMITS = { |
| 781 | "quick": {"pr_pages": 1, "own_repos": 3, "external_repos": 5}, |
| 782 | "default": {"pr_pages": 1, "own_repos": 5, "external_repos": 10}, |
| 783 | "deep": {"pr_pages": 2, "own_repos": 5, "external_repos": 15}, |
| 784 | } |
| 785 | |
| 786 | PERSON_EVENTS_PER_PAGE = 100 |
| 787 | |
| 788 | |
| 789 | def _fetch_readme_snippet(repo: str, max_chars: int = 500) -> Optional[str]: |
| 790 | """Fetch README content for a repo, truncated to first ~max_chars.""" |
| 791 | url = f"https://api.github.com/repos/{repo}/readme" |
| 792 | headers = { |
| 793 | "User-Agent": USER_AGENT, |
| 794 | "Accept": "application/vnd.github.raw+json", |
| 795 | } |
| 796 | req = urllib.request.Request(url, headers=headers) |
| 797 | try: |
| 798 | with http.open_request(req, 10) as resp: |
| 799 | raw = resp.read().decode("utf-8", errors="replace") |
| 800 | except (urllib.error.HTTPError, urllib.error.URLError, OSError, TimeoutError): |
| 801 | return None |
| 802 | |
| 803 | if not raw: |
| 804 | return None |
| 805 | # Try to break at a paragraph boundary |
| 806 | if len(raw) <= max_chars: |
| 807 | return raw |
| 808 | cut = raw[:max_chars] |
| 809 | last_double_newline = cut.rfind("\n\n") |
| 810 | if last_double_newline > max_chars // 3: |
| 811 | return cut[:last_double_newline].rstrip() |
| 812 | return cut.rstrip() + "..." |
| 813 | |
| 814 | |
| 815 | def _historical_cutoff(to_date: str) -> Optional[str]: |
| 816 | """Only a window ending before the current UTC day needs historical lookup.""" |
| 817 | return to_date if to_date < dates.get_date_range(0)[1] else None |
| 818 | |
| 819 | |
| 820 | _RELEASE_HISTORY_PAGES = 3 |
| 821 | |
| 822 | |
| 823 | def _fetch_latest_releases( |
| 824 | repo: str, count: int = 3, max_body: int = 300, *, as_of: Optional[str] = None, |
| 825 | failure_out: Optional[List[str]] = None, |
| 826 | ) -> List[Dict[str, str]]: |
| 827 | """Fetch published releases through the cutoff. Live lookups use one small page.""" |
| 828 | page_size = 100 if as_of else count |
| 829 | page_limit = _RELEASE_HISTORY_PAGES if as_of else 1 |
| 830 | cutoff = as_of or dates.get_date_range(0)[1] |
| 831 | releases = [] |
| 832 | for page in range(1, page_limit + 1): |
| 833 | url = f"https://api.github.com/repos/{repo}/releases?per_page={page_size}" |
| 834 | if page > 1: |
| 835 | url += f"&page={page}" |
| 836 | rows = _fetch_json(url, timeout=10, failure_out=failure_out) |
| 837 | if not isinstance(rows, list): |
| 838 | break |
| 839 | for row in rows: |
| 840 | if not isinstance(row, dict) or row.get("draft"): |
| 841 | continue |
| 842 | published = dates.parse_date(row.get("published_at")) |
| 843 | if not published or published.date().isoformat() > cutoff: |
| 844 | continue |
| 845 | tag = row.get("tag_name") or "" |
| 846 | releases.append((published, { |
| 847 | "tag": tag, "name": row.get("name") or tag, "date": published.date().isoformat(), |
| 848 | "body": (row.get("body") or "")[:max_body], |
| 849 | })) |
| 850 | # A later page can contain an older draft published closer to the cutoff. |
| 851 | if len(rows) < page_size: |
| 852 | break |
| 853 | else: |
| 854 | if as_of: |
| 855 | _log(f"{repo}: historical release lookup reached its {page_limit * page_size}-record limit") |
| 856 | releases.sort(key=lambda entry: entry[0], reverse=True) |
| 857 | return [release for _, release in releases[:count]] |
| 858 | |
| 859 | |
| 860 | def _add_repo_details( |
| 861 | lines: List[str], releases: List[Dict[str, Any]], readme: Optional[str] = None, |
| 862 | *, as_of: Optional[str], counts_observed_at: Optional[str] = None, |
| 863 | readme_limit: int = 300, release_label: str = "Latest release", |
| 864 | ) -> None: |
| 865 | if readme: |
| 866 | lines.append(f" README: {readme[:readme_limit]}") |
| 867 | versions = [] |
| 868 | for release in releases[:2]: |
| 869 | preview = f" - {release['body'][:150]}" if release.get("body") else "" |
| 870 | versions.append(f" {release_label}: {release['name']} ({release['date']}){preview}") |
| 871 | if as_of: |
| 872 | # Normalized snippets are truncated. Keep dated evidence ahead of a long live README. |
| 873 | note = " Descriptions, README and issue status are current at retrieval." |
| 874 | observed = dates.parse_date(counts_observed_at) |
| 875 | if observed: |
| 876 | note = (f" Repository counts observed {observed.date()} UTC. " |
| 877 | "Descriptions, README and issue status are current at retrieval.") |
| 878 | if not versions: |
| 879 | versions.append(f" No verified release evidence through {as_of} is available for this card.") |
| 880 | lines[1:1] = [note, *versions] |
| 881 | else: |
| 882 | lines.extend(versions) |
| 883 | |
| 884 | |
| 885 | def _fetch_top_issues( |
| 886 | repo: str, token: str, as_of: Optional[str] = None, *, failure_out: Optional[List[str]] = None, |
| 887 | ) -> Dict[str, Any]: |
| 888 | """Fetch top feature request (by reactions) and top complaint (by comments).""" |
| 889 | result: Dict[str, Any] = {} |
| 890 | |
| 891 | # Top feature request: issues with enhancement label, sorted by reactions |
| 892 | issue_query = f"is:public repo:{repo} is:issue is:open" |
| 893 | if as_of: |
| 894 | issue_query += f" created:<={as_of}" |
| 895 | feat_q = urllib.parse.quote(f"{issue_query} label:enhancement") |
| 896 | feat_url = f"{SEARCH_URL}?q={feat_q}&sort=reactions&order=desc&per_page=1" |
| 897 | feat_data = _fetch_json(feat_url, token=token, timeout=10, failure_out=failure_out) |
| 898 | if feat_data and feat_data.get("items"): |
| 899 | item = feat_data["items"][0] |
| 900 | result["top_feature_request"] = { |
| 901 | "title": item.get("title", ""), |
| 902 | "reactions": item.get("reactions", {}).get("total_count", 0) if isinstance(item.get("reactions"), dict) else 0, |
| 903 | "comments": item.get("comments") or 0, |
| 904 | "url": item.get("html_url", ""), |
| 905 | } |
| 906 | elif feat_data and feat_data.get("total_count", 0) == 0: |
| 907 | # No enhancement label; fall back to top issue by reactions |
| 908 | fallback_q = urllib.parse.quote(issue_query) |
| 909 | fallback_url = f"{SEARCH_URL}?q={fallback_q}&sort=reactions&order=desc&per_page=1" |
| 910 | fallback_data = _fetch_json(fallback_url, token=token, timeout=10, failure_out=failure_out) |
| 911 | if fallback_data and fallback_data.get("items"): |
| 912 | item = fallback_data["items"][0] |
| 913 | result["top_feature_request"] = { |
| 914 | "title": item.get("title", ""), |
| 915 | "reactions": item.get("reactions", {}).get("total_count", 0) if isinstance(item.get("reactions"), dict) else 0, |
| 916 | "comments": item.get("comments") or 0, |
| 917 | "url": item.get("html_url", ""), |
| 918 | } |
| 919 | |
| 920 | # Top complaint: most-discussed open issue (by comments) |
| 921 | bug_q = urllib.parse.quote(issue_query) |
| 922 | bug_url = f"{SEARCH_URL}?q={bug_q}&sort=comments&order=desc&per_page=1" |
| 923 | bug_data = _fetch_json(bug_url, token=token, timeout=10, failure_out=failure_out) |
| 924 | if bug_data and bug_data.get("items"): |
| 925 | item = bug_data["items"][0] |
| 926 | result["top_complaint"] = { |
| 927 | "title": item.get("title", ""), |
| 928 | "reactions": item.get("reactions", {}).get("total_count", 0) if isinstance(item.get("reactions"), dict) else 0, |
| 929 | "comments": item.get("comments") or 0, |
| 930 | "url": item.get("html_url", ""), |
| 931 | } |
| 932 | |
| 933 | return result |
| 934 | |
| 935 | |
| 936 | def _is_public_repo(data: Any) -> bool: |
| 937 | return ( |
| 938 | isinstance(data, dict) |
| 939 | and data.get("visibility") == "public" |
| 940 | and data.get("private") is not True |
| 941 | ) |
| 942 | |
| 943 | |
| 944 | def _repo_count(value: Any) -> int | None: |
| 945 | return value if type(value) is int and value >= 0 else None |
| 946 | |
| 947 | |
| 948 | def _repo_metadata(data: dict, observed_at: str) -> dict: |
| 949 | """Decode both single-repository and repository-search responses.""" |
| 950 | info = { |
| 951 | "created_on": _parse_date(data.get("created_at")), |
| 952 | "description": (data.get("description") or "")[:200], |
| 953 | "language": data.get("language") or "", |
| 954 | } |
| 955 | for field, key in (("stargazers_count", "stars"), ("open_issues_count", "open_issues"), |
| 956 | ("forks_count", "forks")): |
| 957 | count = _repo_count(data.get(field)) |
| 958 | if count is not None: |
| 959 | info[key] = count |
| 960 | if "stars" in info or "open_issues" in info: |
| 961 | info["repo_counts_observed_at"] = observed_at |
| 962 | return info |
| 963 | |
| 964 | |
| 965 | def _fetch_repo_info(repo: str, token: str, *, failure_out: Optional[List[str]] = None) -> Optional[Dict[str, Any]]: |
| 966 | """Fetch metadata for a public repository.""" |
| 967 | if not _REPO_SLUG.fullmatch(repo): |
| 968 | return None |
| 969 | url = f"https://api.github.com/repos/{repo}" |
| 970 | data = _fetch_json(url, token=token, timeout=10, failure_out=failure_out) |
| 971 | if not _is_public_repo(data): |
| 972 | return None |
| 973 | return _repo_metadata(data, datetime.now(timezone.utc).isoformat()) |
| 974 | |
| 975 | |
| 976 | def _format_stars(n: int) -> str: |
| 977 | """Format star count as human-readable (e.g., 349K, 2.9K, 42).""" |
| 978 | if n >= 1_000_000: |
| 979 | return f"{n / 1_000_000:.1f}M" |
| 980 | if n >= 1_000: |
| 981 | return f"{n / 1_000:.0f}K" if n >= 10_000 else f"{n / 1_000:.1f}K" |
| 982 | return str(n) |
| 983 | |
| 984 | |
| 985 | def _repo_card_counts(info: dict, *, stars_only: bool = False) -> tuple[dict[str, int], str, str]: |
| 986 | """Display missing counters explicitly and keep them out of numeric evidence.""" |
| 987 | keys = ("stars",) if stars_only else ("stars", "open_issues") |
| 988 | counts = {key: info[key] for key in keys if key in info} |
| 989 | stars = f"{_format_stars(counts['stars'])} stars" if "stars" in counts else "stars unavailable" |
| 990 | issues = (f"{counts['open_issues']} open issues/PRs" if "open_issues" in counts |
| 991 | else "open issue/PR count unavailable") |
| 992 | return counts, stars, issues |
| 993 | |
| 994 | |
| 995 | def refetch_datum(item: schema.SourceItem | None, datum_key: str) -> dict[str, Any]: |
| 996 | """Re-fetch one repository counter through the shared HTTP wrapper. |
| 997 | |
| 998 | ``datum_key`` is either the literal ``"stars"`` (item-level claim; the |
| 999 | repo derives from the grounding item) or an ``owner/repo`` slug |
| 1000 | (candidate-enrichment claim; the repo itself is the refetch subject and |
| 1001 | the item is not consulted, so it may be ``None``). |
| 1002 | """ |
| 1003 | if _REPO_SLUG.fullmatch(datum_key): |
| 1004 | repo = datum_key |
| 1005 | elif datum_key != "stars": |
| 1006 | raise KeyError(f"Unsupported GitHub datum: {datum_key}") |
| 1007 | else: |
| 1008 | if item is None: |
| 1009 | raise ValueError("Item-level star refetch requires the grounding item") |
| 1010 | repo = item.container or "" |
| 1011 | if not _REPO_SLUG.fullmatch(repo): |
| 1012 | match = re.match(r"https?://github\.com/([^/]+/[^/#?]+)", item.url) |
| 1013 | repo = _normalize_repo_slug(match.group(1)) if match else "" |
| 1014 | if not _REPO_SLUG.fullmatch(repo): |
| 1015 | raise ValueError("GitHub item has no owner/repository reference") |
| 1016 | headers = {"Accept": "application/vnd.github+json"} |
| 1017 | token = _resolve_token() |
| 1018 | if token: |
| 1019 | headers["Authorization"] = f"Bearer {token}" |
| 1020 | data = http.request( |
| 1021 | "GET", f"https://api.github.com/repos/{repo}", |
| 1022 | headers=headers, timeout=10, retries=2, |
| 1023 | ) |
| 1024 | if not _is_public_repo(data) or _repo_count(data.get("stargazers_count")) is None: |
| 1025 | raise KeyError("Public GitHub star count was not returned") |
| 1026 | fallback_url = item.url if item is not None else f"https://github.com/{repo}" |
| 1027 | return { |
| 1028 | "value": data["stargazers_count"], |
| 1029 | "url": str(data.get("html_url") or fallback_url), |
| 1030 | "timestamp": datetime.now(timezone.utc).isoformat(), |
| 1031 | } |
| 1032 | |
| 1033 | |
| 1034 | def search_github_person( |
| 1035 | username: str, |
| 1036 | from_date: str, |
| 1037 | to_date: str, |
| 1038 | depth: str = "default", |
| 1039 | token: Optional[str] = None, |
| 1040 | ) -> List[Dict[str, Any]]: |
| 1041 | """Person-mode GitHub search: author-scoped queries with star enrichment. |
| 1042 | |
| 1043 | Returns SourceItems for: |
| 1044 | - 1 velocity summary item |
| 1045 | - Per-repo items for top external repos (with stars + release notes) |
| 1046 | - Per-repo items for own repos (with stars + README + top issues + releases) |
| 1047 | """ |
| 1048 | if not re.fullmatch(r"[A-Za-z0-9_-]+(?:\[bot\])?", username): |
| 1049 | return [] |
| 1050 | resolved_token = _resolve_token(token) |
| 1051 | if not resolved_token: |
| 1052 | _log("No GitHub token available for person-mode search") |
| 1053 | return [] |
| 1054 | |
| 1055 | limits = PERSON_DEPTH_LIMITS.get(depth, PERSON_DEPTH_LIMITS["default"]) |
| 1056 | _log(f"Person-mode search for @{username} (since {from_date})") |
| 1057 | |
| 1058 | # Phase 1: PR velocity via search API |
| 1059 | as_of = _historical_cutoff(to_date) |
| 1060 | author_query = f"is:public author:{username} type:pr created:{from_date}..{to_date}" |
| 1061 | total_q = urllib.parse.quote(author_query) |
| 1062 | merged_by = f" merged:<={as_of}" if as_of else "" |
| 1063 | merged_q = urllib.parse.quote(f"{author_query}{merged_by} is:merged") |
| 1064 | |
| 1065 | total_url = f"{SEARCH_URL}?q={total_q}&per_page=1" |
| 1066 | merged_url = f"{SEARCH_URL}?q={merged_q}&sort=reactions&order=desc&per_page=100" |
| 1067 | |
| 1068 | total_data = _fetch_json(total_url, token=resolved_token, timeout=20) |
| 1069 | merged_data = _fetch_json(merged_url, token=resolved_token, timeout=20) |
| 1070 | |
| 1071 | total_prs = total_data.get("total_count", 0) if total_data else 0 |
| 1072 | merged_count = merged_data.get("total_count", 0) if merged_data else 0 |
| 1073 | merged_items = merged_data.get("items", []) if merged_data else [] |
| 1074 | |
| 1075 | _log(f"Found {total_prs} total PRs, {merged_count} merged") |
| 1076 | |
| 1077 | if total_prs == 0 and merged_count == 0: |
| 1078 | # An empty PR search can mean no PRs in the window or an account that |
| 1079 | # GitHub's issue index cannot search. Public PushEvents provide an |
| 1080 | # actor-attributed fallback for either case. |
| 1081 | search_unavailable = total_data is None or merged_data is None |
| 1082 | recent = _person_recent_pushes( |
| 1083 | username, from_date, to_date, limits, resolved_token, |
| 1084 | ) |
| 1085 | if recent: |
| 1086 | reason = "account not searchable" if search_unavailable else "no PRs in window" |
| 1087 | _log(f"PR search empty ({reason}); public events returned {len(recent)} items") |
| 1088 | return recent |
| 1089 | _log("No PRs found, falling back to keyword search") |
| 1090 | return [] |
| 1091 | |
| 1092 | open_q = urllib.parse.quote(f"{author_query} is:open") |
| 1093 | open_data = _fetch_json(f"{SEARCH_URL}?q={open_q}&per_page=1", token=resolved_token, timeout=20) |
| 1094 | open_count = ( |
| 1095 | open_data.get("total_count") |
| 1096 | if isinstance(open_data, dict) and not open_data.get("incomplete_results") |
| 1097 | else None |
| 1098 | ) |
| 1099 | |
| 1100 | # Phase 2: Group merged PRs by repo |
| 1101 | repo_pr_counts: Dict[str, int] = {} |
| 1102 | for item in merged_items: |
| 1103 | repo = _parse_repo_from_url(item.get("html_url", "")) |
| 1104 | if _REPO_SLUG.fullmatch(repo): |
| 1105 | repo_pr_counts[repo] = repo_pr_counts.get(repo, 0) + 1 |
| 1106 | |
| 1107 | # Sort repos by PR count (most active first) |
| 1108 | sorted_repos = sorted(repo_pr_counts.items(), key=lambda x: x[1], reverse=True) |
| 1109 | |
| 1110 | # Repository search supports sorting by stars before the per-page limit. |
| 1111 | repo_query = f"is:public user:{username}" |
| 1112 | if as_of: |
| 1113 | repo_query += f" created:<={as_of}" |
| 1114 | params = urllib.parse.urlencode({ |
| 1115 | "q": repo_query, "sort": "stars", "order": "desc", "per_page": limits["own_repos"], |
| 1116 | }) |
| 1117 | found = _fetch_json(f"https://api.github.com/search/repositories?{params}", token=resolved_token, timeout=15) |
| 1118 | own_repos_data = found.get("items") if isinstance(found, dict) else [] |
| 1119 | own_repos_info: List[Dict[str, Any]] = [] |
| 1120 | if own_repos_data and isinstance(own_repos_data, list): |
| 1121 | observed_at = datetime.now(timezone.utc).isoformat() |
| 1122 | for r in own_repos_data: |
| 1123 | created = _parse_date(r.get("created_at")) |
| 1124 | if as_of and created and created > as_of: |
| 1125 | continue |
| 1126 | full_name = r.get("full_name", "") |
| 1127 | if _REPO_SLUG.fullmatch(full_name or "") and not r.get("fork"): |
| 1128 | own_repos_info.append({ |
| 1129 | "full_name": full_name, |
| 1130 | **_repo_metadata(r, observed_at), |
| 1131 | }) |
| 1132 | |
| 1133 | # Separate external repos from own repos |
| 1134 | external_repos = [ |
| 1135 | (repo, count) for repo, count in sorted_repos |
| 1136 | if repo.split("/", 1)[0].casefold() != username.casefold() |
| 1137 | ] |
| 1138 | external_repos = external_repos[:limits["external_repos"]] |
| 1139 | |
| 1140 | # Phase 4: Parallel enrichment (star counts, releases, READMEs, top issues) |
| 1141 | items: List[Dict[str, Any]] = [] |
| 1142 | idx = 0 |
| 1143 | |
| 1144 | # Build velocity summary |
| 1145 | submitted_line = f"- {total_prs} total PRs submitted" |
| 1146 | if type(open_count) is int and 0 <= open_count <= total_prs: |
| 1147 | submitted_line += f", {open_count} still open" |
| 1148 | if as_of: |
| 1149 | submitted_line += " at retrieval" |
| 1150 | merge_rate = round(100 * merged_count / total_prs) if total_prs > 0 else 0 |
| 1151 | num_repos = len(repo_pr_counts) |
| 1152 | velocity_text = ( |
| 1153 | f"GitHub Person Profile: @{username}\n\n" |
| 1154 | f"CONTRIBUTION VELOCITY (last {dates.days_ago(from_date, to_date)} days)\n" |
| 1155 | f"- {merged_count} PRs merged across {num_repos} repos ({merge_rate}% merge rate)\n" |
| 1156 | f"{submitted_line}\n" |
| 1157 | ) |
| 1158 | |
| 1159 | idx += 1 |
| 1160 | items.append({ |
| 1161 | "id": f"GH{idx}", |
| 1162 | "title": f"@{username}: {merged_count} PRs merged across {num_repos} repos ({merge_rate}% merge rate)", |
| 1163 | "url": f"https://github.com/{username}", |
| 1164 | "date": to_date, |
| 1165 | "author": username, |
| 1166 | "source": "github", |
| 1167 | "score": merged_count, |
| 1168 | "container": f"@{username}", |
| 1169 | "snippet": velocity_text, |
| 1170 | "relevance": 0.95, |
| 1171 | "why_relevant": f"GitHub profile: @{username} - {merged_count} PRs merged across {num_repos} repos", |
| 1172 | "engagement": {"merged_prs": merged_count, "total_prs": total_prs}, |
| 1173 | "metadata": { |
| 1174 | "labels": ["person-profile", "velocity"], |
| 1175 | "state": "open", |
| 1176 | "comment_count": 0, |
| 1177 | "reactions": merged_count, |
| 1178 | "is_pr": False, |
| 1179 | }, |
| 1180 | }) |
| 1181 | |
| 1182 | # Phase 5: Enrich external repos (parallel: star counts + releases) |
| 1183 | _log(f"Enriching {len(external_repos)} external repos + {len(own_repos_info)} own repos") |
| 1184 | |
| 1185 | with ThreadPoolExecutor(max_workers=8) as executor: |
| 1186 | # External repo enrichment: stars + releases |
| 1187 | ext_futures = {} |
| 1188 | for repo, pr_count in external_repos: |
| 1189 | ext_futures[executor.submit(_enrich_external_repo, repo, resolved_token, as_of)] = (repo, pr_count) |
| 1190 | |
| 1191 | # Own repo enrichment: README + releases + top issues |
| 1192 | own_futures = {} |
| 1193 | for own_repo in own_repos_info: |
| 1194 | own_futures[executor.submit(_enrich_own_repo, own_repo["full_name"], resolved_token, as_of)] = own_repo |
| 1195 | |
| 1196 | # Collect external repo results |
| 1197 | for future in as_completed(ext_futures): |
| 1198 | repo, pr_count = ext_futures[future] |
| 1199 | try: |
| 1200 | enrichment = future.result(timeout=20) |
| 1201 | except Exception as exc: |
| 1202 | _log(f"External repo enrichment failed for {repo}: {exc}") |
| 1203 | enrichment = {} |
| 1204 | |
| 1205 | repo_info = enrichment.get("info") or {} |
| 1206 | releases = enrichment.get("releases", []) |
| 1207 | |
| 1208 | counts, stars_label, _ = _repo_card_counts(repo_info, stars_only=True) |
| 1209 | stars = counts.get("stars") |
| 1210 | observed_at = repo_info.get("repo_counts_observed_at") if counts else None |
| 1211 | desc = repo_info.get("description") |
| 1212 | |
| 1213 | snippet_parts = [f"Contributed {pr_count} merged PRs to {repo} ({stars_label})"] |
| 1214 | if desc: |
| 1215 | snippet_parts.append(f" {desc}") |
| 1216 | _add_repo_details(snippet_parts, releases, as_of=as_of, counts_observed_at=observed_at) |
| 1217 | |
| 1218 | idx += 1 |
| 1219 | items.append({ |
| 1220 | "id": f"GH{idx}", |
| 1221 | "title": f"{repo} ({stars_label}) - {pr_count} PRs merged", |
| 1222 | "url": f"https://github.com/{repo}", |
| 1223 | "date": _snapshot_date(releases, from_date, to_date), |
| 1224 | "author": username, |
| 1225 | "source": "github", |
| 1226 | "score": stars, |
| 1227 | "container": repo, |
| 1228 | "snippet": "\n".join(snippet_parts), |
| 1229 | "relevance": min(0.9, 0.6 + math.log1p(stars or 0) / 30 + min(0.15, pr_count / 20)), |
| 1230 | "why_relevant": f"GitHub contribution: {pr_count} PRs merged to {repo} ({stars_label})", |
| 1231 | "engagement": {**counts, "contributed_prs": pr_count}, |
| 1232 | "metadata": { |
| 1233 | "labels": ["person-profile", "external-repo"], |
| 1234 | "repo_counts_observed_at": observed_at, |
| 1235 | "state": "open", |
| 1236 | "comment_count": 0, |
| 1237 | "reactions": stars, |
| 1238 | "is_pr": False, |
| 1239 | "date_is_snapshot": not _has_in_window_release(releases, from_date, to_date), |
| 1240 | }, |
| 1241 | }) |
| 1242 | |
| 1243 | # Collect own repo results |
| 1244 | for future in as_completed(own_futures): |
| 1245 | own_repo = own_futures[future] |
| 1246 | try: |
| 1247 | enrichment = future.result(timeout=25) |
| 1248 | except Exception as exc: |
| 1249 | _log(f"Own repo enrichment failed for {own_repo['full_name']}: {exc}") |
| 1250 | enrichment = {} |
| 1251 | |
| 1252 | repo_name = own_repo["full_name"] |
| 1253 | counts, stars_label, issues_label = _repo_card_counts(own_repo) |
| 1254 | stars = counts.get("stars") |
| 1255 | observed_at = own_repo.get("repo_counts_observed_at") |
| 1256 | desc = own_repo["description"] |
| 1257 | |
| 1258 | readme = enrichment.get("readme") |
| 1259 | releases = enrichment.get("releases", []) |
| 1260 | top_issues = enrichment.get("top_issues", {}) |
| 1261 | |
| 1262 | snippet_parts = [f"Own project: {repo_name} ({stars_label}, {issues_label})"] |
| 1263 | if desc: |
| 1264 | snippet_parts.append(f" {desc}") |
| 1265 | _add_repo_details(snippet_parts, releases, readme, as_of=as_of, counts_observed_at=observed_at) |
| 1266 | feat = top_issues.get("top_feature_request") |
| 1267 | if feat: |
| 1268 | snippet_parts.append(f" Top feature request: \"{feat['title']}\" ({feat['reactions']} reactions, {feat['comments']} comments)") |
| 1269 | complaint = top_issues.get("top_complaint") |
| 1270 | if complaint: |
| 1271 | snippet_parts.append(f" Top complaint: \"{complaint['title']}\" ({complaint['comments']} comments)") |
| 1272 | |
| 1273 | idx += 1 |
| 1274 | items.append({ |
| 1275 | "id": f"GH{idx}", |
| 1276 | "title": f"{repo_name} ({stars_label}) - own project, {issues_label}", |
| 1277 | "url": f"https://github.com/{repo_name}", |
| 1278 | "date": _snapshot_date(releases, from_date, to_date), |
| 1279 | "author": username, |
| 1280 | "source": "github", |
| 1281 | "score": stars, |
| 1282 | "container": repo_name, |
| 1283 | "snippet": "\n".join(snippet_parts), |
| 1284 | "relevance": min(0.95, 0.7 + math.log1p(stars or 0) / 25), |
| 1285 | "why_relevant": f"GitHub own project: {repo_name} ({stars_label})", |
| 1286 | "engagement": counts, |
| 1287 | "metadata": { |
| 1288 | "labels": ["person-profile", "own-repo"], |
| 1289 | "repo_counts_observed_at": observed_at, |
| 1290 | "state": "open", |
| 1291 | "comment_count": 0, |
| 1292 | "reactions": stars, |
| 1293 | "is_pr": False, |
| 1294 | "date_is_snapshot": not _has_in_window_release(releases, from_date, to_date), |
| 1295 | }, |
| 1296 | }) |
| 1297 | |
| 1298 | # Popular projects often reach the same relevance cap. Worker completion |
| 1299 | # order must not decide which project leads or displace the profile summary. |
| 1300 | items.sort(key=lambda item: ( |
| 1301 | -item["relevance"], |
| 1302 | "velocity" not in item["metadata"]["labels"], |
| 1303 | -item["engagement"].get("stars", 0), |
| 1304 | item["container"].casefold(), |
| 1305 | )) |
| 1306 | _log(f"Person-mode returned {len(items)} items") |
| 1307 | return items |
| 1308 | |
| 1309 | |
| 1310 | def _person_recent_pushes( |
| 1311 | username: str, |
| 1312 | from_date: str, |
| 1313 | to_date: str, |
| 1314 | limits: Dict[str, int], |
| 1315 | token: str, |
| 1316 | ) -> List[Dict[str, Any]]: |
| 1317 | """Return repos the selected actor publicly pushed inside the window.""" |
| 1318 | latest_by_repo: Dict[str, Dict[str, str]] = {} |
| 1319 | encoded_username = urllib.parse.quote(username, safe="") |
| 1320 | |
| 1321 | page = 1 |
| 1322 | while True: |
| 1323 | url = ( |
| 1324 | f"https://api.github.com/users/{encoded_username}/events/public" |
| 1325 | f"?per_page={PERSON_EVENTS_PER_PAGE}&page={page}" |
| 1326 | ) |
| 1327 | data = _fetch_json(url, token=token, timeout=15) |
| 1328 | if not data or not isinstance(data, list): |
| 1329 | break |
| 1330 | |
| 1331 | reached_before_window = False |
| 1332 | for event in data: |
| 1333 | created_at = event.get("created_at") |
| 1334 | pushed = _parse_date(created_at) |
| 1335 | if not pushed: |
| 1336 | continue |
| 1337 | if pushed < from_date: |
| 1338 | reached_before_window = True |
| 1339 | break |
| 1340 | if pushed > to_date or event.get("type") != "PushEvent": |
| 1341 | continue |
| 1342 | |
| 1343 | actor = event.get("actor") |
| 1344 | actor_login = actor.get("login", "") if isinstance(actor, dict) else "" |
| 1345 | if actor_login.casefold() != username.casefold(): |
| 1346 | continue |
| 1347 | |
| 1348 | repo = event.get("repo") |
| 1349 | full_name = repo.get("name", "") if isinstance(repo, dict) else "" |
| 1350 | if not _REPO_SLUG.fullmatch(full_name or ""): |
| 1351 | continue |
| 1352 | |
| 1353 | previous = latest_by_repo.get(full_name) |
| 1354 | if previous is None or created_at > previous["created_at"]: |
| 1355 | latest_by_repo[full_name] = { |
| 1356 | "full_name": full_name, |
| 1357 | "pushed": pushed, |
| 1358 | "created_at": created_at, |
| 1359 | "actor": actor_login, |
| 1360 | "event_id": str(event.get("id") or ""), |
| 1361 | } |
| 1362 | |
| 1363 | if reached_before_window or len(data) < PERSON_EVENTS_PER_PAGE: |
| 1364 | break |
| 1365 | page += 1 |
| 1366 | |
| 1367 | if not latest_by_repo: |
| 1368 | return [] |
| 1369 | |
| 1370 | recent = sorted( |
| 1371 | latest_by_repo.values(), |
| 1372 | key=lambda r: r["created_at"], |
| 1373 | reverse=True, |
| 1374 | ) |
| 1375 | _log( |
| 1376 | f"Public events: {len(recent)} actor-attributed repos pushed in window, " |
| 1377 | "loading repository metadata for ranking" |
| 1378 | ) |
| 1379 | |
| 1380 | repo_info: Dict[str, Dict[str, Any]] = {} |
| 1381 | with ThreadPoolExecutor(max_workers=8) as executor: |
| 1382 | info_futures = { |
| 1383 | executor.submit(_fetch_repo_info, r["full_name"], token): r["full_name"] |
| 1384 | for r in recent |
| 1385 | } |
| 1386 | for future in as_completed(info_futures): |
| 1387 | name = info_futures[future] |
| 1388 | try: |
| 1389 | repo_info[name] = future.result(timeout=20) or {} |
| 1390 | except Exception as exc: |
| 1391 | _log(f"Push-event repo metadata failed for {name}: {exc}") |
| 1392 | repo_info[name] = {} |
| 1393 | |
| 1394 | recent.sort( |
| 1395 | key=lambda r: ( |
| 1396 | repo_info.get(r["full_name"], {}).get("stars", 0), |
| 1397 | r["created_at"], |
| 1398 | ), |
| 1399 | reverse=True, |
| 1400 | ) |
| 1401 | selected = recent[:limits["own_repos"]] |
| 1402 | |
| 1403 | enrichments: Dict[str, Dict[str, Any]] = {} |
| 1404 | as_of = _historical_cutoff(to_date) |
| 1405 | _log(f"Public events: enriching {len(selected)} top-ranked repositories") |
| 1406 | with ThreadPoolExecutor(max_workers=8) as executor: |
| 1407 | enrichment_futures = { |
| 1408 | executor.submit(_enrich_own_repo, r["full_name"], token, as_of): r["full_name"] |
| 1409 | for r in selected |
| 1410 | } |
| 1411 | for future in as_completed(enrichment_futures): |
| 1412 | name = enrichment_futures[future] |
| 1413 | try: |
| 1414 | enrichments[name] = future.result(timeout=25) |
| 1415 | except Exception as exc: |
| 1416 | _log(f"Push-event enrichment failed for {name}: {exc}") |
| 1417 | enrichments[name] = {} |
| 1418 | |
| 1419 | items: List[Dict[str, Any]] = [] |
| 1420 | for idx, repo in enumerate(selected, start=1): |
| 1421 | name = repo["full_name"] |
| 1422 | info = repo_info.get(name, {}) |
| 1423 | counts, stars_label, issues_label = _repo_card_counts(info) |
| 1424 | stars = counts.get("stars") |
| 1425 | observed_at = info.get("repo_counts_observed_at") |
| 1426 | enrichment = enrichments.get(name, {}) |
| 1427 | readme = enrichment.get("readme") |
| 1428 | releases = enrichment.get("releases", []) |
| 1429 | |
| 1430 | snippet_parts = [ |
| 1431 | f"@{repo['actor']} pushed {name} on {repo['pushed']} " |
| 1432 | f"({stars_label}, {issues_label})" |
| 1433 | ] |
| 1434 | if info.get("description"): |
| 1435 | snippet_parts.append(f" {info['description']}") |
| 1436 | _add_repo_details(snippet_parts, releases, readme, as_of=as_of, |
| 1437 | counts_observed_at=observed_at, release_label="Release") |
| 1438 | |
| 1439 | items.append({ |
| 1440 | "id": f"GH{idx}", |
| 1441 | "title": f"@{repo['actor']} pushed {name} on {repo['pushed']}", |
| 1442 | "url": f"https://github.com/{name}", |
| 1443 | "date": repo["pushed"], |
| 1444 | "author": repo["actor"], |
| 1445 | "source": "github", |
| 1446 | "score": stars, |
| 1447 | "container": name, |
| 1448 | "snippet": "\n".join(snippet_parts), |
| 1449 | "relevance": min(0.9, 0.6 + math.log1p(stars or 0) / 30), |
| 1450 | "why_relevant": ( |
| 1451 | f"GitHub activity: @{repo['actor']} pushed {name} on {repo['pushed']} " |
| 1452 | f"({stars_label})" |
| 1453 | ), |
| 1454 | "engagement": counts, |
| 1455 | "metadata": { |
| 1456 | "labels": ["person-profile", "recent-push"], |
| 1457 | "repo_counts_observed_at": observed_at, |
| 1458 | "state": "open", |
| 1459 | "comment_count": 0, |
| 1460 | "reactions": stars, |
| 1461 | "is_pr": False, |
| 1462 | "event_type": "PushEvent", |
| 1463 | "event_id": repo["event_id"], |
| 1464 | }, |
| 1465 | }) |
| 1466 | |
| 1467 | return items |
| 1468 | |
| 1469 | |
| 1470 | def _enrich_external_repo(repo: str, token: str, as_of: Optional[str] = None) -> Dict[str, Any]: |
| 1471 | """Fetch star count + releases for an external repo.""" |
| 1472 | info = _fetch_repo_info(repo, token) |
| 1473 | releases = _fetch_latest_releases(repo, as_of=as_of) |
| 1474 | return {"info": info, "releases": releases} |
| 1475 | |
| 1476 | |
| 1477 | def _enrich_own_repo( |
| 1478 | repo: str, token: str, as_of: Optional[str] = None, *, failure_out: Optional[List[str]] = None, |
| 1479 | ) -> Dict[str, Any]: |
| 1480 | """Fetch README + releases + top issues for an own repo.""" |
| 1481 | readme = _fetch_readme_snippet(repo, max_chars=500) |
| 1482 | releases = _fetch_latest_releases(repo, as_of=as_of, failure_out=failure_out) |
| 1483 | top_issues = _fetch_top_issues(repo, token, as_of, failure_out=failure_out) |
| 1484 | return {"readme": readme, "releases": releases, "top_issues": top_issues} |
| 1485 | |
| 1486 | |
| 1487 | # --------------------------------------------------------------------------- |
| 1488 | # Project-mode search: fetch comprehensive data for specific repos |
| 1489 | # --------------------------------------------------------------------------- |
| 1490 | |
| 1491 | def _snapshot_date(releases: List[Dict[str, Any]], from_date: str, to_date: str) -> str: |
| 1492 | """Date for a live repo snapshot item (stars, issues, PRs read now). |
| 1493 | |
| 1494 | The newest release's date when it falls in the window, else ``to_date``. |
| 1495 | An older release date would make the report's date filter drop a repo the |
| 1496 | user pinned: Ghostty's newest release object is its 2022 "tip" nightly. |
| 1497 | """ |
| 1498 | if _has_in_window_release(releases, from_date, to_date): |
| 1499 | return releases[0]["date"] |
| 1500 | return to_date |
| 1501 | |
| 1502 | |
| 1503 | def _has_in_window_release(releases: List[Dict[str, Any]], from_date: str, to_date: str) -> bool: |
| 1504 | """True when the newest release date is a real in-window event. |
| 1505 | |
| 1506 | False means ``_snapshot_date`` fell back to ``to_date``: that date keeps the |
| 1507 | item through the date filter but says nothing about recency, so the item is |
| 1508 | marked ``date_is_snapshot`` and ranks on neutral freshness. |
| 1509 | """ |
| 1510 | release_date = releases[0].get("date") if releases else None |
| 1511 | return bool(release_date and from_date <= release_date <= to_date) |
| 1512 | |
| 1513 | |
| 1514 | def search_github_project( |
| 1515 | repos: List[str], |
| 1516 | from_date: str, |
| 1517 | to_date: str, |
| 1518 | depth: str = "default", |
| 1519 | token: Optional[str] = None, |
| 1520 | *, |
| 1521 | failure_out: Optional[List[tuple[str, str]]] = None, |
| 1522 | ) -> List[Dict[str, Any]]: |
| 1523 | """Project-mode GitHub search: fetch stars, README, releases, top issues for repos. |
| 1524 | |
| 1525 | Args: |
| 1526 | repos: List of 'owner/repo' strings. |
| 1527 | from_date: Start date (YYYY-MM-DD). |
| 1528 | to_date: End date (YYYY-MM-DD). |
| 1529 | depth: 'quick', 'default', or 'deep'. |
| 1530 | token: Optional GitHub token. |
| 1531 | failure_out: Optional list of (repository, raw lookup error) pairs for source coverage. |
| 1532 | |
| 1533 | Returns: |
| 1534 | List of SourceItems, one per repo. |
| 1535 | """ |
| 1536 | repos = [repo for repo in repos if _REPO_SLUG.fullmatch(repo)] |
| 1537 | if not repos: |
| 1538 | return [] |
| 1539 | resolved_token = _resolve_token(token) |
| 1540 | if not resolved_token: |
| 1541 | _log("No GitHub token available for project-mode search") |
| 1542 | return [] |
| 1543 | |
| 1544 | _log(f"Project-mode search for {len(repos)} repos: {', '.join(repos)}") |
| 1545 | |
| 1546 | items: List[Dict[str, Any]] = [] |
| 1547 | |
| 1548 | as_of = _historical_cutoff(to_date) |
| 1549 | with ThreadPoolExecutor(max_workers=min(8, len(repos))) as executor: |
| 1550 | futures = { |
| 1551 | executor.submit(_enrich_project_repo, repo, resolved_token, as_of): repo |
| 1552 | for repo in repos |
| 1553 | } |
| 1554 | |
| 1555 | for idx, future in enumerate(as_completed(futures)): |
| 1556 | repo = futures[future] |
| 1557 | try: |
| 1558 | enrichment = future.result(timeout=25) |
| 1559 | except Exception as exc: |
| 1560 | _log(f"Project enrichment failed for {repo}: {exc}") |
| 1561 | if failure_out is not None: |
| 1562 | failure_out.append((repo, str(exc))) |
| 1563 | continue |
| 1564 | |
| 1565 | if failure_out is not None: |
| 1566 | failure_out.extend((repo, reason) for reason in enrichment.get("failures", [])) |
| 1567 | info = enrichment.get("info") |
| 1568 | if not info: |
| 1569 | _log(f"No repo info for {repo}, skipping") |
| 1570 | continue |
| 1571 | |
| 1572 | readme = enrichment.get("readme") |
| 1573 | releases = enrichment.get("releases", []) |
| 1574 | top_issues = enrichment.get("top_issues", {}) |
| 1575 | |
| 1576 | counts, stars_label, issues_label = _repo_card_counts(info) |
| 1577 | stars = counts.get("stars") |
| 1578 | observed_at = info.get("repo_counts_observed_at") |
| 1579 | desc = info["description"] |
| 1580 | lang = info["language"] |
| 1581 | |
| 1582 | summary = ", ".join(part for part in (stars_label, issues_label, lang) if part) |
| 1583 | star_evidence = f"{stars_label}, live" if stars is not None else stars_label |
| 1584 | snippet_parts = [f"Project: {repo} ({summary})"] |
| 1585 | if desc: |
| 1586 | snippet_parts.append(f" {desc}") |
| 1587 | _add_repo_details(snippet_parts, releases, readme, as_of=as_of, |
| 1588 | counts_observed_at=observed_at, readme_limit=400) |
| 1589 | feat = top_issues.get("top_feature_request") |
| 1590 | if feat: |
| 1591 | snippet_parts.append(f" Top feature request: \"{feat['title']}\" ({feat['reactions']} reactions, {feat['comments']} comments)") |
| 1592 | complaint = top_issues.get("top_complaint") |
| 1593 | if complaint: |
| 1594 | snippet_parts.append(f" Top complaint: \"{complaint['title']}\" ({complaint['comments']} comments)") |
| 1595 | |
| 1596 | items.append({ |
| 1597 | "id": f"GH{idx + 1}", |
| 1598 | "title": f"{repo} ({stars_label}) - {issues_label}", |
| 1599 | "url": f"https://github.com/{repo}", |
| 1600 | "date": _snapshot_date(releases, from_date, to_date), |
| 1601 | "author": repo.split("/")[0], |
| 1602 | "source": "github", |
| 1603 | "score": stars, |
| 1604 | "container": repo, |
| 1605 | "snippet": "\n".join(snippet_parts), |
| 1606 | "relevance": min(0.95, 0.7 + math.log1p(stars or 0) / 25), |
| 1607 | "why_relevant": f"GitHub project: {repo} ({star_evidence})", |
| 1608 | "engagement": counts, |
| 1609 | "metadata": { |
| 1610 | "labels": ["project-mode"], |
| 1611 | "repo_counts_observed_at": observed_at, |
| 1612 | "repo_description": desc or "", |
| 1613 | "state": "open", |
| 1614 | "comment_count": 0, |
| 1615 | "reactions": stars, |
| 1616 | "is_pr": False, |
| 1617 | "date_is_snapshot": not _has_in_window_release(releases, from_date, to_date), |
| 1618 | **({"github_stars": {repo: stars}} if stars is not None else {}), |
| 1619 | }, |
| 1620 | }) |
| 1621 | |
| 1622 | items.sort(key=lambda x: x.get("relevance", 0), reverse=True) |
| 1623 | _log(f"Project-mode returned {len(items)} items") |
| 1624 | return items |
| 1625 | |
| 1626 | |
| 1627 | def _enrich_project_repo(repo: str, token: str, as_of: Optional[str] = None) -> Dict[str, Any]: |
| 1628 | """Fetch all project data for a repo: info + README + releases + top issues.""" |
| 1629 | failures: List[str] = [] |
| 1630 | info = _fetch_repo_info(repo, token, failure_out=failures) |
| 1631 | if not info or (as_of and info.get("created_on") and info["created_on"] > as_of): |
| 1632 | return {"failures": failures} |
| 1633 | details = _enrich_own_repo(repo, token, as_of, failure_out=failures) |
| 1634 | return {"info": info, **details, "failures": failures} |
| 1635 | |
| 1636 | |
| 1637 | # --------------------------------------------------------------------------- |
| 1638 | # Post-rerank star enrichment: annotate candidates with live star counts |
| 1639 | # --------------------------------------------------------------------------- |
| 1640 | |
| 1641 | _REPO_URL_PATTERN = re.compile(r"github\.com/([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)") |
| 1642 | _SKIP_PATHS = {"topics", "search", "orgs", "settings", "features", "about", "pricing", "enterprise", "explore", "marketplace", "sponsors"} |
| 1643 | |
| 1644 | |
| 1645 | def _normalize_repo_slug(match: str) -> str: |
| 1646 | """Strip trailing sentence punctuation and a literal case-insensitive .git suffix.""" |
| 1647 | slug = (match or "").rstrip(".") |
| 1648 | if slug.lower().endswith(".git"): |
| 1649 | slug = slug[:-4] |
| 1650 | return slug.rstrip(".") |
| 1651 | |
| 1652 | |
| 1653 | def extract_repo_refs(candidates: List[Any]) -> List[str]: |
| 1654 | """Extract unique owner/repo strings from candidate URLs, titles, and snippets.""" |
| 1655 | seen: set = set() |
| 1656 | repos: List[str] = [] |
| 1657 | for c in candidates: |
| 1658 | texts = [ |
| 1659 | getattr(c, "url", "") or "", |
| 1660 | getattr(c, "title", "") or "", |
| 1661 | ] |
| 1662 | # Also check evidence snippets if available |
| 1663 | evidence = getattr(c, "evidence", None) |
| 1664 | if evidence: |
| 1665 | texts.append(str(evidence)) |
| 1666 | for text in texts: |
| 1667 | for match in _REPO_URL_PATTERN.findall(text): |
| 1668 | slug = _normalize_repo_slug(match) |
| 1669 | if not _REPO_SLUG.fullmatch(slug): |
| 1670 | continue |
| 1671 | repo = slug.lower() |
| 1672 | owner = repo.split("/")[0] |
| 1673 | if owner in _SKIP_PATHS: |
| 1674 | continue |
| 1675 | if repo not in seen: |
| 1676 | seen.add(repo) |
| 1677 | repos.append(slug) # preserve original case |
| 1678 | return repos |
| 1679 | |
| 1680 | |
| 1681 | def enrich_candidates_with_stars( |
| 1682 | candidates: List[Any], |
| 1683 | token: Optional[str] = None, |
| 1684 | already_enriched: Optional[set] = None, |
| 1685 | max_repos: int = 10, |
| 1686 | collect_map: Optional[Dict[str, int]] = None, |
| 1687 | *, |
| 1688 | collect_snapshots: Optional[Dict[str, dict[str, Any]]] = None, |
| 1689 | ) -> int: |
| 1690 | """Annotate candidates with live GitHub star counts. |
| 1691 | |
| 1692 | Returns the number of repos enriched. |
| 1693 | """ |
| 1694 | resolved_token = _resolve_token(token) |
| 1695 | if not resolved_token: |
| 1696 | return 0 |
| 1697 | |
| 1698 | refs = extract_repo_refs(candidates) |
| 1699 | if not refs: |
| 1700 | return 0 |
| 1701 | |
| 1702 | skip = already_enriched or set() |
| 1703 | to_fetch = [r for r in refs if r.lower() not in {s.lower() for s in skip}][:max_repos] |
| 1704 | if not to_fetch: |
| 1705 | return 0 |
| 1706 | |
| 1707 | _log(f"Star enrichment: fetching {len(to_fetch)} repos") |
| 1708 | |
| 1709 | # Parallel fetch star counts |
| 1710 | snapshots: dict[str, dict[str, Any]] = {} |
| 1711 | with ThreadPoolExecutor(max_workers=min(8, len(to_fetch))) as executor: |
| 1712 | futures = {executor.submit(_fetch_repo_info, repo, resolved_token): repo for repo in to_fetch} |
| 1713 | for future in as_completed(futures): |
| 1714 | repo = futures[future] |
| 1715 | try: |
| 1716 | info = future.result(timeout=10) |
| 1717 | if info and "stars" in info: |
| 1718 | snapshots[repo.lower()] = { |
| 1719 | "stars": info["stars"], "observed_at": info.get("repo_counts_observed_at"), |
| 1720 | } |
| 1721 | except Exception: |
| 1722 | pass |
| 1723 | |
| 1724 | if collect_map is not None: |
| 1725 | collect_map.update({repo: snapshot["stars"] for repo, snapshot in snapshots.items()}) |
| 1726 | if collect_snapshots is not None: |
| 1727 | collect_snapshots.update(snapshots) |
| 1728 | return apply_star_map(candidates, snapshots) |
| 1729 | |
| 1730 | |
| 1731 | def apply_star_map(candidates: List[Any], star_map: Dict[str, Any]) -> int: |
| 1732 | """Annotate candidates with recorded star counts and their observation times. |
| 1733 | |
| 1734 | Older offline recordings contain just the count for each repository. |
| 1735 | """ |
| 1736 | if not star_map: |
| 1737 | return 0 |
| 1738 | # Annotate candidates |
| 1739 | enriched_count = 0 |
| 1740 | for c in candidates: |
| 1741 | texts = [getattr(c, "url", "") or "", getattr(c, "title", "") or ""] |
| 1742 | evidence = getattr(c, "evidence", None) |
| 1743 | if evidence: |
| 1744 | texts.append(str(evidence)) |
| 1745 | combined = " ".join(texts) |
| 1746 | for match in _REPO_URL_PATTERN.findall(combined): |
| 1747 | slug = _normalize_repo_slug(match) |
| 1748 | if not _REPO_SLUG.fullmatch(slug): |
| 1749 | continue |
| 1750 | repo_lower = slug.lower() |
| 1751 | snapshot = star_map.get(repo_lower) |
| 1752 | stars = schema.github_repo_count(snapshot.get("stars") if isinstance(snapshot, dict) else snapshot) |
| 1753 | if stars is None or getattr(c, "metadata", None) is None: |
| 1754 | continue |
| 1755 | c.metadata.setdefault("github_stars", {})[slug] = stars |
| 1756 | observed_at = snapshot.get("observed_at") if isinstance(snapshot, dict) else None |
| 1757 | receipts = c.metadata.get("github_stars_observed_at") |
| 1758 | if isinstance(observed_at, str) and observed_at: |
| 1759 | if not isinstance(receipts, dict): |
| 1760 | receipts = c.metadata["github_stars_observed_at"] = {} |
| 1761 | receipts[slug] = observed_at |
| 1762 | elif isinstance(receipts, dict): |
| 1763 | receipts.pop(slug, None) |
| 1764 | if hasattr(c, "evidence") and c.evidence and "(live:" not in c.evidence: |
| 1765 | c.evidence = c.evidence + f" (live: {_format_stars(stars)} stars)" |
| 1766 | enriched_count += 1 |
| 1767 | break # one annotation per candidate |
| 1768 | |
| 1769 | _log(f"Star enrichment: annotated {enriched_count} candidates") |
| 1770 | return enriched_count |
| 1771 |