tokensafe 4.7.8 → 4.7.10
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/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/auto_inject.py +312 -33
- package/src/installer.py +17 -10
- package/src/mcp_server.py +133 -14
- package/src/oumv_gateway.py +376 -52
- package/src/retrofit.py +69 -10
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
package/src/oumv_gateway.py
CHANGED
|
@@ -41,9 +41,10 @@ _UNSUPPORTED_HINTS = (
|
|
|
41
41
|
class OUMVGateway:
|
|
42
42
|
"""Dispatches OUMV protocol calls to live DevServers with zero-config discovery."""
|
|
43
43
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
44
|
+
# Per-workspace endpoint cache: one process serves several workspace roots
|
|
45
|
+
# (multi-root sessions), so root A's live runtime must never leak into
|
|
46
|
+
# root B's status/observe answer.
|
|
47
|
+
_workspace_states: Dict[str, Dict[str, Any]] = {}
|
|
47
48
|
_SCAN_INTERVAL_SEC: float = 5.0
|
|
48
49
|
# Liveness cache for descriptor-derived ports: the bash guard runs per command,
|
|
49
50
|
# so a TCP probe must be memoized instead of blocking every invocation.
|
|
@@ -88,40 +89,68 @@ class OUMVGateway:
|
|
|
88
89
|
return cls._is_port_open(parsed.hostname or "127.0.0.1", int(port))
|
|
89
90
|
|
|
90
91
|
@classmethod
|
|
91
|
-
def
|
|
92
|
+
def _ws_key(cls, workspace_dir: Optional[str] = None) -> str:
|
|
93
|
+
"""Canonical per-workspace cache key (realpath'd, never empty)."""
|
|
94
|
+
base = workspace_dir or get_active_workspace() or os.getcwd()
|
|
95
|
+
return os.path.realpath(os.path.abspath(base))
|
|
96
|
+
|
|
97
|
+
@classmethod
|
|
98
|
+
def _state_for(cls, workspace_dir: Optional[str] = None) -> Dict[str, Any]:
|
|
99
|
+
"""Per-workspace endpoint state: {"fe", "be", "last_scan"}."""
|
|
100
|
+
return cls._workspace_states.setdefault(
|
|
101
|
+
cls._ws_key(workspace_dir), {"fe": None, "be": None, "last_scan": 0.0}
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
@classmethod
|
|
105
|
+
def _drop_stale_descriptor_endpoints(cls, workspace_dir: Optional[str] = None) -> List[Dict[str, Any]]:
|
|
92
106
|
"""Clears descriptor-sourced endpoints whose port no longer listens.
|
|
93
107
|
|
|
94
108
|
A descriptor is a hint written by the dev server; after a crash it keeps
|
|
95
109
|
pointing at a dead (or reused) port and every consumer would report CONNECTED.
|
|
110
|
+
Without a workspace_dir, every cached workspace is checked; with one, only
|
|
111
|
+
that root's state is touched (and its drops reported to the caller).
|
|
96
112
|
Returns the dropped entries so callers can explain the downgrade.
|
|
97
113
|
"""
|
|
98
114
|
dropped: List[Dict[str, Any]] = []
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
115
|
+
if workspace_dir is not None:
|
|
116
|
+
states = [cls._state_for(workspace_dir)]
|
|
117
|
+
elif cls._workspace_states:
|
|
118
|
+
states = list(cls._workspace_states.values())
|
|
119
|
+
else:
|
|
120
|
+
states = [cls._state_for(None)]
|
|
121
|
+
for st in states:
|
|
122
|
+
for slot in ("fe", "be"):
|
|
123
|
+
entry = st.get(slot)
|
|
124
|
+
if entry and entry.get("source") == "descriptor":
|
|
125
|
+
url = entry.get("url")
|
|
126
|
+
if url and not cls._is_url_live(url):
|
|
127
|
+
dropped.append(entry)
|
|
128
|
+
st[slot] = None
|
|
106
129
|
return dropped
|
|
107
130
|
|
|
108
131
|
@classmethod
|
|
109
132
|
def get_endpoints(cls, workspace_dir: Optional[str] = None) -> Tuple[Optional[Dict[str, Any]], Optional[Dict[str, Any]]]:
|
|
110
|
-
"""Returns (frontend_endpoint, backend_endpoint)
|
|
133
|
+
"""Returns (frontend_endpoint, backend_endpoint) for the given workspace root.
|
|
134
|
+
|
|
135
|
+
Each root has its own scan timestamp and endpoint pair; a scan performed for
|
|
136
|
+
root A never satisfies root B's discovery.
|
|
137
|
+
"""
|
|
138
|
+
st = cls._state_for(workspace_dir)
|
|
111
139
|
now = time.time()
|
|
112
|
-
if (now -
|
|
140
|
+
if (now - st["last_scan"] > cls._SCAN_INTERVAL_SEC) or (not st["fe"] and not st["be"]):
|
|
113
141
|
cls.scan(workspace_dir=workspace_dir)
|
|
114
|
-
cls._drop_stale_descriptor_endpoints()
|
|
115
|
-
return
|
|
142
|
+
cls._drop_stale_descriptor_endpoints(workspace_dir)
|
|
143
|
+
return st["fe"], st["be"]
|
|
116
144
|
|
|
117
145
|
@classmethod
|
|
118
146
|
def scan(cls, workspace_dir: Optional[str] = None):
|
|
119
147
|
"""Scans workspace runtime lockfiles and local ports in parallel."""
|
|
120
|
-
|
|
121
|
-
|
|
148
|
+
ws = workspace_dir or get_active_workspace() or os.getcwd()
|
|
149
|
+
st = cls._state_for(ws)
|
|
150
|
+
st["last_scan"] = time.time()
|
|
122
151
|
|
|
123
152
|
# 1. Check workspace runtime files (.tokensafe/runtime.json or .oumv/runtime.json)
|
|
124
|
-
cls._check_workspace_runtime_files(ws)
|
|
153
|
+
cls._check_workspace_runtime_files(ws, st)
|
|
125
154
|
|
|
126
155
|
# 2. Parallel candidate probe for remaining missing endpoints
|
|
127
156
|
env_fe = os.environ.get("TOKENSAFE_FRONTEND_URL")
|
|
@@ -149,17 +178,17 @@ class OUMVGateway:
|
|
|
149
178
|
]
|
|
150
179
|
|
|
151
180
|
with ThreadPoolExecutor(max_workers=6) as executor:
|
|
152
|
-
future_fe = executor.submit(cls._probe_candidates, fe_candidates, "frontend") if not
|
|
153
|
-
future_be = executor.submit(cls._probe_candidates, be_candidates, "backend") if not
|
|
181
|
+
future_fe = executor.submit(cls._probe_candidates, fe_candidates, "frontend") if not st["fe"] else None
|
|
182
|
+
future_be = executor.submit(cls._probe_candidates, be_candidates, "backend") if not st["be"] else None
|
|
154
183
|
|
|
155
184
|
if future_fe:
|
|
156
185
|
found_fe = future_fe.result()
|
|
157
186
|
if found_fe:
|
|
158
|
-
|
|
187
|
+
st["fe"] = found_fe
|
|
159
188
|
if future_be:
|
|
160
189
|
found_be = future_be.result()
|
|
161
190
|
if found_be:
|
|
162
|
-
|
|
191
|
+
st["be"] = found_be
|
|
163
192
|
|
|
164
193
|
@staticmethod
|
|
165
194
|
def global_runtime_file(workspace_dir: str) -> str:
|
|
@@ -169,13 +198,50 @@ class OUMVGateway:
|
|
|
169
198
|
tokensafe_home = os.environ.get("TOKENSAFE_HOME") or os.path.expanduser("~/.tokensafe")
|
|
170
199
|
return os.path.join(tokensafe_home, "runtimes", f"{ws_id}.json")
|
|
171
200
|
|
|
201
|
+
@staticmethod
|
|
202
|
+
def _descriptor_path_is_trusted(path: str, workspace_dir: Optional[str] = None) -> bool:
|
|
203
|
+
"""A global descriptor whose workspace died must not be adopted.
|
|
204
|
+
|
|
205
|
+
Transient roots (system temp dirs) outlive their dev servers: a leftover
|
|
206
|
+
descriptor keeps describing a directory that no longer exists. Such an
|
|
207
|
+
entry is trusted only while the recorded root is still on disk (so live
|
|
208
|
+
smoke-test/benchmark workspaces in temp dirs keep working); user-project
|
|
209
|
+
roots are always trusted and rely on the port-liveness check instead.
|
|
210
|
+
"""
|
|
211
|
+
try:
|
|
212
|
+
canonical = os.path.realpath(os.path.abspath(path))
|
|
213
|
+
# Only the global registry entry needs this check: workspace-local files
|
|
214
|
+
# live inside the root they describe, so they cannot outlive it this way.
|
|
215
|
+
runtimes_dir = os.path.realpath(os.path.join(
|
|
216
|
+
os.environ.get("TOKENSAFE_HOME") or os.path.expanduser("~/.tokensafe"), "runtimes"
|
|
217
|
+
))
|
|
218
|
+
if os.path.dirname(canonical) != runtimes_dir:
|
|
219
|
+
return True
|
|
220
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
221
|
+
data = json.load(f)
|
|
222
|
+
recorded = (data.get("frontend") or {}).get("workspaceRoot") or (data.get("backend") or {}).get("workspaceRoot")
|
|
223
|
+
if not recorded:
|
|
224
|
+
# Legacy descriptors without a workspaceRoot: judge by the file's
|
|
225
|
+
# own location — the sha256 key cannot be reverse-mapped.
|
|
226
|
+
return True
|
|
227
|
+
recorded_real = os.path.realpath(os.path.abspath(recorded))
|
|
228
|
+
if workspace_dir and recorded_real != os.path.realpath(os.path.abspath(workspace_dir)):
|
|
229
|
+
return False # entry under this key describes another root: stale reuse
|
|
230
|
+
from src.paths import is_transient_dir
|
|
231
|
+
if is_transient_dir(recorded_real) and not os.path.isdir(recorded_real):
|
|
232
|
+
return False
|
|
233
|
+
return True
|
|
234
|
+
except Exception:
|
|
235
|
+
return True
|
|
236
|
+
|
|
172
237
|
@classmethod
|
|
173
|
-
def _check_workspace_runtime_files(cls, workspace_dir: str):
|
|
174
|
-
|
|
238
|
+
def _check_workspace_runtime_files(cls, workspace_dir: str, st: Optional[Dict[str, Any]] = None):
|
|
239
|
+
st = st if st is not None else cls._state_for(workspace_dir)
|
|
240
|
+
lock_paths = [lp for lp in (
|
|
175
241
|
cls.global_runtime_file(workspace_dir),
|
|
176
242
|
os.path.join(workspace_dir, ".tokensafe", "runtime.json"),
|
|
177
243
|
os.path.join(workspace_dir, ".oumv", "runtime.json"),
|
|
178
|
-
]
|
|
244
|
+
) if cls._descriptor_path_is_trusted(lp, workspace_dir)]
|
|
179
245
|
for lp in lock_paths:
|
|
180
246
|
if os.path.isfile(lp):
|
|
181
247
|
try:
|
|
@@ -183,7 +249,7 @@ class OUMVGateway:
|
|
|
183
249
|
data = json.load(f)
|
|
184
250
|
fe_info = data.get("frontend")
|
|
185
251
|
if fe_info and fe_info.get("url"):
|
|
186
|
-
|
|
252
|
+
st["fe"] = {
|
|
187
253
|
"kind": "frontend",
|
|
188
254
|
"name": fe_info.get("name", "tokensafe-ui"),
|
|
189
255
|
"version": fe_info.get("version", "1.0.0"),
|
|
@@ -195,7 +261,7 @@ class OUMVGateway:
|
|
|
195
261
|
}
|
|
196
262
|
be_info = data.get("backend")
|
|
197
263
|
if be_info and be_info.get("url"):
|
|
198
|
-
|
|
264
|
+
st["be"] = {
|
|
199
265
|
"kind": "backend",
|
|
200
266
|
"name": be_info.get("name", "tokensafe-backend"),
|
|
201
267
|
"version": be_info.get("version", "1.0.0"),
|
|
@@ -207,6 +273,7 @@ class OUMVGateway:
|
|
|
207
273
|
}
|
|
208
274
|
except Exception:
|
|
209
275
|
pass
|
|
276
|
+
return st
|
|
210
277
|
|
|
211
278
|
@classmethod
|
|
212
279
|
def _probe_candidates(cls, urls: List[str], kind: str) -> Optional[Dict[str, Any]]:
|
|
@@ -240,11 +307,14 @@ class OUMVGateway:
|
|
|
240
307
|
}).encode("utf-8")
|
|
241
308
|
|
|
242
309
|
headers = {"Content-Type": "application/json", "User-Agent": "TokenSafe-Gateway/1.0"}
|
|
310
|
+
# Session tokens live in per-workspace states; a URL identifies its runtime
|
|
311
|
+
# unambiguously, so scan every root's state for a match.
|
|
243
312
|
token = None
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
313
|
+
for st in cls._workspace_states.values():
|
|
314
|
+
if st.get("fe", {}) and st["fe"].get("url") == endpoint_url:
|
|
315
|
+
token = st["fe"].get("sessionToken")
|
|
316
|
+
elif st.get("be", {}) and st["be"].get("url") == endpoint_url:
|
|
317
|
+
token = st["be"].get("sessionToken")
|
|
248
318
|
|
|
249
319
|
if token:
|
|
250
320
|
headers["X-OUMV-Session-Token"] = token
|
|
@@ -380,7 +450,7 @@ class OUMVGateway:
|
|
|
380
450
|
os.path.join(ws, ".tokensafe", "runtime.json"),
|
|
381
451
|
os.path.join(ws, ".oumv", "runtime.json"),
|
|
382
452
|
):
|
|
383
|
-
if not os.path.isfile(lp):
|
|
453
|
+
if not os.path.isfile(lp) or not cls._descriptor_path_is_trusted(lp, ws):
|
|
384
454
|
continue
|
|
385
455
|
try:
|
|
386
456
|
if (now - os.path.getmtime(lp)) > cls._DESCRIPTOR_MAX_AGE_SEC:
|
|
@@ -407,11 +477,12 @@ class OUMVGateway:
|
|
|
407
477
|
@classmethod
|
|
408
478
|
def status(cls, workspace_dir: Optional[str] = None) -> Dict[str, Any]:
|
|
409
479
|
cls.mark_oumv_used(workspace_dir)
|
|
410
|
-
|
|
480
|
+
ws = workspace_dir or get_active_workspace() or os.getcwd()
|
|
481
|
+
cls.scan(workspace_dir=ws)
|
|
411
482
|
# A descriptor whose port is closed must not be reported as a live runtime.
|
|
412
|
-
dropped = cls._drop_stale_descriptor_endpoints()
|
|
413
|
-
|
|
414
|
-
|
|
483
|
+
dropped = cls._drop_stale_descriptor_endpoints(ws)
|
|
484
|
+
st = cls._state_for(ws)
|
|
485
|
+
fe, be = st["fe"], st["be"]
|
|
415
486
|
|
|
416
487
|
# Out-of-the-box stack detection
|
|
417
488
|
stack_info = {}
|
|
@@ -459,7 +530,13 @@ class OUMVGateway:
|
|
|
459
530
|
|
|
460
531
|
@staticmethod
|
|
461
532
|
def _adapter_lifecycle(stack_info: Dict[str, Any], fe: Optional[Dict[str, Any]], be: Optional[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
|
462
|
-
"""Per-adapter
|
|
533
|
+
"""Per-adapter readiness per the OUMV Adapter Contract (schemas/adapter.json).
|
|
534
|
+
|
|
535
|
+
Every entry carries ONE machine-readable readiness verdict (`status`, mirrored
|
|
536
|
+
by `effective`): active > supported > partial > planned > unsupported. A runtime
|
|
537
|
+
that answers UNSUPPORTED for a detected stack can no longer be reported as a
|
|
538
|
+
`ready` adapter from the catalog at the same time.
|
|
539
|
+
"""
|
|
463
540
|
adapters: List[Dict[str, Any]] = []
|
|
464
541
|
fe_info = stack_info.get("frontend") or {}
|
|
465
542
|
be_info = stack_info.get("backend") or {}
|
|
@@ -475,38 +552,64 @@ class OUMVGateway:
|
|
|
475
552
|
catalog = []
|
|
476
553
|
|
|
477
554
|
def _find_adapter(profile: str, provider: Optional[str]) -> Dict[str, Any]:
|
|
555
|
+
"""Exact catalog match only — never substitute a ready adapter of the same
|
|
556
|
+
profile for a different provider (that is how planned stacks looked ready)."""
|
|
478
557
|
if provider:
|
|
479
558
|
for a in catalog:
|
|
480
559
|
if a.get("id") == f"{profile}/{provider}":
|
|
481
560
|
return a
|
|
482
|
-
for a in catalog:
|
|
483
|
-
if a.get("profile") == profile and a.get("status") == "ready":
|
|
484
|
-
return a
|
|
485
561
|
return {}
|
|
486
562
|
|
|
487
563
|
def _entry(profile: str, connected: Optional[Dict[str, Any]], detected: bool, info: Dict[str, Any]) -> Dict[str, Any]:
|
|
488
564
|
provider = info.get("provider")
|
|
489
565
|
adapter = _find_adapter(profile, provider)
|
|
490
|
-
|
|
566
|
+
catalog_status = adapter.get("status", "planned")
|
|
567
|
+
catalog_ready = catalog_status == "ready"
|
|
568
|
+
exact_match = bool(adapter)
|
|
569
|
+
detection_planned = info.get("status") == "planned" or info.get("oumv_supported") is False
|
|
570
|
+
|
|
491
571
|
if connected:
|
|
492
|
-
|
|
493
|
-
elif
|
|
494
|
-
|
|
495
|
-
|
|
572
|
+
effective = "active"
|
|
573
|
+
elif not detected:
|
|
574
|
+
effective = "unsupported"
|
|
575
|
+
elif detection_planned or not catalog_ready:
|
|
576
|
+
effective = "planned"
|
|
577
|
+
elif not exact_match:
|
|
578
|
+
# A ready adapter exists for the profile but not for this provider.
|
|
579
|
+
effective = "partial"
|
|
580
|
+
else:
|
|
581
|
+
effective = "supported"
|
|
582
|
+
|
|
583
|
+
if effective == "active":
|
|
584
|
+
state, health = "ACTIVE", "healthy"
|
|
585
|
+
detail = f"Live runtime: {connected.get('name', 'unknown')}"
|
|
586
|
+
elif effective in ("supported", "partial"):
|
|
587
|
+
state, health = "HANDSHAKE", "degraded"
|
|
588
|
+
detail = (
|
|
589
|
+
f"Detected statically ({info.get('framework', 'unknown')}); runtime offline — "
|
|
590
|
+
"hybrid static fallback active"
|
|
591
|
+
)
|
|
592
|
+
if effective == "partial":
|
|
593
|
+
detail += f"; no exact adapter for {profile}/{provider} yet"
|
|
594
|
+
elif effective == "planned":
|
|
595
|
+
state, health = "UNSUPPORTED", "unsupported"
|
|
496
596
|
detail = (
|
|
497
|
-
f"{
|
|
597
|
+
f"{f'{profile}/{provider}' if provider else profile} has no implemented OUMV runtime adapter yet. "
|
|
498
598
|
"Do not use tokensafe:oumv for this profile — use repo_map, smart_read_file, and scoped_search instead."
|
|
499
599
|
)
|
|
500
|
-
elif detected:
|
|
501
|
-
state, health, detail = "HANDSHAKE", "degraded", "Detected statically; runtime offline — hybrid static fallback active"
|
|
502
600
|
else:
|
|
503
|
-
state, health
|
|
601
|
+
state, health = "DISCOVER", "unavailable"
|
|
602
|
+
detail = "Not detected in this workspace"
|
|
603
|
+
|
|
604
|
+
caps = adapter.get("capabilities") if effective in ("active", "supported", "partial") else []
|
|
504
605
|
return {
|
|
505
606
|
"profile": profile,
|
|
506
|
-
"adapter": adapter.get("id", f"{profile}/unknown"),
|
|
507
|
-
"status":
|
|
607
|
+
"adapter": adapter.get("id", f"{profile}/{provider or 'unknown'}"),
|
|
608
|
+
"status": effective,
|
|
609
|
+
"effective": effective,
|
|
610
|
+
"catalogStatus": catalog_status,
|
|
508
611
|
"technology": adapter.get("technology"),
|
|
509
|
-
"capabilities":
|
|
612
|
+
"capabilities": caps,
|
|
510
613
|
"lifecycle": {"state": state, "health": {"status": health, "detail": detail}},
|
|
511
614
|
"security": {
|
|
512
615
|
"productionFailClosed": True,
|
|
@@ -882,3 +985,224 @@ class OUMVGateway:
|
|
|
882
985
|
g["edges"] = [e for e in g["edges"] if t in (e["source"] + e["target"]).lower()][:50]
|
|
883
986
|
g["filteredBy"] = target
|
|
884
987
|
return g
|
|
988
|
+
|
|
989
|
+
# 7. Tool: oumv index — repo-wide symbol search (spec §14, optional extension)
|
|
990
|
+
_INDEX_MATCH_CAP = 50
|
|
991
|
+
|
|
992
|
+
@classmethod
|
|
993
|
+
def index(cls, query: str, kinds: Optional[List[str]] = None, limit: int = 25, workspace_dir: Optional[str] = None) -> Dict[str, Any]:
|
|
994
|
+
"""Repo-wide symbol search over the static code graph (spec `oumv/index`).
|
|
995
|
+
|
|
996
|
+
Closes the largest remaining agent token sink: without it, "where is X
|
|
997
|
+
defined / who calls Y" needs raw grep. Ranking: exact name > prefix >
|
|
998
|
+
qualified-suffix > substring; reverse-edge count (who imports/calls this
|
|
999
|
+
symbol) breaks ties. Falls back to the FTS5 content index when the graph
|
|
1000
|
+
holds nothing for the query, and labels that fallback honestly.
|
|
1001
|
+
"""
|
|
1002
|
+
from src.graph_engine import GraphEngine
|
|
1003
|
+
ws = workspace_dir or get_active_workspace() or os.getcwd()
|
|
1004
|
+
q = (query or "").strip()
|
|
1005
|
+
if not q:
|
|
1006
|
+
return {
|
|
1007
|
+
"workspace": ws,
|
|
1008
|
+
"query": query,
|
|
1009
|
+
"error": "VALIDATION_FAILED",
|
|
1010
|
+
"hint": "query is required (a symbol name, Type.member, or substring)",
|
|
1011
|
+
}
|
|
1012
|
+
kind_filter = {k.strip().lower() for k in (kinds or []) if str(k).strip()}
|
|
1013
|
+
|
|
1014
|
+
graph = GraphEngine.get_instance(ws)
|
|
1015
|
+
q_lower = q.lower()
|
|
1016
|
+
scored: List[Tuple[int, int, str, Any]] = [] # (rank, -refs, sym_key, sym)
|
|
1017
|
+
for key, sym in getattr(graph, "symbols", {}).items():
|
|
1018
|
+
name = (sym.name or "").lower()
|
|
1019
|
+
if not name:
|
|
1020
|
+
continue
|
|
1021
|
+
if q_lower == name:
|
|
1022
|
+
rank = 0
|
|
1023
|
+
elif name.startswith(q_lower):
|
|
1024
|
+
rank = 1
|
|
1025
|
+
elif key.lower().endswith("." + q_lower) or key.lower().endswith("::" + q_lower) or name.endswith("." + q_lower):
|
|
1026
|
+
rank = 2
|
|
1027
|
+
elif q_lower in name or q_lower in (sym.signature or "").lower():
|
|
1028
|
+
rank = 3
|
|
1029
|
+
else:
|
|
1030
|
+
continue
|
|
1031
|
+
if kind_filter and sym.kind.lower() not in kind_filter:
|
|
1032
|
+
continue
|
|
1033
|
+
refs = len(getattr(graph, "rev_edges", {}).get(key, ()) or ())
|
|
1034
|
+
scored.append((rank, -refs, key, sym))
|
|
1035
|
+
|
|
1036
|
+
scored.sort(key=lambda item: (item[0], item[1], item[2]))
|
|
1037
|
+
matches = [
|
|
1038
|
+
{
|
|
1039
|
+
"resourceId": f"{sym.kind}:{sym.name}@{sym.file_path}",
|
|
1040
|
+
"name": sym.name,
|
|
1041
|
+
"kind": sym.kind,
|
|
1042
|
+
"file": sym.file_path,
|
|
1043
|
+
"lines": [int(sym.line_start or 0), int(sym.line_end or 0)],
|
|
1044
|
+
"signature": (sym.signature or "").strip(),
|
|
1045
|
+
"refs": -neg_refs,
|
|
1046
|
+
"match": {0: "exact", 1: "prefix", 2: "qualified-suffix", 3: "substring"}[rank],
|
|
1047
|
+
}
|
|
1048
|
+
for rank, neg_refs, _key, sym in scored[:limit]
|
|
1049
|
+
]
|
|
1050
|
+
provenance = "static-graph"
|
|
1051
|
+
if not matches:
|
|
1052
|
+
try:
|
|
1053
|
+
from src.fts_index import CodeFTSIndex
|
|
1054
|
+
fts_rows = CodeFTSIndex(ws).search(q, limit=limit) or []
|
|
1055
|
+
matches = [
|
|
1056
|
+
{
|
|
1057
|
+
"resourceId": f"text:{row.get('file')}:{row.get('line')}",
|
|
1058
|
+
"name": str(row.get("content", ""))[:120],
|
|
1059
|
+
"kind": "text",
|
|
1060
|
+
"file": row.get("file"),
|
|
1061
|
+
"lines": [int(row.get("line") or 0), int(row.get("line") or 0)],
|
|
1062
|
+
"signature": "",
|
|
1063
|
+
"refs": 0,
|
|
1064
|
+
"match": "fts-content",
|
|
1065
|
+
}
|
|
1066
|
+
for row in fts_rows
|
|
1067
|
+
]
|
|
1068
|
+
provenance = "fts-content-index"
|
|
1069
|
+
except Exception:
|
|
1070
|
+
matches = []
|
|
1071
|
+
matches = matches[: cls._INDEX_MATCH_CAP]
|
|
1072
|
+
return {
|
|
1073
|
+
"workspace": ws,
|
|
1074
|
+
"query": q,
|
|
1075
|
+
"matches": matches,
|
|
1076
|
+
"totalMatches": len(scored) if provenance == "static-graph" else len(matches),
|
|
1077
|
+
"truncated": (len(scored) if provenance == "static-graph" else len(matches)) > len(matches),
|
|
1078
|
+
"provenance": provenance,
|
|
1079
|
+
"evidence": {"provenance": "static", "confidence": "confirmed", "sourceAdapter": "tokensafe-graph-engine"},
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
# 8. Tool: oumv preview — dry-run diff before commit (spec `oumv/previewEdit`)
|
|
1083
|
+
@classmethod
|
|
1084
|
+
def preview(cls, path: str, symbol: Optional[str] = None, replacement: Optional[str] = None,
|
|
1085
|
+
expected_version: Optional[str] = None, batch: Optional[List[dict]] = None,
|
|
1086
|
+
runtime: str = "auto", workspace_dir: Optional[str] = None) -> Any:
|
|
1087
|
+
"""Dry-run an edit: returns the would-be result WITHOUT writing anything.
|
|
1088
|
+
|
|
1089
|
+
Delegates to a live runtime implementing `oumv/previewEdit` when one is
|
|
1090
|
+
connected. Without a live runtime, only the honest subset is served
|
|
1091
|
+
offline: a whole-file replacement preview (real unified diff against the
|
|
1092
|
+
current bytes + syntax check). Symbol-level offline preview is refused
|
|
1093
|
+
instead of guessing a diff the runtime never computed.
|
|
1094
|
+
"""
|
|
1095
|
+
ws = workspace_dir or get_active_workspace() or os.getcwd()
|
|
1096
|
+
params: Dict[str, Any] = {
|
|
1097
|
+
"path": path,
|
|
1098
|
+
"filePath": path,
|
|
1099
|
+
"symbol": symbol,
|
|
1100
|
+
"replacement": replacement,
|
|
1101
|
+
"source": replacement,
|
|
1102
|
+
"expectedVersion": expected_version,
|
|
1103
|
+
}
|
|
1104
|
+
if batch:
|
|
1105
|
+
params["edits"] = batch
|
|
1106
|
+
try:
|
|
1107
|
+
url = cls._resolve_client_url(runtime=runtime, target=path, workspace_dir=workspace_dir)
|
|
1108
|
+
res = cls._rpc_call(url, "oumv/previewEdit", params)
|
|
1109
|
+
if isinstance(res, dict):
|
|
1110
|
+
res.setdefault("mode", "LIVE_RUNTIME_PREVIEW")
|
|
1111
|
+
return res
|
|
1112
|
+
except OUMVRpcError as e:
|
|
1113
|
+
if not any(hint in str(e).lower() for hint in _UNSUPPORTED_HINTS):
|
|
1114
|
+
raise # explicit protocol rejection (conflict/syntax/permission) — obey it
|
|
1115
|
+
raise OUMVUnsupportedMethodError(str(e))
|
|
1116
|
+
except RuntimeError as e:
|
|
1117
|
+
if not any(hint in str(e).lower() for hint in _UNSUPPORTED_HINTS):
|
|
1118
|
+
offline = {
|
|
1119
|
+
"mode": "OFFLINE_FULL_FILE_PREVIEW",
|
|
1120
|
+
"path": path,
|
|
1121
|
+
"workspace": ws,
|
|
1122
|
+
"requiresRuntime": True,
|
|
1123
|
+
"hint": (
|
|
1124
|
+
"mutate.preview needs a live OUMV runtime implementing oumv/previewEdit "
|
|
1125
|
+
"(wire 1.6.0+). Only whole-file replacement previews work offline."
|
|
1126
|
+
),
|
|
1127
|
+
}
|
|
1128
|
+
if symbol:
|
|
1129
|
+
offline["error"] = "UNSUPPORTED_OFFLINE"
|
|
1130
|
+
offline["detail"] = "symbol-level preview needs the runtime's AST; nothing was computed or written"
|
|
1131
|
+
return offline
|
|
1132
|
+
if replacement is None:
|
|
1133
|
+
offline["error"] = "VALIDATION_FAILED"
|
|
1134
|
+
offline["detail"] = "offline preview requires 'replacement' (whole-file content)"
|
|
1135
|
+
return offline
|
|
1136
|
+
abs_path = os.path.normpath(os.path.join(ws, path))
|
|
1137
|
+
if not abs_path.startswith(os.path.abspath(ws)):
|
|
1138
|
+
return {"mode": "OFFLINE_FULL_FILE_PREVIEW", "error": "SECURITY_VIOLATION", "detail": f"Path traversal blocked: {path}"}
|
|
1139
|
+
current = ""
|
|
1140
|
+
if os.path.isfile(abs_path):
|
|
1141
|
+
with open(abs_path, "r", encoding="utf-8", errors="replace") as f:
|
|
1142
|
+
current = f.read()
|
|
1143
|
+
import difflib
|
|
1144
|
+
diff_lines = list(difflib.unified_diff(
|
|
1145
|
+
current.splitlines(keepends=True),
|
|
1146
|
+
(replacement or "").splitlines(keepends=True),
|
|
1147
|
+
fromfile=f"a/{path}", tofile=f"b/{path}",
|
|
1148
|
+
))
|
|
1149
|
+
offline["diff"] = "".join(diff_lines)
|
|
1150
|
+
offline["unchanged"] = current == (replacement or "")
|
|
1151
|
+
offline["currentVersion"] = cls._hash_version(abs_path)
|
|
1152
|
+
from src.syntax_guard import check_syntax
|
|
1153
|
+
offline["syntaxCheck"] = check_syntax(abs_path, replacement)
|
|
1154
|
+
return offline
|
|
1155
|
+
raise
|
|
1156
|
+
|
|
1157
|
+
# 9. Tool: oumv build — run the runtime's build/test command (spec §14.3)
|
|
1158
|
+
@classmethod
|
|
1159
|
+
def build(cls, command: Optional[str] = None, target: Optional[str] = None,
|
|
1160
|
+
timeout_ms: Optional[int] = None, runtime: str = "auto", workspace_dir: Optional[str] = None) -> Any:
|
|
1161
|
+
"""Proxies `oumv/build` to a live runtime; no fabricated offline diagnostics.
|
|
1162
|
+
|
|
1163
|
+
§14.3 is an optional extension: a runtime that does not implement it
|
|
1164
|
+
answers -32601, and without a live runtime the honest answer is that the
|
|
1165
|
+
gateway cannot run the application's own build — not a guessed verdict.
|
|
1166
|
+
"""
|
|
1167
|
+
cls.mark_oumv_used(workspace_dir)
|
|
1168
|
+
params: Dict[str, Any] = {}
|
|
1169
|
+
if command:
|
|
1170
|
+
params["command"] = command
|
|
1171
|
+
if target:
|
|
1172
|
+
params["target"] = target
|
|
1173
|
+
if timeout_ms:
|
|
1174
|
+
params["timeoutMs"] = int(timeout_ms)
|
|
1175
|
+
try:
|
|
1176
|
+
url = cls._resolve_client_url(runtime=runtime, target=target, workspace_dir=workspace_dir)
|
|
1177
|
+
res = cls._rpc_call(url, "oumv/build", params)
|
|
1178
|
+
if isinstance(res, dict) and "evidence" not in res:
|
|
1179
|
+
res["evidence"] = {"provenance": "runtime", "confidence": "confirmed", "sourceAdapter": "live-devserver"}
|
|
1180
|
+
return res
|
|
1181
|
+
except OUMVRpcError as e:
|
|
1182
|
+
if not any(hint in str(e).lower() for hint in _UNSUPPORTED_HINTS):
|
|
1183
|
+
raise
|
|
1184
|
+
raise OUMVUnsupportedMethodError(str(e))
|
|
1185
|
+
except RuntimeError as e:
|
|
1186
|
+
# A plain RuntimeError here means no runtime is reachable: the honest
|
|
1187
|
+
# answer is a skip with a reason, never a fabricated verdict.
|
|
1188
|
+
if any(hint in str(e).lower() for hint in _UNSUPPORTED_HINTS):
|
|
1189
|
+
raise
|
|
1190
|
+
return {
|
|
1191
|
+
"status": "skipped",
|
|
1192
|
+
"command": command or "none",
|
|
1193
|
+
"diagnostics": [],
|
|
1194
|
+
"skipReason": (
|
|
1195
|
+
"oumv/build needs a live OUMV runtime implementing §14.3; "
|
|
1196
|
+
"no DevServer is reachable in this workspace"
|
|
1197
|
+
),
|
|
1198
|
+
"requiresRuntime": True,
|
|
1199
|
+
"hint": "start 'tokensafe dev' (or the app's OUMV adapter) and retry; or run the build/test command yourself",
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
@staticmethod
|
|
1203
|
+
def _hash_version(abs_path: str) -> Optional[str]:
|
|
1204
|
+
import hashlib as _hashlib
|
|
1205
|
+
if not os.path.isfile(abs_path):
|
|
1206
|
+
return None
|
|
1207
|
+
with open(abs_path, "rb") as f:
|
|
1208
|
+
return "sha256:" + _hashlib.sha256(f.read()).hexdigest()
|