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,1344 @@
1
+ """CLI entry point for agent-skill-manager."""
2
+
3
+ import argparse
4
+ import json
5
+ import platform
6
+ import shutil
7
+ import sys
8
+ from collections.abc import Callable
9
+ from pathlib import Path
10
+
11
+ from ..config.products import (
12
+ CENTRAL_DIR,
13
+ LOCALAPPDATA,
14
+ PRODUCTS,
15
+ get_all_product_dirs,
16
+ get_product_path,
17
+ )
18
+ from ..services.audit import analyze_skill_dir
19
+ from ..services.ci_format import (
20
+ audit_annotations,
21
+ grades_failed,
22
+ parse_fail_on,
23
+ verify_annotations,
24
+ )
25
+ from ..services.doctor import doctor_report
26
+ from ..services.get import get_skill
27
+ from ..services.manifest import bundle_manifest, install_manifest
28
+ from ..services.overlap import overlap_rows, render_overlap
29
+ from ..services.paths_export import build_path_records
30
+ from ..services.publish import publish_skill
31
+ from ..services.remediation import build_fix_plan, render_plan
32
+ from ..services.scaffold import create_skill
33
+ from ..services.sync import (
34
+ FOOTER,
35
+ adopt_from_platform,
36
+ audit_all,
37
+ audit_skill,
38
+ gc_dead_links,
39
+ get_status,
40
+ install_skill,
41
+ list_skills,
42
+ pack_skill,
43
+ print_onboarding,
44
+ remove_skill,
45
+ residency_report,
46
+ sync_skill,
47
+ )
48
+ from ..utils.filesystem import read_skill_metadata
49
+
50
+
51
+ def _print_product_paths():
52
+ """Emit the full portable cross-platform declaration as JSON.
53
+
54
+ Kept as a separate entry point so ``_print_products`` retains the
55
+ long-standing signature that shell completion and tests patch against.
56
+ """
57
+ records = build_path_records(
58
+ PRODUCTS, home=Path.home(), localappdata=LOCALAPPDATA,
59
+ )
60
+ print(json.dumps(records, ensure_ascii=False, indent=2))
61
+ return 0
62
+
63
+
64
+ def _print_products(*, quiet=False, json_mode=False):
65
+ """Print all supported products and their paths."""
66
+ if json_mode:
67
+ # Flatten per-product into JSON objects with the platform-relevant
68
+ # resolved path / extra dirs and a one-letter sync_method. Stable
69
+ # enough for downstream tools to consume.
70
+ out = []
71
+ for p in PRODUCTS:
72
+ primary = get_product_path(p)
73
+ out.append({
74
+ "name": p["name"],
75
+ "short": p["short"],
76
+ "sync_method": p["sync_method"],
77
+ "primary_path": str(primary) if primary else None,
78
+ "extra_paths": [
79
+ str(d) for d in get_all_product_dirs(p)[1:]
80
+ if d is not None
81
+ ],
82
+ "note": p.get("note", ""),
83
+ })
84
+ print(json.dumps(out, ensure_ascii=False, indent=2))
85
+ return
86
+
87
+ print(f"\n{'='*60}")
88
+ print(f"Supported Products ({len(PRODUCTS)})")
89
+ print(f"{'='*60}")
90
+ if not quiet:
91
+ print(f"Platform: {platform.system()}")
92
+ print(f"Central repo: {CENTRAL_DIR}")
93
+ print(f"{'='*60}\n")
94
+
95
+ for p in PRODUCTS:
96
+ print(f" [{p['short']}] {p['name']}")
97
+ if p["sync_method"] == "native":
98
+ path = get_product_path(p)
99
+ print(f" Path: {path} (native, no sync needed)")
100
+ elif p["sync_method"] == "pack":
101
+ print(" Path: App-managed (use 'pack' command)")
102
+ else:
103
+ primary = get_product_path(p)
104
+ if primary:
105
+ exists = "[ok]" if primary.exists() else "[--]"
106
+ print(f" Path: {primary} {exists}")
107
+ else:
108
+ print(" Path: N/A on this platform (see note)")
109
+ extra_dirs = get_all_product_dirs(p)
110
+ for d in extra_dirs[1:]:
111
+ exists = "[ok]" if d.exists() else "[--]"
112
+ print(f" Alt: {d} {exists}")
113
+ if p.get("note"):
114
+ print(f" Note: {p['note']}")
115
+ print()
116
+
117
+
118
+ def _print_list(*, quiet=False, json_mode=False):
119
+ """List all skills in the central repository."""
120
+ skills = list_skills()
121
+ if not skills:
122
+ if json_mode:
123
+ print(json.dumps([], ensure_ascii=False))
124
+ elif not quiet:
125
+ if not CENTRAL_DIR.exists():
126
+ print(f"Central repository not found: {CENTRAL_DIR}")
127
+ else:
128
+ print(f"No skills found in {CENTRAL_DIR}")
129
+ print_onboarding()
130
+ return
131
+
132
+ if json_mode:
133
+ from ..services.spec import parse_frontmatter
134
+ entries = []
135
+ for s in skills:
136
+ meta = read_skill_metadata(s)
137
+ report = analyze_skill_dir(s)
138
+ fields, _ = parse_frontmatter(
139
+ (s / "SKILL.md").read_text(encoding="utf-8", errors="replace")
140
+ )
141
+ entries.append({
142
+ "skill": s.name,
143
+ "description": meta.get("description", ""),
144
+ # publish-relevant frontmatter (None when absent) - lets
145
+ # scripts spot skills that would fail the publish gate
146
+ "version": fields.get("version"),
147
+ "description_zh": fields.get("description_zh"),
148
+ "audit_score": report["score"],
149
+ "audit_grade": report["grade"],
150
+ "audit_verdict": report["verdict"],
151
+ })
152
+ print(json.dumps(entries, ensure_ascii=False, indent=2))
153
+ return
154
+
155
+ print(f"\nSkills in central repository ({CENTRAL_DIR}):")
156
+ print(f"{'-'*50}")
157
+ verdict_icon = {"safe": "OK", "caution": "CAUTION", "risky": "RISKY", "dangerous": "DANGEROUS"}
158
+ for s in skills:
159
+ meta = read_skill_metadata(s)
160
+ report = analyze_skill_dir(s)
161
+ print(f" {s.name} [score {report['score']}/100 grade {report['grade']} {verdict_icon[report['verdict']]}]")
162
+ if meta.get("description"):
163
+ desc = meta["description"][:80]
164
+ print(f" -> {desc}...")
165
+ print()
166
+
167
+
168
+ def _print_status_grouped(sn, by_skill, product_shorts, term_w, central):
169
+ """Render one skill as a grouped block (v0.25.1, replaces the 6-char
170
+ squeezed table when 15 products can not fit the terminal).
171
+
172
+ Products are grouped by status with full (untruncated) short names,
173
+ wrapped to the terminal width. ``ok`` hides the per-product method
174
+ (junction/link/native) - that detail lives in ``--json`` and in the
175
+ wide-table mode; the value here is who has the skill and who does not.
176
+ """
177
+ import textwrap
178
+
179
+ verdict_icon = {"safe": "OK", "caution": "CAUTION", "risky": "RISKY", "dangerous": "DANGEROUS"}
180
+ print(f"\n{sn}")
181
+ groups: dict[str, list[str]] = {}
182
+ for ps in product_shorts:
183
+ if ps in by_skill[sn]:
184
+ status, _method = by_skill[sn][ps]
185
+ else:
186
+ status = "missing"
187
+ groups.setdefault(status, []).append(ps)
188
+ order = ["ok", "manual", "n/a", "conflict", "missing"]
189
+ for status in order + [s for s in groups if s not in order]:
190
+ names = groups.get(status)
191
+ if not names:
192
+ continue
193
+ label = f" {status} ({len(names)})".ljust(14)
194
+ print(textwrap.fill(
195
+ ", ".join(names),
196
+ width=max(term_w, 60),
197
+ initial_indent=label,
198
+ subsequent_indent=" " * 14,
199
+ ))
200
+ skill_dir = Path(central) / sn
201
+ if skill_dir.exists():
202
+ report = analyze_skill_dir(skill_dir)
203
+ print(f" {'score'.ljust(14)}{report['score']}/{report['grade']} {verdict_icon[report['verdict']]}")
204
+
205
+
206
+ def _print_status(skill_name=None, *, quiet=False, json_mode=False):
207
+ """Print installation status of skills across all products.
208
+
209
+ Column widths adapt to fit the terminal:
210
+ - skill name column: longest name in current results (cap 30, floor 10)
211
+ - product cell: 12 chars
212
+ - score column: dropped first when the table gets too wide; the audit
213
+ verdict is the least actionable info once packed in
214
+ - when even the score-less table can not fit (15 products on an 80-col
215
+ terminal), the whole matrix switches to a grouped vertical layout:
216
+ one block per skill, products listed by status with full short names
217
+ (v0.25.1 - replaces the old 6-char truncated columns that squeezed
218
+ 'ok junction' into 'ok li…').
219
+
220
+ Args:
221
+ quiet: suppress non-essential output (banner, score column for
222
+ empty central, etc.). Errors always print.
223
+ json_mode: emit one JSON object (list of per-product StatusEntry
224
+ records) instead of the formatted table.
225
+ """
226
+ results = get_status(skill_name)
227
+ if not results:
228
+ if json_mode:
229
+ print(json.dumps(results, ensure_ascii=False, indent=2))
230
+ elif skill_name:
231
+ print(f"Skill not found: {skill_name}")
232
+ else:
233
+ if not quiet:
234
+ print("No skills found in central repository.")
235
+ print_onboarding()
236
+ return
237
+
238
+ # Group results by skill (skill -> {product_short: (status, method)})
239
+ verdict_icon = {"safe": "OK", "caution": "CAUTION", "risky": "RISKY", "dangerous": "DANGEROUS"}
240
+ by_skill: dict[str, dict[str, tuple]] = {}
241
+ order: list[str] = []
242
+ for r in results:
243
+ sn = r["skill_name"]
244
+ if sn not in by_skill:
245
+ by_skill[sn] = {}
246
+ order.append(sn)
247
+ by_skill[sn][r["product_short"]] = (r["status"], r["method"])
248
+
249
+ product_shorts = [p["short"] for p in PRODUCTS]
250
+ n_prod = len(product_shorts)
251
+
252
+ # Column body widths (each column is rendered as " " + body, padded to body_w).
253
+ skill_w = max((len(s) for s in order), default=5)
254
+ skill_w = min(max(skill_w, 10), 30)
255
+ cell_w = 12 # fits "ok junction" (11) + slack
256
+ score_w = 13 # fits "100/A DANGEROUS"
257
+
258
+ # Adapt to terminal width. Falls back to 120 cols when not a TTY
259
+ # (piped to grep/cat/less) so the table stays usable in scripts.
260
+ term_w = shutil.get_terminal_size((120, 20)).columns
261
+ total = skill_w + (cell_w + 1) * n_prod + (score_w + 1)
262
+ show_score = True
263
+ if total > term_w:
264
+ show_score = False
265
+ total -= score_w + 1
266
+ # v0.25.1: when even the score-less table can not fit, switch to the
267
+ # grouped vertical layout instead of truncating every product cell to
268
+ # 6 chars ('ok junction' became unreadable 'ok li…').
269
+ grouped = total > term_w and not json_mode
270
+
271
+ def _cell(label: str, n: int) -> str:
272
+ """Format one cell as ' ' + label left-justified to n body chars
273
+ (truncated with an ellipsis if the label is wider than n)."""
274
+ if len(label) > n:
275
+ label = label[: n - 1] + "\u2026"
276
+ return f" {label:<{n}}"
277
+
278
+ header = f"{'Skill':<{skill_w}}"
279
+ for ps in product_shorts:
280
+ header += _cell(ps, cell_w)
281
+ if show_score:
282
+ header += _cell("score", score_w)
283
+ # quiet strips decoration (banner/header/footer) but keeps the data rows;
284
+ # an orphan header with zero rows is worse than either.
285
+ if not json_mode and not quiet and not grouped:
286
+ print(f"\n{header}")
287
+ print("-" * len(header))
288
+
289
+ for sn in order:
290
+ if grouped:
291
+ _print_status_grouped(sn, by_skill, product_shorts, term_w, CENTRAL_DIR)
292
+ continue
293
+ row = f"{sn[:skill_w]:<{skill_w}}"
294
+ for ps in product_shorts:
295
+ if ps in by_skill[sn]:
296
+ status, method = by_skill[sn][ps]
297
+ if status == "ok":
298
+ cell = f"ok {method}"
299
+ elif status == "missing":
300
+ cell = "--"
301
+ elif status == "manual":
302
+ cell = "manual"
303
+ elif status == "n/a":
304
+ cell = "n/a"
305
+ else:
306
+ cell = status
307
+ else:
308
+ cell = "--"
309
+ row += _cell(cell, cell_w)
310
+ if show_score and not json_mode:
311
+ skill_dir = CENTRAL_DIR / sn
312
+ if skill_dir.exists():
313
+ report = analyze_skill_dir(skill_dir)
314
+ row += _cell(f"{report['score']}/{report['grade']} {verdict_icon[report['verdict']]}", score_w)
315
+ else:
316
+ row += _cell("n/a", score_w)
317
+ if not json_mode:
318
+ print(row)
319
+ if not json_mode and not quiet:
320
+ # A2 (health check 2026-10-31): explain degraded cells once, below
321
+ # the table, instead of widening every cell.
322
+ reasons = sorted({r["reason"] for r in results if r.get("reason")})
323
+ if reasons:
324
+ print(f"\n note: {'; '.join(reasons)}")
325
+ if json_mode:
326
+ # Augment the StatusEntry rows with a per-skill audit score / verdict
327
+ # so consumers don't have to re-read the central repo to render it.
328
+ enriched: list[dict] = []
329
+ for r in results:
330
+ entry = dict(r)
331
+ skill_dir = CENTRAL_DIR / str(entry["skill_name"])
332
+ if skill_dir.exists():
333
+ rep = analyze_skill_dir(skill_dir)
334
+ entry["audit_score"] = rep["score"]
335
+ entry["audit_grade"] = rep["grade"]
336
+ entry["audit_verdict"] = rep["verdict"]
337
+ enriched.append(entry)
338
+ print(json.dumps(enriched, ensure_ascii=False, indent=2))
339
+ elif not quiet:
340
+ print(f" -- {FOOTER}")
341
+ print()
342
+
343
+
344
+ def _print_sync(skill_name=None, *, force=False, quiet=False, only=None, gc=False):
345
+ if gc:
346
+ gc_dead_links(verbose=not quiet)
347
+ return 0
348
+ """Sync skills and print results.
349
+
350
+ ``quiet`` flips ``sync_skill(verbose=...)`` to False. Conflict +
351
+ SECURITY WARNING prints stay untouched because they go through
352
+ ``sync_skill`` directly.
353
+
354
+ Returns 1 when a named skill was not found (exit-code contract),
355
+ else 0 - per-product conflicts/failures are reported data, not a
356
+ command failure.
357
+ """
358
+ results = sync_skill(skill_name, verbose=not quiet, force=force, only=only)
359
+ return 1 if (skill_name and not results) else 0
360
+
361
+
362
+ def _print_install(source, sync=False, audit=False, no_audit=False, *, quiet=False, only=None):
363
+ """Install a skill and print results. Returns 1 on failure."""
364
+ ok = install_skill(source, sync=sync, audit=audit, no_audit=no_audit, verbose=not quiet,
365
+ only=only)
366
+ return 0 if ok else 1
367
+
368
+
369
+ def _print_remove(skill_name, *, quiet=False):
370
+ """Remove a skill and print results."""
371
+ remove_skill(skill_name, verbose=not quiet)
372
+
373
+
374
+ def _print_pack(skill_name=None, *, quiet=False):
375
+ """Pack a skill and print results. Returns 1 on failure."""
376
+ return 0 if pack_skill(skill_name, verbose=not quiet) else 1
377
+
378
+
379
+ def _print_adopt(
380
+ platform_short, skill_name=None, *, quiet=False,
381
+ undo=None, json_mode=False,
382
+ ):
383
+ """Adopt from a platform, or undo one auto-adoption (Q12)."""
384
+ if undo:
385
+ from ..services.auto_adopt import undo as undo_adoption
386
+ from ..services.auto_adopt import undo_plan as build_undo_plan
387
+
388
+ if json_mode:
389
+ # dry-run: print the plan, change nothing (Q12)
390
+ result = undo_adoption(undo, dry_run=True, verbose=False)
391
+ print(json.dumps(result, ensure_ascii=False, indent=2))
392
+ return 0 if result["ok"] else 1
393
+
394
+ # Plan first, delete only after the user confirmed (Q12).
395
+ plan = build_undo_plan(undo)
396
+ if plan is None:
397
+ print(f"Error: not an auto-adopted skill: {undo}")
398
+ return 1
399
+ print(f"Undo auto-adoption of '{undo}':")
400
+ print(f" central: {plan.get('central_path', '(none)')}")
401
+ print(f" links: {', '.join(plan.get('product_links', [])) or '(none)'}")
402
+ print(f" source: {plan.get('source_path', '(unknown)')} (kept)")
403
+ try:
404
+ answer = input("Confirm undo? [y/N] ")
405
+ except EOFError:
406
+ answer = ""
407
+ if answer.strip().lower() not in {"y", "yes"}:
408
+ print("Cancelled - nothing was changed.")
409
+ return 1
410
+ result = undo_adoption(undo, dry_run=False, verbose=not quiet)
411
+ if not result["ok"]:
412
+ print(f"Error: {result.get('error', 'unknown error')}")
413
+ return 1
414
+ print(f" removed {len(result['removed'])} location(s); source directory kept.")
415
+ return 0
416
+ from ..config.products import get_product_by_short
417
+ if platform_short is None:
418
+ print("Usage: askill adopt <platform|all> [skill] | askill adopt --undo <skill>")
419
+ return 2
420
+ if platform_short != "all" and get_product_by_short(platform_short) is None:
421
+ print(f"Unknown platform: {platform_short}")
422
+ print(f"Available: {', '.join(p['short'] for p in PRODUCTS)} (or 'all')")
423
+ return 1
424
+ adopt_from_platform(platform_short, skill_name, verbose=not quiet)
425
+ return 0
426
+
427
+
428
+ def _print_audit(
429
+ skill_name=None, *, quiet=False, json_mode=False,
430
+ fail_on=None, gh_format=False,
431
+ ):
432
+ """Audit one or all skills and print reports.
433
+
434
+ CI mode (``--format github`` / ``--fail-on``) gathers the machine-readable
435
+ reports first so a grade gate can drive the exit code; the default human
436
+ path is left byte-for-byte unchanged.
437
+ """
438
+ fail_on = fail_on or set()
439
+ if json_mode or fail_on or gh_format:
440
+ reports = (
441
+ [audit_skill(skill_name, verbose=False)]
442
+ if skill_name
443
+ else audit_all(verbose=False)
444
+ )
445
+ reports = [r for r in reports if r is not None]
446
+ failed = grades_failed(reports, fail_on)
447
+ if json_mode:
448
+ print(json.dumps(reports, ensure_ascii=False, indent=2))
449
+ return 1 if failed else 0
450
+ if gh_format:
451
+ for line in audit_annotations(reports, fail_on=fail_on):
452
+ print(line)
453
+ elif not quiet:
454
+ summary = ", ".join(f"{r['skill']}={r['grade']}" for r in reports) or "(none)"
455
+ print(f"askill audit - {len(reports)} skill(s): {summary}")
456
+ if failed and not quiet:
457
+ print(" gate failed for: " + ", ".join(failed))
458
+ return 1 if failed else 0
459
+ if skill_name:
460
+ audit_skill(skill_name, verbose=not quiet)
461
+ else:
462
+ audit_all(verbose=not quiet)
463
+
464
+
465
+ def _print_overlap(*, quiet=False, json_mode=False, threshold=0.6):
466
+ """Deterministic description-overlap report (P1-9)."""
467
+ rows = overlap_rows(CENTRAL_DIR, threshold=threshold)
468
+ if json_mode:
469
+ print(json.dumps(rows, ensure_ascii=False, indent=2))
470
+ return 0
471
+ if not quiet:
472
+ print(render_overlap(rows, threshold))
473
+ return 0
474
+
475
+
476
+
477
+ _SUPPORTED_NAMES = ", ".join(p["name"] for p in PRODUCTS)
478
+
479
+ USAGE = f"""\
480
+ Skillshuttle - Cross-platform skill management for domestic AI agent products.
481
+
482
+ Supports {len(PRODUCTS)} products: {_SUPPORTED_NAMES}
483
+
484
+ Usage:
485
+ askill status [skill-name] Show installation status across products
486
+ askill sync [skill-name] Sync skill(s) to all products
487
+ [--force] Overwrite differing real dirs (conflicts)
488
+ askill list List skills in central repository
489
+ askill install [--sync] <source> Install a skill, optionally sync to all
490
+ [--audit] [--no-audit] Sources: local path, GitHub URL, or
491
+ skills.sh shorthand (owner/repo,
492
+ owner/repo@skill, skills.sh URL).
493
+ Spec + security checks run by default
494
+ askill search <query> [--install N] Search skills.sh; N installs that result
495
+ askill new <name> Scaffold a new skill (frontmatter
496
+ [--target short] [--minimal] prefilled from product requirements)
497
+ askill publish <skill> --repo owner/name Publish to a git repo
498
+ [--push] [--root] [--create] (default: dry run, additive subdir)
499
+ askill verify [skill-name] Check skills against the agentskills.io spec
500
+ plus per-product frontmatter requirements
501
+ askill remove <skill-name> Remove a skill from all products
502
+ askill pack <skill-name> Package a skill as .zip for DuMate
503
+ askill adopt <platform|all> [skill] Adopt skills from one platform (or
504
+ every product) into the central repo
505
+ askill audit [skill-name] Security audit of skill(s) in central repo
506
+ askill watch Watch central repo; auto-sync changes
507
+ [--interval N] Poll/fallback seconds (native inotify /
508
+ kqueue / ReadDirectoryChangesW events
509
+ wake syncs instantly when available)
510
+ askill update [skill-name] Check/apply updates for tracked skills
511
+ askill drift [product] Report product-dir skills diverging
512
+ from the central repo (new / differs)
513
+ askill products [--paths] List products / export portable paths as JSON
514
+ askill version Show version
515
+
516
+ Exit codes: 0 success (incl. dry runs / empty results) · 1 operational
517
+ failure (install/verify/publish/... could not do its job) · 2 usage error.
518
+ """
519
+
520
+
521
+ def main(argv=None):
522
+ """CLI entry point.
523
+
524
+ Args: pass an explicit argv for testability (defaults to ``sys.argv[1:]``).
525
+ """
526
+ if argv is None:
527
+ argv = sys.argv[1:]
528
+
529
+ if not argv:
530
+ print(USAGE)
531
+ return
532
+
533
+ parser = _build_parser()
534
+ try:
535
+ args = parser.parse_args(argv)
536
+ except SystemExit as e:
537
+ # ``--help`` exits 0: argparse already wrote the message, stop
538
+ # cleanly. Subparser usage errors raise SystemExit(2) directly
539
+ # (exit_on_error does not propagate into subparsers), and that
540
+ # code is the scripting-facing signal - re-raise it unchanged.
541
+ if e.code not in (None, 0):
542
+ raise
543
+ return
544
+ except argparse.ArgumentError as e:
545
+ # Main-parser level validation failure (bad flag / unknown command).
546
+ # For ``install`` we keep the project's usage block instead of
547
+ # argparse's default error so users get the skills.sh shorthand
548
+ # examples they expect. Usage errors must not exit 0 - scripts
549
+ # pipe askill output and rely on exit codes to detect failure.
550
+ if argv and argv[0] == "install":
551
+ print(_INSTALL_HELP)
552
+ else:
553
+ print(f"Error: {e}")
554
+ sys.exit(2)
555
+
556
+ cmd = args.command
557
+
558
+ # Global ``--version`` wins before anything else - command dispatch, the
559
+ # ``cmd is None`` usage dump, and the first-run welcome (which we don't
560
+ # want to print for a version query). Note the distinct dest
561
+ # (``show_version``) declared at the parser - it must match here, and it
562
+ # must NOT collide with ``new --version``'s ``version`` frontmatter attr.
563
+ if getattr(args, "show_version", False):
564
+ _print_version()
565
+ return
566
+
567
+ if cmd is None:
568
+ print(USAGE)
569
+ return
570
+
571
+ quiet = bool(getattr(args, "quiet", False))
572
+ json_mode = bool(getattr(args, "json_mode", False))
573
+ # normalize onto the namespace so every dispatch entry can read them
574
+ # directly (some subparsers don't declare --json; absence means False)
575
+ args.quiet = quiet
576
+ args.json_mode = json_mode
577
+
578
+ # One-time first-run welcome (never in quiet/json/script modes).
579
+ if cmd != "version":
580
+ from ..services import welcome
581
+ welcome.maybe_print_welcome(quiet=quiet, json_mode=json_mode)
582
+
583
+ handler = _HANDLERS.get(cmd)
584
+ if handler is None:
585
+ print(f"Unknown command: {cmd}")
586
+ print(USAGE)
587
+ rc = 2
588
+ else:
589
+ # `watch` never returns; handlers returning None count as success.
590
+ rc = handler(args) or 0
591
+
592
+ # Exit-code contract: 0 success, 1 operational failure, 2 usage error.
593
+ if rc:
594
+ sys.exit(rc)
595
+
596
+
597
+ def _build_parser() -> argparse.ArgumentParser:
598
+ """Build the argparse subcommand parser.
599
+
600
+ The command definitions live in ``controllers/parsers`` (three command
601
+ families). This wrapper stays here so ``main()`` and introspection keep a
602
+ single stable entry point; all flags and registration order are unchanged.
603
+ """
604
+ from .parsers import build_parser
605
+
606
+ return build_parser(len(PRODUCTS))
607
+
608
+
609
+
610
+ _INSTALL_HELP = """\
611
+ Usage: askill install [--sync] [--audit] [--no-audit] <source>
612
+ Sources: local path, GitHub URL, or skills.sh shorthand:
613
+ owner/repo e.g. anthropics/skills
614
+ owner/repo@skill e.g. anthropics/skills@pdf
615
+ https://skills.sh/owner/repo/skill
616
+ --sync Also sync to all products after install
617
+ --audit Print the full audit report after install
618
+ --no-audit Skip the default spec + security checks
619
+ """
620
+
621
+
622
+ def _cmd_drift(product_short, *, quiet=False, json_mode=False):
623
+ """``askill drift [product]`` body (v0.16.0)."""
624
+ from ..services.drift import find_drift
625
+ report = find_drift(product_short)
626
+ if report["error"]:
627
+ print(f"Error: {report['error']}")
628
+ return 1
629
+ if json_mode:
630
+ print(json.dumps(report, ensure_ascii=False, indent=2))
631
+ return 0
632
+
633
+ drifted = {s: e for s, e in report["products"].items() if e["new"] or e["differs"]}
634
+ print(f"\nDrift scan ({_platform_label()}): {len(report['scanned'])} product(s) scanned\n")
635
+ if not drifted:
636
+ print("No drift - every real skill dir matches the central repo.")
637
+ print()
638
+ return 0
639
+ for short, entry in drifted.items():
640
+ print(f" [{short}]")
641
+ if entry["new"]:
642
+ print(f" new: {', '.join(entry['new'])}")
643
+ if entry["differs"]:
644
+ print(f" differs: {', '.join(entry['differs'])}")
645
+ print()
646
+ print(" new -> askill adopt <product> [skill] pull into central")
647
+ print(" differs -> decide which side wins:")
648
+ print(" askill sync <skill> --force keep central, overwrite product")
649
+ print(" (or copy the product version back into the central repo by hand)")
650
+ print(" auto -> askill adopt --undo <skill> revert an auto-adopted skill")
651
+ print()
652
+ return 0
653
+
654
+
655
+ def _platform_label() -> str:
656
+ return {"Windows": "Windows", "Darwin": "macOS"}.get(platform.system(), platform.system())
657
+
658
+
659
+ def _cmd_new(name, targets, description, description_zh, version, minimal,
660
+ *, quiet=False, json_mode=False):
661
+ """``askill new <name>`` body (v0.15.0, docs/v0.15.0-plan.md R1)."""
662
+ report = create_skill(
663
+ name,
664
+ targets=targets,
665
+ description=description,
666
+ description_zh=description_zh,
667
+ version=version,
668
+ minimal=minimal,
669
+ )
670
+ if json_mode:
671
+ print(json.dumps(report, ensure_ascii=False, indent=2))
672
+ return 0 if report["created"] else 1
673
+ if report["error"]:
674
+ print(f"Error: {report['error']}")
675
+ return 1
676
+ path = report["path"]
677
+ fields = list(report["frontmatter"])
678
+ spec = report["spec"] or {}
679
+ spec_part = "spec PASS" if spec.get("ok") else "spec FAIL"
680
+ if report["product_issues"]:
681
+ spec_part = "spec FAIL (product frontmatter issues)"
682
+ print(f"Created skill skeleton: {path}")
683
+ if not quiet:
684
+ print(f" frontmatter: {', '.join(fields)}")
685
+ print(f" verify: {spec_part} (scaffold is compliant as generated)")
686
+ print("Next steps:")
687
+ print(f" 1. Edit SKILL.md in {path} - replace the TODO placeholders")
688
+ print(" 2. askill sync distribute to all products")
689
+ print(f" 3. askill verify {name} re-check after your edits")
690
+
691
+
692
+ def _cmd_publish(name, repo, *, root=False, force=False, https=False,
693
+ create=False, push=False, targets=None, quiet=False):
694
+ """``askill publish <skill> --repo owner/name`` body (v0.15.0 R2)."""
695
+ report = publish_skill(
696
+ name, repo,
697
+ root=root, force=force, https=https, create=create, push=push,
698
+ targets=targets,
699
+ verbose=not quiet,
700
+ )
701
+ if report["error"]:
702
+ print(f"Error: {report['error']}")
703
+ for p in report.get("problems", []):
704
+ print(f" gate: {p}")
705
+ return 1
706
+ if report.get("risky"):
707
+ print(" !! CAUTION: audit flagged this skill (risky/caution) - review before sharing")
708
+ if not report["ok"]:
709
+ return
710
+ if not push:
711
+ print("dry run complete - nothing was pushed. Re-run with --push to publish.")
712
+ return
713
+ entry = report["published"]
714
+ skill, repo_name = entry["skill"], entry["repo"]
715
+ print(f"Published: {skill} -> {entry['url']} ({entry['layout']} layout, {entry['commit']})")
716
+ if entry["layout"] == "root":
717
+ print(f"Install with: askill install {repo_name}")
718
+ print(f" or: npx skills add {repo_name}")
719
+ else:
720
+ print(f"Install with: askill install {repo_name}@{skill}")
721
+ print(f" or: npx skills add {repo_name} --skill {skill}")
722
+ print("skills.sh lists repos automatically once installs happen (no publish API).")
723
+
724
+
725
+ def _cmd_search(query_parts, install_idx, *, quiet=False, json_mode=False):
726
+ """``askill search`` body; extracted from main() so it stays readable."""
727
+ from ..services.registry import RegistryError, search_skills
728
+ if not query_parts:
729
+ if json_mode:
730
+ print(json.dumps({"error": "missing query"}))
731
+ elif not quiet:
732
+ print("Usage: askill search <query> [--install N]")
733
+ print(" e.g. askill search pdf --install 1")
734
+ return
735
+ query = " ".join(query_parts)
736
+ try:
737
+ results = search_skills(query)
738
+ except RegistryError as e:
739
+ if json_mode:
740
+ print(json.dumps({"error": f"skills.sh unreachable: {e}"}))
741
+ elif not quiet:
742
+ print(f"skills.sh registry unavailable: {e}")
743
+ return 1
744
+ if not results:
745
+ if json_mode:
746
+ print(json.dumps({"query": query, "results": []}, ensure_ascii=False))
747
+ elif not quiet:
748
+ print(f"No skills found for {query!r} on skills.sh.")
749
+ return
750
+ if json_mode:
751
+ # Validate --install BEFORE emitting anything so stdout stays a
752
+ # single parseable JSON document (an error doc appended after the
753
+ # results doc would produce an unparseable concatenated stream).
754
+ if install_idx is not None and not (1 <= install_idx <= len(results)):
755
+ print(json.dumps({"error": f"--install {install_idx} out of range 1-{len(results)}"}))
756
+ return 1
757
+ print(json.dumps({"query": query, "results": results}, ensure_ascii=False, indent=2))
758
+ # ``--install N`` inside JSON mode is unusual; we honour it but skip
759
+ # the human-friendly "Installing result #N" line so the stdout
760
+ # stream is parseable JSON only. Caveat: install-time SECURITY
761
+ # WARNING / [product] prints are unconditional by design and can
762
+ # still appear after the JSON document.
763
+ if install_idx is not None:
764
+ pick = results[install_idx - 1]
765
+ install_skill(f"{pick['source']}@{pick['skill_id']}", verbose=False)
766
+ return
767
+
768
+ print(f"\nskills.sh results for {query!r}:")
769
+ print(f"{'-'*70}")
770
+ for n, r in enumerate(results, start=1):
771
+ label = f"{r['source']}@{r['skill_id']}"
772
+ if len(label) > 52:
773
+ label = label[:49] + "..."
774
+ installs = f"{r['installs']:,}" if r["installs"] else "-"
775
+ print(f" {n}. {label:<50} {installs:>10} installs")
776
+ if r["name"] != r["skill_id"]:
777
+ print(f" {r['name'][:70]}")
778
+ print()
779
+ top = results[0]
780
+ print(f"Install one: askill install {top['source']}@{top['skill_id']}")
781
+ print(f" or: askill search {query} --install 1")
782
+ print()
783
+ if install_idx is None:
784
+ return 0
785
+ if install_idx < 1 or install_idx > len(results):
786
+ print(f"Invalid --install index: pick 1-{len(results)}")
787
+ return 1
788
+ pick = results[install_idx - 1]
789
+ print(f"Installing result #{install_idx}: {pick['source']}@{pick['skill_id']}")
790
+ install_skill(f"{pick['source']}@{pick['skill_id']}", verbose=not quiet)
791
+ print("\nRun 'askill sync' to distribute, or 'askill watch' to auto-sync.")
792
+
793
+
794
+ def _cmd_verify(skill_name, *, quiet=False, json_mode=False, fmt="table"):
795
+ """``askill verify [skill-name]`` body."""
796
+ from ..services.spec import (
797
+ check_all_specs,
798
+ check_spec,
799
+ product_frontmatter_issues,
800
+ )
801
+ target_dir = None
802
+ if skill_name:
803
+ skill_dir = CENTRAL_DIR / skill_name
804
+ if not skill_dir.exists():
805
+ if json_mode:
806
+ print(json.dumps({"error": f"skill not found: {skill_name}"}))
807
+ elif not quiet:
808
+ print(f"Skill not found in central repo: {skill_name}")
809
+ return
810
+ target_dir = skill_dir
811
+ reports = [check_spec(skill_dir)]
812
+ else:
813
+ reports = check_all_specs(CENTRAL_DIR)
814
+ if not reports:
815
+ if json_mode:
816
+ print(json.dumps({"results": [], "product_issues": []}))
817
+ elif not quiet:
818
+ print("No skills found in central repository.")
819
+ return
820
+
821
+ if target_dir is not None:
822
+ product_issues = [(target_dir.name, product_frontmatter_issues(target_dir))]
823
+ else:
824
+ product_issues = [
825
+ (d.name, product_frontmatter_issues(d)) for d in list_skills()
826
+ ]
827
+ flagged = [(sn, iss) for sn, iss in product_issues if iss]
828
+ if fmt == "github":
829
+ if json_mode:
830
+ print("Error: --format github cannot be combined with --json",
831
+ file=sys.stderr)
832
+ return 2
833
+ for line in verify_annotations(reports, flagged, central=CENTRAL_DIR):
834
+ print(line)
835
+ return 1 if any(not r["ok"] for r in reports) else 0
836
+ if json_mode:
837
+ print(json.dumps({
838
+ "results": reports,
839
+ "product_issues": flagged,
840
+ }, ensure_ascii=False, indent=2))
841
+ return
842
+
843
+ passed = 0
844
+ print(f"\nAgent Skills spec check (agentskills.io) - {len(reports)} skill(s):\n")
845
+ for r in reports:
846
+ icon = "PASS" if r["ok"] else "FAIL"
847
+ print(f" [{icon}] {r['skill']}")
848
+ for e in r["errors"]:
849
+ print(f" error: {e}")
850
+ for w in r["warnings"]:
851
+ print(f" warning: {w}")
852
+ passed += 1 if r["ok"] else 0
853
+ print(f"\n{passed}/{len(reports)} skill(s) ready for the skills.sh ecosystem.")
854
+ if passed < len(reports):
855
+ print("Fix the errors above so agents and skills.sh can index the skill.")
856
+ rc = 1
857
+ else:
858
+ rc = 0
859
+ if flagged:
860
+ print("\nProduct-specific frontmatter requirements:\n")
861
+ for sn, iss in flagged:
862
+ for issue in iss:
863
+ print(f" [{sn}] {issue}")
864
+ print(" Add the fields above to the skill's SKILL.md frontmatter;")
865
+ print(" affected products will not load the skill until then.")
866
+ else:
867
+ print("All per-product frontmatter requirements satisfied.")
868
+ print()
869
+ return rc
870
+
871
+
872
+ def _cmd_update(skill_name, check_only, *, quiet=False, json_mode=False):
873
+ """``askill update [skill-name] [--check]`` body."""
874
+ from ..services.sources import (
875
+ check_all_updates,
876
+ check_update,
877
+ update_skill,
878
+ )
879
+ if check_only:
880
+ if skill_name:
881
+ result = check_update(skill_name)
882
+ if json_mode:
883
+ print(json.dumps(result, ensure_ascii=False, indent=2))
884
+ elif not quiet:
885
+ status = result["status"]
886
+ skill = result["skill"]
887
+ if status == "up-to-date":
888
+ print(f"{skill}: up-to-date ({result.get('branch', '')})")
889
+ elif status == "update-available":
890
+ print(
891
+ f"{skill}: UPDATE {result.get('local_commit')} -> "
892
+ f"{result.get('remote_commit')} ({result.get('branch', '')})"
893
+ )
894
+ elif status == "untracked":
895
+ print(f"{skill}: untracked (no source recorded - installed locally)")
896
+ elif status == "missing":
897
+ print(f"{skill}: missing (skill directory not found in central repo)")
898
+ elif status == "error":
899
+ print(f"{skill}: error (remote unreachable / git failed)")
900
+ else:
901
+ print(f"{skill}: {status}")
902
+ return
903
+ results = check_all_updates()
904
+ if json_mode:
905
+ print(json.dumps(results, ensure_ascii=False, indent=2))
906
+ return
907
+ if not quiet:
908
+ print("Update check (askill update --check)\n")
909
+ print(" status legend:")
910
+ print(" up-to-date local matches the tracked remote")
911
+ print(" update-available newer commit available on the remote")
912
+ print(" untracked no source recorded (installed locally)")
913
+ print(" missing skill directory gone from the central repo")
914
+ print(" error remote unreachable / git failed")
915
+ print()
916
+ for r in results:
917
+ status = r["status"]
918
+ skill = r["skill"]
919
+ if status == "up-to-date":
920
+ print(f" {skill:<28} up-to-date ({r.get('branch', '')})")
921
+ elif status == "update-available":
922
+ print(
923
+ f" {skill:<28} UPDATE {r.get('local_commit')} -> "
924
+ f"{r.get('remote_commit')} ({r.get('branch', '')})"
925
+ )
926
+ elif status == "untracked":
927
+ print(f" {skill:<28} untracked")
928
+ elif status == "missing":
929
+ print(f" {skill:<28} missing (skill dir gone)")
930
+ elif status == "error":
931
+ print(f" {skill:<28} remote unreachable")
932
+ else:
933
+ print(f" {skill:<28} {status}")
934
+ if not results:
935
+ print(" no tracked skills (install via GitHub URL to enable tracking)")
936
+ return
937
+ if skill_name:
938
+ update_skill(skill_name)
939
+ return
940
+ results = check_all_updates()
941
+ if not results:
942
+ if json_mode:
943
+ print(json.dumps({"tracked_skills": []}))
944
+ elif not quiet:
945
+ print("No tracked skills (install via GitHub URL to enable tracking).")
946
+ return
947
+ pending = [r["skill"] for r in results if r["status"] == "update-available"]
948
+ if not pending:
949
+ if json_mode:
950
+ print(json.dumps({"pending_updates": []}))
951
+ elif not quiet:
952
+ print("All tracked skills are up to date.")
953
+ return
954
+ if json_mode:
955
+ # json_mode applies; perform the update and emit the planned list
956
+ # instead of running the side-effect-heavy updater.
957
+ print(json.dumps({"pending_updates": pending}, ensure_ascii=False, indent=2))
958
+ return
959
+ print(f"Updating {len(pending)} skill(s): {', '.join(pending)}")
960
+ for name in pending:
961
+ update_skill(name, verbose=not quiet)
962
+
963
+
964
+ # ---------------------------------------------------------------- dispatch
965
+ # Command -> handler table (health check 2026-10-31 §9). Each handler takes
966
+ # the parsed Namespace and returns an exit code (None counts as success).
967
+ # `--version` / the welcome banner are handled in main() before this runs;
968
+ # main() normalizes args.quiet/args.json_mode for uniform access below.
969
+
970
+
971
+ def _print_version() -> None:
972
+ from .. import __version__
973
+
974
+ print(f"agent-skill-manager v{__version__}")
975
+
976
+
977
+ def _dispatch_install(args: argparse.Namespace) -> int:
978
+ if args.manifest:
979
+ return _cmd_install_manifest(args.manifest, quiet=args.quiet)
980
+ # nargs="?" lets a missing <source> parse fine; keep the project's
981
+ # shorthand examples here instead of crashing in resolve_source(None).
982
+ if args.source is None:
983
+ print(_INSTALL_HELP)
984
+ sys.exit(2)
985
+ return _print_install(
986
+ args.source, sync=args.sync, audit=args.audit,
987
+ no_audit=args.no_audit, quiet=args.quiet, only=args.only,
988
+ )
989
+
990
+
991
+ def _cmd_bundle(args: argparse.Namespace) -> int:
992
+ try:
993
+ bundle_manifest(
994
+ output=Path(args.output) if args.output else None,
995
+ verbose=not args.quiet,
996
+ external_only=getattr(args, "external_only", False),
997
+ )
998
+ except OSError as e:
999
+ print(f"Error: {e}")
1000
+ return 1
1001
+ return 0
1002
+
1003
+
1004
+ def _cmd_get(args: argparse.Namespace) -> int:
1005
+ return get_skill(
1006
+ args.source,
1007
+ to_dir=args.dir,
1008
+ list_only=args.list,
1009
+ verbose=not args.quiet,
1010
+ )
1011
+
1012
+
1013
+ def _cmd_doctor(args: argparse.Namespace) -> int:
1014
+ fix = getattr(args, "fix", False)
1015
+ apply_repairs = getattr(args, "apply", False)
1016
+ if apply_repairs and not fix:
1017
+ print("Error: --apply requires --fix", file=sys.stderr)
1018
+ return 2
1019
+ if fix:
1020
+ return _cmd_doctor_fix(args, apply_repairs)
1021
+ if args.json_mode:
1022
+ print(json.dumps(doctor_report(verbose=False), ensure_ascii=False, indent=2))
1023
+ return 0
1024
+ report = doctor_report(verbose=True)
1025
+ return 0 if report["ok"] else 1
1026
+
1027
+
1028
+ def _cmd_doctor_fix(args: argparse.Namespace, apply_repairs: bool) -> int:
1029
+ """Print (and optionally execute) a repair plan derived from doctor."""
1030
+ report = doctor_report(verbose=False)
1031
+ central = Path(report["central"]["dir"])
1032
+ # Local import keeps the sync-package test seams untouched.
1033
+ from ..services.inventory import list_skills as list_skills_at
1034
+ central_names = (
1035
+ {d.name for d in list_skills_at(central)} if central.exists() else set()
1036
+ )
1037
+ plan = build_fix_plan(report, central_names)
1038
+
1039
+ if args.json_mode:
1040
+ applied: list[str] = []
1041
+ if apply_repairs:
1042
+ try:
1043
+ applied = _apply_fix_plan(plan, quiet=True)
1044
+ except OSError as e:
1045
+ print(json.dumps({"plan": plan, "error": str(e)},
1046
+ ensure_ascii=False, indent=2))
1047
+ return 1
1048
+ print(json.dumps({"plan": plan, "applied": applied},
1049
+ ensure_ascii=False, indent=2))
1050
+ return 0
1051
+
1052
+ print(render_plan(plan, applying=apply_repairs))
1053
+ if not apply_repairs:
1054
+ if not plan["noop"]:
1055
+ print("\n dry-run only - re-run with `askill doctor --fix --apply` to execute.")
1056
+ return 0
1057
+
1058
+ try:
1059
+ executed = _apply_fix_plan(plan, quiet=args.quiet)
1060
+ except OSError as e:
1061
+ print(f"Error during repair: {e}", file=sys.stderr)
1062
+ return 1
1063
+ print("\n executed: " + (", ".join(executed) if executed else "nothing to execute"))
1064
+ return 0
1065
+
1066
+
1067
+ def _apply_fix_plan(plan: dict, *, quiet: bool) -> list[str]:
1068
+ """Execute only ``auto`` actions, reusing the existing sync primitives."""
1069
+ ids = {a["id"] for a in plan["actions"]}
1070
+ executed: list[str] = []
1071
+ if "relink" in ids:
1072
+ sync_skill(verbose=not quiet)
1073
+ executed.append("askill sync")
1074
+ if "gc" in ids:
1075
+ gc_dead_links(verbose=not quiet)
1076
+ executed.append("askill sync --gc")
1077
+ return executed
1078
+
1079
+
1080
+ def _cmd_rollback(args: argparse.Namespace) -> int:
1081
+ from ..services.sources import list_rollbackable, rollback_skill
1082
+
1083
+ if args.list:
1084
+ items = list_rollbackable()
1085
+ if not items:
1086
+ print("No rollback snapshots (taken automatically before each 'askill update').")
1087
+ return 0
1088
+ print("Rollback snapshot(s) - one per skill, from its last update:")
1089
+ for n, when in items:
1090
+ print(f" {n} (snapshot taken {when})")
1091
+ return 0
1092
+ if not args.skill_name:
1093
+ print("Usage: askill rollback <skill> | askill rollback --list")
1094
+ return 2
1095
+ return 0 if rollback_skill(args.skill_name, verbose=not args.quiet) else 1
1096
+
1097
+
1098
+ def _cmd_install_manifest(path: str, quiet: bool) -> int:
1099
+ report = install_manifest(Path(path), verbose=not quiet)
1100
+ if not report["ok"]:
1101
+ print(f"Error: {report['error']}")
1102
+ return 1
1103
+ if not quiet:
1104
+ print(
1105
+ f"\nAligned: {len(report['installed'])} installed, "
1106
+ f"{len(report['present'])} present, "
1107
+ f"{len(report['failed'])} failed, "
1108
+ f"{len(report['manual'])} need manual handling"
1109
+ )
1110
+ for name, why in report["manual"]:
1111
+ print(f" - {name}: {why}")
1112
+ return 1 if (report["failed"] or report["manual"]) else 0
1113
+
1114
+
1115
+ def _dispatch_audit(args: argparse.Namespace) -> int:
1116
+ """Route the three audit modes and validate CI flags."""
1117
+ residency = getattr(args, "residency", False)
1118
+ overlap = getattr(args, "overlap", False)
1119
+ if residency and overlap:
1120
+ print("Error: --residency and --overlap are mutually exclusive",
1121
+ file=sys.stderr)
1122
+ return 2
1123
+ fail_on: set[str] = set()
1124
+ if getattr(args, "fail_on", None):
1125
+ try:
1126
+ fail_on = parse_fail_on(args.fail_on)
1127
+ except ValueError as e:
1128
+ print(f"Error: {e}", file=sys.stderr)
1129
+ return 2
1130
+ gh_format = getattr(args, "format", "table") == "github"
1131
+ if overlap:
1132
+ return _print_overlap(quiet=args.quiet, json_mode=args.json_mode)
1133
+ if residency:
1134
+ return _print_residency(quiet=args.quiet, json_mode=args.json_mode)
1135
+ return _print_audit(
1136
+ args.skill_name, quiet=args.quiet, json_mode=args.json_mode,
1137
+ fail_on=fail_on, gh_format=gh_format,
1138
+ )
1139
+
1140
+
1141
+ def _print_residency(*, quiet: bool = False, json_mode: bool = False) -> int:
1142
+ rows = residency_report(CENTRAL_DIR)
1143
+ if json_mode:
1144
+ print(json.dumps(rows, ensure_ascii=False, indent=2))
1145
+ return 0
1146
+ if not rows:
1147
+ if not quiet:
1148
+ print("No skills found in central repository.")
1149
+ return 0
1150
+ if not quiet:
1151
+ print(f"\n{'skill':<28} {'desc':>6} {'~tok':>6} {'lines':>6} {'kb':>7} suggestion")
1152
+ print("-" * 66)
1153
+ for r in rows:
1154
+ print(
1155
+ f"{r['skill'][:27]:<28} {r['desc_chars']:>6} "
1156
+ f"{r['desc_tokens_est']:>6} {r['body_lines']:>6} "
1157
+ f"{r['dir_kb']:>7} {r['suggestion']}"
1158
+ )
1159
+ print()
1160
+ print(" -- " + FOOTER)
1161
+ return 0
1162
+
1163
+
1164
+ def _dispatch_watch(args: argparse.Namespace) -> None:
1165
+ # lazy import: pulling the watcher drags in the platform-specific
1166
+ # ReadDirectoryChangesW/inotify/kqueue layer; `status` stays fast.
1167
+ from ..services.watch import watch_loop
1168
+
1169
+ watch_loop(
1170
+ interval=args.interval, json_events=args.json_mode,
1171
+ auto_adopt=getattr(args, "auto_adopt", False),
1172
+ )
1173
+
1174
+
1175
+ def _cmd_upgrade(args: argparse.Namespace) -> int:
1176
+ """``skillshuttle upgrade`` body (v0.29.0; ``askill`` alias): self-upgrade from PyPI."""
1177
+ from ..services import upgrade as up
1178
+
1179
+ quiet = bool(getattr(args, "quiet", False))
1180
+ json_mode = bool(getattr(args, "json_mode", False))
1181
+ check_only = bool(getattr(args, "check", False))
1182
+
1183
+ info = up.detect_install_mode()
1184
+ current = info["version"]
1185
+ if current is None:
1186
+ if json_mode:
1187
+ print(json.dumps({"ok": False, "error": "distribution not installed"}))
1188
+ else:
1189
+ print(
1190
+ f"Error: the {up.DIST_NAME} distribution is not installed - "
1191
+ f"reinstall with `pip install {up.DIST_NAME}`."
1192
+ )
1193
+ return 1
1194
+
1195
+ try:
1196
+ latest = up.fetch_latest_version()
1197
+ except up.UpgradeError as exc:
1198
+ if json_mode:
1199
+ print(json.dumps({"ok": False, "error": str(exc)}))
1200
+ else:
1201
+ print(f"Error: {exc}")
1202
+ print(
1203
+ "If a proxy is configured, `skillshuttle doctor --json` diagnoses "
1204
+ "reachability - PyPI must be reachable to check versions."
1205
+ )
1206
+ return 1
1207
+
1208
+ newer = up.is_newer(latest, current)
1209
+ legacy = info["dist"] == up.LEGACY_DIST_NAME
1210
+
1211
+ def _json_payload(action: str, ok: bool, message: str) -> str:
1212
+ return json.dumps({
1213
+ "ok": ok, "current": current, "latest": latest,
1214
+ "upgrade_available": newer, "mode": info["mode"],
1215
+ "action": action, "message": message,
1216
+ }, ensure_ascii=False)
1217
+
1218
+ if check_only:
1219
+ if json_mode:
1220
+ print(_json_payload("none", True, "check only"))
1221
+ return 0
1222
+ if newer:
1223
+ if legacy:
1224
+ print(f"update available: {current} -> {latest} - {up.MIGRATION_HINT}")
1225
+ else:
1226
+ print(f"update available: {current} -> {latest} (run `skillshuttle upgrade`)")
1227
+ else:
1228
+ print(f"skillshuttle is up to date ({current})")
1229
+ return 0
1230
+
1231
+ if not newer:
1232
+ if json_mode:
1233
+ print(_json_payload("none", True, "already up to date"))
1234
+ elif not quiet:
1235
+ print(f"skillshuttle is up to date ({current})")
1236
+ return 0
1237
+
1238
+ if legacy and info["mode"] != "editable":
1239
+ # Renamed in v1.0.0: upgrading in place would install skillshuttle
1240
+ # alongside cn-skill-sync, both registering the same console scripts
1241
+ # - hand the user the explicit two-step migration instead.
1242
+ if json_mode:
1243
+ print(_json_payload("rename-migrate", False, up.MIGRATION_HINT))
1244
+ else:
1245
+ print(f"Package renamed: {up.MIGRATION_HINT}")
1246
+ return 1
1247
+
1248
+ if info["mode"] == "editable":
1249
+ message = (
1250
+ "editable/source install - PyPI cannot upgrade it; "
1251
+ "the running code is your checkout, so upgrade with `git pull`"
1252
+ )
1253
+ if json_mode:
1254
+ print(_json_payload("refuse-editable", False, message))
1255
+ else:
1256
+ print(f"Refusing to upgrade: {message}.")
1257
+ return 1
1258
+
1259
+ if info["mode"] == "no-pip":
1260
+ if up.uv_on_path():
1261
+ message = "environment has no pip - run `uv tool upgrade skillshuttle`"
1262
+ else:
1263
+ message = (
1264
+ "environment has no pip - reinstall via your original "
1265
+ "installer (e.g. `uv tool install --force skillshuttle`)"
1266
+ )
1267
+ if json_mode:
1268
+ print(_json_payload("hint-uv", False, message))
1269
+ else:
1270
+ print(f"Cannot upgrade in place: {message}.")
1271
+ return 1
1272
+
1273
+ # mode == "pip": let pip do the replacement.
1274
+ if not quiet:
1275
+ print(f"upgrading {up.DIST_NAME} {current} -> {latest} via pip ...")
1276
+ result = up.run_pip_upgrade()
1277
+ if result.returncode != 0:
1278
+ tail = (result.stderr or result.stdout or "").strip()[-800:]
1279
+ if json_mode:
1280
+ print(_json_payload("pip", False, f"pip failed: {tail}"))
1281
+ else:
1282
+ print("upgrade failed:")
1283
+ print(tail)
1284
+ print(
1285
+ "If this mentions a locked skillshuttle.exe (or askill.exe), "
1286
+ "close other running processes (and this terminal) and retry."
1287
+ )
1288
+ return 1
1289
+ if json_mode:
1290
+ print(_json_payload("pip", True, f"upgraded to {latest}; restart to load it"))
1291
+ else:
1292
+ print(f"upgraded to {latest}.")
1293
+ if not quiet:
1294
+ print(
1295
+ "The running process still has the old code - new terminals "
1296
+ "pick it up. Changelog: " + up.CHANGELOG_URL
1297
+ )
1298
+ return 0
1299
+
1300
+
1301
+ _HANDLERS: dict[str, Callable[[argparse.Namespace], int | None]] = {
1302
+ "status": lambda a: _print_status(a.skill_name, quiet=a.quiet, json_mode=a.json_mode),
1303
+ "sync": lambda a: _print_sync(a.skill_name, force=a.force, quiet=a.quiet, only=a.only, gc=a.gc),
1304
+ "list": lambda a: _print_list(quiet=a.quiet, json_mode=a.json_mode),
1305
+ "install": _dispatch_install,
1306
+ "bundle": _cmd_bundle,
1307
+ "get": _cmd_get,
1308
+ "doctor": _cmd_doctor,
1309
+ "rollback": _cmd_rollback,
1310
+ "remove": lambda a: _print_remove(a.skill_name, quiet=a.quiet),
1311
+ "pack": lambda a: _print_pack(skill_name=a.skill_name, quiet=a.quiet),
1312
+ "adopt": lambda a: _print_adopt(
1313
+ a.platform_short.lower() if a.platform_short else None,
1314
+ a.skill_name, quiet=a.quiet,
1315
+ undo=getattr(a, "undo", None), json_mode=getattr(a, "json_mode", False),
1316
+ ),
1317
+ "audit": _dispatch_audit,
1318
+ "search": lambda a: _cmd_search(a.query, a.install_idx, quiet=a.quiet, json_mode=a.json_mode),
1319
+ "new": lambda a: _cmd_new(
1320
+ a.name, a.target, a.description, a.description_zh, a.version,
1321
+ a.minimal, quiet=a.quiet, json_mode=a.json_mode,
1322
+ ),
1323
+ "publish": lambda a: _cmd_publish(
1324
+ a.skill_name, a.repo, root=a.root, force=a.force, https=a.https,
1325
+ create=a.create, push=a.push, targets=a.target, quiet=a.quiet,
1326
+ ),
1327
+ "verify": lambda a: _cmd_verify(
1328
+ a.skill_name, quiet=a.quiet, json_mode=a.json_mode, fmt=a.format,
1329
+ ),
1330
+ "watch": _dispatch_watch,
1331
+ "update": lambda a: _cmd_update(a.skill_name, a.check, quiet=a.quiet, json_mode=a.json_mode),
1332
+ "upgrade": _cmd_upgrade,
1333
+ "products": lambda a: (
1334
+ _print_product_paths()
1335
+ if getattr(a, "paths", False)
1336
+ else _print_products(quiet=a.quiet, json_mode=a.json_mode)
1337
+ ),
1338
+ "drift": lambda a: _cmd_drift(a.product_short, quiet=a.quiet, json_mode=a.json_mode),
1339
+ "version": lambda a: _print_version(),
1340
+ }
1341
+
1342
+
1343
+ if __name__ == "__main__":
1344
+ main()