skill-lens-cli 0.1.0__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.
Files changed (41) hide show
  1. skill_lens/__init__.py +3 -0
  2. skill_lens/cli.py +326 -0
  3. skill_lens/core/__init__.py +1 -0
  4. skill_lens/core/compare.py +172 -0
  5. skill_lens/core/diff.py +503 -0
  6. skill_lens/core/discovery.py +562 -0
  7. skill_lens/core/doctor.py +464 -0
  8. skill_lens/core/exitcodes.py +151 -0
  9. skill_lens/core/hasher.py +117 -0
  10. skill_lens/core/parser.py +311 -0
  11. skill_lens/core/paths.py +130 -0
  12. skill_lens/core/resolver.py +607 -0
  13. skill_lens/core/scanner.py +230 -0
  14. skill_lens/core/system.py +96 -0
  15. skill_lens/models/__init__.py +73 -0
  16. skill_lens/models/compare.py +104 -0
  17. skill_lens/models/diff.py +231 -0
  18. skill_lens/models/doctor.py +98 -0
  19. skill_lens/models/enums.py +84 -0
  20. skill_lens/models/installation.py +74 -0
  21. skill_lens/models/parsing.py +105 -0
  22. skill_lens/models/resolution.py +108 -0
  23. skill_lens/py.typed +0 -0
  24. skill_lens/registry/__init__.py +14 -0
  25. skill_lens/registry/agents/antigravity.toml +50 -0
  26. skill_lens/registry/agents/claude.toml +34 -0
  27. skill_lens/registry/agents/codex.toml +64 -0
  28. skill_lens/registry/agents/dsh.toml +93 -0
  29. skill_lens/registry/agents/grok.toml +37 -0
  30. skill_lens/registry/agents/omp.toml +84 -0
  31. skill_lens/registry/agents/opencode.toml +48 -0
  32. skill_lens/registry/agents/pi.toml +48 -0
  33. skill_lens/registry/agents/qoder.toml +38 -0
  34. skill_lens/registry/agents/windsurf.toml +38 -0
  35. skill_lens/registry/loader.py +128 -0
  36. skill_lens/render.py +464 -0
  37. skill_lens_cli-0.1.0.dist-info/METADATA +296 -0
  38. skill_lens_cli-0.1.0.dist-info/RECORD +41 -0
  39. skill_lens_cli-0.1.0.dist-info/WHEEL +4 -0
  40. skill_lens_cli-0.1.0.dist-info/entry_points.txt +2 -0
  41. skill_lens_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,464 @@
