@jcorpac/skill-vault 1.4.0 → 1.7.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
@@ -94,6 +94,22 @@ python scripts/skill_vault.py verify
94
94
  | `skill-vault restore --category "<Cat>"` | Restore all skills in a specific category. |
95
95
  | `skill-vault search "<query>"` | Search skills across names, descriptions, and categories. |
96
96
  | `skill-vault reindex` | Regenerate `INDEX.md` and sync `backup_manifest.json`. |
97
+ | `skill-vault sync` | Auto-scan plugins & active dirs, ingest new/updated skills, and prune non-core skills. |
98
+ | `skill-vault sync --dry-run` | Preview new/updated skills to ingest without moving or deleting files. |
99
+ | `skill-vault sync --keep-active` | Ingest new/updated skills into the vault while keeping all active. |
100
+ | `skill-vault import <name>` | Import a skill from vault into project directory (e.g. `./skills` or `./.agents/skills`). |
101
+ | `skill-vault import --category "<Cat>"` | Import all skills in a category into the current project. |
102
+ | `skill-vault import --pattern "gcp-*"` | Import matching skills via glob pattern into the project. |
103
+ | `skill-vault import <name> --dest <path>` | Import skill into an explicit project destination folder. |
104
+ | `skill-vault import <name> --vault-dir <path>` | Import from an explicit source vault (defaults to global archive or base). |
105
+ | `skill-vault import <name> --force` | Overwrite existing project skill regardless of recency. |
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. |
97
113
  | `skill-vault verify` | Audit bi-directional consistency across disk, manifest, and index. |
98
114
  | `skill-vault verify --fix` | Audit and automatically self-heal all detected discrepancies. |
99
115
 
@@ -106,6 +122,8 @@ python scripts/skill_vault.py verify
106
122
  3. **Zero Runtime Dependencies**: The core engine requires only Python 3 standard library (`os`, `sys`, `json`, `re`, `shutil`, `hashlib`, `argparse`, `pathlib`).
107
123
  4. **Self-Healing Integrity**: Detects orphaned folders, phantom manifest entries, broken markdown links, and duplicate aliases.
108
124
  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.
