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,503 @@
1
+ """Unified-diff computation for ``skill-lens diff`` (Phase 3).
2
+
3
+ Pure by design: this module imports no ``rich``. It turns a
4
+ :class:`~skill_lens.core.discovery.DiscoveryIndex` into a
5
+ :class:`~skill_lens.models.diff.DiffReport`, and the terminal layer renders that
6
+ model and nothing else.
7
+
8
+ Three rules from the specification (section 6, command 5) drive the design:
9
+
10
+ * **One copy per canonical target.** The index is already deduplicated, so this
11
+ module never re-groups entrypoints. Two symlinks onto one target are one copy
12
+ and cannot produce a diff.
13
+ * **The fingerprint decides, not the raw bytes.** File comparison reuses
14
+ :func:`~skill_lens.core.hasher.hash_file`, which normalises ``\\r\\n`` to
15
+ ``\\n``. Two copies that differ only by line endings therefore share a content
16
+ hash and produce no diff -- a raw byte comparison here would contradict the
17
+ hash that ``scan`` and ``why`` report, which is exactly finding F-16.
18
+ * **Only the valid set is labelled.** A copy that fails frontmatter validation is
19
+ still a diff participant (a broken copy is usually the one worth looking at)
20
+ but gets no Variant letter and is never the baseline.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import difflib
26
+ from collections.abc import Sequence
27
+ from dataclasses import dataclass, replace
28
+ from pathlib import Path
29
+
30
+ from skill_lens.core.discovery import (
31
+ DiscoveredEntry,
32
+ DiscoveryIndex,
33
+ canonical_key,
34
+ discover,
35
+ entry_scope,
36
+ labels_for_entries,
37
+ )
38
+ from skill_lens.core.hasher import hash_file, iter_files
39
+ from skill_lens.models.diff import DiffChange, DiffCopy, DiffFile, DiffHunk, DiffReport
40
+ from skill_lens.models.enums import ParseStatus
41
+ from skill_lens.registry.loader import AgentDefinition, load_registry
42
+
43
+ #: Changed (``+`` / ``-``) lines shown per copy before the diff is truncated.
44
+ MAX_CHANGED_LINES_PER_COPY = 400
45
+ #: Characters of diff body shown across the whole report before truncating.
46
+ MAX_CHARS_PER_REPORT = 20_000
47
+ #: Context lines around each change, matching ``difflib.unified_diff``'s default.
48
+ CONTEXT_LINES = 3
49
+
50
+ #: The label :func:`~skill_lens.core.discovery.variant_labels` gives the copy
51
+ #: every other copy is compared against.
52
+ BASELINE_LABEL = "A"
53
+
54
+ _NOT_FOUND_NOTE = "No copy of this skill name was found in any search root."
55
+ _NO_BASELINE_NOTE = (
56
+ "No copy passed frontmatter validation, so there is no Variant A baseline to diff against."
57
+ )
58
+
59
+
60
+ # --- Content collection ----------------------------------------------------
61
+
62
+
63
+ @dataclass(frozen=True, slots=True)
64
+ class _Collected:
65
+ """One file's comparable content.
66
+
67
+ ``text`` is ``None`` for a file that is not UTF-8 text, which is what makes
68
+ it "binary" here: such a file is reported as differing, never printed.
69
+ ``fingerprint`` always comes from the hasher, so "same content" means
70
+ exactly what it means everywhere else in the tool.
71
+ """
72
+
73
+ text: str | None
74
+ fingerprint: str
75
+ is_binary: bool
76
+
77
+
78
+ def _read_normalized(path: Path) -> str | None:
79
+ """The file as UTF-8 text with ``\\r\\n`` normalised, or ``None`` if binary.
80
+
81
+ Mirrors :func:`~skill_lens.core.hasher.hash_file`'s text path, including
82
+ opening with ``newline=""`` so no translation happens before we normalise.
83
+ """
84
+ try:
85
+ with path.open("r", encoding="utf-8", newline="") as handle:
86
+ text = handle.read()
87
+ except (OSError, UnicodeDecodeError):
88
+ return None
89
+ return text.replace("\r\n", "\n")
90
+
91
+
92
+ def _collect(path: Path) -> _Collected | None:
93
+ """Fingerprint and read one file, or ``None`` when it cannot be read."""
94
+ try:
95
+ fingerprint = hash_file(path)
96
+ except OSError:
97
+ return None
98
+ text = _read_normalized(path)
99
+ return _Collected(text=text, fingerprint=fingerprint, is_binary=text is None)
100
+
101
+
102
+ def _copy_files(entry: DiscoveredEntry) -> dict[str, _Collected]:
103
+ """Every comparable file of one copy, keyed by relative POSIX path.
104
+
105
+ A directory skill is walked with exactly :func:`hasher.iter_files` -- the
106
+ same sorted, forward-slash relative set, with the same exclusions -- so the
107
+ diff can never see a file the fingerprint ignored. A standalone ``.md`` skill
108
+ is a single file keyed by its own name.
109
+ """
110
+ root = Path(entry.canonical_path or entry.entrypoint_path)
111
+ if not root.is_dir():
112
+ collected = _collect(root)
113
+ return {root.name: collected} if collected is not None else {}
114
+ files: dict[str, _Collected] = {}
115
+ for relative in iter_files(root):
116
+ collected = _collect(root / relative)
117
+ if collected is not None:
118
+ files[relative.as_posix()] = collected
119
+ return files
120
+
121
+
122
+ # --- Hunk construction -----------------------------------------------------
123
+
124
+
125
+ def _lines(text: str) -> list[str]:
126
+ """Split on ``\\n`` only -- the one line separator the hasher normalises.
127
+
128
+ ``str.splitlines`` would also break on characters such as ``\\x0b``, which
129
+ the fingerprint treats as ordinary content; using it would let the diff
130
+ disagree with the hash.
131
+ """
132
+ if text.endswith("\n"):
133
+ text = text[:-1]
134
+ return text.split("\n") if text else []
135
+
136
+
137
+ def _range_start(start: int, count: int) -> int:
138
+ """difflib's unified-range rule: an empty range names the line before it."""
139
+ return start + 1 if count else start
140
+
141
+
142
+ def _hunks(old_lines: Sequence[str], new_lines: Sequence[str]) -> tuple[DiffHunk, ...]:
143
+ """Grouped unified-diff hunks with :data:`CONTEXT_LINES` lines of context."""
144
+ matcher = difflib.SequenceMatcher(None, old_lines, new_lines, autojunk=False)
145
+ hunks: list[DiffHunk] = []
146
+ for group in matcher.get_grouped_opcodes(CONTEXT_LINES):
147
+ lines: list[str] = []
148
+ for tag, i1, i2, j1, j2 in group:
149
+ if tag == "equal":
150
+ lines.extend(f" {line}" for line in old_lines[i1:i2])
151
+ continue
152
+ lines.extend(f"-{line}" for line in old_lines[i1:i2])
153
+ lines.extend(f"+{line}" for line in new_lines[j1:j2])
154
+ old_start, old_end = group[0][1], group[-1][2]
155
+ new_start, new_end = group[0][3], group[-1][4]
156
+ hunks.append(
157
+ DiffHunk(
158
+ old_start=_range_start(old_start, old_end - old_start),
159
+ old_count=old_end - old_start,
160
+ new_start=_range_start(new_start, new_end - new_start),
161
+ new_count=new_end - new_start,
162
+ lines=tuple(lines),
163
+ )
164
+ )
165
+ return tuple(hunks)
166
+
167
+
168
+ def _single_sided(content: _Collected, *, removed: bool) -> tuple[DiffHunk, ...]:
169
+ """Hunks for a file that exists on one side only: all added, or all removed."""
170
+ lines = _lines(content.text) if content.text is not None else []
171
+ if not lines:
172
+ return ()
173
+ marker = "-" if removed else "+"
174
+ count = len(lines)
175
+ return (
176
+ DiffHunk(
177
+ old_start=_range_start(0, count if removed else 0),
178
+ old_count=count if removed else 0,
179
+ new_start=_range_start(0, 0 if removed else count),
180
+ new_count=0 if removed else count,
181
+ lines=tuple(f"{marker}{line}" for line in lines),
182
+ ),
183
+ )
184
+
185
+
186
+ def _one_sided(relative: str, content: _Collected, *, removed: bool) -> DiffFile:
187
+ """A file that exists on one side only, shown as all added or all removed."""
188
+ return DiffFile(
189
+ path=relative,
190
+ change=DiffChange.REMOVED if removed else DiffChange.ADDED,
191
+ is_binary=content.is_binary,
192
+ hunks=() if content.is_binary else _single_sided(content, removed=removed),
193
+ )
194
+
195
+
196
+ def _files_between(old: dict[str, _Collected], new: dict[str, _Collected]) -> list[DiffFile]:
197
+ """Every file that differs between the baseline and one other copy.
198
+
199
+ Files are matched by relative path, so an added, removed or renamed file
200
+ appears as exactly that. Files whose fingerprints match are the same content
201
+ and are absent from the result.
202
+ """
203
+ files: list[DiffFile] = []
204
+ for relative in sorted(set(old) | set(new)):
205
+ before, after = old.get(relative), new.get(relative)
206
+ if before is None:
207
+ if after is not None:
208
+ files.append(_one_sided(relative, after, removed=False))
209
+ continue
210
+ if after is None:
211
+ files.append(_one_sided(relative, before, removed=True))
212
+ continue
213
+ if before.fingerprint == after.fingerprint:
214
+ continue
215
+ if before.is_binary or after.is_binary:
216
+ files.append(DiffFile(path=relative, change=DiffChange.MODIFIED, is_binary=True))
217
+ continue
218
+ files.append(
219
+ DiffFile(
220
+ path=relative,
221
+ change=DiffChange.MODIFIED,
222
+ hunks=_hunks(_lines(before.text or ""), _lines(after.text or "")),
223
+ )
224
+ )
225
+ return files
226
+
227
+
228
+ # --- Truncation ------------------------------------------------------------
229
+
230
+
231
+ @dataclass(frozen=True, slots=True)
232
+ class _Budgeted:
233
+ """One copy's diff after the budgets were applied."""
234
+
235
+ files: tuple[DiffFile, ...]
236
+ omitted_lines: int
237
+ omitted_chars: int
238
+ used_chars: int
239
+
240
+
241
+ def _count_changed(hunks: Sequence[DiffHunk]) -> int:
242
+ return sum(1 for hunk in hunks for line in hunk.lines if line[:1] in ("-", "+"))
243
+
244
+
245
+ def _count_chars(hunks: Sequence[DiffHunk]) -> int:
246
+ """Characters of body text, counting the newline each line ends with."""
247
+ return sum(len(line) + 1 for hunk in hunks for line in hunk.lines)
248
+
249
+
250
+ def _recount_start(stored_start: int, original_count: int, kept_count: int) -> int:
251
+ """Adjust a range start when truncation has emptied the range.
252
+
253
+ A zero-length range names the line *before* it (see :func:`_range_start`).
254
+ The stored start was computed for the original count, so when truncation
255
+ empties a range that was not empty before, the start must step back one line.
256
+ Otherwise a truncated all-deletions hunk renders as ``+1,0`` where a standard
257
+ diff reader requires ``+0,0``.
258
+ """
259
+ if original_count > 0 and kept_count == 0:
260
+ return stored_start - 1
261
+ return stored_start
262
+
263
+
264
+ def _recount(hunk: DiffHunk, lines: Sequence[str]) -> DiffHunk:
265
+ """Rebuild a hunk's header from the lines that survived truncation.
266
+
267
+ Without this a truncated hunk would advertise line counts it no longer
268
+ contains, and the printed diff would not add up. The starts are recomputed
269
+ too: a range that truncation emptied must name the line before it, not the
270
+ line it used to begin at.
271
+ """
272
+ old_count = sum(1 for line in lines if line[:1] in (" ", "-"))
273
+ new_count = sum(1 for line in lines if line[:1] in (" ", "+"))
274
+ return DiffHunk(
275
+ old_start=_recount_start(hunk.old_start, hunk.old_count, old_count),
276
+ old_count=old_count,
277
+ new_start=_recount_start(hunk.new_start, hunk.new_count, new_count),
278
+ new_count=new_count,
279
+ lines=tuple(lines),
280
+ )
281
+
282
+
283
+ def _fit_hunk(hunk: DiffHunk, changed_budget: int, char_budget: int) -> tuple[list[str], int, int]:
284
+ """The longest prefix of ``hunk``'s lines that fits both budgets.
285
+
286
+ Returns the lines, how many of them are changes, and how many characters they
287
+ cost. ``changed_budget`` and ``char_budget`` are what is *left*, so a caller
288
+ can fit one hunk at a time without double-counting.
289
+ """
290
+ lines: list[str] = []
291
+ changed = 0
292
+ chars = 0
293
+ for line in hunk.lines:
294
+ line_changed = 1 if line[:1] in ("-", "+") else 0
295
+ cost = len(line) + 1
296
+ if changed + line_changed > changed_budget or chars + cost > char_budget:
297
+ break
298
+ lines.append(line)
299
+ changed += line_changed
300
+ chars += cost
301
+ return lines, changed, chars
302
+
303
+
304
+ def _truncate(files: Sequence[DiffFile], *, changed_budget: int, char_budget: int) -> _Budgeted:
305
+ """Keep as much of one copy's diff as the budgets allow.
306
+
307
+ ``changed_budget`` counts changed lines (the per-copy limit);
308
+ ``char_budget`` is what is left of the report-wide character limit. Both are
309
+ applied in a single pass so the result is deterministic: once either budget
310
+ is exhausted nothing more is emitted, and the caller is told how much was
311
+ dropped. Files with no printable body -- a binary file, an added or removed
312
+ binary -- are always kept, because they carry a finding, not content.
313
+ """
314
+ kept: list[DiffFile] = []
315
+ used_changed = 0
316
+ used_chars = 0
317
+ exhausted = False
318
+ for file in files:
319
+ hunks: list[DiffHunk] = []
320
+ if not exhausted:
321
+ for hunk in file.hunks:
322
+ lines, hunk_changed, hunk_chars = _fit_hunk(
323
+ hunk, changed_budget - used_changed, char_budget - used_chars
324
+ )
325
+ if not hunk_changed:
326
+ # The budget ran out before this hunk's first change, or cut it
327
+ # back to context lines only. A hunk with no changed lines is not
328
+ # a diff, so it is dropped -- and because it is dropped, its
329
+ # context lines are not charged to the budgets either.
330
+ exhausted = True
331
+ break
332
+ hunks.append(_recount(hunk, lines))
333
+ used_changed += hunk_changed
334
+ used_chars += hunk_chars
335
+ if len(lines) < len(hunk.lines):
336
+ exhausted = True
337
+ break
338
+ kept.append(replace(file, hunks=tuple(hunks)))
339
+ total_changed = sum(_count_changed(file.hunks) for file in files)
340
+ total_chars = sum(_count_chars(file.hunks) for file in files)
341
+ return _Budgeted(
342
+ files=tuple(kept),
343
+ omitted_lines=total_changed - used_changed,
344
+ omitted_chars=total_chars - used_chars,
345
+ used_chars=used_chars,
346
+ )
347
+
348
+
349
+ # --- Public entry point ----------------------------------------------------
350
+
351
+
352
+ def _is_valid(entry: DiscoveredEntry) -> bool:
353
+ return entry.parse_status == ParseStatus.VALID.value
354
+
355
+
356
+ def _is_readable(entry: DiscoveredEntry) -> bool:
357
+ """A copy can be compared when the hasher produced a fingerprint for it.
358
+
359
+ Dangling symlinks, cycles and permission-denied roots have no content, so
360
+ they are listed with no diff rather than silently dropped.
361
+ """
362
+ return entry.content_hash is not None
363
+
364
+
365
+ def _copy(
366
+ entry: DiscoveredEntry,
367
+ labels: dict[str, str],
368
+ *,
369
+ is_baseline: bool = False,
370
+ files: tuple[DiffFile, ...] = (),
371
+ truncated: bool = False,
372
+ omitted_lines: int = 0,
373
+ ) -> DiffCopy:
374
+ """Describe one copy of the skill as it takes part in the diff."""
375
+ key = canonical_key(entry)
376
+ return DiffCopy(
377
+ path=key,
378
+ scope=entry_scope(entry),
379
+ parse_status=entry.parse_status,
380
+ is_valid=_is_valid(entry),
381
+ is_readable=_is_readable(entry),
382
+ is_baseline=is_baseline,
383
+ variant_label=labels.get(key),
384
+ content_hash=entry.content_hash,
385
+ error=entry.error_code,
386
+ files=files,
387
+ truncated=truncated,
388
+ omitted_lines=omitted_lines,
389
+ )
390
+
391
+
392
+ def build_diff_report(
393
+ name: str,
394
+ cwd: Path,
395
+ home: Path,
396
+ *,
397
+ index: DiscoveryIndex | None = None,
398
+ registry: dict[str, AgentDefinition] | None = None,
399
+ ) -> DiffReport:
400
+ """Diff every copy of ``name`` against the Variant A baseline.
401
+
402
+ Arguments mirror :func:`~skill_lens.core.resolver.resolve_skill` -- the
403
+ name-based lookup takes the working directory before the home directory.
404
+ The two optional arguments are keyword-only so a caller cannot silently swap
405
+ a working directory for a home directory.
406
+
407
+ A name that exists nowhere yields ``found=False`` and exit code ``0``: like
408
+ ``why``, "nothing found" is a fact, not an error (finding F-10).
409
+ """
410
+ agents = registry if registry is not None else load_registry()
411
+ discovery = index if index is not None else discover(home, cwd, agents)
412
+
413
+ entries = [entry for entry in discovery.entries if entry.name == name]
414
+ if not entries:
415
+ return DiffReport(
416
+ skill_name=name,
417
+ home=str(home),
418
+ cwd=str(cwd),
419
+ found=False,
420
+ notes=(_NOT_FOUND_NOTE,),
421
+ )
422
+
423
+ labels = labels_for_entries(entries)
424
+ baseline_index = next(
425
+ (
426
+ position
427
+ for position, entry in enumerate(entries)
428
+ if labels.get(canonical_key(entry)) == BASELINE_LABEL
429
+ ),
430
+ None,
431
+ )
432
+ baseline = entries[baseline_index] if baseline_index is not None else None
433
+
434
+ # Only meaningful with more than one copy: a single copy has nothing to be
435
+ # compared against, so "no differences" is already the honest answer.
436
+ notes: tuple[str, ...] = (_NO_BASELINE_NOTE,) if baseline is None and len(entries) > 1 else ()
437
+
438
+ baseline_files: dict[str, _Collected] | None = None
439
+ copies: list[DiffCopy] = []
440
+ used_chars = 0
441
+ omitted_chars = 0
442
+ truncated = False
443
+
444
+ for position, entry in enumerate(entries):
445
+ is_baseline = position == baseline_index
446
+ if not (_is_readable(entry) and not is_baseline and baseline is not None):
447
+ copies.append(_copy(entry, labels, is_baseline=is_baseline))
448
+ continue
449
+
450
+ if entry.content_hash == baseline.content_hash:
451
+ # Same bytes, so no diff -- this is the line-ending rule.
452
+ copies.append(_copy(entry, labels, is_baseline=False))
453
+ continue
454
+
455
+ if baseline_files is None:
456
+ baseline_files = _copy_files(baseline)
457
+ budgeted = _truncate(
458
+ _files_between(baseline_files, _copy_files(entry)),
459
+ changed_budget=MAX_CHANGED_LINES_PER_COPY,
460
+ char_budget=max(MAX_CHARS_PER_REPORT - used_chars, 0),
461
+ )
462
+ copy_truncated = budgeted.omitted_lines > 0 or budgeted.omitted_chars > 0
463
+ truncated = truncated or copy_truncated
464
+ used_chars += budgeted.used_chars
465
+ omitted_chars += budgeted.omitted_chars
466
+ copies.append(
467
+ _copy(
468
+ entry,
469
+ labels,
470
+ is_baseline=False,
471
+ files=budgeted.files,
472
+ truncated=copy_truncated,
473
+ omitted_lines=budgeted.omitted_lines,
474
+ )
475
+ )
476
+
477
+ # The baseline leads the list: it is the reference every other copy is read
478
+ # against, and each diff below it is relative to it.
479
+ ordered = (
480
+ [copies[baseline_index], *(c for i, c in enumerate(copies) if i != baseline_index)]
481
+ if baseline_index is not None
482
+ else copies
483
+ )
484
+ return DiffReport(
485
+ skill_name=name,
486
+ home=str(home),
487
+ cwd=str(cwd),
488
+ found=True,
489
+ baseline_path=canonical_key(baseline) if baseline is not None else None,
490
+ copies=tuple(ordered),
491
+ truncated=truncated,
492
+ omitted_chars=omitted_chars,
493
+ notes=notes,
494
+ )
495
+
496
+
497
+ __all__ = [
498
+ "BASELINE_LABEL",
499
+ "CONTEXT_LINES",
500
+ "MAX_CHANGED_LINES_PER_COPY",
501
+ "MAX_CHARS_PER_REPORT",
502
+ "build_diff_report",
503
+ ]