@jcorpac/skill-vault 1.8.0 → 2.0.1

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,8 @@ strictly in backup_manifest.json and INDEX.md, keeping SKILL.md files pure and u
7
7
  """
8
8
 
9
9
  import argparse
10
+ from datetime import datetime
11
+ import fnmatch
10
12
  import hashlib
11
13
  import json
12
14
  import os
@@ -15,6 +17,12 @@ import re
15
17
  import shutil
16
18
  import sys
17
19
 
20
+ SCRIPT_DIR = Path(__file__).resolve().parent
21
+ if str(SCRIPT_DIR) not in sys.path:
22
+ sys.path.insert(0, str(SCRIPT_DIR))
23
+
24
+ import skill_router # noqa: E402
25
+
18
26
  # Default Core Foundation Skills that are protected from auto-archiving
19
27
  DEFAULT_CORE_SKILLS = {
20
28
  "skill-vault",
@@ -121,6 +129,15 @@ WORKSPACE_FINGERPRINTS = {
121
129
  "build.gradle.kts",
122
130
  "AndroidManifest.xml",
123
131
  ],
132
+ "Firebase": [
133
+ "firebase.json",
134
+ "firestore.rules",
135
+ ".firebaserc",
136
+ ],
137
+ "Robotics & MuJoCo": [
138
+ "*.urdf",
139
+ "*.mjcf",
140
+ ],
124
141
  }
125
142
 
126
143
  DEFAULT_WORKSPACE_FINGERPRINTS = WORKSPACE_FINGERPRINTS
@@ -128,10 +145,59 @@ DEFAULT_WORKSPACE_FINGERPRINTS = WORKSPACE_FINGERPRINTS
128
145
  # Default keyword rules for auto-categorizing skills across universal ecosystems
129
146
  DEFAULT_CATEGORY_RULES = {
130
147
  "Knowledge & Wiki Architecture": [
131
- "egm-",
132
148
  "wiki",
149
+ "knowledge base",
133
150
  "documentation architecture",
134
151
  ],
152
+ "Firebase": [
153
+ "firebase",
154
+ "firestore",
155
+ "crashlytics",
156
+ "remote config",
157
+ "app hosting",
158
+ "firebase auth",
159
+ ],
160
+ "Google Workspace": [
161
+ "gmail",
162
+ "gcalendar",
163
+ "gdocs",
164
+ "gdrive",
165
+ "gsheets",
166
+ "gslides",
167
+ "google workspace",
168
+ "google calendar",
169
+ "google docs",
170
+ "google sheets",
171
+ "google slides",
172
+ "google drive",
173
+ ],
174
+ "Robotics & MuJoCo": [
175
+ "mujoco",
176
+ "mjcf",
177
+ "urdf",
178
+ "robotics",
179
+ "kinematics",
180
+ "inverse kinematics",
181
+ "gripper",
182
+ "actuator",
183
+ ],
184
+ "Chrome DevTools & Web Performance": [
185
+ "chrome-devtools",
186
+ "chrome devtools",
187
+ "chrome-extension",
188
+ "chrome extension",
189
+ "memory leak",
190
+ "memory-leak",
191
+ "lcp",
192
+ "core web vitals",
193
+ "lighthouse",
194
+ ],
195
+ "Google Maps & Geo": [
196
+ "google-maps",
197
+ "google_maps",
198
+ "maps-platform",
199
+ "maps platform",
200
+ ],
135
201
  "Gemini API & AI Agents": [
136
202
  "gemini",
137
203
  "adk",
@@ -205,6 +271,13 @@ DEFAULT_CATEGORY_RULES = {
205
271
  "pubsub",
206
272
  "cloud storage",
207
273
  "cloud run",
274
+ "bigtable",
275
+ "gcloud",
276
+ "gcs",
277
+ "google-cloud",
278
+ "google_cloud",
279
+ "spark",
280
+ "lakehouse",
208
281
  ],
209
282
  "Testing, QA & Security": [
210
283
  "playwright",
@@ -315,6 +388,22 @@ def parse_version_tuple(ver_str):
315
388
  return None
316
389
 
317
390
 
391
+ def compare_version_tuples(ver_a, ver_b):
392
+ """Compare two version tuples with zero-padding. Returns 1, -1, or 0."""
393
+ if ver_a is None or ver_b is None:
394
+ return 0
395
+ ta = tuple(ver_a)
396
+ tb = tuple(ver_b)
397
+ max_len = max(len(ta), len(tb))
398
+ pa = ta + (0,) * (max_len - len(ta))
399
+ pb = tb + (0,) * (max_len - len(tb))
400
+ if pa > pb:
401
+ return 1
402
+ if pa < pb:
403
+ return -1
404
+ return 0
405
+
406
+
318
407
  def get_skill_metadata(skill_dir):
319
408
  """Extract parsed version and latest modification timestamp for a skill directory."""
320
409
  skill_dir = Path(skill_dir)
@@ -324,9 +413,12 @@ def get_skill_metadata(skill_dir):
324
413
  if skill_md.exists():
325
414
  try:
326
415
  content = skill_md.read_text(encoding="utf-8", errors="ignore")
327
- fm_match = re.search(r"^---\s*\n(.*?)\n---", content, re.DOTALL)
416
+ fm_match = re.match(r"^---\s*\n(.*?)\n---(?:\s*\n|\s*\Z)", content, re.DOTALL)
328
417
  if fm_match:
329
- v_match = re.search(r"version:\s*([^\n]+)", fm_match.group(1), re.IGNORECASE)
418
+ fm_text = fm_match.group(1)
419
+ v_match = re.search(r"^version:\s*([^\n]+)", fm_text, re.MULTILINE | re.IGNORECASE)
420
+ if not v_match:
421
+ v_match = re.search(r"^[ \t]+version:\s*([^\n]+)", fm_text, re.MULTILINE | re.IGNORECASE)
330
422
  if v_match:
331
423
  ver_tuple = parse_version_tuple(v_match.group(1))
332
424
  except Exception:
@@ -360,17 +452,28 @@ def compare_skill_recency(dir_a, dir_b):
360
452
  -1 if dir_b is newer than dir_a
361
453
  0 if they are equivalent in version and recency
362
454
  """
455
+ a_exists = (Path(dir_a) / "SKILL.md").exists()
456
+ b_exists = (Path(dir_b) / "SKILL.md").exists()
457
+ if a_exists != b_exists:
458
+ return 1 if a_exists else -1
459
+
363
460
  ver_a, mtime_a = get_skill_metadata(dir_a)
364
461
  ver_b, mtime_b = get_skill_metadata(dir_b)
365
462
 
366
463
  # 1. Compare semantic/numeric versions if both exist and differ
367
- if ver_a is not None and ver_b is not None and ver_a != ver_b:
368
- return 1 if ver_a > ver_b else -1
464
+ if ver_a is not None and ver_b is not None:
465
+ vcmp = compare_version_tuples(ver_a, ver_b)
466
+ if vcmp != 0:
467
+ return vcmp
369
468
 
370
469
  # 2. Compare file modification timestamps (allowing a 1-second margin for filesystem granularity)
371
470
  if abs(mtime_a - mtime_b) > 1.0:
372
471
  return 1 if mtime_a > mtime_b else -1
373
472
 
473
+ # 3. Tie-breaker when timestamps match: prefer an explicitly versioned skill
474
+ if (ver_a is not None) != (ver_b is not None):
475
+ return 1 if ver_a is not None else -1
476
+
374
477
  return 0
375
478
 
376
479
 
@@ -387,26 +490,42 @@ def resolve_base_dir(cli_base=None):
387
490
  if p.exists():
388
491
  return p
389
492
 
390
- # Check ancestors of the script location
493
+ # 1. Prioritize ancestors of the script location that actually contain a skill_archive
391
494
  script_path = Path(__file__).resolve()
392
495
  for parent in script_path.parents:
393
- if parent.name != "skill_archive" and (
394
- (parent / "skill_archive").exists() or (parent / "skills").exists()
395
- ):
496
+ if parent.name != "skill_archive" and (parent / "skill_archive").exists():
396
497
  return parent
397
498
 
398
499
  cwd = Path.cwd().resolve()
399
- for candidate in [
500
+ home = Path.home()
501
+ candidates = [
400
502
  cwd,
401
503
  cwd / ".agents",
402
504
  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
- ):
505
+ cwd / ".gemini",
506
+ cwd / ".cursor",
507
+ home / ".gemini" / "config",
508
+ home / ".gemini" / "config" / "skills" / "skill-vault",
509
+ home / ".agents",
510
+ home / ".claude",
511
+ home / ".gemini",
512
+ home / ".cursor",
513
+ ]
514
+ # 2. Check standard workspace and global locations for an existing skill_archive
515
+ for candidate in candidates:
516
+ if candidate.exists() and (candidate / "skill_archive").exists():
517
+ return candidate
518
+
519
+ # 3. Fallback to ancestors with skills/ (skipping installed plugins/skill-vault wrapper)
520
+ for parent in script_path.parents:
521
+ if parent.name == "skill-vault" and parent.parent.name == "plugins":
522
+ continue
523
+ if parent.name != "skill_archive" and (parent / "skills").exists():
524
+ return parent
525
+
526
+ # 4. Fallback to workspace or global locations with skills/
527
+ for candidate in candidates:
528
+ if candidate.exists() and (candidate / "skills").exists():
410
529
  return candidate
411
530
 
412
531
  return cwd
@@ -414,10 +533,12 @@ def resolve_base_dir(cli_base=None):
414
533
 
415
534
  class SkillVault:
416
535
  def __init__(self, base_dir=None):
536
+ self._explicit_base_dir = bool(base_dir)
417
537
  self.base_dir = resolve_base_dir(base_dir)
418
538
  self.archive_dir = self.base_dir / "skill_archive"
419
539
  self.manifest_file = self.archive_dir / "backup_manifest.json"
420
540
  self.index_file = self.archive_dir / "INDEX.md"
541
+ self.search_index_file = self.archive_dir / "search_index.json"
421
542
  self.config_file = self.archive_dir / "vault_config.json"
422
543
  self.skills_dir = self.base_dir / "skills"
423
544
 
@@ -459,11 +580,16 @@ class SkillVault:
459
580
  if cat not in merged_rules:
460
581
  merged_rules[cat] = list(kws)
461
582
 
583
+ routing_cfg = dict(skill_router.DEFAULT_ROUTING_CONFIG)
584
+ if isinstance(user_cfg.get("routing"), dict):
585
+ routing_cfg.update(user_cfg["routing"])
586
+
462
587
  return {
463
588
  "core_skills": sorted(core_skills),
464
589
  "disabled_core_skills": sorted(disabled_core),
465
590
  "workspace_fingerprints": merged_fp,
466
591
  "category_rules": merged_rules,
592
+ "routing": routing_cfg,
467
593
  }
