@jcorpac/skill-vault 1.7.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",
@@ -334,7 +406,14 @@ def get_skill_metadata(skill_dir):
334
406
 
335
407
  latest_mtime = 0.0
336
408
  try:
337
- files = [f for f in skill_dir.rglob("*") if f.is_file()]
409
+ files = []
410
+ if skill_dir.exists():
411
+ for root, dirs, filenames in os.walk(skill_dir):
412
+ root_path = Path(root)
413
+ # Do not bleed mtimes from nested sibling skill folders inside a single_skill_dir
414
+ dirs[:] = [d for d in dirs if not (root_path / d / "SKILL.md").exists()]
415
+ for fname in filenames:
416
+ files.append(root_path / fname)
338
417
  if files:
339
418
  latest_mtime = max(f.stat().st_mtime for f in files)
340
419
  elif skill_dir.exists():
@@ -380,26 +459,42 @@ def resolve_base_dir(cli_base=None):
380
459
  if p.exists():
381
460
  return p
382
461
 
383
- # Check ancestors of the script location
462
+ # 1. Prioritize ancestors of the script location that actually contain a skill_archive
384
463
  script_path = Path(__file__).resolve()
385
464
  for parent in script_path.parents:
386
- if parent.name != "skill_archive" and (
387
- (parent / "skill_archive").exists() or (parent / "skills").exists()
388
- ):
465
+ if parent.name != "skill_archive" and (parent / "skill_archive").exists():
389
466
  return parent
390
467
 
391
468
  cwd = Path.cwd().resolve()
