Coverage for src / lilbee / core / system.py: 100%
39 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-06-28 01:01 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-06-28 01:01 +0000
1"""OS, environment, and platform helpers for lilbee."""
3import os
4import sys
5from pathlib import Path
7#: Directory name for a project-local lilbee knowledge base (sibling of ``.git/``).
8LOCAL_ROOT_DIRNAME = ".lilbee"
11def default_data_dir() -> Path:
12 """Return platform-appropriate data directory.
13 - macOS: ~/Library/Application Support/lilbee
14 - Windows: %LOCALAPPDATA%/lilbee
15 - Linux: ~/.local/share/lilbee (XDG_DATA_HOME)
16 """
17 if sys.platform == "darwin":
18 base = Path.home() / "Library" / "Application Support"
19 elif sys.platform == "win32":
20 base = Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local"))
21 else:
22 base = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share"))
23 return base / "lilbee"
26def find_local_root(start: Path | None = None) -> Path | None:
27 """Walk up from start (default: cwd) looking for a ``.lilbee/`` directory."""
28 start = start or Path.cwd()
29 for candidate in (start, *start.parents):
30 marker = candidate / LOCAL_ROOT_DIRNAME
31 if marker.is_dir():
32 return marker
33 return None
36def canonical_models_dir() -> Path:
37 """Return the shared models directory (always in the platform default, never per-project).
38 Multiple lilbee instances share this directory so models are downloaded once.
39 """
40 return default_data_dir() / "models"
43def is_ignored_dir(name: str, ignore_dirs: frozenset[str]) -> bool:
44 """Return True if a directory name should be skipped during traversal."""
45 return name.startswith(".") or name in ignore_dirs or name.endswith(".egg-info")
48_CTX_TIER_FLOOR = 8192
49_CTX_TIER_TABLE: tuple[tuple[int, int], ...] = (
50 # (total_bytes_threshold, target)
51 (64 * 1024**3, 24576),
52 (32 * 1024**3, 16384),
53 (16 * 1024**3, 12288),
54)
57def chat_ctx_target_for_total_bytes(total_bytes: int) -> int:
58 """Pick a chat_n_ctx_target from total host RAM (floor 8192, tiers at 16/32/64 GiB)."""
59 if total_bytes <= 0:
60 return _CTX_TIER_FLOOR
61 for threshold, target in _CTX_TIER_TABLE:
62 if total_bytes >= threshold:
63 return target
64 return _CTX_TIER_FLOOR
67def _read_total_memory_bytes() -> int:
68 """Total system RAM in bytes, or 0 when introspection is unavailable."""
69 try:
70 import psutil
72 return int(psutil.virtual_memory().total)
73 except Exception:
74 # psutil import or platform read failed; the caller falls back to the floor.
75 return 0
78def scaled_chat_ctx_target_default() -> int:
79 """Pick a chat_n_ctx_target from this host's total RAM at config-load time."""
80 return chat_ctx_target_for_total_bytes(_read_total_memory_bytes())