返回 last30days-skill
hackernews.py
根目录 / skills / last30days / scripts / lib / hackernews.py
1 """Hacker News search via Algolia API (free, no auth required).
2
3 Uses hn.algolia.com/api/v1 for story discovery and comment enrichment.
4 No API key needed - just HTTP calls via stdlib urllib.
5 """
6
7 import datetime
8 import html
9 import math
10 import sys
11 import time
12 from concurrent.futures import ThreadPoolExecutor, as_completed
13 from http.client import HTTPException
14 from typing import Any, Dict, List, Optional
15
16 import re
17
18 from . import http, log
19 from .query import extract_core_subject
20 from .relevance import token_overlap_relevance
21
22 # Common HN prefixes that can cause false-positive keyword matches
23 _HN_PREFIXES = re.compile(r"^(Tell HN|Show HN|Ask HN|Launch HN)\s*:\s*", re.IGNORECASE)
24
25 ALGOLIA_SEARCH_URL = "https://hn.algolia.com/api/v1/search"
26 ALGOLIA_SEARCH_BY_DATE_URL = "https://hn.algolia.com/api/v1/search_by_date"
27 ALGOLIA_ITEM_URL = "https://hn.algolia.com/api/v1/items"
28 # Official HN Firebase item API — `kids` is in the order the thread displays
29 # top-level comments (Algolia's /items children do not carry useful points).
30 FIREBASE_ITEM_URL = "https://hacker-news.firebaseio.com/v0/item"
31
32 DEPTH_CONFIG = {
33 "quick": 15,
34 "default": 30,
35 "deep": 60,
36 }
37
38 MIN_STORY_POINTS = 2
39 HN_OVERFETCH_MULTIPLIER = 2
40
41 ENRICH_LIMITS = {
42 "quick": 3,
43 "default": 5,
44 "deep": 10,
45 }
46
47 DISCOVERY_LIMITS = {"quick": 20, "default": 40, "deep": 60}
48
49
50 def _log(msg: str):
51 log.source_log("HN", msg, tty_only=False)
52
53
54 def _date_to_unix(date_str: str) -> int:
55 """Convert YYYY-MM-DD to Unix timestamp (start of day UTC)."""
56 parts = date_str.split("-")
57 year, month, day = int(parts[0]), int(parts[1]), int(parts[2])
58 dt = datetime.datetime(year, month, day, tzinfo=datetime.timezone.utc)
59 return int(dt.timestamp())
60
61
62 def _unix_to_date(ts: int) -> str:
63 """Convert Unix timestamp to YYYY-MM-DD."""
64 dt = datetime.datetime.fromtimestamp(ts, tz=datetime.timezone.utc)
65 return dt.strftime("%Y-%m-%d")
66
67
68 def _strip_html(text: str) -> str:
69 """Strip HTML tags and decode entities from HN comment text."""
70 text = re.sub(r'<p>', '\n', text)
71 text = re.sub(r'<[^>]+>', '', text)
72 return html.unescape(text).strip()
73
74
75 def _story_hits(response: Any) -> list[dict[str, Any]]:
76 if not isinstance(response, dict) or not isinstance(response.get("hits"), list):
77 raise ValueError("unexpected Hacker News response shape")
78 return [
79 hit for hit in response["hits"]
80 if isinstance(hit, dict) and isinstance(hit.get("title", ""), str)
81 ]
82
83
84 def _story_count(value: Any) -> int:
85 return value if type(value) is int and value > 0 else 0
86
87
88 def search_hackernews(
89 topic: str,
90 from_date: str,
91 to_date: str,
92 depth: str = "default",
93 ) -> Dict[str, Any]:
94 """Search Hacker News via Algolia API.
95
96 Args:
97 topic: Search topic
98 from_date: Start date (YYYY-MM-DD)
99 to_date: End date (YYYY-MM-DD)
100 depth: 'quick', 'default', or 'deep'
101
102 Returns:
103 Dict with Algolia response (contains 'hits' list).
104 """
105 count = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"])
106 fetch_count = count * HN_OVERFETCH_MULTIPLIER
107 from_ts = _date_to_unix(from_date)
108 to_ts = _date_to_unix(to_date) + 86400 # Include the end date
109
110 # Use extracted core subject instead of raw topic for cleaner Algolia matching.
111 # Strip quotes/edge punctuation before and after core extraction so planner-quoted
112 # proper nouns like '"Claude Code"' never leak unbalanced quotes into optionalWords.
113 core_flat = _normalize_query(topic)
114 _log(f"Searching for '{core_flat}' (raw: '{topic}', since {from_date}, count={count})")
115
116 # Use relevance-sorted search. The HN Algolia index only allows
117 # `created_at_i` in numericFilters; `points` is NOT in its
118 # `numericAttributesForFiltering`, so a `points>N` clause makes the API
119 # return HTTP 400 ("invalid numeric attribute(points)") and zero stories.
120 # Low-engagement stories are filtered client-side after overfetching so the
121 # invalid numeric filter is not reintroduced.
122 # NOTE: restrictSearchableAttributes=title omitted intentionally — it would
123 # miss Ask HN/Show HN threads where the topic appears in the body.
124 params = {
125 "query": core_flat,
126 "tags": "story",
127 "numericFilters": f"created_at_i>{from_ts},created_at_i<{to_ts}",
128 "hitsPerPage": str(fetch_count),
129 }
130 # Algolia defaults to AND across query tokens, so a 4-5 word theme query
131 # matches no stories. Mark all-but-the-first token as optional so Algolia
132 # ranks by how many tokens match instead of requiring every one.
133 tokens = core_flat.split()
134 if len(tokens) > 1:
135 params["optionalWords"] = " ".join(tokens[1:])
136
137 from urllib.parse import urlencode
138 url = f"{ALGOLIA_SEARCH_URL}?{urlencode(params)}"
139
140 try:
141 response = http.request("GET", url, timeout=30)
142 raw_hits = _story_hits(response)
143 except http.HTTPError as e:
144 _log(f"Search failed: {e}")
145 return {"hits": [], "error": str(e)}
146 except Exception as e:
147 _log(f"Search failed: {e}")
148 return {"hits": [], "error": str(e)}
149
150 qualifying_hits = [
151 hit for hit in raw_hits
152 if _story_count(hit.get("points")) > MIN_STORY_POINTS
153 ]
154 hits = qualifying_hits[:count]
155 dropped_low_engagement = len(raw_hits) - len(qualifying_hits)
156 if dropped_low_engagement:
157 _log(f"Filtered {dropped_low_engagement}/{len(raw_hits)} low-engagement stories")
158 response = {**response, "hits": hits}
159 _log(f"Found {len(hits)} stories")
160 return response
161
162
163 def fetch_discovery_listings(
164 from_date: str,
165 to_date: str,
166 depth: str = "default",
167 ) -> Dict[str, Any]:
168 """Fetch topic-less HN front-page and best-in-window story listings."""
169 limit = DISCOVERY_LIMITS.get(depth, DISCOVERY_LIMITS["default"])
170 from_ts = _date_to_unix(from_date)
171 to_ts = _date_to_unix(to_date) + 86400
172 from urllib.parse import urlencode
173
174 urls = [
175 f"{ALGOLIA_SEARCH_URL}?{urlencode({'tags': 'front_page', 'hitsPerPage': str(limit)})}",
176 f"{ALGOLIA_SEARCH_URL}?{urlencode({
177 'tags': 'story',
178 'numericFilters': f'created_at_i>{from_ts},created_at_i<{to_ts}',
179 'hitsPerPage': str(limit),
180 })}",
181 ]
182 hits: list[dict[str, Any]] = []
183 errors: list[str] = []
184 for url in urls:
185 try:
186 response = http.request("GET", url, timeout=30)
187 hits.extend(_story_hits(response))
188 except Exception as exc:
189 errors.append(str(exc))
190
191 seen: set[str] = set()
192 unique_hits: list[dict[str, Any]] = []
193 for hit in hits:
194 object_id = str(hit.get("objectID") or "")
195 if not object_id or object_id in seen:
196 continue
197 seen.add(object_id)
198 unique_hits.append(hit)
199
200 items = parse_hackernews_response({"hits": unique_hits}, query="")
201 return {"items": items, "errors": errors}
202
203
204 _WORD_BOUNDARY_RE_CACHE: Dict[str, "re.Pattern[str]"] = {}
205 _EDGE_PUNCT_LEFT = '"\'?!;:()[]{}“”‘’'
206 _EDGE_PUNCT_RIGHT = '"\'?!.;:()[]{}“”‘’'
207
208
209 def _clean_query_token(token: str) -> str:
210 """Strip quotes and edge punctuation while keeping tech symbols (C++, C#, .NET)."""
211 cleaned = token.lstrip(_EDGE_PUNCT_LEFT).rstrip(_EDGE_PUNCT_RIGHT)
212 if cleaned.startswith(".."):
213 cleaned = cleaned.lstrip(".")
214 return "" if cleaned == "." else cleaned
215
216
217 def _flatten_query_for_algolia(text: str) -> str:
218 """Normalise query for Algolia + post-filter comparison.
219
220 Multi-keyword theme queries frequently contain commas (delimiters),
221 hyphens (compound terms like ``ts-bun-node``), planner quotes
222 (``"Claude Code"``), or trailing punctuation (``What is Rust?``).
223 Flatten them to spaces and strip quotes/edge punctuation so the search
224 parameter and the post-filter operate on the same shape while preserving
225 symbol-edged tech terms like ``C++``, ``C#``, ``F#``, and ``.NET``.
226 """
227 raw_tokens = text.replace(",", " ").replace("-", " ").split()
228 tokens = [cleaned for tok in raw_tokens if (cleaned := _clean_query_token(tok))]
229 return " ".join(tokens)
230
231
232 def _normalize_query(text: str) -> str:
233 """Extract core subject and flatten/strip quotes and edge punctuation."""
234 flat = _flatten_query_for_algolia(text)
235 if not flat:
236 return ""
237 return _flatten_query_for_algolia(extract_core_subject(flat))
238
239
240 def _word_boundary_pattern(word: str) -> "re.Pattern[str]":
241 """Build a cached whole-token regex that works on symbol-edged terms."""
242 pattern = _WORD_BOUNDARY_RE_CACHE.get(word)
243 if pattern is None:
244 if word[-1].isalnum() or word[-1] == "_":
245 trailing = r"(?!\w)"
246 else:
247 trailing = rf"(?![A-Za-z_{re.escape(word[-1])}])"
248 pattern = re.compile(rf"(?<!\w){re.escape(word)}{trailing}")
249 _WORD_BOUNDARY_RE_CACHE[word] = pattern
250 return pattern
251
252
253 def _title_matches_query(title: str, query: str, author: str = "") -> bool:
254 """Check if any query token appears as a whole token in the title.
255
256 Returns True when the query is empty (no filter), or when at least one
257 query token matches as a whole token in the title after stripping
258 "Tell HN:", "Show HN:", "Ask HN:", "Launch HN:" prefixes.
259
260 We previously required *every* token to appear (all-words), which killed
261 every Algolia hit on multi-keyword themes like "claude, personal agents,
262 agentic infra" because real HN titles never contain all five tokens
263 verbatim. Relaxing to any-word matches Algolia's `optionalWords` behaviour
264 in `search_hackernews`. Token-overlap relevance scoring at parse time
265 demotes hits where only one weak token matched, so the loosened gate
266 won't surface noise to the top of the ranking.
267
268 Word-character lookarounds (rather than ``\\b`` or naive substring) prevent
269 short tokens like ``ai`` or ``ts`` from matching unrelated words like
270 ``email`` or ``artists`` while still matching symbol-edged tech terms like
271 ``C++``, ``C#``, ``F#``, and ``.NET``.
272 """
273 if not query:
274 return True
275 stripped = _HN_PREFIXES.sub("", title).strip()
276 check_text = stripped.lower()
277 # Normalise the query the same way search_hackernews does so post-filter
278 # tokens line up with what Algolia actually saw.
279 query_words = [w for w in _normalize_query(query).lower().split() if w]
280 if not query_words:
281 return True
282 for word in query_words:
283 if _word_boundary_pattern(word).search(check_text):
284 return True
285 return False
286
287
288 def parse_hackernews_response(response: Dict[str, Any], query: str = "") -> List[Dict[str, Any]]:
289 """Parse Algolia response into normalized item dicts.
290
291 Args:
292 response: Algolia search response
293 query: Original search query for token-overlap relevance scoring
294
295 Returns:
296 List of item dicts ready for normalization.
297 """
298 try:
299 hits = _story_hits(response)
300 except ValueError:
301 return []
302 # Post-filter: remove items where query only matched an HN prefix like "Tell HN:"
303 if query:
304 before = len(hits)
305 hits = [
306 h for h in hits
307 if _title_matches_query(h.get("title", ""), query, h.get("author", ""))
308 ]
309 dropped = before - len(hits)
310 if dropped:
311 _log(f"Prefix filter removed {dropped}/{before} false-positive hits for '{query}'")
312 items = []
313
314 for i, hit in enumerate(hits):
315 object_id = hit.get("objectID", "")
316 points = _story_count(hit.get("points"))
317 num_comments = _story_count(hit.get("num_comments"))
318 created_at_i = hit.get("created_at_i")
319
320 date_str = None
321 if type(created_at_i) is int and created_at_i:
322 try:
323 date_str = _unix_to_date(created_at_i)
324 except (OSError, OverflowError, ValueError):
325 pass
326
327 # Article URL vs HN discussion URL
328 article_url = hit.get("url") or ""
329 hn_url = _hn_item_url(object_id)
330
331 # Relevance: blend Algolia rank with token-overlap content matching
332 rank_score = max(0.3, 1.0 - (i * 0.02)) # 1.0 -> 0.3 over 35 items
333 engagement_boost = min(0.2, math.log1p(points) / 40)
334 if query:
335 content_score = token_overlap_relevance(query, hit.get("title", ""))
336 relevance = min(1.0, 0.6 * rank_score + 0.4 * content_score + engagement_boost)
337 else:
338 relevance = min(1.0, rank_score * 0.7 + engagement_boost + 0.1)
339
340 items.append({
341 "id": object_id,
342 "title": hit.get("title", ""),
343 "url": article_url,
344 "hn_url": hn_url,
345 "author": hit.get("author", ""),
346 "date": date_str,
347 "engagement": {
348 "points": points,
349 "comments": num_comments,
350 },
351 "relevance": round(relevance, 2),
352 "why_relevant": f"HN story about {hit.get('title', 'topic')[:60]}",
353 })
354
355 return items
356
357
358 def _hn_item_url(item_id: Any) -> str:
359 """HN discussion/comment permalink for an item id."""
360 return f"https://news.ycombinator.com/item?id={item_id}"
361
362
363 # Ordering is optional, so a slow Firebase must not hold up the report.
364 FIREBASE_KIDS_TIMEOUT = 5
365 FIREBASE_KIDS_RETRIES = 2
366 FIREBASE_KIDS_BUDGET = 8.0
367
368
369 def _fetch_hn_kids(object_id: str) -> Optional[List[Any]]:
370 """Return HN's display order for a story's top-level comments, or None on failure.
371
372 Algolia's `/items/<id>` children list is effectively id-order with `points`
373 always null, so sorting by points is a no-op (#1285). The Firebase item
374 endpoint returns `kids` in the same order the HN thread UI shows.
375 """
376 url = f"{FIREBASE_ITEM_URL}/{object_id}.json"
377 # Comment order is a refinement over comments Algolia already returned, so a
378 # Firebase failure must not reach the pipeline's sink and mark HN degraded.
379 try:
380 with http.capture_failures():
381 data = http.request(
382 "GET",
383 url,
384 timeout=FIREBASE_KIDS_TIMEOUT,
385 retries=FIREBASE_KIDS_RETRIES,
386 deadline_monotonic=time.monotonic() + FIREBASE_KIDS_BUDGET,
387 )
388 # http.request wraps HTTP and socket errors, but a truncated or non-UTF-8
389 # body escapes as IncompleteRead or UnicodeDecodeError.
390 except (http.HTTPError, HTTPException, UnicodeDecodeError) as e:
391 _log(f"Failed to fetch HN kids for {object_id}: {e}")
392 return None
393 if not isinstance(data, dict):
394 return None
395 kids = data.get("kids")
396 if not isinstance(kids, list):
397 return None
398 return kids
399
400
401 def _order_comments_by_kids(
402 comments: List[Dict[str, Any]],
403 kids: List[Any],
404 ) -> List[Dict[str, Any]]:
405 """Reorder Algolia children to match HN `kids` order; unknowns keep relative order."""
406 by_id: Dict[Any, Dict[str, Any]] = {}
407 for comment in comments:
408 cid = comment.get("id")
409 if cid is not None and cid not in by_id:
410 by_id[cid] = comment
411 ordered: List[Dict[str, Any]] = []
412 seen = set()
413 for kid in kids:
414 comment = by_id.get(kid)
415 if comment is not None:
416 ordered.append(comment)
417 seen.add(kid)
418 for comment in comments:
419 cid = comment.get("id")
420 if cid not in seen:
421 ordered.append(comment)
422 return ordered
423
424
425 def _fetch_item_comments(object_id: str, max_comments: int = 5) -> Dict[str, Any]:
426 """Fetch top-level comments for a story from Algolia items endpoint.
427
428 Args:
429 object_id: HN story ID
430 max_comments: Max comments to return
431
432 Returns:
433 Dict with 'comments' list and 'comment_insights' list.
434 """
435 url = f"{ALGOLIA_ITEM_URL}/{object_id}"
436
437 try:
438 data = http.request("GET", url, timeout=15)
439 except Exception as e:
440 _log(f"Failed to fetch comments for {object_id}: {e}")
441 return {"comments": [], "comment_insights": []}
442
443 children = data.get("children", [])
444
445 # Filter to actual comments. Prefer HN's Firebase `kids` order (#1285);
446 # Algolia children have null points, so a points sort is a no-op and leaves
447 # earliest-posted replies first. Fall back to points only when kids is unavailable.
448 real_comments = [
449 c for c in children
450 if c.get("text") and c.get("author")
451 ]
452 kids = _fetch_hn_kids(object_id)
453 if kids is not None:
454 real_comments = _order_comments_by_kids(real_comments, kids)
455 else:
456 real_comments.sort(key=lambda c: c.get("points") or 0, reverse=True)
457
458 comments = []
459 insights = []
460 # A quote links to where it was said: the comment's own permalink, else the
461 # story's discussion page -- never the article URL.
462 discussion_url = _hn_item_url(object_id)
463 for c in real_comments[:max_comments]:
464 text = _strip_html(c.get("text", ""))
465 excerpt = text[:300] + "..." if len(text) > 300 else text
466 comment_id = c.get("id")
467 comments.append({
468 "author": c.get("author", ""),
469 "text": excerpt,
470 "points": c.get("points"),
471 "url": _hn_item_url(comment_id) if comment_id else discussion_url,
472 })
473 # First sentence as insight
474 first_sentence = text.split(". ")[0].split("\n")[0][:200]
475 if first_sentence:
476 insights.append(first_sentence)
477
478 return {"comments": comments, "comment_insights": insights}
479
480
481 def enrich_top_stories(
482 items: List[Dict[str, Any]],
483 depth: str = "default",
484 ) -> List[Dict[str, Any]]:
485 """Fetch comments for top N stories by points.
486
487 Args:
488 items: Parsed HN items
489 depth: Research depth (controls how many to enrich)
490
491 Returns:
492 Items with top_comments and comment_insights added.
493 """
494 if not items:
495 return items
496
497 limit = ENRICH_LIMITS.get(depth, ENRICH_LIMITS["default"])
498
499 # Sort by points to enrich the most popular stories
500 by_points = sorted(
501 range(len(items)),
502 key=lambda i: items[i].get("engagement", {}).get("points") or 0,
503 reverse=True,
504 )
505 to_enrich = by_points[:limit]
506
507 _log(f"Enriching top {len(to_enrich)} stories with comments")
508
509 with ThreadPoolExecutor(max_workers=5) as executor:
510 # submit_with_context, not executor.submit: a plain submit drops the
511 # pipeline's capture_failures() sink, so failed or rate-limited item
512 # fetches would vanish and the HN source would look fully enriched.
513 futures = {
514 http.submit_with_context(
515 executor,
516 _fetch_item_comments,
517 items[idx]["id"],
518 ): idx
519 for idx in to_enrich
520 }
521
522 for future in as_completed(futures):
523 idx = futures[future]
524 try:
525 result = future.result(timeout=15)
526 items[idx]["top_comments"] = result["comments"]
527 items[idx]["comment_insights"] = result["comment_insights"]
528 except (KeyError, TypeError, OSError) as exc:
529 _log(f"Comment enrichment failed for story {items[idx].get('id', '?')}: {type(exc).__name__}: {exc}")
530 items[idx]["top_comments"] = []
531 items[idx]["comment_insights"] = []
532
533 return items
534
534 lines PYTHON