@jcorpac/skill-vault 1.3.0 → 1.6.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
@@ -85,13 +85,25 @@ python scripts/skill_vault.py verify
85
85
  | `skill-vault status` | Fast summary of skill counts and category breakdown. |
86
86
  | `skill-vault list --active` | List only active skills currently loaded in context memory. |
87
87
  | `skill-vault list --archived` | List only cold-storage skills grouped by category. |
88
- | `skill-vault archive <name> --category "<Cat>"` | Move active skill to archive with category metadata. |
88
+ | `skill-vault archive <name> --category "<Cat>"` | Move active skill to archive with category metadata (preserves newer L2 copies). |
89
+ | `skill-vault archive <name> --force` | Force archive overwrite regardless of archive recency. |
89
90
  | `skill-vault archive --pattern "gcp-*"` | Archive multiple matching skills via glob pattern. |
90
91
  | `skill-vault recategorize <name> "<New Cat>"` | Reorganize skill category without modifying `SKILL.md`. |
91
- | `skill-vault restore <name>` | Restore an archived skill back to active availability. |
92
+ | `skill-vault restore <name>` | Restore an archived skill back to active availability (auto-upgrades if L2 is newer). |
93
+ | `skill-vault restore <name> --force` | Force restore overwrite regardless of active recency. |
92
94
  | `skill-vault restore --category "<Cat>"` | Restore all skills in a specific category. |
93
95
  | `skill-vault search "<query>"` | Search skills across names, descriptions, and categories. |
94
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. |
95
107
  | `skill-vault verify` | Audit bi-directional consistency across disk, manifest, and index. |
96
108
  | `skill-vault verify --fix` | Audit and automatically self-heal all detected discrepancies. |
97
109
 
@@ -103,6 +115,7 @@ python scripts/skill_vault.py verify
103
115
  2. **Environment Agnostic**: Dynamically resolves workspace roots via CLI flags (`--base-dir`), environment variables (`$SKILL_VAULT_BASE`), script parents, or working directories.
104
116
  3. **Zero Runtime Dependencies**: The core engine requires only Python 3 standard library (`os`, `sys`, `json`, `re`, `shutil`, `hashlib`, `argparse`, `pathlib`).
105
117
  4. **Self-Healing Integrity**: Detects orphaned folders, phantom manifest entries, broken markdown links, and duplicate aliases.
118
+ 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.
106
119
 
107
120
  ---
108
121
 
package/SKILL.md CHANGED
@@ -140,6 +140,51 @@ python scripts/skill_vault.py optimize --dry-run
140
140
  python scripts/skill_vault.py optimize --workspace "C:\Projects\my-repo" --protect my-custom-skill