392
- for candidate in [
469
+ home = Path.home()
470
+ candidates = [
393
471
  cwd,
394
472
  cwd / ".agents",
395
473
  cwd / ".claude",
396
- Path.home() / ".gemini" / "config",
397
- Path.home() / ".agents",
398
- Path.home() / ".claude",
399
- ]:
400
- if candidate.exists() and (
401
- (candidate / "skills").exists() or (candidate / "skill_archive").exists()
402
- ):
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():
403
498
  return candidate
404
499
 
405
500
  return cwd
@@ -407,10 +502,12 @@ def resolve_base_dir(cli_base=None):
407
502
 
408
503
  class SkillVault:
409
504
  def __init__(self, base_dir=None):
505
+ self._explicit_base_dir = bool(base_dir)
410
506
  self.base_dir = resolve_base_dir(base_dir)
411
507
  self.archive_dir = self.base_dir / "skill_archive"
412
508
  self.manifest_file = self.archive_dir / "backup_manifest.json"
413
509
  self.index_file = self.archive_dir / "INDEX.md"
510
+ self.search_index_file = self.archive_dir / "search_index.json"
414
511
  self.config_file = self.archive_dir / "vault_config.json"
415
512
  self.skills_dir = self.base_dir / "skills"
416
513
 
@@ -452,11 +549,16 @@ class SkillVault:
452
549
  if cat not in merged_rules:
453
550
  merged_rules[cat] = list(kws)
454
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
+
455
556
  return {
456
557
  "core_skills": sorted(core_skills),
457
558
  "disabled_core_skills": sorted(disabled_core),
458
559
  "workspace_fingerprints": merged_fp,
459
560
  "category_rules": merged_rules,
561
+ "routing": routing_cfg,
460
562
  }
461
563
 
462
564
  def save_config(self, config_data):
@@ -619,13 +721,22 @@ class SkillVault:
619
721
  for folder in base.iterdir():
620
722
  if folder.is_dir():
621
723
  skill_md = folder / "SKILL.md"
622
- folders[folder.name] = {
724
+ has_md = skill_md.exists()
725
+ candidate = {
623
726
  "name": folder.name,
624
727
  "folder": folder,
625
728
  "skill_md": skill_md,
626
- "has_skill_md": skill_md.exists(),
627
- "size": skill_md.stat().st_size if skill_md.exists() else 0,
729
+ "has_skill_md": has_md,
730
+ "size": skill_md.stat().st_size if has_md else 0,
628
731
  }
732
+ existing = folders.get(folder.name)
733
+ if existing is None:
734
+ folders[folder.name] = candidate
735
+ elif has_md and (
736
+ not existing["has_skill_md"]
737
+ or compare_skill_recency(folder, existing["folder"]) > 0
738
+ ):
739
+ folders[folder.name] = candidate
629
740
  return folders
630
741
 
631
742
  def load_manifest(self):
@@ -678,11 +789,83 @@ class SkillVault:
678
789
  return target
679
790
  return None
680
791
 
792
+ def get_root_dir(self):
793
+ """Return the top-level environment or workspace root directory.
794
+
795
+ When base_dir is an installed skill directory nested inside 'skills/skill-vault',
796
+ returns the parent of 'skills' (e.g. ~/.gemini/config or workspace root).
797
+ """
798
+ if self.base_dir.name == "skill-vault" and self.base_dir.parent.name == "skills":
799
+ return self.base_dir.parent.parent
800
+ return self.base_dir
801
+
802
+ def get_skill_vault_dir(self):
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"):
805
+ if not (self.base_dir / ".git").exists():
806
+ return self.base_dir
807
+ root_dir = self.get_root_dir()
808
+ for rel in [
809
+ "plugins/skill-vault",
810
+ "skills/skill-vault",
811
+ ".agents/skills/skill-vault",
812
+ ".claude/skills/skill-vault",
813
+ ]:
814
+ cand = (root_dir / rel).resolve()
815
+ if cand.exists() and not (cand / ".git").exists():
816
+ return cand
817
+ return None
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
+
681
857
  def make_portable_path(self, abs_path):
682
- """Convert path to relative from base_dir if possible."""
858
+ """Convert path to relative from base_dir or root_dir if possible."""
859
+ resolved = Path(abs_path).resolve()
683
860
  try:
684
- return str(Path(abs_path).resolve().relative_to(self.base_dir))
861
+ return str(resolved.relative_to(self.base_dir))
685
862
  except ValueError:
863
+ root_dir = self.get_root_dir()
864
+ if root_dir != self.base_dir:
865
+ try:
866
+ return str(resolved.relative_to(root_dir))
867
+ except ValueError:
868
+ pass
686
869
  return str(abs_path)
687
870
 
688
871
  def resolve_portable_path(self, path_str):
@@ -690,7 +873,69 @@ class SkillVault:
690
873
  p = Path(path_str)
691
874
  if p.is_absolute():
692
875
  return p
693
- return (self.base_dir / p).resolve()
876
+ cand = (self.base_dir / p).resolve()
877
+ if not cand.exists():
878
+ root_dir = self.get_root_dir()
879
+ if root_dir != self.base_dir:
880
+ root_cand = (root_dir / p).resolve()
881
+ if root_cand.exists():
882
+ return root_cand
883
+ return cand
884
+
885
+ def resolve_original_path(self, path_str, skill_name=None):
886
+ """Resolve a stored original_path to an active L1 Path outside skills/skill-vault."""
887
+ root_dir = self.get_root_dir()
888
+ sv_dir = self.get_skill_vault_dir()
889
+ if not path_str:
890
+ skills_root = root_dir / "skills" if root_dir != self.base_dir else self.skills_dir
891
+ return (skills_root / (skill_name or "unknown-skill")).resolve()
892
+
893
+ p = Path(path_str)
894
+ if p.is_absolute():
895
+ resolved = p.resolve()
896
+ if sv_dir and (sv_dir in resolved.parents or resolved == sv_dir):
897
+ try:
898
+ rel = resolved.relative_to(sv_dir)
899
+ return (root_dir / rel).resolve()
900
+ except ValueError:
901
+ pass
902
+ return resolved
903
+
904
+ return (root_dir / p).resolve()
905
+
906
+ def _copy_skill_safely(self, src_dir, dst_dir):
907
+ """Copy a skill folder from src_dir to dst_dir without deleting nested sibling skills."""
908
+ src_dir = Path(src_dir).resolve()
909
+ dst_dir = Path(dst_dir).resolve()
910
+ dst_dir.parent.mkdir(parents=True, exist_ok=True)
911
+
912
+ def _ignore_nested_skills(curr_dir, names):
913
+ curr_path = Path(curr_dir).resolve()
914
+ if curr_path == src_dir:
915
+ return [
916
+ n for n in names
917
+ if (curr_path / n).is_dir() and (curr_path / n / "SKILL.md").exists()
918
+ ]
919
+ return []
920
+
921
+ if dst_dir.exists():
922
+ nested_skill_dirs = {
923
+ sub.name for sub in dst_dir.iterdir()
924
+ if sub.is_dir() and (sub / "SKILL.md").exists()
925
+ }
926
+ if nested_skill_dirs or dst_dir.name == "skills":
927
+ for item in list(dst_dir.iterdir()):
928
+ if item.name in nested_skill_dirs:
929
+ continue
930
+ if item.is_dir():
931
+ shutil.rmtree(item)
932
+ else:
933
+ item.unlink()
934
+ shutil.copytree(src_dir, dst_dir, dirs_exist_ok=True, ignore=_ignore_nested_skills)
935
+ return
936
+ shutil.rmtree(dst_dir)
937
+
938
+ shutil.copytree(src_dir, dst_dir, dirs_exist_ok=True, ignore=_ignore_nested_skills)
694
939
 
695
940
  def parse_index_file(self):
696
941
  """Parse INDEX.md and return extracted skills with categories and link targets."""
@@ -730,43 +975,55 @@ class SkillVault:
730
975
  # --- Workspace & Optimization Engine ---
731
976
 
732
977
  def detect_workspace_categories(self, workspace_path=None):
733
- """Inspect workspace files and return matched skill categories."""
978
+ """Inspect workspace files in a single depth-bounded pass and return matched skill categories."""
734
979
  target_ws = Path(workspace_path).resolve() if workspace_path else Path.cwd().resolve()
735
980
  matched = {}
736
981
  config = self.load_config()
737
982
  fingerprints = config["workspace_fingerprints"]
738
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
+
739
1008
  for category, patterns in fingerprints.items():
740
1009
  for pat in patterns:
741
- if "*" in pat:
742
- matches = list(target_ws.glob(pat)) + list(target_ws.glob(f"**/{pat}"))[:5]
743
- if matches:
744
- matched.setdefault(category, []).append(pat)
745
- 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
+ )
746
1015
  else:
747
- if (target_ws / pat).exists() or list(target_ws.glob(f"**/{pat}"))[:1]:
748
- matched.setdefault(category, []).append(pat)
749
- 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
750
1020
 
751
1021
  # Inspect categories present in manifest for workspace filename/directory keyword matches
752
1022
  manifest = self.load_manifest()
753
1023
  manifest_categories = {m.get("category") for m in manifest if m.get("category")}
754
1024
  unmatched_cats = [c for c in sorted(manifest_categories) if c not in matched]
755
- if unmatched_cats and target_ws.exists():
1025
+ if unmatched_cats:
756
1026
  stop_words = {"and", "the", "skills", "general", "utility"}
757
- ignored_dirs = {".git", "node_modules", "__pycache__", ".venv", "venv", ".tox", "dist", "build"}
758
- ws_tokens = {}
759
- for root, dirs, files in os.walk(target_ws):
760
- dirs[:] = [d for d in dirs if d not in ignored_dirs]
761
- rel_depth = len(Path(root).relative_to(target_ws).parts)
762
- if rel_depth > 3:
763
- dirs[:] = []
764
- continue
765
- for entry_name in dirs + files:
766
- tokens = {t for t in re.split(r"[-_.\s]+", entry_name.lower()) if t}
767
- for tok in tokens:
768
- ws_tokens.setdefault(tok, entry_name)
769
-
770
1027
  for cat in unmatched_cats:
771
1028
  words = [
772
1029
  w.lower()
@@ -788,6 +1045,7 @@ class SkillVault:
788
1045
  """
789
1046
  target_ws = Path(workspace_path).resolve() if workspace_path else Path.cwd().resolve()
790
1047
  core_set = self.get_core_skills(protected_skills)
1048
+ hook_protected = self.get_hook_protected_skills()
791
1049
 
792
1050
  print("==================================================")
793
1051
  print(" SKILL VAULT AUTO-OPTIMIZATION")
@@ -816,6 +1074,8 @@ class SkillVault:
816
1074
  skill_md_path = Path(data["path"]) / "SKILL.md"
817
1075
  if name in core_set:
818
1076
  to_keep.append((name, "Core Foundation Skill"))
1077
+ elif name in hook_protected:
1078
+ to_keep.append((name, "Protected Plugin Hook/MCP Dependency"))
819
1079
  elif self.is_core_skill_frontmatter(skill_md_path):
820
1080
  to_keep.append((name, "Core Foundation Skill (Pinned in Frontmatter)"))
821
1081
  else:
@@ -907,14 +1167,7 @@ class SkillVault:
907
1167
  if explicit_cat:
908
1168
  return explicit_cat
909
1169
 
910
- if skill_name in self.get_core_skills() or skill_name in [
911
- "gmail",
912
- "gcalendar",
913
- "gslides",
914
- "gdocs",
915
- "gdrive",
916
- "gsheets",
917
- ]:
1170
+ if skill_name in self.get_core_skills():
918
1171
  return "General & Utility Skills"
919
1172
 
920
1173
  rules = self.load_config()["category_rules"]
@@ -938,6 +1191,7 @@ class SkillVault:
938
1191
  print("==================================================\n")
939
1192
 
940
1193
  core_set = self.get_core_skills(protect_skills)
1194
+ hook_protected = self.get_hook_protected_skills()
941
1195
 
942
1196
  active_skills = self.get_active_skills()
943
1197
  manifest = self.load_manifest()
@@ -948,6 +1202,7 @@ class SkillVault:
948
1202
  to_prune = []
949
1203
  in_sync = []
950
1204
  retained_core = []
1205
+ protected_hooks = []
951
1206
 
952
1207
  for name, data in sorted(active_skills.items()):
953
1208
  if name == "skill-vault":
@@ -957,6 +1212,7 @@ class SkillVault:
957
1212
  active_path = Path(data["path"])
958
1213
  skill_md_path = active_path / "SKILL.md"
959
1214
  is_core = (name in core_set) or self.is_core_skill_frontmatter(skill_md_path)
1215
+ is_hook_dep = name in hook_protected
960
1216
 
961
1217
  if name in manifest_map:
962
1218
  item = manifest_map[name]
@@ -981,6 +1237,8 @@ class SkillVault:
981
1237
 
982
1238
  if is_core:
983
1239
  retained_core.append(name)
1240
+ elif is_hook_dep:
1241
+ protected_hooks.append(name)
984
1242
  elif not keep_active:
985
1243
  to_prune.append((name, data))
986
1244
 
@@ -995,6 +1253,10 @@ class SkillVault:
995
1253
 
996
1254
  print(f" * In-sync skills in vault: {len(in_sync)}")
997
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}")
998
1260
  print(f" * Non-core active skills to prune: {len(to_prune)}")
999
1261
  for name, _ in to_prune:
1000
1262
  print(f" [PRUNE] {name} (Will be removed from active context to prevent context bloat)")
@@ -1036,6 +1298,8 @@ class SkillVault:
1036
1298
  if data.get("single_skill_dir"):
1037
1299
  for sub in active_path.iterdir():
1038
1300
  if sub.is_dir():
1301
+ if (sub / "SKILL.md").exists():
1302
+ continue
1039
1303
  shutil.rmtree(sub)
1040
1304
  else:
1041
1305
  sub.unlink()
@@ -1145,6 +1409,7 @@ class SkillVault:
1145
1409
  """Archive active skills with an assigned category, prioritizing newer versions."""
1146
1410
  manifest = self.load_manifest()
1147
1411
  manifest_map = {item["name"]: item for item in manifest}
1412
+ hook_protected = self.get_hook_protected_skills()
1148
1413
 
1149
1414
  skills_to_archive = []
1150
1415
  if name:
@@ -1176,8 +1441,11 @@ class SkillVault:
1176
1441
  if recency < 0 and not force:
1177
1442
  print(f"[Skip] L2 archive '{skill_name}' is newer than active L1 version. Preserving newer archive (use --force to overwrite).")
1178
1443
  if not keep_active:
1179
- shutil.rmtree(active_path)
1180
- 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}")
1181
1449
  continue
1182
1450
  elif recency > 0:
1183
1451
  print(f"[Archived] Overwriting older L2 archive with newer active L1 version: {active_path} -> {dest_dir}")
@@ -1206,27 +1474,70 @@ class SkillVault:
1206
1474
  }
1207
1475
 
1208
1476
  if not keep_active:
1209
- shutil.rmtree(active_path)
1210
- 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}")
1211
1482
 
1212
1483
  self.save_manifest(list(manifest_map.values()))
1213
1484
  self.reindex()
1214
1485
  print("Archiving complete.")
1215
1486
 
1216
- def recategorize(self, name, new_category):
1217
- """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."""
1218
1489
  manifest = self.load_manifest()
1219
1490
  manifest_map = {item["name"]: item for item in manifest}
1220
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
+
1221
1531
  if name not in manifest_map:
1222
1532
  print(f"[Error] Skill '{name}' not found in manifest.")
1223
- return
1533
+ return 1
1224
1534
 
1225
1535
  old_cat = manifest_map[name].get("category", "Uncategorized")
1226
1536
  manifest_map[name]["category"] = new_category.strip()
1227
1537
  self.save_manifest(list(manifest_map.values()))
1228
1538
  self.reindex()
1229
1539
  print(f"[Recategorized] '{name}': '{old_cat}' -> '{new_category.strip()}'")
1540
+ return 0
1230
1541
 
1231
1542
  def restore(self, name=None, pattern=None, category=None, restore_all=False, force=False):
1232
1543
  """Restore archived skills back to active locations."""
@@ -1250,31 +1561,324 @@ class SkillVault:
1250
1561
  print("No matching skills found to restore.")
1251
1562
  return
1252
1563
 
1564
+ disk_skills = self.get_archived_skill_folders()
1565
+
1253
1566
  for item in targets:
1254
- archived_path = self.resolve_portable_path(item["archived_path"])
1255
- original_path = self.resolve_portable_path(item["original_path"])
1567
+ skill_name = item["name"]
1568
+ archived_path = self.resolve_portable_path(item.get("archived_path", ""))
1569
+ disk_cand = disk_skills.get(skill_name)
1570
+ if disk_cand and disk_cand["has_skill_md"]:
1571
+ if not (archived_path / "SKILL.md").exists() or compare_skill_recency(disk_cand["folder"], archived_path) > 0:
1572
+ archived_path = disk_cand["folder"]
1256
1573
 
1257
- if not archived_path.exists():
1574
+ original_path = self.resolve_original_path(item.get("original_path", ""), skill_name=skill_name)
1575
+
1576
+ if not (archived_path / "SKILL.md").exists():
1258
1577
  print(f"[Error] Missing archive source: {archived_path}")
1259
1578
  continue
1260
1579
 
1261
- original_path.parent.mkdir(parents=True, exist_ok=True)
1262
- if original_path.exists():
1580
+ if (original_path / "SKILL.md").exists():
1263
1581
  recency = compare_skill_recency(archived_path, original_path)
1264
1582
  if recency > 0 or force:
1265
- shutil.rmtree(original_path)
1266
- shutil.copytree(archived_path, original_path)
1267
- print(f"[Restored] Updated L1 with newer L2 version: {item['name']} -> {original_path}")
1583
+ self._copy_skill_safely(archived_path, original_path)
1584
+ print(f"[Restored] Updated L1 with newer L2 version: {skill_name} -> {original_path}")
1268
1585
  continue
1269
1586
  else:
1270
- print(f"[Skip] Target L1 skill '{item['name']}' is already newer than or equal to L2 archive (use --force to overwrite)")
1587
+ print(f"[Skip] Target L1 skill '{skill_name}' is already newer than or equal to L2 archive (use --force to overwrite)")
1271
1588
  continue
1272
1589
 
1273
- shutil.copytree(archived_path, original_path)
1274
- print(f"[Restored] {item['name']} -> {original_path}")
1590
+ self._copy_skill_safely(archived_path, original_path)
1591
+ print(f"[Restored] {skill_name} -> {original_path}")
1275
1592
 
1276
1593
  print("Restoration complete.")
1277
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
+
1694
+ def uninstall(self, dry_run=False, force=False, keep_archive=False, keep_skill=False):
1695
+ """Cleanly restore all archived skills to L1 without overwriting newer L1 versions and remove skill-vault."""
1696
+ root_dir = self.get_root_dir()
1697
+ sv_dir = self.get_skill_vault_dir()
1698
+ manifest = self.load_manifest()
1699
+ manifest_map = {item["name"]: item for item in manifest if "name" in item}
1700
+ disk_skills = self.get_archived_skill_folders()
1701
+
1702
+ candidates = []
1703
+ manifested_arch_paths = set()
1704
+ for item in manifest:
1705
+ skill_name = item["name"]
1706
+ archived_path = self.resolve_portable_path(item.get("archived_path", ""))
1707
+ disk_cand = disk_skills.get(skill_name)
1708
+ if disk_cand and disk_cand["has_skill_md"]:
1709
+ if not (archived_path / "SKILL.md").exists() or compare_skill_recency(disk_cand["folder"], archived_path) > 0:
1710
+ archived_path = disk_cand["folder"]
1711
+ if archived_path.exists():
1712
+ manifested_arch_paths.add(archived_path.resolve())
1713
+ original_path = self.resolve_original_path(item.get("original_path", ""), skill_name=skill_name)
1714
+ candidates.append((skill_name, archived_path, original_path, False))
1715
+
1716
+ # Rescue any unmanifested skills physically sitting in the archive
1717
+ for folder_name, data in sorted(disk_skills.items()):
1718
+ if folder_name in manifest_map or not data["has_skill_md"]:
1719
+ continue
1720
+ if data["folder"].resolve() in manifested_arch_paths:
1721
+ continue
1722
+ original_path = self.resolve_original_path(f"skills/{folder_name}", skill_name=folder_name)
1723
+ candidates.append((folder_name, data["folder"], original_path, True))
1724
+
1725
+ to_restore = []
1726
+ to_upgrade = []
1727
+ to_preserve = []
1728
+ missing_sources = []
1729
+
1730
+ for skill_name, archived_path, original_path, unmanifested in candidates:
1731
+ has_archived = (archived_path / "SKILL.md").exists()
1732
+ has_active = (original_path / "SKILL.md").exists()
1733
+
1734
+ if not has_archived:
1735
+ if has_active:
1736
+ to_preserve.append((skill_name, archived_path, original_path, "Active L1 present; archive source missing"))
1737
+ else:
1738
+ missing_sources.append((skill_name, archived_path, original_path))
1739
+ continue
1740
+
1741
+ if has_active:
1742
+ recency = compare_skill_recency(archived_path, original_path)
1743
+ if recency > 0 or force:
1744
+ reason = "Forced overwrite" if (force and recency <= 0) else "Newer L2 archive version"
1745
+ to_upgrade.append((skill_name, archived_path, original_path, reason))
1746
+ else:
1747
+ to_preserve.append((skill_name, archived_path, original_path, "L1 version is newer or equal"))
1748
+ else:
1749
+ reason = "Unmanifested archive folder rescued" if unmanifested else "Missing from active L1"
1750
+ to_restore.append((skill_name, archived_path, original_path, reason))
1751
+
1752
+ print("==================================================")
1753
+ print(" SKILL VAULT CLEAN UNINSTALL / DECOMMISSION")
1754
+ print(f" Base Directory: {self.base_dir}")
1755
+ print(f" Root Directory: {root_dir}")
1756
+ print(f" Archive Store: {self.archive_dir}")
1757
+ print(f" Skill Folder: {sv_dir if sv_dir else '(None detected)'}")
1758
+ print("==================================================\n")
1759
+
1760
+ print(f"Restoration Plan ({len(candidates)} total archived/discovered skill(s)):")
1761
+ print(f" * Restore to active L1: {len(to_restore)}")
1762
+ for name, _, dst, reason in to_restore:
1763
+ print(f" [RESTORE] {name} -> {dst} ({reason})")
1764
+
1765
+ print(f" * Upgrade active L1 (newer in L2): {len(to_upgrade)}")
1766
+ for name, _, dst, reason in to_upgrade:
1767
+ print(f" [UPGRADE] {name} -> {dst} ({reason})")
1768
+
1769
+ print(f" * Preserve active L1 (newer/equal): {len(to_preserve)}")
1770
+ for name, _, dst, reason in to_preserve:
1771
+ print(f" [PRESERVE] {name} -> {dst} ({reason})")
1772
+
1773
+ if missing_sources:
1774
+ print(f" * Missing archive sources: {len(missing_sources)}")
1775
+ for name, src, _ in missing_sources:
1776
+ print(f" [ERROR] {name} (missing {src})")
1777
+
1778
+ print("\nCleanup Plan:")
1779
+ if keep_archive:
1780
+ if sv_dir and not keep_skill and self.archive_dir.exists() and (sv_dir in self.archive_dir.parents):
1781
+ print(f" * Archive: Relocate {self.archive_dir} -> {root_dir / 'skill_archive'}")
1782
+ else:
1783
+ print(f" * Archive: Keep {self.archive_dir}")
1784
+ else:
1785
+ print(f" * Archive: Remove {self.archive_dir}")
1786
+
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:
1795
+ print(f" * Skill: Keep {sv_dir if sv_dir else '(None detected)'}")
1796
+ else:
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}")
1803
+ print("")
1804
+
1805
+ if missing_sources:
1806
+ print("[Abort] One or more archive sources are missing. Nothing was modified or deleted.")
1807
+ return 1
1808
+
1809
+ if dry_run:
1810
+ print("[Dry Run] Uninstall preview complete. No files were modified or removed.")
1811
+ return 0
1812
+
1813
+ for name, src, dst, _ in to_restore:
1814
+ self._copy_skill_safely(src, dst)
1815
+ print(f"[Restored] {name} -> {dst}")
1816
+
1817
+ for name, src, dst, _ in to_upgrade:
1818
+ self._copy_skill_safely(src, dst)
1819
+ print(f"[Upgraded] {name} -> {dst}")
1820
+
1821
+ # Verification gate before deleting archive or skill-vault folder
1822
+ dirs_to_delete = []
1823
+ if not keep_archive and self.archive_dir.exists():
1824
+ dirs_to_delete.append(self.archive_dir.resolve())
1825
+ if not keep_skill:
1826
+ dirs_to_delete.extend(sv_dirs)
1827
+
1828
+ verification_errors = []
1829
+ for skill_name, _, original_path, _ in to_restore + to_upgrade + to_preserve:
1830
+ orig_resolved = Path(original_path).resolve()
1831
+ skill_md = orig_resolved / "SKILL.md"
1832
+ if not skill_md.exists() or skill_md.stat().st_size == 0:
1833
+ verification_errors.append(f"Missing or empty SKILL.md for '{skill_name}' at {skill_md}")
1834
+ continue
1835
+ for del_dir in dirs_to_delete:
1836
+ if orig_resolved == del_dir or del_dir in orig_resolved.parents:
1837
+ verification_errors.append(
1838
+ f"Destination '{orig_resolved}' for '{skill_name}' is inside '{del_dir}' which is scheduled for deletion"
1839
+ )
1840
+
1841
+ if verification_errors:
1842
+ print("\n[Abort] Verification failed. Preserving archive and skill-vault to prevent data loss:")
1843
+ for err in verification_errors:
1844
+ print(f" [X] {err}")
1845
+ return 1
1846
+
1847
+ # Relocate or delete archive
1848
+ if keep_archive:
1849
+ if sv_dir and not keep_skill and self.archive_dir.exists() and (sv_dir in self.archive_dir.parents):
1850
+ relocated = (root_dir / "skill_archive").resolve()
1851
+ if self.archive_dir.resolve() != relocated:
1852
+ shutil.copytree(self.archive_dir, relocated, dirs_exist_ok=True)
1853
+ cwd_resolved = Path.cwd().resolve()
1854
+ if cwd_resolved == self.archive_dir.resolve() or self.archive_dir.resolve() in cwd_resolved.parents:
1855
+ os.chdir(root_dir)
1856
+ shutil.rmtree(self.archive_dir)
1857
+ print(f"[Relocated] Archive preserved at: {relocated}")
1858
+ else:
1859
+ if self.archive_dir.exists():
1860
+ cwd_resolved = Path.cwd().resolve()
1861
+ if cwd_resolved == self.archive_dir.resolve() or self.archive_dir.resolve() in cwd_resolved.parents:
1862
+ os.chdir(root_dir)
1863
+ shutil.rmtree(self.archive_dir)
1864
+ print(f"[Removed] Archive directory: {self.archive_dir}")
1865
+
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}")
1877
+
1878
+ total_safe = len(to_restore) + len(to_upgrade) + len(to_preserve)
1879
+ print(f"\n[OK] Clean uninstall complete! {total_safe} skill(s) verified safe in active L1 locations.")
1880
+ return 0
1881
+
1278
1882
  def reindex(self):
1279
1883
  """Rebuild INDEX.md grouped by manifest categories with portable relative links."""
1280
1884
  manifest = self.load_manifest()
@@ -1336,11 +1940,25 @@ class SkillVault:
1336
1940
  f.write("\n".join(lines).strip() + "\n")
1337
1941
 
1338
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
+ )
1339
1949
  updated_routers = self.sync_router_md()
1340
1950
  for r_path in updated_routers:
1341
1951
  print(f"[Router Synced] Updated SKILL.md frontmatter: {r_path}")
1342
1952
  print(f"[Reindexed] {total_count} skills across {len(categories)} categories (Base: {self.base_dir}).")
1343
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
+
1344
1962
  def build_router_description(self):
1345
1963
  """Build a dynamic SKILL.md router description from the current archive manifest."""
1346
1964
  manifest = self.load_manifest()
@@ -1375,10 +1993,13 @@ class SkillVault:
1375
1993
 
1376
1994
  def _get_router_skill_md_candidates(self):
1377
1995
  """Locate candidate SKILL.md files belonging to skill-vault within base_dir."""
1996
+ root_dir = self.get_root_dir()
1378
1997
  raw_candidates = [
1379
1998
  self.skills_dir / "skill-vault" / "SKILL.md",
1380
1999
  self.base_dir / ".agents" / "skills" / "skill-vault" / "SKILL.md",
1381
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",
1382
2003
  ]
1383
2004
  if self.archive_dir.exists():
1384
2005
  raw_candidates.append(self.base_dir / "SKILL.md")
@@ -1395,7 +2016,11 @@ class SkillVault:
1395
2016
  def sync_router_md(self, target_skill_md=None, force=False):
1396
2017
  """Synchronize skill-vault's SKILL.md frontmatter description with the active vault categories."""
1397
2018
  candidates = [Path(target_skill_md)] if target_skill_md else self._get_router_skill_md_candidates()
1398
- 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()
1399
2024
  new_desc_block = f"description: >-\n {new_desc}"
1400
2025
  desc_pattern = re.compile(
1401
2026
  r"^description:\s*(?:>[-+]?|\|[-+]?)?\s*\n?.*?(?=\n[a-zA-Z0-9_-]+:|\Z)",
@@ -1429,6 +2054,20 @@ class SkillVault:
1429
2054
 
1430
2055
  return updated
1431
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
+
1432
2071
  def manage_config(
1433
2072
  self,
1434
2073
  show=False,
@@ -1437,6 +2076,7 @@ class SkillVault:
1437
2076
  remove_core=None,
1438
2077
  add_fingerprint=None,
1439
2078
  add_category_rule=None,
2079
+ set_routing=None,
1440
2080
  sync_prompt=False,
1441
2081
  ):
1442
2082
  """Inspect or update vault_config.json and dynamically synchronize the router prompt."""
@@ -1449,14 +2089,15 @@ class SkillVault:
1449
2089
 
1450
2090
  fp_pairs = _normalize_pairs(add_fingerprint)
1451
2091
  rule_pairs = _normalize_pairs(add_category_rule)
1452
- 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)
1453
2094
 
1454
2095
  if init_config:
1455
2096
  effective = self.load_config()
1456
2097
  self.save_config(effective)
1457
2098
  print(f"[Config Initialized] Wrote vault configuration to: {self.config_file}")
1458
2099
 
1459
- 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:
1460
2101
  raw_cfg = self._load_raw_config()
1461
2102
 
1462
2103
  if add_core:
@@ -1521,6 +2162,18 @@ class SkillVault:
1521
2162
  print(f"[Config Updated] Added category rule: [{c}] <- '{k}'")
1522
2163
  raw_cfg["category_rules"] = rule_map
1523
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
+
1524
2177
  self.save_config(raw_cfg)
1525
2178
 
1526
2179
  if sync_prompt:
@@ -1543,7 +2196,10 @@ class SkillVault:
1543
2196
  print("==================================================\n")
1544
2197
  print(f"Protected Core Skills ({len(effective['core_skills'])}):")
1545
2198
  print(f" {', '.join(effective['core_skills'])}\n")
1546
- 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'])}):")
1547
2203
  for cat, pats in effective["workspace_fingerprints"].items():
1548
2204
  print(f" * {cat}: {len(pats)} pattern(s)")
1549
2205
  print(f"\nCategory Inference Rules ({len(effective['category_rules'])}):")
@@ -1658,33 +2314,636 @@ class SkillVault:
1658
2314
 
1659
2315
  return 0
1660
2316
 
1661
- def search(self, query):
1662
- """Search archived skills."""
1663
- q = query.lower()
1664
- manifest = self.load_manifest()
1665
- 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
+ )
1666
2330
 
1667
- for item in manifest:
1668
- name = item["name"]
1669
- cat = item.get("category", "General & Utility Skills")
1670
- archived_path = self.resolve_portable_path(item["archived_path"])
1671
- skill_md = archived_path / "SKILL.md"
1672
- 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]
1673
2350
 