125
+ 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:`).
126
+ 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.
109
127
 
110
128
  ---
111
129
 
package/SKILL.md CHANGED
@@ -1,17 +1,10 @@
1
1
  ---
2
2
  name: skill-vault
3
+ version: 1.7.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
@@ -150,6 +143,67 @@ Skill Vault automatically protects newer skills and prevents regressions when ar
150
143
  - **`optimize`**: Automatically detects and upgrades active L1 skills if newer versions exist in the vault, while archiving unneeded skills safely.
151
144
  - **`--force`**: Bypasses recency checks on `archive`, `restore`, or `optimize` when an intentional overwrite is required.
152
145
 
146
+ ### J. Project-Level Skill Importing
147
+ To import skills from a global vault (e.g., `~/.gemini/config/skill_archive` or `$SKILL_VAULT_BASE`) into a project workspace on demand:
148
+ ```bash
149
+ # Import a specific skill into the current project (defaults to ./skills or ./.agents/skills)
150
+ python scripts/skill_vault.py import <skill_name>
151
+
152
+ # Import all skills in a category into the current project
153
+ python scripts/skill_vault.py import --category "BigQuery & Data Warehouse"
154
+
155
+ # Import matching skills via glob pattern
156
+ python scripts/skill_vault.py import --pattern "gcp-*"
157
+
158
+ # Import into an explicit project destination
159
+ python scripts/skill_vault.py import <skill_name> --dest "./.agents/skills"
160
+
161
+ # Preview what would be imported without copying
162
+ python scripts/skill_vault.py import <skill_name> --dry-run
163
+
164
+ # Force overwrite of project skill if already present
165
+ python scripts/skill_vault.py import <skill_name> --force
166
+ ```
167
+
168
+ ### K. Automated Plugin Ingestion & Syncing (`sync`)
169
+ Whenever plugins are installed or updated, use `sync` to scan all active locations and plugins, ingest new/updated skills into the vault, protect the Core Foundation Skills, and prune non-core skills:
170
+ ```bash
171
+ # Scan plugins and active skills, ingest new/updated skills, and prune non-core active skills
172
+ python scripts/skill_vault.py sync
173
+
174
+ # Preview what would be ingested and pruned without moving or deleting files
175
+ python scripts/skill_vault.py sync --dry-run
176
+
177
+ # Ingest new/updated skills into the vault while keeping all active
178
+ python scripts/skill_vault.py sync --keep-active
179
+ ```
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
+
153
207
  ---
154
208
 
155
209
  ## 3. Environment & OS Compatibility Guidelines
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jcorpac/skill-vault",
3
- "version": "1.4.0",
3
+ "version": "1.7.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)."""
@@ -175,8 +411,103 @@ class SkillVault:
175
411
  self.archive_dir = self.base_dir / "skill_archive"
176
412
  self.manifest_file = self.archive_dir / "backup_manifest.json"
177
413
  self.index_file = self.archive_dir / "INDEX.md"
414
+ self.config_file = self.archive_dir / "vault_config.json"
178
415
  self.skills_dir = self.base_dir / "skills"
179
416
 
417
+ def _load_raw_config(self):
418
+ """Read raw vault_config.json without creating files or merging defaults."""
419
+ if self.config_file.exists():
420
+ try:
421
+ with open(self.config_file, "r", encoding="utf-8") as f:
422
+ data = json.load(f)
423
+ return data if isinstance(data, dict) else {}
424
+ except Exception as e:
425
+ print(f"[Warning] Failed to parse {self.config_file}: {e}")
426
+ return {}
427
+
428
+ def load_config(self):
429
+ """Load vault_config.json if present and merge with universal defaults."""
430
+ user_cfg = self._load_raw_config()
431
+
432
+ disabled_core = set(user_cfg.get("disabled_core_skills", []))
433
+ core_skills = (set(DEFAULT_CORE_SKILLS) | set(user_cfg.get("core_skills", []))) - disabled_core
434
+
435
+ merged_fp = {cat: list(pats) for cat, pats in WORKSPACE_FINGERPRINTS.items()}
436
+ for cat, pats in user_cfg.get("workspace_fingerprints", {}).items():
437
+ if cat in merged_fp:
438
+ merged_fp[cat] = list(dict.fromkeys(list(pats) + merged_fp[cat]))
439
+ else:
440
+ merged_fp[cat] = list(pats)
441
+
442
+ custom_rules = user_cfg.get("category_rules", {})
443
+ merged_rules = {}
444
+ # Evaluate non-default custom categories first so user overrides take precedence
445
+ for cat, kws in custom_rules.items():
446
+ if cat not in DEFAULT_CATEGORY_RULES:
447
+ merged_rules[cat] = list(kws)
448
+ for cat, kws in custom_rules.items():
449
+ if cat in DEFAULT_CATEGORY_RULES:
450
+ merged_rules[cat] = list(dict.fromkeys(list(kws) + list(DEFAULT_CATEGORY_RULES[cat])))
451
+ for cat, kws in DEFAULT_CATEGORY_RULES.items():
452
+ if cat not in merged_rules:
453
+ merged_rules[cat] = list(kws)
454
+
455
+ return {
456
+ "core_skills": sorted(core_skills),
457
+ "disabled_core_skills": sorted(disabled_core),
458
+ "workspace_fingerprints": merged_fp,
459
+ "category_rules": merged_rules,
460
+ }
461
+
462
+ def save_config(self, config_data):
463
+ """Persist configuration to vault_config.json."""
464
+ self.archive_dir.mkdir(parents=True, exist_ok=True)
465
+ with open(self.config_file, "w", encoding="utf-8") as f:
466
+ json.dump(config_data, f, indent=2, ensure_ascii=False)
467
+
468
+ def get_core_skills(self, extra_protected=None):
469
+ """Return effective set of protected core skill names."""
470
+ core_set = set(self.load_config()["core_skills"])
471
+ if extra_protected:
472
+ core_set.update(extra_protected)
473
+ return core_set
474
+
475
+ def parse_skill_frontmatter_field(self, skill_md_path, field_name):
476
+ """Extract a single scalar field from SKILL.md YAML frontmatter."""
477
+ skill_md_path = Path(skill_md_path)
478
+ if not skill_md_path.exists():
479
+ return None
480
+ try:
481
+ content = skill_md_path.read_text(encoding="utf-8", errors="ignore")
482
+ fm_match = re.search(r"^---\s*\n(.*?)\n---", content, re.DOTALL)
483
+ if fm_match:
484
+ pattern = rf"^{re.escape(field_name)}:\s*([^\n]+)"
485
+ match = re.search(pattern, fm_match.group(1), re.MULTILINE | re.IGNORECASE)
486
+ if match:
487
+ val = match.group(1).strip().strip("'\"")
488
+ return val if val else None
489
+ except Exception:
490
+ pass
491
+ return None
492
+
493
+ def is_core_skill_frontmatter(self, skill_md_path):
494
+ """Return True if SKILL.md frontmatter marks the skill as core/pinned/always_active."""
495
+ for field in ("core", "pinned", "always_active"):
496
+ val = self.parse_skill_frontmatter_field(skill_md_path, field)
497
+ if val and val.strip().lower() in {"true", "yes", "1"}:
498
+ return True
499
+ return False
500
+
501
+ def _keyword_matches(self, keyword, text, normalized_text):
502
+ """Match a category keyword against skill name/description text safely."""
503
+ kw = str(keyword).lower().strip()
504
+ if not kw:
505
+ return False
506
+ if kw.isalpha() and len(kw) <= 4:
507
+ pattern = rf"(?<![a-z]){re.escape(kw)}(?![a-z])"
508
+ return bool(re.search(pattern, text) or re.search(pattern, normalized_text))
509
+ return kw in text or kw in normalized_text
510
+
180
511
  def init(self):
181
512
  """Bootstrap standard directory structure for a new workspace or repository."""
182
513
  self.skills_dir.mkdir(parents=True, exist_ok=True)
@@ -208,27 +539,70 @@ class SkillVault:
208
539
  if p.exists() and p not in dirs:
209
540
  dirs.append(p)
210
541
 
542
+ # If base_dir is nested inside a skills folder (e.g. skills/skill-vault)
543
+ if self.base_dir.parent.name == "skills" and self.base_dir.parent.exists():
544
+ if self.base_dir.parent not in dirs:
545
+ dirs.append(self.base_dir.parent)
546
+ parent_plugins = self.base_dir.parent.parent / "plugins"
547
+ if parent_plugins.exists():
548
+ for p in parent_plugins.iterdir():
549
+ if p.is_dir() and (p / "skills").exists() and (p / "skills") not in dirs:
550
+ dirs.append(p / "skills")
551
+
211
552
  plugins_dir = self.base_dir / "plugins"
212
553
  if plugins_dir.exists():
213
554
  for p in plugins_dir.iterdir():
214
- if p.is_dir() and (p / "skills").exists():
555
+ if p.is_dir() and (p / "skills").exists() and (p / "skills") not in dirs:
215
556
  dirs.append(p / "skills")
216
557
  return dirs
217
558
 
559
+ def parse_skill_name(self, skill_md_path):
560
+ """Extract name from SKILL.md frontmatter."""
561
+ skill_md_path = Path(skill_md_path)
562
+ if not skill_md_path.exists():
563
+ return None
564
+ try:
565
+ content = skill_md_path.read_text(encoding="utf-8", errors="ignore")
566
+ fm_match = re.search(r"^---\s*\n(.*?)\n---", content, re.DOTALL)
567
+ if fm_match:
568
+ n_match = re.search(r"^name:\s*([^\n]+)", fm_match.group(1), re.MULTILINE)
569
+ if n_match:
570
+ return n_match.group(1).strip().strip("'\"")
571
+ except Exception:
572
+ pass
573
+ return None
574
+
218
575
  def get_active_skills(self):
219
- """Discover all currently active skills on disk."""
576
+ """Discover all currently active skills on disk across standard and plugin layouts."""
220
577
  active = {}
221
578
  for search_dir in self.get_active_skill_dirs():
222
- if search_dir.exists():
223
- for folder in search_dir.iterdir():
224
- if folder.is_dir() and (folder / "SKILL.md").exists():
225
- desc = self.parse_skill_description(folder / "SKILL.md")
226
- active[folder.name] = {
227
- "name": folder.name,
228
- "path": str(folder),
229
- "relative_path": self.make_portable_path(folder),
230
- "description": desc,
231
- }
579
+ if not search_dir.exists():
580
+ continue
581
+
582
+ # Case 1: search_dir contains subdirectories with SKILL.md (e.g. skills/<name>/SKILL.md)
583
+ for folder in search_dir.iterdir():
584
+ if folder.is_dir() and (folder / "SKILL.md").exists():
585
+ skill_name = self.parse_skill_name(folder / "SKILL.md") or folder.name
586
+ desc = self.parse_skill_description(folder / "SKILL.md")
587
+ active[skill_name] = {
588
+ "name": skill_name,
589
+ "path": str(folder),
590
+ "relative_path": self.make_portable_path(folder),
591
+ "description": desc,
592
+ "single_skill_dir": False,
593
+ }
594
+
595
+ # Case 2: search_dir itself has SKILL.md directly (e.g. plugins/<plugin>/skills/SKILL.md)
596
+ if (search_dir / "SKILL.md").exists():
597
+ skill_name = self.parse_skill_name(search_dir / "SKILL.md") or search_dir.parent.name
598
+ desc = self.parse_skill_description(search_dir / "SKILL.md")
599
+ active[skill_name] = {
600
+ "name": skill_name,
601
+ "path": str(search_dir),
602
+ "relative_path": self.make_portable_path(search_dir),
603
+ "description": desc,
604
+ "single_skill_dir": True,
605
+ }
232
606
  return active
233
607
 
234
608
  def get_archived_skill_folders(self):
@@ -359,8 +733,10 @@ class SkillVault:
359
733
  """Inspect workspace files and return matched skill categories."""
360
734
  target_ws = Path(workspace_path).resolve() if workspace_path else Path.cwd().resolve()
361
735
  matched = {}
736
+ config = self.load_config()
737
+ fingerprints = config["workspace_fingerprints"]
362
738
 
363
- for category, patterns in WORKSPACE_FINGERPRINTS.items():
739
+ for category, patterns in fingerprints.items():
364
740
  for pat in patterns:
365
741
  if "*" in pat:
366
742
  matches = list(target_ws.glob(pat)) + list(target_ws.glob(f"**/{pat}"))[:5]
@@ -372,6 +748,36 @@ class SkillVault:
372
748
  matched.setdefault(category, []).append(pat)
373
749
  break
374
750
 
751
+ # Inspect categories present in manifest for workspace filename/directory keyword matches
752
+ manifest = self.load_manifest()
753
+ manifest_categories = {m.get("category") for m in manifest if m.get("category")}
754
+ unmatched_cats = [c for c in sorted(manifest_categories) if c not in matched]
755
+ if unmatched_cats and target_ws.exists():
756
+ 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
+ for cat in unmatched_cats:
771
+ words = [
772
+ w.lower()
773
+ for w in re.findall(r"[a-zA-Z0-9]+", cat)
774
+ if len(w) > 2 and w.lower() not in stop_words
775
+ ]
776
+ for w in words:
777
+ if w in ws_tokens:
778
+ matched.setdefault(cat, []).append(ws_tokens[w])
779
+ break
780
+
375
781
  return matched
376
782
 
377
783
  def optimize(self, workspace_path=None, protected_skills=None, dry_run=False, force=False):
@@ -381,9 +787,7 @@ class SkillVault:
381
787
  prioritizing newer versions when versions overlap.
382
788
  """
383
789
  target_ws = Path(workspace_path).resolve() if workspace_path else Path.cwd().resolve()
384
- core_set = set(DEFAULT_CORE_SKILLS)
385
- if protected_skills:
386
- core_set.update(protected_skills)
790
+ core_set = self.get_core_skills(protected_skills)
387
791
 
388
792
  print("==================================================")
389
793
  print(" SKILL VAULT AUTO-OPTIMIZATION")
@@ -409,10 +813,15 @@ class SkillVault:
409
813
  to_keep = []
410
814
 
411
815
  for name, data in active_map.items():
816
+ skill_md_path = Path(data["path"]) / "SKILL.md"
412
817
  if name in core_set:
413
818
  to_keep.append((name, "Core Foundation Skill"))
819
+ elif self.is_core_skill_frontmatter(skill_md_path):
820
+ to_keep.append((name, "Core Foundation Skill (Pinned in Frontmatter)"))
414
821
  else:
415
- skill_cat = manifest_by_name.get(name, {}).get("category", "General & Utility Skills")
822
+ skill_cat = manifest_by_name.get(name, {}).get("category") or self.infer_category(
823
+ name, data["description"], skill_md_path
824
+ )
416
825
  if skill_cat in detected_categories:
417
826
  to_keep.append((name, f"Matched Stack ({skill_cat})"))
418
827
  else:
@@ -483,6 +892,168 @@ class SkillVault:
483
892
 
484
893
  print("\n[OK] Optimization complete! Active context surface is at absolute minimum.")
485
894
 
895
+ # --- Sync & Ingestion Engine ---
896
+
897
+ def infer_category(self, skill_name, skill_desc="", skill_md_path=None):
898
+ """Infer an appropriate category for a skill via frontmatter, custom rules, or universal defaults."""
899
+ resolved_md = Path(skill_md_path) if skill_md_path else None
900
+ if resolved_md is None:
901
+ active_dir = self.find_active_skill(skill_name)
902
+ if active_dir:
903
+ resolved_md = active_dir / "SKILL.md"
904
+
905
+ if resolved_md is not None:
906
+ explicit_cat = self.parse_skill_frontmatter_field(resolved_md, "category")
907
+ if explicit_cat:
908
+ return explicit_cat
909
+
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
+ ]:
918
+ return "General & Utility Skills"
919
+
920
+ rules = self.load_config()["category_rules"]
921
+ text = f"{skill_name} {skill_desc}".lower()
922
+ normalized_text = re.sub(r"[-_]+", " ", text)
923
+
924
+ for cat, keywords in rules.items():
925
+ for kw in keywords:
926
+ if self._keyword_matches(kw, text, normalized_text):
927
+ return cat
928
+
929
+ return "General & Utility Skills"
930
+
931
+ def sync(self, dry_run=False, keep_active=False, force=False, protect_skills=None):
932
+ """Automatically scan plugins and active directories for new or updated skills,
933
+ ingest them into the vault, preserve Core Foundation Skills, and prune non-core active skills."""
934
+ print("==================================================")
935
+ print(" SKILL VAULT AUTO-SYNC & INGEST")
936
+ print(f" Base Directory: {self.base_dir}")
937
+ print(f" Vault Store: {self.archive_dir}")
938
+ print("==================================================\n")
939
+
940
+ core_set = self.get_core_skills(protect_skills)
941
+
942
+ active_skills = self.get_active_skills()
943
+ manifest = self.load_manifest()
944
+ manifest_map = {m["name"]: m for m in manifest}
945
+
946
+ to_ingest_new = []
947
+ to_ingest_update = []
948
+ to_prune = []
949
+ in_sync = []
950
+ retained_core = []
951
+
952
+ for name, data in sorted(active_skills.items()):
953
+ if name == "skill-vault":
954
+ retained_core.append(name)
955
+ continue
956
+
957
+ active_path = Path(data["path"])
958
+ skill_md_path = active_path / "SKILL.md"
959
+ is_core = (name in core_set) or self.is_core_skill_frontmatter(skill_md_path)
960
+
961
+ if name in manifest_map:
962
+ item = manifest_map[name]
963
+ archived_path = self.resolve_portable_path(item.get("archived_path", ""))
964
+ if not archived_path.exists():
965
+ archived_path = self.archive_dir / "skills" / name
966
+
967
+ recency = compare_skill_recency(active_path, archived_path)
968
+ if recency > 0 or force:
969
+ to_ingest_update.append(
970
+ (
971
+ name,
972
+ data,
973
+ item.get("category") or self.infer_category(name, data["description"], skill_md_path),
974
+ )
975
+ )
976
+ else:
977
+ in_sync.append(name)
978
+ else:
979
+ assigned_cat = self.infer_category(name, data["description"], skill_md_path)
980
+ to_ingest_new.append((name, data, assigned_cat))
981
+
982
+ if is_core:
983
+ retained_core.append(name)
984
+ elif not keep_active:
985
+ to_prune.append((name, data))
986
+
987
+ print("Scan Results:")
988
+ print(f" * New skills to ingest into vault: {len(to_ingest_new)}")
989
+ for name, _, cat in to_ingest_new:
990
+ print(f" [NEW] {name} -> Category: {cat}")
991
+
992
+ print(f" * Updated skills to refresh in vault: {len(to_ingest_update)}")
993
+ for name, _, cat in to_ingest_update:
994
+ print(f" [UPDATE] {name} (Newer active version detected)")
995
+
996
+ print(f" * In-sync skills in vault: {len(in_sync)}")
997
+ print(f" * Retained Core Foundation Skills: {len(retained_core)} ({', '.join(sorted(retained_core))})")
998
+ print(f" * Non-core active skills to prune: {len(to_prune)}")
999
+ for name, _ in to_prune:
1000
+ print(f" [PRUNE] {name} (Will be removed from active context to prevent context bloat)")
1001
+ print("")
1002
+
1003
+ if dry_run:
1004
+ print("[Dry Run] Preview complete. No files were modified.")
1005
+ return 0
1006
+
1007
+ total_ingested = 0
1008
+ items_to_write = to_ingest_new + to_ingest_update
1009
+ for name, data, cat in items_to_write:
1010
+ active_path = Path(data["path"]).resolve()
1011
+ if self.archive_dir in active_path.parents or active_path == self.base_dir:
1012
+ continue
1013
+
1014
+ if name in manifest_map and manifest_map[name].get("archived_path"):
1015
+ dest = self.resolve_portable_path(manifest_map[name]["archived_path"])
1016
+ else:
1017
+ dest = self.archive_dir / "skills" / name
1018
+
1019
+ dest.parent.mkdir(parents=True, exist_ok=True)
1020
+ if dest.exists():
1021
+ shutil.rmtree(dest)
1022
+
1023
+ shutil.copytree(active_path, dest)
1024
+ print(f"[Vaulted] {name} -> {dest}")
1025
+
1026
+ manifest_map[name] = {
1027
+ "name": name,
1028
+ "category": cat,
1029
+ "original_path": data["relative_path"],
1030
+ "archived_path": self.make_portable_path(dest),
1031
+ }
1032
+ total_ingested += 1
1033
+
1034
+ for name, data in to_prune:
1035
+ active_path = Path(data["path"])
1036
+ if data.get("single_skill_dir"):
1037
+ for sub in active_path.iterdir():
1038
+ if sub.is_dir():
1039
+ shutil.rmtree(sub)
1040
+ else:
1041
+ sub.unlink()
1042
+ print(f"[Pruned] Emptied single-skill directory: {active_path}")
1043
+ else:
1044
+ if active_path.exists():
1045
+ shutil.rmtree(active_path)
1046
+ print(f"[Pruned] Removed active folder: {active_path}")
1047
+
1048
+ if total_ingested > 0 or to_prune:
1049
+ self.save_manifest(list(manifest_map.values()))
1050
+ self.reindex()
1051
+ self.verify()
1052
+
1053
+ print(f"\n[OK] Sync complete: {total_ingested} skill(s) vaulted/refreshed, {len(to_prune)} active skill(s) pruned.")
1054
+ print(f"Active context memory is clean with {len(retained_core)} Core Foundation Skill(s).\n")
1055
+ return 0
1056
+
486
1057
  # --- Actions ---
487
1058
 
488
1059
  def list_skills(self, show_active=True, show_archived=True, category_filter=None, as_json=False, summary_only=False):
@@ -620,7 +1191,12 @@ class SkillVault:
620
1191
  shutil.copytree(active_path, dest_dir)
621
1192
 
622
1193
  existing_cat = manifest_map.get(skill_name, {}).get("category")
623
- assigned_cat = category_name or existing_cat or "General & Utility Skills"
1194
+ inferred_cat = self.infer_category(
1195
+ skill_name,
1196
+ self.parse_skill_description(active_path / "SKILL.md"),
1197
+ active_path / "SKILL.md",
1198
+ )
1199
+ assigned_cat = category_name or existing_cat or inferred_cat
624
1200
 
625
1201
  manifest_map[skill_name] = {
626
1202
  "name": skill_name,
@@ -760,8 +1336,224 @@ class SkillVault:
760
1336
  f.write("\n".join(lines).strip() + "\n")
761
1337
 
762
1338
  self.save_manifest(list(manifest_by_folder.values()))
1339
+ updated_routers = self.sync_router_md()
1340
+ for r_path in updated_routers:
1341
+ print(f"[Router Synced] Updated SKILL.md frontmatter: {r_path}")
763
1342
  print(f"[Reindexed] {total_count} skills across {len(categories)} categories (Base: {self.base_dir}).")
764
1343
 
1344
+ def build_router_description(self):
1345
+ """Build a dynamic SKILL.md router description from the current archive manifest."""
1346
+ manifest = self.load_manifest()
1347
+ if not manifest:
1348
+ return (
1349
+ "Universal agent-agnostic skill router, lifecycle manager, and tiered storage engine for AI coding agents.\n"
1350
+ " 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"
1351
+ " 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'."
1352
+ )
1353
+
1354
+ grouped = {}
1355
+ for item in manifest:
1356
+ cat = item.get("category") or "General & Utility Skills"
1357
+ grouped.setdefault(cat, []).append(item["name"])
1358
+
1359
+ sorted_cats = sorted(
1360
+ grouped.keys(),
1361
+ key=lambda c: (c == "General & Utility Skills", c.lower()),
1362
+ )
1363
+ cat_entries = []
1364
+ for idx, cat in enumerate(sorted_cats, start=1):
1365
+ samples = ", ".join(sorted(grouped[cat], key=str.lower)[:4])
1366
+ cat_entries.append(f"({idx}) {cat} ({samples})")
1367
+ formatted_categories = ",\n ".join(cat_entries)
1368
+
1369
+ return (
1370
+ f"Universal agent-agnostic skill router and tiered storage manager for {len(manifest)} specialized domain skill(s) in cold storage.\n"
1371
+ f" ALWAYS use this skill whenever the task involves domains or tools not in active memory, including:\n"
1372
+ f" {formatted_categories}.\n"
1373
+ f" Search or restore skills on demand via 'python scripts/skill_vault.py search \"<keyword>\"', view 'skill_archive/INDEX.md', or run 'restore <name>'."
1374
+ )
1375
+
1376
+ def _get_router_skill_md_candidates(self):
1377
+ """Locate candidate SKILL.md files belonging to skill-vault within base_dir."""
1378
+ raw_candidates = [
1379
+ self.skills_dir / "skill-vault" / "SKILL.md",
1380
+ self.base_dir / ".agents" / "skills" / "skill-vault" / "SKILL.md",
1381
+ self.base_dir / ".claude" / "skills" / "skill-vault" / "SKILL.md",
1382
+ ]
1383
+ if self.archive_dir.exists():
1384
+ raw_candidates.append(self.base_dir / "SKILL.md")
1385
+
1386
+ seen = set()
1387
+ candidates = []
1388
+ for cand in raw_candidates:
1389
+ resolved = cand.resolve()
1390
+ if resolved not in seen:
1391
+ seen.add(resolved)
1392
+ candidates.append(cand)
1393
+ return candidates
1394
+
1395
+ def sync_router_md(self, target_skill_md=None, force=False):
1396
+ """Synchronize skill-vault's SKILL.md frontmatter description with the active vault categories."""
1397
+ candidates = [Path(target_skill_md)] if target_skill_md else self._get_router_skill_md_candidates()
1398
+ new_desc = self.build_router_description()
1399
+ new_desc_block = f"description: >-\n {new_desc}"
1400
+ desc_pattern = re.compile(
1401
+ r"^description:\s*(?:>[-+]?|\|[-+]?)?\s*\n?.*?(?=\n[a-zA-Z0-9_-]+:|\Z)",
1402
+ re.DOTALL | re.MULTILINE,
1403
+ )
1404
+
1405
+ updated = []
1406
+ for cand in candidates:
1407
+ if not cand.exists() or self.parse_skill_name(cand) != "skill-vault":
1408
+ continue
1409
+
1410
+ current_desc = self.parse_skill_description(cand)
1411
+ if not force and "Universal agent-agnostic skill router" not in current_desc:
1412
+ continue
1413
+
1414
+ content = cand.read_text(encoding="utf-8", errors="replace")
1415
+ fm_match = re.match(r"^(---\s*\n)(.*?)(\n---(?:\s*\n|\s*\Z))", content, re.DOTALL)
1416
+ if not fm_match:
1417
+ continue
1418
+
1419
+ fm_text = fm_match.group(2)
1420
+ if desc_pattern.search(fm_text):
1421
+ new_fm = desc_pattern.sub(lambda _: new_desc_block, fm_text, count=1)
1422
+ else:
1423
+ new_fm = fm_text.rstrip() + "\n" + new_desc_block
1424
+
1425
+ new_content = fm_match.group(1) + new_fm + fm_match.group(3) + content[fm_match.end():]
1426
+ if new_content != content:
1427
+ cand.write_text(new_content, encoding="utf-8")
1428
+ updated.append(cand)
1429
+
1430
+ return updated
1431
+
1432
+ def manage_config(
1433
+ self,
1434
+ show=False,
1435
+ init_config=False,
1436
+ add_core=None,
1437
+ remove_core=None,
1438
+ add_fingerprint=None,
1439
+ add_category_rule=None,
1440
+ sync_prompt=False,
1441
+ ):
1442
+ """Inspect or update vault_config.json and dynamically synchronize the router prompt."""
1443
+ def _normalize_pairs(pairs):
1444
+ if not pairs:
1445
+ return []
1446
+ if len(pairs) == 2 and isinstance(pairs[0], str) and isinstance(pairs[1], str):
1447
+ return [pairs]
1448
+ return pairs
1449
+
1450
+ fp_pairs = _normalize_pairs(add_fingerprint)
1451
+ rule_pairs = _normalize_pairs(add_category_rule)
1452
+ mutating = bool(init_config or add_core or remove_core or fp_pairs or rule_pairs)
1453
+
1454
+ if init_config:
1455
+ effective = self.load_config()
1456
+ self.save_config(effective)
1457
+ print(f"[Config Initialized] Wrote vault configuration to: {self.config_file}")
1458
+
1459
+ if add_core or remove_core or fp_pairs or rule_pairs:
1460
+ raw_cfg = self._load_raw_config()
1461
+
1462
+ if add_core:
1463
+ core_list = list(raw_cfg.get("core_skills", []))
1464
+ disabled_list = list(raw_cfg.get("disabled_core_skills", []))
1465
+ for skill in add_core:
1466
+ s = skill.strip()
1467
+ if not s:
1468
+ continue
1469
+ if s in disabled_list:
1470
+ disabled_list.remove(s)
1471
+ if s not in core_list and s not in DEFAULT_CORE_SKILLS:
1472
+ core_list.append(s)
1473
+ elif s not in core_list and self.config_file.exists():
1474
+ core_list.append(s)
1475
+ raw_cfg["core_skills"] = core_list
1476
+ if disabled_list or "disabled_core_skills" in raw_cfg:
1477
+ raw_cfg["disabled_core_skills"] = disabled_list
1478
+ print(f"[Config Updated] Added core skill(s): {', '.join(add_core)}")
1479
+
1480
+ if remove_core:
1481
+ core_list = list(raw_cfg.get("core_skills", []))
1482
+ disabled_list = list(raw_cfg.get("disabled_core_skills", []))
1483
+ for skill in remove_core:
1484
+ s = skill.strip()
1485
+ if not s:
1486
+ continue
1487
+ if s in core_list:
1488
+ core_list.remove(s)
1489
+ if s in DEFAULT_CORE_SKILLS and s not in disabled_list:
1490
+ disabled_list.append(s)
1491
+ raw_cfg["core_skills"] = core_list
1492
+ raw_cfg["disabled_core_skills"] = disabled_list
1493
+ print(f"[Config Updated] Removed core skill(s): {', '.join(remove_core)}")
1494
+
1495
+ if fp_pairs:
1496
+ fp_map = dict(raw_cfg.get("workspace_fingerprints", {}))
1497
+ for cat, pat in fp_pairs:
1498
+ c = cat.strip()
1499
+ p = pat.strip()
1500
+ if not c or not p:
1501
+ continue
1502
+ pats = list(fp_map.get(c, []))
1503
+ if p not in pats:
1504
+ pats.append(p)
1505
+ fp_map[c] = pats
1506
+ print(f"[Config Updated] Added workspace fingerprint: [{c}] -> '{p}'")
1507
+ raw_cfg["workspace_fingerprints"] = fp_map
1508
+
1509
+ if rule_pairs:
1510
+ rule_map = dict(raw_cfg.get("category_rules", {}))
1511
+ for cat, kw in rule_pairs:
1512
+ c = cat.strip()
1513
+ k = kw.strip()
1514
+ if not c or not k:
1515
+ continue
1516
+ kws = list(rule_map.get(c, []))
1517
+ if k not in kws:
1518
+ kws.append(k)
1519
+ # Place updated custom category first so overrides take precedence
1520
+ rule_map = {c: kws, **{existing_c: existing_kws for existing_c, existing_kws in rule_map.items() if existing_c != c}}
1521
+ print(f"[Config Updated] Added category rule: [{c}] <- '{k}'")
1522
+ raw_cfg["category_rules"] = rule_map
1523
+
1524
+ self.save_config(raw_cfg)
1525
+
1526
+ if sync_prompt:
1527
+ updated = self.sync_router_md(force=True)
1528
+ if updated:
1529
+ for p in updated:
1530
+ print(f"[Router Synced] Updated SKILL.md frontmatter: {p}")
1531
+ else:
1532
+ print("[Router Sync] No matching skill-vault SKILL.md found to update.")
1533
+
1534
+ if show or (not mutating and not sync_prompt):
1535
+ effective = self.load_config()
1536
+ config_status = "Custom (vault_config.json present)" if self.config_file.exists() else "Built-in Universal Defaults (no vault_config.json)"
1537
+ router_cands = [str(p) for p in self._get_router_skill_md_candidates() if p.exists()]
1538
+ print("==================================================")
1539
+ print(" SKILL VAULT CONFIGURATION")
1540
+ print(f" Base Directory: {self.base_dir}")
1541
+ print(f" Config File: {self.config_file}")
1542
+ print(f" Mode: {config_status}")
1543
+ print("==================================================\n")
1544
+ print(f"Protected Core Skills ({len(effective['core_skills'])}):")
1545
+ print(f" {', '.join(effective['core_skills'])}\n")
1546
+ print(f"Workspace Fingerprint Categories ({len(effective['workspace_fingerprints'])}):")
1547
+ for cat, pats in effective["workspace_fingerprints"].items():
1548
+ print(f" * {cat}: {len(pats)} pattern(s)")
1549
+ print(f"\nCategory Inference Rules ({len(effective['category_rules'])}):")
1550
+ for cat, kws in effective["category_rules"].items():
1551
+ print(f" * {cat}: {len(kws)} keyword(s)")
1552
+ print(f"\nRouter SKILL.md Candidates Found: {len(router_cands)}")
1553
+ for rc in router_cands:
1554
+ print(f" * {rc}")
1555
+ print("")
1556
+
765
1557
  def verify(self, fix=False):
766
1558
  """Perform a comprehensive bi-directional integrity check across Disk, Manifest, and INDEX.md."""
767
1559
  print("==================================================")
@@ -893,6 +1685,226 @@ class SkillVault:
893
1685
  print(f" Description: {desc_snippet}")
894
1686
  print(f" Path: {path_str}\n")
895
1687
 
1688
+ # --- Project Import Engine ---
1689
+
1690
+ def resolve_vault_archive_dir(self, vault_arg=None):
1691
+ """Resolve the source vault archive directory."""
1692
+ if vault_arg:
1693
+ p = Path(vault_arg).resolve()
1694
+ if (p / "skill_archive").exists():
1695
+ return p / "skill_archive"
1696
+ return p
1697
+
1698
+ env_vault = os.environ.get("SKILL_VAULT_DIR") or os.environ.get("SKILL_VAULT_ARCHIVE")
1699
+ if env_vault:
1700
+ p = Path(env_vault).resolve()
1701
+ if (p / "skill_archive").exists():
1702
+ return p / "skill_archive"
1703
+ return p
1704
+
1705
+ env_base = os.environ.get("SKILL_VAULT_BASE") or os.environ.get("SKILL_BASE_DIR")
1706
+ if env_base:
1707
+ p = Path(env_base).resolve() / "skill_archive"
1708
+ if p.exists():
1709
+ return p
1710
+
1711
+ # Check self.archive_dir
1712
+ if self.archive_dir.exists() and (
1713
+ (self.archive_dir / "skills").exists()
1714
+ or (self.archive_dir / "backup_manifest.json").exists()
1715
+ ):
1716
+ return self.archive_dir
1717
+
1718
+ # Check standard global locations
1719
+ candidates = [
1720
+ Path.home() / ".gemini" / "config" / "skills" / "skill-vault" / "skill_archive",
1721
+ Path.home() / ".gemini" / "config" / "skills" / ".skill_archive",
1722
+ Path.home() / ".gemini" / "config" / "skill_archive",
1723
+ Path.home() / ".agents" / "skill_archive",
1724
+ Path.home() / ".claude" / "skill_archive",
1725
+ ]
1726
+ for cand in candidates:
1727
+ if cand.exists() and (
1728
+ (cand / "skills").exists() or (cand / "backup_manifest.json").exists()
1729
+ ):
1730
+ return cand
1731
+
1732
+ return self.archive_dir
1733
+
1734
+ def resolve_dest_dir(self, dest_arg=None):
1735
+ """Resolve target destination directory for imported skills."""
1736
+ if dest_arg:
1737
+ p = Path(dest_arg).resolve()
1738
+ p.mkdir(parents=True, exist_ok=True)
1739
+ return p
1740
+
1741
+ cwd = Path.cwd().resolve()
1742
+ if (cwd / ".agents" / "skills").exists():
1743
+ return cwd / ".agents" / "skills"
1744
+ if (cwd / "skills").exists():
1745
+ return cwd / "skills"
1746
+ if (cwd / ".claude" / "skills").exists():
1747
+ return cwd / ".claude" / "skills"
1748
+ if (cwd / ".agents").exists():
1749
+ p = cwd / ".agents" / "skills"
1750
+ p.mkdir(parents=True, exist_ok=True)
1751
+ return p
1752
+
1753
+ p = cwd / "skills"
1754
+ p.mkdir(parents=True, exist_ok=True)
1755
+ return p
1756
+
1757
+ def find_vault_skill(self, skill_name, vault_archive_dir, manifest_map=None):
1758
+ """Find the physical skill directory in a vault archive store."""
1759
+ vault_archive_dir = Path(vault_archive_dir).resolve()
1760
+ vault_base = (
1761
+ vault_archive_dir.parent
1762
+ if vault_archive_dir.name == "skill_archive"
1763
+ else vault_archive_dir
1764
+ )
1765
+
1766
+ # 1. Check via manifest if provided
1767
+ if manifest_map and skill_name in manifest_map:
1768
+ item = manifest_map[skill_name]
1769
+ rel_archived = item.get("archived_path")
1770
+ if rel_archived:
1771
+ p1 = (vault_base / rel_archived).resolve()
1772
+ if p1.exists() and (p1 / "SKILL.md").exists():
1773
+ return p1
1774
+ p2 = (vault_archive_dir / rel_archived).resolve()
1775
+ if p2.exists() and (p2 / "SKILL.md").exists():
1776
+ return p2
1777
+ p3 = Path(rel_archived)
1778
+ if p3.is_absolute() and p3.exists() and (p3 / "SKILL.md").exists():
1779
+ return p3
1780
+
1781
+ # 2. Check vault_archive_dir / "skills" / skill_name
1782
+ p_std = vault_archive_dir / "skills" / skill_name
1783
+ if p_std.exists() and (p_std / "SKILL.md").exists():
1784
+ return p_std
1785
+
1786
+ # 3. Check vault_archive_dir / skill_name
1787
+ p_direct = vault_archive_dir / skill_name
1788
+ if p_direct.exists() and (p_direct / "SKILL.md").exists():
1789
+ return p_direct
1790
+
1791
+ # 4. Check nested plugins_*_skills subdirectories
1792
+ if vault_archive_dir.exists():
1793
+ for child in vault_archive_dir.iterdir():
1794
+ if child.is_dir():
1795
+ candidate = child / skill_name
1796
+ if candidate.exists() and (candidate / "SKILL.md").exists():
1797
+ return candidate
1798
+
1799
+ return None
1800
+
1801
+ def import_skills(
1802
+ self,
1803
+ name=None,
1804
+ pattern=None,
1805
+ category=None,
1806
+ import_all=False,
1807
+ dest_dir=None,
1808
+ vault_dir=None,
1809
+ force=False,
1810
+ dry_run=False,
1811
+ ):
1812
+ """Import skills from a vault (global archive or specified) into a project destination."""
1813
+ vault_archive_dir = self.resolve_vault_archive_dir(vault_dir)
1814
+ dest_path = self.resolve_dest_dir(dest_dir)
1815
+
1816
+ if not vault_archive_dir.exists():
1817
+ print(f"[Error] Vault archive directory does not exist: {vault_archive_dir}")
1818
+ return 1
1819
+
1820
+ # Load vault manifest if present
1821
+ manifest_file = vault_archive_dir / "backup_manifest.json"
1822
+ vault_manifest = []
1823
+ if manifest_file.exists():
1824
+ try:
1825
+ with open(manifest_file, "r", encoding="utf-8") as f:
1826
+ vault_manifest = json.load(f)
1827
+ except Exception as e:
1828
+ print(f"[Warning] Could not parse vault manifest at {manifest_file}: {e}")
1829
+
1830
+ manifest_map = {item["name"]: item for item in vault_manifest if "name" in item}
1831
+
1832
+ targets = []
1833
+ if import_all:
1834
+ if manifest_map:
1835
+ targets = sorted(manifest_map.keys())
1836
+ else:
1837
+ skills_base = vault_archive_dir / "skills"
1838
+ if skills_base.exists():
1839
+ targets = sorted([d.name for d in skills_base.iterdir() if d.is_dir() and (d / "SKILL.md").exists()])
1840
+ elif category:
1841
+ cat_lower = category.strip().lower()
1842
+ if manifest_map:
1843
+ targets = sorted([n for n, item in manifest_map.items() if item.get("category", "").lower() == cat_lower])
1844
+ if not targets:
1845
+ print(f"[Warning] No skills found matching category '{category}' in vault manifest.")
1846
+ elif pattern:
1847
+ regex = re.compile(pattern.replace("*", ".*"))
1848
+ if manifest_map:
1849
+ targets = sorted([n for n in manifest_map.keys() if regex.match(n)])
1850
+ else:
1851
+ skills_base = vault_archive_dir / "skills"
1852
+ if skills_base.exists():
1853
+ targets = sorted([d.name for d in skills_base.iterdir() if d.is_dir() and regex.match(d.name)])
1854
+ elif name:
1855
+ targets = [name.strip()]
1856
+ else:
1857
+ print("Please specify a skill name, --category, --pattern, or --all to import.")
1858
+ return 1
1859
+
1860
+ if not targets:
1861
+ print("No matching skills found in vault to import.")
1862
+ return 1
1863
+
1864
+ imported_count = 0
1865
+ skipped_count = 0
1866
+ error_count = 0
1867
+
1868
+ print("==================================================")
1869
+ print(" SKILL VAULT PROJECT IMPORT")
1870
+ print(f" Source Vault: {vault_archive_dir}")
1871
+ print(f" Target Dest: {dest_path}")
1872
+ print("==================================================\n")
1873
+
1874
+ for skill_name in targets:
1875
+ source_skill_dir = self.find_vault_skill(skill_name, vault_archive_dir, manifest_map)
1876
+ if not source_skill_dir:
1877
+ print(f"[Error] Skill '{skill_name}' not found in vault ({vault_archive_dir})")
1878
+ error_count += 1
1879
+ continue
1880
+
1881
+ target_skill_dir = dest_path / skill_name
1882
+
1883
+ if target_skill_dir.exists():
1884
+ recency = compare_skill_recency(source_skill_dir, target_skill_dir)
1885
+ if recency <= 0 and not force:
1886
+ print(f"[Skip] Project skill '{skill_name}' is already newer than or equal to vault version (use --force to overwrite)")
1887
+ skipped_count += 1
1888
+ continue
1889
+ else:
1890
+ if dry_run:
1891
+ print(f"[Dry Run] Would update project skill with newer vault version: {skill_name} -> {target_skill_dir}")
1892
+ else:
1893
+ shutil.rmtree(target_skill_dir)
1894
+ shutil.copytree(source_skill_dir, target_skill_dir)
1895
+ print(f"[Imported] Updated project skill with newer vault version: {skill_name} -> {target_skill_dir}")
1896
+ imported_count += 1
1897
+ else:
1898
+ if dry_run:
1899
+ print(f"[Dry Run] Would import: {skill_name} -> {target_skill_dir}")
1900
+ else:
1901
+ shutil.copytree(source_skill_dir, target_skill_dir)
1902
+ print(f"[Imported] {skill_name} -> {target_skill_dir}")
1903
+ imported_count += 1
1904
+
1905
+ print(f"\n[OK] Import completed: {imported_count} imported, {skipped_count} skipped, {error_count} errors.")
1906
+ return 0 if error_count == 0 else 1
1907
+
896
1908
 
897
1909
  def main():
898
1910
  parser = argparse.ArgumentParser(description="Skill Vault: Universal Agent Skill Lifecycle & Storage Manager")
@@ -953,6 +1965,34 @@ def main():
953
1965
  p_srch = subparsers.add_parser("search", help="Search archived skills by keyword, intent, or domain")
954
1966
  p_srch.add_argument("query", help="Keyword to search for")
955
1967
 
1968
+ # Sync
1969
+ p_sync = subparsers.add_parser("sync", help="Scan plugins and active skills, ingest new/updated skills, and prune non-core skills")
1970
+ p_sync.add_argument("--dry-run", action="store_true", help="Preview sync operations without moving or deleting files")
1971
+ p_sync.add_argument("--keep-active", action="store_true", help="Keep all scanned skills active in context instead of pruning")
1972
+ p_sync.add_argument("--force", action="store_true", help="Force overwrite in vault even if vault copy is newer")
1973
+ p_sync.add_argument("--protect", nargs="*", help="Additional skill names to protect from pruning")
1974
+
1975
+ # Import
1976
+ p_imp = subparsers.add_parser("import", help="Import skills from vault into project or target directory")
1977
+ p_imp.add_argument("name", nargs="?", help="Specific skill name to import")
1978
+ p_imp.add_argument("--pattern", help="Glob pattern of skills to import (e.g. 'gcp-*')")
1979
+ p_imp.add_argument("--category", help="Import all skills in a category")
1980
+ p_imp.add_argument("--all", action="store_true", help="Import all skills from the vault")
1981
+ p_imp.add_argument("--dest", help="Destination directory in project (default: ./skills or ./.agents/skills)")
1982
+ p_imp.add_argument("--vault-dir", help="Explicit source vault archive directory")
1983
+ p_imp.add_argument("--force", action="store_true", help="Overwrite existing skill in project regardless of recency")
1984
+ p_imp.add_argument("--dry-run", action="store_true", help="Preview skills that would be imported without copying")
1985
+
1986
+ # Config
1987
+ p_cfg = subparsers.add_parser("config", help="Inspect or customize vault_config.json and sync SKILL.md router prompt")
1988
+ p_cfg.add_argument("--show", action="store_true", help="Show active configuration and defaults")
1989
+ p_cfg.add_argument("--init", action="store_true", dest="init_config", help="Write current configuration defaults to vault_config.json")
1990
+ p_cfg.add_argument("--add-core", nargs="+", metavar="SKILL", help="Add one or more skills to protected core skills")
1991
+ p_cfg.add_argument("--remove-core", nargs="+", metavar="SKILL", help="Remove one or more skills from protected core skills")
1992
+ p_cfg.add_argument("--add-fingerprint", nargs=2, action="append", metavar=("CATEGORY", "PATTERN"), help="Add a workspace file/glob fingerprint for a category")
1993
+ p_cfg.add_argument("--add-category-rule", nargs=2, action="append", metavar=("CATEGORY", "KEYWORD"), help="Add an inference keyword rule for a category")
1994
+ p_cfg.add_argument("--sync-prompt", action="store_true", help="Synchronize SKILL.md router description with archived categories")
1995
+
956
1996
  args = parser.parse_args()
957
1997
  mgr = SkillVault(base_dir=args.base_dir)
958
1998
 
@@ -960,6 +2000,15 @@ def main():
960
2000
  mgr.init()
961
2001
  elif args.command == "optimize":
962
2002
  mgr.optimize(workspace_path=args.workspace, protected_skills=args.protect, dry_run=args.dry_run, force=args.force)
2003
+ elif args.command == "sync":
2004
+ sys.exit(
2005
+ mgr.sync(
2006
+ dry_run=args.dry_run,
2007
+ keep_active=args.keep_active,
2008
+ force=args.force,
2009
+ protect_skills=args.protect,
2010
+ )
2011
+ )
963
2012
  elif args.command == "list":
964
2013
  show_active = not args.archived or args.active
965
2014
  show_archived = not args.active or args.archived
@@ -989,6 +2038,29 @@ def main():
989
2038
  sys.exit(mgr.verify(fix=args.fix))
990
2039
  elif args.command == "search":
991
2040
  mgr.search(query=args.query)
2041
+ elif args.command == "import":
2042
+ sys.exit(
2043
+ mgr.import_skills(
2044
+ name=args.name,
2045
+ pattern=args.pattern,
2046
+ category=args.category,
2047
+ import_all=args.all,
2048
+ dest_dir=args.dest,
2049
+ vault_dir=args.vault_dir,
2050
+ force=args.force,
2051
+ dry_run=args.dry_run,
2052
+ )
2053
+ )
2054
+ elif args.command == "config":
2055
+ mgr.manage_config(
2056
+ show=args.show,
2057
+ init_config=args.init_config,
2058
+ add_core=args.add_core,
2059
+ remove_core=args.remove_core,
2060
+ add_fingerprint=args.add_fingerprint,
2061
+ add_category_rule=args.add_category_rule,
2062
+ sync_prompt=args.sync_prompt,
2063
+ )
992
2064
 
993
2065
 
994
2066
  if __name__ == "__main__":