AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
feat(doctor): unified doctor health command with fix prescriptions (#753)
Matt Van Horn750176314a4c
diff --git a/CONFIGURATION.md b/CONFIGURATION.mdindex 0ebdee3a..1ccd70c8 100644--- a/CONFIGURATION.md+++ b/CONFIGURATION.md@@ -333,6 +333,30 @@ The engine treats public jobs/careers postings as evidence of focus or priority---+## Health check (`doctor`)++One command answers "what's broken, what's serving, and what do I run to fix it" — per source: a rollup tier (ok / warn / off / error), the specific probe state, the backend the next run will use (for chained sources), and an exact fix on any non-ok tier:++```bash+python3 skills/last30days/scripts/last30days.py doctor # grouped text report+python3 skills/last30days/scripts/last30days.py doctor --json # machine contract+python3 skills/last30days/scripts/last30days.py doctor --cached # serve the cached report while fresh+```++Slash-command form: `/last30days doctor`. Reporting problems is a successful run — the exit code is always 0, no browser cookies are read, no network calls are made, and no secret values appear anywhere (key presence is booleans only). Backends within a chained source are probed sequentially with a 5-second budget per binary probe, so a chained source's worst-case check time is additive across its backends (only reached when several binaries hang at once).++Every live run writes its JSON result to `~/.config/last30days/doctor-cache.json` (beside `last-run.json`; honors `LAST30DAYS_CONFIG_DIR`). `doctor --cached` returns that stored report when it is younger than the TTL, and falls through to a live run — rewriting the cache — when it is stale, absent, or corrupt. The cache also self-invalidates on configuration change: the payload carries a schema stamp plus a fingerprint of non-secret config signals (which credentials are present as booleans, the `LAST30DAYS_X_BACKEND` / `LAST30DAYS_REDDIT_BACKEND` pin values, and `INCLUDE_SOURCES`), so adding or removing a key, changing a pin, or toggling an opt-in source makes the next `--cached` call run live — no raw secret ever enters the fingerprint or the file. Every report also carries `from_cache` (true/false) and `generated_at` (when the report was built), in the `--json` top level and as a final `generated: … (cached|live)` text line, so you can always tell how old a cached answer is. A failed cache write is never fatal — doctor prints a one-line stderr warning and continues. An explicit `doctor` without `--cached` always runs live and refreshes the cache.++| Var | Effect |+| --- | --- |+| `LAST30DAYS_DOCTOR_TTL` | Freshness window for `doctor --cached`, in **seconds**. Defaults to `900` (15 minutes). `0` makes every `--cached` call run live. |+| `LAST30DAYS_X_BACKEND` | Pins the X backend (`xai` / `bird` / `xurl` / `xquik`); doctor renders the pin and predicts "will use" accordingly. |+| `LAST30DAYS_REDDIT_BACKEND` | `scrapecreators` makes ScrapeCreators the primary Reddit backend; doctor renders Reddit's conditional routing with the pin applied. |++Web search has **no** env pin — pin it per-run with `--web-backend=<name>` only (see [Web search backend priority](#web-search-backend-priority)).++---+## Trend monitoring (`--store` + watchlist + briefings)The default behavior - one slug-named file per topic, overwritten on rerun - is the snapshot mode. For continuous monitoring, the repo ships three components most users miss:diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.mdindex c9fb651f..87798a84 100644--- a/skills/last30days/SKILL.md+++ b/skills/last30days/SKILL.md@@ -1,7 +1,7 @@---name: last30daysversion: "3.10.0"-description: "Research what people actually say about any topic in the last 30 days. Pulls posts and engagement from Reddit, X, YouTube, TikTok, Hacker News, Polymarket, GitHub, and the web."+description: "Research what people actually say about any topic in the last 30 days. Pulls posts and engagement from Reddit, X, YouTube, TikTok, Hacker News, Polymarket, GitHub, and the web. Includes a doctor health check to diagnose broken or missing sources."argument-hint: 'last30days nvidia earnings reaction | last30days AI video tools | last30days what users want in react'allowed-tools: Bash, Read, Write, AskUserQuestion, WebSearchhomepage: https://github.com/mvanhorn/last30days-skill@@ -625,6 +625,8 @@ SKILL_DIR="<absolute path of the directory containing the SKILL.md you just Read**Reddit backend pin:** Reddit defaults to the free public backend with ScrapeCreators as a backup when `SCRAPECREATORS_API_KEY` is available. If the user says public Reddit is shallow, bot-gated, or missing nested comments, tell them they can set `LAST30DAYS_REDDIT_BACKEND=scrapecreators` alongside `SCRAPECREATORS_API_KEY` to make ScrapeCreators primary and keep public Reddit as fallback. Do not set this automatically for normal runs.+**Doctor health check:** When the user asks for a health check ("is X working?", "why is a source missing?", "what's broken?", "did setup work?"), run `"${LAST30DAYS_PYTHON}" "${SKILL_DIR}/scripts/last30days.py" doctor` (append `--json` for the machine contract) and relay the per-source tiers and fix prescriptions. **MANDATORY standing rule.** Before research that depends on login-backed sources (X via cookies, Reddit's ScrapeCreators backfill), consult `doctor --cached --json` — it serves the report cached at `~/.config/last30days/doctor-cache.json` within its TTL (`LAST30DAYS_DOCTOR_TTL` seconds, default 900) for the cost of one file read. Re-run live `doctor` only when the cache is stale or the previous run reported a degraded login-backed source. When X is in ACTIVE_SOURCES_LIST, announce its predicted backend from the report's `sources.x.active_backend` (e.g. "X will use: bird") in the pre-research status line.+Then display (use "and more" if 5+ sources, otherwise list all with Oxford comma):diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.pyindex 618ef625..dcb162b0 100644--- a/skills/last30days/scripts/last30days.py+++ b/skills/last30days/scripts/last30days.py@@ -686,20 +686,7 @@ def _report_cache_ttl_seconds(config: dict[str, object]) -> int:def _is_report_cache_fresh(timestamp: object, ttl_seconds: int) -> bool:- if ttl_seconds <= 0:- return False- if not isinstance(timestamp, str) or not timestamp:- return False- try:- created_at = datetime.datetime.fromisoformat(timestamp)- except ValueError:- return False- if created_at.tzinfo is None:- created_at = created_at.replace(tzinfo=datetime.timezone.utc)- age = datetime.datetime.now(datetime.timezone.utc) - created_at.astimezone(- datetime.timezone.utc- )- return age.total_seconds() <= ttl_seconds+ return env.is_timestamp_fresh(timestamp, ttl_seconds)def _write_last_run(@@ -910,6 +897,15 @@ SKILL_ONLY_FLAGS = {"--agent",}+# Doctor passthrough: `doctor --json` / `doctor --cached` mirror the setup+# passthrough pattern (neither is a global parser flag; they only mean+# something to doctor). `--cached` serves the stored doctor-cache.json report+# within its TTL and falls through to a live run otherwise.+DOCTOR_PASSTHROUGH_FLAGS = {+ "--json",+ "--cached",+}+def _validate_extra_argv(parser: argparse.ArgumentParser, topic: str, extra_argv: list[str]) -> None:if not extra_argv:@@ -923,6 +919,15 @@ def _validate_extra_argv(parser: argparse.ArgumentParser, topic: str, extra_argv+ f"; supported setup passthrough flags are {', '.join(sorted(SETUP_PASSTHROUGH_FLAGS))}")return+ if topic.lower() == "doctor":+ unsupported = [arg for arg in extra_argv if arg not in DOCTOR_PASSTHROUGH_FLAGS]+ if unsupported:+ parser.error(+ "unsupported doctor argument(s): "+ + ", ".join(unsupported)+ + f"; supported doctor passthrough flags are {', '.join(sorted(DOCTOR_PASSTHROUGH_FLAGS))}"+ )+ returnskill_only = [arg for arg in extra_argv if arg in SKILL_ONLY_FLAGS]other_unknown = [arg for arg in extra_argv if arg not in SKILL_ONLY_FLAGS]if skill_only:@@ -940,7 +945,8 @@ def _validate_extra_argv(parser: argparse.ArgumentParser, topic: str, extra_argvdef _config_policy_for_args(args: argparse.Namespace, topic: str, extra_argv: list[str]) -> env.ConfigLoadPolicy:if args.no_browser_cookies:browser_mode = "off"- elif args.diagnose or args.preflight:+ elif args.diagnose or args.preflight or topic.lower() == "doctor":+ # doctor is plan-only like --diagnose: it must never read cookies.browser_mode = "plan_only"elif topic.lower() == "setup":browser_mode = "read" if _setup_allows_browser_cookies(args, extra_argv) else "off"@@ -948,7 +954,7 @@ def _config_policy_for_args(args: argparse.Namespace, topic: str, extra_argv: librowser_mode = "read"return env.ConfigLoadPolicy(browser_cookies=browser_mode,- inspect_ignored_project_config=args.diagnose or args.preflight,+ inspect_ignored_project_config=args.diagnose or args.preflight or topic.lower() == "doctor",)@@ -1005,6 +1011,18 @@ def main() -> int:print(permission_preflight.render_text(preflight), end="")return 0+ # Handle doctor subcommand: topic-word dispatch mirroring setup (exact+ # match only, so multi-word research topics containing "doctor" still+ # research normally). Aggregates probes/descriptors/prescriptions into+ # one grouped health surface; always exits 0.+ if topic.lower() == "doctor":+ from lib import doctor+ return doctor.run(+ config,+ emit_json=(args.emit == "json" or "--json" in extra_argv),+ cached="--cached" in extra_argv,+ )+# Handle setup subcommandif topic.lower() == "setup":from lib import setup_wizarddiff --git a/skills/last30days/scripts/lib/backends.py b/skills/last30days/scripts/lib/backends.pynew file mode 100644index 00000000..355e2d0d--- /dev/null+++ b/skills/last30days/scripts/lib/backends.py@@ -0,0 +1,607 @@+"""Backend-chain descriptors with predicted selection (doctor, R4).++Chained sources declare their routing here ONCE — imported from the+definitions ``lib/env.py`` already owns (chain order, pin var names) — and+``resolve()`` turns side-effect-free probes into a truthful prediction of+what the next run will do.++Two resolution modes:++- ``alternative`` (X, YouTube, web search): the pipeline tries genuinely+ interchangeable backends in a declared order. Resolution probes ALL+ candidates first, then picks (collect-then-pick): the first fully-usable+ backend wins the "will use" prediction; otherwise the best degraded+ candidate resolves with a warn tier; otherwise the source is an error+ carrying the highest-priority backend's prescription. Collecting before+ picking prevents an installed-but-unauthenticated preferred backend from+ shadowing a fully working fallback.++- ``conditional`` (Reddit): routing is per-query and outcome-dependent —+ public keyless composite by default, ScrapeCreators backfill only when+ results fall below the configured thinness floor (see the gating in+ ``lib/pipeline.py``). No probe can pick one winner, so resolution renders+ honest conditional wording instead of an ``active_backend``. Reddit's+ internal keyless lanes (rss/listing/arctic/shreddit) are sub-probe detail+ inside the public composite, never chain entries.++``active_backend`` semantics: a PREDICTION — "the first backend the probes+say the next run will try" — rendered as "will use". It is not an+observation of what served a past run, and runtime failover can still+diverge mid-run (a present-but-expired paid key passes a presence probe).++Paid lanes (xai, xquik, serper, and every other API-key backend, including+ScrapeCreators) probe KEY PRESENCE ONLY: a dict lookup, never a network+call or credential spend. Binary-backed lanes reuse the U1 dependency+probe layer (``health.probe_dependency``) so a stale shim reads as BROKEN,+not available (#692).++This module observes and predicts only. It must never alter which backend+the pipeline actually uses; parity with the pipeline's pre-failover+selection is asserted in ``tests/test_backend_descriptors.py``.+"""++from __future__ import annotations++from dataclasses import dataclass+from shutil import which+from typing import Any, Callable, Dict, List, Optional, Tuple++from . import env, health, prescriptions++# Resolution modes.+MODE_ALTERNATIVE = "alternative" # probe-ordered chain, first-usable wins+MODE_CONDITIONAL = "conditional" # per-query routing; wording, never a winner++# Rollup tiers for a resolved chain (doctor maps these into its R1 table).+TIER_OK = "ok"+TIER_WARN = "warn"+TIER_ERROR = "error"++# Web search backend order. grounding.web_search's auto branch owns the+# runtime behavior (brave -> exa -> serper -> parallel -> keyless floor);+# there is no importable constant there, so this declaration is guarded by+# the grounding-auto parity test rather than an import.+WEB_BACKEND_ORDER: Tuple[str, ...] = ("brave", "exa", "serper", "parallel", "keyless")++# YouTube backend order (pipeline: yt-dlp first, ScrapeCreators search+# fallback when yt-dlp is absent or fails — see lib/pipeline.py).+YOUTUBE_BACKEND_ORDER: Tuple[str, ...] = ("yt-dlp", "scrapecreators")++# Chain-failure fixes embed the registry's CLI forms (KTD 7): the command a+# backend finding prescribes and the one doctor/quality-nudge render for the+# same failure mode come from one entry and cannot drift.+_SC_PRESCRIPTION = (+ "set SCRAPECREATORS_API_KEY (free 10,000-call signup: "+ f"{prescriptions.get('scrapecreators', 'key_missing').fix_cli})"+)+_X_COOKIES_PRESCRIPTION = (+ "run setup with browser-cookie consent: "+ f"{prescriptions.get('x', 'cookies_missing').fix_cli}"+)+++@dataclass+class BackendFinding:+ """Side-effect-free probe outcome for one backend of a chained source.++ ``status`` uses the ``lib.health`` vocabulary (OK/DEGRADED/MISSING/+ BROKEN/TIMEOUT/ERROR). ``prescription`` is the fix when non-OK.+ ``requires`` is the backend's requirement note for report rendering.+ """++ name: str+ status: str+ detail: str = ""+ prescription: str = ""+ requires: str = ""++ @property+ def usable(self) -> bool:+ """Fully or partially usable (OK/DEGRADED) — eligible for selection."""+ return self.status in (health.OK, health.DEGRADED)+++@dataclass(frozen=True)+class BackendSpec:+ """One backend in a chain: name, probe, requirement note, paid flag.++ ``probe`` must be side-effect-free. When ``paid`` is True the probe is+ key-presence only: no subprocess, no network, no credential spend.+ """++ name: str+ requires: str+ probe: Callable[[Dict[str, Any]], "BackendFinding"]+ paid: bool = False+++@dataclass(frozen=True)+class ChainDescriptor:+ """A chained source's declared routing: backends, mode, and pin knob."""++ source: str+ mode: str+ backends: Tuple[BackendSpec, ...]+ pin_var: Optional[str] = None # env var pin (X, Reddit)+ pin_flag: Optional[str] = None # CLI flag pin (web: --web-backend)+++@dataclass+class BackendResolution:+ """Resolved routing for one chained source.++ ``active_backend`` is the will-use PREDICTION for alternative chains+ and always None for conditional mode (Reddit never gets a computed+ winner — ``conditional`` carries the honest wording instead).+ """++ source: str+ mode: str+ chain: List[str]+ findings: List[BackendFinding]+ active_backend: Optional[str] = None+ tier: str = TIER_OK+ pinned: bool = False+ pin: Optional[str] = None+ prescription: str = ""+ conditional: str = ""++ @property+ def summary(self) -> str:+ """One-line rendering: will-use prediction or conditional wording."""+ if self.mode == MODE_CONDITIONAL:+ return self.conditional+ if self.active_backend is None:+ line = f"no usable backend (chain: {' -> '.join(self.chain)})"+ if self.prescription:+ line += f"; fix: {self.prescription}"+ return line+ line = f"will use: {self.active_backend}"+ if self.pinned:+ line += f" (pinned via {self._pin_origin()})"+ return line++ def _pin_origin(self) -> str:+ d = DESCRIPTORS.get(self.source)+ if d is None:+ return "pin"+ return d.pin_var or d.pin_flag or "pin"+++# ---------------------------------------------------------------------------+# Probes. All side-effect-free; paid lanes are pure dict lookups.+# ---------------------------------------------------------------------------++def _key_probe(name: str, key_var: str, requires: str, note: str = "") -> Callable:+ """Key-presence probe for a paid API lane. Never touches the network."""++ def probe(config: Dict[str, Any]) -> BackendFinding:+ if config.get(key_var):+ return BackendFinding(+ name=name,+ status=health.OK,+ detail=f"{key_var} present",+ requires=requires,+ )+ prescription = note or f"set {key_var} in ~/.config/last30days/.env"+ return BackendFinding(+ name=name,+ status=health.MISSING,+ detail=f"{key_var} not set",+ prescription=prescription,+ requires=requires,+ )++ return probe+++def _probe_bird(config: Dict[str, Any]) -> BackendFinding:+ """Bird = vendored X GraphQL client (node script) + browser-cookie creds.++ Cookie presence is checked FIRST, mirroring ``env._x_backend_available``'s+ gating (``has_bird_creds and is_bird_installed()``): without cookies bird+ is unconfigured regardless of node/script state, and the fix is the+ cookie-consent flow — a broken node runtime must not turn an unconfigured+ backend into an error carrying a node prescription.+ """+ from . import bird_x++ requires = "X browser cookies (AUTH_TOKEN/CT0) + node"+ if not (config.get("AUTH_TOKEN") and config.get("CT0")):+ return BackendFinding(+ name="bird",+ status=health.MISSING,+ detail="X browser cookies (AUTH_TOKEN/CT0) not configured",+ prescription=_X_COOKIES_PRESCRIPTION,+ requires=requires,+ )+ if not bird_x.is_bird_installed():+ # Distinguish a missing/broken node runtime from a missing script.+ node = health.probe_dependency("node")+ if node.status != health.OK:+ return BackendFinding(+ name="bird",+ status=node.status,+ detail=node.detail,+ prescription=node.prescription,+ requires=requires,+ )+ return BackendFinding(+ name="bird",+ status=health.MISSING,+ detail="vendored bird-search client not found",+ prescription="reinstall the skill (npx skills add . -g -y) to restore lib/vendor/bird-search",+ requires=requires,+ )+ node = health.probe_dependency("node")+ if node.status != health.OK:+ # Resolvable-but-broken node (stale shim) must not read as usable.+ return BackendFinding(+ name="bird",+ status=node.status,+ detail=node.detail,+ prescription=node.prescription,+ requires=requires,+ )+ return BackendFinding(+ name="bird",+ status=health.OK,+ detail="browser-cookie auth (AUTH_TOKEN/CT0) configured",+ requires=requires,+ )+++def _probe_xurl(config: Dict[str, Any]) -> BackendFinding:+ """xurl = official X API v2 CLI (OAuth2). Free lane; LOCAL-ONLY probe.++ Doctor's no-network guarantee forbids the live ``xurl whoami`` check+ (``xurl_x.is_available()`` — an authenticated X API call, reserved for+ research time). This probe keys on local evidence instead: the binary+ on PATH plus xurl's on-disk token store (~/.xurl). Stored credentials+ read as OK with an explicit "not live-verified" caveat; an unreadable+ token store is a typed ERROR (broken, not unconfigured).+ """+ from . import xurl_x++ requires = "xurl CLI installed + OAuth2 login"+ if which("xurl") is None:+ return BackendFinding(+ name="xurl",+ status=health.MISSING,+ detail="xurl CLI not found on PATH",+ prescription="npm install -g xurl && xurl auth oauth2 login",+ requires=requires,+ )+ store_status, store_detail = xurl_x.stored_auth_status()+ if store_status == xurl_x.AUTH_OK:+ return BackendFinding(+ name="xurl",+ status=health.OK,+ detail=(+ "installed; stored OAuth2 credentials present; "+ "auth not live-verified (no network)"+ ),+ requires=requires,+ )+ if store_status == xurl_x.AUTH_ERROR:+ return BackendFinding(+ name="xurl",+ status=health.ERROR,+ detail=store_detail,+ prescription="xurl auth oauth2 login",+ requires=requires,+ )+ return BackendFinding(+ name="xurl",+ status=health.MISSING,+ detail="xurl installed but not authenticated",+ prescription="xurl auth oauth2 login",+ requires=requires,+ )+++def _probe_ytdlp(config: Dict[str, Any]) -> BackendFinding:+ """yt-dlp via the U1 dependency-probe layer (missing/broken/timeout)."""+ dep = health.probe_dependency("yt-dlp")+ return BackendFinding(+ name="yt-dlp",+ status=dep.status,+ detail=dep.detail,+ prescription=dep.prescription,+ requires="yt-dlp on the agent-subprocess PATH",+ )+++def _probe_web_keyless(config: Dict[str, Any]) -> BackendFinding:+ """The keyless web-search floor: works keyless, but degraded quality."""+ requires = "no key; suppressed on native-search hosts"+ if env.keyless_web_allowed(config):+ return BackendFinding(+ name="keyless",+ status=health.DEGRADED,+ detail="keyless search floor (no paid key; lower quality)",+ requires=requires,+ )+ return BackendFinding(+ name="keyless",+ status=health.MISSING,+ detail="keyless floor suppressed: host has native web search",+ prescription="",+ requires=requires,+ )+++def _probe_reddit_public(config: Dict[str, Any]) -> BackendFinding:+ """Public keyless Reddit composite; internal lanes are sub-probe detail."""+ return BackendFinding(+ name="public",+ status=health.OK,+ detail="public keyless composite (lanes: rss, listing, arctic, shreddit)",+ requires="none (public endpoints)",+ )+++# ---------------------------------------------------------------------------+# Registry: routing declared once, from env.py's definitions where they exist.+# ---------------------------------------------------------------------------++_X_PROBES: Dict[str, Callable[[Dict[str, Any]], BackendFinding]] = {+ "xai": _key_probe("xai", "XAI_API_KEY", "XAI_API_KEY (xAI/Grok live search)"),+ "bird": _probe_bird,+ "xurl": _probe_xurl,+ "xquik": _key_probe("xquik", "XQUIK_API_KEY", "XQUIK_API_KEY (xquik.com)"),+}+_X_PAID = {"xai", "xquik"}++_WEB_PROBES: Dict[str, Callable[[Dict[str, Any]], BackendFinding]] = {+ "brave": _key_probe("brave", "BRAVE_API_KEY", "BRAVE_API_KEY"),+ "exa": _key_probe("exa", "EXA_API_KEY", "EXA_API_KEY"),+ "serper": _key_probe("serper", "SERPER_API_KEY", "SERPER_API_KEY"),+ "parallel": _key_probe("parallel", "PARALLEL_API_KEY", "PARALLEL_API_KEY"),+ "keyless": _probe_web_keyless,+}+_WEB_KEYED = {"brave", "exa", "serper", "parallel"}++_SC_SPEC = BackendSpec(+ name="scrapecreators",+ requires="SCRAPECREATORS_API_KEY",+ probe=_key_probe(+ "scrapecreators", "SCRAPECREATORS_API_KEY", "SCRAPECREATORS_API_KEY",+ note=_SC_PRESCRIPTION,+ ),+ paid=True,+)++DESCRIPTORS: Dict[str, ChainDescriptor] = {+ # X: chain order and pin var imported from env.py (single source of truth).+ "x": ChainDescriptor(+ source="x",+ mode=MODE_ALTERNATIVE,+ backends=tuple(+ BackendSpec(+ name=name,+ requires={+ "xai": "XAI_API_KEY (xAI/Grok live search)",+ "bird": "X browser cookies (AUTH_TOKEN/CT0) + node",+ "xurl": "xurl CLI installed + OAuth2 login",+ "xquik": "XQUIK_API_KEY (xquik.com)",+ }[name],+ probe=_X_PROBES[name],+ paid=name in _X_PAID,+ )+ for name in env.X_BACKEND_ORDER+ ),+ pin_var=env.X_BACKEND_PIN_VAR,+ ),+ "youtube": ChainDescriptor(+ source="youtube",+ mode=MODE_ALTERNATIVE,+ backends=(+ BackendSpec(+ name="yt-dlp",+ requires="yt-dlp on the agent-subprocess PATH",+ probe=_probe_ytdlp,+ ),+ _SC_SPEC,+ ),+ pin_var=None, # no YouTube pin knob exists+ ),+ "web": ChainDescriptor(+ source="web",+ mode=MODE_ALTERNATIVE,+ backends=tuple(+ BackendSpec(+ name=name,+ requires=(f"{name.upper()}_API_KEY" if name in _WEB_KEYED+ else "no key; suppressed on native-search hosts"),+ probe=_WEB_PROBES[name],+ paid=name in _WEB_KEYED,+ )+ for name in WEB_BACKEND_ORDER+ ),+ pin_var=None, # pinned per-run via --web-backend, not an env var+ pin_flag="--web-backend",+ ),+ "reddit": ChainDescriptor(+ source="reddit",+ mode=MODE_CONDITIONAL,+ backends=(+ BackendSpec(+ name="public",+ requires="none (public endpoints)",+ probe=_probe_reddit_public,+ ),+ _SC_SPEC,+ ),+ pin_var=env.REDDIT_BACKEND_PIN_VAR,+ ),+}+++def get_descriptor(source: str) -> ChainDescriptor:+ """Return the declared routing descriptor for ``source`` (KeyError if none)."""+ return DESCRIPTORS[source]+++# ---------------------------------------------------------------------------+# Resolution+# ---------------------------------------------------------------------------++def resolve(+ source: str,+ config: Dict[str, Any],+ pin: Optional[str] = None,+) -> BackendResolution:+ """Resolve a chained source's routing into a truthful prediction.++ ``pin`` is an explicit per-run pin (the ``--web-backend`` flag); it+ takes precedence over the descriptor's env pin var. ``"auto"``/None+ mean unpinned. Probing is side-effect-free and collect-then-pick.++ Time budget: backends are probed sequentially, so a chain's budget is+ ADDITIVE across its backends — each binary-backed probe is bounded by+ ``health.PROBE_TIMEOUT`` and paid/key lanes are dict lookups that cost+ nothing, giving a worst case of roughly (binary probes in the chain) x+ ``health.PROBE_TIMEOUT``. Deliberately no intra-chain concurrency:+ probes are memoized per process and the worst case only occurs when+ multiple binaries are simultaneously hung.+ """+ descriptor = get_descriptor(source)+ findings = [+ _run_probe(spec, config) for spec in descriptor.backends+ ]+ if descriptor.mode == MODE_CONDITIONAL:+ return _resolve_conditional(descriptor, config, findings)+ return _resolve_alternative(descriptor, config, findings, pin)+++def _run_probe(spec: BackendSpec, config: Dict[str, Any]) -> BackendFinding:+ """Run one probe, isolating failures so one bad probe can't blank a chain."""+ try:+ finding = spec.probe(config)+ except Exception as exc: # a probe bug must not take the report down+ finding = BackendFinding(+ name=spec.name,+ status=health.ERROR,+ detail=f"probe failed: {type(exc).__name__}: {exc}",+ requires=spec.requires,+ )+ if not finding.requires:+ finding.requires = spec.requires+ return finding+++def _resolve_alternative(+ descriptor: ChainDescriptor,+ config: Dict[str, Any],+ findings: List[BackendFinding],+ pin: Optional[str],+) -> BackendResolution:+ names = [spec.name for spec in descriptor.backends]+ by_name = {f.name: f for f in findings}+ res = BackendResolution(+ source=descriptor.source,+ mode=MODE_ALTERNATIVE,+ chain=list(names),+ findings=findings,+ )++ pin_name: Optional[str] = None+ if pin and pin not in ("auto", "none") and pin in by_name:+ pin_name = pin+ elif descriptor.pin_var:+ raw = (config.get(descriptor.pin_var) or "").lower()+ if raw in by_name:+ pin_name = raw++ if pin_name:+ # A pin forces a single backend (no failover) — mirror+ # env.x_backend_chain's pin semantics exactly.+ res.pinned = True+ res.pin = pin_name+ finding = by_name[pin_name]+ if finding.status == health.OK:+ res.active_backend = pin_name+ res.tier = TIER_OK+ elif finding.status == health.DEGRADED:+ res.active_backend = pin_name+ res.tier = TIER_WARN+ else:+ res.tier = TIER_ERROR+ res.prescription = finding.prescription or (+ f"unpin {descriptor.pin_var or descriptor.pin_flag} or fix {pin_name}"+ )+ return res++ # Collect-then-pick: first fully-usable wins; else best degraded; else+ # error carrying the highest-priority backend's prescription.+ for finding in findings:+ if finding.status == health.OK:+ res.active_backend = finding.name+ res.tier = TIER_OK+ return res+ for finding in findings:+ if finding.status == health.DEGRADED:+ res.active_backend = finding.name+ res.tier = TIER_WARN+ return res+ res.tier = TIER_ERROR+ res.prescription = findings[0].prescription if findings else ""+ return res+++def _reddit_sc_min_items(config: Dict[str, Any]) -> int:+ """The thinness floor, parsed exactly as the pipeline parses it+ (lib/pipeline.py reddit fetch: int(... or 0), malformed -> 0)."""+ try:+ return int(config.get(env.REDDIT_SC_MIN_ITEMS_VAR) or 0)+ except (TypeError, ValueError):+ return 0+++def _resolve_conditional(+ descriptor: ChainDescriptor,+ config: Dict[str, Any],+ findings: List[BackendFinding],+) -> BackendResolution:+ """Reddit: render the real per-query semantics, never a computed winner."""+ res = BackendResolution(+ source=descriptor.source,+ mode=MODE_CONDITIONAL,+ chain=[spec.name for spec in descriptor.backends],+ findings=findings,+ active_backend=None, # conditional mode never picks a winner+ tier=TIER_OK, # the public keyless composite is always reachable+ )+ has_key = bool(config.get("SCRAPECREATORS_API_KEY"))+ raw_pin = (config.get(descriptor.pin_var) or "").lower() if descriptor.pin_var else ""+ pinned_sc = has_key and raw_pin == "scrapecreators"+ floor = _reddit_sc_min_items(config)++ if pinned_sc:+ res.pinned = True+ res.pin = "scrapecreators"+ res.conditional = (+ f"ScrapeCreators primary (pinned via {descriptor.pin_var}); "+ "public keyless composite fallback"+ )+ return res++ if has_key:+ if floor > 0:+ backfill = (+ f"ScrapeCreators backfill when results fall below the "+ f"{floor}-item floor"+ )+ else:+ backfill = "ScrapeCreators backfill when the free path returns nothing"+ res.conditional = f"public keyless composite (default); {backfill}"+ return res++ res.conditional = "public keyless composite (default); no ScrapeCreators key for backfill"+ if raw_pin == "scrapecreators":+ # The pipeline ignores the pin without a key; say so honestly.+ res.conditional += (+ f" ({descriptor.pin_var} pin ignored: SCRAPECREATORS_API_KEY not set)"+ )+ return resdiff --git a/skills/last30days/scripts/lib/doctor.py b/skills/last30days/scripts/lib/doctor.pynew file mode 100644index 00000000..bb5f7ba5--- /dev/null+++ b/skills/last30days/scripts/lib/doctor.py@@ -0,0 +1,837 @@+"""Unified `doctor` health surface: aggregate, tier rollup, render (U4).++One command answers "what's broken, what's serving, and what do I run to+fix it" by composing the existing health layers instead of replacing them:++- U1 ``lib/health.py`` dependency probes (ok/missing/broken/timeout)+- U2 ``lib/backends.py`` chain descriptors + "will use" prediction+- U3 ``lib/prescriptions.py`` the single remediation vocabulary+- ``lib/pipeline.diagnose`` + ``lib/permission_preflight`` for the+ engine-level availability and permission summary++The legacy ``--diagnose`` / ``--preflight`` flags keep their frozen JSON+shapes (see ``tests/test_diagnose_compat.py``); anything new appears ONLY+in ``doctor --json``.++Tier rollup (the R1 machine contract). Per source, ``tier`` is the+four-value rollup and ``status`` preserves the most specific state:++| condition | status | tier |+|------------------------------------------------------|---------------|-------|+| probes pass, credentials (if any) present | ok | ok |+| usable but degraded (fallback serving, partial) | degraded | warn |+| opt-in not enabled / key-gated unconfigured | opt-in / | off |+| | unconfigured | |+| configured but missing / broken / timeout / error | that status | error |++Semantics and guarantees:++- ``active_backend`` is a PREDICTION ("will use"), never an observation+ (KTD 4). Reddit is conditional mode: honest wording, no single winner.+- On a native-search host with no web keys, engine-side web search is+ intentionally off — doctor reports tier ``off`` with a host-native note,+ never a false-alarm error. Web search has NO env pin, only the+ ``--web-backend`` flag; the record says so.+- No cookie reads (plan-only, like ``--diagnose``); no secret values+ anywhere — key presence is booleans only.+- Per-source exception isolation: one failing probe becomes that source's+ ``error`` record; it can never blank the report.+- Reporting problems is a successful run: the exit code is always 0.+"""++from __future__ import annotations++import concurrent.futures+import datetime+import hashlib+import json+import os+import shutil+import sys+from pathlib import Path+from typing import Any, Callable, Dict, List, Optional++from . import backends, env, health, prescriptions+from .backends import TIER_ERROR, TIER_OK, TIER_WARN++# Rollup tiers (R1). ok/warn/error are U2's; only "off" is doctor's own.+TIER_OFF = "off"++# Specific statuses and the rollup row each maps to. The doctor-local+# statuses "opt-in" and "unconfigured" have no health constant.+TIER_BY_STATUS: Dict[str, str] = {+ health.OK: TIER_OK,+ health.DEGRADED: TIER_WARN,+ "opt-in": TIER_OFF,+ "unconfigured": TIER_OFF,+ health.MISSING: TIER_ERROR,+ health.BROKEN: TIER_ERROR,+ health.TIMEOUT: TIER_ERROR,+ health.ERROR: TIER_ERROR,+}++GLYPHS = {TIER_OK: "✓", TIER_WARN: "!", TIER_OFF: "○", TIER_ERROR: "✗"}++GROUP_HEADERS = (+ (TIER_OK, "Ready"),+ (TIER_WARN, "Degraded"),+ (TIER_OFF, "Off"),+ (TIER_ERROR, "Errors"),+)++# Report order: chained sources first, then free, then key-gated/opt-in.+SOURCE_ORDER = (+ "reddit",+ "x",+ "youtube",+ "web",+ "hackernews",+ "polymarket",+ "github",+ "digg",+ "tiktok",+ "instagram",+ "threads",+ "bluesky",+ "truthsocial",+ "perplexity",+ "linkedin",+ "pinterest",+ "xiaohongshu",+ "jobs",+)++# Key-presence booleans for the setup block. NEVER values.+KEY_PRESENCE_VARS = (+ "SCRAPECREATORS_API_KEY",+ "XAI_API_KEY",+ "XQUIK_API_KEY",+ "BRAVE_API_KEY",+ "EXA_API_KEY",+ "SERPER_API_KEY",+ "PARALLEL_API_KEY",+ "GROQ_API_KEY",+ "OPENAI_API_KEY",+ "GOOGLE_API_KEY",+ "GEMINI_API_KEY",+ "OPENROUTER_API_KEY",+ "PERPLEXITY_API_KEY",+ "GITHUB_TOKEN",+ "TRUTHSOCIAL_TOKEN",+ "BSKY_APP_PASSWORD",+)++# Failing statuses ranked most-specific-first for chained rollups: a broken+# shim outranks a timeout outranks a generic error when naming the source's+# status (all three roll up to tier error regardless).+_SPECIFIC_FAILURES = (health.BROKEN, health.TIMEOUT, health.ERROR)+++def _fix_text(entry: prescriptions.Prescription) -> str:+ """Render a registry entry as one actionable fix line (NL + CLI forms)."""+ if entry.fix_cli and entry.fix_cli not in entry.fix_nl:+ return f"{entry.fix_nl} (cli: {entry.fix_cli})"+ return entry.fix_nl+++def _record(+ *,+ status: str,+ mode: str = "single",+ backends_list: Optional[List[Dict[str, Any]]] = None,+ active_backend: Optional[str] = None,+ fix: str = "",+ requires: str = "",+ note: str = "",+ detail: str = "",+ pin_var: Optional[str] = None,+ pin_flag: Optional[str] = None,+ pinned: bool = False,+) -> Dict[str, Any]:+ return {+ "tier": TIER_BY_STATUS[status],+ "status": status,+ "mode": mode,+ "backends": backends_list,+ "active_backend": active_backend,+ "fix": fix,+ "requires": requires,+ "note": note,+ "detail": detail,+ "pin_var": pin_var,+ "pin_flag": pin_flag,+ "pinned": pinned,+ }+++# ---------------------------------------------------------------------------+# Chained sources (via U2 descriptors)+# ---------------------------------------------------------------------------++def _finding_json(finding: backends.BackendFinding) -> Dict[str, Any]:+ return {+ "name": finding.name,+ "status": finding.status,+ "detail": finding.detail,+ "requires": finding.requires,+ "fix": finding.prescription,+ }+++def _chained_record(source: str, config: Dict[str, Any]) -> Dict[str, Any]:+ descriptor = backends.get_descriptor(source)+ res = backends.resolve(source, config)+ findings_json = [_finding_json(f) for f in res.findings]+ common = dict(+ mode=res.mode,+ backends_list=findings_json,+ active_backend=res.active_backend,+ pin_var=descriptor.pin_var,+ pin_flag=descriptor.pin_flag,+ pinned=res.pinned,+ )++ if res.mode == backends.MODE_CONDITIONAL:+ # Reddit: honest conditional wording (U2, verbatim), never a winner.+ return _record(status=health.OK, note=res.conditional,+ requires=res.findings[0].requires if res.findings else "",+ **common)++ by_name = {f.name: f for f in res.findings}+ if res.tier == backends.TIER_OK:+ active = by_name.get(res.active_backend)+ return _record(status=health.OK, note=res.summary,+ requires=active.requires if active else "", **common)+ if res.tier == backends.TIER_WARN:+ active = by_name.get(res.active_backend)+ return _record(status=health.DEGRADED, note=res.summary,+ detail=active.detail if active else "",+ fix=res.prescription,+ requires=active.requires if active else "", **common)++ # res.tier == error: separate "nothing configured" (tier off) from+ # "configured but broken" (tier error).+ if source == "web" and env.is_native_search(config):+ # The engine's web lanes are all unavailable BECAUSE the host brings+ # its own (better) native search — intentionally off, no false alarm.+ return _record(+ status="unconfigured",+ note=(+ "host-native search active (LAST30DAYS_NATIVE_SEARCH): the "+ "host's own web search serves this run; set a web key only "+ "if you want engine-side web search"+ ),+ requires=res.findings[0].requires if res.findings else "",+ **common,+ )+ if res.findings and all(f.status == health.MISSING for f in res.findings):+ return _record(+ status="unconfigured",+ fix=res.prescription,+ requires=res.findings[0].requires if res.findings else "",+ note=f"no backend configured (chain: {' -> '.join(res.chain)})",+ **common,+ )+ # Something IS configured/installed but won't serve: name the most+ # specific failure in chain order.+ status = health.ERROR+ fix = res.prescription+ detail = ""+ failed: Optional[backends.BackendFinding] = None+ for wanted in _SPECIFIC_FAILURES:+ failed = next((f for f in res.findings if f.status == wanted), None)+ if failed is not None:+ status = wanted+ fix = failed.prescription or res.prescription+ detail = failed.detail+ break+ # Mirror the OK/WARN branches: the requirement named is the FAILED+ # backend's, not chain[0]'s (which may be a different, merely-missing+ # backend when the failure came from later in the chain).+ return _record(status=status, fix=fix, detail=detail,+ requires=failed.requires if failed+ else (res.findings[0].requires if res.findings else ""),+ **common)+++# ---------------------------------------------------------------------------+# Single-backend sources+# ---------------------------------------------------------------------------++def _sc_fix() -> str:+ return _fix_text(prescriptions.get("scrapecreators", "key_missing"))+++def _sc_gated_record(config: Dict[str, Any], purpose: str) -> Dict[str, Any]:+ if config.get("SCRAPECREATORS_API_KEY"):+ return _record(status=health.OK, requires="SCRAPECREATORS_API_KEY",+ detail=f"SCRAPECREATORS_API_KEY present ({purpose})")+ return _record(status="unconfigured", requires="SCRAPECREATORS_API_KEY",+ fix=_sc_fix())+++def _reddit_record(config):+ return _chained_record("reddit", config)+++def _x_record(config):+ return _chained_record("x", config)+++def _youtube_record(config):+ record = _chained_record("youtube", config)+ if record["status"] == health.OK and not env.transcription_providers(config):+ # Usable, but the caption-free transcript backstop is unavailable.+ entry = prescriptions.get("youtube", "transcription_key_missing")+ record["note"] = (record["note"] + "; " if record["note"] else "") + (+ "no transcription key for caption-free videos"+ )+ record["fix"] = _fix_text(entry)+ return record+++def _web_record(config):+ return _chained_record("web", config)+++def _hackernews_record(config):+ return _record(status=health.OK, requires="none (free Algolia API)")+++def _polymarket_record(config):+ return _record(status=health.OK, requires="none (public API)")+++def _github_record(config):+ authed = bool(config.get("GITHUB_TOKEN") or shutil.which("gh"))+ detail = (+ "authenticated tier (GITHUB_TOKEN or gh CLI)"+ if authed+ else "unauthenticated REST tier (lower rate limits; GITHUB_TOKEN or gh raises them)"+ )+ return _record(status=health.OK, detail=detail,+ requires="none (GITHUB_TOKEN or gh CLI optional)")+++def _digg_record(config):+ probe = health.probe_dependency("digg-pp-cli")+ requires = "digg-pp-cli on the agent-subprocess PATH"+ if probe.ok:+ return _record(status=health.OK, detail=probe.detail, requires=requires)+ entry = prescriptions.for_dependency_probe(probe)+ fix = _fix_text(entry) if entry else probe.prescription+ if probe.status == health.MISSING and not probe.off_path:+ # Never installed: an optional source that simply isn't enabled.+ return _record(status="opt-in", fix=fix, detail=probe.detail, requires=requires)+ # Installed but off-PATH, broken, or timing out: configured-but-broken.+ return _record(status=probe.status, fix=fix, detail=probe.detail, requires=requires)+++def _tiktok_record(config):+ return _sc_gated_record(config, "tiktok")+++def _instagram_record(config):+ return _sc_gated_record(config, "instagram")+++def _threads_record(config):+ return _sc_gated_record(config, "threads")+++def _bluesky_record(config):+ if env.is_bluesky_available(config):+ return _record(status=health.OK, requires="BSKY_HANDLE + BSKY_APP_PASSWORD")+ return _record(+ status="unconfigured",+ requires="BSKY_HANDLE + BSKY_APP_PASSWORD",+ fix=_fix_text(prescriptions.get("bluesky", "app_password_missing")),+ )+++def _truthsocial_record(config):+ if env.is_truthsocial_available(config):+ return _record(status=health.OK, requires="TRUTHSOCIAL_TOKEN")+ return _record(+ status="unconfigured",+ requires="TRUTHSOCIAL_TOKEN",+ fix=_fix_text(prescriptions.get("truthsocial", "token_missing")),+ )+++def _perplexity_record(config):+ requires = "PERPLEXITY_API_KEY or OPENROUTER_API_KEY + INCLUDE_SOURCES=perplexity"+ has_key = bool(config.get("PERPLEXITY_API_KEY") or config.get("OPENROUTER_API_KEY"))+ include = env.include_sources(config)+ if not has_key:+ return _record(+ status="unconfigured", requires=requires,+ fix=(+ "set PERPLEXITY_API_KEY or OPENROUTER_API_KEY in "+ "~/.config/last30days/.env, then add perplexity to INCLUDE_SOURCES"+ ),+ )+ if "perplexity" in include:+ return _record(status=health.OK, requires=requires)+ return _record(+ status="opt-in", requires=requires,+ fix="add perplexity to INCLUDE_SOURCES (or request it via --search perplexity)",+ note="key present; source runs only when opted in",+ )+++def _linkedin_record(config):+ requires = "SCRAPECREATORS_API_KEY + INCLUDE_SOURCES=linkedin"+ if not config.get("SCRAPECREATORS_API_KEY"):+ return _record(status="unconfigured", requires=requires, fix=_sc_fix())+ if "linkedin" in env.include_sources(config):+ return _record(status=health.OK, requires=requires)+ return _record(+ status="opt-in", requires=requires,+ fix="add linkedin to INCLUDE_SOURCES (or request it via --search linkedin)",+ note="key present; power-user opt-in, never auto-activates",+ )+++def _pinterest_record(config):+ requires = "SCRAPECREATORS_API_KEY; requested-only (--search pinterest)"+ if not config.get("SCRAPECREATORS_API_KEY"):+ return _record(status="unconfigured", requires=requires, fix=_sc_fix())+ return _record(+ status="opt-in", requires=requires,+ fix="request it explicitly via --search pinterest (or INCLUDE_SOURCES)",+ note="key present; runs only when requested",+ )+++def _xiaohongshu_record(config):+ requires = "xiaohongshu-mcp service (XIAOHONGSHU_API_BASE); requested-only"+ entry = prescriptions.get("xiaohongshu", "service_unreachable")+ if config.get("XIAOHONGSHU_API_BASE"):+ return _record(+ status=health.OK, requires=requires,+ note=(+ "XIAOHONGSHU_API_BASE configured; service reachability is not "+ "probed (doctor makes no network calls)"+ ),+ )+ return _record(status="opt-in", requires=requires, fix=_fix_text(entry))+++def _jobs_record(config):+ return _record(+ status="opt-in",+ requires="none; activates for company topics or --hiring-signals",+ note="on-demand source: no configuration needed",+ )+++_SOURCE_BUILDERS: Dict[str, Callable[[Dict[str, Any]], Dict[str, Any]]] = {+ "reddit": _reddit_record,+ "x": _x_record,+ "youtube": _youtube_record,+ "web": _web_record,+ "hackernews": _hackernews_record,+ "polymarket": _polymarket_record,+ "github": _github_record,+ "digg": _digg_record,+ "tiktok": _tiktok_record,+ "instagram": _instagram_record,+ "threads": _threads_record,+ "bluesky": _bluesky_record,+ "truthsocial": _truthsocial_record,+ "perplexity": _perplexity_record,+ "linkedin": _linkedin_record,+ "pinterest": _pinterest_record,+ "xiaohongshu": _xiaohongshu_record,+ "jobs": _jobs_record,+}+++# ---------------------------------------------------------------------------+# Aggregation+# ---------------------------------------------------------------------------++def _engine_version() -> str:+ try:+ from . import render++ version = render._skill_version()+ except Exception:+ version = None+ # render's parent-walking helper falls back to "?"; doctor says "unknown".+ if not version or version == "?":+ return "unknown"+ return version+++def _setup_block(config: Dict[str, Any]) -> Dict[str, Any]:+ keys_present = {var: bool(config.get(var)) for var in KEY_PRESENCE_VARS}+ keys_present["x_browser_cookies"] = bool(+ config.get("AUTH_TOKEN") and config.get("CT0")+ )+ keys_present["bluesky_app_password"] = bool(+ config.get("BSKY_HANDLE") and config.get("BSKY_APP_PASSWORD")+ )+ return {+ "setup_complete": env.is_setup_complete(config),+ "keys_present": keys_present,+ }+++def _permissions_block(config: Dict[str, Any]) -> Dict[str, Any]:+ """Secret-free permission summary via the existing preflight provider."""+ from . import pipeline++ diag = pipeline.diagnose(config, None, safe=True)+ return diag["permission_preflight"]+++def build_report(config: Dict[str, Any]) -> Dict[str, Any]:+ """Aggregate every health provider into one report dict.++ Per-source exceptions are isolated: a failing builder yields an+ ``error`` record for that source and the rest of the report survives.+ """+ def _build_one(name: str) -> Dict[str, Any]:+ try:+ return _SOURCE_BUILDERS[name](config)+ except Exception as exc: # one bad probe must not blank the report+ return _record(+ status=health.ERROR,+ detail=f"probe failed: {type(exc).__name__}: {exc}",+ fix=_fix_text(prescriptions.get(name, "probe_error")),+ )++ # Builders are independent probes (subprocess/filesystem bound), so run+ # them concurrently. ``pool.map`` preserves SOURCE_ORDER, keeping the+ # sources dict insertion order — and render grouping — deterministic.+ with concurrent.futures.ThreadPoolExecutor(+ max_workers=min(8, len(SOURCE_ORDER))+ ) as pool:+ sources: Dict[str, Dict[str, Any]] = dict(+ zip(SOURCE_ORDER, pool.map(_build_one, SOURCE_ORDER))+ )++ # Sequential on purpose: the permission preflight composes pipeline+ # diagnostics and must not race the source builders.+ try:+ permissions = _permissions_block(config)+ except Exception as exc:+ permissions = {"status": "unavailable", "error": f"{type(exc).__name__}: {exc}"}++ return {+ "engine_version": _engine_version(),+ "config": {+ "global_env": str(env.CONFIG_FILE) if env.CONFIG_FILE else None,+ "config_source": config.get("_CONFIG_SOURCE"),+ },+ "setup": _setup_block(config),+ "permissions": permissions,+ "sources": sources,+ }+++# ---------------------------------------------------------------------------+# Renderers+# ---------------------------------------------------------------------------++def render_json(report: Dict[str, Any]) -> str:+ return json.dumps(report, indent=2, sort_keys=True)+++def _source_line(name: str, record: Dict[str, Any]) -> str:+ glyph = GLYPHS.get(record["tier"], "?")+ parts = [f" {glyph} {name}"]+ descriptors: List[str] = []+ if record["status"] not in (health.OK,):+ descriptors.append(record["status"])+ if record.get("note"):+ descriptors.append(record["note"])+ elif record.get("detail") and record["tier"] != TIER_OK:+ descriptors.append(record["detail"])+ if descriptors:+ parts.append(" — " + "; ".join(descriptors))+ # fix is only ever populated when there is something actionable, so+ # render it whenever present — an ok-tier record can carry one (the+ # youtube transcription-key note) and must not lose it in text mode.+ if record.get("fix"):+ parts.append(f"; fix: {record['fix']}")+ return "".join(parts)+++def render_text(report: Dict[str, Any]) -> str:+ lines: List[str] = [f"last30days doctor — engine v{report['engine_version']}"]+ config_block = report.get("config") or {}+ if config_block.get("global_env"):+ line = f"config: {config_block['global_env']}"+ if config_block.get("config_source"):+ line += f" (source: {config_block['config_source']})"+ lines.append(line)++ setup = report.get("setup") or {}+ present = sorted(+ name for name, is_set in (setup.get("keys_present") or {}).items() if is_set+ )+ setup_state = "complete" if setup.get("setup_complete") else "not recorded"+ lines.append(+ f"setup: {setup_state}; credentials present: "+ + (", ".join(present) if present else "none")+ + " (values never shown)"+ )++ permissions = report.get("permissions") or {}+ if permissions.get("status"):+ browser = ((permissions.get("local_reads") or {}).get("browser_cookies") or {})+ lines.append(+ f"permissions: {permissions['status']}"+ + (f"; browser cookies: {browser.get('status')}" if browser else "")+ )++ grouped: Dict[str, List[str]] = {tier: [] for tier, _ in GROUP_HEADERS}+ for name, record in (report.get("sources") or {}).items():+ grouped.setdefault(record["tier"], []).append(_source_line(name, record))++ for tier, header in GROUP_HEADERS:+ entries = grouped.get(tier) or []+ lines.append("")+ lines.append(f"{header}:")+ if entries:+ lines.extend(entries)+ else:+ lines.append(" (none)")++ lines.append("")+ lines.append(+ "doctor reports problems without failing; run the printed fixes, "+ "then re-run doctor"+ )+ return "\n".join(lines) + "\n"+++# ---------------------------------------------------------------------------+# Cross-invocation cache (U5 / R5, KTD 8)+#+# Doctor writes its JSON result beside the existing ``last-run.json``+# convention (env.CONFIG_DIR) so the SKILL.md standing rule's pre-research+# check costs one file read on the healthy path instead of a dozen probe+# subprocesses. ``--cached`` serves the stored report within the TTL and+# falls through to a live run (rewriting the cache) when the file is stale,+# absent, or corrupt — corruption is treated as absence, never a crash.+# An explicit ``doctor`` (no ``--cached``) always runs live and refreshes.+#+# The payload carries a schema stamp (mirrors REPORT_CACHE_VERSION in+# last30days.py) and a config fingerprint — a sha256 over the same+# non-secret signals doctor already reports (key-presence booleans, backend+# pin values, INCLUDE_SOURCES). A schema or fingerprint mismatch is treated+# as stale, so a credential or pin change can never serve yesterday's+# conclusions. Served reports carry ``from_cache`` + ``generated_at`` so+# consumers can see staleness instead of inferring it.+# ---------------------------------------------------------------------------++CACHE_FILENAME = "doctor-cache.json"++# Bump when the cached payload/report shape changes incompatibly; a+# mismatched (or absent) stamp is treated as an absent cache.+DOCTOR_CACHE_SCHEMA_VERSION = "last30days-doctor-cache/v1"++# TTL in SECONDS (env-tunable via LAST30DAYS_DOCTOR_TTL; registered in+# lib/env.py's get_config key list so a .env-set value is not swallowed).+DEFAULT_CACHE_TTL_SECONDS = 900++# Config vars whose values must never land in the cache file. Doctor output+# carries no secrets by design (key presence is booleans only); this belt-and-+# suspenders check refuses to persist the cache if a seeded value ever leaks.+_SECRET_CONFIG_VARS = KEY_PRESENCE_VARS + (+ "AUTH_TOKEN", "CT0", "APIFY_API_TOKEN", "GOOGLE_GENAI_API_KEY",+)++# Backend pin vars folded into the config fingerprint. Pin values are+# backend names (e.g. "bird"), never secrets.+_FINGERPRINT_PIN_VARS = (env.X_BACKEND_PIN_VAR, env.REDDIT_BACKEND_PIN_VAR)++# Top-level report keys the renderers read unguarded; a cached report+# missing any of them is treated as corrupt (absent), never rendered.+_REQUIRED_REPORT_KEYS = ("engine_version", "config", "setup", "permissions", "sources")+++def cache_path() -> Optional[Path]:+ """The doctor cache file, beside last-run.json (None in clean mode)."""+ if env.CONFIG_DIR is None:+ return None+ return env.CONFIG_DIR / CACHE_FILENAME+++def cache_ttl_seconds(config: Dict[str, Any]) -> int:+ """LAST30DAYS_DOCTOR_TTL in seconds; process env > config; default 900."""+ raw: Any = os.environ.get("LAST30DAYS_DOCTOR_TTL")+ if raw is None:+ raw = (config or {}).get("LAST30DAYS_DOCTOR_TTL")+ if raw is None or raw == "":+ return DEFAULT_CACHE_TTL_SECONDS+ try:+ return max(0, int(raw))+ except (TypeError, ValueError):+ return DEFAULT_CACHE_TTL_SECONDS+++def _is_fresh(timestamp: Any, ttl_seconds: int) -> bool:+ return env.is_timestamp_fresh(timestamp, ttl_seconds)+++def _config_fingerprint(config: Dict[str, Any]) -> str:+ """sha256 over the non-secret config signals doctor already reports.++ Inputs are key-presence BOOLEANS (never credential values — the same+ ``keys_present`` set the setup block renders), backend pin values+ (backend names, not secrets), and INCLUDE_SOURCES (not a secret).+ Adding or removing a credential, changing a pin, or toggling an opt-in+ source yields a new fingerprint, so ``read_cached_report`` treats the+ old cache as stale instead of serving pre-change conclusions.+ """+ config = config or {}+ signals = {+ "keys_present": _setup_block(config)["keys_present"],+ "pins": {var: str(config.get(var) or "") for var in _FINGERPRINT_PIN_VARS},+ "include_sources": str(config.get("INCLUDE_SOURCES") or ""),+ }+ canonical = json.dumps(signals, sort_keys=True, separators=(",", ":"))+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()+++def _report_shape_ok(report: Any) -> bool:+ """True when a cached report satisfies the render contract.++ Validates everything the renderers read unguarded: the required+ top-level keys exist (dict-valued where render calls ``.get`` on them),+ and every sources record is a dict carrying a known tier and a str+ status. Anything else is corrupt — treated as absent, never rendered.+ """+ if not isinstance(report, dict):+ return False+ if any(key not in report for key in _REQUIRED_REPORT_KEYS):+ return False+ if any(+ not isinstance(report[key], dict)+ for key in ("config", "setup", "permissions", "sources")+ ):+ return False+ sources = report["sources"]+ if not sources:+ return False+ for record in sources.values():+ if not isinstance(record, dict):+ return False+ if record.get("tier") not in GLYPHS:+ return False+ if not isinstance(record.get("status"), str):+ return False+ return True+++def read_cached_report(config: Dict[str, Any]) -> Optional[Dict[str, Any]]:+ """Return the cached report when present, well-formed, and within TTL.++ Any failure mode — unreadable file, invalid JSON, schema mismatch,+ config-fingerprint mismatch, wrong shape, bad or stale timestamp —+ returns None (cache treated as absent, never a crash).++ A served report is stamped with ``from_cache: True`` and+ ``generated_at`` (the cache write time) so consumers see staleness.+ """+ path = cache_path()+ if path is None:+ return None+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ except Exception:+ return None+ if not isinstance(payload, dict):+ return None+ if payload.get("schema") != DOCTOR_CACHE_SCHEMA_VERSION:+ return None # absent or mismatched schema stamp: treat as absent+ if payload.get("fingerprint") != _config_fingerprint(config):+ return None # credentials/pins/opt-ins changed: cache is stale+ report = payload.get("report")+ if not _report_shape_ok(report):+ return None+ if not _is_fresh(payload.get("timestamp"), cache_ttl_seconds(config)):+ return None+ report["generated_at"] = payload.get("timestamp")+ report["from_cache"] = True+ return report+++def _write_cache(report: Dict[str, Any], config: Dict[str, Any]) -> bool:+ """Best-effort cache write; refuses to persist any secret value.++ Never fatal: any failure returns False after a one-line stderr warning+ (doctor's exit-0 contract is unaffected; only ``--cached`` reuse is).+ """+ try:+ path = cache_path()+ if path is None:+ return False+ payload = {+ "schema": DOCTOR_CACHE_SCHEMA_VERSION,+ "fingerprint": _config_fingerprint(config),+ "timestamp": report.get("generated_at")+ or datetime.datetime.now(datetime.timezone.utc).isoformat(),+ "report": report,+ }+ raw = json.dumps(payload, indent=2, sort_keys=True)+ for var in _SECRET_CONFIG_VARS:+ value = (config or {}).get(var)+ if isinstance(value, str) and value and value in raw:+ return False # never write a cache containing a secret+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(raw, encoding="utf-8")+ return True+ except Exception as exc:+ sys.stderr.write(+ f"[last30days] WARNING: could not write doctor cache: "+ f"{type(exc).__name__}: {exc}\n"+ )+ sys.stderr.flush()+ return False+++def run(config: Dict[str, Any], *, emit_json: bool = False, cached: bool = False) -> int:+ """Build (or serve the cached) doctor report and print it. Always exits 0+ (reporting problems is a successful run).++ ``cached=True`` serves the stored report within the TTL; stale, absent,+ corrupt, schema-mismatched, or fingerprint-mismatched caches fall+ through to a live run that rewrites the cache — as does ANY exception+ raised while serving the cache (never-crash contract, KTD 8).+ ``cached=False`` (explicit ``doctor``) always runs live and refreshes.+ """+ def _emit(report: Dict[str, Any]) -> None:+ if emit_json:+ # generated_at/from_cache ride the report dict, so they appear+ # at the JSON top level for free.+ print(render_json(report))+ else:+ # The cache-status line is printed here (run() owns this print)+ # because render_text's header belongs to the render layer, not+ # the cache layer.+ origin = "cached" if report.get("from_cache") else "live"+ print(render_text(report), end="")+ print(f"generated: {report.get('generated_at')} ({origin})")++ if cached:+ try:+ cached_report = read_cached_report(config)+ if cached_report is not None:+ _emit(cached_report)+ return 0+ except Exception:+ # Belt-and-suspenders for shapes the validator misses: any+ # failure serving the cache falls through to a live run.+ pass+ report = build_report(config)+ report["generated_at"] = datetime.datetime.now(datetime.timezone.utc).isoformat()+ report["from_cache"] = False+ _write_cache(report, config)+ _emit(report)+ return 0diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.pyindex a2858382..cb0811bd 100644--- a/skills/last30days/scripts/lib/env.py+++ b/skills/last30days/scripts/lib/env.py@@ -2,6 +2,7 @@from __future__ import annotations+import datetimeimport jsonimport osimport sys@@ -97,6 +98,31 @@ def _truthy(value: Any) -> bool:return str(value).strip().lower() in {"1", "true", "yes", "on"}+def is_timestamp_fresh(timestamp_value: Any, ttl_seconds: int) -> bool:+ """True when ``timestamp_value`` (ISO-8601 string) is within ``ttl_seconds``.++ Shared freshness gate for the doctor cache and the report cache. The guard+ order is load-bearing: a non-positive TTL disables caching entirely, a+ non-string or empty timestamp is stale, a malformed timestamp is stale,+ naive timestamps are treated as UTC, and a future timestamp (negative age)+ counts as fresh.+ """+ if ttl_seconds <= 0:+ return False+ if not isinstance(timestamp_value, str) or not timestamp_value:+ return False+ try:+ created_at = datetime.datetime.fromisoformat(timestamp_value)+ except ValueError:+ return False+ if created_at.tzinfo is None:+ created_at = created_at.replace(tzinfo=datetime.timezone.utc)+ age = datetime.datetime.now(datetime.timezone.utc) - created_at.astimezone(+ datetime.timezone.utc+ )+ return age.total_seconds() <= ttl_seconds++def _project_config_trusted(policy: ConfigLoadPolicy, file_env: dict[str, Any]) -> bool:if policy.allow_project_config:return True@@ -413,6 +439,8 @@ def get_config(policy: ConfigLoadPolicy | None = None) -> dict[str, Any]:('LAST30DAYS_X_MODEL', None),('LAST30DAYS_X_BACKEND', None),('LAST30DAYS_REDDIT_BACKEND', None),+ # Doctor cache freshness window in seconds (doctor --cached).+ ('LAST30DAYS_DOCTOR_TTL', None),('LAST30DAYS_REDDIT_SC_MIN_ITEMS', None),('LAST30DAYS_STORE', None),('LAST30DAYS_MEMORY_DIR', None),@@ -673,8 +701,22 @@ def get_reddit_source(config: dict[str, Any]) -> str | None:# xquik — key-based REST X search (XQUIK_API_KEY); keyless of browser cookies_X_BACKEND_ORDER = ("xai", "bird", "xurl", "xquik")--def _x_backend_available(backend: str, config: dict[str, Any], has_bird_creds: bool) -> bool:+# Public routing definitions for the doctor/backend-descriptor layer+# (lib/backends.py). These are aliases for knowledge this module already+# owns — the declared X chain order and the pin/floor env var names — so+# descriptors import one source of truth instead of restating it.+X_BACKEND_ORDER = _X_BACKEND_ORDER+X_BACKEND_PIN_VAR = 'LAST30DAYS_X_BACKEND'+REDDIT_BACKEND_PIN_VAR = 'LAST30DAYS_REDDIT_BACKEND'+REDDIT_SC_MIN_ITEMS_VAR = 'LAST30DAYS_REDDIT_SC_MIN_ITEMS'+++def _x_backend_available(+ backend: str,+ config: dict[str, Any],+ has_bird_creds: bool,+ local_only: bool = False,+) -> bool:if backend == 'xai':return bool(config.get('XAI_API_KEY'))if backend == 'bird':@@ -682,13 +724,17 @@ def _x_backend_available(backend: str, config: dict[str, Any], has_bird_creds: breturn has_bird_creds and bird_x.is_bird_installed()if backend == 'xurl':from . import xurl_x+ if local_only:+ # Doctor/safe-diagnose path: local evidence only (PATH lookup ++ # token store) — never the live `xurl whoami` network call.+ return xurl_x.has_stored_auth()return xurl_x.is_available()if backend == 'xquik':return is_xquik_available(config)return False-def x_backend_chain(config: dict[str, Any]) -> list[str]:+def x_backend_chain(config: dict[str, Any], local_only: bool = False) -> list[str]:"""Ordered list of available X backends.``chain[0]`` is the default X source; the remaining entries are failover@@ -699,30 +745,41 @@ def x_backend_chain(config: dict[str, Any]) -> list[str]:user explicitly chose it. Browser-cookie probing is intentionally avoided(automatic Keychain access causes popups); bird counts as available onlywhen AUTH_TOKEN and CT0 are present explicitly.++ ``local_only=True`` is the doctor/safe-diagnose flavor: availability is+ answered from local evidence only (no subprocess spawns that reach the+ network — xurl's live `whoami` check is replaced by its on-disk token+ store). Research-time callers keep the default live semantics."""from . import bird_xhas_bird_creds = bool(config.get('AUTH_TOKEN') and config.get('CT0'))if has_bird_creds:bird_x.set_credentials(config.get('AUTH_TOKEN'), config.get('CT0'))- preferred = (config.get('LAST30DAYS_X_BACKEND') or '').lower()+ preferred = (config.get(X_BACKEND_PIN_VAR) or '').lower()if preferred in _X_BACKEND_ORDER:- return [preferred] if _x_backend_available(preferred, config, has_bird_creds) else []+ if _x_backend_available(preferred, config, has_bird_creds, local_only):+ return [preferred]+ return []- return [b for b in _X_BACKEND_ORDER if _x_backend_available(b, config, has_bird_creds)]+ return [+ b for b in _X_BACKEND_ORDER+ if _x_backend_available(b, config, has_bird_creds, local_only)+ ]-def get_x_source(config: dict[str, Any]) -> str | None:+def get_x_source(config: dict[str, Any], local_only: bool = False) -> str | None:"""The default (primary) X backend, or None if no X source is available.Thin wrapper over ``x_backend_chain`` returning the first/primary backend;callers that want failover should use ``x_backend_chain`` directly.+ ``local_only`` is forwarded (see ``x_backend_chain``)."""- chain = x_backend_chain(config)+ chain = x_backend_chain(config, local_only=local_only)return chain[0] if chain else None-def x_pending_browser_auth(config: dict[str, Any]) -> bool:+def x_pending_browser_auth(config: dict[str, Any], local_only: bool = False) -> bool:"""True when X is not available now but ``FROM_BROWSER`` will authenticate it at run time.``--diagnose`` / ``--preflight`` load config in ``plan_only`` mode, which@@ -741,7 +798,9 @@ def x_pending_browser_auth(config: dict[str, Any]) -> bool:extracted creds, so its status must be unchanged — never "pending")."""# Already available via a static backend (bird creds, xAI, xurl, xquik).- if get_x_source(config):+ # local_only (doctor/safe-diagnose) answers the xurl leg from the token+ # store instead of the live `xurl whoami` network call.+ if get_x_source(config, local_only=local_only):return False# Only meaningful in inspection modes that skip extraction; a real ``read``# run has already attempted extraction and must report its true state.@@ -908,6 +967,24 @@ def _parse_exclude_sources(config: dict[str, Any]) -> set[str]:return {s.strip().lower() for s in raw.split(',') if s.strip()}+def include_sources(config: dict[str, Any]) -> set[str]:+ """Public view of the parsed INCLUDE_SOURCES set.++ Thin wrapper over ``_parse_include_sources`` so other modules (doctor,+ etc.) don't reach into env's privates.+ """+ return _parse_include_sources(config)+++def is_setup_complete(config: dict[str, Any]) -> bool:+ """Whether guided setup marked this config complete (SETUP_COMPLETE truthy).++ Thin wrapper over ``_truthy`` so other modules don't reach into env's+ privates.+ """+ return _truthy(config.get('SETUP_COMPLETE'))++def is_threads_available(config: dict[str, Any]) -> bool:"""Check if the Threads credential is available.@@ -986,7 +1063,10 @@ def get_x_source_status(config: dict[str, Any], probe: bool = False) -> dict[str``bird_authenticated`` to False when X clearly returns nothing,so ``--diagnose`` reflects runtime reality instead of staticcredential presence. A transient timeout leaves the status- unchanged (fail open).+ unchanged (fail open). When False (the safe/diagnose path that+ doctor uses), NO network is touched: xurl availability comes+ from local evidence (``xurl_x.has_stored_auth``), never the+ live ``xurl whoami`` call.Returns:Dict with keys: source, bird_installed, bird_authenticated,@@ -1026,6 +1106,13 @@ def get_x_source_status(config: dict[str, Any], probe: bool = False) -> dict[strelse:xquik_status = "configured (not probed)"+ # Xurl availability, computed ONCE. probe=True (a live diagnose) may run+ # the real `xurl whoami`; probe=False is the safe path (doctor,+ # --diagnose, --preflight) and must stay local-only — the live check is+ # an authenticated X API network call.+ from . import xurl_x as _xurl_x+ xurl_available = _xurl_x.is_available() if probe else _xurl_x.has_stored_auth()+# Determine active source. bird (browser cookies) and xAI win when present;# when neither is available, xquik is the active X source. A probe that# clearly failed (False) means xquik is not actually usable.@@ -1034,22 +1121,20 @@ def get_x_source_status(config: dict[str, Any], probe: bool = False) -> dict[strelif xai_available:source = 'xai'else:- from . import xurl_x as _xurl_check- if _xurl_check.is_available():+ if xurl_available:source = 'xurl'elif xquik_available and xquik_working is not False:source = 'xquik'else:source = None- from . import xurl_x as _xurl_xreturn {"source": source,"bird_installed": bird_status["installed"],"bird_authenticated": bird_status["authenticated"],"bird_username": bird_status["username"],"xai_available": xai_available,- "xurl_available": _xurl_x.is_available(),+ "xurl_available": xurl_available,"xquik_available": xquik_available,"xquik_working": xquik_working,"xquik_status": xquik_status,diff --git a/skills/last30days/scripts/lib/health.py b/skills/last30days/scripts/lib/health.pyindex 2e3f2337..de6f63b6 100644--- a/skills/last30days/scripts/lib/health.py+++ b/skills/last30days/scripts/lib/health.py@@ -13,9 +13,12 @@ doomed *sources/tools*.from __future__ import annotations+import osimport shutilimport subprocessfrom dataclasses import dataclass+from pathlib import Path+from typing import Dict, Iterable, List, Optional, Tuple# Health states, best to worst.OK = "ok"@@ -90,3 +93,333 @@ def probe_command(detail = (proc.stderr or proc.stdout or "").strip().splitlines()first = detail[0] if detail else f"exit {proc.returncode}"return SourceHealth(name=name, state=ERROR, reason=f"{name}: {first}")+++# ---------------------------------------------------------------------------+# Dependency probes (doctor command, issue #692).+#+# ``probe_dependency`` generalizes ``probe_command`` for the skill's external+# binaries (yt-dlp, Printing Press CLIs, node for the vendored bird client,+# ffmpeg). It answers three questions the bare shutil.which gate cannot:+# - Is the binary genuinely runnable (a stale shim that resolves on PATH but+# cannot exec is BROKEN, not available)?+# - If not, WHICH fix applies (install vs reinstall vs a PATH edit), keyed to+# the package manager that owns the binary on this machine?+# - Is an on-disk binary merely off the agent-subprocess PATH (the Digg+# ~/.local/bin case) — MISSING with a PATH-fix, never "installed"?+#+# Semantics follow the engine gate: availability means PATH-resolvable in THIS+# process, not present-on-disk. Probes are one short-timeout version exec each+# and memoized per process, so doctor and setup can consult them freely.+# ---------------------------------------------------------------------------++# Per-probe budget in seconds: a healthy --version exec is near-instant, so a+# slow probe is itself a diagnostic (network-mounted shim, hung interpreter).+PROBE_TIMEOUT = 5.0++_PP_CLI_SUFFIX = "-pp-cli"+# Matches setup_wizard.PRINTING_PRESS_NPM (pinned catalog installer).+_PRINTING_PRESS_NPM = "@mvanhorn/[email protected]"++# Dependencies the doctor probes by default.+KNOWN_DEPENDENCIES: Tuple[str, ...] = ("yt-dlp", "digg-pp-cli", "node", "ffmpeg")++# Cheap side-effect-free version invocation per dependency (default --version).+_VERSION_ARGS: Dict[str, List[str]] = {+ "ffmpeg": ["-version"],+}++# Package managers each dependency may be owned by, in preference order, and+# the (install, reinstall) prescription for each. "reinstall" wording matters:+# a BROKEN binary is present, so telling the user to "install" it reads as a+# no-op ("it's already installed") — the stale-shim trap this module exists+# to name.+_MANAGER_PRESCRIPTIONS: Dict[str, Dict[str, Tuple[str, str]]] = {+ "yt-dlp": {+ "brew": ("brew install yt-dlp", "brew reinstall yt-dlp"),+ "pipx": ("pipx install yt-dlp", "pipx reinstall yt-dlp"),+ },+ "node": {+ "brew": ("brew install node", "brew reinstall node"),+ "nvm": ("nvm install --lts", "reinstall node via nvm: nvm install --lts && nvm use --lts"),+ },+ "ffmpeg": {+ "brew": ("brew install ffmpeg", "brew reinstall ffmpeg"),+ "apt": ("sudo apt-get install -y ffmpeg", "sudo apt-get install -y --reinstall ffmpeg"),+ },+}++# Last-resort prescriptions when no known package manager is detected.+_FALLBACK_PRESCRIPTIONS: Dict[str, Tuple[str, str]] = {+ "yt-dlp": (+ "install yt-dlp (https://github.com/yt-dlp/yt-dlp#installation) and ensure it is on PATH",+ "reinstall yt-dlp (https://github.com/yt-dlp/yt-dlp#installation); the current binary won't run",+ ),+ "node": (+ "install Node.js 22+ (https://nodejs.org) and ensure `node` is on PATH",+ "reinstall Node.js 22+ (https://nodejs.org); the current binary won't run",+ ),+ "ffmpeg": (+ "install ffmpeg (https://ffmpeg.org/download.html) and ensure it is on PATH",+ "reinstall ffmpeg (https://ffmpeg.org/download.html); the current binary won't run",+ ),+}+++@dataclass+class DependencyProbe:+ """Uniform probe result for one external dependency.++ ``status`` is one of the module-level constants (OK/MISSING/BROKEN/TIMEOUT).+ ``detail`` says what was observed (version string, exec error, off-PATH+ location). ``prescription`` is the copy-pasteable fix, empty when OK.+ ``owner_pkg_manager`` names the manager the prescription targets+ ("brew", "pipx", "apt", "nvm", "npx"), or "" for PATH fixes / fallbacks.+ """++ name: str+ status: str+ detail: str = ""+ prescription: str = ""+ owner_pkg_manager: str = ""+ # True for the on-disk-but-off-PATH case: MISSING (the engine gate would+ # not pass) but the fix is a PATH edit, not an install.+ off_path: bool = False++ @property+ def ok(self) -> bool:+ return self.status == OK+++# Safe under the GIL (dict get/set are atomic) and each dependency name is+# probed from a single builder today; worst case is one redundant probe.+_dependency_probe_cache: Dict[str, DependencyProbe] = {}+++def clear_dependency_probe_cache() -> None:+ """Reset memoized probes (tests, or a doctor re-run after a fix)."""+ _dependency_probe_cache.clear()+++def _nvm_present() -> bool:+ return bool(os.environ.get("NVM_DIR")) or (Path.home() / ".nvm").is_dir()+++def _manager_available(manager: str) -> bool:+ if manager == "nvm":+ return _nvm_present()+ if manager == "apt":+ return shutil.which("apt-get") is not None+ return shutil.which(manager) is not None+++def _is_pp_cli(name: str) -> bool:+ return name.endswith(_PP_CLI_SUFFIX) and len(name) > len(_PP_CLI_SUFFIX)+++def _pp_install_cmd(name: str) -> str:+ slug = name[: -len(_PP_CLI_SUFFIX)]+ return f"npx -y {_PRINTING_PRESS_NPM} install {slug} --cli-only"+++def pp_install_cmd(slug: str) -> str:+ """Public catalog-install command for the Printing Press CLI ``<slug>-pp-cli``."""+ return _pp_install_cmd(f"{slug}{_PP_CLI_SUFFIX}")+++def static_prescription(name: str, manager: str) -> Tuple[str, str]:+ """Public ``(install, reinstall)`` strings for one dependency/manager pair.++ Reads the static table without probing manager availability; raises+ KeyError for unknown pairs so consumers fail loudly at import time.+ """+ return _MANAGER_PRESCRIPTIONS[name][manager]+++def _prescription(name: str, kind: str) -> Tuple[str, str]:+ """Return ``(prescription, owner_pkg_manager)`` for install/reinstall.++ ``kind`` is "install" (MISSING) or "reinstall" (BROKEN). Printing Press+ CLIs always re-run the catalog installer; other deps pick the first+ detected manager from their preference table, falling back to a generic+ but still actionable instruction.+ """+ idx = 0 if kind == "install" else 1+ if _is_pp_cli(name):+ cmd = _pp_install_cmd(name)+ if kind == "reinstall":+ return f"re-run the Printing Press install: {cmd}", "npx"+ return cmd, "npx"+ for manager, prescriptions in _MANAGER_PRESCRIPTIONS.get(name, {}).items():+ if _manager_available(manager):+ return prescriptions[idx], manager+ fallback = _FALLBACK_PRESCRIPTIONS.get(name)+ if fallback:+ return fallback[idx], ""+ verb = "install" if kind == "install" else "reinstall"+ return f"{verb} {name} and ensure it is on PATH", ""+++def windows_printing_press_bin_dir() -> Optional[Path]:+ """Windows managed install dir for Printing Press CLIs, when applicable.++ Returns ``%LOCALAPPDATA%/Programs/PrintingPress/bin`` on Windows when+ LOCALAPPDATA is set; ``None`` otherwise.+ """+ if os.name != "nt":+ return None+ local_app = os.environ.get("LOCALAPPDATA") or os.environ.get("LocalAppData")+ if not local_app:+ return None+ return Path(local_app) / "Programs" / "PrintingPress" / "bin"+++def installer_bin_dirs() -> List[Path]:+ """Installer-managed bin dirs shared with setup_wizard's Digg candidates.++ Single source of truth for where installers drop binaries: the Printing+ Press library default (~/.local/bin), Go bins, and — on Windows — the+ managed %LOCALAPPDATA%/Programs/PrintingPress/bin dir.+ ``setup_wizard._digg_bin_candidate_paths`` derives its Digg-specific+ paths from this list; keep the two in lockstep by editing only here.+ """+ home = Path.home()+ dirs = [home / ".local" / "bin"]+ gopath = os.environ.get("GOPATH")+ if gopath:+ dirs.append(Path(gopath) / "bin")+ dirs.append(home / "go" / "bin")+ win_dir = windows_printing_press_bin_dir()+ if win_dir is not None:+ dirs.append(win_dir)+ return dirs+++def _off_path_candidate_dirs() -> List[Path]:+ """Directories where installers drop binaries that PATH may not cover.++ The shared installer dirs (``installer_bin_dirs``, which also backs+ setup_wizard's Digg candidates) plus the Homebrew prefixes (an agent+ subprocess PATH sometimes omits even those).+ """+ dirs = installer_bin_dirs()+ dirs.extend([Path("/opt/homebrew/bin"), Path("/usr/local/bin")])+ return dirs+++def _off_path_binary(name: str) -> Optional[Path]:+ """Return an executable for ``name`` in a known dir that PATH misses."""+ names = [name, f"{name}.exe"] if os.name == "nt" else [name]+ for directory in _off_path_candidate_dirs():+ for candidate_name in names:+ candidate = directory / candidate_name+ if candidate.is_file() and os.access(candidate, os.X_OK):+ return candidate+ return None+++def _path_hint(directory: Path) -> str:+ """Render a bin dir with $HOME substituted for copy-pasteable PATH edits."""+ raw = str(directory)+ if os.name == "nt":+ return raw+ home = str(Path.home())+ if raw == home:+ return "$HOME"+ if raw.startswith(home + os.sep):+ return "$HOME/" + raw[len(home) + 1:].replace(os.sep, "/")+ return raw+++def probe_dependency(name: str, timeout: float = PROBE_TIMEOUT) -> DependencyProbe:+ """Probe one external dependency: OK | MISSING | BROKEN | TIMEOUT.++ - MISSING: not resolvable on this process's PATH. If the binary exists in+ a known install dir, the prescription is a PATH edit, not an install —+ installing again would not fix anything.+ - BROKEN: shutil.which resolves it but a cheap version exec fails+ (OSError/exec-format, or any non-zero exit). Prescription says+ *reinstall* — the #692 stale-shim class must never read as available.+ - TIMEOUT: the version exec exceeded the per-probe budget.+ - OK: version exec exited 0; ``detail`` carries the version line.++ Memoized per process; ``clear_dependency_probe_cache()`` resets.+ """+ cached = _dependency_probe_cache.get(name)+ if cached is not None:+ return cached+ probe = _probe_dependency_uncached(name, timeout)+ _dependency_probe_cache[name] = probe+ return probe+++def _probe_dependency_uncached(name: str, timeout: float) -> DependencyProbe:+ resolved = shutil.which(name)+ if resolved is None:+ off_path = _off_path_binary(name)+ if off_path is not None:+ hint = _path_hint(off_path.parent)+ return DependencyProbe(+ name=name,+ status=MISSING,+ detail=f"{name} is installed at {off_path} but that directory is not on this process's PATH",+ prescription=f'add {hint} to PATH (e.g. export PATH="{hint}:$PATH") so {name} resolves',+ owner_pkg_manager="",+ off_path=True,+ )+ prescription, manager = _prescription(name, "install")+ return DependencyProbe(+ name=name,+ status=MISSING,+ detail=f"{name} not found on PATH",+ prescription=prescription,+ owner_pkg_manager=manager,+ )++ command = [name] + _VERSION_ARGS.get(name, ["--version"])+ try:+ proc = subprocess.run(+ command,+ capture_output=True,+ text=True,+ timeout=timeout,+ )+ except (FileNotFoundError, OSError) as exc:+ prescription, manager = _prescription(name, "reinstall")+ return DependencyProbe(+ name=name,+ status=BROKEN,+ detail=f"{name} resolves to {resolved} but won't execute: {exc}",+ prescription=prescription,+ owner_pkg_manager=manager,+ )+ except subprocess.TimeoutExpired:+ prescription, manager = _prescription(name, "reinstall")+ return DependencyProbe(+ name=name,+ status=TIMEOUT,+ detail=f"{name} version probe timed out after {timeout:g}s",+ prescription=f"re-run doctor; if the timeout persists: {prescription}",+ owner_pkg_manager=manager,+ )++ if proc.returncode == 0:+ lines = (proc.stdout or proc.stderr or "").strip().splitlines()+ version = lines[0].strip() if lines else ""+ return DependencyProbe(name=name, status=OK, detail=version)++ lines = (proc.stderr or proc.stdout or "").strip().splitlines()+ why = lines[0].strip() if lines else f"exit {proc.returncode}"+ prescription, manager = _prescription(name, "reinstall")+ return DependencyProbe(+ name=name,+ status=BROKEN,+ detail=f"{name} resolves to {resolved} but the version probe failed: {why}",+ prescription=prescription,+ owner_pkg_manager=manager,+ )+++def probe_dependencies(names: Optional[Iterable[str]] = None) -> Dict[str, DependencyProbe]:+ """Probe every known dependency (or ``names``), memoized per process."""+ return {name: probe_dependency(name) for name in (names or KNOWN_DEPENDENCIES)}diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.pyindex 0d0862e8..22af97c6 100644--- a/skills/last30days/scripts/lib/pipeline.py+++ b/skills/last30days/scripts/lib/pipeline.py@@ -130,13 +130,21 @@ def available_sources(requested_sources: list[str] | None = None,*,x_pending: bool | None = None,+ local_only: bool = False,) -> list[str]:+ """List the sources the next run can serve.++ ``local_only=True`` is the safe/diagnose flavor (doctor's permission+ block): availability is answered from local evidence only, so the X+ check never spawns xurl's live ``whoami`` network call. Research-time+ callers keep the default live semantics.+ """available: list[str] = []# reddit_public needs no API key - always availableavailable.append("reddit")if config.get("SCRAPECREATORS_API_KEY"):available.extend(["tiktok", "instagram"])- if env.get_x_source(config):+ if env.get_x_source(config, local_only=local_only):available.append("x")else:# Safe inspection (--diagnose/--preflight) skips browser-cookie@@ -239,7 +247,8 @@ def diagnose(google_key = _google_key(config)x_status = env.get_x_source_status(config, probe=not safe)# Compute once and reuse for both the diag flag and available_sources below.- x_pending = env.x_pending_browser_auth(config)+ # safe=True (doctor/--diagnose/--preflight) must stay network-free.+ x_pending = env.x_pending_browser_auth(config, local_only=safe)native_web_backend = Noneif config.get("BRAVE_API_KEY"):native_web_backend = "brave"@@ -298,7 +307,12 @@ def diagnose("native_search": env.is_native_search(config),"has_scrapecreators": bool(config.get("SCRAPECREATORS_API_KEY")),"has_github": bool(config.get("GITHUB_TOKEN") or which("gh")),- "available_sources": available_sources(config, requested_sources, x_pending=x_pending),+ # safe=True (doctor/--diagnose/--preflight) must stay network-free:+ # answer X availability from local evidence only. x_pending is+ # precomputed by diagnose() to avoid double evaluation.+ "available_sources": available_sources(+ config, requested_sources, x_pending=x_pending, local_only=safe+ ),"safe": safe,"config_source": config.get("_CONFIG_SOURCE"),"ignored_project_config": config.get("_IGNORED_PROJECT_CONFIG"),@@ -1317,11 +1331,11 @@ def _retrieve_stream(has_sc_key = bool(config.get("SCRAPECREATORS_API_KEY"))sc_first = (has_sc_key- and (config.get("LAST30DAYS_REDDIT_BACKEND") or "").lower()+ and (config.get(env.REDDIT_BACKEND_PIN_VAR) or "").lower()== "scrapecreators")if sc_first:- # LAST30DAYS_REDDIT_BACKEND=scrapecreators: SC primary, public fallback+ # env.REDDIT_BACKEND_PIN_VAR=scrapecreators: SC primary, public fallbacktry:result = reddit.search_and_enrich(reddit_query, from_date, to_date, depth=depth,@@ -1360,10 +1374,10 @@ def _retrieve_stream(# Default: public Reddit first (free). ScrapeCreators backfills when the# free path is empty OR returns fewer than the configured thinness floor- # (LAST30DAYS_REDDIT_SC_MIN_ITEMS, default 0 = empty-only — today's+ # (env.REDDIT_SC_MIN_ITEMS_VAR, default 0 = empty-only — today's# behavior, no extra credit spend unless the user opts in).try:- min_items = int(config.get("LAST30DAYS_REDDIT_SC_MIN_ITEMS") or 0)+ min_items = int(config.get(env.REDDIT_SC_MIN_ITEMS_VAR) or 0)except (TypeError, ValueError):min_items = 0public_results: list[dict] = []diff --git a/skills/last30days/scripts/lib/prescriptions.py b/skills/last30days/scripts/lib/prescriptions.pynew file mode 100644index 00000000..2e931e9b--- /dev/null+++ b/skills/last30days/scripts/lib/prescriptions.py@@ -0,0 +1,294 @@+"""Fix-prescription registry: the single remediation vocabulary (KTD 7).++Each (source, failure mode) entry carries a cause line, a natural-language+fix, an exact CLI fix, and an optional CONFIGURATION.md anchor. Two real+consumers keep the vocabulary honest from day one:++- ``lib/quality_nudge.py`` builds its post-research fix text from these+ entries (only the fix strings migrated here; trigger logic is untouched).+- The doctor aggregator (U4) looks entries up per failed source/backend.++Because both surfaces read the same entry, the nudge a user sees after a+degraded run and the prescription doctor prints for the same failure can+never drift apart.++Composition with the other health layers (reference, don't restate):++- U1 (``lib/health.py``) owns the machine-aware package-manager strings+ (brew/pipx/apt/npx install-vs-reinstall, off-PATH PATH edits). Binary-class+ entries here pull their static defaults from U1's tables, and+ ``for_dependency_probe`` lets a live probe's machine-specific prescription+ win the CLI form while the registry supplies cause/NL/anchor vocabulary.+- U2 (``lib/backends.py``) embeds this registry's CLI forms inside its+ chain-failure prescriptions, so a backend finding and a registry lookup+ agree on the command to run.++No secrets: CLI forms use obvious ``<placeholder>`` values only.+"""++from __future__ import annotations++from dataclasses import dataclass, replace+from typing import Dict, Optional, Tuple++from . import health++# Direct engine invocation prefix (scripting fallback; the slash-command UX+# is "ask the agent to run setup ...", which is the natural-language form).+ENGINE_CLI = "python3 skills/last30days/scripts/last30days.py"+SETUP_BROWSER_COOKIES_CLI = f"{ENGINE_CLI} setup --allow-browser-cookies"+SETUP_GITHUB_CLI = f"{ENGINE_CLI} setup --github"++# U1 owns these remediation strings; reference them instead of restating.+_YTDLP_BREW_INSTALL, _YTDLP_BREW_REINSTALL = health.static_prescription("yt-dlp", "brew")+_YTDLP_PIPX_REINSTALL = health.static_prescription("yt-dlp", "pipx")[1]+_DIGG_PP_INSTALL_CLI = health.pp_install_cmd("digg")++GENERIC_FIX_NL = "see CONFIGURATION.md for setup options for this source"+++@dataclass(frozen=True)+class Prescription:+ """Remediation for one (source, failure mode).++ ``fix_nl`` is the natural-language form ("ask the agent to run setup+ with browser-cookie consent"); ``fix_cli`` is the exact command.+ ``alt_cli`` carries per-platform alternates (Windows/pip) when the+ primary CLI form is macOS/brew. ``anchor`` is a CONFIGURATION.md+ heading anchor ("" when the doc has no dedicated section).+ """++ source: str+ failure: str+ cause: str+ fix_nl: str+ fix_cli: str+ alt_cli: Tuple[str, ...] = ()+ anchor: str = ""+++def _entry(source: str, failure: str, **kwargs) -> Tuple[Tuple[str, str], Prescription]:+ return (source, failure), Prescription(source=source, failure=failure, **kwargs)+++REGISTRY: Dict[Tuple[str, str], Prescription] = dict((+ _entry(+ "x", "cookies_missing",+ cause="X browser cookies (AUTH_TOKEN/CT0) are not configured",+ fix_nl=(+ "log into x.com in your browser and re-run (cookies detected "+ "automatically), or add XAI_API_KEY to your .env (get key at "+ "api.x.ai), or add XQUIK_API_KEY to your .env (get key at xquik.com)"+ ),+ fix_cli=SETUP_BROWSER_COOKIES_CLI,+ anchor="api-keys-env",+ ),+ _entry(+ "x", "cookies_expired",+ cause="X errored this run: cookies are configured but likely expired or revoked",+ fix_nl="log into x.com in your browser, then re-run",+ fix_cli=SETUP_BROWSER_COOKIES_CLI,+ anchor="api-keys-env",+ ),+ _entry(+ "scrapecreators", "key_missing",+ cause="SCRAPECREATORS_API_KEY is not set",+ fix_nl=(+ "ask the agent to run setup with the GitHub device flow "+ "(free 10,000-call signup; the key is persisted automatically)"+ ),+ fix_cli=SETUP_GITHUB_CLI,+ anchor="api-keys-env",+ ),+ _entry(+ "bluesky", "app_password_missing",+ cause="BSKY_HANDLE and/or BSKY_APP_PASSWORD are not set",+ fix_nl=(+ "generate an app password at bsky.app/settings/app-passwords and "+ "add BSKY_HANDLE plus BSKY_APP_PASSWORD to ~/.config/last30days/.env"+ ),+ fix_cli="BSKY_HANDLE=<your-handle> BSKY_APP_PASSWORD=<xxxx-xxxx-xxxx-xxxx>",+ anchor="bluesky-app-password-format-and-search-host",+ ),+ _entry(+ "youtube", "transcription_key_missing",+ cause=(+ "no transcription provider key for the caption-free transcript "+ "backstop (GROQ_API_KEY or OPENAI_API_KEY)"+ ),+ fix_nl=(+ "add a free Groq key from console.groq.com to "+ "~/.config/last30days/.env so caption-free videos still get "+ "transcripts (OPENAI_API_KEY also works as the paid backstop)"+ ),+ fix_cli="GROQ_API_KEY=<your-groq-key>",+ anchor="api-keys-env",+ ),+ _entry(+ "digg", "pp_cli_missing",+ cause="digg-pp-cli is not installed",+ fix_nl=(+ "install the Digg CLI through the Printing Press library, then "+ "re-run setup so the source activates"+ ),+ fix_cli=_DIGG_PP_INSTALL_CLI,+ anchor="first-run-onboarding",+ ),+ _entry(+ "digg", "pp_cli_broken",+ cause=(+ "digg-pp-cli resolves on PATH but won't execute (broken or "+ "hanging binary left behind by a bad install)"+ ),+ fix_nl=(+ "reinstall the Digg CLI (re-run the Printing Press install) so "+ "the binary actually executes; it is installed but not serving"+ ),+ fix_cli=_DIGG_PP_INSTALL_CLI,+ anchor="first-run-onboarding",+ ),+ _entry(+ "digg", "pp_cli_off_path",+ cause=(+ "digg-pp-cli is installed but its directory is not on the "+ "agent-subprocess PATH"+ ),+ fix_nl=(+ "add the install directory (default ~/.local/bin) to the PATH the "+ "agent subprocess uses; the engine gate only activates the source "+ "when the binary resolves on PATH"+ ),+ fix_cli='export PATH="$HOME/.local/bin:$PATH"',+ anchor="first-run-onboarding",+ ),+ _entry(+ "youtube", "ytdlp_missing",+ cause="yt-dlp is not installed on the agent-subprocess PATH",+ fix_nl="install yt-dlp to enable the free local YouTube lane",+ fix_cli=_YTDLP_BREW_INSTALL,+ alt_cli=("scoop install yt-dlp", "pip install -U yt-dlp"),+ ),+ _entry(+ "youtube", "ytdlp_stale",+ cause=(+ "yt-dlp is installed but stale: YouTube's caption format changes "+ "frequently and old binaries silently fail every transcript"+ ),+ fix_nl="update yt-dlp via your package manager",+ fix_cli="brew upgrade yt-dlp",+ alt_cli=("scoop update yt-dlp", "pip install -U yt-dlp"),+ ),+ _entry(+ "youtube", "ytdlp_broken",+ cause=(+ "yt-dlp resolves on PATH but won't execute (the stale-shim class: "+ "a wrapper left behind by an interpreter upgrade)"+ ),+ fix_nl=(+ "reinstall yt-dlp so the binary actually executes; a plain "+ "install reads as a no-op because the broken shim is still present"+ ),+ fix_cli=_YTDLP_BREW_REINSTALL,+ alt_cli=(_YTDLP_PIPX_REINSTALL,),+ ),+ _entry(+ "truthsocial", "token_missing",+ cause="TRUTHSOCIAL_TOKEN is not set",+ fix_nl=(+ "log into truthsocial.com in your browser and let setup read the "+ "session cookie, or copy the bearer token from your browser's dev "+ "tools into ~/.config/last30days/.env"+ ),+ fix_cli=SETUP_BROWSER_COOKIES_CLI,+ anchor="api-keys-env",+ ),+ _entry(+ "xiaohongshu", "service_unreachable",+ cause=(+ "xiaohongshu-mcp service is unreachable at XIAOHONGSHU_API_BASE "+ "(default http://host.docker.internal:18060)"+ ),+ fix_nl=(+ "start the xpzouying/xiaohongshu-mcp service and log in from its "+ "web UI, then point XIAOHONGSHU_API_BASE at the running instance "+ "if it is not on the default host/port"+ ),+ fix_cli="XIAOHONGSHU_API_BASE=http://localhost:18060",+ anchor="api-keys-env",+ ),+))+++def lookup(source: str, failure: str) -> Optional[Prescription]:+ """Return the registered entry for (source, failure), or None."""+ return REGISTRY.get((source, failure))+++def get(source: str, failure: str) -> Prescription:+ """Return the registered entry, or the generic CONFIGURATION.md fallback.++ Never raises: an unregistered failure mode still yields an actionable+ (if generic) prescription, so a report renderer cannot crash on a+ failure class the registry has not learned yet.+ """+ entry = lookup(source, failure)+ if entry is not None:+ return entry+ return Prescription(+ source=source,+ failure=failure,+ cause=f"{source}: {failure.replace('_', ' ')}",+ fix_nl=GENERIC_FIX_NL,+ fix_cli=f"{ENGINE_CLI} setup",+ )+++# ---------------------------------------------------------------------------+# Composition with U1 dependency probes+# ---------------------------------------------------------------------------++def _dependency_failure(probe: health.DependencyProbe) -> Optional[Tuple[str, str]]:+ """Map a failed dependency probe onto a registered (source, failure)."""+ if probe.name == "yt-dlp":+ if probe.status == health.MISSING:+ return ("youtube", "ytdlp_missing")+ return ("youtube", "ytdlp_broken") # BROKEN and TIMEOUT: reinstall class+ if probe.name == "digg-pp-cli":+ # health reports off-PATH binaries as MISSING with ``off_path=True``;+ # the distinction only picks cause/NL wording — the probe's own+ # prescription wins the CLI form either way.+ if probe.status == health.MISSING:+ if probe.off_path:+ return ("digg", "pp_cli_off_path")+ return ("digg", "pp_cli_missing")+ return ("digg", "pp_cli_broken") # BROKEN and TIMEOUT: reinstall class+ return None+++def for_dependency_probe(probe: health.DependencyProbe) -> Optional[Prescription]:+ """Prescription for a failed U1 dependency probe (None when OK).++ U1's machine-aware prescription (the manager that owns the binary on+ THIS machine, or a PATH edit for off-PATH installs) wins the CLI form;+ the registry entry supplies the shared cause/NL/anchor vocabulary.+ Unregistered dependencies wrap the probe so callers still get both+ fix forms without this module restating U1's strings.+ """+ if probe.ok:+ return None+ key = _dependency_failure(probe)+ entry = REGISTRY.get(key) if key else None+ if entry is None:+ return Prescription(+ source=probe.name,+ failure=probe.status,+ cause=probe.detail or f"{probe.name}: {probe.status}",+ fix_nl=f"repair the {probe.name} install; {GENERIC_FIX_NL}",+ fix_cli=probe.prescription or f"{ENGINE_CLI} setup",+ )+ updates = {}+ if probe.detail:+ updates["cause"] = probe.detail+ if probe.prescription and probe.prescription != entry.fix_cli:+ updates["fix_cli"] = probe.prescription+ return replace(entry, **updates) if updates else entrydiff --git a/skills/last30days/scripts/lib/providers.py b/skills/last30days/scripts/lib/providers.pyindex 536bd353..fe018b87 100644--- a/skills/last30days/scripts/lib/providers.py+++ b/skills/last30days/scripts/lib/providers.py@@ -315,7 +315,7 @@ def resolve_runtime(config: dict[str, Any], depth: str) -> tuple[schema.Providerdef _resolve_x_backend(config: dict[str, Any]) -> str | None:- preferred = (config.get("LAST30DAYS_X_BACKEND") or "").lower()+ preferred = (config.get(env.X_BACKEND_PIN_VAR) or "").lower()if preferred in {"xai", "bird"}:return preferredreturn env.get_x_source(config)diff --git a/skills/last30days/scripts/lib/quality_nudge.py b/skills/last30days/scripts/lib/quality_nudge.pyindex 8559d913..31081509 100644--- a/skills/last30days/scripts/lib/quality_nudge.py+++ b/skills/last30days/scripts/lib/quality_nudge.py@@ -2,10 +2,16 @@Computes a quality score based on 5 core sources and buildsa nudge message describing what the user missed and how to fix it.++Fix text comes from ``lib.prescriptions`` (the single remediation+vocabulary shared with the doctor command, KTD 7); only the trigger+logic and the message framing live here."""from typing import List+from . import prescriptions+# The 5 core sourcesCORE_SOURCES = ["hn", "polymarket", "x", "youtube", "reddit"]@@ -291,27 +297,26 @@ def _build_nudge_text(if "x" in core_missing:if "x" in core_errored:- free_suggestions.append(- "X/Twitter errored - log into x.com in your browser, then re-run."- )+ x_fix = prescriptions.get("x", "cookies_expired")+ free_suggestions.append(f"X/Twitter errored - {x_fix.fix_nl}.")else:+ x_fix = prescriptions.get("x", "cookies_missing")free_suggestions.append("X/Twitter: real-time posts with likes and reposts - the fastest "- "signal for breaking topics. Three options: log into x.com in your "- "browser and re-run (cookies detected automatically), or add "- "XAI_API_KEY to your .env (get key at api.x.ai), or add "- "XQUIK_API_KEY to your .env (get key at xquik.com)."+ f"signal for breaking topics. Three options: {x_fix.fix_nl}.")if "youtube" in core_missing:if "youtube" in core_errored:+ yt_fix = prescriptions.get("youtube", "ytdlp_stale")free_suggestions.append(- "YouTube errored - update yt-dlp: brew upgrade yt-dlp"+ f"YouTube errored - update yt-dlp: {yt_fix.fix_cli}")else:+ yt_fix = prescriptions.get("youtube", "ytdlp_missing")free_suggestions.append("YouTube: video transcripts with key moments - often the deepest "- "explanations on any topic. Install yt-dlp: brew install yt-dlp (free)"+ f"explanations on any topic. Install yt-dlp: {yt_fix.fix_cli} (free)")if "youtube" in core_degraded:@@ -319,12 +324,18 @@ def _build_nudge_text(transcripts = int(research_results.get("youtube_transcripts_count") or 0)captions_disabled = int(research_results.get("youtube_captions_disabled_count") or 0)if not has_ytdlp and _youtube_returned_data(research_results):+ install = prescriptions.get("youtube", "ytdlp_missing")+ # Tolerant lookup: alt_cli makes no arity promise, so an entry+ # gaining/losing a platform alternate must degrade the wording,+ # never crash the nudge path.+ scoop_install = install.alt_cli[0] if len(install.alt_cli) > 0 else install.fix_cli+ pip_install = install.alt_cli[1] if len(install.alt_cli) > 1 else scoop_installfree_suggestions.append(f"YouTube returned {videos} videos and {transcripts} transcripts ""through a fallback/provider path, but local yt-dlp is not ""installed. Install yt-dlp to enable the free local YouTube lane "- "and reduce reliance on fallback providers: brew install yt-dlp "- "(macOS), scoop install yt-dlp (Windows), or pip install -U yt-dlp."+ f"and reduce reliance on fallback providers: {install.fix_cli} "+ f"(macOS), {scoop_install} (Windows), or {pip_install}.")else:captions_note = ""@@ -333,13 +344,17 @@ def _build_nudge_text(f" ({captions_disabled} of those had captions disabled by the ""uploader, which is a separate cause and not fixable on your end)")+ update = prescriptions.get("youtube", "ytdlp_stale")+ # Same tolerant lookup as the install branch above.+ scoop_update = update.alt_cli[0] if len(update.alt_cli) > 0 else update.fix_cli+ pip_update = update.alt_cli[1] if len(update.alt_cli) > 1 else scoop_updatefree_suggestions.append(f"YouTube returned {videos} videos but only {transcripts} transcripts "f"captured{captions_note}. The most common remaining cause is a stale ""yt-dlp binary - YouTube's caption format changes frequently and old ""binaries silently fail every transcript. Update via your package "- "manager: scoop update yt-dlp (Windows), brew upgrade yt-dlp (macOS), "- "or pip install -U yt-dlp."+ f"manager: {scoop_update} (Windows), {update.fix_cli} (macOS), "+ f"or {pip_update}.")if "instagram" in bonus_errored:diff --git a/skills/last30days/scripts/lib/setup_wizard.py b/skills/last30days/scripts/lib/setup_wizard.pyindex 9d7b7fe4..9d764c9d 100644--- a/skills/last30days/scripts/lib/setup_wizard.py+++ b/skills/last30days/scripts/lib/setup_wizard.py@@ -178,22 +178,22 @@ def _digg_bin_candidate_paths() -> list[Path]:"""Known install locations for digg-pp-cli (Printing Press library defaults).Order: current installer default (~/.local/bin), legacy Go bins, Windows- managed dir. ``pipeline.available_sources()`` only activates Digg when+ managed dir. The directory list is ``health.installer_bin_dirs()`` — the+ shared single source — with the Digg filename variants appended (plain+ name for Unix-style dirs, ``.exe`` in the Windows managed dir).+ ``pipeline.available_sources()`` only activates Digg when``shutil.which`` resolves on PATH — probing these dirs is for setupverification and honest off-PATH messaging, not engine activation."""- home = Path.home()- candidates: list[Path] = [home / ".local" / "bin" / DIGG_CLI_BIN]- gopath = os.environ.get("GOPATH")- if gopath:- candidates.append(Path(gopath) / "bin" / DIGG_CLI_BIN)- candidates.append(home / "go" / "bin" / DIGG_CLI_BIN)- if os.name == "nt":- local_app = os.environ.get("LOCALAPPDATA") or os.environ.get("LocalAppData")- if local_app:- candidates.append(- Path(local_app) / "Programs" / "PrintingPress" / "bin" / f"{DIGG_CLI_BIN}.exe"- )+ from . import health++ win_dir = health.windows_printing_press_bin_dir()+ candidates: list[Path] = []+ for directory in health.installer_bin_dirs():+ if win_dir is not None and directory == win_dir:+ candidates.append(directory / f"{DIGG_CLI_BIN}.exe")+ else:+ candidates.append(directory / DIGG_CLI_BIN)return candidatesdiff --git a/skills/last30days/scripts/lib/xurl_x.py b/skills/last30days/scripts/lib/xurl_x.pyindex e5f1f283..df30ee32 100644--- a/skills/last30days/scripts/lib/xurl_x.py+++ b/skills/last30days/scripts/lib/xurl_x.py@@ -12,8 +12,10 @@ Priority: xAI API > Bird/GraphQL > xurl > web-only fallbackimport jsonimport re+import shutilimport subprocess-from typing import Any, Dict, List, Optional+from pathlib import Path+from typing import Any, Dict, List, Optional, Tuplefrom . import logfrom .relevance import token_overlap_relevance as _compute_relevance@@ -31,12 +33,35 @@ DEPTH_CONFIG = {}+# Memoized availability, mirroring health.py's per-process dependency-probe+# cache: each uncached is_available() check spawns an `xurl whoami`+# subprocess (a live, authenticated X API call). The doctor/safe-diagnose+# path never uses it — see stored_auth_status()/has_stored_auth() below —+# but research-time callers may consult it more than once per process.+# None means "not yet probed".+_availability_cache: Optional[bool] = None+++def clear_availability_cache() -> None:+ """Reset the memoized is_available() result (tests, or a re-check after auth)."""+ global _availability_cache+ _availability_cache = None++def is_available() -> bool:"""Check if xurl is installed and has valid authentication.Returns True only if xurl binary is found AND the user is authenticated(i.e. ``xurl whoami`` exits 0 and returns a username field).+ Memoized per process; ``clear_availability_cache()`` resets."""+ global _availability_cache+ if _availability_cache is None:+ _availability_cache = _is_available_uncached()+ return _availability_cache+++def _is_available_uncached() -> bool:try:result = subprocess.run(["xurl", "whoami"],@@ -52,6 +77,74 @@ def is_available() -> bool:return False+# ---------------------------------------------------------------------------+# Local auth evidence (doctor / safe-diagnose path — no subprocess, no+# network).+#+# xurl persists OAuth credentials to an on-disk token store at ~/.xurl+# (YAML in current releases; legacy versions wrote JSON — see the upstream+# store package at github.com/xdevplatform/xurl). A populated store is the+# strongest LOCAL evidence of authentication obtainable without spending a+# network call, so doctor keys on it and reports "auth not live-verified"+# instead of running `xurl whoami` (a real, authenticated X API request+# that would violate doctor's no-network guarantee).+# ---------------------------------------------------------------------------++AUTH_OK = "ok" # token store present with stored credentials+AUTH_MISSING = "missing" # no token store, or no credentials stored in it+AUTH_ERROR = "error" # token store exists but could not be read++# Substrings a populated store carries in both the YAML and legacy JSON+# formats (per-user oauth2 token blocks, or an app-only bearer token).+_TOKEN_STORE_MARKERS = (+ "access_token",+ "bearer_token",+ "oauth2_tokens",+ "oauth1_tokens",+)+++def token_store_path() -> Path:+ """xurl's on-disk OAuth token store (~/.xurl)."""+ return Path.home() / ".xurl"+++def stored_auth_status() -> Tuple[str, str]:+ """Local-only evidence of xurl authentication: ``(status, detail)``.++ Reads only the on-disk token store — never spawns xurl, never touches+ the network. ``status`` is AUTH_OK (store holds credentials),+ AUTH_MISSING (no store / empty store / no credential markers), or+ AUTH_ERROR (store exists but cannot be read — surfaced as a typed+ error, not as "unconfigured").+ """+ path = token_store_path()+ try:+ if not path.is_file():+ return AUTH_MISSING, f"no token store at {path}"+ content = path.read_text(encoding="utf-8", errors="replace")+ except OSError as exc:+ return (+ AUTH_ERROR,+ f"token store {path} unreadable: {type(exc).__name__}: {exc}",+ )+ if any(marker in content for marker in _TOKEN_STORE_MARKERS):+ return AUTH_OK, f"stored OAuth credentials found in {path}"+ return AUTH_MISSING, f"token store {path} has no stored credentials"+++def has_stored_auth() -> bool:+ """Local-only availability: xurl on PATH with stored credentials.++ The doctor/safe-diagnose counterpart of ``is_available()`` — the same+ "installed and authenticated" question answered from local evidence+ only (PATH lookup + token store), never a live ``xurl whoami``. A+ broken token store reads as unavailable here; the doctor probe layer+ (``backends._probe_xurl``) reports that case as a typed error.+ """+ return shutil.which("xurl") is not None and stored_auth_status()[0] == AUTH_OK++def search_x(query: str,depth: str = "default",diff --git a/tests/conftest.py b/tests/conftest.pyindex 9dc63d7d..4493d8c7 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -14,3 +14,17 @@ def _no_arctic_network():exercise the real lookup with http.get mocked."""with mock.patch("lib.reddit_arctic.fetch_scores", return_value={}):yield++[email protected](autouse=True)+def _reset_probe_caches():+ """The doctor stack memoizes probe results in module-level dicts (safe for+ the one-shot CLI process, wrong across tests). Clear them around every test+ so a probe cached by one test can never leak into another."""+ from lib import health, xurl_x++ health.clear_dependency_probe_cache()+ xurl_x.clear_availability_cache()+ yield+ health.clear_dependency_probe_cache()+ xurl_x.clear_availability_cache()diff --git a/tests/test_backend_descriptors.py b/tests/test_backend_descriptors.pynew file mode 100644index 00000000..0ae35323--- /dev/null+++ b/tests/test_backend_descriptors.py@@ -0,0 +1,614 @@+"""U2: backend-chain descriptors with predicted selection (lib/backends.py).++Chained sources declare their routing once — imported from the definitions+lib/env.py already owns — and ``backends.resolve`` produces a truthful+"will use" prediction for alternative chains (X, YouTube, web search) plus+honest conditional wording for Reddit.++Covers the plan's U2 scenarios:+ 1. X with cookies present, bird healthy, no XAI key -> predicted ``bird``.+ 2. Pin var set to a later backend -> pin honored and marked pinned.+ 3. Preferred backend installed-but-unauthenticated does not shadow a+ fully-usable fallback (collect-then-pick).+ 4. No backend usable -> tier error; prescription from the highest-priority+ backend.+ 5. Paid lanes probe key presence ONLY — no network, no subprocess.+ 6. Reddit renders conditional wording (default + backfill), never a+ computed winner; a scrapecreators pin renders as pinned.+ 7. Parity: descriptor prediction == pipeline's pre-failover X selection+ (env.x_backend_chain()[0]) across three config permutations.+"""++from unittest import mock++import pytest++from lib import backends, env, health, xurl_x+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++def _probe_dep(status_map=None, default_status=health.OK):+ """Build a fake health.probe_dependency honoring a per-name status map."""+ status_map = status_map or {}++ def fake(name, timeout=health.PROBE_TIMEOUT):+ status = status_map.get(name, default_status)+ if status == health.OK:+ return health.DependencyProbe(name=name, status=health.OK, detail=f"{name} 1.0.0")+ return health.DependencyProbe(+ name=name,+ status=status,+ detail=f"{name} probe simulated {status}",+ prescription=f"reinstall {name}" if status != health.MISSING else f"install {name}",+ owner_pkg_manager="brew",+ )++ return fake+++def _x_env(+ bird_installed=False,+ xurl_installed=False,+ xurl_authed=False,+ node_status=health.OK,+):+ """Context managers configuring the X-chain probe environment.++ ``xurl_authed`` drives BOTH auth surfaces consistently: the research-time+ network check (``is_available``) and the doctor-path local evidence+ (``stored_auth_status``/``has_stored_auth``) — a real machine where the+ user logged in has both.+ """+ stored = (+ (xurl_x.AUTH_OK, "stored OAuth credentials found in ~/.xurl")+ if xurl_authed+ else (xurl_x.AUTH_MISSING, "no token store at ~/.xurl")+ )+ return (+ mock.patch("lib.bird_x.is_bird_installed", return_value=bird_installed),+ mock.patch("lib.bird_x.set_credentials", lambda *a, **k: None),+ mock.patch("lib.xurl_x.is_available", return_value=xurl_authed),+ mock.patch(+ "lib.backends.which",+ lambda name: "/usr/local/bin/xurl" if (name == "xurl" and xurl_installed) else None,+ ),+ mock.patch("lib.health.probe_dependency", _probe_dep({"node": node_status})),+ mock.patch("lib.xurl_x.stored_auth_status", return_value=stored),+ mock.patch(+ "lib.xurl_x.has_stored_auth",+ return_value=xurl_installed and xurl_authed,+ ),+ )+++def _resolve_x(config, **envkw):+ with _stack(_x_env(**envkw)):+ return backends.resolve("x", config)+++class _stack:+ """Enter/exit a tuple of context managers (contextlib.ExitStack, terse)."""++ def __init__(self, ctxs):+ self._ctxs = ctxs++ def __enter__(self):+ for c in self._ctxs:+ c.__enter__()+ return self++ def __exit__(self, *exc):+ for c in reversed(self._ctxs):+ c.__exit__(*exc)+ return False+++# ---------------------------------------------------------------------------+# Descriptor registry: routing declared once, imported from env.py (KTD 6)+# ---------------------------------------------------------------------------++class TestDescriptorRegistry:+ def test_x_chain_comes_from_env_definitions(self):+ d = backends.get_descriptor("x")+ assert d.mode == backends.MODE_ALTERNATIVE+ assert tuple(s.name for s in d.backends) == env.X_BACKEND_ORDER+ assert env.X_BACKEND_ORDER == ("xai", "bird", "xurl", "xquik")+ assert d.pin_var == env.X_BACKEND_PIN_VAR == "LAST30DAYS_X_BACKEND"++ def test_env_exposes_reddit_pin_constants(self):+ assert env.REDDIT_BACKEND_PIN_VAR == "LAST30DAYS_REDDIT_BACKEND"+ assert env.REDDIT_SC_MIN_ITEMS_VAR == "LAST30DAYS_REDDIT_SC_MIN_ITEMS"++ def test_youtube_and_web_chains_declared_in_order(self):+ yt = backends.get_descriptor("youtube")+ assert tuple(s.name for s in yt.backends) == ("yt-dlp", "scrapecreators")+ web = backends.get_descriptor("web")+ assert tuple(s.name for s in web.backends) == (+ "brave", "exa", "serper", "parallel", "keyless",+ )+ assert web.pin_flag == "--web-backend"++ def test_reddit_is_conditional_and_lanes_are_not_chain_entries(self):+ d = backends.get_descriptor("reddit")+ assert d.mode == backends.MODE_CONDITIONAL+ names = [s.name for s in d.backends]+ # Internal keyless lanes are sub-probe detail, never chain entries.+ for lane in ("rss", "listing", "arctic", "shreddit"):+ assert lane not in names+ assert names == ["public", "scrapecreators"]++ def test_unknown_source_raises(self):+ with pytest.raises(KeyError):+ backends.get_descriptor("nope")+ with pytest.raises(KeyError):+ backends.resolve("nope", {})+++# ---------------------------------------------------------------------------+# Scenario 1: cookies present, bird healthy, no XAI key -> bird predicted+# ---------------------------------------------------------------------------++class TestXPrediction:+ def test_bird_predicted_with_cookies_and_no_xai_key(self):+ config = {"AUTH_TOKEN": "dummy-token", "CT0": "dummy-ct0"}+ res = _resolve_x(config, bird_installed=True)+ assert res.active_backend == "bird"+ assert res.tier == backends.TIER_OK+ assert res.pinned is False+ # Chain rendered in declared order regardless of availability.+ assert res.chain == list(env.X_BACKEND_ORDER)+ assert [f.name for f in res.findings] == list(env.X_BACKEND_ORDER)+ assert "will use: bird" in res.summary++ # Scenario 2: pin var set to a later backend -> honored + marked pinned.+ def test_pin_to_later_backend_honored_and_marked(self):+ config = {+ "AUTH_TOKEN": "dummy-token",+ "CT0": "dummy-ct0",+ "XQUIK_API_KEY": "dummy-key",+ "LAST30DAYS_X_BACKEND": "xquik",+ }+ res = _resolve_x(config, bird_installed=True)+ assert res.active_backend == "xquik"+ assert res.pinned is True+ assert res.pin == "xquik"+ assert res.tier == backends.TIER_OK+ assert "pinned" in res.summary++ # Scenario 3: installed-but-unauthenticated preferred backend must not+ # shadow a fully usable fallback (collect-then-pick).+ def test_unauthenticated_preferred_does_not_shadow_usable_fallback(self):+ config = {"XQUIK_API_KEY": "dummy-key"}+ res = _resolve_x(config, xurl_installed=True, xurl_authed=False)+ assert res.active_backend == "xquik"+ assert res.tier == backends.TIER_OK+ xurl = next(f for f in res.findings if f.name == "xurl")+ assert not xurl.usable+ assert "auth" in (xurl.detail + xurl.prescription).lower()++ # Scenario 4: nothing usable -> error tier, highest-priority prescription.+ def test_no_backend_usable_is_error_with_top_priority_prescription(self):+ res = _resolve_x({})+ assert res.active_backend is None+ assert res.tier == backends.TIER_ERROR+ assert "XAI_API_KEY" in res.prescription++ def test_pinned_but_unusable_backend_is_error_with_its_prescription(self):+ # Pin bird without cookies: env.x_backend_chain returns [] (pipeline+ # raises); resolution mirrors that as an error carrying bird's fix.+ config = {"LAST30DAYS_X_BACKEND": "bird"}+ res = _resolve_x(config, bird_installed=True)+ assert res.active_backend is None+ assert res.pinned is True+ assert res.tier == backends.TIER_ERROR+ assert res.prescription # bird's cookie prescription, not xai's+ assert "XAI_API_KEY" not in res.prescription++ def test_broken_node_shim_makes_bird_unusable_and_falls_back(self):+ # U1 integration: a stale node shim (BROKEN, not missing) must not+ # let bird read as usable — the #692 class applied to chains.+ config = {+ "AUTH_TOKEN": "dummy-token",+ "CT0": "dummy-ct0",+ "XQUIK_API_KEY": "dummy-key",+ }+ res = _resolve_x(config, bird_installed=True, node_status=health.BROKEN)+ assert res.active_backend == "xquik"+ bird = next(f for f in res.findings if f.name == "bird")+ assert bird.status == health.BROKEN+ assert not bird.usable++ def test_unconfigured_x_with_broken_node_is_unconfigured_not_node_error(self):+ # F9: cookie presence is checked BEFORE the node runtime. With no X+ # configuration at all, a broken node must not turn bird into a+ # BROKEN finding carrying a node prescription — the honest state is+ # "unconfigured, here is the cookie fix" (which doctor rolls up to+ # tier off, since every finding is MISSING).+ res = _resolve_x({}, node_status=health.BROKEN)+ bird = next(f for f in res.findings if f.name == "bird")+ assert bird.status == health.MISSING+ assert "AUTH_TOKEN/CT0" in bird.detail+ assert "cookie" in bird.prescription.lower()+ assert "node" not in bird.prescription.lower()+ # Doctor's off/unconfigured rollup keys on all-findings-MISSING.+ assert all(f.status == health.MISSING for f in res.findings)++ def test_cookies_present_broken_node_still_reads_broken(self):+ # The inverse guard: once cookies ARE configured, a broken node is a+ # real configured-but-broken state and must keep the node fix.+ config = {"AUTH_TOKEN": "dummy-token", "CT0": "dummy-ct0"}+ res = _resolve_x(config, bird_installed=True, node_status=health.BROKEN)+ bird = next(f for f in res.findings if f.name == "bird")+ assert bird.status == health.BROKEN+ assert "node" in bird.prescription.lower()+++# ---------------------------------------------------------------------------+# Scenario 5: paid lanes probe key presence only — never network/subprocess+# ---------------------------------------------------------------------------++def _forbid_io():+ def boom(*a, **k):+ raise AssertionError("paid-lane probe attempted I/O")++ return (+ mock.patch("socket.socket", boom),+ mock.patch("socket.create_connection", boom),+ mock.patch("urllib.request.urlopen", boom),+ mock.patch("subprocess.run", boom),+ mock.patch("subprocess.Popen", boom),+ )+++class TestPaidLaneProbes:+ PAID = [+ ("x", "xai", "XAI_API_KEY"),+ ("x", "xquik", "XQUIK_API_KEY"),+ ("web", "serper", "SERPER_API_KEY"),+ ("youtube", "scrapecreators", "SCRAPECREATORS_API_KEY"),+ ("reddit", "scrapecreators", "SCRAPECREATORS_API_KEY"),+ ]++ def test_paid_lanes_are_flagged_paid(self):+ for source, name, _key in self.PAID:+ spec = next(+ s for s in backends.get_descriptor(source).backends if s.name == name+ )+ assert spec.paid is True, f"{source}/{name} must be a paid (key-only) lane"++ def test_key_presence_probe_makes_no_network_or_subprocess_calls(self):+ ctxs = _forbid_io()+ with ctxs[0], ctxs[1], ctxs[2], ctxs[3], ctxs[4]:+ for source, name, key in self.PAID:+ spec = next(+ s for s in backends.get_descriptor(source).backends if s.name == name+ )+ present = spec.probe({key: "dummy-key"})+ assert present.status == health.OK+ absent = spec.probe({})+ assert absent.status == health.MISSING+ assert key in absent.prescription+++# ---------------------------------------------------------------------------+# F1 + F10: the doctor-path xurl probe is LOCAL-ONLY (stored-token evidence,+# never a live `xurl whoami` — doctor's no-network guarantee) and typed.+# ---------------------------------------------------------------------------++class TestXurlLocalProbe:+ def _spec(self):+ return next(+ s for s in backends.get_descriptor("x").backends if s.name == "xurl"+ )++ def _finding(self, stored, installed=True):+ """Run the xurl probe under the forbid-all-I/O harness."""+ ctxs = _forbid_io()+ with ctxs[0], ctxs[1], ctxs[2], ctxs[3], ctxs[4], \+ mock.patch(+ "lib.backends.which",+ lambda n: "/usr/local/bin/xurl" if installed else None,+ ), \+ mock.patch("lib.xurl_x.stored_auth_status", return_value=stored):+ return self._spec().probe({})++ def test_token_store_present_is_ok_without_network(self):+ finding = self._finding(+ (xurl_x.AUTH_OK, "stored OAuth credentials found in ~/.xurl")+ )+ assert finding.status == health.OK+ assert "not live-verified" in finding.detail++ def test_no_token_store_is_missing_with_auth_prescription(self):+ finding = self._finding((xurl_x.AUTH_MISSING, "no token store at ~/.xurl"))+ assert finding.status == health.MISSING+ assert "not authenticated" in finding.detail+ assert "xurl auth oauth2 login" in finding.prescription++ def test_unreadable_token_store_is_error_tier(self):+ # F10: binary resolvable but the token-store read fails -> typed+ # ERROR (doctor's error tier), never "unconfigured".+ finding = self._finding(+ (+ xurl_x.AUTH_ERROR,+ "token store ~/.xurl unreadable: PermissionError: denied",+ )+ )+ assert finding.status == health.ERROR+ assert not finding.usable+ assert "unreadable" in finding.detail++ def test_binary_absent_stays_not_installed(self):+ finding = self._finding((xurl_x.AUTH_OK, "irrelevant"), installed=False)+ assert finding.status == health.MISSING+ assert "not found on PATH" in finding.detail++ def test_whole_doctor_path_x_probe_makes_no_network_or_subprocess(self, tmp_path):+ """The full X chain resolution plus the safe get_x_source_status —+ the exact X probes doctor runs — under the forbid-everything+ harness. The token store is a REAL file so the genuine+ stored_auth_status code path (filesystem only) is exercised."""+ store = tmp_path / ".xurl"+ store.write_text(+ "apps:\n app:\n oauth2_tokens:\n me:\n oauth2:\n"+ " access_token: dummy-not-real\n",+ encoding="utf-8",+ )+ config = {"AUTH_TOKEN": "dummy-token", "CT0": "dummy-ct0"}+ bird_status = {+ "installed": True,+ "authenticated": True,+ "username": "env AUTH_TOKEN",+ "can_install": True,+ }+ ctxs = _forbid_io()+ with ctxs[0], ctxs[1], ctxs[2], ctxs[3], ctxs[4], \+ mock.patch(+ "lib.xurl_x.is_available",+ side_effect=AssertionError(+ "doctor path ran the live `xurl whoami` network check"+ ),+ ), \+ mock.patch("lib.xurl_x.token_store_path", return_value=store), \+ mock.patch("lib.backends.which", lambda n: f"/usr/local/bin/{n}"), \+ mock.patch(+ "lib.xurl_x.shutil.which", lambda n: f"/usr/local/bin/{n}"+ ), \+ mock.patch("lib.health.probe_dependency", _probe_dep()), \+ mock.patch("lib.bird_x.is_bird_installed", return_value=True), \+ mock.patch("lib.bird_x.set_credentials", lambda *a, **k: None), \+ mock.patch("lib.bird_x.get_bird_status", return_value=bird_status):+ res = backends.resolve("x", config)+ status = env.get_x_source_status(config, probe=False)+ xurl_finding = next(f for f in res.findings if f.name == "xurl")+ assert xurl_finding.status == health.OK+ assert "not live-verified" in xurl_finding.detail+ assert status["xurl_available"] is True+++# ---------------------------------------------------------------------------+# Scenario 6: Reddit conditional wording, never a computed winner+# ---------------------------------------------------------------------------++class TestRedditConditional:+ def test_sc_key_present_renders_default_plus_backfill_no_winner(self):+ res = backends.resolve("reddit", {"SCRAPECREATORS_API_KEY": "dummy-key"})+ assert res.mode == backends.MODE_CONDITIONAL+ assert res.active_backend is None # never a single computed winner+ assert "will use" not in res.summary+ low = res.conditional.lower()+ assert "public keyless" in low+ assert "default" in low+ assert "scrapecreators backfill" in low+ assert res.tier == backends.TIER_OK++ def test_thinness_floor_appears_in_wording(self):+ res = backends.resolve(+ "reddit",+ {"SCRAPECREATORS_API_KEY": "dummy-key", "LAST30DAYS_REDDIT_SC_MIN_ITEMS": "5"},+ )+ assert "5" in res.conditional+ assert "floor" in res.conditional.lower()++ def test_default_floor_zero_means_empty_only_wording(self):+ res = backends.resolve("reddit", {"SCRAPECREATORS_API_KEY": "dummy-key"})+ assert "nothing" in res.conditional.lower()++ def test_malformed_floor_treated_as_default(self):+ res = backends.resolve(+ "reddit",+ {"SCRAPECREATORS_API_KEY": "dummy-key", "LAST30DAYS_REDDIT_SC_MIN_ITEMS": "lots"},+ )+ assert "nothing" in res.conditional.lower()++ def test_pinned_scrapecreators_renders_pin(self):+ res = backends.resolve(+ "reddit",+ {+ "SCRAPECREATORS_API_KEY": "dummy-key",+ "LAST30DAYS_REDDIT_BACKEND": "scrapecreators",+ },+ )+ assert res.pinned is True+ assert res.pin == "scrapecreators"+ low = res.conditional.lower()+ assert "pinned" in low+ assert "primary" in low+ assert res.active_backend is None # still conditional, not a winner++ def test_no_key_means_no_backfill_wording(self):+ res = backends.resolve("reddit", {})+ low = res.conditional.lower()+ assert "public keyless" in low+ assert "backfill" not in low or "no scrapecreators" in low+ assert res.tier == backends.TIER_OK # public composite always reachable++ def test_pin_without_key_is_ignored_like_the_pipeline(self):+ # pipeline gates sc_first on has_sc_key; the pin alone changes nothing.+ res = backends.resolve(+ "reddit", {"LAST30DAYS_REDDIT_BACKEND": "scrapecreators"},+ )+ assert res.pinned is False+ assert "primary" not in res.conditional.lower().split("pin ignored")[0]++ def test_keyless_lanes_are_sub_probe_detail(self):+ res = backends.resolve("reddit", {})+ public = next(f for f in res.findings if f.name == "public")+ for lane in ("rss", "listing", "arctic", "shreddit"):+ assert lane in public.detail+++# ---------------------------------------------------------------------------+# Scenario 7: parity with the pipeline's pre-failover X selection+# ---------------------------------------------------------------------------++class TestXParityWithPipeline:+ """Descriptor prediction must equal env.x_backend_chain(config)[0] — the+ exact expression pipeline._retrieve_stream uses as its pre-failover+ primary (lib/pipeline.py, `chain = env.x_backend_chain(config)`)."""++ def _assert_parity(self, config, **envkw):+ with _stack(_x_env(**envkw)):+ chain = env.x_backend_chain(config)+ predicted = backends.resolve("x", config).active_backend+ expected = chain[0] if chain else None+ assert predicted == expected, (+ f"prediction {predicted!r} != pipeline pre-failover {expected!r} "+ f"for config keys {sorted(config)}"+ )++ def test_parity_xai_key_only(self):+ self._assert_parity({"XAI_API_KEY": "dummy-key"})++ def test_parity_cookies_and_bird_installed(self):+ self._assert_parity(+ {"AUTH_TOKEN": "dummy-token", "CT0": "dummy-ct0"},+ bird_installed=True,+ )++ def test_parity_pin_forces_xquik(self):+ self._assert_parity(+ {"XQUIK_API_KEY": "dummy-key", "LAST30DAYS_X_BACKEND": "xquik"},+ )++ def test_parity_nothing_configured(self):+ self._assert_parity({})+++# ---------------------------------------------------------------------------+# YouTube chain: yt-dlp -> ScrapeCreators+# ---------------------------------------------------------------------------++class TestYouTubeChain:+ def test_ytdlp_healthy_wins(self):+ with mock.patch("lib.health.probe_dependency", _probe_dep()):+ res = backends.resolve("youtube", {"SCRAPECREATORS_API_KEY": "dummy-key"})+ assert res.active_backend == "yt-dlp"+ assert res.tier == backends.TIER_OK++ def test_missing_ytdlp_falls_back_to_sc_key(self):+ with mock.patch(+ "lib.health.probe_dependency", _probe_dep({"yt-dlp": health.MISSING}),+ ):+ res = backends.resolve("youtube", {"SCRAPECREATORS_API_KEY": "dummy-key"})+ assert res.active_backend == "scrapecreators"+ assert res.tier == backends.TIER_OK++ def test_neither_available_error_carries_ytdlp_prescription(self):+ with mock.patch(+ "lib.health.probe_dependency", _probe_dep({"yt-dlp": health.MISSING}),+ ):+ res = backends.resolve("youtube", {})+ assert res.active_backend is None+ assert res.tier == backends.TIER_ERROR+ assert "yt-dlp" in res.prescription+++# ---------------------------------------------------------------------------+# Web search chain: brave -> exa -> serper -> parallel -> keyless floor+# ---------------------------------------------------------------------------++class TestWebChain:+ def test_brave_key_predicted_first(self):+ res = backends.resolve(+ "web", {"BRAVE_API_KEY": "dummy-key", "EXA_API_KEY": "dummy-key"},+ )+ assert res.active_backend == "brave"+ assert res.tier == backends.TIER_OK++ def test_keyless_floor_is_degraded_warn(self):+ res = backends.resolve("web", {})+ assert res.active_backend == "keyless"+ assert res.tier == backends.TIER_WARN++ def test_native_search_suppresses_keyless_floor(self):+ res = backends.resolve("web", {"LAST30DAYS_NATIVE_SEARCH": "1"})+ keyless = next(f for f in res.findings if f.name == "keyless")+ assert not keyless.usable+ assert res.active_backend is None++ def test_pin_via_web_backend_flag(self):+ res = backends.resolve(+ "web", {"BRAVE_API_KEY": "dummy-key", "EXA_API_KEY": "dummy-key"}, pin="exa",+ )+ assert res.active_backend == "exa"+ assert res.pinned is True+ assert "pinned" in res.summary++ def test_parity_with_grounding_auto_dispatch(self):+ """resolve('web').active_backend must match the backend grounding's+ auto branch actually dispatches to, per config permutation."""+ from lib import grounding++ def _auto_pick(config):+ picked = {}++ def rec(label):+ def f(query, date_range, key, count=5):+ picked["backend"] = label+ return [], {"label": label}+ return f++ with mock.patch.object(grounding, "brave_search", rec("brave")), \+ mock.patch.object(grounding, "exa_search", rec("exa")), \+ mock.patch.object(grounding, "serper_search", rec("serper")), \+ mock.patch.object(grounding, "parallel_search", rec("parallel")), \+ mock.patch(+ "lib.web_search_keyless.keyless_search",+ lambda q, dr, cfg: (picked.__setitem__("backend", "keyless") or ([], {})),+ ):+ grounding.web_search("q", ("2026-06-04", "2026-07-04"), config, backend="auto")+ return picked.get("backend")++ for config in (+ {"BRAVE_API_KEY": "dummy-key"},+ {"SERPER_API_KEY": "dummy-key"},+ {},+ ):+ assert backends.resolve("web", config).active_backend == _auto_pick(config)+++# ---------------------------------------------------------------------------+# Rendering: prediction reads as will-use, never as past observation+# ---------------------------------------------------------------------------++class TestSummaryWording:+ def test_alternative_summary_is_will_use(self):+ res = backends.resolve("web", {"BRAVE_API_KEY": "dummy-key"})+ assert res.summary.startswith("will use: brave")+ assert "used" not in res.summary.split("will use")[1]++ def test_error_summary_names_no_backend(self):+ with mock.patch(+ "lib.health.probe_dependency", _probe_dep({"yt-dlp": health.MISSING}),+ ):+ res = backends.resolve("youtube", {})+ assert "will use" not in res.summary+ assert "no usable backend" in res.summary.lower()++ def test_conditional_summary_is_the_conditional_wording(self):+ res = backends.resolve("reddit", {"SCRAPECREATORS_API_KEY": "dummy-key"})+ assert res.summary == res.conditionaldiff --git a/tests/test_diagnose_compat.py b/tests/test_diagnose_compat.pynew file mode 100644index 00000000..4731b743--- /dev/null+++ b/tests/test_diagnose_compat.py@@ -0,0 +1,284 @@+"""Characterization tests freezing the legacy --diagnose / --preflight JSON shapes.++U4 of the doctor plan (R2): `--diagnose` and `--preflight` become frozen-shape+aliases once `doctor` lands. These snapshots freeze the CURRENT shapes so the+doctor work can prove it changed neither. Additions to the legacy shapes are+prohibited — new data appears only in `doctor --json` — so the key-set+assertions below use exact equality, not superset checks.++The two real consumers, each with an explicit test:++1. The Go MCP `preflight` tool (mcp/internal/tools/preflight.go) invokes+ `--preflight --preflight-report-on-save-dir <dir> --emit=json` and passes+ engine stdout through VERBATIM (`mcplib.NewToolResultText(res.Stdout)`).+ The engine side of that contract is asserted here: the exact invocation,+ the frozen top-level key set, the nested shapes, the conditional-writes+ entry for the report-on-save dir, and the byte format+ (json.dumps(..., indent=2, sort_keys=True) + newline).++2. SKILL.md reads `--diagnose`'s `available_sources` array (the engine's+ authoritative source list). Asserted: the key exists, is a list of+ source-name strings.++hooks/scripts/check-config.sh is NOT a JSON consumer (it reads env files and+last-run.json, never engine JSON) — deliberately no compat test for it.++NOTE: snapshots re-recorded against the committed v3.10.0 baseline+(origin/main a5b3ca1, post-v3.9.x source wave: arxiv/techmeme/stocktwits/+trustpilot + the x_pending_browser_auth diag flag). The SHAPES here must+otherwise stay frozen; re-record only when a committed baseline legitimately+changes them.+"""++import io+import json+import sys+import unittest+from contextlib import redirect_stderr, redirect_stdout+from unittest import mock++import last30days as cli++# Source names the engine can emit in available_sources today (v3.10.0).+KNOWN_SOURCE_NAMES = {+ "reddit", "x", "youtube", "tiktok", "instagram", "hackernews", "bluesky",+ "truthsocial", "polymarket", "grounding", "xiaohongshu", "github",+ "perplexity", "threads", "pinterest", "digg", "jobs", "linkedin",+ "arxiv", "techmeme", "stocktwits", "trustpilot",+}++# ---------------------------------------------------------------------------+# Frozen shapes (exact key sets — additions to legacy JSON are prohibited).+# ---------------------------------------------------------------------------++DIAGNOSE_TOP_KEYS = {+ "providers",+ "local_mode",+ "reasoning_provider",+ "x_backend",+ "bird_installed",+ "bird_authenticated",+ "bird_username",+ "xquik_available",+ "xquik_working",+ "xquik_status",+ "native_web_backend",+ "native_search",+ "has_scrapecreators",+ "has_github",+ "x_pending_browser_auth",+ "available_sources",+ "safe",+ "config_source",+ "ignored_project_config",+ "ignored_project_config_keys",+ "ignored_endpoint_overrides",+ "browser_cookies",+ "external_commands",+ "credential_destinations",+ "local_writes",+ "permission_preflight",+}++DIAGNOSE_PROVIDERS_KEYS = {"google", "openai", "xai", "openrouter", "perplexity"}+DIAGNOSE_BROWSER_COOKIES_KEYS = {"mode", "browsers", "reads_values"}+DIAGNOSE_EXTERNAL_COMMANDS_KEYS = {"yt-dlp", "digg-pp-cli", "arxiv-pp-cli", "techmeme-pp-cli", "trustpilot-pp-cli", "gh"}+DIAGNOSE_CREDENTIAL_DESTINATIONS_KEYS = {"global_env"}++PREFLIGHT_TOP_KEYS = {+ "status",+ "safe",+ "local_reads",+ "local_writes",+ "conditional_writes",+ "external_commands",+ "credentials",+ "network",+ "action_items",+}+PREFLIGHT_LOCAL_READS_KEYS = {"config_source", "project_config", "browser_cookies"}+PREFLIGHT_PROJECT_CONFIG_KEYS = {"status", "trusted", "ignored_path", "ignored_keys"}+PREFLIGHT_BROWSER_COOKIES_KEYS = {"status", "mode", "browsers", "reads_values"}+PREFLIGHT_CREDENTIALS_KEYS = {+ "google", "openai", "xai", "openrouter", "perplexity", "scrapecreators", "github",+}+PREFLIGHT_NETWORK_KEYS = {+ "available_sources", "native_search", "endpoint_overrides", "ignored_endpoint_overrides",+}+++FAKE_KEYLESS_CONFIG: dict = {}++# Obvious dummies only (repo security hygiene): used to prove key-presence+# booleans stay booleans and no credential value ever reaches legacy JSON.+FAKE_KEYED_CONFIG = {+ "SCRAPECREATORS_API_KEY": "dummy-sc-key-not-real-000",+ "XAI_API_KEY": "dummy-xai-key-not-real-000",+ "BRAVE_API_KEY": "dummy-brave-key-not-real-000",+}+++def _run_cli(argv: list[str], config: dict) -> tuple[int, str]:+ """Run cli.main() in-process with a controlled config; return (rc, stdout)."""+ bird_status = {+ "installed": False,+ "authenticated": False,+ "username": None,+ "can_install": True,+ }+ with mock.patch.object(cli.env, "get_config", return_value=dict(config)), \+ mock.patch("lib.bird_x.get_bird_status", return_value=bird_status), \+ mock.patch("lib.bird_x.is_bird_installed", return_value=False), \+ mock.patch("lib.bird_x.set_credentials", lambda *a, **k: None), \+ mock.patch(+ "lib.xurl_x.is_available",+ side_effect=AssertionError(+ "--diagnose/--preflight are safe paths and must not run the "+ "live `xurl whoami` network check"+ ),+ ), \+ mock.patch("lib.xurl_x.has_stored_auth", return_value=False), \+ mock.patch.object(sys, "argv", ["last30days.py"] + argv):+ stdout = io.StringIO()+ stderr = io.StringIO()+ with redirect_stdout(stdout), redirect_stderr(stderr):+ rc = cli.main()+ return rc, stdout.getvalue()+++class DiagnoseShapeCompat(unittest.TestCase):+ """Freeze the --diagnose JSON shape (snapshot: pre-v3.9.0 baseline)."""++ def _diagnose(self, config: dict) -> dict:+ rc, out = _run_cli(["--diagnose"], config)+ self.assertEqual(0, rc)+ return json.loads(out)++ def test_top_level_key_set_is_frozen(self):+ payload = self._diagnose(FAKE_KEYLESS_CONFIG)+ self.assertEqual(DIAGNOSE_TOP_KEYS, set(payload.keys()))++ def test_top_level_key_set_is_frozen_with_keys_configured(self):+ payload = self._diagnose(FAKE_KEYED_CONFIG)+ self.assertEqual(DIAGNOSE_TOP_KEYS, set(payload.keys()))++ def test_nested_shapes_are_frozen(self):+ payload = self._diagnose(FAKE_KEYLESS_CONFIG)+ self.assertEqual(DIAGNOSE_PROVIDERS_KEYS, set(payload["providers"].keys()))+ self.assertEqual(+ DIAGNOSE_BROWSER_COOKIES_KEYS, set(payload["browser_cookies"].keys())+ )+ self.assertEqual(+ DIAGNOSE_EXTERNAL_COMMANDS_KEYS, set(payload["external_commands"].keys())+ )+ self.assertEqual(+ DIAGNOSE_CREDENTIAL_DESTINATIONS_KEYS,+ set(payload["credential_destinations"].keys()),+ )+ # The embedded permission preflight carries the same frozen shape the+ # --preflight alias emits.+ self.assertEqual(+ PREFLIGHT_TOP_KEYS, set(payload["permission_preflight"].keys())+ )++ def test_key_presence_fields_are_booleans_never_values(self):+ payload = self._diagnose(FAKE_KEYED_CONFIG)+ self.assertIs(True, payload["has_scrapecreators"])+ for value in payload["providers"].values():+ self.assertIsInstance(value, bool)+ raw = json.dumps(payload)+ for secret in FAKE_KEYED_CONFIG.values():+ self.assertNotIn(secret, raw)++ def test_diagnose_runs_safe_mode(self):+ payload = self._diagnose(FAKE_KEYLESS_CONFIG)+ self.assertIs(True, payload["safe"])++ def test_skill_md_consumer_available_sources_array(self):+ """Consumer (b): SKILL.md reads `available_sources` as the engine's+ authoritative list of source names."""+ payload = self._diagnose(FAKE_KEYLESS_CONFIG)+ self.assertIn("available_sources", payload)+ sources = payload["available_sources"]+ self.assertIsInstance(sources, list)+ self.assertTrue(sources, "available_sources must never be empty (reddit/hn are free)")+ for name in sources:+ self.assertIsInstance(name, str)+ self.assertIn(name, KNOWN_SOURCE_NAMES)+ # Free sources are always present even in a keyless environment.+ for free in ("reddit", "hackernews", "polymarket", "github"):+ self.assertIn(free, sources)+++class PreflightShapeCompat(unittest.TestCase):+ """Freeze the --preflight JSON shape (snapshot: pre-v3.9.0 baseline)."""++ MCP_SAVE_DIR = "/tmp/last30days-mcp-save-dir"++ def _preflight_mcp_invocation(self, config: dict) -> tuple[str, dict]:+ # Consumer (a): mcp/internal/tools/preflight.go builds exactly+ # ["--preflight", "--preflight-report-on-save-dir", mcpSaveDir()]+ # plus "--emit=json" for format=json, and passes stdout through+ # verbatim. Mirror that invocation exactly.+ rc, out = _run_cli(+ [+ "--preflight",+ "--preflight-report-on-save-dir",+ self.MCP_SAVE_DIR,+ "--emit=json",+ ],+ config,+ )+ self.assertEqual(0, rc)+ return out, json.loads(out)++ def test_mcp_passthrough_top_level_key_set_is_frozen(self):+ _, payload = self._preflight_mcp_invocation(FAKE_KEYLESS_CONFIG)+ self.assertEqual(PREFLIGHT_TOP_KEYS, set(payload.keys()))++ def test_mcp_passthrough_top_level_key_set_is_frozen_with_keys(self):+ _, payload = self._preflight_mcp_invocation(FAKE_KEYED_CONFIG)+ self.assertEqual(PREFLIGHT_TOP_KEYS, set(payload.keys()))++ def test_mcp_passthrough_nested_shapes_are_frozen(self):+ _, payload = self._preflight_mcp_invocation(FAKE_KEYLESS_CONFIG)+ self.assertEqual(PREFLIGHT_LOCAL_READS_KEYS, set(payload["local_reads"].keys()))+ self.assertEqual(+ PREFLIGHT_PROJECT_CONFIG_KEYS,+ set(payload["local_reads"]["project_config"].keys()),+ )+ self.assertEqual(+ PREFLIGHT_BROWSER_COOKIES_KEYS,+ set(payload["local_reads"]["browser_cookies"].keys()),+ )+ self.assertEqual(PREFLIGHT_CREDENTIALS_KEYS, set(payload["credentials"].keys()))+ for entry in payload["credentials"].values():+ self.assertEqual({"present", "label"}, set(entry.keys()))+ self.assertIsInstance(entry["present"], bool)+ self.assertEqual(PREFLIGHT_NETWORK_KEYS, set(payload["network"].keys()))+ self.assertIsInstance(payload["network"]["available_sources"], list)++ def test_mcp_passthrough_reports_conditional_write_for_save_dir(self):+ # With --preflight-report-on-save-dir and no --save-dir, the report+ # dir appears as a conditional write — the MCP tool relies on this to+ # explain what a save WOULD touch.+ _, payload = self._preflight_mcp_invocation(FAKE_KEYLESS_CONFIG)+ self.assertIn(+ {"kind": "report_on_save", "path": self.MCP_SAVE_DIR},+ payload["conditional_writes"],+ )++ def test_mcp_passthrough_byte_format_is_stable(self):+ # The Go tool surfaces stdout verbatim, so the serialization format+ # (indent=2, sort_keys=True, trailing newline) is part of the contract.+ out, payload = self._preflight_mcp_invocation(FAKE_KEYLESS_CONFIG)+ self.assertEqual(json.dumps(payload, indent=2, sort_keys=True) + "\n", out)++ def test_no_secret_values_in_preflight_output(self):+ out, _ = self._preflight_mcp_invocation(FAKE_KEYED_CONFIG)+ for secret in FAKE_KEYED_CONFIG.values():+ self.assertNotIn(secret, out)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_doctor.py b/tests/test_doctor.pynew file mode 100644index 00000000..e78aa987--- /dev/null+++ b/tests/test_doctor.py@@ -0,0 +1,496 @@+"""U4: unified `doctor` command (lib/doctor.py + topic-word dispatch).++Covers the plan's U4 scenarios:+ 1. Fully keyless env -> free sources (reddit, hackernews, polymarket,+ github) tier ok; key-gated sources tier off with prescriptions; exit 0.+ 2. `--json` per-source shape for every registered source (chained and+ single-backend), tier/status rollup rows asserted.+ 3. One probe timing out -> that source status `timeout`, tier `error`,+ all other sources still render (plus per-source exception isolation).+ 4. No-secrets invariant: seeded fake credentials never appear in text or+ JSON output.+ 5. Topic-word dispatch: `doctor` triggers the report; a longer research+ topic containing the word does not (setup's exact-match collision rule).+ 6. Native-search host + no web keys -> web tier off with a host-native+ note, never a false-alarm error.+"""++import io+import json+import sys+import unittest+from contextlib import redirect_stderr, redirect_stdout+from unittest import mock++import last30days as cli+from lib import backends, doctor, health, prescriptions++BIRD_STATUS_OFF = {+ "installed": False,+ "authenticated": False,+ "username": None,+ "can_install": True,+}++# Obvious dummies only (repo security hygiene).+FAKE_SECRETS = {+ "SCRAPECREATORS_API_KEY": "dummy-sc-secret-000",+ "XAI_API_KEY": "dummy-xai-secret-000",+ "BRAVE_API_KEY": "dummy-brave-secret-000",+ "GROQ_API_KEY": "dummy-groq-secret-000",+ "AUTH_TOKEN": "dummy-auth-token-secret-000",+ "CT0": "dummy-ct0-secret-000",+ "BSKY_HANDLE": "dummy.example.social",+ "BSKY_APP_PASSWORD": "dummy-bsky-secret-000",+ "TRUTHSOCIAL_TOKEN": "dummy-truth-secret-000",+ "GITHUB_TOKEN": "dummy-github-secret-000",+}++VALID_TIERS = {"ok", "warn", "off", "error"}+VALID_STATUSES = {+ "ok", "degraded", "opt-in", "unconfigured", "missing", "broken", "timeout", "error",+}+# The R1 rollup table, row by row.+TIER_BY_STATUS = {+ "ok": "ok",+ "degraded": "warn",+ "opt-in": "off",+ "unconfigured": "off",+ "missing": "error",+ "broken": "error",+ "timeout": "error",+ "error": "error",+}+++def _probe_dep(status_map=None, default_status=health.MISSING):+ """Fake health.probe_dependency honoring a per-name status map."""+ status_map = status_map or {}++ def fake(name, timeout=health.PROBE_TIMEOUT):+ status = status_map.get(name, default_status)+ if status == health.OK:+ return health.DependencyProbe(name=name, status=health.OK, detail=f"{name} 1.0.0")+ return health.DependencyProbe(+ name=name,+ status=status,+ detail=f"{name} probe simulated {status}",+ prescription=(+ f"install {name}" if status == health.MISSING else f"reinstall {name}"+ ),+ owner_pkg_manager="brew",+ )++ return fake+++class _Hermetic:+ """Context manager stack making doctor runs machine-independent."""++ def __init__(self, probe_map=None, default_status=health.MISSING):+ self._patches = [+ mock.patch("lib.health.probe_dependency", _probe_dep(probe_map, default_status)),+ mock.patch("lib.bird_x.is_bird_installed", return_value=False),+ mock.patch("lib.bird_x.set_credentials", lambda *a, **k: None),+ mock.patch("lib.bird_x.get_bird_status", return_value=dict(BIRD_STATUS_OFF)),+ # The doctor path is local-only for xurl: the live `xurl whoami`+ # network check must never run (no-network guarantee).+ mock.patch(+ "lib.xurl_x.is_available",+ side_effect=AssertionError(+ "doctor path ran the live `xurl whoami` network check"+ ),+ ),+ mock.patch("lib.xurl_x.has_stored_auth", return_value=False),+ mock.patch(+ "lib.xurl_x.stored_auth_status",+ return_value=("missing", "no token store at ~/.xurl"),+ ),+ mock.patch("lib.backends.which", lambda name: None),+ ]++ def __enter__(self):+ for p in self._patches:+ p.start()+ return self++ def __exit__(self, *exc):+ for p in reversed(self._patches):+ p.stop()+ return False+++def _build(config, **kwargs):+ with _Hermetic(**kwargs):+ return doctor.build_report(dict(config))+++def _run_cli_doctor(argv, config):+ with _Hermetic(), \+ mock.patch.object(cli.env, "get_config", return_value=dict(config)), \+ mock.patch.object(sys, "argv", ["last30days.py"] + argv):+ stdout = io.StringIO()+ stderr = io.StringIO()+ with redirect_stdout(stdout), redirect_stderr(stderr):+ rc = cli.main()+ return rc, stdout.getvalue()+++class KeylessEnvironment(unittest.TestCase):+ """Scenario 1: fully keyless env."""++ def setUp(self):+ self.report = _build({})++ def test_free_sources_tier_ok(self):+ for name in ("reddit", "hackernews", "polymarket", "github"):+ self.assertEqual("ok", self.report["sources"][name]["tier"], name)+ self.assertEqual("ok", self.report["sources"][name]["status"], name)++ def test_key_gated_sources_off_with_prescriptions(self):+ for name in ("x", "tiktok", "instagram", "threads", "bluesky", "truthsocial"):+ record = self.report["sources"][name]+ self.assertEqual("off", record["tier"], name)+ self.assertIn(record["status"], ("unconfigured", "opt-in"), name)+ self.assertTrue(record["fix"], f"{name} must carry a fix prescription")++ def test_youtube_off_when_ytdlp_missing_and_no_key(self):+ record = self.report["sources"]["youtube"]+ self.assertEqual("off", record["tier"])+ self.assertEqual("unconfigured", record["status"])+ self.assertTrue(record["fix"])++ def test_web_keyless_floor_is_degraded_not_error(self):+ record = self.report["sources"]["web"]+ self.assertEqual("warn", record["tier"])+ self.assertEqual("degraded", record["status"])+ self.assertEqual("keyless", record["active_backend"])++ def test_cli_exit_code_zero_even_with_problems(self):+ rc, out = _run_cli_doctor(["doctor"], {})+ self.assertEqual(0, rc)+ self.assertIn("last30days doctor", out)+++class UnconfiguredXWithBrokenNode(unittest.TestCase):+ """F9 repro: no X configuration + a broken node runtime must read as+ off/unconfigured with the cookie fix on bird — never a configured-but-+ broken error carrying a node prescription."""++ def test_x_rolls_up_off_with_cookie_prescription(self):+ report = _build({}, probe_map={"node": health.BROKEN})+ record = report["sources"]["x"]+ self.assertEqual("off", record["tier"])+ self.assertEqual("unconfigured", record["status"])+ bird = next(b for b in record["backends"] if b["name"] == "bird")+ self.assertEqual("missing", bird["status"])+ self.assertIn("cookie", (bird["detail"] + bird["fix"]).lower())+ self.assertNotIn("node", bird["fix"].lower())+++class JsonShape(unittest.TestCase):+ """Scenario 2: documented per-source shape for every registered source."""++ def setUp(self):+ self.report = _build(dict(FAKE_SECRETS))++ def test_every_registered_source_present(self):+ self.assertEqual(set(doctor.SOURCE_ORDER), set(self.report["sources"].keys()))++ def test_per_source_record_shape(self):+ for name, record in self.report["sources"].items():+ for key in ("tier", "status", "backends", "mode", "active_backend", "fix", "requires"):+ self.assertIn(key, record, f"{name} missing {key}")+ self.assertIn(record["tier"], VALID_TIERS, name)+ self.assertIn(record["status"], VALID_STATUSES, name)++ def test_tier_status_rollup_rows(self):+ for name, record in self.report["sources"].items():+ self.assertEqual(+ TIER_BY_STATUS[record["status"]], record["tier"],+ f"{name}: status {record['status']} must roll up to "+ f"{TIER_BY_STATUS[record['status']]}",+ )++ def test_chained_sources_expose_backends_and_mode(self):+ for name in ("x", "youtube", "web"):+ record = self.report["sources"][name]+ self.assertEqual("alternative", record["mode"], name)+ self.assertIsInstance(record["backends"], list, name)+ self.assertTrue(record["backends"], name)+ self.assertEqual("conditional", self.report["sources"]["reddit"]["mode"])+ self.assertIsInstance(self.report["sources"]["reddit"]["backends"], list)++ def test_single_backend_sources_have_single_mode(self):+ for name in ("hackernews", "polymarket", "github", "bluesky"):+ record = self.report["sources"][name]+ self.assertEqual("single", record["mode"], name)+ self.assertIsNone(record["backends"], name)++ def test_conditional_reddit_never_picks_a_winner(self):+ record = self.report["sources"]["reddit"]+ self.assertIsNone(record["active_backend"])+ # Conditional wording is U2's, verbatim.+ with _Hermetic():+ expected = backends.resolve("reddit", dict(FAKE_SECRETS)).conditional+ self.assertEqual(expected, record["note"])++ def test_web_pin_is_flag_only_no_env_pin(self):+ # Web search has NO env pin; only the --web-backend flag.+ record = self.report["sources"]["web"]+ self.assertIsNone(record["pin_var"])+ self.assertEqual("--web-backend", record["pin_flag"])++ def test_chained_ok_source_predicts_will_use(self):+ record = self.report["sources"]["web"]+ self.assertEqual("ok", record["tier"])+ self.assertEqual("brave", record["active_backend"])+ self.assertIn("will use: brave", record["note"])++ def test_top_level_block(self):+ for key in ("engine_version", "config", "setup", "permissions", "sources"):+ self.assertIn(key, self.report)+ self.assertIsInstance(self.report["engine_version"], str)+ self.assertTrue(self.report["engine_version"])+ setup = self.report["setup"]+ self.assertIsInstance(setup["setup_complete"], bool)+ for name, present in setup["keys_present"].items():+ self.assertIsInstance(present, bool, name)+ self.assertIn("status", self.report["permissions"])++ def test_json_renderer_round_trips(self):+ payload = json.loads(doctor.render_json(self.report))+ self.assertEqual(set(doctor.SOURCE_ORDER), set(payload["sources"].keys()))+++class ProbeFailureIsolation(unittest.TestCase):+ """Scenario 3: one bad probe cannot blank the report."""++ def test_timeout_probe_maps_to_timeout_status_error_tier(self):+ report = _build({}, probe_map={"yt-dlp": health.TIMEOUT})+ record = report["sources"]["youtube"]+ self.assertEqual("timeout", record["status"])+ self.assertEqual("error", record["tier"])+ self.assertTrue(record["fix"])+ # Everything else still renders.+ self.assertEqual("ok", report["sources"]["reddit"]["tier"])+ self.assertEqual("ok", report["sources"]["hackernews"]["tier"])++ def test_broken_probe_maps_to_broken(self):+ report = _build({}, probe_map={"yt-dlp": health.BROKEN})+ record = report["sources"]["youtube"]+ self.assertEqual("broken", record["status"])+ self.assertEqual("error", record["tier"])++ def test_chained_failure_requires_names_the_failed_backend(self):+ """F4: chain[0] merely MISSING while a later backend is BROKEN ->+ the record's requires is the BROKEN backend's (mirroring how the+ OK/WARN branches use the active finding), never chain[0]'s."""+ config = {+ "AUTH_TOKEN": "dummy-auth-token-secret-000",+ "CT0": "dummy-ct0-secret-000",+ }+ with _Hermetic(probe_map={"node": health.BROKEN}), \+ mock.patch("lib.bird_x.is_bird_installed", return_value=True):+ report = doctor.build_report(dict(config))+ record = report["sources"]["x"]+ self.assertEqual("broken", record["status"])+ self.assertEqual("error", record["tier"])+ by_name = {b["name"]: b for b in record["backends"]}+ # chain[0] (xai) is merely unconfigured; bird is the broken one.+ self.assertEqual("missing", by_name["xai"]["status"])+ self.assertEqual("broken", by_name["bird"]["status"])+ self.assertEqual(by_name["bird"]["requires"], record["requires"])+ self.assertNotEqual(by_name["xai"]["requires"], record["requires"])++ def test_source_exception_is_isolated(self):+ real_resolve = backends.resolve++ def exploding(source, config, pin=None):+ if source == "x":+ raise RuntimeError("probe blew up")+ return real_resolve(source, config, pin)++ with _Hermetic(), mock.patch("lib.backends.resolve", exploding):+ report = doctor.build_report({})+ record = report["sources"]["x"]+ self.assertEqual("error", record["status"])+ self.assertEqual("error", record["tier"])+ self.assertIn("RuntimeError", record["detail"])+ # The rest of the report survives.+ self.assertEqual("ok", report["sources"]["reddit"]["tier"])+ self.assertEqual(set(doctor.SOURCE_ORDER), set(report["sources"].keys()))+ # And the whole report still renders as text and JSON.+ self.assertTrue(doctor.render_text(report))+ json.loads(doctor.render_json(report))+++class NoSecretsInvariant(unittest.TestCase):+ """Scenario 4: seeded fake credentials never appear in any output."""++ def test_no_secret_values_in_text_or_json(self):+ report = _build(dict(FAKE_SECRETS))+ text = doctor.render_text(report)+ raw_json = doctor.render_json(report)+ for var, secret in FAKE_SECRETS.items():+ if var == "BSKY_HANDLE":+ continue # a handle is an identifier, not a credential+ self.assertNotIn(secret, text, var)+ self.assertNotIn(secret, raw_json, var)++ def test_keys_present_are_booleans(self):+ report = _build(dict(FAKE_SECRETS))+ for name, value in report["setup"]["keys_present"].items():+ self.assertIsInstance(value, bool, name)+++class TopicWordDispatch(unittest.TestCase):+ """Scenario 5: `doctor` dispatches exactly like `setup` (exact match only)."""++ def test_doctor_topic_triggers_report(self):+ with mock.patch("lib.doctor.run", return_value=0) as run, \+ mock.patch.object(cli.env, "get_config", return_value={}), \+ mock.patch.object(sys, "argv", ["last30days.py", "doctor"]):+ stdout, stderr = io.StringIO(), io.StringIO()+ with redirect_stdout(stdout), redirect_stderr(stderr):+ rc = cli.main()+ self.assertEqual(0, rc)+ self.assertTrue(run.called)++ def test_doctor_json_flag_passes_through(self):+ with mock.patch("lib.doctor.run", return_value=0) as run, \+ mock.patch.object(cli.env, "get_config", return_value={}), \+ mock.patch.object(sys, "argv", ["last30days.py", "doctor", "--json"]):+ stdout, stderr = io.StringIO(), io.StringIO()+ with redirect_stdout(stdout), redirect_stderr(stderr):+ rc = cli.main()+ self.assertEqual(0, rc)+ self.assertTrue(run.call_args.kwargs.get("emit_json"))++ def test_doctor_emit_json_also_works(self):+ rc, out = _run_cli_doctor(["doctor", "--emit=json"], {})+ self.assertEqual(0, rc)+ payload = json.loads(out)+ self.assertIn("sources", payload)++ def test_multiword_topic_containing_doctor_is_research_not_report(self):+ # Same collision rule as setup: exact single-word match only. A real+ # research topic goes down the research path (sentinel raised there).+ with mock.patch("lib.doctor.run", side_effect=AssertionError("doctor must not run")), \+ mock.patch.object(cli.env, "get_config", return_value={}), \+ mock.patch.object(+ cli.pipeline, "diagnose", side_effect=RuntimeError("research path reached")+ ), \+ mock.patch.object(sys, "argv", ["last30days.py", "doctor", "who", "reviews"]):+ stdout, stderr = io.StringIO(), io.StringIO()+ with redirect_stdout(stdout), redirect_stderr(stderr):+ with self.assertRaises(RuntimeError):+ cli.main()++ def test_json_flag_rejected_for_research_topics(self):+ with mock.patch.object(+ cli.env, "get_config", side_effect=AssertionError("config should not load")+ ), mock.patch.object(sys, "argv", ["last30days.py", "some", "topic", "--json"]):+ stderr = io.StringIO()+ with redirect_stderr(stderr), self.assertRaises(SystemExit) as exc:+ cli.main()+ self.assertEqual(2, exc.exception.code)+ self.assertIn("--json", stderr.getvalue())+++class IncludeSourcesTokenParsing(unittest.TestCase):+ """Opt-in gates match whole INCLUDE_SOURCES tokens, never substrings."""++ def test_substring_token_does_not_enable_linkedin(self):+ report = _build({+ "SCRAPECREATORS_API_KEY": "dummy-sc-secret-000",+ "INCLUDE_SOURCES": "notlinkedincorp",+ })+ record = report["sources"]["linkedin"]+ self.assertEqual("opt-in", record["status"])+ self.assertEqual("off", record["tier"])++ def test_exact_token_enables_linkedin(self):+ report = _build({+ "SCRAPECREATORS_API_KEY": "dummy-sc-secret-000",+ "INCLUDE_SOURCES": "linkedin",+ })+ record = report["sources"]["linkedin"]+ self.assertEqual("ok", record["status"])+ self.assertEqual("ok", record["tier"])+++class YoutubeTranscriptionNote(unittest.TestCase):+ """F7: yt-dlp probes OK but no GROQ_API_KEY/OPENAI_API_KEY -> the ok+ youtube record carries the caption-free note plus the+ transcription_key_missing fix, and (F14) the text renderer surfaces+ that fix even though the record's tier is ok."""++ def setUp(self):+ self.report = _build({}, probe_map={"yt-dlp": health.OK})+ self.entry = prescriptions.get("youtube", "transcription_key_missing")++ def test_ok_record_carries_note_and_fix(self):+ record = self.report["sources"]["youtube"]+ self.assertEqual("ok", record["tier"])+ self.assertEqual("ok", record["status"])+ self.assertIn("no transcription key for caption-free videos", record["note"])+ self.assertIn(self.entry.fix_nl, record["fix"])+ self.assertIn(self.entry.fix_cli, record["fix"])++ def test_text_line_includes_the_fix_on_the_ok_line(self):+ text = doctor.render_text(self.report)+ line = next(+ l for l in text.splitlines() if l.strip().startswith("✓ youtube")+ )+ self.assertIn("no transcription key for caption-free videos", line)+ self.assertIn(f"fix: {self.entry.fix_nl}", line)+ self.assertIn(self.entry.fix_cli, line)+++class NativeSearchHost(unittest.TestCase):+ """Scenario 6: native-search host with no web keys -> off, not error."""++ def test_web_maps_to_off_with_host_native_note(self):+ report = _build({"LAST30DAYS_NATIVE_SEARCH": "1"})+ record = report["sources"]["web"]+ self.assertEqual("off", record["tier"])+ self.assertEqual("unconfigured", record["status"])+ self.assertIn("host-native search", record["note"])++ def test_web_with_key_stays_ok_on_native_host(self):+ report = _build({+ "LAST30DAYS_NATIVE_SEARCH": "1",+ "EXA_API_KEY": "dummy-exa-secret-000",+ })+ record = report["sources"]["web"]+ self.assertEqual("ok", record["tier"])+ self.assertEqual("exa", record["active_backend"])+++class TextReport(unittest.TestCase):+ """Grouped text rendering: ready / degraded / off / error."""++ def test_groups_and_lines(self):+ report = _build({}, probe_map={"yt-dlp": health.BROKEN})+ text = doctor.render_text(report)+ self.assertIn("last30days doctor", text)+ for header in ("Ready", "Degraded", "Off", "Errors"):+ self.assertIn(header, text)+ # One line per source: glyph + source name; fix on non-ok lines.+ self.assertIn("reddit", text)+ self.assertIn("youtube", text)+ self.assertIn("reinstall yt-dlp", text)+ # Reddit renders U2's conditional wording verbatim, no single winner.+ with _Hermetic():+ conditional = backends.resolve("reddit", {}).conditional+ self.assertIn(conditional, text)++ def test_will_use_rendered_for_chained_ok_source(self):+ report = _build({"BRAVE_API_KEY": "dummy-brave-secret-000"})+ text = doctor.render_text(report)+ self.assertIn("will use: brave", text)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_doctor_cache.py b/tests/test_doctor_cache.pynew file mode 100644index 00000000..44713428--- /dev/null+++ b/tests/test_doctor_cache.py@@ -0,0 +1,669 @@+"""U5: doctor cache — results persist across invocations with a TTL.++Covers the plan's U5 scenarios (R5, R7, KTD 8):+ 1. Fresh cache within TTL -> `--cached` returns the stored result and+ spawns zero probes (probe layer spied, never called).+ 2. Stale or missing cache -> live run executes and rewrites the cache.+ 3. Explicit `doctor` (no `--cached`) -> always live; cache refreshed+ even when a fresh cache exists.+ 4. TTL env override (LAST30DAYS_DOCTOR_TTL, seconds) respected;+ malformed/corrupt cache treated as absent — never a crash.+ 5. No secret values in the cache file under seeded fake credentials.+ 6. SKILL.md contract (test_onboarding_contract.py pattern): doctor+ trigger phrases and the cached standing rule are present, so future+ SKILL.md edits cannot silently erode the integration.+"""++import datetime+import io+import json+import os+import sys+import tempfile+import unittest+from contextlib import redirect_stderr, redirect_stdout+from pathlib import Path+from unittest import mock++import last30days as cli+from lib import doctor, health++ROOT = Path(__file__).resolve().parents[1]+SKILL_MD = ROOT / "skills" / "last30days" / "SKILL.md"++BIRD_STATUS_OFF = {+ "installed": False,+ "authenticated": False,+ "username": None,+ "can_install": True,+}++# Obvious dummies only (repo security hygiene).+FAKE_SECRETS = {+ "SCRAPECREATORS_API_KEY": "dummy-sc-secret-000",+ "XAI_API_KEY": "dummy-xai-secret-000",+ "BRAVE_API_KEY": "dummy-brave-secret-000",+ "AUTH_TOKEN": "dummy-auth-token-secret-000",+ "CT0": "dummy-ct0-secret-000",+ "BSKY_HANDLE": "dummy.example.social",+ "BSKY_APP_PASSWORD": "dummy-bsky-secret-000",+ "TRUTHSOCIAL_TOKEN": "dummy-truth-secret-000",+ "GITHUB_TOKEN": "dummy-github-secret-000",+}+++def _iso_utc(seconds_ago: float = 0.0) -> str:+ return (+ datetime.datetime.now(datetime.timezone.utc)+ - datetime.timedelta(seconds=seconds_ago)+ ).isoformat()+++def _fake_probe(name, timeout=health.PROBE_TIMEOUT):+ return health.DependencyProbe(+ name=name,+ status=health.MISSING,+ detail=f"{name} probe simulated missing",+ prescription=f"install {name}",+ owner_pkg_manager="brew",+ )+++class _Hermetic:+ """Machine-independent doctor runs (mirrors tests/test_doctor.py)."""++ def __init__(self, probe=None):+ self.probe_spy = mock.Mock(side_effect=probe or _fake_probe)+ self._patches = [+ mock.patch("lib.health.probe_dependency", self.probe_spy),+ mock.patch("lib.bird_x.is_bird_installed", return_value=False),+ mock.patch("lib.bird_x.set_credentials", lambda *a, **k: None),+ mock.patch("lib.bird_x.get_bird_status", return_value=dict(BIRD_STATUS_OFF)),+ # Doctor path is local-only for xurl: the live `xurl whoami`+ # network check must never run (no-network guarantee).+ mock.patch(+ "lib.xurl_x.is_available",+ side_effect=AssertionError(+ "doctor path ran the live `xurl whoami` network check"+ ),+ ),+ mock.patch("lib.xurl_x.has_stored_auth", return_value=False),+ mock.patch(+ "lib.xurl_x.stored_auth_status",+ return_value=("missing", "no token store at ~/.xurl"),+ ),+ mock.patch("lib.backends.which", lambda name: None),+ ]++ def __enter__(self):+ for p in self._patches:+ p.start()+ return self++ def __exit__(self, *exc):+ for p in reversed(self._patches):+ p.stop()+ return False+++class _CacheDirCase(unittest.TestCase):+ """Base: isolated CONFIG_DIR + clean TTL env for every test."""++ def setUp(self):+ self._tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self._tmp.cleanup)+ self.config_dir = Path(self._tmp.name)+ patcher = mock.patch.object(cli.env, "CONFIG_DIR", self.config_dir)+ patcher.start()+ self.addCleanup(patcher.stop)+ env_patcher = mock.patch.dict(os.environ, {}, clear=False)+ env_patcher.start()+ self.addCleanup(env_patcher.stop)+ os.environ.pop("LAST30DAYS_DOCTOR_TTL", None)++ @property+ def cache_file(self) -> Path:+ return self.config_dir / doctor.CACHE_FILENAME++ @staticmethod+ def valid_report(marker="cached-sentinel-report"):+ """A report satisfying the render contract, carrying a marker."""+ return {+ "engine_version": marker,+ "config": {"global_env": None, "config_source": None},+ "setup": {"setup_complete": False, "keys_present": {}},+ "permissions": {"status": "ok"},+ "sources": {+ "hackernews": {+ "tier": "ok", "status": "ok", "mode": "single",+ "backends": None, "active_backend": None, "fix": "",+ "requires": "none", "note": marker, "detail": "",+ "pin_var": None, "pin_flag": None, "pinned": False,+ },+ },+ }++ def write_cache(+ self,+ *,+ seconds_ago=0.0,+ marker="cached-sentinel-report",+ config=None,+ schema=None,+ fingerprint=None,+ report=None,+ ):+ """Seed a valid cached payload (schema + fingerprint stamped)."""+ if report is None:+ report = self.valid_report(marker)+ payload = {+ "schema": doctor.DOCTOR_CACHE_SCHEMA_VERSION if schema is None else schema,+ "fingerprint": (+ doctor._config_fingerprint(dict(config or {}))+ if fingerprint is None+ else fingerprint+ ),+ "timestamp": _iso_utc(seconds_ago),+ "report": report,+ }+ self.cache_file.write_text(json.dumps(payload), encoding="utf-8")+ return report++ def run_doctor(self, config=None, *, cached, emit_json=True):+ with _Hermetic() as h:+ stdout = io.StringIO()+ with redirect_stdout(stdout):+ rc = doctor.run(dict(config or {}), emit_json=emit_json, cached=cached)+ return rc, stdout.getvalue(), h.probe_spy+++class FreshCacheServed(_CacheDirCase):+ """Scenario 1: fresh cache within TTL -> stored result, zero probes."""++ def test_cached_returns_stored_report(self):+ self.write_cache(seconds_ago=1)+ rc, out, _ = self.run_doctor(cached=True)+ self.assertEqual(0, rc)+ self.assertIn("cached-sentinel-report", out)+ payload = json.loads(out)+ self.assertIn("sources", payload)++ def test_cached_spawns_zero_probes_and_no_live_aggregation(self):+ self.write_cache(seconds_ago=1)+ with mock.patch(+ "lib.doctor.build_report",+ side_effect=AssertionError("live aggregation must not run"),+ ) as build:+ rc, out, probe_spy = self.run_doctor(cached=True)+ self.assertEqual(0, rc)+ self.assertFalse(probe_spy.called, "probe layer must not be touched")+ self.assertFalse(build.called)++ def test_cached_hit_does_not_rewrite_cache(self):+ self.write_cache(seconds_ago=1)+ before = self.cache_file.read_text(encoding="utf-8")+ self.run_doctor(cached=True)+ self.assertEqual(before, self.cache_file.read_text(encoding="utf-8"))++ def test_cached_text_render_from_cache(self):+ self.write_cache(seconds_ago=1)+ rc, out, probe_spy = self.run_doctor(cached=True, emit_json=False)+ self.assertEqual(0, rc)+ self.assertIn("last30days doctor", out)+ self.assertFalse(probe_spy.called)+++class StaleOrMissingCacheRunsLive(_CacheDirCase):+ """Scenario 2: stale or missing cache -> live run rewrites the cache."""++ def test_stale_cache_falls_through_to_live_run(self):+ self.write_cache(seconds_ago=doctor.DEFAULT_CACHE_TTL_SECONDS * 2)+ rc, out, probe_spy = self.run_doctor(cached=True)+ self.assertEqual(0, rc)+ self.assertNotIn("cached-sentinel-report", out)+ self.assertTrue(probe_spy.called, "stale cache must trigger live probes")++ def test_stale_cache_is_rewritten(self):+ self.write_cache(seconds_ago=doctor.DEFAULT_CACHE_TTL_SECONDS * 2)+ self.run_doctor(cached=True)+ payload = json.loads(self.cache_file.read_text(encoding="utf-8"))+ self.assertNotIn("cached-sentinel-report", json.dumps(payload))+ self.assertIn("report", payload)+ self.assertIn("sources", payload["report"])+ # New timestamp is fresh.+ age = datetime.datetime.now(datetime.timezone.utc) - datetime.datetime.fromisoformat(+ payload["timestamp"]+ )+ self.assertLess(age.total_seconds(), 60)++ def test_missing_cache_runs_live_and_creates_file(self):+ self.assertFalse(self.cache_file.exists())+ rc, out, probe_spy = self.run_doctor(cached=True)+ self.assertEqual(0, rc)+ self.assertTrue(probe_spy.called)+ self.assertTrue(self.cache_file.exists())+ payload = json.loads(self.cache_file.read_text(encoding="utf-8"))+ self.assertEqual(+ set(doctor.SOURCE_ORDER), set(payload["report"]["sources"].keys())+ )+++class ExplicitDoctorAlwaysLive(_CacheDirCase):+ """Scenario 3: no --cached -> live run even when a fresh cache exists."""++ def test_fresh_cache_ignored_without_cached_flag(self):+ self.write_cache(seconds_ago=1)+ rc, out, probe_spy = self.run_doctor(cached=False)+ self.assertEqual(0, rc)+ self.assertNotIn("cached-sentinel-report", out)+ self.assertTrue(probe_spy.called)++ def test_live_run_refreshes_fresh_cache(self):+ self.write_cache(seconds_ago=1)+ self.run_doctor(cached=False)+ raw = self.cache_file.read_text(encoding="utf-8")+ self.assertNotIn("cached-sentinel-report", raw)+ self.assertIn("sources", json.loads(raw)["report"])+++class TtlOverrideAndCorruptCache(_CacheDirCase):+ """Scenario 4: TTL env override respected; corrupt cache = absent."""++ def test_ttl_env_override_shrinks_window(self):+ self.write_cache(seconds_ago=10)+ os.environ["LAST30DAYS_DOCTOR_TTL"] = "1"+ rc, out, probe_spy = self.run_doctor(cached=True)+ self.assertEqual(0, rc)+ self.assertNotIn("cached-sentinel-report", out)+ self.assertTrue(probe_spy.called)++ def test_ttl_env_override_widens_window(self):+ self.write_cache(seconds_ago=doctor.DEFAULT_CACHE_TTL_SECONDS * 2)+ os.environ["LAST30DAYS_DOCTOR_TTL"] = str(doctor.DEFAULT_CACHE_TTL_SECONDS * 10)+ rc, out, probe_spy = self.run_doctor(cached=True)+ self.assertIn("cached-sentinel-report", out)+ self.assertFalse(probe_spy.called)++ def test_ttl_from_config_layer(self):+ # Registered env key: a .env-set value reaches doctor via config.+ self.write_cache(seconds_ago=10)+ rc, out, probe_spy = self.run_doctor({"LAST30DAYS_DOCTOR_TTL": "1"}, cached=True)+ self.assertNotIn("cached-sentinel-report", out)+ self.assertTrue(probe_spy.called)++ def test_ttl_zero_disables_cache_reuse(self):+ self.write_cache(seconds_ago=0)+ os.environ["LAST30DAYS_DOCTOR_TTL"] = "0"+ rc, out, probe_spy = self.run_doctor(cached=True)+ self.assertNotIn("cached-sentinel-report", out)+ self.assertTrue(probe_spy.called)++ def test_garbage_ttl_falls_back_to_default(self):+ self.write_cache(seconds_ago=1)+ os.environ["LAST30DAYS_DOCTOR_TTL"] = "not-a-number"+ rc, out, probe_spy = self.run_doctor(cached=True)+ self.assertIn("cached-sentinel-report", out)+ self.assertFalse(probe_spy.called)++ def test_corrupt_cache_files_treated_as_absent(self):+ for corrupt in (+ "not json at all {",+ json.dumps(["a", "list"]),+ json.dumps({"timestamp": _iso_utc(), "report": "not-a-dict"}),+ json.dumps({"timestamp": "garbage-timestamp", "report": {"sources": {}}}),+ json.dumps({"report": {"sources": {}}}), # no timestamp+ json.dumps({"timestamp": _iso_utc(), "report": {}}), # no sources+ ):+ with self.subTest(corrupt=corrupt[:40]):+ self.cache_file.write_text(corrupt, encoding="utf-8")+ rc, out, probe_spy = self.run_doctor(cached=True)+ self.assertEqual(0, rc, "corrupt cache must never crash")+ self.assertTrue(probe_spy.called, "corrupt cache must fall through")+ # And the corrupt file is replaced by a valid one.+ payload = json.loads(self.cache_file.read_text(encoding="utf-8"))+ self.assertIn("sources", payload["report"])++ def test_no_config_dir_runs_live_without_crash(self):+ with mock.patch.object(cli.env, "CONFIG_DIR", None):+ rc, out, probe_spy = self.run_doctor(cached=True)+ self.assertEqual(0, rc)+ self.assertTrue(probe_spy.called)++ def test_ttl_env_var_is_registered(self):+ # The repo foot-gun: unregistered keys are silently swallowed from+ # .env. LAST30DAYS_DOCTOR_TTL must be in env.py's get_config registry.+ import inspect++ from lib import env as env_mod++ self.assertIn("LAST30DAYS_DOCTOR_TTL", inspect.getsource(env_mod.get_config))+++class DriftedCacheShapes(_CacheDirCase):+ """F3: cached reports that drift from the render contract fall through+ to a live run — never a KeyError crash — in text mode too."""++ def _write_payload(self, report, *, with_envelope=True, seconds_ago=1.0):+ payload = {"timestamp": _iso_utc(seconds_ago), "report": report}+ if with_envelope:+ payload["schema"] = doctor.DOCTOR_CACHE_SCHEMA_VERSION+ payload["fingerprint"] = doctor._config_fingerprint({})+ self.cache_file.write_text(json.dumps(payload), encoding="utf-8")++ def test_fresh_drifted_report_text_mode_no_crash(self):+ # Exact F3 repro: fresh timestamp, report missing engine_version /+ # config / setup / permissions, record missing tier.+ self._write_payload({"sources": {"hackernews": {"status": "ok"}}})+ rc, out, probe_spy = self.run_doctor(cached=True, emit_json=False)+ self.assertEqual(0, rc, "drifted cache must never crash")+ self.assertTrue(probe_spy.called, "drifted cache must fall through live")+ self.assertIn("last30days doctor", out)++ def test_fresh_drifted_report_pre_schema_envelope_no_crash(self):+ # The original repro shape (no schema stamp at all).+ self._write_payload(+ {"sources": {"hackernews": {"status": "ok"}}}, with_envelope=False+ )+ rc, out, probe_spy = self.run_doctor(cached=True, emit_json=False)+ self.assertEqual(0, rc)+ self.assertTrue(probe_spy.called)++ def test_shape_validator_rejects_each_drift(self):+ good = self.valid_report()+ drifted = []+ for key in ("engine_version", "config", "setup", "permissions"):+ broken = json.loads(json.dumps(good))+ del broken[key]+ drifted.append((f"missing {key}", broken))+ for key in ("config", "setup", "permissions"):+ broken = json.loads(json.dumps(good))+ broken[key] = "not-a-dict"+ drifted.append((f"{key} not a dict", broken))+ broken = json.loads(json.dumps(good))+ broken["sources"]["hackernews"] = "not-a-record"+ drifted.append(("record not a dict", broken))+ broken = json.loads(json.dumps(good))+ broken["sources"]["hackernews"]["tier"] = "sideways"+ drifted.append(("unknown tier", broken))+ broken = json.loads(json.dumps(good))+ del broken["sources"]["hackernews"]["tier"]+ drifted.append(("missing tier", broken))+ broken = json.loads(json.dumps(good))+ broken["sources"]["hackernews"]["status"] = 7+ drifted.append(("non-str status", broken))+ for label, report in drifted:+ with self.subTest(drift=label):+ self._write_payload(report)+ rc, out, probe_spy = self.run_doctor(cached=True, emit_json=False)+ self.assertEqual(0, rc, f"{label}: must never crash")+ self.assertTrue(probe_spy.called, f"{label}: must fall through")++ def test_run_survives_shapes_the_validator_misses(self):+ # Even if a bad shape slips past read_cached_report, run()'s+ # try/except falls through to a live build (never-crash contract).+ bad = self.valid_report()+ with mock.patch(+ "lib.doctor.read_cached_report",+ return_value={"sources": bad["sources"]}, # renders would KeyError+ ):+ rc, out, probe_spy = self.run_doctor(cached=True, emit_json=False)+ self.assertEqual(0, rc)+ self.assertTrue(probe_spy.called)+ self.assertIn("last30days doctor", out)+++class SchemaStamp(_CacheDirCase):+ """F8: payloads without the current schema stamp are treated as absent."""++ def test_schema_mismatch_runs_live(self):+ self.write_cache(seconds_ago=1, schema="last30days-doctor-cache/v0")+ rc, out, probe_spy = self.run_doctor(cached=True)+ self.assertEqual(0, rc)+ self.assertNotIn("cached-sentinel-report", out)+ self.assertTrue(probe_spy.called)++ def test_absent_schema_runs_live(self):+ payload = {+ "fingerprint": doctor._config_fingerprint({}),+ "timestamp": _iso_utc(1),+ "report": self.valid_report(),+ }+ self.cache_file.write_text(json.dumps(payload), encoding="utf-8")+ rc, out, probe_spy = self.run_doctor(cached=True)+ self.assertEqual(0, rc)+ self.assertNotIn("cached-sentinel-report", out)+ self.assertTrue(probe_spy.called)++ def test_live_run_stamps_schema_and_fingerprint(self):+ self.run_doctor(cached=False)+ payload = json.loads(self.cache_file.read_text(encoding="utf-8"))+ self.assertEqual(doctor.DOCTOR_CACHE_SCHEMA_VERSION, payload["schema"])+ self.assertEqual(doctor._config_fingerprint({}), payload["fingerprint"])+++class FingerprintInvalidation(_CacheDirCase):+ """F12a: credential/pin/opt-in changes invalidate the cache."""++ def test_key_added_invalidates(self):+ self.write_cache(seconds_ago=1) # fingerprint for empty config+ rc, out, probe_spy = self.run_doctor(+ {"SCRAPECREATORS_API_KEY": "dummy-sc-secret-000"}, cached=True+ )+ self.assertEqual(0, rc)+ self.assertNotIn("cached-sentinel-report", out)+ self.assertTrue(probe_spy.called, "new credential must invalidate cache")++ def test_key_removed_invalidates(self):+ cfg = {"SCRAPECREATORS_API_KEY": "dummy-sc-secret-000"}+ self.write_cache(seconds_ago=1, config=cfg)+ rc, out, probe_spy = self.run_doctor({}, cached=True)+ self.assertNotIn("cached-sentinel-report", out)+ self.assertTrue(probe_spy.called, "removed credential must invalidate cache")++ def test_pin_change_invalidates(self):+ self.write_cache(seconds_ago=1)+ rc, out, probe_spy = self.run_doctor(+ {"LAST30DAYS_X_BACKEND": "bird"}, cached=True+ )+ self.assertNotIn("cached-sentinel-report", out)+ self.assertTrue(probe_spy.called, "pin change must invalidate cache")++ def test_include_sources_change_invalidates(self):+ self.write_cache(seconds_ago=1)+ rc, out, probe_spy = self.run_doctor({"INCLUDE_SOURCES": "linkedin"}, cached=True)+ self.assertNotIn("cached-sentinel-report", out)+ self.assertTrue(probe_spy.called)++ def test_fingerprint_ignores_non_signal_config(self):+ # TTL knob is not a fingerprint signal; same-fingerprint serve holds.+ self.write_cache(seconds_ago=1)+ rc, out, probe_spy = self.run_doctor(+ {"LAST30DAYS_DOCTOR_TTL": str(doctor.DEFAULT_CACHE_TTL_SECONDS)},+ cached=True,+ )+ self.assertIn("cached-sentinel-report", out)+ self.assertFalse(probe_spy.called)+++class StalenessSignals(_CacheDirCase):+ """F12b: from_cache + generated_at surfaced on every doctor report."""++ def test_matching_fingerprint_serves_cache_with_signals(self):+ self.write_cache(seconds_ago=120)+ original_ts = json.loads(self.cache_file.read_text(encoding="utf-8"))["timestamp"]+ rc, out, probe_spy = self.run_doctor(cached=True)+ self.assertEqual(0, rc)+ self.assertFalse(probe_spy.called)+ data = json.loads(out)+ self.assertTrue(data["from_cache"])+ self.assertEqual(original_ts, data["generated_at"])++ def test_live_run_marks_from_cache_false_with_fresh_generated_at(self):+ rc, out, probe_spy = self.run_doctor(cached=False)+ self.assertTrue(probe_spy.called)+ data = json.loads(out)+ self.assertFalse(data["from_cache"])+ age = datetime.datetime.now(datetime.timezone.utc) - datetime.datetime.fromisoformat(+ data["generated_at"]+ )+ self.assertLess(age.total_seconds(), 60)++ def test_text_mode_prints_cache_status_line(self):+ self.write_cache(seconds_ago=1)+ rc, out, probe_spy = self.run_doctor(cached=True, emit_json=False)+ self.assertFalse(probe_spy.called)+ self.assertIn("generated:", out)+ self.assertIn("(cached)", out)++ def test_text_mode_live_status_line(self):+ rc, out, _ = self.run_doctor(cached=False, emit_json=False)+ self.assertIn("generated:", out)+ self.assertIn("(live)", out)+++class CacheWriteFailureWarns(_CacheDirCase):+ """F11: a failing cache write warns on stderr and stays non-fatal."""++ def test_write_failure_warns_and_exits_zero(self):+ with _Hermetic() as h:+ stdout, stderr = io.StringIO(), io.StringIO()+ with mock.patch.object(+ Path, "write_text", side_effect=OSError("disk full")+ ), redirect_stdout(stdout), redirect_stderr(stderr):+ rc = doctor.run({}, emit_json=True, cached=False)+ self.assertEqual(0, rc, "cache write failure must never be fatal")+ self.assertTrue(h.probe_spy.called)+ err = stderr.getvalue()+ self.assertIn("WARNING", err)+ self.assertIn("doctor cache", err)+ self.assertIn("disk full", err)+ # The report itself still rendered.+ self.assertIn("sources", json.loads(stdout.getvalue()))+++class NoSecretsInCacheFile(_CacheDirCase):+ """Scenario 5: seeded fake credentials never land in the cache file."""++ def test_cache_file_has_no_secret_values(self):+ rc, out, _ = self.run_doctor(dict(FAKE_SECRETS), cached=False)+ self.assertEqual(0, rc)+ raw = self.cache_file.read_text(encoding="utf-8")+ for var, secret in FAKE_SECRETS.items():+ if var == "BSKY_HANDLE":+ continue # a handle is an identifier, not a credential+ self.assertNotIn(secret, raw, var)++ def test_fingerprint_field_carries_no_secret_values(self):+ rc, out, _ = self.run_doctor(dict(FAKE_SECRETS), cached=False)+ self.assertEqual(0, rc)+ payload = json.loads(self.cache_file.read_text(encoding="utf-8"))+ fingerprint = payload["fingerprint"]+ # An opaque sha256 hex digest only — no raw values of any kind.+ self.assertRegex(fingerprint, r"^[0-9a-f]{64}$")+ for var, secret in FAKE_SECRETS.items():+ self.assertNotIn(secret, fingerprint, var)+++class CliCachedPassthrough(_CacheDirCase):+ """`doctor --cached` is an accepted passthrough flag wired to doctor.run."""++ def _cli(self, argv):+ with mock.patch("lib.doctor.run", return_value=0) as run, \+ mock.patch.object(cli.env, "get_config", return_value={}), \+ mock.patch.object(sys, "argv", ["last30days.py"] + argv):+ stdout, stderr = io.StringIO(), io.StringIO()+ with redirect_stdout(stdout), redirect_stderr(stderr):+ rc = cli.main()+ return rc, run++ def test_cached_flag_passes_through(self):+ rc, run = self._cli(["doctor", "--cached"])+ self.assertEqual(0, rc)+ self.assertTrue(run.call_args.kwargs.get("cached"))++ def test_cached_json_combination(self):+ rc, run = self._cli(["doctor", "--cached", "--json"])+ self.assertEqual(0, rc)+ self.assertTrue(run.call_args.kwargs.get("cached"))+ self.assertTrue(run.call_args.kwargs.get("emit_json"))++ def test_plain_doctor_is_live(self):+ rc, run = self._cli(["doctor"])+ self.assertEqual(0, rc)+ self.assertFalse(run.call_args.kwargs.get("cached"))++ def test_cached_rejected_for_research_topics(self):+ with mock.patch.object(sys, "argv", ["last30days.py", "some", "topic", "--cached"]):+ stderr = io.StringIO()+ with redirect_stderr(stderr), self.assertRaises(SystemExit) as exc:+ cli.main()+ self.assertEqual(2, exc.exception.code)+ self.assertIn("--cached", stderr.getvalue())+++class DoctorSkillContract(unittest.TestCase):+ """Scenario 6: SKILL.md integration locked against silent erosion+ (same read-the-runtime-contract pattern as test_onboarding_contract.py)."""++ @classmethod+ def setUpClass(cls):+ cls.text = SKILL_MD.read_text(encoding="utf-8")++ def test_doctor_trigger_phrases_present(self):+ for phrase in (+ "health check",+ "is X working",+ "why is a source missing",+ "what's broken",+ ):+ self.assertIn(phrase, self.text, f"missing doctor trigger phrase: {phrase!r}")++ def test_cached_standing_rule_present(self):+ self.assertIn("doctor --cached --json", self.text)+ self.assertIn("login-backed", self.text)+ self.assertIn("doctor-cache.json", self.text)+ self.assertIn("LAST30DAYS_DOCTOR_TTL", self.text)++ def test_rerun_live_only_when_stale_or_degraded(self):+ self.assertIn("stale", self.text)+ self.assertIn("degraded login-backed source", self.text)++ def test_standing_rule_is_marked_mandatory(self):+ # The pre-research cache consult is a must-fire rule; it uses the+ # same bold MANDATORY marker style as Step 0.45 so it cannot read+ # as soft advisory prose (F16b).+ self.assertIn("**MANDATORY standing rule.**", self.text)++ def test_frontmatter_description_carries_health_check_keywords(self):+ # Cold-start prompts like "is my last30days X search broken?" can+ # only load the skill if the machine-parsed frontmatter description+ # mentions the health surface (F16a). It must stay ONE line.+ lines = self.text.splitlines()+ self.assertEqual("---", lines[0])+ closing = lines[1:].index("---") + 1+ frontmatter = lines[1:closing]+ desc_lines = [l for l in frontmatter if l.startswith("description:")]+ self.assertEqual(1, len(desc_lines), "description must be one line")+ desc = desc_lines[0].lower()+ for needle in ("doctor", "health check", "diagnose", "broken"):+ self.assertIn(needle, desc, f"description missing keyword: {needle!r}")++ def test_predicted_backend_announcement(self):+ self.assertIn("active_backend", self.text)++ def test_configuration_md_documents_doctor(self):+ config_text = (ROOT / "CONFIGURATION.md").read_text(encoding="utf-8")+ for needle in (+ "doctor --json",+ "doctor --cached",+ "doctor-cache.json",+ "LAST30DAYS_DOCTOR_TTL",+ "LAST30DAYS_X_BACKEND",+ "LAST30DAYS_REDDIT_BACKEND",+ "--web-backend",+ ):+ self.assertIn(needle, config_text, f"CONFIGURATION.md missing: {needle!r}")+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_env_v3.py b/tests/test_env_v3.pyindex 6bd1b0c5..1544c5bc 100644--- a/tests/test_env_v3.py+++ b/tests/test_env_v3.py@@ -71,6 +71,76 @@ class EnvV3Tests(unittest.TestCase):self.assertEqual(value, config[key])+class XurlSafePathGatingTests(unittest.TestCase):+ """F1: the safe/diagnose path (probe=False — what doctor uses) never+ runs xurl's live `whoami` network check; it keys on local evidence+ (xurl_x.has_stored_auth) instead."""++ BIRD_OFF = {+ "installed": False,+ "authenticated": False,+ "username": None,+ "can_install": True,+ }++ def _status(self, config, probe, stored_mock, live_mock):+ with mock.patch("lib.bird_x.get_bird_status", return_value=dict(self.BIRD_OFF)), \+ mock.patch("lib.bird_x.set_credentials", lambda *a, **k: None), \+ mock.patch("lib.xurl_x.has_stored_auth", **stored_mock), \+ mock.patch("lib.xurl_x.is_available", **live_mock):+ return env.get_x_source_status(config, probe=probe)++ _LIVE_FORBIDDEN = {+ "side_effect": AssertionError(+ "probe=False must not run the live `xurl whoami` network check"+ )+ }+ _STORED_FORBIDDEN = {+ "side_effect": AssertionError("probe=True should use the live check")+ }++ def test_probe_false_uses_local_evidence_only(self):+ status = self._status(+ {}, probe=False,+ stored_mock={"return_value": True}, live_mock=self._LIVE_FORBIDDEN,+ )+ self.assertEqual("xurl", status["source"])+ self.assertTrue(status["xurl_available"])++ def test_probe_false_without_stored_auth_reports_unavailable(self):+ status = self._status(+ {}, probe=False,+ stored_mock={"return_value": False}, live_mock=self._LIVE_FORBIDDEN,+ )+ self.assertIsNone(status["source"])+ self.assertFalse(status["xurl_available"])++ def test_probe_true_keeps_the_live_check(self):+ status = self._status(+ {}, probe=True,+ stored_mock=self._STORED_FORBIDDEN, live_mock={"return_value": True},+ )+ self.assertEqual("xurl", status["source"])+ self.assertTrue(status["xurl_available"])++ def test_x_backend_chain_local_only_never_calls_live_check(self):+ with mock.patch(+ "lib.xurl_x.is_available",+ side_effect=AssertionError("local_only chain must not run `xurl whoami`"),+ ), mock.patch("lib.xurl_x.has_stored_auth", return_value=True):+ chain = env.x_backend_chain({}, local_only=True)+ self.assertEqual(["xurl"], chain)++ def test_x_backend_chain_default_stays_live(self):+ with mock.patch("lib.xurl_x.is_available", return_value=True), \+ mock.patch(+ "lib.xurl_x.has_stored_auth",+ side_effect=AssertionError("default chain should use the live check"),+ ):+ chain = env.x_backend_chain({})+ self.assertEqual(["xurl"], chain)++class ThreadsAvailabilityTests(unittest.TestCase):"""Threads is in the SC default-on family: same key, same per-call costshape as TikTok / Instagram, so the same default-on rule applies.diff --git a/tests/test_health_probe_taxonomy.py b/tests/test_health_probe_taxonomy.pynew file mode 100644index 00000000..b9cfe980--- /dev/null+++ b/tests/test_health_probe_taxonomy.py@@ -0,0 +1,326 @@+"""Tests for the uniform dependency-probe taxonomy in scripts/lib/health.py.++Covers the doctor-command probe layer (issue #692 class): every probed external+dependency (yt-dlp, Printing Press CLIs, node, ffmpeg) must report+ok | missing | broken | timeout with a package-manager-aware prescription.+The stale-shim false negative — shutil.which resolves a binary that cannot+exec — must classify as ``broken`` with a *reinstall* prescription, never as+available.+"""++from __future__ import annotations++import os+import stat+import subprocess+from pathlib import Path+from unittest import mock++import pytest++from lib import health++[email protected](autouse=True)+def _fresh_probe_cache():+ """Probes memoize per process; isolate every test."""+ health.clear_dependency_probe_cache()+ yield+ health.clear_dependency_probe_cache()+++def _which_map(mapping):+ """shutil.which side_effect resolving only the names in ``mapping``."""+ def _which(name, *args, **kwargs):+ return mapping.get(name)+ return _which+++def _completed(rc=0, stdout="", stderr=""):+ return subprocess.CompletedProcess(args=["x"], returncode=rc, stdout=stdout, stderr=stderr)+++class TestMissing:+ """Scenario 1: binary absent from PATH -> missing + installer prescription."""++ def test_ytdlp_missing_brew_prescription(self):+ with mock.patch.object(health.shutil, "which", side_effect=_which_map({"brew": "/opt/homebrew/bin/brew"})), \+ mock.patch.object(health, "_off_path_candidate_dirs", return_value=[]):+ probe = health.probe_dependency("yt-dlp")+ assert probe.status == health.MISSING+ assert probe.off_path is False # genuinely absent, not merely off-PATH+ assert probe.prescription == "brew install yt-dlp"+ assert probe.owner_pkg_manager == "brew"+ assert "not found on PATH" in probe.detail++ def test_ytdlp_missing_pipx_prescription_when_no_brew(self):+ with mock.patch.object(health.shutil, "which", side_effect=_which_map({"pipx": "/usr/local/bin/pipx"})), \+ mock.patch.object(health, "_off_path_candidate_dirs", return_value=[]):+ probe = health.probe_dependency("yt-dlp")+ assert probe.status == health.MISSING+ assert probe.prescription == "pipx install yt-dlp"+ assert probe.owner_pkg_manager == "pipx"++ def test_pp_cli_missing_prescribes_printing_press_install(self):+ with mock.patch.object(health.shutil, "which", side_effect=_which_map({})), \+ mock.patch.object(health, "_off_path_candidate_dirs", return_value=[]):+ probe = health.probe_dependency("digg-pp-cli")+ assert probe.status == health.MISSING+ assert "printing-press-library" in probe.prescription+ assert "install digg --cli-only" in probe.prescription+ assert probe.owner_pkg_manager == "npx"++ def test_node_missing_nvm_prescription_when_no_brew(self, monkeypatch, tmp_path):+ monkeypatch.setenv("NVM_DIR", str(tmp_path))+ with mock.patch.object(health.shutil, "which", side_effect=_which_map({})), \+ mock.patch.object(health, "_off_path_candidate_dirs", return_value=[]):+ probe = health.probe_dependency("node")+ assert probe.status == health.MISSING+ assert "nvm install" in probe.prescription+ assert probe.owner_pkg_manager == "nvm"++ def test_ffmpeg_missing_apt_prescription_when_no_brew(self):+ with mock.patch.object(health.shutil, "which", side_effect=_which_map({"apt-get": "/usr/bin/apt-get"})), \+ mock.patch.object(health, "_off_path_candidate_dirs", return_value=[]):+ probe = health.probe_dependency("ffmpeg")+ assert probe.status == health.MISSING+ assert "apt-get install" in probe.prescription+ assert probe.owner_pkg_manager == "apt"++ def test_missing_with_no_manager_still_prescribes_something(self, monkeypatch):+ monkeypatch.delenv("NVM_DIR", raising=False)+ with mock.patch.object(health.shutil, "which", side_effect=_which_map({})), \+ mock.patch.object(health, "_nvm_present", return_value=False), \+ mock.patch.object(health, "_off_path_candidate_dirs", return_value=[]):+ probe = health.probe_dependency("yt-dlp")+ assert probe.status == health.MISSING+ assert probe.prescription # never an empty prescription for missing+ assert probe.owner_pkg_manager == ""+++class TestBroken:+ """Scenario 2: which resolves but exec fails -> broken + REINSTALL prescription."""++ def test_stale_shim_exec_oserror_is_broken_not_ok(self):+ with mock.patch.object(health.shutil, "which", side_effect=_which_map({"yt-dlp": "/x/yt-dlp", "brew": "/x/brew"})), \+ mock.patch.object(health.subprocess, "run", side_effect=OSError("exec format error")):+ probe = health.probe_dependency("yt-dlp")+ assert probe.status == health.BROKEN+ assert probe.prescription == "brew reinstall yt-dlp"+ assert "reinstall" in probe.prescription.lower()++ def test_nonzero_version_exit_is_broken(self):+ fake = _completed(rc=1, stderr="ModuleNotFoundError: No module named 'yt_dlp'")+ with mock.patch.object(health.shutil, "which", side_effect=_which_map({"yt-dlp": "/x/yt-dlp", "brew": "/x/brew"})), \+ mock.patch.object(health.subprocess, "run", return_value=fake):+ probe = health.probe_dependency("yt-dlp")+ assert probe.status == health.BROKEN+ assert "ModuleNotFoundError" in probe.detail+ assert "reinstall" in probe.prescription.lower()++ def test_broken_pp_cli_prescribes_rerunning_install(self):+ with mock.patch.object(health.shutil, "which", side_effect=_which_map({"digg-pp-cli": "/x/digg-pp-cli"})), \+ mock.patch.object(health.subprocess, "run", side_effect=OSError("bad exec")):+ probe = health.probe_dependency("digg-pp-cli")+ assert probe.status == health.BROKEN+ assert "printing-press-library" in probe.prescription+ assert "install digg --cli-only" in probe.prescription++ def test_real_stale_shim_on_disk(self, tmp_path, monkeypatch):+ """Integration: a real file whose shebang interpreter is gone (#692)."""+ shim = tmp_path / "fake-pp-cli"+ shim.write_text("#!/nonexistent-interpreter/python3\nprint('hi')\n")+ shim.chmod(shim.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)+ monkeypatch.setenv("PATH", str(tmp_path))+ probe = health.probe_dependency("fake-pp-cli")+ assert probe.status == health.BROKEN+ fix = probe.prescription.lower()+ assert "reinstall" in fix or "re-run" in fix+++class TestTimeout:+ """Scenario 3: slow probe -> timeout, distinct message, bounded budget."""++ def test_timeout_status_and_message(self):+ with mock.patch.object(health.shutil, "which", side_effect=_which_map({"ffmpeg": "/x/ffmpeg", "brew": "/x/brew"})), \+ mock.patch.object(+ health.subprocess, "run",+ side_effect=subprocess.TimeoutExpired(cmd=["ffmpeg"], timeout=health.PROBE_TIMEOUT),+ ):+ probe = health.probe_dependency("ffmpeg")+ assert probe.status == health.TIMEOUT+ assert "timed out" in probe.detail++ def test_probe_budget_is_bounded(self):+ with mock.patch.object(health.shutil, "which", side_effect=_which_map({"node": "/x/node", "brew": "/x/brew"})), \+ mock.patch.object(health.subprocess, "run", return_value=_completed(stdout="v22.1.0")) as run:+ health.probe_dependency("node")+ assert run.call_args.kwargs["timeout"] <= health.PROBE_TIMEOUT+++class TestOk:+ """Scenario 4: healthy binary -> ok, no prescription."""++ def test_healthy_binary_ok_no_prescription(self):+ with mock.patch.object(health.shutil, "which", side_effect=_which_map({"yt-dlp": "/x/yt-dlp", "brew": "/x/brew"})), \+ mock.patch.object(health.subprocess, "run", return_value=_completed(stdout="2026.06.09\n")):+ probe = health.probe_dependency("yt-dlp")+ assert probe.status == health.OK+ assert probe.ok+ assert probe.prescription == ""+ assert "2026.06.09" in probe.detail++ def test_real_healthy_binary_end_to_end(self, tmp_path, monkeypatch):+ """Integration: a real executable on a real PATH, no mocks."""+ binary = tmp_path / "fake-pp-cli"+ binary.write_text("#!/bin/sh\necho 1.2.3\n")+ binary.chmod(binary.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)+ monkeypatch.setenv("PATH", f"{tmp_path}{os.pathsep}/bin{os.pathsep}/usr/bin")+ probe = health.probe_dependency("fake-pp-cli")+ assert probe.status == health.OK+ assert "1.2.3" in probe.detail+ assert probe.prescription == ""+++class TestOffPath:+ """Scenario 5: on disk but off PATH -> missing + PATH-fix, never ok."""++ def test_off_path_binary_is_missing_with_path_fix(self, tmp_path):+ binary = tmp_path / "digg-pp-cli"+ binary.write_text("#!/bin/sh\necho ok\n")+ binary.chmod(binary.stat().st_mode | stat.S_IXUSR)+ with mock.patch.object(health.shutil, "which", side_effect=_which_map({"npx": "/x/npx"})), \+ mock.patch.object(health, "_off_path_candidate_dirs", return_value=[tmp_path]):+ probe = health.probe_dependency("digg-pp-cli")+ assert probe.status == health.MISSING+ assert probe.off_path is True+ assert "PATH" in probe.prescription+ assert str(tmp_path) in probe.prescription or "$HOME" in probe.prescription+ assert str(binary) in probe.detail or "$HOME" in probe.detail++ def test_off_path_never_reports_ok(self, tmp_path):+ binary = tmp_path / "yt-dlp"+ binary.write_text("#!/bin/sh\necho 2026.06.09\n")+ binary.chmod(binary.stat().st_mode | stat.S_IXUSR)+ with mock.patch.object(health.shutil, "which", side_effect=_which_map({"brew": "/x/brew"})), \+ mock.patch.object(health, "_off_path_candidate_dirs", return_value=[tmp_path]):+ probe = health.probe_dependency("yt-dlp")+ assert probe.status != health.OK+ assert not probe.ok+++class TestCachingAndRegistry:+ """Probes are memoized per process; the registry covers all doctor deps."""++ def test_probe_memoized_single_subprocess(self):+ with mock.patch.object(health.shutil, "which", side_effect=_which_map({"node": "/x/node", "brew": "/x/brew"})), \+ mock.patch.object(health.subprocess, "run", return_value=_completed(stdout="v22.1.0")) as run:+ first = health.probe_dependency("node")+ second = health.probe_dependency("node")+ assert run.call_count == 1+ assert first is second++ def test_clear_cache_reprobes(self):+ with mock.patch.object(health.shutil, "which", side_effect=_which_map({"node": "/x/node", "brew": "/x/brew"})), \+ mock.patch.object(health.subprocess, "run", return_value=_completed(stdout="v22.1.0")) as run:+ health.probe_dependency("node")+ health.clear_dependency_probe_cache()+ health.probe_dependency("node")+ assert run.call_count == 2++ def test_probe_dependencies_covers_known_set(self):+ with mock.patch.object(health.shutil, "which", side_effect=_which_map({})), \+ mock.patch.object(health, "_off_path_candidate_dirs", return_value=[]):+ probes = health.probe_dependencies()+ assert set(probes) == set(health.KNOWN_DEPENDENCIES)+ assert {"yt-dlp", "digg-pp-cli", "node", "ffmpeg"} <= set(probes)+ for probe in probes.values():+ assert probe.status == health.MISSING+ assert probe.prescription++ def test_any_pp_cli_name_gets_printing_press_prescription(self):+ with mock.patch.object(health.shutil, "which", side_effect=_which_map({})), \+ mock.patch.object(health, "_off_path_candidate_dirs", return_value=[]):+ probe = health.probe_dependency("espn-pp-cli")+ assert probe.status == health.MISSING+ assert "install espn --cli-only" in probe.prescription+ assert probe.owner_pkg_manager == "npx"+++class TestWindowsPrintingPressCandidates:+ """F15 regression (docs/solutions/integration-issues/+ digg-cli-agent-path-setup-wizard.md): the Windows managed install dir+ (%LOCALAPPDATA%/Programs/PrintingPress/bin) must be in the shared+ candidate-dir source so an installed-but-off-PATH digg-pp-cli gets a+ PATH fix, never "never installed".++ os.name is patched only in health's namespace (a delegating stub) —+ patching the global os.name would flip pathlib to WindowsPath and break+ Path construction on posix.+ """++ class _NtOs:+ """Delegates to the real os module but reports name == 'nt'."""+ name = "nt"++ def __getattr__(self, attr):+ return getattr(os, attr)++ def _nt(self):+ return mock.patch.object(health, "os", self._NtOs())++ def test_windows_dir_in_candidates_when_localappdata_set(self, tmp_path):+ with self._nt(), \+ mock.patch.dict(os.environ, {"LOCALAPPDATA": str(tmp_path)}):+ dirs = health._off_path_candidate_dirs()+ assert tmp_path / "Programs" / "PrintingPress" / "bin" in dirs++ def test_windows_dir_absent_without_localappdata(self):+ env_clean = {k: v for k, v in os.environ.items()+ if k.lower() != "localappdata"}+ with self._nt(), \+ mock.patch.dict(os.environ, env_clean, clear=True):+ assert health.windows_printing_press_bin_dir() is None++ def test_posix_has_no_windows_dir(self, tmp_path):+ with mock.patch.dict(os.environ, {"LOCALAPPDATA": str(tmp_path)}):+ assert health.windows_printing_press_bin_dir() is None++ def test_windows_off_path_digg_reports_path_fix(self, tmp_path):+ # Binary present ONLY in the PrintingPress dir: missing + off_path ++ # PATH prescription — the documented failure mode said "never installed".+ pp_dir = tmp_path / "Programs" / "PrintingPress" / "bin"+ pp_dir.mkdir(parents=True)+ binary = pp_dir / "digg-pp-cli.exe"+ binary.write_text("#!/bin/sh\necho ok\n")+ binary.chmod(binary.stat().st_mode | stat.S_IXUSR)+ fake_home = tmp_path / "home"+ with self._nt(), \+ mock.patch.dict(os.environ,+ {"LOCALAPPDATA": str(tmp_path),+ "GOPATH": str(tmp_path / "gopath")}), \+ mock.patch.object(health.Path, "home", return_value=fake_home), \+ mock.patch.object(health.shutil, "which",+ side_effect=_which_map({"npx": "/x/npx"})):+ probe = health.probe_dependency("digg-pp-cli")+ assert probe.status == health.MISSING+ assert probe.off_path is True+ assert "PATH" in probe.prescription+ assert str(pp_dir) in probe.prescription or str(pp_dir) in probe.detail++ def test_setup_wizard_digg_candidates_derive_from_shared_dirs(self, tmp_path):+ # setup_wizard appends the Digg filename variants to the SAME shared+ # dir list health owns — including the .exe in the Windows managed dir.+ from lib import setup_wizard++ with self._nt(), \+ mock.patch.dict(os.environ, {"LOCALAPPDATA": str(tmp_path)}):+ shared = health.installer_bin_dirs()+ candidates = setup_wizard._digg_bin_candidate_paths()+ pp_dir = tmp_path / "Programs" / "PrintingPress" / "bin"+ assert pp_dir in shared+ assert [c.parent for c in candidates] == shared+ assert pp_dir / "digg-pp-cli.exe" in candidates+ for candidate in candidates:+ if candidate.parent != pp_dir:+ assert candidate.name == "digg-pp-cli"diff --git a/tests/test_prescriptions.py b/tests/test_prescriptions.pynew file mode 100644index 00000000..33c4dd08--- /dev/null+++ b/tests/test_prescriptions.py@@ -0,0 +1,347 @@+"""Tests for the fix-prescription registry (doctor plan U3, KTD 7).++One registry maps (source, failure mode) to its remediation in BOTH+natural-language and direct-CLI forms. Consumers: the doctor command (U4)+and lib/quality_nudge.py, which builds its fix text from the same entries+so the two surfaces cannot drift.+"""++import re+from pathlib import Path+from unittest.mock import patch++import pytest++from lib import health, prescriptions+++REPO_ROOT = Path(__file__).resolve().parent.parent+CONFIGURATION_MD = REPO_ROOT / "CONFIGURATION.md"++# A CLI fix must start with a runnable token: the engine invocation, an env+# assignment (optionally exported), or a documented binary name.+RUNNABLE = re.compile(+ r"^(?:python3 \S*last30days\.py\b"+ r"|[A-Z][A-Z0-9_]*="+ r"|export [A-Z][A-Z0-9_]*="+ r"|(?:brew|pipx|pip|scoop|npx|npm|xurl|yt-dlp|docker) )"+)++# The seed failure inventory from the plan (U3 approach section).+SEED_INVENTORY = {+ ("x", "cookies_missing"),+ ("x", "cookies_expired"),+ ("scrapecreators", "key_missing"),+ ("bluesky", "app_password_missing"),+ ("youtube", "transcription_key_missing"),+ ("digg", "pp_cli_missing"),+ ("digg", "pp_cli_off_path"),+ ("digg", "pp_cli_broken"),+ ("youtube", "ytdlp_missing"),+ ("youtube", "ytdlp_stale"),+ ("youtube", "ytdlp_broken"),+ ("truthsocial", "token_missing"),+ ("xiaohongshu", "service_unreachable"),+}+++def _configuration_md_slugs():+ """GitHub-style anchor slugs for every CONFIGURATION.md heading."""+ slugs = set()+ for line in CONFIGURATION_MD.read_text(encoding="utf-8").splitlines():+ m = re.match(r"#{1,6}\s+(.*)", line)+ if not m:+ continue+ text = re.sub(r"[^\w\s-]", "", m.group(1).lower()).strip()+ slugs.add(text.replace(" ", "-"))+ return slugs+++# ---------------------------------------------------------------------------+# Scenario 1: completeness lint over every registered entry+# ---------------------------------------------------------------------------++class TestCompletenessLint:+ def test_seed_inventory_is_registered(self):+ assert SEED_INVENTORY <= set(prescriptions.REGISTRY)++ def test_every_entry_has_cause_and_both_fix_forms(self):+ for key, entry in prescriptions.REGISTRY.items():+ assert entry.cause.strip(), f"{key}: empty cause"+ assert entry.fix_nl.strip(), f"{key}: empty natural-language fix"+ assert entry.fix_cli.strip(), f"{key}: empty CLI fix"++ def test_every_cli_form_starts_with_a_runnable_token(self):+ for key, entry in prescriptions.REGISTRY.items():+ for cli in (entry.fix_cli, *entry.alt_cli):+ assert RUNNABLE.match(cli), f"{key}: not runnable: {cli!r}"++ def test_nl_fix_never_duplicates_the_cli_string_verbatim(self):+ for key, entry in prescriptions.REGISTRY.items():+ assert entry.fix_nl.strip() != entry.fix_cli.strip(), key++ def test_registry_keys_match_entry_fields(self):+ for (source, failure), entry in prescriptions.REGISTRY.items():+ assert entry.source == source+ assert entry.failure == failure++ def test_anchors_point_at_real_configuration_md_headings(self):+ slugs = _configuration_md_slugs()+ for key, entry in prescriptions.REGISTRY.items():+ if entry.anchor:+ assert entry.anchor in slugs, (+ f"{key}: anchor #{entry.anchor} not a CONFIGURATION.md heading"+ )++ def test_no_secret_looking_values(self):+ """Placeholders only - no copy-pasteable live credentials."""+ secretish = re.compile(r"(sk-[A-Za-z0-9]{16,}|gsk_[A-Za-z0-9]{16,}|xox[bap]-)")+ for key, entry in prescriptions.REGISTRY.items():+ blob = " ".join((entry.cause, entry.fix_nl, entry.fix_cli, *entry.alt_cli))+ assert not secretish.search(blob), key+++# ---------------------------------------------------------------------------+# Documented CLI forms for the flagship entries+# ---------------------------------------------------------------------------++class TestDocumentedCliForms:+ def test_x_cookie_fixes_use_setup_with_browser_cookie_consent(self):+ expected = "python3 skills/last30days/scripts/last30days.py setup --allow-browser-cookies"+ assert prescriptions.get("x", "cookies_missing").fix_cli == expected+ assert prescriptions.get("x", "cookies_expired").fix_cli == expected++ def test_scrapecreators_fix_is_the_github_device_flow(self):+ entry = prescriptions.get("scrapecreators", "key_missing")+ assert entry.fix_cli == "python3 skills/last30days/scripts/last30days.py setup --github"++ def test_ytdlp_install_and_reinstall_reference_u1_health_strings(self):+ """Binary-class fixes reference U1's tables instead of restating them."""+ install, reinstall = health._MANAGER_PRESCRIPTIONS["yt-dlp"]["brew"]+ assert prescriptions.get("youtube", "ytdlp_missing").fix_cli == install+ assert prescriptions.get("youtube", "ytdlp_broken").fix_cli == reinstall++ def test_digg_install_references_u1_printing_press_command(self):+ entry = prescriptions.get("digg", "pp_cli_missing")+ assert entry.fix_cli == health._pp_install_cmd("digg-pp-cli")+++# ---------------------------------------------------------------------------+# Scenario 2: quality_nudge text derives from the same registry entries+# ---------------------------------------------------------------------------++def _nudge(config_overrides=None, result_overrides=None, ytdlp_installed=False):+ from lib.quality_nudge import compute_quality_score+ from lib import youtube_yt++ config = {+ "AUTH_TOKEN": None,+ "CT0": None,+ "XAI_API_KEY": None,+ "XQUIK_API_KEY": None,+ "SCRAPECREATORS_API_KEY": None,+ }+ config.update(config_overrides or {})+ results = {"x_error": None, "youtube_error": None, "reddit_error": None}+ results.update(result_overrides or {})+ with patch.object(youtube_yt, "is_ytdlp_installed", return_value=ytdlp_installed):+ return compute_quality_score(config, results)+++class TestSharedWithQualityNudge:+ def test_x_cookie_expired_nudge_is_built_from_the_registry_entry(self):+ entry = prescriptions.get("x", "cookies_expired")+ q = _nudge(+ config_overrides={"AUTH_TOKEN": "tok123"},+ result_overrides={"x_error": "401 unauthorized"},+ ytdlp_installed=True,+ )+ assert q["nudge_text"] is not None+ assert entry.fix_nl in q["nudge_text"]++ def test_x_cookie_missing_nudge_is_built_from_the_registry_entry(self):+ entry = prescriptions.get("x", "cookies_missing")+ q = _nudge(ytdlp_installed=True)+ assert entry.fix_nl in q["nudge_text"]++ def test_ytdlp_missing_nudge_uses_registry_cli(self):+ entry = prescriptions.get("youtube", "ytdlp_missing")+ q = _nudge(config_overrides={"AUTH_TOKEN": "tok123"}, ytdlp_installed=False)+ assert entry.fix_cli in q["nudge_text"]++ def test_ytdlp_stale_degraded_nudge_uses_registry_cli_forms(self):+ entry = prescriptions.get("youtube", "ytdlp_stale")+ q = _nudge(+ config_overrides={"AUTH_TOKEN": "tok123"},+ ytdlp_installed=True,+ result_overrides={+ "youtube_videos_count": 6,+ "youtube_transcripts_count": 0,+ },+ )+ assert entry.fix_cli in q["nudge_text"]+ for alt in entry.alt_cli:+ assert alt in q["nudge_text"]++ def test_quality_nudge_source_no_longer_hardcodes_fix_strings(self):+ """The migrated fix strings must live in the registry only.++ Trigger logic legitimately still reads credential names (e.g.+ ``config.get("XAI_API_KEY")``); this guards the FIX text.+ """+ source = (+ REPO_ROOT / "skills/last30days/scripts/lib/quality_nudge.py"+ ).read_text(encoding="utf-8")+ assert "brew " not in source+ assert "api.x.ai" not in source+ assert "log into x.com" not in source+ assert "yt-dlp: brew" not in source+++# ---------------------------------------------------------------------------+# Scenario 3: unregistered failure -> generic fallback, no crash+# ---------------------------------------------------------------------------++class TestFallback:+ def test_lookup_returns_none_for_unregistered(self):+ assert prescriptions.lookup("linkedin", "flux_capacitor_missing") is None++ def test_get_returns_generic_configuration_md_pointer(self):+ entry = prescriptions.get("linkedin", "flux_capacitor_missing")+ assert "CONFIGURATION.md" in entry.fix_nl+ assert RUNNABLE.match(entry.fix_cli)+ assert entry.source == "linkedin"+ assert entry.failure == "flux_capacitor_missing"++ def test_get_returns_registered_entry_when_present(self):+ assert prescriptions.get("x", "cookies_missing") is prescriptions.REGISTRY[+ ("x", "cookies_missing")+ ]+++# ---------------------------------------------------------------------------+# Composition with U1 dependency probes (health.DependencyProbe)+# ---------------------------------------------------------------------------++class TestDependencyProbeComposition:+ def test_ok_probe_needs_no_prescription(self):+ probe = health.DependencyProbe(name="yt-dlp", status=health.OK, detail="2026.06.01")+ assert prescriptions.for_dependency_probe(probe) is None++ def test_probe_prescription_wins_the_cli_form(self):+ """U1's machine-aware string (pipx owner here) overrides the static CLI."""+ probe = health.DependencyProbe(+ name="yt-dlp",+ status=health.BROKEN,+ detail="yt-dlp resolves to /x/yt-dlp but won't execute: stale shim",+ prescription="pipx reinstall yt-dlp",+ )+ entry = prescriptions.for_dependency_probe(probe)+ assert entry is not None+ assert entry.fix_cli == "pipx reinstall yt-dlp"+ # Registry vocabulary (NL form) is retained.+ assert entry.fix_nl == prescriptions.get("youtube", "ytdlp_broken").fix_nl++ def test_digg_off_path_probe_maps_to_the_path_entry(self):+ probe = health.DependencyProbe(+ name="digg-pp-cli",+ status=health.MISSING,+ detail=(+ "digg-pp-cli is installed at /home/u/.local/bin/digg-pp-cli but "+ "that directory is not on this process's PATH"+ ),+ prescription='add $HOME/.local/bin to PATH (e.g. export PATH="$HOME/.local/bin:$PATH") so digg-pp-cli resolves',+ off_path=True,+ )+ entry = prescriptions.for_dependency_probe(probe)+ assert entry is not None+ assert entry.failure == "pp_cli_off_path"++ def test_digg_broken_probe_maps_to_the_reinstall_entry(self):+ """An installed-but-broken digg binary must get reinstall-framed+ text, never the never-installed "install it" entry (F6); the+ probe's own prescription wins the CLI form, mirroring+ test_probe_prescription_wins_the_cli_form."""+ reinstall = f"re-run the Printing Press install: {health.pp_install_cmd('digg')}"+ probe = health.DependencyProbe(+ name="digg-pp-cli",+ status=health.BROKEN,+ detail=(+ "digg-pp-cli resolves to /home/u/.local/bin/digg-pp-cli "+ "but won't execute"+ ),+ prescription=reinstall,+ )+ entry = prescriptions.for_dependency_probe(probe)+ assert entry is not None+ assert entry.failure == "pp_cli_broken"+ assert entry.fix_cli == reinstall+ # Registry vocabulary (NL form) is retained and reinstall-framed.+ assert entry.fix_nl == prescriptions.get("digg", "pp_cli_broken").fix_nl+ assert "reinstall" in entry.fix_nl+ assert entry.fix_nl != prescriptions.get("digg", "pp_cli_missing").fix_nl++ def test_digg_timeout_probe_also_maps_to_the_reinstall_entry(self):+ probe = health.DependencyProbe(+ name="digg-pp-cli",+ status=health.TIMEOUT,+ detail="digg-pp-cli --version timed out",+ prescription="reinstall digg-pp-cli",+ )+ entry = prescriptions.for_dependency_probe(probe)+ assert entry is not None+ assert entry.failure == "pp_cli_broken"++ def test_unregistered_dependency_wraps_the_probe(self):+ probe = health.DependencyProbe(+ name="ffmpeg",+ status=health.MISSING,+ detail="ffmpeg not found on PATH",+ prescription="brew install ffmpeg",+ )+ entry = prescriptions.for_dependency_probe(probe)+ assert entry is not None+ assert entry.fix_cli == "brew install ffmpeg"+ assert entry.fix_nl # still has a natural-language form+++# ---------------------------------------------------------------------------+# Composition with U2 backend findings (lib/backends.py)+# ---------------------------------------------------------------------------++class TestBackendComposition:+ def test_bird_cookie_prescription_embeds_the_registry_cli(self):+ from lib import backends, bird_x++ entry = prescriptions.get("x", "cookies_missing")+ ok_node = health.DependencyProbe(name="node", status=health.OK, detail="v22.0.0")+ with patch.object(bird_x, "is_bird_installed", return_value=True), \+ patch.object(health, "probe_dependency", return_value=ok_node):+ finding = backends._X_PROBES["bird"]({})+ assert finding.status == health.MISSING+ assert entry.fix_cli in finding.prescription++ def test_scrapecreators_prescription_embeds_the_registry_cli(self):+ from lib import backends++ entry = prescriptions.get("scrapecreators", "key_missing")+ finding = backends._SC_SPEC.probe({})+ assert finding.status == health.MISSING+ assert entry.fix_cli in finding.prescription+ # test_backend_descriptors requires the key name to stay present.+ assert "SCRAPECREATORS_API_KEY" in finding.prescription+++class TestAltCliArityPin:+ """Greptile PR review: quality_nudge composes YouTube nudges from the two+ platform alternates on the ytdlp entries. The consumer is now tolerant of+ any arity (degrades wording instead of crashing), and this pin keeps the+ wording rich: both entries must keep at least the scoop + pip alternates."""++ @pytest.mark.parametrize("failure", ["ytdlp_missing", "ytdlp_stale"])+ def test_ytdlp_entries_keep_two_platform_alternates(self, failure):+ entry = prescriptions.get("youtube", failure)+ assert len(entry.alt_cli) >= 2, (+ f"youtube/{failure} lost a platform alternate; quality_nudge "+ "wording degrades (tolerant, but fix the entry or the prose)"+ )diff --git a/tests/test_reddit_dispatch.py b/tests/test_reddit_dispatch.pyindex 073d2336..50522ca1 100644--- a/tests/test_reddit_dispatch.py+++ b/tests/test_reddit_dispatch.py@@ -3,7 +3,9 @@ that the keyless path never calls search.json (U2)."""from unittest import mock-from lib import pipeline, reddit_keyless, schema+from pathlib import Path++from lib import env, pipeline, reddit_keyless, schemadef _subquery():@@ -107,3 +109,44 @@ class TestNoSearchJson:mock.patch("lib.reddit_keyless.reddit_listing.fetch_listings", return_value=[]):reddit_keyless._discover("topic", "default", ["test"])json_search.assert_not_called()+++class TestEnvConstantParity:+ """F2 regression (restate-as-mirror drift): pipeline's Reddit gating must+ key off env's declared constants (env.REDDIT_BACKEND_PIN_VAR /+ env.REDDIT_SC_MIN_ITEMS_VAR) — never restated raw strings that can drift+ from the single source of truth in lib/env.py."""++ def _run(self, config, public, sc_parsed):+ with mock.patch("lib.reddit_public.search_reddit_public",+ return_value=public) as pub, \+ mock.patch("lib.reddit.search_and_enrich", return_value={"raw": 1}) as sc, \+ mock.patch("lib.reddit.parse_reddit_response", return_value=sc_parsed):+ items, _ = pipeline._retrieve_stream(+ topic="kanye", subquery=_subquery(), source="reddit", config=config,+ depth="quick", date_range=("2026-05-26", "2026-06-25"),+ runtime=_runtime(), mock=False,+ )+ return items, pub, sc++ def test_pipeline_source_has_no_raw_reddit_env_literals(self):+ # The declared constants live in env.py; pipeline.py must not restate+ # the raw LAST30DAYS_REDDIT_* strings (comments included — they drift too).+ source = Path(pipeline.__file__).read_text()+ assert "LAST30DAYS_REDDIT_" not in source++ def test_backend_pin_constant_flips_gating_to_sc_primary(self):+ # Keyed via the env constant, not a raw string: pin=scrapecreators+ # makes SC primary and skips the free path entirely.+ cfg = {"SCRAPECREATORS_API_KEY": "k", env.REDDIT_BACKEND_PIN_VAR: "scrapecreators"}+ items, pub, sc = self._run(cfg, [_item("a")], [_item("z")])+ sc.assert_called_once()+ pub.assert_not_called()+ assert _ids(items) == ["z"]++ def test_min_items_constant_drives_thinness_backfill(self):+ # Keyed via the env constant: floor of 5 vs 1 free item -> SC backfill.+ cfg = {"SCRAPECREATORS_API_KEY": "k", env.REDDIT_SC_MIN_ITEMS_VAR: "5"}+ items, pub, sc = self._run(cfg, [_item("a")], [_item("z")])+ sc.assert_called_once()+ assert _ids(items) == ["a", "z"]diff --git a/tests/test_xurl_x.py b/tests/test_xurl_x.pyindex d79673d1..46258615 100644--- a/tests/test_xurl_x.py+++ b/tests/test_xurl_x.py@@ -1,7 +1,9 @@"""Tests for xurl_x module."""import json+import tempfileimport unittest+from pathlib import Pathfrom unittest import mockfrom lib import xurl_x@@ -26,6 +28,11 @@ def _make_api_response(tweets=None, users=None):class TestIsAvailable(unittest.TestCase):+ def setUp(self):+ # is_available() memoizes per process; isolate every test.+ xurl_x.clear_availability_cache()+ self.addCleanup(xurl_x.clear_availability_cache)+def test_returns_true_when_xurl_authenticated(self):completed = mock.Mock(returncode=0, stdout='{"username": "testuser"}')with mock.patch("subprocess.run", return_value=completed):@@ -58,6 +65,106 @@ class TestIsAvailable(unittest.TestCase):with mock.patch("subprocess.run", return_value=completed):self.assertFalse(xurl_x.is_available())+# ---------------------------------------------------------------------------+# stored_auth_status / has_stored_auth (local-only doctor-path evidence)+# ---------------------------------------------------------------------------+++class _UnreadableStore:+ """Path stub: exists but every read raises (permission-denied store)."""++ def is_file(self):+ return True++ def read_text(self, *args, **kwargs):+ raise PermissionError(13, "Permission denied")++ def __str__(self):+ return "/home/user/.xurl"+++class TestStoredAuth(unittest.TestCase):+ """F1/F10: the doctor path keys on xurl's on-disk token store (~/.xurl)+ instead of the live `xurl whoami` network call. These tests forbid+ subprocess entirely — local evidence must never spawn anything."""++ def setUp(self):+ self._tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self._tmp.cleanup)+ self.store = Path(self._tmp.name) / ".xurl"+ boom = mock.patch(+ "subprocess.run",+ side_effect=AssertionError("local auth evidence must not spawn a subprocess"),+ )+ boom.start()+ self.addCleanup(boom.stop)++ def _status(self, path=None):+ with mock.patch("lib.xurl_x.token_store_path", return_value=path or self.store):+ return xurl_x.stored_auth_status()++ def test_yaml_store_with_access_token_is_ok(self):+ self.store.write_text(+ "apps:\n app:\n oauth2_tokens:\n me:\n oauth2:\n"+ " access_token: dummy-not-real\n",+ encoding="utf-8",+ )+ status, detail = self._status()+ self.assertEqual(xurl_x.AUTH_OK, status)+ self.assertIn(str(self.store), detail)++ def test_legacy_json_store_with_bearer_token_is_ok(self):+ self.store.write_text(+ json.dumps({"bearer_token": {"bearer": "dummy-not-real"}}),+ encoding="utf-8",+ )+ status, _ = self._status()+ self.assertEqual(xurl_x.AUTH_OK, status)++ def test_absent_store_is_missing(self):+ status, detail = self._status()+ self.assertEqual(xurl_x.AUTH_MISSING, status)+ self.assertIn("no token store", detail)++ def test_empty_store_is_missing(self):+ self.store.write_text("", encoding="utf-8")+ status, _ = self._status()+ self.assertEqual(xurl_x.AUTH_MISSING, status)++ def test_store_without_credential_markers_is_missing(self):+ self.store.write_text("apps: {}\ndefault_app: app\n", encoding="utf-8")+ status, detail = self._status()+ self.assertEqual(xurl_x.AUTH_MISSING, status)+ self.assertIn("no stored credentials", detail)++ def test_unreadable_store_is_error_not_missing(self):+ status, detail = self._status(path=_UnreadableStore())+ self.assertEqual(xurl_x.AUTH_ERROR, status)+ self.assertIn("unreadable", detail)+ self.assertIn("PermissionError", detail)++ def test_has_stored_auth_true_with_binary_and_store(self):+ self.store.write_text("access_token: dummy-not-real\n", encoding="utf-8")+ with mock.patch("lib.xurl_x.token_store_path", return_value=self.store), \+ mock.patch("lib.xurl_x.shutil.which", return_value="/usr/local/bin/xurl"):+ self.assertTrue(xurl_x.has_stored_auth())++ def test_has_stored_auth_false_without_binary(self):+ self.store.write_text("access_token: dummy-not-real\n", encoding="utf-8")+ with mock.patch("lib.xurl_x.token_store_path", return_value=self.store), \+ mock.patch("lib.xurl_x.shutil.which", return_value=None):+ self.assertFalse(xurl_x.has_stored_auth())++ def test_has_stored_auth_false_on_broken_store(self):+ # has_stored_auth answers availability only; the typed ERROR surface+ # lives in backends._probe_xurl (see test_backend_descriptors).+ with mock.patch("lib.xurl_x.token_store_path", return_value=_UnreadableStore()), \+ mock.patch("lib.xurl_x.shutil.which", return_value="/usr/local/bin/xurl"):+ self.assertFalse(xurl_x.has_stored_auth())++ def test_default_store_path_is_home_dot_xurl(self):+ self.assertEqual(Path.home() / ".xurl", xurl_x.token_store_path())+# ---------------------------------------------------------------------------# search_x# ---------------------------------------------------------------------------