468
594
 
469
595
  def save_config(self, config_data):
@@ -705,17 +831,60 @@ class SkillVault:
705
831
  return self.base_dir
706
832
 
707
833
  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":
834
+ """Locate the installed skill-vault skill/plugin directory if present (excluding git repo roots)."""
835
+ if self.base_dir.name == "skill-vault" and self.base_dir.parent.name in ("skills", "plugins"):
710
836
  if not (self.base_dir / ".git").exists():
711
837
  return self.base_dir
712
838
  root_dir = self.get_root_dir()
713
- for rel in ["skills/skill-vault", ".agents/skills/skill-vault", ".claude/skills/skill-vault"]:
839
+ for rel in [
840
+ "plugins/skill-vault",
841
+ "skills/skill-vault",
842
+ ".agents/skills/skill-vault",
843
+ ".claude/skills/skill-vault",
844
+ ]:
714
845
  cand = (root_dir / rel).resolve()
715
846
  if cand.exists() and not (cand / ".git").exists():
716
847
  return cand
717
848
  return None
718
849
 
850
+ def get_hook_protected_skills(self):
851
+ """Inspect plugin hooks.json and mcp_config.json files to protect skills referenced by commands."""
852
+ protected = {"skill-vault"}
853
+ plugin_roots = []
854
+ for cand in (self.base_dir / "plugins", self.get_root_dir() / "plugins"):
855
+ if cand.exists() and cand.is_dir():
856
+ res = cand.resolve()
857
+ if res not in plugin_roots:
858
+ plugin_roots.append(res)
859
+
860
+ skill_ref_re = re.compile(r"(?:^|[\s\"'=/\\])skills[/\\]([a-zA-Z0-9._-]+)")
861
+
862
+ def _scan_obj(obj):
863
+ if isinstance(obj, str):
864
+ for m in skill_ref_re.finditer(obj):
865
+ protected.add(m.group(1))
866
+ elif isinstance(obj, list):
867
+ for item in obj:
868
+ _scan_obj(item)
869
+ elif isinstance(obj, dict):
870
+ for val in obj.values():
871
+ _scan_obj(val)
872
+
873
+ for proot in plugin_roots:
874
+ for pdir in proot.iterdir():
875
+ if not pdir.is_dir():
876
+ continue
877
+ for cfg_name in ("hooks.json", "mcp_config.json"):
878
+ cfg_path = pdir / cfg_name
879
+ if not cfg_path.exists():
880
+ continue
881
+ try:
882
+ data = json.loads(cfg_path.read_text(encoding="utf-8", errors="replace"))
883
+ _scan_obj(data)
884
+ except Exception:
885
+ pass
886
+ return protected
887
+
719
888
  def make_portable_path(self, abs_path):
720
889
  """Convert path to relative from base_dir or root_dir if possible."""
721
890
  resolved = Path(abs_path).resolve()
@@ -837,43 +1006,55 @@ class SkillVault:
837
1006
  # --- Workspace & Optimization Engine ---
838
1007
 
839
1008
  def detect_workspace_categories(self, workspace_path=None):
840
- """Inspect workspace files and return matched skill categories."""
1009
+ """Inspect workspace files in a single depth-bounded pass and return matched skill categories."""
841
1010
  target_ws = Path(workspace_path).resolve() if workspace_path else Path.cwd().resolve()
842
1011
  matched = {}
843
1012
  config = self.load_config()
844
1013
  fingerprints = config["workspace_fingerprints"]
845
1014
 
1015
+ if not target_ws.exists():
1016
+ return matched
1017
+
1018
+ ignored_dirs = {".git", "node_modules", "__pycache__", ".venv", "venv", ".tox", "dist", "build", ".next", "target"}
1019
+ seen_names = set()
1020
+ seen_rel_paths = set()
1021
+ ws_tokens = {}
1022
+
1023
+ for root, dirs, files in os.walk(target_ws):
1024
+ dirs[:] = [d for d in dirs if d not in ignored_dirs]
1025
+ rel_path = Path(root).relative_to(target_ws)
1026
+ rel_depth = len(rel_path.parts)
1027
+ if rel_depth > 3:
1028
+ dirs[:] = []
1029
+ continue
1030
+ rel_prefix = "" if rel_path == Path(".") else rel_path.as_posix().lower() + "/"
1031
+ for entry_name in dirs + files:
1032
+ low_name = entry_name.lower()
1033
+ seen_names.add(low_name)
1034
+ seen_rel_paths.add(rel_prefix + low_name)
1035
+ tokens = {t for t in re.split(r"[-_.\s]+", low_name) if t}
1036
+ for tok in tokens:
1037
+ ws_tokens.setdefault(tok, entry_name)
1038
+
846
1039
  for category, patterns in fingerprints.items():
847
1040
  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
1041
+ pat_l = str(pat).lower()
1042
+ if "*" in pat_l or "?" in pat_l:
1043
+ hit = any(fnmatch.fnmatchcase(n, pat_l) for n in seen_names) or any(
1044
+ fnmatch.fnmatchcase(rp, pat_l) for rp in seen_rel_paths
1045
+ )
853
1046
  else:
854
- if (target_ws / pat).exists() or list(target_ws.glob(f"**/{pat}"))[:1]:
855
- matched.setdefault(category, []).append(pat)
856
- break
1047
+ hit = (pat_l in seen_names) or (pat_l in seen_rel_paths)
1048
+ if hit:
1049
+ matched.setdefault(category, []).append(pat)
1050
+ break
857
1051
 
858
1052
  # Inspect categories present in manifest for workspace filename/directory keyword matches
859
1053
  manifest = self.load_manifest()
860
1054
  manifest_categories = {m.get("category") for m in manifest if m.get("category")}
861
1055
  unmatched_cats = [c for c in sorted(manifest_categories) if c not in matched]
862
- if unmatched_cats and target_ws.exists():
1056
+ if unmatched_cats:
863
1057
  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
1058
  for cat in unmatched_cats:
