返回 last30days-skill
quality_nudge.py
根目录 / skills / last30days / scripts / lib / quality_nudge.py
1 """Post-research quality score and upgrade nudge.
2
3 Computes a quality score based on the non-blocking core sources and builds
4 a nudge message describing what the user missed and how to fix it.
5
6 Fix text comes from ``lib.prescriptions`` (the single remediation
7 vocabulary shared with the doctor command, KTD 7); only the trigger
8 logic and the message framing live here.
9 """
10
11 from typing import List, Optional
12
13 from . import env, health, http, prescriptions, x_envelope
14
15
16 # Sources whose absence can justify a post-run quality repair. X remains a
17 # supported source, but it is optional: declining cookie access must not turn a
18 # successful multi-source run into a setup prompt or a lower quality grade.
19 CORE_SOURCES = ["hn", "polymarket", "x", "youtube", "reddit"]
20
21 # Labels for display
22 SOURCE_LABELS = {
23 "hn": "Hacker News",
24 "polymarket": "Polymarket",
25 "x": "X/Twitter",
26 "youtube": "YouTube",
27 "reddit": "Reddit",
28 }
29
30
31 def _is_x_active(config: dict, research_results: dict) -> bool:
32 """Check if X source is active (has credentials AND didn't error)."""
33 if "x" in (research_results.get("active_sources") or []):
34 return not bool(research_results.get("x_error"))
35 has_creds = _has_x_credentials(config)
36 if not has_creds:
37 return False
38 # If X errored this run, it's configured but broken
39 if research_results.get("x_error"):
40 return False
41 return True
42
43
44 def _has_x_credentials(config: dict) -> bool:
45 """Return True when any X/Twitter source credential is configured.
46
47 ``X_BEARER_TOKEN`` counts where the xapi backend can actually run: an
48 official-only host (it heads the auto chain there) or an explicit xapi
49 pin. An ambient bearer on any other host is not a configured X source,
50 so nothing changes there.
51 """
52 if (
53 config.get("AUTH_TOKEN")
54 or config.get("XAI_API_KEY")
55 or config.get("XQUIK_API_KEY")
56 ):
57 return True
58 if config.get("X_BEARER_TOKEN"):
59 return "xapi" in env.x_auto_chain(config) or env.x_backend_pin(config) == "xapi"
60 return False
61
62
63 def _x_error_prescription(config: dict, research_results: dict) -> prescriptions.Prescription:
64 """The fix for a configured X that errored, routed through the X policy.
65
66 The pipeline stamps the failed backend into ``x_error`` or
67 ``x_degraded_error``, sometimes behind a simplified-query retry label.
68 Use that runtime provenance before the host policy.
69 """
70 message = str(research_results.get("x_error") or research_results.get("x_degraded_error") or "")
71 if message.startswith(x_envelope.DETAIL_NOT_PASSED):
72 # The model declared the X connector lane and passed no envelope:
73 # the fix is the connector, on any host.
74 return prescriptions.for_x(config, "connector_missing")
75 backend_error = message.removeprefix("Simplified-query retry failed: ")
76 backend_error = backend_error.removeprefix("All X backends failed — ")
77 if backend_error.startswith("X served via "):
78 served_backend, separator, origin_error = backend_error.removeprefix("X served via ").partition(" after ")
79 if separator:
80 backend_error = origin_error.split(f"; {served_backend}", 1)[0]
81 if backend_error.startswith("xai:"):
82 state = http.classify_failure(message=backend_error)
83 if state == health.PAYMENT_REQUIRED:
84 failure = "xai_payment_required"
85 elif state == health.RATE_LIMITED:
86 failure = "xai_rate_limited"
87 elif state == health.TIMEOUT:
88 failure = "xai_timeout"
89 elif state == health.AUTH_FAILED or "model" in backend_error.lower():
90 failure = "xai_error"
91 else:
92 failure = "xai_unavailable"
93 return prescriptions.for_x(config, failure)
94 failure = "cookies_expired"
95 if env.x_policy(config).hint_namespace == "official":
96 if http.classify_failure(message=message) == health.PAYMENT_REQUIRED:
97 failure = "payment_required"
98 return prescriptions.for_x(config, failure)
99
100
101 def _has_ytdlp() -> bool:
102 """Return True when the local/free YouTube lane is available."""
103 try:
104 from . import youtube_yt
105 return bool(youtube_yt.is_ytdlp_installed())
106 except Exception:
107 return False
108
109
110 def _youtube_returned_data(research_results: dict) -> bool:
111 """Return True when YouTube produced usable items through any provider."""
112 videos = int(research_results.get("youtube_videos_count") or 0)
113 transcripts = int(research_results.get("youtube_transcripts_count") or 0)
114 return videos > 0 or transcripts > 0
115
116
117 def _is_youtube_active(config: dict, research_results: dict, *, has_ytdlp: bool) -> bool:
118 """Check if YouTube source is active (yt-dlp installed)."""
119 if not has_ytdlp:
120 return False
121 if research_results.get("youtube_error"):
122 return False
123 return True
124
125
126 # Below this transcript-fetch ratio, YouTube is considered "degraded" rather
127 # than active. Picked at 50% so a single legitimate caption-disabled video in a
128 # multi-video result does not trip the nudge, but a stale-yt-dlp run that fails
129 # every transcript does. Tunable via DEGRADED_TRANSCRIPT_THRESHOLD env var if
130 # operators need to adjust without code changes.
131 DEFAULT_DEGRADED_TRANSCRIPT_THRESHOLD = 0.5
132
133
134 def _is_youtube_degraded(research_results: dict, threshold: float) -> bool:
135 """YouTube is degraded when videos were returned but the transcript-fetch
136 ratio is below threshold. The canonical cause is a stale yt-dlp binary -
137 YouTube's caption format changes frequently and old binaries silently fail
138 every transcript while the search itself still succeeds.
139
140 Captions-disabled videos are subtracted from the denominator: an uploader
141 who turned off captions can never produce a transcript, so counting that
142 video toward "fetch failures" produces false positives. A single
143 captions-disabled video in a small result set was tripping the nudge.
144
145 When actual fetch outcomes are available, they take precedence over the
146 post-pruning ratio: the report counts only see items that survived
147 freshness/relevance pruning, so a run where every transcript fetch
148 succeeded but the fetched videos were later pruned looks identical to a
149 stale-binary run (#531). Zero failures across attempted fetches proves
150 the binary works - don't flag.
151 """
152 videos = int(research_results.get("youtube_videos_count") or 0)
153 transcripts = int(research_results.get("youtube_transcripts_count") or 0)
154 captions_disabled = int(research_results.get("youtube_captions_disabled_count") or 0)
155 if videos <= 0:
156 return False
157 fetch_attempts = int(research_results.get("youtube_transcript_fetch_attempts") or 0)
158 fetch_failures = int(research_results.get("youtube_transcript_fetch_failures") or 0)
159 if fetch_attempts > 0 and fetch_failures == 0:
160 return False
161 eligible = videos - captions_disabled
162 if eligible <= 0:
163 # Every returned video had captions disabled - upstream content fact,
164 # not a yt-dlp problem. Don't flag.
165 return False
166 # The engine only tries for a few transcripts per search (the depth's
167 # transcript target), so judge against that, not every surviving video:
168 # 4 transcripts from 15 videos with a target of 2 is a healthy run.
169 target = int(research_results.get("youtube_transcript_target") or 0)
170 expected = min(target, eligible) if target > 0 else eligible
171 return (transcripts / expected) < threshold
172
173
174 def _youtube_bot_check_text(research_results: dict, *, has_sc: bool) -> str:
175 """The degraded-YouTube line when yt-dlp hit a YouTube bot check.
176
177 A bot check is YouTube refusing this network, so upgrading yt-dlp cannot
178 help; name the two fixes that do."""
179 videos = int(research_results.get("youtube_videos_count") or 0)
180 transcripts = int(research_results.get("youtube_transcripts_count") or 0)
181 rescued = int(research_results.get("youtube_sc_rescued") or 0)
182 if rescued:
183 rescue = f"ScrapeCreators rescued {rescued} of them. "
184 elif has_sc:
185 rescue = "ScrapeCreators rescued none of them. "
186 else:
187 rescue = ""
188 fixes = "route yt-dlp through a residential host with LAST30DAYS_YOUTUBE_SSH_HOST"
189 if not has_sc:
190 fixes += (
191 ", or add SCRAPECREATORS_API_KEY for the ScrapeCreators transcript "
192 "fallback"
193 )
194 return (
195 f"YouTube returned {videos} videos and {transcripts} transcripts: "
196 "YouTube bot-checked yt-dlp on this network. "
197 f"{rescue}This is a bot check, not a stale yt-dlp, so upgrading it "
198 f"won't help. To get more transcripts, {fixes}."
199 )
200
201
202 def _instagram_bonus_outcome(config: dict, research_results: dict) -> str | None:
203 """Return the bonus-source outcome for Instagram, or None when not applicable.
204
205 Returns:
206 ``"errored"`` — SC is configured, the source ran, and it returned an error
207 (e.g. HTTP 404 from the ScrapeCreators endpoint).
208 ``"no_items"`` — SC is configured, the source ran with no error, but returned
209 zero items (endpoint was live but had nothing for the query).
210 ``None`` — SC not configured, source excluded, or source not run this
211 invocation.
212 """
213 if not config.get("SCRAPECREATORS_API_KEY"):
214 return None
215 excluded = {
216 s.strip().lower()
217 for s in (config.get("EXCLUDE_SOURCES") or "").split(",")
218 if s.strip()
219 }
220 included = {
221 s.strip().lower()
222 for s in (config.get("INCLUDE_SOURCES") or "").split(",")
223 if s.strip()
224 }
225 if "instagram" in excluded or (included and "instagram" not in included):
226 return None
227 count = research_results.get("instagram_items_count")
228 if count is None:
229 return None # source not run this invocation
230 if int(count) == 0:
231 if research_results.get("instagram_error"):
232 return "errored"
233 return "no_items"
234 return None
235
236
237 def compute_quality_score(config: dict, research_results: dict) -> dict:
238 """Compute research quality score from the non-blocking core sources.
239
240 Args:
241 config: Configuration dict from env.get_config()
242 research_results: Dict with keys like x_error, youtube_error,
243 reddit_error reflecting what happened this run. Optional keys
244 ``youtube_videos_count`` and ``youtube_transcripts_count`` enable
245 degraded-YouTube detection (transcript-fetch ratio below threshold,
246 or fallback/provider data returned without local yt-dlp).
247 Optional keys ``instagram_items_count`` and ``instagram_error``
248 enable failed/no-items detection for the bonus Instagram source.
249 ``x_degraded_error``
250 carries a failed xAI lane when another backend served X items.
251
252 Returns:
253 {
254 "score_pct": 0-100,
255 "core_active": ["hn", "polymarket", ...],
256 "core_missing": ["youtube"],
257 "core_errored": [], # configured but errored at top level
258 "core_degraded": [], # configured and returned items but quality below threshold
259 "bonus_errored": [], # bonus sources (Instagram, etc.) configured but failed or returned no items
260 "nudge_text": "..." or None if all sources healthy
261 }
262 """
263 core_active: List[str] = []
264 core_missing: List[str] = []
265 core_errored: List[str] = []
266 core_degraded: List[str] = []
267 bonus_errored: List[str] = []
268
269 # HN, Polymarket, and Reddit are always active
270 core_active.append("hn")
271 core_active.append("polymarket")
272 core_active.append("reddit")
273
274 # X splits three ways. Active counts normally. Configured-but-errored is a
275 # real outage: it still docks the score and surfaces a repair, never an
276 # "optional omission". Only unconfigured/declined X leaves the denominator.
277 optional_omitted: List[str] = []
278 x_configured = _has_x_credentials(config) or (
279 "x" in (research_results.get("active_sources") or [])
280 )
281 if _is_x_active(config, research_results):
282 core_active.append("x")
283 if research_results.get("x_degraded_error"):
284 core_degraded.append("x")
285 elif x_configured and research_results.get("x_error"):
286 core_missing.append("x")
287 core_errored.append("x")
288 else:
289 optional_omitted.append("x")
290
291 # YouTube
292 has_ytdlp = _has_ytdlp()
293 yt_active = _is_youtube_active(config, research_results, has_ytdlp=has_ytdlp)
294 youtube_returned_data = _youtube_returned_data(research_results)
295 if yt_active:
296 core_active.append("youtube")
297 # Active means yt-dlp is installed and search did not error at the top
298 # level. But search-success + transcript-failure is the canonical
299 # stale-binary failure mode that the footer used to hide. Flag as
300 # degraded so the user gets an actionable nudge to update the binary.
301 threshold = float(config.get("DEGRADED_TRANSCRIPT_THRESHOLD") or DEFAULT_DEGRADED_TRANSCRIPT_THRESHOLD)
302 if _is_youtube_degraded(research_results, threshold):
303 core_degraded.append("youtube")
304 elif youtube_returned_data and not research_results.get("youtube_error"):
305 # YouTube produced data through a fallback/provider lane even though the
306 # local free yt-dlp lane is unavailable. Count the source as present,
307 # but surface it as degraded so users do not see the contradictory
308 # "Missing: YouTube" ending after a report with YouTube evidence.
309 # has_ytdlp is provably False here: yt_active is False and youtube_error
310 # is excluded by this guard, leaving unavailable yt-dlp as the cause.
311 core_active.append("youtube")
312 core_degraded.append("youtube")
313 else:
314 core_missing.append("youtube")
315 # Check if configured but errored (yt-dlp installed but failed this run)
316 if has_ytdlp and research_results.get("youtube_error"):
317 core_errored.append("youtube")
318
319 # Bonus sources (Instagram, etc.): SC-key holders expect content but the
320 # source can fail (HTTP 404) or return zero items without surfacing a
321 # clear signal in the brief. Track both outcomes separately.
322 _ig_outcome = _instagram_bonus_outcome(config, research_results)
323 if _ig_outcome == "errored":
324 bonus_errored.append("instagram:failed")
325 elif _ig_outcome == "no_items":
326 bonus_errored.append("instagram:no_items")
327
328 scored_source_count = len(CORE_SOURCES) - len(optional_omitted)
329 score_pct = int(len(core_active) / scored_source_count * 100)
330
331 has_sc = bool(config.get("SCRAPECREATORS_API_KEY"))
332 active_sources = research_results.get("active_sources") or []
333 x_fix = _x_error_prescription(config, research_results) if "x" in core_errored or "x" in core_degraded else None
334 nudge_text = _build_nudge_text(
335 core_missing,
336 core_errored,
337 core_degraded,
338 research_results,
339 has_sc=has_sc,
340 active_sources=active_sources,
341 bonus_errored=bonus_errored,
342 has_ytdlp=has_ytdlp,
343 core_total=scored_source_count,
344 x_fix=x_fix,
345 suggest_youtube_comments=(
346 not env.is_youtube_comments_available(
347 config, ytdlp_installed=has_ytdlp
348 )
349 and "youtube_comments" not in env.exclude_sources(config)
350 ),
351 ) if (core_missing or core_degraded or bonus_errored) else None
352
353 return {
354 "score_pct": score_pct,
355 "core_active": core_active,
356 "core_missing": core_missing,
357 "core_errored": core_errored,
358 "core_degraded": core_degraded,
359 "bonus_errored": bonus_errored,
360 "nudge_text": nudge_text,
361 }
362
363
364 def _build_nudge_text(
365 core_missing: List[str],
366 core_errored: List[str],
367 core_degraded: List[str] = None,
368 research_results: dict = None,
369 has_sc: bool = False,
370 active_sources: list = None,
371 bonus_errored: List[str] = None,
372 has_ytdlp: bool = False,
373 core_total: int | None = None,
374 x_fix: Optional[prescriptions.Prescription] = None,
375 suggest_youtube_comments: bool = False,
376 ) -> str:
377 """Build human-readable nudge text describing what was missed or degraded.
378
379 Prioritizes free suggestions. Optionally mentions bonus sources
380 (TikTok, Instagram, Threads, Pinterest) if ScrapeCreators key is configured.
381 YouTube comments are only listed when the opt-in can actually enable them:
382 not already available through yt-dlp or INCLUDE_SOURCES, and not switched
383 off with EXCLUDE_SOURCES.
384 """
385 lines: List[str] = []
386 core_degraded = core_degraded or []
387 bonus_errored = bonus_errored or []
388 research_results = research_results or {}
389
390 # Describe what was missed
391 missed_parts: List[str] = []
392 for src in core_missing:
393 label = SOURCE_LABELS[src]
394 if src in core_errored:
395 missed_parts.append(f"{label} (errored this run)")
396 else:
397 missed_parts.append(label)
398
399 effective_total = core_total if core_total is not None else len(CORE_SOURCES)
400 active_count = effective_total - len(core_missing)
401 lines.append(f"Research quality: {active_count}/{effective_total} core sources.")
402 if missed_parts:
403 lines.append(f"Missing: {', '.join(missed_parts)}.")
404 if core_degraded:
405 degraded_labels = ", ".join(SOURCE_LABELS[s] for s in core_degraded)
406 lines.append(f"Degraded: {degraded_labels}.")
407 if bonus_errored:
408 failed_sources = []
409 unavailable_sources = []
410 silent_sources = []
411 for s in bonus_errored:
412 if s == "instagram:failed":
413 failed_sources.append("Instagram")
414 elif s == "instagram:no_items":
415 unavailable_sources.append("Instagram")
416 else:
417 silent_sources.append(s.capitalize())
418 if failed_sources:
419 lines.append(f"Bonus source failed: {', '.join(failed_sources)}.")
420 if unavailable_sources:
421 lines.append(f"Bonus source unavailable: {', '.join(unavailable_sources)}.")
422 if silent_sources:
423 lines.append(f"Bonus source silent: {', '.join(silent_sources)}.")
424 lines.append("")
425
426 # Free suggestions
427 free_suggestions: List[str] = []
428
429 # A configured X that errored is the only X entry that can reach
430 # core_missing: unconfigured/declined X is an optional omission and never
431 # lands here. Surface the repair instead of hiding the outage.
432 if "x" in core_missing and "x" in core_errored:
433 if x_fix is None:
434 x_fix = prescriptions.get("x", "cookies_expired")
435 free_suggestions.append(f"X/Twitter errored - {x_fix.fix_nl}.")
436
437 if "x" in core_degraded:
438 if x_fix is None:
439 x_fix = prescriptions.get("x", "cookies_expired")
440 free_suggestions.append(f"X/Twitter used a backup - {x_fix.fix_nl}.")
441
442 if "youtube" in core_missing:
443 if "youtube" in core_errored:
444 yt_error = str(research_results.get("youtube_error") or "").strip()
445 # The engine's own stream timeout says nothing about the binary's
446 # age, so it must not prescribe an upgrade.
447 if http.classify_failure(message=yt_error) == health.TIMEOUT:
448 free_suggestions.append(
449 f"YouTube timed out ({yt_error}) - this is a timeout, "
450 "not a stale yt-dlp, so updating it won't help."
451 )
452 else:
453 yt_fix = prescriptions.get("youtube", "ytdlp_stale")
454 free_suggestions.append(
455 f"YouTube errored - update yt-dlp: {yt_fix.fix_cli}"
456 )
457 else:
458 yt_fix = prescriptions.get("youtube", "ytdlp_missing")
459 free_suggestions.append(
460 "YouTube: video transcripts with key moments - often the deepest "
461 f"explanations on any topic. Install yt-dlp: {yt_fix.fix_cli} (free)"
462 )
463
464 if "youtube" in core_degraded:
465 videos = int(research_results.get("youtube_videos_count") or 0)
466 transcripts = int(research_results.get("youtube_transcripts_count") or 0)
467 captions_disabled = int(research_results.get("youtube_captions_disabled_count") or 0)
468 if not has_ytdlp and _youtube_returned_data(research_results):
469 install = prescriptions.get("youtube", "ytdlp_missing")
470 # Tolerant lookup: alt_cli makes no arity promise, so an entry
471 # gaining/losing a platform alternate must degrade the wording,
472 # never crash the nudge path.
473 scoop_install = install.alt_cli[0] if len(install.alt_cli) > 0 else install.fix_cli
474 pip_install = install.alt_cli[1] if len(install.alt_cli) > 1 else scoop_install
475 free_suggestions.append(
476 f"YouTube returned {videos} videos and {transcripts} transcripts "
477 "through a fallback/provider path, but local yt-dlp is not "
478 "installed. Install yt-dlp to enable the free local YouTube lane "
479 f"and reduce reliance on fallback providers: {install.fix_cli} "
480 f"(macOS), {scoop_install} (Windows), or {pip_install}."
481 )
482 elif int(research_results.get("youtube_bot_checked") or 0) > 0:
483 free_suggestions.append(
484 _youtube_bot_check_text(research_results, has_sc=has_sc)
485 )
486 else:
487 captions_note = ""
488 if captions_disabled > 0:
489 captions_note = (
490 f" ({captions_disabled} of those had captions disabled by the "
491 "uploader, which is a separate cause and not fixable on your end)"
492 )
493 update = prescriptions.get("youtube", "ytdlp_stale")
494 # Same tolerant lookup as the install branch above.
495 scoop_update = update.alt_cli[0] if len(update.alt_cli) > 0 else update.fix_cli
496 pip_update = update.alt_cli[1] if len(update.alt_cli) > 1 else scoop_update
497 free_suggestions.append(
498 f"YouTube returned {videos} videos but only {transcripts} transcripts "
499 f"captured{captions_note}. The most common remaining cause is a stale "
500 "yt-dlp binary - YouTube's caption format changes frequently and old "
501 "binaries silently fail every transcript. Update via your package "
502 f"manager: {scoop_update} (Windows), {update.fix_cli} (macOS), "
503 f"or {pip_update}."
504 )
505
506 if "instagram:failed" in bonus_errored or "instagram:no_items" in bonus_errored:
507 free_suggestions.append(
508 "Instagram returned 0 reels despite SC being configured. SC's "
509 "v2 reels endpoint wraps Google Search and 500's frequently on "
510 "multi-token queries. The skill now retries with hashtag-form "
511 "automatically; if zero items still appear, the topic may have "
512 "no reel coverage on Instagram. Try a single-word topic like "
513 "the most distinctive noun in your query."
514 )
515
516 # Mention bonus opt-in sources when SC key is present
517 if has_sc:
518 bonus_hints = []
519 if "threads" not in (active_sources or []):
520 bonus_hints.append("Threads")
521 if "pinterest" not in (active_sources or []):
522 bonus_hints.append("Pinterest")
523 if suggest_youtube_comments:
524 bonus_hints.append("YouTube comments")
525 if bonus_hints:
526 free_suggestions.append(
527 f"Your SC key also powers {', '.join(bonus_hints)}. "
528 "Add them to INCLUDE_SOURCES in your .env to enable."
529 )
530
531 if free_suggestions:
532 lines.append("Free fixes:")
533 for s in free_suggestions:
534 lines.append(f" - {s}")
535 lines.append("")
536
537 # Bonus sources mention (non-blocking)
538 if not has_sc:
539 lines.append(
540 "Bonus: TikTok and Instagram are available with a free "
541 "ScrapeCreators key at scrapecreators.com (no affiliation)."
542 )
543 else:
544 lines.append("last30days has no affiliation with any API provider.")
545
546 return "\n".join(lines)
547
547 lines PYTHON