@jcorpac/skill-vault 1.8.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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@jcorpac/skill-vault",
3
- "version": "1.8.0",
4
- "description": "Universal Agent Skill Router, Lifecycle Manager, and Tiered Storage Engine for AI Coding Agents.",
3
+ "version": "2.0.1",
4
+ "description": "Automatic Background Skill Router, Lifecycle Manager & Tiered Storage Engine for AI Coding Agents.",
5
5
  "main": "bin/cli.js",
6
6
  "bin": {
7
7
  "skill-vault": "bin/cli.js",
@@ -9,7 +9,10 @@
9
9
  },
10
10
  "files": [
11
11
  "bin/",
12
- "scripts/skill_vault.py",
12
+ "scripts/*.py",
13
+ "plugin.json",
14
+ "hooks.json",
15
+ "mcp_config.json",
13
16
  "SKILL.md",
14
17
  "README.md",
15
18
  "LICENSE"
@@ -23,9 +26,11 @@
23
26
  "ai-agents",
24
27
  "antigravity",
25
28
  "claude-code",
29
+ "gemini-cli",
26
30
  "cursor",
27
31
  "skill-router",
28
32
  "skill-vault",
33
+ "mcp",
29
34
  "context-optimization",
30
35
  "llm-tools"
31
36
  ],