878
1059
  words = [
879
1060
  w.lower()
@@ -895,6 +1076,7 @@ class SkillVault:
895
1076
  """
896
1077
  target_ws = Path(workspace_path).resolve() if workspace_path else Path.cwd().resolve()
897
1078
  core_set = self.get_core_skills(protected_skills)
1079
+ hook_protected = self.get_hook_protected_skills()
898
1080
 
899
1081
  print("==================================================")
900
1082
  print(" SKILL VAULT AUTO-OPTIMIZATION")
@@ -923,6 +1105,8 @@ class SkillVault:
923
1105
  skill_md_path = Path(data["path"]) / "SKILL.md"
924
1106
  if name in core_set:
925
1107
  to_keep.append((name, "Core Foundation Skill"))
1108
+ elif name in hook_protected:
1109
+ to_keep.append((name, "Protected Plugin Hook/MCP Dependency"))
926
1110
  elif self.is_core_skill_frontmatter(skill_md_path):
927
1111
  to_keep.append((name, "Core Foundation Skill (Pinned in Frontmatter)"))
928
1112
  else:
@@ -1014,14 +1198,7 @@ class SkillVault:
1014
1198
  if explicit_cat:
1015
1199
  return explicit_cat
1016
1200
 
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
- ]:
1201
+ if skill_name in self.get_core_skills():
1025
1202
  return "General & Utility Skills"
1026
1203
 
1027
1204
  rules = self.load_config()["category_rules"]
@@ -1045,6 +1222,7 @@ class SkillVault:
1045
1222
  print("==================================================\n")
1046
1223
 
1047
1224
  core_set = self.get_core_skills(protect_skills)
1225
+ hook_protected = self.get_hook_protected_skills()
1048
1226
 
1049
1227
  active_skills = self.get_active_skills()
1050
1228
  manifest = self.load_manifest()
@@ -1055,6 +1233,7 @@ class SkillVault:
1055
1233
  to_prune = []
1056
1234
  in_sync = []
1057
1235
  retained_core = []
1236
+ protected_hooks = []
1058
1237
 
1059
1238
  for name, data in sorted(active_skills.items()):
1060
1239
  if name == "skill-vault":
@@ -1064,6 +1243,7 @@ class SkillVault:
1064
1243
  active_path = Path(data["path"])
1065
1244
  skill_md_path = active_path / "SKILL.md"
1066
1245
  is_core = (name in core_set) or self.is_core_skill_frontmatter(skill_md_path)
1246
+ is_hook_dep = name in hook_protected
1067
1247
 
1068
1248
  if name in manifest_map:
1069
1249
  item = manifest_map[name]
@@ -1088,6 +1268,8 @@ class SkillVault:
1088
1268
 
1089
1269
  if is_core:
1090
1270
  retained_core.append(name)
1271
+ elif is_hook_dep:
1272
+ protected_hooks.append(name)
1091
1273
  elif not keep_active:
1092
1274
  to_prune.append((name, data))
1093
1275
 
@@ -1102,6 +1284,10 @@ class SkillVault:
1102
1284
 
1103
1285
  print(f" * In-sync skills in vault: {len(in_sync)}")
1104
1286
  print(f" * Retained Core Foundation Skills: {len(retained_core)} ({', '.join(sorted(retained_core))})")
1287
+ if protected_hooks:
1288
+ print(f" * Hook/MCP-Protected Plugin Skills: {len(protected_hooks)}")
1289
+ for name in sorted(protected_hooks):
1290
+ print(f" [Protected (Hook Dependency)] {name}")
1105
1291
  print(f" * Non-core active skills to prune: {len(to_prune)}")
1106
1292
  for name, _ in to_prune:
1107
1293
  print(f" [PRUNE] {name} (Will be removed from active context to prevent context bloat)")
@@ -1254,6 +1440,7 @@ class SkillVault:
1254
1440
  """Archive active skills with an assigned category, prioritizing newer versions."""
1255
1441
  manifest = self.load_manifest()
1256
1442
  manifest_map = {item["name"]: item for item in manifest}
1443
+ hook_protected = self.get_hook_protected_skills()
1257
1444
 
1258
1445
  skills_to_archive = []
1259
1446
  if name:
@@ -1285,8 +1472,11 @@ class SkillVault:
1285
1472
  if recency < 0 and not force:
1286
1473
  print(f"[Skip] L2 archive '{skill_name}' is newer than active L1 version. Preserving newer archive (use --force to overwrite).")
1287
1474
  if not keep_active:
1288
- shutil.rmtree(active_path)
1289
- print(f"[Cleaned] Removed older active directory: {active_path}")
1475
+ if skill_name in hook_protected:
1476
+ print(f"[Protected (Hook Dependency)] Preserving active '{skill_name}' (referenced by plugin hooks/MCP; use --force to override)")
1477
+ else:
1478
+ shutil.rmtree(active_path)
1479
+ print(f"[Cleaned] Removed older active directory: {active_path}")
1290
1480
  continue
1291
1481
  elif recency > 0:
1292
1482
  print(f"[Archived] Overwriting older L2 archive with newer active L1 version: {active_path} -> {dest_dir}")
@@ -1315,27 +1505,70 @@ class SkillVault:
1315
1505
  }
1316
1506
 
1317
1507
  if not keep_active:
1318
- shutil.rmtree(active_path)
1319
- print(f"[Cleaned] Removed active directory: {active_path}")
1508
+ if skill_name in hook_protected and not force:
1509
+ print(f"[Protected (Hook Dependency)] Preserving active '{skill_name}' (referenced by plugin hooks/MCP; use --force to override)")
1510
+ else:
1511
+ shutil.rmtree(active_path)
1512
+ print(f"[Cleaned] Removed active directory: {active_path}")
1320
1513
 
1321
1514
  self.save_manifest(list(manifest_map.values()))
1322
1515
  self.reindex()
1323
1516
  print("Archiving complete.")
1324
1517
 
1325
- def recategorize(self, name, new_category):
1326
- """Update category for an archived skill."""
1518
+ def recategorize(self, name=None, new_category=None, auto=False, dry_run=False):
1519
+ """Update category for an archived skill, or auto-recategorize General & Utility Skills."""
1327
1520
  manifest = self.load_manifest()
1328
1521
  manifest_map = {item["name"]: item for item in manifest}
1329
1522
 
1523
+ if auto:
1524
+ updates = []
1525
+ scanned_general = 0
1526
+ for item in manifest:
1527
+ cur_cat = item.get("category") or "General & Utility Skills"
1528
+ if cur_cat != "General & Utility Skills":
1529
+ continue
1530
+ scanned_general += 1
1531
+ archived_path = self.resolve_portable_path(item.get("archived_path", ""))
1532
+ skill_md = archived_path / "SKILL.md"
1533
+ desc = self.parse_skill_description(skill_md) if skill_md.exists() else ""
1534
+ inferred = self.infer_category(item["name"], desc, skill_md if skill_md.exists() else None)
1535
+ if inferred and inferred != "General & Utility Skills":
1536
+ updates.append((item["name"], cur_cat, inferred))
1537
+ if not dry_run:
1538
+ item["category"] = inferred
1539
+
1540
+ print("==================================================")
1541
+ print(" SKILL VAULT AUTO-RECATEGORIZATION")
1542
+ print(f" General skills scanned: {scanned_general}")
1543
+ print(f" Improved categories: {len(updates)}")
1544
+ print("==================================================\n")
1545
+ for sname, old_c, new_c in updates:
1546
+ print(f" * {sname}: '{old_c}' -> '{new_c}'")
1547
+
1548
+ if dry_run:
1549
+ print("\n[Dry Run] Auto-recategorization preview complete. No changes saved.")
1550
+ return 0
1551
+
1552
+ if updates:
1553
+ self.save_manifest(manifest)
1554
+ self.reindex()
1555
+ print(f"\n[OK] Recategorized {len(updates)} skill(s).")
1556
+ return 0
1557
+
1558
+ if not name or not new_category:
1559
+ print("[Error] Please specify skill name and new category, or pass --auto.")
1560
+ return 1
1561
+
1330
1562
  if name not in manifest_map:
1331
1563
  print(f"[Error] Skill '{name}' not found in manifest.")
1332
- return
1564
+ return 1
1333
1565
 
1334
1566
  old_cat = manifest_map[name].get("category", "Uncategorized")
1335
1567
  manifest_map[name]["category"] = new_category.strip()
1336
1568
  self.save_manifest(list(manifest_map.values()))
1337
1569
  self.reindex()
1338
1570
  print(f"[Recategorized] '{name}': '{old_cat}' -> '{new_category.strip()}'")
1571
+ return 0
1339
1572
 
1340
1573
  def restore(self, name=None, pattern=None, category=None, restore_all=False, force=False):
1341
1574
  """Restore archived skills back to active locations."""
@@ -1390,6 +1623,105 @@ class SkillVault:
1390
1623
 
1391
1624
  print("Restoration complete.")
1392
1625
 
1626
+ def _find_external_harness_configs(self):
1627
+ """Return existing harness config files that contain skill-vault hook/MCP entries."""
1628
+ root_dir = self.get_root_dir().resolve()
1629
+ home = Path.home().resolve()
1630
+ candidates = [
1631
+ root_dir / ".claude" / "settings.json",
1632
+ root_dir / ".gemini" / "settings.json",
1633
+ root_dir / ".cursor" / "mcp.json",
1634
+ ]
1635
+ global_roots = {
1636
+ home,
1637
+ (home / ".gemini" / "config").resolve(),
1638
+ (home / ".claude").resolve(),
1639
+ (home / ".agents").resolve(),
1640
+ }
1641
+ if root_dir in global_roots:
1642
+ candidates.extend([
1643
+ home / ".claude" / "settings.json",
1644
+ home / ".gemini" / "settings.json",
1645
+ home / ".cursor" / "mcp.json",
1646
+ ])
1647
+
1648
+ matched = []
1649
+ seen = set()
1650
+ for p in candidates:
1651
+ res = p.resolve()
1652
+ if res in seen or not p.exists():
1653
+ continue
1654
+ seen.add(res)
1655
+ try:
1656
+ text = p.read_text(encoding="utf-8", errors="replace")
1657
+ if "skill-vault" in text or "hook_runner.py" in text or "mcp_server.py" in text:
1658
+ matched.append(p)
1659
+ except OSError:
1660
+ pass
1661
+ return matched
1662
+
1663
+ @staticmethod
1664
+ def _clean_external_harness_config(cfg_path):
1665
+ """Surgically remove skill-vault hook/MCP entries from an external harness JSON config."""
1666
+ cfg_path = Path(cfg_path)
1667
+ if not cfg_path.exists():
1668
+ return False
1669
+ try:
1670
+ data = json.loads(cfg_path.read_text(encoding="utf-8", errors="replace"))
1671
+ except Exception:
1672
+ return False
1673
+ if not isinstance(data, dict):
1674
+ return False
1675
+
1676
+ changed = False
1677
+ mcp = data.get("mcpServers")
1678
+ if isinstance(mcp, dict) and "skill-vault" in mcp:
1679
+ del mcp["skill-vault"]
1680
+ if not mcp:
1681
+ del data["mcpServers"]
1682
+ changed = True
1683
+
1684
+ hooks = data.get("hooks")
1685
+ if isinstance(hooks, dict):
1686
+ for evt in list(hooks.keys()):
1687
+ groups = hooks.get(evt)
1688
+ if not isinstance(groups, list):
1689
+ continue
1690
+ new_groups = []
1691
+ for grp in groups:
1692
+ if not isinstance(grp, dict):
1693
+ new_groups.append(grp)
1694
+ continue
1695
+ sub_hooks = grp.get("hooks")
1696
+ if isinstance(sub_hooks, list):
1697
+ kept = [
1698
+ h for h in sub_hooks
1699
+ if not (
1700
+ isinstance(h, dict)
1701
+ and ("hook_runner.py" in str(h.get("command", "")) or "skill-vault" in str(h.get("command", "")))
1702
+ )
1703
+ ]
1704
+ if len(kept) != len(sub_hooks):
1705
+ changed = True
1706
+ if kept:
1707
+ grp_copy = dict(grp)
1708
+ grp_copy["hooks"] = kept
1709
+ new_groups.append(grp_copy)
1710
+ else:
1711
+ new_groups.append(grp)
1712
+ if new_groups:
1713
+ hooks[evt] = new_groups
1714
+ else:
1715
+ del hooks[evt]
1716
+ if not hooks:
1717
+ del data["hooks"]
1718
+
1719
+ if changed:
1720
+ tmp = cfg_path.with_name(f".{cfg_path.name}.{os.getpid()}.tmp")
1721
+ tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
1722
+ os.replace(tmp, cfg_path)
1723
+ return changed
1724
+
1393
1725
  def uninstall(self, dry_run=False, force=False, keep_archive=False, keep_skill=False):
1394
1726
  """Cleanly restore all archived skills to L1 without overwriting newer L1 versions and remove skill-vault."""
1395
1727
  root_dir = self.get_root_dir()
@@ -1483,10 +1815,22 @@ class SkillVault:
1483
1815
  else:
1484
1816
  print(f" * Archive: Remove {self.archive_dir}")
1485
1817
 
1486
- if keep_skill or not sv_dir:
1818
+ sv_dirs = []
1819
+ for cand in [sv_dir, root_dir / "plugins" / "skill-vault", root_dir / "skills" / "skill-vault"]:
1820
+ if cand and cand.exists() and not (cand / ".git").exists():
1821
+ resolved_cand = cand.resolve()
1822
+ if resolved_cand not in sv_dirs:
1823
+ sv_dirs.append(resolved_cand)
1824
+
1825
+ if keep_skill or not sv_dirs:
1487
1826
  print(f" * Skill: Keep {sv_dir if sv_dir else '(None detected)'}")
1488
1827
  else:
1489
- print(f" * Skill: Remove {sv_dir}")
1828
+ for d in sv_dirs:
1829
+ print(f" * Skill: Remove {d}")
1830
+
1831
+ harness_targets = [] if keep_skill else self._find_external_harness_configs()
1832
+ for hpath in harness_targets:
1833
+ print(f" * Wiring: Remove skill-vault entries from {hpath}")
1490
1834
  print("")
1491
1835
 
1492
1836
  if missing_sources:
@@ -1509,8 +1853,8 @@ class SkillVault:
1509
1853
  dirs_to_delete = []
1510
1854
  if not keep_archive and self.archive_dir.exists():
1511
1855
  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())
1856
+ if not keep_skill:
1857
+ dirs_to_delete.extend(sv_dirs)
1514
1858
 
1515
1859
  verification_errors = []
1516
1860
  for skill_name, _, original_path, _ in to_restore + to_upgrade + to_preserve:
@@ -1550,12 +1894,17 @@ class SkillVault:
1550
1894
  shutil.rmtree(self.archive_dir)
1551
1895
  print(f"[Removed] Archive directory: {self.archive_dir}")
1552
1896
 
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}")
1897
+ if not keep_skill:
1898
+ for d in sv_dirs:
1899
+ if d.exists():
1900
+ cwd_resolved = Path.cwd().resolve()
1901
+ if cwd_resolved == d or d in cwd_resolved.parents:
1902
+ os.chdir(root_dir)
1903
+ shutil.rmtree(d)
1904
+ print(f"[Removed] Skill-vault directory: {d}")
1905
+ for hpath in harness_targets:
1906
+ if self._clean_external_harness_config(hpath):
1907
+ print(f"[Cleaned] Removed skill-vault entries from: {hpath}")
1559
1908
 
1560
1909
  total_safe = len(to_restore) + len(to_upgrade) + len(to_preserve)
1561
1910
  print(f"\n[OK] Clean uninstall complete! {total_safe} skill(s) verified safe in active L1 locations.")
@@ -1622,11 +1971,25 @@ class SkillVault:
1622
1971
  f.write("\n".join(lines).strip() + "\n")
1623
1972
 
1624
1973
  self.save_manifest(list(manifest_by_folder.values()))
1974
+ skill_router.build_search_index(
1975
+ archive_dir=self.archive_dir,
1976
+ manifest=list(manifest_by_folder.values()),
1977
+ base_dir=self.base_dir,
1978
+ resolve_path_fn=self.resolve_portable_path,
1979
+ )
1625
1980
  updated_routers = self.sync_router_md()
1626
1981
  for r_path in updated_routers:
1627
1982
  print(f"[Router Synced] Updated SKILL.md frontmatter: {r_path}")
1628
1983
  print(f"[Reindexed] {total_count} skills across {len(categories)} categories (Base: {self.base_dir}).")
1629
1984
 
1985
+ def build_compact_router_description(self):
1986
+ """Build a minimal ~45-token frontmatter description when background hooks are active."""
1987
+ return (
1988
+ "Universal agent-agnostic skill router and tiered storage manager. "
1989
+ "Background hooks automatically inject relevant vaulted skills on demand; "
1990
+ "use MCP tools list_skills/search_skills/load_skill for mid-turn lookups."
1991
+ )
1992
+
1630
1993
  def build_router_description(self):
1631
1994
  """Build a dynamic SKILL.md router description from the current archive manifest."""
1632
1995
  manifest = self.load_manifest()
@@ -1661,10 +2024,13 @@ class SkillVault:
1661
2024
 
1662
2025
  def _get_router_skill_md_candidates(self):
1663
2026
  """Locate candidate SKILL.md files belonging to skill-vault within base_dir."""
2027
+ root_dir = self.get_root_dir()
1664
2028
  raw_candidates = [
1665
2029
  self.skills_dir / "skill-vault" / "SKILL.md",
1666
2030
  self.base_dir / ".agents" / "skills" / "skill-vault" / "SKILL.md",
1667
2031
  self.base_dir / ".claude" / "skills" / "skill-vault" / "SKILL.md",
2032
+ self.base_dir / "plugins" / "skill-vault" / "skills" / "skill-vault" / "SKILL.md",
2033
+ root_dir / "plugins" / "skill-vault" / "skills" / "skill-vault" / "SKILL.md",
1668
2034
  ]
1669
2035
  if self.archive_dir.exists():
1670
2036
  raw_candidates.append(self.base_dir / "SKILL.md")
@@ -1681,7 +2047,11 @@ class SkillVault:
1681
2047
  def sync_router_md(self, target_skill_md=None, force=False):
1682
2048
  """Synchronize skill-vault's SKILL.md frontmatter description with the active vault categories."""
1683
2049
  candidates = [Path(target_skill_md)] if target_skill_md else self._get_router_skill_md_candidates()
1684
- new_desc = self.build_router_description()
2050
+ routing_cfg = self.load_config().get("routing", {})
2051
+ if routing_cfg.get("compact_router_prompt"):
2052
+ new_desc = self.build_compact_router_description()
2053
+ else:
2054
+ new_desc = self.build_router_description()
1685
2055
  new_desc_block = f"description: >-\n {new_desc}"
1686
2056
  desc_pattern = re.compile(
1687
2057
  r"^description:\s*(?:>[-+]?|\|[-+]?)?\s*\n?.*?(?=\n[a-zA-Z0-9_-]+:|\Z)",
@@ -1715,6 +2085,20 @@ class SkillVault:
1715
2085
 
1716
2086
  return updated
1717
2087
 
2088
+ @staticmethod
2089
+ def _parse_routing_value(key, raw_val):
2090
+ default = skill_router.DEFAULT_ROUTING_CONFIG.get(key)
2091
+ val = str(raw_val).strip()
2092
+ if isinstance(default, bool):
2093
+ return val.lower() in {"1", "true", "yes", "on"}
2094
+ if isinstance(default, int):
2095
+ return int(val)
2096
+ if isinstance(default, float):
2097
+ return float(val)
2098
+ if isinstance(default, list):
2099
+ return [v.strip() for v in val.split(",") if v.strip()]
2100
+ return val
2101
+
1718
2102
  def manage_config(
1719
2103
  self,
1720
2104
  show=False,
@@ -1723,6 +2107,7 @@ class SkillVault:
1723
2107
  remove_core=None,
1724
2108
  add_fingerprint=None,
1725
2109
  add_category_rule=None,
2110
+ set_routing=None,
1726
2111
  sync_prompt=False,
1727
2112
  ):
1728
2113
  """Inspect or update vault_config.json and dynamically synchronize the router prompt."""
@@ -1735,14 +2120,15 @@ class SkillVault:
1735
2120
 
1736
2121
  fp_pairs = _normalize_pairs(add_fingerprint)
1737
2122
  rule_pairs = _normalize_pairs(add_category_rule)
1738
- mutating = bool(init_config or add_core or remove_core or fp_pairs or rule_pairs)
2123
+ routing_pairs = _normalize_pairs(set_routing)
2124
+ mutating = bool(init_config or add_core or remove_core or fp_pairs or rule_pairs or routing_pairs)
1739
2125
 
1740
2126
  if init_config:
1741
2127
  effective = self.load_config()
1742
2128
  self.save_config(effective)
1743
2129
  print(f"[Config Initialized] Wrote vault configuration to: {self.config_file}")
1744
2130
 
1745
- if add_core or remove_core or fp_pairs or rule_pairs:
2131
+ if add_core or remove_core or fp_pairs or rule_pairs or routing_pairs:
1746
2132
  raw_cfg = self._load_raw_config()
1747
2133
 
1748
2134
  if add_core:
@@ -1807,6 +2193,18 @@ class SkillVault:
1807
2193
  print(f"[Config Updated] Added category rule: [{c}] <- '{k}'")
1808
2194
  raw_cfg["category_rules"] = rule_map
1809
2195
 
2196
+ if routing_pairs:
2197
+ routing_map = dict(raw_cfg.get("routing", {}))
2198
+ for r_key, r_val in routing_pairs:
2199
+ k = r_key.strip()
2200
+ if k not in skill_router.DEFAULT_ROUTING_CONFIG:
2201
+ print(f"[Warning] Unknown routing key '{k}'. Valid keys: {', '.join(sorted(skill_router.DEFAULT_ROUTING_CONFIG))}")
2202
+ continue
2203
+ parsed = self._parse_routing_value(k, r_val)
2204
+ routing_map[k] = parsed
2205
+ print(f"[Config Updated] Routing '{k}' = {parsed!r}")
2206
+ raw_cfg["routing"] = routing_map
2207
+
1810
2208
  self.save_config(raw_cfg)
1811
2209
 
1812
2210
  if sync_prompt:
@@ -1829,7 +2227,10 @@ class SkillVault:
1829
2227
  print("==================================================\n")
1830
2228
  print(f"Protected Core Skills ({len(effective['core_skills'])}):")
1831
2229
  print(f" {', '.join(effective['core_skills'])}\n")
1832
- print(f"Workspace Fingerprint Categories ({len(effective['workspace_fingerprints'])}):")
2230
+ print("Background JIT Routing Settings:")
2231
+ for rk, rv in sorted(effective["routing"].items()):
2232
+ print(f" * {rk}: {rv!r}")
2233
+ print(f"\nWorkspace Fingerprint Categories ({len(effective['workspace_fingerprints'])}):")
1833
2234
  for cat, pats in effective["workspace_fingerprints"].items():
1834
2235
  print(f" * {cat}: {len(pats)} pattern(s)")
1835
2236
  print(f"\nCategory Inference Rules ({len(effective['category_rules'])}):")
@@ -1944,33 +2345,759 @@ class SkillVault:
1944
2345
 
1945
2346
  return 0
1946
2347
 
1947
- def search(self, query):
1948
- """Search archived skills."""
1949
- q = query.lower()
1950
- manifest = self.load_manifest()
1951
- results = []
2348
+ def search(self, query, category=None, limit=10, as_json=False):
2349
+ """Search archived skills using pre-built BM25 index with substring fallback."""
2350
+ index_data = skill_router.load_or_build_index(
2351
+ archive_dir=self.archive_dir,
2352
+ base_dir=self.base_dir,
2353
+ resolve_path_fn=self.resolve_portable_path,
2354
+ )
2355
+ results = skill_router.search_index(
2356
+ index_data=index_data,
2357
+ query=query,
2358
+ category=category,
2359
+ limit=limit,
2360
+ )
1952
2361
 
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)
2362
+ # Fallback substring search when query is a partial fragment not captured by tokenization
2363
+ if not results and query.strip():
2364
+ q = query.strip().lower()
2365
+ for item in self.load_manifest():
2366
+ name = item["name"]
2367
+ cat = item.get("category", "General & Utility Skills")
2368
+ if category and cat.lower() != category.strip().lower():
2369
+ continue
2370
+ archived_path = self.resolve_portable_path(item["archived_path"])
2371
+ desc = self.parse_skill_description(archived_path / "SKILL.md")
2372
+ if q in name.lower() or q in desc.lower() or q in cat.lower():
2373
+ results.append({
2374
+ "name": name,
2375
+ "category": cat,
2376
+ "score": 1.0,
2377
+ "description": desc,
2378
+ "resolved_path": str(archived_path),
2379
+ })
2380
+ results = results[:limit]
1959
2381
 
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)))
2382
+ if as_json:
2383
+ print(json.dumps(results, indent=2, ensure_ascii=False))
2384
+ return
1962
2385
 
