tokensafe 4.7.12 → 4.7.13

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/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.12"
47
+ "version": "4.7.13"
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': ['pattern'],
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=action in ("status", "observe", "understand", "verify", "graph", "index", "preview", "build"),
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
 
@@ -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
- "Use tokensafe:repo_map, tokensafe:smart_read_file, and tokensafe:scoped_search for this backend; "
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 observe(cls, level: str = "L0", target: Optional[str] = None, runtime: str = "auto", workspace_dir: Optional[str] = None) -> Any:
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", workspace_dir: Optional[str] = None) -> Any:
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, replacement)
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(replacement)
1013
+ f.write(new_content)
901
1014
 
902
- new_version = "sha256:" + hashlib.sha256(replacement.encode("utf-8")).hexdigest()
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
package/src/retrofit.py CHANGED
@@ -51,8 +51,19 @@ def _detect_package_json_entry(pkg_json_path: str, rel_dir: str = ".") -> Tuple[
51
51
 
52
52
  has_vite = "vite" in deps
53
53
  if "next" in deps:
54
- # Next has no Vite dev server; the zero-footprint plugin cannot mount there.
55
- fe_info.update({"framework": "nextjs", "provider": "react", "adapter": "tokensafe-ui/oumv/react", "version": deps.get("next"), "oumv_supported": False, "status": "needs-vite"})
54
+ # The App Router is served by the Node runtime as a Route Handler: there is
55
+ # no Vite dev server to patch, and the DOM bridge for client components is
56
+ # separate work. The server profile is what this adapter certifies.
57
+ fe_info.update({
58
+ "framework": "nextjs",
59
+ "provider": "node",
60
+ "profile": "backend",
61
+ "adapter": "tokensafe-backend-node/next",
62
+ "version": deps.get("next"),
63
+ "oumv_supported": True,
64
+ "status": "ready",
65
+ "note": "App Router Route Handler (server profile); client-component DOM bridge is not part of this adapter",
66
+ })
56
67
  elif "react" in deps:
57
68
  fe_info.update({"framework": "react", "provider": "react", "adapter": "tokensafe-ui/oumv/react", "version": deps.get("react"), "oumv_supported": has_vite, "status": "ready" if has_vite else "needs-vite"})
58
69
  elif "vue" in deps:
@@ -77,18 +88,48 @@ def _detect_package_json_entry(pkg_json_path: str, rel_dir: str = ".") -> Tuple[
77
88
  node_fw = "hono"
78
89
  elif "koa" in deps:
79
90
  node_fw = "koa"
91
+ elif "elysia" in deps:
92
+ node_fw = "elysia"
93
+
94
+ # Bun-only services (queue workers, cron jobs) declare no HTTP framework at
95
+ # all. They used to vanish from `packages` even though their manifest was
96
+ # listed in `detected_files`, so a monorepo looked fully covered when 4 of
97
+ # its 6 packages had no OUMV adapter.
98
+ pkg_dir = os.path.dirname(pkg_json_path)
99
+ bun_marker = (
100
+ any(key in deps for key in ("@types/bun", "bun-types", "elysia"))
101
+ or os.path.isfile(os.path.join(pkg_dir, "bun.lockb"))
102
+ or os.path.isfile(os.path.join(pkg_dir, "bun.lock"))
103
+ )
104
+ if bun_marker:
105
+ managers.append("bun")
80
106
 
81
107
  if node_fw:
108
+ supported_fw = node_fw in ("express", "fastify")
82
109
  be_out = {
83
110
  "framework": node_fw,
84
- "provider": "node",
85
- "adapter": "tokensafe-backend/node",
86
- "language": "node",
111
+ "provider": "bun" if node_fw == "elysia" else "node",
112
+ "adapter": None if node_fw == "elysia" else "tokensafe-backend/node",
113
+ "language": "bun" if node_fw == "elysia" else "node",
87
114
  "root": rel_dir,
88
115
  # Express/Fastify ship a certified adapter (npm tokensafe-backend-node);
89
- # Nest/Hono/Koa do not yet.
90
- "oumv_supported": node_fw in ("express", "fastify"),
91
- "status": "ready" if node_fw in ("express", "fastify") else "planned",
116
+ # Elysia/Nest/Hono/Koa do not yet.
117
+ "oumv_supported": supported_fw,
118
+ "status": "ready" if supported_fw else "planned",
119
+ }
120
+ elif bun_marker and not fe_out:
121
+ # Bun runtime without a web framework: a worker/queue service, not a
122
+ # backend. A frontend package that merely uses Bun as its package
123
+ # manager is not a worker, so `fe_out` wins.
124
+ be_out = {
125
+ "framework": "bun",
126
+ "provider": "bun",
127
+ "adapter": None,
128
+ "language": "bun",
129
+ "root": rel_dir,
130
+ "role": "worker",
131
+ "oumv_supported": False,
132
+ "status": "planned",
92
133
  }
93
134
 
94
135
  if isinstance(pkg_data.get("workspaces"), (list, dict)):
@@ -156,7 +197,10 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
156
197
  pkg_json_path = os.path.join(target_dir, "package.json")
157
198
  if os.path.isfile(pkg_json_path):
158
199
  _add_detected(os.path.relpath(pkg_json_path, workspace_dir))
159
- fe_info, be_info, _ = _detect_package_json_entry(pkg_json_path, rel_dir=rel)
200
+ fe_info, be_info, pkg_managers = _detect_package_json_entry(pkg_json_path, rel_dir=rel)
201
+ for manager in pkg_managers:
202
+ if manager not in stack["package_managers"]:
203
+ stack["package_managers"].append(manager)
160
204
  if fe_info:
161
205
  if not stack["frontend"]:
162
206
  stack["frontend"] = fe_info
@@ -171,16 +215,33 @@ def detect_project_stack(workspace_dir: str) -> Dict[str, Any]:
171
215
  "status": fe_info.get("status", "ready"),
172
216
  })
