tokensafe 4.7.12 → 4.7.14
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 +7 -3
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +2 -0
- package/src/__init__.py +1 -1
- package/src/auto_inject.py +133 -4
- package/src/batch_editor.py +40 -9
- package/src/graph_engine.py +298 -27
- package/src/mcp_server.py +102 -13
- package/src/oumv_gateway.py +149 -6
- package/src/retrofit.py +103 -13
- package/src/scoped_search.py +126 -0
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
package/src/mcp_server.py
CHANGED
|
@@ -44,7 +44,7 @@ from src.session_context import current_root, current_session_id
|
|
|
44
44
|
|
|
45
45
|
SERVER_INFO = {
|
|
46
46
|
"name": "tokensafe-mcp",
|
|
47
|
-
"version": "4.7.
|
|
47
|
+
"version": "4.7.14"
|
|
48
48
|
}
|
|
49
49
|
|
|
50
50
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -352,6 +352,21 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
|
|
|
352
352
|
'type': 'string'},
|
|
353
353
|
'query': { 'description': 'Text, identifier, or symbol name',
|
|
354
354
|
'type': 'string'},
|
|
355
|
+
'queries': { 'description': 'Batch mode (same contract as batch_search): '
|
|
356
|
+
'up to 20 {query|pattern, type, path, glob, '
|
|
357
|
+
'max_results} items in ONE call',
|
|
358
|
+
'items': { 'properties': { 'case_sensitive': {'type': 'boolean'},
|
|
359
|
+
'glob': {'type': 'string'},
|
|
360
|
+
'max_results': {'type': 'integer'},
|
|
361
|
+
'path': {'type': 'string'},
|
|
362
|
+
'pattern': {'type': 'string'},
|
|
363
|
+
'query': {'type': 'string'},
|
|
364
|
+
'type': {'enum': ['text', 'regex', 'glob', 'fuzzy', 'git'],
|
|
365
|
+
'type': 'string'},
|
|
366
|
+
'use_regex': {'type': 'boolean'}},
|
|
367
|
+
'type': 'object'},
|
|
368
|
+
'maxItems': 20,
|
|
369
|
+
'type': 'array'},
|
|
355
370
|
'scope': { 'description': "Filter: 'code', 'config', 'all', extension "
|
|
356
371
|
"('go', '*.py'), or subfolder "
|
|
357
372
|
"('internal/promo') (default 'all')",
|
|
@@ -359,7 +374,6 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
|
|
|
359
374
|
'use_regex': { 'description': "Omit = auto-detect ('|', \\d → regex); "
|
|
360
375
|
'false = literal; true = regex',
|
|
361
376
|
'type': 'boolean'}},
|
|
362
|
-
'required': ['query'],
|
|
363
377
|
'type': 'object'},
|
|
364
378
|
'name': 'scoped_search'},
|
|
365
379
|
{ 'annotations': {'readOnlyHint': True},
|
|
@@ -697,8 +711,14 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
|
|
|
697
711
|
'or '
|
|
698
712
|
'read-only '
|
|
699
713
|
'git '
|
|
700
|
-
'command'
|
|
714
|
+
'command '
|
|
715
|
+
'(alias: '
|
|
716
|
+
'query)',
|
|
701
717
|
'type': 'string'},
|
|
718
|
+
'query': { 'description': 'Alias '
|
|
719
|
+
'for '
|
|
720
|
+
'pattern',
|
|
721
|
+
'type': 'string'},
|
|
702
722
|
'type': { 'description': 'Query '
|
|
703
723
|
'type: '
|
|
704
724
|
'text, '
|
|
@@ -713,7 +733,7 @@ FULL_TOOLS = [ { 'annotations': {'readOnlyHint': True},
|
|
|
713
733
|
'fuzzy',
|
|
714
734
|
'git'],
|
|
715
735
|
'type': 'string'}},
|
|
716
|
-
'required': [
|
|
736
|
+
'required': [],
|
|
717
737
|
'type': 'object'},
|
|
718
738
|
'maxItems': 20,
|
|
719
739
|
'type': 'array'}},
|
|
@@ -758,7 +778,7 @@ TOOLS = [{'name': 'smart_read_file',
|
|
|
758
778
|
'anyOf': [{'required': ['path']}, {'required': ['endpoint']}, {'required': ['package_name']}]}},
|
|
759
779
|
{'name': 'scoped_search',
|
|
760
780
|
'annotations': {'readOnlyHint': True},
|
|
761
|
-
'description': 'Search replacing grep/find: query+scope, or queries=[{pattern,type,path,glob}] batch (max 20).',
|
|
781
|
+
'description': 'Search replacing grep/find: query+scope, or queries=[{query|pattern,type,path,glob}] batch (max 20).',
|
|
762
782
|
'inputSchema': {'type': 'object',
|
|
763
783
|
'properties': {'query': {'type': 'string'},
|
|
764
784
|
'mode': {'type': 'string',
|
|
@@ -822,7 +842,8 @@ TOOLS = [{'name': 'smart_read_file',
|
|
|
822
842
|
{'name': 'oumv',
|
|
823
843
|
'annotations': {'readOnlyHint': False},
|
|
824
844
|
'description': "OUMV runtime: 'status'|'observe' L0-L4|'understand'|'verify'|'mutate' (OCC edit)|'graph'|'index' "
|
|
825
|
-
"(repo-wide symbol search: query, kinds?, limit?)|'preview' (dry-run diff, no write)
|
|
845
|
+
"(repo-wide symbol search: query, kinds?, limit?)|'preview' (dry-run diff, no write)|'build' "
|
|
846
|
+
"(run the runtime's build/test command, §14.3)|'cancel' (cooperative, by requestId).",
|
|
826
847
|
'inputSchema': {'type': 'object',
|
|
827
848
|
'properties': {'action': {'type': 'string',
|
|
828
849
|
'enum': ['status',
|
|
@@ -833,14 +854,19 @@ TOOLS = [{'name': 'smart_read_file',
|
|
|
833
854
|
'graph',
|
|
834
855
|
'index',
|
|
835
856
|
'preview',
|
|
836
|
-
'build'
|
|
857
|
+
'build',
|
|
858
|
+
'cancel']},
|
|
837
859
|
'level': {'type': 'string'},
|
|
838
860
|
'query': {'type': 'string'},
|
|
839
861
|
'target': {'type': 'string'},
|
|
840
|
-
'path': {'type': 'string'
|
|
862
|
+
'path': {'type': 'string',
|
|
863
|
+
'description': 'File to observe (becomes the target, L1 answers for '
|
|
864
|
+
'that file) or the target repo root for status'},
|
|
841
865
|
'symbol': {'type': 'string'},
|
|
842
866
|
'replacement': {'type': 'string'},
|
|
843
|
-
'expectedVersion': {'type': 'string'
|
|
867
|
+
'expectedVersion': {'type': 'string',
|
|
868
|
+
'description': 'OCC token from observe file.version; '
|
|
869
|
+
'offline mutate enforces it'},
|
|
844
870
|
'kinds': {'type': 'array',
|
|
845
871
|
'items': {'type': 'string'},
|
|
846
872
|
'description': 'index: symbol-kind filter (function, class, ...)'},
|
|
@@ -852,9 +878,11 @@ TOOLS = [{'name': 'smart_read_file',
|
|
|
852
878
|
'description': 'preview/build: per-call budget (§3/§14.3)'},
|
|
853
879
|
'verify_action': {'type': 'string'},
|
|
854
880
|
'payload': {'type': 'object'},
|
|
881
|
+
'requestId': {'type': 'string',
|
|
882
|
+
'description': 'cancel: the requestId echoed by the target call'},
|
|
855
883
|
'workspace_dir': {'type': 'string',
|
|
856
884
|
'description': 'Target repo root; for '
|
|
857
|
-
'status/observe/understand/verify/graph/index/preview '
|
|
885
|
+
'status/observe/understand/verify/graph/index/preview/build/cancel '
|
|
858
886
|
'also accepted as path'}}}},
|
|
859
887
|
{'name': 'run_helper',
|
|
860
888
|
'annotations': {'readOnlyHint': False},
|
|
@@ -1147,6 +1175,19 @@ def _oumv_workspace_arg(args: dict, allow_path: bool = False) -> Tuple[Optional[
|
|
|
1147
1175
|
|
|
1148
1176
|
|
|
1149
1177
|
MCP_TOOL_TIMEOUT = float(os.environ.get("TOKENSAFE_MCP_TIMEOUT", "8.0"))
|
|
1178
|
+
# A cold AST crawl of a large monorepo takes ~15 s and is cached afterwards. Cutting
|
|
1179
|
+
# it at the transport default failed the first repo_map/observe/read of every session
|
|
1180
|
+
# (2026-11-28 paidz: repo_map, smart_read_file and oumv all died at 8 s while one
|
|
1181
|
+
# crawl held the graph lock).
|
|
1182
|
+
MCP_GRAPH_TIMEOUT = float(os.environ.get("TOKENSAFE_MCP_GRAPH_TIMEOUT", "30.0"))
|
|
1183
|
+
_GRAPH_TOOLS = {
|
|
1184
|
+
"repo_map",
|
|
1185
|
+
"get_architecture_graph",
|
|
1186
|
+
"oumv",
|
|
1187
|
+
"smart_read_file",
|
|
1188
|
+
"smart_bundle",
|
|
1189
|
+
"slice_external_type",
|
|
1190
|
+
}
|
|
1150
1191
|
|
|
1151
1192
|
|
|
1152
1193
|
def _fallback_error(tool_name: str, reason: str) -> dict:
|
|
@@ -1926,6 +1967,7 @@ _OUMV_ACTIONS = {
|
|
|
1926
1967
|
"index": "oumv_index",
|
|
1927
1968
|
"preview": "oumv_preview",
|
|
1928
1969
|
"build": "oumv_build",
|
|
1970
|
+
"cancel": "oumv_cancel",
|
|
1929
1971
|
}
|
|
1930
1972
|
_HELPER_ACTIONS = {
|
|
1931
1973
|
"sanitize": "sanitize_command",
|
|
@@ -2015,14 +2057,38 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
2015
2057
|
# inspecting a second repo (workspace_dir, or `path` for the read actions)
|
|
2016
2058
|
# used to get the bound workspace's stack back with no error — a silently
|
|
2017
2059
|
# wrong answer. Resolve the explicit root here and fail closed on a bad one.
|
|
2060
|
+
#
|
|
2061
|
+
# `path` is overloaded: for observe/understand a *file* path is the thing to
|
|
2062
|
+
# observe, while a directory is a workspace root. Treating the file as a root
|
|
2063
|
+
# (dirname) produced target:null and a whole-repo dump.
|
|
2064
|
+
file_target: Optional[str] = None
|
|
2065
|
+
raw_path = str(args.get("path") or "").strip()
|
|
2066
|
+
if action in ("observe", "understand") and raw_path:
|
|
2067
|
+
probe_base = str(args.get("workspace_dir") or "").strip() or _oumv_default_workspace() or os.getcwd()
|
|
2068
|
+
probe = raw_path if os.path.isabs(raw_path) else os.path.join(probe_base, raw_path)
|
|
2069
|
+
if os.path.isfile(probe):
|
|
2070
|
+
file_target = os.path.abspath(probe)
|
|
2018
2071
|
ws, ws_err = _oumv_workspace_arg(
|
|
2019
2072
|
args,
|
|
2020
|
-
allow_path=
|
|
2073
|
+
allow_path=(
|
|
2074
|
+
not file_target
|
|
2075
|
+
and action in ("status", "observe", "understand", "verify", "graph", "index", "preview", "build", "cancel")
|
|
2076
|
+
),
|
|
2021
2077
|
)
|
|
2022
2078
|
if ws_err:
|
|
2023
2079
|
return _fallback_error("oumv", ws_err)
|
|
2080
|
+
if file_target:
|
|
2081
|
+
# NB: no local `from ... import GraphEngine` here — a function-local import
|
|
2082
|
+
# shadows the module-level name for the WHOLE of _dispatch_tool_call, and
|
|
2083
|
+
# the smart_read_file handler below then raises UnboundLocalError.
|
|
2084
|
+
try:
|
|
2085
|
+
ws = GraphEngine.find_project_root(file_target)
|
|
2086
|
+
except Exception:
|
|
2087
|
+
ws = ws or os.path.dirname(file_target)
|
|
2024
2088
|
if ws:
|
|
2025
2089
|
args = dict(args, workspace_dir=ws)
|
|
2090
|
+
if file_target:
|
|
2091
|
+
args = dict(args, target=args.get("target") or file_target)
|
|
2026
2092
|
mapped = _OUMV_ACTIONS[action]
|
|
2027
2093
|
if action == "verify":
|
|
2028
2094
|
args = dict(args, action=args.get("verify_action") or "invoke")
|
|
@@ -3318,10 +3384,11 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
3318
3384
|
lvl = str(args.get("level") or "L0").strip()
|
|
3319
3385
|
tgt = str(args.get("target") or "").strip() or None
|
|
3320
3386
|
rt = str(args.get("runtime") or "auto").strip()
|
|
3387
|
+
raw_path = str(args.get("path") or "").strip() or None
|
|
3321
3388
|
ws, ws_err = _oumv_workspace_arg(args)
|
|
3322
3389
|
if ws_err:
|
|
3323
3390
|
return _fallback_error("oumv_observe", ws_err)
|
|
3324
|
-
res = OUMVGateway.observe(level=lvl, target=tgt, runtime=rt, workspace_dir=ws)
|
|
3391
|
+
res = OUMVGateway.observe(level=lvl, target=tgt, runtime=rt, workspace_dir=ws, path=raw_path)
|
|
3325
3392
|
return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
|
|
3326
3393
|
except Exception as e:
|
|
3327
3394
|
return _fallback_error("oumv_observe", f"failed to observe OUMV runtime: {e}")
|
|
@@ -3332,10 +3399,11 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
3332
3399
|
qry = str(args.get("query") or "causality").strip()
|
|
3333
3400
|
tgt = str(args.get("target") or "").strip() or None
|
|
3334
3401
|
rt = str(args.get("runtime") or "auto").strip()
|
|
3402
|
+
raw_path = str(args.get("path") or "").strip() or None
|
|
3335
3403
|
ws, ws_err = _oumv_workspace_arg(args)
|
|
3336
3404
|
if ws_err:
|
|
3337
3405
|
return _fallback_error("oumv_understand", ws_err)
|
|
3338
|
-
res = OUMVGateway.understand(query=qry, target=tgt, runtime=rt, workspace_dir=ws)
|
|
3406
|
+
res = OUMVGateway.understand(query=qry, target=tgt, runtime=rt, workspace_dir=ws, path=raw_path)
|
|
3339
3407
|
return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
|
|
3340
3408
|
except Exception as e:
|
|
3341
3409
|
return _fallback_error("oumv_understand", f"failed to query OUMV understanding: {e}")
|
|
@@ -3436,6 +3504,20 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
3436
3504
|
except Exception as e:
|
|
3437
3505
|
return _fallback_error("oumv_build", f"failed to run OUMV build: {e}")
|
|
3438
3506
|
|
|
3507
|
+
elif name == "oumv_cancel":
|
|
3508
|
+
try:
|
|
3509
|
+
from src.oumv_gateway import OUMVGateway
|
|
3510
|
+
rid = str(args.get("requestId") or "").strip() or None
|
|
3511
|
+
tgt = str(args.get("target") or "").strip() or None
|
|
3512
|
+
rt = str(args.get("runtime") or "auto").strip()
|
|
3513
|
+
ws, ws_err = _oumv_workspace_arg(args)
|
|
3514
|
+
if ws_err:
|
|
3515
|
+
return _fallback_error("oumv_cancel", ws_err)
|
|
3516
|
+
res = OUMVGateway.cancel(request_id=rid, target=tgt, runtime=rt, workspace_dir=ws)
|
|
3517
|
+
return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
|
|
3518
|
+
except Exception as e:
|
|
3519
|
+
return _fallback_error("oumv_cancel", f"failed to cancel OUMV request: {e}")
|
|
3520
|
+
|
|
3439
3521
|
elif name == "apply_edits":
|
|
3440
3522
|
try:
|
|
3441
3523
|
from src.batch_editor import execute_batch_edits
|
|
@@ -3651,6 +3733,9 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
3651
3733
|
if not isinstance(q_copy, dict):
|
|
3652
3734
|
safe_queries.append(q_copy)
|
|
3653
3735
|
continue
|
|
3736
|
+
# `query` is the scoped_search spelling; batch items use `pattern`.
|
|
3737
|
+
if not q_copy.get("pattern") and q_copy.get("query"):
|
|
3738
|
+
q_copy["pattern"] = q_copy.pop("query")
|
|
3654
3739
|
if is_quota_exceeded:
|
|
3655
3740
|
q_copy["max_results"] = min(_safe_int(q_copy.get("max_results"), 3, lo=1, hi=100), 3)
|
|
3656
3741
|
safe_queries.append(q_copy)
|
|
@@ -3921,6 +4006,10 @@ def _tool_timeout(tool_name: str, tool_args: dict) -> float:
|
|
|
3921
4006
|
declared = 30 if has_verify else 0
|
|
3922
4007
|
if declared > 0:
|
|
3923
4008
|
return min(max(MCP_TOOL_TIMEOUT, declared + 5.0), 180.0)
|
|
4009
|
+
if tool_name in _GRAPH_TOOLS:
|
|
4010
|
+
# Graph-backed calls may pay a one-time cold crawl; it is cached on disk, so
|
|
4011
|
+
# the next call is milliseconds. TOKENSAFE_MCP_GRAPH_TIMEOUT tunes the ceiling.
|
|
4012
|
+
return max(MCP_TOOL_TIMEOUT, MCP_GRAPH_TIMEOUT)
|
|
3924
4013
|
return MCP_TOOL_TIMEOUT
|
|
3925
4014
|
|
|
3926
4015
|
|
package/src/oumv_gateway.py
CHANGED
|
@@ -526,6 +526,14 @@ class OUMVGateway:
|
|
|
526
526
|
}
|
|
527
527
|
for d in dropped
|
|
528
528
|
]
|
|
529
|
+
# A cold AST crawl costs ~15 s on a large monorepo. Start it now, in the
|
|
530
|
+
# background: the first repo_map/observe/mutate call then finds it warm
|
|
531
|
+
# instead of spending the whole tool budget waiting for it.
|
|
532
|
+
try:
|
|
533
|
+
from src.graph_engine import GraphEngine
|
|
534
|
+
GraphEngine.warm_async(ws)
|
|
535
|
+
except Exception:
|
|
536
|
+
pass
|
|
529
537
|
return result
|
|
530
538
|
|
|
531
539
|
@staticmethod
|
|
@@ -639,7 +647,11 @@ class OUMVGateway:
|
|
|
639
647
|
"supportedProfiles": supported,
|
|
640
648
|
"guidance": (
|
|
641
649
|
f"OUMV runtime adapter for {be.get('framework', 'Node.js')} is not available yet (planned). "
|
|
642
|
-
"
|
|
650
|
+
"Static L1 still answers for one file: "
|
|
651
|
+
"tokensafe:oumv(action='observe', level='L1', path='<file>') returns its symbols, "
|
|
652
|
+
"file.version (the OCC token) and mutation how-to. "
|
|
653
|
+
"For source edits use tokensafe:apply_edits, or tokensafe:oumv(action='mutate') offline "
|
|
654
|
+
"with that expectedVersion (OCC + syntax guard + backup); "
|
|
643
655
|
+ ("keep using tokensafe:oumv(runtime='frontend') for UI." if supported else "use standard tests for verification.")
|
|
644
656
|
),
|
|
645
657
|
}
|
|
@@ -649,8 +661,33 @@ class OUMVGateway:
|
|
|
649
661
|
|
|
650
662
|
# 2. Tool: oumv_observe
|
|
651
663
|
@classmethod
|
|
652
|
-
def
|
|
664
|
+
def _observe_target(cls, target: Optional[str], path: Optional[str], workspace_dir: Optional[str]) -> Optional[str]:
|
|
665
|
+
"""`path` is a file to observe, not a second spelling of `workspace_dir`.
|
|
666
|
+
|
|
667
|
+
The 2026-11-28 paidz session passed path=<file> and got target:null plus a
|
|
668
|
+
33 KB whole-repo L1 dump: the file path was consumed as a workspace root.
|
|
669
|
+
"""
|
|
670
|
+
t = (target or "").strip()
|
|
671
|
+
if t:
|
|
672
|
+
return t
|
|
673
|
+
raw = (path or "").strip()
|
|
674
|
+
if not raw:
|
|
675
|
+
return None
|
|
676
|
+
ws = workspace_dir or get_active_workspace() or os.getcwd()
|
|
677
|
+
candidates = [raw] if os.path.isabs(raw) else [os.path.join(ws, raw), raw]
|
|
678
|
+
for cand in candidates:
|
|
679
|
+
if os.path.isfile(cand):
|
|
680
|
+
try:
|
|
681
|
+
return os.path.relpath(os.path.abspath(cand), os.path.abspath(ws)).replace(os.sep, "/")
|
|
682
|
+
except ValueError:
|
|
683
|
+
return os.path.basename(cand)
|
|
684
|
+
return None
|
|
685
|
+
|
|
686
|
+
@classmethod
|
|
687
|
+
def observe(cls, level: str = "L0", target: Optional[str] = None, runtime: str = "auto",
|
|
688
|
+
workspace_dir: Optional[str] = None, path: Optional[str] = None) -> Any:
|
|
653
689
|
cls.mark_oumv_used(workspace_dir)
|
|
690
|
+
target = cls._observe_target(target, path, workspace_dir)
|
|
654
691
|
fe, be = cls.get_endpoints(workspace_dir=workspace_dir)
|
|
655
692
|
if runtime == "backend" and not be:
|
|
656
693
|
notice = cls._unsupported_backend_notice(workspace_dir, runtime)
|
|
@@ -705,8 +742,10 @@ class OUMVGateway:
|
|
|
705
742
|
|
|
706
743
|
# 3. Tool: oumv_understand
|
|
707
744
|
@classmethod
|
|
708
|
-
def understand(cls, query: str = "causality", target: Optional[str] = None, runtime: str = "auto",
|
|
745
|
+
def understand(cls, query: str = "causality", target: Optional[str] = None, runtime: str = "auto",
|
|
746
|
+
workspace_dir: Optional[str] = None, path: Optional[str] = None) -> Any:
|
|
709
747
|
cls.mark_oumv_used(workspace_dir)
|
|
748
|
+
target = cls._observe_target(target, path, workspace_dir)
|
|
710
749
|
fe, be = cls.get_endpoints(workspace_dir=workspace_dir)
|
|
711
750
|
if runtime == "backend" and not be:
|
|
712
751
|
notice = cls._unsupported_backend_notice(workspace_dir, runtime)
|
|
@@ -820,6 +859,56 @@ class OUMVGateway:
|
|
|
820
859
|
})
|
|
821
860
|
return {"edges": edges[:30], "count": len(edges), "evidence": evidence}
|
|
822
861
|
|
|
862
|
+
@staticmethod
|
|
863
|
+
def _file_symbols(ws: str, rel_path: str) -> List[Any]:
|
|
864
|
+
"""Symbols declared in one file, parsed without crawling the repository."""
|
|
865
|
+
try:
|
|
866
|
+
from src.graph_engine import CodeGraph
|
|
867
|
+
full = os.path.join(ws, rel_path)
|
|
868
|
+
if not os.path.isfile(full):
|
|
869
|
+
return []
|
|
870
|
+
graph = CodeGraph(ws, use_disk_cache=False)
|
|
871
|
+
graph._index_file(full, rel_path)
|
|
872
|
+
except Exception:
|
|
873
|
+
return []
|
|
874
|
+
return [graph.symbols[k] for k in graph.file_symbols.get(rel_path, []) if k in graph.symbols]
|
|
875
|
+
|
|
876
|
+
@classmethod
|
|
877
|
+
def _resolve_symbol_range(cls, ws: str, rel_path: str, symbol: str) -> Optional[tuple]:
|
|
878
|
+
"""Line range of a declaration: exact name, then case-insensitive, then suffix."""
|
|
879
|
+
syms = cls._file_symbols(ws, rel_path)
|
|
880
|
+
if not syms:
|
|
881
|
+
return None
|
|
882
|
+
wanted = (symbol or "").strip()
|
|
883
|
+
short = wanted.split("::")[-1].split(".")[-1]
|
|
884
|
+
matches = [s for s in syms if s.name in (wanted, short)]
|
|
885
|
+
if not matches:
|
|
886
|
+
matches = [s for s in syms if s.name.lower() == short.lower()]
|
|
887
|
+
if not matches:
|
|
888
|
+
matches = [s for s in syms if s.name.lower().endswith(short.lower())]
|
|
889
|
+
if not matches:
|
|
890
|
+
return None
|
|
891
|
+
# A method outranks a same-named local; among equals the tightest range wins.
|
|
892
|
+
matches.sort(key=lambda s: (0 if s.kind in ("function", "method") else 1, s.line_end - s.line_start))
|
|
893
|
+
best = matches[0]
|
|
894
|
+
if best.line_start < 1 or best.line_end < best.line_start:
|
|
895
|
+
return None
|
|
896
|
+
return best.line_start, best.line_end
|
|
897
|
+
|
|
898
|
+
@classmethod
|
|
899
|
+
def _file_symbol_names(cls, ws: str, rel_path: str) -> List[str]:
|
|
900
|
+
return [s.name for s in cls._file_symbols(ws, rel_path)]
|
|
901
|
+
|
|
902
|
+
@staticmethod
|
|
903
|
+
def _splice_range(content: str, start_line: int, end_line: int, replacement: str) -> str:
|
|
904
|
+
"""Replaces lines [start_line, end_line] (1-based, inclusive) in `content`."""
|
|
905
|
+
lines = content.splitlines(keepends=True)
|
|
906
|
+
newline = "\r\n" if "\r\n" in content[:4096] else "\n"
|
|
907
|
+
rep = replacement
|
|
908
|
+
if not rep.endswith(("\n", "\r")):
|
|
909
|
+
rep += newline
|
|
910
|
+
return "".join(lines[:start_line - 1]) + rep + "".join(lines[end_line:])
|
|
911
|
+
|
|
823
912
|
# 4. Tool: oumv_mutate
|
|
824
913
|
@classmethod
|
|
825
914
|
def mutate(cls, path: str, symbol: Optional[str] = None, replacement: Optional[str] = None, expected_version: Optional[str] = None, runtime: str = "auto", workspace_dir: Optional[str] = None) -> Any:
|
|
@@ -864,6 +953,7 @@ class OUMVGateway:
|
|
|
864
953
|
raise RuntimeError(f"[OUMV SECURITY_VIOLATION: -32003] Path traversal blocked: {path}")
|
|
865
954
|
|
|
866
955
|
import hashlib
|
|
956
|
+
content = b""
|
|
867
957
|
current_version = None
|
|
868
958
|
if os.path.isfile(abs_path):
|
|
869
959
|
with open(abs_path, "rb") as f:
|
|
@@ -873,9 +963,32 @@ class OUMVGateway:
|
|
|
873
963
|
if expected_version and current_version and expected_version != current_version:
|
|
874
964
|
raise RuntimeError(f"[OUMV CONFLICT: -32001] OCC version mismatch: expected {expected_version}, current is {current_version}")
|
|
875
965
|
|
|
966
|
+
# A symbol-scoped edit replaces that declaration only. Writing the
|
|
967
|
+
# snippet as the whole file — which this path used to do — silently
|
|
968
|
+
# truncated every other symbol in the target.
|
|
969
|
+
new_content = replacement
|
|
970
|
+
symbol_range = None
|
|
971
|
+
if symbol and os.path.isfile(abs_path):
|
|
972
|
+
rel_path = os.path.relpath(abs_path, os.path.abspath(ws)).replace("\\", "/")
|
|
973
|
+
symbol_range = cls._resolve_symbol_range(ws, rel_path, symbol)
|
|
974
|
+
if not symbol_range:
|
|
975
|
+
known = cls._file_symbol_names(ws, rel_path)
|
|
976
|
+
raise RuntimeError(
|
|
977
|
+
f"[OUMV SYMBOL_NOT_FOUND] '{symbol}' is not declared in {path}. "
|
|
978
|
+
f"Known symbols: {', '.join(known[:8]) or 'none'}. "
|
|
979
|
+
f"For a non-declaration range use apply_edits(start_line/end_line) instead."
|
|
980
|
+
)
|
|
981
|
+
start_line, end_line = symbol_range
|
|
982
|
+
new_content = cls._splice_range(
|
|
983
|
+
content.decode("utf-8", errors="replace"),
|
|
984
|
+
start_line,
|
|
985
|
+
end_line,
|
|
986
|
+
replacement,
|
|
987
|
+
)
|
|
988
|
+
|
|
876
989
|
# Syntax pre-flight: never persist syntactically broken code (OUMV spec §8 Mutation Policy)
|
|
877
990
|
from src.syntax_guard import check_syntax
|
|
878
|
-
syntax_check = check_syntax(abs_path,
|
|
991
|
+
syntax_check = check_syntax(abs_path, new_content)
|
|
879
992
|
if syntax_check.get("status") == "failed":
|
|
880
993
|
raise RuntimeError(
|
|
881
994
|
f"[OUMV SYNTAX_ERROR: -32002] Edit rejected by syntax guard "
|
|
@@ -897,9 +1010,9 @@ class OUMVGateway:
|
|
|
897
1010
|
|
|
898
1011
|
os.makedirs(os.path.dirname(abs_path), exist_ok=True)
|
|
899
1012
|
with open(abs_path, "w", encoding="utf-8") as f:
|
|
900
|
-
f.write(
|
|
1013
|
+
f.write(new_content)
|
|
901
1014
|
|
|
902
|
-
new_version = "sha256:" + hashlib.sha256(
|
|
1015
|
+
new_version = "sha256:" + hashlib.sha256(new_content.encode("utf-8")).hexdigest()
|
|
903
1016
|
result = {
|
|
904
1017
|
"success": True,
|
|
905
1018
|
"path": path,
|
|
@@ -909,6 +1022,8 @@ class OUMVGateway:
|
|
|
909
1022
|
"syntaxCheck": syntax_check,
|
|
910
1023
|
"message": "Surgical edit applied directly to workspace file (dev-server offline)",
|
|
911
1024
|
}
|
|
1025
|
+
if symbol_range:
|
|
1026
|
+
result["symbolRange"] = {"startLine": symbol_range[0], "endLine": symbol_range[1]}
|
|
912
1027
|
if backup_path:
|
|
913
1028
|
result["backupPath"] = backup_path
|
|
914
1029
|
result["rollbackHint"] = f"Previous content backed up at {backup_path}"
|
|
@@ -1199,6 +1314,34 @@ class OUMVGateway:
|
|
|
1199
1314
|
"hint": "start 'tokensafe dev' (or the app's OUMV adapter) and retry; or run the build/test command yourself",
|
|
1200
1315
|
}
|
|
1201
1316
|
|
|
1317
|
+
# 10. Tool: oumv cancel — cooperative cancellation by requestId (spec §3)
|
|
1318
|
+
@classmethod
|
|
1319
|
+
def cancel(cls, request_id: Optional[str] = None, target: Optional[str] = None,
|
|
1320
|
+
runtime: str = "auto", workspace_dir: Optional[str] = None) -> Any:
|
|
1321
|
+
"""Proxies `oumv/cancel`.
|
|
1322
|
+
|
|
1323
|
+
Cancellation is cooperative and best-effort: the runtime answers
|
|
1324
|
+
`{"cancelled": bool}` — a request that already finished is not an error.
|
|
1325
|
+
There is no offline fallback, because a cancellation no runtime received
|
|
1326
|
+
is not a cancellation.
|
|
1327
|
+
"""
|
|
1328
|
+
cls.mark_oumv_used(workspace_dir)
|
|
1329
|
+
request_id = (request_id or "").strip()
|
|
1330
|
+
target = (target or "").strip()
|
|
1331
|
+
if not request_id and not target:
|
|
1332
|
+
raise ValueError("cancel needs requestId or target='last'")
|
|
1333
|
+
params: Dict[str, Any] = {"requestId": request_id} if request_id else {"target": target}
|
|
1334
|
+
url = cls._resolve_client_url(runtime=runtime, workspace_dir=workspace_dir)
|
|
1335
|
+
try:
|
|
1336
|
+
res = cls._rpc_call(url, "oumv/cancel", params)
|
|
1337
|
+
except OUMVRpcError as e:
|
|
1338
|
+
if not any(hint in str(e).lower() for hint in _UNSUPPORTED_HINTS):
|
|
1339
|
+
raise
|
|
1340
|
+
raise OUMVUnsupportedMethodError(str(e))
|
|
1341
|
+
if isinstance(res, dict) and "evidence" not in res:
|
|
1342
|
+
res["evidence"] = {"provenance": "runtime", "confidence": "confirmed", "sourceAdapter": "live-devserver"}
|
|
1343
|
+
return res
|
|
1344
|
+
|
|
1202
1345
|
@staticmethod
|
|
1203
1346
|
def _hash_version(abs_path: str) -> Optional[str]:
|
|
1204
1347
|
import hashlib as _hashlib
|