返回 last30days-skill
prescriptions.py
根目录 / skills / last30days / scripts / lib / prescriptions.py
1 """Fix-prescription registry: the single remediation vocabulary (KTD 7).
2
3 Each (source, failure mode) entry carries a cause line, a natural-language
4 fix, an exact CLI fix, and an optional CONFIGURATION.md anchor. Two real
5 consumers keep the vocabulary honest from day one:
6
7 - ``lib/quality_nudge.py`` builds its post-research fix text from these
8 entries (only the fix strings migrated here; trigger logic is untouched).
9 - The doctor aggregator (U4) looks entries up per failed source/backend.
10
11 Because both surfaces read the same entry, the nudge a user sees after a
12 degraded run and the prescription doctor prints for the same failure can
13 never drift apart.
14
15 Composition with the other health layers (reference, don't restate):
16
17 - U1 (``lib/health.py``) owns the machine-aware package-manager strings
18 (brew/pipx/apt/npx install-vs-reinstall, off-PATH PATH edits). Binary-class
19 entries here pull their static defaults from U1's tables, and
20 ``for_dependency_probe`` lets a live probe's machine-specific prescription
21 win the CLI form while the registry supplies cause/NL/anchor vocabulary.
22 - U2 (``lib/backends.py``) embeds this registry's CLI forms inside its
23 chain-failure prescriptions, so a backend finding and a registry lookup
24 agree on the command to run.
25
26 No secrets: CLI forms use obvious ``<placeholder>`` values only.
27 """
28
29 from __future__ import annotations
30
31 from dataclasses import dataclass, replace
32 from typing import Dict, Optional, Tuple
33
34 from . import env, health
35 from .x_api import BEARER_COVERAGE_NOTE
36
37 # Direct engine invocation prefix (scripting fallback; the slash-command UX
38 # is "ask the agent to run setup ...", which is the natural-language form).
39 ENGINE_CLI = "python3 skills/last30days/scripts/last30days.py"
40 SETUP_BROWSER_COOKIES_CLI = f"{ENGINE_CLI} setup --allow-browser-cookies"
41 SETUP_GITHUB_CLI = f"{ENGINE_CLI} setup --github"
42
43 # U1 owns these remediation strings; reference them instead of restating.
44 _YTDLP_BREW_INSTALL, _YTDLP_BREW_REINSTALL = health.static_prescription("yt-dlp", "brew")
45 _YTDLP_PIPX_REINSTALL = health.static_prescription("yt-dlp", "pipx")[1]
46 _DIGG_PP_INSTALL_CLI = health.pp_install_cmd("digg")
47
48 GENERIC_FIX_NL = "see CONFIGURATION.md for setup options for this source"
49
50
51 @dataclass(frozen=True)
52 class Prescription:
53 """Remediation for one (source, failure mode).
54
55 ``fix_nl`` is the natural-language form ("ask the agent to run setup
56 with browser-cookie consent"); ``fix_cli`` is the exact command.
57 ``alt_cli`` carries per-platform alternates (Windows/pip) when the
58 primary CLI form is macOS/brew. ``anchor`` is a CONFIGURATION.md
59 heading anchor ("" when the doc has no dedicated section).
60 """
61
62 source: str
63 failure: str
64 cause: str
65 fix_nl: str
66 fix_cli: str
67 alt_cli: Tuple[str, ...] = ()
68 anchor: str = ""
69
70
71 def _entry(source: str, failure: str, **kwargs) -> Tuple[Tuple[str, str], Prescription]:
72 return (source, failure), Prescription(source=source, failure=failure, **kwargs)
73
74
75 REGISTRY: Dict[Tuple[str, str], Prescription] = dict((
76 _entry(
77 "x", "cookies_missing",
78 cause="X browser cookies (AUTH_TOKEN/CT0) are not configured",
79 fix_nl=(
80 "log into x.com in your browser and re-run (cookies detected "
81 "automatically), or set AUTH_TOKEN and CT0 manually in your .env "
82 "if browser cookies cannot be read, or add XAI_API_KEY to your .env "
83 "(get key at api.x.ai), or add XQUIK_API_KEY to your .env (get key at xquik.com)"
84 ),
85 fix_cli=SETUP_BROWSER_COOKIES_CLI,
86 anchor="api-keys-env",
87 ),
88 _entry(
89 "x", "cookies_expired",
90 cause="X errored this run: cookies are configured but likely expired or revoked",
91 fix_nl="log into x.com in your browser, then re-run",
92 fix_cli=SETUP_BROWSER_COOKIES_CLI,
93 anchor="api-keys-env",
94 ),
95 _entry(
96 "x", "xai_error",
97 cause="the xAI X search backend failed this run",
98 fix_nl=(
99 "check XAI_API_KEY and its chat/model permissions in console.x.ai, "
100 "confirm LAST30DAYS_X_MODEL names an available model, then re-run"
101 ),
102 fix_cli="XAI_API_KEY=<your-xai-key> LAST30DAYS_X_MODEL=<available-xai-model>",
103 anchor="api-keys-env",
104 ),
105 _entry(
106 "x", "xai_payment_required",
107 cause="the xAI X search backend has no available credits",
108 fix_nl="check xAI billing and credits in console.x.ai, then re-run",
109 fix_cli=f'{ENGINE_CLI} "<topic>" --search x',
110 anchor="api-keys-env",
111 ),
112 _entry(
113 "x", "xai_rate_limited",
114 cause="the xAI X search backend hit its rate limit",
115 fix_nl="wait for the xAI rate limit to reset, then re-run",
116 fix_cli=f'{ENGINE_CLI} "<topic>" --search x',
117 anchor="api-keys-env",
118 ),
119 _entry(
120 "x", "xai_timeout",
121 cause="the xAI X search backend timed out",
122 fix_nl="xAI timed out; retry the run or select another configured X backend",
123 fix_cli=f'{ENGINE_CLI} "<topic>" --search x',
124 anchor="api-keys-env",
125 ),
126 _entry(
127 "x", "xai_unavailable",
128 cause="the xAI X search backend failed this run",
129 fix_nl="retry xAI later or select another configured X backend",
130 fix_cli=f'{ENGINE_CLI} "<topic>" --search x',
131 anchor="api-keys-env",
132 ),
133 _entry(
134 "x", "grok_cli_missing",
135 cause="the Grok CLI is not installed, so the keyless X path is unavailable",
136 fix_nl=(
137 "install the Grok CLI (npm install -g @xai-official/grok; see https://docs.grok.com/ for other install options) "
138 "and sign in with `grok login` to search X without any X credential"
139 ),
140 fix_cli="npm install -g @xai-official/grok",
141 anchor="api-keys-env",
142 ),
143 _entry(
144 "x", "grok_not_authenticated",
145 cause="the Grok CLI is installed but not signed in",
146 fix_nl="sign in to Grok once; no X account or API key is needed after that",
147 fix_cli="grok login",
148 anchor="api-keys-env",
149 ),
150 # Official X path (an official-only host per env.x_policy, or an explicit
151 # xapi pin). Copy is limited to the host X lanes (Grok Bot's built-in X
152 # tools, then the X for Grok Bot connector), X_BEARER_TOKEN, XAI_API_KEY,
153 # and X API credits; the bearer path is described as about a week, never
154 # as parity with the host lanes. Anchors point at
155 # the CONFIGURATION.md Grok Bot subsection (slug grok-bot).
156 _entry(
157 "x", "bearer_missing",
158 cause=(
159 "no official X path is configured (Grok Bot X tools, X connector, "
160 "X_BEARER_TOKEN, or XAI_API_KEY)"
161 ),
162 fix_nl=(
163 "fetch X with Grok Bot's built-in X tools and pass the posts with --x-posts, or add the X for Grok Bot "
164 "plugin and connect X in Grok Bot settings (full 30-day coverage), or set "
165 f"X_BEARER_TOKEN from the X developer console ({BEARER_COVERAGE_NOTE}), "
166 "or set XAI_API_KEY from console.x.ai"
167 ),
168 fix_cli="X_BEARER_TOKEN=<your-x-api-bearer-token>",
169 anchor="grok-bot",
170 ),
171 _entry(
172 "x", "bearer_invalid",
173 cause="the X API rejected X_BEARER_TOKEN (401/403)",
174 fix_nl=(
175 "set a valid X_BEARER_TOKEN from the X developer console "
176 f"({BEARER_COVERAGE_NOTE}), or add the X for Grok Bot plugin and connect X in Grok Bot settings "
177 "(full 30-day coverage)"
178 ),
179 fix_cli="X_BEARER_TOKEN=<your-x-api-bearer-token>",
180 anchor="grok-bot",
181 ),
182 _entry(
183 "x", "payment_required",
184 cause="X API credits are exhausted (HTTP 402)",
185 fix_nl=(
186 "top up X API credits in the X developer console, or connect X in "
187 "Grok Bot settings (full 30-day coverage)"
188 ),
189 fix_cli="X_BEARER_TOKEN=<bearer-from-a-project-with-credits>",
190 anchor="grok-bot",
191 ),
192 _entry(
193 "x", "connector_missing",
194 cause=(
195 "the host X lane was declared but no host-fetched result was "
196 "passed to the engine"
197 ),
198 fix_nl=(
199 "fetch X with Grok Bot's built-in X tools (or the X for Grok Bot connector) and pass the "
200 "posts with --x-posts, or unset LAST30DAYS_X_HOST_LANE and set X_BEARER_TOKEN from the X "
201 f"developer console ({BEARER_COVERAGE_NOTE})"
202 ),
203 fix_cli=f'{ENGINE_CLI} "<topic>" --x-posts <path-to-x-posts.json>',
204 anchor="grok-bot",
205 ),
206 _entry(
207 "scrapecreators", "key_missing",
208 cause="SCRAPECREATORS_API_KEY is not set",
209 fix_nl=(
210 "ask the agent to run setup with the GitHub device flow "
211 "(free 10,000-call signup; the key is persisted automatically)"
212 ),
213 fix_cli=SETUP_GITHUB_CLI,
214 anchor="api-keys-env",
215 ),
216 _entry(
217 "bluesky", "app_password_missing",
218 cause="BSKY_HANDLE and/or BSKY_APP_PASSWORD are not set",
219 fix_nl=(
220 "generate an app password at bsky.app/settings/app-passwords and "
221 "add BSKY_HANDLE plus BSKY_APP_PASSWORD to ~/.config/last30days/.env"
222 ),
223 fix_cli="BSKY_HANDLE=<your-handle> BSKY_APP_PASSWORD=<xxxx-xxxx-xxxx-xxxx>",
224 anchor="bluesky-app-password-format-and-search-host",
225 ),
226 _entry(
227 "digg", "pp_cli_missing",
228 cause="digg-pp-cli is not installed",
229 fix_nl=(
230 "install the Digg CLI through the Printing Press library, then "
231 "re-run setup so the source activates"
232 ),
233 fix_cli=_DIGG_PP_INSTALL_CLI,
234 anchor="first-run-onboarding",
235 ),
236 _entry(
237 "digg", "pp_cli_broken",
238 cause=(
239 "digg-pp-cli resolves on PATH but won't execute (broken or "
240 "hanging binary left behind by a bad install)"
241 ),
242 fix_nl=(
243 "reinstall the Digg CLI (re-run the Printing Press install) so "
244 "the binary actually executes; it is installed but not serving"
245 ),
246 fix_cli=_DIGG_PP_INSTALL_CLI,
247 anchor="first-run-onboarding",
248 ),
249 _entry(
250 "digg", "pp_cli_outdated",
251 cause=(
252 "digg-pp-cli is an older release: it searches only Digg's AI and "
253 "tech sections and reports no engagement scores"
254 ),
255 fix_nl=(
256 "re-run the Printing Press install to upgrade the Digg CLI so it "
257 "searches every Digg topic with engagement scores; Digg keeps "
258 "working on AI and tech until then"
259 ),
260 fix_cli=_DIGG_PP_INSTALL_CLI,
261 anchor="first-run-onboarding",
262 ),
263 _entry(
264 "digg", "pp_cli_off_path",
265 cause=(
266 "digg-pp-cli is installed but its directory is not on the "
267 "agent-subprocess PATH"
268 ),
269 fix_nl=(
270 "add the install directory (default ~/.local/bin) to the PATH the "
271 "agent subprocess uses; the engine gate only activates the source "
272 "when the binary resolves on PATH"
273 ),
274 fix_cli='export PATH="$HOME/.local/bin:$PATH"',
275 anchor="first-run-onboarding",
276 ),
277 _entry(
278 "youtube", "ytdlp_missing",
279 cause="yt-dlp is not installed on the agent-subprocess PATH",
280 fix_nl="install yt-dlp to enable the free local YouTube lane",
281 fix_cli=_YTDLP_BREW_INSTALL,
282 alt_cli=("scoop install yt-dlp", "pip install -U yt-dlp"),
283 ),
284 _entry(
285 "youtube", "ytdlp_stale",
286 cause=(
287 "yt-dlp is installed but stale: YouTube's caption format changes "
288 "frequently and old binaries silently fail every transcript"
289 ),
290 fix_nl="update yt-dlp via your package manager",
291 fix_cli="brew upgrade yt-dlp",
292 alt_cli=("scoop update yt-dlp", "pip install -U yt-dlp"),
293 ),
294 _entry(
295 "youtube", "ytdlp_broken",
296 cause=(
297 "yt-dlp resolves on PATH but won't execute (the stale-shim class: "
298 "a wrapper left behind by an interpreter upgrade)"
299 ),
300 fix_nl=(
301 "reinstall yt-dlp so the binary actually executes; a plain "
302 "install reads as a no-op because the broken shim is still present"
303 ),
304 fix_cli=_YTDLP_BREW_REINSTALL,
305 alt_cli=(_YTDLP_PIPX_REINSTALL,),
306 ),
307 _entry(
308 "truthsocial", "token_missing",
309 cause="TRUTHSOCIAL_TOKEN is not set",
310 fix_nl=(
311 "log into truthsocial.com in your browser and let setup read the "
312 "session cookie, or copy the bearer token from your browser's dev "
313 "tools into ~/.config/last30days/.env"
314 ),
315 fix_cli=SETUP_BROWSER_COOKIES_CLI,
316 anchor="api-keys-env",
317 ),
318 _entry(
319 "xiaohongshu", "service_unreachable",
320 cause=(
321 "Xiaohongshu browser-session service is unreachable or not logged "
322 "in; last30days auto-probes http://localhost:18060 and "
323 "http://host.docker.internal:18060 unless XIAOHONGSHU_API_BASE is set"
324 ),
325 fix_nl=(
326 "start a local x-mcp browser plugin or xpzouying/xiaohongshu-mcp "
327 "service that can see your logged-in Xiaohongshu browser session; "
328 "set XIAOHONGSHU_API_BASE only when it runs on a custom host/port"
329 ),
330 fix_cli="XIAOHONGSHU_API_BASE=http://your-host:18060 # only for a custom host; leave unset to auto-probe localhost and host.docker.internal",
331 anchor="api-keys-env",
332 ),
333 ))
334
335
336 def lookup(source: str, failure: str) -> Optional[Prescription]:
337 """Return the registered entry for (source, failure), or None."""
338 return REGISTRY.get((source, failure))
339
340
341 # Failure names remapped on an official-only host (env.x_policy): every
342 # cookie or Grok CLI failure has an official-path counterpart, so no fix
343 # line there names cookies, the scraper, or the CLI. Official names
344 # pass through unchanged on every host.
345 _OFFICIAL_X_FAILURES: Dict[str, str] = {
346 "cookies_missing": "bearer_missing",
347 "cookies_expired": "bearer_invalid",
348 "grok_cli_missing": "bearer_missing",
349 "grok_not_authenticated": "bearer_missing",
350 }
351
352
353 def for_x(config: dict, failure: str) -> Prescription:
354 """Policy-aware X prescription.
355
356 On an official-only host (``env.x_policy(config).hint_namespace ==
357 "official"``) a default-namespace failure resolves to its official
358 counterpart; elsewhere today's entry is returned unchanged. Never
359 raises (falls through to ``get``'s generic fallback).
360 """
361 if env.x_policy(config or {}).hint_namespace == "official":
362 failure = _OFFICIAL_X_FAILURES.get(failure, failure)
363 return get("x", failure)
364
365
366 def get(source: str, failure: str) -> Prescription:
367 """Return the registered entry, or the generic CONFIGURATION.md fallback.
368
369 Never raises: an unregistered failure mode still yields an actionable
370 (if generic) prescription, so a report renderer cannot crash on a
371 failure class the registry has not learned yet.
372 """
373 entry = lookup(source, failure)
374 if entry is not None:
375 return entry
376 return Prescription(
377 source=source,
378 failure=failure,
379 cause=f"{source}: {failure.replace('_', ' ')}",
380 fix_nl=GENERIC_FIX_NL,
381 fix_cli=f"{ENGINE_CLI} setup",
382 )
383
384
385 # ---------------------------------------------------------------------------
386 # Composition with U1 dependency probes
387 # ---------------------------------------------------------------------------
388
389 def _dependency_failure(probe: health.DependencyProbe) -> Optional[Tuple[str, str]]:
390 """Map a failed dependency probe onto a registered (source, failure)."""
391 if probe.name == "yt-dlp":
392 if probe.status == health.MISSING:
393 return ("youtube", "ytdlp_missing")
394 return ("youtube", "ytdlp_broken") # BROKEN and TIMEOUT: reinstall class
395 if probe.name == "digg-pp-cli":
396 # health reports off-PATH binaries as MISSING with ``off_path=True``;
397 # the distinction only picks cause/NL wording — the probe's own
398 # prescription wins the CLI form either way.
399 if probe.status == health.MISSING:
400 if probe.off_path:
401 return ("digg", "pp_cli_off_path")
402 return ("digg", "pp_cli_missing")
403 return ("digg", "pp_cli_broken") # BROKEN and TIMEOUT: reinstall class
404 return None
405
406
407 def for_dependency_probe(probe: health.DependencyProbe) -> Optional[Prescription]:
408 """Prescription for a failed U1 dependency probe (None when OK).
409
410 U1's machine-aware prescription (the manager that owns the binary on
411 THIS machine, or a PATH edit for off-PATH installs) wins the CLI form;
412 the registry entry supplies the shared cause/NL/anchor vocabulary.
413 Unregistered dependencies wrap the probe so callers still get both
414 fix forms without this module restating U1's strings.
415 """
416 if probe.ok:
417 return None
418 key = _dependency_failure(probe)
419 entry = REGISTRY.get(key) if key else None
420 if entry is None:
421 return Prescription(
422 source=probe.name,
423 failure=probe.status,
424 cause=probe.detail or f"{probe.name}: {probe.status}",
425 fix_nl=f"repair the {probe.name} install; {GENERIC_FIX_NL}",
426 fix_cli=probe.prescription or f"{ENGINE_CLI} setup",
427 )
428 updates = {}
429 if probe.detail:
430 updates["cause"] = probe.detail
431 if probe.prescription and probe.prescription != entry.fix_cli:
432 updates["fix_cli"] = probe.prescription
433 return replace(entry, **updates) if updates else entry
434
434 lines PYTHON