tokensafe 4.5.5 → 4.6.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.
@@ -10,7 +10,12 @@ Supported query types:
10
10
  - 'regex': regular expression pattern matching.
11
11
  - 'glob': file name and path pattern matching.
12
12
  - 'fuzzy': case-insensitive fuzzy path and symbol search.
13
- - 'git': read-only git queries (status, diff, log, show, branch, rev-parse, ls-files).
13
+ - 'git': read-only git queries (status, diff, log, show, branch, rev-parse,
14
+ ls-files, blame, shortlog, describe, tag) with writing/escaping flags blocked.
15
+
16
+ `path` may point to a directory or to a single file. A missing path, an
17
+ uncompilable regex, and an unknown `file_type` are reported as per-query
18
+ errors instead of silent zero-hit results.
14
19
  """
15
20
 
16
21
  import os
@@ -36,11 +41,15 @@ ALLOWED_GIT_COMMANDS = {
36
41
  HARDENED_GIT_BASE_ARGS = [
37
42
  "--no-optional-locks",
38
43
  "-c", "core.fsmonitor=false",
44
+ "-c", "core.quotePath=false",
39
45
  "-c", "diff.external=",
40
46
  "-c", "gpg.program=false",
41
- "--no-pager"
47
+ "--no-pager",
42
48
  ]
43
49
 
50
+ # Subcommands that support --no-textconv (a per-command option, not a global one)
51
+ _TEXTCONV_SUBCOMMANDS = frozenset({"diff", "log", "show", "blame"})
52
+
44
53
 
45
54
  def _is_git_command_safe(args_str: str) -> Tuple[bool, str, List[str]]:
46
55
  """Checks if git command is strictly read-only and returns tokens."""
@@ -57,8 +66,15 @@ def _is_git_command_safe(args_str: str) -> Tuple[bool, str, List[str]]:
57
66
  if subcmd not in ALLOWED_GIT_COMMANDS:
58
67
  return False, f"Git subcommand '{subcmd}' is not in the read-only allowlist ({', '.join(sorted(ALLOWED_GIT_COMMANDS))}).", []
59
68
 
60
- # Block destructive, config-overriding, or mutating flags
61
- _BLOCKED_GIT_PREFIXES = ("-c", "-C", "--git-dir", "--work-tree", "--exec-path", "--output", "--ext-diff", "--exec")
69
+ # Block destructive, config-overriding, escaping, or helper-executing options.
70
+ # --no-index/--contents/--pathspec-from-file read arbitrary files outside the
71
+ # workspace root the MCP handler confines sub-queries to; --textconv runs
72
+ # repo-configured helpers, so it is blocked and --no-textconv is forced below.
73
+ _BLOCKED_GIT_PREFIXES = (
74
+ "-c", "-C", "--git-dir", "--work-tree", "--exec-path", "--output",
75
+ "--ext-diff", "--exec", "--no-index", "--contents", "--pathspec-from-file",
76
+ "--textconv",
77
+ )
62
78
  _READ_ONLY_BRANCH_TAG_FLAGS = {
63
79
  "-l", "--list", "-a", "--all", "-r", "--remotes", "-v", "-vv", "--verbose",
64
80
  "--show-current", "--contains", "--no-contains", "--merged", "--no-merged",
@@ -80,7 +96,7 @@ def _is_git_command_safe(args_str: str) -> Tuple[bool, str, List[str]]:
80
96
  return True, "", tokens
81
97
 
82
98
 
83
- def _run_git_query(pattern: str, cwd: str, timeout_sec: int = 5) -> Dict[str, Any]:
99
+ def _run_git_query(pattern: str, cwd: str, timeout_sec: int = 5, max_results: int = 50) -> Dict[str, Any]:
84
100
  """Runs a read-only git query."""
85
101
  is_safe, err_msg, tokens = _is_git_command_safe(pattern)
86
102
  if not is_safe:
@@ -90,15 +106,24 @@ def _run_git_query(pattern: str, cwd: str, timeout_sec: int = 5) -> Dict[str, An
90
106
  if not git_bin:
91
107
  return {"error": "git executable not found in PATH", "matches": [], "count": 0}
92
108
 
93
- cmd = [git_bin, *HARDENED_GIT_BASE_ARGS, *tokens]
109
+ # --no-textconv is a per-subcommand option (diff/log/show/blame), so it must
110
+ # follow the subcommand, not sit in the global option block.
111
+ if tokens and tokens[0].lower() in _TEXTCONV_SUBCOMMANDS:
112
+ cmd = [git_bin, *HARDENED_GIT_BASE_ARGS, tokens[0], "--no-textconv", *tokens[1:]]
113
+ else:
114
+ cmd = [git_bin, *HARDENED_GIT_BASE_ARGS, *tokens]
115
+
94
116
  env = os.environ.copy()
95
117
  env["GIT_TERMINAL_PROMPT"] = "0"
96
118
  env["GIT_PAGER"] = "cat"
119
+ # Never let git consume the MCP server's own stdin (rev-parse --parseopt blocks on it).
120
+ stdin_devnull = subprocess.DEVNULL
97
121
 
98
122
  try:
99
123
  proc = subprocess.run(
100
124
  cmd,
101
125
  cwd=cwd,
126
+ stdin=stdin_devnull,
102
127
  stdout=subprocess.PIPE,
103
128
  stderr=subprocess.PIPE,
104
129
  text=True,
@@ -111,7 +136,8 @@ def _run_git_query(pattern: str, cwd: str, timeout_sec: int = 5) -> Dict[str, An
111
136
 
112
137
  raw_out = strip_ansi(proc.stdout or "").strip()
113
138
  lines = [l for l in raw_out.splitlines() if l.strip()]
114
- return {"matches": lines[:50], "count": len(lines), "raw": "\n".join(lines[:50])}
139
+ limited = lines[:max_results]
140
+ return {"matches": limited, "count": len(limited), "raw": "\n".join(limited)}
115
141
  except subprocess.TimeoutExpired:
116
142
  return {"error": f"git query timed out after {timeout_sec}s", "matches": [], "count": 0}
117
143
  except Exception as e:
@@ -133,7 +159,9 @@ def _run_rg_query(
133
159
  if not rg_bin:
134
160
  return None
135
161
 
136
- cmd = [rg_bin, "--no-heading", "--line-number", "--color=never", "--max-count", str(max_results)]
162
+ # --with-filename is mandatory: for a single-file target ripgrep omits the
163
+ # path prefix, so every output line would be unparseable below (silent 0 hits).
164
+ cmd = [rg_bin, "--no-heading", "--with-filename", "--line-number", "--color=never", "--max-count", str(max_results)]
137
165
  if not is_regex:
138
166
  cmd.append("--fixed-strings")
139
167
  if not case_sensitive:
@@ -157,11 +185,16 @@ def _run_rg_query(
157
185
  proc = subprocess.run(
158
186
  cmd,
159
187
  cwd=cwd,
188
+ stdin=subprocess.DEVNULL,
160
189
  stdout=subprocess.PIPE,
161
190
  stderr=subprocess.PIPE,
162
191
  text=True,
163
192
  timeout=5
164
193
  )
194
+ err_text = (proc.stderr or "").strip()
195
+ # rg exits 1 for "no matches" (not an error) and 2 for real failures.
196
+ if proc.returncode not in (0, 1) and err_text:
197
+ raise RuntimeError(f"ripgrep failed: {err_text.splitlines()[0]}")
165
198
  matches = []
166
199
  _rg_line_re = re.compile(r"^(.*):(\d+):(.*)$")
167
200
  for line in proc.stdout.splitlines():
@@ -184,6 +217,49 @@ def _run_rg_query(
184
217
  return None
185
218
 
186
219
 
220
+ def _iter_search_files(search_root: str, cwd: str):
221
+ """Yields (full_path, rel_path) for an explicit file target or a directory tree."""
222
+ if os.path.isfile(search_root):
223
+ yield search_root, os.path.relpath(search_root, cwd)
224
+ return
225
+ for root, dirs, files in os.walk(search_root):
226
+ dirs[:] = [d for d in dirs if d not in IGNORED_DIRS and not d.startswith(".")]
227
+ for f in files:
228
+ full_path = os.path.join(root, f)
229
+ yield full_path, os.path.relpath(full_path, cwd)
230
+
231
+
232
+ # Approximation of ripgrep's --type map for the pure-Python fallback, so the
233
+ # file_type filter is not silently ignored when rg is unavailable.
234
+ FILE_TYPE_EXTENSIONS = {
235
+ "typescript": {".ts", ".tsx", ".mts", ".cts"},
236
+ "ts": {".ts", ".tsx", ".mts", ".cts"},
237
+ "javascript": {".js", ".jsx", ".mjs", ".cjs"},
238
+ "js": {".js", ".jsx", ".mjs", ".cjs"},
239
+ "python": {".py", ".pyi"},
240
+ "py": {".py", ".pyi"},
241
+ "rust": {".rs"},
242
+ "go": {".go"},
243
+ "java": {".java"},
244
+ "ruby": {".rb"},
245
+ "php": {".php"},
246
+ "c": {".c", ".h"},
247
+ "cpp": {".cpp", ".cc", ".cxx", ".hpp", ".hh"},
248
+ "csharp": {".cs"},
249
+ "markdown": {".md", ".markdown"},
250
+ "md": {".md", ".markdown"},
251
+ "json": {".json"},
252
+ "yaml": {".yaml", ".yml"},
253
+ "toml": {".toml"},
254
+ "html": {".html", ".htm"},
255
+ "css": {".css", ".scss", ".sass", ".less"},
256
+ "sql": {".sql"},
257
+ "shell": {".sh", ".bash", ".zsh"},
258
+ "swift": {".swift"},
259
+ "kotlin": {".kt", ".kts"},
260
+ }
261
+
262
+
187
263
  def _run_python_text_search(
188
264
  pattern: str,
189
265
  cwd: str,
@@ -192,59 +268,71 @@ def _run_python_text_search(
192
268
  case_sensitive: bool = False,
193
269
  scope: str = "all",
194
270
  glob_filter: Optional[str] = None,
271
+ file_type: Optional[str] = None,
195
272
  max_results: int = 25
196
273
  ) -> List[Dict[str, Any]]:
197
- """Pure Python search fallback."""
274
+ """Pure Python search fallback. Raises ValueError for an unusable regex or file_type."""
198
275
  search_root = os.path.normpath(os.path.join(cwd, path_filter)) if path_filter else cwd
199
276
  if not os.path.exists(search_root):
200
277
  return []
201
278
 
279
+ type_exts = None
280
+ if file_type:
281
+ type_exts = FILE_TYPE_EXTENSIONS.get(str(file_type).lower().lstrip("."))
282
+ if type_exts is None:
283
+ raise ValueError(
284
+ f"unsupported file_type '{file_type}' (known: {', '.join(sorted(FILE_TYPE_EXTENSIONS))})"
285
+ )
286
+
202
287
  regex = None
203
288
  if is_regex:
204
289
  flags = 0 if case_sensitive else re.IGNORECASE
205
290
  try:
206
291
  regex = re.compile(pattern, flags)
207
- except re.error:
208
- regex = None
292
+ except re.error as e:
293
+ # Never degrade to a literal search: that silently returns bogus hits.
294
+ raise ValueError(f"invalid regular expression: {e}")
209
295
 
210
296
  matches = []
211
297
  target_lower = pattern if case_sensitive else pattern.lower()
298
+ explicit_file = os.path.isfile(search_root)
212
299
 
213
- for root, dirs, files in os.walk(search_root):
214
- dirs[:] = [d for d in dirs if d not in IGNORED_DIRS and not d.startswith(".")]
215
- for f in files:
216
- ext = os.path.splitext(f)[1].lower()
300
+ for full_path, rel_p in _iter_search_files(search_root, cwd):
301
+ # An explicitly named file is searched as-is: extension, scope, and glob
302
+ # filters only make sense when walking a directory tree.
303
+ if not explicit_file:
304
+ ext = os.path.splitext(full_path)[1].lower()
217
305
  if ext in IGNORED_EXTENSIONS:
218
306
  continue
219
307
  if scope == "code" and ext not in CODE_EXTENSIONS:
220
308
  continue
221
- full_path = os.path.join(root, f)
222
- rel_p = os.path.relpath(full_path, cwd)
223
- if glob_filter and not (fnmatch.fnmatch(f, glob_filter) or fnmatch.fnmatch(rel_p, glob_filter)):
309
+ if type_exts is not None and ext not in type_exts:
224
310
  continue
225
-
226
- try:
227
- with open(full_path, "r", encoding="utf-8", errors="replace") as fp:
228
- for line_idx, line in enumerate(fp):
229
- hit = False
230
- if regex:
231
- hit = bool(regex.search(line))
232
- elif case_sensitive:
233
- hit = pattern in line
234
- else:
235
- hit = target_lower in line.lower()
236
-
237
- if hit:
238
- matches.append({
239
- "file": rel_p,
240
- "line": line_idx + 1,
241
- "content": line.strip()[:180]
242
- })
243
- if len(matches) >= max_results:
244
- return matches
245
- except Exception:
311
+ if glob_filter and not (fnmatch.fnmatch(os.path.basename(full_path), glob_filter) or fnmatch.fnmatch(rel_p, glob_filter)):
246
312
  continue
247
313
 
314
+ try:
315
+ with open(full_path, "r", encoding="utf-8", errors="replace") as fp:
316
+ for line_idx, line in enumerate(fp):
317
+ hit = False
318
+ if regex:
319
+ hit = bool(regex.search(line))
320
+ elif case_sensitive:
321
+ hit = pattern in line
322
+ else:
323
+ hit = target_lower in line.lower()
324
+
325
+ if hit:
326
+ matches.append({
327
+ "file": rel_p,
328
+ "line": line_idx + 1,
329
+ "content": line.strip()[:180]
330
+ })
331
+ if len(matches) >= max_results:
332
+ return matches
333
+ except Exception:
334
+ continue
335
+
248
336
  return matches
249
337
 
250
338
 
@@ -254,15 +342,18 @@ def _run_glob_search(pattern: str, cwd: str, path_filter: Optional[str] = None,
254
342
  if not os.path.exists(search_root):
255
343
  return []
256
344
 
345
+ if os.path.isfile(search_root):
346
+ rel_p = os.path.relpath(search_root, cwd)
347
+ if fnmatch.fnmatch(rel_p, pattern) or fnmatch.fnmatch(os.path.basename(search_root), pattern):
348
+ return [rel_p]
349
+ return []
350
+
257
351
  results = []
258
- for root, dirs, files in os.walk(search_root):
259
- dirs[:] = [d for d in dirs if d not in IGNORED_DIRS and not d.startswith(".")]
260
- for f in files:
261
- rel_p = os.path.relpath(os.path.join(root, f), cwd)
262
- if fnmatch.fnmatch(rel_p, pattern) or fnmatch.fnmatch(f, pattern):
263
- results.append(rel_p)
264
- if len(results) >= max_results:
265
- return results
352
+ for full_path, rel_p in _iter_search_files(search_root, cwd):
353
+ if fnmatch.fnmatch(rel_p, pattern) or fnmatch.fnmatch(os.path.basename(full_path), pattern):
354
+ results.append(rel_p)
355
+ if len(results) >= max_results:
356
+ return results
266
357
  return results
267
358
 
268
359
 
@@ -274,17 +365,14 @@ def _run_fuzzy_search(pattern: str, cwd: str, path_filter: Optional[str] = None,
274
365
 
275
366
  pat_lower = pattern.lower().replace(" ", "")
276
367
  results = []
277
- for root, dirs, files in os.walk(search_root):
278
- dirs[:] = [d for d in dirs if d not in IGNORED_DIRS and not d.startswith(".")]
279
- for f in files:
280
- rel_p = os.path.relpath(os.path.join(root, f), cwd)
281
- name_lower = rel_p.lower()
282
- # Subsequence match
283
- it = iter(name_lower)
284
- if all(ch in it for ch in pat_lower):
285
- results.append(rel_p)
286
- if len(results) >= max_results:
287
- return results
368
+ for _, rel_p in _iter_search_files(search_root, cwd):
369
+ name_lower = rel_p.lower()
370
+ # Subsequence match
371
+ it = iter(name_lower)
372
+ if all(ch in it for ch in pat_lower):
373
+ results.append(rel_p)
374
+ if len(results) >= max_results:
375
+ return results
288
376
  return results
289
377
 
290
378
 
@@ -298,20 +386,39 @@ def _execute_single_query(query_dict: Dict[str, Any], cwd: str) -> Dict[str, Any
298
386
  output_mode = str(query_dict.get("output_mode") or "content").lower()
299
387
  file_type = query_dict.get("file_type")
300
388
  glob_filter = query_dict.get("glob")
389
+ scope = str(query_dict.get("scope") or "all").lower()
301
390
 
302
391
  if not pattern and q_type != "git":
303
392
  return {"type": q_type, "pattern": pattern, "error": "Empty pattern.", "matches": [], "count": 0}
304
393
 
394
+ # A path that does not exist must be an explicit error: an empty result list
395
+ # is indistinguishable from a genuine zero-hit search.
396
+ if path_filter:
397
+ search_root = os.path.normpath(os.path.join(cwd, str(path_filter)))
398
+ if not os.path.exists(search_root):
399
+ return {
400
+ "type": q_type,
401
+ "pattern": pattern,
402
+ "error": f"path does not exist: {path_filter}",
403
+ "matches": [],
404
+ "count": 0,
405
+ }
406
+
305
407
  if q_type == "git":
306
- res = _run_git_query(pattern, cwd)
408
+ git_cwd = os.path.normpath(os.path.join(cwd, str(path_filter))) if path_filter else cwd
409
+ res = _run_git_query(pattern, git_cwd, max_results=max_res)
307
410
  return {"type": "git", "pattern": pattern, **res}
308
411
 
309
412
  if q_type == "glob":
310
413
  matched_paths = _run_glob_search(pattern, cwd, path_filter=path_filter, max_results=max_res)
414
+ if output_mode == "count":
415
+ return {"type": "glob", "pattern": pattern, "count": len(matched_paths)}
311
416
  return {"type": "glob", "pattern": pattern, "matches": matched_paths, "count": len(matched_paths)}
312
417
 
313
418
  if q_type == "fuzzy":
314
419
  matched_paths = _run_fuzzy_search(pattern, cwd, path_filter=path_filter, max_results=max_res)
420
+ if output_mode == "count":
421
+ return {"type": "fuzzy", "pattern": pattern, "count": len(matched_paths)}
315
422
  return {"type": "fuzzy", "pattern": pattern, "matches": matched_paths, "count": len(matched_paths)}
316
423
 
317
424
  is_regex = (q_type == "regex")
@@ -327,16 +434,20 @@ def _execute_single_query(query_dict: Dict[str, Any], cwd: str) -> Dict[str, Any
327
434
  max_results=max_res
328
435
  )
329
436
 
330
- matches = rg_matches if rg_matches is not None else _run_python_text_search(
331
- pattern=pattern,
332
- cwd=cwd,
333
- path_filter=path_filter,
334
- is_regex=is_regex,
335
- case_sensitive=case_sensitive,
336
- scope="all",
337
- glob_filter=glob_filter,
338
- max_results=max_res
339
- )
437
+ try:
438
+ matches = rg_matches if rg_matches is not None else _run_python_text_search(
439
+ pattern=pattern,
440
+ cwd=cwd,
441
+ path_filter=path_filter,
442
+ is_regex=is_regex,
443
+ case_sensitive=case_sensitive,
444
+ scope=scope,
445
+ glob_filter=glob_filter,
446
+ file_type=file_type,
447
+ max_results=max_res
448
+ )
449
+ except ValueError as e:
450
+ return {"type": q_type, "pattern": pattern, "error": str(e), "matches": [], "count": 0}
340
451
 
341
452
  if output_mode == "files_with_matches":
342
453
  unique_files = list(dict.fromkeys(m["file"] for m in matches if isinstance(m, dict) and "file" in m))
@@ -404,11 +515,13 @@ def execute_batch_search(
404
515
  if q_type == "git":
405
516
  raw_git = res.get("raw")
406
517
  if raw_git:
407
- md_lines.append("```text\n" + raw_git[:1200] + "\n```")
518
+ md_lines.append("```text\n" + raw_git + "\n```")
408
519
  elif not matches:
409
520
  md_lines.append("*(clean / no output)*")
410
521
  elif isinstance(matches, list):
411
- for m in matches[:15]:
522
+ # Honor the caller's max_results instead of a fixed 15-item cap;
523
+ # the Zero-Spill Guard folds oversized payloads at the MCP boundary.
524
+ for m in matches:
412
525
  if isinstance(m, dict):
413
526
  f_name = m.get("file", "")
414
527
  l_num = m.get("line", "")
@@ -416,12 +529,11 @@ def execute_batch_search(
416
529
  md_lines.append(f"- `{f_name}:{l_num}`: {content}")
417
530
  elif isinstance(m, str):
418
531
  md_lines.append(f"- `{m}`")
419
- if len(matches) > 15:
420
- md_lines.append(f"- *(+{len(matches) - 15} more matches)*")
421
532
 
422
533
  summary_md = "\n".join(md_lines)
534
+ errored = [r for r in results if isinstance(r, dict) and r.get("error")]
423
535
  return {
424
- "success": True,
536
+ "success": not (errored and len(errored) == len(results)),
425
537
  "query_count": len(queries),
426
538
  "results": results,
427
539
  "summary_md": summary_md
@@ -0,0 +1,212 @@
1
+ """
2
+ Unified Cross-Stack Intelligence Graph (OUMV spec §11).
3
+
4
+ Merges three independent evidence sources into one resource graph:
5
+ 1. Static analysis (frontend API call sites -> backend endpoints, from the AST graph engine).
6
+ 2. Live frontend runtime surface (mounted components / actions, provenance "runtime").
7
+ 3. Live backend runtime surface (endpoints actually served, provenance "runtime").
8
+
9
+ Every node and edge carries EvidenceMetadata (spec §6.2). Missing runtime evidence
10
+ is reported explicitly instead of being inferred.
11
+ """
12
+
13
+ import time
14
+ from typing import Any, Callable, Dict, List, Optional
15
+
16
+
17
+ def _static_evidence() -> Dict[str, str]:
18
+ return {"provenance": "static", "sourceAdapter": "tokensafe-graph-engine", "confidence": "probable"}
19
+
20
+
21
+ def _runtime_evidence(source: str) -> Dict[str, str]:
22
+ return {"provenance": "runtime", "sourceAdapter": source, "confidence": "confirmed"}
23
+
24
+
25
+ def build_unified_graph(
26
+ workspace_dir: Optional[str] = None,
27
+ fe: Optional[Dict[str, Any]] = None,
28
+ be: Optional[Dict[str, Any]] = None,
29
+ rpc_call: Optional[Callable[..., Any]] = None,
30
+ ) -> Dict[str, Any]:
31
+ """Builds the unified cross-stack graph for a workspace.
32
+
33
+ Args:
34
+ workspace_dir: workspace root (defaults to the active workspace).
35
+ fe / be: live runtime descriptors from OUMVGateway.get_endpoints().
36
+ rpc_call: callable(url, method, params) used to observe live surfaces.
37
+ """
38
+ from src.graph_engine import GraphEngine
39
+ from src.paths import get_active_workspace
40
+
41
+ ws = workspace_dir or get_active_workspace()
42
+ static = GraphEngine.get_instance(ws)
43
+
44
+ nodes: Dict[str, Dict[str, Any]] = {}
45
+ edges: List[Dict[str, Any]] = []
46
+
47
+ def _endpoint_node_id(method: Optional[str], route: str) -> str:
48
+ return f"backend.endpoint:{method or 'ANY'}:{route}"
49
+
50
+ # 1. Static backend endpoints
51
+ for rel_path, eps in getattr(static, "file_endpoints", {}).items():
52
+ for route, sym, method in eps:
53
+ node_id = _endpoint_node_id(method, route)
54
+ nodes.setdefault(node_id, {
55
+ "id": node_id,
56
+ "type": "backend.endpoint",
57
+ "route": route,
58
+ "method": method,
59
+ "file": rel_path,
60
+ "symbol": sym,
61
+ "evidence": _static_evidence(),
62
+ })
63
+
64
+ # 2. Static frontend action (API call) sites
65
+ for rel_path, calls in getattr(static, "file_api_calls", {}).items():
66
+ for route, sym, method in calls:
67
+ node_id = f"frontend.action:{method or 'ANY'}:{route}:{rel_path}:{sym or ''}"
68
+ nodes.setdefault(node_id, {
69
+ "id": node_id,
70
+ "type": "frontend.action",
71
+ "route": route,
72
+ "method": method,
73
+ "file": rel_path,
74
+ "symbol": sym,
75
+ "evidence": _static_evidence(),
76
+ })
77
+
78
+ # 3. Static cross-stack edges (frontend call -> backend endpoint)
79
+ for link in getattr(static, "api_links", []):
80
+ source = link["source"]
81
+ target = link["target"]
82
+ src_id = f"frontend.action:{source.get('method') or 'ANY'}:{source.get('route')}:{source.get('file')}:{source.get('symbol') or ''}"
83
+ dst_id = _endpoint_node_id(target.get("method"), target.get("route") or "")
84
+ edges.append({
85
+ "source": src_id,
86
+ "target": dst_id,
87
+ "relation": "calls",
88
+ "evidence": _static_evidence(),
89
+ })
90
+
91
+ runtime_fe_ok = False
92
+ runtime_be_ok = False
93
+
94
+ # 4. Live backend surface: confirms endpoints actually served
95
+ if be and rpc_call:
96
+ try:
97
+ surface = rpc_call(be["url"], "oumv/observe", {"level": "L1"})
98
+ if isinstance(surface, dict):
99
+ runtime_be_ok = True
100
+ for ep in surface.get("endpoints", []) or []:
101
+ node_id = _endpoint_node_id(ep.get("method"), ep.get("path") or ep.get("route") or "")
102
+ if not node_id.endswith(":"):
103
+ if node_id in nodes:
104
+ nodes[node_id]["runtimeConfirmed"] = True
105
+ else:
106
+ nodes[node_id] = {
107
+ "id": node_id,
108
+ "type": "backend.endpoint",
109
+ "route": ep.get("path") or ep.get("route"),
110
+ "method": ep.get("method"),
111
+ "evidence": _runtime_evidence("live-backend-runtime"),
112
+ }
113
+ except Exception:
114
+ pass
115
+
116
+ # 5. Live frontend surface: mounted components / actions
117
+ if fe and rpc_call:
118
+ try:
119
+ surface = rpc_call(fe["url"], "oumv/observe", {"level": "L1"})
120
+ if isinstance(surface, dict):
121
+ runtime_fe_ok = True
122
+ for comp in surface.get("components", []) or surface.get("elements", []) or []:
123
+ comp_id = comp.get("id") or comp.get("agentId") or comp.get("componentId")
124
+ if not comp_id:
125
+ continue
126
+ node_id = f"frontend.component:{comp_id}"
127
+ nodes.setdefault(node_id, {
128
+ "id": node_id,
129
+ "type": "frontend.component",
130
+ "evidence": _runtime_evidence("live-frontend-runtime"),
131
+ })
132
+ except Exception:
133
+ pass
134
+
135
+ provenance_summary = {
136
+ "staticNodes": sum(1 for n in nodes.values() if n["evidence"]["provenance"] == "static"),
137
+ "runtimeNodes": sum(1 for n in nodes.values() if n["evidence"]["provenance"] == "runtime"),
138
+ "runtimeConfirmedEndpoints": sum(1 for n in nodes.values() if n.get("runtimeConfirmed")),
139
+ "edges": len(edges),
140
+ }
141
+
142
+ return {
143
+ "mode": "UNIFIED_CROSS_STACK_GRAPH",
144
+ "workspace": ws,
145
+ "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
146
+ "nodes": list(nodes.values()),
147
+ "edges": edges,
148
+ "provenanceSummary": provenance_summary,
149
+ "missingEvidence": [
150
+ "Frontend call origins are statically inferred; runtime fetch tracing is not yet recorded by the frontend bridge.",
151
+ ],
152
+ "runtimes": {
153
+ "frontend": "live" if runtime_fe_ok else ("unreachable" if fe else "offline"),
154
+ "backend": "live" if runtime_be_ok else ("unreachable" if be else "offline"),
155
+ },
156
+ }
157
+
158
+
159
+ def who_depends_on(target: str, graph: Dict[str, Any]) -> Dict[str, Any]:
160
+ """Answers §11.4: which frontend resources call a given backend endpoint."""
161
+ t = (target or "").strip()
162
+ result: Dict[str, Any] = {
163
+ "query": "who_depends_on",
164
+ "target": t,
165
+ "frontendCallers": [],
166
+ "runtimeConfirmed": False,
167
+ "evidence": _static_evidence(),
168
+ }
169
+ if not t:
170
+ result["error"] = "target is required (e.g. '/api/orders' or 'POST /api/orders')"
171
+ return result
172
+
173
+ t_lower = t.lower()
174
+ for edge in graph.get("edges", []):
175
+ target_route = (edge.get("target") or "").lower()
176
+ if t_lower in target_route:
177
+ result["frontendCallers"].append({
178
+ "source": edge["source"],
179
+ "relation": "calls",
180
+ "evidence": edge.get("evidence"),
181
+ })
182
+
183
+ nodes = {n["id"]: n for n in graph.get("nodes", [])}
184
+ for node_id, node in nodes.items():
185
+ if node.get("type") == "backend.endpoint" and t_lower in f"{node.get('method') or ''} {node.get('route') or ''}".lower():
186
+ if node.get("runtimeConfirmed"):
187
+ result["runtimeConfirmed"] = True
188
+
189
+ result["frontendCallers"] = result["frontendCallers"][:30]
190
+ return result
191
+
192
+
193
+ def impact_from_graph(target: str, graph: Dict[str, Any]) -> Dict[str, Any]:
194
+ """Graph-based impact view: affected cross-stack callers with suggested verification."""
195
+ callers = who_depends_on(target, graph)
196
+ verification_steps = [
197
+ f"oumv_verify(target='POST {target}') — in-memory endpoint check",
198
+ ]
199
+ for caller in callers.get("frontendCallers", [])[:3]:
200
+ parts = caller["source"].split(":")
201
+ route_hint = parts[2] if len(parts) > 2 else caller["source"]
202
+ verification_steps.append(
203
+ f"oumv_understand(query='causality', target='{route_hint}') — confirm the calling code still matches"
204
+ )
205
+ return {
206
+ "query": "impact",
207
+ "target": target,
208
+ "frontendCallers": callers.get("frontendCallers", []),
209
+ "runtimeConfirmed": callers.get("runtimeConfirmed", False),
210
+ "suggestedVerification": verification_steps,
211
+ "missingEvidence": graph.get("missingEvidence", []),
212
+ }