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
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
"""One-call file brief for OUMV.
|
|
2
|
+
|
|
3
|
+
`observe` answers "what surface does this workspace expose", `smart_read_file`
|
|
4
|
+
answers "what does this symbol contain", and `understand(impact)` answers "who
|
|
5
|
+
depends on it". Reading one component used to cost three or four calls plus a
|
|
6
|
+
manual merge. `build_brief` composes the same primitives into one payload:
|
|
7
|
+
skeleton, exports, public props, mutable module state and every call site.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
from typing import Any, Dict, List, Optional
|
|
14
|
+
|
|
15
|
+
from src.graph_engine import GraphEngine
|
|
16
|
+
|
|
17
|
+
_MAX_SKELETON_CHARS = 16000
|
|
18
|
+
_MAX_ITEMS = 40
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _read_text(path: str) -> str:
|
|
22
|
+
try:
|
|
23
|
+
if os.path.getsize(path) > 2 * 1024 * 1024:
|
|
24
|
+
return ""
|
|
25
|
+
with open(path, "r", encoding="utf-8", errors="replace") as fh:
|
|
26
|
+
return fh.read()
|
|
27
|
+
except OSError:
|
|
28
|
+
return ""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _braced_block(code: str, open_idx: int) -> Optional[str]:
|
|
32
|
+
depth = 0
|
|
33
|
+
for i in range(open_idx, len(code)):
|
|
34
|
+
ch = code[i]
|
|
35
|
+
if ch == "{":
|
|
36
|
+
depth += 1
|
|
37
|
+
elif ch == "}":
|
|
38
|
+
depth -= 1
|
|
39
|
+
if depth == 0:
|
|
40
|
+
return code[open_idx + 1:i]
|
|
41
|
+
return None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _parse_members(body: str) -> List[Dict[str, Any]]:
|
|
45
|
+
members: List[Dict[str, Any]] = []
|
|
46
|
+
for raw_line in body.splitlines():
|
|
47
|
+
line = raw_line.strip()
|
|
48
|
+
if not line or line.startswith(("//", "/*", "*", "*/")):
|
|
49
|
+
continue
|
|
50
|
+
line = line.rstrip(",").rstrip(";").strip()
|
|
51
|
+
m = re.match(r"(?:readonly\s+)?([A-Za-z_$][\w$]*)(\?)?\s*:\s*(.+)$", line)
|
|
52
|
+
if m:
|
|
53
|
+
members.append({
|
|
54
|
+
"name": m.group(1),
|
|
55
|
+
"optional": bool(m.group(2)),
|
|
56
|
+
"type": m.group(3).strip(),
|
|
57
|
+
})
|
|
58
|
+
elif re.match(r"^[A-Za-z_$][\w$]*$", line):
|
|
59
|
+
members.append({"name": line, "optional": False, "type": "unknown"})
|
|
60
|
+
return members[:_MAX_ITEMS]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _extract_public_props(code: str, component_names: List[str]) -> Optional[Dict[str, Any]]:
|
|
64
|
+
"""Best-effort props contract: named interface/type first, destructuring second."""
|
|
65
|
+
candidates: List[str] = []
|
|
66
|
+
for name in component_names:
|
|
67
|
+
for type_name in (f"{name}Props", f"{name}Properties", "Props"):
|
|
68
|
+
if type_name not in candidates:
|
|
69
|
+
candidates.append(type_name)
|
|
70
|
+
|
|
71
|
+
for type_name in candidates:
|
|
72
|
+
decl = re.search(
|
|
73
|
+
rf"(?:export\s+)?(?:interface\s+{re.escape(type_name)}\b[^{{]*|type\s+{re.escape(type_name)}\s*=\s*)",
|
|
74
|
+
code,
|
|
75
|
+
)
|
|
76
|
+
if not decl:
|
|
77
|
+
continue
|
|
78
|
+
open_idx = code.find("{", decl.end())
|
|
79
|
+
if open_idx == -1:
|
|
80
|
+
continue
|
|
81
|
+
body = _braced_block(code, open_idx)
|
|
82
|
+
if not body:
|
|
83
|
+
continue
|
|
84
|
+
members = _parse_members(body)
|
|
85
|
+
if members:
|
|
86
|
+
return {
|
|
87
|
+
"name": type_name,
|
|
88
|
+
"source": "type_literal",
|
|
89
|
+
"members": members,
|
|
90
|
+
"confidence": "probable",
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
for name in component_names:
|
|
94
|
+
decl = re.search(
|
|
95
|
+
rf"(?:function\s+{re.escape(name)}\s*(?:<[^>]*>)?\s*\(|"
|
|
96
|
+
rf"const\s+{re.escape(name)}\s*(?::[^=]+)?=\s*(?:React\.)?(?:memo|forwardRef)?\s*\()",
|
|
97
|
+
code,
|
|
98
|
+
)
|
|
99
|
+
if not decl:
|
|
100
|
+
continue
|
|
101
|
+
open_idx = code.find("{", decl.end())
|
|
102
|
+
if open_idx == -1:
|
|
103
|
+
continue
|
|
104
|
+
body = _braced_block(code, open_idx)
|
|
105
|
+
if not body or "\n" in body:
|
|
106
|
+
continue
|
|
107
|
+
members: List[Dict[str, Any]] = []
|
|
108
|
+
for part in body.split(","):
|
|
109
|
+
part = part.strip()
|
|
110
|
+
if not part or part.startswith("..."):
|
|
111
|
+
continue
|
|
112
|
+
raw_name = part.split(":", 1)[0].split("=", 1)[0].strip()
|
|
113
|
+
if not re.match(r"^[A-Za-z_$][\w$]*$", raw_name):
|
|
114
|
+
continue
|
|
115
|
+
typed = part.split(":", 1)[1].strip() if ":" in part else ""
|
|
116
|
+
type_str = typed.split("=", 1)[0].strip() if typed else "unknown"
|
|
117
|
+
members.append({
|
|
118
|
+
"name": raw_name,
|
|
119
|
+
"optional": "=" in part,
|
|
120
|
+
"type": type_str or "unknown",
|
|
121
|
+
})
|
|
122
|
+
if members:
|
|
123
|
+
return {
|
|
124
|
+
"name": None,
|
|
125
|
+
"source": "destructured_params",
|
|
126
|
+
"members": members[:_MAX_ITEMS],
|
|
127
|
+
"confidence": "probable",
|
|
128
|
+
}
|
|
129
|
+
return None
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
_JS_STATE_RE = re.compile(r"^(?:export\s+)?(let|var)\s+([A-Za-z_$][\w$]*)")
|
|
133
|
+
_PY_STATE_RE = re.compile(r"^([A-Za-z_][\w]*)\s*(?::[^=]+)?=")
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _extract_module_state(code: str, ext: str, lines: List[str]) -> List[Dict[str, Any]]:
|
|
137
|
+
"""Mutable module-level state: `let`/`var` in JS/TS, globals in Python."""
|
|
138
|
+
out: List[Dict[str, Any]] = []
|
|
139
|
+
if ext in (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"):
|
|
140
|
+
for line_no, line in enumerate(lines, 1):
|
|
141
|
+
m = _JS_STATE_RE.match(line)
|
|
142
|
+
if m:
|
|
143
|
+
out.append({
|
|
144
|
+
"name": m.group(2),
|
|
145
|
+
"kind": m.group(1),
|
|
146
|
+
"line": line_no,
|
|
147
|
+
"snippet": line.strip()[:120],
|
|
148
|
+
})
|
|
149
|
+
elif ext == ".py":
|
|
150
|
+
for line_no, line in enumerate(lines, 1):
|
|
151
|
+
if not line or line[0].isspace():
|
|
152
|
+
continue
|
|
153
|
+
stripped = line.lstrip()
|
|
154
|
+
if stripped.startswith(("def ", "class ", "import ", "from ", "@", "#")):
|
|
155
|
+
continue
|
|
156
|
+
m = _PY_STATE_RE.match(line)
|
|
157
|
+
if m:
|
|
158
|
+
out.append({
|
|
159
|
+
"name": m.group(1),
|
|
160
|
+
"kind": "module_global",
|
|
161
|
+
"line": line_no,
|
|
162
|
+
"snippet": line.strip()[:120],
|
|
163
|
+
})
|
|
164
|
+
return out[:20]
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _file_symbols(graph: Any, rel: str, lines: List[str]) -> List[Dict[str, Any]]:
|
|
168
|
+
out: List[Dict[str, Any]] = []
|
|
169
|
+
for key in graph.file_symbols.get(rel, []):
|
|
170
|
+
sym = graph.symbols.get(key)
|
|
171
|
+
if not sym:
|
|
172
|
+
continue
|
|
173
|
+
sig_line = lines[sym.line_start - 1] if 0 < sym.line_start <= len(lines) else ""
|
|
174
|
+
out.append({
|
|
175
|
+
"name": sym.name,
|
|
176
|
+
"kind": sym.kind,
|
|
177
|
+
"lines": [sym.line_start, sym.line_end],
|
|
178
|
+
"signature": sym.signature,
|
|
179
|
+
"exported": bool(re.match(r"\s*export\b", sig_line)),
|
|
180
|
+
})
|
|
181
|
+
return out[:_MAX_ITEMS]
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _node_info(graph: Any, node: str) -> Dict[str, Any]:
|
|
185
|
+
if node.startswith("file:"):
|
|
186
|
+
return {"type": "file", "file": node[5:]}
|
|
187
|
+
sym = graph.symbols.get(node)
|
|
188
|
+
if sym:
|
|
189
|
+
return {"type": "symbol", "name": sym.name, "kind": sym.kind, "file": sym.file_path}
|
|
190
|
+
return {"type": "node", "id": node}
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _call_sites(graph: Any, names: List[str], impact: Dict[str, Any]) -> Dict[str, Any]:
|
|
194
|
+
graph_sites: List[Dict[str, Any]] = []
|
|
195
|
+
seen: set = set()
|
|
196
|
+
for name in names:
|
|
197
|
+
for node in graph.rev_edges.get(f"call:{name}", set()):
|
|
198
|
+
info = _node_info(graph, node)
|
|
199
|
+
key = (info.get("type"), info.get("file"), info.get("name"), info.get("id"))
|
|
200
|
+
if key in seen:
|
|
201
|
+
continue
|
|
202
|
+
seen.add(key)
|
|
203
|
+
info["via"] = name
|
|
204
|
+
info["confidence"] = "probable"
|
|
205
|
+
graph_sites.append(info)
|
|
206
|
+
for dep in impact.get("directDependents", []):
|
|
207
|
+
file_ref = dep.get("file") or dep.get("id") or ""
|
|
208
|
+
key = ("dependent", file_ref)
|
|
209
|
+
if key in seen:
|
|
210
|
+
continue
|
|
211
|
+
seen.add(key)
|
|
212
|
+
graph_sites.append({
|
|
213
|
+
"type": dep.get("type") or "file",
|
|
214
|
+
"file": file_ref,
|
|
215
|
+
"name": dep.get("name"),
|
|
216
|
+
"via": "import_edge",
|
|
217
|
+
"confidence": "probable",
|
|
218
|
+
})
|
|
219
|
+
text_level = impact.get("textLevelReferences", [])
|
|
220
|
+
return {
|
|
221
|
+
"graph": graph_sites[:25],
|
|
222
|
+
"textLevel": text_level[:25],
|
|
223
|
+
"total": len(graph_sites) + len(text_level),
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def build_brief(workspace: str, target: str, symbol: Optional[str] = None) -> Dict[str, Any]:
|
|
228
|
+
"""Builds the single-call brief for one file or symbol."""
|
|
229
|
+
raw = (target or "").strip()
|
|
230
|
+
evidence = {
|
|
231
|
+
"provenance": "static",
|
|
232
|
+
"sourceAdapter": "tokensafe-graph-engine",
|
|
233
|
+
"confidence": "probable",
|
|
234
|
+
}
|
|
235
|
+
if not raw:
|
|
236
|
+
return {
|
|
237
|
+
"target": raw,
|
|
238
|
+
"targetResolved": False,
|
|
239
|
+
"error": "target or path is required",
|
|
240
|
+
"warnings": ["target or path is required"],
|
|
241
|
+
"evidence": evidence,
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
graph = GraphEngine.get_instance(workspace)
|
|
245
|
+
graph.scan()
|
|
246
|
+
rel = graph._as_repo_rel(raw)
|
|
247
|
+
target_symbol = (symbol or "").strip() or None
|
|
248
|
+
warnings: List[str] = []
|
|
249
|
+
|
|
250
|
+
if rel not in graph.file_stats and rel not in graph.file_symbols:
|
|
251
|
+
# A bare component name is a valid brief target too.
|
|
252
|
+
matches = [
|
|
253
|
+
key for key, sym in graph.symbols.items()
|
|
254
|
+
if sym.name == rel or key.endswith(f"::{rel}")
|
|
255
|
+
]
|
|
256
|
+
if matches:
|
|
257
|
+
stem = os.path.splitext(os.path.basename(rel))[0].lower()
|
|
258
|
+
|
|
259
|
+
def _rank(key: str) -> tuple:
|
|
260
|
+
sym = graph.symbols[key]
|
|
261
|
+
file_stem = os.path.splitext(os.path.basename(sym.file_path))[0].lower()
|
|
262
|
+
return (
|
|
263
|
+
0 if file_stem == stem else 1,
|
|
264
|
+
0 if sym.signature.lstrip().startswith("export") else 1,
|
|
265
|
+
sym.file_path,
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
matches.sort(key=_rank)
|
|
269
|
+
target_symbol = target_symbol or graph.symbols[matches[0]].name
|
|
270
|
+
rel = graph.symbols[matches[0]].file_path
|
|
271
|
+
else:
|
|
272
|
+
return {
|
|
273
|
+
"target": raw,
|
|
274
|
+
"targetResolved": False,
|
|
275
|
+
"warnings": ["target not found in the graph index"],
|
|
276
|
+
"suggestions": graph._suggest_targets(rel),
|
|
277
|
+
"evidence": evidence,
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
full = os.path.join(graph.root_dir, rel)
|
|
281
|
+
code = _read_text(full)
|
|
282
|
+
lines = code.splitlines() if code else []
|
|
283
|
+
ext = os.path.splitext(rel)[1].lower()
|
|
284
|
+
|
|
285
|
+
symbols = _file_symbols(graph, rel, lines)
|
|
286
|
+
exported = [s for s in symbols if s["exported"]] or symbols
|
|
287
|
+
component_names = [s["name"] for s in exported if s["name"][:1].isupper()]
|
|
288
|
+
if not component_names:
|
|
289
|
+
component_names = [os.path.splitext(os.path.basename(rel))[0]]
|
|
290
|
+
|
|
291
|
+
props = None
|
|
292
|
+
if ext in (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"):
|
|
293
|
+
props = _extract_public_props(code, component_names)
|
|
294
|
+
module_state = _extract_module_state(code, ext, lines)
|
|
295
|
+
|
|
296
|
+
skeleton = ""
|
|
297
|
+
try:
|
|
298
|
+
skeleton = graph.graph_guided_skeletonize(
|
|
299
|
+
full, target_symbol, include_deps=True, dep_mode="signature"
|
|
300
|
+
)
|
|
301
|
+
except Exception:
|
|
302
|
+
skeleton = ""
|
|
303
|
+
if not skeleton:
|
|
304
|
+
try:
|
|
305
|
+
from src.skeletonizer import Skeletonizer
|
|
306
|
+
skel_path, _orig, _skel = Skeletonizer.get_skeleton_file(full, target_symbol)
|
|
307
|
+
skeleton = _read_text(skel_path) if skel_path else ""
|
|
308
|
+
except Exception:
|
|
309
|
+
skeleton = ""
|
|
310
|
+
if len(skeleton) > _MAX_SKELETON_CHARS:
|
|
311
|
+
skeleton = skeleton[:_MAX_SKELETON_CHARS] + "\n// [brief: skeleton truncated]"
|
|
312
|
+
warnings.append(f"skeleton truncated at {_MAX_SKELETON_CHARS} chars")
|
|
313
|
+
|
|
314
|
+
impact = graph.get_static_impact(rel)
|
|
315
|
+
names = [s["name"] for s in exported]
|
|
316
|
+
if target_symbol and target_symbol not in names:
|
|
317
|
+
names.insert(0, target_symbol)
|
|
318
|
+
call_sites = _call_sites(graph, names, impact)
|
|
319
|
+
if not call_sites["graph"] and call_sites["textLevel"]:
|
|
320
|
+
warnings.append(
|
|
321
|
+
"no static import/call edge; call sites are probable text-level references"
|
|
322
|
+
)
|
|
323
|
+
if impact.get("textLevelCoverage", {}).get("partial"):
|
|
324
|
+
warnings.append("text-level call-site scan was bounded")
|
|
325
|
+
|
|
326
|
+
brief: Dict[str, Any] = {
|
|
327
|
+
"target": rel,
|
|
328
|
+
"targetResolved": True,
|
|
329
|
+
"targetKind": "symbol" if target_symbol else "file",
|
|
330
|
+
"file": graph._file_facts(rel),
|
|
331
|
+
"exports": exported,
|
|
332
|
+
"publicProps": props,
|
|
333
|
+
"moduleState": module_state,
|
|
334
|
+
"skeleton": skeleton,
|
|
335
|
+
"callSites": call_sites,
|
|
336
|
+
"warnings": warnings + impact.get("warnings", []),
|
|
337
|
+
"coverage": {
|
|
338
|
+
"textLevel": impact.get("textLevelCoverage"),
|
|
339
|
+
"skeletonChars": len(skeleton),
|
|
340
|
+
"symbols": len(symbols),
|
|
341
|
+
},
|
|
342
|
+
"evidence": evidence,
|
|
343
|
+
}
|
|
344
|
+
if target_symbol:
|
|
345
|
+
brief["symbol"] = target_symbol
|
|
346
|
+
return brief
|
package/src/oumv_gateway.py
CHANGED
|
@@ -153,6 +153,7 @@ class OUMVGateway:
|
|
|
153
153
|
"""Scans workspace runtime lockfiles and local ports in parallel."""
|
|
154
154
|
ws = workspace_dir or get_active_workspace() or os.getcwd()
|
|
155
155
|
st = cls._state_for(ws)
|
|
156
|
+
st["stale"] = []
|
|
156
157
|
st["last_scan"] = time.time()
|
|
157
158
|
|
|
158
159
|
# 1. Check workspace runtime files (.tokensafe/runtime.json or .oumv/runtime.json)
|
|
@@ -240,6 +241,11 @@ class OUMVGateway:
|
|
|
240
241
|
except Exception:
|
|
241
242
|
return True
|
|
242
243
|
|
|
244
|
+
@staticmethod
|
|
245
|
+
def _record_stale(st: Dict[str, Any], kind: Any, url: Any, reason: str) -> None:
|
|
246
|
+
"""Collects a descriptor that must not be adopted, with the reason."""
|
|
247
|
+
st.setdefault("stale", []).append({"kind": kind, "url": url, "reason": reason})
|
|
248
|
+
|
|
243
249
|
@classmethod
|
|
244
250
|
def _check_workspace_runtime_files(cls, workspace_dir: str, st: Optional[Dict[str, Any]] = None):
|
|
245
251
|
st = st if st is not None else cls._state_for(workspace_dir)
|
|
@@ -248,42 +254,102 @@ class OUMVGateway:
|
|
|
248
254
|
os.path.join(workspace_dir, ".tokensafe", "runtime.json"),
|
|
249
255
|
os.path.join(workspace_dir, ".oumv", "runtime.json"),
|
|
250
256
|
) if cls._descriptor_path_is_trusted(lp, workspace_dir)]
|
|
257
|
+
now = time.time()
|
|
251
258
|
for lp in lock_paths:
|
|
252
|
-
if os.path.isfile(lp):
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
259
|
+
if not os.path.isfile(lp):
|
|
260
|
+
continue
|
|
261
|
+
try:
|
|
262
|
+
# §9.2: a reader treats a descriptor without a live handshake as
|
|
263
|
+
# stale, and an old one is stale by age even if a port answers.
|
|
264
|
+
if now - os.path.getmtime(lp) > cls._DESCRIPTOR_MAX_AGE_SEC:
|
|
265
|
+
cls._record_stale(st, None, None, f"{os.path.basename(lp)} is older than 12 h (stale dev server)")
|
|
266
|
+
continue
|
|
267
|
+
with open(lp, "r", encoding="utf-8") as f:
|
|
268
|
+
data = json.load(f)
|
|
269
|
+
if not isinstance(data, dict):
|
|
270
|
+
raise ValueError("descriptor root is not an object")
|
|
271
|
+
except Exception as exc:
|
|
272
|
+
# A corrupt registry must be reported, never silently trusted.
|
|
273
|
+
cls._record_stale(st, None, None, f"{os.path.basename(lp)} is unreadable: {exc}")
|
|
274
|
+
continue
|
|
275
|
+
fe_info = data.get("frontend")
|
|
276
|
+
if fe_info and fe_info.get("url"):
|
|
277
|
+
entry = {
|
|
278
|
+
"kind": "frontend",
|
|
279
|
+
"name": fe_info.get("name", "tokensafe-ui"),
|
|
280
|
+
"version": fe_info.get("version", "1.0.0"),
|
|
281
|
+
"url": fe_info["url"],
|
|
282
|
+
"sessionToken": fe_info.get("sessionToken"),
|
|
283
|
+
"healthy": True,
|
|
284
|
+
"source": "descriptor",
|
|
285
|
+
"capabilities": fe_info.get("capabilities", {}),
|
|
286
|
+
}
|
|
287
|
+
if cls._runtime_is_reachable(entry["url"], entry.get("sessionToken")):
|
|
288
|
+
st["fe"] = entry
|
|
289
|
+
else:
|
|
290
|
+
cls._record_stale(st, "frontend", entry["url"], "descriptor present but no live OUMV handshake")
|
|
291
|
+
be_info = data.get("backend")
|
|
292
|
+
if be_info and be_info.get("url"):
|
|
293
|
+
entry = {
|
|
294
|
+
"kind": "backend",
|
|
295
|
+
"name": be_info.get("name", "tokensafe-backend"),
|
|
296
|
+
"version": be_info.get("version", "1.0.0"),
|
|
297
|
+
"url": be_info["url"],
|
|
298
|
+
"sessionToken": be_info.get("session_token") or be_info.get("sessionToken"),
|
|
299
|
+
"healthy": True,
|
|
300
|
+
"source": "descriptor",
|
|
301
|
+
"capabilities": be_info.get("capabilities", {}),
|
|
302
|
+
# Spec §7.4: the descriptor names its browser bridge, so
|
|
303
|
+
# discovery knows client components are reachable.
|
|
304
|
+
**({"bridge": be_info.get("frontend")} if be_info.get("frontend") else {}),
|
|
305
|
+
}
|
|
306
|
+
if cls._runtime_is_reachable(entry["url"], entry.get("sessionToken")):
|
|
307
|
+
st["be"] = entry
|
|
308
|
+
else:
|
|
309
|
+
cls._record_stale(st, "backend", entry["url"], "descriptor present but no live OUMV handshake")
|
|
285
310
|
return st
|
|
286
311
|
|
|
312
|
+
@classmethod
|
|
313
|
+
def prune_stale_descriptors(cls, workspace_dir: Optional[str] = None) -> List[str]:
|
|
314
|
+
"""Removes this workspace's descriptors that have no live runtime.
|
|
315
|
+
|
|
316
|
+
Explicit `tokensafe oumv doctor --prune` only: a reader never deletes a
|
|
317
|
+
file on its own (it could race a writer that is just starting up).
|
|
318
|
+
"""
|
|
319
|
+
ws = workspace_dir or get_active_workspace() or os.getcwd()
|
|
320
|
+
removed: List[str] = []
|
|
321
|
+
for path in (
|
|
322
|
+
cls.global_runtime_file(ws),
|
|
323
|
+
os.path.join(ws, ".tokensafe", "runtime.json"),
|
|
324
|
+
os.path.join(ws, ".oumv", "runtime.json"),
|
|
325
|
+
):
|
|
326
|
+
if not os.path.isfile(path):
|
|
327
|
+
continue
|
|
328
|
+
try:
|
|
329
|
+
if time.time() - os.path.getmtime(path) > cls._DESCRIPTOR_MAX_AGE_SEC:
|
|
330
|
+
os.unlink(path)
|
|
331
|
+
removed.append(path)
|
|
332
|
+
continue
|
|
333
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
334
|
+
data = json.load(f)
|
|
335
|
+
if not isinstance(data, dict):
|
|
336
|
+
raise ValueError("descriptor root is not an object")
|
|
337
|
+
except Exception:
|
|
338
|
+
os.unlink(path)
|
|
339
|
+
removed.append(path)
|
|
340
|
+
continue
|
|
341
|
+
live = False
|
|
342
|
+
for key in ("frontend", "backend"):
|
|
343
|
+
info = data.get(key)
|
|
344
|
+
if info and info.get("url") and cls._runtime_is_reachable(
|
|
345
|
+
info["url"], info.get("sessionToken")
|
|
346
|
+
):
|
|
347
|
+
live = True
|
|
348
|
+
if not live:
|
|
349
|
+
os.unlink(path)
|
|
350
|
+
removed.append(path)
|
|
351
|
+
return removed
|
|
352
|
+
|
|
287
353
|
@classmethod
|
|
288
354
|
def _probe_candidates(cls, urls: List[str], kind: str) -> Optional[Dict[str, Any]]:
|
|
289
355
|
for url in urls:
|
|
@@ -322,18 +388,25 @@ class OUMVGateway:
|
|
|
322
388
|
return None
|
|
323
389
|
|
|
324
390
|
@classmethod
|
|
325
|
-
def _runtime_is_reachable(cls, url: Optional[str]) -> bool:
|
|
391
|
+
def _runtime_is_reachable(cls, url: Optional[str], token: Optional[str] = None) -> bool:
|
|
326
392
|
"""True when a live OUMV runtime answers a handshake at `url`."""
|
|
327
393
|
if not url:
|
|
328
394
|
return False
|
|
329
395
|
try:
|
|
330
|
-
res = cls._rpc_call(url, "oumv/handshake", {"protocolVersion": "1.6.0"}, timeout=0.35)
|
|
396
|
+
res = cls._rpc_call(url, "oumv/handshake", {"protocolVersion": "1.6.0"}, timeout=0.35, token=token)
|
|
331
397
|
except Exception:
|
|
332
398
|
return False
|
|
333
399
|
return bool(res and isinstance(res, dict) and "runtimeInfo" in res)
|
|
334
400
|
|
|
335
401
|
@classmethod
|
|
336
|
-
def _rpc_call(
|
|
402
|
+
def _rpc_call(
|
|
403
|
+
cls,
|
|
404
|
+
endpoint_url: str,
|
|
405
|
+
method: str,
|
|
406
|
+
params: Optional[dict] = None,
|
|
407
|
+
timeout: float = 3.0,
|
|
408
|
+
token: Optional[str] = None,
|
|
409
|
+
) -> Any:
|
|
337
410
|
payload = json.dumps({
|
|
338
411
|
"jsonrpc": "2.0",
|
|
339
412
|
"id": 1,
|
|
@@ -343,13 +416,14 @@ class OUMVGateway:
|
|
|
343
416
|
|
|
344
417
|
headers = {"Content-Type": "application/json", "User-Agent": "TokenSafe-Gateway/1.0"}
|
|
345
418
|
# Session tokens live in per-workspace states; a URL identifies its runtime
|
|
346
|
-
# unambiguously, so scan every root's state for a match.
|
|
347
|
-
token
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
419
|
+
# unambiguously, so scan every root's state for a match. A descriptor probe
|
|
420
|
+
# passes the token before the entry is adopted.
|
|
421
|
+
if token is None:
|
|
422
|
+
for st in cls._workspace_states.values():
|
|
423
|
+
if st.get("fe", {}) and st["fe"].get("url") == endpoint_url:
|
|
424
|
+
token = st["fe"].get("sessionToken")
|
|
425
|
+
elif st.get("be", {}) and st["be"].get("url") == endpoint_url:
|
|
426
|
+
token = st["be"].get("sessionToken")
|
|
353
427
|
|
|
354
428
|
if token:
|
|
355
429
|
headers["X-OUMV-Session-Token"] = token
|
|
@@ -561,6 +635,11 @@ class OUMVGateway:
|
|
|
561
635
|
}
|
|
562
636
|
for d in dropped
|
|
563
637
|
]
|
|
638
|
+
# Descriptors rejected by the scan (corrupt file, expired TTL, no live
|
|
639
|
+
# handshake) are reported too, so the downgrade is visible and explained.
|
|
640
|
+
recorded_stale = list(st.get("stale") or [])
|
|
641
|
+
if recorded_stale:
|
|
642
|
+
result["staleRuntimes"] = result.get("staleRuntimes", []) + recorded_stale
|
|
564
643
|
# A cold AST crawl costs ~15 s on a large monorepo. Start it now, in the
|
|
565
644
|
# background: the first repo_map/observe/mutate call then finds it warm
|
|
566
645
|
# instead of spending the whole tool budget waiting for it.
|
|
@@ -775,6 +854,16 @@ class OUMVGateway:
|
|
|
775
854
|
graph = GraphEngine.get_instance(ws)
|
|
776
855
|
return graph.get_static_oumv_slice(level=level, target=target)
|
|
777
856
|
|
|
857
|
+
# 2.5 Tool: oumv_brief — one call for skeleton + call sites + props + state
|
|
858
|
+
@classmethod
|
|
859
|
+
def brief(cls, target: Optional[str] = None, symbol: Optional[str] = None,
|
|
860
|
+
workspace_dir: Optional[str] = None, path: Optional[str] = None) -> Any:
|
|
861
|
+
cls.mark_oumv_used(workspace_dir)
|
|
862
|
+
target = cls._observe_target(target, path, workspace_dir)
|
|
863
|
+
from src.oumv_brief import build_brief
|
|
864
|
+
ws = workspace_dir or get_active_workspace() or os.getcwd()
|
|
865
|
+
return build_brief(ws, target or "", symbol=symbol)
|
|
866
|
+
|
|
778
867
|
# 3. Tool: oumv_understand
|
|
779
868
|
@classmethod
|
|
780
869
|
def understand(cls, query: str = "causality", target: Optional[str] = None, runtime: str = "auto",
|