@jcorpac/skill-vault 1.8.0 → 2.0.0

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.
@@ -7,6 +7,7 @@ strictly in backup_manifest.json and INDEX.md, keeping SKILL.md files pure and u
7
7
  """
8
8
 
9
9
  import argparse
10
+ import fnmatch
10
11
  import hashlib
11
12
  import json
12
13
  import os
@@ -15,6 +16,12 @@ import re
15
16
  import shutil
16
17
  import sys
17
18
 
19
+ SCRIPT_DIR = Path(__file__).resolve().parent
20
+ if str(SCRIPT_DIR) not in sys.path:
21
+ sys.path.insert(0, str(SCRIPT_DIR))
22
+
23
+ import skill_router # noqa: E402
24
+
18
25
  # Default Core Foundation Skills that are protected from auto-archiving
19
26
  DEFAULT_CORE_SKILLS = {
20
27
  "skill-vault",
@@ -121,6 +128,15 @@ WORKSPACE_FINGERPRINTS = {
121
128
  "build.gradle.kts",
122
129
  "AndroidManifest.xml",
123
130
  ],
131
+ "Firebase": [
132
+ "firebase.json",
133
+ "firestore.rules",
134
+ ".firebaserc",
135
+ ],
136
+ "Robotics & MuJoCo": [
137
+ "*.urdf",
138
+ "*.mjcf",
139
+ ],
124
140
  }
125
141
 
126
142
  DEFAULT_WORKSPACE_FINGERPRINTS = WORKSPACE_FINGERPRINTS
@@ -128,10 +144,59 @@ DEFAULT_WORKSPACE_FINGERPRINTS = WORKSPACE_FINGERPRINTS
128
144
  # Default keyword rules for auto-categorizing skills across universal ecosystems
129
145
  DEFAULT_CATEGORY_RULES = {
130
146
  "Knowledge & Wiki Architecture": [
131
- "egm-",
132
147
  "wiki",
148
+ "knowledge base",
133
149
  "documentation architecture",
134
150
  ],
151
+ "Firebase": [
152
+ "firebase",
153
+ "firestore",
154
+ "crashlytics",
155
+ "remote config",
156
+ "app hosting",
157
+ "firebase auth",
158
+ ],
159
+ "Google Workspace": [
160
+ "gmail",
161
+ "gcalendar",
162
+ "gdocs",
163
+ "gdrive",
164
+ "gsheets",
165
+ "gslides",
166
+ "google workspace",
167
+ "google calendar",
168
+ "google docs",
169
+ "google sheets",
170
+ "google slides",
171
+ "google drive",
172
+ ],
173
+ "Robotics & MuJoCo": [
174
+ "mujoco",
175
+ "mjcf",
176
+ "urdf",
177
+ "robotics",
178
+ "kinematics",
179
+ "inverse kinematics",
180
+ "gripper",
181
+ "actuator",
182
+ ],
183
+ "Chrome DevTools & Web Performance": [
184
+ "chrome-devtools",
185
+ "chrome devtools",
186
+ "chrome-extension",
187
+ "chrome extension",
188
+ "memory leak",
189
+ "memory-leak",
190
+ "lcp",
191
+ "core web vitals",
192
+ "lighthouse",
193
+ ],
194
+ "Google Maps & Geo": [
195
+ "google-maps",
196
+ "google_maps",
197
+ "maps-platform",
198
+ "maps platform",
199
+ ],
135
200
  "Gemini API & AI Agents": [
136
201
  "gemini",
137
202
  "adk",
@@ -205,6 +270,13 @@ DEFAULT_CATEGORY_RULES = {
205
270
  "pubsub",
206
271
  "cloud storage",
207
272
  "cloud run",
273
+ "bigtable",
274
+ "gcloud",
275
+ "gcs",
276
+ "google-cloud",
277
+ "google_cloud",
278
+ "spark",
279
+ "lakehouse",
208
280
  ],
209
281
  "Testing, QA & Security": [
210
282
  "playwright",
@@ -387,26 +459,42 @@ def resolve_base_dir(cli_base=None):
387
459
  if p.exists():
388
460
  return p
389
461
 
390
- # Check ancestors of the script location
462
+ # 1. Prioritize ancestors of the script location that actually contain a skill_archive
391
463
  script_path = Path(__file__).resolve()
392
464
  for parent in script_path.parents:
393
- if parent.name != "skill_archive" and (
394
- (parent / "skill_archive").exists() or (parent / "skills").exists()
395
- ):
465
+ if parent.name != "skill_archive" and (parent / "skill_archive").exists():
396
466
  return parent
397
467
 
398
468
  cwd = Path.cwd().resolve()
399
- for candidate in [
469
+ home = Path.home()
470
+ candidates = [
400
471
  cwd,
401
472
  cwd / ".agents",
402
473
  cwd / ".claude",
403
- Path.home() / ".gemini" / "config",
404
- Path.home() / ".agents",
405
- Path.home() / ".claude",
406
- ]:
407
- if candidate.exists() and (
408
- (candidate / "skills").exists() or (candidate / "skill_archive").exists()
409
- ):
474
+ cwd / ".gemini",
475
+ cwd / ".cursor",
476
+ home / ".gemini" / "config",
477
+ home / ".gemini" / "config" / "skills" / "skill-vault",
478
+ home / ".agents",
479
+ home / ".claude",
480
+ home / ".gemini",
481
+ home / ".cursor",
482
+ ]
483
+ # 2. Check standard workspace and global locations for an existing skill_archive
484
+ for candidate in candidates:
485
+ if candidate.exists() and (candidate / "skill_archive").exists():
486
+ return candidate
487
+
488
+ # 3. Fallback to ancestors with skills/ (skipping installed plugins/skill-vault wrapper)
489
+ for parent in script_path.parents:
490
+ if parent.name == "skill-vault" and parent.parent.name == "plugins":
491
+ continue
492
+ if parent.name != "skill_archive" and (parent / "skills").exists():
493
+ return parent
494
+
495
+ # 4. Fallback to workspace or global locations with skills/
496
+ for candidate in candidates:
497
+ if candidate.exists() and (candidate / "skills").exists():
410
498
  return candidate
411
499
 
412
500
  return cwd
@@ -414,10 +502,12 @@ def resolve_base_dir(cli_base=None):
414
502
 
415
503
  class SkillVault:
416
504
  def __init__(self, base_dir=None):
505
+ self._explicit_base_dir = bool(base_dir)
417
506
  self.base_dir = resolve_base_dir(base_dir)
418
507
  self.archive_dir = self.base_dir / "skill_archive"
419
508
  self.manifest_file = self.archive_dir / "backup_manifest.json"
420
509
  self.index_file = self.archive_dir / "INDEX.md"
510
+ self.search_index_file = self.archive_dir / "search_index.json"
421
511
  self.config_file = self.archive_dir / "vault_config.json"
422
512
  self.skills_dir = self.base_dir / "skills"
423
513
 
@@ -459,11 +549,16 @@ class SkillVault:
459
549
  if cat not in merged_rules:
460
550
  merged_rules[cat] = list(kws)
461
551
 
552
+ routing_cfg = dict(skill_router.DEFAULT_ROUTING_CONFIG)
553
+ if isinstance(user_cfg.get("routing"), dict):
554
+ routing_cfg.update(user_cfg["routing"])
555
+
462
556
  return {
463
557
  "core_skills": sorted(core_skills),
464
558
  "disabled_core_skills": sorted(disabled_core),
465
559
  "workspace_fingerprints": merged_fp,
466
560
  "category_rules": merged_rules,
561
+ "routing": routing_cfg,
467
562
  }
468
563
 
469
564
  def save_config(self, config_data):
@@ -705,17 +800,60 @@ class SkillVault:
705
800
  return self.base_dir
706
801
 
707
802
  def get_skill_vault_dir(self):
708
- """Locate the installed skill-vault skill directory if present (excluding git repo roots)."""
709
- if self.base_dir.name == "skill-vault" and self.base_dir.parent.name == "skills":
803
+ """Locate the installed skill-vault skill/plugin directory if present (excluding git repo roots)."""
804
+ if self.base_dir.name == "skill-vault" and self.base_dir.parent.name in ("skills", "plugins"):
710
805
  if not (self.base_dir / ".git").exists():
711
806
  return self.base_dir
712
807
  root_dir = self.get_root_dir()
713
- for rel in ["skills/skill-vault", ".agents/skills/skill-vault", ".claude/skills/skill-vault"]:
808
+ for rel in [
809
+ "plugins/skill-vault",
810
+ "skills/skill-vault",
811
+ ".agents/skills/skill-vault",
812
+ ".claude/skills/skill-vault",
813
+ ]:
714
814
  cand = (root_dir / rel).resolve()
715
815
  if cand.exists() and not (cand / ".git").exists():
716
816
  return cand
717
817
  return None
718
818
 
819
+ def get_hook_protected_skills(self):
820
+ """Inspect plugin hooks.json and mcp_config.json files to protect skills referenced by commands."""
821
+ protected = {"skill-vault"}
822
+ plugin_roots = []
823
+ for cand in (self.base_dir / "plugins", self.get_root_dir() / "plugins"):
824
+ if cand.exists() and cand.is_dir():
825
+ res = cand.resolve()
826
+ if res not in plugin_roots:
827
+ plugin_roots.append(res)
828
+
829
+ skill_ref_re = re.compile(r"(?:^|[\s\"'=/\\])skills[/\\]([a-zA-Z0-9._-]+)")
830
+
831
+ def _scan_obj(obj):
832
+ if isinstance(obj, str):
833
+ for m in skill_ref_re.finditer(obj):
834
+ protected.add(m.group(1))
835
+ elif isinstance(obj, list):
836
+ for item in obj:
837
+ _scan_obj(item)
838
+ elif isinstance(obj, dict):
839
+ for val in obj.values():
840
+ _scan_obj(val)
841
+
842
+ for proot in plugin_roots:
843
+ for pdir in proot.iterdir():
844
+ if not pdir.is_dir():
845
+ continue
846
+ for cfg_name in ("hooks.json", "mcp_config.json"):
847
+ cfg_path = pdir / cfg_name
848
+ if not cfg_path.exists():
849
+ continue
850
+ try:
851
+ data = json.loads(cfg_path.read_text(encoding="utf-8", errors="replace"))
852
+ _scan_obj(data)
853
+ except Exception:
854
+ pass
855
+ return protected
856
+
719
857
  def make_portable_path(self, abs_path):
720
858
  """Convert path to relative from base_dir or root_dir if possible."""
721
859
  resolved = Path(abs_path).resolve()
@@ -837,43 +975,55 @@ class SkillVault:
837
975
  # --- Workspace & Optimization Engine ---
838
976
 
839
977
  def detect_workspace_categories(self, workspace_path=None):
840
- """Inspect workspace files and return matched skill categories."""
978
+ """Inspect workspace files in a single depth-bounded pass and return matched skill categories."""
841
979
  target_ws = Path(workspace_path).resolve() if workspace_path else Path.cwd().resolve()
842
980
  matched = {}
843
981
  config = self.load_config()
844
982
  fingerprints = config["workspace_fingerprints"]
845
983
 
984
+ if not target_ws.exists():
985
+ return matched
986
+
987
+ ignored_dirs = {".git", "node_modules", "__pycache__", ".venv", "venv", ".tox", "dist", "build", ".next", "target"}
988
+ seen_names = set()
989
+ seen_rel_paths = set()
990
+ ws_tokens = {}
991
+
992
+ for root, dirs, files in os.walk(target_ws):
993
+ dirs[:] = [d for d in dirs if d not in ignored_dirs]
994
+ rel_path = Path(root).relative_to(target_ws)
995
+ rel_depth = len(rel_path.parts)
996
+ if rel_depth > 3:
997
+ dirs[:] = []
998
+ continue
999
+ rel_prefix = "" if rel_path == Path(".") else rel_path.as_posix().lower() + "/"
1000
+ for entry_name in dirs + files:
1001
+ low_name = entry_name.lower()
1002
+ seen_names.add(low_name)
1003
+ seen_rel_paths.add(rel_prefix + low_name)
1004
+ tokens = {t for t in re.split(r"[-_.\s]+", low_name) if t}
1005
+ for tok in tokens:
1006
+ ws_tokens.setdefault(tok, entry_name)
1007
+
846
1008
  for category, patterns in fingerprints.items():
847
1009
  for pat in patterns:
848
- if "*" in pat:
849
- matches = list(target_ws.glob(pat)) + list(target_ws.glob(f"**/{pat}"))[:5]
850
- if matches:
851
- matched.setdefault(category, []).append(pat)
852
- break
1010
+ pat_l = str(pat).lower()
1011
+ if "*" in pat_l or "?" in pat_l:
1012
+ hit = any(fnmatch.fnmatchcase(n, pat_l) for n in seen_names) or any(
1013
+ fnmatch.fnmatchcase(rp, pat_l) for rp in seen_rel_paths
1014
+ )
853
1015
  else:
854
- if (target_ws / pat).exists() or list(target_ws.glob(f"**/{pat}"))[:1]:
855
- matched.setdefault(category, []).append(pat)
856
- break
1016
+ hit = (pat_l in seen_names) or (pat_l in seen_rel_paths)
1017
+ if hit:
1018
+ matched.setdefault(category, []).append(pat)
1019
+ break
857
1020
 
858
1021
  # Inspect categories present in manifest for workspace filename/directory keyword matches
859
1022
  manifest = self.load_manifest()
860
1023
  manifest_categories = {m.get("category") for m in manifest if m.get("category")}
861
1024
  unmatched_cats = [c for c in sorted(manifest_categories) if c not in matched]
862
- if unmatched_cats and target_ws.exists():
1025
+ if unmatched_cats:
863
1026
  stop_words = {"and", "the", "skills", "general", "utility"}
864
- ignored_dirs = {".git", "node_modules", "__pycache__", ".venv", "venv", ".tox", "dist", "build"}
865
- ws_tokens = {}
866
- for root, dirs, files in os.walk(target_ws):
867
- dirs[:] = [d for d in dirs if d not in ignored_dirs]
868
- rel_depth = len(Path(root).relative_to(target_ws).parts)
869
- if rel_depth > 3:
870
- dirs[:] = []
871
- continue
872
- for entry_name in dirs + files:
873
- tokens = {t for t in re.split(r"[-_.\s]+", entry_name.lower()) if t}
874
- for tok in tokens:
875
- ws_tokens.setdefault(tok, entry_name)
876
-
877
1027
  for cat in unmatched_cats:
878
1028
  words = [
879
1029
  w.lower()
@@ -895,6 +1045,7 @@ class SkillVault:
895
1045
  """
