@jcorpac/skill-vault 1.6.0 → 1.8.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.
package/README.md CHANGED
@@ -104,8 +104,17 @@ python scripts/skill_vault.py verify
104
104
  | `skill-vault import <name> --vault-dir <path>` | Import from an explicit source vault (defaults to global archive or base). |
105
105
  | `skill-vault import <name> --force` | Overwrite existing project skill regardless of recency. |
106
106
  | `skill-vault import <name> --dry-run` | Preview what would be imported without copying files. |
107
+ | `skill-vault config --show` | Inspect effective core skills, stack fingerprints, and category rules. |
108
+ | `skill-vault config --init` | Write `skill_archive/vault_config.json` with universal defaults for customization. |
109
+ | `skill-vault config --add-core <name>` | Add a skill to protected Core Foundation Skills (or use `--remove-core`). |
110
+ | `skill-vault config --add-fingerprint "<Cat>" "<pat>"` | Add a workspace file/glob fingerprint to a skill category. |
111
+ | `skill-vault config --add-category-rule "<Cat>" "<kw>"` | Add a keyword rule for automatic skill categorization. |
112
+ | `skill-vault config --sync-prompt` | Dynamically update `SKILL.md`'s router description with your vault's categories. |
107
113
  | `skill-vault verify` | Audit bi-directional consistency across disk, manifest, and index. |
108
114
  | `skill-vault verify --fix` | Audit and automatically self-heal all detected discrepancies. |
115
+ | `skill-vault uninstall` | Cleanly restore all archived skills to L1 (preserving newer L1 versions), verify, and remove archive + `skill-vault` (alias: `eject`). |
116
+ | `skill-vault uninstall --dry-run` | Preview the uninstall restoration and cleanup plan without modifying files. |
117
+ | `skill-vault uninstall --keep-archive` | Restore all skills to L1 and remove `skill-vault`, while preserving/relocating `skill_archive`. |
109
118
 
110
119
  ---
111
120
 
@@ -116,6 +125,8 @@ python scripts/skill_vault.py verify
116
125
  3. **Zero Runtime Dependencies**: The core engine requires only Python 3 standard library (`os`, `sys`, `json`, `re`, `shutil`, `hashlib`, `argparse`, `pathlib`).
117
126
  4. **Self-Healing Integrity**: Detects orphaned folders, phantom manifest entries, broken markdown links, and duplicate aliases.
118
127
  5. **Recency & Version Prioritization**: Automatically protects newer versions when archiving, restoring, or optimizing by evaluating semantic version tags (`version:`) with filesystem timestamp (`mtime`) fallbacks. Use `--force` to override.
128
+ 6. **Universal Cross-Ecosystem Stack Detection**: Includes built-in workspace fingerprinting and category inference across Frontend, Backend, Cloud/DevOps, Databases, Mobile, AI/ML, Testing/Security, Data Engineering, and Science — fully extensible via `vault_config.json` and `SKILL.md` frontmatter (`core: true`, `category:`).
129
+ 7. **Dynamic Router Prompt Syncing**: `reindex` and `config --sync-prompt` automatically keep `skill-vault`'s `SKILL.md` frontmatter description synchronized with the exact skills and categories in the user's own vault.
119
130
 
120
131
  ---
121
132
 
package/SKILL.md CHANGED
@@ -1,17 +1,10 @@
1
1
  ---
2
2
  name: skill-vault
3
+ version: 1.8.0
3
4
  description: >-
4
- Universal agent-agnostic skill router and tiered storage manager for 210+ specialized domain skills in cold storage.
5
- ALWAYS use this skill whenever the task involves domains or tools not in active memory, including:
6
- (1) AlloyDB (Omni, replication, vector, tuning),
7
- (2) Cloud SQL (Postgres, MySQL, backup/DR, performance),
8
- (3) BigQuery & Data Warehouse (dbt, Dataform, optimization),
9
- (4) GCP & Data Engineering (Airflow/Composer, Spanner, Dataproc, GCS),
10
- (5) Gemini API & AI Agents (ADK, Live API, Omni Flash, evals),
11
- (6) Science & Biomedicine (AlphaFold, AlphaGenome, Foldseek, ChEMBL, PDB, PyMOL, PubMed, variant analysis),
12
- (7) Android Development, or
13
- (8) General Utilities.
14
- Search or restore skills on demand via 'python scripts/skill_vault.py search "<keyword>"', view 'skill_archive/INDEX.md', or run 'restore <name>'.
5
+ Universal agent-agnostic skill router, lifecycle manager, and tiered storage engine for AI coding agents.
6
+ ALWAYS use this skill whenever a task involves specialized domain skills, frameworks, or tools not currently loaded in active context memory (L1), or when managing skill context bloat.
7
+ Search cold storage (L2) on demand via 'python scripts/skill_vault.py search "<keyword>"', view 'skill_archive/INDEX.md', or dynamically mount skills via 'restore', 'import', or 'optimize'.
15
8
  ---
16
9
 
17
10
  # Skill Vault: Universal Agent Skill Lifecycle & Storage Manager
@@ -137,7 +130,7 @@ python scripts/skill_vault.py optimize
137
130
  python scripts/skill_vault.py optimize --dry-run
138
131
 
139
132
  # Optimize for a specific workspace folder and protect custom skills
140
- python scripts/skill_vault.py optimize --workspace "C:\Projects\my-repo" --protect my-custom-skill
133
+ python scripts/skill_vault.py optimize --workspace "./my-repo" --protect my-custom-skill
141
134
  ```
142
135
 
143
136
  ### I. Recency & Version Prioritization Protocol
@@ -185,6 +178,48 @@ python scripts/skill_vault.py sync --dry-run
185
178
  python scripts/skill_vault.py sync --keep-active
186
179
  ```
187
180
 
181
+ ### L. Universal Stack Customization & Dynamic Router Sync (`config`)
182
+ Skill Vault supports cross-ecosystem workspace fingerprinting and auto-categorization out of the box (Frontend, Backend, Cloud/DevOps, Databases, Mobile, AI/ML, Testing/Security, Data Engineering, and Science), and can be customized per user or repository via `skill_archive/vault_config.json` or `SKILL.md` frontmatter tags:
183
+
184
+ ```bash
185
+ # Inspect active core skills, stack fingerprints, and category rules
186
+ python scripts/skill_vault.py config --show
187
+
188
+ # Initialize skill_archive/vault_config.json with universal defaults
189
+ python scripts/skill_vault.py config --init
190
+
191
+ # Protect or unprotect specific core foundation skills from auto-archiving/pruning
192
+ python scripts/skill_vault.py config --add-core <skill_name>
193
+ python scripts/skill_vault.py config --remove-core <skill_name>
194
+
195
+ # Add custom workspace file/glob fingerprints and category keyword rules
196
+ python scripts/skill_vault.py config --add-fingerprint "<Category>" "<pattern>"
197
+ python scripts/skill_vault.py config --add-category-rule "<Category>" "<keyword>"
198
+
199
+ # Dynamically update SKILL.md's router description with currently indexed categories
200
+ python scripts/skill_vault.py config --sync-prompt
201
+ ```
202
+
203
+ Any individual skill's `SKILL.md` frontmatter can also declare:
204
+ - `core: true` (or `pinned: true` / `always_active: true`) to automatically protect that skill during `sync` and `optimize`.
205
+ - `category: "<Category>"` to pin its vault category without needing `--category` flags.
206
+
207
+ ### M. Clean Uninstallation & Safe Decommissioning (`uninstall` / `eject`)
208
+ To cleanly remove or replace `skill-vault` without losing any archived skills or overwriting newer active L1 versions:
209
+ ```bash
210
+ # Preview restoration and cleanup plan without modifying files
211
+ python scripts/skill_vault.py uninstall --dry-run
212
+
213
+ # Restore all archived skills to L1 (preserving newer L1 versions), verify SKILL.md files, and remove archive + skill-vault
214
+ python scripts/skill_vault.py uninstall
215
+
216
+ # Keep skill_archive as a backup (relocates it out of skills/skill-vault if nested)
217
+ python scripts/skill_vault.py uninstall --keep-archive
218
+
219
+ # Restore all skills and clear archive, while keeping the skill-vault folder itself
220
+ python scripts/skill_vault.py uninstall --keep-skill
221
+ ```
222
+
188
223
  ---