1963
2386
  if not results:
1964
2387
  print(f"No archived skills matched '{query}'.")
1965
2388
  return
1966
2389
 
1967
2390
  print(f"Found {len(results)} matching skill(s):\n")
1968
- for name, cat, desc, path_str in results:
1969
- print(f"* {name} [{cat}]")
2391
+ for r in results:
2392
+ path_str = r.get("resolved_path") or str(self.resolve_portable_path(r.get("archived_path", "")))
2393
+ desc = r.get("description", "")
2394
+ print(f"* {r['name']} [{r['category']}] (score: {r['score']})")
1970
2395
  desc_snippet = desc[:130] + "..." if len(desc) > 130 else desc
1971
2396
  print(f" Description: {desc_snippet}")
1972
2397
  print(f" Path: {path_str}\n")
1973
2398
 
2399
+ # --- JIT Router Debugging, Deduplication, Telemetry & Setup ---
2400
+
2401
+ def route(self, prompt, workspace_path=None, mode=None, as_json=False):
2402
+ """Dry-run the JIT skill router against a prompt and inspect scores, tiers, and tokens."""
2403
+ index_data = skill_router.load_or_build_index(
2404
+ archive_dir=self.archive_dir,
2405
+ base_dir=self.base_dir,
2406
+ resolve_path_fn=self.resolve_portable_path,
2407
+ )
2408
+ cfg = dict(self.load_config().get("routing", {}))
2409
+ if mode:
2410
+ cfg["mode"] = mode
2411
+
2412
+ ws_cats = []
2413
+ ws_target = Path(workspace_path).resolve() if workspace_path else Path.cwd().resolve()
2414
+ if ws_target.exists():
2415
+ ws_cats = sorted(self.detect_workspace_categories(ws_target).keys())
2416
+
2417
+ result = skill_router.route_prompt(
2418
+ index_data=index_data,
2419
+ prompt=prompt,
2420
+ archive_dir=self.archive_dir,
2421
+ base_dir=self.base_dir,
2422
+ workspace_categories=ws_cats,
2423
+ routing_config=cfg,
2424
+ )
2425
+
2426
+ if as_json:
2427
+ payload = {
2428
+ "prompt": prompt,
2429
+ "mode": cfg.get("mode", "hybrid"),
2430
+ "workspace_categories": ws_cats,
2431
+ "ambiguous": result["ambiguous"],
2432
+ "estimated_tokens": result["estimated_tokens"],
2433
+ "inline": [
2434
+ {
2435
+ "name": i["name"],
2436
+ "category": i["category"],
2437
+ "score": i["score"],
2438
+ "matched_terms": i.get("matched_terms", []),
2439
+ "truncated": i.get("truncated", False),
2440
+ }
2441
+ for i in result["inline"]
2442
+ ],
2443
+ "pointers": [
2444
+ {
2445
+ "name": p["name"],
2446
+ "category": p["category"],
2447
+ "score": p["score"],
2448
+ "matched_terms": p.get("matched_terms", []),
2449
+ }
2450
+ for p in result["pointers"]
2451
+ ],
2452
+ "top_candidates": [
2453
+ {
2454
+ "name": c["name"],
2455
+ "category": c["category"],
2456
+ "score": c["score"],
2457
+ "matched_terms": c.get("matched_terms", []),
2458
+ }
2459
+ for c in result.get("candidates", [])[:8]
2460
+ ],
2461
+ }
2462
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
2463
+ return 0
2464
+
2465
+ print("==================================================")
2466
+ print(" SKILL VAULT ROUTE DIAGNOSTIC")
2467
+ print(f" Prompt: {prompt}")
2468
+ print(f" Mode: {cfg.get('mode', 'hybrid')}")
2469
+ print(f" Workspace: {', '.join(ws_cats) if ws_cats else '(none detected)'}")
2470
+ print(f" Ambiguous: {result['ambiguous']}")
2471
+ print(f" Est Tokens:{result['estimated_tokens']}")
2472
+ print("==================================================\n")
2473
+
2474
+ if result["inline"]:
2475
+ print(f"INLINE ({len(result['inline'])}):")
2476
+ for i in result["inline"]:
2477
+ terms = ", ".join(i.get("matched_terms", []))
2478
+ trunc = " [TRUNCATED]" if i.get("truncated") else ""
2479
+ print(f" * {i['name']} [{i['category']}] score={i['score']} terms=[{terms}]{trunc}")
2480
+ else:
2481
+ print("INLINE: (none)")
2482
+
2483
+ if result["pointers"]:
2484
+ print(f"\nPOINTERS ({len(result['pointers'])}):")
2485
+ for p in result["pointers"]:
2486
+ terms = ", ".join(p.get("matched_terms", []))
2487
+ print(f" * {p['name']} [{p['category']}] score={p['score']} terms=[{terms}]")
2488
+ else:
2489
+ print("\nPOINTERS: (none)")
2490
+
2491
+ top_cands = result.get("candidates", [])[:8]
2492
+ if top_cands:
2493
+ print(f"\nTop Ranked Candidates:")
2494
+ for c in top_cands:
2495
+ terms = ", ".join(c.get("matched_terms", []))
2496
+ print(f" - {c['name']} [{c['category']}] score={c['score']} terms=[{terms}]")
2497
+ print("")
2498
+ return 0
2499
+
2500
+ @staticmethod
2501
+ def _inspect_dedupe_entry(idx, item, dir_path):
2502
+ """Extract canonical name, frontmatter alias, content hash, and recency metadata for dedupe."""
2503
+ canon_name = skill_router.canonicalize_skill_name(item.get("name", ""))
2504
+ fm_canon_name = None
2505
+ content_hash = None
2506
+ size_bytes = 0
2507
+ skill_md = dir_path / "SKILL.md"
2508
+ if skill_md.exists():
2509
+ try:
2510
+ raw_bytes = skill_md.read_bytes()
2511
+ size_bytes = len(raw_bytes)
2512
+ if size_bytes >= 64:
2513
+ content_hash = hashlib.sha256(raw_bytes).hexdigest()
2514
+ content = raw_bytes.decode("utf-8", errors="ignore")
2515
+ fm_match = re.match(r"^---\s*\n(.*?)\n---(?:\s*\n|\s*\Z)", content, re.DOTALL)
2516
+ if fm_match:
2517
+ n_match = re.search(r"^name:\s*([^\n]+)", fm_match.group(1), re.MULTILINE | re.IGNORECASE)
2518
+ if n_match:
2519
+ fm_raw = n_match.group(1).strip().strip("'\"")
2520
+ if fm_raw:
2521
+ fm_canon_name = skill_router.canonicalize_skill_name(fm_raw) or None
2522
+ except OSError:
2523
+ pass
2524
+ ver_tuple, mtime = get_skill_metadata(dir_path)
2525
+ return {
2526
+ "idx": idx,
2527
+ "item": item,
2528
+ "dir_path": dir_path,
2529
+ "canon_name": canon_name,
2530
+ "fm_canon_name": fm_canon_name,
2531
+ "content_hash": content_hash,
2532
+ "size_bytes": size_bytes,
2533
+ "ver_tuple": ver_tuple,
2534
+ "mtime": mtime,
2535
+ }
2536
+
2537
+ @staticmethod
2538
+ def _dedupe_candidate_beats(cand_info, win_info):
2539
+ """Return True if cand_info is newer or preferred over win_info."""
2540
+ rec = compare_skill_recency(cand_info["dir_path"], win_info["dir_path"])
2541
+ if rec != 0:
2542
+ return rec > 0
2543
+ cand_name = cand_info["item"]["name"]
2544
+ win_name = win_info["item"]["name"]
2545
+ cand_hyphen = "-" in cand_name and "_" not in cand_name
2546
+ win_hyphen = "-" in win_name and "_" not in win_name
2547
+ if cand_hyphen != win_hyphen:
2548
+ return cand_hyphen
2549
+ if cand_info["size_bytes"] != win_info["size_bytes"]:
2550
+ return cand_info["size_bytes"] > win_info["size_bytes"]
2551
+ return cand_name.lower() < win_name.lower()
2552
+
2553
+ @staticmethod
2554
+ def _format_dedupe_meta(info):
2555
+ ver_str = ".".join(map(str, info["ver_tuple"])) if info["ver_tuple"] is not None else "none"
2556
+ mtime_str = (
2557
+ datetime.fromtimestamp(info["mtime"]).strftime("%Y-%m-%d %H:%M")
2558
+ if info["mtime"] > 0
2559
+ else "unknown"
2560
+ )
2561
+ return f"[ver={ver_str}, mtime={mtime_str}]"
2562
+
2563
+ def dedupe(self, dry_run=False):
2564
+ """Consolidate duplicate skills in L2 (canonical name, frontmatter name, or identical content), keeping the newest version."""
2565
+ manifest = self.load_manifest()
2566
+ infos = [
2567
+ self._inspect_dedupe_entry(i, item, self.resolve_portable_path(item.get("archived_path", "")))
2568
+ for i, item in enumerate(manifest)
2569
+ ]
2570
+
2571
+ # Union-Find over manifest entries sharing canonical name, frontmatter name, or SKILL.md SHA-256
2572
+ parent = list(range(len(infos)))
2573
+
2574
+ def _find(x):
2575
+ while parent[x] != x:
2576
+ parent[x] = parent[parent[x]]
2577
+ x = parent[x]
2578
+ return x
2579
+
2580
+ def _union(a, b):
2581
+ ra, rb = _find(a), _find(b)
2582
+ if ra != rb:
2583
+ parent[rb] = ra
2584
+
2585
+ buckets = {}
2586
+ for info in infos:
2587
+ idx = info["idx"]
2588
+ keys = []
2589
+ if info["canon_name"]:
2590
+ keys.append(("name", info["canon_name"]))
2591
+ if info["fm_canon_name"]:
2592
+ keys.append(("name", info["fm_canon_name"]))
2593
+ if info["content_hash"]:
2594
+ keys.append(("sha256", info["content_hash"]))
2595
+ for key in keys:
2596
+ buckets.setdefault(key, []).append(idx)
2597
+
2598
+ for key_indices in buckets.values():
2599
+ if len(key_indices) > 1:
2600
+ head = key_indices[0]
2601
+ for other in key_indices[1:]:
2602
+ _union(head, other)
2603
+
2604
+ components = {}
2605
+ for info in infos:
2606
+ components.setdefault(_find(info["idx"]), []).append(info)
2607
+
2608
+ dup_components = [grp for grp in components.values() if len(grp) > 1]
2609
+ print("==================================================")
2610
+ print(" SKILL VAULT DUPLICATE CHECK")
2611
+ print(f" Total Manifest Entries: {len(manifest)}")
2612
+ print(f" Duplicate Groups Found: {len(dup_components)}")
2613
+ print("==================================================\n")
2614
+
2615
+ if not dup_components:
2616
+ print("[OK] No duplicate skills found in vault.")
2617
+ return 0
2618
+
2619
+ to_remove = []
2620
+ kept_entries = []
2621
+ prepared_groups = []
2622
+ for grp in components.values():
2623
+ if len(grp) == 1:
2624
+ kept_entries.append(grp[0]["item"])
2625
+ continue
2626
+
2627
+ win_info = grp[0]
2628
+ for cand_info in grp[1:]:
2629
+ if self._dedupe_candidate_beats(cand_info, win_info):
2630
+ win_info = cand_info
2631
+ kept_entries.append(win_info["item"])
2632
+
2633
+ reasons = set()
2634
+ for i in range(len(grp)):
2635
+ for j in range(i + 1, len(grp)):
2636
+ a, b = grp[i], grp[j]
2637
+ if a["canon_name"] and a["canon_name"] == b["canon_name"]:
2638
+ reasons.add("canonical-name")
2639
+ else:
2640
+ a_names = {n for n in (a["canon_name"], a["fm_canon_name"]) if n}
2641
+ b_names = {n for n in (b["canon_name"], b["fm_canon_name"]) if n}
2642
+ if a_names & b_names:
2643
+ reasons.add("frontmatter-name")
2644
+ if a["content_hash"] and a["content_hash"] == b["content_hash"]:
2645
+ reasons.add("identical-content")
2646
+
2647
+ group_label = win_info["canon_name"] or win_info["item"]["name"]
2648
+ losers = [c for c in grp if c["idx"] != win_info["idx"]]
2649
+ losers.sort(key=lambda c: c["item"]["name"].lower())
2650
+ prepared_groups.append((group_label, sorted(reasons), win_info, losers))
2651
+
2652
+ prepared_groups.sort(key=lambda g: g[0].lower())
2653
+ for group_label, reasons, win_info, losers in prepared_groups:
2654
+ reasons_str = ", ".join(reasons) if reasons else "canonical-name"
2655
+ print(f"Group '{group_label}' (matched by: {reasons_str}):")
2656
+ win_item = win_info["item"]
2657
+ print(
2658
+ f" [KEEP] {win_item['name']} ({win_item.get('category', 'General & Utility Skills')}) "
2659
+ f"{self._format_dedupe_meta(win_info)} -> {win_info['dir_path']}"
2660
+ )
2661
+ for cand_info in losers:
2662
+ cand_item = cand_info["item"]
2663
+ print(
2664
+ f" [REMOVE] {cand_item['name']} ({cand_item.get('category', 'General & Utility Skills')}) "
2665
+ f"{self._format_dedupe_meta(cand_info)} -> {cand_info['dir_path']}"
2666
+ )
2667
+ to_remove.append((cand_item, cand_info["dir_path"], win_info["dir_path"]))
2668
+
2669
+ if dry_run:
2670
+ print(f"\n[Dry Run] Would consolidate {len(to_remove)} duplicate skill(s). No files were modified.")
2671
+ return 0
2672
+
2673
+ for cand, cand_dir, winner_dir in to_remove:
2674
+ if cand_dir.exists() and cand_dir.resolve() != winner_dir.resolve():
2675
+ shutil.rmtree(cand_dir)
2676
+ print(f"[Removed] {cand_dir}")
2677
+
2678
+ self.save_manifest(kept_entries)
2679
+ self.reindex()
2680
+ print(f"\n[OK] Consolidated {len(to_remove)} duplicate skill(s).")
2681
+ return 0
2682
+
2683
+ def stats(self, limit=100, as_json=False):
2684
+ """Summarize local background routing telemetry from routing_log.jsonl."""
2685
+ log_file = self.archive_dir / ".state" / "routing_log.jsonl"
2686
+ records = []
2687
+ if log_file.exists():
2688
+ try:
2689
+ lines = [ln for ln in log_file.read_text(encoding="utf-8", errors="replace").splitlines() if ln.strip()]
2690
+ if limit and limit > 0:
2691
+ lines = lines[-limit:]
2692
+ for ln in lines:
2693
+ try:
2694
+ records.append(json.loads(ln))
2695
+ except Exception:
2696
+ pass
2697
+ except OSError:
2698
+ pass
2699
+
2700
+ total = len(records)
2701
+ short_circuited = sum(1 for r in records if r.get("short_circuited"))
2702
+ zero_token = sum(1 for r in records if int(r.get("estimated_tokens", 0)) == 0)
2703
+ matched = [r for r in records if int(r.get("estimated_tokens", 0)) > 0]
2704
+ latencies = sorted(float(r.get("latency_ms", 0.0)) for r in records)
2705
+ avg_latency = round(sum(latencies) / total, 2) if total else 0.0
2706
+ p95_idx = min(len(latencies) - 1, int(len(latencies) * 0.95)) if latencies else 0
2707
+ p95_latency = round(latencies[p95_idx], 2) if latencies else 0.0
2708
+ avg_tokens_matched = round(sum(int(r.get("estimated_tokens", 0)) for r in matched) / len(matched), 1) if matched else 0.0
2709
+ zero_pct = round((zero_token / total) * 100.0, 1) if total else 0.0
2710
+
2711
+ skill_counts = {}
2712
+ for r in records:
2713
+ for s in r.get("matched_inline", []) + r.get("matched_pointers", []):
2714
+ skill_counts[s] = skill_counts.get(s, 0) + 1
2715
+ top_skills = sorted(skill_counts.items(), key=lambda kv: (-kv[1], kv[0]))[:10]
2716
+
2717
+ summary = {
2718
+ "total_turns": total,
2719
+ "short_circuited_turns": short_circuited,
2720
+ "zero_token_turns": zero_token,
2721
+ "zero_token_pct": zero_pct,
2722
+ "matched_turns": len(matched),
2723
+ "avg_tokens_per_matched_turn": avg_tokens_matched,
2724
+ "avg_latency_ms": avg_latency,
2725
+ "p95_latency_ms": p95_latency,
2726
+ "top_skills": [{"name": k, "count": v} for k, v in top_skills],
2727
+ }
2728
+
2729
+ if as_json:
2730
+ print(json.dumps(summary, indent=2))
2731
+ return 0
2732
+
2733
+ print("==================================================")
2734
+ print(" SKILL VAULT ROUTING STATS")
2735
+ print(f" Log File: {log_file}")
2736
+ print("==================================================\n")
2737
+ if total == 0:
2738
+ print("No routing telemetry recorded yet.")
2739
+ return 0
2740
+ print(f" * Total Routed Turns: {total} (short-circuited: {short_circuited})")
2741
+ print(f" * Zero-Token Turns: {zero_token} ({zero_pct}%)")
2742
+ print(f" * Matched Turns: {len(matched)} (avg ~{avg_tokens_matched} tokens)")
2743
+ print(f" * Latency (avg / p95): {avg_latency} ms / {p95_latency} ms")
2744
+ if top_skills:
2745
+ print("\n Top Matched Skills:")
2746
+ for name, cnt in top_skills:
2747
+ print(f" - {name}: {cnt}")
2748
+ print("")
2749
+ return 0
2750
+
2751
+ def _merge_json_config_file(self, cfg_path, mutator_fn, dry_run=False):
2752
+ cfg_path = Path(cfg_path)
2753
+ existing = {}
2754
+ if cfg_path.exists():
2755
+ try:
2756
+ existing = json.loads(cfg_path.read_text(encoding="utf-8", errors="replace"))
2757
+ if not isinstance(existing, dict):
2758
+ existing = {}
2759
+ except Exception:
2760
+ existing = {}
2761
+
2762
+ updated = mutator_fn(json.loads(json.dumps(existing)))
2763
+ if dry_run:
2764
+ return updated
2765
+
2766
+ cfg_path.parent.mkdir(parents=True, exist_ok=True)
2767
+ bak_path = cfg_path.with_suffix(cfg_path.suffix + ".bak")
2768
+ if cfg_path.exists() and not bak_path.exists():
2769
+ shutil.copy2(cfg_path, bak_path)
2770
+ tmp = cfg_path.with_name(f".{cfg_path.name}.{os.getpid()}.tmp")
2771
+ tmp.write_text(json.dumps(updated, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
2772
+ os.replace(tmp, cfg_path)
2773
+ return updated
2774
+
2775
+ @staticmethod
2776
+ def _build_hook_command(py_exe, script_ref, harness, event_name, vault_base_dir):
2777
+ """Build a cmd /c and sh -c safe command string avoiding Windows >2 quote stripping."""
2778
+ py_str = str(py_exe)
2779
+ base_str = str(vault_base_dir)
2780
+ py_token = f'"{py_str}"' if (" " in py_str and not py_str.startswith('"')) else py_str
2781
+ script_token = f'"{script_ref}"' if (" " in str(script_ref) and '"' not in py_token) else str(script_ref)
2782
+ # Never introduce a second quoted pair on Windows cmd /c; vault_link.json carries baseDir when paths have spaces
2783
+ if " " in base_str or '"' in py_token or '"' in script_token:
2784
+ base_flag = ""
2785
+ else:
2786
+ base_flag = f" --base-dir {base_str}"
2787
+ return f"{py_token} {script_token} --harness {harness} --event {event_name}{base_flag}"
2788
+
2789
+ def setup(
2790
+ self,
2791
+ agent="auto",
2792
+ scope="global",
2793
+ dry_run=False,
2794
+ migrate_archive=False,
2795
+ target_dir=None,
2796
+ python_exe=None,
2797
+ ):
2798
+ """Install background hooks, read-only MCP server, and plugin bundle for coding agents."""
2799
+ src_scripts_dir = Path(__file__).resolve().parent
2800
+ required_scripts = ["skill_vault.py", "skill_router.py", "hook_runner.py", "mcp_server.py"]
2801
+ for sname in required_scripts:
2802
+ if not (src_scripts_dir / sname).exists():
2803
+ print(f"[Error] Required script missing: {src_scripts_dir / sname}")
2804
+ return 1
2805
+
2806
+ src_skill_md = None
2807
+ for cand_md in [
2808
+ src_scripts_dir.parent / "SKILL.md",
2809
+ src_scripts_dir.parent / "skills" / "skill-vault" / "SKILL.md",
2810
+ ]:
2811
+ if cand_md.exists():
2812
+ src_skill_md = cand_md
2813
+ break
2814
+
2815
+ py = str(python_exe or sys.executable)
2816
+ home = Path.home()
2817
+ cwd = Path.cwd().resolve()
2818
+
2819
+ if agent == "auto":
2820
+ agents = []
2821
+ if scope == "workspace":
2822
+ if (cwd / ".agents").exists():
2823
+ agents.append("antigravity")
2824
+ if (cwd / ".claude").exists():
2825
+ agents.append("claude")
2826
+ if (cwd / ".gemini").exists():
2827
+ agents.append("gemini-cli")
2828
+ if (cwd / ".cursor").exists():
2829
+ agents.append("cursor")
2830
+ else:
2831
+ if (home / ".gemini" / "config").exists():
2832
+ agents.append("antigravity")
2833
+ if (home / ".claude").exists():
2834
+ agents.append("claude")
2835
+ if (home / ".gemini" / "settings.json").exists():
2836
+ agents.append("gemini-cli")
2837
+ if (home / ".cursor").exists():
2838
+ agents.append("cursor")
2839
+ if not agents:
2840
+ agents = ["antigravity"]
2841
+ else:
2842
+ agents = [agent]
2843
+
2844
+ # Determine canonical vault base directory per scope and target agent
2845
+ home_cfg = home / ".gemini" / "config"
2846
+ legacy_sv = home_cfg / "skills" / "skill-vault"
2847
+ legacy_arch = legacy_sv / "skill_archive"
2848
+ canon_arch = home_cfg / "skill_archive"
2849
+ primary_agent = agents[0]
2850
+
2851
+ if self._explicit_base_dir:
2852
+ vault_base_dir = self.base_dir
2853
+ elif scope == "workspace":
2854
+ ws_existing = [
2855
+ cwd / ".agents",
2856
+ cwd / ".claude",
2857
+ cwd / ".gemini",
2858
+ cwd / ".cursor",
2859
+ cwd,
2860
+ ]
2861
+ found_ws = next((c for c in ws_existing if (c / "skill_archive").exists()), None)
2862
+ if found_ws is not None:
2863
+ vault_base_dir = found_ws
2864
+ elif primary_agent == "claude":
2865
+ vault_base_dir = cwd / ".claude"
2866
+ elif primary_agent == "gemini-cli":
2867
+ vault_base_dir = cwd / ".gemini"
2868
+ elif primary_agent == "cursor":
2869
+ vault_base_dir = (cwd / ".agents") if (cwd / ".agents").exists() else (cwd / ".cursor")
2870
+ else:
2871
+ vault_base_dir = cwd / ".agents"
2872
+ else:
2873
+ if migrate_archive and legacy_arch.exists() and not canon_arch.exists():
2874
+ vault_base_dir = home_cfg
2875
+ else:
2876
+ global_existing = [
2877
+ home_cfg,
2878
+ home / ".claude",
2879
+ home / ".agents",
2880
+ home / ".gemini",
2881
+ home / ".cursor",
2882
+ legacy_sv,
2883
+ ]
2884
+ found_global = next((c for c in global_existing if (c / "skill_archive").exists()), None)
2885
+ if found_global is not None:
2886
+ vault_base_dir = found_global
2887
+ elif primary_agent == "claude":
2888
+ vault_base_dir = home / ".claude"
2889
+ elif primary_agent == "gemini-cli":
2890
+ vault_base_dir = home / ".gemini"
2891
+ elif primary_agent == "cursor":
2892
+ vault_base_dir = home / ".cursor"
2893
+ else:
2894
+ vault_base_dir = home_cfg
2895
+
2896
+ print("==================================================")
2897
+ print(" SKILL VAULT ORCHESTRATION SETUP")
2898
+ print(f" Target Agent(s): {', '.join(agents)}")
2899
+ print(f" Scope: {scope}")
2900
+ print(f" Vault Base: {vault_base_dir}")
2901
+ print(f" Python Runtime: {py}")
2902
+ print("==================================================\n")
2903
+
2904
+ # Handle archive migration if requested
2905
+ will_migrate = (
2906
+ migrate_archive
2907
+ and scope == "global"
2908
+ and not self._explicit_base_dir
2909
+ and legacy_arch.exists()
2910
+ and not canon_arch.exists()
2911
+ )
2912
+ if will_migrate:
2913
+ print(f"[Migration Plan] {legacy_arch} -> {canon_arch}")
2914
+ print(f" Verify integrity before removing legacy {legacy_sv}\n")
2915
+ if not dry_run:
2916
+ src_count = len(SkillVault(base_dir=str(legacy_sv)).get_archived_skill_folders())
2917
+ shutil.copytree(legacy_arch, canon_arch, dirs_exist_ok=True)
2918
+ migrated_mgr = SkillVault(base_dir=str(home_cfg))
2919
+ if migrated_mgr.verify(fix=False) != 0:
2920
+ print("[Error] Archive migration verification failed! Legacy archive preserved untouched.")
2921
+ return 1
2922
+ dst_count = len(migrated_mgr.get_archived_skill_folders())
2923
+ if dst_count < src_count:
2924
+ print(f"[Error] Migrated skill count ({dst_count}) < source ({src_count}). Legacy archive preserved untouched.")
2925
+ return 1
2926
+ if legacy_sv.exists():
2927
+ shutil.rmtree(legacy_sv)
2928
+ print(f"[Migrated] Verified {dst_count} skill(s) at {canon_arch} and removed legacy {legacy_sv}\n")
2929
+
2930
+ # Ensure vault archive exists
2931
+ if not dry_run:
2932
+ vault_base_dir.mkdir(parents=True, exist_ok=True)
2933
+ vault_mgr = SkillVault(base_dir=str(vault_base_dir))
2934
+ if not dry_run and not vault_mgr.archive_dir.exists():
2935
+ vault_mgr.init()
2936
+
2937
+ for target_agent in agents:
2938
+ if target_agent == "antigravity":
2939
+ if target_dir:
2940
+ td = Path(target_dir).resolve()
2941
+ if td.name == "skill-vault":
2942
+ plugin_dir = td
2943
+ elif td.name == "plugins":
2944
+ plugin_dir = td / "skill-vault"
2945
+ else:
2946
+ plugin_dir = td / "plugins" / "skill-vault"
2947
+ elif scope == "workspace":
2948
+ plugin_dir = cwd / ".agents" / "plugins" / "skill-vault"
2949
+ else:
2950
+ plugin_dir = home_cfg / "plugins" / "skill-vault"
2951
+
2952
+ hooks_payload = {
2953
+ "skill-vault-session-sync": {
2954
+ "SessionStart": [
2955
+ {
2956
+ "type": "command",
2957
+ "command": self._build_hook_command(
2958
+ py, "scripts/hook_runner.py", "antigravity", "SessionStart", vault_base_dir
2959
+ ),
2960
+ "timeout": 30,
2961
+ }
2962
+ ]
2963
+ },
2964
+ "skill-vault-jit-router": {
2965
+ "PreInvocation": [
2966
+ {
2967
+ "type": "command",
2968
+ "command": self._build_hook_command(
2969
+ py, "scripts/hook_runner.py", "antigravity", "PreInvocation", vault_base_dir
2970
+ ),
2971
+ "timeout": 10,
2972
+ }
2973
+ ]
2974
+ },
2975
+ }
2976
+ mcp_payload = {
2977
+ "mcpServers": {
2978
+ "skill-vault": {
2979
+ "command": py,
2980
+ "type": "stdio",
2981
+ "args": ["scripts/mcp_server.py"],
2982
+ "env": {"SKILL_VAULT_BASE": str(vault_base_dir)},
2983
+ }
2984
+ }
2985
+ }
2986
+ plugin_meta = {
2987
+ "name": "skill-vault",
2988
+ "displayName": "Skill Vault",
2989
+ "version": "2.0.1",
2990
+ "description": "Automatic background skill router, cold-storage archive, and read-only JIT MCP server.",
2991
+ "author": "jcorpac",
2992
+ "license": "MIT",
2993
+ }
2994
+
2995
+ print(f"[Antigravity Plugin] Target: {plugin_dir}")
2996
+ if dry_run:
2997
+ print(f" * Would install scripts: {', '.join(required_scripts)}")
2998
+ print(" * Would write plugin.json, hooks.json, mcp_config.json, vault_link.json, skills/skill-vault/SKILL.md")
2999
+ else:
3000
+ scripts_dest = plugin_dir / "scripts"
3001
+ scripts_dest.mkdir(parents=True, exist_ok=True)
3002
+ for sname in required_scripts:
3003
+ shutil.copy2(src_scripts_dir / sname, scripts_dest / sname)
3004
+
3005
+ if src_skill_md and src_skill_md.exists():
3006
+ dest_md_dir = plugin_dir / "skills" / "skill-vault"
3007
+ dest_md_dir.mkdir(parents=True, exist_ok=True)
3008
+ shutil.copy2(src_skill_md, dest_md_dir / "SKILL.md")
3009
+
3010
+ (plugin_dir / "plugin.json").write_text(json.dumps(plugin_meta, indent=2) + "\n", encoding="utf-8")
3011
+ (plugin_dir / "hooks.json").write_text(json.dumps(hooks_payload, indent=2) + "\n", encoding="utf-8")
3012
+ (plugin_dir / "mcp_config.json").write_text(json.dumps(mcp_payload, indent=2) + "\n", encoding="utf-8")
3013
+ (plugin_dir / "vault_link.json").write_text(json.dumps({"baseDir": str(vault_base_dir)}, indent=2) + "\n", encoding="utf-8")
3014
+ print(f" [OK] Installed Antigravity plugin bundle to {plugin_dir}")
3015
+
3016
+ elif target_agent in ("claude", "gemini-cli", "cursor"):
3017
+ # Stage permanent runtime scripts inside archive/.runtime so npx/temp paths never break
3018
+ runtime_dir = vault_mgr.archive_dir / ".runtime" / "scripts"
3019
+ hook_script = runtime_dir / "hook_runner.py"
3020
+ mcp_script = runtime_dir / "mcp_server.py"
3021
+ if not dry_run:
3022
+ runtime_dir.mkdir(parents=True, exist_ok=True)
3023
+ for sname in required_scripts:
3024
+ shutil.copy2(src_scripts_dir / sname, runtime_dir / sname)
3025
+ (runtime_dir.parent / "vault_link.json").write_text(
3026
+ json.dumps({"baseDir": str(vault_base_dir)}, indent=2) + "\n", encoding="utf-8"
3027
+ )
3028
+
3029
+ if target_agent == "claude":
3030
+ cfg_file = Path(target_dir).resolve() if target_dir else (
3031
+ (cwd / ".claude" / "settings.json") if scope == "workspace" else (home / ".claude" / "settings.json")
3032
+ )
3033
+ evt_name = "UserPromptSubmit"
3034
+ elif target_agent == "gemini-cli":
3035
+ cfg_file = Path(target_dir).resolve() if target_dir else (
3036
+ (cwd / ".gemini" / "settings.json") if scope == "workspace" else (home / ".gemini" / "settings.json")
3037
+ )
3038
+ evt_name = "BeforeAgent"
3039
+ else:
3040
+ cfg_file = Path(target_dir).resolve() if target_dir else (
3041
+ (cwd / ".cursor" / "mcp.json") if scope == "workspace" else (home / ".cursor" / "mcp.json")
3042
+ )
3043
+ evt_name = None
3044
+
3045
+ def _mutate(cfg):
3046
+ mcp_servers = cfg.setdefault("mcpServers", {})
3047
+ mcp_servers["skill-vault"] = {
3048
+ "command": py,
3049
+ "args": [str(mcp_script), "--base-dir", str(vault_base_dir)],
3050
+ "env": {"SKILL_VAULT_BASE": str(vault_base_dir)},
3051
+ }
3052
+ if evt_name:
3053
+ hooks = cfg.setdefault("hooks", {})
3054
+ for hook_ev in ("SessionStart", evt_name):
3055
+ groups = [
3056
+ g for g in hooks.get(hook_ev, [])
3057
+ if not any(
3058
+ "hook_runner.py" in str(h.get("command", "")) or "skill-vault" in str(h.get("command", ""))
3059
+ for h in (g.get("hooks", []) if isinstance(g, dict) else [])
3060
+ )
3061
+ ]
3062
+ groups.append({
3063
+ "matcher": "",
3064
+ "hooks": [{
3065
+ "type": "command",
3066
+ "command": self._build_hook_command(
3067
+ py, str(hook_script), target_agent, hook_ev, vault_base_dir
3068
+ ),
3069
+ }],
3070
+ })
3071
+ hooks[hook_ev] = groups
3072
+ return cfg
3073
+
3074
+ print(f"[{target_agent}] Config: {cfg_file}")
3075
+ self._merge_json_config_file(cfg_file, _mutate, dry_run=dry_run)
3076
+ if dry_run:
3077
+ print(f" * Would merge hooks/MCP into {cfg_file}")
3078
+ else:
3079
+ print(f" [OK] Updated {cfg_file}")
3080
+ else:
3081
+ print(f"[Error] Unsupported agent '{target_agent}'.")
3082
+ return 1
3083
+
3084
+ if dry_run:
3085
+ print("\n[Dry Run] Setup preview complete. No files were modified.")
3086
+ return 0
3087
+
3088
+ # Enable compact router prompt & rebuild search_index.json
3089
+ raw_cfg = vault_mgr._load_raw_config()
3090
+ routing_map = dict(raw_cfg.get("routing", {}))
3091
+ routing_map["compact_router_prompt"] = True
3092
+ raw_cfg["routing"] = routing_map
3093
+ vault_mgr.save_config(raw_cfg)
3094
+ vault_mgr.reindex()
3095
+ if "antigravity" in agents:
3096
+ vault_mgr.sync_router_md(target_skill_md=plugin_dir / "skills" / "skill-vault" / "SKILL.md", force=True)
3097
+
3098
+ print("\n[OK] Skill Vault background orchestration is configured and ready.")
3099
+ return 0
3100
+
1974
3101
  # --- Project Import Engine ---
1975
3102
 
1976
3103
  def resolve_vault_archive_dir(self, vault_arg=None):
@@ -2001,13 +3128,15 @@ class SkillVault:
2001
3128
  ):
2002
3129
  return self.archive_dir
2003
3130
 
2004
- # Check standard global locations
3131
+ # Check standard global locations (canonical ~/.gemini/config/skill_archive first)
2005
3132
  candidates = [
3133
+ Path.home() / ".gemini" / "config" / "skill_archive",
2006
3134
  Path.home() / ".gemini" / "config" / "skills" / "skill-vault" / "skill_archive",
2007
3135
  Path.home() / ".gemini" / "config" / "skills" / ".skill_archive",
2008
- Path.home() / ".gemini" / "config" / "skill_archive",
2009
3136
  Path.home() / ".agents" / "skill_archive",
2010
3137
  Path.home() / ".claude" / "skill_archive",
3138
+ Path.home() / ".gemini" / "skill_archive",
3139
+ Path.home() / ".cursor" / "skill_archive",
2011
3140
  ]
2012
3141
  for cand in candidates:
2013
3142
  if cand.exists() and (
@@ -2228,9 +3357,11 @@ def main():
2228
3357
  p_arch.add_argument("--force", action="store_true", help="Force overwrite in archive regardless of recency")
2229
3358
 
2230
3359
  # 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")
3360
+ p_rec = subparsers.add_parser("recategorize", help="Recategorize an archived skill in metadata or auto-recategorize General skills")
3361
+ p_rec.add_argument("name", nargs="?", help="Skill name")
3362
+ p_rec.add_argument("category", nargs="?", help="New category name")
3363
+ p_rec.add_argument("--auto", action="store_true", help="Auto-recategorize skills in 'General & Utility Skills'")
3364
+ p_rec.add_argument("--dry-run", action="store_true", help="Preview auto-recategorization without modifying manifest")
2234
3365
 
2235
3366
  # Restore
2236
3367
  p_rest = subparsers.add_parser("restore", help="Restore archived skills back to active availability")
@@ -2241,7 +3372,7 @@ def main():
2241
3372
  p_rest.add_argument("--force", action="store_true", help="Overwrite existing active directory")
2242
3373
 
2243
3374
  # Reindex
2244
- p_idx = subparsers.add_parser("reindex", help="Rebuild INDEX.md and sync manifest")
3375
+ p_idx = subparsers.add_parser("reindex", help="Rebuild INDEX.md, search_index.json, and sync manifest")
2245
3376
 
2246
3377
  # Verify / Integrity Check
2247
3378
  p_ver = subparsers.add_parser("verify", help="Verify archive integrity across disk, manifest, and index")
@@ -2249,7 +3380,51 @@ def main():
2249
3380
 
2250
3381
  # Search
2251
3382
  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")
3383
+ p_srch.add_argument("query", help="Keyword or natural-language query to search for")
3384
+ p_srch.add_argument("--category", help="Filter search results by category")
3385
+ p_srch.add_argument("--limit", type=int, default=10, help="Maximum number of results to show")
3386
+ p_srch.add_argument("--json", action="store_true", help="Output structured JSON")
3387
+
3388
+ # Route (dry-run JIT router debugger)
3389
+ p_route = subparsers.add_parser("route", help="Dry-run the background JIT skill router against a prompt")
3390
+ p_route.add_argument("prompt", help="User prompt to evaluate")
3391
+ p_route.add_argument("--workspace", help="Optional workspace path for soft stack tie-breaking")
3392
+ p_route.add_argument("--mode", choices=["hybrid", "inline", "pointer"], help="Override routing mode")
3393
+ p_route.add_argument("--json", action="store_true", help="Output structured JSON")
3394
+
3395
+ # Dedupe
3396
+ p_dedupe = subparsers.add_parser(
3397
+ "dedupe",
3398
+ help="Consolidate duplicate skills in archive (canonical name, frontmatter name, or identical content), keeping the newest version",
3399
+ )
3400
+ p_dedupe.add_argument("--dry-run", action="store_true", help="Preview duplicates without deleting files")
3401
+
3402
+ # Stats
3403
+ p_stats = subparsers.add_parser("stats", help="Show local background routing telemetry summary")
3404
+ p_stats.add_argument("--limit", type=int, default=100, help="Inspect most recent N turns")
3405
+ p_stats.add_argument("--json", action="store_true", help="Output structured JSON")
3406
+
3407
+ # Setup
3408
+ p_setup = subparsers.add_parser("setup", help="Install background hooks, MCP server, and plugin wiring")
3409
+ p_setup.add_argument(
3410
+ "--agent",
3411
+ choices=["auto", "antigravity", "claude", "gemini-cli", "cursor"],
3412
+ default="auto",
3413
+ help="Target agent harness (default: auto)",
3414
+ )
3415
+ p_setup.add_argument(
3416
+ "--scope",
3417
+ choices=["global", "workspace"],
3418
+ default="global",
3419
+ help="Install globally or inside current workspace",
3420
+ )
3421
+ p_setup.add_argument("--dry-run", action="store_true", help="Preview installation plan without modifying files")
3422
+ p_setup.add_argument(
3423
+ "--migrate-archive",
3424
+ action="store_true",
3425
+ help="Safely migrate legacy ~/.gemini/config/skills/skill-vault/skill_archive to ~/.gemini/config/skill_archive",
3426
+ )
3427
+ p_setup.add_argument("--target-dir", help="Explicit target plugin directory or config file path")
2253
3428
 
2254
3429
  # Sync
2255
3430
  p_sync = subparsers.add_parser("sync", help="Scan plugins and active skills, ingest new/updated skills, and prune non-core skills")
@@ -2277,6 +3452,7 @@ def main():
2277
3452
  p_cfg.add_argument("--remove-core", nargs="+", metavar="SKILL", help="Remove one or more skills from protected core skills")
2278
3453
  p_cfg.add_argument("--add-fingerprint", nargs=2, action="append", metavar=("CATEGORY", "PATTERN"), help="Add a workspace file/glob fingerprint for a category")
2279
3454
  p_cfg.add_argument("--add-category-rule", nargs=2, action="append", metavar=("CATEGORY", "KEYWORD"), help="Add an inference keyword rule for a category")
3455
+ p_cfg.add_argument("--set-routing", nargs=2, action="append", metavar=("KEY", "VALUE"), help="Set a routing configuration option (e.g. mode hybrid)")
2280
3456
  p_cfg.add_argument("--sync-prompt", action="store_true", help="Synchronize SKILL.md router description with archived categories")
2281
3457
 
2282
3458
  # Uninstall / Eject
@@ -2326,7 +3502,7 @@ def main():
2326
3502
  elif args.command == "archive":
2327
3503
  mgr.archive(name=args.name, pattern=args.pattern, category=args.category, keep_active=args.keep_active, force=args.force)
2328
3504
  elif args.command == "recategorize":
2329
- mgr.recategorize(name=args.name, new_category=args.category)
3505
+ sys.exit(mgr.recategorize(name=args.name, new_category=args.category, auto=args.auto, dry_run=args.dry_run))
2330
3506
  elif args.command == "restore":
2331
3507
  mgr.restore(name=args.name, pattern=args.pattern, category=args.category, restore_all=args.all, force=args.force)
2332
3508
  elif args.command == "reindex":
@@ -2334,7 +3510,23 @@ def main():
2334
3510
  elif args.command == "verify":
2335
3511
  sys.exit(mgr.verify(fix=args.fix))
2336
3512
  elif args.command == "search":
2337
- mgr.search(query=args.query)
3513
+ mgr.search(query=args.query, category=args.category, limit=args.limit, as_json=args.json)
3514
+ elif args.command == "route":
3515
+ sys.exit(mgr.route(prompt=args.prompt, workspace_path=args.workspace, mode=args.mode, as_json=args.json))
3516
+ elif args.command == "dedupe":
3517
+ sys.exit(mgr.dedupe(dry_run=args.dry_run))
3518
+ elif args.command == "stats":
3519
+ sys.exit(mgr.stats(limit=args.limit, as_json=args.json))
3520
+ elif args.command == "setup":
3521
+ sys.exit(
3522
+ mgr.setup(
3523
+ agent=args.agent,
3524
+ scope=args.scope,
3525
+ dry_run=args.dry_run,
3526
+ migrate_archive=args.migrate_archive,
3527
+ target_dir=args.target_dir,
3528
+ )
3529
+ )
2338
3530
  elif args.command == "import":
2339
3531
  sys.exit(
2340
3532
  mgr.import_skills(
@@ -2356,6 +3548,7 @@ def main():
2356
3548
  remove_core=args.remove_core,
2357
3549
  add_fingerprint=args.add_fingerprint,
2358
3550
  add_category_rule=args.add_category_rule,
3551
+ set_routing=args.set_routing,
2359
3552
  sync_prompt=args.sync_prompt,
2360
3553
  )
2361
3554
  elif args.command in ("uninstall", "eject"):