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,117 @@
1
+ """Streaming SHA-256 content fingerprinting.
2
+
3
+ Rules from the specification (section 4):
4
+
5
+ * Sorted relative file paths, always with forward slashes ``/``.
6
+ * Text files are decoded as UTF-8 with ``\\r\\n`` normalised to ``\\n``.
7
+ * Binary files are hashed raw, byte for byte.
8
+ * The **entire** file is streamed in chunks (no truncation, no prefix false
9
+ positives).
10
+ * ``.git/``, ``.DS_Store`` and AppleDouble ``._*`` entries are ignored.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+ import os
17
+ from pathlib import Path
18
+ from typing import TYPE_CHECKING
19
+
20
+ if TYPE_CHECKING:
21
+ from hashlib import _Hash
22
+
23
+ HASH_PREFIX = "sha256:"
24
+ _CHUNK_SIZE = 64 * 1024
25
+ _IGNORED_DIRS = frozenset({".git"})
26
+ _IGNORED_FILES = frozenset({".DS_Store"})
27
+
28
+
29
+ def _is_ignored(relative: Path) -> bool:
30
+ """True for paths the fingerprint must skip (VCS, macOS metadata)."""
31
+ if any(part in _IGNORED_DIRS for part in relative.parts):
32
+ return True
33
+ name = relative.name
34
+ return name in _IGNORED_FILES or name.startswith("._")
35
+
36
+
37
+ def iter_files(root: Path) -> list[Path]:
38
+ """Return the hashable files under ``root`` in sorted, stable order.
39
+
40
+ Only relative paths are returned, sorted as POSIX strings so the same tree
41
+ fingerprints identically on macOS and Linux.
42
+ """
43
+ collected: list[Path] = []
44
+ for dirpath, dirnames, filenames in os.walk(root):
45
+ dirnames[:] = sorted(d for d in dirnames if d not in _IGNORED_DIRS)
46
+ for filename in sorted(filenames):
47
+ candidate = Path(dirpath) / filename
48
+ relative = candidate.relative_to(root)
49
+ if not _is_ignored(relative):
50
+ collected.append(relative)
51
+ collected.sort(key=lambda p: p.as_posix())
52
+ return collected
53
+
54
+
55
+ def _update_text(hasher: _Hash, path: Path) -> None:
56
+ """Stream ``path`` as UTF-8 text, normalising ``\\r\\n`` across chunks."""
57
+ pending_cr = False
58
+ with path.open("r", encoding="utf-8", newline="") as handle:
59
+ while True:
60
+ chunk = handle.read(_CHUNK_SIZE)
61
+ if not chunk:
62
+ break
63
+ if pending_cr:
64
+ chunk = "\r" + chunk
65
+ pending_cr = False
66
+ if chunk.endswith("\r"):
67
+ chunk = chunk[:-1]
68
+ pending_cr = True
69
+ hasher.update(chunk.replace("\r\n", "\n").encode("utf-8"))
70
+ if pending_cr:
71
+ hasher.update(b"\r")
72
+
73
+
74
+ def _update_binary(hasher: _Hash, path: Path) -> None:
75
+ with path.open("rb") as handle:
76
+ while True:
77
+ chunk = handle.read(_CHUNK_SIZE)
78
+ if not chunk:
79
+ break
80
+ hasher.update(chunk)
81
+
82
+
83
+ def hash_file(path: Path) -> str:
84
+ """Fingerprint a single file, choosing text or binary handling.
85
+
86
+ UTF-8 decodability decides: decodable files are newline-normalised as text;
87
+ anything else is hashed as raw bytes.
88
+ """
89
+ text_hasher = hashlib.sha256()
90
+ try:
91
+ _update_text(text_hasher, path)
92
+ except UnicodeDecodeError:
93
+ binary_hasher = hashlib.sha256()
94
+ _update_binary(binary_hasher, path)
95
+ return HASH_PREFIX + binary_hasher.hexdigest()
96
+ return HASH_PREFIX + text_hasher.hexdigest()
97
+
98
+
99
+ def hash_directory(root: Path) -> str:
100
+ """Fingerprint an entire skill directory.
101
+
102
+ Combines sorted relative paths with each file's own content hash, so a
103
+ rename, an added file or an edited file all change the fingerprint.
104
+ """
105
+ hasher = hashlib.sha256()
106
+ for relative in iter_files(root):
107
+ posix = relative.as_posix()
108
+ file_hash = hash_file(root / relative)
109
+ hasher.update(f"{posix}\0{file_hash}\n".encode())
110
+ return HASH_PREFIX + hasher.hexdigest()
111
+
112
+
113
+ def hash_path(path: Path) -> str:
114
+ """Fingerprint a file or a directory, dispatching on the real type."""
115
+ if path.is_dir():
116
+ return hash_directory(path)
117
+ return hash_file(path)
@@ -0,0 +1,311 @@
1
+ """Frontmatter parsing, identity extraction and symlink canonicalization.
2
+
3
+ This module is intentionally free of any agent-specific precedence logic --
4
+ that is the resolver's job (Phase 2). Here we only answer two questions:
5
+
6
+ 1. *What does this skill document say about itself?* (parsing + identity)
7
+ 2. *What real thing does this entrypoint point at?* (canonicalization)
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import stat
14
+ from pathlib import Path
15
+
16
+ import yaml
17
+
18
+ from skill_lens.models.enums import ParseStatus
19
+ from skill_lens.models.parsing import (
20
+ ERR_DANGLING_SYMLINK,
21
+ ERR_MALFORMED_YAML,
22
+ ERR_MISSING_DESCRIPTION,
23
+ ERR_MISSING_FRONTMATTER,
24
+ ERR_PERMISSION_DENIED,
25
+ ERR_SYMLINK_CYCLE,
26
+ ERR_UNDECODABLE_TEXT,
27
+ CanonicalResult,
28
+ CanonicalStatus,
29
+ ParseResult,
30
+ )
31
+
32
+ FRONTMATTER_DELIM = "---"
33
+ _SKILL_FILENAMES = ("SKILL.md", "skill.md")
34
+
35
+
36
+ # --- Discovery -------------------------------------------------------------
37
+
38
+
39
+ def find_skill_document(entrypoint: Path) -> Path | None:
40
+ """Locate the markdown document for an entrypoint.
41
+
42
+ Supports both directory skills (``name/SKILL.md``) and Antigravity's
43
+ standalone file skills (``name.md``). Returns ``None`` when neither exists.
44
+
45
+ The filesystem probes are guarded: on Python < 3.14 ``is_file()`` on a path
46
+ inside a directory the OS refuses to open raises ``PermissionError``
47
+ (newer versions return ``False``). Swallowing it here makes the answer
48
+ version-independent; the caller still classifies such an entrypoint as
49
+ ``UNREADABLE`` through :func:`is_unreadable_directory`, so a blocked skill
50
+ is reported rather than dropped or allowed to crash the walk.
51
+ """
52
+ try:
53
+ if entrypoint.is_dir():
54
+ for filename in _SKILL_FILENAMES:
55
+ candidate = entrypoint / filename
56
+ if candidate.is_file():
57
+ return candidate
58
+ return None
59
+ if entrypoint.is_file() and entrypoint.suffix.lower() == ".md":
60
+ return entrypoint
61
+ except OSError:
62
+ return None
63
+ return None
64
+
65
+
66
+ def split_frontmatter(text: str) -> tuple[str | None, str]:
67
+ """Split a document into ``(frontmatter_text, body)``.
68
+
69
+ ``frontmatter_text`` is ``None`` when the document does not open with a
70
+ ``---`` fence, or when the closing fence is missing. A leading UTF-8 BOM
71
+ is tolerated.
72
+ """
73
+ stripped = text.lstrip("\ufeff")
74
+ if not stripped.startswith(FRONTMATTER_DELIM):
75
+ return None, stripped
76
+
77
+ lines = stripped.splitlines()
78
+ # The first line must be exactly the delimiter (allow trailing whitespace).
79
+ if lines[0].strip() != FRONTMATTER_DELIM:
80
+ return None, stripped
81
+
82
+ for index in range(1, len(lines)):
83
+ if lines[index].strip() == FRONTMATTER_DELIM:
84
+ frontmatter = "\n".join(lines[1:index])
85
+ body = "\n".join(lines[index + 1 :])
86
+ if body and not body.endswith("\n"):
87
+ body += "\n"
88
+ return frontmatter, body
89
+ return None, stripped
90
+
91
+
92
+ def _coerce_description(value: object) -> str | None:
93
+ """Normalise a description value into a non-empty string, or ``None``."""
94
+ if isinstance(value, str):
95
+ cleaned = value.strip()
96
+ return cleaned or None
97
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
98
+ return str(value)
99
+ return None
100
+
101
+
102
+ def parse_skill_document(path: Path) -> ParseResult:
103
+ """Parse one skill document into a :class:`ParseResult`.
104
+
105
+ Never raises: unreadable files become ``UNREADABLE`` results so a single
106
+ bad file can never abort a scan.
107
+ """
108
+ directory_name = path.parent.name if path.name.lower() in _SKILL_FILENAMES else path.stem
109
+
110
+ try:
111
+ raw = path.read_text(encoding="utf-8")
112
+ except UnicodeDecodeError:
113
+ return ParseResult(
114
+ status=ParseStatus.UNREADABLE,
115
+ directory_name=directory_name,
116
+ body="",
117
+ source_path=str(path),
118
+ errors=(ERR_UNDECODABLE_TEXT,),
119
+ )
120
+ except OSError:
121
+ return ParseResult(
122
+ status=ParseStatus.UNREADABLE,
123
+ directory_name=directory_name,
124
+ body="",
125
+ source_path=str(path),
126
+ errors=(ERR_PERMISSION_DENIED,),
127
+ )
128
+
129
+ frontmatter_text, body = split_frontmatter(raw)
130
+ if frontmatter_text is None:
131
+ return ParseResult(
132
+ status=ParseStatus.MALFORMED_YAML,
133
+ directory_name=directory_name,
134
+ body=body,
135
+ source_path=str(path),
136
+ errors=(ERR_MISSING_FRONTMATTER,),
137
+ )
138
+
139
+ try:
140
+ loaded = yaml.safe_load(frontmatter_text)
141
+ except yaml.YAMLError:
142
+ return ParseResult(
143
+ status=ParseStatus.MALFORMED_YAML,
144
+ directory_name=directory_name,
145
+ body=body,
146
+ source_path=str(path),
147
+ errors=(ERR_MALFORMED_YAML,),
148
+ )
149
+
150
+ if not isinstance(loaded, dict):
151
+ return ParseResult(
152
+ status=ParseStatus.MALFORMED_YAML,
153
+ directory_name=directory_name,
154
+ body=body,
155
+ source_path=str(path),
156
+ errors=(ERR_MALFORMED_YAML,),
157
+ )
158
+
159
+ frontmatter = {str(key): value for key, value in loaded.items()}
160
+ name_value = loaded.get("name")
161
+ frontmatter_name = (
162
+ str(name_value).strip() if isinstance(name_value, (str, int, float)) else None
163
+ )
164
+ if not frontmatter_name:
165
+ frontmatter_name = None
166
+
167
+ description = _coerce_description(loaded.get("description"))
168
+ if description is None:
169
+ return ParseResult(
170
+ status=ParseStatus.MISSING_DESCRIPTION,
171
+ directory_name=directory_name,
172
+ body=body,
173
+ frontmatter_name=frontmatter_name,
174
+ source_path=str(path),
175
+ errors=(ERR_MISSING_DESCRIPTION,),
176
+ frontmatter=frontmatter,
177
+ )
178
+
179
+ return ParseResult(
180
+ status=ParseStatus.VALID,
181
+ directory_name=directory_name,
182
+ body=body,
183
+ frontmatter_name=frontmatter_name,
184
+ description=description,
185
+ source_path=str(path),
186
+ frontmatter=frontmatter,
187
+ )
188
+
189
+
190
+ def parse_skill(entrypoint: Path) -> ParseResult | None:
191
+ """Discover and parse the document behind ``entrypoint``.
192
+
193
+ Returns ``None`` when the entrypoint holds no skill document at all. A
194
+ directory that exists but cannot be listed (e.g. blocked by macOS TCC) is
195
+ reported as ``UNREADABLE`` rather than silently dropped.
196
+ """
197
+ document = find_skill_document(entrypoint)
198
+ if document is None:
199
+ if is_unreadable_directory(entrypoint):
200
+ return ParseResult(
201
+ status=ParseStatus.UNREADABLE,
202
+ directory_name=entrypoint.name,
203
+ body="",
204
+ source_path=str(entrypoint),
205
+ errors=(ERR_PERMISSION_DENIED,),
206
+ )
207
+ return None
208
+ return parse_skill_document(document)
209
+
210
+
211
+ def is_unreadable_directory(path: Path) -> bool:
212
+ """True when ``path`` is a directory that cannot be listed.
213
+
214
+ Used to record permission-blocked roots (macOS TCC) as ``unreadable``
215
+ instead of failing the whole walk.
216
+ """
217
+ if not path.is_dir():
218
+ return False
219
+ try:
220
+ os.listdir(path)
221
+ except OSError:
222
+ return True
223
+ return False
224
+
225
+
226
+ # --- Symlink canonicalization ---------------------------------------------
227
+
228
+
229
+ def _physical(path: Path) -> str:
230
+ """The fully resolved physical path, normalized.
231
+
232
+ A symlink farm commonly uses *relative* targets
233
+ (``~/.pi/agent/skills/../.agents/skills/x``), so the walked path still
234
+ contains ``..`` segments. Without normalization every agent's link into the
235
+ same shared library yields a different string, and the library stops being
236
+ reported as one canonical skill with N entrypoints. ``realpath`` also
237
+ resolves any remaining symlinked parent directories.
238
+ """
239
+ return os.path.realpath(str(path))
240
+
241
+
242
+ def canonicalize(entrypoint: Path) -> CanonicalResult:
243
+ """Follow ``entrypoint`` to its real target, guarding against cycles.
244
+
245
+ Only **symlink** nodes are tracked (via ``lstat``), so a legitimate chain
246
+ that ends at a real directory reports ``OK`` while a circular chain of
247
+ links is caught and reported as ``CYCLE`` instead of hanging. Broken links
248
+ report ``BROKEN``; permission failures report ``UNREADABLE``.
249
+ """
250
+ path = Path(entrypoint)
251
+ is_symlink = path.is_symlink()
252
+ visited: set[tuple[int, int]] = set()
253
+
254
+ for _ in range(64): # hard stop; real chains are far shorter
255
+ try:
256
+ link_stat = path.lstat()
257
+ except FileNotFoundError:
258
+ return CanonicalResult(
259
+ status=CanonicalStatus.BROKEN,
260
+ entrypoint_path=str(entrypoint),
261
+ resolved_path=None,
262
+ is_symlink=is_symlink,
263
+ error=ERR_DANGLING_SYMLINK,
264
+ )
265
+ except OSError:
266
+ return CanonicalResult(
267
+ status=CanonicalStatus.UNREADABLE,
268
+ entrypoint_path=str(entrypoint),
269
+ resolved_path=None,
270
+ is_symlink=is_symlink,
271
+ error=ERR_PERMISSION_DENIED,
272
+ )
273
+
274
+ if not stat.S_ISLNK(link_stat.st_mode):
275
+ return CanonicalResult(
276
+ status=CanonicalStatus.OK,
277
+ entrypoint_path=str(entrypoint),
278
+ resolved_path=_physical(path),
279
+ is_symlink=is_symlink,
280
+ )
281
+
282
+ key = (link_stat.st_dev, link_stat.st_ino)
283
+ if key in visited:
284
+ return CanonicalResult(
285
+ status=CanonicalStatus.CYCLE,
286
+ entrypoint_path=str(entrypoint),
287
+ resolved_path=None,
288
+ is_symlink=is_symlink,
289
+ error=ERR_SYMLINK_CYCLE,
290
+ )
291
+ visited.add(key)
292
+
293
+ try:
294
+ target = os.readlink(path)
295
+ except OSError:
296
+ return CanonicalResult(
297
+ status=CanonicalStatus.UNREADABLE,
298
+ entrypoint_path=str(entrypoint),
299
+ resolved_path=None,
300
+ is_symlink=True,
301
+ error=ERR_PERMISSION_DENIED,
302
+ )
303
+ path = Path(target) if os.path.isabs(target) else path.parent / target
304
+
305
+ return CanonicalResult(
306
+ status=CanonicalStatus.CYCLE,
307
+ entrypoint_path=str(entrypoint),
308
+ resolved_path=None,
309
+ is_symlink=is_symlink,
310
+ error=ERR_SYMLINK_CYCLE,
311
+ )
@@ -0,0 +1,130 @@
1
+ """Lazy, call-time environment and path resolution.
2
+
3
+ Golden rule: **never** expand ``~`` or read ``$HOME`` at import time. Every
4
+ function here resolves environment state on each call so tests can freely
5
+ monkeypatch ``HOME`` / ``XDG_CONFIG_HOME`` and so ``--sandbox`` can redirect
6
+ the entire tool at a mock home directory.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ from pathlib import Path
13
+
14
+ # Populated by ``use_sandbox`` (the ``--sandbox`` CLI flag). When set, every
15
+ # path helper resolves relative to this mock home instead of the real one.
16
+ _SANDBOX: Path | None = None
17
+
18
+
19
+ def _resolved(path: Path) -> Path:
20
+ """Resolve ``path`` without raising on a refusal or a symlink loop.
21
+
22
+ ``Path.resolve()`` raises ``RuntimeError`` -- *not* ``OSError`` -- for a
23
+ symlink loop on Python 3.11/3.12; Python 3.13+ stops at the loop instead of
24
+ raising. Catching both keeps output and sandbox checks identical on every
25
+ supported version, which is exactly the kind of cross-version divergence
26
+ that made the first CI run fail.
27
+ """
28
+ try:
29
+ return path.resolve()
30
+ except (OSError, RuntimeError):
31
+ return path
32
+
33
+
34
+ def set_sandbox(root: str | os.PathLike[str] | None) -> None:
35
+ """Redirect all path resolution into ``root`` (a mock ``$HOME``).
36
+
37
+ Passing ``None`` clears the sandbox and restores real-environment
38
+ resolution. This is the single switch used by tests and safe demos.
39
+ """
40
+ global _SANDBOX
41
+ _SANDBOX = _resolved(Path(root).expanduser()) if root is not None else None
42
+
43
+
44
+ def get_sandbox() -> Path | None:
45
+ """Return the active sandbox root, or ``None`` when unset."""
46
+ return _SANDBOX
47
+
48
+
49
+ def home() -> Path:
50
+ """Resolve the effective home directory at call time."""
51
+ if _SANDBOX is not None:
52
+ return _SANDBOX
53
+ return Path(os.environ.get("HOME", "~")).expanduser()
54
+
55
+
56
+ def xdg_config_home() -> Path:
57
+ """Resolve ``$XDG_CONFIG_HOME``, defaulting to ``~/.config`` at call time."""
58
+ env = os.environ.get("XDG_CONFIG_HOME")
59
+ if env:
60
+ return Path(env).expanduser()
61
+ return home() / ".config"
62
+
63
+
64
+ def terminal_cwd() -> Path:
65
+ """The folder the user is standing in, for the default ``--cwd``.
66
+
67
+ Under a sandbox the real terminal folder is meaningless -- it would point
68
+ outside the mock home and let a sandboxed run read the real filesystem --
69
+ so the sandbox root is used instead. Resolved at call time, never at import.
70
+ """
71
+ if _SANDBOX is not None:
72
+ return _SANDBOX
73
+ try:
74
+ return Path.cwd()
75
+ except OSError: # pragma: no cover - deleted cwd is vanishingly rare
76
+ return home()
77
+
78
+
79
+ def resolve(*parts: str | os.PathLike[str]) -> Path:
80
+ """Join ``parts`` onto the effective home directory (lazy, not expanded)."""
81
+ path = home()
82
+ for part in parts:
83
+ path = path / part
84
+ return path
85
+
86
+
87
+ def _home_variants() -> tuple[Path, ...]:
88
+ """The effective home as written, and as fully resolved.
89
+
90
+ A home directory can sit behind a symlink (macOS ``/tmp`` is
91
+ ``/private/tmp``). ``canonicalize()`` returns resolved paths while
92
+ entrypoints keep the path as written, so both forms are needed to collapse
93
+ either one to ``~``.
94
+ """
95
+ root = home()
96
+ resolved = _resolved(root)
97
+ return (root,) if resolved == root else (root, resolved)
98
+
99
+
100
+ def display(path: str | os.PathLike[str]) -> str:
101
+ """Render ``path`` with the effective home collapsed to ``~`` for output.
102
+
103
+ Keeps terminal output readable without ever exposing full absolute paths
104
+ for the common case. Both sides are tried as-written and fully resolved,
105
+ so a path reached through a symlinked home still collapses.
106
+ """
107
+ target = Path(path)
108
+ resolved = _resolved(target)
109
+ targets = (target,) if resolved == target else (target, resolved)
110
+ for root in _home_variants():
111
+ for candidate in targets:
112
+ try:
113
+ relative = candidate.relative_to(root)
114
+ except ValueError:
115
+ continue
116
+ return "~" if relative == Path(".") else f"~/{relative}"
117
+ return str(target)
118
+
119
+
120
+ def same_location(left: str | os.PathLike[str], right: str | os.PathLike[str]) -> bool:
121
+ """True when two paths name the same place on disk.
122
+
123
+ Compares resolved paths, so an entrypoint and its canonical target are
124
+ recognised as one file even when one of them still carries symlinked
125
+ parent directories.
126
+ """
127
+ try:
128
+ return Path(left).resolve() == Path(right).resolve()
129
+ except (OSError, RuntimeError): # pragma: no cover - unresolvable path
130
+ return False