返回 last30days-skill
doctor.py
根目录 / skills / last30days / scripts / lib / doctor.py
1 """Unified `doctor` health surface: aggregate, tier rollup, render (U4).
2
3 One command answers "what's broken, what's serving, and what do I run to
4 fix it" by composing the existing health layers instead of replacing them:
5
6 - U1 ``lib/health.py`` dependency probes (ok/missing/broken/timeout)
7 - U2 ``lib/backends.py`` chain descriptors + "will use" prediction
8 - U3 ``lib/prescriptions.py`` the single remediation vocabulary
9 - ``lib/pipeline.diagnose`` + ``lib/permission_preflight`` for the
10 engine-level availability and permission summary
11
12 The legacy ``--diagnose`` / ``--preflight`` flags keep their frozen JSON
13 shapes (see ``tests/test_diagnose_compat.py``); anything new appears ONLY
14 in ``doctor --json``.
15
16 Tier rollup (the R1 machine contract). Per source, ``tier`` is the
17 four-value rollup and ``status`` preserves the most specific state:
18
19 | condition | status | tier |
20 |------------------------------------------------------|---------------|-------|
21 | probes pass, credentials (if any) present | ok | ok |
22 | usable but degraded (fallback serving, partial) | degraded | warn |
23 | opt-in not enabled / key-gated unconfigured | opt-in / | off |
24 | | unconfigured | |
25 | configured but missing / broken / timeout / error | that status | error |
26
27 Semantics and guarantees:
28
29 - ``active_backend`` is a PREDICTION ("will use"), never an observation
30 (KTD 4). Reddit is conditional mode: honest wording, no single winner.
31 - On a native-search host with no web keys, engine-side web search is
32 intentionally off — doctor reports tier ``off`` with a host-native note,
33 never a false-alarm error. Web search has NO env pin, only the
34 ``--web-backend`` flag; the record says so.
35 - No cookie reads (plan-only, like ``--diagnose``); no secret values
36 anywhere — key presence is booleans only.
37 - Per-source exception isolation: one failing probe becomes that source's
38 ``error`` record; it can never blank the report.
39 - Reporting problems is a successful run: the exit code is always 0.
40 """
41
42 from __future__ import annotations
43
44 import concurrent.futures
45 import datetime
46 import hashlib
47 import json
48 import os
49 import shutil
50 import stat
51 import sys
52 import time
53 import urllib.error
54 import urllib.request
55 from pathlib import Path
56 from typing import Any, Callable, Dict, List, Optional
57
58 from . import (
59 backends,
60 brightdata,
61 deepline,
62 digg,
63 env,
64 health,
65 http,
66 prescriptions,
67 private_files,
68 proxy,
69 reddit_health,
70 rust_accel,
71 trustpilot,
72 x_api,
73 )
74 from .backends import TIER_ERROR, TIER_OK, TIER_WARN
75
76 # Rollup tiers (R1). ok/warn/error are U2's; only "off" is doctor's own.
77 TIER_OFF = "off"
78
79 # Specific statuses and the rollup row each maps to. The doctor-local
80 # statuses "opt-in" and "unconfigured" have no health constant.
81 TIER_BY_STATUS: Dict[str, str] = {
82 health.OK: TIER_OK,
83 health.DEGRADED: TIER_WARN,
84 "opt-in": TIER_OFF,
85 "unconfigured": TIER_OFF,
86 "excluded": TIER_OFF,
87 health.MISSING: TIER_ERROR,
88 health.BROKEN: TIER_ERROR,
89 health.TIMEOUT: TIER_ERROR,
90 health.ERROR: TIER_ERROR,
91 }
92
93 # Tier -> glyph, still used by the cached-report shape validator to confirm a
94 # record carries a known tier. The user-facing render uses AUDIT_GLYPHS below.
95 GLYPHS = {TIER_OK: "✓", TIER_WARN: "!", TIER_OFF: "○", TIER_ERROR: "✗"}
96
97 # Four-state audit (R1). A presentation layer derived from the tier rollup +
98 # last-run evidence + optional live probe - it augments the per-source records,
99 # it does not replace them (the tier/status fields stay in the record and JSON).
100 AUDIT_WORKING = "working"
101 AUDIT_UNVERIFIED = "unverified"
102 AUDIT_NOT_WORKING = "not-working"
103 AUDIT_COULD_BE_ON = "could-be-on"
104
105 AUDIT_GLYPHS = {
106 AUDIT_WORKING: "●", # ●
107 AUDIT_UNVERIFIED: "◐", # ◐
108 AUDIT_NOT_WORKING: "✕", # ✕
109 AUDIT_COULD_BE_ON: "○", # ○
110 }
111
112 AUDIT_GROUPS = (
113 (AUDIT_WORKING, "WORKING"),
114 (AUDIT_UNVERIFIED, "TURNED ON - UNVERIFIED"),
115 (AUDIT_NOT_WORKING, "NOT WORKING"),
116 (AUDIT_COULD_BE_ON, "COULD BE ON"),
117 )
118
119 # Sources that need neither credentials nor a CLI: they always serve, so with
120 # no run evidence and no probe they are WORKING, not UNVERIFIED. Reddit is not
121 # one: every anonymous Reddit route closed in 2026, and its keyless floor rides
122 # third-party web search and an archive that can each refuse this network, so
123 # it is WORKING only on run or probe evidence.
124 KEYLESS_ALWAYS_ON = frozenset(
125 {"hackernews", "polymarket", "github", "library"}
126 )
127
128 # Fresh-run outcome states -> audit bucket for a tier-ok source. Anything not
129 # listed here (error / timeout / rate-limited / auth-failed / unreachable /
130 # schema-drift) means the source ran and failed -> NOT WORKING.
131 _RUN_WORKING_STATES = frozenset({health.OK, health.NO_RESULTS})
132 _RUN_UNVERIFIED_STATES = frozenset({health.PARTIAL, health.SKIPPED_UNCONFIGURED})
133
134
135 def audit_state(
136 name: str,
137 record: Dict[str, Any],
138 run_outcome: Optional[Dict[str, Any]] = None,
139 probe_result: Optional[Dict[str, Any]] = None,
140 ) -> str:
141 """Map a source's (tier, run evidence, probe) to one of four audit states.
142
143 Precedence: a failing/degraded tier is NOT WORKING regardless of history;
144 an off tier (opt-in / unconfigured) is COULD BE ON. For a tier-ok source,
145 fresh run evidence wins (ok/no-results -> WORKING; partial/skipped ->
146 UNVERIFIED; any error/timeout/rate-limit/etc -> NOT WORKING), then a live
147 probe, then the keyless-always-on fallback, else UNVERIFIED.
148 """
149 tier = record.get("tier")
150 if tier in (TIER_ERROR, TIER_WARN):
151 return AUDIT_NOT_WORKING
152 if tier == TIER_OFF:
153 return AUDIT_COULD_BE_ON
154 # tier ok
155 if run_outcome:
156 state = run_outcome.get("state")
157 if state in _RUN_WORKING_STATES:
158 return AUDIT_WORKING
159 if state in _RUN_UNVERIFIED_STATES:
160 return AUDIT_UNVERIFIED
161 return AUDIT_NOT_WORKING
162 if probe_result is not None:
163 if probe_result.get("partial"):
164 return AUDIT_UNVERIFIED
165 if probe_result.get("ok"):
166 return AUDIT_WORKING
167 # A transient refusal (host rate-limited THIS probe) is not evidence the
168 # source is broken: the lane retries with backoff and serves fine. Report
169 # it as unverified instead of claiming a working source is down.
170 if probe_result.get("transient"):
171 return AUDIT_UNVERIFIED
172 return AUDIT_NOT_WORKING
173 if name in KEYLESS_ALWAYS_ON:
174 return AUDIT_WORKING
175 return AUDIT_UNVERIFIED
176
177 # Report order: chained sources first, then free, then key-gated/opt-in.
178 SOURCE_ORDER = (
179 "reddit",
180 "x",
181 "youtube",
182 "web",
183 "hackernews",
184 "polymarket",
185 "github",
186 "devto",
187 "v2ex",
188 "juejin",
189 "digg",
190 "techmeme",
191 "news_rss",
192 "arxiv",
193 "yahoo_finance",
194 "trustpilot",
195 "amazon",
196 "meta_ads",
197 "tiktok",
198 "instagram",
199 "threads",
200 "telegram",
201 "bluesky",
202 "truthsocial",
203 "perplexity",
204 "linkedin",
205 "deepline",
206 "pinterest",
207 "xiaohongshu",
208 "jobs",
209 "patents",
210 "library",
211 )
212
213 # Sources whose availability depends on a downloaded CLI binary. doctor probes
214 # each (installed AND functional, via health.probe_dependency) and surfaces a
215 # per-source marker plus a dedicated CLI-health block (R2). Everything not
216 # listed is keyless - it needs no CLI. gh is OPTIONAL for GitHub (the REST tier
217 # works without it), so its absence is a note, never a failure.
218 CLI_DEPENDENCIES = {
219 "youtube": "yt-dlp",
220 "digg": "digg-pp-cli",
221 "techmeme": "techmeme-pp-cli",
222 "news_rss": "news-rss-pp-cli",
223 "arxiv": "arxiv-pp-cli",
224 "yahoo_finance": "yahoo-finance-pp-cli",
225 "trustpilot": "trustpilot-pp-cli",
226 # The only entry that also needs auth; _amazon_record reports the
227 # installed-but-unauthenticated state the shared CLI helper cannot.
228 "amazon": "brightdata",
229 "github": "gh",
230 }
231 _OPTIONAL_CLI_SOURCES = frozenset({"github"})
232
233 # Key-presence booleans for the setup block. NEVER values.
234 KEY_PRESENCE_VARS = (
235 "SCRAPECREATORS_API_KEY",
236 "XAI_API_KEY",
237 "XQUIK_API_KEY",
238 "X_BEARER_TOKEN",
239 "DEEPLINE_API_KEY",
240 "BRIGHTDATA_API_KEY",
241 "BRAVE_API_KEY",
242 "EXA_API_KEY",
243 "SERPER_API_KEY",
244 "PARALLEL_API_KEY",
245 "GROQ_API_KEY",
246 "OPENAI_API_KEY",
247 "GOOGLE_API_KEY",
248 "GEMINI_API_KEY",
249 "GOOGLE_GENAI_API_KEY",
250 "OPENROUTER_API_KEY",
251 "PERPLEXITY_API_KEY",
252 "GITHUB_TOKEN",
253 "TRUTHSOCIAL_TOKEN",
254 "BSKY_APP_PASSWORD",
255 )
256
257 # Failing statuses ranked most-specific-first for chained rollups: a broken
258 # shim outranks a timeout outranks a generic error when naming the source's
259 # status (all three roll up to tier error regardless).
260 _SPECIFIC_FAILURES = (health.BROKEN, health.TIMEOUT, health.ERROR)
261
262
263 def _fix_text(entry: prescriptions.Prescription) -> str:
264 """Render a registry entry as one actionable fix line (NL + CLI forms)."""
265 if entry.fix_cli and entry.fix_cli not in entry.fix_nl:
266 return f"{entry.fix_nl} (cli: {entry.fix_cli})"
267 return entry.fix_nl
268
269
270 def _record(
271 *,
272 status: str,
273 mode: str = "single",
274 backends_list: Optional[List[Dict[str, Any]]] = None,
275 active_backend: Optional[str] = None,
276 fix: str = "",
277 requires: str = "",
278 note: str = "",
279 detail: str = "",
280 pin_var: Optional[str] = None,
281 pin_flag: Optional[str] = None,
282 pinned: bool = False,
283 ) -> Dict[str, Any]:
284 return {
285 "tier": TIER_BY_STATUS[status],
286 "status": status,
287 "mode": mode,
288 "backends": backends_list,
289 "active_backend": active_backend,
290 "fix": fix,
291 "requires": requires,
292 "note": note,
293 "detail": detail,
294 "pin_var": pin_var,
295 "pin_flag": pin_flag,
296 "pinned": pinned,
297 }
298
299
300 # ---------------------------------------------------------------------------
301 # Chained sources (via U2 descriptors)
302 # ---------------------------------------------------------------------------
303
304 def _finding_json(finding: backends.BackendFinding) -> Dict[str, Any]:
305 return {
306 "name": finding.name,
307 "status": finding.status,
308 "detail": finding.detail,
309 "requires": finding.requires,
310 "fix": finding.prescription,
311 }
312
313
314 def _host_native_web_note(config: Dict[str, Any]) -> str:
315 """Doctor-local note when the host's own web search serves this run.
316
317 Keys on LAST30DAYS_NATIVE_SEARCH (via env.is_native_search) AND on
318 CLAUDECODE as a host signal - Claude Code always exposes a web-search tool,
319 but `doctor` run in a plain shell never sees the LAST30DAYS_NATIVE_SEARCH
320 the engine exports only for its own run, so without the CLAUDECODE signal it
321 would mislabel a fine setup as "degraded/keyless". Messaging only: it does
322 not change env.is_native_search or the engine's keyless-floor behavior. The
323 note names the signal actually detected so it never cites an env var the
324 user did not set.
325 """
326 if env.is_native_search(config):
327 return (
328 "host-native search active (LAST30DAYS_NATIVE_SEARCH): the host's "
329 "own web search serves this run; set a web key only if you want "
330 "engine-side web search"
331 )
332 if config.get("CLAUDECODE") or os.environ.get("CLAUDECODE"):
333 return (
334 "host-native web search active (Claude Code): the host's own web "
335 "search serves this run; set a web key only if you want "
336 "engine-side web search"
337 )
338 return ""
339
340
341 def _chained_record(source: str, config: Dict[str, Any]) -> Dict[str, Any]:
342 descriptor = backends.get_descriptor(source)
343 res = backends.resolve(source, config)
344 findings_json = [_finding_json(f) for f in res.findings]
345 common = dict(
346 mode=res.mode,
347 backends_list=findings_json,
348 active_backend=res.active_backend,
349 pin_var=descriptor.pin_var,
350 pin_flag=descriptor.pin_flag,
351 pinned=res.pinned,
352 )
353
354 if res.mode == backends.MODE_CONDITIONAL:
355 # Reddit: honest conditional wording (U2, verbatim), never a winner.
356 return _record(status=health.OK, note=res.conditional,
357 requires=res.findings[0].requires if res.findings else "",
358 **common)
359
360 by_name = {f.name: f for f in res.findings}
361 if res.tier == backends.TIER_OK:
362 active = by_name.get(res.active_backend)
363 return _record(status=health.OK, note=res.summary,
364 requires=active.requires if active else "", **common)
365
366 # Doctor-local (KTD-3): on a host that brings its own web search, the
367 # engine's web lanes (keyless floor or nothing configured) are intentionally
368 # dormant - report that, not an alarming "degraded/keyless". This must run
369 # before the WARN branch, because the keyless floor resolves to WARN and
370 # would otherwise return first. Messaging only; it never touches
371 # env.is_native_search or the engine's keyless-floor runtime behavior.
372 if source == "web":
373 host_note = _host_native_web_note(config)
374 if host_note:
375 return _record(
376 status="unconfigured",
377 note=host_note,
378 requires=res.findings[0].requires if res.findings else "",
379 **common,
380 )
381
382 if res.tier == backends.TIER_WARN:
383 active = by_name.get(res.active_backend)
384 return _record(status=health.DEGRADED, note=res.summary,
385 detail=active.detail if active else "",
386 fix=res.prescription,
387 requires=active.requires if active else "", **common)
388
389 # res.tier == error: when explicitly pinned, attribute status/detail/requires/fix
390 # strictly to the pinned backend rather than unrelated chain entries.
391 if res.pinned and res.pin in by_name:
392 pinned_finding = by_name[res.pin]
393 pin_status = (
394 pinned_finding.status
395 if pinned_finding.status in TIER_BY_STATUS
396 else health.ERROR
397 )
398 return _record(
399 status=pin_status,
400 fix=pinned_finding.prescription or res.prescription,
401 detail=pinned_finding.detail,
402 requires=pinned_finding.requires,
403 **common,
404 )
405
406 # Unpinned error: separate "nothing configured" (tier off) from
407 # "configured but broken" (tier error).
408 if res.findings and all(f.status == health.MISSING for f in res.findings):
409 return _record(
410 status="unconfigured",
411 fix=res.prescription,
412 requires=res.findings[0].requires if res.findings else "",
413 note=f"no backend configured (chain: {' -> '.join(res.chain)})",
414 **common,
415 )
416 # Something IS configured/installed but won't serve: name the most
417 # specific failure in chain order.
418 status = health.ERROR
419 fix = res.prescription
420 detail = ""
421 failed: Optional[backends.BackendFinding] = None
422 for wanted in _SPECIFIC_FAILURES:
423 failed = next((f for f in res.findings if f.status == wanted), None)
424 if failed is not None:
425 status = wanted
426 fix = failed.prescription or res.prescription
427 detail = failed.detail
428 break
429 # Mirror the OK/WARN branches: the requirement named is the FAILED
430 # backend's, not chain[0]'s (which may be a different, merely-missing
431 # backend when the failure came from later in the chain).
432 return _record(status=status, fix=fix, detail=detail,
433 requires=failed.requires if failed
434 else (res.findings[0].requires if res.findings else ""),
435 **common)
436
437
438 # ---------------------------------------------------------------------------
439 # Single-backend sources
440 # ---------------------------------------------------------------------------
441
442 def _sc_fix() -> str:
443 return _fix_text(prescriptions.get("scrapecreators", "key_missing"))
444
445
446 def _sc_key_detail(config: Dict[str, Any]) -> str:
447 """How the ScrapeCreators lane is keyed: the user's key or the API key proxy."""
448 if proxy.is_sentinel(config.get("SCRAPECREATORS_API_KEY")):
449 return "ScrapeCreators via API key"
450 return "SCRAPECREATORS_API_KEY present"
451
452
453 def _sc_gated_record(config: Dict[str, Any], purpose: str) -> Dict[str, Any]:
454 if config.get("SCRAPECREATORS_API_KEY"):
455 return _record(status=health.OK, requires="SCRAPECREATORS_API_KEY",
456 detail=f"{_sc_key_detail(config)} ({purpose})")
457 if purpose in ("tiktok", "instagram") and env.is_shortform_oss_available(config, purpose):
458 return _record(
459 status=health.OK,
460 requires="yt-dlp + web discovery (SearXNG/Serper/Exa/Brave/keyless floor/host search)",
461 detail=_shortform_keyless_detail(config, purpose),
462 )
463 return _record(status="unconfigured", requires="SCRAPECREATORS_API_KEY",
464 fix=_sc_fix())
465
466
467 def _shortform_keyless_detail(config: Dict[str, Any], purpose: str) -> str:
468 """Which discovery sources the keyless lane has, and how much to expect.
469
470 Exa serves no Instagram posts, so its key is not listed there.
471 """
472 armed = ", ".join(env.shortform_discovery_sources(config, purpose))
473 if purpose == "instagram":
474 return (
475 f"keyless lane armed via {armed}; best effort, low recall (public pages, "
476 "no views or comments); ScrapeCreators key absent"
477 )
478 comments = ("top comments from the public endpoint" if env.is_tiktok_public_comments_on(config)
479 else "comments off")
480 return (f"keyless lane armed via {armed}; {comments}; finds videos through "
481 "creators, not keyword search; ScrapeCreators key absent")
482
483
484 def _sc_optin_record(config: Dict[str, Any], source: str, purpose: str) -> Dict[str, Any]:
485 """SC-gated source that ALSO requires an INCLUDE_SOURCES opt-in to run.
486
487 Unlike ``_sc_gated_record`` (used by the on-by-default TikTok/Instagram),
488 a key alone is not enough here: the pipeline only fires this source when it
489 is in INCLUDE_SOURCES. Reporting a bare key as Ready is the Threads
490 false-Ready bug - this mirrors ``_linkedin_record``'s correct gating so
491 doctor and the pipeline cannot disagree.
492 """
493 requires = f"SCRAPECREATORS_API_KEY + INCLUDE_SOURCES={source}"
494 if not config.get("SCRAPECREATORS_API_KEY"):
495 return _record(status="unconfigured", requires=requires, fix=_sc_fix())
496 if source in env.include_sources(config):
497 return _record(status=health.OK, requires=requires,
498 detail=f"{_sc_key_detail(config)} ({purpose})")
499 return _record(
500 status="opt-in", requires=requires,
501 fix=f"add {source} to INCLUDE_SOURCES (or request it via --search {source})",
502 note="key present; opt-in, never auto-activates",
503 )
504
505
506 def _reddit_record(config):
507 return _chained_record("reddit", config)
508
509
510 # Official-path wording. The bearer path is never described as
511 # parity with the connector lane.
512 X_BEARER_CAVEAT = x_api.BEARER_COVERAGE_NOTE
513 X_CONNECTOR_NOTE = "will use: built-in X tools or X connector (host-fetched at run time)"
514 X_CONNECTOR_ARMED = "host X lane armed (built-in X tools or X connector)"
515
516
517 def _x_will_use_note(record: Dict[str, Any], policy: env.XPolicy) -> str:
518 """The will-use line for a predicted X backend, shaped by the policy.
519
520 On an official-only host a pinned backend renders as ``will use: <name>
521 (pinned)`` and nothing else names it (the pin variable is not
522 advertised). Off it the backends summary is kept verbatim.
523 The bearer prediction carries the about-a-week caveat on every host.
524 """
525 name = record["active_backend"]
526 if policy.official_only:
527 qualifiers: List[str] = []
528 if record.get("pinned"):
529 qualifiers.append("pinned")
530 if name == "xapi":
531 qualifiers.append(X_BEARER_CAVEAT)
532 return f"will use: {name}" + (f" ({'; '.join(qualifiers)})" if qualifiers else "")
533 note = record.get("note") or f"will use: {name}"
534 if name == "xapi":
535 if note.endswith(")"):
536 return f"{note[:-1]}; {X_BEARER_CAVEAT})"
537 return f"{note} ({X_BEARER_CAVEAT})"
538 return note
539
540
541 def _x_record(config):
542 record = _chained_record("x", config)
543 policy = env.x_policy(config)
544 if policy.official_only and not record.get("pinned"):
545 # The pin is documented in CONFIGURATION.md only; doctor never
546 # advertises the knob on an official-only host.
547 record["pin_var"] = None
548 if record.get("active_backend"):
549 record["note"] = _x_will_use_note(record, policy)
550 return record
551 # The declared X connector lane serves X when no engine backend is
552 # predicted (the same precedence as diagnose.x_backend). Host-independent:
553 # the envelope is accepted anywhere.
554 if env.x_host_lane_declared(config):
555 record["status"] = health.OK
556 record["tier"] = TIER_BY_STATUS[health.OK]
557 record["active_backend"] = "connector"
558 record["note"] = X_CONNECTOR_NOTE
559 record["detail"] = ""
560 record["fix"] = ""
561 return record
562 # Diagnose/doctor load config in plan_only mode, so browser cookies are not
563 # extracted and every X backend reads as statically missing -> unconfigured.
564 # But if bird is installed and FROM_BROWSER will authenticate X at run time,
565 # a normal run serves X fine (this is how the reporting user pulled 29 posts
566 # while doctor said "Off"). Reuse the existing shared predicate so doctor and
567 # diagnose cannot drift. It reads no cookie *values*, so it confirms a run
568 # will *attempt* browser auth, not that the session is currently valid -
569 # keep the note honest and point at the verified key-backed path.
570 #
571 # Policy-gated: on an official-only host no run-time cookie source
572 # exists unless bird is pinned, and then the note names only the pin.
573 #
574 # This check MUST come before grok normalization: a pending bird path or
575 # a recorded setup denial takes precedence over an unused grok store.
576 # Handle both "unconfigured" (all backends missing) and "error" (grok present
577 # but opt-in, no auto-chain backend usable) when pending bird applies.
578 #
579 # HOWEVER: pending bird must NOT replace a record that has a configured
580 # auto-chain backend in ERROR/DEGRADED/BROKEN/TIMEOUT. Same rule as the
581 # grok normalizer: only upgrade when no auto backend is configured-but-broken.
582 pin = env.x_backend_pin(config)
583 auto_chain_names = set(env.x_auto_chain(config))
584 all_auto_missing = all(
585 b.get("status") == health.MISSING
586 for b in record.get("backends", []) if b.get("name") in auto_chain_names
587 )
588 bird_finding = next(
589 (b for b in record.get("backends", []) if b.get("name") == "bird"),
590 None,
591 )
592 pinned_bird_missing = bool(
593 record.get("pinned")
594 and pin == "bird"
595 and bird_finding is not None
596 and bird_finding.get("status") == health.MISSING
597 )
598 can_apply_browser_auth = (
599 (not record.get("pinned") and all_auto_missing) or pinned_bird_missing
600 )
601 pending_bird = policy.cookie_discovery and env.x_pending_browser_auth(
602 config, local_only=True
603 )
604 reported_denials = set((config.get("LAST30DAYS_X_COOKIE_ACCESS_DENIED") or "").split(","))
605 known_browsers = set(env.COOKIE_BROWSER_NAMES)
606 if (
607 policy.cookie_discovery
608 and str(config.get("BROWSER_CONSENT") or "").lower() in {"1", "true", "yes", "on"}
609 and str(config.get("FROM_BROWSER") or "").strip().lower() != "off"
610 ):
611 denied_browsers = sorted(reported_denials & known_browsers)
612 else:
613 denied_browsers = []
614 if denied_browsers and record.get("pinned") and pin != "bird":
615 observation = (
616 "Last setup: permission denied reading X cookies from "
617 f"{', '.join(denied_browsers)}; current access not checked"
618 )
619 record["note"] = f"{record['note']}; {observation}" if record["note"] else observation
620 return record
621 if (pending_bird or denied_browsers) and record["status"] in (
622 "unconfigured", health.ERROR, health.MISSING,
623 ):
624 # Apply pending-bird / browser-cookie denial only when unpinned with all
625 # auto-chain backends missing, or when pinned specifically to bird and
626 # bird's only gap is missing static cookies.
627 if can_apply_browser_auth:
628 if denied_browsers:
629 record["status"] = health.ERROR
630 record["tier"] = TIER_BY_STATUS[health.ERROR]
631 record["note"] = (
632 "Last setup: permission denied reading X cookies from "
633 f"{', '.join(denied_browsers)}; current access not checked"
634 )
635 record["fix"] = env.X_COOKIE_ACCESS_FIX
636 return record
637 node = health.probe_dependency("node")
638 if node.status != health.OK:
639 node_status = (
640 node.status if node.status in TIER_BY_STATUS else health.ERROR
641 )
642 record["status"] = node_status
643 record["tier"] = TIER_BY_STATUS[node_status]
644 record["detail"] = node.detail
645 record["fix"] = node.prescription
646 record["requires"] = (
647 bird_finding.get("requires")
648 if bird_finding is not None and bird_finding.get("requires")
649 else "X browser cookies (AUTH_TOKEN/CT0) + node"
650 )
651 record["note"] = ""
652 if bird_finding is not None:
653 bird_finding["status"] = node_status
654 bird_finding["detail"] = node.detail
655 bird_finding["fix"] = node.prescription
656 return record
657 record["status"] = health.OK
658 record["tier"] = TIER_BY_STATUS[health.OK]
659 record["detail"] = ""
660 if policy.official_only:
661 record["note"] = "will use: bird (pinned)"
662 elif record.get("pinned"):
663 record["note"] = (
664 f"will use: bird (pinned via {env.X_BACKEND_PIN_VAR}; "
665 "browser cookies; session not verified until a run)"
666 )
667 else:
668 record["note"] = (
669 "will use: bird (browser cookies; session not verified until a run "
670 "- add XAI_API_KEY for a verified, cookie-free path)"
671 )
672 record["fix"] = ""
673 return record
674 # PATH presence explains an unconfigured sidecar; it does not authorize it.
675 # Refusals, backend pins and configured failures retain their own diagnosis.
676 if (
677 not policy.official_only
678 and not record.get("pinned")
679 and all_auto_missing
680 and record["status"] in ("unconfigured", health.ERROR)
681 and not env.cookie_access_denied(config)
682 and str(config.get("AGENTCOOKIE") or env.read_secret_env("AGENTCOOKIE") or "").strip().lower() != "off"
683 ):
684 from . import agentcookie
685
686 if (
687 agentcookie.is_disabled(config)
688 and env.x_extras_enabled(config)
689 and shutil.which(agentcookie.AGENTCOOKIE_BIN)
690 ):
691 record["status"] = "opt-in"
692 record["tier"] = TIER_OFF
693 record["note"] = "agentcookie is on PATH; sidecar cookie access is not enabled"
694 record["fix"] = "set AGENTCOOKIE=on to allow sidecar X cookie reads"
695 return record
696 #
697 # Grok is opt-in only: a leftover ~/.grok/auth.json must never steal the X
698 # lane. The grok backend appears in the chain findings (for visibility) but
699 # is never auto-selected. Doctor reports it as "available, unused - pin
700 # LAST30DAYS_X_BACKEND=grok to enable" rather than "will use: grok".
701 #
702 # Policy-gated: on an official-only host the CLI is not probed
703 # unless pinned and is never offered, so this branch does not run there
704 # (no "pin LAST30DAYS_X_BACKEND=grok" note on a Grok Bot host).
705 #
706 # R3/R8: When no auto-chain backend is CONFIGURED (all MISSING) but grok has
707 # any non-MISSING status, X is unconfigured/skipped - NOT broken/auth-failed.
708 # The tier must be "off" (unconfigured), not "error" (NOT WORKING).
709 #
710 # HOWEVER: if an auto-chain backend IS configured but broken (ERROR/DEGRADED),
711 # do NOT normalize to unconfigured. Keep that backend's error and repair
712 # guidance. Unused grok must not swallow a genuine auto-chain failure.
713 #
714 # Do NOT apply this normalization when pending browser auth would make bird
715 # usable — check pending_bird first (handled above via early return).
716 if (
717 not policy.official_only
718 and record["tier"] == TIER_ERROR
719 and not record.get("pinned")
720 and record.get("active_backend") is None
721 and not pending_bird
722 ):
723 backends_list = record.get("backends", [])
724 # Only normalize if ALL auto-chain backends are MISSING (not configured).
725 # If any auto backend is ERROR/DEGRADED/BROKEN/TIMEOUT, keep that error.
726 if not all_auto_missing:
727 # An auto-chain backend is configured but broken — do NOT normalize.
728 # Keep the original error and its repair guidance.
729 return record
730 grok_finding = next(
731 (b for b in backends_list if b.get("name") == "grok"),
732 None,
733 )
734 # A probe that raised is an unavailable check, not a broken credential store.
735 if (
736 grok_finding
737 and grok_finding.get("status") == health.ERROR
738 and str(grok_finding.get("detail") or "").startswith("probe failed:")
739 ):
740 xapi_ok = any(
741 b.get("name") == "xapi" and b.get("status") in (health.OK, health.DEGRADED)
742 for b in backends_list
743 )
744 record["status"], record["tier"] = "unconfigured", TIER_OFF
745 record["note"] = "X unconfigured; grok CLI availability could not be checked"
746 if xapi_ok:
747 record["note"] += "; pin LAST30DAYS_X_BACKEND=xapi to enable the X API backend"
748 record["fix"] = ""
749 else:
750 record["fix"] = _fix_text(prescriptions.for_x(config, "cookies_missing"))
751 return record
752 if grok_finding and grok_finding.get("status") in (
753 health.OK,
754 health.DEGRADED,
755 health.ERROR,
756 ):
757 record["status"] = "unconfigured"
758 record["tier"] = TIER_OFF
759 if grok_finding.get("status") == health.ERROR:
760 record["note"] = (
761 "X unconfigured; grok CLI store is broken but unused (opt-in only) — "
762 "pin LAST30DAYS_X_BACKEND=grok to enable, then fix the store"
763 )
764 else:
765 record["note"] = (
766 "X unconfigured; grok CLI available but opt-in only — "
767 "pin LAST30DAYS_X_BACKEND=grok to enable"
768 )
769 record["fix"] = ""
770 return record
771 xapi_finding = next(
772 (b for b in backends_list if b.get("name") == "xapi"),
773 None,
774 )
775 if xapi_finding and xapi_finding.get("status") in (health.OK, health.DEGRADED):
776 # Same shape as the grok note: a configured opt-in backend is not
777 # a broken X, it is an unconfigured X with a one-line enable.
778 record["status"] = "unconfigured"
779 record["tier"] = TIER_OFF
780 record["note"] = (
781 "X unconfigured; X_BEARER_TOKEN is set but the X API backend is opt-in "
782 "on this host — pin LAST30DAYS_X_BACKEND=xapi to enable"
783 )
784 record["fix"] = ""
785 return record
786 if policy.official_only and record.get("pinned") and not record.get("active_backend"):
787 if pin in ("bird", "grok") and not record.get("note"):
788 state_label = (
789 "is not configured" if record["status"] == health.MISSING else "is unavailable"
790 )
791 record["note"] = f"pinned backend {pin} {state_label}"
792 record["detail"] = ""
793 return record
794
795
796 def _youtube_record(config):
797 record = _chained_record("youtube", config)
798 if record["status"] != health.OK:
799 return record
800 notes: List[str] = []
801 # No transcription-key advice here: the caption-free transcription module
802 # (lib/transcribe.py) is not called by any source yet, so a GROQ_API_KEY or
803 # OPENAI_API_KEY would change nothing.
804 # Comment *text* is free via yt-dlp, so this caveat only fires when yt-dlp
805 # is absent and the legacy ScrapeCreators path is the only one left. Never
806 # prescribe a paid key for something the installed toolchain already does.
807 if not env.is_youtube_comments_available(config):
808 notes.append(
809 "comment text needs yt-dlp (free) or a ScrapeCreators key "
810 "+ youtube_comments opt-in"
811 )
812 # Actionable fix for the comment-text caveat.
813 if not record["fix"]:
814 if not config.get("SCRAPECREATORS_API_KEY"):
815 record["fix"] = _sc_fix()
816 else:
817 record["fix"] = (
818 "add youtube_comments to INCLUDE_SOURCES in "
819 "~/.config/last30days/.env to enable YouTube comment text"
820 )
821 if notes:
822 joined = "; ".join(notes)
823 record["note"] = (record["note"] + "; " + joined) if record["note"] else joined
824 return record
825
826
827 def _web_record(config):
828 return _chained_record("web", config)
829
830
831 def _hackernews_record(config):
832 return _record(status=health.OK, requires="none (free Algolia API)")
833
834
835 def _devto_record(config):
836 requires = "none (public Forem API)"
837 if "devto" in env.include_sources(config):
838 return _record(status=health.OK, requires=requires)
839 return _record(
840 status="opt-in", requires=requires,
841 fix="add devto to INCLUDE_SOURCES (or request it via --search devto)",
842 note="off by default; --devto-tags activates it for a run",
843 )
844
845
846 def _v2ex_record(config):
847 requires = "none (public SOV2EX search and V2EX API)"
848 if "v2ex" in env.include_sources(config):
849 return _record(status=health.OK, requires=requires)
850 return _record(
851 status="opt-in", requires=requires,
852 fix="add v2ex to INCLUDE_SOURCES (or request it via --search v2ex)",
853 note="off by default",
854 )
855
856
857 def _juejin_record(config):
858 requires = "none (public Juejin web API)"
859 if "juejin" in env.include_sources(config):
860 return _record(status=health.OK, requires=requires)
861 return _record(
862 status="opt-in", requires=requires,
863 fix="add juejin to INCLUDE_SOURCES (or request it via --search juejin)",
864 note="off by default",
865 )
866
867
868 def _polymarket_record(config):
869 return _record(status=health.OK, requires="none (public API)")
870
871
872 def _github_record(config):
873 authed = bool(config.get("GITHUB_TOKEN") or env.read_secret_env("GITHUB_TOKEN") or shutil.which("gh"))
874 detail = (
875 "authenticated tier (GITHUB_TOKEN or gh CLI)"
876 if authed
877 else "unauthenticated REST tier (lower rate limits; GITHUB_TOKEN or gh raises them)"
878 )
879 return _record(status=health.OK, detail=detail,
880 requires="none (GITHUB_TOKEN or gh CLI optional)")
881
882
883 def _digg_record(config):
884 probe = health.probe_dependency("digg-pp-cli")
885 requires = "digg-pp-cli on the agent-subprocess PATH"
886 if probe.ok:
887 if probe.outdated:
888 # Below the oldest release the engine can call, so its searches
889 # fail: degraded, with the pinned upgrade as the fix. The detail
890 # names both versions.
891 return _record(
892 status=health.DEGRADED, fix=probe.prescription,
893 note="digg-pp-cli is older than the engine can call; upgrade it",
894 detail=probe.detail, requires=requires,
895 )
896 if digg.cli_searches_all_topics() is not False:
897 # Current, or its help could not be read: nothing known to fix.
898 return _record(status=health.OK, detail=probe.detail, requires=requires)
899 # An older CLI still answers, on AI and tech only, so the source
900 # stays ok and carries the upgrade as its fix.
901 outdated = prescriptions.get("digg", "pp_cli_outdated")
902 return _record(
903 status=health.OK, fix=_fix_text(outdated), note=outdated.cause,
904 detail=probe.detail, requires=requires,
905 )
906 entry = prescriptions.for_dependency_probe(probe)
907 fix = _fix_text(entry) if entry else probe.prescription
908 if probe.status == health.MISSING and not probe.off_path:
909 # Never installed: an optional source that simply isn't enabled.
910 return _record(status="opt-in", fix=fix, detail=probe.detail, requires=requires)
911 # Installed but off-PATH, broken, or timing out: configured-but-broken.
912 return _record(status=probe.status, fix=fix, detail=probe.detail, requires=requires)
913
914
915 def _cli_gated_record(config, cli_name: str, purpose: str):
916 """A source gated purely on a keyless downloaded CLI (mirrors _digg_record).
917
918 ok -> installed and functional, with upgrade guidance if limited;
919 opt-in -> never installed; failing status -> off-PATH, broken, or timing out.
920 """
921 probe = health.probe_dependency(cli_name)
922 requires = f"{cli_name} on the agent-subprocess PATH"
923 if probe.ok:
924 if probe.outdated:
925 return _record(
926 status=health.OK, fix=probe.prescription, note=probe.detail,
927 detail=probe.detail, requires=requires,
928 )
929 return _record(status=health.OK, detail=probe.detail, requires=requires)
930 entry = prescriptions.for_dependency_probe(probe)
931 fix = _fix_text(entry) if entry else probe.prescription
932 if probe.status == health.MISSING and not probe.off_path:
933 return _record(status="opt-in", fix=fix, detail=probe.detail, requires=requires)
934 return _record(status=probe.status, fix=fix, detail=probe.detail, requires=requires)
935
936
937 def _techmeme_record(config):
938 return _cli_gated_record(config, "techmeme-pp-cli", "techmeme")
939
940
941 def _news_rss_record(config):
942 return _cli_gated_record(config, "news-rss-pp-cli", "news_rss")
943
944
945 def _arxiv_record(config):
946 return _cli_gated_record(config, "arxiv-pp-cli", "arxiv")
947
948
949 def _yahoo_finance_record(config):
950 """The share-price line. Unlike a search source it runs only for a topic
951 that resolves to a listed company, so a working install records nothing on
952 most runs; the note says so, so that quiet is not read as a fault."""
953 record = _cli_gated_record(config, "yahoo-finance-pp-cli", "yahoo_finance")
954 if record["status"] == health.OK:
955 record["note"] = (
956 "share-price line for topics that resolve to a listed company; "
957 "no price line on other topics is expected"
958 )
959 return record
960
961
962 def _trustpilot_record(config):
963 """Installed is not the same as able to run: the lane needs opt-in
964 (INCLUDE_SOURCES=trustpilot) AND a browser session that lasts four
965 minutes, or a cached company record."""
966 requires = "trustpilot-pp-cli on the agent-subprocess PATH + INCLUDE_SOURCES=trustpilot"
967 record = _cli_gated_record(config, "trustpilot-pp-cli", "trustpilot")
968 record["requires"] = requires
969 if record["status"] != health.OK:
970 return record
971 if "trustpilot" not in env.include_sources(config):
972 return _record(
973 status="opt-in",
974 requires=requires,
975 detail=record["detail"],
976 fix="add trustpilot to INCLUDE_SOURCES (or request it via --search trustpilot)",
977 note="CLI installed; opt-in, never auto-activates",
978 )
979 if not trustpilot._harvest_allowed(config):
980 return _record(
981 status="excluded",
982 requires=requires,
983 detail=record["detail"],
984 fix=f"unset {trustpilot.NO_BROWSER_ENV} (or set it to 0) to allow Trustpilot",
985 note=(
986 f"disabled by {trustpilot.NO_BROWSER_ENV}; research runs skip "
987 "Trustpilot even with a fresh browser session"
988 ),
989 )
990 state = trustpilot.can_run_now(config)
991 if state["session_fresh"]:
992 record["note"] = "browser session is fresh; can run now"
993 elif state["cached_companies"]:
994 count = state["cached_companies"]
995 record["note"] = (
996 f"no fresh browser session; {count} cached company "
997 f"record{'s' if count != 1 else ''} can be read"
998 )
999 else:
1000 record["status"] = health.DEGRADED
1001 record["tier"] = TIER_BY_STATUS[health.DEGRADED]
1002 record["fix"] = (
1003 "run `trustpilot-pp-cli auth login` for a fresh browser session (~3 minutes)"
1004 )
1005 record["note"] = (
1006 "cannot run now: no fresh browser session and no cached company record "
1007 "(a research run never opens a browser; `trustpilot-pp-cli auth login` "
1008 "gives a session for about 3 minutes)"
1009 )
1010 return record
1011
1012
1013 def _amazon_record(config):
1014 """Amazon buyer signals: CLI-gated, auth-gated, AND opt-in-gated.
1015
1016 Unlike the other CLI-gated sources, a present binary is not enough --
1017 the Bright Data CLI owns its own login, AND pipeline.available_sources()
1018 requires INCLUDE_SOURCES=amazon (or --search amazon). Report those states
1019 separately so doctor and the pipeline agree.
1020 """
1021 probe = health.probe_dependency(brightdata.CLI_BIN)
1022 requires = f"{brightdata.CLI_BIN} on the agent-subprocess PATH, logged in + INCLUDE_SOURCES=amazon"
1023 if probe.ok:
1024 if not brightdata.has_credentials(config):
1025 return _record(
1026 status="unconfigured",
1027 fix="run `brightdata login` to activate the amazon source",
1028 detail="brightdata is installed but has no credentials",
1029 requires=requires,
1030 )
1031 if "amazon" in env.include_sources(config):
1032 return _record(status=health.OK, detail=probe.detail, requires=requires)
1033 return _record(
1034 status="opt-in",
1035 fix="add amazon to INCLUDE_SOURCES (or request it via --search amazon)",
1036 note="brightdata CLI installed and logged in; opt-in, never auto-activates",
1037 detail=probe.detail,
1038 requires=requires,
1039 )
1040 entry = prescriptions.for_dependency_probe(probe)
1041 fix = _fix_text(entry) if entry else probe.prescription
1042 if probe.status == health.MISSING and not probe.off_path:
1043 return _record(
1044 status="opt-in",
1045 fix="npm i -g @brightdata/cli && brightdata login",
1046 detail=probe.detail,
1047 requires=requires,
1048 )
1049 return _record(status=probe.status, fix=fix, detail=probe.detail, requires=requires)
1050
1051
1052 def _tiktok_record(config):
1053 return _sc_gated_record(config, "tiktok")
1054
1055
1056 def _instagram_record(config):
1057 return _sc_gated_record(config, "instagram")
1058
1059
1060 def _threads_record(config):
1061 # Threads needs the key AND an INCLUDE_SOURCES=threads opt-in to run, so it
1062 # is opt-in-gated (not on-by-default like TikTok/Instagram).
1063 return _sc_optin_record(config, "threads", "threads")
1064
1065
1066 def _telegram_record(config):
1067 # Telegram needs the key AND an INCLUDE_SOURCES=telegram opt-in AND a
1068 # channel list (TELEGRAM_SOURCES). Without named channels there is no
1069 # discovery endpoint to call.
1070 requires = "SCRAPECREATORS_API_KEY + INCLUDE_SOURCES=telegram + TELEGRAM_SOURCES"
1071 if not config.get("SCRAPECREATORS_API_KEY"):
1072 return _record(status="unconfigured", requires=requires, fix=_sc_fix())
1073 from . import telegram
1074 channels = telegram._get_channel_sources(config)
1075 if "telegram" in env.include_sources(config):
1076 if channels:
1077 return _record(
1078 status=health.OK,
1079 requires=requires,
1080 detail=f"{_sc_key_detail(config)}, {len(channels)} channel(s) configured",
1081 )
1082 return _record(
1083 status="unconfigured",
1084 requires=requires,
1085 fix="set TELEGRAM_SOURCES to a comma-separated list of public channel handles",
1086 note="key present and opt-in active, but no channels configured",
1087 )
1088 return _record(
1089 status="opt-in",
1090 requires=requires,
1091 fix="add telegram to INCLUDE_SOURCES and set TELEGRAM_SOURCES to channel handles",
1092 note="key present; opt-in only, channels required",
1093 )
1094
1095
1096 def _bluesky_record(config):
1097 if env.is_bluesky_available(config):
1098 return _record(status=health.OK, requires="BSKY_HANDLE + BSKY_APP_PASSWORD")
1099 return _record(
1100 status="unconfigured",
1101 requires="BSKY_HANDLE + BSKY_APP_PASSWORD",
1102 fix=_fix_text(prescriptions.get("bluesky", "app_password_missing")),
1103 )
1104
1105
1106 def _truthsocial_record(config):
1107 if env.is_truthsocial_available(config):
1108 return _record(status=health.OK, requires="TRUTHSOCIAL_TOKEN")
1109 return _record(
1110 status="unconfigured",
1111 requires="TRUTHSOCIAL_TOKEN",
1112 fix=_fix_text(prescriptions.get("truthsocial", "token_missing")),
1113 )
1114
1115
1116 def _perplexity_record(config):
1117 requires = (
1118 "PERPLEXITY_API_KEY or OPENROUTER_API_KEY + "
1119 "INCLUDE_SOURCES=perplexity"
1120 )
1121 has_direct_key = bool(config.get("PERPLEXITY_API_KEY"))
1122 has_openrouter_key = bool(config.get("OPENROUTER_API_KEY"))
1123 has_key = has_direct_key or has_openrouter_key
1124 include = env.include_sources(config)
1125 if not has_key:
1126 return _record(
1127 status="unconfigured", requires=requires,
1128 fix=(
1129 "set PERPLEXITY_API_KEY or OPENROUTER_API_KEY in "
1130 "~/.config/last30days/.env, then add perplexity to INCLUDE_SOURCES"
1131 ),
1132 )
1133 if "perplexity" in include:
1134 return _record(
1135 status=health.OK,
1136 requires=requires,
1137 note=(
1138 "direct Agent/Search APIs"
1139 if has_direct_key
1140 else "OpenRouter Sonar compatibility fallback"
1141 ),
1142 )
1143 return _record(
1144 status="opt-in", requires=requires,
1145 fix="add perplexity to INCLUDE_SOURCES (or request it via --search perplexity)",
1146 note="key present; source runs only when opted in",
1147 )
1148
1149
1150 def _meta_ads_record(config):
1151 return _sc_optin_record(config, "meta_ads", "Meta Ad Library")
1152
1153
1154 def _linkedin_record(config):
1155 requires = "SCRAPECREATORS_API_KEY + INCLUDE_SOURCES=linkedin"
1156 if not config.get("SCRAPECREATORS_API_KEY"):
1157 return _record(status="unconfigured", requires=requires, fix=_sc_fix())
1158 if "linkedin" in env.include_sources(config):
1159 return _record(status=health.OK, requires=requires)
1160 return _record(
1161 status="opt-in", requires=requires,
1162 fix="add linkedin to INCLUDE_SOURCES (or request it via --search linkedin)",
1163 note="key present; power-user opt-in, never auto-activates",
1164 )
1165
1166
1167 def _deepline_record(config):
1168 """Person-run lanes (LinkedIn profile and posts, name lookup).
1169
1170 Uses the run's own availability check, so doctor and a person run agree.
1171 """
1172 requires = "DEEPLINE_API_KEY; used by person runs only"
1173 if not deepline.is_available(config):
1174 return _record(
1175 status="unconfigured", requires=requires,
1176 fix="set DEEPLINE_API_KEY to read LinkedIn profiles and posts in person runs",
1177 )
1178 return _record(
1179 status=health.OK, requires=requires,
1180 note="key present; paid calls run only for a person run",
1181 )
1182
1183
1184 def _pinterest_record(config):
1185 return _sc_optin_record(config, "pinterest", "pinterest")
1186
1187
1188 def _xiaohongshu_record(config):
1189 requires = (
1190 "logged-in Xiaohongshu browser-session service + "
1191 "INCLUDE_SOURCES=xiaohongshu (or --search xhs)"
1192 )
1193 entry = prescriptions.get("xiaohongshu", "service_unreachable")
1194 opted_in = "xiaohongshu" in env.include_sources(config)
1195 if config.get("XIAOHONGSHU_API_BASE"):
1196 if opted_in:
1197 return _record(
1198 status=health.OK, requires=requires,
1199 note=(
1200 "XIAOHONGSHU_API_BASE configured; service reachability is not "
1201 "probed (doctor makes no network calls)"
1202 ),
1203 )
1204 return _record(
1205 status="opt-in", requires=requires,
1206 fix="add xiaohongshu to INCLUDE_SOURCES (or request it via --search xhs)",
1207 note="XIAOHONGSHU_API_BASE configured; opt-in, runs only when opted in or requested",
1208 )
1209 return _record(
1210 status="opt-in",
1211 requires=requires,
1212 fix=_fix_text(entry),
1213 note=(
1214 "auto-probes http://localhost:18060 first, then "
1215 "http://host.docker.internal:18060"
1216 ),
1217 )
1218
1219
1220 def _jobs_record(config):
1221 return _record(
1222 status="opt-in",
1223 requires="none; activates for company topics or --hiring-signals",
1224 note="on-demand source: no configuration needed",
1225 )
1226
1227
1228 def _patents_record(config):
1229 """The patent digest. Like the share-price line it runs only for a topic
1230 that is a company, and a company may have published nothing, so a quiet
1231 run is the usual case; the note says so."""
1232 return _record(
1233 status="opt-in",
1234 requires="none (public USPTO search); activates for company topics",
1235 note=(
1236 "on-demand source: no configuration needed; no patents line is "
1237 "expected for topics that are not companies, for companies with "
1238 "no filings in the window, or if USPTO starts requiring sign-in"
1239 ),
1240 )
1241
1242
1243 def _count_saved_briefs(memory_dir) -> int:
1244 """Cheap count of saved research briefs (directory listing, no file parse).
1245
1246 Globs the ``*-raw*.md`` artifacts the engine writes, deliberately avoiding
1247 library.scan_library's read_text+parse of every file - a count does not
1248 need the parsed content, and the full scan adds real latency to every
1249 `doctor` run on a large library.
1250 """
1251 path = Path(memory_dir).expanduser()
1252 return sum(1 for _ in path.glob("*-raw*.md"))
1253
1254
1255 def _library_record(config):
1256 """Local research library that feeds the report's 'From your library' block.
1257
1258 This is not a network source - it reports how many saved briefs are indexed
1259 so the 'From your library' block's presence is explained on the health
1260 surface. Read-only and never fails the run: an empty store, a missing store,
1261 or a SQLite build without FTS5 all resolve to an informational OK line.
1262 """
1263 from . import library, library_index
1264
1265 if not library_index.fts5_available():
1266 return _record(
1267 status=health.OK,
1268 requires="none (local SQLite)",
1269 note=(
1270 "search index unavailable (this SQLite build lacks FTS5); "
1271 "saved briefs still render, `library search` is disabled"
1272 ),
1273 )
1274 try:
1275 count = _count_saved_briefs(
1276 config.get("LAST30DAYS_MEMORY_DIR") or library.DEFAULT_MEMORY_DIR
1277 )
1278 except Exception:
1279 return _record(
1280 status=health.OK,
1281 requires="none (local SQLite)",
1282 note="local research library (powers the 'From your library' block)",
1283 )
1284 if count == 0:
1285 note = "no saved briefs yet - runs you save build this over time"
1286 else:
1287 plural = "brief" if count == 1 else "briefs"
1288 note = (
1289 f"{count} saved {plural}; powers the 'From your library' block "
1290 "(LAST30DAYS_LIBRARY_CONTEXT=off to hide)"
1291 )
1292 return _record(status=health.OK, requires="none (local SQLite)", note=note)
1293
1294
1295 _SOURCE_BUILDERS: Dict[str, Callable[[Dict[str, Any]], Dict[str, Any]]] = {
1296 "reddit": _reddit_record,
1297 "x": _x_record,
1298 "youtube": _youtube_record,
1299 "web": _web_record,
1300 "hackernews": _hackernews_record,
1301 "polymarket": _polymarket_record,
1302 "github": _github_record,
1303 "devto": _devto_record,
1304 "v2ex": _v2ex_record,
1305 "juejin": _juejin_record,
1306 "digg": _digg_record,
1307 "techmeme": _techmeme_record,
1308 "news_rss": _news_rss_record,
1309 "arxiv": _arxiv_record,
1310 "yahoo_finance": _yahoo_finance_record,
1311 "trustpilot": _trustpilot_record,
1312 "amazon": _amazon_record,
1313 "meta_ads": _meta_ads_record,
1314 "tiktok": _tiktok_record,
1315 "instagram": _instagram_record,
1316 "threads": _threads_record,
1317 "telegram": _telegram_record,
1318 "bluesky": _bluesky_record,
1319 "truthsocial": _truthsocial_record,
1320 "perplexity": _perplexity_record,
1321 "linkedin": _linkedin_record,
1322 "deepline": _deepline_record,
1323 "pinterest": _pinterest_record,
1324 "xiaohongshu": _xiaohongshu_record,
1325 "jobs": _jobs_record,
1326 "patents": _patents_record,
1327 "library": _library_record,
1328 }
1329
1330
1331 # ---------------------------------------------------------------------------
1332 # Run-evidence overlay (U1): read the engine's last-report.json
1333 #
1334 # doctor predicts config health; a research run records what ACTUALLY happened
1335 # per source in Report.source_status. Reading the last run lets doctor tell
1336 # "configured" from "working" (the four-state audit) and powers --postmortem.
1337 # This is a read-only reuse of the engine's existing report cache - no new
1338 # writer. The schema stamp + filename mirror REPORT_CACHE_VERSION /
1339 # _last_report_cache_path() in last30days.py (the same mirror pattern the
1340 # doctor-cache block below already uses for its own schema stamp).
1341 # ---------------------------------------------------------------------------
1342
1343 # Must equal last30days.REPORT_CACHE_VERSION: a stamp the engine no longer
1344 # writes makes every run read as "No saved run found"
1345 # (tests/test_doctor_postmortem_after_run.py holds the two together).
1346 REPORT_CACHE_SCHEMA_VERSION = "last30days-report-cache/v2"
1347 REPORT_CACHE_FILENAME = "last-report.json"
1348 DEFAULT_REPORT_CACHE_TTL_SECONDS = 3600
1349
1350
1351 def _last_report_path() -> Optional[Path]:
1352 """The engine's last-report.json, beside the doctor cache (None in clean mode)."""
1353 if env.CONFIG_DIR is None:
1354 return None
1355 return env.CONFIG_DIR / REPORT_CACHE_FILENAME
1356
1357
1358 def load_run_evidence(
1359 config: Dict[str, Any], ttl_seconds: int = DEFAULT_REPORT_CACHE_TTL_SECONDS
1360 ) -> Dict[str, Any]:
1361 """Return the last research run's per-source outcomes, read-only.
1362
1363 Shape: ``{"outcomes": {source: {state, items_returned, detail, fix_hint,
1364 at}}, "topic": str|None, "at": str|None, "fresh": bool, "present": bool}``.
1365
1366 Any failure mode - absent file, unreadable, invalid JSON, schema mismatch,
1367 wrong shape - yields the empty, not-present result and never raises
1368 (doctor's exit-0 contract is absolute). ``fresh`` reflects the report TTL:
1369 ``--postmortem`` reads regardless of freshness (labeling the age), while the
1370 plain-``doctor`` overlay consumes only fresh evidence so a week-old run
1371 cannot mislabel a source as WORKING today.
1372 """
1373 empty = {"outcomes": {}, "topic": None, "at": None, "fresh": False, "present": False}
1374 path = _last_report_path()
1375 if path is None or not path.exists():
1376 return empty
1377 try:
1378 payload = json.loads(path.read_text(encoding="utf-8"))
1379 except Exception:
1380 return empty
1381 if not isinstance(payload, dict):
1382 return empty
1383 if payload.get("schema") != REPORT_CACHE_SCHEMA_VERSION:
1384 return empty
1385 reports = payload.get("reports") or []
1386 if not reports or not isinstance(reports[0], dict):
1387 return empty
1388 report = reports[0].get("report")
1389 if not isinstance(report, dict):
1390 return empty
1391 raw_status = report.get("source_status") or {}
1392 outcomes: Dict[str, Any] = {}
1393 if isinstance(raw_status, dict):
1394 for source, outcome in raw_status.items():
1395 if not isinstance(outcome, dict):
1396 continue
1397 state = outcome.get("state")
1398 if not isinstance(state, str):
1399 continue
1400 outcomes[source] = {
1401 "state": state,
1402 "items_returned": int(outcome.get("items_returned") or 0),
1403 "detail": outcome.get("detail"),
1404 "fix_hint": outcome.get("fix_hint"),
1405 "at": outcome.get("at"),
1406 }
1407 timestamp = payload.get("timestamp")
1408 return {
1409 "outcomes": outcomes,
1410 "topic": payload.get("topic"),
1411 "at": timestamp or report.get("generated_at"),
1412 "fresh": bool(env.is_timestamp_fresh(timestamp, ttl_seconds)),
1413 "present": True,
1414 }
1415
1416
1417 # ---------------------------------------------------------------------------
1418 # Backup + comment sub-lanes (U7 / R8, R9)
1419 #
1420 # Backups (Reddit's SC backfill, YouTube's SC transcript/search backstop, X's
1421 # cookie-vs-key dual path) and comment lanes (youtube/tiktok/instagram) are not
1422 # independent sources - they are capabilities of their parent. doctor surfaces
1423 # them as indented sub-lines so "is a backup armed when yt-dlp is rate-limited?"
1424 # is answerable at a glance without inventing fake sources.
1425 # ---------------------------------------------------------------------------
1426
1427 def _x_auth_path(config: Dict[str, Any]) -> Dict[str, Any]:
1428 """The "X auth path" sub-lane, routed through the X policy.
1429
1430 Off an official-only host the wording is unchanged (key-backed, cookie
1431 path, or nothing armed). On one it names only the official path: the
1432 connector lane when declared, else the bearer (with the about-a-week
1433 caveat), the xAI key, or xurl; a pinned non-official backend is named
1434 once, on the will-use line, never here.
1435 """
1436 policy = env.x_policy(config)
1437 if not policy.official_only:
1438 has_key = bool(config.get("XAI_API_KEY") or config.get("XQUIK_API_KEY"))
1439 cookie = bool(
1440 env.x_pending_browser_auth(config, local_only=True)
1441 and health.probe_dependency("node").status == health.OK
1442 )
1443 if has_key and proxy.is_sentinel(config.get("XAI_API_KEY")) and not config.get("XQUIK_API_KEY"):
1444 note = "xAI via API key (verified, cookie-free; paid per call)"
1445 elif has_key:
1446 note = "XAI_API_KEY key-backed path (verified, cookie-free)"
1447 elif cookie:
1448 note = (
1449 "browser-cookie path primary; add XAI_API_KEY for a verified "
1450 "cookie-free backup"
1451 )
1452 else:
1453 note = "no auth path armed"
1454 return {"name": "X auth path", "armed": has_key or cookie, "note": note}
1455 if env.x_host_lane_declared(config):
1456 return {"name": "X auth path", "armed": True, "note": X_CONNECTOR_ARMED}
1457 source = env.get_x_source(config, local_only=True)
1458 if source == "xapi":
1459 note = f"X_BEARER_TOKEN path ({X_BEARER_CAVEAT})"
1460 elif source == "xai" and proxy.is_sentinel(config.get("XAI_API_KEY")):
1461 note = "xAI licensed path via API key"
1462 elif source == "xai":
1463 note = "XAI_API_KEY licensed path (console.x.ai)"
1464 elif source == "xurl":
1465 note = "X API through the xurl CLI (stored app-only bearer)"
1466 elif source:
1467 note = "explicit backend pin"
1468 else:
1469 note = (
1470 "no official X path armed (use Grok Bot's built-in X tools or add the X for Grok Bot plugin, or set "
1471 "X_BEARER_TOKEN or XAI_API_KEY)"
1472 )
1473 return {"name": "X auth path", "armed": bool(source), "note": note}
1474
1475
1476 # One row per keyless Reddit path (site search, each keyless web rung, the
1477 # Arctic Shift archive), with the last run's outcome read back from
1478 # last-report.json, any persisted skip, and what to do about it.
1479 _REDDIT_PATH_LABELS = (
1480 ("search", "Reddit site search"),
1481 ("brave", "Brave web search"),
1482 ("ddg", "DuckDuckGo web search"),
1483 ("startpage", "Startpage web search"),
1484 ("arctic", "Arctic Shift archive"),
1485 )
1486
1487
1488 def _reddit_last_run(path: str, outcomes: Dict[str, str]) -> Optional[str]:
1489 """This path's outcome in the saved run: a failure token, ``served``, or None."""
1490 if path in outcomes:
1491 return outcomes[path]
1492 if path in reddit_health.WEB_RUNGS and outcomes.get("web") == "served":
1493 return "served"
1494 return None
1495
1496
1497 def _reddit_path_action(path: str, last_run: Optional[str], until: Optional[str]) -> str:
1498 if until:
1499 return "none needed while another path serves; the skip lifts at the time shown"
1500 if last_run == reddit_health.BLOCKED:
1501 if path == "search":
1502 return "none: Reddit refuses its site search on this network, so the web floor serves instead"
1503 return "none needed while another path serves; a refused path is skipped for 6 h"
1504 if last_run == reddit_health.THROTTLED:
1505 return "none: a rate limit skips this path for one run only"
1506 if last_run == reddit_health.DOWN:
1507 if path == "arctic":
1508 return "wait for Arctic Shift to recover; threads keep their search-result data meanwhile"
1509 return "none: the next run asks it again"
1510 if last_run == reddit_health.SKIPPED_CACHED:
1511 return "none: a recent refusal was still in force; the skip expires after 6 h"
1512 return "none"
1513
1514
1515 def _reddit_session_row(config: Dict[str, Any], outcomes: Dict[str, str]) -> Dict[str, Any]:
1516 """The logged-in session's row: its consent state, the browser setup
1517 recorded, whether this run would use it, and its last outcome. Reads the
1518 config and the health cache only, never a cookie (the gate is pure)."""
1519 from datetime import datetime, timedelta, timezone
1520
1521 consent = env.reddit_consent_state(config)
1522 browser = str(config.get(env.REDDIT_FROM_BROWSER_VAR) or "")
1523 probe = dict(config)
1524 probe["_BROWSER_COOKIE_MODE"] = "read" # doctor itself is plan-only
1525 allowed, why = env.reddit_session_gate(probe)
1526 entry = reddit_health.entries().get("session") or {}
1527 until = None
1528 if entry.get("state") == reddit_health.BLOCKED:
1529 try:
1530 at = datetime.fromisoformat(str(entry.get("at")))
1531 at = at if at.tzinfo else at.replace(tzinfo=timezone.utc)
1532 lift = at + timedelta(seconds=reddit_health.SKIP_TTL_SECONDS)
1533 if lift > datetime.now(timezone.utc):
1534 until = lift.strftime("%Y-%m-%d %H:%M UTC")
1535 except (TypeError, ValueError):
1536 pass
1537 last_run = outcomes.get("session")
1538 if consent != "granted":
1539 action = (
1540 "off: you declined it" if consent == "refused"
1541 else "off: opt in with setup --reddit-session (reads your reddit.com login)"
1542 )
1543 elif not allowed:
1544 action = f"off this run: {why}"
1545 elif last_run == reddit_health.SESSION_EXPIRED or str(entry.get("reason") or "").startswith("session-expired"):
1546 action = f"log in to reddit.com in {browser or 'your browser'}; a new login clears the skip"
1547 else:
1548 action = "none"
1549 return {
1550 "path": "session",
1551 "name": "Logged-in Reddit session",
1552 "consent": consent,
1553 "browser": browser or None,
1554 "would_run": allowed,
1555 "last_run": last_run,
1556 "skip_until": until,
1557 "action": action,
1558 }
1559
1560
1561 def _reddit_path_rows(
1562 outcome: Optional[Dict[str, Any]], config: Optional[Dict[str, Any]] = None,
1563 ) -> List[Dict[str, Any]]:
1564 """Doctor rows for the Reddit paths. Reads the health cache and the saved
1565 run only: no request, no cookie."""
1566 outcomes = reddit_health.parse_detail((outcome or {}).get("detail"))
1567 rows: List[Dict[str, Any]] = [_reddit_session_row(config or {}, outcomes)]
1568 for path, label in _REDDIT_PATH_LABELS:
1569 until_dt = reddit_health.skip_until(path)
1570 until = until_dt.strftime("%Y-%m-%d %H:%M UTC") if until_dt else None
1571 last_run = _reddit_last_run(path, outcomes)
1572 rows.append({
1573 "path": path,
1574 "name": label,
1575 "last_run": last_run,
1576 "skip_until": until,
1577 "action": _reddit_path_action(path, last_run, until),
1578 })
1579 return rows
1580
1581
1582 def _mark_reddit_skips_cleared(report: Dict[str, Any], cleared: List[str]) -> None:
1583 """Note on each Reddit row whose skip this doctor run cleared."""
1584 record = (report.get("sources") or {}).get("reddit") or {}
1585 for row in record.get("paths") or []:
1586 if row.get("path") in cleared:
1587 row["skip_cleared"] = True
1588 row["action"] = "doctor cleared this skip; the next run asks this path again"
1589
1590
1591 def _reddit_sc_last_run(outcome: Optional[Dict[str, Any]]) -> str:
1592 detail = str((outcome or {}).get("detail") or "")
1593 if not detail:
1594 return ""
1595 if "ScrapeCreators backfill failed" in detail:
1596 return "; last run: backfill failed"
1597 if reddit_health.parse_detail(detail).get("sc") == "served":
1598 return "; last run: backfill served"
1599 if "ScrapeCreators backfill ran" in detail:
1600 return "; last run: backfill ran, added nothing"
1601 return "; last run: not needed"
1602
1603
1604 def _sub_lanes_for(source: str, config: Dict[str, Any]):
1605 """Return (backups, comments) metadata for a source, or ([], None)."""
1606 backups: List[Dict[str, Any]] = []
1607 comments: Optional[Dict[str, Any]] = None
1608 has_sc = bool(config.get("SCRAPECREATORS_API_KEY"))
1609 if source == "reddit":
1610 floor = env.reddit_sc_min_items(config)
1611 if floor > 0:
1612 note = f"fills in when results fall below the {floor}-item floor"
1613 else:
1614 note = "fills in when the free public path returns nothing"
1615 backups.append({"name": "ScrapeCreators backfill", "armed": has_sc, "note": note})
1616 elif source == "youtube":
1617 backups.append({
1618 "name": "ScrapeCreators transcript/search backstop",
1619 "armed": env.is_youtube_sc_available(config),
1620 "note": "used when yt-dlp is rate-limited or bot-gated",
1621 })
1622 comments = {"enabled": bool(env.is_youtube_comments_available(config))}
1623 elif source == "x":
1624 backups.append(_x_auth_path(config))
1625 elif source == "tiktok":
1626 comments = {"enabled": bool(env.is_tiktok_comments_available(config))}
1627 backups.append({
1628 "name": "yt-dlp + web discovery",
1629 "armed": env.is_shortform_oss_available(config, "tiktok"),
1630 "note": (
1631 "used when ScrapeCreators is missing or 402s; via "
1632 + ", ".join(env.shortform_discovery_sources(config, "tiktok"))
1633 ),
1634 })
1635 elif source == "instagram":
1636 comments = {"enabled": bool(env.is_instagram_comments_available(config))}
1637 backups.append({
1638 "name": "yt-dlp + web discovery",
1639 "armed": env.is_shortform_oss_available(config, "instagram"),
1640 "note": (
1641 "used when ScrapeCreators is missing or 402s; best effort, low recall; via "
1642 + ", ".join(env.shortform_discovery_sources(config, "instagram"))
1643 ),
1644 })
1645 return backups, comments
1646
1647
1648 # ---------------------------------------------------------------------------
1649 # Aggregation
1650 # ---------------------------------------------------------------------------
1651
1652 def _engine_version() -> str:
1653 try:
1654 from . import render
1655
1656 version = render._skill_version()
1657 except Exception:
1658 version = None
1659 # render's parent-walking helper falls back to "?"; doctor says "unknown".
1660 if not version or version == "?":
1661 return "unknown"
1662 return version
1663
1664
1665 def _setup_block(config: Dict[str, Any]) -> Dict[str, Any]:
1666 # A lane served by the API-key proxy is not a key the user holds.
1667 keys_present = {
1668 var: bool(config.get(var)) and not proxy.is_sentinel(config.get(var))
1669 for var in KEY_PRESENCE_VARS
1670 }
1671 keys_present["x_browser_cookies"] = bool(
1672 config.get("AUTH_TOKEN") and config.get("CT0")
1673 )
1674 keys_present["bluesky_app_password"] = bool(
1675 config.get("BSKY_HANDLE") and config.get("BSKY_APP_PASSWORD")
1676 )
1677 return {
1678 "setup_complete": env.is_setup_complete(config),
1679 "keys_present": keys_present,
1680 # Paid lanes served through LAST30DAYS_API_MODE=proxy (names only).
1681 "via_api_key": proxy.via_api_key(config),
1682 # get_config() rejected these before any presence check ran, so
1683 # keys_present already reads them as absent. Carrying the names here is
1684 # what lets the text renderer say *why* they are absent instead of
1685 # leaving the user to read "credentials present: none". Only keys left
1686 # unset are listed: one whose placeholder fell through to a real
1687 # lower-priority credential is configured and does not appear.
1688 "unsubstituted_templates": env.templated_config_keys(config),
1689 }
1690
1691
1692 def _brief_capture_hooks_block(config: Dict[str, Any]) -> Dict[str, Any]:
1693 """Read-only summary of installed brief-capture hooks and archived finished briefs."""
1694 from . import brief_capture, hook_installer, library
1695
1696 memory_dir = Path(
1697 config.get("LAST30DAYS_MEMORY_DIR") or library.DEFAULT_MEMORY_DIR
1698 ).expanduser()
1699 finished_dir = memory_dir / brief_capture.FINISHED_SUBDIR
1700 finished_count = (
1701 sum(1 for _ in finished_dir.glob("*.md")) if finished_dir.is_dir() else 0
1702 )
1703 return {
1704 "harnesses": hook_installer.hook_status(),
1705 "finished_briefs": finished_count,
1706 "finished_dir": str(finished_dir),
1707 }
1708
1709
1710 def _permissions_block(config: Dict[str, Any]) -> Dict[str, Any]:
1711 """Secret-free permission summary via the existing preflight provider."""
1712 from . import pipeline
1713
1714 diag = pipeline.diagnose(config, None, safe=True)
1715 return diag["permission_preflight"]
1716
1717
1718 def _is_excluded(source: str, excluded: set[str]) -> bool:
1719 return source in excluded
1720
1721
1722 def _excluded_record(source: str, config: Dict[str, Any]) -> Dict[str, Any]:
1723 tokens = env.excluded_source_tokens(source, config) or [source]
1724 token_list = ", ".join(tokens)
1725 if len(tokens) == 1:
1726 fix_tokens = tokens[0]
1727 elif len(tokens) == 2:
1728 fix_tokens = f"{tokens[0]} and {tokens[1]}"
1729 else:
1730 fix_tokens = f"{', '.join(tokens[:-1])}, and {tokens[-1]}"
1731 descriptor = backends.DESCRIPTORS.get(source)
1732 extra: Dict[str, Any] = {}
1733 if descriptor is not None:
1734 extra.update(
1735 mode=descriptor.mode,
1736 backends_list=[],
1737 active_backend=None,
1738 pin_var=descriptor.pin_var,
1739 pin_flag=descriptor.pin_flag,
1740 pinned=False,
1741 )
1742 return _record(
1743 status="excluded",
1744 note=f"excluded via EXCLUDE_SOURCES ({token_list})",
1745 fix=f"remove {fix_tokens} from EXCLUDE_SOURCES to re-enable",
1746 **extra,
1747 )
1748
1749
1750 def build_report(config: Dict[str, Any]) -> Dict[str, Any]:
1751 """Aggregate every health provider into one report dict.
1752
1753 Per-source exceptions are isolated: a failing builder yields an
1754 ``error`` record for that source and the rest of the report survives.
1755 """
1756 excluded = env.exclude_sources(config)
1757
1758 def _build_one(name: str) -> Dict[str, Any]:
1759 if _is_excluded(name, excluded):
1760 return _excluded_record(name, config)
1761 try:
1762 return _SOURCE_BUILDERS[name](config)
1763 except Exception as exc: # one bad probe must not blank the report
1764 return _record(
1765 status=health.ERROR,
1766 detail=f"probe failed: {type(exc).__name__}: {exc}",
1767 fix=_fix_text(prescriptions.get(name, "probe_error")),
1768 )
1769
1770 # Builders are independent probes (subprocess/filesystem bound), so run
1771 # them concurrently. ``pool.map`` preserves SOURCE_ORDER, keeping the
1772 # sources dict insertion order — and render grouping — deterministic.
1773 with concurrent.futures.ThreadPoolExecutor(
1774 max_workers=min(8, len(SOURCE_ORDER))
1775 ) as pool:
1776 sources: Dict[str, Dict[str, Any]] = dict(
1777 zip(SOURCE_ORDER, pool.map(_build_one, SOURCE_ORDER))
1778 )
1779
1780 # U1: overlay the last research run's per-source outcome onto each record
1781 # so the audit layer can tell "configured" from "actually working".
1782 # U2: derive each record's four-state audit bucket (probe evidence, when a
1783 # live probe runs, is layered on in run() before render).
1784 evidence = load_run_evidence(config)
1785 for source, record in sources.items():
1786 if _is_excluded(source, excluded):
1787 record["run_outcome"] = None
1788 record["audit_state"] = audit_state(source, record, None)
1789 continue
1790 record["run_outcome"] = evidence["outcomes"].get(source) if evidence["fresh"] else None
1791 record["audit_state"] = audit_state(source, record, record["run_outcome"])
1792
1793 # U3: annotate each CLI-dependent source with its binary's health so the
1794 # per-source marker and the dedicated CLI-health block can render (R2).
1795 for source, cli_name in CLI_DEPENDENCIES.items():
1796 if _is_excluded(source, excluded):
1797 continue
1798 record = sources.get(source)
1799 if record is None:
1800 continue
1801 try:
1802 probe = health.probe_dependency(cli_name)
1803 except Exception:
1804 continue
1805 record["cli"] = {
1806 "name": cli_name,
1807 "status": probe.status,
1808 "off_path": bool(getattr(probe, "off_path", False)),
1809 "detail": probe.detail,
1810 "optional": source in _OPTIONAL_CLI_SOURCES,
1811 }
1812
1813 # U7: attach backup + comment sub-lanes to their parent source.
1814 for source, record in sources.items():
1815 if _is_excluded(source, excluded):
1816 continue
1817 backups, comments = _sub_lanes_for(source, config)
1818 if backups:
1819 record["backups"] = backups
1820 if comments is not None:
1821 record["comments"] = comments
1822
1823 # Reddit: one row per path, from the health cache and the saved run (any
1824 # age: the row says what the last run saw, the skip says what is in force).
1825 reddit_record = sources.get("reddit")
1826 if reddit_record is not None and not _is_excluded("reddit", excluded):
1827 reddit_outcome = evidence["outcomes"].get("reddit")
1828 try:
1829 reddit_record["paths"] = _reddit_path_rows(reddit_outcome, config)
1830 except Exception:
1831 pass
1832 for backup in reddit_record.get("backups") or []:
1833 if backup.get("name") == "ScrapeCreators backfill":
1834 backup["note"] = f"{backup.get('note') or ''}{_reddit_sc_last_run(reddit_outcome)}"
1835
1836 # Sequential on purpose: the permission preflight composes pipeline
1837 # diagnostics and must not race the source builders.
1838 try:
1839 permissions = _permissions_block(config)
1840 except Exception as exc:
1841 permissions = {"status": "unavailable", "error": f"{type(exc).__name__}: {exc}"}
1842
1843 try:
1844 brief_hooks = _brief_capture_hooks_block(config)
1845 except Exception as exc:
1846 brief_hooks = {"error": f"{type(exc).__name__}: {exc}", "harnesses": {}, "finished_briefs": 0}
1847
1848 return {
1849 "engine_version": _engine_version(),
1850 "config": {
1851 "global_env": str(env.CONFIG_FILE) if env.CONFIG_FILE else None,
1852 "config_source": config.get("_CONFIG_SOURCE"),
1853 # The resolved host value, so a missing export is visible.
1854 "host": env.x_policy(config).host or None,
1855 # A .env line cannot declare the X connector lane.
1856 "host_lane_file_ignored": bool(config.get("_X_HOST_LANE_FILE_IGNORED")),
1857 },
1858 "setup": _setup_block(config),
1859 "rust_core": rust_accel.status(),
1860 "brief_capture_hooks": brief_hooks,
1861 "permissions": permissions,
1862 "sources": sources,
1863 "mode": "config",
1864 "run_evidence": {
1865 "present": evidence["present"],
1866 "fresh": evidence["fresh"],
1867 "topic": evidence["topic"],
1868 "at": evidence["at"],
1869 },
1870 }
1871
1872
1873 # ---------------------------------------------------------------------------
1874 # Renderers
1875 # ---------------------------------------------------------------------------
1876
1877 def render_json(report: Dict[str, Any]) -> str:
1878 return json.dumps(report, indent=2, sort_keys=True)
1879
1880
1881 def _cli_marker(record: Dict[str, Any]) -> str:
1882 """Inline `[CLI: name ✓]` / `[keyless]` marker (populated by U3)."""
1883 cli = record.get("cli")
1884 if not cli:
1885 return ""
1886 name = cli.get("name")
1887 if cli.get("status") == health.OK:
1888 return f" [CLI: {name} ✓]"
1889 if cli.get("off_path"):
1890 return f" [CLI: {name} ✗ off-PATH]"
1891 return f" [CLI: {name} ✗ {cli.get('status')}]"
1892
1893
1894 def _run_evidence_suffix(record: Dict[str, Any], state: str) -> str:
1895 """Last-run outcome tail for a source line (R4)."""
1896 ro = record.get("run_outcome")
1897 if not ro:
1898 if state == AUDIT_UNVERIFIED:
1899 return " [no recent run]"
1900 return ""
1901 st = ro.get("state")
1902 count = ro.get("items_returned") or 0
1903 detail = ro.get("detail")
1904 if st in _RUN_WORKING_STATES:
1905 if count:
1906 return f" [✓ {count} items last run]"
1907 return " [✓ ran clean, 0 matches last run]"
1908 if st == health.PARTIAL:
1909 tail = f" ({detail})" if detail else ""
1910 return f" [⚠ partial last run{tail}]"
1911 tail = detail or st
1912 return f" [✕ {tail} last run]"
1913
1914
1915 def _audit_source_line(name: str, record: Dict[str, Any], state: str) -> str:
1916 glyph = AUDIT_GLYPHS.get(state, "?")
1917 parts = [f" {glyph} {name}{_cli_marker(record)}"]
1918 descriptors: List[str] = []
1919 if record.get("status") not in (health.OK,):
1920 descriptors.append(record["status"])
1921 if record.get("note"):
1922 descriptors.append(record["note"])
1923 elif record.get("detail") and record.get("tier") != TIER_OK:
1924 descriptors.append(record["detail"])
1925 if descriptors:
1926 parts.append(" — " + "; ".join(descriptors))
1927 if (record.get("probe") or {}).get("partial"):
1928 parts.append("; " + str(record["probe"].get("detail") or "partial probe"))
1929 evidence = _run_evidence_suffix(record, state)
1930 if evidence:
1931 parts.append(evidence)
1932 # fix is only ever populated when there is something actionable, so
1933 # render it whenever present — an ok-tier record can carry one (the
1934 # youtube transcription-key note) and must not lose it in text mode.
1935 if record.get("fix"):
1936 parts.append(f"; fix: {record['fix']}")
1937 # Backup / comment sub-lanes render on their own indented lines (U7),
1938 # after the primary line (with its fix) is complete.
1939 for sub in _sub_lane_lines(record):
1940 parts.append("\n" + sub)
1941 return "".join(parts)
1942
1943
1944 def _sub_lane_lines(record: Dict[str, Any]) -> List[str]:
1945 """Indented backup/comment sub-lane lines under a source (R8, R9)."""
1946 lines: List[str] = []
1947 for row in record.get("paths") or []:
1948 seen = row.get("last_run") or "no saved run"
1949 parts = [f"last run {seen}" if row.get("last_run") else seen]
1950 if row.get("consent"):
1951 browser = f" ({row['browser']})" if row.get("browser") else ""
1952 parts.insert(0, f"consent {row['consent']}{browser}")
1953 if row.get("skip_until"):
1954 parts.append(f"skipped until {row['skip_until']}")
1955 lines.append(
1956 f" path: {row['name']} - {'; '.join(parts)} - action: {row.get('action') or 'none'}"
1957 )
1958 for backup in record.get("backups") or []:
1959 state = "armed" if backup.get("armed") else "off"
1960 note = f" - {backup['note']}" if backup.get("note") else ""
1961 lines.append(f" backup: {backup['name']} — {state}{note}")
1962 comments = record.get("comments")
1963 if comments is not None:
1964 state = "on" if comments.get("enabled") else "off"
1965 lines.append(f" comments: {state}")
1966 return lines
1967
1968
1969 def _cli_health_lines(report: Dict[str, Any]) -> List[str]:
1970 """Dedicated CLI-health block (R2): one row per CLI-dependent source,
1971 plus a note naming the keyless sources that need no CLI at all.
1972 """
1973 sources = report.get("sources") or {}
1974 rows: List[str] = []
1975 for source in SOURCE_ORDER:
1976 cli = (sources.get(source) or {}).get("cli")
1977 if not cli:
1978 continue
1979 ok = cli.get("status") == health.OK
1980 glyph = "✓" if ok else "✗"
1981 detail = cli.get("detail") or cli.get("status")
1982 tail = ""
1983 if not ok:
1984 if cli.get("off_path"):
1985 tail = " (installed off-PATH)"
1986 elif cli.get("optional"):
1987 tail = " (optional)"
1988 rows.append(f" {glyph} {cli['name']} — {source}{tail}: {detail}")
1989 if not rows:
1990 return []
1991 return (
1992 ["CLI health (downloaded binaries):"]
1993 + rows
1994 + [" · Reddit, Hacker News, Polymarket need no CLI (keyless)"]
1995 )
1996
1997
1998 def render_text(report: Dict[str, Any]) -> str:
1999 lines: List[str] = [f"last30days doctor — engine v{report['engine_version']}"]
2000 config_block = report.get("config") or {}
2001 if config_block.get("global_env"):
2002 line = f"config: {config_block['global_env']}"
2003 if config_block.get("config_source"):
2004 line += f" (source: {config_block['config_source']})"
2005 lines.append(line)
2006 host = config_block.get("host")
2007 if host:
2008 lines.append(f"host: {host} ({env.X_HOST_VAR})")
2009 else:
2010 lines.append(f"host: not set ({env.X_HOST_VAR} unset; default X policy)")
2011 if config_block.get("host_lane_file_ignored"):
2012 lines.append(
2013 f"note: a {env.X_HOST_LANE_VAR} line in .env cannot declare the X "
2014 "connector lane (ignored); export it in the process environment "
2015 "for the session instead"
2016 )
2017
2018 setup = report.get("setup") or {}
2019 present = sorted(
2020 name for name, is_set in (setup.get("keys_present") or {}).items() if is_set
2021 )
2022 setup_state = "complete" if setup.get("setup_complete") else "not recorded"
2023 lines.append(
2024 f"setup: {setup_state}; credentials present: "
2025 + (", ".join(present) if present else "none")
2026 + " (values never shown)"
2027 )
2028 via_key = setup.get("via_api_key") or []
2029 if via_key:
2030 lines.append(
2031 "paid lanes via API key (LAST30DAYS_API_MODE=proxy): " + ", ".join(via_key)
2032 )
2033 templated = setup.get("unsubstituted_templates") or []
2034 if templated:
2035 lines.append(
2036 "note: unsubstituted config template(s), counted as unset: "
2037 + ", ".join(templated)
2038 + " (set a real value or remove each)"
2039 )
2040
2041 permissions = report.get("permissions") or {}
2042 if permissions.get("status"):
2043 browser = ((permissions.get("local_reads") or {}).get("browser_cookies") or {})
2044 lines.append(
2045 f"permissions: {permissions['status']}"
2046 + (f"; browser cookies: {browser.get('status')}" if browser else "")
2047 )
2048
2049 rc = report.get("rust_core") or {}
2050 if rc:
2051 if rc.get("active"):
2052 ver = f" v{rc['installed_version']}" if rc.get("installed_version") else ""
2053 lines.append(f"compute core: rust (last30days-core{ver}, {rc.get('binary_path')})")
2054 elif rc.get("mode") == "python":
2055 lines.append("compute core: python (LAST30DAYS_ENGINE=python)")
2056 elif rc.get("state") == "disabled_after_error":
2057 detail = rc.get("detail") or "worker error"
2058 lines.append(
2059 f"compute core: python fallback (last30days-core disabled after runtime error: {detail})"
2060 )
2061 elif rc.get("binary_path"):
2062 lines.append(
2063 f"compute core: rust binary discovered at {rc.get('binary_path')} "
2064 "(protocol not yet verified)"
2065 )
2066 else:
2067 lines.append(
2068 "compute core: python fallback (last30days-core binary not installed; "
2069 "run `last30days.py setup` to install)"
2070 )
2071
2072 run_ev = report.get("run_evidence") or {}
2073 if run_ev.get("present") and run_ev.get("fresh"):
2074 topic = run_ev.get("topic") or "last run"
2075 lines.append(
2076 f"last run: {topic} - overlaying actual source outcomes below"
2077 )
2078 elif run_ev.get("present"):
2079 lines.append(
2080 "last run: found but stale - run `doctor --postmortem` to inspect it"
2081 )
2082
2083 grouped: Dict[str, List[str]] = {state: [] for state, _ in AUDIT_GROUPS}
2084 for name, record in (report.get("sources") or {}).items():
2085 state = record.get("audit_state") or audit_state(
2086 name, record, record.get("run_outcome")
2087 )
2088 grouped.setdefault(state, []).append(_audit_source_line(name, record, state))
2089
2090 for state, header in AUDIT_GROUPS:
2091 entries = grouped.get(state) or []
2092 lines.append("")
2093 lines.append(f"{AUDIT_GLYPHS.get(state, '')} {header}:")
2094 if entries:
2095 lines.extend(entries)
2096 else:
2097 lines.append(" (none)")
2098
2099 cli_block = _cli_health_lines(report)
2100 if cli_block:
2101 lines.append("")
2102 lines.extend(cli_block)
2103
2104 hooks_info = report.get("brief_capture_hooks") or {}
2105 harnesses = hooks_info.get("harnesses") or {}
2106 if harnesses:
2107 active = [
2108 f"{name} ({entry['status']})"
2109 for name, entry in harnesses.items()
2110 if entry.get("status") in {"installed", "plugin-active"}
2111 ]
2112 finished_count = hooks_info.get("finished_briefs", 0)
2113 if active:
2114 active_label = ", ".join(active)
2115 else:
2116 bundled_note = (
2117 " (Claude plugin hook available when installed as a plugin)"
2118 if (harnesses.get("claude") or {}).get("plugin_bundled_available")
2119 else ""
2120 )
2121 active_label = (
2122 f"none active{bundled_note} — run `last30days.py setup --install-hooks`"
2123 )
2124 lines.append("")
2125 lines.append(f"brief capture hooks: {active_label}; finished briefs: {finished_count}")
2126
2127 lines.append("")
2128 lines.append(
2129 "doctor reports problems without failing; run the printed fixes, "
2130 "then re-run doctor"
2131 )
2132 return "\n".join(lines) + "\n"
2133
2134
2135 # ---------------------------------------------------------------------------
2136 # Post-mortem (U4 / R5): what actually happened on the last run
2137 #
2138 # Unlike plain doctor (config prediction), --postmortem reads the last run's
2139 # per-source SourceOutcome and reports what broke, at any age (labeled). It is
2140 # a reader of the same last-report.json the overlay uses - no new persistence.
2141 # ---------------------------------------------------------------------------
2142
2143 def _age_label(iso: Any) -> str:
2144 if not iso:
2145 return ""
2146 try:
2147 ts = datetime.datetime.fromisoformat(iso)
2148 except (TypeError, ValueError):
2149 return ""
2150 if ts.tzinfo is None:
2151 ts = ts.replace(tzinfo=datetime.timezone.utc)
2152 secs = int(
2153 (datetime.datetime.now(datetime.timezone.utc) - ts).total_seconds()
2154 )
2155 if secs < 0:
2156 return ""
2157 if secs < 3600:
2158 return f"{secs // 60}m ago"
2159 if secs < 86400:
2160 return f"{secs // 3600}h ago"
2161 return f"{secs // 86400}d ago"
2162
2163
2164 def build_postmortem(config: Dict[str, Any]) -> Dict[str, Any]:
2165 """Assemble the last run's per-source outcomes (any age) for --postmortem."""
2166 evidence = load_run_evidence(config)
2167 return {
2168 "engine_version": _engine_version(),
2169 "mode": "postmortem",
2170 "present": evidence["present"],
2171 "topic": evidence["topic"],
2172 "at": evidence["at"],
2173 "outcomes": evidence["outcomes"],
2174 }
2175
2176
2177 def _postmortem_state_label(source: str, outcome: Dict[str, Any]) -> str:
2178 """State label for a failed post-mortem line.
2179
2180 ``payment-required`` reads as "credits exhausted" ("X API credits
2181 exhausted" for X) so the fix is obvious at a glance: top up, not re-login.
2182 Every other state prints as its raw name.
2183 """
2184 state = str(outcome.get("state") or "")
2185 if state == health.PAYMENT_REQUIRED:
2186 return health.credits_exhausted_label(source)
2187 return state
2188
2189
2190 def render_postmortem_text(pm: Dict[str, Any]) -> str:
2191 lines = [f"last30days post-mortem — engine v{pm['engine_version']}"]
2192 if not pm.get("present"):
2193 lines.append("")
2194 lines.append(
2195 "No saved run found - run `/last30days <topic>` first, or "
2196 "`doctor --probe` for a live check."
2197 )
2198 return "\n".join(lines) + "\n"
2199 topic = pm.get("topic") or "last run"
2200 age = _age_label(pm.get("at"))
2201 lines.append(f"last run: {topic}" + (f" ({age})" if age else ""))
2202
2203 failed, partial, succeeded, skipped = [], [], [], []
2204 for source, outcome in (pm.get("outcomes") or {}).items():
2205 state = outcome.get("state")
2206 if state in _RUN_WORKING_STATES:
2207 succeeded.append((source, outcome))
2208 elif state == health.PARTIAL:
2209 partial.append((source, outcome))
2210 elif state == health.SKIPPED_UNCONFIGURED:
2211 skipped.append((source, outcome))
2212 else:
2213 failed.append((source, outcome))
2214
2215 if failed:
2216 lines.append("")
2217 lines.append("Failed:")
2218 for source, outcome in failed:
2219 detail = outcome.get("detail") or outcome.get("state")
2220 lines.append(f" ✕ {source} — {_postmortem_state_label(source, outcome)}: {detail}")
2221 if outcome.get("fix_hint"):
2222 lines.append(f" fix: {outcome['fix_hint']}")
2223 if partial:
2224 lines.append("")
2225 lines.append("Partial:")
2226 for source, outcome in partial:
2227 count = outcome.get("items_returned") or 0
2228 detail = outcome.get("detail")
2229 tail = f" — {detail}" if detail else ""
2230 lines.append(f" ⚠ {source} ({count} items){tail}")
2231 if outcome.get("fix_hint"):
2232 lines.append(f" fix: {outcome['fix_hint']}")
2233 if succeeded:
2234 lines.append("")
2235 def _succeeded_label(source: str, outcome: Dict[str, Any]) -> str:
2236 count = outcome.get("items_returned") or 0
2237 detail = outcome.get("detail")
2238 if detail:
2239 noun = "item" if count == 1 else "items"
2240 return f"{source} ({count} {noun}; {detail})"
2241 return f"{source} ({count})"
2242
2243 names = ", ".join(_succeeded_label(s, o) for s, o in succeeded)
2244 lines.append(f"Succeeded: {names}")
2245 if skipped:
2246 lines.append("")
2247 lines.append(
2248 "Skipped (not configured): " + ", ".join(s for s, _ in skipped)
2249 )
2250 if not failed and not partial:
2251 lines.append("")
2252 lines.append("No failures on the last run.")
2253 return "\n".join(lines) + "\n"
2254
2255
2256 # ---------------------------------------------------------------------------
2257 # Cross-invocation cache (U5 / R5, KTD 8)
2258 #
2259 # Doctor writes its JSON result beside the existing ``last-run.json``
2260 # convention (env.CONFIG_DIR) so the SKILL.md standing rule's pre-research
2261 # check costs one file read on the healthy path instead of a dozen probe
2262 # subprocesses. ``--cached`` serves the stored report within the TTL and
2263 # falls through to a live run (rewriting the cache) when the file is stale,
2264 # absent, or corrupt — corruption is treated as absence, never a crash.
2265 # An explicit ``doctor`` (no ``--cached``) always runs live and refreshes.
2266 #
2267 # The payload carries a schema stamp (mirrors REPORT_CACHE_VERSION in
2268 # last30days.py) and a config fingerprint — a sha256 over the same
2269 # non-secret signals doctor already reports (key-presence booleans, backend
2270 # pin values, INCLUDE_SOURCES). A schema or fingerprint mismatch is treated
2271 # as stale, so a credential or pin change can never serve yesterday's
2272 # conclusions. Served reports carry ``from_cache`` + ``generated_at`` so
2273 # consumers can see staleness instead of inferring it.
2274 # ---------------------------------------------------------------------------
2275
2276 CACHE_FILENAME = "doctor-cache.json"
2277
2278 # Bump when the cached payload/report shape changes incompatibly; a
2279 # mismatched (or absent) stamp is treated as an absent cache.
2280 DOCTOR_CACHE_SCHEMA_VERSION = "last30days-doctor-cache/v1"
2281
2282 # TTL in SECONDS (env-tunable via LAST30DAYS_DOCTOR_TTL; registered in
2283 # lib/env.py's get_config key list so a .env-set value is not swallowed).
2284 DEFAULT_CACHE_TTL_SECONDS = 900
2285
2286 # Config vars whose values must never land in the cache file. Doctor output
2287 # carries no secrets by design (key presence is booleans only); this belt-and-
2288 # suspenders check refuses to persist the cache if a seeded value ever leaks.
2289 _SECRET_CONFIG_VARS = KEY_PRESENCE_VARS + (
2290 "AUTH_TOKEN",
2291 "CT0",
2292 "APIFY_API_TOKEN",
2293 "LAST30DAYS_PUBLISH_PASSWORD",
2294 "LAST30DAYS_API_KEY",
2295 env.REDDIT_SESSION_COOKIE_VAR,
2296 )
2297
2298 # Backend pin vars folded into the config fingerprint. Pin values are
2299 # backend names (e.g. "bird"), never secrets. The host key and the X
2300 # connector lane signal join them: both are non-secret switches that
2301 # change every X conclusion, so a cached report must not outlive them.
2302 _FINGERPRINT_PIN_VARS = (
2303 env.X_BACKEND_PIN_VAR,
2304 env.REDDIT_BACKEND_PIN_VAR,
2305 env.YOUTUBE_BACKEND_PIN_VAR,
2306 env.X_HOST_VAR,
2307 env.X_HOST_LANE_VAR,
2308 # The Reddit session's consent and browser change the session row.
2309 env.REDDIT_CONSENT_VAR,
2310 env.REDDIT_FROM_BROWSER_VAR,
2311 )
2312
2313 # Top-level report keys the renderers read unguarded; a cached report
2314 # missing any of them is treated as corrupt (absent), never rendered.
2315 _REQUIRED_REPORT_KEYS = ("engine_version", "config", "setup", "permissions", "sources")
2316
2317
2318 def cache_path() -> Optional[Path]:
2319 """The doctor cache file, beside last-run.json (None in clean mode)."""
2320 if env.CONFIG_DIR is None:
2321 return None
2322 return env.CONFIG_DIR / CACHE_FILENAME
2323
2324
2325 def cache_ttl_seconds(config: Dict[str, Any]) -> int:
2326 """LAST30DAYS_DOCTOR_TTL in seconds; process env > config; default 900."""
2327 raw: Any = os.environ.get("LAST30DAYS_DOCTOR_TTL")
2328 if raw is None:
2329 raw = (config or {}).get("LAST30DAYS_DOCTOR_TTL")
2330 if raw is None or raw == "":
2331 return DEFAULT_CACHE_TTL_SECONDS
2332 try:
2333 return max(0, int(raw))
2334 except (TypeError, ValueError):
2335 return DEFAULT_CACHE_TTL_SECONDS
2336
2337
2338 def _is_fresh(timestamp: Any, ttl_seconds: int) -> bool:
2339 return env.is_timestamp_fresh(timestamp, ttl_seconds)
2340
2341
2342 def _config_fingerprint(config: Dict[str, Any]) -> str:
2343 """sha256 over the non-secret config signals doctor already reports.
2344
2345 Inputs are key-presence BOOLEANS (never credential values — the same
2346 ``keys_present`` set the setup block renders), backend pin values
2347 (backend names, not secrets), and non-secret switches affecting doctor's
2348 conclusions. Adding or removing a credential, changing a pin, or toggling
2349 any tracked source/host/storage knob yields a new fingerprint, so
2350 ``read_cached_report`` treats the old cache as stale.
2351 """
2352 config = config or {}
2353
2354 def _cfg_or_env(key: str) -> str:
2355 raw = config.get(key)
2356 if raw is None:
2357 raw = os.environ.get(key)
2358 return str(raw or "")
2359
2360 from . import permission_preflight
2361
2362 raw_hosted_key = config.get("LAST30DAYS_API_KEY")
2363 if raw_hosted_key is None:
2364 raw_hosted_key = env.read_secret_env("LAST30DAYS_API_KEY")
2365 hosted_key_present = (
2366 bool(str(raw_hosted_key or "").strip()) and not proxy.is_sentinel(raw_hosted_key)
2367 )
2368 hosted_api_base = _cfg_or_env("LAST30DAYS_API_BASE").strip()
2369 if not hosted_api_base:
2370 hosted_endpoint_state = "unset"
2371 elif permission_preflight._valid_hosted_api_base(hosted_api_base):
2372 hosted_endpoint_state = "valid"
2373 else:
2374 hosted_endpoint_state = "invalid"
2375
2376 signals = {
2377 "keys_present": _setup_block(config)["keys_present"],
2378 "via_api_key": proxy.via_api_key(config),
2379 "hosted_key_present": hosted_key_present,
2380 "hosted_api_mode": _cfg_or_env("LAST30DAYS_API_MODE").strip().lower(),
2381 "hosted_endpoint_state": hosted_endpoint_state,
2382 "corpus_dirs": permission_preflight._configured_corpus_dirs(config),
2383 "pins": {var: str(config.get(var) or "") for var in _FINGERPRINT_PIN_VARS},
2384 "include_sources": str(config.get("INCLUDE_SOURCES") or ""),
2385 "exclude_sources": str(config.get("EXCLUDE_SOURCES") or ""),
2386 "trustpilot_no_browser": _cfg_or_env(trustpilot.NO_BROWSER_ENV),
2387 "telegram_sources": _cfg_or_env("TELEGRAM_SOURCES"),
2388 "xiaohongshu_api_base": str(config.get("XIAOHONGSHU_API_BASE") or ""),
2389 "native_search": _cfg_or_env("LAST30DAYS_NATIVE_SEARCH"),
2390 "claudecode": _cfg_or_env("CLAUDECODE"),
2391 "setup_complete": str(config.get("SETUP_COMPLETE") or ""),
2392 "reddit_sc_min_items": str(config.get("LAST30DAYS_REDDIT_SC_MIN_ITEMS") or ""),
2393 "memory_dir": str(config.get("LAST30DAYS_MEMORY_DIR") or ""),
2394 "library_context": str(config.get("LAST30DAYS_LIBRARY_CONTEXT") or ""),
2395 "x_cookie_access_denied": str(config.get("LAST30DAYS_X_COOKIE_ACCESS_DENIED") or ""),
2396 "browser_consent": str(config.get("BROWSER_CONSENT") or ""),
2397 "from_browser": str(config.get("FROM_BROWSER") or ""),
2398 "agentcookie": str(config.get("AGENTCOOKIE") or env.read_secret_env("AGENTCOOKIE") or ""),
2399 "x_api_opt_in": env.x_api_opt_in(),
2400 }
2401 canonical = json.dumps(signals, sort_keys=True, separators=(",", ":"))
2402 return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
2403
2404
2405 def _report_shape_ok(report: Any) -> bool:
2406 """True when a cached report satisfies the render contract.
2407
2408 Validates everything the renderers read unguarded: the required
2409 top-level keys exist (dict-valued where render calls ``.get`` on them),
2410 and every sources record is a dict carrying a known tier and a str
2411 status. Anything else is corrupt — treated as absent, never rendered.
2412 """
2413 if not isinstance(report, dict):
2414 return False
2415 if any(key not in report for key in _REQUIRED_REPORT_KEYS):
2416 return False
2417 if any(
2418 not isinstance(report[key], dict)
2419 for key in ("config", "setup", "permissions", "sources")
2420 ):
2421 return False
2422 sources = report["sources"]
2423 if not sources:
2424 return False
2425 for record in sources.values():
2426 if not isinstance(record, dict):
2427 return False
2428 if record.get("tier") not in GLYPHS:
2429 return False
2430 if not isinstance(record.get("status"), str):
2431 return False
2432 return True
2433
2434
2435 _MAX_DOCTOR_CACHE_BYTES = 4 * 1024 * 1024
2436
2437
2438 def _read_cache_text(path: Path) -> str:
2439 """Read the doctor cache file without following symlinks/FIFOs and with a size cap."""
2440 target = Path(path)
2441 if os.name == "posix":
2442 flags = (
2443 os.O_RDONLY
2444 | getattr(os, "O_NOFOLLOW", 0)
2445 | getattr(os, "O_NONBLOCK", 0)
2446 | getattr(os, "O_CLOEXEC", 0)
2447 )
2448 fd = os.open(target, flags)
2449 try:
2450 st = os.fstat(fd)
2451 if not stat.S_ISREG(st.st_mode):
2452 raise OSError(f"Expected a regular cache file: {target}")
2453 if st.st_size > _MAX_DOCTOR_CACHE_BYTES:
2454 raise ValueError("Doctor cache exceeds size limit")
2455 with os.fdopen(fd, "rb") as stream:
2456 fd = -1
2457 data = stream.read(_MAX_DOCTOR_CACHE_BYTES + 1)
2458 finally:
2459 if fd != -1:
2460 os.close(fd)
2461 if len(data) > _MAX_DOCTOR_CACHE_BYTES:
2462 raise ValueError("Doctor cache exceeds size limit")
2463 return data.decode("utf-8")
2464 private_files._reject_symlink_or_nonregular(target)
2465 with target.open("rb") as stream:
2466 data = stream.read(_MAX_DOCTOR_CACHE_BYTES + 1)
2467 if len(data) > _MAX_DOCTOR_CACHE_BYTES:
2468 raise ValueError("Doctor cache exceeds size limit")
2469 return data.decode("utf-8")
2470
2471
2472 def read_cached_report(config: Dict[str, Any]) -> Optional[Dict[str, Any]]:
2473 """Return the cached report when present, well-formed, and within TTL.
2474
2475 Any failure mode — unreadable file, invalid JSON, schema mismatch,
2476 config-fingerprint mismatch, wrong shape, bad or stale timestamp —
2477 returns None (cache treated as absent, never a crash).
2478
2479 A served report is stamped with ``from_cache: True`` and
2480 ``generated_at`` (the cache write time) so consumers see staleness.
2481 """
2482 path = cache_path()
2483 if path is None:
2484 return None
2485 try:
2486 payload = json.loads(_read_cache_text(path))
2487 except Exception:
2488 return None
2489 if not isinstance(payload, dict):
2490 return None
2491 if payload.get("schema") != DOCTOR_CACHE_SCHEMA_VERSION:
2492 return None # absent or mismatched schema stamp: treat as absent
2493 if payload.get("fingerprint") != _config_fingerprint(config):
2494 return None # credentials/pins/opt-ins changed: cache is stale
2495 report = payload.get("report")
2496 if not _report_shape_ok(report):
2497 return None
2498 if not _is_fresh(payload.get("timestamp"), cache_ttl_seconds(config)):
2499 return None
2500 report["generated_at"] = payload.get("timestamp")
2501 report["from_cache"] = True
2502 return report
2503
2504
2505 def _cache_secret_values(config: Dict[str, Any]) -> set[str]:
2506 secrets: set[str] = set()
2507 cfg = config or {}
2508 for var in _SECRET_CONFIG_VARS:
2509 value = cfg.get(var)
2510 if isinstance(value, str) and len(value) >= 4 and not proxy.is_sentinel(value):
2511 secrets.add(value)
2512 env_api_key = env.read_secret_env("LAST30DAYS_API_KEY")
2513 if isinstance(env_api_key, str) and len(env_api_key) >= 4 and not proxy.is_sentinel(env_api_key):
2514 secrets.add(env_api_key)
2515 for value in http.config_secret_values(cfg):
2516 if len(value) >= 4 and not proxy.is_sentinel(value):
2517 secrets.add(value)
2518 return secrets
2519
2520
2521 def _write_cache(report: Dict[str, Any], config: Dict[str, Any]) -> bool:
2522 """Best-effort cache write; refuses to persist any secret value.
2523
2524 Never fatal: any failure returns False after a one-line stderr warning
2525 (doctor's exit-0 contract is unaffected; only ``--cached`` reuse is).
2526 """
2527 try:
2528 path = cache_path()
2529 if path is None:
2530 return False
2531 payload = {
2532 "schema": DOCTOR_CACHE_SCHEMA_VERSION,
2533 "fingerprint": _config_fingerprint(config),
2534 "timestamp": report.get("generated_at")
2535 or datetime.datetime.now(datetime.timezone.utc).isoformat(),
2536 "report": report,
2537 }
2538 raw = json.dumps(payload, indent=2, sort_keys=True)
2539 for value in _cache_secret_values(config):
2540 if value in raw:
2541 return False # never write a cache containing a secret
2542 path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
2543 private_files.replace_private_text(path, raw)
2544 return True
2545 except Exception as exc:
2546 sys.stderr.write(
2547 f"[last30days] WARNING: could not write doctor cache: "
2548 f"{type(exc).__name__}: {exc}\n"
2549 )
2550 sys.stderr.flush()
2551 return False
2552
2553
2554 # ---------------------------------------------------------------------------
2555 # Live probe (U5 / R6)
2556 #
2557 # When there is no fresh run to learn from (or on explicit --probe), doctor
2558 # runs a BOUNDED live test so WORKING is verified, not guessed. Scope is
2559 # deliberate: free HTTP endpoints + keyless CLIs only. Credit-gated /
2560 # session-gated sources (x, tiktok, instagram, threads, ...) are NOT
2561 # live-probed - a health check must never spend ScrapeCreators credits or trip
2562 # auth rate limits; they stay UNVERIFIED with that noted. Every probe is capped
2563 # by a per-source deadline so a single slow source (YouTube's 120s search) can
2564 # never hang doctor.
2565 # ---------------------------------------------------------------------------
2566
2567 # Free, keyless liveness endpoints (reachability check, tiny payload).
2568 _HTTP_PROBE_URLS = {
2569 # Reddit's keyless floor as the lane asks it, built by the lane's own
2570 # module so the probe cannot drift from what the engine requests
2571 # (hand-copied URLs kept certifying endpoints the engine had abandoned,
2572 # last of them the anonymous site search). Brave discovery first; the
2573 # Arctic Shift /posts/ids hydration step follows in _PROBE_FOLLOW_UPS.
2574 "reddit": reddit_health.brave_probe_url(),
2575 "hackernews": "https://hn.algolia.com/api/v1/search?query=test&hitsPerPage=1",
2576 "polymarket": "https://gamma-api.polymarket.com/events?limit=1",
2577 "github": "https://api.github.com/rate_limit",
2578 }
2579
2580 # Per-source exception to "a 4xx still means the endpoint responded". The
2581 # keyless Reddit floor sends no credentials, so a 403/429 there is the host
2582 # refusing this client (the exact failure the engine hits), not reachability.
2583 _PROBE_BLOCKED_STATUSES = {"reddit": frozenset({403, 429})}
2584
2585 # Blocked statuses that mean "refused this probe right now", not "the source is
2586 # down". A single unretried 429 reported a healthy source as NOT WORKING, so
2587 # these get one retry and, if still refused, downgrade to unverified rather
2588 # than a false outage. 403 stays hard: that is a real keyless block.
2589 _PROBE_TRANSIENT_STATUSES = {"reddit": frozenset({429})}
2590
2591 # One retry only: the probe budget is the per-source deadline, and a source that
2592 # rate-limits twice in a row is worth surfacing as unverified.
2593 _PROBE_RETRY_DELAY_SECONDS = 2.0
2594
2595 # Probe with the identity the lane sends, or the probe measures the User-Agent
2596 # rather than the endpoint (get_text sends http.BROWSER_USER_AGENT).
2597 _PROBE_HEADERS = {
2598 "reddit": {
2599 "User-Agent": http.BROWSER_USER_AGENT,
2600 "Accept": "text/html",
2601 },
2602 }
2603
2604 # Per-source body validators, run on a 2xx: None means the body is the page the
2605 # lane parses, anything else is the reason it is not. A search engine answers a
2606 # refused client with a 200 challenge page, so status alone reads it as working.
2607 _PROBE_BODY_CHECKS: Dict[str, Callable[[str], Optional[str]]] = {
2608 "reddit": reddit_health.brave_probe_body,
2609 }
2610
2611 # Steps probed after the first URL passes: (health path, label, url, headers,
2612 # body check). Reddit's floor needs both discovery and hydration to serve.
2613 _PROBE_FOLLOW_UPS: Dict[str, tuple] = {
2614 "reddit": (
2615 (
2616 "arctic", "Arctic Shift", reddit_health.arctic_probe_url(),
2617 {"User-Agent": http.USER_AGENT, "Accept": "application/json"},
2618 reddit_health.arctic_probe_body,
2619 ),
2620 ),
2621 }
2622 # The health path the first probe URL answers for.
2623 _PROBE_HEALTH_PATH = {"reddit": ("brave", "Brave")}
2624
2625 DEFAULT_PROBE_TIMEOUT_SECONDS = 10
2626
2627
2628 def probe_timeout_seconds(config: Dict[str, Any]) -> int:
2629 """Per-source probe deadline; process env > config > default 10s."""
2630 raw: Any = os.environ.get("LAST30DAYS_DOCTOR_PROBE_TIMEOUT")
2631 if raw is None:
2632 raw = (config or {}).get("LAST30DAYS_DOCTOR_PROBE_TIMEOUT")
2633 if raw is None or raw == "":
2634 return DEFAULT_PROBE_TIMEOUT_SECONDS
2635 try:
2636 return max(1, int(raw))
2637 except (TypeError, ValueError):
2638 return DEFAULT_PROBE_TIMEOUT_SECONDS
2639
2640
2641 def _probeable_sources() -> tuple:
2642 """Sources doctor will live-probe: free HTTP endpoints + keyless CLIs.
2643
2644 github is HTTP-probed (its REST tier works without gh), so it is excluded
2645 from the CLI-probe path even though gh is in CLI_DEPENDENCIES.
2646 """
2647 cli_only = [s for s in CLI_DEPENDENCIES if s not in _HTTP_PROBE_URLS]
2648 return tuple(dict.fromkeys(list(_HTTP_PROBE_URLS) + cli_only))
2649
2650
2651 def _http_ok(
2652 url: str,
2653 timeout: float,
2654 *,
2655 blocked_statuses: frozenset = frozenset(),
2656 headers: Optional[Dict[str, str]] = None,
2657 body_check: Optional[Callable[[str], Optional[str]]] = None,
2658 deadline_monotonic: Optional[float] = None,
2659 ) -> tuple:
2660 """Reachability check: a 4xx still means the endpoint responded; 5xx or a
2661 connection/timeout error means it did not.
2662
2663 ``blocked_statuses`` names the per-source codes that mean "responded, but
2664 refused us" (Reddit's keyless 403/429) — those are a failure, not
2665 reachability. ``headers`` overrides the probe identity so a source can be
2666 probed with the same User-Agent its lane sends. ``body_check`` validates
2667 a 2xx body; a non-None reason fails the probe as blocked.
2668 """
2669 def _verdict(code: int) -> tuple:
2670 return code < 500 and code not in blocked_statuses, f"HTTP {code}"
2671
2672 try:
2673 req = urllib.request.Request(
2674 url, headers=headers or {"User-Agent": "last30days-doctor"}
2675 )
2676 if deadline_monotonic is not None:
2677 from . import bounded_get
2678
2679 code, body, error = bounded_get.get(
2680 req, timeout=timeout, deadline_monotonic=deadline_monotonic,
2681 read_body=body_check is not None, read_error_body=False,
2682 )
2683 if error is not None:
2684 return _verdict(error.code)
2685 if body_check is not None and code < 300:
2686 reason = body_check((body or b"").decode("utf-8", errors="replace"))
2687 if reason:
2688 return False, f"HTTP {code} but blocked: {reason}"
2689 return _verdict(code)
2690 with urllib.request.urlopen(req, timeout=timeout) as resp:
2691 code = getattr(resp, "status", 200) or 200
2692 if body_check is not None and code < 300:
2693 text = resp.read().decode("utf-8", errors="replace")
2694 reason = body_check(text)
2695 if reason:
2696 return False, f"HTTP {code} but blocked: {reason}"
2697 return _verdict(code)
2698 except urllib.error.HTTPError as exc:
2699 return _verdict(exc.code)
2700 except Exception as exc:
2701 from . import bounded_get
2702
2703 if isinstance(exc, bounded_get.GetTimeout):
2704 return False, "probe exceeded deadline"
2705 return False, f"{type(exc).__name__}: {exc}"
2706
2707
2708 def _transient_probe_detail(name: str, detail: str) -> bool:
2709 """True when ``detail`` is a status this source may refuse us transiently.
2710
2711 ``_http_ok`` renders its verdict as ``HTTP {code}``; both live in this module,
2712 so matching that shape here keeps the retry rule next to the codes it covers.
2713 """
2714 transient = _PROBE_TRANSIENT_STATUSES.get(name)
2715 if not transient:
2716 return False
2717 return any(detail == f"HTTP {code}" for code in transient)
2718
2719
2720 def _probe_url(
2721 name: str,
2722 url: str,
2723 timeout: float,
2724 deadline: float,
2725 *,
2726 headers: Optional[Dict[str, str]],
2727 body_check: Optional[Callable[[str], Optional[str]]],
2728 ) -> Dict[str, Any]:
2729 """One URL's probe verdict, with the per-source transient retry."""
2730 expired = {"ok": False, "detail": "probe exceeded deadline", "probed": True}
2731 probe_kwargs = {
2732 "blocked_statuses": _PROBE_BLOCKED_STATUSES.get(name, frozenset()),
2733 "headers": headers,
2734 "body_check": body_check,
2735 "deadline_monotonic": deadline,
2736 }
2737 ok, detail = _http_ok(url, timeout, **probe_kwargs)
2738 if time.monotonic() >= deadline or detail == "probe exceeded deadline":
2739 return expired
2740 if not ok and _transient_probe_detail(name, detail):
2741 remaining = deadline - time.monotonic()
2742 if remaining <= 0:
2743 return expired
2744 if remaining <= _PROBE_RETRY_DELAY_SECONDS:
2745 return {
2746 "ok": False,
2747 "transient": True,
2748 "detail": f"{detail} (retry skipped: insufficient probe budget)",
2749 "probed": True,
2750 }
2751 time.sleep(_PROBE_RETRY_DELAY_SECONDS)
2752 remaining = deadline - time.monotonic()
2753 if remaining <= 0:
2754 return expired
2755 ok, detail = _http_ok(url, remaining, **probe_kwargs)
2756 if time.monotonic() >= deadline or detail == "probe exceeded deadline":
2757 return expired
2758 if not ok and _transient_probe_detail(name, detail):
2759 return {
2760 "ok": False,
2761 "transient": True,
2762 "detail": f"{detail} (rate-limited twice; the lane retries with backoff)",
2763 "probed": True,
2764 }
2765 return {"ok": ok, "detail": detail, "probed": True}
2766
2767
2768 def _record_probe_health(path: str, res: Dict[str, Any]) -> None:
2769 """A doctor re-probe is fresh evidence: a pass clears the path's skip and a
2770 403 records one (reddit_health persists both); a 429 stays in memory."""
2771 try:
2772 if res.get("ok"):
2773 reddit_health.record(path, reddit_health.OK, "doctor probe")
2774 elif res.get("transient"):
2775 reddit_health.record(path, reddit_health.THROTTLED, "doctor probe")
2776 elif "HTTP 403" in str(res.get("detail") or ""):
2777 reddit_health.record(path, reddit_health.BLOCKED, "doctor probe: HTTP 403")
2778 except Exception:
2779 pass
2780
2781
2782 def _probe_source(name: str, config: Dict[str, Any], timeout: float) -> Optional[Dict[str, Any]]:
2783 if _is_excluded(name, env.exclude_sources(config)):
2784 return None
2785 deadline = time.monotonic() + timeout
2786 expired = {"ok": False, "detail": "probe exceeded deadline", "probed": True}
2787 if timeout <= 0:
2788 return expired
2789 url = _HTTP_PROBE_URLS.get(name)
2790 if url:
2791 res = _probe_url(
2792 name, url, timeout, deadline,
2793 headers=_PROBE_HEADERS.get(name), body_check=_PROBE_BODY_CHECKS.get(name),
2794 )
2795 first = _PROBE_HEALTH_PATH.get(name)
2796 if first:
2797 _record_probe_health(first[0], res)
2798 follow_ups = _PROBE_FOLLOW_UPS.get(name) or ()
2799 if (name == "reddit" and not res.get("ok")
2800 and not res.get("transient")
2801 and res.get("detail") != "probe exceeded deadline"):
2802 remaining = deadline - time.monotonic()
2803 if remaining > 0:
2804 listing = _probe_url(
2805 name, reddit_health.arctic_listing_probe_url(), remaining, deadline,
2806 headers={"User-Agent": http.USER_AGENT, "Accept": "application/json"},
2807 body_check=reddit_health.arctic_probe_body,
2808 )
2809 if listing.get("ok") and listing.get("detail") == "HTTP 200":
2810 return {
2811 "ok": False,
2812 "partial": True,
2813 "detail": f"Brave: {res['detail']}; Arctic Shift listings reachable",
2814 "probed": True,
2815 }
2816 if not res.get("ok") or not follow_ups:
2817 return res
2818 details = [f"{first[1]} {res['detail']}" if first else res["detail"]]
2819 for path, label, step_url, headers, body_check in follow_ups:
2820 remaining = deadline - time.monotonic()
2821 if remaining <= 0:
2822 return expired
2823 step = _probe_url(
2824 name, step_url, remaining, deadline, headers=headers, body_check=body_check,
2825 )
2826 _record_probe_health(path, step)
2827 if not step.get("ok"):
2828 return {**step, "detail": f"{label}: {step['detail']}"}
2829 details.append(f"{label} {step['detail']}")
2830 return {"ok": True, "detail": "; ".join(details), "probed": True}
2831 cli = CLI_DEPENDENCIES.get(name)
2832 if cli:
2833 try:
2834 probe = health.probe_dependency(cli, timeout=max(0, deadline - time.monotonic()))
2835 if time.monotonic() >= deadline:
2836 return expired
2837 except Exception as exc:
2838 return {"ok": False, "detail": f"{type(exc).__name__}: {exc}", "probed": True}
2839 return {"ok": bool(probe.ok), "detail": probe.detail, "probed": True}
2840 return None
2841
2842
2843 def _probe_sources(config: Dict[str, Any], timeout: int) -> Dict[str, Dict[str, Any]]:
2844 """Probe the probeable sources concurrently, each capped at ``timeout``.
2845
2846 A source that blows its deadline resolves to a probe-failure for that
2847 source only (never a hung command); other probes are unaffected.
2848 """
2849 excluded = env.exclude_sources(config)
2850 names = tuple(
2851 name for name in _probeable_sources()
2852 if not _is_excluded(name, excluded)
2853 )
2854 results: Dict[str, Dict[str, Any]] = {}
2855 with concurrent.futures.ThreadPoolExecutor(
2856 max_workers=min(8, len(names) or 1)
2857 ) as pool:
2858 futures = {
2859 name: pool.submit(_probe_source, name, config, timeout) for name in names
2860 }
2861 for name, fut in futures.items():
2862 try:
2863 res = fut.result()
2864 except concurrent.futures.TimeoutError:
2865 res = {"ok": False, "detail": "probe exceeded deadline", "probed": True}
2866 except Exception as exc:
2867 res = {
2868 "ok": False,
2869 "detail": f"{type(exc).__name__}: {exc}",
2870 "probed": True,
2871 }
2872 if res is not None:
2873 results[name] = res
2874 return results
2875
2876
2877 def _apply_probe(report: Dict[str, Any], probe_results: Dict[str, Dict[str, Any]]) -> None:
2878 """Attach probe results and re-derive audit_state for probed sources."""
2879 for name, res in probe_results.items():
2880 record = (report.get("sources") or {}).get(name)
2881 if record is None:
2882 continue
2883 record["probe"] = res
2884 record["audit_state"] = audit_state(
2885 name, record, record.get("run_outcome"), res
2886 )
2887
2888
2889 def run(
2890 config: Dict[str, Any],
2891 *,
2892 emit_json: bool = False,
2893 cached: bool = False,
2894 postmortem: bool = False,
2895 probe: bool = False,
2896 ) -> int:
2897 """Build (or serve the cached) doctor report and print it. Always exits 0
2898 (reporting problems is a successful run).
2899
2900 ``postmortem=True`` reads the last run's per-source outcomes (any age) and
2901 reports what broke, instead of predicting config health.
2902 ``probe=True`` (or no fresh run) runs a bounded live probe (U5) so WORKING
2903 is verified, not guessed.
2904 ``cached=True`` serves the stored report within the TTL; stale, absent,
2905 corrupt, schema-mismatched, or fingerprint-mismatched caches fall
2906 through to a live run that rewrites the cache — as does ANY exception
2907 raised while serving the cache (never-crash contract, KTD 8).
2908 ``cached=False`` (explicit ``doctor``) always runs live and refreshes.
2909 """
2910 if postmortem:
2911 pm = build_postmortem(config)
2912 if emit_json:
2913 print(json.dumps(pm, indent=2, sort_keys=True))
2914 else:
2915 print(render_postmortem_text(pm), end="")
2916 return 0
2917
2918 def _emit(report: Dict[str, Any]) -> None:
2919 if emit_json:
2920 # generated_at/from_cache ride the report dict, so they appear
2921 # at the JSON top level for free.
2922 print(render_json(report))
2923 else:
2924 # The cache-status line is printed here (run() owns this print)
2925 # because render_text's header belongs to the render layer, not
2926 # the cache layer.
2927 origin = "cached" if report.get("from_cache") else "live"
2928 print(render_text(report), end="")
2929 print(f"generated: {report.get('generated_at')} ({origin})")
2930
2931 if cached:
2932 try:
2933 cached_report = read_cached_report(config)
2934 if cached_report is not None:
2935 _emit(cached_report)
2936 return 0
2937 except Exception:
2938 # Belt-and-suspenders for shapes the validator misses: any
2939 # failure serving the cache falls through to a live run.
2940 pass
2941 report = build_report(config)
2942 if not cached:
2943 # An explicit doctor is how a user asks for a fresh look: the report
2944 # above still shows a cached grok audit failure, and dropping it here
2945 # makes the next run re-audit the build.
2946 try:
2947 from . import grok_audit
2948
2949 grok_audit.clear_failed()
2950 except Exception:
2951 pass
2952 # Same for Reddit's path skips: a doctor run is how a user says "try
2953 # that path again". The rows above keep showing what was skipped.
2954 try:
2955 _mark_reddit_skips_cleared(report, reddit_health.clear())
2956 except Exception:
2957 pass
2958 report["generated_at"] = datetime.datetime.now(datetime.timezone.utc).isoformat()
2959 report["from_cache"] = False
2960
2961 # U5: verify WORKING with a bounded live probe when asked (--probe) or when
2962 # there is no fresh run to learn from ("if no recent runs, run a live
2963 # test"). Scoped to free/CLI sources; credit-gated sources stay UNVERIFIED.
2964 fresh_run = bool((report.get("run_evidence") or {}).get("fresh"))
2965 if probe or not fresh_run:
2966 timeout = probe_timeout_seconds(config)
2967 excluded = env.exclude_sources(config)
2968 probeable = tuple(
2969 name for name in _probeable_sources()
2970 if not _is_excluded(name, excluded)
2971 )
2972 sys.stderr.write(
2973 f"[last30days] doctor live probe: checking {len(probeable)} free/CLI "
2974 f"sources ({timeout}s each; no credit-gated sources - x/tiktok/"
2975 f"instagram/threads stay unverified)\n"
2976 )
2977 sys.stderr.flush()
2978 try:
2979 probe_results = _probe_sources(config, timeout)
2980 except Exception:
2981 probe_results = {}
2982 _apply_probe(report, probe_results)
2983 report["mode"] = "probe"
2984 report["probe"] = {"ran": True, "timeout": timeout, "sources": list(probeable)}
2985
2986 _write_cache(report, config)
2987 _emit(report)
2988 return 0
2989
2989 lines PYTHON