package/plugin.json ADDED
@@ -0,0 +1,10 @@
1
+ {
2
+ "name": "skill-vault",
3
+ "displayName": "Skill Vault",
4
+ "version": "2.0.1",
5
+ "description": "Automatic background skill router, cold-storage archive, and read-only JIT MCP server for AI coding agents.",
6
+ "author": "jcorpac",
7
+ "homepage": "https://github.com/jcorpac/skill-vault#readme",
8
+ "repository": "https://github.com/jcorpac/skill-vault",
9
+ "license": "MIT"
10
+ }
@@ -0,0 +1,488 @@
1
+ #!/usr/bin/env python3
2
+ """Skill Vault Background Hook Runner (Antigravity, Claude Code, Gemini CLI).
3
+
4
+ Executes silently at SessionStart and PreInvocation / UserPromptSubmit / BeforeAgent
5
+ to maintain the L2 archive index and inject relevant skills just-in-time with zero
6
+ user approvals. Strictly fails safe (always exits 0 with valid JSON on stdout).
7
+ """
8
+
9
+ import argparse
10
+ import contextlib
11
+ import hashlib
12
+ import io
13
+ import json
14
+ import os
15
+ from pathlib import Path
16
+ import sys
17
+ import time
18
+
19
+ SCRIPT_DIR = Path(__file__).resolve().parent
20
+ if str(SCRIPT_DIR) not in sys.path:
21
+ sys.path.insert(0, str(SCRIPT_DIR))
22
+
23
+ import skill_router # noqa: E402
24
+
25
+
26
+ def _configure_stdio():
27
+ for stream_name in ("stdin", "stdout", "stderr"):
28
+ stream = getattr(sys, stream_name, None)
29
+ if stream is not None and hasattr(stream, "reconfigure"):
30
+ try:
31
+ stream.reconfigure(encoding="utf-8", errors="replace")
32
+ except Exception:
33
+ pass
34
+
35
+
36
+ def _resolve_base_and_archive(cli_base=None, workspace_paths=None):
37
+ """Resolve Skill Vault base_dir and archive_dir without heavy imports."""
38
+ if cli_base:
39
+ p = Path(cli_base).resolve()
40
+ return p, p / "skill_archive"
41
+
42
+ for env_key in ("SKILL_VAULT_BASE", "SKILL_BASE_DIR", "AGENTS_HOME"):
43
+ val = os.environ.get(env_key)
44
+ if val:
45
+ p = Path(val).resolve()
46
+ return p, p / "skill_archive"
47
+
48
+ candidates = []
49
+
50
+ plugin_data = os.environ.get("PLUGIN_DATA")
51
+ if plugin_data:
52
+ candidates.append(Path(plugin_data).resolve())
53
+
54
+ # Installed plugin link file written by `skill-vault setup`
55
+ vault_link = SCRIPT_DIR.parent / "vault_link.json"
56
+ if vault_link.exists():
57
+ try:
58
+ link_data = json.loads(vault_link.read_text(encoding="utf-8"))
59
+ if isinstance(link_data, dict) and link_data.get("baseDir"):
60
+ candidates.append(Path(link_data["baseDir"]).resolve())
61
+ except Exception:
62
+ pass
63
+
64
+ # Check script ancestors (e.g. ~/.gemini/config/plugins/skill-vault/scripts/hook_runner.py -> ~/.gemini/config)
65
+ for parent in Path(__file__).resolve().parents:
66
+ if parent.name != "skill_archive" and (parent / "skill_archive").exists():
67
+ candidates.append(parent)
68
+
69
+ # Check workspace roots for workspace-scoped archives
70
+ for ws in workspace_paths or []:
71
+ if not ws:
72
+ continue
73
+ wsp = Path(ws).resolve()
74
+ for sub in (wsp / ".agents", wsp, wsp / ".claude", wsp / ".gemini", wsp / ".cursor"):
75
+ if (sub / "skill_archive").exists():
76
+ candidates.append(sub)
77
+
78
+ home = Path.home()
79
+ candidates.extend([
80
+ home / ".gemini" / "config",
81
+ home / ".gemini" / "config" / "skills" / "skill-vault",
82
+ home / ".agents",
83
+ home / ".claude",
84
+ home / ".gemini",
85
+ home / ".cursor",
86
+ ])
87
+
88
+ for cand in candidates:
89
+ arch = cand / "skill_archive"
90
+ if arch.exists() and (
91
+ (arch / "backup_manifest.json").exists()
92
+ or (arch / "search_index.json").exists()
93
+ or (arch / "skills").exists()
94
+ ):
95
+ return cand, arch
96
+
97
+ # Fallback to first valid candidate or ~/.gemini/config
98
+ for cand in candidates:
99
+ if cand.exists():
100
+ return cand, cand / "skill_archive"
101
+
102
+ fallback = home / ".gemini" / "config"
103
+ return fallback, fallback / "skill_archive"
104
+
105
+
106
+ def _load_routing_config(archive_dir):
107
+ """Read routing settings from vault_config.json merged with defaults."""
108
+ cfg = dict(skill_router.DEFAULT_ROUTING_CONFIG)
109
+ cfg_file = Path(archive_dir) / "vault_config.json"
110
+ if cfg_file.exists():
111
+ try:
112
+ with open(cfg_file, "r", encoding="utf-8") as f:
113
+ data = json.load(f)
114
+ if isinstance(data, dict) and isinstance(data.get("routing"), dict):
115
+ cfg.update(data["routing"])
116
+ except Exception:
117
+ pass
118
+ return cfg
119
+
120
+
121
+ def _detect_harness(requested_harness, payload, cli_event):
122
+ if requested_harness and requested_harness != "auto":
123
+ return requested_harness
124
+
125
+ antigravity_events = {
126
+ "SessionStart", "PreInvocation", "PostInvocation",
127
+ "PreToolUse", "PostToolUse", "Stop",
128
+ }
129
+ if payload.get("hookEventName") in antigravity_events:
130
+ return "antigravity"
131
+ if any(k in payload for k in ("lastUserInput", "conversationId", "workspacePaths", "invocationNum")):
132
+ return "antigravity"
133
+ if cli_event == "PreInvocation":
134
+ return "antigravity"
135
+
136
+ hook_evt = payload.get("hook_event_name") or cli_event or ""
137
+ if hook_evt == "BeforeAgent":
138
+ return "gemini-cli"
139
+ if hook_evt == "UserPromptSubmit" or ("session_id" in payload and "prompt" in payload):
140
+ return "claude"
141
+
142
+ return "antigravity"
143
+
144
+
145
+ def _detect_event(cli_event, payload):
146
+ if cli_event:
147
+ return cli_event
148
+ return payload.get("hookEventName") or payload.get("hook_event_name") or "PreInvocation"
149
+
150
+
151
+ def _fast_active_skill_names(base_dir, workspace_paths=None):
152
+ """Quickly collect active L1 skill folder names without reading SKILL.md files."""
153
+ names = set()
154
+ roots = [Path(base_dir)]
155
+ for ws in workspace_paths or []:
156
+ if ws:
157
+ wsp = Path(ws).resolve()
158
+ if wsp not in roots:
159
+ roots.append(wsp)
160
+
161
+ for root in roots:
162
+ for sub in ("skills", ".agents/skills", ".claude/skills"):
163
+ sdir = root / sub
164
+ if sdir.exists() and sdir.is_dir():
165
+ try:
166
+ for item in sdir.iterdir():
167
+ if item.is_dir() and (item / "SKILL.md").exists():
168
+ names.add(item.name)
169
+ except OSError:
170
+ pass
171
+ plugins_dir = root / "plugins"
172
+ if plugins_dir.exists() and plugins_dir.is_dir():
173
+ try:
174
+ for plug in plugins_dir.iterdir():
175
+ pskills = plug / "skills"
176
+ if pskills.exists() and pskills.is_dir():
177
+ for item in pskills.iterdir():
178
+ if item.is_dir() and (item / "SKILL.md").exists():
179
+ names.add(item.name)
180
+ except OSError:
181
+ pass
182
+ return names
183
+
184
+
185
+ def _collect_skill_dirs_snapshot(mgr):
186
+ """Build lightweight mtime snapshot across active and plugin skill directories."""
187
+ snapshot = {}
188
+ hook_protected = set()
189
+ if hasattr(mgr, "get_hook_protected_skills"):
190
+ try:
191
+ hook_protected = mgr.get_hook_protected_skills()
192
+ except Exception:
193
+ hook_protected = set()
194
+
195
+ for sdir in mgr.get_active_skill_dirs():
196
+ sdir_path = Path(sdir)
197
+ if not sdir_path.exists():
198
+ continue
199
+ try:
200
+ if (sdir_path / "SKILL.md").exists():
201
+ snapshot[str(sdir_path / "SKILL.md")] = round((sdir_path / "SKILL.md").stat().st_mtime, 2)
202
+ for item in sdir_path.iterdir():
203
+ if item.is_dir() and (item / "SKILL.md").exists():
204
+ if item.name == "skill-vault" or item.name in hook_protected:
205
+ continue
206
+ snapshot[str(item)] = round((item / "SKILL.md").stat().st_mtime, 2)
207
+ except OSError:
208
+ pass
209
+ return snapshot
210
+
211
+
212
+ def _handle_session_start(base_dir, archive_dir, payload, routing_cfg):
213
+ """Run silent background index check, optional plugin sync, and workspace cache warmup."""
214
+ if not routing_cfg.get("enabled", True):
215
+ return {}
216
+
217
+ workspace_paths = payload.get("workspacePaths") or ([payload["cwd"]] if payload.get("cwd") else [])
218
+
219
+ # Prune old conversation state files
220
+ if archive_dir.exists():
221
+ skill_router.prune_old_states(archive_dir, max_age_days=7)
222
+
223
+ # Import SkillVault only inside SessionStart for sync + workspace fingerprinting
224
+ from skill_vault import SkillVault # noqa: E402
225
+
226
+ sink = io.StringIO()
227
+ with contextlib.redirect_stdout(sink), contextlib.redirect_stderr(sink):
228
+ mgr = SkillVault(base_dir=str(base_dir))
229
+ auto_sync = bool(routing_cfg.get("auto_sync_on_session_start", True))
230
+ auto_prune = bool(routing_cfg.get("auto_prune_on_session_start", True))
231
+
232
+ if auto_sync and archive_dir.exists():
233
+ state_dir = archive_dir / ".state"
234
+ state_dir.mkdir(parents=True, exist_ok=True)
235
+ stamp_file = state_dir / "sync_stamp.json"
236
+
237
+ current_snap = _collect_skill_dirs_snapshot(mgr)
238
+ prev_snap = None
239
+ if stamp_file.exists():
240
+ try:
241
+ prev_snap = json.loads(stamp_file.read_text(encoding="utf-8"))
242
+ except Exception:
243
+ prev_snap = None
244
+
245
+ if current_snap != prev_snap:
246
+ mgr.sync(keep_active=not auto_prune)
247
+ post_snap = _collect_skill_dirs_snapshot(mgr)
248
+ skill_router._atomic_write_json(stamp_file, post_snap)
249
+
250
+ # Ensure search_index.json exists & is up-to-date
251
+ if archive_dir.exists():
252
+ skill_router.load_or_build_index(
253
+ archive_dir=archive_dir,
254
+ base_dir=mgr.base_dir,
255
+ resolve_path_fn=mgr.resolve_portable_path,
256
+ )
257
+
258
+ # Warm workspace fingerprint cache
259
+ if workspace_paths and archive_dir.exists():
260
+ ws_cats = set()
261
+ for wsp in workspace_paths:
262
+ if wsp and Path(wsp).exists():
263
+ ws_cats.update(mgr.detect_workspace_categories(wsp).keys())
264
+ skill_router.cache_workspace_categories(archive_dir, workspace_paths, sorted(ws_cats))
265
+
266
+ return {}
267
+
268
+
269
+ def _handle_prompt_hook(base_dir, archive_dir, payload, harness, event_name, routing_cfg, start_time):
270
+ """Route user prompt against L2 index and emit harness-native injection JSON."""
271
+ if not routing_cfg.get("enabled", True):
272
+ return {}
273
+
274
+ if not archive_dir.exists():
275
+ return {}
276
+
277
+ prompt = payload.get("lastUserInput") or payload.get("prompt") or ""
278
+ if not isinstance(prompt, str) or not prompt.strip():
279
+ return {}
280
+
281
+ conversation_id = payload.get("conversationId") or payload.get("session_id") or "default"
282
+ workspace_paths = payload.get("workspacePaths") or ([payload["cwd"]] if payload.get("cwd") else [])
283
+ invocation_num = payload.get("invocationNum")
284
+ initial_num_steps = payload.get("initialNumSteps")
285
+
286
+ conv_state = skill_router.ConversationState(archive_dir, conversation_id)
287
+ input_hash = hashlib.sha256(prompt.strip().encode("utf-8", errors="ignore")).hexdigest()[:16]
288
+
289
+ if conv_state.should_short_circuit(input_hash, invocation_num=invocation_num, initial_num_steps=initial_num_steps):
290
+ latency_ms = round((time.perf_counter() - start_time) * 1000.0, 2)
291
+ skill_router.log_routing_event(
292
+ archive_dir,
293
+ {
294
+ "ts": round(time.time(), 3),
295
+ "event": event_name,
296
+ "harness": harness,
297
+ "latency_ms": latency_ms,
298
+ "matched_inline": [],
299
+ "matched_pointers": [],
300
+ "estimated_tokens": 0,
301
+ "short_circuited": True,
302
+ },
303
+ )
304
+ return {}
305
+
306
+ # Fast zero-token early exit before loading search_index.json or workspace cache
307
+ if not skill_router.tokenize(prompt, include_stems=False):
308
+ conv_state.record_turn(
309
+ input_hash=input_hash,
310
+ initial_num_steps=initial_num_steps,
311
+ inline_keys=[],
312
+ pointer_keys=[],
313
+ )
314
+ latency_ms = round((time.perf_counter() - start_time) * 1000.0, 2)
315
+ skill_router.log_routing_event(
316
+ archive_dir,
317
+ {
318
+ "ts": round(time.time(), 3),
319
+ "event": event_name,
320
+ "harness": harness,
321
+ "latency_ms": latency_ms,
322
+ "matched_inline": [],
323
+ "matched_pointers": [],
324
+ "estimated_tokens": 0,
325
+ "short_circuited": False,
326
+ },
327
+ )
328
+ return {}
329
+
330
+ # Load pre-built search index (fast path <5ms)
331
+ index_data = skill_router.load_or_build_index(archive_dir=archive_dir, base_dir=base_dir)
332
+ if not index_data.get("skills"):
333
+ return {}
334
+
335
+ # Cached workspace stack categories (compute once if cache miss)
336
+ ws_cats = skill_router.get_cached_workspace_categories(archive_dir, workspace_paths)
337
+ if ws_cats is None and workspace_paths:
338
+ ws_cats_set = set()
339
+ try:
340
+ from skill_vault import SkillVault # noqa: E402
341
+
342
+ sink = io.StringIO()
343
+ with contextlib.redirect_stdout(sink), contextlib.redirect_stderr(sink):
344
+ mgr = SkillVault(base_dir=str(base_dir))
345
+ for wsp in workspace_paths:
346
+ if wsp and Path(wsp).exists():
347
+ ws_cats_set.update(mgr.detect_workspace_categories(wsp).keys())
348
+ ws_cats = sorted(ws_cats_set)
349
+ skill_router.cache_workspace_categories(archive_dir, workspace_paths, ws_cats)
350
+ except Exception:
351
+ ws_cats = []
352
+
353
+ active_names = _fast_active_skill_names(base_dir, workspace_paths)
354
+ exclude_names = active_names | conv_state.get_excluded_skills()
355
+
356
+ result = skill_router.route_prompt(
357
+ index_data=index_data,
358
+ prompt=prompt,
359
+ archive_dir=archive_dir,
360
+ base_dir=base_dir,
361
+ workspace_categories=ws_cats,
362
+ exclude_names=exclude_names,
363
+ routing_config=routing_cfg,
364
+ )
365
+
366
+ inline_keys = [item["canonical_key"] for item in result["inline"]]
367
+ pointer_keys = [item["canonical_key"] for item in result["pointers"]]
368
+ conv_state.record_turn(
369
+ input_hash=input_hash,
370
+ initial_num_steps=initial_num_steps,
371
+ inline_keys=inline_keys,
372
+ pointer_keys=pointer_keys,
373
+ )
374
+
375
+ latency_ms = round((time.perf_counter() - start_time) * 1000.0, 2)
376
+ skill_router.log_routing_event(
377
+ archive_dir,
378
+ {
379
+ "ts": round(time.time(), 3),
380
+ "event": event_name,
381
+ "harness": harness,
382
+ "latency_ms": latency_ms,
383
+ "matched_inline": [i["name"] for i in result["inline"]],
384
+ "matched_pointers": [p["name"] for p in result["pointers"]],
385
+ "estimated_tokens": result["estimated_tokens"],
386
+ "short_circuited": False,
387
+ },
388
+ )
389
+
390
+ injection_text = result.get("injection_text", "")
391
+ if not injection_text:
392
+ return {}
393
+
394
+ if harness == "antigravity":
395
+ metadata = {}
396
+ if routing_cfg.get("show_ui_notice") and result.get("ui_notice"):
397
+ metadata["user_markdown"] = result["ui_notice"]
398
+ return {
399
+ "injectSteps": [
400
+ {
401
+ "systemMessage": {
402
+ "systemMessage": injection_text,
403
+ "metadata": metadata,
404
+ }
405
+ }
406
+ ]
407
+ }
408
+
409
+ hook_evt = "BeforeAgent" if harness == "gemini-cli" else "UserPromptSubmit"
410
+ return {
411
+ "hookSpecificOutput": {
412
+ "hookEventName": hook_evt,
413
+ "additionalContext": injection_text,
414
+ }
415
+ }
416
+
417
+
418
+ def _record_hook_error(archive_dir, err):
419
+ try:
420
+ if archive_dir and Path(archive_dir).exists():
421
+ state_dir = Path(archive_dir) / ".state"
422
+ state_dir.mkdir(parents=True, exist_ok=True)
423
+ log_path = state_dir / "hook_errors.log"
424
+ with open(log_path, "a", encoding="utf-8", errors="replace") as f:
425
+ f.write(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {type(err).__name__}: {err}\n")
426
+ except Exception:
427
+ pass
428
+
429
+
430
+ def main():
431
+ _configure_stdio()
432
+ start_time = time.perf_counter()
433
+
434
+ parser = argparse.ArgumentParser(description="Skill Vault Lifecycle Hook Runner")
435
+ parser.add_argument("--event", help="Hook event name override")
436
+ parser.add_argument(
437
+ "--harness",
438
+ choices=["auto", "antigravity", "claude", "gemini-cli"],
439
+ default="auto",
440
+ help="Target agent harness format",
441
+ )
442
+ parser.add_argument("--base-dir", help="Explicit Skill Vault base directory")
443
+ args, _ = parser.parse_known_args()
444
+
445
+ archive_dir = None
446
+ try:
447
+ raw_stdin = ""
448
+ if sys.stdin is not None:
449
+ raw_stdin = sys.stdin.read()
450
+ payload = json.loads(raw_stdin) if raw_stdin and raw_stdin.strip() else {}
451
+ if not isinstance(payload, dict):
452
+ payload = {}
453
+ except Exception:
454
+ payload = {}
455
+
456
+ try:
457
+ ws_paths = payload.get("workspacePaths") or ([payload["cwd"]] if payload.get("cwd") else [])
458
+ base_dir, archive_dir = _resolve_base_and_archive(args.base_dir, workspace_paths=ws_paths)
459
+ routing_cfg = _load_routing_config(archive_dir)
460
+
461
+ event_name = _detect_event(args.event, payload)
462
+ harness = _detect_harness(args.harness, payload, event_name)
463
+
464
+ if event_name == "SessionStart":
465
+ out = _handle_session_start(base_dir, archive_dir, payload, routing_cfg)
466
+ elif event_name in ("PreInvocation", "UserPromptSubmit", "BeforeAgent"):
467
+ out = _handle_prompt_hook(
468
+ base_dir=base_dir,
469
+ archive_dir=archive_dir,
470
+ payload=payload,
471
+ harness=harness,
472
+ event_name=event_name,
473
+ routing_cfg=routing_cfg,
474
+ start_time=start_time,
475
+ )
476
+ else:
477
+ out = {}
478
+
479
+ sys.stdout.write(json.dumps(out, ensure_ascii=False) + "\n")
480
+ sys.stdout.flush()
481
+ except Exception as exc:
482
+ _record_hook_error(archive_dir, exc)
483
+ sys.stdout.write("{}\n")
484
+ sys.stdout.flush()
485
+
486
+
487
+ if __name__ == "__main__":
488
+ main()