1
+ """``skill-lens doctor``: hygiene and ecosystem-health findings.
2
+
3
+ Pure diagnostics -- no Rich, no writes, no repairs. Like the rest of the
4
+ engine the module takes a finished :class:`~skill_lens.core.discovery.
5
+ DiscoveryIndex` (or builds one) and emits frozen models; the walk it reports
6
+ on already swallowed every per-directory ``OSError`` into tagged unreadable
7
+ roots, so nothing here can crash on a hostile home folder.
8
+
9
+ Provenance rule (AGENTS.md rule 6): every finding carries its ``rule_id`` and
10
+ ``evidence`` level. Checks that rest on vendor documentation -- only the Codex
11
+ context budget -- are tagged ``documented`` with their source; everything else
12
+ here is observed on disk and tagged ``empirical``.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from skill_lens.core import paths
21
+ from skill_lens.core.discovery import DiscoveredEntry, DiscoveryIndex, discover
22
+ from skill_lens.core.system import (
23
+ ERR_MISSING_FILE,
24
+ ERR_NOT_JSON,
25
+ installer_lockfile,
26
+ live_discovery,
27
+ read_json_guarded,
28
+ shared_library,
29
+ )
30
+ from skill_lens.models.doctor import DoctorFinding, DoctorReport
31
+ from skill_lens.models.enums import Evidence, ParseStatus, Severity
32
+ from skill_lens.models.parsing import (
33
+ ERR_DANGLING_SYMLINK,
34
+ ERR_PERMISSION_DENIED,
35
+ ERR_SYMLINK_CYCLE,
36
+ )
37
+
38
+ #: Codex prepends every skill description to the model context. Vendor docs
39
+ #: describe a budget of roughly 8,000 characters; past it Codex is documented
40
+ #: to omit skills silently. Source: https://developers.openai.com/codex/skills
41
+ #: (spec section 6, check 4). Module-level so tests can lower the threshold.
42
+ CODEX_CONTEXT_BUDGET_CHARS = 8_000
43
+
44
+ #: The agent whose context budget is known to be shared across skill
45
+ #: descriptions. Others are excluded until they document the same mechanism.
46
+ _BUDGET_AGENT = "codex"
47
+
48
+ #: Any path component named this is a traversal hazard: agent search rules
49
+ #: that recurse through installed dependency trees pick up third-party skill
50
+ #: files nobody authored (spec section 6, check 5 -- observed live).
51
+ _TRAVERSAL_MARKER = "node_modules"
52
+
53
+ #: Discovery's symlink error tag -> (finding code, message clause). The engine
54
+ #: only translates tags it already saw, so a new tag needs a row here -- and
55
+ #: the ERROR severity is deliberate: an entrypoint that reaches nothing is
56
+ #: exactly as un-loadable as a malformed file, whatever the reason.
57
+ _SYMLINK_CLAUSES = {
58
+ ERR_DANGLING_SYMLINK: ("dangling_symlink", "links to a target that does not exist"),
59
+ ERR_SYMLINK_CYCLE: ("symlink_cycle", "is part of a symlink loop"),
60
+ }
61
+
62
+
63
+ def build_doctor_report(
64
+ home: Path,
65
+ cwd: Path,
66
+ index: DiscoveryIndex | None = None,
67
+ registry: Any | None = None,
68
+ ) -> DoctorReport:
69
+ """Run every hygiene check over one discovery pass.
70
+
71
+ ``index`` lets callers reuse the walk ``scan`` already paid for; when it
72
+ is ``None`` a live discovery runs first. Order of findings is fixed
73
+ (errors, then warnings, then info) so output is stable across runs.
74
+ """
75
+ discovery = index if index is not None else discover(home, cwd, registry)
76
+
77
+ findings: list[DoctorFinding] = []
78
+ findings.extend(_symlink_findings(discovery))
79
+ findings.extend(_frontmatter_findings(discovery))
80
+ findings.extend(_unreadable_findings(discovery))
81
+ findings.extend(_codex_budget_findings(discovery))
82
+ findings.extend(_traversal_findings(discovery))
83
+ findings.extend(_farm_findings(discovery))
84
+ findings.extend(_lockfile_findings(home))
85
+ findings.extend(_registry_evidence_findings(registry))
86
+
87
+ findings.sort(key=_severity_order)
88
+ return DoctorReport(home=str(home), cwd=str(cwd), findings=tuple(findings))
89
+
90
+
91
+ def _severity_order(finding: DoctorFinding) -> tuple[int, str, str]:
92
+ rank = {Severity.ERROR: 0, Severity.WARNING: 1, Severity.INFO: 2}[finding.severity]
93
+ return (rank, finding.code, finding.path or "")
94
+
95
+
96
+ def _entrypoint(entry: DiscoveredEntry) -> str:
97
+ """The path to show: the entrypoint as written, collapsed to ``~``."""
98
+ return paths.display(entry.entrypoint_path)
99
+
100
+
101
+ def _symlink_findings(index: DiscoveryIndex) -> list[DoctorFinding]:
102
+ """Broken links, cycles, and refusals: an entrypoint that reaches nothing (❌).
103
+
104
+ Discovery already tagged every symlink it could not resolve -- this only
105
+ groups those tags into findings, so a link that is broken for one agent
106
+ is never judged healthy by another. A refusal comes in two shapes: the
107
+ link's *target* is off-limits (``ERR_PERMISSION_DENIED`` on the entry) or
108
+ the path resolves but the file inside is refused (an ``UNREADABLE`` parse
109
+ -- how a chmod-000 skill directory under a readable root arrives). Same
110
+ finding either way: the agent cannot open this skill.
111
+ """
112
+ findings: list[DoctorFinding] = []
113
+ for entry in index.entries:
114
+ code = entry.error_code
115
+ detail: str | None = code
116
+ if code in _SYMLINK_CLAUSES:
117
+ finding_code, clause = _SYMLINK_CLAUSES[code]
118
+ elif code == ERR_PERMISSION_DENIED:
119
+ finding_code, clause = ("unreadable_skill", "exists but the OS refuses to open it")
120
+ elif entry.parse is not None and entry.parse.status is ParseStatus.UNREADABLE:
121
+ finding_code, clause = ("unreadable_skill", "exists but the OS refuses to open it")
122
+ detail = ERR_PERMISSION_DENIED
123
+ else:
124
+ continue
125
+ shown = _entrypoint(entry)
126
+ findings.append(
127
+ DoctorFinding(
128
+ code=finding_code,
129
+ severity=Severity.ERROR,
130
+ message=f"'{shown}' {clause} -- {_reached_by(entry)} cannot load '{entry.name}'.",
131
+ rule_id="doctor_symlink_health",
132
+ evidence=Evidence.EMPIRICAL,
133
+ path=shown,
134
+ detail=detail,
135
+ )
136
+ )
137
+ return findings
138
+
139
+
140
+ def _reached_by(entry: DiscoveredEntry) -> str:
141
+ agents = sorted({hit.agent_id for hit in entry.hits})
142
+ return ", ".join(agents) if agents else "no agent"
143
+
144
+
145
+ def _frontmatter_findings(index: DiscoveryIndex) -> list[DoctorFinding]:
146
+ """Skills whose document will be rejected by any parser (❌).
147
+
148
+ Discovery resolves the frontmatter state per *canonical target*; several
149
+ agents reach it through the farm, so one finding names the library and
150
+ lists who is affected.
151
+ """
152
+ findings: list[DoctorFinding] = []
153
+ for entry in index.entries:
154
+ status = entry.parse.status if entry.parse else None
155
+ if status is ParseStatus.MALFORMED_YAML:
156
+ message = (
157
+ f"'{_entrypoint(entry)}' has no readable YAML frontmatter"
158
+ f" -- {_reached_by(entry)} will skip '{entry.name}'."
159
+ )
160
+ elif status is ParseStatus.MISSING_DESCRIPTION:
161
+ message = (
162
+ f"'{_entrypoint(entry)}' is missing the required 'description' field"
163
+ f" -- {_reached_by(entry)} will skip '{entry.name}'."
164
+ )
165
+ else:
166
+ continue
167
+ findings.append(
168
+ DoctorFinding(
169
+ code="malformed_frontmatter",
170
+ severity=Severity.ERROR,
171
+ message=message,
172
+ rule_id="doctor_frontmatter",
173
+ evidence=Evidence.EMPIRICAL,
174
+ path=_entrypoint(entry),
175
+ detail=(status.value if status else None),
176
+ )
177
+ )
178
+ return findings
179
+
180
+
181
+ def _unreadable_findings(index: DiscoveryIndex) -> list[DoctorFinding]:
182
+ """Roots macOS TCC (or mode bits) refuse to list (⚠️).
183
+
184
+ This is the one finding a user cannot fix with their skills: the folder
185
+ is there, agents are configured to read it, and the operating system says
186
+ no. Full paths are intentional -- ``paths.display`` collapses to ``~``
187
+ only when it is the *effective* home, so the report states exactly which
188
+ directory was refused.
189
+ """
190
+ findings: list[DoctorFinding] = []
191
+ for root in index.unreadable_roots:
192
+ findings.append(
193
+ DoctorFinding(
194
+ code="unreadable_root",
195
+ severity=Severity.WARNING,
196
+ message=(
197
+ f"{root.agent_id}'s search path '{paths.display(root.path)}' "
198
+ "exists but cannot be read (macOS privacy protection or file "
199
+ "permissions) -- skills there are invisible to Skill Lens."
200
+ ),
201
+ rule_id="doctor_tcc",
202
+ evidence=Evidence.EMPIRICAL,
203
+ path=root.path,
204
+ detail=root.detail,
205
+ )
206
+ )
207
+ return findings
208
+
209
+
210
+ def _codex_budget_findings(index: DiscoveryIndex) -> list[DoctorFinding]:
211
+ """The Codex context-budget check (⚠️, documented).
212
+
213
+ Sums the description length of every *valid* skill description Codex
214
+ reaches (any scope: personal, shared farm, project, system). Invalid
215
+ skills are skipped by Codex itself, so they consume no budget and are
216
+ honestly excluded -- the finding says what was counted.
217
+ """
218
+ total = 0
219
+ counted = 0
220
+ for entry in index.entries:
221
+ if not any(hit.agent_id == _BUDGET_AGENT for hit in entry.hits):
222
+ continue
223
+ if entry.parse is None or entry.parse.status is not ParseStatus.VALID:
224
+ continue
225
+ if entry.parse.description:
226
+ total += len(entry.parse.description)
227
+ counted += 1
228
+ if total <= CODEX_CONTEXT_BUDGET_CHARS:
229
+ return []
230
+ over = total - CODEX_CONTEXT_BUDGET_CHARS
231
+ return [
232
+ DoctorFinding(
233
+ code="codex_context_budget",
234
+ severity=Severity.WARNING,
235
+ message=(
236
+ f"{counted} Codex-reachable skill descriptions total {total:,} characters, "
237
+ f"about {over:,} over the ~{CODEX_CONTEXT_BUDGET_CHARS:,} documented budget "
238
+ "-- Codex may silently omit some skills."
239
+ ),
240
+ rule_id="doctor_codex_context_budget",
241
+ evidence=Evidence.DOCUMENTED,
242
+ detail=f"https://developers.openai.com/codex/skills; counted={total}",
243
+ )
244
+ ]
245
+
246
+
247
+ def _traversal_findings(index: DiscoveryIndex) -> list[DoctorFinding]:
248
+ """Recursive roots that walk through dependency trees (⚠️).
249
+
250
+ Observed live: a recursive plugin/profile root descended into
251
+ ``node_modules`` and surfaced third-party skills nobody installed on
252
+ purpose. One finding per agent that saw such an entrypoint.
253
+
254
+ Scope note: discovery only descends into directories named ``skills``
255
+ (spec section 5 forbids unbounded crawls), so a ``SKILL.md`` inside
256
+ ``node_modules`` that is *not* under a ``skills/`` folder is never even
257
+ collected -- the hazard this check reports is a recursive ``skills``
258
+ root punching through a dependency tree, the realistic live shape.
259
+ """
260
+ findings: list[DoctorFinding] = []
261
+ seen: set[tuple[str, str]] = set()
262
+ for entry in index.entries:
263
+ if _TRAVERSAL_MARKER not in Path(entry.entrypoint_path).parts:
264
+ continue
265
+ for hit in entry.hits:
266
+ key = (hit.agent_id, hit.root_id)
267
+ if key in seen:
268
+ continue
269
+ seen.add(key)
270
+ findings.append(
271
+ DoctorFinding(
272
+ code="traversal_hazard",
273
+ severity=Severity.WARNING,
274
+ message=(
275
+ f"{hit.agent_id}'s root '{hit.root_id}' recursed through a "
276
+ f"'{_TRAVERSAL_MARKER}' tree and found '{entry.name}' -- "
277
+ "third-party skill files may load unintentionally."
278
+ ),
279
+ rule_id="doctor_traversal_hazard",
280
+ evidence=Evidence.EMPIRICAL,
281
+ path=paths.display(entry.entrypoint_path),
282
+ detail=_TRAVERSAL_MARKER,
283
+ )
284
+ )
285
+ return findings
286
+
287
+
288
+ def _farm_findings(index: DiscoveryIndex) -> list[DoctorFinding]:
289
+ """Symlink farm health (info).
290
+
291
+ The ecosystem pattern is one shared library (``~/.agents/skills``) linked
292
+ into each agent's folder. A skill is "farmed" when its canonical target
293
+ sits in that library and agents reach it through symlinked entrypoints
294
+ stored elsewhere. This states the numbers plainly: N farmed skills behind
295
+ K links. It is informational -- a farm is healthy by design -- but it
296
+ explains why the same skill shows up under several agents in ``scan``.
297
+ """
298
+ # Resolve the library to a canonical path or a symlinked home (macOS
299
+ # ``/tmp`` is ``/private/tmp``) would compare two spellings of one place.
300
+ library = str(shared_library(Path(index.home)).resolve())
301
+ farmed = 0
302
+ link_count = 0
303
+ for entry in index.entries:
304
+ canonical = entry.canonical_path
305
+ if not canonical or not _under(canonical, library):
306
+ continue
307
+ links = [
308
+ path
309
+ for path in (entry.entrypoint_paths or (entry.entrypoint_path,))
310
+ if Path(path).is_symlink() and not _under(path, library)
311
+ ]
312
+ if not links:
313
+ continue
314
+ farmed += 1
315
+ link_count += len(links)
316
+ if not farmed:
317
+ return []
318
+ return [
319
+ DoctorFinding(
320
+ code="symlink_farm",
321
+ severity=Severity.INFO,
322
+ message=(
323
+ f"{farmed} skills are shared through symlink farms "
324
+ f"({link_count} links point into one library) -- that is the "
325
+ "installer's normal layout, not a defect."
326
+ ),
327
+ rule_id="doctor_symlink_farm",
328
+ evidence=Evidence.EMPIRICAL,
329
+ detail=f"library={paths.display(library)}",
330
+ )
331
+ ]
332
+
333
+
334
+ def _under(path_str: str, parent_str: str) -> bool:
335
+ """True when ``path_str`` sits inside ``parent_str`` (component-safe)."""
336
+ try:
337
+ Path(path_str).relative_to(parent_str)
338
+ except ValueError:
339
+ return False
340
+ return True
341
+
342
+
343
+ def _lockfile_findings(home: Path) -> list[DoctorFinding]:
344
+ """Installer lockfile status (ℹ️, or ⚠️ when unparseable).
345
+
346
+ ``~/.agents/.skill-lock.json`` records how the shared library was
347
+ installed. Missing is normal (no installer ever ran); invalid JSON means
348
+ an installer wrote garbage and will mis-read it later, which is worth a
349
+ warning; a readable file gets an informational line so the user knows
350
+ Skill Lens saw it.
351
+ """
352
+ lockfile = installer_lockfile(home)
353
+ value, error = read_json_guarded(lockfile)
354
+ shown = paths.display(lockfile)
355
+ if error == ERR_MISSING_FILE:
356
+ return [
357
+ DoctorFinding(
358
+ code="installer_lockfile",
359
+ severity=Severity.INFO,
360
+ message=f"No installer lockfile at '{shown}' (normal if you never ran one).",
361
+ rule_id="doctor_installer_lockfile",
362
+ evidence=Evidence.EMPIRICAL,
363
+ path=shown,
364
+ detail=ERR_MISSING_FILE,
365
+ )
366
+ ]
367
+ if error == ERR_PERMISSION_DENIED:
368
+ return [
369
+ DoctorFinding(
370
+ code="installer_lockfile",
371
+ severity=Severity.WARNING,
372
+ message=f"'{shown}' exists but cannot be read (file permissions).",
373
+ rule_id="doctor_installer_lockfile",
374
+ evidence=Evidence.EMPIRICAL,
375
+ path=shown,
376
+ detail=error,
377
+ )
378
+ ]
379
+ if error == ERR_NOT_JSON:
380
+ return [
381
+ DoctorFinding(
382
+ code="installer_lockfile",
383
+ severity=Severity.WARNING,
384
+ message=f"'{shown}' is not valid JSON -- the installer may mis-read it.",
385
+ rule_id="doctor_installer_lockfile",
386
+ evidence=Evidence.EMPIRICAL,
387
+ path=shown,
388
+ detail=ERR_NOT_JSON,
389
+ )
390
+ ]
391
+ entries = len(value) if isinstance(value, (list, dict)) else 0
392
+ return [
393
+ DoctorFinding(
394
+ code="installer_lockfile",
395
+ severity=Severity.INFO,
396
+ message=f"Installer lockfile '{shown}' parses cleanly ({entries} top-level keys).",
397
+ rule_id="doctor_installer_lockfile",
398
+ evidence=Evidence.EMPIRICAL,
399
+ path=shown,
400
+ detail="ok",
401
+ )
402
+ ]
403
+
404
+
405
+ def _registry_evidence_findings(registry: Any | None = None) -> list[DoctorFinding]:
406
+ """Report agents whose behaviour Skill Lens cannot cite (ℹ️).
407
+
408
+ Every other check in this module reports something about the *user's* setup.
409
+ This one reports something about *ours*: an agent whose precedence Skill Lens
410
+ had to infer, because no primary documentation could be found for it. Any
411
+ resolution reported for such an agent is an informed guess rather than a
412
+ verified answer, and the user is entitled to know that before trusting it.
413
+
414
+ Only ``inferred`` agents are reported. ``empirical`` means somebody observed
415
+ the real behaviour, which is genuine evidence even without a vendor doc, and
416
+ ``documented`` is a citation. Reporting those would cry wolf on every agent
417
+ in the registry and teach the user to ignore the check.
418
+
419
+ Severity is ``info`` deliberately. This is a limitation of our knowledge,
420
+ not a fault on the user's disk, so it must never make ``--fail-on warning``
421
+ or ``--fail-on error`` trip. It shows up under ``--fail-on info`` alongside
422
+ genuine informational notes.
423
+
424
+ With the registry as shipped today this returns nothing, because every agent
425
+ is either documented or empirically verified. That is the intended quiet
426
+ state: the check exists to catch a regression, and a guard that is always
427
+ loud is a guard nobody reads.
428
+ """
429
+ from skill_lens.registry.loader import list_agents # noqa: PLC0415
430
+
431
+ definitions = list_agents()
432
+ if registry is not None:
433
+ # ``load_registry`` returns {id: AgentDefinition}; iterating that
434
+ # directly yields the *keys*, so take the values explicitly.
435
+ items = registry.values() if isinstance(registry, dict) else registry
436
+ definitions = sorted(items, key=lambda agent: agent.id)
437
+
438
+ uncited = sorted(
439
+ agent.id for agent in definitions if agent.policy_evidence is Evidence.INFERRED
440
+ )
441
+ if not uncited:
442
+ return []
443
+ listed = ", ".join(uncited)
444
+ return [
445
+ DoctorFinding(
446
+ code="registry_uncited_agent",
447
+ severity=Severity.INFO,
448
+ message=(
449
+ f"Skill Lens cannot cite primary documentation for {len(uncited)} "
450
+ f"agent(s): {listed}. Their precedence is inferred, so treat "
451
+ "resolution for them as an informed guess."
452
+ ),
453
+ rule_id="doctor_registry_evidence",
454
+ evidence=Evidence.INFERRED,
455
+ path=None,
456
+ detail=f"uncited={','.join(uncited)}",
457
+ )
458
+ ]
459
+
460
+
461
+ def run_doctor(cwd: Path | None = None) -> DoctorReport:
462
+ """One-call entry point used by the CLI: live discovery, then report."""
463
+ discovery = live_discovery(cwd)
464
+ return build_doctor_report(Path(discovery.home), Path(discovery.cwd), discovery)
@@ -0,0 +1,151 @@
1
+ """Exit-code policy: when a finished report should fail the process.
2
+
3
+ This module is deliberately pure. It decides *only* whether a set of findings
4
+ reached the caller's threshold, and returns the integer a shell should see. It
5
+ does not know about Typer, Rich, the filesystem, or any command. ``cli.py``
6
+ turns the result into ``typer.Exit``; nothing else decides an exit code.
7
+
8
+ The contract, in one place:
9
+
10
+ ===== ==========================================================
11
+ Code Meaning
12
+ ===== ==========================================================
13
+ ``0`` The command ran and nothing reached the threshold.
14
+ ``1`` The command ran and findings reached the threshold.
15
+ ``2`` The command could not run: bad usage, unknown agent,
16
+ unreadable input. Already the pre-Phase-6 behaviour for
17
+ ``why`` and ``compare``.
18
+ ``3`` Reserved for an unexpected internal fault. Never emitted
19
+ deliberately; it exists so a future bug does not have to
20
+ invent a meaning that collides with the codes above.
21
+ ===== ==========================================================
22
+
23
+ Why the default is ``NEVER``
24
+ ----------------------------
25
+
26
+ Every Skill Lens command exited ``0`` before this module existed, including
27
+ ``doctor`` on a machine with real errors. That is the right default for a report
28
+ you read and the wrong default for a check you automate. Since a report is the
29
+ common case and a gate is opt-in, ``NEVER`` preserves existing behaviour exactly
30
+ and ``--fail-on`` is what turns the tool into a gate. Changing the default later
31
+ would silently break anyone's CI, so it is not changed later.
32
+
33
+ A threshold is a *comparison*, never a count: ``--fail-on error`` fails when any
34
+ finding is at ``error``, regardless of how many informational notes sit beside
35
+ it. Counting would make the exit status depend on unrelated noise.
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ from enum import IntEnum, StrEnum
41
+
42
+ from skill_lens.models.enums import Severity
43
+
44
+
45
+ class ExitCode(IntEnum):
46
+ """Process exit statuses. Values are the integers shells actually see.
47
+
48
+ ``IntEnum`` rather than ``StrEnum``: these *are* integers, a shell compares
49
+ them numerically, and ``StrEnum`` would refuse to hold them. They are never
50
+ serialized into the JSON reports, so there is no string form to preserve.
51
+ """
52
+
53
+ OK = 0
54
+ """The command ran and nothing reached the threshold."""
55
+
56
+ FINDINGS = 1
57
+ """The command ran and findings reached the threshold."""
58
+
59
+ USAGE = 2
60
+ """The command could not run: bad usage or an unknown agent."""
61
+
62
+ INTERNAL = 3
63
+ """Reserved for an unexpected internal fault."""
64
+
65
+
66
+ class FailOn(StrEnum):
67
+ """Which severity turns a finished report into a failed run."""
68
+
69
+ NEVER = "never"
70
+ """Always exit 0. The default, and the pre-Phase-6 behaviour."""
71
+
72
+ ERROR = "error"
73
+ """Fail when any finding is an ``error``."""
74
+
75
+ WARNING = "warning"
76
+ """Fail when any finding is an ``error`` or a ``warning``."""
77
+
78
+ INFO = "info"
79
+ """Fail when any finding exists at all, informational notes included."""
80
+
81
+
82
+ #: Ordering used for both "at or above" comparisons and ``info`` as the floor.
83
+ _SEVERITY_RANK: dict[Severity, int] = {
84
+ Severity.ERROR: 0,
85
+ Severity.WARNING: 1,
86
+ Severity.INFO: 2,
87
+ }
88
+
89
+ #: The threshold each ``--fail-on`` value sets, or ``None`` for ``never``.
90
+ _THRESHOLD: dict[FailOn, Severity | None] = {
91
+ FailOn.NEVER: None,
92
+ FailOn.ERROR: Severity.ERROR,
93
+ FailOn.WARNING: Severity.WARNING,
94
+ FailOn.INFO: Severity.INFO,
95
+ }
96
+
97
+ _FAIL_ON_HELP = (
98
+ "Lowest severity that makes the command exit "
99
+ f"{int(ExitCode.FINDINGS)} instead of {int(ExitCode.OK)}."
100
+ )
101
+
102
+ #: Appended to the help text so ``--fail-on info`` cannot mislead anyone.
103
+ #:
104
+ #: ``info`` looks like the strictest setting and is, but it is also effectively
105
+ #: unusable as a gate: ``doctor`` emits informational notes about *normal* setups
106
+ #: (an absent installer lockfile, a symlink farm that is the installer's normal
107
+ #: layout). A completely empty home already produces one, so ``--fail-on info``
108
+ #: fails everywhere. Saying so here is cheaper than letting someone discover it
109
+ #: as a broken pipeline.
110
+ _FAIL_ON_CAVEAT = (
111
+ " Note: 'info' also trips on routine informational notes that describe a "
112
+ "healthy setup, so it fails on almost any machine; use 'error' or 'warning' "
113
+ "for a gate."
114
+ )
115
+
116
+
117
+ def fail_on_help() -> str:
118
+ """The ``--fail-on`` help text, including the valid values.
119
+
120
+ Kept beside the enum so the CLI cannot drift from the vocabulary it accepts.
121
+ """
122
+ values = ", ".join(option.value for option in FailOn)
123
+ return f"{_FAIL_ON_HELP} One of: {values}.{_FAIL_ON_CAVEAT}"
124
+
125
+
126
+ def exit_code_for(severities: tuple[Severity, ...] | list[Severity], fail_on: FailOn) -> ExitCode:
127
+ """Return the exit status for a finished run.
128
+
129
+ ``severities`` is the severity of every finding the report contains, in any
130
+ order. ``fail_on`` is the caller's threshold.
131
+
132
+ An empty report always succeeds, whatever the threshold: "nothing was wrong"
133
+ is never a reason to fail, and a gate that fails on an empty report would be
134
+ unusable.
135
+ """
136
+ threshold = _THRESHOLD[fail_on]
137
+ if threshold is None:
138
+ return ExitCode.OK
139
+ # "At or above" in Skill Lens means *more severe than* the threshold, and
140
+ # lower ranks are more severe.
141
+ #
142
+ # An empty report needs no special case: ``any()`` over nothing is False, so
143
+ # a clean run already returns OK at every threshold. That behaviour is
144
+ # asserted by the Phase 6 gate; it is a property of the comparison, not of a
145
+ # guard here. An earlier version had an explicit ``not severities`` branch,
146
+ # which mutation testing showed could be deleted with every test still
147
+ # green -- dead code that looks like protection is worse than none.
148
+ cutoff = _SEVERITY_RANK[threshold]
149
+ if any(_SEVERITY_RANK[severity] <= cutoff for severity in severities):
150
+ return ExitCode.FINDINGS
151
+ return ExitCode.OK