skillshuttle 1.0.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 (53) hide show
  1. agent_skill_manager/__init__.py +12 -0
  2. agent_skill_manager/__main__.py +5 -0
  3. agent_skill_manager/completion/__init__.py +25 -0
  4. agent_skill_manager/completion/_askill +112 -0
  5. agent_skill_manager/completion/askill.bash +105 -0
  6. agent_skill_manager/completion/askill.fish +94 -0
  7. agent_skill_manager/config/__init__.py +4 -0
  8. agent_skill_manager/config/products.py +238 -0
  9. agent_skill_manager/controllers/__init__.py +4 -0
  10. agent_skill_manager/controllers/cli.py +1344 -0
  11. agent_skill_manager/controllers/parsers/__init__.py +77 -0
  12. agent_skill_manager/controllers/parsers/authoring.py +109 -0
  13. agent_skill_manager/controllers/parsers/distribution.py +168 -0
  14. agent_skill_manager/controllers/parsers/operations.py +108 -0
  15. agent_skill_manager/models/__init__.py +11 -0
  16. agent_skill_manager/models/product.py +30 -0
  17. agent_skill_manager/models/report.py +62 -0
  18. agent_skill_manager/services/__init__.py +4 -0
  19. agent_skill_manager/services/audit.py +441 -0
  20. agent_skill_manager/services/auto_adopt.py +238 -0
  21. agent_skill_manager/services/ci_format.py +100 -0
  22. agent_skill_manager/services/doctor.py +305 -0
  23. agent_skill_manager/services/drift.py +88 -0
  24. agent_skill_manager/services/get.py +160 -0
  25. agent_skill_manager/services/inventory.py +37 -0
  26. agent_skill_manager/services/manifest.py +167 -0
  27. agent_skill_manager/services/overlap.py +112 -0
  28. agent_skill_manager/services/paths_export.py +204 -0
  29. agent_skill_manager/services/publish.py +298 -0
  30. agent_skill_manager/services/registry.py +124 -0
  31. agent_skill_manager/services/remediation.py +145 -0
  32. agent_skill_manager/services/scaffold.py +191 -0
  33. agent_skill_manager/services/sources.py +261 -0
  34. agent_skill_manager/services/spec.py +188 -0
  35. agent_skill_manager/services/sync/__init__.py +35 -0
  36. agent_skill_manager/services/sync/adopt.py +174 -0
  37. agent_skill_manager/services/sync/audit_report.py +128 -0
  38. agent_skill_manager/services/sync/engine.py +510 -0
  39. agent_skill_manager/services/sync/install.py +411 -0
  40. agent_skill_manager/services/sync/pack.py +43 -0
  41. agent_skill_manager/services/sync/settings_io.py +110 -0
  42. agent_skill_manager/services/upgrade.py +205 -0
  43. agent_skill_manager/services/watch.py +473 -0
  44. agent_skill_manager/services/welcome.py +49 -0
  45. agent_skill_manager/utils/__init__.py +4 -0
  46. agent_skill_manager/utils/filesystem.py +219 -0
  47. agent_skill_manager/utils/watcher.py +607 -0
  48. skillshuttle-1.0.0.dist-info/METADATA +552 -0
  49. skillshuttle-1.0.0.dist-info/RECORD +53 -0
  50. skillshuttle-1.0.0.dist-info/WHEEL +5 -0
  51. skillshuttle-1.0.0.dist-info/entry_points.txt +3 -0
  52. skillshuttle-1.0.0.dist-info/licenses/LICENSE +21 -0
  53. skillshuttle-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,100 @@