141
141
  ```
142
142
 
143
+ ### I. Recency & Version Prioritization Protocol
144
+ Skill Vault automatically protects newer skills and prevents regressions when archiving, restoring, or optimizing:
145
+ 1. **Semantic Version Check**: Compares `version:` headers in `SKILL.md` frontmatter (e.g., `v2` > `v1`, `1.2.0` > `1.1.0`).
146
+ 2. **Timestamp Recency Fallback**: If versions match or are unversioned, compares the newest file modification timestamp (`mtime`).
147
+ 3. **Tier Behavior**:
148
+ - **`archive`**: When L1 is newer or equal to L2, updates L2 with the active version. If L2 is strictly newer, preserves L2 to avoid overwriting with stale files.
149
+ - **`restore`**: When L2 is strictly newer than L1, upgrades active L1 with the newer vault copy. If L1 is newer or equal, preserves L1.
150
+ - **`optimize`**: Automatically detects and upgrades active L1 skills if newer versions exist in the vault, while archiving unneeded skills safely.
151
+ - **`--force`**: Bypasses recency checks on `archive`, `restore`, or `optimize` when an intentional overwrite is required.
152
+
153
+ ### J. Project-Level Skill Importing
154
+ To import skills from a global vault (e.g., `~/.gemini/config/skill_archive` or `$SKILL_VAULT_BASE`) into a project workspace on demand:
155
+ ```bash
156
+ # Import a specific skill into the current project (defaults to ./skills or ./.agents/skills)
157
+ python scripts/skill_vault.py import <skill_name>
158
+
159
+ # Import all skills in a category into the current project
160
+ python scripts/skill_vault.py import --category "BigQuery & Data Warehouse"
161
+
162
+ # Import matching skills via glob pattern
163
+ python scripts/skill_vault.py import --pattern "gcp-*"
164
+
165
+ # Import into an explicit project destination
166
+ python scripts/skill_vault.py import <skill_name> --dest "./.agents/skills"
167
+
168
+ # Preview what would be imported without copying
169
+ python scripts/skill_vault.py import <skill_name> --dry-run
170
+
171
+ # Force overwrite of project skill if already present
172
+ python scripts/skill_vault.py import <skill_name> --force
173
+ ```
174
+
175
+ ### K. Automated Plugin Ingestion & Syncing (`sync`)
176
+ 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:
177
+ ```bash
178
+ # Scan plugins and active skills, ingest new/updated skills, and prune non-core active skills
179
+ python scripts/skill_vault.py sync
180
+
181
+ # Preview what would be ingested and pruned without moving or deleting files
182
+ python scripts/skill_vault.py sync --dry-run
183
+
184
+ # Ingest new/updated skills into the vault while keeping all active
185
+ python scripts/skill_vault.py sync --keep-active
186
+ ```
187
+
143
188
  ---
144
189
 
145
190
  ## 3. Environment & OS Compatibility Guidelines
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jcorpac/skill-vault",
3
- "version": "1.3.0",
3
+ "version": "1.6.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": {
@@ -68,6 +68,69 @@ WORKSPACE_FINGERPRINTS = {
68
68
  }
69
69
 
70
70
 
71
+ def parse_version_tuple(ver_str):
72
+ """Parse version string into a comparable numeric tuple, e.g. 'v20' -> (20,), '1.1.5' -> (1, 1, 5)."""
73
+ if not ver_str:
74
+ return None
75
+ cleaned = str(ver_str).strip().strip("'\"").lstrip("vV")
76
+ nums = re.findall(r"\d+", cleaned)
77
+ if nums:
78
+ return tuple(int(n) for n in nums)
79
+ return None
80
+
81
+
82
+ def get_skill_metadata(skill_dir):
83
+ """Extract parsed version and latest modification timestamp for a skill directory."""
84
+ skill_dir = Path(skill_dir)
85
+ skill_md = skill_dir / "SKILL.md"
86
+
87
+ ver_tuple = None
88
+ if skill_md.exists():
89
+ try:
90
+ content = skill_md.read_text(encoding="utf-8", errors="ignore")
91
+ fm_match = re.search(r"^---\s*\n(.*?)\n---", content, re.DOTALL)
92
+ if fm_match:
93
+ v_match = re.search(r"version:\s*([^\n]+)", fm_match.group(1), re.IGNORECASE)
94
+ if v_match:
95
+ ver_tuple = parse_version_tuple(v_match.group(1))
96
+ except Exception:
97
+ pass
98
+
99
+ latest_mtime = 0.0
100
+ try:
101
+ files = [f for f in skill_dir.rglob("*") if f.is_file()]
102
+ if files:
103
+ latest_mtime = max(f.stat().st_mtime for f in files)
104
+ elif skill_dir.exists():
105
+ latest_mtime = skill_dir.stat().st_mtime
106
+ except Exception:
107
+ pass
108
+
109
+ return ver_tuple, latest_mtime
110
+
111
+
112
+ def compare_skill_recency(dir_a, dir_b):
113
+ """Compare two skill directories to determine which is newer.
114
+
115
+ Returns:
116
+ 1 if dir_a is newer than dir_b
117
+ -1 if dir_b is newer than dir_a
118
+ 0 if they are equivalent in version and recency
119
+ """
120
+ ver_a, mtime_a = get_skill_metadata(dir_a)
121
+ ver_b, mtime_b = get_skill_metadata(dir_b)
122
+
123
+ # 1. Compare semantic/numeric versions if both exist and differ
124
+ if ver_a is not None and ver_b is not None and ver_a != ver_b:
125
+ return 1 if ver_a > ver_b else -1
126
+
127
+ # 2. Compare file modification timestamps (allowing a 1-second margin for filesystem granularity)
128
+ if abs(mtime_a - mtime_b) > 1.0:
129
+ return 1 if mtime_a > mtime_b else -1
130
+
131
+ return 0
132
+
133
+
71
134
  def resolve_base_dir(cli_base=None):
72
135
  """Dynamically resolve the base directory for skills and archives."""
73
136
  if cli_base:
@@ -134,30 +197,81 @@ class SkillVault:
134
197
 
135
198
  for sub in [".agents/skills", ".claude/skills"]:
136
199
  p = self.base_dir / sub
137
- if p.exists():
200
+ if p.exists() and p not in dirs:
138
201
  dirs.append(p)
139
202
 
203
+ # Also search active working directory and its skill locations if distinct from base_dir
204
+ cwd = Path.cwd().resolve()
205
+ if cwd != self.base_dir:
206
+ for sub in ["skills", ".agents/skills", ".claude/skills"]:
207
+ p = cwd / sub
208
+ if p.exists() and p not in dirs:
209
+ dirs.append(p)
210
+
211
+ # If base_dir is nested inside a skills folder (e.g. skills/skill-vault)
212
+ if self.base_dir.parent.name == "skills" and self.base_dir.parent.exists():
213
+ if self.base_dir.parent not in dirs:
214
+ dirs.append(self.base_dir.parent)
215
+ parent_plugins = self.base_dir.parent.parent / "plugins"
216
+ if parent_plugins.exists():
217
+ for p in parent_plugins.iterdir():
218
+ if p.is_dir() and (p / "skills").exists() and (p / "skills") not in dirs:
219
+ dirs.append(p / "skills")
220
+
140
221
  plugins_dir = self.base_dir / "plugins"
141
222
  if plugins_dir.exists():
142
223
  for p in plugins_dir.iterdir():
143
- if p.is_dir() and (p / "skills").exists():
224
+ if p.is_dir() and (p / "skills").exists() and (p / "skills") not in dirs:
144
225
  dirs.append(p / "skills")
145
226
  return dirs
146
227
 
228
+ def parse_skill_name(self, skill_md_path):
229
+ """Extract name from SKILL.md frontmatter."""
230
+ skill_md_path = Path(skill_md_path)
231
+ if not skill_md_path.exists():
232
+ return None
233
+ try:
234
+ content = skill_md_path.read_text(encoding="utf-8", errors="ignore")
235
+ fm_match = re.search(r"^---\s*\n(.*?)\n---", content, re.DOTALL)
236
+ if fm_match:
237
+ n_match = re.search(r"^name:\s*([^\n]+)", fm_match.group(1), re.MULTILINE)
238
+ if n_match:
239
+ return n_match.group(1).strip().strip("'\"")
240
+ except Exception:
241
+ pass
242
+ return None
243
+
147
244
  def get_active_skills(self):
148
- """Discover all currently active skills on disk."""
245
+ """Discover all currently active skills on disk across standard and plugin layouts."""
149
246
  active = {}
150
247
  for search_dir in self.get_active_skill_dirs():
151
- if search_dir.exists():
152
- for folder in search_dir.iterdir():
153
- if folder.is_dir() and (folder / "SKILL.md").exists():
154
- desc = self.parse_skill_description(folder / "SKILL.md")
155
- active[folder.name] = {
156
- "name": folder.name,
157
- "path": str(folder),
158
- "relative_path": self.make_portable_path(folder),
159
- "description": desc,
160
- }
248
+ if not search_dir.exists():
249
+ continue
250
+
251
+ # Case 1: search_dir contains subdirectories with SKILL.md (e.g. skills/<name>/SKILL.md)
252
+ for folder in search_dir.iterdir():
253
+ if folder.is_dir() and (folder / "SKILL.md").exists():
254
+ skill_name = self.parse_skill_name(folder / "SKILL.md") or folder.name
255
+ desc = self.parse_skill_description(folder / "SKILL.md")
256
+ active[skill_name] = {
257
+ "name": skill_name,
258
+ "path": str(folder),
259
+ "relative_path": self.make_portable_path(folder),
260
+ "description": desc,
261
+ "single_skill_dir": False,
262
+ }
263
+
264
+ # Case 2: search_dir itself has SKILL.md directly (e.g. plugins/<plugin>/skills/SKILL.md)
265
+ if (search_dir / "SKILL.md").exists():
266
+ skill_name = self.parse_skill_name(search_dir / "SKILL.md") or search_dir.parent.name
267
+ desc = self.parse_skill_description(search_dir / "SKILL.md")
268
+ active[skill_name] = {
269
+ "name": skill_name,
270
+ "path": str(search_dir),
271
+ "relative_path": self.make_portable_path(search_dir),
272
+ "description": desc,
273
+ "single_skill_dir": True,
274
+ }
161
275
  return active
162
276
 
163
277
  def get_archived_skill_folders(self):
@@ -303,10 +417,11 @@ class SkillVault:
303
417
 
304
418
  return matched
305
419
 
306
- def optimize(self, workspace_path=None, protected_skills=None, dry_run=False):
420
+ def optimize(self, workspace_path=None, protected_skills=None, dry_run=False, force=False):
307
421
  """Automatically minimize active skills to essential Core + workspace-relevant skills.
308
422
 
309
- Archives unneeded active skills into cold storage and mounts matching domain skills.
423
+ Archives unneeded active skills into cold storage and mounts matching domain skills,
424
+ prioritizing newer versions when versions overlap.
310
425
  """
311
426
  target_ws = Path(workspace_path).resolve() if workspace_path else Path.cwd().resolve()
312
427
  core_set = set(DEFAULT_CORE_SKILLS)
@@ -346,6 +461,17 @@ class SkillVault:
346
461
  else:
347
462
  to_archive.append((name, skill_cat))
348
463
 
464
+ # Check if any kept active skill has a newer version in the archive
465
+ to_upgrade = []
466
+ for name, reason in to_keep:
467
+ if name in manifest_by_name:
468
+ item = manifest_by_name[name]
469
+ archived_path = self.resolve_portable_path(item.get("archived_path", ""))
470
+ active_path = self.find_active_skill(name)
471
+ if archived_path.exists() and active_path and active_path.exists():
472
+ if compare_skill_recency(archived_path, active_path) > 0:
473
+ to_upgrade.append((name, reason))
474
+
349
475
  # 3. Determine skills in vault that should be mounted
350
476
  to_mount = []
351
477
  for cat in detected_categories.keys():
@@ -359,6 +485,11 @@ class SkillVault:
359
485
  for name, reason in to_keep:
360
486
  print(f" [KEEP] {name} - {reason}")
361
487
 
488
+ if to_upgrade:
489
+ print(f"\n * Upgrading Active Skills with Newer Vault Versions ({len(to_upgrade)} skills):")
490
+ for name, reason in to_upgrade:
491
+ print(f" [UPGRADE] {name} (Newer version found in Vault)")
492
+
362
493
  if to_archive:
363
494
  print(f"\n * Evicting to Cold Storage Archive ({len(to_archive)} skills):")
364
495
  for name, cat in to_archive:
@@ -375,20 +506,161 @@ class SkillVault:
375
506
  print("\n[Dry Run] Optimization preview complete. No files were moved.")
376
507
  return
377
508
 
509
+ # Execute Upgrades
510
+ if to_upgrade:
511
+ print("\nExecuting Auto-Upgrades from Newer Vault Copies...")
512
+ for name, _ in to_upgrade:
513
+ self.restore(name=name, force=True)
514
+
378
515
  # Execute Evictions (Archive)
379
516
  if to_archive:
380
517
  print("\nExecuting Auto-Archival...")
381
518
  for name, cat in to_archive:
382
- self.archive(name=name, category=cat, keep_active=False)
519
+ self.archive(name=name, category=cat, keep_active=False, force=force)
383
520
 
384
521
  # Execute Mounts (Restore)
385
522
  if to_mount:
386
523
  print("\nExecuting Auto-Mounts...")
387
524
  for name, cat in to_mount:
388
- self.restore(name=name)
525
+ self.restore(name=name, force=force)
389
526
 
390
527
  print("\n[OK] Optimization complete! Active context surface is at absolute minimum.")
391
528
 
529
+ # --- Sync & Ingestion Engine ---
530
+
531
+ def infer_category(self, skill_name, skill_desc=""):
532
+ """Infer an appropriate category for a new skill based on name and description keywords."""
533
+ 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"
548
+ return "General & Utility Skills"
549
+
550
+ def sync(self, dry_run=False, keep_active=False, force=False, protect_skills=None):
551
+ """Automatically scan plugins and active directories for new or updated skills,
552
+ ingest them into the vault, preserve Core Foundation Skills, and prune non-core active skills."""
553
+ print("==================================================")
554
+ print(" SKILL VAULT AUTO-SYNC & INGEST")
555
+ print(f" Base Directory: {self.base_dir}")
556
+ print(f" Vault Store: {self.archive_dir}")
557
+ print("==================================================\n")
558
+
559
+ core_set = set(DEFAULT_CORE_SKILLS)
560
+ if protect_skills:
561
+ core_set.update(protect_skills)
562
+
563
+ active_skills = self.get_active_skills()
564
+ manifest = self.load_manifest()
565
+ manifest_map = {m["name"]: m for m in manifest}
566
+
567
+ to_ingest_new = []
568
+ to_ingest_update = []
569
+ to_prune = []
570
+ in_sync = []
571
+ retained_core = []
572
+
573
+ for name, data in sorted(active_skills.items()):
574
+ active_path = Path(data["path"])
575
+ is_core = name in core_set
576
+
577
+ if name in manifest_map:
578
+ item = manifest_map[name]
579
+ archived_path = self.resolve_portable_path(item.get("archived_path", ""))
580
+ if not archived_path.exists():
581
+ archived_path = self.archive_dir / "skills" / name
582
+
583
+ recency = compare_skill_recency(active_path, archived_path)
584
+ if recency > 0 or force:
585
+ to_ingest_update.append((name, data, item.get("category") or self.infer_category(name, data["description"])))
586
+ else:
587
+ in_sync.append(name)
588
+ else:
589
+ assigned_cat = self.infer_category(name, data["description"])
590
+ to_ingest_new.append((name, data, assigned_cat))
591
+
592
+ if is_core:
593
+ retained_core.append(name)
594
+ elif not keep_active:
595
+ to_prune.append((name, data))
596
+
597
+ print("Scan Results:")
598
+ print(f" * New skills to ingest into vault: {len(to_ingest_new)}")
599
+ for name, _, cat in to_ingest_new:
600
+ print(f" [NEW] {name} -> Category: {cat}")
601
+
602
+ print(f" * Updated skills to refresh in vault: {len(to_ingest_update)}")
603
+ for name, _, cat in to_ingest_update:
604
+ print(f" [UPDATE] {name} (Newer active version detected)")
605
+
606
+ print(f" * In-sync skills in vault: {len(in_sync)}")
607
+ print(f" * Retained Core Foundation Skills: {len(retained_core)} ({', '.join(sorted(retained_core))})")
608
+ print(f" * Non-core active skills to prune: {len(to_prune)}")
609
+ for name, _ in to_prune:
610
+ print(f" [PRUNE] {name} (Will be removed from active context to prevent context bloat)")
611
+ print("")
612
+
613
+ if dry_run:
614
+ print("[Dry Run] Preview complete. No files were modified.")
615
+ return 0
616
+
617
+ total_ingested = 0
618
+ items_to_write = to_ingest_new + to_ingest_update
619
+ for name, data, cat in items_to_write:
620
+ active_path = Path(data["path"])
621
+ if name in manifest_map and manifest_map[name].get("archived_path"):
622
+ dest = self.resolve_portable_path(manifest_map[name]["archived_path"])
623
+ else:
624
+ dest = self.archive_dir / "skills" / name
625
+
626
+ dest.parent.mkdir(parents=True, exist_ok=True)
627
+ if dest.exists():
628
+ shutil.rmtree(dest)
629
+
630
+ shutil.copytree(active_path, dest)
631
+ print(f"[Vaulted] {name} -> {dest}")
632
+
633
+ manifest_map[name] = {
634
+ "name": name,
635
+ "category": cat,
636
+ "original_path": data["relative_path"],
637
+ "archived_path": self.make_portable_path(dest),
638
+ }
639
+ total_ingested += 1
640
+
641
+ for name, data in to_prune:
642
+ active_path = Path(data["path"])
643
+ if data.get("single_skill_dir"):
644
+ for sub in active_path.iterdir():
645
+ if sub.is_dir():
646
+ shutil.rmtree(sub)
647
+ else:
648
+ sub.unlink()
649
+ print(f"[Pruned] Emptied single-skill directory: {active_path}")
650
+ else:
651
+ if active_path.exists():
652
+ shutil.rmtree(active_path)
653
+ print(f"[Pruned] Removed active folder: {active_path}")
654
+
655
+ if total_ingested > 0 or to_prune:
656
+ self.save_manifest(list(manifest_map.values()))
657
+ self.reindex()
658
+ self.verify()
659
+
660
+ print(f"\n[OK] Sync complete: {total_ingested} skill(s) vaulted/refreshed, {len(to_prune)} active skill(s) pruned.")
661
+ print(f"Active context memory is clean with {len(retained_core)} Core Foundation Skill(s).\n")
662
+ return 0
663
+
392
664
  # --- Actions ---
393
665
 
394
666
  def list_skills(self, show_active=True, show_archived=True, category_filter=None, as_json=False, summary_only=False):
@@ -476,8 +748,8 @@ class SkillVault:
476
748
  print(f" * {s['name']}: {desc_snippet}")
477
749
  print("")
478
750
 
479
- def archive(self, name=None, pattern=None, category=None, keep_active=False):
480
- """Archive active skills with an assigned category."""
751
+ def archive(self, name=None, pattern=None, category=None, keep_active=False, force=False):
752
+ """Archive active skills with an assigned category, prioritizing newer versions."""
481
753
  manifest = self.load_manifest()
482
754
  manifest_map = {item["name"]: item for item in manifest}
483
755
 
@@ -507,9 +779,23 @@ class SkillVault:
507
779
  dest_dir.parent.mkdir(parents=True, exist_ok=True)
508
780
 
509
781
  if dest_dir.exists():
510
- shutil.rmtree(dest_dir)
782
+ recency = compare_skill_recency(active_path, dest_dir)
783
+ if recency < 0 and not force:
784
+ print(f"[Skip] L2 archive '{skill_name}' is newer than active L1 version. Preserving newer archive (use --force to overwrite).")
785
+ if not keep_active:
786
+ shutil.rmtree(active_path)
787
+ print(f"[Cleaned] Removed older active directory: {active_path}")
788
+ continue
789
+ elif recency > 0:
790
+ print(f"[Archived] Overwriting older L2 archive with newer active L1 version: {active_path} -> {dest_dir}")
791
+ shutil.rmtree(dest_dir)
792
+ else:
793
+ shutil.rmtree(dest_dir)
794
+ print(f"[Archived] {active_path} -> {dest_dir}")
795
+ else:
796
+ print(f"[Archived] {active_path} -> {dest_dir}")
797
+
511
798
  shutil.copytree(active_path, dest_dir)
512
- print(f"[Archived] {active_path} -> {dest_dir}")
513
799
 
514
800
  existing_cat = manifest_map.get(skill_name, {}).get("category")
515
801
  assigned_cat = category_name or existing_cat or "General & Utility Skills"
@@ -576,10 +862,14 @@ class SkillVault:
576
862
 
577
863
  original_path.parent.mkdir(parents=True, exist_ok=True)
578
864
  if original_path.exists():
579
- if force:
865
+ recency = compare_skill_recency(archived_path, original_path)
866
+ if recency > 0 or force:
580
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}")
870
+ continue
581
871
  else:
582
- print(f"[Skip] Target exists: {original_path} (use --force to overwrite)")
872
+ print(f"[Skip] Target L1 skill '{item['name']}' is already newer than or equal to L2 archive (use --force to overwrite)")
583
873
  continue
584
874
 
585
875
  shutil.copytree(archived_path, original_path)
@@ -781,6 +1071,226 @@ class SkillVault:
781
1071
  print(f" Description: {desc_snippet}")
782
1072
  print(f" Path: {path_str}\n")
783
1073
 
1074
+ # --- Project Import Engine ---
1075
+
1076
+ def resolve_vault_archive_dir(self, vault_arg=None):
1077
+ """Resolve the source vault archive directory."""
1078
+ if vault_arg:
1079
+ p = Path(vault_arg).resolve()
1080
+ if (p / "skill_archive").exists():
1081
+ return p / "skill_archive"
1082
+ return p
1083
+
1084
+ env_vault = os.environ.get("SKILL_VAULT_DIR") or os.environ.get("SKILL_VAULT_ARCHIVE")
1085
+ if env_vault:
1086
+ p = Path(env_vault).resolve()
1087
+ if (p / "skill_archive").exists():
1088
+ return p / "skill_archive"
1089
+ return p
1090
+
1091
+ env_base = os.environ.get("SKILL_VAULT_BASE") or os.environ.get("SKILL_BASE_DIR")
1092
+ if env_base:
1093
+ p = Path(env_base).resolve() / "skill_archive"
1094
+ if p.exists():
1095
+ return p
1096
+
1097
+ # Check self.archive_dir
1098
+ if self.archive_dir.exists() and (
1099
+ (self.archive_dir / "skills").exists()
1100
+ or (self.archive_dir / "backup_manifest.json").exists()
1101
+ ):
1102
+ return self.archive_dir
1103
+
1104
+ # Check standard global locations
1105
+ candidates = [
1106
+ Path.home() / ".gemini" / "config" / "skills" / "skill-vault" / "skill_archive",
1107
+ Path.home() / ".gemini" / "config" / "skills" / ".skill_archive",
1108
+ Path.home() / ".gemini" / "config" / "skill_archive",
1109
+ Path.home() / ".agents" / "skill_archive",
1110
+ Path.home() / ".claude" / "skill_archive",
1111
+ ]
1112
+ for cand in candidates:
1113
+ if cand.exists() and (
1114
+ (cand / "skills").exists() or (cand / "backup_manifest.json").exists()
1115
+ ):
1116
+ return cand
1117
+
1118
+ return self.archive_dir
1119
+
1120
+ def resolve_dest_dir(self, dest_arg=None):
1121
+ """Resolve target destination directory for imported skills."""
1122
+ if dest_arg:
1123
+ p = Path(dest_arg).resolve()
1124
+ p.mkdir(parents=True, exist_ok=True)
1125
+ return p
1126
+
1127
+ cwd = Path.cwd().resolve()
1128
+ if (cwd / ".agents" / "skills").exists():
1129
+ return cwd / ".agents" / "skills"
1130
+ if (cwd / "skills").exists():
1131
+ return cwd / "skills"
1132
+ if (cwd / ".claude" / "skills").exists():
1133
+ return cwd / ".claude" / "skills"
1134
+ if (cwd / ".agents").exists():
1135
+ p = cwd / ".agents" / "skills"
1136
+ p.mkdir(parents=True, exist_ok=True)
1137
+ return p
1138
+
1139
+ p = cwd / "skills"
1140
+ p.mkdir(parents=True, exist_ok=True)
1141
+ return p
1142
+
1143
+ def find_vault_skill(self, skill_name, vault_archive_dir, manifest_map=None):
1144
+ """Find the physical skill directory in a vault archive store."""
1145
+ vault_archive_dir = Path(vault_archive_dir).resolve()
1146
+ vault_base = (
1147
+ vault_archive_dir.parent
1148
+ if vault_archive_dir.name == "skill_archive"
1149
+ else vault_archive_dir
1150
+ )
1151
+
1152
+ # 1. Check via manifest if provided
1153
+ if manifest_map and skill_name in manifest_map:
1154
+ item = manifest_map[skill_name]
1155
+ rel_archived = item.get("archived_path")
1156
+ if rel_archived:
1157
+ p1 = (vault_base / rel_archived).resolve()
1158
+ if p1.exists() and (p1 / "SKILL.md").exists():
1159
+ return p1
1160
+ p2 = (vault_archive_dir / rel_archived).resolve()
1161
+ if p2.exists() and (p2 / "SKILL.md").exists():
1162
+ return p2
1163
+ p3 = Path(rel_archived)
1164
+ if p3.is_absolute() and p3.exists() and (p3 / "SKILL.md").exists():
1165
+ return p3
1166
+
1167
+ # 2. Check vault_archive_dir / "skills" / skill_name
1168
+ p_std = vault_archive_dir / "skills" / skill_name
1169
+ if p_std.exists() and (p_std / "SKILL.md").exists():
1170
+ return p_std
1171
+
1172
+ # 3. Check vault_archive_dir / skill_name
1173
+ p_direct = vault_archive_dir / skill_name
1174
+ if p_direct.exists() and (p_direct / "SKILL.md").exists():
1175
+ return p_direct
1176
+
1177
+ # 4. Check nested plugins_*_skills subdirectories
1178
+ if vault_archive_dir.exists():
1179
+ for child in vault_archive_dir.iterdir():
1180
+ if child.is_dir():
1181
+ candidate = child / skill_name
1182
+ if candidate.exists() and (candidate / "SKILL.md").exists():
1183
+ return candidate
1184
+
1185
+ return None
1186
+
1187
+ def import_skills(
1188
+ self,
1189
+ name=None,
1190
+ pattern=None,
1191
+ category=None,
1192
+ import_all=False,
1193
+ dest_dir=None,
1194
+ vault_dir=None,
1195
+ force=False,
1196
+ dry_run=False,
1197
+ ):
1198
+ """Import skills from a vault (global archive or specified) into a project destination."""
1199
+ vault_archive_dir = self.resolve_vault_archive_dir(vault_dir)
1200
+ dest_path = self.resolve_dest_dir(dest_dir)
1201
+
1202
+ if not vault_archive_dir.exists():
1203
+ print(f"[Error] Vault archive directory does not exist: {vault_archive_dir}")
1204
+ return 1
1205
+
1206
+ # Load vault manifest if present
1207
+ manifest_file = vault_archive_dir / "backup_manifest.json"
1208
+ vault_manifest = []
1209
+ if manifest_file.exists():
1210
+ try:
1211
+ with open(manifest_file, "r", encoding="utf-8") as f:
1212
+ vault_manifest = json.load(f)
1213
+ except Exception as e:
1214
+ print(f"[Warning] Could not parse vault manifest at {manifest_file}: {e}")
1215
+
1216
+ manifest_map = {item["name"]: item for item in vault_manifest if "name" in item}
1217
+
1218
+ targets = []
1219
+ if import_all:
1220
+ if manifest_map:
1221
+ targets = sorted(manifest_map.keys())
1222
+ else:
1223
+ skills_base = vault_archive_dir / "skills"
1224
+ if skills_base.exists():
1225
+ targets = sorted([d.name for d in skills_base.iterdir() if d.is_dir() and (d / "SKILL.md").exists()])
1226
+ elif category:
1227
+ cat_lower = category.strip().lower()
1228
+ if manifest_map:
1229
+ targets = sorted([n for n, item in manifest_map.items() if item.get("category", "").lower() == cat_lower])
1230
+ if not targets:
1231
+ print(f"[Warning] No skills found matching category '{category}' in vault manifest.")
1232
+ elif pattern:
1233
+ regex = re.compile(pattern.replace("*", ".*"))
1234
+ if manifest_map:
1235
+ targets = sorted([n for n in manifest_map.keys() if regex.match(n)])
1236
+ else:
1237
+ skills_base = vault_archive_dir / "skills"
1238
+ if skills_base.exists():
1239
+ targets = sorted([d.name for d in skills_base.iterdir() if d.is_dir() and regex.match(d.name)])
1240
+ elif name:
1241
+ targets = [name.strip()]
1242
+ else:
1243
+ print("Please specify a skill name, --category, --pattern, or --all to import.")
1244
+ return 1
1245
+
1246
+ if not targets:
1247
+ print("No matching skills found in vault to import.")
1248
+ return 1
1249
+
1250
+ imported_count = 0
1251
+ skipped_count = 0
1252
+ error_count = 0
1253
+
1254
+ print("==================================================")
1255
+ print(" SKILL VAULT PROJECT IMPORT")
1256
+ print(f" Source Vault: {vault_archive_dir}")
1257
+ print(f" Target Dest: {dest_path}")
1258
+ print("==================================================\n")
1259
+
1260
+ for skill_name in targets:
1261
+ source_skill_dir = self.find_vault_skill(skill_name, vault_archive_dir, manifest_map)
1262
+ if not source_skill_dir:
1263
+ print(f"[Error] Skill '{skill_name}' not found in vault ({vault_archive_dir})")
1264
+ error_count += 1
1265
+ continue
1266
+
1267
+ target_skill_dir = dest_path / skill_name
1268
+
1269
+ if target_skill_dir.exists():
1270
+ recency = compare_skill_recency(source_skill_dir, target_skill_dir)
1271
+ if recency <= 0 and not force:
1272
+ print(f"[Skip] Project skill '{skill_name}' is already newer than or equal to vault version (use --force to overwrite)")
1273
+ skipped_count += 1
1274
+ continue
1275
+ else:
1276
+ if dry_run:
1277
+ print(f"[Dry Run] Would update project skill with newer vault version: {skill_name} -> {target_skill_dir}")
1278
+ else:
1279
+ shutil.rmtree(target_skill_dir)
1280
+ shutil.copytree(source_skill_dir, target_skill_dir)
1281
+ print(f"[Imported] Updated project skill with newer vault version: {skill_name} -> {target_skill_dir}")
1282
+ imported_count += 1
1283
+ else:
1284
+ if dry_run:
1285
+ print(f"[Dry Run] Would import: {skill_name} -> {target_skill_dir}")
1286
+ else:
1287
+ shutil.copytree(source_skill_dir, target_skill_dir)
1288
+ print(f"[Imported] {skill_name} -> {target_skill_dir}")
1289
+ imported_count += 1
1290
+
1291
+ print(f"\n[OK] Import completed: {imported_count} imported, {skipped_count} skipped, {error_count} errors.")
1292
+ return 0 if error_count == 0 else 1
1293
+
784
1294
 
785
1295
  def main():
786
1296
  parser = argparse.ArgumentParser(description="Skill Vault: Universal Agent Skill Lifecycle & Storage Manager")
@@ -795,6 +1305,7 @@ def main():
795
1305
  p_opt.add_argument("--workspace", help="Path to workspace directory to inspect")
796
1306
  p_opt.add_argument("--protect", nargs="*", help="Additional skill names to protect from auto-archiving")
797
1307
  p_opt.add_argument("--dry-run", action="store_true", help="Preview optimization changes without moving files")
1308
+ p_opt.add_argument("--force", action="store_true", help="Force overwrite during optimization regardless of recency")
798
1309
 
799
1310
  # List / Overview
800
1311
  p_list = subparsers.add_parser("list", help="Present active and archived skills")
@@ -814,6 +1325,7 @@ def main():
814
1325
  p_arch.add_argument("--pattern", help="Glob pattern (e.g. 'gcp-*')")
815
1326
  p_arch.add_argument("--category", help="Category name (e.g. 'Cloud Architecture')")
816
1327
  p_arch.add_argument("--keep-active", action="store_true", help="Do not delete source folder")
1328
+ p_arch.add_argument("--force", action="store_true", help="Force overwrite in archive regardless of recency")
817
1329
 
818
1330
  # Recategorize
819
1331
  p_rec = subparsers.add_parser("recategorize", help="Recategorize an archived skill in metadata")
@@ -839,13 +1351,40 @@ def main():
839
1351
  p_srch = subparsers.add_parser("search", help="Search archived skills by keyword, intent, or domain")
840
1352
  p_srch.add_argument("query", help="Keyword to search for")
841
1353
 
1354
+ # Sync
1355
+ p_sync = subparsers.add_parser("sync", help="Scan plugins and active skills, ingest new/updated skills, and prune non-core skills")
1356
+ p_sync.add_argument("--dry-run", action="store_true", help="Preview sync operations without moving or deleting files")
1357
+ p_sync.add_argument("--keep-active", action="store_true", help="Keep all scanned skills active in context instead of pruning")
1358
+ p_sync.add_argument("--force", action="store_true", help="Force overwrite in vault even if vault copy is newer")
1359
+ p_sync.add_argument("--protect", nargs="*", help="Additional skill names to protect from pruning")
1360
+
1361
+ # Import
1362
+ p_imp = subparsers.add_parser("import", help="Import skills from vault into project or target directory")
1363
+ p_imp.add_argument("name", nargs="?", help="Specific skill name to import")
1364
+ p_imp.add_argument("--pattern", help="Glob pattern of skills to import (e.g. 'gcp-*')")
1365
+ p_imp.add_argument("--category", help="Import all skills in a category")
1366
+ p_imp.add_argument("--all", action="store_true", help="Import all skills from the vault")
1367
+ p_imp.add_argument("--dest", help="Destination directory in project (default: ./skills or ./.agents/skills)")
1368
+ p_imp.add_argument("--vault-dir", help="Explicit source vault archive directory")
1369
+ p_imp.add_argument("--force", action="store_true", help="Overwrite existing skill in project regardless of recency")
1370
+ p_imp.add_argument("--dry-run", action="store_true", help="Preview skills that would be imported without copying")
1371
+
842
1372
  args = parser.parse_args()
843
1373
  mgr = SkillVault(base_dir=args.base_dir)
844
1374
 
845
1375
  if args.command == "init":
846
1376
  mgr.init()
847
1377
  elif args.command == "optimize":
848
- mgr.optimize(workspace_path=args.workspace, protected_skills=args.protect, dry_run=args.dry_run)
1378
+ mgr.optimize(workspace_path=args.workspace, protected_skills=args.protect, dry_run=args.dry_run, force=args.force)
1379
+ elif args.command == "sync":
1380
+ sys.exit(
1381
+ mgr.sync(
1382
+ dry_run=args.dry_run,
1383
+ keep_active=args.keep_active,
1384
+ force=args.force,
1385
+ protect_skills=args.protect,
1386
+ )
1387
+ )
849
1388
  elif args.command == "list":
850
1389
  show_active = not args.archived or args.active
851
1390
  show_archived = not args.active or args.archived
@@ -864,7 +1403,7 @@ def main():
864
1403
  summary_only=True,
865
1404
  )
866
1405
  elif args.command == "archive":
867
- mgr.archive(name=args.name, pattern=args.pattern, category=args.category, keep_active=args.keep_active)
1406
+ mgr.archive(name=args.name, pattern=args.pattern, category=args.category, keep_active=args.keep_active, force=args.force)
868
1407
  elif args.command == "recategorize":
869
1408
  mgr.recategorize(name=args.name, new_category=args.category)
870
1409
  elif args.command == "restore":
@@ -875,6 +1414,19 @@ def main():
875
1414
  sys.exit(mgr.verify(fix=args.fix))
876
1415
  elif args.command == "search":
877
1416
  mgr.search(query=args.query)
1417
+ elif args.command == "import":
1418
+ sys.exit(
1419
+ mgr.import_skills(
1420
+ name=args.name,
1421
+ pattern=args.pattern,
1422
+ category=args.category,
1423
+ import_all=args.all,
1424
+ dest_dir=args.dest,
1425
+ vault_dir=args.vault_dir,
1426
+ force=args.force,
1427
+ dry_run=args.dry_run,
1428
+ )
1429
+ )
878
1430
 
879
1431
 
880
1432
  if __name__ == "__main__":