896
1046
  target_ws = Path(workspace_path).resolve() if workspace_path else Path.cwd().resolve()
897
1047
  core_set = self.get_core_skills(protected_skills)
1048
+ hook_protected = self.get_hook_protected_skills()
898
1049
 
899
1050
  print("==================================================")
900
1051
  print(" SKILL VAULT AUTO-OPTIMIZATION")
@@ -923,6 +1074,8 @@ class SkillVault:
923
1074
  skill_md_path = Path(data["path"]) / "SKILL.md"
924
1075
  if name in core_set:
925
1076
  to_keep.append((name, "Core Foundation Skill"))
1077
+ elif name in hook_protected:
1078
+ to_keep.append((name, "Protected Plugin Hook/MCP Dependency"))
926
1079
  elif self.is_core_skill_frontmatter(skill_md_path):
927
1080
  to_keep.append((name, "Core Foundation Skill (Pinned in Frontmatter)"))
928
1081
  else:
@@ -1014,14 +1167,7 @@ class SkillVault:
1014
1167
  if explicit_cat:
1015
1168
  return explicit_cat
1016
1169
 
1017
- if skill_name in self.get_core_skills() or skill_name in [
1018
- "gmail",
1019
- "gcalendar",
1020
- "gslides",
1021
- "gdocs",
1022
- "gdrive",
1023
- "gsheets",
1024
- ]:
1170
+ if skill_name in self.get_core_skills():
1025
1171
  return "General & Utility Skills"
1026
1172
 
1027
1173
  rules = self.load_config()["category_rules"]
@@ -1045,6 +1191,7 @@ class SkillVault:
1045
1191
  print("==================================================\n")
1046
1192
 
1047
1193
  core_set = self.get_core_skills(protect_skills)
1194
+ hook_protected = self.get_hook_protected_skills()
1048
1195
 
1049
1196
  active_skills = self.get_active_skills()
1050
1197
  manifest = self.load_manifest()
@@ -1055,6 +1202,7 @@ class SkillVault:
1055
1202
  to_prune = []
1056
1203
  in_sync = []
1057
1204
  retained_core = []
1205
+ protected_hooks = []
1058
1206
 
1059
1207
  for name, data in sorted(active_skills.items()):
1060
1208
  if name == "skill-vault":
@@ -1064,6 +1212,7 @@ class SkillVault:
1064
1212
  active_path = Path(data["path"])
1065
1213
  skill_md_path = active_path / "SKILL.md"
1066
1214
  is_core = (name in core_set) or self.is_core_skill_frontmatter(skill_md_path)
1215
+ is_hook_dep = name in hook_protected
1067
1216
 
1068
1217
  if name in manifest_map:
1069
1218
  item = manifest_map[name]
@@ -1088,6 +1237,8 @@ class SkillVault:
1088
1237
 
1089
1238
  if is_core:
1090
1239
  retained_core.append(name)
1240
+ elif is_hook_dep:
1241
+ protected_hooks.append(name)
1091
1242
  elif not keep_active:
1092
1243
  to_prune.append((name, data))
1093
1244
 
@@ -1102,6 +1253,10 @@ class SkillVault:
1102
1253
 
1103
1254
  print(f" * In-sync skills in vault: {len(in_sync)}")
1104
1255
  print(f" * Retained Core Foundation Skills: {len(retained_core)} ({', '.join(sorted(retained_core))})")
1256
+ if protected_hooks:
1257
+ print(f" * Hook/MCP-Protected Plugin Skills: {len(protected_hooks)}")
1258
+ for name in sorted(protected_hooks):
1259
+ print(f" [Protected (Hook Dependency)] {name}")
1105
1260
  print(f" * Non-core active skills to prune: {len(to_prune)}")
1106
1261
  for name, _ in to_prune:
1107
1262
  print(f" [PRUNE] {name} (Will be removed from active context to prevent context bloat)")
@@ -1254,6 +1409,7 @@ class SkillVault:
1254
1409
  """Archive active skills with an assigned category, prioritizing newer versions."""
1255
1410
  manifest = self.load_manifest()
1256
1411
  manifest_map = {item["name"]: item for item in manifest}
1412
+ hook_protected = self.get_hook_protected_skills()
1257
1413
 
1258
1414
  skills_to_archive = []
1259
1415
  if name:
@@ -1285,8 +1441,11 @@ class SkillVault:
1285
1441
  if recency < 0 and not force:
1286
1442
  print(f"[Skip] L2 archive '{skill_name}' is newer than active L1 version. Preserving newer archive (use --force to overwrite).")
1287
1443
  if not keep_active:
1288
- shutil.rmtree(active_path)
1289
- print(f"[Cleaned] Removed older active directory: {active_path}")
1444
+ if skill_name in hook_protected:
1445
+ print(f"[Protected (Hook Dependency)] Preserving active '{skill_name}' (referenced by plugin hooks/MCP; use --force to override)")
1446
+ else:
1447
+ shutil.rmtree(active_path)
1448
+ print(f"[Cleaned] Removed older active directory: {active_path}")
1290
1449
  continue
1291
1450
  elif recency > 0:
1292
1451
  print(f"[Archived] Overwriting older L2 archive with newer active L1 version: {active_path} -> {dest_dir}")
@@ -1315,27 +1474,70 @@ class SkillVault:
1315
1474
  }