189
224
 
190
225
  ## 3. Environment & OS Compatibility Guidelines
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jcorpac/skill-vault",
3
- "version": "1.6.0",
3
+ "version": "1.8.0",
4
4
  "description": "Universal Agent Skill Router, Lifecycle Manager, and Tiered Storage Engine for AI Coding Agents.",
5
5
  "main": "bin/cli.js",
6
6
  "bin": {
@@ -26,6 +26,62 @@ DEFAULT_CORE_SKILLS = {
26
26
 
27
27
  # Workspace fingerprint signatures mapping to skill categories
28
28
  WORKSPACE_FINGERPRINTS = {
29
+ "Frontend & Web Development": [
30
+ "package.json",
31
+ "tsconfig.json",
32
+ "next.config.*",
33
+ "vite.config.*",
34
+ "angular.json",
35
+ "svelte.config.*",
36
+ "tailwind.config.*",
37
+ ],
38
+ "Backend & APIs": [
39
+ "pyproject.toml",
40
+ "requirements.txt",
41
+ "go.mod",
42
+ "Cargo.toml",
43
+ "pom.xml",
44
+ "Gemfile",
45
+ "composer.json",
46
+ "openapi.yaml",
47
+ "swagger.json",
48
+ ],
49
+ "Cloud & DevOps": [
50
+ "Dockerfile",
51
+ "docker-compose.yml",
52
+ "docker-compose.yaml",
53
+ "*.tf",
54
+ "Chart.yaml",
55
+ "Pulumi.yaml",
56
+ "serverless.yml",
57
+ ],
58
+ "Databases & Storage": [
59
+ "schema.prisma",
60
+ "drizzle.config.*",
61
+ "alembic.ini",
62
+ "flyway.conf",
63
+ "*.sql",
64
+ ],
65
+ "Mobile & Cross-Platform": [
66
+ "pubspec.yaml",
67
+ "Podfile",
68
+ "Package.swift",
69
+ "app.json",
70
+ "metro.config.js",
71
+ ],
72
+ "AI, LLM & Machine Learning": [
73
+ "*.ipynb",
74
+ "MLproject",
75
+ "conda.yaml",
76
+ "dvc.yaml",
77
+ ],
78
+ "Testing, QA & Security": [
79
+ "playwright.config.*",
80
+ "cypress.config.*",
81
+ "vitest.config.*",
82
+ "jest.config.*",
83
+ "pytest.ini",
84
+ ],
29
85
  "BigQuery & Data Warehouse": [
30
86
  "dbt_project.yml",
31
87
  "dataform.json",
@@ -67,6 +123,186 @@ WORKSPACE_FINGERPRINTS = {
67
123
  ],
68
124
  }
69
125
 
126
+ DEFAULT_WORKSPACE_FINGERPRINTS = WORKSPACE_FINGERPRINTS
127
+
128
+ # Default keyword rules for auto-categorizing skills across universal ecosystems
129
+ DEFAULT_CATEGORY_RULES = {
130
+ "Knowledge & Wiki Architecture": [
131
+ "egm-",
132
+ "wiki",
133
+ "documentation architecture",
134
+ ],
135
+ "Gemini API & AI Agents": [
136
+ "gemini",
137
+ "adk",
138
+ "live-api",
139
+ "live api",
140
+ "llm agent",
141
+ "vertex ai",
142
+ "vertex",
143
+ ],
144
+ "Android Development": [
145
+ "android",
146
+ "gradle",
147
+ "apk",
148
+ "adb",
149
+ "jetpack compose",
150
+ ],
151
+ "BigQuery & Data Warehouse": [
152
+ "bigquery",
153
+ "dbt",
154
+ "dataform",
155
+ "data warehouse",
156
+ "lakehouse",
157
+ ],
158
+ "AlloyDB": [
159
+ "alloydb",
160
+ "omni",
161
+ ],
162
+ "Databases & Storage": [
163
+ "prisma",
164
+ "drizzle",
165
+ "sqlalchemy",
166
+ "redis",
167
+ "mongodb",
168
+ "dynamodb",
169
+ "cassandra",
170
+ "clickhouse",
171
+ "supabase",
172
+ "sqlite",
173
+ "vector db",
174
+ "pinecone",
175
+ "qdrant",
176
+ ],
177
+ "Cloud SQL": [
178
+ "cloud sql",
179
+ "cloudsql",
180
+ "postgres",
181
+ "postgresql",
182
+ "mysql",
183
+ ],
184
+ "Science & Biomedicine": [
185
+ "protein",
186
+ "alphafold",
187
+ "pdb",
188
+ "dna",
189
+ "rna",
190
+ "chembl",
191
+ "bioinformatics",
192
+ "variant",
193
+ "genome",
194
+ "pymol",
195
+ "foldseek",
196
+ "pubmed",
197
+ ],
198
+ "GCP & Data Engineering": [
199
+ "gcp",
200
+ "airflow",
201
+ "composer",
202
+ "spanner",
203
+ "dataflow",
204
+ "dataproc",
205
+ "pubsub",
206
+ "cloud storage",
207
+ "cloud run",
208
+ ],
209
+ "Testing, QA & Security": [
210
+ "playwright",
211
+ "cypress",
212
+ "jest",
213
+ "vitest",
214
+ "pytest",
215
+ "selenium",
216
+ "e2e",
217
+ "unit test",
218
+ "tdd",
219
+ "owasp",
220
+ "pentest",
221
+ "vulnerability",
222
+ "security audit",
223
+ ],
224
+ "Mobile & Cross-Platform": [
225
+ "flutter",
226
+ "dart",
227
+ "swift",
228
+ "swiftui",
229
+ "ios",
230
+ "xcode",
231
+ "react native",
232
+ "expo",
233
+ "kotlin multiplatform",
234
+ ],
235
+ "Frontend & Web Development": [
236
+ "react",
237
+ "nextjs",
238
+ "next.js",
239
+ "vue",
240
+ "svelte",
241
+ "angular",
242
+ "tailwind",
243
+ "css",
244
+ "frontend",
245
+ "vite",
246
+ "webpack",
247
+ "dom",
248
+ "a11y",
249
+ "accessibility",
250
+ ],
251
+ "Cloud & DevOps": [
252
+ "aws",
253
+ "azure",
254
+ "kubernetes",
255
+ "k8s",
256
+ "helm",
257
+ "docker",
258
+ "terraform",
259
+ "pulumi",
260
+ "ansible",
261
+ "github actions",
262
+ "ci/cd",
263
+ "cloudflare",
264
+ "vercel",
265
+ "netlify",
266
+ "devops",
267
+ "prometheus",
268
+ "grafana",
269
+ ],
270
+ "AI, LLM & Machine Learning": [
271
+ "openai",
272
+ "anthropic",
273
+ "claude",
274
+ "langchain",
275
+ "llamaindex",
276
+ "huggingface",
277
+ "pytorch",
278
+ "tensorflow",
279
+ "rag",
280
+ "embeddings",
281
+ "fine-tuning",
282
+ "machine learning",
283
+ "deep learning",
284
+ ],
285
+ "Backend & APIs": [
286
+ "fastapi",
287
+ "flask",
288
+ "django",
289
+ "express",
290
+ "nestjs",
291
+ "graphql",
292
+ "rest api",
293
+ "grpc",
294
+ "golang",
295
+ "rust",
296
+ "spring boot",
297
+ "rails",
298
+ "microservice",
299
+ "backend",
300
+ "oauth",
301
+ "jwt",
302
+ "stripe",
303
+ ],
304
+ }
305
+
70
306
 
71
307
  def parse_version_tuple(ver_str):
72
308
  """Parse version string into a comparable numeric tuple, e.g. 'v20' -> (20,), '1.1.5' -> (1, 1, 5)."""
@@ -98,7 +334,14 @@ def get_skill_metadata(skill_dir):
98
334
 
99
335
  latest_mtime = 0.0
100
336
  try:
101
- files = [f for f in skill_dir.rglob("*") if f.is_file()]
337
+ files = []
338
+ if skill_dir.exists():
339
+ for root, dirs, filenames in os.walk(skill_dir):
340
+ root_path = Path(root)
341
+ # Do not bleed mtimes from nested sibling skill folders inside a single_skill_dir
342
+ dirs[:] = [d for d in dirs if not (root_path / d / "SKILL.md").exists()]
343
+ for fname in filenames:
344
+ files.append(root_path / fname)
102
345
  if files:
103
346
  latest_mtime = max(f.stat().st_mtime for f in files)
104
347
  elif skill_dir.exists():
@@ -175,8 +418,103 @@ class SkillVault:
175
418
  self.archive_dir = self.base_dir / "skill_archive"
176
419
  self.manifest_file = self.archive_dir / "backup_manifest.json"
177
420
  self.index_file = self.archive_dir / "INDEX.md"
421
+ self.config_file = self.archive_dir / "vault_config.json"
178
422
  self.skills_dir = self.base_dir / "skills"
179
423
 
424
+ def _load_raw_config(self):
425
+ """Read raw vault_config.json without creating files or merging defaults."""
426
+ if self.config_file.exists():
427
+ try:
428
+ with open(self.config_file, "r", encoding="utf-8") as f:
429
+ data = json.load(f)
430
+ return data if isinstance(data, dict) else {}
431
+ except Exception as e:
432
+ print(f"[Warning] Failed to parse {self.config_file}: {e}")
433
+ return {}
434
+
435
+ def load_config(self):
436
+ """Load vault_config.json if present and merge with universal defaults."""
437
+ user_cfg = self._load_raw_config()
438
+
439
+ disabled_core = set(user_cfg.get("disabled_core_skills", []))
440
+ core_skills = (set(DEFAULT_CORE_SKILLS) | set(user_cfg.get("core_skills", []))) - disabled_core
441
+
442
+ merged_fp = {cat: list(pats) for cat, pats in WORKSPACE_FINGERPRINTS.items()}
443
+ for cat, pats in user_cfg.get("workspace_fingerprints", {}).items():
444
+ if cat in merged_fp:
445
+ merged_fp[cat] = list(dict.fromkeys(list(pats) + merged_fp[cat]))
446
+ else:
447
+ merged_fp[cat] = list(pats)
448
+
449
+ custom_rules = user_cfg.get("category_rules", {})
450
+ merged_rules = {}
451
+ # Evaluate non-default custom categories first so user overrides take precedence
452
+ for cat, kws in custom_rules.items():
453
+ if cat not in DEFAULT_CATEGORY_RULES:
454
+ merged_rules[cat] = list(kws)
455
+ for cat, kws in custom_rules.items():
456
+ if cat in DEFAULT_CATEGORY_RULES:
457
+ merged_rules[cat] = list(dict.fromkeys(list(kws) + list(DEFAULT_CATEGORY_RULES[cat])))
458
+ for cat, kws in DEFAULT_CATEGORY_RULES.items():
459
+ if cat not in merged_rules:
460
+ merged_rules[cat] = list(kws)
461
+
462
+ return {
463
+ "core_skills": sorted(core_skills),
464
+ "disabled_core_skills": sorted(disabled_core),
465
+ "workspace_fingerprints": merged_fp,
466
+ "category_rules": merged_rules,
467
+ }
468
+
469
+ def save_config(self, config_data):
470
+ """Persist configuration to vault_config.json."""
471
+ self.archive_dir.mkdir(parents=True, exist_ok=True)
472
+ with open(self.config_file, "w", encoding="utf-8") as f:
473
+ json.dump(config_data, f, indent=2, ensure_ascii=False)
474
+
475
+ def get_core_skills(self, extra_protected=None):
476
+ """Return effective set of protected core skill names."""
477
+ core_set = set(self.load_config()["core_skills"])
478
+ if extra_protected:
479
+ core_set.update(extra_protected)
480
+ return core_set
481
+
482
+ def parse_skill_frontmatter_field(self, skill_md_path, field_name):
483
+ """Extract a single scalar field from SKILL.md YAML frontmatter."""
484
+ skill_md_path = Path(skill_md_path)
485
+ if not skill_md_path.exists():
486
+ return None
487
+ try:
488
+ content = skill_md_path.read_text(encoding="utf-8", errors="ignore")
489
+ fm_match = re.search(r"^---\s*\n(.*?)\n---", content, re.DOTALL)
490
+ if fm_match:
491
+ pattern = rf"^{re.escape(field_name)}:\s*([^\n]+)"
492
+ match = re.search(pattern, fm_match.group(1), re.MULTILINE | re.IGNORECASE)
493
+ if match:
494
+ val = match.group(1).strip().strip("'\"")
495
+ return val if val else None
496
+ except Exception:
497
+ pass
498
+ return None
499
+
500
+ def is_core_skill_frontmatter(self, skill_md_path):
501
+ """Return True if SKILL.md frontmatter marks the skill as core/pinned/always_active."""
502
+ for field in ("core", "pinned", "always_active"):
503
+ val = self.parse_skill_frontmatter_field(skill_md_path, field)
504
+ if val and val.strip().lower() in {"true", "yes", "1"}:
505
+ return True
506
+ return False
507
+
508
+ def _keyword_matches(self, keyword, text, normalized_text):
509
+ """Match a category keyword against skill name/description text safely."""
510
+ kw = str(keyword).lower().strip()
511
+ if not kw:
512
+ return False
513
+ if kw.isalpha() and len(kw) <= 4:
514
+ pattern = rf"(?<![a-z]){re.escape(kw)}(?![a-z])"
515
+ return bool(re.search(pattern, text) or re.search(pattern, normalized_text))
516
+ return kw in text or kw in normalized_text
517
+
180
518
  def init(self):
181
519
  """Bootstrap standard directory structure for a new workspace or repository."""
182
520
  self.skills_dir.mkdir(parents=True, exist_ok=True)
@@ -288,13 +626,22 @@ class SkillVault:
288
626
  for folder in base.iterdir():
289
627
  if folder.is_dir():
290
628
  skill_md = folder / "SKILL.md"
291
- folders[folder.name] = {
629
+ has_md = skill_md.exists()
630
+ candidate = {
292
631
  "name": folder.name,
293
632
  "folder": folder,
294
633
  "skill_md": skill_md,
295
- "has_skill_md": skill_md.exists(),
296
- "size": skill_md.stat().st_size if skill_md.exists() else 0,
634
+ "has_skill_md": has_md,
635
+ "size": skill_md.stat().st_size if has_md else 0,
297
636
  }
637
+ existing = folders.get(folder.name)
638
+ if existing is None:
639
+ folders[folder.name] = candidate
640
+ elif has_md and (
641
+ not existing["has_skill_md"]
642
+ or compare_skill_recency(folder, existing["folder"]) > 0
643
+ ):
644
+ folders[folder.name] = candidate
298
645
  return folders
299
646
 
300
647
  def load_manifest(self):
@@ -347,11 +694,40 @@ class SkillVault:
347
694
  return target
348
695
  return None
349
696
 
697
+ def get_root_dir(self):
698
+ """Return the top-level environment or workspace root directory.
699
+
700
+ When base_dir is an installed skill directory nested inside 'skills/skill-vault',
701
+ returns the parent of 'skills' (e.g. ~/.gemini/config or workspace root).
702
+ """
703
+ if self.base_dir.name == "skill-vault" and self.base_dir.parent.name == "skills":
704
+ return self.base_dir.parent.parent
705
+ return self.base_dir
706
+
707
+ 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":
710
+ if not (self.base_dir / ".git").exists():
711
+ return self.base_dir
712
+ root_dir = self.get_root_dir()
713
+ for rel in ["skills/skill-vault", ".agents/skills/skill-vault", ".claude/skills/skill-vault"]:
714
+ cand = (root_dir / rel).resolve()
715
+ if cand.exists() and not (cand / ".git").exists():
716
+ return cand
717
+ return None
718
+
350
719
  def make_portable_path(self, abs_path):
351
- """Convert path to relative from base_dir if possible."""
720
+ """Convert path to relative from base_dir or root_dir if possible."""
721
+ resolved = Path(abs_path).resolve()
352
722
  try:
353
- return str(Path(abs_path).resolve().relative_to(self.base_dir))
723
+ return str(resolved.relative_to(self.base_dir))
354
724
  except ValueError:
725
+ root_dir = self.get_root_dir()
726
+ if root_dir != self.base_dir:
727
+ try:
728
+ return str(resolved.relative_to(root_dir))
729
+ except ValueError:
730
+ pass
355
731
  return str(abs_path)
356
732
 
357
733
  def resolve_portable_path(self, path_str):
@@ -359,7 +735,69 @@ class SkillVault:
359
735
  p = Path(path_str)
360
736
  if p.is_absolute():
361
737
  return p
362
- return (self.base_dir / p).resolve()
738
+ cand = (self.base_dir / p).resolve()
739
+ if not cand.exists():
740
+ root_dir = self.get_root_dir()
741
+ if root_dir != self.base_dir:
742
+ root_cand = (root_dir / p).resolve()
743
+ if root_cand.exists():
744
+ return root_cand
745
+ return cand
746
+
747
+ def resolve_original_path(self, path_str, skill_name=None):
748
+ """Resolve a stored original_path to an active L1 Path outside skills/skill-vault."""
749
+ root_dir = self.get_root_dir()
750
+ sv_dir = self.get_skill_vault_dir()
751
+ if not path_str:
752
+ skills_root = root_dir / "skills" if root_dir != self.base_dir else self.skills_dir
753
+ return (skills_root / (skill_name or "unknown-skill")).resolve()
754
+
755
+ p = Path(path_str)
756
+ if p.is_absolute():
757
+ resolved = p.resolve()
758
+ if sv_dir and (sv_dir in resolved.parents or resolved == sv_dir):
759
+ try:
760
+ rel = resolved.relative_to(sv_dir)
761
+ return (root_dir / rel).resolve()
762
+ except ValueError:
763
+ pass
764
+ return resolved
765
+
766
+ return (root_dir / p).resolve()
767
+
768
+ def _copy_skill_safely(self, src_dir, dst_dir):
769
+ """Copy a skill folder from src_dir to dst_dir without deleting nested sibling skills."""
770
+ src_dir = Path(src_dir).resolve()
771
+ dst_dir = Path(dst_dir).resolve()
772
+ dst_dir.parent.mkdir(parents=True, exist_ok=True)
773
+
774
+ def _ignore_nested_skills(curr_dir, names):
775
+ curr_path = Path(curr_dir).resolve()
776
+ if curr_path == src_dir:
777
+ return [
778
+ n for n in names
779
+ if (curr_path / n).is_dir() and (curr_path / n / "SKILL.md").exists()
780
+ ]
781
+ return []
782
+
783
+ if dst_dir.exists():
784
+ nested_skill_dirs = {
785
+ sub.name for sub in dst_dir.iterdir()
786
+ if sub.is_dir() and (sub / "SKILL.md").exists()
787
+ }
788
+ if nested_skill_dirs or dst_dir.name == "skills":
789
+ for item in list(dst_dir.iterdir()):
790
+ if item.name in nested_skill_dirs:
791
+ continue
792
+ if item.is_dir():
793
+ shutil.rmtree(item)
794
+ else:
795
+ item.unlink()
796
+ shutil.copytree(src_dir, dst_dir, dirs_exist_ok=True, ignore=_ignore_nested_skills)
797
+ return
798
+ shutil.rmtree(dst_dir)
799
+
800
+ shutil.copytree(src_dir, dst_dir, dirs_exist_ok=True, ignore=_ignore_nested_skills)
363
801
 
364
802
  def parse_index_file(self):
365
803
  """Parse INDEX.md and return extracted skills with categories and link targets."""
@@ -402,8 +840,10 @@ class SkillVault:
402
840
  """Inspect workspace files and return matched skill categories."""
403
841
  target_ws = Path(workspace_path).resolve() if workspace_path else Path.cwd().resolve()
404
842
  matched = {}
843
+ config = self.load_config()
844
+ fingerprints = config["workspace_fingerprints"]
405
845
 
406
- for category, patterns in WORKSPACE_FINGERPRINTS.items():
846
+ for category, patterns in fingerprints.items():
407
847
  for pat in patterns:
408
848
  if "*" in pat:
409
849
  matches = list(target_ws.glob(pat)) + list(target_ws.glob(f"**/{pat}"))[:5]
@@ -415,6 +855,36 @@ class SkillVault:
415
855
  matched.setdefault(category, []).append(pat)
416
856
  break
417
857
 
858
+ # Inspect categories present in manifest for workspace filename/directory keyword matches
859
+ manifest = self.load_manifest()
860
+ manifest_categories = {m.get("category") for m in manifest if m.get("category")}
861
+ unmatched_cats = [c for c in sorted(manifest_categories) if c not in matched]
862
+ if unmatched_cats and target_ws.exists():
863
+ 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
+ for cat in unmatched_cats:
878
+ words = [
879
+ w.lower()
880
+ for w in re.findall(r"[a-zA-Z0-9]+", cat)
881
+ if len(w) > 2 and w.lower() not in stop_words
882
+ ]
883
+ for w in words:
884
+ if w in ws_tokens:
885
+ matched.setdefault(cat, []).append(ws_tokens[w])
886
+ break
887
+
418
888
  return matched
419
889
 
420
890
  def optimize(self, workspace_path=None, protected_skills=None, dry_run=False, force=False):
@@ -424,9 +894,7 @@ class SkillVault:
424
894
  prioritizing newer versions when versions overlap.
425
895
  """
426
896
  target_ws = Path(workspace_path).resolve() if workspace_path else Path.cwd().resolve()
427
- core_set = set(DEFAULT_CORE_SKILLS)
428
- if protected_skills:
429
- core_set.update(protected_skills)
897
+ core_set = self.get_core_skills(protected_skills)
430
898
 
431
899
  print("==================================================")
432
900
  print(" SKILL VAULT AUTO-OPTIMIZATION")
@@ -452,10 +920,15 @@ class SkillVault:
452
920
  to_keep = []
453
921
 
454
922
  for name, data in active_map.items():
923
+ skill_md_path = Path(data["path"]) / "SKILL.md"
455
924
  if name in core_set:
456
925
  to_keep.append((name, "Core Foundation Skill"))
926
+ elif self.is_core_skill_frontmatter(skill_md_path):
927
+ to_keep.append((name, "Core Foundation Skill (Pinned in Frontmatter)"))
457
928
  else:
458
- skill_cat = manifest_by_name.get(name, {}).get("category", "General & Utility Skills")
929
+ skill_cat = manifest_by_name.get(name, {}).get("category") or self.infer_category(
930
+ name, data["description"], skill_md_path
931
+ )
459
932
  if skill_cat in detected_categories:
460
933
  to_keep.append((name, f"Matched Stack ({skill_cat})"))
461
934
  else:
@@ -528,23 +1001,38 @@ class SkillVault:
528
1001
 
529
1002
  # --- Sync & Ingestion Engine ---
530
1003
 
531
- def infer_category(self, skill_name, skill_desc=""):
532
- """Infer an appropriate category for a new skill based on name and description keywords."""
1004
+ def infer_category(self, skill_name, skill_desc="", skill_md_path=None):
1005
+ """Infer an appropriate category for a skill via frontmatter, custom rules, or universal defaults."""
1006
+ resolved_md = Path(skill_md_path) if skill_md_path else None
1007
+ if resolved_md is None:
1008
+ active_dir = self.find_active_skill(skill_name)
1009
+ if active_dir:
1010
+ resolved_md = active_dir / "SKILL.md"
1011
+
1012
+ if resolved_md is not None:
1013
+ explicit_cat = self.parse_skill_frontmatter_field(resolved_md, "category")
1014
+ if explicit_cat:
1015
+ return explicit_cat
1016
+
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
+ ]:
1025
+ return "General & Utility Skills"
1026
+
1027
+ rules = self.load_config()["category_rules"]
533
1028
  text = f"{skill_name} {skill_desc}".lower()
534
- if any(k in text for k in ["gemini", "adk", "live api", "llm agent", "vertex ai"]):
535
- return "Gemini API & AI Agents"
536
- if any(k in text for k in ["android", "gradle", "apk", "adb"]):
537
- return "Android Development"
538
- if any(k in text for k in ["bigquery", "dbt", "dataform", "data warehouse", "lakehouse"]):
539
- return "BigQuery & Data Warehouse"
540
- if any(k in text for k in ["alloydb", "omni"]):
541
- return "AlloyDB"
542
- if any(k in text for k in ["cloud sql", "postgres", "mysql"]):
543
- return "Cloud SQL"
544
- if any(k in text for k in ["protein", "alphafold", "pdb", "dna", "rna", "chembl", "bioinformatics", "variant", "genome", "pymol"]):
545
- return "Science & Biomedicine"
546
- if any(k in text for k in ["gcp", "airflow", "composer", "spanner", "dataflow", "dataproc", "pubsub", "cloud storage"]):
547
- return "GCP & Data Engineering"
1029
+ normalized_text = re.sub(r"[-_]+", " ", text)
1030
+
1031
+ for cat, keywords in rules.items():
1032
+ for kw in keywords:
1033
+ if self._keyword_matches(kw, text, normalized_text):
1034
+ return cat
1035
+
548
1036
  return "General & Utility Skills"
549
1037
 
550
1038
  def sync(self, dry_run=False, keep_active=False, force=False, protect_skills=None):
@@ -556,9 +1044,7 @@ class SkillVault:
556
1044
  print(f" Vault Store: {self.archive_dir}")
557
1045
  print("==================================================\n")
558
1046
 
559
- core_set = set(DEFAULT_CORE_SKILLS)
560
- if protect_skills:
561
- core_set.update(protect_skills)
1047
+ core_set = self.get_core_skills(protect_skills)
562
1048
 
563
1049
  active_skills = self.get_active_skills()
564
1050
  manifest = self.load_manifest()
@@ -571,8 +1057,13 @@ class SkillVault:
571
1057
  retained_core = []
572
1058
 
573
1059
  for name, data in sorted(active_skills.items()):
1060
+ if name == "skill-vault":
1061
+ retained_core.append(name)
1062
+ continue
1063
+
574
1064
  active_path = Path(data["path"])
575
- is_core = name in core_set
1065
+ skill_md_path = active_path / "SKILL.md"
1066
+ is_core = (name in core_set) or self.is_core_skill_frontmatter(skill_md_path)
576
1067
 
577
1068
  if name in manifest_map:
578
1069
  item = manifest_map[name]
@@ -582,11 +1073,17 @@ class SkillVault:
582
1073
 
583
1074
  recency = compare_skill_recency(active_path, archived_path)
584
1075
  if recency > 0 or force:
585
- to_ingest_update.append((name, data, item.get("category") or self.infer_category(name, data["description"])))
1076
+ to_ingest_update.append(
1077
+ (
1078
+ name,
1079
+ data,
1080
+ item.get("category") or self.infer_category(name, data["description"], skill_md_path),
1081
+ )
1082
+ )
586
1083
  else:
587
1084
  in_sync.append(name)
588
1085
  else:
589
- assigned_cat = self.infer_category(name, data["description"])
1086
+ assigned_cat = self.infer_category(name, data["description"], skill_md_path)
590
1087
  to_ingest_new.append((name, data, assigned_cat))
591
1088
 
592
1089
  if is_core:
@@ -617,7 +1114,10 @@ class SkillVault:
617
1114
  total_ingested = 0
618
1115
  items_to_write = to_ingest_new + to_ingest_update
619
1116
  for name, data, cat in items_to_write:
620
- active_path = Path(data["path"])
1117
+ active_path = Path(data["path"]).resolve()
1118
+ if self.archive_dir in active_path.parents or active_path == self.base_dir:
1119
+ continue
1120
+
621
1121
  if name in manifest_map and manifest_map[name].get("archived_path"):
622
1122
  dest = self.resolve_portable_path(manifest_map[name]["archived_path"])
623
1123
  else:
@@ -643,6 +1143,8 @@ class SkillVault:
643
1143
  if data.get("single_skill_dir"):
644
1144
  for sub in active_path.iterdir():
645
1145
  if sub.is_dir():
1146
+ if (sub / "SKILL.md").exists():
1147
+ continue
646
1148
  shutil.rmtree(sub)
647
1149
  else:
648
1150
  sub.unlink()
@@ -798,7 +1300,12 @@ class SkillVault:
798
1300
  shutil.copytree(active_path, dest_dir)
799
1301
 
800
1302
  existing_cat = manifest_map.get(skill_name, {}).get("category")
801
- assigned_cat = category_name or existing_cat or "General & Utility Skills"
1303
+ inferred_cat = self.infer_category(
1304
+ skill_name,
1305
+ self.parse_skill_description(active_path / "SKILL.md"),
1306
+ active_path / "SKILL.md",
1307
+ )
1308
+ assigned_cat = category_name or existing_cat or inferred_cat
802
1309
 
803
1310
  manifest_map[skill_name] = {
804
1311
  "name": skill_name,
@@ -852,31 +1359,208 @@ class SkillVault:
852
1359
  print("No matching skills found to restore.")
853
1360
  return
854
1361
 
1362
+ disk_skills = self.get_archived_skill_folders()
1363
+
855
1364
  for item in targets:
856
- archived_path = self.resolve_portable_path(item["archived_path"])
857
- original_path = self.resolve_portable_path(item["original_path"])
1365
+ skill_name = item["name"]
1366
+ archived_path = self.resolve_portable_path(item.get("archived_path", ""))
1367
+ disk_cand = disk_skills.get(skill_name)
1368
+ if disk_cand and disk_cand["has_skill_md"]:
1369
+ if not (archived_path / "SKILL.md").exists() or compare_skill_recency(disk_cand["folder"], archived_path) > 0:
1370
+ archived_path = disk_cand["folder"]
858
1371
 
859
- if not archived_path.exists():
1372
+ original_path = self.resolve_original_path(item.get("original_path", ""), skill_name=skill_name)
1373
+
1374
+ if not (archived_path / "SKILL.md").exists():
860
1375
  print(f"[Error] Missing archive source: {archived_path}")
861
1376
  continue
862
1377
 
863
- original_path.parent.mkdir(parents=True, exist_ok=True)
864
- if original_path.exists():
1378
+ if (original_path / "SKILL.md").exists():
865
1379
  recency = compare_skill_recency(archived_path, original_path)
866
1380
  if recency > 0 or force:
867
- shutil.rmtree(original_path)
868
- shutil.copytree(archived_path, original_path)
869
- print(f"[Restored] Updated L1 with newer L2 version: {item['name']} -> {original_path}")
1381
+ self._copy_skill_safely(archived_path, original_path)
1382
+ print(f"[Restored] Updated L1 with newer L2 version: {skill_name} -> {original_path}")
870
1383
  continue
871
1384
  else:
872
- print(f"[Skip] Target L1 skill '{item['name']}' is already newer than or equal to L2 archive (use --force to overwrite)")
1385
+ print(f"[Skip] Target L1 skill '{skill_name}' is already newer than or equal to L2 archive (use --force to overwrite)")
873
1386
  continue
874
1387
 
875
- shutil.copytree(archived_path, original_path)
876
- print(f"[Restored] {item['name']} -> {original_path}")
1388
+ self._copy_skill_safely(archived_path, original_path)
1389
+ print(f"[Restored] {skill_name} -> {original_path}")
877
1390
 
878
1391
  print("Restoration complete.")
879
1392
 
1393
+ def uninstall(self, dry_run=False, force=False, keep_archive=False, keep_skill=False):
1394
+ """Cleanly restore all archived skills to L1 without overwriting newer L1 versions and remove skill-vault."""
1395
+ root_dir = self.get_root_dir()
1396
+ sv_dir = self.get_skill_vault_dir()
1397
+ manifest = self.load_manifest()
1398
+ manifest_map = {item["name"]: item for item in manifest if "name" in item}
1399
+ disk_skills = self.get_archived_skill_folders()
1400
+
1401
+ candidates = []
1402
+ manifested_arch_paths = set()
1403
+ for item in manifest:
1404
+ skill_name = item["name"]
1405
+ archived_path = self.resolve_portable_path(item.get("archived_path", ""))
1406
+ disk_cand = disk_skills.get(skill_name)
1407
+ if disk_cand and disk_cand["has_skill_md"]:
1408
+ if not (archived_path / "SKILL.md").exists() or compare_skill_recency(disk_cand["folder"], archived_path) > 0:
1409
+ archived_path = disk_cand["folder"]
1410
+ if archived_path.exists():
1411
+ manifested_arch_paths.add(archived_path.resolve())
1412
+ original_path = self.resolve_original_path(item.get("original_path", ""), skill_name=skill_name)
1413
+ candidates.append((skill_name, archived_path, original_path, False))
1414
+
1415
+ # Rescue any unmanifested skills physically sitting in the archive
1416
+ for folder_name, data in sorted(disk_skills.items()):
1417
+ if folder_name in manifest_map or not data["has_skill_md"]:
1418
+ continue
1419
+ if data["folder"].resolve() in manifested_arch_paths:
1420
+ continue
1421
+ original_path = self.resolve_original_path(f"skills/{folder_name}", skill_name=folder_name)
1422
+ candidates.append((folder_name, data["folder"], original_path, True))
1423
+
1424
+ to_restore = []
1425
+ to_upgrade = []
1426
+ to_preserve = []
1427
+ missing_sources = []
1428
+
1429
+ for skill_name, archived_path, original_path, unmanifested in candidates:
1430
+ has_archived = (archived_path / "SKILL.md").exists()
1431
+ has_active = (original_path / "SKILL.md").exists()
1432
+
1433
+ if not has_archived:
1434
+ if has_active:
1435
+ to_preserve.append((skill_name, archived_path, original_path, "Active L1 present; archive source missing"))
1436
+ else:
1437
+ missing_sources.append((skill_name, archived_path, original_path))
1438
+ continue
1439
+
1440
+ if has_active:
1441
+ recency = compare_skill_recency(archived_path, original_path)
1442
+ if recency > 0 or force:
1443
+ reason = "Forced overwrite" if (force and recency <= 0) else "Newer L2 archive version"
1444
+ to_upgrade.append((skill_name, archived_path, original_path, reason))
1445
+ else:
1446
+ to_preserve.append((skill_name, archived_path, original_path, "L1 version is newer or equal"))
1447
+ else:
1448
+ reason = "Unmanifested archive folder rescued" if unmanifested else "Missing from active L1"
1449
+ to_restore.append((skill_name, archived_path, original_path, reason))
1450
+
1451
+ print("==================================================")
1452
+ print(" SKILL VAULT CLEAN UNINSTALL / DECOMMISSION")
1453
+ print(f" Base Directory: {self.base_dir}")
1454
+ print(f" Root Directory: {root_dir}")
1455
+ print(f" Archive Store: {self.archive_dir}")
1456
+ print(f" Skill Folder: {sv_dir if sv_dir else '(None detected)'}")
1457
+ print("==================================================\n")
1458
+
1459
+ print(f"Restoration Plan ({len(candidates)} total archived/discovered skill(s)):")
1460
+ print(f" * Restore to active L1: {len(to_restore)}")
1461
+ for name, _, dst, reason in to_restore:
1462
+ print(f" [RESTORE] {name} -> {dst} ({reason})")
1463
+
1464
+ print(f" * Upgrade active L1 (newer in L2): {len(to_upgrade)}")
1465
+ for name, _, dst, reason in to_upgrade:
1466
+ print(f" [UPGRADE] {name} -> {dst} ({reason})")
1467
+
1468
+ print(f" * Preserve active L1 (newer/equal): {len(to_preserve)}")
1469
+ for name, _, dst, reason in to_preserve:
1470
+ print(f" [PRESERVE] {name} -> {dst} ({reason})")
1471
+
1472
+ if missing_sources:
1473
+ print(f" * Missing archive sources: {len(missing_sources)}")
1474
+ for name, src, _ in missing_sources:
1475
+ print(f" [ERROR] {name} (missing {src})")
1476
+
1477
+ print("\nCleanup Plan:")
1478
+ if keep_archive:
1479
+ if sv_dir and not keep_skill and self.archive_dir.exists() and (sv_dir in self.archive_dir.parents):
1480
+ print(f" * Archive: Relocate {self.archive_dir} -> {root_dir / 'skill_archive'}")
1481
+ else:
1482
+ print(f" * Archive: Keep {self.archive_dir}")
1483
+ else:
1484
+ print(f" * Archive: Remove {self.archive_dir}")
1485
+
1486
+ if keep_skill or not sv_dir:
1487
+ print(f" * Skill: Keep {sv_dir if sv_dir else '(None detected)'}")
1488
+ else:
1489
+ print(f" * Skill: Remove {sv_dir}")
1490
+ print("")
1491
+
1492
+ if missing_sources:
1493
+ print("[Abort] One or more archive sources are missing. Nothing was modified or deleted.")
1494
+ return 1
1495
+
1496
+ if dry_run:
1497
+ print("[Dry Run] Uninstall preview complete. No files were modified or removed.")
1498
+ return 0
1499
+
1500
+ for name, src, dst, _ in to_restore:
1501
+ self._copy_skill_safely(src, dst)
1502
+ print(f"[Restored] {name} -> {dst}")
1503
+
1504
+ for name, src, dst, _ in to_upgrade:
1505
+ self._copy_skill_safely(src, dst)
1506
+ print(f"[Upgraded] {name} -> {dst}")
1507
+
1508
+ # Verification gate before deleting archive or skill-vault folder
1509
+ dirs_to_delete = []
1510
+ if not keep_archive and self.archive_dir.exists():
1511
+ 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())
1514
+
1515
+ verification_errors = []
1516
+ for skill_name, _, original_path, _ in to_restore + to_upgrade + to_preserve:
1517
+ orig_resolved = Path(original_path).resolve()
1518
+ skill_md = orig_resolved / "SKILL.md"
1519
+ if not skill_md.exists() or skill_md.stat().st_size == 0:
1520
+ verification_errors.append(f"Missing or empty SKILL.md for '{skill_name}' at {skill_md}")
1521
+ continue
1522
+ for del_dir in dirs_to_delete:
1523
+ if orig_resolved == del_dir or del_dir in orig_resolved.parents:
1524
+ verification_errors.append(
1525
+ f"Destination '{orig_resolved}' for '{skill_name}' is inside '{del_dir}' which is scheduled for deletion"
1526
+ )
1527
+
1528
+ if verification_errors:
1529
+ print("\n[Abort] Verification failed. Preserving archive and skill-vault to prevent data loss:")
1530
+ for err in verification_errors:
1531
+ print(f" [X] {err}")
1532
+ return 1
1533
+
1534
+ # Relocate or delete archive
1535
+ if keep_archive:
1536
+ if sv_dir and not keep_skill and self.archive_dir.exists() and (sv_dir in self.archive_dir.parents):
1537
+ relocated = (root_dir / "skill_archive").resolve()
1538
+ if self.archive_dir.resolve() != relocated:
1539
+ shutil.copytree(self.archive_dir, relocated, dirs_exist_ok=True)
1540
+ cwd_resolved = Path.cwd().resolve()
1541
+ if cwd_resolved == self.archive_dir.resolve() or self.archive_dir.resolve() in cwd_resolved.parents:
1542
+ os.chdir(root_dir)
1543
+ shutil.rmtree(self.archive_dir)
1544
+ print(f"[Relocated] Archive preserved at: {relocated}")
1545
+ else:
1546
+ if self.archive_dir.exists():
1547
+ cwd_resolved = Path.cwd().resolve()
1548
+ if cwd_resolved == self.archive_dir.resolve() or self.archive_dir.resolve() in cwd_resolved.parents:
1549
+ os.chdir(root_dir)
1550
+ shutil.rmtree(self.archive_dir)
1551
+ print(f"[Removed] Archive directory: {self.archive_dir}")
1552
+
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}")
1559
+
1560
+ total_safe = len(to_restore) + len(to_upgrade) + len(to_preserve)
1561
+ print(f"\n[OK] Clean uninstall complete! {total_safe} skill(s) verified safe in active L1 locations.")
1562
+ return 0
1563
+
880
1564
  def reindex(self):
881
1565
  """Rebuild INDEX.md grouped by manifest categories with portable relative links."""
882
1566
  manifest = self.load_manifest()
@@ -938,8 +1622,224 @@ class SkillVault:
938
1622
  f.write("\n".join(lines).strip() + "\n")
939
1623
 
940
1624
  self.save_manifest(list(manifest_by_folder.values()))
1625
+ updated_routers = self.sync_router_md()
1626
+ for r_path in updated_routers:
1627
+ print(f"[Router Synced] Updated SKILL.md frontmatter: {r_path}")
941
1628
  print(f"[Reindexed] {total_count} skills across {len(categories)} categories (Base: {self.base_dir}).")
942
1629
 
1630
+ def build_router_description(self):
1631
+ """Build a dynamic SKILL.md router description from the current archive manifest."""
1632
+ manifest = self.load_manifest()
1633
+ if not manifest:
1634
+ return (
1635
+ "Universal agent-agnostic skill router, lifecycle manager, and tiered storage engine for AI coding agents.\n"
1636
+ " ALWAYS use this skill whenever a task involves specialized domain skills, frameworks, or tools not currently loaded in active context memory (L1), or when managing skill context bloat.\n"
1637
+ " Search cold storage (L2) on demand via 'python scripts/skill_vault.py search \"<keyword>\"', view 'skill_archive/INDEX.md', or dynamically mount skills via 'restore', 'import', or 'optimize'."
1638
+ )
1639
+
1640
+ grouped = {}
1641
+ for item in manifest:
1642
+ cat = item.get("category") or "General & Utility Skills"
1643
+ grouped.setdefault(cat, []).append(item["name"])
1644
+
1645
+ sorted_cats = sorted(
1646
+ grouped.keys(),
1647
+ key=lambda c: (c == "General & Utility Skills", c.lower()),
1648
+ )
1649
+ cat_entries = []
1650
+ for idx, cat in enumerate(sorted_cats, start=1):
1651
+ samples = ", ".join(sorted(grouped[cat], key=str.lower)[:4])
1652
+ cat_entries.append(f"({idx}) {cat} ({samples})")
1653
+ formatted_categories = ",\n ".join(cat_entries)
1654
+
1655
+ return (
1656
+ f"Universal agent-agnostic skill router and tiered storage manager for {len(manifest)} specialized domain skill(s) in cold storage.\n"
1657
+ f" ALWAYS use this skill whenever the task involves domains or tools not in active memory, including:\n"
1658
+ f" {formatted_categories}.\n"
1659
+ f" Search or restore skills on demand via 'python scripts/skill_vault.py search \"<keyword>\"', view 'skill_archive/INDEX.md', or run 'restore <name>'."
1660
+ )
1661
+
1662
+ def _get_router_skill_md_candidates(self):
1663
+ """Locate candidate SKILL.md files belonging to skill-vault within base_dir."""
1664
+ raw_candidates = [
1665
+ self.skills_dir / "skill-vault" / "SKILL.md",
1666
+ self.base_dir / ".agents" / "skills" / "skill-vault" / "SKILL.md",
1667
+ self.base_dir / ".claude" / "skills" / "skill-vault" / "SKILL.md",
1668
+ ]
1669
+ if self.archive_dir.exists():
1670
+ raw_candidates.append(self.base_dir / "SKILL.md")
1671
+
1672
+ seen = set()
1673
+ candidates = []
1674
+ for cand in raw_candidates:
1675
+ resolved = cand.resolve()
1676
+ if resolved not in seen:
1677
+ seen.add(resolved)
1678
+ candidates.append(cand)
1679
+ return candidates
1680
+
1681
+ def sync_router_md(self, target_skill_md=None, force=False):
1682
+ """Synchronize skill-vault's SKILL.md frontmatter description with the active vault categories."""
1683
+ candidates = [Path(target_skill_md)] if target_skill_md else self._get_router_skill_md_candidates()
1684
+ new_desc = self.build_router_description()
1685
+ new_desc_block = f"description: >-\n {new_desc}"
1686
+ desc_pattern = re.compile(
1687
+ r"^description:\s*(?:>[-+]?|\|[-+]?)?\s*\n?.*?(?=\n[a-zA-Z0-9_-]+:|\Z)",
1688
+ re.DOTALL | re.MULTILINE,
1689
+ )
1690
+
1691
+ updated = []
1692
+ for cand in candidates:
1693
+ if not cand.exists() or self.parse_skill_name(cand) != "skill-vault":
1694
+ continue
1695
+
1696
+ current_desc = self.parse_skill_description(cand)
1697
+ if not force and "Universal agent-agnostic skill router" not in current_desc:
1698
+ continue
1699
+
1700
+ content = cand.read_text(encoding="utf-8", errors="replace")
1701
+ fm_match = re.match(r"^(---\s*\n)(.*?)(\n---(?:\s*\n|\s*\Z))", content, re.DOTALL)
1702
+ if not fm_match:
1703
+ continue
1704
+
1705
+ fm_text = fm_match.group(2)
1706
+ if desc_pattern.search(fm_text):
1707
+ new_fm = desc_pattern.sub(lambda _: new_desc_block, fm_text, count=1)
1708
+ else:
1709
+ new_fm = fm_text.rstrip() + "\n" + new_desc_block
1710
+
1711
+ new_content = fm_match.group(1) + new_fm + fm_match.group(3) + content[fm_match.end():]
1712
+ if new_content != content:
1713
+ cand.write_text(new_content, encoding="utf-8")
1714
+ updated.append(cand)
1715
+
1716
+ return updated
1717
+
1718
+ def manage_config(
1719
+ self,
1720
+ show=False,
1721
+ init_config=False,
1722
+ add_core=None,
1723
+ remove_core=None,
1724
+ add_fingerprint=None,
1725
+ add_category_rule=None,
1726
+ sync_prompt=False,
1727
+ ):
1728
+ """Inspect or update vault_config.json and dynamically synchronize the router prompt."""
1729
+ def _normalize_pairs(pairs):
1730
+ if not pairs:
1731
+ return []
1732
+ if len(pairs) == 2 and isinstance(pairs[0], str) and isinstance(pairs[1], str):
1733
+ return [pairs]
1734
+ return pairs
1735
+
1736
+ fp_pairs = _normalize_pairs(add_fingerprint)
1737
+ rule_pairs = _normalize_pairs(add_category_rule)
1738
+ mutating = bool(init_config or add_core or remove_core or fp_pairs or rule_pairs)
1739
+
1740
+ if init_config:
1741
+ effective = self.load_config()
1742
+ self.save_config(effective)
1743
+ print(f"[Config Initialized] Wrote vault configuration to: {self.config_file}")
1744
+
1745
+ if add_core or remove_core or fp_pairs or rule_pairs:
1746
+ raw_cfg = self._load_raw_config()
1747
+
1748
+ if add_core:
1749
+ core_list = list(raw_cfg.get("core_skills", []))
1750
+ disabled_list = list(raw_cfg.get("disabled_core_skills", []))
1751
+ for skill in add_core:
1752
+ s = skill.strip()
1753
+ if not s:
1754
+ continue
1755
+ if s in disabled_list:
1756
+ disabled_list.remove(s)
1757
+ if s not in core_list and s not in DEFAULT_CORE_SKILLS:
1758
+ core_list.append(s)
1759
+ elif s not in core_list and self.config_file.exists():
1760
+ core_list.append(s)
1761
+ raw_cfg["core_skills"] = core_list
1762
+ if disabled_list or "disabled_core_skills" in raw_cfg:
1763
+ raw_cfg["disabled_core_skills"] = disabled_list
1764
+ print(f"[Config Updated] Added core skill(s): {', '.join(add_core)}")
1765
+
1766
+ if remove_core:
1767
+ core_list = list(raw_cfg.get("core_skills", []))
1768
+ disabled_list = list(raw_cfg.get("disabled_core_skills", []))
1769
+ for skill in remove_core:
1770
+ s = skill.strip()
1771
+ if not s:
1772
+ continue
1773
+ if s in core_list:
1774
+ core_list.remove(s)
1775
+ if s in DEFAULT_CORE_SKILLS and s not in disabled_list:
1776
+ disabled_list.append(s)
1777
+ raw_cfg["core_skills"] = core_list
1778
+ raw_cfg["disabled_core_skills"] = disabled_list
1779
+ print(f"[Config Updated] Removed core skill(s): {', '.join(remove_core)}")
1780
+
1781
+ if fp_pairs:
1782
+ fp_map = dict(raw_cfg.get("workspace_fingerprints", {}))
1783
+ for cat, pat in fp_pairs:
1784
+ c = cat.strip()
1785
+ p = pat.strip()
1786
+ if not c or not p:
1787
+ continue
1788
+ pats = list(fp_map.get(c, []))
1789
+ if p not in pats:
1790
+ pats.append(p)
1791
+ fp_map[c] = pats
1792
+ print(f"[Config Updated] Added workspace fingerprint: [{c}] -> '{p}'")
1793
+ raw_cfg["workspace_fingerprints"] = fp_map
1794
+
1795
+ if rule_pairs:
1796
+ rule_map = dict(raw_cfg.get("category_rules", {}))
1797
+ for cat, kw in rule_pairs:
1798
+ c = cat.strip()
1799
+ k = kw.strip()
1800
+ if not c or not k:
1801
+ continue
1802
+ kws = list(rule_map.get(c, []))
1803
+ if k not in kws:
1804
+ kws.append(k)
1805
+ # Place updated custom category first so overrides take precedence
1806
+ rule_map = {c: kws, **{existing_c: existing_kws for existing_c, existing_kws in rule_map.items() if existing_c != c}}
1807
+ print(f"[Config Updated] Added category rule: [{c}] <- '{k}'")
1808
+ raw_cfg["category_rules"] = rule_map
1809
+
1810
+ self.save_config(raw_cfg)
1811
+
1812
+ if sync_prompt:
1813
+ updated = self.sync_router_md(force=True)
1814
+ if updated:
1815
+ for p in updated:
1816
+ print(f"[Router Synced] Updated SKILL.md frontmatter: {p}")
1817
+ else:
1818
+ print("[Router Sync] No matching skill-vault SKILL.md found to update.")
1819
+
1820
+ if show or (not mutating and not sync_prompt):
1821
+ effective = self.load_config()
1822
+ config_status = "Custom (vault_config.json present)" if self.config_file.exists() else "Built-in Universal Defaults (no vault_config.json)"
1823
+ router_cands = [str(p) for p in self._get_router_skill_md_candidates() if p.exists()]
1824
+ print("==================================================")
1825
+ print(" SKILL VAULT CONFIGURATION")
1826
+ print(f" Base Directory: {self.base_dir}")
1827
+ print(f" Config File: {self.config_file}")
1828
+ print(f" Mode: {config_status}")
1829
+ print("==================================================\n")
1830
+ print(f"Protected Core Skills ({len(effective['core_skills'])}):")
1831
+ print(f" {', '.join(effective['core_skills'])}\n")
1832
+ print(f"Workspace Fingerprint Categories ({len(effective['workspace_fingerprints'])}):")
1833
+ for cat, pats in effective["workspace_fingerprints"].items():
1834
+ print(f" * {cat}: {len(pats)} pattern(s)")
1835
+ print(f"\nCategory Inference Rules ({len(effective['category_rules'])}):")
1836
+ for cat, kws in effective["category_rules"].items():
1837
+ print(f" * {cat}: {len(kws)} keyword(s)")
1838
+ print(f"\nRouter SKILL.md Candidates Found: {len(router_cands)}")
1839
+ for rc in router_cands:
1840
+ print(f" * {rc}")
1841
+ print("")
1842
+
943
1843
  def verify(self, fix=False):
944
1844
  """Perform a comprehensive bi-directional integrity check across Disk, Manifest, and INDEX.md."""
945
1845
  print("==================================================")
@@ -1369,6 +2269,27 @@ def main():
1369
2269
  p_imp.add_argument("--force", action="store_true", help="Overwrite existing skill in project regardless of recency")
1370
2270
  p_imp.add_argument("--dry-run", action="store_true", help="Preview skills that would be imported without copying")
1371
2271
 
2272
+ # Config
2273
+ p_cfg = subparsers.add_parser("config", help="Inspect or customize vault_config.json and sync SKILL.md router prompt")
2274
+ p_cfg.add_argument("--show", action="store_true", help="Show active configuration and defaults")
2275
+ p_cfg.add_argument("--init", action="store_true", dest="init_config", help="Write current configuration defaults to vault_config.json")
2276
+ p_cfg.add_argument("--add-core", nargs="+", metavar="SKILL", help="Add one or more skills to protected core skills")
2277
+ p_cfg.add_argument("--remove-core", nargs="+", metavar="SKILL", help="Remove one or more skills from protected core skills")
2278
+ p_cfg.add_argument("--add-fingerprint", nargs=2, action="append", metavar=("CATEGORY", "PATTERN"), help="Add a workspace file/glob fingerprint for a category")
2279
+ p_cfg.add_argument("--add-category-rule", nargs=2, action="append", metavar=("CATEGORY", "KEYWORD"), help="Add an inference keyword rule for a category")
2280
+ p_cfg.add_argument("--sync-prompt", action="store_true", help="Synchronize SKILL.md router description with archived categories")
2281
+
2282
+ # Uninstall / Eject
2283
+ p_uninst = subparsers.add_parser(
2284
+ "uninstall",
2285
+ aliases=["eject"],
2286
+ help="Cleanly restore all archived skills to L1 (preserving newer L1 versions) and remove skill-vault",
2287
+ )
2288
+ p_uninst.add_argument("--dry-run", action="store_true", help="Preview restoration and removal plan without modifying files")
2289
+ p_uninst.add_argument("--force", action="store_true", help="Overwrite active L1 skills even if L1 copy is newer")
2290
+ p_uninst.add_argument("--keep-archive", action="store_true", help="Preserve skill_archive (relocating it out of skill-vault if nested)")
2291
+ p_uninst.add_argument("--keep-skill", action="store_true", help="Restore all skills and remove archive, but keep the skill-vault skill folder")
2292
+
1372
2293
  args = parser.parse_args()
1373
2294
  mgr = SkillVault(base_dir=args.base_dir)
1374
2295
 
@@ -1427,6 +2348,25 @@ def main():
1427
2348
  dry_run=args.dry_run,
1428
2349
  )
1429
2350
  )
2351
+ elif args.command == "config":
2352
+ mgr.manage_config(
2353
+ show=args.show,
2354
+ init_config=args.init_config,
2355
+ add_core=args.add_core,
2356
+ remove_core=args.remove_core,
2357
+ add_fingerprint=args.add_fingerprint,
2358
+ add_category_rule=args.add_category_rule,
2359
+ sync_prompt=args.sync_prompt,
2360
+ )
2361
+ elif args.command in ("uninstall", "eject"):
2362
+ sys.exit(
2363
+ mgr.uninstall(
2364
+ dry_run=args.dry_run,
2365
+ force=args.force,
2366
+ keep_archive=args.keep_archive,
2367
+ keep_skill=args.keep_skill,
2368
+ )
2369
+ )
1430
2370
 
1431
2371
 
1432
2372
  if __name__ == "__main__":