| 1 | """Native Rust core bridge with verified auto-install and transparent Python fallback. |
| 2 | |
| 3 | Discovers or installs a standalone ``last30days-core`` binary (no Rust toolchain |
| 4 | required on the user's machine) and communicates over a persistent |
| 5 | newline-delimited JSON stdio worker. Pure Python remains as an automatic |
| 6 | fallback for offline sandboxes, unsupported architectures, or when |
| 7 | ``LAST30DAYS_ENGINE=python`` is set. |
| 8 | """ |
| 9 | |
| 10 | from __future__ import annotations |
| 11 | |
| 12 | import atexit |
| 13 | import hashlib |
| 14 | import hmac |
| 15 | import http.client |
| 16 | import json |
| 17 | import math |
| 18 | import os |
| 19 | import platform |
| 20 | import re |
| 21 | import select |
| 22 | import shutil |
| 23 | import stat |
| 24 | import subprocess |
| 25 | import sys |
| 26 | import tempfile |
| 27 | import threading |
| 28 | import time |
| 29 | import urllib.error |
| 30 | import urllib.parse |
| 31 | import urllib.request |
| 32 | from pathlib import Path |
| 33 | from typing import Any |
| 34 | |
| 35 | from . import skill_meta |
| 36 | |
| 37 | PROTOCOL_VERSION = 1 |
| 38 | DEFAULT_TIMEOUT_SECONDS = 30.0 |
| 39 | RELEASE_REPO = "mvanhorn/last30days-skill" |
| 40 | CHECKSUMS_ASSET = "last30days-core-SHA256SUMS.txt" |
| 41 | MAX_BINARY_BYTES = 25 * 1024 * 1024 |
| 42 | MAX_CHECKSUMS_BYTES = 64 * 1024 |
| 43 | DOWNLOAD_TIMEOUT_SECONDS = 30.0 |
| 44 | AUTO_INSTALL_COOLDOWN_SECONDS = 24 * 60 * 60 |
| 45 | |
| 46 | _BINARY_NAME = "last30days-core.exe" if sys.platform == "win32" else "last30days-core" |
| 47 | _VERSION_STAMP_NAME = ".last30days-core-version" |
| 48 | _ATTEMPT_STAMP_NAME = ".last30days-core-attempt" |
| 49 | _SEMVER_RE = re.compile(r"^\d+\.\d+\.\d+$") |
| 50 | _HEX64_RE = re.compile(r"^[0-9a-f]{64}$") |
| 51 | _ALLOWED_DOWNLOAD_HOSTS = frozenset( |
| 52 | { |
| 53 | "github.com", |
| 54 | "objects.githubusercontent.com", |
| 55 | "release-assets.githubusercontent.com", |
| 56 | } |
| 57 | ) |
| 58 | |
| 59 | |
| 60 | class RustAccelError(RuntimeError): |
| 61 | """Raised when LAST30DAYS_ENGINE=rust is forced and the Rust worker fails.""" |
| 62 | |
| 63 | |
| 64 | def engine_mode() -> str: |
| 65 | """Return configured acceleration mode: ``'auto'``, ``'rust'``, or ``'python'``.""" |
| 66 | raw = (os.environ.get("LAST30DAYS_ENGINE") or "auto").strip().lower() |
| 67 | if raw in {"python", "py", "off", "0", "false"}: |
| 68 | return "python" |
| 69 | if raw in {"rust", "rs", "force", "required"}: |
| 70 | return "rust" |
| 71 | return "auto" |
| 72 | |
| 73 | |
| 74 | def worker_timeout() -> float: |
| 75 | """Return per-request timeout in seconds for the Rust stdio worker.""" |
| 76 | raw = (os.environ.get("LAST30DAYS_RUST_TIMEOUT") or "").strip() |
| 77 | if not raw: |
| 78 | return DEFAULT_TIMEOUT_SECONDS |
| 79 | try: |
| 80 | value = float(raw) |
| 81 | except ValueError: |
| 82 | return DEFAULT_TIMEOUT_SECONDS |
| 83 | if not math.isfinite(value) or value <= 0: |
| 84 | return DEFAULT_TIMEOUT_SECONDS |
| 85 | return value |
| 86 | |
| 87 | |
| 88 | def install_bin_path() -> Path: |
| 89 | """Return the managed user-local install path for ``last30days-core``.""" |
| 90 | return Path.home() / ".local" / "share" / "last30days" / "bin" / _BINARY_NAME |
| 91 | |
| 92 | |
| 93 | def _candidate_binary_paths() -> list[Path]: |
| 94 | candidates: list[Path] = [] |
| 95 | override = (os.environ.get("LAST30DAYS_RUST_BIN") or "").strip() |
| 96 | if override: |
| 97 | candidates.append(Path(override).expanduser()) |
| 98 | candidates.append(install_bin_path()) |
| 99 | # Dev checkout layout: skills/last30days/scripts/lib/rust_accel.py -> repo root -> rust/target/release/ |
| 100 | repo_root = Path(__file__).resolve().parents[4] |
| 101 | candidates.append(repo_root / "rust" / "target" / "release" / _BINARY_NAME) |
| 102 | found_on_path = shutil.which(_BINARY_NAME) |
| 103 | if found_on_path: |
| 104 | candidates.append(Path(found_on_path)) |
| 105 | return candidates |
| 106 | |
| 107 | |
| 108 | def find_binary() -> str | None: |
| 109 | """Return path to an executable ``last30days-core`` binary, or ``None``.""" |
| 110 | for path in _candidate_binary_paths(): |
| 111 | try: |
| 112 | if path.is_file() and os.access(path, os.X_OK): |
| 113 | return str(path) |
| 114 | except OSError: |
| 115 | continue |
| 116 | return None |
| 117 | |
| 118 | |
| 119 | def platform_asset_name( |
| 120 | system: str | None = None, |
| 121 | machine: str | None = None, |
| 122 | ) -> str | None: |
| 123 | """Return the GitHub Release asset name for this OS/architecture, or ``None``.""" |
| 124 | plat = (system if system is not None else sys.platform).lower() |
| 125 | arch = (machine if machine is not None else platform.machine()).lower() |
| 126 | if plat == "darwin": |
| 127 | if arch in {"arm64", "aarch64"}: |
| 128 | return "last30days-core-darwin-arm64" |
| 129 | if arch in {"x86_64", "amd64"}: |
| 130 | return "last30days-core-darwin-amd64" |
| 131 | return None |
| 132 | if plat.startswith("linux"): |
| 133 | if arch in {"x86_64", "amd64"}: |
| 134 | return "last30days-core-linux-amd64" |
| 135 | if arch in {"aarch64", "arm64"}: |
| 136 | return "last30days-core-linux-arm64" |
| 137 | return None |
| 138 | if plat in {"win32", "cygwin", "msys"}: |
| 139 | if arch in {"amd64", "x86_64"}: |
| 140 | return "last30days-core-windows-amd64.exe" |
| 141 | return None |
| 142 | return None |
| 143 | |
| 144 | |
| 145 | def expected_skill_version(script_file: Path | None = None) -> str | None: |
| 146 | """Return validated ``X.Y.Z`` version from skill, plugin, or MCP sentinel metadata.""" |
| 147 | here = (script_file if script_file is not None else Path(__file__)).resolve() |
| 148 | candidates: list[str | None] = [] |
| 149 | |
| 150 | # 1. Standard skill install: <skill>/scripts/lib/rust_accel.py -> <skill>/SKILL.md |
| 151 | if len(here.parents) > 2: |
| 152 | candidates.append(skill_meta.read_skill_version(here.parents[2] / "SKILL.md")) |
| 153 | |
| 154 | # 2. Plugin cache install: ancestor .claude-plugin/plugin.json |
| 155 | for parent in here.parents: |
| 156 | manifest = parent / ".claude-plugin" / "plugin.json" |
| 157 | if manifest.is_file(): |
| 158 | try: |
| 159 | raw_ver = json.loads(manifest.read_text(encoding="utf-8")).get("version") |
| 160 | except (OSError, ValueError): |
| 161 | continue |
| 162 | if isinstance(raw_ver, str): |
| 163 | candidates.append(raw_ver) |
| 164 | break |
| 165 | |
| 166 | # 3. Extracted MCP bundle: <cache>/<version>/lib/rust_accel.py -> <cache>/<version>/.version |
| 167 | if len(here.parents) > 1: |
| 168 | candidates.append(_read_stamp(here.parents[1] / ".version")) |
| 169 | |
| 170 | for raw in candidates: |
| 171 | if not raw: |
| 172 | continue |
| 173 | cleaned = raw.strip().removeprefix("v") |
| 174 | if _SEMVER_RE.fullmatch(cleaned): |
| 175 | return cleaned |
| 176 | return None |
| 177 | |
| 178 | |
| 179 | def _validate_download_url(url: str) -> str: |
| 180 | parsed = urllib.parse.urlsplit(url) |
| 181 | host = (parsed.hostname or "").lower() |
| 182 | if ( |
| 183 | parsed.scheme != "https" |
| 184 | or parsed.username is not None |
| 185 | or parsed.password is not None |
| 186 | or host not in _ALLOWED_DOWNLOAD_HOSTS |
| 187 | ): |
| 188 | raise ValueError(f"refusing disallowed download URL: {url}") |
| 189 | return url |
| 190 | |
| 191 | |
| 192 | class _SafeHttpsRedirectHandler(urllib.request.HTTPRedirectHandler): |
| 193 | """Allow only HTTPS redirects to GitHub release asset hosts.""" |
| 194 | |
| 195 | max_redirections = 5 |
| 196 | |
| 197 | def redirect_request(self, req, fp, code, msg, headers, newurl): |
| 198 | resolved = urllib.parse.urljoin(req.full_url, newurl) |
| 199 | _validate_download_url(resolved) |
| 200 | return super().redirect_request(req, fp, code, msg, headers, resolved) |
| 201 | |
| 202 | |
| 203 | def _https_fetch_bytes( |
| 204 | url: str, |
| 205 | *, |
| 206 | max_bytes: int, |
| 207 | timeout: float = DOWNLOAD_TIMEOUT_SECONDS, |
| 208 | ) -> bytes: |
| 209 | """Fetch bounded bytes from an allowlisted GitHub Releases HTTPS URL.""" |
| 210 | _validate_download_url(url) |
| 211 | opener = urllib.request.build_opener( |
| 212 | urllib.request.HTTPSHandler(), |
| 213 | _SafeHttpsRedirectHandler(), |
| 214 | ) |
| 215 | req = urllib.request.Request( |
| 216 | url, |
| 217 | headers={"User-Agent": "last30days-core-installer/1"}, |
| 218 | ) |
| 219 | with opener.open(req, timeout=timeout) as resp: |
| 220 | _validate_download_url(resp.geturl()) |
| 221 | chunks: list[bytes] = [] |
| 222 | total = 0 |
| 223 | while True: |
| 224 | chunk = resp.read(65536) |
| 225 | if not chunk: |
| 226 | break |
| 227 | total += len(chunk) |
| 228 | if total > max_bytes: |
| 229 | raise ValueError(f"download exceeds {max_bytes} byte limit") |
| 230 | chunks.append(chunk) |
| 231 | return b"".join(chunks) |
| 232 | |
| 233 | |
| 234 | def parse_checksums(text: str) -> dict[str, str]: |
| 235 | """Parse ``sha256sum`` output into ``{asset_filename: sha256_hex}``.""" |
| 236 | out: dict[str, str] = {} |
| 237 | for raw_line in text.splitlines(): |
| 238 | line = raw_line.strip() |
| 239 | if not line or line.startswith("#"): |
| 240 | continue |
| 241 | parts = line.split(None, 1) |
| 242 | if len(parts) != 2: |
| 243 | continue |
| 244 | digest, name = parts[0].lower(), parts[1].strip() |
| 245 | if name.startswith("*"): |
| 246 | name = name[1:] |
| 247 | if not _HEX64_RE.fullmatch(digest): |
| 248 | continue |
| 249 | if not name or "/" in name or "\\" in name or name in {".", ".."}: |
| 250 | continue |
| 251 | out[name] = digest |
| 252 | return out |
| 253 | |
| 254 | |
| 255 | def _verify_binary_executable(bin_path: Path) -> tuple[bool, str | None]: |
| 256 | """Run a one-shot ping against ``bin_path`` to verify execution and protocol.""" |
| 257 | try: |
| 258 | proc = subprocess.run( |
| 259 | [str(bin_path), "serve"], |
| 260 | input='{"op":"ping"}\n', |
| 261 | capture_output=True, |
| 262 | text=True, |
| 263 | encoding="utf-8", |
| 264 | timeout=5.0, |
| 265 | check=False, |
| 266 | ) |
| 267 | except (OSError, subprocess.SubprocessError): |
| 268 | return False, None |
| 269 | if proc.returncode != 0 or not isinstance(proc.stdout, str): |
| 270 | return False, None |
| 271 | first_line = proc.stdout.strip().splitlines()[:1] |
| 272 | if not first_line: |
| 273 | return False, None |
| 274 | try: |
| 275 | resp = json.loads(first_line[0]) |
| 276 | except ValueError: |
| 277 | return False, None |
| 278 | if resp.get("status") != "ok" or resp.get("protocol") != PROTOCOL_VERSION: |
| 279 | return False, None |
| 280 | version = resp.get("version") |
| 281 | return True, str(version) if version else None |
| 282 | |
| 283 | |
| 284 | def _read_stamp(path: Path) -> str | None: |
| 285 | try: |
| 286 | if path.is_symlink() or not path.is_file(): |
| 287 | return None |
| 288 | return path.read_text(encoding="utf-8").strip() or None |
| 289 | except OSError: |
| 290 | return None |
| 291 | |
| 292 | |
| 293 | def _write_stamp_atomic(path: Path, value: str) -> None: |
| 294 | tmp_path: Path | None = None |
| 295 | try: |
| 296 | with tempfile.NamedTemporaryFile( |
| 297 | mode="w", |
| 298 | encoding="utf-8", |
| 299 | dir=path.parent, |
| 300 | prefix=f".{path.name}.", |
| 301 | delete=False, |
| 302 | ) as fh: |
| 303 | tmp_path = Path(fh.name) |
| 304 | fh.write(value + "\n") |
| 305 | fh.flush() |
| 306 | os.fsync(fh.fileno()) |
| 307 | os.replace(tmp_path, path) |
| 308 | tmp_path = None |
| 309 | except OSError: |
| 310 | pass |
| 311 | finally: |
| 312 | if tmp_path is not None: |
| 313 | try: |
| 314 | tmp_path.unlink(missing_ok=True) |
| 315 | except OSError: |
| 316 | pass |
| 317 | |
| 318 | |
| 319 | def _ensure_safe_install_dir(dest_dir: Path) -> None: |
| 320 | """Create ``dest_dir`` safely and reject symlinked install targets.""" |
| 321 | if dest_dir.is_symlink(): |
| 322 | raise OSError(f"refusing to install into symlink directory: {dest_dir}") |
| 323 | dest_dir.mkdir(parents=True, exist_ok=True) |
| 324 | if dest_dir.is_symlink() or not dest_dir.is_dir(): |
| 325 | raise OSError(f"install directory is not a regular directory: {dest_dir}") |
| 326 | |
| 327 | |
| 328 | def _release_asset_url(version: str, asset: str) -> str: |
| 329 | return f"https://github.com/{RELEASE_REPO}/releases/download/v{version}/{asset}" |
| 330 | |
| 331 | |
| 332 | def install_release_binary( |
| 333 | *, |
| 334 | version: str | None = None, |
| 335 | force: bool = False, |
| 336 | timeout: float = DOWNLOAD_TIMEOUT_SECONDS, |
| 337 | ) -> dict[str, Any]: |
| 338 | """Ensure a verified ``last30days-core`` binary is installed for this platform. |
| 339 | |
| 340 | Downloads the platform release binary and ``last30days-core-SHA256SUMS.txt`` |
| 341 | from GitHub Releases over HTTPS, verifies the SHA-256 digest and live |
| 342 | protocol handshake before atomically installing into |
| 343 | ``~/.local/share/last30days/bin/last30days-core``. Never raises. |
| 344 | """ |
| 345 | if engine_mode() == "python": |
| 346 | return { |
| 347 | "installed": False, |
| 348 | "action": "disabled", |
| 349 | "path": None, |
| 350 | "version": None, |
| 351 | "detail": "LAST30DAYS_ENGINE=python", |
| 352 | } |
| 353 | |
| 354 | target_version = version if version is not None else expected_skill_version() |
| 355 | managed_path = install_bin_path() |
| 356 | version_stamp = managed_path.parent / _VERSION_STAMP_NAME |
| 357 | attempt_stamp = managed_path.parent / _ATTEMPT_STAMP_NAME |
| 358 | had_managed = managed_path.is_file() and not managed_path.is_symlink() |
| 359 | |
| 360 | if not force: |
| 361 | existing = find_binary() |
| 362 | if existing is not None: |
| 363 | existing_path = Path(existing) |
| 364 | is_managed = existing_path == managed_path |
| 365 | if not is_managed: |
| 366 | return { |
| 367 | "installed": True, |
| 368 | "action": "already_installed", |
| 369 | "path": existing, |
| 370 | "version": None, |
| 371 | "detail": "using existing binary", |
| 372 | } |
| 373 | had_managed = True |
| 374 | stamped = _read_stamp(version_stamp) |
| 375 | if not target_version or stamped == target_version: |
| 376 | return { |
| 377 | "installed": True, |
| 378 | "action": "already_installed", |
| 379 | "path": existing, |
| 380 | "version": stamped, |
| 381 | "detail": "managed binary up to date", |
| 382 | } |
| 383 | |
| 384 | asset = platform_asset_name() |
| 385 | if asset is None: |
| 386 | return { |
| 387 | "installed": had_managed, |
| 388 | "action": "unsupported_platform", |
| 389 | "path": str(managed_path) if had_managed else None, |
| 390 | "version": _read_stamp(version_stamp) if had_managed else None, |
| 391 | "detail": f"no prebuilt binary for {sys.platform}/{platform.machine()}; using Python fallback", |
| 392 | } |
| 393 | |
| 394 | if not target_version or not _SEMVER_RE.fullmatch(target_version): |
| 395 | return { |
| 396 | "installed": had_managed, |
| 397 | "action": "install_failed", |
| 398 | "path": str(managed_path) if had_managed else None, |
| 399 | "version": _read_stamp(version_stamp) if had_managed else None, |
| 400 | "detail": f"invalid release version: {target_version!r}", |
| 401 | } |
| 402 | |
| 403 | tmp_path: Path | None = None |
| 404 | try: |
| 405 | checksums_raw = _https_fetch_bytes( |
| 406 | _release_asset_url(target_version, CHECKSUMS_ASSET), |
| 407 | max_bytes=MAX_CHECKSUMS_BYTES, |
| 408 | timeout=timeout, |
| 409 | ) |
| 410 | checksums = parse_checksums(checksums_raw.decode("utf-8")) |
| 411 | expected_sha = checksums.get(asset) |
| 412 | if not expected_sha: |
| 413 | raise ValueError(f"no SHA-256 checksum published for {asset}") |
| 414 | |
| 415 | binary_bytes = _https_fetch_bytes( |
| 416 | _release_asset_url(target_version, asset), |
| 417 | max_bytes=MAX_BINARY_BYTES, |
| 418 | timeout=timeout, |
| 419 | ) |
| 420 | actual_sha = hashlib.sha256(binary_bytes).hexdigest() |
| 421 | if not hmac.compare_digest(actual_sha, expected_sha): |
| 422 | raise ValueError( |
| 423 | f"SHA-256 mismatch for {asset} (expected {expected_sha[:12]}..., got {actual_sha[:12]}...)" |
| 424 | ) |
| 425 | |
| 426 | _ensure_safe_install_dir(managed_path.parent) |
| 427 | if managed_path.is_symlink(): |
| 428 | raise OSError(f"refusing to overwrite symlink binary: {managed_path}") |
| 429 | |
| 430 | with tempfile.NamedTemporaryFile( |
| 431 | mode="wb", |
| 432 | dir=managed_path.parent, |
| 433 | prefix=".last30days-core-dl-", |
| 434 | delete=False, |
| 435 | ) as fh: |
| 436 | tmp_path = Path(fh.name) |
| 437 | fh.write(binary_bytes) |
| 438 | fh.flush() |
| 439 | os.fsync(fh.fileno()) |
| 440 | |
| 441 | if os.name == "posix": |
| 442 | os.chmod(tmp_path, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH) |
| 443 | |
| 444 | ok, bin_ver = _verify_binary_executable(tmp_path) |
| 445 | if not ok: |
| 446 | raise RustAccelError("downloaded binary failed protocol handshake verification") |
| 447 | |
| 448 | shutdown() |
| 449 | os.replace(tmp_path, managed_path) |
| 450 | tmp_path = None |
| 451 | _write_stamp_atomic(version_stamp, target_version) |
| 452 | try: |
| 453 | attempt_stamp.unlink(missing_ok=True) |
| 454 | except OSError: |
| 455 | pass |
| 456 | _POOL._disabled_for_bin = None |
| 457 | _POOL._verified_bin = str(managed_path) |
| 458 | _POOL._last_error = None |
| 459 | return { |
| 460 | "installed": True, |
| 461 | "action": "upgraded" if had_managed else "installed", |
| 462 | "path": str(managed_path), |
| 463 | "version": target_version or bin_ver, |
| 464 | "detail": f"verified SHA-256 and installed {asset}", |
| 465 | } |
| 466 | except ( |
| 467 | OSError, |
| 468 | ValueError, |
| 469 | urllib.error.URLError, |
| 470 | http.client.HTTPException, |
| 471 | RustAccelError, |
| 472 | ) as exc: |
| 473 | return { |
| 474 | "installed": had_managed, |
| 475 | "action": "install_failed", |
| 476 | "path": str(managed_path) if had_managed else None, |
| 477 | "version": _read_stamp(version_stamp) if had_managed else None, |
| 478 | "detail": str(exc), |
| 479 | } |
| 480 | finally: |
| 481 | if tmp_path is not None: |
| 482 | try: |
| 483 | tmp_path.unlink(missing_ok=True) |
| 484 | except OSError: |
| 485 | pass |
| 486 | |
| 487 | |
| 488 | def _auto_install_target_version() -> str | None: |
| 489 | """Return target release version if a live run would attempt auto-install, else ``None``.""" |
| 490 | if engine_mode() == "python": |
| 491 | return None |
| 492 | target_version = expected_skill_version() |
| 493 | managed_path = install_bin_path() |
| 494 | version_stamp = managed_path.parent / _VERSION_STAMP_NAME |
| 495 | existing = find_binary() |
| 496 | if existing is not None: |
| 497 | if Path(existing) != managed_path: |
| 498 | return None |
| 499 | if not target_version or _read_stamp(version_stamp) == target_version: |
| 500 | return None |
| 501 | if platform_asset_name() is None or not target_version: |
| 502 | return None |
| 503 | |
| 504 | attempt_stamp = managed_path.parent / _ATTEMPT_STAMP_NAME |
| 505 | last_attempt = _read_stamp(attempt_stamp) |
| 506 | if last_attempt is not None: |
| 507 | try: |
| 508 | if (time.time() - float(last_attempt)) < AUTO_INSTALL_COOLDOWN_SECONDS: |
| 509 | return None |
| 510 | except ValueError: |
| 511 | pass |
| 512 | return target_version |
| 513 | |
| 514 | |
| 515 | def would_auto_install_on_run() -> bool: |
| 516 | """Return ``True`` when the next live run would download and install ``last30days-core``.""" |
| 517 | return _auto_install_target_version() is not None |
| 518 | |
| 519 | |
| 520 | def ensure_installed_for_run(*, timeout: float = 10.0) -> dict[str, Any] | None: |
| 521 | """Best-effort one-time auto-install on live runs with 24h failure backoff. |
| 522 | |
| 523 | Returns the install result dict when an install/upgrade was attempted, or |
| 524 | ``None`` when a current binary is already available, Rust is disabled, or a |
| 525 | recent failed attempt is still within its cooldown window. |
| 526 | """ |
| 527 | target_version = _auto_install_target_version() |
| 528 | if target_version is None: |
| 529 | return None |
| 530 | |
| 531 | managed_path = install_bin_path() |
| 532 | attempt_stamp = managed_path.parent / _ATTEMPT_STAMP_NAME |
| 533 | result = install_release_binary(version=target_version, timeout=timeout) |
| 534 | if result.get("action") == "install_failed": |
| 535 | try: |
| 536 | _ensure_safe_install_dir(managed_path.parent) |
| 537 | _write_stamp_atomic(attempt_stamp, f"{time.time():.0f}") |
| 538 | except OSError: |
| 539 | pass |
| 540 | return result |
| 541 | |
| 542 | |
| 543 | def status() -> dict[str, Any]: |
| 544 | """Return offline, zero-subprocess status snapshot for ``doctor``.""" |
| 545 | mode = engine_mode() |
| 546 | expected = expected_skill_version() |
| 547 | asset = platform_asset_name() |
| 548 | if mode == "python": |
| 549 | return { |
| 550 | "mode": mode, |
| 551 | "state": "disabled", |
| 552 | "active": False, |
| 553 | "verified": False, |
| 554 | "binary_path": None, |
| 555 | "installed_version": None, |
| 556 | "expected_version": expected, |
| 557 | "platform_asset": asset, |
| 558 | "fallback": "python", |
| 559 | "detail": "LAST30DAYS_ENGINE=python", |
| 560 | } |
| 561 | bin_path = find_binary() |
| 562 | if bin_path is None: |
| 563 | return { |
| 564 | "mode": mode, |
| 565 | "state": "not_installed", |
| 566 | "active": False, |
| 567 | "verified": False, |
| 568 | "binary_path": None, |
| 569 | "installed_version": None, |
| 570 | "expected_version": expected, |
| 571 | "platform_asset": asset, |
| 572 | "fallback": "python", |
| 573 | "detail": None, |
| 574 | } |
| 575 | path_obj = Path(bin_path) |
| 576 | stamped = _read_stamp(path_obj.parent / _VERSION_STAMP_NAME) if path_obj == install_bin_path() else None |
| 577 | with _POOL._lock: |
| 578 | disabled = mode == "auto" and _POOL._disabled_for_bin == bin_path |
| 579 | verified_live = _POOL._verified_bin == bin_path |
| 580 | last_error = _POOL._last_error |
| 581 | if disabled: |
| 582 | return { |
| 583 | "mode": mode, |
| 584 | "state": "disabled_after_error", |
| 585 | "active": False, |
| 586 | "verified": False, |
| 587 | "binary_path": bin_path, |
| 588 | "installed_version": stamped, |
| 589 | "expected_version": expected, |
| 590 | "platform_asset": asset, |
| 591 | "fallback": "python", |
| 592 | "detail": last_error or "worker disabled after runtime failure", |
| 593 | } |
| 594 | verified = verified_live or (path_obj == install_bin_path() and stamped is not None) |
| 595 | return { |
| 596 | "mode": mode, |
| 597 | "state": "active" if verified else "discovered_unverified", |
| 598 | "active": verified, |
| 599 | "verified": verified, |
| 600 | "binary_path": bin_path, |
| 601 | "installed_version": stamped, |
| 602 | "expected_version": expected, |
| 603 | "platform_asset": asset, |
| 604 | "fallback": None if verified else "python (unverified)", |
| 605 | "detail": None if verified else "binary discovered on disk; protocol not yet verified", |
| 606 | } |
| 607 | |
| 608 | |
| 609 | class _WorkerPool: |
| 610 | """Process-local, thread-safe persistent stdio worker with bounded I/O.""" |
| 611 | |
| 612 | def __init__(self) -> None: |
| 613 | self._lock = threading.Lock() |
| 614 | self._proc: subprocess.Popen[bytes] | None = None |
| 615 | self._bin_path: str | None = None |
| 616 | self._pid: int = os.getpid() |
| 617 | self._disabled_for_bin: str | None = None |
| 618 | self._verified_bin: str | None = None |
| 619 | self._last_error: str | None = None |
| 620 | self._read_buf = bytearray() |
| 621 | |
| 622 | @staticmethod |
| 623 | def _terminate_proc( |
| 624 | proc: subprocess.Popen[bytes] | None, |
| 625 | *, |
| 626 | force: bool = False, |
| 627 | ) -> None: |
| 628 | if proc is None: |
| 629 | return |
| 630 | for stream in (proc.stdin, proc.stdout): |
| 631 | if stream is not None: |
| 632 | try: |
| 633 | stream.close() |
| 634 | except OSError: |
| 635 | pass |
| 636 | if force: |
| 637 | try: |
| 638 | proc.kill() |
| 639 | proc.wait(timeout=0.5) |
| 640 | except (OSError, subprocess.TimeoutExpired): |
| 641 | pass |
| 642 | return |
| 643 | try: |
| 644 | proc.terminate() |
| 645 | proc.wait(timeout=0.5) |
| 646 | except (OSError, subprocess.TimeoutExpired): |
| 647 | try: |
| 648 | proc.kill() |
| 649 | proc.wait(timeout=0.5) |
| 650 | except (OSError, subprocess.TimeoutExpired): |
| 651 | pass |
| 652 | |
| 653 | def _reset_locked(self, *, force: bool = False) -> None: |
| 654 | proc = self._proc |
| 655 | self._proc = None |
| 656 | self._bin_path = None |
| 657 | self._read_buf.clear() |
| 658 | self._terminate_proc(proc, force=force) |
| 659 | |
| 660 | def shutdown(self) -> None: |
| 661 | acquired = self._lock.acquire(timeout=0.2) |
| 662 | if acquired: |
| 663 | try: |
| 664 | self._reset_locked() |
| 665 | finally: |
| 666 | self._lock.release() |
| 667 | else: |
| 668 | # Another thread is mid-roundtrip; kill the worker directly so |
| 669 | # interpreter exit never deadlocks waiting for self._lock. |
| 670 | self._terminate_proc(self._proc, force=True) |
| 671 | |
| 672 | def _ensure_started_locked( |
| 673 | self, |
| 674 | bin_path: str, |
| 675 | timeout: float, |
| 676 | ) -> subprocess.Popen[bytes]: |
| 677 | current_pid = os.getpid() |
| 678 | if self._pid != current_pid: |
| 679 | # Forked child: drop parent handle without touching parent's child process. |
| 680 | self._proc = None |
| 681 | self._bin_path = None |
| 682 | self._pid = current_pid |
| 683 | self._disabled_for_bin = None |
| 684 | self._verified_bin = None |
| 685 | self._last_error = None |
| 686 | self._read_buf.clear() |
| 687 | |
| 688 | if self._proc is not None and self._proc.poll() is None and self._bin_path == bin_path: |
| 689 | return self._proc |
| 690 | |
| 691 | self._reset_locked() |
| 692 | proc = subprocess.Popen( |
| 693 | [bin_path, "serve"], |
| 694 | stdin=subprocess.PIPE, |
| 695 | stdout=subprocess.PIPE, |
| 696 | stderr=subprocess.DEVNULL, |
| 697 | bufsize=0, |
| 698 | ) |
| 699 | if os.name == "posix": |
| 700 | assert proc.stdin is not None and proc.stdout is not None |
| 701 | os.set_blocking(proc.stdin.fileno(), False) |
| 702 | os.set_blocking(proc.stdout.fileno(), False) |
| 703 | self._proc = proc |
| 704 | self._bin_path = bin_path |
| 705 | |
| 706 | # Handshake once on worker start to confirm protocol compatibility. |
| 707 | resp = self._roundtrip_locked(proc, {"op": "ping"}, timeout=min(5.0, timeout)) |
| 708 | if resp.get("status") != "ok" or resp.get("protocol") != PROTOCOL_VERSION: |
| 709 | self._reset_locked() |
| 710 | raise RustAccelError( |
| 711 | f"incompatible last30days-core binary at {bin_path}: {resp!r}" |
| 712 | ) |
| 713 | self._verified_bin = bin_path |
| 714 | self._last_error = None |
| 715 | return proc |
| 716 | |
| 717 | def _roundtrip_posix_locked( |
| 718 | self, |
| 719 | proc: subprocess.Popen[bytes], |
| 720 | data: bytes, |
| 721 | timeout: float, |
| 722 | ) -> dict[str, Any]: |
| 723 | assert proc.stdin is not None and proc.stdout is not None |
| 724 | deadline = time.monotonic() + timeout |
| 725 | stdin_fd = proc.stdin.fileno() |
| 726 | stdout_fd = proc.stdout.fileno() |
| 727 | |
| 728 | view = memoryview(data) |
| 729 | written = 0 |
| 730 | while written < len(data): |
| 731 | remaining = deadline - time.monotonic() |
| 732 | if remaining <= 0: |
| 733 | raise TimeoutError( |
| 734 | f"last30days-core worker timed out after {timeout:.1f}s while writing request" |
| 735 | ) |
| 736 | _, writable, _ = select.select([], [stdin_fd], [], remaining) |
| 737 | if not writable: |
| 738 | raise TimeoutError( |
| 739 | f"last30days-core worker timed out after {timeout:.1f}s while writing request" |
| 740 | ) |
| 741 | try: |
| 742 | count = os.write(stdin_fd, view[written:]) |
| 743 | except BlockingIOError: |
| 744 | continue |
| 745 | if count == 0: |
| 746 | raise RustAccelError("last30days-core worker closed stdin unexpectedly") |
| 747 | written += count |
| 748 | |
| 749 | while True: |
| 750 | newline_idx = self._read_buf.find(b"\n") |
| 751 | if newline_idx != -1: |
| 752 | raw_line = bytes(self._read_buf[:newline_idx]) |
| 753 | del self._read_buf[: newline_idx + 1] |
| 754 | return json.loads(raw_line.decode("utf-8")) |
| 755 | remaining = deadline - time.monotonic() |
| 756 | if remaining <= 0: |
| 757 | raise TimeoutError( |
| 758 | f"last30days-core worker timed out after {timeout:.1f}s waiting for response" |
| 759 | ) |
| 760 | readable, _, _ = select.select([stdout_fd], [], [], remaining) |
| 761 | if not readable: |
| 762 | raise TimeoutError( |
| 763 | f"last30days-core worker timed out after {timeout:.1f}s waiting for response" |
| 764 | ) |
| 765 | try: |
| 766 | chunk = os.read(stdout_fd, 65536) |
| 767 | except BlockingIOError: |
| 768 | continue |
| 769 | if not chunk: |
| 770 | raise RustAccelError("last30days-core worker closed stdout unexpectedly") |
| 771 | self._read_buf.extend(chunk) |
| 772 | |
| 773 | def _roundtrip_threaded_locked( |
| 774 | self, |
| 775 | proc: subprocess.Popen[bytes], |
| 776 | data: bytes, |
| 777 | timeout: float, |
| 778 | ) -> dict[str, Any]: |
| 779 | assert proc.stdin is not None and proc.stdout is not None |
| 780 | result: dict[str, Any] = {} |
| 781 | error: list[BaseException] = [] |
| 782 | |
| 783 | def _worker() -> None: |
| 784 | try: |
| 785 | assert proc.stdin is not None and proc.stdout is not None |
| 786 | view = memoryview(data) |
| 787 | written = 0 |
| 788 | while written < len(data): |
| 789 | count = proc.stdin.write(view[written:]) |
| 790 | if not count: |
| 791 | raise RustAccelError("last30days-core worker closed stdin unexpectedly") |
| 792 | written += count |
| 793 | while True: |
| 794 | newline_idx = self._read_buf.find(b"\n") |
| 795 | if newline_idx != -1: |
| 796 | raw_line = bytes(self._read_buf[:newline_idx]) |
| 797 | del self._read_buf[: newline_idx + 1] |
| 798 | result["resp"] = json.loads(raw_line.decode("utf-8")) |
| 799 | return |
| 800 | chunk = proc.stdout.read(65536) |
| 801 | if not chunk: |
| 802 | raise RustAccelError("last30days-core worker closed stdout unexpectedly") |
| 803 | self._read_buf.extend(chunk) |
| 804 | except BaseException as exc: # noqa: BLE001 |
| 805 | error.append(exc) |
| 806 | |
| 807 | thread = threading.Thread(target=_worker, daemon=True) |
| 808 | thread.start() |
| 809 | thread.join(timeout=timeout) |
| 810 | if thread.is_alive(): |
| 811 | self._terminate_proc(proc, force=True) |
| 812 | thread.join(timeout=0.5) |
| 813 | raise TimeoutError( |
| 814 | f"last30days-core worker timed out after {timeout:.1f}s waiting for response" |
| 815 | ) |
| 816 | if error: |
| 817 | raise error[0] |
| 818 | return result["resp"] |
| 819 | |
| 820 | def _roundtrip_locked( |
| 821 | self, |
| 822 | proc: subprocess.Popen[bytes], |
| 823 | payload: dict[str, Any], |
| 824 | *, |
| 825 | timeout: float, |
| 826 | ) -> dict[str, Any]: |
| 827 | encoded = ( |
| 828 | json.dumps(payload, separators=(",", ":"), ensure_ascii=False) + "\n" |
| 829 | ).encode("utf-8") |
| 830 | if os.name == "posix": |
| 831 | return self._roundtrip_posix_locked(proc, encoded, timeout) |
| 832 | return self._roundtrip_threaded_locked(proc, encoded, timeout) |
| 833 | |
| 834 | def call(self, payload: dict[str, Any]) -> dict[str, Any] | None: |
| 835 | mode = engine_mode() |
| 836 | if mode == "python": |
| 837 | return None |
| 838 | |
| 839 | bin_path = find_binary() |
| 840 | if bin_path is None: |
| 841 | if mode == "rust": |
| 842 | raise RustAccelError( |
| 843 | "LAST30DAYS_ENGINE=rust requested, but no last30days-core binary was found" |
| 844 | ) |
| 845 | return None |
| 846 | |
| 847 | timeout = worker_timeout() |
| 848 | with self._lock: |
| 849 | if mode == "auto" and self._disabled_for_bin == bin_path: |
| 850 | return None |
| 851 | try: |
| 852 | proc = self._ensure_started_locked(bin_path, timeout) |
| 853 | resp = self._roundtrip_locked(proc, payload, timeout=timeout) |
| 854 | except TimeoutError as exc: |
| 855 | self._reset_locked(force=True) |
| 856 | if mode == "rust": |
| 857 | raise RustAccelError(f"last30days-core call failed: {exc}") from exc |
| 858 | self._disabled_for_bin = bin_path |
| 859 | self._verified_bin = None |
| 860 | self._last_error = str(exc) |
| 861 | return None |
| 862 | except (OSError, ValueError, RustAccelError) as exc: |
| 863 | self._reset_locked() |
| 864 | if mode == "rust": |
| 865 | raise RustAccelError(f"last30days-core call failed: {exc}") from exc |
| 866 | self._disabled_for_bin = bin_path |
| 867 | self._verified_bin = None |
| 868 | self._last_error = str(exc) |
| 869 | return None |
| 870 | |
| 871 | if resp.get("status") != "ok": |
| 872 | if mode == "rust": |
| 873 | raise RustAccelError(f"last30days-core error: {resp.get('message')}") |
| 874 | return None |
| 875 | return resp |
| 876 | |
| 877 | |
| 878 | _POOL = _WorkerPool() |
| 879 | atexit.register(_POOL.shutdown) |
| 880 | |
| 881 | |
| 882 | def shutdown() -> None: |
| 883 | """Stop any running background ``last30days-core`` worker.""" |
| 884 | _POOL.shutdown() |
| 885 | |
| 886 | |
| 887 | def is_available() -> bool: |
| 888 | """Return ``True`` if Rust acceleration is active and reachable.""" |
| 889 | if engine_mode() == "python": |
| 890 | return False |
| 891 | return _POOL.call({"op": "ping"}) is not None |
| 892 | |
| 893 | |
| 894 | def dedupe_kept_indices( |
| 895 | entries: list[dict[str, str]], |
| 896 | threshold: float, |
| 897 | ) -> list[int] | None: |
| 898 | """Run pass-2 fuzzy near-duplicate filtering in Rust, returning kept indices.""" |
| 899 | resp = _POOL.call( |
| 900 | { |
| 901 | "op": "dedupe_indices", |
| 902 | "entries": entries, |
| 903 | "threshold": threshold, |
| 904 | } |
| 905 | ) |
| 906 | if resp is None: |
| 907 | return None |
| 908 | return resp["indices"] |
| 909 | |
| 910 | |
| 911 | def annotate_stream( |
| 912 | items: list[dict[str, Any]], |
| 913 | ranking_query: str, |
| 914 | freshness_mode: str, |
| 915 | reference_date: str, |
| 916 | max_days: int, |
| 917 | ) -> list[dict[str, Any]] | None: |
| 918 | """Run batch relevance, freshness, and engagement annotation in Rust.""" |
| 919 | resp = _POOL.call( |
| 920 | { |
| 921 | "op": "annotate_stream", |
| 922 | "items": items, |
| 923 | "ranking_query": ranking_query, |
| 924 | "freshness_mode": freshness_mode, |
| 925 | "reference_date": reference_date, |
| 926 | "max_days": max_days, |
| 927 | } |
| 928 | ) |
| 929 | if resp is None: |
| 930 | return None |
| 931 | return resp["items"] |
| 932 | |
| 933 | |
| 934 | def cluster_candidates( |
| 935 | candidates: list[dict[str, Any]], |
| 936 | plan: dict[str, str], |
| 937 | ) -> list[dict[str, Any]] | None: |
| 938 | """Run greedy clustering, MMR representative selection, and entity merging in Rust.""" |
| 939 | resp = _POOL.call( |
| 940 | { |
| 941 | "op": "cluster_candidates", |
| 942 | "candidates": candidates, |
| 943 | "plan": plan, |
| 944 | } |
| 945 | ) |
| 946 | if resp is None: |
| 947 | return None |
| 948 | return resp["clusters"] |
| 949 | |
| 950 | |
| 951 | def public_markdown(markdown: str) -> str | None: |
| 952 | """Run ``library.public_markdown`` privacy redaction in Rust.""" |
| 953 | resp = _POOL.call({"op": "public_markdown", "markdown": markdown}) |
| 954 | if resp is None: |
| 955 | return None |
| 956 | return resp["markdown"] |
| 957 | |
| 958 | |
| 959 | def has_private_corpus(markdown: str) -> bool | None: |
| 960 | """Run ``library.has_private_corpus`` detection in Rust.""" |
| 961 | resp = _POOL.call({"op": "has_private_corpus", "markdown": markdown}) |
| 962 | if resp is None: |
| 963 | return None |
| 964 | return bool(resp["value"]) |
| 965 | |
| 966 | |
| 967 | def is_unbounded_private_brief( |
| 968 | markdown: str, |
| 969 | source_format: str | None = None, |
| 970 | ) -> bool | None: |
| 971 | """Run ``library.is_unbounded_private_brief`` check in Rust.""" |
| 972 | resp = _POOL.call( |
| 973 | { |
| 974 | "op": "is_unbounded_private_brief", |
| 975 | "markdown": markdown, |
| 976 | "source_format": source_format, |
| 977 | } |
| 978 | ) |
| 979 | if resp is None: |
| 980 | return None |
| 981 | return bool(resp["value"]) |
| 982 | |
| 983 | |
| 984 | def sanitize_markdown_batch(items: list[dict[str, Any]]) -> list[dict[str, Any]] | None: |
| 985 | """Sanitize and fingerprint a batch of Markdown strings in parallel in Rust.""" |
| 986 | resp = _POOL.call({"op": "sanitize_markdown_batch", "items": items}) |
| 987 | if resp is None: |
| 988 | return None |
| 989 | return resp["results"] |
| 990 | |
| 991 | |
| 992 | def scan_markdown_files(requests: list[dict[str, Any]]) -> list[dict[str, Any]] | None: |
| 993 | """Read, sanitize, parse metadata, and fingerprint saved Markdown files in parallel.""" |
| 994 | resp = _POOL.call({"op": "scan_markdown_files", "requests": requests}) |
| 995 | if resp is None: |
| 996 | return None |
| 997 | return resp["outcomes"] |
| 998 |