@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.
@@ -0,0 +1,1187 @@
1
+ #!/usr/bin/env python3
2
+ """Skill Router: Pre-built BM25 + Multi-Signal Search Index and JIT Context Router.
3
+
4
+ Pure Python 3 standard library only (compatible with Python 3.10+ on Windows, macOS, Linux).
5
+ Provides fast (<50ms) precision-first skill discovery and confidence-tiered injection
6
+ directly from cold storage (L2) without modifying SKILL.md files or bloating L1.
7
+ """
8
+
9
+ from collections import Counter
10
+ import hashlib
11
+ import json
12
+ import math
13
+ import os
14
+ from pathlib import Path
15
+ import re
16
+ import time
17
+
18
+ INDEX_SCHEMA_VERSION = 3
19
+
20
+ DEFAULT_ROUTING_CONFIG = {
21
+ "enabled": True,
22
+ "mode": "hybrid", # "hybrid" | "inline" | "pointer"
23
+ "max_inline_skills": 2,
24
+ "max_inline_chars": 12000,
25
+ "max_single_skill_chars": 9000,
26
+ "max_pointer_skills": 4,
27
+ "min_score_inline": 5.5,
28
+ "min_score_pointer": 2.8,
29
+ "inline_margin_ratio": 1.15,
30
+ "workspace_boost": 1.35,
31
+ "auto_sync_on_session_start": True,
32
+ "auto_prune_on_session_start": True,
33
+ "compact_router_prompt": False,
34
+ "show_ui_notice": False,
35
+ "always_exclude": [],
36
+ }
37
+
38
+ FIELD_WEIGHTS = {
39
+ "name_terms": 4.0,
40
+ "tag_terms": 2.8,
41
+ "desc_terms": 2.2,
42
+ "heading_terms": 1.5,
43
+ "body_terms": 0.7,
44
+ }
45
+
46
+ # English stopwords + generic coding/chat verbs and nouns that carry no domain signal alone
47
+ STOPWORDS = {
48
+ "a", "about", "above", "after", "again", "against", "all", "also", "am", "an", "and",
49
+ "any", "are", "aren", "arent", "as", "at", "be", "because", "been", "before", "being",
50
+ "below", "between", "both", "but", "by", "can", "cannot", "could", "couldn", "did",
51
+ "didn", "do", "does", "doesn", "doing", "don", "dont", "down", "during", "each", "few",
52
+ "for", "from", "further", "get", "got", "had", "has", "have", "having", "he", "hello",
53
+ "help", "her", "here", "hers", "herself", "hey", "hi", "him", "himself", "his", "how",
54
+ "i", "if", "in", "into", "is", "isn", "it", "its", "itself", "just", "know", "let",
55
+ "like", "ll", "look", "looks", "make", "may", "me", "might", "more", "most", "must",
56
+ "my", "myself", "need", "new", "no", "nor", "not", "now", "of", "off", "ok", "okay",
57
+ "on", "once", "only", "or", "other", "our", "ours", "ourselves", "out", "over", "own",
58
+ "please", "re", "really", "right", "same", "see", "she", "should", "shouldn", "so",
59
+ "some", "such", "sure", "tell", "than", "thank", "thanks", "that", "the", "their",
60
+ "theirs", "them", "themselves", "then", "there", "these", "they", "thing", "things",
61
+ "this", "those", "through", "to", "too", "under", "understand", "understood", "until",
62
+ "up", "use", "used", "using", "ve", "very", "want", "was", "wasn", "way", "we", "well",
63
+ "were", "weren", "what", "whats", "when", "where", "which", "while", "who", "whom",
64
+ "why", "will", "with", "won", "would", "wouldn", "yes", "yet", "you", "your", "yours",
65
+ "yourself", "yourselves",
66
+ # Generic coding & conversation words
67
+ "add", "agent", "agents", "always", "another", "app", "apps", "apply", "ask", "based",
68
+ "best", "better", "bug", "bugs", "build", "building", "call", "change", "changed",
69
+ "changes", "check", "checking", "class", "classes", "clean", "cleaner", "code", "coding",
70
+ "command", "commands", "commit", "common", "config", "configure", "context", "continue",
71
+ "create", "creating", "current", "currently", "data", "date", "dates", "default",
72
+ "delete", "detail", "details", "dir", "directory", "doc", "docs", "document", "done",
73
+ "edit", "end", "ensure", "error", "errors", "etc", "every", "everything", "example",
74
+ "examples", "examine", "exist", "existing", "explain", "failing", "fails", "fail",
75
+ "feature", "features", "file", "files", "find", "fix", "fixing", "flag", "flags",
76
+ "folder", "folders", "follow", "following", "format", "full", "function", "functions",
77
+ "general", "generate", "give", "goal", "good", "great", "guide", "handle", "implement",
78
+ "implementation", "include", "including", "info", "information", "input", "inside",
79
+ "install", "installed", "instead", "into", "issue", "issues", "item", "items", "keep",
80
+ "key", "line", "lines", "list", "load", "local", "loop", "main", "manage", "management",
81
+ "match", "matching", "message", "method", "methods", "mode", "model", "models", "modify",
82
+ "module", "multiple", "name", "named", "names", "need", "needed", "needs", "next", "nice",
83
+ "note", "notes", "number", "numbers", "object", "open", "option", "options", "order",
84
+ "output", "overview", "page", "pages", "part", "path", "paths", "pattern", "plan",
85
+ "planning", "point", "possible", "print", "problem", "problems", "process", "project",
86
+ "projects", "prompt", "prompts", "provide", "provided", "purpose", "question", "quick",
87
+ "read", "reading", "real", "related", "remove", "rename", "repo", "report", "repository",
88
+ "request", "require", "required", "requires", "result", "results", "return", "returns",
89
+ "review", "run", "running", "runs", "save", "script", "scripts", "search", "section",
90
+ "see", "select", "send", "server", "service", "services", "session", "set", "setting",
91
+ "settings", "setup", "show", "showing", "simple", "single", "skill", "skills", "small",
92
+ "solution", "solve", "something", "source", "specific", "staged", "standard", "start",
93
+ "state", "step", "steps", "still", "stop", "structure", "style", "support", "supported",
94
+ "system", "target", "task", "tasks", "test", "testing", "tests", "text", "time", "tool",
95
+ "tools", "topic", "try", "type", "types", "unit", "update", "updated", "updates", "usage",
96
+ "user", "users", "utility", "valid", "value", "values", "variable", "variables", "verify",
97
+ "version", "view", "work", "working", "works", "workspace", "write", "writing", "written",
98
+ "refactor", "refactored", "refactoring", "rewrite", "rewriting", "simplify", "simplified",
99
+ "helper", "helpers", "snippet", "snippets", "codebase", "parse", "parsed", "parsing",
100
+ "convert", "converting", "converted", "sort", "sorting", "filter", "filtering",
101
+ "string", "strings", "array", "arrays", "dict", "dictionary", "lists", "regex", "regexp",
102
+ "loops", "formatting", "formatted",
103
+ "able", "actually", "already", "although", "around", "away", "back", "become", "becomes",
104
+ "beyond", "big", "come", "comes", "different", "either", "else", "enough", "even", "ever",
105
+ "extra", "far", "feel", "first", "found", "free", "getting", "given", "goes", "going",
106
+ "gone", "hard", "however", "important", "influence", "influenced", "influences", "intention",
107
+ "intentions", "kind", "known", "large", "last", "later", "least", "less", "likely", "little",
108
+ "long", "lot", "made", "mainly", "makes", "making", "many", "maybe", "mean", "means", "mine",
109
+ "much", "neither", "never", "nothing", "often", "old", "ones", "others", "overall",
110
+ "particular", "perhaps", "probably", "put", "quite", "rather", "said", "say", "says",
111
+ "second", "seem", "seems", "seen", "several", "shall", "short", "since", "somehow", "someone",
112
+ "sometimes", "somewhere", "soon", "suggest", "suggested", "suggesting", "suggestions",
113
+ "systems", "take", "taken", "takes", "taking", "think", "thinking", "though", "thought",
114
+ "three", "thus", "together", "told", "toward", "towards", "tried", "tries", "true", "trying",
115
+ "two", "unable", "unless", "upon", "useful", "usually", "various", "wants", "ways", "went",
116
+ "whatever", "whether", "whole", "whose", "within", "without", "workspaces",
117
+ }
118
+
119
+ # High-signal 2-character domain tokens to retain
120
+ SHORT_DOMAIN_TOKENS = {
121
+ "ai", "ml", "db", "ui", "ux", "ci", "cd", "qa", "tf", "go",
122
+ "ik", "js", "ts", "py", "bq", "vm", "os", "io", "ip", "pr",
123
+ "uv",
124
+ }
125
+
126
+ # Broad tech terms that should not trigger skill injection on their own as a solo 1-token query
127
+ GENERIC_SINGLE_TOKENS = {
128
+ "python", "javascript", "typescript", "java", "golang", "rust", "ruby", "php", "csharp",
129
+ "cpp", "html", "css", "json", "yaml", "toml", "xml", "csv", "sql", "bash", "shell",
130
+ "powershell", "pwsh", "markdown", "linux", "windows", "macos", "git", "github", "cloud",
131
+ "database", "databases", "storage", "query", "queries", "table", "tables", "schema",
132
+ "debug", "debugging", "optimize", "optimization", "performance", "security", "audit",
133
+ "monitor", "monitoring", "health", "access", "admin", "backup", "layout", "widget",
134
+ "widgets", "component", "components", "container", "containers", "cluster", "clusters",
135
+ "deploy", "deployment", "pipeline", "pipelines", "notebook", "notebooks", "graph",
136
+ "report", "draft", "resolve", "mobile", "web", "frontend", "backend", "api", "apis",
137
+ "server", "client", "network", "auth", "authentication", "replication", "migration",
138
+ "analysis", "analyze", "analytics", "extension", "extensions", "preview", "device",
139
+ "rules", "rule", "slow", "fast", "faster", "practices", "practice",
140
+ "distributed", "distribute", "distribution", "dependent", "depends", "depend",
141
+ "dependencies", "dependency", "architecture", "architectural", "improvement", "improvements",
142
+ "publish", "published", "publishing", "npm", "safe", "safely", "safety",
143
+ "package", "packages", "install", "library", "libraries", "framework", "frameworks",
144
+ }
145
+
146
+ _STEM_SUFFIXES = (
147
+ ("ization", "ize"),
148
+ ("ations", "ate"),
149
+ ("ation", "ate"),
150
+ ("ities", "ity"),
151
+ ("ments", "ment"),
152
+ ("iness", "y"),
153
+ ("ies", "y"),
154
+ ("ing", ""),
155
+ ("ers", "er"),
156
+ ("ed", ""),
157
+ ("es", ""),
158
+ ("s", ""),
159
+ )
160
+
161
+
162
+ def _light_stem(token):
163
+ """Apply conservative suffix normalization for English plurals/verb forms."""
164
+ if len(token) < 5 or any(ch in token for ch in (".", "-", "_")) or any(ch.isdigit() for ch in token):
165
+ return token
166
+ if token.endswith(("ss", "us", "is", "os", "gres", "etes", "ias")):
167
+ return token
168
+ for suffix, repl in _STEM_SUFFIXES:
169
+ if token.endswith(suffix):
170
+ stem = token[: -len(suffix)] + repl
171
+ if len(stem) >= 4:
172
+ return stem
173
+ break
174
+ return token
175
+
176
+
177
+ def _is_valid_token(tok):
178
+ """Return True if token carries meaningful domain signal."""
179
+ if not tok or tok in STOPWORDS:
180
+ return False
181
+ has_alpha = any("a" <= ch <= "z" for ch in tok)
182
+ if not has_alpha:
183
+ return False
184
+ if len(tok) >= 3:
185
+ return True
186
+ if tok in SHORT_DOMAIN_TOKENS:
187
+ return True
188
+ if any(ch.isdigit() for ch in tok) and len(tok) >= 2:
189
+ return True
190
+ return False
191
+
192
+
193
+ def tokenize(text, include_stems=True):
194
+ """Extract normalized domain tokens from text while preserving compound identifiers."""
195
+ if not text:
196
+ return []
197
+
198
+ lowered = text.lower()
199
+ raw_chunks = re.findall(r"[a-z0-9]+(?:[._/-][a-z0-9]+)*", lowered)
200
+ tokens = []
201
+
202
+ for chunk in raw_chunks:
203
+ chunk_clean = chunk.strip("._/-")
204
+ if not chunk_clean:
205
+ continue
206
+
207
+ # Preserve compound filenames/commands/identifiers like firestore.rules, alloydb-omni
208
+ if any(sep in chunk_clean for sep in (".", "-", "_")) and "/" not in chunk_clean:
209
+ if _is_valid_token(chunk_clean):
210
+ tokens.append(chunk_clean)
211
+
212
+ parts = re.split(r"[._/\-]+", chunk_clean)
213
+ for part in parts:
214
+ if _is_valid_token(part):
215
+ tokens.append(part)
216
+ if include_stems:
217
+ stemmed = _light_stem(part)
218
+ if stemmed != part and _is_valid_token(stemmed):
219
+ tokens.append(stemmed)
220
+
221
+ return tokens
222
+
223
+
224
+ def canonicalize_skill_name(name):
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
229
+
230
+
231
+ def _parse_version_tuple(ver_str):
232
+ if not ver_str:
233
+ return None
234
+ cleaned = str(ver_str).strip().strip("'\"").lstrip("vV")
235
+ nums = re.findall(r"\d+", cleaned)
236
+ return tuple(int(n) for n in nums) if nums else None
237
+
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
+
255
+ def _parse_frontmatter(content):
256
+ """Parse YAML frontmatter fields from SKILL.md without external YAML dependencies."""
257
+ fm_match = re.match(r"^---\s*\n(.*?)\n---(?:\s*\n|\s*\Z)", content, re.DOTALL)
258
+ if not fm_match:
259
+ return {}, content
260
+
261
+ fm_text = fm_match.group(1)
262
+ body = content[fm_match.end():]
263
+ meta = {}
264
+
265
+ # Scalar fields
266
+ for field in ("name", "version", "category"):
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)
270
+ if m:
271
+ val = m.group(1).strip().strip("'\"")
272
+ if val:
273
+ meta[field] = val
274
+
275
+ # Description (supports folded/literal YAML blocks and inline scalars)
276
+ desc_match = re.search(
277
+ r"^description:\s*(?:>[-+]?|\|[-+]?)?\s*\n?(.*?)(?=\n[a-zA-Z0-9_-]+:|\Z)",
278
+ fm_text,
279
+ re.DOTALL | re.MULTILINE | re.IGNORECASE,
280
+ )
281
+ if desc_match:
282
+ raw_desc = desc_match.group(1).strip()
283
+ meta["description"] = " ".join(
284
+ line.strip().strip("'\"") for line in raw_desc.splitlines() if line.strip()
285
+ )
286
+
287
+ # List or comma-separated fields: tags, triggers, globs
288
+ for list_field in ("tags", "triggers", "globs"):
289
+ block_match = re.search(
290
+ rf"^{list_field}:\s*(.*?)(?=\n[a-zA-Z0-9_-]+:|\Z)",
291
+ fm_text,
292
+ re.DOTALL | re.MULTILINE | re.IGNORECASE,
293
+ )
294
+ if block_match:
295
+ raw_val = block_match.group(1).strip()
296
+ raw_val = raw_val.strip("[]")
297
+ items = []
298
+ for part in re.split(r"[\n,]+", raw_val):
299
+ cleaned = re.sub(r"^\s*-\s*", "", part).strip().strip("'\"")
300
+ if cleaned:
301
+ items.append(cleaned)
302
+ if items:
303
+ meta[list_field] = items
304
+
305
+ return meta, body
306
+
307
+
308
+ def _list_companion_files(skill_dir, max_files=30):
309
+ """List companion files (references/, scripts/, examples/, resources/) in POSIX relative form."""
310
+ skill_dir = Path(skill_dir)
311
+ if not skill_dir.exists():
312
+ return []
313
+ companions = []
314
+ for root, dirs, files in os.walk(skill_dir):
315
+ root_path = Path(root)
316
+ dirs[:] = sorted(
317
+ d for d in dirs
318
+ if d not in {"__pycache__", ".git", "node_modules"}
319
+ and not (root_path / d / "SKILL.md").exists()
320
+ )
321
+ for fname in sorted(files):
322
+ fpath = root_path / fname
323
+ if root_path == skill_dir and fname == "SKILL.md":
324
+ continue
325
+ try:
326
+ rel = fpath.relative_to(skill_dir).as_posix()
327
+ companions.append(rel)
328
+ if len(companions) >= max_files:
329
+ return companions
330
+ except ValueError:
331
+ pass
332
+ return companions
333
+
334
+
335
+ def _extract_skill_fields(skill_name, category, skill_dir, skill_md_path):
336
+ """Extract weighted token frequency maps and metadata from a skill's SKILL.md."""
337
+ try:
338
+ content = Path(skill_md_path).read_text(encoding="utf-8", errors="replace")
339
+ except Exception:
340
+ content = ""
341
+
342
+ meta, body = _parse_frontmatter(content)
343
+ description = meta.get("description") or "No description available."
344
+ ver_tuple = _parse_version_tuple(meta.get("version"))
345
+
346
+ # 1. Name terms (deduplicate skill_name vs meta['name'] to avoid artificial tf=2 inflation)
347
+ meta_name = meta.get("name", "")
348
+ name_input = skill_name if not meta_name or meta_name.strip().lower() == skill_name.strip().lower() else f"{skill_name} {meta_name}"
349
+ name_tokens = tokenize(name_input)
350
+ name_tf = dict(Counter(name_tokens))
351
+
352
+ # 2. Explicit author-declared frontmatter tag / trigger / glob terms ONLY
353
+ tag_inputs = []
354
+ for lf in ("tags", "triggers", "globs"):
355
+ if lf in meta:
356
+ tag_inputs.extend(meta[lf])
357
+ tag_tf = dict(Counter(tokenize(" ".join(tag_inputs))))
358
+
359
+ # 3. Description terms
360
+ desc_tf = dict(Counter(tokenize(description)))
361
+
362
+ # 4. Headings + Category terms
363
+ headings = re.findall(r"^#{1,3}\s+(.+)$", body, re.MULTILINE)
364
+ heading_text = f"{category} " + " ".join(headings)
365
+ heading_tf = dict(Counter(tokenize(heading_text)))
366
+
367
+ # 5. Distinctive body terms + selective technical inline code identifiers (top 60)
368
+ inline_code = re.findall(r"`([^`\n]{2,60})`", body)
369
+ code_tokens = tokenize(" ".join(inline_code))
370
+ seen_code = []
371
+ seen_code_set = set()
372
+ for tok in code_tokens:
373
+ is_distinctive = (
374
+ any(ch in tok for ch in (".", "-", "_"))
375
+ or any(ch.isdigit() for ch in tok)
376
+ or tok not in GENERIC_SINGLE_TOKENS
377
+ )
378
+ if is_distinctive and tok not in seen_code_set:
379
+ seen_code_set.add(tok)
380
+ seen_code.append(tok)
381
+ if len(seen_code) >= 40:
382
+ break
383
+
384
+ body_clean = re.sub(r"```.*?```", " ", body, flags=re.DOTALL)
385
+ body_counts = Counter(tokenize(body_clean) + seen_code)
386
+ body_tf = dict(body_counts.most_common(60))
387
+
388
+ # Compute mtime safely without bleeding nested sibling skills
389
+ latest_mtime = 0.0
390
+ try:
391
+ skill_dir_path = Path(skill_dir)
392
+ mtimes = []
393
+ if Path(skill_md_path).exists():
394
+ mtimes.append(Path(skill_md_path).stat().st_mtime)
395
+ if skill_dir_path.exists():
396
+ for root, dirs, files in os.walk(skill_dir_path):
397
+ rp = Path(root)
398
+ dirs[:] = [d for d in dirs if not (rp / d / "SKILL.md").exists()]
399
+ for fn in files:
400
+ try:
401
+ mtimes.append((rp / fn).stat().st_mtime)
402
+ except OSError:
403
+ pass
404
+ if mtimes:
405
+ latest_mtime = max(mtimes)
406
+ except OSError:
407
+ pass
408
+
409
+ skill_md_bytes = 0
410
+ try:
411
+ skill_md_bytes = Path(skill_md_path).stat().st_size
412
+ except OSError:
413
+ skill_md_bytes = len(content.encode("utf-8", errors="ignore"))
414
+
415
+ return {
416
+ "name": skill_name,
417
+ "canonical_key": canonicalize_skill_name(skill_name),
418
+ "category": category or "General & Utility Skills",
419
+ "description": description,
420
+ "version_tuple": list(ver_tuple) if ver_tuple is not None else None,
421
+ "mtime": latest_mtime,
422
+ "skill_md_bytes": skill_md_bytes,
423
+ "companion_files": _list_companion_files(skill_dir),
424
+ "fields": {
425
+ "name_terms": name_tf,
426
+ "tag_terms": tag_tf,
427
+ "desc_terms": desc_tf,
428
+ "heading_terms": heading_tf,
429
+ "body_terms": body_tf,
430
+ },
431
+ }
432
+
433
+
434
+ def _is_newer_entry(cand, existing):
435
+ """Return True if cand entry is strictly newer/preferred over existing entry."""
436
+ va = cand.get("version_tuple")
437
+ vb = existing.get("version_tuple")
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
442
+
443
+ ma = cand.get("mtime", 0.0)
444
+ mb = existing.get("mtime", 0.0)
445
+ if abs(ma - mb) > 1.0:
446
+ return ma > mb
447
+
448
+ if (va is not None) != (vb is not None):
449
+ return va is not None
450
+
451
+ # Tie-breaker: prefer hyphenated names over underscored names
452
+ cand_hyphen = "-" in cand["name"] and "_" not in cand["name"]
453
+ exist_hyphen = "-" in existing["name"] and "_" not in existing["name"]
454
+ if cand_hyphen != exist_hyphen:
455
+ return cand_hyphen
456
+ return cand["name"].lower() < existing["name"].lower()
457
+
458
+
459
+ def _resolve_archived_skill_dir(base_dir, archive_dir, raw_archived_path):
460
+ """Resolve an archived_path stored in manifest across relative/absolute layouts."""
461
+ p = Path(raw_archived_path)
462
+ if p.is_absolute():
463
+ return p
464
+ if base_dir is not None:
465
+ cand = (Path(base_dir) / p).resolve()
466
+ if cand.exists():
467
+ return cand
468
+ cand2 = (Path(archive_dir).parent / p).resolve()
469
+ if cand2.exists():
470
+ return cand2
471
+ return (Path(archive_dir) / p).resolve()
472
+
473
+
474
+ def build_search_index(archive_dir, manifest, base_dir=None, resolve_path_fn=None):
475
+ """Build and atomically persist search_index.json from backup_manifest.json."""
476
+ archive_path = Path(archive_dir).resolve()
477
+ archive_path.mkdir(parents=True, exist_ok=True)
478
+ manifest_file = archive_path / "backup_manifest.json"
479
+ manifest_mtime = manifest_file.stat().st_mtime if manifest_file.exists() else time.time()
480
+
481
+ deduped = {}
482
+ for item in manifest:
483
+ name = item.get("name")
484
+ raw_arch = item.get("archived_path", "")
485
+ if not name or not raw_arch:
486
+ continue
487
+ if resolve_path_fn is not None:
488
+ skill_dir = Path(resolve_path_fn(raw_arch))
489
+ else:
490
+ skill_dir = _resolve_archived_skill_dir(base_dir, archive_path, raw_arch)
491
+
492
+ skill_md = skill_dir / "SKILL.md"
493
+ if not skill_md.exists():
494
+ continue
495
+
496
+ entry = _extract_skill_fields(
497
+ skill_name=name,
498
+ category=item.get("category") or "General & Utility Skills",
499
+ skill_dir=skill_dir,
500
+ skill_md_path=skill_md,
501
+ )
502
+ entry["archived_path"] = raw_arch
503
+ entry["resolved_path"] = str(skill_dir)
504
+ entry["aliases"] = [name]
505
+
506
+ ckey = entry["canonical_key"]
507
+ if ckey not in deduped:
508
+ deduped[ckey] = entry
509
+ else:
510
+ existing = deduped[ckey]
511
+ aliases = list(dict.fromkeys(existing.get("aliases", []) + [name]))
512
+ if _is_newer_entry(entry, existing):
513
+ entry["aliases"] = aliases
514
+ deduped[ckey] = entry
515
+ else:
516
+ existing["aliases"] = aliases
517
+
518
+ skills_list = sorted(deduped.values(), key=lambda x: x["name"].lower())
519
+ doc_count = len(skills_list)
520
+
521
+ # Compute document frequency (across any field per skill) and average field lengths
522
+ df = Counter()
523
+ field_totals = {f: 0 for f in FIELD_WEIGHTS}
524
+
525
+ for entry in skills_list:
526
+ seen_terms = set()
527
+ for fname in FIELD_WEIGHTS:
528
+ tf_map = entry["fields"].get(fname, {})
529
+ field_totals[fname] += sum(tf_map.values())
530
+ seen_terms.update(tf_map.keys())
531
+ for term in seen_terms:
532
+ df[term] += 1
533
+
534
+ avg_len = {
535
+ fname: (field_totals[fname] / doc_count) if doc_count > 0 else 1.0
536
+ for fname in FIELD_WEIGHTS
537
+ }
538
+ for fname in avg_len:
539
+ if avg_len[fname] <= 0:
540
+ avg_len[fname] = 1.0
541
+
542
+ index_data = {
543
+ "schema_version": INDEX_SCHEMA_VERSION,
544
+ "built_at": time.time(),
545
+ "manifest_mtime": manifest_mtime,
546
+ "doc_count": doc_count,
547
+ "avg_len": avg_len,
548
+ "df": dict(df),
549
+ "skills": skills_list,
550
+ }
551
+
552
+ index_file = archive_path / "search_index.json"
553
+ tmp_file = archive_path / f".search_index.{os.getpid()}.tmp"
554
+ with open(tmp_file, "w", encoding="utf-8") as f:
555
+ json.dump(index_data, f, ensure_ascii=False)
556
+ os.replace(tmp_file, index_file)
557
+ return index_data
558
+
559
+
560
+ def load_or_build_index(archive_dir, base_dir=None, resolve_path_fn=None):
561
+ """Load pre-built search_index.json in <5ms, or rebuild lazily if missing/stale."""
562
+ archive_path = Path(archive_dir).resolve()
563
+ index_file = archive_path / "search_index.json"
564
+ manifest_file = archive_path / "backup_manifest.json"
565
+ manifest_mtime = manifest_file.stat().st_mtime if manifest_file.exists() else 0.0
566
+
567
+ if index_file.exists():
568
+ try:
569
+ with open(index_file, "r", encoding="utf-8") as f:
570
+ data = json.load(f)
571
+ if (
572
+ isinstance(data, dict)
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)
578
+ and float(data.get("manifest_mtime", 0.0)) >= manifest_mtime - 0.5
579
+ ):
580
+ return data
581
+ except Exception:
582
+ pass
583
+
584
+ manifest = []
585
+ if manifest_file.exists():
586
+ try:
587
+ with open(manifest_file, "r", encoding="utf-8") as f:
588
+ manifest = json.load(f)
589
+ except Exception:
590
+ manifest = []
591
+
592
+ return build_search_index(
593
+ archive_dir=archive_path,
594
+ manifest=manifest,
595
+ base_dir=base_dir,
596
+ resolve_path_fn=resolve_path_fn,
597
+ )
598
+
599
+
600
+ def _normalized_idf(df_val, doc_count):
601
+ """Compute corpus-size-normalized BM25 IDF so thresholds stay calibrated from N=10 to N=1000+."""
602
+ if doc_count <= 0:
603
+ return 0.0
604
+ raw = math.log((doc_count - df_val + 0.5) / (df_val + 0.5) + 1.0)
605
+ scale = 3.2 / math.log(max(doc_count, 5) + 1.0)
606
+ return raw * scale
607
+
608
+
609
+ def search_index(
610
+ index_data,
611
+ query,
612
+ category=None,
613
+ workspace_categories=None,
614
+ exclude_names=None,
615
+ limit=10,
616
+ routing_config=None,
617
+ ):
618
+ """Score indexed skills using multi-field BM25 + exact-name + coverage + workspace tie-breaker."""
619
+ cfg = dict(DEFAULT_ROUTING_CONFIG)
620
+ if routing_config:
621
+ cfg.update(routing_config)
622
+
623
+ skills = index_data.get("skills", [])
624
+ doc_count = index_data.get("doc_count", len(skills))
625
+ avg_len = index_data.get("avg_len", {f: 1.0 for f in FIELD_WEIGHTS})
626
+ df_map = index_data.get("df", {})
627
+
628
+ exclude_canon = {canonicalize_skill_name(n) for n in (exclude_names or []) if n}
629
+ ws_cats = set(workspace_categories or [])
630
+ ws_boost = float(cfg.get("workspace_boost", 1.35))
631
+
632
+ raw_query = (query or "").strip().lower()
633
+ raw_query_norm = re.sub(r"[-_]+", " ", raw_query)
634
+ # Extract distinct semantic concepts without summing base + stem duplicates
635
+ concept_tokens = list(dict.fromkeys(tokenize(query, include_stems=False)))
636
+
637
+ if not raw_query and not category:
638
+ return []
639
+
640
+ specific_concepts = [
641
+ c for c in concept_tokens
642
+ if c not in GENERIC_SINGLE_TOKENS
643
+ and (df_map.get(c, 0) > 0 or df_map.get(_light_stem(c), 0) > 0)
644
+ ]
645
+
646
+ k1 = 1.2
647
+ results = []
648
+
649
+ for entry in skills:
650
+ ckey = entry.get("canonical_key") or canonicalize_skill_name(entry.get("name"))
651
+ if ckey in exclude_canon:
652
+ continue
653
+
654
+ entry_cat = entry.get("category", "General & Utility Skills")
655
+ if category and entry_cat.lower() != category.strip().lower():
656
+ continue
657
+
658
+ if not raw_query and category:
659
+ results.append({
660
+ "name": entry["name"],
661
+ "canonical_key": ckey,
662
+ "category": entry_cat,
663
+ "score": 10.0,
664
+ "matched_terms": [],
665
+ "description": entry.get("description", ""),
666
+ "archived_path": entry.get("archived_path", ""),
667
+ "resolved_path": entry.get("resolved_path", ""),
668
+ "skill_md_bytes": entry.get("skill_md_bytes", 0),
669
+ "companion_files": entry.get("companion_files", []),
670
+ "aliases": entry.get("aliases", [entry["name"]]),
671
+ "exact_name_hit": False,
672
+ })
673
+ continue
674
+
675
+ fields = entry.get("fields", {})
676
+ cat_tokens = set(tokenize(entry_cat, include_stems=False))
677
+ bm25_score = 0.0
678
+ matched_terms = []
679
+ matched_in_name = False
680
+ matched_in_tags = False
681
+ matched_in_desc_or_head = False
682
+ matched_concepts = set()
683
+ matched_specific = 0
684
+ high_signal_hits = 0
685
+ matched_name_concepts = 0
686
+ matched_non_generic_in_name_or_tag = False
687
+ matched_category_token = False
688
+ matched_non_generic_desc = 0
689
+
690
+ for ctok in concept_tokens:
691
+ forms = list(dict.fromkeys([ctok, _light_stem(ctok)]))
692
+ best_form_score = 0.0
693
+ form_name = False
694
+ form_tag = False
695
+ form_desc_or_head = False
696
+ form_high = False
697
+
698
+ for f_tok in forms:
699
+ df_val = df_map.get(f_tok, 0)
700
+ if df_val == 0:
701
+ continue
702
+ idf = _normalized_idf(df_val, doc_count)
703
+ field_scores = []
704
+
705
+ for fname, weight in FIELD_WEIGHTS.items():
706
+ tf_map = fields.get(fname, {})
707
+ tf = tf_map.get(f_tok, 0)
708
+ if tf <= 0:
709
+ continue
710
+ if fname == "name_terms":
711
+ form_name = True
712
+ form_high = True
713
+ elif fname == "tag_terms":
714
+ form_tag = True
715
+ form_high = True
716
+ elif fname in ("desc_terms", "heading_terms"):
717
+ form_desc_or_head = True
718
+ form_high = True
719
+
720
+ dl = max(sum(tf_map.values()), 1)
721
+ adl = max(float(avg_len.get(fname, 1.0)), 1.0)
722
+ b_val = 0.25 if fname == "name_terms" else 0.75
723
+ tf_norm = (tf * (k1 + 1.0)) / (tf + k1 * (1.0 - b_val + b_val * dl / adl))
724
+ field_scores.append(weight * idf * tf_norm)
725
+
726
+ if field_scores:
727
+ field_scores.sort(reverse=True)
728
+ blended = min(
729
+ field_scores[0] * 1.35,
730
+ field_scores[0] + 0.20 * sum(field_scores[1:]),
731
+ )
732
+ if idf >= 2.0 and (form_name or form_tag):
733
+ blended *= 1.15
734
+ if blended > best_form_score:
735
+ best_form_score = blended
736
+
737
+ if best_form_score > 0.0:
738
+ bm25_score += best_form_score
739
+ matched_terms.append(ctok)
740
+ matched_concepts.add(ctok)
741
+ is_non_generic = ctok not in GENERIC_SINGLE_TOKENS
742
+ if ctok in specific_concepts:
743
+ matched_specific += 1
744
+ if form_name:
745
+ matched_in_name = True
746
+ matched_name_concepts += 1
747
+ if form_tag:
748
+ matched_in_tags = True
749
+ if is_non_generic and (form_name or form_tag):
750
+ matched_non_generic_in_name_or_tag = True
751
+ if is_non_generic and ctok in cat_tokens:
752
+ matched_category_token = True
753
+ if is_non_generic and form_desc_or_head:
754
+ matched_non_generic_desc += 1
755
+ if form_high:
756
+ if not (form_name or form_tag):
757
+ matched_in_desc_or_head = True
758
+ high_signal_hits += 1
759
+
760
+ # Exact skill name / alias hit check
761
+ exact_name_hit = False
762
+ for alias in entry.get("aliases", [entry["name"]]):
763
+ alias_l = alias.lower()
764
+ alias_spaces = re.sub(r"[-_]+", " ", alias_l)
765
+ if len(alias_l) >= 4:
766
+ if (
767
+ re.search(rf"(?<![a-z0-9]){re.escape(alias_l)}(?![a-z0-9])", raw_query)
768
+ or re.search(rf"(?<![a-z0-9]){re.escape(alias_spaces)}(?![a-z0-9])", raw_query_norm)
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
776
+
777
+ if exact_name_hit:
778
+ bm25_score += 10.0
779
+
780
+ # Multi-term coverage bonus when >=2 distinct prompt concepts hit high-signal fields
781
+ if high_signal_hits >= 2:
782
+ bm25_score += 1.5 * (high_signal_hits - 1)
783
+
784
+ # Dominant-concept gate & identity-anchor guards to keep unrelated conversational prompts at 0 tokens
785
+ if not exact_name_hit and specific_concepts and matched_specific == 0:
786
+ bm25_score *= 0.20
787
+ elif not exact_name_hit and len(matched_concepts) <= 1 and bm25_score > 0:
788
+ only_tok = next(iter(matched_concepts)) if matched_concepts else ""
789
+ df_ratio = (df_map.get(only_tok, 0) / doc_count) if doc_count > 0 else 0.0
790
+ only_body = not (matched_in_name or matched_in_tags or matched_in_desc_or_head)
791
+ not_name_or_tag = not (matched_in_name or matched_in_tags)
792
+
793
+ if only_tok in GENERIC_SINGLE_TOKENS and only_tok != ckey:
794
+ bm25_score *= 0.15
795
+ elif only_body:
796
+ bm25_score *= 0.25
797
+ elif df_ratio > 0.35 or (df_ratio > 0.20 and not matched_in_name):
798
+ bm25_score *= 0.30
799
+ elif not_name_or_tag and len(concept_tokens) >= 2:
800
+ bm25_score *= 0.45
801
+ elif not exact_name_hit and matched_concepts and all(c in GENERIC_SINGLE_TOKENS for c in matched_concepts):
802
+ if matched_name_concepts < 2:
803
+ bm25_score *= 0.20
804
+ elif (
805
+ not exact_name_hit
806
+ and matched_concepts
807
+ and not matched_non_generic_in_name_or_tag
808
+ and not matched_category_token
809
+ and matched_non_generic_desc < 2
810
+ and matched_name_concepts < 2
811
+ ):
812
+ bm25_score *= 0.30
813
+
814
+ # Soft workspace tie-breaker ONLY when prompt already has real signal
815
+ if bm25_score > 0.5 and entry_cat in ws_cats:
816
+ bm25_score *= ws_boost
817
+
818
+ if bm25_score > 0.0:
819
+ results.append({
820
+ "name": entry["name"],
821
+ "canonical_key": ckey,
822
+ "category": entry_cat,
823
+ "score": round(bm25_score, 3),
824
+ "matched_terms": list(dict.fromkeys(matched_terms)),
825
+ "description": entry.get("description", ""),
826
+ "archived_path": entry.get("archived_path", ""),
827
+ "resolved_path": entry.get("resolved_path", ""),
828
+ "skill_md_bytes": entry.get("skill_md_bytes", 0),
829
+ "companion_files": entry.get("companion_files", []),
830
+ "aliases": entry.get("aliases", [entry["name"]]),
831
+ "exact_name_hit": exact_name_hit,
832
+ })
833
+
834
+ results.sort(key=lambda r: (-r["score"], r["name"].lower()))
835
+ return results[:limit] if limit else results
836
+
837
+
838
+ def _resolve_skill_md_for_candidate(cand, archive_dir, base_dir=None):
839
+ """Locate readable SKILL.md path for a ranked candidate."""
840
+ raw_res = cand.get("resolved_path")
841
+ if raw_res:
842
+ p = Path(raw_res) / "SKILL.md"
843
+ if p.exists():
844
+ return p, Path(raw_res)
845
+ raw_arch = cand.get("archived_path")
846
+ if raw_arch:
847
+ skill_dir = _resolve_archived_skill_dir(base_dir, archive_dir, raw_arch)
848
+ p = skill_dir / "SKILL.md"
849
+ if p.exists():
850
+ return p, skill_dir
851
+ return None, None
852
+
853
+
854
+ def _truncate_skill_body(text, max_chars, skill_name):
855
+ """Truncate overly long SKILL.md cleanly on a line boundary with MCP load hint."""
856
+ if len(text) <= max_chars:
857
+ return text, False
858
+ cutoff = max(max_chars - 240, 500)
859
+ snippet = text[:cutoff]
860
+ last_nl = snippet.rfind("\n")
861
+ if last_nl > cutoff * 0.6:
862
+ snippet = snippet[:last_nl]
863
+ notice = (
864
+ f"\n\n[... truncated at {len(snippet)} chars to preserve context budget; "
865
+ f"call MCP load_skill(name=\"{skill_name}\") if remaining sections are needed ...]"
866
+ )
867
+ return snippet + notice, True
868
+
869
+
870
+ def route_prompt(
871
+ index_data,
872
+ prompt,
873
+ archive_dir,
874
+ base_dir=None,
875
+ workspace_categories=None,
876
+ exclude_names=None,
877
+ routing_config=None,
878
+ ):
879
+ """Select confidence-tiered skills (inline / pointer / none) and format injection text."""
880
+ cfg = dict(DEFAULT_ROUTING_CONFIG)
881
+ if routing_config:
882
+ cfg.update(routing_config)
883
+
884
+ empty_result = {
885
+ "inline": [],
886
+ "pointers": [],
887
+ "candidates": [],
888
+ "estimated_tokens": 0,
889
+ "injection_text": "",
890
+ "ui_notice": "",
891
+ "ambiguous": False,
892
+ }
893
+
894
+ if not cfg.get("enabled", True) or not (prompt or "").strip():
895
+ return empty_result
896
+
897
+ mode = str(cfg.get("mode", "hybrid")).lower()
898
+ min_pointer = float(cfg.get("min_score_pointer", 2.8))
899
+ min_inline = float(cfg.get("min_score_inline", 5.5))
900
+ max_inline = int(cfg.get("max_inline_skills", 2))
901
+ max_pointers = int(cfg.get("max_pointer_skills", 4))
902
+ max_inline_chars = int(cfg.get("max_inline_chars", 12000))
903
+ max_single_chars = int(cfg.get("max_single_skill_chars", 9000))
904
+ margin_ratio = float(cfg.get("inline_margin_ratio", 1.15))
905
+
906
+ always_excl = set(cfg.get("always_exclude", []) or [])
907
+ combined_excl = set(exclude_names or []) | always_excl
908
+
909
+ candidates = search_index(
910
+ index_data=index_data,
911
+ query=prompt,
912
+ workspace_categories=workspace_categories,
913
+ exclude_names=combined_excl,
914
+ limit=max(12, max_inline + max_pointers + 4),
915
+ routing_config=cfg,
916
+ )
917
+
918
+ viable = [c for c in candidates if c["score"] >= min_pointer]
919
+ if not viable:
920
+ empty_result["candidates"] = candidates
921
+ return empty_result
922
+
923
+ # Relative score floor: prune trailing weak noise far below the top match
924
+ top = viable[0]
925
+ rel_floor = max(min_pointer, top["score"] * 0.30)
926
+ viable = [c for c in viable if c["score"] >= rel_floor]
927
+
928
+ # Ambiguity check: if >=4 peers in the top skill's category tie closely without exact-name hit,
929
+ # demote all to compact pointers instead of guessing 2 arbitrary skills.
930
+ ambiguous = False
931
+ if not top.get("exact_name_hit"):
932
+ floor = top["score"] / max(margin_ratio, 1.01)
933
+ close_peers = [
934
+ c for c in viable
935
+ if c["category"] == top["category"] and c["score"] >= floor
936
+ ]
937
+ if len(close_peers) >= 4:
938
+ ambiguous = True
939
+
940
+ inline_items = []
941
+ pointer_items = []
942
+
943
+ if mode == "pointer" or ambiguous:
944
+ pointer_items = viable[: max_pointers + (max_inline if mode == "pointer" else 0)]
945
+ else:
946
+ remaining_chars = max_inline_chars
947
+ for cand in viable:
948
+ passes_inline_floor = cand["score"] >= min_inline or mode == "inline"
949
+ if len(inline_items) > 0 and cand["score"] < top["score"] * 0.45:
950
+ passes_inline_floor = False
951
+ should_try_inline = (
952
+ len(inline_items) < max_inline
953
+ and passes_inline_floor
954
+ and remaining_chars >= 600
955
+ )
956
+ if should_try_inline:
957
+ md_path, skill_dir = _resolve_skill_md_for_candidate(cand, archive_dir, base_dir)
958
+ if md_path and md_path.exists():
959
+ try:
960
+ raw_text = md_path.read_text(encoding="utf-8", errors="replace").strip()
961
+ except Exception:
962
+ raw_text = ""
963
+ if raw_text:
964
+ budget = min(max_single_chars, remaining_chars)
965
+ body_text, truncated = _truncate_skill_body(raw_text, budget, cand["name"])
966
+ item = dict(cand)
967
+ item["skill_dir"] = str(skill_dir)
968
+ item["skill_md_path"] = str(md_path)
969
+ item["content"] = body_text
970
+ item["truncated"] = truncated
971
+ inline_items.append(item)
972
+ remaining_chars -= len(body_text)
973
+ continue
974
+ if len(pointer_items) < max_pointers:
975
+ item = dict(cand)
976
+ _, skill_dir = _resolve_skill_md_for_candidate(cand, archive_dir, base_dir)
977
+ item["skill_dir"] = str(skill_dir) if skill_dir else cand.get("resolved_path", "")
978
+ pointer_items.append(item)
979
+
980
+ if not inline_items and not pointer_items:
981
+ empty_result["candidates"] = candidates
982
+ return empty_result
983
+
984
+ # Format compact injection block
985
+ sections = ["<skill_vault_context>"]
986
+ if inline_items:
987
+ sections.append(
988
+ "Relevant skills automatically loaded from cold storage (L2) for this request:"
989
+ )
990
+ for item in inline_items:
991
+ companions = item.get("companion_files", [])
992
+ comp_str = ", ".join(companions[:12])
993
+ if len(companions) > 12:
994
+ comp_str += f", ... (+{len(companions) - 12} more)"
995
+ sections.append(
996
+ f'<skill name="{item["name"]}" category="{item["category"]}" base_dir="{item["skill_dir"]}">'
997
+ )
998
+ if comp_str:
999
+ sections.append(
1000
+ f"[Companion files inside base_dir (load via MCP load_skill or read_file): {comp_str}]"
1001
+ )
1002
+ sections.append(item["content"])
1003
+ sections.append("</skill>")
1004
+
1005
+ if pointer_items:
1006
+ sections.append("<available_vault_skills>")
1007
+ sections.append(
1008
+ "Additional matching vaulted skills (call MCP load_skill(name) or read SKILL.md if needed):"
1009
+ )
1010
+ for item in pointer_items:
1011
+ desc = item.get("description", "").strip()
1012
+ short_desc = desc[:130] + "..." if len(desc) > 130 else desc
1013
+ skill_md_loc = str(Path(item["skill_dir"]) / "SKILL.md") if item.get("skill_dir") else item.get("archived_path", "")
1014
+ sections.append(
1015
+ f'- **{item["name"]}** [{item["category"]}]: {short_desc} (`{skill_md_loc}`)'
1016
+ )
1017
+ sections.append("</available_vault_skills>")
1018
+
1019
+ sections.append("</skill_vault_context>")
1020
+ injection_text = "\n".join(sections)
1021
+ est_tokens = max(1, len(injection_text) // 4)
1022
+
1023
+ inlined_names = [i["name"] for i in inline_items]
1024
+ pointed_names = [p["name"] for p in pointer_items]
1025
+ notice_parts = []
1026
+ if inlined_names:
1027
+ notice_parts.append("Loaded: " + ", ".join(f"`{n}`" for n in inlined_names))
1028
+ if pointed_names:
1029
+ notice_parts.append("Available: " + ", ".join(f"`{n}`" for n in pointed_names))
1030
+ ui_notice = f"*Skill Vault:* {' | '.join(notice_parts)}" if notice_parts else ""
1031
+
1032
+ return {
1033
+ "inline": inline_items,
1034
+ "pointers": pointer_items,
1035
+ "candidates": candidates,
1036
+ "estimated_tokens": est_tokens,
1037
+ "injection_text": injection_text,
1038
+ "ui_notice": ui_notice,
1039
+ "ambiguous": ambiguous,
1040
+ }
1041
+
1042
+
1043
+ # --- Per-Conversation State, Workspace Cache & Telemetry ---
1044
+
1045
+
1046
+ def _state_dir(archive_dir):
1047
+ d = Path(archive_dir).resolve() / ".state"
1048
+ d.mkdir(parents=True, exist_ok=True)
1049
+ return d
1050
+
1051
+
1052
+ def _atomic_write_json(path, data):
1053
+ path = Path(path)
1054
+ path.parent.mkdir(parents=True, exist_ok=True)
1055
+ tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
1056
+ with open(tmp, "w", encoding="utf-8") as f:
1057
+ json.dump(data, f, ensure_ascii=False)
1058
+ os.replace(tmp, path)
1059
+
1060
+
1061
+ class ConversationState:
1062
+ """Manages per-conversation routing state for same-turn short-circuit & cross-turn dedup."""
1063
+
1064
+ def __init__(self, archive_dir, conversation_id):
1065
+ self.state_dir = _state_dir(archive_dir)
1066
+ cid = str(conversation_id or "default")
1067
+ digest = hashlib.sha256(cid.encode("utf-8", errors="ignore")).hexdigest()[:16]
1068
+ self.path = self.state_dir / f"conv_{digest}.json"
1069
+ self.data = self._load()
1070
+
1071
+ def _load(self):
1072
+ if self.path.exists():
1073
+ try:
1074
+ with open(self.path, "r", encoding="utf-8") as f:
1075
+ data = json.load(f)
1076
+ if isinstance(data, dict):
1077
+ return data
1078
+ except Exception:
1079
+ pass
1080
+ return {
1081
+ "last_input_hash": None,
1082
+ "last_initial_steps": None,
1083
+ "injected_skills": [],
1084
+ "pointed_skills": [],
1085
+ "updated_at": 0.0,
1086
+ }
1087
+
1088
+ def save(self):
1089
+ self.data["updated_at"] = time.time()
1090
+ _atomic_write_json(self.path, self.data)
1091
+
1092
+ def should_short_circuit(self, input_hash, invocation_num=None, initial_num_steps=None):
1093
+ """Return True if this PreInvocation call repeats the same user input."""
1094
+ return self.data.get("last_input_hash") == input_hash
1095
+
1096
+ def get_excluded_skills(self):
1097
+ return set(self.data.get("injected_skills", [])) | set(self.data.get("pointed_skills", []))
1098
+
1099
+ def record_turn(self, input_hash, initial_num_steps, inline_keys, pointer_keys):
1100
+ self.data["last_input_hash"] = input_hash
1101
+ self.data["last_initial_steps"] = initial_num_steps
1102
+ injected = list(dict.fromkeys(list(self.data.get("injected_skills", [])) + list(inline_keys)))
1103
+ pointed = list(dict.fromkeys(list(self.data.get("pointed_skills", [])) + list(pointer_keys)))
1104
+ self.data["injected_skills"] = injected
1105
+ self.data["pointed_skills"] = pointed
1106
+ self.save()
1107
+
1108
+
1109
+ def prune_old_states(archive_dir, max_age_days=7):
1110
+ """Remove stale conversation state files older than max_age_days."""
1111
+ state_dir = Path(archive_dir).resolve() / ".state"
1112
+ if not state_dir.exists():
1113
+ return 0
1114
+ cutoff = time.time() - (max_age_days * 86400.0)
1115
+ removed = 0
1116
+ for f in state_dir.glob("conv_*.json"):
1117
+ try:
1118
+ if f.stat().st_mtime < cutoff:
1119
+ f.unlink()
1120
+ removed += 1
1121
+ except OSError:
1122
+ pass
1123
+ return removed
1124
+
1125
+
1126
+ def get_cached_workspace_categories(archive_dir, workspace_paths, ttl_seconds=600):
1127
+ """Retrieve cached workspace categories if still within TTL."""
1128
+ if not workspace_paths:
1129
+ return None
1130
+ state_dir = _state_dir(archive_dir)
1131
+ key = hashlib.sha256("|".join(sorted(str(p) for p in workspace_paths)).encode("utf-8")).hexdigest()[:16]
1132
+ cache_file = state_dir / "ws_cache.json"
1133
+ if not cache_file.exists():
1134
+ return None
1135
+ try:
1136
+ with open(cache_file, "r", encoding="utf-8") as f:
1137
+ cache = json.load(f)
1138
+ entry = cache.get(key)
1139
+ if entry and (time.time() - float(entry.get("ts", 0.0))) <= ttl_seconds:
1140
+ return list(entry.get("categories", []))
1141
+ except Exception:
1142
+ pass
1143
+ return None
1144
+
1145
+
1146
+ def cache_workspace_categories(archive_dir, workspace_paths, categories):
1147
+ """Persist detected workspace categories for fast lookup in PreInvocation."""
1148
+ if not workspace_paths:
1149
+ return
1150
+ state_dir = _state_dir(archive_dir)
1151
+ key = hashlib.sha256("|".join(sorted(str(p) for p in workspace_paths)).encode("utf-8")).hexdigest()[:16]
1152
+ cache_file = state_dir / "ws_cache.json"
1153
+ cache = {}
1154
+ if cache_file.exists():
1155
+ try:
1156
+ with open(cache_file, "r", encoding="utf-8") as f:
1157
+ loaded = json.load(f)
1158
+ if isinstance(loaded, dict):
1159
+ cache = loaded
1160
+ except Exception:
1161
+ cache = {}
1162
+
1163
+ now = time.time()
1164
+ cache = {k: v for k, v in cache.items() if now - float(v.get("ts", 0.0)) < 86400}
1165
+ cache[key] = {"ts": now, "categories": sorted(set(categories))}
1166
+ _atomic_write_json(cache_file, cache)
1167
+
1168
+
1169
+ def log_routing_event(archive_dir, record, max_lines=1000):
1170
+ """Append a privacy-preserving telemetry record (no raw prompts) to routing_log.jsonl."""
1171
+ state_dir = _state_dir(archive_dir)
1172
+ log_file = state_dir / "routing_log.jsonl"
1173
+ line = json.dumps(record, ensure_ascii=False)
1174
+ try:
1175
+ lines = []
1176
+ if log_file.exists():
1177
+ with open(log_file, "r", encoding="utf-8", errors="replace") as f:
1178
+ lines = f.read().splitlines()
1179
+ lines.append(line)
1180
+ if len(lines) > max_lines:
1181
+ lines = lines[-max_lines:]
1182
+ tmp = state_dir / f".routing_log.{os.getpid()}.tmp"
1183
+ with open(tmp, "w", encoding="utf-8") as f:
1184
+ f.write("\n".join(lines) + "\n")
1185
+ os.replace(tmp, log_file)
1186
+ except OSError:
1187
+ pass