1316
1475
 
1317
1476
  if not keep_active:
1318
- shutil.rmtree(active_path)
1319
- print(f"[Cleaned] Removed active directory: {active_path}")
1477
+ if skill_name in hook_protected and not force:
1478
+ print(f"[Protected (Hook Dependency)] Preserving active '{skill_name}' (referenced by plugin hooks/MCP; use --force to override)")
1479
+ else:
1480
+ shutil.rmtree(active_path)
1481
+ print(f"[Cleaned] Removed active directory: {active_path}")
1320
1482
 
1321
1483
  self.save_manifest(list(manifest_map.values()))
1322
1484
  self.reindex()
1323
1485
  print("Archiving complete.")
1324
1486
 
1325
- def recategorize(self, name, new_category):
1326
- """Update category for an archived skill."""
1487
+ def recategorize(self, name=None, new_category=None, auto=False, dry_run=False):
1488
+ """Update category for an archived skill, or auto-recategorize General & Utility Skills."""
1327
1489
  manifest = self.load_manifest()
1328
1490
  manifest_map = {item["name"]: item for item in manifest}
1329
1491
 
1492
+ if auto:
1493
+ updates = []
1494
+ scanned_general = 0
1495
+ for item in manifest:
1496
+ cur_cat = item.get("category") or "General & Utility Skills"
1497
+ if cur_cat != "General & Utility Skills":
1498
+ continue
1499
+ scanned_general += 1
1500
+ archived_path = self.resolve_portable_path(item.get("archived_path", ""))
1501
+ skill_md = archived_path / "SKILL.md"
1502
+ desc = self.parse_skill_description(skill_md) if skill_md.exists() else ""
1503
+ inferred = self.infer_category(item["name"], desc, skill_md if skill_md.exists() else None)
1504
+ if inferred and inferred != "General & Utility Skills":
1505
+ updates.append((item["name"], cur_cat, inferred))
1506
+ if not dry_run:
1507
+ item["category"] = inferred
1508
+
1509
+ print("==================================================")
1510
+ print(" SKILL VAULT AUTO-RECATEGORIZATION")
1511
+ print(f" General skills scanned: {scanned_general}")
1512
+ print(f" Improved categories: {len(updates)}")
1513
+ print("==================================================\n")
1514
+ for sname, old_c, new_c in updates:
1515
+ print(f" * {sname}: '{old_c}' -> '{new_c}'")
1516
+
1517
+ if dry_run:
1518
+ print("\n[Dry Run] Auto-recategorization preview complete. No changes saved.")
1519
+ return 0
1520
+
1521
+ if updates:
1522
+ self.save_manifest(manifest)
1523
+ self.reindex()
1524
+ print(f"\n[OK] Recategorized {len(updates)} skill(s).")
1525
+ return 0
1526
+
1527
+ if not name or not new_category:
1528
+ print("[Error] Please specify skill name and new category, or pass --auto.")
1529
+ return 1
1530
+
1330
1531
  if name not in manifest_map:
1331
1532
  print(f"[Error] Skill '{name}' not found in manifest.")
1332
- return
1533
+ return 1
1333
1534
 
1334
1535
  old_cat = manifest_map[name].get("category", "Uncategorized")
1335
1536
  manifest_map[name]["category"] = new_category.strip()
1336
1537
  self.save_manifest(list(manifest_map.values()))
1337
1538
  self.reindex()
1338
1539
  print(f"[Recategorized] '{name}': '{old_cat}' -> '{new_category.strip()}'")
1540
+ return 0
1339
1541
 
1340
1542
  def restore(self, name=None, pattern=None, category=None, restore_all=False, force=False):
1341
1543
  """Restore archived skills back to active locations."""
@@ -1390,6 +1592,105 @@ class SkillVault:
1390
1592
 
1391
1593
  print("Restoration complete.")
1392
1594
 
1595
+ def _find_external_harness_configs(self):
1596
+ """Return existing harness config files that contain skill-vault hook/MCP entries."""
1597
+ root_dir = self.get_root_dir().resolve()
1598
+ home = Path.home().resolve()
1599
+ candidates = [
1600
+ root_dir / ".claude" / "settings.json",
1601
+ root_dir / ".gemini" / "settings.json",
1602
+ root_dir / ".cursor" / "mcp.json",
1603
+ ]
1604
+ global_roots = {
1605
+ home,
1606
+ (home / ".gemini" / "config").resolve(),
1607
+ (home / ".claude").resolve(),
1608
+ (home / ".agents").resolve(),
1609
+ }
1610
+ if root_dir in global_roots:
1611
+ candidates.extend([
1612
+ home / ".claude" / "settings.json",
1613
+ home / ".gemini" / "settings.json",
1614
+ home / ".cursor" / "mcp.json",
1615
+ ])
1616
+
1617
+ matched = []
1618
+ seen = set()
1619
+ for p in candidates:
1620
+ res = p.resolve()
1621
+ if res in seen or not p.exists():
1622
+ continue
1623
+ seen.add(res)
1624
+ try:
1625
+ text = p.read_text(encoding="utf-8", errors="replace")
1626
+ if "skill-vault" in text or "hook_runner.py" in text or "mcp_server.py" in text:
1627
+ matched.append(p)
1628
+ except OSError:
1629
+ pass
1630
+ return matched
1631
+
1632
+ @staticmethod
1633
+ def _clean_external_harness_config(cfg_path):
1634
+ """Surgically remove skill-vault hook/MCP entries from an external harness JSON config."""
1635
+ cfg_path = Path(cfg_path)
1636
+ if not cfg_path.exists():
1637
+ return False
1638
+ try:
1639
+ data = json.loads(cfg_path.read_text(encoding="utf-8", errors="replace"))
1640
+ except Exception:
1641
+ return False
1642
+ if not isinstance(data, dict):
1643
+ return False
1644
+
1645
+ changed = False
1646
+ mcp = data.get("mcpServers")
1647
+ if isinstance(mcp, dict) and "skill-vault" in mcp:
1648
+ del mcp["skill-vault"]
1649
+ if not mcp:
1650
+ del data["mcpServers"]
1651
+ changed = True
1652
+
1653
+ hooks = data.get("hooks")
1654
+ if isinstance(hooks, dict):
1655
+ for evt in list(hooks.keys()):
1656
+ groups = hooks.get(evt)
1657
+ if not isinstance(groups, list):
1658
+ continue
1659
+ new_groups = []
1660
+ for grp in groups:
1661
+ if not isinstance(grp, dict):
1662
+ new_groups.append(grp)
1663
+ continue
1664
+ sub_hooks = grp.get("hooks")
1665
+ if isinstance(sub_hooks, list):
1666
+ kept = [
1667
+ h for h in sub_hooks
1668
+ if not (
1669
+ isinstance(h, dict)
1670
+ and ("hook_runner.py" in str(h.get("command", "")) or "skill-vault" in str(h.get("command", "")))
1671
+ )
1672
+ ]
1673
+ if len(kept) != len(sub_hooks):
1674
+ changed = True
1675
+ if kept:
1676
+ grp_copy = dict(grp)
1677
+ grp_copy["hooks"] = kept
1678
+ new_groups.append(grp_copy)
1679
+ else:
1680
+ new_groups.append(grp)
1681
+ if new_groups:
1682
+ hooks[evt] = new_groups
1683
+ else:
1684
+ del hooks[evt]
1685
+ if not hooks:
1686
+ del data["hooks"]
1687
+
1688
+ if changed:
1689
+ tmp = cfg_path.with_name(f".{cfg_path.name}.{os.getpid()}.tmp")
1690
+ tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
1691
+ os.replace(tmp, cfg_path)
1692
+ return changed
1693
+
1393
1694
  def uninstall(self, dry_run=False, force=False, keep_archive=False, keep_skill=False):
1394
1695
  """Cleanly restore all archived skills to L1 without overwriting newer L1 versions and remove skill-vault."""
1395
1696
  root_dir = self.get_root_dir()
@@ -1483,10 +1784,22 @@ class SkillVault:
1483
1784
  else:
1484
1785
  print(f" * Archive: Remove {self.archive_dir}")
1485
1786
 
1486
- if keep_skill or not sv_dir:
1787
+ sv_dirs = []
1788
+ for cand in [sv_dir, root_dir / "plugins" / "skill-vault", root_dir / "skills" / "skill-vault"]:
1789
+ if cand and cand.exists() and not (cand / ".git").exists():
1790
+ resolved_cand = cand.resolve()
1791
+ if resolved_cand not in sv_dirs:
1792
+ sv_dirs.append(resolved_cand)
1793
+
1794
+ if keep_skill or not sv_dirs:
1487
1795
  print(f" * Skill: Keep {sv_dir if sv_dir else '(None detected)'}")
1488
1796
  else:
1489
- print(f" * Skill: Remove {sv_dir}")
1797
+ for d in sv_dirs:
1798
+ print(f" * Skill: Remove {d}")
1799
+
1800
+ harness_targets = [] if keep_skill else self._find_external_harness_configs()
1801
+ for hpath in harness_targets:
1802
+ print(f" * Wiring: Remove skill-vault entries from {hpath}")
1490
1803
  print("")
1491
1804
 
1492
1805
  if missing_sources:
@@ -1509,8 +1822,8 @@ class SkillVault:
1509
1822
  dirs_to_delete = []
1510
1823
  if not keep_archive and self.archive_dir.exists():
1511
1824
  dirs_to_delete.append(self.archive_dir.resolve())
1512
- if sv_dir and not keep_skill and sv_dir.exists():
1513
- dirs_to_delete.append(sv_dir.resolve())
1825
+ if not keep_skill:
1826
+ dirs_to_delete.extend(sv_dirs)
1514
1827
 
1515
1828
  verification_errors = []
1516
1829
  for skill_name, _, original_path, _ in to_restore + to_upgrade + to_preserve:
@@ -1550,12 +1863,17 @@ class SkillVault:
1550
1863
  shutil.rmtree(self.archive_dir)
