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,167 @@
1
+ """Team manifest sync: export the central skill list, align another machine.
2
+
3
+ ``askill bundle`` writes ``askill-manifest.json``: every central-repo skill
4
+ with its name, an explicit ``origin`` (``git`` for tracked sources, ``local``
5
+ for hand-authored skills) and - when available - the origin needed to
6
+ reinstall. ``askill install --manifest PATH`` aligns the local central repo
7
+ to that list: missing skills are installed from their recorded origin, present
8
+ ones are reported, local skills are listed for manual handling.
9
+
10
+ The manifest is deliberately human-readable JSON so it can be committed to a
11
+ team repository and reviewed like code. Zero network on bundle; install
12
+ touches the network only for git-sourced skills that are missing.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ from pathlib import Path
18
+
19
+ from ..config.products import CENTRAL_DIR
20
+ from .inventory import list_skills
21
+ from .sources import load_sources
22
+ from .sync.install import _install_from_url
23
+
24
+ MANIFEST_NAME = "askill-manifest.json"
25
+ MANIFEST_VERSION = 1
26
+
27
+ __all__ = ["MANIFEST_NAME", "MANIFEST_VERSION", "bundle_manifest", "install_manifest"]
28
+
29
+
30
+ def bundle_manifest(
31
+ output: Path | None = None,
32
+ central: Path | None = None,
33
+ verbose: bool = True,
34
+ external_only: bool = False,
35
+ ) -> Path:
36
+ """Write the manifest for the central repository.
37
+
38
+ Args:
39
+ output: where to write (default: ``<central-parent>/askill-manifest.json``).
40
+ central: override the central repository (tests).
41
+ verbose: print a one-line summary.
42
+ external_only: skip locally authored skills (``origin: local``), so a
43
+ teammate's manifest contains only reproducible remote installs.
44
+
45
+ Returns:
46
+ Path of the written manifest.
47
+ """
48
+ base = Path(central) if central is not None else CENTRAL_DIR
49
+ sources = load_sources()
50
+ skills: list[dict] = []
51
+ for d in list_skills(base):
52
+ info = sources.get(d.name)
53
+ source = None
54
+ if info and info.get("repo_url"):
55
+ source = {
56
+ "kind": "git",
57
+ "repo_url": info["repo_url"],
58
+ "sub_path": info.get("sub_path") or "",
59
+ "branch": info.get("branch"),
60
+ }
61
+ origin = "git" if source else "local"
62
+ if external_only and origin == "local":
63
+ continue
64
+ skills.append({"name": d.name, "origin": origin, "source": source})
65
+
66
+ manifest = {
67
+ "version": MANIFEST_VERSION,
68
+ "generated_by": "askill",
69
+ "skills": skills,
70
+ }
71
+ out = Path(output) if output is not None else base.parent / MANIFEST_NAME
72
+ out.parent.mkdir(parents=True, exist_ok=True)
73
+ out.write_text(
74
+ json.dumps(manifest, ensure_ascii=False, indent=2) + "\n",
75
+ encoding="utf-8",
76
+ )
77
+ if verbose:
78
+ tracked = sum(1 for s in skills if s["origin"] == "git")
79
+ print(f"Manifest written: {out}")
80
+ print(
81
+ f" {len(skills)} skill(s), {tracked} with reinstall source, "
82
+ f"{len(skills) - tracked} locally authored"
83
+ + (" (filtered out by --external-only)" if external_only else "")
84
+ )
85
+ return out
86
+
87
+
88
+ def install_manifest(
89
+ path: Path,
90
+ central: Path | None = None,
91
+ verbose: bool = True,
92
+ ) -> dict:
93
+ """Align the local central repository to a manifest.
94
+
95
+ Missing skills are installed from their recorded git origin (network
96
+ only for those); present skills are reported; local skills without a
97
+ reusable source are returned in ``manual`` with an explicit reason and
98
+ are **never** fetched from the network.
99
+
100
+ Returns:
101
+ ``{"ok", "error", "installed", "present", "failed", "manual"}``.
102
+ ``ok`` is False only when the manifest itself cannot be read or is
103
+ an unsupported version; per-skill problems surface in the lists.
104
+ """
105
+ report: dict = {
106
+ "ok": True, "error": None,
107
+ "installed": [], "present": [], "failed": [], "manual": [],
108
+ }
109
+ p = Path(path)
110
+ try:
111
+ data = json.loads(p.read_text(encoding="utf-8"))
112
+ except (OSError, ValueError) as e:
113
+ report["ok"] = False
114
+ report["error"] = f"cannot read manifest: {e}"
115
+ return report
116
+ if data.get("version") != MANIFEST_VERSION:
117
+ report["ok"] = False
118
+ report["error"] = (
119
+ f"unsupported manifest version {data.get('version')!r} "
120
+ f"(expected {MANIFEST_VERSION})"
121
+ )
122
+ return report
123
+
124
+ base = Path(central) if central is not None else CENTRAL_DIR
125
+ base.mkdir(parents=True, exist_ok=True)
126
+
127
+ for entry in data.get("skills", []):
128
+ name = entry.get("name")
129
+ if not name:
130
+ continue
131
+ dest = base / name
132
+ if dest.exists():
133
+ report["present"].append(name)
134
+ if verbose:
135
+ print(f" {name}: already in central repo")
136
+ continue
137
+ source = entry.get("source") or {}
138
+ if source.get("kind") != "git" or not source.get("repo_url"):
139
+ origin = entry.get("origin") or ("local" if not source else "unknown")
140
+ why = (
141
+ "locally authored skill - copy it from the team repo manually "
142
+ "(no remote source, network not attempted)"
143
+ if origin == "local" else
144
+ "no reinstall source recorded - install manually"
145
+ )
146
+ report["manual"].append((name, why))
147
+ if verbose:
148
+ print(f" {name}: {why}")
149
+ continue
150
+ url = source["repo_url"]
151
+ if source.get("sub_path"):
152
+ url = f"{url}/tree/{source.get('branch') or 'HEAD'}/{source['sub_path']}"
153
+ elif source.get("branch"):
154
+ url = f"{url}/tree/{source['branch']}"
155
+ if verbose:
156
+ print(f" {name}: installing from {url}")
157
+ try:
158
+ installed_name, ok = _install_from_url(url, verbose=verbose)
159
+ except Exception as e: # network/git failures must not abort the run
160
+ installed_name, ok = None, False
161
+ if verbose:
162
+ print(f" {name}: install error: {e}")
163
+ if ok and installed_name:
164
+ report["installed"].append(installed_name)
165
+ else:
166
+ report["failed"].append((name, "install failed (see output above)"))
167
+ return report
@@ -0,0 +1,112 @@
1
+ """Deterministic description-overlap audit (``askill audit --overlap``, P1-9).
2
+
3
+ Every installed skill's ``description`` sits in the agent's context whether
4
+ or not the skill is used. Two skills with near-identical descriptions both
5
+ cost tokens *and* make activation ambiguous. This module ranks such pairs.
6
+
7
+ It is deliberately **lexical, not semantic**: word tokens plus CJK character
8
+ bigrams, Jaccard similarity, stable sort. No embeddings, no LLM, no network,
9
+ no third-party dependency. Results are a triage hint, never a verdict.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ from pathlib import Path
16
+
17
+ from .inventory import list_skills
18
+ from .spec import parse_frontmatter
19
+
20
+ __all__ = ["overlap_rows", "render_overlap"]
21
+
22
+ STOPWORDS = {
23
+ "a", "an", "and", "are", "as", "at", "be", "by", "for", "from", "how",
24
+ "in", "is", "it", "of", "on", "or", "that", "the", "this", "to", "use",
25
+ "used", "using", "when", "with", "you", "your", "skill", "skills",
26
+ "agent", "agents", "should", "can", "help", "helps",
27
+ }
28
+
29
+ _WORD = re.compile(r"[a-z0-9][a-z0-9_-]{2,}")
30
+ _CJK = re.compile(r"[\u4e00-\u9fff]")
31
+
32
+
33
+ def _tokens(text: str) -> set[str]:
34
+ """English word tokens + CJK character bigrams (no tokenizer dependency)."""
35
+ lowered = text.lower()
36
+ words = {w for w in _WORD.findall(lowered) if w not in STOPWORDS}
37
+ chars = _CJK.findall(lowered)
38
+ bigrams = {chars[i] + chars[i + 1] for i in range(len(chars) - 1)}
39
+ return words | bigrams
40
+
41
+
42
+ def overlap_rows(central: Path, threshold: float = 0.6) -> list[dict]:
43
+ """Return description-overlap pairs, sorted by score then name (stable).
44
+
45
+ ``shared`` lists the common tokens so a human can judge whether the pair
46
+ is a real duplicate or just shares domain vocabulary.
47
+ """
48
+ descriptions: dict[str, str] = {}
49
+ for skill_dir in list_skills(central):
50
+ try:
51
+ text = (skill_dir / "SKILL.md").read_text(
52
+ encoding="utf-8", errors="replace",
53
+ )
54
+ frontmatter, _ = parse_frontmatter(text)
55
+ except OSError:
56
+ continue
57
+ desc = str(frontmatter.get("description") or "").strip()
58
+ if desc:
59
+ descriptions[skill_dir.name] = desc
60
+
61
+ names = sorted(descriptions)
62
+ tokens = {name: _tokens(descriptions[name]) for name in names}
63
+ rows: list[dict] = []
64
+ for i, first in enumerate(names):
65
+ for second in names[i + 1:]:
66
+ a, b = tokens[first], tokens[second]
67
+ if not a or not b:
68
+ continue
69
+ shared = a & b
70
+ score = len(shared) / len(a | b)
71
+ if score < threshold:
72
+ continue
73
+ rows.append({
74
+ "skill_a": first,
75
+ "skill_b": second,
76
+ "score": round(score, 3),
77
+ "shared": sorted(shared)[:8],
78
+ "suggestion": (
79
+ "likely duplicate - consider merging or removing one"
80
+ if score >= 0.85 else
81
+ "overlapping descriptions - differentiate or consolidate"
82
+ ),
83
+ })
84
+ rows.sort(key=lambda r: (-r["score"], r["skill_a"], r["skill_b"]))
85
+ return rows
86
+
87
+
88
+ def render_overlap(rows: list[dict], threshold: float) -> str:
89
+ """Human-readable, bounded-width report."""
90
+ lines = [
91
+ f"askill audit --overlap - deterministic description overlap (Jaccard >= {threshold})",
92
+ "",
93
+ "Lexical similarity only (word tokens + CJK bigrams); verify each pair by reading the SKILL.md files. Not a semantic judgement.",
94
+ "",
95
+ ]
96
+ if not rows:
97
+ lines.append(" No description pairs above the threshold.")
98
+ return "\n".join(lines) + "\n"
99
+ lines += [
100
+ f" {len(rows)} pair(s) found:",
101
+ "",
102
+ f" {'skill A':<26} {'skill B':<26} {'score':>6} shared tokens",
103
+ " " + "-" * 78,
104
+ ]
105
+ for row in rows:
106
+ shared = ", ".join(row["shared"][:5]) or "—"
107
+ lines.append(
108
+ f" {row['skill_a'][:25]:<26} {row['skill_b'][:25]:<26} "
109
+ f"{row['score']:>6.3f} {shared}"
110
+ )
111
+ lines.append(f" -> {row['suggestion']}")
112
+ return "\n".join(lines) + "\n"
@@ -0,0 +1,204 @@
1
+ """Machine-readable export of the declarative product registry.
2
+
3
+ Design constraints (see ``docs/optimization-report-2026-11-15.md`` P1-5):
4
+
5
+ * ``config/products.py`` stays the **only** source of truth. Every field here
6
+ is derived from a ``ProductSpec``; nothing is hard-coded.
7
+ * Stdlib only, and **no intra-package imports**. The companion script
8
+ ``scripts/export_agents_md.py`` loads this module by file path, so the export
9
+ works from a fresh clone without ``pip install -e .`` and without dragging a
10
+ package hierarchy into ``sys.path``.
11
+ * Absolute home paths are rendered as portable ``~/...`` / ``%LOCALAPPDATA%/...``
12
+ strings — an upstream PR must never contain a maintainer's home directory.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import re
18
+ from collections.abc import Iterable, Mapping
19
+ from datetime import date
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ PLATFORMS = ("macos", "windows", "linux")
24
+ UPSTREAM_AGENTS_MD_URL = (
25
+ "https://github.com/vercel-labs/skills/blob/main/docs/agents.md"
26
+ )
27
+
28
+
29
+ def _portable(path: Any, *, home: Path, localappdata: Path) -> str | None:
30
+ """Render an absolute path as ``~/...`` / ``%LOCALAPPDATA%/...``.
31
+
32
+ ``LOCALAPPDATA`` is checked first because on Windows it usually lives
33
+ *under* the home directory; checking home first would hide it.
34
+ Unknown roots fall back to the absolute POSIX form rather than being
35
+ silently rewritten.
36
+ """
37
+ if path is None:
38
+ return None
39
+ p = Path(path)
40
+ for prefix, label in ((localappdata, "%LOCALAPPDATA%"), (home, "~")):
41
+ try:
42
+ rel = p.relative_to(prefix)
43
+ except (ValueError, TypeError):
44
+ continue
45
+ return label if str(rel) == "." else f"{label}/{rel.as_posix()}"
46
+ return p.as_posix()
47
+
48
+
49
+ def build_path_records(
50
+ products: Iterable[Mapping[str, Any]],
51
+ *,
52
+ home: Path,
53
+ localappdata: Path,
54
+ ) -> list[dict[str, Any]]:
55
+ """Derive a full cross-platform, portable record per declared product."""
56
+ def rel(value: Any) -> str | None:
57
+ return _portable(value, home=home, localappdata=localappdata)
58
+
59
+ records: list[dict[str, Any]] = []
60
+ for p in products:
61
+ records.append({
62
+ "name": p.get("name", ""),
63
+ "short": p.get("short", ""),
64
+ "sync_method": p.get("sync_method", ""),
65
+ "macos_path": rel(p.get("macos_path")),
66
+ "windows_path": rel(p.get("windows_path")),
67
+ "linux_path": rel(p.get("linux_path")),
68
+ "extra_dirs": {
69
+ plat: [rel(d) for d in (p.get(f"extra_dirs_{plat}") or [])]
70
+ for plat in PLATFORMS
71
+ },
72
+ "settings_file": rel(p.get("settings_file")),
73
+ "settings_mode": p.get("settings_mode"),
74
+ "required_frontmatter": list(p.get("required_frontmatter") or []),
75
+ "note": p.get("note", ""),
76
+ })
77
+
78
+ # ``shared_with`` is derived, never declared: two products sharing both
79
+ # primary paths are directory aliases (Trae CN / TRAE SOLO CN, etc.).
80
+ # Pack products have no paths and therefore never form a shared group.
81
+ groups: dict[tuple[str | None, str | None], list[str]] = {}
82
+ for rec in records:
83
+ key = (rec["macos_path"], rec["windows_path"])
84
+ if key[0] or key[1]:
85
+ groups.setdefault(key, []).append(rec["short"])
86
+ for rec in records:
87
+ key = (rec["macos_path"], rec["windows_path"])
88
+ rec["shared_with"] = [s for s in groups.get(key, []) if s != rec["short"]]
89
+ return records
90
+
91
+
92
+ def _slug(value: str) -> str:
93
+ """Normalise a product/agent label for conservative name matching."""
94
+ return re.sub(r"[^a-z0-9]", "", value.lower())
95
+
96
+
97
+ def _base_name(name: str) -> str:
98
+ """Drop company suffixes and aliases: ``Comate / Wenxin ...`` -> ``Comate``."""
99
+ return name.split("/")[0].split("(")[0].strip()
100
+
101
+
102
+ def parse_upstream_agents(text: str) -> set[str]:
103
+ """Extract normalised agent labels from an upstream ``agents.md`` table.
104
+
105
+ Only the first three columns of markdown table rows are considered
106
+ (agent name, ``--agent`` identifiers, project path); backticked literals
107
+ are indexed separately so ``trae-cn`` matches the ``Trae CN`` label.
108
+ """
109
+ tokens: set[str] = set()
110
+ for line in text.splitlines():
111
+ stripped = line.strip()
112
+ if not stripped.startswith("|"):
113
+ continue
114
+ cells = [c.strip() for c in stripped.strip("|").split("|")]
115
+ for cell in cells[:3]:
116
+ for literal in re.findall(r"`([^`]+)`", cell):
117
+ slug = _slug(literal)
118
+ if slug:
119
+ tokens.add(slug)
120
+ slug = _slug(cell)
121
+ if slug:
122
+ tokens.add(slug)
123
+ return tokens
124
+
125
+
126
+ def match_upstream(record: dict[str, Any], tokens: set[str]) -> str | None:
127
+ """Return the upstream token that covers this record, or ``None``.
128
+
129
+ Deliberately conservative: the record's base-name slug must equal a token
130
+ or be contained in one (``kimi`` -> ``kimicodecli``). Short generic tokens
131
+ are not allowed to match *into* a record, so ``qwen-code`` does not
132
+ silently cover ``qwenwork``.
133
+ """
134
+ candidates = {_slug(_base_name(record["name"])), _slug(record["short"])}
135
+ candidates.discard("")
136
+ exact = sorted(token for token in tokens if token in candidates)
137
+ if exact:
138
+ return exact[0]
139
+ # Multi-agent rows ("Cline, Kimi Code CLI, Zed, ...") produce one very
140
+ # long token; prefer the shortest containing token so the gap report
141
+ # shows `kimicodecli` rather than that whole merged cell.
142
+ partial = [t for t in tokens if any(c in t for c in candidates)]
143
+ return min(partial, key=lambda t: (len(t), t)) if partial else None
144
+
145
+
146
+ def render_agents_md(
147
+ records: list[dict[str, Any]],
148
+ *,
149
+ upstream_text: str | None = None,
150
+ generated_on: str | None = None,
151
+ ) -> str:
152
+ """Render a paste-ready upstream contribution fragment.
153
+
154
+ ``upstream_text`` is an optional local snapshot of the upstream
155
+ ``agents.md``; when supplied, a "not covered yet" section is appended so
156
+ a PR author knows exactly which rows are worth proposing.
157
+ """
158
+ day = generated_on or date.today().isoformat()
159
+
160
+ def cell(value: str | None) -> str:
161
+ return f"`{value}`" if value else "—"
162
+
163
+ lines = [
164
+ f"# askill product paths (exported {day})",
165
+ "",
166
+ "> Source of truth: `src/config/products.py`, exported via `askill products --json --paths`.",
167
+ f"> Intended for upstream contributions such as [npx skills agents.md]({UPSTREAM_AGENTS_MD_URL}).",
168
+ "> Project Path is `—`: askill manages user-level directories only; project-level paths must be confirmed by the upstream maintainer.",
169
+ "",
170
+ "| Agent | `--agent` | Project Path | Global Path (macOS) | Global Path (Windows) | Linux | sync | shared_with | note |",
171
+ "|---|---|---|---|---|---|---|---|---|",
172
+ ]
173
+ for r in records:
174
+ note = (r.get("note") or "").replace("|", "\\|")
175
+ shared = ", ".join(r.get("shared_with") or []) or "—"
176
+ lines.append(
177
+ f"| {r['name']} | `{r['short']}` | — | {cell(r['macos_path'])} | "
178
+ f"{cell(r['windows_path'])} | {cell(r['linux_path'])} | "
179
+ f"{r['sync_method']} | {shared} | {note} |"
180
+ )
181
+
182
+ if upstream_text is not None:
183
+ tokens = parse_upstream_agents(upstream_text)
184
+ missing = [r for r in records if match_upstream(r, tokens) is None]
185
+ lines += [
186
+ "",
187
+ f"## Not covered upstream ({len(missing)} of {len(records)}, snapshot {day})",
188
+ "",
189
+ "> Name matching is conservative and automatic — verify each row against the live upstream file before opening a PR.",
190
+ "",
191
+ "| Agent | short | Global Path (macOS) | Global Path (Windows) |",
192
+ "|---|---|---|---|",
193
+ ]
194
+ for r in missing:
195
+ lines.append(
196
+ f"| {r['name']} | `{r['short']}` | {cell(r['macos_path'])} | "
197
+ f"{cell(r['windows_path'])} |"
198
+ )
199
+ lines += ["", "Covered rows:", ""]
200
+ for r in records:
201
+ token = match_upstream(r, tokens)
202
+ if token:
203
+ lines.append(f"- `{r['short']}` → `{token}`")
204
+ return "\n".join(lines) + "\n"