1674
- if q in name.lower() or q in desc.lower() or q in cat.lower():
1675
- results.append((name, cat, desc, str(archived_path)))
2351
+ if as_json:
2352
+ print(json.dumps(results, indent=2, ensure_ascii=False))
2353
+ return
1676
2354
 
1677
2355
  if not results:
1678
2356
  print(f"No archived skills matched '{query}'.")
1679
2357
  return
1680
2358
 
1681
2359
  print(f"Found {len(results)} matching skill(s):\n")
1682
- for name, cat, desc, path_str in results:
1683
- 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']})")
1684
2364
  desc_snippet = desc[:130] + "..." if len(desc) > 130 else desc
1685
2365
  print(f" Description: {desc_snippet}")
1686
2366
  print(f" Path: {path_str}\n")
1687
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
+
1688
2947
  # --- Project Import Engine ---
1689
2948
 
1690
2949
  def resolve_vault_archive_dir(self, vault_arg=None):
@@ -1715,13 +2974,15 @@ class SkillVault:
1715
2974
  ):
1716
2975
  return self.archive_dir
1717
2976
 
1718
- # Check standard global locations
2977
+ # Check standard global locations (canonical ~/.gemini/config/skill_archive first)
1719
2978
  candidates = [
2979
+ Path.home() / ".gemini" / "config" / "skill_archive",
1720
2980
  Path.home() / ".gemini" / "config" / "skills" / "skill-vault" / "skill_archive",
1721
2981
  Path.home() / ".gemini" / "config" / "skills" / ".skill_archive",
1722
- Path.home() / ".gemini" / "config" / "skill_archive",
1723
2982
  Path.home() / ".agents" / "skill_archive",
1724
2983
  Path.home() / ".claude" / "skill_archive",
2984
+ Path.home() / ".gemini" / "skill_archive",
2985
+ Path.home() / ".cursor" / "skill_archive",
1725
2986
  ]
