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,562 @@
1
+ """Filesystem discovery: find skill entrypoints and tag how agents reach them.
2
+
3
+ Discovery is deliberately **agent-agnostic**. It scans every root of every
4
+ known agent and records, per entrypoint, which ``(agent, root)`` pairs reach
5
+ it. The resolver then decides, per agent, what is searched vs unsearched.
6
+
7
+ This split is what lets ``why`` explain an ``UNSEARCHED`` copy: the copy is
8
+ found because some *other* agent looks there, then marked as outside this
9
+ agent's search rules.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ from collections.abc import Iterable
16
+ from dataclasses import dataclass, field
17
+ from pathlib import Path
18
+
19
+ from skill_lens.core.hasher import hash_path
20
+ from skill_lens.core.parser import canonicalize, find_skill_document, parse_skill
21
+ from skill_lens.models.enums import ParseStatus, Scope
22
+ from skill_lens.models.parsing import (
23
+ ERR_DANGLING_SYMLINK,
24
+ ERR_PERMISSION_DENIED,
25
+ ERR_SYMLINK_CYCLE,
26
+ CanonicalResult,
27
+ CanonicalStatus,
28
+ ParseResult,
29
+ )
30
+ from skill_lens.registry.loader import AgentDefinition, AgentRoot, load_registry
31
+
32
+ MAX_WALK_DEPTH = 4
33
+
34
+ #: Most specific scope first. Used for stable ordering of scan rows and of
35
+ #: Variant A / B labels, so both commands agree on what "first" means.
36
+ SCOPE_SPECIFICITY = {
37
+ Scope.PROJECT: 0,
38
+ Scope.USER: 1,
39
+ Scope.SYSTEM: 2,
40
+ Scope.PLUGIN: 3,
41
+ }
42
+
43
+ #: Variant labels, in the order they are handed out. Copies beyond this many
44
+ #: are left unlabelled rather than given an invented letter.
45
+ VARIANT_LABELS = ("A", "B", "C", "D", "E", "F")
46
+
47
+
48
+ def entry_scope(entry: DiscoveredEntry) -> Scope:
49
+ """The most project-specific scope any reaching root assigns to ``entry``.
50
+
51
+ Deliberately a property of the *entry*, not of the agent asking about it:
52
+ a library reachable both as a project root and as a user root has one
53
+ inventory scope, and every consumer must agree on it.
54
+ """
55
+ scopes = {hit.scope for hit in entry.hits}
56
+ for scope in (Scope.PROJECT, Scope.SYSTEM, Scope.PLUGIN, Scope.USER):
57
+ if scope in scopes:
58
+ return scope
59
+ return Scope.USER
60
+
61
+
62
+ def variant_labels(items: Iterable[tuple[str, str, str | None, Scope, int]]) -> dict[str, str]:
63
+ """Label same-named copies whose bytes differ as Variant A / B / ...
64
+
65
+ **One rule, one set of inputs, used by both ``why`` and ``scan``.** Two
66
+ earlier attempts were wrong in different ways: first the two commands
67
+ ordered differently (scope vs an agent's rank), then they shared the
68
+ ordering but still disagreed because they passed *different scopes* in --
69
+ ``scan`` reported the most project-specific scope any root assigns, while
70
+ ``why`` passed the scope of the one root the requested agent uses. The
71
+ scope must come from :func:`entry_scope` on both sides, because it has to
72
+ be a property of the entry rather than of whoever is asking.
73
+
74
+ Ordering is by scope specificity (project before user), then discovery
75
+ order. At most :data:`VARIANT_LABELS` copies are labelled; further copies
76
+ are left unlabelled rather than given an invented letter.
77
+
78
+ ``items`` are ``(name, key, content_hash, scope, position)`` tuples for one
79
+ skill name, where ``key`` identifies the copy (its canonical path) and
80
+ ``position`` is its stable index in discovery order.
81
+
82
+ Copies with identical content hashes are the same bytes, not variants, and
83
+ share one label. Copies that failed validation have no comparable content
84
+ and are left unlabelled.
85
+ """
86
+ by_hash: dict[str | None, list[tuple[str, str, Scope, int]]] = {}
87
+ for name, key, content_hash, scope, position in items:
88
+ by_hash.setdefault(content_hash, []).append((name, key, scope, position))
89
+
90
+ ordered = sorted(
91
+ by_hash.values(),
92
+ key=lambda group: (
93
+ min(SCOPE_SPECIFICITY.get(scope, 9) for _n, _k, scope, _p in group),
94
+ min(position for _n, _k, _s, position in group),
95
+ ),
96
+ )
97
+ labels: dict[str, str] = {}
98
+ for position, group in enumerate(ordered):
99
+ if position >= len(VARIANT_LABELS):
100
+ break
101
+ for _name, key, _scope, _position in group:
102
+ labels[key] = VARIANT_LABELS[position]
103
+ return labels
104
+
105
+
106
+ def canonical_key(entry: DiscoveredEntry) -> str:
107
+ """The key that identifies one copy: its canonical target, or its own path.
108
+
109
+ A copy with no resolvable target (a dangling symlink, a cycle) is keyed by
110
+ its entrypoint so it can never collapse onto a real skill.
111
+ """
112
+ return entry.canonical_path or entry.entrypoint_path
113
+
114
+
115
+ def labels_for_entries(entries: Iterable[DiscoveredEntry]) -> dict[str, str]:
116
+ """Variant labels for a set of entries, keyed by :func:`canonical_key`.
117
+
118
+ This is the one place the label inputs are assembled, so ``scan``, ``why``
119
+ and ``diff`` cannot drift apart the way they did in finding F-16. The rules
120
+ it encodes, all of them deliberate:
121
+
122
+ * only *valid* copies that have a content hash are labelled -- a copy that
123
+ failed validation has no comparable content and gets no letter;
124
+ * the scope is always :func:`entry_scope`'s, because a copy's label must be
125
+ a property of the copy and not of whichever command is asking;
126
+ * ``position`` is the entry's index in the order given, which is what breaks
127
+ ties between two copies of equal scope specificity.
128
+ """
129
+ by_name: dict[str, list[tuple[str, str, str | None, Scope, int]]] = {}
130
+ for position, entry in enumerate(entries):
131
+ if entry.parse_status != ParseStatus.VALID.value or entry.content_hash is None:
132
+ continue
133
+ by_name.setdefault(entry.name, []).append(
134
+ (entry.name, canonical_key(entry), entry.content_hash, entry_scope(entry), position)
135
+ )
136
+ labels: dict[str, str] = {}
137
+ for items in by_name.values():
138
+ labels.update(variant_labels(items))
139
+ return labels
140
+
141
+
142
+ @dataclass(frozen=True, slots=True)
143
+ class RootHit:
144
+ """One ``(agent, root)`` pair that reaches an entrypoint.
145
+
146
+ ``entrypoint_path`` is the *path this root actually sees*. A symlink farm
147
+ reaches one canonical library through several different paths, and
148
+ precedence is judged per entrypoint path (spec section 4), so the path
149
+ belongs to the hit -- not to the merged entry.
150
+ """
151
+
152
+ agent_id: str
153
+ root_id: str
154
+ rank: int
155
+ rule_id: str
156
+ evidence: str
157
+ scope: Scope
158
+ nested: bool = False
159
+ file_rule_id: str | None = None
160
+ nested_rule_id: str | None = None
161
+ specificity: int = 0
162
+ entrypoint_path: str = ""
163
+
164
+ def rule_for(self, is_file: bool) -> str:
165
+ if self.nested and self.nested_rule_id:
166
+ return self.nested_rule_id
167
+ if is_file and self.file_rule_id:
168
+ return self.file_rule_id
169
+ return self.rule_id
170
+
171
+
172
+ @dataclass(frozen=True, slots=True)
173
+ class DiscoveredEntry:
174
+ """A single canonical skill on disk plus every entrypoint that reaches it.
175
+
176
+ One record per **canonical target** (spec section 4, *Inventory &
177
+ Identity*): a symlink farm is one library with N entrypoints, never N
178
+ installations.
179
+
180
+ Each :class:`RootHit` in ``hits`` keeps its own ``entrypoint_path``, so the
181
+ resolver can still judge precedence on the path the *requested* agent uses
182
+ (spec section 4, *Precedence & Collision*). ``entrypoint_paths`` lists every
183
+ path on disk, for honest counts.
184
+ """
185
+
186
+ entrypoint_path: str
187
+ name: str
188
+ is_file: bool
189
+ is_symlink: bool
190
+ canonical: CanonicalResult
191
+ parse: ParseResult | None
192
+ content_hash: str | None
193
+ hits: tuple[RootHit, ...] = ()
194
+ entrypoint_paths: tuple[str, ...] = ()
195
+ variant_label: str | None = None
196
+
197
+ @property
198
+ def canonical_path(self) -> str | None:
199
+ return self.canonical.resolved_path
200
+
201
+ @property
202
+ def parse_status(self) -> str:
203
+ if self.parse is not None:
204
+ return self.parse.status.value
205
+ return "invalid"
206
+
207
+ @property
208
+ def error_code(self) -> str | None:
209
+ if self.canonical.status is CanonicalStatus.CYCLE:
210
+ return ERR_SYMLINK_CYCLE
211
+ if self.canonical.status is CanonicalStatus.BROKEN:
212
+ return ERR_DANGLING_SYMLINK
213
+ if self.canonical.status is CanonicalStatus.UNREADABLE:
214
+ return ERR_PERMISSION_DENIED
215
+ return None
216
+
217
+
218
+ @dataclass(frozen=True, slots=True)
219
+ class UnreadableRoot:
220
+ """A root that exists but could not be listed (e.g. macOS TCC)."""
221
+
222
+ agent_id: str
223
+ root_id: str
224
+ path: str
225
+ detail: str
226
+
227
+
228
+ @dataclass(slots=True)
229
+ class DiscoveryIndex:
230
+ """The result of one full discovery pass over a mock or real home."""
231
+
232
+ home: str
233
+ cwd: str
234
+ entries: list[DiscoveredEntry] = field(default_factory=list)
235
+ unreadable_roots: list[UnreadableRoot] = field(default_factory=list)
236
+
237
+ def all_agents(self) -> set[str]:
238
+ return {hit.agent_id for entry in self.entries for hit in entry.hits}
239
+
240
+
241
+ # --- Boundary detection ----------------------------------------------------
242
+
243
+
244
+ def find_walk_boundary(cwd: Path, kind: str) -> Path | None:
245
+ """Find the directory that bounds an upward project walk, if any.
246
+
247
+ Looks for ``.git`` (a directory for a normal checkout, a file for a linked
248
+ worktree). Returns ``None`` when no boundary marker is found, which means
249
+ "this working directory is not inside a project" -- so project-scoped roots
250
+ do not apply. This prevents a machine-wide ``scan`` from mislabelling
251
+ global roots as project roots.
252
+ """
253
+ markers = (".git",) if kind != "project_root_markers" else (".git", "pyproject.toml")
254
+ for directory in (cwd, *cwd.parents):
255
+ for marker in markers:
256
+ if (directory / marker).exists():
257
+ return directory
258
+ return None
259
+
260
+
261
+ def normalize_cwd(cwd: Path, home: Path) -> Path:
262
+ """Resolve ``cwd`` to an absolute path, treating relative input as home-relative.
263
+
264
+ ``--cwd .`` therefore means "the mock/real home itself", which keeps
265
+ sandboxed scans inside the sandbox and never escapes into the process's
266
+ real working directory.
267
+ """
268
+ expanded = Path(cwd).expanduser()
269
+ if expanded.is_absolute():
270
+ return expanded
271
+ return (home / expanded).resolve()
272
+
273
+
274
+ def _ancestor_dirs(cwd: Path, boundary: Path) -> list[Path]:
275
+ """Directories from ``cwd`` up to and including ``boundary``."""
276
+ chain: list[Path] = []
277
+ current = cwd
278
+ while True:
279
+ chain.append(current)
280
+ if current == boundary or current.parent == current:
281
+ break
282
+ current = current.parent
283
+ return chain
284
+
285
+
286
+ # --- Root expansion --------------------------------------------------------
287
+
288
+
289
+ def _absolute_roots_allowed(home: Path) -> bool:
290
+ """Absolute system roots (e.g. ``/etc/codex/skills``) are scanned live only.
291
+
292
+ Under a sandbox (tests, ``--sandbox``) they are skipped so a scan can never
293
+ read real system directories and contaminate deterministic results.
294
+ """
295
+ from skill_lens.core import paths
296
+
297
+ return paths.get_sandbox() is None and home == paths.home()
298
+
299
+
300
+ def _directories_for_root(
301
+ home: Path, cwd: Path, root: AgentRoot, boundary: Path | None
302
+ ) -> list[tuple[Path, bool]]:
303
+ """Return ``(directory, nested)`` pairs a root resolves to for this cwd.
304
+
305
+ Global/system/plugin roots are relative to the home directory. Project
306
+ roots are joined onto each ancestor of ``cwd`` up to the git boundary, so a
307
+ project skill is the *root* copy (not nested) while a skill found further up
308
+ the monorepo from the working directory is nested (qualifies as ``dir:skill``).
309
+ When there is no boundary (cwd is not in a project), no project root applies.
310
+ """
311
+ if root.is_absolute:
312
+ if not _absolute_roots_allowed(home):
313
+ return []
314
+ return [(Path(root.path), False)]
315
+ if not root.is_project:
316
+ return [(home / root.path, False)]
317
+ if boundary is None:
318
+ return []
319
+
320
+ results: list[tuple[Path, bool]] = []
321
+ for directory in _ancestor_dirs(cwd, boundary):
322
+ candidate = directory / root.path
323
+ try:
324
+ if candidate.exists() or candidate.is_symlink():
325
+ results.append((candidate, directory != boundary))
326
+ except OSError:
327
+ # An ancestor is off-limits; this project root simply does not
328
+ # apply. The blocked directory is reported elsewhere, so skip it.
329
+ continue
330
+ return results
331
+
332
+
333
+ # --- Entry listing ---------------------------------------------------------
334
+
335
+
336
+ def _is_skill_dir(path: Path) -> bool:
337
+ return find_skill_document(path) is not None
338
+
339
+
340
+ def _is_symlinked_markdown(path: Path) -> bool:
341
+ """True when ``path`` is a symlink whose target is a standalone ``.md`` file.
342
+
343
+ A symlinked file skill must keep the *file* classification, otherwise the
344
+ root's ``file_rule_id`` is never emitted and a standalone-file agent reports
345
+ the directory-skill rule instead. Resolved safely: an unresolvable link
346
+ (cycle, dangling) simply is not a markdown file skill.
347
+ """
348
+ if path.suffix.lower() != ".md":
349
+ return False
350
+ try:
351
+ return path.resolve().is_file()
352
+ except (OSError, RuntimeError):
353
+ # A symlink loop makes ``resolve()`` raise ``RuntimeError`` on Python
354
+ # 3.11/3.12 (3.13+ stops at the loop instead); an unresolvable link
355
+ # raises ``OSError``. Either way, it is not a markdown file skill.
356
+ return False
357
+
358
+
359
+ def _list_entries(base: Path) -> list[tuple[Path, bool]]:
360
+ """List skill entrypoints directly under ``base`` as ``(path, is_file)``.
361
+
362
+ A ``.system`` container is **not** descended here: bundled system skills are
363
+ owned by a dedicated root whose path ends in ``.system`` (see codex.toml),
364
+ so attributing them here too would give them the wrong scope and rank.
365
+ """
366
+ try:
367
+ children = sorted(base.iterdir(), key=lambda p: p.name)
368
+ except OSError:
369
+ return []
370
+
371
+ results: list[tuple[Path, bool]] = []
372
+ for child in children:
373
+ if child.is_symlink():
374
+ results.append((child, _is_symlinked_markdown(child)))
375
+ elif child.is_dir():
376
+ if _is_skill_dir(child) or _unreadable(child):
377
+ results.append((child, False))
378
+ elif child.suffix.lower() == ".md":
379
+ results.append((child, True))
380
+ return results
381
+
382
+
383
+ def _list_recursive_entries(base: Path) -> list[tuple[Path, bool]]:
384
+ """Find ``skills`` directories under ``base`` up to :data:`MAX_WALK_DEPTH`."""
385
+ found: list[tuple[Path, bool]] = []
386
+ base_depth = len(base.parts)
387
+ for dirpath, dirnames, _filenames in os.walk(base):
388
+ current = Path(dirpath)
389
+ if len(current.parts) - base_depth >= MAX_WALK_DEPTH:
390
+ dirnames[:] = []
391
+ continue
392
+ dirnames[:] = [d for d in dirnames if d != ".git"]
393
+ if current.name == "skills":
394
+ found.extend(_list_entries(current))
395
+ dirnames[:] = []
396
+ return found
397
+
398
+
399
+ # --- Main discovery --------------------------------------------------------
400
+
401
+
402
+ def discover(
403
+ home: Path,
404
+ cwd: Path,
405
+ registry: dict[str, AgentDefinition] | None = None,
406
+ ) -> DiscoveryIndex:
407
+ """Scan every agent's roots and return a tagged :class:`DiscoveryIndex`."""
408
+ agents = registry if registry is not None else load_registry()
409
+ cwd = normalize_cwd(cwd, home)
410
+ index = DiscoveryIndex(home=str(home), cwd=str(cwd))
411
+
412
+ seen: set[tuple[str, str, str]] = set()
413
+ for agent in agents.values():
414
+ boundary = find_walk_boundary(cwd, agent.walk_boundary)
415
+ for root in agent.roots:
416
+ for base, nested in _directories_for_root(home, cwd, root, boundary):
417
+ try:
418
+ if not base.exists() and not base.is_symlink():
419
+ continue
420
+ if base.is_dir() and not base.is_symlink() and _unreadable(base):
421
+ index.unreadable_roots.append(
422
+ UnreadableRoot(
423
+ agent_id=agent.id,
424
+ root_id=root.id,
425
+ path=str(base),
426
+ detail=ERR_PERMISSION_DENIED,
427
+ )
428
+ )
429
+ continue
430
+ except OSError:
431
+ # The root, or a parent directory, cannot be inspected --
432
+ # e.g. a nested root under a TCC-blocked parent. The blocked
433
+ # parent is recorded as unreadable on its own pass; skip
434
+ # this one rather than letting a stat behind it abort the
435
+ # whole walk (Python 3.11-3.13 re-raise PermissionError from
436
+ # ``exists``/``is_dir``; 3.14 swallows it).
437
+ continue
438
+ listing = _list_recursive_entries(base) if root.recursive else _list_entries(base)
439
+ for entrypoint, is_file in listing:
440
+ key = (agent.id, root.id, str(entrypoint))
441
+ if key in seen:
442
+ continue
443
+ seen.add(key)
444
+ hit = RootHit(
445
+ agent_id=agent.id,
446
+ root_id=root.id,
447
+ rank=root.rank,
448
+ rule_id=root.rule_id,
449
+ evidence=root.evidence.value,
450
+ scope=root.scope,
451
+ nested=nested,
452
+ file_rule_id=root.file_rule_id,
453
+ nested_rule_id=root.nested_rule_id,
454
+ specificity=len(Path(root.path).parts),
455
+ entrypoint_path=str(entrypoint),
456
+ )
457
+ index.entries.append(_build_entry(entrypoint, is_file, hit))
458
+
459
+ index.entries = _merge_entries(index.entries)
460
+ return index
461
+
462
+
463
+ def _unreadable(path: Path) -> bool:
464
+ try:
465
+ os.listdir(path)
466
+ except OSError:
467
+ return True
468
+ return False
469
+
470
+
471
+ def _build_entry(entrypoint: Path, is_file: bool, hit: RootHit) -> DiscoveredEntry:
472
+ canonical = canonicalize(entrypoint)
473
+ parse: ParseResult | None = None
474
+ content_hash: str | None = None
475
+ if canonical.status is CanonicalStatus.OK:
476
+ parse = parse_skill(entrypoint)
477
+ try:
478
+ content_hash = hash_path(entrypoint)
479
+ except OSError:
480
+ content_hash = None
481
+
482
+ name = _entry_name(entrypoint, is_file, parse)
483
+ return DiscoveredEntry(
484
+ entrypoint_path=str(entrypoint),
485
+ name=name,
486
+ is_file=is_file,
487
+ is_symlink=entrypoint.is_symlink(),
488
+ canonical=canonical,
489
+ parse=parse,
490
+ content_hash=content_hash,
491
+ hits=(hit,),
492
+ entrypoint_paths=(str(entrypoint),),
493
+ )
494
+
495
+
496
+ def _entry_name(entrypoint: Path, is_file: bool, parse: ParseResult | None) -> str:
497
+ if parse is not None:
498
+ return parse.directory_name
499
+ if is_file or entrypoint.suffix.lower() == ".md":
500
+ return entrypoint.stem
501
+ return entrypoint.name
502
+
503
+
504
+ def _merge_entries(entries: list[DiscoveredEntry]) -> list[DiscoveredEntry]:
505
+ """Group entrypoints that share a canonical target into one record.
506
+
507
+ A symlink farm (many entrypoints, one real target) becomes a single entry
508
+ whose ``hits`` union every reaching root, each hit keeping the entrypoint
509
+ path *it* was reached through. Entries with no resolvable canonical (cycles,
510
+ dangling links) are keyed by their own path so they never collapse with a
511
+ real skill.
512
+ """
513
+ merged: dict[str, DiscoveredEntry] = {}
514
+ order: list[str] = []
515
+ for entry in entries:
516
+ key = entry.canonical_path or f"@{entry.entrypoint_path}"
517
+ if key not in merged:
518
+ merged[key] = entry
519
+ order.append(key)
520
+ continue
521
+ existing = merged[key]
522
+ hits = _union_hits(existing.hits, entry.hits)
523
+ merged[key] = DiscoveredEntry(
524
+ entrypoint_path=existing.entrypoint_path,
525
+ name=existing.name or entry.name,
526
+ # A symlinked ``.md`` is a file skill even when the sibling entry
527
+ # that reached the same target was a directory, so OR the flags.
528
+ is_file=existing.is_file or entry.is_file,
529
+ is_symlink=existing.is_symlink or entry.is_symlink,
530
+ canonical=existing.canonical,
531
+ parse=existing.parse or entry.parse,
532
+ content_hash=existing.content_hash or entry.content_hash,
533
+ hits=hits,
534
+ entrypoint_paths=_union_paths(existing.entrypoint_paths, entry.entrypoint_paths),
535
+ )
536
+ return [merged[key] for key in order]
537
+
538
+
539
+ def _union_paths(current: tuple[str, ...], incoming: tuple[str, ...]) -> tuple[str, ...]:
540
+ """Concatenate entrypoint paths, keeping order and dropping duplicates.
541
+
542
+ Several agent roots can reach the same physical path, so the same path may
543
+ arrive more than once; counting it twice would inflate the metrics.
544
+ """
545
+ seen: set[str] = set()
546
+ merged: list[str] = []
547
+ for path in (*current, *incoming):
548
+ if path not in seen:
549
+ seen.add(path)
550
+ merged.append(path)
551
+ return tuple(merged)
552
+
553
+
554
+ def _union_hits(current: tuple[RootHit, ...], incoming: tuple[RootHit, ...]) -> tuple[RootHit, ...]:
555
+ combined = list(current)
556
+ existing = {(h.agent_id, h.root_id, h.nested) for h in combined}
557
+ for hit in incoming:
558
+ marker = (hit.agent_id, hit.root_id, hit.nested)
559
+ if marker not in existing:
560
+ combined.append(hit)
561
+ existing.add(marker)
562
+ return tuple(combined)