1551
1864
  print(f"[Removed] Archive directory: {self.archive_dir}")
1552
1865
 
1553
- if sv_dir and not keep_skill and sv_dir.exists():
1554
- cwd_resolved = Path.cwd().resolve()
1555
- if cwd_resolved == sv_dir.resolve() or sv_dir.resolve() in cwd_resolved.parents:
1556
- os.chdir(root_dir)
1557
- shutil.rmtree(sv_dir)
1558
- print(f"[Removed] Skill-vault directory: {sv_dir}")
1866
+ if not keep_skill:
1867
+ for d in sv_dirs:
1868
+ if d.exists():
1869
+ cwd_resolved = Path.cwd().resolve()
1870
+ if cwd_resolved == d or d in cwd_resolved.parents:
1871
+ os.chdir(root_dir)
1872
+ shutil.rmtree(d)
1873
+ print(f"[Removed] Skill-vault directory: {d}")
1874
+ for hpath in harness_targets:
1875
+ if self._clean_external_harness_config(hpath):
1876
+ print(f"[Cleaned] Removed skill-vault entries from: {hpath}")
1559
1877
 
1560
1878
  total_safe = len(to_restore) + len(to_upgrade) + len(to_preserve)
1561
1879
  print(f"\n[OK] Clean uninstall complete! {total_safe} skill(s) verified safe in active L1 locations.")
@@ -1622,11 +1940,25 @@ class SkillVault:
1622
1940
  f.write("\n".join(lines).strip() + "\n")
1623
1941
 
1624
1942
  self.save_manifest(list(manifest_by_folder.values()))
1943
+ skill_router.build_search_index(
1944
+ archive_dir=self.archive_dir,
1945
+ manifest=list(manifest_by_folder.values()),
1946
+ base_dir=self.base_dir,
1947
+ resolve_path_fn=self.resolve_portable_path,
1948
+ )
1625
1949
  updated_routers = self.sync_router_md()
1626
1950
  for r_path in updated_routers:
1627
1951
  print(f"[Router Synced] Updated SKILL.md frontmatter: {r_path}")
1628
1952
  print(f"[Reindexed] {total_count} skills across {len(categories)} categories (Base: {self.base_dir}).")
1629
1953
 
1954
+ def build_compact_router_description(self):
1955
+ """Build a minimal ~45-token frontmatter description when background hooks are active."""
1956
+ return (
1957
+ "Universal agent-agnostic skill router and tiered storage manager. "
1958
+ "Background hooks automatically inject relevant vaulted skills on demand; "
1959
+ "use MCP tools search_skills/load_skill for mid-turn lookups."
1960
+ )
1961
+
1630
1962
  def build_router_description(self):
1631
1963
  """Build a dynamic SKILL.md router description from the current archive manifest."""
1632
1964
  manifest = self.load_manifest()
@@ -1661,10 +1993,13 @@ class SkillVault:
1661
1993
 
1662
1994
  def _get_router_skill_md_candidates(self):
1663
1995
  """Locate candidate SKILL.md files belonging to skill-vault within base_dir."""
1996
+ root_dir = self.get_root_dir()
1664
1997
  raw_candidates = [
1665
1998
  self.skills_dir / "skill-vault" / "SKILL.md",
1666
1999
  self.base_dir / ".agents" / "skills" / "skill-vault" / "SKILL.md",
1667
2000
  self.base_dir / ".claude" / "skills" / "skill-vault" / "SKILL.md",
2001
+ self.base_dir / "plugins" / "skill-vault" / "skills" / "skill-vault" / "SKILL.md",
2002
+ root_dir / "plugins" / "skill-vault" / "skills" / "skill-vault" / "SKILL.md",
1668
2003
  ]
1669
2004
  if self.archive_dir.exists():
1670
2005
  raw_candidates.append(self.base_dir / "SKILL.md")
@@ -1681,7 +2016,11 @@ class SkillVault:
1681
2016
  def sync_router_md(self, target_skill_md=None, force=False):
1682
2017
  """Synchronize skill-vault's SKILL.md frontmatter description with the active vault categories."""
1683
2018
  candidates = [Path(target_skill_md)] if target_skill_md else self._get_router_skill_md_candidates()
1684
- new_desc = self.build_router_description()
2019
+ routing_cfg = self.load_config().get("routing", {})
2020
+ if routing_cfg.get("compact_router_prompt"):
2021
+ new_desc = self.build_compact_router_description()
2022
+ else:
2023
+ new_desc = self.build_router_description()
1685
2024
  new_desc_block = f"description: >-\n {new_desc}"
