返回 last30days-skill
health.py
根目录 / skills / last30days / scripts / lib / health.py
1 """Typed source health: classify a source/tool outcome honestly.
2
3 The pipeline historically collapsed every failure into "returned nothing" or a
4 flat ``errors_by_source`` entry, which hides the difference between a tool that
5 is *absent*, one that is *present but broken* (the classic stale-venv-shim after
6 a Python upgrade), one that *timed out*, and one that merely *degraded* (fewer
7 results than expected). This module gives callers a small typed vocabulary so
8 warnings can say what actually happened and prescribe the right fix.
9
10 It complements ``preflight.py`` (which gates doomed *queries*); this gates
11 doomed *sources/tools*.
12 """
13
14 from __future__ import annotations
15
16 import os
17 import re
18 import shutil
19 import subprocess
20 import time
21 from dataclasses import dataclass
22 from pathlib import Path
23 from typing import Dict, Iterable, List, Optional, Tuple
24
25 from . import subproc
26
27 # Health states, best to worst.
28 OK = "ok"
29 DEGRADED = "degraded" # ran, but returned less than expected
30 MISSING = "missing" # tool/binary/credential absent
31 BROKEN = "broken" # present but won't execute (stale shim, bad perms)
32 TIMEOUT = "timeout" # exceeded the probe deadline
33 ERROR = "error" # ran and failed for another reason
34
35 # Per-run outcomes. Doctor does not emit these: it predicts source readiness
36 # before retrieval, while Report.source_status records what happened in one run.
37 NO_RESULTS = "no-results"
38 PARTIAL = "partial"
39 RATE_LIMITED = "rate-limited"
40 AUTH_FAILED = "auth-failed"
41 PAYMENT_REQUIRED = "payment-required" # HTTP 402 / credits exhausted: top up, not re-login
42 UNREACHABLE = "unreachable"
43 SCHEMA_DRIFT = "schema-drift"
44 SKIPPED_UNCONFIGURED = "skipped-unconfigured"
45
46 # The exit code alone also means clarification in hosted mode.
47 STRICT_EXIT_CODE = 3
48 STRICT_EXIT_PREFIX = "[last30days] strict-exit: degraded sources: "
49
50 # Prefer the failure whose remediation matters most when several requests fail.
51 FAILURE_SPECIFICITY = {
52 AUTH_FAILED: 0,
53 PAYMENT_REQUIRED: 1,
54 RATE_LIMITED: 2,
55 SCHEMA_DRIFT: 3,
56 TIMEOUT: 4,
57 UNREACHABLE: 5,
58 ERROR: 6,
59 }
60
61
62 def credits_exhausted_label(source: str) -> str:
63 """Human label for a ``PAYMENT_REQUIRED`` outcome on ``source``.
64
65 The X source names the API whose credits ran out; every other source
66 gets the generic phrasing so the same label serves render summaries and
67 the doctor post-mortem without each surface hand-writing its own.
68 """
69 return "X API credits exhausted" if source == "x" else "credits exhausted"
70
71
72 @dataclass
73 class SourceHealth:
74 """Typed outcome for a source or the tool backing it.
75
76 ``state`` is one of the module-level constants. ``reason`` is a short,
77 human-readable explanation suitable for a run warning.
78 """
79
80 name: str
81 state: str
82 reason: str = ""
83
84 @property
85 def ok(self) -> bool:
86 return self.state == OK
87
88 @property
89 def usable(self) -> bool:
90 """True when the source produced something worth keeping (ok/degraded)."""
91 return self.state in (OK, DEGRADED)
92
93
94 def probe_command(
95 command: list[str],
96 timeout: float = 5.0,
97 ) -> SourceHealth:
98 """Probe an external command, distinguishing missing/broken/timeout/ok.
99
100 Separating these is what lets the caller emit a correct repair prescription
101 instead of a generic "failed":
102 - ``missing``: the executable is not on PATH.
103 - ``broken``: on PATH but won't run — FileNotFoundError/OSError on exec, or
104 shell exit 126/127 (not-executable / not-found-after-resolution), the
105 signature of a stale interpreter shim after an upgrade.
106 - ``timeout``: exceeded ``timeout`` seconds.
107 - ``ok``: exited 0.
108 - ``error``: ran but exited non-zero for another reason.
109
110 The command should be side-effect-free (e.g. ``["gh", "auth", "status"]``);
111 callers pass a status/version subcommand, not a mutating one.
112 """
113 name = command[0] if command else ""
114 resolved = shutil.which(name) if name else None
115 if resolved is None:
116 return SourceHealth(name=name, state=MISSING, reason=f"{name or 'command'} not found on PATH")
117
118 try:
119 proc = subprocess.run(
120 [resolved, *command[1:]],
121 capture_output=True,
122 text=True,
123 timeout=timeout,
124 )
125 except (FileNotFoundError, OSError) as exc:
126 return SourceHealth(name=name, state=BROKEN, reason=f"{name} present but won't execute: {exc}")
127 except subprocess.TimeoutExpired:
128 return SourceHealth(name=name, state=TIMEOUT, reason=f"{name} timed out after {timeout:g}s")
129
130 if proc.returncode == 0:
131 return SourceHealth(name=name, state=OK)
132 if proc.returncode in (126, 127):
133 return SourceHealth(name=name, state=BROKEN, reason=f"{name} not executable (exit {proc.returncode})")
134 detail = (proc.stderr or proc.stdout or "").strip().splitlines()
135 first = detail[0] if detail else f"exit {proc.returncode}"
136 return SourceHealth(name=name, state=ERROR, reason=f"{name}: {first}")
137
138
139 # ---------------------------------------------------------------------------
140 # Dependency probes (doctor command, issue #692).
141 #
142 # ``probe_dependency`` generalizes ``probe_command`` for the skill's external
143 # binaries (yt-dlp, Printing Press CLIs, node for the vendored bird client,
144 # ffmpeg). It answers three questions the bare shutil.which gate cannot:
145 # - Is the binary genuinely runnable (a stale shim that resolves on PATH but
146 # cannot exec is BROKEN, not available)?
147 # - If not, WHICH fix applies (install vs reinstall vs a PATH edit), keyed to
148 # the package manager that owns the binary on this machine?
149 # - Is an on-disk binary merely off the agent-subprocess PATH (the Digg
150 # ~/.local/bin case) — MISSING with a PATH-fix, never "installed"?
151 #
152 # Semantics follow the engine gate: availability means PATH-resolvable in THIS
153 # process, not present-on-disk. Probes are one short-timeout version exec each
154 # and memoized per process, so doctor and setup can consult them freely.
155 # ---------------------------------------------------------------------------
156
157 # Per-probe budget in seconds: a healthy --version exec is near-instant, so a
158 # slow probe is itself a diagnostic (network-mounted shim, hung interpreter).
159 PROBE_TIMEOUT = 5.0
160
161 _PP_CLI_SUFFIX = "-pp-cli"
162 # The pinned Printing Press catalog installer. The only copy of this string:
163 # setup_wizard imports it, so setup installs and doctor prescribes the same
164 # release (default install dir $HOME/.local/bin on macOS/Linux).
165 PRINTING_PRESS_NPM = "@mvanhorn/printing-press-library@0.1.27"
166
167 # Oldest helper version the engine can call, per binary. Versions compare as
168 # dotted integer tuples, never across helpers: each numbers its own releases
169 # (digg-pp-cli 2026.11.1 beside yahoo-finance-pp-cli 1.0.0). A helper with no
170 # entry here, or whose version cannot be read, is never called outdated.
171 #
172 # digg-pp-cli: 2026.10.1 is the first release whose `search` takes --topic,
173 # the flag the engine sends when `search --help` lists no --sort. Earlier
174 # releases reject the call outright.
175 #
176 # techmeme-pp-cli: 2026.11.1 is the first release whose `search` takes --pages
177 # (printing-press-library #2470), so a run reads past Techmeme's first 10 hits.
178 # It also emits a dated record per headline (since 2026.9.1, #1440), which the
179 # engine needs to window hits to the run. Older releases still work, one page.
180 MIN_HELPER_VERSIONS: Dict[str, Tuple[int, ...]] = {
181 "digg-pp-cli": (2026, 10, 1),
182 "techmeme-pp-cli": (2026, 11, 1),
183 }
184
185 # Why an older helper falls short, for doctor's detail line, when it still runs
186 # in a reduced form. A helper absent here cannot be called below its minimum.
187 MIN_HELPER_SHORTFALL: Dict[str, str] = {
188 "techmeme-pp-cli": "it still runs but reads only Techmeme's first 10 results; upgrade to read more pages",
189 }
190
191 _VERSION_RE = re.compile(r"\d+(?:\.\d+)+")
192
193 # Dependencies the doctor probes by default.
194 KNOWN_DEPENDENCIES: Tuple[str, ...] = (
195 "yt-dlp", "digg-pp-cli", "yahoo-finance-pp-cli", "node", "ffmpeg", "grok",
196 )
197
198 # Cheap side-effect-free version invocation per dependency (default --version).
199 _VERSION_ARGS: Dict[str, List[str]] = {
200 "ffmpeg": ["-version"],
201 }
202
203 # Package managers each dependency may be owned by, in preference order, and
204 # the (install, reinstall) prescription for each. "reinstall" wording matters:
205 # a BROKEN binary is present, so telling the user to "install" it reads as a
206 # no-op ("it's already installed") — the stale-shim trap this module exists
207 # to name.
208 _MANAGER_PRESCRIPTIONS: Dict[str, Dict[str, Tuple[str, str]]] = {
209 "yt-dlp": {
210 "brew": ("brew install yt-dlp", "brew reinstall yt-dlp"),
211 "pipx": ("pipx install yt-dlp", "pipx reinstall yt-dlp"),
212 },
213 "node": {
214 "brew": ("brew install node", "brew reinstall node"),
215 "nvm": ("nvm install --lts", "reinstall node via nvm: nvm install --lts && nvm use --lts"),
216 },
217 "ffmpeg": {
218 "brew": ("brew install ffmpeg", "brew reinstall ffmpeg"),
219 "apt": ("sudo apt-get install -y ffmpeg", "sudo apt-get install -y --reinstall ffmpeg"),
220 },
221 # The official installer is the primary path; npm is a real alternative
222 # (the package is published as @xai-official/grok) and fits the existing
223 # manager-preference machinery.
224 "grok": {
225 "npm": (
226 "npm install -g @xai-official/grok",
227 "reinstall the Grok CLI: npm install -g @xai-official/grok@latest",
228 ),
229 },
230 }
231
232 # Last-resort prescriptions when no known package manager is detected.
233 _FALLBACK_PRESCRIPTIONS: Dict[str, Tuple[str, str]] = {
234 "yt-dlp": (
235 "install yt-dlp (https://github.com/yt-dlp/yt-dlp#installation) and ensure it is on PATH",
236 "reinstall yt-dlp (https://github.com/yt-dlp/yt-dlp#installation); the current binary won't run",
237 ),
238 "node": (
239 "install Node.js 22+ (https://nodejs.org) and ensure `node` is on PATH",
240 "reinstall Node.js 22+ (https://nodejs.org); the current binary won't run",
241 ),
242 "ffmpeg": (
243 "install ffmpeg (https://ffmpeg.org/download.html) and ensure it is on PATH",
244 "reinstall ffmpeg (https://ffmpeg.org/download.html); the current binary won't run",
245 ),
246 "grok": (
247 "install the Grok CLI: npm install -g @xai-official/grok (see https://docs.grok.com/ for other install options), then run `grok login`",
248 "reinstall the Grok CLI: npm install -g @xai-official/grok@latest (see https://docs.grok.com/ for other install options); the current binary won't run",
249 ),
250 }
251
252
253 @dataclass
254 class DependencyProbe:
255 """Uniform probe result for one external dependency.
256
257 ``status`` is one of the module-level constants (OK/MISSING/BROKEN/TIMEOUT).
258 ``detail`` says what was observed (version string, exec error, off-PATH
259 location). ``prescription`` is the copy-pasteable fix, empty when OK.
260 ``owner_pkg_manager`` names the manager the prescription targets
261 ("brew", "pipx", "apt", "nvm", "npx"), or "" for PATH fixes / fallbacks.
262 """
263
264 name: str
265 status: str
266 detail: str = ""
267 prescription: str = ""
268 owner_pkg_manager: str = ""
269 # True for the on-disk-but-off-PATH case: MISSING (the engine gate would
270 # not pass) but the fix is a PATH edit, not an install.
271 off_path: bool = False
272 # For an OK helper with a minimum in MIN_HELPER_VERSIONS: True when below
273 # it (``prescription`` then carries the upgrade), False when at or above
274 # it, None when the helper has no minimum or its version is unreadable.
275 outdated: Optional[bool] = None
276
277 @property
278 def ok(self) -> bool:
279 return self.status == OK
280
281
282 # Safe under the GIL (dict get/set are atomic) and each dependency name is
283 # probed from a single builder today; worst case is one redundant probe.
284 _dependency_probe_cache: Dict[str, DependencyProbe] = {}
285
286
287 def clear_dependency_probe_cache() -> None:
288 """Reset memoized probes (tests, or a doctor re-run after a fix)."""
289 _dependency_probe_cache.clear()
290
291
292 def _nvm_present() -> bool:
293 return bool(os.environ.get("NVM_DIR")) or (Path.home() / ".nvm").is_dir()
294
295
296 def _manager_available(manager: str) -> bool:
297 if manager == "nvm":
298 return _nvm_present()
299 if manager == "apt":
300 return shutil.which("apt-get") is not None
301 return shutil.which(manager) is not None
302
303
304 def _is_pp_cli(name: str) -> bool:
305 return name.endswith(_PP_CLI_SUFFIX) and len(name) > len(_PP_CLI_SUFFIX)
306
307
308 def _pp_install_cmd(name: str) -> str:
309 slug = name[: -len(_PP_CLI_SUFFIX)]
310 return f"npx -y {PRINTING_PRESS_NPM} install {slug} --cli-only"
311
312
313 def pp_install_cmd(slug: str) -> str:
314 """Public catalog-install command for the Printing Press CLI ``<slug>-pp-cli``."""
315 return _pp_install_cmd(f"{slug}{_PP_CLI_SUFFIX}")
316
317
318 def helper_upgrade_cmd(slug: str) -> str:
319 """Shell command that upgrades the helper ``<slug>-pp-cli`` in place.
320
321 The pinned catalog install replaces an older binary, so upgrading is the
322 install command run again, e.g.
323 ``npx -y @mvanhorn/printing-press-library@<pin> install digg --cli-only``.
324 """
325 return pp_install_cmd(slug)
326
327
328 def parse_version(text: str) -> Optional[Tuple[int, ...]]:
329 """First dotted version in a ``--version`` line, as an integer tuple.
330
331 ``"digg-pp-cli 2026.11.1"`` -> ``(2026, 11, 1)``; None when the line has
332 no dotted number (``"digg-pp-cli dev"``).
333 """
334 match = _VERSION_RE.search(text or "")
335 if match is None:
336 return None
337 return tuple(int(part) for part in match.group(0).split("."))
338
339
340 def _format_version(version: Tuple[int, ...]) -> str:
341 return ".".join(str(part) for part in version)
342
343
344 def _version_verdict(name: str, version_line: str) -> Optional[bool]:
345 """True below the helper's minimum, False at or above, None when unknown."""
346 minimum = MIN_HELPER_VERSIONS.get(name)
347 if minimum is None:
348 return None
349 version = parse_version(version_line)
350 if version is None:
351 return None
352 return version < minimum
353
354
355 def helper_outdated(name: str, resolved: Optional[str] = None,
356 timeout: float = PROBE_TIMEOUT) -> Optional[bool]:
357 """Whether the helper ``name`` on PATH is older than the engine can call.
358
359 Reads ``<resolved> --version`` fresh (setup asks again after an upgrade,
360 so the memoized probe would be stale). Runs nothing for a helper with no
361 minimum. Returns True/False, or None when there is no minimum or the
362 version could not be read; None never triggers an upgrade.
363 """
364 if name not in MIN_HELPER_VERSIONS:
365 return None
366 command = [resolved or name] + _VERSION_ARGS.get(name, ["--version"])
367 try:
368 proc = subproc.run_with_timeout(
369 command, timeout=timeout, cleanup_grace=0.1, capture_limit_bytes=64 * 1024,
370 )
371 except (OSError, subproc.SubprocTimeout):
372 return None
373 if proc.returncode != 0:
374 return None
375 return _version_verdict(name, (proc.stdout or proc.stderr or "").strip())
376
377
378 def static_prescription(name: str, manager: str) -> Tuple[str, str]:
379 """Public ``(install, reinstall)`` strings for one dependency/manager pair.
380
381 Reads the static table without probing manager availability; raises
382 KeyError for unknown pairs so consumers fail loudly at import time.
383 """
384 return _MANAGER_PRESCRIPTIONS[name][manager]
385
386
387 def _prescription(name: str, kind: str) -> Tuple[str, str]:
388 """Return ``(prescription, owner_pkg_manager)`` for install/reinstall.
389
390 ``kind`` is "install" (MISSING) or "reinstall" (BROKEN). Printing Press
391 CLIs always re-run the catalog installer; other deps pick the first
392 detected manager from their preference table, falling back to a generic
393 but still actionable instruction.
394 """
395 idx = 0 if kind == "install" else 1
396 if _is_pp_cli(name):
397 cmd = _pp_install_cmd(name)
398 if kind == "reinstall":
399 return f"re-run the Printing Press install: {cmd}", "npx"
400 return cmd, "npx"
401 for manager, prescriptions in _MANAGER_PRESCRIPTIONS.get(name, {}).items():
402 if _manager_available(manager):
403 return prescriptions[idx], manager
404 fallback = _FALLBACK_PRESCRIPTIONS.get(name)
405 if fallback:
406 return fallback[idx], ""
407 verb = "install" if kind == "install" else "reinstall"
408 return f"{verb} {name} and ensure it is on PATH", ""
409
410
411 def windows_printing_press_bin_dir() -> Optional[Path]:
412 """Windows managed install dir for Printing Press CLIs, when applicable.
413
414 Returns ``%LOCALAPPDATA%/Programs/PrintingPress/bin`` on Windows when
415 LOCALAPPDATA is set; ``None`` otherwise.
416 """
417 if os.name != "nt":
418 return None
419 local_app = os.environ.get("LOCALAPPDATA") or os.environ.get("LocalAppData")
420 if not local_app:
421 return None
422 return Path(local_app) / "Programs" / "PrintingPress" / "bin"
423
424
425 def add_managed_bin_dir_to_path() -> Optional[Path]:
426 """Append the Windows Printing Press bin dir to this process's PATH.
427
428 The Printing Press installer drops its CLIs (Digg, arXiv, Techmeme,
429 Yahoo Finance, ...) in ``%LOCALAPPDATA%/Programs/PrintingPress/bin`` and
430 does not put that dir on the user PATH, so every source gated on
431 ``shutil.which`` stayed off until the user edited PATH by hand (#1434).
432 The dir holds only installer-managed binaries, so appending it (lowest
433 precedence) is safe. Returns the dir when it was added, else ``None``.
434 """
435 directory = windows_printing_press_bin_dir()
436 if directory is None or not directory.is_dir():
437 return None
438 current = os.environ.get("PATH", "")
439 entries = {os.path.normcase(os.path.normpath(p)) for p in current.split(os.pathsep) if p}
440 if os.path.normcase(os.path.normpath(str(directory))) in entries:
441 return None
442 os.environ["PATH"] = f"{current}{os.pathsep}{directory}" if current else str(directory)
443 return directory
444
445
446 def path_edit_example(directory: str) -> str:
447 """A copy-pasteable command that puts ``directory`` on PATH for this OS.
448
449 POSIX gets the shell ``export``; Windows gets a PowerShell command that
450 persists the dir on the user PATH (an ``export`` line with a Windows path
451 neither runs in PowerShell nor survives a restart).
452 """
453 if os.name == "nt":
454 # PowerShell single-quoted strings escape an apostrophe by doubling it
455 # (a C:\Users\O'Brien path would otherwise end the string early).
456 quoted = directory.replace("'", "''")
457 return (
458 "[Environment]::SetEnvironmentVariable('Path', "
459 "[Environment]::GetEnvironmentVariable('Path', 'User') + "
460 f"';{quoted}', 'User')"
461 )
462 return f'export PATH="{directory}:$PATH"'
463
464
465 def path_edit_prescription(directory: str, name: str) -> str:
466 """Prescription text for a binary that sits in ``directory`` off PATH."""
467 restart = " then restart your agent host" if os.name == "nt" else ""
468 return f"add {directory} to PATH (e.g. {path_edit_example(directory)}){restart} so {name} resolves"
469
470
471 def installer_bin_dirs() -> List[Path]:
472 """Printing Press install directories shared by setup and doctor.
473
474 Includes the library default (~/.local/bin), Go bins and the managed
475 %LOCALAPPDATA%/Programs/PrintingPress/bin directory on Windows.
476 """
477 home = Path.home()
478 dirs = [home / ".local" / "bin"]
479 gopath = os.environ.get("GOPATH")
480 if gopath:
481 dirs.append(Path(gopath) / "bin")
482 dirs.append(home / "go" / "bin")
483 win_dir = windows_printing_press_bin_dir()
484 if win_dir is not None:
485 dirs.append(win_dir)
486 return dirs
487
488
489 def _off_path_candidate_dirs() -> List[Path]:
490 """Directories where installers drop binaries that PATH may not cover.
491
492 The shared installer dirs (``installer_bin_dirs``, which also backs
493 setup_wizard's Digg candidates) plus the Homebrew prefixes (an agent
494 subprocess PATH sometimes omits even those).
495 """
496 dirs = installer_bin_dirs()
497 dirs.extend([Path("/opt/homebrew/bin"), Path("/usr/local/bin")])
498 return dirs
499
500
501 def find_installed_binary(name: str, directories: Iterable[Path]) -> Optional[Path]:
502 """Look for a native helper in the supplied installation directories."""
503 filenames = (f"{name}.exe", name) if os.name == "nt" else (name,)
504 for directory in directories:
505 for filename in filenames:
506 candidate = directory / filename
507 if os.path.isfile(candidate) and os.access(candidate, os.X_OK):
508 return candidate
509 return None
510
511
512 def windows_npm_launcher(name: str) -> Optional[Path]:
513 """Find npm's .cmd shim in a Windows global prefix without running npm."""
514 if os.name != "nt":
515 return None
516 prefix = os.environ.get("NPM_CONFIG_PREFIX")
517 appdata = os.environ.get("APPDATA")
518 directories = [Path(prefix)] if prefix else []
519 if appdata:
520 directories.append(Path(appdata) / "npm")
521 for directory in directories:
522 candidate = directory / f"{name}.cmd"
523 if directory.is_absolute() and os.path.isfile(candidate):
524 return candidate
525 return None
526
527
528 def _off_path_binary(name: str) -> Optional[Path]:
529 """Return an executable for ``name`` in a known dir that PATH misses."""
530 if name == "grok":
531 launcher = windows_npm_launcher(name)
532 if launcher is not None:
533 return launcher
534 return find_installed_binary(name, _off_path_candidate_dirs())
535
536
537 def _path_hint(directory: Path) -> str:
538 """Render a bin dir with $HOME substituted for copy-pasteable PATH edits."""
539 raw = str(directory)
540 if os.name == "nt":
541 return raw
542 home = str(Path.home())
543 if raw == home:
544 return "$HOME"
545 if raw.startswith(home + os.sep):
546 return "$HOME/" + raw[len(home) + 1:].replace(os.sep, "/")
547 return raw
548
549
550 def probe_dependency(name: str, timeout: float = PROBE_TIMEOUT) -> DependencyProbe:
551 """Probe one external dependency: OK | MISSING | BROKEN | TIMEOUT.
552
553 - MISSING: not resolvable on this process's PATH. If the binary exists in
554 a known install dir, the prescription is a PATH edit, not an install —
555 installing again would not fix anything.
556 - BROKEN: shutil.which resolves it but a cheap version exec fails
557 (OSError/exec-format, or any non-zero exit). Prescription says
558 *reinstall* — the #692 stale-shim class must never read as available.
559 - TIMEOUT: the version exec exceeded the per-probe budget.
560 - OK: version exec exited 0; ``detail`` carries the version line.
561
562 Memoized per process; ``clear_dependency_probe_cache()`` resets.
563 """
564 cached = _dependency_probe_cache.get(name)
565 if cached is not None:
566 return cached
567 probe = _probe_dependency_uncached(name, timeout)
568 _dependency_probe_cache[name] = probe
569 return probe
570
571
572 def _probe_dependency_uncached(name: str, timeout: float) -> DependencyProbe:
573 deadline = time.monotonic() + timeout
574 resolved = shutil.which(name)
575 if resolved is None:
576 off_path = _off_path_binary(name)
577 if off_path is not None:
578 hint = _path_hint(off_path.parent)
579 return DependencyProbe(
580 name=name,
581 status=MISSING,
582 detail=f"{name} is installed at {off_path} but that directory is not on this process's PATH",
583 prescription=path_edit_prescription(hint, name),
584 owner_pkg_manager="",
585 off_path=True,
586 )
587 prescription, manager = _prescription(name, "install")
588 return DependencyProbe(
589 name=name,
590 status=MISSING,
591 detail=f"{name} not found on PATH",
592 prescription=prescription,
593 owner_pkg_manager=manager,
594 )
595
596 command = [resolved] + _VERSION_ARGS.get(name, ["--version"])
597 try:
598 cleanup_grace = 0.1
599 proc = subproc.run_with_timeout(
600 command,
601 timeout=max(0, deadline - time.monotonic() - 2 * cleanup_grace),
602 deadline_monotonic=deadline - 2 * cleanup_grace,
603 cleanup_grace=cleanup_grace,
604 capture_limit_bytes=64 * 1024,
605 )
606 except (FileNotFoundError, OSError) as exc:
607 prescription, manager = _prescription(name, "reinstall")
608 return DependencyProbe(
609 name=name,
610 status=BROKEN,
611 detail=f"{name} resolves to {resolved} but won't execute: {exc}",
612 prescription=prescription,
613 owner_pkg_manager=manager,
614 )
615 except subproc.SubprocTimeout:
616 prescription, manager = _prescription(name, "reinstall")
617 return DependencyProbe(
618 name=name,
619 status=TIMEOUT,
620 detail=f"{name} version probe timed out after {timeout:g}s",
621 prescription=f"re-run doctor; if the timeout persists: {prescription}",
622 owner_pkg_manager=manager,
623 )
624
625 if proc.returncode == 0:
626 lines = (proc.stdout or proc.stderr or "").strip().splitlines()
627 version = lines[0].strip() if lines else ""
628 if name not in MIN_HELPER_VERSIONS:
629 return DependencyProbe(name=name, status=OK, detail=version)
630 outdated = _version_verdict(name, version)
631 if outdated is None:
632 return DependencyProbe(
633 name=name, status=OK, detail=f"{version} (version unknown)".strip(),
634 )
635 if not outdated:
636 return DependencyProbe(name=name, status=OK, detail=version, outdated=False)
637 minimum = _format_version(MIN_HELPER_VERSIONS[name])
638 # A Printing Press install replaces the older binary in place.
639 prescription, manager = _prescription(name, "install")
640 return DependencyProbe(
641 name=name,
642 status=OK,
643 detail=f"{version} (older than {minimum}; "
644 f"{MIN_HELPER_SHORTFALL.get(name, 'the oldest the engine can call')})",
645 prescription=prescription,
646 owner_pkg_manager=manager,
647 outdated=True,
648 )
649
650 lines = (proc.stderr or proc.stdout or "").strip().splitlines()
651 why = lines[0].strip() if lines else f"exit {proc.returncode}"
652 prescription, manager = _prescription(name, "reinstall")
653 return DependencyProbe(
654 name=name,
655 status=BROKEN,
656 detail=f"{name} resolves to {resolved} but the version probe failed: {why}",
657 prescription=prescription,
658 owner_pkg_manager=manager,
659 )
660
661
662 def probe_dependencies(names: Optional[Iterable[str]] = None) -> Dict[str, DependencyProbe]:
663 """Probe every known dependency (or ``names``), memoized per process."""
664 return {name: probe_dependency(name) for name in (names or KNOWN_DEPENDENCIES)}
665
665 lines PYTHON