@jcorpac/skill-vault 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Skill Vault Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,119 @@
1
+ # Skill Vault ๐Ÿ›ก๏ธ
2
+
3
+ [![CI Test Suite](https://github.com/jcorpac/skill-vault/actions/workflows/test.yml/badge.svg)](https://github.com/jcorpac/skill-vault/actions)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
5
+ [![npm version](https://img.shields.io/npm/v/@jcorpac/skill-vault.svg)](https://www.npmjs.com/package/@jcorpac/skill-vault)
6
+ [![Agent Skills](https://img.shields.io/badge/Agent%20Skills-Standard-green.svg)](SKILL.md)
7
+
8
+ > **Universal Agent Skill Router, Lifecycle Manager & Tiered Storage Engine for AI Coding Agents.**
9
+ > Works across **Google Antigravity, Claude Code, Cursor, Windsurf, OpenCode, and CI/CD**.
10
+
11
+ ---
12
+
13
+ ## โšก The Problem: Context Bloat & Skill Bleed
14
+
15
+ As teams collect specialized skills (database admin, cloud deployment, bioinformatics, testing workflows), loading 50โ€“100+ skills into active AI prompts causes:
16
+ 1. **Context Window Saturation**: Thousands of prompt tokens consumed before the conversation even starts.
17
+ 2. **Skill Bleed**: AI models get confused by conflicting tool instructions from unrelated frameworks.
18
+ 3. **Broken Manifests & Orphan Folders**: Manual directory changes leave dangling references.
19
+
20
+ ## ๐Ÿ’ก The Solution: Tiered Skill Memory
21
+
22
+ **Skill Vault** implements a **two-tier memory model**:
23
+ - **L1 Active Memory (`skills/`)**: Lightweight general-purpose skills actively loaded in context.
24
+ - **L2 Cold Storage (`skill_archive/`)**: Deep domain skills indexed in metadata, searchable in milliseconds, and dynamically mounted or restored on demand.
25
+
26
+ ```
27
+ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
28
+ โ”‚ AI CODING AGENT โ”‚
29
+ โ”‚ (Google Antigravity / Claude Code / Cursor / Windsurf) โ”‚
30
+ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
31
+ โ”‚
32
+ โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
33
+ โ–ผ โ–ผ
34
+ [L1 Active Context Memory] [L2 Cold Storage Archive]
35
+ ./.agents/skills/ ./skill_archive/skills/
36
+ - general-git-workflow - alloydb-omni-cluster
37
+ - managing-python-deps - gcp-composer-troubleshoot
38
+ - alphafold-protein-analysis
39
+ โ”‚ โ–ฒ
40
+ โ”‚ npx @jcorpac/skill-vault โ”‚
41
+ โ”‚ archive โ”‚
42
+ โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–บโ”‚
43
+ โ”‚ npx @jcorpac/skill-vault โ”‚
44
+ โ”‚ restore โ”‚
45
+ โ”‚โ—„โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
46
+ ```
47
+
48
+ ---
49
+
50
+ ## ๐Ÿš€ Quickstart
51
+
52
+ ### Option 1: Run via `npx` (Zero Installation)
53
+ ```bash
54
+ # Initialize a repository for skill storage
55
+ npx @jcorpac/skill-vault init
56
+
57
+ # Search indexed skills
58
+ npx @jcorpac/skill-vault search "database"
59
+
60
+ # Verify archive integrity
61
+ npx @jcorpac/skill-vault verify --fix
62
+ ```
63
+
64
+ ### Option 2: Install as an Agent Skill
65
+ Install directly into Claude Code, Antigravity, or Cursor:
66
+ ```bash
67
+ npx skills add jcorpac/skill-vault
68
+ ```
69
+
70
+ ### Option 3: Use with Python CLI (Pure Standard Library)
71
+ ```bash
72
+ python scripts/skill_vault.py verify
73
+ ```
74
+
75
+ ---
76
+
77
+ ## ๐Ÿ› ๏ธ CLI Command Reference
78
+
79
+ | Command | Description |
80
+ | :--- | :--- |
81
+ | `skill-vault init` | Bootstrap standard skill and archive folders in workspace. |
82
+ | `skill-vault archive <name> --category "<Cat>"` | Move active skill to archive with category metadata. |
83
+ | `skill-vault archive --pattern "gcp-*"` | Archive multiple matching skills via glob pattern. |
84
+ | `skill-vault recategorize <name> "<New Cat>"` | Reorganize skill category without modifying `SKILL.md`. |
85
+ | `skill-vault restore <name>` | Restore an archived skill back to active availability. |
86
+ | `skill-vault restore --category "<Cat>"` | Restore all skills in a specific category. |
87
+ | `skill-vault search "<query>"` | Search skills across names, descriptions, and categories. |
88
+ | `skill-vault reindex` | Regenerate `INDEX.md` and sync `backup_manifest.json`. |
89
+ | `skill-vault verify` | Audit bi-directional consistency across disk, manifest, and index. |
90
+ | `skill-vault verify --fix` | Audit and automatically self-heal all detected discrepancies. |
91
+
92
+ ---
93
+
94
+ ## ๐ŸŽฏ Key Design Principles
95
+
96
+ 1. **`SKILL.md` Purity**: `SKILL.md` files are immutable instructions. Categories and routing metadata are stored strictly in `backup_manifest.json` and rendered in `INDEX.md`.
97
+ 2. **Environment Agnostic**: Dynamically resolves workspace roots via CLI flags (`--base-dir`), environment variables (`$SKILL_VAULT_BASE`), script parents, or working directories.
98
+ 3. **Zero Runtime Dependencies**: The core engine requires only Python 3 standard library (`os`, `sys`, `json`, `re`, `shutil`, `hashlib`, `argparse`, `pathlib`).
99
+ 4. **Self-Healing Integrity**: Detects orphaned folders, phantom manifest entries, broken markdown links, and duplicate aliases.
100
+
101
+ ---
102
+
103
+ ## ๐Ÿงช Running the Test Suite
104
+
105
+ Skill Vault includes a comprehensive, sandboxed test harness:
106
+
107
+ ```bash
108
+ # Run unit tests
109
+ python -m unittest discover -s tests -v
110
+
111
+ # Or via npm
112
+ npm test
113
+ ```
114
+
115
+ ---
116
+
117
+ ## ๐Ÿ“„ License
118
+
119
+ MIT License. See [LICENSE](LICENSE) for details.
package/SKILL.md ADDED
@@ -0,0 +1,117 @@
1
+ ---
2
+ name: skill-vault
3
+ description: Universal agent-agnostic and OS-agnostic skill router, tiered storage manager, and lifecycle auditor. Solves context bloat and skill bleed by managing active skills vs archived cold storage across environments (Google Antigravity, Claude Code, Cursor, CI/CD).
4
+ ---
5
+
6
+ # Skill Vault: Universal Agent Skill Lifecycle & Storage Manager
7
+
8
+ ## Overview
9
+ **Skill Vault** provides an **agent-agnostic**, **environment-agnostic**, and **OS-agnostic** framework for:
10
+ 1. **Tiered Context Optimization**: Managing active skills (L1 context memory) and cold-storage archives (L2 disk storage) to eliminate "skill bleed" and prompt token waste.
11
+ 2. **Dynamic Skill Routing**: Discovering, querying, and dynamically executing specialized domain skills across active and archived repositories.
12
+ 3. **Decoupled Categorization**: Organizing skills via manifest metadata without modifying `SKILL.md` files.
13
+ 4. **Bi-Directional Integrity Auditing**: Verifying and self-healing consistency across disk folders, `backup_manifest.json`, and `INDEX.md`.
14
+
15
+ ---
16
+
17
+ ## 1. Skill Discovery & Execution Protocol (Agent-Agnostic)
18
+
19
+ Whenever a user request requires specialized domain knowledge:
20
+
21
+ 1. **Locate Target Skill**:
22
+ - Check active skill locations (`skills/`, `.agents/skills/`, `.claude/skills/`, `plugins/*/skills/`).
23
+ - If missing from active locations, search the central archive manifest via CLI:
24
+ ```bash
25
+ python scripts/skill_vault.py search "<keyword or topic>"
26
+ ```
27
+ or consult `skill_archive/INDEX.md` / `skill_archive/backup_manifest.json`.
28
+
29
+ 2. **Execute Based on Environment Capabilities**:
30
+ - **Multi-Agent / Delegation Supported** (e.g., Antigravity `invoke_subagent`, Claude Code subagent):
31
+ Spawn a subagent instructed to view the target `SKILL.md` and execute the task.
32
+ - **Single-Agent CLI / Standalone Mode**:
33
+ Use native file-reading tools to load the target `SKILL.md` directly into main context.
34
+
35
+ ---
36
+
37
+ ## 2. Skill Lifecycle Management Operations (Automated via CLI)
38
+
39
+ All lifecycle operations are executed via the portable Python CLI `scripts/skill_vault.py`.
40
+
41
+ > [!NOTE]
42
+ > `SKILL.md` files are **never modified** when categorizing or archiving. Categories are strictly routing metadata stored inside `backup_manifest.json` and presented in `INDEX.md`.
43
+
44
+ ### A. Archiving Skills (LLM-Driven Categorization)
45
+ When asked to archive an active skill into cold storage:
46
+ 1. Read the skill's `SKILL.md` to understand its domain.
47
+ 2. Select a concise, human-readable category fitting the user's workspace (e.g. `"Cloud Infrastructure"`, `"Data Engineering"`, `"Mobile Development"`, `"Bioinformatics"`).
48
+ 3. Run the archive command with `--category`:
49
+ ```bash
50
+ # Archive a single skill with category
51
+ python scripts/skill_vault.py archive <skill_name> --category "<Category Name>"
52
+
53
+ # Archive multiple skills matching a pattern
54
+ python scripts/skill_vault.py archive --pattern "gcp-*" --category "GCP & Data Engineering"
55
+
56
+ # Archive while keeping the active folder intact
57
+ python scripts/skill_vault.py archive <skill_name> --category "<Category Name>" --keep-active
58
+ ```
59
+
60
+ ### B. Recategorizing Skills
61
+ To reorganize existing archived skills without touching `SKILL.md`:
62
+ ```bash
63
+ python scripts/skill_vault.py recategorize <skill_name> "<New Category Name>"
64
+ ```
65
+
66
+ ### C. Unarchiving / Restoring Skills
67
+ To restore archived skills back to active availability:
68
+ ```bash
69
+ # Restore a specific skill
70
+ python scripts/skill_vault.py restore <skill_name>
71
+
72
+ # Restore all skills in a category
73
+ python scripts/skill_vault.py restore --category "GCP & Data Engineering"
74
+
75
+ # Restore all archived skills
76
+ python scripts/skill_vault.py restore --all
77
+ ```
78
+
79
+ ### D. Reindexing & Manifest Refresh
80
+ To rebuild `INDEX.md` and ensure all paths and category sections are synchronized:
81
+ ```bash
82
+ python scripts/skill_vault.py reindex
83
+ ```
84
+
85
+ ### E. Skill Discovery & Keyword Search
86
+ ```bash
87
+ python scripts/skill_vault.py search "<keyword>"
88
+ ```
89
+
90
+ ### F. Archive Integrity Audit & Self-Healing
91
+ To confirm bi-directional consistency across disk folders, `backup_manifest.json`, and `INDEX.md`:
92
+ ```bash
93
+ # Run integrity verification audit
94
+ python scripts/skill_vault.py verify
95
+
96
+ # Run audit and automatically fix any detected discrepancies
97
+ python scripts/skill_vault.py verify --fix
98
+ ```
99
+
100
+ ---
101
+
102
+ ## 3. Environment & OS Compatibility Guidelines
103
+
104
+ - **Base Directory**: Auto-discovers the workspace root relative to the script location, current working directory, or via `--base-dir <path>` / `$SKILL_VAULT_BASE`.
105
+ - **Portable Relative Links**: `INDEX.md` and `backup_manifest.json` use relative paths, allowing the skill repository to be committed to Git or shared across environments seamlessly.
106
+ - **Pure Python**: Requires only Python 3 standard library (`os`, `sys`, `json`, `re`, `shutil`, `hashlib`, `argparse`, `pathlib`).
107
+
108
+ ---
109
+
110
+ ## 4. Automated Testing Harness
111
+
112
+ A sandboxed test suite is located in `tests/test_skill_vault.py` to prevent regressions whenever changes are made:
113
+
114
+ ```bash
115
+ # Run test suite
116
+ python -m unittest discover -s tests -v
117
+ ```
package/bin/cli.js ADDED
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Skill Vault CLI - Node.js thin runner
5
+ * Spawns the underlying portable Python engine (scripts/skill_vault.py).
6
+ */
7
+
8
+ const { spawn } = require('child_process');
9
+ const path = require('path');
10
+
11
+ const scriptPath = path.join(__dirname, '..', 'scripts', 'skill_vault.py');
12
+ const pythonCmd = process.platform === 'win32' ? 'python' : 'python3';
13
+
14
+ const child = spawn(pythonCmd, [scriptPath, ...process.argv.slice(2)], {
15
+ stdio: 'inherit'
16
+ });
17
+
18
+ child.on('error', (err) => {
19
+ if (err.code === 'ENOENT') {
20
+ console.error(`\x1b[31m[Skill Vault Error]\x1b[0m Python 3 was not found on your system PATH. Please ensure Python 3 is installed.`);
21
+ } else {
22
+ console.error(`\x1b[31m[Skill Vault Error]\x1b[0m ${err.message}`);
23
+ }
24
+ process.exit(1);
25
+ });
26
+
27
+ child.on('exit', (code) => {
28
+ process.exit(code ?? 0);
29
+ });
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@jcorpac/skill-vault",
3
+ "version": "1.0.0",
4
+ "description": "Universal Agent Skill Router, Lifecycle Manager, and Tiered Storage Engine for AI Coding Agents.",
5
+ "main": "bin/cli.js",
6
+ "bin": {
7
+ "skill-vault": "bin/cli.js",
8
+ "skillvault": "bin/cli.js"
9
+ },
10
+ "files": [
11
+ "bin/",
12
+ "scripts/",
13
+ "SKILL.md",
14
+ "README.md",
15
+ "LICENSE"
16
+ ],
17
+ "scripts": {
18
+ "test": "python -m unittest discover -s tests -v",
19
+ "verify": "node bin/cli.js verify"
20
+ },
21
+ "keywords": [
22
+ "agent-skills",
23
+ "ai-agents",
24
+ "antigravity",
25
+ "claude-code",
26
+ "cursor",
27
+ "skill-router",
28
+ "skill-vault",
29
+ "context-optimization",
30
+ "llm-tools"
31
+ ],
32
+ "author": "jcorpac",
33
+ "license": "MIT",
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+https://github.com/jcorpac/skill-vault.git"
37
+ },
38
+ "bugs": {
39
+ "url": "https://github.com/jcorpac/skill-vault/issues"
40
+ },
41
+ "homepage": "https://github.com/jcorpac/skill-vault#readme"
42
+ }
@@ -0,0 +1,593 @@
1
+ #!/usr/bin/env python3
2
+ """Skill Vault: Universal Skill Archive, Lifecycle Manager & Router.
3
+
4
+ Works across Google Antigravity, Claude Code, Cursor, CI/CD, and standalone repositories.
5
+ Resolves paths relatively without hardcoded user directories. Categories are stored
6
+ strictly in backup_manifest.json and INDEX.md, keeping SKILL.md files pure and untouched.
7
+ """
8
+
9
+ import argparse
10
+ import hashlib
11
+ import json
12
+ import os
13
+ from pathlib import Path
14
+ import re
15
+ import shutil
16
+ import sys
17
+
18
+
19
+ def resolve_base_dir(cli_base=None):
20
+ """Dynamically resolve the base directory for skills and archives."""
21
+ if cli_base:
22
+ p = Path(cli_base).resolve()
23
+ if p.exists():
24
+ return p
25
+
26
+ env_base = os.environ.get("SKILL_VAULT_BASE") or os.environ.get("SKILL_BASE_DIR") or os.environ.get("AGENTS_HOME")
27
+ if env_base:
28
+ p = Path(env_base).resolve()
29
+ if p.exists():
30
+ return p
31
+
32
+ # Check ancestors of the script location
33
+ script_path = Path(__file__).resolve()
34
+ for parent in script_path.parents:
35
+ if parent.name != "skill_archive" and (
36
+ (parent / "skill_archive").exists() or (parent / "skills").exists()
37
+ ):
38
+ return parent
39
+
40
+ cwd = Path.cwd().resolve()
41
+ for candidate in [
42
+ cwd,
43
+ cwd / ".agents",
44
+ cwd / ".claude",
45
+ Path.home() / ".gemini" / "config",
46
+ Path.home() / ".agents",
47
+ Path.home() / ".claude",
48
+ ]:
49
+ if candidate.exists() and (
50
+ (candidate / "skills").exists() or (candidate / "skill_archive").exists()
51
+ ):
52
+ return candidate
53
+
54
+ return cwd
55
+
56
+
57
+ class SkillVault:
58
+ def __init__(self, base_dir=None):
59
+ self.base_dir = resolve_base_dir(base_dir)
60
+ self.archive_dir = self.base_dir / "skill_archive"
61
+ self.manifest_file = self.archive_dir / "backup_manifest.json"
62
+ self.index_file = self.archive_dir / "INDEX.md"
63
+ self.skills_dir = self.base_dir / "skills"
64
+
65
+ def init(self):
66
+ """Bootstrap standard directory structure for a new workspace or repository."""
67
+ self.skills_dir.mkdir(parents=True, exist_ok=True)
68
+ (self.archive_dir / "skills").mkdir(parents=True, exist_ok=True)
69
+ if not self.manifest_file.exists():
70
+ self.save_manifest([])
71
+ if not self.index_file.exists():
72
+ self.index_file.write_text("# Skill Archive Index\n\nTotal Archived Skills: 0\n", encoding="utf-8")
73
+ print(f"[Initialized] Skill Vault initialized at: {self.base_dir}")
74
+ print(f" โ€ข Active skills: {self.skills_dir}")
75
+ print(f" โ€ข Archive store: {self.archive_dir}")
76
+
77
+ def get_active_skill_dirs(self):
78
+ """Discover active skill directories."""
79
+ dirs = []
80
+ if self.skills_dir.exists():
81
+ dirs.append(self.skills_dir)
82
+
83
+ for sub in [".agents/skills", ".claude/skills"]:
84
+ p = self.base_dir / sub
85
+ if p.exists():
86
+ dirs.append(p)
87
+
88
+ plugins_dir = self.base_dir / "plugins"
89
+ if plugins_dir.exists():
90
+ for p in plugins_dir.iterdir():
91
+ if p.is_dir() and (p / "skills").exists():
92
+ dirs.append(p / "skills")
93
+ return dirs
94
+
95
+ def get_archived_skill_folders(self):
96
+ """Discover all skill folders physically present in the archive directory."""
97
+ archive_subdirs = [self.archive_dir / "skills"]
98
+ if self.archive_dir.exists():
99
+ for p in self.archive_dir.iterdir():
100
+ if p.is_dir() and p.name.startswith("plugins_") and p.name.endswith("_skills"):
101
+ archive_subdirs.append(p)
102
+
103
+ folders = {}
104
+ for base in archive_subdirs:
105
+ if base.exists():
106
+ for folder in base.iterdir():
107
+ if folder.is_dir():
108
+ skill_md = folder / "SKILL.md"
109
+ folders[folder.name] = {
110
+ "name": folder.name,
111
+ "folder": folder,
112
+ "skill_md": skill_md,
113
+ "has_skill_md": skill_md.exists(),
114
+ "size": skill_md.stat().st_size if skill_md.exists() else 0,
115
+ }
116
+ return folders
117
+
118
+ def load_manifest(self):
119
+ """Load backup_manifest.json."""
120
+ if self.manifest_file.exists():
121
+ try:
122
+ with open(self.manifest_file, "r", encoding="utf-8") as f:
123
+ return json.load(f)
124
+ except Exception as e:
125
+ print(f"[Warning] Failed to parse {self.manifest_file}: {e}")
126
+ return []
127
+
128
+ def save_manifest(self, manifest):
129
+ """Save manifest sorted by category and name."""
130
+ manifest.sort(key=lambda x: (x.get("category", "").lower(), x.get("name", "").lower()))
131
+ self.archive_dir.mkdir(parents=True, exist_ok=True)
132
+ with open(self.manifest_file, "w", encoding="utf-8") as f:
133
+ json.dump(manifest, f, indent=2, ensure_ascii=False)
134
+
135
+ def parse_skill_description(self, skill_md_path):
136
+ """Extract description from SKILL.md without modifying it."""
137
+ skill_md_path = Path(skill_md_path)
138
+ if not skill_md_path.exists():
139
+ return "No description available."
140
+
141
+ with open(skill_md_path, "r", encoding="utf-8", errors="replace") as f:
142
+ content = f.read()
143
+
144
+ fm_match = re.match(r"^---\s*\n(.*?)\n---\s*\n", content, re.DOTALL)
145
+ if fm_match:
146
+ fm_text = fm_match.group(1)
147
+ desc_match = re.search(
148
+ r"^description:\s*(?:>[-+]?|\|[-+]?)?\s*\n?(.*?)(?=\n[a-zA-Z0-9_-]+:|\Z)",
149
+ fm_text,
150
+ re.DOTALL | re.MULTILINE,
151
+ )
152
+ if desc_match:
153
+ raw_desc = desc_match.group(1).strip()
154
+ return " ".join(line.strip() for line in raw_desc.splitlines() if line.strip())
155
+ simple_desc = re.search(r"^description:\s*([^\n]+)", fm_text, re.MULTILINE)
156
+ if simple_desc:
157
+ return simple_desc.group(1).strip().strip("'\"")
158
+ return "No description available."
159
+
160
+ def find_active_skill(self, skill_name):
161
+ """Find active skill across discovered search paths."""
162
+ for search_dir in self.get_active_skill_dirs():
163
+ target = search_dir / skill_name
164
+ if target.exists() and (target / "SKILL.md").exists():
165
+ return target
166
+ return None
167
+
168
+ def make_portable_path(self, abs_path):
169
+ """Convert path to relative from base_dir if possible."""
170
+ try:
171
+ return str(Path(abs_path).resolve().relative_to(self.base_dir))
172
+ except ValueError:
173
+ return str(abs_path)
174
+
175
+ def resolve_portable_path(self, path_str):
176
+ """Resolve a stored relative path back to an absolute Path."""
177
+ p = Path(path_str)
178
+ if p.is_absolute():
179
+ return p
180
+ return (self.base_dir / p).resolve()
181
+
182
+ def parse_index_file(self):
183
+ """Parse INDEX.md and return extracted skills with categories and link targets."""
184
+ if not self.index_file.exists():
185
+ return {}
186
+
187
+ with open(self.index_file, "r", encoding="utf-8", errors="replace") as f:
188
+ content = f.read()
189
+
190
+ indexed_skills = {}
191
+ current_category = "General & Utility Skills"
192
+
193
+ for line in content.splitlines():
194
+ cat_match = re.match(r"^##\s+(.*?)\s+\(\d+\s+skills?\)", line)
195
+ if cat_match:
196
+ current_category = cat_match.group(1).strip()
197
+ continue
198
+
199
+ skill_match = re.match(r"^###\s+`([^`]+)`", line)
200
+ if skill_match:
201
+ skill_name = skill_match.group(1).strip()
202
+ indexed_skills[skill_name] = {
203
+ "name": skill_name,
204
+ "category": current_category,
205
+ "link_path": None,
206
+ }
207
+ continue
208
+
209
+ link_match = re.search(r"\- \*\*Archived Path\*\*:\s+\[`SKILL\.md`\]\((.*?)\)", line)
210
+ if link_match and indexed_skills:
211
+ last_skill = list(indexed_skills.keys())[-1]
212
+ if indexed_skills[last_skill]["link_path"] is None:
213
+ indexed_skills[last_skill]["link_path"] = link_match.group(1).strip()
214
+
215
+ return indexed_skills
216
+
217
+ # --- Actions ---
218
+
219
+ def archive(self, name=None, pattern=None, category=None, keep_active=False):
220
+ """Archive active skills with an assigned category."""
221
+ manifest = self.load_manifest()
222
+ manifest_map = {item["name"]: item for item in manifest}
223
+
224
+ skills_to_archive = []
225
+ if name:
226
+ skills_to_archive.append(name)
227
+ elif pattern:
228
+ regex = re.compile(pattern.replace("*", ".*"))
229
+ for s_dir in self.get_active_skill_dirs():
230
+ for item in s_dir.iterdir():
231
+ if item.is_dir() and regex.match(item.name):
232
+ skills_to_archive.append(item.name)
233
+
234
+ if not skills_to_archive:
235
+ print("No matching active skills found to archive.")
236
+ return
237
+
238
+ category_name = category.strip() if category else None
239
+
240
+ for skill_name in sorted(set(skills_to_archive)):
241
+ active_path = self.find_active_skill(skill_name)
242
+ if not active_path:
243
+ print(f"[Skip] Active skill '{skill_name}' not found.")
244
+ continue
245
+
246
+ dest_dir = self.archive_dir / "skills" / skill_name
247
+ dest_dir.parent.mkdir(parents=True, exist_ok=True)
248
+
249
+ if dest_dir.exists():
250
+ shutil.rmtree(dest_dir)
251
+ shutil.copytree(active_path, dest_dir)
252
+ print(f"[Archived] {active_path} -> {dest_dir}")
253
+
254
+ existing_cat = manifest_map.get(skill_name, {}).get("category")
255
+ assigned_cat = category_name or existing_cat or "General & Utility Skills"
256
+
257
+ manifest_map[skill_name] = {
258
+ "name": skill_name,
259
+ "category": assigned_cat,
260
+ "original_path": self.make_portable_path(active_path),
261
+ "archived_path": self.make_portable_path(dest_dir),
262
+ }
263
+
264
+ if not keep_active:
265
+ shutil.rmtree(active_path)
266
+ print(f"[Cleaned] Removed active directory: {active_path}")
267
+
268
+ self.save_manifest(list(manifest_map.values()))
269
+ self.reindex()
270
+ print("Archiving complete.")
271
+
272
+ def recategorize(self, name, new_category):
273
+ """Update category for an archived skill."""
274
+ manifest = self.load_manifest()
275
+ manifest_map = {item["name"]: item for item in manifest}
276
+
277
+ if name not in manifest_map:
278
+ print(f"[Error] Skill '{name}' not found in manifest.")
279
+ return
280
+
281
+ old_cat = manifest_map[name].get("category", "Uncategorized")
282
+ manifest_map[name]["category"] = new_category.strip()
283
+ self.save_manifest(list(manifest_map.values()))
284
+ self.reindex()
285
+ print(f"[Recategorized] '{name}': '{old_cat}' -> '{new_category.strip()}'")
286
+
287
+ def restore(self, name=None, pattern=None, category=None, restore_all=False, force=False):
288
+ """Restore archived skills back to active locations."""
289
+ manifest = self.load_manifest()
290
+ if not manifest:
291
+ print("Manifest is empty. Nothing to restore.")
292
+ return
293
+
294
+ targets = []
295
+ if restore_all:
296
+ targets = manifest
297
+ elif name:
298
+ targets = [m for m in manifest if m["name"] == name]
299
+ elif pattern:
300
+ regex = re.compile(pattern.replace("*", ".*"))
301
+ targets = [m for m in manifest if regex.match(m["name"])]
302
+ elif category:
303
+ targets = [m for m in manifest if m.get("category", "").lower() == category.lower()]
304
+
305
+ if not targets:
306
+ print("No matching skills found to restore.")
307
+ return
308
+
309
+ for item in targets:
310
+ archived_path = self.resolve_portable_path(item["archived_path"])
311
+ original_path = self.resolve_portable_path(item["original_path"])
312
+
313
+ if not archived_path.exists():
314
+ print(f"[Error] Missing archive source: {archived_path}")
315
+ continue
316
+
317
+ original_path.parent.mkdir(parents=True, exist_ok=True)
318
+ if original_path.exists():
319
+ if force:
320
+ shutil.rmtree(original_path)
321
+ else:
322
+ print(f"[Skip] Target exists: {original_path} (use --force to overwrite)")
323
+ continue
324
+
325
+ shutil.copytree(archived_path, original_path)
326
+ print(f"[Restored] {item['name']} -> {original_path}")
327
+
328
+ print("Restoration complete.")
329
+
330
+ def reindex(self):
331
+ """Rebuild INDEX.md grouped by manifest categories with portable relative links."""
332
+ manifest = self.load_manifest()
333
+ manifest_by_folder = {}
334
+
335
+ for item in manifest:
336
+ archived_path = self.resolve_portable_path(item.get("archived_path", ""))
337
+ if archived_path.exists() and (archived_path / "SKILL.md").exists():
338
+ folder_name = archived_path.name
339
+ if folder_name not in manifest_by_folder or item.get("name") == folder_name:
340
+ manifest_by_folder[folder_name] = {
341
+ "name": folder_name,
342
+ "category": item.get("category") or "General & Utility Skills",
343
+ "original_path": item.get("original_path", self.make_portable_path(self.skills_dir / folder_name)),
344
+ "archived_path": self.make_portable_path(archived_path),
345
+ }
346
+
347
+ # Discover all archive directories physically on disk
348
+ disk_skills = self.get_archived_skill_folders()
349
+ for name, data in disk_skills.items():
350
+ if data["has_skill_md"] and name not in manifest_by_folder:
351
+ manifest_by_folder[name] = {
352
+ "name": name,
353
+ "category": "General & Utility Skills",
354
+ "original_path": self.make_portable_path(self.skills_dir / name),
355
+ "archived_path": self.make_portable_path(data["folder"]),
356
+ }
357
+
358
+ # Group by category
359
+ categories = {}
360
+ for name, item in manifest_by_folder.items():
361
+ cat = item.get("category") or "General & Utility Skills"
362
+ categories.setdefault(cat, []).append(item)
363
+
364
+ total_count = len(manifest_by_folder)
365
+ lines = ["# Skill Archive Index", "", f"Total Archived Skills: {total_count}", ""]
366
+
367
+ for cat in sorted(categories.keys()):
368
+ skills_in_cat = sorted(categories[cat], key=lambda x: x["name"].lower())
369
+ lines.append(f"## {cat} ({len(skills_in_cat)} skills)")
370
+ lines.append("")
371
+ for s in skills_in_cat:
372
+ skill_name = s["name"]
373
+ archived_path = self.resolve_portable_path(s["archived_path"])
374
+ skill_md = archived_path / "SKILL.md"
375
+ desc = self.parse_skill_description(skill_md)
376
+
377
+ lines.append(f"### `{skill_name}`")
378
+ lines.append(f"- **Description**: {desc}")
379
+
380
+ try:
381
+ rel_link = skill_md.relative_to(self.archive_dir).as_posix()
382
+ lines.append(f"- **Archived Path**: [`SKILL.md`]({rel_link})")
383
+ except ValueError:
384
+ file_uri = skill_md.resolve().as_uri().replace("file:////", "file:///")
385
+ lines.append(f"- **Archived Path**: [`SKILL.md`]({file_uri})")
386
+ lines.append("")
387
+
388
+ self.archive_dir.mkdir(parents=True, exist_ok=True)
389
+ with open(self.index_file, "w", encoding="utf-8") as f:
390
+ f.write("\n".join(lines).strip() + "\n")
391
+
392
+ self.save_manifest(list(manifest_by_folder.values()))
393
+ print(f"[Reindexed] {total_count} skills across {len(categories)} categories (Base: {self.base_dir}).")
394
+
395
+ def verify(self, fix=False):
396
+ """Perform a comprehensive bi-directional integrity check across Disk, Manifest, and INDEX.md."""
397
+ print("==================================================")
398
+ print(" SKILL VAULT INTEGRITY AUDIT")
399
+ print(f" Base Directory: {self.base_dir}")
400
+ print(f" Archive Store: {self.archive_dir}")
401
+ print("==================================================\n")
402
+
403
+ disk_skills = self.get_archived_skill_folders()
404
+ manifest = self.load_manifest()
405
+ manifest_map = {m["name"]: m for m in manifest}
406
+ indexed_skills = self.parse_index_file()
407
+
408
+ issues = []
409
+ warnings = []
410
+
411
+ # 1. Check Disk Skill Folders
412
+ for name, d in disk_skills.items():
413
+ if not d["has_skill_md"]:
414
+ issues.append(f"[Disk Error] Folder '{name}' in archive is missing SKILL.md")
415
+ elif d["size"] == 0:
416
+ issues.append(f"[Disk Error] SKILL.md in '{name}' is 0 bytes (empty file)")
417
+
418
+ # 2. Check Disk vs Manifest
419
+ disk_names = set(disk_skills.keys())
420
+ manifest_names = set(manifest_map.keys())
421
+
422
+ unmanifested_disk = disk_names - manifest_names
423
+ if unmanifested_disk:
424
+ for name in sorted(unmanifested_disk):
425
+ issues.append(f"[Uncataloged on Disk] '{name}' exists in archive folder but NOT in backup_manifest.json")
426
+
427
+ phantom_manifest = manifest_names - disk_names
428
+ if phantom_manifest:
429
+ for name in sorted(phantom_manifest):
430
+ issues.append(f"[Phantom Manifest Entry] '{name}' listed in backup_manifest.json but NOT found on disk")
431
+
432
+ # 3. Check Manifest Path Integrity
433
+ for item in manifest:
434
+ name = item["name"]
435
+ archived_path = self.resolve_portable_path(item.get("archived_path", ""))
436
+ if not archived_path.exists():
437
+ issues.append(f"[Broken Manifest Path] '{name}' archived_path does not exist: {archived_path}")
438
+ elif not (archived_path / "SKILL.md").exists():
439
+ issues.append(f"[Missing SKILL.md] '{name}' archived_path has no SKILL.md: {archived_path}")
440
+
441
+ if not item.get("category"):
442
+ warnings.append(f"[Missing Category] '{name}' in manifest has no category assigned")
443
+
444
+ # 4. Check Disk vs INDEX.md
445
+ index_names = set(indexed_skills.keys())
446
+ unindexed_disk = disk_names - index_names
447
+ if unindexed_disk:
448
+ for name in sorted(unindexed_disk):
449
+ issues.append(f"[Unindexed on Disk] '{name}' exists on disk but is NOT listed in INDEX.md")
450
+
451
+ phantom_index = index_names - disk_names
452
+ if phantom_index:
453
+ for name in sorted(phantom_index):
454
+ issues.append(f"[Phantom Index Entry] '{name}' listed in INDEX.md but does NOT exist on disk")
455
+
456
+ # 5. Check INDEX.md vs Manifest
457
+ unindexed_manifest = manifest_names - index_names
458
+ if unindexed_manifest:
459
+ for name in sorted(unindexed_manifest):
460
+ issues.append(f"[Manifest/Index Mismatch] '{name}' is in backup_manifest.json but NOT in INDEX.md")
461
+
462
+ # 6. Check INDEX.md Link Validity
463
+ for name, data in indexed_skills.items():
464
+ link_path_str = data.get("link_path")
465
+ if link_path_str:
466
+ if link_path_str.startswith("file:///"):
467
+ pass
468
+ else:
469
+ target_file = (self.archive_dir / link_path_str).resolve()
470
+ if not target_file.exists():
471
+ issues.append(f"[Broken Index Link] '{name}' link target missing: {target_file}")
472
+
473
+ # Summary Metrics
474
+ print("Component Counts:")
475
+ print(f" * Physical Folders on Disk: {len(disk_skills)}")
476
+ print(f" * Entries in backup_manifest.json: {len(manifest)}")
477
+ print(f" * Entries in INDEX.md: {len(indexed_skills)}\n")
478
+
479
+ if not issues and not warnings:
480
+ print("[OK] 100% Integrity Verified! Disk, manifest, and index are in perfect sync.\n")
481
+ return 0
482
+
483
+ if warnings:
484
+ print(f"Warnings ({len(warnings)}):")
485
+ for w in warnings:
486
+ print(f" [!] {w}")
487
+ print("")
488
+
489
+ if issues:
490
+ print(f"Discrepancies / Errors ({len(issues)}):")
491
+ for iss in issues:
492
+ print(f" [X] {iss}")
493
+ print("")
494
+
495
+ if fix:
496
+ print("[Self-Healing] Applying automatic repairs (--fix enabled)...")
497
+ self.reindex()
498
+ print("[Self-Healing] Reindexed and resynchronized successfully.\n")
499
+ return 0
500
+ else:
501
+ print("Tip: Run with '--fix' (e.g. 'python skill_vault.py verify --fix') to automatically repair discrepancies.\n")
502
+ return 1
503
+
504
+ return 0
505
+
506
+ def search(self, query):
507
+ """Search archived skills."""
508
+ q = query.lower()
509
+ manifest = self.load_manifest()
510
+ results = []
511
+
512
+ for item in manifest:
513
+ name = item["name"]
514
+ cat = item.get("category", "General & Utility Skills")
515
+ archived_path = self.resolve_portable_path(item["archived_path"])
516
+ skill_md = archived_path / "SKILL.md"
517
+ desc = self.parse_skill_description(skill_md)
518
+
519
+ if q in name.lower() or q in desc.lower() or q in cat.lower():
520
+ results.append((name, cat, desc, str(archived_path)))
521
+
522
+ if not results:
523
+ print(f"No archived skills matched '{query}'.")
524
+ return
525
+
526
+ print(f"Found {len(results)} matching skill(s):\n")
527
+ for name, cat, desc, path_str in results:
528
+ print(f"* {name} [{cat}]")
529
+ desc_snippet = desc[:130] + "..." if len(desc) > 130 else desc
530
+ print(f" Description: {desc_snippet}")
531
+ print(f" Path: {path_str}\n")
532
+
533
+
534
+ def main():
535
+ parser = argparse.ArgumentParser(description="Skill Vault: Universal Agent Skill Lifecycle & Storage Manager")
536
+ parser.add_argument("--base-dir", help="Explicit base directory for skills and archive")
537
+ subparsers = parser.add_subparsers(dest="command", required=True)
538
+
539
+ # Init
540
+ p_init = subparsers.add_parser("init", help="Bootstrap standard skill directory structure in workspace")
541
+
542
+ # Archive
543
+ p_arch = subparsers.add_parser("archive", help="Archive active skills into cold storage")
544
+ p_arch.add_argument("name", nargs="?", help="Specific skill name")
545
+ p_arch.add_argument("--pattern", help="Glob pattern (e.g. 'gcp-*')")
546
+ p_arch.add_argument("--category", help="Category name (e.g. 'Cloud Architecture')")
547
+ p_arch.add_argument("--keep-active", action="store_true", help="Do not delete source folder")
548
+
549
+ # Recategorize
550
+ p_rec = subparsers.add_parser("recategorize", help="Recategorize an archived skill in metadata")
551
+ p_rec.add_argument("name", help="Skill name")
552
+ p_rec.add_argument("category", help="New category name")
553
+
554
+ # Restore
555
+ p_rest = subparsers.add_parser("restore", help="Restore archived skills back to active availability")
556
+ p_rest.add_argument("name", nargs="?", help="Specific skill name")
557
+ p_rest.add_argument("--all", action="store_true", help="Restore all archived skills")
558
+ p_rest.add_argument("--pattern", help="Glob pattern to restore")
559
+ p_rest.add_argument("--category", help="Category name to restore")
560
+ p_rest.add_argument("--force", action="store_true", help="Overwrite existing active directory")
561
+
562
+ # Reindex
563
+ p_idx = subparsers.add_parser("reindex", help="Rebuild INDEX.md and sync manifest")
564
+
565
+ # Verify / Integrity Check
566
+ p_ver = subparsers.add_parser("verify", help="Verify archive integrity across disk, manifest, and index")
567
+ p_ver.add_argument("--fix", action="store_true", help="Automatically repair any detected discrepancies")
568
+
569
+ # Search
570
+ p_srch = subparsers.add_parser("search", help="Search archived skills by keyword, intent, or domain")
571
+ p_srch.add_argument("query", help="Keyword to search for")
572
+
573
+ args = parser.parse_args()
574
+ mgr = SkillVault(base_dir=args.base_dir)
575
+
576
+ if args.command == "init":
577
+ mgr.init()
578
+ elif args.command == "archive":
579
+ mgr.archive(name=args.name, pattern=args.pattern, category=args.category, keep_active=args.keep_active)
580
+ elif args.command == "recategorize":
581
+ mgr.recategorize(name=args.name, new_category=args.category)
582
+ elif args.command == "restore":
583
+ mgr.restore(name=args.name, pattern=args.pattern, category=args.category, restore_all=args.all, force=args.force)
584
+ elif args.command == "reindex":
585
+ mgr.reindex()
586
+ elif args.command == "verify":
587
+ sys.exit(mgr.verify(fix=args.fix))
588
+ elif args.command == "search":
589
+ mgr.search(query=args.query)
590
+
591
+
592
+ if __name__ == "__main__":
593
+ main()