1726
2987
  for cand in candidates:
1727
2988
  if cand.exists() and (
@@ -1942,9 +3203,11 @@ def main():
1942
3203
  p_arch.add_argument("--force", action="store_true", help="Force overwrite in archive regardless of recency")
1943
3204
 
1944
3205
  # Recategorize
1945
- p_rec = subparsers.add_parser("recategorize", help="Recategorize an archived skill in metadata")
1946
- p_rec.add_argument("name", help="Skill name")
1947
- 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")
1948
3211
 
1949
3212
  # Restore
1950
3213
  p_rest = subparsers.add_parser("restore", help="Restore archived skills back to active availability")
@@ -1955,7 +3218,7 @@ def main():
1955
3218
  p_rest.add_argument("--force", action="store_true", help="Overwrite existing active directory")
1956
3219
 
1957
3220
  # Reindex
1958
- 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")
1959
3222
 
1960
3223
  # Verify / Integrity Check
1961
3224
  p_ver = subparsers.add_parser("verify", help="Verify archive integrity across disk, manifest, and index")
@@ -1963,7 +3226,48 @@ def main():
1963
3226
 
1964
3227
  # Search
1965
3228
  p_srch = subparsers.add_parser("search", help="Search archived skills by keyword, intent, or domain")
1966
- 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")
1967
3271
 
1968
3272
  # Sync
1969
3273
  p_sync = subparsers.add_parser("sync", help="Scan plugins and active skills, ingest new/updated skills, and prune non-core skills")
@@ -1991,8 +3295,20 @@ def main():
1991
3295
  p_cfg.add_argument("--remove-core", nargs="+", metavar="SKILL", help="Remove one or more skills from protected core skills")
1992
3296
  p_cfg.add_argument("--add-fingerprint", nargs=2, action="append", metavar=("CATEGORY", "PATTERN"), help="Add a workspace file/glob fingerprint for a category")
1993
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)")
1994
3299
  p_cfg.add_argument("--sync-prompt", action="store_true", help="Synchronize SKILL.md router description with archived categories")