173
217
  if be_info:
174
- if not stack["backend"]:
218
+ role = be_info.get("role") or "backend"
219
+ if role == "backend" and not stack["backend"]:
175
220
  stack["backend"] = be_info
176
- _add_package({
177
- "role": "backend",
221
+ entry = {
222
+ "role": role,
178
223
  "path": rel,
179
224
  "framework": be_info["framework"],
180
225
  "provider": be_info["provider"],
181
226
  "adapter": be_info["adapter"],
182
227
  "oumvSupported": bool(be_info.get("oumv_supported", False)),
183
228
  "status": be_info.get("status", "planned"),
229
+ }
230
+ if not entry["oumvSupported"]:
231
+ entry["reason"] = f"no OUMV adapter for {be_info['framework']} yet"
232
+ _add_package(entry)
233
+ if not fe_info and not be_info:
234
+ # Every manifest that was detected must also be accounted for: a
235
+ # package missing from `packages` reads as "not there", not "unsupported".
236
+ _add_package({
237
+ "role": "package",
238
+ "path": rel,
239
+ "framework": "node",
240
+ "provider": "node",
241
+ "adapter": None,
242
+ "oumvSupported": False,
243
+ "status": "unsupported",
244
+ "reason": "manifest present, but no supported frontend/backend framework was detected",
184
245
  })
185
246
 
186
247
  # Go Backend detection
@@ -618,6 +679,30 @@ def get_adapters_catalog() -> List[Dict[str, Any]]:
618
679
  {"name": "verify.behavior", "constraints": {"readOnly": True, "developmentOnly": True}},
619
680
  ],
620
681
  },
682
+ {
683
+ "id": "backend/next",
684
+ "name": "Next.js App Router Adapter (Route Handler, server profile)",
685
+ "profile": "backend",
686
+ "profiles": ["backend"],
687
+ "repo": "tokensafe-backend/node",
688
+ "mode": "hybrid",
689
+ "status": "ready",
690
+ "description": "App Router Route Handler (app/api/tokensafe/route.ts) serving JSON-RPC + SSE over the Node runtime; route surface read from app/**/route.{ts,tsx,js,jsx}, verify dispatched through an adopter-supplied Web handler; the client-component DOM bridge is separate work (certified Level 3)",
691
+ "technology": {
692
+ "language": "typescript",
693
+ "framework": "next (app router)",
694
+ "package": {"manager": "npm", "name": "tokensafe-backend-node", "install": "npm install --save-dev tokensafe-backend-node"},
695
+ },
696
+ "capabilities": [
697
+ {"name": "observe.pulse", "constraints": {"readOnly": True, "developmentOnly": True}},
698
+ {"name": "observe.surface", "constraints": {"readOnly": True, "developmentOnly": True, "note": "app/**/route.* scan"}},
699
+ {"name": "observe.source", "constraints": {"readOnly": True, "developmentOnly": True}},
700
+ {"name": "observe.traces", "constraints": {"readOnly": True, "developmentOnly": True, "note": "requires verifyFetch wiring"}},
701
+ {"name": "understand.impact", "constraints": {"readOnly": True, "developmentOnly": True}},
702
+ {"name": "mutate.source", "constraints": {"readOnly": False, "developmentOnly": True, "requiresPermission": "permissions.mutate != false"}},
703
+ {"name": "verify.behavior", "constraints": {"readOnly": True, "developmentOnly": True, "note": "requires verifyFetch wiring"}},
704
+ ],
705
+ },
621
706
  {
622
707
  "id": "backend/aspnetcore",
623
708
  "name": "ASP.NET Core Adapter (minimal APIs, MVC controllers, EF Core)",