1686
2025
  desc_pattern = re.compile(
1687
2026
  r"^description:\s*(?:>[-+]?|\|[-+]?)?\s*\n?.*?(?=\n[a-zA-Z0-9_-]+:|\Z)",
@@ -1715,6 +2054,20 @@ class SkillVault:
1715
2054
 
1716
2055
  return updated
1717
2056
 
2057
+ @staticmethod
2058
+ def _parse_routing_value(key, raw_val):
2059
+ default = skill_router.DEFAULT_ROUTING_CONFIG.get(key)
2060
+ val = str(raw_val).strip()
2061
+ if isinstance(default, bool):
2062
+ return val.lower() in {"1", "true", "yes", "on"}
2063
+ if isinstance(default, int):
2064
+ return int(val)
2065
+ if isinstance(default, float):
2066
+ return float(val)
2067
+ if isinstance(default, list):
2068
+ return [v.strip() for v in val.split(",") if v.strip()]
2069
+ return val
2070
+
1718
2071
  def manage_config(
1719
2072
  self,
1720
2073
  show=False,
@@ -1723,6 +2076,7 @@ class SkillVault:
1723
2076
  remove_core=None,
1724
2077
  add_fingerprint=None,
1725
2078
  add_category_rule=None,
2079
+ set_routing=None,
1726
2080
  sync_prompt=False,
1727
2081
  ):
1728
2082
  """Inspect or update vault_config.json and dynamically synchronize the router prompt."""
@@ -1735,14 +2089,15 @@ class SkillVault:
1735
2089
 
1736
2090
  fp_pairs = _normalize_pairs(add_fingerprint)
1737
2091
  rule_pairs = _normalize_pairs(add_category_rule)
1738
- mutating = bool(init_config or add_core or remove_core or fp_pairs or rule_pairs)
2092
+ routing_pairs = _normalize_pairs(set_routing)
2093
+ mutating = bool(init_config or add_core or remove_core or fp_pairs or rule_pairs or routing_pairs)
1739
2094
 
1740
2095
  if init_config:
1741
2096
  effective = self.load_config()
1742
2097
  self.save_config(effective)
1743
2098
  print(f"[Config Initialized] Wrote vault configuration to: {self.config_file}")
1744
2099
 
1745
- if add_core or remove_core or fp_pairs or rule_pairs:
2100
+ if add_core or remove_core or fp_pairs or rule_pairs or routing_pairs:
1746
2101
  raw_cfg = self._load_raw_config()
1747
2102
 
1748
2103
  if add_core:
@@ -1807,6 +2162,18 @@ class SkillVault:
1807
2162
  print(f"[Config Updated] Added category rule: [{c}] <- '{k}'")
1808
2163
  raw_cfg["category_rules"] = rule_map
1809
2164
 
2165
+ if routing_pairs:
2166
+ routing_map = dict(raw_cfg.get("routing", {}))
2167
+ for r_key, r_val in routing_pairs:
2168
+ k = r_key.strip()
2169
+ if k not in skill_router.DEFAULT_ROUTING_CONFIG:
2170
+ print(f"[Warning] Unknown routing key '{k}'. Valid keys: {', '.join(sorted(skill_router.DEFAULT_ROUTING_CONFIG))}")
2171
+ continue
2172
+ parsed = self._parse_routing_value(k, r_val)
2173
+ routing_map[k] = parsed
2174
+ print(f"[Config Updated] Routing '{k}' = {parsed!r}")
2175
+ raw_cfg["routing"] = routing_map
2176
+
1810
2177
  self.save_config(raw_cfg)
1811
2178
 
1812
2179
  if sync_prompt:
@@ -1829,7 +2196,10 @@ class SkillVault:
1829
2196
  print("==================================================\n")
1830
2197
  print(f"Protected Core Skills ({len(effective['core_skills'])}):")
1831
2198
  print(f" {', '.join(effective['core_skills'])}\n")
1832
- print(f"Workspace Fingerprint Categories ({len(effective['workspace_fingerprints'])}):")
2199
+ print("Background JIT Routing Settings:")
2200
+ for rk, rv in sorted(effective["routing"].items()):
2201
+ print(f" * {rk}: {rv!r}")
2202
+ print(f"\nWorkspace Fingerprint Categories ({len(effective['workspace_fingerprints'])}):")
1833
2203
  for cat, pats in effective["workspace_fingerprints"].items():
1834
2204
  print(f" * {cat}: {len(pats)} pattern(s)")
1835
2205
  print(f"\nCategory Inference Rules ({len(effective['category_rules'])}):")
@@ -1944,33 +2314,636 @@ class SkillVault:
1944
2314
 
1945
2315
  return 0
1946
2316
 
1947
- def search(self, query):
1948
- """Search archived skills."""
1949
- q = query.lower()
1950
- manifest = self.load_manifest()
1951
- results = []
2317
+ def search(self, query, category=None, limit=10, as_json=False):
2318
+ """Search archived skills using pre-built BM25 index with substring fallback."""
2319
+ index_data = skill_router.load_or_build_index(
2320
+ archive_dir=self.archive_dir,
2321
+ base_dir=self.base_dir,
2322
+ resolve_path_fn=self.resolve_portable_path,
2323
+ )
2324
+ results = skill_router.search_index(
2325
+ index_data=index_data,
2326
+ query=query,
2327
+ category=category,
2328
+ limit=limit,
2329
+ )
1952
2330
 
1953
- for item in manifest:
1954
- name = item["name"]
1955
- cat = item.get("category", "General & Utility Skills")
1956
- archived_path = self.resolve_portable_path(item["archived_path"])
1957
- skill_md = archived_path / "SKILL.md"
1958
- desc = self.parse_skill_description(skill_md)
2331
+ # Fallback substring search when query is a partial fragment not captured by tokenization
2332
+ if not results and query.strip():
2333
+ q = query.strip().lower()
2334
+ for item in self.load_manifest():
2335
+ name = item["name"]
2336
+ cat = item.get("category", "General & Utility Skills")
2337
+ if category and cat.lower() != category.strip().lower():
2338
+ continue
2339
+ archived_path = self.resolve_portable_path(item["archived_path"])
2340
+ desc = self.parse_skill_description(archived_path / "SKILL.md")
2341
+ if q in name.lower() or q in desc.lower() or q in cat.lower():
2342
+ results.append({
2343
+ "name": name,
2344
+ "category": cat,
2345
+ "score": 1.0,
2346
+ "description": desc,
2347
+ "resolved_path": str(archived_path),
2348
+ })
2349
+ results = results[:limit]
1959
2350
 
1960
- if q in name.lower() or q in desc.lower() or q in cat.lower():
1961
- results.append((name, cat, desc, str(archived_path)))
2351
+ if as_json:
2352
+ print(json.dumps(results, indent=2, ensure_ascii=False))
2353
+ return
1962
2354
 
1963
2355
  if not results:
1964
2356
  print(f"No archived skills matched '{query}'.")
1965
2357
  return
1966
2358
 
1967
2359
  print(f"Found {len(results)} matching skill(s):\n")
1968
- for name, cat, desc, path_str in results:
1969
- print(f"* {name} [{cat}]")
2360
+ for r in results:
2361
+ path_str = r.get("resolved_path") or str(self.resolve_portable_path(r.get("archived_path", "")))
2362
+ desc = r.get("description", "")
2363
+ print(f"* {r['name']} [{r['category']}] (score: {r['score']})")
1970
2364
  desc_snippet = desc[:130] + "..." if len(desc) > 130 else desc
1971
2365
  print(f" Description: {desc_snippet}")
1972
2366
  print(f" Path: {path_str}\n")
1973
2367
 
2368
+ # --- JIT Router Debugging, Deduplication, Telemetry & Setup ---
2369
+
2370
+ def route(self, prompt, workspace_path=None, mode=None, as_json=False):
2371
+ """Dry-run the JIT skill router against a prompt and inspect scores, tiers, and tokens."""
2372
+ index_data = skill_router.load_or_build_index(
2373
+ archive_dir=self.archive_dir,
2374
+ base_dir=self.base_dir,
2375
+ resolve_path_fn=self.resolve_portable_path,
2376
+ )
2377
+ cfg = dict(self.load_config().get("routing", {}))
2378
+ if mode:
2379
+ cfg["mode"] = mode
2380
+
2381
+ ws_cats = []
2382
+ ws_target = Path(workspace_path).resolve() if workspace_path else Path.cwd().resolve()
2383
+ if ws_target.exists():
2384
+ ws_cats = sorted(self.detect_workspace_categories(ws_target).keys())
2385
+
2386
+ result = skill_router.route_prompt(
2387
+ index_data=index_data,
2388
+ prompt=prompt,
2389
+ archive_dir=self.archive_dir,
2390
+ base_dir=self.base_dir,
2391
+ workspace_categories=ws_cats,
2392
+ routing_config=cfg,
2393
+ )
2394
+
2395
+ if as_json:
2396
+ payload = {
2397
+ "prompt": prompt,
2398
+ "mode": cfg.get("mode", "hybrid"),
2399
+ "workspace_categories": ws_cats,
2400
+ "ambiguous": result["ambiguous"],
2401
+ "estimated_tokens": result["estimated_tokens"],
2402
+ "inline": [
2403
+ {
2404
+ "name": i["name"],
2405
+ "category": i["category"],
2406
+ "score": i["score"],
2407
+ "matched_terms": i.get("matched_terms", []),
2408
+ "truncated": i.get("truncated", False),
2409
+ }
2410
+ for i in result["inline"]
2411
+ ],
2412
+ "pointers": [
2413
+ {
2414
+ "name": p["name"],
2415
+ "category": p["category"],
2416
+ "score": p["score"],
2417
+ "matched_terms": p.get("matched_terms", []),
2418
+ }
2419
+ for p in result["pointers"]
2420
+ ],
2421
+ "top_candidates": [
2422
+ {
2423
+ "name": c["name"],
2424
+ "category": c["category"],
2425
+ "score": c["score"],
2426
+ "matched_terms": c.get("matched_terms", []),
2427
+ }
2428
+ for c in result.get("candidates", [])[:8]
2429
+ ],
2430
+ }
2431
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
2432
+ return 0
2433
+
2434
+ print("==================================================")
2435
+ print(" SKILL VAULT ROUTE DIAGNOSTIC")
2436
+ print(f" Prompt: {prompt}")
2437
+ print(f" Mode: {cfg.get('mode', 'hybrid')}")
2438
+ print(f" Workspace: {', '.join(ws_cats) if ws_cats else '(none detected)'}")
2439
+ print(f" Ambiguous: {result['ambiguous']}")
2440
+ print(f" Est Tokens:{result['estimated_tokens']}")
2441
+ print("==================================================\n")
2442
+
2443
+ if result["inline"]:
2444
+ print(f"INLINE ({len(result['inline'])}):")
2445
+ for i in result["inline"]:
2446
+ terms = ", ".join(i.get("matched_terms", []))
2447
+ trunc = " [TRUNCATED]" if i.get("truncated") else ""
2448
+ print(f" * {i['name']} [{i['category']}] score={i['score']} terms=[{terms}]{trunc}")
2449
+ else:
2450
+ print("INLINE: (none)")
2451
+
2452
+ if result["pointers"]:
2453
+ print(f"\nPOINTERS ({len(result['pointers'])}):")
2454
+ for p in result["pointers"]:
2455
+ terms = ", ".join(p.get("matched_terms", []))
2456
+ print(f" * {p['name']} [{p['category']}] score={p['score']} terms=[{terms}]")
2457
+ else:
2458
+ print("\nPOINTERS: (none)")
2459
+
2460
+ top_cands = result.get("candidates", [])[:8]
2461
+ if top_cands:
2462
+ print(f"\nTop Ranked Candidates:")
2463
+ for c in top_cands:
2464
+ terms = ", ".join(c.get("matched_terms", []))
2465
+ print(f" - {c['name']} [{c['category']}] score={c['score']} terms=[{terms}]")
2466
+ print("")
2467
+ return 0
2468
+
2469
+ def dedupe(self, dry_run=False):
2470
+ """Consolidate hyphen/underscore duplicate skills in L2, preserving the newest version."""
2471
+ manifest = self.load_manifest()
2472
+ groups = {}
2473
+ for item in manifest:
2474
+ ckey = skill_router.canonicalize_skill_name(item.get("name", ""))
2475
+ groups.setdefault(ckey, []).append(item)
2476
+
2477
+ dup_groups = {k: v for k, v in groups.items() if len(v) > 1}
2478
+ print("==================================================")
2479
+ print(" SKILL VAULT DUPLICATE CHECK")
2480
+ print(f" Total Manifest Entries: {len(manifest)}")
2481
+ print(f" Duplicate Groups Found: {len(dup_groups)}")
2482
+ print("==================================================\n")
2483
+
2484
+ if not dup_groups:
2485
+ print("[OK] No duplicate canonical skill names found in vault.")
2486
+ return 0
2487
+
2488
+ to_remove = []
2489
+ kept_entries = {}
2490
+ for ckey, items in sorted(groups.items()):
2491
+ if len(items) == 1:
2492
+ kept_entries[items[0]["name"]] = items[0]
2493
+ continue
2494
+
2495
+ winner = items[0]
2496
+ winner_dir = self.resolve_portable_path(winner.get("archived_path", ""))
2497
+ for cand in items[1:]:
2498
+ cand_dir = self.resolve_portable_path(cand.get("archived_path", ""))
2499
+ rec = compare_skill_recency(cand_dir, winner_dir)
2500
+ cand_hyphen = "-" in cand["name"] and "_" not in cand["name"]
2501
+ win_hyphen = "-" in winner["name"] and "_" not in winner["name"]
2502
+ if rec > 0 or (rec == 0 and cand_hyphen and not win_hyphen) or (rec == 0 and cand_hyphen == win_hyphen and cand["name"] < winner["name"]):
2503
+ winner = cand
2504
+ winner_dir = cand_dir
2505
+
2506
+ kept_entries[winner["name"]] = winner
2507
+ print(f"Group '{ckey}':")
2508
+ print(f" [KEEP] {winner['name']} ({winner.get('category', 'General & Utility Skills')}) -> {winner_dir}")
2509
+ for cand in items:
2510
+ if cand["name"] != winner["name"]:
2511
+ cand_dir = self.resolve_portable_path(cand.get("archived_path", ""))
2512
+ print(f" [REMOVE] {cand['name']} ({cand.get('category', 'General & Utility Skills')}) -> {cand_dir}")
2513
+ to_remove.append((cand, cand_dir, winner_dir))
2514
+
2515
+ if dry_run:
2516
+ print(f"\n[Dry Run] Would consolidate {len(to_remove)} duplicate skill(s). No files were modified.")
2517
+ return 0
2518
+
2519
+ for cand, cand_dir, winner_dir in to_remove:
2520
+ if cand_dir.exists() and cand_dir.resolve() != winner_dir.resolve():
2521
+ shutil.rmtree(cand_dir)
2522
+ print(f"[Removed] {cand_dir}")
2523
+
2524
+ self.save_manifest(list(kept_entries.values()))
2525
+ self.reindex()
2526
+ print(f"\n[OK] Consolidated {len(to_remove)} duplicate skill(s).")
2527
+ return 0
2528
+
2529
+ def stats(self, limit=100, as_json=False):
2530
+ """Summarize local background routing telemetry from routing_log.jsonl."""
2531
+ log_file = self.archive_dir / ".state" / "routing_log.jsonl"
2532
+ records = []
2533
+ if log_file.exists():
2534
+ try:
2535
+ lines = [ln for ln in log_file.read_text(encoding="utf-8", errors="replace").splitlines() if ln.strip()]
2536
+ if limit and limit > 0:
2537
+ lines = lines[-limit:]
2538
+ for ln in lines:
2539
+ try:
2540
+ records.append(json.loads(ln))
2541
+ except Exception:
2542
+ pass
2543
+ except OSError:
2544
+ pass
2545
+
2546
+ total = len(records)
2547
+ short_circuited = sum(1 for r in records if r.get("short_circuited"))
2548
+ zero_token = sum(1 for r in records if int(r.get("estimated_tokens", 0)) == 0)
2549
+ matched = [r for r in records if int(r.get("estimated_tokens", 0)) > 0]
2550
+ latencies = sorted(float(r.get("latency_ms", 0.0)) for r in records)
2551
+ avg_latency = round(sum(latencies) / total, 2) if total else 0.0
2552
+ p95_idx = min(len(latencies) - 1, int(len(latencies) * 0.95)) if latencies else 0
2553
+ p95_latency = round(latencies[p95_idx], 2) if latencies else 0.0
2554
+ avg_tokens_matched = round(sum(int(r.get("estimated_tokens", 0)) for r in matched) / len(matched), 1) if matched else 0.0
2555
+ zero_pct = round((zero_token / total) * 100.0, 1) if total else 0.0
2556
+
2557
+ skill_counts = {}
2558
+ for r in records:
2559
+ for s in r.get("matched_inline", []) + r.get("matched_pointers", []):
2560
+ skill_counts[s] = skill_counts.get(s, 0) + 1
2561
+ top_skills = sorted(skill_counts.items(), key=lambda kv: (-kv[1], kv[0]))[:10]
2562
+
2563
+ summary = {
2564
+ "total_turns": total,
2565
+ "short_circuited_turns": short_circuited,
2566
+ "zero_token_turns": zero_token,
2567
+ "zero_token_pct": zero_pct,
2568
+ "matched_turns": len(matched),
2569
+ "avg_tokens_per_matched_turn": avg_tokens_matched,
2570
+ "avg_latency_ms": avg_latency,
2571
+ "p95_latency_ms": p95_latency,
2572
+ "top_skills": [{"name": k, "count": v} for k, v in top_skills],
2573
+ }
2574
+
2575
+ if as_json:
2576
+ print(json.dumps(summary, indent=2))
2577
+ return 0
2578
+
2579
+ print("==================================================")
2580
+ print(" SKILL VAULT ROUTING STATS")
2581
+ print(f" Log File: {log_file}")
2582
+ print("==================================================\n")
2583
+ if total == 0:
2584
+ print("No routing telemetry recorded yet.")
2585
+ return 0
2586
+ print(f" * Total Routed Turns: {total} (short-circuited: {short_circuited})")
2587
+ print(f" * Zero-Token Turns: {zero_token} ({zero_pct}%)")
2588
+ print(f" * Matched Turns: {len(matched)} (avg ~{avg_tokens_matched} tokens)")
2589
+ print(f" * Latency (avg / p95): {avg_latency} ms / {p95_latency} ms")
2590
+ if top_skills:
2591
+ print("\n Top Matched Skills:")
2592
+ for name, cnt in top_skills:
2593
+ print(f" - {name}: {cnt}")
2594
+ print("")
2595
+ return 0
2596
+
2597
+ def _merge_json_config_file(self, cfg_path, mutator_fn, dry_run=False):
2598
+ cfg_path = Path(cfg_path)
2599
+ existing = {}
2600
+ if cfg_path.exists():
2601
+ try:
2602
+ existing = json.loads(cfg_path.read_text(encoding="utf-8", errors="replace"))
2603
+ if not isinstance(existing, dict):
2604
+ existing = {}
2605
+ except Exception:
2606
+ existing = {}
2607
+
2608
+ updated = mutator_fn(json.loads(json.dumps(existing)))
2609
+ if dry_run:
2610
+ return updated
2611
+
2612
+ cfg_path.parent.mkdir(parents=True, exist_ok=True)
2613
+ bak_path = cfg_path.with_suffix(cfg_path.suffix + ".bak")
2614
+ if cfg_path.exists() and not bak_path.exists():
2615
+ shutil.copy2(cfg_path, bak_path)
2616
+ tmp = cfg_path.with_name(f".{cfg_path.name}.{os.getpid()}.tmp")
2617
+ tmp.write_text(json.dumps(updated, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
2618
+ os.replace(tmp, cfg_path)
2619
+ return updated
2620
+
2621
+ @staticmethod
2622
+ def _build_hook_command(py_exe, script_ref, harness, event_name, vault_base_dir):
2623
+ """Build a cmd /c and sh -c safe command string avoiding Windows >2 quote stripping."""
2624
+ py_str = str(py_exe)
2625
+ base_str = str(vault_base_dir)
2626
+ py_token = f'"{py_str}"' if (" " in py_str and not py_str.startswith('"')) else py_str
2627
+ script_token = f'"{script_ref}"' if (" " in str(script_ref) and '"' not in py_token) else str(script_ref)
2628
+ # Never introduce a second quoted pair on Windows cmd /c; vault_link.json carries baseDir when paths have spaces
2629
+ if " " in base_str or '"' in py_token or '"' in script_token:
2630
+ base_flag = ""
2631
+ else:
2632
+ base_flag = f" --base-dir {base_str}"
2633
+ return f"{py_token} {script_token} --harness {harness} --event {event_name}{base_flag}"
2634
+
2635
+ def setup(
2636
+ self,
2637
+ agent="auto",
2638
+ scope="global",
2639
+ dry_run=False,
2640
+ migrate_archive=False,
2641
+ target_dir=None,
2642
+ python_exe=None,
2643
+ ):
2644
+ """Install background hooks, read-only MCP server, and plugin bundle for coding agents."""
2645
+ src_scripts_dir = Path(__file__).resolve().parent
2646
+ required_scripts = ["skill_vault.py", "skill_router.py", "hook_runner.py", "mcp_server.py"]
2647
+ for sname in required_scripts:
2648
+ if not (src_scripts_dir / sname).exists():
2649
+ print(f"[Error] Required script missing: {src_scripts_dir / sname}")
2650
+ return 1
2651
+
2652
+ src_skill_md = None
2653
+ for cand_md in [
2654
+ src_scripts_dir.parent / "SKILL.md",
2655
+ src_scripts_dir.parent / "skills" / "skill-vault" / "SKILL.md",
2656
+ ]:
2657
+ if cand_md.exists():
2658
+ src_skill_md = cand_md
2659
+ break
2660
+
2661
+ py = str(python_exe or sys.executable)
2662
+ home = Path.home()
2663
+ cwd = Path.cwd().resolve()
2664
+
2665
+ if agent == "auto":
2666
+ agents = []
2667
+ if scope == "workspace":
2668
+ if (cwd / ".agents").exists():
2669
+ agents.append("antigravity")
2670
+ if (cwd / ".claude").exists():
2671
+ agents.append("claude")
2672
+ if (cwd / ".gemini").exists():
2673
+ agents.append("gemini-cli")
2674
+ if (cwd / ".cursor").exists():
2675
+ agents.append("cursor")
2676
+ else:
2677
+ if (home / ".gemini" / "config").exists():
2678
+ agents.append("antigravity")
2679
+ if (home / ".claude").exists():
2680
+ agents.append("claude")
2681
+ if (home / ".gemini" / "settings.json").exists():
2682
+ agents.append("gemini-cli")
2683
+ if (home / ".cursor").exists():
2684
+ agents.append("cursor")
2685
+ if not agents:
2686
+ agents = ["antigravity"]
2687
+ else:
2688
+ agents = [agent]
2689
+
2690
+ # Determine canonical vault base directory per scope and target agent
2691
+ home_cfg = home / ".gemini" / "config"
2692
+ legacy_sv = home_cfg / "skills" / "skill-vault"
2693
+ legacy_arch = legacy_sv / "skill_archive"
2694
+ canon_arch = home_cfg / "skill_archive"
2695
+ primary_agent = agents[0]
2696
+
2697
+ if self._explicit_base_dir:
2698
+ vault_base_dir = self.base_dir
2699
+ elif scope == "workspace":
2700
+ ws_existing = [
2701
+ cwd / ".agents",
2702
+ cwd / ".claude",
2703
+ cwd / ".gemini",
2704
+ cwd / ".cursor",
2705
+ cwd,
2706
+ ]
2707
+ found_ws = next((c for c in ws_existing if (c / "skill_archive").exists()), None)
2708
+ if found_ws is not None:
2709
+ vault_base_dir = found_ws
2710
+ elif primary_agent == "claude":
2711
+ vault_base_dir = cwd / ".claude"
2712
+ elif primary_agent == "gemini-cli":
2713
+ vault_base_dir = cwd / ".gemini"
2714
+ elif primary_agent == "cursor":
2715
+ vault_base_dir = (cwd / ".agents") if (cwd / ".agents").exists() else (cwd / ".cursor")
2716
+ else:
2717
+ vault_base_dir = cwd / ".agents"
2718
+ else:
2719
+ if migrate_archive and legacy_arch.exists() and not canon_arch.exists():
2720
+ vault_base_dir = home_cfg
2721
+ else:
2722
+ global_existing = [
2723
+ home_cfg,
2724
+ home / ".claude",
2725
+ home / ".agents",
2726
+ home / ".gemini",
2727
+ home / ".cursor",
2728
+ legacy_sv,
2729
+ ]
2730
+ found_global = next((c for c in global_existing if (c / "skill_archive").exists()), None)
2731
+ if found_global is not None:
2732
+ vault_base_dir = found_global
2733
+ elif primary_agent == "claude":
2734
+ vault_base_dir = home / ".claude"
2735
+ elif primary_agent == "gemini-cli":
2736
+ vault_base_dir = home / ".gemini"
2737
+ elif primary_agent == "cursor":
2738
+ vault_base_dir = home / ".cursor"
2739
+ else:
2740
+ vault_base_dir = home_cfg
2741
+
2742
+ print("==================================================")
2743
+ print(" SKILL VAULT ORCHESTRATION SETUP")
2744
+ print(f" Target Agent(s): {', '.join(agents)}")
2745
+ print(f" Scope: {scope}")
2746
+ print(f" Vault Base: {vault_base_dir}")
2747
+ print(f" Python Runtime: {py}")
2748
+ print("==================================================\n")
2749
+
2750
+ # Handle archive migration if requested
2751
+ will_migrate = (
2752
+ migrate_archive
2753
+ and scope == "global"
2754
+ and not self._explicit_base_dir
2755
+ and legacy_arch.exists()
2756
+ and not canon_arch.exists()
2757
+ )
2758
+ if will_migrate:
2759
+ print(f"[Migration Plan] {legacy_arch} -> {canon_arch}")
2760
+ print(f" Verify integrity before removing legacy {legacy_sv}\n")
2761
+ if not dry_run:
2762
+ src_count = len(SkillVault(base_dir=str(legacy_sv)).get_archived_skill_folders())
2763
+ shutil.copytree(legacy_arch, canon_arch, dirs_exist_ok=True)
2764
+ migrated_mgr = SkillVault(base_dir=str(home_cfg))
2765
+ if migrated_mgr.verify(fix=False) != 0:
2766
+ print("[Error] Archive migration verification failed! Legacy archive preserved untouched.")
2767
+ return 1
2768
+ dst_count = len(migrated_mgr.get_archived_skill_folders())
2769
+ if dst_count < src_count:
2770
+ print(f"[Error] Migrated skill count ({dst_count}) < source ({src_count}). Legacy archive preserved untouched.")
2771
+ return 1
2772
+ if legacy_sv.exists():
2773
+ shutil.rmtree(legacy_sv)
2774
+ print(f"[Migrated] Verified {dst_count} skill(s) at {canon_arch} and removed legacy {legacy_sv}\n")
2775
+
2776
+ # Ensure vault archive exists
2777
+ if not dry_run:
2778
+ vault_base_dir.mkdir(parents=True, exist_ok=True)
2779
+ vault_mgr = SkillVault(base_dir=str(vault_base_dir))
2780
+ if not dry_run and not vault_mgr.archive_dir.exists():
2781
+ vault_mgr.init()
2782
+
2783
+ for target_agent in agents:
2784
+ if target_agent == "antigravity":
2785
+ if target_dir:
2786
+ td = Path(target_dir).resolve()
2787
+ if td.name == "skill-vault":
2788
+ plugin_dir = td
2789
+ elif td.name == "plugins":
2790
+ plugin_dir = td / "skill-vault"
2791
+ else:
2792
+ plugin_dir = td / "plugins" / "skill-vault"
2793
+ elif scope == "workspace":
2794
+ plugin_dir = cwd / ".agents" / "plugins" / "skill-vault"
2795
+ else:
2796
+ plugin_dir = home_cfg / "plugins" / "skill-vault"
2797
+
2798
+ hooks_payload = {
2799
+ "skill-vault-session-sync": {
2800
+ "SessionStart": [
2801
+ {
2802
+ "type": "command",
2803
+ "command": self._build_hook_command(
2804
+ py, "scripts/hook_runner.py", "antigravity", "SessionStart", vault_base_dir
2805
+ ),
2806
+ "timeout": 30,
2807
+ }
2808
+ ]
2809
+ },
2810
+ "skill-vault-jit-router": {
2811
+ "PreInvocation": [
2812
+ {
2813
+ "type": "command",
2814
+ "command": self._build_hook_command(
2815
+ py, "scripts/hook_runner.py", "antigravity", "PreInvocation", vault_base_dir
2816
+ ),
2817
+ "timeout": 10,
2818
+ }
2819
+ ]
2820
+ },
2821
+ }
2822
+ mcp_payload = {
2823
+ "mcpServers": {
2824
+ "skill-vault": {
2825
+ "command": py,
2826
+ "type": "stdio",
2827
+ "args": ["scripts/mcp_server.py"],
2828
+ "env": {"SKILL_VAULT_BASE": str(vault_base_dir)},
2829
+ }
2830
+ }
2831
+ }
2832
+ plugin_meta = {
2833
+ "name": "skill-vault",
2834
+ "displayName": "Skill Vault",
2835
+ "version": "2.0.0",
2836
+ "description": "Automatic background skill router, cold-storage archive, and read-only JIT MCP server.",
2837
+ "author": "jcorpac",
2838
+ "license": "MIT",
2839
+ }
2840
+
2841
+ print(f"[Antigravity Plugin] Target: {plugin_dir}")
2842
+ if dry_run:
2843
+ print(f" * Would install scripts: {', '.join(required_scripts)}")
2844
+ print(" * Would write plugin.json, hooks.json, mcp_config.json, vault_link.json, skills/skill-vault/SKILL.md")
2845
+ else:
2846
+ scripts_dest = plugin_dir / "scripts"
2847
+ scripts_dest.mkdir(parents=True, exist_ok=True)
2848
+ for sname in required_scripts:
2849
+ shutil.copy2(src_scripts_dir / sname, scripts_dest / sname)
2850
+
2851
+ if src_skill_md and src_skill_md.exists():
2852
+ dest_md_dir = plugin_dir / "skills" / "skill-vault"
2853
+ dest_md_dir.mkdir(parents=True, exist_ok=True)
2854
+ shutil.copy2(src_skill_md, dest_md_dir / "SKILL.md")
2855
+
2856
+ (plugin_dir / "plugin.json").write_text(json.dumps(plugin_meta, indent=2) + "\n", encoding="utf-8")
2857
+ (plugin_dir / "hooks.json").write_text(json.dumps(hooks_payload, indent=2) + "\n", encoding="utf-8")
2858
+ (plugin_dir / "mcp_config.json").write_text(json.dumps(mcp_payload, indent=2) + "\n", encoding="utf-8")
2859
+ (plugin_dir / "vault_link.json").write_text(json.dumps({"baseDir": str(vault_base_dir)}, indent=2) + "\n", encoding="utf-8")
2860
+ print(f" [OK] Installed Antigravity plugin bundle to {plugin_dir}")
2861
+
2862
+ elif target_agent in ("claude", "gemini-cli", "cursor"):
2863
+ # Stage permanent runtime scripts inside archive/.runtime so npx/temp paths never break
2864
+ runtime_dir = vault_mgr.archive_dir / ".runtime" / "scripts"
2865
+ hook_script = runtime_dir / "hook_runner.py"
2866
+ mcp_script = runtime_dir / "mcp_server.py"
2867
+ if not dry_run:
2868
+ runtime_dir.mkdir(parents=True, exist_ok=True)
2869
+ for sname in required_scripts:
2870
+ shutil.copy2(src_scripts_dir / sname, runtime_dir / sname)
2871
+ (runtime_dir.parent / "vault_link.json").write_text(
2872
+ json.dumps({"baseDir": str(vault_base_dir)}, indent=2) + "\n", encoding="utf-8"
2873
+ )
2874
+
2875
+ if target_agent == "claude":
2876
+ cfg_file = Path(target_dir).resolve() if target_dir else (
2877
+ (cwd / ".claude" / "settings.json") if scope == "workspace" else (home / ".claude" / "settings.json")
2878
+ )
2879
+ evt_name = "UserPromptSubmit"
2880
+ elif target_agent == "gemini-cli":
2881
+ cfg_file = Path(target_dir).resolve() if target_dir else (
2882
+ (cwd / ".gemini" / "settings.json") if scope == "workspace" else (home / ".gemini" / "settings.json")
2883
+ )
2884
+ evt_name = "BeforeAgent"
2885
+ else:
2886
+ cfg_file = Path(target_dir).resolve() if target_dir else (
2887
+ (cwd / ".cursor" / "mcp.json") if scope == "workspace" else (home / ".cursor" / "mcp.json")
2888
+ )
2889
+ evt_name = None
2890
+
2891
+ def _mutate(cfg):
2892
+ mcp_servers = cfg.setdefault("mcpServers", {})
2893
+ mcp_servers["skill-vault"] = {
2894
+ "command": py,
2895
+ "args": [str(mcp_script), "--base-dir", str(vault_base_dir)],
2896
+ "env": {"SKILL_VAULT_BASE": str(vault_base_dir)},
2897
+ }
2898
+ if evt_name:
2899
+ hooks = cfg.setdefault("hooks", {})
2900
+ for hook_ev in ("SessionStart", evt_name):
2901
+ groups = [
2902
+ g for g in hooks.get(hook_ev, [])
2903
+ if not any(
2904
+ "hook_runner.py" in str(h.get("command", "")) or "skill-vault" in str(h.get("command", ""))
2905
+ for h in (g.get("hooks", []) if isinstance(g, dict) else [])
2906
+ )
2907
+ ]
2908
+ groups.append({
2909
+ "matcher": "",
2910
+ "hooks": [{
2911
+ "type": "command",
2912
+ "command": self._build_hook_command(
2913
+ py, str(hook_script), target_agent, hook_ev, vault_base_dir
2914
+ ),
2915
+ }],
2916
+ })
2917
+ hooks[hook_ev] = groups
2918
+ return cfg
2919
+
2920
+ print(f"[{target_agent}] Config: {cfg_file}")
2921
+ self._merge_json_config_file(cfg_file, _mutate, dry_run=dry_run)
2922
+ if dry_run:
2923
+ print(f" * Would merge hooks/MCP into {cfg_file}")
2924
+ else:
2925
+ print(f" [OK] Updated {cfg_file}")
2926
+ else:
2927
+ print(f"[Error] Unsupported agent '{target_agent}'.")
2928
+ return 1
2929
+
2930
+ if dry_run:
2931
+ print("\n[Dry Run] Setup preview complete. No files were modified.")
2932
+ return 0
2933
+
2934
+ # Enable compact router prompt & rebuild search_index.json
2935
+ raw_cfg = vault_mgr._load_raw_config()
2936
+ routing_map = dict(raw_cfg.get("routing", {}))
2937
+ routing_map["compact_router_prompt"] = True
2938
+ raw_cfg["routing"] = routing_map
2939
+ vault_mgr.save_config(raw_cfg)
2940
+ vault_mgr.reindex()
2941
+ if "antigravity" in agents:
2942
+ vault_mgr.sync_router_md(target_skill_md=plugin_dir / "skills" / "skill-vault" / "SKILL.md", force=True)
2943
+
2944
+ print("\n[OK] Skill Vault background orchestration is configured and ready.")
2945
+ return 0
2946
+
1974
2947
  # --- Project Import Engine ---
1975
2948
 
1976
2949
  def resolve_vault_archive_dir(self, vault_arg=None):
@@ -2001,13 +2974,15 @@ class SkillVault:
2001
2974
  ):
2002
2975
  return self.archive_dir
2003
2976
 
2004
- # Check standard global locations
2977
+ # Check standard global locations (canonical ~/.gemini/config/skill_archive first)
2005
2978
  candidates = [
2979
+ Path.home() / ".gemini" / "config" / "skill_archive",
2006
2980
  Path.home() / ".gemini" / "config" / "skills" / "skill-vault" / "skill_archive",
2007
2981
  Path.home() / ".gemini" / "config" / "skills" / ".skill_archive",
2008
- Path.home() / ".gemini" / "config" / "skill_archive",
2009
2982
  Path.home() / ".agents" / "skill_archive",
2010
2983
  Path.home() / ".claude" / "skill_archive",
2984
+ Path.home() / ".gemini" / "skill_archive",
2985
+ Path.home() / ".cursor" / "skill_archive",
2011
2986
  ]
2012
2987
  for cand in candidates:
2013
2988
  if cand.exists() and (
@@ -2228,9 +3203,11 @@ def main():
2228
3203
  p_arch.add_argument("--force", action="store_true", help="Force overwrite in archive regardless of recency")
2229
3204
 
2230
3205
  # Recategorize
2231
- p_rec = subparsers.add_parser("recategorize", help="Recategorize an archived skill in metadata")
2232
- p_rec.add_argument("name", help="Skill name")
2233
- p_rec.add_argument("category", help="New category name")
3206
+ p_rec = subparsers.add_parser("recategorize", help="Recategorize an archived skill in metadata or auto-recategorize General skills")
3207
+ p_rec.add_argument("name", nargs="?", help="Skill name")
3208
+ p_rec.add_argument("category", nargs="?", help="New category name")
3209
+ p_rec.add_argument("--auto", action="store_true", help="Auto-recategorize skills in 'General & Utility Skills'")
3210
+ p_rec.add_argument("--dry-run", action="store_true", help="Preview auto-recategorization without modifying manifest")
2234
3211
 
2235
3212
  # Restore
2236
3213
  p_rest = subparsers.add_parser("restore", help="Restore archived skills back to active availability")
@@ -2241,7 +3218,7 @@ def main():
2241
3218
  p_rest.add_argument("--force", action="store_true", help="Overwrite existing active directory")
2242
3219
 
2243
3220
  # Reindex
2244
- p_idx = subparsers.add_parser("reindex", help="Rebuild INDEX.md and sync manifest")
3221
+ p_idx = subparsers.add_parser("reindex", help="Rebuild INDEX.md, search_index.json, and sync manifest")
2245
3222
 
2246
3223
  # Verify / Integrity Check
2247
3224
  p_ver = subparsers.add_parser("verify", help="Verify archive integrity across disk, manifest, and index")
@@ -2249,7 +3226,48 @@ def main():
2249
3226
 
2250
3227
  # Search
2251
3228
  p_srch = subparsers.add_parser("search", help="Search archived skills by keyword, intent, or domain")
2252
- p_srch.add_argument("query", help="Keyword to search for")
3229
+ p_srch.add_argument("query", help="Keyword or natural-language query to search for")
3230
+ p_srch.add_argument("--category", help="Filter search results by category")
3231
+ p_srch.add_argument("--limit", type=int, default=10, help="Maximum number of results to show")
3232
+ p_srch.add_argument("--json", action="store_true", help="Output structured JSON")
3233
+
3234
+ # Route (dry-run JIT router debugger)
3235
+ p_route = subparsers.add_parser("route", help="Dry-run the background JIT skill router against a prompt")
3236
+ p_route.add_argument("prompt", help="User prompt to evaluate")
3237
+ p_route.add_argument("--workspace", help="Optional workspace path for soft stack tie-breaking")
3238
+ p_route.add_argument("--mode", choices=["hybrid", "inline", "pointer"], help="Override routing mode")
3239
+ p_route.add_argument("--json", action="store_true", help="Output structured JSON")
3240
+
3241
+ # Dedupe
3242
+ p_dedupe = subparsers.add_parser("dedupe", help="Consolidate hyphen/underscore duplicate skills in archive")
3243
+ p_dedupe.add_argument("--dry-run", action="store_true", help="Preview duplicates without deleting files")
3244
+
3245
+ # Stats
3246
+ p_stats = subparsers.add_parser("stats", help="Show local background routing telemetry summary")
3247
+ p_stats.add_argument("--limit", type=int, default=100, help="Inspect most recent N turns")
3248
+ p_stats.add_argument("--json", action="store_true", help="Output structured JSON")
3249
+
3250
+ # Setup
3251
+ p_setup = subparsers.add_parser("setup", help="Install background hooks, MCP server, and plugin wiring")
3252
+ p_setup.add_argument(
3253
+ "--agent",
3254
+ choices=["auto", "antigravity", "claude", "gemini-cli", "cursor"],
3255
+ default="auto",
3256
+ help="Target agent harness (default: auto)",
3257
+ )
3258
+ p_setup.add_argument(
3259
+ "--scope",
3260
+ choices=["global", "workspace"],
3261
+ default="global",
3262
+ help="Install globally or inside current workspace",
3263
+ )
3264
+ p_setup.add_argument("--dry-run", action="store_true", help="Preview installation plan without modifying files")
3265
+ p_setup.add_argument(
3266
+ "--migrate-archive",
3267
+ action="store_true",
3268
+ help="Safely migrate legacy ~/.gemini/config/skills/skill-vault/skill_archive to ~/.gemini/config/skill_archive",
3269
+ )
3270
+ p_setup.add_argument("--target-dir", help="Explicit target plugin directory or config file path")
2253
3271
 
2254
3272
  # Sync
2255
3273
  p_sync = subparsers.add_parser("sync", help="Scan plugins and active skills, ingest new/updated skills, and prune non-core skills")
@@ -2277,6 +3295,7 @@ def main():
2277
3295
  p_cfg.add_argument("--remove-core", nargs="+", metavar="SKILL", help="Remove one or more skills from protected core skills")
2278
3296
  p_cfg.add_argument("--add-fingerprint", nargs=2, action="append", metavar=("CATEGORY", "PATTERN"), help="Add a workspace file/glob fingerprint for a category")
2279
3297
  p_cfg.add_argument("--add-category-rule", nargs=2, action="append", metavar=("CATEGORY", "KEYWORD"), help="Add an inference keyword rule for a category")
3298
+ p_cfg.add_argument("--set-routing", nargs=2, action="append", metavar=("KEY", "VALUE"), help="Set a routing configuration option (e.g. mode hybrid)")
2280
3299
  p_cfg.add_argument("--sync-prompt", action="store_true", help="Synchronize SKILL.md router description with archived categories")
2281
3300
 
2282
3301
  # Uninstall / Eject
@@ -2326,7 +3345,7 @@ def main():
2326
3345
  elif args.command == "archive":
2327
3346
  mgr.archive(name=args.name, pattern=args.pattern, category=args.category, keep_active=args.keep_active, force=args.force)
2328
3347
  elif args.command == "recategorize":
2329
- mgr.recategorize(name=args.name, new_category=args.category)
3348
+ sys.exit(mgr.recategorize(name=args.name, new_category=args.category, auto=args.auto, dry_run=args.dry_run))
2330
3349
  elif args.command == "restore":
2331
3350
  mgr.restore(name=args.name, pattern=args.pattern, category=args.category, restore_all=args.all, force=args.force)
2332
3351
  elif args.command == "reindex":
@@ -2334,7 +3353,23 @@ def main():
2334
3353
  elif args.command == "verify":
2335
3354
  sys.exit(mgr.verify(fix=args.fix))
2336
3355
  elif args.command == "search":
2337
- mgr.search(query=args.query)
3356
+ mgr.search(query=args.query, category=args.category, limit=args.limit, as_json=args.json)
3357
+ elif args.command == "route":
3358
+ sys.exit(mgr.route(prompt=args.prompt, workspace_path=args.workspace, mode=args.mode, as_json=args.json))
3359
+ elif args.command == "dedupe":
3360
+ sys.exit(mgr.dedupe(dry_run=args.dry_run))
3361
+ elif args.command == "stats":
3362
+ sys.exit(mgr.stats(limit=args.limit, as_json=args.json))
3363
+ elif args.command == "setup":
3364
+ sys.exit(
3365
+ mgr.setup(
3366
+ agent=args.agent,
3367
+ scope=args.scope,
3368
+ dry_run=args.dry_run,
3369
+ migrate_archive=args.migrate_archive,
3370
+ target_dir=args.target_dir,
3371
+ )
3372
+ )
2338
3373
  elif args.command == "import":
2339
3374
  sys.exit(
2340
3375
  mgr.import_skills(
@@ -2356,6 +3391,7 @@ def main():
2356
3391
  remove_core=args.remove_core,
2357
3392
  add_fingerprint=args.add_fingerprint,
2358
3393
  add_category_rule=args.add_category_rule,
3394
+ set_routing=args.set_routing,
2359
3395
  sync_prompt=args.sync_prompt,
2360
3396
  )
2361
3397
  elif args.command in ("uninstall", "eject"):