1995
3300
 
3301
+ # Uninstall / Eject
3302
+ p_uninst = subparsers.add_parser(
3303
+ "uninstall",
3304
+ aliases=["eject"],
3305
+ help="Cleanly restore all archived skills to L1 (preserving newer L1 versions) and remove skill-vault",
3306
+ )
3307
+ p_uninst.add_argument("--dry-run", action="store_true", help="Preview restoration and removal plan without modifying files")
3308
+ p_uninst.add_argument("--force", action="store_true", help="Overwrite active L1 skills even if L1 copy is newer")
3309
+ p_uninst.add_argument("--keep-archive", action="store_true", help="Preserve skill_archive (relocating it out of skill-vault if nested)")
3310
+ p_uninst.add_argument("--keep-skill", action="store_true", help="Restore all skills and remove archive, but keep the skill-vault skill folder")
3311
+
1996
3312
  args = parser.parse_args()
1997
3313
  mgr = SkillVault(base_dir=args.base_dir)
1998
3314
 
@@ -2029,7 +3345,7 @@ def main():
2029
3345
  elif args.command == "archive":
2030
3346
  mgr.archive(name=args.name, pattern=args.pattern, category=args.category, keep_active=args.keep_active, force=args.force)
2031
3347
  elif args.command == "recategorize":