1
+ """GitHub Actions annotation formatters (P1-8).
2
+
3
+ Pure functions: no filesystem or network access. The CLI gathers the reports
4
+ and prints the returned lines, so the existing human-readable output and the
5
+ 0/1/2 exit-code contract stay untouched.
6
+
7
+ Workflow command syntax:
8
+ https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-commands
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ from collections.abc import Iterable, Mapping
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ __all__ = ["audit_annotations", "grades_failed", "parse_fail_on", "verify_annotations"]
19
+
20
+ VALID_GRADES = {"A", "B", "C", "D", "F"}
21
+
22
+
23
+ def _escape(value: Any) -> str:
24
+ """Escape data for a workflow command (%, CR, LF are special)."""
25
+ return (
26
+ str(value)
27
+ .replace("%", "%25")
28
+ .replace("\r", "%0D")
29
+ .replace("\n", "%0A")
30
+ )
31
+
32
+
33
+ def parse_fail_on(value: str | None) -> set[str]:
34
+ """Parse ``--fail-on D,F`` into a grade set; raise ValueError on junk."""
35
+ if not value:
36
+ return set()
37
+ grades = {part.strip().upper() for part in re.split(r"[,\s]+", value) if part.strip()}
38
+ bad = grades - VALID_GRADES
39
+ if bad:
40
+ raise ValueError(
41
+ f"invalid grade(s): {', '.join(sorted(bad))} "
42
+ f"(expected any of {', '.join(sorted(VALID_GRADES))})"
43
+ )
44
+ return grades
45
+
46
+
47
+ def grades_failed(reports: Iterable[Mapping[str, Any]], fail_on: set[str]) -> list[str]:
48
+ """Skill names whose audit grade is in ``fail_on`` (stable order)."""
49
+ return sorted(r["skill"] for r in reports if r.get("grade") in fail_on)
50
+
51
+
52
+ def verify_annotations(
53
+ results: list[dict],
54
+ product_issues: list[tuple[str, list[str]]],
55
+ *,
56
+ central: Path,
57
+ ) -> list[str]:
58
+ """Emit one annotation per spec error / warning / frontmatter gap."""
59
+ lines: list[str] = []
60
+ for r in results:
61
+ path = central / r["skill"] / "SKILL.md"
62
+ for error in r.get("errors", []):
63
+ lines.append(f"::error file={_escape(path)},line=1::{_escape(error)}")
64
+ for warning in r.get("warnings", []):
65
+ lines.append(f"::warning file={_escape(path)},line=1::{_escape(warning)}")
66
+ for name, issues in product_issues:
67
+ path = central / name / "SKILL.md"
68
+ for issue in issues:
69
+ lines.append(f"::warning file={_escape(path)},line=1::{_escape(issue)}")
70
+ return lines
71
+
72
+
73
+ def audit_annotations(
74
+ reports: Iterable[Mapping[str, Any]],
75
+ *,
76
+ fail_on: set[str] | None = None,
77
+ ) -> list[str]:
78
+ """Emit annotations for high-severity findings and failed grade gates."""
79
+ failed = set(grades_failed(reports, fail_on or set()))
80
+ lines: list[str] = []
81
+ for report in reports:
82
+ root = str(report.get("path") or report.get("skill", ""))
83
+ for finding in report.get("findings", []):
84
+ severity = finding.get("severity")
85
+ if severity not in {"critical", "high"}:
86
+ continue
87
+ file = f"{root}/{finding.get('file', 'SKILL.md')}"
88
+ line = finding.get("line") or 1
89
+ lines.append(
90
+ f"::error file={_escape(file)},line={_escape(line)}::"
91
+ f"{_escape(finding.get('message', ''))}"
92
+ )
93
+ if report["skill"] in failed:
94
+ file = f"{root}/SKILL.md"
95
+ lines.append(
96
+ f"::error file={_escape(file)},line=1::"
97
+ f"audit grade {report['grade']} ({report.get('verdict', '')}) "
98
+ f"is in --fail-on"
99
+ )
100
+ return lines
@@ -0,0 +1,305 @@
1
+ """Environment and repository health diagnostics (``askill doctor``, v0.23.0).
2
+
3
+ One command that answers "why is askill misbehaving on this machine":
4
+ git availability, configured proxies (git config + env) with a live TCP
5
+ reachability probe - the unreachable-local-proxy failure mode behind most
6
+ "install from GitHub failed" reports - central repository state (skills,
7
+ tracked sources, orphan tracking entries), per-product link health
8
+ (broken links, real dirs that forked from central), and whether
9
+ settings-managed products' settings files are writable right now.
10
+
11
+ Strictly read-only: the settings probe opens ``r+b`` and closes without
12
+ writing; nothing else touches the filesystem or the network beyond the
13
+ proxy TCP probes.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import os
19
+ import shutil
20
+ import socket
21
+ import subprocess
22
+ from pathlib import Path
23
+ from urllib.parse import urlparse
24
+
25
+ from ..config.products import PRODUCTS, get_product_path
26
+ from ..utils.filesystem import is_symlink_or_junction
27
+ from .inventory import list_skills
28
+
29
+ __all__ = ["doctor_report"]
30
+
31
+
32
+ # ---------------------------------------------------------------- helpers
33
+
34
+ def _load_sources_for(central: Path) -> dict:
35
+ """Sources registry read straight from *central* (no module globals)."""
36
+ try:
37
+ f = central / ".askill-sources.json"
38
+ if f.exists():
39
+ return json.loads(f.read_text(encoding="utf-8"))
40
+ except (OSError, ValueError):
41
+ pass
42
+ return {}
43
+
44
+
45
+ def _git_version() -> str | None:
46
+ git = shutil.which("git")
47
+ if not git:
48
+ return None
49
+ try:
50
+ r = subprocess.run(
51
+ ["git", "--version"], capture_output=True, text=True,
52
+ encoding="utf-8", errors="replace", timeout=15,
53
+ )
54
+ return (r.stdout or "").strip() or git
55
+ except (OSError, subprocess.TimeoutExpired):
56
+ return git
57
+
58
+
59
+ def _configured_proxies() -> list[dict]:
60
+ """All configured proxy URLs with their source (git config first, then env)."""
61
+ found: dict[str, dict] = {}
62
+ for key in ("http.proxy", "https.proxy"):
63
+ try:
64
+ r = subprocess.run(
65
+ ["git", "config", "--global", "--get", key],
66
+ capture_output=True, text=True, encoding="utf-8",
67
+ errors="replace", timeout=15,
68
+ )
69
+ url = (r.stdout or "").strip()
70
+ except (OSError, subprocess.TimeoutExpired):
71
+ url = ""
72
+ if url:
73
+ found[f"git {key}"] = {"source": f"git config {key}", "url": url}
74
+ for var in ("HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY"):
75
+ env_url: str | None = os.environ.get(var) or os.environ.get(var.lower())
76
+ if env_url and env_url not in {v["url"] for v in found.values()}:
77
+ found[f"env {var}"] = {"source": f"env {var}", "url": env_url}
78
+ return list(found.values())
79
+
80
+
81
+ def _probe_tcp(url: str, timeout: float = 1.5) -> bool | None:
82
+ """TCP-connect to the proxy's host:port. None when the URL has no probe target."""
83
+ try:
84
+ parsed = urlparse(url if "//" in url else f"http://{url}")
85
+ host = parsed.hostname
86
+ port = parsed.port or (443 if parsed.scheme == "https" else 80)
87
+ except ValueError:
88
+ return None
89
+ if not host:
90
+ return None
91
+ try:
92
+ with socket.create_connection((host, port), timeout=timeout):
93
+ return True
94
+ except OSError:
95
+ return False
96
+
97
+
98
+ def _settings_writable(path: Path) -> bool | None:
99
+ """Probe a settings file for exclusive locks by opening r+b (no write)."""
100
+ try:
101
+ with open(path, "r+b"):
102
+ return True
103
+ except PermissionError:
104
+ return False
105
+ except OSError:
106
+ return None # missing / not a regular file
107
+
108
+
109
+ def _scan_product_dir(pdir: Path, central_names: set[str]) -> dict:
110
+ """Link health for one product skills dir (read-only sweep).
111
+
112
+ ``broken_names`` names the dead links so doctor can point at them;
113
+ ``fork_dirs`` counts real (non-linked) folders whose name matches a
114
+ central skill - the actual drift candidates. Real folders with other
115
+ names are product-local skills, not drift, and are not flagged.
116
+ """
117
+ links = broken = real_dirs = fork_dirs = 0
118
+ broken_names: list[str] = []
119
+ try:
120
+ entries = list(pdir.iterdir())
121
+ except OSError:
122
+ return {
123
+ "links": None, "broken_links": None, "broken_names": [],
124
+ "real_dirs": None, "fork_dirs": None,
125
+ }
126
+ for e in entries:
127
+ if is_symlink_or_junction(e):
128
+ links += 1
129
+ if not e.exists():
130
+ broken += 1
131
+ broken_names.append(e.name)
132
+ elif e.is_dir():
133
+ real_dirs += 1
134
+ if e.name in central_names:
135
+ fork_dirs += 1
136
+ return {
137
+ "links": links, "broken_links": broken, "broken_names": broken_names,
138
+ "real_dirs": real_dirs, "fork_dirs": fork_dirs,
139
+ }
140
+
141
+
142
+ # ---------------------------------------------------------------- main
143
+
144
+ def doctor_report(central: Path | None = None, verbose: bool = True) -> dict:
145
+ """Run all diagnostics and return the report (also printed when verbose).
146
+
147
+ ``ok`` is False only when at least one check has severity ``fail``
148
+ (things that make askill itself unable to work). Warnings are
149
+ machine/product states the user can heal with documented commands.
150
+ """
151
+ base = Path(central) if central is not None else None
152
+ if base is None:
153
+ from ..config.products import CENTRAL_DIR
154
+ base = CENTRAL_DIR
155
+
156
+ checks: list[dict] = []
157
+
158
+ # 1. git
159
+ ver = _git_version()
160
+ if ver:
161
+ checks.append({"id": "git", "severity": "ok", "detail": ver})
162
+ else:
163
+ checks.append({
164
+ "id": "git", "severity": "fail",
165
+ "detail": "git not found - 'askill install' from GitHub needs it",
166
+ })
167
+
168
+ # 2. proxies (configured but unreachable = the top install-failure cause)
169
+ proxies: list[dict] = []
170
+ for px in _configured_proxies():
171
+ reachable = _probe_tcp(px["url"])
172
+ entry = {**px, "reachable": reachable}
173
+ proxies.append(entry)
174
+ if reachable is False:
175
+ checks.append({
176
+ "id": f"proxy:{px['source']}", "severity": "fail",
177
+ "detail": (
178
+ f"{px['source']} -> {px['url']} is not reachable; "
179
+ "git clone (askill install / get / update) will fail. "
180
+ "Start your proxy client, or: "
181
+ "git config --global --unset http.proxy"
182
+ ),
183
+ })
184
+ continue
185
+ checks.append({
186
+ "id": f"proxy:{px['source']}", "severity": "ok",
187
+ "detail": f"{px['source']} -> {px['url']} reachable",
188
+ })
189
+
190
+ # 3. central repository
191
+ skills = list_skills(base) if base.exists() else []
192
+ sources = _load_sources_for(base)
193
+ orphan_sources = [n for n in sources if n not in {d.name for d in skills}]
194
+ checks.append({
195
+ "id": "central", "severity": "warn" if not base.exists() else "ok",
196
+ "detail": (
197
+ f"{base} - {len(skills)} skill(s), "
198
+ f"{len(sources)} tracked source(s)"
199
+ + (f", {len(orphan_sources)} orphan source entr(ies)" if orphan_sources else "")
200
+ ),
201
+ })
202
+ if orphan_sources:
203
+ checks.append({
204
+ "id": "orphan-sources", "severity": "warn",
205
+ "detail": (
206
+ "tracking entries without a matching central skill: "
207
+ + ", ".join(sorted(orphan_sources))
208
+ + " (clean with: remove the entry from .askill-sources.json)"
209
+ ),
210
+ })
211
+
212
+ # 4. products
213
+ central_names = {d.name for d in skills}
214
+ product_rows: list[dict] = []
215
+ broken_total = 0
216
+ real_dir_products: list[str] = []
217
+ for p in PRODUCTS:
218
+ # get_product_path is typed Path | None but the config paths are raw
219
+ # strings at runtime - coerce defensively instead of trusting the cast
220
+ raw = get_product_path(p)
221
+ pdir = Path(raw) if raw is not None else None
222
+ row = {
223
+ "name": p["name"], "short": p["short"],
224
+ "sync_method": p.get("sync_method"),
225
+ "dir": str(pdir) if pdir else "",
226
+ "dir_exists": bool(pdir and pdir.exists()),
227
+ }
228
+ if pdir is None:
229
+ product_rows.append(row)
230
+ continue
231
+ scan = _scan_product_dir(pdir, central_names) if pdir.exists() else {}
232
+ row.update(scan)
233
+ if (scan.get("broken_links") or 0) > 0:
234
+ broken_total += scan["broken_links"]
235
+ if (scan.get("fork_dirs") or 0) > 0:
236
+ real_dir_products.append(p["name"])
237
+ sf = p.get("settings_file")
238
+ if sf is not None:
239
+ sfp = Path(sf)
240
+ row["settings_file"] = str(sfp)
241
+ row["settings_writable"] = _settings_writable(sfp) if sfp.exists() else None
242
+ product_rows.append(row)
243
+
244
+ if broken_total:
245
+ checks.append({
246
+ "id": "broken-links", "severity": "warn",
247
+ "detail": (
248
+ f"{broken_total} broken link(s) across products - relink "
249
+ "central skills with `askill sync`, remove stale ones with "
250
+ "`askill sync --gc`"
251
+ ),
252
+ })
253
+ if real_dir_products:
254
+ checks.append({
255
+ "id": "drift-candidates", "severity": "warn",
256
+ "detail": (
257
+ "product dirs contain real folders shadowing central skills: "
258
+ + ", ".join(real_dir_products)
259
+ + " - inspect with: askill drift"
260
+ + " (auto-adopted? use: askill adopt --undo <skill>)"
261
+ ),
262
+ })
263
+
264
+ ok = not any(c["severity"] == "fail" for c in checks)
265
+ report = {
266
+ "ok": ok,
267
+ "checks": checks,
268
+ "central": {
269
+ "dir": str(base), "exists": base.exists(),
270
+ "skills": len(skills), "tracked": len(sources),
271
+ "orphan_sources": sorted(orphan_sources),
272
+ },
273
+ "products": product_rows,
274
+ }
275
+
276
+ if verbose:
277
+ _print_report(report)
278
+ return report
279
+
280
+
281
+ def _print_report(report: dict) -> None:
282
+ """Human-readable rendering (the --json dump is the report dict itself)."""
283
+ print("askill doctor - environment & repository health\n")
284
+ icon = {"ok": "[ok] ", "warn": "[warn]", "fail": "[FAIL]"}
285
+ for c in report["checks"]:
286
+ print(f" {icon.get(c['severity'], '[?] ')} {c['id']}: {c['detail']}")
287
+ print(f"\n products ({len(report['products'])}):")
288
+ for row in report["products"]:
289
+ if not row["dir_exists"]:
290
+ print(f" {row['name']:<28} dir missing (run askill sync to create)")
291
+ continue
292
+ parts = [f"{row.get('links', '?')} link(s)"]
293
+ if row.get("broken_links"):
294
+ names = row.get("broken_names") or []
295
+ shown = ", ".join(names[:4]) + (" ..." if len(names) > 4 else "")
296
+ parts.append(f"{row['broken_links']} dead ({shown})")
297
+ if row.get("real_dirs"):
298
+ parts.append(f"{row['real_dirs']} real dir(s)")
299
+ if row.get("settings_writable") is False:
300
+ parts.append("settings.json LOCKED")
301
+ print(f" {row['name']:<28} {', '.join(parts)}")
302
+ print()
303
+ verdict = "healthy" if report["ok"] else "issues found (see FAIL above)"
304
+ print(f" overall: {verdict}")
305
+ print(" -- pass --json for a machine-readable report (great for bug reports)")
@@ -0,0 +1,88 @@
1
+ """Drift detection: product directories diverging from the central repo.
2
+
3
+ v0.16.0, first slice of the bidirectional-sync direction
4
+ (docs/v0.15.0-plan.md listed it as a non-goal; this is the safe,
5
+ read-only foundation for it).
6
+
7
+ What counts as drift - a skill directory inside a product's skills dir
8
+ that is a **real directory** (not a junction/symlink askill created):
9
+
10
+ - ``new`` no same-named skill in the central repo -> ``askill adopt``
11
+ can pull it in
12
+ - ``differs`` same-named skill exists in central but the product's real
13
+ copy has different content -> a decision is needed:
14
+ ``askill sync <skill> --force`` overwrites the product copy
15
+ with central, or the product version should be pulled in
16
+
17
+ Linked/copied-by-askill directories are never drift: junctions and
18
+ symlinks ARE the central repo by construction, and copy-mode results are
19
+ kept in sync by every sync/watch run.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ from pathlib import Path
24
+
25
+ from ..config.products import (
26
+ CENTRAL_DIR,
27
+ PRODUCTS,
28
+ _platform_key,
29
+ get_product_path,
30
+ )
31
+ from ..utils.filesystem import _dirs_equivalent, is_symlink_or_junction
32
+
33
+
34
+ def find_drift(
35
+ product_short: str | None = None,
36
+ central_dir: Path | None = None,
37
+ ) -> dict:
38
+ """Scan product skill dirs for real directories that diverge.
39
+
40
+ Args:
41
+ product_short: Limit the scan to one product (must exist).
42
+ central_dir: Override the central repository (tests).
43
+
44
+ Returns:
45
+ ``{"platform", "scanned": [shorts], "products": {short: {"new":
46
+ [names], "differs": [names]}}, "error": None | str}`` - products
47
+ with no drift are present with empty lists.
48
+ """
49
+ result: dict = {
50
+ "platform": _platform_key(), "scanned": [], "products": {}, "error": None,
51
+ }
52
+ known = sorted(p["short"] for p in PRODUCTS)
53
+ if product_short is not None and product_short not in known:
54
+ # validate against THIS module's PRODUCTS so tests can patch the registry
55
+ result["error"] = (
56
+ f"Unknown product: {product_short} "
57
+ f"(available: {', '.join(known)} or 'all')"
58
+ )
59
+ return result
60
+
61
+ central = Path(central_dir) if central_dir is not None else CENTRAL_DIR
62
+ # enumerate directly (not via list_skills) so a caller-supplied
63
+ # central_dir - tests patch it - is always the view being matched
64
+ central_names = (
65
+ {d.name for d in central.iterdir()
66
+ if d.is_dir() and (d / "SKILL.md").exists()}
67
+ if central.exists() else set()
68
+ )
69
+
70
+ targets = [product_short] if product_short else [p["short"] for p in PRODUCTS]
71
+ for short in targets:
72
+ # look up in THIS module's PRODUCTS so tests can patch the registry
73
+ p = next((x for x in PRODUCTS if x["short"] == short), None)
74
+ entry: dict[str, list[str]] = {"new": [], "differs": []}
75
+ path = get_product_path(p) if p else None
76
+ if p is None or p["sync_method"] != "symlink" or path is None or not path.is_dir():
77
+ result["products"][short] = entry
78
+ continue
79
+ result["scanned"].append(short)
80
+ for item in sorted(path.iterdir()):
81
+ if not item.is_dir() or is_symlink_or_junction(item):
82
+ continue # links are central by construction
83
+ if item.name not in central_names:
84
+ entry["new"].append(item.name)
85
+ elif not _dirs_equivalent(central / item.name, item):
86
+ entry["differs"].append(item.name)
87
+ result["products"][short] = entry
88
+ return result
@@ -0,0 +1,160 @@
1
+ """Reference tier: read a skill without installing it (``askill get``, v0.22.0).
2
+
3
+ Borrowed from asm's ``get`` / ``borrow`` flow: a skill's SKILL.md body is
4
+ only useful while it is loaded, so trying a skill should not require
5
+ installing it into the central repo. ``askill get <source>`` prints the
6
+ SKILL.md to stdout; ``--dir`` copies the full skill folder (supporting
7
+ files, scripts, references) to a temp path for the caller to inspect and
8
+ clean up; ``--list`` shows what a repo offers. Nothing is installed,
9
+ synced, audited, or recorded in source tracking - get is strictly
10
+ read-only.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import shutil
15
+ import tempfile
16
+ from pathlib import Path
17
+
18
+ from .sync.install import _report_clone_failure, _shallow_clone
19
+
20
+ __all__ = ["get_skill"]
21
+
22
+
23
+ def _resolve_repo(source: str) -> tuple[str | None, str | None]:
24
+ """Map a source to (repo_url, skill_hint) for preview.
25
+
26
+ Accepts the same shorthands as install (owner/repo, owner/repo@skill,
27
+ skills.sh links) plus plain GitHub repo and /tree/ URLs.
28
+ """
29
+ from .registry import resolve_source
30
+
31
+ resolved = resolve_source(source)
32
+ if resolved:
33
+ return resolved["repo_url"], resolved["skill"]
34
+ if source.startswith("http") and "github.com" in source:
35
+ if "/tree/" in source:
36
+ parts = source.split("/tree/", 1)
37
+ segs = parts[1].lstrip("/").split("/")
38
+ hint = segs[-1] if len(segs) > 1 else None
39
+ return parts[0], hint
40
+ return source.rstrip("/"), None
41
+ return None, None
42
+
43
+
44
+ def _find_skill_dirs(root: Path) -> list[Path]:
45
+ """Directories containing a SKILL.md, shallowest first (root included)."""
46
+ found = [p.parent for p in root.rglob("SKILL.md")]
47
+ found.sort(key=lambda d: (len(d.parts), str(d).lower()))
48
+ return found
49
+
50
+
51
+ def _get_local(src: Path, *, to_dir: bool, list_only: bool) -> int:
52
+ """Preview a local skill directory without installing (v0.25.0)."""
53
+ dirs = _find_skill_dirs(src)
54
+ if list_only:
55
+ if not dirs:
56
+ print(f"No SKILL.md found under {src}.")
57
+ return 1
58
+ print(f"{len(dirs)} skill(s) under {src}:")
59
+ for d in dirs:
60
+ label = "(this dir)" if d == src else str(d.relative_to(src))
61
+ print(f" {d.name} {label}")
62
+ return 0
63
+
64
+ if dirs and dirs[0] == src:
65
+ skill_dir = src
66
+ elif len(dirs) == 1:
67
+ skill_dir = dirs[0]
68
+ elif [d for d in dirs if d.name == src.name]:
69
+ skill_dir = next(d for d in dirs if d.name == src.name)
70
+ else:
71
+ print("No SKILL.md in this directory or single skill subfolder; found:")
72
+ for d in dirs[:8]:
73
+ print(f" {d.name}")
74
+ return 1
75
+
76
+ if to_dir:
77
+ out = Path(tempfile.gettempdir()) / "askill-get" / skill_dir.name
78
+ if out.exists():
79
+ shutil.rmtree(out)
80
+ out.parent.mkdir(parents=True, exist_ok=True)
81
+ shutil.copytree(skill_dir, out)
82
+ print(f"Borrowed to: {out}")
83
+ print("Plain temp copy - delete the folder when done.")
84
+ return 0
85
+
86
+ print((skill_dir / "SKILL.md").read_text(encoding="utf-8", errors="replace"))
87
+ return 0
88
+
89
+
90
+ def get_skill(
91
+ source: str,
92
+ *,
93
+ to_dir: bool = False,
94
+ list_only: bool = False,
95
+ verbose: bool = True,
96
+ ) -> int:
97
+ """Preview a skill without installing. Returns a process exit code."""
98
+ # v0.25.0: local directory - same read-only semantics, no clone
99
+ if not source.startswith("http"):
100
+ src = Path(source)
101
+ if src.exists() and src.is_dir():
102
+ return _get_local(src, to_dir=to_dir, list_only=list_only)
103
+
104
+ repo_url, hint = _resolve_repo(source)
105
+ if not repo_url:
106
+ print("Unsupported source. Use owner/repo@skill, owner/repo, or a GitHub URL.")
107
+ return 2
108
+
109
+ with tempfile.TemporaryDirectory() as tmp:
110
+ ok, err = _shallow_clone(repo_url, None, Path(tmp))
111
+ if not ok:
112
+ if verbose:
113
+ _report_clone_failure(err)
114
+ return 1
115
+ root = Path(tmp)
116
+
117
+ dirs = _find_skill_dirs(root)
118
+
119
+ if list_only:
120
+ if not dirs:
121
+ print("No SKILL.md found in this repo.")
122
+ return 1
123
+ print(f"{len(dirs)} skill(s) in {repo_url}:")
124
+ for d in dirs:
125
+ label = "(repo root)" if d == root else str(d.relative_to(root))
126
+ print(f" {d.name} {label}")
127
+ print("\nPreview one: askill get <repo>@<skill>")
128
+ return 0
129
+
130
+ if hint:
131
+ match = next((d for d in dirs if d.name == hint), None)
132
+ if match is None:
133
+ print(f"Skill '{hint}' not found in {repo_url}.")
134
+ print("List what exists: askill get <repo> --list")
135
+ return 1
136
+ skill_dir = match
137
+ elif dirs and dirs[0] == root:
138
+ skill_dir = root
139
+ elif len(dirs) == 1:
140
+ skill_dir = dirs[0]
141
+ else:
142
+ print("No SKILL.md at repo root and multiple skill folders found:")
143
+ for d in dirs:
144
+ print(f" {d.name}")
145
+ print("Pick one: askill get <repo>@<skill>")
146
+ return 1
147
+
148
+ if to_dir:
149
+ out = Path(tempfile.gettempdir()) / "askill-get" / skill_dir.name
150
+ if out.exists():
151
+ shutil.rmtree(out)
152
+ out.parent.mkdir(parents=True, exist_ok=True)
153
+ shutil.copytree(skill_dir, out)
154
+ print(f"Borrowed to: {out}")
155
+ print("Plain temp copy - read SKILL.md and the supporting files,")
156
+ print("then delete the folder when done.")
157
+ return 0
158
+
159
+ print((skill_dir / "SKILL.md").read_text(encoding="utf-8", errors="replace"))
160
+ return 0
@@ -0,0 +1,37 @@
1
+ """Central-repo skill enumeration (read-only inventory layer).
2
+
3
+ Split out of :mod:`services.sync` so ``spec`` can enumerate skills without
4
+ importing the sync engine (spec ⇄ sync formed a module-level import cycle,
5
+ found by the 2026-10-31 architecture health check §3). ``sync`` keeps a
6
+ thin ``list_skills()`` wrapper that reads its own ``CENTRAL_DIR`` module
7
+ attribute, so the established ``patch sync.CENTRAL_DIR`` test seam keeps
8
+ working for every existing consumer.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from pathlib import Path
14
+
15
+ from ..config.products import CENTRAL_DIR
16
+
17
+ __all__ = ["list_skills"]
18
+
19
+
20
+ def list_skills(central: Path | None = None) -> list[Path]:
21
+ """List all skills in the central repository.
22
+
23
+ Args:
24
+ central: override the central repository (tests, tooling).
25
+ Defaults to the configured ``CENTRAL_DIR``.
26
+
27
+ Returns:
28
+ Sorted list of skill directory paths (directories that contain
29
+ a ``SKILL.md``).
30
+ """
31
+ base = Path(central) if central is not None else CENTRAL_DIR
32
+ if not base.exists():
33
+ return []
34
+ return sorted(
35
+ d for d in base.iterdir()
36
+ if d.is_dir() and (d / "SKILL.md").exists()
37
+ )