@jcorpac/skill-vault 2.0.0 → 2.0.1
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 +5 -4
- package/SKILL.md +5 -4
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/scripts/mcp_server.py +188 -25
- package/scripts/skill_router.py +47 -19
- package/scripts/skill_vault.py +197 -40
package/README.md
CHANGED
|
@@ -28,9 +28,10 @@ Loading 50–250+ specialized skills into active AI prompts causes:
|
|
|
28
28
|
└──────────────┬────────────────────────────────────────┬─────────────────┘
|
|
29
29
|
│ │
|
|
30
30
|
[1. Background Lifecycle Hooks] [2. Mid-Turn Read-Only MCP]
|
|
31
|
-
• SessionStart (silent sync & index) •
|
|
32
|
-
• PreInvocation / UserPromptSubmit •
|
|
33
|
-
└─► Pre-built BM25 + Multi-Signal
|
|
31
|
+
• SessionStart (silent sync & index) • list_skills(category?)
|
|
32
|
+
• PreInvocation / UserPromptSubmit • search_skills(query)
|
|
33
|
+
└─► Pre-built BM25 + Multi-Signal • load_skill(name, file?)
|
|
34
|
+
Router (~50–90ms, no approvals)
|
|
34
35
|
├─ Unrelated prompt ──► Injects 0 tokens
|
|
35
36
|
├─ High confidence ──► Inlines top 1–2 SKILL.md (<=12 KB cap)
|
|
36
37
|
└─ Broad / medium ──► Emits 1-line compact pointers
|
|
@@ -96,7 +97,7 @@ python scripts/skill_vault.py verify --fix
|
|
|
96
97
|
## 🎯 Key Design Principles
|
|
97
98
|
|
|
98
99
|
1. **Zero Context Bloat by Default**: Generic prompts (`"Refactor this function"`, `"Write a git commit message"`) inject **0 tokens**. Same-turn tool-call loops short-circuit automatically, and already-injected skills never re-inject in the same conversation.
|
|
99
|
-
2. **Zero-Approval Background Execution**: Hooks run natively in the agent lifecycle before the model is called; mid-turn fallback uses a
|
|
100
|
+
2. **Zero-Approval Background Execution**: Hooks run natively in the agent lifecycle before the model is called; mid-turn fallback uses a 3-tool read-only MCP server (`list_skills`, `search_skills`, `load_skill`) with strict directory-containment guards.
|
|
100
101
|
3. **`SKILL.md` Purity**: `SKILL.md` files are never modified during indexing or categorization.
|
|
101
102
|
4. **Hook-Dependency Safety**: `sync`, `optimize`, and `archive` inspect sibling `hooks.json` and `mcp_config.json` files so plugin-referenced skill scripts are never accidentally pruned.
|
|
102
103
|
5. **Zero Runtime Dependencies**: Pure Python 3.10+ standard library across Windows, macOS, and Linux.
|
package/SKILL.md
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: skill-vault
|
|
3
|
-
version: 2.0.
|
|
3
|
+
version: 2.0.1
|
|
4
4
|
description: >-
|
|
5
5
|
Universal agent-agnostic skill router and tiered storage manager.
|
|
6
6
|
Background hooks automatically inject relevant vaulted skills on demand;
|
|
7
|
-
use MCP tools search_skills/load_skill for mid-turn lookups.
|
|
7
|
+
use MCP tools list_skills/search_skills/load_skill for mid-turn lookups.
|
|
8
8
|
---
|
|
9
9
|
|
|
10
10
|
# Skill Vault: Automatic Skill Router & Cold-Storage Manager
|
|
@@ -16,7 +16,8 @@ description: >-
|
|
|
16
16
|
- `PreInvocation` / `UserPromptSubmit` / `BeforeAgent` scores the user prompt via a pre-built BM25 + multi-signal index (`<100ms`), injects top high-confidence skills or compact pointers directly from L2, and injects **0 tokens** on unrelated turns.
|
|
17
17
|
2. **Read-Only MCP Fallback (Mid-Turn Discovery)**:
|
|
18
18
|
- If a task pivots mid-turn to a specialized domain not present in context, call the `skill-vault` MCP tools:
|
|
19
|
-
- `
|
|
19
|
+
- `list_skills(category?, include_descriptions?)` — List all vaulted L2 skill names grouped by category in one call.
|
|
20
|
+
- `search_skills(query, category?, limit?, offset?)` — Search vaulted L2 skills by keyword, intent, or list categories.
|
|
20
21
|
- `load_skill(name, file?)` — Read a vaulted skill's `SKILL.md` or any companion file (`references/`, `scripts/`, `examples/`).
|
|
21
22
|
- Never mutate L1 active directories or run shell commands solely to browse archived skills when MCP tools are available.
|
|
22
23
|
|
|
@@ -43,7 +44,7 @@ skill-vault sync [--dry-run] [--keep-active]
|
|
|
43
44
|
# Re-classify 'General & Utility Skills' using built-in + custom rules
|
|
44
45
|
skill-vault recategorize --auto [--dry-run]
|
|
45
46
|
|
|
46
|
-
# Consolidate
|
|
47
|
+
# Consolidate duplicate skills in L2 (keeps newest version)
|
|
47
48
|
skill-vault dedupe [--dry-run]
|
|
48
49
|
|
|
49
50
|
# Inspect or tune routing thresholds & core skills
|
package/package.json
CHANGED
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "skill-vault",
|
|
3
3
|
"displayName": "Skill Vault",
|
|
4
|
-
"version": "2.0.
|
|
4
|
+
"version": "2.0.1",
|
|
5
5
|
"description": "Automatic background skill router, cold-storage archive, and read-only JIT MCP server for AI coding agents.",
|
|
6
6
|
"author": "jcorpac",
|
|
7
7
|
"homepage": "https://github.com/jcorpac/skill-vault#readme",
|
package/scripts/mcp_server.py
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
2
|
"""Skill Vault Read-Only MCP Stdio Server.
|
|
3
3
|
|
|
4
|
-
Provides
|
|
5
|
-
(supporting both newline-delimited JSON and Content-Length framing) so coding
|
|
6
|
-
|
|
4
|
+
Provides three read-only fallback tools (`search_skills`, `list_skills`, `load_skill`) over
|
|
5
|
+
JSON-RPC 2.0 (supporting both newline-delimited JSON and Content-Length framing) so coding
|
|
6
|
+
agents can discover and inspect cold-storage skills mid-turn without shell approvals or L1 mutations.
|
|
7
7
|
"""
|
|
8
8
|
|
|
9
9
|
import argparse
|
|
10
10
|
import json
|
|
11
11
|
import os
|
|
12
12
|
from pathlib import Path
|
|
13
|
+
import re
|
|
13
14
|
import sys
|
|
14
15
|
|
|
15
16
|
SCRIPT_DIR = Path(__file__).resolve().parent
|
|
@@ -19,7 +20,7 @@ if str(SCRIPT_DIR) not in sys.path:
|
|
|
19
20
|
import skill_router # noqa: E402
|
|
20
21
|
|
|
21
22
|
SERVER_NAME = "skill-vault"
|
|
22
|
-
SERVER_VERSION = "2.0.
|
|
23
|
+
SERVER_VERSION = "2.0.1"
|
|
23
24
|
MAX_READ_BYTES = 102400 # 100 KB safety cap per tool call
|
|
24
25
|
|
|
25
26
|
TOOLS_SPEC = [
|
|
@@ -27,7 +28,7 @@ TOOLS_SPEC = [
|
|
|
27
28
|
"name": "search_skills",
|
|
28
29
|
"description": (
|
|
29
30
|
"Search vaulted cold-storage skills by keyword, intent, or category. "
|
|
30
|
-
"Pass an empty query to list all
|
|
31
|
+
"Pass an empty query to list categories and counts, or use list_skills to list all skill names in one call."
|
|
31
32
|
),
|
|
32
33
|
"inputSchema": {
|
|
33
34
|
"type": "object",
|
|
@@ -45,6 +46,11 @@ TOOLS_SPEC = [
|
|
|
45
46
|
"description": "Maximum results to return (default 8, max 25).",
|
|
46
47
|
"default": 8,
|
|
47
48
|
},
|
|
49
|
+
"offset": {
|
|
50
|
+
"type": "integer",
|
|
51
|
+
"description": "Pagination offset into sorted results (default 0).",
|
|
52
|
+
"default": 0,
|
|
53
|
+
},
|
|
48
54
|
},
|
|
49
55
|
"required": ["query"],
|
|
50
56
|
},
|
|
@@ -55,6 +61,36 @@ TOOLS_SPEC = [
|
|
|
55
61
|
"openWorldHint": False,
|
|
56
62
|
},
|
|
57
63
|
},
|
|
64
|
+
{
|
|
65
|
+
"name": "list_skills",
|
|
66
|
+
"description": (
|
|
67
|
+
"List all vaulted cold-storage skill names grouped by category in a single compact call "
|
|
68
|
+
"(no 25-item limit). Optionally filter by category or include short 1-line descriptions."
|
|
69
|
+
),
|
|
70
|
+
"inputSchema": {
|
|
71
|
+
"type": "object",
|
|
72
|
+
"properties": {
|
|
73
|
+
"category": {
|
|
74
|
+
"type": "string",
|
|
75
|
+
"description": "Optional category name filter (case-insensitive).",
|
|
76
|
+
},
|
|
77
|
+
"include_descriptions": {
|
|
78
|
+
"type": "boolean",
|
|
79
|
+
"description": (
|
|
80
|
+
"Include truncated 1-line descriptions per skill "
|
|
81
|
+
"(default false for compact names-only output)."
|
|
82
|
+
),
|
|
83
|
+
"default": False,
|
|
84
|
+
},
|
|
85
|
+
},
|
|
86
|
+
},
|
|
87
|
+
"annotations": {
|
|
88
|
+
"readOnlyHint": True,
|
|
89
|
+
"destructiveHint": False,
|
|
90
|
+
"idempotentHint": True,
|
|
91
|
+
"openWorldHint": False,
|
|
92
|
+
},
|
|
93
|
+
},
|
|
58
94
|
{
|
|
59
95
|
"name": "load_skill",
|
|
60
96
|
"description": (
|
|
@@ -148,10 +184,40 @@ def _resolve_base_and_archive(cli_base=None):
|
|
|
148
184
|
return fallback, fallback / "skill_archive"
|
|
149
185
|
|
|
150
186
|
|
|
187
|
+
_INDEX_CACHE = {}
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _file_sig(path):
|
|
191
|
+
try:
|
|
192
|
+
st = Path(path).stat()
|
|
193
|
+
return (st.st_mtime_ns, st.st_size)
|
|
194
|
+
except OSError:
|
|
195
|
+
return None
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def clear_index_cache():
|
|
199
|
+
"""Clear the in-memory search index cache."""
|
|
200
|
+
_INDEX_CACHE.clear()
|
|
201
|
+
|
|
202
|
+
|
|
151
203
|
def _load_index(base_dir, archive_dir):
|
|
152
|
-
|
|
204
|
+
archive_path = Path(archive_dir).resolve()
|
|
205
|
+
cache_key = str(archive_path)
|
|
206
|
+
if not archive_path.exists():
|
|
207
|
+
_INDEX_CACHE.pop(cache_key, None)
|
|
153
208
|
return {"doc_count": 0, "skills": [], "df": {}, "avg_len": {}}
|
|
154
|
-
|
|
209
|
+
|
|
210
|
+
index_sig = _file_sig(archive_path / "search_index.json")
|
|
211
|
+
manifest_sig = _file_sig(archive_path / "backup_manifest.json")
|
|
212
|
+
cached = _INDEX_CACHE.get(cache_key)
|
|
213
|
+
if cached is not None and cached[0] == index_sig and cached[1] == manifest_sig:
|
|
214
|
+
return cached[2]
|
|
215
|
+
|
|
216
|
+
data = skill_router.load_or_build_index(archive_dir=archive_path, base_dir=base_dir)
|
|
217
|
+
new_index_sig = _file_sig(archive_path / "search_index.json")
|
|
218
|
+
new_manifest_sig = _file_sig(archive_path / "backup_manifest.json")
|
|
219
|
+
_INDEX_CACHE[cache_key] = (new_index_sig, new_manifest_sig, data)
|
|
220
|
+
return data
|
|
155
221
|
|
|
156
222
|
|
|
157
223
|
def _tool_result(text, is_error=False):
|
|
@@ -161,6 +227,78 @@ def _tool_result(text, is_error=False):
|
|
|
161
227
|
}
|
|
162
228
|
|
|
163
229
|
|
|
230
|
+
def _short_desc(text, max_len=160):
|
|
231
|
+
collapsed = " ".join(str(text or "").split())
|
|
232
|
+
if len(collapsed) <= max_len:
|
|
233
|
+
return collapsed
|
|
234
|
+
return collapsed[: max_len - 3].rstrip() + "..."
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _handle_list_skills(args, base_dir, archive_dir):
|
|
238
|
+
category = args.get("category")
|
|
239
|
+
if category is not None:
|
|
240
|
+
category = str(category).strip() or None
|
|
241
|
+
|
|
242
|
+
raw_inc = args.get("include_descriptions", False)
|
|
243
|
+
if isinstance(raw_inc, bool):
|
|
244
|
+
include_descriptions = raw_inc
|
|
245
|
+
elif isinstance(raw_inc, str):
|
|
246
|
+
include_descriptions = raw_inc.strip().lower() in ("true", "1", "yes")
|
|
247
|
+
else:
|
|
248
|
+
include_descriptions = bool(raw_inc)
|
|
249
|
+
|
|
250
|
+
index_data = _load_index(base_dir, archive_dir)
|
|
251
|
+
skills = index_data.get("skills", [])
|
|
252
|
+
|
|
253
|
+
grouped = {}
|
|
254
|
+
for entry in skills:
|
|
255
|
+
cat = entry.get("category") or "General & Utility Skills"
|
|
256
|
+
grouped.setdefault(cat, []).append(entry)
|
|
257
|
+
|
|
258
|
+
all_categories = sorted(grouped.keys(), key=str.lower)
|
|
259
|
+
|
|
260
|
+
if category:
|
|
261
|
+
cat_lower = category.lower()
|
|
262
|
+
filtered_items = [
|
|
263
|
+
(cat, items) for cat, items in grouped.items() if cat.lower() == cat_lower
|
|
264
|
+
]
|
|
265
|
+
else:
|
|
266
|
+
filtered_items = list(grouped.items())
|
|
267
|
+
|
|
268
|
+
filtered_items.sort(key=lambda kv: (-len(kv[1]), kv[0].lower()))
|
|
269
|
+
|
|
270
|
+
cat_blocks = []
|
|
271
|
+
total_matching = 0
|
|
272
|
+
for cat, items in filtered_items:
|
|
273
|
+
sorted_entries = sorted(items, key=lambda s: s.get("name", "").lower())
|
|
274
|
+
total_matching += len(sorted_entries)
|
|
275
|
+
if include_descriptions:
|
|
276
|
+
skill_list = [
|
|
277
|
+
{
|
|
278
|
+
"name": s["name"],
|
|
279
|
+
"description": _short_desc(s.get("description", "")),
|
|
280
|
+
}
|
|
281
|
+
for s in sorted_entries
|
|
282
|
+
]
|
|
283
|
+
else:
|
|
284
|
+
skill_list = [s["name"] for s in sorted_entries]
|
|
285
|
+
cat_blocks.append({
|
|
286
|
+
"category": cat,
|
|
287
|
+
"count": len(sorted_entries),
|
|
288
|
+
"skills": skill_list,
|
|
289
|
+
})
|
|
290
|
+
|
|
291
|
+
payload = {
|
|
292
|
+
"total_skills": total_matching,
|
|
293
|
+
"category_count": len(cat_blocks),
|
|
294
|
+
"categories": cat_blocks,
|
|
295
|
+
}
|
|
296
|
+
if category and total_matching == 0:
|
|
297
|
+
payload["available_categories"] = all_categories
|
|
298
|
+
|
|
299
|
+
return _tool_result(json.dumps(payload, indent=2, ensure_ascii=False))
|
|
300
|
+
|
|
301
|
+
|
|
164
302
|
def _handle_search_skills(args, base_dir, archive_dir):
|
|
165
303
|
query = str(args.get("query") or "")
|
|
166
304
|
category = args.get("category")
|
|
@@ -171,6 +309,10 @@ def _handle_search_skills(args, base_dir, archive_dir):
|
|
|
171
309
|
except (TypeError, ValueError):
|
|
172
310
|
limit = 8
|
|
173
311
|
limit = max(1, min(limit, 25))
|
|
312
|
+
try:
|
|
313
|
+
offset = max(0, int(args.get("offset", 0)))
|
|
314
|
+
except (TypeError, ValueError):
|
|
315
|
+
offset = 0
|
|
174
316
|
|
|
175
317
|
index_data = _load_index(base_dir, archive_dir)
|
|
176
318
|
skills = index_data.get("skills", [])
|
|
@@ -189,36 +331,55 @@ def _handle_search_skills(args, base_dir, archive_dir):
|
|
|
189
331
|
}
|
|
190
332
|
return _tool_result(json.dumps(summary, indent=2, ensure_ascii=False))
|
|
191
333
|
|
|
192
|
-
|
|
334
|
+
all_matches = skill_router.search_index(
|
|
193
335
|
index_data=index_data,
|
|
194
336
|
query=query,
|
|
195
337
|
category=category,
|
|
196
|
-
limit=
|
|
338
|
+
limit=None,
|
|
197
339
|
)
|
|
198
340
|
|
|
199
|
-
# Substring fallback for partial fragments (e.g., "proto") if
|
|
200
|
-
if not
|
|
341
|
+
# Substring fallback for partial fragments (e.g., "proto") if BM25 returned nothing
|
|
342
|
+
if not all_matches and query.strip():
|
|
201
343
|
q_lower = query.strip().lower()
|
|
344
|
+
word_pat = re.compile(rf"(?<![a-z0-9]){re.escape(q_lower)}(?![a-z0-9])")
|
|
202
345
|
fallback = []
|
|
203
346
|
for entry in skills:
|
|
204
|
-
|
|
347
|
+
entry_cat = entry.get("category", "General & Utility Skills")
|
|
348
|
+
if category and entry_cat.lower() != category.lower():
|
|
205
349
|
continue
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
350
|
+
name_l = entry.get("name", "").lower()
|
|
351
|
+
aliases_l = [a.lower() for a in entry.get("aliases", [entry.get("name", "")])]
|
|
352
|
+
desc_l = entry.get("description", "").lower()
|
|
353
|
+
cat_l = entry_cat.lower()
|
|
354
|
+
|
|
355
|
+
if q_lower == name_l or q_lower in aliases_l:
|
|
356
|
+
score = 10.0
|
|
357
|
+
elif q_lower in name_l or any(q_lower in a for a in aliases_l):
|
|
358
|
+
score = 5.0
|
|
359
|
+
elif word_pat.search(desc_l):
|
|
360
|
+
score = 2.0
|
|
361
|
+
elif q_lower in desc_l or q_lower in cat_l:
|
|
362
|
+
score = 1.0
|
|
363
|
+
else:
|
|
364
|
+
continue
|
|
365
|
+
|
|
366
|
+
fallback.append({
|
|
367
|
+
"name": entry["name"],
|
|
368
|
+
"category": entry_cat,
|
|
369
|
+
"score": score,
|
|
370
|
+
"description": entry.get("description", ""),
|
|
371
|
+
"companion_files": entry.get("companion_files", []),
|
|
372
|
+
})
|
|
373
|
+
fallback.sort(key=lambda m: (-m["score"], m["name"].lower()))
|
|
374
|
+
all_matches = fallback
|
|
375
|
+
|
|
376
|
+
total_matches = len(all_matches)
|
|
377
|
+
matches = all_matches[offset : offset + limit]
|
|
219
378
|
|
|
220
379
|
payload = {
|
|
221
380
|
"query": query,
|
|
381
|
+
"total_matches": total_matches,
|
|
382
|
+
"offset": offset,
|
|
222
383
|
"count": len(matches),
|
|
223
384
|
"results": [
|
|
224
385
|
{
|
|
@@ -405,6 +566,8 @@ def _dispatch_request(msg, base_dir, archive_dir):
|
|
|
405
566
|
args = params.get("arguments") or {}
|
|
406
567
|
if tool_name == "search_skills":
|
|
407
568
|
res = _handle_search_skills(args, base_dir, archive_dir)
|
|
569
|
+
elif tool_name == "list_skills":
|
|
570
|
+
res = _handle_list_skills(args, base_dir, archive_dir)
|
|
408
571
|
elif tool_name == "load_skill":
|
|
409
572
|
res = _handle_load_skill(args, base_dir, archive_dir)
|
|
410
573
|
else:
|
package/scripts/skill_router.py
CHANGED
|
@@ -120,6 +120,7 @@ STOPWORDS = {
|
|
|
120
120
|
SHORT_DOMAIN_TOKENS = {
|
|
121
121
|
"ai", "ml", "db", "ui", "ux", "ci", "cd", "qa", "tf", "go",
|
|
122
122
|
"ik", "js", "ts", "py", "bq", "vm", "os", "io", "ip", "pr",
|
|
123
|
+
"uv",
|
|
123
124
|
}
|
|
124
125
|
|
|
125
126
|
# Broad tech terms that should not trigger skill injection on their own as a solo 1-token query
|
|
@@ -221,8 +222,10 @@ def tokenize(text, include_stems=True):
|
|
|
221
222
|
|
|
222
223
|
|
|
223
224
|
def canonicalize_skill_name(name):
|
|
224
|
-
"""Return canonical deduplication key normalizing case and
|
|
225
|
-
|
|
225
|
+
"""Return canonical deduplication key normalizing case and separator differences (-, _, ., spaces)."""
|
|
226
|
+
raw = str(name or "").strip().lower()
|
|
227
|
+
alnum = re.sub(r"[^a-z0-9]+", "", raw)
|
|
228
|
+
return alnum or raw
|
|
226
229
|
|
|
227
230
|
|
|
228
231
|
def _parse_version_tuple(ver_str):
|
|
@@ -233,6 +236,22 @@ def _parse_version_tuple(ver_str):
|
|
|
233
236
|
return tuple(int(n) for n in nums) if nums else None
|
|
234
237
|
|
|
235
238
|
|
|
239
|
+
def _compare_version_tuples(ver_a, ver_b):
|
|
240
|
+
"""Compare two version tuples with zero-padding. Returns 1, -1, or 0."""
|
|
241
|
+
if ver_a is None or ver_b is None:
|
|
242
|
+
return 0
|
|
243
|
+
ta = tuple(ver_a)
|
|
244
|
+
tb = tuple(ver_b)
|
|
245
|
+
max_len = max(len(ta), len(tb))
|
|
246
|
+
pa = ta + (0,) * (max_len - len(ta))
|
|
247
|
+
pb = tb + (0,) * (max_len - len(tb))
|
|
248
|
+
if pa > pb:
|
|
249
|
+
return 1
|
|
250
|
+
if pa < pb:
|
|
251
|
+
return -1
|
|
252
|
+
return 0
|
|
253
|
+
|
|
254
|
+
|
|
236
255
|
def _parse_frontmatter(content):
|
|
237
256
|
"""Parse YAML frontmatter fields from SKILL.md without external YAML dependencies."""
|
|
238
257
|
fm_match = re.match(r"^---\s*\n(.*?)\n---(?:\s*\n|\s*\Z)", content, re.DOTALL)
|
|
@@ -246,6 +265,8 @@ def _parse_frontmatter(content):
|
|
|
246
265
|
# Scalar fields
|
|
247
266
|
for field in ("name", "version", "category"):
|
|
248
267
|
m = re.search(rf"^{field}:\s*([^\n]+)", fm_text, re.MULTILINE | re.IGNORECASE)
|
|
268
|
+
if not m and field == "version":
|
|
269
|
+
m = re.search(r"^[ \t]+version:\s*([^\n]+)", fm_text, re.MULTILINE | re.IGNORECASE)
|
|
249
270
|
if m:
|
|
250
271
|
val = m.group(1).strip().strip("'\"")
|
|
251
272
|
if val:
|
|
@@ -414,24 +435,25 @@ def _is_newer_entry(cand, existing):
|
|
|
414
435
|
"""Return True if cand entry is strictly newer/preferred over existing entry."""
|
|
415
436
|
va = cand.get("version_tuple")
|
|
416
437
|
vb = existing.get("version_tuple")
|
|
417
|
-
if va is not None and vb is not None
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
if va is None and vb is not None:
|
|
422
|
-
return False
|
|
438
|
+
if va is not None and vb is not None:
|
|
439
|
+
vcmp = _compare_version_tuples(va, vb)
|
|
440
|
+
if vcmp != 0:
|
|
441
|
+
return vcmp > 0
|
|
423
442
|
|
|
424
443
|
ma = cand.get("mtime", 0.0)
|
|
425
444
|
mb = existing.get("mtime", 0.0)
|
|
426
445
|
if abs(ma - mb) > 1.0:
|
|
427
446
|
return ma > mb
|
|
428
447
|
|
|
448
|
+
if (va is not None) != (vb is not None):
|
|
449
|
+
return va is not None
|
|
450
|
+
|
|
429
451
|
# Tie-breaker: prefer hyphenated names over underscored names
|
|
430
452
|
cand_hyphen = "-" in cand["name"] and "_" not in cand["name"]
|
|
431
453
|
exist_hyphen = "-" in existing["name"] and "_" not in existing["name"]
|
|
432
454
|
if cand_hyphen != exist_hyphen:
|
|
433
455
|
return cand_hyphen
|
|
434
|
-
return cand["name"] < existing["name"]
|
|
456
|
+
return cand["name"].lower() < existing["name"].lower()
|
|
435
457
|
|
|
436
458
|
|
|
437
459
|
def _resolve_archived_skill_dir(base_dir, archive_dir, raw_archived_path):
|
|
@@ -548,7 +570,11 @@ def load_or_build_index(archive_dir, base_dir=None, resolve_path_fn=None):
|
|
|
548
570
|
data = json.load(f)
|
|
549
571
|
if (
|
|
550
572
|
isinstance(data, dict)
|
|
551
|
-
and data.get("schema_version")
|
|
573
|
+
and isinstance(data.get("schema_version"), int)
|
|
574
|
+
and data.get("schema_version") >= INDEX_SCHEMA_VERSION
|
|
575
|
+
and isinstance(data.get("skills"), list)
|
|
576
|
+
and isinstance(data.get("df"), dict)
|
|
577
|
+
and isinstance(data.get("avg_len"), dict)
|
|
552
578
|
and float(data.get("manifest_mtime", 0.0)) >= manifest_mtime - 0.5
|
|
553
579
|
):
|
|
554
580
|
return data
|
|
@@ -608,7 +634,7 @@ def search_index(
|
|
|
608
634
|
# Extract distinct semantic concepts without summing base + stem duplicates
|
|
609
635
|
concept_tokens = list(dict.fromkeys(tokenize(query, include_stems=False)))
|
|
610
636
|
|
|
611
|
-
if not
|
|
637
|
+
if not raw_query and not category:
|
|
612
638
|
return []
|
|
613
639
|
|
|
614
640
|
specific_concepts = [
|
|
@@ -629,7 +655,7 @@ def search_index(
|
|
|
629
655
|
if category and entry_cat.lower() != category.strip().lower():
|
|
630
656
|
continue
|
|
631
657
|
|
|
632
|
-
if not
|
|
658
|
+
if not raw_query and category:
|
|
633
659
|
results.append({
|
|
634
660
|
"name": entry["name"],
|
|
635
661
|
"canonical_key": ckey,
|
|
@@ -736,15 +762,17 @@ def search_index(
|
|
|
736
762
|
for alias in entry.get("aliases", [entry["name"]]):
|
|
737
763
|
alias_l = alias.lower()
|
|
738
764
|
alias_spaces = re.sub(r"[-_]+", " ", alias_l)
|
|
739
|
-
if (
|
|
740
|
-
|
|
741
|
-
and (
|
|
765
|
+
if len(alias_l) >= 4:
|
|
766
|
+
if (
|
|
742
767
|
re.search(rf"(?<![a-z0-9]){re.escape(alias_l)}(?![a-z0-9])", raw_query)
|
|
743
768
|
or re.search(rf"(?<![a-z0-9]){re.escape(alias_spaces)}(?![a-z0-9])", raw_query_norm)
|
|
744
|
-
)
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
769
|
+
):
|
|
770
|
+
exact_name_hit = True
|
|
771
|
+
break
|
|
772
|
+
elif len(alias_l) >= 2 and alias_l not in STOPWORDS:
|
|
773
|
+
if raw_query == alias_l or raw_query_norm == alias_spaces:
|
|
774
|
+
exact_name_hit = True
|
|
775
|
+
break
|
|
748
776
|
|
|
749
777
|
if exact_name_hit:
|
|
750
778
|
bm25_score += 10.0
|
package/scripts/skill_vault.py
CHANGED
|
@@ -7,6 +7,7 @@ strictly in backup_manifest.json and INDEX.md, keeping SKILL.md files pure and u
|
|
|
7
7
|
"""
|
|
8
8
|
|
|
9
9
|
import argparse
|
|
10
|
+
from datetime import datetime
|
|
10
11
|
import fnmatch
|
|
11
12
|
import hashlib
|
|
12
13
|
import json
|
|
@@ -387,6 +388,22 @@ def parse_version_tuple(ver_str):
|
|
|
387
388
|
return None
|
|
388
389
|
|
|
389
390
|
|
|
391
|
+
def compare_version_tuples(ver_a, ver_b):
|
|
392
|
+
"""Compare two version tuples with zero-padding. Returns 1, -1, or 0."""
|
|
393
|
+
if ver_a is None or ver_b is None:
|
|
394
|
+
return 0
|
|
395
|
+
ta = tuple(ver_a)
|
|
396
|
+
tb = tuple(ver_b)
|
|
397
|
+
max_len = max(len(ta), len(tb))
|
|
398
|
+
pa = ta + (0,) * (max_len - len(ta))
|
|
399
|
+
pb = tb + (0,) * (max_len - len(tb))
|
|
400
|
+
if pa > pb:
|
|
401
|
+
return 1
|
|
402
|
+
if pa < pb:
|
|
403
|
+
return -1
|
|
404
|
+
return 0
|
|
405
|
+
|
|
406
|
+
|
|
390
407
|
def get_skill_metadata(skill_dir):
|
|
391
408
|
"""Extract parsed version and latest modification timestamp for a skill directory."""
|
|
392
409
|
skill_dir = Path(skill_dir)
|
|
@@ -396,9 +413,12 @@ def get_skill_metadata(skill_dir):
|
|
|
396
413
|
if skill_md.exists():
|
|
397
414
|
try:
|
|
398
415
|
content = skill_md.read_text(encoding="utf-8", errors="ignore")
|
|
399
|
-
fm_match = re.
|
|
416
|
+
fm_match = re.match(r"^---\s*\n(.*?)\n---(?:\s*\n|\s*\Z)", content, re.DOTALL)
|
|
400
417
|
if fm_match:
|
|
401
|
-
|
|
418
|
+
fm_text = fm_match.group(1)
|
|
419
|
+
v_match = re.search(r"^version:\s*([^\n]+)", fm_text, re.MULTILINE | re.IGNORECASE)
|
|
420
|
+
if not v_match:
|
|
421
|
+
v_match = re.search(r"^[ \t]+version:\s*([^\n]+)", fm_text, re.MULTILINE | re.IGNORECASE)
|
|
402
422
|
if v_match:
|
|
403
423
|
ver_tuple = parse_version_tuple(v_match.group(1))
|
|
404
424
|
except Exception:
|
|
@@ -432,17 +452,28 @@ def compare_skill_recency(dir_a, dir_b):
|
|
|
432
452
|
-1 if dir_b is newer than dir_a
|
|
433
453
|
0 if they are equivalent in version and recency
|
|
434
454
|
"""
|
|
455
|
+
a_exists = (Path(dir_a) / "SKILL.md").exists()
|
|
456
|
+
b_exists = (Path(dir_b) / "SKILL.md").exists()
|
|
457
|
+
if a_exists != b_exists:
|
|
458
|
+
return 1 if a_exists else -1
|
|
459
|
+
|
|
435
460
|
ver_a, mtime_a = get_skill_metadata(dir_a)
|
|
436
461
|
ver_b, mtime_b = get_skill_metadata(dir_b)
|
|
437
462
|
|
|
438
463
|
# 1. Compare semantic/numeric versions if both exist and differ
|
|
439
|
-
if ver_a is not None and ver_b is not None
|
|
440
|
-
|
|
464
|
+
if ver_a is not None and ver_b is not None:
|
|
465
|
+
vcmp = compare_version_tuples(ver_a, ver_b)
|
|
466
|
+
if vcmp != 0:
|
|
467
|
+
return vcmp
|
|
441
468
|
|
|
442
469
|
# 2. Compare file modification timestamps (allowing a 1-second margin for filesystem granularity)
|
|
443
470
|
if abs(mtime_a - mtime_b) > 1.0:
|
|
444
471
|
return 1 if mtime_a > mtime_b else -1
|
|
445
472
|
|
|
473
|
+
# 3. Tie-breaker when timestamps match: prefer an explicitly versioned skill
|
|
474
|
+
if (ver_a is not None) != (ver_b is not None):
|
|
475
|
+
return 1 if ver_a is not None else -1
|
|
476
|
+
|
|
446
477
|
return 0
|
|
447
478
|
|
|
448
479
|
|
|
@@ -1956,7 +1987,7 @@ class SkillVault:
|
|
|
1956
1987
|
return (
|
|
1957
1988
|
"Universal agent-agnostic skill router and tiered storage manager. "
|
|
1958
1989
|
"Background hooks automatically inject relevant vaulted skills on demand; "
|
|
1959
|
-
"use MCP tools search_skills/load_skill for mid-turn lookups."
|
|
1990
|
+
"use MCP tools list_skills/search_skills/load_skill for mid-turn lookups."
|
|
1960
1991
|
)
|
|
1961
1992
|
|
|
1962
1993
|
def build_router_description(self):
|
|
@@ -2466,51 +2497,174 @@ class SkillVault:
|
|
|
2466
2497
|
print("")
|
|
2467
2498
|
return 0
|
|
2468
2499
|
|
|
2500
|
+
@staticmethod
|
|
2501
|
+
def _inspect_dedupe_entry(idx, item, dir_path):
|
|
2502
|
+
"""Extract canonical name, frontmatter alias, content hash, and recency metadata for dedupe."""
|
|
2503
|
+
canon_name = skill_router.canonicalize_skill_name(item.get("name", ""))
|
|
2504
|
+
fm_canon_name = None
|
|
2505
|
+
content_hash = None
|
|
2506
|
+
size_bytes = 0
|
|
2507
|
+
skill_md = dir_path / "SKILL.md"
|
|
2508
|
+
if skill_md.exists():
|
|
2509
|
+
try:
|
|
2510
|
+
raw_bytes = skill_md.read_bytes()
|
|
2511
|
+
size_bytes = len(raw_bytes)
|
|
2512
|
+
if size_bytes >= 64:
|
|
2513
|
+
content_hash = hashlib.sha256(raw_bytes).hexdigest()
|
|
2514
|
+
content = raw_bytes.decode("utf-8", errors="ignore")
|
|
2515
|
+
fm_match = re.match(r"^---\s*\n(.*?)\n---(?:\s*\n|\s*\Z)", content, re.DOTALL)
|
|
2516
|
+
if fm_match:
|
|
2517
|
+
n_match = re.search(r"^name:\s*([^\n]+)", fm_match.group(1), re.MULTILINE | re.IGNORECASE)
|
|
2518
|
+
if n_match:
|
|
2519
|
+
fm_raw = n_match.group(1).strip().strip("'\"")
|
|
2520
|
+
if fm_raw:
|
|
2521
|
+
fm_canon_name = skill_router.canonicalize_skill_name(fm_raw) or None
|
|
2522
|
+
except OSError:
|
|
2523
|
+
pass
|
|
2524
|
+
ver_tuple, mtime = get_skill_metadata(dir_path)
|
|
2525
|
+
return {
|
|
2526
|
+
"idx": idx,
|
|
2527
|
+
"item": item,
|
|
2528
|
+
"dir_path": dir_path,
|
|
2529
|
+
"canon_name": canon_name,
|
|
2530
|
+
"fm_canon_name": fm_canon_name,
|
|
2531
|
+
"content_hash": content_hash,
|
|
2532
|
+
"size_bytes": size_bytes,
|
|
2533
|
+
"ver_tuple": ver_tuple,
|
|
2534
|
+
"mtime": mtime,
|
|
2535
|
+
}
|
|
2536
|
+
|
|
2537
|
+
@staticmethod
|
|
2538
|
+
def _dedupe_candidate_beats(cand_info, win_info):
|
|
2539
|
+
"""Return True if cand_info is newer or preferred over win_info."""
|
|
2540
|
+
rec = compare_skill_recency(cand_info["dir_path"], win_info["dir_path"])
|
|
2541
|
+
if rec != 0:
|
|
2542
|
+
return rec > 0
|
|
2543
|
+
cand_name = cand_info["item"]["name"]
|
|
2544
|
+
win_name = win_info["item"]["name"]
|
|
2545
|
+
cand_hyphen = "-" in cand_name and "_" not in cand_name
|
|
2546
|
+
win_hyphen = "-" in win_name and "_" not in win_name
|
|
2547
|
+
if cand_hyphen != win_hyphen:
|
|
2548
|
+
return cand_hyphen
|
|
2549
|
+
if cand_info["size_bytes"] != win_info["size_bytes"]:
|
|
2550
|
+
return cand_info["size_bytes"] > win_info["size_bytes"]
|
|
2551
|
+
return cand_name.lower() < win_name.lower()
|
|
2552
|
+
|
|
2553
|
+
@staticmethod
|
|
2554
|
+
def _format_dedupe_meta(info):
|
|
2555
|
+
ver_str = ".".join(map(str, info["ver_tuple"])) if info["ver_tuple"] is not None else "none"
|
|
2556
|
+
mtime_str = (
|
|
2557
|
+
datetime.fromtimestamp(info["mtime"]).strftime("%Y-%m-%d %H:%M")
|
|
2558
|
+
if info["mtime"] > 0
|
|
2559
|
+
else "unknown"
|
|
2560
|
+
)
|
|
2561
|
+
return f"[ver={ver_str}, mtime={mtime_str}]"
|
|
2562
|
+
|
|
2469
2563
|
def dedupe(self, dry_run=False):
|
|
2470
|
-
"""Consolidate
|
|
2564
|
+
"""Consolidate duplicate skills in L2 (canonical name, frontmatter name, or identical content), keeping the newest version."""
|
|
2471
2565
|
manifest = self.load_manifest()
|
|
2472
|
-
|
|
2473
|
-
|
|
2474
|
-
|
|
2475
|
-
|
|
2566
|
+
infos = [
|
|
2567
|
+
self._inspect_dedupe_entry(i, item, self.resolve_portable_path(item.get("archived_path", "")))
|
|
2568
|
+
for i, item in enumerate(manifest)
|
|
2569
|
+
]
|
|
2476
2570
|
|
|
2477
|
-
|
|
2571
|
+
# Union-Find over manifest entries sharing canonical name, frontmatter name, or SKILL.md SHA-256
|
|
2572
|
+
parent = list(range(len(infos)))
|
|
2573
|
+
|
|
2574
|
+
def _find(x):
|
|
2575
|
+
while parent[x] != x:
|
|
2576
|
+
parent[x] = parent[parent[x]]
|
|
2577
|
+
x = parent[x]
|
|
2578
|
+
return x
|
|
2579
|
+
|
|
2580
|
+
def _union(a, b):
|
|
2581
|
+
ra, rb = _find(a), _find(b)
|
|
2582
|
+
if ra != rb:
|
|
2583
|
+
parent[rb] = ra
|
|
2584
|
+
|
|
2585
|
+
buckets = {}
|
|
2586
|
+
for info in infos:
|
|
2587
|
+
idx = info["idx"]
|
|
2588
|
+
keys = []
|
|
2589
|
+
if info["canon_name"]:
|
|
2590
|
+
keys.append(("name", info["canon_name"]))
|
|
2591
|
+
if info["fm_canon_name"]:
|
|
2592
|
+
keys.append(("name", info["fm_canon_name"]))
|
|
2593
|
+
if info["content_hash"]:
|
|
2594
|
+
keys.append(("sha256", info["content_hash"]))
|
|
2595
|
+
for key in keys:
|
|
2596
|
+
buckets.setdefault(key, []).append(idx)
|
|
2597
|
+
|
|
2598
|
+
for key_indices in buckets.values():
|
|
2599
|
+
if len(key_indices) > 1:
|
|
2600
|
+
head = key_indices[0]
|
|
2601
|
+
for other in key_indices[1:]:
|
|
2602
|
+
_union(head, other)
|
|
2603
|
+
|
|
2604
|
+
components = {}
|
|
2605
|
+
for info in infos:
|
|
2606
|
+
components.setdefault(_find(info["idx"]), []).append(info)
|
|
2607
|
+
|
|
2608
|
+
dup_components = [grp for grp in components.values() if len(grp) > 1]
|
|
2478
2609
|
print("==================================================")
|
|
2479
2610
|
print(" SKILL VAULT DUPLICATE CHECK")
|
|
2480
2611
|
print(f" Total Manifest Entries: {len(manifest)}")
|
|
2481
|
-
print(f" Duplicate Groups Found: {len(
|
|
2612
|
+
print(f" Duplicate Groups Found: {len(dup_components)}")
|
|
2482
2613
|
print("==================================================\n")
|
|
2483
2614
|
|
|
2484
|
-
if not
|
|
2485
|
-
print("[OK] No duplicate
|
|
2615
|
+
if not dup_components:
|
|
2616
|
+
print("[OK] No duplicate skills found in vault.")
|
|
2486
2617
|
return 0
|
|
2487
2618
|
|
|
2488
2619
|
to_remove = []
|
|
2489
|
-
kept_entries =
|
|
2490
|
-
|
|
2491
|
-
|
|
2492
|
-
|
|
2620
|
+
kept_entries = []
|
|
2621
|
+
prepared_groups = []
|
|
2622
|
+
for grp in components.values():
|
|
2623
|
+
if len(grp) == 1:
|
|
2624
|
+
kept_entries.append(grp[0]["item"])
|
|
2493
2625
|
continue
|
|
2494
2626
|
|
|
2495
|
-
|
|
2496
|
-
|
|
2497
|
-
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
|
|
2506
|
-
|
|
2507
|
-
|
|
2508
|
-
|
|
2509
|
-
|
|
2510
|
-
|
|
2511
|
-
|
|
2512
|
-
|
|
2513
|
-
|
|
2627
|
+
win_info = grp[0]
|
|
2628
|
+
for cand_info in grp[1:]:
|
|
2629
|
+
if self._dedupe_candidate_beats(cand_info, win_info):
|
|
2630
|
+
win_info = cand_info
|
|
2631
|
+
kept_entries.append(win_info["item"])
|
|
2632
|
+
|
|
2633
|
+
reasons = set()
|
|
2634
|
+
for i in range(len(grp)):
|
|
2635
|
+
for j in range(i + 1, len(grp)):
|
|
2636
|
+
a, b = grp[i], grp[j]
|
|
2637
|
+
if a["canon_name"] and a["canon_name"] == b["canon_name"]:
|
|
2638
|
+
reasons.add("canonical-name")
|
|
2639
|
+
else:
|
|
2640
|
+
a_names = {n for n in (a["canon_name"], a["fm_canon_name"]) if n}
|
|
2641
|
+
b_names = {n for n in (b["canon_name"], b["fm_canon_name"]) if n}
|
|
2642
|
+
if a_names & b_names:
|
|
2643
|
+
reasons.add("frontmatter-name")
|
|
2644
|
+
if a["content_hash"] and a["content_hash"] == b["content_hash"]:
|
|
2645
|
+
reasons.add("identical-content")
|
|
2646
|
+
|
|
2647
|
+
group_label = win_info["canon_name"] or win_info["item"]["name"]
|
|
2648
|
+
losers = [c for c in grp if c["idx"] != win_info["idx"]]
|
|
2649
|
+
losers.sort(key=lambda c: c["item"]["name"].lower())
|
|
2650
|
+
prepared_groups.append((group_label, sorted(reasons), win_info, losers))
|
|
2651
|
+
|
|
2652
|
+
prepared_groups.sort(key=lambda g: g[0].lower())
|
|
2653
|
+
for group_label, reasons, win_info, losers in prepared_groups:
|
|
2654
|
+
reasons_str = ", ".join(reasons) if reasons else "canonical-name"
|
|
2655
|
+
print(f"Group '{group_label}' (matched by: {reasons_str}):")
|
|
2656
|
+
win_item = win_info["item"]
|
|
2657
|
+
print(
|
|
2658
|
+
f" [KEEP] {win_item['name']} ({win_item.get('category', 'General & Utility Skills')}) "
|
|
2659
|
+
f"{self._format_dedupe_meta(win_info)} -> {win_info['dir_path']}"
|
|
2660
|
+
)
|
|
2661
|
+
for cand_info in losers:
|
|
2662
|
+
cand_item = cand_info["item"]
|
|
2663
|
+
print(
|
|
2664
|
+
f" [REMOVE] {cand_item['name']} ({cand_item.get('category', 'General & Utility Skills')}) "
|
|
2665
|
+
f"{self._format_dedupe_meta(cand_info)} -> {cand_info['dir_path']}"
|
|
2666
|
+
)
|
|
2667
|
+
to_remove.append((cand_item, cand_info["dir_path"], win_info["dir_path"]))
|
|
2514
2668
|
|
|
2515
2669
|
if dry_run:
|
|
2516
2670
|
print(f"\n[Dry Run] Would consolidate {len(to_remove)} duplicate skill(s). No files were modified.")
|
|
@@ -2521,7 +2675,7 @@ class SkillVault:
|
|
|
2521
2675
|
shutil.rmtree(cand_dir)
|
|
2522
2676
|
print(f"[Removed] {cand_dir}")
|
|
2523
2677
|
|
|
2524
|
-
self.save_manifest(
|
|
2678
|
+
self.save_manifest(kept_entries)
|
|
2525
2679
|
self.reindex()
|
|
2526
2680
|
print(f"\n[OK] Consolidated {len(to_remove)} duplicate skill(s).")
|
|
2527
2681
|
return 0
|
|
@@ -2832,7 +2986,7 @@ class SkillVault:
|
|
|
2832
2986
|
plugin_meta = {
|
|
2833
2987
|
"name": "skill-vault",
|
|
2834
2988
|
"displayName": "Skill Vault",
|
|
2835
|
-
"version": "2.0.
|
|
2989
|
+
"version": "2.0.1",
|
|
2836
2990
|
"description": "Automatic background skill router, cold-storage archive, and read-only JIT MCP server.",
|
|
2837
2991
|
"author": "jcorpac",
|
|
2838
2992
|
"license": "MIT",
|
|
@@ -3239,7 +3393,10 @@ def main():
|
|
|
3239
3393
|
p_route.add_argument("--json", action="store_true", help="Output structured JSON")
|
|
3240
3394
|
|
|
3241
3395
|
# Dedupe
|
|
3242
|
-
p_dedupe = subparsers.add_parser(
|
|
3396
|
+
p_dedupe = subparsers.add_parser(
|
|
3397
|
+
"dedupe",
|
|
3398
|
+
help="Consolidate duplicate skills in archive (canonical name, frontmatter name, or identical content), keeping the newest version",
|
|
3399
|
+
)
|
|
3243
3400
|
p_dedupe.add_argument("--dry-run", action="store_true", help="Preview duplicates without deleting files")
|
|
3244
3401
|
|
|
3245
3402
|
# Stats
|