sim-cli-core 0.2.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sim/compat.py ADDED
@@ -0,0 +1,411 @@
1
+ """Loader for per-driver `compatibility.yaml` files.
2
+
3
+ Each driver ships a `compatibility.yaml` next to its `driver.py`. This
4
+ module parses that file into a small typed surface (`Profile`,
5
+ `Compatibility`) and answers three questions:
6
+
7
+ 1. Given a detected solver version, which profile applies?
8
+ 2. What profiles does sim-cli know about across all drivers?
9
+ 3. For a given profile, which sim-skills overlay layers are active?
10
+
11
+ It is intentionally a **metadata catalogue**, not a runtime. sim-cli
12
+ runs every driver in its own process — compat.yaml exists so the CLI
13
+ can tell users which profile applies to a detected solver version and
14
+ so the skills layer can resolve a profile to its (sdk, solver)
15
+ overlay paths.
16
+
17
+ ## Plugin awareness
18
+
19
+ Driver registry entries point at packages (built-in
20
+ ``sim.drivers.<name>`` or external ``sim_plugin_<name>``). For both,
21
+ ``compatibility.yaml`` lives at the package root and is loaded via
22
+ ``importlib.resources`` so wheel-installed plugins work the same as
23
+ in-tree built-ins. ``load_compatibility_by_name(name)`` is the
24
+ plugin-aware entry point; ``load_compatibility(driver_dir)`` remains
25
+ for path-based callers and tests.
26
+
27
+ Public surface:
28
+ load_compatibility_by_name(name) -> Compatibility | None
29
+ load_compatibility(driver_dir) -> Compatibility (legacy, path-based)
30
+ Compatibility.resolve(solver_version) -> Profile | None
31
+ Compatibility.profile_by_name(name) -> Profile | None
32
+ find_profile(name) -> (driver, Profile) | None
33
+ all_known_profiles() -> list[(driver, Profile)]
34
+ safe_detect_installed(driver) -> list
35
+
36
+ Skills layering surface:
37
+ find_skills_root() -> Path | None
38
+ verify_skills_layout(root, profiles=None) -> list[str]
39
+ skills_block_for_profile(driver, profile) -> dict
40
+ """
41
+ from __future__ import annotations
42
+
43
+ import os
44
+ from dataclasses import dataclass
45
+ from functools import lru_cache
46
+ from importlib import resources as _resources
47
+ from pathlib import Path
48
+ from typing import Iterable
49
+
50
+ import yaml
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class Profile:
55
+ """A named (SDK pin, solver version list) tuple from compatibility.yaml.
56
+
57
+ `sdk` is optional: solvers like OpenFOAM have no Python SDK to pin.
58
+
59
+ `active_sdk_layer` and `active_solver_layer` declare which sub-folders
60
+ under `<sim-skills>/<driver>/sdk/` and `<sim-skills>/<driver>/solver/`
61
+ apply to this profile. Both are optional — SDK-less drivers leave
62
+ `active_sdk_layer` unset, drivers with no version-sensitive solver
63
+ content leave `active_solver_layer` unset. The `base/` overlay is
64
+ always active and needs no field.
65
+ """
66
+ name: str
67
+ solver_versions: tuple[str, ...]
68
+ sdk: str | None = None
69
+ notes: str = ""
70
+ active_sdk_layer: str | None = None
71
+ active_solver_layer: str | None = None
72
+
73
+ def matches_solver(self, solver_version: str) -> bool:
74
+ return _normalize_solver_version(solver_version) in self.solver_versions
75
+
76
+ def to_dict(self) -> dict:
77
+ return {
78
+ "name": self.name,
79
+ "sdk": self.sdk,
80
+ "solver_versions": list(self.solver_versions),
81
+ "notes": self.notes.strip(),
82
+ "active_sdk_layer": self.active_sdk_layer,
83
+ "active_solver_layer": self.active_solver_layer,
84
+ }
85
+
86
+
87
+ @dataclass(frozen=True)
88
+ class Compatibility:
89
+ """Parsed compatibility.yaml for one driver."""
90
+ driver: str
91
+ profiles: tuple[Profile, ...]
92
+ sdk_package: str | None = None
93
+
94
+ def profile_by_name(self, name: str) -> Profile | None:
95
+ for p in self.profiles:
96
+ if p.name == name:
97
+ return p
98
+ return None
99
+
100
+ def resolve(self, solver_version: str) -> Profile | None:
101
+ """Return the first profile whose solver_versions contains V.
102
+
103
+ Profiles are walked in declaration order; if multiple match, the
104
+ first wins. Returns None when no profile matches.
105
+ """
106
+ normalized = _normalize_solver_version(solver_version)
107
+ for p in self.profiles:
108
+ if normalized in p.solver_versions:
109
+ return p
110
+ return None
111
+
112
+
113
+ def _normalize_solver_version(v: str) -> str:
114
+ """Coerce solver version strings into the canonical short form ('25.2').
115
+
116
+ Handles common variants:
117
+ "25.2" -> "25.2"
118
+ "25.2.0" -> "25.2"
119
+ "2025 R2" -> "25.2"
120
+ "v252" -> "25.2"
121
+ "252" -> "25.2"
122
+ """
123
+ if v is None:
124
+ return ""
125
+ s = str(v).strip()
126
+ if not s:
127
+ return ""
128
+
129
+ digits = "".join(ch for ch in s if ch.isdigit())
130
+ if len(digits) == 3 and ("v" + digits in s.lower() or s == digits):
131
+ return f"{digits[:2]}.{digits[2]}"
132
+
133
+ s_compact = s.replace(" ", "").lower()
134
+ if "r" in s_compact:
135
+ year_part, _, rel_part = s_compact.partition("r")
136
+ if year_part.isdigit() and rel_part.isdigit() and len(year_part) == 4:
137
+ return f"{year_part[2:]}.{rel_part}"
138
+
139
+ parts = s.split(".")
140
+ if len(parts) >= 2 and parts[0].isdigit() and parts[1].isdigit():
141
+ return f"{parts[0]}.{parts[1]}"
142
+
143
+ return s
144
+
145
+
146
+ def _registry_module_for(driver_name: str) -> str | None:
147
+ """Resolve a driver name to its package module path via the registry.
148
+
149
+ Returns the *module path* (e.g. ``"sim.drivers.coolprop"`` for built-ins
150
+ or ``"sim_plugin_coolprop"`` for external plugins). Returns None when
151
+ the driver isn't registered.
152
+
153
+ We import the registry lazily to avoid a circular import at module load
154
+ time — ``sim.drivers`` imports from ``sim.driver`` which imports from
155
+ nowhere; ``sim.compat`` is the higher layer.
156
+ """
157
+ from sim.drivers import _REGISTRY # local import — see docstring
158
+ for name, spec in _REGISTRY:
159
+ if name == driver_name:
160
+ module_path, _, _cls = spec.rpartition(":")
161
+ return module_path or None
162
+ return None
163
+
164
+
165
+ def load_compatibility_by_name(driver_name: str) -> "Compatibility | None":
166
+ """Plugin-aware ``compatibility.yaml`` loader.
167
+
168
+ Resolves ``driver_name`` to its package via the registry, then reads
169
+ ``compatibility.yaml`` from the package using ``importlib.resources``.
170
+ Works identically for built-in drivers (``sim.drivers.<name>``) and
171
+ external plugins (``sim_plugin_<name>``).
172
+
173
+ Returns None when:
174
+ * the driver isn't registered, OR
175
+ * its package has no ``compatibility.yaml`` (some drivers are
176
+ SDK-less / version-insensitive — e.g. simpy), OR
177
+ * the file is malformed (logged at WARNING in the future; silent
178
+ for now to match legacy behaviour).
179
+ """
180
+ module_path = _registry_module_for(driver_name)
181
+ if module_path is None:
182
+ return None
183
+ try:
184
+ traversable = _resources.files(module_path).joinpath("compatibility.yaml")
185
+ if not traversable.is_file():
186
+ return None
187
+ text = traversable.read_text(encoding="utf-8")
188
+ except (FileNotFoundError, ModuleNotFoundError, OSError):
189
+ return None
190
+ return _parse_compatibility_text(driver_name, text)
191
+
192
+
193
+ def find_profile(profile_name: str) -> tuple[str, "Profile"] | None:
194
+ """Find a profile by name across every registered driver."""
195
+ from sim.drivers import _REGISTRY # local import — see _registry_module_for
196
+ for driver_name, _spec in _REGISTRY:
197
+ compat = load_compatibility_by_name(driver_name)
198
+ if compat is None:
199
+ continue
200
+ prof = compat.profile_by_name(profile_name)
201
+ if prof is not None:
202
+ return compat.driver, prof
203
+ return None
204
+
205
+
206
+ def all_known_profiles() -> list[tuple[str, "Profile"]]:
207
+ """Enumerate every profile across every registered driver."""
208
+ from sim.drivers import _REGISTRY # local import — see _registry_module_for
209
+ out: list[tuple[str, Profile]] = []
210
+ for driver_name, _spec in _REGISTRY:
211
+ compat = load_compatibility_by_name(driver_name)
212
+ if compat is None:
213
+ continue
214
+ for p in compat.profiles:
215
+ out.append((compat.driver, p))
216
+ return out
217
+
218
+
219
+ def safe_detect_installed(driver) -> list:
220
+ """Call driver.detect_installed() defensively."""
221
+ method = getattr(driver, "detect_installed", None)
222
+ if method is None:
223
+ return []
224
+ try:
225
+ result = method()
226
+ return list(result) if result else []
227
+ except Exception:
228
+ return []
229
+
230
+
231
+ def _parse_compatibility_text(source_label: str, text: str) -> Compatibility:
232
+ """Parse a compatibility.yaml string into a Compatibility object.
233
+
234
+ ``source_label`` is used only in error messages (path, package, etc.).
235
+ Raises ``ValueError`` on malformed input. Trusts well-formed input; the
236
+ caller decides whether a missing file is an error.
237
+ """
238
+ raw = yaml.safe_load(text) or {}
239
+ if not isinstance(raw, dict):
240
+ raise ValueError(f"{source_label} top-level must be a mapping")
241
+
242
+ try:
243
+ driver = raw["driver"]
244
+ raw_profiles = raw.get("profiles") or []
245
+ except KeyError as e:
246
+ raise ValueError(f"{source_label} missing required field: {e}") from e
247
+
248
+ sdk_package = raw.get("sdk_package")
249
+
250
+ profiles: list[Profile] = []
251
+ for i, p in enumerate(raw_profiles):
252
+ if not isinstance(p, dict):
253
+ raise ValueError(f"{source_label} profile #{i} must be a mapping, not {type(p).__name__}")
254
+ try:
255
+ profiles.append(
256
+ Profile(
257
+ name=p["name"],
258
+ sdk=p.get("sdk"),
259
+ solver_versions=tuple(
260
+ _normalize_solver_version(v) for v in p["solver_versions"]
261
+ ),
262
+ notes=p.get("notes", "") or "",
263
+ active_sdk_layer=p.get("active_sdk_layer"),
264
+ active_solver_layer=p.get("active_solver_layer"),
265
+ )
266
+ )
267
+ except KeyError as e:
268
+ raise ValueError(
269
+ f"{source_label} profile #{i} missing required field: {e}"
270
+ ) from e
271
+
272
+ return Compatibility(
273
+ driver=driver,
274
+ sdk_package=sdk_package,
275
+ profiles=tuple(profiles),
276
+ )
277
+
278
+
279
+ @lru_cache(maxsize=64)
280
+ def load_compatibility(driver_dir: str | Path) -> Compatibility:
281
+ """Load and cache the compatibility.yaml for one driver directory.
282
+
283
+ Path-based loader retained for tests and any caller that already has
284
+ the directory in hand. Plugin-aware code should call
285
+ ``load_compatibility_by_name(driver_name)`` instead — that one resolves
286
+ via the registry and reads from the package's resources, which works
287
+ for wheel-installed plugins.
288
+ """
289
+ path = Path(driver_dir) / "compatibility.yaml"
290
+ if not path.is_file():
291
+ raise FileNotFoundError(
292
+ f"compatibility.yaml not found for driver at {driver_dir}"
293
+ )
294
+ return _parse_compatibility_text(str(path), path.read_text(encoding="utf-8"))
295
+
296
+
297
+ # ── Skills layering ─────────────────────────────────────────────────────────
298
+
299
+
300
+ _SKILLS_HINT = (
301
+ "set SIM_SKILLS_ROOT or place sim-skills/ next to sim-cli/"
302
+ )
303
+
304
+
305
+ def find_skills_root() -> Path | None:
306
+ """Locate the sim-skills root.
307
+
308
+ Probe order:
309
+ 1. ``SIM_SKILLS_ROOT`` env var (authoritative when set)
310
+ 2. ``../sim-skills`` sibling of the sim-cli checkout
311
+
312
+ Returns None when neither succeeds. The function never raises —
313
+ callers degrade gracefully by returning a hint to the user.
314
+ """
315
+ raw = os.environ.get("SIM_SKILLS_ROOT")
316
+ if raw:
317
+ p = Path(raw)
318
+ return p.resolve() if p.is_dir() else None
319
+
320
+ # this file lives at <sim-cli>/src/sim/compat.py
321
+ sibling = Path(__file__).resolve().parents[2].parent / "sim-skills"
322
+ return sibling.resolve() if sibling.is_dir() else None
323
+
324
+
325
+ def verify_skills_layout(
326
+ skills_root: Path,
327
+ profiles: Iterable[tuple[str, "Profile"]] | None = None,
328
+ ) -> list[str]:
329
+ """For every (driver, profile), verify the on-disk skills tree.
330
+
331
+ Checks per driver:
332
+ - ``<skills_root>/<driver>/SKILL.md`` exists
333
+ - ``<skills_root>/<driver>/base/`` exists
334
+
335
+ Checks per profile (only when the field is set):
336
+ - ``<skills_root>/<driver>/sdk/<active_sdk_layer>/`` exists
337
+ - ``<skills_root>/<driver>/solver/<active_solver_layer>/`` exists
338
+
339
+ Returns a list of human-readable mismatch lines. Empty list = healthy.
340
+ Pass `profiles=None` to walk every profile in every driver compat.yaml.
341
+ """
342
+ if profiles is None:
343
+ profiles = all_known_profiles()
344
+
345
+ mismatches: list[str] = []
346
+ seen_drivers: set[str] = set()
347
+
348
+ for driver_name, profile in profiles:
349
+ driver_dir = skills_root / driver_name
350
+
351
+ if driver_name not in seen_drivers:
352
+ seen_drivers.add(driver_name)
353
+ if not driver_dir.is_dir():
354
+ mismatches.append(
355
+ f"{driver_name}: missing driver dir {driver_dir}"
356
+ )
357
+ continue
358
+ if not (driver_dir / "SKILL.md").is_file():
359
+ mismatches.append(
360
+ f"{driver_name}: missing SKILL.md index at {driver_dir / 'SKILL.md'}"
361
+ )
362
+ if not (driver_dir / "base").is_dir():
363
+ mismatches.append(
364
+ f"{driver_name}: missing base/ overlay at {driver_dir / 'base'}"
365
+ )
366
+
367
+ if profile.active_sdk_layer:
368
+ sdk_dir = driver_dir / "sdk" / profile.active_sdk_layer
369
+ if not sdk_dir.is_dir():
370
+ mismatches.append(
371
+ f"{driver_name}/{profile.name}: missing sdk/{profile.active_sdk_layer}/ overlay"
372
+ )
373
+ if profile.active_solver_layer:
374
+ solver_dir = driver_dir / "solver" / profile.active_solver_layer
375
+ if not solver_dir.is_dir():
376
+ mismatches.append(
377
+ f"{driver_name}/{profile.name}: missing solver/{profile.active_solver_layer}/ overlay"
378
+ )
379
+
380
+ return mismatches
381
+
382
+
383
+ def skills_block_for_profile(driver: str, profile: "Profile | None") -> dict:
384
+ """Build the ``skills`` dict that ``/connect`` returns to the agent.
385
+
386
+ Always returns a dict with the four keys ``root``, ``index``,
387
+ ``active_sdk_layer``, ``active_solver_layer``. When the skills tree
388
+ can't be located, returns ``{root: None, index: None, ..., hint: str}``
389
+ so the LLM can produce a useful error message.
390
+ """
391
+ active_sdk = profile.active_sdk_layer if profile is not None else None
392
+ active_solver = profile.active_solver_layer if profile is not None else None
393
+
394
+ root = find_skills_root()
395
+ driver_dir = (root / driver) if root is not None else None
396
+
397
+ if driver_dir is None or not driver_dir.is_dir():
398
+ return {
399
+ "root": None,
400
+ "index": None,
401
+ "active_sdk_layer": active_sdk,
402
+ "active_solver_layer": active_solver,
403
+ "hint": _SKILLS_HINT,
404
+ }
405
+
406
+ return {
407
+ "root": str(driver_dir),
408
+ "index": str(driver_dir / "SKILL.md"),
409
+ "active_sdk_layer": active_sdk,
410
+ "active_solver_layer": active_solver,
411
+ }