@jcorpac/skill-vault 1.7.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1159 @@
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
+ }
124
+
125
+ # Broad tech terms that should not trigger skill injection on their own as a solo 1-token query
126
+ GENERIC_SINGLE_TOKENS = {
127
+ "python", "javascript", "typescript", "java", "golang", "rust", "ruby", "php", "csharp",
128
+ "cpp", "html", "css", "json", "yaml", "toml", "xml", "csv", "sql", "bash", "shell",
129
+ "powershell", "pwsh", "markdown", "linux", "windows", "macos", "git", "github", "cloud",
130
+ "database", "databases", "storage", "query", "queries", "table", "tables", "schema",
131
+ "debug", "debugging", "optimize", "optimization", "performance", "security", "audit",
132
+ "monitor", "monitoring", "health", "access", "admin", "backup", "layout", "widget",
133
+ "widgets", "component", "components", "container", "containers", "cluster", "clusters",
134
+ "deploy", "deployment", "pipeline", "pipelines", "notebook", "notebooks", "graph",
135
+ "report", "draft", "resolve", "mobile", "web", "frontend", "backend", "api", "apis",
136
+ "server", "client", "network", "auth", "authentication", "replication", "migration",
137
+ "analysis", "analyze", "analytics", "extension", "extensions", "preview", "device",
138
+ "rules", "rule", "slow", "fast", "faster", "practices", "practice",
139
+ "distributed", "distribute", "distribution", "dependent", "depends", "depend",
140
+ "dependencies", "dependency", "architecture", "architectural", "improvement", "improvements",
141
+ "publish", "published", "publishing", "npm", "safe", "safely", "safety",
142
+ "package", "packages", "install", "library", "libraries", "framework", "frameworks",
143
+ }
144
+
145
+ _STEM_SUFFIXES = (
146
+ ("ization", "ize"),
147
+ ("ations", "ate"),
148
+ ("ation", "ate"),
149
+ ("ities", "ity"),
150
+ ("ments", "ment"),
151
+ ("iness", "y"),
152
+ ("ies", "y"),
153
+ ("ing", ""),
154
+ ("ers", "er"),
155
+ ("ed", ""),
156
+ ("es", ""),
157
+ ("s", ""),
158
+ )
159
+
160
+
161
+ def _light_stem(token):
162
+ """Apply conservative suffix normalization for English plurals/verb forms."""
163
+ if len(token) < 5 or any(ch in token for ch in (".", "-", "_")) or any(ch.isdigit() for ch in token):
164
+ return token
165
+ if token.endswith(("ss", "us", "is", "os", "gres", "etes", "ias")):
166
+ return token
167
+ for suffix, repl in _STEM_SUFFIXES:
168
+ if token.endswith(suffix):
169
+ stem = token[: -len(suffix)] + repl
170
+ if len(stem) >= 4:
171
+ return stem
172
+ break
173
+ return token
174
+
175
+
176
+ def _is_valid_token(tok):
177
+ """Return True if token carries meaningful domain signal."""
178
+ if not tok or tok in STOPWORDS:
179
+ return False
180
+ has_alpha = any("a" <= ch <= "z" for ch in tok)
181
+ if not has_alpha:
182
+ return False
183
+ if len(tok) >= 3:
184
+ return True
185
+ if tok in SHORT_DOMAIN_TOKENS:
186
+ return True
187
+ if any(ch.isdigit() for ch in tok) and len(tok) >= 2:
188
+ return True
189
+ return False
190
+
191
+
192
+ def tokenize(text, include_stems=True):
193
+ """Extract normalized domain tokens from text while preserving compound identifiers."""
194
+ if not text:
195
+ return []
196
+
197
+ lowered = text.lower()
198
+ raw_chunks = re.findall(r"[a-z0-9]+(?:[._/-][a-z0-9]+)*", lowered)
199
+ tokens = []
200
+
201
+ for chunk in raw_chunks:
202
+ chunk_clean = chunk.strip("._/-")
203
+ if not chunk_clean:
204
+ continue
205
+
206
+ # Preserve compound filenames/commands/identifiers like firestore.rules, alloydb-omni
207
+ if any(sep in chunk_clean for sep in (".", "-", "_")) and "/" not in chunk_clean:
208
+ if _is_valid_token(chunk_clean):
209
+ tokens.append(chunk_clean)
210
+
211
+ parts = re.split(r"[._/\-]+", chunk_clean)
212
+ for part in parts:
213
+ if _is_valid_token(part):
214
+ tokens.append(part)
215
+ if include_stems:
216
+ stemmed = _light_stem(part)
217
+ if stemmed != part and _is_valid_token(stemmed):
218
+ tokens.append(stemmed)
219
+
220
+ return tokens
221
+
222
+
223
+ def canonicalize_skill_name(name):
224
+ """Return canonical deduplication key normalizing case and underscore/hyphen differences."""
225
+ return str(name or "").strip().lower().replace("_", "-")
226
+
227
+
228
+ def _parse_version_tuple(ver_str):
229
+ if not ver_str:
230
+ return None
231
+ cleaned = str(ver_str).strip().strip("'\"").lstrip("vV")
232
+ nums = re.findall(r"\d+", cleaned)
233
+ return tuple(int(n) for n in nums) if nums else None
234
+
235
+
236
+ def _parse_frontmatter(content):
237
+ """Parse YAML frontmatter fields from SKILL.md without external YAML dependencies."""
238
+ fm_match = re.match(r"^---\s*\n(.*?)\n---(?:\s*\n|\s*\Z)", content, re.DOTALL)
239
+ if not fm_match:
240
+ return {}, content
241
+
242
+ fm_text = fm_match.group(1)
243
+ body = content[fm_match.end():]
244
+ meta = {}
245
+
246
+ # Scalar fields
247
+ for field in ("name", "version", "category"):
248
+ m = re.search(rf"^{field}:\s*([^\n]+)", fm_text, re.MULTILINE | re.IGNORECASE)
249
+ if m:
250
+ val = m.group(1).strip().strip("'\"")
251
+ if val:
252
+ meta[field] = val
253
+
254
+ # Description (supports folded/literal YAML blocks and inline scalars)
255
+ desc_match = re.search(
256
+ r"^description:\s*(?:>[-+]?|\|[-+]?)?\s*\n?(.*?)(?=\n[a-zA-Z0-9_-]+:|\Z)",
257
+ fm_text,
258
+ re.DOTALL | re.MULTILINE | re.IGNORECASE,
259
+ )
260
+ if desc_match:
261
+ raw_desc = desc_match.group(1).strip()
262
+ meta["description"] = " ".join(
263
+ line.strip().strip("'\"") for line in raw_desc.splitlines() if line.strip()
264
+ )
265
+
266
+ # List or comma-separated fields: tags, triggers, globs
267
+ for list_field in ("tags", "triggers", "globs"):
268
+ block_match = re.search(
269
+ rf"^{list_field}:\s*(.*?)(?=\n[a-zA-Z0-9_-]+:|\Z)",
270
+ fm_text,
271
+ re.DOTALL | re.MULTILINE | re.IGNORECASE,
272
+ )
273
+ if block_match:
274
+ raw_val = block_match.group(1).strip()
275
+ raw_val = raw_val.strip("[]")
276
+ items = []
277
+ for part in re.split(r"[\n,]+", raw_val):
278
+ cleaned = re.sub(r"^\s*-\s*", "", part).strip().strip("'\"")
279
+ if cleaned:
280
+ items.append(cleaned)
281
+ if items:
282
+ meta[list_field] = items
283
+
284
+ return meta, body
285
+
286
+
287
+ def _list_companion_files(skill_dir, max_files=30):
288
+ """List companion files (references/, scripts/, examples/, resources/) in POSIX relative form."""
289
+ skill_dir = Path(skill_dir)
290
+ if not skill_dir.exists():
291
+ return []
292
+ companions = []
293
+ for root, dirs, files in os.walk(skill_dir):
294
+ root_path = Path(root)
295
+ dirs[:] = sorted(
296
+ d for d in dirs
297
+ if d not in {"__pycache__", ".git", "node_modules"}
298
+ and not (root_path / d / "SKILL.md").exists()
299
+ )
300
+ for fname in sorted(files):
301
+ fpath = root_path / fname
302
+ if root_path == skill_dir and fname == "SKILL.md":
303
+ continue
304
+ try:
305
+ rel = fpath.relative_to(skill_dir).as_posix()
306
+ companions.append(rel)
307
+ if len(companions) >= max_files:
308
+ return companions
309
+ except ValueError:
310
+ pass
311
+ return companions
312
+
313
+
314
+ def _extract_skill_fields(skill_name, category, skill_dir, skill_md_path):
315
+ """Extract weighted token frequency maps and metadata from a skill's SKILL.md."""
316
+ try:
317
+ content = Path(skill_md_path).read_text(encoding="utf-8", errors="replace")
318
+ except Exception:
319
+ content = ""
320
+
321
+ meta, body = _parse_frontmatter(content)
322
+ description = meta.get("description") or "No description available."
323
+ ver_tuple = _parse_version_tuple(meta.get("version"))
324
+
325
+ # 1. Name terms (deduplicate skill_name vs meta['name'] to avoid artificial tf=2 inflation)
326
+ meta_name = meta.get("name", "")
327
+ name_input = skill_name if not meta_name or meta_name.strip().lower() == skill_name.strip().lower() else f"{skill_name} {meta_name}"
328
+ name_tokens = tokenize(name_input)
329
+ name_tf = dict(Counter(name_tokens))
330
+
331
+ # 2. Explicit author-declared frontmatter tag / trigger / glob terms ONLY
332
+ tag_inputs = []
333
+ for lf in ("tags", "triggers", "globs"):
334
+ if lf in meta:
335
+ tag_inputs.extend(meta[lf])
336
+ tag_tf = dict(Counter(tokenize(" ".join(tag_inputs))))
337
+
338
+ # 3. Description terms
339
+ desc_tf = dict(Counter(tokenize(description)))
340
+
341
+ # 4. Headings + Category terms
342
+ headings = re.findall(r"^#{1,3}\s+(.+)$", body, re.MULTILINE)
343
+ heading_text = f"{category} " + " ".join(headings)
344
+ heading_tf = dict(Counter(tokenize(heading_text)))
345
+
346
+ # 5. Distinctive body terms + selective technical inline code identifiers (top 60)
347
+ inline_code = re.findall(r"`([^`\n]{2,60})`", body)
348
+ code_tokens = tokenize(" ".join(inline_code))
349
+ seen_code = []
350
+ seen_code_set = set()
351
+ for tok in code_tokens:
352
+ is_distinctive = (
353
+ any(ch in tok for ch in (".", "-", "_"))
354
+ or any(ch.isdigit() for ch in tok)
355
+ or tok not in GENERIC_SINGLE_TOKENS
356
+ )
357
+ if is_distinctive and tok not in seen_code_set:
358
+ seen_code_set.add(tok)
359
+ seen_code.append(tok)
360
+ if len(seen_code) >= 40:
361
+ break
362
+
363
+ body_clean = re.sub(r"```.*?```", " ", body, flags=re.DOTALL)
364
+ body_counts = Counter(tokenize(body_clean) + seen_code)
365
+ body_tf = dict(body_counts.most_common(60))
366
+
367
+ # Compute mtime safely without bleeding nested sibling skills
368
+ latest_mtime = 0.0
369
+ try:
370
+ skill_dir_path = Path(skill_dir)
371
+ mtimes = []
372
+ if Path(skill_md_path).exists():
373
+ mtimes.append(Path(skill_md_path).stat().st_mtime)
374
+ if skill_dir_path.exists():
375
+ for root, dirs, files in os.walk(skill_dir_path):
376
+ rp = Path(root)
377
+ dirs[:] = [d for d in dirs if not (rp / d / "SKILL.md").exists()]
378
+ for fn in files:
379
+ try:
380
+ mtimes.append((rp / fn).stat().st_mtime)
381
+ except OSError:
382
+ pass
383
+ if mtimes:
384
+ latest_mtime = max(mtimes)
385
+ except OSError:
386
+ pass
387
+
388
+ skill_md_bytes = 0
389
+ try:
390
+ skill_md_bytes = Path(skill_md_path).stat().st_size
391
+ except OSError:
392
+ skill_md_bytes = len(content.encode("utf-8", errors="ignore"))
393
+
394
+ return {
395
+ "name": skill_name,
396
+ "canonical_key": canonicalize_skill_name(skill_name),
397
+ "category": category or "General & Utility Skills",
398
+ "description": description,
399
+ "version_tuple": list(ver_tuple) if ver_tuple is not None else None,
400
+ "mtime": latest_mtime,
401
+ "skill_md_bytes": skill_md_bytes,
402
+ "companion_files": _list_companion_files(skill_dir),
403
+ "fields": {
404
+ "name_terms": name_tf,
405
+ "tag_terms": tag_tf,
406
+ "desc_terms": desc_tf,
407
+ "heading_terms": heading_tf,
408
+ "body_terms": body_tf,
409
+ },
410
+ }
411
+
412
+
413
+ def _is_newer_entry(cand, existing):
414
+ """Return True if cand entry is strictly newer/preferred over existing entry."""
415
+ va = cand.get("version_tuple")
416
+ vb = existing.get("version_tuple")
417
+ if va is not None and vb is not None and va != vb:
418
+ return tuple(va) > tuple(vb)
419
+ if va is not None and vb is None:
420
+ return True
421
+ if va is None and vb is not None:
422
+ return False
423
+
424
+ ma = cand.get("mtime", 0.0)
425
+ mb = existing.get("mtime", 0.0)
426
+ if abs(ma - mb) > 1.0:
427
+ return ma > mb
428
+
429
+ # Tie-breaker: prefer hyphenated names over underscored names
430
+ cand_hyphen = "-" in cand["name"] and "_" not in cand["name"]
431
+ exist_hyphen = "-" in existing["name"] and "_" not in existing["name"]
432
+ if cand_hyphen != exist_hyphen:
433
+ return cand_hyphen
434
+ return cand["name"] < existing["name"]
435
+
436
+
437
+ def _resolve_archived_skill_dir(base_dir, archive_dir, raw_archived_path):
438
+ """Resolve an archived_path stored in manifest across relative/absolute layouts."""
439
+ p = Path(raw_archived_path)
440
+ if p.is_absolute():
441
+ return p
442
+ if base_dir is not None:
443
+ cand = (Path(base_dir) / p).resolve()
444
+ if cand.exists():
445
+ return cand
446
+ cand2 = (Path(archive_dir).parent / p).resolve()
447
+ if cand2.exists():
448
+ return cand2
449
+ return (Path(archive_dir) / p).resolve()
450
+
451
+
452
+ def build_search_index(archive_dir, manifest, base_dir=None, resolve_path_fn=None):
453
+ """Build and atomically persist search_index.json from backup_manifest.json."""
454
+ archive_path = Path(archive_dir).resolve()
455
+ archive_path.mkdir(parents=True, exist_ok=True)
456
+ manifest_file = archive_path / "backup_manifest.json"
457
+ manifest_mtime = manifest_file.stat().st_mtime if manifest_file.exists() else time.time()
458
+
459
+ deduped = {}
460
+ for item in manifest:
461
+ name = item.get("name")
462
+ raw_arch = item.get("archived_path", "")
463
+ if not name or not raw_arch:
464
+ continue
465
+ if resolve_path_fn is not None:
466
+ skill_dir = Path(resolve_path_fn(raw_arch))
467
+ else:
468
+ skill_dir = _resolve_archived_skill_dir(base_dir, archive_path, raw_arch)
469
+
470
+ skill_md = skill_dir / "SKILL.md"
471
+ if not skill_md.exists():
472
+ continue
473
+
474
+ entry = _extract_skill_fields(
475
+ skill_name=name,
476
+ category=item.get("category") or "General & Utility Skills",
477
+ skill_dir=skill_dir,
478
+ skill_md_path=skill_md,
479
+ )
480
+ entry["archived_path"] = raw_arch
481
+ entry["resolved_path"] = str(skill_dir)
482
+ entry["aliases"] = [name]
483
+
484
+ ckey = entry["canonical_key"]
485
+ if ckey not in deduped:
486
+ deduped[ckey] = entry
487
+ else:
488
+ existing = deduped[ckey]
489
+ aliases = list(dict.fromkeys(existing.get("aliases", []) + [name]))
490
+ if _is_newer_entry(entry, existing):
491
+ entry["aliases"] = aliases
492
+ deduped[ckey] = entry
493
+ else:
494
+ existing["aliases"] = aliases
495
+
496
+ skills_list = sorted(deduped.values(), key=lambda x: x["name"].lower())
497
+ doc_count = len(skills_list)
498
+
499
+ # Compute document frequency (across any field per skill) and average field lengths
500
+ df = Counter()
501
+ field_totals = {f: 0 for f in FIELD_WEIGHTS}
502
+
503
+ for entry in skills_list:
504
+ seen_terms = set()
505
+ for fname in FIELD_WEIGHTS:
506
+ tf_map = entry["fields"].get(fname, {})
507
+ field_totals[fname] += sum(tf_map.values())
508
+ seen_terms.update(tf_map.keys())
509
+ for term in seen_terms:
510
+ df[term] += 1
511
+
512
+ avg_len = {
513
+ fname: (field_totals[fname] / doc_count) if doc_count > 0 else 1.0
514
+ for fname in FIELD_WEIGHTS
515
+ }
516
+ for fname in avg_len:
517
+ if avg_len[fname] <= 0:
518
+ avg_len[fname] = 1.0
519
+
520
+ index_data = {
521
+ "schema_version": INDEX_SCHEMA_VERSION,
522
+ "built_at": time.time(),
523
+ "manifest_mtime": manifest_mtime,
524
+ "doc_count": doc_count,
525
+ "avg_len": avg_len,
526
+ "df": dict(df),
527
+ "skills": skills_list,
528
+ }
529
+
530
+ index_file = archive_path / "search_index.json"
531
+ tmp_file = archive_path / f".search_index.{os.getpid()}.tmp"
532
+ with open(tmp_file, "w", encoding="utf-8") as f:
533
+ json.dump(index_data, f, ensure_ascii=False)
534
+ os.replace(tmp_file, index_file)
535
+ return index_data
536
+
537
+
538
+ def load_or_build_index(archive_dir, base_dir=None, resolve_path_fn=None):
539
+ """Load pre-built search_index.json in <5ms, or rebuild lazily if missing/stale."""
540
+ archive_path = Path(archive_dir).resolve()
541
+ index_file = archive_path / "search_index.json"
542
+ manifest_file = archive_path / "backup_manifest.json"
543
+ manifest_mtime = manifest_file.stat().st_mtime if manifest_file.exists() else 0.0
544
+
545
+ if index_file.exists():
546
+ try:
547
+ with open(index_file, "r", encoding="utf-8") as f:
548
+ data = json.load(f)
549
+ if (
550
+ isinstance(data, dict)
551
+ and data.get("schema_version") == INDEX_SCHEMA_VERSION
552
+ and float(data.get("manifest_mtime", 0.0)) >= manifest_mtime - 0.5
553
+ ):
554
+ return data
555
+ except Exception:
556
+ pass
557
+
558
+ manifest = []
559
+ if manifest_file.exists():
560
+ try:
561
+ with open(manifest_file, "r", encoding="utf-8") as f:
562
+ manifest = json.load(f)
563
+ except Exception:
564
+ manifest = []
565
+
566
+ return build_search_index(
567
+ archive_dir=archive_path,
568
+ manifest=manifest,
569
+ base_dir=base_dir,
570
+ resolve_path_fn=resolve_path_fn,
571
+ )
572
+
573
+
574
+ def _normalized_idf(df_val, doc_count):
575
+ """Compute corpus-size-normalized BM25 IDF so thresholds stay calibrated from N=10 to N=1000+."""
576
+ if doc_count <= 0:
577
+ return 0.0
578
+ raw = math.log((doc_count - df_val + 0.5) / (df_val + 0.5) + 1.0)
579
+ scale = 3.2 / math.log(max(doc_count, 5) + 1.0)
580
+ return raw * scale
581
+
582
+
583
+ def search_index(
584
+ index_data,
585
+ query,
586
+ category=None,
587
+ workspace_categories=None,
588
+ exclude_names=None,
589
+ limit=10,
590
+ routing_config=None,
591
+ ):
592
+ """Score indexed skills using multi-field BM25 + exact-name + coverage + workspace tie-breaker."""
593
+ cfg = dict(DEFAULT_ROUTING_CONFIG)
594
+ if routing_config:
595
+ cfg.update(routing_config)
596
+
597
+ skills = index_data.get("skills", [])
598
+ doc_count = index_data.get("doc_count", len(skills))
599
+ avg_len = index_data.get("avg_len", {f: 1.0 for f in FIELD_WEIGHTS})
600
+ df_map = index_data.get("df", {})
601
+
602
+ exclude_canon = {canonicalize_skill_name(n) for n in (exclude_names or []) if n}
603
+ ws_cats = set(workspace_categories or [])
604
+ ws_boost = float(cfg.get("workspace_boost", 1.35))
605
+
606
+ raw_query = (query or "").strip().lower()
607
+ raw_query_norm = re.sub(r"[-_]+", " ", raw_query)
608
+ # Extract distinct semantic concepts without summing base + stem duplicates
609
+ concept_tokens = list(dict.fromkeys(tokenize(query, include_stems=False)))
610
+
611
+ if not concept_tokens and not category:
612
+ return []
613
+
614
+ specific_concepts = [
615
+ c for c in concept_tokens
616
+ if c not in GENERIC_SINGLE_TOKENS
617
+ and (df_map.get(c, 0) > 0 or df_map.get(_light_stem(c), 0) > 0)
618
+ ]
619
+
620
+ k1 = 1.2
621
+ results = []
622
+
623
+ for entry in skills:
624
+ ckey = entry.get("canonical_key") or canonicalize_skill_name(entry.get("name"))
625
+ if ckey in exclude_canon:
626
+ continue
627
+
628
+ entry_cat = entry.get("category", "General & Utility Skills")
629
+ if category and entry_cat.lower() != category.strip().lower():
630
+ continue
631
+
632
+ if not concept_tokens and category:
633
+ results.append({
634
+ "name": entry["name"],
635
+ "canonical_key": ckey,
636
+ "category": entry_cat,
637
+ "score": 10.0,
638
+ "matched_terms": [],
639
+ "description": entry.get("description", ""),
640
+ "archived_path": entry.get("archived_path", ""),
641
+ "resolved_path": entry.get("resolved_path", ""),
642
+ "skill_md_bytes": entry.get("skill_md_bytes", 0),
643
+ "companion_files": entry.get("companion_files", []),
644
+ "aliases": entry.get("aliases", [entry["name"]]),
645
+ "exact_name_hit": False,
646
+ })
647
+ continue
648
+
649
+ fields = entry.get("fields", {})
650
+ cat_tokens = set(tokenize(entry_cat, include_stems=False))
651
+ bm25_score = 0.0
652
+ matched_terms = []
653
+ matched_in_name = False
654
+ matched_in_tags = False
655
+ matched_in_desc_or_head = False
656
+ matched_concepts = set()
657
+ matched_specific = 0
658
+ high_signal_hits = 0
659
+ matched_name_concepts = 0
660
+ matched_non_generic_in_name_or_tag = False
661
+ matched_category_token = False
662
+ matched_non_generic_desc = 0
663
+
664
+ for ctok in concept_tokens:
665
+ forms = list(dict.fromkeys([ctok, _light_stem(ctok)]))
666
+ best_form_score = 0.0
667
+ form_name = False
668
+ form_tag = False
669
+ form_desc_or_head = False
670
+ form_high = False
671
+
672
+ for f_tok in forms:
673
+ df_val = df_map.get(f_tok, 0)
674
+ if df_val == 0:
675
+ continue
676
+ idf = _normalized_idf(df_val, doc_count)
677
+ field_scores = []
678
+
679
+ for fname, weight in FIELD_WEIGHTS.items():
680
+ tf_map = fields.get(fname, {})
681
+ tf = tf_map.get(f_tok, 0)
682
+ if tf <= 0:
683
+ continue
684
+ if fname == "name_terms":
685
+ form_name = True
686
+ form_high = True
687
+ elif fname == "tag_terms":
688
+ form_tag = True
689
+ form_high = True
690
+ elif fname in ("desc_terms", "heading_terms"):
691
+ form_desc_or_head = True
692
+ form_high = True
693
+
694
+ dl = max(sum(tf_map.values()), 1)
695
+ adl = max(float(avg_len.get(fname, 1.0)), 1.0)
696
+ b_val = 0.25 if fname == "name_terms" else 0.75
697
+ tf_norm = (tf * (k1 + 1.0)) / (tf + k1 * (1.0 - b_val + b_val * dl / adl))
698
+ field_scores.append(weight * idf * tf_norm)
699
+
700
+ if field_scores:
701
+ field_scores.sort(reverse=True)
702
+ blended = min(
703
+ field_scores[0] * 1.35,
704
+ field_scores[0] + 0.20 * sum(field_scores[1:]),
705
+ )
706
+ if idf >= 2.0 and (form_name or form_tag):
707
+ blended *= 1.15
708
+ if blended > best_form_score:
709
+ best_form_score = blended
710
+
711
+ if best_form_score > 0.0:
712
+ bm25_score += best_form_score
713
+ matched_terms.append(ctok)
714
+ matched_concepts.add(ctok)
715
+ is_non_generic = ctok not in GENERIC_SINGLE_TOKENS
716
+ if ctok in specific_concepts:
717
+ matched_specific += 1
718
+ if form_name:
719
+ matched_in_name = True
720
+ matched_name_concepts += 1
721
+ if form_tag:
722
+ matched_in_tags = True
723
+ if is_non_generic and (form_name or form_tag):
724
+ matched_non_generic_in_name_or_tag = True
725
+ if is_non_generic and ctok in cat_tokens:
726
+ matched_category_token = True
727
+ if is_non_generic and form_desc_or_head:
728
+ matched_non_generic_desc += 1
729
+ if form_high:
730
+ if not (form_name or form_tag):
731
+ matched_in_desc_or_head = True
732
+ high_signal_hits += 1
733
+
734
+ # Exact skill name / alias hit check
735
+ exact_name_hit = False
736
+ for alias in entry.get("aliases", [entry["name"]]):
737
+ alias_l = alias.lower()
738
+ alias_spaces = re.sub(r"[-_]+", " ", alias_l)
739
+ if (
740
+ len(alias_l) >= 4
741
+ and (
742
+ re.search(rf"(?<![a-z0-9]){re.escape(alias_l)}(?![a-z0-9])", raw_query)
743
+ or re.search(rf"(?<![a-z0-9]){re.escape(alias_spaces)}(?![a-z0-9])", raw_query_norm)
744
+ )
745
+ ):
746
+ exact_name_hit = True
747
+ break
748
+
749
+ if exact_name_hit:
750
+ bm25_score += 10.0
751
+
752
+ # Multi-term coverage bonus when >=2 distinct prompt concepts hit high-signal fields
753
+ if high_signal_hits >= 2:
754
+ bm25_score += 1.5 * (high_signal_hits - 1)
755
+
756
+ # Dominant-concept gate & identity-anchor guards to keep unrelated conversational prompts at 0 tokens
757
+ if not exact_name_hit and specific_concepts and matched_specific == 0:
758
+ bm25_score *= 0.20
759
+ elif not exact_name_hit and len(matched_concepts) <= 1 and bm25_score > 0:
760
+ only_tok = next(iter(matched_concepts)) if matched_concepts else ""
761
+ df_ratio = (df_map.get(only_tok, 0) / doc_count) if doc_count > 0 else 0.0
762
+ only_body = not (matched_in_name or matched_in_tags or matched_in_desc_or_head)
763
+ not_name_or_tag = not (matched_in_name or matched_in_tags)
764
+
765
+ if only_tok in GENERIC_SINGLE_TOKENS and only_tok != ckey:
766
+ bm25_score *= 0.15
767
+ elif only_body:
768
+ bm25_score *= 0.25
769
+ elif df_ratio > 0.35 or (df_ratio > 0.20 and not matched_in_name):
770
+ bm25_score *= 0.30
771
+ elif not_name_or_tag and len(concept_tokens) >= 2:
772
+ bm25_score *= 0.45
773
+ elif not exact_name_hit and matched_concepts and all(c in GENERIC_SINGLE_TOKENS for c in matched_concepts):
774
+ if matched_name_concepts < 2:
775
+ bm25_score *= 0.20
776
+ elif (
777
+ not exact_name_hit
778
+ and matched_concepts
779
+ and not matched_non_generic_in_name_or_tag
780
+ and not matched_category_token
781
+ and matched_non_generic_desc < 2
782
+ and matched_name_concepts < 2
783
+ ):
784
+ bm25_score *= 0.30
785
+
786
+ # Soft workspace tie-breaker ONLY when prompt already has real signal
787
+ if bm25_score > 0.5 and entry_cat in ws_cats:
788
+ bm25_score *= ws_boost
789
+
790
+ if bm25_score > 0.0:
791
+ results.append({
792
+ "name": entry["name"],
793
+ "canonical_key": ckey,
794
+ "category": entry_cat,
795
+ "score": round(bm25_score, 3),
796
+ "matched_terms": list(dict.fromkeys(matched_terms)),
797
+ "description": entry.get("description", ""),
798
+ "archived_path": entry.get("archived_path", ""),
799
+ "resolved_path": entry.get("resolved_path", ""),
800
+ "skill_md_bytes": entry.get("skill_md_bytes", 0),
801
+ "companion_files": entry.get("companion_files", []),
802
+ "aliases": entry.get("aliases", [entry["name"]]),
803
+ "exact_name_hit": exact_name_hit,
804
+ })
805
+
806
+ results.sort(key=lambda r: (-r["score"], r["name"].lower()))
807
+ return results[:limit] if limit else results
808
+
809
+
810
+ def _resolve_skill_md_for_candidate(cand, archive_dir, base_dir=None):
811
+ """Locate readable SKILL.md path for a ranked candidate."""
812
+ raw_res = cand.get("resolved_path")
813
+ if raw_res:
814
+ p = Path(raw_res) / "SKILL.md"
815
+ if p.exists():
816
+ return p, Path(raw_res)
817
+ raw_arch = cand.get("archived_path")
818
+ if raw_arch:
819
+ skill_dir = _resolve_archived_skill_dir(base_dir, archive_dir, raw_arch)
820
+ p = skill_dir / "SKILL.md"
821
+ if p.exists():
822
+ return p, skill_dir
823
+ return None, None
824
+
825
+
826
+ def _truncate_skill_body(text, max_chars, skill_name):
827
+ """Truncate overly long SKILL.md cleanly on a line boundary with MCP load hint."""
828
+ if len(text) <= max_chars:
829
+ return text, False
830
+ cutoff = max(max_chars - 240, 500)
831
+ snippet = text[:cutoff]
832
+ last_nl = snippet.rfind("\n")
833
+ if last_nl > cutoff * 0.6:
834
+ snippet = snippet[:last_nl]
835
+ notice = (
836
+ f"\n\n[... truncated at {len(snippet)} chars to preserve context budget; "
837
+ f"call MCP load_skill(name=\"{skill_name}\") if remaining sections are needed ...]"
838
+ )
839
+ return snippet + notice, True
840
+
841
+
842
+ def route_prompt(
843
+ index_data,
844
+ prompt,
845
+ archive_dir,
846
+ base_dir=None,
847
+ workspace_categories=None,
848
+ exclude_names=None,
849
+ routing_config=None,
850
+ ):
851
+ """Select confidence-tiered skills (inline / pointer / none) and format injection text."""
852
+ cfg = dict(DEFAULT_ROUTING_CONFIG)
853
+ if routing_config:
854
+ cfg.update(routing_config)
855
+
856
+ empty_result = {
857
+ "inline": [],
858
+ "pointers": [],
859
+ "candidates": [],
860
+ "estimated_tokens": 0,
861
+ "injection_text": "",
862
+ "ui_notice": "",
863
+ "ambiguous": False,
864
+ }
865
+
866
+ if not cfg.get("enabled", True) or not (prompt or "").strip():
867
+ return empty_result
868
+
869
+ mode = str(cfg.get("mode", "hybrid")).lower()
870
+ min_pointer = float(cfg.get("min_score_pointer", 2.8))
871
+ min_inline = float(cfg.get("min_score_inline", 5.5))
872
+ max_inline = int(cfg.get("max_inline_skills", 2))
873
+ max_pointers = int(cfg.get("max_pointer_skills", 4))
874
+ max_inline_chars = int(cfg.get("max_inline_chars", 12000))
875
+ max_single_chars = int(cfg.get("max_single_skill_chars", 9000))
876
+ margin_ratio = float(cfg.get("inline_margin_ratio", 1.15))
877
+
878
+ always_excl = set(cfg.get("always_exclude", []) or [])
879
+ combined_excl = set(exclude_names or []) | always_excl
880
+
881
+ candidates = search_index(
882
+ index_data=index_data,
883
+ query=prompt,
884
+ workspace_categories=workspace_categories,
885
+ exclude_names=combined_excl,
886
+ limit=max(12, max_inline + max_pointers + 4),
887
+ routing_config=cfg,
888
+ )
889
+
890
+ viable = [c for c in candidates if c["score"] >= min_pointer]
891
+ if not viable:
892
+ empty_result["candidates"] = candidates
893
+ return empty_result
894
+
895
+ # Relative score floor: prune trailing weak noise far below the top match
896
+ top = viable[0]
897
+ rel_floor = max(min_pointer, top["score"] * 0.30)
898
+ viable = [c for c in viable if c["score"] >= rel_floor]
899
+
900
+ # Ambiguity check: if >=4 peers in the top skill's category tie closely without exact-name hit,
901
+ # demote all to compact pointers instead of guessing 2 arbitrary skills.
902
+ ambiguous = False
903
+ if not top.get("exact_name_hit"):
904
+ floor = top["score"] / max(margin_ratio, 1.01)
905
+ close_peers = [
906
+ c for c in viable
907
+ if c["category"] == top["category"] and c["score"] >= floor
908
+ ]
909
+ if len(close_peers) >= 4:
910
+ ambiguous = True
911
+
912
+ inline_items = []
913
+ pointer_items = []
914
+
915
+ if mode == "pointer" or ambiguous:
916
+ pointer_items = viable[: max_pointers + (max_inline if mode == "pointer" else 0)]
917
+ else:
918
+ remaining_chars = max_inline_chars
919
+ for cand in viable:
920
+ passes_inline_floor = cand["score"] >= min_inline or mode == "inline"
921
+ if len(inline_items) > 0 and cand["score"] < top["score"] * 0.45:
922
+ passes_inline_floor = False
923
+ should_try_inline = (
924
+ len(inline_items) < max_inline
925
+ and passes_inline_floor
926
+ and remaining_chars >= 600
927
+ )
928
+ if should_try_inline:
929
+ md_path, skill_dir = _resolve_skill_md_for_candidate(cand, archive_dir, base_dir)
930
+ if md_path and md_path.exists():
931
+ try:
932
+ raw_text = md_path.read_text(encoding="utf-8", errors="replace").strip()
933
+ except Exception:
934
+ raw_text = ""
935
+ if raw_text:
936
+ budget = min(max_single_chars, remaining_chars)
937
+ body_text, truncated = _truncate_skill_body(raw_text, budget, cand["name"])
938
+ item = dict(cand)
939
+ item["skill_dir"] = str(skill_dir)
940
+ item["skill_md_path"] = str(md_path)
941
+ item["content"] = body_text
942
+ item["truncated"] = truncated
943
+ inline_items.append(item)
944
+ remaining_chars -= len(body_text)
945
+ continue
946
+ if len(pointer_items) < max_pointers:
947
+ item = dict(cand)
948
+ _, skill_dir = _resolve_skill_md_for_candidate(cand, archive_dir, base_dir)
949
+ item["skill_dir"] = str(skill_dir) if skill_dir else cand.get("resolved_path", "")
950
+ pointer_items.append(item)
951
+
952
+ if not inline_items and not pointer_items:
953
+ empty_result["candidates"] = candidates
954
+ return empty_result
955
+
956
+ # Format compact injection block
957
+ sections = ["<skill_vault_context>"]
958
+ if inline_items:
959
+ sections.append(
960
+ "Relevant skills automatically loaded from cold storage (L2) for this request:"
961
+ )
962
+ for item in inline_items:
963
+ companions = item.get("companion_files", [])
964
+ comp_str = ", ".join(companions[:12])
965
+ if len(companions) > 12:
966
+ comp_str += f", ... (+{len(companions) - 12} more)"
967
+ sections.append(
968
+ f'<skill name="{item["name"]}" category="{item["category"]}" base_dir="{item["skill_dir"]}">'
969
+ )
970
+ if comp_str:
971
+ sections.append(
972
+ f"[Companion files inside base_dir (load via MCP load_skill or read_file): {comp_str}]"
973
+ )
974
+ sections.append(item["content"])
975
+ sections.append("</skill>")
976
+
977
+ if pointer_items:
978
+ sections.append("<available_vault_skills>")
979
+ sections.append(
980
+ "Additional matching vaulted skills (call MCP load_skill(name) or read SKILL.md if needed):"
981
+ )
982
+ for item in pointer_items:
983
+ desc = item.get("description", "").strip()
984
+ short_desc = desc[:130] + "..." if len(desc) > 130 else desc
985
+ skill_md_loc = str(Path(item["skill_dir"]) / "SKILL.md") if item.get("skill_dir") else item.get("archived_path", "")
986
+ sections.append(
987
+ f'- **{item["name"]}** [{item["category"]}]: {short_desc} (`{skill_md_loc}`)'
988
+ )
989
+ sections.append("</available_vault_skills>")
990
+
991
+ sections.append("</skill_vault_context>")
992
+ injection_text = "\n".join(sections)
993
+ est_tokens = max(1, len(injection_text) // 4)
994
+
995
+ inlined_names = [i["name"] for i in inline_items]
996
+ pointed_names = [p["name"] for p in pointer_items]
997
+ notice_parts = []
998
+ if inlined_names:
999
+ notice_parts.append("Loaded: " + ", ".join(f"`{n}`" for n in inlined_names))
1000
+ if pointed_names:
1001
+ notice_parts.append("Available: " + ", ".join(f"`{n}`" for n in pointed_names))
1002
+ ui_notice = f"*Skill Vault:* {' | '.join(notice_parts)}" if notice_parts else ""
1003
+
1004
+ return {
1005
+ "inline": inline_items,
1006
+ "pointers": pointer_items,
1007
+ "candidates": candidates,
1008
+ "estimated_tokens": est_tokens,
1009
+ "injection_text": injection_text,
1010
+ "ui_notice": ui_notice,
1011
+ "ambiguous": ambiguous,
1012
+ }
1013
+
1014
+
1015
+ # --- Per-Conversation State, Workspace Cache & Telemetry ---
1016
+
1017
+
1018
+ def _state_dir(archive_dir):
1019
+ d = Path(archive_dir).resolve() / ".state"
1020
+ d.mkdir(parents=True, exist_ok=True)
1021
+ return d
1022
+
1023
+
1024
+ def _atomic_write_json(path, data):
1025
+ path = Path(path)
1026
+ path.parent.mkdir(parents=True, exist_ok=True)
1027
+ tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
1028
+ with open(tmp, "w", encoding="utf-8") as f:
1029
+ json.dump(data, f, ensure_ascii=False)
1030
+ os.replace(tmp, path)
1031
+
1032
+
1033
+ class ConversationState:
1034
+ """Manages per-conversation routing state for same-turn short-circuit & cross-turn dedup."""
1035
+
1036
+ def __init__(self, archive_dir, conversation_id):
1037
+ self.state_dir = _state_dir(archive_dir)
1038
+ cid = str(conversation_id or "default")
1039
+ digest = hashlib.sha256(cid.encode("utf-8", errors="ignore")).hexdigest()[:16]
1040
+ self.path = self.state_dir / f"conv_{digest}.json"
1041
+ self.data = self._load()
1042
+
1043
+ def _load(self):
1044
+ if self.path.exists():
1045
+ try:
1046
+ with open(self.path, "r", encoding="utf-8") as f:
1047
+ data = json.load(f)
1048
+ if isinstance(data, dict):
1049
+ return data
1050
+ except Exception:
1051
+ pass
1052
+ return {
1053
+ "last_input_hash": None,
1054
+ "last_initial_steps": None,
1055
+ "injected_skills": [],
1056
+ "pointed_skills": [],
1057
+ "updated_at": 0.0,
1058
+ }
1059
+
1060
+ def save(self):
1061
+ self.data["updated_at"] = time.time()
1062
+ _atomic_write_json(self.path, self.data)
1063
+
1064
+ def should_short_circuit(self, input_hash, invocation_num=None, initial_num_steps=None):
1065
+ """Return True if this PreInvocation call repeats the same user input."""
1066
+ return self.data.get("last_input_hash") == input_hash
1067
+
1068
+ def get_excluded_skills(self):
1069
+ return set(self.data.get("injected_skills", [])) | set(self.data.get("pointed_skills", []))
1070
+
1071
+ def record_turn(self, input_hash, initial_num_steps, inline_keys, pointer_keys):
1072
+ self.data["last_input_hash"] = input_hash
1073
+ self.data["last_initial_steps"] = initial_num_steps
1074
+ injected = list(dict.fromkeys(list(self.data.get("injected_skills", [])) + list(inline_keys)))
1075
+ pointed = list(dict.fromkeys(list(self.data.get("pointed_skills", [])) + list(pointer_keys)))
1076
+ self.data["injected_skills"] = injected
1077
+ self.data["pointed_skills"] = pointed
1078
+ self.save()
1079
+
1080
+
1081
+ def prune_old_states(archive_dir, max_age_days=7):
1082
+ """Remove stale conversation state files older than max_age_days."""
1083
+ state_dir = Path(archive_dir).resolve() / ".state"
1084
+ if not state_dir.exists():
1085
+ return 0
1086
+ cutoff = time.time() - (max_age_days * 86400.0)
1087
+ removed = 0
1088
+ for f in state_dir.glob("conv_*.json"):
1089
+ try:
1090
+ if f.stat().st_mtime < cutoff:
1091
+ f.unlink()
1092
+ removed += 1
1093
+ except OSError:
1094
+ pass
1095
+ return removed
1096
+
1097
+
1098
+ def get_cached_workspace_categories(archive_dir, workspace_paths, ttl_seconds=600):
1099
+ """Retrieve cached workspace categories if still within TTL."""
1100
+ if not workspace_paths:
1101
+ return None
1102
+ state_dir = _state_dir(archive_dir)
1103
+ key = hashlib.sha256("|".join(sorted(str(p) for p in workspace_paths)).encode("utf-8")).hexdigest()[:16]
1104
+ cache_file = state_dir / "ws_cache.json"
1105
+ if not cache_file.exists():
1106
+ return None
1107
+ try:
1108
+ with open(cache_file, "r", encoding="utf-8") as f:
1109
+ cache = json.load(f)
1110
+ entry = cache.get(key)
1111
+ if entry and (time.time() - float(entry.get("ts", 0.0))) <= ttl_seconds:
1112
+ return list(entry.get("categories", []))
1113
+ except Exception:
1114
+ pass
1115
+ return None
1116
+
1117
+
1118
+ def cache_workspace_categories(archive_dir, workspace_paths, categories):
1119
+ """Persist detected workspace categories for fast lookup in PreInvocation."""
1120
+ if not workspace_paths:
1121
+ return
1122
+ state_dir = _state_dir(archive_dir)
1123
+ key = hashlib.sha256("|".join(sorted(str(p) for p in workspace_paths)).encode("utf-8")).hexdigest()[:16]
1124
+ cache_file = state_dir / "ws_cache.json"
1125
+ cache = {}
1126
+ if cache_file.exists():
1127
+ try:
1128
+ with open(cache_file, "r", encoding="utf-8") as f:
1129
+ loaded = json.load(f)
1130
+ if isinstance(loaded, dict):
1131
+ cache = loaded
1132
+ except Exception:
1133
+ cache = {}
1134
+
1135
+ now = time.time()
1136
+ cache = {k: v for k, v in cache.items() if now - float(v.get("ts", 0.0)) < 86400}
1137
+ cache[key] = {"ts": now, "categories": sorted(set(categories))}
1138
+ _atomic_write_json(cache_file, cache)
1139
+
1140
+
1141
+ def log_routing_event(archive_dir, record, max_lines=1000):
1142
+ """Append a privacy-preserving telemetry record (no raw prompts) to routing_log.jsonl."""
1143
+ state_dir = _state_dir(archive_dir)
1144
+ log_file = state_dir / "routing_log.jsonl"
1145
+ line = json.dumps(record, ensure_ascii=False)
1146
+ try:
1147
+ lines = []
1148
+ if log_file.exists():
1149
+ with open(log_file, "r", encoding="utf-8", errors="replace") as f:
1150
+ lines = f.read().splitlines()
1151
+ lines.append(line)
1152
+ if len(lines) > max_lines:
1153
+ lines = lines[-max_lines:]
1154
+ tmp = state_dir / f".routing_log.{os.getpid()}.tmp"
1155
+ with open(tmp, "w", encoding="utf-8") as f:
1156
+ f.write("\n".join(lines) + "\n")
1157
+ os.replace(tmp, log_file)
1158
+ except OSError:
1159
+ pass