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,441 @@
1
+ """Static security audit for agent skills.
2
+
3
+ Zero-dependency static analysis of a skill directory. Detects:
4
+ - prompt injection / instruction-override patterns in SKILL.md
5
+ - dangerous code patterns in bundled scripts (exec, eval, shell pipes, ...)
6
+ - data exfiltration patterns (sensitive paths, secrets, webhooks, outbound POST)
7
+ - network access in instructions and scripts
8
+ - binary payloads (executables and unexpected binary data)
9
+ - file integrity issues (missing SKILL.md, oversized files, too many files)
10
+
11
+ Scoring: start at 100 and subtract weighted severities (capped per category).
12
+ Grade: A >= 90, B >= 80, C >= 70, D >= 60, F < 60.
13
+ Verdict: safe / caution / risky / dangerous.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ import re
20
+ from concurrent.futures import ThreadPoolExecutor
21
+ from pathlib import Path
22
+
23
+ from ..models.report import Finding, SkillReport
24
+
25
+ # ---------------------------------------------------------------- constants
26
+
27
+ SCRIPT_EXTS = {
28
+ ".py", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".sh", ".bash", ".zsh",
29
+ ".bat", ".cmd", ".ps1", ".psm1", ".rb", ".pl", ".go", ".rs", ".java", ".exs",
30
+ }
31
+ MARKDOWN_EXTS = {".md", ".markdown"}
32
+ # Extensions treated as known-safe binary data files (images, fonts, archives)
33
+ BINARY_DATA_EXTS = {
34
+ ".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp", ".ico", ".bmp",
35
+ ".pdf", ".woff", ".woff2", ".ttf", ".otf", ".zip", ".gz", ".tar", ".7z",
36
+ }
37
+ # Extensions treated as executable / native binaries
38
+ BINARY_EXEC_EXTS = {
39
+ ".exe", ".dll", ".so", ".dylib", ".bin", ".scr", ".jar", ".class",
40
+ ".msi", ".pkg", ".app", ".o", ".a", ".sys", ".drv",
41
+ }
42
+ MAX_FILE_BYTES = 5 * 1024 * 1024
43
+ MAX_TOTAL_BYTES = 50 * 1024 * 1024
44
+ MAX_FILES = 200
45
+
46
+ # Development artifacts skipped entirely (not skill payload).
47
+ SKIP_DIRS = {".git", ".hg", ".svn", "__pycache__", "node_modules",
48
+ ".venv", "venv", ".idea", ".vscode", ".DS_Store", "dist", "build"}
49
+ SKIP_FILE_SUFFIXES = {".pyc", ".pyo", ".class", ".log", ".tmp", ".swp"}
50
+ SKIP_FILE_NAMES = {".DS_Store", "Thumbs.db"}
51
+
52
+ # P0-2: development / test code is still scanned (so nothing is hidden from a
53
+ # human reviewer) but findings there are down-weighted - benign dev tooling
54
+ # such as a dev-server stop script matching "shutdown", or a test fixture
55
+ # referencing ~/.ssh, must not masquerade as a real runtime risk and sink
56
+ # the skill's security score. Opt out via the ASKILL_AUDIT_DEV_MODE env var:
57
+ # downweight (default) | skip (ignore dev/test files entirely) | off (legacy)
58
+ DEV_CONTEXT_SEGMENTS = {
59
+ "test", "tests", "spec", "specs", "__tests__", "fixtures", "fixture",
60
+ "mock", "mocks", "example", "examples", "docs", "doc", "bin", "scripts",
61
+ "dev", "staging", "e2e", "tmp", "temp",
62
+ }
63
+ DEV_CONTEXT_SUFFIXES = (
64
+ ".test.", ".tests.", ".spec.", "-test.", "-spec.", "_test.", "_spec.",
65
+ )
66
+ # Severity reduction applied to findings inside a dev/test path.
67
+ _DEV_REDUCE = {"critical": "medium", "high": "low", "medium": "low", "low": "low", "info": "info"}
68
+
69
+
70
+ def _is_dev_context(rel: Path) -> bool:
71
+ """True if *rel* lives in a development / test path rather than the
72
+ skill's runtime payload (e.g. a ``tests/`` or ``bin/`` sub-directory, or a
73
+ ``foo.test.js`` file)."""
74
+ if set(rel.parts) & DEV_CONTEXT_SEGMENTS:
75
+ return True
76
+ name = rel.name.lower()
77
+ return any(s in name for s in DEV_CONTEXT_SUFFIXES)
78
+
79
+ SEVERITY_WEIGHTS = {"critical": 40, "high": 20, "medium": 10, "low": 3, "info": 0}
80
+ _CATEGORY_CAP = 40
81
+ # P0-2: a much smaller cap for minor (low) findings per category. Without it,
82
+ # dozens of benign pattern hits (a URL, a .env reference, a child_process call
83
+ # in legitimate code) summed past the serious cap and let a large but harmless
84
+ # skill score an F. Now only genuine critical/high/medium risks drive the
85
+ # score down; low-severity noise is capped at _MINOR_CAP per category.
86
+ _MINOR_CAP = 10
87
+
88
+ # ---------------------------------------------------------------- patterns
89
+
90
+ # (severity, regex, message) — matched against SKILL.md / markdown content.
91
+ PROMPT_PATTERNS = [
92
+ ("critical", re.compile(r"ignore\s+(all\s+|any\s+)?(previous|prior|earlier|above)\s+(instructions?|rules?|guidelines?|directives?)", re.IGNORECASE),
93
+ "prompt injection: instruction override detected"),
94
+ ("critical", re.compile(r"disregard\s+(all\s+|any\s+)?(previous|prior|earlier|above|safety)?\s*(instructions?|rules?|guidelines?|directives?)", re.IGNORECASE),
95
+ "prompt injection: 'disregard instructions' pattern"),
96
+ ("critical", re.compile(r"bypass\s+(the\s+|all\s+)?(safety|security|sandbox|content\s*filter|moderation)", re.IGNORECASE),
97
+ "prompt injection: bypass-safety language"),
98
+ ("critical", re.compile(r"(steal|exfiltrate|leak)\s+(the\s+|user'?s\s+|all\s+)?(data|files|credentials|secrets|conversation)", re.IGNORECASE),
99
+ "exfiltration instruction in prompt text"),
100
+ ("critical", re.compile(r"never\s+(ask|request|seek)\s+(for\s+)?(permission|consent|confirmation|approval)", re.IGNORECASE),
101
+ "instructed to act without user permission"),
102
+ ("critical", re.compile(r"do\s+not\s+(follow|obey|comply\s+with)\s+(any\s+|the\s+)?(safety|security|policy|policies|rules?|guardrails?)", re.IGNORECASE),
103
+ "instructed to ignore safety rules"),
104
+ ("critical", re.compile(r"(turn|switch)\s+off\s+(safety|security|guardrails?)", re.IGNORECASE),
105
+ "instructed to disable safety features"),
106
+ ("critical", re.compile(r"(disable|deactivate)\s+(all\s+)?(safety|security|guardrails?|sandbox)", re.IGNORECASE),
107
+ "instructed to deactivate safeguards"),
108
+ ("high", re.compile(r"(hide|conceal)\s+(your|this|the)\s+(activity|actions?|behavior|tracks?)", re.IGNORECASE),
109
+ "instructed to hide its activity"),
110
+ ("high", re.compile(r"do\s+not\s+(tell|inform|disclose|reveal|mention)\s+(the\s+)?user", re.IGNORECASE),
111
+ "instructed to withhold information from the user"),
112
+ ("high", re.compile(r"(silently|secretly)\s+(send|upload|copy|exfiltrate)", re.IGNORECASE),
113
+ "covert data transfer instruction"),
114
+ ("high", re.compile(r"without\s+(the\s+)?user'?s\s+(knowledge|awareness|consent|permission)", re.IGNORECASE),
115
+ "acting without user awareness"),
116
+ ("high", re.compile(r"(send|upload|post|transmit)\s+(this|all|the|collected)\s+(data|files|conversation|content)\s+to", re.IGNORECASE),
117
+ "instructed to send data to an external party"),
118
+ ("medium", re.compile(r"(discord(app)?\.com/api/webhooks|hooks\.slack\.com/services|open\.feishu\.cn/open-apis|qyapi\.weixin\.qq\.com/cgi-bin/webhook|api\.telegram\.org/bot)", re.IGNORECASE),
119
+ "webhook URL in instructions"),
120
+ ("medium", re.compile(r"(phishing|keylog\w*|record\s+keystrokes|screen\s*capture)", re.IGNORECASE),
121
+ "credential-harvesting language"),
122
+ ("low", re.compile(r"https?://[^\s\)\]\">]+", re.IGNORECASE),
123
+ "network endpoint referenced in instructions"),
124
+ ]
125
+
126
+ # (severity, regex, message) — matched against script files.
127
+ CODE_PATTERNS = [
128
+ ("critical", re.compile(r"(curl|wget)\b[^\n|]{0,200}\|\s*(ba)?sh\b", re.IGNORECASE),
129
+ "remote content piped to shell (curl|sh)"),
130
+ ("critical", re.compile(r"(curl|wget)\b[^\n|]{0,200}\|\s*zsh\b", re.IGNORECASE),
131
+ "remote content piped to zsh"),
132
+ ("critical", re.compile(r"irm\s+\S+\s*\|\s*iex", re.IGNORECASE),
133
+ "PowerShell download-and-execute (irm | iex)"),
134
+ ("critical", re.compile(r"\bnc\s+-e\b", re.IGNORECASE),
135
+ "netcat reverse shell"),
136
+ ("critical", re.compile(r"\bbash\s+-i\s*>&", re.IGNORECASE),
137
+ "interactive reverse shell"),
138
+ ("critical", re.compile(r"\brm\s+-rf\s+(/|/tmp|/var|/usr|/etc|~)", re.IGNORECASE),
139
+ "destructive recursive delete of system paths"),
140
+ ("critical", re.compile(r"\bmkfs\b", re.IGNORECASE),
141
+ "filesystem format command"),
142
+ ("critical", re.compile(r"\bformat\s+[c-zC-Z]:", re.IGNORECASE),
143
+ "Windows drive format command"),
144
+ ("high", re.compile(r"(?<!\.)\bexec\s*\(", re.IGNORECASE),
145
+ "dynamic code execution (exec)"),
146
+ ("high", re.compile(r"subprocess\b[\s\S]{0,120}?shell\s*=\s*True", re.IGNORECASE),
147
+ "shell=True subprocess call"),
148
+ ("high", re.compile(r"Invoke-Expression", re.IGNORECASE),
149
+ "PowerShell Invoke-Expression"),
150
+ ("high", re.compile(r"\biex\s*\(", re.IGNORECASE),
151
+ "PowerShell iex call"),
152
+ ("high", re.compile(r"-EncodedCommand", re.IGNORECASE),
153
+ "PowerShell encoded command"),
154
+ ("high", re.compile(r"new\s+Function\s*\(", re.IGNORECASE),
155
+ "JavaScript dynamic function constructor"),
156
+ ("high", re.compile(r"\brm\s+-rf\b", re.IGNORECASE),
157
+ "recursive delete (rm -rf)"),
158
+ ("high", re.compile(r"\bdd\s+if=", re.IGNORECASE),
159
+ "raw disk write (dd)"),
160
+ ("high", re.compile(r"\bshutdown\b", re.IGNORECASE),
161
+ "system shutdown command"),
162
+ ("high", re.compile(r"(\.ssh|\.aws|\.gnupg|id_rsa|id_ed25519|\.netrc)", re.IGNORECASE),
163
+ "reads sensitive credential files"),
164
+ ("medium", re.compile(r"\beval\s*\(", re.IGNORECASE),
165
+ "dynamic code evaluation (eval)"),
166
+ ("medium", re.compile(r"os\.system\s*\(", re.IGNORECASE),
167
+ "shell command via os.system"),
168
+ ("medium", re.compile(r"__import__\s*\(", re.IGNORECASE),
169
+ "dynamic module import"),
170
+ ("medium", re.compile(r"base64\.b64decode\s*\(", re.IGNORECASE),
171
+ "base64 payload decoding"),
172
+ ("medium", re.compile(r"\bDownloadString\b", re.IGNORECASE),
173
+ "PowerShell DownloadString"),
174
+ ("medium", re.compile(r"\bDownloadFile\b", re.IGNORECASE),
175
+ "PowerShell DownloadFile"),
176
+ ("medium", re.compile(r"child_process", re.IGNORECASE),
177
+ "JavaScript child_process usage"),
178
+ ("medium", re.compile(r"curl\s+\S+\s+(-d\b|--data\b|-X\s+POST)", re.IGNORECASE),
179
+ "outbound POST via curl"),
180
+ ("medium", re.compile(r"requests\.(post|put)\s*\(", re.IGNORECASE),
181
+ "outbound data upload via requests"),
182
+ ("low", re.compile(r"\.env", re.IGNORECASE),
183
+ "references .env (possible secrets file)"),
184
+ ("low", re.compile(r"(api[_-]?key|access[_-]?token|secret[_-]?key|client[_-]?secret)\s*[:=]", re.IGNORECASE),
185
+ "hardcoded secret in code"),
186
+ ("low", re.compile(r"fetch\s*\(\s*['\"]https?://", re.IGNORECASE),
187
+ "network fetch to remote URL"),
188
+ ("low", re.compile(r"https?://", re.IGNORECASE),
189
+ "network access in script"),
190
+ ]
191
+
192
+
193
+ def _read_bytes(path: Path) -> bytes:
194
+ try:
195
+ with open(path, "rb") as f:
196
+ return f.read(4096)
197
+ except OSError:
198
+ return b""
199
+
200
+
201
+ def _is_binary(chunk: bytes) -> bool:
202
+ return b"\x00" in chunk
203
+
204
+
205
+ def _scan_text(
206
+ content: str,
207
+ patterns: list[tuple[str, re.Pattern[str], str]],
208
+ path: Path,
209
+ findings: list[Finding],
210
+ category: str,
211
+ dev: bool = False,
212
+ ) -> None:
213
+ """Match patterns against text content; one finding per (file, pattern).
214
+
215
+ When *dev* is True (the file lives in a development / test path) the
216
+ finding's severity is down-weighted and tagged so benign dev tooling does
217
+ not distort the skill's security score.
218
+ """
219
+ seen = set()
220
+ for severity, regex, message in patterns:
221
+ for i, line in enumerate(content.splitlines(), 1):
222
+ if regex.search(line):
223
+ key = (path.name, regex.pattern)
224
+ if key in seen:
225
+ break
226
+ seen.add(key)
227
+ finding: Finding = {
228
+ "severity": severity,
229
+ "category": category,
230
+ "file": str(path),
231
+ "line": i,
232
+ "pattern": regex.pattern,
233
+ "message": message,
234
+ }
235
+ if dev:
236
+ finding["severity"] = _DEV_REDUCE.get(severity, severity)
237
+ finding["message"] = f"{message} (dev/test path - verify)"
238
+ finding["dev_context"] = True
239
+ findings.append(finding)
240
+ break
241
+
242
+
243
+ def _grade(score: int) -> tuple[str, str]:
244
+ if score >= 90:
245
+ return "A", "safe"
246
+ if score >= 80:
247
+ return "B", "safe"
248
+ if score >= 70:
249
+ return "C", "caution"
250
+ if score >= 60:
251
+ return "D", "risky"
252
+ return "F", "dangerous"
253
+
254
+
255
+ def _score(findings: list[Finding]) -> int:
256
+ """100 minus weighted severities.
257
+
258
+ Serious findings (critical/high/medium) are capped at ``_CATEGORY_CAP``
259
+ per category; minor (low) findings are capped at the much smaller
260
+ ``_MINOR_CAP`` per category. This keeps the score driven by genuine
261
+ high-impact risks while benign low-severity noise can no longer sink a
262
+ skill's rating.
263
+ """
264
+ serious: dict[str, int] = {}
265
+ minor: dict[str, int] = {}
266
+ for f in findings:
267
+ w = SEVERITY_WEIGHTS.get(f["severity"], 0)
268
+ if w == 0:
269
+ continue
270
+ bucket = serious if f["severity"] in ("critical", "high", "medium") else minor
271
+ bucket[f["category"]] = bucket.get(f["category"], 0) + w
272
+ total = sum(min(v, _CATEGORY_CAP) for v in serious.values())
273
+ total += sum(min(v, _MINOR_CAP) for v in minor.values())
274
+ return max(0, 100 - total)
275
+
276
+
277
+ def analyze_skill_dir(skill_dir: Path) -> SkillReport:
278
+ """Run the full static audit on one skill directory.
279
+
280
+ Returns a :class:`SkillReport` (TypedDict) with:
281
+ skill, path, files, total_bytes, score, grade, verdict,
282
+ summary {critical/high/medium/low/info: count}, findings [ ... ]
283
+ """
284
+ skill_dir = Path(skill_dir)
285
+ findings: list[Finding] = []
286
+
287
+ # P0-2: how to treat development / test paths. downweight (default) keeps
288
+ # them scanned but lowers severity; skip ignores them; off restores the
289
+ # legacy behaviour of scoring every file at full severity.
290
+ dev_mode = os.environ.get("ASKILL_AUDIT_DEV_MODE", "downweight").lower()
291
+
292
+ skill_md = skill_dir / "SKILL.md"
293
+ files = []
294
+ if skill_dir.exists():
295
+ for p in skill_dir.rglob("*"):
296
+ if not p.is_file():
297
+ continue
298
+ if any(part in SKIP_DIRS for part in p.parts):
299
+ continue
300
+ if p.suffix.lower() in SKIP_FILE_SUFFIXES:
301
+ continue
302
+ if p.name in SKIP_FILE_NAMES:
303
+ continue
304
+ files.append(p)
305
+ total_bytes = sum(p.stat().st_size for p in files)
306
+
307
+ # --- file integrity -------------------------------------------------
308
+ if not skill_dir.exists():
309
+ findings.append({
310
+ "severity": "critical", "category": "file-integrity",
311
+ "file": str(skill_dir), "line": None, "pattern": "",
312
+ "message": "skill directory does not exist",
313
+ })
314
+ elif not skill_md.exists():
315
+ findings.append({
316
+ "severity": "critical", "category": "file-integrity",
317
+ "file": str(skill_dir), "line": None, "pattern": "",
318
+ "message": "SKILL.md is missing",
319
+ })
320
+ else:
321
+ raw = _read_bytes(skill_md)
322
+ if len(raw) < 20:
323
+ findings.append({
324
+ "severity": "high", "category": "file-integrity",
325
+ "file": str(skill_md), "line": None, "pattern": "",
326
+ "message": "SKILL.md is suspiciously small (< 20 bytes)",
327
+ })
328
+
329
+ if len(files) > MAX_FILES:
330
+ findings.append({
331
+ "severity": "medium", "category": "file-integrity",
332
+ "file": str(skill_dir), "line": None, "pattern": "",
333
+ "message": f"unusually many files ({len(files)} > {MAX_FILES})",
334
+ })
335
+ if total_bytes > MAX_TOTAL_BYTES:
336
+ findings.append({
337
+ "severity": "medium", "category": "file-integrity",
338
+ "file": str(skill_dir), "line": None, "pattern": "",
339
+ "message": f"total size {total_bytes // 1024 // 1024}MB exceeds {MAX_TOTAL_BYTES // 1024 // 1024}MB",
340
+ })
341
+
342
+ # --- per-file scans --------------------------------------------------
343
+ for f in files:
344
+ rel = f.relative_to(skill_dir)
345
+ dev = _is_dev_context(rel)
346
+ if dev and dev_mode == "skip":
347
+ continue # dev/test files ignored entirely (opt-in via env)
348
+ if f.is_symlink():
349
+ findings.append({
350
+ "severity": "medium", "category": "file-integrity",
351
+ "file": str(f), "line": None, "pattern": "",
352
+ "message": "symlink inside skill directory",
353
+ })
354
+ continue
355
+
356
+ chunk = _read_bytes(f)
357
+ if _is_binary(chunk):
358
+ if f.suffix.lower() in BINARY_EXEC_EXTS:
359
+ findings.append({
360
+ "severity": "high", "category": "binary-file",
361
+ "file": str(f), "line": None, "pattern": f.suffix,
362
+ "message": f"executable binary file ({f.suffix})",
363
+ })
364
+ elif f.suffix.lower() not in BINARY_DATA_EXTS:
365
+ findings.append({
366
+ "severity": "high", "category": "binary-file",
367
+ "file": str(f), "line": None, "pattern": f.suffix or "(none)",
368
+ "message": "unexpected binary data (not an image/font/archive)",
369
+ })
370
+ else:
371
+ findings.append({
372
+ "severity": "low", "category": "binary-file",
373
+ "file": str(f), "line": None, "pattern": f.suffix,
374
+ "message": "binary data file bundled with skill",
375
+ })
376
+ continue
377
+
378
+ try:
379
+ content = f.read_text(encoding="utf-8", errors="replace")
380
+ except OSError:
381
+ continue
382
+
383
+ if f.suffix.lower() in MARKDOWN_EXTS:
384
+ _scan_text(content, PROMPT_PATTERNS, rel, findings, "prompt-injection",
385
+ dev=(dev and dev_mode == "downweight"))
386
+ elif f.suffix.lower() in SCRIPT_EXTS:
387
+ _scan_text(content, CODE_PATTERNS, rel, findings, "dangerous-code",
388
+ dev=(dev and dev_mode == "downweight"))
389
+
390
+ if f.stat().st_size > MAX_FILE_BYTES:
391
+ findings.append({
392
+ "severity": "high", "category": "file-integrity",
393
+ "file": str(f), "line": None, "pattern": "",
394
+ "message": f"file too large ({f.stat().st_size // 1024 // 1024}MB)",
395
+ })
396
+
397
+ # --- score -----------------------------------------------------------
398
+ summary = {"critical": 0, "high": 0, "medium": 0, "low": 0, "info": 0}
399
+ # Renamed from ``f`` -> ``finding`` so mypy doesn't reuse the outer
400
+ # loop's ``f: Path`` type from the per-file scan above.
401
+ for finding in findings:
402
+ summary[finding["severity"]] = summary.get(finding["severity"], 0) + 1
403
+
404
+ score = _score(findings)
405
+ grade, verdict = _grade(score)
406
+
407
+ return {
408
+ "skill": skill_dir.name,
409
+ "path": str(skill_dir),
410
+ "files": len(files),
411
+ "total_bytes": total_bytes,
412
+ "score": score,
413
+ "grade": grade,
414
+ "verdict": verdict,
415
+ "summary": summary,
416
+ "findings": findings,
417
+ }
418
+
419
+
420
+ def analyze_all(central_dir: Path, max_workers: int = 8) -> list[SkillReport]:
421
+ """Audit every skill directory under the central repository.
422
+
423
+ Each ``analyze_skill_dir`` call is I/O bound (reads SKILL.md and any
424
+ bundled scripts), so we run them concurrently via a small thread
425
+ pool. ``pool.map`` preserves the sorted input order in the output,
426
+ matching the previous serial behaviour so existing callers (and the
427
+ tests that check report order) keep working.
428
+ """
429
+ central_dir = Path(central_dir)
430
+ if not central_dir.exists():
431
+ return []
432
+ skill_dirs = sorted(
433
+ d for d in central_dir.iterdir()
434
+ if d.is_dir() and not d.is_symlink()
435
+ )
436
+ if not skill_dirs:
437
+ return []
438
+ with ThreadPoolExecutor(
439
+ max_workers=min(len(skill_dirs), max_workers),
440
+ ) as pool:
441
+ return list(pool.map(analyze_skill_dir, skill_dirs))
@@ -0,0 +1,238 @@
1
+ """Automatic adoption of product-side skills into the central repo (v0.27).
2
+
3
+ See ``docs/auto-adopt-design.md`` for the fifteen settled design decisions.
4
+ This module is only called from ``askill watch --auto-adopt``; without the flag
5
+ there is no behavioural change at all.
6
+
7
+ Hard rules encoded here:
8
+
9
+ * only a **real directory** with ``SKILL.md`` and **no central namesake** is
10
+ adopted - links, conflicts and drift stay in the human ``adopt`` path;
11
+ * the source product keeps its real directory forever, including after undo
12
+ (``sync.remove_skill`` deliberately deletes product-side entries and is
13
+ therefore *not* used here);
14
+ * provenance goes to ``.askill-adoptions.json``, never to
15
+ ``.askill-sources.json`` (that would make ``update`` assume a git remote).
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import hashlib
21
+ import json
22
+ import shutil
23
+ from datetime import datetime, timezone
24
+ from pathlib import Path
25
+ from typing import Any
26
+
27
+ from ..config.products import CENTRAL_DIR, PRODUCTS, get_all_product_dirs
28
+ from ..utils.filesystem import is_symlink_or_junction, remove_path
29
+ from .inventory import list_skills
30
+
31
+ __all__ = [
32
+ "AUDIT_FILE",
33
+ "TIME_BUDGET_S",
34
+ "adopt_one",
35
+ "load_audit",
36
+ "save_audit",
37
+ "scan_candidates",
38
+ "undo",
39
+ "undo_plan",
40
+ ]
41
+
42
+ AUDIT_FILE = ".askill-adoptions.json"
43
+ AUDIT_VERSION = 1
44
+ TIME_BUDGET_S = 2.0 # per watch-loop iteration, not per candidate
45
+
46
+
47
+ def _base(central: Path | None) -> Path:
48
+ return Path(central) if central is not None else CENTRAL_DIR
49
+
50
+
51
+ def load_audit(central: Path | None = None) -> dict[str, Any]:
52
+ """Read the adoption ledger; a corrupt file degrades to an empty one."""
53
+ try:
54
+ data = json.loads((_base(central) / AUDIT_FILE).read_text(encoding="utf-8"))
55
+ if data.get("version") == AUDIT_VERSION and isinstance(data.get("entries"), dict):
56
+ return data
57
+ except (OSError, ValueError):
58
+ pass
59
+ return {"version": AUDIT_VERSION, "entries": {}}
60
+
61
+
62
+ def save_audit(data: dict[str, Any], central: Path | None = None) -> None:
63
+ """Atomically write the ledger so a crash cannot leave a half record."""
64
+ base = _base(central)
65
+ base.mkdir(parents=True, exist_ok=True)
66
+ target = base / AUDIT_FILE
67
+ tmp = base / (AUDIT_FILE + ".tmp")
68
+ tmp.write_text(
69
+ json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8",
70
+ )
71
+ tmp.replace(target)
72
+
73
+
74
+ def _content_hash(skill_dir: Path) -> str:
75
+ try:
76
+ return hashlib.sha256((skill_dir / "SKILL.md").read_bytes()).hexdigest()[:16]
77
+ except OSError:
78
+ return ""
79
+
80
+
81
+ def scan_candidates(
82
+ central: Path | None = None,
83
+ products: Any = None,
84
+ ) -> dict[str, list[dict[str, Any]]]:
85
+ """Find auto-adoptable skills and explain every rejected directory.
86
+
87
+ Returns ``{"candidates": [...], "skipped": [...]}``. ``products`` defaults
88
+ to the module-level ``PRODUCTS`` (the established patch seam).
89
+ """
90
+ base = _base(central)
91
+ sources = products if products is not None else PRODUCTS
92
+ central_names = {d.name for d in list_skills(base)} if base.exists() else set()
93
+
94
+ candidates: dict[str, dict[str, Any]] = {}
95
+ skipped: list[dict[str, Any]] = []
96
+ for product in sources:
97
+ if product.get("sync_method") != "symlink":
98
+ continue
99
+ short = product.get("short", "?")
100
+ for directory in get_all_product_dirs(product):
101
+ if not directory or not Path(directory).exists():
102
+ continue
103
+ try:
104
+ entries = sorted(Path(directory).iterdir())
105
+ except OSError:
106
+ skipped.append({
107
+ "name": None, "product": short,
108
+ "reason": "unreadable", "path": str(directory),
109
+ })
110
+ continue
111
+ for entry in entries:
112
+ if not entry.is_dir() or not (entry / "SKILL.md").exists():
113
+ continue
114
+ if is_symlink_or_junction(entry):
115
+ reason = "link"
116
+ elif entry.name in central_names:
117
+ reason = "already-central"
118
+ elif entry.name in candidates:
119
+ reason = "duplicate"
120
+ else:
121
+ reason = ""
122
+ if reason:
123
+ skipped.append({
124
+ "name": entry.name, "product": short,
125
+ "reason": reason, "path": str(entry),
126
+ })
127
+ continue
128
+ candidates[entry.name] = {
129
+ "name": entry.name,
130
+ "product_short": short,
131
+ "source_path": str(entry),
132
+ "content_hash": _content_hash(entry),
133
+ }
134
+ return {"candidates": list(candidates.values()), "skipped": skipped}
135
+
136
+
137
+ def adopt_one(
138
+ candidate: dict[str, Any],
139
+ central: Path | None = None,
140
+ *,
141
+ audit: bool = True,
142
+ verbose: bool = True,
143
+ ) -> dict[str, Any]:
144
+ """Copy one candidate into the central repo and record its provenance."""
145
+ name = candidate["name"]
146
+ base = _base(central)
147
+ dest = base / name
148
+ if dest.exists():
149
+ return {"name": name, "status": "skipped", "reason": "already-central"}
150
+
151
+ base.mkdir(parents=True, exist_ok=True)
152
+ try:
153
+ shutil.copytree(Path(candidate["source_path"]), dest)
154
+ except OSError as exc:
155
+ return {"name": name, "status": "failed", "reason": str(exc)}
156
+
157
+ if audit:
158
+ data = load_audit(base)
159
+ data["entries"][name] = {
160
+ "product_short": candidate.get("product_short", "?"),
161
+ "source_path": candidate.get("source_path", ""),
162
+ "content_hash": candidate.get("content_hash", ""),
163
+ "adopted_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
164
+ }
165
+ save_audit(data, base)
166
+ if verbose:
167
+ print(f" [auto-adopt] {name} <- {candidate.get('product_short', '?')}")
168
+ return {"name": name, "status": "adopted", "central_path": str(dest)}
169
+
170
+
171
+ def undo_plan(
172
+ skill_name: str,
173
+ central: Path | None = None,
174
+ products: Any = None,
175
+ ) -> dict[str, Any] | None:
176
+ """Describe an undo without touching the filesystem."""
177
+ base = _base(central)
178
+ entry = load_audit(base)["entries"].get(skill_name)
179
+ if entry is None:
180
+ return None
181
+ sources = products if products is not None else PRODUCTS
182
+ links: list[str] = []
183
+ for product in sources:
184
+ if product.get("sync_method") in ("native", "pack"):
185
+ continue
186
+ for directory in get_all_product_dirs(product):
187
+ if not directory:
188
+ continue
189
+ candidate = Path(directory) / skill_name
190
+ # Only links are cleaned. A real directory - including the source
191
+ # product's own copy - is always left untouched.
192
+ if candidate.exists() and is_symlink_or_junction(candidate):
193
+ links.append(str(candidate))
194
+ return {
195
+ "name": skill_name,
196
+ "central_path": str(base / skill_name),
197
+ "source_path": entry.get("source_path", ""),
198
+ "product_short": entry.get("product_short", "?"),
199
+ "product_links": links,
200
+ }
201
+
202
+
203
+ def undo(
204
+ skill_name: str,
205
+ central: Path | None = None,
206
+ *,
207
+ dry_run: bool = False,
208
+ verbose: bool = True,
209
+ ) -> dict[str, Any]:
210
+ """Undo an auto-adoption; keep every real directory (Q12)."""
211
+ plan = undo_plan(skill_name, central)
212
+ if plan is None:
213
+ return {"ok": False, "error": f"not an auto-adopted skill: {skill_name}"}
214
+ if dry_run:
215
+ return {"ok": True, "dry_run": True, "plan": plan, "removed": []}
216
+
217
+ removed: list[str] = []
218
+ for link in plan["product_links"]:
219
+ try:
220
+ remove_path(Path(link))
221
+ removed.append(link)
222
+ except OSError as exc:
223
+ if verbose:
224
+ print(f" [undo] could not remove {link}: {exc}")
225
+ central_dir = Path(plan["central_path"])
226
+ if central_dir.exists():
227
+ try:
228
+ shutil.rmtree(central_dir)
229
+ removed.append(str(central_dir))
230
+ except OSError as exc:
231
+ return {"ok": False, "error": str(exc), "removed": removed}
232
+
233
+ data = load_audit(central)
234
+ data["entries"].pop(skill_name, None)
235
+ save_audit(data, central)
236
+ if verbose:
237
+ print(f" [undo] {skill_name} removed from central; source kept at {plan['source_path']}")
238
+ return {"ok": True, "dry_run": False, "removed": removed, "source_kept": True}