2032
- 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))
2033
3349
  elif args.command == "restore":
2034
3350
  mgr.restore(name=args.name, pattern=args.pattern, category=args.category, restore_all=args.all, force=args.force)
2035
3351
  elif args.command == "reindex":
@@ -2037,7 +3353,23 @@ def main():
2037
3353
  elif args.command == "verify":
2038
3354
  sys.exit(mgr.verify(fix=args.fix))
2039
3355
  elif args.command == "search":
2040
- 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
+ )
2041
3373
  elif args.command == "import":
2042
3374
  sys.exit(
2043
3375
  mgr.import_skills(
@@ -2059,8 +3391,18 @@ def main():
2059
3391
  remove_core=args.remove_core,
2060
3392
  add_fingerprint=args.add_fingerprint,
2061
3393
  add_category_rule=args.add_category_rule,
3394
+ set_routing=args.set_routing,
2062
3395
  sync_prompt=args.sync_prompt,
2063
3396
  )
3397
+ elif args.command in ("uninstall", "eject"):
3398
+ sys.exit(
3399
+ mgr.uninstall(
3400
+ dry_run=args.dry_run,
3401
+ force=args.force,
3402
+ keep_archive=args.keep_archive,
3403
+ keep_skill=args.keep_skill,
3404
+ )
3405
+ )
2064
3406
 
2065
3407
 
2066
3408
  if __name__ == "__main__":