tokensafe 4.12.4 → 4.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +8 -6
- package/hooks/pre_invocation.py +8 -4
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +4 -3
- package/server.json +3 -3
- package/src/auto_inject.py +1026 -279
- package/src/backend_release.py +10 -0
- package/src/batch_editor.py +18 -8
- package/src/batch_search.py +39 -16
- package/src/bundle_probe.py +205 -0
- package/src/cli.py +76 -7
- package/src/fts_index.py +9 -0
- package/src/globmatch.py +124 -0
- package/src/governor.py +120 -44
- package/src/graph_engine.py +292 -14
- package/src/installer.py +3 -3
- package/src/mcp_server.py +153 -35
- package/src/metrics.py +7 -0
- package/src/oumv_brief.py +346 -0
- package/src/oumv_gateway.py +132 -43
- package/src/quality_score.py +46 -24
- package/src/retrofit.py +35 -11
- package/src/savings.py +1 -0
- package/src/scoped_search.py +238 -9
- package/src/session_brief.py +6 -1
- package/src/telemetry_sync.py +1 -1
- package/src/treesitter_backend.py +26 -1
- package/src/version_checker.py +1 -1
- package/src/web_reader.py +42 -0
- package/src/workspace_roots.py +246 -0
package/src/backend_release.py
CHANGED
|
@@ -15,3 +15,13 @@ BACKEND_RELEASE_TAG = "v0.20.0"
|
|
|
15
15
|
# Wire version that tag speaks. Printed in briefs so an agent never mixes a
|
|
16
16
|
# backend release with an older protocol line.
|
|
17
17
|
BACKEND_WIRE_VERSION = "1.8.0"
|
|
18
|
+
|
|
19
|
+
# npm release of `tokensafe-backend-node` that ships the same adapters. The
|
|
20
|
+
# package has its own semver line (`node/package.json`), so it is pinned
|
|
21
|
+
# separately from the Go tag; `tokensafe inject` installs exactly this version.
|
|
22
|
+
BACKEND_NPM_VERSION = "0.15.0"
|
|
23
|
+
|
|
24
|
+
# NuGet release of `TokenSafe.Oumv.AspNetCore`. It has its own semver line too
|
|
25
|
+
# (`dotnet/src/TokenSafe.Oumv/TokenSafe.Oumv.csproj`), so tying it to the Go tag
|
|
26
|
+
# would ask NuGet for a version that does not exist.
|
|
27
|
+
BACKEND_DOTNET_VERSION = "0.7.0"
|
package/src/batch_editor.py
CHANGED
|
@@ -579,14 +579,24 @@ def execute_batch_edits(
|
|
|
579
579
|
continue
|
|
580
580
|
|
|
581
581
|
if os.path.isabs(rel_path):
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
)
|
|
588
|
-
|
|
589
|
-
|
|
582
|
+
# Defense in depth: the MCP wrapper rebases absolute paths that live
|
|
583
|
+
# inside one known root. A direct caller is accepted only inside the
|
|
584
|
+
# selected base, so containment remains the single write boundary.
|
|
585
|
+
abs_candidate = os.path.realpath(os.path.abspath(rel_path))
|
|
586
|
+
try:
|
|
587
|
+
inside = os.path.commonpath([real_base, abs_candidate]) == real_base
|
|
588
|
+
except ValueError:
|
|
589
|
+
inside = False
|
|
590
|
+
if not inside:
|
|
591
|
+
failed_files.append({
|
|
592
|
+
"path": rel_path,
|
|
593
|
+
"error": (
|
|
594
|
+
f"absolute path '{rel_path}' is outside the working directory '{base_dir}'. "
|
|
595
|
+
"Pass 'cwd' (the repo root) with a repo-relative 'path' value."
|
|
596
|
+
),
|
|
597
|
+
})
|
|
598
|
+
continue
|
|
599
|
+
rel_path = os.path.relpath(abs_candidate, real_base).replace("\\", "/")
|
|
590
600
|
|
|
591
601
|
abs_path = os.path.normpath(os.path.join(base_dir, rel_path))
|
|
592
602
|
real_target = os.path.realpath(abs_path)
|
package/src/batch_search.py
CHANGED
|
@@ -27,6 +27,7 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
|
27
27
|
from typing import Dict, Any, List, Optional, Tuple
|
|
28
28
|
|
|
29
29
|
from src.scoped_search import ScopedSearch, IGNORED_DIRS, IGNORED_EXTENSIONS, CODE_EXTENSIONS
|
|
30
|
+
from src.globmatch import GlobPatternError, compile_patterns, matches_any
|
|
30
31
|
from src.format_parsers.ansi import strip_ansi
|
|
31
32
|
|
|
32
33
|
MAX_BATCH_QUERIES = 20
|
|
@@ -361,25 +362,30 @@ def _run_python_text_search(
|
|
|
361
362
|
return matches
|
|
362
363
|
|
|
363
364
|
|
|
364
|
-
def _run_glob_search(pattern: str, cwd: str, path_filter: Optional[str] = None, max_results: int = 50) -> List[str]:
|
|
365
|
-
"""Finds matching files by glob
|
|
365
|
+
def _run_glob_search(pattern: str, cwd: str, path_filter: Optional[str] = None, max_results: int = 50) -> Tuple[List[str], int, int]:
|
|
366
|
+
"""Finds matching files by a brace-aware glob.
|
|
367
|
+
|
|
368
|
+
Returns (hits, scanned, total); the walk always completes so the caller can
|
|
369
|
+
report honest coverage even when the result list is capped.
|
|
370
|
+
"""
|
|
371
|
+
patterns = compile_patterns(pattern)
|
|
366
372
|
search_root = os.path.normpath(os.path.join(cwd, path_filter)) if path_filter else cwd
|
|
367
373
|
if not os.path.exists(search_root):
|
|
368
|
-
|
|
374
|
+
raise FileNotFoundError(search_root)
|
|
369
375
|
|
|
370
376
|
if os.path.isfile(search_root):
|
|
371
|
-
rel_p = os.path.relpath(search_root, cwd)
|
|
372
|
-
if
|
|
373
|
-
return [rel_p]
|
|
374
|
-
return []
|
|
377
|
+
rel_p = os.path.relpath(search_root, cwd).replace("\\", "/")
|
|
378
|
+
return ([rel_p] if matches_any(patterns, rel_p) else []), 1, 1
|
|
375
379
|
|
|
376
|
-
results = []
|
|
380
|
+
results: List[str] = []
|
|
381
|
+
scanned = 0
|
|
377
382
|
for full_path, rel_p in _iter_search_files(search_root, cwd):
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
+
scanned += 1
|
|
384
|
+
rel_p = rel_p.replace("\\", "/")
|
|
385
|
+
if matches_any(patterns, rel_p, os.path.basename(full_path)):
|
|
386
|
+
if len(results) < max_results:
|
|
387
|
+
results.append(rel_p)
|
|
388
|
+
return results, scanned, scanned
|
|
383
389
|
|
|
384
390
|
|
|
385
391
|
def _run_fuzzy_search(pattern: str, cwd: str, path_filter: Optional[str] = None, max_results: int = 30) -> List[str]:
|
|
@@ -435,10 +441,27 @@ def _execute_single_query(query_dict: Dict[str, Any], cwd: str) -> Dict[str, Any
|
|
|
435
441
|
return {"type": "git", "pattern": pattern, **res}
|
|
436
442
|
|
|
437
443
|
if q_type == "glob":
|
|
438
|
-
|
|
444
|
+
try:
|
|
445
|
+
matched_paths, scanned, total = _run_glob_search(
|
|
446
|
+
pattern, cwd, path_filter=path_filter, max_results=max_res
|
|
447
|
+
)
|
|
448
|
+
except GlobPatternError as e:
|
|
449
|
+
return {
|
|
450
|
+
"type": "glob", "pattern": pattern,
|
|
451
|
+
"error": f"invalid glob pattern: {e}",
|
|
452
|
+
"matches": [], "count": 0,
|
|
453
|
+
"scanned_files": 0, "total_files": None, "partial": False,
|
|
454
|
+
}
|
|
455
|
+
base = {
|
|
456
|
+
"type": "glob", "pattern": pattern,
|
|
457
|
+
"scanned_files": scanned, "total_files": total,
|
|
458
|
+
"partial": False, "truncated": len(matched_paths) >= max_res,
|
|
459
|
+
}
|
|
460
|
+
if not matched_paths:
|
|
461
|
+
base["note"] = "glob matched no files (braces are expanded; ** is accepted)"
|
|
439
462
|
if output_mode == "count":
|
|
440
|
-
return {
|
|
441
|
-
return {
|
|
463
|
+
return {**base, "count": len(matched_paths)}
|
|
464
|
+
return {**base, "matches": matched_paths, "count": len(matched_paths)}
|
|
442
465
|
|
|
443
466
|
if q_type == "fuzzy":
|
|
444
467
|
matched_paths = _run_fuzzy_search(pattern, cwd, path_filter=path_filter, max_results=max_res)
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Deploy-time bundle probe: fetch a live entry, follow its hashed chunks, check strings.
|
|
2
|
+
|
|
3
|
+
Verifying a Vite/Bunny deploy by hand costs four shell calls plus ad-hoc regex
|
|
4
|
+
work (entry -> chunk hash -> chunk -> grep). `probe_bundle` does the same in one
|
|
5
|
+
call and answers with a found/missing table, so a stale CDN cache is visible
|
|
6
|
+
without a second round trip.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
import time
|
|
12
|
+
from typing import Any, Dict, List, Optional
|
|
13
|
+
from urllib.parse import urljoin, urlparse
|
|
14
|
+
|
|
15
|
+
from src.web_reader import WebReader
|
|
16
|
+
|
|
17
|
+
_MAX_CHUNKS = 20
|
|
18
|
+
_DEFAULT_TIMEOUT_MS = 6000
|
|
19
|
+
_MAX_TIMEOUT_MS = 15000
|
|
20
|
+
_ASSET_RE = re.compile(
|
|
21
|
+
r"""<\s*(?:script|link)\b[^>]*?(?:src|href)\s*=\s*["']([^"']+)["'][^>]*>""",
|
|
22
|
+
re.IGNORECASE,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _decode(body: bytes, headers: Dict[str, str]) -> str:
|
|
27
|
+
charset = "utf-8"
|
|
28
|
+
content_type = headers.get("content-type", "")
|
|
29
|
+
if "charset=" in content_type:
|
|
30
|
+
charset = content_type.split("charset=")[-1].split(";")[0].strip() or "utf-8"
|
|
31
|
+
return body.decode(charset, errors="replace")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _find(needle: str, text: str) -> List[Dict[str, Any]]:
|
|
35
|
+
count = 0
|
|
36
|
+
first_line = 0
|
|
37
|
+
for line_no, line in enumerate(text.splitlines(), 1):
|
|
38
|
+
hits = line.count(needle)
|
|
39
|
+
if hits:
|
|
40
|
+
count += hits
|
|
41
|
+
if not first_line:
|
|
42
|
+
first_line = line_no
|
|
43
|
+
if not count:
|
|
44
|
+
return []
|
|
45
|
+
return [{"line": first_line, "count": count}]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _asset_urls(entry_url: str, entry_text: str, chunks: Optional[List[str]]) -> List[str]:
|
|
49
|
+
urls: List[str] = []
|
|
50
|
+
if chunks:
|
|
51
|
+
candidates = [str(c).strip() for c in chunks if str(c or "").strip()]
|
|
52
|
+
else:
|
|
53
|
+
candidates = [m.group(1).strip() for m in _ASSET_RE.finditer(entry_text)]
|
|
54
|
+
for raw in candidates:
|
|
55
|
+
if raw.startswith(("data:", "#", "mailto:", "javascript:")):
|
|
56
|
+
continue
|
|
57
|
+
url = urljoin(entry_url, raw)
|
|
58
|
+
if urlparse(url).scheme not in ("http", "https"):
|
|
59
|
+
continue
|
|
60
|
+
if url == entry_url or url in urls:
|
|
61
|
+
continue
|
|
62
|
+
urls.append(url)
|
|
63
|
+
return urls[:_MAX_CHUNKS]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def probe_bundle(
|
|
67
|
+
url: str,
|
|
68
|
+
expect: Optional[List[str]] = None,
|
|
69
|
+
reject: Optional[List[str]] = None,
|
|
70
|
+
chunks: Optional[List[str]] = None,
|
|
71
|
+
timeout_ms: Optional[int] = None,
|
|
72
|
+
) -> Dict[str, Any]:
|
|
73
|
+
"""Fetches `url`, its hashed chunks, and reports expect/reject string checks."""
|
|
74
|
+
start = time.monotonic()
|
|
75
|
+
target = str(url or "").strip()
|
|
76
|
+
expect = [str(s) for s in (expect or []) if str(s or "")]
|
|
77
|
+
reject = [str(s) for s in (reject or []) if str(s or "")]
|
|
78
|
+
try:
|
|
79
|
+
budget_ms = int(timeout_ms if timeout_ms is not None else _DEFAULT_TIMEOUT_MS)
|
|
80
|
+
except (TypeError, ValueError):
|
|
81
|
+
budget_ms = _DEFAULT_TIMEOUT_MS
|
|
82
|
+
budget_ms = max(500, min(_MAX_TIMEOUT_MS, budget_ms))
|
|
83
|
+
deadline = start + budget_ms / 1000.0
|
|
84
|
+
|
|
85
|
+
result: Dict[str, Any] = {
|
|
86
|
+
"url": target,
|
|
87
|
+
"ok": False,
|
|
88
|
+
"entry": None,
|
|
89
|
+
"chunks": [],
|
|
90
|
+
"checks": [],
|
|
91
|
+
"missing": [],
|
|
92
|
+
"unexpected": [],
|
|
93
|
+
"coverage": {"fetched": 0, "failed": 0, "requested": 0, "timed_out": False},
|
|
94
|
+
"elapsed_ms": 0,
|
|
95
|
+
"markdown": "",
|
|
96
|
+
}
|
|
97
|
+
if not target:
|
|
98
|
+
result["error"] = "url is required"
|
|
99
|
+
result["markdown"] = "Bundle probe failed: url is required."
|
|
100
|
+
return result
|
|
101
|
+
|
|
102
|
+
def _remaining() -> float:
|
|
103
|
+
return max(0.0, deadline - time.monotonic())
|
|
104
|
+
|
|
105
|
+
status, body, headers, err = WebReader.fetch_raw(
|
|
106
|
+
target, timeout=max(0.5, min(3.0, _remaining())), accept="text/html,application/xhtml+xml,*/*"
|
|
107
|
+
)
|
|
108
|
+
result["coverage"]["requested"] = 1
|
|
109
|
+
if err or status is None or status >= 400:
|
|
110
|
+
result["coverage"]["failed"] = 1
|
|
111
|
+
result["entry"] = {"url": target, "status": status, "bytes": len(body), "error": err or f"HTTP {status}"}
|
|
112
|
+
result["missing"] = expect
|
|
113
|
+
result["checks"] = [
|
|
114
|
+
{"kind": "expect", "string": s, "found": False, "locations": []} for s in expect
|
|
115
|
+
] + [
|
|
116
|
+
{"kind": "reject", "string": s, "found": False, "locations": []} for s in reject
|
|
117
|
+
]
|
|
118
|
+
result["elapsed_ms"] = int((time.monotonic() - start) * 1000)
|
|
119
|
+
result["markdown"] = _render(result)
|
|
120
|
+
return result
|
|
121
|
+
|
|
122
|
+
result["coverage"]["fetched"] = 1
|
|
123
|
+
entry_text = _decode(body, headers)
|
|
124
|
+
result["entry"] = {"url": target, "status": status, "bytes": len(body)}
|
|
125
|
+
|
|
126
|
+
asset_urls = _asset_urls(target, entry_text, chunks)
|
|
127
|
+
result["coverage"]["requested"] += len(asset_urls)
|
|
128
|
+
for asset_url in asset_urls:
|
|
129
|
+
if _remaining() <= 0:
|
|
130
|
+
result["coverage"]["timed_out"] = True
|
|
131
|
+
result["chunks"].append({"url": asset_url, "status": None, "bytes": 0, "error": "probe budget exhausted"})
|
|
132
|
+
result["coverage"]["failed"] += 1
|
|
133
|
+
continue
|
|
134
|
+
a_status, a_body, a_headers, a_err = WebReader.fetch_raw(
|
|
135
|
+
asset_url, timeout=max(0.5, min(3.0, _remaining())), accept="*/*"
|
|
136
|
+
)
|
|
137
|
+
if a_err or a_status is None or a_status >= 400:
|
|
138
|
+
result["coverage"]["failed"] += 1
|
|
139
|
+
result["chunks"].append({
|
|
140
|
+
"url": asset_url,
|
|
141
|
+
"status": a_status,
|
|
142
|
+
"bytes": len(a_body),
|
|
143
|
+
"error": a_err or f"HTTP {a_status}",
|
|
144
|
+
})
|
|
145
|
+
continue
|
|
146
|
+
result["coverage"]["fetched"] += 1
|
|
147
|
+
result["chunks"].append({"url": asset_url, "status": a_status, "bytes": len(a_body)})
|
|
148
|
+
entry_text += "\n" + _decode(a_body, a_headers)
|
|
149
|
+
|
|
150
|
+
checks: List[Dict[str, Any]] = []
|
|
151
|
+
for needle in expect:
|
|
152
|
+
locations = _find(needle, entry_text)
|
|
153
|
+
checks.append({"kind": "expect", "string": needle, "found": bool(locations), "locations": locations})
|
|
154
|
+
if not locations:
|
|
155
|
+
result["missing"].append(needle)
|
|
156
|
+
for needle in reject:
|
|
157
|
+
locations = _find(needle, entry_text)
|
|
158
|
+
checks.append({"kind": "reject", "string": needle, "found": bool(locations), "locations": locations})
|
|
159
|
+
if locations:
|
|
160
|
+
result["unexpected"].append(needle)
|
|
161
|
+
result["checks"] = checks
|
|
162
|
+
result["ok"] = (
|
|
163
|
+
not result["missing"]
|
|
164
|
+
and not result["unexpected"]
|
|
165
|
+
and result["coverage"]["failed"] == 0
|
|
166
|
+
and not result["coverage"]["timed_out"]
|
|
167
|
+
)
|
|
168
|
+
result["elapsed_ms"] = int((time.monotonic() - start) * 1000)
|
|
169
|
+
result["markdown"] = _render(result)
|
|
170
|
+
return result
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _render(result: Dict[str, Any]) -> str:
|
|
174
|
+
state = "OK" if result.get("ok") else "FAIL"
|
|
175
|
+
entry = result.get("entry") or {}
|
|
176
|
+
lines = [
|
|
177
|
+
f"### Bundle probe: {result.get('url')} — {state}",
|
|
178
|
+
(
|
|
179
|
+
f"_entry: HTTP {entry.get('status')} · {entry.get('bytes', 0):,} B · "
|
|
180
|
+
f"{len(result.get('chunks', []))} chunk(s) · {result.get('elapsed_ms', 0)} ms_"
|
|
181
|
+
),
|
|
182
|
+
]
|
|
183
|
+
if entry.get("error"):
|
|
184
|
+
lines.append(f"_entry error: {entry['error']}_")
|
|
185
|
+
for chunk in result.get("chunks", []):
|
|
186
|
+
note = chunk.get("error") or f"HTTP {chunk.get('status')}"
|
|
187
|
+
lines.append(f"- chunk `{chunk.get('url')}`: {note}, {chunk.get('bytes', 0):,} B")
|
|
188
|
+
if result.get("checks"):
|
|
189
|
+
lines.append("")
|
|
190
|
+
lines.append("| check | kind | found | location |")
|
|
191
|
+
lines.append("|---|---|---|---|")
|
|
192
|
+
for check in result["checks"]:
|
|
193
|
+
locations = check.get("locations") or []
|
|
194
|
+
where = (
|
|
195
|
+
f"line {locations[0]['line']} ({locations[0]['count']}x)" if locations else "—"
|
|
196
|
+
)
|
|
197
|
+
lines.append(
|
|
198
|
+
f"| `{check['string']}` | {check['kind']} | {'yes' if check['found'] else 'NO'} | {where} |"
|
|
199
|
+
)
|
|
200
|
+
if result.get("missing"):
|
|
201
|
+
lines.append("")
|
|
202
|
+
lines.append(f"_missing: {', '.join(f'`{s}`' for s in result['missing'])}_")
|
|
203
|
+
if result.get("unexpected"):
|
|
204
|
+
lines.append(f"_rejected strings present: {', '.join(f'`{s}`' for s in result['unexpected'])}_")
|
|
205
|
+
return "\n".join(lines)
|
package/src/cli.py
CHANGED
|
@@ -104,6 +104,7 @@ def _print_help():
|
|
|
104
104
|
print(" inject [status|apply|revert] Auto-wire adapters with zero repo footprint (add --dry-run)")
|
|
105
105
|
print(" adapters [list] Catalog of frontend/backend OUMV runtime adapters")
|
|
106
106
|
print(" oumv doctor / status Diagnose OUMV configuration, ports, and permissions")
|
|
107
|
+
print(" oumv doctor --prune Remove descriptors with no live OUMV runtime")
|
|
107
108
|
print(" create <name> [--template ...] Greenfield project scaffolder (tokensafe-ui + tokensafe-backend)")
|
|
108
109
|
print(" init [--template ...] Initialize TokenSafe stack in current directory")
|
|
109
110
|
print(" stats / markdown / html Savings analytics (terminal / .md report / dashboard)")
|
|
@@ -744,6 +745,8 @@ def main(argv: Optional[List[str]] = None):
|
|
|
744
745
|
if dry_run:
|
|
745
746
|
print(f" \033[33m[DRY-RUN]\033[0m Proposed configuration (.tokensafe/oumv.json):")
|
|
746
747
|
print(json.dumps(cfg, indent=4))
|
|
748
|
+
elif not conf_file:
|
|
749
|
+
print(" ○ No OUMV profile detected: nothing to configure (no .tokensafe/oumv.json written)\n")
|
|
747
750
|
elif created:
|
|
748
751
|
mutate_enabled = cfg.get("permissions", {}).get("mutate", True)
|
|
749
752
|
policy = (
|
|
@@ -806,29 +809,59 @@ def main(argv: Optional[List[str]] = None):
|
|
|
806
809
|
print(f" Profiles: {', '.join(data['profiles']) or 'none detected'}")
|
|
807
810
|
for action in data["actions"]:
|
|
808
811
|
writes = "writes repo" if action["writes_repo"] else "zero repo footprint"
|
|
809
|
-
|
|
812
|
+
app = action.get("app")
|
|
813
|
+
where = f" [{app}]" if app not in (None, ".", "") else ""
|
|
814
|
+
status = f" ({action['status']})" if action.get("status") else ""
|
|
815
|
+
print(f" - {action['kind']:<24} {action['profile']:<9}{where} {writes}{status}")
|
|
810
816
|
if action.get("entrypoint"):
|
|
811
817
|
print(f" entrypoint: {action['entrypoint']} (patched: {action.get('already_patched')})")
|
|
812
818
|
if action.get("install"):
|
|
813
819
|
print(f" install: {action['install']}")
|
|
814
820
|
if action.get("run"):
|
|
815
821
|
print(f" run: {action['run']}")
|
|
822
|
+
if action.get("reason"):
|
|
823
|
+
print(f" reason: {action['reason']}")
|
|
824
|
+
if action.get("snippet"):
|
|
825
|
+
print(" snippet:")
|
|
826
|
+
for line in action["snippet"].splitlines():
|
|
827
|
+
print(f" {line}")
|
|
816
828
|
print(f" Python autoload: {'✔ installed' if data['python_autoload_present'] else '○ not installed'}")
|
|
817
829
|
print(f" Revertable: {'✔ yes' if data['revertable'] else '○ no'}\n")
|
|
818
830
|
elif sub == "revert":
|
|
819
831
|
result = auto_inject.revert(workspace)
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
print(f"
|
|
832
|
+
for key, value in result.items():
|
|
833
|
+
if key == "workspace" or not isinstance(value, dict):
|
|
834
|
+
continue
|
|
835
|
+
print(f" {key}: {value.get('status', '?')}")
|
|
836
|
+
if value.get("entrypoint"):
|
|
837
|
+
print(f" entrypoint: {value['entrypoint']}")
|
|
838
|
+
if value.get("removed"):
|
|
839
|
+
print(f" removed: {', '.join(value['removed'])}")
|
|
840
|
+
if value.get("restored"):
|
|
841
|
+
print(f" restored: {', '.join(value['restored'])}")
|
|
842
|
+
if value.get("modules"):
|
|
843
|
+
for module in value["modules"]:
|
|
844
|
+
print(f" module: {module.get('path')} ({module.get('status')})")
|
|
845
|
+
if value.get("project"):
|
|
846
|
+
print(f" project: {value['project']}")
|
|
847
|
+
if value.get("kept"):
|
|
848
|
+
for kept in value["kept"]:
|
|
849
|
+
print(f" kept: {kept.get('path')} ({kept.get('reason')})")
|
|
850
|
+
if value.get("reason"):
|
|
851
|
+
print(f" reason: {value['reason']}")
|
|
824
852
|
else:
|
|
825
853
|
result = auto_inject.apply(workspace, dry_run=dry_run, include_go=True)
|
|
826
854
|
prefix = "[DRY-RUN] " if dry_run else ""
|
|
827
855
|
cfg = result.get("config", {})
|
|
828
|
-
|
|
856
|
+
if cfg.get("skipped"):
|
|
857
|
+
print(f"\n{prefix}OUMV config: not written ({cfg['skipped']})")
|
|
858
|
+
else:
|
|
859
|
+
print(f"\n{prefix}OUMV config: {cfg.get('path')} ({'created' if cfg.get('created') else 'preserved'}), mutate={cfg.get('mutate')}")
|
|
829
860
|
for action in result.get("actions", []):
|
|
830
861
|
status = action.get("status", "?")
|
|
831
|
-
|
|
862
|
+
app = action.get("app")
|
|
863
|
+
where = f" [{app}]" if app not in (None, ".", "") else ""
|
|
864
|
+
print(f" {prefix}{action['kind']}{where}: {status}")
|
|
832
865
|
if action.get("run"):
|
|
833
866
|
print(f" run: {action['run']}")
|
|
834
867
|
if action.get("reason"):
|
|
@@ -850,6 +883,16 @@ def main(argv: Optional[List[str]] = None):
|
|
|
850
883
|
sub = args[1] if len(args) > 1 else "status"
|
|
851
884
|
if sub in ("doctor", "audit"):
|
|
852
885
|
from src.retrofit import run_doctor
|
|
886
|
+
if "--prune" in args[2:]:
|
|
887
|
+
from src.oumv_gateway import OUMVGateway
|
|
888
|
+
removed = OUMVGateway.prune_stale_descriptors(os.getcwd())
|
|
889
|
+
if removed:
|
|
890
|
+
print("removed stale OUMV descriptors:")
|
|
891
|
+
for path in removed:
|
|
892
|
+
print(f" - {path}")
|
|
893
|
+
else:
|
|
894
|
+
print("no stale OUMV descriptors to remove")
|
|
895
|
+
return
|
|
853
896
|
doc = run_doctor(os.getcwd())
|
|
854
897
|
print(f"\n\033[1m\033[36m⚡ TOKENSAFE OUMV DOCTOR ⚡\033[0m\n")
|
|
855
898
|
print(f" Config (.tokensafe/oumv.json): {'✔ Present' if doc['config_present'] else '○ Not found (run tokensafe integrate)'}")
|
|
@@ -882,6 +925,7 @@ def main(argv: Optional[List[str]] = None):
|
|
|
882
925
|
if "--help" in args or "-h" in args:
|
|
883
926
|
print(
|
|
884
927
|
"\n tokensafe dev [path] [--port N] [--host H] [--open]\n"
|
|
928
|
+
" [--framework react|vue|solid|angular]\n"
|
|
885
929
|
"\n Starts the app's own Vite dev server with the tokensafe-ui OUMV bridge and\n"
|
|
886
930
|
" leaves the repository untouched. Needs a Vite frontend: React, Vue, Solid,\n"
|
|
887
931
|
" or Angular through @analogjs/vite-plugin-angular. Run it in the app directory.\n"
|
|
@@ -890,6 +934,7 @@ def main(argv: Optional[List[str]] = None):
|
|
|
890
934
|
target_dir = os.getcwd()
|
|
891
935
|
port_val: Optional[int] = None
|
|
892
936
|
host_val: Optional[str] = None
|
|
937
|
+
framework_val: Optional[str] = None
|
|
893
938
|
open_browser = False
|
|
894
939
|
unknown_flags: List[str] = []
|
|
895
940
|
i = 1
|
|
@@ -920,6 +965,14 @@ def main(argv: Optional[List[str]] = None):
|
|
|
920
965
|
host_val = "true"
|
|
921
966
|
elif a == "--open":
|
|
922
967
|
open_browser = True
|
|
968
|
+
elif a.startswith("--framework="):
|
|
969
|
+
framework_val = a.split("=", 1)[1].strip().lower()
|
|
970
|
+
elif a == "--framework":
|
|
971
|
+
if nxt is not None and not nxt.startswith("-"):
|
|
972
|
+
framework_val = nxt.strip().lower()
|
|
973
|
+
i += 1
|
|
974
|
+
else:
|
|
975
|
+
unknown_flags.append(a)
|
|
923
976
|
elif a.startswith("-"):
|
|
924
977
|
unknown_flags.append(a)
|
|
925
978
|
else:
|
|
@@ -927,6 +980,13 @@ def main(argv: Optional[List[str]] = None):
|
|
|
927
980
|
i += 1
|
|
928
981
|
if unknown_flags:
|
|
929
982
|
print(f"⚠ Ignoring unsupported 'tokensafe dev' flag(s): {' '.join(unknown_flags)}")
|
|
983
|
+
supported_frameworks = ("react", "vue", "solid", "angular")
|
|
984
|
+
if framework_val is not None and framework_val not in supported_frameworks:
|
|
985
|
+
print(
|
|
986
|
+
f"✗ --framework {framework_val} is not served by `tokensafe dev`: "
|
|
987
|
+
f"choose one of {', '.join(supported_frameworks)}."
|
|
988
|
+
)
|
|
989
|
+
sys.exit(2)
|
|
930
990
|
# `tokensafe dev` cannot invent a frontend: without a Vite app the server
|
|
931
991
|
# would serve an empty directory. Refuse with the reason and the nearest
|
|
932
992
|
# frontend path instead of failing inside Vite.
|
|
@@ -948,6 +1008,15 @@ def main(argv: Optional[List[str]] = None):
|
|
|
948
1008
|
note = frontend.get("note") or f"status: {frontend.get('status')}"
|
|
949
1009
|
print(f"✗ {frontend.get('framework')} detected, but the OUMV dev bridge is not available: {note}")
|
|
950
1010
|
sys.exit(1)
|
|
1011
|
+
if framework_val is not None:
|
|
1012
|
+
detected_framework = str(frontend.get("framework") or "")
|
|
1013
|
+
if detected_framework and detected_framework != framework_val:
|
|
1014
|
+
print(
|
|
1015
|
+
f"✗ --framework {framework_val} does not match the detected frontend "
|
|
1016
|
+
f"({detected_framework}). `tokensafe dev` serves the app's own Vite frontend;\n"
|
|
1017
|
+
" run it without --framework."
|
|
1018
|
+
)
|
|
1019
|
+
sys.exit(2)
|
|
951
1020
|
# In a monorepo the frontend is a nested package: run the server there,
|
|
952
1021
|
# not at the root that has no index.html.
|
|
953
1022
|
frontend_root = frontend.get("root")
|
package/src/fts_index.py
CHANGED
|
@@ -231,6 +231,15 @@ class CodeFTSIndex:
|
|
|
231
231
|
"duration_ms": duration_ms
|
|
232
232
|
}
|
|
233
233
|
|
|
234
|
+
def indexed_file_count(self) -> int:
|
|
235
|
+
"""Distinct files in the index (0 when it was never built)."""
|
|
236
|
+
try:
|
|
237
|
+
with self._get_connection() as con:
|
|
238
|
+
row = con.execute("SELECT COUNT(*) FROM file_meta").fetchone()
|
|
239
|
+
return int(row[0] or 0) if row else 0
|
|
240
|
+
except Exception:
|
|
241
|
+
return 0
|
|
242
|
+
|
|
234
243
|
def search(
|
|
235
244
|
self,
|
|
236
245
|
query: str,
|
package/src/globmatch.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Brace-aware glob matching shared by search and graph import resolution.
|
|
2
|
+
|
|
3
|
+
`fnmatch` treats `{a,b}` literally, so `**/*{vip,Vip}*.test.*` silently matched
|
|
4
|
+
nothing and `import.meta.glob('./pages/*.{ts,tsx}')` never produced an edge.
|
|
5
|
+
This module expands brace groups into plain fnmatch patterns and reports
|
|
6
|
+
malformed patterns as errors instead of returning an empty result.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import fnmatch
|
|
11
|
+
import os
|
|
12
|
+
from typing import List, Optional, Sequence, Tuple, Union
|
|
13
|
+
|
|
14
|
+
MAX_EXPANSIONS = 64
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class GlobPatternError(ValueError):
|
|
18
|
+
"""Malformed glob pattern: callers must surface the error, not 0 matches."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _find_group(pattern: str) -> Optional[Tuple[int, int]]:
|
|
22
|
+
start = pattern.find("{")
|
|
23
|
+
if start == -1:
|
|
24
|
+
return None
|
|
25
|
+
depth = 0
|
|
26
|
+
for i in range(start, len(pattern)):
|
|
27
|
+
ch = pattern[i]
|
|
28
|
+
if ch == "{":
|
|
29
|
+
depth += 1
|
|
30
|
+
elif ch == "}":
|
|
31
|
+
depth -= 1
|
|
32
|
+
if depth == 0:
|
|
33
|
+
return start, i
|
|
34
|
+
raise GlobPatternError(f"unbalanced '{{' in glob pattern: {pattern!r}")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _split_alts(body: str) -> List[str]:
|
|
38
|
+
parts: List[str] = []
|
|
39
|
+
buf: List[str] = []
|
|
40
|
+
depth = 0
|
|
41
|
+
for ch in body:
|
|
42
|
+
if ch == "{":
|
|
43
|
+
depth += 1
|
|
44
|
+
elif ch == "}":
|
|
45
|
+
depth -= 1
|
|
46
|
+
if ch == "," and depth == 0:
|
|
47
|
+
parts.append("".join(buf))
|
|
48
|
+
buf = []
|
|
49
|
+
else:
|
|
50
|
+
buf.append(ch)
|
|
51
|
+
parts.append("".join(buf))
|
|
52
|
+
return parts
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def expand_braces(pattern: str, max_expansions: int = MAX_EXPANSIONS) -> List[str]:
|
|
56
|
+
"""Expands every `{a,b}` group, including nested ones, into plain patterns."""
|
|
57
|
+
pattern = str(pattern or "").strip()
|
|
58
|
+
if not pattern:
|
|
59
|
+
raise GlobPatternError("empty glob pattern")
|
|
60
|
+
group = _find_group(pattern)
|
|
61
|
+
if group is None:
|
|
62
|
+
return [pattern]
|
|
63
|
+
start, end = group
|
|
64
|
+
prefix, body, suffix = pattern[:start], pattern[start + 1:end], pattern[end + 1:]
|
|
65
|
+
expanded: List[str] = []
|
|
66
|
+
for alt in _split_alts(body):
|
|
67
|
+
for item in expand_braces(prefix + alt + suffix, max_expansions=max_expansions):
|
|
68
|
+
if item not in expanded:
|
|
69
|
+
expanded.append(item)
|
|
70
|
+
if len(expanded) > max_expansions:
|
|
71
|
+
raise GlobPatternError(
|
|
72
|
+
f"glob pattern expands to more than {max_expansions} alternatives: {pattern!r}"
|
|
73
|
+
)
|
|
74
|
+
return expanded
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def validate(pattern: str) -> None:
|
|
78
|
+
"""Raises GlobPatternError on unbalanced braces/brackets."""
|
|
79
|
+
expand_braces(pattern)
|
|
80
|
+
i = 0
|
|
81
|
+
while i < len(pattern):
|
|
82
|
+
ch = pattern[i]
|
|
83
|
+
if ch == "[":
|
|
84
|
+
close = pattern.find("]", i + 1)
|
|
85
|
+
if close == -1:
|
|
86
|
+
raise GlobPatternError(f"unbalanced '[' in glob pattern: {pattern!r}")
|
|
87
|
+
i = close
|
|
88
|
+
i += 1
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def compile_patterns(pattern: Union[str, Sequence[str]]) -> List[str]:
|
|
92
|
+
"""Validates and expands one pattern or a list into deduped plain patterns."""
|
|
93
|
+
if isinstance(pattern, str):
|
|
94
|
+
patterns = [pattern]
|
|
95
|
+
else:
|
|
96
|
+
patterns = [str(p) for p in pattern if str(p or "").strip()]
|
|
97
|
+
if not patterns:
|
|
98
|
+
raise GlobPatternError("empty glob pattern")
|
|
99
|
+
out: List[str] = []
|
|
100
|
+
for p in patterns:
|
|
101
|
+
for expanded in expand_braces(p):
|
|
102
|
+
if expanded not in out:
|
|
103
|
+
out.append(expanded)
|
|
104
|
+
return out
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def split_negations(patterns: Sequence[str]) -> Tuple[List[str], List[str]]:
|
|
108
|
+
"""Splits Vite-style `['./a/*', '!./a/skip*']` into positives and negatives."""
|
|
109
|
+
positive: List[str] = []
|
|
110
|
+
negative: List[str] = []
|
|
111
|
+
for raw in patterns:
|
|
112
|
+
p = str(raw or "").strip()
|
|
113
|
+
if not p:
|
|
114
|
+
continue
|
|
115
|
+
if p.startswith("!"):
|
|
116
|
+
negative.append(p[1:])
|
|
117
|
+
else:
|
|
118
|
+
positive.append(p)
|
|
119
|
+
return positive, negative
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def matches_any(patterns: Sequence[str], rel_path: str, basename: Optional[str] = None) -> bool:
|
|
123
|
+
base = basename if basename is not None else os.path.basename(rel_path)
|
|
124
|
+
return any(fnmatch.fnmatch(rel_path, p) or fnmatch.fnmatch(base, p) for p in patterns)
|